From a8f99a9a0bf4862d5233c3a3b2a2c12b4424beb1 Mon Sep 17 00:00:00 2001 From: Becky Reamy Date: Mon, 30 Sep 2019 13:21:58 -0400 Subject: [PATCH 01/26] KPMP-1332: Modify gitignore --- .gitignore | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.gitignore b/.gitignore index 533bc1bd..b4b293ca 100755 --- a/.gitignore +++ b/.gitignore @@ -14,3 +14,5 @@ out .idea .settings .classpath +**/credentials.json +tokens From 508a6db107d21e02a4f4a3e60147d2e18369f73f Mon Sep 17 00:00:00 2001 From: Becky Reamy Date: Mon, 30 Sep 2019 14:13:00 -0400 Subject: [PATCH 02/26] KPMP-1332: Getting pieces in place to write out metadata.json file --- .../java/org/kpmp/RegenerateZipFiles.java | 5 +- .../kpmp/externalProcess/CommandBuilder.java | 4 +- .../kpmp/googleDrive/GoogleDriveService.java | 92 +++++++++---------- .../org/kpmp/packages/PackageFileHandler.java | 22 +++++ .../org/kpmp/packages/PackageService.java | 5 +- .../externalProcess/CommandBuilderTest.java | 12 +-- .../kpmp/packages/PackageFileHandlerTest.java | 83 ++++++++++++++++- 7 files changed, 161 insertions(+), 62 deletions(-) diff --git a/src/main/java/org/kpmp/RegenerateZipFiles.java b/src/main/java/org/kpmp/RegenerateZipFiles.java index d15f2420..cddbd373 100755 --- a/src/main/java/org/kpmp/RegenerateZipFiles.java +++ b/src/main/java/org/kpmp/RegenerateZipFiles.java @@ -59,7 +59,9 @@ public void run(String... args) throws Exception { try { File existingZipFile = new File(zipFileName); existingZipFile.delete(); - String[] zipCommand = commandBuilder.buildZipCommand(packageId, packageMetadata); + String[] zipCommand = commandBuilder.buildZipCommand(packageId); + // TODO: Write out metadata.json file + boolean success = processExecutor.executeProcess(zipCommand); if (success) { LocalDateTime start = LocalDateTime.ofInstant(startRezipTime.toInstant(), @@ -76,6 +78,7 @@ public void run(String... args) throws Exception { } } } + // TODO: Delete metadata.json file if exists } } diff --git a/src/main/java/org/kpmp/externalProcess/CommandBuilder.java b/src/main/java/org/kpmp/externalProcess/CommandBuilder.java index dbed32a3..6aab0531 100644 --- a/src/main/java/org/kpmp/externalProcess/CommandBuilder.java +++ b/src/main/java/org/kpmp/externalProcess/CommandBuilder.java @@ -18,7 +18,7 @@ public CommandBuilder(FilePathHelper filePathHelper) { this.filePathHelper = filePathHelper; } - public String[] buildZipCommand(String packageId, String metadataJson) { + public String[] buildZipCommand(String packageId) { List commandArgs = new ArrayList<>(); commandArgs.add("java"); commandArgs.add("-jar"); @@ -29,10 +29,10 @@ public String[] buildZipCommand(String packageId, String metadataJson) { for (String fileName : fileNames) { commandArgs.add("--zip.fileNames=" + packagePath + File.separator + fileName); } + commandArgs.add("--zip.fileNames=" + packagePath + File.separator + "metadata.json"); String zipFileName = filePathHelper.getZipFileName(packageId); commandArgs.add("--zip.zipFilePath=" + zipFileName); - commandArgs.add("--zip.additionalFileData=metadata.json|" + metadataJson); return commandArgs.toArray(new String[0]); } diff --git a/src/main/java/org/kpmp/googleDrive/GoogleDriveService.java b/src/main/java/org/kpmp/googleDrive/GoogleDriveService.java index 2801d2f8..ae845ff0 100644 --- a/src/main/java/org/kpmp/googleDrive/GoogleDriveService.java +++ b/src/main/java/org/kpmp/googleDrive/GoogleDriveService.java @@ -1,8 +1,14 @@ package org.kpmp.googleDrive; -import com.google.api.client.json.JsonFactory; -import com.google.api.client.json.jackson2.JacksonFactory; -import com.google.api.services.drive.DriveScopes; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.security.GeneralSecurityException; +import java.util.Collections; +import java.util.List; + +import org.springframework.stereotype.Service; import com.google.api.client.auth.oauth2.Credential; import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp; @@ -17,61 +23,47 @@ import com.google.api.services.drive.Drive; import com.google.api.services.drive.DriveScopes; import com.google.api.services.drive.model.File; -import com.google.api.services.drive.model.FileList; -import org.springframework.stereotype.Service; - -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.security.GeneralSecurityException; -import java.util.Collections; -import java.util.List; @Service public class GoogleDriveService { - private static final String APPLICATION_NAME = "KPMP Data Lake Repository"; - private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance(); - private static final String TOKENS_DIRECTORY_PATH = "tokens"; - private static final String TOP_LEVEL_FOLDER_ID = "1WEfJYFDqxLBBAdsKDC3zqvq0owW8hLwH"; + private static final String APPLICATION_NAME = "KPMP Data Lake Repository"; + private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance(); + private static final String TOKENS_DIRECTORY_PATH = "tokens"; + private static final String TOP_LEVEL_FOLDER_ID = "1WEfJYFDqxLBBAdsKDC3zqvq0owW8hLwH"; - private static final List SCOPES = Collections.singletonList(DriveScopes.DRIVE_FILE); - private static final String CREDENTIALS_FILE_PATH = "/credentials.json"; - private final Drive driveService; + private static final List SCOPES = Collections.singletonList(DriveScopes.DRIVE_FILE); + private static final String CREDENTIALS_FILE_PATH = "/credentials.json"; + private final Drive driveService; - public GoogleDriveService() throws GeneralSecurityException, IOException { - final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); - driveService = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT)) - .setApplicationName(APPLICATION_NAME) - .build(); - } + public GoogleDriveService() throws GeneralSecurityException, IOException { + final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); + driveService = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT)) + .setApplicationName(APPLICATION_NAME).build(); + } - private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException { - InputStream in = GoogleDriveService.class.getResourceAsStream(CREDENTIALS_FILE_PATH); - if (in == null) { - throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH); - } - GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in)); + private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException { + InputStream in = GoogleDriveService.class.getResourceAsStream(CREDENTIALS_FILE_PATH); + if (in == null) { + throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH); + } + GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in)); - GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder( - HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES) - .setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH))) - .setAccessType("offline") - .build(); - LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build(); - return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user"); - } + GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY, + clientSecrets, SCOPES) + .setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH))) + .setAccessType("offline").build(); + LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build(); + return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user"); + } - public String createFolder(String folderName) throws IOException { - File fileMetadata = new File(); - fileMetadata.setName(folderName); - fileMetadata.setMimeType("application/vnd.google-apps.folder"); - fileMetadata.setParents(Collections.singletonList(TOP_LEVEL_FOLDER_ID)); + public String createFolder(String folderName) throws IOException { + File fileMetadata = new File(); + fileMetadata.setName(folderName); + fileMetadata.setMimeType("application/vnd.google-apps.folder"); + fileMetadata.setParents(Collections.singletonList(TOP_LEVEL_FOLDER_ID)); - File file = driveService.files().create(fileMetadata) - .setFields("id") - .execute(); - return file.getId(); - } + File file = driveService.files().create(fileMetadata).setFields("id").execute(); + return file.getId(); + } } diff --git a/src/main/java/org/kpmp/packages/PackageFileHandler.java b/src/main/java/org/kpmp/packages/PackageFileHandler.java index c11ca1cd..c5f067b0 100755 --- a/src/main/java/org/kpmp/packages/PackageFileHandler.java +++ b/src/main/java/org/kpmp/packages/PackageFileHandler.java @@ -1,5 +1,6 @@ package org.kpmp.packages; +import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; @@ -42,4 +43,25 @@ public void saveMultipartFile(MultipartFile file, String packageId, String filen } } + public void saveFile(String fileContents, String packageId, String filename, boolean shouldOverwrite) + throws IOException { + String packageDirectoryPath = filePathHelper.getPackagePath(packageId); + File packageDirectory = new File(packageDirectoryPath); + + if (!packageDirectory.exists()) { + Files.createDirectories(Paths.get(packageDirectoryPath)); + } + + File fileToSave = new File(packageDirectoryPath + File.separator + filename); + + if (fileToSave.exists() && shouldOverwrite) { + fileToSave.delete(); + } else if (fileToSave.exists() && !shouldOverwrite) { + throw new FileAlreadyExistsException(fileToSave.getPath()); + } + + InputStream inputStream = new ByteArrayInputStream(fileContents.getBytes()); + FileOutputStream fileOutputStream = new FileOutputStream(fileToSave); + IOUtils.copy(inputStream, fileOutputStream); + } } diff --git a/src/main/java/org/kpmp/packages/PackageService.java b/src/main/java/org/kpmp/packages/PackageService.java index 8178d6d9..364e3905 100755 --- a/src/main/java/org/kpmp/packages/PackageService.java +++ b/src/main/java/org/kpmp/packages/PackageService.java @@ -127,7 +127,9 @@ public void createZipFile(String packageId, String origin, User user) throws Exc public void run() { try { String packageMetadata = packageRepository.getJSONByPackageId(packageId); - String[] zipCommand = commandBuilder.buildZipCommand(packageId, packageMetadata); + // TODO: Write out metadata.json file to package directory + + String[] zipCommand = commandBuilder.buildZipCommand(packageId); boolean success = processExecutor.executeProcess(zipCommand); if (success) { logger.logInfoMessage(PackageService.class, null, packageId, @@ -152,6 +154,7 @@ public void run() { logger.logErrorMessage(PackageService.class, user, packageId, PackageService.class.getSimpleName(), e.getMessage()); } + // TODO: Delete metadata.json file if exists } }.start(); diff --git a/src/test/java/org/kpmp/externalProcess/CommandBuilderTest.java b/src/test/java/org/kpmp/externalProcess/CommandBuilderTest.java index 2498d6d8..5ba1fb23 100644 --- a/src/test/java/org/kpmp/externalProcess/CommandBuilderTest.java +++ b/src/test/java/org/kpmp/externalProcess/CommandBuilderTest.java @@ -35,15 +35,15 @@ public void testBuildZipCommand_oneFile() { when(filePathHelper.getFilenames("/here/is/a/path")).thenReturn(Arrays.asList("file1.txt")); when(filePathHelper.getZipFileName("packageId")).thenReturn("/here/is/a/path/packageId.zip"); - String[] command = builder.buildZipCommand("packageId", "metadata contents"); + String[] command = builder.buildZipCommand("packageId"); assertEquals(6, command.length); assertEquals("java", command[0]); assertEquals("-jar", command[1]); assertEquals("/home/gradle/zipWorker/zipWorker.jar", command[2]); assertEquals("--zip.fileNames=/here/is/a/path/file1.txt", command[3]); - assertEquals("--zip.zipFilePath=/here/is/a/path/packageId.zip", command[4]); - assertEquals("--zip.additionalFileData=metadata.json|metadata contents", command[5]); + assertEquals("--zip.fileNames=/here/is/a/path/metadata.json", command[4]); + assertEquals("--zip.zipFilePath=/here/is/a/path/packageId.zip", command[5]); } @Test @@ -52,7 +52,7 @@ public void testBuildZipCommand_multipleFiles() { when(filePathHelper.getFilenames("/here/is/a/path")).thenReturn(Arrays.asList("file1.txt", "file2.txt")); when(filePathHelper.getZipFileName("packageId")).thenReturn("/here/is/a/path/packageId.zip"); - String[] command = builder.buildZipCommand("packageId", "metadata contents with a /"); + String[] command = builder.buildZipCommand("packageId"); assertEquals(7, command.length); assertEquals("java", command[0]); @@ -60,8 +60,8 @@ public void testBuildZipCommand_multipleFiles() { assertEquals("/home/gradle/zipWorker/zipWorker.jar", command[2]); assertEquals("--zip.fileNames=/here/is/a/path/file1.txt", command[3]); assertEquals("--zip.fileNames=/here/is/a/path/file2.txt", command[4]); - assertEquals("--zip.zipFilePath=/here/is/a/path/packageId.zip", command[5]); - assertEquals("--zip.additionalFileData=metadata.json|metadata contents with a /", command[6]); + assertEquals("--zip.fileNames=/here/is/a/path/metadata.json", command[5]); + assertEquals("--zip.zipFilePath=/here/is/a/path/packageId.zip", command[6]); } } diff --git a/src/test/java/org/kpmp/packages/PackageFileHandlerTest.java b/src/test/java/org/kpmp/packages/PackageFileHandlerTest.java index 2cea5c91..ded092b9 100755 --- a/src/test/java/org/kpmp/packages/PackageFileHandlerTest.java +++ b/src/test/java/org/kpmp/packages/PackageFileHandlerTest.java @@ -1,6 +1,7 @@ package org.kpmp.packages; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -39,9 +40,81 @@ public void tearDown() throws Exception { fileHandler = null; } + @Test + public void testSaveFile() throws Exception { + Path dataDirectory = Files.createTempDirectory("packageFileHandler"); + File tempDirectory = new File(dataDirectory.toString()); + tempDirectory.deleteOnExit(); + String dataDirectoryPath = dataDirectory.toString(); + when(filePathHelper.getPackagePath("packageId")).thenReturn(dataDirectoryPath); + String fileContents = "Here is the data in the file with special characters: µg/µL"; + + fileHandler.saveFile(fileContents, "packageId", "metadata.json", true); + + File savedFile = new File(dataDirectoryPath + File.separator + "metadata.json"); + assertEquals(true, savedFile.exists()); + BufferedReader reader = new BufferedReader(new FileReader(savedFile)); + String line = ""; + String actualFileContents = ""; + while ((line = reader.readLine()) != null) { + actualFileContents += line; + } + + assertEquals("Here is the data in the file with special characters: µg/µL", actualFileContents); + reader.close(); + } + + @Test + public void testSaveFile_whenFileExistsAndShouldOverwrite() throws Exception { + Path dataDirectory = Files.createTempDirectory("packageFileHandler"); + File tempDirectory = new File(dataDirectory.toString()); + tempDirectory.deleteOnExit(); + File existingFile = new File(dataDirectory + File.separator + "metadata.json"); + existingFile.createNewFile(); + String dataDirectoryPath = dataDirectory.toString(); + when(filePathHelper.getPackagePath("packageId")).thenReturn(dataDirectoryPath); + String fileContents = "Here is the data in the file with special characters: µg/µL"; + + fileHandler.saveFile(fileContents, "packageId", "metadata.json", true); + + File savedFile = new File(dataDirectoryPath + File.separator + "metadata.json"); + assertEquals(true, savedFile.exists()); + BufferedReader reader = new BufferedReader(new FileReader(savedFile)); + String line = ""; + String actualFileContents = ""; + while ((line = reader.readLine()) != null) { + actualFileContents += line; + } + assertEquals("Here is the data in the file with special characters: µg/µL", actualFileContents); + reader.close(); + } + + @Test + public void testSaveFile_whenFileExistsAndShouldNotOverwrite() throws Exception { + Path dataDirectory = Files.createTempDirectory("packageFileHandler"); + File tempDirectory = new File(dataDirectory.toString()); + tempDirectory.deleteOnExit(); + File existingFile = new File(dataDirectory + File.separator + "metadata.json"); + existingFile.createNewFile(); + String dataDirectoryPath = dataDirectory.toString(); + when(filePathHelper.getPackagePath("packageId")).thenReturn(dataDirectoryPath); + String fileContents = "Here is the data in the file with special characters: µg/µL"; + + try { + fileHandler.saveFile(fileContents, "packageId", "metadata.json", false); + // cleaning up after ourselves + fail("Should have thrown " + IOException.class); + } catch (IOException expected) { + assertEquals(dataDirectory + File.separator + "metadata.json", expected.getMessage()); + } + + } + @Test public void testSaveMultipartFile_firstPart() throws IOException { Path dataDirectory = Files.createTempDirectory("packageFileHandler"); + File tempDirectory = new File(dataDirectory.toString()); + tempDirectory.deleteOnExit(); String dataDirectoryPath = dataDirectory.toString(); when(filePathHelper.getPackagePath("packageId")).thenReturn(dataDirectoryPath); MultipartFile file = mock(MultipartFile.class); @@ -65,6 +138,8 @@ public void testSaveMultipartFile_firstPart() throws IOException { @Test public void testSaveMultipartFile_createsMissingDirectories() throws IOException { Path dataDirectory = Files.createTempDirectory("packageFileHandler"); + File tempDirectory = new File(dataDirectory.toString()); + tempDirectory.deleteOnExit(); String dataDirectoryPath = dataDirectory.toString() + File.separator + "anotherDirectory"; when(filePathHelper.getPackagePath("packageId")).thenReturn(dataDirectoryPath); MultipartFile file = mock(MultipartFile.class); @@ -80,6 +155,8 @@ public void testSaveMultipartFile_createsMissingDirectories() throws IOException @Test public void testSaveMultipartFile_twoParts() throws IOException { Path dataDirectory = Files.createTempDirectory("packageFileHandler"); + File tempDirectory = new File(dataDirectory.toString()); + tempDirectory.deleteOnExit(); String dataDirectoryPath = dataDirectory.toString(); when(filePathHelper.getPackagePath("packageId")).thenReturn(dataDirectoryPath); MultipartFile filePartOne = mock(MultipartFile.class); @@ -110,6 +187,8 @@ public void testSaveMultipartFile_twoParts() throws IOException { @Test public void testSaveMultipartFile_fileExists() throws IOException { Path dataDirectory = Files.createTempDirectory("packageFileHandler"); + File tempDirectory = new File(dataDirectory.toString()); + tempDirectory.deleteOnExit(); String dataDirectoryPath = dataDirectory.toString(); when(filePathHelper.getPackagePath("packageId")).thenReturn(dataDirectoryPath); MultipartFile fileOne = mock(MultipartFile.class); @@ -121,8 +200,8 @@ public void testSaveMultipartFile_fileExists() throws IOException { fileHandler.saveMultipartFile(fileOne, "packageId", "filename.txt", false); - assertThrows(FileAlreadyExistsException.class, () -> fileHandler.saveMultipartFile(fileTwo, "packageId", "filename.txt", false)); - + assertThrows(FileAlreadyExistsException.class, + () -> fileHandler.saveMultipartFile(fileTwo, "packageId", "filename.txt", false)); } From 63294aabd8bffcc186f71544c3dcb0c847240e29 Mon Sep 17 00:00:00 2001 From: Becky Reamy Date: Mon, 30 Sep 2019 16:40:32 -0400 Subject: [PATCH 03/26] KPMP-1332: Checking in changes to use new zipping algorithm --- src/main/java/org/kpmp/RegenerateZipFiles.java | 9 ++++++--- .../java/org/kpmp/packages/PackageFileHandler.java | 10 +++++----- src/main/java/org/kpmp/packages/PackageService.java | 5 +++-- 3 files changed, 14 insertions(+), 10 deletions(-) diff --git a/src/main/java/org/kpmp/RegenerateZipFiles.java b/src/main/java/org/kpmp/RegenerateZipFiles.java index cddbd373..cbcbdf1b 100755 --- a/src/main/java/org/kpmp/RegenerateZipFiles.java +++ b/src/main/java/org/kpmp/RegenerateZipFiles.java @@ -13,6 +13,7 @@ import org.kpmp.externalProcess.ProcessExecutor; import org.kpmp.packages.CustomPackageRepository; import org.kpmp.packages.FilePathHelper; +import org.kpmp.packages.PackageFileHandler; import org.kpmp.packages.PackageKeys; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -30,14 +31,16 @@ public class RegenerateZipFiles implements CommandLineRunner { private CommandBuilder commandBuilder; private ProcessExecutor processExecutor; private final Logger log = LoggerFactory.getLogger(this.getClass()); + private PackageFileHandler packageFileHandler; @Autowired public RegenerateZipFiles(CustomPackageRepository packageRepository, CommandBuilder commandBuilder, - FilePathHelper pathHelper, ProcessExecutor processExecutor) { + FilePathHelper pathHelper, ProcessExecutor processExecutor, PackageFileHandler packageFileHandler) { this.packageRepository = packageRepository; this.commandBuilder = commandBuilder; this.pathHelper = pathHelper; this.processExecutor = processExecutor; + this.packageFileHandler = packageFileHandler; } public static void main(String[] args) { @@ -52,6 +55,7 @@ public void run(String... args) throws Exception { for (JSONObject packageInfo : jsons) { String packageId = packageInfo.getString(PackageKeys.ID.getKey()); String packageMetadata = packageRepository.getJSONByPackageId(packageId); + File metadataFile = packageFileHandler.saveFile(packageMetadata, packageId, "metadata.json", true); String zipFileName = pathHelper.getZipFileName(packageId); if (packageInfo.getBoolean(PackageKeys.REGENERATE_ZIP.getKey())) { Date startRezipTime = new Date(); @@ -60,9 +64,9 @@ public void run(String... args) throws Exception { File existingZipFile = new File(zipFileName); existingZipFile.delete(); String[] zipCommand = commandBuilder.buildZipCommand(packageId); - // TODO: Write out metadata.json file boolean success = processExecutor.executeProcess(zipCommand); + metadataFile.delete(); if (success) { LocalDateTime start = LocalDateTime.ofInstant(startRezipTime.toInstant(), ZoneId.systemDefault()); @@ -78,7 +82,6 @@ public void run(String... args) throws Exception { } } } - // TODO: Delete metadata.json file if exists } } diff --git a/src/main/java/org/kpmp/packages/PackageFileHandler.java b/src/main/java/org/kpmp/packages/PackageFileHandler.java index c5f067b0..996a25c4 100755 --- a/src/main/java/org/kpmp/packages/PackageFileHandler.java +++ b/src/main/java/org/kpmp/packages/PackageFileHandler.java @@ -1,6 +1,5 @@ package org.kpmp.packages; -import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; @@ -9,6 +8,7 @@ import java.nio.file.Files; import java.nio.file.Paths; +import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @@ -43,7 +43,7 @@ public void saveMultipartFile(MultipartFile file, String packageId, String filen } } - public void saveFile(String fileContents, String packageId, String filename, boolean shouldOverwrite) + public File saveFile(String fileContents, String packageId, String filename, boolean shouldOverwrite) throws IOException { String packageDirectoryPath = filePathHelper.getPackagePath(packageId); File packageDirectory = new File(packageDirectoryPath); @@ -60,8 +60,8 @@ public void saveFile(String fileContents, String packageId, String filename, boo throw new FileAlreadyExistsException(fileToSave.getPath()); } - InputStream inputStream = new ByteArrayInputStream(fileContents.getBytes()); - FileOutputStream fileOutputStream = new FileOutputStream(fileToSave); - IOUtils.copy(inputStream, fileOutputStream); + FileUtils.writeStringToFile(fileToSave, fileContents, "UTF-8"); + + return fileToSave; } } diff --git a/src/main/java/org/kpmp/packages/PackageService.java b/src/main/java/org/kpmp/packages/PackageService.java index 364e3905..3e571616 100755 --- a/src/main/java/org/kpmp/packages/PackageService.java +++ b/src/main/java/org/kpmp/packages/PackageService.java @@ -127,10 +127,12 @@ public void createZipFile(String packageId, String origin, User user) throws Exc public void run() { try { String packageMetadata = packageRepository.getJSONByPackageId(packageId); - // TODO: Write out metadata.json file to package directory + File metadataJson = packageFileHandler.saveFile(packageMetadata, packageId, "metadata.json", true); String[] zipCommand = commandBuilder.buildZipCommand(packageId); boolean success = processExecutor.executeProcess(zipCommand); + metadataJson.delete(); + if (success) { logger.logInfoMessage(PackageService.class, null, packageId, PackageService.class.getSimpleName() + ".createZipFile", @@ -154,7 +156,6 @@ public void run() { logger.logErrorMessage(PackageService.class, user, packageId, PackageService.class.getSimpleName(), e.getMessage()); } - // TODO: Delete metadata.json file if exists } }.start(); From caf2b553bd73eaf952f81c13bf50af293df51404 Mon Sep 17 00:00:00 2001 From: Becky Reamy Date: Mon, 30 Sep 2019 16:56:52 -0400 Subject: [PATCH 04/26] KPMP-1332: Final cleanup --- README.md | 2 +- .../org/kpmp/packages/MetadataJsonMixin.java | 22 -------- src/main/java/org/kpmp/packages/Package.java | 14 +---- .../java/org/kpmp/packages/PackageTest.java | 53 ++----------------- 4 files changed, 8 insertions(+), 83 deletions(-) delete mode 100755 src/main/java/org/kpmp/packages/MetadataJsonMixin.java diff --git a/README.md b/README.md index 41f0101d..50b632d1 100644 --- a/README.md +++ b/README.md @@ -33,7 +33,7 @@ To regenerate zip files: 5. Bash into the spring container `docker exec -it spring bash` 6. Rebuild the orion-data jar -`./gradlew build` +`./gradlew build -x test` 7. Run the zip generator `java -cp build/libs/orion-data.jar -Dloader.main=org.kpmp.RegenerateZipFiles org.springframework.boot.loader.PropertiesLauncher` diff --git a/src/main/java/org/kpmp/packages/MetadataJsonMixin.java b/src/main/java/org/kpmp/packages/MetadataJsonMixin.java deleted file mode 100755 index ad58ae16..00000000 --- a/src/main/java/org/kpmp/packages/MetadataJsonMixin.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.kpmp.packages; - -import java.util.Date; - -import com.fasterxml.jackson.annotation.JsonFormat; -import com.fasterxml.jackson.annotation.JsonIgnore; - -abstract class MetadataJsonMixin { - - @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss 'UTC'", timezone = "GMT") - abstract Date getCreatedAt(); - - @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd") - abstract Date getExperimentDate(); - - @JsonIgnore - abstract Boolean getRegenerateZip(); - - @JsonIgnore - abstract Boolean getLargeFilesChecked(); - -} diff --git a/src/main/java/org/kpmp/packages/Package.java b/src/main/java/org/kpmp/packages/Package.java index 55660486..a97b1a5e 100755 --- a/src/main/java/org/kpmp/packages/Package.java +++ b/src/main/java/org/kpmp/packages/Package.java @@ -5,7 +5,6 @@ import java.util.List; import org.kpmp.users.User; -import org.kpmp.users.UserJsonMixin; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.DBRef; import org.springframework.data.mongodb.core.mapping.Document; @@ -13,8 +12,6 @@ import org.springframework.lang.Nullable; import com.fasterxml.jackson.annotation.JsonPropertyOrder; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; @Document(collection = "packages") @JsonPropertyOrder({ "packageId", "createdAt", "packageType", "submitter", "tisName", "protocol", "subjectId", @@ -142,15 +139,8 @@ public void setRegenerateZip(Boolean regenerateZip) { public String toString() { return "packageId: " + packageId + ", packageType: " + packageType + ", createdAt: " + createdAt + ", submitterId: " + submitter.getId() + ", protocol: " + protocol + ", subjectId: " + subjectId - + ", experimentDate: " + experimentDate + ", description: " + description + ", tisName: " - + tisName + ", number of attachments: " + attachments.size() + ", regenerateZip: " + regenerateZip; - } - - public String generateJSON() throws JsonProcessingException { - ObjectMapper mapper = new ObjectMapper(); - mapper.addMixIn(Package.class, MetadataJsonMixin.class); - mapper.addMixIn(User.class, UserJsonMixin.class); - return mapper.writeValueAsString(this); + + ", experimentDate: " + experimentDate + ", description: " + description + ", tisName: " + tisName + + ", number of attachments: " + attachments.size() + ", regenerateZip: " + regenerateZip; } } diff --git a/src/test/java/org/kpmp/packages/PackageTest.java b/src/test/java/org/kpmp/packages/PackageTest.java index 9f25b88a..79fe16f7 100755 --- a/src/test/java/org/kpmp/packages/PackageTest.java +++ b/src/test/java/org/kpmp/packages/PackageTest.java @@ -3,12 +3,9 @@ import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; -import java.text.DateFormat; -import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Date; import java.util.List; -import java.util.TimeZone; import org.junit.After; import org.junit.Before; @@ -116,51 +113,11 @@ public void testToString() throws Exception { user.setId("1234"); packageInfo.setSubmitter(user); - assertEquals("packageId: packageId, packageType: packageType, createdAt: " + createdAt + ", " - + "submitterId: 1234, " - + "protocol: protocol, subjectId: subjectId, experimentDate: null, description: description, " - + "tisName: TIS, number of attachments: 1, regenerateZip: true", packageInfo.toString()); - } - - @Test - public void testGenerateJSON() throws Exception { - Date createdAt = new Date(); - Date experimentDate = new Date(); - Package packageInfo = new Package(); - Attachment attachment = new Attachment(); - attachment.setFileName("filename"); - attachment.setId("fileId"); - attachment.setSize(433); - packageInfo.setAttachments(Arrays.asList(attachment)); - packageInfo.setCreatedAt(createdAt); - packageInfo.setDescription("description"); - packageInfo.setTisName("TIS"); - packageInfo.setPackageId("packageId"); - packageInfo.setPackageType("packageType"); - packageInfo.setProtocol("protocol"); - packageInfo.setSubjectId("subjectId"); - User testUser = new User(); - testUser.setId("1234"); - testUser.setFirstName("Arnold"); - testUser.setLastName("Schwarzenegger"); - testUser.setDisplayName("Conan"); - testUser.setEmail("arnie@illbeback.com"); - packageInfo.setSubmitter(testUser); - packageInfo.setExperimentDate(experimentDate); - DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss 'UTC'"); - df.setTimeZone(TimeZone.getTimeZone("UTC")); - String createdAtString = df.format(createdAt); - DateFormat experimentDateFormat = new SimpleDateFormat("yyyy-MM-dd"); - String experimentDateString = experimentDateFormat.format(experimentDate); - assertEquals( - "{\"packageId\":\"packageId\",\"createdAt\":\"" + createdAtString + "\"," - + "\"packageType\":\"packageType\"," + - "\"submitter\":{\"firstName\":\"Arnold\",\"lastName\":\"Schwarzenegger\"," - + "\"displayName\":\"Conan\",\"email\":\"arnie@illbeback.com\"}," - + "\"tisName\":\"TIS\"," + "\"protocol\":\"protocol\",\"subjectId\":\"subjectId\"," - + "\"experimentDate\":\"" + experimentDateString + "\",\"description\":\"description\"," - + "\"attachments\":[{\"fileName\":\"filename\",\"size\":433,\"id\":\"fileId\"}]}", - packageInfo.generateJSON()); + "packageId: packageId, packageType: packageType, createdAt: " + createdAt + ", " + "submitterId: 1234, " + + "protocol: protocol, subjectId: subjectId, experimentDate: null, description: description, " + + "tisName: TIS, number of attachments: 1, regenerateZip: true", + packageInfo.toString()); } + } From c7a4bc6180d7c652b2207df934aa38eb494c8856 Mon Sep 17 00:00:00 2001 From: Zach Wright Date: Fri, 4 Oct 2019 11:22:14 -0400 Subject: [PATCH 05/26] KPMP-1323: Use ENV for Google folder --- .../kpmp/googleDrive/GoogleDriveService.java | 30 +++++++++++-------- 1 file changed, 17 insertions(+), 13 deletions(-) diff --git a/src/main/java/org/kpmp/googleDrive/GoogleDriveService.java b/src/main/java/org/kpmp/googleDrive/GoogleDriveService.java index ae845ff0..736d46d1 100644 --- a/src/main/java/org/kpmp/googleDrive/GoogleDriveService.java +++ b/src/main/java/org/kpmp/googleDrive/GoogleDriveService.java @@ -1,15 +1,5 @@ package org.kpmp.googleDrive; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.security.GeneralSecurityException; -import java.util.Collections; -import java.util.List; - -import org.springframework.stereotype.Service; - import com.google.api.client.auth.oauth2.Credential; import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp; import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver; @@ -23,6 +13,16 @@ import com.google.api.services.drive.Drive; import com.google.api.services.drive.DriveScopes; import com.google.api.services.drive.model.File; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Service; + +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.security.GeneralSecurityException; +import java.util.Collections; +import java.util.List; @Service public class GoogleDriveService { @@ -30,16 +30,20 @@ public class GoogleDriveService { private static final String APPLICATION_NAME = "KPMP Data Lake Repository"; private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance(); private static final String TOKENS_DIRECTORY_PATH = "tokens"; - private static final String TOP_LEVEL_FOLDER_ID = "1WEfJYFDqxLBBAdsKDC3zqvq0owW8hLwH"; + private String topLevelFolderId; private static final List SCOPES = Collections.singletonList(DriveScopes.DRIVE_FILE); private static final String CREDENTIALS_FILE_PATH = "/credentials.json"; private final Drive driveService; - public GoogleDriveService() throws GeneralSecurityException, IOException { + private final Environment env; + + public GoogleDriveService(Environment env) throws GeneralSecurityException, IOException { final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); driveService = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT)) .setApplicationName(APPLICATION_NAME).build(); + this.env = env; + topLevelFolderId = env.getProperty("GOOGLE_DRIVE_FOLDER_ID"); } private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException { @@ -61,7 +65,7 @@ public String createFolder(String folderName) throws IOException { File fileMetadata = new File(); fileMetadata.setName(folderName); fileMetadata.setMimeType("application/vnd.google-apps.folder"); - fileMetadata.setParents(Collections.singletonList(TOP_LEVEL_FOLDER_ID)); + fileMetadata.setParents(Collections.singletonList(topLevelFolderId)); File file = driveService.files().create(fileMetadata).setFields("id").execute(); return file.getId(); From c5a4d27af2a808ff8750a759a79ac3fed19757c5 Mon Sep 17 00:00:00 2001 From: Becky Reamy Date: Mon, 7 Oct 2019 15:47:05 -0400 Subject: [PATCH 06/26] KPMP-1317: Stashing changes --- .../org/kpmp/filters/AuthorizationFilter.java | 52 ++++++++++++++++--- src/main/resources/application.properties | 3 ++ 2 files changed, 49 insertions(+), 6 deletions(-) diff --git a/src/main/java/org/kpmp/filters/AuthorizationFilter.java b/src/main/java/org/kpmp/filters/AuthorizationFilter.java index e52feb91..3fc410d5 100644 --- a/src/main/java/org/kpmp/filters/AuthorizationFilter.java +++ b/src/main/java/org/kpmp/filters/AuthorizationFilter.java @@ -8,24 +8,38 @@ import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; +import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; import org.kpmp.logging.LoggingService; import org.kpmp.shibboleth.ShibbolethUserService; import org.kpmp.users.User; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; +import org.springframework.web.client.RestTemplate; @Component public class AuthorizationFilter implements Filter { private LoggingService logger; private ShibbolethUserService shibUserService; + private RestTemplate restTemplate; + + @Value("${user.auth.host}") + private String userAuthHost; + @Value("${user.auth.endpoint}") + private String userAuthEndpoint; @Autowired - public AuthorizationFilter(LoggingService logger, ShibbolethUserService shibUserService) { + public AuthorizationFilter(LoggingService logger, ShibbolethUserService shibUserService, RestTemplate restTemplate, + Environment env) { this.logger = logger; this.shibUserService = shibUserService; + this.restTemplate = restTemplate; } @Override @@ -39,13 +53,39 @@ public void doFilter(ServletRequest incomingRequest, ServletResponse incomingRes throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) incomingRequest; + HttpServletResponse response = (HttpServletResponse) incomingResponse; + + HttpSession existingSession = request.getSession(false); + Cookie[] cookies = request.getCookies(); User user = shibUserService.getUser(request); - // This is where we will implement the logic to talk to the user portal and do - // authorization. + String shibId = user.getShibId(); + + if (hasExistingSession(existingSession, shibId, cookies, request)) { + chain.doFilter(incomingRequest, incomingResponse); + } else { + // get user information + String uri = userAuthHost + userAuthEndpoint + "/"; + } + + } - logger.logInfoMessage(this.getClass(), user, null, this.getClass().getSimpleName() + ".doFilter", - "Passing through authentication filter"); - chain.doFilter(incomingRequest, incomingResponse); + private boolean hasExistingSession(HttpSession existingSession, String shibId, Cookie[] cookies, + HttpServletRequest request) { + if (existingSession != null) { + for (Cookie cookie : cookies) { + if (cookie.getName().equals("shibId")) { + if (cookie.getValue().equals(shibId)) { + return true; + } else { + logger.logInfoMessage(this.getClass(), null, + "MSG: Invalidating session. Cookie does not match shibId for user", request); + existingSession.invalidate(); + return false; + } + } + } + } + return false; } @Override diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 3bb4de4d..90e40f06 100755 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -10,6 +10,9 @@ notification.endpoint=/v1/notifications/package state.service.host=http://state-spring:3060 state.service.endpoint=/v1/state +user.auth.host=http://user-auth +user.auth.endpoint=/v1/user/info + spring.servlet.multipart.max-file-size=102400MB spring.servlet.multipart.max-request-size=102400MB spring.http.multipart.enabled=false From 7c951ba0b3ecc6a7a398a8bec87f0675793dfbdb Mon Sep 17 00:00:00 2001 From: Becky Reamy Date: Mon, 7 Oct 2019 15:51:07 -0400 Subject: [PATCH 07/26] KPMP-1332: Only send metadata.json once --- src/main/java/org/kpmp/externalProcess/CommandBuilder.java | 1 - .../java/org/kpmp/externalProcess/CommandBuilderTest.java | 5 +++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/kpmp/externalProcess/CommandBuilder.java b/src/main/java/org/kpmp/externalProcess/CommandBuilder.java index 6aab0531..0274cd1e 100644 --- a/src/main/java/org/kpmp/externalProcess/CommandBuilder.java +++ b/src/main/java/org/kpmp/externalProcess/CommandBuilder.java @@ -29,7 +29,6 @@ public String[] buildZipCommand(String packageId) { for (String fileName : fileNames) { commandArgs.add("--zip.fileNames=" + packagePath + File.separator + fileName); } - commandArgs.add("--zip.fileNames=" + packagePath + File.separator + "metadata.json"); String zipFileName = filePathHelper.getZipFileName(packageId); commandArgs.add("--zip.zipFilePath=" + zipFileName); diff --git a/src/test/java/org/kpmp/externalProcess/CommandBuilderTest.java b/src/test/java/org/kpmp/externalProcess/CommandBuilderTest.java index 5ba1fb23..004c5ead 100644 --- a/src/test/java/org/kpmp/externalProcess/CommandBuilderTest.java +++ b/src/test/java/org/kpmp/externalProcess/CommandBuilderTest.java @@ -32,7 +32,7 @@ public void tearDown() throws Exception { @Test public void testBuildZipCommand_oneFile() { when(filePathHelper.getPackagePath("packageId")).thenReturn("/here/is/a/path"); - when(filePathHelper.getFilenames("/here/is/a/path")).thenReturn(Arrays.asList("file1.txt")); + when(filePathHelper.getFilenames("/here/is/a/path")).thenReturn(Arrays.asList("file1.txt", "metadata.json")); when(filePathHelper.getZipFileName("packageId")).thenReturn("/here/is/a/path/packageId.zip"); String[] command = builder.buildZipCommand("packageId"); @@ -49,7 +49,8 @@ public void testBuildZipCommand_oneFile() { @Test public void testBuildZipCommand_multipleFiles() { when(filePathHelper.getPackagePath("packageId")).thenReturn("/here/is/a/path"); - when(filePathHelper.getFilenames("/here/is/a/path")).thenReturn(Arrays.asList("file1.txt", "file2.txt")); + when(filePathHelper.getFilenames("/here/is/a/path")) + .thenReturn(Arrays.asList("file1.txt", "file2.txt", "metadata.json")); when(filePathHelper.getZipFileName("packageId")).thenReturn("/here/is/a/path/packageId.zip"); String[] command = builder.buildZipCommand("packageId"); From b8fa9d543478147a032fac4e2e4d95fe822bb291 Mon Sep 17 00:00:00 2001 From: Becky Reamy Date: Tue, 8 Oct 2019 15:40:43 -0400 Subject: [PATCH 08/26] KPMP-1317: Removed some warnings...added lots of tests --- .../org/kpmp/filters/AuthorizationFilter.java | 98 +++++++- .../kpmp/googleDrive/GoogleDriveService.java | 26 +-- src/main/resources/application.properties | 6 +- .../kpmp/filters/AuthorizationFilterTest.java | 211 +++++++++++++++++- 4 files changed, 314 insertions(+), 27 deletions(-) diff --git a/src/main/java/org/kpmp/filters/AuthorizationFilter.java b/src/main/java/org/kpmp/filters/AuthorizationFilter.java index 3fc410d5..97663c19 100644 --- a/src/main/java/org/kpmp/filters/AuthorizationFilter.java +++ b/src/main/java/org/kpmp/filters/AuthorizationFilter.java @@ -1,6 +1,7 @@ package org.kpmp.filters; import java.io.IOException; +import java.util.List; import javax.servlet.Filter; import javax.servlet.FilterChain; @@ -13,18 +14,35 @@ import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; import org.kpmp.logging.LoggingService; import org.kpmp.shibboleth.ShibbolethUserService; import org.kpmp.users.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.env.Environment; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; +import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.RestTemplate; @Component public class AuthorizationFilter implements Filter { + private static final String USER_NOT_PART_OF_KPMP = "User is not part of KPMP: "; + private static final String USER_NO_DLU_ACCESS = "User does not have access to DLU: "; + private static final String GROUPS_KEY = "groups"; + private static final String USER_DOES_NOT_EXIST = "User does not exist in User Portal: "; + private static final String CLIENT_ID_PROPERTY = "CLIENT_ID"; + private static final String COOKIE_NAME = "shibid"; + private static final int SECONDS_IN_MINUTE = 60; + private static final int MINUTES_IN_HOUR = 60; + private static final int SESSION_TIMEOUT_HOURS = 8; + private static final int SESSION_TIMEOUT_SECONDS = SECONDS_IN_MINUTE * MINUTES_IN_HOUR * SESSION_TIMEOUT_HOURS; + private LoggingService logger; private ShibbolethUserService shibUserService; private RestTemplate restTemplate; @@ -33,6 +51,11 @@ public class AuthorizationFilter implements Filter { private String userAuthHost; @Value("${user.auth.endpoint}") private String userAuthEndpoint; + @Value("#{'${user.auth.allowed.groups}'.split(',')}") + private List allowedGroups; + @Value("${user.auth.kpmp.group}") + private String kpmpGroup; + private Environment env; @Autowired public AuthorizationFilter(LoggingService logger, ShibbolethUserService shibUserService, RestTemplate restTemplate, @@ -40,6 +63,7 @@ public AuthorizationFilter(LoggingService logger, ShibbolethUserService shibUser this.logger = logger; this.shibUserService = shibUserService; this.restTemplate = restTemplate; + this.env = env; } @Override @@ -55,22 +79,82 @@ public void doFilter(ServletRequest incomingRequest, ServletResponse incomingRes HttpServletRequest request = (HttpServletRequest) incomingRequest; HttpServletResponse response = (HttpServletResponse) incomingResponse; - HttpSession existingSession = request.getSession(false); Cookie[] cookies = request.getCookies(); User user = shibUserService.getUser(request); String shibId = user.getShibId(); - if (hasExistingSession(existingSession, shibId, cookies, request)) { - chain.doFilter(incomingRequest, incomingResponse); + if (hasExistingSession(shibId, cookies, request)) { + chain.doFilter(request, response); } else { - // get user information - String uri = userAuthHost + userAuthEndpoint + "/"; + String clientId = env.getProperty(CLIENT_ID_PROPERTY); + String uri = userAuthHost + userAuthEndpoint + "/" + clientId + "/" + shibId; + try { + ResponseEntity userInfoResponse = restTemplate.getForEntity(uri, String.class); + String userInfo = userInfoResponse.getBody(); + try { + JSONObject userJson = new JSONObject(userInfo); + JSONArray userGroups = userJson.getJSONArray(GROUPS_KEY); + + if (isAllowed(userGroups)) { + HttpSession session = request.getSession(true); + session.setMaxInactiveInterval(SESSION_TIMEOUT_SECONDS); + Cookie message = new Cookie(COOKIE_NAME, shibId); + session.setAttribute("roles", userGroups); + response.addCookie(message); + chain.doFilter(request, response); + } else if (isKPMP(userGroups)) { + handleError(USER_NO_DLU_ACCESS + userGroups, HttpStatus.FORBIDDEN, request, response); + } else { + handleError(USER_NOT_PART_OF_KPMP + userGroups, HttpStatus.NOT_FOUND, request, response); + } + + } catch (JSONException e) { + handleError("Unable to parse response from User Portal, denying user " + shibId + + " access. Response: " + userInfo, HttpStatus.FAILED_DEPENDENCY, request, response); + + } + + } catch (HttpClientErrorException e) { + int statusCode = e.getRawStatusCode(); + if (statusCode == HttpStatus.NOT_FOUND.value()) { + handleError(USER_DOES_NOT_EXIST + shibId, HttpStatus.FAILED_DEPENDENCY, request, response); + } else if (statusCode != HttpStatus.OK.value()) { + handleError("Unable to get user information. User auth returned status code: " + statusCode, + HttpStatus.FAILED_DEPENDENCY, request, response); + } + } } } - private boolean hasExistingSession(HttpSession existingSession, String shibId, Cookie[] cookies, - HttpServletRequest request) { + private boolean isAllowed(JSONArray userGroups) throws JSONException { + for (int i = 0; i < userGroups.length(); i++) { + String group = userGroups.getString(i); + if (allowedGroups.contains(group)) { + return true; + } + } + return false; + } + + private boolean isKPMP(JSONArray userGroups) throws JSONException { + for (int i = 0; i < userGroups.length(); i++) { + String group = userGroups.getString(i); + if (kpmpGroup.equals(group)) { + return true; + } + } + return false; + } + + private void handleError(String errorMessage, HttpStatus status, HttpServletRequest request, + HttpServletResponse response) { + logger.logErrorMessage(this.getClass(), null, errorMessage, request); + response.setStatus(status.value()); + } + + private boolean hasExistingSession(String shibId, Cookie[] cookies, HttpServletRequest request) { + HttpSession existingSession = request.getSession(false); if (existingSession != null) { for (Cookie cookie : cookies) { if (cookie.getName().equals("shibId")) { diff --git a/src/main/java/org/kpmp/googleDrive/GoogleDriveService.java b/src/main/java/org/kpmp/googleDrive/GoogleDriveService.java index 736d46d1..02f7886b 100644 --- a/src/main/java/org/kpmp/googleDrive/GoogleDriveService.java +++ b/src/main/java/org/kpmp/googleDrive/GoogleDriveService.java @@ -1,5 +1,16 @@ package org.kpmp.googleDrive; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.security.GeneralSecurityException; +import java.util.Collections; +import java.util.List; + +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Service; + import com.google.api.client.auth.oauth2.Credential; import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp; import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver; @@ -13,16 +24,6 @@ import com.google.api.services.drive.Drive; import com.google.api.services.drive.DriveScopes; import com.google.api.services.drive.model.File; -import org.springframework.core.env.Environment; -import org.springframework.stereotype.Service; - -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.security.GeneralSecurityException; -import java.util.Collections; -import java.util.List; @Service public class GoogleDriveService { @@ -30,19 +31,16 @@ public class GoogleDriveService { private static final String APPLICATION_NAME = "KPMP Data Lake Repository"; private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance(); private static final String TOKENS_DIRECTORY_PATH = "tokens"; - private String topLevelFolderId; + private String topLevelFolderId; private static final List SCOPES = Collections.singletonList(DriveScopes.DRIVE_FILE); private static final String CREDENTIALS_FILE_PATH = "/credentials.json"; private final Drive driveService; - private final Environment env; - public GoogleDriveService(Environment env) throws GeneralSecurityException, IOException { final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); driveService = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT)) .setApplicationName(APPLICATION_NAME).build(); - this.env = env; topLevelFolderId = env.getProperty("GOOGLE_DRIVE_FOLDER_ID"); } diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 90e40f06..70833040 100755 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -10,8 +10,12 @@ notification.endpoint=/v1/notifications/package state.service.host=http://state-spring:3060 state.service.endpoint=/v1/state -user.auth.host=http://user-auth +user.auth.host=http://user-auth:8080 user.auth.endpoint=/v1/user/info +user.auth.allowed.groups=uw_rit_kpmp_role_developer +#user.auth.allowed.groups=uw_rit_kpmp_app_data-lake-uploader +user.auth.kpmp.group=uw_rit_kpmp_role_kpmp-user + spring.servlet.multipart.max-file-size=102400MB spring.servlet.multipart.max-request-size=102400MB diff --git a/src/test/java/org/kpmp/filters/AuthorizationFilterTest.java b/src/test/java/org/kpmp/filters/AuthorizationFilterTest.java index b7cdd332..8ec20b87 100644 --- a/src/test/java/org/kpmp/filters/AuthorizationFilterTest.java +++ b/src/test/java/org/kpmp/filters/AuthorizationFilterTest.java @@ -1,15 +1,21 @@ package org.kpmp.filters; +import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import java.util.Arrays; + import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; +import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; import org.junit.After; import org.junit.Before; @@ -17,8 +23,15 @@ import org.kpmp.logging.LoggingService; import org.kpmp.shibboleth.ShibbolethUserService; import org.kpmp.users.User; +import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; +import org.springframework.core.env.Environment; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.RestTemplate; public class AuthorizationFilterTest { @@ -27,11 +40,19 @@ public class AuthorizationFilterTest { private LoggingService logger; @Mock private ShibbolethUserService shibUserService; + @Mock + private RestTemplate restTemplate; + @Mock + private Environment env; @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); - filter = new AuthorizationFilter(logger, shibUserService); + filter = new AuthorizationFilter(logger, shibUserService, restTemplate, env); + ReflectionTestUtils.setField(filter, "userAuthHost", "hostname"); + ReflectionTestUtils.setField(filter, "userAuthEndpoint", "endpoint"); + ReflectionTestUtils.setField(filter, "allowedGroups", Arrays.asList("group1", "group2")); + ReflectionTestUtils.setField(filter, "kpmpGroup", "imaKpmpUser"); } @After @@ -50,19 +71,199 @@ public void testInit() throws ServletException { } @Test - public void testDoFilter() throws Exception { + public void testDoFilter_userHasValidCookie() throws Exception { HttpServletRequest incomingRequest = mock(HttpServletRequest.class); HttpServletResponse incomingResponse = mock(HttpServletResponse.class); FilterChain chain = mock(FilterChain.class); User user = mock(User.class); - when(user.getEmail()).thenReturn("jimmy@buffet.org"); + when(user.getShibId()).thenReturn("shibboleth id"); when(shibUserService.getUser(incomingRequest)).thenReturn(user); + HttpSession session = mock(HttpSession.class); + when(incomingRequest.getSession(false)).thenReturn(session); + Cookie goodCookie = mock(Cookie.class); + when(goodCookie.getName()).thenReturn("shibId"); + when(goodCookie.getValue()).thenReturn("shibboleth id"); + Cookie badCookie = mock(Cookie.class); + when(badCookie.getName()).thenReturn("Darth Vader"); + when(incomingRequest.getCookies()).thenReturn(new Cookie[] { badCookie, goodCookie }); filter.doFilter(incomingRequest, incomingResponse, chain); verify(chain).doFilter(incomingRequest, incomingResponse); - verify(logger, times(1)).logInfoMessage(AuthorizationFilter.class, user, null, "AuthorizationFilter.doFilter", - "Passing through authentication filter"); + } + + @SuppressWarnings("unchecked") + @Test + public void testDoFilter_userHasSomeoneElsesCookieAndGotEmptyResponse() throws Exception { + HttpServletRequest incomingRequest = mock(HttpServletRequest.class); + HttpServletResponse incomingResponse = mock(HttpServletResponse.class); + FilterChain chain = mock(FilterChain.class); + User user = mock(User.class); + when(user.getShibId()).thenReturn("shibboleth id"); + when(shibUserService.getUser(incomingRequest)).thenReturn(user); + HttpSession session = mock(HttpSession.class); + when(incomingRequest.getSession(false)).thenReturn(session); + Cookie shibCookie = mock(Cookie.class); + when(shibCookie.getName()).thenReturn("shibId"); + when(shibCookie.getValue()).thenReturn("not your cookie"); + when(incomingRequest.getCookies()).thenReturn(new Cookie[] { shibCookie }); + ResponseEntity response = mock(ResponseEntity.class); + when(response.getBody()).thenReturn("{}"); + when(restTemplate.getForEntity(any(String.class), any(Class.class))).thenReturn(response); + + filter.doFilter(incomingRequest, incomingResponse, chain); + + verify(chain, times(0)).doFilter(incomingRequest, incomingResponse); + verify(logger).logInfoMessage(AuthorizationFilter.class, null, + "MSG: Invalidating session. Cookie does not match shibId for user", incomingRequest); + verify(session).invalidate(); + verify(incomingResponse).setStatus(HttpStatus.FAILED_DEPENDENCY.value()); + verify(logger).logErrorMessage(AuthorizationFilter.class, null, + "Unable to parse response from User Portal, denying user shibboleth id access. Response: {}", + incomingRequest); + } + + @SuppressWarnings("unchecked") + @Test + public void testDoFilter_whenNoSessionAndEmptyResponse() throws Exception { + HttpServletRequest incomingRequest = mock(HttpServletRequest.class); + HttpServletResponse incomingResponse = mock(HttpServletResponse.class); + FilterChain chain = mock(FilterChain.class); + User user = mock(User.class); + when(user.getShibId()).thenReturn("shibboleth id"); + when(shibUserService.getUser(incomingRequest)).thenReturn(user); + when(incomingRequest.getSession(false)).thenReturn(null); + ResponseEntity response = mock(ResponseEntity.class); + when(response.getBody()).thenReturn("{}"); + when(restTemplate.getForEntity(any(String.class), any(Class.class))).thenReturn(response); + + filter.doFilter(incomingRequest, incomingResponse, chain); + + verify(chain, times(0)).doFilter(incomingRequest, incomingResponse); + verify(incomingResponse).setStatus(HttpStatus.FAILED_DEPENDENCY.value()); + verify(logger).logErrorMessage(AuthorizationFilter.class, null, + "Unable to parse response from User Portal, denying user shibboleth id access. Response: {}", + incomingRequest); + } + + @SuppressWarnings("unchecked") + @Test + public void testDoFilter_noSessionHasAllowedGroup() throws Exception { + HttpServletRequest incomingRequest = mock(HttpServletRequest.class); + HttpServletResponse incomingResponse = mock(HttpServletResponse.class); + HttpSession session = mock(HttpSession.class); + when(incomingRequest.getSession(true)).thenReturn(session); + FilterChain chain = mock(FilterChain.class); + User user = mock(User.class); + when(user.getShibId()).thenReturn("shibboleth id"); + when(shibUserService.getUser(incomingRequest)).thenReturn(user); + when(incomingRequest.getSession(false)).thenReturn(null); + ResponseEntity response = mock(ResponseEntity.class); + when(response.getBody()).thenReturn("{groups: [ 'group1', 'another group']}"); + when(restTemplate.getForEntity(any(String.class), any(Class.class))).thenReturn(response); + + filter.doFilter(incomingRequest, incomingResponse, chain); + + verify(chain).doFilter(incomingRequest, incomingResponse); + verify(session).setMaxInactiveInterval(8 * 60 * 60); + ArgumentCaptor cookieJar = ArgumentCaptor.forClass(Cookie.class); + verify(incomingResponse).addCookie(cookieJar.capture()); + assertEquals(cookieJar.getValue().getName(), "shibid"); + assertEquals(cookieJar.getValue().getValue(), "shibboleth id"); + } + + @SuppressWarnings("unchecked") + @Test + public void testDoFilter_noSessionDoesNotHaveAllowedGroupHasKpmpGroup() throws Exception { + HttpServletRequest incomingRequest = mock(HttpServletRequest.class); + HttpServletResponse incomingResponse = mock(HttpServletResponse.class); + HttpSession session = mock(HttpSession.class); + when(incomingRequest.getSession(true)).thenReturn(session); + FilterChain chain = mock(FilterChain.class); + User user = mock(User.class); + when(user.getShibId()).thenReturn("shibboleth id"); + when(shibUserService.getUser(incomingRequest)).thenReturn(user); + when(incomingRequest.getSession(false)).thenReturn(null); + ResponseEntity response = mock(ResponseEntity.class); + when(response.getBody()).thenReturn("{groups: [ 'imaKpmpUser', 'another group']}"); + when(restTemplate.getForEntity(any(String.class), any(Class.class))).thenReturn(response); + + filter.doFilter(incomingRequest, incomingResponse, chain); + + verify(chain, times(0)).doFilter(incomingRequest, incomingResponse); + verify(incomingResponse).setStatus(HttpStatus.FORBIDDEN.value()); + verify(logger).logErrorMessage(AuthorizationFilter.class, null, + "User does not have access to DLU: [\"imaKpmpUser\",\"another group\"]", incomingRequest); + } + + @SuppressWarnings("unchecked") + @Test + public void testDoFilter_noSessionDoesNotHaveAllowedGroupNoKpmpGroup() throws Exception { + HttpServletRequest incomingRequest = mock(HttpServletRequest.class); + HttpServletResponse incomingResponse = mock(HttpServletResponse.class); + HttpSession session = mock(HttpSession.class); + when(incomingRequest.getSession(true)).thenReturn(session); + FilterChain chain = mock(FilterChain.class); + User user = mock(User.class); + when(user.getShibId()).thenReturn("shibboleth id"); + when(shibUserService.getUser(incomingRequest)).thenReturn(user); + when(incomingRequest.getSession(false)).thenReturn(null); + ResponseEntity response = mock(ResponseEntity.class); + when(response.getBody()).thenReturn("{groups: [ 'unrelated group', 'another group']}"); + when(restTemplate.getForEntity(any(String.class), any(Class.class))).thenReturn(response); + + filter.doFilter(incomingRequest, incomingResponse, chain); + + verify(chain, times(0)).doFilter(incomingRequest, incomingResponse); + verify(incomingResponse).setStatus(HttpStatus.NOT_FOUND.value()); + verify(logger).logErrorMessage(AuthorizationFilter.class, null, + "User is not part of KPMP: [\"unrelated group\",\"another group\"]", incomingRequest); + } + + @SuppressWarnings("unchecked") + @Test + public void testDoFilter_userAuthReturned404() throws Exception { + HttpServletRequest incomingRequest = mock(HttpServletRequest.class); + HttpServletResponse incomingResponse = mock(HttpServletResponse.class); + HttpSession session = mock(HttpSession.class); + when(incomingRequest.getSession(true)).thenReturn(session); + FilterChain chain = mock(FilterChain.class); + User user = mock(User.class); + when(user.getShibId()).thenReturn("shibboleth id"); + when(shibUserService.getUser(incomingRequest)).thenReturn(user); + when(incomingRequest.getSession(false)).thenReturn(null); + when(restTemplate.getForEntity(any(String.class), any(Class.class))) + .thenThrow(new HttpClientErrorException(HttpStatus.NOT_FOUND)); + + filter.doFilter(incomingRequest, incomingResponse, chain); + + verify(chain, times(0)).doFilter(incomingRequest, incomingResponse); + verify(incomingResponse).setStatus(HttpStatus.FAILED_DEPENDENCY.value()); + verify(logger).logErrorMessage(AuthorizationFilter.class, null, + "User does not exist in User Portal: shibboleth id", incomingRequest); + } + + @SuppressWarnings("unchecked") + @Test + public void testDoFilter_userAuthReturnedAnotherErrorCode() throws Exception { + HttpServletRequest incomingRequest = mock(HttpServletRequest.class); + HttpServletResponse incomingResponse = mock(HttpServletResponse.class); + HttpSession session = mock(HttpSession.class); + when(incomingRequest.getSession(true)).thenReturn(session); + FilterChain chain = mock(FilterChain.class); + User user = mock(User.class); + when(user.getShibId()).thenReturn("shibboleth id"); + when(shibUserService.getUser(incomingRequest)).thenReturn(user); + when(incomingRequest.getSession(false)).thenReturn(null); + when(restTemplate.getForEntity(any(String.class), any(Class.class))) + .thenThrow(new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR)); + + filter.doFilter(incomingRequest, incomingResponse, chain); + + verify(chain, times(0)).doFilter(incomingRequest, incomingResponse); + verify(incomingResponse).setStatus(HttpStatus.FAILED_DEPENDENCY.value()); + verify(logger).logErrorMessage(AuthorizationFilter.class, null, + "Unable to get user information. User auth returned status code: 500", incomingRequest); } @Test From dec581c0868c914f5c0d7189277ba77acf7da6a9 Mon Sep 17 00:00:00 2001 From: Becky Reamy Date: Tue, 8 Oct 2019 15:50:08 -0400 Subject: [PATCH 09/26] KPMP-1317: Changed allowed group so we are not all locked out --- src/main/resources/application.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 70833040..7e745234 100755 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -12,7 +12,7 @@ state.service.endpoint=/v1/state user.auth.host=http://user-auth:8080 user.auth.endpoint=/v1/user/info -user.auth.allowed.groups=uw_rit_kpmp_role_developer +user.auth.allowed.groups=uw_rit_kpmp_role_data-visualization-center #user.auth.allowed.groups=uw_rit_kpmp_app_data-lake-uploader user.auth.kpmp.group=uw_rit_kpmp_role_kpmp-user From 9340918951a598e13332d0d292ecfb4c4dfb385a Mon Sep 17 00:00:00 2001 From: Becky Reamy Date: Thu, 10 Oct 2019 11:40:08 -0400 Subject: [PATCH 10/26] KPMP-1321: Handle user not found same as user found but does not have KPMP group --- src/main/java/org/kpmp/filters/AuthorizationFilter.java | 2 +- src/test/java/org/kpmp/filters/AuthorizationFilterTest.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/kpmp/filters/AuthorizationFilter.java b/src/main/java/org/kpmp/filters/AuthorizationFilter.java index 97663c19..a3074e77 100644 --- a/src/main/java/org/kpmp/filters/AuthorizationFilter.java +++ b/src/main/java/org/kpmp/filters/AuthorizationFilter.java @@ -117,7 +117,7 @@ public void doFilter(ServletRequest incomingRequest, ServletResponse incomingRes } catch (HttpClientErrorException e) { int statusCode = e.getRawStatusCode(); if (statusCode == HttpStatus.NOT_FOUND.value()) { - handleError(USER_DOES_NOT_EXIST + shibId, HttpStatus.FAILED_DEPENDENCY, request, response); + handleError(USER_DOES_NOT_EXIST + shibId, HttpStatus.NOT_FOUND, request, response); } else if (statusCode != HttpStatus.OK.value()) { handleError("Unable to get user information. User auth returned status code: " + statusCode, HttpStatus.FAILED_DEPENDENCY, request, response); diff --git a/src/test/java/org/kpmp/filters/AuthorizationFilterTest.java b/src/test/java/org/kpmp/filters/AuthorizationFilterTest.java index 8ec20b87..c29beaa3 100644 --- a/src/test/java/org/kpmp/filters/AuthorizationFilterTest.java +++ b/src/test/java/org/kpmp/filters/AuthorizationFilterTest.java @@ -238,7 +238,7 @@ public void testDoFilter_userAuthReturned404() throws Exception { filter.doFilter(incomingRequest, incomingResponse, chain); verify(chain, times(0)).doFilter(incomingRequest, incomingResponse); - verify(incomingResponse).setStatus(HttpStatus.FAILED_DEPENDENCY.value()); + verify(incomingResponse).setStatus(HttpStatus.NOT_FOUND.value()); verify(logger).logErrorMessage(AuthorizationFilter.class, null, "User does not exist in User Portal: shibboleth id", incomingRequest); } From 9a3b10e5532c0d42b3d8d2365d4b00d723659776 Mon Sep 17 00:00:00 2001 From: Becky Reamy Date: Fri, 11 Oct 2019 09:39:20 -0400 Subject: [PATCH 11/26] KPMP-1303: Clean up build.gradle --- build.gradle | 56 +------------------ .../externalProcess/CommandBuilderTest.java | 2 +- .../kpmp/packages/PackageFileHandlerTest.java | 10 ++-- .../kpmp/packages/PackageRepositoryTest.java | 55 ------------------ .../org/kpmp/packages/TestMongoConfig.java | 56 ------------------- .../org/kpmp/users/UserControllerTest.java | 12 ++-- .../org/kpmp/users/UserRepositoryTest.java | 33 ----------- .../java/org/kpmp/users/UserServiceTest.java | 2 +- 8 files changed, 17 insertions(+), 209 deletions(-) delete mode 100755 src/test/java/org/kpmp/packages/PackageRepositoryTest.java delete mode 100755 src/test/java/org/kpmp/packages/TestMongoConfig.java delete mode 100755 src/test/java/org/kpmp/users/UserRepositoryTest.java diff --git a/build.gradle b/build.gradle index f5b394da..31dbd673 100755 --- a/build.gradle +++ b/build.gradle @@ -15,82 +15,32 @@ apply plugin: 'io.spring.dependency-management' jar { baseName='orion-data' - version= '2.4' + version= '2.5' } repositories { mavenCentral() } -sourceSets { - integrationTest { - java { - compileClasspath += main.output + test.output - runtimeClasspath += main.output + test.output - srcDir file('src/integration-test/java') - } - resources.srcDir file('src/integration-test/resources') - } -} - -configurations { - integrationTestCompile.extendsFrom testCompile - integrationTestRuntime.extendsFrom testRuntime -} - -processResources { - filesMatching('application.properties') { - expand(project.properties) - } -} - sourceCompatibility = 1.8 targetCompatibility = 1.8 dependencies { compile 'org.springframework.boot:spring-boot-starter-web' compile 'commons-io:commons-io:2.6' - compile 'org.mockito:mockito-core' - compile 'org.junit.jupiter:junit-jupiter-engine:5.2.0' compile 'mysql:mysql-connector-java:6.0.5' - compile 'org.springframework.boot:spring-boot-starter-test' compile 'org.springframework:spring-test:5.0.5.RELEASE' compile 'org.springframework.data:spring-data-mongodb:2.0.8.RELEASE' compile 'org.springframework.boot:spring-boot-starter-data-mongodb' - testCompile 'de.flapdoodle.embed:de.flapdoodle.embed.mongo:2.1.1' - testCompile 'cz.jirutka.spring:embedmongo-spring:1.3.1' compile 'org.apache.commons:commons-compress:1.17' compile 'org.apache.commons:commons-text:1.7' compile 'com.google.api-client:google-api-client:1.23.0' compile 'com.google.oauth-client:google-oauth-client-jetty:1.23.0' compile 'com.google.apis:google-api-services-drive:v3-rev110-1.23.0' + compile 'org.springframework.boot:spring-boot-starter-test' + testCompile 'org.mockito:mockito-core' } -ext { - snippetsDir = file('build/generated-snippets') -} - -test { - outputs.dir snippetsDir -} - -tasks.withType(Test) { - testLogging { - exceptionFormat "full" - events "skipped", "passed", "failed" - showStandardStreams false - } - } - -task integrationTest(type: Test) { - testClassesDirs = sourceSets.integrationTest.output.classesDirs - classpath = sourceSets.integrationTest.runtimeClasspath - outputs.upToDateWhen { false } -} - -check.dependsOn integrationTest -integrationTest.mustRunAfter test - springBoot { mainClassName = "org.kpmp.Application" } diff --git a/src/test/java/org/kpmp/externalProcess/CommandBuilderTest.java b/src/test/java/org/kpmp/externalProcess/CommandBuilderTest.java index 004c5ead..2b7c6fca 100644 --- a/src/test/java/org/kpmp/externalProcess/CommandBuilderTest.java +++ b/src/test/java/org/kpmp/externalProcess/CommandBuilderTest.java @@ -1,6 +1,6 @@ package org.kpmp.externalProcess; -import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.when; import java.util.Arrays; diff --git a/src/test/java/org/kpmp/packages/PackageFileHandlerTest.java b/src/test/java/org/kpmp/packages/PackageFileHandlerTest.java index ded092b9..713043ac 100755 --- a/src/test/java/org/kpmp/packages/PackageFileHandlerTest.java +++ b/src/test/java/org/kpmp/packages/PackageFileHandlerTest.java @@ -2,7 +2,6 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; -import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -198,10 +197,13 @@ public void testSaveMultipartFile_fileExists() throws IOException { InputStream testInputStream2 = IOUtils.toInputStream("Here is the data in file 2", "UTF-8"); when(fileTwo.getInputStream()).thenReturn(testInputStream2); - fileHandler.saveMultipartFile(fileOne, "packageId", "filename.txt", false); + try { + fileHandler.saveMultipartFile(fileOne, "packageId", "filename.txt", false); + fileHandler.saveMultipartFile(fileOne, "packageId", "filename.txt", false); + fail("Should have thrown exception"); + } catch (FileAlreadyExistsException e) { - assertThrows(FileAlreadyExistsException.class, - () -> fileHandler.saveMultipartFile(fileTwo, "packageId", "filename.txt", false)); + } } diff --git a/src/test/java/org/kpmp/packages/PackageRepositoryTest.java b/src/test/java/org/kpmp/packages/PackageRepositoryTest.java deleted file mode 100755 index e5dfa419..00000000 --- a/src/test/java/org/kpmp/packages/PackageRepositoryTest.java +++ /dev/null @@ -1,55 +0,0 @@ -package org.kpmp.packages; - -import static org.junit.Assert.assertEquals; - -import java.util.List; - -import org.junit.After; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -/** - * - * Just a quick note...this test is really an integration test, and should live - * with the other integration tests. However, we are currently skipping running - * those tests on Travis since they need the mysql database, and we don't have - * one to connect to. - * - * Since we are switching to use mongo in the background and moving away from - * mysql, we will be able to configure those tests to use an embedded mongo as - * we have here. At that point, we will move this guy to live with his friends. - * - */ - -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = { TestMongoConfig.class }) -public class PackageRepositoryTest { - - @After - public void tearDown() throws Exception { - packageRepo.deleteAll(); - } - - @Autowired - private PackageRepository packageRepo; - - @Test - public void testFindAll() { - packageRepo.save(new Package()); - List packages = packageRepo.findAll(); - assertEquals(1, packages.size()); - } - - @Test - public void testFindByPackageId() { - Package uploadPackage = new Package(); - uploadPackage.setPackageId("1234"); - packageRepo.save(uploadPackage); - Package foundPackage = packageRepo.findByPackageId("1234"); - assertEquals(uploadPackage.getPackageId(), foundPackage.getPackageId()); - } - -} diff --git a/src/test/java/org/kpmp/packages/TestMongoConfig.java b/src/test/java/org/kpmp/packages/TestMongoConfig.java deleted file mode 100755 index 0191a759..00000000 --- a/src/test/java/org/kpmp/packages/TestMongoConfig.java +++ /dev/null @@ -1,56 +0,0 @@ -package org.kpmp.packages; - -import java.io.IOException; - -import org.kpmp.Application; -import org.kpmp.GenerateUploadReport; -import org.kpmp.RegenerateZipFiles; -import org.kpmp.WebConfig; -import org.kpmp.googleDrive.GoogleDriveService; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.ComponentScan.Filter; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.FilterType; -import org.springframework.data.mongodb.core.MongoTemplate; -import org.springframework.data.mongodb.repository.config.EnableMongoRepositories; -import org.springframework.web.client.RestTemplate; - -import com.mongodb.MongoClient; - -import cz.jirutka.spring.embedmongo.EmbeddedMongoFactoryBean; - -@Configuration -@ComponentScan(basePackages = { "org.kpmp.packages", "org.kpmp.users", "org.kpmp", - "org.kpmp.forms" }, excludeFilters = @Filter(type = FilterType.ASSIGNABLE_TYPE, classes = { - GoogleDriveService.class, PackageController.class, PackageService.class, CustomPackageRepository.class, Application.class, - GenerateUploadReport.class, RegenerateZipFiles.class, WebConfig.class })) -@EnableMongoRepositories(basePackages = { "org.kpmp.packages", "org.kpmp.users", "org.kpmp.forms", "org.kpmp" }) -public class TestMongoConfig { - - private static final String MONGO_DB_URL = "localhost"; - private static final String MONGO_DB_NAME = "embeded_db"; - - @Value("${embedded.mongodb.version:latest}") - private String mongoVersion; - - @Bean - public MongoTemplate mongoTemplate() throws IOException { - EmbeddedMongoFactoryBean mongo = new EmbeddedMongoFactoryBean(); - mongo.setBindIp(MONGO_DB_URL); - if (!mongoVersion.equals("latest")) { - mongo.setVersion(mongoVersion); - } - MongoClient mongoClient = mongo.getObject(); - - MongoTemplate mongoTemplate = new MongoTemplate(mongoClient, MONGO_DB_NAME); - return mongoTemplate; - } - - @Bean - public RestTemplate restTemplate() { - return new RestTemplate(); - } - -} diff --git a/src/test/java/org/kpmp/users/UserControllerTest.java b/src/test/java/org/kpmp/users/UserControllerTest.java index 5af846c3..abd6fde1 100755 --- a/src/test/java/org/kpmp/users/UserControllerTest.java +++ b/src/test/java/org/kpmp/users/UserControllerTest.java @@ -10,14 +10,14 @@ import javax.servlet.http.HttpServletRequest; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; import org.kpmp.logging.LoggingService; import org.mockito.Mock; import org.mockito.MockitoAnnotations; -class UserControllerTest { +public class UserControllerTest { @Mock private UserService userService; @@ -25,13 +25,13 @@ class UserControllerTest { @Mock private LoggingService logger; - @BeforeEach + @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); controller = new UserController(userService, logger); } - @AfterEach + @After public void tearDown() throws Exception { controller = null; } diff --git a/src/test/java/org/kpmp/users/UserRepositoryTest.java b/src/test/java/org/kpmp/users/UserRepositoryTest.java deleted file mode 100755 index 0dee0bb0..00000000 --- a/src/test/java/org/kpmp/users/UserRepositoryTest.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.kpmp.users; - -import static org.junit.Assert.assertEquals; - -import org.junit.After; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.kpmp.packages.TestMongoConfig; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = { TestMongoConfig.class }) -public class UserRepositoryTest { - - @Autowired - private UserRepository userRepository; - - @After - public void tearDown() throws Exception { - userRepository.deleteAll(); - } - - @Test - public void testFindByEmail() { - User testUser = new User(); - testUser.setEmail("jimminy@cricket.com"); - userRepository.save(testUser); - User user = userRepository.findByEmail("jimminy@cricket.com"); - assertEquals(testUser.getEmail(), user.getEmail()); - } -} diff --git a/src/test/java/org/kpmp/users/UserServiceTest.java b/src/test/java/org/kpmp/users/UserServiceTest.java index 234cb951..a40b7da6 100755 --- a/src/test/java/org/kpmp/users/UserServiceTest.java +++ b/src/test/java/org/kpmp/users/UserServiceTest.java @@ -1,6 +1,6 @@ package org.kpmp.users; -import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; From f9920fd10a9bd106e9437f1a9f0e1fe6e1cb5b30 Mon Sep 17 00:00:00 2001 From: Becky Reamy Date: Tue, 15 Oct 2019 14:12:57 -0400 Subject: [PATCH 12/26] KPMP-1321: Added active check --- src/main/java/org/kpmp/filters/AuthorizationFilter.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/kpmp/filters/AuthorizationFilter.java b/src/main/java/org/kpmp/filters/AuthorizationFilter.java index a3074e77..046eafd0 100644 --- a/src/main/java/org/kpmp/filters/AuthorizationFilter.java +++ b/src/main/java/org/kpmp/filters/AuthorizationFilter.java @@ -95,7 +95,7 @@ public void doFilter(ServletRequest incomingRequest, ServletResponse incomingRes JSONObject userJson = new JSONObject(userInfo); JSONArray userGroups = userJson.getJSONArray(GROUPS_KEY); - if (isAllowed(userGroups)) { + if (isAllowed(userGroups) && userJson.getBoolean("active")) { HttpSession session = request.getSession(true); session.setMaxInactiveInterval(SESSION_TIMEOUT_SECONDS); Cookie message = new Cookie(COOKIE_NAME, shibId); From 8ed730d1b45e590e0ad1d514f0c7ea2f9e615483 Mon Sep 17 00:00:00 2001 From: Becky Reamy Date: Wed, 16 Oct 2019 11:17:03 -0400 Subject: [PATCH 13/26] KPMP-1364: Remove shibId from metadata.json --- src/main/java/org/kpmp/packages/CustomPackageRepository.java | 1 + src/main/java/org/kpmp/packages/PackageKeys.java | 5 +++-- .../java/org/kpmp/packages/CustomPackageRepositoryTest.java | 2 +- src/test/java/org/kpmp/packages/PackageKeysTest.java | 3 ++- 4 files changed, 7 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/kpmp/packages/CustomPackageRepository.java b/src/main/java/org/kpmp/packages/CustomPackageRepository.java index c3ce9a7f..11571e9f 100755 --- a/src/main/java/org/kpmp/packages/CustomPackageRepository.java +++ b/src/main/java/org/kpmp/packages/CustomPackageRepository.java @@ -169,6 +169,7 @@ private JSONObject setUserInformation(String json) throws JSONException, JsonPro String submitterId = submitterIdObject.getString(PackageKeys.SUBMITTER_ID.getKey()); Optional userOptional = userRepository.findById(submitterId); jsonObject.remove(PackageKeys.SUBMITTER.getKey()); + jsonObject.remove(PackageKeys.SHIBID.getKey()); if (userOptional.isPresent()) { User user = userOptional.get(); String submitterJsonString = user.generateJSONForApp(); diff --git a/src/main/java/org/kpmp/packages/PackageKeys.java b/src/main/java/org/kpmp/packages/PackageKeys.java index 883c1803..6c6e7ea8 100644 --- a/src/main/java/org/kpmp/packages/PackageKeys.java +++ b/src/main/java/org/kpmp/packages/PackageKeys.java @@ -5,10 +5,11 @@ public enum PackageKeys { CLASS("_class"), CREATED_AT("createdAt"), DATA_GENERATORS("dataGenerators"), DESCRIPTION("description"), DISPLAY_NAME("displayName"), EMAIL("email"), FILES("files"), FILE_NAME("fileName"), FIRST_NAME("firstName"), ID("_id"), LAST_NAME("lastName"), PACKAGE_TYPE("packageType"), PROTOCOL("protocol"), - REGENERATE_ZIP("regenerateZip"), SIZE("size"), SUBJECT_ID("subjectId"), SUBMITTER("submitter"), + REGENERATE_ZIP("regenerateZip"), SHIBID("shibId"), SIZE("size"), SUBJECT_ID("subjectId"), SUBMITTER("submitter"), SUBMITTER_EMAIL("submitterEmail"), SUBMITTER_FIRST_NAME("submitterFirstName"), SUBMITTER_ID("$oid"), SUBMITTER_ID_OBJECT("$id"), SUBMITTER_LAST_NAME("submitterLastName"), - TIS_INTERNAL_EXPERIMENT_ID("tisInternalExperimentID"), TIS_NAME("tisName"), VERSION("version"), LARGE_FILES_CHECKED("largeFilesChecked"); + TIS_INTERNAL_EXPERIMENT_ID("tisInternalExperimentID"), TIS_NAME("tisName"), VERSION("version"), + LARGE_FILES_CHECKED("largeFilesChecked"); private String key; diff --git a/src/test/java/org/kpmp/packages/CustomPackageRepositoryTest.java b/src/test/java/org/kpmp/packages/CustomPackageRepositoryTest.java index 8f30217b..cbfe0ab9 100644 --- a/src/test/java/org/kpmp/packages/CustomPackageRepositoryTest.java +++ b/src/test/java/org/kpmp/packages/CustomPackageRepositoryTest.java @@ -203,7 +203,7 @@ public void testGetJSONByPackageId() throws Exception { JsonWriterSettings jsonWriterSettingsReturn = mock(JsonWriterSettings.class); when(jsonWriterSettings.getSettings()).thenReturn(jsonWriterSettingsReturn); when(document.toJson(any(JsonWriterSettings.class), any(DocumentCodec.class))).thenReturn( - "{ \"_id\": \"123\", \"key\": \"value with /\", \"submitter\": { $id: { $oid: '123' }}, \"regenerateZip\": true, \"createdAt\": { $date: 123567 } }"); + "{ \"_id\": \"123\", \"key\": \"value with /\", \"submitter\": { $id: { $oid: '123' }, \"shibId\": \"555\"}, \"regenerateZip\": true, \"createdAt\": { $date: 123567 } }"); when(result.first()).thenReturn(document); User user = mock(User.class); when(user.generateJSONForApp()).thenReturn("{user: information, exists: here}"); diff --git a/src/test/java/org/kpmp/packages/PackageKeysTest.java b/src/test/java/org/kpmp/packages/PackageKeysTest.java index f43216f6..b78ab292 100644 --- a/src/test/java/org/kpmp/packages/PackageKeysTest.java +++ b/src/test/java/org/kpmp/packages/PackageKeysTest.java @@ -8,7 +8,7 @@ public class PackageKeysTest { @Test public void testLength() throws Exception { - assertEquals(26, PackageKeys.values().length); + assertEquals(27, PackageKeys.values().length); } @Test @@ -27,6 +27,7 @@ public void testGetKey() { assertEquals("packageType", PackageKeys.PACKAGE_TYPE.getKey()); assertEquals("protocol", PackageKeys.PROTOCOL.getKey()); assertEquals("regenerateZip", PackageKeys.REGENERATE_ZIP.getKey()); + assertEquals("shibId", PackageKeys.SHIBID.getKey()); assertEquals("size", PackageKeys.SIZE.getKey()); assertEquals("subjectId", PackageKeys.SUBJECT_ID.getKey()); assertEquals("submitter", PackageKeys.SUBMITTER.getKey()); From 0dc9cbe383618403cf4ce489a7b83e9f513fb093 Mon Sep 17 00:00:00 2001 From: Becky Reamy Date: Wed, 16 Oct 2019 11:21:33 -0400 Subject: [PATCH 14/26] KPMP-1364: Fix failing test --- src/test/java/org/kpmp/filters/AuthorizationFilterTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/java/org/kpmp/filters/AuthorizationFilterTest.java b/src/test/java/org/kpmp/filters/AuthorizationFilterTest.java index c29beaa3..6085228c 100644 --- a/src/test/java/org/kpmp/filters/AuthorizationFilterTest.java +++ b/src/test/java/org/kpmp/filters/AuthorizationFilterTest.java @@ -159,7 +159,7 @@ public void testDoFilter_noSessionHasAllowedGroup() throws Exception { when(shibUserService.getUser(incomingRequest)).thenReturn(user); when(incomingRequest.getSession(false)).thenReturn(null); ResponseEntity response = mock(ResponseEntity.class); - when(response.getBody()).thenReturn("{groups: [ 'group1', 'another group']}"); + when(response.getBody()).thenReturn("{groups: [ 'group1', 'another group'], active: true}"); when(restTemplate.getForEntity(any(String.class), any(Class.class))).thenReturn(response); filter.doFilter(incomingRequest, incomingResponse, chain); From 913c6af68d7af767958febe79412be9ca1fbd54d Mon Sep 17 00:00:00 2001 From: Becky Reamy Date: Fri, 18 Oct 2019 12:27:07 -0400 Subject: [PATCH 15/26] KPMP-1364: Fix removal of shibId --- src/main/java/org/kpmp/packages/CustomPackageRepository.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/kpmp/packages/CustomPackageRepository.java b/src/main/java/org/kpmp/packages/CustomPackageRepository.java index 11571e9f..79b6b9d3 100755 --- a/src/main/java/org/kpmp/packages/CustomPackageRepository.java +++ b/src/main/java/org/kpmp/packages/CustomPackageRepository.java @@ -169,11 +169,11 @@ private JSONObject setUserInformation(String json) throws JSONException, JsonPro String submitterId = submitterIdObject.getString(PackageKeys.SUBMITTER_ID.getKey()); Optional userOptional = userRepository.findById(submitterId); jsonObject.remove(PackageKeys.SUBMITTER.getKey()); - jsonObject.remove(PackageKeys.SHIBID.getKey()); if (userOptional.isPresent()) { User user = userOptional.get(); String submitterJsonString = user.generateJSONForApp(); JSONObject submitterJson = new JSONObject(submitterJsonString); + submitterJson.remove(PackageKeys.SHIBID.getKey()); jsonObject.put(PackageKeys.SUBMITTER.getKey(), submitterJson); } return jsonObject; From 8963f4a23ae5b334e1adae12e07e49e000c8bd3d Mon Sep 17 00:00:00 2001 From: Becky Reamy Date: Mon, 28 Oct 2019 09:04:37 -0400 Subject: [PATCH 16/26] KPMP-1381: Change the allowed group the the real one we expect --- src/main/resources/application.properties | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 7e745234..b9c6f844 100755 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -12,8 +12,7 @@ state.service.endpoint=/v1/state user.auth.host=http://user-auth:8080 user.auth.endpoint=/v1/user/info -user.auth.allowed.groups=uw_rit_kpmp_role_data-visualization-center -#user.auth.allowed.groups=uw_rit_kpmp_app_data-lake-uploader +user.auth.allowed.groups=uw_rit_kpmp_app_data-lake-uploader user.auth.kpmp.group=uw_rit_kpmp_role_kpmp-user From b591f271bd9da446a3f28ece73faa4ea63bc5a46 Mon Sep 17 00:00:00 2001 From: Becky Reamy Date: Mon, 28 Oct 2019 09:40:05 -0400 Subject: [PATCH 17/26] KPMP-1134: Removed generate upload report as DMD covers this functionality --- .../java/org/kpmp/GenerateUploadReport.java | 132 ------------------ 1 file changed, 132 deletions(-) delete mode 100644 src/main/java/org/kpmp/GenerateUploadReport.java diff --git a/src/main/java/org/kpmp/GenerateUploadReport.java b/src/main/java/org/kpmp/GenerateUploadReport.java deleted file mode 100644 index f058fde9..00000000 --- a/src/main/java/org/kpmp/GenerateUploadReport.java +++ /dev/null @@ -1,132 +0,0 @@ -package org.kpmp; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.json.JSONArray; -import org.json.JSONObject; -import org.kpmp.packages.CustomPackageRepository; -import org.kpmp.packages.PackageKeys; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.CommandLineRunner; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.WebApplicationType; -import org.springframework.context.annotation.ComponentScan; - -@ComponentScan(basePackages = { "org.kpmp" }) -public class GenerateUploadReport implements CommandLineRunner { - - private CustomPackageRepository packageRepository; - - @Autowired - public GenerateUploadReport(CustomPackageRepository packageRepository) { - this.packageRepository = packageRepository; - } - - public static void main(String[] args) { - SpringApplication app = new SpringApplication(GenerateUploadReport.class); - app.setWebApplicationType(WebApplicationType.NONE); - app.run(args); - } - - @SuppressWarnings({ "rawtypes" }) - @Override - public void run(String... args) throws Exception { - List jsons = packageRepository.findAll(); - List packageDatas = new ArrayList(); - for (JSONObject packageInfo : jsons) { - Map packageData = new LinkedHashMap<>(); - JSONObject submitter = packageInfo.getJSONObject(PackageKeys.SUBMITTER.getKey()); - String submitterName = submitter.getString(PackageKeys.FIRST_NAME.getKey()) + " " - + submitter.getString(PackageKeys.LAST_NAME.getKey()); - packageData.put("Package ID", packageInfo.getString(PackageKeys.ID.getKey())); - packageData.put("In ERROR?", packageInfo.getString("inError")); - packageData.put("Submitter", submitterName); - packageData.put("TIS Name", packageInfo.getString(PackageKeys.TIS_NAME.getKey())); - packageData.put("Specimen ID", packageInfo.getString(PackageKeys.SUBJECT_ID.getKey())); - if (packageInfo.has(PackageKeys.TIS_INTERNAL_EXPERIMENT_ID.getKey())) { - packageData.put("TIS Internal Experiment ID", - packageInfo.getString(PackageKeys.TIS_INTERNAL_EXPERIMENT_ID.getKey())); - } else { - packageData.put("TIS Internal Experiment ID", "N/A"); - } - if (packageInfo.has(PackageKeys.DATA_GENERATORS.getKey())) { - packageData.put("Data Generator(s)", packageInfo.getString(PackageKeys.DATA_GENERATORS.getKey())); - } else { - packageData.put("Data Generator(s)", "N/A"); - } - packageData.put("Package Type", packageInfo.getString(PackageKeys.PACKAGE_TYPE.getKey())); - packageData.put("Protocol", packageInfo.getString(PackageKeys.PROTOCOL.getKey())); - String description = packageInfo.getString(PackageKeys.DESCRIPTION.getKey()); - description = description.replace("\n", " "); - description = description.replace("\r", " "); - description = description.replace("\r\n", " "); - packageData.put("Dataset Description", description); - packageData.put("Created At", packageInfo.getString(PackageKeys.CREATED_AT.getKey())); - JSONArray files = packageInfo.getJSONArray(PackageKeys.FILES.getKey()); - StringBuilder fileNames = new StringBuilder(); - for (int i = 0; i < files.length(); i++) { - JSONObject file = files.getJSONObject(i); - if (fileNames.length() != 0) { - fileNames.append(", "); - } else { - fileNames.append("\""); - } - fileNames.append(file.get(PackageKeys.FILE_NAME.getKey())); - } - fileNames.append("\""); - packageData.put("Files", fileNames.toString()); - packageDatas.add(packageData); - } - - writeToCSV(packageDatas); - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - private void writeToCSV(List packageDatas) throws FileNotFoundException, IOException { - FileOutputStream report = new FileOutputStream(new File("report.tsv")); - if (packageDatas.size() == 0) { - System.err.println("**** Retrieved 0 packages. NO REPORT GENERATED! ****"); - System.exit(0); - } - - Map firstPackage = packageDatas.get(0); - Set headers = firstPackage.keySet(); - - int count = 0; - for (String header : headers) { - if (count > 0) { - report.write("\t".getBytes()); - } - report.write(header.getBytes()); - count++; - } - report.write(System.lineSeparator().getBytes()); - - count = 0; - for (Map packageData : packageDatas) { - for (String key : headers) { - if (count > 0) { - report.write("\t".getBytes()); - } - if (packageData.get(key) == null) { - report.write("N/A".getBytes()); - } else { - report.write(packageData.get(key).toString().getBytes()); - } - count++; - } - report.write(System.lineSeparator().getBytes()); - count = 0; - } - report.close(); - } - -} From 2bbf612033384dc05dc6c3a1e2e1cc865b28a956 Mon Sep 17 00:00:00 2001 From: Becky Reamy Date: Mon, 28 Oct 2019 09:47:58 -0400 Subject: [PATCH 18/26] KPMP-1134: Trying to reduce/remove cyclic dependencies among packages --- src/main/java/org/kpmp/packages/CustomPackageRepository.java | 1 - src/main/java/org/kpmp/packages/PackageController.java | 1 - .../java/org/kpmp/{ => packages}/UniversalIdGenerator.java | 4 ++-- .../java/org/kpmp/packages/CustomPackageRepositoryTest.java | 1 - src/test/java/org/kpmp/packages/PackageControllerTest.java | 1 - .../org/kpmp/{ => packages}/UniversalIdGeneratorTest.java | 3 ++- 6 files changed, 4 insertions(+), 7 deletions(-) rename src/main/java/org/kpmp/{ => packages}/UniversalIdGenerator.java (77%) rename src/test/java/org/kpmp/{ => packages}/UniversalIdGeneratorTest.java (89%) diff --git a/src/main/java/org/kpmp/packages/CustomPackageRepository.java b/src/main/java/org/kpmp/packages/CustomPackageRepository.java index 79b6b9d3..a73a3430 100755 --- a/src/main/java/org/kpmp/packages/CustomPackageRepository.java +++ b/src/main/java/org/kpmp/packages/CustomPackageRepository.java @@ -17,7 +17,6 @@ import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; -import org.kpmp.UniversalIdGenerator; import org.kpmp.logging.LoggingService; import org.kpmp.users.User; import org.kpmp.users.UserRepository; diff --git a/src/main/java/org/kpmp/packages/PackageController.java b/src/main/java/org/kpmp/packages/PackageController.java index 50982e12..5487edd3 100755 --- a/src/main/java/org/kpmp/packages/PackageController.java +++ b/src/main/java/org/kpmp/packages/PackageController.java @@ -9,7 +9,6 @@ import org.json.JSONException; import org.json.JSONObject; -import org.kpmp.UniversalIdGenerator; import org.kpmp.googleDrive.GoogleDriveService; import org.kpmp.logging.LoggingService; import org.kpmp.shibboleth.ShibbolethUserService; diff --git a/src/main/java/org/kpmp/UniversalIdGenerator.java b/src/main/java/org/kpmp/packages/UniversalIdGenerator.java similarity index 77% rename from src/main/java/org/kpmp/UniversalIdGenerator.java rename to src/main/java/org/kpmp/packages/UniversalIdGenerator.java index 7abe7872..ce1b3e94 100644 --- a/src/main/java/org/kpmp/UniversalIdGenerator.java +++ b/src/main/java/org/kpmp/packages/UniversalIdGenerator.java @@ -1,11 +1,11 @@ -package org.kpmp; +package org.kpmp.packages; import java.util.UUID; import org.springframework.stereotype.Component; @Component -public class UniversalIdGenerator { +class UniversalIdGenerator { public String generateUniversalId() { UUID uuid = UUID.randomUUID(); diff --git a/src/test/java/org/kpmp/packages/CustomPackageRepositoryTest.java b/src/test/java/org/kpmp/packages/CustomPackageRepositoryTest.java index cbfe0ab9..f9aafa53 100644 --- a/src/test/java/org/kpmp/packages/CustomPackageRepositoryTest.java +++ b/src/test/java/org/kpmp/packages/CustomPackageRepositoryTest.java @@ -20,7 +20,6 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; -import org.kpmp.UniversalIdGenerator; import org.kpmp.logging.LoggingService; import org.kpmp.users.User; import org.kpmp.users.UserRepository; diff --git a/src/test/java/org/kpmp/packages/PackageControllerTest.java b/src/test/java/org/kpmp/packages/PackageControllerTest.java index 81df7104..68d784d7 100755 --- a/src/test/java/org/kpmp/packages/PackageControllerTest.java +++ b/src/test/java/org/kpmp/packages/PackageControllerTest.java @@ -22,7 +22,6 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; -import org.kpmp.UniversalIdGenerator; import org.kpmp.googleDrive.GoogleDriveService; import org.kpmp.logging.LoggingService; import org.kpmp.shibboleth.ShibbolethUserService; diff --git a/src/test/java/org/kpmp/UniversalIdGeneratorTest.java b/src/test/java/org/kpmp/packages/UniversalIdGeneratorTest.java similarity index 89% rename from src/test/java/org/kpmp/UniversalIdGeneratorTest.java rename to src/test/java/org/kpmp/packages/UniversalIdGeneratorTest.java index 2e693a99..0277203d 100644 --- a/src/test/java/org/kpmp/UniversalIdGeneratorTest.java +++ b/src/test/java/org/kpmp/packages/UniversalIdGeneratorTest.java @@ -1,4 +1,4 @@ -package org.kpmp; +package org.kpmp.packages; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; @@ -8,6 +8,7 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; +import org.kpmp.packages.UniversalIdGenerator; public class UniversalIdGeneratorTest { From 0a4ed7c8df81dc90ede150c15da2de44d401fa2a Mon Sep 17 00:00:00 2001 From: Becky Reamy Date: Mon, 28 Oct 2019 14:23:25 -0400 Subject: [PATCH 19/26] KPMP-1134: Initialize states --- .gitignore | 1 + scripts/2.5/initializeStates.js | 79 +++++++++++ scripts/2.5/package-lock.json | 244 ++++++++++++++++++++++++++++++++ scripts/2.5/package.json | 6 + scripts/package-lock.json | 67 +++++++++ 5 files changed, 397 insertions(+) create mode 100755 scripts/2.5/initializeStates.js create mode 100644 scripts/2.5/package-lock.json create mode 100644 scripts/2.5/package.json create mode 100644 scripts/package-lock.json diff --git a/.gitignore b/.gitignore index b4b293ca..ebedd6ac 100755 --- a/.gitignore +++ b/.gitignore @@ -16,3 +16,4 @@ out .classpath **/credentials.json tokens +**/node_modules diff --git a/scripts/2.5/initializeStates.js b/scripts/2.5/initializeStates.js new file mode 100755 index 00000000..119069b9 --- /dev/null +++ b/scripts/2.5/initializeStates.js @@ -0,0 +1,79 @@ +const MongoClient = require('mongodb').MongoClient; +const assert = require('assert'); + +const url = 'mongodb://localhost:27017'; +const dbName = 'dataLake'; +var stateMap = new Map(); +var missingStates = new Array(); + +const createStateMap = function(db, callback) { + var stateCollection = db.collection("state"); + + stateCollection.find({}).toArray(function(err, docs) { + assert.equal(null, err); + docs.forEach(function(doc) { + var packageId = doc.packageId; + var docList = stateMap.get(packageId); + if (docList === undefined) { + docList= []; + } + docList.push(doc); + stateMap.set(packageId, docList); + }); + callback(stateMap); + }); +} + +const determineMissingStates= function(stateMap, db, callback) { + var packageCollection = db.collection("packages"); + + + packageCollection.find({}).toArray(function(err, docs) { + assert.equal(null, err); + docs.forEach(function(doc) { + let packageId = doc._id; + if (doc.largeFilesChecked === true) { + if (!stateMap.has(packageId)) { + console.log("********************"); + console.log("Large file upload is mising the corresponding METADATA_RECEIVED state: " + doc._id); + console.log("Please address manually"); + console.log("********************"); + } + } else if (doc.inError === true) { + if (!stateMap.has(packageId)) { + var state = { 'packageId' : packageId, 'state': 'UPLOAD_FAILED', codicil: 'backfilling errors', stateChangeDate: doc.createdAt}; + missingStates.push(state); + } + } else if (!stateMap.has(packageId)) { + var state = { 'packageId' : packageId, 'state': 'UPLOAD_SUCCEEDED', codicil: '', stateChangeDate: doc.createdAt}; + missingStates.push(state); + } + }); + callback(); + }); + +} + +const insertStates = function(db, callback) { + var stateCollection = db.collection("state"); + stateCollection.insertMany(missingStates); + callback(); +} + +MongoClient.connect(url, {'forceServerObjectId' : true}, function(err, client) { + + assert.equal(null, err); + console.log("successfully connected to server"); + + const db = client.db(dbName); + + createStateMap(db, function() { + determineMissingStates(stateMap, db, function() { + insertStates(db, function() { + client.close(); + }); + }); + }); + +}); + diff --git a/scripts/2.5/package-lock.json b/scripts/2.5/package-lock.json new file mode 100644 index 00000000..a56e7683 --- /dev/null +++ b/scripts/2.5/package-lock.json @@ -0,0 +1,244 @@ +{ + "requires": true, + "lockfileVersion": 1, + "dependencies": { + "assert": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/assert/-/assert-2.0.0.tgz", + "integrity": "sha512-se5Cd+js9dXJnu6Ag2JFc00t+HmHOen+8Q+L7O9zI0PqQXr20uk2J0XQqMxZEeo5U50o8Nvmmx7dZrl+Ufr35A==", + "requires": { + "es6-object-assign": "^1.1.0", + "is-nan": "^1.2.1", + "object-is": "^1.0.1", + "util": "^0.12.0" + } + }, + "bson": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/bson/-/bson-1.1.1.tgz", + "integrity": "sha512-jCGVYLoYMHDkOsbwJZBCqwMHyH4c+wzgI9hG7Z6SZJRXWr+x58pdIbm2i9a/jFGCkRJqRUr8eoI7lDWa0hTkxg==" + }, + "define-properties": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.1.3.tgz", + "integrity": "sha512-3MqfYKj2lLzdMSf8ZIZE/V+Zuy+BgD6f164e8K2w7dgnpKArBDerGYpM46IYYcjnkdPNMjPk9A6VFB8+3SKlXQ==", + "requires": { + "object-keys": "^1.0.12" + } + }, + "es-abstract": { + "version": "1.16.0", + "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.16.0.tgz", + "integrity": "sha512-xdQnfykZ9JMEiasTAJZJdMWCQ1Vm00NBw79/AWi7ELfZuuPCSOMDZbT9mkOfSctVtfhb+sAAzrm+j//GjjLHLg==", + "requires": { + "es-to-primitive": "^1.2.0", + "function-bind": "^1.1.1", + "has": "^1.0.3", + "has-symbols": "^1.0.0", + "is-callable": "^1.1.4", + "is-regex": "^1.0.4", + "object-inspect": "^1.6.0", + "object-keys": "^1.1.1", + "string.prototype.trimleft": "^2.1.0", + "string.prototype.trimright": "^2.1.0" + } + }, + "es-to-primitive": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/es-to-primitive/-/es-to-primitive-1.2.0.tgz", + "integrity": "sha512-qZryBOJjV//LaxLTV6UC//WewneB3LcXOL9NP++ozKVXsIIIpm/2c13UDiD9Jp2eThsecw9m3jPqDwTyobcdbg==", + "requires": { + "is-callable": "^1.1.4", + "is-date-object": "^1.0.1", + "is-symbol": "^1.0.2" + } + }, + "es6-object-assign": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/es6-object-assign/-/es6-object-assign-1.1.0.tgz", + "integrity": "sha1-wsNYJlYkfDnqEHyx5mUrb58kUjw=" + }, + "function-bind": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz", + "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==" + }, + "has": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz", + "integrity": "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==", + "requires": { + "function-bind": "^1.1.1" + } + }, + "has-symbols": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.0.tgz", + "integrity": "sha1-uhqPGvKg/DllD1yFA2dwQSIGO0Q=" + }, + "inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" + }, + "is-arguments": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/is-arguments/-/is-arguments-1.0.4.tgz", + "integrity": "sha512-xPh0Rmt8NE65sNzvyUmWgI1tz3mKq74lGA0mL8LYZcoIzKOzDh6HmrYm3d18k60nHerC8A9Km8kYu87zfSFnLA==" + }, + "is-callable": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.1.4.tgz", + "integrity": "sha512-r5p9sxJjYnArLjObpjA4xu5EKI3CuKHkJXMhT7kwbpUyIFD1n5PMAsoPvWnvtZiNz7LjkYDRZhd7FlI0eMijEA==" + }, + "is-date-object": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-date-object/-/is-date-object-1.0.1.tgz", + "integrity": "sha1-mqIOtq7rv/d/vTPnTKAbM1gdOhY=" + }, + "is-generator-function": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/is-generator-function/-/is-generator-function-1.0.7.tgz", + "integrity": "sha512-YZc5EwyO4f2kWCax7oegfuSr9mFz1ZvieNYBEjmukLxgXfBUbxAWGVF7GZf0zidYtoBl3WvC07YK0wT76a+Rtw==" + }, + "is-nan": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/is-nan/-/is-nan-1.2.1.tgz", + "integrity": "sha1-n69ltvttskt/XAYoR16nH5iEAeI=", + "requires": { + "define-properties": "^1.1.1" + } + }, + "is-regex": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.0.4.tgz", + "integrity": "sha1-VRdIm1RwkbCTDglWVM7SXul+lJE=", + "requires": { + "has": "^1.0.1" + } + }, + "is-symbol": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-symbol/-/is-symbol-1.0.2.tgz", + "integrity": "sha512-HS8bZ9ox60yCJLH9snBpIwv9pYUAkcuLhSA1oero1UB5y9aiQpRA8y2ex945AOtCZL1lJDeIk3G5LthswI46Lw==", + "requires": { + "has-symbols": "^1.0.0" + } + }, + "memory-pager": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/memory-pager/-/memory-pager-1.5.0.tgz", + "integrity": "sha512-ZS4Bp4r/Zoeq6+NLJpP+0Zzm0pR8whtGPf1XExKLJBAczGMnSi3It14OiNCStjQjM6NU1okjQGSxgEZN8eBYKg==", + "optional": true + }, + "mongodb": { + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/mongodb/-/mongodb-3.3.3.tgz", + "integrity": "sha512-MdRnoOjstmnrKJsK8PY0PjP6fyF/SBS4R8coxmhsfEU7tQ46/J6j+aSHF2n4c2/H8B+Hc/Klbfp8vggZfI0mmA==", + "requires": { + "bson": "^1.1.1", + "require_optional": "^1.0.1", + "safe-buffer": "^5.1.2", + "saslprep": "^1.0.0" + } + }, + "object-inspect": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.6.0.tgz", + "integrity": "sha512-GJzfBZ6DgDAmnuaM3104jR4s1Myxr3Y3zfIyN4z3UdqN69oSRacNK8UhnobDdC+7J2AHCjGwxQubNJfE70SXXQ==" + }, + "object-is": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/object-is/-/object-is-1.0.1.tgz", + "integrity": "sha1-CqYOyZiaCz7Xlc9NBvYs8a1lObY=" + }, + "object-keys": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz", + "integrity": "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==" + }, + "object.entries": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/object.entries/-/object.entries-1.1.0.tgz", + "integrity": "sha512-l+H6EQ8qzGRxbkHOd5I/aHRhHDKoQXQ8g0BYt4uSweQU1/J6dZUOyWh9a2Vky35YCKjzmgxOzta2hH6kf9HuXA==", + "requires": { + "define-properties": "^1.1.3", + "es-abstract": "^1.12.0", + "function-bind": "^1.1.1", + "has": "^1.0.3" + } + }, + "require_optional": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/require_optional/-/require_optional-1.0.1.tgz", + "integrity": "sha512-qhM/y57enGWHAe3v/NcwML6a3/vfESLe/sGM2dII+gEO0BpKRUkWZow/tyloNqJyN6kXSl3RyyM8Ll5D/sJP8g==", + "requires": { + "resolve-from": "^2.0.0", + "semver": "^5.1.0" + } + }, + "resolve-from": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-2.0.0.tgz", + "integrity": "sha1-lICrIOlP+h2egKgEx+oUdhGWa1c=" + }, + "safe-buffer": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.0.tgz", + "integrity": "sha512-fZEwUGbVl7kouZs1jCdMLdt95hdIv0ZeHg6L7qPeciMZhZ+/gdesW4wgTARkrFWEpspjEATAzUGPG8N2jJiwbg==" + }, + "saslprep": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/saslprep/-/saslprep-1.0.3.tgz", + "integrity": "sha512-/MY/PEMbk2SuY5sScONwhUDsV2p77Znkb/q3nSVstq/yQzYJOH/Azh29p9oJLsl3LnQwSvZDKagDGBsBwSooag==", + "optional": true, + "requires": { + "sparse-bitfield": "^3.0.3" + } + }, + "semver": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz", + "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==" + }, + "sparse-bitfield": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/sparse-bitfield/-/sparse-bitfield-3.0.3.tgz", + "integrity": "sha1-/0rm5oZWBWuks+eSqzM004JzyhE=", + "optional": true, + "requires": { + "memory-pager": "^1.0.2" + } + }, + "string.prototype.trimleft": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/string.prototype.trimleft/-/string.prototype.trimleft-2.1.0.tgz", + "integrity": "sha512-FJ6b7EgdKxxbDxc79cOlok6Afd++TTs5szo+zJTUyow3ycrRfJVE2pq3vcN53XexvKZu/DJMDfeI/qMiZTrjTw==", + "requires": { + "define-properties": "^1.1.3", + "function-bind": "^1.1.1" + } + }, + "string.prototype.trimright": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/string.prototype.trimright/-/string.prototype.trimright-2.1.0.tgz", + "integrity": "sha512-fXZTSV55dNBwv16uw+hh5jkghxSnc5oHq+5K/gXgizHwAvMetdAJlHqqoFC1FSDVPYWLkAKl2cxpUT41sV7nSg==", + "requires": { + "define-properties": "^1.1.3", + "function-bind": "^1.1.1" + } + }, + "util": { + "version": "0.12.1", + "resolved": "https://registry.npmjs.org/util/-/util-0.12.1.tgz", + "integrity": "sha512-MREAtYOp+GTt9/+kwf00IYoHZyjM8VU4aVrkzUlejyqaIjd2GztVl5V9hGXKlvBKE3gENn/FMfHE5v6hElXGcQ==", + "requires": { + "inherits": "^2.0.3", + "is-arguments": "^1.0.4", + "is-generator-function": "^1.0.7", + "object.entries": "^1.1.0", + "safe-buffer": "^5.1.2" + } + } + } +} diff --git a/scripts/2.5/package.json b/scripts/2.5/package.json new file mode 100644 index 00000000..2532a25f --- /dev/null +++ b/scripts/2.5/package.json @@ -0,0 +1,6 @@ +{ + "dependencies": { + "assert": "^2.0.0", + "mongodb": "^3.3.3" + } +} diff --git a/scripts/package-lock.json b/scripts/package-lock.json new file mode 100644 index 00000000..34789b93 --- /dev/null +++ b/scripts/package-lock.json @@ -0,0 +1,67 @@ +{ + "requires": true, + "lockfileVersion": 1, + "dependencies": { + "bson": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/bson/-/bson-1.1.1.tgz", + "integrity": "sha512-jCGVYLoYMHDkOsbwJZBCqwMHyH4c+wzgI9hG7Z6SZJRXWr+x58pdIbm2i9a/jFGCkRJqRUr8eoI7lDWa0hTkxg==" + }, + "memory-pager": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/memory-pager/-/memory-pager-1.5.0.tgz", + "integrity": "sha512-ZS4Bp4r/Zoeq6+NLJpP+0Zzm0pR8whtGPf1XExKLJBAczGMnSi3It14OiNCStjQjM6NU1okjQGSxgEZN8eBYKg==" + }, + "mongodb": { + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/mongodb/-/mongodb-3.3.3.tgz", + "integrity": "sha512-MdRnoOjstmnrKJsK8PY0PjP6fyF/SBS4R8coxmhsfEU7tQ46/J6j+aSHF2n4c2/H8B+Hc/Klbfp8vggZfI0mmA==", + "requires": { + "bson": "^1.1.1", + "require_optional": "^1.0.1", + "safe-buffer": "^5.1.2", + "saslprep": "^1.0.0" + } + }, + "require_optional": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/require_optional/-/require_optional-1.0.1.tgz", + "integrity": "sha512-qhM/y57enGWHAe3v/NcwML6a3/vfESLe/sGM2dII+gEO0BpKRUkWZow/tyloNqJyN6kXSl3RyyM8Ll5D/sJP8g==", + "requires": { + "resolve-from": "^2.0.0", + "semver": "^5.1.0" + } + }, + "resolve-from": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-2.0.0.tgz", + "integrity": "sha1-lICrIOlP+h2egKgEx+oUdhGWa1c=" + }, + "safe-buffer": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.0.tgz", + "integrity": "sha512-fZEwUGbVl7kouZs1jCdMLdt95hdIv0ZeHg6L7qPeciMZhZ+/gdesW4wgTARkrFWEpspjEATAzUGPG8N2jJiwbg==" + }, + "saslprep": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/saslprep/-/saslprep-1.0.3.tgz", + "integrity": "sha512-/MY/PEMbk2SuY5sScONwhUDsV2p77Znkb/q3nSVstq/yQzYJOH/Azh29p9oJLsl3LnQwSvZDKagDGBsBwSooag==", + "requires": { + "sparse-bitfield": "^3.0.3" + } + }, + "semver": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz", + "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==" + }, + "sparse-bitfield": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/sparse-bitfield/-/sparse-bitfield-3.0.3.tgz", + "integrity": "sha1-/0rm5oZWBWuks+eSqzM004JzyhE=", + "requires": { + "memory-pager": "^1.0.2" + } + } + } +} From 56f9ad36eb2d0918e38d3fc3b28e1892906cceba Mon Sep 17 00:00:00 2001 From: Becky Reamy Date: Mon, 28 Oct 2019 15:22:10 -0400 Subject: [PATCH 20/26] KPMP-1270: Refactoring to remove cycles --- scripts/2.5/node_modules/.bin/semver | 1 + scripts/2.5/node_modules/assert/CHANGELOG.md | 14 + scripts/2.5/node_modules/assert/LICENSE | 18 + scripts/2.5/node_modules/assert/README.md | 73 + scripts/2.5/node_modules/assert/package.json | 77 + scripts/2.5/node_modules/bson/HISTORY.md | 268 + scripts/2.5/node_modules/bson/LICENSE.md | 201 + scripts/2.5/node_modules/bson/README.md | 170 + scripts/2.5/node_modules/bson/bower.json | 25 + .../node_modules/bson/browser_build/bson.js | 17769 ++++++++++++++++ .../bson/browser_build/package.json | 8 + scripts/2.5/node_modules/bson/index.js | 46 + .../2.5/node_modules/bson/lib/bson/binary.js | 384 + .../2.5/node_modules/bson/lib/bson/bson.js | 386 + .../2.5/node_modules/bson/lib/bson/code.js | 24 + .../2.5/node_modules/bson/lib/bson/db_ref.js | 32 + .../node_modules/bson/lib/bson/decimal128.js | 820 + .../2.5/node_modules/bson/lib/bson/double.js | 33 + .../bson/lib/bson/float_parser.js | 124 + .../2.5/node_modules/bson/lib/bson/int_32.js | 33 + .../2.5/node_modules/bson/lib/bson/long.js | 851 + scripts/2.5/node_modules/bson/lib/bson/map.js | 128 + .../2.5/node_modules/bson/lib/bson/max_key.js | 14 + .../2.5/node_modules/bson/lib/bson/min_key.js | 14 + .../node_modules/bson/lib/bson/objectid.js | 389 + .../bson/lib/bson/parser/calculate_size.js | 255 + .../bson/lib/bson/parser/deserializer.js | 782 + .../bson/lib/bson/parser/serializer.js | 1182 + .../bson/lib/bson/parser/utils.js | 28 + .../2.5/node_modules/bson/lib/bson/regexp.js | 33 + .../2.5/node_modules/bson/lib/bson/symbol.js | 50 + .../node_modules/bson/lib/bson/timestamp.js | 854 + scripts/2.5/node_modules/bson/package.json | 87 + .../define-properties/.editorconfig | 13 + .../node_modules/define-properties/.eslintrc | 12 + .../node_modules/define-properties/.jscs.json | 175 + .../define-properties/.travis.yml | 233 + .../define-properties/CHANGELOG.md | 44 + .../node_modules/define-properties/LICENSE | 21 + .../node_modules/define-properties/README.md | 86 + .../node_modules/define-properties/index.js | 58 + .../define-properties/package.json | 99 + .../define-properties/test/index.js | 125 + .../node_modules/es-abstract/.editorconfig | 13 + .../2.5/node_modules/es-abstract/.eslintrc | 70 + .../es-abstract/.github/FUNDING.yml | 12 + scripts/2.5/node_modules/es-abstract/.nycrc | 14 + .../2.5/node_modules/es-abstract/.travis.yml | 333 + .../2.5/node_modules/es-abstract/CHANGELOG.md | 264 + .../node_modules/es-abstract/GetIntrinsic.js | 189 + scripts/2.5/node_modules/es-abstract/LICENSE | 21 + scripts/2.5/node_modules/es-abstract/Makefile | 61 + .../2.5/node_modules/es-abstract/README.md | 48 + .../2.5/node_modules/es-abstract/es2015.js | 1464 ++ .../2.5/node_modules/es-abstract/es2016.js | 98 + .../2.5/node_modules/es-abstract/es2017.js | 71 + .../2.5/node_modules/es-abstract/es2018.js | 289 + .../2.5/node_modules/es-abstract/es2019.js | 111 + scripts/2.5/node_modules/es-abstract/es5.js | 544 + scripts/2.5/node_modules/es-abstract/es6.js | 3 + scripts/2.5/node_modules/es-abstract/es7.js | 3 + .../es-abstract/helpers/assertRecord.js | 48 + .../es-abstract/helpers/assign.js | 21 + .../es-abstract/helpers/callBind.js | 17 + .../es-abstract/helpers/callBound.js | 15 + .../node_modules/es-abstract/helpers/every.js | 10 + .../es-abstract/helpers/forEach.js | 7 + .../es-abstract/helpers/getInferredName.js | 10 + .../es-abstract/helpers/getIteratorMethod.js | 46 + .../es-abstract/helpers/getProto.js | 15 + .../helpers/getSymbolDescription.js | 30 + .../es-abstract/helpers/isFinite.js | 5 + .../node_modules/es-abstract/helpers/isNaN.js | 5 + .../es-abstract/helpers/isPrefixOf.js | 13 + .../es-abstract/helpers/isPrimitive.js | 5 + .../helpers/isPropertyDescriptor.js | 31 + .../helpers/isSamePropertyDescriptor.js | 20 + .../es-abstract/helpers/maxSafeInteger.js | 8 + .../node_modules/es-abstract/helpers/mod.js | 6 + .../es-abstract/helpers/regexTester.js | 11 + .../es-abstract/helpers/setProto.js | 16 + .../node_modules/es-abstract/helpers/sign.js | 5 + scripts/2.5/node_modules/es-abstract/index.js | 26 + .../es-abstract/operations/.eslintrc | 5 + .../2.5/node_modules/es-abstract/package.json | 130 + .../node_modules/es-abstract/test/.eslintrc | 13 + .../es-abstract/test/GetIntrinsic.js | 48 + .../node_modules/es-abstract/test/diffOps.js | 26 + .../node_modules/es-abstract/test/es2015.js | 9 + .../node_modules/es-abstract/test/es2016.js | 9 + .../node_modules/es-abstract/test/es2017.js | 9 + .../node_modules/es-abstract/test/es2018.js | 9 + .../node_modules/es-abstract/test/es2019.js | 9 + .../2.5/node_modules/es-abstract/test/es5.js | 782 + .../2.5/node_modules/es-abstract/test/es6.js | 18 + .../2.5/node_modules/es-abstract/test/es7.js | 18 + .../es-abstract/test/helpers/assertRecord.js | 60 + .../test/helpers/getSymbolDescription.js | 50 + .../es-abstract/test/helpers/values.js | 121 + .../node_modules/es-abstract/test/index.js | 30 + .../node_modules/es-abstract/test/tests.js | 4075 ++++ .../es-to-primitive/.editorconfig | 20 + .../node_modules/es-to-primitive/.eslintrc | 14 + .../node_modules/es-to-primitive/.jscs.json | 176 + .../node_modules/es-to-primitive/.travis.yml | 243 + .../node_modules/es-to-primitive/CHANGELOG.md | 38 + .../2.5/node_modules/es-to-primitive/LICENSE | 22 + .../2.5/node_modules/es-to-primitive/Makefile | 61 + .../node_modules/es-to-primitive/README.md | 51 + .../node_modules/es-to-primitive/es2015.js | 75 + .../2.5/node_modules/es-to-primitive/es5.js | 45 + .../2.5/node_modules/es-to-primitive/es6.js | 3 + .../es-to-primitive/helpers/isPrimitive.js | 3 + .../2.5/node_modules/es-to-primitive/index.js | 17 + .../node_modules/es-to-primitive/package.json | 113 + .../es-to-primitive/test/.eslintrc | 9 + .../es-to-primitive/test/es2015.js | 151 + .../node_modules/es-to-primitive/test/es5.js | 94 + .../node_modules/es-to-primitive/test/es6.js | 151 + .../es-to-primitive/test/index.js | 20 + .../node_modules/es6-object-assign/LICENSE | 22 + .../node_modules/es6-object-assign/README.md | 96 + .../node_modules/es6-object-assign/auto.js | 3 + .../dist/object-assign-auto.js | 54 + .../dist/object-assign-auto.min.js | 1 + .../es6-object-assign/dist/object-assign.js | 50 + .../dist/object-assign.min.js | 1 + .../node_modules/es6-object-assign/index.js | 46 + .../es6-object-assign/package.json | 72 + .../node_modules/function-bind/.editorconfig | 20 + .../2.5/node_modules/function-bind/.eslintrc | 15 + .../2.5/node_modules/function-bind/.jscs.json | 176 + .../2.5/node_modules/function-bind/.npmignore | 22 + .../node_modules/function-bind/.travis.yml | 168 + .../2.5/node_modules/function-bind/LICENSE | 20 + .../2.5/node_modules/function-bind/README.md | 48 + .../function-bind/implementation.js | 52 + .../2.5/node_modules/function-bind/index.js | 5 + .../node_modules/function-bind/package.json | 98 + .../node_modules/function-bind/test/.eslintrc | 9 + .../node_modules/function-bind/test/index.js | 252 + .../2.5/node_modules/has-symbols/.eslintrc | 10 + .../2.5/node_modules/has-symbols/.npmignore | 37 + .../2.5/node_modules/has-symbols/.travis.yml | 113 + .../2.5/node_modules/has-symbols/CHANGELOG.md | 3 + scripts/2.5/node_modules/has-symbols/LICENSE | 21 + .../2.5/node_modules/has-symbols/README.md | 45 + scripts/2.5/node_modules/has-symbols/index.js | 13 + .../2.5/node_modules/has-symbols/package.json | 108 + scripts/2.5/node_modules/has-symbols/shams.js | 42 + .../node_modules/has-symbols/test/index.js | 22 + .../has-symbols/test/shams/core-js.js | 28 + .../test/shams/get-own-property-symbols.js | 28 + .../node_modules/has-symbols/test/tests.js | 54 + scripts/2.5/node_modules/has/LICENSE-MIT | 22 + scripts/2.5/node_modules/has/README.md | 18 + scripts/2.5/node_modules/has/package.json | 75 + scripts/2.5/node_modules/has/src/index.js | 5 + scripts/2.5/node_modules/has/test/index.js | 10 + scripts/2.5/node_modules/inherits/LICENSE | 16 + scripts/2.5/node_modules/inherits/README.md | 42 + scripts/2.5/node_modules/inherits/inherits.js | 9 + .../node_modules/inherits/inherits_browser.js | 27 + .../2.5/node_modules/inherits/package.json | 61 + .../node_modules/is-arguments/.editorconfig | 20 + .../2.5/node_modules/is-arguments/.eslintrc | 10 + .../2.5/node_modules/is-arguments/.jscs.json | 176 + .../2.5/node_modules/is-arguments/.travis.yml | 248 + .../node_modules/is-arguments/CHANGELOG.md | 32 + scripts/2.5/node_modules/is-arguments/LICENSE | 20 + .../2.5/node_modules/is-arguments/README.md | 49 + .../2.5/node_modules/is-arguments/index.js | 31 + .../node_modules/is-arguments/package.json | 101 + scripts/2.5/node_modules/is-arguments/test.js | 44 + .../node_modules/is-callable/.editorconfig | 20 + .../2.5/node_modules/is-callable/.eslintrc | 11 + .../node_modules/is-callable/.istanbul.yml | 47 + .../2.5/node_modules/is-callable/.jscs.json | 176 + .../2.5/node_modules/is-callable/.travis.yml | 225 + .../2.5/node_modules/is-callable/CHANGELOG.md | 56 + scripts/2.5/node_modules/is-callable/LICENSE | 22 + scripts/2.5/node_modules/is-callable/Makefile | 61 + .../2.5/node_modules/is-callable/README.md | 59 + scripts/2.5/node_modules/is-callable/index.js | 37 + .../2.5/node_modules/is-callable/package.json | 124 + scripts/2.5/node_modules/is-callable/test.js | 158 + .../2.5/node_modules/is-date-object/.eslintrc | 9 + .../node_modules/is-date-object/.jscs.json | 122 + .../node_modules/is-date-object/.npmignore | 28 + .../node_modules/is-date-object/.travis.yml | 58 + .../node_modules/is-date-object/CHANGELOG.md | 10 + .../2.5/node_modules/is-date-object/LICENSE | 22 + .../2.5/node_modules/is-date-object/Makefile | 61 + .../2.5/node_modules/is-date-object/README.md | 53 + .../2.5/node_modules/is-date-object/index.js | 20 + .../node_modules/is-date-object/package.json | 93 + .../2.5/node_modules/is-date-object/test.js | 33 + .../is-generator-function/.editorconfig | 20 + .../is-generator-function/.eslintrc | 9 + .../is-generator-function/.jscs.json | 176 + .../node_modules/is-generator-function/.nvmrc | 1 + .../is-generator-function/.travis.yml | 191 + .../is-generator-function/CHANGELOG.md | 44 + .../is-generator-function/LICENSE | 20 + .../is-generator-function/Makefile | 61 + .../is-generator-function/README.md | 42 + .../is-generator-function/index.js | 32 + .../is-generator-function/package.json | 101 + .../is-generator-function/test/.eslintrc | 5 + .../is-generator-function/test/corejs.js | 5 + .../is-generator-function/test/index.js | 94 + .../is-generator-function/test/uglified.js | 8 + scripts/2.5/node_modules/is-nan/.eslintrc | 9 + scripts/2.5/node_modules/is-nan/.jscs.json | 124 + scripts/2.5/node_modules/is-nan/.npmignore | 15 + scripts/2.5/node_modules/is-nan/.travis.yml | 49 + scripts/2.5/node_modules/is-nan/CHANGELOG.md | 27 + scripts/2.5/node_modules/is-nan/LICENSE | 20 + scripts/2.5/node_modules/is-nan/README.md | 56 + .../2.5/node_modules/is-nan/implementation.js | 7 + scripts/2.5/node_modules/is-nan/index.js | 17 + scripts/2.5/node_modules/is-nan/package.json | 101 + scripts/2.5/node_modules/is-nan/polyfill.js | 10 + scripts/2.5/node_modules/is-nan/shim.js | 12 + scripts/2.5/node_modules/is-nan/test/index.js | 10 + .../2.5/node_modules/is-nan/test/shimmed.js | 28 + scripts/2.5/node_modules/is-nan/test/tests.js | 36 + scripts/2.5/node_modules/is-regex/.eslintrc | 9 + scripts/2.5/node_modules/is-regex/.jscs.json | 176 + scripts/2.5/node_modules/is-regex/.npmignore | 15 + scripts/2.5/node_modules/is-regex/.travis.yml | 165 + .../2.5/node_modules/is-regex/CHANGELOG.md | 27 + scripts/2.5/node_modules/is-regex/LICENSE | 20 + scripts/2.5/node_modules/is-regex/Makefile | 61 + scripts/2.5/node_modules/is-regex/README.md | 54 + scripts/2.5/node_modules/is-regex/index.js | 39 + .../2.5/node_modules/is-regex/package.json | 100 + scripts/2.5/node_modules/is-regex/test.js | 58 + .../2.5/node_modules/is-symbol/.editorconfig | 13 + scripts/2.5/node_modules/is-symbol/.eslintrc | 9 + scripts/2.5/node_modules/is-symbol/.jscs.json | 176 + scripts/2.5/node_modules/is-symbol/.nvmrc | 1 + .../2.5/node_modules/is-symbol/.travis.yml | 241 + .../2.5/node_modules/is-symbol/CHANGELOG.md | 12 + scripts/2.5/node_modules/is-symbol/LICENSE | 22 + scripts/2.5/node_modules/is-symbol/Makefile | 61 + scripts/2.5/node_modules/is-symbol/README.md | 46 + scripts/2.5/node_modules/is-symbol/index.js | 35 + .../2.5/node_modules/is-symbol/package.json | 96 + .../2.5/node_modules/is-symbol/test/.eslintrc | 7 + .../2.5/node_modules/is-symbol/test/index.js | 92 + .../2.5/node_modules/memory-pager/.travis.yml | 4 + scripts/2.5/node_modules/memory-pager/LICENSE | 21 + .../2.5/node_modules/memory-pager/README.md | 65 + .../2.5/node_modules/memory-pager/index.js | 160 + .../node_modules/memory-pager/package.json | 52 + scripts/2.5/node_modules/memory-pager/test.js | 80 + scripts/2.5/node_modules/mongodb/HISTORY.md | 2485 +++ scripts/2.5/node_modules/mongodb/LICENSE.md | 201 + scripts/2.5/node_modules/mongodb/README.md | 499 + scripts/2.5/node_modules/mongodb/index.js | 68 + scripts/2.5/node_modules/mongodb/lib/admin.js | 293 + .../mongodb/lib/aggregation_cursor.js | 370 + scripts/2.5/node_modules/mongodb/lib/apm.js | 31 + .../node_modules/mongodb/lib/async/.eslintrc | 5 + .../mongodb/lib/async/async_iterator.js | 33 + .../node_modules/mongodb/lib/bulk/common.js | 1239 ++ .../node_modules/mongodb/lib/bulk/ordered.js | 105 + .../mongodb/lib/bulk/unordered.js | 118 + .../node_modules/mongodb/lib/change_stream.js | 576 + .../node_modules/mongodb/lib/collection.js | 2113 ++ .../mongodb/lib/command_cursor.js | 269 + .../2.5/node_modules/mongodb/lib/constants.js | 10 + .../mongodb/lib/core/auth/auth_provider.js | 158 + .../lib/core/auth/defaultAuthProviders.js | 29 + .../mongodb/lib/core/auth/gssapi.js | 241 + .../lib/core/auth/mongo_credentials.js | 81 + .../mongodb/lib/core/auth/mongocr.js | 51 + .../mongodb/lib/core/auth/plain.js | 35 + .../mongodb/lib/core/auth/scram.js | 293 + .../mongodb/lib/core/auth/sspi.js | 131 + .../mongodb/lib/core/auth/x509.js | 26 + .../mongodb/lib/core/connection/apm.js | 236 + .../lib/core/connection/command_result.js | 36 + .../mongodb/lib/core/connection/commands.js | 507 + .../mongodb/lib/core/connection/connect.js | 370 + .../mongodb/lib/core/connection/connection.js | 628 + .../mongodb/lib/core/connection/logger.js | 246 + .../mongodb/lib/core/connection/msg.js | 221 + .../mongodb/lib/core/connection/pool.js | 1256 ++ .../mongodb/lib/core/connection/utils.js | 57 + .../node_modules/mongodb/lib/core/cursor.js | 886 + .../node_modules/mongodb/lib/core/error.js | 237 + .../node_modules/mongodb/lib/core/index.js | 50 + .../mongodb/lib/core/sdam/monitoring.js | 235 + .../mongodb/lib/core/sdam/server.js | 511 + .../lib/core/sdam/server_description.js | 163 + .../mongodb/lib/core/sdam/server_selectors.js | 244 + .../mongodb/lib/core/sdam/srv_polling.js | 135 + .../mongodb/lib/core/sdam/topology.js | 1186 ++ .../lib/core/sdam/topology_description.js | 408 + .../node_modules/mongodb/lib/core/sessions.js | 767 + .../mongodb/lib/core/tools/smoke_plugin.js | 61 + .../mongodb/lib/core/topologies/mongos.js | 1392 ++ .../lib/core/topologies/read_preference.js | 202 + .../mongodb/lib/core/topologies/replset.js | 1553 ++ .../lib/core/topologies/replset_state.js | 1121 + .../mongodb/lib/core/topologies/server.js | 989 + .../mongodb/lib/core/topologies/shared.js | 476 + .../mongodb/lib/core/transactions.js | 168 + .../mongodb/lib/core/uri_parser.js | 637 + .../node_modules/mongodb/lib/core/utils.js | 177 + .../mongodb/lib/core/wireprotocol/command.js | 170 + .../lib/core/wireprotocol/compression.js | 73 + .../lib/core/wireprotocol/constants.js | 13 + .../mongodb/lib/core/wireprotocol/get_more.js | 90 + .../mongodb/lib/core/wireprotocol/index.js | 18 + .../lib/core/wireprotocol/kill_cursors.js | 70 + .../mongodb/lib/core/wireprotocol/query.js | 231 + .../mongodb/lib/core/wireprotocol/shared.js | 115 + .../lib/core/wireprotocol/write_command.js | 50 + .../2.5/node_modules/mongodb/lib/cursor.js | 1089 + scripts/2.5/node_modules/mongodb/lib/db.js | 1029 + .../mongodb/lib/dynamic_loaders.js | 32 + scripts/2.5/node_modules/mongodb/lib/error.js | 45 + .../mongodb/lib/gridfs-stream/download.js | 421 + .../mongodb/lib/gridfs-stream/index.js | 358 + .../mongodb/lib/gridfs-stream/upload.js | 538 + .../node_modules/mongodb/lib/gridfs/chunk.js | 236 + .../mongodb/lib/gridfs/grid_store.js | 1913 ++ .../node_modules/mongodb/lib/mongo_client.js | 479 + .../mongodb/lib/operations/add_user.js | 96 + .../mongodb/lib/operations/admin_ops.js | 62 + .../mongodb/lib/operations/aggregate.js | 106 + .../mongodb/lib/operations/bulk_write.js | 104 + .../mongodb/lib/operations/close.js | 46 + .../mongodb/lib/operations/collection_ops.js | 374 + .../mongodb/lib/operations/collections.js | 55 + .../mongodb/lib/operations/command.js | 120 + .../mongodb/lib/operations/command_v2.js | 109 + .../lib/operations/common_functions.js | 406 + .../mongodb/lib/operations/connect.js | 709 + .../mongodb/lib/operations/count.js | 72 + .../mongodb/lib/operations/count_documents.js | 41 + .../lib/operations/create_collection.js | 118 + .../mongodb/lib/operations/create_index.js | 92 + .../mongodb/lib/operations/create_indexes.js | 61 + .../mongodb/lib/operations/cursor_ops.js | 239 + .../mongodb/lib/operations/db_ops.js | 831 + .../mongodb/lib/operations/delete_many.js | 25 + .../mongodb/lib/operations/delete_one.js | 25 + .../mongodb/lib/operations/distinct.js | 85 + .../mongodb/lib/operations/drop.js | 53 + .../mongodb/lib/operations/drop_index.js | 42 + .../mongodb/lib/operations/drop_indexes.js | 23 + .../operations/estimated_document_count.js | 58 + .../operations/execute_db_admin_command.js | 34 + .../lib/operations/execute_operation.js | 198 + .../mongodb/lib/operations/explain.js | 23 + .../mongodb/lib/operations/find.js | 35 + .../mongodb/lib/operations/find_and_modify.js | 98 + .../mongodb/lib/operations/find_one.js | 33 + .../lib/operations/find_one_and_delete.js | 16 + .../lib/operations/find_one_and_replace.js | 18 + .../lib/operations/find_one_and_update.js | 19 + .../lib/operations/geo_haystack_search.js | 79 + .../mongodb/lib/operations/has_next.js | 40 + .../mongodb/lib/operations/index_exists.js | 39 + .../lib/operations/index_information.js | 23 + .../mongodb/lib/operations/indexes.js | 22 + .../mongodb/lib/operations/insert_many.js | 63 + .../mongodb/lib/operations/insert_one.js | 39 + .../mongodb/lib/operations/is_capped.js | 19 + .../lib/operations/list_collections.js | 106 + .../mongodb/lib/operations/list_databases.js | 38 + .../mongodb/lib/operations/list_indexes.js | 42 + .../mongodb/lib/operations/map_reduce.js | 189 + .../mongodb/lib/operations/next.js | 32 + .../mongodb/lib/operations/operation.js | 67 + .../lib/operations/options_operation.js | 32 + .../mongodb/lib/operations/profiling_level.js | 31 + .../mongodb/lib/operations/re_index.js | 28 + .../mongodb/lib/operations/remove_user.js | 52 + .../mongodb/lib/operations/rename.js | 61 + .../mongodb/lib/operations/replace_one.js | 47 + .../lib/operations/set_profiling_level.js | 48 + .../mongodb/lib/operations/stats.js | 45 + .../mongodb/lib/operations/to_array.js | 66 + .../mongodb/lib/operations/update_many.js | 29 + .../mongodb/lib/operations/update_one.js | 44 + .../lib/operations/validate_collection.js | 40 + .../node_modules/mongodb/lib/read_concern.js | 61 + .../mongodb/lib/topologies/mongos.js | 452 + .../mongodb/lib/topologies/native_topology.js | 72 + .../mongodb/lib/topologies/replset.js | 496 + .../mongodb/lib/topologies/server.js | 455 + .../mongodb/lib/topologies/topology_base.js | 438 + .../node_modules/mongodb/lib/url_parser.js | 623 + scripts/2.5/node_modules/mongodb/lib/utils.js | 716 + .../node_modules/mongodb/lib/write_concern.js | 66 + scripts/2.5/node_modules/mongodb/package.json | 104 + .../2.5/node_modules/object-inspect/.nycrc | 17 + .../node_modules/object-inspect/.travis.yml | 216 + .../2.5/node_modules/object-inspect/LICENSE | 18 + .../object-inspect/example/all.js | 19 + .../object-inspect/example/circular.js | 4 + .../node_modules/object-inspect/example/fn.js | 3 + .../object-inspect/example/inspect.js | 7 + .../2.5/node_modules/object-inspect/index.js | 257 + .../node_modules/object-inspect/package.json | 84 + .../object-inspect/readme.markdown | 61 + .../object-inspect/test-core-js.js | 16 + .../object-inspect/test/bigint.js | 30 + .../object-inspect/test/browser/dom.js | 15 + .../object-inspect/test/circular.js | 9 + .../node_modules/object-inspect/test/deep.js | 9 + .../object-inspect/test/element.js | 53 + .../node_modules/object-inspect/test/err.js | 29 + .../node_modules/object-inspect/test/fn.js | 28 + .../node_modules/object-inspect/test/has.js | 31 + .../node_modules/object-inspect/test/holes.js | 15 + .../object-inspect/test/inspect.js | 8 + .../object-inspect/test/lowbyte.js | 12 + .../object-inspect/test/number.js | 12 + .../object-inspect/test/quoteStyle.js | 17 + .../node_modules/object-inspect/test/undef.js | 12 + .../object-inspect/test/values.js | 136 + .../object-inspect/util.inspect.js | 1 + scripts/2.5/node_modules/object-is/.jscs.json | 55 + scripts/2.5/node_modules/object-is/.npmignore | 15 + .../2.5/node_modules/object-is/.travis.yml | 18 + scripts/2.5/node_modules/object-is/LICENSE | 20 + scripts/2.5/node_modules/object-is/README.md | 54 + scripts/2.5/node_modules/object-is/index.js | 19 + .../2.5/node_modules/object-is/package.json | 86 + scripts/2.5/node_modules/object-is/test.js | 50 + .../node_modules/object-keys/.editorconfig | 13 + .../2.5/node_modules/object-keys/.eslintrc | 17 + .../2.5/node_modules/object-keys/.travis.yml | 277 + .../2.5/node_modules/object-keys/CHANGELOG.md | 232 + scripts/2.5/node_modules/object-keys/LICENSE | 21 + .../2.5/node_modules/object-keys/README.md | 76 + .../object-keys/implementation.js | 122 + scripts/2.5/node_modules/object-keys/index.js | 32 + .../node_modules/object-keys/isArguments.js | 17 + .../2.5/node_modules/object-keys/package.json | 118 + .../node_modules/object-keys/test/index.js | 5 + .../node_modules/object.entries/.editorconfig | 20 + .../2.5/node_modules/object.entries/.eslintrc | 11 + .../node_modules/object.entries/.travis.yml | 269 + .../node_modules/object.entries/CHANGELOG.md | 33 + .../2.5/node_modules/object.entries/LICENSE | 22 + .../2.5/node_modules/object.entries/README.md | 59 + .../2.5/node_modules/object.entries/auto.js | 3 + .../object.entries/implementation.js | 17 + .../2.5/node_modules/object.entries/index.js | 17 + .../node_modules/object.entries/package.json | 107 + .../node_modules/object.entries/polyfill.js | 7 + .../2.5/node_modules/object.entries/shim.js | 14 + .../object.entries/test/.eslintrc | 11 + .../node_modules/object.entries/test/index.js | 17 + .../object.entries/test/shimmed.js | 36 + .../node_modules/object.entries/test/tests.js | 84 + .../node_modules/require_optional/.npmignore | 33 + .../node_modules/require_optional/.travis.yml | 9 + .../node_modules/require_optional/HISTORY.md | 7 + .../2.5/node_modules/require_optional/LICENSE | 201 + .../node_modules/require_optional/README.md | 2 + .../node_modules/require_optional/index.js | 128 + .../require_optional/package.json | 67 + .../require_optional/test/nestedTest/index.js | 8 + .../test/nestedTest/package.json | 11 + .../test/require_optional_tests.js | 59 + .../2.5/node_modules/resolve-from/index.js | 23 + scripts/2.5/node_modules/resolve-from/license | 21 + .../node_modules/resolve-from/package.json | 66 + .../2.5/node_modules/resolve-from/readme.md | 58 + scripts/2.5/node_modules/safe-buffer/LICENSE | 21 + .../2.5/node_modules/safe-buffer/README.md | 586 + .../2.5/node_modules/safe-buffer/index.d.ts | 187 + scripts/2.5/node_modules/safe-buffer/index.js | 64 + .../2.5/node_modules/safe-buffer/package.json | 62 + .../2.5/node_modules/saslprep/.editorconfig | 10 + .../2.5/node_modules/saslprep/.gitattributes | 1 + scripts/2.5/node_modules/saslprep/.travis.yml | 10 + .../2.5/node_modules/saslprep/CHANGELOG.md | 19 + scripts/2.5/node_modules/saslprep/LICENSE | 22 + .../2.5/node_modules/saslprep/code-points.mem | Bin 0 -> 419864 bytes .../saslprep/generate-code-points.js | 51 + scripts/2.5/node_modules/saslprep/index.js | 157 + .../node_modules/saslprep/lib/code-points.js | 996 + .../saslprep/lib/memory-code-points.js | 39 + scripts/2.5/node_modules/saslprep/lib/util.js | 21 + .../2.5/node_modules/saslprep/package.json | 100 + scripts/2.5/node_modules/saslprep/readme.md | 31 + .../2.5/node_modules/saslprep/test/index.js | 76 + .../2.5/node_modules/saslprep/test/util.js | 16 + scripts/2.5/node_modules/semver/CHANGELOG.md | 39 + scripts/2.5/node_modules/semver/LICENSE | 15 + scripts/2.5/node_modules/semver/README.md | 412 + scripts/2.5/node_modules/semver/bin/semver | 160 + scripts/2.5/node_modules/semver/package.json | 60 + scripts/2.5/node_modules/semver/range.bnf | 16 + scripts/2.5/node_modules/semver/semver.js | 1483 ++ .../node_modules/sparse-bitfield/.npmignore | 1 + .../node_modules/sparse-bitfield/.travis.yml | 6 + .../2.5/node_modules/sparse-bitfield/LICENSE | 21 + .../node_modules/sparse-bitfield/README.md | 62 + .../2.5/node_modules/sparse-bitfield/index.js | 95 + .../node_modules/sparse-bitfield/package.json | 55 + .../2.5/node_modules/sparse-bitfield/test.js | 79 + .../string.prototype.trimleft/.editorconfig | 20 + .../string.prototype.trimleft/.eslintrc | 15 + .../string.prototype.trimleft/.travis.yml | 317 + .../string.prototype.trimleft/CHANGELOG.md | 30 + .../string.prototype.trimleft/LICENSE | 22 + .../string.prototype.trimleft/README.md | 47 + .../string.prototype.trimleft/auto.js | 3 + .../implementation.js | 12 + .../string.prototype.trimleft/index.js | 18 + .../string.prototype.trimleft/package.json | 97 + .../string.prototype.trimleft/polyfill.js | 14 + .../string.prototype.trimleft/shim.js | 14 + .../string.prototype.trimleft/test/index.js | 18 + .../string.prototype.trimleft/test/shimmed.js | 37 + .../string.prototype.trimleft/test/tests.js | 26 + .../string.prototype.trimright/.editorconfig | 20 + .../string.prototype.trimright/.eslintrc | 15 + .../string.prototype.trimright/.travis.yml | 317 + .../string.prototype.trimright/CHANGELOG.md | 30 + .../string.prototype.trimright/LICENSE | 22 + .../string.prototype.trimright/README.md | 47 + .../string.prototype.trimright/auto.js | 3 + .../implementation.js | 12 + .../string.prototype.trimright/index.js | 18 + .../string.prototype.trimright/package.json | 97 + .../string.prototype.trimright/polyfill.js | 14 + .../string.prototype.trimright/shim.js | 14 + .../string.prototype.trimright/test/index.js | 17 + .../test/shimmed.js | 37 + .../string.prototype.trimright/test/tests.js | 26 + scripts/2.5/node_modules/util/CHANGELOG.md | 22 + scripts/2.5/node_modules/util/LICENSE | 18 + scripts/2.5/node_modules/util/README.md | 48 + scripts/2.5/node_modules/util/package.json | 73 + .../2.5/node_modules/util/support/isBuffer.js | 3 + .../util/support/isBufferBrowser.js | 6 + .../2.5/node_modules/util/support/types.js | 422 + scripts/2.5/node_modules/util/util.js | 715 + scripts/node_modules/.bin/semver | 1 + scripts/node_modules/bson/HISTORY.md | 268 + scripts/node_modules/bson/LICENSE.md | 201 + scripts/node_modules/bson/README.md | 170 + scripts/node_modules/bson/bower.json | 25 + .../node_modules/bson/browser_build/bson.js | 17769 ++++++++++++++++ .../bson/browser_build/package.json | 8 + scripts/node_modules/bson/index.js | 46 + scripts/node_modules/bson/lib/bson/binary.js | 384 + scripts/node_modules/bson/lib/bson/bson.js | 386 + scripts/node_modules/bson/lib/bson/code.js | 24 + scripts/node_modules/bson/lib/bson/db_ref.js | 32 + .../node_modules/bson/lib/bson/decimal128.js | 820 + scripts/node_modules/bson/lib/bson/double.js | 33 + .../bson/lib/bson/float_parser.js | 124 + scripts/node_modules/bson/lib/bson/int_32.js | 33 + scripts/node_modules/bson/lib/bson/long.js | 851 + scripts/node_modules/bson/lib/bson/map.js | 128 + scripts/node_modules/bson/lib/bson/max_key.js | 14 + scripts/node_modules/bson/lib/bson/min_key.js | 14 + .../node_modules/bson/lib/bson/objectid.js | 389 + .../bson/lib/bson/parser/calculate_size.js | 255 + .../bson/lib/bson/parser/deserializer.js | 782 + .../bson/lib/bson/parser/serializer.js | 1182 + .../bson/lib/bson/parser/utils.js | 28 + scripts/node_modules/bson/lib/bson/regexp.js | 33 + scripts/node_modules/bson/lib/bson/symbol.js | 50 + .../node_modules/bson/lib/bson/timestamp.js | 854 + scripts/node_modules/bson/package.json | 87 + scripts/node_modules/memory-pager/.travis.yml | 4 + scripts/node_modules/memory-pager/LICENSE | 21 + scripts/node_modules/memory-pager/README.md | 65 + scripts/node_modules/memory-pager/index.js | 160 + .../node_modules/memory-pager/package.json | 52 + scripts/node_modules/memory-pager/test.js | 80 + scripts/node_modules/mongodb/HISTORY.md | 2485 +++ scripts/node_modules/mongodb/LICENSE.md | 201 + scripts/node_modules/mongodb/README.md | 499 + scripts/node_modules/mongodb/index.js | 68 + scripts/node_modules/mongodb/lib/admin.js | 293 + .../mongodb/lib/aggregation_cursor.js | 370 + scripts/node_modules/mongodb/lib/apm.js | 31 + .../node_modules/mongodb/lib/async/.eslintrc | 5 + .../mongodb/lib/async/async_iterator.js | 33 + .../node_modules/mongodb/lib/bulk/common.js | 1239 ++ .../node_modules/mongodb/lib/bulk/ordered.js | 105 + .../mongodb/lib/bulk/unordered.js | 118 + .../node_modules/mongodb/lib/change_stream.js | 576 + .../node_modules/mongodb/lib/collection.js | 2113 ++ .../mongodb/lib/command_cursor.js | 269 + scripts/node_modules/mongodb/lib/constants.js | 10 + .../mongodb/lib/core/auth/auth_provider.js | 158 + .../lib/core/auth/defaultAuthProviders.js | 29 + .../mongodb/lib/core/auth/gssapi.js | 241 + .../lib/core/auth/mongo_credentials.js | 81 + .../mongodb/lib/core/auth/mongocr.js | 51 + .../mongodb/lib/core/auth/plain.js | 35 + .../mongodb/lib/core/auth/scram.js | 293 + .../mongodb/lib/core/auth/sspi.js | 131 + .../mongodb/lib/core/auth/x509.js | 26 + .../mongodb/lib/core/connection/apm.js | 236 + .../lib/core/connection/command_result.js | 36 + .../mongodb/lib/core/connection/commands.js | 507 + .../mongodb/lib/core/connection/connect.js | 370 + .../mongodb/lib/core/connection/connection.js | 628 + .../mongodb/lib/core/connection/logger.js | 246 + .../mongodb/lib/core/connection/msg.js | 221 + .../mongodb/lib/core/connection/pool.js | 1256 ++ .../mongodb/lib/core/connection/utils.js | 57 + .../node_modules/mongodb/lib/core/cursor.js | 886 + .../node_modules/mongodb/lib/core/error.js | 237 + .../node_modules/mongodb/lib/core/index.js | 50 + .../mongodb/lib/core/sdam/monitoring.js | 235 + .../mongodb/lib/core/sdam/server.js | 511 + .../lib/core/sdam/server_description.js | 163 + .../mongodb/lib/core/sdam/server_selectors.js | 244 + .../mongodb/lib/core/sdam/srv_polling.js | 135 + .../mongodb/lib/core/sdam/topology.js | 1186 ++ .../lib/core/sdam/topology_description.js | 408 + .../node_modules/mongodb/lib/core/sessions.js | 767 + .../mongodb/lib/core/tools/smoke_plugin.js | 61 + .../mongodb/lib/core/topologies/mongos.js | 1392 ++ .../lib/core/topologies/read_preference.js | 202 + .../mongodb/lib/core/topologies/replset.js | 1553 ++ .../lib/core/topologies/replset_state.js | 1121 + .../mongodb/lib/core/topologies/server.js | 989 + .../mongodb/lib/core/topologies/shared.js | 476 + .../mongodb/lib/core/transactions.js | 168 + .../mongodb/lib/core/uri_parser.js | 637 + .../node_modules/mongodb/lib/core/utils.js | 177 + .../mongodb/lib/core/wireprotocol/command.js | 170 + .../lib/core/wireprotocol/compression.js | 73 + .../lib/core/wireprotocol/constants.js | 13 + .../mongodb/lib/core/wireprotocol/get_more.js | 90 + .../mongodb/lib/core/wireprotocol/index.js | 18 + .../lib/core/wireprotocol/kill_cursors.js | 70 + .../mongodb/lib/core/wireprotocol/query.js | 231 + .../mongodb/lib/core/wireprotocol/shared.js | 115 + .../lib/core/wireprotocol/write_command.js | 50 + scripts/node_modules/mongodb/lib/cursor.js | 1089 + scripts/node_modules/mongodb/lib/db.js | 1029 + .../mongodb/lib/dynamic_loaders.js | 32 + scripts/node_modules/mongodb/lib/error.js | 45 + .../mongodb/lib/gridfs-stream/download.js | 421 + .../mongodb/lib/gridfs-stream/index.js | 358 + .../mongodb/lib/gridfs-stream/upload.js | 538 + .../node_modules/mongodb/lib/gridfs/chunk.js | 236 + .../mongodb/lib/gridfs/grid_store.js | 1913 ++ .../node_modules/mongodb/lib/mongo_client.js | 479 + .../mongodb/lib/operations/add_user.js | 96 + .../mongodb/lib/operations/admin_ops.js | 62 + .../mongodb/lib/operations/aggregate.js | 106 + .../mongodb/lib/operations/bulk_write.js | 104 + .../mongodb/lib/operations/close.js | 46 + .../mongodb/lib/operations/collection_ops.js | 374 + .../mongodb/lib/operations/collections.js | 55 + .../mongodb/lib/operations/command.js | 120 + .../mongodb/lib/operations/command_v2.js | 109 + .../lib/operations/common_functions.js | 406 + .../mongodb/lib/operations/connect.js | 709 + .../mongodb/lib/operations/count.js | 72 + .../mongodb/lib/operations/count_documents.js | 41 + .../lib/operations/create_collection.js | 118 + .../mongodb/lib/operations/create_index.js | 92 + .../mongodb/lib/operations/create_indexes.js | 61 + .../mongodb/lib/operations/cursor_ops.js | 239 + .../mongodb/lib/operations/db_ops.js | 831 + .../mongodb/lib/operations/delete_many.js | 25 + .../mongodb/lib/operations/delete_one.js | 25 + .../mongodb/lib/operations/distinct.js | 85 + .../mongodb/lib/operations/drop.js | 53 + .../mongodb/lib/operations/drop_index.js | 42 + .../mongodb/lib/operations/drop_indexes.js | 23 + .../operations/estimated_document_count.js | 58 + .../operations/execute_db_admin_command.js | 34 + .../lib/operations/execute_operation.js | 198 + .../mongodb/lib/operations/explain.js | 23 + .../mongodb/lib/operations/find.js | 35 + .../mongodb/lib/operations/find_and_modify.js | 98 + .../mongodb/lib/operations/find_one.js | 33 + .../lib/operations/find_one_and_delete.js | 16 + .../lib/operations/find_one_and_replace.js | 18 + .../lib/operations/find_one_and_update.js | 19 + .../lib/operations/geo_haystack_search.js | 79 + .../mongodb/lib/operations/has_next.js | 40 + .../mongodb/lib/operations/index_exists.js | 39 + .../lib/operations/index_information.js | 23 + .../mongodb/lib/operations/indexes.js | 22 + .../mongodb/lib/operations/insert_many.js | 63 + .../mongodb/lib/operations/insert_one.js | 39 + .../mongodb/lib/operations/is_capped.js | 19 + .../lib/operations/list_collections.js | 106 + .../mongodb/lib/operations/list_databases.js | 38 + .../mongodb/lib/operations/list_indexes.js | 42 + .../mongodb/lib/operations/map_reduce.js | 189 + .../mongodb/lib/operations/next.js | 32 + .../mongodb/lib/operations/operation.js | 67 + .../lib/operations/options_operation.js | 32 + .../mongodb/lib/operations/profiling_level.js | 31 + .../mongodb/lib/operations/re_index.js | 28 + .../mongodb/lib/operations/remove_user.js | 52 + .../mongodb/lib/operations/rename.js | 61 + .../mongodb/lib/operations/replace_one.js | 47 + .../lib/operations/set_profiling_level.js | 48 + .../mongodb/lib/operations/stats.js | 45 + .../mongodb/lib/operations/to_array.js | 66 + .../mongodb/lib/operations/update_many.js | 29 + .../mongodb/lib/operations/update_one.js | 44 + .../lib/operations/validate_collection.js | 40 + .../node_modules/mongodb/lib/read_concern.js | 61 + .../mongodb/lib/topologies/mongos.js | 452 + .../mongodb/lib/topologies/native_topology.js | 72 + .../mongodb/lib/topologies/replset.js | 496 + .../mongodb/lib/topologies/server.js | 455 + .../mongodb/lib/topologies/topology_base.js | 438 + .../node_modules/mongodb/lib/url_parser.js | 623 + scripts/node_modules/mongodb/lib/utils.js | 716 + .../node_modules/mongodb/lib/write_concern.js | 66 + scripts/node_modules/mongodb/package.json | 104 + .../node_modules/require_optional/.npmignore | 33 + .../node_modules/require_optional/.travis.yml | 9 + .../node_modules/require_optional/HISTORY.md | 7 + scripts/node_modules/require_optional/LICENSE | 201 + .../node_modules/require_optional/README.md | 2 + .../node_modules/require_optional/index.js | 128 + .../require_optional/package.json | 67 + .../require_optional/test/nestedTest/index.js | 8 + .../test/nestedTest/package.json | 11 + .../test/require_optional_tests.js | 59 + scripts/node_modules/resolve-from/index.js | 23 + scripts/node_modules/resolve-from/license | 21 + .../node_modules/resolve-from/package.json | 66 + scripts/node_modules/resolve-from/readme.md | 58 + scripts/node_modules/safe-buffer/LICENSE | 21 + scripts/node_modules/safe-buffer/README.md | 586 + scripts/node_modules/safe-buffer/index.d.ts | 187 + scripts/node_modules/safe-buffer/index.js | 64 + scripts/node_modules/safe-buffer/package.json | 62 + scripts/node_modules/saslprep/.editorconfig | 10 + scripts/node_modules/saslprep/.gitattributes | 1 + scripts/node_modules/saslprep/.travis.yml | 10 + scripts/node_modules/saslprep/CHANGELOG.md | 19 + scripts/node_modules/saslprep/LICENSE | 22 + scripts/node_modules/saslprep/code-points.mem | Bin 0 -> 419864 bytes .../saslprep/generate-code-points.js | 51 + scripts/node_modules/saslprep/index.js | 157 + .../node_modules/saslprep/lib/code-points.js | 996 + .../saslprep/lib/memory-code-points.js | 39 + scripts/node_modules/saslprep/lib/util.js | 21 + scripts/node_modules/saslprep/package.json | 100 + scripts/node_modules/saslprep/readme.md | 31 + scripts/node_modules/saslprep/test/index.js | 76 + scripts/node_modules/saslprep/test/util.js | 16 + scripts/node_modules/semver/CHANGELOG.md | 39 + scripts/node_modules/semver/LICENSE | 15 + scripts/node_modules/semver/README.md | 412 + scripts/node_modules/semver/bin/semver | 160 + scripts/node_modules/semver/package.json | 60 + scripts/node_modules/semver/range.bnf | 16 + scripts/node_modules/semver/semver.js | 1483 ++ .../node_modules/sparse-bitfield/.npmignore | 1 + .../node_modules/sparse-bitfield/.travis.yml | 6 + scripts/node_modules/sparse-bitfield/LICENSE | 21 + .../node_modules/sparse-bitfield/README.md | 62 + scripts/node_modules/sparse-bitfield/index.js | 95 + .../node_modules/sparse-bitfield/package.json | 55 + scripts/node_modules/sparse-bitfield/test.js | 79 + .../{state => }/PackageNotificationInfo.java | 4 +- .../org/kpmp/packages/PackageService.java | 2 - .../java/org/kpmp/packages/PackageView.java | 1 - .../org/kpmp/packages/{state => }/State.java | 2 +- .../{state => }/StateHandlerService.java | 2 +- .../PackageNotificationInfoTest.java | 3 +- .../org/kpmp/packages/PackageServiceTest.java | 2 - .../org/kpmp/packages/PackageViewTest.java | 1 - .../{state => }/StateHandlerServiceTest.java | 5 +- .../kpmp/packages/{state => }/StateTest.java | 3 +- 786 files changed, 168392 insertions(+), 13 deletions(-) create mode 120000 scripts/2.5/node_modules/.bin/semver create mode 100644 scripts/2.5/node_modules/assert/CHANGELOG.md create mode 100644 scripts/2.5/node_modules/assert/LICENSE create mode 100644 scripts/2.5/node_modules/assert/README.md create mode 100644 scripts/2.5/node_modules/assert/package.json create mode 100644 scripts/2.5/node_modules/bson/HISTORY.md create mode 100644 scripts/2.5/node_modules/bson/LICENSE.md create mode 100644 scripts/2.5/node_modules/bson/README.md create mode 100644 scripts/2.5/node_modules/bson/bower.json create mode 100644 scripts/2.5/node_modules/bson/browser_build/bson.js create mode 100644 scripts/2.5/node_modules/bson/browser_build/package.json create mode 100644 scripts/2.5/node_modules/bson/index.js create mode 100644 scripts/2.5/node_modules/bson/lib/bson/binary.js create mode 100644 scripts/2.5/node_modules/bson/lib/bson/bson.js create mode 100644 scripts/2.5/node_modules/bson/lib/bson/code.js create mode 100644 scripts/2.5/node_modules/bson/lib/bson/db_ref.js create mode 100644 scripts/2.5/node_modules/bson/lib/bson/decimal128.js create mode 100644 scripts/2.5/node_modules/bson/lib/bson/double.js create mode 100644 scripts/2.5/node_modules/bson/lib/bson/float_parser.js create mode 100644 scripts/2.5/node_modules/bson/lib/bson/int_32.js create mode 100644 scripts/2.5/node_modules/bson/lib/bson/long.js create mode 100644 scripts/2.5/node_modules/bson/lib/bson/map.js create mode 100644 scripts/2.5/node_modules/bson/lib/bson/max_key.js create mode 100644 scripts/2.5/node_modules/bson/lib/bson/min_key.js create mode 100644 scripts/2.5/node_modules/bson/lib/bson/objectid.js create mode 100644 scripts/2.5/node_modules/bson/lib/bson/parser/calculate_size.js create mode 100644 scripts/2.5/node_modules/bson/lib/bson/parser/deserializer.js create mode 100644 scripts/2.5/node_modules/bson/lib/bson/parser/serializer.js create mode 100644 scripts/2.5/node_modules/bson/lib/bson/parser/utils.js create mode 100644 scripts/2.5/node_modules/bson/lib/bson/regexp.js create mode 100644 scripts/2.5/node_modules/bson/lib/bson/symbol.js create mode 100644 scripts/2.5/node_modules/bson/lib/bson/timestamp.js create mode 100644 scripts/2.5/node_modules/bson/package.json create mode 100644 scripts/2.5/node_modules/define-properties/.editorconfig create mode 100644 scripts/2.5/node_modules/define-properties/.eslintrc create mode 100644 scripts/2.5/node_modules/define-properties/.jscs.json create mode 100644 scripts/2.5/node_modules/define-properties/.travis.yml create mode 100644 scripts/2.5/node_modules/define-properties/CHANGELOG.md create mode 100644 scripts/2.5/node_modules/define-properties/LICENSE create mode 100644 scripts/2.5/node_modules/define-properties/README.md create mode 100644 scripts/2.5/node_modules/define-properties/index.js create mode 100644 scripts/2.5/node_modules/define-properties/package.json create mode 100644 scripts/2.5/node_modules/define-properties/test/index.js create mode 100644 scripts/2.5/node_modules/es-abstract/.editorconfig create mode 100644 scripts/2.5/node_modules/es-abstract/.eslintrc create mode 100644 scripts/2.5/node_modules/es-abstract/.github/FUNDING.yml create mode 100644 scripts/2.5/node_modules/es-abstract/.nycrc create mode 100644 scripts/2.5/node_modules/es-abstract/.travis.yml create mode 100644 scripts/2.5/node_modules/es-abstract/CHANGELOG.md create mode 100644 scripts/2.5/node_modules/es-abstract/GetIntrinsic.js create mode 100644 scripts/2.5/node_modules/es-abstract/LICENSE create mode 100644 scripts/2.5/node_modules/es-abstract/Makefile create mode 100644 scripts/2.5/node_modules/es-abstract/README.md create mode 100644 scripts/2.5/node_modules/es-abstract/es2015.js create mode 100644 scripts/2.5/node_modules/es-abstract/es2016.js create mode 100644 scripts/2.5/node_modules/es-abstract/es2017.js create mode 100644 scripts/2.5/node_modules/es-abstract/es2018.js create mode 100644 scripts/2.5/node_modules/es-abstract/es2019.js create mode 100644 scripts/2.5/node_modules/es-abstract/es5.js create mode 100644 scripts/2.5/node_modules/es-abstract/es6.js create mode 100644 scripts/2.5/node_modules/es-abstract/es7.js create mode 100644 scripts/2.5/node_modules/es-abstract/helpers/assertRecord.js create mode 100644 scripts/2.5/node_modules/es-abstract/helpers/assign.js create mode 100644 scripts/2.5/node_modules/es-abstract/helpers/callBind.js create mode 100644 scripts/2.5/node_modules/es-abstract/helpers/callBound.js create mode 100644 scripts/2.5/node_modules/es-abstract/helpers/every.js create mode 100644 scripts/2.5/node_modules/es-abstract/helpers/forEach.js create mode 100644 scripts/2.5/node_modules/es-abstract/helpers/getInferredName.js create mode 100644 scripts/2.5/node_modules/es-abstract/helpers/getIteratorMethod.js create mode 100644 scripts/2.5/node_modules/es-abstract/helpers/getProto.js create mode 100644 scripts/2.5/node_modules/es-abstract/helpers/getSymbolDescription.js create mode 100644 scripts/2.5/node_modules/es-abstract/helpers/isFinite.js create mode 100644 scripts/2.5/node_modules/es-abstract/helpers/isNaN.js create mode 100644 scripts/2.5/node_modules/es-abstract/helpers/isPrefixOf.js create mode 100644 scripts/2.5/node_modules/es-abstract/helpers/isPrimitive.js create mode 100644 scripts/2.5/node_modules/es-abstract/helpers/isPropertyDescriptor.js create mode 100644 scripts/2.5/node_modules/es-abstract/helpers/isSamePropertyDescriptor.js create mode 100644 scripts/2.5/node_modules/es-abstract/helpers/maxSafeInteger.js create mode 100644 scripts/2.5/node_modules/es-abstract/helpers/mod.js create mode 100644 scripts/2.5/node_modules/es-abstract/helpers/regexTester.js create mode 100644 scripts/2.5/node_modules/es-abstract/helpers/setProto.js create mode 100644 scripts/2.5/node_modules/es-abstract/helpers/sign.js create mode 100644 scripts/2.5/node_modules/es-abstract/index.js create mode 100644 scripts/2.5/node_modules/es-abstract/operations/.eslintrc create mode 100644 scripts/2.5/node_modules/es-abstract/package.json create mode 100644 scripts/2.5/node_modules/es-abstract/test/.eslintrc create mode 100644 scripts/2.5/node_modules/es-abstract/test/GetIntrinsic.js create mode 100644 scripts/2.5/node_modules/es-abstract/test/diffOps.js create mode 100644 scripts/2.5/node_modules/es-abstract/test/es2015.js create mode 100644 scripts/2.5/node_modules/es-abstract/test/es2016.js create mode 100644 scripts/2.5/node_modules/es-abstract/test/es2017.js create mode 100644 scripts/2.5/node_modules/es-abstract/test/es2018.js create mode 100644 scripts/2.5/node_modules/es-abstract/test/es2019.js create mode 100644 scripts/2.5/node_modules/es-abstract/test/es5.js create mode 100644 scripts/2.5/node_modules/es-abstract/test/es6.js create mode 100644 scripts/2.5/node_modules/es-abstract/test/es7.js create mode 100644 scripts/2.5/node_modules/es-abstract/test/helpers/assertRecord.js create mode 100644 scripts/2.5/node_modules/es-abstract/test/helpers/getSymbolDescription.js create mode 100644 scripts/2.5/node_modules/es-abstract/test/helpers/values.js create mode 100644 scripts/2.5/node_modules/es-abstract/test/index.js create mode 100644 scripts/2.5/node_modules/es-abstract/test/tests.js create mode 100644 scripts/2.5/node_modules/es-to-primitive/.editorconfig create mode 100644 scripts/2.5/node_modules/es-to-primitive/.eslintrc create mode 100644 scripts/2.5/node_modules/es-to-primitive/.jscs.json create mode 100644 scripts/2.5/node_modules/es-to-primitive/.travis.yml create mode 100644 scripts/2.5/node_modules/es-to-primitive/CHANGELOG.md create mode 100644 scripts/2.5/node_modules/es-to-primitive/LICENSE create mode 100644 scripts/2.5/node_modules/es-to-primitive/Makefile create mode 100644 scripts/2.5/node_modules/es-to-primitive/README.md create mode 100644 scripts/2.5/node_modules/es-to-primitive/es2015.js create mode 100644 scripts/2.5/node_modules/es-to-primitive/es5.js create mode 100644 scripts/2.5/node_modules/es-to-primitive/es6.js create mode 100644 scripts/2.5/node_modules/es-to-primitive/helpers/isPrimitive.js create mode 100644 scripts/2.5/node_modules/es-to-primitive/index.js create mode 100644 scripts/2.5/node_modules/es-to-primitive/package.json create mode 100644 scripts/2.5/node_modules/es-to-primitive/test/.eslintrc create mode 100644 scripts/2.5/node_modules/es-to-primitive/test/es2015.js create mode 100644 scripts/2.5/node_modules/es-to-primitive/test/es5.js create mode 100644 scripts/2.5/node_modules/es-to-primitive/test/es6.js create mode 100644 scripts/2.5/node_modules/es-to-primitive/test/index.js create mode 100644 scripts/2.5/node_modules/es6-object-assign/LICENSE create mode 100644 scripts/2.5/node_modules/es6-object-assign/README.md create mode 100644 scripts/2.5/node_modules/es6-object-assign/auto.js create mode 100644 scripts/2.5/node_modules/es6-object-assign/dist/object-assign-auto.js create mode 100644 scripts/2.5/node_modules/es6-object-assign/dist/object-assign-auto.min.js create mode 100644 scripts/2.5/node_modules/es6-object-assign/dist/object-assign.js create mode 100644 scripts/2.5/node_modules/es6-object-assign/dist/object-assign.min.js create mode 100644 scripts/2.5/node_modules/es6-object-assign/index.js create mode 100644 scripts/2.5/node_modules/es6-object-assign/package.json create mode 100644 scripts/2.5/node_modules/function-bind/.editorconfig create mode 100644 scripts/2.5/node_modules/function-bind/.eslintrc create mode 100644 scripts/2.5/node_modules/function-bind/.jscs.json create mode 100644 scripts/2.5/node_modules/function-bind/.npmignore create mode 100644 scripts/2.5/node_modules/function-bind/.travis.yml create mode 100644 scripts/2.5/node_modules/function-bind/LICENSE create mode 100644 scripts/2.5/node_modules/function-bind/README.md create mode 100644 scripts/2.5/node_modules/function-bind/implementation.js create mode 100644 scripts/2.5/node_modules/function-bind/index.js create mode 100644 scripts/2.5/node_modules/function-bind/package.json create mode 100644 scripts/2.5/node_modules/function-bind/test/.eslintrc create mode 100644 scripts/2.5/node_modules/function-bind/test/index.js create mode 100644 scripts/2.5/node_modules/has-symbols/.eslintrc create mode 100644 scripts/2.5/node_modules/has-symbols/.npmignore create mode 100644 scripts/2.5/node_modules/has-symbols/.travis.yml create mode 100644 scripts/2.5/node_modules/has-symbols/CHANGELOG.md create mode 100644 scripts/2.5/node_modules/has-symbols/LICENSE create mode 100644 scripts/2.5/node_modules/has-symbols/README.md create mode 100644 scripts/2.5/node_modules/has-symbols/index.js create mode 100644 scripts/2.5/node_modules/has-symbols/package.json create mode 100644 scripts/2.5/node_modules/has-symbols/shams.js create mode 100644 scripts/2.5/node_modules/has-symbols/test/index.js create mode 100644 scripts/2.5/node_modules/has-symbols/test/shams/core-js.js create mode 100644 scripts/2.5/node_modules/has-symbols/test/shams/get-own-property-symbols.js create mode 100644 scripts/2.5/node_modules/has-symbols/test/tests.js create mode 100644 scripts/2.5/node_modules/has/LICENSE-MIT create mode 100644 scripts/2.5/node_modules/has/README.md create mode 100644 scripts/2.5/node_modules/has/package.json create mode 100644 scripts/2.5/node_modules/has/src/index.js create mode 100644 scripts/2.5/node_modules/has/test/index.js create mode 100644 scripts/2.5/node_modules/inherits/LICENSE create mode 100644 scripts/2.5/node_modules/inherits/README.md create mode 100644 scripts/2.5/node_modules/inherits/inherits.js create mode 100644 scripts/2.5/node_modules/inherits/inherits_browser.js create mode 100644 scripts/2.5/node_modules/inherits/package.json create mode 100644 scripts/2.5/node_modules/is-arguments/.editorconfig create mode 100644 scripts/2.5/node_modules/is-arguments/.eslintrc create mode 100644 scripts/2.5/node_modules/is-arguments/.jscs.json create mode 100644 scripts/2.5/node_modules/is-arguments/.travis.yml create mode 100644 scripts/2.5/node_modules/is-arguments/CHANGELOG.md create mode 100644 scripts/2.5/node_modules/is-arguments/LICENSE create mode 100644 scripts/2.5/node_modules/is-arguments/README.md create mode 100644 scripts/2.5/node_modules/is-arguments/index.js create mode 100644 scripts/2.5/node_modules/is-arguments/package.json create mode 100644 scripts/2.5/node_modules/is-arguments/test.js create mode 100644 scripts/2.5/node_modules/is-callable/.editorconfig create mode 100644 scripts/2.5/node_modules/is-callable/.eslintrc create mode 100644 scripts/2.5/node_modules/is-callable/.istanbul.yml create mode 100644 scripts/2.5/node_modules/is-callable/.jscs.json create mode 100644 scripts/2.5/node_modules/is-callable/.travis.yml create mode 100644 scripts/2.5/node_modules/is-callable/CHANGELOG.md create mode 100644 scripts/2.5/node_modules/is-callable/LICENSE create mode 100644 scripts/2.5/node_modules/is-callable/Makefile create mode 100644 scripts/2.5/node_modules/is-callable/README.md create mode 100644 scripts/2.5/node_modules/is-callable/index.js create mode 100644 scripts/2.5/node_modules/is-callable/package.json create mode 100644 scripts/2.5/node_modules/is-callable/test.js create mode 100644 scripts/2.5/node_modules/is-date-object/.eslintrc create mode 100644 scripts/2.5/node_modules/is-date-object/.jscs.json create mode 100644 scripts/2.5/node_modules/is-date-object/.npmignore create mode 100644 scripts/2.5/node_modules/is-date-object/.travis.yml create mode 100644 scripts/2.5/node_modules/is-date-object/CHANGELOG.md create mode 100644 scripts/2.5/node_modules/is-date-object/LICENSE create mode 100644 scripts/2.5/node_modules/is-date-object/Makefile create mode 100644 scripts/2.5/node_modules/is-date-object/README.md create mode 100644 scripts/2.5/node_modules/is-date-object/index.js create mode 100644 scripts/2.5/node_modules/is-date-object/package.json create mode 100644 scripts/2.5/node_modules/is-date-object/test.js create mode 100644 scripts/2.5/node_modules/is-generator-function/.editorconfig create mode 100644 scripts/2.5/node_modules/is-generator-function/.eslintrc create mode 100644 scripts/2.5/node_modules/is-generator-function/.jscs.json create mode 100644 scripts/2.5/node_modules/is-generator-function/.nvmrc create mode 100644 scripts/2.5/node_modules/is-generator-function/.travis.yml create mode 100644 scripts/2.5/node_modules/is-generator-function/CHANGELOG.md create mode 100644 scripts/2.5/node_modules/is-generator-function/LICENSE create mode 100644 scripts/2.5/node_modules/is-generator-function/Makefile create mode 100644 scripts/2.5/node_modules/is-generator-function/README.md create mode 100644 scripts/2.5/node_modules/is-generator-function/index.js create mode 100644 scripts/2.5/node_modules/is-generator-function/package.json create mode 100644 scripts/2.5/node_modules/is-generator-function/test/.eslintrc create mode 100644 scripts/2.5/node_modules/is-generator-function/test/corejs.js create mode 100644 scripts/2.5/node_modules/is-generator-function/test/index.js create mode 100644 scripts/2.5/node_modules/is-generator-function/test/uglified.js create mode 100644 scripts/2.5/node_modules/is-nan/.eslintrc create mode 100644 scripts/2.5/node_modules/is-nan/.jscs.json create mode 100644 scripts/2.5/node_modules/is-nan/.npmignore create mode 100644 scripts/2.5/node_modules/is-nan/.travis.yml create mode 100644 scripts/2.5/node_modules/is-nan/CHANGELOG.md create mode 100644 scripts/2.5/node_modules/is-nan/LICENSE create mode 100644 scripts/2.5/node_modules/is-nan/README.md create mode 100644 scripts/2.5/node_modules/is-nan/implementation.js create mode 100644 scripts/2.5/node_modules/is-nan/index.js create mode 100644 scripts/2.5/node_modules/is-nan/package.json create mode 100644 scripts/2.5/node_modules/is-nan/polyfill.js create mode 100644 scripts/2.5/node_modules/is-nan/shim.js create mode 100644 scripts/2.5/node_modules/is-nan/test/index.js create mode 100644 scripts/2.5/node_modules/is-nan/test/shimmed.js create mode 100644 scripts/2.5/node_modules/is-nan/test/tests.js create mode 100644 scripts/2.5/node_modules/is-regex/.eslintrc create mode 100644 scripts/2.5/node_modules/is-regex/.jscs.json create mode 100644 scripts/2.5/node_modules/is-regex/.npmignore create mode 100644 scripts/2.5/node_modules/is-regex/.travis.yml create mode 100644 scripts/2.5/node_modules/is-regex/CHANGELOG.md create mode 100644 scripts/2.5/node_modules/is-regex/LICENSE create mode 100644 scripts/2.5/node_modules/is-regex/Makefile create mode 100644 scripts/2.5/node_modules/is-regex/README.md create mode 100644 scripts/2.5/node_modules/is-regex/index.js create mode 100644 scripts/2.5/node_modules/is-regex/package.json create mode 100644 scripts/2.5/node_modules/is-regex/test.js create mode 100644 scripts/2.5/node_modules/is-symbol/.editorconfig create mode 100644 scripts/2.5/node_modules/is-symbol/.eslintrc create mode 100644 scripts/2.5/node_modules/is-symbol/.jscs.json create mode 100644 scripts/2.5/node_modules/is-symbol/.nvmrc create mode 100644 scripts/2.5/node_modules/is-symbol/.travis.yml create mode 100644 scripts/2.5/node_modules/is-symbol/CHANGELOG.md create mode 100644 scripts/2.5/node_modules/is-symbol/LICENSE create mode 100644 scripts/2.5/node_modules/is-symbol/Makefile create mode 100644 scripts/2.5/node_modules/is-symbol/README.md create mode 100644 scripts/2.5/node_modules/is-symbol/index.js create mode 100644 scripts/2.5/node_modules/is-symbol/package.json create mode 100644 scripts/2.5/node_modules/is-symbol/test/.eslintrc create mode 100644 scripts/2.5/node_modules/is-symbol/test/index.js create mode 100644 scripts/2.5/node_modules/memory-pager/.travis.yml create mode 100644 scripts/2.5/node_modules/memory-pager/LICENSE create mode 100644 scripts/2.5/node_modules/memory-pager/README.md create mode 100644 scripts/2.5/node_modules/memory-pager/index.js create mode 100644 scripts/2.5/node_modules/memory-pager/package.json create mode 100644 scripts/2.5/node_modules/memory-pager/test.js create mode 100644 scripts/2.5/node_modules/mongodb/HISTORY.md create mode 100644 scripts/2.5/node_modules/mongodb/LICENSE.md create mode 100644 scripts/2.5/node_modules/mongodb/README.md create mode 100644 scripts/2.5/node_modules/mongodb/index.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/admin.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/aggregation_cursor.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/apm.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/async/.eslintrc create mode 100644 scripts/2.5/node_modules/mongodb/lib/async/async_iterator.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/bulk/common.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/bulk/ordered.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/bulk/unordered.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/change_stream.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/collection.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/command_cursor.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/constants.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/core/auth/auth_provider.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/core/auth/defaultAuthProviders.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/core/auth/gssapi.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/core/auth/mongo_credentials.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/core/auth/mongocr.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/core/auth/plain.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/core/auth/scram.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/core/auth/sspi.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/core/auth/x509.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/core/connection/apm.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/core/connection/command_result.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/core/connection/commands.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/core/connection/connect.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/core/connection/connection.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/core/connection/logger.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/core/connection/msg.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/core/connection/pool.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/core/connection/utils.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/core/cursor.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/core/error.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/core/index.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/core/sdam/monitoring.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/core/sdam/server.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/core/sdam/server_description.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/core/sdam/server_selectors.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/core/sdam/srv_polling.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/core/sdam/topology.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/core/sdam/topology_description.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/core/sessions.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/core/tools/smoke_plugin.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/core/topologies/mongos.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/core/topologies/read_preference.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/core/topologies/replset.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/core/topologies/replset_state.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/core/topologies/server.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/core/topologies/shared.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/core/transactions.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/core/uri_parser.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/core/utils.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/core/wireprotocol/command.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/core/wireprotocol/compression.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/core/wireprotocol/constants.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/core/wireprotocol/get_more.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/core/wireprotocol/index.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/core/wireprotocol/kill_cursors.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/core/wireprotocol/query.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/core/wireprotocol/shared.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/core/wireprotocol/write_command.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/cursor.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/db.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/dynamic_loaders.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/error.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/gridfs-stream/download.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/gridfs-stream/index.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/gridfs-stream/upload.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/gridfs/chunk.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/gridfs/grid_store.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/mongo_client.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/add_user.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/admin_ops.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/aggregate.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/bulk_write.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/close.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/collection_ops.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/collections.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/command.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/command_v2.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/common_functions.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/connect.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/count.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/count_documents.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/create_collection.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/create_index.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/create_indexes.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/cursor_ops.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/db_ops.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/delete_many.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/delete_one.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/distinct.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/drop.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/drop_index.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/drop_indexes.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/estimated_document_count.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/execute_db_admin_command.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/execute_operation.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/explain.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/find.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/find_and_modify.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/find_one.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/find_one_and_delete.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/find_one_and_replace.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/find_one_and_update.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/geo_haystack_search.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/has_next.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/index_exists.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/index_information.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/indexes.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/insert_many.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/insert_one.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/is_capped.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/list_collections.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/list_databases.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/list_indexes.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/map_reduce.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/next.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/operation.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/options_operation.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/profiling_level.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/re_index.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/remove_user.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/rename.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/replace_one.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/set_profiling_level.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/stats.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/to_array.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/update_many.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/update_one.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/validate_collection.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/read_concern.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/topologies/mongos.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/topologies/native_topology.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/topologies/replset.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/topologies/server.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/topologies/topology_base.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/url_parser.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/utils.js create mode 100644 scripts/2.5/node_modules/mongodb/lib/write_concern.js create mode 100644 scripts/2.5/node_modules/mongodb/package.json create mode 100644 scripts/2.5/node_modules/object-inspect/.nycrc create mode 100644 scripts/2.5/node_modules/object-inspect/.travis.yml create mode 100644 scripts/2.5/node_modules/object-inspect/LICENSE create mode 100644 scripts/2.5/node_modules/object-inspect/example/all.js create mode 100644 scripts/2.5/node_modules/object-inspect/example/circular.js create mode 100644 scripts/2.5/node_modules/object-inspect/example/fn.js create mode 100644 scripts/2.5/node_modules/object-inspect/example/inspect.js create mode 100644 scripts/2.5/node_modules/object-inspect/index.js create mode 100644 scripts/2.5/node_modules/object-inspect/package.json create mode 100644 scripts/2.5/node_modules/object-inspect/readme.markdown create mode 100644 scripts/2.5/node_modules/object-inspect/test-core-js.js create mode 100644 scripts/2.5/node_modules/object-inspect/test/bigint.js create mode 100644 scripts/2.5/node_modules/object-inspect/test/browser/dom.js create mode 100644 scripts/2.5/node_modules/object-inspect/test/circular.js create mode 100644 scripts/2.5/node_modules/object-inspect/test/deep.js create mode 100644 scripts/2.5/node_modules/object-inspect/test/element.js create mode 100644 scripts/2.5/node_modules/object-inspect/test/err.js create mode 100644 scripts/2.5/node_modules/object-inspect/test/fn.js create mode 100644 scripts/2.5/node_modules/object-inspect/test/has.js create mode 100644 scripts/2.5/node_modules/object-inspect/test/holes.js create mode 100644 scripts/2.5/node_modules/object-inspect/test/inspect.js create mode 100644 scripts/2.5/node_modules/object-inspect/test/lowbyte.js create mode 100644 scripts/2.5/node_modules/object-inspect/test/number.js create mode 100644 scripts/2.5/node_modules/object-inspect/test/quoteStyle.js create mode 100644 scripts/2.5/node_modules/object-inspect/test/undef.js create mode 100644 scripts/2.5/node_modules/object-inspect/test/values.js create mode 100644 scripts/2.5/node_modules/object-inspect/util.inspect.js create mode 100644 scripts/2.5/node_modules/object-is/.jscs.json create mode 100644 scripts/2.5/node_modules/object-is/.npmignore create mode 100644 scripts/2.5/node_modules/object-is/.travis.yml create mode 100644 scripts/2.5/node_modules/object-is/LICENSE create mode 100644 scripts/2.5/node_modules/object-is/README.md create mode 100644 scripts/2.5/node_modules/object-is/index.js create mode 100644 scripts/2.5/node_modules/object-is/package.json create mode 100644 scripts/2.5/node_modules/object-is/test.js create mode 100644 scripts/2.5/node_modules/object-keys/.editorconfig create mode 100644 scripts/2.5/node_modules/object-keys/.eslintrc create mode 100644 scripts/2.5/node_modules/object-keys/.travis.yml create mode 100644 scripts/2.5/node_modules/object-keys/CHANGELOG.md create mode 100644 scripts/2.5/node_modules/object-keys/LICENSE create mode 100644 scripts/2.5/node_modules/object-keys/README.md create mode 100644 scripts/2.5/node_modules/object-keys/implementation.js create mode 100644 scripts/2.5/node_modules/object-keys/index.js create mode 100644 scripts/2.5/node_modules/object-keys/isArguments.js create mode 100644 scripts/2.5/node_modules/object-keys/package.json create mode 100644 scripts/2.5/node_modules/object-keys/test/index.js create mode 100644 scripts/2.5/node_modules/object.entries/.editorconfig create mode 100644 scripts/2.5/node_modules/object.entries/.eslintrc create mode 100644 scripts/2.5/node_modules/object.entries/.travis.yml create mode 100644 scripts/2.5/node_modules/object.entries/CHANGELOG.md create mode 100644 scripts/2.5/node_modules/object.entries/LICENSE create mode 100644 scripts/2.5/node_modules/object.entries/README.md create mode 100644 scripts/2.5/node_modules/object.entries/auto.js create mode 100644 scripts/2.5/node_modules/object.entries/implementation.js create mode 100644 scripts/2.5/node_modules/object.entries/index.js create mode 100644 scripts/2.5/node_modules/object.entries/package.json create mode 100644 scripts/2.5/node_modules/object.entries/polyfill.js create mode 100644 scripts/2.5/node_modules/object.entries/shim.js create mode 100644 scripts/2.5/node_modules/object.entries/test/.eslintrc create mode 100644 scripts/2.5/node_modules/object.entries/test/index.js create mode 100644 scripts/2.5/node_modules/object.entries/test/shimmed.js create mode 100644 scripts/2.5/node_modules/object.entries/test/tests.js create mode 100644 scripts/2.5/node_modules/require_optional/.npmignore create mode 100644 scripts/2.5/node_modules/require_optional/.travis.yml create mode 100644 scripts/2.5/node_modules/require_optional/HISTORY.md create mode 100644 scripts/2.5/node_modules/require_optional/LICENSE create mode 100644 scripts/2.5/node_modules/require_optional/README.md create mode 100644 scripts/2.5/node_modules/require_optional/index.js create mode 100644 scripts/2.5/node_modules/require_optional/package.json create mode 100644 scripts/2.5/node_modules/require_optional/test/nestedTest/index.js create mode 100644 scripts/2.5/node_modules/require_optional/test/nestedTest/package.json create mode 100644 scripts/2.5/node_modules/require_optional/test/require_optional_tests.js create mode 100644 scripts/2.5/node_modules/resolve-from/index.js create mode 100644 scripts/2.5/node_modules/resolve-from/license create mode 100644 scripts/2.5/node_modules/resolve-from/package.json create mode 100644 scripts/2.5/node_modules/resolve-from/readme.md create mode 100644 scripts/2.5/node_modules/safe-buffer/LICENSE create mode 100644 scripts/2.5/node_modules/safe-buffer/README.md create mode 100644 scripts/2.5/node_modules/safe-buffer/index.d.ts create mode 100644 scripts/2.5/node_modules/safe-buffer/index.js create mode 100644 scripts/2.5/node_modules/safe-buffer/package.json create mode 100644 scripts/2.5/node_modules/saslprep/.editorconfig create mode 100644 scripts/2.5/node_modules/saslprep/.gitattributes create mode 100644 scripts/2.5/node_modules/saslprep/.travis.yml create mode 100644 scripts/2.5/node_modules/saslprep/CHANGELOG.md create mode 100644 scripts/2.5/node_modules/saslprep/LICENSE create mode 100644 scripts/2.5/node_modules/saslprep/code-points.mem create mode 100644 scripts/2.5/node_modules/saslprep/generate-code-points.js create mode 100644 scripts/2.5/node_modules/saslprep/index.js create mode 100644 scripts/2.5/node_modules/saslprep/lib/code-points.js create mode 100644 scripts/2.5/node_modules/saslprep/lib/memory-code-points.js create mode 100644 scripts/2.5/node_modules/saslprep/lib/util.js create mode 100644 scripts/2.5/node_modules/saslprep/package.json create mode 100644 scripts/2.5/node_modules/saslprep/readme.md create mode 100644 scripts/2.5/node_modules/saslprep/test/index.js create mode 100644 scripts/2.5/node_modules/saslprep/test/util.js create mode 100644 scripts/2.5/node_modules/semver/CHANGELOG.md create mode 100644 scripts/2.5/node_modules/semver/LICENSE create mode 100644 scripts/2.5/node_modules/semver/README.md create mode 100755 scripts/2.5/node_modules/semver/bin/semver create mode 100644 scripts/2.5/node_modules/semver/package.json create mode 100644 scripts/2.5/node_modules/semver/range.bnf create mode 100644 scripts/2.5/node_modules/semver/semver.js create mode 100644 scripts/2.5/node_modules/sparse-bitfield/.npmignore create mode 100644 scripts/2.5/node_modules/sparse-bitfield/.travis.yml create mode 100644 scripts/2.5/node_modules/sparse-bitfield/LICENSE create mode 100644 scripts/2.5/node_modules/sparse-bitfield/README.md create mode 100644 scripts/2.5/node_modules/sparse-bitfield/index.js create mode 100644 scripts/2.5/node_modules/sparse-bitfield/package.json create mode 100644 scripts/2.5/node_modules/sparse-bitfield/test.js create mode 100644 scripts/2.5/node_modules/string.prototype.trimleft/.editorconfig create mode 100644 scripts/2.5/node_modules/string.prototype.trimleft/.eslintrc create mode 100644 scripts/2.5/node_modules/string.prototype.trimleft/.travis.yml create mode 100644 scripts/2.5/node_modules/string.prototype.trimleft/CHANGELOG.md create mode 100644 scripts/2.5/node_modules/string.prototype.trimleft/LICENSE create mode 100644 scripts/2.5/node_modules/string.prototype.trimleft/README.md create mode 100644 scripts/2.5/node_modules/string.prototype.trimleft/auto.js create mode 100644 scripts/2.5/node_modules/string.prototype.trimleft/implementation.js create mode 100644 scripts/2.5/node_modules/string.prototype.trimleft/index.js create mode 100644 scripts/2.5/node_modules/string.prototype.trimleft/package.json create mode 100644 scripts/2.5/node_modules/string.prototype.trimleft/polyfill.js create mode 100644 scripts/2.5/node_modules/string.prototype.trimleft/shim.js create mode 100644 scripts/2.5/node_modules/string.prototype.trimleft/test/index.js create mode 100644 scripts/2.5/node_modules/string.prototype.trimleft/test/shimmed.js create mode 100644 scripts/2.5/node_modules/string.prototype.trimleft/test/tests.js create mode 100644 scripts/2.5/node_modules/string.prototype.trimright/.editorconfig create mode 100644 scripts/2.5/node_modules/string.prototype.trimright/.eslintrc create mode 100644 scripts/2.5/node_modules/string.prototype.trimright/.travis.yml create mode 100644 scripts/2.5/node_modules/string.prototype.trimright/CHANGELOG.md create mode 100644 scripts/2.5/node_modules/string.prototype.trimright/LICENSE create mode 100644 scripts/2.5/node_modules/string.prototype.trimright/README.md create mode 100644 scripts/2.5/node_modules/string.prototype.trimright/auto.js create mode 100644 scripts/2.5/node_modules/string.prototype.trimright/implementation.js create mode 100644 scripts/2.5/node_modules/string.prototype.trimright/index.js create mode 100644 scripts/2.5/node_modules/string.prototype.trimright/package.json create mode 100644 scripts/2.5/node_modules/string.prototype.trimright/polyfill.js create mode 100644 scripts/2.5/node_modules/string.prototype.trimright/shim.js create mode 100644 scripts/2.5/node_modules/string.prototype.trimright/test/index.js create mode 100644 scripts/2.5/node_modules/string.prototype.trimright/test/shimmed.js create mode 100644 scripts/2.5/node_modules/string.prototype.trimright/test/tests.js create mode 100644 scripts/2.5/node_modules/util/CHANGELOG.md create mode 100644 scripts/2.5/node_modules/util/LICENSE create mode 100644 scripts/2.5/node_modules/util/README.md create mode 100644 scripts/2.5/node_modules/util/package.json create mode 100644 scripts/2.5/node_modules/util/support/isBuffer.js create mode 100644 scripts/2.5/node_modules/util/support/isBufferBrowser.js create mode 100644 scripts/2.5/node_modules/util/support/types.js create mode 100644 scripts/2.5/node_modules/util/util.js create mode 120000 scripts/node_modules/.bin/semver create mode 100644 scripts/node_modules/bson/HISTORY.md create mode 100644 scripts/node_modules/bson/LICENSE.md create mode 100644 scripts/node_modules/bson/README.md create mode 100644 scripts/node_modules/bson/bower.json create mode 100644 scripts/node_modules/bson/browser_build/bson.js create mode 100644 scripts/node_modules/bson/browser_build/package.json create mode 100644 scripts/node_modules/bson/index.js create mode 100644 scripts/node_modules/bson/lib/bson/binary.js create mode 100644 scripts/node_modules/bson/lib/bson/bson.js create mode 100644 scripts/node_modules/bson/lib/bson/code.js create mode 100644 scripts/node_modules/bson/lib/bson/db_ref.js create mode 100644 scripts/node_modules/bson/lib/bson/decimal128.js create mode 100644 scripts/node_modules/bson/lib/bson/double.js create mode 100644 scripts/node_modules/bson/lib/bson/float_parser.js create mode 100644 scripts/node_modules/bson/lib/bson/int_32.js create mode 100644 scripts/node_modules/bson/lib/bson/long.js create mode 100644 scripts/node_modules/bson/lib/bson/map.js create mode 100644 scripts/node_modules/bson/lib/bson/max_key.js create mode 100644 scripts/node_modules/bson/lib/bson/min_key.js create mode 100644 scripts/node_modules/bson/lib/bson/objectid.js create mode 100644 scripts/node_modules/bson/lib/bson/parser/calculate_size.js create mode 100644 scripts/node_modules/bson/lib/bson/parser/deserializer.js create mode 100644 scripts/node_modules/bson/lib/bson/parser/serializer.js create mode 100644 scripts/node_modules/bson/lib/bson/parser/utils.js create mode 100644 scripts/node_modules/bson/lib/bson/regexp.js create mode 100644 scripts/node_modules/bson/lib/bson/symbol.js create mode 100644 scripts/node_modules/bson/lib/bson/timestamp.js create mode 100644 scripts/node_modules/bson/package.json create mode 100644 scripts/node_modules/memory-pager/.travis.yml create mode 100644 scripts/node_modules/memory-pager/LICENSE create mode 100644 scripts/node_modules/memory-pager/README.md create mode 100644 scripts/node_modules/memory-pager/index.js create mode 100644 scripts/node_modules/memory-pager/package.json create mode 100644 scripts/node_modules/memory-pager/test.js create mode 100644 scripts/node_modules/mongodb/HISTORY.md create mode 100644 scripts/node_modules/mongodb/LICENSE.md create mode 100644 scripts/node_modules/mongodb/README.md create mode 100644 scripts/node_modules/mongodb/index.js create mode 100644 scripts/node_modules/mongodb/lib/admin.js create mode 100644 scripts/node_modules/mongodb/lib/aggregation_cursor.js create mode 100644 scripts/node_modules/mongodb/lib/apm.js create mode 100644 scripts/node_modules/mongodb/lib/async/.eslintrc create mode 100644 scripts/node_modules/mongodb/lib/async/async_iterator.js create mode 100644 scripts/node_modules/mongodb/lib/bulk/common.js create mode 100644 scripts/node_modules/mongodb/lib/bulk/ordered.js create mode 100644 scripts/node_modules/mongodb/lib/bulk/unordered.js create mode 100644 scripts/node_modules/mongodb/lib/change_stream.js create mode 100644 scripts/node_modules/mongodb/lib/collection.js create mode 100644 scripts/node_modules/mongodb/lib/command_cursor.js create mode 100644 scripts/node_modules/mongodb/lib/constants.js create mode 100644 scripts/node_modules/mongodb/lib/core/auth/auth_provider.js create mode 100644 scripts/node_modules/mongodb/lib/core/auth/defaultAuthProviders.js create mode 100644 scripts/node_modules/mongodb/lib/core/auth/gssapi.js create mode 100644 scripts/node_modules/mongodb/lib/core/auth/mongo_credentials.js create mode 100644 scripts/node_modules/mongodb/lib/core/auth/mongocr.js create mode 100644 scripts/node_modules/mongodb/lib/core/auth/plain.js create mode 100644 scripts/node_modules/mongodb/lib/core/auth/scram.js create mode 100644 scripts/node_modules/mongodb/lib/core/auth/sspi.js create mode 100644 scripts/node_modules/mongodb/lib/core/auth/x509.js create mode 100644 scripts/node_modules/mongodb/lib/core/connection/apm.js create mode 100644 scripts/node_modules/mongodb/lib/core/connection/command_result.js create mode 100644 scripts/node_modules/mongodb/lib/core/connection/commands.js create mode 100644 scripts/node_modules/mongodb/lib/core/connection/connect.js create mode 100644 scripts/node_modules/mongodb/lib/core/connection/connection.js create mode 100644 scripts/node_modules/mongodb/lib/core/connection/logger.js create mode 100644 scripts/node_modules/mongodb/lib/core/connection/msg.js create mode 100644 scripts/node_modules/mongodb/lib/core/connection/pool.js create mode 100644 scripts/node_modules/mongodb/lib/core/connection/utils.js create mode 100644 scripts/node_modules/mongodb/lib/core/cursor.js create mode 100644 scripts/node_modules/mongodb/lib/core/error.js create mode 100644 scripts/node_modules/mongodb/lib/core/index.js create mode 100644 scripts/node_modules/mongodb/lib/core/sdam/monitoring.js create mode 100644 scripts/node_modules/mongodb/lib/core/sdam/server.js create mode 100644 scripts/node_modules/mongodb/lib/core/sdam/server_description.js create mode 100644 scripts/node_modules/mongodb/lib/core/sdam/server_selectors.js create mode 100644 scripts/node_modules/mongodb/lib/core/sdam/srv_polling.js create mode 100644 scripts/node_modules/mongodb/lib/core/sdam/topology.js create mode 100644 scripts/node_modules/mongodb/lib/core/sdam/topology_description.js create mode 100644 scripts/node_modules/mongodb/lib/core/sessions.js create mode 100644 scripts/node_modules/mongodb/lib/core/tools/smoke_plugin.js create mode 100644 scripts/node_modules/mongodb/lib/core/topologies/mongos.js create mode 100644 scripts/node_modules/mongodb/lib/core/topologies/read_preference.js create mode 100644 scripts/node_modules/mongodb/lib/core/topologies/replset.js create mode 100644 scripts/node_modules/mongodb/lib/core/topologies/replset_state.js create mode 100644 scripts/node_modules/mongodb/lib/core/topologies/server.js create mode 100644 scripts/node_modules/mongodb/lib/core/topologies/shared.js create mode 100644 scripts/node_modules/mongodb/lib/core/transactions.js create mode 100644 scripts/node_modules/mongodb/lib/core/uri_parser.js create mode 100644 scripts/node_modules/mongodb/lib/core/utils.js create mode 100644 scripts/node_modules/mongodb/lib/core/wireprotocol/command.js create mode 100644 scripts/node_modules/mongodb/lib/core/wireprotocol/compression.js create mode 100644 scripts/node_modules/mongodb/lib/core/wireprotocol/constants.js create mode 100644 scripts/node_modules/mongodb/lib/core/wireprotocol/get_more.js create mode 100644 scripts/node_modules/mongodb/lib/core/wireprotocol/index.js create mode 100644 scripts/node_modules/mongodb/lib/core/wireprotocol/kill_cursors.js create mode 100644 scripts/node_modules/mongodb/lib/core/wireprotocol/query.js create mode 100644 scripts/node_modules/mongodb/lib/core/wireprotocol/shared.js create mode 100644 scripts/node_modules/mongodb/lib/core/wireprotocol/write_command.js create mode 100644 scripts/node_modules/mongodb/lib/cursor.js create mode 100644 scripts/node_modules/mongodb/lib/db.js create mode 100644 scripts/node_modules/mongodb/lib/dynamic_loaders.js create mode 100644 scripts/node_modules/mongodb/lib/error.js create mode 100644 scripts/node_modules/mongodb/lib/gridfs-stream/download.js create mode 100644 scripts/node_modules/mongodb/lib/gridfs-stream/index.js create mode 100644 scripts/node_modules/mongodb/lib/gridfs-stream/upload.js create mode 100644 scripts/node_modules/mongodb/lib/gridfs/chunk.js create mode 100644 scripts/node_modules/mongodb/lib/gridfs/grid_store.js create mode 100644 scripts/node_modules/mongodb/lib/mongo_client.js create mode 100644 scripts/node_modules/mongodb/lib/operations/add_user.js create mode 100644 scripts/node_modules/mongodb/lib/operations/admin_ops.js create mode 100644 scripts/node_modules/mongodb/lib/operations/aggregate.js create mode 100644 scripts/node_modules/mongodb/lib/operations/bulk_write.js create mode 100644 scripts/node_modules/mongodb/lib/operations/close.js create mode 100644 scripts/node_modules/mongodb/lib/operations/collection_ops.js create mode 100644 scripts/node_modules/mongodb/lib/operations/collections.js create mode 100644 scripts/node_modules/mongodb/lib/operations/command.js create mode 100644 scripts/node_modules/mongodb/lib/operations/command_v2.js create mode 100644 scripts/node_modules/mongodb/lib/operations/common_functions.js create mode 100644 scripts/node_modules/mongodb/lib/operations/connect.js create mode 100644 scripts/node_modules/mongodb/lib/operations/count.js create mode 100644 scripts/node_modules/mongodb/lib/operations/count_documents.js create mode 100644 scripts/node_modules/mongodb/lib/operations/create_collection.js create mode 100644 scripts/node_modules/mongodb/lib/operations/create_index.js create mode 100644 scripts/node_modules/mongodb/lib/operations/create_indexes.js create mode 100644 scripts/node_modules/mongodb/lib/operations/cursor_ops.js create mode 100644 scripts/node_modules/mongodb/lib/operations/db_ops.js create mode 100644 scripts/node_modules/mongodb/lib/operations/delete_many.js create mode 100644 scripts/node_modules/mongodb/lib/operations/delete_one.js create mode 100644 scripts/node_modules/mongodb/lib/operations/distinct.js create mode 100644 scripts/node_modules/mongodb/lib/operations/drop.js create mode 100644 scripts/node_modules/mongodb/lib/operations/drop_index.js create mode 100644 scripts/node_modules/mongodb/lib/operations/drop_indexes.js create mode 100644 scripts/node_modules/mongodb/lib/operations/estimated_document_count.js create mode 100644 scripts/node_modules/mongodb/lib/operations/execute_db_admin_command.js create mode 100644 scripts/node_modules/mongodb/lib/operations/execute_operation.js create mode 100644 scripts/node_modules/mongodb/lib/operations/explain.js create mode 100644 scripts/node_modules/mongodb/lib/operations/find.js create mode 100644 scripts/node_modules/mongodb/lib/operations/find_and_modify.js create mode 100644 scripts/node_modules/mongodb/lib/operations/find_one.js create mode 100644 scripts/node_modules/mongodb/lib/operations/find_one_and_delete.js create mode 100644 scripts/node_modules/mongodb/lib/operations/find_one_and_replace.js create mode 100644 scripts/node_modules/mongodb/lib/operations/find_one_and_update.js create mode 100644 scripts/node_modules/mongodb/lib/operations/geo_haystack_search.js create mode 100644 scripts/node_modules/mongodb/lib/operations/has_next.js create mode 100644 scripts/node_modules/mongodb/lib/operations/index_exists.js create mode 100644 scripts/node_modules/mongodb/lib/operations/index_information.js create mode 100644 scripts/node_modules/mongodb/lib/operations/indexes.js create mode 100644 scripts/node_modules/mongodb/lib/operations/insert_many.js create mode 100644 scripts/node_modules/mongodb/lib/operations/insert_one.js create mode 100644 scripts/node_modules/mongodb/lib/operations/is_capped.js create mode 100644 scripts/node_modules/mongodb/lib/operations/list_collections.js create mode 100644 scripts/node_modules/mongodb/lib/operations/list_databases.js create mode 100644 scripts/node_modules/mongodb/lib/operations/list_indexes.js create mode 100644 scripts/node_modules/mongodb/lib/operations/map_reduce.js create mode 100644 scripts/node_modules/mongodb/lib/operations/next.js create mode 100644 scripts/node_modules/mongodb/lib/operations/operation.js create mode 100644 scripts/node_modules/mongodb/lib/operations/options_operation.js create mode 100644 scripts/node_modules/mongodb/lib/operations/profiling_level.js create mode 100644 scripts/node_modules/mongodb/lib/operations/re_index.js create mode 100644 scripts/node_modules/mongodb/lib/operations/remove_user.js create mode 100644 scripts/node_modules/mongodb/lib/operations/rename.js create mode 100644 scripts/node_modules/mongodb/lib/operations/replace_one.js create mode 100644 scripts/node_modules/mongodb/lib/operations/set_profiling_level.js create mode 100644 scripts/node_modules/mongodb/lib/operations/stats.js create mode 100644 scripts/node_modules/mongodb/lib/operations/to_array.js create mode 100644 scripts/node_modules/mongodb/lib/operations/update_many.js create mode 100644 scripts/node_modules/mongodb/lib/operations/update_one.js create mode 100644 scripts/node_modules/mongodb/lib/operations/validate_collection.js create mode 100644 scripts/node_modules/mongodb/lib/read_concern.js create mode 100644 scripts/node_modules/mongodb/lib/topologies/mongos.js create mode 100644 scripts/node_modules/mongodb/lib/topologies/native_topology.js create mode 100644 scripts/node_modules/mongodb/lib/topologies/replset.js create mode 100644 scripts/node_modules/mongodb/lib/topologies/server.js create mode 100644 scripts/node_modules/mongodb/lib/topologies/topology_base.js create mode 100644 scripts/node_modules/mongodb/lib/url_parser.js create mode 100644 scripts/node_modules/mongodb/lib/utils.js create mode 100644 scripts/node_modules/mongodb/lib/write_concern.js create mode 100644 scripts/node_modules/mongodb/package.json create mode 100644 scripts/node_modules/require_optional/.npmignore create mode 100644 scripts/node_modules/require_optional/.travis.yml create mode 100644 scripts/node_modules/require_optional/HISTORY.md create mode 100644 scripts/node_modules/require_optional/LICENSE create mode 100644 scripts/node_modules/require_optional/README.md create mode 100644 scripts/node_modules/require_optional/index.js create mode 100644 scripts/node_modules/require_optional/package.json create mode 100644 scripts/node_modules/require_optional/test/nestedTest/index.js create mode 100644 scripts/node_modules/require_optional/test/nestedTest/package.json create mode 100644 scripts/node_modules/require_optional/test/require_optional_tests.js create mode 100644 scripts/node_modules/resolve-from/index.js create mode 100644 scripts/node_modules/resolve-from/license create mode 100644 scripts/node_modules/resolve-from/package.json create mode 100644 scripts/node_modules/resolve-from/readme.md create mode 100644 scripts/node_modules/safe-buffer/LICENSE create mode 100644 scripts/node_modules/safe-buffer/README.md create mode 100644 scripts/node_modules/safe-buffer/index.d.ts create mode 100644 scripts/node_modules/safe-buffer/index.js create mode 100644 scripts/node_modules/safe-buffer/package.json create mode 100644 scripts/node_modules/saslprep/.editorconfig create mode 100644 scripts/node_modules/saslprep/.gitattributes create mode 100644 scripts/node_modules/saslprep/.travis.yml create mode 100644 scripts/node_modules/saslprep/CHANGELOG.md create mode 100644 scripts/node_modules/saslprep/LICENSE create mode 100644 scripts/node_modules/saslprep/code-points.mem create mode 100644 scripts/node_modules/saslprep/generate-code-points.js create mode 100644 scripts/node_modules/saslprep/index.js create mode 100644 scripts/node_modules/saslprep/lib/code-points.js create mode 100644 scripts/node_modules/saslprep/lib/memory-code-points.js create mode 100644 scripts/node_modules/saslprep/lib/util.js create mode 100644 scripts/node_modules/saslprep/package.json create mode 100644 scripts/node_modules/saslprep/readme.md create mode 100644 scripts/node_modules/saslprep/test/index.js create mode 100644 scripts/node_modules/saslprep/test/util.js create mode 100644 scripts/node_modules/semver/CHANGELOG.md create mode 100644 scripts/node_modules/semver/LICENSE create mode 100644 scripts/node_modules/semver/README.md create mode 100755 scripts/node_modules/semver/bin/semver create mode 100644 scripts/node_modules/semver/package.json create mode 100644 scripts/node_modules/semver/range.bnf create mode 100644 scripts/node_modules/semver/semver.js create mode 100644 scripts/node_modules/sparse-bitfield/.npmignore create mode 100644 scripts/node_modules/sparse-bitfield/.travis.yml create mode 100644 scripts/node_modules/sparse-bitfield/LICENSE create mode 100644 scripts/node_modules/sparse-bitfield/README.md create mode 100644 scripts/node_modules/sparse-bitfield/index.js create mode 100644 scripts/node_modules/sparse-bitfield/package.json create mode 100644 scripts/node_modules/sparse-bitfield/test.js rename src/main/java/org/kpmp/packages/{state => }/PackageNotificationInfo.java (95%) rename src/main/java/org/kpmp/packages/{state => }/State.java (96%) rename src/main/java/org/kpmp/packages/{state => }/StateHandlerService.java (98%) rename src/test/java/org/kpmp/packages/{state => }/PackageNotificationInfoTest.java (96%) rename src/test/java/org/kpmp/packages/{state => }/StateHandlerServiceTest.java (97%) rename src/test/java/org/kpmp/packages/{state => }/StateTest.java (95%) diff --git a/scripts/2.5/node_modules/.bin/semver b/scripts/2.5/node_modules/.bin/semver new file mode 120000 index 00000000..317eb293 --- /dev/null +++ b/scripts/2.5/node_modules/.bin/semver @@ -0,0 +1 @@ +../semver/bin/semver \ No newline at end of file diff --git a/scripts/2.5/node_modules/assert/CHANGELOG.md b/scripts/2.5/node_modules/assert/CHANGELOG.md new file mode 100644 index 00000000..807626d6 --- /dev/null +++ b/scripts/2.5/node_modules/assert/CHANGELOG.md @@ -0,0 +1,14 @@ +# assert change log + +All notable changes to this project will be documented in this file. + +This project adheres to [Semantic Versioning](http://semver.org/). + +## 2.0.0 + +* Sync with Node.js master. ([@lukechilds](https://github.com/lukechilds) in [#44](https://github.com/browserify/commonjs-assert/pull/44)) + +**Note:** Support for IE9 and IE10 has been dropped. IE11 is still supported. + +## 1.5.0 +* Add strict mode APIs. ([@lukechilds](https://github.com/lukechilds) in [#41](https://github.com/browserify/commonjs-assert/pull/41)) diff --git a/scripts/2.5/node_modules/assert/LICENSE b/scripts/2.5/node_modules/assert/LICENSE new file mode 100644 index 00000000..e3d4e695 --- /dev/null +++ b/scripts/2.5/node_modules/assert/LICENSE @@ -0,0 +1,18 @@ +Copyright Joyent, Inc. and other Node contributors. All rights reserved. +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. diff --git a/scripts/2.5/node_modules/assert/README.md b/scripts/2.5/node_modules/assert/README.md new file mode 100644 index 00000000..e2cc9e15 --- /dev/null +++ b/scripts/2.5/node_modules/assert/README.md @@ -0,0 +1,73 @@ +# assert + +> The [`assert`](https://nodejs.org/api/assert.html) module from Node.js, for the browser. + +[![Build Status](https://travis-ci.org/browserify/commonjs-assert.svg?branch=master)](https://travis-ci.org/browserify/commonjs-assert) +[![npm](https://img.shields.io/npm/dm/assert.svg)](https://www.npmjs.com/package/assert) +[![npm](https://img.shields.io/npm/v/assert.svg)](https://www.npmjs.com/package/assert) + +With browserify, simply `require('assert')` or use the `assert` global and you will get this module. + +The goal is to provide an API that is as functionally identical to the [Node.js `assert` API](https://nodejs.org/api/assert.html) as possible. Read the [official docs](https://nodejs.org/api/assert.html) for API documentation. + +## Install + +To use this module directly (without browserify), install it as a dependency: + +``` +npm install assert +``` + +## Usage + +The goal is to provide an API that is as functionally identical to the [Node.js `assert` API](https://nodejs.org/api/assert.html) as possible. Read the [official docs](https://nodejs.org/api/assert.html) for API documentation. + +### Inconsistencies with Node.js `assert` + +Due to differences between browsers, some error properties such as `message` and `stack` will be inconsistent. However the assertion behaviour is as close as possible to Node.js and the same error `code` will always be used. + +## Contributing + +To contribute, work on the source files. Then build and run the tests against the built files. Be careful to not introduce syntax that will be transpiled down to unsupported syntax. For example, `for...of` loops will be transpiled to use `Symbol.iterator` which is unavailable in IE. + +### Build scripts + +#### `npm run build` + +Builds the project into the `build` dir. + +#### `npm run dev` + +Watches source files for changes and rebuilds them into the `build` dir. + +#### `npm run test` + +Builds the source files into the `build` dir and then runs the tests against the built project. + +#### `npm run test:nobuild` + +Runs the tests against the built project without rebuilding first. + +This is useful if you're debugging in the transpiled code and want to re-run the tests without overwriting any changes you may have made. + +#### `npm run test:source` + +Runs the tests against the unbuilt source files. + +This will only work on modern Node.js versions. + +#### `npm run test:browsers` + +Run browser tests against the all targets in the cloud. + +Requires airtap credentials to be configured on your machine. + +#### `npm run test:browsers:local` + +Run a local browser test server. No airtap configuration required. + +When paired with `npm run dev` any changes you make to the source files will be automatically transpiled and served on the next request to the test server. + +## License + +MIT © Joyent, Inc. and other Node contributors diff --git a/scripts/2.5/node_modules/assert/package.json b/scripts/2.5/node_modules/assert/package.json new file mode 100644 index 00000000..f6d36c2a --- /dev/null +++ b/scripts/2.5/node_modules/assert/package.json @@ -0,0 +1,77 @@ +{ + "_from": "assert", + "_id": "assert@2.0.0", + "_inBundle": false, + "_integrity": "sha512-se5Cd+js9dXJnu6Ag2JFc00t+HmHOen+8Q+L7O9zI0PqQXr20uk2J0XQqMxZEeo5U50o8Nvmmx7dZrl+Ufr35A==", + "_location": "/assert", + "_phantomChildren": {}, + "_requested": { + "type": "tag", + "registry": true, + "raw": "assert", + "name": "assert", + "escapedName": "assert", + "rawSpec": "", + "saveSpec": null, + "fetchSpec": "latest" + }, + "_requiredBy": [ + "#USER", + "/" + ], + "_resolved": "https://registry.npmjs.org/assert/-/assert-2.0.0.tgz", + "_shasum": "95fc1c616d48713510680f2eaf2d10dd22e02d32", + "_spec": "assert", + "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/2.5", + "bugs": { + "url": "https://github.com/browserify/commonjs-assert/issues" + }, + "bundleDependencies": false, + "dependencies": { + "es6-object-assign": "^1.1.0", + "is-nan": "^1.2.1", + "object-is": "^1.0.1", + "util": "^0.12.0" + }, + "deprecated": false, + "description": "The assert module from Node.js, for the browser.", + "devDependencies": { + "@babel/cli": "^7.4.4", + "@babel/core": "^7.4.4", + "@babel/preset-env": "^7.4.4", + "airtap": "^2.0.2", + "array-fill": "^1.2.0", + "core-js": "^3.0.1", + "cross-env": "^5.2.0", + "object.entries": "^1.1.0", + "object.getownpropertydescriptors": "^2.0.3", + "tape": "^4.10.1" + }, + "files": [ + "build/assert.js", + "build/internal" + ], + "homepage": "https://github.com/browserify/commonjs-assert", + "keywords": [ + "assert", + "browser" + ], + "license": "MIT", + "main": "build/assert.js", + "name": "assert", + "repository": { + "type": "git", + "url": "git+https://github.com/browserify/commonjs-assert.git" + }, + "scripts": { + "build": "babel assert.js test.js --out-dir build && babel internal --out-dir build/internal && babel test --out-dir build/test", + "dev": "babel assert.js test.js --watch --out-dir build & babel internal --watch --out-dir build/internal & babel test --watch --out-dir build/test", + "prepare": "npm run build", + "test": "npm run build && npm run test:nobuild", + "test:browsers": "airtap build/test.js", + "test:browsers:local": "npm run test:browsers -- --local", + "test:nobuild": "node build/test.js", + "test:source": "node test.js" + }, + "version": "2.0.0" +} diff --git a/scripts/2.5/node_modules/bson/HISTORY.md b/scripts/2.5/node_modules/bson/HISTORY.md new file mode 100644 index 00000000..0da8acef --- /dev/null +++ b/scripts/2.5/node_modules/bson/HISTORY.md @@ -0,0 +1,268 @@ + +## [1.1.1](https://github.com/mongodb/js-bson/compare/v1.1.0...v1.1.1) (2019-03-08) + + +### Bug Fixes + +* **object-id:** support 4.x->1.x interop for MinKey and ObjectId ([53419a5](https://github.com/mongodb/js-bson/commit/53419a5)) + + +### Features + +* replace new Buffer with modern versions ([24aefba](https://github.com/mongodb/js-bson/commit/24aefba)) + + + + +# [1.1.0](https://github.com/mongodb/js-bson/compare/v1.0.9...v1.1.0) (2018-08-13) + + +### Bug Fixes + +* **serializer:** do not use checkKeys for $clusterTime ([573e141](https://github.com/mongodb/js-bson/commit/573e141)) + + + + +## [1.0.9](https://github.com/mongodb/js-bson/compare/v1.0.8...v1.0.9) (2018-06-07) + + +### Bug Fixes + +* **serializer:** remove use of `const` ([5feb12f](https://github.com/mongodb/js-bson/commit/5feb12f)) + + + + +## [1.0.7](https://github.com/mongodb/js-bson/compare/v1.0.6...v1.0.7) (2018-06-06) + + +### Bug Fixes + +* **binary:** add type checking for buffer ([26b05b5](https://github.com/mongodb/js-bson/commit/26b05b5)) +* **bson:** fix custom inspect property ([080323b](https://github.com/mongodb/js-bson/commit/080323b)) +* **readme:** clarify documentation about deserialize methods ([20f764c](https://github.com/mongodb/js-bson/commit/20f764c)) +* **serialization:** normalize function stringification ([1320c10](https://github.com/mongodb/js-bson/commit/1320c10)) + + + + +## [1.0.6](https://github.com/mongodb/js-bson/compare/v1.0.5...v1.0.6) (2018-03-12) + + +### Features + +* **serialization:** support arbitrary sizes for the internal serialization buffer ([abe97bc](https://github.com/mongodb/js-bson/commit/abe97bc)) + + + + +## 1.0.5 (2018-02-26) + + +### Bug Fixes + +* **decimal128:** add basic guard against REDOS attacks ([bd61c45](https://github.com/mongodb/js-bson/commit/bd61c45)) +* **objectid:** if pid is 1, use random value ([e188ae6](https://github.com/mongodb/js-bson/commit/e188ae6)) + + + +1.0.4 2016-01-11 +---------------- +- #204 remove Buffer.from as it's partially broken in early 4.x.x. series of node releases. + +1.0.3 2016-01-03 +---------------- +- Fixed toString for ObjectId so it will work with inspect. + +1.0.2 2016-01-02 +---------------- +- Minor optimizations for ObjectID to use Buffer.from where available. + +1.0.1 2016-12-06 +---------------- +- Reverse behavior for undefined to be serialized as NULL. MongoDB 3.4 does not allow for undefined comparisons. + +1.0.0 2016-12-06 +---------------- +- Introduced new BSON API and documentation. + +0.5.7 2016-11-18 +----------------- +- NODE-848 BSON Regex flags must be alphabetically ordered. + +0.5.6 2016-10-19 +----------------- +- NODE-833, Detects cyclic dependencies in documents and throws error if one is found. +- Fix(deserializer): corrected the check for (size + index) comparison… (Issue #195, https://github.com/JoelParke). + +0.5.5 2016-09-15 +----------------- +- Added DBPointer up conversion to DBRef + +0.5.4 2016-08-23 +----------------- +- Added promoteValues flag (default to true) allowing user to specify if deserialization should be into wrapper classes only. + +0.5.3 2016-07-11 +----------------- +- Throw error if ObjectId is not a string or a buffer. + +0.5.2 2016-07-11 +----------------- +- All values encoded big-endian style for ObjectId. + +0.5.1 2016-07-11 +----------------- +- Fixed encoding/decoding issue in ObjectId timestamp generation. +- Removed BinaryParser dependency from the serializer/deserializer. + +0.5.0 2016-07-05 +----------------- +- Added Decimal128 type and extended test suite to include entire bson corpus. + +0.4.23 2016-04-08 +----------------- +- Allow for proper detection of ObjectId or objects that look like ObjectId, improving compatibility across third party libraries. +- Remove one package from dependency due to having been pulled from NPM. + +0.4.22 2016-03-04 +----------------- +- Fix "TypeError: data.copy is not a function" in Electron (Issue #170, https://github.com/kangas). +- Fixed issue with undefined type on deserializing. + +0.4.21 2016-01-12 +----------------- +- Minor optimizations to avoid non needed object creation. + +0.4.20 2015-10-15 +----------------- +- Added bower file to repository. +- Fixed browser pid sometimes set greater than 0xFFFF on browsers (Issue #155, https://github.com/rahatarmanahmed) + +0.4.19 2015-10-15 +----------------- +- Remove all support for bson-ext. + +0.4.18 2015-10-15 +----------------- +- ObjectID equality check should return boolean instead of throwing exception for invalid oid string #139 +- add option for deserializing binary into Buffer object #116 + +0.4.17 2015-10-15 +----------------- +- Validate regexp string for null bytes and throw if there is one. + +0.4.16 2015-10-07 +----------------- +- Fixed issue with return statement in Map.js. + +0.4.15 2015-10-06 +----------------- +- Exposed Map correctly via index.js file. + +0.4.14 2015-10-06 +----------------- +- Exposed Map correctly via bson.js file. + +0.4.13 2015-10-06 +----------------- +- Added ES6 Map type serialization as well as a polyfill for ES5. + +0.4.12 2015-09-18 +----------------- +- Made ignore undefined an optional parameter. + +0.4.11 2015-08-06 +----------------- +- Minor fix for invalid key checking. + +0.4.10 2015-08-06 +----------------- +- NODE-38 Added new BSONRegExp type to allow direct serialization to MongoDB type. +- Some performance improvements by in lining code. + +0.4.9 2015-08-06 +---------------- +- Undefined fields are omitted from serialization in objects. + +0.4.8 2015-07-14 +---------------- +- Fixed size validation to ensure we can deserialize from dumped files. + +0.4.7 2015-06-26 +---------------- +- Added ability to instruct deserializer to return raw BSON buffers for named array fields. +- Minor deserialization optimization by moving inlined function out. + +0.4.6 2015-06-17 +---------------- +- Fixed serializeWithBufferAndIndex bug. + +0.4.5 2015-06-17 +---------------- +- Removed any references to the shared buffer to avoid non GC collectible bson instances. + +0.4.4 2015-06-17 +---------------- +- Fixed rethrowing of error when not RangeError. + +0.4.3 2015-06-17 +---------------- +- Start buffer at 64K and double as needed, meaning we keep a low memory profile until needed. + +0.4.2 2015-06-16 +---------------- +- More fixes for corrupt Bson + +0.4.1 2015-06-16 +---------------- +- More fixes for corrupt Bson + +0.4.0 2015-06-16 +---------------- +- New JS serializer serializing into a single buffer then copying out the new buffer. Performance is similar to current C++ parser. +- Removed bson-ext extension dependency for now. + +0.3.2 2015-03-27 +---------------- +- Removed node-gyp from install script in package.json. + +0.3.1 2015-03-27 +---------------- +- Return pure js version on native() call if failed to initialize. + +0.3.0 2015-03-26 +---------------- +- Pulled out all C++ code into bson-ext and made it an optional dependency. + +0.2.21 2015-03-21 +----------------- +- Updated Nan to 1.7.0 to support io.js and node 0.12.0 + +0.2.19 2015-02-16 +----------------- +- Updated Nan to 1.6.2 to support io.js and node 0.12.0 + +0.2.18 2015-01-20 +----------------- +- Updated Nan to 1.5.1 to support io.js + +0.2.16 2014-12-17 +----------------- +- Made pid cycle on 0xffff to avoid weird overflows on creation of ObjectID's + +0.2.12 2014-08-24 +----------------- +- Fixes for fortify review of c++ extension +- toBSON correctly allows returns of non objects + +0.2.3 2013-10-01 +---------------- +- Drying of ObjectId code for generation of id (Issue #54, https://github.com/moredip) +- Fixed issue where corrupt CString's could cause endless loop +- Support for Node 0.11.X > (Issue #49, https://github.com/kkoopa) + +0.1.4 2012-09-25 +---------------- +- Added precompiled c++ native extensions for win32 ia32 and x64 diff --git a/scripts/2.5/node_modules/bson/LICENSE.md b/scripts/2.5/node_modules/bson/LICENSE.md new file mode 100644 index 00000000..261eeb9e --- /dev/null +++ b/scripts/2.5/node_modules/bson/LICENSE.md @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/scripts/2.5/node_modules/bson/README.md b/scripts/2.5/node_modules/bson/README.md new file mode 100644 index 00000000..06883410 --- /dev/null +++ b/scripts/2.5/node_modules/bson/README.md @@ -0,0 +1,170 @@ +# BSON parser + +BSON is short for Bin­ary JSON and is the bin­ary-en­coded seri­al­iz­a­tion of JSON-like doc­u­ments. You can learn more about it in [the specification](http://bsonspec.org). + +This browser version of the BSON parser is compiled using [webpack](https://webpack.js.org/) and the current version is pre-compiled in the `browser_build` directory. + +This is the default BSON parser, however, there is a C++ Node.js addon version as well that does not support the browser. It can be found at [mongod-js/bson-ext](https://github.com/mongodb-js/bson-ext). + +## Usage + +To build a new version perform the following operations: + +``` +npm install +npm run build +``` + +A simple example of how to use BSON in the browser: + +```html + + + +``` + +A simple example of how to use BSON in `Node.js`: + +```js +// Get BSON parser class +var BSON = require('bson') +// Get the Long type +var Long = BSON.Long; +// Create a bson parser instance +var bson = new BSON(); + +// Serialize document +var doc = { long: Long.fromNumber(100) } + +// Serialize a document +var data = bson.serialize(doc) +console.log('data:', data) + +// Deserialize the resulting Buffer +var doc_2 = bson.deserialize(data) +console.log('doc_2:', doc_2) +``` + +## Installation + +`npm install bson` + +## API + +### BSON types + +For all BSON types documentation, please refer to the following sources: + * [MongoDB BSON Type Reference](https://docs.mongodb.com/manual/reference/bson-types/) + * [BSON Spec](https://bsonspec.org/) + +### BSON serialization and deserialiation + +**`new BSON()`** - Creates a new BSON serializer/deserializer you can use to serialize and deserialize BSON. + +#### BSON.serialize + +The BSON `serialize` method takes a JavaScript object and an optional options object and returns a Node.js Buffer. + + * `BSON.serialize(object, options)` + * @param {Object} object the JavaScript object to serialize. + * @param {Boolean} [options.checkKeys=false] the serializer will check if keys are valid. + * @param {Boolean} [options.serializeFunctions=false] serialize the JavaScript functions. + * @param {Boolean} [options.ignoreUndefined=true] + * @return {Buffer} returns a Buffer instance. + +#### BSON.serializeWithBufferAndIndex + +The BSON `serializeWithBufferAndIndex` method takes an object, a target buffer instance and an optional options object and returns the end serialization index in the final buffer. + + * `BSON.serializeWithBufferAndIndex(object, buffer, options)` + * @param {Object} object the JavaScript object to serialize. + * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. + * @param {Boolean} [options.checkKeys=false] the serializer will check if keys are valid. + * @param {Boolean} [options.serializeFunctions=false] serialize the JavaScript functions. + * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields. + * @param {Number} [options.index=0] the index in the buffer where we wish to start serializing into. + * @return {Number} returns the index pointing to the last written byte in the buffer. + +#### BSON.calculateObjectSize + +The BSON `calculateObjectSize` method takes a JavaScript object and an optional options object and returns the size of the BSON object. + + * `BSON.calculateObjectSize(object, options)` + * @param {Object} object the JavaScript object to serialize. + * @param {Boolean} [options.serializeFunctions=false] serialize the JavaScript functions. + * @param {Boolean} [options.ignoreUndefined=true] + * @return {Buffer} returns a Buffer instance. + +#### BSON.deserialize + +The BSON `deserialize` method takes a Node.js Buffer and an optional options object and returns a deserialized JavaScript object. + + * `BSON.deserialize(buffer, options)` + * @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized. + * @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse. + * @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function. + * @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits + * @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a Node.js Buffer instance. + * @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types. + * @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer. + * @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances. + * @return {Object} returns the deserialized Javascript Object. + +#### BSON.deserializeStream + +The BSON `deserializeStream` method takes a Node.js Buffer, `startIndex` and allow more control over deserialization of a Buffer containing concatenated BSON documents. + + * `BSON.deserializeStream(buffer, startIndex, numberOfDocuments, documents, docStartIndex, options)` + * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. + * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. + * @param {Number} numberOfDocuments number of documents to deserialize. + * @param {Array} documents an array where to store the deserialized documents. + * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. + * @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized. + * @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse. + * @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function. + * @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits + * @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a Node.js Buffer instance. + * @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types. + * @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer. + * @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances. + * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. + +## FAQ + +#### Why does `undefined` get converted to `null`? + +The `undefined` BSON type has been [deprecated for many years](http://bsonspec.org/spec.html), so this library has dropped support for it. Use the `ignoreUndefined` option (for example, from the [driver](http://mongodb.github.io/node-mongodb-native/2.2/api/MongoClient.html#connect) ) to instead remove `undefined` keys. + +#### How do I add custom serialization logic? + +This library looks for `toBSON()` functions on every path, and calls the `toBSON()` function to get the value to serialize. + +```javascript +var bson = new BSON(); + +class CustomSerialize { + toBSON() { + return 42; + } +} + +const obj = { answer: new CustomSerialize() }; +// "{ answer: 42 }" +console.log(bson.deserialize(bson.serialize(obj))); +``` diff --git a/scripts/2.5/node_modules/bson/bower.json b/scripts/2.5/node_modules/bson/bower.json new file mode 100644 index 00000000..b32140ea --- /dev/null +++ b/scripts/2.5/node_modules/bson/bower.json @@ -0,0 +1,25 @@ +{ + "name": "bson", + "description": "A bson parser for node.js and the browser", + "keywords": [ + "mongodb", + "bson", + "parser" + ], + "author": "Christian Amor Kvalheim ", + "main": "./browser_build/bson.js", + "license": "Apache-2.0", + "moduleType": [ + "globals", + "node" + ], + "ignore": [ + "**/.*", + "alternate_parsers", + "benchmarks", + "bower_components", + "node_modules", + "test", + "tools" + ] +} diff --git a/scripts/2.5/node_modules/bson/browser_build/bson.js b/scripts/2.5/node_modules/bson/browser_build/bson.js new file mode 100644 index 00000000..e601c992 --- /dev/null +++ b/scripts/2.5/node_modules/bson/browser_build/bson.js @@ -0,0 +1,17769 @@ +(function webpackUniversalModuleDefinition(root, factory) { + if(typeof exports === 'object' && typeof module === 'object') + module.exports = factory(); + else if(typeof define === 'function' && define.amd) + define([], factory); + else { + var a = factory(); + for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i]; + } +})(this, function() { +return /******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; + +/******/ // The require function +/******/ function __webpack_require__(moduleId) { + +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) +/******/ return installedModules[moduleId].exports; + +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ exports: {}, +/******/ id: moduleId, +/******/ loaded: false +/******/ }; + +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); + +/******/ // Flag the module as loaded +/******/ module.loaded = true; + +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } + + +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; + +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; + +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = "/"; + +/******/ // Load entry module and return exports +/******/ return __webpack_require__(0); +/******/ }) +/************************************************************************/ +/******/ ([ +/* 0 */ +/***/ (function(module, exports, __webpack_require__) { + + __webpack_require__(1); + module.exports = __webpack_require__(327); + + +/***/ }), +/* 1 */ +/***/ (function(module, exports, __webpack_require__) { + + /* WEBPACK VAR INJECTION */(function(global) {"use strict"; + + __webpack_require__(2); + + __webpack_require__(323); + + __webpack_require__(324); + + if (global._babelPolyfill) { + throw new Error("only one instance of babel-polyfill is allowed"); + } + global._babelPolyfill = true; + + var DEFINE_PROPERTY = "defineProperty"; + function define(O, key, value) { + O[key] || Object[DEFINE_PROPERTY](O, key, { + writable: true, + configurable: true, + value: value + }); + } + + define(String.prototype, "padLeft", "".padStart); + define(String.prototype, "padRight", "".padEnd); + + "pop,reverse,shift,keys,values,entries,indexOf,every,some,forEach,map,filter,find,findIndex,includes,join,slice,concat,push,splice,unshift,sort,lastIndexOf,reduce,reduceRight,copyWithin,fill".split(",").forEach(function (key) { + [][key] && define(Array, key, Function.call.bind([][key])); + }); + /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) + +/***/ }), +/* 2 */ +/***/ (function(module, exports, __webpack_require__) { + + __webpack_require__(3); + __webpack_require__(51); + __webpack_require__(52); + __webpack_require__(53); + __webpack_require__(54); + __webpack_require__(56); + __webpack_require__(59); + __webpack_require__(60); + __webpack_require__(61); + __webpack_require__(62); + __webpack_require__(63); + __webpack_require__(64); + __webpack_require__(65); + __webpack_require__(66); + __webpack_require__(67); + __webpack_require__(69); + __webpack_require__(71); + __webpack_require__(73); + __webpack_require__(75); + __webpack_require__(78); + __webpack_require__(79); + __webpack_require__(80); + __webpack_require__(84); + __webpack_require__(86); + __webpack_require__(88); + __webpack_require__(91); + __webpack_require__(92); + __webpack_require__(93); + __webpack_require__(94); + __webpack_require__(96); + __webpack_require__(97); + __webpack_require__(98); + __webpack_require__(99); + __webpack_require__(100); + __webpack_require__(101); + __webpack_require__(102); + __webpack_require__(104); + __webpack_require__(105); + __webpack_require__(106); + __webpack_require__(108); + __webpack_require__(109); + __webpack_require__(110); + __webpack_require__(112); + __webpack_require__(114); + __webpack_require__(115); + __webpack_require__(116); + __webpack_require__(117); + __webpack_require__(118); + __webpack_require__(119); + __webpack_require__(120); + __webpack_require__(121); + __webpack_require__(122); + __webpack_require__(123); + __webpack_require__(124); + __webpack_require__(125); + __webpack_require__(126); + __webpack_require__(131); + __webpack_require__(132); + __webpack_require__(136); + __webpack_require__(137); + __webpack_require__(138); + __webpack_require__(139); + __webpack_require__(141); + __webpack_require__(142); + __webpack_require__(143); + __webpack_require__(144); + __webpack_require__(145); + __webpack_require__(146); + __webpack_require__(147); + __webpack_require__(148); + __webpack_require__(149); + __webpack_require__(150); + __webpack_require__(151); + __webpack_require__(152); + __webpack_require__(153); + __webpack_require__(154); + __webpack_require__(155); + __webpack_require__(157); + __webpack_require__(158); + __webpack_require__(160); + __webpack_require__(161); + __webpack_require__(167); + __webpack_require__(168); + __webpack_require__(170); + __webpack_require__(171); + __webpack_require__(172); + __webpack_require__(176); + __webpack_require__(177); + __webpack_require__(178); + __webpack_require__(179); + __webpack_require__(180); + __webpack_require__(182); + __webpack_require__(183); + __webpack_require__(184); + __webpack_require__(185); + __webpack_require__(188); + __webpack_require__(190); + __webpack_require__(191); + __webpack_require__(192); + __webpack_require__(194); + __webpack_require__(196); + __webpack_require__(198); + __webpack_require__(199); + __webpack_require__(200); + __webpack_require__(202); + __webpack_require__(203); + __webpack_require__(204); + __webpack_require__(205); + __webpack_require__(216); + __webpack_require__(220); + __webpack_require__(221); + __webpack_require__(223); + __webpack_require__(224); + __webpack_require__(228); + __webpack_require__(229); + __webpack_require__(231); + __webpack_require__(232); + __webpack_require__(233); + __webpack_require__(234); + __webpack_require__(235); + __webpack_require__(236); + __webpack_require__(237); + __webpack_require__(238); + __webpack_require__(239); + __webpack_require__(240); + __webpack_require__(241); + __webpack_require__(242); + __webpack_require__(243); + __webpack_require__(244); + __webpack_require__(245); + __webpack_require__(246); + __webpack_require__(247); + __webpack_require__(248); + __webpack_require__(249); + __webpack_require__(251); + __webpack_require__(252); + __webpack_require__(253); + __webpack_require__(254); + __webpack_require__(255); + __webpack_require__(257); + __webpack_require__(258); + __webpack_require__(259); + __webpack_require__(261); + __webpack_require__(262); + __webpack_require__(263); + __webpack_require__(264); + __webpack_require__(265); + __webpack_require__(266); + __webpack_require__(267); + __webpack_require__(268); + __webpack_require__(270); + __webpack_require__(271); + __webpack_require__(273); + __webpack_require__(274); + __webpack_require__(275); + __webpack_require__(276); + __webpack_require__(279); + __webpack_require__(280); + __webpack_require__(282); + __webpack_require__(283); + __webpack_require__(284); + __webpack_require__(285); + __webpack_require__(287); + __webpack_require__(288); + __webpack_require__(289); + __webpack_require__(290); + __webpack_require__(291); + __webpack_require__(292); + __webpack_require__(293); + __webpack_require__(294); + __webpack_require__(295); + __webpack_require__(296); + __webpack_require__(298); + __webpack_require__(299); + __webpack_require__(300); + __webpack_require__(301); + __webpack_require__(302); + __webpack_require__(303); + __webpack_require__(304); + __webpack_require__(305); + __webpack_require__(306); + __webpack_require__(307); + __webpack_require__(308); + __webpack_require__(310); + __webpack_require__(311); + __webpack_require__(312); + __webpack_require__(313); + __webpack_require__(314); + __webpack_require__(315); + __webpack_require__(316); + __webpack_require__(317); + __webpack_require__(318); + __webpack_require__(319); + __webpack_require__(320); + __webpack_require__(321); + __webpack_require__(322); + module.exports = __webpack_require__(9); + + +/***/ }), +/* 3 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // ECMAScript 6 symbols shim + var global = __webpack_require__(4); + var has = __webpack_require__(5); + var DESCRIPTORS = __webpack_require__(6); + var $export = __webpack_require__(8); + var redefine = __webpack_require__(18); + var META = __webpack_require__(22).KEY; + var $fails = __webpack_require__(7); + var shared = __webpack_require__(23); + var setToStringTag = __webpack_require__(25); + var uid = __webpack_require__(19); + var wks = __webpack_require__(26); + var wksExt = __webpack_require__(27); + var wksDefine = __webpack_require__(28); + var enumKeys = __webpack_require__(29); + var isArray = __webpack_require__(44); + var anObject = __webpack_require__(12); + var isObject = __webpack_require__(13); + var toIObject = __webpack_require__(32); + var toPrimitive = __webpack_require__(16); + var createDesc = __webpack_require__(17); + var _create = __webpack_require__(45); + var gOPNExt = __webpack_require__(48); + var $GOPD = __webpack_require__(50); + var $DP = __webpack_require__(11); + var $keys = __webpack_require__(30); + var gOPD = $GOPD.f; + var dP = $DP.f; + var gOPN = gOPNExt.f; + var $Symbol = global.Symbol; + var $JSON = global.JSON; + var _stringify = $JSON && $JSON.stringify; + var PROTOTYPE = 'prototype'; + var HIDDEN = wks('_hidden'); + var TO_PRIMITIVE = wks('toPrimitive'); + var isEnum = {}.propertyIsEnumerable; + var SymbolRegistry = shared('symbol-registry'); + var AllSymbols = shared('symbols'); + var OPSymbols = shared('op-symbols'); + var ObjectProto = Object[PROTOTYPE]; + var USE_NATIVE = typeof $Symbol == 'function'; + var QObject = global.QObject; + // Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173 + var setter = !QObject || !QObject[PROTOTYPE] || !QObject[PROTOTYPE].findChild; + + // fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687 + var setSymbolDesc = DESCRIPTORS && $fails(function () { + return _create(dP({}, 'a', { + get: function () { return dP(this, 'a', { value: 7 }).a; } + })).a != 7; + }) ? function (it, key, D) { + var protoDesc = gOPD(ObjectProto, key); + if (protoDesc) delete ObjectProto[key]; + dP(it, key, D); + if (protoDesc && it !== ObjectProto) dP(ObjectProto, key, protoDesc); + } : dP; + + var wrap = function (tag) { + var sym = AllSymbols[tag] = _create($Symbol[PROTOTYPE]); + sym._k = tag; + return sym; + }; + + var isSymbol = USE_NATIVE && typeof $Symbol.iterator == 'symbol' ? function (it) { + return typeof it == 'symbol'; + } : function (it) { + return it instanceof $Symbol; + }; + + var $defineProperty = function defineProperty(it, key, D) { + if (it === ObjectProto) $defineProperty(OPSymbols, key, D); + anObject(it); + key = toPrimitive(key, true); + anObject(D); + if (has(AllSymbols, key)) { + if (!D.enumerable) { + if (!has(it, HIDDEN)) dP(it, HIDDEN, createDesc(1, {})); + it[HIDDEN][key] = true; + } else { + if (has(it, HIDDEN) && it[HIDDEN][key]) it[HIDDEN][key] = false; + D = _create(D, { enumerable: createDesc(0, false) }); + } return setSymbolDesc(it, key, D); + } return dP(it, key, D); + }; + var $defineProperties = function defineProperties(it, P) { + anObject(it); + var keys = enumKeys(P = toIObject(P)); + var i = 0; + var l = keys.length; + var key; + while (l > i) $defineProperty(it, key = keys[i++], P[key]); + return it; + }; + var $create = function create(it, P) { + return P === undefined ? _create(it) : $defineProperties(_create(it), P); + }; + var $propertyIsEnumerable = function propertyIsEnumerable(key) { + var E = isEnum.call(this, key = toPrimitive(key, true)); + if (this === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key)) return false; + return E || !has(this, key) || !has(AllSymbols, key) || has(this, HIDDEN) && this[HIDDEN][key] ? E : true; + }; + var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(it, key) { + it = toIObject(it); + key = toPrimitive(key, true); + if (it === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key)) return; + var D = gOPD(it, key); + if (D && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key])) D.enumerable = true; + return D; + }; + var $getOwnPropertyNames = function getOwnPropertyNames(it) { + var names = gOPN(toIObject(it)); + var result = []; + var i = 0; + var key; + while (names.length > i) { + if (!has(AllSymbols, key = names[i++]) && key != HIDDEN && key != META) result.push(key); + } return result; + }; + var $getOwnPropertySymbols = function getOwnPropertySymbols(it) { + var IS_OP = it === ObjectProto; + var names = gOPN(IS_OP ? OPSymbols : toIObject(it)); + var result = []; + var i = 0; + var key; + while (names.length > i) { + if (has(AllSymbols, key = names[i++]) && (IS_OP ? has(ObjectProto, key) : true)) result.push(AllSymbols[key]); + } return result; + }; + + // 19.4.1.1 Symbol([description]) + if (!USE_NATIVE) { + $Symbol = function Symbol() { + if (this instanceof $Symbol) throw TypeError('Symbol is not a constructor!'); + var tag = uid(arguments.length > 0 ? arguments[0] : undefined); + var $set = function (value) { + if (this === ObjectProto) $set.call(OPSymbols, value); + if (has(this, HIDDEN) && has(this[HIDDEN], tag)) this[HIDDEN][tag] = false; + setSymbolDesc(this, tag, createDesc(1, value)); + }; + if (DESCRIPTORS && setter) setSymbolDesc(ObjectProto, tag, { configurable: true, set: $set }); + return wrap(tag); + }; + redefine($Symbol[PROTOTYPE], 'toString', function toString() { + return this._k; + }); + + $GOPD.f = $getOwnPropertyDescriptor; + $DP.f = $defineProperty; + __webpack_require__(49).f = gOPNExt.f = $getOwnPropertyNames; + __webpack_require__(43).f = $propertyIsEnumerable; + __webpack_require__(42).f = $getOwnPropertySymbols; + + if (DESCRIPTORS && !__webpack_require__(24)) { + redefine(ObjectProto, 'propertyIsEnumerable', $propertyIsEnumerable, true); + } + + wksExt.f = function (name) { + return wrap(wks(name)); + }; + } + + $export($export.G + $export.W + $export.F * !USE_NATIVE, { Symbol: $Symbol }); + + for (var es6Symbols = ( + // 19.4.2.2, 19.4.2.3, 19.4.2.4, 19.4.2.6, 19.4.2.8, 19.4.2.9, 19.4.2.10, 19.4.2.11, 19.4.2.12, 19.4.2.13, 19.4.2.14 + 'hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables' + ).split(','), j = 0; es6Symbols.length > j;)wks(es6Symbols[j++]); + + for (var wellKnownSymbols = $keys(wks.store), k = 0; wellKnownSymbols.length > k;) wksDefine(wellKnownSymbols[k++]); + + $export($export.S + $export.F * !USE_NATIVE, 'Symbol', { + // 19.4.2.1 Symbol.for(key) + 'for': function (key) { + return has(SymbolRegistry, key += '') + ? SymbolRegistry[key] + : SymbolRegistry[key] = $Symbol(key); + }, + // 19.4.2.5 Symbol.keyFor(sym) + keyFor: function keyFor(sym) { + if (!isSymbol(sym)) throw TypeError(sym + ' is not a symbol!'); + for (var key in SymbolRegistry) if (SymbolRegistry[key] === sym) return key; + }, + useSetter: function () { setter = true; }, + useSimple: function () { setter = false; } + }); + + $export($export.S + $export.F * !USE_NATIVE, 'Object', { + // 19.1.2.2 Object.create(O [, Properties]) + create: $create, + // 19.1.2.4 Object.defineProperty(O, P, Attributes) + defineProperty: $defineProperty, + // 19.1.2.3 Object.defineProperties(O, Properties) + defineProperties: $defineProperties, + // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P) + getOwnPropertyDescriptor: $getOwnPropertyDescriptor, + // 19.1.2.7 Object.getOwnPropertyNames(O) + getOwnPropertyNames: $getOwnPropertyNames, + // 19.1.2.8 Object.getOwnPropertySymbols(O) + getOwnPropertySymbols: $getOwnPropertySymbols + }); + + // 24.3.2 JSON.stringify(value [, replacer [, space]]) + $JSON && $export($export.S + $export.F * (!USE_NATIVE || $fails(function () { + var S = $Symbol(); + // MS Edge converts symbol values to JSON as {} + // WebKit converts symbol values to JSON as null + // V8 throws on boxed symbols + return _stringify([S]) != '[null]' || _stringify({ a: S }) != '{}' || _stringify(Object(S)) != '{}'; + })), 'JSON', { + stringify: function stringify(it) { + var args = [it]; + var i = 1; + var replacer, $replacer; + while (arguments.length > i) args.push(arguments[i++]); + $replacer = replacer = args[1]; + if (!isObject(replacer) && it === undefined || isSymbol(it)) return; // IE8 returns string on undefined + if (!isArray(replacer)) replacer = function (key, value) { + if (typeof $replacer == 'function') value = $replacer.call(this, key, value); + if (!isSymbol(value)) return value; + }; + args[1] = replacer; + return _stringify.apply($JSON, args); + } + }); + + // 19.4.3.4 Symbol.prototype[@@toPrimitive](hint) + $Symbol[PROTOTYPE][TO_PRIMITIVE] || __webpack_require__(10)($Symbol[PROTOTYPE], TO_PRIMITIVE, $Symbol[PROTOTYPE].valueOf); + // 19.4.3.5 Symbol.prototype[@@toStringTag] + setToStringTag($Symbol, 'Symbol'); + // 20.2.1.9 Math[@@toStringTag] + setToStringTag(Math, 'Math', true); + // 24.3.3 JSON[@@toStringTag] + setToStringTag(global.JSON, 'JSON', true); + + +/***/ }), +/* 4 */ +/***/ (function(module, exports) { + + // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 + var global = module.exports = typeof window != 'undefined' && window.Math == Math + ? window : typeof self != 'undefined' && self.Math == Math ? self + // eslint-disable-next-line no-new-func + : Function('return this')(); + if (typeof __g == 'number') __g = global; // eslint-disable-line no-undef + + +/***/ }), +/* 5 */ +/***/ (function(module, exports) { + + var hasOwnProperty = {}.hasOwnProperty; + module.exports = function (it, key) { + return hasOwnProperty.call(it, key); + }; + + +/***/ }), +/* 6 */ +/***/ (function(module, exports, __webpack_require__) { + + // Thank's IE8 for his funny defineProperty + module.exports = !__webpack_require__(7)(function () { + return Object.defineProperty({}, 'a', { get: function () { return 7; } }).a != 7; + }); + + +/***/ }), +/* 7 */ +/***/ (function(module, exports) { + + module.exports = function (exec) { + try { + return !!exec(); + } catch (e) { + return true; + } + }; + + +/***/ }), +/* 8 */ +/***/ (function(module, exports, __webpack_require__) { + + var global = __webpack_require__(4); + var core = __webpack_require__(9); + var hide = __webpack_require__(10); + var redefine = __webpack_require__(18); + var ctx = __webpack_require__(20); + var PROTOTYPE = 'prototype'; + + var $export = function (type, name, source) { + var IS_FORCED = type & $export.F; + var IS_GLOBAL = type & $export.G; + var IS_STATIC = type & $export.S; + var IS_PROTO = type & $export.P; + var IS_BIND = type & $export.B; + var target = IS_GLOBAL ? global : IS_STATIC ? global[name] || (global[name] = {}) : (global[name] || {})[PROTOTYPE]; + var exports = IS_GLOBAL ? core : core[name] || (core[name] = {}); + var expProto = exports[PROTOTYPE] || (exports[PROTOTYPE] = {}); + var key, own, out, exp; + if (IS_GLOBAL) source = name; + for (key in source) { + // contains in native + own = !IS_FORCED && target && target[key] !== undefined; + // export native or passed + out = (own ? target : source)[key]; + // bind timers to global for call from export context + exp = IS_BIND && own ? ctx(out, global) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out; + // extend global + if (target) redefine(target, key, out, type & $export.U); + // export + if (exports[key] != out) hide(exports, key, exp); + if (IS_PROTO && expProto[key] != out) expProto[key] = out; + } + }; + global.core = core; + // type bitmap + $export.F = 1; // forced + $export.G = 2; // global + $export.S = 4; // static + $export.P = 8; // proto + $export.B = 16; // bind + $export.W = 32; // wrap + $export.U = 64; // safe + $export.R = 128; // real proto method for `library` + module.exports = $export; + + +/***/ }), +/* 9 */ +/***/ (function(module, exports) { + + var core = module.exports = { version: '2.5.7' }; + if (typeof __e == 'number') __e = core; // eslint-disable-line no-undef + + +/***/ }), +/* 10 */ +/***/ (function(module, exports, __webpack_require__) { + + var dP = __webpack_require__(11); + var createDesc = __webpack_require__(17); + module.exports = __webpack_require__(6) ? function (object, key, value) { + return dP.f(object, key, createDesc(1, value)); + } : function (object, key, value) { + object[key] = value; + return object; + }; + + +/***/ }), +/* 11 */ +/***/ (function(module, exports, __webpack_require__) { + + var anObject = __webpack_require__(12); + var IE8_DOM_DEFINE = __webpack_require__(14); + var toPrimitive = __webpack_require__(16); + var dP = Object.defineProperty; + + exports.f = __webpack_require__(6) ? Object.defineProperty : function defineProperty(O, P, Attributes) { + anObject(O); + P = toPrimitive(P, true); + anObject(Attributes); + if (IE8_DOM_DEFINE) try { + return dP(O, P, Attributes); + } catch (e) { /* empty */ } + if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported!'); + if ('value' in Attributes) O[P] = Attributes.value; + return O; + }; + + +/***/ }), +/* 12 */ +/***/ (function(module, exports, __webpack_require__) { + + var isObject = __webpack_require__(13); + module.exports = function (it) { + if (!isObject(it)) throw TypeError(it + ' is not an object!'); + return it; + }; + + +/***/ }), +/* 13 */ +/***/ (function(module, exports) { + + module.exports = function (it) { + return typeof it === 'object' ? it !== null : typeof it === 'function'; + }; + + +/***/ }), +/* 14 */ +/***/ (function(module, exports, __webpack_require__) { + + module.exports = !__webpack_require__(6) && !__webpack_require__(7)(function () { + return Object.defineProperty(__webpack_require__(15)('div'), 'a', { get: function () { return 7; } }).a != 7; + }); + + +/***/ }), +/* 15 */ +/***/ (function(module, exports, __webpack_require__) { + + var isObject = __webpack_require__(13); + var document = __webpack_require__(4).document; + // typeof document.createElement is 'object' in old IE + var is = isObject(document) && isObject(document.createElement); + module.exports = function (it) { + return is ? document.createElement(it) : {}; + }; + + +/***/ }), +/* 16 */ +/***/ (function(module, exports, __webpack_require__) { + + // 7.1.1 ToPrimitive(input [, PreferredType]) + var isObject = __webpack_require__(13); + // instead of the ES6 spec version, we didn't implement @@toPrimitive case + // and the second argument - flag - preferred type is a string + module.exports = function (it, S) { + if (!isObject(it)) return it; + var fn, val; + if (S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val; + if (typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it))) return val; + if (!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val; + throw TypeError("Can't convert object to primitive value"); + }; + + +/***/ }), +/* 17 */ +/***/ (function(module, exports) { + + module.exports = function (bitmap, value) { + return { + enumerable: !(bitmap & 1), + configurable: !(bitmap & 2), + writable: !(bitmap & 4), + value: value + }; + }; + + +/***/ }), +/* 18 */ +/***/ (function(module, exports, __webpack_require__) { + + var global = __webpack_require__(4); + var hide = __webpack_require__(10); + var has = __webpack_require__(5); + var SRC = __webpack_require__(19)('src'); + var TO_STRING = 'toString'; + var $toString = Function[TO_STRING]; + var TPL = ('' + $toString).split(TO_STRING); + + __webpack_require__(9).inspectSource = function (it) { + return $toString.call(it); + }; + + (module.exports = function (O, key, val, safe) { + var isFunction = typeof val == 'function'; + if (isFunction) has(val, 'name') || hide(val, 'name', key); + if (O[key] === val) return; + if (isFunction) has(val, SRC) || hide(val, SRC, O[key] ? '' + O[key] : TPL.join(String(key))); + if (O === global) { + O[key] = val; + } else if (!safe) { + delete O[key]; + hide(O, key, val); + } else if (O[key]) { + O[key] = val; + } else { + hide(O, key, val); + } + // add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative + })(Function.prototype, TO_STRING, function toString() { + return typeof this == 'function' && this[SRC] || $toString.call(this); + }); + + +/***/ }), +/* 19 */ +/***/ (function(module, exports) { + + var id = 0; + var px = Math.random(); + module.exports = function (key) { + return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36)); + }; + + +/***/ }), +/* 20 */ +/***/ (function(module, exports, __webpack_require__) { + + // optional / simple context binding + var aFunction = __webpack_require__(21); + module.exports = function (fn, that, length) { + aFunction(fn); + if (that === undefined) return fn; + switch (length) { + case 1: return function (a) { + return fn.call(that, a); + }; + case 2: return function (a, b) { + return fn.call(that, a, b); + }; + case 3: return function (a, b, c) { + return fn.call(that, a, b, c); + }; + } + return function (/* ...args */) { + return fn.apply(that, arguments); + }; + }; + + +/***/ }), +/* 21 */ +/***/ (function(module, exports) { + + module.exports = function (it) { + if (typeof it != 'function') throw TypeError(it + ' is not a function!'); + return it; + }; + + +/***/ }), +/* 22 */ +/***/ (function(module, exports, __webpack_require__) { + + var META = __webpack_require__(19)('meta'); + var isObject = __webpack_require__(13); + var has = __webpack_require__(5); + var setDesc = __webpack_require__(11).f; + var id = 0; + var isExtensible = Object.isExtensible || function () { + return true; + }; + var FREEZE = !__webpack_require__(7)(function () { + return isExtensible(Object.preventExtensions({})); + }); + var setMeta = function (it) { + setDesc(it, META, { value: { + i: 'O' + ++id, // object ID + w: {} // weak collections IDs + } }); + }; + var fastKey = function (it, create) { + // return primitive with prefix + if (!isObject(it)) return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it; + if (!has(it, META)) { + // can't set metadata to uncaught frozen object + if (!isExtensible(it)) return 'F'; + // not necessary to add metadata + if (!create) return 'E'; + // add missing metadata + setMeta(it); + // return object ID + } return it[META].i; + }; + var getWeak = function (it, create) { + if (!has(it, META)) { + // can't set metadata to uncaught frozen object + if (!isExtensible(it)) return true; + // not necessary to add metadata + if (!create) return false; + // add missing metadata + setMeta(it); + // return hash weak collections IDs + } return it[META].w; + }; + // add metadata on freeze-family methods calling + var onFreeze = function (it) { + if (FREEZE && meta.NEED && isExtensible(it) && !has(it, META)) setMeta(it); + return it; + }; + var meta = module.exports = { + KEY: META, + NEED: false, + fastKey: fastKey, + getWeak: getWeak, + onFreeze: onFreeze + }; + + +/***/ }), +/* 23 */ +/***/ (function(module, exports, __webpack_require__) { + + var core = __webpack_require__(9); + var global = __webpack_require__(4); + var SHARED = '__core-js_shared__'; + var store = global[SHARED] || (global[SHARED] = {}); + + (module.exports = function (key, value) { + return store[key] || (store[key] = value !== undefined ? value : {}); + })('versions', []).push({ + version: core.version, + mode: __webpack_require__(24) ? 'pure' : 'global', + copyright: '© 2018 Denis Pushkarev (zloirock.ru)' + }); + + +/***/ }), +/* 24 */ +/***/ (function(module, exports) { + + module.exports = false; + + +/***/ }), +/* 25 */ +/***/ (function(module, exports, __webpack_require__) { + + var def = __webpack_require__(11).f; + var has = __webpack_require__(5); + var TAG = __webpack_require__(26)('toStringTag'); + + module.exports = function (it, tag, stat) { + if (it && !has(it = stat ? it : it.prototype, TAG)) def(it, TAG, { configurable: true, value: tag }); + }; + + +/***/ }), +/* 26 */ +/***/ (function(module, exports, __webpack_require__) { + + var store = __webpack_require__(23)('wks'); + var uid = __webpack_require__(19); + var Symbol = __webpack_require__(4).Symbol; + var USE_SYMBOL = typeof Symbol == 'function'; + + var $exports = module.exports = function (name) { + return store[name] || (store[name] = + USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)('Symbol.' + name)); + }; + + $exports.store = store; + + +/***/ }), +/* 27 */ +/***/ (function(module, exports, __webpack_require__) { + + exports.f = __webpack_require__(26); + + +/***/ }), +/* 28 */ +/***/ (function(module, exports, __webpack_require__) { + + var global = __webpack_require__(4); + var core = __webpack_require__(9); + var LIBRARY = __webpack_require__(24); + var wksExt = __webpack_require__(27); + var defineProperty = __webpack_require__(11).f; + module.exports = function (name) { + var $Symbol = core.Symbol || (core.Symbol = LIBRARY ? {} : global.Symbol || {}); + if (name.charAt(0) != '_' && !(name in $Symbol)) defineProperty($Symbol, name, { value: wksExt.f(name) }); + }; + + +/***/ }), +/* 29 */ +/***/ (function(module, exports, __webpack_require__) { + + // all enumerable object keys, includes symbols + var getKeys = __webpack_require__(30); + var gOPS = __webpack_require__(42); + var pIE = __webpack_require__(43); + module.exports = function (it) { + var result = getKeys(it); + var getSymbols = gOPS.f; + if (getSymbols) { + var symbols = getSymbols(it); + var isEnum = pIE.f; + var i = 0; + var key; + while (symbols.length > i) if (isEnum.call(it, key = symbols[i++])) result.push(key); + } return result; + }; + + +/***/ }), +/* 30 */ +/***/ (function(module, exports, __webpack_require__) { + + // 19.1.2.14 / 15.2.3.14 Object.keys(O) + var $keys = __webpack_require__(31); + var enumBugKeys = __webpack_require__(41); + + module.exports = Object.keys || function keys(O) { + return $keys(O, enumBugKeys); + }; + + +/***/ }), +/* 31 */ +/***/ (function(module, exports, __webpack_require__) { + + var has = __webpack_require__(5); + var toIObject = __webpack_require__(32); + var arrayIndexOf = __webpack_require__(36)(false); + var IE_PROTO = __webpack_require__(40)('IE_PROTO'); + + module.exports = function (object, names) { + var O = toIObject(object); + var i = 0; + var result = []; + var key; + for (key in O) if (key != IE_PROTO) has(O, key) && result.push(key); + // Don't enum bug & hidden keys + while (names.length > i) if (has(O, key = names[i++])) { + ~arrayIndexOf(result, key) || result.push(key); + } + return result; + }; + + +/***/ }), +/* 32 */ +/***/ (function(module, exports, __webpack_require__) { + + // to indexed object, toObject with fallback for non-array-like ES3 strings + var IObject = __webpack_require__(33); + var defined = __webpack_require__(35); + module.exports = function (it) { + return IObject(defined(it)); + }; + + +/***/ }), +/* 33 */ +/***/ (function(module, exports, __webpack_require__) { + + // fallback for non-array-like ES3 and non-enumerable old V8 strings + var cof = __webpack_require__(34); + // eslint-disable-next-line no-prototype-builtins + module.exports = Object('z').propertyIsEnumerable(0) ? Object : function (it) { + return cof(it) == 'String' ? it.split('') : Object(it); + }; + + +/***/ }), +/* 34 */ +/***/ (function(module, exports) { + + var toString = {}.toString; + + module.exports = function (it) { + return toString.call(it).slice(8, -1); + }; + + +/***/ }), +/* 35 */ +/***/ (function(module, exports) { + + // 7.2.1 RequireObjectCoercible(argument) + module.exports = function (it) { + if (it == undefined) throw TypeError("Can't call method on " + it); + return it; + }; + + +/***/ }), +/* 36 */ +/***/ (function(module, exports, __webpack_require__) { + + // false -> Array#indexOf + // true -> Array#includes + var toIObject = __webpack_require__(32); + var toLength = __webpack_require__(37); + var toAbsoluteIndex = __webpack_require__(39); + module.exports = function (IS_INCLUDES) { + return function ($this, el, fromIndex) { + var O = toIObject($this); + var length = toLength(O.length); + var index = toAbsoluteIndex(fromIndex, length); + var value; + // Array#includes uses SameValueZero equality algorithm + // eslint-disable-next-line no-self-compare + if (IS_INCLUDES && el != el) while (length > index) { + value = O[index++]; + // eslint-disable-next-line no-self-compare + if (value != value) return true; + // Array#indexOf ignores holes, Array#includes - not + } else for (;length > index; index++) if (IS_INCLUDES || index in O) { + if (O[index] === el) return IS_INCLUDES || index || 0; + } return !IS_INCLUDES && -1; + }; + }; + + +/***/ }), +/* 37 */ +/***/ (function(module, exports, __webpack_require__) { + + // 7.1.15 ToLength + var toInteger = __webpack_require__(38); + var min = Math.min; + module.exports = function (it) { + return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991 + }; + + +/***/ }), +/* 38 */ +/***/ (function(module, exports) { + + // 7.1.4 ToInteger + var ceil = Math.ceil; + var floor = Math.floor; + module.exports = function (it) { + return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it); + }; + + +/***/ }), +/* 39 */ +/***/ (function(module, exports, __webpack_require__) { + + var toInteger = __webpack_require__(38); + var max = Math.max; + var min = Math.min; + module.exports = function (index, length) { + index = toInteger(index); + return index < 0 ? max(index + length, 0) : min(index, length); + }; + + +/***/ }), +/* 40 */ +/***/ (function(module, exports, __webpack_require__) { + + var shared = __webpack_require__(23)('keys'); + var uid = __webpack_require__(19); + module.exports = function (key) { + return shared[key] || (shared[key] = uid(key)); + }; + + +/***/ }), +/* 41 */ +/***/ (function(module, exports) { + + // IE 8- don't enum bug keys + module.exports = ( + 'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf' + ).split(','); + + +/***/ }), +/* 42 */ +/***/ (function(module, exports) { + + exports.f = Object.getOwnPropertySymbols; + + +/***/ }), +/* 43 */ +/***/ (function(module, exports) { + + exports.f = {}.propertyIsEnumerable; + + +/***/ }), +/* 44 */ +/***/ (function(module, exports, __webpack_require__) { + + // 7.2.2 IsArray(argument) + var cof = __webpack_require__(34); + module.exports = Array.isArray || function isArray(arg) { + return cof(arg) == 'Array'; + }; + + +/***/ }), +/* 45 */ +/***/ (function(module, exports, __webpack_require__) { + + // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) + var anObject = __webpack_require__(12); + var dPs = __webpack_require__(46); + var enumBugKeys = __webpack_require__(41); + var IE_PROTO = __webpack_require__(40)('IE_PROTO'); + var Empty = function () { /* empty */ }; + var PROTOTYPE = 'prototype'; + + // Create object with fake `null` prototype: use iframe Object with cleared prototype + var createDict = function () { + // Thrash, waste and sodomy: IE GC bug + var iframe = __webpack_require__(15)('iframe'); + var i = enumBugKeys.length; + var lt = '<'; + var gt = '>'; + var iframeDocument; + iframe.style.display = 'none'; + __webpack_require__(47).appendChild(iframe); + iframe.src = 'javascript:'; // eslint-disable-line no-script-url + // createDict = iframe.contentWindow.Object; + // html.removeChild(iframe); + iframeDocument = iframe.contentWindow.document; + iframeDocument.open(); + iframeDocument.write(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt); + iframeDocument.close(); + createDict = iframeDocument.F; + while (i--) delete createDict[PROTOTYPE][enumBugKeys[i]]; + return createDict(); + }; + + module.exports = Object.create || function create(O, Properties) { + var result; + if (O !== null) { + Empty[PROTOTYPE] = anObject(O); + result = new Empty(); + Empty[PROTOTYPE] = null; + // add "__proto__" for Object.getPrototypeOf polyfill + result[IE_PROTO] = O; + } else result = createDict(); + return Properties === undefined ? result : dPs(result, Properties); + }; + + +/***/ }), +/* 46 */ +/***/ (function(module, exports, __webpack_require__) { + + var dP = __webpack_require__(11); + var anObject = __webpack_require__(12); + var getKeys = __webpack_require__(30); + + module.exports = __webpack_require__(6) ? Object.defineProperties : function defineProperties(O, Properties) { + anObject(O); + var keys = getKeys(Properties); + var length = keys.length; + var i = 0; + var P; + while (length > i) dP.f(O, P = keys[i++], Properties[P]); + return O; + }; + + +/***/ }), +/* 47 */ +/***/ (function(module, exports, __webpack_require__) { + + var document = __webpack_require__(4).document; + module.exports = document && document.documentElement; + + +/***/ }), +/* 48 */ +/***/ (function(module, exports, __webpack_require__) { + + // fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window + var toIObject = __webpack_require__(32); + var gOPN = __webpack_require__(49).f; + var toString = {}.toString; + + var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames + ? Object.getOwnPropertyNames(window) : []; + + var getWindowNames = function (it) { + try { + return gOPN(it); + } catch (e) { + return windowNames.slice(); + } + }; + + module.exports.f = function getOwnPropertyNames(it) { + return windowNames && toString.call(it) == '[object Window]' ? getWindowNames(it) : gOPN(toIObject(it)); + }; + + +/***/ }), +/* 49 */ +/***/ (function(module, exports, __webpack_require__) { + + // 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O) + var $keys = __webpack_require__(31); + var hiddenKeys = __webpack_require__(41).concat('length', 'prototype'); + + exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) { + return $keys(O, hiddenKeys); + }; + + +/***/ }), +/* 50 */ +/***/ (function(module, exports, __webpack_require__) { + + var pIE = __webpack_require__(43); + var createDesc = __webpack_require__(17); + var toIObject = __webpack_require__(32); + var toPrimitive = __webpack_require__(16); + var has = __webpack_require__(5); + var IE8_DOM_DEFINE = __webpack_require__(14); + var gOPD = Object.getOwnPropertyDescriptor; + + exports.f = __webpack_require__(6) ? gOPD : function getOwnPropertyDescriptor(O, P) { + O = toIObject(O); + P = toPrimitive(P, true); + if (IE8_DOM_DEFINE) try { + return gOPD(O, P); + } catch (e) { /* empty */ } + if (has(O, P)) return createDesc(!pIE.f.call(O, P), O[P]); + }; + + +/***/ }), +/* 51 */ +/***/ (function(module, exports, __webpack_require__) { + + var $export = __webpack_require__(8); + // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) + $export($export.S, 'Object', { create: __webpack_require__(45) }); + + +/***/ }), +/* 52 */ +/***/ (function(module, exports, __webpack_require__) { + + var $export = __webpack_require__(8); + // 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes) + $export($export.S + $export.F * !__webpack_require__(6), 'Object', { defineProperty: __webpack_require__(11).f }); + + +/***/ }), +/* 53 */ +/***/ (function(module, exports, __webpack_require__) { + + var $export = __webpack_require__(8); + // 19.1.2.3 / 15.2.3.7 Object.defineProperties(O, Properties) + $export($export.S + $export.F * !__webpack_require__(6), 'Object', { defineProperties: __webpack_require__(46) }); + + +/***/ }), +/* 54 */ +/***/ (function(module, exports, __webpack_require__) { + + // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P) + var toIObject = __webpack_require__(32); + var $getOwnPropertyDescriptor = __webpack_require__(50).f; + + __webpack_require__(55)('getOwnPropertyDescriptor', function () { + return function getOwnPropertyDescriptor(it, key) { + return $getOwnPropertyDescriptor(toIObject(it), key); + }; + }); + + +/***/ }), +/* 55 */ +/***/ (function(module, exports, __webpack_require__) { + + // most Object methods by ES6 should accept primitives + var $export = __webpack_require__(8); + var core = __webpack_require__(9); + var fails = __webpack_require__(7); + module.exports = function (KEY, exec) { + var fn = (core.Object || {})[KEY] || Object[KEY]; + var exp = {}; + exp[KEY] = exec(fn); + $export($export.S + $export.F * fails(function () { fn(1); }), 'Object', exp); + }; + + +/***/ }), +/* 56 */ +/***/ (function(module, exports, __webpack_require__) { + + // 19.1.2.9 Object.getPrototypeOf(O) + var toObject = __webpack_require__(57); + var $getPrototypeOf = __webpack_require__(58); + + __webpack_require__(55)('getPrototypeOf', function () { + return function getPrototypeOf(it) { + return $getPrototypeOf(toObject(it)); + }; + }); + + +/***/ }), +/* 57 */ +/***/ (function(module, exports, __webpack_require__) { + + // 7.1.13 ToObject(argument) + var defined = __webpack_require__(35); + module.exports = function (it) { + return Object(defined(it)); + }; + + +/***/ }), +/* 58 */ +/***/ (function(module, exports, __webpack_require__) { + + // 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O) + var has = __webpack_require__(5); + var toObject = __webpack_require__(57); + var IE_PROTO = __webpack_require__(40)('IE_PROTO'); + var ObjectProto = Object.prototype; + + module.exports = Object.getPrototypeOf || function (O) { + O = toObject(O); + if (has(O, IE_PROTO)) return O[IE_PROTO]; + if (typeof O.constructor == 'function' && O instanceof O.constructor) { + return O.constructor.prototype; + } return O instanceof Object ? ObjectProto : null; + }; + + +/***/ }), +/* 59 */ +/***/ (function(module, exports, __webpack_require__) { + + // 19.1.2.14 Object.keys(O) + var toObject = __webpack_require__(57); + var $keys = __webpack_require__(30); + + __webpack_require__(55)('keys', function () { + return function keys(it) { + return $keys(toObject(it)); + }; + }); + + +/***/ }), +/* 60 */ +/***/ (function(module, exports, __webpack_require__) { + + // 19.1.2.7 Object.getOwnPropertyNames(O) + __webpack_require__(55)('getOwnPropertyNames', function () { + return __webpack_require__(48).f; + }); + + +/***/ }), +/* 61 */ +/***/ (function(module, exports, __webpack_require__) { + + // 19.1.2.5 Object.freeze(O) + var isObject = __webpack_require__(13); + var meta = __webpack_require__(22).onFreeze; + + __webpack_require__(55)('freeze', function ($freeze) { + return function freeze(it) { + return $freeze && isObject(it) ? $freeze(meta(it)) : it; + }; + }); + + +/***/ }), +/* 62 */ +/***/ (function(module, exports, __webpack_require__) { + + // 19.1.2.17 Object.seal(O) + var isObject = __webpack_require__(13); + var meta = __webpack_require__(22).onFreeze; + + __webpack_require__(55)('seal', function ($seal) { + return function seal(it) { + return $seal && isObject(it) ? $seal(meta(it)) : it; + }; + }); + + +/***/ }), +/* 63 */ +/***/ (function(module, exports, __webpack_require__) { + + // 19.1.2.15 Object.preventExtensions(O) + var isObject = __webpack_require__(13); + var meta = __webpack_require__(22).onFreeze; + + __webpack_require__(55)('preventExtensions', function ($preventExtensions) { + return function preventExtensions(it) { + return $preventExtensions && isObject(it) ? $preventExtensions(meta(it)) : it; + }; + }); + + +/***/ }), +/* 64 */ +/***/ (function(module, exports, __webpack_require__) { + + // 19.1.2.12 Object.isFrozen(O) + var isObject = __webpack_require__(13); + + __webpack_require__(55)('isFrozen', function ($isFrozen) { + return function isFrozen(it) { + return isObject(it) ? $isFrozen ? $isFrozen(it) : false : true; + }; + }); + + +/***/ }), +/* 65 */ +/***/ (function(module, exports, __webpack_require__) { + + // 19.1.2.13 Object.isSealed(O) + var isObject = __webpack_require__(13); + + __webpack_require__(55)('isSealed', function ($isSealed) { + return function isSealed(it) { + return isObject(it) ? $isSealed ? $isSealed(it) : false : true; + }; + }); + + +/***/ }), +/* 66 */ +/***/ (function(module, exports, __webpack_require__) { + + // 19.1.2.11 Object.isExtensible(O) + var isObject = __webpack_require__(13); + + __webpack_require__(55)('isExtensible', function ($isExtensible) { + return function isExtensible(it) { + return isObject(it) ? $isExtensible ? $isExtensible(it) : true : false; + }; + }); + + +/***/ }), +/* 67 */ +/***/ (function(module, exports, __webpack_require__) { + + // 19.1.3.1 Object.assign(target, source) + var $export = __webpack_require__(8); + + $export($export.S + $export.F, 'Object', { assign: __webpack_require__(68) }); + + +/***/ }), +/* 68 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // 19.1.2.1 Object.assign(target, source, ...) + var getKeys = __webpack_require__(30); + var gOPS = __webpack_require__(42); + var pIE = __webpack_require__(43); + var toObject = __webpack_require__(57); + var IObject = __webpack_require__(33); + var $assign = Object.assign; + + // should work with symbols and should have deterministic property order (V8 bug) + module.exports = !$assign || __webpack_require__(7)(function () { + var A = {}; + var B = {}; + // eslint-disable-next-line no-undef + var S = Symbol(); + var K = 'abcdefghijklmnopqrst'; + A[S] = 7; + K.split('').forEach(function (k) { B[k] = k; }); + return $assign({}, A)[S] != 7 || Object.keys($assign({}, B)).join('') != K; + }) ? function assign(target, source) { // eslint-disable-line no-unused-vars + var T = toObject(target); + var aLen = arguments.length; + var index = 1; + var getSymbols = gOPS.f; + var isEnum = pIE.f; + while (aLen > index) { + var S = IObject(arguments[index++]); + var keys = getSymbols ? getKeys(S).concat(getSymbols(S)) : getKeys(S); + var length = keys.length; + var j = 0; + var key; + while (length > j) if (isEnum.call(S, key = keys[j++])) T[key] = S[key]; + } return T; + } : $assign; + + +/***/ }), +/* 69 */ +/***/ (function(module, exports, __webpack_require__) { + + // 19.1.3.10 Object.is(value1, value2) + var $export = __webpack_require__(8); + $export($export.S, 'Object', { is: __webpack_require__(70) }); + + +/***/ }), +/* 70 */ +/***/ (function(module, exports) { + + // 7.2.9 SameValue(x, y) + module.exports = Object.is || function is(x, y) { + // eslint-disable-next-line no-self-compare + return x === y ? x !== 0 || 1 / x === 1 / y : x != x && y != y; + }; + + +/***/ }), +/* 71 */ +/***/ (function(module, exports, __webpack_require__) { + + // 19.1.3.19 Object.setPrototypeOf(O, proto) + var $export = __webpack_require__(8); + $export($export.S, 'Object', { setPrototypeOf: __webpack_require__(72).set }); + + +/***/ }), +/* 72 */ +/***/ (function(module, exports, __webpack_require__) { + + // Works with __proto__ only. Old v8 can't work with null proto objects. + /* eslint-disable no-proto */ + var isObject = __webpack_require__(13); + var anObject = __webpack_require__(12); + var check = function (O, proto) { + anObject(O); + if (!isObject(proto) && proto !== null) throw TypeError(proto + ": can't set as prototype!"); + }; + module.exports = { + set: Object.setPrototypeOf || ('__proto__' in {} ? // eslint-disable-line + function (test, buggy, set) { + try { + set = __webpack_require__(20)(Function.call, __webpack_require__(50).f(Object.prototype, '__proto__').set, 2); + set(test, []); + buggy = !(test instanceof Array); + } catch (e) { buggy = true; } + return function setPrototypeOf(O, proto) { + check(O, proto); + if (buggy) O.__proto__ = proto; + else set(O, proto); + return O; + }; + }({}, false) : undefined), + check: check + }; + + +/***/ }), +/* 73 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // 19.1.3.6 Object.prototype.toString() + var classof = __webpack_require__(74); + var test = {}; + test[__webpack_require__(26)('toStringTag')] = 'z'; + if (test + '' != '[object z]') { + __webpack_require__(18)(Object.prototype, 'toString', function toString() { + return '[object ' + classof(this) + ']'; + }, true); + } + + +/***/ }), +/* 74 */ +/***/ (function(module, exports, __webpack_require__) { + + // getting tag from 19.1.3.6 Object.prototype.toString() + var cof = __webpack_require__(34); + var TAG = __webpack_require__(26)('toStringTag'); + // ES3 wrong here + var ARG = cof(function () { return arguments; }()) == 'Arguments'; + + // fallback for IE11 Script Access Denied error + var tryGet = function (it, key) { + try { + return it[key]; + } catch (e) { /* empty */ } + }; + + module.exports = function (it) { + var O, T, B; + return it === undefined ? 'Undefined' : it === null ? 'Null' + // @@toStringTag case + : typeof (T = tryGet(O = Object(it), TAG)) == 'string' ? T + // builtinTag case + : ARG ? cof(O) + // ES3 arguments fallback + : (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B; + }; + + +/***/ }), +/* 75 */ +/***/ (function(module, exports, __webpack_require__) { + + // 19.2.3.2 / 15.3.4.5 Function.prototype.bind(thisArg, args...) + var $export = __webpack_require__(8); + + $export($export.P, 'Function', { bind: __webpack_require__(76) }); + + +/***/ }), +/* 76 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var aFunction = __webpack_require__(21); + var isObject = __webpack_require__(13); + var invoke = __webpack_require__(77); + var arraySlice = [].slice; + var factories = {}; + + var construct = function (F, len, args) { + if (!(len in factories)) { + for (var n = [], i = 0; i < len; i++) n[i] = 'a[' + i + ']'; + // eslint-disable-next-line no-new-func + factories[len] = Function('F,a', 'return new F(' + n.join(',') + ')'); + } return factories[len](F, args); + }; + + module.exports = Function.bind || function bind(that /* , ...args */) { + var fn = aFunction(this); + var partArgs = arraySlice.call(arguments, 1); + var bound = function (/* args... */) { + var args = partArgs.concat(arraySlice.call(arguments)); + return this instanceof bound ? construct(fn, args.length, args) : invoke(fn, args, that); + }; + if (isObject(fn.prototype)) bound.prototype = fn.prototype; + return bound; + }; + + +/***/ }), +/* 77 */ +/***/ (function(module, exports) { + + // fast apply, http://jsperf.lnkit.com/fast-apply/5 + module.exports = function (fn, args, that) { + var un = that === undefined; + switch (args.length) { + case 0: return un ? fn() + : fn.call(that); + case 1: return un ? fn(args[0]) + : fn.call(that, args[0]); + case 2: return un ? fn(args[0], args[1]) + : fn.call(that, args[0], args[1]); + case 3: return un ? fn(args[0], args[1], args[2]) + : fn.call(that, args[0], args[1], args[2]); + case 4: return un ? fn(args[0], args[1], args[2], args[3]) + : fn.call(that, args[0], args[1], args[2], args[3]); + } return fn.apply(that, args); + }; + + +/***/ }), +/* 78 */ +/***/ (function(module, exports, __webpack_require__) { + + var dP = __webpack_require__(11).f; + var FProto = Function.prototype; + var nameRE = /^\s*function ([^ (]*)/; + var NAME = 'name'; + + // 19.2.4.2 name + NAME in FProto || __webpack_require__(6) && dP(FProto, NAME, { + configurable: true, + get: function () { + try { + return ('' + this).match(nameRE)[1]; + } catch (e) { + return ''; + } + } + }); + + +/***/ }), +/* 79 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var isObject = __webpack_require__(13); + var getPrototypeOf = __webpack_require__(58); + var HAS_INSTANCE = __webpack_require__(26)('hasInstance'); + var FunctionProto = Function.prototype; + // 19.2.3.6 Function.prototype[@@hasInstance](V) + if (!(HAS_INSTANCE in FunctionProto)) __webpack_require__(11).f(FunctionProto, HAS_INSTANCE, { value: function (O) { + if (typeof this != 'function' || !isObject(O)) return false; + if (!isObject(this.prototype)) return O instanceof this; + // for environment w/o native `@@hasInstance` logic enough `instanceof`, but add this: + while (O = getPrototypeOf(O)) if (this.prototype === O) return true; + return false; + } }); + + +/***/ }), +/* 80 */ +/***/ (function(module, exports, __webpack_require__) { + + var $export = __webpack_require__(8); + var $parseInt = __webpack_require__(81); + // 18.2.5 parseInt(string, radix) + $export($export.G + $export.F * (parseInt != $parseInt), { parseInt: $parseInt }); + + +/***/ }), +/* 81 */ +/***/ (function(module, exports, __webpack_require__) { + + var $parseInt = __webpack_require__(4).parseInt; + var $trim = __webpack_require__(82).trim; + var ws = __webpack_require__(83); + var hex = /^[-+]?0[xX]/; + + module.exports = $parseInt(ws + '08') !== 8 || $parseInt(ws + '0x16') !== 22 ? function parseInt(str, radix) { + var string = $trim(String(str), 3); + return $parseInt(string, (radix >>> 0) || (hex.test(string) ? 16 : 10)); + } : $parseInt; + + +/***/ }), +/* 82 */ +/***/ (function(module, exports, __webpack_require__) { + + var $export = __webpack_require__(8); + var defined = __webpack_require__(35); + var fails = __webpack_require__(7); + var spaces = __webpack_require__(83); + var space = '[' + spaces + ']'; + var non = '\u200b\u0085'; + var ltrim = RegExp('^' + space + space + '*'); + var rtrim = RegExp(space + space + '*$'); + + var exporter = function (KEY, exec, ALIAS) { + var exp = {}; + var FORCE = fails(function () { + return !!spaces[KEY]() || non[KEY]() != non; + }); + var fn = exp[KEY] = FORCE ? exec(trim) : spaces[KEY]; + if (ALIAS) exp[ALIAS] = fn; + $export($export.P + $export.F * FORCE, 'String', exp); + }; + + // 1 -> String#trimLeft + // 2 -> String#trimRight + // 3 -> String#trim + var trim = exporter.trim = function (string, TYPE) { + string = String(defined(string)); + if (TYPE & 1) string = string.replace(ltrim, ''); + if (TYPE & 2) string = string.replace(rtrim, ''); + return string; + }; + + module.exports = exporter; + + +/***/ }), +/* 83 */ +/***/ (function(module, exports) { + + module.exports = '\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003' + + '\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF'; + + +/***/ }), +/* 84 */ +/***/ (function(module, exports, __webpack_require__) { + + var $export = __webpack_require__(8); + var $parseFloat = __webpack_require__(85); + // 18.2.4 parseFloat(string) + $export($export.G + $export.F * (parseFloat != $parseFloat), { parseFloat: $parseFloat }); + + +/***/ }), +/* 85 */ +/***/ (function(module, exports, __webpack_require__) { + + var $parseFloat = __webpack_require__(4).parseFloat; + var $trim = __webpack_require__(82).trim; + + module.exports = 1 / $parseFloat(__webpack_require__(83) + '-0') !== -Infinity ? function parseFloat(str) { + var string = $trim(String(str), 3); + var result = $parseFloat(string); + return result === 0 && string.charAt(0) == '-' ? -0 : result; + } : $parseFloat; + + +/***/ }), +/* 86 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var global = __webpack_require__(4); + var has = __webpack_require__(5); + var cof = __webpack_require__(34); + var inheritIfRequired = __webpack_require__(87); + var toPrimitive = __webpack_require__(16); + var fails = __webpack_require__(7); + var gOPN = __webpack_require__(49).f; + var gOPD = __webpack_require__(50).f; + var dP = __webpack_require__(11).f; + var $trim = __webpack_require__(82).trim; + var NUMBER = 'Number'; + var $Number = global[NUMBER]; + var Base = $Number; + var proto = $Number.prototype; + // Opera ~12 has broken Object#toString + var BROKEN_COF = cof(__webpack_require__(45)(proto)) == NUMBER; + var TRIM = 'trim' in String.prototype; + + // 7.1.3 ToNumber(argument) + var toNumber = function (argument) { + var it = toPrimitive(argument, false); + if (typeof it == 'string' && it.length > 2) { + it = TRIM ? it.trim() : $trim(it, 3); + var first = it.charCodeAt(0); + var third, radix, maxCode; + if (first === 43 || first === 45) { + third = it.charCodeAt(2); + if (third === 88 || third === 120) return NaN; // Number('+0x1') should be NaN, old V8 fix + } else if (first === 48) { + switch (it.charCodeAt(1)) { + case 66: case 98: radix = 2; maxCode = 49; break; // fast equal /^0b[01]+$/i + case 79: case 111: radix = 8; maxCode = 55; break; // fast equal /^0o[0-7]+$/i + default: return +it; + } + for (var digits = it.slice(2), i = 0, l = digits.length, code; i < l; i++) { + code = digits.charCodeAt(i); + // parseInt parses a string to a first unavailable symbol + // but ToNumber should return NaN if a string contains unavailable symbols + if (code < 48 || code > maxCode) return NaN; + } return parseInt(digits, radix); + } + } return +it; + }; + + if (!$Number(' 0o1') || !$Number('0b1') || $Number('+0x1')) { + $Number = function Number(value) { + var it = arguments.length < 1 ? 0 : value; + var that = this; + return that instanceof $Number + // check on 1..constructor(foo) case + && (BROKEN_COF ? fails(function () { proto.valueOf.call(that); }) : cof(that) != NUMBER) + ? inheritIfRequired(new Base(toNumber(it)), that, $Number) : toNumber(it); + }; + for (var keys = __webpack_require__(6) ? gOPN(Base) : ( + // ES3: + 'MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,' + + // ES6 (in case, if modules with ES6 Number statics required before): + 'EPSILON,isFinite,isInteger,isNaN,isSafeInteger,MAX_SAFE_INTEGER,' + + 'MIN_SAFE_INTEGER,parseFloat,parseInt,isInteger' + ).split(','), j = 0, key; keys.length > j; j++) { + if (has(Base, key = keys[j]) && !has($Number, key)) { + dP($Number, key, gOPD(Base, key)); + } + } + $Number.prototype = proto; + proto.constructor = $Number; + __webpack_require__(18)(global, NUMBER, $Number); + } + + +/***/ }), +/* 87 */ +/***/ (function(module, exports, __webpack_require__) { + + var isObject = __webpack_require__(13); + var setPrototypeOf = __webpack_require__(72).set; + module.exports = function (that, target, C) { + var S = target.constructor; + var P; + if (S !== C && typeof S == 'function' && (P = S.prototype) !== C.prototype && isObject(P) && setPrototypeOf) { + setPrototypeOf(that, P); + } return that; + }; + + +/***/ }), +/* 88 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var toInteger = __webpack_require__(38); + var aNumberValue = __webpack_require__(89); + var repeat = __webpack_require__(90); + var $toFixed = 1.0.toFixed; + var floor = Math.floor; + var data = [0, 0, 0, 0, 0, 0]; + var ERROR = 'Number.toFixed: incorrect invocation!'; + var ZERO = '0'; + + var multiply = function (n, c) { + var i = -1; + var c2 = c; + while (++i < 6) { + c2 += n * data[i]; + data[i] = c2 % 1e7; + c2 = floor(c2 / 1e7); + } + }; + var divide = function (n) { + var i = 6; + var c = 0; + while (--i >= 0) { + c += data[i]; + data[i] = floor(c / n); + c = (c % n) * 1e7; + } + }; + var numToString = function () { + var i = 6; + var s = ''; + while (--i >= 0) { + if (s !== '' || i === 0 || data[i] !== 0) { + var t = String(data[i]); + s = s === '' ? t : s + repeat.call(ZERO, 7 - t.length) + t; + } + } return s; + }; + var pow = function (x, n, acc) { + return n === 0 ? acc : n % 2 === 1 ? pow(x, n - 1, acc * x) : pow(x * x, n / 2, acc); + }; + var log = function (x) { + var n = 0; + var x2 = x; + while (x2 >= 4096) { + n += 12; + x2 /= 4096; + } + while (x2 >= 2) { + n += 1; + x2 /= 2; + } return n; + }; + + $export($export.P + $export.F * (!!$toFixed && ( + 0.00008.toFixed(3) !== '0.000' || + 0.9.toFixed(0) !== '1' || + 1.255.toFixed(2) !== '1.25' || + 1000000000000000128.0.toFixed(0) !== '1000000000000000128' + ) || !__webpack_require__(7)(function () { + // V8 ~ Android 4.3- + $toFixed.call({}); + })), 'Number', { + toFixed: function toFixed(fractionDigits) { + var x = aNumberValue(this, ERROR); + var f = toInteger(fractionDigits); + var s = ''; + var m = ZERO; + var e, z, j, k; + if (f < 0 || f > 20) throw RangeError(ERROR); + // eslint-disable-next-line no-self-compare + if (x != x) return 'NaN'; + if (x <= -1e21 || x >= 1e21) return String(x); + if (x < 0) { + s = '-'; + x = -x; + } + if (x > 1e-21) { + e = log(x * pow(2, 69, 1)) - 69; + z = e < 0 ? x * pow(2, -e, 1) : x / pow(2, e, 1); + z *= 0x10000000000000; + e = 52 - e; + if (e > 0) { + multiply(0, z); + j = f; + while (j >= 7) { + multiply(1e7, 0); + j -= 7; + } + multiply(pow(10, j, 1), 0); + j = e - 1; + while (j >= 23) { + divide(1 << 23); + j -= 23; + } + divide(1 << j); + multiply(1, 1); + divide(2); + m = numToString(); + } else { + multiply(0, z); + multiply(1 << -e, 0); + m = numToString() + repeat.call(ZERO, f); + } + } + if (f > 0) { + k = m.length; + m = s + (k <= f ? '0.' + repeat.call(ZERO, f - k) + m : m.slice(0, k - f) + '.' + m.slice(k - f)); + } else { + m = s + m; + } return m; + } + }); + + +/***/ }), +/* 89 */ +/***/ (function(module, exports, __webpack_require__) { + + var cof = __webpack_require__(34); + module.exports = function (it, msg) { + if (typeof it != 'number' && cof(it) != 'Number') throw TypeError(msg); + return +it; + }; + + +/***/ }), +/* 90 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var toInteger = __webpack_require__(38); + var defined = __webpack_require__(35); + + module.exports = function repeat(count) { + var str = String(defined(this)); + var res = ''; + var n = toInteger(count); + if (n < 0 || n == Infinity) throw RangeError("Count can't be negative"); + for (;n > 0; (n >>>= 1) && (str += str)) if (n & 1) res += str; + return res; + }; + + +/***/ }), +/* 91 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var $fails = __webpack_require__(7); + var aNumberValue = __webpack_require__(89); + var $toPrecision = 1.0.toPrecision; + + $export($export.P + $export.F * ($fails(function () { + // IE7- + return $toPrecision.call(1, undefined) !== '1'; + }) || !$fails(function () { + // V8 ~ Android 4.3- + $toPrecision.call({}); + })), 'Number', { + toPrecision: function toPrecision(precision) { + var that = aNumberValue(this, 'Number#toPrecision: incorrect invocation!'); + return precision === undefined ? $toPrecision.call(that) : $toPrecision.call(that, precision); + } + }); + + +/***/ }), +/* 92 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.1.2.1 Number.EPSILON + var $export = __webpack_require__(8); + + $export($export.S, 'Number', { EPSILON: Math.pow(2, -52) }); + + +/***/ }), +/* 93 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.1.2.2 Number.isFinite(number) + var $export = __webpack_require__(8); + var _isFinite = __webpack_require__(4).isFinite; + + $export($export.S, 'Number', { + isFinite: function isFinite(it) { + return typeof it == 'number' && _isFinite(it); + } + }); + + +/***/ }), +/* 94 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.1.2.3 Number.isInteger(number) + var $export = __webpack_require__(8); + + $export($export.S, 'Number', { isInteger: __webpack_require__(95) }); + + +/***/ }), +/* 95 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.1.2.3 Number.isInteger(number) + var isObject = __webpack_require__(13); + var floor = Math.floor; + module.exports = function isInteger(it) { + return !isObject(it) && isFinite(it) && floor(it) === it; + }; + + +/***/ }), +/* 96 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.1.2.4 Number.isNaN(number) + var $export = __webpack_require__(8); + + $export($export.S, 'Number', { + isNaN: function isNaN(number) { + // eslint-disable-next-line no-self-compare + return number != number; + } + }); + + +/***/ }), +/* 97 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.1.2.5 Number.isSafeInteger(number) + var $export = __webpack_require__(8); + var isInteger = __webpack_require__(95); + var abs = Math.abs; + + $export($export.S, 'Number', { + isSafeInteger: function isSafeInteger(number) { + return isInteger(number) && abs(number) <= 0x1fffffffffffff; + } + }); + + +/***/ }), +/* 98 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.1.2.6 Number.MAX_SAFE_INTEGER + var $export = __webpack_require__(8); + + $export($export.S, 'Number', { MAX_SAFE_INTEGER: 0x1fffffffffffff }); + + +/***/ }), +/* 99 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.1.2.10 Number.MIN_SAFE_INTEGER + var $export = __webpack_require__(8); + + $export($export.S, 'Number', { MIN_SAFE_INTEGER: -0x1fffffffffffff }); + + +/***/ }), +/* 100 */ +/***/ (function(module, exports, __webpack_require__) { + + var $export = __webpack_require__(8); + var $parseFloat = __webpack_require__(85); + // 20.1.2.12 Number.parseFloat(string) + $export($export.S + $export.F * (Number.parseFloat != $parseFloat), 'Number', { parseFloat: $parseFloat }); + + +/***/ }), +/* 101 */ +/***/ (function(module, exports, __webpack_require__) { + + var $export = __webpack_require__(8); + var $parseInt = __webpack_require__(81); + // 20.1.2.13 Number.parseInt(string, radix) + $export($export.S + $export.F * (Number.parseInt != $parseInt), 'Number', { parseInt: $parseInt }); + + +/***/ }), +/* 102 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.2.2.3 Math.acosh(x) + var $export = __webpack_require__(8); + var log1p = __webpack_require__(103); + var sqrt = Math.sqrt; + var $acosh = Math.acosh; + + $export($export.S + $export.F * !($acosh + // V8 bug: https://code.google.com/p/v8/issues/detail?id=3509 + && Math.floor($acosh(Number.MAX_VALUE)) == 710 + // Tor Browser bug: Math.acosh(Infinity) -> NaN + && $acosh(Infinity) == Infinity + ), 'Math', { + acosh: function acosh(x) { + return (x = +x) < 1 ? NaN : x > 94906265.62425156 + ? Math.log(x) + Math.LN2 + : log1p(x - 1 + sqrt(x - 1) * sqrt(x + 1)); + } + }); + + +/***/ }), +/* 103 */ +/***/ (function(module, exports) { + + // 20.2.2.20 Math.log1p(x) + module.exports = Math.log1p || function log1p(x) { + return (x = +x) > -1e-8 && x < 1e-8 ? x - x * x / 2 : Math.log(1 + x); + }; + + +/***/ }), +/* 104 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.2.2.5 Math.asinh(x) + var $export = __webpack_require__(8); + var $asinh = Math.asinh; + + function asinh(x) { + return !isFinite(x = +x) || x == 0 ? x : x < 0 ? -asinh(-x) : Math.log(x + Math.sqrt(x * x + 1)); + } + + // Tor Browser bug: Math.asinh(0) -> -0 + $export($export.S + $export.F * !($asinh && 1 / $asinh(0) > 0), 'Math', { asinh: asinh }); + + +/***/ }), +/* 105 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.2.2.7 Math.atanh(x) + var $export = __webpack_require__(8); + var $atanh = Math.atanh; + + // Tor Browser bug: Math.atanh(-0) -> 0 + $export($export.S + $export.F * !($atanh && 1 / $atanh(-0) < 0), 'Math', { + atanh: function atanh(x) { + return (x = +x) == 0 ? x : Math.log((1 + x) / (1 - x)) / 2; + } + }); + + +/***/ }), +/* 106 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.2.2.9 Math.cbrt(x) + var $export = __webpack_require__(8); + var sign = __webpack_require__(107); + + $export($export.S, 'Math', { + cbrt: function cbrt(x) { + return sign(x = +x) * Math.pow(Math.abs(x), 1 / 3); + } + }); + + +/***/ }), +/* 107 */ +/***/ (function(module, exports) { + + // 20.2.2.28 Math.sign(x) + module.exports = Math.sign || function sign(x) { + // eslint-disable-next-line no-self-compare + return (x = +x) == 0 || x != x ? x : x < 0 ? -1 : 1; + }; + + +/***/ }), +/* 108 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.2.2.11 Math.clz32(x) + var $export = __webpack_require__(8); + + $export($export.S, 'Math', { + clz32: function clz32(x) { + return (x >>>= 0) ? 31 - Math.floor(Math.log(x + 0.5) * Math.LOG2E) : 32; + } + }); + + +/***/ }), +/* 109 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.2.2.12 Math.cosh(x) + var $export = __webpack_require__(8); + var exp = Math.exp; + + $export($export.S, 'Math', { + cosh: function cosh(x) { + return (exp(x = +x) + exp(-x)) / 2; + } + }); + + +/***/ }), +/* 110 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.2.2.14 Math.expm1(x) + var $export = __webpack_require__(8); + var $expm1 = __webpack_require__(111); + + $export($export.S + $export.F * ($expm1 != Math.expm1), 'Math', { expm1: $expm1 }); + + +/***/ }), +/* 111 */ +/***/ (function(module, exports) { + + // 20.2.2.14 Math.expm1(x) + var $expm1 = Math.expm1; + module.exports = (!$expm1 + // Old FF bug + || $expm1(10) > 22025.465794806719 || $expm1(10) < 22025.4657948067165168 + // Tor Browser bug + || $expm1(-2e-17) != -2e-17 + ) ? function expm1(x) { + return (x = +x) == 0 ? x : x > -1e-6 && x < 1e-6 ? x + x * x / 2 : Math.exp(x) - 1; + } : $expm1; + + +/***/ }), +/* 112 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.2.2.16 Math.fround(x) + var $export = __webpack_require__(8); + + $export($export.S, 'Math', { fround: __webpack_require__(113) }); + + +/***/ }), +/* 113 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.2.2.16 Math.fround(x) + var sign = __webpack_require__(107); + var pow = Math.pow; + var EPSILON = pow(2, -52); + var EPSILON32 = pow(2, -23); + var MAX32 = pow(2, 127) * (2 - EPSILON32); + var MIN32 = pow(2, -126); + + var roundTiesToEven = function (n) { + return n + 1 / EPSILON - 1 / EPSILON; + }; + + module.exports = Math.fround || function fround(x) { + var $abs = Math.abs(x); + var $sign = sign(x); + var a, result; + if ($abs < MIN32) return $sign * roundTiesToEven($abs / MIN32 / EPSILON32) * MIN32 * EPSILON32; + a = (1 + EPSILON32 / EPSILON) * $abs; + result = a - (a - $abs); + // eslint-disable-next-line no-self-compare + if (result > MAX32 || result != result) return $sign * Infinity; + return $sign * result; + }; + + +/***/ }), +/* 114 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.2.2.17 Math.hypot([value1[, value2[, … ]]]) + var $export = __webpack_require__(8); + var abs = Math.abs; + + $export($export.S, 'Math', { + hypot: function hypot(value1, value2) { // eslint-disable-line no-unused-vars + var sum = 0; + var i = 0; + var aLen = arguments.length; + var larg = 0; + var arg, div; + while (i < aLen) { + arg = abs(arguments[i++]); + if (larg < arg) { + div = larg / arg; + sum = sum * div * div + 1; + larg = arg; + } else if (arg > 0) { + div = arg / larg; + sum += div * div; + } else sum += arg; + } + return larg === Infinity ? Infinity : larg * Math.sqrt(sum); + } + }); + + +/***/ }), +/* 115 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.2.2.18 Math.imul(x, y) + var $export = __webpack_require__(8); + var $imul = Math.imul; + + // some WebKit versions fails with big numbers, some has wrong arity + $export($export.S + $export.F * __webpack_require__(7)(function () { + return $imul(0xffffffff, 5) != -5 || $imul.length != 2; + }), 'Math', { + imul: function imul(x, y) { + var UINT16 = 0xffff; + var xn = +x; + var yn = +y; + var xl = UINT16 & xn; + var yl = UINT16 & yn; + return 0 | xl * yl + ((UINT16 & xn >>> 16) * yl + xl * (UINT16 & yn >>> 16) << 16 >>> 0); + } + }); + + +/***/ }), +/* 116 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.2.2.21 Math.log10(x) + var $export = __webpack_require__(8); + + $export($export.S, 'Math', { + log10: function log10(x) { + return Math.log(x) * Math.LOG10E; + } + }); + + +/***/ }), +/* 117 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.2.2.20 Math.log1p(x) + var $export = __webpack_require__(8); + + $export($export.S, 'Math', { log1p: __webpack_require__(103) }); + + +/***/ }), +/* 118 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.2.2.22 Math.log2(x) + var $export = __webpack_require__(8); + + $export($export.S, 'Math', { + log2: function log2(x) { + return Math.log(x) / Math.LN2; + } + }); + + +/***/ }), +/* 119 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.2.2.28 Math.sign(x) + var $export = __webpack_require__(8); + + $export($export.S, 'Math', { sign: __webpack_require__(107) }); + + +/***/ }), +/* 120 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.2.2.30 Math.sinh(x) + var $export = __webpack_require__(8); + var expm1 = __webpack_require__(111); + var exp = Math.exp; + + // V8 near Chromium 38 has a problem with very small numbers + $export($export.S + $export.F * __webpack_require__(7)(function () { + return !Math.sinh(-2e-17) != -2e-17; + }), 'Math', { + sinh: function sinh(x) { + return Math.abs(x = +x) < 1 + ? (expm1(x) - expm1(-x)) / 2 + : (exp(x - 1) - exp(-x - 1)) * (Math.E / 2); + } + }); + + +/***/ }), +/* 121 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.2.2.33 Math.tanh(x) + var $export = __webpack_require__(8); + var expm1 = __webpack_require__(111); + var exp = Math.exp; + + $export($export.S, 'Math', { + tanh: function tanh(x) { + var a = expm1(x = +x); + var b = expm1(-x); + return a == Infinity ? 1 : b == Infinity ? -1 : (a - b) / (exp(x) + exp(-x)); + } + }); + + +/***/ }), +/* 122 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.2.2.34 Math.trunc(x) + var $export = __webpack_require__(8); + + $export($export.S, 'Math', { + trunc: function trunc(it) { + return (it > 0 ? Math.floor : Math.ceil)(it); + } + }); + + +/***/ }), +/* 123 */ +/***/ (function(module, exports, __webpack_require__) { + + var $export = __webpack_require__(8); + var toAbsoluteIndex = __webpack_require__(39); + var fromCharCode = String.fromCharCode; + var $fromCodePoint = String.fromCodePoint; + + // length should be 1, old FF problem + $export($export.S + $export.F * (!!$fromCodePoint && $fromCodePoint.length != 1), 'String', { + // 21.1.2.2 String.fromCodePoint(...codePoints) + fromCodePoint: function fromCodePoint(x) { // eslint-disable-line no-unused-vars + var res = []; + var aLen = arguments.length; + var i = 0; + var code; + while (aLen > i) { + code = +arguments[i++]; + if (toAbsoluteIndex(code, 0x10ffff) !== code) throw RangeError(code + ' is not a valid code point'); + res.push(code < 0x10000 + ? fromCharCode(code) + : fromCharCode(((code -= 0x10000) >> 10) + 0xd800, code % 0x400 + 0xdc00) + ); + } return res.join(''); + } + }); + + +/***/ }), +/* 124 */ +/***/ (function(module, exports, __webpack_require__) { + + var $export = __webpack_require__(8); + var toIObject = __webpack_require__(32); + var toLength = __webpack_require__(37); + + $export($export.S, 'String', { + // 21.1.2.4 String.raw(callSite, ...substitutions) + raw: function raw(callSite) { + var tpl = toIObject(callSite.raw); + var len = toLength(tpl.length); + var aLen = arguments.length; + var res = []; + var i = 0; + while (len > i) { + res.push(String(tpl[i++])); + if (i < aLen) res.push(String(arguments[i])); + } return res.join(''); + } + }); + + +/***/ }), +/* 125 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // 21.1.3.25 String.prototype.trim() + __webpack_require__(82)('trim', function ($trim) { + return function trim() { + return $trim(this, 3); + }; + }); + + +/***/ }), +/* 126 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $at = __webpack_require__(127)(true); + + // 21.1.3.27 String.prototype[@@iterator]() + __webpack_require__(128)(String, 'String', function (iterated) { + this._t = String(iterated); // target + this._i = 0; // next index + // 21.1.5.2.1 %StringIteratorPrototype%.next() + }, function () { + var O = this._t; + var index = this._i; + var point; + if (index >= O.length) return { value: undefined, done: true }; + point = $at(O, index); + this._i += point.length; + return { value: point, done: false }; + }); + + +/***/ }), +/* 127 */ +/***/ (function(module, exports, __webpack_require__) { + + var toInteger = __webpack_require__(38); + var defined = __webpack_require__(35); + // true -> String#at + // false -> String#codePointAt + module.exports = function (TO_STRING) { + return function (that, pos) { + var s = String(defined(that)); + var i = toInteger(pos); + var l = s.length; + var a, b; + if (i < 0 || i >= l) return TO_STRING ? '' : undefined; + a = s.charCodeAt(i); + return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff + ? TO_STRING ? s.charAt(i) : a + : TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000; + }; + }; + + +/***/ }), +/* 128 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var LIBRARY = __webpack_require__(24); + var $export = __webpack_require__(8); + var redefine = __webpack_require__(18); + var hide = __webpack_require__(10); + var Iterators = __webpack_require__(129); + var $iterCreate = __webpack_require__(130); + var setToStringTag = __webpack_require__(25); + var getPrototypeOf = __webpack_require__(58); + var ITERATOR = __webpack_require__(26)('iterator'); + var BUGGY = !([].keys && 'next' in [].keys()); // Safari has buggy iterators w/o `next` + var FF_ITERATOR = '@@iterator'; + var KEYS = 'keys'; + var VALUES = 'values'; + + var returnThis = function () { return this; }; + + module.exports = function (Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED) { + $iterCreate(Constructor, NAME, next); + var getMethod = function (kind) { + if (!BUGGY && kind in proto) return proto[kind]; + switch (kind) { + case KEYS: return function keys() { return new Constructor(this, kind); }; + case VALUES: return function values() { return new Constructor(this, kind); }; + } return function entries() { return new Constructor(this, kind); }; + }; + var TAG = NAME + ' Iterator'; + var DEF_VALUES = DEFAULT == VALUES; + var VALUES_BUG = false; + var proto = Base.prototype; + var $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT]; + var $default = $native || getMethod(DEFAULT); + var $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined; + var $anyNative = NAME == 'Array' ? proto.entries || $native : $native; + var methods, key, IteratorPrototype; + // Fix native + if ($anyNative) { + IteratorPrototype = getPrototypeOf($anyNative.call(new Base())); + if (IteratorPrototype !== Object.prototype && IteratorPrototype.next) { + // Set @@toStringTag to native iterators + setToStringTag(IteratorPrototype, TAG, true); + // fix for some old engines + if (!LIBRARY && typeof IteratorPrototype[ITERATOR] != 'function') hide(IteratorPrototype, ITERATOR, returnThis); + } + } + // fix Array#{values, @@iterator}.name in V8 / FF + if (DEF_VALUES && $native && $native.name !== VALUES) { + VALUES_BUG = true; + $default = function values() { return $native.call(this); }; + } + // Define iterator + if ((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])) { + hide(proto, ITERATOR, $default); + } + // Plug for library + Iterators[NAME] = $default; + Iterators[TAG] = returnThis; + if (DEFAULT) { + methods = { + values: DEF_VALUES ? $default : getMethod(VALUES), + keys: IS_SET ? $default : getMethod(KEYS), + entries: $entries + }; + if (FORCED) for (key in methods) { + if (!(key in proto)) redefine(proto, key, methods[key]); + } else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods); + } + return methods; + }; + + +/***/ }), +/* 129 */ +/***/ (function(module, exports) { + + module.exports = {}; + + +/***/ }), +/* 130 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var create = __webpack_require__(45); + var descriptor = __webpack_require__(17); + var setToStringTag = __webpack_require__(25); + var IteratorPrototype = {}; + + // 25.1.2.1.1 %IteratorPrototype%[@@iterator]() + __webpack_require__(10)(IteratorPrototype, __webpack_require__(26)('iterator'), function () { return this; }); + + module.exports = function (Constructor, NAME, next) { + Constructor.prototype = create(IteratorPrototype, { next: descriptor(1, next) }); + setToStringTag(Constructor, NAME + ' Iterator'); + }; + + +/***/ }), +/* 131 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var $at = __webpack_require__(127)(false); + $export($export.P, 'String', { + // 21.1.3.3 String.prototype.codePointAt(pos) + codePointAt: function codePointAt(pos) { + return $at(this, pos); + } + }); + + +/***/ }), +/* 132 */ +/***/ (function(module, exports, __webpack_require__) { + + // 21.1.3.6 String.prototype.endsWith(searchString [, endPosition]) + 'use strict'; + var $export = __webpack_require__(8); + var toLength = __webpack_require__(37); + var context = __webpack_require__(133); + var ENDS_WITH = 'endsWith'; + var $endsWith = ''[ENDS_WITH]; + + $export($export.P + $export.F * __webpack_require__(135)(ENDS_WITH), 'String', { + endsWith: function endsWith(searchString /* , endPosition = @length */) { + var that = context(this, searchString, ENDS_WITH); + var endPosition = arguments.length > 1 ? arguments[1] : undefined; + var len = toLength(that.length); + var end = endPosition === undefined ? len : Math.min(toLength(endPosition), len); + var search = String(searchString); + return $endsWith + ? $endsWith.call(that, search, end) + : that.slice(end - search.length, end) === search; + } + }); + + +/***/ }), +/* 133 */ +/***/ (function(module, exports, __webpack_require__) { + + // helper for String#{startsWith, endsWith, includes} + var isRegExp = __webpack_require__(134); + var defined = __webpack_require__(35); + + module.exports = function (that, searchString, NAME) { + if (isRegExp(searchString)) throw TypeError('String#' + NAME + " doesn't accept regex!"); + return String(defined(that)); + }; + + +/***/ }), +/* 134 */ +/***/ (function(module, exports, __webpack_require__) { + + // 7.2.8 IsRegExp(argument) + var isObject = __webpack_require__(13); + var cof = __webpack_require__(34); + var MATCH = __webpack_require__(26)('match'); + module.exports = function (it) { + var isRegExp; + return isObject(it) && ((isRegExp = it[MATCH]) !== undefined ? !!isRegExp : cof(it) == 'RegExp'); + }; + + +/***/ }), +/* 135 */ +/***/ (function(module, exports, __webpack_require__) { + + var MATCH = __webpack_require__(26)('match'); + module.exports = function (KEY) { + var re = /./; + try { + '/./'[KEY](re); + } catch (e) { + try { + re[MATCH] = false; + return !'/./'[KEY](re); + } catch (f) { /* empty */ } + } return true; + }; + + +/***/ }), +/* 136 */ +/***/ (function(module, exports, __webpack_require__) { + + // 21.1.3.7 String.prototype.includes(searchString, position = 0) + 'use strict'; + var $export = __webpack_require__(8); + var context = __webpack_require__(133); + var INCLUDES = 'includes'; + + $export($export.P + $export.F * __webpack_require__(135)(INCLUDES), 'String', { + includes: function includes(searchString /* , position = 0 */) { + return !!~context(this, searchString, INCLUDES) + .indexOf(searchString, arguments.length > 1 ? arguments[1] : undefined); + } + }); + + +/***/ }), +/* 137 */ +/***/ (function(module, exports, __webpack_require__) { + + var $export = __webpack_require__(8); + + $export($export.P, 'String', { + // 21.1.3.13 String.prototype.repeat(count) + repeat: __webpack_require__(90) + }); + + +/***/ }), +/* 138 */ +/***/ (function(module, exports, __webpack_require__) { + + // 21.1.3.18 String.prototype.startsWith(searchString [, position ]) + 'use strict'; + var $export = __webpack_require__(8); + var toLength = __webpack_require__(37); + var context = __webpack_require__(133); + var STARTS_WITH = 'startsWith'; + var $startsWith = ''[STARTS_WITH]; + + $export($export.P + $export.F * __webpack_require__(135)(STARTS_WITH), 'String', { + startsWith: function startsWith(searchString /* , position = 0 */) { + var that = context(this, searchString, STARTS_WITH); + var index = toLength(Math.min(arguments.length > 1 ? arguments[1] : undefined, that.length)); + var search = String(searchString); + return $startsWith + ? $startsWith.call(that, search, index) + : that.slice(index, index + search.length) === search; + } + }); + + +/***/ }), +/* 139 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // B.2.3.2 String.prototype.anchor(name) + __webpack_require__(140)('anchor', function (createHTML) { + return function anchor(name) { + return createHTML(this, 'a', 'name', name); + }; + }); + + +/***/ }), +/* 140 */ +/***/ (function(module, exports, __webpack_require__) { + + var $export = __webpack_require__(8); + var fails = __webpack_require__(7); + var defined = __webpack_require__(35); + var quot = /"/g; + // B.2.3.2.1 CreateHTML(string, tag, attribute, value) + var createHTML = function (string, tag, attribute, value) { + var S = String(defined(string)); + var p1 = '<' + tag; + if (attribute !== '') p1 += ' ' + attribute + '="' + String(value).replace(quot, '"') + '"'; + return p1 + '>' + S + ''; + }; + module.exports = function (NAME, exec) { + var O = {}; + O[NAME] = exec(createHTML); + $export($export.P + $export.F * fails(function () { + var test = ''[NAME]('"'); + return test !== test.toLowerCase() || test.split('"').length > 3; + }), 'String', O); + }; + + +/***/ }), +/* 141 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // B.2.3.3 String.prototype.big() + __webpack_require__(140)('big', function (createHTML) { + return function big() { + return createHTML(this, 'big', '', ''); + }; + }); + + +/***/ }), +/* 142 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // B.2.3.4 String.prototype.blink() + __webpack_require__(140)('blink', function (createHTML) { + return function blink() { + return createHTML(this, 'blink', '', ''); + }; + }); + + +/***/ }), +/* 143 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // B.2.3.5 String.prototype.bold() + __webpack_require__(140)('bold', function (createHTML) { + return function bold() { + return createHTML(this, 'b', '', ''); + }; + }); + + +/***/ }), +/* 144 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // B.2.3.6 String.prototype.fixed() + __webpack_require__(140)('fixed', function (createHTML) { + return function fixed() { + return createHTML(this, 'tt', '', ''); + }; + }); + + +/***/ }), +/* 145 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // B.2.3.7 String.prototype.fontcolor(color) + __webpack_require__(140)('fontcolor', function (createHTML) { + return function fontcolor(color) { + return createHTML(this, 'font', 'color', color); + }; + }); + + +/***/ }), +/* 146 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // B.2.3.8 String.prototype.fontsize(size) + __webpack_require__(140)('fontsize', function (createHTML) { + return function fontsize(size) { + return createHTML(this, 'font', 'size', size); + }; + }); + + +/***/ }), +/* 147 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // B.2.3.9 String.prototype.italics() + __webpack_require__(140)('italics', function (createHTML) { + return function italics() { + return createHTML(this, 'i', '', ''); + }; + }); + + +/***/ }), +/* 148 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // B.2.3.10 String.prototype.link(url) + __webpack_require__(140)('link', function (createHTML) { + return function link(url) { + return createHTML(this, 'a', 'href', url); + }; + }); + + +/***/ }), +/* 149 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // B.2.3.11 String.prototype.small() + __webpack_require__(140)('small', function (createHTML) { + return function small() { + return createHTML(this, 'small', '', ''); + }; + }); + + +/***/ }), +/* 150 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // B.2.3.12 String.prototype.strike() + __webpack_require__(140)('strike', function (createHTML) { + return function strike() { + return createHTML(this, 'strike', '', ''); + }; + }); + + +/***/ }), +/* 151 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // B.2.3.13 String.prototype.sub() + __webpack_require__(140)('sub', function (createHTML) { + return function sub() { + return createHTML(this, 'sub', '', ''); + }; + }); + + +/***/ }), +/* 152 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // B.2.3.14 String.prototype.sup() + __webpack_require__(140)('sup', function (createHTML) { + return function sup() { + return createHTML(this, 'sup', '', ''); + }; + }); + + +/***/ }), +/* 153 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.3.3.1 / 15.9.4.4 Date.now() + var $export = __webpack_require__(8); + + $export($export.S, 'Date', { now: function () { return new Date().getTime(); } }); + + +/***/ }), +/* 154 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var toObject = __webpack_require__(57); + var toPrimitive = __webpack_require__(16); + + $export($export.P + $export.F * __webpack_require__(7)(function () { + return new Date(NaN).toJSON() !== null + || Date.prototype.toJSON.call({ toISOString: function () { return 1; } }) !== 1; + }), 'Date', { + // eslint-disable-next-line no-unused-vars + toJSON: function toJSON(key) { + var O = toObject(this); + var pv = toPrimitive(O); + return typeof pv == 'number' && !isFinite(pv) ? null : O.toISOString(); + } + }); + + +/***/ }), +/* 155 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.3.4.36 / 15.9.5.43 Date.prototype.toISOString() + var $export = __webpack_require__(8); + var toISOString = __webpack_require__(156); + + // PhantomJS / old WebKit has a broken implementations + $export($export.P + $export.F * (Date.prototype.toISOString !== toISOString), 'Date', { + toISOString: toISOString + }); + + +/***/ }), +/* 156 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // 20.3.4.36 / 15.9.5.43 Date.prototype.toISOString() + var fails = __webpack_require__(7); + var getTime = Date.prototype.getTime; + var $toISOString = Date.prototype.toISOString; + + var lz = function (num) { + return num > 9 ? num : '0' + num; + }; + + // PhantomJS / old WebKit has a broken implementations + module.exports = (fails(function () { + return $toISOString.call(new Date(-5e13 - 1)) != '0385-07-25T07:06:39.999Z'; + }) || !fails(function () { + $toISOString.call(new Date(NaN)); + })) ? function toISOString() { + if (!isFinite(getTime.call(this))) throw RangeError('Invalid time value'); + var d = this; + var y = d.getUTCFullYear(); + var m = d.getUTCMilliseconds(); + var s = y < 0 ? '-' : y > 9999 ? '+' : ''; + return s + ('00000' + Math.abs(y)).slice(s ? -6 : -4) + + '-' + lz(d.getUTCMonth() + 1) + '-' + lz(d.getUTCDate()) + + 'T' + lz(d.getUTCHours()) + ':' + lz(d.getUTCMinutes()) + + ':' + lz(d.getUTCSeconds()) + '.' + (m > 99 ? m : '0' + lz(m)) + 'Z'; + } : $toISOString; + + +/***/ }), +/* 157 */ +/***/ (function(module, exports, __webpack_require__) { + + var DateProto = Date.prototype; + var INVALID_DATE = 'Invalid Date'; + var TO_STRING = 'toString'; + var $toString = DateProto[TO_STRING]; + var getTime = DateProto.getTime; + if (new Date(NaN) + '' != INVALID_DATE) { + __webpack_require__(18)(DateProto, TO_STRING, function toString() { + var value = getTime.call(this); + // eslint-disable-next-line no-self-compare + return value === value ? $toString.call(this) : INVALID_DATE; + }); + } + + +/***/ }), +/* 158 */ +/***/ (function(module, exports, __webpack_require__) { + + var TO_PRIMITIVE = __webpack_require__(26)('toPrimitive'); + var proto = Date.prototype; + + if (!(TO_PRIMITIVE in proto)) __webpack_require__(10)(proto, TO_PRIMITIVE, __webpack_require__(159)); + + +/***/ }), +/* 159 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var anObject = __webpack_require__(12); + var toPrimitive = __webpack_require__(16); + var NUMBER = 'number'; + + module.exports = function (hint) { + if (hint !== 'string' && hint !== NUMBER && hint !== 'default') throw TypeError('Incorrect hint'); + return toPrimitive(anObject(this), hint != NUMBER); + }; + + +/***/ }), +/* 160 */ +/***/ (function(module, exports, __webpack_require__) { + + // 22.1.2.2 / 15.4.3.2 Array.isArray(arg) + var $export = __webpack_require__(8); + + $export($export.S, 'Array', { isArray: __webpack_require__(44) }); + + +/***/ }), +/* 161 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var ctx = __webpack_require__(20); + var $export = __webpack_require__(8); + var toObject = __webpack_require__(57); + var call = __webpack_require__(162); + var isArrayIter = __webpack_require__(163); + var toLength = __webpack_require__(37); + var createProperty = __webpack_require__(164); + var getIterFn = __webpack_require__(165); + + $export($export.S + $export.F * !__webpack_require__(166)(function (iter) { Array.from(iter); }), 'Array', { + // 22.1.2.1 Array.from(arrayLike, mapfn = undefined, thisArg = undefined) + from: function from(arrayLike /* , mapfn = undefined, thisArg = undefined */) { + var O = toObject(arrayLike); + var C = typeof this == 'function' ? this : Array; + var aLen = arguments.length; + var mapfn = aLen > 1 ? arguments[1] : undefined; + var mapping = mapfn !== undefined; + var index = 0; + var iterFn = getIterFn(O); + var length, result, step, iterator; + if (mapping) mapfn = ctx(mapfn, aLen > 2 ? arguments[2] : undefined, 2); + // if object isn't iterable or it's array with default iterator - use simple case + if (iterFn != undefined && !(C == Array && isArrayIter(iterFn))) { + for (iterator = iterFn.call(O), result = new C(); !(step = iterator.next()).done; index++) { + createProperty(result, index, mapping ? call(iterator, mapfn, [step.value, index], true) : step.value); + } + } else { + length = toLength(O.length); + for (result = new C(length); length > index; index++) { + createProperty(result, index, mapping ? mapfn(O[index], index) : O[index]); + } + } + result.length = index; + return result; + } + }); + + +/***/ }), +/* 162 */ +/***/ (function(module, exports, __webpack_require__) { + + // call something on iterator step with safe closing on error + var anObject = __webpack_require__(12); + module.exports = function (iterator, fn, value, entries) { + try { + return entries ? fn(anObject(value)[0], value[1]) : fn(value); + // 7.4.6 IteratorClose(iterator, completion) + } catch (e) { + var ret = iterator['return']; + if (ret !== undefined) anObject(ret.call(iterator)); + throw e; + } + }; + + +/***/ }), +/* 163 */ +/***/ (function(module, exports, __webpack_require__) { + + // check on default Array iterator + var Iterators = __webpack_require__(129); + var ITERATOR = __webpack_require__(26)('iterator'); + var ArrayProto = Array.prototype; + + module.exports = function (it) { + return it !== undefined && (Iterators.Array === it || ArrayProto[ITERATOR] === it); + }; + + +/***/ }), +/* 164 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $defineProperty = __webpack_require__(11); + var createDesc = __webpack_require__(17); + + module.exports = function (object, index, value) { + if (index in object) $defineProperty.f(object, index, createDesc(0, value)); + else object[index] = value; + }; + + +/***/ }), +/* 165 */ +/***/ (function(module, exports, __webpack_require__) { + + var classof = __webpack_require__(74); + var ITERATOR = __webpack_require__(26)('iterator'); + var Iterators = __webpack_require__(129); + module.exports = __webpack_require__(9).getIteratorMethod = function (it) { + if (it != undefined) return it[ITERATOR] + || it['@@iterator'] + || Iterators[classof(it)]; + }; + + +/***/ }), +/* 166 */ +/***/ (function(module, exports, __webpack_require__) { + + var ITERATOR = __webpack_require__(26)('iterator'); + var SAFE_CLOSING = false; + + try { + var riter = [7][ITERATOR](); + riter['return'] = function () { SAFE_CLOSING = true; }; + // eslint-disable-next-line no-throw-literal + Array.from(riter, function () { throw 2; }); + } catch (e) { /* empty */ } + + module.exports = function (exec, skipClosing) { + if (!skipClosing && !SAFE_CLOSING) return false; + var safe = false; + try { + var arr = [7]; + var iter = arr[ITERATOR](); + iter.next = function () { return { done: safe = true }; }; + arr[ITERATOR] = function () { return iter; }; + exec(arr); + } catch (e) { /* empty */ } + return safe; + }; + + +/***/ }), +/* 167 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var createProperty = __webpack_require__(164); + + // WebKit Array.of isn't generic + $export($export.S + $export.F * __webpack_require__(7)(function () { + function F() { /* empty */ } + return !(Array.of.call(F) instanceof F); + }), 'Array', { + // 22.1.2.3 Array.of( ...items) + of: function of(/* ...args */) { + var index = 0; + var aLen = arguments.length; + var result = new (typeof this == 'function' ? this : Array)(aLen); + while (aLen > index) createProperty(result, index, arguments[index++]); + result.length = aLen; + return result; + } + }); + + +/***/ }), +/* 168 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // 22.1.3.13 Array.prototype.join(separator) + var $export = __webpack_require__(8); + var toIObject = __webpack_require__(32); + var arrayJoin = [].join; + + // fallback for not array-like strings + $export($export.P + $export.F * (__webpack_require__(33) != Object || !__webpack_require__(169)(arrayJoin)), 'Array', { + join: function join(separator) { + return arrayJoin.call(toIObject(this), separator === undefined ? ',' : separator); + } + }); + + +/***/ }), +/* 169 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var fails = __webpack_require__(7); + + module.exports = function (method, arg) { + return !!method && fails(function () { + // eslint-disable-next-line no-useless-call + arg ? method.call(null, function () { /* empty */ }, 1) : method.call(null); + }); + }; + + +/***/ }), +/* 170 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var html = __webpack_require__(47); + var cof = __webpack_require__(34); + var toAbsoluteIndex = __webpack_require__(39); + var toLength = __webpack_require__(37); + var arraySlice = [].slice; + + // fallback for not array-like ES3 strings and DOM objects + $export($export.P + $export.F * __webpack_require__(7)(function () { + if (html) arraySlice.call(html); + }), 'Array', { + slice: function slice(begin, end) { + var len = toLength(this.length); + var klass = cof(this); + end = end === undefined ? len : end; + if (klass == 'Array') return arraySlice.call(this, begin, end); + var start = toAbsoluteIndex(begin, len); + var upTo = toAbsoluteIndex(end, len); + var size = toLength(upTo - start); + var cloned = new Array(size); + var i = 0; + for (; i < size; i++) cloned[i] = klass == 'String' + ? this.charAt(start + i) + : this[start + i]; + return cloned; + } + }); + + +/***/ }), +/* 171 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var aFunction = __webpack_require__(21); + var toObject = __webpack_require__(57); + var fails = __webpack_require__(7); + var $sort = [].sort; + var test = [1, 2, 3]; + + $export($export.P + $export.F * (fails(function () { + // IE8- + test.sort(undefined); + }) || !fails(function () { + // V8 bug + test.sort(null); + // Old WebKit + }) || !__webpack_require__(169)($sort)), 'Array', { + // 22.1.3.25 Array.prototype.sort(comparefn) + sort: function sort(comparefn) { + return comparefn === undefined + ? $sort.call(toObject(this)) + : $sort.call(toObject(this), aFunction(comparefn)); + } + }); + + +/***/ }), +/* 172 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var $forEach = __webpack_require__(173)(0); + var STRICT = __webpack_require__(169)([].forEach, true); + + $export($export.P + $export.F * !STRICT, 'Array', { + // 22.1.3.10 / 15.4.4.18 Array.prototype.forEach(callbackfn [, thisArg]) + forEach: function forEach(callbackfn /* , thisArg */) { + return $forEach(this, callbackfn, arguments[1]); + } + }); + + +/***/ }), +/* 173 */ +/***/ (function(module, exports, __webpack_require__) { + + // 0 -> Array#forEach + // 1 -> Array#map + // 2 -> Array#filter + // 3 -> Array#some + // 4 -> Array#every + // 5 -> Array#find + // 6 -> Array#findIndex + var ctx = __webpack_require__(20); + var IObject = __webpack_require__(33); + var toObject = __webpack_require__(57); + var toLength = __webpack_require__(37); + var asc = __webpack_require__(174); + module.exports = function (TYPE, $create) { + var IS_MAP = TYPE == 1; + var IS_FILTER = TYPE == 2; + var IS_SOME = TYPE == 3; + var IS_EVERY = TYPE == 4; + var IS_FIND_INDEX = TYPE == 6; + var NO_HOLES = TYPE == 5 || IS_FIND_INDEX; + var create = $create || asc; + return function ($this, callbackfn, that) { + var O = toObject($this); + var self = IObject(O); + var f = ctx(callbackfn, that, 3); + var length = toLength(self.length); + var index = 0; + var result = IS_MAP ? create($this, length) : IS_FILTER ? create($this, 0) : undefined; + var val, res; + for (;length > index; index++) if (NO_HOLES || index in self) { + val = self[index]; + res = f(val, index, O); + if (TYPE) { + if (IS_MAP) result[index] = res; // map + else if (res) switch (TYPE) { + case 3: return true; // some + case 5: return val; // find + case 6: return index; // findIndex + case 2: result.push(val); // filter + } else if (IS_EVERY) return false; // every + } + } + return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : result; + }; + }; + + +/***/ }), +/* 174 */ +/***/ (function(module, exports, __webpack_require__) { + + // 9.4.2.3 ArraySpeciesCreate(originalArray, length) + var speciesConstructor = __webpack_require__(175); + + module.exports = function (original, length) { + return new (speciesConstructor(original))(length); + }; + + +/***/ }), +/* 175 */ +/***/ (function(module, exports, __webpack_require__) { + + var isObject = __webpack_require__(13); + var isArray = __webpack_require__(44); + var SPECIES = __webpack_require__(26)('species'); + + module.exports = function (original) { + var C; + if (isArray(original)) { + C = original.constructor; + // cross-realm fallback + if (typeof C == 'function' && (C === Array || isArray(C.prototype))) C = undefined; + if (isObject(C)) { + C = C[SPECIES]; + if (C === null) C = undefined; + } + } return C === undefined ? Array : C; + }; + + +/***/ }), +/* 176 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var $map = __webpack_require__(173)(1); + + $export($export.P + $export.F * !__webpack_require__(169)([].map, true), 'Array', { + // 22.1.3.15 / 15.4.4.19 Array.prototype.map(callbackfn [, thisArg]) + map: function map(callbackfn /* , thisArg */) { + return $map(this, callbackfn, arguments[1]); + } + }); + + +/***/ }), +/* 177 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var $filter = __webpack_require__(173)(2); + + $export($export.P + $export.F * !__webpack_require__(169)([].filter, true), 'Array', { + // 22.1.3.7 / 15.4.4.20 Array.prototype.filter(callbackfn [, thisArg]) + filter: function filter(callbackfn /* , thisArg */) { + return $filter(this, callbackfn, arguments[1]); + } + }); + + +/***/ }), +/* 178 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var $some = __webpack_require__(173)(3); + + $export($export.P + $export.F * !__webpack_require__(169)([].some, true), 'Array', { + // 22.1.3.23 / 15.4.4.17 Array.prototype.some(callbackfn [, thisArg]) + some: function some(callbackfn /* , thisArg */) { + return $some(this, callbackfn, arguments[1]); + } + }); + + +/***/ }), +/* 179 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var $every = __webpack_require__(173)(4); + + $export($export.P + $export.F * !__webpack_require__(169)([].every, true), 'Array', { + // 22.1.3.5 / 15.4.4.16 Array.prototype.every(callbackfn [, thisArg]) + every: function every(callbackfn /* , thisArg */) { + return $every(this, callbackfn, arguments[1]); + } + }); + + +/***/ }), +/* 180 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var $reduce = __webpack_require__(181); + + $export($export.P + $export.F * !__webpack_require__(169)([].reduce, true), 'Array', { + // 22.1.3.18 / 15.4.4.21 Array.prototype.reduce(callbackfn [, initialValue]) + reduce: function reduce(callbackfn /* , initialValue */) { + return $reduce(this, callbackfn, arguments.length, arguments[1], false); + } + }); + + +/***/ }), +/* 181 */ +/***/ (function(module, exports, __webpack_require__) { + + var aFunction = __webpack_require__(21); + var toObject = __webpack_require__(57); + var IObject = __webpack_require__(33); + var toLength = __webpack_require__(37); + + module.exports = function (that, callbackfn, aLen, memo, isRight) { + aFunction(callbackfn); + var O = toObject(that); + var self = IObject(O); + var length = toLength(O.length); + var index = isRight ? length - 1 : 0; + var i = isRight ? -1 : 1; + if (aLen < 2) for (;;) { + if (index in self) { + memo = self[index]; + index += i; + break; + } + index += i; + if (isRight ? index < 0 : length <= index) { + throw TypeError('Reduce of empty array with no initial value'); + } + } + for (;isRight ? index >= 0 : length > index; index += i) if (index in self) { + memo = callbackfn(memo, self[index], index, O); + } + return memo; + }; + + +/***/ }), +/* 182 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var $reduce = __webpack_require__(181); + + $export($export.P + $export.F * !__webpack_require__(169)([].reduceRight, true), 'Array', { + // 22.1.3.19 / 15.4.4.22 Array.prototype.reduceRight(callbackfn [, initialValue]) + reduceRight: function reduceRight(callbackfn /* , initialValue */) { + return $reduce(this, callbackfn, arguments.length, arguments[1], true); + } + }); + + +/***/ }), +/* 183 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var $indexOf = __webpack_require__(36)(false); + var $native = [].indexOf; + var NEGATIVE_ZERO = !!$native && 1 / [1].indexOf(1, -0) < 0; + + $export($export.P + $export.F * (NEGATIVE_ZERO || !__webpack_require__(169)($native)), 'Array', { + // 22.1.3.11 / 15.4.4.14 Array.prototype.indexOf(searchElement [, fromIndex]) + indexOf: function indexOf(searchElement /* , fromIndex = 0 */) { + return NEGATIVE_ZERO + // convert -0 to +0 + ? $native.apply(this, arguments) || 0 + : $indexOf(this, searchElement, arguments[1]); + } + }); + + +/***/ }), +/* 184 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var toIObject = __webpack_require__(32); + var toInteger = __webpack_require__(38); + var toLength = __webpack_require__(37); + var $native = [].lastIndexOf; + var NEGATIVE_ZERO = !!$native && 1 / [1].lastIndexOf(1, -0) < 0; + + $export($export.P + $export.F * (NEGATIVE_ZERO || !__webpack_require__(169)($native)), 'Array', { + // 22.1.3.14 / 15.4.4.15 Array.prototype.lastIndexOf(searchElement [, fromIndex]) + lastIndexOf: function lastIndexOf(searchElement /* , fromIndex = @[*-1] */) { + // convert -0 to +0 + if (NEGATIVE_ZERO) return $native.apply(this, arguments) || 0; + var O = toIObject(this); + var length = toLength(O.length); + var index = length - 1; + if (arguments.length > 1) index = Math.min(index, toInteger(arguments[1])); + if (index < 0) index = length + index; + for (;index >= 0; index--) if (index in O) if (O[index] === searchElement) return index || 0; + return -1; + } + }); + + +/***/ }), +/* 185 */ +/***/ (function(module, exports, __webpack_require__) { + + // 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length) + var $export = __webpack_require__(8); + + $export($export.P, 'Array', { copyWithin: __webpack_require__(186) }); + + __webpack_require__(187)('copyWithin'); + + +/***/ }), +/* 186 */ +/***/ (function(module, exports, __webpack_require__) { + + // 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length) + 'use strict'; + var toObject = __webpack_require__(57); + var toAbsoluteIndex = __webpack_require__(39); + var toLength = __webpack_require__(37); + + module.exports = [].copyWithin || function copyWithin(target /* = 0 */, start /* = 0, end = @length */) { + var O = toObject(this); + var len = toLength(O.length); + var to = toAbsoluteIndex(target, len); + var from = toAbsoluteIndex(start, len); + var end = arguments.length > 2 ? arguments[2] : undefined; + var count = Math.min((end === undefined ? len : toAbsoluteIndex(end, len)) - from, len - to); + var inc = 1; + if (from < to && to < from + count) { + inc = -1; + from += count - 1; + to += count - 1; + } + while (count-- > 0) { + if (from in O) O[to] = O[from]; + else delete O[to]; + to += inc; + from += inc; + } return O; + }; + + +/***/ }), +/* 187 */ +/***/ (function(module, exports, __webpack_require__) { + + // 22.1.3.31 Array.prototype[@@unscopables] + var UNSCOPABLES = __webpack_require__(26)('unscopables'); + var ArrayProto = Array.prototype; + if (ArrayProto[UNSCOPABLES] == undefined) __webpack_require__(10)(ArrayProto, UNSCOPABLES, {}); + module.exports = function (key) { + ArrayProto[UNSCOPABLES][key] = true; + }; + + +/***/ }), +/* 188 */ +/***/ (function(module, exports, __webpack_require__) { + + // 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length) + var $export = __webpack_require__(8); + + $export($export.P, 'Array', { fill: __webpack_require__(189) }); + + __webpack_require__(187)('fill'); + + +/***/ }), +/* 189 */ +/***/ (function(module, exports, __webpack_require__) { + + // 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length) + 'use strict'; + var toObject = __webpack_require__(57); + var toAbsoluteIndex = __webpack_require__(39); + var toLength = __webpack_require__(37); + module.exports = function fill(value /* , start = 0, end = @length */) { + var O = toObject(this); + var length = toLength(O.length); + var aLen = arguments.length; + var index = toAbsoluteIndex(aLen > 1 ? arguments[1] : undefined, length); + var end = aLen > 2 ? arguments[2] : undefined; + var endPos = end === undefined ? length : toAbsoluteIndex(end, length); + while (endPos > index) O[index++] = value; + return O; + }; + + +/***/ }), +/* 190 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // 22.1.3.8 Array.prototype.find(predicate, thisArg = undefined) + var $export = __webpack_require__(8); + var $find = __webpack_require__(173)(5); + var KEY = 'find'; + var forced = true; + // Shouldn't skip holes + if (KEY in []) Array(1)[KEY](function () { forced = false; }); + $export($export.P + $export.F * forced, 'Array', { + find: function find(callbackfn /* , that = undefined */) { + return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); + } + }); + __webpack_require__(187)(KEY); + + +/***/ }), +/* 191 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // 22.1.3.9 Array.prototype.findIndex(predicate, thisArg = undefined) + var $export = __webpack_require__(8); + var $find = __webpack_require__(173)(6); + var KEY = 'findIndex'; + var forced = true; + // Shouldn't skip holes + if (KEY in []) Array(1)[KEY](function () { forced = false; }); + $export($export.P + $export.F * forced, 'Array', { + findIndex: function findIndex(callbackfn /* , that = undefined */) { + return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); + } + }); + __webpack_require__(187)(KEY); + + +/***/ }), +/* 192 */ +/***/ (function(module, exports, __webpack_require__) { + + __webpack_require__(193)('Array'); + + +/***/ }), +/* 193 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var global = __webpack_require__(4); + var dP = __webpack_require__(11); + var DESCRIPTORS = __webpack_require__(6); + var SPECIES = __webpack_require__(26)('species'); + + module.exports = function (KEY) { + var C = global[KEY]; + if (DESCRIPTORS && C && !C[SPECIES]) dP.f(C, SPECIES, { + configurable: true, + get: function () { return this; } + }); + }; + + +/***/ }), +/* 194 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var addToUnscopables = __webpack_require__(187); + var step = __webpack_require__(195); + var Iterators = __webpack_require__(129); + var toIObject = __webpack_require__(32); + + // 22.1.3.4 Array.prototype.entries() + // 22.1.3.13 Array.prototype.keys() + // 22.1.3.29 Array.prototype.values() + // 22.1.3.30 Array.prototype[@@iterator]() + module.exports = __webpack_require__(128)(Array, 'Array', function (iterated, kind) { + this._t = toIObject(iterated); // target + this._i = 0; // next index + this._k = kind; // kind + // 22.1.5.2.1 %ArrayIteratorPrototype%.next() + }, function () { + var O = this._t; + var kind = this._k; + var index = this._i++; + if (!O || index >= O.length) { + this._t = undefined; + return step(1); + } + if (kind == 'keys') return step(0, index); + if (kind == 'values') return step(0, O[index]); + return step(0, [index, O[index]]); + }, 'values'); + + // argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7) + Iterators.Arguments = Iterators.Array; + + addToUnscopables('keys'); + addToUnscopables('values'); + addToUnscopables('entries'); + + +/***/ }), +/* 195 */ +/***/ (function(module, exports) { + + module.exports = function (done, value) { + return { value: value, done: !!done }; + }; + + +/***/ }), +/* 196 */ +/***/ (function(module, exports, __webpack_require__) { + + var global = __webpack_require__(4); + var inheritIfRequired = __webpack_require__(87); + var dP = __webpack_require__(11).f; + var gOPN = __webpack_require__(49).f; + var isRegExp = __webpack_require__(134); + var $flags = __webpack_require__(197); + var $RegExp = global.RegExp; + var Base = $RegExp; + var proto = $RegExp.prototype; + var re1 = /a/g; + var re2 = /a/g; + // "new" creates a new object, old webkit buggy here + var CORRECT_NEW = new $RegExp(re1) !== re1; + + if (__webpack_require__(6) && (!CORRECT_NEW || __webpack_require__(7)(function () { + re2[__webpack_require__(26)('match')] = false; + // RegExp constructor can alter flags and IsRegExp works correct with @@match + return $RegExp(re1) != re1 || $RegExp(re2) == re2 || $RegExp(re1, 'i') != '/a/i'; + }))) { + $RegExp = function RegExp(p, f) { + var tiRE = this instanceof $RegExp; + var piRE = isRegExp(p); + var fiU = f === undefined; + return !tiRE && piRE && p.constructor === $RegExp && fiU ? p + : inheritIfRequired(CORRECT_NEW + ? new Base(piRE && !fiU ? p.source : p, f) + : Base((piRE = p instanceof $RegExp) ? p.source : p, piRE && fiU ? $flags.call(p) : f) + , tiRE ? this : proto, $RegExp); + }; + var proxy = function (key) { + key in $RegExp || dP($RegExp, key, { + configurable: true, + get: function () { return Base[key]; }, + set: function (it) { Base[key] = it; } + }); + }; + for (var keys = gOPN(Base), i = 0; keys.length > i;) proxy(keys[i++]); + proto.constructor = $RegExp; + $RegExp.prototype = proto; + __webpack_require__(18)(global, 'RegExp', $RegExp); + } + + __webpack_require__(193)('RegExp'); + + +/***/ }), +/* 197 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // 21.2.5.3 get RegExp.prototype.flags + var anObject = __webpack_require__(12); + module.exports = function () { + var that = anObject(this); + var result = ''; + if (that.global) result += 'g'; + if (that.ignoreCase) result += 'i'; + if (that.multiline) result += 'm'; + if (that.unicode) result += 'u'; + if (that.sticky) result += 'y'; + return result; + }; + + +/***/ }), +/* 198 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + __webpack_require__(199); + var anObject = __webpack_require__(12); + var $flags = __webpack_require__(197); + var DESCRIPTORS = __webpack_require__(6); + var TO_STRING = 'toString'; + var $toString = /./[TO_STRING]; + + var define = function (fn) { + __webpack_require__(18)(RegExp.prototype, TO_STRING, fn, true); + }; + + // 21.2.5.14 RegExp.prototype.toString() + if (__webpack_require__(7)(function () { return $toString.call({ source: 'a', flags: 'b' }) != '/a/b'; })) { + define(function toString() { + var R = anObject(this); + return '/'.concat(R.source, '/', + 'flags' in R ? R.flags : !DESCRIPTORS && R instanceof RegExp ? $flags.call(R) : undefined); + }); + // FF44- RegExp#toString has a wrong name + } else if ($toString.name != TO_STRING) { + define(function toString() { + return $toString.call(this); + }); + } + + +/***/ }), +/* 199 */ +/***/ (function(module, exports, __webpack_require__) { + + // 21.2.5.3 get RegExp.prototype.flags() + if (__webpack_require__(6) && /./g.flags != 'g') __webpack_require__(11).f(RegExp.prototype, 'flags', { + configurable: true, + get: __webpack_require__(197) + }); + + +/***/ }), +/* 200 */ +/***/ (function(module, exports, __webpack_require__) { + + // @@match logic + __webpack_require__(201)('match', 1, function (defined, MATCH, $match) { + // 21.1.3.11 String.prototype.match(regexp) + return [function match(regexp) { + 'use strict'; + var O = defined(this); + var fn = regexp == undefined ? undefined : regexp[MATCH]; + return fn !== undefined ? fn.call(regexp, O) : new RegExp(regexp)[MATCH](String(O)); + }, $match]; + }); + + +/***/ }), +/* 201 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var hide = __webpack_require__(10); + var redefine = __webpack_require__(18); + var fails = __webpack_require__(7); + var defined = __webpack_require__(35); + var wks = __webpack_require__(26); + + module.exports = function (KEY, length, exec) { + var SYMBOL = wks(KEY); + var fns = exec(defined, SYMBOL, ''[KEY]); + var strfn = fns[0]; + var rxfn = fns[1]; + if (fails(function () { + var O = {}; + O[SYMBOL] = function () { return 7; }; + return ''[KEY](O) != 7; + })) { + redefine(String.prototype, KEY, strfn); + hide(RegExp.prototype, SYMBOL, length == 2 + // 21.2.5.8 RegExp.prototype[@@replace](string, replaceValue) + // 21.2.5.11 RegExp.prototype[@@split](string, limit) + ? function (string, arg) { return rxfn.call(string, this, arg); } + // 21.2.5.6 RegExp.prototype[@@match](string) + // 21.2.5.9 RegExp.prototype[@@search](string) + : function (string) { return rxfn.call(string, this); } + ); + } + }; + + +/***/ }), +/* 202 */ +/***/ (function(module, exports, __webpack_require__) { + + // @@replace logic + __webpack_require__(201)('replace', 2, function (defined, REPLACE, $replace) { + // 21.1.3.14 String.prototype.replace(searchValue, replaceValue) + return [function replace(searchValue, replaceValue) { + 'use strict'; + var O = defined(this); + var fn = searchValue == undefined ? undefined : searchValue[REPLACE]; + return fn !== undefined + ? fn.call(searchValue, O, replaceValue) + : $replace.call(String(O), searchValue, replaceValue); + }, $replace]; + }); + + +/***/ }), +/* 203 */ +/***/ (function(module, exports, __webpack_require__) { + + // @@search logic + __webpack_require__(201)('search', 1, function (defined, SEARCH, $search) { + // 21.1.3.15 String.prototype.search(regexp) + return [function search(regexp) { + 'use strict'; + var O = defined(this); + var fn = regexp == undefined ? undefined : regexp[SEARCH]; + return fn !== undefined ? fn.call(regexp, O) : new RegExp(regexp)[SEARCH](String(O)); + }, $search]; + }); + + +/***/ }), +/* 204 */ +/***/ (function(module, exports, __webpack_require__) { + + // @@split logic + __webpack_require__(201)('split', 2, function (defined, SPLIT, $split) { + 'use strict'; + var isRegExp = __webpack_require__(134); + var _split = $split; + var $push = [].push; + var $SPLIT = 'split'; + var LENGTH = 'length'; + var LAST_INDEX = 'lastIndex'; + if ( + 'abbc'[$SPLIT](/(b)*/)[1] == 'c' || + 'test'[$SPLIT](/(?:)/, -1)[LENGTH] != 4 || + 'ab'[$SPLIT](/(?:ab)*/)[LENGTH] != 2 || + '.'[$SPLIT](/(.?)(.?)/)[LENGTH] != 4 || + '.'[$SPLIT](/()()/)[LENGTH] > 1 || + ''[$SPLIT](/.?/)[LENGTH] + ) { + var NPCG = /()??/.exec('')[1] === undefined; // nonparticipating capturing group + // based on es5-shim implementation, need to rework it + $split = function (separator, limit) { + var string = String(this); + if (separator === undefined && limit === 0) return []; + // If `separator` is not a regex, use native split + if (!isRegExp(separator)) return _split.call(string, separator, limit); + var output = []; + var flags = (separator.ignoreCase ? 'i' : '') + + (separator.multiline ? 'm' : '') + + (separator.unicode ? 'u' : '') + + (separator.sticky ? 'y' : ''); + var lastLastIndex = 0; + var splitLimit = limit === undefined ? 4294967295 : limit >>> 0; + // Make `global` and avoid `lastIndex` issues by working with a copy + var separatorCopy = new RegExp(separator.source, flags + 'g'); + var separator2, match, lastIndex, lastLength, i; + // Doesn't need flags gy, but they don't hurt + if (!NPCG) separator2 = new RegExp('^' + separatorCopy.source + '$(?!\\s)', flags); + while (match = separatorCopy.exec(string)) { + // `separatorCopy.lastIndex` is not reliable cross-browser + lastIndex = match.index + match[0][LENGTH]; + if (lastIndex > lastLastIndex) { + output.push(string.slice(lastLastIndex, match.index)); + // Fix browsers whose `exec` methods don't consistently return `undefined` for NPCG + // eslint-disable-next-line no-loop-func + if (!NPCG && match[LENGTH] > 1) match[0].replace(separator2, function () { + for (i = 1; i < arguments[LENGTH] - 2; i++) if (arguments[i] === undefined) match[i] = undefined; + }); + if (match[LENGTH] > 1 && match.index < string[LENGTH]) $push.apply(output, match.slice(1)); + lastLength = match[0][LENGTH]; + lastLastIndex = lastIndex; + if (output[LENGTH] >= splitLimit) break; + } + if (separatorCopy[LAST_INDEX] === match.index) separatorCopy[LAST_INDEX]++; // Avoid an infinite loop + } + if (lastLastIndex === string[LENGTH]) { + if (lastLength || !separatorCopy.test('')) output.push(''); + } else output.push(string.slice(lastLastIndex)); + return output[LENGTH] > splitLimit ? output.slice(0, splitLimit) : output; + }; + // Chakra, V8 + } else if ('0'[$SPLIT](undefined, 0)[LENGTH]) { + $split = function (separator, limit) { + return separator === undefined && limit === 0 ? [] : _split.call(this, separator, limit); + }; + } + // 21.1.3.17 String.prototype.split(separator, limit) + return [function split(separator, limit) { + var O = defined(this); + var fn = separator == undefined ? undefined : separator[SPLIT]; + return fn !== undefined ? fn.call(separator, O, limit) : $split.call(String(O), separator, limit); + }, $split]; + }); + + +/***/ }), +/* 205 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var LIBRARY = __webpack_require__(24); + var global = __webpack_require__(4); + var ctx = __webpack_require__(20); + var classof = __webpack_require__(74); + var $export = __webpack_require__(8); + var isObject = __webpack_require__(13); + var aFunction = __webpack_require__(21); + var anInstance = __webpack_require__(206); + var forOf = __webpack_require__(207); + var speciesConstructor = __webpack_require__(208); + var task = __webpack_require__(209).set; + var microtask = __webpack_require__(210)(); + var newPromiseCapabilityModule = __webpack_require__(211); + var perform = __webpack_require__(212); + var userAgent = __webpack_require__(213); + var promiseResolve = __webpack_require__(214); + var PROMISE = 'Promise'; + var TypeError = global.TypeError; + var process = global.process; + var versions = process && process.versions; + var v8 = versions && versions.v8 || ''; + var $Promise = global[PROMISE]; + var isNode = classof(process) == 'process'; + var empty = function () { /* empty */ }; + var Internal, newGenericPromiseCapability, OwnPromiseCapability, Wrapper; + var newPromiseCapability = newGenericPromiseCapability = newPromiseCapabilityModule.f; + + var USE_NATIVE = !!function () { + try { + // correct subclassing with @@species support + var promise = $Promise.resolve(1); + var FakePromise = (promise.constructor = {})[__webpack_require__(26)('species')] = function (exec) { + exec(empty, empty); + }; + // unhandled rejections tracking support, NodeJS Promise without it fails @@species test + return (isNode || typeof PromiseRejectionEvent == 'function') + && promise.then(empty) instanceof FakePromise + // v8 6.6 (Node 10 and Chrome 66) have a bug with resolving custom thenables + // https://bugs.chromium.org/p/chromium/issues/detail?id=830565 + // we can't detect it synchronously, so just check versions + && v8.indexOf('6.6') !== 0 + && userAgent.indexOf('Chrome/66') === -1; + } catch (e) { /* empty */ } + }(); + + // helpers + var isThenable = function (it) { + var then; + return isObject(it) && typeof (then = it.then) == 'function' ? then : false; + }; + var notify = function (promise, isReject) { + if (promise._n) return; + promise._n = true; + var chain = promise._c; + microtask(function () { + var value = promise._v; + var ok = promise._s == 1; + var i = 0; + var run = function (reaction) { + var handler = ok ? reaction.ok : reaction.fail; + var resolve = reaction.resolve; + var reject = reaction.reject; + var domain = reaction.domain; + var result, then, exited; + try { + if (handler) { + if (!ok) { + if (promise._h == 2) onHandleUnhandled(promise); + promise._h = 1; + } + if (handler === true) result = value; + else { + if (domain) domain.enter(); + result = handler(value); // may throw + if (domain) { + domain.exit(); + exited = true; + } + } + if (result === reaction.promise) { + reject(TypeError('Promise-chain cycle')); + } else if (then = isThenable(result)) { + then.call(result, resolve, reject); + } else resolve(result); + } else reject(value); + } catch (e) { + if (domain && !exited) domain.exit(); + reject(e); + } + }; + while (chain.length > i) run(chain[i++]); // variable length - can't use forEach + promise._c = []; + promise._n = false; + if (isReject && !promise._h) onUnhandled(promise); + }); + }; + var onUnhandled = function (promise) { + task.call(global, function () { + var value = promise._v; + var unhandled = isUnhandled(promise); + var result, handler, console; + if (unhandled) { + result = perform(function () { + if (isNode) { + process.emit('unhandledRejection', value, promise); + } else if (handler = global.onunhandledrejection) { + handler({ promise: promise, reason: value }); + } else if ((console = global.console) && console.error) { + console.error('Unhandled promise rejection', value); + } + }); + // Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should + promise._h = isNode || isUnhandled(promise) ? 2 : 1; + } promise._a = undefined; + if (unhandled && result.e) throw result.v; + }); + }; + var isUnhandled = function (promise) { + return promise._h !== 1 && (promise._a || promise._c).length === 0; + }; + var onHandleUnhandled = function (promise) { + task.call(global, function () { + var handler; + if (isNode) { + process.emit('rejectionHandled', promise); + } else if (handler = global.onrejectionhandled) { + handler({ promise: promise, reason: promise._v }); + } + }); + }; + var $reject = function (value) { + var promise = this; + if (promise._d) return; + promise._d = true; + promise = promise._w || promise; // unwrap + promise._v = value; + promise._s = 2; + if (!promise._a) promise._a = promise._c.slice(); + notify(promise, true); + }; + var $resolve = function (value) { + var promise = this; + var then; + if (promise._d) return; + promise._d = true; + promise = promise._w || promise; // unwrap + try { + if (promise === value) throw TypeError("Promise can't be resolved itself"); + if (then = isThenable(value)) { + microtask(function () { + var wrapper = { _w: promise, _d: false }; // wrap + try { + then.call(value, ctx($resolve, wrapper, 1), ctx($reject, wrapper, 1)); + } catch (e) { + $reject.call(wrapper, e); + } + }); + } else { + promise._v = value; + promise._s = 1; + notify(promise, false); + } + } catch (e) { + $reject.call({ _w: promise, _d: false }, e); // wrap + } + }; + + // constructor polyfill + if (!USE_NATIVE) { + // 25.4.3.1 Promise(executor) + $Promise = function Promise(executor) { + anInstance(this, $Promise, PROMISE, '_h'); + aFunction(executor); + Internal.call(this); + try { + executor(ctx($resolve, this, 1), ctx($reject, this, 1)); + } catch (err) { + $reject.call(this, err); + } + }; + // eslint-disable-next-line no-unused-vars + Internal = function Promise(executor) { + this._c = []; // <- awaiting reactions + this._a = undefined; // <- checked in isUnhandled reactions + this._s = 0; // <- state + this._d = false; // <- done + this._v = undefined; // <- value + this._h = 0; // <- rejection state, 0 - default, 1 - handled, 2 - unhandled + this._n = false; // <- notify + }; + Internal.prototype = __webpack_require__(215)($Promise.prototype, { + // 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected) + then: function then(onFulfilled, onRejected) { + var reaction = newPromiseCapability(speciesConstructor(this, $Promise)); + reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true; + reaction.fail = typeof onRejected == 'function' && onRejected; + reaction.domain = isNode ? process.domain : undefined; + this._c.push(reaction); + if (this._a) this._a.push(reaction); + if (this._s) notify(this, false); + return reaction.promise; + }, + // 25.4.5.1 Promise.prototype.catch(onRejected) + 'catch': function (onRejected) { + return this.then(undefined, onRejected); + } + }); + OwnPromiseCapability = function () { + var promise = new Internal(); + this.promise = promise; + this.resolve = ctx($resolve, promise, 1); + this.reject = ctx($reject, promise, 1); + }; + newPromiseCapabilityModule.f = newPromiseCapability = function (C) { + return C === $Promise || C === Wrapper + ? new OwnPromiseCapability(C) + : newGenericPromiseCapability(C); + }; + } + + $export($export.G + $export.W + $export.F * !USE_NATIVE, { Promise: $Promise }); + __webpack_require__(25)($Promise, PROMISE); + __webpack_require__(193)(PROMISE); + Wrapper = __webpack_require__(9)[PROMISE]; + + // statics + $export($export.S + $export.F * !USE_NATIVE, PROMISE, { + // 25.4.4.5 Promise.reject(r) + reject: function reject(r) { + var capability = newPromiseCapability(this); + var $$reject = capability.reject; + $$reject(r); + return capability.promise; + } + }); + $export($export.S + $export.F * (LIBRARY || !USE_NATIVE), PROMISE, { + // 25.4.4.6 Promise.resolve(x) + resolve: function resolve(x) { + return promiseResolve(LIBRARY && this === Wrapper ? $Promise : this, x); + } + }); + $export($export.S + $export.F * !(USE_NATIVE && __webpack_require__(166)(function (iter) { + $Promise.all(iter)['catch'](empty); + })), PROMISE, { + // 25.4.4.1 Promise.all(iterable) + all: function all(iterable) { + var C = this; + var capability = newPromiseCapability(C); + var resolve = capability.resolve; + var reject = capability.reject; + var result = perform(function () { + var values = []; + var index = 0; + var remaining = 1; + forOf(iterable, false, function (promise) { + var $index = index++; + var alreadyCalled = false; + values.push(undefined); + remaining++; + C.resolve(promise).then(function (value) { + if (alreadyCalled) return; + alreadyCalled = true; + values[$index] = value; + --remaining || resolve(values); + }, reject); + }); + --remaining || resolve(values); + }); + if (result.e) reject(result.v); + return capability.promise; + }, + // 25.4.4.4 Promise.race(iterable) + race: function race(iterable) { + var C = this; + var capability = newPromiseCapability(C); + var reject = capability.reject; + var result = perform(function () { + forOf(iterable, false, function (promise) { + C.resolve(promise).then(capability.resolve, reject); + }); + }); + if (result.e) reject(result.v); + return capability.promise; + } + }); + + +/***/ }), +/* 206 */ +/***/ (function(module, exports) { + + module.exports = function (it, Constructor, name, forbiddenField) { + if (!(it instanceof Constructor) || (forbiddenField !== undefined && forbiddenField in it)) { + throw TypeError(name + ': incorrect invocation!'); + } return it; + }; + + +/***/ }), +/* 207 */ +/***/ (function(module, exports, __webpack_require__) { + + var ctx = __webpack_require__(20); + var call = __webpack_require__(162); + var isArrayIter = __webpack_require__(163); + var anObject = __webpack_require__(12); + var toLength = __webpack_require__(37); + var getIterFn = __webpack_require__(165); + var BREAK = {}; + var RETURN = {}; + var exports = module.exports = function (iterable, entries, fn, that, ITERATOR) { + var iterFn = ITERATOR ? function () { return iterable; } : getIterFn(iterable); + var f = ctx(fn, that, entries ? 2 : 1); + var index = 0; + var length, step, iterator, result; + if (typeof iterFn != 'function') throw TypeError(iterable + ' is not iterable!'); + // fast case for arrays with default iterator + if (isArrayIter(iterFn)) for (length = toLength(iterable.length); length > index; index++) { + result = entries ? f(anObject(step = iterable[index])[0], step[1]) : f(iterable[index]); + if (result === BREAK || result === RETURN) return result; + } else for (iterator = iterFn.call(iterable); !(step = iterator.next()).done;) { + result = call(iterator, f, step.value, entries); + if (result === BREAK || result === RETURN) return result; + } + }; + exports.BREAK = BREAK; + exports.RETURN = RETURN; + + +/***/ }), +/* 208 */ +/***/ (function(module, exports, __webpack_require__) { + + // 7.3.20 SpeciesConstructor(O, defaultConstructor) + var anObject = __webpack_require__(12); + var aFunction = __webpack_require__(21); + var SPECIES = __webpack_require__(26)('species'); + module.exports = function (O, D) { + var C = anObject(O).constructor; + var S; + return C === undefined || (S = anObject(C)[SPECIES]) == undefined ? D : aFunction(S); + }; + + +/***/ }), +/* 209 */ +/***/ (function(module, exports, __webpack_require__) { + + var ctx = __webpack_require__(20); + var invoke = __webpack_require__(77); + var html = __webpack_require__(47); + var cel = __webpack_require__(15); + var global = __webpack_require__(4); + var process = global.process; + var setTask = global.setImmediate; + var clearTask = global.clearImmediate; + var MessageChannel = global.MessageChannel; + var Dispatch = global.Dispatch; + var counter = 0; + var queue = {}; + var ONREADYSTATECHANGE = 'onreadystatechange'; + var defer, channel, port; + var run = function () { + var id = +this; + // eslint-disable-next-line no-prototype-builtins + if (queue.hasOwnProperty(id)) { + var fn = queue[id]; + delete queue[id]; + fn(); + } + }; + var listener = function (event) { + run.call(event.data); + }; + // Node.js 0.9+ & IE10+ has setImmediate, otherwise: + if (!setTask || !clearTask) { + setTask = function setImmediate(fn) { + var args = []; + var i = 1; + while (arguments.length > i) args.push(arguments[i++]); + queue[++counter] = function () { + // eslint-disable-next-line no-new-func + invoke(typeof fn == 'function' ? fn : Function(fn), args); + }; + defer(counter); + return counter; + }; + clearTask = function clearImmediate(id) { + delete queue[id]; + }; + // Node.js 0.8- + if (__webpack_require__(34)(process) == 'process') { + defer = function (id) { + process.nextTick(ctx(run, id, 1)); + }; + // Sphere (JS game engine) Dispatch API + } else if (Dispatch && Dispatch.now) { + defer = function (id) { + Dispatch.now(ctx(run, id, 1)); + }; + // Browsers with MessageChannel, includes WebWorkers + } else if (MessageChannel) { + channel = new MessageChannel(); + port = channel.port2; + channel.port1.onmessage = listener; + defer = ctx(port.postMessage, port, 1); + // Browsers with postMessage, skip WebWorkers + // IE8 has postMessage, but it's sync & typeof its postMessage is 'object' + } else if (global.addEventListener && typeof postMessage == 'function' && !global.importScripts) { + defer = function (id) { + global.postMessage(id + '', '*'); + }; + global.addEventListener('message', listener, false); + // IE8- + } else if (ONREADYSTATECHANGE in cel('script')) { + defer = function (id) { + html.appendChild(cel('script'))[ONREADYSTATECHANGE] = function () { + html.removeChild(this); + run.call(id); + }; + }; + // Rest old browsers + } else { + defer = function (id) { + setTimeout(ctx(run, id, 1), 0); + }; + } + } + module.exports = { + set: setTask, + clear: clearTask + }; + + +/***/ }), +/* 210 */ +/***/ (function(module, exports, __webpack_require__) { + + var global = __webpack_require__(4); + var macrotask = __webpack_require__(209).set; + var Observer = global.MutationObserver || global.WebKitMutationObserver; + var process = global.process; + var Promise = global.Promise; + var isNode = __webpack_require__(34)(process) == 'process'; + + module.exports = function () { + var head, last, notify; + + var flush = function () { + var parent, fn; + if (isNode && (parent = process.domain)) parent.exit(); + while (head) { + fn = head.fn; + head = head.next; + try { + fn(); + } catch (e) { + if (head) notify(); + else last = undefined; + throw e; + } + } last = undefined; + if (parent) parent.enter(); + }; + + // Node.js + if (isNode) { + notify = function () { + process.nextTick(flush); + }; + // browsers with MutationObserver, except iOS Safari - https://github.com/zloirock/core-js/issues/339 + } else if (Observer && !(global.navigator && global.navigator.standalone)) { + var toggle = true; + var node = document.createTextNode(''); + new Observer(flush).observe(node, { characterData: true }); // eslint-disable-line no-new + notify = function () { + node.data = toggle = !toggle; + }; + // environments with maybe non-completely correct, but existent Promise + } else if (Promise && Promise.resolve) { + // Promise.resolve without an argument throws an error in LG WebOS 2 + var promise = Promise.resolve(undefined); + notify = function () { + promise.then(flush); + }; + // for other environments - macrotask based on: + // - setImmediate + // - MessageChannel + // - window.postMessag + // - onreadystatechange + // - setTimeout + } else { + notify = function () { + // strange IE + webpack dev server bug - use .call(global) + macrotask.call(global, flush); + }; + } + + return function (fn) { + var task = { fn: fn, next: undefined }; + if (last) last.next = task; + if (!head) { + head = task; + notify(); + } last = task; + }; + }; + + +/***/ }), +/* 211 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // 25.4.1.5 NewPromiseCapability(C) + var aFunction = __webpack_require__(21); + + function PromiseCapability(C) { + var resolve, reject; + this.promise = new C(function ($$resolve, $$reject) { + if (resolve !== undefined || reject !== undefined) throw TypeError('Bad Promise constructor'); + resolve = $$resolve; + reject = $$reject; + }); + this.resolve = aFunction(resolve); + this.reject = aFunction(reject); + } + + module.exports.f = function (C) { + return new PromiseCapability(C); + }; + + +/***/ }), +/* 212 */ +/***/ (function(module, exports) { + + module.exports = function (exec) { + try { + return { e: false, v: exec() }; + } catch (e) { + return { e: true, v: e }; + } + }; + + +/***/ }), +/* 213 */ +/***/ (function(module, exports, __webpack_require__) { + + var global = __webpack_require__(4); + var navigator = global.navigator; + + module.exports = navigator && navigator.userAgent || ''; + + +/***/ }), +/* 214 */ +/***/ (function(module, exports, __webpack_require__) { + + var anObject = __webpack_require__(12); + var isObject = __webpack_require__(13); + var newPromiseCapability = __webpack_require__(211); + + module.exports = function (C, x) { + anObject(C); + if (isObject(x) && x.constructor === C) return x; + var promiseCapability = newPromiseCapability.f(C); + var resolve = promiseCapability.resolve; + resolve(x); + return promiseCapability.promise; + }; + + +/***/ }), +/* 215 */ +/***/ (function(module, exports, __webpack_require__) { + + var redefine = __webpack_require__(18); + module.exports = function (target, src, safe) { + for (var key in src) redefine(target, key, src[key], safe); + return target; + }; + + +/***/ }), +/* 216 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var strong = __webpack_require__(217); + var validate = __webpack_require__(218); + var MAP = 'Map'; + + // 23.1 Map Objects + module.exports = __webpack_require__(219)(MAP, function (get) { + return function Map() { return get(this, arguments.length > 0 ? arguments[0] : undefined); }; + }, { + // 23.1.3.6 Map.prototype.get(key) + get: function get(key) { + var entry = strong.getEntry(validate(this, MAP), key); + return entry && entry.v; + }, + // 23.1.3.9 Map.prototype.set(key, value) + set: function set(key, value) { + return strong.def(validate(this, MAP), key === 0 ? 0 : key, value); + } + }, strong, true); + + +/***/ }), +/* 217 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var dP = __webpack_require__(11).f; + var create = __webpack_require__(45); + var redefineAll = __webpack_require__(215); + var ctx = __webpack_require__(20); + var anInstance = __webpack_require__(206); + var forOf = __webpack_require__(207); + var $iterDefine = __webpack_require__(128); + var step = __webpack_require__(195); + var setSpecies = __webpack_require__(193); + var DESCRIPTORS = __webpack_require__(6); + var fastKey = __webpack_require__(22).fastKey; + var validate = __webpack_require__(218); + var SIZE = DESCRIPTORS ? '_s' : 'size'; + + var getEntry = function (that, key) { + // fast case + var index = fastKey(key); + var entry; + if (index !== 'F') return that._i[index]; + // frozen object case + for (entry = that._f; entry; entry = entry.n) { + if (entry.k == key) return entry; + } + }; + + module.exports = { + getConstructor: function (wrapper, NAME, IS_MAP, ADDER) { + var C = wrapper(function (that, iterable) { + anInstance(that, C, NAME, '_i'); + that._t = NAME; // collection type + that._i = create(null); // index + that._f = undefined; // first entry + that._l = undefined; // last entry + that[SIZE] = 0; // size + if (iterable != undefined) forOf(iterable, IS_MAP, that[ADDER], that); + }); + redefineAll(C.prototype, { + // 23.1.3.1 Map.prototype.clear() + // 23.2.3.2 Set.prototype.clear() + clear: function clear() { + for (var that = validate(this, NAME), data = that._i, entry = that._f; entry; entry = entry.n) { + entry.r = true; + if (entry.p) entry.p = entry.p.n = undefined; + delete data[entry.i]; + } + that._f = that._l = undefined; + that[SIZE] = 0; + }, + // 23.1.3.3 Map.prototype.delete(key) + // 23.2.3.4 Set.prototype.delete(value) + 'delete': function (key) { + var that = validate(this, NAME); + var entry = getEntry(that, key); + if (entry) { + var next = entry.n; + var prev = entry.p; + delete that._i[entry.i]; + entry.r = true; + if (prev) prev.n = next; + if (next) next.p = prev; + if (that._f == entry) that._f = next; + if (that._l == entry) that._l = prev; + that[SIZE]--; + } return !!entry; + }, + // 23.2.3.6 Set.prototype.forEach(callbackfn, thisArg = undefined) + // 23.1.3.5 Map.prototype.forEach(callbackfn, thisArg = undefined) + forEach: function forEach(callbackfn /* , that = undefined */) { + validate(this, NAME); + var f = ctx(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3); + var entry; + while (entry = entry ? entry.n : this._f) { + f(entry.v, entry.k, this); + // revert to the last existing entry + while (entry && entry.r) entry = entry.p; + } + }, + // 23.1.3.7 Map.prototype.has(key) + // 23.2.3.7 Set.prototype.has(value) + has: function has(key) { + return !!getEntry(validate(this, NAME), key); + } + }); + if (DESCRIPTORS) dP(C.prototype, 'size', { + get: function () { + return validate(this, NAME)[SIZE]; + } + }); + return C; + }, + def: function (that, key, value) { + var entry = getEntry(that, key); + var prev, index; + // change existing entry + if (entry) { + entry.v = value; + // create new entry + } else { + that._l = entry = { + i: index = fastKey(key, true), // <- index + k: key, // <- key + v: value, // <- value + p: prev = that._l, // <- previous entry + n: undefined, // <- next entry + r: false // <- removed + }; + if (!that._f) that._f = entry; + if (prev) prev.n = entry; + that[SIZE]++; + // add to index + if (index !== 'F') that._i[index] = entry; + } return that; + }, + getEntry: getEntry, + setStrong: function (C, NAME, IS_MAP) { + // add .keys, .values, .entries, [@@iterator] + // 23.1.3.4, 23.1.3.8, 23.1.3.11, 23.1.3.12, 23.2.3.5, 23.2.3.8, 23.2.3.10, 23.2.3.11 + $iterDefine(C, NAME, function (iterated, kind) { + this._t = validate(iterated, NAME); // target + this._k = kind; // kind + this._l = undefined; // previous + }, function () { + var that = this; + var kind = that._k; + var entry = that._l; + // revert to the last existing entry + while (entry && entry.r) entry = entry.p; + // get next entry + if (!that._t || !(that._l = entry = entry ? entry.n : that._t._f)) { + // or finish the iteration + that._t = undefined; + return step(1); + } + // return step by kind + if (kind == 'keys') return step(0, entry.k); + if (kind == 'values') return step(0, entry.v); + return step(0, [entry.k, entry.v]); + }, IS_MAP ? 'entries' : 'values', !IS_MAP, true); + + // add [@@species], 23.1.2.2, 23.2.2.2 + setSpecies(NAME); + } + }; + + +/***/ }), +/* 218 */ +/***/ (function(module, exports, __webpack_require__) { + + var isObject = __webpack_require__(13); + module.exports = function (it, TYPE) { + if (!isObject(it) || it._t !== TYPE) throw TypeError('Incompatible receiver, ' + TYPE + ' required!'); + return it; + }; + + +/***/ }), +/* 219 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var global = __webpack_require__(4); + var $export = __webpack_require__(8); + var redefine = __webpack_require__(18); + var redefineAll = __webpack_require__(215); + var meta = __webpack_require__(22); + var forOf = __webpack_require__(207); + var anInstance = __webpack_require__(206); + var isObject = __webpack_require__(13); + var fails = __webpack_require__(7); + var $iterDetect = __webpack_require__(166); + var setToStringTag = __webpack_require__(25); + var inheritIfRequired = __webpack_require__(87); + + module.exports = function (NAME, wrapper, methods, common, IS_MAP, IS_WEAK) { + var Base = global[NAME]; + var C = Base; + var ADDER = IS_MAP ? 'set' : 'add'; + var proto = C && C.prototype; + var O = {}; + var fixMethod = function (KEY) { + var fn = proto[KEY]; + redefine(proto, KEY, + KEY == 'delete' ? function (a) { + return IS_WEAK && !isObject(a) ? false : fn.call(this, a === 0 ? 0 : a); + } : KEY == 'has' ? function has(a) { + return IS_WEAK && !isObject(a) ? false : fn.call(this, a === 0 ? 0 : a); + } : KEY == 'get' ? function get(a) { + return IS_WEAK && !isObject(a) ? undefined : fn.call(this, a === 0 ? 0 : a); + } : KEY == 'add' ? function add(a) { fn.call(this, a === 0 ? 0 : a); return this; } + : function set(a, b) { fn.call(this, a === 0 ? 0 : a, b); return this; } + ); + }; + if (typeof C != 'function' || !(IS_WEAK || proto.forEach && !fails(function () { + new C().entries().next(); + }))) { + // create collection constructor + C = common.getConstructor(wrapper, NAME, IS_MAP, ADDER); + redefineAll(C.prototype, methods); + meta.NEED = true; + } else { + var instance = new C(); + // early implementations not supports chaining + var HASNT_CHAINING = instance[ADDER](IS_WEAK ? {} : -0, 1) != instance; + // V8 ~ Chromium 40- weak-collections throws on primitives, but should return false + var THROWS_ON_PRIMITIVES = fails(function () { instance.has(1); }); + // most early implementations doesn't supports iterables, most modern - not close it correctly + var ACCEPT_ITERABLES = $iterDetect(function (iter) { new C(iter); }); // eslint-disable-line no-new + // for early implementations -0 and +0 not the same + var BUGGY_ZERO = !IS_WEAK && fails(function () { + // V8 ~ Chromium 42- fails only with 5+ elements + var $instance = new C(); + var index = 5; + while (index--) $instance[ADDER](index, index); + return !$instance.has(-0); + }); + if (!ACCEPT_ITERABLES) { + C = wrapper(function (target, iterable) { + anInstance(target, C, NAME); + var that = inheritIfRequired(new Base(), target, C); + if (iterable != undefined) forOf(iterable, IS_MAP, that[ADDER], that); + return that; + }); + C.prototype = proto; + proto.constructor = C; + } + if (THROWS_ON_PRIMITIVES || BUGGY_ZERO) { + fixMethod('delete'); + fixMethod('has'); + IS_MAP && fixMethod('get'); + } + if (BUGGY_ZERO || HASNT_CHAINING) fixMethod(ADDER); + // weak collections should not contains .clear method + if (IS_WEAK && proto.clear) delete proto.clear; + } + + setToStringTag(C, NAME); + + O[NAME] = C; + $export($export.G + $export.W + $export.F * (C != Base), O); + + if (!IS_WEAK) common.setStrong(C, NAME, IS_MAP); + + return C; + }; + + +/***/ }), +/* 220 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var strong = __webpack_require__(217); + var validate = __webpack_require__(218); + var SET = 'Set'; + + // 23.2 Set Objects + module.exports = __webpack_require__(219)(SET, function (get) { + return function Set() { return get(this, arguments.length > 0 ? arguments[0] : undefined); }; + }, { + // 23.2.3.1 Set.prototype.add(value) + add: function add(value) { + return strong.def(validate(this, SET), value = value === 0 ? 0 : value, value); + } + }, strong); + + +/***/ }), +/* 221 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var each = __webpack_require__(173)(0); + var redefine = __webpack_require__(18); + var meta = __webpack_require__(22); + var assign = __webpack_require__(68); + var weak = __webpack_require__(222); + var isObject = __webpack_require__(13); + var fails = __webpack_require__(7); + var validate = __webpack_require__(218); + var WEAK_MAP = 'WeakMap'; + var getWeak = meta.getWeak; + var isExtensible = Object.isExtensible; + var uncaughtFrozenStore = weak.ufstore; + var tmp = {}; + var InternalMap; + + var wrapper = function (get) { + return function WeakMap() { + return get(this, arguments.length > 0 ? arguments[0] : undefined); + }; + }; + + var methods = { + // 23.3.3.3 WeakMap.prototype.get(key) + get: function get(key) { + if (isObject(key)) { + var data = getWeak(key); + if (data === true) return uncaughtFrozenStore(validate(this, WEAK_MAP)).get(key); + return data ? data[this._i] : undefined; + } + }, + // 23.3.3.5 WeakMap.prototype.set(key, value) + set: function set(key, value) { + return weak.def(validate(this, WEAK_MAP), key, value); + } + }; + + // 23.3 WeakMap Objects + var $WeakMap = module.exports = __webpack_require__(219)(WEAK_MAP, wrapper, methods, weak, true, true); + + // IE11 WeakMap frozen keys fix + if (fails(function () { return new $WeakMap().set((Object.freeze || Object)(tmp), 7).get(tmp) != 7; })) { + InternalMap = weak.getConstructor(wrapper, WEAK_MAP); + assign(InternalMap.prototype, methods); + meta.NEED = true; + each(['delete', 'has', 'get', 'set'], function (key) { + var proto = $WeakMap.prototype; + var method = proto[key]; + redefine(proto, key, function (a, b) { + // store frozen objects on internal weakmap shim + if (isObject(a) && !isExtensible(a)) { + if (!this._f) this._f = new InternalMap(); + var result = this._f[key](a, b); + return key == 'set' ? this : result; + // store all the rest on native weakmap + } return method.call(this, a, b); + }); + }); + } + + +/***/ }), +/* 222 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var redefineAll = __webpack_require__(215); + var getWeak = __webpack_require__(22).getWeak; + var anObject = __webpack_require__(12); + var isObject = __webpack_require__(13); + var anInstance = __webpack_require__(206); + var forOf = __webpack_require__(207); + var createArrayMethod = __webpack_require__(173); + var $has = __webpack_require__(5); + var validate = __webpack_require__(218); + var arrayFind = createArrayMethod(5); + var arrayFindIndex = createArrayMethod(6); + var id = 0; + + // fallback for uncaught frozen keys + var uncaughtFrozenStore = function (that) { + return that._l || (that._l = new UncaughtFrozenStore()); + }; + var UncaughtFrozenStore = function () { + this.a = []; + }; + var findUncaughtFrozen = function (store, key) { + return arrayFind(store.a, function (it) { + return it[0] === key; + }); + }; + UncaughtFrozenStore.prototype = { + get: function (key) { + var entry = findUncaughtFrozen(this, key); + if (entry) return entry[1]; + }, + has: function (key) { + return !!findUncaughtFrozen(this, key); + }, + set: function (key, value) { + var entry = findUncaughtFrozen(this, key); + if (entry) entry[1] = value; + else this.a.push([key, value]); + }, + 'delete': function (key) { + var index = arrayFindIndex(this.a, function (it) { + return it[0] === key; + }); + if (~index) this.a.splice(index, 1); + return !!~index; + } + }; + + module.exports = { + getConstructor: function (wrapper, NAME, IS_MAP, ADDER) { + var C = wrapper(function (that, iterable) { + anInstance(that, C, NAME, '_i'); + that._t = NAME; // collection type + that._i = id++; // collection id + that._l = undefined; // leak store for uncaught frozen objects + if (iterable != undefined) forOf(iterable, IS_MAP, that[ADDER], that); + }); + redefineAll(C.prototype, { + // 23.3.3.2 WeakMap.prototype.delete(key) + // 23.4.3.3 WeakSet.prototype.delete(value) + 'delete': function (key) { + if (!isObject(key)) return false; + var data = getWeak(key); + if (data === true) return uncaughtFrozenStore(validate(this, NAME))['delete'](key); + return data && $has(data, this._i) && delete data[this._i]; + }, + // 23.3.3.4 WeakMap.prototype.has(key) + // 23.4.3.4 WeakSet.prototype.has(value) + has: function has(key) { + if (!isObject(key)) return false; + var data = getWeak(key); + if (data === true) return uncaughtFrozenStore(validate(this, NAME)).has(key); + return data && $has(data, this._i); + } + }); + return C; + }, + def: function (that, key, value) { + var data = getWeak(anObject(key), true); + if (data === true) uncaughtFrozenStore(that).set(key, value); + else data[that._i] = value; + return that; + }, + ufstore: uncaughtFrozenStore + }; + + +/***/ }), +/* 223 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var weak = __webpack_require__(222); + var validate = __webpack_require__(218); + var WEAK_SET = 'WeakSet'; + + // 23.4 WeakSet Objects + __webpack_require__(219)(WEAK_SET, function (get) { + return function WeakSet() { return get(this, arguments.length > 0 ? arguments[0] : undefined); }; + }, { + // 23.4.3.1 WeakSet.prototype.add(value) + add: function add(value) { + return weak.def(validate(this, WEAK_SET), value, true); + } + }, weak, false, true); + + +/***/ }), +/* 224 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var $typed = __webpack_require__(225); + var buffer = __webpack_require__(226); + var anObject = __webpack_require__(12); + var toAbsoluteIndex = __webpack_require__(39); + var toLength = __webpack_require__(37); + var isObject = __webpack_require__(13); + var ArrayBuffer = __webpack_require__(4).ArrayBuffer; + var speciesConstructor = __webpack_require__(208); + var $ArrayBuffer = buffer.ArrayBuffer; + var $DataView = buffer.DataView; + var $isView = $typed.ABV && ArrayBuffer.isView; + var $slice = $ArrayBuffer.prototype.slice; + var VIEW = $typed.VIEW; + var ARRAY_BUFFER = 'ArrayBuffer'; + + $export($export.G + $export.W + $export.F * (ArrayBuffer !== $ArrayBuffer), { ArrayBuffer: $ArrayBuffer }); + + $export($export.S + $export.F * !$typed.CONSTR, ARRAY_BUFFER, { + // 24.1.3.1 ArrayBuffer.isView(arg) + isView: function isView(it) { + return $isView && $isView(it) || isObject(it) && VIEW in it; + } + }); + + $export($export.P + $export.U + $export.F * __webpack_require__(7)(function () { + return !new $ArrayBuffer(2).slice(1, undefined).byteLength; + }), ARRAY_BUFFER, { + // 24.1.4.3 ArrayBuffer.prototype.slice(start, end) + slice: function slice(start, end) { + if ($slice !== undefined && end === undefined) return $slice.call(anObject(this), start); // FF fix + var len = anObject(this).byteLength; + var first = toAbsoluteIndex(start, len); + var fin = toAbsoluteIndex(end === undefined ? len : end, len); + var result = new (speciesConstructor(this, $ArrayBuffer))(toLength(fin - first)); + var viewS = new $DataView(this); + var viewT = new $DataView(result); + var index = 0; + while (first < fin) { + viewT.setUint8(index++, viewS.getUint8(first++)); + } return result; + } + }); + + __webpack_require__(193)(ARRAY_BUFFER); + + +/***/ }), +/* 225 */ +/***/ (function(module, exports, __webpack_require__) { + + var global = __webpack_require__(4); + var hide = __webpack_require__(10); + var uid = __webpack_require__(19); + var TYPED = uid('typed_array'); + var VIEW = uid('view'); + var ABV = !!(global.ArrayBuffer && global.DataView); + var CONSTR = ABV; + var i = 0; + var l = 9; + var Typed; + + var TypedArrayConstructors = ( + 'Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array' + ).split(','); + + while (i < l) { + if (Typed = global[TypedArrayConstructors[i++]]) { + hide(Typed.prototype, TYPED, true); + hide(Typed.prototype, VIEW, true); + } else CONSTR = false; + } + + module.exports = { + ABV: ABV, + CONSTR: CONSTR, + TYPED: TYPED, + VIEW: VIEW + }; + + +/***/ }), +/* 226 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var global = __webpack_require__(4); + var DESCRIPTORS = __webpack_require__(6); + var LIBRARY = __webpack_require__(24); + var $typed = __webpack_require__(225); + var hide = __webpack_require__(10); + var redefineAll = __webpack_require__(215); + var fails = __webpack_require__(7); + var anInstance = __webpack_require__(206); + var toInteger = __webpack_require__(38); + var toLength = __webpack_require__(37); + var toIndex = __webpack_require__(227); + var gOPN = __webpack_require__(49).f; + var dP = __webpack_require__(11).f; + var arrayFill = __webpack_require__(189); + var setToStringTag = __webpack_require__(25); + var ARRAY_BUFFER = 'ArrayBuffer'; + var DATA_VIEW = 'DataView'; + var PROTOTYPE = 'prototype'; + var WRONG_LENGTH = 'Wrong length!'; + var WRONG_INDEX = 'Wrong index!'; + var $ArrayBuffer = global[ARRAY_BUFFER]; + var $DataView = global[DATA_VIEW]; + var Math = global.Math; + var RangeError = global.RangeError; + // eslint-disable-next-line no-shadow-restricted-names + var Infinity = global.Infinity; + var BaseBuffer = $ArrayBuffer; + var abs = Math.abs; + var pow = Math.pow; + var floor = Math.floor; + var log = Math.log; + var LN2 = Math.LN2; + var BUFFER = 'buffer'; + var BYTE_LENGTH = 'byteLength'; + var BYTE_OFFSET = 'byteOffset'; + var $BUFFER = DESCRIPTORS ? '_b' : BUFFER; + var $LENGTH = DESCRIPTORS ? '_l' : BYTE_LENGTH; + var $OFFSET = DESCRIPTORS ? '_o' : BYTE_OFFSET; + + // IEEE754 conversions based on https://github.com/feross/ieee754 + function packIEEE754(value, mLen, nBytes) { + var buffer = new Array(nBytes); + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var rt = mLen === 23 ? pow(2, -24) - pow(2, -77) : 0; + var i = 0; + var s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0; + var e, m, c; + value = abs(value); + // eslint-disable-next-line no-self-compare + if (value != value || value === Infinity) { + // eslint-disable-next-line no-self-compare + m = value != value ? 1 : 0; + e = eMax; + } else { + e = floor(log(value) / LN2); + if (value * (c = pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value += rt / c; + } else { + value += rt * pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * pow(2, mLen); + e = e + eBias; + } else { + m = value * pow(2, eBias - 1) * pow(2, mLen); + e = 0; + } + } + for (; mLen >= 8; buffer[i++] = m & 255, m /= 256, mLen -= 8); + e = e << mLen | m; + eLen += mLen; + for (; eLen > 0; buffer[i++] = e & 255, e /= 256, eLen -= 8); + buffer[--i] |= s * 128; + return buffer; + } + function unpackIEEE754(buffer, mLen, nBytes) { + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var nBits = eLen - 7; + var i = nBytes - 1; + var s = buffer[i--]; + var e = s & 127; + var m; + s >>= 7; + for (; nBits > 0; e = e * 256 + buffer[i], i--, nBits -= 8); + m = e & (1 << -nBits) - 1; + e >>= -nBits; + nBits += mLen; + for (; nBits > 0; m = m * 256 + buffer[i], i--, nBits -= 8); + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : s ? -Infinity : Infinity; + } else { + m = m + pow(2, mLen); + e = e - eBias; + } return (s ? -1 : 1) * m * pow(2, e - mLen); + } + + function unpackI32(bytes) { + return bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0]; + } + function packI8(it) { + return [it & 0xff]; + } + function packI16(it) { + return [it & 0xff, it >> 8 & 0xff]; + } + function packI32(it) { + return [it & 0xff, it >> 8 & 0xff, it >> 16 & 0xff, it >> 24 & 0xff]; + } + function packF64(it) { + return packIEEE754(it, 52, 8); + } + function packF32(it) { + return packIEEE754(it, 23, 4); + } + + function addGetter(C, key, internal) { + dP(C[PROTOTYPE], key, { get: function () { return this[internal]; } }); + } + + function get(view, bytes, index, isLittleEndian) { + var numIndex = +index; + var intIndex = toIndex(numIndex); + if (intIndex + bytes > view[$LENGTH]) throw RangeError(WRONG_INDEX); + var store = view[$BUFFER]._b; + var start = intIndex + view[$OFFSET]; + var pack = store.slice(start, start + bytes); + return isLittleEndian ? pack : pack.reverse(); + } + function set(view, bytes, index, conversion, value, isLittleEndian) { + var numIndex = +index; + var intIndex = toIndex(numIndex); + if (intIndex + bytes > view[$LENGTH]) throw RangeError(WRONG_INDEX); + var store = view[$BUFFER]._b; + var start = intIndex + view[$OFFSET]; + var pack = conversion(+value); + for (var i = 0; i < bytes; i++) store[start + i] = pack[isLittleEndian ? i : bytes - i - 1]; + } + + if (!$typed.ABV) { + $ArrayBuffer = function ArrayBuffer(length) { + anInstance(this, $ArrayBuffer, ARRAY_BUFFER); + var byteLength = toIndex(length); + this._b = arrayFill.call(new Array(byteLength), 0); + this[$LENGTH] = byteLength; + }; + + $DataView = function DataView(buffer, byteOffset, byteLength) { + anInstance(this, $DataView, DATA_VIEW); + anInstance(buffer, $ArrayBuffer, DATA_VIEW); + var bufferLength = buffer[$LENGTH]; + var offset = toInteger(byteOffset); + if (offset < 0 || offset > bufferLength) throw RangeError('Wrong offset!'); + byteLength = byteLength === undefined ? bufferLength - offset : toLength(byteLength); + if (offset + byteLength > bufferLength) throw RangeError(WRONG_LENGTH); + this[$BUFFER] = buffer; + this[$OFFSET] = offset; + this[$LENGTH] = byteLength; + }; + + if (DESCRIPTORS) { + addGetter($ArrayBuffer, BYTE_LENGTH, '_l'); + addGetter($DataView, BUFFER, '_b'); + addGetter($DataView, BYTE_LENGTH, '_l'); + addGetter($DataView, BYTE_OFFSET, '_o'); + } + + redefineAll($DataView[PROTOTYPE], { + getInt8: function getInt8(byteOffset) { + return get(this, 1, byteOffset)[0] << 24 >> 24; + }, + getUint8: function getUint8(byteOffset) { + return get(this, 1, byteOffset)[0]; + }, + getInt16: function getInt16(byteOffset /* , littleEndian */) { + var bytes = get(this, 2, byteOffset, arguments[1]); + return (bytes[1] << 8 | bytes[0]) << 16 >> 16; + }, + getUint16: function getUint16(byteOffset /* , littleEndian */) { + var bytes = get(this, 2, byteOffset, arguments[1]); + return bytes[1] << 8 | bytes[0]; + }, + getInt32: function getInt32(byteOffset /* , littleEndian */) { + return unpackI32(get(this, 4, byteOffset, arguments[1])); + }, + getUint32: function getUint32(byteOffset /* , littleEndian */) { + return unpackI32(get(this, 4, byteOffset, arguments[1])) >>> 0; + }, + getFloat32: function getFloat32(byteOffset /* , littleEndian */) { + return unpackIEEE754(get(this, 4, byteOffset, arguments[1]), 23, 4); + }, + getFloat64: function getFloat64(byteOffset /* , littleEndian */) { + return unpackIEEE754(get(this, 8, byteOffset, arguments[1]), 52, 8); + }, + setInt8: function setInt8(byteOffset, value) { + set(this, 1, byteOffset, packI8, value); + }, + setUint8: function setUint8(byteOffset, value) { + set(this, 1, byteOffset, packI8, value); + }, + setInt16: function setInt16(byteOffset, value /* , littleEndian */) { + set(this, 2, byteOffset, packI16, value, arguments[2]); + }, + setUint16: function setUint16(byteOffset, value /* , littleEndian */) { + set(this, 2, byteOffset, packI16, value, arguments[2]); + }, + setInt32: function setInt32(byteOffset, value /* , littleEndian */) { + set(this, 4, byteOffset, packI32, value, arguments[2]); + }, + setUint32: function setUint32(byteOffset, value /* , littleEndian */) { + set(this, 4, byteOffset, packI32, value, arguments[2]); + }, + setFloat32: function setFloat32(byteOffset, value /* , littleEndian */) { + set(this, 4, byteOffset, packF32, value, arguments[2]); + }, + setFloat64: function setFloat64(byteOffset, value /* , littleEndian */) { + set(this, 8, byteOffset, packF64, value, arguments[2]); + } + }); + } else { + if (!fails(function () { + $ArrayBuffer(1); + }) || !fails(function () { + new $ArrayBuffer(-1); // eslint-disable-line no-new + }) || fails(function () { + new $ArrayBuffer(); // eslint-disable-line no-new + new $ArrayBuffer(1.5); // eslint-disable-line no-new + new $ArrayBuffer(NaN); // eslint-disable-line no-new + return $ArrayBuffer.name != ARRAY_BUFFER; + })) { + $ArrayBuffer = function ArrayBuffer(length) { + anInstance(this, $ArrayBuffer); + return new BaseBuffer(toIndex(length)); + }; + var ArrayBufferProto = $ArrayBuffer[PROTOTYPE] = BaseBuffer[PROTOTYPE]; + for (var keys = gOPN(BaseBuffer), j = 0, key; keys.length > j;) { + if (!((key = keys[j++]) in $ArrayBuffer)) hide($ArrayBuffer, key, BaseBuffer[key]); + } + if (!LIBRARY) ArrayBufferProto.constructor = $ArrayBuffer; + } + // iOS Safari 7.x bug + var view = new $DataView(new $ArrayBuffer(2)); + var $setInt8 = $DataView[PROTOTYPE].setInt8; + view.setInt8(0, 2147483648); + view.setInt8(1, 2147483649); + if (view.getInt8(0) || !view.getInt8(1)) redefineAll($DataView[PROTOTYPE], { + setInt8: function setInt8(byteOffset, value) { + $setInt8.call(this, byteOffset, value << 24 >> 24); + }, + setUint8: function setUint8(byteOffset, value) { + $setInt8.call(this, byteOffset, value << 24 >> 24); + } + }, true); + } + setToStringTag($ArrayBuffer, ARRAY_BUFFER); + setToStringTag($DataView, DATA_VIEW); + hide($DataView[PROTOTYPE], $typed.VIEW, true); + exports[ARRAY_BUFFER] = $ArrayBuffer; + exports[DATA_VIEW] = $DataView; + + +/***/ }), +/* 227 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://tc39.github.io/ecma262/#sec-toindex + var toInteger = __webpack_require__(38); + var toLength = __webpack_require__(37); + module.exports = function (it) { + if (it === undefined) return 0; + var number = toInteger(it); + var length = toLength(number); + if (number !== length) throw RangeError('Wrong length!'); + return length; + }; + + +/***/ }), +/* 228 */ +/***/ (function(module, exports, __webpack_require__) { + + var $export = __webpack_require__(8); + $export($export.G + $export.W + $export.F * !__webpack_require__(225).ABV, { + DataView: __webpack_require__(226).DataView + }); + + +/***/ }), +/* 229 */ +/***/ (function(module, exports, __webpack_require__) { + + __webpack_require__(230)('Int8', 1, function (init) { + return function Int8Array(data, byteOffset, length) { + return init(this, data, byteOffset, length); + }; + }); + + +/***/ }), +/* 230 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + if (__webpack_require__(6)) { + var LIBRARY = __webpack_require__(24); + var global = __webpack_require__(4); + var fails = __webpack_require__(7); + var $export = __webpack_require__(8); + var $typed = __webpack_require__(225); + var $buffer = __webpack_require__(226); + var ctx = __webpack_require__(20); + var anInstance = __webpack_require__(206); + var propertyDesc = __webpack_require__(17); + var hide = __webpack_require__(10); + var redefineAll = __webpack_require__(215); + var toInteger = __webpack_require__(38); + var toLength = __webpack_require__(37); + var toIndex = __webpack_require__(227); + var toAbsoluteIndex = __webpack_require__(39); + var toPrimitive = __webpack_require__(16); + var has = __webpack_require__(5); + var classof = __webpack_require__(74); + var isObject = __webpack_require__(13); + var toObject = __webpack_require__(57); + var isArrayIter = __webpack_require__(163); + var create = __webpack_require__(45); + var getPrototypeOf = __webpack_require__(58); + var gOPN = __webpack_require__(49).f; + var getIterFn = __webpack_require__(165); + var uid = __webpack_require__(19); + var wks = __webpack_require__(26); + var createArrayMethod = __webpack_require__(173); + var createArrayIncludes = __webpack_require__(36); + var speciesConstructor = __webpack_require__(208); + var ArrayIterators = __webpack_require__(194); + var Iterators = __webpack_require__(129); + var $iterDetect = __webpack_require__(166); + var setSpecies = __webpack_require__(193); + var arrayFill = __webpack_require__(189); + var arrayCopyWithin = __webpack_require__(186); + var $DP = __webpack_require__(11); + var $GOPD = __webpack_require__(50); + var dP = $DP.f; + var gOPD = $GOPD.f; + var RangeError = global.RangeError; + var TypeError = global.TypeError; + var Uint8Array = global.Uint8Array; + var ARRAY_BUFFER = 'ArrayBuffer'; + var SHARED_BUFFER = 'Shared' + ARRAY_BUFFER; + var BYTES_PER_ELEMENT = 'BYTES_PER_ELEMENT'; + var PROTOTYPE = 'prototype'; + var ArrayProto = Array[PROTOTYPE]; + var $ArrayBuffer = $buffer.ArrayBuffer; + var $DataView = $buffer.DataView; + var arrayForEach = createArrayMethod(0); + var arrayFilter = createArrayMethod(2); + var arraySome = createArrayMethod(3); + var arrayEvery = createArrayMethod(4); + var arrayFind = createArrayMethod(5); + var arrayFindIndex = createArrayMethod(6); + var arrayIncludes = createArrayIncludes(true); + var arrayIndexOf = createArrayIncludes(false); + var arrayValues = ArrayIterators.values; + var arrayKeys = ArrayIterators.keys; + var arrayEntries = ArrayIterators.entries; + var arrayLastIndexOf = ArrayProto.lastIndexOf; + var arrayReduce = ArrayProto.reduce; + var arrayReduceRight = ArrayProto.reduceRight; + var arrayJoin = ArrayProto.join; + var arraySort = ArrayProto.sort; + var arraySlice = ArrayProto.slice; + var arrayToString = ArrayProto.toString; + var arrayToLocaleString = ArrayProto.toLocaleString; + var ITERATOR = wks('iterator'); + var TAG = wks('toStringTag'); + var TYPED_CONSTRUCTOR = uid('typed_constructor'); + var DEF_CONSTRUCTOR = uid('def_constructor'); + var ALL_CONSTRUCTORS = $typed.CONSTR; + var TYPED_ARRAY = $typed.TYPED; + var VIEW = $typed.VIEW; + var WRONG_LENGTH = 'Wrong length!'; + + var $map = createArrayMethod(1, function (O, length) { + return allocate(speciesConstructor(O, O[DEF_CONSTRUCTOR]), length); + }); + + var LITTLE_ENDIAN = fails(function () { + // eslint-disable-next-line no-undef + return new Uint8Array(new Uint16Array([1]).buffer)[0] === 1; + }); + + var FORCED_SET = !!Uint8Array && !!Uint8Array[PROTOTYPE].set && fails(function () { + new Uint8Array(1).set({}); + }); + + var toOffset = function (it, BYTES) { + var offset = toInteger(it); + if (offset < 0 || offset % BYTES) throw RangeError('Wrong offset!'); + return offset; + }; + + var validate = function (it) { + if (isObject(it) && TYPED_ARRAY in it) return it; + throw TypeError(it + ' is not a typed array!'); + }; + + var allocate = function (C, length) { + if (!(isObject(C) && TYPED_CONSTRUCTOR in C)) { + throw TypeError('It is not a typed array constructor!'); + } return new C(length); + }; + + var speciesFromList = function (O, list) { + return fromList(speciesConstructor(O, O[DEF_CONSTRUCTOR]), list); + }; + + var fromList = function (C, list) { + var index = 0; + var length = list.length; + var result = allocate(C, length); + while (length > index) result[index] = list[index++]; + return result; + }; + + var addGetter = function (it, key, internal) { + dP(it, key, { get: function () { return this._d[internal]; } }); + }; + + var $from = function from(source /* , mapfn, thisArg */) { + var O = toObject(source); + var aLen = arguments.length; + var mapfn = aLen > 1 ? arguments[1] : undefined; + var mapping = mapfn !== undefined; + var iterFn = getIterFn(O); + var i, length, values, result, step, iterator; + if (iterFn != undefined && !isArrayIter(iterFn)) { + for (iterator = iterFn.call(O), values = [], i = 0; !(step = iterator.next()).done; i++) { + values.push(step.value); + } O = values; + } + if (mapping && aLen > 2) mapfn = ctx(mapfn, arguments[2], 2); + for (i = 0, length = toLength(O.length), result = allocate(this, length); length > i; i++) { + result[i] = mapping ? mapfn(O[i], i) : O[i]; + } + return result; + }; + + var $of = function of(/* ...items */) { + var index = 0; + var length = arguments.length; + var result = allocate(this, length); + while (length > index) result[index] = arguments[index++]; + return result; + }; + + // iOS Safari 6.x fails here + var TO_LOCALE_BUG = !!Uint8Array && fails(function () { arrayToLocaleString.call(new Uint8Array(1)); }); + + var $toLocaleString = function toLocaleString() { + return arrayToLocaleString.apply(TO_LOCALE_BUG ? arraySlice.call(validate(this)) : validate(this), arguments); + }; + + var proto = { + copyWithin: function copyWithin(target, start /* , end */) { + return arrayCopyWithin.call(validate(this), target, start, arguments.length > 2 ? arguments[2] : undefined); + }, + every: function every(callbackfn /* , thisArg */) { + return arrayEvery(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined); + }, + fill: function fill(value /* , start, end */) { // eslint-disable-line no-unused-vars + return arrayFill.apply(validate(this), arguments); + }, + filter: function filter(callbackfn /* , thisArg */) { + return speciesFromList(this, arrayFilter(validate(this), callbackfn, + arguments.length > 1 ? arguments[1] : undefined)); + }, + find: function find(predicate /* , thisArg */) { + return arrayFind(validate(this), predicate, arguments.length > 1 ? arguments[1] : undefined); + }, + findIndex: function findIndex(predicate /* , thisArg */) { + return arrayFindIndex(validate(this), predicate, arguments.length > 1 ? arguments[1] : undefined); + }, + forEach: function forEach(callbackfn /* , thisArg */) { + arrayForEach(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined); + }, + indexOf: function indexOf(searchElement /* , fromIndex */) { + return arrayIndexOf(validate(this), searchElement, arguments.length > 1 ? arguments[1] : undefined); + }, + includes: function includes(searchElement /* , fromIndex */) { + return arrayIncludes(validate(this), searchElement, arguments.length > 1 ? arguments[1] : undefined); + }, + join: function join(separator) { // eslint-disable-line no-unused-vars + return arrayJoin.apply(validate(this), arguments); + }, + lastIndexOf: function lastIndexOf(searchElement /* , fromIndex */) { // eslint-disable-line no-unused-vars + return arrayLastIndexOf.apply(validate(this), arguments); + }, + map: function map(mapfn /* , thisArg */) { + return $map(validate(this), mapfn, arguments.length > 1 ? arguments[1] : undefined); + }, + reduce: function reduce(callbackfn /* , initialValue */) { // eslint-disable-line no-unused-vars + return arrayReduce.apply(validate(this), arguments); + }, + reduceRight: function reduceRight(callbackfn /* , initialValue */) { // eslint-disable-line no-unused-vars + return arrayReduceRight.apply(validate(this), arguments); + }, + reverse: function reverse() { + var that = this; + var length = validate(that).length; + var middle = Math.floor(length / 2); + var index = 0; + var value; + while (index < middle) { + value = that[index]; + that[index++] = that[--length]; + that[length] = value; + } return that; + }, + some: function some(callbackfn /* , thisArg */) { + return arraySome(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined); + }, + sort: function sort(comparefn) { + return arraySort.call(validate(this), comparefn); + }, + subarray: function subarray(begin, end) { + var O = validate(this); + var length = O.length; + var $begin = toAbsoluteIndex(begin, length); + return new (speciesConstructor(O, O[DEF_CONSTRUCTOR]))( + O.buffer, + O.byteOffset + $begin * O.BYTES_PER_ELEMENT, + toLength((end === undefined ? length : toAbsoluteIndex(end, length)) - $begin) + ); + } + }; + + var $slice = function slice(start, end) { + return speciesFromList(this, arraySlice.call(validate(this), start, end)); + }; + + var $set = function set(arrayLike /* , offset */) { + validate(this); + var offset = toOffset(arguments[1], 1); + var length = this.length; + var src = toObject(arrayLike); + var len = toLength(src.length); + var index = 0; + if (len + offset > length) throw RangeError(WRONG_LENGTH); + while (index < len) this[offset + index] = src[index++]; + }; + + var $iterators = { + entries: function entries() { + return arrayEntries.call(validate(this)); + }, + keys: function keys() { + return arrayKeys.call(validate(this)); + }, + values: function values() { + return arrayValues.call(validate(this)); + } + }; + + var isTAIndex = function (target, key) { + return isObject(target) + && target[TYPED_ARRAY] + && typeof key != 'symbol' + && key in target + && String(+key) == String(key); + }; + var $getDesc = function getOwnPropertyDescriptor(target, key) { + return isTAIndex(target, key = toPrimitive(key, true)) + ? propertyDesc(2, target[key]) + : gOPD(target, key); + }; + var $setDesc = function defineProperty(target, key, desc) { + if (isTAIndex(target, key = toPrimitive(key, true)) + && isObject(desc) + && has(desc, 'value') + && !has(desc, 'get') + && !has(desc, 'set') + // TODO: add validation descriptor w/o calling accessors + && !desc.configurable + && (!has(desc, 'writable') || desc.writable) + && (!has(desc, 'enumerable') || desc.enumerable) + ) { + target[key] = desc.value; + return target; + } return dP(target, key, desc); + }; + + if (!ALL_CONSTRUCTORS) { + $GOPD.f = $getDesc; + $DP.f = $setDesc; + } + + $export($export.S + $export.F * !ALL_CONSTRUCTORS, 'Object', { + getOwnPropertyDescriptor: $getDesc, + defineProperty: $setDesc + }); + + if (fails(function () { arrayToString.call({}); })) { + arrayToString = arrayToLocaleString = function toString() { + return arrayJoin.call(this); + }; + } + + var $TypedArrayPrototype$ = redefineAll({}, proto); + redefineAll($TypedArrayPrototype$, $iterators); + hide($TypedArrayPrototype$, ITERATOR, $iterators.values); + redefineAll($TypedArrayPrototype$, { + slice: $slice, + set: $set, + constructor: function () { /* noop */ }, + toString: arrayToString, + toLocaleString: $toLocaleString + }); + addGetter($TypedArrayPrototype$, 'buffer', 'b'); + addGetter($TypedArrayPrototype$, 'byteOffset', 'o'); + addGetter($TypedArrayPrototype$, 'byteLength', 'l'); + addGetter($TypedArrayPrototype$, 'length', 'e'); + dP($TypedArrayPrototype$, TAG, { + get: function () { return this[TYPED_ARRAY]; } + }); + + // eslint-disable-next-line max-statements + module.exports = function (KEY, BYTES, wrapper, CLAMPED) { + CLAMPED = !!CLAMPED; + var NAME = KEY + (CLAMPED ? 'Clamped' : '') + 'Array'; + var GETTER = 'get' + KEY; + var SETTER = 'set' + KEY; + var TypedArray = global[NAME]; + var Base = TypedArray || {}; + var TAC = TypedArray && getPrototypeOf(TypedArray); + var FORCED = !TypedArray || !$typed.ABV; + var O = {}; + var TypedArrayPrototype = TypedArray && TypedArray[PROTOTYPE]; + var getter = function (that, index) { + var data = that._d; + return data.v[GETTER](index * BYTES + data.o, LITTLE_ENDIAN); + }; + var setter = function (that, index, value) { + var data = that._d; + if (CLAMPED) value = (value = Math.round(value)) < 0 ? 0 : value > 0xff ? 0xff : value & 0xff; + data.v[SETTER](index * BYTES + data.o, value, LITTLE_ENDIAN); + }; + var addElement = function (that, index) { + dP(that, index, { + get: function () { + return getter(this, index); + }, + set: function (value) { + return setter(this, index, value); + }, + enumerable: true + }); + }; + if (FORCED) { + TypedArray = wrapper(function (that, data, $offset, $length) { + anInstance(that, TypedArray, NAME, '_d'); + var index = 0; + var offset = 0; + var buffer, byteLength, length, klass; + if (!isObject(data)) { + length = toIndex(data); + byteLength = length * BYTES; + buffer = new $ArrayBuffer(byteLength); + } else if (data instanceof $ArrayBuffer || (klass = classof(data)) == ARRAY_BUFFER || klass == SHARED_BUFFER) { + buffer = data; + offset = toOffset($offset, BYTES); + var $len = data.byteLength; + if ($length === undefined) { + if ($len % BYTES) throw RangeError(WRONG_LENGTH); + byteLength = $len - offset; + if (byteLength < 0) throw RangeError(WRONG_LENGTH); + } else { + byteLength = toLength($length) * BYTES; + if (byteLength + offset > $len) throw RangeError(WRONG_LENGTH); + } + length = byteLength / BYTES; + } else if (TYPED_ARRAY in data) { + return fromList(TypedArray, data); + } else { + return $from.call(TypedArray, data); + } + hide(that, '_d', { + b: buffer, + o: offset, + l: byteLength, + e: length, + v: new $DataView(buffer) + }); + while (index < length) addElement(that, index++); + }); + TypedArrayPrototype = TypedArray[PROTOTYPE] = create($TypedArrayPrototype$); + hide(TypedArrayPrototype, 'constructor', TypedArray); + } else if (!fails(function () { + TypedArray(1); + }) || !fails(function () { + new TypedArray(-1); // eslint-disable-line no-new + }) || !$iterDetect(function (iter) { + new TypedArray(); // eslint-disable-line no-new + new TypedArray(null); // eslint-disable-line no-new + new TypedArray(1.5); // eslint-disable-line no-new + new TypedArray(iter); // eslint-disable-line no-new + }, true)) { + TypedArray = wrapper(function (that, data, $offset, $length) { + anInstance(that, TypedArray, NAME); + var klass; + // `ws` module bug, temporarily remove validation length for Uint8Array + // https://github.com/websockets/ws/pull/645 + if (!isObject(data)) return new Base(toIndex(data)); + if (data instanceof $ArrayBuffer || (klass = classof(data)) == ARRAY_BUFFER || klass == SHARED_BUFFER) { + return $length !== undefined + ? new Base(data, toOffset($offset, BYTES), $length) + : $offset !== undefined + ? new Base(data, toOffset($offset, BYTES)) + : new Base(data); + } + if (TYPED_ARRAY in data) return fromList(TypedArray, data); + return $from.call(TypedArray, data); + }); + arrayForEach(TAC !== Function.prototype ? gOPN(Base).concat(gOPN(TAC)) : gOPN(Base), function (key) { + if (!(key in TypedArray)) hide(TypedArray, key, Base[key]); + }); + TypedArray[PROTOTYPE] = TypedArrayPrototype; + if (!LIBRARY) TypedArrayPrototype.constructor = TypedArray; + } + var $nativeIterator = TypedArrayPrototype[ITERATOR]; + var CORRECT_ITER_NAME = !!$nativeIterator + && ($nativeIterator.name == 'values' || $nativeIterator.name == undefined); + var $iterator = $iterators.values; + hide(TypedArray, TYPED_CONSTRUCTOR, true); + hide(TypedArrayPrototype, TYPED_ARRAY, NAME); + hide(TypedArrayPrototype, VIEW, true); + hide(TypedArrayPrototype, DEF_CONSTRUCTOR, TypedArray); + + if (CLAMPED ? new TypedArray(1)[TAG] != NAME : !(TAG in TypedArrayPrototype)) { + dP(TypedArrayPrototype, TAG, { + get: function () { return NAME; } + }); + } + + O[NAME] = TypedArray; + + $export($export.G + $export.W + $export.F * (TypedArray != Base), O); + + $export($export.S, NAME, { + BYTES_PER_ELEMENT: BYTES + }); + + $export($export.S + $export.F * fails(function () { Base.of.call(TypedArray, 1); }), NAME, { + from: $from, + of: $of + }); + + if (!(BYTES_PER_ELEMENT in TypedArrayPrototype)) hide(TypedArrayPrototype, BYTES_PER_ELEMENT, BYTES); + + $export($export.P, NAME, proto); + + setSpecies(NAME); + + $export($export.P + $export.F * FORCED_SET, NAME, { set: $set }); + + $export($export.P + $export.F * !CORRECT_ITER_NAME, NAME, $iterators); + + if (!LIBRARY && TypedArrayPrototype.toString != arrayToString) TypedArrayPrototype.toString = arrayToString; + + $export($export.P + $export.F * fails(function () { + new TypedArray(1).slice(); + }), NAME, { slice: $slice }); + + $export($export.P + $export.F * (fails(function () { + return [1, 2].toLocaleString() != new TypedArray([1, 2]).toLocaleString(); + }) || !fails(function () { + TypedArrayPrototype.toLocaleString.call([1, 2]); + })), NAME, { toLocaleString: $toLocaleString }); + + Iterators[NAME] = CORRECT_ITER_NAME ? $nativeIterator : $iterator; + if (!LIBRARY && !CORRECT_ITER_NAME) hide(TypedArrayPrototype, ITERATOR, $iterator); + }; + } else module.exports = function () { /* empty */ }; + + +/***/ }), +/* 231 */ +/***/ (function(module, exports, __webpack_require__) { + + __webpack_require__(230)('Uint8', 1, function (init) { + return function Uint8Array(data, byteOffset, length) { + return init(this, data, byteOffset, length); + }; + }); + + +/***/ }), +/* 232 */ +/***/ (function(module, exports, __webpack_require__) { + + __webpack_require__(230)('Uint8', 1, function (init) { + return function Uint8ClampedArray(data, byteOffset, length) { + return init(this, data, byteOffset, length); + }; + }, true); + + +/***/ }), +/* 233 */ +/***/ (function(module, exports, __webpack_require__) { + + __webpack_require__(230)('Int16', 2, function (init) { + return function Int16Array(data, byteOffset, length) { + return init(this, data, byteOffset, length); + }; + }); + + +/***/ }), +/* 234 */ +/***/ (function(module, exports, __webpack_require__) { + + __webpack_require__(230)('Uint16', 2, function (init) { + return function Uint16Array(data, byteOffset, length) { + return init(this, data, byteOffset, length); + }; + }); + + +/***/ }), +/* 235 */ +/***/ (function(module, exports, __webpack_require__) { + + __webpack_require__(230)('Int32', 4, function (init) { + return function Int32Array(data, byteOffset, length) { + return init(this, data, byteOffset, length); + }; + }); + + +/***/ }), +/* 236 */ +/***/ (function(module, exports, __webpack_require__) { + + __webpack_require__(230)('Uint32', 4, function (init) { + return function Uint32Array(data, byteOffset, length) { + return init(this, data, byteOffset, length); + }; + }); + + +/***/ }), +/* 237 */ +/***/ (function(module, exports, __webpack_require__) { + + __webpack_require__(230)('Float32', 4, function (init) { + return function Float32Array(data, byteOffset, length) { + return init(this, data, byteOffset, length); + }; + }); + + +/***/ }), +/* 238 */ +/***/ (function(module, exports, __webpack_require__) { + + __webpack_require__(230)('Float64', 8, function (init) { + return function Float64Array(data, byteOffset, length) { + return init(this, data, byteOffset, length); + }; + }); + + +/***/ }), +/* 239 */ +/***/ (function(module, exports, __webpack_require__) { + + // 26.1.1 Reflect.apply(target, thisArgument, argumentsList) + var $export = __webpack_require__(8); + var aFunction = __webpack_require__(21); + var anObject = __webpack_require__(12); + var rApply = (__webpack_require__(4).Reflect || {}).apply; + var fApply = Function.apply; + // MS Edge argumentsList argument is optional + $export($export.S + $export.F * !__webpack_require__(7)(function () { + rApply(function () { /* empty */ }); + }), 'Reflect', { + apply: function apply(target, thisArgument, argumentsList) { + var T = aFunction(target); + var L = anObject(argumentsList); + return rApply ? rApply(T, thisArgument, L) : fApply.call(T, thisArgument, L); + } + }); + + +/***/ }), +/* 240 */ +/***/ (function(module, exports, __webpack_require__) { + + // 26.1.2 Reflect.construct(target, argumentsList [, newTarget]) + var $export = __webpack_require__(8); + var create = __webpack_require__(45); + var aFunction = __webpack_require__(21); + var anObject = __webpack_require__(12); + var isObject = __webpack_require__(13); + var fails = __webpack_require__(7); + var bind = __webpack_require__(76); + var rConstruct = (__webpack_require__(4).Reflect || {}).construct; + + // MS Edge supports only 2 arguments and argumentsList argument is optional + // FF Nightly sets third argument as `new.target`, but does not create `this` from it + var NEW_TARGET_BUG = fails(function () { + function F() { /* empty */ } + return !(rConstruct(function () { /* empty */ }, [], F) instanceof F); + }); + var ARGS_BUG = !fails(function () { + rConstruct(function () { /* empty */ }); + }); + + $export($export.S + $export.F * (NEW_TARGET_BUG || ARGS_BUG), 'Reflect', { + construct: function construct(Target, args /* , newTarget */) { + aFunction(Target); + anObject(args); + var newTarget = arguments.length < 3 ? Target : aFunction(arguments[2]); + if (ARGS_BUG && !NEW_TARGET_BUG) return rConstruct(Target, args, newTarget); + if (Target == newTarget) { + // w/o altered newTarget, optimization for 0-4 arguments + switch (args.length) { + case 0: return new Target(); + case 1: return new Target(args[0]); + case 2: return new Target(args[0], args[1]); + case 3: return new Target(args[0], args[1], args[2]); + case 4: return new Target(args[0], args[1], args[2], args[3]); + } + // w/o altered newTarget, lot of arguments case + var $args = [null]; + $args.push.apply($args, args); + return new (bind.apply(Target, $args))(); + } + // with altered newTarget, not support built-in constructors + var proto = newTarget.prototype; + var instance = create(isObject(proto) ? proto : Object.prototype); + var result = Function.apply.call(Target, instance, args); + return isObject(result) ? result : instance; + } + }); + + +/***/ }), +/* 241 */ +/***/ (function(module, exports, __webpack_require__) { + + // 26.1.3 Reflect.defineProperty(target, propertyKey, attributes) + var dP = __webpack_require__(11); + var $export = __webpack_require__(8); + var anObject = __webpack_require__(12); + var toPrimitive = __webpack_require__(16); + + // MS Edge has broken Reflect.defineProperty - throwing instead of returning false + $export($export.S + $export.F * __webpack_require__(7)(function () { + // eslint-disable-next-line no-undef + Reflect.defineProperty(dP.f({}, 1, { value: 1 }), 1, { value: 2 }); + }), 'Reflect', { + defineProperty: function defineProperty(target, propertyKey, attributes) { + anObject(target); + propertyKey = toPrimitive(propertyKey, true); + anObject(attributes); + try { + dP.f(target, propertyKey, attributes); + return true; + } catch (e) { + return false; + } + } + }); + + +/***/ }), +/* 242 */ +/***/ (function(module, exports, __webpack_require__) { + + // 26.1.4 Reflect.deleteProperty(target, propertyKey) + var $export = __webpack_require__(8); + var gOPD = __webpack_require__(50).f; + var anObject = __webpack_require__(12); + + $export($export.S, 'Reflect', { + deleteProperty: function deleteProperty(target, propertyKey) { + var desc = gOPD(anObject(target), propertyKey); + return desc && !desc.configurable ? false : delete target[propertyKey]; + } + }); + + +/***/ }), +/* 243 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // 26.1.5 Reflect.enumerate(target) + var $export = __webpack_require__(8); + var anObject = __webpack_require__(12); + var Enumerate = function (iterated) { + this._t = anObject(iterated); // target + this._i = 0; // next index + var keys = this._k = []; // keys + var key; + for (key in iterated) keys.push(key); + }; + __webpack_require__(130)(Enumerate, 'Object', function () { + var that = this; + var keys = that._k; + var key; + do { + if (that._i >= keys.length) return { value: undefined, done: true }; + } while (!((key = keys[that._i++]) in that._t)); + return { value: key, done: false }; + }); + + $export($export.S, 'Reflect', { + enumerate: function enumerate(target) { + return new Enumerate(target); + } + }); + + +/***/ }), +/* 244 */ +/***/ (function(module, exports, __webpack_require__) { + + // 26.1.6 Reflect.get(target, propertyKey [, receiver]) + var gOPD = __webpack_require__(50); + var getPrototypeOf = __webpack_require__(58); + var has = __webpack_require__(5); + var $export = __webpack_require__(8); + var isObject = __webpack_require__(13); + var anObject = __webpack_require__(12); + + function get(target, propertyKey /* , receiver */) { + var receiver = arguments.length < 3 ? target : arguments[2]; + var desc, proto; + if (anObject(target) === receiver) return target[propertyKey]; + if (desc = gOPD.f(target, propertyKey)) return has(desc, 'value') + ? desc.value + : desc.get !== undefined + ? desc.get.call(receiver) + : undefined; + if (isObject(proto = getPrototypeOf(target))) return get(proto, propertyKey, receiver); + } + + $export($export.S, 'Reflect', { get: get }); + + +/***/ }), +/* 245 */ +/***/ (function(module, exports, __webpack_require__) { + + // 26.1.7 Reflect.getOwnPropertyDescriptor(target, propertyKey) + var gOPD = __webpack_require__(50); + var $export = __webpack_require__(8); + var anObject = __webpack_require__(12); + + $export($export.S, 'Reflect', { + getOwnPropertyDescriptor: function getOwnPropertyDescriptor(target, propertyKey) { + return gOPD.f(anObject(target), propertyKey); + } + }); + + +/***/ }), +/* 246 */ +/***/ (function(module, exports, __webpack_require__) { + + // 26.1.8 Reflect.getPrototypeOf(target) + var $export = __webpack_require__(8); + var getProto = __webpack_require__(58); + var anObject = __webpack_require__(12); + + $export($export.S, 'Reflect', { + getPrototypeOf: function getPrototypeOf(target) { + return getProto(anObject(target)); + } + }); + + +/***/ }), +/* 247 */ +/***/ (function(module, exports, __webpack_require__) { + + // 26.1.9 Reflect.has(target, propertyKey) + var $export = __webpack_require__(8); + + $export($export.S, 'Reflect', { + has: function has(target, propertyKey) { + return propertyKey in target; + } + }); + + +/***/ }), +/* 248 */ +/***/ (function(module, exports, __webpack_require__) { + + // 26.1.10 Reflect.isExtensible(target) + var $export = __webpack_require__(8); + var anObject = __webpack_require__(12); + var $isExtensible = Object.isExtensible; + + $export($export.S, 'Reflect', { + isExtensible: function isExtensible(target) { + anObject(target); + return $isExtensible ? $isExtensible(target) : true; + } + }); + + +/***/ }), +/* 249 */ +/***/ (function(module, exports, __webpack_require__) { + + // 26.1.11 Reflect.ownKeys(target) + var $export = __webpack_require__(8); + + $export($export.S, 'Reflect', { ownKeys: __webpack_require__(250) }); + + +/***/ }), +/* 250 */ +/***/ (function(module, exports, __webpack_require__) { + + // all object keys, includes non-enumerable and symbols + var gOPN = __webpack_require__(49); + var gOPS = __webpack_require__(42); + var anObject = __webpack_require__(12); + var Reflect = __webpack_require__(4).Reflect; + module.exports = Reflect && Reflect.ownKeys || function ownKeys(it) { + var keys = gOPN.f(anObject(it)); + var getSymbols = gOPS.f; + return getSymbols ? keys.concat(getSymbols(it)) : keys; + }; + + +/***/ }), +/* 251 */ +/***/ (function(module, exports, __webpack_require__) { + + // 26.1.12 Reflect.preventExtensions(target) + var $export = __webpack_require__(8); + var anObject = __webpack_require__(12); + var $preventExtensions = Object.preventExtensions; + + $export($export.S, 'Reflect', { + preventExtensions: function preventExtensions(target) { + anObject(target); + try { + if ($preventExtensions) $preventExtensions(target); + return true; + } catch (e) { + return false; + } + } + }); + + +/***/ }), +/* 252 */ +/***/ (function(module, exports, __webpack_require__) { + + // 26.1.13 Reflect.set(target, propertyKey, V [, receiver]) + var dP = __webpack_require__(11); + var gOPD = __webpack_require__(50); + var getPrototypeOf = __webpack_require__(58); + var has = __webpack_require__(5); + var $export = __webpack_require__(8); + var createDesc = __webpack_require__(17); + var anObject = __webpack_require__(12); + var isObject = __webpack_require__(13); + + function set(target, propertyKey, V /* , receiver */) { + var receiver = arguments.length < 4 ? target : arguments[3]; + var ownDesc = gOPD.f(anObject(target), propertyKey); + var existingDescriptor, proto; + if (!ownDesc) { + if (isObject(proto = getPrototypeOf(target))) { + return set(proto, propertyKey, V, receiver); + } + ownDesc = createDesc(0); + } + if (has(ownDesc, 'value')) { + if (ownDesc.writable === false || !isObject(receiver)) return false; + if (existingDescriptor = gOPD.f(receiver, propertyKey)) { + if (existingDescriptor.get || existingDescriptor.set || existingDescriptor.writable === false) return false; + existingDescriptor.value = V; + dP.f(receiver, propertyKey, existingDescriptor); + } else dP.f(receiver, propertyKey, createDesc(0, V)); + return true; + } + return ownDesc.set === undefined ? false : (ownDesc.set.call(receiver, V), true); + } + + $export($export.S, 'Reflect', { set: set }); + + +/***/ }), +/* 253 */ +/***/ (function(module, exports, __webpack_require__) { + + // 26.1.14 Reflect.setPrototypeOf(target, proto) + var $export = __webpack_require__(8); + var setProto = __webpack_require__(72); + + if (setProto) $export($export.S, 'Reflect', { + setPrototypeOf: function setPrototypeOf(target, proto) { + setProto.check(target, proto); + try { + setProto.set(target, proto); + return true; + } catch (e) { + return false; + } + } + }); + + +/***/ }), +/* 254 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // https://github.com/tc39/Array.prototype.includes + var $export = __webpack_require__(8); + var $includes = __webpack_require__(36)(true); + + $export($export.P, 'Array', { + includes: function includes(el /* , fromIndex = 0 */) { + return $includes(this, el, arguments.length > 1 ? arguments[1] : undefined); + } + }); + + __webpack_require__(187)('includes'); + + +/***/ }), +/* 255 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // https://tc39.github.io/proposal-flatMap/#sec-Array.prototype.flatMap + var $export = __webpack_require__(8); + var flattenIntoArray = __webpack_require__(256); + var toObject = __webpack_require__(57); + var toLength = __webpack_require__(37); + var aFunction = __webpack_require__(21); + var arraySpeciesCreate = __webpack_require__(174); + + $export($export.P, 'Array', { + flatMap: function flatMap(callbackfn /* , thisArg */) { + var O = toObject(this); + var sourceLen, A; + aFunction(callbackfn); + sourceLen = toLength(O.length); + A = arraySpeciesCreate(O, 0); + flattenIntoArray(A, O, O, sourceLen, 0, 1, callbackfn, arguments[1]); + return A; + } + }); + + __webpack_require__(187)('flatMap'); + + +/***/ }), +/* 256 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // https://tc39.github.io/proposal-flatMap/#sec-FlattenIntoArray + var isArray = __webpack_require__(44); + var isObject = __webpack_require__(13); + var toLength = __webpack_require__(37); + var ctx = __webpack_require__(20); + var IS_CONCAT_SPREADABLE = __webpack_require__(26)('isConcatSpreadable'); + + function flattenIntoArray(target, original, source, sourceLen, start, depth, mapper, thisArg) { + var targetIndex = start; + var sourceIndex = 0; + var mapFn = mapper ? ctx(mapper, thisArg, 3) : false; + var element, spreadable; + + while (sourceIndex < sourceLen) { + if (sourceIndex in source) { + element = mapFn ? mapFn(source[sourceIndex], sourceIndex, original) : source[sourceIndex]; + + spreadable = false; + if (isObject(element)) { + spreadable = element[IS_CONCAT_SPREADABLE]; + spreadable = spreadable !== undefined ? !!spreadable : isArray(element); + } + + if (spreadable && depth > 0) { + targetIndex = flattenIntoArray(target, original, element, toLength(element.length), targetIndex, depth - 1) - 1; + } else { + if (targetIndex >= 0x1fffffffffffff) throw TypeError(); + target[targetIndex] = element; + } + + targetIndex++; + } + sourceIndex++; + } + return targetIndex; + } + + module.exports = flattenIntoArray; + + +/***/ }), +/* 257 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // https://tc39.github.io/proposal-flatMap/#sec-Array.prototype.flatten + var $export = __webpack_require__(8); + var flattenIntoArray = __webpack_require__(256); + var toObject = __webpack_require__(57); + var toLength = __webpack_require__(37); + var toInteger = __webpack_require__(38); + var arraySpeciesCreate = __webpack_require__(174); + + $export($export.P, 'Array', { + flatten: function flatten(/* depthArg = 1 */) { + var depthArg = arguments[0]; + var O = toObject(this); + var sourceLen = toLength(O.length); + var A = arraySpeciesCreate(O, 0); + flattenIntoArray(A, O, O, sourceLen, 0, depthArg === undefined ? 1 : toInteger(depthArg)); + return A; + } + }); + + __webpack_require__(187)('flatten'); + + +/***/ }), +/* 258 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // https://github.com/mathiasbynens/String.prototype.at + var $export = __webpack_require__(8); + var $at = __webpack_require__(127)(true); + + $export($export.P, 'String', { + at: function at(pos) { + return $at(this, pos); + } + }); + + +/***/ }), +/* 259 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // https://github.com/tc39/proposal-string-pad-start-end + var $export = __webpack_require__(8); + var $pad = __webpack_require__(260); + var userAgent = __webpack_require__(213); + + // https://github.com/zloirock/core-js/issues/280 + $export($export.P + $export.F * /Version\/10\.\d+(\.\d+)? Safari\//.test(userAgent), 'String', { + padStart: function padStart(maxLength /* , fillString = ' ' */) { + return $pad(this, maxLength, arguments.length > 1 ? arguments[1] : undefined, true); + } + }); + + +/***/ }), +/* 260 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://github.com/tc39/proposal-string-pad-start-end + var toLength = __webpack_require__(37); + var repeat = __webpack_require__(90); + var defined = __webpack_require__(35); + + module.exports = function (that, maxLength, fillString, left) { + var S = String(defined(that)); + var stringLength = S.length; + var fillStr = fillString === undefined ? ' ' : String(fillString); + var intMaxLength = toLength(maxLength); + if (intMaxLength <= stringLength || fillStr == '') return S; + var fillLen = intMaxLength - stringLength; + var stringFiller = repeat.call(fillStr, Math.ceil(fillLen / fillStr.length)); + if (stringFiller.length > fillLen) stringFiller = stringFiller.slice(0, fillLen); + return left ? stringFiller + S : S + stringFiller; + }; + + +/***/ }), +/* 261 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // https://github.com/tc39/proposal-string-pad-start-end + var $export = __webpack_require__(8); + var $pad = __webpack_require__(260); + var userAgent = __webpack_require__(213); + + // https://github.com/zloirock/core-js/issues/280 + $export($export.P + $export.F * /Version\/10\.\d+(\.\d+)? Safari\//.test(userAgent), 'String', { + padEnd: function padEnd(maxLength /* , fillString = ' ' */) { + return $pad(this, maxLength, arguments.length > 1 ? arguments[1] : undefined, false); + } + }); + + +/***/ }), +/* 262 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // https://github.com/sebmarkbage/ecmascript-string-left-right-trim + __webpack_require__(82)('trimLeft', function ($trim) { + return function trimLeft() { + return $trim(this, 1); + }; + }, 'trimStart'); + + +/***/ }), +/* 263 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // https://github.com/sebmarkbage/ecmascript-string-left-right-trim + __webpack_require__(82)('trimRight', function ($trim) { + return function trimRight() { + return $trim(this, 2); + }; + }, 'trimEnd'); + + +/***/ }), +/* 264 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // https://tc39.github.io/String.prototype.matchAll/ + var $export = __webpack_require__(8); + var defined = __webpack_require__(35); + var toLength = __webpack_require__(37); + var isRegExp = __webpack_require__(134); + var getFlags = __webpack_require__(197); + var RegExpProto = RegExp.prototype; + + var $RegExpStringIterator = function (regexp, string) { + this._r = regexp; + this._s = string; + }; + + __webpack_require__(130)($RegExpStringIterator, 'RegExp String', function next() { + var match = this._r.exec(this._s); + return { value: match, done: match === null }; + }); + + $export($export.P, 'String', { + matchAll: function matchAll(regexp) { + defined(this); + if (!isRegExp(regexp)) throw TypeError(regexp + ' is not a regexp!'); + var S = String(this); + var flags = 'flags' in RegExpProto ? String(regexp.flags) : getFlags.call(regexp); + var rx = new RegExp(regexp.source, ~flags.indexOf('g') ? flags : 'g' + flags); + rx.lastIndex = toLength(regexp.lastIndex); + return new $RegExpStringIterator(rx, S); + } + }); + + +/***/ }), +/* 265 */ +/***/ (function(module, exports, __webpack_require__) { + + __webpack_require__(28)('asyncIterator'); + + +/***/ }), +/* 266 */ +/***/ (function(module, exports, __webpack_require__) { + + __webpack_require__(28)('observable'); + + +/***/ }), +/* 267 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://github.com/tc39/proposal-object-getownpropertydescriptors + var $export = __webpack_require__(8); + var ownKeys = __webpack_require__(250); + var toIObject = __webpack_require__(32); + var gOPD = __webpack_require__(50); + var createProperty = __webpack_require__(164); + + $export($export.S, 'Object', { + getOwnPropertyDescriptors: function getOwnPropertyDescriptors(object) { + var O = toIObject(object); + var getDesc = gOPD.f; + var keys = ownKeys(O); + var result = {}; + var i = 0; + var key, desc; + while (keys.length > i) { + desc = getDesc(O, key = keys[i++]); + if (desc !== undefined) createProperty(result, key, desc); + } + return result; + } + }); + + +/***/ }), +/* 268 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://github.com/tc39/proposal-object-values-entries + var $export = __webpack_require__(8); + var $values = __webpack_require__(269)(false); + + $export($export.S, 'Object', { + values: function values(it) { + return $values(it); + } + }); + + +/***/ }), +/* 269 */ +/***/ (function(module, exports, __webpack_require__) { + + var getKeys = __webpack_require__(30); + var toIObject = __webpack_require__(32); + var isEnum = __webpack_require__(43).f; + module.exports = function (isEntries) { + return function (it) { + var O = toIObject(it); + var keys = getKeys(O); + var length = keys.length; + var i = 0; + var result = []; + var key; + while (length > i) if (isEnum.call(O, key = keys[i++])) { + result.push(isEntries ? [key, O[key]] : O[key]); + } return result; + }; + }; + + +/***/ }), +/* 270 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://github.com/tc39/proposal-object-values-entries + var $export = __webpack_require__(8); + var $entries = __webpack_require__(269)(true); + + $export($export.S, 'Object', { + entries: function entries(it) { + return $entries(it); + } + }); + + +/***/ }), +/* 271 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var toObject = __webpack_require__(57); + var aFunction = __webpack_require__(21); + var $defineProperty = __webpack_require__(11); + + // B.2.2.2 Object.prototype.__defineGetter__(P, getter) + __webpack_require__(6) && $export($export.P + __webpack_require__(272), 'Object', { + __defineGetter__: function __defineGetter__(P, getter) { + $defineProperty.f(toObject(this), P, { get: aFunction(getter), enumerable: true, configurable: true }); + } + }); + + +/***/ }), +/* 272 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // Forced replacement prototype accessors methods + module.exports = __webpack_require__(24) || !__webpack_require__(7)(function () { + var K = Math.random(); + // In FF throws only define methods + // eslint-disable-next-line no-undef, no-useless-call + __defineSetter__.call(null, K, function () { /* empty */ }); + delete __webpack_require__(4)[K]; + }); + + +/***/ }), +/* 273 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var toObject = __webpack_require__(57); + var aFunction = __webpack_require__(21); + var $defineProperty = __webpack_require__(11); + + // B.2.2.3 Object.prototype.__defineSetter__(P, setter) + __webpack_require__(6) && $export($export.P + __webpack_require__(272), 'Object', { + __defineSetter__: function __defineSetter__(P, setter) { + $defineProperty.f(toObject(this), P, { set: aFunction(setter), enumerable: true, configurable: true }); + } + }); + + +/***/ }), +/* 274 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var toObject = __webpack_require__(57); + var toPrimitive = __webpack_require__(16); + var getPrototypeOf = __webpack_require__(58); + var getOwnPropertyDescriptor = __webpack_require__(50).f; + + // B.2.2.4 Object.prototype.__lookupGetter__(P) + __webpack_require__(6) && $export($export.P + __webpack_require__(272), 'Object', { + __lookupGetter__: function __lookupGetter__(P) { + var O = toObject(this); + var K = toPrimitive(P, true); + var D; + do { + if (D = getOwnPropertyDescriptor(O, K)) return D.get; + } while (O = getPrototypeOf(O)); + } + }); + + +/***/ }), +/* 275 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var toObject = __webpack_require__(57); + var toPrimitive = __webpack_require__(16); + var getPrototypeOf = __webpack_require__(58); + var getOwnPropertyDescriptor = __webpack_require__(50).f; + + // B.2.2.5 Object.prototype.__lookupSetter__(P) + __webpack_require__(6) && $export($export.P + __webpack_require__(272), 'Object', { + __lookupSetter__: function __lookupSetter__(P) { + var O = toObject(this); + var K = toPrimitive(P, true); + var D; + do { + if (D = getOwnPropertyDescriptor(O, K)) return D.set; + } while (O = getPrototypeOf(O)); + } + }); + + +/***/ }), +/* 276 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://github.com/DavidBruant/Map-Set.prototype.toJSON + var $export = __webpack_require__(8); + + $export($export.P + $export.R, 'Map', { toJSON: __webpack_require__(277)('Map') }); + + +/***/ }), +/* 277 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://github.com/DavidBruant/Map-Set.prototype.toJSON + var classof = __webpack_require__(74); + var from = __webpack_require__(278); + module.exports = function (NAME) { + return function toJSON() { + if (classof(this) != NAME) throw TypeError(NAME + "#toJSON isn't generic"); + return from(this); + }; + }; + + +/***/ }), +/* 278 */ +/***/ (function(module, exports, __webpack_require__) { + + var forOf = __webpack_require__(207); + + module.exports = function (iter, ITERATOR) { + var result = []; + forOf(iter, false, result.push, result, ITERATOR); + return result; + }; + + +/***/ }), +/* 279 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://github.com/DavidBruant/Map-Set.prototype.toJSON + var $export = __webpack_require__(8); + + $export($export.P + $export.R, 'Set', { toJSON: __webpack_require__(277)('Set') }); + + +/***/ }), +/* 280 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://tc39.github.io/proposal-setmap-offrom/#sec-map.of + __webpack_require__(281)('Map'); + + +/***/ }), +/* 281 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // https://tc39.github.io/proposal-setmap-offrom/ + var $export = __webpack_require__(8); + + module.exports = function (COLLECTION) { + $export($export.S, COLLECTION, { of: function of() { + var length = arguments.length; + var A = new Array(length); + while (length--) A[length] = arguments[length]; + return new this(A); + } }); + }; + + +/***/ }), +/* 282 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://tc39.github.io/proposal-setmap-offrom/#sec-set.of + __webpack_require__(281)('Set'); + + +/***/ }), +/* 283 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://tc39.github.io/proposal-setmap-offrom/#sec-weakmap.of + __webpack_require__(281)('WeakMap'); + + +/***/ }), +/* 284 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://tc39.github.io/proposal-setmap-offrom/#sec-weakset.of + __webpack_require__(281)('WeakSet'); + + +/***/ }), +/* 285 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://tc39.github.io/proposal-setmap-offrom/#sec-map.from + __webpack_require__(286)('Map'); + + +/***/ }), +/* 286 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // https://tc39.github.io/proposal-setmap-offrom/ + var $export = __webpack_require__(8); + var aFunction = __webpack_require__(21); + var ctx = __webpack_require__(20); + var forOf = __webpack_require__(207); + + module.exports = function (COLLECTION) { + $export($export.S, COLLECTION, { from: function from(source /* , mapFn, thisArg */) { + var mapFn = arguments[1]; + var mapping, A, n, cb; + aFunction(this); + mapping = mapFn !== undefined; + if (mapping) aFunction(mapFn); + if (source == undefined) return new this(); + A = []; + if (mapping) { + n = 0; + cb = ctx(mapFn, arguments[2], 2); + forOf(source, false, function (nextItem) { + A.push(cb(nextItem, n++)); + }); + } else { + forOf(source, false, A.push, A); + } + return new this(A); + } }); + }; + + +/***/ }), +/* 287 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://tc39.github.io/proposal-setmap-offrom/#sec-set.from + __webpack_require__(286)('Set'); + + +/***/ }), +/* 288 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://tc39.github.io/proposal-setmap-offrom/#sec-weakmap.from + __webpack_require__(286)('WeakMap'); + + +/***/ }), +/* 289 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://tc39.github.io/proposal-setmap-offrom/#sec-weakset.from + __webpack_require__(286)('WeakSet'); + + +/***/ }), +/* 290 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://github.com/tc39/proposal-global + var $export = __webpack_require__(8); + + $export($export.G, { global: __webpack_require__(4) }); + + +/***/ }), +/* 291 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://github.com/tc39/proposal-global + var $export = __webpack_require__(8); + + $export($export.S, 'System', { global: __webpack_require__(4) }); + + +/***/ }), +/* 292 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://github.com/ljharb/proposal-is-error + var $export = __webpack_require__(8); + var cof = __webpack_require__(34); + + $export($export.S, 'Error', { + isError: function isError(it) { + return cof(it) === 'Error'; + } + }); + + +/***/ }), +/* 293 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://rwaldron.github.io/proposal-math-extensions/ + var $export = __webpack_require__(8); + + $export($export.S, 'Math', { + clamp: function clamp(x, lower, upper) { + return Math.min(upper, Math.max(lower, x)); + } + }); + + +/***/ }), +/* 294 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://rwaldron.github.io/proposal-math-extensions/ + var $export = __webpack_require__(8); + + $export($export.S, 'Math', { DEG_PER_RAD: Math.PI / 180 }); + + +/***/ }), +/* 295 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://rwaldron.github.io/proposal-math-extensions/ + var $export = __webpack_require__(8); + var RAD_PER_DEG = 180 / Math.PI; + + $export($export.S, 'Math', { + degrees: function degrees(radians) { + return radians * RAD_PER_DEG; + } + }); + + +/***/ }), +/* 296 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://rwaldron.github.io/proposal-math-extensions/ + var $export = __webpack_require__(8); + var scale = __webpack_require__(297); + var fround = __webpack_require__(113); + + $export($export.S, 'Math', { + fscale: function fscale(x, inLow, inHigh, outLow, outHigh) { + return fround(scale(x, inLow, inHigh, outLow, outHigh)); + } + }); + + +/***/ }), +/* 297 */ +/***/ (function(module, exports) { + + // https://rwaldron.github.io/proposal-math-extensions/ + module.exports = Math.scale || function scale(x, inLow, inHigh, outLow, outHigh) { + if ( + arguments.length === 0 + // eslint-disable-next-line no-self-compare + || x != x + // eslint-disable-next-line no-self-compare + || inLow != inLow + // eslint-disable-next-line no-self-compare + || inHigh != inHigh + // eslint-disable-next-line no-self-compare + || outLow != outLow + // eslint-disable-next-line no-self-compare + || outHigh != outHigh + ) return NaN; + if (x === Infinity || x === -Infinity) return x; + return (x - inLow) * (outHigh - outLow) / (inHigh - inLow) + outLow; + }; + + +/***/ }), +/* 298 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://gist.github.com/BrendanEich/4294d5c212a6d2254703 + var $export = __webpack_require__(8); + + $export($export.S, 'Math', { + iaddh: function iaddh(x0, x1, y0, y1) { + var $x0 = x0 >>> 0; + var $x1 = x1 >>> 0; + var $y0 = y0 >>> 0; + return $x1 + (y1 >>> 0) + (($x0 & $y0 | ($x0 | $y0) & ~($x0 + $y0 >>> 0)) >>> 31) | 0; + } + }); + + +/***/ }), +/* 299 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://gist.github.com/BrendanEich/4294d5c212a6d2254703 + var $export = __webpack_require__(8); + + $export($export.S, 'Math', { + isubh: function isubh(x0, x1, y0, y1) { + var $x0 = x0 >>> 0; + var $x1 = x1 >>> 0; + var $y0 = y0 >>> 0; + return $x1 - (y1 >>> 0) - ((~$x0 & $y0 | ~($x0 ^ $y0) & $x0 - $y0 >>> 0) >>> 31) | 0; + } + }); + + +/***/ }), +/* 300 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://gist.github.com/BrendanEich/4294d5c212a6d2254703 + var $export = __webpack_require__(8); + + $export($export.S, 'Math', { + imulh: function imulh(u, v) { + var UINT16 = 0xffff; + var $u = +u; + var $v = +v; + var u0 = $u & UINT16; + var v0 = $v & UINT16; + var u1 = $u >> 16; + var v1 = $v >> 16; + var t = (u1 * v0 >>> 0) + (u0 * v0 >>> 16); + return u1 * v1 + (t >> 16) + ((u0 * v1 >>> 0) + (t & UINT16) >> 16); + } + }); + + +/***/ }), +/* 301 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://rwaldron.github.io/proposal-math-extensions/ + var $export = __webpack_require__(8); + + $export($export.S, 'Math', { RAD_PER_DEG: 180 / Math.PI }); + + +/***/ }), +/* 302 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://rwaldron.github.io/proposal-math-extensions/ + var $export = __webpack_require__(8); + var DEG_PER_RAD = Math.PI / 180; + + $export($export.S, 'Math', { + radians: function radians(degrees) { + return degrees * DEG_PER_RAD; + } + }); + + +/***/ }), +/* 303 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://rwaldron.github.io/proposal-math-extensions/ + var $export = __webpack_require__(8); + + $export($export.S, 'Math', { scale: __webpack_require__(297) }); + + +/***/ }), +/* 304 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://gist.github.com/BrendanEich/4294d5c212a6d2254703 + var $export = __webpack_require__(8); + + $export($export.S, 'Math', { + umulh: function umulh(u, v) { + var UINT16 = 0xffff; + var $u = +u; + var $v = +v; + var u0 = $u & UINT16; + var v0 = $v & UINT16; + var u1 = $u >>> 16; + var v1 = $v >>> 16; + var t = (u1 * v0 >>> 0) + (u0 * v0 >>> 16); + return u1 * v1 + (t >>> 16) + ((u0 * v1 >>> 0) + (t & UINT16) >>> 16); + } + }); + + +/***/ }), +/* 305 */ +/***/ (function(module, exports, __webpack_require__) { + + // http://jfbastien.github.io/papers/Math.signbit.html + var $export = __webpack_require__(8); + + $export($export.S, 'Math', { signbit: function signbit(x) { + // eslint-disable-next-line no-self-compare + return (x = +x) != x ? x : x == 0 ? 1 / x == Infinity : x > 0; + } }); + + +/***/ }), +/* 306 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://github.com/tc39/proposal-promise-finally + 'use strict'; + var $export = __webpack_require__(8); + var core = __webpack_require__(9); + var global = __webpack_require__(4); + var speciesConstructor = __webpack_require__(208); + var promiseResolve = __webpack_require__(214); + + $export($export.P + $export.R, 'Promise', { 'finally': function (onFinally) { + var C = speciesConstructor(this, core.Promise || global.Promise); + var isFunction = typeof onFinally == 'function'; + return this.then( + isFunction ? function (x) { + return promiseResolve(C, onFinally()).then(function () { return x; }); + } : onFinally, + isFunction ? function (e) { + return promiseResolve(C, onFinally()).then(function () { throw e; }); + } : onFinally + ); + } }); + + +/***/ }), +/* 307 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // https://github.com/tc39/proposal-promise-try + var $export = __webpack_require__(8); + var newPromiseCapability = __webpack_require__(211); + var perform = __webpack_require__(212); + + $export($export.S, 'Promise', { 'try': function (callbackfn) { + var promiseCapability = newPromiseCapability.f(this); + var result = perform(callbackfn); + (result.e ? promiseCapability.reject : promiseCapability.resolve)(result.v); + return promiseCapability.promise; + } }); + + +/***/ }), +/* 308 */ +/***/ (function(module, exports, __webpack_require__) { + + var metadata = __webpack_require__(309); + var anObject = __webpack_require__(12); + var toMetaKey = metadata.key; + var ordinaryDefineOwnMetadata = metadata.set; + + metadata.exp({ defineMetadata: function defineMetadata(metadataKey, metadataValue, target, targetKey) { + ordinaryDefineOwnMetadata(metadataKey, metadataValue, anObject(target), toMetaKey(targetKey)); + } }); + + +/***/ }), +/* 309 */ +/***/ (function(module, exports, __webpack_require__) { + + var Map = __webpack_require__(216); + var $export = __webpack_require__(8); + var shared = __webpack_require__(23)('metadata'); + var store = shared.store || (shared.store = new (__webpack_require__(221))()); + + var getOrCreateMetadataMap = function (target, targetKey, create) { + var targetMetadata = store.get(target); + if (!targetMetadata) { + if (!create) return undefined; + store.set(target, targetMetadata = new Map()); + } + var keyMetadata = targetMetadata.get(targetKey); + if (!keyMetadata) { + if (!create) return undefined; + targetMetadata.set(targetKey, keyMetadata = new Map()); + } return keyMetadata; + }; + var ordinaryHasOwnMetadata = function (MetadataKey, O, P) { + var metadataMap = getOrCreateMetadataMap(O, P, false); + return metadataMap === undefined ? false : metadataMap.has(MetadataKey); + }; + var ordinaryGetOwnMetadata = function (MetadataKey, O, P) { + var metadataMap = getOrCreateMetadataMap(O, P, false); + return metadataMap === undefined ? undefined : metadataMap.get(MetadataKey); + }; + var ordinaryDefineOwnMetadata = function (MetadataKey, MetadataValue, O, P) { + getOrCreateMetadataMap(O, P, true).set(MetadataKey, MetadataValue); + }; + var ordinaryOwnMetadataKeys = function (target, targetKey) { + var metadataMap = getOrCreateMetadataMap(target, targetKey, false); + var keys = []; + if (metadataMap) metadataMap.forEach(function (_, key) { keys.push(key); }); + return keys; + }; + var toMetaKey = function (it) { + return it === undefined || typeof it == 'symbol' ? it : String(it); + }; + var exp = function (O) { + $export($export.S, 'Reflect', O); + }; + + module.exports = { + store: store, + map: getOrCreateMetadataMap, + has: ordinaryHasOwnMetadata, + get: ordinaryGetOwnMetadata, + set: ordinaryDefineOwnMetadata, + keys: ordinaryOwnMetadataKeys, + key: toMetaKey, + exp: exp + }; + + +/***/ }), +/* 310 */ +/***/ (function(module, exports, __webpack_require__) { + + var metadata = __webpack_require__(309); + var anObject = __webpack_require__(12); + var toMetaKey = metadata.key; + var getOrCreateMetadataMap = metadata.map; + var store = metadata.store; + + metadata.exp({ deleteMetadata: function deleteMetadata(metadataKey, target /* , targetKey */) { + var targetKey = arguments.length < 3 ? undefined : toMetaKey(arguments[2]); + var metadataMap = getOrCreateMetadataMap(anObject(target), targetKey, false); + if (metadataMap === undefined || !metadataMap['delete'](metadataKey)) return false; + if (metadataMap.size) return true; + var targetMetadata = store.get(target); + targetMetadata['delete'](targetKey); + return !!targetMetadata.size || store['delete'](target); + } }); + + +/***/ }), +/* 311 */ +/***/ (function(module, exports, __webpack_require__) { + + var metadata = __webpack_require__(309); + var anObject = __webpack_require__(12); + var getPrototypeOf = __webpack_require__(58); + var ordinaryHasOwnMetadata = metadata.has; + var ordinaryGetOwnMetadata = metadata.get; + var toMetaKey = metadata.key; + + var ordinaryGetMetadata = function (MetadataKey, O, P) { + var hasOwn = ordinaryHasOwnMetadata(MetadataKey, O, P); + if (hasOwn) return ordinaryGetOwnMetadata(MetadataKey, O, P); + var parent = getPrototypeOf(O); + return parent !== null ? ordinaryGetMetadata(MetadataKey, parent, P) : undefined; + }; + + metadata.exp({ getMetadata: function getMetadata(metadataKey, target /* , targetKey */) { + return ordinaryGetMetadata(metadataKey, anObject(target), arguments.length < 3 ? undefined : toMetaKey(arguments[2])); + } }); + + +/***/ }), +/* 312 */ +/***/ (function(module, exports, __webpack_require__) { + + var Set = __webpack_require__(220); + var from = __webpack_require__(278); + var metadata = __webpack_require__(309); + var anObject = __webpack_require__(12); + var getPrototypeOf = __webpack_require__(58); + var ordinaryOwnMetadataKeys = metadata.keys; + var toMetaKey = metadata.key; + + var ordinaryMetadataKeys = function (O, P) { + var oKeys = ordinaryOwnMetadataKeys(O, P); + var parent = getPrototypeOf(O); + if (parent === null) return oKeys; + var pKeys = ordinaryMetadataKeys(parent, P); + return pKeys.length ? oKeys.length ? from(new Set(oKeys.concat(pKeys))) : pKeys : oKeys; + }; + + metadata.exp({ getMetadataKeys: function getMetadataKeys(target /* , targetKey */) { + return ordinaryMetadataKeys(anObject(target), arguments.length < 2 ? undefined : toMetaKey(arguments[1])); + } }); + + +/***/ }), +/* 313 */ +/***/ (function(module, exports, __webpack_require__) { + + var metadata = __webpack_require__(309); + var anObject = __webpack_require__(12); + var ordinaryGetOwnMetadata = metadata.get; + var toMetaKey = metadata.key; + + metadata.exp({ getOwnMetadata: function getOwnMetadata(metadataKey, target /* , targetKey */) { + return ordinaryGetOwnMetadata(metadataKey, anObject(target) + , arguments.length < 3 ? undefined : toMetaKey(arguments[2])); + } }); + + +/***/ }), +/* 314 */ +/***/ (function(module, exports, __webpack_require__) { + + var metadata = __webpack_require__(309); + var anObject = __webpack_require__(12); + var ordinaryOwnMetadataKeys = metadata.keys; + var toMetaKey = metadata.key; + + metadata.exp({ getOwnMetadataKeys: function getOwnMetadataKeys(target /* , targetKey */) { + return ordinaryOwnMetadataKeys(anObject(target), arguments.length < 2 ? undefined : toMetaKey(arguments[1])); + } }); + + +/***/ }), +/* 315 */ +/***/ (function(module, exports, __webpack_require__) { + + var metadata = __webpack_require__(309); + var anObject = __webpack_require__(12); + var getPrototypeOf = __webpack_require__(58); + var ordinaryHasOwnMetadata = metadata.has; + var toMetaKey = metadata.key; + + var ordinaryHasMetadata = function (MetadataKey, O, P) { + var hasOwn = ordinaryHasOwnMetadata(MetadataKey, O, P); + if (hasOwn) return true; + var parent = getPrototypeOf(O); + return parent !== null ? ordinaryHasMetadata(MetadataKey, parent, P) : false; + }; + + metadata.exp({ hasMetadata: function hasMetadata(metadataKey, target /* , targetKey */) { + return ordinaryHasMetadata(metadataKey, anObject(target), arguments.length < 3 ? undefined : toMetaKey(arguments[2])); + } }); + + +/***/ }), +/* 316 */ +/***/ (function(module, exports, __webpack_require__) { + + var metadata = __webpack_require__(309); + var anObject = __webpack_require__(12); + var ordinaryHasOwnMetadata = metadata.has; + var toMetaKey = metadata.key; + + metadata.exp({ hasOwnMetadata: function hasOwnMetadata(metadataKey, target /* , targetKey */) { + return ordinaryHasOwnMetadata(metadataKey, anObject(target) + , arguments.length < 3 ? undefined : toMetaKey(arguments[2])); + } }); + + +/***/ }), +/* 317 */ +/***/ (function(module, exports, __webpack_require__) { + + var $metadata = __webpack_require__(309); + var anObject = __webpack_require__(12); + var aFunction = __webpack_require__(21); + var toMetaKey = $metadata.key; + var ordinaryDefineOwnMetadata = $metadata.set; + + $metadata.exp({ metadata: function metadata(metadataKey, metadataValue) { + return function decorator(target, targetKey) { + ordinaryDefineOwnMetadata( + metadataKey, metadataValue, + (targetKey !== undefined ? anObject : aFunction)(target), + toMetaKey(targetKey) + ); + }; + } }); + + +/***/ }), +/* 318 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://github.com/rwaldron/tc39-notes/blob/master/es6/2014-09/sept-25.md#510-globalasap-for-enqueuing-a-microtask + var $export = __webpack_require__(8); + var microtask = __webpack_require__(210)(); + var process = __webpack_require__(4).process; + var isNode = __webpack_require__(34)(process) == 'process'; + + $export($export.G, { + asap: function asap(fn) { + var domain = isNode && process.domain; + microtask(domain ? domain.bind(fn) : fn); + } + }); + + +/***/ }), +/* 319 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // https://github.com/zenparsing/es-observable + var $export = __webpack_require__(8); + var global = __webpack_require__(4); + var core = __webpack_require__(9); + var microtask = __webpack_require__(210)(); + var OBSERVABLE = __webpack_require__(26)('observable'); + var aFunction = __webpack_require__(21); + var anObject = __webpack_require__(12); + var anInstance = __webpack_require__(206); + var redefineAll = __webpack_require__(215); + var hide = __webpack_require__(10); + var forOf = __webpack_require__(207); + var RETURN = forOf.RETURN; + + var getMethod = function (fn) { + return fn == null ? undefined : aFunction(fn); + }; + + var cleanupSubscription = function (subscription) { + var cleanup = subscription._c; + if (cleanup) { + subscription._c = undefined; + cleanup(); + } + }; + + var subscriptionClosed = function (subscription) { + return subscription._o === undefined; + }; + + var closeSubscription = function (subscription) { + if (!subscriptionClosed(subscription)) { + subscription._o = undefined; + cleanupSubscription(subscription); + } + }; + + var Subscription = function (observer, subscriber) { + anObject(observer); + this._c = undefined; + this._o = observer; + observer = new SubscriptionObserver(this); + try { + var cleanup = subscriber(observer); + var subscription = cleanup; + if (cleanup != null) { + if (typeof cleanup.unsubscribe === 'function') cleanup = function () { subscription.unsubscribe(); }; + else aFunction(cleanup); + this._c = cleanup; + } + } catch (e) { + observer.error(e); + return; + } if (subscriptionClosed(this)) cleanupSubscription(this); + }; + + Subscription.prototype = redefineAll({}, { + unsubscribe: function unsubscribe() { closeSubscription(this); } + }); + + var SubscriptionObserver = function (subscription) { + this._s = subscription; + }; + + SubscriptionObserver.prototype = redefineAll({}, { + next: function next(value) { + var subscription = this._s; + if (!subscriptionClosed(subscription)) { + var observer = subscription._o; + try { + var m = getMethod(observer.next); + if (m) return m.call(observer, value); + } catch (e) { + try { + closeSubscription(subscription); + } finally { + throw e; + } + } + } + }, + error: function error(value) { + var subscription = this._s; + if (subscriptionClosed(subscription)) throw value; + var observer = subscription._o; + subscription._o = undefined; + try { + var m = getMethod(observer.error); + if (!m) throw value; + value = m.call(observer, value); + } catch (e) { + try { + cleanupSubscription(subscription); + } finally { + throw e; + } + } cleanupSubscription(subscription); + return value; + }, + complete: function complete(value) { + var subscription = this._s; + if (!subscriptionClosed(subscription)) { + var observer = subscription._o; + subscription._o = undefined; + try { + var m = getMethod(observer.complete); + value = m ? m.call(observer, value) : undefined; + } catch (e) { + try { + cleanupSubscription(subscription); + } finally { + throw e; + } + } cleanupSubscription(subscription); + return value; + } + } + }); + + var $Observable = function Observable(subscriber) { + anInstance(this, $Observable, 'Observable', '_f')._f = aFunction(subscriber); + }; + + redefineAll($Observable.prototype, { + subscribe: function subscribe(observer) { + return new Subscription(observer, this._f); + }, + forEach: function forEach(fn) { + var that = this; + return new (core.Promise || global.Promise)(function (resolve, reject) { + aFunction(fn); + var subscription = that.subscribe({ + next: function (value) { + try { + return fn(value); + } catch (e) { + reject(e); + subscription.unsubscribe(); + } + }, + error: reject, + complete: resolve + }); + }); + } + }); + + redefineAll($Observable, { + from: function from(x) { + var C = typeof this === 'function' ? this : $Observable; + var method = getMethod(anObject(x)[OBSERVABLE]); + if (method) { + var observable = anObject(method.call(x)); + return observable.constructor === C ? observable : new C(function (observer) { + return observable.subscribe(observer); + }); + } + return new C(function (observer) { + var done = false; + microtask(function () { + if (!done) { + try { + if (forOf(x, false, function (it) { + observer.next(it); + if (done) return RETURN; + }) === RETURN) return; + } catch (e) { + if (done) throw e; + observer.error(e); + return; + } observer.complete(); + } + }); + return function () { done = true; }; + }); + }, + of: function of() { + for (var i = 0, l = arguments.length, items = new Array(l); i < l;) items[i] = arguments[i++]; + return new (typeof this === 'function' ? this : $Observable)(function (observer) { + var done = false; + microtask(function () { + if (!done) { + for (var j = 0; j < items.length; ++j) { + observer.next(items[j]); + if (done) return; + } observer.complete(); + } + }); + return function () { done = true; }; + }); + } + }); + + hide($Observable.prototype, OBSERVABLE, function () { return this; }); + + $export($export.G, { Observable: $Observable }); + + __webpack_require__(193)('Observable'); + + +/***/ }), +/* 320 */ +/***/ (function(module, exports, __webpack_require__) { + + // ie9- setTimeout & setInterval additional parameters fix + var global = __webpack_require__(4); + var $export = __webpack_require__(8); + var userAgent = __webpack_require__(213); + var slice = [].slice; + var MSIE = /MSIE .\./.test(userAgent); // <- dirty ie9- check + var wrap = function (set) { + return function (fn, time /* , ...args */) { + var boundArgs = arguments.length > 2; + var args = boundArgs ? slice.call(arguments, 2) : false; + return set(boundArgs ? function () { + // eslint-disable-next-line no-new-func + (typeof fn == 'function' ? fn : Function(fn)).apply(this, args); + } : fn, time); + }; + }; + $export($export.G + $export.B + $export.F * MSIE, { + setTimeout: wrap(global.setTimeout), + setInterval: wrap(global.setInterval) + }); + + +/***/ }), +/* 321 */ +/***/ (function(module, exports, __webpack_require__) { + + var $export = __webpack_require__(8); + var $task = __webpack_require__(209); + $export($export.G + $export.B, { + setImmediate: $task.set, + clearImmediate: $task.clear + }); + + +/***/ }), +/* 322 */ +/***/ (function(module, exports, __webpack_require__) { + + var $iterators = __webpack_require__(194); + var getKeys = __webpack_require__(30); + var redefine = __webpack_require__(18); + var global = __webpack_require__(4); + var hide = __webpack_require__(10); + var Iterators = __webpack_require__(129); + var wks = __webpack_require__(26); + var ITERATOR = wks('iterator'); + var TO_STRING_TAG = wks('toStringTag'); + var ArrayValues = Iterators.Array; + + var DOMIterables = { + CSSRuleList: true, // TODO: Not spec compliant, should be false. + CSSStyleDeclaration: false, + CSSValueList: false, + ClientRectList: false, + DOMRectList: false, + DOMStringList: false, + DOMTokenList: true, + DataTransferItemList: false, + FileList: false, + HTMLAllCollection: false, + HTMLCollection: false, + HTMLFormElement: false, + HTMLSelectElement: false, + MediaList: true, // TODO: Not spec compliant, should be false. + MimeTypeArray: false, + NamedNodeMap: false, + NodeList: true, + PaintRequestList: false, + Plugin: false, + PluginArray: false, + SVGLengthList: false, + SVGNumberList: false, + SVGPathSegList: false, + SVGPointList: false, + SVGStringList: false, + SVGTransformList: false, + SourceBufferList: false, + StyleSheetList: true, // TODO: Not spec compliant, should be false. + TextTrackCueList: false, + TextTrackList: false, + TouchList: false + }; + + for (var collections = getKeys(DOMIterables), i = 0; i < collections.length; i++) { + var NAME = collections[i]; + var explicit = DOMIterables[NAME]; + var Collection = global[NAME]; + var proto = Collection && Collection.prototype; + var key; + if (proto) { + if (!proto[ITERATOR]) hide(proto, ITERATOR, ArrayValues); + if (!proto[TO_STRING_TAG]) hide(proto, TO_STRING_TAG, NAME); + Iterators[NAME] = ArrayValues; + if (explicit) for (key in $iterators) if (!proto[key]) redefine(proto, key, $iterators[key], true); + } + } + + +/***/ }), +/* 323 */ +/***/ (function(module, exports) { + + /* WEBPACK VAR INJECTION */(function(global) {/** + * Copyright (c) 2014, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * https://raw.github.com/facebook/regenerator/master/LICENSE file. An + * additional grant of patent rights can be found in the PATENTS file in + * the same directory. + */ + + !(function(global) { + "use strict"; + + var Op = Object.prototype; + var hasOwn = Op.hasOwnProperty; + var undefined; // More compressible than void 0. + var $Symbol = typeof Symbol === "function" ? Symbol : {}; + var iteratorSymbol = $Symbol.iterator || "@@iterator"; + var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator"; + var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; + + var inModule = typeof module === "object"; + var runtime = global.regeneratorRuntime; + if (runtime) { + if (inModule) { + // If regeneratorRuntime is defined globally and we're in a module, + // make the exports object identical to regeneratorRuntime. + module.exports = runtime; + } + // Don't bother evaluating the rest of this file if the runtime was + // already defined globally. + return; + } + + // Define the runtime globally (as expected by generated code) as either + // module.exports (if we're in a module) or a new, empty object. + runtime = global.regeneratorRuntime = inModule ? module.exports : {}; + + function wrap(innerFn, outerFn, self, tryLocsList) { + // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator. + var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator; + var generator = Object.create(protoGenerator.prototype); + var context = new Context(tryLocsList || []); + + // The ._invoke method unifies the implementations of the .next, + // .throw, and .return methods. + generator._invoke = makeInvokeMethod(innerFn, self, context); + + return generator; + } + runtime.wrap = wrap; + + // Try/catch helper to minimize deoptimizations. Returns a completion + // record like context.tryEntries[i].completion. This interface could + // have been (and was previously) designed to take a closure to be + // invoked without arguments, but in all the cases we care about we + // already have an existing method we want to call, so there's no need + // to create a new function object. We can even get away with assuming + // the method takes exactly one argument, since that happens to be true + // in every case, so we don't have to touch the arguments object. The + // only additional allocation required is the completion record, which + // has a stable shape and so hopefully should be cheap to allocate. + function tryCatch(fn, obj, arg) { + try { + return { type: "normal", arg: fn.call(obj, arg) }; + } catch (err) { + return { type: "throw", arg: err }; + } + } + + var GenStateSuspendedStart = "suspendedStart"; + var GenStateSuspendedYield = "suspendedYield"; + var GenStateExecuting = "executing"; + var GenStateCompleted = "completed"; + + // Returning this object from the innerFn has the same effect as + // breaking out of the dispatch switch statement. + var ContinueSentinel = {}; + + // Dummy constructor functions that we use as the .constructor and + // .constructor.prototype properties for functions that return Generator + // objects. For full spec compliance, you may wish to configure your + // minifier not to mangle the names of these two functions. + function Generator() {} + function GeneratorFunction() {} + function GeneratorFunctionPrototype() {} + + // This is a polyfill for %IteratorPrototype% for environments that + // don't natively support it. + var IteratorPrototype = {}; + IteratorPrototype[iteratorSymbol] = function () { + return this; + }; + + var getProto = Object.getPrototypeOf; + var NativeIteratorPrototype = getProto && getProto(getProto(values([]))); + if (NativeIteratorPrototype && + NativeIteratorPrototype !== Op && + hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) { + // This environment has a native %IteratorPrototype%; use it instead + // of the polyfill. + IteratorPrototype = NativeIteratorPrototype; + } + + var Gp = GeneratorFunctionPrototype.prototype = + Generator.prototype = Object.create(IteratorPrototype); + GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype; + GeneratorFunctionPrototype.constructor = GeneratorFunction; + GeneratorFunctionPrototype[toStringTagSymbol] = + GeneratorFunction.displayName = "GeneratorFunction"; + + // Helper for defining the .next, .throw, and .return methods of the + // Iterator interface in terms of a single ._invoke method. + function defineIteratorMethods(prototype) { + ["next", "throw", "return"].forEach(function(method) { + prototype[method] = function(arg) { + return this._invoke(method, arg); + }; + }); + } + + runtime.isGeneratorFunction = function(genFun) { + var ctor = typeof genFun === "function" && genFun.constructor; + return ctor + ? ctor === GeneratorFunction || + // For the native GeneratorFunction constructor, the best we can + // do is to check its .name property. + (ctor.displayName || ctor.name) === "GeneratorFunction" + : false; + }; + + runtime.mark = function(genFun) { + if (Object.setPrototypeOf) { + Object.setPrototypeOf(genFun, GeneratorFunctionPrototype); + } else { + genFun.__proto__ = GeneratorFunctionPrototype; + if (!(toStringTagSymbol in genFun)) { + genFun[toStringTagSymbol] = "GeneratorFunction"; + } + } + genFun.prototype = Object.create(Gp); + return genFun; + }; + + // Within the body of any async function, `await x` is transformed to + // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test + // `hasOwn.call(value, "__await")` to determine if the yielded value is + // meant to be awaited. + runtime.awrap = function(arg) { + return { __await: arg }; + }; + + function AsyncIterator(generator) { + function invoke(method, arg, resolve, reject) { + var record = tryCatch(generator[method], generator, arg); + if (record.type === "throw") { + reject(record.arg); + } else { + var result = record.arg; + var value = result.value; + if (value && + typeof value === "object" && + hasOwn.call(value, "__await")) { + return Promise.resolve(value.__await).then(function(value) { + invoke("next", value, resolve, reject); + }, function(err) { + invoke("throw", err, resolve, reject); + }); + } + + return Promise.resolve(value).then(function(unwrapped) { + // When a yielded Promise is resolved, its final value becomes + // the .value of the Promise<{value,done}> result for the + // current iteration. If the Promise is rejected, however, the + // result for this iteration will be rejected with the same + // reason. Note that rejections of yielded Promises are not + // thrown back into the generator function, as is the case + // when an awaited Promise is rejected. This difference in + // behavior between yield and await is important, because it + // allows the consumer to decide what to do with the yielded + // rejection (swallow it and continue, manually .throw it back + // into the generator, abandon iteration, whatever). With + // await, by contrast, there is no opportunity to examine the + // rejection reason outside the generator function, so the + // only option is to throw it from the await expression, and + // let the generator function handle the exception. + result.value = unwrapped; + resolve(result); + }, reject); + } + } + + if (typeof global.process === "object" && global.process.domain) { + invoke = global.process.domain.bind(invoke); + } + + var previousPromise; + + function enqueue(method, arg) { + function callInvokeWithMethodAndArg() { + return new Promise(function(resolve, reject) { + invoke(method, arg, resolve, reject); + }); + } + + return previousPromise = + // If enqueue has been called before, then we want to wait until + // all previous Promises have been resolved before calling invoke, + // so that results are always delivered in the correct order. If + // enqueue has not been called before, then it is important to + // call invoke immediately, without waiting on a callback to fire, + // so that the async generator function has the opportunity to do + // any necessary setup in a predictable way. This predictability + // is why the Promise constructor synchronously invokes its + // executor callback, and why async functions synchronously + // execute code before the first await. Since we implement simple + // async functions in terms of async generators, it is especially + // important to get this right, even though it requires care. + previousPromise ? previousPromise.then( + callInvokeWithMethodAndArg, + // Avoid propagating failures to Promises returned by later + // invocations of the iterator. + callInvokeWithMethodAndArg + ) : callInvokeWithMethodAndArg(); + } + + // Define the unified helper method that is used to implement .next, + // .throw, and .return (see defineIteratorMethods). + this._invoke = enqueue; + } + + defineIteratorMethods(AsyncIterator.prototype); + AsyncIterator.prototype[asyncIteratorSymbol] = function () { + return this; + }; + runtime.AsyncIterator = AsyncIterator; + + // Note that simple async functions are implemented on top of + // AsyncIterator objects; they just return a Promise for the value of + // the final result produced by the iterator. + runtime.async = function(innerFn, outerFn, self, tryLocsList) { + var iter = new AsyncIterator( + wrap(innerFn, outerFn, self, tryLocsList) + ); + + return runtime.isGeneratorFunction(outerFn) + ? iter // If outerFn is a generator, return the full iterator. + : iter.next().then(function(result) { + return result.done ? result.value : iter.next(); + }); + }; + + function makeInvokeMethod(innerFn, self, context) { + var state = GenStateSuspendedStart; + + return function invoke(method, arg) { + if (state === GenStateExecuting) { + throw new Error("Generator is already running"); + } + + if (state === GenStateCompleted) { + if (method === "throw") { + throw arg; + } + + // Be forgiving, per 25.3.3.3.3 of the spec: + // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume + return doneResult(); + } + + context.method = method; + context.arg = arg; + + while (true) { + var delegate = context.delegate; + if (delegate) { + var delegateResult = maybeInvokeDelegate(delegate, context); + if (delegateResult) { + if (delegateResult === ContinueSentinel) continue; + return delegateResult; + } + } + + if (context.method === "next") { + // Setting context._sent for legacy support of Babel's + // function.sent implementation. + context.sent = context._sent = context.arg; + + } else if (context.method === "throw") { + if (state === GenStateSuspendedStart) { + state = GenStateCompleted; + throw context.arg; + } + + context.dispatchException(context.arg); + + } else if (context.method === "return") { + context.abrupt("return", context.arg); + } + + state = GenStateExecuting; + + var record = tryCatch(innerFn, self, context); + if (record.type === "normal") { + // If an exception is thrown from innerFn, we leave state === + // GenStateExecuting and loop back for another invocation. + state = context.done + ? GenStateCompleted + : GenStateSuspendedYield; + + if (record.arg === ContinueSentinel) { + continue; + } + + return { + value: record.arg, + done: context.done + }; + + } else if (record.type === "throw") { + state = GenStateCompleted; + // Dispatch the exception by looping back around to the + // context.dispatchException(context.arg) call above. + context.method = "throw"; + context.arg = record.arg; + } + } + }; + } + + // Call delegate.iterator[context.method](context.arg) and handle the + // result, either by returning a { value, done } result from the + // delegate iterator, or by modifying context.method and context.arg, + // setting context.delegate to null, and returning the ContinueSentinel. + function maybeInvokeDelegate(delegate, context) { + var method = delegate.iterator[context.method]; + if (method === undefined) { + // A .throw or .return when the delegate iterator has no .throw + // method always terminates the yield* loop. + context.delegate = null; + + if (context.method === "throw") { + if (delegate.iterator.return) { + // If the delegate iterator has a return method, give it a + // chance to clean up. + context.method = "return"; + context.arg = undefined; + maybeInvokeDelegate(delegate, context); + + if (context.method === "throw") { + // If maybeInvokeDelegate(context) changed context.method from + // "return" to "throw", let that override the TypeError below. + return ContinueSentinel; + } + } + + context.method = "throw"; + context.arg = new TypeError( + "The iterator does not provide a 'throw' method"); + } + + return ContinueSentinel; + } + + var record = tryCatch(method, delegate.iterator, context.arg); + + if (record.type === "throw") { + context.method = "throw"; + context.arg = record.arg; + context.delegate = null; + return ContinueSentinel; + } + + var info = record.arg; + + if (! info) { + context.method = "throw"; + context.arg = new TypeError("iterator result is not an object"); + context.delegate = null; + return ContinueSentinel; + } + + if (info.done) { + // Assign the result of the finished delegate to the temporary + // variable specified by delegate.resultName (see delegateYield). + context[delegate.resultName] = info.value; + + // Resume execution at the desired location (see delegateYield). + context.next = delegate.nextLoc; + + // If context.method was "throw" but the delegate handled the + // exception, let the outer generator proceed normally. If + // context.method was "next", forget context.arg since it has been + // "consumed" by the delegate iterator. If context.method was + // "return", allow the original .return call to continue in the + // outer generator. + if (context.method !== "return") { + context.method = "next"; + context.arg = undefined; + } + + } else { + // Re-yield the result returned by the delegate method. + return info; + } + + // The delegate iterator is finished, so forget it and continue with + // the outer generator. + context.delegate = null; + return ContinueSentinel; + } + + // Define Generator.prototype.{next,throw,return} in terms of the + // unified ._invoke helper method. + defineIteratorMethods(Gp); + + Gp[toStringTagSymbol] = "Generator"; + + // A Generator should always return itself as the iterator object when the + // @@iterator function is called on it. Some browsers' implementations of the + // iterator prototype chain incorrectly implement this, causing the Generator + // object to not be returned from this call. This ensures that doesn't happen. + // See https://github.com/facebook/regenerator/issues/274 for more details. + Gp[iteratorSymbol] = function() { + return this; + }; + + Gp.toString = function() { + return "[object Generator]"; + }; + + function pushTryEntry(locs) { + var entry = { tryLoc: locs[0] }; + + if (1 in locs) { + entry.catchLoc = locs[1]; + } + + if (2 in locs) { + entry.finallyLoc = locs[2]; + entry.afterLoc = locs[3]; + } + + this.tryEntries.push(entry); + } + + function resetTryEntry(entry) { + var record = entry.completion || {}; + record.type = "normal"; + delete record.arg; + entry.completion = record; + } + + function Context(tryLocsList) { + // The root entry object (effectively a try statement without a catch + // or a finally block) gives us a place to store values thrown from + // locations where there is no enclosing try statement. + this.tryEntries = [{ tryLoc: "root" }]; + tryLocsList.forEach(pushTryEntry, this); + this.reset(true); + } + + runtime.keys = function(object) { + var keys = []; + for (var key in object) { + keys.push(key); + } + keys.reverse(); + + // Rather than returning an object with a next method, we keep + // things simple and return the next function itself. + return function next() { + while (keys.length) { + var key = keys.pop(); + if (key in object) { + next.value = key; + next.done = false; + return next; + } + } + + // To avoid creating an additional object, we just hang the .value + // and .done properties off the next function object itself. This + // also ensures that the minifier will not anonymize the function. + next.done = true; + return next; + }; + }; + + function values(iterable) { + if (iterable) { + var iteratorMethod = iterable[iteratorSymbol]; + if (iteratorMethod) { + return iteratorMethod.call(iterable); + } + + if (typeof iterable.next === "function") { + return iterable; + } + + if (!isNaN(iterable.length)) { + var i = -1, next = function next() { + while (++i < iterable.length) { + if (hasOwn.call(iterable, i)) { + next.value = iterable[i]; + next.done = false; + return next; + } + } + + next.value = undefined; + next.done = true; + + return next; + }; + + return next.next = next; + } + } + + // Return an iterator with no values. + return { next: doneResult }; + } + runtime.values = values; + + function doneResult() { + return { value: undefined, done: true }; + } + + Context.prototype = { + constructor: Context, + + reset: function(skipTempReset) { + this.prev = 0; + this.next = 0; + // Resetting context._sent for legacy support of Babel's + // function.sent implementation. + this.sent = this._sent = undefined; + this.done = false; + this.delegate = null; + + this.method = "next"; + this.arg = undefined; + + this.tryEntries.forEach(resetTryEntry); + + if (!skipTempReset) { + for (var name in this) { + // Not sure about the optimal order of these conditions: + if (name.charAt(0) === "t" && + hasOwn.call(this, name) && + !isNaN(+name.slice(1))) { + this[name] = undefined; + } + } + } + }, + + stop: function() { + this.done = true; + + var rootEntry = this.tryEntries[0]; + var rootRecord = rootEntry.completion; + if (rootRecord.type === "throw") { + throw rootRecord.arg; + } + + return this.rval; + }, + + dispatchException: function(exception) { + if (this.done) { + throw exception; + } + + var context = this; + function handle(loc, caught) { + record.type = "throw"; + record.arg = exception; + context.next = loc; + + if (caught) { + // If the dispatched exception was caught by a catch block, + // then let that catch block handle the exception normally. + context.method = "next"; + context.arg = undefined; + } + + return !! caught; + } + + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + var record = entry.completion; + + if (entry.tryLoc === "root") { + // Exception thrown outside of any try block that could handle + // it, so set the completion value of the entire function to + // throw the exception. + return handle("end"); + } + + if (entry.tryLoc <= this.prev) { + var hasCatch = hasOwn.call(entry, "catchLoc"); + var hasFinally = hasOwn.call(entry, "finallyLoc"); + + if (hasCatch && hasFinally) { + if (this.prev < entry.catchLoc) { + return handle(entry.catchLoc, true); + } else if (this.prev < entry.finallyLoc) { + return handle(entry.finallyLoc); + } + + } else if (hasCatch) { + if (this.prev < entry.catchLoc) { + return handle(entry.catchLoc, true); + } + + } else if (hasFinally) { + if (this.prev < entry.finallyLoc) { + return handle(entry.finallyLoc); + } + + } else { + throw new Error("try statement without catch or finally"); + } + } + } + }, + + abrupt: function(type, arg) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + if (entry.tryLoc <= this.prev && + hasOwn.call(entry, "finallyLoc") && + this.prev < entry.finallyLoc) { + var finallyEntry = entry; + break; + } + } + + if (finallyEntry && + (type === "break" || + type === "continue") && + finallyEntry.tryLoc <= arg && + arg <= finallyEntry.finallyLoc) { + // Ignore the finally entry if control is not jumping to a + // location outside the try/catch block. + finallyEntry = null; + } + + var record = finallyEntry ? finallyEntry.completion : {}; + record.type = type; + record.arg = arg; + + if (finallyEntry) { + this.method = "next"; + this.next = finallyEntry.finallyLoc; + return ContinueSentinel; + } + + return this.complete(record); + }, + + complete: function(record, afterLoc) { + if (record.type === "throw") { + throw record.arg; + } + + if (record.type === "break" || + record.type === "continue") { + this.next = record.arg; + } else if (record.type === "return") { + this.rval = this.arg = record.arg; + this.method = "return"; + this.next = "end"; + } else if (record.type === "normal" && afterLoc) { + this.next = afterLoc; + } + + return ContinueSentinel; + }, + + finish: function(finallyLoc) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + if (entry.finallyLoc === finallyLoc) { + this.complete(entry.completion, entry.afterLoc); + resetTryEntry(entry); + return ContinueSentinel; + } + } + }, + + "catch": function(tryLoc) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + if (entry.tryLoc === tryLoc) { + var record = entry.completion; + if (record.type === "throw") { + var thrown = record.arg; + resetTryEntry(entry); + } + return thrown; + } + } + + // The context.catch method must only be called with a location + // argument that corresponds to a known catch block. + throw new Error("illegal catch attempt"); + }, + + delegateYield: function(iterable, resultName, nextLoc) { + this.delegate = { + iterator: values(iterable), + resultName: resultName, + nextLoc: nextLoc + }; + + if (this.method === "next") { + // Deliberately forget the last sent value so that we don't + // accidentally pass it on to the delegate. + this.arg = undefined; + } + + return ContinueSentinel; + } + }; + })( + // Among the various tricks for obtaining a reference to the global + // object, this seems to be the most reliable technique that does not + // use indirect eval (which violates Content Security Policy). + typeof global === "object" ? global : + typeof window === "object" ? window : + typeof self === "object" ? self : this + ); + + /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) + +/***/ }), +/* 324 */ +/***/ (function(module, exports, __webpack_require__) { + + __webpack_require__(325); + module.exports = __webpack_require__(9).RegExp.escape; + + +/***/ }), +/* 325 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://github.com/benjamingr/RexExp.escape + var $export = __webpack_require__(8); + var $re = __webpack_require__(326)(/[\\^$*+?.()|[\]{}]/g, '\\$&'); + + $export($export.S, 'RegExp', { escape: function escape(it) { return $re(it); } }); + + +/***/ }), +/* 326 */ +/***/ (function(module, exports) { + + module.exports = function (regExp, replace) { + var replacer = replace === Object(replace) ? function (part) { + return replace[part]; + } : replace; + return function (it) { + return String(it).replace(regExp, replacer); + }; + }; + + +/***/ }), +/* 327 */ +/***/ (function(module, exports, __webpack_require__) { + + var BSON = __webpack_require__(328), + Binary = __webpack_require__(351), + Code = __webpack_require__(346), + DBRef = __webpack_require__(350), + Decimal128 = __webpack_require__(347), + Double = __webpack_require__(331), + Int32 = __webpack_require__(345), + Long = __webpack_require__(330), + Map = __webpack_require__(329), + MaxKey = __webpack_require__(349), + MinKey = __webpack_require__(348), + ObjectId = __webpack_require__(333), + BSONRegExp = __webpack_require__(343), + Symbol = __webpack_require__(344), + Timestamp = __webpack_require__(332); + + // BSON MAX VALUES + BSON.BSON_INT32_MAX = 0x7fffffff; + BSON.BSON_INT32_MIN = -0x80000000; + + BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; + BSON.BSON_INT64_MIN = -Math.pow(2, 63); + + // JS MAX PRECISE VALUES + BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. + BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. + + // Add BSON types to function creation + BSON.Binary = Binary; + BSON.Code = Code; + BSON.DBRef = DBRef; + BSON.Decimal128 = Decimal128; + BSON.Double = Double; + BSON.Int32 = Int32; + BSON.Long = Long; + BSON.Map = Map; + BSON.MaxKey = MaxKey; + BSON.MinKey = MinKey; + BSON.ObjectId = ObjectId; + BSON.ObjectID = ObjectId; + BSON.BSONRegExp = BSONRegExp; + BSON.Symbol = Symbol; + BSON.Timestamp = Timestamp; + + // Return the BSON + module.exports = BSON; + +/***/ }), +/* 328 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + + var Map = __webpack_require__(329), + Long = __webpack_require__(330), + Double = __webpack_require__(331), + Timestamp = __webpack_require__(332), + ObjectID = __webpack_require__(333), + BSONRegExp = __webpack_require__(343), + Symbol = __webpack_require__(344), + Int32 = __webpack_require__(345), + Code = __webpack_require__(346), + Decimal128 = __webpack_require__(347), + MinKey = __webpack_require__(348), + MaxKey = __webpack_require__(349), + DBRef = __webpack_require__(350), + Binary = __webpack_require__(351); + + // Parts of the parser + var deserialize = __webpack_require__(352), + serializer = __webpack_require__(353), + calculateObjectSize = __webpack_require__(355), + utils = __webpack_require__(339); + + /** + * @ignore + * @api private + */ + // Default Max Size + var MAXSIZE = 1024 * 1024 * 17; + + // Current Internal Temporary Serialization Buffer + var buffer = utils.allocBuffer(MAXSIZE); + + var BSON = function () {}; + + /** + * Serialize a Javascript object. + * + * @param {Object} object the Javascript object to serialize. + * @param {Boolean} [options.checkKeys] the serializer will check if keys are valid. + * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. + * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. + * @param {Number} [options.minInternalBufferSize=1024*1024*17] minimum size of the internal temporary serialization buffer **(default:1024*1024*17)**. + * @return {Buffer} returns the Buffer object containing the serialized object. + * @api public + */ + BSON.prototype.serialize = function serialize(object, options) { + options = options || {}; + // Unpack the options + var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; + var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; + var minInternalBufferSize = typeof options.minInternalBufferSize === 'number' ? options.minInternalBufferSize : MAXSIZE; + + // Resize the internal serialization buffer if needed + if (buffer.length < minInternalBufferSize) { + buffer = utils.allocBuffer(minInternalBufferSize); + } + + // Attempt to serialize + var serializationIndex = serializer(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, []); + // Create the final buffer + var finishedBuffer = utils.allocBuffer(serializationIndex); + // Copy into the finished buffer + buffer.copy(finishedBuffer, 0, 0, finishedBuffer.length); + // Return the buffer + return finishedBuffer; + }; + + /** + * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. + * + * @param {Object} object the Javascript object to serialize. + * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. + * @param {Boolean} [options.checkKeys] the serializer will check if keys are valid. + * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. + * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. + * @param {Number} [options.index] the index in the buffer where we wish to start serializing into. + * @return {Number} returns the index pointing to the last written byte in the buffer. + * @api public + */ + BSON.prototype.serializeWithBufferAndIndex = function (object, finalBuffer, options) { + options = options || {}; + // Unpack the options + var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; + var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; + var startIndex = typeof options.index === 'number' ? options.index : 0; + + // Attempt to serialize + var serializationIndex = serializer(finalBuffer, object, checkKeys, startIndex || 0, 0, serializeFunctions, ignoreUndefined); + + // Return the index + return serializationIndex - 1; + }; + + /** + * Deserialize data as BSON. + * + * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. + * @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized. + * @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse. + * @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function. + * @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits + * @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a node.js Buffer instance. + * @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types. + * @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer. + * @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances. + * @return {Object} returns the deserialized Javascript Object. + * @api public + */ + BSON.prototype.deserialize = function (buffer, options) { + return deserialize(buffer, options); + }; + + /** + * Calculate the bson size for a passed in Javascript object. + * + * @param {Object} object the Javascript object to calculate the BSON byte size for. + * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. + * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. + * @return {Number} returns the number of bytes the BSON object will take up. + * @api public + */ + BSON.prototype.calculateObjectSize = function (object, options) { + options = options || {}; + + var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; + + return calculateObjectSize(object, serializeFunctions, ignoreUndefined); + }; + + /** + * Deserialize stream data as BSON documents. + * + * @param {Buffer} data the buffer containing the serialized set of BSON documents. + * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. + * @param {Number} numberOfDocuments number of documents to deserialize. + * @param {Array} documents an array where to store the deserialized documents. + * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. + * @param {Object} [options] additional options used for the deserialization. + * @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized. + * @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse. + * @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function. + * @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits + * @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a node.js Buffer instance. + * @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types. + * @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer. + * @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances. + * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. + * @api public + */ + BSON.prototype.deserializeStream = function (data, startIndex, numberOfDocuments, documents, docStartIndex, options) { + options = options != null ? options : {}; + var index = startIndex; + // Loop over all documents + for (var i = 0; i < numberOfDocuments; i++) { + // Find size of the document + var size = data[index] | data[index + 1] << 8 | data[index + 2] << 16 | data[index + 3] << 24; + // Update options with index + options['index'] = index; + // Parse the document at this point + documents[docStartIndex + i] = this.deserialize(data, options); + // Adjust index by the document size + index = index + size; + } + + // Return object containing end index of parsing and list of documents + return index; + }; + + /** + * @ignore + * @api private + */ + // BSON MAX VALUES + BSON.BSON_INT32_MAX = 0x7fffffff; + BSON.BSON_INT32_MIN = -0x80000000; + + BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; + BSON.BSON_INT64_MIN = -Math.pow(2, 63); + + // JS MAX PRECISE VALUES + BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. + BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. + + // Internal long versions + // var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. + // var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. + + /** + * Number BSON Type + * + * @classconstant BSON_DATA_NUMBER + **/ + BSON.BSON_DATA_NUMBER = 1; + /** + * String BSON Type + * + * @classconstant BSON_DATA_STRING + **/ + BSON.BSON_DATA_STRING = 2; + /** + * Object BSON Type + * + * @classconstant BSON_DATA_OBJECT + **/ + BSON.BSON_DATA_OBJECT = 3; + /** + * Array BSON Type + * + * @classconstant BSON_DATA_ARRAY + **/ + BSON.BSON_DATA_ARRAY = 4; + /** + * Binary BSON Type + * + * @classconstant BSON_DATA_BINARY + **/ + BSON.BSON_DATA_BINARY = 5; + /** + * ObjectID BSON Type + * + * @classconstant BSON_DATA_OID + **/ + BSON.BSON_DATA_OID = 7; + /** + * Boolean BSON Type + * + * @classconstant BSON_DATA_BOOLEAN + **/ + BSON.BSON_DATA_BOOLEAN = 8; + /** + * Date BSON Type + * + * @classconstant BSON_DATA_DATE + **/ + BSON.BSON_DATA_DATE = 9; + /** + * null BSON Type + * + * @classconstant BSON_DATA_NULL + **/ + BSON.BSON_DATA_NULL = 10; + /** + * RegExp BSON Type + * + * @classconstant BSON_DATA_REGEXP + **/ + BSON.BSON_DATA_REGEXP = 11; + /** + * Code BSON Type + * + * @classconstant BSON_DATA_CODE + **/ + BSON.BSON_DATA_CODE = 13; + /** + * Symbol BSON Type + * + * @classconstant BSON_DATA_SYMBOL + **/ + BSON.BSON_DATA_SYMBOL = 14; + /** + * Code with Scope BSON Type + * + * @classconstant BSON_DATA_CODE_W_SCOPE + **/ + BSON.BSON_DATA_CODE_W_SCOPE = 15; + /** + * 32 bit Integer BSON Type + * + * @classconstant BSON_DATA_INT + **/ + BSON.BSON_DATA_INT = 16; + /** + * Timestamp BSON Type + * + * @classconstant BSON_DATA_TIMESTAMP + **/ + BSON.BSON_DATA_TIMESTAMP = 17; + /** + * Long BSON Type + * + * @classconstant BSON_DATA_LONG + **/ + BSON.BSON_DATA_LONG = 18; + /** + * MinKey BSON Type + * + * @classconstant BSON_DATA_MIN_KEY + **/ + BSON.BSON_DATA_MIN_KEY = 0xff; + /** + * MaxKey BSON Type + * + * @classconstant BSON_DATA_MAX_KEY + **/ + BSON.BSON_DATA_MAX_KEY = 0x7f; + + /** + * Binary Default Type + * + * @classconstant BSON_BINARY_SUBTYPE_DEFAULT + **/ + BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; + /** + * Binary Function Type + * + * @classconstant BSON_BINARY_SUBTYPE_FUNCTION + **/ + BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; + /** + * Binary Byte Array Type + * + * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY + **/ + BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; + /** + * Binary UUID Type + * + * @classconstant BSON_BINARY_SUBTYPE_UUID + **/ + BSON.BSON_BINARY_SUBTYPE_UUID = 3; + /** + * Binary MD5 Type + * + * @classconstant BSON_BINARY_SUBTYPE_MD5 + **/ + BSON.BSON_BINARY_SUBTYPE_MD5 = 4; + /** + * Binary User Defined Type + * + * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED + **/ + BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; + + // Return BSON + module.exports = BSON; + module.exports.Code = Code; + module.exports.Map = Map; + module.exports.Symbol = Symbol; + module.exports.BSON = BSON; + module.exports.DBRef = DBRef; + module.exports.Binary = Binary; + module.exports.ObjectID = ObjectID; + module.exports.Long = Long; + module.exports.Timestamp = Timestamp; + module.exports.Double = Double; + module.exports.Int32 = Int32; + module.exports.MinKey = MinKey; + module.exports.MaxKey = MaxKey; + module.exports.BSONRegExp = BSONRegExp; + module.exports.Decimal128 = Decimal128; + +/***/ }), +/* 329 */ +/***/ (function(module, exports) { + + /* WEBPACK VAR INJECTION */(function(global) {'use strict'; + + // We have an ES6 Map available, return the native instance + + if (typeof global.Map !== 'undefined') { + module.exports = global.Map; + module.exports.Map = global.Map; + } else { + // We will return a polyfill + var Map = function (array) { + this._keys = []; + this._values = {}; + + for (var i = 0; i < array.length; i++) { + if (array[i] == null) continue; // skip null and undefined + var entry = array[i]; + var key = entry[0]; + var value = entry[1]; + // Add the key to the list of keys in order + this._keys.push(key); + // Add the key and value to the values dictionary with a point + // to the location in the ordered keys list + this._values[key] = { v: value, i: this._keys.length - 1 }; + } + }; + + Map.prototype.clear = function () { + this._keys = []; + this._values = {}; + }; + + Map.prototype.delete = function (key) { + var value = this._values[key]; + if (value == null) return false; + // Delete entry + delete this._values[key]; + // Remove the key from the ordered keys list + this._keys.splice(value.i, 1); + return true; + }; + + Map.prototype.entries = function () { + var self = this; + var index = 0; + + return { + next: function () { + var key = self._keys[index++]; + return { + value: key !== undefined ? [key, self._values[key].v] : undefined, + done: key !== undefined ? false : true + }; + } + }; + }; + + Map.prototype.forEach = function (callback, self) { + self = self || this; + + for (var i = 0; i < this._keys.length; i++) { + var key = this._keys[i]; + // Call the forEach callback + callback.call(self, this._values[key].v, key, self); + } + }; + + Map.prototype.get = function (key) { + return this._values[key] ? this._values[key].v : undefined; + }; + + Map.prototype.has = function (key) { + return this._values[key] != null; + }; + + Map.prototype.keys = function () { + var self = this; + var index = 0; + + return { + next: function () { + var key = self._keys[index++]; + return { + value: key !== undefined ? key : undefined, + done: key !== undefined ? false : true + }; + } + }; + }; + + Map.prototype.set = function (key, value) { + if (this._values[key]) { + this._values[key].v = value; + return this; + } + + // Add the key to the list of keys in order + this._keys.push(key); + // Add the key and value to the values dictionary with a point + // to the location in the ordered keys list + this._values[key] = { v: value, i: this._keys.length - 1 }; + return this; + }; + + Map.prototype.values = function () { + var self = this; + var index = 0; + + return { + next: function () { + var key = self._keys[index++]; + return { + value: key !== undefined ? self._values[key].v : undefined, + done: key !== undefined ? false : true + }; + } + }; + }; + + // Last ismaster + Object.defineProperty(Map.prototype, 'size', { + enumerable: true, + get: function () { + return this._keys.length; + } + }); + + module.exports = Map; + module.exports.Map = Map; + } + /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) + +/***/ }), +/* 330 */ +/***/ (function(module, exports) { + + // Licensed under the Apache License, Version 2.0 (the "License"); + // you may not use this file except in compliance with the License. + // You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + // Copyright 2009 Google Inc. All Rights Reserved + + /** + * Defines a Long class for representing a 64-bit two's-complement + * integer value, which faithfully simulates the behavior of a Java "Long". This + * implementation is derived from LongLib in GWT. + * + * Constructs a 64-bit two's-complement integer, given its low and high 32-bit + * values as *signed* integers. See the from* functions below for more + * convenient ways of constructing Longs. + * + * The internal representation of a Long is the two given signed, 32-bit values. + * We use 32-bit pieces because these are the size of integers on which + * Javascript performs bit-operations. For operations like addition and + * multiplication, we split each number into 16-bit pieces, which can easily be + * multiplied within Javascript's floating-point representation without overflow + * or change in sign. + * + * In the algorithms below, we frequently reduce the negative case to the + * positive case by negating the input(s) and then post-processing the result. + * Note that we must ALWAYS check specially whether those values are MIN_VALUE + * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as + * a positive number, it overflows back into a negative). Not handling this + * case would often result in infinite recursion. + * + * @class + * @param {number} low the low (signed) 32 bits of the Long. + * @param {number} high the high (signed) 32 bits of the Long. + * @return {Long} + */ + function Long(low, high) { + if (!(this instanceof Long)) return new Long(low, high); + + this._bsontype = 'Long'; + /** + * @type {number} + * @ignore + */ + this.low_ = low | 0; // force into 32 signed bits. + + /** + * @type {number} + * @ignore + */ + this.high_ = high | 0; // force into 32 signed bits. + } + + /** + * Return the int value. + * + * @method + * @return {number} the value, assuming it is a 32-bit integer. + */ + Long.prototype.toInt = function () { + return this.low_; + }; + + /** + * Return the Number value. + * + * @method + * @return {number} the closest floating-point representation to this value. + */ + Long.prototype.toNumber = function () { + return this.high_ * Long.TWO_PWR_32_DBL_ + this.getLowBitsUnsigned(); + }; + + /** + * Return the JSON value. + * + * @method + * @return {string} the JSON representation. + */ + Long.prototype.toJSON = function () { + return this.toString(); + }; + + /** + * Return the String value. + * + * @method + * @param {number} [opt_radix] the radix in which the text should be written. + * @return {string} the textual representation of this value. + */ + Long.prototype.toString = function (opt_radix) { + var radix = opt_radix || 10; + if (radix < 2 || 36 < radix) { + throw Error('radix out of range: ' + radix); + } + + if (this.isZero()) { + return '0'; + } + + if (this.isNegative()) { + if (this.equals(Long.MIN_VALUE)) { + // We need to change the Long value before it can be negated, so we remove + // the bottom-most digit in this base and then recurse to do the rest. + var radixLong = Long.fromNumber(radix); + var div = this.div(radixLong); + var rem = div.multiply(radixLong).subtract(this); + return div.toString(radix) + rem.toInt().toString(radix); + } else { + return '-' + this.negate().toString(radix); + } + } + + // Do several (6) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = Long.fromNumber(Math.pow(radix, 6)); + + rem = this; + var result = ''; + + while (!rem.isZero()) { + var remDiv = rem.div(radixToPower); + var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); + var digits = intval.toString(radix); + + rem = remDiv; + if (rem.isZero()) { + return digits + result; + } else { + while (digits.length < 6) { + digits = '0' + digits; + } + result = '' + digits + result; + } + } + }; + + /** + * Return the high 32-bits value. + * + * @method + * @return {number} the high 32-bits as a signed value. + */ + Long.prototype.getHighBits = function () { + return this.high_; + }; + + /** + * Return the low 32-bits value. + * + * @method + * @return {number} the low 32-bits as a signed value. + */ + Long.prototype.getLowBits = function () { + return this.low_; + }; + + /** + * Return the low unsigned 32-bits value. + * + * @method + * @return {number} the low 32-bits as an unsigned value. + */ + Long.prototype.getLowBitsUnsigned = function () { + return this.low_ >= 0 ? this.low_ : Long.TWO_PWR_32_DBL_ + this.low_; + }; + + /** + * Returns the number of bits needed to represent the absolute value of this Long. + * + * @method + * @return {number} Returns the number of bits needed to represent the absolute value of this Long. + */ + Long.prototype.getNumBitsAbs = function () { + if (this.isNegative()) { + if (this.equals(Long.MIN_VALUE)) { + return 64; + } else { + return this.negate().getNumBitsAbs(); + } + } else { + var val = this.high_ !== 0 ? this.high_ : this.low_; + for (var bit = 31; bit > 0; bit--) { + if ((val & 1 << bit) !== 0) { + break; + } + } + return this.high_ !== 0 ? bit + 33 : bit + 1; + } + }; + + /** + * Return whether this value is zero. + * + * @method + * @return {boolean} whether this value is zero. + */ + Long.prototype.isZero = function () { + return this.high_ === 0 && this.low_ === 0; + }; + + /** + * Return whether this value is negative. + * + * @method + * @return {boolean} whether this value is negative. + */ + Long.prototype.isNegative = function () { + return this.high_ < 0; + }; + + /** + * Return whether this value is odd. + * + * @method + * @return {boolean} whether this value is odd. + */ + Long.prototype.isOdd = function () { + return (this.low_ & 1) === 1; + }; + + /** + * Return whether this Long equals the other + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long equals the other + */ + Long.prototype.equals = function (other) { + return this.high_ === other.high_ && this.low_ === other.low_; + }; + + /** + * Return whether this Long does not equal the other. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long does not equal the other. + */ + Long.prototype.notEquals = function (other) { + return this.high_ !== other.high_ || this.low_ !== other.low_; + }; + + /** + * Return whether this Long is less than the other. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long is less than the other. + */ + Long.prototype.lessThan = function (other) { + return this.compare(other) < 0; + }; + + /** + * Return whether this Long is less than or equal to the other. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long is less than or equal to the other. + */ + Long.prototype.lessThanOrEqual = function (other) { + return this.compare(other) <= 0; + }; + + /** + * Return whether this Long is greater than the other. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long is greater than the other. + */ + Long.prototype.greaterThan = function (other) { + return this.compare(other) > 0; + }; + + /** + * Return whether this Long is greater than or equal to the other. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long is greater than or equal to the other. + */ + Long.prototype.greaterThanOrEqual = function (other) { + return this.compare(other) >= 0; + }; + + /** + * Compares this Long with the given one. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. + */ + Long.prototype.compare = function (other) { + if (this.equals(other)) { + return 0; + } + + var thisNeg = this.isNegative(); + var otherNeg = other.isNegative(); + if (thisNeg && !otherNeg) { + return -1; + } + if (!thisNeg && otherNeg) { + return 1; + } + + // at this point, the signs are the same, so subtraction will not overflow + if (this.subtract(other).isNegative()) { + return -1; + } else { + return 1; + } + }; + + /** + * The negation of this value. + * + * @method + * @return {Long} the negation of this value. + */ + Long.prototype.negate = function () { + if (this.equals(Long.MIN_VALUE)) { + return Long.MIN_VALUE; + } else { + return this.not().add(Long.ONE); + } + }; + + /** + * Returns the sum of this and the given Long. + * + * @method + * @param {Long} other Long to add to this one. + * @return {Long} the sum of this and the given Long. + */ + Long.prototype.add = function (other) { + // Divide each number into 4 chunks of 16 bits, and then sum the chunks. + + var a48 = this.high_ >>> 16; + var a32 = this.high_ & 0xffff; + var a16 = this.low_ >>> 16; + var a00 = this.low_ & 0xffff; + + var b48 = other.high_ >>> 16; + var b32 = other.high_ & 0xffff; + var b16 = other.low_ >>> 16; + var b00 = other.low_ & 0xffff; + + var c48 = 0, + c32 = 0, + c16 = 0, + c00 = 0; + c00 += a00 + b00; + c16 += c00 >>> 16; + c00 &= 0xffff; + c16 += a16 + b16; + c32 += c16 >>> 16; + c16 &= 0xffff; + c32 += a32 + b32; + c48 += c32 >>> 16; + c32 &= 0xffff; + c48 += a48 + b48; + c48 &= 0xffff; + return Long.fromBits(c16 << 16 | c00, c48 << 16 | c32); + }; + + /** + * Returns the difference of this and the given Long. + * + * @method + * @param {Long} other Long to subtract from this. + * @return {Long} the difference of this and the given Long. + */ + Long.prototype.subtract = function (other) { + return this.add(other.negate()); + }; + + /** + * Returns the product of this and the given Long. + * + * @method + * @param {Long} other Long to multiply with this. + * @return {Long} the product of this and the other. + */ + Long.prototype.multiply = function (other) { + if (this.isZero()) { + return Long.ZERO; + } else if (other.isZero()) { + return Long.ZERO; + } + + if (this.equals(Long.MIN_VALUE)) { + return other.isOdd() ? Long.MIN_VALUE : Long.ZERO; + } else if (other.equals(Long.MIN_VALUE)) { + return this.isOdd() ? Long.MIN_VALUE : Long.ZERO; + } + + if (this.isNegative()) { + if (other.isNegative()) { + return this.negate().multiply(other.negate()); + } else { + return this.negate().multiply(other).negate(); + } + } else if (other.isNegative()) { + return this.multiply(other.negate()).negate(); + } + + // If both Longs are small, use float multiplication + if (this.lessThan(Long.TWO_PWR_24_) && other.lessThan(Long.TWO_PWR_24_)) { + return Long.fromNumber(this.toNumber() * other.toNumber()); + } + + // Divide each Long into 4 chunks of 16 bits, and then add up 4x4 products. + // We can skip products that would overflow. + + var a48 = this.high_ >>> 16; + var a32 = this.high_ & 0xffff; + var a16 = this.low_ >>> 16; + var a00 = this.low_ & 0xffff; + + var b48 = other.high_ >>> 16; + var b32 = other.high_ & 0xffff; + var b16 = other.low_ >>> 16; + var b00 = other.low_ & 0xffff; + + var c48 = 0, + c32 = 0, + c16 = 0, + c00 = 0; + c00 += a00 * b00; + c16 += c00 >>> 16; + c00 &= 0xffff; + c16 += a16 * b00; + c32 += c16 >>> 16; + c16 &= 0xffff; + c16 += a00 * b16; + c32 += c16 >>> 16; + c16 &= 0xffff; + c32 += a32 * b00; + c48 += c32 >>> 16; + c32 &= 0xffff; + c32 += a16 * b16; + c48 += c32 >>> 16; + c32 &= 0xffff; + c32 += a00 * b32; + c48 += c32 >>> 16; + c32 &= 0xffff; + c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; + c48 &= 0xffff; + return Long.fromBits(c16 << 16 | c00, c48 << 16 | c32); + }; + + /** + * Returns this Long divided by the given one. + * + * @method + * @param {Long} other Long by which to divide. + * @return {Long} this Long divided by the given one. + */ + Long.prototype.div = function (other) { + if (other.isZero()) { + throw Error('division by zero'); + } else if (this.isZero()) { + return Long.ZERO; + } + + if (this.equals(Long.MIN_VALUE)) { + if (other.equals(Long.ONE) || other.equals(Long.NEG_ONE)) { + return Long.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE + } else if (other.equals(Long.MIN_VALUE)) { + return Long.ONE; + } else { + // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. + var halfThis = this.shiftRight(1); + var approx = halfThis.div(other).shiftLeft(1); + if (approx.equals(Long.ZERO)) { + return other.isNegative() ? Long.ONE : Long.NEG_ONE; + } else { + var rem = this.subtract(other.multiply(approx)); + var result = approx.add(rem.div(other)); + return result; + } + } + } else if (other.equals(Long.MIN_VALUE)) { + return Long.ZERO; + } + + if (this.isNegative()) { + if (other.isNegative()) { + return this.negate().div(other.negate()); + } else { + return this.negate().div(other).negate(); + } + } else if (other.isNegative()) { + return this.div(other.negate()).negate(); + } + + // Repeat the following until the remainder is less than other: find a + // floating-point that approximates remainder / other *from below*, add this + // into the result, and subtract it from the remainder. It is critical that + // the approximate value is less than or equal to the real value so that the + // remainder never becomes negative. + var res = Long.ZERO; + rem = this; + while (rem.greaterThanOrEqual(other)) { + // Approximate the result of division. This may be a little greater or + // smaller than the actual value. + approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); + + // We will tweak the approximate result by changing it in the 48-th digit or + // the smallest non-fractional digit, whichever is larger. + var log2 = Math.ceil(Math.log(approx) / Math.LN2); + var delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48); + + // Decrease the approximation until it is smaller than the remainder. Note + // that if it is too large, the product overflows and is negative. + var approxRes = Long.fromNumber(approx); + var approxRem = approxRes.multiply(other); + while (approxRem.isNegative() || approxRem.greaterThan(rem)) { + approx -= delta; + approxRes = Long.fromNumber(approx); + approxRem = approxRes.multiply(other); + } + + // We know the answer can't be zero... and actually, zero would cause + // infinite recursion since we would make no progress. + if (approxRes.isZero()) { + approxRes = Long.ONE; + } + + res = res.add(approxRes); + rem = rem.subtract(approxRem); + } + return res; + }; + + /** + * Returns this Long modulo the given one. + * + * @method + * @param {Long} other Long by which to mod. + * @return {Long} this Long modulo the given one. + */ + Long.prototype.modulo = function (other) { + return this.subtract(this.div(other).multiply(other)); + }; + + /** + * The bitwise-NOT of this value. + * + * @method + * @return {Long} the bitwise-NOT of this value. + */ + Long.prototype.not = function () { + return Long.fromBits(~this.low_, ~this.high_); + }; + + /** + * Returns the bitwise-AND of this Long and the given one. + * + * @method + * @param {Long} other the Long with which to AND. + * @return {Long} the bitwise-AND of this and the other. + */ + Long.prototype.and = function (other) { + return Long.fromBits(this.low_ & other.low_, this.high_ & other.high_); + }; + + /** + * Returns the bitwise-OR of this Long and the given one. + * + * @method + * @param {Long} other the Long with which to OR. + * @return {Long} the bitwise-OR of this and the other. + */ + Long.prototype.or = function (other) { + return Long.fromBits(this.low_ | other.low_, this.high_ | other.high_); + }; + + /** + * Returns the bitwise-XOR of this Long and the given one. + * + * @method + * @param {Long} other the Long with which to XOR. + * @return {Long} the bitwise-XOR of this and the other. + */ + Long.prototype.xor = function (other) { + return Long.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); + }; + + /** + * Returns this Long with bits shifted to the left by the given amount. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Long} this shifted to the left by the given amount. + */ + Long.prototype.shiftLeft = function (numBits) { + numBits &= 63; + if (numBits === 0) { + return this; + } else { + var low = this.low_; + if (numBits < 32) { + var high = this.high_; + return Long.fromBits(low << numBits, high << numBits | low >>> 32 - numBits); + } else { + return Long.fromBits(0, low << numBits - 32); + } + } + }; + + /** + * Returns this Long with bits shifted to the right by the given amount. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Long} this shifted to the right by the given amount. + */ + Long.prototype.shiftRight = function (numBits) { + numBits &= 63; + if (numBits === 0) { + return this; + } else { + var high = this.high_; + if (numBits < 32) { + var low = this.low_; + return Long.fromBits(low >>> numBits | high << 32 - numBits, high >> numBits); + } else { + return Long.fromBits(high >> numBits - 32, high >= 0 ? 0 : -1); + } + } + }; + + /** + * Returns this Long with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Long} this shifted to the right by the given amount, with zeros placed into the new leading bits. + */ + Long.prototype.shiftRightUnsigned = function (numBits) { + numBits &= 63; + if (numBits === 0) { + return this; + } else { + var high = this.high_; + if (numBits < 32) { + var low = this.low_; + return Long.fromBits(low >>> numBits | high << 32 - numBits, high >>> numBits); + } else if (numBits === 32) { + return Long.fromBits(high, 0); + } else { + return Long.fromBits(high >>> numBits - 32, 0); + } + } + }; + + /** + * Returns a Long representing the given (32-bit) integer value. + * + * @method + * @param {number} value the 32-bit integer in question. + * @return {Long} the corresponding Long value. + */ + Long.fromInt = function (value) { + if (-128 <= value && value < 128) { + var cachedObj = Long.INT_CACHE_[value]; + if (cachedObj) { + return cachedObj; + } + } + + var obj = new Long(value | 0, value < 0 ? -1 : 0); + if (-128 <= value && value < 128) { + Long.INT_CACHE_[value] = obj; + } + return obj; + }; + + /** + * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. + * + * @method + * @param {number} value the number in question. + * @return {Long} the corresponding Long value. + */ + Long.fromNumber = function (value) { + if (isNaN(value) || !isFinite(value)) { + return Long.ZERO; + } else if (value <= -Long.TWO_PWR_63_DBL_) { + return Long.MIN_VALUE; + } else if (value + 1 >= Long.TWO_PWR_63_DBL_) { + return Long.MAX_VALUE; + } else if (value < 0) { + return Long.fromNumber(-value).negate(); + } else { + return new Long(value % Long.TWO_PWR_32_DBL_ | 0, value / Long.TWO_PWR_32_DBL_ | 0); + } + }; + + /** + * Returns a Long representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. + * + * @method + * @param {number} lowBits the low 32-bits. + * @param {number} highBits the high 32-bits. + * @return {Long} the corresponding Long value. + */ + Long.fromBits = function (lowBits, highBits) { + return new Long(lowBits, highBits); + }; + + /** + * Returns a Long representation of the given string, written using the given radix. + * + * @method + * @param {string} str the textual representation of the Long. + * @param {number} opt_radix the radix in which the text is written. + * @return {Long} the corresponding Long value. + */ + Long.fromString = function (str, opt_radix) { + if (str.length === 0) { + throw Error('number format error: empty string'); + } + + var radix = opt_radix || 10; + if (radix < 2 || 36 < radix) { + throw Error('radix out of range: ' + radix); + } + + if (str.charAt(0) === '-') { + return Long.fromString(str.substring(1), radix).negate(); + } else if (str.indexOf('-') >= 0) { + throw Error('number format error: interior "-" character: ' + str); + } + + // Do several (8) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = Long.fromNumber(Math.pow(radix, 8)); + + var result = Long.ZERO; + for (var i = 0; i < str.length; i += 8) { + var size = Math.min(8, str.length - i); + var value = parseInt(str.substring(i, i + size), radix); + if (size < 8) { + var power = Long.fromNumber(Math.pow(radix, size)); + result = result.multiply(power).add(Long.fromNumber(value)); + } else { + result = result.multiply(radixToPower); + result = result.add(Long.fromNumber(value)); + } + } + return result; + }; + + // NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the + // from* methods on which they depend. + + /** + * A cache of the Long representations of small integer values. + * @type {Object} + * @ignore + */ + Long.INT_CACHE_ = {}; + + // NOTE: the compiler should inline these constant values below and then remove + // these variables, so there should be no runtime penalty for these. + + /** + * Number used repeated below in calculations. This must appear before the + * first call to any from* function below. + * @type {number} + * @ignore + */ + Long.TWO_PWR_16_DBL_ = 1 << 16; + + /** + * @type {number} + * @ignore + */ + Long.TWO_PWR_24_DBL_ = 1 << 24; + + /** + * @type {number} + * @ignore + */ + Long.TWO_PWR_32_DBL_ = Long.TWO_PWR_16_DBL_ * Long.TWO_PWR_16_DBL_; + + /** + * @type {number} + * @ignore + */ + Long.TWO_PWR_31_DBL_ = Long.TWO_PWR_32_DBL_ / 2; + + /** + * @type {number} + * @ignore + */ + Long.TWO_PWR_48_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_16_DBL_; + + /** + * @type {number} + * @ignore + */ + Long.TWO_PWR_64_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_32_DBL_; + + /** + * @type {number} + * @ignore + */ + Long.TWO_PWR_63_DBL_ = Long.TWO_PWR_64_DBL_ / 2; + + /** @type {Long} */ + Long.ZERO = Long.fromInt(0); + + /** @type {Long} */ + Long.ONE = Long.fromInt(1); + + /** @type {Long} */ + Long.NEG_ONE = Long.fromInt(-1); + + /** @type {Long} */ + Long.MAX_VALUE = Long.fromBits(0xffffffff | 0, 0x7fffffff | 0); + + /** @type {Long} */ + Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0); + + /** + * @type {Long} + * @ignore + */ + Long.TWO_PWR_24_ = Long.fromInt(1 << 24); + + /** + * Expose. + */ + module.exports = Long; + module.exports.Long = Long; + +/***/ }), +/* 331 */ +/***/ (function(module, exports) { + + /** + * A class representation of the BSON Double type. + * + * @class + * @param {number} value the number we want to represent as a double. + * @return {Double} + */ + function Double(value) { + if (!(this instanceof Double)) return new Double(value); + + this._bsontype = 'Double'; + this.value = value; + } + + /** + * Access the number value. + * + * @method + * @return {number} returns the wrapped double number. + */ + Double.prototype.valueOf = function () { + return this.value; + }; + + /** + * @ignore + */ + Double.prototype.toJSON = function () { + return this.value; + }; + + module.exports = Double; + module.exports.Double = Double; + +/***/ }), +/* 332 */ +/***/ (function(module, exports) { + + // Licensed under the Apache License, Version 2.0 (the "License"); + // you may not use this file except in compliance with the License. + // You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + // Copyright 2009 Google Inc. All Rights Reserved + + /** + * This type is for INTERNAL use in MongoDB only and should not be used in applications. + * The appropriate corresponding type is the JavaScript Date type. + * + * Defines a Timestamp class for representing a 64-bit two's-complement + * integer value, which faithfully simulates the behavior of a Java "Timestamp". This + * implementation is derived from TimestampLib in GWT. + * + * Constructs a 64-bit two's-complement integer, given its low and high 32-bit + * values as *signed* integers. See the from* functions below for more + * convenient ways of constructing Timestamps. + * + * The internal representation of a Timestamp is the two given signed, 32-bit values. + * We use 32-bit pieces because these are the size of integers on which + * Javascript performs bit-operations. For operations like addition and + * multiplication, we split each number into 16-bit pieces, which can easily be + * multiplied within Javascript's floating-point representation without overflow + * or change in sign. + * + * In the algorithms below, we frequently reduce the negative case to the + * positive case by negating the input(s) and then post-processing the result. + * Note that we must ALWAYS check specially whether those values are MIN_VALUE + * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as + * a positive number, it overflows back into a negative). Not handling this + * case would often result in infinite recursion. + * + * @class + * @param {number} low the low (signed) 32 bits of the Timestamp. + * @param {number} high the high (signed) 32 bits of the Timestamp. + */ + function Timestamp(low, high) { + if (!(this instanceof Timestamp)) return new Timestamp(low, high); + this._bsontype = 'Timestamp'; + /** + * @type {number} + * @ignore + */ + this.low_ = low | 0; // force into 32 signed bits. + + /** + * @type {number} + * @ignore + */ + this.high_ = high | 0; // force into 32 signed bits. + } + + /** + * Return the int value. + * + * @return {number} the value, assuming it is a 32-bit integer. + */ + Timestamp.prototype.toInt = function () { + return this.low_; + }; + + /** + * Return the Number value. + * + * @method + * @return {number} the closest floating-point representation to this value. + */ + Timestamp.prototype.toNumber = function () { + return this.high_ * Timestamp.TWO_PWR_32_DBL_ + this.getLowBitsUnsigned(); + }; + + /** + * Return the JSON value. + * + * @method + * @return {string} the JSON representation. + */ + Timestamp.prototype.toJSON = function () { + return this.toString(); + }; + + /** + * Return the String value. + * + * @method + * @param {number} [opt_radix] the radix in which the text should be written. + * @return {string} the textual representation of this value. + */ + Timestamp.prototype.toString = function (opt_radix) { + var radix = opt_radix || 10; + if (radix < 2 || 36 < radix) { + throw Error('radix out of range: ' + radix); + } + + if (this.isZero()) { + return '0'; + } + + if (this.isNegative()) { + if (this.equals(Timestamp.MIN_VALUE)) { + // We need to change the Timestamp value before it can be negated, so we remove + // the bottom-most digit in this base and then recurse to do the rest. + var radixTimestamp = Timestamp.fromNumber(radix); + var div = this.div(radixTimestamp); + var rem = div.multiply(radixTimestamp).subtract(this); + return div.toString(radix) + rem.toInt().toString(radix); + } else { + return '-' + this.negate().toString(radix); + } + } + + // Do several (6) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = Timestamp.fromNumber(Math.pow(radix, 6)); + + rem = this; + var result = ''; + + while (!rem.isZero()) { + var remDiv = rem.div(radixToPower); + var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); + var digits = intval.toString(radix); + + rem = remDiv; + if (rem.isZero()) { + return digits + result; + } else { + while (digits.length < 6) { + digits = '0' + digits; + } + result = '' + digits + result; + } + } + }; + + /** + * Return the high 32-bits value. + * + * @method + * @return {number} the high 32-bits as a signed value. + */ + Timestamp.prototype.getHighBits = function () { + return this.high_; + }; + + /** + * Return the low 32-bits value. + * + * @method + * @return {number} the low 32-bits as a signed value. + */ + Timestamp.prototype.getLowBits = function () { + return this.low_; + }; + + /** + * Return the low unsigned 32-bits value. + * + * @method + * @return {number} the low 32-bits as an unsigned value. + */ + Timestamp.prototype.getLowBitsUnsigned = function () { + return this.low_ >= 0 ? this.low_ : Timestamp.TWO_PWR_32_DBL_ + this.low_; + }; + + /** + * Returns the number of bits needed to represent the absolute value of this Timestamp. + * + * @method + * @return {number} Returns the number of bits needed to represent the absolute value of this Timestamp. + */ + Timestamp.prototype.getNumBitsAbs = function () { + if (this.isNegative()) { + if (this.equals(Timestamp.MIN_VALUE)) { + return 64; + } else { + return this.negate().getNumBitsAbs(); + } + } else { + var val = this.high_ !== 0 ? this.high_ : this.low_; + for (var bit = 31; bit > 0; bit--) { + if ((val & 1 << bit) !== 0) { + break; + } + } + return this.high_ !== 0 ? bit + 33 : bit + 1; + } + }; + + /** + * Return whether this value is zero. + * + * @method + * @return {boolean} whether this value is zero. + */ + Timestamp.prototype.isZero = function () { + return this.high_ === 0 && this.low_ === 0; + }; + + /** + * Return whether this value is negative. + * + * @method + * @return {boolean} whether this value is negative. + */ + Timestamp.prototype.isNegative = function () { + return this.high_ < 0; + }; + + /** + * Return whether this value is odd. + * + * @method + * @return {boolean} whether this value is odd. + */ + Timestamp.prototype.isOdd = function () { + return (this.low_ & 1) === 1; + }; + + /** + * Return whether this Timestamp equals the other + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp equals the other + */ + Timestamp.prototype.equals = function (other) { + return this.high_ === other.high_ && this.low_ === other.low_; + }; + + /** + * Return whether this Timestamp does not equal the other. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp does not equal the other. + */ + Timestamp.prototype.notEquals = function (other) { + return this.high_ !== other.high_ || this.low_ !== other.low_; + }; + + /** + * Return whether this Timestamp is less than the other. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp is less than the other. + */ + Timestamp.prototype.lessThan = function (other) { + return this.compare(other) < 0; + }; + + /** + * Return whether this Timestamp is less than or equal to the other. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp is less than or equal to the other. + */ + Timestamp.prototype.lessThanOrEqual = function (other) { + return this.compare(other) <= 0; + }; + + /** + * Return whether this Timestamp is greater than the other. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp is greater than the other. + */ + Timestamp.prototype.greaterThan = function (other) { + return this.compare(other) > 0; + }; + + /** + * Return whether this Timestamp is greater than or equal to the other. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp is greater than or equal to the other. + */ + Timestamp.prototype.greaterThanOrEqual = function (other) { + return this.compare(other) >= 0; + }; + + /** + * Compares this Timestamp with the given one. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. + */ + Timestamp.prototype.compare = function (other) { + if (this.equals(other)) { + return 0; + } + + var thisNeg = this.isNegative(); + var otherNeg = other.isNegative(); + if (thisNeg && !otherNeg) { + return -1; + } + if (!thisNeg && otherNeg) { + return 1; + } + + // at this point, the signs are the same, so subtraction will not overflow + if (this.subtract(other).isNegative()) { + return -1; + } else { + return 1; + } + }; + + /** + * The negation of this value. + * + * @method + * @return {Timestamp} the negation of this value. + */ + Timestamp.prototype.negate = function () { + if (this.equals(Timestamp.MIN_VALUE)) { + return Timestamp.MIN_VALUE; + } else { + return this.not().add(Timestamp.ONE); + } + }; + + /** + * Returns the sum of this and the given Timestamp. + * + * @method + * @param {Timestamp} other Timestamp to add to this one. + * @return {Timestamp} the sum of this and the given Timestamp. + */ + Timestamp.prototype.add = function (other) { + // Divide each number into 4 chunks of 16 bits, and then sum the chunks. + + var a48 = this.high_ >>> 16; + var a32 = this.high_ & 0xffff; + var a16 = this.low_ >>> 16; + var a00 = this.low_ & 0xffff; + + var b48 = other.high_ >>> 16; + var b32 = other.high_ & 0xffff; + var b16 = other.low_ >>> 16; + var b00 = other.low_ & 0xffff; + + var c48 = 0, + c32 = 0, + c16 = 0, + c00 = 0; + c00 += a00 + b00; + c16 += c00 >>> 16; + c00 &= 0xffff; + c16 += a16 + b16; + c32 += c16 >>> 16; + c16 &= 0xffff; + c32 += a32 + b32; + c48 += c32 >>> 16; + c32 &= 0xffff; + c48 += a48 + b48; + c48 &= 0xffff; + return Timestamp.fromBits(c16 << 16 | c00, c48 << 16 | c32); + }; + + /** + * Returns the difference of this and the given Timestamp. + * + * @method + * @param {Timestamp} other Timestamp to subtract from this. + * @return {Timestamp} the difference of this and the given Timestamp. + */ + Timestamp.prototype.subtract = function (other) { + return this.add(other.negate()); + }; + + /** + * Returns the product of this and the given Timestamp. + * + * @method + * @param {Timestamp} other Timestamp to multiply with this. + * @return {Timestamp} the product of this and the other. + */ + Timestamp.prototype.multiply = function (other) { + if (this.isZero()) { + return Timestamp.ZERO; + } else if (other.isZero()) { + return Timestamp.ZERO; + } + + if (this.equals(Timestamp.MIN_VALUE)) { + return other.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; + } else if (other.equals(Timestamp.MIN_VALUE)) { + return this.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; + } + + if (this.isNegative()) { + if (other.isNegative()) { + return this.negate().multiply(other.negate()); + } else { + return this.negate().multiply(other).negate(); + } + } else if (other.isNegative()) { + return this.multiply(other.negate()).negate(); + } + + // If both Timestamps are small, use float multiplication + if (this.lessThan(Timestamp.TWO_PWR_24_) && other.lessThan(Timestamp.TWO_PWR_24_)) { + return Timestamp.fromNumber(this.toNumber() * other.toNumber()); + } + + // Divide each Timestamp into 4 chunks of 16 bits, and then add up 4x4 products. + // We can skip products that would overflow. + + var a48 = this.high_ >>> 16; + var a32 = this.high_ & 0xffff; + var a16 = this.low_ >>> 16; + var a00 = this.low_ & 0xffff; + + var b48 = other.high_ >>> 16; + var b32 = other.high_ & 0xffff; + var b16 = other.low_ >>> 16; + var b00 = other.low_ & 0xffff; + + var c48 = 0, + c32 = 0, + c16 = 0, + c00 = 0; + c00 += a00 * b00; + c16 += c00 >>> 16; + c00 &= 0xffff; + c16 += a16 * b00; + c32 += c16 >>> 16; + c16 &= 0xffff; + c16 += a00 * b16; + c32 += c16 >>> 16; + c16 &= 0xffff; + c32 += a32 * b00; + c48 += c32 >>> 16; + c32 &= 0xffff; + c32 += a16 * b16; + c48 += c32 >>> 16; + c32 &= 0xffff; + c32 += a00 * b32; + c48 += c32 >>> 16; + c32 &= 0xffff; + c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; + c48 &= 0xffff; + return Timestamp.fromBits(c16 << 16 | c00, c48 << 16 | c32); + }; + + /** + * Returns this Timestamp divided by the given one. + * + * @method + * @param {Timestamp} other Timestamp by which to divide. + * @return {Timestamp} this Timestamp divided by the given one. + */ + Timestamp.prototype.div = function (other) { + if (other.isZero()) { + throw Error('division by zero'); + } else if (this.isZero()) { + return Timestamp.ZERO; + } + + if (this.equals(Timestamp.MIN_VALUE)) { + if (other.equals(Timestamp.ONE) || other.equals(Timestamp.NEG_ONE)) { + return Timestamp.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE + } else if (other.equals(Timestamp.MIN_VALUE)) { + return Timestamp.ONE; + } else { + // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. + var halfThis = this.shiftRight(1); + var approx = halfThis.div(other).shiftLeft(1); + if (approx.equals(Timestamp.ZERO)) { + return other.isNegative() ? Timestamp.ONE : Timestamp.NEG_ONE; + } else { + var rem = this.subtract(other.multiply(approx)); + var result = approx.add(rem.div(other)); + return result; + } + } + } else if (other.equals(Timestamp.MIN_VALUE)) { + return Timestamp.ZERO; + } + + if (this.isNegative()) { + if (other.isNegative()) { + return this.negate().div(other.negate()); + } else { + return this.negate().div(other).negate(); + } + } else if (other.isNegative()) { + return this.div(other.negate()).negate(); + } + + // Repeat the following until the remainder is less than other: find a + // floating-point that approximates remainder / other *from below*, add this + // into the result, and subtract it from the remainder. It is critical that + // the approximate value is less than or equal to the real value so that the + // remainder never becomes negative. + var res = Timestamp.ZERO; + rem = this; + while (rem.greaterThanOrEqual(other)) { + // Approximate the result of division. This may be a little greater or + // smaller than the actual value. + approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); + + // We will tweak the approximate result by changing it in the 48-th digit or + // the smallest non-fractional digit, whichever is larger. + var log2 = Math.ceil(Math.log(approx) / Math.LN2); + var delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48); + + // Decrease the approximation until it is smaller than the remainder. Note + // that if it is too large, the product overflows and is negative. + var approxRes = Timestamp.fromNumber(approx); + var approxRem = approxRes.multiply(other); + while (approxRem.isNegative() || approxRem.greaterThan(rem)) { + approx -= delta; + approxRes = Timestamp.fromNumber(approx); + approxRem = approxRes.multiply(other); + } + + // We know the answer can't be zero... and actually, zero would cause + // infinite recursion since we would make no progress. + if (approxRes.isZero()) { + approxRes = Timestamp.ONE; + } + + res = res.add(approxRes); + rem = rem.subtract(approxRem); + } + return res; + }; + + /** + * Returns this Timestamp modulo the given one. + * + * @method + * @param {Timestamp} other Timestamp by which to mod. + * @return {Timestamp} this Timestamp modulo the given one. + */ + Timestamp.prototype.modulo = function (other) { + return this.subtract(this.div(other).multiply(other)); + }; + + /** + * The bitwise-NOT of this value. + * + * @method + * @return {Timestamp} the bitwise-NOT of this value. + */ + Timestamp.prototype.not = function () { + return Timestamp.fromBits(~this.low_, ~this.high_); + }; + + /** + * Returns the bitwise-AND of this Timestamp and the given one. + * + * @method + * @param {Timestamp} other the Timestamp with which to AND. + * @return {Timestamp} the bitwise-AND of this and the other. + */ + Timestamp.prototype.and = function (other) { + return Timestamp.fromBits(this.low_ & other.low_, this.high_ & other.high_); + }; + + /** + * Returns the bitwise-OR of this Timestamp and the given one. + * + * @method + * @param {Timestamp} other the Timestamp with which to OR. + * @return {Timestamp} the bitwise-OR of this and the other. + */ + Timestamp.prototype.or = function (other) { + return Timestamp.fromBits(this.low_ | other.low_, this.high_ | other.high_); + }; + + /** + * Returns the bitwise-XOR of this Timestamp and the given one. + * + * @method + * @param {Timestamp} other the Timestamp with which to XOR. + * @return {Timestamp} the bitwise-XOR of this and the other. + */ + Timestamp.prototype.xor = function (other) { + return Timestamp.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); + }; + + /** + * Returns this Timestamp with bits shifted to the left by the given amount. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Timestamp} this shifted to the left by the given amount. + */ + Timestamp.prototype.shiftLeft = function (numBits) { + numBits &= 63; + if (numBits === 0) { + return this; + } else { + var low = this.low_; + if (numBits < 32) { + var high = this.high_; + return Timestamp.fromBits(low << numBits, high << numBits | low >>> 32 - numBits); + } else { + return Timestamp.fromBits(0, low << numBits - 32); + } + } + }; + + /** + * Returns this Timestamp with bits shifted to the right by the given amount. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Timestamp} this shifted to the right by the given amount. + */ + Timestamp.prototype.shiftRight = function (numBits) { + numBits &= 63; + if (numBits === 0) { + return this; + } else { + var high = this.high_; + if (numBits < 32) { + var low = this.low_; + return Timestamp.fromBits(low >>> numBits | high << 32 - numBits, high >> numBits); + } else { + return Timestamp.fromBits(high >> numBits - 32, high >= 0 ? 0 : -1); + } + } + }; + + /** + * Returns this Timestamp with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Timestamp} this shifted to the right by the given amount, with zeros placed into the new leading bits. + */ + Timestamp.prototype.shiftRightUnsigned = function (numBits) { + numBits &= 63; + if (numBits === 0) { + return this; + } else { + var high = this.high_; + if (numBits < 32) { + var low = this.low_; + return Timestamp.fromBits(low >>> numBits | high << 32 - numBits, high >>> numBits); + } else if (numBits === 32) { + return Timestamp.fromBits(high, 0); + } else { + return Timestamp.fromBits(high >>> numBits - 32, 0); + } + } + }; + + /** + * Returns a Timestamp representing the given (32-bit) integer value. + * + * @method + * @param {number} value the 32-bit integer in question. + * @return {Timestamp} the corresponding Timestamp value. + */ + Timestamp.fromInt = function (value) { + if (-128 <= value && value < 128) { + var cachedObj = Timestamp.INT_CACHE_[value]; + if (cachedObj) { + return cachedObj; + } + } + + var obj = new Timestamp(value | 0, value < 0 ? -1 : 0); + if (-128 <= value && value < 128) { + Timestamp.INT_CACHE_[value] = obj; + } + return obj; + }; + + /** + * Returns a Timestamp representing the given value, provided that it is a finite number. Otherwise, zero is returned. + * + * @method + * @param {number} value the number in question. + * @return {Timestamp} the corresponding Timestamp value. + */ + Timestamp.fromNumber = function (value) { + if (isNaN(value) || !isFinite(value)) { + return Timestamp.ZERO; + } else if (value <= -Timestamp.TWO_PWR_63_DBL_) { + return Timestamp.MIN_VALUE; + } else if (value + 1 >= Timestamp.TWO_PWR_63_DBL_) { + return Timestamp.MAX_VALUE; + } else if (value < 0) { + return Timestamp.fromNumber(-value).negate(); + } else { + return new Timestamp(value % Timestamp.TWO_PWR_32_DBL_ | 0, value / Timestamp.TWO_PWR_32_DBL_ | 0); + } + }; + + /** + * Returns a Timestamp representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. + * + * @method + * @param {number} lowBits the low 32-bits. + * @param {number} highBits the high 32-bits. + * @return {Timestamp} the corresponding Timestamp value. + */ + Timestamp.fromBits = function (lowBits, highBits) { + return new Timestamp(lowBits, highBits); + }; + + /** + * Returns a Timestamp representation of the given string, written using the given radix. + * + * @method + * @param {string} str the textual representation of the Timestamp. + * @param {number} opt_radix the radix in which the text is written. + * @return {Timestamp} the corresponding Timestamp value. + */ + Timestamp.fromString = function (str, opt_radix) { + if (str.length === 0) { + throw Error('number format error: empty string'); + } + + var radix = opt_radix || 10; + if (radix < 2 || 36 < radix) { + throw Error('radix out of range: ' + radix); + } + + if (str.charAt(0) === '-') { + return Timestamp.fromString(str.substring(1), radix).negate(); + } else if (str.indexOf('-') >= 0) { + throw Error('number format error: interior "-" character: ' + str); + } + + // Do several (8) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = Timestamp.fromNumber(Math.pow(radix, 8)); + + var result = Timestamp.ZERO; + for (var i = 0; i < str.length; i += 8) { + var size = Math.min(8, str.length - i); + var value = parseInt(str.substring(i, i + size), radix); + if (size < 8) { + var power = Timestamp.fromNumber(Math.pow(radix, size)); + result = result.multiply(power).add(Timestamp.fromNumber(value)); + } else { + result = result.multiply(radixToPower); + result = result.add(Timestamp.fromNumber(value)); + } + } + return result; + }; + + // NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the + // from* methods on which they depend. + + /** + * A cache of the Timestamp representations of small integer values. + * @type {Object} + * @ignore + */ + Timestamp.INT_CACHE_ = {}; + + // NOTE: the compiler should inline these constant values below and then remove + // these variables, so there should be no runtime penalty for these. + + /** + * Number used repeated below in calculations. This must appear before the + * first call to any from* function below. + * @type {number} + * @ignore + */ + Timestamp.TWO_PWR_16_DBL_ = 1 << 16; + + /** + * @type {number} + * @ignore + */ + Timestamp.TWO_PWR_24_DBL_ = 1 << 24; + + /** + * @type {number} + * @ignore + */ + Timestamp.TWO_PWR_32_DBL_ = Timestamp.TWO_PWR_16_DBL_ * Timestamp.TWO_PWR_16_DBL_; + + /** + * @type {number} + * @ignore + */ + Timestamp.TWO_PWR_31_DBL_ = Timestamp.TWO_PWR_32_DBL_ / 2; + + /** + * @type {number} + * @ignore + */ + Timestamp.TWO_PWR_48_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_16_DBL_; + + /** + * @type {number} + * @ignore + */ + Timestamp.TWO_PWR_64_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_32_DBL_; + + /** + * @type {number} + * @ignore + */ + Timestamp.TWO_PWR_63_DBL_ = Timestamp.TWO_PWR_64_DBL_ / 2; + + /** @type {Timestamp} */ + Timestamp.ZERO = Timestamp.fromInt(0); + + /** @type {Timestamp} */ + Timestamp.ONE = Timestamp.fromInt(1); + + /** @type {Timestamp} */ + Timestamp.NEG_ONE = Timestamp.fromInt(-1); + + /** @type {Timestamp} */ + Timestamp.MAX_VALUE = Timestamp.fromBits(0xffffffff | 0, 0x7fffffff | 0); + + /** @type {Timestamp} */ + Timestamp.MIN_VALUE = Timestamp.fromBits(0, 0x80000000 | 0); + + /** + * @type {Timestamp} + * @ignore + */ + Timestamp.TWO_PWR_24_ = Timestamp.fromInt(1 << 24); + + /** + * Expose. + */ + module.exports = Timestamp; + module.exports.Timestamp = Timestamp; + +/***/ }), +/* 333 */ +/***/ (function(module, exports, __webpack_require__) { + + /* WEBPACK VAR INJECTION */(function(Buffer, process) {// Custom inspect property name / symbol. + var inspect = 'inspect'; + + var utils = __webpack_require__(339); + + /** + * Machine id. + * + * Create a random 3-byte value (i.e. unique for this + * process). Other drivers use a md5 of the machine id here, but + * that would mean an asyc call to gethostname, so we don't bother. + * @ignore + */ + var MACHINE_ID = parseInt(Math.random() * 0xffffff, 10); + + // Regular expression that checks for hex value + var checkForHexRegExp = new RegExp('^[0-9a-fA-F]{24}$'); + + // Check if buffer exists + try { + if (Buffer && Buffer.from) { + var hasBufferType = true; + inspect = __webpack_require__(340).inspect.custom || 'inspect'; + } + } catch (err) { + hasBufferType = false; + } + + /** + * Create a new ObjectID instance + * + * @class + * @param {(string|number)} id Can be a 24 byte hex string, 12 byte binary string or a Number. + * @property {number} generationTime The generation time of this ObjectId instance + * @return {ObjectID} instance of ObjectID. + */ + var ObjectID = function ObjectID(id) { + // Duck-typing to support ObjectId from different npm packages + if (id instanceof ObjectID) return id; + if (!(this instanceof ObjectID)) return new ObjectID(id); + + this._bsontype = 'ObjectID'; + + // The most common usecase (blank id, new objectId instance) + if (id == null || typeof id === 'number') { + // Generate a new id + this.id = this.generate(id); + // If we are caching the hex string + if (ObjectID.cacheHexString) this.__id = this.toString('hex'); + // Return the object + return; + } + + // Check if the passed in id is valid + var valid = ObjectID.isValid(id); + + // Throw an error if it's not a valid setup + if (!valid && id != null) { + throw new Error('Argument passed in must be a single String of 12 bytes or a string of 24 hex characters'); + } else if (valid && typeof id === 'string' && id.length === 24 && hasBufferType) { + return new ObjectID(utils.toBuffer(id, 'hex')); + } else if (valid && typeof id === 'string' && id.length === 24) { + return ObjectID.createFromHexString(id); + } else if (id != null && id.length === 12) { + // assume 12 byte string + this.id = id; + } else if (id != null && id.toHexString) { + // Duck-typing to support ObjectId from different npm packages + return id; + } else { + throw new Error('Argument passed in must be a single String of 12 bytes or a string of 24 hex characters'); + } + + if (ObjectID.cacheHexString) this.__id = this.toString('hex'); + }; + + // Allow usage of ObjectId as well as ObjectID + // var ObjectId = ObjectID; + + // Precomputed hex table enables speedy hex string conversion + var hexTable = []; + for (var i = 0; i < 256; i++) { + hexTable[i] = (i <= 15 ? '0' : '') + i.toString(16); + } + + /** + * Return the ObjectID id as a 24 byte hex string representation + * + * @method + * @return {string} return the 24 byte hex string representation. + */ + ObjectID.prototype.toHexString = function () { + if (ObjectID.cacheHexString && this.__id) return this.__id; + + var hexString = ''; + if (!this.id || !this.id.length) { + throw new Error('invalid ObjectId, ObjectId.id must be either a string or a Buffer, but is [' + JSON.stringify(this.id) + ']'); + } + + if (this.id instanceof _Buffer) { + hexString = convertToHex(this.id); + if (ObjectID.cacheHexString) this.__id = hexString; + return hexString; + } + + for (var i = 0; i < this.id.length; i++) { + hexString += hexTable[this.id.charCodeAt(i)]; + } + + if (ObjectID.cacheHexString) this.__id = hexString; + return hexString; + }; + + /** + * Update the ObjectID index used in generating new ObjectID's on the driver + * + * @method + * @return {number} returns next index value. + * @ignore + */ + ObjectID.prototype.get_inc = function () { + return ObjectID.index = (ObjectID.index + 1) % 0xffffff; + }; + + /** + * Update the ObjectID index used in generating new ObjectID's on the driver + * + * @method + * @return {number} returns next index value. + * @ignore + */ + ObjectID.prototype.getInc = function () { + return this.get_inc(); + }; + + /** + * Generate a 12 byte id buffer used in ObjectID's + * + * @method + * @param {number} [time] optional parameter allowing to pass in a second based timestamp. + * @return {Buffer} return the 12 byte id buffer string. + */ + ObjectID.prototype.generate = function (time) { + if ('number' !== typeof time) { + time = ~~(Date.now() / 1000); + } + + // Use pid + var pid = (typeof process === 'undefined' || process.pid === 1 ? Math.floor(Math.random() * 100000) : process.pid) % 0xffff; + var inc = this.get_inc(); + // Buffer used + var buffer = utils.allocBuffer(12); + // Encode time + buffer[3] = time & 0xff; + buffer[2] = time >> 8 & 0xff; + buffer[1] = time >> 16 & 0xff; + buffer[0] = time >> 24 & 0xff; + // Encode machine + buffer[6] = MACHINE_ID & 0xff; + buffer[5] = MACHINE_ID >> 8 & 0xff; + buffer[4] = MACHINE_ID >> 16 & 0xff; + // Encode pid + buffer[8] = pid & 0xff; + buffer[7] = pid >> 8 & 0xff; + // Encode index + buffer[11] = inc & 0xff; + buffer[10] = inc >> 8 & 0xff; + buffer[9] = inc >> 16 & 0xff; + // Return the buffer + return buffer; + }; + + /** + * Converts the id into a 24 byte hex string for printing + * + * @param {String} format The Buffer toString format parameter. + * @return {String} return the 24 byte hex string representation. + * @ignore + */ + ObjectID.prototype.toString = function (format) { + // Is the id a buffer then use the buffer toString method to return the format + if (this.id && this.id.copy) { + return this.id.toString(typeof format === 'string' ? format : 'hex'); + } + + // if(this.buffer ) + return this.toHexString(); + }; + + /** + * Converts to a string representation of this Id. + * + * @return {String} return the 24 byte hex string representation. + * @ignore + */ + ObjectID.prototype[inspect] = ObjectID.prototype.toString; + + /** + * Converts to its JSON representation. + * + * @return {String} return the 24 byte hex string representation. + * @ignore + */ + ObjectID.prototype.toJSON = function () { + return this.toHexString(); + }; + + /** + * Compares the equality of this ObjectID with `otherID`. + * + * @method + * @param {object} otherID ObjectID instance to compare against. + * @return {boolean} the result of comparing two ObjectID's + */ + ObjectID.prototype.equals = function equals(otherId) { + // var id; + + if (otherId instanceof ObjectID) { + return this.toString() === otherId.toString(); + } else if (typeof otherId === 'string' && ObjectID.isValid(otherId) && otherId.length === 12 && this.id instanceof _Buffer) { + return otherId === this.id.toString('binary'); + } else if (typeof otherId === 'string' && ObjectID.isValid(otherId) && otherId.length === 24) { + return otherId.toLowerCase() === this.toHexString(); + } else if (typeof otherId === 'string' && ObjectID.isValid(otherId) && otherId.length === 12) { + return otherId === this.id; + } else if (otherId != null && (otherId instanceof ObjectID || otherId.toHexString)) { + return otherId.toHexString() === this.toHexString(); + } else { + return false; + } + }; + + /** + * Returns the generation date (accurate up to the second) that this ID was generated. + * + * @method + * @return {date} the generation date + */ + ObjectID.prototype.getTimestamp = function () { + var timestamp = new Date(); + var time = this.id[3] | this.id[2] << 8 | this.id[1] << 16 | this.id[0] << 24; + timestamp.setTime(Math.floor(time) * 1000); + return timestamp; + }; + + /** + * @ignore + */ + ObjectID.index = ~~(Math.random() * 0xffffff); + + /** + * @ignore + */ + ObjectID.createPk = function createPk() { + return new ObjectID(); + }; + + /** + * Creates an ObjectID from a second based number, with the rest of the ObjectID zeroed out. Used for comparisons or sorting the ObjectID. + * + * @method + * @param {number} time an integer number representing a number of seconds. + * @return {ObjectID} return the created ObjectID + */ + ObjectID.createFromTime = function createFromTime(time) { + var buffer = utils.toBuffer([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); + // Encode time into first 4 bytes + buffer[3] = time & 0xff; + buffer[2] = time >> 8 & 0xff; + buffer[1] = time >> 16 & 0xff; + buffer[0] = time >> 24 & 0xff; + // Return the new objectId + return new ObjectID(buffer); + }; + + // Lookup tables + //var encodeLookup = '0123456789abcdef'.split(''); + var decodeLookup = []; + i = 0; + while (i < 10) decodeLookup[0x30 + i] = i++; + while (i < 16) decodeLookup[0x41 - 10 + i] = decodeLookup[0x61 - 10 + i] = i++; + + var _Buffer = Buffer; + var convertToHex = function (bytes) { + return bytes.toString('hex'); + }; + + /** + * Creates an ObjectID from a hex string representation of an ObjectID. + * + * @method + * @param {string} hexString create a ObjectID from a passed in 24 byte hexstring. + * @return {ObjectID} return the created ObjectID + */ + ObjectID.createFromHexString = function createFromHexString(string) { + // Throw an error if it's not a valid setup + if (typeof string === 'undefined' || string != null && string.length !== 24) { + throw new Error('Argument passed in must be a single String of 12 bytes or a string of 24 hex characters'); + } + + // Use Buffer.from method if available + if (hasBufferType) return new ObjectID(utils.toBuffer(string, 'hex')); + + // Calculate lengths + var array = new _Buffer(12); + var n = 0; + var i = 0; + + while (i < 24) { + array[n++] = decodeLookup[string.charCodeAt(i++)] << 4 | decodeLookup[string.charCodeAt(i++)]; + } + + return new ObjectID(array); + }; + + /** + * Checks if a value is a valid bson ObjectId + * + * @method + * @return {boolean} return true if the value is a valid bson ObjectId, return false otherwise. + */ + ObjectID.isValid = function isValid(id) { + if (id == null) return false; + + if (typeof id === 'number') { + return true; + } + + if (typeof id === 'string') { + return id.length === 12 || id.length === 24 && checkForHexRegExp.test(id); + } + + if (id instanceof ObjectID) { + return true; + } + + if (id instanceof _Buffer) { + return true; + } + + // Duck-Typing detection of ObjectId like objects + if (id.toHexString) { + return id.id.length === 12 || id.id.length === 24 && checkForHexRegExp.test(id.id); + } + + return false; + }; + + /** + * @ignore + */ + Object.defineProperty(ObjectID.prototype, 'generationTime', { + enumerable: true, + get: function () { + return this.id[3] | this.id[2] << 8 | this.id[1] << 16 | this.id[0] << 24; + }, + set: function (value) { + // Encode time into first 4 bytes + this.id[3] = value & 0xff; + this.id[2] = value >> 8 & 0xff; + this.id[1] = value >> 16 & 0xff; + this.id[0] = value >> 24 & 0xff; + } + }); + + /** + * Expose. + */ + module.exports = ObjectID; + module.exports.ObjectID = ObjectID; + module.exports.ObjectId = ObjectID; + /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(334).Buffer, __webpack_require__(338))) + +/***/ }), +/* 334 */ +/***/ (function(module, exports, __webpack_require__) { + + /* WEBPACK VAR INJECTION */(function(global) {/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ + /* eslint-disable no-proto */ + + 'use strict' + + var base64 = __webpack_require__(335) + var ieee754 = __webpack_require__(336) + var isArray = __webpack_require__(337) + + exports.Buffer = Buffer + exports.SlowBuffer = SlowBuffer + exports.INSPECT_MAX_BYTES = 50 + + /** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Use Object implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * Due to various browser bugs, sometimes the Object implementation will be used even + * when the browser supports typed arrays. + * + * Note: + * + * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, + * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. + * + * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. + * + * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of + * incorrect length in some situations. + + * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they + * get the Object implementation, which is slower but behaves correctly. + */ + Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined + ? global.TYPED_ARRAY_SUPPORT + : typedArraySupport() + + /* + * Export kMaxLength after typed array support is determined. + */ + exports.kMaxLength = kMaxLength() + + function typedArraySupport () { + try { + var arr = new Uint8Array(1) + arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }} + return arr.foo() === 42 && // typed array instances can be augmented + typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray` + arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray` + } catch (e) { + return false + } + } + + function kMaxLength () { + return Buffer.TYPED_ARRAY_SUPPORT + ? 0x7fffffff + : 0x3fffffff + } + + function createBuffer (that, length) { + if (kMaxLength() < length) { + throw new RangeError('Invalid typed array length') + } + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = new Uint8Array(length) + that.__proto__ = Buffer.prototype + } else { + // Fallback: Return an object instance of the Buffer class + if (that === null) { + that = new Buffer(length) + } + that.length = length + } + + return that + } + + /** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + + function Buffer (arg, encodingOrOffset, length) { + if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { + return new Buffer(arg, encodingOrOffset, length) + } + + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new Error( + 'If encoding is specified then the first argument must be a string' + ) + } + return allocUnsafe(this, arg) + } + return from(this, arg, encodingOrOffset, length) + } + + Buffer.poolSize = 8192 // not used by this implementation + + // TODO: Legacy, not needed anymore. Remove in next major version. + Buffer._augment = function (arr) { + arr.__proto__ = Buffer.prototype + return arr + } + + function from (that, value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } + + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + return fromArrayBuffer(that, value, encodingOrOffset, length) + } + + if (typeof value === 'string') { + return fromString(that, value, encodingOrOffset) + } + + return fromObject(that, value) + } + + /** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ + Buffer.from = function (value, encodingOrOffset, length) { + return from(null, value, encodingOrOffset, length) + } + + if (Buffer.TYPED_ARRAY_SUPPORT) { + Buffer.prototype.__proto__ = Uint8Array.prototype + Buffer.__proto__ = Uint8Array + if (typeof Symbol !== 'undefined' && Symbol.species && + Buffer[Symbol.species] === Buffer) { + // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 + Object.defineProperty(Buffer, Symbol.species, { + value: null, + configurable: true + }) + } + } + + function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be a number') + } else if (size < 0) { + throw new RangeError('"size" argument must not be negative') + } + } + + function alloc (that, size, fill, encoding) { + assertSize(size) + if (size <= 0) { + return createBuffer(that, size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(that, size).fill(fill, encoding) + : createBuffer(that, size).fill(fill) + } + return createBuffer(that, size) + } + + /** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ + Buffer.alloc = function (size, fill, encoding) { + return alloc(null, size, fill, encoding) + } + + function allocUnsafe (that, size) { + assertSize(size) + that = createBuffer(that, size < 0 ? 0 : checked(size) | 0) + if (!Buffer.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < size; ++i) { + that[i] = 0 + } + } + return that + } + + /** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ + Buffer.allocUnsafe = function (size) { + return allocUnsafe(null, size) + } + /** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ + Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(null, size) + } + + function fromString (that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8' + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') + } + + var length = byteLength(string, encoding) | 0 + that = createBuffer(that, length) + + var actual = that.write(string, encoding) + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + that = that.slice(0, actual) + } + + return that + } + + function fromArrayLike (that, array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0 + that = createBuffer(that, length) + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255 + } + return that + } + + function fromArrayBuffer (that, array, byteOffset, length) { + array.byteLength // this throws if `array` is not a valid ArrayBuffer + + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('\'offset\' is out of bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('\'length\' is out of bounds') + } + + if (byteOffset === undefined && length === undefined) { + array = new Uint8Array(array) + } else if (length === undefined) { + array = new Uint8Array(array, byteOffset) + } else { + array = new Uint8Array(array, byteOffset, length) + } + + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = array + that.__proto__ = Buffer.prototype + } else { + // Fallback: Return an object instance of the Buffer class + that = fromArrayLike(that, array) + } + return that + } + + function fromObject (that, obj) { + if (Buffer.isBuffer(obj)) { + var len = checked(obj.length) | 0 + that = createBuffer(that, len) + + if (that.length === 0) { + return that + } + + obj.copy(that, 0, 0, len) + return that + } + + if (obj) { + if ((typeof ArrayBuffer !== 'undefined' && + obj.buffer instanceof ArrayBuffer) || 'length' in obj) { + if (typeof obj.length !== 'number' || isnan(obj.length)) { + return createBuffer(that, 0) + } + return fromArrayLike(that, obj) + } + + if (obj.type === 'Buffer' && isArray(obj.data)) { + return fromArrayLike(that, obj.data) + } + } + + throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') + } + + function checked (length) { + // Note: cannot use `length < kMaxLength()` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= kMaxLength()) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + kMaxLength().toString(16) + ' bytes') + } + return length | 0 + } + + function SlowBuffer (length) { + if (+length != length) { // eslint-disable-line eqeqeq + length = 0 + } + return Buffer.alloc(+length) + } + + Buffer.isBuffer = function isBuffer (b) { + return !!(b != null && b._isBuffer) + } + + Buffer.compare = function compare (a, b) { + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + throw new TypeError('Arguments must be Buffers') + } + + if (a === b) return 0 + + var x = a.length + var y = b.length + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i] + y = b[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 + } + + Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } + } + + Buffer.concat = function concat (list, length) { + if (!isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + var i + if (length === undefined) { + length = 0 + for (i = 0; i < list.length; ++i) { + length += list[i].length + } + } + + var buffer = Buffer.allocUnsafe(length) + var pos = 0 + for (i = 0; i < list.length; ++i) { + var buf = list[i] + if (!Buffer.isBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos) + pos += buf.length + } + return buffer + } + + function byteLength (string, encoding) { + if (Buffer.isBuffer(string)) { + return string.length + } + if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && + (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + string = '' + string + } + + var len = string.length + if (len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + case undefined: + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) return utf8ToBytes(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } + } + Buffer.byteLength = byteLength + + function slowToString (encoding, start, end) { + var loweredCase = false + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0 + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length + } + + if (end <= 0) { + return '' + } + + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0 + start >>>= 0 + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8' + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase() + loweredCase = true + } + } + } + + // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect + // Buffer instances. + Buffer.prototype._isBuffer = true + + function swap (b, n, m) { + var i = b[n] + b[n] = b[m] + b[m] = i + } + + Buffer.prototype.swap16 = function swap16 () { + var len = this.length + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1) + } + return this + } + + Buffer.prototype.swap32 = function swap32 () { + var len = this.length + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3) + swap(this, i + 1, i + 2) + } + return this + } + + Buffer.prototype.swap64 = function swap64 () { + var len = this.length + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7) + swap(this, i + 1, i + 6) + swap(this, i + 2, i + 5) + swap(this, i + 3, i + 4) + } + return this + } + + Buffer.prototype.toString = function toString () { + var length = this.length | 0 + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) + } + + Buffer.prototype.equals = function equals (b) { + if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 + } + + Buffer.prototype.inspect = function inspect () { + var str = '' + var max = exports.INSPECT_MAX_BYTES + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') + if (this.length > max) str += ' ... ' + } + return '' + } + + Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (!Buffer.isBuffer(target)) { + throw new TypeError('Argument must be a Buffer') + } + + if (start === undefined) { + start = 0 + } + if (end === undefined) { + end = target ? target.length : 0 + } + if (thisStart === undefined) { + thisStart = 0 + } + if (thisEnd === undefined) { + thisEnd = this.length + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0 + end >>>= 0 + thisStart >>>= 0 + thisEnd >>>= 0 + + if (this === target) return 0 + + var x = thisEnd - thisStart + var y = end - start + var len = Math.min(x, y) + + var thisCopy = this.slice(thisStart, thisEnd) + var targetCopy = target.slice(start, end) + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i] + y = targetCopy[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 + } + + // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, + // OR the last index of `val` in `buffer` at offset <= `byteOffset`. + // + // Arguments: + // - buffer - a Buffer to search + // - val - a string, Buffer, or number + // - byteOffset - an index into `buffer`; will be clamped to an int32 + // - encoding - an optional encoding, relevant is val is a string + // - dir - true for indexOf, false for lastIndexOf + function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset + byteOffset = 0 + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000 + } + byteOffset = +byteOffset // Coerce to Number. + if (isNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1) + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1 + } else if (byteOffset < 0) { + if (dir) byteOffset = 0 + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding) + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (Buffer.isBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF // Search for a byte value [0-255] + if (Buffer.TYPED_ARRAY_SUPPORT && + typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') + } + + function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1 + var arrLength = arr.length + var valLength = val.length + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase() + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2 + arrLength /= 2 + valLength /= 2 + byteOffset /= 2 + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + var i + if (dir) { + var foundIndex = -1 + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex + foundIndex = -1 + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength + for (i = byteOffset; i >= 0; i--) { + var found = true + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false + break + } + } + if (found) return i + } + } + + return -1 + } + + Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 + } + + Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) + } + + Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) + } + + function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0 + var remaining = buf.length - offset + if (!length) { + length = remaining + } else { + length = Number(length) + if (length > remaining) { + length = remaining + } + } + + // must be an even number of digits + var strLen = string.length + if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') + + if (length > strLen / 2) { + length = strLen / 2 + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16) + if (isNaN(parsed)) return i + buf[offset + i] = parsed + } + return i + } + + function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) + } + + function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) + } + + function latin1Write (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) + } + + function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) + } + + function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) + } + + Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8' + length = this.length + offset = 0 + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset + length = this.length + offset = 0 + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset | 0 + if (isFinite(length)) { + length = length | 0 + if (encoding === undefined) encoding = 'utf8' + } else { + encoding = length + length = undefined + } + // legacy write(string, encoding, offset, length) - remove in v0.13 + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + var remaining = this.length - offset + if (length === undefined || length > remaining) length = remaining + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8' + + var loweredCase = false + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + return asciiWrite(this, string, offset, length) + + case 'latin1': + case 'binary': + return latin1Write(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } + } + + Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } + } + + function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return base64.fromByteArray(buf) + } else { + return base64.fromByteArray(buf.slice(start, end)) + } + } + + function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end) + var res = [] + + var i = start + while (i < end) { + var firstByte = buf[i] + var codePoint = null + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1 + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte + } + break + case 2: + secondByte = buf[i + 1] + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint + } + } + break + case 3: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint + } + } + break + case 4: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + fourthByte = buf[i + 3] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD + bytesPerSequence = 1 + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000 + res.push(codePoint >>> 10 & 0x3FF | 0xD800) + codePoint = 0xDC00 | codePoint & 0x3FF + } + + res.push(codePoint) + i += bytesPerSequence + } + + return decodeCodePointsArray(res) + } + + // Based on http://stackoverflow.com/a/22747272/680742, the browser with + // the lowest limit is Chrome, with 0x10000 args. + // We go 1 magnitude less, for safety + var MAX_ARGUMENTS_LENGTH = 0x1000 + + function decodeCodePointsArray (codePoints) { + var len = codePoints.length + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + var res = '' + var i = 0 + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ) + } + return res + } + + function asciiSlice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F) + } + return ret + } + + function latin1Slice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]) + } + return ret + } + + function hexSlice (buf, start, end) { + var len = buf.length + + if (!start || start < 0) start = 0 + if (!end || end < 0 || end > len) end = len + + var out = '' + for (var i = start; i < end; ++i) { + out += toHex(buf[i]) + } + return out + } + + function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end) + var res = '' + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256) + } + return res + } + + Buffer.prototype.slice = function slice (start, end) { + var len = this.length + start = ~~start + end = end === undefined ? len : ~~end + + if (start < 0) { + start += len + if (start < 0) start = 0 + } else if (start > len) { + start = len + } + + if (end < 0) { + end += len + if (end < 0) end = 0 + } else if (end > len) { + end = len + } + + if (end < start) end = start + + var newBuf + if (Buffer.TYPED_ARRAY_SUPPORT) { + newBuf = this.subarray(start, end) + newBuf.__proto__ = Buffer.prototype + } else { + var sliceLen = end - start + newBuf = new Buffer(sliceLen, undefined) + for (var i = 0; i < sliceLen; ++i) { + newBuf[i] = this[i + start] + } + } + + return newBuf + } + + /* + * Need to make sure that buffer isn't trying to write out of bounds. + */ + function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') + } + + Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + + return val + } + + Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) { + checkOffset(offset, byteLength, this.length) + } + + var val = this[offset + --byteLength] + var mul = 1 + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul + } + + return val + } + + Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length) + return this[offset] + } + + Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + return this[offset] | (this[offset + 1] << 8) + } + + Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + return (this[offset] << 8) | this[offset + 1] + } + + Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) + } + + Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) + } + + Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val + } + + Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var i = byteLength + var mul = 1 + var val = this[offset + --i] + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val + } + + Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length) + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) + } + + Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset] | (this[offset + 1] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val + } + + Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset + 1] | (this[offset] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val + } + + Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) + } + + Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) + } + + Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, true, 23, 4) + } + + Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, false, 23, 4) + } + + Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, true, 52, 8) + } + + Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, false, 52, 8) + } + + function checkInt (buf, value, offset, ext, max, min) { + if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') + } + + Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + var mul = 1 + var i = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength + } + + Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + var i = byteLength - 1 + var mul = 1 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength + } + + Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) + this[offset] = (value & 0xff) + return offset + 1 + } + + function objectWriteUInt16 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffff + value + 1 + for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { + buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> + (littleEndian ? i : 1 - i) * 8 + } + } + + Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + } else { + objectWriteUInt16(this, value, offset, true) + } + return offset + 2 + } + + Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + } else { + objectWriteUInt16(this, value, offset, false) + } + return offset + 2 + } + + function objectWriteUInt32 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffffffff + value + 1 + for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { + buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff + } + } + + Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset + 3] = (value >>> 24) + this[offset + 2] = (value >>> 16) + this[offset + 1] = (value >>> 8) + this[offset] = (value & 0xff) + } else { + objectWriteUInt32(this, value, offset, true) + } + return offset + 4 + } + + Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + } else { + objectWriteUInt32(this, value, offset, false) + } + return offset + 4 + } + + Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = 0 + var mul = 1 + var sub = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength + } + + Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = byteLength - 1 + var mul = 1 + var sub = 0 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength + } + + Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) + if (value < 0) value = 0xff + value + 1 + this[offset] = (value & 0xff) + return offset + 1 + } + + Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + } else { + objectWriteUInt16(this, value, offset, true) + } + return offset + 2 + } + + Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + } else { + objectWriteUInt16(this, value, offset, false) + } + return offset + 2 + } + + Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + this[offset + 2] = (value >>> 16) + this[offset + 3] = (value >>> 24) + } else { + objectWriteUInt32(this, value, offset, true) + } + return offset + 4 + } + + Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (value < 0) value = 0xffffffff + value + 1 + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + } else { + objectWriteUInt32(this, value, offset, false) + } + return offset + 4 + } + + function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') + } + + function writeFloat (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) + } + ieee754.write(buf, value, offset, littleEndian, 23, 4) + return offset + 4 + } + + Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) + } + + Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) + } + + function writeDouble (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) + } + ieee754.write(buf, value, offset, littleEndian, 52, 8) + return offset + 8 + } + + Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) + } + + Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) + } + + // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) + Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!start) start = 0 + if (!end && end !== 0) end = this.length + if (targetStart >= target.length) targetStart = target.length + if (!targetStart) targetStart = 0 + if (end > 0 && end < start) end = start + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start + } + + var len = end - start + var i + + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start] + } + } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { + // ascending copy from start + for (i = 0; i < len; ++i) { + target[i + targetStart] = this[i + start] + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, start + len), + targetStart + ) + } + + return len + } + + // Usage: + // buffer.fill(number[, offset[, end]]) + // buffer.fill(buffer[, offset[, end]]) + // buffer.fill(string[, offset[, end]][, encoding]) + Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start + start = 0 + end = this.length + } else if (typeof end === 'string') { + encoding = end + end = this.length + } + if (val.length === 1) { + var code = val.charCodeAt(0) + if (code < 256) { + val = code + } + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + } else if (typeof val === 'number') { + val = val & 255 + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0 + end = end === undefined ? this.length : end >>> 0 + + if (!val) val = 0 + + var i + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val + } + } else { + var bytes = Buffer.isBuffer(val) + ? val + : utf8ToBytes(new Buffer(val, encoding).toString()) + var len = bytes.length + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len] + } + } + + return this + } + + // HELPER FUNCTIONS + // ================ + + var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g + + function base64clean (str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = stringtrim(str).replace(INVALID_BASE64_RE, '') + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '=' + } + return str + } + + function stringtrim (str) { + if (str.trim) return str.trim() + return str.replace(/^\s+|\s+$/g, '') + } + + function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) + } + + function utf8ToBytes (string, units) { + units = units || Infinity + var codePoint + var length = string.length + var leadSurrogate = null + var bytes = [] + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i) + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } + + // valid lead + leadSurrogate = codePoint + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + leadSurrogate = codePoint + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + } + + leadSurrogate = null + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint) + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else { + throw new Error('Invalid code point') + } + } + + return bytes + } + + function asciiToBytes (str) { + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF) + } + return byteArray + } + + function utf16leToBytes (str, units) { + var c, hi, lo + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i) + hi = c >> 8 + lo = c % 256 + byteArray.push(lo) + byteArray.push(hi) + } + + return byteArray + } + + function base64ToBytes (str) { + return base64.toByteArray(base64clean(str)) + } + + function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i] + } + return i + } + + function isnan (val) { + return val !== val // eslint-disable-line no-self-compare + } + + /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) + +/***/ }), +/* 335 */ +/***/ (function(module, exports) { + + 'use strict' + + exports.byteLength = byteLength + exports.toByteArray = toByteArray + exports.fromByteArray = fromByteArray + + var lookup = [] + var revLookup = [] + var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array + + var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' + for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i] + revLookup[code.charCodeAt(i)] = i + } + + // Support decoding URL-safe base64 strings, as Node.js does. + // See: https://en.wikipedia.org/wiki/Base64#URL_applications + revLookup['-'.charCodeAt(0)] = 62 + revLookup['_'.charCodeAt(0)] = 63 + + function getLens (b64) { + var len = b64.length + + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // Trim off extra bytes after placeholder bytes are found + // See: https://github.com/beatgammit/base64-js/issues/42 + var validLen = b64.indexOf('=') + if (validLen === -1) validLen = len + + var placeHoldersLen = validLen === len + ? 0 + : 4 - (validLen % 4) + + return [validLen, placeHoldersLen] + } + + // base64 is 4/3 + up to two characters of the original data + function byteLength (b64) { + var lens = getLens(b64) + var validLen = lens[0] + var placeHoldersLen = lens[1] + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen + } + + function _byteLength (b64, validLen, placeHoldersLen) { + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen + } + + function toByteArray (b64) { + var tmp + var lens = getLens(b64) + var validLen = lens[0] + var placeHoldersLen = lens[1] + + var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)) + + var curByte = 0 + + // if there are placeholders, only get up to the last complete 4 chars + var len = placeHoldersLen > 0 + ? validLen - 4 + : validLen + + for (var i = 0; i < len; i += 4) { + tmp = + (revLookup[b64.charCodeAt(i)] << 18) | + (revLookup[b64.charCodeAt(i + 1)] << 12) | + (revLookup[b64.charCodeAt(i + 2)] << 6) | + revLookup[b64.charCodeAt(i + 3)] + arr[curByte++] = (tmp >> 16) & 0xFF + arr[curByte++] = (tmp >> 8) & 0xFF + arr[curByte++] = tmp & 0xFF + } + + if (placeHoldersLen === 2) { + tmp = + (revLookup[b64.charCodeAt(i)] << 2) | + (revLookup[b64.charCodeAt(i + 1)] >> 4) + arr[curByte++] = tmp & 0xFF + } + + if (placeHoldersLen === 1) { + tmp = + (revLookup[b64.charCodeAt(i)] << 10) | + (revLookup[b64.charCodeAt(i + 1)] << 4) | + (revLookup[b64.charCodeAt(i + 2)] >> 2) + arr[curByte++] = (tmp >> 8) & 0xFF + arr[curByte++] = tmp & 0xFF + } + + return arr + } + + function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + + lookup[num >> 12 & 0x3F] + + lookup[num >> 6 & 0x3F] + + lookup[num & 0x3F] + } + + function encodeChunk (uint8, start, end) { + var tmp + var output = [] + for (var i = start; i < end; i += 3) { + tmp = + ((uint8[i] << 16) & 0xFF0000) + + ((uint8[i + 1] << 8) & 0xFF00) + + (uint8[i + 2] & 0xFF) + output.push(tripletToBase64(tmp)) + } + return output.join('') + } + + function fromByteArray (uint8) { + var tmp + var len = uint8.length + var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes + var parts = [] + var maxChunkLength = 16383 // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk( + uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength) + )) + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1] + parts.push( + lookup[tmp >> 2] + + lookup[(tmp << 4) & 0x3F] + + '==' + ) + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + uint8[len - 1] + parts.push( + lookup[tmp >> 10] + + lookup[(tmp >> 4) & 0x3F] + + lookup[(tmp << 2) & 0x3F] + + '=' + ) + } + + return parts.join('') + } + + +/***/ }), +/* 336 */ +/***/ (function(module, exports) { + + exports.read = function (buffer, offset, isLE, mLen, nBytes) { + var e, m + var eLen = (nBytes * 8) - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var nBits = -7 + var i = isLE ? (nBytes - 1) : 0 + var d = isLE ? -1 : 1 + var s = buffer[offset + i] + + i += d + + e = s & ((1 << (-nBits)) - 1) + s >>= (-nBits) + nBits += eLen + for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1) + e >>= (-nBits) + nBits += mLen + for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen) + e = e - eBias + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) + } + + exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c + var eLen = (nBytes * 8) - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) + var i = isLE ? 0 : (nBytes - 1) + var d = isLE ? 1 : -1 + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 + + value = Math.abs(value) + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0 + e = eMax + } else { + e = Math.floor(Math.log(value) / Math.LN2) + if (value * (c = Math.pow(2, -e)) < 1) { + e-- + c *= 2 + } + if (e + eBias >= 1) { + value += rt / c + } else { + value += rt * Math.pow(2, 1 - eBias) + } + if (value * c >= 2) { + e++ + c /= 2 + } + + if (e + eBias >= eMax) { + m = 0 + e = eMax + } else if (e + eBias >= 1) { + m = ((value * c) - 1) * Math.pow(2, mLen) + e = e + eBias + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) + e = 0 + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m + eLen += mLen + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128 + } + + +/***/ }), +/* 337 */ +/***/ (function(module, exports) { + + var toString = {}.toString; + + module.exports = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; + }; + + +/***/ }), +/* 338 */ +/***/ (function(module, exports) { + + // shim for using process in browser + var process = module.exports = {}; + + // cached from whatever global is present so that test runners that stub it + // don't break things. But we need to wrap it in a try catch in case it is + // wrapped in strict mode code which doesn't define any globals. It's inside a + // function because try/catches deoptimize in certain engines. + + var cachedSetTimeout; + var cachedClearTimeout; + + function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); + } + function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); + } + (function () { + try { + if (typeof setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } else { + cachedSetTimeout = defaultSetTimout; + } + } catch (e) { + cachedSetTimeout = defaultSetTimout; + } + try { + if (typeof clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; + } + } catch (e) { + cachedClearTimeout = defaultClearTimeout; + } + } ()) + function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + + } + function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + + } + var queue = []; + var draining = false; + var currentQueue; + var queueIndex = -1; + + function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } + } + + function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); + } + + process.nextTick = function (fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } + }; + + // v8 likes predictible objects + function Item(fun, array) { + this.fun = fun; + this.array = array; + } + Item.prototype.run = function () { + this.fun.apply(null, this.array); + }; + process.title = 'browser'; + process.browser = true; + process.env = {}; + process.argv = []; + process.version = ''; // empty string to avoid regexp issues + process.versions = {}; + + function noop() {} + + process.on = noop; + process.addListener = noop; + process.once = noop; + process.off = noop; + process.removeListener = noop; + process.removeAllListeners = noop; + process.emit = noop; + process.prependListener = noop; + process.prependOnceListener = noop; + + process.listeners = function (name) { return [] } + + process.binding = function (name) { + throw new Error('process.binding is not supported'); + }; + + process.cwd = function () { return '/' }; + process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); + }; + process.umask = function() { return 0; }; + + +/***/ }), +/* 339 */ +/***/ (function(module, exports, __webpack_require__) { + + /* WEBPACK VAR INJECTION */(function(Buffer) {'use strict'; + + /** + * Normalizes our expected stringified form of a function across versions of node + * @param {Function} fn The function to stringify + */ + + function normalizedFunctionString(fn) { + return fn.toString().replace(/function *\(/, 'function ('); + } + + function newBuffer(item, encoding) { + return new Buffer(item, encoding); + } + + function allocBuffer() { + return Buffer.alloc.apply(Buffer, arguments); + } + + function toBuffer() { + return Buffer.from.apply(Buffer, arguments); + } + + module.exports = { + normalizedFunctionString: normalizedFunctionString, + allocBuffer: typeof Buffer.alloc === 'function' ? allocBuffer : newBuffer, + toBuffer: typeof Buffer.from === 'function' ? toBuffer : newBuffer + }; + /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(334).Buffer)) + +/***/ }), +/* 340 */ +/***/ (function(module, exports, __webpack_require__) { + + /* WEBPACK VAR INJECTION */(function(global, process) {// Copyright Joyent, Inc. and other Node contributors. + // + // Permission is hereby granted, free of charge, to any person obtaining a + // copy of this software and associated documentation files (the + // "Software"), to deal in the Software without restriction, including + // without limitation the rights to use, copy, modify, merge, publish, + // distribute, sublicense, and/or sell copies of the Software, and to permit + // persons to whom the Software is furnished to do so, subject to the + // following conditions: + // + // The above copyright notice and this permission notice shall be included + // in all copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + // USE OR OTHER DEALINGS IN THE SOFTWARE. + + var formatRegExp = /%[sdj%]/g; + exports.format = function(f) { + if (!isString(f)) { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); + } + return objects.join(' '); + } + + var i = 1; + var args = arguments; + var len = args.length; + var str = String(f).replace(formatRegExp, function(x) { + if (x === '%%') return '%'; + if (i >= len) return x; + switch (x) { + case '%s': return String(args[i++]); + case '%d': return Number(args[i++]); + case '%j': + try { + return JSON.stringify(args[i++]); + } catch (_) { + return '[Circular]'; + } + default: + return x; + } + }); + for (var x = args[i]; i < len; x = args[++i]) { + if (isNull(x) || !isObject(x)) { + str += ' ' + x; + } else { + str += ' ' + inspect(x); + } + } + return str; + }; + + + // Mark that a method should not be used. + // Returns a modified function which warns once by default. + // If --no-deprecation is set, then it is a no-op. + exports.deprecate = function(fn, msg) { + // Allow for deprecating things in the process of starting up. + if (isUndefined(global.process)) { + return function() { + return exports.deprecate(fn, msg).apply(this, arguments); + }; + } + + if (process.noDeprecation === true) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (process.throwDeprecation) { + throw new Error(msg); + } else if (process.traceDeprecation) { + console.trace(msg); + } else { + console.error(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; + }; + + + var debugs = {}; + var debugEnviron; + exports.debuglog = function(set) { + if (isUndefined(debugEnviron)) + debugEnviron = process.env.NODE_DEBUG || ''; + set = set.toUpperCase(); + if (!debugs[set]) { + if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { + var pid = process.pid; + debugs[set] = function() { + var msg = exports.format.apply(exports, arguments); + console.error('%s %d: %s', set, pid, msg); + }; + } else { + debugs[set] = function() {}; + } + } + return debugs[set]; + }; + + + /** + * Echos the value of a value. Trys to print the value out + * in the best way possible given the different types. + * + * @param {Object} obj The object to print out. + * @param {Object} opts Optional options object that alters the output. + */ + /* legacy: obj, showHidden, depth, colors*/ + function inspect(obj, opts) { + // default options + var ctx = { + seen: [], + stylize: stylizeNoColor + }; + // legacy... + if (arguments.length >= 3) ctx.depth = arguments[2]; + if (arguments.length >= 4) ctx.colors = arguments[3]; + if (isBoolean(opts)) { + // legacy... + ctx.showHidden = opts; + } else if (opts) { + // got an "options" object + exports._extend(ctx, opts); + } + // set default options + if (isUndefined(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined(ctx.depth)) ctx.depth = 2; + if (isUndefined(ctx.colors)) ctx.colors = false; + if (isUndefined(ctx.customInspect)) ctx.customInspect = true; + if (ctx.colors) ctx.stylize = stylizeWithColor; + return formatValue(ctx, obj, ctx.depth); + } + exports.inspect = inspect; + + + // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics + inspect.colors = { + 'bold' : [1, 22], + 'italic' : [3, 23], + 'underline' : [4, 24], + 'inverse' : [7, 27], + 'white' : [37, 39], + 'grey' : [90, 39], + 'black' : [30, 39], + 'blue' : [34, 39], + 'cyan' : [36, 39], + 'green' : [32, 39], + 'magenta' : [35, 39], + 'red' : [31, 39], + 'yellow' : [33, 39] + }; + + // Don't use 'blue' not visible on cmd.exe + inspect.styles = { + 'special': 'cyan', + 'number': 'yellow', + 'boolean': 'yellow', + 'undefined': 'grey', + 'null': 'bold', + 'string': 'green', + 'date': 'magenta', + // "name": intentionally not styling + 'regexp': 'red' + }; + + + function stylizeWithColor(str, styleType) { + var style = inspect.styles[styleType]; + + if (style) { + return '\u001b[' + inspect.colors[style][0] + 'm' + str + + '\u001b[' + inspect.colors[style][1] + 'm'; + } else { + return str; + } + } + + + function stylizeNoColor(str, styleType) { + return str; + } + + + function arrayToHash(array) { + var hash = {}; + + array.forEach(function(val, idx) { + hash[val] = true; + }); + + return hash; + } + + + function formatValue(ctx, value, recurseTimes) { + // Provide a hook for user-specified inspect functions. + // Check that value is an object with an inspect function on it + if (ctx.customInspect && + value && + isFunction(value.inspect) && + // Filter out the util module, it's inspect function is special + value.inspect !== exports.inspect && + // Also filter out any prototype objects using the circular check. + !(value.constructor && value.constructor.prototype === value)) { + var ret = value.inspect(recurseTimes, ctx); + if (!isString(ret)) { + ret = formatValue(ctx, ret, recurseTimes); + } + return ret; + } + + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } + + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); + + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } + + // IE doesn't make error fields non-enumerable + // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx + if (isError(value) + && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { + return formatError(value); + } + + // Some type of object without properties can be shortcutted. + if (keys.length === 0) { + if (isFunction(value)) { + var name = value.name ? ': ' + value.name : ''; + return ctx.stylize('[Function' + name + ']', 'special'); + } + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } + if (isDate(value)) { + return ctx.stylize(Date.prototype.toString.call(value), 'date'); + } + if (isError(value)) { + return formatError(value); + } + } + + var base = '', array = false, braces = ['{', '}']; + + // Make Array say that they are Array + if (isArray(value)) { + array = true; + braces = ['[', ']']; + } + + // Make functions say that they are functions + if (isFunction(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; + } + + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } + + // Make dates with properties first say the date + if (isDate(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); + } + + // Make error with message first say the error + if (isError(value)) { + base = ' ' + formatError(value); + } + + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } + + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); + } + } + + ctx.seen.push(value); + + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + } else { + output = keys.map(function(key) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); + }); + } + + ctx.seen.pop(); + + return reduceToSingleString(output, base, braces); + } + + + function formatPrimitive(ctx, value) { + if (isUndefined(value)) + return ctx.stylize('undefined', 'undefined'); + if (isString(value)) { + var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + '\''; + return ctx.stylize(simple, 'string'); + } + if (isNumber(value)) + return ctx.stylize('' + value, 'number'); + if (isBoolean(value)) + return ctx.stylize('' + value, 'boolean'); + // For some reason typeof null is "object", so special case here. + if (isNull(value)) + return ctx.stylize('null', 'null'); + } + + + function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; + } + + + function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { + var output = []; + for (var i = 0, l = value.length; i < l; ++i) { + if (hasOwnProperty(value, String(i))) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + String(i), true)); + } else { + output.push(''); + } + } + keys.forEach(function(key) { + if (!key.match(/^\d+$/)) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + key, true)); + } + }); + return output; + } + + + function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { + var name, str, desc; + desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; + if (desc.get) { + if (desc.set) { + str = ctx.stylize('[Getter/Setter]', 'special'); + } else { + str = ctx.stylize('[Getter]', 'special'); + } + } else { + if (desc.set) { + str = ctx.stylize('[Setter]', 'special'); + } + } + if (!hasOwnProperty(visibleKeys, key)) { + name = '[' + key + ']'; + } + if (!str) { + if (ctx.seen.indexOf(desc.value) < 0) { + if (isNull(recurseTimes)) { + str = formatValue(ctx, desc.value, null); + } else { + str = formatValue(ctx, desc.value, recurseTimes - 1); + } + if (str.indexOf('\n') > -1) { + if (array) { + str = str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n').substr(2); + } else { + str = '\n' + str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n'); + } + } + } else { + str = ctx.stylize('[Circular]', 'special'); + } + } + if (isUndefined(name)) { + if (array && key.match(/^\d+$/)) { + return str; + } + name = JSON.stringify('' + key); + if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { + name = name.substr(1, name.length - 2); + name = ctx.stylize(name, 'name'); + } else { + name = name.replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'"); + name = ctx.stylize(name, 'string'); + } + } + + return name + ': ' + str; + } + + + function reduceToSingleString(output, base, braces) { + var numLinesEst = 0; + var length = output.reduce(function(prev, cur) { + numLinesEst++; + if (cur.indexOf('\n') >= 0) numLinesEst++; + return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; + }, 0); + + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; + } + + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; + } + + + // NOTE: These type checking functions intentionally don't use `instanceof` + // because it is fragile and can be easily faked with `Object.create()`. + function isArray(ar) { + return Array.isArray(ar); + } + exports.isArray = isArray; + + function isBoolean(arg) { + return typeof arg === 'boolean'; + } + exports.isBoolean = isBoolean; + + function isNull(arg) { + return arg === null; + } + exports.isNull = isNull; + + function isNullOrUndefined(arg) { + return arg == null; + } + exports.isNullOrUndefined = isNullOrUndefined; + + function isNumber(arg) { + return typeof arg === 'number'; + } + exports.isNumber = isNumber; + + function isString(arg) { + return typeof arg === 'string'; + } + exports.isString = isString; + + function isSymbol(arg) { + return typeof arg === 'symbol'; + } + exports.isSymbol = isSymbol; + + function isUndefined(arg) { + return arg === void 0; + } + exports.isUndefined = isUndefined; + + function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; + } + exports.isRegExp = isRegExp; + + function isObject(arg) { + return typeof arg === 'object' && arg !== null; + } + exports.isObject = isObject; + + function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; + } + exports.isDate = isDate; + + function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); + } + exports.isError = isError; + + function isFunction(arg) { + return typeof arg === 'function'; + } + exports.isFunction = isFunction; + + function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; + } + exports.isPrimitive = isPrimitive; + + exports.isBuffer = __webpack_require__(341); + + function objectToString(o) { + return Object.prototype.toString.call(o); + } + + + function pad(n) { + return n < 10 ? '0' + n.toString(10) : n.toString(10); + } + + + var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', + 'Oct', 'Nov', 'Dec']; + + // 26 Feb 16:19:34 + function timestamp() { + var d = new Date(); + var time = [pad(d.getHours()), + pad(d.getMinutes()), + pad(d.getSeconds())].join(':'); + return [d.getDate(), months[d.getMonth()], time].join(' '); + } + + + // log is just a thin wrapper to console.log that prepends a timestamp + exports.log = function() { + console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); + }; + + + /** + * Inherit the prototype methods from one constructor into another. + * + * The Function.prototype.inherits from lang.js rewritten as a standalone + * function (not on Function.prototype). NOTE: If this file is to be loaded + * during bootstrapping this function needs to be rewritten using some native + * functions as prototype setup using normal JavaScript does not work as + * expected during bootstrapping (see mirror.js in r114903). + * + * @param {function} ctor Constructor function which needs to inherit the + * prototype. + * @param {function} superCtor Constructor function to inherit prototype from. + */ + exports.inherits = __webpack_require__(342); + + exports._extend = function(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject(add)) return origin; + + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; + } + return origin; + }; + + function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); + } + + /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()), __webpack_require__(338))) + +/***/ }), +/* 341 */ +/***/ (function(module, exports) { + + module.exports = function isBuffer(arg) { + return arg && typeof arg === 'object' + && typeof arg.copy === 'function' + && typeof arg.fill === 'function' + && typeof arg.readUInt8 === 'function'; + } + +/***/ }), +/* 342 */ +/***/ (function(module, exports) { + + if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; + } else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } + } + + +/***/ }), +/* 343 */ +/***/ (function(module, exports) { + + /** + * A class representation of the BSON RegExp type. + * + * @class + * @return {BSONRegExp} A MinKey instance + */ + function BSONRegExp(pattern, options) { + if (!(this instanceof BSONRegExp)) return new BSONRegExp(); + + // Execute + this._bsontype = 'BSONRegExp'; + this.pattern = pattern || ''; + this.options = options || ''; + + // Validate options + for (var i = 0; i < this.options.length; i++) { + if (!(this.options[i] === 'i' || this.options[i] === 'm' || this.options[i] === 'x' || this.options[i] === 'l' || this.options[i] === 's' || this.options[i] === 'u')) { + throw new Error('the regular expression options [' + this.options[i] + '] is not supported'); + } + } + } + + module.exports = BSONRegExp; + module.exports.BSONRegExp = BSONRegExp; + +/***/ }), +/* 344 */ +/***/ (function(module, exports, __webpack_require__) { + + /* WEBPACK VAR INJECTION */(function(Buffer) {// Custom inspect property name / symbol. + var inspect = Buffer ? __webpack_require__(340).inspect.custom || 'inspect' : 'inspect'; + + /** + * A class representation of the BSON Symbol type. + * + * @class + * @deprecated + * @param {string} value the string representing the symbol. + * @return {Symbol} + */ + function Symbol(value) { + if (!(this instanceof Symbol)) return new Symbol(value); + this._bsontype = 'Symbol'; + this.value = value; + } + + /** + * Access the wrapped string value. + * + * @method + * @return {String} returns the wrapped string. + */ + Symbol.prototype.valueOf = function () { + return this.value; + }; + + /** + * @ignore + */ + Symbol.prototype.toString = function () { + return this.value; + }; + + /** + * @ignore + */ + Symbol.prototype[inspect] = function () { + return this.value; + }; + + /** + * @ignore + */ + Symbol.prototype.toJSON = function () { + return this.value; + }; + + module.exports = Symbol; + module.exports.Symbol = Symbol; + /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(334).Buffer)) + +/***/ }), +/* 345 */ +/***/ (function(module, exports) { + + /** + * A class representation of a BSON Int32 type. + * + * @class + * @param {number} value the number we want to represent as an int32. + * @return {Int32} + */ + var Int32 = function (value) { + if (!(this instanceof Int32)) return new Int32(value); + + this._bsontype = 'Int32'; + this.value = value; + }; + + /** + * Access the number value. + * + * @method + * @return {number} returns the wrapped int32 number. + */ + Int32.prototype.valueOf = function () { + return this.value; + }; + + /** + * @ignore + */ + Int32.prototype.toJSON = function () { + return this.value; + }; + + module.exports = Int32; + module.exports.Int32 = Int32; + +/***/ }), +/* 346 */ +/***/ (function(module, exports) { + + /** + * A class representation of the BSON Code type. + * + * @class + * @param {(string|function)} code a string or function. + * @param {Object} [scope] an optional scope for the function. + * @return {Code} + */ + var Code = function Code(code, scope) { + if (!(this instanceof Code)) return new Code(code, scope); + this._bsontype = 'Code'; + this.code = code; + this.scope = scope; + }; + + /** + * @ignore + */ + Code.prototype.toJSON = function () { + return { scope: this.scope, code: this.code }; + }; + + module.exports = Code; + module.exports.Code = Code; + +/***/ }), +/* 347 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + + var Long = __webpack_require__(330); + + var PARSE_STRING_REGEXP = /^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/; + var PARSE_INF_REGEXP = /^(\+|-)?(Infinity|inf)$/i; + var PARSE_NAN_REGEXP = /^(\+|-)?NaN$/i; + + var EXPONENT_MAX = 6111; + var EXPONENT_MIN = -6176; + var EXPONENT_BIAS = 6176; + var MAX_DIGITS = 34; + + // Nan value bits as 32 bit values (due to lack of longs) + var NAN_BUFFER = [0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00].reverse(); + // Infinity value bits 32 bit values (due to lack of longs) + var INF_NEGATIVE_BUFFER = [0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00].reverse(); + var INF_POSITIVE_BUFFER = [0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00].reverse(); + + var EXPONENT_REGEX = /^([-+])?(\d+)?$/; + + var utils = __webpack_require__(339); + + // Detect if the value is a digit + var isDigit = function (value) { + return !isNaN(parseInt(value, 10)); + }; + + // Divide two uint128 values + var divideu128 = function (value) { + var DIVISOR = Long.fromNumber(1000 * 1000 * 1000); + var _rem = Long.fromNumber(0); + var i = 0; + + if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) { + return { quotient: value, rem: _rem }; + } + + for (i = 0; i <= 3; i++) { + // Adjust remainder to match value of next dividend + _rem = _rem.shiftLeft(32); + // Add the divided to _rem + _rem = _rem.add(new Long(value.parts[i], 0)); + value.parts[i] = _rem.div(DIVISOR).low_; + _rem = _rem.modulo(DIVISOR); + } + + return { quotient: value, rem: _rem }; + }; + + // Multiply two Long values and return the 128 bit value + var multiply64x2 = function (left, right) { + if (!left && !right) { + return { high: Long.fromNumber(0), low: Long.fromNumber(0) }; + } + + var leftHigh = left.shiftRightUnsigned(32); + var leftLow = new Long(left.getLowBits(), 0); + var rightHigh = right.shiftRightUnsigned(32); + var rightLow = new Long(right.getLowBits(), 0); + + var productHigh = leftHigh.multiply(rightHigh); + var productMid = leftHigh.multiply(rightLow); + var productMid2 = leftLow.multiply(rightHigh); + var productLow = leftLow.multiply(rightLow); + + productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); + productMid = new Long(productMid.getLowBits(), 0).add(productMid2).add(productLow.shiftRightUnsigned(32)); + + productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); + productLow = productMid.shiftLeft(32).add(new Long(productLow.getLowBits(), 0)); + + // Return the 128 bit result + return { high: productHigh, low: productLow }; + }; + + var lessThan = function (left, right) { + // Make values unsigned + var uhleft = left.high_ >>> 0; + var uhright = right.high_ >>> 0; + + // Compare high bits first + if (uhleft < uhright) { + return true; + } else if (uhleft === uhright) { + var ulleft = left.low_ >>> 0; + var ulright = right.low_ >>> 0; + if (ulleft < ulright) return true; + } + + return false; + }; + + // var longtoHex = function(value) { + // var buffer = utils.allocBuffer(8); + // var index = 0; + // // Encode the low 64 bits of the decimal + // // Encode low bits + // buffer[index++] = value.low_ & 0xff; + // buffer[index++] = (value.low_ >> 8) & 0xff; + // buffer[index++] = (value.low_ >> 16) & 0xff; + // buffer[index++] = (value.low_ >> 24) & 0xff; + // // Encode high bits + // buffer[index++] = value.high_ & 0xff; + // buffer[index++] = (value.high_ >> 8) & 0xff; + // buffer[index++] = (value.high_ >> 16) & 0xff; + // buffer[index++] = (value.high_ >> 24) & 0xff; + // return buffer.reverse().toString('hex'); + // }; + + // var int32toHex = function(value) { + // var buffer = utils.allocBuffer(4); + // var index = 0; + // // Encode the low 64 bits of the decimal + // // Encode low bits + // buffer[index++] = value & 0xff; + // buffer[index++] = (value >> 8) & 0xff; + // buffer[index++] = (value >> 16) & 0xff; + // buffer[index++] = (value >> 24) & 0xff; + // return buffer.reverse().toString('hex'); + // }; + + /** + * A class representation of the BSON Decimal128 type. + * + * @class + * @param {Buffer} bytes a buffer containing the raw Decimal128 bytes. + * @return {Double} + */ + var Decimal128 = function (bytes) { + this._bsontype = 'Decimal128'; + this.bytes = bytes; + }; + + /** + * Create a Decimal128 instance from a string representation + * + * @method + * @param {string} string a numeric string representation. + * @return {Decimal128} returns a Decimal128 instance. + */ + Decimal128.fromString = function (string) { + // Parse state tracking + var isNegative = false; + var sawRadix = false; + var foundNonZero = false; + + // Total number of significant digits (no leading or trailing zero) + var significantDigits = 0; + // Total number of significand digits read + var nDigitsRead = 0; + // Total number of digits (no leading zeros) + var nDigits = 0; + // The number of the digits after radix + var radixPosition = 0; + // The index of the first non-zero in *str* + var firstNonZero = 0; + + // Digits Array + var digits = [0]; + // The number of digits in digits + var nDigitsStored = 0; + // Insertion pointer for digits + var digitsInsert = 0; + // The index of the first non-zero digit + var firstDigit = 0; + // The index of the last digit + var lastDigit = 0; + + // Exponent + var exponent = 0; + // loop index over array + var i = 0; + // The high 17 digits of the significand + var significandHigh = [0, 0]; + // The low 17 digits of the significand + var significandLow = [0, 0]; + // The biased exponent + var biasedExponent = 0; + + // Read index + var index = 0; + + // Trim the string + string = string.trim(); + + // Naively prevent against REDOS attacks. + // TODO: implementing a custom parsing for this, or refactoring the regex would yield + // further gains. + if (string.length >= 7000) { + throw new Error('' + string + ' not a valid Decimal128 string'); + } + + // Results + var stringMatch = string.match(PARSE_STRING_REGEXP); + var infMatch = string.match(PARSE_INF_REGEXP); + var nanMatch = string.match(PARSE_NAN_REGEXP); + + // Validate the string + if (!stringMatch && !infMatch && !nanMatch || string.length === 0) { + throw new Error('' + string + ' not a valid Decimal128 string'); + } + + // Check if we have an illegal exponent format + if (stringMatch && stringMatch[4] && stringMatch[2] === undefined) { + throw new Error('' + string + ' not a valid Decimal128 string'); + } + + // Get the negative or positive sign + if (string[index] === '+' || string[index] === '-') { + isNegative = string[index++] === '-'; + } + + // Check if user passed Infinity or NaN + if (!isDigit(string[index]) && string[index] !== '.') { + if (string[index] === 'i' || string[index] === 'I') { + return new Decimal128(utils.toBuffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); + } else if (string[index] === 'N') { + return new Decimal128(utils.toBuffer(NAN_BUFFER)); + } + } + + // Read all the digits + while (isDigit(string[index]) || string[index] === '.') { + if (string[index] === '.') { + if (sawRadix) { + return new Decimal128(utils.toBuffer(NAN_BUFFER)); + } + + sawRadix = true; + index = index + 1; + continue; + } + + if (nDigitsStored < 34) { + if (string[index] !== '0' || foundNonZero) { + if (!foundNonZero) { + firstNonZero = nDigitsRead; + } + + foundNonZero = true; + + // Only store 34 digits + digits[digitsInsert++] = parseInt(string[index], 10); + nDigitsStored = nDigitsStored + 1; + } + } + + if (foundNonZero) { + nDigits = nDigits + 1; + } + + if (sawRadix) { + radixPosition = radixPosition + 1; + } + + nDigitsRead = nDigitsRead + 1; + index = index + 1; + } + + if (sawRadix && !nDigitsRead) { + throw new Error('' + string + ' not a valid Decimal128 string'); + } + + // Read exponent if exists + if (string[index] === 'e' || string[index] === 'E') { + // Read exponent digits + var match = string.substr(++index).match(EXPONENT_REGEX); + + // No digits read + if (!match || !match[2]) { + return new Decimal128(utils.toBuffer(NAN_BUFFER)); + } + + // Get exponent + exponent = parseInt(match[0], 10); + + // Adjust the index + index = index + match[0].length; + } + + // Return not a number + if (string[index]) { + return new Decimal128(utils.toBuffer(NAN_BUFFER)); + } + + // Done reading input + // Find first non-zero digit in digits + firstDigit = 0; + + if (!nDigitsStored) { + firstDigit = 0; + lastDigit = 0; + digits[0] = 0; + nDigits = 1; + nDigitsStored = 1; + significantDigits = 0; + } else { + lastDigit = nDigitsStored - 1; + significantDigits = nDigits; + + if (exponent !== 0 && significantDigits !== 1) { + while (string[firstNonZero + significantDigits - 1] === '0') { + significantDigits = significantDigits - 1; + } + } + } + + // Normalization of exponent + // Correct exponent based on radix position, and shift significand as needed + // to represent user input + + // Overflow prevention + if (exponent <= radixPosition && radixPosition - exponent > 1 << 14) { + exponent = EXPONENT_MIN; + } else { + exponent = exponent - radixPosition; + } + + // Attempt to normalize the exponent + while (exponent > EXPONENT_MAX) { + // Shift exponent to significand and decrease + lastDigit = lastDigit + 1; + + if (lastDigit - firstDigit > MAX_DIGITS) { + // Check if we have a zero then just hard clamp, otherwise fail + var digitsString = digits.join(''); + if (digitsString.match(/^0+$/)) { + exponent = EXPONENT_MAX; + break; + } else { + return new Decimal128(utils.toBuffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); + } + } + + exponent = exponent - 1; + } + + while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) { + // Shift last digit + if (lastDigit === 0) { + exponent = EXPONENT_MIN; + significantDigits = 0; + break; + } + + if (nDigitsStored < nDigits) { + // adjust to match digits not stored + nDigits = nDigits - 1; + } else { + // adjust to round + lastDigit = lastDigit - 1; + } + + if (exponent < EXPONENT_MAX) { + exponent = exponent + 1; + } else { + // Check if we have a zero then just hard clamp, otherwise fail + digitsString = digits.join(''); + if (digitsString.match(/^0+$/)) { + exponent = EXPONENT_MAX; + break; + } else { + return new Decimal128(utils.toBuffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); + } + } + } + + // Round + // We've normalized the exponent, but might still need to round. + if (lastDigit - firstDigit + 1 < significantDigits && string[significantDigits] !== '0') { + var endOfString = nDigitsRead; + + // If we have seen a radix point, 'string' is 1 longer than we have + // documented with ndigits_read, so inc the position of the first nonzero + // digit and the position that digits are read to. + if (sawRadix && exponent === EXPONENT_MIN) { + firstNonZero = firstNonZero + 1; + endOfString = endOfString + 1; + } + + var roundDigit = parseInt(string[firstNonZero + lastDigit + 1], 10); + var roundBit = 0; + + if (roundDigit >= 5) { + roundBit = 1; + + if (roundDigit === 5) { + roundBit = digits[lastDigit] % 2 === 1; + + for (i = firstNonZero + lastDigit + 2; i < endOfString; i++) { + if (parseInt(string[i], 10)) { + roundBit = 1; + break; + } + } + } + } + + if (roundBit) { + var dIdx = lastDigit; + + for (; dIdx >= 0; dIdx--) { + if (++digits[dIdx] > 9) { + digits[dIdx] = 0; + + // overflowed most significant digit + if (dIdx === 0) { + if (exponent < EXPONENT_MAX) { + exponent = exponent + 1; + digits[dIdx] = 1; + } else { + return new Decimal128(utils.toBuffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); + } + } + } else { + break; + } + } + } + } + + // Encode significand + // The high 17 digits of the significand + significandHigh = Long.fromNumber(0); + // The low 17 digits of the significand + significandLow = Long.fromNumber(0); + + // read a zero + if (significantDigits === 0) { + significandHigh = Long.fromNumber(0); + significandLow = Long.fromNumber(0); + } else if (lastDigit - firstDigit < 17) { + dIdx = firstDigit; + significandLow = Long.fromNumber(digits[dIdx++]); + significandHigh = new Long(0, 0); + + for (; dIdx <= lastDigit; dIdx++) { + significandLow = significandLow.multiply(Long.fromNumber(10)); + significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); + } + } else { + dIdx = firstDigit; + significandHigh = Long.fromNumber(digits[dIdx++]); + + for (; dIdx <= lastDigit - 17; dIdx++) { + significandHigh = significandHigh.multiply(Long.fromNumber(10)); + significandHigh = significandHigh.add(Long.fromNumber(digits[dIdx])); + } + + significandLow = Long.fromNumber(digits[dIdx++]); + + for (; dIdx <= lastDigit; dIdx++) { + significandLow = significandLow.multiply(Long.fromNumber(10)); + significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); + } + } + + var significand = multiply64x2(significandHigh, Long.fromString('100000000000000000')); + + significand.low = significand.low.add(significandLow); + + if (lessThan(significand.low, significandLow)) { + significand.high = significand.high.add(Long.fromNumber(1)); + } + + // Biased exponent + biasedExponent = exponent + EXPONENT_BIAS; + var dec = { low: Long.fromNumber(0), high: Long.fromNumber(0) }; + + // Encode combination, exponent, and significand. + if (significand.high.shiftRightUnsigned(49).and(Long.fromNumber(1)).equals(Long.fromNumber)) { + // Encode '11' into bits 1 to 3 + dec.high = dec.high.or(Long.fromNumber(0x3).shiftLeft(61)); + dec.high = dec.high.or(Long.fromNumber(biasedExponent).and(Long.fromNumber(0x3fff).shiftLeft(47))); + dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x7fffffffffff))); + } else { + dec.high = dec.high.or(Long.fromNumber(biasedExponent & 0x3fff).shiftLeft(49)); + dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x1ffffffffffff))); + } + + dec.low = significand.low; + + // Encode sign + if (isNegative) { + dec.high = dec.high.or(Long.fromString('9223372036854775808')); + } + + // Encode into a buffer + var buffer = utils.allocBuffer(16); + index = 0; + + // Encode the low 64 bits of the decimal + // Encode low bits + buffer[index++] = dec.low.low_ & 0xff; + buffer[index++] = dec.low.low_ >> 8 & 0xff; + buffer[index++] = dec.low.low_ >> 16 & 0xff; + buffer[index++] = dec.low.low_ >> 24 & 0xff; + // Encode high bits + buffer[index++] = dec.low.high_ & 0xff; + buffer[index++] = dec.low.high_ >> 8 & 0xff; + buffer[index++] = dec.low.high_ >> 16 & 0xff; + buffer[index++] = dec.low.high_ >> 24 & 0xff; + + // Encode the high 64 bits of the decimal + // Encode low bits + buffer[index++] = dec.high.low_ & 0xff; + buffer[index++] = dec.high.low_ >> 8 & 0xff; + buffer[index++] = dec.high.low_ >> 16 & 0xff; + buffer[index++] = dec.high.low_ >> 24 & 0xff; + // Encode high bits + buffer[index++] = dec.high.high_ & 0xff; + buffer[index++] = dec.high.high_ >> 8 & 0xff; + buffer[index++] = dec.high.high_ >> 16 & 0xff; + buffer[index++] = dec.high.high_ >> 24 & 0xff; + + // Return the new Decimal128 + return new Decimal128(buffer); + }; + + // Extract least significant 5 bits + var COMBINATION_MASK = 0x1f; + // Extract least significant 14 bits + var EXPONENT_MASK = 0x3fff; + // Value of combination field for Inf + var COMBINATION_INFINITY = 30; + // Value of combination field for NaN + var COMBINATION_NAN = 31; + // Value of combination field for NaN + // var COMBINATION_SNAN = 32; + // decimal128 exponent bias + EXPONENT_BIAS = 6176; + + /** + * Create a string representation of the raw Decimal128 value + * + * @method + * @return {string} returns a Decimal128 string representation. + */ + Decimal128.prototype.toString = function () { + // Note: bits in this routine are referred to starting at 0, + // from the sign bit, towards the coefficient. + + // bits 0 - 31 + var high; + // bits 32 - 63 + var midh; + // bits 64 - 95 + var midl; + // bits 96 - 127 + var low; + // bits 1 - 5 + var combination; + // decoded biased exponent (14 bits) + var biased_exponent; + // the number of significand digits + var significand_digits = 0; + // the base-10 digits in the significand + var significand = new Array(36); + for (var i = 0; i < significand.length; i++) significand[i] = 0; + // read pointer into significand + var index = 0; + + // unbiased exponent + var exponent; + // the exponent if scientific notation is used + var scientific_exponent; + + // true if the number is zero + var is_zero = false; + + // the most signifcant significand bits (50-46) + var significand_msb; + // temporary storage for significand decoding + var significand128 = { parts: new Array(4) }; + // indexing variables + i; + var j, k; + + // Output string + var string = []; + + // Unpack index + index = 0; + + // Buffer reference + var buffer = this.bytes; + + // Unpack the low 64bits into a long + low = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + midl = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + + // Unpack the high 64bits into a long + midh = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + high = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + + // Unpack index + index = 0; + + // Create the state of the decimal + var dec = { + low: new Long(low, midl), + high: new Long(midh, high) + }; + + if (dec.high.lessThan(Long.ZERO)) { + string.push('-'); + } + + // Decode combination field and exponent + combination = high >> 26 & COMBINATION_MASK; + + if (combination >> 3 === 3) { + // Check for 'special' values + if (combination === COMBINATION_INFINITY) { + return string.join('') + 'Infinity'; + } else if (combination === COMBINATION_NAN) { + return 'NaN'; + } else { + biased_exponent = high >> 15 & EXPONENT_MASK; + significand_msb = 0x08 + (high >> 14 & 0x01); + } + } else { + significand_msb = high >> 14 & 0x07; + biased_exponent = high >> 17 & EXPONENT_MASK; + } + + exponent = biased_exponent - EXPONENT_BIAS; + + // Create string of significand digits + + // Convert the 114-bit binary number represented by + // (significand_high, significand_low) to at most 34 decimal + // digits through modulo and division. + significand128.parts[0] = (high & 0x3fff) + ((significand_msb & 0xf) << 14); + significand128.parts[1] = midh; + significand128.parts[2] = midl; + significand128.parts[3] = low; + + if (significand128.parts[0] === 0 && significand128.parts[1] === 0 && significand128.parts[2] === 0 && significand128.parts[3] === 0) { + is_zero = true; + } else { + for (k = 3; k >= 0; k--) { + var least_digits = 0; + // Peform the divide + var result = divideu128(significand128); + significand128 = result.quotient; + least_digits = result.rem.low_; + + // We now have the 9 least significant digits (in base 2). + // Convert and output to string. + if (!least_digits) continue; + + for (j = 8; j >= 0; j--) { + // significand[k * 9 + j] = Math.round(least_digits % 10); + significand[k * 9 + j] = least_digits % 10; + // least_digits = Math.round(least_digits / 10); + least_digits = Math.floor(least_digits / 10); + } + } + } + + // Output format options: + // Scientific - [-]d.dddE(+/-)dd or [-]dE(+/-)dd + // Regular - ddd.ddd + + if (is_zero) { + significand_digits = 1; + significand[index] = 0; + } else { + significand_digits = 36; + i = 0; + + while (!significand[index]) { + i++; + significand_digits = significand_digits - 1; + index = index + 1; + } + } + + scientific_exponent = significand_digits - 1 + exponent; + + // The scientific exponent checks are dictated by the string conversion + // specification and are somewhat arbitrary cutoffs. + // + // We must check exponent > 0, because if this is the case, the number + // has trailing zeros. However, we *cannot* output these trailing zeros, + // because doing so would change the precision of the value, and would + // change stored data if the string converted number is round tripped. + + if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) { + // Scientific format + string.push(significand[index++]); + significand_digits = significand_digits - 1; + + if (significand_digits) { + string.push('.'); + } + + for (i = 0; i < significand_digits; i++) { + string.push(significand[index++]); + } + + // Exponent + string.push('E'); + if (scientific_exponent > 0) { + string.push('+' + scientific_exponent); + } else { + string.push(scientific_exponent); + } + } else { + // Regular format with no decimal place + if (exponent >= 0) { + for (i = 0; i < significand_digits; i++) { + string.push(significand[index++]); + } + } else { + var radix_position = significand_digits + exponent; + + // non-zero digits before radix + if (radix_position > 0) { + for (i = 0; i < radix_position; i++) { + string.push(significand[index++]); + } + } else { + string.push('0'); + } + + string.push('.'); + // add leading zeros after radix + while (radix_position++ < 0) { + string.push('0'); + } + + for (i = 0; i < significand_digits - Math.max(radix_position - 1, 0); i++) { + string.push(significand[index++]); + } + } + } + + return string.join(''); + }; + + Decimal128.prototype.toJSON = function () { + return { $numberDecimal: this.toString() }; + }; + + module.exports = Decimal128; + module.exports.Decimal128 = Decimal128; + +/***/ }), +/* 348 */ +/***/ (function(module, exports) { + + /** + * A class representation of the BSON MinKey type. + * + * @class + * @return {MinKey} A MinKey instance + */ + function MinKey() { + if (!(this instanceof MinKey)) return new MinKey(); + + this._bsontype = 'MinKey'; + } + + module.exports = MinKey; + module.exports.MinKey = MinKey; + +/***/ }), +/* 349 */ +/***/ (function(module, exports) { + + /** + * A class representation of the BSON MaxKey type. + * + * @class + * @return {MaxKey} A MaxKey instance + */ + function MaxKey() { + if (!(this instanceof MaxKey)) return new MaxKey(); + + this._bsontype = 'MaxKey'; + } + + module.exports = MaxKey; + module.exports.MaxKey = MaxKey; + +/***/ }), +/* 350 */ +/***/ (function(module, exports) { + + /** + * A class representation of the BSON DBRef type. + * + * @class + * @param {string} namespace the collection name. + * @param {ObjectID} oid the reference ObjectID. + * @param {string} [db] optional db name, if omitted the reference is local to the current db. + * @return {DBRef} + */ + function DBRef(namespace, oid, db) { + if (!(this instanceof DBRef)) return new DBRef(namespace, oid, db); + + this._bsontype = 'DBRef'; + this.namespace = namespace; + this.oid = oid; + this.db = db; + } + + /** + * @ignore + * @api private + */ + DBRef.prototype.toJSON = function () { + return { + $ref: this.namespace, + $id: this.oid, + $db: this.db == null ? '' : this.db + }; + }; + + module.exports = DBRef; + module.exports.DBRef = DBRef; + +/***/ }), +/* 351 */ +/***/ (function(module, exports, __webpack_require__) { + + /* WEBPACK VAR INJECTION */(function(global) {/** + * Module dependencies. + * @ignore + */ + + // Test if we're in Node via presence of "global" not absence of "window" + // to support hybrid environments like Electron + if (typeof global !== 'undefined') { + var Buffer = __webpack_require__(334).Buffer; // TODO just use global Buffer + } + + var utils = __webpack_require__(339); + + /** + * A class representation of the BSON Binary type. + * + * Sub types + * - **BSON.BSON_BINARY_SUBTYPE_DEFAULT**, default BSON type. + * - **BSON.BSON_BINARY_SUBTYPE_FUNCTION**, BSON function type. + * - **BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY**, BSON byte array type. + * - **BSON.BSON_BINARY_SUBTYPE_UUID**, BSON uuid type. + * - **BSON.BSON_BINARY_SUBTYPE_MD5**, BSON md5 type. + * - **BSON.BSON_BINARY_SUBTYPE_USER_DEFINED**, BSON user defined type. + * + * @class + * @param {Buffer} buffer a buffer object containing the binary data. + * @param {Number} [subType] the option binary type. + * @return {Binary} + */ + function Binary(buffer, subType) { + if (!(this instanceof Binary)) return new Binary(buffer, subType); + + if (buffer != null && !(typeof buffer === 'string') && !Buffer.isBuffer(buffer) && !(buffer instanceof Uint8Array) && !Array.isArray(buffer)) { + throw new Error('only String, Buffer, Uint8Array or Array accepted'); + } + + this._bsontype = 'Binary'; + + if (buffer instanceof Number) { + this.sub_type = buffer; + this.position = 0; + } else { + this.sub_type = subType == null ? BSON_BINARY_SUBTYPE_DEFAULT : subType; + this.position = 0; + } + + if (buffer != null && !(buffer instanceof Number)) { + // Only accept Buffer, Uint8Array or Arrays + if (typeof buffer === 'string') { + // Different ways of writing the length of the string for the different types + if (typeof Buffer !== 'undefined') { + this.buffer = utils.toBuffer(buffer); + } else if (typeof Uint8Array !== 'undefined' || Object.prototype.toString.call(buffer) === '[object Array]') { + this.buffer = writeStringToArray(buffer); + } else { + throw new Error('only String, Buffer, Uint8Array or Array accepted'); + } + } else { + this.buffer = buffer; + } + this.position = buffer.length; + } else { + if (typeof Buffer !== 'undefined') { + this.buffer = utils.allocBuffer(Binary.BUFFER_SIZE); + } else if (typeof Uint8Array !== 'undefined') { + this.buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE)); + } else { + this.buffer = new Array(Binary.BUFFER_SIZE); + } + // Set position to start of buffer + this.position = 0; + } + } + + /** + * Updates this binary with byte_value. + * + * @method + * @param {string} byte_value a single byte we wish to write. + */ + Binary.prototype.put = function put(byte_value) { + // If it's a string and a has more than one character throw an error + if (byte_value['length'] != null && typeof byte_value !== 'number' && byte_value.length !== 1) throw new Error('only accepts single character String, Uint8Array or Array'); + if (typeof byte_value !== 'number' && byte_value < 0 || byte_value > 255) throw new Error('only accepts number in a valid unsigned byte range 0-255'); + + // Decode the byte value once + var decoded_byte = null; + if (typeof byte_value === 'string') { + decoded_byte = byte_value.charCodeAt(0); + } else if (byte_value['length'] != null) { + decoded_byte = byte_value[0]; + } else { + decoded_byte = byte_value; + } + + if (this.buffer.length > this.position) { + this.buffer[this.position++] = decoded_byte; + } else { + if (typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer)) { + // Create additional overflow buffer + var buffer = utils.allocBuffer(Binary.BUFFER_SIZE + this.buffer.length); + // Combine the two buffers together + this.buffer.copy(buffer, 0, 0, this.buffer.length); + this.buffer = buffer; + this.buffer[this.position++] = decoded_byte; + } else { + buffer = null; + // Create a new buffer (typed or normal array) + if (Object.prototype.toString.call(this.buffer) === '[object Uint8Array]') { + buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE + this.buffer.length)); + } else { + buffer = new Array(Binary.BUFFER_SIZE + this.buffer.length); + } + + // We need to copy all the content to the new array + for (var i = 0; i < this.buffer.length; i++) { + buffer[i] = this.buffer[i]; + } + + // Reassign the buffer + this.buffer = buffer; + // Write the byte + this.buffer[this.position++] = decoded_byte; + } + } + }; + + /** + * Writes a buffer or string to the binary. + * + * @method + * @param {(Buffer|string)} string a string or buffer to be written to the Binary BSON object. + * @param {number} offset specify the binary of where to write the content. + * @return {null} + */ + Binary.prototype.write = function write(string, offset) { + offset = typeof offset === 'number' ? offset : this.position; + + // If the buffer is to small let's extend the buffer + if (this.buffer.length < offset + string.length) { + var buffer = null; + // If we are in node.js + if (typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer)) { + buffer = utils.allocBuffer(this.buffer.length + string.length); + this.buffer.copy(buffer, 0, 0, this.buffer.length); + } else if (Object.prototype.toString.call(this.buffer) === '[object Uint8Array]') { + // Create a new buffer + buffer = new Uint8Array(new ArrayBuffer(this.buffer.length + string.length)); + // Copy the content + for (var i = 0; i < this.position; i++) { + buffer[i] = this.buffer[i]; + } + } + + // Assign the new buffer + this.buffer = buffer; + } + + if (typeof Buffer !== 'undefined' && Buffer.isBuffer(string) && Buffer.isBuffer(this.buffer)) { + string.copy(this.buffer, offset, 0, string.length); + this.position = offset + string.length > this.position ? offset + string.length : this.position; + // offset = string.length + } else if (typeof Buffer !== 'undefined' && typeof string === 'string' && Buffer.isBuffer(this.buffer)) { + this.buffer.write(string, offset, 'binary'); + this.position = offset + string.length > this.position ? offset + string.length : this.position; + // offset = string.length; + } else if (Object.prototype.toString.call(string) === '[object Uint8Array]' || Object.prototype.toString.call(string) === '[object Array]' && typeof string !== 'string') { + for (i = 0; i < string.length; i++) { + this.buffer[offset++] = string[i]; + } + + this.position = offset > this.position ? offset : this.position; + } else if (typeof string === 'string') { + for (i = 0; i < string.length; i++) { + this.buffer[offset++] = string.charCodeAt(i); + } + + this.position = offset > this.position ? offset : this.position; + } + }; + + /** + * Reads **length** bytes starting at **position**. + * + * @method + * @param {number} position read from the given position in the Binary. + * @param {number} length the number of bytes to read. + * @return {Buffer} + */ + Binary.prototype.read = function read(position, length) { + length = length && length > 0 ? length : this.position; + + // Let's return the data based on the type we have + if (this.buffer['slice']) { + return this.buffer.slice(position, position + length); + } else { + // Create a buffer to keep the result + var buffer = typeof Uint8Array !== 'undefined' ? new Uint8Array(new ArrayBuffer(length)) : new Array(length); + for (var i = 0; i < length; i++) { + buffer[i] = this.buffer[position++]; + } + } + // Return the buffer + return buffer; + }; + + /** + * Returns the value of this binary as a string. + * + * @method + * @return {string} + */ + Binary.prototype.value = function value(asRaw) { + asRaw = asRaw == null ? false : asRaw; + + // Optimize to serialize for the situation where the data == size of buffer + if (asRaw && typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer) && this.buffer.length === this.position) return this.buffer; + + // If it's a node.js buffer object + if (typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer)) { + return asRaw ? this.buffer.slice(0, this.position) : this.buffer.toString('binary', 0, this.position); + } else { + if (asRaw) { + // we support the slice command use it + if (this.buffer['slice'] != null) { + return this.buffer.slice(0, this.position); + } else { + // Create a new buffer to copy content to + var newBuffer = Object.prototype.toString.call(this.buffer) === '[object Uint8Array]' ? new Uint8Array(new ArrayBuffer(this.position)) : new Array(this.position); + // Copy content + for (var i = 0; i < this.position; i++) { + newBuffer[i] = this.buffer[i]; + } + // Return the buffer + return newBuffer; + } + } else { + return convertArraytoUtf8BinaryString(this.buffer, 0, this.position); + } + } + }; + + /** + * Length. + * + * @method + * @return {number} the length of the binary. + */ + Binary.prototype.length = function length() { + return this.position; + }; + + /** + * @ignore + */ + Binary.prototype.toJSON = function () { + return this.buffer != null ? this.buffer.toString('base64') : ''; + }; + + /** + * @ignore + */ + Binary.prototype.toString = function (format) { + return this.buffer != null ? this.buffer.slice(0, this.position).toString(format) : ''; + }; + + /** + * Binary default subtype + * @ignore + */ + var BSON_BINARY_SUBTYPE_DEFAULT = 0; + + /** + * @ignore + */ + var writeStringToArray = function (data) { + // Create a buffer + var buffer = typeof Uint8Array !== 'undefined' ? new Uint8Array(new ArrayBuffer(data.length)) : new Array(data.length); + // Write the content to the buffer + for (var i = 0; i < data.length; i++) { + buffer[i] = data.charCodeAt(i); + } + // Write the string to the buffer + return buffer; + }; + + /** + * Convert Array ot Uint8Array to Binary String + * + * @ignore + */ + var convertArraytoUtf8BinaryString = function (byteArray, startIndex, endIndex) { + var result = ''; + for (var i = startIndex; i < endIndex; i++) { + result = result + String.fromCharCode(byteArray[i]); + } + return result; + }; + + Binary.BUFFER_SIZE = 256; + + /** + * Default BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ + Binary.SUBTYPE_DEFAULT = 0; + /** + * Function BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ + Binary.SUBTYPE_FUNCTION = 1; + /** + * Byte Array BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ + Binary.SUBTYPE_BYTE_ARRAY = 2; + /** + * OLD UUID BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ + Binary.SUBTYPE_UUID_OLD = 3; + /** + * UUID BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ + Binary.SUBTYPE_UUID = 4; + /** + * MD5 BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ + Binary.SUBTYPE_MD5 = 5; + /** + * User BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ + Binary.SUBTYPE_USER_DEFINED = 128; + + /** + * Expose. + */ + module.exports = Binary; + module.exports.Binary = Binary; + /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) + +/***/ }), +/* 352 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + + var Long = __webpack_require__(330).Long, + Double = __webpack_require__(331).Double, + Timestamp = __webpack_require__(332).Timestamp, + ObjectID = __webpack_require__(333).ObjectID, + Symbol = __webpack_require__(344).Symbol, + Code = __webpack_require__(346).Code, + MinKey = __webpack_require__(348).MinKey, + MaxKey = __webpack_require__(349).MaxKey, + Decimal128 = __webpack_require__(347), + Int32 = __webpack_require__(345), + DBRef = __webpack_require__(350).DBRef, + BSONRegExp = __webpack_require__(343).BSONRegExp, + Binary = __webpack_require__(351).Binary; + + var utils = __webpack_require__(339); + + var deserialize = function (buffer, options, isArray) { + options = options == null ? {} : options; + var index = options && options.index ? options.index : 0; + // Read the document size + var size = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; + + // Ensure buffer is valid size + if (size < 5 || buffer.length < size || size + index > buffer.length) { + throw new Error('corrupt bson message'); + } + + // Illegal end value + if (buffer[index + size - 1] !== 0) { + throw new Error("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00"); + } + + // Start deserializtion + return deserializeObject(buffer, index, options, isArray); + }; + + var deserializeObject = function (buffer, index, options, isArray) { + var evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions']; + var cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions']; + var cacheFunctionsCrc32 = options['cacheFunctionsCrc32'] == null ? false : options['cacheFunctionsCrc32']; + + if (!cacheFunctionsCrc32) var crc32 = null; + + var fieldsAsRaw = options['fieldsAsRaw'] == null ? null : options['fieldsAsRaw']; + + // Return raw bson buffer instead of parsing it + var raw = options['raw'] == null ? false : options['raw']; + + // Return BSONRegExp objects instead of native regular expressions + var bsonRegExp = typeof options['bsonRegExp'] === 'boolean' ? options['bsonRegExp'] : false; + + // Controls the promotion of values vs wrapper classes + var promoteBuffers = options['promoteBuffers'] == null ? false : options['promoteBuffers']; + var promoteLongs = options['promoteLongs'] == null ? true : options['promoteLongs']; + var promoteValues = options['promoteValues'] == null ? true : options['promoteValues']; + + // Set the start index + var startIndex = index; + + // Validate that we have at least 4 bytes of buffer + if (buffer.length < 5) throw new Error('corrupt bson message < 5 bytes long'); + + // Read the document size + var size = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + + // Ensure buffer is valid size + if (size < 5 || size > buffer.length) throw new Error('corrupt bson message'); + + // Create holding object + var object = isArray ? [] : {}; + // Used for arrays to skip having to perform utf8 decoding + var arrayIndex = 0; + + var done = false; + + // While we have more left data left keep parsing + // while (buffer[index + 1] !== 0) { + while (!done) { + // Read the type + var elementType = buffer[index++]; + // If we get a zero it's the last byte, exit + if (elementType === 0) break; + + // Get the start search index + var i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); + var name = isArray ? arrayIndex++ : buffer.toString('utf8', index, i); + + index = i + 1; + + if (elementType === BSON.BSON_DATA_STRING) { + var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + if (stringSize <= 0 || stringSize > buffer.length - index || buffer[index + stringSize - 1] !== 0) throw new Error('bad string length in bson'); + object[name] = buffer.toString('utf8', index, index + stringSize - 1); + index = index + stringSize; + } else if (elementType === BSON.BSON_DATA_OID) { + var oid = utils.allocBuffer(12); + buffer.copy(oid, 0, index, index + 12); + object[name] = new ObjectID(oid); + index = index + 12; + } else if (elementType === BSON.BSON_DATA_INT && promoteValues === false) { + object[name] = new Int32(buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24); + } else if (elementType === BSON.BSON_DATA_INT) { + object[name] = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + } else if (elementType === BSON.BSON_DATA_NUMBER && promoteValues === false) { + object[name] = new Double(buffer.readDoubleLE(index)); + index = index + 8; + } else if (elementType === BSON.BSON_DATA_NUMBER) { + object[name] = buffer.readDoubleLE(index); + index = index + 8; + } else if (elementType === BSON.BSON_DATA_DATE) { + var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + object[name] = new Date(new Long(lowBits, highBits).toNumber()); + } else if (elementType === BSON.BSON_DATA_BOOLEAN) { + if (buffer[index] !== 0 && buffer[index] !== 1) throw new Error('illegal boolean type value'); + object[name] = buffer[index++] === 1; + } else if (elementType === BSON.BSON_DATA_OBJECT) { + var _index = index; + var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; + if (objectSize <= 0 || objectSize > buffer.length - index) throw new Error('bad embedded document length in bson'); + + // We have a raw value + if (raw) { + object[name] = buffer.slice(index, index + objectSize); + } else { + object[name] = deserializeObject(buffer, _index, options, false); + } + + index = index + objectSize; + } else if (elementType === BSON.BSON_DATA_ARRAY) { + _index = index; + objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; + var arrayOptions = options; + + // Stop index + var stopIndex = index + objectSize; + + // All elements of array to be returned as raw bson + if (fieldsAsRaw && fieldsAsRaw[name]) { + arrayOptions = {}; + for (var n in options) arrayOptions[n] = options[n]; + arrayOptions['raw'] = true; + } + + object[name] = deserializeObject(buffer, _index, arrayOptions, true); + index = index + objectSize; + + if (buffer[index - 1] !== 0) throw new Error('invalid array terminator byte'); + if (index !== stopIndex) throw new Error('corrupted array bson'); + } else if (elementType === BSON.BSON_DATA_UNDEFINED) { + object[name] = undefined; + } else if (elementType === BSON.BSON_DATA_NULL) { + object[name] = null; + } else if (elementType === BSON.BSON_DATA_LONG) { + // Unpack the low and high bits + lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + var long = new Long(lowBits, highBits); + // Promote the long if possible + if (promoteLongs && promoteValues === true) { + object[name] = long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) ? long.toNumber() : long; + } else { + object[name] = long; + } + } else if (elementType === BSON.BSON_DATA_DECIMAL128) { + // Buffer to contain the decimal bytes + var bytes = utils.allocBuffer(16); + // Copy the next 16 bytes into the bytes buffer + buffer.copy(bytes, 0, index, index + 16); + // Update index + index = index + 16; + // Assign the new Decimal128 value + var decimal128 = new Decimal128(bytes); + // If we have an alternative mapper use that + object[name] = decimal128.toObject ? decimal128.toObject() : decimal128; + } else if (elementType === BSON.BSON_DATA_BINARY) { + var binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + var totalBinarySize = binarySize; + var subType = buffer[index++]; + + // Did we have a negative binary size, throw + if (binarySize < 0) throw new Error('Negative binary type element size found'); + + // Is the length longer than the document + if (binarySize > buffer.length) throw new Error('Binary type size larger than document size'); + + // Decode as raw Buffer object if options specifies it + if (buffer['slice'] != null) { + // If we have subtype 2 skip the 4 bytes for the size + if (subType === Binary.SUBTYPE_BYTE_ARRAY) { + binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + if (binarySize < 0) throw new Error('Negative binary type element size found for subtype 0x02'); + if (binarySize > totalBinarySize - 4) throw new Error('Binary type with subtype 0x02 contains to long binary size'); + if (binarySize < totalBinarySize - 4) throw new Error('Binary type with subtype 0x02 contains to short binary size'); + } + + if (promoteBuffers && promoteValues) { + object[name] = buffer.slice(index, index + binarySize); + } else { + object[name] = new Binary(buffer.slice(index, index + binarySize), subType); + } + } else { + var _buffer = typeof Uint8Array !== 'undefined' ? new Uint8Array(new ArrayBuffer(binarySize)) : new Array(binarySize); + // If we have subtype 2 skip the 4 bytes for the size + if (subType === Binary.SUBTYPE_BYTE_ARRAY) { + binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + if (binarySize < 0) throw new Error('Negative binary type element size found for subtype 0x02'); + if (binarySize > totalBinarySize - 4) throw new Error('Binary type with subtype 0x02 contains to long binary size'); + if (binarySize < totalBinarySize - 4) throw new Error('Binary type with subtype 0x02 contains to short binary size'); + } + + // Copy the data + for (i = 0; i < binarySize; i++) { + _buffer[i] = buffer[index + i]; + } + + if (promoteBuffers && promoteValues) { + object[name] = _buffer; + } else { + object[name] = new Binary(_buffer, subType); + } + } + + // Update the index + index = index + binarySize; + } else if (elementType === BSON.BSON_DATA_REGEXP && bsonRegExp === false) { + // Get the start search index + i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); + // Return the C string + var source = buffer.toString('utf8', index, i); + // Create the regexp + index = i + 1; + + // Get the start search index + i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); + // Return the C string + var regExpOptions = buffer.toString('utf8', index, i); + index = i + 1; + + // For each option add the corresponding one for javascript + var optionsArray = new Array(regExpOptions.length); + + // Parse options + for (i = 0; i < regExpOptions.length; i++) { + switch (regExpOptions[i]) { + case 'm': + optionsArray[i] = 'm'; + break; + case 's': + optionsArray[i] = 'g'; + break; + case 'i': + optionsArray[i] = 'i'; + break; + } + } + + object[name] = new RegExp(source, optionsArray.join('')); + } else if (elementType === BSON.BSON_DATA_REGEXP && bsonRegExp === true) { + // Get the start search index + i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); + // Return the C string + source = buffer.toString('utf8', index, i); + index = i + 1; + + // Get the start search index + i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); + // Return the C string + regExpOptions = buffer.toString('utf8', index, i); + index = i + 1; + + // Set the object + object[name] = new BSONRegExp(source, regExpOptions); + } else if (elementType === BSON.BSON_DATA_SYMBOL) { + stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + if (stringSize <= 0 || stringSize > buffer.length - index || buffer[index + stringSize - 1] !== 0) throw new Error('bad string length in bson'); + object[name] = new Symbol(buffer.toString('utf8', index, index + stringSize - 1)); + index = index + stringSize; + } else if (elementType === BSON.BSON_DATA_TIMESTAMP) { + lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + object[name] = new Timestamp(lowBits, highBits); + } else if (elementType === BSON.BSON_DATA_MIN_KEY) { + object[name] = new MinKey(); + } else if (elementType === BSON.BSON_DATA_MAX_KEY) { + object[name] = new MaxKey(); + } else if (elementType === BSON.BSON_DATA_CODE) { + stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + if (stringSize <= 0 || stringSize > buffer.length - index || buffer[index + stringSize - 1] !== 0) throw new Error('bad string length in bson'); + var functionString = buffer.toString('utf8', index, index + stringSize - 1); + + // If we are evaluating the functions + if (evalFunctions) { + // If we have cache enabled let's look for the md5 of the function in the cache + if (cacheFunctions) { + var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; + // Got to do this to avoid V8 deoptimizing the call due to finding eval + object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); + } else { + object[name] = isolateEval(functionString); + } + } else { + object[name] = new Code(functionString); + } + + // Update parse index position + index = index + stringSize; + } else if (elementType === BSON.BSON_DATA_CODE_W_SCOPE) { + var totalSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + + // Element cannot be shorter than totalSize + stringSize + documentSize + terminator + if (totalSize < 4 + 4 + 4 + 1) { + throw new Error('code_w_scope total size shorter minimum expected length'); + } + + // Get the code string size + stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Check if we have a valid string + if (stringSize <= 0 || stringSize > buffer.length - index || buffer[index + stringSize - 1] !== 0) throw new Error('bad string length in bson'); + + // Javascript function + functionString = buffer.toString('utf8', index, index + stringSize - 1); + // Update parse index position + index = index + stringSize; + // Parse the element + _index = index; + // Decode the size of the object document + objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; + // Decode the scope object + var scopeObject = deserializeObject(buffer, _index, options, false); + // Adjust the index + index = index + objectSize; + + // Check if field length is to short + if (totalSize < 4 + 4 + objectSize + stringSize) { + throw new Error('code_w_scope total size is to short, truncating scope'); + } + + // Check if totalSize field is to long + if (totalSize > 4 + 4 + objectSize + stringSize) { + throw new Error('code_w_scope total size is to long, clips outer document'); + } + + // If we are evaluating the functions + if (evalFunctions) { + // If we have cache enabled let's look for the md5 of the function in the cache + if (cacheFunctions) { + hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; + // Got to do this to avoid V8 deoptimizing the call due to finding eval + object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); + } else { + object[name] = isolateEval(functionString); + } + + object[name].scope = scopeObject; + } else { + object[name] = new Code(functionString, scopeObject); + } + } else if (elementType === BSON.BSON_DATA_DBPOINTER) { + // Get the code string size + stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Check if we have a valid string + if (stringSize <= 0 || stringSize > buffer.length - index || buffer[index + stringSize - 1] !== 0) throw new Error('bad string length in bson'); + // Namespace + var namespace = buffer.toString('utf8', index, index + stringSize - 1); + // Update parse index position + index = index + stringSize; + + // Read the oid + var oidBuffer = utils.allocBuffer(12); + buffer.copy(oidBuffer, 0, index, index + 12); + oid = new ObjectID(oidBuffer); + + // Update the index + index = index + 12; + + // Split the namespace + var parts = namespace.split('.'); + var db = parts.shift(); + var collection = parts.join('.'); + // Upgrade to DBRef type + object[name] = new DBRef(collection, oid, db); + } else { + throw new Error('Detected unknown BSON type ' + elementType.toString(16) + ' for fieldname "' + name + '", are you using the latest BSON parser'); + } + } + + // Check if the deserialization was against a valid array/object + if (size !== index - startIndex) { + if (isArray) throw new Error('corrupt array bson'); + throw new Error('corrupt object bson'); + } + + // Check if we have a db ref object + if (object['$id'] != null) object = new DBRef(object['$ref'], object['$id'], object['$db']); + return object; + }; + + /** + * Ensure eval is isolated. + * + * @ignore + * @api private + */ + var isolateEvalWithHash = function (functionCache, hash, functionString, object) { + // Contains the value we are going to set + var value = null; + + // Check for cache hit, eval if missing and return cached function + if (functionCache[hash] == null) { + eval('value = ' + functionString); + functionCache[hash] = value; + } + // Set the object + return functionCache[hash].bind(object); + }; + + /** + * Ensure eval is isolated. + * + * @ignore + * @api private + */ + var isolateEval = function (functionString) { + // Contains the value we are going to set + var value = null; + // Eval the function + eval('value = ' + functionString); + return value; + }; + + var BSON = {}; + + /** + * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 + * + * @ignore + * @api private + */ + var functionCache = BSON.functionCache = {}; + + /** + * Number BSON Type + * + * @classconstant BSON_DATA_NUMBER + **/ + BSON.BSON_DATA_NUMBER = 1; + /** + * String BSON Type + * + * @classconstant BSON_DATA_STRING + **/ + BSON.BSON_DATA_STRING = 2; + /** + * Object BSON Type + * + * @classconstant BSON_DATA_OBJECT + **/ + BSON.BSON_DATA_OBJECT = 3; + /** + * Array BSON Type + * + * @classconstant BSON_DATA_ARRAY + **/ + BSON.BSON_DATA_ARRAY = 4; + /** + * Binary BSON Type + * + * @classconstant BSON_DATA_BINARY + **/ + BSON.BSON_DATA_BINARY = 5; + /** + * Binary BSON Type + * + * @classconstant BSON_DATA_UNDEFINED + **/ + BSON.BSON_DATA_UNDEFINED = 6; + /** + * ObjectID BSON Type + * + * @classconstant BSON_DATA_OID + **/ + BSON.BSON_DATA_OID = 7; + /** + * Boolean BSON Type + * + * @classconstant BSON_DATA_BOOLEAN + **/ + BSON.BSON_DATA_BOOLEAN = 8; + /** + * Date BSON Type + * + * @classconstant BSON_DATA_DATE + **/ + BSON.BSON_DATA_DATE = 9; + /** + * null BSON Type + * + * @classconstant BSON_DATA_NULL + **/ + BSON.BSON_DATA_NULL = 10; + /** + * RegExp BSON Type + * + * @classconstant BSON_DATA_REGEXP + **/ + BSON.BSON_DATA_REGEXP = 11; + /** + * Code BSON Type + * + * @classconstant BSON_DATA_DBPOINTER + **/ + BSON.BSON_DATA_DBPOINTER = 12; + /** + * Code BSON Type + * + * @classconstant BSON_DATA_CODE + **/ + BSON.BSON_DATA_CODE = 13; + /** + * Symbol BSON Type + * + * @classconstant BSON_DATA_SYMBOL + **/ + BSON.BSON_DATA_SYMBOL = 14; + /** + * Code with Scope BSON Type + * + * @classconstant BSON_DATA_CODE_W_SCOPE + **/ + BSON.BSON_DATA_CODE_W_SCOPE = 15; + /** + * 32 bit Integer BSON Type + * + * @classconstant BSON_DATA_INT + **/ + BSON.BSON_DATA_INT = 16; + /** + * Timestamp BSON Type + * + * @classconstant BSON_DATA_TIMESTAMP + **/ + BSON.BSON_DATA_TIMESTAMP = 17; + /** + * Long BSON Type + * + * @classconstant BSON_DATA_LONG + **/ + BSON.BSON_DATA_LONG = 18; + /** + * Long BSON Type + * + * @classconstant BSON_DATA_DECIMAL128 + **/ + BSON.BSON_DATA_DECIMAL128 = 19; + /** + * MinKey BSON Type + * + * @classconstant BSON_DATA_MIN_KEY + **/ + BSON.BSON_DATA_MIN_KEY = 0xff; + /** + * MaxKey BSON Type + * + * @classconstant BSON_DATA_MAX_KEY + **/ + BSON.BSON_DATA_MAX_KEY = 0x7f; + + /** + * Binary Default Type + * + * @classconstant BSON_BINARY_SUBTYPE_DEFAULT + **/ + BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; + /** + * Binary Function Type + * + * @classconstant BSON_BINARY_SUBTYPE_FUNCTION + **/ + BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; + /** + * Binary Byte Array Type + * + * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY + **/ + BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; + /** + * Binary UUID Type + * + * @classconstant BSON_BINARY_SUBTYPE_UUID + **/ + BSON.BSON_BINARY_SUBTYPE_UUID = 3; + /** + * Binary MD5 Type + * + * @classconstant BSON_BINARY_SUBTYPE_MD5 + **/ + BSON.BSON_BINARY_SUBTYPE_MD5 = 4; + /** + * Binary User Defined Type + * + * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED + **/ + BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; + + // BSON MAX VALUES + BSON.BSON_INT32_MAX = 0x7fffffff; + BSON.BSON_INT32_MIN = -0x80000000; + + BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; + BSON.BSON_INT64_MIN = -Math.pow(2, 63); + + // JS MAX PRECISE VALUES + BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. + BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. + + // Internal long versions + var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. + var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. + + module.exports = deserialize; + +/***/ }), +/* 353 */ +/***/ (function(module, exports, __webpack_require__) { + + /* WEBPACK VAR INJECTION */(function(Buffer) {'use strict'; + + var writeIEEE754 = __webpack_require__(354).writeIEEE754, + Long = __webpack_require__(330).Long, + Map = __webpack_require__(329), + Binary = __webpack_require__(351).Binary; + + var normalizedFunctionString = __webpack_require__(339).normalizedFunctionString; + + // try { + // var _Buffer = Uint8Array; + // } catch (e) { + // _Buffer = Buffer; + // } + + var regexp = /\x00/; // eslint-disable-line no-control-regex + var ignoreKeys = ['$db', '$ref', '$id', '$clusterTime']; + + // To ensure that 0.4 of node works correctly + var isDate = function isDate(d) { + return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; + }; + + var isRegExp = function isRegExp(d) { + return Object.prototype.toString.call(d) === '[object RegExp]'; + }; + + var serializeString = function (buffer, key, value, index, isArray) { + // Encode String type + buffer[index++] = BSON.BSON_DATA_STRING; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Write the string + var size = buffer.write(value, index + 4, 'utf8'); + // Write the size of the string to buffer + buffer[index + 3] = size + 1 >> 24 & 0xff; + buffer[index + 2] = size + 1 >> 16 & 0xff; + buffer[index + 1] = size + 1 >> 8 & 0xff; + buffer[index] = size + 1 & 0xff; + // Update index + index = index + 4 + size; + // Write zero + buffer[index++] = 0; + return index; + }; + + var serializeNumber = function (buffer, key, value, index, isArray) { + // We have an integer value + if (Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { + // If the value fits in 32 bits encode as int, if it fits in a double + // encode it as a double, otherwise long + if (value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { + // Set int type 32 bits or less + buffer[index++] = BSON.BSON_DATA_INT; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the int value + buffer[index++] = value & 0xff; + buffer[index++] = value >> 8 & 0xff; + buffer[index++] = value >> 16 & 0xff; + buffer[index++] = value >> 24 & 0xff; + } else if (value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { + // Encode as double + buffer[index++] = BSON.BSON_DATA_NUMBER; + // Number of written bytes + numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write float + writeIEEE754(buffer, value, index, 'little', 52, 8); + // Ajust index + index = index + 8; + } else { + // Set long type + buffer[index++] = BSON.BSON_DATA_LONG; + // Number of written bytes + numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + var longVal = Long.fromNumber(value); + var lowBits = longVal.getLowBits(); + var highBits = longVal.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = lowBits >> 8 & 0xff; + buffer[index++] = lowBits >> 16 & 0xff; + buffer[index++] = lowBits >> 24 & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = highBits >> 8 & 0xff; + buffer[index++] = highBits >> 16 & 0xff; + buffer[index++] = highBits >> 24 & 0xff; + } + } else { + // Encode as double + buffer[index++] = BSON.BSON_DATA_NUMBER; + // Number of written bytes + numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write float + writeIEEE754(buffer, value, index, 'little', 52, 8); + // Ajust index + index = index + 8; + } + + return index; + }; + + var serializeNull = function (buffer, key, value, index, isArray) { + // Set long type + buffer[index++] = BSON.BSON_DATA_NULL; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + return index; + }; + + var serializeBoolean = function (buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_BOOLEAN; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Encode the boolean value + buffer[index++] = value ? 1 : 0; + return index; + }; + + var serializeDate = function (buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_DATE; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + // Write the date + var dateInMilis = Long.fromNumber(value.getTime()); + var lowBits = dateInMilis.getLowBits(); + var highBits = dateInMilis.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = lowBits >> 8 & 0xff; + buffer[index++] = lowBits >> 16 & 0xff; + buffer[index++] = lowBits >> 24 & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = highBits >> 8 & 0xff; + buffer[index++] = highBits >> 16 & 0xff; + buffer[index++] = highBits >> 24 & 0xff; + return index; + }; + + var serializeRegExp = function (buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_REGEXP; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + if (value.source && value.source.match(regexp) != null) { + throw Error('value ' + value.source + ' must not contain null bytes'); + } + // Adjust the index + index = index + buffer.write(value.source, index, 'utf8'); + // Write zero + buffer[index++] = 0x00; + // Write the parameters + if (value.global) buffer[index++] = 0x73; // s + if (value.ignoreCase) buffer[index++] = 0x69; // i + if (value.multiline) buffer[index++] = 0x6d; // m + // Add ending zero + buffer[index++] = 0x00; + return index; + }; + + var serializeBSONRegExp = function (buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_REGEXP; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + // Check the pattern for 0 bytes + if (value.pattern.match(regexp) != null) { + // The BSON spec doesn't allow keys with null bytes because keys are + // null-terminated. + throw Error('pattern ' + value.pattern + ' must not contain null bytes'); + } + + // Adjust the index + index = index + buffer.write(value.pattern, index, 'utf8'); + // Write zero + buffer[index++] = 0x00; + // Write the options + index = index + buffer.write(value.options.split('').sort().join(''), index, 'utf8'); + // Add ending zero + buffer[index++] = 0x00; + return index; + }; + + var serializeMinMax = function (buffer, key, value, index, isArray) { + // Write the type of either min or max key + if (value === null) { + buffer[index++] = BSON.BSON_DATA_NULL; + } else if (value._bsontype === 'MinKey') { + buffer[index++] = BSON.BSON_DATA_MIN_KEY; + } else { + buffer[index++] = BSON.BSON_DATA_MAX_KEY; + } + + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + return index; + }; + + var serializeObjectId = function (buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_OID; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + // Write the objectId into the shared buffer + if (typeof value.id === 'string') { + buffer.write(value.id, index, 'binary'); + } else if (value.id && value.id.copy) { + value.id.copy(buffer, index, 0, 12); + } else { + throw new Error('object [' + JSON.stringify(value) + '] is not a valid ObjectId'); + } + + // Ajust index + return index + 12; + }; + + var serializeBuffer = function (buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_BINARY; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Get size of the buffer (current write point) + var size = value.length; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = size >> 8 & 0xff; + buffer[index++] = size >> 16 & 0xff; + buffer[index++] = size >> 24 & 0xff; + // Write the default subtype + buffer[index++] = BSON.BSON_BINARY_SUBTYPE_DEFAULT; + // Copy the content form the binary field to the buffer + value.copy(buffer, index, 0, size); + // Adjust the index + index = index + size; + return index; + }; + + var serializeObject = function (buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, isArray, path) { + for (var i = 0; i < path.length; i++) { + if (path[i] === value) throw new Error('cyclic dependency detected'); + } + + // Push value to stack + path.push(value); + // Write the type + buffer[index++] = Array.isArray(value) ? BSON.BSON_DATA_ARRAY : BSON.BSON_DATA_OBJECT; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + var endIndex = serializeInto(buffer, value, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path); + // Pop stack + path.pop(); + // Write size + return endIndex; + }; + + var serializeDecimal128 = function (buffer, key, value, index, isArray) { + buffer[index++] = BSON.BSON_DATA_DECIMAL128; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the data from the value + value.bytes.copy(buffer, index, 0, 16); + return index + 16; + }; + + var serializeLong = function (buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = value._bsontype === 'Long' ? BSON.BSON_DATA_LONG : BSON.BSON_DATA_TIMESTAMP; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the date + var lowBits = value.getLowBits(); + var highBits = value.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = lowBits >> 8 & 0xff; + buffer[index++] = lowBits >> 16 & 0xff; + buffer[index++] = lowBits >> 24 & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = highBits >> 8 & 0xff; + buffer[index++] = highBits >> 16 & 0xff; + buffer[index++] = highBits >> 24 & 0xff; + return index; + }; + + var serializeInt32 = function (buffer, key, value, index, isArray) { + // Set int type 32 bits or less + buffer[index++] = BSON.BSON_DATA_INT; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the int value + buffer[index++] = value & 0xff; + buffer[index++] = value >> 8 & 0xff; + buffer[index++] = value >> 16 & 0xff; + buffer[index++] = value >> 24 & 0xff; + return index; + }; + + var serializeDouble = function (buffer, key, value, index, isArray) { + // Encode as double + buffer[index++] = BSON.BSON_DATA_NUMBER; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write float + writeIEEE754(buffer, value, index, 'little', 52, 8); + // Ajust index + index = index + 8; + return index; + }; + + var serializeFunction = function (buffer, key, value, index, checkKeys, depth, isArray) { + buffer[index++] = BSON.BSON_DATA_CODE; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Function string + var functionString = normalizedFunctionString(value); + + // Write the string + var size = buffer.write(functionString, index + 4, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = size & 0xff; + buffer[index + 1] = size >> 8 & 0xff; + buffer[index + 2] = size >> 16 & 0xff; + buffer[index + 3] = size >> 24 & 0xff; + // Update index + index = index + 4 + size - 1; + // Write zero + buffer[index++] = 0; + return index; + }; + + var serializeCode = function (buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, isArray) { + if (value.scope && typeof value.scope === 'object') { + // Write the type + buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + // Starting index + var startIndex = index; + + // Serialize the function + // Get the function string + var functionString = typeof value.code === 'string' ? value.code : value.code.toString(); + // Index adjustment + index = index + 4; + // Write string into buffer + var codeSize = buffer.write(functionString, index + 4, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = codeSize & 0xff; + buffer[index + 1] = codeSize >> 8 & 0xff; + buffer[index + 2] = codeSize >> 16 & 0xff; + buffer[index + 3] = codeSize >> 24 & 0xff; + // Write end 0 + buffer[index + 4 + codeSize - 1] = 0; + // Write the + index = index + codeSize + 4; + + // + // Serialize the scope value + var endIndex = serializeInto(buffer, value.scope, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined); + index = endIndex - 1; + + // Writ the total + var totalSize = endIndex - startIndex; + + // Write the total size of the object + buffer[startIndex++] = totalSize & 0xff; + buffer[startIndex++] = totalSize >> 8 & 0xff; + buffer[startIndex++] = totalSize >> 16 & 0xff; + buffer[startIndex++] = totalSize >> 24 & 0xff; + // Write trailing zero + buffer[index++] = 0; + } else { + buffer[index++] = BSON.BSON_DATA_CODE; + // Number of written bytes + numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Function string + functionString = value.code.toString(); + // Write the string + var size = buffer.write(functionString, index + 4, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = size & 0xff; + buffer[index + 1] = size >> 8 & 0xff; + buffer[index + 2] = size >> 16 & 0xff; + buffer[index + 3] = size >> 24 & 0xff; + // Update index + index = index + 4 + size - 1; + // Write zero + buffer[index++] = 0; + } + + return index; + }; + + var serializeBinary = function (buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_BINARY; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Extract the buffer + var data = value.value(true); + // Calculate size + var size = value.position; + // Add the deprecated 02 type 4 bytes of size to total + if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) size = size + 4; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = size >> 8 & 0xff; + buffer[index++] = size >> 16 & 0xff; + buffer[index++] = size >> 24 & 0xff; + // Write the subtype to the buffer + buffer[index++] = value.sub_type; + + // If we have binary type 2 the 4 first bytes are the size + if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { + size = size - 4; + buffer[index++] = size & 0xff; + buffer[index++] = size >> 8 & 0xff; + buffer[index++] = size >> 16 & 0xff; + buffer[index++] = size >> 24 & 0xff; + } + + // Write the data to the object + data.copy(buffer, index, 0, value.position); + // Adjust the index + index = index + value.position; + return index; + }; + + var serializeSymbol = function (buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_SYMBOL; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the string + var size = buffer.write(value.value, index + 4, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = size & 0xff; + buffer[index + 1] = size >> 8 & 0xff; + buffer[index + 2] = size >> 16 & 0xff; + buffer[index + 3] = size >> 24 & 0xff; + // Update index + index = index + 4 + size - 1; + // Write zero + buffer[index++] = 0x00; + return index; + }; + + var serializeDBRef = function (buffer, key, value, index, depth, serializeFunctions, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_OBJECT; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + var startIndex = index; + var endIndex; + + // Serialize object + if (null != value.db) { + endIndex = serializeInto(buffer, { + $ref: value.namespace, + $id: value.oid, + $db: value.db + }, false, index, depth + 1, serializeFunctions); + } else { + endIndex = serializeInto(buffer, { + $ref: value.namespace, + $id: value.oid + }, false, index, depth + 1, serializeFunctions); + } + + // Calculate object size + var size = endIndex - startIndex; + // Write the size + buffer[startIndex++] = size & 0xff; + buffer[startIndex++] = size >> 8 & 0xff; + buffer[startIndex++] = size >> 16 & 0xff; + buffer[startIndex++] = size >> 24 & 0xff; + // Set index + return endIndex; + }; + + var serializeInto = function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializeFunctions, ignoreUndefined, path) { + startingIndex = startingIndex || 0; + path = path || []; + + // Push the object to the path + path.push(object); + + // Start place to serialize into + var index = startingIndex + 4; + // var self = this; + + // Special case isArray + if (Array.isArray(object)) { + // Get object keys + for (var i = 0; i < object.length; i++) { + var key = '' + i; + var value = object[i]; + + // Is there an override value + if (value && value.toBSON) { + if (typeof value.toBSON !== 'function') throw new Error('toBSON is not a function'); + value = value.toBSON(); + } + + var type = typeof value; + if (type === 'string') { + index = serializeString(buffer, key, value, index, true); + } else if (type === 'number') { + index = serializeNumber(buffer, key, value, index, true); + } else if (type === 'boolean') { + index = serializeBoolean(buffer, key, value, index, true); + } else if (value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index, true); + } else if (value === undefined) { + index = serializeNull(buffer, key, value, index, true); + } else if (value === null) { + index = serializeNull(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'ObjectID' || value['_bsontype'] === 'ObjectId') { + index = serializeObjectId(buffer, key, value, index, true); + } else if (Buffer.isBuffer(value)) { + index = serializeBuffer(buffer, key, value, index, true); + } else if (value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index, true); + } else if (type === 'object' && value['_bsontype'] == null) { + index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, true, path); + } else if (type === 'object' && value['_bsontype'] === 'Decimal128') { + index = serializeDecimal128(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { + index = serializeLong(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'Double') { + index = serializeDouble(buffer, key, value, index, true); + } else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions, true); + } else if (value['_bsontype'] === 'Code') { + index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, true); + } else if (value['_bsontype'] === 'Binary') { + index = serializeBinary(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'Symbol') { + index = serializeSymbol(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, true); + } else if (value['_bsontype'] === 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'Int32') { + index = serializeInt32(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { + index = serializeMinMax(buffer, key, value, index, true); + } + } + } else if (object instanceof Map) { + var iterator = object.entries(); + var done = false; + + while (!done) { + // Unpack the next entry + var entry = iterator.next(); + done = entry.done; + // Are we done, then skip and terminate + if (done) continue; + + // Get the entry values + key = entry.value[0]; + value = entry.value[1]; + + // Check the type of the value + type = typeof value; + + // Check the key and throw error if it's illegal + if (typeof key === 'string' && ignoreKeys.indexOf(key) === -1) { + if (key.match(regexp) != null) { + // The BSON spec doesn't allow keys with null bytes because keys are + // null-terminated. + throw Error('key ' + key + ' must not contain null bytes'); + } + + if (checkKeys) { + if ('$' === key[0]) { + throw Error('key ' + key + " must not start with '$'"); + } else if (~key.indexOf('.')) { + throw Error('key ' + key + " must not contain '.'"); + } + } + } + + if (type === 'string') { + index = serializeString(buffer, key, value, index); + } else if (type === 'number') { + index = serializeNumber(buffer, key, value, index); + } else if (type === 'boolean') { + index = serializeBoolean(buffer, key, value, index); + } else if (value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index); + // } else if (value === undefined && ignoreUndefined === true) { + } else if (value === null || value === undefined && ignoreUndefined === false) { + index = serializeNull(buffer, key, value, index); + } else if (value['_bsontype'] === 'ObjectID' || value['_bsontype'] === 'ObjectId') { + index = serializeObjectId(buffer, key, value, index); + } else if (Buffer.isBuffer(value)) { + index = serializeBuffer(buffer, key, value, index); + } else if (value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index); + } else if (type === 'object' && value['_bsontype'] == null) { + index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, false, path); + } else if (type === 'object' && value['_bsontype'] === 'Decimal128') { + index = serializeDecimal128(buffer, key, value, index); + } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { + index = serializeLong(buffer, key, value, index); + } else if (value['_bsontype'] === 'Double') { + index = serializeDouble(buffer, key, value, index); + } else if (value['_bsontype'] === 'Code') { + index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); + } else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); + } else if (value['_bsontype'] === 'Binary') { + index = serializeBinary(buffer, key, value, index); + } else if (value['_bsontype'] === 'Symbol') { + index = serializeSymbol(buffer, key, value, index); + } else if (value['_bsontype'] === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); + } else if (value['_bsontype'] === 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index); + } else if (value['_bsontype'] === 'Int32') { + index = serializeInt32(buffer, key, value, index); + } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { + index = serializeMinMax(buffer, key, value, index); + } + } + } else { + // Did we provide a custom serialization method + if (object.toBSON) { + if (typeof object.toBSON !== 'function') throw new Error('toBSON is not a function'); + object = object.toBSON(); + if (object != null && typeof object !== 'object') throw new Error('toBSON function did not return an object'); + } + + // Iterate over all the keys + for (key in object) { + value = object[key]; + // Is there an override value + if (value && value.toBSON) { + if (typeof value.toBSON !== 'function') throw new Error('toBSON is not a function'); + value = value.toBSON(); + } + + // Check the type of the value + type = typeof value; + + // Check the key and throw error if it's illegal + if (typeof key === 'string' && ignoreKeys.indexOf(key) === -1) { + if (key.match(regexp) != null) { + // The BSON spec doesn't allow keys with null bytes because keys are + // null-terminated. + throw Error('key ' + key + ' must not contain null bytes'); + } + + if (checkKeys) { + if ('$' === key[0]) { + throw Error('key ' + key + " must not start with '$'"); + } else if (~key.indexOf('.')) { + throw Error('key ' + key + " must not contain '.'"); + } + } + } + + if (type === 'string') { + index = serializeString(buffer, key, value, index); + } else if (type === 'number') { + index = serializeNumber(buffer, key, value, index); + } else if (type === 'boolean') { + index = serializeBoolean(buffer, key, value, index); + } else if (value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index); + } else if (value === undefined) { + if (ignoreUndefined === false) index = serializeNull(buffer, key, value, index); + } else if (value === null) { + index = serializeNull(buffer, key, value, index); + } else if (value['_bsontype'] === 'ObjectID' || value['_bsontype'] === 'ObjectId') { + index = serializeObjectId(buffer, key, value, index); + } else if (Buffer.isBuffer(value)) { + index = serializeBuffer(buffer, key, value, index); + } else if (value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index); + } else if (type === 'object' && value['_bsontype'] == null) { + index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, false, path); + } else if (type === 'object' && value['_bsontype'] === 'Decimal128') { + index = serializeDecimal128(buffer, key, value, index); + } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { + index = serializeLong(buffer, key, value, index); + } else if (value['_bsontype'] === 'Double') { + index = serializeDouble(buffer, key, value, index); + } else if (value['_bsontype'] === 'Code') { + index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); + } else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); + } else if (value['_bsontype'] === 'Binary') { + index = serializeBinary(buffer, key, value, index); + } else if (value['_bsontype'] === 'Symbol') { + index = serializeSymbol(buffer, key, value, index); + } else if (value['_bsontype'] === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); + } else if (value['_bsontype'] === 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index); + } else if (value['_bsontype'] === 'Int32') { + index = serializeInt32(buffer, key, value, index); + } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { + index = serializeMinMax(buffer, key, value, index); + } + } + } + + // Remove the path + path.pop(); + + // Final padding byte for object + buffer[index++] = 0x00; + + // Final size + var size = index - startingIndex; + // Write the size of the object + buffer[startingIndex++] = size & 0xff; + buffer[startingIndex++] = size >> 8 & 0xff; + buffer[startingIndex++] = size >> 16 & 0xff; + buffer[startingIndex++] = size >> 24 & 0xff; + return index; + }; + + var BSON = {}; + + /** + * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 + * + * @ignore + * @api private + */ + // var functionCache = (BSON.functionCache = {}); + + /** + * Number BSON Type + * + * @classconstant BSON_DATA_NUMBER + **/ + BSON.BSON_DATA_NUMBER = 1; + /** + * String BSON Type + * + * @classconstant BSON_DATA_STRING + **/ + BSON.BSON_DATA_STRING = 2; + /** + * Object BSON Type + * + * @classconstant BSON_DATA_OBJECT + **/ + BSON.BSON_DATA_OBJECT = 3; + /** + * Array BSON Type + * + * @classconstant BSON_DATA_ARRAY + **/ + BSON.BSON_DATA_ARRAY = 4; + /** + * Binary BSON Type + * + * @classconstant BSON_DATA_BINARY + **/ + BSON.BSON_DATA_BINARY = 5; + /** + * ObjectID BSON Type, deprecated + * + * @classconstant BSON_DATA_UNDEFINED + **/ + BSON.BSON_DATA_UNDEFINED = 6; + /** + * ObjectID BSON Type + * + * @classconstant BSON_DATA_OID + **/ + BSON.BSON_DATA_OID = 7; + /** + * Boolean BSON Type + * + * @classconstant BSON_DATA_BOOLEAN + **/ + BSON.BSON_DATA_BOOLEAN = 8; + /** + * Date BSON Type + * + * @classconstant BSON_DATA_DATE + **/ + BSON.BSON_DATA_DATE = 9; + /** + * null BSON Type + * + * @classconstant BSON_DATA_NULL + **/ + BSON.BSON_DATA_NULL = 10; + /** + * RegExp BSON Type + * + * @classconstant BSON_DATA_REGEXP + **/ + BSON.BSON_DATA_REGEXP = 11; + /** + * Code BSON Type + * + * @classconstant BSON_DATA_CODE + **/ + BSON.BSON_DATA_CODE = 13; + /** + * Symbol BSON Type + * + * @classconstant BSON_DATA_SYMBOL + **/ + BSON.BSON_DATA_SYMBOL = 14; + /** + * Code with Scope BSON Type + * + * @classconstant BSON_DATA_CODE_W_SCOPE + **/ + BSON.BSON_DATA_CODE_W_SCOPE = 15; + /** + * 32 bit Integer BSON Type + * + * @classconstant BSON_DATA_INT + **/ + BSON.BSON_DATA_INT = 16; + /** + * Timestamp BSON Type + * + * @classconstant BSON_DATA_TIMESTAMP + **/ + BSON.BSON_DATA_TIMESTAMP = 17; + /** + * Long BSON Type + * + * @classconstant BSON_DATA_LONG + **/ + BSON.BSON_DATA_LONG = 18; + /** + * Long BSON Type + * + * @classconstant BSON_DATA_DECIMAL128 + **/ + BSON.BSON_DATA_DECIMAL128 = 19; + /** + * MinKey BSON Type + * + * @classconstant BSON_DATA_MIN_KEY + **/ + BSON.BSON_DATA_MIN_KEY = 0xff; + /** + * MaxKey BSON Type + * + * @classconstant BSON_DATA_MAX_KEY + **/ + BSON.BSON_DATA_MAX_KEY = 0x7f; + /** + * Binary Default Type + * + * @classconstant BSON_BINARY_SUBTYPE_DEFAULT + **/ + BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; + /** + * Binary Function Type + * + * @classconstant BSON_BINARY_SUBTYPE_FUNCTION + **/ + BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; + /** + * Binary Byte Array Type + * + * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY + **/ + BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; + /** + * Binary UUID Type + * + * @classconstant BSON_BINARY_SUBTYPE_UUID + **/ + BSON.BSON_BINARY_SUBTYPE_UUID = 3; + /** + * Binary MD5 Type + * + * @classconstant BSON_BINARY_SUBTYPE_MD5 + **/ + BSON.BSON_BINARY_SUBTYPE_MD5 = 4; + /** + * Binary User Defined Type + * + * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED + **/ + BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; + + // BSON MAX VALUES + BSON.BSON_INT32_MAX = 0x7fffffff; + BSON.BSON_INT32_MIN = -0x80000000; + + BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; + BSON.BSON_INT64_MIN = -Math.pow(2, 63); + + // JS MAX PRECISE VALUES + BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. + BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. + + // Internal long versions + // var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. + // var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. + + module.exports = serializeInto; + /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(334).Buffer)) + +/***/ }), +/* 354 */ +/***/ (function(module, exports) { + + // Copyright (c) 2008, Fair Oaks Labs, Inc. + // All rights reserved. + // + // Redistribution and use in source and binary forms, with or without + // modification, are permitted provided that the following conditions are met: + // + // * Redistributions of source code must retain the above copyright notice, + // this list of conditions and the following disclaimer. + // + // * Redistributions in binary form must reproduce the above copyright notice, + // this list of conditions and the following disclaimer in the documentation + // and/or other materials provided with the distribution. + // + // * Neither the name of Fair Oaks Labs, Inc. nor the names of its contributors + // may be used to endorse or promote products derived from this software + // without specific prior written permission. + // + // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + // POSSIBILITY OF SUCH DAMAGE. + // + // + // Modifications to writeIEEE754 to support negative zeroes made by Brian White + + var readIEEE754 = function (buffer, offset, endian, mLen, nBytes) { + var e, + m, + bBE = endian === 'big', + eLen = nBytes * 8 - mLen - 1, + eMax = (1 << eLen) - 1, + eBias = eMax >> 1, + nBits = -7, + i = bBE ? 0 : nBytes - 1, + d = bBE ? 1 : -1, + s = buffer[offset + i]; + + i += d; + + e = s & (1 << -nBits) - 1; + s >>= -nBits; + nBits += eLen; + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8); + + m = e & (1 << -nBits) - 1; + e >>= -nBits; + nBits += mLen; + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8); + + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : (s ? -1 : 1) * Infinity; + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen); + }; + + var writeIEEE754 = function (buffer, value, offset, endian, mLen, nBytes) { + var e, + m, + c, + bBE = endian === 'big', + eLen = nBytes * 8 - mLen - 1, + eMax = (1 << eLen) - 1, + eBias = eMax >> 1, + rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0, + i = bBE ? nBytes - 1 : 0, + d = bBE ? -1 : 1, + s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0; + + value = Math.abs(value); + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8); + + e = e << mLen | m; + eLen += mLen; + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8); + + buffer[offset + i - d] |= s * 128; + }; + + exports.readIEEE754 = readIEEE754; + exports.writeIEEE754 = writeIEEE754; + +/***/ }), +/* 355 */ +/***/ (function(module, exports, __webpack_require__) { + + /* WEBPACK VAR INJECTION */(function(Buffer) {'use strict'; + + var Long = __webpack_require__(330).Long, + Double = __webpack_require__(331).Double, + Timestamp = __webpack_require__(332).Timestamp, + ObjectID = __webpack_require__(333).ObjectID, + Symbol = __webpack_require__(344).Symbol, + BSONRegExp = __webpack_require__(343).BSONRegExp, + Code = __webpack_require__(346).Code, + Decimal128 = __webpack_require__(347), + MinKey = __webpack_require__(348).MinKey, + MaxKey = __webpack_require__(349).MaxKey, + DBRef = __webpack_require__(350).DBRef, + Binary = __webpack_require__(351).Binary; + + var normalizedFunctionString = __webpack_require__(339).normalizedFunctionString; + + // To ensure that 0.4 of node works correctly + var isDate = function isDate(d) { + return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; + }; + + var calculateObjectSize = function calculateObjectSize(object, serializeFunctions, ignoreUndefined) { + var totalLength = 4 + 1; + + if (Array.isArray(object)) { + for (var i = 0; i < object.length; i++) { + totalLength += calculateElement(i.toString(), object[i], serializeFunctions, true, ignoreUndefined); + } + } else { + // If we have toBSON defined, override the current object + if (object.toBSON) { + object = object.toBSON(); + } + + // Calculate size + for (var key in object) { + totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined); + } + } + + return totalLength; + }; + + /** + * @ignore + * @api private + */ + function calculateElement(name, value, serializeFunctions, isArray, ignoreUndefined) { + // If we have toBSON defined, override the current object + if (value && value.toBSON) { + value = value.toBSON(); + } + + switch (typeof value) { + case 'string': + return 1 + Buffer.byteLength(name, 'utf8') + 1 + 4 + Buffer.byteLength(value, 'utf8') + 1; + case 'number': + if (Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { + if (value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { + // 32 bit + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (4 + 1); + } else { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); + } + } else { + // 64 bit + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); + } + case 'undefined': + if (isArray || !ignoreUndefined) return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1; + return 0; + case 'boolean': + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (1 + 1); + case 'object': + if (value == null || value instanceof MinKey || value instanceof MaxKey || value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1; + } else if (value instanceof ObjectID || value['_bsontype'] === 'ObjectID' || value['_bsontype'] === 'ObjectId') { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (12 + 1); + } else if (value instanceof Date || isDate(value)) { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); + } else if (typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (1 + 4 + 1) + value.length; + } else if (value instanceof Long || value instanceof Double || value instanceof Timestamp || value['_bsontype'] === 'Long' || value['_bsontype'] === 'Double' || value['_bsontype'] === 'Timestamp') { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); + } else if (value instanceof Decimal128 || value['_bsontype'] === 'Decimal128') { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (16 + 1); + } else if (value instanceof Code || value['_bsontype'] === 'Code') { + // Calculate size depending on the availability of a scope + if (value.scope != null && Object.keys(value.scope).length > 0) { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + 4 + 4 + Buffer.byteLength(value.code.toString(), 'utf8') + 1 + calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined); + } else { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + 4 + Buffer.byteLength(value.code.toString(), 'utf8') + 1; + } + } else if (value instanceof Binary || value['_bsontype'] === 'Binary') { + // Check what kind of subtype we have + if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (value.position + 1 + 4 + 1 + 4); + } else { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (value.position + 1 + 4 + 1); + } + } else if (value instanceof Symbol || value['_bsontype'] === 'Symbol') { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + Buffer.byteLength(value.value, 'utf8') + 4 + 1 + 1; + } else if (value instanceof DBRef || value['_bsontype'] === 'DBRef') { + // Set up correct object for serialization + var ordered_values = { + $ref: value.namespace, + $id: value.oid + }; + + // Add db reference if it exists + if (null != value.db) { + ordered_values['$db'] = value.db; + } + + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + calculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined); + } else if (value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]') { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + Buffer.byteLength(value.source, 'utf8') + 1 + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1; + } else if (value instanceof BSONRegExp || value['_bsontype'] === 'BSONRegExp') { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + Buffer.byteLength(value.pattern, 'utf8') + 1 + Buffer.byteLength(value.options, 'utf8') + 1; + } else { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + calculateObjectSize(value, serializeFunctions, ignoreUndefined) + 1; + } + case 'function': + // WTF for 0.4.X where typeof /someregexp/ === 'function' + if (value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]' || String.call(value) === '[object RegExp]') { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + Buffer.byteLength(value.source, 'utf8') + 1 + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1; + } else { + if (serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + 4 + 4 + Buffer.byteLength(normalizedFunctionString(value), 'utf8') + 1 + calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined); + } else if (serializeFunctions) { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + 4 + Buffer.byteLength(normalizedFunctionString(value), 'utf8') + 1; + } + } + } + + return 0; + } + + var BSON = {}; + + // BSON MAX VALUES + BSON.BSON_INT32_MAX = 0x7fffffff; + BSON.BSON_INT32_MIN = -0x80000000; + + // JS MAX PRECISE VALUES + BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. + BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. + + module.exports = calculateObjectSize; + /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(334).Buffer)) + +/***/ }) +/******/ ]) +}); +; \ No newline at end of file diff --git a/scripts/2.5/node_modules/bson/browser_build/package.json b/scripts/2.5/node_modules/bson/browser_build/package.json new file mode 100644 index 00000000..980db7f9 --- /dev/null +++ b/scripts/2.5/node_modules/bson/browser_build/package.json @@ -0,0 +1,8 @@ +{ "name" : "bson" +, "description" : "A bson parser for node.js and the browser" +, "main": "../" +, "directories" : { "lib" : "../lib/bson" } +, "engines" : { "node" : ">=0.6.0" } +, "licenses" : [ { "type" : "Apache License, Version 2.0" + , "url" : "http://www.apache.org/licenses/LICENSE-2.0" } ] +} diff --git a/scripts/2.5/node_modules/bson/index.js b/scripts/2.5/node_modules/bson/index.js new file mode 100644 index 00000000..6502552d --- /dev/null +++ b/scripts/2.5/node_modules/bson/index.js @@ -0,0 +1,46 @@ +var BSON = require('./lib/bson/bson'), + Binary = require('./lib/bson/binary'), + Code = require('./lib/bson/code'), + DBRef = require('./lib/bson/db_ref'), + Decimal128 = require('./lib/bson/decimal128'), + Double = require('./lib/bson/double'), + Int32 = require('./lib/bson/int_32'), + Long = require('./lib/bson/long'), + Map = require('./lib/bson/map'), + MaxKey = require('./lib/bson/max_key'), + MinKey = require('./lib/bson/min_key'), + ObjectId = require('./lib/bson/objectid'), + BSONRegExp = require('./lib/bson/regexp'), + Symbol = require('./lib/bson/symbol'), + Timestamp = require('./lib/bson/timestamp'); + +// BSON MAX VALUES +BSON.BSON_INT32_MAX = 0x7fffffff; +BSON.BSON_INT32_MIN = -0x80000000; + +BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; +BSON.BSON_INT64_MIN = -Math.pow(2, 63); + +// JS MAX PRECISE VALUES +BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. +BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. + +// Add BSON types to function creation +BSON.Binary = Binary; +BSON.Code = Code; +BSON.DBRef = DBRef; +BSON.Decimal128 = Decimal128; +BSON.Double = Double; +BSON.Int32 = Int32; +BSON.Long = Long; +BSON.Map = Map; +BSON.MaxKey = MaxKey; +BSON.MinKey = MinKey; +BSON.ObjectId = ObjectId; +BSON.ObjectID = ObjectId; +BSON.BSONRegExp = BSONRegExp; +BSON.Symbol = Symbol; +BSON.Timestamp = Timestamp; + +// Return the BSON +module.exports = BSON; diff --git a/scripts/2.5/node_modules/bson/lib/bson/binary.js b/scripts/2.5/node_modules/bson/lib/bson/binary.js new file mode 100644 index 00000000..6d190bca --- /dev/null +++ b/scripts/2.5/node_modules/bson/lib/bson/binary.js @@ -0,0 +1,384 @@ +/** + * Module dependencies. + * @ignore + */ + +// Test if we're in Node via presence of "global" not absence of "window" +// to support hybrid environments like Electron +if (typeof global !== 'undefined') { + var Buffer = require('buffer').Buffer; // TODO just use global Buffer +} + +var utils = require('./parser/utils'); + +/** + * A class representation of the BSON Binary type. + * + * Sub types + * - **BSON.BSON_BINARY_SUBTYPE_DEFAULT**, default BSON type. + * - **BSON.BSON_BINARY_SUBTYPE_FUNCTION**, BSON function type. + * - **BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY**, BSON byte array type. + * - **BSON.BSON_BINARY_SUBTYPE_UUID**, BSON uuid type. + * - **BSON.BSON_BINARY_SUBTYPE_MD5**, BSON md5 type. + * - **BSON.BSON_BINARY_SUBTYPE_USER_DEFINED**, BSON user defined type. + * + * @class + * @param {Buffer} buffer a buffer object containing the binary data. + * @param {Number} [subType] the option binary type. + * @return {Binary} + */ +function Binary(buffer, subType) { + if (!(this instanceof Binary)) return new Binary(buffer, subType); + + if ( + buffer != null && + !(typeof buffer === 'string') && + !Buffer.isBuffer(buffer) && + !(buffer instanceof Uint8Array) && + !Array.isArray(buffer) + ) { + throw new Error('only String, Buffer, Uint8Array or Array accepted'); + } + + this._bsontype = 'Binary'; + + if (buffer instanceof Number) { + this.sub_type = buffer; + this.position = 0; + } else { + this.sub_type = subType == null ? BSON_BINARY_SUBTYPE_DEFAULT : subType; + this.position = 0; + } + + if (buffer != null && !(buffer instanceof Number)) { + // Only accept Buffer, Uint8Array or Arrays + if (typeof buffer === 'string') { + // Different ways of writing the length of the string for the different types + if (typeof Buffer !== 'undefined') { + this.buffer = utils.toBuffer(buffer); + } else if ( + typeof Uint8Array !== 'undefined' || + Object.prototype.toString.call(buffer) === '[object Array]' + ) { + this.buffer = writeStringToArray(buffer); + } else { + throw new Error('only String, Buffer, Uint8Array or Array accepted'); + } + } else { + this.buffer = buffer; + } + this.position = buffer.length; + } else { + if (typeof Buffer !== 'undefined') { + this.buffer = utils.allocBuffer(Binary.BUFFER_SIZE); + } else if (typeof Uint8Array !== 'undefined') { + this.buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE)); + } else { + this.buffer = new Array(Binary.BUFFER_SIZE); + } + // Set position to start of buffer + this.position = 0; + } +} + +/** + * Updates this binary with byte_value. + * + * @method + * @param {string} byte_value a single byte we wish to write. + */ +Binary.prototype.put = function put(byte_value) { + // If it's a string and a has more than one character throw an error + if (byte_value['length'] != null && typeof byte_value !== 'number' && byte_value.length !== 1) + throw new Error('only accepts single character String, Uint8Array or Array'); + if ((typeof byte_value !== 'number' && byte_value < 0) || byte_value > 255) + throw new Error('only accepts number in a valid unsigned byte range 0-255'); + + // Decode the byte value once + var decoded_byte = null; + if (typeof byte_value === 'string') { + decoded_byte = byte_value.charCodeAt(0); + } else if (byte_value['length'] != null) { + decoded_byte = byte_value[0]; + } else { + decoded_byte = byte_value; + } + + if (this.buffer.length > this.position) { + this.buffer[this.position++] = decoded_byte; + } else { + if (typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer)) { + // Create additional overflow buffer + var buffer = utils.allocBuffer(Binary.BUFFER_SIZE + this.buffer.length); + // Combine the two buffers together + this.buffer.copy(buffer, 0, 0, this.buffer.length); + this.buffer = buffer; + this.buffer[this.position++] = decoded_byte; + } else { + buffer = null; + // Create a new buffer (typed or normal array) + if (Object.prototype.toString.call(this.buffer) === '[object Uint8Array]') { + buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE + this.buffer.length)); + } else { + buffer = new Array(Binary.BUFFER_SIZE + this.buffer.length); + } + + // We need to copy all the content to the new array + for (var i = 0; i < this.buffer.length; i++) { + buffer[i] = this.buffer[i]; + } + + // Reassign the buffer + this.buffer = buffer; + // Write the byte + this.buffer[this.position++] = decoded_byte; + } + } +}; + +/** + * Writes a buffer or string to the binary. + * + * @method + * @param {(Buffer|string)} string a string or buffer to be written to the Binary BSON object. + * @param {number} offset specify the binary of where to write the content. + * @return {null} + */ +Binary.prototype.write = function write(string, offset) { + offset = typeof offset === 'number' ? offset : this.position; + + // If the buffer is to small let's extend the buffer + if (this.buffer.length < offset + string.length) { + var buffer = null; + // If we are in node.js + if (typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer)) { + buffer = utils.allocBuffer(this.buffer.length + string.length); + this.buffer.copy(buffer, 0, 0, this.buffer.length); + } else if (Object.prototype.toString.call(this.buffer) === '[object Uint8Array]') { + // Create a new buffer + buffer = new Uint8Array(new ArrayBuffer(this.buffer.length + string.length)); + // Copy the content + for (var i = 0; i < this.position; i++) { + buffer[i] = this.buffer[i]; + } + } + + // Assign the new buffer + this.buffer = buffer; + } + + if (typeof Buffer !== 'undefined' && Buffer.isBuffer(string) && Buffer.isBuffer(this.buffer)) { + string.copy(this.buffer, offset, 0, string.length); + this.position = offset + string.length > this.position ? offset + string.length : this.position; + // offset = string.length + } else if ( + typeof Buffer !== 'undefined' && + typeof string === 'string' && + Buffer.isBuffer(this.buffer) + ) { + this.buffer.write(string, offset, 'binary'); + this.position = offset + string.length > this.position ? offset + string.length : this.position; + // offset = string.length; + } else if ( + Object.prototype.toString.call(string) === '[object Uint8Array]' || + (Object.prototype.toString.call(string) === '[object Array]' && typeof string !== 'string') + ) { + for (i = 0; i < string.length; i++) { + this.buffer[offset++] = string[i]; + } + + this.position = offset > this.position ? offset : this.position; + } else if (typeof string === 'string') { + for (i = 0; i < string.length; i++) { + this.buffer[offset++] = string.charCodeAt(i); + } + + this.position = offset > this.position ? offset : this.position; + } +}; + +/** + * Reads **length** bytes starting at **position**. + * + * @method + * @param {number} position read from the given position in the Binary. + * @param {number} length the number of bytes to read. + * @return {Buffer} + */ +Binary.prototype.read = function read(position, length) { + length = length && length > 0 ? length : this.position; + + // Let's return the data based on the type we have + if (this.buffer['slice']) { + return this.buffer.slice(position, position + length); + } else { + // Create a buffer to keep the result + var buffer = + typeof Uint8Array !== 'undefined' + ? new Uint8Array(new ArrayBuffer(length)) + : new Array(length); + for (var i = 0; i < length; i++) { + buffer[i] = this.buffer[position++]; + } + } + // Return the buffer + return buffer; +}; + +/** + * Returns the value of this binary as a string. + * + * @method + * @return {string} + */ +Binary.prototype.value = function value(asRaw) { + asRaw = asRaw == null ? false : asRaw; + + // Optimize to serialize for the situation where the data == size of buffer + if ( + asRaw && + typeof Buffer !== 'undefined' && + Buffer.isBuffer(this.buffer) && + this.buffer.length === this.position + ) + return this.buffer; + + // If it's a node.js buffer object + if (typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer)) { + return asRaw + ? this.buffer.slice(0, this.position) + : this.buffer.toString('binary', 0, this.position); + } else { + if (asRaw) { + // we support the slice command use it + if (this.buffer['slice'] != null) { + return this.buffer.slice(0, this.position); + } else { + // Create a new buffer to copy content to + var newBuffer = + Object.prototype.toString.call(this.buffer) === '[object Uint8Array]' + ? new Uint8Array(new ArrayBuffer(this.position)) + : new Array(this.position); + // Copy content + for (var i = 0; i < this.position; i++) { + newBuffer[i] = this.buffer[i]; + } + // Return the buffer + return newBuffer; + } + } else { + return convertArraytoUtf8BinaryString(this.buffer, 0, this.position); + } + } +}; + +/** + * Length. + * + * @method + * @return {number} the length of the binary. + */ +Binary.prototype.length = function length() { + return this.position; +}; + +/** + * @ignore + */ +Binary.prototype.toJSON = function() { + return this.buffer != null ? this.buffer.toString('base64') : ''; +}; + +/** + * @ignore + */ +Binary.prototype.toString = function(format) { + return this.buffer != null ? this.buffer.slice(0, this.position).toString(format) : ''; +}; + +/** + * Binary default subtype + * @ignore + */ +var BSON_BINARY_SUBTYPE_DEFAULT = 0; + +/** + * @ignore + */ +var writeStringToArray = function(data) { + // Create a buffer + var buffer = + typeof Uint8Array !== 'undefined' + ? new Uint8Array(new ArrayBuffer(data.length)) + : new Array(data.length); + // Write the content to the buffer + for (var i = 0; i < data.length; i++) { + buffer[i] = data.charCodeAt(i); + } + // Write the string to the buffer + return buffer; +}; + +/** + * Convert Array ot Uint8Array to Binary String + * + * @ignore + */ +var convertArraytoUtf8BinaryString = function(byteArray, startIndex, endIndex) { + var result = ''; + for (var i = startIndex; i < endIndex; i++) { + result = result + String.fromCharCode(byteArray[i]); + } + return result; +}; + +Binary.BUFFER_SIZE = 256; + +/** + * Default BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_DEFAULT = 0; +/** + * Function BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_FUNCTION = 1; +/** + * Byte Array BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_BYTE_ARRAY = 2; +/** + * OLD UUID BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_UUID_OLD = 3; +/** + * UUID BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_UUID = 4; +/** + * MD5 BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_MD5 = 5; +/** + * User BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_USER_DEFINED = 128; + +/** + * Expose. + */ +module.exports = Binary; +module.exports.Binary = Binary; diff --git a/scripts/2.5/node_modules/bson/lib/bson/bson.js b/scripts/2.5/node_modules/bson/lib/bson/bson.js new file mode 100644 index 00000000..912c5b92 --- /dev/null +++ b/scripts/2.5/node_modules/bson/lib/bson/bson.js @@ -0,0 +1,386 @@ +'use strict'; + +var Map = require('./map'), + Long = require('./long'), + Double = require('./double'), + Timestamp = require('./timestamp'), + ObjectID = require('./objectid'), + BSONRegExp = require('./regexp'), + Symbol = require('./symbol'), + Int32 = require('./int_32'), + Code = require('./code'), + Decimal128 = require('./decimal128'), + MinKey = require('./min_key'), + MaxKey = require('./max_key'), + DBRef = require('./db_ref'), + Binary = require('./binary'); + +// Parts of the parser +var deserialize = require('./parser/deserializer'), + serializer = require('./parser/serializer'), + calculateObjectSize = require('./parser/calculate_size'), + utils = require('./parser/utils'); + +/** + * @ignore + * @api private + */ +// Default Max Size +var MAXSIZE = 1024 * 1024 * 17; + +// Current Internal Temporary Serialization Buffer +var buffer = utils.allocBuffer(MAXSIZE); + +var BSON = function() {}; + +/** + * Serialize a Javascript object. + * + * @param {Object} object the Javascript object to serialize. + * @param {Boolean} [options.checkKeys] the serializer will check if keys are valid. + * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. + * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. + * @param {Number} [options.minInternalBufferSize=1024*1024*17] minimum size of the internal temporary serialization buffer **(default:1024*1024*17)**. + * @return {Buffer} returns the Buffer object containing the serialized object. + * @api public + */ +BSON.prototype.serialize = function serialize(object, options) { + options = options || {}; + // Unpack the options + var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; + var serializeFunctions = + typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + var ignoreUndefined = + typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; + var minInternalBufferSize = + typeof options.minInternalBufferSize === 'number' ? options.minInternalBufferSize : MAXSIZE; + + // Resize the internal serialization buffer if needed + if (buffer.length < minInternalBufferSize) { + buffer = utils.allocBuffer(minInternalBufferSize); + } + + // Attempt to serialize + var serializationIndex = serializer( + buffer, + object, + checkKeys, + 0, + 0, + serializeFunctions, + ignoreUndefined, + [] + ); + // Create the final buffer + var finishedBuffer = utils.allocBuffer(serializationIndex); + // Copy into the finished buffer + buffer.copy(finishedBuffer, 0, 0, finishedBuffer.length); + // Return the buffer + return finishedBuffer; +}; + +/** + * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. + * + * @param {Object} object the Javascript object to serialize. + * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. + * @param {Boolean} [options.checkKeys] the serializer will check if keys are valid. + * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. + * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. + * @param {Number} [options.index] the index in the buffer where we wish to start serializing into. + * @return {Number} returns the index pointing to the last written byte in the buffer. + * @api public + */ +BSON.prototype.serializeWithBufferAndIndex = function(object, finalBuffer, options) { + options = options || {}; + // Unpack the options + var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; + var serializeFunctions = + typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + var ignoreUndefined = + typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; + var startIndex = typeof options.index === 'number' ? options.index : 0; + + // Attempt to serialize + var serializationIndex = serializer( + finalBuffer, + object, + checkKeys, + startIndex || 0, + 0, + serializeFunctions, + ignoreUndefined + ); + + // Return the index + return serializationIndex - 1; +}; + +/** + * Deserialize data as BSON. + * + * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. + * @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized. + * @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse. + * @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function. + * @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits + * @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a node.js Buffer instance. + * @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types. + * @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer. + * @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances. + * @return {Object} returns the deserialized Javascript Object. + * @api public + */ +BSON.prototype.deserialize = function(buffer, options) { + return deserialize(buffer, options); +}; + +/** + * Calculate the bson size for a passed in Javascript object. + * + * @param {Object} object the Javascript object to calculate the BSON byte size for. + * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. + * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. + * @return {Number} returns the number of bytes the BSON object will take up. + * @api public + */ +BSON.prototype.calculateObjectSize = function(object, options) { + options = options || {}; + + var serializeFunctions = + typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + var ignoreUndefined = + typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; + + return calculateObjectSize(object, serializeFunctions, ignoreUndefined); +}; + +/** + * Deserialize stream data as BSON documents. + * + * @param {Buffer} data the buffer containing the serialized set of BSON documents. + * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. + * @param {Number} numberOfDocuments number of documents to deserialize. + * @param {Array} documents an array where to store the deserialized documents. + * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. + * @param {Object} [options] additional options used for the deserialization. + * @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized. + * @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse. + * @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function. + * @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits + * @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a node.js Buffer instance. + * @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types. + * @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer. + * @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances. + * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. + * @api public + */ +BSON.prototype.deserializeStream = function( + data, + startIndex, + numberOfDocuments, + documents, + docStartIndex, + options +) { + options = options != null ? options : {}; + var index = startIndex; + // Loop over all documents + for (var i = 0; i < numberOfDocuments; i++) { + // Find size of the document + var size = + data[index] | (data[index + 1] << 8) | (data[index + 2] << 16) | (data[index + 3] << 24); + // Update options with index + options['index'] = index; + // Parse the document at this point + documents[docStartIndex + i] = this.deserialize(data, options); + // Adjust index by the document size + index = index + size; + } + + // Return object containing end index of parsing and list of documents + return index; +}; + +/** + * @ignore + * @api private + */ +// BSON MAX VALUES +BSON.BSON_INT32_MAX = 0x7fffffff; +BSON.BSON_INT32_MIN = -0x80000000; + +BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; +BSON.BSON_INT64_MIN = -Math.pow(2, 63); + +// JS MAX PRECISE VALUES +BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. +BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. + +// Internal long versions +// var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. +// var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. + +/** + * Number BSON Type + * + * @classconstant BSON_DATA_NUMBER + **/ +BSON.BSON_DATA_NUMBER = 1; +/** + * String BSON Type + * + * @classconstant BSON_DATA_STRING + **/ +BSON.BSON_DATA_STRING = 2; +/** + * Object BSON Type + * + * @classconstant BSON_DATA_OBJECT + **/ +BSON.BSON_DATA_OBJECT = 3; +/** + * Array BSON Type + * + * @classconstant BSON_DATA_ARRAY + **/ +BSON.BSON_DATA_ARRAY = 4; +/** + * Binary BSON Type + * + * @classconstant BSON_DATA_BINARY + **/ +BSON.BSON_DATA_BINARY = 5; +/** + * ObjectID BSON Type + * + * @classconstant BSON_DATA_OID + **/ +BSON.BSON_DATA_OID = 7; +/** + * Boolean BSON Type + * + * @classconstant BSON_DATA_BOOLEAN + **/ +BSON.BSON_DATA_BOOLEAN = 8; +/** + * Date BSON Type + * + * @classconstant BSON_DATA_DATE + **/ +BSON.BSON_DATA_DATE = 9; +/** + * null BSON Type + * + * @classconstant BSON_DATA_NULL + **/ +BSON.BSON_DATA_NULL = 10; +/** + * RegExp BSON Type + * + * @classconstant BSON_DATA_REGEXP + **/ +BSON.BSON_DATA_REGEXP = 11; +/** + * Code BSON Type + * + * @classconstant BSON_DATA_CODE + **/ +BSON.BSON_DATA_CODE = 13; +/** + * Symbol BSON Type + * + * @classconstant BSON_DATA_SYMBOL + **/ +BSON.BSON_DATA_SYMBOL = 14; +/** + * Code with Scope BSON Type + * + * @classconstant BSON_DATA_CODE_W_SCOPE + **/ +BSON.BSON_DATA_CODE_W_SCOPE = 15; +/** + * 32 bit Integer BSON Type + * + * @classconstant BSON_DATA_INT + **/ +BSON.BSON_DATA_INT = 16; +/** + * Timestamp BSON Type + * + * @classconstant BSON_DATA_TIMESTAMP + **/ +BSON.BSON_DATA_TIMESTAMP = 17; +/** + * Long BSON Type + * + * @classconstant BSON_DATA_LONG + **/ +BSON.BSON_DATA_LONG = 18; +/** + * MinKey BSON Type + * + * @classconstant BSON_DATA_MIN_KEY + **/ +BSON.BSON_DATA_MIN_KEY = 0xff; +/** + * MaxKey BSON Type + * + * @classconstant BSON_DATA_MAX_KEY + **/ +BSON.BSON_DATA_MAX_KEY = 0x7f; + +/** + * Binary Default Type + * + * @classconstant BSON_BINARY_SUBTYPE_DEFAULT + **/ +BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; +/** + * Binary Function Type + * + * @classconstant BSON_BINARY_SUBTYPE_FUNCTION + **/ +BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; +/** + * Binary Byte Array Type + * + * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY + **/ +BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; +/** + * Binary UUID Type + * + * @classconstant BSON_BINARY_SUBTYPE_UUID + **/ +BSON.BSON_BINARY_SUBTYPE_UUID = 3; +/** + * Binary MD5 Type + * + * @classconstant BSON_BINARY_SUBTYPE_MD5 + **/ +BSON.BSON_BINARY_SUBTYPE_MD5 = 4; +/** + * Binary User Defined Type + * + * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED + **/ +BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; + +// Return BSON +module.exports = BSON; +module.exports.Code = Code; +module.exports.Map = Map; +module.exports.Symbol = Symbol; +module.exports.BSON = BSON; +module.exports.DBRef = DBRef; +module.exports.Binary = Binary; +module.exports.ObjectID = ObjectID; +module.exports.Long = Long; +module.exports.Timestamp = Timestamp; +module.exports.Double = Double; +module.exports.Int32 = Int32; +module.exports.MinKey = MinKey; +module.exports.MaxKey = MaxKey; +module.exports.BSONRegExp = BSONRegExp; +module.exports.Decimal128 = Decimal128; diff --git a/scripts/2.5/node_modules/bson/lib/bson/code.js b/scripts/2.5/node_modules/bson/lib/bson/code.js new file mode 100644 index 00000000..c2984cd5 --- /dev/null +++ b/scripts/2.5/node_modules/bson/lib/bson/code.js @@ -0,0 +1,24 @@ +/** + * A class representation of the BSON Code type. + * + * @class + * @param {(string|function)} code a string or function. + * @param {Object} [scope] an optional scope for the function. + * @return {Code} + */ +var Code = function Code(code, scope) { + if (!(this instanceof Code)) return new Code(code, scope); + this._bsontype = 'Code'; + this.code = code; + this.scope = scope; +}; + +/** + * @ignore + */ +Code.prototype.toJSON = function() { + return { scope: this.scope, code: this.code }; +}; + +module.exports = Code; +module.exports.Code = Code; diff --git a/scripts/2.5/node_modules/bson/lib/bson/db_ref.js b/scripts/2.5/node_modules/bson/lib/bson/db_ref.js new file mode 100644 index 00000000..f95795b1 --- /dev/null +++ b/scripts/2.5/node_modules/bson/lib/bson/db_ref.js @@ -0,0 +1,32 @@ +/** + * A class representation of the BSON DBRef type. + * + * @class + * @param {string} namespace the collection name. + * @param {ObjectID} oid the reference ObjectID. + * @param {string} [db] optional db name, if omitted the reference is local to the current db. + * @return {DBRef} + */ +function DBRef(namespace, oid, db) { + if (!(this instanceof DBRef)) return new DBRef(namespace, oid, db); + + this._bsontype = 'DBRef'; + this.namespace = namespace; + this.oid = oid; + this.db = db; +} + +/** + * @ignore + * @api private + */ +DBRef.prototype.toJSON = function() { + return { + $ref: this.namespace, + $id: this.oid, + $db: this.db == null ? '' : this.db + }; +}; + +module.exports = DBRef; +module.exports.DBRef = DBRef; diff --git a/scripts/2.5/node_modules/bson/lib/bson/decimal128.js b/scripts/2.5/node_modules/bson/lib/bson/decimal128.js new file mode 100644 index 00000000..924513f4 --- /dev/null +++ b/scripts/2.5/node_modules/bson/lib/bson/decimal128.js @@ -0,0 +1,820 @@ +'use strict'; + +var Long = require('./long'); + +var PARSE_STRING_REGEXP = /^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/; +var PARSE_INF_REGEXP = /^(\+|-)?(Infinity|inf)$/i; +var PARSE_NAN_REGEXP = /^(\+|-)?NaN$/i; + +var EXPONENT_MAX = 6111; +var EXPONENT_MIN = -6176; +var EXPONENT_BIAS = 6176; +var MAX_DIGITS = 34; + +// Nan value bits as 32 bit values (due to lack of longs) +var NAN_BUFFER = [ + 0x7c, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00 +].reverse(); +// Infinity value bits 32 bit values (due to lack of longs) +var INF_NEGATIVE_BUFFER = [ + 0xf8, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00 +].reverse(); +var INF_POSITIVE_BUFFER = [ + 0x78, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00 +].reverse(); + +var EXPONENT_REGEX = /^([-+])?(\d+)?$/; + +var utils = require('./parser/utils'); + +// Detect if the value is a digit +var isDigit = function(value) { + return !isNaN(parseInt(value, 10)); +}; + +// Divide two uint128 values +var divideu128 = function(value) { + var DIVISOR = Long.fromNumber(1000 * 1000 * 1000); + var _rem = Long.fromNumber(0); + var i = 0; + + if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) { + return { quotient: value, rem: _rem }; + } + + for (i = 0; i <= 3; i++) { + // Adjust remainder to match value of next dividend + _rem = _rem.shiftLeft(32); + // Add the divided to _rem + _rem = _rem.add(new Long(value.parts[i], 0)); + value.parts[i] = _rem.div(DIVISOR).low_; + _rem = _rem.modulo(DIVISOR); + } + + return { quotient: value, rem: _rem }; +}; + +// Multiply two Long values and return the 128 bit value +var multiply64x2 = function(left, right) { + if (!left && !right) { + return { high: Long.fromNumber(0), low: Long.fromNumber(0) }; + } + + var leftHigh = left.shiftRightUnsigned(32); + var leftLow = new Long(left.getLowBits(), 0); + var rightHigh = right.shiftRightUnsigned(32); + var rightLow = new Long(right.getLowBits(), 0); + + var productHigh = leftHigh.multiply(rightHigh); + var productMid = leftHigh.multiply(rightLow); + var productMid2 = leftLow.multiply(rightHigh); + var productLow = leftLow.multiply(rightLow); + + productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); + productMid = new Long(productMid.getLowBits(), 0) + .add(productMid2) + .add(productLow.shiftRightUnsigned(32)); + + productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); + productLow = productMid.shiftLeft(32).add(new Long(productLow.getLowBits(), 0)); + + // Return the 128 bit result + return { high: productHigh, low: productLow }; +}; + +var lessThan = function(left, right) { + // Make values unsigned + var uhleft = left.high_ >>> 0; + var uhright = right.high_ >>> 0; + + // Compare high bits first + if (uhleft < uhright) { + return true; + } else if (uhleft === uhright) { + var ulleft = left.low_ >>> 0; + var ulright = right.low_ >>> 0; + if (ulleft < ulright) return true; + } + + return false; +}; + +// var longtoHex = function(value) { +// var buffer = utils.allocBuffer(8); +// var index = 0; +// // Encode the low 64 bits of the decimal +// // Encode low bits +// buffer[index++] = value.low_ & 0xff; +// buffer[index++] = (value.low_ >> 8) & 0xff; +// buffer[index++] = (value.low_ >> 16) & 0xff; +// buffer[index++] = (value.low_ >> 24) & 0xff; +// // Encode high bits +// buffer[index++] = value.high_ & 0xff; +// buffer[index++] = (value.high_ >> 8) & 0xff; +// buffer[index++] = (value.high_ >> 16) & 0xff; +// buffer[index++] = (value.high_ >> 24) & 0xff; +// return buffer.reverse().toString('hex'); +// }; + +// var int32toHex = function(value) { +// var buffer = utils.allocBuffer(4); +// var index = 0; +// // Encode the low 64 bits of the decimal +// // Encode low bits +// buffer[index++] = value & 0xff; +// buffer[index++] = (value >> 8) & 0xff; +// buffer[index++] = (value >> 16) & 0xff; +// buffer[index++] = (value >> 24) & 0xff; +// return buffer.reverse().toString('hex'); +// }; + +/** + * A class representation of the BSON Decimal128 type. + * + * @class + * @param {Buffer} bytes a buffer containing the raw Decimal128 bytes. + * @return {Double} + */ +var Decimal128 = function(bytes) { + this._bsontype = 'Decimal128'; + this.bytes = bytes; +}; + +/** + * Create a Decimal128 instance from a string representation + * + * @method + * @param {string} string a numeric string representation. + * @return {Decimal128} returns a Decimal128 instance. + */ +Decimal128.fromString = function(string) { + // Parse state tracking + var isNegative = false; + var sawRadix = false; + var foundNonZero = false; + + // Total number of significant digits (no leading or trailing zero) + var significantDigits = 0; + // Total number of significand digits read + var nDigitsRead = 0; + // Total number of digits (no leading zeros) + var nDigits = 0; + // The number of the digits after radix + var radixPosition = 0; + // The index of the first non-zero in *str* + var firstNonZero = 0; + + // Digits Array + var digits = [0]; + // The number of digits in digits + var nDigitsStored = 0; + // Insertion pointer for digits + var digitsInsert = 0; + // The index of the first non-zero digit + var firstDigit = 0; + // The index of the last digit + var lastDigit = 0; + + // Exponent + var exponent = 0; + // loop index over array + var i = 0; + // The high 17 digits of the significand + var significandHigh = [0, 0]; + // The low 17 digits of the significand + var significandLow = [0, 0]; + // The biased exponent + var biasedExponent = 0; + + // Read index + var index = 0; + + // Trim the string + string = string.trim(); + + // Naively prevent against REDOS attacks. + // TODO: implementing a custom parsing for this, or refactoring the regex would yield + // further gains. + if (string.length >= 7000) { + throw new Error('' + string + ' not a valid Decimal128 string'); + } + + // Results + var stringMatch = string.match(PARSE_STRING_REGEXP); + var infMatch = string.match(PARSE_INF_REGEXP); + var nanMatch = string.match(PARSE_NAN_REGEXP); + + // Validate the string + if ((!stringMatch && !infMatch && !nanMatch) || string.length === 0) { + throw new Error('' + string + ' not a valid Decimal128 string'); + } + + // Check if we have an illegal exponent format + if (stringMatch && stringMatch[4] && stringMatch[2] === undefined) { + throw new Error('' + string + ' not a valid Decimal128 string'); + } + + // Get the negative or positive sign + if (string[index] === '+' || string[index] === '-') { + isNegative = string[index++] === '-'; + } + + // Check if user passed Infinity or NaN + if (!isDigit(string[index]) && string[index] !== '.') { + if (string[index] === 'i' || string[index] === 'I') { + return new Decimal128(utils.toBuffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); + } else if (string[index] === 'N') { + return new Decimal128(utils.toBuffer(NAN_BUFFER)); + } + } + + // Read all the digits + while (isDigit(string[index]) || string[index] === '.') { + if (string[index] === '.') { + if (sawRadix) { + return new Decimal128(utils.toBuffer(NAN_BUFFER)); + } + + sawRadix = true; + index = index + 1; + continue; + } + + if (nDigitsStored < 34) { + if (string[index] !== '0' || foundNonZero) { + if (!foundNonZero) { + firstNonZero = nDigitsRead; + } + + foundNonZero = true; + + // Only store 34 digits + digits[digitsInsert++] = parseInt(string[index], 10); + nDigitsStored = nDigitsStored + 1; + } + } + + if (foundNonZero) { + nDigits = nDigits + 1; + } + + if (sawRadix) { + radixPosition = radixPosition + 1; + } + + nDigitsRead = nDigitsRead + 1; + index = index + 1; + } + + if (sawRadix && !nDigitsRead) { + throw new Error('' + string + ' not a valid Decimal128 string'); + } + + // Read exponent if exists + if (string[index] === 'e' || string[index] === 'E') { + // Read exponent digits + var match = string.substr(++index).match(EXPONENT_REGEX); + + // No digits read + if (!match || !match[2]) { + return new Decimal128(utils.toBuffer(NAN_BUFFER)); + } + + // Get exponent + exponent = parseInt(match[0], 10); + + // Adjust the index + index = index + match[0].length; + } + + // Return not a number + if (string[index]) { + return new Decimal128(utils.toBuffer(NAN_BUFFER)); + } + + // Done reading input + // Find first non-zero digit in digits + firstDigit = 0; + + if (!nDigitsStored) { + firstDigit = 0; + lastDigit = 0; + digits[0] = 0; + nDigits = 1; + nDigitsStored = 1; + significantDigits = 0; + } else { + lastDigit = nDigitsStored - 1; + significantDigits = nDigits; + + if (exponent !== 0 && significantDigits !== 1) { + while (string[firstNonZero + significantDigits - 1] === '0') { + significantDigits = significantDigits - 1; + } + } + } + + // Normalization of exponent + // Correct exponent based on radix position, and shift significand as needed + // to represent user input + + // Overflow prevention + if (exponent <= radixPosition && radixPosition - exponent > 1 << 14) { + exponent = EXPONENT_MIN; + } else { + exponent = exponent - radixPosition; + } + + // Attempt to normalize the exponent + while (exponent > EXPONENT_MAX) { + // Shift exponent to significand and decrease + lastDigit = lastDigit + 1; + + if (lastDigit - firstDigit > MAX_DIGITS) { + // Check if we have a zero then just hard clamp, otherwise fail + var digitsString = digits.join(''); + if (digitsString.match(/^0+$/)) { + exponent = EXPONENT_MAX; + break; + } else { + return new Decimal128(utils.toBuffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); + } + } + + exponent = exponent - 1; + } + + while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) { + // Shift last digit + if (lastDigit === 0) { + exponent = EXPONENT_MIN; + significantDigits = 0; + break; + } + + if (nDigitsStored < nDigits) { + // adjust to match digits not stored + nDigits = nDigits - 1; + } else { + // adjust to round + lastDigit = lastDigit - 1; + } + + if (exponent < EXPONENT_MAX) { + exponent = exponent + 1; + } else { + // Check if we have a zero then just hard clamp, otherwise fail + digitsString = digits.join(''); + if (digitsString.match(/^0+$/)) { + exponent = EXPONENT_MAX; + break; + } else { + return new Decimal128(utils.toBuffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); + } + } + } + + // Round + // We've normalized the exponent, but might still need to round. + if (lastDigit - firstDigit + 1 < significantDigits && string[significantDigits] !== '0') { + var endOfString = nDigitsRead; + + // If we have seen a radix point, 'string' is 1 longer than we have + // documented with ndigits_read, so inc the position of the first nonzero + // digit and the position that digits are read to. + if (sawRadix && exponent === EXPONENT_MIN) { + firstNonZero = firstNonZero + 1; + endOfString = endOfString + 1; + } + + var roundDigit = parseInt(string[firstNonZero + lastDigit + 1], 10); + var roundBit = 0; + + if (roundDigit >= 5) { + roundBit = 1; + + if (roundDigit === 5) { + roundBit = digits[lastDigit] % 2 === 1; + + for (i = firstNonZero + lastDigit + 2; i < endOfString; i++) { + if (parseInt(string[i], 10)) { + roundBit = 1; + break; + } + } + } + } + + if (roundBit) { + var dIdx = lastDigit; + + for (; dIdx >= 0; dIdx--) { + if (++digits[dIdx] > 9) { + digits[dIdx] = 0; + + // overflowed most significant digit + if (dIdx === 0) { + if (exponent < EXPONENT_MAX) { + exponent = exponent + 1; + digits[dIdx] = 1; + } else { + return new Decimal128( + utils.toBuffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER) + ); + } + } + } else { + break; + } + } + } + } + + // Encode significand + // The high 17 digits of the significand + significandHigh = Long.fromNumber(0); + // The low 17 digits of the significand + significandLow = Long.fromNumber(0); + + // read a zero + if (significantDigits === 0) { + significandHigh = Long.fromNumber(0); + significandLow = Long.fromNumber(0); + } else if (lastDigit - firstDigit < 17) { + dIdx = firstDigit; + significandLow = Long.fromNumber(digits[dIdx++]); + significandHigh = new Long(0, 0); + + for (; dIdx <= lastDigit; dIdx++) { + significandLow = significandLow.multiply(Long.fromNumber(10)); + significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); + } + } else { + dIdx = firstDigit; + significandHigh = Long.fromNumber(digits[dIdx++]); + + for (; dIdx <= lastDigit - 17; dIdx++) { + significandHigh = significandHigh.multiply(Long.fromNumber(10)); + significandHigh = significandHigh.add(Long.fromNumber(digits[dIdx])); + } + + significandLow = Long.fromNumber(digits[dIdx++]); + + for (; dIdx <= lastDigit; dIdx++) { + significandLow = significandLow.multiply(Long.fromNumber(10)); + significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); + } + } + + var significand = multiply64x2(significandHigh, Long.fromString('100000000000000000')); + + significand.low = significand.low.add(significandLow); + + if (lessThan(significand.low, significandLow)) { + significand.high = significand.high.add(Long.fromNumber(1)); + } + + // Biased exponent + biasedExponent = exponent + EXPONENT_BIAS; + var dec = { low: Long.fromNumber(0), high: Long.fromNumber(0) }; + + // Encode combination, exponent, and significand. + if ( + significand.high + .shiftRightUnsigned(49) + .and(Long.fromNumber(1)) + .equals(Long.fromNumber) + ) { + // Encode '11' into bits 1 to 3 + dec.high = dec.high.or(Long.fromNumber(0x3).shiftLeft(61)); + dec.high = dec.high.or( + Long.fromNumber(biasedExponent).and(Long.fromNumber(0x3fff).shiftLeft(47)) + ); + dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x7fffffffffff))); + } else { + dec.high = dec.high.or(Long.fromNumber(biasedExponent & 0x3fff).shiftLeft(49)); + dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x1ffffffffffff))); + } + + dec.low = significand.low; + + // Encode sign + if (isNegative) { + dec.high = dec.high.or(Long.fromString('9223372036854775808')); + } + + // Encode into a buffer + var buffer = utils.allocBuffer(16); + index = 0; + + // Encode the low 64 bits of the decimal + // Encode low bits + buffer[index++] = dec.low.low_ & 0xff; + buffer[index++] = (dec.low.low_ >> 8) & 0xff; + buffer[index++] = (dec.low.low_ >> 16) & 0xff; + buffer[index++] = (dec.low.low_ >> 24) & 0xff; + // Encode high bits + buffer[index++] = dec.low.high_ & 0xff; + buffer[index++] = (dec.low.high_ >> 8) & 0xff; + buffer[index++] = (dec.low.high_ >> 16) & 0xff; + buffer[index++] = (dec.low.high_ >> 24) & 0xff; + + // Encode the high 64 bits of the decimal + // Encode low bits + buffer[index++] = dec.high.low_ & 0xff; + buffer[index++] = (dec.high.low_ >> 8) & 0xff; + buffer[index++] = (dec.high.low_ >> 16) & 0xff; + buffer[index++] = (dec.high.low_ >> 24) & 0xff; + // Encode high bits + buffer[index++] = dec.high.high_ & 0xff; + buffer[index++] = (dec.high.high_ >> 8) & 0xff; + buffer[index++] = (dec.high.high_ >> 16) & 0xff; + buffer[index++] = (dec.high.high_ >> 24) & 0xff; + + // Return the new Decimal128 + return new Decimal128(buffer); +}; + +// Extract least significant 5 bits +var COMBINATION_MASK = 0x1f; +// Extract least significant 14 bits +var EXPONENT_MASK = 0x3fff; +// Value of combination field for Inf +var COMBINATION_INFINITY = 30; +// Value of combination field for NaN +var COMBINATION_NAN = 31; +// Value of combination field for NaN +// var COMBINATION_SNAN = 32; +// decimal128 exponent bias +EXPONENT_BIAS = 6176; + +/** + * Create a string representation of the raw Decimal128 value + * + * @method + * @return {string} returns a Decimal128 string representation. + */ +Decimal128.prototype.toString = function() { + // Note: bits in this routine are referred to starting at 0, + // from the sign bit, towards the coefficient. + + // bits 0 - 31 + var high; + // bits 32 - 63 + var midh; + // bits 64 - 95 + var midl; + // bits 96 - 127 + var low; + // bits 1 - 5 + var combination; + // decoded biased exponent (14 bits) + var biased_exponent; + // the number of significand digits + var significand_digits = 0; + // the base-10 digits in the significand + var significand = new Array(36); + for (var i = 0; i < significand.length; i++) significand[i] = 0; + // read pointer into significand + var index = 0; + + // unbiased exponent + var exponent; + // the exponent if scientific notation is used + var scientific_exponent; + + // true if the number is zero + var is_zero = false; + + // the most signifcant significand bits (50-46) + var significand_msb; + // temporary storage for significand decoding + var significand128 = { parts: new Array(4) }; + // indexing variables + i; + var j, k; + + // Output string + var string = []; + + // Unpack index + index = 0; + + // Buffer reference + var buffer = this.bytes; + + // Unpack the low 64bits into a long + low = + buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + midl = + buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + + // Unpack the high 64bits into a long + midh = + buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + high = + buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + + // Unpack index + index = 0; + + // Create the state of the decimal + var dec = { + low: new Long(low, midl), + high: new Long(midh, high) + }; + + if (dec.high.lessThan(Long.ZERO)) { + string.push('-'); + } + + // Decode combination field and exponent + combination = (high >> 26) & COMBINATION_MASK; + + if (combination >> 3 === 3) { + // Check for 'special' values + if (combination === COMBINATION_INFINITY) { + return string.join('') + 'Infinity'; + } else if (combination === COMBINATION_NAN) { + return 'NaN'; + } else { + biased_exponent = (high >> 15) & EXPONENT_MASK; + significand_msb = 0x08 + ((high >> 14) & 0x01); + } + } else { + significand_msb = (high >> 14) & 0x07; + biased_exponent = (high >> 17) & EXPONENT_MASK; + } + + exponent = biased_exponent - EXPONENT_BIAS; + + // Create string of significand digits + + // Convert the 114-bit binary number represented by + // (significand_high, significand_low) to at most 34 decimal + // digits through modulo and division. + significand128.parts[0] = (high & 0x3fff) + ((significand_msb & 0xf) << 14); + significand128.parts[1] = midh; + significand128.parts[2] = midl; + significand128.parts[3] = low; + + if ( + significand128.parts[0] === 0 && + significand128.parts[1] === 0 && + significand128.parts[2] === 0 && + significand128.parts[3] === 0 + ) { + is_zero = true; + } else { + for (k = 3; k >= 0; k--) { + var least_digits = 0; + // Peform the divide + var result = divideu128(significand128); + significand128 = result.quotient; + least_digits = result.rem.low_; + + // We now have the 9 least significant digits (in base 2). + // Convert and output to string. + if (!least_digits) continue; + + for (j = 8; j >= 0; j--) { + // significand[k * 9 + j] = Math.round(least_digits % 10); + significand[k * 9 + j] = least_digits % 10; + // least_digits = Math.round(least_digits / 10); + least_digits = Math.floor(least_digits / 10); + } + } + } + + // Output format options: + // Scientific - [-]d.dddE(+/-)dd or [-]dE(+/-)dd + // Regular - ddd.ddd + + if (is_zero) { + significand_digits = 1; + significand[index] = 0; + } else { + significand_digits = 36; + i = 0; + + while (!significand[index]) { + i++; + significand_digits = significand_digits - 1; + index = index + 1; + } + } + + scientific_exponent = significand_digits - 1 + exponent; + + // The scientific exponent checks are dictated by the string conversion + // specification and are somewhat arbitrary cutoffs. + // + // We must check exponent > 0, because if this is the case, the number + // has trailing zeros. However, we *cannot* output these trailing zeros, + // because doing so would change the precision of the value, and would + // change stored data if the string converted number is round tripped. + + if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) { + // Scientific format + string.push(significand[index++]); + significand_digits = significand_digits - 1; + + if (significand_digits) { + string.push('.'); + } + + for (i = 0; i < significand_digits; i++) { + string.push(significand[index++]); + } + + // Exponent + string.push('E'); + if (scientific_exponent > 0) { + string.push('+' + scientific_exponent); + } else { + string.push(scientific_exponent); + } + } else { + // Regular format with no decimal place + if (exponent >= 0) { + for (i = 0; i < significand_digits; i++) { + string.push(significand[index++]); + } + } else { + var radix_position = significand_digits + exponent; + + // non-zero digits before radix + if (radix_position > 0) { + for (i = 0; i < radix_position; i++) { + string.push(significand[index++]); + } + } else { + string.push('0'); + } + + string.push('.'); + // add leading zeros after radix + while (radix_position++ < 0) { + string.push('0'); + } + + for (i = 0; i < significand_digits - Math.max(radix_position - 1, 0); i++) { + string.push(significand[index++]); + } + } + } + + return string.join(''); +}; + +Decimal128.prototype.toJSON = function() { + return { $numberDecimal: this.toString() }; +}; + +module.exports = Decimal128; +module.exports.Decimal128 = Decimal128; diff --git a/scripts/2.5/node_modules/bson/lib/bson/double.js b/scripts/2.5/node_modules/bson/lib/bson/double.js new file mode 100644 index 00000000..523c21f8 --- /dev/null +++ b/scripts/2.5/node_modules/bson/lib/bson/double.js @@ -0,0 +1,33 @@ +/** + * A class representation of the BSON Double type. + * + * @class + * @param {number} value the number we want to represent as a double. + * @return {Double} + */ +function Double(value) { + if (!(this instanceof Double)) return new Double(value); + + this._bsontype = 'Double'; + this.value = value; +} + +/** + * Access the number value. + * + * @method + * @return {number} returns the wrapped double number. + */ +Double.prototype.valueOf = function() { + return this.value; +}; + +/** + * @ignore + */ +Double.prototype.toJSON = function() { + return this.value; +}; + +module.exports = Double; +module.exports.Double = Double; diff --git a/scripts/2.5/node_modules/bson/lib/bson/float_parser.js b/scripts/2.5/node_modules/bson/lib/bson/float_parser.js new file mode 100644 index 00000000..0054a2f6 --- /dev/null +++ b/scripts/2.5/node_modules/bson/lib/bson/float_parser.js @@ -0,0 +1,124 @@ +// Copyright (c) 2008, Fair Oaks Labs, Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * Neither the name of Fair Oaks Labs, Inc. nor the names of its contributors +// may be used to endorse or promote products derived from this software +// without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// +// +// Modifications to writeIEEE754 to support negative zeroes made by Brian White + +var readIEEE754 = function(buffer, offset, endian, mLen, nBytes) { + var e, + m, + bBE = endian === 'big', + eLen = nBytes * 8 - mLen - 1, + eMax = (1 << eLen) - 1, + eBias = eMax >> 1, + nBits = -7, + i = bBE ? 0 : nBytes - 1, + d = bBE ? 1 : -1, + s = buffer[offset + i]; + + i += d; + + e = s & ((1 << -nBits) - 1); + s >>= -nBits; + nBits += eLen; + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8); + + m = e & ((1 << -nBits) - 1); + e >>= -nBits; + nBits += mLen; + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8); + + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : (s ? -1 : 1) * Infinity; + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen); +}; + +var writeIEEE754 = function(buffer, value, offset, endian, mLen, nBytes) { + var e, + m, + c, + bBE = endian === 'big', + eLen = nBytes * 8 - mLen - 1, + eMax = (1 << eLen) - 1, + eBias = eMax >> 1, + rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0, + i = bBE ? nBytes - 1 : 0, + d = bBE ? -1 : 1, + s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; + + value = Math.abs(value); + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8); + + e = (e << mLen) | m; + eLen += mLen; + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8); + + buffer[offset + i - d] |= s * 128; +}; + +exports.readIEEE754 = readIEEE754; +exports.writeIEEE754 = writeIEEE754; diff --git a/scripts/2.5/node_modules/bson/lib/bson/int_32.js b/scripts/2.5/node_modules/bson/lib/bson/int_32.js new file mode 100644 index 00000000..85dbdec6 --- /dev/null +++ b/scripts/2.5/node_modules/bson/lib/bson/int_32.js @@ -0,0 +1,33 @@ +/** + * A class representation of a BSON Int32 type. + * + * @class + * @param {number} value the number we want to represent as an int32. + * @return {Int32} + */ +var Int32 = function(value) { + if (!(this instanceof Int32)) return new Int32(value); + + this._bsontype = 'Int32'; + this.value = value; +}; + +/** + * Access the number value. + * + * @method + * @return {number} returns the wrapped int32 number. + */ +Int32.prototype.valueOf = function() { + return this.value; +}; + +/** + * @ignore + */ +Int32.prototype.toJSON = function() { + return this.value; +}; + +module.exports = Int32; +module.exports.Int32 = Int32; diff --git a/scripts/2.5/node_modules/bson/lib/bson/long.js b/scripts/2.5/node_modules/bson/lib/bson/long.js new file mode 100644 index 00000000..78215aa3 --- /dev/null +++ b/scripts/2.5/node_modules/bson/lib/bson/long.js @@ -0,0 +1,851 @@ +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Copyright 2009 Google Inc. All Rights Reserved + +/** + * Defines a Long class for representing a 64-bit two's-complement + * integer value, which faithfully simulates the behavior of a Java "Long". This + * implementation is derived from LongLib in GWT. + * + * Constructs a 64-bit two's-complement integer, given its low and high 32-bit + * values as *signed* integers. See the from* functions below for more + * convenient ways of constructing Longs. + * + * The internal representation of a Long is the two given signed, 32-bit values. + * We use 32-bit pieces because these are the size of integers on which + * Javascript performs bit-operations. For operations like addition and + * multiplication, we split each number into 16-bit pieces, which can easily be + * multiplied within Javascript's floating-point representation without overflow + * or change in sign. + * + * In the algorithms below, we frequently reduce the negative case to the + * positive case by negating the input(s) and then post-processing the result. + * Note that we must ALWAYS check specially whether those values are MIN_VALUE + * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as + * a positive number, it overflows back into a negative). Not handling this + * case would often result in infinite recursion. + * + * @class + * @param {number} low the low (signed) 32 bits of the Long. + * @param {number} high the high (signed) 32 bits of the Long. + * @return {Long} + */ +function Long(low, high) { + if (!(this instanceof Long)) return new Long(low, high); + + this._bsontype = 'Long'; + /** + * @type {number} + * @ignore + */ + this.low_ = low | 0; // force into 32 signed bits. + + /** + * @type {number} + * @ignore + */ + this.high_ = high | 0; // force into 32 signed bits. +} + +/** + * Return the int value. + * + * @method + * @return {number} the value, assuming it is a 32-bit integer. + */ +Long.prototype.toInt = function() { + return this.low_; +}; + +/** + * Return the Number value. + * + * @method + * @return {number} the closest floating-point representation to this value. + */ +Long.prototype.toNumber = function() { + return this.high_ * Long.TWO_PWR_32_DBL_ + this.getLowBitsUnsigned(); +}; + +/** + * Return the JSON value. + * + * @method + * @return {string} the JSON representation. + */ +Long.prototype.toJSON = function() { + return this.toString(); +}; + +/** + * Return the String value. + * + * @method + * @param {number} [opt_radix] the radix in which the text should be written. + * @return {string} the textual representation of this value. + */ +Long.prototype.toString = function(opt_radix) { + var radix = opt_radix || 10; + if (radix < 2 || 36 < radix) { + throw Error('radix out of range: ' + radix); + } + + if (this.isZero()) { + return '0'; + } + + if (this.isNegative()) { + if (this.equals(Long.MIN_VALUE)) { + // We need to change the Long value before it can be negated, so we remove + // the bottom-most digit in this base and then recurse to do the rest. + var radixLong = Long.fromNumber(radix); + var div = this.div(radixLong); + var rem = div.multiply(radixLong).subtract(this); + return div.toString(radix) + rem.toInt().toString(radix); + } else { + return '-' + this.negate().toString(radix); + } + } + + // Do several (6) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = Long.fromNumber(Math.pow(radix, 6)); + + rem = this; + var result = ''; + + while (!rem.isZero()) { + var remDiv = rem.div(radixToPower); + var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); + var digits = intval.toString(radix); + + rem = remDiv; + if (rem.isZero()) { + return digits + result; + } else { + while (digits.length < 6) { + digits = '0' + digits; + } + result = '' + digits + result; + } + } +}; + +/** + * Return the high 32-bits value. + * + * @method + * @return {number} the high 32-bits as a signed value. + */ +Long.prototype.getHighBits = function() { + return this.high_; +}; + +/** + * Return the low 32-bits value. + * + * @method + * @return {number} the low 32-bits as a signed value. + */ +Long.prototype.getLowBits = function() { + return this.low_; +}; + +/** + * Return the low unsigned 32-bits value. + * + * @method + * @return {number} the low 32-bits as an unsigned value. + */ +Long.prototype.getLowBitsUnsigned = function() { + return this.low_ >= 0 ? this.low_ : Long.TWO_PWR_32_DBL_ + this.low_; +}; + +/** + * Returns the number of bits needed to represent the absolute value of this Long. + * + * @method + * @return {number} Returns the number of bits needed to represent the absolute value of this Long. + */ +Long.prototype.getNumBitsAbs = function() { + if (this.isNegative()) { + if (this.equals(Long.MIN_VALUE)) { + return 64; + } else { + return this.negate().getNumBitsAbs(); + } + } else { + var val = this.high_ !== 0 ? this.high_ : this.low_; + for (var bit = 31; bit > 0; bit--) { + if ((val & (1 << bit)) !== 0) { + break; + } + } + return this.high_ !== 0 ? bit + 33 : bit + 1; + } +}; + +/** + * Return whether this value is zero. + * + * @method + * @return {boolean} whether this value is zero. + */ +Long.prototype.isZero = function() { + return this.high_ === 0 && this.low_ === 0; +}; + +/** + * Return whether this value is negative. + * + * @method + * @return {boolean} whether this value is negative. + */ +Long.prototype.isNegative = function() { + return this.high_ < 0; +}; + +/** + * Return whether this value is odd. + * + * @method + * @return {boolean} whether this value is odd. + */ +Long.prototype.isOdd = function() { + return (this.low_ & 1) === 1; +}; + +/** + * Return whether this Long equals the other + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long equals the other + */ +Long.prototype.equals = function(other) { + return this.high_ === other.high_ && this.low_ === other.low_; +}; + +/** + * Return whether this Long does not equal the other. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long does not equal the other. + */ +Long.prototype.notEquals = function(other) { + return this.high_ !== other.high_ || this.low_ !== other.low_; +}; + +/** + * Return whether this Long is less than the other. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long is less than the other. + */ +Long.prototype.lessThan = function(other) { + return this.compare(other) < 0; +}; + +/** + * Return whether this Long is less than or equal to the other. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long is less than or equal to the other. + */ +Long.prototype.lessThanOrEqual = function(other) { + return this.compare(other) <= 0; +}; + +/** + * Return whether this Long is greater than the other. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long is greater than the other. + */ +Long.prototype.greaterThan = function(other) { + return this.compare(other) > 0; +}; + +/** + * Return whether this Long is greater than or equal to the other. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long is greater than or equal to the other. + */ +Long.prototype.greaterThanOrEqual = function(other) { + return this.compare(other) >= 0; +}; + +/** + * Compares this Long with the given one. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. + */ +Long.prototype.compare = function(other) { + if (this.equals(other)) { + return 0; + } + + var thisNeg = this.isNegative(); + var otherNeg = other.isNegative(); + if (thisNeg && !otherNeg) { + return -1; + } + if (!thisNeg && otherNeg) { + return 1; + } + + // at this point, the signs are the same, so subtraction will not overflow + if (this.subtract(other).isNegative()) { + return -1; + } else { + return 1; + } +}; + +/** + * The negation of this value. + * + * @method + * @return {Long} the negation of this value. + */ +Long.prototype.negate = function() { + if (this.equals(Long.MIN_VALUE)) { + return Long.MIN_VALUE; + } else { + return this.not().add(Long.ONE); + } +}; + +/** + * Returns the sum of this and the given Long. + * + * @method + * @param {Long} other Long to add to this one. + * @return {Long} the sum of this and the given Long. + */ +Long.prototype.add = function(other) { + // Divide each number into 4 chunks of 16 bits, and then sum the chunks. + + var a48 = this.high_ >>> 16; + var a32 = this.high_ & 0xffff; + var a16 = this.low_ >>> 16; + var a00 = this.low_ & 0xffff; + + var b48 = other.high_ >>> 16; + var b32 = other.high_ & 0xffff; + var b16 = other.low_ >>> 16; + var b00 = other.low_ & 0xffff; + + var c48 = 0, + c32 = 0, + c16 = 0, + c00 = 0; + c00 += a00 + b00; + c16 += c00 >>> 16; + c00 &= 0xffff; + c16 += a16 + b16; + c32 += c16 >>> 16; + c16 &= 0xffff; + c32 += a32 + b32; + c48 += c32 >>> 16; + c32 &= 0xffff; + c48 += a48 + b48; + c48 &= 0xffff; + return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32); +}; + +/** + * Returns the difference of this and the given Long. + * + * @method + * @param {Long} other Long to subtract from this. + * @return {Long} the difference of this and the given Long. + */ +Long.prototype.subtract = function(other) { + return this.add(other.negate()); +}; + +/** + * Returns the product of this and the given Long. + * + * @method + * @param {Long} other Long to multiply with this. + * @return {Long} the product of this and the other. + */ +Long.prototype.multiply = function(other) { + if (this.isZero()) { + return Long.ZERO; + } else if (other.isZero()) { + return Long.ZERO; + } + + if (this.equals(Long.MIN_VALUE)) { + return other.isOdd() ? Long.MIN_VALUE : Long.ZERO; + } else if (other.equals(Long.MIN_VALUE)) { + return this.isOdd() ? Long.MIN_VALUE : Long.ZERO; + } + + if (this.isNegative()) { + if (other.isNegative()) { + return this.negate().multiply(other.negate()); + } else { + return this.negate() + .multiply(other) + .negate(); + } + } else if (other.isNegative()) { + return this.multiply(other.negate()).negate(); + } + + // If both Longs are small, use float multiplication + if (this.lessThan(Long.TWO_PWR_24_) && other.lessThan(Long.TWO_PWR_24_)) { + return Long.fromNumber(this.toNumber() * other.toNumber()); + } + + // Divide each Long into 4 chunks of 16 bits, and then add up 4x4 products. + // We can skip products that would overflow. + + var a48 = this.high_ >>> 16; + var a32 = this.high_ & 0xffff; + var a16 = this.low_ >>> 16; + var a00 = this.low_ & 0xffff; + + var b48 = other.high_ >>> 16; + var b32 = other.high_ & 0xffff; + var b16 = other.low_ >>> 16; + var b00 = other.low_ & 0xffff; + + var c48 = 0, + c32 = 0, + c16 = 0, + c00 = 0; + c00 += a00 * b00; + c16 += c00 >>> 16; + c00 &= 0xffff; + c16 += a16 * b00; + c32 += c16 >>> 16; + c16 &= 0xffff; + c16 += a00 * b16; + c32 += c16 >>> 16; + c16 &= 0xffff; + c32 += a32 * b00; + c48 += c32 >>> 16; + c32 &= 0xffff; + c32 += a16 * b16; + c48 += c32 >>> 16; + c32 &= 0xffff; + c32 += a00 * b32; + c48 += c32 >>> 16; + c32 &= 0xffff; + c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; + c48 &= 0xffff; + return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32); +}; + +/** + * Returns this Long divided by the given one. + * + * @method + * @param {Long} other Long by which to divide. + * @return {Long} this Long divided by the given one. + */ +Long.prototype.div = function(other) { + if (other.isZero()) { + throw Error('division by zero'); + } else if (this.isZero()) { + return Long.ZERO; + } + + if (this.equals(Long.MIN_VALUE)) { + if (other.equals(Long.ONE) || other.equals(Long.NEG_ONE)) { + return Long.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE + } else if (other.equals(Long.MIN_VALUE)) { + return Long.ONE; + } else { + // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. + var halfThis = this.shiftRight(1); + var approx = halfThis.div(other).shiftLeft(1); + if (approx.equals(Long.ZERO)) { + return other.isNegative() ? Long.ONE : Long.NEG_ONE; + } else { + var rem = this.subtract(other.multiply(approx)); + var result = approx.add(rem.div(other)); + return result; + } + } + } else if (other.equals(Long.MIN_VALUE)) { + return Long.ZERO; + } + + if (this.isNegative()) { + if (other.isNegative()) { + return this.negate().div(other.negate()); + } else { + return this.negate() + .div(other) + .negate(); + } + } else if (other.isNegative()) { + return this.div(other.negate()).negate(); + } + + // Repeat the following until the remainder is less than other: find a + // floating-point that approximates remainder / other *from below*, add this + // into the result, and subtract it from the remainder. It is critical that + // the approximate value is less than or equal to the real value so that the + // remainder never becomes negative. + var res = Long.ZERO; + rem = this; + while (rem.greaterThanOrEqual(other)) { + // Approximate the result of division. This may be a little greater or + // smaller than the actual value. + approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); + + // We will tweak the approximate result by changing it in the 48-th digit or + // the smallest non-fractional digit, whichever is larger. + var log2 = Math.ceil(Math.log(approx) / Math.LN2); + var delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48); + + // Decrease the approximation until it is smaller than the remainder. Note + // that if it is too large, the product overflows and is negative. + var approxRes = Long.fromNumber(approx); + var approxRem = approxRes.multiply(other); + while (approxRem.isNegative() || approxRem.greaterThan(rem)) { + approx -= delta; + approxRes = Long.fromNumber(approx); + approxRem = approxRes.multiply(other); + } + + // We know the answer can't be zero... and actually, zero would cause + // infinite recursion since we would make no progress. + if (approxRes.isZero()) { + approxRes = Long.ONE; + } + + res = res.add(approxRes); + rem = rem.subtract(approxRem); + } + return res; +}; + +/** + * Returns this Long modulo the given one. + * + * @method + * @param {Long} other Long by which to mod. + * @return {Long} this Long modulo the given one. + */ +Long.prototype.modulo = function(other) { + return this.subtract(this.div(other).multiply(other)); +}; + +/** + * The bitwise-NOT of this value. + * + * @method + * @return {Long} the bitwise-NOT of this value. + */ +Long.prototype.not = function() { + return Long.fromBits(~this.low_, ~this.high_); +}; + +/** + * Returns the bitwise-AND of this Long and the given one. + * + * @method + * @param {Long} other the Long with which to AND. + * @return {Long} the bitwise-AND of this and the other. + */ +Long.prototype.and = function(other) { + return Long.fromBits(this.low_ & other.low_, this.high_ & other.high_); +}; + +/** + * Returns the bitwise-OR of this Long and the given one. + * + * @method + * @param {Long} other the Long with which to OR. + * @return {Long} the bitwise-OR of this and the other. + */ +Long.prototype.or = function(other) { + return Long.fromBits(this.low_ | other.low_, this.high_ | other.high_); +}; + +/** + * Returns the bitwise-XOR of this Long and the given one. + * + * @method + * @param {Long} other the Long with which to XOR. + * @return {Long} the bitwise-XOR of this and the other. + */ +Long.prototype.xor = function(other) { + return Long.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); +}; + +/** + * Returns this Long with bits shifted to the left by the given amount. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Long} this shifted to the left by the given amount. + */ +Long.prototype.shiftLeft = function(numBits) { + numBits &= 63; + if (numBits === 0) { + return this; + } else { + var low = this.low_; + if (numBits < 32) { + var high = this.high_; + return Long.fromBits(low << numBits, (high << numBits) | (low >>> (32 - numBits))); + } else { + return Long.fromBits(0, low << (numBits - 32)); + } + } +}; + +/** + * Returns this Long with bits shifted to the right by the given amount. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Long} this shifted to the right by the given amount. + */ +Long.prototype.shiftRight = function(numBits) { + numBits &= 63; + if (numBits === 0) { + return this; + } else { + var high = this.high_; + if (numBits < 32) { + var low = this.low_; + return Long.fromBits((low >>> numBits) | (high << (32 - numBits)), high >> numBits); + } else { + return Long.fromBits(high >> (numBits - 32), high >= 0 ? 0 : -1); + } + } +}; + +/** + * Returns this Long with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Long} this shifted to the right by the given amount, with zeros placed into the new leading bits. + */ +Long.prototype.shiftRightUnsigned = function(numBits) { + numBits &= 63; + if (numBits === 0) { + return this; + } else { + var high = this.high_; + if (numBits < 32) { + var low = this.low_; + return Long.fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits); + } else if (numBits === 32) { + return Long.fromBits(high, 0); + } else { + return Long.fromBits(high >>> (numBits - 32), 0); + } + } +}; + +/** + * Returns a Long representing the given (32-bit) integer value. + * + * @method + * @param {number} value the 32-bit integer in question. + * @return {Long} the corresponding Long value. + */ +Long.fromInt = function(value) { + if (-128 <= value && value < 128) { + var cachedObj = Long.INT_CACHE_[value]; + if (cachedObj) { + return cachedObj; + } + } + + var obj = new Long(value | 0, value < 0 ? -1 : 0); + if (-128 <= value && value < 128) { + Long.INT_CACHE_[value] = obj; + } + return obj; +}; + +/** + * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. + * + * @method + * @param {number} value the number in question. + * @return {Long} the corresponding Long value. + */ +Long.fromNumber = function(value) { + if (isNaN(value) || !isFinite(value)) { + return Long.ZERO; + } else if (value <= -Long.TWO_PWR_63_DBL_) { + return Long.MIN_VALUE; + } else if (value + 1 >= Long.TWO_PWR_63_DBL_) { + return Long.MAX_VALUE; + } else if (value < 0) { + return Long.fromNumber(-value).negate(); + } else { + return new Long((value % Long.TWO_PWR_32_DBL_) | 0, (value / Long.TWO_PWR_32_DBL_) | 0); + } +}; + +/** + * Returns a Long representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. + * + * @method + * @param {number} lowBits the low 32-bits. + * @param {number} highBits the high 32-bits. + * @return {Long} the corresponding Long value. + */ +Long.fromBits = function(lowBits, highBits) { + return new Long(lowBits, highBits); +}; + +/** + * Returns a Long representation of the given string, written using the given radix. + * + * @method + * @param {string} str the textual representation of the Long. + * @param {number} opt_radix the radix in which the text is written. + * @return {Long} the corresponding Long value. + */ +Long.fromString = function(str, opt_radix) { + if (str.length === 0) { + throw Error('number format error: empty string'); + } + + var radix = opt_radix || 10; + if (radix < 2 || 36 < radix) { + throw Error('radix out of range: ' + radix); + } + + if (str.charAt(0) === '-') { + return Long.fromString(str.substring(1), radix).negate(); + } else if (str.indexOf('-') >= 0) { + throw Error('number format error: interior "-" character: ' + str); + } + + // Do several (8) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = Long.fromNumber(Math.pow(radix, 8)); + + var result = Long.ZERO; + for (var i = 0; i < str.length; i += 8) { + var size = Math.min(8, str.length - i); + var value = parseInt(str.substring(i, i + size), radix); + if (size < 8) { + var power = Long.fromNumber(Math.pow(radix, size)); + result = result.multiply(power).add(Long.fromNumber(value)); + } else { + result = result.multiply(radixToPower); + result = result.add(Long.fromNumber(value)); + } + } + return result; +}; + +// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the +// from* methods on which they depend. + +/** + * A cache of the Long representations of small integer values. + * @type {Object} + * @ignore + */ +Long.INT_CACHE_ = {}; + +// NOTE: the compiler should inline these constant values below and then remove +// these variables, so there should be no runtime penalty for these. + +/** + * Number used repeated below in calculations. This must appear before the + * first call to any from* function below. + * @type {number} + * @ignore + */ +Long.TWO_PWR_16_DBL_ = 1 << 16; + +/** + * @type {number} + * @ignore + */ +Long.TWO_PWR_24_DBL_ = 1 << 24; + +/** + * @type {number} + * @ignore + */ +Long.TWO_PWR_32_DBL_ = Long.TWO_PWR_16_DBL_ * Long.TWO_PWR_16_DBL_; + +/** + * @type {number} + * @ignore + */ +Long.TWO_PWR_31_DBL_ = Long.TWO_PWR_32_DBL_ / 2; + +/** + * @type {number} + * @ignore + */ +Long.TWO_PWR_48_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_16_DBL_; + +/** + * @type {number} + * @ignore + */ +Long.TWO_PWR_64_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_32_DBL_; + +/** + * @type {number} + * @ignore + */ +Long.TWO_PWR_63_DBL_ = Long.TWO_PWR_64_DBL_ / 2; + +/** @type {Long} */ +Long.ZERO = Long.fromInt(0); + +/** @type {Long} */ +Long.ONE = Long.fromInt(1); + +/** @type {Long} */ +Long.NEG_ONE = Long.fromInt(-1); + +/** @type {Long} */ +Long.MAX_VALUE = Long.fromBits(0xffffffff | 0, 0x7fffffff | 0); + +/** @type {Long} */ +Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0); + +/** + * @type {Long} + * @ignore + */ +Long.TWO_PWR_24_ = Long.fromInt(1 << 24); + +/** + * Expose. + */ +module.exports = Long; +module.exports.Long = Long; diff --git a/scripts/2.5/node_modules/bson/lib/bson/map.js b/scripts/2.5/node_modules/bson/lib/bson/map.js new file mode 100644 index 00000000..7edb4f2a --- /dev/null +++ b/scripts/2.5/node_modules/bson/lib/bson/map.js @@ -0,0 +1,128 @@ +'use strict'; + +// We have an ES6 Map available, return the native instance +if (typeof global.Map !== 'undefined') { + module.exports = global.Map; + module.exports.Map = global.Map; +} else { + // We will return a polyfill + var Map = function(array) { + this._keys = []; + this._values = {}; + + for (var i = 0; i < array.length; i++) { + if (array[i] == null) continue; // skip null and undefined + var entry = array[i]; + var key = entry[0]; + var value = entry[1]; + // Add the key to the list of keys in order + this._keys.push(key); + // Add the key and value to the values dictionary with a point + // to the location in the ordered keys list + this._values[key] = { v: value, i: this._keys.length - 1 }; + } + }; + + Map.prototype.clear = function() { + this._keys = []; + this._values = {}; + }; + + Map.prototype.delete = function(key) { + var value = this._values[key]; + if (value == null) return false; + // Delete entry + delete this._values[key]; + // Remove the key from the ordered keys list + this._keys.splice(value.i, 1); + return true; + }; + + Map.prototype.entries = function() { + var self = this; + var index = 0; + + return { + next: function() { + var key = self._keys[index++]; + return { + value: key !== undefined ? [key, self._values[key].v] : undefined, + done: key !== undefined ? false : true + }; + } + }; + }; + + Map.prototype.forEach = function(callback, self) { + self = self || this; + + for (var i = 0; i < this._keys.length; i++) { + var key = this._keys[i]; + // Call the forEach callback + callback.call(self, this._values[key].v, key, self); + } + }; + + Map.prototype.get = function(key) { + return this._values[key] ? this._values[key].v : undefined; + }; + + Map.prototype.has = function(key) { + return this._values[key] != null; + }; + + Map.prototype.keys = function() { + var self = this; + var index = 0; + + return { + next: function() { + var key = self._keys[index++]; + return { + value: key !== undefined ? key : undefined, + done: key !== undefined ? false : true + }; + } + }; + }; + + Map.prototype.set = function(key, value) { + if (this._values[key]) { + this._values[key].v = value; + return this; + } + + // Add the key to the list of keys in order + this._keys.push(key); + // Add the key and value to the values dictionary with a point + // to the location in the ordered keys list + this._values[key] = { v: value, i: this._keys.length - 1 }; + return this; + }; + + Map.prototype.values = function() { + var self = this; + var index = 0; + + return { + next: function() { + var key = self._keys[index++]; + return { + value: key !== undefined ? self._values[key].v : undefined, + done: key !== undefined ? false : true + }; + } + }; + }; + + // Last ismaster + Object.defineProperty(Map.prototype, 'size', { + enumerable: true, + get: function() { + return this._keys.length; + } + }); + + module.exports = Map; + module.exports.Map = Map; +} diff --git a/scripts/2.5/node_modules/bson/lib/bson/max_key.js b/scripts/2.5/node_modules/bson/lib/bson/max_key.js new file mode 100644 index 00000000..eebca7bc --- /dev/null +++ b/scripts/2.5/node_modules/bson/lib/bson/max_key.js @@ -0,0 +1,14 @@ +/** + * A class representation of the BSON MaxKey type. + * + * @class + * @return {MaxKey} A MaxKey instance + */ +function MaxKey() { + if (!(this instanceof MaxKey)) return new MaxKey(); + + this._bsontype = 'MaxKey'; +} + +module.exports = MaxKey; +module.exports.MaxKey = MaxKey; diff --git a/scripts/2.5/node_modules/bson/lib/bson/min_key.js b/scripts/2.5/node_modules/bson/lib/bson/min_key.js new file mode 100644 index 00000000..15f45228 --- /dev/null +++ b/scripts/2.5/node_modules/bson/lib/bson/min_key.js @@ -0,0 +1,14 @@ +/** + * A class representation of the BSON MinKey type. + * + * @class + * @return {MinKey} A MinKey instance + */ +function MinKey() { + if (!(this instanceof MinKey)) return new MinKey(); + + this._bsontype = 'MinKey'; +} + +module.exports = MinKey; +module.exports.MinKey = MinKey; diff --git a/scripts/2.5/node_modules/bson/lib/bson/objectid.js b/scripts/2.5/node_modules/bson/lib/bson/objectid.js new file mode 100644 index 00000000..79de40d2 --- /dev/null +++ b/scripts/2.5/node_modules/bson/lib/bson/objectid.js @@ -0,0 +1,389 @@ +// Custom inspect property name / symbol. +var inspect = 'inspect'; + +var utils = require('./parser/utils'); + +/** + * Machine id. + * + * Create a random 3-byte value (i.e. unique for this + * process). Other drivers use a md5 of the machine id here, but + * that would mean an asyc call to gethostname, so we don't bother. + * @ignore + */ +var MACHINE_ID = parseInt(Math.random() * 0xffffff, 10); + +// Regular expression that checks for hex value +var checkForHexRegExp = new RegExp('^[0-9a-fA-F]{24}$'); + +// Check if buffer exists +try { + if (Buffer && Buffer.from) { + var hasBufferType = true; + inspect = require('util').inspect.custom || 'inspect'; + } +} catch (err) { + hasBufferType = false; +} + +/** +* Create a new ObjectID instance +* +* @class +* @param {(string|number)} id Can be a 24 byte hex string, 12 byte binary string or a Number. +* @property {number} generationTime The generation time of this ObjectId instance +* @return {ObjectID} instance of ObjectID. +*/ +var ObjectID = function ObjectID(id) { + // Duck-typing to support ObjectId from different npm packages + if (id instanceof ObjectID) return id; + if (!(this instanceof ObjectID)) return new ObjectID(id); + + this._bsontype = 'ObjectID'; + + // The most common usecase (blank id, new objectId instance) + if (id == null || typeof id === 'number') { + // Generate a new id + this.id = this.generate(id); + // If we are caching the hex string + if (ObjectID.cacheHexString) this.__id = this.toString('hex'); + // Return the object + return; + } + + // Check if the passed in id is valid + var valid = ObjectID.isValid(id); + + // Throw an error if it's not a valid setup + if (!valid && id != null) { + throw new Error( + 'Argument passed in must be a single String of 12 bytes or a string of 24 hex characters' + ); + } else if (valid && typeof id === 'string' && id.length === 24 && hasBufferType) { + return new ObjectID(utils.toBuffer(id, 'hex')); + } else if (valid && typeof id === 'string' && id.length === 24) { + return ObjectID.createFromHexString(id); + } else if (id != null && id.length === 12) { + // assume 12 byte string + this.id = id; + } else if (id != null && id.toHexString) { + // Duck-typing to support ObjectId from different npm packages + return id; + } else { + throw new Error( + 'Argument passed in must be a single String of 12 bytes or a string of 24 hex characters' + ); + } + + if (ObjectID.cacheHexString) this.__id = this.toString('hex'); +}; + +// Allow usage of ObjectId as well as ObjectID +// var ObjectId = ObjectID; + +// Precomputed hex table enables speedy hex string conversion +var hexTable = []; +for (var i = 0; i < 256; i++) { + hexTable[i] = (i <= 15 ? '0' : '') + i.toString(16); +} + +/** +* Return the ObjectID id as a 24 byte hex string representation +* +* @method +* @return {string} return the 24 byte hex string representation. +*/ +ObjectID.prototype.toHexString = function() { + if (ObjectID.cacheHexString && this.__id) return this.__id; + + var hexString = ''; + if (!this.id || !this.id.length) { + throw new Error( + 'invalid ObjectId, ObjectId.id must be either a string or a Buffer, but is [' + + JSON.stringify(this.id) + + ']' + ); + } + + if (this.id instanceof _Buffer) { + hexString = convertToHex(this.id); + if (ObjectID.cacheHexString) this.__id = hexString; + return hexString; + } + + for (var i = 0; i < this.id.length; i++) { + hexString += hexTable[this.id.charCodeAt(i)]; + } + + if (ObjectID.cacheHexString) this.__id = hexString; + return hexString; +}; + +/** +* Update the ObjectID index used in generating new ObjectID's on the driver +* +* @method +* @return {number} returns next index value. +* @ignore +*/ +ObjectID.prototype.get_inc = function() { + return (ObjectID.index = (ObjectID.index + 1) % 0xffffff); +}; + +/** +* Update the ObjectID index used in generating new ObjectID's on the driver +* +* @method +* @return {number} returns next index value. +* @ignore +*/ +ObjectID.prototype.getInc = function() { + return this.get_inc(); +}; + +/** +* Generate a 12 byte id buffer used in ObjectID's +* +* @method +* @param {number} [time] optional parameter allowing to pass in a second based timestamp. +* @return {Buffer} return the 12 byte id buffer string. +*/ +ObjectID.prototype.generate = function(time) { + if ('number' !== typeof time) { + time = ~~(Date.now() / 1000); + } + + // Use pid + var pid = + (typeof process === 'undefined' || process.pid === 1 + ? Math.floor(Math.random() * 100000) + : process.pid) % 0xffff; + var inc = this.get_inc(); + // Buffer used + var buffer = utils.allocBuffer(12); + // Encode time + buffer[3] = time & 0xff; + buffer[2] = (time >> 8) & 0xff; + buffer[1] = (time >> 16) & 0xff; + buffer[0] = (time >> 24) & 0xff; + // Encode machine + buffer[6] = MACHINE_ID & 0xff; + buffer[5] = (MACHINE_ID >> 8) & 0xff; + buffer[4] = (MACHINE_ID >> 16) & 0xff; + // Encode pid + buffer[8] = pid & 0xff; + buffer[7] = (pid >> 8) & 0xff; + // Encode index + buffer[11] = inc & 0xff; + buffer[10] = (inc >> 8) & 0xff; + buffer[9] = (inc >> 16) & 0xff; + // Return the buffer + return buffer; +}; + +/** +* Converts the id into a 24 byte hex string for printing +* +* @param {String} format The Buffer toString format parameter. +* @return {String} return the 24 byte hex string representation. +* @ignore +*/ +ObjectID.prototype.toString = function(format) { + // Is the id a buffer then use the buffer toString method to return the format + if (this.id && this.id.copy) { + return this.id.toString(typeof format === 'string' ? format : 'hex'); + } + + // if(this.buffer ) + return this.toHexString(); +}; + +/** +* Converts to a string representation of this Id. +* +* @return {String} return the 24 byte hex string representation. +* @ignore +*/ +ObjectID.prototype[inspect] = ObjectID.prototype.toString; + +/** +* Converts to its JSON representation. +* +* @return {String} return the 24 byte hex string representation. +* @ignore +*/ +ObjectID.prototype.toJSON = function() { + return this.toHexString(); +}; + +/** +* Compares the equality of this ObjectID with `otherID`. +* +* @method +* @param {object} otherID ObjectID instance to compare against. +* @return {boolean} the result of comparing two ObjectID's +*/ +ObjectID.prototype.equals = function equals(otherId) { + // var id; + + if (otherId instanceof ObjectID) { + return this.toString() === otherId.toString(); + } else if ( + typeof otherId === 'string' && + ObjectID.isValid(otherId) && + otherId.length === 12 && + this.id instanceof _Buffer + ) { + return otherId === this.id.toString('binary'); + } else if (typeof otherId === 'string' && ObjectID.isValid(otherId) && otherId.length === 24) { + return otherId.toLowerCase() === this.toHexString(); + } else if (typeof otherId === 'string' && ObjectID.isValid(otherId) && otherId.length === 12) { + return otherId === this.id; + } else if (otherId != null && (otherId instanceof ObjectID || otherId.toHexString)) { + return otherId.toHexString() === this.toHexString(); + } else { + return false; + } +}; + +/** +* Returns the generation date (accurate up to the second) that this ID was generated. +* +* @method +* @return {date} the generation date +*/ +ObjectID.prototype.getTimestamp = function() { + var timestamp = new Date(); + var time = this.id[3] | (this.id[2] << 8) | (this.id[1] << 16) | (this.id[0] << 24); + timestamp.setTime(Math.floor(time) * 1000); + return timestamp; +}; + +/** +* @ignore +*/ +ObjectID.index = ~~(Math.random() * 0xffffff); + +/** +* @ignore +*/ +ObjectID.createPk = function createPk() { + return new ObjectID(); +}; + +/** +* Creates an ObjectID from a second based number, with the rest of the ObjectID zeroed out. Used for comparisons or sorting the ObjectID. +* +* @method +* @param {number} time an integer number representing a number of seconds. +* @return {ObjectID} return the created ObjectID +*/ +ObjectID.createFromTime = function createFromTime(time) { + var buffer = utils.toBuffer([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); + // Encode time into first 4 bytes + buffer[3] = time & 0xff; + buffer[2] = (time >> 8) & 0xff; + buffer[1] = (time >> 16) & 0xff; + buffer[0] = (time >> 24) & 0xff; + // Return the new objectId + return new ObjectID(buffer); +}; + +// Lookup tables +//var encodeLookup = '0123456789abcdef'.split(''); +var decodeLookup = []; +i = 0; +while (i < 10) decodeLookup[0x30 + i] = i++; +while (i < 16) decodeLookup[0x41 - 10 + i] = decodeLookup[0x61 - 10 + i] = i++; + +var _Buffer = Buffer; +var convertToHex = function(bytes) { + return bytes.toString('hex'); +}; + +/** +* Creates an ObjectID from a hex string representation of an ObjectID. +* +* @method +* @param {string} hexString create a ObjectID from a passed in 24 byte hexstring. +* @return {ObjectID} return the created ObjectID +*/ +ObjectID.createFromHexString = function createFromHexString(string) { + // Throw an error if it's not a valid setup + if (typeof string === 'undefined' || (string != null && string.length !== 24)) { + throw new Error( + 'Argument passed in must be a single String of 12 bytes or a string of 24 hex characters' + ); + } + + // Use Buffer.from method if available + if (hasBufferType) return new ObjectID(utils.toBuffer(string, 'hex')); + + // Calculate lengths + var array = new _Buffer(12); + var n = 0; + var i = 0; + + while (i < 24) { + array[n++] = (decodeLookup[string.charCodeAt(i++)] << 4) | decodeLookup[string.charCodeAt(i++)]; + } + + return new ObjectID(array); +}; + +/** +* Checks if a value is a valid bson ObjectId +* +* @method +* @return {boolean} return true if the value is a valid bson ObjectId, return false otherwise. +*/ +ObjectID.isValid = function isValid(id) { + if (id == null) return false; + + if (typeof id === 'number') { + return true; + } + + if (typeof id === 'string') { + return id.length === 12 || (id.length === 24 && checkForHexRegExp.test(id)); + } + + if (id instanceof ObjectID) { + return true; + } + + if (id instanceof _Buffer) { + return true; + } + + // Duck-Typing detection of ObjectId like objects + if (id.toHexString) { + return id.id.length === 12 || (id.id.length === 24 && checkForHexRegExp.test(id.id)); + } + + return false; +}; + +/** +* @ignore +*/ +Object.defineProperty(ObjectID.prototype, 'generationTime', { + enumerable: true, + get: function() { + return this.id[3] | (this.id[2] << 8) | (this.id[1] << 16) | (this.id[0] << 24); + }, + set: function(value) { + // Encode time into first 4 bytes + this.id[3] = value & 0xff; + this.id[2] = (value >> 8) & 0xff; + this.id[1] = (value >> 16) & 0xff; + this.id[0] = (value >> 24) & 0xff; + } +}); + +/** + * Expose. + */ +module.exports = ObjectID; +module.exports.ObjectID = ObjectID; +module.exports.ObjectId = ObjectID; diff --git a/scripts/2.5/node_modules/bson/lib/bson/parser/calculate_size.js b/scripts/2.5/node_modules/bson/lib/bson/parser/calculate_size.js new file mode 100644 index 00000000..7e0026ca --- /dev/null +++ b/scripts/2.5/node_modules/bson/lib/bson/parser/calculate_size.js @@ -0,0 +1,255 @@ +'use strict'; + +var Long = require('../long').Long, + Double = require('../double').Double, + Timestamp = require('../timestamp').Timestamp, + ObjectID = require('../objectid').ObjectID, + Symbol = require('../symbol').Symbol, + BSONRegExp = require('../regexp').BSONRegExp, + Code = require('../code').Code, + Decimal128 = require('../decimal128'), + MinKey = require('../min_key').MinKey, + MaxKey = require('../max_key').MaxKey, + DBRef = require('../db_ref').DBRef, + Binary = require('../binary').Binary; + +var normalizedFunctionString = require('./utils').normalizedFunctionString; + +// To ensure that 0.4 of node works correctly +var isDate = function isDate(d) { + return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; +}; + +var calculateObjectSize = function calculateObjectSize( + object, + serializeFunctions, + ignoreUndefined +) { + var totalLength = 4 + 1; + + if (Array.isArray(object)) { + for (var i = 0; i < object.length; i++) { + totalLength += calculateElement( + i.toString(), + object[i], + serializeFunctions, + true, + ignoreUndefined + ); + } + } else { + // If we have toBSON defined, override the current object + if (object.toBSON) { + object = object.toBSON(); + } + + // Calculate size + for (var key in object) { + totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined); + } + } + + return totalLength; +}; + +/** + * @ignore + * @api private + */ +function calculateElement(name, value, serializeFunctions, isArray, ignoreUndefined) { + // If we have toBSON defined, override the current object + if (value && value.toBSON) { + value = value.toBSON(); + } + + switch (typeof value) { + case 'string': + return 1 + Buffer.byteLength(name, 'utf8') + 1 + 4 + Buffer.byteLength(value, 'utf8') + 1; + case 'number': + if (Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { + if (value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { + // 32 bit + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (4 + 1); + } else { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); + } + } else { + // 64 bit + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); + } + case 'undefined': + if (isArray || !ignoreUndefined) + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1; + return 0; + case 'boolean': + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (1 + 1); + case 'object': + if ( + value == null || + value instanceof MinKey || + value instanceof MaxKey || + value['_bsontype'] === 'MinKey' || + value['_bsontype'] === 'MaxKey' + ) { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1; + } else if (value instanceof ObjectID || value['_bsontype'] === 'ObjectID' || value['_bsontype'] === 'ObjectId') { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (12 + 1); + } else if (value instanceof Date || isDate(value)) { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); + } else if (typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (1 + 4 + 1) + value.length + ); + } else if ( + value instanceof Long || + value instanceof Double || + value instanceof Timestamp || + value['_bsontype'] === 'Long' || + value['_bsontype'] === 'Double' || + value['_bsontype'] === 'Timestamp' + ) { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); + } else if (value instanceof Decimal128 || value['_bsontype'] === 'Decimal128') { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (16 + 1); + } else if (value instanceof Code || value['_bsontype'] === 'Code') { + // Calculate size depending on the availability of a scope + if (value.scope != null && Object.keys(value.scope).length > 0) { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + 4 + + 4 + + Buffer.byteLength(value.code.toString(), 'utf8') + + 1 + + calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined) + ); + } else { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + 4 + + Buffer.byteLength(value.code.toString(), 'utf8') + + 1 + ); + } + } else if (value instanceof Binary || value['_bsontype'] === 'Binary') { + // Check what kind of subtype we have + if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + (value.position + 1 + 4 + 1 + 4) + ); + } else { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (value.position + 1 + 4 + 1) + ); + } + } else if (value instanceof Symbol || value['_bsontype'] === 'Symbol') { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + Buffer.byteLength(value.value, 'utf8') + + 4 + + 1 + + 1 + ); + } else if (value instanceof DBRef || value['_bsontype'] === 'DBRef') { + // Set up correct object for serialization + var ordered_values = { + $ref: value.namespace, + $id: value.oid + }; + + // Add db reference if it exists + if (null != value.db) { + ordered_values['$db'] = value.db; + } + + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + calculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined) + ); + } else if ( + value instanceof RegExp || + Object.prototype.toString.call(value) === '[object RegExp]' + ) { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + Buffer.byteLength(value.source, 'utf8') + + 1 + + (value.global ? 1 : 0) + + (value.ignoreCase ? 1 : 0) + + (value.multiline ? 1 : 0) + + 1 + ); + } else if (value instanceof BSONRegExp || value['_bsontype'] === 'BSONRegExp') { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + Buffer.byteLength(value.pattern, 'utf8') + + 1 + + Buffer.byteLength(value.options, 'utf8') + + 1 + ); + } else { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + calculateObjectSize(value, serializeFunctions, ignoreUndefined) + + 1 + ); + } + case 'function': + // WTF for 0.4.X where typeof /someregexp/ === 'function' + if ( + value instanceof RegExp || + Object.prototype.toString.call(value) === '[object RegExp]' || + String.call(value) === '[object RegExp]' + ) { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + Buffer.byteLength(value.source, 'utf8') + + 1 + + (value.global ? 1 : 0) + + (value.ignoreCase ? 1 : 0) + + (value.multiline ? 1 : 0) + + 1 + ); + } else { + if (serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + 4 + + 4 + + Buffer.byteLength(normalizedFunctionString(value), 'utf8') + + 1 + + calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined) + ); + } else if (serializeFunctions) { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + 4 + + Buffer.byteLength(normalizedFunctionString(value), 'utf8') + + 1 + ); + } + } + } + + return 0; +} + +var BSON = {}; + +// BSON MAX VALUES +BSON.BSON_INT32_MAX = 0x7fffffff; +BSON.BSON_INT32_MIN = -0x80000000; + +// JS MAX PRECISE VALUES +BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. +BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. + +module.exports = calculateObjectSize; diff --git a/scripts/2.5/node_modules/bson/lib/bson/parser/deserializer.js b/scripts/2.5/node_modules/bson/lib/bson/parser/deserializer.js new file mode 100644 index 00000000..be3c8654 --- /dev/null +++ b/scripts/2.5/node_modules/bson/lib/bson/parser/deserializer.js @@ -0,0 +1,782 @@ +'use strict'; + +var Long = require('../long').Long, + Double = require('../double').Double, + Timestamp = require('../timestamp').Timestamp, + ObjectID = require('../objectid').ObjectID, + Symbol = require('../symbol').Symbol, + Code = require('../code').Code, + MinKey = require('../min_key').MinKey, + MaxKey = require('../max_key').MaxKey, + Decimal128 = require('../decimal128'), + Int32 = require('../int_32'), + DBRef = require('../db_ref').DBRef, + BSONRegExp = require('../regexp').BSONRegExp, + Binary = require('../binary').Binary; + +var utils = require('./utils'); + +var deserialize = function(buffer, options, isArray) { + options = options == null ? {} : options; + var index = options && options.index ? options.index : 0; + // Read the document size + var size = + buffer[index] | + (buffer[index + 1] << 8) | + (buffer[index + 2] << 16) | + (buffer[index + 3] << 24); + + // Ensure buffer is valid size + if (size < 5 || buffer.length < size || size + index > buffer.length) { + throw new Error('corrupt bson message'); + } + + // Illegal end value + if (buffer[index + size - 1] !== 0) { + throw new Error("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00"); + } + + // Start deserializtion + return deserializeObject(buffer, index, options, isArray); +}; + +var deserializeObject = function(buffer, index, options, isArray) { + var evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions']; + var cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions']; + var cacheFunctionsCrc32 = + options['cacheFunctionsCrc32'] == null ? false : options['cacheFunctionsCrc32']; + + if (!cacheFunctionsCrc32) var crc32 = null; + + var fieldsAsRaw = options['fieldsAsRaw'] == null ? null : options['fieldsAsRaw']; + + // Return raw bson buffer instead of parsing it + var raw = options['raw'] == null ? false : options['raw']; + + // Return BSONRegExp objects instead of native regular expressions + var bsonRegExp = typeof options['bsonRegExp'] === 'boolean' ? options['bsonRegExp'] : false; + + // Controls the promotion of values vs wrapper classes + var promoteBuffers = options['promoteBuffers'] == null ? false : options['promoteBuffers']; + var promoteLongs = options['promoteLongs'] == null ? true : options['promoteLongs']; + var promoteValues = options['promoteValues'] == null ? true : options['promoteValues']; + + // Set the start index + var startIndex = index; + + // Validate that we have at least 4 bytes of buffer + if (buffer.length < 5) throw new Error('corrupt bson message < 5 bytes long'); + + // Read the document size + var size = + buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + + // Ensure buffer is valid size + if (size < 5 || size > buffer.length) throw new Error('corrupt bson message'); + + // Create holding object + var object = isArray ? [] : {}; + // Used for arrays to skip having to perform utf8 decoding + var arrayIndex = 0; + + var done = false; + + // While we have more left data left keep parsing + // while (buffer[index + 1] !== 0) { + while (!done) { + // Read the type + var elementType = buffer[index++]; + // If we get a zero it's the last byte, exit + if (elementType === 0) break; + + // Get the start search index + var i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); + var name = isArray ? arrayIndex++ : buffer.toString('utf8', index, i); + + index = i + 1; + + if (elementType === BSON.BSON_DATA_STRING) { + var stringSize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + if ( + stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0 + ) + throw new Error('bad string length in bson'); + object[name] = buffer.toString('utf8', index, index + stringSize - 1); + index = index + stringSize; + } else if (elementType === BSON.BSON_DATA_OID) { + var oid = utils.allocBuffer(12); + buffer.copy(oid, 0, index, index + 12); + object[name] = new ObjectID(oid); + index = index + 12; + } else if (elementType === BSON.BSON_DATA_INT && promoteValues === false) { + object[name] = new Int32( + buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24) + ); + } else if (elementType === BSON.BSON_DATA_INT) { + object[name] = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + } else if (elementType === BSON.BSON_DATA_NUMBER && promoteValues === false) { + object[name] = new Double(buffer.readDoubleLE(index)); + index = index + 8; + } else if (elementType === BSON.BSON_DATA_NUMBER) { + object[name] = buffer.readDoubleLE(index); + index = index + 8; + } else if (elementType === BSON.BSON_DATA_DATE) { + var lowBits = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + var highBits = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + object[name] = new Date(new Long(lowBits, highBits).toNumber()); + } else if (elementType === BSON.BSON_DATA_BOOLEAN) { + if (buffer[index] !== 0 && buffer[index] !== 1) throw new Error('illegal boolean type value'); + object[name] = buffer[index++] === 1; + } else if (elementType === BSON.BSON_DATA_OBJECT) { + var _index = index; + var objectSize = + buffer[index] | + (buffer[index + 1] << 8) | + (buffer[index + 2] << 16) | + (buffer[index + 3] << 24); + if (objectSize <= 0 || objectSize > buffer.length - index) + throw new Error('bad embedded document length in bson'); + + // We have a raw value + if (raw) { + object[name] = buffer.slice(index, index + objectSize); + } else { + object[name] = deserializeObject(buffer, _index, options, false); + } + + index = index + objectSize; + } else if (elementType === BSON.BSON_DATA_ARRAY) { + _index = index; + objectSize = + buffer[index] | + (buffer[index + 1] << 8) | + (buffer[index + 2] << 16) | + (buffer[index + 3] << 24); + var arrayOptions = options; + + // Stop index + var stopIndex = index + objectSize; + + // All elements of array to be returned as raw bson + if (fieldsAsRaw && fieldsAsRaw[name]) { + arrayOptions = {}; + for (var n in options) arrayOptions[n] = options[n]; + arrayOptions['raw'] = true; + } + + object[name] = deserializeObject(buffer, _index, arrayOptions, true); + index = index + objectSize; + + if (buffer[index - 1] !== 0) throw new Error('invalid array terminator byte'); + if (index !== stopIndex) throw new Error('corrupted array bson'); + } else if (elementType === BSON.BSON_DATA_UNDEFINED) { + object[name] = undefined; + } else if (elementType === BSON.BSON_DATA_NULL) { + object[name] = null; + } else if (elementType === BSON.BSON_DATA_LONG) { + // Unpack the low and high bits + lowBits = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + highBits = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + var long = new Long(lowBits, highBits); + // Promote the long if possible + if (promoteLongs && promoteValues === true) { + object[name] = + long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) + ? long.toNumber() + : long; + } else { + object[name] = long; + } + } else if (elementType === BSON.BSON_DATA_DECIMAL128) { + // Buffer to contain the decimal bytes + var bytes = utils.allocBuffer(16); + // Copy the next 16 bytes into the bytes buffer + buffer.copy(bytes, 0, index, index + 16); + // Update index + index = index + 16; + // Assign the new Decimal128 value + var decimal128 = new Decimal128(bytes); + // If we have an alternative mapper use that + object[name] = decimal128.toObject ? decimal128.toObject() : decimal128; + } else if (elementType === BSON.BSON_DATA_BINARY) { + var binarySize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + var totalBinarySize = binarySize; + var subType = buffer[index++]; + + // Did we have a negative binary size, throw + if (binarySize < 0) throw new Error('Negative binary type element size found'); + + // Is the length longer than the document + if (binarySize > buffer.length) throw new Error('Binary type size larger than document size'); + + // Decode as raw Buffer object if options specifies it + if (buffer['slice'] != null) { + // If we have subtype 2 skip the 4 bytes for the size + if (subType === Binary.SUBTYPE_BYTE_ARRAY) { + binarySize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + if (binarySize < 0) + throw new Error('Negative binary type element size found for subtype 0x02'); + if (binarySize > totalBinarySize - 4) + throw new Error('Binary type with subtype 0x02 contains to long binary size'); + if (binarySize < totalBinarySize - 4) + throw new Error('Binary type with subtype 0x02 contains to short binary size'); + } + + if (promoteBuffers && promoteValues) { + object[name] = buffer.slice(index, index + binarySize); + } else { + object[name] = new Binary(buffer.slice(index, index + binarySize), subType); + } + } else { + var _buffer = + typeof Uint8Array !== 'undefined' + ? new Uint8Array(new ArrayBuffer(binarySize)) + : new Array(binarySize); + // If we have subtype 2 skip the 4 bytes for the size + if (subType === Binary.SUBTYPE_BYTE_ARRAY) { + binarySize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + if (binarySize < 0) + throw new Error('Negative binary type element size found for subtype 0x02'); + if (binarySize > totalBinarySize - 4) + throw new Error('Binary type with subtype 0x02 contains to long binary size'); + if (binarySize < totalBinarySize - 4) + throw new Error('Binary type with subtype 0x02 contains to short binary size'); + } + + // Copy the data + for (i = 0; i < binarySize; i++) { + _buffer[i] = buffer[index + i]; + } + + if (promoteBuffers && promoteValues) { + object[name] = _buffer; + } else { + object[name] = new Binary(_buffer, subType); + } + } + + // Update the index + index = index + binarySize; + } else if (elementType === BSON.BSON_DATA_REGEXP && bsonRegExp === false) { + // Get the start search index + i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); + // Return the C string + var source = buffer.toString('utf8', index, i); + // Create the regexp + index = i + 1; + + // Get the start search index + i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); + // Return the C string + var regExpOptions = buffer.toString('utf8', index, i); + index = i + 1; + + // For each option add the corresponding one for javascript + var optionsArray = new Array(regExpOptions.length); + + // Parse options + for (i = 0; i < regExpOptions.length; i++) { + switch (regExpOptions[i]) { + case 'm': + optionsArray[i] = 'm'; + break; + case 's': + optionsArray[i] = 'g'; + break; + case 'i': + optionsArray[i] = 'i'; + break; + } + } + + object[name] = new RegExp(source, optionsArray.join('')); + } else if (elementType === BSON.BSON_DATA_REGEXP && bsonRegExp === true) { + // Get the start search index + i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); + // Return the C string + source = buffer.toString('utf8', index, i); + index = i + 1; + + // Get the start search index + i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); + // Return the C string + regExpOptions = buffer.toString('utf8', index, i); + index = i + 1; + + // Set the object + object[name] = new BSONRegExp(source, regExpOptions); + } else if (elementType === BSON.BSON_DATA_SYMBOL) { + stringSize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + if ( + stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0 + ) + throw new Error('bad string length in bson'); + object[name] = new Symbol(buffer.toString('utf8', index, index + stringSize - 1)); + index = index + stringSize; + } else if (elementType === BSON.BSON_DATA_TIMESTAMP) { + lowBits = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + highBits = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + object[name] = new Timestamp(lowBits, highBits); + } else if (elementType === BSON.BSON_DATA_MIN_KEY) { + object[name] = new MinKey(); + } else if (elementType === BSON.BSON_DATA_MAX_KEY) { + object[name] = new MaxKey(); + } else if (elementType === BSON.BSON_DATA_CODE) { + stringSize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + if ( + stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0 + ) + throw new Error('bad string length in bson'); + var functionString = buffer.toString('utf8', index, index + stringSize - 1); + + // If we are evaluating the functions + if (evalFunctions) { + // If we have cache enabled let's look for the md5 of the function in the cache + if (cacheFunctions) { + var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; + // Got to do this to avoid V8 deoptimizing the call due to finding eval + object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); + } else { + object[name] = isolateEval(functionString); + } + } else { + object[name] = new Code(functionString); + } + + // Update parse index position + index = index + stringSize; + } else if (elementType === BSON.BSON_DATA_CODE_W_SCOPE) { + var totalSize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + + // Element cannot be shorter than totalSize + stringSize + documentSize + terminator + if (totalSize < 4 + 4 + 4 + 1) { + throw new Error('code_w_scope total size shorter minimum expected length'); + } + + // Get the code string size + stringSize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + // Check if we have a valid string + if ( + stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0 + ) + throw new Error('bad string length in bson'); + + // Javascript function + functionString = buffer.toString('utf8', index, index + stringSize - 1); + // Update parse index position + index = index + stringSize; + // Parse the element + _index = index; + // Decode the size of the object document + objectSize = + buffer[index] | + (buffer[index + 1] << 8) | + (buffer[index + 2] << 16) | + (buffer[index + 3] << 24); + // Decode the scope object + var scopeObject = deserializeObject(buffer, _index, options, false); + // Adjust the index + index = index + objectSize; + + // Check if field length is to short + if (totalSize < 4 + 4 + objectSize + stringSize) { + throw new Error('code_w_scope total size is to short, truncating scope'); + } + + // Check if totalSize field is to long + if (totalSize > 4 + 4 + objectSize + stringSize) { + throw new Error('code_w_scope total size is to long, clips outer document'); + } + + // If we are evaluating the functions + if (evalFunctions) { + // If we have cache enabled let's look for the md5 of the function in the cache + if (cacheFunctions) { + hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; + // Got to do this to avoid V8 deoptimizing the call due to finding eval + object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); + } else { + object[name] = isolateEval(functionString); + } + + object[name].scope = scopeObject; + } else { + object[name] = new Code(functionString, scopeObject); + } + } else if (elementType === BSON.BSON_DATA_DBPOINTER) { + // Get the code string size + stringSize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + // Check if we have a valid string + if ( + stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0 + ) + throw new Error('bad string length in bson'); + // Namespace + var namespace = buffer.toString('utf8', index, index + stringSize - 1); + // Update parse index position + index = index + stringSize; + + // Read the oid + var oidBuffer = utils.allocBuffer(12); + buffer.copy(oidBuffer, 0, index, index + 12); + oid = new ObjectID(oidBuffer); + + // Update the index + index = index + 12; + + // Split the namespace + var parts = namespace.split('.'); + var db = parts.shift(); + var collection = parts.join('.'); + // Upgrade to DBRef type + object[name] = new DBRef(collection, oid, db); + } else { + throw new Error( + 'Detected unknown BSON type ' + + elementType.toString(16) + + ' for fieldname "' + + name + + '", are you using the latest BSON parser' + ); + } + } + + // Check if the deserialization was against a valid array/object + if (size !== index - startIndex) { + if (isArray) throw new Error('corrupt array bson'); + throw new Error('corrupt object bson'); + } + + // Check if we have a db ref object + if (object['$id'] != null) object = new DBRef(object['$ref'], object['$id'], object['$db']); + return object; +}; + +/** + * Ensure eval is isolated. + * + * @ignore + * @api private + */ +var isolateEvalWithHash = function(functionCache, hash, functionString, object) { + // Contains the value we are going to set + var value = null; + + // Check for cache hit, eval if missing and return cached function + if (functionCache[hash] == null) { + eval('value = ' + functionString); + functionCache[hash] = value; + } + // Set the object + return functionCache[hash].bind(object); +}; + +/** + * Ensure eval is isolated. + * + * @ignore + * @api private + */ +var isolateEval = function(functionString) { + // Contains the value we are going to set + var value = null; + // Eval the function + eval('value = ' + functionString); + return value; +}; + +var BSON = {}; + +/** + * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 + * + * @ignore + * @api private + */ +var functionCache = (BSON.functionCache = {}); + +/** + * Number BSON Type + * + * @classconstant BSON_DATA_NUMBER + **/ +BSON.BSON_DATA_NUMBER = 1; +/** + * String BSON Type + * + * @classconstant BSON_DATA_STRING + **/ +BSON.BSON_DATA_STRING = 2; +/** + * Object BSON Type + * + * @classconstant BSON_DATA_OBJECT + **/ +BSON.BSON_DATA_OBJECT = 3; +/** + * Array BSON Type + * + * @classconstant BSON_DATA_ARRAY + **/ +BSON.BSON_DATA_ARRAY = 4; +/** + * Binary BSON Type + * + * @classconstant BSON_DATA_BINARY + **/ +BSON.BSON_DATA_BINARY = 5; +/** + * Binary BSON Type + * + * @classconstant BSON_DATA_UNDEFINED + **/ +BSON.BSON_DATA_UNDEFINED = 6; +/** + * ObjectID BSON Type + * + * @classconstant BSON_DATA_OID + **/ +BSON.BSON_DATA_OID = 7; +/** + * Boolean BSON Type + * + * @classconstant BSON_DATA_BOOLEAN + **/ +BSON.BSON_DATA_BOOLEAN = 8; +/** + * Date BSON Type + * + * @classconstant BSON_DATA_DATE + **/ +BSON.BSON_DATA_DATE = 9; +/** + * null BSON Type + * + * @classconstant BSON_DATA_NULL + **/ +BSON.BSON_DATA_NULL = 10; +/** + * RegExp BSON Type + * + * @classconstant BSON_DATA_REGEXP + **/ +BSON.BSON_DATA_REGEXP = 11; +/** + * Code BSON Type + * + * @classconstant BSON_DATA_DBPOINTER + **/ +BSON.BSON_DATA_DBPOINTER = 12; +/** + * Code BSON Type + * + * @classconstant BSON_DATA_CODE + **/ +BSON.BSON_DATA_CODE = 13; +/** + * Symbol BSON Type + * + * @classconstant BSON_DATA_SYMBOL + **/ +BSON.BSON_DATA_SYMBOL = 14; +/** + * Code with Scope BSON Type + * + * @classconstant BSON_DATA_CODE_W_SCOPE + **/ +BSON.BSON_DATA_CODE_W_SCOPE = 15; +/** + * 32 bit Integer BSON Type + * + * @classconstant BSON_DATA_INT + **/ +BSON.BSON_DATA_INT = 16; +/** + * Timestamp BSON Type + * + * @classconstant BSON_DATA_TIMESTAMP + **/ +BSON.BSON_DATA_TIMESTAMP = 17; +/** + * Long BSON Type + * + * @classconstant BSON_DATA_LONG + **/ +BSON.BSON_DATA_LONG = 18; +/** + * Long BSON Type + * + * @classconstant BSON_DATA_DECIMAL128 + **/ +BSON.BSON_DATA_DECIMAL128 = 19; +/** + * MinKey BSON Type + * + * @classconstant BSON_DATA_MIN_KEY + **/ +BSON.BSON_DATA_MIN_KEY = 0xff; +/** + * MaxKey BSON Type + * + * @classconstant BSON_DATA_MAX_KEY + **/ +BSON.BSON_DATA_MAX_KEY = 0x7f; + +/** + * Binary Default Type + * + * @classconstant BSON_BINARY_SUBTYPE_DEFAULT + **/ +BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; +/** + * Binary Function Type + * + * @classconstant BSON_BINARY_SUBTYPE_FUNCTION + **/ +BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; +/** + * Binary Byte Array Type + * + * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY + **/ +BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; +/** + * Binary UUID Type + * + * @classconstant BSON_BINARY_SUBTYPE_UUID + **/ +BSON.BSON_BINARY_SUBTYPE_UUID = 3; +/** + * Binary MD5 Type + * + * @classconstant BSON_BINARY_SUBTYPE_MD5 + **/ +BSON.BSON_BINARY_SUBTYPE_MD5 = 4; +/** + * Binary User Defined Type + * + * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED + **/ +BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; + +// BSON MAX VALUES +BSON.BSON_INT32_MAX = 0x7fffffff; +BSON.BSON_INT32_MIN = -0x80000000; + +BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; +BSON.BSON_INT64_MIN = -Math.pow(2, 63); + +// JS MAX PRECISE VALUES +BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. +BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. + +// Internal long versions +var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. +var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. + +module.exports = deserialize; diff --git a/scripts/2.5/node_modules/bson/lib/bson/parser/serializer.js b/scripts/2.5/node_modules/bson/lib/bson/parser/serializer.js new file mode 100644 index 00000000..e4ff2bd9 --- /dev/null +++ b/scripts/2.5/node_modules/bson/lib/bson/parser/serializer.js @@ -0,0 +1,1182 @@ +'use strict'; + +var writeIEEE754 = require('../float_parser').writeIEEE754, + Long = require('../long').Long, + Map = require('../map'), + Binary = require('../binary').Binary; + +var normalizedFunctionString = require('./utils').normalizedFunctionString; + +// try { +// var _Buffer = Uint8Array; +// } catch (e) { +// _Buffer = Buffer; +// } + +var regexp = /\x00/; // eslint-disable-line no-control-regex +var ignoreKeys = ['$db', '$ref', '$id', '$clusterTime']; + +// To ensure that 0.4 of node works correctly +var isDate = function isDate(d) { + return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; +}; + +var isRegExp = function isRegExp(d) { + return Object.prototype.toString.call(d) === '[object RegExp]'; +}; + +var serializeString = function(buffer, key, value, index, isArray) { + // Encode String type + buffer[index++] = BSON.BSON_DATA_STRING; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Write the string + var size = buffer.write(value, index + 4, 'utf8'); + // Write the size of the string to buffer + buffer[index + 3] = ((size + 1) >> 24) & 0xff; + buffer[index + 2] = ((size + 1) >> 16) & 0xff; + buffer[index + 1] = ((size + 1) >> 8) & 0xff; + buffer[index] = (size + 1) & 0xff; + // Update index + index = index + 4 + size; + // Write zero + buffer[index++] = 0; + return index; +}; + +var serializeNumber = function(buffer, key, value, index, isArray) { + // We have an integer value + if (Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { + // If the value fits in 32 bits encode as int, if it fits in a double + // encode it as a double, otherwise long + if (value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { + // Set int type 32 bits or less + buffer[index++] = BSON.BSON_DATA_INT; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the int value + buffer[index++] = value & 0xff; + buffer[index++] = (value >> 8) & 0xff; + buffer[index++] = (value >> 16) & 0xff; + buffer[index++] = (value >> 24) & 0xff; + } else if (value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { + // Encode as double + buffer[index++] = BSON.BSON_DATA_NUMBER; + // Number of written bytes + numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write float + writeIEEE754(buffer, value, index, 'little', 52, 8); + // Ajust index + index = index + 8; + } else { + // Set long type + buffer[index++] = BSON.BSON_DATA_LONG; + // Number of written bytes + numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + var longVal = Long.fromNumber(value); + var lowBits = longVal.getLowBits(); + var highBits = longVal.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = (highBits >> 8) & 0xff; + buffer[index++] = (highBits >> 16) & 0xff; + buffer[index++] = (highBits >> 24) & 0xff; + } + } else { + // Encode as double + buffer[index++] = BSON.BSON_DATA_NUMBER; + // Number of written bytes + numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write float + writeIEEE754(buffer, value, index, 'little', 52, 8); + // Ajust index + index = index + 8; + } + + return index; +}; + +var serializeNull = function(buffer, key, value, index, isArray) { + // Set long type + buffer[index++] = BSON.BSON_DATA_NULL; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + return index; +}; + +var serializeBoolean = function(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_BOOLEAN; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Encode the boolean value + buffer[index++] = value ? 1 : 0; + return index; +}; + +var serializeDate = function(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_DATE; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + // Write the date + var dateInMilis = Long.fromNumber(value.getTime()); + var lowBits = dateInMilis.getLowBits(); + var highBits = dateInMilis.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = (highBits >> 8) & 0xff; + buffer[index++] = (highBits >> 16) & 0xff; + buffer[index++] = (highBits >> 24) & 0xff; + return index; +}; + +var serializeRegExp = function(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_REGEXP; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + if (value.source && value.source.match(regexp) != null) { + throw Error('value ' + value.source + ' must not contain null bytes'); + } + // Adjust the index + index = index + buffer.write(value.source, index, 'utf8'); + // Write zero + buffer[index++] = 0x00; + // Write the parameters + if (value.global) buffer[index++] = 0x73; // s + if (value.ignoreCase) buffer[index++] = 0x69; // i + if (value.multiline) buffer[index++] = 0x6d; // m + // Add ending zero + buffer[index++] = 0x00; + return index; +}; + +var serializeBSONRegExp = function(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_REGEXP; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + // Check the pattern for 0 bytes + if (value.pattern.match(regexp) != null) { + // The BSON spec doesn't allow keys with null bytes because keys are + // null-terminated. + throw Error('pattern ' + value.pattern + ' must not contain null bytes'); + } + + // Adjust the index + index = index + buffer.write(value.pattern, index, 'utf8'); + // Write zero + buffer[index++] = 0x00; + // Write the options + index = + index + + buffer.write( + value.options + .split('') + .sort() + .join(''), + index, + 'utf8' + ); + // Add ending zero + buffer[index++] = 0x00; + return index; +}; + +var serializeMinMax = function(buffer, key, value, index, isArray) { + // Write the type of either min or max key + if (value === null) { + buffer[index++] = BSON.BSON_DATA_NULL; + } else if (value._bsontype === 'MinKey') { + buffer[index++] = BSON.BSON_DATA_MIN_KEY; + } else { + buffer[index++] = BSON.BSON_DATA_MAX_KEY; + } + + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + return index; +}; + +var serializeObjectId = function(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_OID; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + // Write the objectId into the shared buffer + if (typeof value.id === 'string') { + buffer.write(value.id, index, 'binary'); + } else if (value.id && value.id.copy) { + value.id.copy(buffer, index, 0, 12); + } else { + throw new Error('object [' + JSON.stringify(value) + '] is not a valid ObjectId'); + } + + // Ajust index + return index + 12; +}; + +var serializeBuffer = function(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_BINARY; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Get size of the buffer (current write point) + var size = value.length; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write the default subtype + buffer[index++] = BSON.BSON_BINARY_SUBTYPE_DEFAULT; + // Copy the content form the binary field to the buffer + value.copy(buffer, index, 0, size); + // Adjust the index + index = index + size; + return index; +}; + +var serializeObject = function( + buffer, + key, + value, + index, + checkKeys, + depth, + serializeFunctions, + ignoreUndefined, + isArray, + path +) { + for (var i = 0; i < path.length; i++) { + if (path[i] === value) throw new Error('cyclic dependency detected'); + } + + // Push value to stack + path.push(value); + // Write the type + buffer[index++] = Array.isArray(value) ? BSON.BSON_DATA_ARRAY : BSON.BSON_DATA_OBJECT; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + var endIndex = serializeInto( + buffer, + value, + checkKeys, + index, + depth + 1, + serializeFunctions, + ignoreUndefined, + path + ); + // Pop stack + path.pop(); + // Write size + return endIndex; +}; + +var serializeDecimal128 = function(buffer, key, value, index, isArray) { + buffer[index++] = BSON.BSON_DATA_DECIMAL128; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the data from the value + value.bytes.copy(buffer, index, 0, 16); + return index + 16; +}; + +var serializeLong = function(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = value._bsontype === 'Long' ? BSON.BSON_DATA_LONG : BSON.BSON_DATA_TIMESTAMP; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the date + var lowBits = value.getLowBits(); + var highBits = value.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = (highBits >> 8) & 0xff; + buffer[index++] = (highBits >> 16) & 0xff; + buffer[index++] = (highBits >> 24) & 0xff; + return index; +}; + +var serializeInt32 = function(buffer, key, value, index, isArray) { + // Set int type 32 bits or less + buffer[index++] = BSON.BSON_DATA_INT; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the int value + buffer[index++] = value & 0xff; + buffer[index++] = (value >> 8) & 0xff; + buffer[index++] = (value >> 16) & 0xff; + buffer[index++] = (value >> 24) & 0xff; + return index; +}; + +var serializeDouble = function(buffer, key, value, index, isArray) { + // Encode as double + buffer[index++] = BSON.BSON_DATA_NUMBER; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write float + writeIEEE754(buffer, value, index, 'little', 52, 8); + // Ajust index + index = index + 8; + return index; +}; + +var serializeFunction = function(buffer, key, value, index, checkKeys, depth, isArray) { + buffer[index++] = BSON.BSON_DATA_CODE; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Function string + var functionString = normalizedFunctionString(value); + + // Write the string + var size = buffer.write(functionString, index + 4, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = size & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 3] = (size >> 24) & 0xff; + // Update index + index = index + 4 + size - 1; + // Write zero + buffer[index++] = 0; + return index; +}; + +var serializeCode = function( + buffer, + key, + value, + index, + checkKeys, + depth, + serializeFunctions, + ignoreUndefined, + isArray +) { + if (value.scope && typeof value.scope === 'object') { + // Write the type + buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + // Starting index + var startIndex = index; + + // Serialize the function + // Get the function string + var functionString = typeof value.code === 'string' ? value.code : value.code.toString(); + // Index adjustment + index = index + 4; + // Write string into buffer + var codeSize = buffer.write(functionString, index + 4, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = codeSize & 0xff; + buffer[index + 1] = (codeSize >> 8) & 0xff; + buffer[index + 2] = (codeSize >> 16) & 0xff; + buffer[index + 3] = (codeSize >> 24) & 0xff; + // Write end 0 + buffer[index + 4 + codeSize - 1] = 0; + // Write the + index = index + codeSize + 4; + + // + // Serialize the scope value + var endIndex = serializeInto( + buffer, + value.scope, + checkKeys, + index, + depth + 1, + serializeFunctions, + ignoreUndefined + ); + index = endIndex - 1; + + // Writ the total + var totalSize = endIndex - startIndex; + + // Write the total size of the object + buffer[startIndex++] = totalSize & 0xff; + buffer[startIndex++] = (totalSize >> 8) & 0xff; + buffer[startIndex++] = (totalSize >> 16) & 0xff; + buffer[startIndex++] = (totalSize >> 24) & 0xff; + // Write trailing zero + buffer[index++] = 0; + } else { + buffer[index++] = BSON.BSON_DATA_CODE; + // Number of written bytes + numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Function string + functionString = value.code.toString(); + // Write the string + var size = buffer.write(functionString, index + 4, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = size & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 3] = (size >> 24) & 0xff; + // Update index + index = index + 4 + size - 1; + // Write zero + buffer[index++] = 0; + } + + return index; +}; + +var serializeBinary = function(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_BINARY; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Extract the buffer + var data = value.value(true); + // Calculate size + var size = value.position; + // Add the deprecated 02 type 4 bytes of size to total + if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) size = size + 4; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write the subtype to the buffer + buffer[index++] = value.sub_type; + + // If we have binary type 2 the 4 first bytes are the size + if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { + size = size - 4; + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + } + + // Write the data to the object + data.copy(buffer, index, 0, value.position); + // Adjust the index + index = index + value.position; + return index; +}; + +var serializeSymbol = function(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_SYMBOL; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the string + var size = buffer.write(value.value, index + 4, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = size & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 3] = (size >> 24) & 0xff; + // Update index + index = index + 4 + size - 1; + // Write zero + buffer[index++] = 0x00; + return index; +}; + +var serializeDBRef = function(buffer, key, value, index, depth, serializeFunctions, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_OBJECT; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + var startIndex = index; + var endIndex; + + // Serialize object + if (null != value.db) { + endIndex = serializeInto( + buffer, + { + $ref: value.namespace, + $id: value.oid, + $db: value.db + }, + false, + index, + depth + 1, + serializeFunctions + ); + } else { + endIndex = serializeInto( + buffer, + { + $ref: value.namespace, + $id: value.oid + }, + false, + index, + depth + 1, + serializeFunctions + ); + } + + // Calculate object size + var size = endIndex - startIndex; + // Write the size + buffer[startIndex++] = size & 0xff; + buffer[startIndex++] = (size >> 8) & 0xff; + buffer[startIndex++] = (size >> 16) & 0xff; + buffer[startIndex++] = (size >> 24) & 0xff; + // Set index + return endIndex; +}; + +var serializeInto = function serializeInto( + buffer, + object, + checkKeys, + startingIndex, + depth, + serializeFunctions, + ignoreUndefined, + path +) { + startingIndex = startingIndex || 0; + path = path || []; + + // Push the object to the path + path.push(object); + + // Start place to serialize into + var index = startingIndex + 4; + // var self = this; + + // Special case isArray + if (Array.isArray(object)) { + // Get object keys + for (var i = 0; i < object.length; i++) { + var key = '' + i; + var value = object[i]; + + // Is there an override value + if (value && value.toBSON) { + if (typeof value.toBSON !== 'function') throw new Error('toBSON is not a function'); + value = value.toBSON(); + } + + var type = typeof value; + if (type === 'string') { + index = serializeString(buffer, key, value, index, true); + } else if (type === 'number') { + index = serializeNumber(buffer, key, value, index, true); + } else if (type === 'boolean') { + index = serializeBoolean(buffer, key, value, index, true); + } else if (value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index, true); + } else if (value === undefined) { + index = serializeNull(buffer, key, value, index, true); + } else if (value === null) { + index = serializeNull(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'ObjectID' || value['_bsontype'] === 'ObjectId') { + index = serializeObjectId(buffer, key, value, index, true); + } else if (Buffer.isBuffer(value)) { + index = serializeBuffer(buffer, key, value, index, true); + } else if (value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index, true); + } else if (type === 'object' && value['_bsontype'] == null) { + index = serializeObject( + buffer, + key, + value, + index, + checkKeys, + depth, + serializeFunctions, + ignoreUndefined, + true, + path + ); + } else if (type === 'object' && value['_bsontype'] === 'Decimal128') { + index = serializeDecimal128(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { + index = serializeLong(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'Double') { + index = serializeDouble(buffer, key, value, index, true); + } else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction( + buffer, + key, + value, + index, + checkKeys, + depth, + serializeFunctions, + true + ); + } else if (value['_bsontype'] === 'Code') { + index = serializeCode( + buffer, + key, + value, + index, + checkKeys, + depth, + serializeFunctions, + ignoreUndefined, + true + ); + } else if (value['_bsontype'] === 'Binary') { + index = serializeBinary(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'Symbol') { + index = serializeSymbol(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, true); + } else if (value['_bsontype'] === 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'Int32') { + index = serializeInt32(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { + index = serializeMinMax(buffer, key, value, index, true); + } + } + } else if (object instanceof Map) { + var iterator = object.entries(); + var done = false; + + while (!done) { + // Unpack the next entry + var entry = iterator.next(); + done = entry.done; + // Are we done, then skip and terminate + if (done) continue; + + // Get the entry values + key = entry.value[0]; + value = entry.value[1]; + + // Check the type of the value + type = typeof value; + + // Check the key and throw error if it's illegal + if (typeof key === 'string' && ignoreKeys.indexOf(key) === -1) { + if (key.match(regexp) != null) { + // The BSON spec doesn't allow keys with null bytes because keys are + // null-terminated. + throw Error('key ' + key + ' must not contain null bytes'); + } + + if (checkKeys) { + if ('$' === key[0]) { + throw Error('key ' + key + " must not start with '$'"); + } else if (~key.indexOf('.')) { + throw Error('key ' + key + " must not contain '.'"); + } + } + } + + if (type === 'string') { + index = serializeString(buffer, key, value, index); + } else if (type === 'number') { + index = serializeNumber(buffer, key, value, index); + } else if (type === 'boolean') { + index = serializeBoolean(buffer, key, value, index); + } else if (value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index); + // } else if (value === undefined && ignoreUndefined === true) { + } else if (value === null || (value === undefined && ignoreUndefined === false)) { + index = serializeNull(buffer, key, value, index); + } else if (value['_bsontype'] === 'ObjectID' || value['_bsontype'] === 'ObjectId') { + index = serializeObjectId(buffer, key, value, index); + } else if (Buffer.isBuffer(value)) { + index = serializeBuffer(buffer, key, value, index); + } else if (value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index); + } else if (type === 'object' && value['_bsontype'] == null) { + index = serializeObject( + buffer, + key, + value, + index, + checkKeys, + depth, + serializeFunctions, + ignoreUndefined, + false, + path + ); + } else if (type === 'object' && value['_bsontype'] === 'Decimal128') { + index = serializeDecimal128(buffer, key, value, index); + } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { + index = serializeLong(buffer, key, value, index); + } else if (value['_bsontype'] === 'Double') { + index = serializeDouble(buffer, key, value, index); + } else if (value['_bsontype'] === 'Code') { + index = serializeCode( + buffer, + key, + value, + index, + checkKeys, + depth, + serializeFunctions, + ignoreUndefined + ); + } else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); + } else if (value['_bsontype'] === 'Binary') { + index = serializeBinary(buffer, key, value, index); + } else if (value['_bsontype'] === 'Symbol') { + index = serializeSymbol(buffer, key, value, index); + } else if (value['_bsontype'] === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); + } else if (value['_bsontype'] === 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index); + } else if (value['_bsontype'] === 'Int32') { + index = serializeInt32(buffer, key, value, index); + } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { + index = serializeMinMax(buffer, key, value, index); + } + } + } else { + // Did we provide a custom serialization method + if (object.toBSON) { + if (typeof object.toBSON !== 'function') throw new Error('toBSON is not a function'); + object = object.toBSON(); + if (object != null && typeof object !== 'object') + throw new Error('toBSON function did not return an object'); + } + + // Iterate over all the keys + for (key in object) { + value = object[key]; + // Is there an override value + if (value && value.toBSON) { + if (typeof value.toBSON !== 'function') throw new Error('toBSON is not a function'); + value = value.toBSON(); + } + + // Check the type of the value + type = typeof value; + + // Check the key and throw error if it's illegal + if (typeof key === 'string' && ignoreKeys.indexOf(key) === -1) { + if (key.match(regexp) != null) { + // The BSON spec doesn't allow keys with null bytes because keys are + // null-terminated. + throw Error('key ' + key + ' must not contain null bytes'); + } + + if (checkKeys) { + if ('$' === key[0]) { + throw Error('key ' + key + " must not start with '$'"); + } else if (~key.indexOf('.')) { + throw Error('key ' + key + " must not contain '.'"); + } + } + } + + if (type === 'string') { + index = serializeString(buffer, key, value, index); + } else if (type === 'number') { + index = serializeNumber(buffer, key, value, index); + } else if (type === 'boolean') { + index = serializeBoolean(buffer, key, value, index); + } else if (value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index); + } else if (value === undefined) { + if (ignoreUndefined === false) index = serializeNull(buffer, key, value, index); + } else if (value === null) { + index = serializeNull(buffer, key, value, index); + } else if (value['_bsontype'] === 'ObjectID' || value['_bsontype'] === 'ObjectId') { + index = serializeObjectId(buffer, key, value, index); + } else if (Buffer.isBuffer(value)) { + index = serializeBuffer(buffer, key, value, index); + } else if (value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index); + } else if (type === 'object' && value['_bsontype'] == null) { + index = serializeObject( + buffer, + key, + value, + index, + checkKeys, + depth, + serializeFunctions, + ignoreUndefined, + false, + path + ); + } else if (type === 'object' && value['_bsontype'] === 'Decimal128') { + index = serializeDecimal128(buffer, key, value, index); + } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { + index = serializeLong(buffer, key, value, index); + } else if (value['_bsontype'] === 'Double') { + index = serializeDouble(buffer, key, value, index); + } else if (value['_bsontype'] === 'Code') { + index = serializeCode( + buffer, + key, + value, + index, + checkKeys, + depth, + serializeFunctions, + ignoreUndefined + ); + } else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); + } else if (value['_bsontype'] === 'Binary') { + index = serializeBinary(buffer, key, value, index); + } else if (value['_bsontype'] === 'Symbol') { + index = serializeSymbol(buffer, key, value, index); + } else if (value['_bsontype'] === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); + } else if (value['_bsontype'] === 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index); + } else if (value['_bsontype'] === 'Int32') { + index = serializeInt32(buffer, key, value, index); + } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { + index = serializeMinMax(buffer, key, value, index); + } + } + } + + // Remove the path + path.pop(); + + // Final padding byte for object + buffer[index++] = 0x00; + + // Final size + var size = index - startingIndex; + // Write the size of the object + buffer[startingIndex++] = size & 0xff; + buffer[startingIndex++] = (size >> 8) & 0xff; + buffer[startingIndex++] = (size >> 16) & 0xff; + buffer[startingIndex++] = (size >> 24) & 0xff; + return index; +}; + +var BSON = {}; + +/** + * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 + * + * @ignore + * @api private + */ +// var functionCache = (BSON.functionCache = {}); + +/** + * Number BSON Type + * + * @classconstant BSON_DATA_NUMBER + **/ +BSON.BSON_DATA_NUMBER = 1; +/** + * String BSON Type + * + * @classconstant BSON_DATA_STRING + **/ +BSON.BSON_DATA_STRING = 2; +/** + * Object BSON Type + * + * @classconstant BSON_DATA_OBJECT + **/ +BSON.BSON_DATA_OBJECT = 3; +/** + * Array BSON Type + * + * @classconstant BSON_DATA_ARRAY + **/ +BSON.BSON_DATA_ARRAY = 4; +/** + * Binary BSON Type + * + * @classconstant BSON_DATA_BINARY + **/ +BSON.BSON_DATA_BINARY = 5; +/** + * ObjectID BSON Type, deprecated + * + * @classconstant BSON_DATA_UNDEFINED + **/ +BSON.BSON_DATA_UNDEFINED = 6; +/** + * ObjectID BSON Type + * + * @classconstant BSON_DATA_OID + **/ +BSON.BSON_DATA_OID = 7; +/** + * Boolean BSON Type + * + * @classconstant BSON_DATA_BOOLEAN + **/ +BSON.BSON_DATA_BOOLEAN = 8; +/** + * Date BSON Type + * + * @classconstant BSON_DATA_DATE + **/ +BSON.BSON_DATA_DATE = 9; +/** + * null BSON Type + * + * @classconstant BSON_DATA_NULL + **/ +BSON.BSON_DATA_NULL = 10; +/** + * RegExp BSON Type + * + * @classconstant BSON_DATA_REGEXP + **/ +BSON.BSON_DATA_REGEXP = 11; +/** + * Code BSON Type + * + * @classconstant BSON_DATA_CODE + **/ +BSON.BSON_DATA_CODE = 13; +/** + * Symbol BSON Type + * + * @classconstant BSON_DATA_SYMBOL + **/ +BSON.BSON_DATA_SYMBOL = 14; +/** + * Code with Scope BSON Type + * + * @classconstant BSON_DATA_CODE_W_SCOPE + **/ +BSON.BSON_DATA_CODE_W_SCOPE = 15; +/** + * 32 bit Integer BSON Type + * + * @classconstant BSON_DATA_INT + **/ +BSON.BSON_DATA_INT = 16; +/** + * Timestamp BSON Type + * + * @classconstant BSON_DATA_TIMESTAMP + **/ +BSON.BSON_DATA_TIMESTAMP = 17; +/** + * Long BSON Type + * + * @classconstant BSON_DATA_LONG + **/ +BSON.BSON_DATA_LONG = 18; +/** + * Long BSON Type + * + * @classconstant BSON_DATA_DECIMAL128 + **/ +BSON.BSON_DATA_DECIMAL128 = 19; +/** + * MinKey BSON Type + * + * @classconstant BSON_DATA_MIN_KEY + **/ +BSON.BSON_DATA_MIN_KEY = 0xff; +/** + * MaxKey BSON Type + * + * @classconstant BSON_DATA_MAX_KEY + **/ +BSON.BSON_DATA_MAX_KEY = 0x7f; +/** + * Binary Default Type + * + * @classconstant BSON_BINARY_SUBTYPE_DEFAULT + **/ +BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; +/** + * Binary Function Type + * + * @classconstant BSON_BINARY_SUBTYPE_FUNCTION + **/ +BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; +/** + * Binary Byte Array Type + * + * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY + **/ +BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; +/** + * Binary UUID Type + * + * @classconstant BSON_BINARY_SUBTYPE_UUID + **/ +BSON.BSON_BINARY_SUBTYPE_UUID = 3; +/** + * Binary MD5 Type + * + * @classconstant BSON_BINARY_SUBTYPE_MD5 + **/ +BSON.BSON_BINARY_SUBTYPE_MD5 = 4; +/** + * Binary User Defined Type + * + * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED + **/ +BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; + +// BSON MAX VALUES +BSON.BSON_INT32_MAX = 0x7fffffff; +BSON.BSON_INT32_MIN = -0x80000000; + +BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; +BSON.BSON_INT64_MIN = -Math.pow(2, 63); + +// JS MAX PRECISE VALUES +BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. +BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. + +// Internal long versions +// var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. +// var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. + +module.exports = serializeInto; diff --git a/scripts/2.5/node_modules/bson/lib/bson/parser/utils.js b/scripts/2.5/node_modules/bson/lib/bson/parser/utils.js new file mode 100644 index 00000000..6faa4396 --- /dev/null +++ b/scripts/2.5/node_modules/bson/lib/bson/parser/utils.js @@ -0,0 +1,28 @@ +'use strict'; + +/** + * Normalizes our expected stringified form of a function across versions of node + * @param {Function} fn The function to stringify + */ +function normalizedFunctionString(fn) { + return fn.toString().replace(/function *\(/, 'function ('); +} + +function newBuffer(item, encoding) { + return new Buffer(item, encoding); +} + +function allocBuffer() { + return Buffer.alloc.apply(Buffer, arguments); +} + +function toBuffer() { + return Buffer.from.apply(Buffer, arguments); +} + +module.exports = { + normalizedFunctionString: normalizedFunctionString, + allocBuffer: typeof Buffer.alloc === 'function' ? allocBuffer : newBuffer, + toBuffer: typeof Buffer.from === 'function' ? toBuffer : newBuffer +}; + diff --git a/scripts/2.5/node_modules/bson/lib/bson/regexp.js b/scripts/2.5/node_modules/bson/lib/bson/regexp.js new file mode 100644 index 00000000..108f0166 --- /dev/null +++ b/scripts/2.5/node_modules/bson/lib/bson/regexp.js @@ -0,0 +1,33 @@ +/** + * A class representation of the BSON RegExp type. + * + * @class + * @return {BSONRegExp} A MinKey instance + */ +function BSONRegExp(pattern, options) { + if (!(this instanceof BSONRegExp)) return new BSONRegExp(); + + // Execute + this._bsontype = 'BSONRegExp'; + this.pattern = pattern || ''; + this.options = options || ''; + + // Validate options + for (var i = 0; i < this.options.length; i++) { + if ( + !( + this.options[i] === 'i' || + this.options[i] === 'm' || + this.options[i] === 'x' || + this.options[i] === 'l' || + this.options[i] === 's' || + this.options[i] === 'u' + ) + ) { + throw new Error('the regular expression options [' + this.options[i] + '] is not supported'); + } + } +} + +module.exports = BSONRegExp; +module.exports.BSONRegExp = BSONRegExp; diff --git a/scripts/2.5/node_modules/bson/lib/bson/symbol.js b/scripts/2.5/node_modules/bson/lib/bson/symbol.js new file mode 100644 index 00000000..ba20cabe --- /dev/null +++ b/scripts/2.5/node_modules/bson/lib/bson/symbol.js @@ -0,0 +1,50 @@ +// Custom inspect property name / symbol. +var inspect = Buffer ? require('util').inspect.custom || 'inspect' : 'inspect'; + +/** + * A class representation of the BSON Symbol type. + * + * @class + * @deprecated + * @param {string} value the string representing the symbol. + * @return {Symbol} + */ +function Symbol(value) { + if (!(this instanceof Symbol)) return new Symbol(value); + this._bsontype = 'Symbol'; + this.value = value; +} + +/** + * Access the wrapped string value. + * + * @method + * @return {String} returns the wrapped string. + */ +Symbol.prototype.valueOf = function() { + return this.value; +}; + +/** + * @ignore + */ +Symbol.prototype.toString = function() { + return this.value; +}; + +/** + * @ignore + */ +Symbol.prototype[inspect] = function() { + return this.value; +}; + +/** + * @ignore + */ +Symbol.prototype.toJSON = function() { + return this.value; +}; + +module.exports = Symbol; +module.exports.Symbol = Symbol; diff --git a/scripts/2.5/node_modules/bson/lib/bson/timestamp.js b/scripts/2.5/node_modules/bson/lib/bson/timestamp.js new file mode 100644 index 00000000..dc61a6cc --- /dev/null +++ b/scripts/2.5/node_modules/bson/lib/bson/timestamp.js @@ -0,0 +1,854 @@ +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Copyright 2009 Google Inc. All Rights Reserved + +/** + * This type is for INTERNAL use in MongoDB only and should not be used in applications. + * The appropriate corresponding type is the JavaScript Date type. + * + * Defines a Timestamp class for representing a 64-bit two's-complement + * integer value, which faithfully simulates the behavior of a Java "Timestamp". This + * implementation is derived from TimestampLib in GWT. + * + * Constructs a 64-bit two's-complement integer, given its low and high 32-bit + * values as *signed* integers. See the from* functions below for more + * convenient ways of constructing Timestamps. + * + * The internal representation of a Timestamp is the two given signed, 32-bit values. + * We use 32-bit pieces because these are the size of integers on which + * Javascript performs bit-operations. For operations like addition and + * multiplication, we split each number into 16-bit pieces, which can easily be + * multiplied within Javascript's floating-point representation without overflow + * or change in sign. + * + * In the algorithms below, we frequently reduce the negative case to the + * positive case by negating the input(s) and then post-processing the result. + * Note that we must ALWAYS check specially whether those values are MIN_VALUE + * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as + * a positive number, it overflows back into a negative). Not handling this + * case would often result in infinite recursion. + * + * @class + * @param {number} low the low (signed) 32 bits of the Timestamp. + * @param {number} high the high (signed) 32 bits of the Timestamp. + */ +function Timestamp(low, high) { + if (!(this instanceof Timestamp)) return new Timestamp(low, high); + this._bsontype = 'Timestamp'; + /** + * @type {number} + * @ignore + */ + this.low_ = low | 0; // force into 32 signed bits. + + /** + * @type {number} + * @ignore + */ + this.high_ = high | 0; // force into 32 signed bits. +} + +/** + * Return the int value. + * + * @return {number} the value, assuming it is a 32-bit integer. + */ +Timestamp.prototype.toInt = function() { + return this.low_; +}; + +/** + * Return the Number value. + * + * @method + * @return {number} the closest floating-point representation to this value. + */ +Timestamp.prototype.toNumber = function() { + return this.high_ * Timestamp.TWO_PWR_32_DBL_ + this.getLowBitsUnsigned(); +}; + +/** + * Return the JSON value. + * + * @method + * @return {string} the JSON representation. + */ +Timestamp.prototype.toJSON = function() { + return this.toString(); +}; + +/** + * Return the String value. + * + * @method + * @param {number} [opt_radix] the radix in which the text should be written. + * @return {string} the textual representation of this value. + */ +Timestamp.prototype.toString = function(opt_radix) { + var radix = opt_radix || 10; + if (radix < 2 || 36 < radix) { + throw Error('radix out of range: ' + radix); + } + + if (this.isZero()) { + return '0'; + } + + if (this.isNegative()) { + if (this.equals(Timestamp.MIN_VALUE)) { + // We need to change the Timestamp value before it can be negated, so we remove + // the bottom-most digit in this base and then recurse to do the rest. + var radixTimestamp = Timestamp.fromNumber(radix); + var div = this.div(radixTimestamp); + var rem = div.multiply(radixTimestamp).subtract(this); + return div.toString(radix) + rem.toInt().toString(radix); + } else { + return '-' + this.negate().toString(radix); + } + } + + // Do several (6) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = Timestamp.fromNumber(Math.pow(radix, 6)); + + rem = this; + var result = ''; + + while (!rem.isZero()) { + var remDiv = rem.div(radixToPower); + var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); + var digits = intval.toString(radix); + + rem = remDiv; + if (rem.isZero()) { + return digits + result; + } else { + while (digits.length < 6) { + digits = '0' + digits; + } + result = '' + digits + result; + } + } +}; + +/** + * Return the high 32-bits value. + * + * @method + * @return {number} the high 32-bits as a signed value. + */ +Timestamp.prototype.getHighBits = function() { + return this.high_; +}; + +/** + * Return the low 32-bits value. + * + * @method + * @return {number} the low 32-bits as a signed value. + */ +Timestamp.prototype.getLowBits = function() { + return this.low_; +}; + +/** + * Return the low unsigned 32-bits value. + * + * @method + * @return {number} the low 32-bits as an unsigned value. + */ +Timestamp.prototype.getLowBitsUnsigned = function() { + return this.low_ >= 0 ? this.low_ : Timestamp.TWO_PWR_32_DBL_ + this.low_; +}; + +/** + * Returns the number of bits needed to represent the absolute value of this Timestamp. + * + * @method + * @return {number} Returns the number of bits needed to represent the absolute value of this Timestamp. + */ +Timestamp.prototype.getNumBitsAbs = function() { + if (this.isNegative()) { + if (this.equals(Timestamp.MIN_VALUE)) { + return 64; + } else { + return this.negate().getNumBitsAbs(); + } + } else { + var val = this.high_ !== 0 ? this.high_ : this.low_; + for (var bit = 31; bit > 0; bit--) { + if ((val & (1 << bit)) !== 0) { + break; + } + } + return this.high_ !== 0 ? bit + 33 : bit + 1; + } +}; + +/** + * Return whether this value is zero. + * + * @method + * @return {boolean} whether this value is zero. + */ +Timestamp.prototype.isZero = function() { + return this.high_ === 0 && this.low_ === 0; +}; + +/** + * Return whether this value is negative. + * + * @method + * @return {boolean} whether this value is negative. + */ +Timestamp.prototype.isNegative = function() { + return this.high_ < 0; +}; + +/** + * Return whether this value is odd. + * + * @method + * @return {boolean} whether this value is odd. + */ +Timestamp.prototype.isOdd = function() { + return (this.low_ & 1) === 1; +}; + +/** + * Return whether this Timestamp equals the other + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp equals the other + */ +Timestamp.prototype.equals = function(other) { + return this.high_ === other.high_ && this.low_ === other.low_; +}; + +/** + * Return whether this Timestamp does not equal the other. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp does not equal the other. + */ +Timestamp.prototype.notEquals = function(other) { + return this.high_ !== other.high_ || this.low_ !== other.low_; +}; + +/** + * Return whether this Timestamp is less than the other. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp is less than the other. + */ +Timestamp.prototype.lessThan = function(other) { + return this.compare(other) < 0; +}; + +/** + * Return whether this Timestamp is less than or equal to the other. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp is less than or equal to the other. + */ +Timestamp.prototype.lessThanOrEqual = function(other) { + return this.compare(other) <= 0; +}; + +/** + * Return whether this Timestamp is greater than the other. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp is greater than the other. + */ +Timestamp.prototype.greaterThan = function(other) { + return this.compare(other) > 0; +}; + +/** + * Return whether this Timestamp is greater than or equal to the other. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp is greater than or equal to the other. + */ +Timestamp.prototype.greaterThanOrEqual = function(other) { + return this.compare(other) >= 0; +}; + +/** + * Compares this Timestamp with the given one. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. + */ +Timestamp.prototype.compare = function(other) { + if (this.equals(other)) { + return 0; + } + + var thisNeg = this.isNegative(); + var otherNeg = other.isNegative(); + if (thisNeg && !otherNeg) { + return -1; + } + if (!thisNeg && otherNeg) { + return 1; + } + + // at this point, the signs are the same, so subtraction will not overflow + if (this.subtract(other).isNegative()) { + return -1; + } else { + return 1; + } +}; + +/** + * The negation of this value. + * + * @method + * @return {Timestamp} the negation of this value. + */ +Timestamp.prototype.negate = function() { + if (this.equals(Timestamp.MIN_VALUE)) { + return Timestamp.MIN_VALUE; + } else { + return this.not().add(Timestamp.ONE); + } +}; + +/** + * Returns the sum of this and the given Timestamp. + * + * @method + * @param {Timestamp} other Timestamp to add to this one. + * @return {Timestamp} the sum of this and the given Timestamp. + */ +Timestamp.prototype.add = function(other) { + // Divide each number into 4 chunks of 16 bits, and then sum the chunks. + + var a48 = this.high_ >>> 16; + var a32 = this.high_ & 0xffff; + var a16 = this.low_ >>> 16; + var a00 = this.low_ & 0xffff; + + var b48 = other.high_ >>> 16; + var b32 = other.high_ & 0xffff; + var b16 = other.low_ >>> 16; + var b00 = other.low_ & 0xffff; + + var c48 = 0, + c32 = 0, + c16 = 0, + c00 = 0; + c00 += a00 + b00; + c16 += c00 >>> 16; + c00 &= 0xffff; + c16 += a16 + b16; + c32 += c16 >>> 16; + c16 &= 0xffff; + c32 += a32 + b32; + c48 += c32 >>> 16; + c32 &= 0xffff; + c48 += a48 + b48; + c48 &= 0xffff; + return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32); +}; + +/** + * Returns the difference of this and the given Timestamp. + * + * @method + * @param {Timestamp} other Timestamp to subtract from this. + * @return {Timestamp} the difference of this and the given Timestamp. + */ +Timestamp.prototype.subtract = function(other) { + return this.add(other.negate()); +}; + +/** + * Returns the product of this and the given Timestamp. + * + * @method + * @param {Timestamp} other Timestamp to multiply with this. + * @return {Timestamp} the product of this and the other. + */ +Timestamp.prototype.multiply = function(other) { + if (this.isZero()) { + return Timestamp.ZERO; + } else if (other.isZero()) { + return Timestamp.ZERO; + } + + if (this.equals(Timestamp.MIN_VALUE)) { + return other.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; + } else if (other.equals(Timestamp.MIN_VALUE)) { + return this.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; + } + + if (this.isNegative()) { + if (other.isNegative()) { + return this.negate().multiply(other.negate()); + } else { + return this.negate() + .multiply(other) + .negate(); + } + } else if (other.isNegative()) { + return this.multiply(other.negate()).negate(); + } + + // If both Timestamps are small, use float multiplication + if (this.lessThan(Timestamp.TWO_PWR_24_) && other.lessThan(Timestamp.TWO_PWR_24_)) { + return Timestamp.fromNumber(this.toNumber() * other.toNumber()); + } + + // Divide each Timestamp into 4 chunks of 16 bits, and then add up 4x4 products. + // We can skip products that would overflow. + + var a48 = this.high_ >>> 16; + var a32 = this.high_ & 0xffff; + var a16 = this.low_ >>> 16; + var a00 = this.low_ & 0xffff; + + var b48 = other.high_ >>> 16; + var b32 = other.high_ & 0xffff; + var b16 = other.low_ >>> 16; + var b00 = other.low_ & 0xffff; + + var c48 = 0, + c32 = 0, + c16 = 0, + c00 = 0; + c00 += a00 * b00; + c16 += c00 >>> 16; + c00 &= 0xffff; + c16 += a16 * b00; + c32 += c16 >>> 16; + c16 &= 0xffff; + c16 += a00 * b16; + c32 += c16 >>> 16; + c16 &= 0xffff; + c32 += a32 * b00; + c48 += c32 >>> 16; + c32 &= 0xffff; + c32 += a16 * b16; + c48 += c32 >>> 16; + c32 &= 0xffff; + c32 += a00 * b32; + c48 += c32 >>> 16; + c32 &= 0xffff; + c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; + c48 &= 0xffff; + return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32); +}; + +/** + * Returns this Timestamp divided by the given one. + * + * @method + * @param {Timestamp} other Timestamp by which to divide. + * @return {Timestamp} this Timestamp divided by the given one. + */ +Timestamp.prototype.div = function(other) { + if (other.isZero()) { + throw Error('division by zero'); + } else if (this.isZero()) { + return Timestamp.ZERO; + } + + if (this.equals(Timestamp.MIN_VALUE)) { + if (other.equals(Timestamp.ONE) || other.equals(Timestamp.NEG_ONE)) { + return Timestamp.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE + } else if (other.equals(Timestamp.MIN_VALUE)) { + return Timestamp.ONE; + } else { + // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. + var halfThis = this.shiftRight(1); + var approx = halfThis.div(other).shiftLeft(1); + if (approx.equals(Timestamp.ZERO)) { + return other.isNegative() ? Timestamp.ONE : Timestamp.NEG_ONE; + } else { + var rem = this.subtract(other.multiply(approx)); + var result = approx.add(rem.div(other)); + return result; + } + } + } else if (other.equals(Timestamp.MIN_VALUE)) { + return Timestamp.ZERO; + } + + if (this.isNegative()) { + if (other.isNegative()) { + return this.negate().div(other.negate()); + } else { + return this.negate() + .div(other) + .negate(); + } + } else if (other.isNegative()) { + return this.div(other.negate()).negate(); + } + + // Repeat the following until the remainder is less than other: find a + // floating-point that approximates remainder / other *from below*, add this + // into the result, and subtract it from the remainder. It is critical that + // the approximate value is less than or equal to the real value so that the + // remainder never becomes negative. + var res = Timestamp.ZERO; + rem = this; + while (rem.greaterThanOrEqual(other)) { + // Approximate the result of division. This may be a little greater or + // smaller than the actual value. + approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); + + // We will tweak the approximate result by changing it in the 48-th digit or + // the smallest non-fractional digit, whichever is larger. + var log2 = Math.ceil(Math.log(approx) / Math.LN2); + var delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48); + + // Decrease the approximation until it is smaller than the remainder. Note + // that if it is too large, the product overflows and is negative. + var approxRes = Timestamp.fromNumber(approx); + var approxRem = approxRes.multiply(other); + while (approxRem.isNegative() || approxRem.greaterThan(rem)) { + approx -= delta; + approxRes = Timestamp.fromNumber(approx); + approxRem = approxRes.multiply(other); + } + + // We know the answer can't be zero... and actually, zero would cause + // infinite recursion since we would make no progress. + if (approxRes.isZero()) { + approxRes = Timestamp.ONE; + } + + res = res.add(approxRes); + rem = rem.subtract(approxRem); + } + return res; +}; + +/** + * Returns this Timestamp modulo the given one. + * + * @method + * @param {Timestamp} other Timestamp by which to mod. + * @return {Timestamp} this Timestamp modulo the given one. + */ +Timestamp.prototype.modulo = function(other) { + return this.subtract(this.div(other).multiply(other)); +}; + +/** + * The bitwise-NOT of this value. + * + * @method + * @return {Timestamp} the bitwise-NOT of this value. + */ +Timestamp.prototype.not = function() { + return Timestamp.fromBits(~this.low_, ~this.high_); +}; + +/** + * Returns the bitwise-AND of this Timestamp and the given one. + * + * @method + * @param {Timestamp} other the Timestamp with which to AND. + * @return {Timestamp} the bitwise-AND of this and the other. + */ +Timestamp.prototype.and = function(other) { + return Timestamp.fromBits(this.low_ & other.low_, this.high_ & other.high_); +}; + +/** + * Returns the bitwise-OR of this Timestamp and the given one. + * + * @method + * @param {Timestamp} other the Timestamp with which to OR. + * @return {Timestamp} the bitwise-OR of this and the other. + */ +Timestamp.prototype.or = function(other) { + return Timestamp.fromBits(this.low_ | other.low_, this.high_ | other.high_); +}; + +/** + * Returns the bitwise-XOR of this Timestamp and the given one. + * + * @method + * @param {Timestamp} other the Timestamp with which to XOR. + * @return {Timestamp} the bitwise-XOR of this and the other. + */ +Timestamp.prototype.xor = function(other) { + return Timestamp.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); +}; + +/** + * Returns this Timestamp with bits shifted to the left by the given amount. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Timestamp} this shifted to the left by the given amount. + */ +Timestamp.prototype.shiftLeft = function(numBits) { + numBits &= 63; + if (numBits === 0) { + return this; + } else { + var low = this.low_; + if (numBits < 32) { + var high = this.high_; + return Timestamp.fromBits(low << numBits, (high << numBits) | (low >>> (32 - numBits))); + } else { + return Timestamp.fromBits(0, low << (numBits - 32)); + } + } +}; + +/** + * Returns this Timestamp with bits shifted to the right by the given amount. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Timestamp} this shifted to the right by the given amount. + */ +Timestamp.prototype.shiftRight = function(numBits) { + numBits &= 63; + if (numBits === 0) { + return this; + } else { + var high = this.high_; + if (numBits < 32) { + var low = this.low_; + return Timestamp.fromBits((low >>> numBits) | (high << (32 - numBits)), high >> numBits); + } else { + return Timestamp.fromBits(high >> (numBits - 32), high >= 0 ? 0 : -1); + } + } +}; + +/** + * Returns this Timestamp with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Timestamp} this shifted to the right by the given amount, with zeros placed into the new leading bits. + */ +Timestamp.prototype.shiftRightUnsigned = function(numBits) { + numBits &= 63; + if (numBits === 0) { + return this; + } else { + var high = this.high_; + if (numBits < 32) { + var low = this.low_; + return Timestamp.fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits); + } else if (numBits === 32) { + return Timestamp.fromBits(high, 0); + } else { + return Timestamp.fromBits(high >>> (numBits - 32), 0); + } + } +}; + +/** + * Returns a Timestamp representing the given (32-bit) integer value. + * + * @method + * @param {number} value the 32-bit integer in question. + * @return {Timestamp} the corresponding Timestamp value. + */ +Timestamp.fromInt = function(value) { + if (-128 <= value && value < 128) { + var cachedObj = Timestamp.INT_CACHE_[value]; + if (cachedObj) { + return cachedObj; + } + } + + var obj = new Timestamp(value | 0, value < 0 ? -1 : 0); + if (-128 <= value && value < 128) { + Timestamp.INT_CACHE_[value] = obj; + } + return obj; +}; + +/** + * Returns a Timestamp representing the given value, provided that it is a finite number. Otherwise, zero is returned. + * + * @method + * @param {number} value the number in question. + * @return {Timestamp} the corresponding Timestamp value. + */ +Timestamp.fromNumber = function(value) { + if (isNaN(value) || !isFinite(value)) { + return Timestamp.ZERO; + } else if (value <= -Timestamp.TWO_PWR_63_DBL_) { + return Timestamp.MIN_VALUE; + } else if (value + 1 >= Timestamp.TWO_PWR_63_DBL_) { + return Timestamp.MAX_VALUE; + } else if (value < 0) { + return Timestamp.fromNumber(-value).negate(); + } else { + return new Timestamp( + (value % Timestamp.TWO_PWR_32_DBL_) | 0, + (value / Timestamp.TWO_PWR_32_DBL_) | 0 + ); + } +}; + +/** + * Returns a Timestamp representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. + * + * @method + * @param {number} lowBits the low 32-bits. + * @param {number} highBits the high 32-bits. + * @return {Timestamp} the corresponding Timestamp value. + */ +Timestamp.fromBits = function(lowBits, highBits) { + return new Timestamp(lowBits, highBits); +}; + +/** + * Returns a Timestamp representation of the given string, written using the given radix. + * + * @method + * @param {string} str the textual representation of the Timestamp. + * @param {number} opt_radix the radix in which the text is written. + * @return {Timestamp} the corresponding Timestamp value. + */ +Timestamp.fromString = function(str, opt_radix) { + if (str.length === 0) { + throw Error('number format error: empty string'); + } + + var radix = opt_radix || 10; + if (radix < 2 || 36 < radix) { + throw Error('radix out of range: ' + radix); + } + + if (str.charAt(0) === '-') { + return Timestamp.fromString(str.substring(1), radix).negate(); + } else if (str.indexOf('-') >= 0) { + throw Error('number format error: interior "-" character: ' + str); + } + + // Do several (8) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = Timestamp.fromNumber(Math.pow(radix, 8)); + + var result = Timestamp.ZERO; + for (var i = 0; i < str.length; i += 8) { + var size = Math.min(8, str.length - i); + var value = parseInt(str.substring(i, i + size), radix); + if (size < 8) { + var power = Timestamp.fromNumber(Math.pow(radix, size)); + result = result.multiply(power).add(Timestamp.fromNumber(value)); + } else { + result = result.multiply(radixToPower); + result = result.add(Timestamp.fromNumber(value)); + } + } + return result; +}; + +// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the +// from* methods on which they depend. + +/** + * A cache of the Timestamp representations of small integer values. + * @type {Object} + * @ignore + */ +Timestamp.INT_CACHE_ = {}; + +// NOTE: the compiler should inline these constant values below and then remove +// these variables, so there should be no runtime penalty for these. + +/** + * Number used repeated below in calculations. This must appear before the + * first call to any from* function below. + * @type {number} + * @ignore + */ +Timestamp.TWO_PWR_16_DBL_ = 1 << 16; + +/** + * @type {number} + * @ignore + */ +Timestamp.TWO_PWR_24_DBL_ = 1 << 24; + +/** + * @type {number} + * @ignore + */ +Timestamp.TWO_PWR_32_DBL_ = Timestamp.TWO_PWR_16_DBL_ * Timestamp.TWO_PWR_16_DBL_; + +/** + * @type {number} + * @ignore + */ +Timestamp.TWO_PWR_31_DBL_ = Timestamp.TWO_PWR_32_DBL_ / 2; + +/** + * @type {number} + * @ignore + */ +Timestamp.TWO_PWR_48_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_16_DBL_; + +/** + * @type {number} + * @ignore + */ +Timestamp.TWO_PWR_64_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_32_DBL_; + +/** + * @type {number} + * @ignore + */ +Timestamp.TWO_PWR_63_DBL_ = Timestamp.TWO_PWR_64_DBL_ / 2; + +/** @type {Timestamp} */ +Timestamp.ZERO = Timestamp.fromInt(0); + +/** @type {Timestamp} */ +Timestamp.ONE = Timestamp.fromInt(1); + +/** @type {Timestamp} */ +Timestamp.NEG_ONE = Timestamp.fromInt(-1); + +/** @type {Timestamp} */ +Timestamp.MAX_VALUE = Timestamp.fromBits(0xffffffff | 0, 0x7fffffff | 0); + +/** @type {Timestamp} */ +Timestamp.MIN_VALUE = Timestamp.fromBits(0, 0x80000000 | 0); + +/** + * @type {Timestamp} + * @ignore + */ +Timestamp.TWO_PWR_24_ = Timestamp.fromInt(1 << 24); + +/** + * Expose. + */ +module.exports = Timestamp; +module.exports.Timestamp = Timestamp; diff --git a/scripts/2.5/node_modules/bson/package.json b/scripts/2.5/node_modules/bson/package.json new file mode 100644 index 00000000..fe065124 --- /dev/null +++ b/scripts/2.5/node_modules/bson/package.json @@ -0,0 +1,87 @@ +{ + "_from": "bson@^1.1.1", + "_id": "bson@1.1.1", + "_inBundle": false, + "_integrity": "sha512-jCGVYLoYMHDkOsbwJZBCqwMHyH4c+wzgI9hG7Z6SZJRXWr+x58pdIbm2i9a/jFGCkRJqRUr8eoI7lDWa0hTkxg==", + "_location": "/bson", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "bson@^1.1.1", + "name": "bson", + "escapedName": "bson", + "rawSpec": "^1.1.1", + "saveSpec": null, + "fetchSpec": "^1.1.1" + }, + "_requiredBy": [ + "/mongodb" + ], + "_resolved": "https://registry.npmjs.org/bson/-/bson-1.1.1.tgz", + "_shasum": "4330f5e99104c4e751e7351859e2d408279f2f13", + "_spec": "bson@^1.1.1", + "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/2.5/node_modules/mongodb", + "author": { + "name": "Christian Amor Kvalheim", + "email": "christkv@gmail.com" + }, + "browser": "lib/bson/bson.js", + "bugs": { + "url": "https://github.com/mongodb/js-bson/issues" + }, + "bundleDependencies": false, + "config": { + "native": false + }, + "contributors": [], + "deprecated": false, + "description": "A bson parser for node.js and the browser", + "devDependencies": { + "babel-core": "^6.14.0", + "babel-loader": "^6.2.5", + "babel-polyfill": "^6.13.0", + "babel-preset-es2015": "^6.14.0", + "babel-preset-stage-0": "^6.5.0", + "babel-register": "^6.14.0", + "benchmark": "1.0.0", + "colors": "1.1.0", + "conventional-changelog-cli": "^1.3.5", + "nodeunit": "0.9.0", + "webpack": "^1.13.2", + "webpack-polyfills-plugin": "0.0.9" + }, + "directories": { + "lib": "./lib/bson" + }, + "engines": { + "node": ">=0.6.19" + }, + "files": [ + "lib", + "index.js", + "browser_build", + "bower.json" + ], + "homepage": "https://github.com/mongodb/js-bson#readme", + "keywords": [ + "mongodb", + "bson", + "parser" + ], + "license": "Apache-2.0", + "main": "./index", + "name": "bson", + "repository": { + "type": "git", + "url": "git+https://github.com/mongodb/js-bson.git" + }, + "scripts": { + "build": "webpack --config ./webpack.dist.config.js", + "changelog": "conventional-changelog -p angular -i HISTORY.md -s", + "format": "prettier --print-width 100 --tab-width 2 --single-quote --write 'test/**/*.js' 'lib/**/*.js'", + "lint": "eslint lib test", + "test": "nodeunit ./test/node" + }, + "version": "1.1.1" +} diff --git a/scripts/2.5/node_modules/define-properties/.editorconfig b/scripts/2.5/node_modules/define-properties/.editorconfig new file mode 100644 index 00000000..eaa21416 --- /dev/null +++ b/scripts/2.5/node_modules/define-properties/.editorconfig @@ -0,0 +1,13 @@ +root = true + +[*] +indent_style = tab; +insert_final_newline = true; +quote_type = auto; +space_after_anonymous_functions = true; +space_after_control_statements = true; +spaces_around_operators = true; +trim_trailing_whitespace = true; +spaces_in_brackets = false; +end_of_line = lf; + diff --git a/scripts/2.5/node_modules/define-properties/.eslintrc b/scripts/2.5/node_modules/define-properties/.eslintrc new file mode 100644 index 00000000..db992d7a --- /dev/null +++ b/scripts/2.5/node_modules/define-properties/.eslintrc @@ -0,0 +1,12 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "id-length": [2, { "min": 1, "max": 35 }], + "max-lines-per-function": [2, 100], + "max-params": [2, 4], + "max-statements": [2, 13] + } +} diff --git a/scripts/2.5/node_modules/define-properties/.jscs.json b/scripts/2.5/node_modules/define-properties/.jscs.json new file mode 100644 index 00000000..6f2d7f9f --- /dev/null +++ b/scripts/2.5/node_modules/define-properties/.jscs.json @@ -0,0 +1,175 @@ +{ + "es3": true, + + "additionalRules": [], + + "requireSemicolons": true, + + "disallowMultipleSpaces": true, + + "disallowIdentifierNames": [], + + "requireCurlyBraces": { + "allExcept": [], + "keywords": ["if", "else", "for", "while", "do", "try", "catch"] + }, + + "requireSpaceAfterKeywords": ["if", "else", "for", "while", "do", "switch", "return", "try", "catch", "function"], + + "disallowSpaceAfterKeywords": [], + + "disallowSpaceBeforeComma": true, + "disallowSpaceAfterComma": false, + "disallowSpaceBeforeSemicolon": true, + + "disallowNodeTypes": [ + "DebuggerStatement", + "LabeledStatement", + "SwitchCase", + "SwitchStatement", + "WithStatement" + ], + + "requireObjectKeysOnNewLine": { "allExcept": ["sameLine"] }, + + "requireSpacesInAnonymousFunctionExpression": { "beforeOpeningRoundBrace": true, "beforeOpeningCurlyBrace": true }, + "requireSpacesInNamedFunctionExpression": { "beforeOpeningCurlyBrace": true }, + "disallowSpacesInNamedFunctionExpression": { "beforeOpeningRoundBrace": true }, + "requireSpacesInFunctionDeclaration": { "beforeOpeningCurlyBrace": true }, + "disallowSpacesInFunctionDeclaration": { "beforeOpeningRoundBrace": true }, + + "requireSpaceBetweenArguments": true, + + "disallowSpacesInsideParentheses": true, + + "disallowSpacesInsideArrayBrackets": true, + + "disallowQuotedKeysInObjects": { "allExcept": ["reserved"] }, + + "disallowSpaceAfterObjectKeys": true, + + "requireCommaBeforeLineBreak": true, + + "disallowSpaceAfterPrefixUnaryOperators": ["++", "--", "+", "-", "~", "!"], + "requireSpaceAfterPrefixUnaryOperators": [], + + "disallowSpaceBeforePostfixUnaryOperators": ["++", "--"], + "requireSpaceBeforePostfixUnaryOperators": [], + + "disallowSpaceBeforeBinaryOperators": [], + "requireSpaceBeforeBinaryOperators": ["+", "-", "/", "*", "=", "==", "===", "!=", "!=="], + + "requireSpaceAfterBinaryOperators": ["+", "-", "/", "*", "=", "==", "===", "!=", "!=="], + "disallowSpaceAfterBinaryOperators": [], + + "disallowImplicitTypeConversion": ["binary", "string"], + + "disallowKeywords": ["with", "eval"], + + "requireKeywordsOnNewLine": [], + "disallowKeywordsOnNewLine": ["else"], + + "requireLineFeedAtFileEnd": true, + + "disallowTrailingWhitespace": true, + + "disallowTrailingComma": true, + + "excludeFiles": ["node_modules/**", "vendor/**"], + + "disallowMultipleLineStrings": true, + + "requireDotNotation": { "allExcept": ["keywords"] }, + + "requireParenthesesAroundIIFE": true, + + "validateLineBreaks": "LF", + + "validateQuoteMarks": { + "escape": true, + "mark": "'" + }, + + "disallowOperatorBeforeLineBreak": [], + + "requireSpaceBeforeKeywords": [ + "do", + "for", + "if", + "else", + "switch", + "case", + "try", + "catch", + "finally", + "while", + "with", + "return" + ], + + "validateAlignedFunctionParameters": { + "lineBreakAfterOpeningBraces": true, + "lineBreakBeforeClosingBraces": true + }, + + "requirePaddingNewLinesBeforeExport": true, + + "validateNewlineAfterArrayElements": { + "maximum": 3 + }, + + "requirePaddingNewLinesAfterUseStrict": true, + + "disallowArrowFunctions": true, + + "disallowMultiLineTernary": true, + + "validateOrderInObjectKeys": "asc-insensitive", + + "disallowIdenticalDestructuringNames": true, + + "disallowNestedTernaries": { "maxLevel": 1 }, + + "requireSpaceAfterComma": { "allExcept": ["trailing"] }, + "requireAlignedMultilineParams": false, + + "requireSpacesInGenerator": { + "afterStar": true + }, + + "disallowSpacesInGenerator": { + "beforeStar": true + }, + + "disallowVar": false, + + "requireArrayDestructuring": false, + + "requireEnhancedObjectLiterals": false, + + "requireObjectDestructuring": false, + + "requireEarlyReturn": false, + + "requireCapitalizedConstructorsNew": { + "allExcept": ["Function", "String", "Object", "Symbol", "Number", "Date", "RegExp", "Error", "Boolean", "Array"] + }, + + "requireImportAlphabetized": false, + + "requireSpaceBeforeObjectValues": true, + "requireSpaceBeforeDestructuredValues": true, + + "disallowSpacesInsideTemplateStringPlaceholders": true, + + "disallowArrayDestructuringReturn": false, + + "requireNewlineBeforeSingleStatementsInIf": false, + + "disallowUnusedVariables": true, + + "requireSpacesInsideImportedObjectBraces": true, + + "requireUseStrict": true +} + diff --git a/scripts/2.5/node_modules/define-properties/.travis.yml b/scripts/2.5/node_modules/define-properties/.travis.yml new file mode 100644 index 00000000..ec72d5f3 --- /dev/null +++ b/scripts/2.5/node_modules/define-properties/.travis.yml @@ -0,0 +1,233 @@ +language: node_js +os: + - linux +node_js: + - "10.8" + - "9.11" + - "8.11" + - "7.10" + - "6.14" + - "5.12" + - "4.9" + - "iojs-v3.3" + - "iojs-v2.5" + - "iojs-v1.8" + - "0.12" + - "0.10" + - "0.8" +before_install: + - 'case "${TRAVIS_NODE_VERSION}" in 0.*) export NPM_CONFIG_STRICT_SSL=false ;; esac' + - 'nvm install-latest-npm' +install: + - 'if [ "${TRAVIS_NODE_VERSION}" = "0.6" ] || [ "${TRAVIS_NODE_VERSION}" = "0.9" ]; then nvm install --latest-npm 0.8 && npm install && nvm use "${TRAVIS_NODE_VERSION}"; else npm install; fi;' +script: + - 'if [ -n "${PRETEST-}" ]; then npm run pretest ; fi' + - 'if [ -n "${POSTTEST-}" ]; then npm run posttest ; fi' + - 'if [ -n "${COVERAGE-}" ]; then npm run coverage ; fi' + - 'if [ -n "${TEST-}" ]; then npm run tests-only ; fi' +sudo: false +env: + - TEST=true +matrix: + fast_finish: true + include: + - node_js: "lts/*" + env: PRETEST=true + - node_js: "lts/*" + env: POSTTEST=true + - node_js: "4" + env: COVERAGE=true + - node_js: "10.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.13" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.12" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v3.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v3.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v3.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.4" + env: TEST=true ALLOW_FAILURE=true + allow_failures: + - os: osx + - env: TEST=true ALLOW_FAILURE=true + - env: COVERAGE=true diff --git a/scripts/2.5/node_modules/define-properties/CHANGELOG.md b/scripts/2.5/node_modules/define-properties/CHANGELOG.md new file mode 100644 index 00000000..5cad1e26 --- /dev/null +++ b/scripts/2.5/node_modules/define-properties/CHANGELOG.md @@ -0,0 +1,44 @@ +1.1.3 / 2018-08-14 +================= + * [Refactor] use a for loop instead of `foreach` to make for smaller bundle sizes + * [Robustness] cache `Array.prototype.concat` and `Object.defineProperty` + * [Deps] update `object-keys` + * [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `nsp`, `tape`, `jscs`; remove unused eccheck script + dep + * [Tests] use pretest/posttest for linting/security + * [Tests] fix npm upgrades on older nodes + +1.1.2 / 2015-10-14 +================= + * [Docs] Switch from vb.teelaun.ch to versionbadg.es for the npm version badge SVG + * [Deps] Update `object-keys` + * [Dev Deps] update `jscs`, `tape`, `eslint`, `@ljharb/eslint-config`, `nsp` + * [Tests] up to `io.js` `v3.3`, `node` `v4.2` + +1.1.1 / 2015-07-21 +================= + * [Deps] Update `object-keys` + * [Dev Deps] Update `tape`, `eslint` + * [Tests] Test on `io.js` `v2.4` + +1.1.0 / 2015-07-01 +================= + * [New] Add support for symbol-valued properties. + * [Dev Deps] Update `nsp`, `eslint` + * [Tests] Test up to `io.js` `v2.3` + +1.0.3 / 2015-05-30 +================= + * Using a more reliable check for supported property descriptors. + +1.0.2 / 2015-05-23 +================= + * Test up to `io.js` `v2.0` + * Update `tape`, `jscs`, `nsp`, `eslint`, `object-keys`, `editorconfig-tools`, `covert` + +1.0.1 / 2015-01-06 +================= + * Update `object-keys` to fix ES3 support + +1.0.0 / 2015-01-04 +================= + * v1.0.0 diff --git a/scripts/2.5/node_modules/define-properties/LICENSE b/scripts/2.5/node_modules/define-properties/LICENSE new file mode 100644 index 00000000..8c271c14 --- /dev/null +++ b/scripts/2.5/node_modules/define-properties/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (C) 2015 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. \ No newline at end of file diff --git a/scripts/2.5/node_modules/define-properties/README.md b/scripts/2.5/node_modules/define-properties/README.md new file mode 100644 index 00000000..33b6111f --- /dev/null +++ b/scripts/2.5/node_modules/define-properties/README.md @@ -0,0 +1,86 @@ +#define-properties [![Version Badge][npm-version-svg]][package-url] + +[![Build Status][travis-svg]][travis-url] +[![dependency status][deps-svg]][deps-url] +[![dev dependency status][dev-deps-svg]][dev-deps-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +[![browser support][testling-svg]][testling-url] + +Define multiple non-enumerable properties at once. Uses `Object.defineProperty` when available; falls back to standard assignment in older engines. +Existing properties are not overridden. Accepts a map of property names to a predicate that, when true, force-overrides. + +## Example + +```js +var define = require('define-properties'); +var assert = require('assert'); + +var obj = define({ a: 1, b: 2 }, { + a: 10, + b: 20, + c: 30 +}); +assert(obj.a === 1); +assert(obj.b === 2); +assert(obj.c === 30); +if (define.supportsDescriptors) { + assert.deepEqual(Object.keys(obj), ['a', 'b']); + assert.deepEqual(Object.getOwnPropertyDescriptor(obj, 'c'), { + configurable: true, + enumerable: false, + value: 30, + writable: false + }); +} +``` + +Then, with predicates: +```js +var define = require('define-properties'); +var assert = require('assert'); + +var obj = define({ a: 1, b: 2, c: 3 }, { + a: 10, + b: 20, + c: 30 +}, { + a: function () { return false; }, + b: function () { return true; } +}); +assert(obj.a === 1); +assert(obj.b === 20); +assert(obj.c === 3); +if (define.supportsDescriptors) { + assert.deepEqual(Object.keys(obj), ['a', 'c']); + assert.deepEqual(Object.getOwnPropertyDescriptor(obj, 'b'), { + configurable: true, + enumerable: false, + value: 20, + writable: false + }); +} +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.org/package/define-properties +[npm-version-svg]: http://versionbadg.es/ljharb/define-properties.svg +[travis-svg]: https://travis-ci.org/ljharb/define-properties.svg +[travis-url]: https://travis-ci.org/ljharb/define-properties +[deps-svg]: https://david-dm.org/ljharb/define-properties.svg +[deps-url]: https://david-dm.org/ljharb/define-properties +[dev-deps-svg]: https://david-dm.org/ljharb/define-properties/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/define-properties#info=devDependencies +[testling-svg]: https://ci.testling.com/ljharb/define-properties.png +[testling-url]: https://ci.testling.com/ljharb/define-properties +[npm-badge-png]: https://nodei.co/npm/define-properties.png?downloads=true&stars=true +[license-image]: http://img.shields.io/npm/l/define-properties.svg +[license-url]: LICENSE +[downloads-image]: http://img.shields.io/npm/dm/define-properties.svg +[downloads-url]: http://npm-stat.com/charts.html?package=define-properties + diff --git a/scripts/2.5/node_modules/define-properties/index.js b/scripts/2.5/node_modules/define-properties/index.js new file mode 100644 index 00000000..cb3ae1c7 --- /dev/null +++ b/scripts/2.5/node_modules/define-properties/index.js @@ -0,0 +1,58 @@ +'use strict'; + +var keys = require('object-keys'); +var hasSymbols = typeof Symbol === 'function' && typeof Symbol('foo') === 'symbol'; + +var toStr = Object.prototype.toString; +var concat = Array.prototype.concat; +var origDefineProperty = Object.defineProperty; + +var isFunction = function (fn) { + return typeof fn === 'function' && toStr.call(fn) === '[object Function]'; +}; + +var arePropertyDescriptorsSupported = function () { + var obj = {}; + try { + origDefineProperty(obj, 'x', { enumerable: false, value: obj }); + // eslint-disable-next-line no-unused-vars, no-restricted-syntax + for (var _ in obj) { // jscs:ignore disallowUnusedVariables + return false; + } + return obj.x === obj; + } catch (e) { /* this is IE 8. */ + return false; + } +}; +var supportsDescriptors = origDefineProperty && arePropertyDescriptorsSupported(); + +var defineProperty = function (object, name, value, predicate) { + if (name in object && (!isFunction(predicate) || !predicate())) { + return; + } + if (supportsDescriptors) { + origDefineProperty(object, name, { + configurable: true, + enumerable: false, + value: value, + writable: true + }); + } else { + object[name] = value; + } +}; + +var defineProperties = function (object, map) { + var predicates = arguments.length > 2 ? arguments[2] : {}; + var props = keys(map); + if (hasSymbols) { + props = concat.call(props, Object.getOwnPropertySymbols(map)); + } + for (var i = 0; i < props.length; i += 1) { + defineProperty(object, props[i], map[props[i]], predicates[props[i]]); + } +}; + +defineProperties.supportsDescriptors = !!supportsDescriptors; + +module.exports = defineProperties; diff --git a/scripts/2.5/node_modules/define-properties/package.json b/scripts/2.5/node_modules/define-properties/package.json new file mode 100644 index 00000000..8ca60c09 --- /dev/null +++ b/scripts/2.5/node_modules/define-properties/package.json @@ -0,0 +1,99 @@ +{ + "_from": "define-properties@^1.1.1", + "_id": "define-properties@1.1.3", + "_inBundle": false, + "_integrity": "sha512-3MqfYKj2lLzdMSf8ZIZE/V+Zuy+BgD6f164e8K2w7dgnpKArBDerGYpM46IYYcjnkdPNMjPk9A6VFB8+3SKlXQ==", + "_location": "/define-properties", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "define-properties@^1.1.1", + "name": "define-properties", + "escapedName": "define-properties", + "rawSpec": "^1.1.1", + "saveSpec": null, + "fetchSpec": "^1.1.1" + }, + "_requiredBy": [ + "/is-nan", + "/object.entries", + "/string.prototype.trimleft", + "/string.prototype.trimright" + ], + "_resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.1.3.tgz", + "_shasum": "cf88da6cbee26fe6db7094f61d870cbd84cee9f1", + "_spec": "define-properties@^1.1.1", + "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/2.5/node_modules/is-nan", + "author": { + "name": "Jordan Harband" + }, + "bugs": { + "url": "https://github.com/ljharb/define-properties/issues" + }, + "bundleDependencies": false, + "dependencies": { + "object-keys": "^1.0.12" + }, + "deprecated": false, + "description": "Define multiple non-enumerable properties at once. Uses `Object.defineProperty` when available; falls back to standard assignment in older engines.", + "devDependencies": { + "@ljharb/eslint-config": "^13.0.0", + "covert": "^1.1.0", + "eslint": "^5.3.0", + "jscs": "^3.0.7", + "nsp": "^3.2.1", + "tape": "^4.9.0" + }, + "engines": { + "node": ">= 0.4" + }, + "homepage": "https://github.com/ljharb/define-properties#readme", + "keywords": [ + "Object.defineProperty", + "Object.defineProperties", + "object", + "property descriptor", + "descriptor", + "define", + "ES5" + ], + "license": "MIT", + "main": "index.js", + "name": "define-properties", + "repository": { + "type": "git", + "url": "git://github.com/ljharb/define-properties.git" + }, + "scripts": { + "coverage": "covert test/*.js", + "coverage-quiet": "covert test/*.js --quiet", + "eslint": "eslint test/*.js *.js", + "jscs": "jscs test/*.js *.js", + "lint": "npm run --silent jscs && npm run --silent eslint", + "posttest": "npm run --silent security", + "pretest": "npm run --silent lint", + "security": "nsp check", + "test": "npm run --silent tests-only", + "tests-only": "node test/index.js" + }, + "testling": { + "files": "test/index.js", + "browsers": [ + "iexplore/6.0..latest", + "firefox/3.0..6.0", + "firefox/15.0..latest", + "firefox/nightly", + "chrome/4.0..10.0", + "chrome/20.0..latest", + "chrome/canary", + "opera/10.0..latest", + "opera/next", + "safari/4.0..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2" + ] + }, + "version": "1.1.3" +} diff --git a/scripts/2.5/node_modules/define-properties/test/index.js b/scripts/2.5/node_modules/define-properties/test/index.js new file mode 100644 index 00000000..3387f6bc --- /dev/null +++ b/scripts/2.5/node_modules/define-properties/test/index.js @@ -0,0 +1,125 @@ +'use strict'; + +var define = require('../'); +var test = require('tape'); +var keys = require('object-keys'); + +var arePropertyDescriptorsSupported = function () { + var obj = { a: 1 }; + try { + Object.defineProperty(obj, 'x', { value: obj }); + return obj.x === obj; + } catch (e) { /* this is IE 8. */ + return false; + } +}; +var descriptorsSupported = !!Object.defineProperty && arePropertyDescriptorsSupported(); + +var hasSymbols = typeof Symbol === 'function' && typeof Symbol('foo') === 'symbol'; + +test('defineProperties', function (dt) { + dt.test('with descriptor support', { skip: !descriptorsSupported }, function (t) { + var getDescriptor = function (value) { + return { + configurable: true, + enumerable: false, + value: value, + writable: true + }; + }; + + var obj = { + a: 1, + b: 2, + c: 3 + }; + t.deepEqual(keys(obj), ['a', 'b', 'c'], 'all literal-set keys start enumerable'); + define(obj, { + b: 3, + c: 4, + d: 5 + }); + t.deepEqual(obj, { + a: 1, + b: 2, + c: 3 + }, 'existing properties were not overridden'); + t.deepEqual(Object.getOwnPropertyDescriptor(obj, 'd'), getDescriptor(5), 'new property "d" was added and is not enumerable'); + t.deepEqual(['a', 'b', 'c'], keys(obj), 'new keys are not enumerable'); + + define(obj, { + a: 2, + b: 3, + c: 4 + }, { + a: function () { return true; }, + b: function () { return false; } + }); + t.deepEqual(obj, { + b: 2, + c: 3 + }, 'properties only overriden when predicate exists and returns true'); + t.deepEqual(Object.getOwnPropertyDescriptor(obj, 'd'), getDescriptor(5), 'existing property "d" remained and is not enumerable'); + t.deepEqual(Object.getOwnPropertyDescriptor(obj, 'a'), getDescriptor(2), 'existing property "a" was overridden and is not enumerable'); + t.deepEqual(['b', 'c'], keys(obj), 'overridden keys are not enumerable'); + + t.end(); + }); + + dt.test('without descriptor support', { skip: descriptorsSupported }, function (t) { + var obj = { + a: 1, + b: 2, + c: 3 + }; + define(obj, { + b: 3, + c: 4, + d: 5 + }); + t.deepEqual(obj, { + a: 1, + b: 2, + c: 3, + d: 5 + }, 'existing properties were not overridden, new properties were added'); + + define(obj, { + a: 2, + b: 3, + c: 4 + }, { + a: function () { return true; }, + b: function () { return false; } + }); + t.deepEqual(obj, { + a: 2, + b: 2, + c: 3, + d: 5 + }, 'properties only overriden when predicate exists and returns true'); + + t.end(); + }); + + dt.end(); +}); + +test('symbols', { skip: !hasSymbols }, function (t) { + var sym = Symbol('foo'); + var obj = {}; + var aValue = {}; + var bValue = {}; + var properties = { a: aValue }; + properties[sym] = bValue; + + define(obj, properties); + + t.deepEqual(Object.keys(obj), [], 'object has no enumerable keys'); + t.deepEqual(Object.getOwnPropertyNames(obj), ['a'], 'object has non-enumerable "a" key'); + t.deepEqual(Object.getOwnPropertySymbols(obj), [sym], 'object has non-enumerable symbol key'); + t.equal(obj.a, aValue, 'string keyed value is defined'); + t.equal(obj[sym], bValue, 'symbol keyed value is defined'); + + t.end(); +}); diff --git a/scripts/2.5/node_modules/es-abstract/.editorconfig b/scripts/2.5/node_modules/es-abstract/.editorconfig new file mode 100644 index 00000000..eaa21416 --- /dev/null +++ b/scripts/2.5/node_modules/es-abstract/.editorconfig @@ -0,0 +1,13 @@ +root = true + +[*] +indent_style = tab; +insert_final_newline = true; +quote_type = auto; +space_after_anonymous_functions = true; +space_after_control_statements = true; +spaces_around_operators = true; +trim_trailing_whitespace = true; +spaces_in_brackets = false; +end_of_line = lf; + diff --git a/scripts/2.5/node_modules/es-abstract/.eslintrc b/scripts/2.5/node_modules/es-abstract/.eslintrc new file mode 100644 index 00000000..fedc4628 --- /dev/null +++ b/scripts/2.5/node_modules/es-abstract/.eslintrc @@ -0,0 +1,70 @@ +{ + "root": true, + + "extends": "@ljharb", + + "env": { + "es6": true, + }, + + "rules": { + "arrow-parens": [2, "always"], + "array-bracket-newline": 0, + "array-element-newline": 0, + "complexity": 0, + "eqeqeq": [2, "allow-null"], + "func-name-matching": 0, + "id-length": [2, { "min": 1, "max": 30 }], + "max-params": [2, 4], + "max-statements": [2, 24], + "max-statements-per-line": [2, { "max": 2 }], + "multiline-comment-style": 1, + "no-magic-numbers": 0, + "new-cap": 0, + "no-extra-parens": 1, + "operator-linebreak": [2, "before"], + "sort-keys": 0, + }, + + "overrides": [ + { + "files": "./es5.js", + "rules": { + "max-lines": [2, 600], + "max-statements": [2, 30], + }, + }, + { + "files": "./es2015.js", + "rules": { + "max-lines": [2, 1500], + }, + }, + { + "files": "operations/*", + "rules": { + "max-lines": 0, + }, + }, + { + "files": "operations/*.js", + "parserOptions": { + "ecmaVersion": "2018", + }, + "rules": { +//camelcase +//array-callback-return +//consistent-return + "no-console": 0, + "no-multi-str": 0, + }, + }, + { + "files": "operations/getOps.js", + "rules": { + "no-console": 0, + "no-process-exit": 0, + }, + }, + ], +} diff --git a/scripts/2.5/node_modules/es-abstract/.github/FUNDING.yml b/scripts/2.5/node_modules/es-abstract/.github/FUNDING.yml new file mode 100644 index 00000000..beeb7a28 --- /dev/null +++ b/scripts/2.5/node_modules/es-abstract/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/es-abstract +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with a single custom sponsorship URL diff --git a/scripts/2.5/node_modules/es-abstract/.nycrc b/scripts/2.5/node_modules/es-abstract/.nycrc new file mode 100644 index 00000000..3421adaa --- /dev/null +++ b/scripts/2.5/node_modules/es-abstract/.nycrc @@ -0,0 +1,14 @@ +{ + "all": true, + "check-coverage": true, + "reporter": ["text-summary", "text", "html", "json"], + "lines": 86, + "statements": 85.93, + "functions": 82.43, + "branches": 76.06, + "exclude": [ + "coverage", + "operations", + "test" + ] +} diff --git a/scripts/2.5/node_modules/es-abstract/.travis.yml b/scripts/2.5/node_modules/es-abstract/.travis.yml new file mode 100644 index 00000000..a0a9356e --- /dev/null +++ b/scripts/2.5/node_modules/es-abstract/.travis.yml @@ -0,0 +1,333 @@ +language: node_js +os: + - linux +node_js: + - "12.12" + - "11.15" + - "10.16" + - "9.11" + - "8.16" + - "7.10" + - "6.17" + - "5.12" + - "4.9" + - "iojs-v3.3" + - "iojs-v2.5" + - "iojs-v1.8" + - "0.12" + - "0.10" + - "0.8" + - "0.6" +cache: + directories: + - "$HOME/.npm" + - "$(nvm cache dir)" + - "$(nvm_version_path $(nvm_version_remote 0.4))" + - "$(nvm_version_path $(nvm_version_remote 0.6))" + - "$(nvm_version_path $(nvm_version_remote 0.10))" +before_install: + - 'case "${TRAVIS_NODE_VERSION}" in 0.*) export NPM_CONFIG_STRICT_SSL=false ;; esac' + - 'nvm install-latest-npm' +install: + - 'if [ "${TRAVIS_NODE_VERSION}" = "0.6" ] || [ "${TRAVIS_NODE_VERSION}" = "0.9" ]; then nvm install --latest-npm 0.8 && npm install && nvm use "${TRAVIS_NODE_VERSION}"; else npm install; fi;' +script: + - 'if [ -n "${PRETEST-}" ]; then npm run pretest ; fi' + - 'if [ -n "${POSTTEST-}" ]; then npm run posttest ; fi' + - 'if [ -n "${COVERAGE-}" ]; then npm run coverage && bash <(curl -s https://codecov.io/bash) -f coverage/*.json; fi' + - 'if [ -n "${TEST-}" ]; then npm run tests-only ; fi' +sudo: false +env: + - TEST=true +matrix: + fast_finish: true + include: + - node_js: "lts/*" + env: PRETEST=true + - node_js: "lts/*" + env: POSTTEST=true + - node_js: "0.8" + env: COVERAGE=true + - node_js: "0.12" + env: COVERAGE=true + - node_js: "4" + env: COVERAGE=true + - node_js: "8" + env: COVERAGE=true + - node_js: "12.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "12.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "12.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "12.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "12.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "12.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "12.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "12.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "12.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "12.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "12.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "12.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.14" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.13" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.12" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.15" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.14" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.13" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.12" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.15" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.14" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.13" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.12" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.16" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.15" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.14" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.13" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.12" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v3.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v3.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v3.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.4" + env: TEST=true ALLOW_FAILURE=true + allow_failures: + - os: osx + - env: TEST=true ALLOW_FAILURE=true + - node_js: "0.6" diff --git a/scripts/2.5/node_modules/es-abstract/CHANGELOG.md b/scripts/2.5/node_modules/es-abstract/CHANGELOG.md new file mode 100644 index 00000000..048d2057 --- /dev/null +++ b/scripts/2.5/node_modules/es-abstract/CHANGELOG.md @@ -0,0 +1,264 @@ +1.16.0 / 2019-10-18 +================= + * [New] `ES2015+`: add `SetFunctionName` + * [New] `ES2015+`: add `GetPrototypeFromConstructor`, with caveats + * [New] `ES2015+`: add `CreateListFromArrayLike` + * [New] `ES2016+`: add `OrdinarySetPrototypeOf` + * [New] `ES2016+`: add `OrdinaryGetPrototypeOf` + * [New] add `getSymbolDescription` and `getInferredName` helpers + * [Fix] `GetIterator`: add fallback for pre-Symbol environments, tests + * [Dev Deps] update `object.fromentries` + * [Tests] add `node` `v12.2` + + +1.15.0 / 2019-10-02 +================= + * [New] `ES2018`+: add `DateString`, `TimeString` + * [New] `ES2015`+: add `ToDateString` + * [New] `ES5`+: add `msFromTime`, `SecFromTime`, `MinFromTime`, `HourFromTime`, `TimeWithinDay`, `Day`, `DayFromYear`, `TimeFromYear`, `YearFromTime`, `WeekDay`, `DaysInYear`, `InLeapYear`, `DayWithinYear`, `MonthFromTime`, `DateFromTime`, `MakeDay`, `MakeDate`, `MakeTime`, `TimeClip`, `modulo` + * [New] add `regexTester` helper + * [New] add `callBound` helper + * [New] add ES2020’s intrinsic dot notation + * [New] add `isPrefixOf` helper + * [New] add `maxSafeInteger` helper + * [Deps] update `string.prototype.trimleft`, `string.prototype.trimright` + * [Dev Deps] update `eslint` + * [Tests] on `node` `v12.11` + * [meta] npmignore operations scripts; add "deltas" + +1.14.2 / 2019-09-08 +================= + * [Fix] `ES2016`: `IterableToArrayLike`: add proper fallback for strings, pre-Symbols + * [Tests] on `node` `v12.10` + +1.14.1 / 2019-09-03 +================= + * [meta] republish with some extra files removed + +1.14.0 / 2019-09-02 +================= + * [New] add ES2019 + * [New] `ES2017+`: add `IterableToList` + * [New] `ES2016`: add `IterableToArrayLike` + * [New] `ES2015+`: add `ArrayCreate`, `ArraySetLength`, `OrdinaryDefineOwnProperty`, `OrdinaryGetOwnProperty`, `OrdinaryHasProperty`, `CreateHTML`, `GetOwnPropertyKeys`, `InstanceofOperator`, `SymbolDescriptiveString`, `GetSubstitution`, `ValidateAndApplyPropertyDescriptor`, `IsPromise`, `OrdinaryHasInstance`, `TestIntegrityLevel`, `SetIntegrityLevel` + * [New] add `callBind` helper, and use it + * [New] add helpers: `isPropertyDescriptor`, `every` + * [New] ES5+: add `Abstract Relational Comparison` + * [New] ES5+: add `Abstract Equality Comparison`, `Strict Equality Comparison` + * [Fix] `ES2015+`: `GetIterator`: only require native Symbols when `method` is omitted + * [Fix] `ES2015`: `Call`: error message now properly displays Symbols using `object-inspect` + * [Fix] `ES2015+`: `ValidateAndApplyPropertyDescriptor`: use ES2017 logic to bypass spec bugs + * [Fix] `ES2015+`: `CreateDataProperty`, `DefinePropertyOrThrow`, `ValidateAndApplyPropertyDescriptor`: add fallbacks for ES3 + * [Fix] `ES2015+`: `FromPropertyDescriptor`: no longer requires a fully complete Property Descriptor + * [Fix] `ES5`: `IsPropertyDescriptor`: call into `IsDataDescriptor` and `IsAccessorDescriptor` + * [Refactor] use `has-symbols` for Symbol detection + * [Fix] `helpers/assertRecord`: remove `console.log` + * [Deps] update `object-keys` + * [readme] add security note + * [meta] change http URLs to https + * [meta] linter cleanup + * [meta] fix getOps script + * [meta] add FUNDING.yml + * [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `safe-publish-latest`, `semver`, `replace`, `cheerio`, `tape` + * [Tests] up to `node` `v12.9`, `v11.15`, `v10.16`, `v8.16`, `v6.17` + * [Tests] temporarily allow node 0.6 to fail; segfaulting in travis + * [Tests] use the values helper more in es5 tests + * [Tests] fix linting to apply to all files + * [Tests] run `npx aud` only on prod deps + * [Tests] add v.descriptors helpers + * [Tests] use `npx aud` instead of `npm audit` with hoops + * [Tests] use `eclint` instead of `editorconfig-tools` + * [Tests] some intrinsic cleanup + * [Tests] migrate es5 tests to use values helper + * [Tests] add some missing ES2015 ops + +1.13.0 / 2019-01-02 +================= + * [New] add ES2018 + * [New] add ES2015/ES2016: EnumerableOwnNames; ES2017: EnumerableOwnProperties + * [New] `ES2015+`: add `thisBooleanValue`, `thisNumberValue`, `thisStringValue`, `thisTimeValue` + * [New] `ES2015+`: add `DefinePropertyOrThrow`, `DeletePropertyOrThrow`, `CreateMethodProperty` + * [New] add `assertRecord` helper + * [Deps] update `is-callable`, `has`, `object-keys`, `es-to-primitive` + * [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape`, `semver`, `safe-publish-latest`, `replace` + * [Tests] use `npm audit` instead of `nsp` + * [Tests] remove `jscs` + * [Tests] up to `node` `v11.6`, `v10.15`, `v8.15`, `v6.16` + * [Tests] move descriptor factories to `values` helper + * [Tests] add `getOps` to programmatically fetch abstract operation names + +1.12.0 / 2018-05-31 +================= + * [New] add `GetIntrinsic` entry point + * [New] `ES2015`+: add `ObjectCreate` + * [Robustness]: `ES2015+`: ensure `Math.{abs,floor}` and `Function.call` are cached + +1.11.0 / 2018-03-21 +================= + * [New] `ES2015+`: add iterator abstract ops + * [Dev Deps] update `eslint`, `nsp`, `object.assign`, `semver`, `tape` + * [Tests] up to `node` `v9.8`, `v8.10`, `v6.13` + +1.10.0 / 2017-11-24 +================= + * [New] ES2015+: `AdvanceStringIndex` + * [Dev Deps] update `eslint`, `nsp` + * [Tests] require node 0.6 to pass again + * [Tests] up to `node` `v9.2`, `v8.9`, `v6.12`; use `nvm install-latest-npm`; pin included builds to LTS + +1.9.0 / 2017-09-30 +================= + * [New] `es2015+`: add `ArraySpeciesCreate` + * [New] ES2015+: add `CreateDataProperty` and `CreateDataPropertyOrThrow` + * [Tests] consolidate duplicated tests + * [Tests] increase coverage + * [Dev Deps] update `nsp`, `eslint` + +1.8.2 / 2017-09-03 +================= + * [Fix] `es2015`+: `ToNumber`: provide the proper hint for Date objects (#27) + * [Dev Deps] update `eslint` + +1.8.1 / 2017-08-30 +================= + * [Fix] ES2015+: `ToPropertyKey`: should return a symbol for Symbols (#26) + * [Deps] update `function-bind` + * [Dev Deps] update `eslint`, `@ljharb/eslint-config` + * [Docs] github broke markdown parsing + +1.8.0 / 2017-08-04 +================= + * [New] add ES2017 + * [New] move es6+ to es2015+; leave es6/es7 as aliases + * [New] ES5+: add `IsPropertyDescriptor`, `IsAccessorDescriptor`, `IsDataDescriptor`, `IsGenericDescriptor`, `FromPropertyDescriptor`, `ToPropertyDescriptor` + * [New] ES2015+: add `CompletePropertyDescriptor`, `Set`, `HasOwnProperty`, `HasProperty`, `IsConcatSpreadable`, `Invoke`, `CreateIterResultObject`, `RegExpExec` + * [Fix] es7/es2016: do not mutate ES6 + * [Fix] assign helper only supports one source + * [Deps] update `is-regex` + * [Dev Deps] update `nsp`, `eslint`, `@ljharb/eslint-config` + * [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `nsp`, `semver`, `tape` + * [Tests] add tests for missing and excess operations + * [Tests] add codecov for coverage + * [Tests] up to `node` `v8.2`, `v7.10`, `v6.11`, `v4.8`; newer npm breaks on older node + * [Tests] use same lists of value types across tests; ensure tests are the same when ops are the same + * [Tests] ES2015: add ToNumber symbol tests + * [Tests] switch to `nyc` for code coverage + * [Tests] make IsRegExp tests consistent across editions + +1.7.0 / 2017-01-22 +================= + * [New] ES6: Add `GetMethod` (#16) + * [New] ES6: Add `GetV` (#16) + * [New] ES6: Add `Get` (#17) + * [Tests] up to `node` `v7.4`, `v6.9`, `v4.6`; improve test matrix + * [Dev Deps] update `tape`, `nsp`, `eslint`, `@ljharb/eslint-config`, `safe-publish-latest` + +1.6.1 / 2016-08-21 +================= + * [Fix] ES6: IsConstructor should return true for `class` constructors. + +1.6.0 / 2016-08-20 +================= + * [New] ES5 / ES6: add `Type` + * [New] ES6: `SpeciesConstructor` + * [Dev Deps] update `jscs`, `nsp`, `eslint`, `@ljharb/eslint-config`, `semver`; add `safe-publish-latest` + * [Tests] up to `node` `v6.4`, `v5.12`, `v4.5` + +1.5.1 / 2016-05-30 +================= + * [Fix] `ES.IsRegExp`: actually look up `Symbol.match` on the argument + * [Refactor] create `isNaN` helper + * [Deps] update `is-callable`, `function-bind` + * [Deps] update `es-to-primitive`, fix ES5 tests + * [Dev Deps] update `jscs`, `eslint`, `@ljharb/eslint-config`, `tape`, `nsp` + * [Tests] up to `node` `v6.2`, `v5.11`, `v4.4` + * [Tests] use pretest/posttest for linting/security + +1.5.0 / 2015-12-27 +================= + * [New] adds `Symbol.toPrimitive` support via `es-to-primitive` + * [Deps] update `is-callable`, `es-to-primitive` + * [Dev Deps] update `jscs`, `nsp`, `eslint`, `@ljharb/eslint-config`, `semver`, `tape` + * [Tests] up to `node` `v5.3` + +1.4.3 / 2015-11-04 +================= + * [Fix] `ES6.ToNumber`: should give `NaN` for explicitly signed hex strings (#4) + * [Refactor] `ES6.ToNumber`: No need to double-trim + * [Refactor] group tests better + * [Tests] should still pass on `node` `v0.8` + +1.4.2 / 2015-11-02 +================= + * [Fix] ensure `ES.ToNumber` trims whitespace, and does not trim non-whitespace (#3) + +1.4.1 / 2015-10-31 +================= + * [Fix] ensure only 0-1 are valid binary and 0-7 are valid octal digits (#2) + * [Dev Deps] update `tape`, `jscs`, `nsp`, `eslint`, `@ljharb/eslint-config` + * [Tests] on `node` `v5.0` + * [Tests] fix npm upgrades for older node versions + * package.json: use object form of "authors", add "contributors" + +1.4.0 / 2015-09-26 +================= + * [Deps] update `is-callable` + * [Dev Deps] update `tape`, `jscs`, `eslint`, `@ljharb/eslint-config` + * [Tests] on `node` `v4.2` + * [New] Add `SameValueNonNumber` to ES7 + +1.3.2 / 2015-09-26 +================= + * [Fix] Fix `ES6.IsRegExp` to properly handle `Symbol.match`, per spec. + * [Tests] up to `io.js` `v3.3`, `node` `v4.1` + * [Dev Deps] update `tape`, `jscs`, `nsp`, `eslint`, `@ljharb/eslint-config`, `semver` + +1.3.1 / 2015-08-15 +================= + * [Fix] Ensure that objects that `toString` to a binary or octal literal also convert properly + +1.3.0 / 2015-08-15 +================= + * [New] ES6’s ToNumber now supports binary and octal literals. + * [Dev Deps] update `jscs`, `eslint`, `@ljharb/eslint-config`, `tape` + * [Docs] Switch from vb.teelaun.ch to versionbadg.es for the npm version badge SVG + * [Tests] up to `io.js` `v3.0` + +1.2.2 / 2015-07-28 +================= + * [Fix] Both `ES5.CheckObjectCoercible` and `ES6.RequireObjectCoercible` return the value if they don't throw. + * [Tests] Test on latest `io.js` versions. + * [Dev Deps] Update `eslint`, `jscs`, `tape`, `semver`, `covert`, `nsp` + +1.2.1 / 2015-03-20 +================= + * Fix `isFinite` helper. + +1.2.0 / 2015-03-19 +================= + * Use `es-to-primitive` for ToPrimitive methods. + * Test on latest `io.js` versions; allow failures on all but 2 latest `node`/`io.js` versions. + +1.1.2 / 2015-03-20 +================= + * Fix isFinite helper. + +1.1.1 / 2015-03-19 +================= + * Fix isPrimitive check for functions + * Update `eslint`, `editorconfig-tools`, `semver`, `nsp` + +1.1.0 / 2015-02-17 +================= + * Add ES7 export (non-default). + * All grade A-supported `node`/`iojs` versions now ship with an `npm` that understands `^`. + * Test on `iojs-v1.2`. + +1.0.1 / 2015-01-30 +================= + * Use `is-callable` instead of an internal function. + * Update `tape`, `jscs`, `nsp`, `eslint` + +1.0.0 / 2015-01-10 +================= + * v1.0.0 diff --git a/scripts/2.5/node_modules/es-abstract/GetIntrinsic.js b/scripts/2.5/node_modules/es-abstract/GetIntrinsic.js new file mode 100644 index 00000000..6c43b0db --- /dev/null +++ b/scripts/2.5/node_modules/es-abstract/GetIntrinsic.js @@ -0,0 +1,189 @@ +'use strict'; + +/* globals + Atomics, + SharedArrayBuffer, +*/ + +var undefined; // eslint-disable-line no-shadow-restricted-names + +var $TypeError = TypeError; + +var ThrowTypeError = Object.getOwnPropertyDescriptor + ? (function () { return Object.getOwnPropertyDescriptor(arguments, 'callee').get; }()) + : function () { throw new $TypeError(); }; + +var hasSymbols = require('has-symbols')(); + +var getProto = Object.getPrototypeOf || function (x) { return x.__proto__; }; // eslint-disable-line no-proto + +var generator; // = function * () {}; +var generatorFunction = generator ? getProto(generator) : undefined; +var asyncFn; // async function() {}; +var asyncFunction = asyncFn ? asyncFn.constructor : undefined; +var asyncGen; // async function * () {}; +var asyncGenFunction = asyncGen ? getProto(asyncGen) : undefined; +var asyncGenIterator = asyncGen ? asyncGen() : undefined; + +var TypedArray = typeof Uint8Array === 'undefined' ? undefined : getProto(Uint8Array); + +var INTRINSICS = { + '$ %Array%': Array, + '$ %ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer, + '$ %ArrayBufferPrototype%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer.prototype, + '$ %ArrayIteratorPrototype%': hasSymbols ? getProto([][Symbol.iterator]()) : undefined, + '$ %ArrayPrototype%': Array.prototype, + '$ %ArrayProto_entries%': Array.prototype.entries, + '$ %ArrayProto_forEach%': Array.prototype.forEach, + '$ %ArrayProto_keys%': Array.prototype.keys, + '$ %ArrayProto_values%': Array.prototype.values, + '$ %AsyncFromSyncIteratorPrototype%': undefined, + '$ %AsyncFunction%': asyncFunction, + '$ %AsyncFunctionPrototype%': asyncFunction ? asyncFunction.prototype : undefined, + '$ %AsyncGenerator%': asyncGen ? getProto(asyncGenIterator) : undefined, + '$ %AsyncGeneratorFunction%': asyncGenFunction, + '$ %AsyncGeneratorPrototype%': asyncGenFunction ? asyncGenFunction.prototype : undefined, + '$ %AsyncIteratorPrototype%': asyncGenIterator && hasSymbols && Symbol.asyncIterator ? asyncGenIterator[Symbol.asyncIterator]() : undefined, + '$ %Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics, + '$ %Boolean%': Boolean, + '$ %BooleanPrototype%': Boolean.prototype, + '$ %DataView%': typeof DataView === 'undefined' ? undefined : DataView, + '$ %DataViewPrototype%': typeof DataView === 'undefined' ? undefined : DataView.prototype, + '$ %Date%': Date, + '$ %DatePrototype%': Date.prototype, + '$ %decodeURI%': decodeURI, + '$ %decodeURIComponent%': decodeURIComponent, + '$ %encodeURI%': encodeURI, + '$ %encodeURIComponent%': encodeURIComponent, + '$ %Error%': Error, + '$ %ErrorPrototype%': Error.prototype, + '$ %eval%': eval, // eslint-disable-line no-eval + '$ %EvalError%': EvalError, + '$ %EvalErrorPrototype%': EvalError.prototype, + '$ %Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array, + '$ %Float32ArrayPrototype%': typeof Float32Array === 'undefined' ? undefined : Float32Array.prototype, + '$ %Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array, + '$ %Float64ArrayPrototype%': typeof Float64Array === 'undefined' ? undefined : Float64Array.prototype, + '$ %Function%': Function, + '$ %FunctionPrototype%': Function.prototype, + '$ %Generator%': generator ? getProto(generator()) : undefined, + '$ %GeneratorFunction%': generatorFunction, + '$ %GeneratorPrototype%': generatorFunction ? generatorFunction.prototype : undefined, + '$ %Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array, + '$ %Int8ArrayPrototype%': typeof Int8Array === 'undefined' ? undefined : Int8Array.prototype, + '$ %Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array, + '$ %Int16ArrayPrototype%': typeof Int16Array === 'undefined' ? undefined : Int8Array.prototype, + '$ %Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array, + '$ %Int32ArrayPrototype%': typeof Int32Array === 'undefined' ? undefined : Int32Array.prototype, + '$ %isFinite%': isFinite, + '$ %isNaN%': isNaN, + '$ %IteratorPrototype%': hasSymbols ? getProto(getProto([][Symbol.iterator]())) : undefined, + '$ %JSON%': JSON, + '$ %JSONParse%': JSON.parse, + '$ %Map%': typeof Map === 'undefined' ? undefined : Map, + '$ %MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols ? undefined : getProto(new Map()[Symbol.iterator]()), + '$ %MapPrototype%': typeof Map === 'undefined' ? undefined : Map.prototype, + '$ %Math%': Math, + '$ %Number%': Number, + '$ %NumberPrototype%': Number.prototype, + '$ %Object%': Object, + '$ %ObjectPrototype%': Object.prototype, + '$ %ObjProto_toString%': Object.prototype.toString, + '$ %ObjProto_valueOf%': Object.prototype.valueOf, + '$ %parseFloat%': parseFloat, + '$ %parseInt%': parseInt, + '$ %Promise%': typeof Promise === 'undefined' ? undefined : Promise, + '$ %PromisePrototype%': typeof Promise === 'undefined' ? undefined : Promise.prototype, + '$ %PromiseProto_then%': typeof Promise === 'undefined' ? undefined : Promise.prototype.then, + '$ %Promise_all%': typeof Promise === 'undefined' ? undefined : Promise.all, + '$ %Promise_reject%': typeof Promise === 'undefined' ? undefined : Promise.reject, + '$ %Promise_resolve%': typeof Promise === 'undefined' ? undefined : Promise.resolve, + '$ %Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy, + '$ %RangeError%': RangeError, + '$ %RangeErrorPrototype%': RangeError.prototype, + '$ %ReferenceError%': ReferenceError, + '$ %ReferenceErrorPrototype%': ReferenceError.prototype, + '$ %Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect, + '$ %RegExp%': RegExp, + '$ %RegExpPrototype%': RegExp.prototype, + '$ %Set%': typeof Set === 'undefined' ? undefined : Set, + '$ %SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols ? undefined : getProto(new Set()[Symbol.iterator]()), + '$ %SetPrototype%': typeof Set === 'undefined' ? undefined : Set.prototype, + '$ %SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer, + '$ %SharedArrayBufferPrototype%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer.prototype, + '$ %String%': String, + '$ %StringIteratorPrototype%': hasSymbols ? getProto(''[Symbol.iterator]()) : undefined, + '$ %StringPrototype%': String.prototype, + '$ %Symbol%': hasSymbols ? Symbol : undefined, + '$ %SymbolPrototype%': hasSymbols ? Symbol.prototype : undefined, + '$ %SyntaxError%': SyntaxError, + '$ %SyntaxErrorPrototype%': SyntaxError.prototype, + '$ %ThrowTypeError%': ThrowTypeError, + '$ %TypedArray%': TypedArray, + '$ %TypedArrayPrototype%': TypedArray ? TypedArray.prototype : undefined, + '$ %TypeError%': $TypeError, + '$ %TypeErrorPrototype%': $TypeError.prototype, + '$ %Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array, + '$ %Uint8ArrayPrototype%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array.prototype, + '$ %Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray, + '$ %Uint8ClampedArrayPrototype%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray.prototype, + '$ %Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array, + '$ %Uint16ArrayPrototype%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array.prototype, + '$ %Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array, + '$ %Uint32ArrayPrototype%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array.prototype, + '$ %URIError%': URIError, + '$ %URIErrorPrototype%': URIError.prototype, + '$ %WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap, + '$ %WeakMapPrototype%': typeof WeakMap === 'undefined' ? undefined : WeakMap.prototype, + '$ %WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet, + '$ %WeakSetPrototype%': typeof WeakSet === 'undefined' ? undefined : WeakSet.prototype +}; + +var bind = require('function-bind'); +var $replace = bind.call(Function.call, String.prototype.replace); + +/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */ +var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g; +var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */ +var stringToPath = function stringToPath(string) { + var result = []; + $replace(string, rePropName, function (match, number, quote, subString) { + result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : (number || match); + }); + return result; +}; +/* end adaptation */ + +var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) { + var key = '$ ' + name; + if (!(key in INTRINSICS)) { + throw new SyntaxError('intrinsic ' + name + ' does not exist!'); + } + + // istanbul ignore if // hopefully this is impossible to test :-) + if (typeof INTRINSICS[key] === 'undefined' && !allowMissing) { + throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!'); + } + + return INTRINSICS[key]; +}; + +module.exports = function GetIntrinsic(name, allowMissing) { + if (arguments.length > 1 && typeof allowMissing !== 'boolean') { + throw new TypeError('"allowMissing" argument must be a boolean'); + } + + var parts = stringToPath(name); + + if (parts.length === 0) { + return getBaseIntrinsic(name, allowMissing); + } + + var value = getBaseIntrinsic('%' + parts[0] + '%', allowMissing); + for (var i = 1; i < parts.length; i += 1) { + if (value != null) { + value = value[parts[i]]; + } + } + return value; +}; diff --git a/scripts/2.5/node_modules/es-abstract/LICENSE b/scripts/2.5/node_modules/es-abstract/LICENSE new file mode 100644 index 00000000..8c271c14 --- /dev/null +++ b/scripts/2.5/node_modules/es-abstract/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (C) 2015 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. \ No newline at end of file diff --git a/scripts/2.5/node_modules/es-abstract/Makefile b/scripts/2.5/node_modules/es-abstract/Makefile new file mode 100644 index 00000000..959bbd49 --- /dev/null +++ b/scripts/2.5/node_modules/es-abstract/Makefile @@ -0,0 +1,61 @@ +# Since we rely on paths relative to the makefile location, abort if make isn't being run from there. +$(if $(findstring /,$(MAKEFILE_LIST)),$(error Please only invoke this makefile from the directory it resides in)) + + # The files that need updating when incrementing the version number. +VERSIONED_FILES := *.js */*.js *.json README* + + +# Add the local npm packages' bin folder to the PATH, so that `make` can find them, when invoked directly. +# Note that rather than using `$(npm bin)` the 'node_modules/.bin' path component is hard-coded, so that invocation works even from an environment +# where npm is (temporarily) unavailable due to having deactivated an nvm instance loaded into the calling shell in order to avoid interference with tests. +export PATH := $(shell printf '%s' "$$PWD/node_modules/.bin:$$PATH") +UTILS := semver +# Make sure that all required utilities can be located. +UTIL_CHECK := $(or $(shell PATH="$(PATH)" which $(UTILS) >/dev/null && echo 'ok'),$(error Did you forget to run `npm install` after cloning the repo? At least one of the required supporting utilities not found: $(UTILS))) + +# Default target (by virtue of being the first non '.'-prefixed in the file). +.PHONY: _no-target-specified +_no-target-specified: + $(error Please specify the target to make - `make list` shows targets. Alternatively, use `npm test` to run the default tests; `npm run` shows all tests) + +# Lists all targets defined in this makefile. +.PHONY: list +list: + @$(MAKE) -pRrn : -f $(MAKEFILE_LIST) 2>/dev/null | awk -v RS= -F: '/^# File/,/^# Finished Make data base/ {if ($$1 !~ "^[#.]") {print $$1}}' | command grep -v -e '^[^[:alnum:]]' -e '^$@$$command ' | sort + +# All-tests target: invokes the specified test suites for ALL shells defined in $(SHELLS). +.PHONY: test +test: + @npm test + +.PHONY: _ensure-tag +_ensure-tag: +ifndef TAG + $(error Please invoke with `make TAG= release`, where is either an increment specifier (patch, minor, major, prepatch, preminor, premajor, prerelease), or an explicit major.minor.patch version number) +endif + +CHANGELOG_ERROR = $(error No CHANGELOG specified) +.PHONY: _ensure-changelog +_ensure-changelog: + @ (git status -sb --porcelain | command grep -E '^( M|[MA] ) CHANGELOG.md' > /dev/null) || (echo no CHANGELOG.md specified && exit 2) + +# Ensures that the git workspace is clean. +.PHONY: _ensure-clean +_ensure-clean: + @[ -z "$$((git status --porcelain --untracked-files=no || echo err) | command grep -v 'CHANGELOG.md')" ] || { echo "Workspace is not clean; please commit changes first." >&2; exit 2; } + +# Makes a release; invoke with `make TAG= release`. +.PHONY: release +release: _ensure-tag _ensure-changelog _ensure-clean + @old_ver=`git describe --abbrev=0 --tags --match 'v[0-9]*.[0-9]*.[0-9]*'` || { echo "Failed to determine current version." >&2; exit 1; }; old_ver=$${old_ver#v}; \ + new_ver=`echo "$(TAG)" | sed 's/^v//'`; new_ver=$${new_ver:-patch}; \ + if printf "$$new_ver" | command grep -q '^[0-9]'; then \ + semver "$$new_ver" >/dev/null || { echo 'Invalid version number specified: $(TAG) - must be major.minor.patch' >&2; exit 2; }; \ + semver -r "> $$old_ver" "$$new_ver" >/dev/null || { echo 'Invalid version number specified: $(TAG) - must be HIGHER than current one.' >&2; exit 2; } \ + else \ + new_ver=`semver -i "$$new_ver" "$$old_ver"` || { echo 'Invalid version-increment specifier: $(TAG)' >&2; exit 2; } \ + fi; \ + printf "=== Bumping version **$$old_ver** to **$$new_ver** before committing and tagging:\n=== TYPE 'proceed' TO PROCEED, anything else to abort: " && read response && [ "$$response" = 'proceed' ] || { echo 'Aborted.' >&2; exit 2; }; \ + replace "$$old_ver" "$$new_ver" -- $(VERSIONED_FILES) && \ + git commit -m "v$$new_ver" $(VERSIONED_FILES) CHANGELOG.md && \ + git tag -a -m "v$$new_ver" "v$$new_ver" diff --git a/scripts/2.5/node_modules/es-abstract/README.md b/scripts/2.5/node_modules/es-abstract/README.md new file mode 100644 index 00000000..20342d11 --- /dev/null +++ b/scripts/2.5/node_modules/es-abstract/README.md @@ -0,0 +1,48 @@ +# es-abstract [![Version Badge][npm-version-svg]][package-url] + +[![Build Status][travis-svg]][travis-url] +[![dependency status][deps-svg]][deps-url] +[![dev dependency status][dev-deps-svg]][dev-deps-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +[![browser support][testling-svg]][testling-url] + +ECMAScript spec abstract operations. +When different versions of the spec conflict, the default export will be the latest version of the abstract operation. +All abstract operations will also be available under an `es5`/`es2015`/`es2016`/`es2017`/`es2018`/`es2019` entry point, and exported property, if you require a specific version. + +## Example + +```js +var ES = require('es-abstract'); +var assert = require('assert'); + +assert(ES.isCallable(function () {})); +assert(!ES.isCallable(/a/g)); +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +## Security + +Please email [@ljharb](https://github.com/ljharb) or see https://tidelift.com/security if you have a potential security vulnerability to report. + +[package-url]: https://npmjs.org/package/es-abstract +[npm-version-svg]: http://versionbadg.es/ljharb/es-abstract.svg +[travis-svg]: https://travis-ci.org/ljharb/es-abstract.svg +[travis-url]: https://travis-ci.org/ljharb/es-abstract +[deps-svg]: https://david-dm.org/ljharb/es-abstract.svg +[deps-url]: https://david-dm.org/ljharb/es-abstract +[dev-deps-svg]: https://david-dm.org/ljharb/es-abstract/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/es-abstract#info=devDependencies +[testling-svg]: https://ci.testling.com/ljharb/es-abstract.png +[testling-url]: https://ci.testling.com/ljharb/es-abstract +[npm-badge-png]: https://nodei.co/npm/es-abstract.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/es-abstract.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/es-abstract.svg +[downloads-url]: https://npm-stat.com/charts.html?package=es-abstract diff --git a/scripts/2.5/node_modules/es-abstract/es2015.js b/scripts/2.5/node_modules/es-abstract/es2015.js new file mode 100644 index 00000000..6a1f045e --- /dev/null +++ b/scripts/2.5/node_modules/es-abstract/es2015.js @@ -0,0 +1,1464 @@ +'use strict'; + +var has = require('has'); +var toPrimitive = require('es-to-primitive/es6'); +var keys = require('object-keys'); +var inspect = require('object-inspect'); + +var GetIntrinsic = require('./GetIntrinsic'); + +var $TypeError = GetIntrinsic('%TypeError%'); +var $RangeError = GetIntrinsic('%RangeError%'); +var $SyntaxError = GetIntrinsic('%SyntaxError%'); +var $Array = GetIntrinsic('%Array%'); +var $ArrayPrototype = $Array.prototype; +var $String = GetIntrinsic('%String%'); +var $Object = GetIntrinsic('%Object%'); +var $Number = GetIntrinsic('%Number%'); +var $Symbol = GetIntrinsic('%Symbol%', true); +var $RegExp = GetIntrinsic('%RegExp%'); +var $Date = GetIntrinsic('%Date%'); +var $Function = GetIntrinsic('%Function%'); +var $preventExtensions = $Object.preventExtensions; + +var hasSymbols = require('has-symbols')(); + +var assertRecord = require('./helpers/assertRecord'); +var $isNaN = require('./helpers/isNaN'); +var $isFinite = require('./helpers/isFinite'); +var MAX_ARRAY_LENGTH = Math.pow(2, 32) - 1; +var MAX_SAFE_INTEGER = require('./helpers/maxSafeInteger'); + +var assign = require('./helpers/assign'); +var sign = require('./helpers/sign'); +var mod = require('./helpers/mod'); +var isPrimitive = require('./helpers/isPrimitive'); +var forEach = require('./helpers/forEach'); +var every = require('./helpers/every'); +var isSamePropertyDescriptor = require('./helpers/isSamePropertyDescriptor'); +var isPropertyDescriptor = require('./helpers/isPropertyDescriptor'); +var parseInteger = parseInt; +var callBound = require('./helpers/callBound'); +var regexTester = require('./helpers/regexTester'); +var getIteratorMethod = require('./helpers/getIteratorMethod'); +var getSymbolDescription = require('./helpers/getSymbolDescription'); + +var $PromiseThen = callBound('Promise.prototype.then', true); +var arraySlice = callBound('Array.prototype.slice'); +var strSlice = callBound('String.prototype.slice'); +var $indexOf = callBound('Array.prototype.indexOf'); +var $push = callBound('Array.prototype.push'); + +var isBinary = regexTester(/^0b[01]+$/i); +var isOctal = regexTester(/^0o[0-7]+$/i); +var isDigit = regexTester(/^[0-9]$/); +var regexExec = callBound('RegExp.prototype.exec'); +var nonWS = ['\u0085', '\u200b', '\ufffe'].join(''); +var nonWSregex = new $RegExp('[' + nonWS + ']', 'g'); +var hasNonWS = regexTester(nonWSregex); +var isInvalidHexLiteral = regexTester(/^[-+]0x[0-9a-f]+$/i); +var $charCodeAt = callBound('String.prototype.charCodeAt'); +var $isEnumerable = callBound('Object.prototype.propertyIsEnumerable'); + +var toStr = callBound('Object.prototype.toString'); + +var $NumberValueOf = callBound('Number.prototype.valueOf'); +var $BooleanValueOf = callBound('Boolean.prototype.valueOf'); +var $StringValueOf = callBound('String.prototype.valueOf'); +var $DateValueOf = callBound('Date.prototype.valueOf'); +var $SymbolToString = callBound('Symbol.prototype.toString', true); + +var $floor = Math.floor; +var $abs = Math.abs; + +var $ObjectCreate = $Object.create; +var $gOPD = $Object.getOwnPropertyDescriptor; +var $gOPN = $Object.getOwnPropertyNames; +var $gOPS = $Object.getOwnPropertySymbols; +var $isExtensible = $Object.isExtensible; +var $defineProperty = $Object.defineProperty; +var $setProto = require('./helpers/setProto'); + +var DefineOwnProperty = function DefineOwnProperty(ES, O, P, desc) { + if (!$defineProperty) { + if (!ES.IsDataDescriptor(desc)) { + // ES3 does not support getters/setters + return false; + } + if (!desc['[[Configurable]]'] || !desc['[[Writable]]']) { + return false; + } + + // fallback for ES3 + if (P in O && $isEnumerable(O, P) !== !!desc['[[Enumerable]]']) { + // a non-enumerable existing property + return false; + } + + // property does not exist at all, or exists but is enumerable + var V = desc['[[Value]]']; + O[P] = V; // will use [[Define]] + return ES.SameValue(O[P], V); + } + $defineProperty(O, P, ES.FromPropertyDescriptor(desc)); + return true; +}; + +// whitespace from: https://es5.github.io/#x15.5.4.20 +// implementation from https://github.com/es-shims/es5-shim/blob/v3.4.0/es5-shim.js#L1304-L1324 +var ws = [ + '\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003', + '\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028', + '\u2029\uFEFF' +].join(''); +var trimRegex = new RegExp('(^[' + ws + ']+)|([' + ws + ']+$)', 'g'); +var $replace = callBound('String.prototype.replace'); +var trim = function (value) { + return $replace(value, trimRegex, ''); +}; + +var ES5 = require('./es5'); + +var hasRegExpMatcher = require('is-regex'); + +// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-abstract-operations +var ES6 = assign(assign({}, ES5), { + + // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-call-f-v-args + Call: function Call(F, V) { + var args = arguments.length > 2 ? arguments[2] : []; + if (!this.IsCallable(F)) { + throw new $TypeError(inspect(F) + ' is not a function'); + } + return F.apply(V, args); + }, + + // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-toprimitive + ToPrimitive: toPrimitive, + + // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-toboolean + // ToBoolean: ES5.ToBoolean, + + // https://ecma-international.org/ecma-262/6.0/#sec-tonumber + ToNumber: function ToNumber(argument) { + var value = isPrimitive(argument) ? argument : toPrimitive(argument, $Number); + if (typeof value === 'symbol') { + throw new $TypeError('Cannot convert a Symbol value to a number'); + } + if (typeof value === 'string') { + if (isBinary(value)) { + return this.ToNumber(parseInteger(strSlice(value, 2), 2)); + } else if (isOctal(value)) { + return this.ToNumber(parseInteger(strSlice(value, 2), 8)); + } else if (hasNonWS(value) || isInvalidHexLiteral(value)) { + return NaN; + } else { + var trimmed = trim(value); + if (trimmed !== value) { + return this.ToNumber(trimmed); + } + } + } + return $Number(value); + }, + + // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tointeger + // ToInteger: ES5.ToNumber, + + // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-toint32 + // ToInt32: ES5.ToInt32, + + // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-touint32 + // ToUint32: ES5.ToUint32, + + // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-toint16 + ToInt16: function ToInt16(argument) { + var int16bit = this.ToUint16(argument); + return int16bit >= 0x8000 ? int16bit - 0x10000 : int16bit; + }, + + // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-touint16 + // ToUint16: ES5.ToUint16, + + // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-toint8 + ToInt8: function ToInt8(argument) { + var int8bit = this.ToUint8(argument); + return int8bit >= 0x80 ? int8bit - 0x100 : int8bit; + }, + + // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-touint8 + ToUint8: function ToUint8(argument) { + var number = this.ToNumber(argument); + if ($isNaN(number) || number === 0 || !$isFinite(number)) { return 0; } + var posInt = sign(number) * $floor($abs(number)); + return mod(posInt, 0x100); + }, + + // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-touint8clamp + ToUint8Clamp: function ToUint8Clamp(argument) { + var number = this.ToNumber(argument); + if ($isNaN(number) || number <= 0) { return 0; } + if (number >= 0xFF) { return 0xFF; } + var f = $floor(argument); + if (f + 0.5 < number) { return f + 1; } + if (number < f + 0.5) { return f; } + if (f % 2 !== 0) { return f + 1; } + return f; + }, + + // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tostring + ToString: function ToString(argument) { + if (typeof argument === 'symbol') { + throw new $TypeError('Cannot convert a Symbol value to a string'); + } + return $String(argument); + }, + + // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-toobject + ToObject: function ToObject(value) { + this.RequireObjectCoercible(value); + return $Object(value); + }, + + // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-topropertykey + ToPropertyKey: function ToPropertyKey(argument) { + var key = this.ToPrimitive(argument, $String); + return typeof key === 'symbol' ? key : this.ToString(key); + }, + + // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength + ToLength: function ToLength(argument) { + var len = this.ToInteger(argument); + if (len <= 0) { return 0; } // includes converting -0 to +0 + if (len > MAX_SAFE_INTEGER) { return MAX_SAFE_INTEGER; } + return len; + }, + + // https://ecma-international.org/ecma-262/6.0/#sec-canonicalnumericindexstring + CanonicalNumericIndexString: function CanonicalNumericIndexString(argument) { + if (toStr(argument) !== '[object String]') { + throw new $TypeError('must be a string'); + } + if (argument === '-0') { return -0; } + var n = this.ToNumber(argument); + if (this.SameValue(this.ToString(n), argument)) { return n; } + return void 0; + }, + + // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-requireobjectcoercible + RequireObjectCoercible: ES5.CheckObjectCoercible, + + // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-isarray + IsArray: $Array.isArray || function IsArray(argument) { + return toStr(argument) === '[object Array]'; + }, + + // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-iscallable + // IsCallable: ES5.IsCallable, + + // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-isconstructor + IsConstructor: function IsConstructor(argument) { + return typeof argument === 'function' && !!argument.prototype; // unfortunately there's no way to truly check this without try/catch `new argument` or Proxy + }, + + // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-isextensible-o + IsExtensible: $preventExtensions + ? function IsExtensible(obj) { + if (isPrimitive(obj)) { + return false; + } + return $isExtensible(obj); + } + : function isExtensible(obj) { return true; }, // eslint-disable-line no-unused-vars + + // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-isinteger + IsInteger: function IsInteger(argument) { + if (typeof argument !== 'number' || $isNaN(argument) || !$isFinite(argument)) { + return false; + } + var abs = $abs(argument); + return $floor(abs) === abs; + }, + + // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-ispropertykey + IsPropertyKey: function IsPropertyKey(argument) { + return typeof argument === 'string' || typeof argument === 'symbol'; + }, + + // https://ecma-international.org/ecma-262/6.0/#sec-isregexp + IsRegExp: function IsRegExp(argument) { + if (!argument || typeof argument !== 'object') { + return false; + } + if (hasSymbols) { + var isRegExp = argument[$Symbol.match]; + if (typeof isRegExp !== 'undefined') { + return ES5.ToBoolean(isRegExp); + } + } + return hasRegExpMatcher(argument); + }, + + // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevalue + // SameValue: ES5.SameValue, + + // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero + SameValueZero: function SameValueZero(x, y) { + return (x === y) || ($isNaN(x) && $isNaN(y)); + }, + + /** + * 7.3.2 GetV (V, P) + * 1. Assert: IsPropertyKey(P) is true. + * 2. Let O be ToObject(V). + * 3. ReturnIfAbrupt(O). + * 4. Return O.[[Get]](P, V). + */ + GetV: function GetV(V, P) { + // 7.3.2.1 + if (!this.IsPropertyKey(P)) { + throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true'); + } + + // 7.3.2.2-3 + var O = this.ToObject(V); + + // 7.3.2.4 + return O[P]; + }, + + /** + * 7.3.9 - https://ecma-international.org/ecma-262/6.0/#sec-getmethod + * 1. Assert: IsPropertyKey(P) is true. + * 2. Let func be GetV(O, P). + * 3. ReturnIfAbrupt(func). + * 4. If func is either undefined or null, return undefined. + * 5. If IsCallable(func) is false, throw a TypeError exception. + * 6. Return func. + */ + GetMethod: function GetMethod(O, P) { + // 7.3.9.1 + if (!this.IsPropertyKey(P)) { + throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true'); + } + + // 7.3.9.2 + var func = this.GetV(O, P); + + // 7.3.9.4 + if (func == null) { + return void 0; + } + + // 7.3.9.5 + if (!this.IsCallable(func)) { + throw new $TypeError(P + 'is not a function'); + } + + // 7.3.9.6 + return func; + }, + + /** + * 7.3.1 Get (O, P) - https://ecma-international.org/ecma-262/6.0/#sec-get-o-p + * 1. Assert: Type(O) is Object. + * 2. Assert: IsPropertyKey(P) is true. + * 3. Return O.[[Get]](P, O). + */ + Get: function Get(O, P) { + // 7.3.1.1 + if (this.Type(O) !== 'Object') { + throw new $TypeError('Assertion failed: Type(O) is not Object'); + } + // 7.3.1.2 + if (!this.IsPropertyKey(P)) { + throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true, got ' + inspect(P)); + } + // 7.3.1.3 + return O[P]; + }, + + Type: function Type(x) { + if (typeof x === 'symbol') { + return 'Symbol'; + } + return ES5.Type(x); + }, + + // https://ecma-international.org/ecma-262/6.0/#sec-speciesconstructor + SpeciesConstructor: function SpeciesConstructor(O, defaultConstructor) { + if (this.Type(O) !== 'Object') { + throw new $TypeError('Assertion failed: Type(O) is not Object'); + } + var C = O.constructor; + if (typeof C === 'undefined') { + return defaultConstructor; + } + if (this.Type(C) !== 'Object') { + throw new $TypeError('O.constructor is not an Object'); + } + var S = hasSymbols && $Symbol.species ? C[$Symbol.species] : void 0; + if (S == null) { + return defaultConstructor; + } + if (this.IsConstructor(S)) { + return S; + } + throw new $TypeError('no constructor found'); + }, + + // https://www.ecma-international.org/ecma-262/6.0/#sec-frompropertydescriptor + FromPropertyDescriptor: function FromPropertyDescriptor(Desc) { + if (typeof Desc === 'undefined') { + return Desc; + } + + assertRecord(this, 'Property Descriptor', 'Desc', Desc); + + var obj = {}; + if ('[[Value]]' in Desc) { + obj.value = Desc['[[Value]]']; + } + if ('[[Writable]]' in Desc) { + obj.writable = Desc['[[Writable]]']; + } + if ('[[Get]]' in Desc) { + obj.get = Desc['[[Get]]']; + } + if ('[[Set]]' in Desc) { + obj.set = Desc['[[Set]]']; + } + if ('[[Enumerable]]' in Desc) { + obj.enumerable = Desc['[[Enumerable]]']; + } + if ('[[Configurable]]' in Desc) { + obj.configurable = Desc['[[Configurable]]']; + } + return obj; + }, + + // https://ecma-international.org/ecma-262/6.0/#sec-completepropertydescriptor + CompletePropertyDescriptor: function CompletePropertyDescriptor(Desc) { + assertRecord(this, 'Property Descriptor', 'Desc', Desc); + + if (this.IsGenericDescriptor(Desc) || this.IsDataDescriptor(Desc)) { + if (!has(Desc, '[[Value]]')) { + Desc['[[Value]]'] = void 0; + } + if (!has(Desc, '[[Writable]]')) { + Desc['[[Writable]]'] = false; + } + } else { + if (!has(Desc, '[[Get]]')) { + Desc['[[Get]]'] = void 0; + } + if (!has(Desc, '[[Set]]')) { + Desc['[[Set]]'] = void 0; + } + } + if (!has(Desc, '[[Enumerable]]')) { + Desc['[[Enumerable]]'] = false; + } + if (!has(Desc, '[[Configurable]]')) { + Desc['[[Configurable]]'] = false; + } + return Desc; + }, + + // https://ecma-international.org/ecma-262/6.0/#sec-set-o-p-v-throw + Set: function Set(O, P, V, Throw) { + if (this.Type(O) !== 'Object') { + throw new $TypeError('O must be an Object'); + } + if (!this.IsPropertyKey(P)) { + throw new $TypeError('P must be a Property Key'); + } + if (this.Type(Throw) !== 'Boolean') { + throw new $TypeError('Throw must be a Boolean'); + } + if (Throw) { + O[P] = V; + return true; + } else { + try { + O[P] = V; + } catch (e) { + return false; + } + } + }, + + // https://ecma-international.org/ecma-262/6.0/#sec-hasownproperty + HasOwnProperty: function HasOwnProperty(O, P) { + if (this.Type(O) !== 'Object') { + throw new $TypeError('O must be an Object'); + } + if (!this.IsPropertyKey(P)) { + throw new $TypeError('P must be a Property Key'); + } + return has(O, P); + }, + + // https://ecma-international.org/ecma-262/6.0/#sec-hasproperty + HasProperty: function HasProperty(O, P) { + if (this.Type(O) !== 'Object') { + throw new $TypeError('O must be an Object'); + } + if (!this.IsPropertyKey(P)) { + throw new $TypeError('P must be a Property Key'); + } + return P in O; + }, + + // https://ecma-international.org/ecma-262/6.0/#sec-isconcatspreadable + IsConcatSpreadable: function IsConcatSpreadable(O) { + if (this.Type(O) !== 'Object') { + return false; + } + if (hasSymbols && typeof $Symbol.isConcatSpreadable === 'symbol') { + var spreadable = this.Get(O, Symbol.isConcatSpreadable); + if (typeof spreadable !== 'undefined') { + return this.ToBoolean(spreadable); + } + } + return this.IsArray(O); + }, + + // https://ecma-international.org/ecma-262/6.0/#sec-invoke + Invoke: function Invoke(O, P) { + if (!this.IsPropertyKey(P)) { + throw new $TypeError('P must be a Property Key'); + } + var argumentsList = arraySlice(arguments, 2); + var func = this.GetV(O, P); + return this.Call(func, O, argumentsList); + }, + + // https://ecma-international.org/ecma-262/6.0/#sec-getiterator + GetIterator: function GetIterator(obj, method) { + var actualMethod = method; + if (arguments.length < 2) { + actualMethod = getIteratorMethod(this, obj); + } + var iterator = this.Call(actualMethod, obj); + if (this.Type(iterator) !== 'Object') { + throw new $TypeError('iterator must return an object'); + } + + return iterator; + }, + + // https://ecma-international.org/ecma-262/6.0/#sec-iteratornext + IteratorNext: function IteratorNext(iterator, value) { + var result = this.Invoke(iterator, 'next', arguments.length < 2 ? [] : [value]); + if (this.Type(result) !== 'Object') { + throw new $TypeError('iterator next must return an object'); + } + return result; + }, + + // https://ecma-international.org/ecma-262/6.0/#sec-iteratorcomplete + IteratorComplete: function IteratorComplete(iterResult) { + if (this.Type(iterResult) !== 'Object') { + throw new $TypeError('Assertion failed: Type(iterResult) is not Object'); + } + return this.ToBoolean(this.Get(iterResult, 'done')); + }, + + // https://ecma-international.org/ecma-262/6.0/#sec-iteratorvalue + IteratorValue: function IteratorValue(iterResult) { + if (this.Type(iterResult) !== 'Object') { + throw new $TypeError('Assertion failed: Type(iterResult) is not Object'); + } + return this.Get(iterResult, 'value'); + }, + + // https://ecma-international.org/ecma-262/6.0/#sec-iteratorstep + IteratorStep: function IteratorStep(iterator) { + var result = this.IteratorNext(iterator); + var done = this.IteratorComplete(result); + return done === true ? false : result; + }, + + // https://ecma-international.org/ecma-262/6.0/#sec-iteratorclose + IteratorClose: function IteratorClose(iterator, completion) { + if (this.Type(iterator) !== 'Object') { + throw new $TypeError('Assertion failed: Type(iterator) is not Object'); + } + if (!this.IsCallable(completion)) { + throw new $TypeError('Assertion failed: completion is not a thunk for a Completion Record'); + } + var completionThunk = completion; + + var iteratorReturn = this.GetMethod(iterator, 'return'); + + if (typeof iteratorReturn === 'undefined') { + return completionThunk(); + } + + var completionRecord; + try { + var innerResult = this.Call(iteratorReturn, iterator, []); + } catch (e) { + // if we hit here, then "e" is the innerResult completion that needs re-throwing + + // if the completion is of type "throw", this will throw. + completionRecord = completionThunk(); + completionThunk = null; // ensure it's not called twice. + + // if not, then return the innerResult completion + throw e; + } + completionRecord = completionThunk(); // if innerResult worked, then throw if the completion does + completionThunk = null; // ensure it's not called twice. + + if (this.Type(innerResult) !== 'Object') { + throw new $TypeError('iterator .return must return an object'); + } + + return completionRecord; + }, + + // https://ecma-international.org/ecma-262/6.0/#sec-createiterresultobject + CreateIterResultObject: function CreateIterResultObject(value, done) { + if (this.Type(done) !== 'Boolean') { + throw new $TypeError('Assertion failed: Type(done) is not Boolean'); + } + return { + value: value, + done: done + }; + }, + + // https://ecma-international.org/ecma-262/6.0/#sec-regexpexec + RegExpExec: function RegExpExec(R, S) { + if (this.Type(R) !== 'Object') { + throw new $TypeError('R must be an Object'); + } + if (this.Type(S) !== 'String') { + throw new $TypeError('S must be a String'); + } + var exec = this.Get(R, 'exec'); + if (this.IsCallable(exec)) { + var result = this.Call(exec, R, [S]); + if (result === null || this.Type(result) === 'Object') { + return result; + } + throw new $TypeError('"exec" method must return `null` or an Object'); + } + return regexExec(R, S); + }, + + // https://ecma-international.org/ecma-262/6.0/#sec-arrayspeciescreate + ArraySpeciesCreate: function ArraySpeciesCreate(originalArray, length) { + if (!this.IsInteger(length) || length < 0) { + throw new $TypeError('Assertion failed: length must be an integer >= 0'); + } + var len = length === 0 ? 0 : length; + var C; + var isArray = this.IsArray(originalArray); + if (isArray) { + C = this.Get(originalArray, 'constructor'); + // TODO: figure out how to make a cross-realm normal Array, a same-realm Array + // if (this.IsConstructor(C)) { + // if C is another realm's Array, C = undefined + // Object.getPrototypeOf(Object.getPrototypeOf(Object.getPrototypeOf(Array))) === null ? + // } + if (this.Type(C) === 'Object' && hasSymbols && $Symbol.species) { + C = this.Get(C, $Symbol.species); + if (C === null) { + C = void 0; + } + } + } + if (typeof C === 'undefined') { + return $Array(len); + } + if (!this.IsConstructor(C)) { + throw new $TypeError('C must be a constructor'); + } + return new C(len); // this.Construct(C, len); + }, + + CreateDataProperty: function CreateDataProperty(O, P, V) { + if (this.Type(O) !== 'Object') { + throw new $TypeError('Assertion failed: Type(O) is not Object'); + } + if (!this.IsPropertyKey(P)) { + throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true'); + } + var oldDesc = $gOPD(O, P); + var extensible = oldDesc || this.IsExtensible(O); + var immutable = oldDesc && (!oldDesc.writable || !oldDesc.configurable); + if (immutable || !extensible) { + return false; + } + return DefineOwnProperty(this, O, P, { + '[[Configurable]]': true, + '[[Enumerable]]': true, + '[[Value]]': V, + '[[Writable]]': true + }); + }, + + // https://ecma-international.org/ecma-262/6.0/#sec-createdatapropertyorthrow + CreateDataPropertyOrThrow: function CreateDataPropertyOrThrow(O, P, V) { + if (this.Type(O) !== 'Object') { + throw new $TypeError('Assertion failed: Type(O) is not Object'); + } + if (!this.IsPropertyKey(P)) { + throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true'); + } + var success = this.CreateDataProperty(O, P, V); + if (!success) { + throw new $TypeError('unable to create data property'); + } + return success; + }, + + // https://www.ecma-international.org/ecma-262/6.0/#sec-objectcreate + ObjectCreate: function ObjectCreate(proto, internalSlotsList) { + if (proto !== null && this.Type(proto) !== 'Object') { + throw new $TypeError('Assertion failed: proto must be null or an object'); + } + var slots = arguments.length < 2 ? [] : internalSlotsList; + if (slots.length > 0) { + throw new $SyntaxError('es-abstract does not yet support internal slots'); + } + + if (proto === null && !$ObjectCreate) { + throw new $SyntaxError('native Object.create support is required to create null objects'); + } + + return $ObjectCreate(proto); + }, + + // https://ecma-international.org/ecma-262/6.0/#sec-advancestringindex + AdvanceStringIndex: function AdvanceStringIndex(S, index, unicode) { + if (this.Type(S) !== 'String') { + throw new $TypeError('S must be a String'); + } + if (!this.IsInteger(index) || index < 0 || index > MAX_SAFE_INTEGER) { + throw new $TypeError('Assertion failed: length must be an integer >= 0 and <= 2**53'); + } + if (this.Type(unicode) !== 'Boolean') { + throw new $TypeError('Assertion failed: unicode must be a Boolean'); + } + if (!unicode) { + return index + 1; + } + var length = S.length; + if ((index + 1) >= length) { + return index + 1; + } + + var first = $charCodeAt(S, index); + if (first < 0xD800 || first > 0xDBFF) { + return index + 1; + } + + var second = $charCodeAt(S, index + 1); + if (second < 0xDC00 || second > 0xDFFF) { + return index + 1; + } + + return index + 2; + }, + + // https://www.ecma-international.org/ecma-262/6.0/#sec-createmethodproperty + CreateMethodProperty: function CreateMethodProperty(O, P, V) { + if (this.Type(O) !== 'Object') { + throw new $TypeError('Assertion failed: Type(O) is not Object'); + } + + if (!this.IsPropertyKey(P)) { + throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true'); + } + + var newDesc = { + '[[Configurable]]': true, + '[[Enumerable]]': false, + '[[Value]]': V, + '[[Writable]]': true + }; + return DefineOwnProperty(this, O, P, newDesc); + }, + + // https://www.ecma-international.org/ecma-262/6.0/#sec-definepropertyorthrow + DefinePropertyOrThrow: function DefinePropertyOrThrow(O, P, desc) { + if (this.Type(O) !== 'Object') { + throw new $TypeError('Assertion failed: Type(O) is not Object'); + } + + if (!this.IsPropertyKey(P)) { + throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true'); + } + + var Desc = isPropertyDescriptor(this, desc) ? desc : this.ToPropertyDescriptor(desc); + if (!isPropertyDescriptor(this, Desc)) { + throw new $TypeError('Assertion failed: Desc is not a valid Property Descriptor'); + } + + return DefineOwnProperty(this, O, P, Desc); + }, + + // https://www.ecma-international.org/ecma-262/6.0/#sec-deletepropertyorthrow + DeletePropertyOrThrow: function DeletePropertyOrThrow(O, P) { + if (this.Type(O) !== 'Object') { + throw new $TypeError('Assertion failed: Type(O) is not Object'); + } + + if (!this.IsPropertyKey(P)) { + throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true'); + } + + var success = delete O[P]; + if (!success) { + throw new TypeError('Attempt to delete property failed.'); + } + return success; + }, + + // https://www.ecma-international.org/ecma-262/6.0/#sec-enumerableownnames + EnumerableOwnNames: function EnumerableOwnNames(O) { + if (this.Type(O) !== 'Object') { + throw new $TypeError('Assertion failed: Type(O) is not Object'); + } + + return keys(O); + }, + + // https://ecma-international.org/ecma-262/6.0/#sec-properties-of-the-number-prototype-object + thisNumberValue: function thisNumberValue(value) { + if (this.Type(value) === 'Number') { + return value; + } + + return $NumberValueOf(value); + }, + + // https://ecma-international.org/ecma-262/6.0/#sec-properties-of-the-boolean-prototype-object + thisBooleanValue: function thisBooleanValue(value) { + if (this.Type(value) === 'Boolean') { + return value; + } + + return $BooleanValueOf(value); + }, + + // https://ecma-international.org/ecma-262/6.0/#sec-properties-of-the-string-prototype-object + thisStringValue: function thisStringValue(value) { + if (this.Type(value) === 'String') { + return value; + } + + return $StringValueOf(value); + }, + + // https://ecma-international.org/ecma-262/6.0/#sec-properties-of-the-date-prototype-object + thisTimeValue: function thisTimeValue(value) { + return $DateValueOf(value); + }, + + // https://www.ecma-international.org/ecma-262/6.0/#sec-setintegritylevel + SetIntegrityLevel: function SetIntegrityLevel(O, level) { + if (this.Type(O) !== 'Object') { + throw new $TypeError('Assertion failed: Type(O) is not Object'); + } + if (level !== 'sealed' && level !== 'frozen') { + throw new $TypeError('Assertion failed: `level` must be `"sealed"` or `"frozen"`'); + } + if (!$preventExtensions) { + throw new $SyntaxError('SetIntegrityLevel requires native `Object.preventExtensions` support'); + } + var status = $preventExtensions(O); + if (!status) { + return false; + } + if (!$gOPN) { + throw new $SyntaxError('SetIntegrityLevel requires native `Object.getOwnPropertyNames` support'); + } + var theKeys = $gOPN(O); + var ES = this; + if (level === 'sealed') { + forEach(theKeys, function (k) { + ES.DefinePropertyOrThrow(O, k, { configurable: false }); + }); + } else if (level === 'frozen') { + forEach(theKeys, function (k) { + var currentDesc = $gOPD(O, k); + if (typeof currentDesc !== 'undefined') { + var desc; + if (ES.IsAccessorDescriptor(ES.ToPropertyDescriptor(currentDesc))) { + desc = { configurable: false }; + } else { + desc = { configurable: false, writable: false }; + } + ES.DefinePropertyOrThrow(O, k, desc); + } + }); + } + return true; + }, + + // https://www.ecma-international.org/ecma-262/6.0/#sec-testintegritylevel + TestIntegrityLevel: function TestIntegrityLevel(O, level) { + if (this.Type(O) !== 'Object') { + throw new $TypeError('Assertion failed: Type(O) is not Object'); + } + if (level !== 'sealed' && level !== 'frozen') { + throw new $TypeError('Assertion failed: `level` must be `"sealed"` or `"frozen"`'); + } + var status = this.IsExtensible(O); + if (status) { + return false; + } + var theKeys = $gOPN(O); + var ES = this; + return theKeys.length === 0 || every(theKeys, function (k) { + var currentDesc = $gOPD(O, k); + if (typeof currentDesc !== 'undefined') { + if (currentDesc.configurable) { + return false; + } + if (level === 'frozen' && ES.IsDataDescriptor(ES.ToPropertyDescriptor(currentDesc)) && currentDesc.writable) { + return false; + } + } + return true; + }); + }, + + // https://www.ecma-international.org/ecma-262/6.0/#sec-ordinaryhasinstance + OrdinaryHasInstance: function OrdinaryHasInstance(C, O) { + if (this.IsCallable(C) === false) { + return false; + } + if (this.Type(O) !== 'Object') { + return false; + } + var P = this.Get(C, 'prototype'); + if (this.Type(P) !== 'Object') { + throw new $TypeError('OrdinaryHasInstance called on an object with an invalid prototype property.'); + } + return O instanceof C; + }, + + // https://www.ecma-international.org/ecma-262/6.0/#sec-ordinaryhasproperty + OrdinaryHasProperty: function OrdinaryHasProperty(O, P) { + if (this.Type(O) !== 'Object') { + throw new $TypeError('Assertion failed: Type(O) is not Object'); + } + if (!this.IsPropertyKey(P)) { + throw new $TypeError('Assertion failed: P must be a Property Key'); + } + return P in O; + }, + + // https://www.ecma-international.org/ecma-262/6.0/#sec-instanceofoperator + InstanceofOperator: function InstanceofOperator(O, C) { + if (this.Type(O) !== 'Object') { + throw new $TypeError('Assertion failed: Type(O) is not Object'); + } + var instOfHandler = hasSymbols && $Symbol.hasInstance ? this.GetMethod(C, $Symbol.hasInstance) : void 0; + if (typeof instOfHandler !== 'undefined') { + return this.ToBoolean(this.Call(instOfHandler, C, [O])); + } + if (!this.IsCallable(C)) { + throw new $TypeError('`C` is not Callable'); + } + return this.OrdinaryHasInstance(C, O); + }, + + // https://www.ecma-international.org/ecma-262/6.0/#sec-ispromise + IsPromise: function IsPromise(x) { + if (this.Type(x) !== 'Object') { + return false; + } + if (!$PromiseThen) { // Promises are not supported + return false; + } + try { + $PromiseThen(x); // throws if not a promise + } catch (e) { + return false; + } + return true; + }, + + // https://www.ecma-international.org/ecma-262/6.0/#sec-abstract-equality-comparison + 'Abstract Equality Comparison': function AbstractEqualityComparison(x, y) { + var xType = this.Type(x); + var yType = this.Type(y); + if (xType === yType) { + return x === y; // ES6+ specified this shortcut anyways. + } + if (x == null && y == null) { + return true; + } + if (xType === 'Number' && yType === 'String') { + return this['Abstract Equality Comparison'](x, this.ToNumber(y)); + } + if (xType === 'String' && yType === 'Number') { + return this['Abstract Equality Comparison'](this.ToNumber(x), y); + } + if (xType === 'Boolean') { + return this['Abstract Equality Comparison'](this.ToNumber(x), y); + } + if (yType === 'Boolean') { + return this['Abstract Equality Comparison'](x, this.ToNumber(y)); + } + if ((xType === 'String' || xType === 'Number' || xType === 'Symbol') && yType === 'Object') { + return this['Abstract Equality Comparison'](x, this.ToPrimitive(y)); + } + if (xType === 'Object' && (yType === 'String' || yType === 'Number' || yType === 'Symbol')) { + return this['Abstract Equality Comparison'](this.ToPrimitive(x), y); + } + return false; + }, + + // eslint-disable-next-line max-lines-per-function, max-statements, id-length, max-params + ValidateAndApplyPropertyDescriptor: function ValidateAndApplyPropertyDescriptor(O, P, extensible, Desc, current) { + // this uses the ES2017+ logic, since it fixes a number of bugs in the ES2015 logic. + var oType = this.Type(O); + if (oType !== 'Undefined' && oType !== 'Object') { + throw new $TypeError('Assertion failed: O must be undefined or an Object'); + } + if (this.Type(extensible) !== 'Boolean') { + throw new $TypeError('Assertion failed: extensible must be a Boolean'); + } + if (!isPropertyDescriptor(this, Desc)) { + throw new $TypeError('Assertion failed: Desc must be a Property Descriptor'); + } + if (this.Type(current) !== 'Undefined' && !isPropertyDescriptor(this, current)) { + throw new $TypeError('Assertion failed: current must be a Property Descriptor, or undefined'); + } + if (oType !== 'Undefined' && !this.IsPropertyKey(P)) { + throw new $TypeError('Assertion failed: if O is not undefined, P must be a Property Key'); + } + if (this.Type(current) === 'Undefined') { + if (!extensible) { + return false; + } + if (this.IsGenericDescriptor(Desc) || this.IsDataDescriptor(Desc)) { + if (oType !== 'Undefined') { + DefineOwnProperty(this, O, P, { + '[[Configurable]]': Desc['[[Configurable]]'], + '[[Enumerable]]': Desc['[[Enumerable]]'], + '[[Value]]': Desc['[[Value]]'], + '[[Writable]]': Desc['[[Writable]]'] + }); + } + } else { + if (!this.IsAccessorDescriptor(Desc)) { + throw new $TypeError('Assertion failed: Desc is not an accessor descriptor'); + } + if (oType !== 'Undefined') { + return DefineOwnProperty(this, O, P, Desc); + } + } + return true; + } + if (this.IsGenericDescriptor(Desc) && !('[[Configurable]]' in Desc) && !('[[Enumerable]]' in Desc)) { + return true; + } + if (isSamePropertyDescriptor(this, Desc, current)) { + return true; // removed by ES2017, but should still be correct + } + // "if every field in Desc is absent, return true" can't really match the assertion that it's a Property Descriptor + if (!current['[[Configurable]]']) { + if (Desc['[[Configurable]]']) { + return false; + } + if ('[[Enumerable]]' in Desc && !Desc['[[Enumerable]]'] === !!current['[[Enumerable]]']) { + return false; + } + } + if (this.IsGenericDescriptor(Desc)) { + // no further validation is required. + } else if (this.IsDataDescriptor(current) !== this.IsDataDescriptor(Desc)) { + if (!current['[[Configurable]]']) { + return false; + } + if (this.IsDataDescriptor(current)) { + if (oType !== 'Undefined') { + DefineOwnProperty(this, O, P, { + '[[Configurable]]': current['[[Configurable]]'], + '[[Enumerable]]': current['[[Enumerable]]'], + '[[Get]]': undefined + }); + } + } else if (oType !== 'Undefined') { + DefineOwnProperty(this, O, P, { + '[[Configurable]]': current['[[Configurable]]'], + '[[Enumerable]]': current['[[Enumerable]]'], + '[[Value]]': undefined + }); + } + } else if (this.IsDataDescriptor(current) && this.IsDataDescriptor(Desc)) { + if (!current['[[Configurable]]'] && !current['[[Writable]]']) { + if ('[[Writable]]' in Desc && Desc['[[Writable]]']) { + return false; + } + if ('[[Value]]' in Desc && !this.SameValue(Desc['[[Value]]'], current['[[Value]]'])) { + return false; + } + return true; + } + } else if (this.IsAccessorDescriptor(current) && this.IsAccessorDescriptor(Desc)) { + if (!current['[[Configurable]]']) { + if ('[[Set]]' in Desc && !this.SameValue(Desc['[[Set]]'], current['[[Set]]'])) { + return false; + } + if ('[[Get]]' in Desc && !this.SameValue(Desc['[[Get]]'], current['[[Get]]'])) { + return false; + } + return true; + } + } else { + throw new $TypeError('Assertion failed: current and Desc are not both data, both accessors, or one accessor and one data.'); + } + if (oType !== 'Undefined') { + return DefineOwnProperty(this, O, P, Desc); + } + return true; + }, + + // https://www.ecma-international.org/ecma-262/6.0/#sec-ordinarydefineownproperty + OrdinaryDefineOwnProperty: function OrdinaryDefineOwnProperty(O, P, Desc) { + if (this.Type(O) !== 'Object') { + throw new $TypeError('Assertion failed: O must be an Object'); + } + if (!this.IsPropertyKey(P)) { + throw new $TypeError('Assertion failed: P must be a Property Key'); + } + if (!isPropertyDescriptor(this, Desc)) { + throw new $TypeError('Assertion failed: Desc must be a Property Descriptor'); + } + var desc = $gOPD(O, P); + var current = desc && this.ToPropertyDescriptor(desc); + var extensible = this.IsExtensible(O); + return this.ValidateAndApplyPropertyDescriptor(O, P, extensible, Desc, current); + }, + + // https://www.ecma-international.org/ecma-262/6.0/#sec-ordinarygetownproperty + OrdinaryGetOwnProperty: function OrdinaryGetOwnProperty(O, P) { + if (this.Type(O) !== 'Object') { + throw new $TypeError('Assertion failed: O must be an Object'); + } + if (!this.IsPropertyKey(P)) { + throw new $TypeError('Assertion failed: P must be a Property Key'); + } + if (!has(O, P)) { + return void 0; + } + if (!$gOPD) { + // ES3 fallback + var arrayLength = this.IsArray(O) && P === 'length'; + var regexLastIndex = this.IsRegExp(O) && P === 'lastIndex'; + return { + '[[Configurable]]': !(arrayLength || regexLastIndex), + '[[Enumerable]]': $isEnumerable(O, P), + '[[Value]]': O[P], + '[[Writable]]': true + }; + } + return this.ToPropertyDescriptor($gOPD(O, P)); + }, + + // https://www.ecma-international.org/ecma-262/6.0/#sec-arraycreate + ArrayCreate: function ArrayCreate(length) { + if (!this.IsInteger(length) || length < 0) { + throw new $TypeError('Assertion failed: `length` must be an integer Number >= 0'); + } + if (length > MAX_ARRAY_LENGTH) { + throw new $RangeError('length is greater than (2**32 - 1)'); + } + var proto = arguments.length > 1 ? arguments[1] : $ArrayPrototype; + var A = []; // steps 5 - 7, and 9 + if (proto !== $ArrayPrototype) { // step 8 + if (!$setProto) { + throw new $SyntaxError('ArrayCreate: a `proto` argument that is not `Array.prototype` is not supported in an environment that does not support setting the [[Prototype]]'); + } + $setProto(A, proto); + } + if (length !== 0) { // bypasses the need for step 2 + A.length = length; + } + /* step 10, the above as a shortcut for the below + this.OrdinaryDefineOwnProperty(A, 'length', { + '[[Configurable]]': false, + '[[Enumerable]]': false, + '[[Value]]': length, + '[[Writable]]': true + }); + */ + return A; + }, + + // eslint-disable-next-line max-statements, max-lines-per-function + ArraySetLength: function ArraySetLength(A, Desc) { + if (!this.IsArray(A)) { + throw new $TypeError('Assertion failed: A must be an Array'); + } + if (!isPropertyDescriptor(this, Desc)) { + throw new $TypeError('Assertion failed: Desc must be a Property Descriptor'); + } + if (!('[[Value]]' in Desc)) { + return this.OrdinaryDefineOwnProperty(A, 'length', Desc); + } + var newLenDesc = assign({}, Desc); + var newLen = this.ToUint32(Desc['[[Value]]']); + var numberLen = this.ToNumber(Desc['[[Value]]']); + if (newLen !== numberLen) { + throw new $RangeError('Invalid array length'); + } + newLenDesc['[[Value]]'] = newLen; + var oldLenDesc = this.OrdinaryGetOwnProperty(A, 'length'); + if (!this.IsDataDescriptor(oldLenDesc)) { + throw new $TypeError('Assertion failed: an array had a non-data descriptor on `length`'); + } + var oldLen = oldLenDesc['[[Value]]']; + if (newLen >= oldLen) { + return this.OrdinaryDefineOwnProperty(A, 'length', newLenDesc); + } + if (!oldLenDesc['[[Writable]]']) { + return false; + } + var newWritable; + if (!('[[Writable]]' in newLenDesc) || newLenDesc['[[Writable]]']) { + newWritable = true; + } else { + newWritable = false; + newLenDesc['[[Writable]]'] = true; + } + var succeeded = this.OrdinaryDefineOwnProperty(A, 'length', newLenDesc); + if (!succeeded) { + return false; + } + while (newLen < oldLen) { + oldLen -= 1; + var deleteSucceeded = delete A[this.ToString(oldLen)]; + if (!deleteSucceeded) { + newLenDesc['[[Value]]'] = oldLen + 1; + if (!newWritable) { + newLenDesc['[[Writable]]'] = false; + this.OrdinaryDefineOwnProperty(A, 'length', newLenDesc); + return false; + } + } + } + if (!newWritable) { + return this.OrdinaryDefineOwnProperty(A, 'length', { '[[Writable]]': false }); + } + return true; + }, + + // https://www.ecma-international.org/ecma-262/6.0/#sec-createhtml + CreateHTML: function CreateHTML(string, tag, attribute, value) { + if (this.Type(tag) !== 'String' || this.Type(attribute) !== 'String') { + throw new $TypeError('Assertion failed: `tag` and `attribute` must be strings'); + } + var str = this.RequireObjectCoercible(string); + var S = this.ToString(str); + var p1 = '<' + tag; + if (attribute !== '') { + var V = this.ToString(value); + var escapedV = $replace(V, /\x22/g, '"'); + p1 += '\x20' + attribute + '\x3D\x22' + escapedV + '\x22'; + } + return p1 + '>' + S + ''; + }, + + // https://www.ecma-international.org/ecma-262/6.0/#sec-getownpropertykeys + GetOwnPropertyKeys: function GetOwnPropertyKeys(O, Type) { + if (this.Type(O) !== 'Object') { + throw new $TypeError('Assertion failed: Type(O) is not Object'); + } + if (Type === 'Symbol') { + return hasSymbols && $gOPS ? $gOPS(O) : []; + } + if (Type === 'String') { + if (!$gOPN) { + return keys(O); + } + return $gOPN(O); + } + throw new $TypeError('Assertion failed: `Type` must be `"String"` or `"Symbol"`'); + }, + + // https://www.ecma-international.org/ecma-262/6.0/#sec-symboldescriptivestring + SymbolDescriptiveString: function SymbolDescriptiveString(sym) { + if (this.Type(sym) !== 'Symbol') { + throw new $TypeError('Assertion failed: `sym` must be a Symbol'); + } + return $SymbolToString(sym); + }, + + // https://www.ecma-international.org/ecma-262/6.0/#sec-getsubstitution + // eslint-disable-next-line max-statements, max-params, max-lines-per-function + GetSubstitution: function GetSubstitution(matched, str, position, captures, replacement) { + if (this.Type(matched) !== 'String') { + throw new $TypeError('Assertion failed: `matched` must be a String'); + } + var matchLength = matched.length; + + if (this.Type(str) !== 'String') { + throw new $TypeError('Assertion failed: `str` must be a String'); + } + var stringLength = str.length; + + if (!this.IsInteger(position) || position < 0 || position > stringLength) { + throw new $TypeError('Assertion failed: `position` must be a nonnegative integer, and less than or equal to the length of `string`, got ' + inspect(position)); + } + + var ES = this; + var isStringOrHole = function (capture, index, arr) { return ES.Type(capture) === 'String' || !(index in arr); }; + if (!this.IsArray(captures) || !every(captures, isStringOrHole)) { + throw new $TypeError('Assertion failed: `captures` must be a List of Strings, got ' + inspect(captures)); + } + + if (this.Type(replacement) !== 'String') { + throw new $TypeError('Assertion failed: `replacement` must be a String'); + } + + var tailPos = position + matchLength; + var m = captures.length; + + var result = ''; + for (var i = 0; i < replacement.length; i += 1) { + // if this is a $, and it's not the end of the replacement + var current = replacement[i]; + var isLast = (i + 1) >= replacement.length; + var nextIsLast = (i + 2) >= replacement.length; + if (current === '$' && !isLast) { + var next = replacement[i + 1]; + if (next === '$') { + result += '$'; + i += 1; + } else if (next === '&') { + result += matched; + i += 1; + } else if (next === '`') { + result += position === 0 ? '' : strSlice(str, 0, position - 1); + i += 1; + } else if (next === "'") { + result += tailPos >= stringLength ? '' : strSlice(str, tailPos); + i += 1; + } else { + var nextNext = nextIsLast ? null : replacement[i + 2]; + if (isDigit(next) && next !== '0' && (nextIsLast || !isDigit(nextNext))) { + // $1 through $9, and not followed by a digit + var n = parseInteger(next, 10); + // if (n > m, impl-defined) + result += (n <= m && this.Type(captures[n - 1]) === 'Undefined') ? '' : captures[n - 1]; + i += 1; + } else if (isDigit(next) && (nextIsLast || isDigit(nextNext))) { + // $00 through $99 + var nn = next + nextNext; + var nnI = parseInteger(nn, 10) - 1; + // if nn === '00' or nn > m, impl-defined + result += (nn <= m && this.Type(captures[nnI]) === 'Undefined') ? '' : captures[nnI]; + i += 2; + } else { + result += '$'; + } + } + } else { + // the final $, or else not a $ + result += replacement[i]; + } + } + return result; + }, + + // https://ecma-international.org/ecma-262/6.0/#sec-todatestring + ToDateString: function ToDateString(tv) { + if (this.Type(tv) !== 'Number') { + throw new $TypeError('Assertion failed: `tv` must be a Number'); + } + if ($isNaN(tv)) { + return 'Invalid Date'; + } + return $Date(tv); + }, + + // https://ecma-international.org/ecma-262/6.0/#sec-createlistfromarraylike + CreateListFromArrayLike: function CreateListFromArrayLike(obj) { + var elementTypes = arguments.length > 1 + ? arguments[1] + : ['Undefined', 'Null', 'Boolean', 'String', 'Symbol', 'Number', 'Object']; + + if (this.Type(obj) !== 'Object') { + throw new $TypeError('Assertion failed: `obj` must be an Object'); + } + if (!this.IsArray(elementTypes)) { + throw new $TypeError('Assertion failed: `elementTypes`, if provided, must be an array'); + } + var len = this.ToLength(this.Get(obj, 'length')); + var list = []; + var index = 0; + while (index < len) { + var indexName = this.ToString(index); + var next = this.Get(obj, indexName); + var nextType = this.Type(next); + if ($indexOf(elementTypes, nextType) < 0) { + throw new $TypeError('item type ' + nextType + ' is not a valid elementType'); + } + $push(list, next); + index += 1; + } + return list; + }, + + // https://ecma-international.org/ecma-262/6.0/#sec-getprototypefromconstructor + GetPrototypeFromConstructor: function GetPrototypeFromConstructor(constructor, intrinsicDefaultProto) { + var intrinsic = GetIntrinsic(intrinsicDefaultProto); // throws if not a valid intrinsic + if (!this.IsConstructor(constructor)) { + throw new $TypeError('Assertion failed: `constructor` must be a constructor'); + } + var proto = this.Get(constructor, 'prototype'); + if (this.Type(proto) !== 'Object') { + if (!(constructor instanceof $Function)) { + // ignore other realms, for now + throw new $TypeError('cross-realm constructors not currently supported'); + } + proto = intrinsic; + } + return proto; + }, + + // https://ecma-international.org/ecma-262/6.0/#sec-setfunctionname + SetFunctionName: function SetFunctionName(F, name) { + if (typeof F !== 'function') { + throw new $TypeError('Assertion failed: `F` must be a function'); + } + if (!this.IsExtensible(F) || has(F, 'name')) { + throw new $TypeError('Assertion failed: `F` must be extensible, and must not have a `name` own property'); + } + var nameType = this.Type(name); + if (nameType !== 'Symbol' && nameType !== 'String') { + throw new $TypeError('Assertion failed: `name` must be a Symbol or a String'); + } + if (nameType === 'Symbol') { + var description = getSymbolDescription(name); + // eslint-disable-next-line no-param-reassign + name = typeof description === 'undefined' ? '' : '[' + description + ']'; + } + if (arguments.length > 2) { + var prefix = arguments[2]; + // eslint-disable-next-line no-param-reassign + name = prefix + ' ' + name; + } + return this.DefinePropertyOrThrow(F, 'name', { + '[[Value]]': name, + '[[Writable]]': false, + '[[Enumerable]]': false, + '[[Configurable]]': true + }); + } +}); + +delete ES6.CheckObjectCoercible; // renamed in ES6 to RequireObjectCoercible + +module.exports = ES6; diff --git a/scripts/2.5/node_modules/es-abstract/es2016.js b/scripts/2.5/node_modules/es-abstract/es2016.js new file mode 100644 index 00000000..9b5f9d4d --- /dev/null +++ b/scripts/2.5/node_modules/es-abstract/es2016.js @@ -0,0 +1,98 @@ +'use strict'; + +var ES2015 = require('./es2015'); +var GetIntrinsic = require('./GetIntrinsic'); +var assign = require('./helpers/assign'); +var $setProto = require('./helpers/setProto'); + +var callBound = require('./helpers/callBound'); +var getIteratorMethod = require('./helpers/getIteratorMethod'); + +var $TypeError = GetIntrinsic('%TypeError%'); +var $arrayPush = callBound('Array.prototype.push'); +var $getProto = require('./helpers/getProto'); + +var ES2016 = assign(assign({}, ES2015), { + // https://www.ecma-international.org/ecma-262/7.0/#sec-samevaluenonnumber + SameValueNonNumber: function SameValueNonNumber(x, y) { + if (typeof x === 'number' || typeof x !== typeof y) { + throw new TypeError('SameValueNonNumber requires two non-number values of the same type.'); + } + return this.SameValue(x, y); + }, + + // https://www.ecma-international.org/ecma-262/7.0/#sec-iterabletoarraylike + IterableToArrayLike: function IterableToArrayLike(items) { + var usingIterator = getIteratorMethod(this, items); + if (typeof usingIterator !== 'undefined') { + var iterator = this.GetIterator(items, usingIterator); + var values = []; + var next = true; + while (next) { + next = this.IteratorStep(iterator); + if (next) { + var nextValue = this.IteratorValue(next); + $arrayPush(values, nextValue); + } + } + return values; + } + + return this.ToObject(items); + }, + + // https://ecma-international.org/ecma-262/7.0/#sec-ordinarygetprototypeof + OrdinaryGetPrototypeOf: function (O) { + if (this.Type(O) !== 'Object') { + throw new $TypeError('Assertion failed: O must be an Object'); + } + if (!$getProto) { + throw new $TypeError('This environment does not support fetching prototypes.'); + } + return $getProto(O); + }, + + // https://ecma-international.org/ecma-262/7.0/#sec-ordinarysetprototypeof + OrdinarySetPrototypeOf: function (O, V) { + if (this.Type(V) !== 'Object' && this.Type(V) !== 'Null') { + throw new $TypeError('Assertion failed: V must be Object or Null'); + } + /* + var extensible = this.IsExtensible(O); + var current = this.OrdinaryGetPrototypeOf(O); + if (this.SameValue(V, current)) { + return true; + } + if (!extensible) { + return false; + } + */ + try { + $setProto(O, V); + } catch (e) { + return false; + } + return this.OrdinaryGetPrototypeOf(O) === V; + /* + var p = V; + var done = false; + while (!done) { + if (p === null) { + done = true; + } else if (this.SameValue(p, O)) { + return false; + } else { + if (wat) { + done = true; + } else { + p = p.[[Prototype]]; + } + } + } + O.[[Prototype]] = V; + return true; + */ + } +}); + +module.exports = ES2016; diff --git a/scripts/2.5/node_modules/es-abstract/es2017.js b/scripts/2.5/node_modules/es-abstract/es2017.js new file mode 100644 index 00000000..98039903 --- /dev/null +++ b/scripts/2.5/node_modules/es-abstract/es2017.js @@ -0,0 +1,71 @@ +'use strict'; + +var GetIntrinsic = require('./GetIntrinsic'); + +var ES2016 = require('./es2016'); +var assign = require('./helpers/assign'); +var forEach = require('./helpers/forEach'); +var callBind = require('./helpers/callBind'); + +var $TypeError = GetIntrinsic('%TypeError%'); +var callBound = require('./helpers/callBound'); +var $isEnumerable = callBound('Object.prototype.propertyIsEnumerable'); +var $pushApply = callBind.apply(GetIntrinsic('%Array.prototype.push%')); +var $arrayPush = callBound('Array.prototype.push'); + +var ES2017 = assign(assign({}, ES2016), { + ToIndex: function ToIndex(value) { + if (typeof value === 'undefined') { + return 0; + } + var integerIndex = this.ToInteger(value); + if (integerIndex < 0) { + throw new RangeError('index must be >= 0'); + } + var index = this.ToLength(integerIndex); + if (!this.SameValueZero(integerIndex, index)) { + throw new RangeError('index must be >= 0 and < 2 ** 53 - 1'); + } + return index; + }, + + // https://www.ecma-international.org/ecma-262/8.0/#sec-enumerableownproperties + EnumerableOwnProperties: function EnumerableOwnProperties(O, kind) { + var keys = ES2016.EnumerableOwnNames(O); + if (kind === 'key') { + return keys; + } + if (kind === 'value' || kind === 'key+value') { + var results = []; + forEach(keys, function (key) { + if ($isEnumerable(O, key)) { + $pushApply(results, [ + kind === 'value' ? O[key] : [key, O[key]] + ]); + } + }); + return results; + } + throw new $TypeError('Assertion failed: "kind" is not "key", "value", or "key+value": ' + kind); + }, + + // https://www.ecma-international.org/ecma-262/8.0/#sec-iterabletolist + IterableToList: function IterableToList(items, method) { + var iterator = this.GetIterator(items, method); + var values = []; + var next = true; + while (next) { + next = this.IteratorStep(iterator); + if (next) { + var nextValue = this.IteratorValue(next); + $arrayPush(values, nextValue); + } + } + return values; + } +}); + +delete ES2017.EnumerableOwnNames; // replaced with EnumerableOwnProperties +delete ES2017.IterableToArrayLike; // replaced with IterableToList + +module.exports = ES2017; diff --git a/scripts/2.5/node_modules/es-abstract/es2018.js b/scripts/2.5/node_modules/es-abstract/es2018.js new file mode 100644 index 00000000..2de7fa7a --- /dev/null +++ b/scripts/2.5/node_modules/es-abstract/es2018.js @@ -0,0 +1,289 @@ +'use strict'; + +var GetIntrinsic = require('./GetIntrinsic'); + +var keys = require('object-keys'); +var inspect = require('object-inspect'); + +var ES2017 = require('./es2017'); +var assign = require('./helpers/assign'); +var forEach = require('./helpers/forEach'); +var callBind = require('./helpers/callBind'); +var every = require('./helpers/every'); +var isPrefixOf = require('./helpers/isPrefixOf'); + +var $String = GetIntrinsic('%String%'); +var $TypeError = GetIntrinsic('%TypeError%'); + +var callBound = require('./helpers/callBound'); +var regexTester = require('./helpers/regexTester'); +var $isNaN = require('./helpers/isNaN'); + +var $SymbolValueOf = callBound('Symbol.prototype.valueOf', true); +// var $charAt = callBound('String.prototype.charAt'); +var $strSlice = callBound('String.prototype.slice'); +var $indexOf = callBound('String.prototype.indexOf'); +var $parseInt = parseInt; + +var isDigit = regexTester(/^[0-9]$/); + +var $PromiseResolve = callBound('Promise.resolve', true); + +var $isEnumerable = callBound('Object.prototype.propertyIsEnumerable'); +var $pushApply = callBind.apply(GetIntrinsic('%Array.prototype.push%')); +var $gOPS = $SymbolValueOf ? GetIntrinsic('%Object.getOwnPropertySymbols%') : null; + +var padTimeComponent = function padTimeComponent(c, count) { + return $strSlice('00' + c, -(count || 2)); +}; + +var weekdays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; +var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; + +var OwnPropertyKeys = function OwnPropertyKeys(ES, source) { + var ownKeys = keys(source); + if ($gOPS) { + $pushApply(ownKeys, $gOPS(source)); + } + return ownKeys; +}; + +var ES2018 = assign(assign({}, ES2017), { + EnumerableOwnPropertyNames: ES2017.EnumerableOwnProperties, + + // https://ecma-international.org/ecma-262/9.0/#sec-thissymbolvalue + thisSymbolValue: function thisSymbolValue(value) { + if (!$SymbolValueOf) { + throw new SyntaxError('Symbols are not supported; thisSymbolValue requires that `value` be a Symbol or a Symbol object'); + } + if (this.Type(value) === 'Symbol') { + return value; + } + return $SymbolValueOf(value); + }, + + // https://www.ecma-international.org/ecma-262/9.0/#sec-isstringprefix + IsStringPrefix: function IsStringPrefix(p, q) { + if (this.Type(p) !== 'String') { + throw new TypeError('Assertion failed: "p" must be a String'); + } + + if (this.Type(q) !== 'String') { + throw new TypeError('Assertion failed: "q" must be a String'); + } + + return isPrefixOf(p, q); + /* + if (p === q || p === '') { + return true; + } + + var pLength = p.length; + var qLength = q.length; + if (pLength >= qLength) { + return false; + } + + // assert: pLength < qLength + + for (var i = 0; i < pLength; i += 1) { + if ($charAt(p, i) !== $charAt(q, i)) { + return false; + } + } + return true; + */ + }, + + // https://www.ecma-international.org/ecma-262/9.0/#sec-tostring-applied-to-the-number-type + NumberToString: function NumberToString(m) { + if (this.Type(m) !== 'Number') { + throw new TypeError('Assertion failed: "m" must be a String'); + } + + return $String(m); + }, + + // https://www.ecma-international.org/ecma-262/9.0/#sec-copydataproperties + CopyDataProperties: function CopyDataProperties(target, source, excludedItems) { + if (this.Type(target) !== 'Object') { + throw new TypeError('Assertion failed: "target" must be an Object'); + } + + if (!this.IsArray(excludedItems)) { + throw new TypeError('Assertion failed: "excludedItems" must be a List of Property Keys'); + } + for (var i = 0; i < excludedItems.length; i += 1) { + if (!this.IsPropertyKey(excludedItems[i])) { + throw new TypeError('Assertion failed: "excludedItems" must be a List of Property Keys'); + } + } + + if (typeof source === 'undefined' || source === null) { + return target; + } + + var ES = this; + + var fromObj = ES.ToObject(source); + + var sourceKeys = OwnPropertyKeys(ES, fromObj); + forEach(sourceKeys, function (nextKey) { + var excluded = false; + + forEach(excludedItems, function (e) { + if (ES.SameValue(e, nextKey) === true) { + excluded = true; + } + }); + + var enumerable = $isEnumerable(fromObj, nextKey) || ( + // this is to handle string keys being non-enumerable in older engines + typeof source === 'string' + && nextKey >= 0 + && ES.IsInteger(ES.ToNumber(nextKey)) + ); + if (excluded === false && enumerable) { + var propValue = ES.Get(fromObj, nextKey); + ES.CreateDataProperty(target, nextKey, propValue); + } + }); + + return target; + }, + + // https://ecma-international.org/ecma-262/9.0/#sec-promise-resolve + PromiseResolve: function PromiseResolve(C, x) { + if (!$PromiseResolve) { + throw new SyntaxError('This environment does not support Promises.'); + } + return $PromiseResolve(C, x); + }, + + // http://www.ecma-international.org/ecma-262/9.0/#sec-getsubstitution + // eslint-disable-next-line max-statements, max-params, max-lines-per-function + GetSubstitution: function GetSubstitution(matched, str, position, captures, namedCaptures, replacement) { + if (this.Type(matched) !== 'String') { + throw new $TypeError('Assertion failed: `matched` must be a String'); + } + var matchLength = matched.length; + + if (this.Type(str) !== 'String') { + throw new $TypeError('Assertion failed: `str` must be a String'); + } + var stringLength = str.length; + + if (!this.IsInteger(position) || position < 0 || position > stringLength) { + throw new $TypeError('Assertion failed: `position` must be a nonnegative integer, and less than or equal to the length of `string`, got ' + inspect(position)); + } + + var ES = this; + var isStringOrHole = function (capture, index, arr) { return ES.Type(capture) === 'String' || !(index in arr); }; + if (!this.IsArray(captures) || !every(captures, isStringOrHole)) { + throw new $TypeError('Assertion failed: `captures` must be a List of Strings, got ' + inspect(captures)); + } + + if (this.Type(replacement) !== 'String') { + throw new $TypeError('Assertion failed: `replacement` must be a String'); + } + + var tailPos = position + matchLength; + var m = captures.length; + if (this.Type(namedCaptures) !== 'Undefined') { + namedCaptures = this.ToObject(namedCaptures); // eslint-disable-line no-param-reassign + } + + var result = ''; + for (var i = 0; i < replacement.length; i += 1) { + // if this is a $, and it's not the end of the replacement + var current = replacement[i]; + var isLast = (i + 1) >= replacement.length; + var nextIsLast = (i + 2) >= replacement.length; + if (current === '$' && !isLast) { + var next = replacement[i + 1]; + if (next === '$') { + result += '$'; + i += 1; + } else if (next === '&') { + result += matched; + i += 1; + } else if (next === '`') { + result += position === 0 ? '' : $strSlice(str, 0, position - 1); + i += 1; + } else if (next === "'") { + result += tailPos >= stringLength ? '' : $strSlice(str, tailPos); + i += 1; + } else { + var nextNext = nextIsLast ? null : replacement[i + 2]; + if (isDigit(next) && next !== '0' && (nextIsLast || !isDigit(nextNext))) { + // $1 through $9, and not followed by a digit + var n = $parseInt(next, 10); + // if (n > m, impl-defined) + result += (n <= m && this.Type(captures[n - 1]) === 'Undefined') ? '' : captures[n - 1]; + i += 1; + } else if (isDigit(next) && (nextIsLast || isDigit(nextNext))) { + // $00 through $99 + var nn = next + nextNext; + var nnI = $parseInt(nn, 10) - 1; + // if nn === '00' or nn > m, impl-defined + result += (nn <= m && this.Type(captures[nnI]) === 'Undefined') ? '' : captures[nnI]; + i += 2; + } else if (next === '<') { + // eslint-disable-next-line max-depth + if (this.Type(namedCaptures) === 'Undefined') { + result += '$<'; + i += 2; + } else { + var endIndex = $indexOf(replacement, '>', i); + // eslint-disable-next-line max-depth + if (endIndex > -1) { + var groupName = $strSlice(replacement, i, endIndex); + var capture = this.Get(namedCaptures, groupName); + // eslint-disable-next-line max-depth + if (this.Type(capture) !== 'Undefined') { + result += this.ToString(capture); + } + i += '$<' + groupName + '>'.length; + } + } + } else { + result += '$'; + } + } + } else { + // the final $, or else not a $ + result += replacement[i]; + } + } + return result; + }, + + // https://www.ecma-international.org/ecma-262/9.0/#sec-datestring + DateString: function DateString(tv) { + if (this.Type(tv) !== 'Number' || $isNaN(tv)) { + throw new $TypeError('Assertion failed: `tv` must be a non-NaN Number'); + } + var weekday = weekdays[this.WeekDay(tv)]; + var month = months[this.MonthFromTime(tv)]; + var day = padTimeComponent(this.DateFromTime(tv)); + var year = padTimeComponent(this.YearFromTime(tv), 4); + return weekday + '\x20' + month + '\x20' + day + '\x20' + year; + }, + + // https://www.ecma-international.org/ecma-262/9.0/#sec-timestring + TimeString: function TimeString(tv) { + if (this.Type(tv) !== 'Number' || $isNaN(tv)) { + throw new $TypeError('Assertion failed: `tv` must be a non-NaN Number'); + } + var hour = this.HourFromTime(tv); + var minute = this.MinFromTime(tv); + var second = this.SecFromTime(tv); + return padTimeComponent(hour) + ':' + padTimeComponent(minute) + ':' + padTimeComponent(second) + '\x20GMT'; + } +}); + +delete ES2018.EnumerableOwnProperties; // replaced with EnumerableOwnPropertyNames + +delete ES2018.IsPropertyDescriptor; // not an actual abstract operation + +module.exports = ES2018; diff --git a/scripts/2.5/node_modules/es-abstract/es2019.js b/scripts/2.5/node_modules/es-abstract/es2019.js new file mode 100644 index 00000000..937c06c2 --- /dev/null +++ b/scripts/2.5/node_modules/es-abstract/es2019.js @@ -0,0 +1,111 @@ +'use strict'; + +var trimStart = require('string.prototype.trimleft'); +var trimEnd = require('string.prototype.trimright'); +var inspect = require('object-inspect'); + +var ES2018 = require('./es2018'); +var assign = require('./helpers/assign'); +var MAX_SAFE_INTEGER = require('./helpers/maxSafeInteger'); + +var GetIntrinsic = require('./GetIntrinsic'); + +var $TypeError = GetIntrinsic('%TypeError%'); + +var ES2019 = assign(assign({}, ES2018), { + // https://tc39.es/ecma262/#sec-add-entries-from-iterable + AddEntriesFromIterable: function AddEntriesFromIterable(target, iterable, adder) { + if (!this.IsCallable(adder)) { + throw new $TypeError('Assertion failed: `adder` is not callable'); + } + if (iterable == null) { + throw new $TypeError('Assertion failed: `iterable` is present, and not nullish'); + } + var iteratorRecord = this.GetIterator(iterable); + while (true) { // eslint-disable-line no-constant-condition + var next = this.IteratorStep(iteratorRecord); + if (!next) { + return target; + } + var nextItem = this.IteratorValue(next); + if (this.Type(nextItem) !== 'Object') { + var error = new $TypeError('iterator next must return an Object, got ' + inspect(nextItem)); + return this.IteratorClose( + iteratorRecord, + function () { throw error; } // eslint-disable-line no-loop-func + ); + } + try { + var k = this.Get(nextItem, '0'); + var v = this.Get(nextItem, '1'); + this.Call(adder, target, [k, v]); + } catch (e) { + return this.IteratorClose( + iteratorRecord, + function () { throw e; } // eslint-disable-line no-loop-func + ); + } + } + }, + + // https://ecma-international.org/ecma-262/10.0/#sec-flattenintoarray + // eslint-disable-next-line max-params, max-statements + FlattenIntoArray: function FlattenIntoArray(target, source, sourceLen, start, depth) { + var mapperFunction; + if (arguments.length > 5) { + mapperFunction = arguments[5]; + } + + var targetIndex = start; + var sourceIndex = 0; + while (sourceIndex < sourceLen) { + var P = this.ToString(sourceIndex); + var exists = this.HasProperty(source, P); + if (exists === true) { + var element = this.Get(source, P); + if (typeof mapperFunction !== 'undefined') { + if (arguments.length <= 6) { + throw new $TypeError('Assertion failed: thisArg is required when mapperFunction is provided'); + } + element = this.Call(mapperFunction, arguments[6], [element, sourceIndex, source]); + } + var shouldFlatten = false; + if (depth > 0) { + shouldFlatten = this.IsArray(element); + } + if (shouldFlatten) { + var elementLen = this.ToLength(this.Get(element, 'length')); + targetIndex = this.FlattenIntoArray(target, element, elementLen, targetIndex, depth - 1); + } else { + if (targetIndex >= MAX_SAFE_INTEGER) { + throw new $TypeError('index too large'); + } + this.CreateDataPropertyOrThrow(target, this.ToString(targetIndex), element); + targetIndex += 1; + } + } + sourceIndex += 1; + } + + return targetIndex; + }, + + // https://ecma-international.org/ecma-262/10.0/#sec-trimstring + TrimString: function TrimString(string, where) { + var str = this.RequireObjectCoercible(string); + var S = this.ToString(str); + var T; + if (where === 'start') { + T = trimStart(S); + } else if (where === 'end') { + T = trimEnd(S); + } else if (where === 'start+end') { + T = trimStart(trimEnd(S)); + } else { + throw new $TypeError('Assertion failed: invalid `where` value; must be "start", "end", or "start+end"'); + } + return T; + } +}); + +module.exports = ES2019; diff --git a/scripts/2.5/node_modules/es-abstract/es5.js b/scripts/2.5/node_modules/es-abstract/es5.js new file mode 100644 index 00000000..9a97ba39 --- /dev/null +++ b/scripts/2.5/node_modules/es-abstract/es5.js @@ -0,0 +1,544 @@ +'use strict'; + +var GetIntrinsic = require('./GetIntrinsic'); + +var $Object = GetIntrinsic('%Object%'); +var $EvalError = GetIntrinsic('%EvalError%'); +var $TypeError = GetIntrinsic('%TypeError%'); +var $String = GetIntrinsic('%String%'); +var $Date = GetIntrinsic('%Date%'); +var $Number = GetIntrinsic('%Number%'); +var $floor = GetIntrinsic('%Math.floor%'); +var $DateUTC = GetIntrinsic('%Date.UTC%'); +var $abs = GetIntrinsic('%Math.abs%'); + +var assertRecord = require('./helpers/assertRecord'); +var isPropertyDescriptor = require('./helpers/isPropertyDescriptor'); +var $isNaN = require('./helpers/isNaN'); +var $isFinite = require('./helpers/isFinite'); +var sign = require('./helpers/sign'); +var mod = require('./helpers/mod'); +var isPrefixOf = require('./helpers/isPrefixOf'); +var callBound = require('./helpers/callBound'); + +var IsCallable = require('is-callable'); +var toPrimitive = require('es-to-primitive/es5'); + +var has = require('has'); + +var $getUTCFullYear = callBound('Date.prototype.getUTCFullYear'); + +var HoursPerDay = 24; +var MinutesPerHour = 60; +var SecondsPerMinute = 60; +var msPerSecond = 1e3; +var msPerMinute = msPerSecond * SecondsPerMinute; +var msPerHour = msPerMinute * MinutesPerHour; +var msPerDay = 86400000; + +// https://es5.github.io/#x9 +var ES5 = { + ToPrimitive: toPrimitive, + + ToBoolean: function ToBoolean(value) { + return !!value; + }, + ToNumber: function ToNumber(value) { + return +value; // eslint-disable-line no-implicit-coercion + }, + ToInteger: function ToInteger(value) { + var number = this.ToNumber(value); + if ($isNaN(number)) { return 0; } + if (number === 0 || !$isFinite(number)) { return number; } + return sign(number) * Math.floor(Math.abs(number)); + }, + ToInt32: function ToInt32(x) { + return this.ToNumber(x) >> 0; + }, + ToUint32: function ToUint32(x) { + return this.ToNumber(x) >>> 0; + }, + ToUint16: function ToUint16(value) { + var number = this.ToNumber(value); + if ($isNaN(number) || number === 0 || !$isFinite(number)) { return 0; } + var posInt = sign(number) * Math.floor(Math.abs(number)); + return mod(posInt, 0x10000); + }, + ToString: function ToString(value) { + return $String(value); + }, + ToObject: function ToObject(value) { + this.CheckObjectCoercible(value); + return $Object(value); + }, + CheckObjectCoercible: function CheckObjectCoercible(value, optMessage) { + /* jshint eqnull:true */ + if (value == null) { + throw new $TypeError(optMessage || 'Cannot call method on ' + value); + } + return value; + }, + IsCallable: IsCallable, + SameValue: function SameValue(x, y) { + if (x === y) { // 0 === -0, but they are not identical. + if (x === 0) { return 1 / x === 1 / y; } + return true; + } + return $isNaN(x) && $isNaN(y); + }, + + // https://ecma-international.org/ecma-262/5.1/#sec-8 + Type: function Type(x) { + if (x === null) { + return 'Null'; + } + if (typeof x === 'undefined') { + return 'Undefined'; + } + if (typeof x === 'function' || typeof x === 'object') { + return 'Object'; + } + if (typeof x === 'number') { + return 'Number'; + } + if (typeof x === 'boolean') { + return 'Boolean'; + } + if (typeof x === 'string') { + return 'String'; + } + }, + + // https://ecma-international.org/ecma-262/6.0/#sec-property-descriptor-specification-type + IsPropertyDescriptor: function IsPropertyDescriptor(Desc) { + return isPropertyDescriptor(this, Desc); + }, + + // https://ecma-international.org/ecma-262/5.1/#sec-8.10.1 + IsAccessorDescriptor: function IsAccessorDescriptor(Desc) { + if (typeof Desc === 'undefined') { + return false; + } + + assertRecord(this, 'Property Descriptor', 'Desc', Desc); + + if (!has(Desc, '[[Get]]') && !has(Desc, '[[Set]]')) { + return false; + } + + return true; + }, + + // https://ecma-international.org/ecma-262/5.1/#sec-8.10.2 + IsDataDescriptor: function IsDataDescriptor(Desc) { + if (typeof Desc === 'undefined') { + return false; + } + + assertRecord(this, 'Property Descriptor', 'Desc', Desc); + + if (!has(Desc, '[[Value]]') && !has(Desc, '[[Writable]]')) { + return false; + } + + return true; + }, + + // https://ecma-international.org/ecma-262/5.1/#sec-8.10.3 + IsGenericDescriptor: function IsGenericDescriptor(Desc) { + if (typeof Desc === 'undefined') { + return false; + } + + assertRecord(this, 'Property Descriptor', 'Desc', Desc); + + if (!this.IsAccessorDescriptor(Desc) && !this.IsDataDescriptor(Desc)) { + return true; + } + + return false; + }, + + // https://ecma-international.org/ecma-262/5.1/#sec-8.10.4 + FromPropertyDescriptor: function FromPropertyDescriptor(Desc) { + if (typeof Desc === 'undefined') { + return Desc; + } + + assertRecord(this, 'Property Descriptor', 'Desc', Desc); + + if (this.IsDataDescriptor(Desc)) { + return { + value: Desc['[[Value]]'], + writable: !!Desc['[[Writable]]'], + enumerable: !!Desc['[[Enumerable]]'], + configurable: !!Desc['[[Configurable]]'] + }; + } else if (this.IsAccessorDescriptor(Desc)) { + return { + get: Desc['[[Get]]'], + set: Desc['[[Set]]'], + enumerable: !!Desc['[[Enumerable]]'], + configurable: !!Desc['[[Configurable]]'] + }; + } else { + throw new $TypeError('FromPropertyDescriptor must be called with a fully populated Property Descriptor'); + } + }, + + // https://ecma-international.org/ecma-262/5.1/#sec-8.10.5 + ToPropertyDescriptor: function ToPropertyDescriptor(Obj) { + if (this.Type(Obj) !== 'Object') { + throw new $TypeError('ToPropertyDescriptor requires an object'); + } + + var desc = {}; + if (has(Obj, 'enumerable')) { + desc['[[Enumerable]]'] = this.ToBoolean(Obj.enumerable); + } + if (has(Obj, 'configurable')) { + desc['[[Configurable]]'] = this.ToBoolean(Obj.configurable); + } + if (has(Obj, 'value')) { + desc['[[Value]]'] = Obj.value; + } + if (has(Obj, 'writable')) { + desc['[[Writable]]'] = this.ToBoolean(Obj.writable); + } + if (has(Obj, 'get')) { + var getter = Obj.get; + if (typeof getter !== 'undefined' && !this.IsCallable(getter)) { + throw new TypeError('getter must be a function'); + } + desc['[[Get]]'] = getter; + } + if (has(Obj, 'set')) { + var setter = Obj.set; + if (typeof setter !== 'undefined' && !this.IsCallable(setter)) { + throw new $TypeError('setter must be a function'); + } + desc['[[Set]]'] = setter; + } + + if ((has(desc, '[[Get]]') || has(desc, '[[Set]]')) && (has(desc, '[[Value]]') || has(desc, '[[Writable]]'))) { + throw new $TypeError('Invalid property descriptor. Cannot both specify accessors and a value or writable attribute'); + } + return desc; + }, + + // https://ecma-international.org/ecma-262/5.1/#sec-11.9.3 + 'Abstract Equality Comparison': function AbstractEqualityComparison(x, y) { + var xType = this.Type(x); + var yType = this.Type(y); + if (xType === yType) { + return x === y; // ES6+ specified this shortcut anyways. + } + if (x == null && y == null) { + return true; + } + if (xType === 'Number' && yType === 'String') { + return this['Abstract Equality Comparison'](x, this.ToNumber(y)); + } + if (xType === 'String' && yType === 'Number') { + return this['Abstract Equality Comparison'](this.ToNumber(x), y); + } + if (xType === 'Boolean') { + return this['Abstract Equality Comparison'](this.ToNumber(x), y); + } + if (yType === 'Boolean') { + return this['Abstract Equality Comparison'](x, this.ToNumber(y)); + } + if ((xType === 'String' || xType === 'Number') && yType === 'Object') { + return this['Abstract Equality Comparison'](x, this.ToPrimitive(y)); + } + if (xType === 'Object' && (yType === 'String' || yType === 'Number')) { + return this['Abstract Equality Comparison'](this.ToPrimitive(x), y); + } + return false; + }, + + // https://ecma-international.org/ecma-262/5.1/#sec-11.9.6 + 'Strict Equality Comparison': function StrictEqualityComparison(x, y) { + var xType = this.Type(x); + var yType = this.Type(y); + if (xType !== yType) { + return false; + } + if (xType === 'Undefined' || xType === 'Null') { + return true; + } + return x === y; // shortcut for steps 4-7 + }, + + // https://ecma-international.org/ecma-262/5.1/#sec-11.8.5 + // eslint-disable-next-line max-statements + 'Abstract Relational Comparison': function AbstractRelationalComparison(x, y, LeftFirst) { + if (this.Type(LeftFirst) !== 'Boolean') { + throw new $TypeError('Assertion failed: LeftFirst argument must be a Boolean'); + } + var px; + var py; + if (LeftFirst) { + px = this.ToPrimitive(x, $Number); + py = this.ToPrimitive(y, $Number); + } else { + py = this.ToPrimitive(y, $Number); + px = this.ToPrimitive(x, $Number); + } + var bothStrings = this.Type(px) === 'String' && this.Type(py) === 'String'; + if (!bothStrings) { + var nx = this.ToNumber(px); + var ny = this.ToNumber(py); + if ($isNaN(nx) || $isNaN(ny)) { + return undefined; + } + if ($isFinite(nx) && $isFinite(ny) && nx === ny) { + return false; + } + if (nx === 0 && ny === 0) { + return false; + } + if (nx === Infinity) { + return false; + } + if (ny === Infinity) { + return true; + } + if (ny === -Infinity) { + return false; + } + if (nx === -Infinity) { + return true; + } + return nx < ny; // by now, these are both nonzero, finite, and not equal + } + if (isPrefixOf(py, px)) { + return false; + } + if (isPrefixOf(px, py)) { + return true; + } + return px < py; // both strings, neither a prefix of the other. shortcut for steps c-f + }, + + // https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.10 + msFromTime: function msFromTime(t) { + return mod(t, msPerSecond); + }, + + // https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.10 + SecFromTime: function SecFromTime(t) { + return mod($floor(t / msPerSecond), SecondsPerMinute); + }, + + // https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.10 + MinFromTime: function MinFromTime(t) { + return mod($floor(t / msPerMinute), MinutesPerHour); + }, + + // https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.10 + HourFromTime: function HourFromTime(t) { + return mod($floor(t / msPerHour), HoursPerDay); + }, + + // https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.2 + Day: function Day(t) { + return $floor(t / msPerDay); + }, + + // https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.2 + TimeWithinDay: function TimeWithinDay(t) { + return mod(t, msPerDay); + }, + + // https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.3 + DayFromYear: function DayFromYear(y) { + return (365 * (y - 1970)) + $floor((y - 1969) / 4) - $floor((y - 1901) / 100) + $floor((y - 1601) / 400); + }, + + // https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.3 + TimeFromYear: function TimeFromYear(y) { + return msPerDay * this.DayFromYear(y); + }, + + // https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.3 + YearFromTime: function YearFromTime(t) { + // largest y such that this.TimeFromYear(y) <= t + return $getUTCFullYear(new $Date(t)); + }, + + // https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.6 + WeekDay: function WeekDay(t) { + return mod(this.Day(t) + 4, 7); + }, + + // https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.3 + DaysInYear: function DaysInYear(y) { + if (mod(y, 4) !== 0) { + return 365; + } + if (mod(y, 100) !== 0) { + return 366; + } + if (mod(y, 400) !== 0) { + return 365; + } + return 366; + }, + + // https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.3 + InLeapYear: function InLeapYear(t) { + var days = this.DaysInYear(this.YearFromTime(t)); + if (days === 365) { + return 0; + } + if (days === 366) { + return 1; + } + throw new $EvalError('Assertion failed: there are not 365 or 366 days in a year, got: ' + days); + }, + + // https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.4 + DayWithinYear: function DayWithinYear(t) { + return this.Day(t) - this.DayFromYear(this.YearFromTime(t)); + }, + + // https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.4 + MonthFromTime: function MonthFromTime(t) { + var day = this.DayWithinYear(t); + if (0 <= day && day < 31) { + return 0; + } + var leap = this.InLeapYear(t); + if (31 <= day && day < (59 + leap)) { + return 1; + } + if ((59 + leap) <= day && day < (90 + leap)) { + return 2; + } + if ((90 + leap) <= day && day < (120 + leap)) { + return 3; + } + if ((120 + leap) <= day && day < (151 + leap)) { + return 4; + } + if ((151 + leap) <= day && day < (181 + leap)) { + return 5; + } + if ((181 + leap) <= day && day < (212 + leap)) { + return 6; + } + if ((212 + leap) <= day && day < (243 + leap)) { + return 7; + } + if ((243 + leap) <= day && day < (273 + leap)) { + return 8; + } + if ((273 + leap) <= day && day < (304 + leap)) { + return 9; + } + if ((304 + leap) <= day && day < (334 + leap)) { + return 10; + } + if ((334 + leap) <= day && day < (365 + leap)) { + return 11; + } + }, + + // https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.5 + DateFromTime: function DateFromTime(t) { + var m = this.MonthFromTime(t); + var d = this.DayWithinYear(t); + if (m === 0) { + return d + 1; + } + if (m === 1) { + return d - 30; + } + var leap = this.InLeapYear(t); + if (m === 2) { + return d - 58 - leap; + } + if (m === 3) { + return d - 89 - leap; + } + if (m === 4) { + return d - 119 - leap; + } + if (m === 5) { + return d - 150 - leap; + } + if (m === 6) { + return d - 180 - leap; + } + if (m === 7) { + return d - 211 - leap; + } + if (m === 8) { + return d - 242 - leap; + } + if (m === 9) { + return d - 272 - leap; + } + if (m === 10) { + return d - 303 - leap; + } + if (m === 11) { + return d - 333 - leap; + } + throw new $EvalError('Assertion failed: MonthFromTime returned an impossible value: ' + m); + }, + + // https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.12 + MakeDay: function MakeDay(year, month, date) { + if (!$isFinite(year) || !$isFinite(month) || !$isFinite(date)) { + return NaN; + } + var y = this.ToInteger(year); + var m = this.ToInteger(month); + var dt = this.ToInteger(date); + var ym = y + $floor(m / 12); + var mn = mod(m, 12); + var t = $DateUTC(ym, mn, 1); + if (this.YearFromTime(t) !== ym || this.MonthFromTime(t) !== mn || this.DateFromTime(t) !== 1) { + return NaN; + } + return this.Day(t) + dt - 1; + }, + + // https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.13 + MakeDate: function MakeDate(day, time) { + if (!$isFinite(day) || !$isFinite(time)) { + return NaN; + } + return (day * msPerDay) + time; + }, + + // https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.11 + MakeTime: function MakeTime(hour, min, sec, ms) { + if (!$isFinite(hour) || !$isFinite(min) || !$isFinite(sec) || !$isFinite(ms)) { + return NaN; + } + var h = this.ToInteger(hour); + var m = this.ToInteger(min); + var s = this.ToInteger(sec); + var milli = this.ToInteger(ms); + var t = (h * msPerHour) + (m * msPerMinute) + (s * msPerSecond) + milli; + return t; + }, + + // https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.14 + TimeClip: function TimeClip(time) { + if (!$isFinite(time) || $abs(time) > 8.64e15) { + return NaN; + } + return $Number(new $Date(this.ToNumber(time))); + }, + + // https://ecma-international.org/ecma-262/5.1/#sec-5.2 + modulo: function modulo(x, y) { + return mod(x, y); + } +}; + +module.exports = ES5; diff --git a/scripts/2.5/node_modules/es-abstract/es6.js b/scripts/2.5/node_modules/es-abstract/es6.js new file mode 100644 index 00000000..2d1f4dc9 --- /dev/null +++ b/scripts/2.5/node_modules/es-abstract/es6.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./es2015'); diff --git a/scripts/2.5/node_modules/es-abstract/es7.js b/scripts/2.5/node_modules/es-abstract/es7.js new file mode 100644 index 00000000..f2f15c0a --- /dev/null +++ b/scripts/2.5/node_modules/es-abstract/es7.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./es2016'); diff --git a/scripts/2.5/node_modules/es-abstract/helpers/assertRecord.js b/scripts/2.5/node_modules/es-abstract/helpers/assertRecord.js new file mode 100644 index 00000000..72df7716 --- /dev/null +++ b/scripts/2.5/node_modules/es-abstract/helpers/assertRecord.js @@ -0,0 +1,48 @@ +'use strict'; + +var GetIntrinsic = require('../GetIntrinsic'); + +var $TypeError = GetIntrinsic('%TypeError%'); +var $SyntaxError = GetIntrinsic('%SyntaxError%'); + +var has = require('has'); + +var predicates = { + // https://ecma-international.org/ecma-262/6.0/#sec-property-descriptor-specification-type + 'Property Descriptor': function isPropertyDescriptor(ES, Desc) { + if (ES.Type(Desc) !== 'Object') { + return false; + } + var allowed = { + '[[Configurable]]': true, + '[[Enumerable]]': true, + '[[Get]]': true, + '[[Set]]': true, + '[[Value]]': true, + '[[Writable]]': true + }; + + for (var key in Desc) { // eslint-disable-line + if (has(Desc, key) && !allowed[key]) { + return false; + } + } + + var isData = has(Desc, '[[Value]]'); + var IsAccessor = has(Desc, '[[Get]]') || has(Desc, '[[Set]]'); + if (isData && IsAccessor) { + throw new $TypeError('Property Descriptors may not be both accessor and data descriptors'); + } + return true; + } +}; + +module.exports = function assertRecord(ES, recordType, argumentName, value) { + var predicate = predicates[recordType]; + if (typeof predicate !== 'function') { + throw new $SyntaxError('unknown record type: ' + recordType); + } + if (!predicate(ES, value)) { + throw new $TypeError(argumentName + ' must be a ' + recordType); + } +}; diff --git a/scripts/2.5/node_modules/es-abstract/helpers/assign.js b/scripts/2.5/node_modules/es-abstract/helpers/assign.js new file mode 100644 index 00000000..420bebb8 --- /dev/null +++ b/scripts/2.5/node_modules/es-abstract/helpers/assign.js @@ -0,0 +1,21 @@ +'use strict'; + +var GetIntrinsic = require('../GetIntrinsic'); + +var has = require('has'); + +var $assign = GetIntrinsic('%Object%').assign; + +module.exports = function assign(target, source) { + if ($assign) { + return $assign(target, source); + } + + // eslint-disable-next-line no-restricted-syntax + for (var key in source) { + if (has(source, key)) { + target[key] = source[key]; + } + } + return target; +}; diff --git a/scripts/2.5/node_modules/es-abstract/helpers/callBind.js b/scripts/2.5/node_modules/es-abstract/helpers/callBind.js new file mode 100644 index 00000000..dd206abe --- /dev/null +++ b/scripts/2.5/node_modules/es-abstract/helpers/callBind.js @@ -0,0 +1,17 @@ +'use strict'; + +var bind = require('function-bind'); + +var GetIntrinsic = require('../GetIntrinsic'); + +var $Function = GetIntrinsic('%Function%'); +var $apply = $Function.apply; +var $call = $Function.call; + +module.exports = function callBind() { + return bind.apply($call, arguments); +}; + +module.exports.apply = function applyBind() { + return bind.apply($apply, arguments); +}; diff --git a/scripts/2.5/node_modules/es-abstract/helpers/callBound.js b/scripts/2.5/node_modules/es-abstract/helpers/callBound.js new file mode 100644 index 00000000..9dc8fc51 --- /dev/null +++ b/scripts/2.5/node_modules/es-abstract/helpers/callBound.js @@ -0,0 +1,15 @@ +'use strict'; + +var GetIntrinsic = require('../GetIntrinsic'); + +var callBind = require('./callBind'); + +var $indexOf = callBind(GetIntrinsic('String.prototype.indexOf')); + +module.exports = function callBoundIntrinsic(name, allowMissing) { + var intrinsic = GetIntrinsic(name, !!allowMissing); + if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.')) { + return callBind(intrinsic); + } + return intrinsic; +}; diff --git a/scripts/2.5/node_modules/es-abstract/helpers/every.js b/scripts/2.5/node_modules/es-abstract/helpers/every.js new file mode 100644 index 00000000..42a45821 --- /dev/null +++ b/scripts/2.5/node_modules/es-abstract/helpers/every.js @@ -0,0 +1,10 @@ +'use strict'; + +module.exports = function every(array, predicate) { + for (var i = 0; i < array.length; i += 1) { + if (!predicate(array[i], i, array)) { + return false; + } + } + return true; +}; diff --git a/scripts/2.5/node_modules/es-abstract/helpers/forEach.js b/scripts/2.5/node_modules/es-abstract/helpers/forEach.js new file mode 100644 index 00000000..35915a65 --- /dev/null +++ b/scripts/2.5/node_modules/es-abstract/helpers/forEach.js @@ -0,0 +1,7 @@ +'use strict'; + +module.exports = function forEach(array, callback) { + for (var i = 0; i < array.length; i += 1) { + callback(array[i], i, array); // eslint-disable-line callback-return + } +}; diff --git a/scripts/2.5/node_modules/es-abstract/helpers/getInferredName.js b/scripts/2.5/node_modules/es-abstract/helpers/getInferredName.js new file mode 100644 index 00000000..2dab6e77 --- /dev/null +++ b/scripts/2.5/node_modules/es-abstract/helpers/getInferredName.js @@ -0,0 +1,10 @@ +'use strict'; + +var getInferredName; +try { + // eslint-disable-next-line no-new-func + getInferredName = Function('s', 'return { [s]() {} }[s].name;'); +} catch (e) {} + +var inferred = function () {}; +module.exports = getInferredName && inferred.name === 'inferred' ? getInferredName : null; diff --git a/scripts/2.5/node_modules/es-abstract/helpers/getIteratorMethod.js b/scripts/2.5/node_modules/es-abstract/helpers/getIteratorMethod.js new file mode 100644 index 00000000..d1f8596e --- /dev/null +++ b/scripts/2.5/node_modules/es-abstract/helpers/getIteratorMethod.js @@ -0,0 +1,46 @@ +'use strict'; + +var hasSymbols = require('has-symbols')(); +var GetIntrinsic = require('../GetIntrinsic'); +var callBound = require('./callBound'); + +var $iterator = GetIntrinsic('%Symbol.iterator%', true); +var $arraySlice = callBound('Array.prototype.slice'); +var $arrayJoin = callBound('Array.prototype.join'); + +module.exports = function getIteratorMethod(ES, iterable) { + var usingIterator; + if (hasSymbols) { + usingIterator = ES.GetMethod(iterable, $iterator); + } else if (ES.IsArray(iterable)) { + usingIterator = function () { + var i = -1; + var arr = this; // eslint-disable-line no-invalid-this + return { + next: function () { + i += 1; + return { + done: i >= arr.length, + value: arr[i] + }; + } + }; + }; + } else if (ES.Type(iterable) === 'String') { + usingIterator = function () { + var i = 0; + return { + next: function () { + var nextIndex = ES.AdvanceStringIndex(iterable, i, true); + var value = $arrayJoin($arraySlice(iterable, i, nextIndex), ''); + i = nextIndex; + return { + done: nextIndex > iterable.length, + value: value + }; + } + }; + }; + } + return usingIterator; +}; diff --git a/scripts/2.5/node_modules/es-abstract/helpers/getProto.js b/scripts/2.5/node_modules/es-abstract/helpers/getProto.js new file mode 100644 index 00000000..af10fd8a --- /dev/null +++ b/scripts/2.5/node_modules/es-abstract/helpers/getProto.js @@ -0,0 +1,15 @@ +'use strict'; + +var GetIntrinsic = require('../GetIntrinsic'); + +var originalGetProto = GetIntrinsic('%Object.getPrototypeOf%', true); +var $ArrayProto = GetIntrinsic('%Array.prototype%'); + +module.exports = originalGetProto || ( + // eslint-disable-next-line no-proto + [].__proto__ === $ArrayProto + ? function (O) { + return O.__proto__; // eslint-disable-line no-proto + } + : null +); diff --git a/scripts/2.5/node_modules/es-abstract/helpers/getSymbolDescription.js b/scripts/2.5/node_modules/es-abstract/helpers/getSymbolDescription.js new file mode 100644 index 00000000..dff8fccb --- /dev/null +++ b/scripts/2.5/node_modules/es-abstract/helpers/getSymbolDescription.js @@ -0,0 +1,30 @@ +'use strict'; + +var GetIntrinsic = require('../GetIntrinsic'); + +var callBound = require('./callBound'); + +var $SyntaxError = GetIntrinsic('%SyntaxError%'); +var symToStr = callBound('Symbol.prototype.toString', true); + +var getInferredName = require('./getInferredName'); + +module.exports = function getSymbolDescription(symbol) { + if (!symToStr) { + throw new $SyntaxError('Symbols are not supported in this environment'); + } + var str = symToStr(symbol); // will throw if not a symbol + + if (getInferredName) { + var name = getInferredName(symbol); + if (name === '') { return; } + // eslint-disable-next-line consistent-return + return name.slice(1, -1); // name.slice('['.length, -']'.length); + } + + var desc = str.slice(7, -1); // str.slice('Symbol('.length, -')'.length); + if (desc) { + // eslint-disable-next-line consistent-return + return desc; + } +}; diff --git a/scripts/2.5/node_modules/es-abstract/helpers/isFinite.js b/scripts/2.5/node_modules/es-abstract/helpers/isFinite.js new file mode 100644 index 00000000..9e7cd4f8 --- /dev/null +++ b/scripts/2.5/node_modules/es-abstract/helpers/isFinite.js @@ -0,0 +1,5 @@ +'use strict'; + +var $isNaN = Number.isNaN || function (a) { return a !== a; }; + +module.exports = Number.isFinite || function (x) { return typeof x === 'number' && !$isNaN(x) && x !== Infinity && x !== -Infinity; }; diff --git a/scripts/2.5/node_modules/es-abstract/helpers/isNaN.js b/scripts/2.5/node_modules/es-abstract/helpers/isNaN.js new file mode 100644 index 00000000..cb8631dc --- /dev/null +++ b/scripts/2.5/node_modules/es-abstract/helpers/isNaN.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = Number.isNaN || function isNaN(a) { + return a !== a; +}; diff --git a/scripts/2.5/node_modules/es-abstract/helpers/isPrefixOf.js b/scripts/2.5/node_modules/es-abstract/helpers/isPrefixOf.js new file mode 100644 index 00000000..b67d6405 --- /dev/null +++ b/scripts/2.5/node_modules/es-abstract/helpers/isPrefixOf.js @@ -0,0 +1,13 @@ +'use strict'; + +var $strSlice = require('../helpers/callBound')('String.prototype.slice'); + +module.exports = function isPrefixOf(prefix, string) { + if (prefix === string) { + return true; + } + if (prefix.length > string.length) { + return false; + } + return $strSlice(string, 0, prefix.length) === prefix; +}; diff --git a/scripts/2.5/node_modules/es-abstract/helpers/isPrimitive.js b/scripts/2.5/node_modules/es-abstract/helpers/isPrimitive.js new file mode 100644 index 00000000..06f0bf04 --- /dev/null +++ b/scripts/2.5/node_modules/es-abstract/helpers/isPrimitive.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = function isPrimitive(value) { + return value === null || (typeof value !== 'function' && typeof value !== 'object'); +}; diff --git a/scripts/2.5/node_modules/es-abstract/helpers/isPropertyDescriptor.js b/scripts/2.5/node_modules/es-abstract/helpers/isPropertyDescriptor.js new file mode 100644 index 00000000..23e89952 --- /dev/null +++ b/scripts/2.5/node_modules/es-abstract/helpers/isPropertyDescriptor.js @@ -0,0 +1,31 @@ +'use strict'; + +var GetIntrinsic = require('../GetIntrinsic'); + +var has = require('has'); +var $TypeError = GetIntrinsic('%TypeError%'); + +module.exports = function IsPropertyDescriptor(ES, Desc) { + if (ES.Type(Desc) !== 'Object') { + return false; + } + var allowed = { + '[[Configurable]]': true, + '[[Enumerable]]': true, + '[[Get]]': true, + '[[Set]]': true, + '[[Value]]': true, + '[[Writable]]': true + }; + + for (var key in Desc) { // eslint-disable-line + if (has(Desc, key) && !allowed[key]) { + return false; + } + } + + if (ES.IsDataDescriptor(Desc) && ES.IsAccessorDescriptor(Desc)) { + throw new $TypeError('Property Descriptors may not be both accessor and data descriptors'); + } + return true; +}; diff --git a/scripts/2.5/node_modules/es-abstract/helpers/isSamePropertyDescriptor.js b/scripts/2.5/node_modules/es-abstract/helpers/isSamePropertyDescriptor.js new file mode 100644 index 00000000..a6162a1d --- /dev/null +++ b/scripts/2.5/node_modules/es-abstract/helpers/isSamePropertyDescriptor.js @@ -0,0 +1,20 @@ +'use strict'; + +var every = require('./every'); + +module.exports = function isSamePropertyDescriptor(ES, D1, D2) { + var fields = [ + '[[Configurable]]', + '[[Enumerable]]', + '[[Get]]', + '[[Set]]', + '[[Value]]', + '[[Writable]]' + ]; + return every(fields, function (field) { + if ((field in D1) !== (field in D2)) { + return false; + } + return ES.SameValue(D1[field], D2[field]); + }); +}; diff --git a/scripts/2.5/node_modules/es-abstract/helpers/maxSafeInteger.js b/scripts/2.5/node_modules/es-abstract/helpers/maxSafeInteger.js new file mode 100644 index 00000000..2fe8f38e --- /dev/null +++ b/scripts/2.5/node_modules/es-abstract/helpers/maxSafeInteger.js @@ -0,0 +1,8 @@ +'use strict'; + +var GetIntrinsic = require('../GetIntrinsic'); + +var $Math = GetIntrinsic('%Math%'); +var $Number = GetIntrinsic('%Number%'); + +module.exports = $Number.MAX_SAFE_INTEGER || $Math.pow(2, 53) - 1; diff --git a/scripts/2.5/node_modules/es-abstract/helpers/mod.js b/scripts/2.5/node_modules/es-abstract/helpers/mod.js new file mode 100644 index 00000000..70f0eead --- /dev/null +++ b/scripts/2.5/node_modules/es-abstract/helpers/mod.js @@ -0,0 +1,6 @@ +'use strict'; + +module.exports = function mod(number, modulo) { + var remain = number % modulo; + return Math.floor(remain >= 0 ? remain : remain + modulo); +}; diff --git a/scripts/2.5/node_modules/es-abstract/helpers/regexTester.js b/scripts/2.5/node_modules/es-abstract/helpers/regexTester.js new file mode 100644 index 00000000..982cc9f7 --- /dev/null +++ b/scripts/2.5/node_modules/es-abstract/helpers/regexTester.js @@ -0,0 +1,11 @@ +'use strict'; + +var GetIntrinsic = require('../GetIntrinsic'); + +var $test = GetIntrinsic('RegExp.prototype.test'); + +var callBind = require('./callBind'); + +module.exports = function regexTester(regex) { + return callBind($test, regex); +}; diff --git a/scripts/2.5/node_modules/es-abstract/helpers/setProto.js b/scripts/2.5/node_modules/es-abstract/helpers/setProto.js new file mode 100644 index 00000000..4c234746 --- /dev/null +++ b/scripts/2.5/node_modules/es-abstract/helpers/setProto.js @@ -0,0 +1,16 @@ +'use strict'; + +var GetIntrinsic = require('../GetIntrinsic'); + +var originalSetProto = GetIntrinsic('%Object.setPrototypeOf%', true); +var $ArrayProto = GetIntrinsic('%Array.prototype%'); + +module.exports = originalSetProto || ( + // eslint-disable-next-line no-proto, no-negated-condition + [].__proto__ !== $ArrayProto + ? null + : function (O, proto) { + O.__proto__ = proto; // eslint-disable-line no-proto + return O; + } +); diff --git a/scripts/2.5/node_modules/es-abstract/helpers/sign.js b/scripts/2.5/node_modules/es-abstract/helpers/sign.js new file mode 100644 index 00000000..598ea7d8 --- /dev/null +++ b/scripts/2.5/node_modules/es-abstract/helpers/sign.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = function sign(number) { + return number >= 0 ? 1 : -1; +}; diff --git a/scripts/2.5/node_modules/es-abstract/index.js b/scripts/2.5/node_modules/es-abstract/index.js new file mode 100644 index 00000000..7cef0395 --- /dev/null +++ b/scripts/2.5/node_modules/es-abstract/index.js @@ -0,0 +1,26 @@ +'use strict'; + +var assign = require('./helpers/assign'); + +var ES5 = require('./es5'); +var ES2015 = require('./es2015'); +var ES2016 = require('./es2016'); +var ES2017 = require('./es2017'); +var ES2018 = require('./es2018'); +var ES2019 = require('./es2019'); + +var ES = { + ES5: ES5, + ES6: ES2015, + ES2015: ES2015, + ES7: ES2016, + ES2016: ES2016, + ES2017: ES2017, + ES2018: ES2018, + ES2019: ES2019 +}; +assign(ES, ES5); +delete ES.CheckObjectCoercible; // renamed in ES6 to RequireObjectCoercible +assign(ES, ES2015); + +module.exports = ES; diff --git a/scripts/2.5/node_modules/es-abstract/operations/.eslintrc b/scripts/2.5/node_modules/es-abstract/operations/.eslintrc new file mode 100644 index 00000000..bcd76f76 --- /dev/null +++ b/scripts/2.5/node_modules/es-abstract/operations/.eslintrc @@ -0,0 +1,5 @@ +{ + "rules": { + "id-length": 0, + }, +} diff --git a/scripts/2.5/node_modules/es-abstract/package.json b/scripts/2.5/node_modules/es-abstract/package.json new file mode 100644 index 00000000..3c668e4e --- /dev/null +++ b/scripts/2.5/node_modules/es-abstract/package.json @@ -0,0 +1,130 @@ +{ + "_from": "es-abstract@^1.12.0", + "_id": "es-abstract@1.16.0", + "_inBundle": false, + "_integrity": "sha512-xdQnfykZ9JMEiasTAJZJdMWCQ1Vm00NBw79/AWi7ELfZuuPCSOMDZbT9mkOfSctVtfhb+sAAzrm+j//GjjLHLg==", + "_location": "/es-abstract", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "es-abstract@^1.12.0", + "name": "es-abstract", + "escapedName": "es-abstract", + "rawSpec": "^1.12.0", + "saveSpec": null, + "fetchSpec": "^1.12.0" + }, + "_requiredBy": [ + "/object.entries" + ], + "_resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.16.0.tgz", + "_shasum": "d3a26dc9c3283ac9750dca569586e976d9dcc06d", + "_spec": "es-abstract@^1.12.0", + "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/2.5/node_modules/object.entries", + "author": { + "name": "Jordan Harband", + "email": "ljharb@gmail.com", + "url": "http://ljharb.codes" + }, + "bugs": { + "url": "https://github.com/ljharb/es-abstract/issues" + }, + "bundleDependencies": false, + "contributors": [ + { + "name": "Jordan Harband", + "email": "ljharb@gmail.com", + "url": "http://ljharb.codes" + } + ], + "dependencies": { + "es-to-primitive": "^1.2.0", + "function-bind": "^1.1.1", + "has": "^1.0.3", + "has-symbols": "^1.0.0", + "is-callable": "^1.1.4", + "is-regex": "^1.0.4", + "object-inspect": "^1.6.0", + "object-keys": "^1.1.1", + "string.prototype.trimleft": "^2.1.0", + "string.prototype.trimright": "^2.1.0" + }, + "deprecated": false, + "description": "ECMAScript spec abstract operations.", + "devDependencies": { + "@ljharb/eslint-config": "^14.1.0", + "cheerio": "^1.0.0-rc.3", + "diff": "^4.0.1", + "eclint": "^2.8.1", + "eslint": "^6.5.1", + "foreach": "^2.0.5", + "make-arrow-function": "^1.1.0", + "nyc": "^10.3.2", + "object-is": "^1.0.1", + "object.assign": "^4.1.0", + "object.fromentries": "^2.0.1", + "replace": "^1.1.1", + "safe-publish-latest": "^1.1.3", + "semver": "^6.3.0", + "tape": "^4.11.0" + }, + "engines": { + "node": ">= 0.4" + }, + "greenkeeper": { + "//": "nyc is ignored because it requires node 4+, and we support older than that", + "ignore": [ + "nyc" + ] + }, + "homepage": "https://github.com/ljharb/es-abstract#readme", + "keywords": [ + "ECMAScript", + "ES", + "abstract", + "operation", + "abstract operation", + "JavaScript", + "ES5", + "ES6", + "ES7" + ], + "license": "MIT", + "main": "index.js", + "name": "es-abstract", + "repository": { + "type": "git", + "url": "git://github.com/ljharb/es-abstract.git" + }, + "scripts": { + "coverage": "nyc npm run --silent tests-only >/dev/null", + "eccheck": "eclint check *.js **/*.js > /dev/null", + "lint": "eslint .", + "postcoverage": "nyc report", + "posttest": "npx aud --production", + "prepublish": "safe-publish-latest", + "pretest": "npm run --silent lint", + "test": "npm run tests-only", + "tests-only": "node test" + }, + "testling": { + "files": "test/index.js", + "browsers": [ + "iexplore/6.0..latest", + "firefox/3.0..6.0", + "firefox/15.0..latest", + "firefox/nightly", + "chrome/4.0..10.0", + "chrome/20.0..latest", + "chrome/canary", + "opera/10.0..latest", + "opera/next", + "safari/4.0..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2" + ] + }, + "version": "1.16.0" +} diff --git a/scripts/2.5/node_modules/es-abstract/test/.eslintrc b/scripts/2.5/node_modules/es-abstract/test/.eslintrc new file mode 100644 index 00000000..f33c7476 --- /dev/null +++ b/scripts/2.5/node_modules/es-abstract/test/.eslintrc @@ -0,0 +1,13 @@ +{ + "rules": { + "id-length": 0, + "max-lines": 0, + "max-lines-per-function": 0, + "max-statements-per-line": [2, { "max": 3 }], + "max-nested-callbacks": [2, 4], + "max-statements": 0, + "no-implicit-coercion": 1, + "no-invalid-this": 1, + "object-curly-newline": 0, + } +} diff --git a/scripts/2.5/node_modules/es-abstract/test/GetIntrinsic.js b/scripts/2.5/node_modules/es-abstract/test/GetIntrinsic.js new file mode 100644 index 00000000..2ec9ff8d --- /dev/null +++ b/scripts/2.5/node_modules/es-abstract/test/GetIntrinsic.js @@ -0,0 +1,48 @@ +'use strict'; + +var GetIntrinsic = require('../GetIntrinsic'); + +var test = require('tape'); +var forEach = require('foreach'); +var debug = require('object-inspect'); + +var v = require('./helpers/values'); + +test('export', function (t) { + t.equal(typeof GetIntrinsic, 'function', 'it is a function'); + t.equal(GetIntrinsic.length, 2, 'function has length of 2'); + + t.end(); +}); + +test('throws', function (t) { + t['throws']( + function () { GetIntrinsic('not an intrinsic'); }, + SyntaxError, + 'nonexistent intrinsic throws a syntax error' + ); + + forEach(v.nonBooleans, function (nonBoolean) { + t['throws']( + function () { GetIntrinsic('%', nonBoolean); }, + TypeError, + debug(nonBoolean) + ' is not a Boolean' + ); + }); + + t.end(); +}); + +test('base intrinsics', function (t) { + t.equal(GetIntrinsic('%Object%'), Object, '%Object% yields Object'); + t.equal(GetIntrinsic('%Array%'), Array, '%Array% yields Array'); + + t.end(); +}); + +test('dotted paths', function (t) { + t.equal(GetIntrinsic('%Object.prototype.toString%'), Object.prototype.toString, '%Object.prototype.toString% yields Object.prototype.toString'); + t.equal(GetIntrinsic('%Array.prototype.push%'), Array.prototype.push, '%Array.prototype.push% yields Array.prototype.push'); + + t.end(); +}); diff --git a/scripts/2.5/node_modules/es-abstract/test/diffOps.js b/scripts/2.5/node_modules/es-abstract/test/diffOps.js new file mode 100644 index 00000000..0fb2fc40 --- /dev/null +++ b/scripts/2.5/node_modules/es-abstract/test/diffOps.js @@ -0,0 +1,26 @@ +'use strict'; + +var keys = require('object-keys'); +var forEach = require('foreach'); + +module.exports = function diffOperations(actual, expected, expectedMissing) { + var actualKeys = keys(actual); + var expectedKeys = keys(expected); + + var extra = []; + var missing = []; + forEach(actualKeys, function (op) { + if (!(op in expected)) { + extra.push(op); + } else if (expectedMissing.indexOf(op) !== -1) { + extra.push(op); + } + }); + forEach(expectedKeys, function (op) { + if (typeof actual[op] !== 'function' && expectedMissing.indexOf(op) === -1) { + missing.push(op); + } + }); + + return { missing: missing, extra: extra }; +}; diff --git a/scripts/2.5/node_modules/es-abstract/test/es2015.js b/scripts/2.5/node_modules/es-abstract/test/es2015.js new file mode 100644 index 00000000..7922d9cc --- /dev/null +++ b/scripts/2.5/node_modules/es-abstract/test/es2015.js @@ -0,0 +1,9 @@ +'use strict'; + +var ES = require('../').ES2015; + +var ops = require('../operations/2015'); + +var expectedMissing = ['Construct', 'CreateArrayFromList', 'CreateListIterator', 'NormalCompletion', 'RegExpBuiltinExec']; + +require('./tests').es2015(ES, ops, expectedMissing); diff --git a/scripts/2.5/node_modules/es-abstract/test/es2016.js b/scripts/2.5/node_modules/es-abstract/test/es2016.js new file mode 100644 index 00000000..016d35f7 --- /dev/null +++ b/scripts/2.5/node_modules/es-abstract/test/es2016.js @@ -0,0 +1,9 @@ +'use strict'; + +var ES = require('../').ES2016; + +var ops = require('../operations/2016'); + +var expectedMissing = ['AddRestrictedFunctionProperties', 'AllocateArrayBuffer', 'AllocateTypedArray', 'AllocateTypedArrayBuffer', 'BlockDeclarationInstantiation', 'BoundFunctionCreate', 'Canonicalize', 'CharacterRange', 'CharacterRangeOrUnion', 'CharacterSetMatcher', 'CloneArrayBuffer', 'Completion', 'Construct', 'CopyDataBlockBytes', 'CreateArrayFromList', 'CreateArrayIterator', 'CreateBuiltinFunction', 'CreateByteDataBlock', 'CreateDynamicFunction', 'CreateIntrinsics', 'CreateListIterator', 'CreateMapIterator', 'CreateMappedArgumentsObject', 'CreatePerIterationEnvironment', 'CreateRealm', 'CreateResolvingFunctions', 'CreateSetIterator', 'CreateStringIterator', 'CreateUnmappedArgumentsObject', 'Decode', 'DetachArrayBuffer', 'Encode', 'EnqueueJob', 'EnumerateObjectProperties', 'EscapeRegExpPattern', 'EvalDeclarationInstantiation', 'EvaluateCall', 'EvaluateDirectCall', 'EvaluateNew', 'ForBodyEvaluation', 'ForIn/OfBodyEvaluation', 'ForIn/OfHeadEvaluation', 'FulfillPromise', 'FunctionAllocate', 'FunctionCreate', 'FunctionDeclarationInstantiation', 'FunctionInitialize', 'GeneratorFunctionCreate', 'GeneratorResume', 'GeneratorResumeAbrupt', 'GeneratorStart', 'GeneratorValidate', 'GeneratorYield', 'GetActiveScriptOrModule', 'GetFunctionRealm', 'GetGlobalObject', 'GetIdentifierReference', 'GetModuleNamespace', 'GetNewTarget', 'GetSuperConstructor', 'GetTemplateObject', 'GetThisEnvironment', 'GetThisValue', 'GetValue', 'GetValueFromBuffer', 'GetViewValue', 'GlobalDeclarationInstantiation', 'HostPromiseRejectionTracker', 'HostReportErrors', 'HostResolveImportedModule', 'IfAbruptRejectPromise', 'ImportedLocalNames', 'InitializeBoundName', 'InitializeHostDefinedRealm', 'InitializeReferencedBinding', 'IntegerIndexedElementGet', 'IntegerIndexedElementSet', 'IntegerIndexedObjectCreate', 'InternalizeJSONProperty', 'IsAnonymousFunctionDefinition', 'IsCompatiblePropertyDescriptor', 'IsDetachedBuffer', 'IsInTailPosition', 'IsLabelledFunction', 'IsWordChar', 'LocalTime', 'LoopContinues', 'MakeArgGetter', 'MakeArgSetter', 'MakeClassConstructor', 'MakeConstructor', 'MakeMethod', 'MakeSuperPropertyReference', 'ModuleNamespaceCreate', 'NewDeclarativeEnvironment', 'NewFunctionEnvironment', 'NewGlobalEnvironment', 'NewModuleEnvironment', 'NewObjectEnvironment', 'NewPromiseCapability', 'NextJob', 'NormalCompletion', 'ObjectDefineProperties', 'OrdinaryCallBindThis', 'OrdinaryCallEvaluateBody', 'OrdinaryCreateFromConstructor', 'OrdinaryDelete', 'OrdinaryGet', 'OrdinaryIsExtensible', 'OrdinaryOwnPropertyKeys', 'OrdinaryPreventExtensions', 'OrdinarySet', 'ParseModule', 'ParseScript', 'PerformEval', 'PerformPromiseAll', 'PerformPromiseRace', 'PerformPromiseThen', 'PrepareForOrdinaryCall', 'PrepareForTailCall', 'PromiseReactionJob', 'PromiseResolveThenableJob', 'ProxyCreate', 'PutValue', 'QuoteJSONString', 'RegExpAlloc', 'RegExpBuiltinExec', 'RegExpCreate', 'RegExpInitialize', 'RejectPromise', 'RepeatMatcher', 'ResolveBinding', 'ResolveThisBinding', 'ReturnIfAbrupt', 'ScriptEvaluation', 'ScriptEvaluationJob', 'SerializeJSONArray', 'SerializeJSONObject', 'SerializeJSONProperty', 'SetDefaultGlobalBindings', 'SetRealmGlobalObject', 'SetValueInBuffer', 'SetViewValue', 'SortCompare', 'SplitMatch', 'StringCreate', 'ToString Applied to the Number Type', 'TopLevelModuleEvaluationJob', 'TriggerPromiseReactions', 'TypedArrayCreate', 'TypedArraySpeciesCreate', 'UTC', 'UTF16Decode', 'UTF16Encoding', 'UpdateEmpty', 'ValidateTypedArray', 'abs', 'floor', 'max', 'min']; + +require('./tests').es2016(ES, ops, expectedMissing); diff --git a/scripts/2.5/node_modules/es-abstract/test/es2017.js b/scripts/2.5/node_modules/es-abstract/test/es2017.js new file mode 100644 index 00000000..c497679c --- /dev/null +++ b/scripts/2.5/node_modules/es-abstract/test/es2017.js @@ -0,0 +1,9 @@ +'use strict'; + +var ES = require('../').ES2017; + +var ops = require('../operations/2017'); + +var expectedMissing = ['AddRestrictedFunctionProperties', 'AddWaiter', 'AgentCanSuspend', 'AgentSignifier', 'AllocateArrayBuffer', 'AllocateSharedArrayBuffer', 'AllocateTypedArray', 'AllocateTypedArrayBuffer', 'AsyncFunctionAwait', 'AsyncFunctionCreate', 'AsyncFunctionStart', 'AtomicLoad', 'AtomicReadModifyWrite', 'BlockDeclarationInstantiation', 'BoundFunctionCreate', 'Canonicalize', 'CharacterRange', 'CharacterRangeOrUnion', 'CharacterSetMatcher', 'CloneArrayBuffer', 'Completion', 'ComposeWriteEventBytes', 'Construct', 'CopyDataBlockBytes', 'CreateArrayFromList', 'CreateArrayIterator', 'CreateBuiltinFunction', 'CreateByteDataBlock', 'CreateDynamicFunction', 'CreateIntrinsics', 'CreateListIterator', 'CreateMapIterator', 'CreateMappedArgumentsObject', 'CreatePerIterationEnvironment', 'CreateRealm', 'CreateResolvingFunctions', 'CreateSetIterator', 'CreateSharedByteDataBlock', 'CreateStringIterator', 'CreateUnmappedArgumentsObject', 'Decode', 'DetachArrayBuffer', 'Encode', 'EnqueueJob', 'EnterCriticalSection', 'EnumerateObjectProperties', 'EscapeRegExpPattern', 'EvalDeclarationInstantiation', 'EvaluateCall', 'EvaluateDirectCall', 'EvaluateNew', 'EventSet', 'ForBodyEvaluation', 'ForIn/OfBodyEvaluation', 'ForIn/OfHeadEvaluation', 'FulfillPromise', 'FunctionAllocate', 'FunctionCreate', 'FunctionDeclarationInstantiation', 'FunctionInitialize', 'GeneratorFunctionCreate', 'GeneratorResume', 'GeneratorResumeAbrupt', 'GeneratorStart', 'GeneratorValidate', 'GeneratorYield', 'GetActiveScriptOrModule', 'GetBase', 'GetFunctionRealm', 'GetGlobalObject', 'GetIdentifierReference', 'GetModifySetValueInBuffer', 'GetModuleNamespace', 'GetNewTarget', 'GetReferencedName', 'GetSuperConstructor', 'GetTemplateObject', 'GetThisEnvironment', 'GetThisValue', 'GetValue', 'GetValueFromBuffer', 'GetViewValue', 'GetWaiterList', 'GlobalDeclarationInstantiation', 'HasPrimitiveBase', 'HostEnsureCanCompileStrings', 'HostEventSet', 'HostPromiseRejectionTracker', 'HostReportErrors', 'HostResolveImportedModule', 'IfAbruptRejectPromise', 'ImportedLocalNames', 'InitializeBoundName', 'InitializeHostDefinedRealm', 'InitializeReferencedBinding', 'IntegerIndexedElementGet', 'IntegerIndexedElementSet', 'IntegerIndexedObjectCreate', 'InternalizeJSONProperty', 'IsAnonymousFunctionDefinition', 'IsCompatiblePropertyDescriptor', 'IsDetachedBuffer', 'IsInTailPosition', 'IsLabelledFunction', 'IsPropertyReference', 'IsSharedArrayBuffer', 'IsStrictReference', 'IsSuperReference', 'IsUnresolvableReference', 'IsWordChar', 'LeaveCriticalSection', 'LocalTime', 'LoopContinues', 'MakeArgGetter', 'MakeArgSetter', 'MakeClassConstructor', 'MakeConstructor', 'MakeMethod', 'MakeSuperPropertyReference', 'ModuleNamespaceCreate', 'NewDeclarativeEnvironment', 'NewFunctionEnvironment', 'NewGlobalEnvironment', 'NewModuleEnvironment', 'NewObjectEnvironment', 'NewPromiseCapability', 'NormalCompletion', 'NumberToRawBytes', 'ObjectDefineProperties', 'OrdinaryCallBindThis', 'OrdinaryCallEvaluateBody', 'OrdinaryCreateFromConstructor', 'OrdinaryDelete', 'OrdinaryGet', 'OrdinaryIsExtensible', 'OrdinaryOwnPropertyKeys', 'OrdinaryPreventExtensions', 'OrdinarySet', 'OrdinaryToPrimitive', 'ParseModule', 'ParseScript', 'PerformEval', 'PerformPromiseAll', 'PerformPromiseRace', 'PerformPromiseThen', 'PrepareForOrdinaryCall', 'PrepareForTailCall', 'PromiseReactionJob', 'PromiseResolveThenableJob', 'ProxyCreate', 'PutValue', 'QuoteJSONString', 'RawBytesToNumber', 'RegExpAlloc', 'RegExpBuiltinExec', 'RegExpCreate', 'RegExpInitialize', 'RejectPromise', 'RemoveWaiter', 'RemoveWaiters', 'RepeatMatcher', 'ResolveBinding', 'ResolveThisBinding', 'ReturnIfAbrupt', 'RunJobs', 'ScriptEvaluation', 'ScriptEvaluationJob', 'SerializeJSONArray', 'SerializeJSONObject', 'SerializeJSONProperty', 'SetDefaultGlobalBindings', 'SetImmutablePrototype', 'SetRealmGlobalObject', 'SetValueInBuffer', 'SetViewValue', 'SharedDataBlockEventSet', 'SortCompare', 'SplitMatch', 'StringCreate', 'StringGetOwnProperty', 'Suspend', 'ToString Applied to the Number Type', 'TopLevelModuleEvaluationJob', 'TriggerPromiseReactions', 'TypedArrayCreate', 'TypedArraySpeciesCreate', 'UTC', 'UTF16Decode', 'UTF16Encoding', 'UpdateEmpty', 'ValidateAtomicAccess', 'ValidateSharedIntegerTypedArray', 'ValidateTypedArray', 'ValueOfReadEvent', 'WakeWaiter', 'WordCharacters', 'abs', 'agent-order', 'floor', 'happens-before', 'host-synchronizes-with', 'max', 'memory-order', 'min', 'reads-bytes-from', 'reads-from', 'synchronizes-with']; + +require('./tests').es2017(ES, ops, expectedMissing); diff --git a/scripts/2.5/node_modules/es-abstract/test/es2018.js b/scripts/2.5/node_modules/es-abstract/test/es2018.js new file mode 100644 index 00000000..37c029a3 --- /dev/null +++ b/scripts/2.5/node_modules/es-abstract/test/es2018.js @@ -0,0 +1,9 @@ +'use strict'; + +var ES = require('../').ES2018; + +var ops = require('../operations/2018'); + +var expectedMissing = ['abs', 'AddRestrictedFunctionProperties', 'AddWaiter', 'agent-order', 'AgentCanSuspend', 'AgentSignifier', 'AllocateArrayBuffer', 'AllocateSharedArrayBuffer', 'AllocateTypedArray', 'AllocateTypedArrayBuffer', 'AsyncFunctionStart', 'AsyncGeneratorEnqueue', 'AsyncGeneratorReject', 'AsyncGeneratorResolve', 'AsyncGeneratorResumeNext', 'AsyncGeneratorStart', 'AsyncGeneratorYield', 'AtomicLoad', 'AtomicReadModifyWrite', 'Await', 'BlockDeclarationInstantiation', 'BoundFunctionCreate', 'Canonicalize', 'CaseClauseIsSelected', 'CharacterRange', 'CharacterRangeOrUnion', 'CharacterSetMatcher', 'CloneArrayBuffer', 'Completion', 'ComposeWriteEventBytes', 'CopyDataBlockBytes', 'CreateArrayIterator', 'CreateAsyncFromSyncIterator', 'CreateBuiltinFunction', 'CreateByteDataBlock', 'CreateDynamicFunction', 'CreateIntrinsics', 'CreateMapIterator', 'CreateMappedArgumentsObject', 'CreatePerIterationEnvironment', 'CreateRealm', 'CreateResolvingFunctions', 'CreateSetIterator', 'CreateSharedByteDataBlock', 'CreateStringIterator', 'CreateUnmappedArgumentsObject', 'Decode', 'DetachArrayBuffer', 'Encode', 'EnqueueJob', 'EnterCriticalSection', 'EnumerateObjectProperties', 'EscapeRegExpPattern', 'EvalDeclarationInstantiation', 'EvaluateCall', 'EvaluateNew', 'EventSet', 'floor', 'ForBodyEvaluation', 'ForIn/OfBodyEvaluation', 'ForIn/OfHeadEvaluation', 'FulfillPromise', 'FunctionAllocate', 'FunctionCreate', 'FunctionDeclarationInstantiation', 'FunctionInitialize', 'GeneratorFunctionCreate', 'GeneratorResume', 'GeneratorResumeAbrupt', 'GeneratorStart', 'GeneratorValidate', 'GeneratorYield', 'GetActiveScriptOrModule', 'GetBase', 'GetFunctionRealm', 'GetGeneratorKind', 'GetGlobalObject', 'GetIdentifierReference', 'GetModifySetValueInBuffer', 'GetModuleNamespace', 'GetNewTarget', 'GetReferencedName', 'GetSuperConstructor', 'GetTemplateObject', 'GetThisEnvironment', 'GetThisValue', 'GetValue', 'GetValueFromBuffer', 'GetViewValue', 'GetWaiterList', 'GlobalDeclarationInstantiation', 'happens-before', 'HasPrimitiveBase', 'host-synchronizes-with', 'HostEnsureCanCompileStrings', 'HostEventSet', 'HostPromiseRejectionTracker', 'HostReportErrors', 'HostResolveImportedModule', 'IfAbruptRejectPromise', 'ImportedLocalNames', 'InitializeBoundName', 'InitializeHostDefinedRealm', 'InitializeReferencedBinding', 'InnerModuleEvaluation', 'InnerModuleInstantiation', 'IntegerIndexedElementGet', 'IntegerIndexedElementSet', 'IntegerIndexedObjectCreate', 'InternalizeJSONProperty', 'IsAnonymousFunctionDefinition', 'IsCompatiblePropertyDescriptor', 'IsDetachedBuffer', 'IsInTailPosition', 'IsLabelledFunction', 'IsPropertyReference', 'IsSharedArrayBuffer', 'IsStrictReference', 'IsSuperReference', 'IsUnresolvableReference', 'IsWordChar', 'LeaveCriticalSection', 'LocalTime', 'LoopContinues', 'MakeArgGetter', 'MakeArgSetter', 'MakeClassConstructor', 'MakeConstructor', 'MakeMethod', 'MakeSuperPropertyReference', 'max', 'memory-order', 'min', 'ModuleDeclarationEnvironmentSetup', 'ModuleExecution', 'ModuleNamespaceCreate', 'NewDeclarativeEnvironment', 'NewFunctionEnvironment', 'NewGlobalEnvironment', 'NewModuleEnvironment', 'NewObjectEnvironment', 'NewPromiseCapability', 'NumberToRawBytes', 'ObjectDefineProperties', 'OrdinaryCallBindThis', 'OrdinaryCallEvaluateBody', 'OrdinaryCreateFromConstructor', 'OrdinaryDelete', 'OrdinaryGet', 'OrdinaryIsExtensible', 'OrdinaryOwnPropertyKeys', 'OrdinaryPreventExtensions', 'OrdinaryToPrimitive', 'ParseModule', 'ParseScript', 'PerformEval', 'PerformPromiseAll', 'PerformPromiseRace', 'PerformPromiseThen', 'PrepareForOrdinaryCall', 'PrepareForTailCall', 'PromiseReactionJob', 'PromiseResolveThenableJob', 'ProxyCreate', 'PutValue', 'QuoteJSONString', 'RawBytesToNumber', 'reads-bytes-from', 'reads-from', 'RegExpAlloc', 'RegExpCreate', 'RegExpInitialize', 'RejectPromise', 'RemoveWaiter', 'RemoveWaiters', 'RepeatMatcher', 'ResolveBinding', 'ResolveThisBinding', 'ReturnIfAbrupt', 'RunJobs', 'ScriptEvaluation', 'ScriptEvaluationJob', 'SerializeJSONArray', 'SerializeJSONObject', 'SerializeJSONProperty', 'SetDefaultGlobalBindings', 'SetImmutablePrototype', 'SetRealmGlobalObject', 'SetValueInBuffer', 'SetViewValue', 'SharedDataBlockEventSet', 'SortCompare', 'SplitMatch', 'StringCreate', 'StringGetOwnProperty', 'Suspend', 'synchronizes-with', 'TimeZoneString', 'TopLevelModuleEvaluationJob', 'TriggerPromiseReactions', 'TypedArrayCreate', 'TypedArraySpeciesCreate', 'UnicodeEscape', 'UpdateEmpty', 'UTC', 'UTF16Decode', 'UTF16Encoding', 'ValidateAtomicAccess', 'ValidateSharedIntegerTypedArray', 'ValidateTypedArray', 'ValueOfReadEvent', 'WakeWaiter', 'WordCharacters', 'AsyncFunctionCreate', 'AsyncGeneratorFunctionCreate', 'AsyncIteratorClose', 'BackreferenceMatcher', 'Construct', 'CreateArrayFromList', 'CreateListIteratorRecord', 'NormalCompletion', 'OrdinarySet', 'OrdinarySetWithOwnDescriptor', 'RegExpBuiltinExec', 'SetFunctionLength', 'ThrowCompletion', 'UnicodeMatchProperty', 'UnicodeMatchPropertyValue']; + +require('./tests').es2018(ES, ops, expectedMissing); diff --git a/scripts/2.5/node_modules/es-abstract/test/es2019.js b/scripts/2.5/node_modules/es-abstract/test/es2019.js new file mode 100644 index 00000000..94e00a39 --- /dev/null +++ b/scripts/2.5/node_modules/es-abstract/test/es2019.js @@ -0,0 +1,9 @@ +'use strict'; + +var ES = require('../').ES2019; + +var ops = require('../operations/2019'); + +var expectedMissing = ['abs', 'AddRestrictedFunctionProperties', 'AddWaiter', 'agent-order', 'AgentCanSuspend', 'AgentSignifier', 'AllocateArrayBuffer', 'AllocateSharedArrayBuffer', 'AllocateTypedArray', 'AllocateTypedArrayBuffer', 'AsyncFunctionStart', 'AsyncGeneratorEnqueue', 'AsyncGeneratorReject', 'AsyncGeneratorResolve', 'AsyncGeneratorResumeNext', 'AsyncGeneratorStart', 'AsyncGeneratorYield', 'AtomicLoad', 'AtomicReadModifyWrite', 'Await', 'BlockDeclarationInstantiation', 'BoundFunctionCreate', 'Canonicalize', 'CaseClauseIsSelected', 'CharacterRange', 'CharacterRangeOrUnion', 'CharacterSetMatcher', 'CloneArrayBuffer', 'Completion', 'ComposeWriteEventBytes', 'CopyDataBlockBytes', 'CreateArrayIterator', 'CreateAsyncFromSyncIterator', 'CreateBuiltinFunction', 'CreateByteDataBlock', 'CreateDynamicFunction', 'CreateIntrinsics', 'CreateMapIterator', 'CreateMappedArgumentsObject', 'CreatePerIterationEnvironment', 'CreateRealm', 'CreateResolvingFunctions', 'CreateSetIterator', 'CreateSharedByteDataBlock', 'CreateStringIterator', 'CreateUnmappedArgumentsObject', 'Decode', 'DetachArrayBuffer', 'Encode', 'EnqueueJob', 'EnterCriticalSection', 'EnumerateObjectProperties', 'EscapeRegExpPattern', 'EvalDeclarationInstantiation', 'EvaluateCall', 'EvaluateNew', 'EventSet', 'floor', 'ForBodyEvaluation', 'ForIn/OfBodyEvaluation', 'ForIn/OfHeadEvaluation', 'FulfillPromise', 'FunctionAllocate', 'FunctionCreate', 'FunctionDeclarationInstantiation', 'FunctionInitialize', 'GeneratorFunctionCreate', 'GeneratorResume', 'GeneratorResumeAbrupt', 'GeneratorStart', 'GeneratorValidate', 'GeneratorYield', 'GetActiveScriptOrModule', 'GetBase', 'GetFunctionRealm', 'GetGeneratorKind', 'GetGlobalObject', 'GetIdentifierReference', 'GetModifySetValueInBuffer', 'GetModuleNamespace', 'GetNewTarget', 'GetReferencedName', 'GetSuperConstructor', 'GetTemplateObject', 'GetThisEnvironment', 'GetThisValue', 'GetValue', 'GetValueFromBuffer', 'GetViewValue', 'GetWaiterList', 'GlobalDeclarationInstantiation', 'happens-before', 'HasPrimitiveBase', 'host-synchronizes-with', 'HostEnsureCanCompileStrings', 'HostEventSet', 'HostPromiseRejectionTracker', 'HostReportErrors', 'HostResolveImportedModule', 'IfAbruptRejectPromise', 'ImportedLocalNames', 'InitializeBoundName', 'InitializeHostDefinedRealm', 'InitializeReferencedBinding', 'InnerModuleEvaluation', 'InnerModuleInstantiation', 'IntegerIndexedElementGet', 'IntegerIndexedElementSet', 'IntegerIndexedObjectCreate', 'InternalizeJSONProperty', 'IsAnonymousFunctionDefinition', 'IsCompatiblePropertyDescriptor', 'IsDetachedBuffer', 'IsInTailPosition', 'IsLabelledFunction', 'IsPropertyReference', 'IsSharedArrayBuffer', 'IsStrictReference', 'IsSuperReference', 'IsUnresolvableReference', 'IsWordChar', 'LeaveCriticalSection', 'LocalTime', 'LoopContinues', 'MakeArgGetter', 'MakeArgSetter', 'MakeClassConstructor', 'MakeConstructor', 'MakeMethod', 'MakeSuperPropertyReference', 'max', 'memory-order', 'min', 'ModuleDeclarationEnvironmentSetup', 'ModuleExecution', 'ModuleNamespaceCreate', 'NewDeclarativeEnvironment', 'NewFunctionEnvironment', 'NewGlobalEnvironment', 'NewModuleEnvironment', 'NewObjectEnvironment', 'NewPromiseCapability', 'NumberToRawBytes', 'ObjectDefineProperties', 'OrdinaryCallBindThis', 'OrdinaryCallEvaluateBody', 'OrdinaryCreateFromConstructor', 'OrdinaryDelete', 'OrdinaryGet', 'OrdinaryIsExtensible', 'OrdinaryOwnPropertyKeys', 'OrdinaryPreventExtensions', 'OrdinaryToPrimitive', 'ParseModule', 'ParseScript', 'PerformEval', 'PerformPromiseAll', 'PerformPromiseRace', 'PerformPromiseThen', 'PrepareForOrdinaryCall', 'PrepareForTailCall', 'PromiseReactionJob', 'PromiseResolveThenableJob', 'ProxyCreate', 'PutValue', 'QuoteJSONString', 'RawBytesToNumber', 'reads-bytes-from', 'reads-from', 'RegExpAlloc', 'RegExpCreate', 'RegExpInitialize', 'RejectPromise', 'RemoveWaiter', 'RemoveWaiters', 'RepeatMatcher', 'ResolveBinding', 'ResolveThisBinding', 'ReturnIfAbrupt', 'RunJobs', 'ScriptEvaluation', 'ScriptEvaluationJob', 'SerializeJSONArray', 'SerializeJSONObject', 'SerializeJSONProperty', 'SetDefaultGlobalBindings', 'SetImmutablePrototype', 'SetRealmGlobalObject', 'SetValueInBuffer', 'SetViewValue', 'SharedDataBlockEventSet', 'SortCompare', 'SplitMatch', 'StringCreate', 'StringGetOwnProperty', 'Suspend', 'synchronizes-with', 'TimeZoneString', 'TopLevelModuleEvaluationJob', 'TriggerPromiseReactions', 'TypedArrayCreate', 'TypedArraySpeciesCreate', 'UnicodeEscape', 'UpdateEmpty', 'UTC', 'UTF16Decode', 'UTF16Encoding', 'ValidateAtomicAccess', 'ValidateSharedIntegerTypedArray', 'ValidateTypedArray', 'ValueOfReadEvent', 'WakeWaiter', 'WordCharacters', 'AsyncFunctionCreate', 'AsyncGeneratorFunctionCreate', 'AsyncIteratorClose', 'BackreferenceMatcher', 'Construct', 'CreateArrayFromList', 'CreateListIteratorRecord', 'NormalCompletion', 'OrdinarySet', 'OrdinarySetWithOwnDescriptor', 'RegExpBuiltinExec', 'SetFunctionLength', 'ThrowCompletion', 'UnicodeMatchProperty', 'UnicodeMatchPropertyValue', 'AsyncFromSyncIteratorContinuation', 'ExecuteModule', 'InitializeEnvironment', 'NotifyWaiter', 'SynchronizeEventSet']; + +require('./tests').es2019(ES, ops, expectedMissing); diff --git a/scripts/2.5/node_modules/es-abstract/test/es5.js b/scripts/2.5/node_modules/es-abstract/test/es5.js new file mode 100644 index 00000000..efd9042b --- /dev/null +++ b/scripts/2.5/node_modules/es-abstract/test/es5.js @@ -0,0 +1,782 @@ +'use strict'; + +var ES = require('../').ES5; +var test = require('tape'); + +var forEach = require('foreach'); +var is = require('object-is'); +var debug = require('object-inspect'); + +var v = require('./helpers/values'); + +test('ToPrimitive', function (t) { + t.test('primitives', function (st) { + var testPrimitive = function (primitive) { + st.ok(is(ES.ToPrimitive(primitive), primitive), debug(primitive) + ' is returned correctly'); + }; + forEach(v.primitives, testPrimitive); + st.end(); + }); + + t.test('objects', function (st) { + st.equal(ES.ToPrimitive(v.coercibleObject), v.coercibleObject.valueOf(), 'coercibleObject coerces to valueOf'); + st.equal(ES.ToPrimitive(v.coercibleObject, Number), v.coercibleObject.valueOf(), 'coercibleObject with hint Number coerces to valueOf'); + st.equal(ES.ToPrimitive(v.coercibleObject, String), v.coercibleObject.toString(), 'coercibleObject with hint String coerces to toString'); + st.equal(ES.ToPrimitive(v.coercibleFnObject), v.coercibleFnObject.toString(), 'coercibleFnObject coerces to toString'); + st.equal(ES.ToPrimitive(v.toStringOnlyObject), v.toStringOnlyObject.toString(), 'toStringOnlyObject returns toString'); + st.equal(ES.ToPrimitive(v.valueOfOnlyObject), v.valueOfOnlyObject.valueOf(), 'valueOfOnlyObject returns valueOf'); + st.equal(ES.ToPrimitive({}), '[object Object]', '{} with no hint coerces to Object#toString'); + st.equal(ES.ToPrimitive({}, String), '[object Object]', '{} with hint String coerces to Object#toString'); + st.equal(ES.ToPrimitive({}, Number), '[object Object]', '{} with hint Number coerces to Object#toString'); + st['throws'](function () { return ES.ToPrimitive(v.uncoercibleObject); }, TypeError, 'uncoercibleObject throws a TypeError'); + st['throws'](function () { return ES.ToPrimitive(v.uncoercibleFnObject); }, TypeError, 'uncoercibleFnObject throws a TypeError'); + st.end(); + }); + + t.end(); +}); + +test('ToBoolean', function (t) { + t.equal(false, ES.ToBoolean(undefined), 'undefined coerces to false'); + t.equal(false, ES.ToBoolean(null), 'null coerces to false'); + t.equal(false, ES.ToBoolean(false), 'false returns false'); + t.equal(true, ES.ToBoolean(true), 'true returns true'); + forEach([0, -0, NaN], function (falsyNumber) { + t.equal(false, ES.ToBoolean(falsyNumber), 'falsy number ' + falsyNumber + ' coerces to false'); + }); + forEach([Infinity, 42, 1, -Infinity], function (truthyNumber) { + t.equal(true, ES.ToBoolean(truthyNumber), 'truthy number ' + truthyNumber + ' coerces to true'); + }); + t.equal(false, ES.ToBoolean(''), 'empty string coerces to false'); + t.equal(true, ES.ToBoolean('foo'), 'nonempty string coerces to true'); + forEach(v.objects, function (obj) { + t.equal(true, ES.ToBoolean(obj), 'object coerces to true'); + }); + t.equal(true, ES.ToBoolean(v.uncoercibleObject), 'uncoercibleObject coerces to true'); + t.end(); +}); + +test('ToNumber', function (t) { + t.ok(is(NaN, ES.ToNumber(undefined)), 'undefined coerces to NaN'); + t.ok(is(ES.ToNumber(null), 0), 'null coerces to +0'); + t.ok(is(ES.ToNumber(false), 0), 'false coerces to +0'); + t.equal(1, ES.ToNumber(true), 'true coerces to 1'); + t.ok(is(NaN, ES.ToNumber(NaN)), 'NaN returns itself'); + forEach([0, -0, 42, Infinity, -Infinity], function (num) { + t.equal(num, ES.ToNumber(num), num + ' returns itself'); + }); + forEach(['foo', '0', '4a', '2.0', 'Infinity', '-Infinity'], function (numString) { + t.ok(is(+numString, ES.ToNumber(numString)), '"' + numString + '" coerces to ' + Number(numString)); + }); + forEach(v.objects, function (object) { + t.ok(is(ES.ToNumber(object), ES.ToNumber(ES.ToPrimitive(object))), 'object ' + object + ' coerces to same as ToPrimitive of object does'); + }); + t['throws'](function () { return ES.ToNumber(v.uncoercibleObject); }, TypeError, 'uncoercibleObject throws'); + t.end(); +}); + +test('ToInteger', function (t) { + t.ok(is(0, ES.ToInteger(NaN)), 'NaN coerces to +0'); + forEach([0, Infinity, 42], function (num) { + t.ok(is(num, ES.ToInteger(num)), num + ' returns itself'); + t.ok(is(-num, ES.ToInteger(-num)), '-' + num + ' returns itself'); + }); + t.equal(3, ES.ToInteger(Math.PI), 'pi returns 3'); + t['throws'](function () { return ES.ToInteger(v.uncoercibleObject); }, TypeError, 'uncoercibleObject throws'); + t.end(); +}); + +test('ToInt32', function (t) { + t.ok(is(0, ES.ToInt32(NaN)), 'NaN coerces to +0'); + forEach([0, Infinity], function (num) { + t.ok(is(0, ES.ToInt32(num)), num + ' returns +0'); + t.ok(is(0, ES.ToInt32(-num)), '-' + num + ' returns +0'); + }); + t['throws'](function () { return ES.ToInt32(v.uncoercibleObject); }, TypeError, 'uncoercibleObject throws'); + t.ok(is(ES.ToInt32(0x100000000), 0), '2^32 returns +0'); + t.ok(is(ES.ToInt32(0x100000000 - 1), -1), '2^32 - 1 returns -1'); + t.ok(is(ES.ToInt32(0x80000000), -0x80000000), '2^31 returns -2^31'); + t.ok(is(ES.ToInt32(0x80000000 - 1), 0x80000000 - 1), '2^31 - 1 returns 2^31 - 1'); + forEach([0, Infinity, NaN, 0x100000000, 0x80000000, 0x10000, 0x42], function (num) { + t.ok(is(ES.ToInt32(num), ES.ToInt32(ES.ToUint32(num))), 'ToInt32(x) === ToInt32(ToUint32(x)) for 0x' + num.toString(16)); + t.ok(is(ES.ToInt32(-num), ES.ToInt32(ES.ToUint32(-num))), 'ToInt32(x) === ToInt32(ToUint32(x)) for -0x' + num.toString(16)); + }); + t.end(); +}); + +test('ToUint32', function (t) { + t.ok(is(0, ES.ToUint32(NaN)), 'NaN coerces to +0'); + forEach([0, Infinity], function (num) { + t.ok(is(0, ES.ToUint32(num)), num + ' returns +0'); + t.ok(is(0, ES.ToUint32(-num)), '-' + num + ' returns +0'); + }); + t['throws'](function () { return ES.ToUint32(v.uncoercibleObject); }, TypeError, 'uncoercibleObject throws'); + t.ok(is(ES.ToUint32(0x100000000), 0), '2^32 returns +0'); + t.ok(is(ES.ToUint32(0x100000000 - 1), 0x100000000 - 1), '2^32 - 1 returns 2^32 - 1'); + t.ok(is(ES.ToUint32(0x80000000), 0x80000000), '2^31 returns 2^31'); + t.ok(is(ES.ToUint32(0x80000000 - 1), 0x80000000 - 1), '2^31 - 1 returns 2^31 - 1'); + forEach([0, Infinity, NaN, 0x100000000, 0x80000000, 0x10000, 0x42], function (num) { + t.ok(is(ES.ToUint32(num), ES.ToUint32(ES.ToInt32(num))), 'ToUint32(x) === ToUint32(ToInt32(x)) for 0x' + num.toString(16)); + t.ok(is(ES.ToUint32(-num), ES.ToUint32(ES.ToInt32(-num))), 'ToUint32(x) === ToUint32(ToInt32(x)) for -0x' + num.toString(16)); + }); + t.end(); +}); + +test('ToUint16', function (t) { + t.ok(is(0, ES.ToUint16(NaN)), 'NaN coerces to +0'); + forEach([0, Infinity], function (num) { + t.ok(is(0, ES.ToUint16(num)), num + ' returns +0'); + t.ok(is(0, ES.ToUint16(-num)), '-' + num + ' returns +0'); + }); + t['throws'](function () { return ES.ToUint16(v.uncoercibleObject); }, TypeError, 'uncoercibleObject throws'); + t.ok(is(ES.ToUint16(0x100000000), 0), '2^32 returns +0'); + t.ok(is(ES.ToUint16(0x100000000 - 1), 0x10000 - 1), '2^32 - 1 returns 2^16 - 1'); + t.ok(is(ES.ToUint16(0x80000000), 0), '2^31 returns +0'); + t.ok(is(ES.ToUint16(0x80000000 - 1), 0x10000 - 1), '2^31 - 1 returns 2^16 - 1'); + t.ok(is(ES.ToUint16(0x10000), 0), '2^16 returns +0'); + t.ok(is(ES.ToUint16(0x10000 - 1), 0x10000 - 1), '2^16 - 1 returns 2^16 - 1'); + t.end(); +}); + +test('ToString', function (t) { + t['throws'](function () { return ES.ToString(v.uncoercibleObject); }, TypeError, 'uncoercibleObject throws'); + t.end(); +}); + +test('ToObject', function (t) { + t['throws'](function () { return ES.ToObject(undefined); }, TypeError, 'undefined throws'); + t['throws'](function () { return ES.ToObject(null); }, TypeError, 'null throws'); + forEach(v.numbers, function (number) { + var obj = ES.ToObject(number); + t.equal(typeof obj, 'object', 'number ' + number + ' coerces to object'); + t.equal(true, obj instanceof Number, 'object of ' + number + ' is Number object'); + t.ok(is(obj.valueOf(), number), 'object of ' + number + ' coerces to ' + number); + }); + t.end(); +}); + +test('CheckObjectCoercible', function (t) { + t['throws'](function () { return ES.CheckObjectCoercible(undefined); }, TypeError, 'undefined throws'); + t['throws'](function () { return ES.CheckObjectCoercible(null); }, TypeError, 'null throws'); + var checkCoercible = function (value) { + t.doesNotThrow(function () { return ES.CheckObjectCoercible(value); }, debug(value) + ' does not throw'); + }; + forEach(v.objects.concat(v.nonNullPrimitives), checkCoercible); + t.end(); +}); + +test('IsCallable', function (t) { + t.equal(true, ES.IsCallable(function () {}), 'function is callable'); + var nonCallables = [/a/g, {}, Object.prototype, NaN].concat(v.primitives); + forEach(nonCallables, function (nonCallable) { + t.equal(false, ES.IsCallable(nonCallable), debug(nonCallable) + ' is not callable'); + }); + t.end(); +}); + +test('SameValue', function (t) { + t.equal(true, ES.SameValue(NaN, NaN), 'NaN is SameValue as NaN'); + t.equal(false, ES.SameValue(0, -0), '+0 is not SameValue as -0'); + forEach(v.objects.concat(v.primitives), function (val) { + t.equal(val === val, ES.SameValue(val, val), debug(val) + ' is SameValue to itself'); + }); + t.end(); +}); + +test('Type', function (t) { + t.equal(ES.Type(), 'Undefined', 'Type() is Undefined'); + t.equal(ES.Type(undefined), 'Undefined', 'Type(undefined) is Undefined'); + t.equal(ES.Type(null), 'Null', 'Type(null) is Null'); + t.equal(ES.Type(true), 'Boolean', 'Type(true) is Boolean'); + t.equal(ES.Type(false), 'Boolean', 'Type(false) is Boolean'); + t.equal(ES.Type(0), 'Number', 'Type(0) is Number'); + t.equal(ES.Type(NaN), 'Number', 'Type(NaN) is Number'); + t.equal(ES.Type('abc'), 'String', 'Type("abc") is String'); + t.equal(ES.Type(function () {}), 'Object', 'Type(function () {}) is Object'); + t.equal(ES.Type({}), 'Object', 'Type({}) is Object'); + t.end(); +}); + +test('IsPropertyDescriptor', function (t) { + forEach(v.primitives, function (primitive) { + t.equal(ES.IsPropertyDescriptor(primitive), false, debug(primitive) + ' is not a Property Descriptor'); + }); + + t.equal(ES.IsPropertyDescriptor({ invalid: true }), false, 'invalid keys not allowed on a Property Descriptor'); + + t.equal(ES.IsPropertyDescriptor({}), true, 'empty object is an incomplete Property Descriptor'); + + t.equal(ES.IsPropertyDescriptor(v.accessorDescriptor()), true, 'accessor descriptor is a Property Descriptor'); + t.equal(ES.IsPropertyDescriptor(v.mutatorDescriptor()), true, 'mutator descriptor is a Property Descriptor'); + t.equal(ES.IsPropertyDescriptor(v.dataDescriptor()), true, 'data descriptor is a Property Descriptor'); + t.equal(ES.IsPropertyDescriptor(v.genericDescriptor()), true, 'generic descriptor is a Property Descriptor'); + + t['throws']( + function () { ES.IsPropertyDescriptor(v.bothDescriptor()); }, + TypeError, + 'a Property Descriptor can not be both a Data and an Accessor Descriptor' + ); + + t['throws']( + function () { ES.IsPropertyDescriptor(v.bothDescriptorWritable()); }, + TypeError, + 'a Property Descriptor can not be both a Data and an Accessor Descriptor' + ); + + t.end(); +}); + +test('IsAccessorDescriptor', function (t) { + forEach(v.nonNullPrimitives.concat(null), function (primitive) { + t['throws'](function () { ES.IsAccessorDescriptor(primitive); }, TypeError, debug(primitive) + ' is not a Property Descriptor'); + }); + + t.equal(ES.IsAccessorDescriptor(), false, 'no value is not an Accessor Descriptor'); + t.equal(ES.IsAccessorDescriptor(undefined), false, 'undefined value is not an Accessor Descriptor'); + + t.equal(ES.IsAccessorDescriptor(v.accessorDescriptor()), true, 'accessor descriptor is an Accessor Descriptor'); + t.equal(ES.IsAccessorDescriptor(v.mutatorDescriptor()), true, 'mutator descriptor is an Accessor Descriptor'); + t.equal(ES.IsAccessorDescriptor(v.dataDescriptor()), false, 'data descriptor is not an Accessor Descriptor'); + t.equal(ES.IsAccessorDescriptor(v.genericDescriptor()), false, 'generic descriptor is not an Accessor Descriptor'); + + t.end(); +}); + +test('IsDataDescriptor', function (t) { + forEach(v.nonNullPrimitives.concat(null), function (primitive) { + t['throws'](function () { ES.IsDataDescriptor(primitive); }, TypeError, debug(primitive) + ' is not a Property Descriptor'); + }); + + t.equal(ES.IsDataDescriptor(), false, 'no value is not a Data Descriptor'); + t.equal(ES.IsDataDescriptor(undefined), false, 'undefined value is not a Data Descriptor'); + + t.equal(ES.IsDataDescriptor(v.accessorDescriptor()), false, 'accessor descriptor is not a Data Descriptor'); + t.equal(ES.IsDataDescriptor(v.mutatorDescriptor()), false, 'mutator descriptor is not a Data Descriptor'); + t.equal(ES.IsDataDescriptor(v.dataDescriptor()), true, 'data descriptor is a Data Descriptor'); + t.equal(ES.IsDataDescriptor(v.genericDescriptor()), false, 'generic descriptor is not a Data Descriptor'); + + t.end(); +}); + +test('IsGenericDescriptor', function (t) { + forEach(v.nonNullPrimitives.concat(null), function (primitive) { + t['throws']( + function () { ES.IsGenericDescriptor(primitive); }, + TypeError, + debug(primitive) + ' is not a Property Descriptor' + ); + }); + + t.equal(ES.IsGenericDescriptor(), false, 'no value is not a Data Descriptor'); + t.equal(ES.IsGenericDescriptor(undefined), false, 'undefined value is not a Data Descriptor'); + + t.equal(ES.IsGenericDescriptor(v.accessorDescriptor()), false, 'accessor descriptor is not a generic Descriptor'); + t.equal(ES.IsGenericDescriptor(v.mutatorDescriptor()), false, 'mutator descriptor is not a generic Descriptor'); + t.equal(ES.IsGenericDescriptor(v.dataDescriptor()), false, 'data descriptor is not a generic Descriptor'); + + t.equal(ES.IsGenericDescriptor(v.genericDescriptor()), true, 'generic descriptor is a generic Descriptor'); + + t.end(); +}); + +test('FromPropertyDescriptor', function (t) { + t.equal(ES.FromPropertyDescriptor(), undefined, 'no value begets undefined'); + t.equal(ES.FromPropertyDescriptor(undefined), undefined, 'undefined value begets undefined'); + + forEach(v.nonNullPrimitives.concat(null), function (primitive) { + t['throws']( + function () { ES.FromPropertyDescriptor(primitive); }, + TypeError, + debug(primitive) + ' is not a Property Descriptor' + ); + }); + + var accessor = v.accessorDescriptor(); + t.deepEqual(ES.FromPropertyDescriptor(accessor), { + get: accessor['[[Get]]'], + set: accessor['[[Set]]'], + enumerable: !!accessor['[[Enumerable]]'], + configurable: !!accessor['[[Configurable]]'] + }); + + var mutator = v.mutatorDescriptor(); + t.deepEqual(ES.FromPropertyDescriptor(mutator), { + get: mutator['[[Get]]'], + set: mutator['[[Set]]'], + enumerable: !!mutator['[[Enumerable]]'], + configurable: !!mutator['[[Configurable]]'] + }); + var data = v.dataDescriptor(); + t.deepEqual(ES.FromPropertyDescriptor(data), { + value: data['[[Value]]'], + writable: data['[[Writable]]'], + enumerable: !!data['[[Enumerable]]'], + configurable: !!data['[[Configurable]]'] + }); + + t['throws']( + function () { ES.FromPropertyDescriptor(v.genericDescriptor()); }, + TypeError, + 'a complete Property Descriptor is required' + ); + + t.end(); +}); + +test('ToPropertyDescriptor', function (t) { + forEach(v.nonNullPrimitives.concat(null), function (primitive) { + t['throws']( + function () { ES.ToPropertyDescriptor(primitive); }, + TypeError, + debug(primitive) + ' is not an Object' + ); + }); + + var accessor = v.accessorDescriptor(); + t.deepEqual(ES.ToPropertyDescriptor({ + get: accessor['[[Get]]'], + enumerable: !!accessor['[[Enumerable]]'], + configurable: !!accessor['[[Configurable]]'] + }), accessor); + + var mutator = v.mutatorDescriptor(); + t.deepEqual(ES.ToPropertyDescriptor({ + set: mutator['[[Set]]'], + enumerable: !!mutator['[[Enumerable]]'], + configurable: !!mutator['[[Configurable]]'] + }), mutator); + + var data = v.descriptors.nonConfigurable(v.dataDescriptor()); + t.deepEqual(ES.ToPropertyDescriptor({ + value: data['[[Value]]'], + writable: data['[[Writable]]'], + configurable: !!data['[[Configurable]]'] + }), data); + + var both = v.bothDescriptor(); + t['throws']( + function () { + ES.ToPropertyDescriptor({ get: both['[[Get]]'], value: both['[[Value]]'] }); + }, + TypeError, + 'data and accessor descriptors are mutually exclusive' + ); + + t['throws']( + function () { ES.ToPropertyDescriptor({ get: 'not callable' }); }, + TypeError, + '"get" must be undefined or callable' + ); + + t['throws']( + function () { ES.ToPropertyDescriptor({ set: 'not callable' }); }, + TypeError, + '"set" must be undefined or callable' + ); + + t.end(); +}); + +test('Abstract Equality Comparison', function (t) { + t.test('same types use ===', function (st) { + forEach(v.primitives.concat(v.objects), function (value) { + st.equal(ES['Abstract Equality Comparison'](value, value), value === value, debug(value) + ' is abstractly equal to itself'); + }); + st.end(); + }); + + t.test('different types coerce', function (st) { + var pairs = [ + [null, undefined], + [3, '3'], + [true, '3'], + [true, 3], + [false, 0], + [false, '0'], + [3, [3]], + ['3', [3]], + [true, [1]], + [false, [0]], + [String(v.coercibleObject), v.coercibleObject], + [Number(String(v.coercibleObject)), v.coercibleObject], + [Number(v.coercibleObject), v.coercibleObject], + [String(Number(v.coercibleObject)), v.coercibleObject] + ]; + forEach(pairs, function (pair) { + var a = pair[0]; + var b = pair[1]; + // eslint-disable-next-line eqeqeq + st.equal(ES['Abstract Equality Comparison'](a, b), a == b, debug(a) + ' == ' + debug(b)); + // eslint-disable-next-line eqeqeq + st.equal(ES['Abstract Equality Comparison'](b, a), b == a, debug(b) + ' == ' + debug(a)); + }); + st.end(); + }); + + t.end(); +}); + +test('Strict Equality Comparison', function (t) { + t.test('same types use ===', function (st) { + forEach(v.primitives.concat(v.objects), function (value) { + st.equal(ES['Strict Equality Comparison'](value, value), value === value, debug(value) + ' is strictly equal to itself'); + }); + st.end(); + }); + + t.test('different types are not ===', function (st) { + var pairs = [ + [null, undefined], + [3, '3'], + [true, '3'], + [true, 3], + [false, 0], + [false, '0'], + [3, [3]], + ['3', [3]], + [true, [1]], + [false, [0]], + [String(v.coercibleObject), v.coercibleObject], + [Number(String(v.coercibleObject)), v.coercibleObject], + [Number(v.coercibleObject), v.coercibleObject], + [String(Number(v.coercibleObject)), v.coercibleObject] + ]; + forEach(pairs, function (pair) { + var a = pair[0]; + var b = pair[1]; + st.equal(ES['Strict Equality Comparison'](a, b), a === b, debug(a) + ' === ' + debug(b)); + st.equal(ES['Strict Equality Comparison'](b, a), b === a, debug(b) + ' === ' + debug(a)); + }); + st.end(); + }); + + t.end(); +}); + +test('Abstract Relational Comparison', function (t) { + t.test('at least one operand is NaN', function (st) { + st.equal(ES['Abstract Relational Comparison'](NaN, {}, true), undefined, 'LeftFirst: first is NaN, returns undefined'); + st.equal(ES['Abstract Relational Comparison']({}, NaN, true), undefined, 'LeftFirst: second is NaN, returns undefined'); + st.equal(ES['Abstract Relational Comparison'](NaN, {}, false), undefined, '!LeftFirst: first is NaN, returns undefined'); + st.equal(ES['Abstract Relational Comparison']({}, NaN, false), undefined, '!LeftFirst: second is NaN, returns undefined'); + st.end(); + }); + + t.equal(ES['Abstract Relational Comparison'](3, 4, true), true, 'LeftFirst: 3 is less than 4'); + t.equal(ES['Abstract Relational Comparison'](4, 3, true), false, 'LeftFirst: 3 is not less than 4'); + t.equal(ES['Abstract Relational Comparison'](3, 4, false), true, '!LeftFirst: 3 is less than 4'); + t.equal(ES['Abstract Relational Comparison'](4, 3, false), false, '!LeftFirst: 3 is not less than 4'); + + t.equal(ES['Abstract Relational Comparison']('3', '4', true), true, 'LeftFirst: "3" is less than "4"'); + t.equal(ES['Abstract Relational Comparison']('4', '3', true), false, 'LeftFirst: "3" is not less than "4"'); + t.equal(ES['Abstract Relational Comparison']('3', '4', false), true, '!LeftFirst: "3" is less than "4"'); + t.equal(ES['Abstract Relational Comparison']('4', '3', false), false, '!LeftFirst: "3" is not less than "4"'); + + t.equal(ES['Abstract Relational Comparison'](v.coercibleObject, 42, true), true, 'LeftFirst: coercible object is less than 42'); + t.equal(ES['Abstract Relational Comparison'](42, v.coercibleObject, true), false, 'LeftFirst: 42 is not less than coercible object'); + t.equal(ES['Abstract Relational Comparison'](v.coercibleObject, 42, false), true, '!LeftFirst: coercible object is less than 42'); + t.equal(ES['Abstract Relational Comparison'](42, v.coercibleObject, false), false, '!LeftFirst: 42 is not less than coercible object'); + + t.equal(ES['Abstract Relational Comparison'](v.coercibleObject, '3', true), false, 'LeftFirst: coercible object is not less than "3"'); + t.equal(ES['Abstract Relational Comparison']('3', v.coercibleObject, true), false, 'LeftFirst: "3" is not less than coercible object'); + t.equal(ES['Abstract Relational Comparison'](v.coercibleObject, '3', false), false, '!LeftFirst: coercible object is not less than "3"'); + t.equal(ES['Abstract Relational Comparison']('3', v.coercibleObject, false), false, '!LeftFirst: "3" is not less than coercible object'); + + t.end(); +}); + +test('FromPropertyDescriptor', function (t) { + t.equal(ES.FromPropertyDescriptor(), undefined, 'no value begets undefined'); + t.equal(ES.FromPropertyDescriptor(undefined), undefined, 'undefined value begets undefined'); + + forEach(v.nonUndefinedPrimitives, function (primitive) { + t['throws']( + function () { ES.FromPropertyDescriptor(primitive); }, + TypeError, + debug(primitive) + ' is not a Property Descriptor' + ); + }); + + var accessor = v.accessorDescriptor(); + t.deepEqual(ES.FromPropertyDescriptor(accessor), { + get: accessor['[[Get]]'], + set: accessor['[[Set]]'], + enumerable: !!accessor['[[Enumerable]]'], + configurable: !!accessor['[[Configurable]]'] + }); + + var mutator = v.mutatorDescriptor(); + t.deepEqual(ES.FromPropertyDescriptor(mutator), { + get: mutator['[[Get]]'], + set: mutator['[[Set]]'], + enumerable: !!mutator['[[Enumerable]]'], + configurable: !!mutator['[[Configurable]]'] + }); + var data = v.dataDescriptor(); + t.deepEqual(ES.FromPropertyDescriptor(data), { + value: data['[[Value]]'], + writable: data['[[Writable]]'], + enumerable: !!data['[[Enumerable]]'], + configurable: !!data['[[Configurable]]'] + }); + + t['throws']( + function () { ES.FromPropertyDescriptor(v.genericDescriptor()); }, + TypeError, + 'a complete Property Descriptor is required' + ); + + t.end(); +}); + +test('SecFromTime', function (t) { + var now = new Date(); + t.equal(ES.SecFromTime(now.getTime()), now.getUTCSeconds(), 'second from Date timestamp matches getUTCSeconds'); + t.end(); +}); + +test('MinFromTime', function (t) { + var now = new Date(); + t.equal(ES.MinFromTime(now.getTime()), now.getUTCMinutes(), 'minute from Date timestamp matches getUTCMinutes'); + t.end(); +}); + +test('HourFromTime', function (t) { + var now = new Date(); + t.equal(ES.HourFromTime(now.getTime()), now.getUTCHours(), 'hour from Date timestamp matches getUTCHours'); + t.end(); +}); + +test('msFromTime', function (t) { + var now = new Date(); + t.equal(ES.msFromTime(now.getTime()), now.getUTCMilliseconds(), 'ms from Date timestamp matches getUTCMilliseconds'); + t.end(); +}); + +var msPerSecond = 1e3; +var msPerMinute = 60 * msPerSecond; +var msPerHour = 60 * msPerMinute; +var msPerDay = 24 * msPerHour; + +test('Day', function (t) { + var time = Date.UTC(2019, 8, 10, 2, 3, 4, 5); + var add = 2.5; + var later = new Date(time + (add * msPerDay)); + + t.equal(ES.Day(later.getTime()), ES.Day(time) + Math.floor(add), 'adding 2.5 days worth of ms, gives a Day delta of 2'); + t.end(); +}); + +test('TimeWithinDay', function (t) { + var time = Date.UTC(2019, 8, 10, 2, 3, 4, 5); + var add = 2.5; + var later = new Date(time + (add * msPerDay)); + + t.equal(ES.TimeWithinDay(later.getTime()), ES.TimeWithinDay(time) + (0.5 * msPerDay), 'adding 2.5 days worth of ms, gives a TimeWithinDay delta of +0.5'); + t.end(); +}); + +test('DayFromYear', function (t) { + t.equal(ES.DayFromYear(2021) - ES.DayFromYear(2020), 366, '2021 is a leap year, has 366 days'); + t.equal(ES.DayFromYear(2020) - ES.DayFromYear(2019), 365, '2020 is not a leap year, has 365 days'); + t.equal(ES.DayFromYear(2019) - ES.DayFromYear(2018), 365, '2019 is not a leap year, has 365 days'); + t.equal(ES.DayFromYear(2018) - ES.DayFromYear(2017), 365, '2018 is not a leap year, has 365 days'); + t.equal(ES.DayFromYear(2017) - ES.DayFromYear(2016), 366, '2017 is a leap year, has 366 days'); + + t.end(); +}); + +test('TimeFromYear', function (t) { + for (var i = 1900; i < 2100; i += 1) { + t.equal(ES.TimeFromYear(i), Date.UTC(i, 0, 1), 'TimeFromYear matches a Date object’s year: ' + i); + } + t.end(); +}); + +test('YearFromTime', function (t) { + for (var i = 1900; i < 2100; i += 1) { + t.equal(ES.YearFromTime(Date.UTC(i, 0, 1)), i, 'YearFromTime matches a Date object’s year on 1/1: ' + i); + t.equal(ES.YearFromTime(Date.UTC(i, 10, 1)), i, 'YearFromTime matches a Date object’s year on 10/1: ' + i); + } + t.end(); +}); + +test('WeekDay', function (t) { + var now = new Date(); + var today = now.getUTCDay(); + for (var i = 0; i < 7; i += 1) { + var weekDay = ES.WeekDay(now.getTime() + (i * msPerDay)); + t.equal(weekDay, (today + i) % 7, i + ' days after today (' + today + '), WeekDay is ' + weekDay); + } + t.end(); +}); + +test('DaysInYear', function (t) { + t.equal(ES.DaysInYear(2021), 365, '2021 is not a leap year'); + t.equal(ES.DaysInYear(2020), 366, '2020 is a leap year'); + t.equal(ES.DaysInYear(2019), 365, '2019 is not a leap year'); + t.equal(ES.DaysInYear(2018), 365, '2018 is not a leap year'); + t.equal(ES.DaysInYear(2017), 365, '2017 is not a leap year'); + t.equal(ES.DaysInYear(2016), 366, '2016 is a leap year'); + + t.end(); +}); + +test('InLeapYear', function (t) { + t.equal(ES.InLeapYear(Date.UTC(2021, 0, 1)), 0, '2021 is not a leap year'); + t.equal(ES.InLeapYear(Date.UTC(2020, 0, 1)), 1, '2020 is a leap year'); + t.equal(ES.InLeapYear(Date.UTC(2019, 0, 1)), 0, '2019 is not a leap year'); + t.equal(ES.InLeapYear(Date.UTC(2018, 0, 1)), 0, '2018 is not a leap year'); + t.equal(ES.InLeapYear(Date.UTC(2017, 0, 1)), 0, '2017 is not a leap year'); + t.equal(ES.InLeapYear(Date.UTC(2016, 0, 1)), 1, '2016 is a leap year'); + + t.end(); +}); + +test('DayWithinYear', function (t) { + t.equal(ES.DayWithinYear(Date.UTC(2019, 0, 1)), 0, '1/1 is the 1st day'); + t.equal(ES.DayWithinYear(Date.UTC(2019, 11, 31)), 364, '12/31 is the 365th day in a non leap year'); + t.equal(ES.DayWithinYear(Date.UTC(2016, 11, 31)), 365, '12/31 is the 366th day in a leap year'); + + t.end(); +}); + +test('MonthFromTime', function (t) { + t.equal(ES.MonthFromTime(Date.UTC(2019, 0, 1)), 0, 'non-leap: 1/1 gives January'); + t.equal(ES.MonthFromTime(Date.UTC(2019, 0, 31)), 0, 'non-leap: 1/31 gives January'); + t.equal(ES.MonthFromTime(Date.UTC(2019, 1, 1)), 1, 'non-leap: 2/1 gives February'); + t.equal(ES.MonthFromTime(Date.UTC(2019, 1, 28)), 1, 'non-leap: 2/28 gives February'); + t.equal(ES.MonthFromTime(Date.UTC(2019, 1, 29)), 2, 'non-leap: 2/29 gives March'); + t.equal(ES.MonthFromTime(Date.UTC(2019, 2, 1)), 2, 'non-leap: 3/1 gives March'); + t.equal(ES.MonthFromTime(Date.UTC(2019, 2, 31)), 2, 'non-leap: 3/31 gives March'); + t.equal(ES.MonthFromTime(Date.UTC(2019, 3, 1)), 3, 'non-leap: 4/1 gives April'); + t.equal(ES.MonthFromTime(Date.UTC(2019, 3, 30)), 3, 'non-leap: 4/30 gives April'); + t.equal(ES.MonthFromTime(Date.UTC(2019, 4, 1)), 4, 'non-leap: 5/1 gives May'); + t.equal(ES.MonthFromTime(Date.UTC(2019, 4, 31)), 4, 'non-leap: 5/31 gives May'); + t.equal(ES.MonthFromTime(Date.UTC(2019, 5, 1)), 5, 'non-leap: 6/1 gives June'); + t.equal(ES.MonthFromTime(Date.UTC(2019, 5, 30)), 5, 'non-leap: 6/30 gives June'); + t.equal(ES.MonthFromTime(Date.UTC(2019, 6, 1)), 6, 'non-leap: 7/1 gives July'); + t.equal(ES.MonthFromTime(Date.UTC(2019, 6, 31)), 6, 'non-leap: 7/31 gives July'); + t.equal(ES.MonthFromTime(Date.UTC(2019, 7, 1)), 7, 'non-leap: 8/1 gives August'); + t.equal(ES.MonthFromTime(Date.UTC(2019, 7, 30)), 7, 'non-leap: 8/30 gives August'); + t.equal(ES.MonthFromTime(Date.UTC(2019, 8, 1)), 8, 'non-leap: 9/1 gives September'); + t.equal(ES.MonthFromTime(Date.UTC(2019, 8, 30)), 8, 'non-leap: 9/30 gives September'); + t.equal(ES.MonthFromTime(Date.UTC(2019, 9, 1)), 9, 'non-leap: 10/1 gives October'); + t.equal(ES.MonthFromTime(Date.UTC(2019, 9, 31)), 9, 'non-leap: 10/31 gives October'); + t.equal(ES.MonthFromTime(Date.UTC(2019, 10, 1)), 10, 'non-leap: 11/1 gives November'); + t.equal(ES.MonthFromTime(Date.UTC(2019, 10, 30)), 10, 'non-leap: 11/30 gives November'); + t.equal(ES.MonthFromTime(Date.UTC(2019, 11, 1)), 11, 'non-leap: 12/1 gives December'); + t.equal(ES.MonthFromTime(Date.UTC(2019, 11, 31)), 11, 'non-leap: 12/31 gives December'); + + t.equal(ES.MonthFromTime(Date.UTC(2016, 0, 1)), 0, 'leap: 1/1 gives January'); + t.equal(ES.MonthFromTime(Date.UTC(2016, 0, 31)), 0, 'leap: 1/31 gives January'); + t.equal(ES.MonthFromTime(Date.UTC(2016, 1, 1)), 1, 'leap: 2/1 gives February'); + t.equal(ES.MonthFromTime(Date.UTC(2016, 1, 28)), 1, 'leap: 2/28 gives February'); + t.equal(ES.MonthFromTime(Date.UTC(2016, 1, 29)), 1, 'leap: 2/29 gives February'); + t.equal(ES.MonthFromTime(Date.UTC(2016, 2, 1)), 2, 'leap: 3/1 gives March'); + t.equal(ES.MonthFromTime(Date.UTC(2016, 2, 31)), 2, 'leap: 3/31 gives March'); + t.equal(ES.MonthFromTime(Date.UTC(2016, 3, 1)), 3, 'leap: 4/1 gives April'); + t.equal(ES.MonthFromTime(Date.UTC(2016, 3, 30)), 3, 'leap: 4/30 gives April'); + t.equal(ES.MonthFromTime(Date.UTC(2016, 4, 1)), 4, 'leap: 5/1 gives May'); + t.equal(ES.MonthFromTime(Date.UTC(2016, 4, 31)), 4, 'leap: 5/31 gives May'); + t.equal(ES.MonthFromTime(Date.UTC(2016, 5, 1)), 5, 'leap: 6/1 gives June'); + t.equal(ES.MonthFromTime(Date.UTC(2016, 5, 30)), 5, 'leap: 6/30 gives June'); + t.equal(ES.MonthFromTime(Date.UTC(2016, 6, 1)), 6, 'leap: 7/1 gives July'); + t.equal(ES.MonthFromTime(Date.UTC(2016, 6, 31)), 6, 'leap: 7/31 gives July'); + t.equal(ES.MonthFromTime(Date.UTC(2016, 7, 1)), 7, 'leap: 8/1 gives August'); + t.equal(ES.MonthFromTime(Date.UTC(2016, 7, 30)), 7, 'leap: 8/30 gives August'); + t.equal(ES.MonthFromTime(Date.UTC(2016, 8, 1)), 8, 'leap: 9/1 gives September'); + t.equal(ES.MonthFromTime(Date.UTC(2016, 8, 30)), 8, 'leap: 9/30 gives September'); + t.equal(ES.MonthFromTime(Date.UTC(2016, 9, 1)), 9, 'leap: 10/1 gives October'); + t.equal(ES.MonthFromTime(Date.UTC(2016, 9, 31)), 9, 'leap: 10/31 gives October'); + t.equal(ES.MonthFromTime(Date.UTC(2016, 10, 1)), 10, 'leap: 11/1 gives November'); + t.equal(ES.MonthFromTime(Date.UTC(2016, 10, 30)), 10, 'leap: 11/30 gives November'); + t.equal(ES.MonthFromTime(Date.UTC(2016, 11, 1)), 11, 'leap: 12/1 gives December'); + t.equal(ES.MonthFromTime(Date.UTC(2016, 11, 31)), 11, 'leap: 12/31 gives December'); + t.end(); +}); + +test('DateFromTime', function (t) { + var i; + for (i = 1; i <= 28; i += 1) { + t.equal(ES.DateFromTime(Date.UTC(2019, 1, i)), i, '2019.02.' + i + ' is date ' + i); + } + for (i = 1; i <= 29; i += 1) { + t.equal(ES.DateFromTime(Date.UTC(2016, 1, i)), i, '2016.02.' + i + ' is date ' + i); + } + for (i = 1; i <= 30; i += 1) { + t.equal(ES.DateFromTime(Date.UTC(2019, 8, i)), i, '2019.09.' + i + ' is date ' + i); + } + for (i = 1; i <= 31; i += 1) { + t.equal(ES.DateFromTime(Date.UTC(2019, 9, i)), i, '2019.10.' + i + ' is date ' + i); + } + t.end(); +}); + +test('MakeDay', function (t) { + var day2015 = 16687; + t.equal(ES.MakeDay(2015, 8, 9), day2015, '2015.09.09 is day 16687'); + var day2016 = day2015 + 366; // 2016 is a leap year + t.equal(ES.MakeDay(2016, 8, 9), day2016, '2015.09.09 is day 17053'); + var day2017 = day2016 + 365; + t.equal(ES.MakeDay(2017, 8, 9), day2017, '2017.09.09 is day 17418'); + var day2018 = day2017 + 365; + t.equal(ES.MakeDay(2018, 8, 9), day2018, '2018.09.09 is day 17783'); + var day2019 = day2018 + 365; + t.equal(ES.MakeDay(2019, 8, 9), day2019, '2019.09.09 is day 18148'); + t.end(); +}); + +test('MakeDate', function (t) { + forEach(v.infinities.concat(NaN), function (nonFiniteNumber) { + t.ok(is(ES.MakeDate(nonFiniteNumber, 0), NaN), debug(nonFiniteNumber) + ' is not a finite `day`'); + t.ok(is(ES.MakeDate(0, nonFiniteNumber), NaN), debug(nonFiniteNumber) + ' is not a finite `time`'); + }); + t.equal(ES.MakeDate(0, 0), 0, 'zero day and zero time is zero date'); + t.equal(ES.MakeDate(0, 123), 123, 'zero day and nonzero time is a date of the "time"'); + t.equal(ES.MakeDate(1, 0), msPerDay, 'day of 1 and zero time is a date of "ms per day"'); + t.equal(ES.MakeDate(3, 0), 3 * msPerDay, 'day of 3 and zero time is a date of thrice "ms per day"'); + t.equal(ES.MakeDate(1, 123), msPerDay + 123, 'day of 1 and nonzero time is a date of "ms per day" plus the "time"'); + t.equal(ES.MakeDate(3, 123), (3 * msPerDay) + 123, 'day of 3 and nonzero time is a date of thrice "ms per day" plus the "time"'); + + t.end(); +}); + +test('MakeTime', function (t) { + forEach(v.infinities.concat(NaN), function (nonFiniteNumber) { + t.ok(is(ES.MakeTime(nonFiniteNumber, 0, 0, 0), NaN), debug(nonFiniteNumber) + ' is not a finite `hour`'); + t.ok(is(ES.MakeTime(0, nonFiniteNumber, 0, 0), NaN), debug(nonFiniteNumber) + ' is not a finite `min`'); + t.ok(is(ES.MakeTime(0, 0, nonFiniteNumber, 0), NaN), debug(nonFiniteNumber) + ' is not a finite `sec`'); + t.ok(is(ES.MakeTime(0, 0, 0, nonFiniteNumber), NaN), debug(nonFiniteNumber) + ' is not a finite `ms`'); + }); + + t.equal( + ES.MakeTime(1.2, 2.3, 3.4, 4.5), + (1 * msPerHour) + (2 * msPerMinute) + (3 * msPerSecond) + 4, + 'all numbers are converted to integer, multiplied by the right number of ms, and summed' + ); + t.end(); +}); + +test('TimeClip', function (t) { + forEach(v.infinities.concat(NaN), function (nonFiniteNumber) { + t.ok(is(ES.TimeClip(nonFiniteNumber), NaN), debug(nonFiniteNumber) + ' is not a finite `time`'); + }); + t.ok(is(ES.TimeClip(8.64e15 + 1), NaN), '8.64e15 is the largest magnitude considered "finite"'); + t.ok(is(ES.TimeClip(-8.64e15 - 1), NaN), '-8.64e15 is the largest magnitude considered "finite"'); + + forEach(v.zeroes.concat([-10, 10, Date.now()]), function (time) { + t.equal(ES.TimeClip(time), time, debug(time) + ' is a time of ' + debug(time)); + }); + + t.end(); +}); + +test('modulo', function (t) { + t.equal(3 % 2, 1, '+3 % 2 is +1'); + t.equal(ES.modulo(3, 2), 1, '+3 mod 2 is +1'); + + t.equal(-3 % 2, -1, '-3 % 2 is -1'); + t.equal(ES.modulo(-3, 2), 1, '-3 mod 2 is +1'); + t.end(); +}); diff --git a/scripts/2.5/node_modules/es-abstract/test/es6.js b/scripts/2.5/node_modules/es-abstract/test/es6.js new file mode 100644 index 00000000..e7c9d98a --- /dev/null +++ b/scripts/2.5/node_modules/es-abstract/test/es6.js @@ -0,0 +1,18 @@ +'use strict'; + +var test = require('tape'); + +var ES = require('../'); +var ES6 = ES.ES6; +var ES2015 = ES.ES2015; +var ES6entry = require('../es6'); + +test('legacy es6 export', function (t) { + t.equal(ES6, ES2015, 'main ES6 === main ES2015'); + t.end(); +}); + +test('legacy es6 entry point', function (t) { + t.equal(ES6, ES6entry, 'main ES6 === ES6 entry point'); + t.end(); +}); diff --git a/scripts/2.5/node_modules/es-abstract/test/es7.js b/scripts/2.5/node_modules/es-abstract/test/es7.js new file mode 100644 index 00000000..ee57e153 --- /dev/null +++ b/scripts/2.5/node_modules/es-abstract/test/es7.js @@ -0,0 +1,18 @@ +'use strict'; + +var test = require('tape'); + +var ES = require('../'); +var ES7 = ES.ES7; +var ES2016 = ES.ES2016; +var ES7entry = require('../es7'); + +test('legacy es7 export', function (t) { + t.equal(ES7, ES2016, 'main ES7 === main ES2016'); + t.end(); +}); + +test('legacy es7 entry point', function (t) { + t.equal(ES7, ES7entry, 'main ES7 === ES7 entry point'); + t.end(); +}); diff --git a/scripts/2.5/node_modules/es-abstract/test/helpers/assertRecord.js b/scripts/2.5/node_modules/es-abstract/test/helpers/assertRecord.js new file mode 100644 index 00000000..22e1aea4 --- /dev/null +++ b/scripts/2.5/node_modules/es-abstract/test/helpers/assertRecord.js @@ -0,0 +1,60 @@ +'use strict'; + +var forEach = require('foreach'); +var debug = require('object-inspect'); + +var assertRecord = require('../../helpers/assertRecord'); +var v = require('./values'); + +module.exports = function assertRecordTests(ES, test) { + test('Property Descriptor', function (t) { + var record = 'Property Descriptor'; + + forEach(v.nonUndefinedPrimitives, function (primitive) { + t['throws']( + function () { assertRecord(ES, record, 'arg', primitive); }, + TypeError, + debug(primitive) + ' is not a Property Descriptor' + ); + }); + + t['throws']( + function () { assertRecord(ES, record, 'arg', { invalid: true }); }, + TypeError, + 'invalid keys not allowed on a Property Descriptor' + ); + + t.doesNotThrow( + function () { assertRecord(ES, record, 'arg', {}); }, + 'empty object is an incomplete Property Descriptor' + ); + + t.doesNotThrow( + function () { assertRecord(ES, record, 'arg', v.accessorDescriptor()); }, + 'accessor descriptor is a Property Descriptor' + ); + + t.doesNotThrow( + function () { assertRecord(ES, record, 'arg', v.mutatorDescriptor()); }, + 'mutator descriptor is a Property Descriptor' + ); + + t.doesNotThrow( + function () { assertRecord(ES, record, 'arg', v.dataDescriptor()); }, + 'data descriptor is a Property Descriptor' + ); + + t.doesNotThrow( + function () { assertRecord(ES, record, 'arg', v.genericDescriptor()); }, + 'generic descriptor is a Property Descriptor' + ); + + t['throws']( + function () { assertRecord(ES, record, 'arg', v.bothDescriptor()); }, + TypeError, + 'a Property Descriptor can not be both a Data and an Accessor Descriptor' + ); + + t.end(); + }); +}; diff --git a/scripts/2.5/node_modules/es-abstract/test/helpers/getSymbolDescription.js b/scripts/2.5/node_modules/es-abstract/test/helpers/getSymbolDescription.js new file mode 100644 index 00000000..49af899f --- /dev/null +++ b/scripts/2.5/node_modules/es-abstract/test/helpers/getSymbolDescription.js @@ -0,0 +1,50 @@ +'use strict'; + +var test = require('tape'); +var debug = require('object-inspect'); +var forEach = require('foreach'); + +var v = require('./values'); +var getSymbolDescription = require('../../helpers/getSymbolDescription'); + +test('getSymbolDescription', function (t) { + t.test('no symbols', { skip: v.hasSymbols }, function (st) { + st['throws']( + getSymbolDescription, + SyntaxError, + 'requires Symbol support' + ); + + st.end(); + }); + + forEach(v.nonSymbolPrimitives.concat(v.objects), function (nonSymbol) { + t['throws']( + function () { getSymbolDescription(nonSymbol); }, + TypeError, + debug(nonSymbol) + ' is not a Symbol' + ); + }); + + t.test('with symbols', { skip: !v.hasSymbols }, function (st) { + forEach( + [ + [Symbol(), undefined], + [Symbol(undefined), undefined], + [Symbol(null), 'null'], + [Symbol(''), ''], + [Symbol.iterator, 'Symbol.iterator'], + [Symbol('foo'), 'foo'] + ], + function (pair) { + var sym = pair[0]; + var desc = pair[1]; + st.equal(getSymbolDescription(sym), desc, debug(sym) + ' yields ' + debug(desc)); + } + ); + + st.end(); + }); + + t.end(); +}); diff --git a/scripts/2.5/node_modules/es-abstract/test/helpers/values.js b/scripts/2.5/node_modules/es-abstract/test/helpers/values.js new file mode 100644 index 00000000..ccef743a --- /dev/null +++ b/scripts/2.5/node_modules/es-abstract/test/helpers/values.js @@ -0,0 +1,121 @@ +'use strict'; + +var assign = require('../../helpers/assign'); + +var hasSymbols = require('has-symbols')(); + +var coercibleObject = { valueOf: function () { return 3; }, toString: function () { return 42; } }; +var coercibleFnObject = { + valueOf: function () { return function valueOfFn() {}; }, + toString: function () { return 42; } +}; +var valueOfOnlyObject = { valueOf: function () { return 4; }, toString: function () { return {}; } }; +var toStringOnlyObject = { valueOf: function () { return {}; }, toString: function () { return 7; } }; +var uncoercibleObject = { valueOf: function () { return {}; }, toString: function () { return {}; } }; +var uncoercibleFnObject = { + valueOf: function () { return function valueOfFn() {}; }, + toString: function () { return function toStrFn() {}; } +}; +var objects = [{}, coercibleObject, coercibleFnObject, toStringOnlyObject, valueOfOnlyObject]; +var nullPrimitives = [undefined, null]; +var nonIntegerNumbers = [-1.3, 0.2, 1.8, 1 / 3]; +var zeroes = [0, -0]; +var infinities = [Infinity, -Infinity]; +var numbers = zeroes.concat([42], infinities, nonIntegerNumbers); +var strings = ['', 'foo', 'a\uD83D\uDCA9c']; +var booleans = [true, false]; +var symbols = hasSymbols ? [Symbol.iterator, Symbol('foo')] : []; +var nonSymbolPrimitives = [].concat(nullPrimitives, booleans, strings, numbers); +var nonNumberPrimitives = [].concat(nullPrimitives, booleans, strings, symbols); +var nonNullPrimitives = [].concat(booleans, strings, numbers, symbols); +var nonUndefinedPrimitives = [].concat(null, nonNullPrimitives); +var nonStrings = [].concat(nullPrimitives, booleans, numbers, symbols, objects); +var primitives = [].concat(nullPrimitives, nonNullPrimitives); +var nonPropertyKeys = [].concat(nullPrimitives, booleans, numbers, objects); +var propertyKeys = [].concat(strings, symbols); +var nonBooleans = [].concat(nullPrimitives, strings, symbols, numbers, objects); +var falsies = [].concat(nullPrimitives, false, '', 0, -0, NaN); +var truthies = [].concat(true, 'foo', 42, symbols, objects); +var timestamps = [].concat(0, 946713600000, 1546329600000); +var nonFunctions = [].concat(primitives, objects, [42]); +var nonArrays = [].concat(nonFunctions); + +var descriptors = { + configurable: function (descriptor) { + return assign(assign({}, descriptor), { '[[Configurable]]': true }); + }, + nonConfigurable: function (descriptor) { + return assign(assign({}, descriptor), { '[[Configurable]]': false }); + }, + enumerable: function (descriptor) { + return assign(assign({}, descriptor), { '[[Enumerable]]': true }); + }, + nonEnumerable: function (descriptor) { + return assign(assign({}, descriptor), { '[[Enumerable]]': false }); + }, + writable: function (descriptor) { + return assign(assign({}, descriptor), { '[[Writable]]': true }); + }, + nonWritable: function (descriptor) { + return assign(assign({}, descriptor), { '[[Writable]]': false }); + } +}; + +module.exports = { + coercibleObject: coercibleObject, + coercibleFnObject: coercibleFnObject, + valueOfOnlyObject: valueOfOnlyObject, + toStringOnlyObject: toStringOnlyObject, + uncoercibleObject: uncoercibleObject, + uncoercibleFnObject: uncoercibleFnObject, + objects: objects, + nonFunctions: nonFunctions, + nonArrays: nonArrays, + nullPrimitives: nullPrimitives, + numbers: numbers, + zeroes: zeroes, + infinities: infinities, + strings: strings, + booleans: booleans, + symbols: symbols, + hasSymbols: hasSymbols, + nonSymbolPrimitives: nonSymbolPrimitives, + nonNumberPrimitives: nonNumberPrimitives, + nonNullPrimitives: nonNullPrimitives, + nonUndefinedPrimitives: nonUndefinedPrimitives, + nonStrings: nonStrings, + nonNumbers: nonNumberPrimitives.concat(objects), + nonIntegerNumbers: nonIntegerNumbers, + primitives: primitives, + nonPropertyKeys: nonPropertyKeys, + propertyKeys: propertyKeys, + nonBooleans: nonBooleans, + falsies: falsies, + truthies: truthies, + timestamps: timestamps, + bothDescriptor: function () { + return { '[[Get]]': function () {}, '[[Value]]': true }; + }, + bothDescriptorWritable: function () { + return descriptors.writable({ '[[Get]]': function () {} }); + }, + accessorDescriptor: function (value) { + return descriptors.enumerable(descriptors.configurable({ + '[[Get]]': function get() { return value; } + })); + }, + mutatorDescriptor: function () { + return descriptors.enumerable(descriptors.configurable({ + '[[Set]]': function () {} + })); + }, + dataDescriptor: function (value) { + return descriptors.nonWritable({ + '[[Value]]': arguments.length > 0 ? value : 42 + }); + }, + genericDescriptor: function () { + return descriptors.configurable(descriptors.nonEnumerable()); + }, + descriptors: descriptors +}; diff --git a/scripts/2.5/node_modules/es-abstract/test/index.js b/scripts/2.5/node_modules/es-abstract/test/index.js new file mode 100644 index 00000000..a435044b --- /dev/null +++ b/scripts/2.5/node_modules/es-abstract/test/index.js @@ -0,0 +1,30 @@ +'use strict'; + +var ES = require('../'); +var test = require('tape'); + +var ESkeys = Object.keys(ES).sort(); +var ES6keys = Object.keys(ES.ES6).sort(); + +test('exposed properties', function (t) { + t.deepEqual(ESkeys, ES6keys.concat(['ES2019', 'ES2018', 'ES2017', 'ES7', 'ES2016', 'ES6', 'ES2015', 'ES5']).sort(), 'main ES object keys match ES6 keys'); + t.end(); +}); + +test('methods match', function (t) { + ES6keys.forEach(function (key) { + t.equal(ES.ES6[key], ES[key], 'method ' + key + ' on main ES object is ES6 method'); + }); + t.end(); +}); + +require('./GetIntrinsic'); + +require('./es5'); +require('./es6'); +require('./es2015'); +require('./es7'); +require('./es2016'); +require('./es2017'); +require('./es2018'); +require('./es2019'); diff --git a/scripts/2.5/node_modules/es-abstract/test/tests.js b/scripts/2.5/node_modules/es-abstract/test/tests.js new file mode 100644 index 00000000..eb8f91df --- /dev/null +++ b/scripts/2.5/node_modules/es-abstract/test/tests.js @@ -0,0 +1,4075 @@ +'use strict'; + +var test = require('tape'); + +var forEach = require('foreach'); +var is = require('object-is'); +var debug = require('object-inspect'); +var assign = require('object.assign'); +var keys = require('object-keys'); +var has = require('has'); +var arrowFns = require('make-arrow-function').list(); + +var getInferredName = require('../helpers/getInferredName'); +var assertRecordTests = require('./helpers/assertRecord'); +var v = require('./helpers/values'); +var diffOps = require('./diffOps'); + +var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || Math.pow(2, 53) - 1; + +var getArraySubclassWithSpeciesConstructor = function getArraySubclass(speciesConstructor) { + var Bar = function Bar() { + var inst = []; + Object.setPrototypeOf(inst, Bar.prototype); + Object.defineProperty(inst, 'constructor', { value: Bar }); + return inst; + }; + Bar.prototype = Object.create(Array.prototype); + Object.setPrototypeOf(Bar, Array); + Object.defineProperty(Bar, Symbol.species, { value: speciesConstructor }); + + return Bar; +}; + +var testIterator = function (t, iterator, expected) { + var resultCount = 0; + var result; + while (result = iterator.next(), !result.done) { // eslint-disable-line no-sequences + t.deepEqual(result, { done: false, value: expected[resultCount] }, 'result ' + resultCount); + resultCount += 1; + } + t.equal(resultCount, expected.length, 'expected ' + expected.length + ', got ' + resultCount); +}; + +var hasSpecies = v.hasSymbols && Symbol.species; + +var hasGroups = 'groups' in (/a/).exec('a'); +var groups = function groups(matchObject) { + return hasGroups ? assign(matchObject, { groups: matchObject.groups }) : matchObject; +}; + +var testEnumerableOwnNames = function (t, enumerableOwnNames) { + forEach(v.primitives, function (nonObject) { + t['throws']( + function () { enumerableOwnNames(nonObject); }, + debug(nonObject) + ' is not an Object' + ); + }); + + var Child = function Child() { + this.own = {}; + }; + Child.prototype = { + inherited: {} + }; + + var obj = new Child(); + + t.equal('own' in obj, true, 'has "own"'); + t.equal(has(obj, 'own'), true, 'has own "own"'); + t.equal(Object.prototype.propertyIsEnumerable.call(obj, 'own'), true, 'has enumerable "own"'); + + t.equal('inherited' in obj, true, 'has "inherited"'); + t.equal(has(obj, 'inherited'), false, 'has non-own "inherited"'); + t.equal(has(Child.prototype, 'inherited'), true, 'Child.prototype has own "inherited"'); + t.equal(Child.prototype.inherited, obj.inherited, 'Child.prototype.inherited === obj.inherited'); + t.equal(Object.prototype.propertyIsEnumerable.call(Child.prototype, 'inherited'), true, 'has enumerable "inherited"'); + + t.equal('toString' in obj, true, 'has "toString"'); + t.equal(has(obj, 'toString'), false, 'has non-own "toString"'); + t.equal(has(Object.prototype, 'toString'), true, 'Object.prototype has own "toString"'); + t.equal(Object.prototype.toString, obj.toString, 'Object.prototype.toString === obj.toString'); + // eslint-disable-next-line no-useless-call + t.equal(Object.prototype.propertyIsEnumerable.call(Object.prototype, 'toString'), false, 'has non-enumerable "toString"'); + + return obj; +}; + +var es2015 = function ES2015(ES, ops, expectedMissing, skips) { + test('has expected operations', function (t) { + var diff = diffOps(ES, ops, expectedMissing); + + t.deepEqual(diff.extra, [], 'no extra ops'); + + t.deepEqual(diff.missing, [], 'no unexpected missing ops'); + + t.end(); + }); + + test('ToPrimitive', function (t) { + t.test('primitives', function (st) { + var testPrimitive = function (primitive) { + st.ok(is(ES.ToPrimitive(primitive), primitive), debug(primitive) + ' is returned correctly'); + }; + forEach(v.primitives, testPrimitive); + st.end(); + }); + + t.test('objects', function (st) { + st.equal(ES.ToPrimitive(v.coercibleObject), 3, 'coercibleObject with no hint coerces to valueOf'); + st.ok(is(ES.ToPrimitive({}), '[object Object]'), '{} with no hint coerces to Object#toString'); + st.equal(ES.ToPrimitive(v.coercibleObject, Number), 3, 'coercibleObject with hint Number coerces to valueOf'); + st.ok(is(ES.ToPrimitive({}, Number), '[object Object]'), '{} with hint Number coerces to NaN'); + st.equal(ES.ToPrimitive(v.coercibleObject, String), 42, 'coercibleObject with hint String coerces to nonstringified toString'); + st.equal(ES.ToPrimitive({}, String), '[object Object]', '{} with hint String coerces to Object#toString'); + st.equal(ES.ToPrimitive(v.toStringOnlyObject), 7, 'toStringOnlyObject returns non-stringified toString'); + st.equal(ES.ToPrimitive(v.valueOfOnlyObject), 4, 'valueOfOnlyObject returns valueOf'); + st['throws'](function () { return ES.ToPrimitive(v.uncoercibleObject); }, TypeError, 'uncoercibleObject throws a TypeError'); + st.end(); + }); + + t.test('dates', function (st) { + var invalid = new Date(NaN); + st.equal(ES.ToPrimitive(invalid), Date.prototype.toString.call(invalid), 'invalid Date coerces to Date#toString'); + var now = new Date(); + st.equal(ES.ToPrimitive(now), Date.prototype.toString.call(now), 'Date coerces to Date#toString'); + st.end(); + }); + + t.end(); + }); + + test('ToBoolean', function (t) { + t.equal(false, ES.ToBoolean(undefined), 'undefined coerces to false'); + t.equal(false, ES.ToBoolean(null), 'null coerces to false'); + t.equal(false, ES.ToBoolean(false), 'false returns false'); + t.equal(true, ES.ToBoolean(true), 'true returns true'); + + t.test('numbers', function (st) { + forEach(v.zeroes.concat(NaN), function (falsyNumber) { + st.equal(false, ES.ToBoolean(falsyNumber), 'falsy number ' + falsyNumber + ' coerces to false'); + }); + forEach(v.infinities.concat([42, 1]), function (truthyNumber) { + st.equal(true, ES.ToBoolean(truthyNumber), 'truthy number ' + truthyNumber + ' coerces to true'); + }); + + st.end(); + }); + + t.equal(false, ES.ToBoolean(''), 'empty string coerces to false'); + t.equal(true, ES.ToBoolean('foo'), 'nonempty string coerces to true'); + + t.test('objects', function (st) { + forEach(v.objects, function (obj) { + st.equal(true, ES.ToBoolean(obj), 'object coerces to true'); + }); + st.equal(true, ES.ToBoolean(v.uncoercibleObject), 'uncoercibleObject coerces to true'); + + st.end(); + }); + + t.end(); + }); + + test('ToNumber', function (t) { + t.ok(is(NaN, ES.ToNumber(undefined)), 'undefined coerces to NaN'); + t.ok(is(ES.ToNumber(null), 0), 'null coerces to +0'); + t.ok(is(ES.ToNumber(false), 0), 'false coerces to +0'); + t.equal(1, ES.ToNumber(true), 'true coerces to 1'); + + t.test('numbers', function (st) { + st.ok(is(NaN, ES.ToNumber(NaN)), 'NaN returns itself'); + forEach(v.zeroes.concat(v.infinities, 42), function (num) { + st.equal(num, ES.ToNumber(num), num + ' returns itself'); + }); + forEach(['foo', '0', '4a', '2.0', 'Infinity', '-Infinity'], function (numString) { + st.ok(is(+numString, ES.ToNumber(numString)), '"' + numString + '" coerces to ' + Number(numString)); + }); + st.end(); + }); + + t.test('objects', function (st) { + forEach(v.objects, function (object) { + st.ok(is(ES.ToNumber(object), ES.ToNumber(ES.ToPrimitive(object))), 'object ' + object + ' coerces to same as ToPrimitive of object does'); + }); + st['throws'](function () { return ES.ToNumber(v.uncoercibleObject); }, TypeError, 'uncoercibleObject throws'); + st.end(); + }); + + t.test('binary literals', function (st) { + st.equal(ES.ToNumber('0b10'), 2, '0b10 is 2'); + st.equal(ES.ToNumber({ toString: function () { return '0b11'; } }), 3, 'Object that toStrings to 0b11 is 3'); + + st.equal(true, is(ES.ToNumber('0b12'), NaN), '0b12 is NaN'); + st.equal(true, is(ES.ToNumber({ toString: function () { return '0b112'; } }), NaN), 'Object that toStrings to 0b112 is NaN'); + st.end(); + }); + + t.test('octal literals', function (st) { + st.equal(ES.ToNumber('0o10'), 8, '0o10 is 8'); + st.equal(ES.ToNumber({ toString: function () { return '0o11'; } }), 9, 'Object that toStrings to 0o11 is 9'); + + st.equal(true, is(ES.ToNumber('0o18'), NaN), '0o18 is NaN'); + st.equal(true, is(ES.ToNumber({ toString: function () { return '0o118'; } }), NaN), 'Object that toStrings to 0o118 is NaN'); + st.end(); + }); + + t.test('signed hex numbers', function (st) { + st.equal(true, is(ES.ToNumber('-0xF'), NaN), '-0xF is NaN'); + st.equal(true, is(ES.ToNumber(' -0xF '), NaN), 'space-padded -0xF is NaN'); + st.equal(true, is(ES.ToNumber('+0xF'), NaN), '+0xF is NaN'); + st.equal(true, is(ES.ToNumber(' +0xF '), NaN), 'space-padded +0xF is NaN'); + + st.end(); + }); + + t.test('trimming of whitespace and non-whitespace characters', function (st) { + var whitespace = ' \t\x0b\f\xa0\ufeff\n\r\u2028\u2029\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000'; + st.equal(0, ES.ToNumber(whitespace + 0 + whitespace), 'whitespace is trimmed'); + + // Zero-width space (zws), next line character (nel), and non-character (bom) are not whitespace. + var nonWhitespaces = { + '\\u0085': '\u0085', + '\\u200b': '\u200b', + '\\ufffe': '\ufffe' + }; + + forEach(nonWhitespaces, function (desc, nonWS) { + st.equal(true, is(ES.ToNumber(nonWS + 0 + nonWS), NaN), 'non-whitespace ' + desc + ' not trimmed'); + }); + + st.end(); + }); + + forEach(v.symbols, function (symbol) { + t['throws']( + function () { ES.ToNumber(symbol); }, + TypeError, + 'Symbols can’t be converted to a Number: ' + debug(symbol) + ); + }); + + t.test('dates', function (st) { + var invalid = new Date(NaN); + st.ok(is(ES.ToNumber(invalid), NaN), 'invalid Date coerces to NaN'); + var now = Date.now(); + st.equal(ES.ToNumber(new Date(now)), now, 'Date coerces to timestamp'); + st.end(); + }); + + t.end(); + }); + + test('ToInteger', function (t) { + t.ok(is(0, ES.ToInteger(NaN)), 'NaN coerces to +0'); + forEach([0, Infinity, 42], function (num) { + t.ok(is(num, ES.ToInteger(num)), num + ' returns itself'); + t.ok(is(-num, ES.ToInteger(-num)), '-' + num + ' returns itself'); + }); + t.equal(3, ES.ToInteger(Math.PI), 'pi returns 3'); + t['throws'](function () { return ES.ToInteger(v.uncoercibleObject); }, TypeError, 'uncoercibleObject throws'); + t.end(); + }); + + test('ToInt32', function (t) { + t.ok(is(0, ES.ToInt32(NaN)), 'NaN coerces to +0'); + forEach([0, Infinity], function (num) { + t.ok(is(0, ES.ToInt32(num)), num + ' returns +0'); + t.ok(is(0, ES.ToInt32(-num)), '-' + num + ' returns +0'); + }); + t['throws'](function () { return ES.ToInt32(v.uncoercibleObject); }, TypeError, 'uncoercibleObject throws'); + t.ok(is(ES.ToInt32(0x100000000), 0), '2^32 returns +0'); + t.ok(is(ES.ToInt32(0x100000000 - 1), -1), '2^32 - 1 returns -1'); + t.ok(is(ES.ToInt32(0x80000000), -0x80000000), '2^31 returns -2^31'); + t.ok(is(ES.ToInt32(0x80000000 - 1), 0x80000000 - 1), '2^31 - 1 returns 2^31 - 1'); + forEach([0, Infinity, NaN, 0x100000000, 0x80000000, 0x10000, 0x42], function (num) { + t.ok(is(ES.ToInt32(num), ES.ToInt32(ES.ToUint32(num))), 'ToInt32(x) === ToInt32(ToUint32(x)) for 0x' + num.toString(16)); + t.ok(is(ES.ToInt32(-num), ES.ToInt32(ES.ToUint32(-num))), 'ToInt32(x) === ToInt32(ToUint32(x)) for -0x' + num.toString(16)); + }); + t.end(); + }); + + test('ToUint32', function (t) { + t.ok(is(0, ES.ToUint32(NaN)), 'NaN coerces to +0'); + forEach([0, Infinity], function (num) { + t.ok(is(0, ES.ToUint32(num)), num + ' returns +0'); + t.ok(is(0, ES.ToUint32(-num)), '-' + num + ' returns +0'); + }); + t['throws'](function () { return ES.ToUint32(v.uncoercibleObject); }, TypeError, 'uncoercibleObject throws'); + t.ok(is(ES.ToUint32(0x100000000), 0), '2^32 returns +0'); + t.ok(is(ES.ToUint32(0x100000000 - 1), 0x100000000 - 1), '2^32 - 1 returns 2^32 - 1'); + t.ok(is(ES.ToUint32(0x80000000), 0x80000000), '2^31 returns 2^31'); + t.ok(is(ES.ToUint32(0x80000000 - 1), 0x80000000 - 1), '2^31 - 1 returns 2^31 - 1'); + forEach([0, Infinity, NaN, 0x100000000, 0x80000000, 0x10000, 0x42], function (num) { + t.ok(is(ES.ToUint32(num), ES.ToUint32(ES.ToInt32(num))), 'ToUint32(x) === ToUint32(ToInt32(x)) for 0x' + num.toString(16)); + t.ok(is(ES.ToUint32(-num), ES.ToUint32(ES.ToInt32(-num))), 'ToUint32(x) === ToUint32(ToInt32(x)) for -0x' + num.toString(16)); + }); + t.end(); + }); + + test('ToInt16', function (t) { + t.ok(is(0, ES.ToInt16(NaN)), 'NaN coerces to +0'); + forEach([0, Infinity], function (num) { + t.ok(is(0, ES.ToInt16(num)), num + ' returns +0'); + t.ok(is(0, ES.ToInt16(-num)), '-' + num + ' returns +0'); + }); + t['throws'](function () { return ES.ToInt16(v.uncoercibleObject); }, TypeError, 'uncoercibleObject throws'); + t.ok(is(ES.ToInt16(0x100000000), 0), '2^32 returns +0'); + t.ok(is(ES.ToInt16(0x100000000 - 1), -1), '2^32 - 1 returns -1'); + t.ok(is(ES.ToInt16(0x80000000), 0), '2^31 returns +0'); + t.ok(is(ES.ToInt16(0x80000000 - 1), -1), '2^31 - 1 returns -1'); + t.ok(is(ES.ToInt16(0x10000), 0), '2^16 returns +0'); + t.ok(is(ES.ToInt16(0x10000 - 1), -1), '2^16 - 1 returns -1'); + t.end(); + }); + + test('ToUint16', function (t) { + t.ok(is(0, ES.ToUint16(NaN)), 'NaN coerces to +0'); + forEach([0, Infinity], function (num) { + t.ok(is(0, ES.ToUint16(num)), num + ' returns +0'); + t.ok(is(0, ES.ToUint16(-num)), '-' + num + ' returns +0'); + }); + t['throws'](function () { return ES.ToUint16(v.uncoercibleObject); }, TypeError, 'uncoercibleObject throws'); + t.ok(is(ES.ToUint16(0x100000000), 0), '2^32 returns +0'); + t.ok(is(ES.ToUint16(0x100000000 - 1), 0x10000 - 1), '2^32 - 1 returns 2^16 - 1'); + t.ok(is(ES.ToUint16(0x80000000), 0), '2^31 returns +0'); + t.ok(is(ES.ToUint16(0x80000000 - 1), 0x10000 - 1), '2^31 - 1 returns 2^16 - 1'); + t.ok(is(ES.ToUint16(0x10000), 0), '2^16 returns +0'); + t.ok(is(ES.ToUint16(0x10000 - 1), 0x10000 - 1), '2^16 - 1 returns 2^16 - 1'); + t.end(); + }); + + test('ToInt8', function (t) { + t.ok(is(0, ES.ToInt8(NaN)), 'NaN coerces to +0'); + forEach([0, Infinity], function (num) { + t.ok(is(0, ES.ToInt8(num)), num + ' returns +0'); + t.ok(is(0, ES.ToInt8(-num)), '-' + num + ' returns +0'); + }); + t['throws'](function () { return ES.ToInt8(v.uncoercibleObject); }, TypeError, 'uncoercibleObject throws'); + t.ok(is(ES.ToInt8(0x100000000), 0), '2^32 returns +0'); + t.ok(is(ES.ToInt8(0x100000000 - 1), -1), '2^32 - 1 returns -1'); + t.ok(is(ES.ToInt8(0x80000000), 0), '2^31 returns +0'); + t.ok(is(ES.ToInt8(0x80000000 - 1), -1), '2^31 - 1 returns -1'); + t.ok(is(ES.ToInt8(0x10000), 0), '2^16 returns +0'); + t.ok(is(ES.ToInt8(0x10000 - 1), -1), '2^16 - 1 returns -1'); + t.ok(is(ES.ToInt8(0x100), 0), '2^8 returns +0'); + t.ok(is(ES.ToInt8(0x100 - 1), -1), '2^8 - 1 returns -1'); + t.ok(is(ES.ToInt8(0x10), 0x10), '2^4 returns 2^4'); + t.end(); + }); + + test('ToUint8', function (t) { + t.ok(is(0, ES.ToUint8(NaN)), 'NaN coerces to +0'); + forEach([0, Infinity], function (num) { + t.ok(is(0, ES.ToUint8(num)), num + ' returns +0'); + t.ok(is(0, ES.ToUint8(-num)), '-' + num + ' returns +0'); + }); + t['throws'](function () { return ES.ToUint8(v.uncoercibleObject); }, TypeError, 'uncoercibleObject throws'); + t.ok(is(ES.ToUint8(0x100000000), 0), '2^32 returns +0'); + t.ok(is(ES.ToUint8(0x100000000 - 1), 0x100 - 1), '2^32 - 1 returns 2^8 - 1'); + t.ok(is(ES.ToUint8(0x80000000), 0), '2^31 returns +0'); + t.ok(is(ES.ToUint8(0x80000000 - 1), 0x100 - 1), '2^31 - 1 returns 2^8 - 1'); + t.ok(is(ES.ToUint8(0x10000), 0), '2^16 returns +0'); + t.ok(is(ES.ToUint8(0x10000 - 1), 0x100 - 1), '2^16 - 1 returns 2^8 - 1'); + t.ok(is(ES.ToUint8(0x100), 0), '2^8 returns +0'); + t.ok(is(ES.ToUint8(0x100 - 1), 0x100 - 1), '2^8 - 1 returns 2^16 - 1'); + t.ok(is(ES.ToUint8(0x10), 0x10), '2^4 returns 2^4'); + t.ok(is(ES.ToUint8(0x10 - 1), 0x10 - 1), '2^4 - 1 returns 2^4 - 1'); + t.end(); + }); + + test('ToUint8Clamp', function (t) { + t.ok(is(0, ES.ToUint8Clamp(NaN)), 'NaN coerces to +0'); + t.ok(is(0, ES.ToUint8Clamp(0)), '+0 returns +0'); + t.ok(is(0, ES.ToUint8Clamp(-0)), '-0 returns +0'); + t.ok(is(0, ES.ToUint8Clamp(-Infinity)), '-Infinity returns +0'); + t['throws'](function () { return ES.ToUint8Clamp(v.uncoercibleObject); }, TypeError, 'uncoercibleObject throws'); + forEach([255, 256, 0x100000, Infinity], function (number) { + t.ok(is(255, ES.ToUint8Clamp(number)), number + ' coerces to 255'); + }); + t.equal(1, ES.ToUint8Clamp(1.49), '1.49 coerces to 1'); + t.equal(2, ES.ToUint8Clamp(1.5), '1.5 coerces to 2, because 2 is even'); + t.equal(2, ES.ToUint8Clamp(1.51), '1.51 coerces to 2'); + + t.equal(2, ES.ToUint8Clamp(2.49), '2.49 coerces to 2'); + t.equal(2, ES.ToUint8Clamp(2.5), '2.5 coerces to 2, because 2 is even'); + t.equal(3, ES.ToUint8Clamp(2.51), '2.51 coerces to 3'); + t.end(); + }); + + test('ToString', function (t) { + forEach(v.objects.concat(v.nonSymbolPrimitives), function (item) { + t.equal(ES.ToString(item), String(item), 'ES.ToString(' + debug(item) + ') ToStrings to String(' + debug(item) + ')'); + }); + + t['throws'](function () { return ES.ToString(v.uncoercibleObject); }, TypeError, 'uncoercibleObject throws'); + + forEach(v.symbols, function (symbol) { + t['throws'](function () { return ES.ToString(symbol); }, TypeError, debug(symbol) + ' throws'); + }); + t.end(); + }); + + test('ToObject', function (t) { + t['throws'](function () { return ES.ToObject(undefined); }, TypeError, 'undefined throws'); + t['throws'](function () { return ES.ToObject(null); }, TypeError, 'null throws'); + forEach(v.numbers, function (number) { + var obj = ES.ToObject(number); + t.equal(typeof obj, 'object', 'number ' + number + ' coerces to object'); + t.equal(true, obj instanceof Number, 'object of ' + number + ' is Number object'); + t.ok(is(obj.valueOf(), number), 'object of ' + number + ' coerces to ' + number); + }); + t.end(); + }); + + test('RequireObjectCoercible', function (t) { + t.equal(false, 'CheckObjectCoercible' in ES, 'CheckObjectCoercible -> RequireObjectCoercible in ES6'); + t['throws'](function () { return ES.RequireObjectCoercible(undefined); }, TypeError, 'undefined throws'); + t['throws'](function () { return ES.RequireObjectCoercible(null); }, TypeError, 'null throws'); + var isCoercible = function (value) { + t.doesNotThrow(function () { return ES.RequireObjectCoercible(value); }, debug(value) + ' does not throw'); + }; + forEach(v.objects.concat(v.nonNullPrimitives), isCoercible); + t.end(); + }); + + test('IsCallable', function (t) { + t.equal(true, ES.IsCallable(function () {}), 'function is callable'); + var nonCallables = [/a/g, {}, Object.prototype, NaN].concat(v.nonFunctions); + forEach(nonCallables, function (nonCallable) { + t.equal(false, ES.IsCallable(nonCallable), debug(nonCallable) + ' is not callable'); + }); + t.end(); + }); + + test('SameValue', function (t) { + t.equal(true, ES.SameValue(NaN, NaN), 'NaN is SameValue as NaN'); + t.equal(false, ES.SameValue(0, -0), '+0 is not SameValue as -0'); + forEach(v.objects.concat(v.primitives), function (val) { + t.equal(val === val, ES.SameValue(val, val), debug(val) + ' is SameValue to itself'); + }); + t.end(); + }); + + test('SameValueZero', function (t) { + t.equal(true, ES.SameValueZero(NaN, NaN), 'NaN is SameValueZero as NaN'); + t.equal(true, ES.SameValueZero(0, -0), '+0 is SameValueZero as -0'); + forEach(v.objects.concat(v.primitives), function (val) { + t.equal(val === val, ES.SameValueZero(val, val), debug(val) + ' is SameValueZero to itself'); + }); + t.end(); + }); + + test('ToPropertyKey', function (t) { + forEach(v.objects.concat(v.nonSymbolPrimitives), function (value) { + t.equal(ES.ToPropertyKey(value), String(value), 'ToPropertyKey(value) === String(value) for non-Symbols'); + }); + + forEach(v.symbols, function (symbol) { + t.equal( + ES.ToPropertyKey(symbol), + symbol, + 'ToPropertyKey(' + debug(symbol) + ') === ' + debug(symbol) + ); + t.equal( + ES.ToPropertyKey(Object(symbol)), + symbol, + 'ToPropertyKey(' + debug(Object(symbol)) + ') === ' + debug(symbol) + ); + }); + + t.end(); + }); + + test('ToLength', function (t) { + t['throws'](function () { return ES.ToLength(v.uncoercibleObject); }, TypeError, 'uncoercibleObject throws a TypeError'); + t.equal(3, ES.ToLength(v.coercibleObject), 'coercibleObject coerces to 3'); + t.equal(42, ES.ToLength('42.5'), '"42.5" coerces to 42'); + t.equal(7, ES.ToLength(7.3), '7.3 coerces to 7'); + forEach([-0, -1, -42, -Infinity], function (negative) { + t.ok(is(0, ES.ToLength(negative)), negative + ' coerces to +0'); + }); + t.equal(MAX_SAFE_INTEGER, ES.ToLength(MAX_SAFE_INTEGER + 1), '2^53 coerces to 2^53 - 1'); + t.equal(MAX_SAFE_INTEGER, ES.ToLength(MAX_SAFE_INTEGER + 3), '2^53 + 2 coerces to 2^53 - 1'); + t.end(); + }); + + test('IsArray', function (t) { + t.equal(true, ES.IsArray([]), '[] is array'); + t.equal(false, ES.IsArray({}), '{} is not array'); + t.equal(false, ES.IsArray({ length: 1, 0: true }), 'arraylike object is not array'); + forEach(v.objects.concat(v.primitives), function (value) { + t.equal(false, ES.IsArray(value), debug(value) + ' is not array'); + }); + t.end(); + }); + + test('IsRegExp', function (t) { + forEach([/a/g, new RegExp('a', 'g')], function (regex) { + t.equal(true, ES.IsRegExp(regex), regex + ' is regex'); + }); + + forEach(v.objects.concat(v.primitives), function (nonRegex) { + t.equal(false, ES.IsRegExp(nonRegex), debug(nonRegex) + ' is not regex'); + }); + + t.test('Symbol.match', { skip: !v.hasSymbols || !Symbol.match }, function (st) { + var obj = {}; + obj[Symbol.match] = true; + st.equal(true, ES.IsRegExp(obj), 'object with truthy Symbol.match is regex'); + + var regex = /a/; + regex[Symbol.match] = false; + st.equal(false, ES.IsRegExp(regex), 'regex with falsy Symbol.match is not regex'); + + st.end(); + }); + + t.end(); + }); + + test('IsPropertyKey', function (t) { + forEach(v.numbers.concat(v.objects), function (notKey) { + t.equal(false, ES.IsPropertyKey(notKey), debug(notKey) + ' is not property key'); + }); + + t.equal(true, ES.IsPropertyKey('foo'), 'string is property key'); + + forEach(v.symbols, function (symbol) { + t.equal(true, ES.IsPropertyKey(symbol), debug(symbol) + ' is property key'); + }); + t.end(); + }); + + test('IsInteger', function (t) { + for (var i = -100; i < 100; i += 10) { + t.equal(true, ES.IsInteger(i), i + ' is integer'); + t.equal(false, ES.IsInteger(i + 0.2), (i + 0.2) + ' is not integer'); + } + t.equal(true, ES.IsInteger(-0), '-0 is integer'); + var notInts = v.nonNumbers.concat(v.nonIntegerNumbers, v.infinities, [NaN, [], new Date()]); + forEach(notInts, function (notInt) { + t.equal(false, ES.IsInteger(notInt), debug(notInt) + ' is not integer'); + }); + t.equal(false, ES.IsInteger(v.uncoercibleObject), 'uncoercibleObject is not integer'); + t.end(); + }); + + test('IsExtensible', function (t) { + forEach(v.objects, function (object) { + t.equal(true, ES.IsExtensible(object), debug(object) + ' object is extensible'); + }); + forEach(v.primitives, function (primitive) { + t.equal(false, ES.IsExtensible(primitive), debug(primitive) + ' is not extensible'); + }); + if (Object.preventExtensions) { + t.equal(false, ES.IsExtensible(Object.preventExtensions({})), 'object with extensions prevented is not extensible'); + } + t.end(); + }); + + test('CanonicalNumericIndexString', function (t) { + var throwsOnNonString = function (notString) { + t['throws']( + function () { return ES.CanonicalNumericIndexString(notString); }, + TypeError, + debug(notString) + ' is not a string' + ); + }; + forEach(v.objects.concat(v.numbers), throwsOnNonString); + t.ok(is(-0, ES.CanonicalNumericIndexString('-0')), '"-0" returns -0'); + for (var i = -50; i < 50; i += 10) { + t.equal(i, ES.CanonicalNumericIndexString(String(i)), '"' + i + '" returns ' + i); + t.equal(undefined, ES.CanonicalNumericIndexString(String(i) + 'a'), '"' + i + 'a" returns undefined'); + } + t.end(); + }); + + test('IsConstructor', function (t) { + t.equal(true, ES.IsConstructor(function () {}), 'function is constructor'); + t.equal(false, ES.IsConstructor(/a/g), 'regex is not constructor'); + forEach(v.objects, function (object) { + t.equal(false, ES.IsConstructor(object), object + ' object is not constructor'); + }); + + try { + var foo = Function('return class Foo {}')(); // eslint-disable-line no-new-func + t.equal(ES.IsConstructor(foo), true, 'class is constructor'); + } catch (e) { + t.comment('SKIP: class syntax not supported.'); + } + t.end(); + }); + + test('Call', function (t) { + var receiver = {}; + var notFuncs = v.nonFunctions.concat([/a/g, new RegExp('a', 'g')]); + t.plan(notFuncs.length + 4); + var throwsIfNotCallable = function (notFunc) { + t['throws']( + function () { return ES.Call(notFunc, receiver); }, + TypeError, + debug(notFunc) + ' (' + typeof notFunc + ') is not callable' + ); + }; + forEach(notFuncs, throwsIfNotCallable); + ES.Call( + function (a, b) { + t.equal(this, receiver, 'context matches expected'); + t.deepEqual([a, b], [1, 2], 'named args are correct'); + t.equal(arguments.length, 3, 'extra argument was passed'); + t.equal(arguments[2], 3, 'extra argument was correct'); + }, + receiver, + [1, 2, 3] + ); + t.end(); + }); + + test('GetV', function (t) { + t['throws'](function () { return ES.GetV({ 7: 7 }, 7); }, TypeError, 'Throws a TypeError if `P` is not a property key'); + var obj = { a: function () {} }; + t.equal(ES.GetV(obj, 'a'), obj.a, 'returns property if it exists'); + t.equal(ES.GetV(obj, 'b'), undefined, 'returns undefiend if property does not exist'); + t.end(); + }); + + test('GetMethod', function (t) { + t['throws'](function () { return ES.GetMethod({ 7: 7 }, 7); }, TypeError, 'Throws a TypeError if `P` is not a property key'); + t.equal(ES.GetMethod({}, 'a'), undefined, 'returns undefined in property is undefined'); + t.equal(ES.GetMethod({ a: null }, 'a'), undefined, 'returns undefined if property is null'); + t.equal(ES.GetMethod({ a: undefined }, 'a'), undefined, 'returns undefined if property is undefined'); + var obj = { a: function () {} }; + t['throws'](function () { ES.GetMethod({ a: 'b' }, 'a'); }, TypeError, 'throws TypeError if property exists and is not callable'); + t.equal(ES.GetMethod(obj, 'a'), obj.a, 'returns property if it is callable'); + t.end(); + }); + + test('Get', function (t) { + t['throws'](function () { return ES.Get('a', 'a'); }, TypeError, 'Throws a TypeError if `O` is not an Object'); + t['throws'](function () { return ES.Get({ 7: 7 }, 7); }, TypeError, 'Throws a TypeError if `P` is not a property key'); + + var value = {}; + t.test('Symbols', { skip: !v.hasSymbols }, function (st) { + var sym = Symbol('sym'); + var obj = {}; + obj[sym] = value; + st.equal(ES.Get(obj, sym), value, 'returns property `P` if it exists on object `O`'); + st.end(); + }); + t.equal(ES.Get({ a: value }, 'a'), value, 'returns property `P` if it exists on object `O`'); + t.end(); + }); + + test('Type', { skip: !v.hasSymbols }, function (t) { + t.equal(ES.Type(Symbol.iterator), 'Symbol', 'Type(Symbol.iterator) is Symbol'); + t.end(); + }); + + test('SpeciesConstructor', function (t) { + t['throws'](function () { ES.SpeciesConstructor(null); }, TypeError); + t['throws'](function () { ES.SpeciesConstructor(undefined); }, TypeError); + + var defaultConstructor = function Foo() {}; + + t.equal( + ES.SpeciesConstructor({ constructor: undefined }, defaultConstructor), + defaultConstructor, + 'undefined constructor returns defaultConstructor' + ); + + t['throws']( + function () { return ES.SpeciesConstructor({ constructor: null }, defaultConstructor); }, + TypeError, + 'non-undefined non-object constructor throws' + ); + + t.test('with Symbol.species', { skip: !hasSpecies }, function (st) { + var Bar = function Bar() {}; + Bar[Symbol.species] = null; + + st.equal( + ES.SpeciesConstructor(new Bar(), defaultConstructor), + defaultConstructor, + 'undefined/null Symbol.species returns default constructor' + ); + + var Baz = function Baz() {}; + Baz[Symbol.species] = Bar; + st.equal( + ES.SpeciesConstructor(new Baz(), defaultConstructor), + Bar, + 'returns Symbol.species constructor value' + ); + + Baz[Symbol.species] = {}; + st['throws']( + function () { ES.SpeciesConstructor(new Baz(), defaultConstructor); }, + TypeError, + 'throws when non-constructor non-null non-undefined species value found' + ); + + st.end(); + }); + + t.end(); + }); + + test('IsPropertyDescriptor', { skip: skips && skips.IsPropertyDescriptor }, function (t) { + forEach(v.nonUndefinedPrimitives, function (primitive) { + t.equal( + ES.IsPropertyDescriptor(primitive), + false, + debug(primitive) + ' is not a Property Descriptor' + ); + }); + + t.equal(ES.IsPropertyDescriptor({ invalid: true }), false, 'invalid keys not allowed on a Property Descriptor'); + + t.equal(ES.IsPropertyDescriptor({}), true, 'empty object is an incomplete Property Descriptor'); + + t.equal(ES.IsPropertyDescriptor(v.accessorDescriptor()), true, 'accessor descriptor is a Property Descriptor'); + t.equal(ES.IsPropertyDescriptor(v.mutatorDescriptor()), true, 'mutator descriptor is a Property Descriptor'); + t.equal(ES.IsPropertyDescriptor(v.dataDescriptor()), true, 'data descriptor is a Property Descriptor'); + t.equal(ES.IsPropertyDescriptor(v.genericDescriptor()), true, 'generic descriptor is a Property Descriptor'); + + t['throws']( + function () { + ES.IsPropertyDescriptor(v.bothDescriptor()); + }, TypeError, + 'a Property Descriptor can not be both a Data and an Accessor Descriptor' + ); + + t.end(); + }); + + assertRecordTests(ES, test); + + test('IsAccessorDescriptor', function (t) { + forEach(v.nonUndefinedPrimitives, function (primitive) { + t['throws']( + function () { ES.IsAccessorDescriptor(primitive); }, + TypeError, + debug(primitive) + ' is not a Property Descriptor' + ); + }); + + t.equal(ES.IsAccessorDescriptor(), false, 'no value is not an Accessor Descriptor'); + t.equal(ES.IsAccessorDescriptor(undefined), false, 'undefined value is not an Accessor Descriptor'); + + t.equal(ES.IsAccessorDescriptor(v.accessorDescriptor()), true, 'accessor descriptor is an Accessor Descriptor'); + t.equal(ES.IsAccessorDescriptor(v.mutatorDescriptor()), true, 'mutator descriptor is an Accessor Descriptor'); + t.equal(ES.IsAccessorDescriptor(v.dataDescriptor()), false, 'data descriptor is not an Accessor Descriptor'); + t.equal(ES.IsAccessorDescriptor(v.genericDescriptor()), false, 'generic descriptor is not an Accessor Descriptor'); + + t.end(); + }); + + test('IsDataDescriptor', function (t) { + forEach(v.nonUndefinedPrimitives, function (primitive) { + t['throws']( + function () { ES.IsDataDescriptor(primitive); }, + TypeError, + debug(primitive) + ' is not a Property Descriptor' + ); + }); + + t.equal(ES.IsDataDescriptor(), false, 'no value is not a Data Descriptor'); + t.equal(ES.IsDataDescriptor(undefined), false, 'undefined value is not a Data Descriptor'); + + t.equal(ES.IsDataDescriptor(v.accessorDescriptor()), false, 'accessor descriptor is not a Data Descriptor'); + t.equal(ES.IsDataDescriptor(v.mutatorDescriptor()), false, 'mutator descriptor is not a Data Descriptor'); + t.equal(ES.IsDataDescriptor(v.dataDescriptor()), true, 'data descriptor is a Data Descriptor'); + t.equal(ES.IsDataDescriptor(v.genericDescriptor()), false, 'generic descriptor is not a Data Descriptor'); + + t.end(); + }); + + test('IsGenericDescriptor', function (t) { + forEach(v.nonUndefinedPrimitives, function (primitive) { + t['throws']( + function () { ES.IsGenericDescriptor(primitive); }, + TypeError, + debug(primitive) + ' is not a Property Descriptor' + ); + }); + + t.equal(ES.IsGenericDescriptor(), false, 'no value is not a Data Descriptor'); + t.equal(ES.IsGenericDescriptor(undefined), false, 'undefined value is not a Data Descriptor'); + + t.equal(ES.IsGenericDescriptor(v.accessorDescriptor()), false, 'accessor descriptor is not a generic Descriptor'); + t.equal(ES.IsGenericDescriptor(v.mutatorDescriptor()), false, 'mutator descriptor is not a generic Descriptor'); + t.equal(ES.IsGenericDescriptor(v.dataDescriptor()), false, 'data descriptor is not a generic Descriptor'); + + t.equal(ES.IsGenericDescriptor(v.genericDescriptor()), true, 'generic descriptor is a generic Descriptor'); + + t.end(); + }); + + test('FromPropertyDescriptor', function (t) { + t.equal(ES.FromPropertyDescriptor(), undefined, 'no value begets undefined'); + t.equal(ES.FromPropertyDescriptor(undefined), undefined, 'undefined value begets undefined'); + + forEach(v.nonUndefinedPrimitives, function (primitive) { + t['throws']( + function () { ES.FromPropertyDescriptor(primitive); }, + TypeError, + debug(primitive) + ' is not a Property Descriptor' + ); + }); + + var accessor = v.accessorDescriptor(); + t.deepEqual(ES.FromPropertyDescriptor(accessor), { + get: accessor['[[Get]]'], + enumerable: !!accessor['[[Enumerable]]'], + configurable: !!accessor['[[Configurable]]'] + }); + + var mutator = v.mutatorDescriptor(); + t.deepEqual(ES.FromPropertyDescriptor(mutator), { + set: mutator['[[Set]]'], + enumerable: !!mutator['[[Enumerable]]'], + configurable: !!mutator['[[Configurable]]'] + }); + var data = v.dataDescriptor(); + t.deepEqual(ES.FromPropertyDescriptor(data), { + value: data['[[Value]]'], + writable: data['[[Writable]]'] + }); + + t.deepEqual(ES.FromPropertyDescriptor(v.genericDescriptor()), { + enumerable: false, + configurable: true + }); + + t.end(); + }); + + test('ToPropertyDescriptor', function (t) { + forEach(v.nonUndefinedPrimitives, function (primitive) { + t['throws']( + function () { ES.ToPropertyDescriptor(primitive); }, + TypeError, + debug(primitive) + ' is not an Object' + ); + }); + + var accessor = v.accessorDescriptor(); + t.deepEqual(ES.ToPropertyDescriptor({ + get: accessor['[[Get]]'], + enumerable: !!accessor['[[Enumerable]]'], + configurable: !!accessor['[[Configurable]]'] + }), accessor); + + var mutator = v.mutatorDescriptor(); + t.deepEqual(ES.ToPropertyDescriptor({ + set: mutator['[[Set]]'], + enumerable: !!mutator['[[Enumerable]]'], + configurable: !!mutator['[[Configurable]]'] + }), mutator); + + var data = v.dataDescriptor(); + t.deepEqual(ES.ToPropertyDescriptor({ + value: data['[[Value]]'], + writable: data['[[Writable]]'], + configurable: !!data['[[Configurable]]'] + }), assign(data, { '[[Configurable]]': false })); + + var both = v.bothDescriptor(); + t['throws']( + function () { + ES.FromPropertyDescriptor({ get: both['[[Get]]'], value: both['[[Value]]'] }); + }, + TypeError, + 'data and accessor descriptors are mutually exclusive' + ); + + t.end(); + }); + + test('CompletePropertyDescriptor', function (t) { + forEach(v.nonUndefinedPrimitives, function (primitive) { + t['throws']( + function () { ES.CompletePropertyDescriptor(primitive); }, + TypeError, + debug(primitive) + ' is not a Property Descriptor' + ); + }); + + var generic = v.genericDescriptor(); + t.deepEqual( + ES.CompletePropertyDescriptor(generic), + { + '[[Configurable]]': !!generic['[[Configurable]]'], + '[[Enumerable]]': !!generic['[[Enumerable]]'], + '[[Value]]': undefined, + '[[Writable]]': false + }, + 'completes a Generic Descriptor' + ); + + var data = v.dataDescriptor(); + t.deepEqual( + ES.CompletePropertyDescriptor(data), + { + '[[Configurable]]': !!data['[[Configurable]]'], + '[[Enumerable]]': false, + '[[Value]]': data['[[Value]]'], + '[[Writable]]': !!data['[[Writable]]'] + }, + 'completes a Data Descriptor' + ); + + var accessor = v.accessorDescriptor(); + t.deepEqual( + ES.CompletePropertyDescriptor(accessor), + { + '[[Get]]': accessor['[[Get]]'], + '[[Enumerable]]': !!accessor['[[Enumerable]]'], + '[[Configurable]]': !!accessor['[[Configurable]]'], + '[[Set]]': undefined + }, + 'completes an Accessor Descriptor' + ); + + var mutator = v.mutatorDescriptor(); + t.deepEqual( + ES.CompletePropertyDescriptor(mutator), + { + '[[Set]]': mutator['[[Set]]'], + '[[Enumerable]]': !!mutator['[[Enumerable]]'], + '[[Configurable]]': !!mutator['[[Configurable]]'], + '[[Get]]': undefined + }, + 'completes a mutator Descriptor' + ); + + t['throws']( + function () { ES.CompletePropertyDescriptor(v.bothDescriptor()); }, + TypeError, + 'data and accessor descriptors are mutually exclusive' + ); + + t.end(); + }); + + test('Set', function (t) { + forEach(v.primitives, function (primitive) { + t['throws']( + function () { ES.Set(primitive, '', null, false); }, + TypeError, + debug(primitive) + ' is not an Object' + ); + }); + + forEach(v.nonPropertyKeys, function (nonKey) { + t['throws']( + function () { ES.Set({}, nonKey, null, false); }, + TypeError, + debug(nonKey) + ' is not a Property Key' + ); + }); + + forEach(v.nonBooleans, function (nonBoolean) { + t['throws']( + function () { ES.Set({}, '', null, nonBoolean); }, + TypeError, + debug(nonBoolean) + ' is not a Boolean' + ); + }); + + var o = {}; + var value = {}; + ES.Set(o, 'key', value, true); + t.deepEqual(o, { key: value }, 'key is set'); + + t.test('nonwritable', { skip: !Object.defineProperty }, function (st) { + var obj = { a: value }; + Object.defineProperty(obj, 'a', { writable: false }); + + st['throws']( + function () { ES.Set(obj, 'a', value, true); }, + TypeError, + 'can not Set nonwritable property' + ); + + st.doesNotThrow( + function () { ES.Set(obj, 'a', value, false); }, + 'setting Throw to false prevents an exception' + ); + + st.end(); + }); + + t.test('nonconfigurable', { skip: !Object.defineProperty }, function (st) { + var obj = { a: value }; + Object.defineProperty(obj, 'a', { configurable: false }); + + ES.Set(obj, 'a', value, true); + st.deepEqual(obj, { a: value }, 'key is set'); + + st.end(); + }); + + t.end(); + }); + + test('HasOwnProperty', function (t) { + forEach(v.primitives, function (primitive) { + t['throws']( + function () { ES.HasOwnProperty(primitive, 'key'); }, + TypeError, + debug(primitive) + ' is not an Object' + ); + }); + + forEach(v.nonPropertyKeys, function (nonKey) { + t['throws']( + function () { ES.HasOwnProperty({}, nonKey); }, + TypeError, + debug(nonKey) + ' is not a Property Key' + ); + }); + + t.equal(ES.HasOwnProperty({}, 'toString'), false, 'inherited properties are not own'); + t.equal( + ES.HasOwnProperty({ toString: 1 }, 'toString'), + true, + 'shadowed inherited own properties are own' + ); + t.equal(ES.HasOwnProperty({ a: 1 }, 'a'), true, 'own properties are own'); + + t.end(); + }); + + test('HasProperty', function (t) { + forEach(v.primitives, function (primitive) { + t['throws']( + function () { ES.HasProperty(primitive, 'key'); }, + TypeError, + debug(primitive) + ' is not an Object' + ); + }); + + forEach(v.nonPropertyKeys, function (nonKey) { + t['throws']( + function () { ES.HasProperty({}, nonKey); }, + TypeError, + debug(nonKey) + ' is not a Property Key' + ); + }); + + t.equal(ES.HasProperty({}, 'nope'), false, 'object does not have nonexistent properties'); + t.equal(ES.HasProperty({}, 'toString'), true, 'object has inherited properties'); + t.equal( + ES.HasProperty({ toString: 1 }, 'toString'), + true, + 'object has shadowed inherited own properties' + ); + t.equal(ES.HasProperty({ a: 1 }, 'a'), true, 'object has own properties'); + + t.end(); + }); + + test('IsConcatSpreadable', function (t) { + forEach(v.primitives, function (primitive) { + t.equal(ES.IsConcatSpreadable(primitive), false, debug(primitive) + ' is not an Object'); + }); + + var hasSymbolConcatSpreadable = v.hasSymbols && Symbol.isConcatSpreadable; + t.test('Symbol.isConcatSpreadable', { skip: !hasSymbolConcatSpreadable }, function (st) { + forEach(v.falsies, function (falsy) { + var obj = {}; + obj[Symbol.isConcatSpreadable] = falsy; + st.equal( + ES.IsConcatSpreadable(obj), + false, + 'an object with ' + debug(falsy) + ' as Symbol.isConcatSpreadable is not concat spreadable' + ); + }); + + forEach(v.truthies, function (truthy) { + var obj = {}; + obj[Symbol.isConcatSpreadable] = truthy; + st.equal( + ES.IsConcatSpreadable(obj), + true, + 'an object with ' + debug(truthy) + ' as Symbol.isConcatSpreadable is concat spreadable' + ); + }); + + st.end(); + }); + + forEach(v.objects, function (object) { + t.equal( + ES.IsConcatSpreadable(object), + false, + 'non-array without Symbol.isConcatSpreadable is not concat spreadable' + ); + }); + + t.equal(ES.IsConcatSpreadable([]), true, 'arrays are concat spreadable'); + + t.end(); + }); + + test('Invoke', function (t) { + forEach(v.nonPropertyKeys, function (nonKey) { + t['throws']( + function () { ES.Invoke({}, nonKey); }, + TypeError, + debug(nonKey) + ' is not a Property Key' + ); + }); + + t['throws'](function () { ES.Invoke({ o: false }, 'o'); }, TypeError, 'fails on a non-function'); + + t.test('invoked callback', function (st) { + var aValue = {}; + var bValue = {}; + var obj = { + f: function (a) { + st.equal(arguments.length, 2, '2 args passed'); + st.equal(a, aValue, 'first arg is correct'); + st.equal(arguments[1], bValue, 'second arg is correct'); + } + }; + st.plan(3); + ES.Invoke(obj, 'f', aValue, bValue); + }); + + t.end(); + }); + + test('GetIterator', function (t) { + var arr = [1, 2]; + testIterator(t, ES.GetIterator(arr), arr); + + testIterator(t, ES.GetIterator('abc'), 'abc'.split('')); + + t.test('Symbol.iterator', { skip: !v.hasSymbols }, function (st) { + var m = new Map(); + m.set(1, 'a'); + m.set(2, 'b'); + + testIterator(st, ES.GetIterator(m), [[1, 'a'], [2, 'b']]); + + st.end(); + }); + + t.end(); + }); + + test('IteratorNext', { skip: true }); + + test('IteratorComplete', { skip: true }); + + test('IteratorValue', { skip: true }); + + test('IteratorStep', { skip: true }); + + test('IteratorClose', { skip: true }); + + test('CreateIterResultObject', function (t) { + forEach(v.nonBooleans, function (nonBoolean) { + t['throws']( + function () { ES.CreateIterResultObject({}, nonBoolean); }, + TypeError, + '"done" argument must be a boolean; ' + debug(nonBoolean) + ' is not' + ); + }); + + var value = {}; + t.deepEqual( + ES.CreateIterResultObject(value, true), + { value: value, done: true }, + 'creates a "done" iteration result' + ); + t.deepEqual( + ES.CreateIterResultObject(value, false), + { value: value, done: false }, + 'creates a "not done" iteration result' + ); + + t.end(); + }); + + test('RegExpExec', function (t) { + forEach(v.primitives, function (primitive) { + t['throws']( + function () { ES.RegExpExec(primitive); }, + TypeError, + '"R" argument must be an object; ' + debug(primitive) + ' is not' + ); + }); + + forEach(v.nonStrings, function (nonString) { + t['throws']( + function () { ES.RegExpExec({}, nonString); }, + TypeError, + '"S" argument must be a String; ' + debug(nonString) + ' is not' + ); + }); + + t.test('gets and calls a callable "exec"', function (st) { + var str = '123'; + var o = { + exec: function (S) { + st.equal(this, o, '"exec" receiver is R'); + st.equal(S, str, '"exec" argument is S'); + + return null; + } + }; + st.plan(2); + ES.RegExpExec(o, str); + st.end(); + }); + + t.test('throws if a callable "exec" returns a non-null non-object', function (st) { + var str = '123'; + st.plan(v.nonNullPrimitives.length); + forEach(v.nonNullPrimitives, function (nonNullPrimitive) { + st['throws']( + function () { ES.RegExpExec({ exec: function () { return nonNullPrimitive; } }, str); }, + TypeError, + '"exec" method must return `null` or an Object; ' + debug(nonNullPrimitive) + ' is not' + ); + }); + st.end(); + }); + + t.test('actual regex that should match against a string', function (st) { + var S = 'aabc'; + var R = /a/g; + var match1 = ES.RegExpExec(R, S); + var match2 = ES.RegExpExec(R, S); + var match3 = ES.RegExpExec(R, S); + st.deepEqual(match1, assign(['a'], groups({ index: 0, input: S })), 'match object 1 is as expected'); + st.deepEqual(match2, assign(['a'], groups({ index: 1, input: S })), 'match object 2 is as expected'); + st.equal(match3, null, 'match 3 is null as expected'); + st.end(); + }); + + t.test('actual regex that should match against a string, with shadowed "exec"', function (st) { + var S = 'aabc'; + var R = /a/g; + R.exec = undefined; + var match1 = ES.RegExpExec(R, S); + var match2 = ES.RegExpExec(R, S); + var match3 = ES.RegExpExec(R, S); + st.deepEqual(match1, assign(['a'], groups({ index: 0, input: S })), 'match object 1 is as expected'); + st.deepEqual(match2, assign(['a'], groups({ index: 1, input: S })), 'match object 2 is as expected'); + st.equal(match3, null, 'match 3 is null as expected'); + st.end(); + }); + t.end(); + }); + + test('ArraySpeciesCreate', function (t) { + t.test('errors', function (st) { + var testNonNumber = function (nonNumber) { + st['throws']( + function () { ES.ArraySpeciesCreate([], nonNumber); }, + TypeError, + debug(nonNumber) + ' is not a number' + ); + }; + forEach(v.nonNumbers, testNonNumber); + + st['throws']( + function () { ES.ArraySpeciesCreate([], -1); }, + TypeError, + '-1 is not >= 0' + ); + st['throws']( + function () { ES.ArraySpeciesCreate([], -Infinity); }, + TypeError, + '-Infinity is not >= 0' + ); + + var testNonIntegers = function (nonInteger) { + st['throws']( + function () { ES.ArraySpeciesCreate([], nonInteger); }, + TypeError, + debug(nonInteger) + ' is not an integer' + ); + }; + forEach(v.nonIntegerNumbers, testNonIntegers); + + st.end(); + }); + + t.test('works with a non-array', function (st) { + forEach(v.objects.concat(v.primitives), function (nonArray) { + var arr = ES.ArraySpeciesCreate(nonArray, 0); + st.ok(ES.IsArray(arr), 'is an array'); + st.equal(arr.length, 0, 'length is correct'); + st.equal(arr.constructor, Array, 'constructor is correct'); + }); + + st.end(); + }); + + t.test('works with a normal array', function (st) { + var len = 2; + var orig = [1, 2, 3]; + var arr = ES.ArraySpeciesCreate(orig, len); + + st.ok(ES.IsArray(arr), 'is an array'); + st.equal(arr.length, len, 'length is correct'); + st.equal(arr.constructor, orig.constructor, 'constructor is correct'); + + st.end(); + }); + + t.test('-0 length produces +0 length', function (st) { + var len = -0; + st.ok(is(len, -0), '-0 is negative zero'); + st.notOk(is(len, 0), '-0 is not positive zero'); + + var orig = [1, 2, 3]; + var arr = ES.ArraySpeciesCreate(orig, len); + + st.equal(ES.IsArray(arr), true); + st.ok(is(arr.length, 0)); + st.equal(arr.constructor, orig.constructor); + + st.end(); + }); + + t.test('works with species construtor', { skip: !hasSpecies }, function (st) { + var sentinel = {}; + var Foo = function Foo(len) { + this.length = len; + this.sentinel = sentinel; + }; + var Bar = getArraySubclassWithSpeciesConstructor(Foo); + var bar = new Bar(); + + t.equal(ES.IsArray(bar), true, 'Bar instance is an array'); + + var arr = ES.ArraySpeciesCreate(bar, 3); + st.equal(arr.constructor, Foo, 'result used species constructor'); + st.equal(arr.length, 3, 'length property is correct'); + st.equal(arr.sentinel, sentinel, 'Foo constructor was exercised'); + + st.end(); + }); + + t.test('works with null species constructor', { skip: !hasSpecies }, function (st) { + var Bar = getArraySubclassWithSpeciesConstructor(null); + var bar = new Bar(); + + t.equal(ES.IsArray(bar), true, 'Bar instance is an array'); + + var arr = ES.ArraySpeciesCreate(bar, 3); + st.equal(arr.constructor, Array, 'result used default constructor'); + st.equal(arr.length, 3, 'length property is correct'); + + st.end(); + }); + + t.test('works with undefined species constructor', { skip: !hasSpecies }, function (st) { + var Bar = getArraySubclassWithSpeciesConstructor(); + var bar = new Bar(); + + t.equal(ES.IsArray(bar), true, 'Bar instance is an array'); + + var arr = ES.ArraySpeciesCreate(bar, 3); + st.equal(arr.constructor, Array, 'result used default constructor'); + st.equal(arr.length, 3, 'length property is correct'); + + st.end(); + }); + + t.test('throws with object non-construtor species constructor', { skip: !hasSpecies }, function (st) { + forEach(v.objects, function (obj) { + var Bar = getArraySubclassWithSpeciesConstructor(obj); + var bar = new Bar(); + + st.equal(ES.IsArray(bar), true, 'Bar instance is an array'); + + st['throws']( + function () { ES.ArraySpeciesCreate(bar, 3); }, + TypeError, + debug(obj) + ' is not a constructor' + ); + }); + + st.end(); + }); + + t.end(); + }); + + test('CreateDataProperty', function (t) { + forEach(v.primitives, function (primitive) { + t['throws']( + function () { ES.CreateDataProperty(primitive); }, + TypeError, + debug(primitive) + ' is not an object' + ); + }); + + forEach(v.nonPropertyKeys, function (nonPropertyKey) { + t['throws']( + function () { ES.CreateDataProperty({}, nonPropertyKey); }, + TypeError, + debug(nonPropertyKey) + ' is not a property key' + ); + }); + + var sentinel = {}; + forEach(v.propertyKeys, function (propertyKey) { + var obj = {}; + var status = ES.CreateDataProperty(obj, propertyKey, sentinel); + t.equal(status, true, 'status is true'); + t.equal( + obj[propertyKey], + sentinel, + debug(sentinel) + ' is installed on "' + debug(propertyKey) + '" on the object' + ); + + if (typeof Object.defineProperty === 'function') { + var nonWritable = Object.defineProperty({}, propertyKey, { configurable: true, writable: false }); + + var nonWritableStatus = ES.CreateDataProperty(nonWritable, propertyKey, sentinel); + t.equal(nonWritableStatus, false, 'create data property failed'); + t.notEqual( + nonWritable[propertyKey], + sentinel, + debug(sentinel) + ' is not installed on "' + debug(propertyKey) + '" on the object when key is nonwritable' + ); + + var nonConfigurable = Object.defineProperty({}, propertyKey, { configurable: false, writable: true }); + + var nonConfigurableStatus = ES.CreateDataProperty(nonConfigurable, propertyKey, sentinel); + t.equal(nonConfigurableStatus, false, 'create data property failed'); + t.notEqual( + nonConfigurable[propertyKey], + sentinel, + debug(sentinel) + ' is not installed on "' + debug(propertyKey) + '" on the object when key is nonconfigurable' + ); + } + }); + + t.end(); + }); + + test('CreateDataPropertyOrThrow', function (t) { + forEach(v.primitives, function (primitive) { + t['throws']( + function () { ES.CreateDataPropertyOrThrow(primitive); }, + TypeError, + debug(primitive) + ' is not an object' + ); + }); + + forEach(v.nonPropertyKeys, function (nonPropertyKey) { + t['throws']( + function () { ES.CreateDataPropertyOrThrow({}, nonPropertyKey); }, + TypeError, + debug(nonPropertyKey) + ' is not a property key' + ); + }); + + var sentinel = {}; + forEach(v.propertyKeys, function (propertyKey) { + var obj = {}; + var status = ES.CreateDataPropertyOrThrow(obj, propertyKey, sentinel); + t.equal(status, true, 'status is true'); + t.equal( + obj[propertyKey], + sentinel, + debug(sentinel) + ' is installed on "' + debug(propertyKey) + '" on the object' + ); + + if (typeof Object.preventExtensions === 'function') { + var notExtensible = {}; + Object.preventExtensions(notExtensible); + + t['throws']( + function () { ES.CreateDataPropertyOrThrow(notExtensible, propertyKey, sentinel); }, + TypeError, + 'can not install ' + debug(propertyKey) + ' on non-extensible object' + ); + t.notEqual( + notExtensible[propertyKey], + sentinel, + debug(sentinel) + ' is not installed on "' + debug(propertyKey) + '" on the object' + ); + } + }); + + t.end(); + }); + + test('ObjectCreate', function (t) { + forEach(v.nonNullPrimitives, function (value) { + t['throws']( + function () { ES.ObjectCreate(value); }, + TypeError, + debug(value) + ' is not null, or an object' + ); + }); + + t.test('proto arg', function (st) { + var Parent = function Parent() {}; + Parent.prototype.foo = {}; + var child = ES.ObjectCreate(Parent.prototype); + st.equal(child instanceof Parent, true, 'child is instanceof Parent'); + st.equal(child.foo, Parent.prototype.foo, 'child inherits properties from Parent.prototype'); + + st.end(); + }); + + t.test('internal slots arg', function (st) { + st.doesNotThrow(function () { ES.ObjectCreate(null, []); }, 'an empty slot list is valid'); + + st['throws']( + function () { ES.ObjectCreate(null, ['a']); }, + SyntaxError, + 'internal slots are not supported' + ); + + st.end(); + }); + + t.test('null proto', { skip: !Object.create }, function (st) { + st.equal('toString' in {}, true, 'normal objects have toString'); + st.equal('toString' in ES.ObjectCreate(null), false, 'makes a null object'); + + st.end(); + }); + + t.test('null proto when no native Object.create', { skip: Object.create }, function (st) { + st['throws']( + function () { ES.ObjectCreate(null); }, + SyntaxError, + 'without a native Object.create, can not create null objects' + ); + + st.end(); + }); + + t.end(); + }); + + test('AdvanceStringIndex', function (t) { + forEach(v.nonStrings, function (nonString) { + t['throws']( + function () { ES.AdvanceStringIndex(nonString); }, + TypeError, + '"S" argument must be a String; ' + debug(nonString) + ' is not' + ); + }); + + var notInts = v.nonNumbers.concat( + v.nonIntegerNumbers, + v.infinities, + [NaN, [], new Date(), Math.pow(2, 53), -1] + ); + forEach(notInts, function (nonInt) { + t['throws']( + function () { ES.AdvanceStringIndex('abc', nonInt); }, + TypeError, + '"index" argument must be an integer, ' + debug(nonInt) + ' is not.' + ); + }); + + forEach(v.nonBooleans, function (nonBoolean) { + t['throws']( + function () { ES.AdvanceStringIndex('abc', 0, nonBoolean); }, + TypeError, + debug(nonBoolean) + ' is not a Boolean' + ); + }); + + var str = 'a\uD83D\uDCA9c'; + + t.test('non-unicode mode', function (st) { + for (var i = 0; i < str.length + 2; i += 1) { + st.equal(ES.AdvanceStringIndex(str, i, false), i + 1, i + ' advances to ' + (i + 1)); + } + + st.end(); + }); + + t.test('unicode mode', function (st) { + st.equal(ES.AdvanceStringIndex(str, 0, true), 1, '0 advances to 1'); + st.equal(ES.AdvanceStringIndex(str, 1, true), 3, '1 advances to 3'); + st.equal(ES.AdvanceStringIndex(str, 2, true), 3, '2 advances to 3'); + st.equal(ES.AdvanceStringIndex(str, 3, true), 4, '3 advances to 4'); + st.equal(ES.AdvanceStringIndex(str, 4, true), 5, '4 advances to 5'); + + st.end(); + }); + + t.test('lone surrogates', function (st) { + var halfPoo = 'a\uD83Dc'; + + st.equal(ES.AdvanceStringIndex(halfPoo, 0, true), 1, '0 advances to 1'); + st.equal(ES.AdvanceStringIndex(halfPoo, 1, true), 2, '1 advances to 2'); + st.equal(ES.AdvanceStringIndex(halfPoo, 2, true), 3, '2 advances to 3'); + st.equal(ES.AdvanceStringIndex(halfPoo, 3, true), 4, '3 advances to 4'); + + st.end(); + }); + + t.test('surrogate pairs', function (st) { + var lowestPair = String.fromCharCode('0xD800') + String.fromCharCode('0xDC00'); + var highestPair = String.fromCharCode('0xDBFF') + String.fromCharCode('0xDFFF'); + var poop = String.fromCharCode('0xD83D') + String.fromCharCode('0xDCA9'); + + st.equal(ES.AdvanceStringIndex(lowestPair, 0, true), 2, 'lowest surrogate pair, 0 -> 2'); + st.equal(ES.AdvanceStringIndex(highestPair, 0, true), 2, 'highest surrogate pair, 0 -> 2'); + st.equal(ES.AdvanceStringIndex(poop, 0, true), 2, 'poop, 0 -> 2'); + + st.end(); + }); + + t.end(); + }); + + test('CreateMethodProperty', function (t) { + forEach(v.primitives, function (primitive) { + t['throws']( + function () { ES.CreateMethodProperty(primitive, 'key'); }, + TypeError, + 'O must be an Object' + ); + }); + + forEach(v.nonPropertyKeys, function (nonPropertyKey) { + t['throws']( + function () { ES.CreateMethodProperty({}, nonPropertyKey); }, + TypeError, + debug(nonPropertyKey) + ' is not a Property Key' + ); + }); + + t.test('defines correctly', function (st) { + var obj = {}; + var key = 'the key'; + var value = { foo: 'bar' }; + + st.equal(ES.CreateMethodProperty(obj, key, value), true, 'defines property successfully'); + st.test('property descriptor', { skip: !Object.getOwnPropertyDescriptor }, function (s2t) { + s2t.deepEqual( + Object.getOwnPropertyDescriptor(obj, key), + { + configurable: true, + enumerable: false, + value: value, + writable: true + }, + 'sets the correct property descriptor' + ); + + s2t.end(); + }); + st.equal(obj[key], value, 'sets the correct value'); + + st.end(); + }); + + t.test('fails as expected on a frozen object', { skip: !Object.freeze }, function (st) { + var obj = Object.freeze({ foo: 'bar' }); + st['throws']( + function () { ES.CreateMethodProperty(obj, 'foo', { value: 'baz' }); }, + TypeError, + 'nonconfigurable key can not be defined' + ); + + st.end(); + }); + + var hasNonConfigurableFunctionName = !Object.getOwnPropertyDescriptor + || !Object.getOwnPropertyDescriptor(function () {}, 'name').configurable; + t.test('fails as expected on a function with a nonconfigurable name', { skip: !hasNonConfigurableFunctionName }, function (st) { + st['throws']( + function () { ES.CreateMethodProperty(function () {}, 'name', { value: 'baz' }); }, + TypeError, + 'nonconfigurable function name can not be defined' + ); + st.end(); + }); + + t.end(); + }); + + test('DefinePropertyOrThrow', function (t) { + forEach(v.primitives, function (primitive) { + t['throws']( + function () { ES.DefinePropertyOrThrow(primitive, 'key', {}); }, + TypeError, + 'O must be an Object' + ); + }); + + forEach(v.nonPropertyKeys, function (nonPropertyKey) { + t['throws']( + function () { ES.DefinePropertyOrThrow({}, nonPropertyKey, {}); }, + TypeError, + debug(nonPropertyKey) + ' is not a Property Key' + ); + }); + + t.test('defines correctly', function (st) { + var obj = {}; + var key = 'the key'; + var descriptor = { + configurable: true, + enumerable: false, + value: { foo: 'bar' }, + writable: true + }; + + st.equal(ES.DefinePropertyOrThrow(obj, key, descriptor), true, 'defines property successfully'); + st.test('property descriptor', { skip: !Object.getOwnPropertyDescriptor }, function (s2t) { + s2t.deepEqual( + Object.getOwnPropertyDescriptor(obj, key), + descriptor, + 'sets the correct property descriptor' + ); + + s2t.end(); + }); + st.deepEqual(obj[key], descriptor.value, 'sets the correct value'); + + st.end(); + }); + + t.test('fails as expected on a frozen object', { skip: !Object.freeze }, function (st) { + var obj = Object.freeze({ foo: 'bar' }); + st['throws']( + function () { + ES.DefinePropertyOrThrow(obj, 'foo', { configurable: true, value: 'baz' }); + }, + TypeError, + 'nonconfigurable key can not be defined' + ); + + st.end(); + }); + + var hasNonConfigurableFunctionName = !Object.getOwnPropertyDescriptor + || !Object.getOwnPropertyDescriptor(function () {}, 'name').configurable; + t.test('fails as expected on a function with a nonconfigurable name', { skip: !hasNonConfigurableFunctionName }, function (st) { + st['throws']( + function () { + ES.DefinePropertyOrThrow(function () {}, 'name', { configurable: true, value: 'baz' }); + }, + TypeError, + 'nonconfigurable function name can not be defined' + ); + st.end(); + }); + + t.end(); + }); + + test('DeletePropertyOrThrow', function (t) { + forEach(v.primitives, function (primitive) { + t['throws']( + function () { ES.DeletePropertyOrThrow(primitive, 'key', {}); }, + TypeError, + 'O must be an Object' + ); + }); + + forEach(v.nonPropertyKeys, function (nonPropertyKey) { + t['throws']( + function () { ES.DeletePropertyOrThrow({}, nonPropertyKey, {}); }, + TypeError, + debug(nonPropertyKey) + ' is not a Property Key' + ); + }); + + t.test('defines correctly', function (st) { + var obj = { 'the key': 42 }; + var key = 'the key'; + + st.equal(ES.DeletePropertyOrThrow(obj, key), true, 'deletes property successfully'); + st.equal(key in obj, false, 'key is no longer in the object'); + + st.end(); + }); + + t.test('fails as expected on a frozen object', { skip: !Object.freeze }, function (st) { + var obj = Object.freeze({ foo: 'bar' }); + st['throws']( + function () { ES.DeletePropertyOrThrow(obj, 'foo'); }, + TypeError, + 'nonconfigurable key can not be deleted' + ); + + st.end(); + }); + + var hasNonConfigurableFunctionName = !Object.getOwnPropertyDescriptor + || !Object.getOwnPropertyDescriptor(function () {}, 'name').configurable; + t.test('fails as expected on a function with a nonconfigurable name', { skip: !hasNonConfigurableFunctionName }, function (st) { + st['throws']( + function () { ES.DeletePropertyOrThrow(function () {}, 'name'); }, + TypeError, + 'nonconfigurable function name can not be deleted' + ); + st.end(); + }); + + t.end(); + }); + + test('EnumerableOwnNames', { skip: skips && skips.EnumerableOwnNames }, function (t) { + var obj = testEnumerableOwnNames(t, function (O) { return ES.EnumerableOwnNames(O); }); + + t.deepEqual( + ES.EnumerableOwnNames(obj), + ['own'], + 'returns enumerable own names' + ); + + t.end(); + }); + + test('thisNumberValue', function (t) { + forEach(v.nonNumbers, function (nonNumber) { + t['throws']( + function () { ES.thisNumberValue(nonNumber); }, + TypeError, + debug(nonNumber) + ' is not a Number' + ); + }); + + forEach(v.numbers, function (number) { + t.equal(ES.thisNumberValue(number), number, debug(number) + ' is its own thisNumberValue'); + var obj = Object(number); + t.equal(ES.thisNumberValue(obj), number, debug(obj) + ' is the boxed thisNumberValue'); + }); + + t.end(); + }); + + test('thisBooleanValue', function (t) { + forEach(v.nonBooleans, function (nonBoolean) { + t['throws']( + function () { ES.thisBooleanValue(nonBoolean); }, + TypeError, + debug(nonBoolean) + ' is not a Boolean' + ); + }); + + forEach(v.booleans, function (boolean) { + t.equal(ES.thisBooleanValue(boolean), boolean, debug(boolean) + ' is its own thisBooleanValue'); + var obj = Object(boolean); + t.equal(ES.thisBooleanValue(obj), boolean, debug(obj) + ' is the boxed thisBooleanValue'); + }); + + t.end(); + }); + + test('thisStringValue', function (t) { + forEach(v.nonStrings, function (nonString) { + t['throws']( + function () { ES.thisStringValue(nonString); }, + TypeError, + debug(nonString) + ' is not a String' + ); + }); + + forEach(v.strings, function (string) { + t.equal(ES.thisStringValue(string), string, debug(string) + ' is its own thisStringValue'); + var obj = Object(string); + t.equal(ES.thisStringValue(obj), string, debug(obj) + ' is the boxed thisStringValue'); + }); + + t.end(); + }); + + test('thisTimeValue', function (t) { + forEach(v.primitives.concat(v.objects), function (nonDate) { + t['throws']( + function () { ES.thisTimeValue(nonDate); }, + TypeError, + debug(nonDate) + ' is not a Date' + ); + }); + + forEach(v.timestamps, function (timestamp) { + var date = new Date(timestamp); + + t.equal(ES.thisTimeValue(date), timestamp, debug(date) + ' is its own thisTimeValue'); + }); + + t.end(); + }); + + test('SetIntegrityLevel', function (t) { + forEach(v.primitives, function (primitive) { + t['throws']( + function () { ES.SetIntegrityLevel(primitive); }, + TypeError, + debug(primitive) + ' is not an Object' + ); + }); + + t['throws']( + function () { ES.SetIntegrityLevel({}); }, + /^TypeError: Assertion failed: `level` must be `"sealed"` or `"frozen"`$/, + '`level` must be `"sealed"` or `"frozen"`' + ); + + var O = { a: 1 }; + t.equal(ES.SetIntegrityLevel(O, 'sealed'), true); + t['throws']( + function () { O.b = 2; }, + /^TypeError: (Cannot|Can't) add property b, object is not extensible$/, + 'sealing prevent new properties from being added' + ); + O.a = 2; + t.equal(O.a, 2, 'pre-frozen, existing properties are mutable'); + + t.equal(ES.SetIntegrityLevel(O, 'frozen'), true); + t['throws']( + function () { O.a = 3; }, + /^TypeError: Cannot assign to read only property 'a' of /, + 'freezing prevents existing properties from being mutated' + ); + + t.end(); + }); + + test('TestIntegrityLevel', function (t) { + forEach(v.primitives, function (primitive) { + t['throws']( + function () { ES.TestIntegrityLevel(primitive); }, + TypeError, + debug(primitive) + ' is not an Object' + ); + }); + + t['throws']( + function () { ES.TestIntegrityLevel({ a: 1 }); }, + /^TypeError: Assertion failed: `level` must be `"sealed"` or `"frozen"`$/, + '`level` must be `"sealed"` or `"frozen"`' + ); + + t.equal(ES.TestIntegrityLevel({ a: 1 }, 'sealed'), false, 'basic object is not sealed'); + t.equal(ES.TestIntegrityLevel({ a: 1 }, 'frozen'), false, 'basic object is not frozen'); + + t.test('preventExtensions', { skip: !Object.preventExtensions }, function (st) { + var o = Object.preventExtensions({ a: 1 }); + st.equal(ES.TestIntegrityLevel(o, 'sealed'), false, 'nonextensible object is not sealed'); + st.equal(ES.TestIntegrityLevel(o, 'frozen'), false, 'nonextensible object is not frozen'); + + var empty = Object.preventExtensions({}); + st.equal(ES.TestIntegrityLevel(empty, 'sealed'), true, 'empty nonextensible object is sealed'); + st.equal(ES.TestIntegrityLevel(empty, 'frozen'), true, 'empty nonextensible object is frozen'); + st.end(); + }); + + t.test('seal', { skip: !Object.seal }, function (st) { + var o = Object.seal({ a: 1 }); + st.equal(ES.TestIntegrityLevel(o, 'sealed'), true, 'sealed object is sealed'); + st.equal(ES.TestIntegrityLevel(o, 'frozen'), false, 'sealed object is not frozen'); + + var empty = Object.seal({}); + st.equal(ES.TestIntegrityLevel(empty, 'sealed'), true, 'empty sealed object is sealed'); + st.equal(ES.TestIntegrityLevel(empty, 'frozen'), true, 'empty sealed object is frozen'); + + st.end(); + }); + + t.test('freeze', { skip: !Object.freeze }, function (st) { + var o = Object.freeze({ a: 1 }); + st.equal(ES.TestIntegrityLevel(o, 'sealed'), true, 'frozen object is sealed'); + st.equal(ES.TestIntegrityLevel(o, 'frozen'), true, 'frozen object is frozen'); + + var empty = Object.freeze({}); + st.equal(ES.TestIntegrityLevel(empty, 'sealed'), true, 'empty frozen object is sealed'); + st.equal(ES.TestIntegrityLevel(empty, 'frozen'), true, 'empty frozen object is frozen'); + + st.end(); + }); + + t.end(); + }); + + test('OrdinaryHasInstance', function (t) { + forEach(v.nonFunctions, function (nonFunction) { + t.equal(ES.OrdinaryHasInstance(nonFunction, {}), false, debug(nonFunction) + ' is not callable'); + }); + + forEach(v.primitives, function (primitive) { + t.equal(ES.OrdinaryHasInstance(function () {}, primitive), false, debug(primitive) + ' is not an object'); + }); + + var C = function C() {}; + var D = function D() {}; + t.equal(ES.OrdinaryHasInstance(C, new C()), true, 'constructor function has an instance of itself'); + t.equal(ES.OrdinaryHasInstance(C, new D()), false, 'constructor/instance mismatch is false'); + t.equal(ES.OrdinaryHasInstance(D, new C()), false, 'instance/constructor mismatch is false'); + t.equal(ES.OrdinaryHasInstance(C, {}), false, 'plain object is not an instance of a constructor'); + t.equal(ES.OrdinaryHasInstance(Object, {}), true, 'plain object is an instance of Object'); + + t.end(); + }); + + test('OrdinaryHasProperty', function (t) { + forEach(v.primitives, function (primitive) { + t['throws']( + function () { ES.OrdinaryHasProperty(primitive, ''); }, + TypeError, + debug(primitive) + ' is not an object' + ); + }); + forEach(v.nonPropertyKeys, function (nonPropertyKey) { + t['throws']( + function () { ES.OrdinaryHasProperty({}, nonPropertyKey); }, + TypeError, + 'P: ' + debug(nonPropertyKey) + ' is not a Property Key' + ); + }); + + t.equal(ES.OrdinaryHasProperty({ a: 1 }, 'a'), true, 'own property is true'); + t.equal(ES.OrdinaryHasProperty({}, 'toString'), true, 'inherited property is true'); + t.equal(ES.OrdinaryHasProperty({}, 'nope'), false, 'absent property is false'); + + t.end(); + }); + + test('InstanceofOperator', function (t) { + forEach(v.primitives, function (primitive) { + t['throws']( + function () { ES.InstanceofOperator(primitive, function () {}); }, + TypeError, + debug(primitive) + ' is not an object' + ); + }); + + forEach(v.nonFunctions, function (nonFunction) { + t['throws']( + function () { ES.InstanceofOperator({}, nonFunction); }, + TypeError, + debug(nonFunction) + ' is not callable' + ); + }); + + var C = function C() {}; + var D = function D() {}; + + t.equal(ES.InstanceofOperator(new C(), C), true, 'constructor function has an instance of itself'); + t.equal(ES.InstanceofOperator(new D(), C), false, 'constructor/instance mismatch is false'); + t.equal(ES.InstanceofOperator(new C(), D), false, 'instance/constructor mismatch is false'); + t.equal(ES.InstanceofOperator({}, C), false, 'plain object is not an instance of a constructor'); + t.equal(ES.InstanceofOperator({}, Object), true, 'plain object is an instance of Object'); + + t.test('Symbol.hasInstance', { skip: !v.hasSymbols || !Symbol.hasInstance }, function (st) { + st.plan(4); + + var O = {}; + var C2 = function () {}; + st.equal(ES.InstanceofOperator(O, C2), false, 'O is not an instance of C2'); + + Object.defineProperty(C2, Symbol.hasInstance, { + value: function (obj) { + st.equal(this, C2, 'hasInstance receiver is C2'); + st.equal(obj, O, 'hasInstance argument is O'); + + return {}; // testing coercion to boolean + } + }); + + st.equal(ES.InstanceofOperator(O, C2), true, 'O is now an instance of C2'); + + st.end(); + }); + + t.end(); + }); + + test('Abstract Equality Comparison', function (t) { + t.test('same types use ===', function (st) { + forEach(v.primitives.concat(v.objects), function (value) { + st.equal(ES['Abstract Equality Comparison'](value, value), value === value, debug(value) + ' is abstractly equal to itself'); + }); + st.end(); + }); + + t.test('different types coerce', function (st) { + var pairs = [ + [null, undefined], + [3, '3'], + [true, '3'], + [true, 3], + [false, 0], + [false, '0'], + [3, [3]], + ['3', [3]], + [true, [1]], + [false, [0]], + [String(v.coercibleObject), v.coercibleObject], + [Number(String(v.coercibleObject)), v.coercibleObject], + [Number(v.coercibleObject), v.coercibleObject], + [String(Number(v.coercibleObject)), v.coercibleObject] + ]; + forEach(pairs, function (pair) { + var a = pair[0]; + var b = pair[1]; + // eslint-disable-next-line eqeqeq + st.equal(ES['Abstract Equality Comparison'](a, b), a == b, debug(a) + ' == ' + debug(b)); + // eslint-disable-next-line eqeqeq + st.equal(ES['Abstract Equality Comparison'](b, a), b == a, debug(b) + ' == ' + debug(a)); + }); + st.end(); + }); + + t.end(); + }); + + test('Strict Equality Comparison', function (t) { + t.test('same types use ===', function (st) { + forEach(v.primitives.concat(v.objects), function (value) { + st.equal(ES['Strict Equality Comparison'](value, value), value === value, debug(value) + ' is strictly equal to itself'); + }); + st.end(); + }); + + t.test('different types are not ===', function (st) { + var pairs = [ + [null, undefined], + [3, '3'], + [true, '3'], + [true, 3], + [false, 0], + [false, '0'], + [3, [3]], + ['3', [3]], + [true, [1]], + [false, [0]], + [String(v.coercibleObject), v.coercibleObject], + [Number(String(v.coercibleObject)), v.coercibleObject], + [Number(v.coercibleObject), v.coercibleObject], + [String(Number(v.coercibleObject)), v.coercibleObject] + ]; + forEach(pairs, function (pair) { + var a = pair[0]; + var b = pair[1]; + st.equal(ES['Strict Equality Comparison'](a, b), a === b, debug(a) + ' === ' + debug(b)); + st.equal(ES['Strict Equality Comparison'](b, a), b === a, debug(b) + ' === ' + debug(a)); + }); + st.end(); + }); + + t.end(); + }); + + test('Abstract Relational Comparison', function (t) { + t.test('at least one operand is NaN', function (st) { + st.equal(ES['Abstract Relational Comparison'](NaN, {}, true), undefined, 'LeftFirst: first is NaN, returns undefined'); + st.equal(ES['Abstract Relational Comparison']({}, NaN, true), undefined, 'LeftFirst: second is NaN, returns undefined'); + st.equal(ES['Abstract Relational Comparison'](NaN, {}, false), undefined, '!LeftFirst: first is NaN, returns undefined'); + st.equal(ES['Abstract Relational Comparison']({}, NaN, false), undefined, '!LeftFirst: second is NaN, returns undefined'); + st.end(); + }); + + t.equal(ES['Abstract Relational Comparison'](3, 4, true), true, 'LeftFirst: 3 is less than 4'); + t.equal(ES['Abstract Relational Comparison'](4, 3, true), false, 'LeftFirst: 3 is not less than 4'); + t.equal(ES['Abstract Relational Comparison'](3, 4, false), true, '!LeftFirst: 3 is less than 4'); + t.equal(ES['Abstract Relational Comparison'](4, 3, false), false, '!LeftFirst: 3 is not less than 4'); + + t.equal(ES['Abstract Relational Comparison']('3', '4', true), true, 'LeftFirst: "3" is less than "4"'); + t.equal(ES['Abstract Relational Comparison']('4', '3', true), false, 'LeftFirst: "3" is not less than "4"'); + t.equal(ES['Abstract Relational Comparison']('3', '4', false), true, '!LeftFirst: "3" is less than "4"'); + t.equal(ES['Abstract Relational Comparison']('4', '3', false), false, '!LeftFirst: "3" is not less than "4"'); + + t.equal(ES['Abstract Relational Comparison'](v.coercibleObject, 42, true), true, 'LeftFirst: coercible object is less than 42'); + t.equal(ES['Abstract Relational Comparison'](42, v.coercibleObject, true), false, 'LeftFirst: 42 is not less than coercible object'); + t.equal(ES['Abstract Relational Comparison'](v.coercibleObject, 42, false), true, '!LeftFirst: coercible object is less than 42'); + t.equal(ES['Abstract Relational Comparison'](42, v.coercibleObject, false), false, '!LeftFirst: 42 is not less than coercible object'); + + t.equal(ES['Abstract Relational Comparison'](v.coercibleObject, '3', true), false, 'LeftFirst: coercible object is not less than "3"'); + t.equal(ES['Abstract Relational Comparison']('3', v.coercibleObject, true), false, 'LeftFirst: "3" is not less than coercible object'); + t.equal(ES['Abstract Relational Comparison'](v.coercibleObject, '3', false), false, '!LeftFirst: coercible object is not less than "3"'); + t.equal(ES['Abstract Relational Comparison']('3', v.coercibleObject, false), false, '!LeftFirst: "3" is not less than coercible object'); + + t.end(); + }); + + test('ValidateAndApplyPropertyDescriptor', function (t) { + forEach(v.nonUndefinedPrimitives, function (nonUndefinedPrimitive) { + t['throws']( + function () { ES.ValidateAndApplyPropertyDescriptor(nonUndefinedPrimitive, '', false, v.genericDescriptor(), v.genericDescriptor()); }, + TypeError, + 'O: ' + debug(nonUndefinedPrimitive) + ' is not undefined or an Object' + ); + }); + + forEach(v.nonBooleans, function (nonBoolean) { + t['throws']( + function () { + return ES.ValidateAndApplyPropertyDescriptor( + undefined, + null, + nonBoolean, + v.genericDescriptor(), + v.genericDescriptor() + ); + }, + TypeError, + 'extensible: ' + debug(nonBoolean) + ' is not a Boolean' + ); + }); + + forEach(v.primitives, function (primitive) { + // Desc must be a Property Descriptor + t['throws']( + function () { + return ES.ValidateAndApplyPropertyDescriptor( + undefined, + null, + false, + primitive, + v.genericDescriptor() + ); + }, + TypeError, + 'Desc: ' + debug(primitive) + ' is not a Property Descriptor' + ); + }); + + forEach(v.nonUndefinedPrimitives, function (primitive) { + // current must be undefined or a Property Descriptor + t['throws']( + function () { + return ES.ValidateAndApplyPropertyDescriptor( + undefined, + null, + false, + v.genericDescriptor(), + primitive + ); + }, + TypeError, + 'current: ' + debug(primitive) + ' is not a Property Descriptor or undefined' + ); + }); + + forEach(v.nonPropertyKeys, function (nonPropertyKey) { + // if O is an object, P must be a property key + t['throws']( + function () { + return ES.ValidateAndApplyPropertyDescriptor( + {}, + nonPropertyKey, + false, + v.genericDescriptor(), + v.genericDescriptor() + ); + }, + TypeError, + 'P: ' + debug(nonPropertyKey) + ' is not a Property Key' + ); + }); + + t.test('current is undefined', function (st) { + var propertyKey = 'howdy'; + + st.test('generic descriptor', function (s2t) { + var generic = v.genericDescriptor(); + generic['[[Enumerable]]'] = true; + var O = {}; + ES.ValidateAndApplyPropertyDescriptor(undefined, propertyKey, true, generic); + s2t.equal( + ES.ValidateAndApplyPropertyDescriptor(O, propertyKey, false, generic), + false, + 'when extensible is false, nothing happens' + ); + s2t.deepEqual(O, {}, 'no changes applied when O is undefined or extensible is false'); + s2t.equal( + ES.ValidateAndApplyPropertyDescriptor(O, propertyKey, true, generic), + true, + 'operation is successful' + ); + var expected = {}; + expected[propertyKey] = undefined; + s2t.deepEqual(O, expected, 'generic descriptor has been defined as an own data property'); + s2t.end(); + }); + + st.test('data descriptor', function (s2t) { + var data = v.dataDescriptor(); + data['[[Enumerable]]'] = true; + + var O = {}; + ES.ValidateAndApplyPropertyDescriptor(undefined, propertyKey, true, data); + s2t.equal( + ES.ValidateAndApplyPropertyDescriptor(O, propertyKey, false, data), + false, + 'when extensible is false, nothing happens' + ); + s2t.deepEqual(O, {}, 'no changes applied when O is undefined or extensible is false'); + s2t.equal( + ES.ValidateAndApplyPropertyDescriptor(O, propertyKey, true, data), + true, + 'operation is successful' + ); + var expected = {}; + expected[propertyKey] = data['[[Value]]']; + s2t.deepEqual(O, expected, 'data descriptor has been defined as an own data property'); + s2t.end(); + }); + + st.test('accessor descriptor', function (s2t) { + var count = 0; + var accessor = v.accessorDescriptor(); + accessor['[[Enumerable]]'] = true; + accessor['[[Get]]'] = function () { + count += 1; + return count; + }; + + var O = {}; + ES.ValidateAndApplyPropertyDescriptor(undefined, propertyKey, true, accessor); + s2t.equal( + ES.ValidateAndApplyPropertyDescriptor(O, propertyKey, false, accessor), + false, + 'when extensible is false, nothing happens' + ); + s2t.deepEqual(O, {}, 'no changes applied when O is undefined or extensible is false'); + s2t.equal( + ES.ValidateAndApplyPropertyDescriptor(O, propertyKey, true, accessor), + true, + 'operation is successful' + ); + var expected = {}; + expected[propertyKey] = accessor['[[Get]]']() + 1; + s2t.deepEqual(O, expected, 'accessor descriptor has been defined as an own accessor property'); + s2t.end(); + }); + + st.end(); + }); + + t.test('every field in Desc is absent', { skip: 'it is unclear if having no fields qualifies Desc to be a Property Descriptor' }); + + forEach([v.dataDescriptor, v.accessorDescriptor, v.mutatorDescriptor], function (getDescriptor) { + t.equal( + ES.ValidateAndApplyPropertyDescriptor(undefined, 'property key', true, getDescriptor(), getDescriptor()), + true, + 'when Desc and current are the same, early return true' + ); + }); + + t.test('current is nonconfigurable', function (st) { + // note: these must not be generic descriptors, or else the algorithm returns an early true + st.equal( + ES.ValidateAndApplyPropertyDescriptor( + undefined, + 'property key', + true, + v.descriptors.configurable(v.dataDescriptor()), + v.descriptors.nonConfigurable(v.dataDescriptor()) + ), + false, + 'false if Desc is configurable' + ); + + st.equal( + ES.ValidateAndApplyPropertyDescriptor( + undefined, + 'property key', + true, + v.descriptors.enumerable(v.dataDescriptor()), + v.descriptors.nonEnumerable(v.dataDescriptor()) + ), + false, + 'false if Desc is Enumerable and current is not' + ); + + st.equal( + ES.ValidateAndApplyPropertyDescriptor( + undefined, + 'property key', + true, + v.descriptors.nonEnumerable(v.dataDescriptor()), + v.descriptors.enumerable(v.dataDescriptor()) + ), + false, + 'false if Desc is not Enumerable and current is' + ); + + var descLackingEnumerable = v.accessorDescriptor(); + delete descLackingEnumerable['[[Enumerable]]']; + st.equal( + ES.ValidateAndApplyPropertyDescriptor( + undefined, + 'property key', + true, + descLackingEnumerable, + v.descriptors.enumerable(v.accessorDescriptor()) + ), + true, + 'not false if Desc lacks Enumerable' + ); + + st.end(); + }); + + t.test('Desc and current: one is a data descriptor, one is not', { skip: !Object.defineProperty }, function (st) { + // note: Desc must be configurable if current is nonconfigurable, to hit this branch + st.equal( + ES.ValidateAndApplyPropertyDescriptor( + undefined, + 'property key', + true, + v.descriptors.configurable(v.accessorDescriptor()), + v.descriptors.nonConfigurable(v.dataDescriptor()) + ), + false, + 'false if current (data) is nonconfigurable' + ); + + st.equal( + ES.ValidateAndApplyPropertyDescriptor( + undefined, + 'property key', + true, + v.descriptors.configurable(v.dataDescriptor()), + v.descriptors.nonConfigurable(v.accessorDescriptor()) + ), + false, + 'false if current (not data) is nonconfigurable' + ); + + // one is data and one is not, + // // if current is data, convert to accessor + // // else convert to data + + var startsWithData = { + 'property key': 42 + }; + st.equal( + ES.ValidateAndApplyPropertyDescriptor( + startsWithData, + 'property key', + true, + v.descriptors.enumerable(v.descriptors.configurable(v.accessorDescriptor())), + v.descriptors.enumerable(v.descriptors.configurable(v.dataDescriptor())) + ), + true, + 'operation is successful: current is data, Desc is accessor' + ); + var shouldBeAccessor = Object.getOwnPropertyDescriptor(startsWithData, 'property key'); + st.equal(typeof shouldBeAccessor.get, 'function', 'has a getter'); + + var key = 'property key'; + var startsWithAccessor = {}; + Object.defineProperty(startsWithAccessor, key, { + configurable: true, + enumerable: true, + get: function get() { return 42; } + }); + st.equal( + ES.ValidateAndApplyPropertyDescriptor( + startsWithAccessor, + key, + true, + v.descriptors.enumerable(v.descriptors.configurable(v.dataDescriptor())), + v.descriptors.enumerable(v.descriptors.configurable(v.accessorDescriptor(42))) + ), + true, + 'operation is successful: current is accessor, Desc is data' + ); + var shouldBeData = Object.getOwnPropertyDescriptor(startsWithAccessor, 'property key'); + st.deepEqual(shouldBeData, { configurable: true, enumerable: true, value: 42, writable: false }, 'is a data property'); + + st.end(); + }); + + t.test('Desc and current are both data descriptors', function (st) { + st.equal( + ES.ValidateAndApplyPropertyDescriptor( + undefined, + 'property key', + true, + v.descriptors.writable(v.dataDescriptor()), + v.descriptors.nonWritable(v.descriptors.nonConfigurable(v.dataDescriptor())) + ), + false, + 'false if frozen current and writable Desc' + ); + + st.equal( + ES.ValidateAndApplyPropertyDescriptor( + undefined, + 'property key', + true, + v.descriptors.configurable({ '[[Value]]': 42 }), + v.descriptors.nonWritable({ '[[Value]]': 7 }) + ), + false, + 'false if nonwritable current has a different value than Desc' + ); + + st.end(); + }); + + t.test('current is nonconfigurable; Desc and current are both accessor descriptors', function (st) { + st.equal( + ES.ValidateAndApplyPropertyDescriptor( + undefined, + 'property key', + true, + v.mutatorDescriptor(), + v.descriptors.nonConfigurable(v.mutatorDescriptor()) + ), + false, + 'false if both Sets are not equal' + ); + + st.equal( + ES.ValidateAndApplyPropertyDescriptor( + undefined, + 'property key', + true, + v.accessorDescriptor(), + v.descriptors.nonConfigurable(v.accessorDescriptor()) + ), + false, + 'false if both Gets are not equal' + ); + + st.end(); + }); + + t.end(); + }); + + test('OrdinaryGetOwnProperty', function (t) { + forEach(v.primitives, function (primitive) { + t['throws']( + function () { ES.OrdinaryGetOwnProperty(primitive, ''); }, + TypeError, + 'O: ' + debug(primitive) + ' is not an Object' + ); + }); + forEach(v.nonPropertyKeys, function (nonPropertyKey) { + t['throws']( + function () { ES.OrdinaryGetOwnProperty({}, nonPropertyKey); }, + TypeError, + 'P: ' + debug(nonPropertyKey) + ' is not a Property Key' + ); + }); + + t.equal(ES.OrdinaryGetOwnProperty({}, 'not in the object'), undefined, 'missing property yields undefined'); + t.equal(ES.OrdinaryGetOwnProperty({}, 'toString'), undefined, 'inherited non-own property yields undefined'); + + t.deepEqual( + ES.OrdinaryGetOwnProperty({ a: 1 }, 'a'), + ES.ToPropertyDescriptor({ + configurable: true, + enumerable: true, + value: 1, + writable: true + }), + 'own assigned data property yields expected descriptor' + ); + + t.deepEqual( + ES.OrdinaryGetOwnProperty(/a/, 'lastIndex'), + ES.ToPropertyDescriptor({ + configurable: false, + enumerable: false, + value: 0, + writable: true + }), + 'regex lastIndex yields expected descriptor' + ); + + t.deepEqual( + ES.OrdinaryGetOwnProperty([], 'length'), + ES.ToPropertyDescriptor({ + configurable: false, + enumerable: false, + value: 0, + writable: true + }), + 'array length yields expected descriptor' + ); + + t.deepEqual( + ES.OrdinaryGetOwnProperty(Object.prototype, 'toString'), + ES.ToPropertyDescriptor({ + configurable: true, + enumerable: false, + value: Object.prototype.toString, + writable: true + }), + 'own non-enumerable data property yields expected descriptor' + ); + + t.test('ES5+', { skip: !Object.defineProperty }, function (st) { + var O = {}; + Object.defineProperty(O, 'foo', { + configurable: false, + enumerable: false, + value: O, + writable: true + }); + + t.deepEqual( + ES.OrdinaryGetOwnProperty(O, 'foo'), + ES.ToPropertyDescriptor({ + configurable: false, + enumerable: false, + value: O, + writable: true + }), + 'defined own property yields expected descriptor' + ); + + st.end(); + }); + + t.end(); + }); + + test('OrdinaryDefineOwnProperty', { skip: !Object.defineProperty }, function (t) { + forEach(v.primitives, function (primitive) { + t['throws']( + function () { ES.CopyDataProperties(primitive, {}, []); }, + TypeError, + 'O: ' + debug(primitive) + ' is not an Object' + ); + }); + forEach(v.nonPropertyKeys, function (nonPropertyKey) { + t['throws']( + function () { ES.OrdinaryDefineOwnProperty({}, nonPropertyKey, v.genericDescriptor()); }, + TypeError, + 'P: ' + debug(nonPropertyKey) + ' is not a Property Key' + ); + }); + forEach(v.primitives, function (primitive) { + t['throws']( + function () { ES.OrdinaryDefineOwnProperty(primitive, '', v.genericDescriptor()); }, + TypeError, + 'Desc: ' + debug(primitive) + ' is not a Property Descriptor' + ); + }); + + var O = {}; + var P = 'property key'; + var Desc = v.accessorDescriptor(); + t.equal( + ES.OrdinaryDefineOwnProperty(O, P, Desc), + true, + 'operation is successful' + ); + t.deepEqual( + Object.getOwnPropertyDescriptor(O, P), + ES.FromPropertyDescriptor(ES.CompletePropertyDescriptor(Desc)), + 'expected property descriptor is defined' + ); + + t.end(); + }); + + test('ArrayCreate', function (t) { + forEach(v.nonIntegerNumbers.concat([-1]), function (nonIntegerNumber) { + t['throws']( + function () { ES.ArrayCreate(nonIntegerNumber); }, + TypeError, + 'length must be an integer number >= 0' + ); + }); + + t['throws']( + function () { ES.ArrayCreate(Math.pow(2, 32)); }, + RangeError, + 'length must be < 2**32' + ); + + t.deepEqual(ES.ArrayCreate(-0), [], 'length of -0 creates an empty array'); + t.deepEqual(ES.ArrayCreate(0), [], 'length of +0 creates an empty array'); + // eslint-disable-next-line no-sparse-arrays, comma-spacing + t.deepEqual(ES.ArrayCreate(1), [,], 'length of 1 creates a sparse array of length 1'); + // eslint-disable-next-line no-sparse-arrays, comma-spacing + t.deepEqual(ES.ArrayCreate(2), [,,], 'length of 2 creates a sparse array of length 2'); + + // eslint-disable-next-line no-proto + t.test('proto argument', { skip: [].__proto__ !== Array.prototype }, function (st) { + var fakeProto = { + push: { toString: function () { return 'not array push'; } } + }; + st.equal(ES.ArrayCreate(0, fakeProto).push, fakeProto.push, 'passing the proto argument works'); + st.end(); + }); + + t.end(); + }); + + test('ArraySetLength', function (t) { + forEach(v.primitives.concat(v.objects), function (nonArray) { + t['throws']( + function () { ES.ArraySetLength(nonArray, 0); }, + TypeError, + 'A: ' + debug(nonArray) + ' is not an Array' + ); + }); + + forEach(v.nonUndefinedPrimitives, function (primitive) { + t['throws']( + function () { ES.ArraySetLength([], primitive); }, + TypeError, + 'Desc: ' + debug(primitive) + ' is not a Property Descriptor' + ); + }); + + t.test('making length nonwritable', { skip: !Object.defineProperty }, function (st) { + var a = []; + ES.ArraySetLength(a, { '[[Writable]]': false }); + st.deepEqual( + Object.getOwnPropertyDescriptor(a, 'length'), + { + configurable: false, + enumerable: false, + value: 0, + writable: false + }, + 'without a value, length becomes nonwritable' + ); + st.end(); + }); + + var arr = []; + ES.ArraySetLength(arr, { '[[Value]]': 7 }); + t.equal(arr.length, 7, 'array now has a length of 7'); + + t.end(); + }); + + test('CreateHTML', function (t) { + forEach(v.nonStrings, function (nonString) { + t['throws']( + function () { ES.CreateHTML('', nonString, '', ''); }, + TypeError, + 'tag: ' + debug(nonString) + ' is not a String' + ); + t['throws']( + function () { ES.CreateHTML('', '', nonString, ''); }, + TypeError, + 'attribute: ' + debug(nonString) + ' is not a String' + ); + }); + + t.equal( + ES.CreateHTML( + { toString: function () { return 'the string'; } }, + 'some HTML tag!', + '' + ), + 'the string', + 'works with an empty string attribute value' + ); + + t.equal( + ES.CreateHTML( + { toString: function () { return 'the string'; } }, + 'some HTML tag!', + 'attr', + 'value "with quotes"' + ), + 'the string', + 'works with an attribute, and a value with quotes' + ); + + t.end(); + }); + + test('GetOwnPropertyKeys', function (t) { + forEach(v.primitives, function (primitive) { + t['throws']( + function () { ES.GetOwnPropertyKeys(primitive, 'String'); }, + TypeError, + 'O: ' + debug(primitive) + ' is not an Object' + ); + }); + + t['throws']( + function () { ES.GetOwnPropertyKeys({}, 'not string or symbol'); }, + TypeError, + 'Type: must be "String" or "Symbol"' + ); + + t.test('Symbols', { skip: !v.hasSymbols }, function (st) { + var O = { a: 1 }; + O[Symbol.iterator] = true; + var s = Symbol('test'); + Object.defineProperty(O, s, { enumerable: false, value: true }); + + st.deepEqual( + ES.GetOwnPropertyKeys(O, 'Symbol'), + [Symbol.iterator, s], + 'works with Symbols, enumerable or not' + ); + + st.end(); + }); + + t.test('non-enumerable names', { skip: !Object.defineProperty }, function (st) { + var O = { a: 1 }; + Object.defineProperty(O, 'b', { enumerable: false, value: 2 }); + if (v.hasSymbols) { + O[Symbol.iterator] = true; + } + + st.deepEqual( + ES.GetOwnPropertyKeys(O, 'String').sort(), + ['a', 'b'].sort(), + 'works with Strings, enumerable or not' + ); + + st.end(); + }); + + t.deepEqual( + ES.GetOwnPropertyKeys({ a: 1, b: 2 }, 'String').sort(), + ['a', 'b'].sort(), + 'works with enumerable keys' + ); + + t.end(); + }); + + test('SymbolDescriptiveString', function (t) { + forEach(v.nonSymbolPrimitives.concat(v.objects), function (nonSymbol) { + t['throws']( + function () { ES.SymbolDescriptiveString(nonSymbol); }, + TypeError, + debug(nonSymbol) + ' is not a Symbol' + ); + }); + + t.test('Symbols', { skip: !v.hasSymbols }, function (st) { + st.equal(ES.SymbolDescriptiveString(Symbol()), 'Symbol()', 'undefined description'); + st.equal(ES.SymbolDescriptiveString(Symbol('')), 'Symbol()', 'empty string description'); + st.equal(ES.SymbolDescriptiveString(Symbol.iterator), 'Symbol(Symbol.iterator)', 'well-known symbol'); + st.equal(ES.SymbolDescriptiveString(Symbol('foo')), 'Symbol(foo)', 'string description'); + + st.end(); + }); + + t.end(); + }); + + test('GetSubstitution', { skip: skips && skips.GetSubstitution }, function (t) { + forEach(v.nonStrings, function (nonString) { + t['throws']( + function () { ES.GetSubstitution(nonString, '', 0, [], ''); }, + TypeError, + '`matched`: ' + debug(nonString) + ' is not a String' + ); + + t['throws']( + function () { ES.GetSubstitution('', nonString, 0, [], ''); }, + TypeError, + '`str`: ' + debug(nonString) + ' is not a String' + ); + + t['throws']( + function () { ES.GetSubstitution('', '', 0, [], nonString); }, + TypeError, + '`replacement`: ' + debug(nonString) + ' is not a String' + ); + + t['throws']( + function () { ES.GetSubstitution('', '', 0, [nonString], ''); }, + TypeError, + '`captures`: ' + debug([nonString]) + ' is not an Array of strings' + ); + }); + + forEach(v.nonIntegerNumbers.concat([-1, -42, -Infinity]), function (nonNonNegativeInteger) { + t['throws']( + function () { ES.GetSubstitution('', '', nonNonNegativeInteger, [], ''); }, + TypeError, + '`position`: ' + debug(nonNonNegativeInteger) + ' is not a non-negative integer' + ); + }); + + forEach(v.nonArrays, function (nonArray) { + t['throws']( + function () { ES.GetSubstitution('', '', 0, nonArray, ''); }, + TypeError, + '`captures`: ' + debug(nonArray) + ' is not an Array' + ); + }); + + t.equal( + ES.GetSubstitution('def', 'abcdefghi', 3, [], '123'), + '123', + 'returns the substitution' + ); + t.equal( + ES.GetSubstitution('abcdef', 'abcdefghi', 0, [], '$$2$'), + '$2$', + 'supports $$, and trailing $' + ); + + t.equal( + ES.GetSubstitution('abcdef', 'abcdefghi', 0, [], '>$&<'), + '>abcdef<', + 'supports $&' + ); + + t.equal( + ES.GetSubstitution('abcdef', 'abcdefghi', 0, [], '>$`<'), + '><', + 'supports $` at position 0' + ); + t.equal( + ES.GetSubstitution('def', 'abcdefghi', 3, [], '>$`<'), + '>ab<', + 'supports $` at position > 0' + ); + + t.equal( + ES.GetSubstitution('def', 'abcdefghi', 7, [], ">$'<"), + '><', + "supports $' at a position where there's less than `matched.length` chars left" + ); + t.equal( + ES.GetSubstitution('def', 'abcdefghi', 3, [], ">$'<"), + '>ghi<', + "supports $' at a position where there's more than `matched.length` chars left" + ); + + for (var i = 0; i < 100; i += 1) { + var captures = []; + captures[i] = 'test'; + if (i > 0) { + t.equal( + ES.GetSubstitution('abcdef', 'abcdefghi', 0, [], '>$' + i + '<'), + '>undefined<', + 'supports $' + i + ' with no captures' + ); + t.equal( + ES.GetSubstitution('abcdef', 'abcdefghi', 0, [], '>$' + i), + '>undefined', + 'supports $' + i + ' at the end of the replacement, with no captures' + ); + t.equal( + ES.GetSubstitution('abcdef', 'abcdefghi', 0, captures, '>$' + i + '<'), + '><', + 'supports $' + i + ' with a capture at that index' + ); + t.equal( + ES.GetSubstitution('abcdef', 'abcdefghi', 0, captures, '>$' + i), + '>', + 'supports $' + i + ' at the end of the replacement, with a capture at that index' + ); + } + if (i < 10) { + t.equal( + ES.GetSubstitution('abcdef', 'abcdefghi', 0, [], '>$0' + i + '<'), + i === 0 ? '><' : '>undefined<', + 'supports $0' + i + ' with no captures' + ); + t.equal( + ES.GetSubstitution('abcdef', 'abcdefghi', 0, [], '>$0' + i), + i === 0 ? '>' : '>undefined', + 'supports $0' + i + ' at the end of the replacement, with no captures' + ); + t.equal( + ES.GetSubstitution('abcdef', 'abcdefghi', 0, captures, '>$0' + i + '<'), + '><', + 'supports $0' + i + ' with a capture at that index' + ); + t.equal( + ES.GetSubstitution('abcdef', 'abcdefghi', 0, captures, '>$0' + i), + '>', + 'supports $0' + i + ' at the end of the replacement, with a capture at that index' + ); + } + } + + t.end(); + }); + + test('SecFromTime', function (t) { + var now = new Date(); + t.equal(ES.SecFromTime(now.getTime()), now.getUTCSeconds(), 'second from Date timestamp matches getUTCSeconds'); + t.end(); + }); + + test('MinFromTime', function (t) { + var now = new Date(); + t.equal(ES.MinFromTime(now.getTime()), now.getUTCMinutes(), 'minute from Date timestamp matches getUTCMinutes'); + t.end(); + }); + + test('HourFromTime', function (t) { + var now = new Date(); + t.equal(ES.HourFromTime(now.getTime()), now.getUTCHours(), 'hour from Date timestamp matches getUTCHours'); + t.end(); + }); + + test('msFromTime', function (t) { + var now = new Date(); + t.equal(ES.msFromTime(now.getTime()), now.getUTCMilliseconds(), 'ms from Date timestamp matches getUTCMilliseconds'); + t.end(); + }); + + var msPerSecond = 1e3; + var msPerMinute = 60 * msPerSecond; + var msPerHour = 60 * msPerMinute; + var msPerDay = 24 * msPerHour; + + test('Day', function (t) { + var time = Date.UTC(2019, 8, 10, 2, 3, 4, 5); + var add = 2.5; + var later = new Date(time + (add * msPerDay)); + + t.equal(ES.Day(later.getTime()), ES.Day(time) + Math.floor(add), 'adding 2.5 days worth of ms, gives a Day delta of 2'); + t.end(); + }); + + test('TimeWithinDay', function (t) { + var time = Date.UTC(2019, 8, 10, 2, 3, 4, 5); + var add = 2.5; + var later = new Date(time + (add * msPerDay)); + + t.equal(ES.TimeWithinDay(later.getTime()), ES.TimeWithinDay(time) + (0.5 * msPerDay), 'adding 2.5 days worth of ms, gives a TimeWithinDay delta of +0.5'); + t.end(); + }); + + test('DayFromYear', function (t) { + t.equal(ES.DayFromYear(2021) - ES.DayFromYear(2020), 366, '2021 is a leap year, has 366 days'); + t.equal(ES.DayFromYear(2020) - ES.DayFromYear(2019), 365, '2020 is not a leap year, has 365 days'); + t.equal(ES.DayFromYear(2019) - ES.DayFromYear(2018), 365, '2019 is not a leap year, has 365 days'); + t.equal(ES.DayFromYear(2018) - ES.DayFromYear(2017), 365, '2018 is not a leap year, has 365 days'); + t.equal(ES.DayFromYear(2017) - ES.DayFromYear(2016), 366, '2017 is a leap year, has 366 days'); + + t.end(); + }); + + test('TimeFromYear', function (t) { + for (var i = 1900; i < 2100; i += 1) { + t.equal(ES.TimeFromYear(i), Date.UTC(i, 0, 1), 'TimeFromYear matches a Date object’s year: ' + i); + } + t.end(); + }); + + test('YearFromTime', function (t) { + for (var i = 1900; i < 2100; i += 1) { + t.equal(ES.YearFromTime(Date.UTC(i, 0, 1)), i, 'YearFromTime matches a Date object’s year on 1/1: ' + i); + t.equal(ES.YearFromTime(Date.UTC(i, 10, 1)), i, 'YearFromTime matches a Date object’s year on 10/1: ' + i); + } + t.end(); + }); + + test('WeekDay', function (t) { + var now = new Date(); + var today = now.getUTCDay(); + for (var i = 0; i < 7; i += 1) { + var weekDay = ES.WeekDay(now.getTime() + (i * msPerDay)); + t.equal(weekDay, (today + i) % 7, i + ' days after today (' + today + '), WeekDay is ' + weekDay); + } + t.end(); + }); + + test('DaysInYear', function (t) { + t.equal(ES.DaysInYear(2021), 365, '2021 is not a leap year'); + t.equal(ES.DaysInYear(2020), 366, '2020 is a leap year'); + t.equal(ES.DaysInYear(2019), 365, '2019 is not a leap year'); + t.equal(ES.DaysInYear(2018), 365, '2018 is not a leap year'); + t.equal(ES.DaysInYear(2017), 365, '2017 is not a leap year'); + t.equal(ES.DaysInYear(2016), 366, '2016 is a leap year'); + + t.end(); + }); + + test('InLeapYear', function (t) { + t.equal(ES.InLeapYear(Date.UTC(2021, 0, 1)), 0, '2021 is not a leap year'); + t.equal(ES.InLeapYear(Date.UTC(2020, 0, 1)), 1, '2020 is a leap year'); + t.equal(ES.InLeapYear(Date.UTC(2019, 0, 1)), 0, '2019 is not a leap year'); + t.equal(ES.InLeapYear(Date.UTC(2018, 0, 1)), 0, '2018 is not a leap year'); + t.equal(ES.InLeapYear(Date.UTC(2017, 0, 1)), 0, '2017 is not a leap year'); + t.equal(ES.InLeapYear(Date.UTC(2016, 0, 1)), 1, '2016 is a leap year'); + + t.end(); + }); + + test('DayWithinYear', function (t) { + t.equal(ES.DayWithinYear(Date.UTC(2019, 0, 1)), 0, '1/1 is the 1st day'); + t.equal(ES.DayWithinYear(Date.UTC(2019, 11, 31)), 364, '12/31 is the 365th day in a non leap year'); + t.equal(ES.DayWithinYear(Date.UTC(2016, 11, 31)), 365, '12/31 is the 366th day in a leap year'); + + t.end(); + }); + + test('MonthFromTime', function (t) { + t.equal(ES.MonthFromTime(Date.UTC(2019, 0, 1)), 0, 'non-leap: 1/1 gives January'); + t.equal(ES.MonthFromTime(Date.UTC(2019, 0, 31)), 0, 'non-leap: 1/31 gives January'); + t.equal(ES.MonthFromTime(Date.UTC(2019, 1, 1)), 1, 'non-leap: 2/1 gives February'); + t.equal(ES.MonthFromTime(Date.UTC(2019, 1, 28)), 1, 'non-leap: 2/28 gives February'); + t.equal(ES.MonthFromTime(Date.UTC(2019, 1, 29)), 2, 'non-leap: 2/29 gives March'); + t.equal(ES.MonthFromTime(Date.UTC(2019, 2, 1)), 2, 'non-leap: 3/1 gives March'); + t.equal(ES.MonthFromTime(Date.UTC(2019, 2, 31)), 2, 'non-leap: 3/31 gives March'); + t.equal(ES.MonthFromTime(Date.UTC(2019, 3, 1)), 3, 'non-leap: 4/1 gives April'); + t.equal(ES.MonthFromTime(Date.UTC(2019, 3, 30)), 3, 'non-leap: 4/30 gives April'); + t.equal(ES.MonthFromTime(Date.UTC(2019, 4, 1)), 4, 'non-leap: 5/1 gives May'); + t.equal(ES.MonthFromTime(Date.UTC(2019, 4, 31)), 4, 'non-leap: 5/31 gives May'); + t.equal(ES.MonthFromTime(Date.UTC(2019, 5, 1)), 5, 'non-leap: 6/1 gives June'); + t.equal(ES.MonthFromTime(Date.UTC(2019, 5, 30)), 5, 'non-leap: 6/30 gives June'); + t.equal(ES.MonthFromTime(Date.UTC(2019, 6, 1)), 6, 'non-leap: 7/1 gives July'); + t.equal(ES.MonthFromTime(Date.UTC(2019, 6, 31)), 6, 'non-leap: 7/31 gives July'); + t.equal(ES.MonthFromTime(Date.UTC(2019, 7, 1)), 7, 'non-leap: 8/1 gives August'); + t.equal(ES.MonthFromTime(Date.UTC(2019, 7, 30)), 7, 'non-leap: 8/30 gives August'); + t.equal(ES.MonthFromTime(Date.UTC(2019, 8, 1)), 8, 'non-leap: 9/1 gives September'); + t.equal(ES.MonthFromTime(Date.UTC(2019, 8, 30)), 8, 'non-leap: 9/30 gives September'); + t.equal(ES.MonthFromTime(Date.UTC(2019, 9, 1)), 9, 'non-leap: 10/1 gives October'); + t.equal(ES.MonthFromTime(Date.UTC(2019, 9, 31)), 9, 'non-leap: 10/31 gives October'); + t.equal(ES.MonthFromTime(Date.UTC(2019, 10, 1)), 10, 'non-leap: 11/1 gives November'); + t.equal(ES.MonthFromTime(Date.UTC(2019, 10, 30)), 10, 'non-leap: 11/30 gives November'); + t.equal(ES.MonthFromTime(Date.UTC(2019, 11, 1)), 11, 'non-leap: 12/1 gives December'); + t.equal(ES.MonthFromTime(Date.UTC(2019, 11, 31)), 11, 'non-leap: 12/31 gives December'); + + t.equal(ES.MonthFromTime(Date.UTC(2016, 0, 1)), 0, 'leap: 1/1 gives January'); + t.equal(ES.MonthFromTime(Date.UTC(2016, 0, 31)), 0, 'leap: 1/31 gives January'); + t.equal(ES.MonthFromTime(Date.UTC(2016, 1, 1)), 1, 'leap: 2/1 gives February'); + t.equal(ES.MonthFromTime(Date.UTC(2016, 1, 28)), 1, 'leap: 2/28 gives February'); + t.equal(ES.MonthFromTime(Date.UTC(2016, 1, 29)), 1, 'leap: 2/29 gives February'); + t.equal(ES.MonthFromTime(Date.UTC(2016, 2, 1)), 2, 'leap: 3/1 gives March'); + t.equal(ES.MonthFromTime(Date.UTC(2016, 2, 31)), 2, 'leap: 3/31 gives March'); + t.equal(ES.MonthFromTime(Date.UTC(2016, 3, 1)), 3, 'leap: 4/1 gives April'); + t.equal(ES.MonthFromTime(Date.UTC(2016, 3, 30)), 3, 'leap: 4/30 gives April'); + t.equal(ES.MonthFromTime(Date.UTC(2016, 4, 1)), 4, 'leap: 5/1 gives May'); + t.equal(ES.MonthFromTime(Date.UTC(2016, 4, 31)), 4, 'leap: 5/31 gives May'); + t.equal(ES.MonthFromTime(Date.UTC(2016, 5, 1)), 5, 'leap: 6/1 gives June'); + t.equal(ES.MonthFromTime(Date.UTC(2016, 5, 30)), 5, 'leap: 6/30 gives June'); + t.equal(ES.MonthFromTime(Date.UTC(2016, 6, 1)), 6, 'leap: 7/1 gives July'); + t.equal(ES.MonthFromTime(Date.UTC(2016, 6, 31)), 6, 'leap: 7/31 gives July'); + t.equal(ES.MonthFromTime(Date.UTC(2016, 7, 1)), 7, 'leap: 8/1 gives August'); + t.equal(ES.MonthFromTime(Date.UTC(2016, 7, 30)), 7, 'leap: 8/30 gives August'); + t.equal(ES.MonthFromTime(Date.UTC(2016, 8, 1)), 8, 'leap: 9/1 gives September'); + t.equal(ES.MonthFromTime(Date.UTC(2016, 8, 30)), 8, 'leap: 9/30 gives September'); + t.equal(ES.MonthFromTime(Date.UTC(2016, 9, 1)), 9, 'leap: 10/1 gives October'); + t.equal(ES.MonthFromTime(Date.UTC(2016, 9, 31)), 9, 'leap: 10/31 gives October'); + t.equal(ES.MonthFromTime(Date.UTC(2016, 10, 1)), 10, 'leap: 11/1 gives November'); + t.equal(ES.MonthFromTime(Date.UTC(2016, 10, 30)), 10, 'leap: 11/30 gives November'); + t.equal(ES.MonthFromTime(Date.UTC(2016, 11, 1)), 11, 'leap: 12/1 gives December'); + t.equal(ES.MonthFromTime(Date.UTC(2016, 11, 31)), 11, 'leap: 12/31 gives December'); + t.end(); + }); + + test('DateFromTime', function (t) { + var i; + for (i = 1; i <= 28; i += 1) { + t.equal(ES.DateFromTime(Date.UTC(2019, 1, i)), i, '2019.02.' + i + ' is date ' + i); + } + for (i = 1; i <= 29; i += 1) { + t.equal(ES.DateFromTime(Date.UTC(2016, 1, i)), i, '2016.02.' + i + ' is date ' + i); + } + for (i = 1; i <= 30; i += 1) { + t.equal(ES.DateFromTime(Date.UTC(2019, 8, i)), i, '2019.09.' + i + ' is date ' + i); + } + for (i = 1; i <= 31; i += 1) { + t.equal(ES.DateFromTime(Date.UTC(2019, 9, i)), i, '2019.10.' + i + ' is date ' + i); + } + t.end(); + }); + + test('MakeDay', function (t) { + var day2015 = 16687; + t.equal(ES.MakeDay(2015, 8, 9), day2015, '2015.09.09 is day 16687'); + var day2016 = day2015 + 366; // 2016 is a leap year + t.equal(ES.MakeDay(2016, 8, 9), day2016, '2015.09.09 is day 17053'); + var day2017 = day2016 + 365; + t.equal(ES.MakeDay(2017, 8, 9), day2017, '2017.09.09 is day 17418'); + var day2018 = day2017 + 365; + t.equal(ES.MakeDay(2018, 8, 9), day2018, '2018.09.09 is day 17783'); + var day2019 = day2018 + 365; + t.equal(ES.MakeDay(2019, 8, 9), day2019, '2019.09.09 is day 18148'); + t.end(); + }); + + test('MakeDate', function (t) { + forEach(v.infinities.concat(NaN), function (nonFiniteNumber) { + t.ok(is(ES.MakeDate(nonFiniteNumber, 0), NaN), debug(nonFiniteNumber) + ' is not a finite `day`'); + t.ok(is(ES.MakeDate(0, nonFiniteNumber), NaN), debug(nonFiniteNumber) + ' is not a finite `time`'); + }); + t.equal(ES.MakeDate(0, 0), 0, 'zero day and zero time is zero date'); + t.equal(ES.MakeDate(0, 123), 123, 'zero day and nonzero time is a date of the "time"'); + t.equal(ES.MakeDate(1, 0), msPerDay, 'day of 1 and zero time is a date of "ms per day"'); + t.equal(ES.MakeDate(3, 0), 3 * msPerDay, 'day of 3 and zero time is a date of thrice "ms per day"'); + t.equal(ES.MakeDate(1, 123), msPerDay + 123, 'day of 1 and nonzero time is a date of "ms per day" plus the "time"'); + t.equal(ES.MakeDate(3, 123), (3 * msPerDay) + 123, 'day of 3 and nonzero time is a date of thrice "ms per day" plus the "time"'); + + t.end(); + }); + + test('MakeTime', function (t) { + forEach(v.infinities.concat(NaN), function (nonFiniteNumber) { + t.ok(is(ES.MakeTime(nonFiniteNumber, 0, 0, 0), NaN), debug(nonFiniteNumber) + ' is not a finite `hour`'); + t.ok(is(ES.MakeTime(0, nonFiniteNumber, 0, 0), NaN), debug(nonFiniteNumber) + ' is not a finite `min`'); + t.ok(is(ES.MakeTime(0, 0, nonFiniteNumber, 0), NaN), debug(nonFiniteNumber) + ' is not a finite `sec`'); + t.ok(is(ES.MakeTime(0, 0, 0, nonFiniteNumber), NaN), debug(nonFiniteNumber) + ' is not a finite `ms`'); + }); + + t.equal( + ES.MakeTime(1.2, 2.3, 3.4, 4.5), + (1 * msPerHour) + (2 * msPerMinute) + (3 * msPerSecond) + 4, + 'all numbers are converted to integer, multiplied by the right number of ms, and summed' + ); + + t.end(); + }); + + test('TimeClip', function (t) { + forEach(v.infinities.concat(NaN), function (nonFiniteNumber) { + t.ok(is(ES.TimeClip(nonFiniteNumber), NaN), debug(nonFiniteNumber) + ' is not a finite `time`'); + }); + t.ok(is(ES.TimeClip(8.64e15 + 1), NaN), '8.64e15 is the largest magnitude considered "finite"'); + t.ok(is(ES.TimeClip(-8.64e15 - 1), NaN), '-8.64e15 is the largest magnitude considered "finite"'); + + forEach(v.zeroes.concat([-10, 10, Date.now()]), function (time) { + t.equal(ES.TimeClip(time), time, debug(time) + ' is a time of ' + debug(time)); + }); + + t.end(); + }); + + test('modulo', function (t) { + t.equal(3 % 2, 1, '+3 % 2 is +1'); + t.equal(ES.modulo(3, 2), 1, '+3 mod 2 is +1'); + + t.equal(-3 % 2, -1, '-3 % 2 is -1'); + t.equal(ES.modulo(-3, 2), 1, '-3 mod 2 is +1'); + t.end(); + }); + + test('ToDateString', function (t) { + forEach(v.nonNumbers, function (nonNumber) { + t['throws']( + function () { ES.ToDateString(nonNumber); }, + TypeError, + debug(nonNumber) + ' is not a Number' + ); + }); + + t.equal(ES.ToDateString(NaN), 'Invalid Date', 'NaN becomes "Invalid Date"'); + var now = Date.now(); + t.equal(ES.ToDateString(now), Date(now), 'any timestamp becomes `Date(timestamp)`'); + t.end(); + }); + + test('CreateListFromArrayLike', function (t) { + forEach(v.primitives, function (nonObject) { + t['throws']( + function () { ES.CreateListFromArrayLike(nonObject); }, + TypeError, + debug(nonObject) + ' is not an Object' + ); + }); + forEach(v.nonArrays, function (nonArray) { + t['throws']( + function () { ES.CreateListFromArrayLike({}, nonArray); }, + TypeError, + debug(nonArray) + ' is not an Array' + ); + }); + + t.deepEqual( + ES.CreateListFromArrayLike({ length: 2, 0: 'a', 1: 'b', 2: 'c' }), + ['a', 'b'], + 'arraylike stops at the length' + ); + + t.end(); + }); + + test('GetPrototypeFromConstructor', function (t) { + forEach(v.nonFunctions, function (nonFunction) { + t['throws']( + function () { ES.GetPrototypeFromConstructor(nonFunction, '%Array%'); }, + TypeError, + debug(nonFunction) + ' is not a constructor' + ); + }); + + forEach(arrowFns, function (arrowFn) { + t['throws']( + function () { ES.GetPrototypeFromConstructor(arrowFn, '%Array%'); }, + TypeError, + debug(arrowFn) + ' is not a constructor' + ); + }); + + var f = function () {}; + t.equal( + ES.GetPrototypeFromConstructor(f, '%Array.prototype%'), + f.prototype, + 'function with normal `prototype` property returns it' + ); + forEach([true, 'foo', 42], function (truthyPrimitive) { + f.prototype = truthyPrimitive; + t.equal( + ES.GetPrototypeFromConstructor(f, '%Array.prototype%'), + Array.prototype, + 'function with non-object `prototype` property (' + debug(truthyPrimitive) + ') returns default intrinsic' + ); + }); + + t.end(); + }); + + var getNamelessFunction = function () { + var f = Object(function () {}); + try { + delete f.name; + } catch (e) { /**/ } + return f; + }; + + test('SetFunctionName', function (t) { + t.test('non-extensible function', { skip: !Object.preventExtensions }, function (st) { + var f = getNamelessFunction(); + Object.preventExtensions(f); + st['throws']( + function () { ES.SetFunctionName(f, ''); }, + TypeError, + 'throws on a non-extensible function' + ); + st.end(); + }); + + t['throws']( + function () { ES.SetFunctionName(function g() {}, ''); }, + TypeError, + 'throws if function has an own `name` property' + ); + + forEach(v.nonPropertyKeys, function (nonPropertyKey) { + t['throws']( + function () { ES.SetFunctionName(getNamelessFunction(), nonPropertyKey); }, + TypeError, + debug(nonPropertyKey) + ' is not a Symbol or String' + ); + }); + + t.test('symbols', { skip: !v.hasSymbols || has(getNamelessFunction(), 'name') }, function (st) { + var pairs = [ + [Symbol(), ''], + [Symbol(undefined), ''], + [Symbol(null), '[null]'], + [Symbol(''), getInferredName ? '[]' : ''], + [Symbol.iterator, '[Symbol.iterator]'], + [Symbol('foo'), '[foo]'] + ]; + forEach(pairs, function (pair) { + var sym = pair[0]; + var desc = pair[1]; + var f = getNamelessFunction(); + ES.SetFunctionName(f, sym); + st.equal(f.name, desc, debug(sym) + ' yields a name of ' + debug(desc)); + }); + + st.end(); + }); + + var f = getNamelessFunction(); + t.test('when names are configurable', { skip: has(f, 'name') }, function (st) { + // without prefix + st.notEqual(f.name, 'foo', 'precondition'); + ES.SetFunctionName(f, 'foo'); + st.equal(f.name, 'foo', 'function name is set without a prefix'); + + // with prefix + var g = getNamelessFunction(); + st.notEqual(g.name, 'pre- foo', 'precondition'); + ES.SetFunctionName(g, 'foo', 'pre-'); + st.equal(g.name, 'pre- foo', 'function name is set with a prefix'); + + st.end(); + }); + + t.end(); + }); +}; + +var es2016 = function ES2016(ES, ops, expectedMissing, skips) { + es2015(ES, ops, expectedMissing, skips); + + test('SameValueNonNumber', function (t) { + var willThrow = [ + [3, 4], + [NaN, 4], + [4, ''], + ['abc', true], + [{}, false] + ]; + forEach(willThrow, function (nums) { + t['throws'](function () { return ES.SameValueNonNumber.apply(ES, nums); }, TypeError, 'value must be same type and non-number'); + }); + + forEach(v.objects.concat(v.nonNumberPrimitives), function (val) { + t.equal(val === val, ES.SameValueNonNumber(val, val), debug(val) + ' is SameValueNonNumber to itself'); + }); + + t.end(); + }); + + test('IterableToArrayLike', { skip: skips && skips.IterableToArrayLike }, function (t) { + t.test('custom iterables', { skip: !v.hasSymbols }, function (st) { + var O = {}; + O[Symbol.iterator] = function () { + var i = -1; + return { + next: function () { + i += 1; + return { + done: i >= 5, + value: i + }; + } + }; + }; + st.deepEqual( + ES.IterableToArrayLike(O), + [0, 1, 2, 3, 4], + 'Symbol.iterator method is called and values collected' + ); + + st.end(); + }); + + t.deepEqual(ES.IterableToArrayLike('abc'), ['a', 'b', 'c'], 'a string of code units spreads'); + t.deepEqual(ES.IterableToArrayLike('💩'), ['💩'], 'a string of code points spreads'); + t.deepEqual(ES.IterableToArrayLike('a💩c'), ['a', '💩', 'c'], 'a string of code points and units spreads'); + + var arr = [1, 2, 3]; + t.deepEqual(ES.IterableToArrayLike(arr), arr, 'an array becomes a similar array'); + t.notEqual(ES.IterableToArrayLike(arr), arr, 'an array becomes a different, but similar, array'); + + var O = {}; + t.equal(ES.IterableToArrayLike(O), O, 'a non-iterable non-array non-string object is returned directly'); + + t.end(); + }); + + test('OrdinaryGetPrototypeOf', function (t) { + t.equal(ES.OrdinaryGetPrototypeOf([]), Array.prototype, 'array [[Prototype]] is Array.prototype'); + t.equal(ES.OrdinaryGetPrototypeOf({}), Object.prototype, 'object [[Prototype]] is Object.prototype'); + t.equal(ES.OrdinaryGetPrototypeOf(/a/g), RegExp.prototype, 'regex [[Prototype]] is RegExp.prototype'); + t.equal(ES.OrdinaryGetPrototypeOf(Object('')), String.prototype, 'boxed string [[Prototype]] is String.prototype'); + t.equal(ES.OrdinaryGetPrototypeOf(Object(42)), Number.prototype, 'boxed number [[Prototype]] is Number.prototype'); + t.equal(ES.OrdinaryGetPrototypeOf(Object(true)), Boolean.prototype, 'boxed boolean [[Prototype]] is Boolean.prototype'); + if (v.hasSymbols) { + t.equal(ES.OrdinaryGetPrototypeOf(Object(Symbol.iterator)), Symbol.prototype, 'boxed symbol [[Prototype]] is Symbol.prototype'); + } + + forEach(v.primitives, function (primitive) { + t['throws']( + function () { ES.OrdinaryGetPrototypeOf(primitive); }, + TypeError, + debug(primitive) + ' is not an Object' + ); + }); + t.end(); + }); + + test('OrdinarySetPrototypeOf', function (t) { + var a = []; + var proto = {}; + + t.equal(ES.OrdinaryGetPrototypeOf(a), Array.prototype, 'precondition'); + t.equal(ES.OrdinarySetPrototypeOf(a, proto), true, 'setting prototype is successful'); + t.equal(ES.OrdinaryGetPrototypeOf(a), proto, 'postcondition'); + + t.end(); + }); +}; + +var es2017 = function ES2017(ES, ops, expectedMissing, skips) { + es2016(ES, ops, expectedMissing, assign({}, skips, { + EnumerableOwnNames: true, + IterableToArrayLike: true + })); + + test('ToIndex', function (t) { + t.ok(is(ES.ToIndex(), 0), 'no value gives 0'); + t.ok(is(ES.ToIndex(undefined), 0), 'undefined value gives 0'); + + t['throws'](function () { ES.ToIndex(-1); }, RangeError, 'negative numbers throw'); + + t['throws'](function () { ES.ToIndex(MAX_SAFE_INTEGER + 1); }, RangeError, 'too large numbers throw'); + + t.equal(ES.ToIndex(3), 3, 'numbers work'); + t.equal(ES.ToIndex(v.valueOfOnlyObject), 4, 'coercible objects are coerced'); + + t.end(); + }); + + test('EnumerableOwnProperties', { skip: skips && skips.EnumerableOwnProperties }, function (t) { + var obj = testEnumerableOwnNames(t, function (O) { + return ES.EnumerableOwnProperties(O, 'key'); + }); + + t.deepEqual( + ES.EnumerableOwnProperties(obj, 'value'), + [obj.own], + 'returns enumerable own values' + ); + + t.deepEqual( + ES.EnumerableOwnProperties(obj, 'key+value'), + [['own', obj.own]], + 'returns enumerable own entries' + ); + + t.end(); + }); + + test('IterableToList', function (t) { + var customIterator = function () { + var i = -1; + return { + next: function () { + i += 1; + return { + done: i >= 5, + value: i + }; + } + }; + }; + + t.deepEqual( + ES.IterableToList({}, customIterator), + [0, 1, 2, 3, 4], + 'iterator method is called and values collected' + ); + + t.test('Symbol support', { skip: !v.hasSymbols }, function (st) { + st.deepEqual(ES.IterableToList('abc', String.prototype[Symbol.iterator]), ['a', 'b', 'c'], 'a string of code units spreads'); + st.deepEqual(ES.IterableToList('☃', String.prototype[Symbol.iterator]), ['☃'], 'a string of code points spreads'); + + var arr = [1, 2, 3]; + st.deepEqual(ES.IterableToList(arr, arr[Symbol.iterator]), arr, 'an array becomes a similar array'); + st.notEqual(ES.IterableToList(arr, arr[Symbol.iterator]), arr, 'an array becomes a different, but similar, array'); + + st.end(); + }); + + t['throws']( + function () { ES.IterableToList({}, void 0); }, + TypeError, + 'non-function iterator method' + ); + + t.end(); + }); +}; + +var es2018 = function ES2018(ES, ops, expectedMissing, skips) { + es2017(ES, ops, expectedMissing, assign({}, skips, { + EnumerableOwnProperties: true, + GetSubstitution: true, + IsPropertyDescriptor: true + })); + + test('thisSymbolValue', function (t) { + forEach(v.nonSymbolPrimitives.concat(v.objects), function (nonSymbol) { + t['throws']( + function () { ES.thisSymbolValue(nonSymbol); }, + v.hasSymbols ? TypeError : SyntaxError, + debug(nonSymbol) + ' is not a Symbol' + ); + }); + + t.test('no native Symbols', { skip: v.hasSymbols }, function (st) { + forEach(v.objects.concat(v.primitives), function (value) { + st['throws']( + function () { ES.thisSymbolValue(value); }, + SyntaxError, + 'Symbols are not supported' + ); + }); + st.end(); + }); + + t.test('symbol values', { skip: !v.hasSymbols }, function (st) { + forEach(v.symbols, function (symbol) { + st.equal(ES.thisSymbolValue(symbol), symbol, 'Symbol value of ' + debug(symbol) + ' is same symbol'); + + st.equal( + ES.thisSymbolValue(Object(symbol)), + symbol, + 'Symbol value of ' + debug(Object(symbol)) + ' is ' + debug(symbol) + ); + }); + + st.end(); + }); + + t.end(); + }); + + test('IsStringPrefix', function (t) { + forEach(v.nonStrings, function (nonString) { + t['throws']( + function () { ES.IsStringPrefix(nonString, 'a'); }, + TypeError, + 'first arg: ' + debug(nonString) + ' is not a string' + ); + t['throws']( + function () { ES.IsStringPrefix('a', nonString); }, + TypeError, + 'second arg: ' + debug(nonString) + ' is not a string' + ); + }); + + forEach(v.strings, function (string) { + t.equal(ES.IsStringPrefix(string, string), true, debug(string) + ' is a prefix of itself'); + + t.equal(ES.IsStringPrefix('', string), true, 'the empty string is a prefix of everything'); + }); + + t.equal(ES.IsStringPrefix('abc', 'abcd'), true, '"abc" is a prefix of "abcd"'); + t.equal(ES.IsStringPrefix('abcd', 'abc'), false, '"abcd" is not a prefix of "abc"'); + + t.equal(ES.IsStringPrefix('a', 'bc'), false, '"a" is not a prefix of "bc"'); + + t.end(); + }); + + test('NumberToString', function (t) { + forEach(v.nonNumbers, function (nonNumber) { + t['throws']( + function () { ES.NumberToString(nonNumber); }, + TypeError, + debug(nonNumber) + ' is not a Number' + ); + }); + + forEach(v.numbers, function (number) { + t.equal(ES.NumberToString(number), String(number), debug(number) + ' stringifies to ' + number); + }); + + t.end(); + }); + + test('CopyDataProperties', function (t) { + t.test('first argument: target', function (st) { + forEach(v.primitives, function (primitive) { + st['throws']( + function () { ES.CopyDataProperties(primitive, {}, []); }, + TypeError, + debug(primitive) + ' is not an Object' + ); + }); + st.end(); + }); + + t.test('second argument: source', function (st) { + var frozenTarget = Object.freeze ? Object.freeze({}) : {}; + forEach(v.nullPrimitives, function (nullish) { + st.equal( + ES.CopyDataProperties(frozenTarget, nullish, []), + frozenTarget, + debug(nullish) + ' "source" yields identical, unmodified target' + ); + }); + + forEach(v.nonNullPrimitives, function (objectCoercible) { + var target = {}; + var result = ES.CopyDataProperties(target, objectCoercible, []); + st.equal(result, target, 'result === target'); + st.deepEqual(keys(result), keys(Object(objectCoercible)), 'target ends up with keys of ' + debug(objectCoercible)); + }); + + st.end(); + }); + + t.test('third argument: excludedItems', function (st) { + forEach(v.objects.concat(v.primitives), function (nonArray) { + st['throws']( + function () { ES.CopyDataProperties({}, {}, nonArray); }, + TypeError, + debug(nonArray) + ' is not an Array' + ); + }); + + forEach(v.nonPropertyKeys, function (nonPropertyKey) { + st['throws']( + function () { ES.CopyDataProperties({}, {}, [nonPropertyKey]); }, + TypeError, + debug(nonPropertyKey) + ' is not a Property Key' + ); + }); + + var result = ES.CopyDataProperties({}, { a: 1, b: 2, c: 3 }, ['b']); + st.deepEqual(keys(result), ['a', 'c'], 'excluded string keys are excluded'); + + st.test('excluding symbols', { skip: !v.hasSymbols }, function (s2t) { + var source = {}; + forEach(v.symbols, function (symbol) { + source[symbol] = true; + }); + + var includedSymbols = v.symbols.slice(1); + var excludedSymbols = v.symbols.slice(0, 1); + var target = ES.CopyDataProperties({}, source, excludedSymbols); + + forEach(includedSymbols, function (symbol) { + s2t.equal(has(target, symbol), true, debug(symbol) + ' is included'); + }); + + forEach(excludedSymbols, function (symbol) { + s2t.equal(has(target, symbol), false, debug(symbol) + ' is excluded'); + }); + + s2t.end(); + }); + + st.end(); + }); + + t.end(); + }); + + test('PromiseResolve', function (t) { + t.test('Promises unsupported', { skip: typeof Promise === 'function' }, function (st) { + st['throws']( + function () { ES.PromiseResolve(); }, + SyntaxError, + 'Promises are not supported' + ); + st.end(); + }); + + t.test('Promises supported', { skip: typeof Promise !== 'function' }, function (st) { + st.plan(2); + + var a = {}; + var b = {}; + var fulfilled = Promise.resolve(a); + var rejected = Promise.reject(b); + + ES.PromiseResolve(Promise, fulfilled).then(function (x) { + st.equal(x, a, 'fulfilled promise resolves to fulfilled'); + }); + + ES.PromiseResolve(Promise, rejected)['catch'](function (e) { + st.equal(e, b, 'rejected promise resolves to rejected'); + }); + }); + + t.end(); + }); + + test('EnumerableOwnPropertyNames', { skip: skips && skips.EnumerableOwnPropertyNames }, function (t) { + var obj = testEnumerableOwnNames(t, function (O) { + return ES.EnumerableOwnPropertyNames(O, 'key'); + }); + + t.deepEqual( + ES.EnumerableOwnPropertyNames(obj, 'value'), + [obj.own], + 'returns enumerable own values' + ); + + t.deepEqual( + ES.EnumerableOwnPropertyNames(obj, 'key+value'), + [['own', obj.own]], + 'returns enumerable own entries' + ); + + t.end(); + }); + + test('IsPromise', { skip: typeof Promise !== 'function' }, function (t) { + forEach(v.objects.concat(v.primitives), function (nonPromise) { + t.equal(ES.IsPromise(nonPromise), false, debug(nonPromise) + ' is not a Promise'); + }); + + var thenable = { then: Promise.prototype.then }; + t.equal(ES.IsPromise(thenable), false, 'generic thenable is not a Promise'); + + t.equal(ES.IsPromise(Promise.resolve()), true, 'Promise is a Promise'); + + t.end(); + }); + + test('GetSubstitution (ES2018+)', function (t) { + forEach(v.nonStrings, function (nonString) { + t['throws']( + function () { ES.GetSubstitution(nonString, '', 0, [], undefined, ''); }, + TypeError, + '`matched`: ' + debug(nonString) + ' is not a String' + ); + + t['throws']( + function () { ES.GetSubstitution('', nonString, 0, [], undefined, ''); }, + TypeError, + '`str`: ' + debug(nonString) + ' is not a String' + ); + + t['throws']( + function () { ES.GetSubstitution('', '', 0, [], undefined, nonString); }, + TypeError, + '`replacement`: ' + debug(nonString) + ' is not a String' + ); + + t['throws']( + function () { ES.GetSubstitution('', '', 0, [nonString], undefined, ''); }, + TypeError, + '`captures`: ' + debug([nonString]) + ' is not an Array of strings' + ); + }); + + forEach(v.nonIntegerNumbers.concat([-1, -42, -Infinity]), function (nonNonNegativeInteger) { + t['throws']( + function () { ES.GetSubstitution('', '', nonNonNegativeInteger, [], undefined, ''); }, + TypeError, + '`position`: ' + debug(nonNonNegativeInteger) + ' is not a non-negative integer' + ); + }); + + forEach(v.nonArrays, function (nonArray) { + t['throws']( + function () { ES.GetSubstitution('', '', 0, nonArray, undefined, ''); }, + TypeError, + '`captures`: ' + debug(nonArray) + ' is not an Array' + ); + }); + + t.equal( + ES.GetSubstitution('def', 'abcdefghi', 3, [], undefined, '123'), + '123', + 'returns the substitution' + ); + t.equal( + ES.GetSubstitution('abcdef', 'abcdefghi', 0, [], undefined, '$$2$'), + '$2$', + 'supports $$, and trailing $' + ); + + t.equal( + ES.GetSubstitution('abcdef', 'abcdefghi', 0, [], undefined, '>$&<'), + '>abcdef<', + 'supports $&' + ); + + t.equal( + ES.GetSubstitution('abcdef', 'abcdefghi', 0, [], undefined, '>$`<'), + '><', + 'supports $` at position 0' + ); + t.equal( + ES.GetSubstitution('def', 'abcdefghi', 3, [], undefined, '>$`<'), + '>ab<', + 'supports $` at position > 0' + ); + + t.equal( + ES.GetSubstitution('def', 'abcdefghi', 7, [], undefined, ">$'<"), + '><', + "supports $' at a position where there's less than `matched.length` chars left" + ); + t.equal( + ES.GetSubstitution('def', 'abcdefghi', 3, [], undefined, ">$'<"), + '>ghi<', + "supports $' at a position where there's more than `matched.length` chars left" + ); + + for (var i = 0; i < 100; i += 1) { + var captures = []; + captures[i] = 'test'; + if (i > 0) { + t.equal( + ES.GetSubstitution('abcdef', 'abcdefghi', 0, [], undefined, '>$' + i + '<'), + '>undefined<', + 'supports $' + i + ' with no captures' + ); + t.equal( + ES.GetSubstitution('abcdef', 'abcdefghi', 0, [], undefined, '>$' + i), + '>undefined', + 'supports $' + i + ' at the end of the replacement, with no captures' + ); + t.equal( + ES.GetSubstitution('abcdef', 'abcdefghi', 0, captures, undefined, '>$' + i + '<'), + '><', + 'supports $' + i + ' with a capture at that index' + ); + t.equal( + ES.GetSubstitution('abcdef', 'abcdefghi', 0, captures, undefined, '>$' + i), + '>', + 'supports $' + i + ' at the end of the replacement, with a capture at that index' + ); + } + if (i < 10) { + t.equal( + ES.GetSubstitution('abcdef', 'abcdefghi', 0, [], undefined, '>$0' + i + '<'), + i === 0 ? '><' : '>undefined<', + 'supports $0' + i + ' with no captures' + ); + t.equal( + ES.GetSubstitution('abcdef', 'abcdefghi', 0, [], undefined, '>$0' + i), + i === 0 ? '>' : '>undefined', + 'supports $0' + i + ' at the end of the replacement, with no captures' + ); + t.equal( + ES.GetSubstitution('abcdef', 'abcdefghi', 0, captures, undefined, '>$0' + i + '<'), + '><', + 'supports $0' + i + ' with a capture at that index' + ); + t.equal( + ES.GetSubstitution('abcdef', 'abcdefghi', 0, captures, undefined, '>$0' + i), + '>', + 'supports $0' + i + ' at the end of the replacement, with a capture at that index' + ); + } + } + + t.end(); + }); + + test('DateString', function (t) { + forEach(v.nonNumbers.concat(NaN), function (nonNumberOrNaN) { + t['throws']( + function () { ES.DateString(nonNumberOrNaN); }, + TypeError, + debug(nonNumberOrNaN) + ' is not a non-NaN Number' + ); + }); + + t.equal(ES.DateString(Date.UTC(2019, 8, 10, 7, 8, 9)), 'Tue Sep 10 2019'); + t.equal(ES.DateString(Date.UTC(2016, 1, 29, 7, 8, 9)), 'Mon Feb 29 2016'); // leap day + t.end(); + }); + + test('TimeString', function (t) { + forEach(v.nonNumbers.concat(NaN), function (nonNumberOrNaN) { + t['throws']( + function () { ES.TimeString(nonNumberOrNaN); }, + TypeError, + debug(nonNumberOrNaN) + ' is not a non-NaN Number' + ); + }); + + var tv = Date.UTC(2019, 8, 10, 7, 8, 9); + t.equal(ES.TimeString(tv), '07:08:09 GMT'); + t.end(); + }); +}; + +var es2019 = function ES2018(ES, ops, expectedMissing, skips) { + es2018(ES, ops, expectedMissing, assign({}, skips, { + })); + + test('AddEntriesFromIterable', function (t) { + t['throws']( + function () { ES.AddEntriesFromIterable({}, undefined, function () {}); }, + TypeError, + 'iterable must not be undefined' + ); + t['throws']( + function () { ES.AddEntriesFromIterable({}, null, function () {}); }, + TypeError, + 'iterable must not be null' + ); + forEach(v.nonFunctions, function (nonFunction) { + t['throws']( + function () { ES.AddEntriesFromIterable({}, {}, nonFunction); }, + TypeError, + debug(nonFunction) + ' is not a function' + ); + }); + + t.test('Symbol support', { skip: !v.hasSymbols }, function (st) { + st.plan(4); + + var O = {}; + st.equal(ES.AddEntriesFromIterable(O, [], function () {}), O, 'returns the target'); + + var adder = function (key, value) { + st.equal(this, O, 'adder gets proper receiver'); + st.equal(key, 0, 'k is key'); + st.equal(value, 'a', 'v is value'); + }; + ES.AddEntriesFromIterable(O, ['a'].entries(), adder); + + st.end(); + }); + + t.end(); + }); + + test('FlattenIntoArray', function (t) { + t.test('no mapper function', function (st) { + var testDepth = function testDepth(tt, depth, expected) { + var a = []; + var o = [[1], 2, , [[3]], [], 4, [[[[5]]]]]; // eslint-disable-line no-sparse-arrays + ES.FlattenIntoArray(a, o, o.length, 0, depth); + tt.deepEqual(a, expected, 'depth: ' + depth); + }; + + testDepth(st, 1, [1, 2, [3], 4, [[[5]]]]); + testDepth(st, 2, [1, 2, 3, 4, [[5]]]); + testDepth(st, 3, [1, 2, 3, 4, [5]]); + testDepth(st, 4, [1, 2, 3, 4, 5]); + testDepth(st, Infinity, [1, 2, 3, 4, 5]); + st.end(); + }); + + t.test('mapper function', function (st) { + var testMapper = function testMapper(tt, mapper, expected, thisArg) { + var a = []; + var o = [[1], 2, , [[3]], [], 4, [[[[5]]]]]; // eslint-disable-line no-sparse-arrays + ES.FlattenIntoArray(a, o, o.length, 0, 1, mapper, thisArg); + tt.deepEqual(a, expected); + }; + + var double = function double(x) { + return typeof x === 'number' ? 2 * x : x; + }; + testMapper( + st, + double, + [1, 4, [3], 8, [[[5]]]] + ); + testMapper( + st, + function (x) { return [this, double(x)]; }, + [42, [1], 42, 4, 42, [[3]], 42, [], 42, 8, 42, [[[[5]]]]], + 42 + ); + st.end(); + }); + + t.end(); + }); + + test('TrimString', function (t) { + t.test('non-object string', function (st) { + forEach(v.nullPrimitives, function (nullish) { + st['throws']( + function () { ES.TrimString(nullish); }, + debug(nullish) + ' is not an Object' + ); + }); + st.end(); + }); + + var string = ' \n abc \n '; + t.equal(ES.TrimString(string, 'start'), string.slice(string.indexOf('a'))); + t.equal(ES.TrimString(string, 'end'), string.slice(0, string.lastIndexOf('c') + 1)); + t.equal(ES.TrimString(string, 'start+end'), string.slice(string.indexOf('a'), string.lastIndexOf('c') + 1)); + + t.end(); + }); +}; + +module.exports = { + es2015: es2015, + es2016: es2016, + es2017: es2017, + es2018: es2018, + es2019: es2019 +}; diff --git a/scripts/2.5/node_modules/es-to-primitive/.editorconfig b/scripts/2.5/node_modules/es-to-primitive/.editorconfig new file mode 100644 index 00000000..bc228f82 --- /dev/null +++ b/scripts/2.5/node_modules/es-to-primitive/.editorconfig @@ -0,0 +1,20 @@ +root = true + +[*] +indent_style = tab +indent_size = 4 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true +max_line_length = 150 + +[CHANGELOG.md] +indent_style = space +indent_size = 2 + +[*.json] +max_line_length = off + +[Makefile] +max_line_length = off diff --git a/scripts/2.5/node_modules/es-to-primitive/.eslintrc b/scripts/2.5/node_modules/es-to-primitive/.eslintrc new file mode 100644 index 00000000..09e0c6c2 --- /dev/null +++ b/scripts/2.5/node_modules/es-to-primitive/.eslintrc @@ -0,0 +1,14 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "complexity": [2, 14], + "func-name-matching": 0, + "id-length": [2, { "min": 1, "max": 24, "properties": "never" }], + "max-lines-per-function": [2, { "max": 68 }], + "max-statements": [2, 20], + "new-cap": [2, { "capIsNewExceptions": ["GetMethod"] }] + } +} diff --git a/scripts/2.5/node_modules/es-to-primitive/.jscs.json b/scripts/2.5/node_modules/es-to-primitive/.jscs.json new file mode 100644 index 00000000..8666c750 --- /dev/null +++ b/scripts/2.5/node_modules/es-to-primitive/.jscs.json @@ -0,0 +1,176 @@ +{ + "es3": true, + + "additionalRules": [], + + "requireSemicolons": true, + + "disallowMultipleSpaces": true, + + "disallowIdentifierNames": [], + + "requireCurlyBraces": { + "allExcept": [], + "keywords": ["if", "else", "for", "while", "do", "try", "catch"] + }, + + "requireSpaceAfterKeywords": ["if", "else", "for", "while", "do", "switch", "return", "try", "catch", "function"], + + "disallowSpaceAfterKeywords": [], + + "disallowSpaceBeforeComma": true, + "disallowSpaceAfterComma": false, + "disallowSpaceBeforeSemicolon": true, + + "disallowNodeTypes": [ + "DebuggerStatement", + "ForInStatement", + "LabeledStatement", + "SwitchCase", + "SwitchStatement", + "WithStatement" + ], + + "requireObjectKeysOnNewLine": { "allExcept": ["sameLine"] }, + + "requireSpacesInAnonymousFunctionExpression": { "beforeOpeningRoundBrace": true, "beforeOpeningCurlyBrace": true }, + "requireSpacesInNamedFunctionExpression": { "beforeOpeningCurlyBrace": true }, + "disallowSpacesInNamedFunctionExpression": { "beforeOpeningRoundBrace": true }, + "requireSpacesInFunctionDeclaration": { "beforeOpeningCurlyBrace": true }, + "disallowSpacesInFunctionDeclaration": { "beforeOpeningRoundBrace": true }, + + "requireSpaceBetweenArguments": true, + + "disallowSpacesInsideParentheses": true, + + "disallowSpacesInsideArrayBrackets": true, + + "disallowQuotedKeysInObjects": { "allExcept": ["reserved"] }, + + "disallowSpaceAfterObjectKeys": true, + + "requireCommaBeforeLineBreak": true, + + "disallowSpaceAfterPrefixUnaryOperators": ["++", "--", "+", "-", "~", "!"], + "requireSpaceAfterPrefixUnaryOperators": [], + + "disallowSpaceBeforePostfixUnaryOperators": ["++", "--"], + "requireSpaceBeforePostfixUnaryOperators": [], + + "disallowSpaceBeforeBinaryOperators": [], + "requireSpaceBeforeBinaryOperators": ["+", "-", "/", "*", "=", "==", "===", "!=", "!=="], + + "requireSpaceAfterBinaryOperators": ["+", "-", "/", "*", "=", "==", "===", "!=", "!=="], + "disallowSpaceAfterBinaryOperators": [], + + "disallowImplicitTypeConversion": ["binary", "string"], + + "disallowKeywords": ["with", "eval"], + + "requireKeywordsOnNewLine": [], + "disallowKeywordsOnNewLine": ["else"], + + "requireLineFeedAtFileEnd": true, + + "disallowTrailingWhitespace": true, + + "disallowTrailingComma": true, + + "excludeFiles": ["node_modules/**", "vendor/**"], + + "disallowMultipleLineStrings": true, + + "requireDotNotation": { "allExcept": ["keywords"] }, + + "requireParenthesesAroundIIFE": true, + + "validateLineBreaks": "LF", + + "validateQuoteMarks": { + "escape": true, + "mark": "'" + }, + + "disallowOperatorBeforeLineBreak": [], + + "requireSpaceBeforeKeywords": [ + "do", + "for", + "if", + "else", + "switch", + "case", + "try", + "catch", + "finally", + "while", + "with", + "return" + ], + + "validateAlignedFunctionParameters": { + "lineBreakAfterOpeningBraces": true, + "lineBreakBeforeClosingBraces": true + }, + + "requirePaddingNewLinesBeforeExport": true, + + "validateNewlineAfterArrayElements": { + "maximum": 12 + }, + + "requirePaddingNewLinesAfterUseStrict": true, + + "disallowArrowFunctions": true, + + "disallowMultiLineTernary": true, + + "validateOrderInObjectKeys": false, + + "disallowIdenticalDestructuringNames": true, + + "disallowNestedTernaries": { "maxLevel": 1 }, + + "requireSpaceAfterComma": { "allExcept": ["trailing"] }, + "requireAlignedMultilineParams": false, + + "requireSpacesInGenerator": { + "afterStar": true + }, + + "disallowSpacesInGenerator": { + "beforeStar": true + }, + + "disallowVar": false, + + "requireArrayDestructuring": false, + + "requireEnhancedObjectLiterals": false, + + "requireObjectDestructuring": false, + + "requireEarlyReturn": false, + + "requireCapitalizedConstructorsNew": { + "allExcept": ["Function", "String", "Object", "Symbol", "Number", "Date", "RegExp", "Error", "Boolean", "Array", "GetMethod"] + }, + + "requireImportAlphabetized": false, + + "requireSpaceBeforeObjectValues": true, + "requireSpaceBeforeDestructuredValues": true, + + "disallowSpacesInsideTemplateStringPlaceholders": true, + + "disallowArrayDestructuringReturn": false, + + "requireNewlineBeforeSingleStatementsInIf": false, + + "disallowUnusedVariables": true, + + "requireSpacesInsideImportedObjectBraces": true, + + "requireUseStrict": true +} + diff --git a/scripts/2.5/node_modules/es-to-primitive/.travis.yml b/scripts/2.5/node_modules/es-to-primitive/.travis.yml new file mode 100644 index 00000000..c9ee1ece --- /dev/null +++ b/scripts/2.5/node_modules/es-to-primitive/.travis.yml @@ -0,0 +1,243 @@ +language: node_js +cache: + directories: + - "$(nvm cache dir)" +os: + - linux +node_js: + - "10.11" + - "9.11" + - "8.12" + - "7.10" + - "6.14" + - "5.12" + - "4.9" + - "iojs-v3.3" + - "iojs-v2.5" + - "iojs-v1.8" + - "0.12" + - "0.11" + - "0.10" + - "0.8" + - "0.6" +before_install: + - 'case "${TRAVIS_NODE_VERSION}" in 0.*) export NPM_CONFIG_STRICT_SSL=false ;; esac' + - 'nvm install-latest-npm' +install: + - 'if [ "${TRAVIS_NODE_VERSION}" = "0.6" ] || [ "${TRAVIS_NODE_VERSION}" = "0.9" ]; then nvm install --latest-npm 0.8 && npm install && nvm use "${TRAVIS_NODE_VERSION}"; else npm install; fi;' +script: + - 'if [ -n "${PRETEST-}" ]; then npm run pretest ; fi' + - 'if [ -n "${POSTTEST-}" ]; then npm run posttest ; fi' + - 'if [ -n "${COVERAGE-}" ]; then npm run coverage ; fi' + - 'if [ -n "${TEST-}" ]; then npm run tests-only ; fi' +sudo: false +env: + - TEST=true +matrix: + fast_finish: true + include: + - node_js: "lts/*" + env: PRETEST=true + - node_js: "lts/*" + env: POSTTEST=true + - node_js: "4" + env: COVERAGE=true + - node_js: "10.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.13" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.12" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v3.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v3.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v3.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.4" + env: TEST=true ALLOW_FAILURE=true + allow_failures: + - os: osx + - env: TEST=true ALLOW_FAILURE=true + - env: COVERAGE=true + - node_js: "0.6" diff --git a/scripts/2.5/node_modules/es-to-primitive/CHANGELOG.md b/scripts/2.5/node_modules/es-to-primitive/CHANGELOG.md new file mode 100644 index 00000000..96298696 --- /dev/null +++ b/scripts/2.5/node_modules/es-to-primitive/CHANGELOG.md @@ -0,0 +1,38 @@ +1.2.0 / 2018-09-27 +================= + * [New] create ES2015 entry point/property, to replace ES6 + * [Fix] Ensure optional arguments are not part of the length (#29) + * [Deps] update `is-callable` + * [Dev Deps] update `tape`, `jscs`, `nsp`, `eslint`, `@ljharb/eslint-config`, `semver`, `object-inspect`, `replace` + * [Tests] avoid util.inspect bug with `new Date(NaN)` on node v6.0 and v6.1. + * [Tests] up to `node` `v10.11`, `v9.11`, `v8.12`, `v6.14`, `v4.9` + +1.1.1 / 2016-01-03 +================= + * [Fix: ES5] fix coercion logic: ES5’s ToPrimitive does not coerce any primitive value, regardless of hint (#2) + +1.1.0 / 2015-12-27 +================= + * [New] add `Symbol.toPrimitive` support + * [Deps] update `is-callable`, `is-date-object` + * [Dev Deps] update `eslint`, `tape`, `semver`, `jscs`, `covert`, `nsp`, `@ljharb/eslint-config` + * [Dev Deps] remove unused deps + * [Tests] up to `node` `v5.3` + * [Tests] fix npm upgrades on older node versions + * [Tests] fix testling + * [Docs] Switch from vb.teelaun.ch to versionbadg.es for the npm version badge SVG + +1.0.1 / 2016-01-03 +================= + * [Fix: ES5] fix coercion logic: ES5’s ToPrimitive does not coerce any primitive value, regardless of hint (#2) + * [Deps] update `is-callable`, `is-date-object` + * [Dev Deps] update `eslint`, `tape`, `semver`, `jscs`, `covert`, `nsp`, `@ljharb/eslint-config` + * [Dev Deps] remove unused deps + * [Tests] up to `node` `v5.3` + * [Tests] fix npm upgrades on older node versions + * [Tests] fix testling + * [Docs] Switch from vb.teelaun.ch to versionbadg.es for the npm version badge SVG + +1.0.0 / 2015-03-19 +================= + * Initial release. diff --git a/scripts/2.5/node_modules/es-to-primitive/LICENSE b/scripts/2.5/node_modules/es-to-primitive/LICENSE new file mode 100644 index 00000000..b43df444 --- /dev/null +++ b/scripts/2.5/node_modules/es-to-primitive/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/scripts/2.5/node_modules/es-to-primitive/Makefile b/scripts/2.5/node_modules/es-to-primitive/Makefile new file mode 100644 index 00000000..b9e4fe1a --- /dev/null +++ b/scripts/2.5/node_modules/es-to-primitive/Makefile @@ -0,0 +1,61 @@ +# Since we rely on paths relative to the makefile location, abort if make isn't being run from there. +$(if $(findstring /,$(MAKEFILE_LIST)),$(error Please only invoke this makefile from the directory it resides in)) + + # The files that need updating when incrementing the version number. +VERSIONED_FILES := *.js *.json README* + + +# Add the local npm packages' bin folder to the PATH, so that `make` can find them, when invoked directly. +# Note that rather than using `$(npm bin)` the 'node_modules/.bin' path component is hard-coded, so that invocation works even from an environment +# where npm is (temporarily) unavailable due to having deactivated an nvm instance loaded into the calling shell in order to avoid interference with tests. +export PATH := $(shell printf '%s' "$$PWD/node_modules/.bin:$$PATH") +UTILS := semver +# Make sure that all required utilities can be located. +UTIL_CHECK := $(or $(shell PATH="$(PATH)" which $(UTILS) >/dev/null && echo 'ok'),$(error Did you forget to run `npm install` after cloning the repo? At least one of the required supporting utilities not found: $(UTILS))) + +# Default target (by virtue of being the first non '.'-prefixed in the file). +.PHONY: _no-target-specified +_no-target-specified: + $(error Please specify the target to make - `make list` shows targets. Alternatively, use `npm test` to run the default tests; `npm run` shows all tests) + +# Lists all targets defined in this makefile. +.PHONY: list +list: + @$(MAKE) -pRrn : -f $(MAKEFILE_LIST) 2>/dev/null | awk -v RS= -F: '/^# File/,/^# Finished Make data base/ {if ($$1 !~ "^[#.]") {print $$1}}' | command grep -v -e '^[^[:alnum:]]' -e '^$@$$command ' | sort + +# All-tests target: invokes the specified test suites for ALL shells defined in $(SHELLS). +.PHONY: test +test: + @npm test + +.PHONY: _ensure-tag +_ensure-tag: +ifndef TAG + $(error Please invoke with `make TAG= release`, where is either an increment specifier (patch, minor, major, prepatch, preminor, premajor, prerelease), or an explicit major.minor.patch version number) +endif + +CHANGELOG_ERROR = $(error No CHANGELOG specified) +.PHONY: _ensure-changelog +_ensure-changelog: + @ (git status -sb --porcelain | command grep -E '^( M|[MA] ) CHANGELOG.md' > /dev/null) || (echo no CHANGELOG.md specified && exit 2) + +# Ensures that the git workspace is clean. +.PHONY: _ensure-clean +_ensure-clean: + @[ -z "$$((git status --porcelain --untracked-files=no || echo err) | command grep -v 'CHANGELOG.md')" ] || { echo "Workspace is not clean; please commit changes first." >&2; exit 2; } + +# Makes a release; invoke with `make TAG= release`. +.PHONY: release +release: _ensure-tag _ensure-changelog _ensure-clean + @old_ver=`git describe --abbrev=0 --tags --match 'v[0-9]*.[0-9]*.[0-9]*'` || { echo "Failed to determine current version." >&2; exit 1; }; old_ver=$${old_ver#v}; \ + new_ver=`echo "$(TAG)" | sed 's/^v//'`; new_ver=$${new_ver:-patch}; \ + if printf "$$new_ver" | command grep -q '^[0-9]'; then \ + semver "$$new_ver" >/dev/null || { echo 'Invalid version number specified: $(TAG) - must be major.minor.patch' >&2; exit 2; }; \ + semver -r "> $$old_ver" "$$new_ver" >/dev/null || { echo 'Invalid version number specified: $(TAG) - must be HIGHER than current one.' >&2; exit 2; } \ + else \ + new_ver=`semver -i "$$new_ver" "$$old_ver"` || { echo 'Invalid version-increment specifier: $(TAG)' >&2; exit 2; } \ + fi; \ + printf "=== Bumping version **$$old_ver** to **$$new_ver** before committing and tagging:\n=== TYPE 'proceed' TO PROCEED, anything else to abort: " && read response && [ "$$response" = 'proceed' ] || { echo 'Aborted.' >&2; exit 2; }; \ + replace "$$old_ver" "$$new_ver" -- $(VERSIONED_FILES) && \ + git commit -m "v$$new_ver" $(VERSIONED_FILES) CHANGELOG.md && \ + git tag -a -m "v$$new_ver" "v$$new_ver" diff --git a/scripts/2.5/node_modules/es-to-primitive/README.md b/scripts/2.5/node_modules/es-to-primitive/README.md new file mode 100644 index 00000000..1831ecf3 --- /dev/null +++ b/scripts/2.5/node_modules/es-to-primitive/README.md @@ -0,0 +1,51 @@ +# es-to-primitive [![Version Badge][npm-version-svg]][package-url] + +[![Build Status][travis-svg]][travis-url] +[![dependency status][deps-svg]][deps-url] +[![dev dependency status][dev-deps-svg]][dev-deps-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +ECMAScript “ToPrimitive” algorithm. Provides ES5 and ES2015 versions. +When different versions of the spec conflict, the default export will be the latest version of the abstract operation. +Alternative versions will also be available under an `es5`/`es2015` exported property if you require a specific version. + +## Example + +```js +var toPrimitive = require('es-to-primitive'); +var assert = require('assert'); + +assert(toPrimitive(function () {}) === String(function () {})); + +var date = new Date(); +assert(toPrimitive(date) === String(date)); + +assert(toPrimitive({ valueOf: function () { return 3; } }) === 3); + +assert(toPrimitive(['a', 'b', 3]) === String(['a', 'b', 3])); + +var sym = Symbol(); +assert(toPrimitive(Object(sym)) === sym); +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.org/package/es-to-primitive +[npm-version-svg]: http://versionbadg.es/ljharb/es-to-primitive.svg +[travis-svg]: https://travis-ci.org/ljharb/es-to-primitive.svg +[travis-url]: https://travis-ci.org/ljharb/es-to-primitive +[deps-svg]: https://david-dm.org/ljharb/es-to-primitive.svg +[deps-url]: https://david-dm.org/ljharb/es-to-primitive +[dev-deps-svg]: https://david-dm.org/ljharb/es-to-primitive/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/es-to-primitive#info=devDependencies +[testling-svg]: https://ci.testling.com/ljharb/es-to-primitive.png +[testling-url]: https://ci.testling.com/ljharb/es-to-primitive +[npm-badge-png]: https://nodei.co/npm/es-to-primitive.png?downloads=true&stars=true +[license-image]: http://img.shields.io/npm/l/es-to-primitive.svg +[license-url]: LICENSE +[downloads-image]: http://img.shields.io/npm/dm/es-to-primitive.svg +[downloads-url]: http://npm-stat.com/charts.html?package=es-to-primitive diff --git a/scripts/2.5/node_modules/es-to-primitive/es2015.js b/scripts/2.5/node_modules/es-to-primitive/es2015.js new file mode 100644 index 00000000..4a11a346 --- /dev/null +++ b/scripts/2.5/node_modules/es-to-primitive/es2015.js @@ -0,0 +1,75 @@ +'use strict'; + +var hasSymbols = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol'; + +var isPrimitive = require('./helpers/isPrimitive'); +var isCallable = require('is-callable'); +var isDate = require('is-date-object'); +var isSymbol = require('is-symbol'); + +var ordinaryToPrimitive = function OrdinaryToPrimitive(O, hint) { + if (typeof O === 'undefined' || O === null) { + throw new TypeError('Cannot call method on ' + O); + } + if (typeof hint !== 'string' || (hint !== 'number' && hint !== 'string')) { + throw new TypeError('hint must be "string" or "number"'); + } + var methodNames = hint === 'string' ? ['toString', 'valueOf'] : ['valueOf', 'toString']; + var method, result, i; + for (i = 0; i < methodNames.length; ++i) { + method = O[methodNames[i]]; + if (isCallable(method)) { + result = method.call(O); + if (isPrimitive(result)) { + return result; + } + } + } + throw new TypeError('No default value'); +}; + +var GetMethod = function GetMethod(O, P) { + var func = O[P]; + if (func !== null && typeof func !== 'undefined') { + if (!isCallable(func)) { + throw new TypeError(func + ' returned for property ' + P + ' of object ' + O + ' is not a function'); + } + return func; + } + return void 0; +}; + +// http://www.ecma-international.org/ecma-262/6.0/#sec-toprimitive +module.exports = function ToPrimitive(input) { + if (isPrimitive(input)) { + return input; + } + var hint = 'default'; + if (arguments.length > 1) { + if (arguments[1] === String) { + hint = 'string'; + } else if (arguments[1] === Number) { + hint = 'number'; + } + } + + var exoticToPrim; + if (hasSymbols) { + if (Symbol.toPrimitive) { + exoticToPrim = GetMethod(input, Symbol.toPrimitive); + } else if (isSymbol(input)) { + exoticToPrim = Symbol.prototype.valueOf; + } + } + if (typeof exoticToPrim !== 'undefined') { + var result = exoticToPrim.call(input, hint); + if (isPrimitive(result)) { + return result; + } + throw new TypeError('unable to convert exotic object to primitive'); + } + if (hint === 'default' && (isDate(input) || isSymbol(input))) { + hint = 'string'; + } + return ordinaryToPrimitive(input, hint === 'default' ? 'number' : hint); +}; diff --git a/scripts/2.5/node_modules/es-to-primitive/es5.js b/scripts/2.5/node_modules/es-to-primitive/es5.js new file mode 100644 index 00000000..602aa362 --- /dev/null +++ b/scripts/2.5/node_modules/es-to-primitive/es5.js @@ -0,0 +1,45 @@ +'use strict'; + +var toStr = Object.prototype.toString; + +var isPrimitive = require('./helpers/isPrimitive'); + +var isCallable = require('is-callable'); + +// http://ecma-international.org/ecma-262/5.1/#sec-8.12.8 +var ES5internalSlots = { + '[[DefaultValue]]': function (O) { + var actualHint; + if (arguments.length > 1) { + actualHint = arguments[1]; + } else { + actualHint = toStr.call(O) === '[object Date]' ? String : Number; + } + + if (actualHint === String || actualHint === Number) { + var methods = actualHint === String ? ['toString', 'valueOf'] : ['valueOf', 'toString']; + var value, i; + for (i = 0; i < methods.length; ++i) { + if (isCallable(O[methods[i]])) { + value = O[methods[i]](); + if (isPrimitive(value)) { + return value; + } + } + } + throw new TypeError('No default value'); + } + throw new TypeError('invalid [[DefaultValue]] hint supplied'); + } +}; + +// http://ecma-international.org/ecma-262/5.1/#sec-9.1 +module.exports = function ToPrimitive(input) { + if (isPrimitive(input)) { + return input; + } + if (arguments.length > 1) { + return ES5internalSlots['[[DefaultValue]]'](input, arguments[1]); + } + return ES5internalSlots['[[DefaultValue]]'](input); +}; diff --git a/scripts/2.5/node_modules/es-to-primitive/es6.js b/scripts/2.5/node_modules/es-to-primitive/es6.js new file mode 100644 index 00000000..2d1f4dc9 --- /dev/null +++ b/scripts/2.5/node_modules/es-to-primitive/es6.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('./es2015'); diff --git a/scripts/2.5/node_modules/es-to-primitive/helpers/isPrimitive.js b/scripts/2.5/node_modules/es-to-primitive/helpers/isPrimitive.js new file mode 100644 index 00000000..36691564 --- /dev/null +++ b/scripts/2.5/node_modules/es-to-primitive/helpers/isPrimitive.js @@ -0,0 +1,3 @@ +module.exports = function isPrimitive(value) { + return value === null || (typeof value !== 'function' && typeof value !== 'object'); +}; diff --git a/scripts/2.5/node_modules/es-to-primitive/index.js b/scripts/2.5/node_modules/es-to-primitive/index.js new file mode 100644 index 00000000..e60d912e --- /dev/null +++ b/scripts/2.5/node_modules/es-to-primitive/index.js @@ -0,0 +1,17 @@ +'use strict'; + +var ES5 = require('./es5'); +var ES6 = require('./es6'); +var ES2015 = require('./es2015'); + +if (Object.defineProperty) { + Object.defineProperty(ES2015, 'ES5', { enumerable: false, value: ES5 }); + Object.defineProperty(ES2015, 'ES6', { enumerable: false, value: ES6 }); + Object.defineProperty(ES2015, 'ES2015', { enumerable: false, value: ES2015 }); +} else { + ES6.ES5 = ES5; + ES6.ES6 = ES6; + ES6.ES2015 = ES2015; +} + +module.exports = ES2015; diff --git a/scripts/2.5/node_modules/es-to-primitive/package.json b/scripts/2.5/node_modules/es-to-primitive/package.json new file mode 100644 index 00000000..73ded945 --- /dev/null +++ b/scripts/2.5/node_modules/es-to-primitive/package.json @@ -0,0 +1,113 @@ +{ + "_from": "es-to-primitive@^1.2.0", + "_id": "es-to-primitive@1.2.0", + "_inBundle": false, + "_integrity": "sha512-qZryBOJjV//LaxLTV6UC//WewneB3LcXOL9NP++ozKVXsIIIpm/2c13UDiD9Jp2eThsecw9m3jPqDwTyobcdbg==", + "_location": "/es-to-primitive", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "es-to-primitive@^1.2.0", + "name": "es-to-primitive", + "escapedName": "es-to-primitive", + "rawSpec": "^1.2.0", + "saveSpec": null, + "fetchSpec": "^1.2.0" + }, + "_requiredBy": [ + "/es-abstract" + ], + "_resolved": "https://registry.npmjs.org/es-to-primitive/-/es-to-primitive-1.2.0.tgz", + "_shasum": "edf72478033456e8dda8ef09e00ad9650707f377", + "_spec": "es-to-primitive@^1.2.0", + "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/2.5/node_modules/es-abstract", + "author": { + "name": "Jordan Harband" + }, + "bugs": { + "url": "https://github.com/ljharb/es-to-primitive/issues" + }, + "bundleDependencies": false, + "dependencies": { + "is-callable": "^1.1.4", + "is-date-object": "^1.0.1", + "is-symbol": "^1.0.2" + }, + "deprecated": false, + "description": "ECMAScript “ToPrimitive” algorithm. Provides ES5 and ES2015 versions.", + "devDependencies": { + "@ljharb/eslint-config": "^13.0.0", + "covert": "^1.1.0", + "eslint": "^5.6.0", + "foreach": "^2.0.5", + "function.prototype.name": "^1.1.0", + "jscs": "^3.0.7", + "nsp": "^3.2.1", + "object-inspect": "^1.6.0", + "object-is": "^1.0.1", + "replace": "^1.0.0", + "semver": "^5.5.1", + "tape": "^4.9.1" + }, + "engines": { + "node": ">= 0.4" + }, + "homepage": "https://github.com/ljharb/es-to-primitive#readme", + "keywords": [ + "primitive", + "abstract", + "ecmascript", + "es5", + "es6", + "es2015", + "toPrimitive", + "coerce", + "type", + "object", + "string", + "number", + "boolean", + "symbol", + "null", + "undefined" + ], + "license": "MIT", + "main": "index.js", + "name": "es-to-primitive", + "repository": { + "type": "git", + "url": "git://github.com/ljharb/es-to-primitive.git" + }, + "scripts": { + "coverage": "covert test/*.js", + "coverage-quiet": "covert test/*.js --quiet", + "eslint": "eslint test/*.js *.js", + "jscs": "jscs test/*.js *.js", + "lint": "npm run --silent jscs && npm run --silent eslint", + "posttest": "npm run --silent security", + "pretest": "npm run --silent lint", + "security": "nsp check", + "test": "npm run --silent tests-only", + "tests-only": "node --es-staging test" + }, + "testling": { + "files": "test", + "browsers": [ + "iexplore/6.0..latest", + "firefox/3.0..6.0", + "firefox/15.0..latest", + "firefox/nightly", + "chrome/4.0..10.0", + "chrome/20.0..latest", + "chrome/canary", + "opera/10.0..latest", + "opera/next", + "safari/4.0..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2" + ] + }, + "version": "1.2.0" +} diff --git a/scripts/2.5/node_modules/es-to-primitive/test/.eslintrc b/scripts/2.5/node_modules/es-to-primitive/test/.eslintrc new file mode 100644 index 00000000..9beb88c7 --- /dev/null +++ b/scripts/2.5/node_modules/es-to-primitive/test/.eslintrc @@ -0,0 +1,9 @@ +{ + "rules": { + "array-bracket-newline": 0, + "array-element-newline": 0, + "max-statements-per-line": [2, { "max": 3 }], + "no-magic-numbers": [0], + "sort-keys": [0] + } +} diff --git a/scripts/2.5/node_modules/es-to-primitive/test/es2015.js b/scripts/2.5/node_modules/es-to-primitive/test/es2015.js new file mode 100644 index 00000000..80f4083d --- /dev/null +++ b/scripts/2.5/node_modules/es-to-primitive/test/es2015.js @@ -0,0 +1,151 @@ +'use strict'; + +var test = require('tape'); +var toPrimitive = require('../es2015'); +var is = require('object-is'); +var forEach = require('foreach'); +var functionName = require('function.prototype.name'); +var debug = require('object-inspect'); + +var hasSymbols = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol'; +var hasSymbolToPrimitive = hasSymbols && typeof Symbol.toPrimitive === 'symbol'; + +test('function properties', function (t) { + t.equal(toPrimitive.length, 1, 'length is 1'); + t.equal(functionName(toPrimitive), 'ToPrimitive', 'name is ToPrimitive'); + + t.end(); +}); + +var primitives = [null, undefined, true, false, 0, -0, 42, NaN, Infinity, -Infinity, '', 'abc']; + +test('primitives', function (t) { + forEach(primitives, function (i) { + t.ok(is(toPrimitive(i), i), 'toPrimitive(' + debug(i) + ') returns the same value'); + t.ok(is(toPrimitive(i, String), i), 'toPrimitive(' + debug(i) + ', String) returns the same value'); + t.ok(is(toPrimitive(i, Number), i), 'toPrimitive(' + debug(i) + ', Number) returns the same value'); + }); + t.end(); +}); + +test('Symbols', { skip: !hasSymbols }, function (t) { + var symbols = [ + Symbol('foo'), + Symbol.iterator, + Symbol['for']('foo') // eslint-disable-line no-restricted-properties + ]; + forEach(symbols, function (sym) { + t.equal(toPrimitive(sym), sym, 'toPrimitive(' + debug(sym) + ') returns the same value'); + t.equal(toPrimitive(sym, String), sym, 'toPrimitive(' + debug(sym) + ', String) returns the same value'); + t.equal(toPrimitive(sym, Number), sym, 'toPrimitive(' + debug(sym) + ', Number) returns the same value'); + }); + + var primitiveSym = Symbol('primitiveSym'); + var objectSym = Object(primitiveSym); + t.equal(toPrimitive(objectSym), primitiveSym, 'toPrimitive(' + debug(objectSym) + ') returns ' + debug(primitiveSym)); + t.equal(toPrimitive(objectSym, String), primitiveSym, 'toPrimitive(' + debug(objectSym) + ', String) returns ' + debug(primitiveSym)); + t.equal(toPrimitive(objectSym, Number), primitiveSym, 'toPrimitive(' + debug(objectSym) + ', Number) returns ' + debug(primitiveSym)); + t.end(); +}); + +test('Arrays', function (t) { + var arrays = [[], ['a', 'b'], [1, 2]]; + forEach(arrays, function (arr) { + t.equal(toPrimitive(arr), String(arr), 'toPrimitive(' + debug(arr) + ') returns the string version of the array'); + t.equal(toPrimitive(arr, String), String(arr), 'toPrimitive(' + debug(arr) + ') returns the string version of the array'); + t.equal(toPrimitive(arr, Number), String(arr), 'toPrimitive(' + debug(arr) + ') returns the string version of the array'); + }); + t.end(); +}); + +test('Dates', function (t) { + var dates = [new Date(), new Date(0), new Date(NaN)]; + forEach(dates, function (date) { + t.equal(toPrimitive(date), String(date), 'toPrimitive(' + debug(date) + ') returns the string version of the date'); + t.equal(toPrimitive(date, String), String(date), 'toPrimitive(' + debug(date) + ') returns the string version of the date'); + t.ok(is(toPrimitive(date, Number), Number(date)), 'toPrimitive(' + debug(date) + ') returns the number version of the date'); + }); + t.end(); +}); + +var coercibleObject = { valueOf: function () { return 3; }, toString: function () { return 42; } }; +var valueOfOnlyObject = { valueOf: function () { return 4; }, toString: function () { return {}; } }; +var toStringOnlyObject = { valueOf: function () { return {}; }, toString: function () { return 7; } }; +var coercibleFnObject = { + valueOf: function () { return function valueOfFn() {}; }, + toString: function () { return 42; } +}; +var uncoercibleObject = { valueOf: function () { return {}; }, toString: function () { return {}; } }; +var uncoercibleFnObject = { + valueOf: function () { return function valueOfFn() {}; }, + toString: function () { return function toStrFn() {}; } +}; + +test('Objects', function (t) { + t.equal(toPrimitive(coercibleObject), coercibleObject.valueOf(), 'coercibleObject with no hint coerces to valueOf'); + t.equal(toPrimitive(coercibleObject, Number), coercibleObject.valueOf(), 'coercibleObject with hint Number coerces to valueOf'); + t.equal(toPrimitive(coercibleObject, String), coercibleObject.toString(), 'coercibleObject with hint String coerces to non-stringified toString'); + + t.equal(toPrimitive(coercibleFnObject), coercibleFnObject.toString(), 'coercibleFnObject coerces to non-stringified toString'); + t.equal(toPrimitive(coercibleFnObject, Number), coercibleFnObject.toString(), 'coercibleFnObject with hint Number coerces to non-stringified toString'); + t.equal(toPrimitive(coercibleFnObject, String), coercibleFnObject.toString(), 'coercibleFnObject with hint String coerces to non-stringified toString'); + + t.equal(toPrimitive({}), '[object Object]', '{} with no hint coerces to Object#toString'); + t.equal(toPrimitive({}, Number), '[object Object]', '{} with hint Number coerces to Object#toString'); + t.equal(toPrimitive({}, String), '[object Object]', '{} with hint String coerces to Object#toString'); + + t.equal(toPrimitive(toStringOnlyObject), toStringOnlyObject.toString(), 'toStringOnlyObject returns non-stringified toString'); + t.equal(toPrimitive(toStringOnlyObject, Number), toStringOnlyObject.toString(), 'toStringOnlyObject with hint Number returns non-stringified toString'); + t.equal(toPrimitive(toStringOnlyObject, String), toStringOnlyObject.toString(), 'toStringOnlyObject with hint String returns non-stringified toString'); + + t.equal(toPrimitive(valueOfOnlyObject), valueOfOnlyObject.valueOf(), 'valueOfOnlyObject returns valueOf'); + t.equal(toPrimitive(valueOfOnlyObject, Number), valueOfOnlyObject.valueOf(), 'valueOfOnlyObject with hint Number returns valueOf'); + t.equal(toPrimitive(valueOfOnlyObject, String), valueOfOnlyObject.valueOf(), 'valueOfOnlyObject with hint String returns non-stringified valueOf'); + + t.test('Symbol.toPrimitive', { skip: !hasSymbolToPrimitive }, function (st) { + var overriddenObject = { toString: st.fail, valueOf: st.fail }; + overriddenObject[Symbol.toPrimitive] = function (hint) { return String(hint); }; + + st.equal(toPrimitive(overriddenObject), 'default', 'object with Symbol.toPrimitive + no hint invokes that'); + st.equal(toPrimitive(overriddenObject, Number), 'number', 'object with Symbol.toPrimitive + hint Number invokes that'); + st.equal(toPrimitive(overriddenObject, String), 'string', 'object with Symbol.toPrimitive + hint String invokes that'); + + var nullToPrimitive = { toString: coercibleObject.toString, valueOf: coercibleObject.valueOf }; + nullToPrimitive[Symbol.toPrimitive] = null; + st.equal(toPrimitive(nullToPrimitive), toPrimitive(coercibleObject), 'object with no hint + null Symbol.toPrimitive ignores it'); + st.equal(toPrimitive(nullToPrimitive, Number), toPrimitive(coercibleObject, Number), 'object with hint Number + null Symbol.toPrimitive ignores it'); + st.equal(toPrimitive(nullToPrimitive, String), toPrimitive(coercibleObject, String), 'object with hint String + null Symbol.toPrimitive ignores it'); + + st.test('exceptions', function (sst) { + var nonFunctionToPrimitive = { toString: sst.fail, valueOf: sst.fail }; + nonFunctionToPrimitive[Symbol.toPrimitive] = {}; + sst['throws'](toPrimitive.bind(null, nonFunctionToPrimitive), TypeError, 'Symbol.toPrimitive returning a non-function throws'); + + var uncoercibleToPrimitive = { toString: sst.fail, valueOf: sst.fail }; + uncoercibleToPrimitive[Symbol.toPrimitive] = function (hint) { + return { toString: function () { return hint; } }; + }; + sst['throws'](toPrimitive.bind(null, uncoercibleToPrimitive), TypeError, 'Symbol.toPrimitive returning an object throws'); + + var throwingToPrimitive = { toString: sst.fail, valueOf: sst.fail }; + throwingToPrimitive[Symbol.toPrimitive] = function (hint) { throw new RangeError(hint); }; + sst['throws'](toPrimitive.bind(null, throwingToPrimitive), RangeError, 'Symbol.toPrimitive throwing throws'); + + sst.end(); + }); + + st.end(); + }); + + t.test('exceptions', function (st) { + st['throws'](toPrimitive.bind(null, uncoercibleObject), TypeError, 'uncoercibleObject throws a TypeError'); + st['throws'](toPrimitive.bind(null, uncoercibleObject, Number), TypeError, 'uncoercibleObject with hint Number throws a TypeError'); + st['throws'](toPrimitive.bind(null, uncoercibleObject, String), TypeError, 'uncoercibleObject with hint String throws a TypeError'); + + st['throws'](toPrimitive.bind(null, uncoercibleFnObject), TypeError, 'uncoercibleFnObject throws a TypeError'); + st['throws'](toPrimitive.bind(null, uncoercibleFnObject, Number), TypeError, 'uncoercibleFnObject with hint Number throws a TypeError'); + st['throws'](toPrimitive.bind(null, uncoercibleFnObject, String), TypeError, 'uncoercibleFnObject with hint String throws a TypeError'); + st.end(); + }); + t.end(); +}); diff --git a/scripts/2.5/node_modules/es-to-primitive/test/es5.js b/scripts/2.5/node_modules/es-to-primitive/test/es5.js new file mode 100644 index 00000000..8b80ff5b --- /dev/null +++ b/scripts/2.5/node_modules/es-to-primitive/test/es5.js @@ -0,0 +1,94 @@ +'use strict'; + +var test = require('tape'); +var toPrimitive = require('../es5'); +var is = require('object-is'); +var forEach = require('foreach'); +var functionName = require('function.prototype.name'); +var debug = require('object-inspect'); + +test('function properties', function (t) { + t.equal(toPrimitive.length, 1, 'length is 1'); + t.equal(functionName(toPrimitive), 'ToPrimitive', 'name is ToPrimitive'); + + t.end(); +}); + +var primitives = [null, undefined, true, false, 0, -0, 42, NaN, Infinity, -Infinity, '', 'abc']; + +test('primitives', function (t) { + forEach(primitives, function (i) { + t.ok(is(toPrimitive(i), i), 'toPrimitive(' + debug(i) + ') returns the same value'); + t.ok(is(toPrimitive(i, String), i), 'toPrimitive(' + debug(i) + ', String) returns the same value'); + t.ok(is(toPrimitive(i, Number), i), 'toPrimitive(' + debug(i) + ', Number) returns the same value'); + }); + t.end(); +}); + +test('Arrays', function (t) { + var arrays = [[], ['a', 'b'], [1, 2]]; + forEach(arrays, function (arr) { + t.ok(is(toPrimitive(arr), arr.toString()), 'toPrimitive(' + debug(arr) + ') returns toString of the array'); + t.equal(toPrimitive(arr, String), arr.toString(), 'toPrimitive(' + debug(arr) + ') returns toString of the array'); + t.ok(is(toPrimitive(arr, Number), arr.toString()), 'toPrimitive(' + debug(arr) + ') returns toString of the array'); + }); + t.end(); +}); + +test('Dates', function (t) { + var dates = [new Date(), new Date(0), new Date(NaN)]; + forEach(dates, function (date) { + t.equal(toPrimitive(date), date.toString(), 'toPrimitive(' + debug(date) + ') returns toString of the date'); + t.equal(toPrimitive(date, String), date.toString(), 'toPrimitive(' + debug(date) + ') returns toString of the date'); + t.ok(is(toPrimitive(date, Number), date.valueOf()), 'toPrimitive(' + debug(date) + ') returns valueOf of the date'); + }); + t.end(); +}); + +var coercibleObject = { valueOf: function () { return 3; }, toString: function () { return 42; } }; +var valueOfOnlyObject = { valueOf: function () { return 4; }, toString: function () { return {}; } }; +var toStringOnlyObject = { valueOf: function () { return {}; }, toString: function () { return 7; } }; +var coercibleFnObject = { + valueOf: function () { return function valueOfFn() {}; }, + toString: function () { return 42; } +}; +var uncoercibleObject = { valueOf: function () { return {}; }, toString: function () { return {}; } }; +var uncoercibleFnObject = { + valueOf: function () { return function valueOfFn() {}; }, + toString: function () { return function toStrFn() {}; } +}; + +test('Objects', function (t) { + t.equal(toPrimitive(coercibleObject), coercibleObject.valueOf(), 'coercibleObject with no hint coerces to valueOf'); + t.equal(toPrimitive(coercibleObject, String), coercibleObject.toString(), 'coercibleObject with hint String coerces to toString'); + t.equal(toPrimitive(coercibleObject, Number), coercibleObject.valueOf(), 'coercibleObject with hint Number coerces to valueOf'); + + t.equal(toPrimitive(coercibleFnObject), coercibleFnObject.toString(), 'coercibleFnObject coerces to toString'); + t.equal(toPrimitive(coercibleFnObject, String), coercibleFnObject.toString(), 'coercibleFnObject with hint String coerces to toString'); + t.equal(toPrimitive(coercibleFnObject, Number), coercibleFnObject.toString(), 'coercibleFnObject with hint Number coerces to toString'); + + t.ok(is(toPrimitive({}), '[object Object]'), '{} with no hint coerces to Object#toString'); + t.equal(toPrimitive({}, String), '[object Object]', '{} with hint String coerces to Object#toString'); + t.ok(is(toPrimitive({}, Number), '[object Object]'), '{} with hint Number coerces to Object#toString'); + + t.equal(toPrimitive(toStringOnlyObject), toStringOnlyObject.toString(), 'toStringOnlyObject returns toString'); + t.equal(toPrimitive(toStringOnlyObject, String), toStringOnlyObject.toString(), 'toStringOnlyObject with hint String returns toString'); + t.equal(toPrimitive(toStringOnlyObject, Number), toStringOnlyObject.toString(), 'toStringOnlyObject with hint Number returns toString'); + + t.equal(toPrimitive(valueOfOnlyObject), valueOfOnlyObject.valueOf(), 'valueOfOnlyObject returns valueOf'); + t.equal(toPrimitive(valueOfOnlyObject, String), valueOfOnlyObject.valueOf(), 'valueOfOnlyObject with hint String returns valueOf'); + t.equal(toPrimitive(valueOfOnlyObject, Number), valueOfOnlyObject.valueOf(), 'valueOfOnlyObject with hint Number returns valueOf'); + + t.test('exceptions', function (st) { + st['throws'](toPrimitive.bind(null, uncoercibleObject), TypeError, 'uncoercibleObject throws a TypeError'); + st['throws'](toPrimitive.bind(null, uncoercibleObject, String), TypeError, 'uncoercibleObject with hint String throws a TypeError'); + st['throws'](toPrimitive.bind(null, uncoercibleObject, Number), TypeError, 'uncoercibleObject with hint Number throws a TypeError'); + + st['throws'](toPrimitive.bind(null, uncoercibleFnObject), TypeError, 'uncoercibleFnObject throws a TypeError'); + st['throws'](toPrimitive.bind(null, uncoercibleFnObject, String), TypeError, 'uncoercibleFnObject with hint String throws a TypeError'); + st['throws'](toPrimitive.bind(null, uncoercibleFnObject, Number), TypeError, 'uncoercibleFnObject with hint Number throws a TypeError'); + st.end(); + }); + + t.end(); +}); diff --git a/scripts/2.5/node_modules/es-to-primitive/test/es6.js b/scripts/2.5/node_modules/es-to-primitive/test/es6.js new file mode 100644 index 00000000..c6df63fb --- /dev/null +++ b/scripts/2.5/node_modules/es-to-primitive/test/es6.js @@ -0,0 +1,151 @@ +'use strict'; + +var test = require('tape'); +var toPrimitive = require('../es6'); +var is = require('object-is'); +var forEach = require('foreach'); +var functionName = require('function.prototype.name'); +var debug = require('object-inspect'); + +var hasSymbols = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol'; +var hasSymbolToPrimitive = hasSymbols && typeof Symbol.toPrimitive === 'symbol'; + +test('function properties', function (t) { + t.equal(toPrimitive.length, 1, 'length is 1'); + t.equal(functionName(toPrimitive), 'ToPrimitive', 'name is ToPrimitive'); + + t.end(); +}); + +var primitives = [null, undefined, true, false, 0, -0, 42, NaN, Infinity, -Infinity, '', 'abc']; + +test('primitives', function (t) { + forEach(primitives, function (i) { + t.ok(is(toPrimitive(i), i), 'toPrimitive(' + debug(i) + ') returns the same value'); + t.ok(is(toPrimitive(i, String), i), 'toPrimitive(' + debug(i) + ', String) returns the same value'); + t.ok(is(toPrimitive(i, Number), i), 'toPrimitive(' + debug(i) + ', Number) returns the same value'); + }); + t.end(); +}); + +test('Symbols', { skip: !hasSymbols }, function (t) { + var symbols = [ + Symbol('foo'), + Symbol.iterator, + Symbol['for']('foo') // eslint-disable-line no-restricted-properties + ]; + forEach(symbols, function (sym) { + t.equal(toPrimitive(sym), sym, 'toPrimitive(' + debug(sym) + ') returns the same value'); + t.equal(toPrimitive(sym, String), sym, 'toPrimitive(' + debug(sym) + ', String) returns the same value'); + t.equal(toPrimitive(sym, Number), sym, 'toPrimitive(' + debug(sym) + ', Number) returns the same value'); + }); + + var primitiveSym = Symbol('primitiveSym'); + var objectSym = Object(primitiveSym); + t.equal(toPrimitive(objectSym), primitiveSym, 'toPrimitive(' + debug(objectSym) + ') returns ' + debug(primitiveSym)); + t.equal(toPrimitive(objectSym, String), primitiveSym, 'toPrimitive(' + debug(objectSym) + ', String) returns ' + debug(primitiveSym)); + t.equal(toPrimitive(objectSym, Number), primitiveSym, 'toPrimitive(' + debug(objectSym) + ', Number) returns ' + debug(primitiveSym)); + t.end(); +}); + +test('Arrays', function (t) { + var arrays = [[], ['a', 'b'], [1, 2]]; + forEach(arrays, function (arr) { + t.equal(toPrimitive(arr), String(arr), 'toPrimitive(' + debug(arr) + ') returns the string version of the array'); + t.equal(toPrimitive(arr, String), String(arr), 'toPrimitive(' + debug(arr) + ') returns the string version of the array'); + t.equal(toPrimitive(arr, Number), String(arr), 'toPrimitive(' + debug(arr) + ') returns the string version of the array'); + }); + t.end(); +}); + +test('Dates', function (t) { + var dates = [new Date(), new Date(0), new Date(NaN)]; + forEach(dates, function (date) { + t.equal(toPrimitive(date), String(date), 'toPrimitive(' + debug(date) + ') returns the string version of the date'); + t.equal(toPrimitive(date, String), String(date), 'toPrimitive(' + debug(date) + ') returns the string version of the date'); + t.ok(is(toPrimitive(date, Number), Number(date)), 'toPrimitive(' + debug(date) + ') returns the number version of the date'); + }); + t.end(); +}); + +var coercibleObject = { valueOf: function () { return 3; }, toString: function () { return 42; } }; +var valueOfOnlyObject = { valueOf: function () { return 4; }, toString: function () { return {}; } }; +var toStringOnlyObject = { valueOf: function () { return {}; }, toString: function () { return 7; } }; +var coercibleFnObject = { + valueOf: function () { return function valueOfFn() {}; }, + toString: function () { return 42; } +}; +var uncoercibleObject = { valueOf: function () { return {}; }, toString: function () { return {}; } }; +var uncoercibleFnObject = { + valueOf: function () { return function valueOfFn() {}; }, + toString: function () { return function toStrFn() {}; } +}; + +test('Objects', function (t) { + t.equal(toPrimitive(coercibleObject), coercibleObject.valueOf(), 'coercibleObject with no hint coerces to valueOf'); + t.equal(toPrimitive(coercibleObject, Number), coercibleObject.valueOf(), 'coercibleObject with hint Number coerces to valueOf'); + t.equal(toPrimitive(coercibleObject, String), coercibleObject.toString(), 'coercibleObject with hint String coerces to non-stringified toString'); + + t.equal(toPrimitive(coercibleFnObject), coercibleFnObject.toString(), 'coercibleFnObject coerces to non-stringified toString'); + t.equal(toPrimitive(coercibleFnObject, Number), coercibleFnObject.toString(), 'coercibleFnObject with hint Number coerces to non-stringified toString'); + t.equal(toPrimitive(coercibleFnObject, String), coercibleFnObject.toString(), 'coercibleFnObject with hint String coerces to non-stringified toString'); + + t.equal(toPrimitive({}), '[object Object]', '{} with no hint coerces to Object#toString'); + t.equal(toPrimitive({}, Number), '[object Object]', '{} with hint Number coerces to Object#toString'); + t.equal(toPrimitive({}, String), '[object Object]', '{} with hint String coerces to Object#toString'); + + t.equal(toPrimitive(toStringOnlyObject), toStringOnlyObject.toString(), 'toStringOnlyObject returns non-stringified toString'); + t.equal(toPrimitive(toStringOnlyObject, Number), toStringOnlyObject.toString(), 'toStringOnlyObject with hint Number returns non-stringified toString'); + t.equal(toPrimitive(toStringOnlyObject, String), toStringOnlyObject.toString(), 'toStringOnlyObject with hint String returns non-stringified toString'); + + t.equal(toPrimitive(valueOfOnlyObject), valueOfOnlyObject.valueOf(), 'valueOfOnlyObject returns valueOf'); + t.equal(toPrimitive(valueOfOnlyObject, Number), valueOfOnlyObject.valueOf(), 'valueOfOnlyObject with hint Number returns valueOf'); + t.equal(toPrimitive(valueOfOnlyObject, String), valueOfOnlyObject.valueOf(), 'valueOfOnlyObject with hint String returns non-stringified valueOf'); + + t.test('Symbol.toPrimitive', { skip: !hasSymbolToPrimitive }, function (st) { + var overriddenObject = { toString: st.fail, valueOf: st.fail }; + overriddenObject[Symbol.toPrimitive] = function (hint) { return String(hint); }; + + st.equal(toPrimitive(overriddenObject), 'default', 'object with Symbol.toPrimitive + no hint invokes that'); + st.equal(toPrimitive(overriddenObject, Number), 'number', 'object with Symbol.toPrimitive + hint Number invokes that'); + st.equal(toPrimitive(overriddenObject, String), 'string', 'object with Symbol.toPrimitive + hint String invokes that'); + + var nullToPrimitive = { toString: coercibleObject.toString, valueOf: coercibleObject.valueOf }; + nullToPrimitive[Symbol.toPrimitive] = null; + st.equal(toPrimitive(nullToPrimitive), toPrimitive(coercibleObject), 'object with no hint + null Symbol.toPrimitive ignores it'); + st.equal(toPrimitive(nullToPrimitive, Number), toPrimitive(coercibleObject, Number), 'object with hint Number + null Symbol.toPrimitive ignores it'); + st.equal(toPrimitive(nullToPrimitive, String), toPrimitive(coercibleObject, String), 'object with hint String + null Symbol.toPrimitive ignores it'); + + st.test('exceptions', function (sst) { + var nonFunctionToPrimitive = { toString: sst.fail, valueOf: sst.fail }; + nonFunctionToPrimitive[Symbol.toPrimitive] = {}; + sst['throws'](toPrimitive.bind(null, nonFunctionToPrimitive), TypeError, 'Symbol.toPrimitive returning a non-function throws'); + + var uncoercibleToPrimitive = { toString: sst.fail, valueOf: sst.fail }; + uncoercibleToPrimitive[Symbol.toPrimitive] = function (hint) { + return { toString: function () { return hint; } }; + }; + sst['throws'](toPrimitive.bind(null, uncoercibleToPrimitive), TypeError, 'Symbol.toPrimitive returning an object throws'); + + var throwingToPrimitive = { toString: sst.fail, valueOf: sst.fail }; + throwingToPrimitive[Symbol.toPrimitive] = function (hint) { throw new RangeError(hint); }; + sst['throws'](toPrimitive.bind(null, throwingToPrimitive), RangeError, 'Symbol.toPrimitive throwing throws'); + + sst.end(); + }); + + st.end(); + }); + + t.test('exceptions', function (st) { + st['throws'](toPrimitive.bind(null, uncoercibleObject), TypeError, 'uncoercibleObject throws a TypeError'); + st['throws'](toPrimitive.bind(null, uncoercibleObject, Number), TypeError, 'uncoercibleObject with hint Number throws a TypeError'); + st['throws'](toPrimitive.bind(null, uncoercibleObject, String), TypeError, 'uncoercibleObject with hint String throws a TypeError'); + + st['throws'](toPrimitive.bind(null, uncoercibleFnObject), TypeError, 'uncoercibleFnObject throws a TypeError'); + st['throws'](toPrimitive.bind(null, uncoercibleFnObject, Number), TypeError, 'uncoercibleFnObject with hint Number throws a TypeError'); + st['throws'](toPrimitive.bind(null, uncoercibleFnObject, String), TypeError, 'uncoercibleFnObject with hint String throws a TypeError'); + st.end(); + }); + t.end(); +}); diff --git a/scripts/2.5/node_modules/es-to-primitive/test/index.js b/scripts/2.5/node_modules/es-to-primitive/test/index.js new file mode 100644 index 00000000..ad71f39e --- /dev/null +++ b/scripts/2.5/node_modules/es-to-primitive/test/index.js @@ -0,0 +1,20 @@ +'use strict'; + +var toPrimitive = require('../'); +var ES5 = require('../es5'); +var ES6 = require('../es6'); +var ES2015 = require('../es2015'); + +var test = require('tape'); + +test('default export', function (t) { + t.equal(toPrimitive, ES2015, 'default export is ES2015'); + t.equal(toPrimitive.ES5, ES5, 'ES5 property has ES5 method'); + t.equal(toPrimitive.ES6, ES6, 'ES6 property has ES6 method'); + t.equal(toPrimitive.ES2015, ES2015, 'ES2015 property has ES2015 method'); + t.end(); +}); + +require('./es5'); +require('./es6'); +require('./es2015'); diff --git a/scripts/2.5/node_modules/es6-object-assign/LICENSE b/scripts/2.5/node_modules/es6-object-assign/LICENSE new file mode 100644 index 00000000..3fef2a24 --- /dev/null +++ b/scripts/2.5/node_modules/es6-object-assign/LICENSE @@ -0,0 +1,22 @@ +Copyright (c) 2015-2017 Rubén Norte + +MIT License + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/scripts/2.5/node_modules/es6-object-assign/README.md b/scripts/2.5/node_modules/es6-object-assign/README.md new file mode 100644 index 00000000..39172998 --- /dev/null +++ b/scripts/2.5/node_modules/es6-object-assign/README.md @@ -0,0 +1,96 @@ +[![npm](https://img.shields.io/npm/l/es6-object-assign.svg)](https://www.npmjs.org/package/es6-object-assign) +[![npm](https://img.shields.io/npm/v/es6-object-assign.svg)](https://www.npmjs.org/package/es6-object-assign) + +# ES6 Object.assign() + +ECMAScript 2015 (ES2015/ES6) [Object.assign()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) polyfill and [ponyfill](https://ponyfill.com) for ECMAScript 5 environments. + +The main definition of this package has been copied from the polyfill defined in the [Mozilla Developer Network](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign). + +## Installation + +### NPM + +```bash +npm install es6-object-assign +``` + +### Manual download and import + +The package is also available as a UMD module (compatible with AMD, CommonJS and exposing a global variable `ObjectAssign`) in `dist/object-assign.js` and `dist/object-assign.min.js` (833 bytes minified and gzipped). + +The versions with automatic polyfilling are `dist/object-assign-auto.js` and `dist/object-assign-auto.min.js`. + +## Usage + +**CommonJS**: + +```javascript +// Polyfill, modifying the global Object +require('es6-object-assign').polyfill(); +var obj = Object.assign({}, { foo: 'bar' }); + +// Same version with automatic polyfilling +require('es6-object-assign/auto'); +var obj = Object.assign({}, { foo: 'bar' }); + +// Or ponyfill, using a reference to the function without modifying globals +var assign = require('es6-object-assign').assign; +var obj = assign({}, { foo: 'bar' }); +``` + +**Globals**: + +Manual polyfill: + +```html + + +``` + +Automatic polyfill: + +```html + + +``` + +Ponyfill, without modifying globals: + +```html + + +``` + +## License + +The MIT License (MIT) + +Copyright (c) 2017 Rubén Norte + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/scripts/2.5/node_modules/es6-object-assign/auto.js b/scripts/2.5/node_modules/es6-object-assign/auto.js new file mode 100644 index 00000000..43b68da0 --- /dev/null +++ b/scripts/2.5/node_modules/es6-object-assign/auto.js @@ -0,0 +1,3 @@ +'use strict'; + +require('./index').polyfill(); diff --git a/scripts/2.5/node_modules/es6-object-assign/dist/object-assign-auto.js b/scripts/2.5/node_modules/es6-object-assign/dist/object-assign-auto.js new file mode 100644 index 00000000..12d22b6d --- /dev/null +++ b/scripts/2.5/node_modules/es6-object-assign/dist/object-assign-auto.js @@ -0,0 +1,54 @@ +(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o dist/object-assign-auto.min.js", + "compress:manual": "uglifyjs dist/object-assign.js --compress --mangle > dist/object-assign.min.js" + }, + "version": "1.1.0" +} diff --git a/scripts/2.5/node_modules/function-bind/.editorconfig b/scripts/2.5/node_modules/function-bind/.editorconfig new file mode 100644 index 00000000..ac29adef --- /dev/null +++ b/scripts/2.5/node_modules/function-bind/.editorconfig @@ -0,0 +1,20 @@ +root = true + +[*] +indent_style = tab +indent_size = 4 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true +max_line_length = 120 + +[CHANGELOG.md] +indent_style = space +indent_size = 2 + +[*.json] +max_line_length = off + +[Makefile] +max_line_length = off diff --git a/scripts/2.5/node_modules/function-bind/.eslintrc b/scripts/2.5/node_modules/function-bind/.eslintrc new file mode 100644 index 00000000..9b33d8ed --- /dev/null +++ b/scripts/2.5/node_modules/function-bind/.eslintrc @@ -0,0 +1,15 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "func-name-matching": 0, + "indent": [2, 4], + "max-nested-callbacks": [2, 3], + "max-params": [2, 3], + "max-statements": [2, 20], + "no-new-func": [1], + "strict": [0] + } +} diff --git a/scripts/2.5/node_modules/function-bind/.jscs.json b/scripts/2.5/node_modules/function-bind/.jscs.json new file mode 100644 index 00000000..8c447948 --- /dev/null +++ b/scripts/2.5/node_modules/function-bind/.jscs.json @@ -0,0 +1,176 @@ +{ + "es3": true, + + "additionalRules": [], + + "requireSemicolons": true, + + "disallowMultipleSpaces": true, + + "disallowIdentifierNames": [], + + "requireCurlyBraces": { + "allExcept": [], + "keywords": ["if", "else", "for", "while", "do", "try", "catch"] + }, + + "requireSpaceAfterKeywords": ["if", "else", "for", "while", "do", "switch", "return", "try", "catch", "function"], + + "disallowSpaceAfterKeywords": [], + + "disallowSpaceBeforeComma": true, + "disallowSpaceAfterComma": false, + "disallowSpaceBeforeSemicolon": true, + + "disallowNodeTypes": [ + "DebuggerStatement", + "ForInStatement", + "LabeledStatement", + "SwitchCase", + "SwitchStatement", + "WithStatement" + ], + + "requireObjectKeysOnNewLine": { "allExcept": ["sameLine"] }, + + "requireSpacesInAnonymousFunctionExpression": { "beforeOpeningRoundBrace": true, "beforeOpeningCurlyBrace": true }, + "requireSpacesInNamedFunctionExpression": { "beforeOpeningCurlyBrace": true }, + "disallowSpacesInNamedFunctionExpression": { "beforeOpeningRoundBrace": true }, + "requireSpacesInFunctionDeclaration": { "beforeOpeningCurlyBrace": true }, + "disallowSpacesInFunctionDeclaration": { "beforeOpeningRoundBrace": true }, + + "requireSpaceBetweenArguments": true, + + "disallowSpacesInsideParentheses": true, + + "disallowSpacesInsideArrayBrackets": true, + + "disallowQuotedKeysInObjects": { "allExcept": ["reserved"] }, + + "disallowSpaceAfterObjectKeys": true, + + "requireCommaBeforeLineBreak": true, + + "disallowSpaceAfterPrefixUnaryOperators": ["++", "--", "+", "-", "~", "!"], + "requireSpaceAfterPrefixUnaryOperators": [], + + "disallowSpaceBeforePostfixUnaryOperators": ["++", "--"], + "requireSpaceBeforePostfixUnaryOperators": [], + + "disallowSpaceBeforeBinaryOperators": [], + "requireSpaceBeforeBinaryOperators": ["+", "-", "/", "*", "=", "==", "===", "!=", "!=="], + + "requireSpaceAfterBinaryOperators": ["+", "-", "/", "*", "=", "==", "===", "!=", "!=="], + "disallowSpaceAfterBinaryOperators": [], + + "disallowImplicitTypeConversion": ["binary", "string"], + + "disallowKeywords": ["with", "eval"], + + "requireKeywordsOnNewLine": [], + "disallowKeywordsOnNewLine": ["else"], + + "requireLineFeedAtFileEnd": true, + + "disallowTrailingWhitespace": true, + + "disallowTrailingComma": true, + + "excludeFiles": ["node_modules/**", "vendor/**"], + + "disallowMultipleLineStrings": true, + + "requireDotNotation": { "allExcept": ["keywords"] }, + + "requireParenthesesAroundIIFE": true, + + "validateLineBreaks": "LF", + + "validateQuoteMarks": { + "escape": true, + "mark": "'" + }, + + "disallowOperatorBeforeLineBreak": [], + + "requireSpaceBeforeKeywords": [ + "do", + "for", + "if", + "else", + "switch", + "case", + "try", + "catch", + "finally", + "while", + "with", + "return" + ], + + "validateAlignedFunctionParameters": { + "lineBreakAfterOpeningBraces": true, + "lineBreakBeforeClosingBraces": true + }, + + "requirePaddingNewLinesBeforeExport": true, + + "validateNewlineAfterArrayElements": { + "maximum": 8 + }, + + "requirePaddingNewLinesAfterUseStrict": true, + + "disallowArrowFunctions": true, + + "disallowMultiLineTernary": true, + + "validateOrderInObjectKeys": "asc-insensitive", + + "disallowIdenticalDestructuringNames": true, + + "disallowNestedTernaries": { "maxLevel": 1 }, + + "requireSpaceAfterComma": { "allExcept": ["trailing"] }, + "requireAlignedMultilineParams": false, + + "requireSpacesInGenerator": { + "afterStar": true + }, + + "disallowSpacesInGenerator": { + "beforeStar": true + }, + + "disallowVar": false, + + "requireArrayDestructuring": false, + + "requireEnhancedObjectLiterals": false, + + "requireObjectDestructuring": false, + + "requireEarlyReturn": false, + + "requireCapitalizedConstructorsNew": { + "allExcept": ["Function", "String", "Object", "Symbol", "Number", "Date", "RegExp", "Error", "Boolean", "Array"] + }, + + "requireImportAlphabetized": false, + + "requireSpaceBeforeObjectValues": true, + "requireSpaceBeforeDestructuredValues": true, + + "disallowSpacesInsideTemplateStringPlaceholders": true, + + "disallowArrayDestructuringReturn": false, + + "requireNewlineBeforeSingleStatementsInIf": false, + + "disallowUnusedVariables": true, + + "requireSpacesInsideImportedObjectBraces": true, + + "requireUseStrict": true +} + diff --git a/scripts/2.5/node_modules/function-bind/.npmignore b/scripts/2.5/node_modules/function-bind/.npmignore new file mode 100644 index 00000000..dbb555fd --- /dev/null +++ b/scripts/2.5/node_modules/function-bind/.npmignore @@ -0,0 +1,22 @@ +# gitignore +.DS_Store +.monitor +.*.swp +.nodemonignore +releases +*.log +*.err +fleet.json +public/browserify +bin/*.json +.bin +build +compile +.lock-wscript +coverage +node_modules + +# Only apps should have lockfiles +npm-shrinkwrap.json +package-lock.json +yarn.lock diff --git a/scripts/2.5/node_modules/function-bind/.travis.yml b/scripts/2.5/node_modules/function-bind/.travis.yml new file mode 100644 index 00000000..85f70d24 --- /dev/null +++ b/scripts/2.5/node_modules/function-bind/.travis.yml @@ -0,0 +1,168 @@ +language: node_js +os: + - linux +node_js: + - "8.4" + - "7.10" + - "6.11" + - "5.12" + - "4.8" + - "iojs-v3.3" + - "iojs-v2.5" + - "iojs-v1.8" + - "0.12" + - "0.10" + - "0.8" +before_install: + - 'if [ "${TRAVIS_NODE_VERSION}" = "0.6" ]; then npm install -g npm@1.3 ; elif [ "${TRAVIS_NODE_VERSION}" != "0.9" ]; then case "$(npm --version)" in 1.*) npm install -g npm@1.4.28 ;; 2.*) npm install -g npm@2 ;; esac ; fi' + - 'if [ "${TRAVIS_NODE_VERSION}" != "0.6" ] && [ "${TRAVIS_NODE_VERSION}" != "0.9" ]; then if [ "${TRAVIS_NODE_VERSION%${TRAVIS_NODE_VERSION#[0-9]}}" = "0" ] || [ "${TRAVIS_NODE_VERSION:0:4}" = "iojs" ]; then npm install -g npm@4.5 ; else npm install -g npm; fi; fi' +install: + - 'if [ "${TRAVIS_NODE_VERSION}" = "0.6" ]; then nvm install 0.8 && npm install -g npm@1.3 && npm install -g npm@1.4.28 && npm install -g npm@2 && npm install && nvm use "${TRAVIS_NODE_VERSION}"; else npm install; fi;' +script: + - 'if [ -n "${PRETEST-}" ]; then npm run pretest ; fi' + - 'if [ -n "${POSTTEST-}" ]; then npm run posttest ; fi' + - 'if [ -n "${COVERAGE-}" ]; then npm run coverage ; fi' + - 'if [ -n "${TEST-}" ]; then npm run tests-only ; fi' +sudo: false +env: + - TEST=true +matrix: + fast_finish: true + include: + - node_js: "node" + env: PRETEST=true + - node_js: "4" + env: COVERAGE=true + - node_js: "8.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v3.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v3.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v3.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.4" + env: TEST=true ALLOW_FAILURE=true + allow_failures: + - os: osx + - env: TEST=true ALLOW_FAILURE=true diff --git a/scripts/2.5/node_modules/function-bind/LICENSE b/scripts/2.5/node_modules/function-bind/LICENSE new file mode 100644 index 00000000..62d6d237 --- /dev/null +++ b/scripts/2.5/node_modules/function-bind/LICENSE @@ -0,0 +1,20 @@ +Copyright (c) 2013 Raynos. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + diff --git a/scripts/2.5/node_modules/function-bind/README.md b/scripts/2.5/node_modules/function-bind/README.md new file mode 100644 index 00000000..81862a02 --- /dev/null +++ b/scripts/2.5/node_modules/function-bind/README.md @@ -0,0 +1,48 @@ +# function-bind + + + + + +Implementation of function.prototype.bind + +## Example + +I mainly do this for unit tests I run on phantomjs. +PhantomJS does not have Function.prototype.bind :( + +```js +Function.prototype.bind = require("function-bind") +``` + +## Installation + +`npm install function-bind` + +## Contributors + + - Raynos + +## MIT Licenced + + [travis-svg]: https://travis-ci.org/Raynos/function-bind.svg + [travis-url]: https://travis-ci.org/Raynos/function-bind + [npm-badge-svg]: https://badge.fury.io/js/function-bind.svg + [npm-url]: https://npmjs.org/package/function-bind + [5]: https://coveralls.io/repos/Raynos/function-bind/badge.png + [6]: https://coveralls.io/r/Raynos/function-bind + [7]: https://gemnasium.com/Raynos/function-bind.png + [8]: https://gemnasium.com/Raynos/function-bind + [deps-svg]: https://david-dm.org/Raynos/function-bind.svg + [deps-url]: https://david-dm.org/Raynos/function-bind + [dev-deps-svg]: https://david-dm.org/Raynos/function-bind/dev-status.svg + [dev-deps-url]: https://david-dm.org/Raynos/function-bind#info=devDependencies + [11]: https://ci.testling.com/Raynos/function-bind.png + [12]: https://ci.testling.com/Raynos/function-bind diff --git a/scripts/2.5/node_modules/function-bind/implementation.js b/scripts/2.5/node_modules/function-bind/implementation.js new file mode 100644 index 00000000..cc4daec1 --- /dev/null +++ b/scripts/2.5/node_modules/function-bind/implementation.js @@ -0,0 +1,52 @@ +'use strict'; + +/* eslint no-invalid-this: 1 */ + +var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; +var slice = Array.prototype.slice; +var toStr = Object.prototype.toString; +var funcType = '[object Function]'; + +module.exports = function bind(that) { + var target = this; + if (typeof target !== 'function' || toStr.call(target) !== funcType) { + throw new TypeError(ERROR_MESSAGE + target); + } + var args = slice.call(arguments, 1); + + var bound; + var binder = function () { + if (this instanceof bound) { + var result = target.apply( + this, + args.concat(slice.call(arguments)) + ); + if (Object(result) === result) { + return result; + } + return this; + } else { + return target.apply( + that, + args.concat(slice.call(arguments)) + ); + } + }; + + var boundLength = Math.max(0, target.length - args.length); + var boundArgs = []; + for (var i = 0; i < boundLength; i++) { + boundArgs.push('$' + i); + } + + bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder); + + if (target.prototype) { + var Empty = function Empty() {}; + Empty.prototype = target.prototype; + bound.prototype = new Empty(); + Empty.prototype = null; + } + + return bound; +}; diff --git a/scripts/2.5/node_modules/function-bind/index.js b/scripts/2.5/node_modules/function-bind/index.js new file mode 100644 index 00000000..3bb6b960 --- /dev/null +++ b/scripts/2.5/node_modules/function-bind/index.js @@ -0,0 +1,5 @@ +'use strict'; + +var implementation = require('./implementation'); + +module.exports = Function.prototype.bind || implementation; diff --git a/scripts/2.5/node_modules/function-bind/package.json b/scripts/2.5/node_modules/function-bind/package.json new file mode 100644 index 00000000..ea8e7b63 --- /dev/null +++ b/scripts/2.5/node_modules/function-bind/package.json @@ -0,0 +1,98 @@ +{ + "_from": "function-bind@^1.1.1", + "_id": "function-bind@1.1.1", + "_inBundle": false, + "_integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==", + "_location": "/function-bind", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "function-bind@^1.1.1", + "name": "function-bind", + "escapedName": "function-bind", + "rawSpec": "^1.1.1", + "saveSpec": null, + "fetchSpec": "^1.1.1" + }, + "_requiredBy": [ + "/es-abstract", + "/has", + "/object.entries", + "/string.prototype.trimleft", + "/string.prototype.trimright" + ], + "_resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz", + "_shasum": "a56899d3ea3c9bab874bb9773b7c5ede92f4895d", + "_spec": "function-bind@^1.1.1", + "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/2.5/node_modules/object.entries", + "author": { + "name": "Raynos", + "email": "raynos2@gmail.com" + }, + "bugs": { + "url": "https://github.com/Raynos/function-bind/issues", + "email": "raynos2@gmail.com" + }, + "bundleDependencies": false, + "contributors": [ + { + "name": "Raynos" + }, + { + "name": "Jordan Harband", + "url": "https://github.com/ljharb" + } + ], + "dependencies": {}, + "deprecated": false, + "description": "Implementation of Function.prototype.bind", + "devDependencies": { + "@ljharb/eslint-config": "^12.2.1", + "covert": "^1.1.0", + "eslint": "^4.5.0", + "jscs": "^3.0.7", + "tape": "^4.8.0" + }, + "homepage": "https://github.com/Raynos/function-bind", + "keywords": [ + "function", + "bind", + "shim", + "es5" + ], + "license": "MIT", + "main": "index", + "name": "function-bind", + "repository": { + "type": "git", + "url": "git://github.com/Raynos/function-bind.git" + }, + "scripts": { + "coverage": "covert test/*.js", + "eslint": "eslint *.js */*.js", + "jscs": "jscs *.js */*.js", + "lint": "npm run jscs && npm run eslint", + "posttest": "npm run coverage -- --quiet", + "pretest": "npm run lint", + "test": "npm run tests-only", + "tests-only": "node test" + }, + "testling": { + "files": "test/index.js", + "browsers": [ + "ie/8..latest", + "firefox/16..latest", + "firefox/nightly", + "chrome/22..latest", + "chrome/canary", + "opera/12..latest", + "opera/next", + "safari/5.1..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2..latest" + ] + }, + "version": "1.1.1" +} diff --git a/scripts/2.5/node_modules/function-bind/test/.eslintrc b/scripts/2.5/node_modules/function-bind/test/.eslintrc new file mode 100644 index 00000000..8a56d5b7 --- /dev/null +++ b/scripts/2.5/node_modules/function-bind/test/.eslintrc @@ -0,0 +1,9 @@ +{ + "rules": { + "array-bracket-newline": 0, + "array-element-newline": 0, + "max-statements-per-line": [2, { "max": 2 }], + "no-invalid-this": 0, + "no-magic-numbers": 0, + } +} diff --git a/scripts/2.5/node_modules/function-bind/test/index.js b/scripts/2.5/node_modules/function-bind/test/index.js new file mode 100644 index 00000000..2edecce2 --- /dev/null +++ b/scripts/2.5/node_modules/function-bind/test/index.js @@ -0,0 +1,252 @@ +// jscs:disable requireUseStrict + +var test = require('tape'); + +var functionBind = require('../implementation'); +var getCurrentContext = function () { return this; }; + +test('functionBind is a function', function (t) { + t.equal(typeof functionBind, 'function'); + t.end(); +}); + +test('non-functions', function (t) { + var nonFunctions = [true, false, [], {}, 42, 'foo', NaN, /a/g]; + t.plan(nonFunctions.length); + for (var i = 0; i < nonFunctions.length; ++i) { + try { functionBind.call(nonFunctions[i]); } catch (ex) { + t.ok(ex instanceof TypeError, 'throws when given ' + String(nonFunctions[i])); + } + } + t.end(); +}); + +test('without a context', function (t) { + t.test('binds properly', function (st) { + var args, context; + var namespace = { + func: functionBind.call(function () { + args = Array.prototype.slice.call(arguments); + context = this; + }) + }; + namespace.func(1, 2, 3); + st.deepEqual(args, [1, 2, 3]); + st.equal(context, getCurrentContext.call()); + st.end(); + }); + + t.test('binds properly, and still supplies bound arguments', function (st) { + var args, context; + var namespace = { + func: functionBind.call(function () { + args = Array.prototype.slice.call(arguments); + context = this; + }, undefined, 1, 2, 3) + }; + namespace.func(4, 5, 6); + st.deepEqual(args, [1, 2, 3, 4, 5, 6]); + st.equal(context, getCurrentContext.call()); + st.end(); + }); + + t.test('returns properly', function (st) { + var args; + var namespace = { + func: functionBind.call(function () { + args = Array.prototype.slice.call(arguments); + return this; + }, null) + }; + var context = namespace.func(1, 2, 3); + st.equal(context, getCurrentContext.call(), 'returned context is namespaced context'); + st.deepEqual(args, [1, 2, 3], 'passed arguments are correct'); + st.end(); + }); + + t.test('returns properly with bound arguments', function (st) { + var args; + var namespace = { + func: functionBind.call(function () { + args = Array.prototype.slice.call(arguments); + return this; + }, null, 1, 2, 3) + }; + var context = namespace.func(4, 5, 6); + st.equal(context, getCurrentContext.call(), 'returned context is namespaced context'); + st.deepEqual(args, [1, 2, 3, 4, 5, 6], 'passed arguments are correct'); + st.end(); + }); + + t.test('called as a constructor', function (st) { + var thunkify = function (value) { + return function () { return value; }; + }; + st.test('returns object value', function (sst) { + var expectedReturnValue = [1, 2, 3]; + var Constructor = functionBind.call(thunkify(expectedReturnValue), null); + var result = new Constructor(); + sst.equal(result, expectedReturnValue); + sst.end(); + }); + + st.test('does not return primitive value', function (sst) { + var Constructor = functionBind.call(thunkify(42), null); + var result = new Constructor(); + sst.notEqual(result, 42); + sst.end(); + }); + + st.test('object from bound constructor is instance of original and bound constructor', function (sst) { + var A = function (x) { + this.name = x || 'A'; + }; + var B = functionBind.call(A, null, 'B'); + + var result = new B(); + sst.ok(result instanceof B, 'result is instance of bound constructor'); + sst.ok(result instanceof A, 'result is instance of original constructor'); + sst.end(); + }); + + st.end(); + }); + + t.end(); +}); + +test('with a context', function (t) { + t.test('with no bound arguments', function (st) { + var args, context; + var boundContext = {}; + var namespace = { + func: functionBind.call(function () { + args = Array.prototype.slice.call(arguments); + context = this; + }, boundContext) + }; + namespace.func(1, 2, 3); + st.equal(context, boundContext, 'binds a context properly'); + st.deepEqual(args, [1, 2, 3], 'supplies passed arguments'); + st.end(); + }); + + t.test('with bound arguments', function (st) { + var args, context; + var boundContext = {}; + var namespace = { + func: functionBind.call(function () { + args = Array.prototype.slice.call(arguments); + context = this; + }, boundContext, 1, 2, 3) + }; + namespace.func(4, 5, 6); + st.equal(context, boundContext, 'binds a context properly'); + st.deepEqual(args, [1, 2, 3, 4, 5, 6], 'supplies bound and passed arguments'); + st.end(); + }); + + t.test('returns properly', function (st) { + var boundContext = {}; + var args; + var namespace = { + func: functionBind.call(function () { + args = Array.prototype.slice.call(arguments); + return this; + }, boundContext) + }; + var context = namespace.func(1, 2, 3); + st.equal(context, boundContext, 'returned context is bound context'); + st.notEqual(context, getCurrentContext.call(), 'returned context is not lexical context'); + st.deepEqual(args, [1, 2, 3], 'passed arguments are correct'); + st.end(); + }); + + t.test('returns properly with bound arguments', function (st) { + var boundContext = {}; + var args; + var namespace = { + func: functionBind.call(function () { + args = Array.prototype.slice.call(arguments); + return this; + }, boundContext, 1, 2, 3) + }; + var context = namespace.func(4, 5, 6); + st.equal(context, boundContext, 'returned context is bound context'); + st.notEqual(context, getCurrentContext.call(), 'returned context is not lexical context'); + st.deepEqual(args, [1, 2, 3, 4, 5, 6], 'passed arguments are correct'); + st.end(); + }); + + t.test('passes the correct arguments when called as a constructor', function (st) { + var expected = { name: 'Correct' }; + var namespace = { + Func: functionBind.call(function (arg) { + return arg; + }, { name: 'Incorrect' }) + }; + var returned = new namespace.Func(expected); + st.equal(returned, expected, 'returns the right arg when called as a constructor'); + st.end(); + }); + + t.test('has the new instance\'s context when called as a constructor', function (st) { + var actualContext; + var expectedContext = { foo: 'bar' }; + var namespace = { + Func: functionBind.call(function () { + actualContext = this; + }, expectedContext) + }; + var result = new namespace.Func(); + st.equal(result instanceof namespace.Func, true); + st.notEqual(actualContext, expectedContext); + st.end(); + }); + + t.end(); +}); + +test('bound function length', function (t) { + t.test('sets a correct length without thisArg', function (st) { + var subject = functionBind.call(function (a, b, c) { return a + b + c; }); + st.equal(subject.length, 3); + st.equal(subject(1, 2, 3), 6); + st.end(); + }); + + t.test('sets a correct length with thisArg', function (st) { + var subject = functionBind.call(function (a, b, c) { return a + b + c; }, {}); + st.equal(subject.length, 3); + st.equal(subject(1, 2, 3), 6); + st.end(); + }); + + t.test('sets a correct length without thisArg and first argument', function (st) { + var subject = functionBind.call(function (a, b, c) { return a + b + c; }, undefined, 1); + st.equal(subject.length, 2); + st.equal(subject(2, 3), 6); + st.end(); + }); + + t.test('sets a correct length with thisArg and first argument', function (st) { + var subject = functionBind.call(function (a, b, c) { return a + b + c; }, {}, 1); + st.equal(subject.length, 2); + st.equal(subject(2, 3), 6); + st.end(); + }); + + t.test('sets a correct length without thisArg and too many arguments', function (st) { + var subject = functionBind.call(function (a, b, c) { return a + b + c; }, undefined, 1, 2, 3, 4); + st.equal(subject.length, 0); + st.equal(subject(), 6); + st.end(); + }); + + t.test('sets a correct length with thisArg and too many arguments', function (st) { + var subject = functionBind.call(function (a, b, c) { return a + b + c; }, {}, 1, 2, 3, 4); + st.equal(subject.length, 0); + st.equal(subject(), 6); + st.end(); + }); +}); diff --git a/scripts/2.5/node_modules/has-symbols/.eslintrc b/scripts/2.5/node_modules/has-symbols/.eslintrc new file mode 100644 index 00000000..f78f6f18 --- /dev/null +++ b/scripts/2.5/node_modules/has-symbols/.eslintrc @@ -0,0 +1,10 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "max-statements-per-line": [2, { "max": 2 }], + "no-magic-numbers": 0 + } +} diff --git a/scripts/2.5/node_modules/has-symbols/.npmignore b/scripts/2.5/node_modules/has-symbols/.npmignore new file mode 100644 index 00000000..5148e527 --- /dev/null +++ b/scripts/2.5/node_modules/has-symbols/.npmignore @@ -0,0 +1,37 @@ +# Logs +logs +*.log +npm-debug.log* + +# Runtime data +pids +*.pid +*.seed + +# Directory for instrumented libs generated by jscoverage/JSCover +lib-cov + +# Coverage directory used by tools like istanbul +coverage + +# nyc test coverage +.nyc_output + +# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) +.grunt + +# node-waf configuration +.lock-wscript + +# Compiled binary addons (http://nodejs.org/api/addons.html) +build/Release + +# Dependency directories +node_modules +jspm_packages + +# Optional npm cache directory +.npm + +# Optional REPL history +.node_repl_history diff --git a/scripts/2.5/node_modules/has-symbols/.travis.yml b/scripts/2.5/node_modules/has-symbols/.travis.yml new file mode 100644 index 00000000..3b3331a3 --- /dev/null +++ b/scripts/2.5/node_modules/has-symbols/.travis.yml @@ -0,0 +1,113 @@ +language: node_js +node_js: + - "6.6" + - "6.5" + - "6.4" + - "6.3" + - "6.2" + - "6.1" + - "6.0" + - "5.12" + - "5.11" + - "5.10" + - "5.9" + - "5.8" + - "5.7" + - "5.6" + - "5.5" + - "5.4" + - "5.3" + - "5.2" + - "5.1" + - "5.0" + - "4.5" + - "4.4" + - "4.3" + - "4.2" + - "4.1" + - "4.0" + - "iojs-v3.3" + - "iojs-v3.2" + - "iojs-v3.1" + - "iojs-v3.0" + - "iojs-v2.5" + - "iojs-v2.4" + - "iojs-v2.3" + - "iojs-v2.2" + - "iojs-v2.1" + - "iojs-v2.0" + - "iojs-v1.8" + - "iojs-v1.7" + - "iojs-v1.6" + - "iojs-v1.5" + - "iojs-v1.4" + - "iojs-v1.3" + - "iojs-v1.2" + - "iojs-v1.1" + - "iojs-v1.0" + - "0.12" + - "0.11" + - "0.10" + - "0.9" + - "0.8" + - "0.6" + - "0.4" +before_install: + - 'if [ "${TRAVIS_NODE_VERSION}" != "0.9" ]; then case "$(npm --version)" in 1.*) npm install -g npm@1.4.28 ;; 2.*) npm install -g npm@2 ;; esac ; fi' + - 'if [ "${TRAVIS_NODE_VERSION}" != "0.6" ] && [ "${TRAVIS_NODE_VERSION}" != "0.9" ]; then npm install -g npm; fi' +script: + - 'if [ -n "${LINT-}" ]; then npm run lint ; fi' + - 'if [ -n "${COVERAGE-}" ]; then npm run coverage ; fi' + - 'if [ -n "${TEST-}" ]; then npm run tests-only ; fi' +sudo: false +env: + - TEST=true +matrix: + fast_finish: true + include: + - node_js: "node" + env: LINT=true + allow_failures: + - node_js: "6.5" + - node_js: "6.4" + - node_js: "6.3" + - node_js: "6.2" + - node_js: "6.1" + - node_js: "6.0" + - node_js: "5.11" + - node_js: "5.10" + - node_js: "5.9" + - node_js: "5.8" + - node_js: "5.7" + - node_js: "5.6" + - node_js: "5.5" + - node_js: "5.4" + - node_js: "5.3" + - node_js: "5.2" + - node_js: "5.1" + - node_js: "5.0" + - node_js: "4.4" + - node_js: "4.3" + - node_js: "4.2" + - node_js: "4.1" + - node_js: "4.0" + - node_js: "iojs-v3.2" + - node_js: "iojs-v3.1" + - node_js: "iojs-v3.0" + - node_js: "iojs-v2.4" + - node_js: "iojs-v2.3" + - node_js: "iojs-v2.2" + - node_js: "iojs-v2.1" + - node_js: "iojs-v2.0" + - node_js: "iojs-v1.7" + - node_js: "iojs-v1.6" + - node_js: "iojs-v1.5" + - node_js: "iojs-v1.4" + - node_js: "iojs-v1.3" + - node_js: "iojs-v1.2" + - node_js: "iojs-v1.1" + - node_js: "iojs-v1.0" + - node_js: "0.11" + - node_js: "0.9" + - node_js: "0.6" + - node_js: "0.4" diff --git a/scripts/2.5/node_modules/has-symbols/CHANGELOG.md b/scripts/2.5/node_modules/has-symbols/CHANGELOG.md new file mode 100644 index 00000000..da7f9da7 --- /dev/null +++ b/scripts/2.5/node_modules/has-symbols/CHANGELOG.md @@ -0,0 +1,3 @@ +1.0.0 / 2016-09-19 +================= + * Initial release. diff --git a/scripts/2.5/node_modules/has-symbols/LICENSE b/scripts/2.5/node_modules/has-symbols/LICENSE new file mode 100644 index 00000000..df31cbf3 --- /dev/null +++ b/scripts/2.5/node_modules/has-symbols/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2016 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/scripts/2.5/node_modules/has-symbols/README.md b/scripts/2.5/node_modules/has-symbols/README.md new file mode 100644 index 00000000..b27b31ac --- /dev/null +++ b/scripts/2.5/node_modules/has-symbols/README.md @@ -0,0 +1,45 @@ +# has-symbols [![Version Badge][2]][1] + +[![Build Status][3]][4] +[![dependency status][5]][6] +[![dev dependency status][7]][8] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][11]][1] + +Determine if the JS environment has Symbol support. Supports spec, or shams. + +## Example + +```js +var hasSymbols = require('has-symbols'); + +hasSymbols() === true; // if the environment has native Symbol support. Not polyfillable, not forgeable. + +var hasSymbolsKinda = require('has-symbols/shams'); +hasSymbolsKinda() === true; // if the environment has a Symbol sham that mostly follows the spec. +``` + +## Supported Symbol shams + - get-own-property-symbols [npm](https://www.npmjs.com/package/get-own-property-symbols) | [github](https://github.com/WebReflection/get-own-property-symbols) + - core-js [npm](https://www.npmjs.com/package/core-js) | [github](https://github.com/zloirock/core-js) + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[1]: https://npmjs.org/package/has-symbols +[2]: http://versionbadg.es/ljharb/has-symbols.svg +[3]: https://travis-ci.org/ljharb/has-symbols.svg +[4]: https://travis-ci.org/ljharb/has-symbols +[5]: https://david-dm.org/ljharb/has-symbols.svg +[6]: https://david-dm.org/ljharb/has-symbols +[7]: https://david-dm.org/ljharb/has-symbols/dev-status.svg +[8]: https://david-dm.org/ljharb/has-symbols#info=devDependencies +[9]: https://ci.testling.com/ljharb/has-symbols.png +[10]: https://ci.testling.com/ljharb/has-symbols +[11]: https://nodei.co/npm/has-symbols.png?downloads=true&stars=true +[license-image]: http://img.shields.io/npm/l/has-symbols.svg +[license-url]: LICENSE +[downloads-image]: http://img.shields.io/npm/dm/has-symbols.svg +[downloads-url]: http://npm-stat.com/charts.html?package=has-symbols diff --git a/scripts/2.5/node_modules/has-symbols/index.js b/scripts/2.5/node_modules/has-symbols/index.js new file mode 100644 index 00000000..f72159e0 --- /dev/null +++ b/scripts/2.5/node_modules/has-symbols/index.js @@ -0,0 +1,13 @@ +'use strict'; + +var origSymbol = global.Symbol; +var hasSymbolSham = require('./shams'); + +module.exports = function hasNativeSymbols() { + if (typeof origSymbol !== 'function') { return false; } + if (typeof Symbol !== 'function') { return false; } + if (typeof origSymbol('foo') !== 'symbol') { return false; } + if (typeof Symbol('bar') !== 'symbol') { return false; } + + return hasSymbolSham(); +}; diff --git a/scripts/2.5/node_modules/has-symbols/package.json b/scripts/2.5/node_modules/has-symbols/package.json new file mode 100644 index 00000000..f4aae2b1 --- /dev/null +++ b/scripts/2.5/node_modules/has-symbols/package.json @@ -0,0 +1,108 @@ +{ + "_from": "has-symbols@^1.0.0", + "_id": "has-symbols@1.0.0", + "_inBundle": false, + "_integrity": "sha1-uhqPGvKg/DllD1yFA2dwQSIGO0Q=", + "_location": "/has-symbols", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "has-symbols@^1.0.0", + "name": "has-symbols", + "escapedName": "has-symbols", + "rawSpec": "^1.0.0", + "saveSpec": null, + "fetchSpec": "^1.0.0" + }, + "_requiredBy": [ + "/es-abstract", + "/is-symbol" + ], + "_resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.0.tgz", + "_shasum": "ba1a8f1af2a0fc39650f5c850367704122063b44", + "_spec": "has-symbols@^1.0.0", + "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/2.5/node_modules/es-abstract", + "author": { + "name": "Jordan Harband", + "email": "ljharb@gmail.com", + "url": "http://ljharb.codes" + }, + "bugs": { + "url": "https://github.com/ljharb/has-symbols/issues" + }, + "bundleDependencies": false, + "contributors": [ + { + "name": "Jordan Harband", + "email": "ljharb@gmail.com", + "url": "http://ljharb.codes" + } + ], + "dependencies": {}, + "deprecated": false, + "description": "Determine if the JS environment has Symbol support. Supports spec, or shams.", + "devDependencies": { + "@ljharb/eslint-config": "^8.0.0", + "core-js": "^2.4.1", + "eslint": "^3.5.0", + "get-own-property-symbols": "^0.9.2", + "nsp": "^2.6.1", + "safe-publish-latest": "^1.0.1", + "tape": "^4.6.0" + }, + "engines": { + "node": ">= 0.4" + }, + "homepage": "https://github.com/ljharb/has-symbols#readme", + "keywords": [ + "Symbol", + "symbols", + "typeof", + "sham", + "polyfill", + "native", + "core-js", + "ES6" + ], + "license": "MIT", + "main": "index.js", + "name": "has-symbols", + "repository": { + "type": "git", + "url": "git://github.com/ljharb/has-symbols.git" + }, + "scripts": { + "lint": "eslint *.js", + "posttest": "npm run --silent security", + "prepublish": "safe-publish-latest", + "pretest": "npm run --silent lint", + "security": "nsp check", + "test": "npm run --silent tests-only", + "test:shams": "npm run --silent test:shams:getownpropertysymbols && npm run --silent test:shams:corejs", + "test:shams:corejs": "node test/shams/core-js.js", + "test:shams:getownpropertysymbols": "node test/shams/get-own-property-symbols.js", + "test:staging": "node --harmony --es-staging test", + "test:stock": "node test", + "tests-only": "npm run --silent test:stock && npm run --silent test:staging && npm run --silent test:shams" + }, + "testling": { + "files": "test/index.js", + "browsers": [ + "iexplore/6.0..latest", + "firefox/3.0..6.0", + "firefox/15.0..latest", + "firefox/nightly", + "chrome/4.0..10.0", + "chrome/20.0..latest", + "chrome/canary", + "opera/10.0..latest", + "opera/next", + "safari/4.0..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2" + ] + }, + "version": "1.0.0" +} diff --git a/scripts/2.5/node_modules/has-symbols/shams.js b/scripts/2.5/node_modules/has-symbols/shams.js new file mode 100644 index 00000000..f6c1ff4a --- /dev/null +++ b/scripts/2.5/node_modules/has-symbols/shams.js @@ -0,0 +1,42 @@ +'use strict'; + +/* eslint complexity: [2, 17], max-statements: [2, 33] */ +module.exports = function hasSymbols() { + if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; } + if (typeof Symbol.iterator === 'symbol') { return true; } + + var obj = {}; + var sym = Symbol('test'); + var symObj = Object(sym); + if (typeof sym === 'string') { return false; } + + if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; } + if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; } + + // temp disabled per https://github.com/ljharb/object.assign/issues/17 + // if (sym instanceof Symbol) { return false; } + // temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4 + // if (!(symObj instanceof Symbol)) { return false; } + + // if (typeof Symbol.prototype.toString !== 'function') { return false; } + // if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; } + + var symVal = 42; + obj[sym] = symVal; + for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax + if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; } + + if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; } + + var syms = Object.getOwnPropertySymbols(obj); + if (syms.length !== 1 || syms[0] !== sym) { return false; } + + if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; } + + if (typeof Object.getOwnPropertyDescriptor === 'function') { + var descriptor = Object.getOwnPropertyDescriptor(obj, sym); + if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; } + } + + return true; +}; diff --git a/scripts/2.5/node_modules/has-symbols/test/index.js b/scripts/2.5/node_modules/has-symbols/test/index.js new file mode 100644 index 00000000..fc32aff9 --- /dev/null +++ b/scripts/2.5/node_modules/has-symbols/test/index.js @@ -0,0 +1,22 @@ +'use strict'; + +var test = require('tape'); +var hasSymbols = require('../'); +var runSymbolTests = require('./tests'); + +test('interface', function (t) { + t.equal(typeof hasSymbols, 'function', 'is a function'); + t.equal(typeof hasSymbols(), 'boolean', 'returns a boolean'); + t.end(); +}); + +test('Symbols are supported', { skip: !hasSymbols() }, function (t) { + runSymbolTests(t); + t.end(); +}); + +test('Symbols are not supported', { skip: hasSymbols() }, function (t) { + t.equal(typeof Symbol, 'undefined', 'global Symbol is undefined'); + t.equal(typeof Object.getOwnPropertySymbols, 'undefined', 'Object.getOwnPropertySymbols does not exist'); + t.end(); +}); diff --git a/scripts/2.5/node_modules/has-symbols/test/shams/core-js.js b/scripts/2.5/node_modules/has-symbols/test/shams/core-js.js new file mode 100644 index 00000000..df5365c2 --- /dev/null +++ b/scripts/2.5/node_modules/has-symbols/test/shams/core-js.js @@ -0,0 +1,28 @@ +'use strict'; + +var test = require('tape'); + +if (typeof Symbol === 'function' && typeof Symbol() === 'symbol') { + test('has native Symbol support', function (t) { + t.equal(typeof Symbol, 'function'); + t.equal(typeof Symbol(), 'symbol'); + t.end(); + }); + return; +} + +var hasSymbols = require('../../shams'); + +test('polyfilled Symbols', function (t) { + /* eslint-disable global-require */ + t.equal(hasSymbols(), false, 'hasSymbols is false before polyfilling'); + require('core-js/fn/symbol'); + require('core-js/fn/symbol/to-string-tag'); + + require('../tests')(t); + + var hasSymbolsAfter = hasSymbols(); + t.equal(hasSymbolsAfter, true, 'hasSymbols is true after polyfilling'); + /* eslint-enable global-require */ + t.end(); +}); diff --git a/scripts/2.5/node_modules/has-symbols/test/shams/get-own-property-symbols.js b/scripts/2.5/node_modules/has-symbols/test/shams/get-own-property-symbols.js new file mode 100644 index 00000000..9191b248 --- /dev/null +++ b/scripts/2.5/node_modules/has-symbols/test/shams/get-own-property-symbols.js @@ -0,0 +1,28 @@ +'use strict'; + +var test = require('tape'); + +if (typeof Symbol === 'function' && typeof Symbol() === 'symbol') { + test('has native Symbol support', function (t) { + t.equal(typeof Symbol, 'function'); + t.equal(typeof Symbol(), 'symbol'); + t.end(); + }); + return; +} + +var hasSymbols = require('../../shams'); + +test('polyfilled Symbols', function (t) { + /* eslint-disable global-require */ + t.equal(hasSymbols(), false, 'hasSymbols is false before polyfilling'); + + require('get-own-property-symbols'); + + require('../tests')(t); + + var hasSymbolsAfter = hasSymbols(); + t.equal(hasSymbolsAfter, true, 'hasSymbols is true after polyfilling'); + /* eslint-enable global-require */ + t.end(); +}); diff --git a/scripts/2.5/node_modules/has-symbols/test/tests.js b/scripts/2.5/node_modules/has-symbols/test/tests.js new file mode 100644 index 00000000..93ff0eae --- /dev/null +++ b/scripts/2.5/node_modules/has-symbols/test/tests.js @@ -0,0 +1,54 @@ +'use strict'; + +module.exports = function runSymbolTests(t) { + t.equal(typeof Symbol, 'function', 'global Symbol is a function'); + + if (typeof Symbol !== 'function') { return false }; + + t.notEqual(Symbol(), Symbol(), 'two symbols are not equal'); + + /* + t.equal( + Symbol.prototype.toString.call(Symbol('foo')), + Symbol.prototype.toString.call(Symbol('foo')), + 'two symbols with the same description stringify the same' + ); + */ + + var foo = Symbol('foo'); + + /* + t.notEqual( + String(foo), + String(Symbol('bar')), + 'two symbols with different descriptions do not stringify the same' + ); + */ + + t.equal(typeof Symbol.prototype.toString, 'function', 'Symbol#toString is a function'); + // t.equal(String(foo), Symbol.prototype.toString.call(foo), 'Symbol#toString equals String of the same symbol'); + + t.equal(typeof Object.getOwnPropertySymbols, 'function', 'Object.getOwnPropertySymbols is a function'); + + var obj = {}; + var sym = Symbol('test'); + var symObj = Object(sym); + t.notEqual(typeof sym, 'string', 'Symbol is not a string'); + t.equal(Object.prototype.toString.call(sym), '[object Symbol]', 'symbol primitive Object#toStrings properly'); + t.equal(Object.prototype.toString.call(symObj), '[object Symbol]', 'symbol primitive Object#toStrings properly'); + + var symVal = 42; + obj[sym] = symVal; + for (sym in obj) { t.fail('symbol property key was found in for..in of object'); } + + t.deepEqual(Object.keys(obj), [], 'no enumerable own keys on symbol-valued object'); + t.deepEqual(Object.getOwnPropertyNames(obj), [], 'no own names on symbol-valued object'); + t.deepEqual(Object.getOwnPropertySymbols(obj), [sym], 'one own symbol on symbol-valued object'); + t.equal(Object.prototype.propertyIsEnumerable.call(obj, sym), true, 'symbol is enumerable'); + t.deepEqual(Object.getOwnPropertyDescriptor(obj, sym), { + configurable: true, + enumerable: true, + value: 42, + writable: true + }, 'property descriptor is correct'); +}; diff --git a/scripts/2.5/node_modules/has/LICENSE-MIT b/scripts/2.5/node_modules/has/LICENSE-MIT new file mode 100644 index 00000000..ae7014d3 --- /dev/null +++ b/scripts/2.5/node_modules/has/LICENSE-MIT @@ -0,0 +1,22 @@ +Copyright (c) 2013 Thiago de Arruda + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/scripts/2.5/node_modules/has/README.md b/scripts/2.5/node_modules/has/README.md new file mode 100644 index 00000000..635e3a4b --- /dev/null +++ b/scripts/2.5/node_modules/has/README.md @@ -0,0 +1,18 @@ +# has + +> Object.prototype.hasOwnProperty.call shortcut + +## Installation + +```sh +npm install --save has +``` + +## Usage + +```js +var has = require('has'); + +has({}, 'hasOwnProperty'); // false +has(Object.prototype, 'hasOwnProperty'); // true +``` diff --git a/scripts/2.5/node_modules/has/package.json b/scripts/2.5/node_modules/has/package.json new file mode 100644 index 00000000..264e52f9 --- /dev/null +++ b/scripts/2.5/node_modules/has/package.json @@ -0,0 +1,75 @@ +{ + "_from": "has@^1.0.3", + "_id": "has@1.0.3", + "_inBundle": false, + "_integrity": "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==", + "_location": "/has", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "has@^1.0.3", + "name": "has", + "escapedName": "has", + "rawSpec": "^1.0.3", + "saveSpec": null, + "fetchSpec": "^1.0.3" + }, + "_requiredBy": [ + "/es-abstract", + "/is-regex", + "/object.entries" + ], + "_resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz", + "_shasum": "722d7cbfc1f6aa8241f16dd814e011e1f41e8796", + "_spec": "has@^1.0.3", + "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/2.5/node_modules/object.entries", + "author": { + "name": "Thiago de Arruda", + "email": "tpadilha84@gmail.com" + }, + "bugs": { + "url": "https://github.com/tarruda/has/issues" + }, + "bundleDependencies": false, + "contributors": [ + { + "name": "Jordan Harband", + "email": "ljharb@gmail.com", + "url": "http://ljharb.codes" + } + ], + "dependencies": { + "function-bind": "^1.1.1" + }, + "deprecated": false, + "description": "Object.prototype.hasOwnProperty.call shortcut", + "devDependencies": { + "@ljharb/eslint-config": "^12.2.1", + "eslint": "^4.19.1", + "tape": "^4.9.0" + }, + "engines": { + "node": ">= 0.4.0" + }, + "homepage": "https://github.com/tarruda/has", + "license": "MIT", + "licenses": [ + { + "type": "MIT", + "url": "https://github.com/tarruda/has/blob/master/LICENSE-MIT" + } + ], + "main": "./src", + "name": "has", + "repository": { + "type": "git", + "url": "git://github.com/tarruda/has.git" + }, + "scripts": { + "lint": "eslint .", + "pretest": "npm run lint", + "test": "tape test" + }, + "version": "1.0.3" +} diff --git a/scripts/2.5/node_modules/has/src/index.js b/scripts/2.5/node_modules/has/src/index.js new file mode 100644 index 00000000..dd92dd90 --- /dev/null +++ b/scripts/2.5/node_modules/has/src/index.js @@ -0,0 +1,5 @@ +'use strict'; + +var bind = require('function-bind'); + +module.exports = bind.call(Function.call, Object.prototype.hasOwnProperty); diff --git a/scripts/2.5/node_modules/has/test/index.js b/scripts/2.5/node_modules/has/test/index.js new file mode 100644 index 00000000..43d480b2 --- /dev/null +++ b/scripts/2.5/node_modules/has/test/index.js @@ -0,0 +1,10 @@ +'use strict'; + +var test = require('tape'); +var has = require('../'); + +test('has', function (t) { + t.equal(has({}, 'hasOwnProperty'), false, 'object literal does not have own property "hasOwnProperty"'); + t.equal(has(Object.prototype, 'hasOwnProperty'), true, 'Object.prototype has own property "hasOwnProperty"'); + t.end(); +}); diff --git a/scripts/2.5/node_modules/inherits/LICENSE b/scripts/2.5/node_modules/inherits/LICENSE new file mode 100644 index 00000000..dea3013d --- /dev/null +++ b/scripts/2.5/node_modules/inherits/LICENSE @@ -0,0 +1,16 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. + diff --git a/scripts/2.5/node_modules/inherits/README.md b/scripts/2.5/node_modules/inherits/README.md new file mode 100644 index 00000000..b1c56658 --- /dev/null +++ b/scripts/2.5/node_modules/inherits/README.md @@ -0,0 +1,42 @@ +Browser-friendly inheritance fully compatible with standard node.js +[inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor). + +This package exports standard `inherits` from node.js `util` module in +node environment, but also provides alternative browser-friendly +implementation through [browser +field](https://gist.github.com/shtylman/4339901). Alternative +implementation is a literal copy of standard one located in standalone +module to avoid requiring of `util`. It also has a shim for old +browsers with no `Object.create` support. + +While keeping you sure you are using standard `inherits` +implementation in node.js environment, it allows bundlers such as +[browserify](https://github.com/substack/node-browserify) to not +include full `util` package to your client code if all you need is +just `inherits` function. It worth, because browser shim for `util` +package is large and `inherits` is often the single function you need +from it. + +It's recommended to use this package instead of +`require('util').inherits` for any code that has chances to be used +not only in node.js but in browser too. + +## usage + +```js +var inherits = require('inherits'); +// then use exactly as the standard one +``` + +## note on version ~1.0 + +Version ~1.0 had completely different motivation and is not compatible +neither with 2.0 nor with standard node.js `inherits`. + +If you are using version ~1.0 and planning to switch to ~2.0, be +careful: + +* new version uses `super_` instead of `super` for referencing + superclass +* new version overwrites current prototype while old one preserves any + existing fields on it diff --git a/scripts/2.5/node_modules/inherits/inherits.js b/scripts/2.5/node_modules/inherits/inherits.js new file mode 100644 index 00000000..f71f2d93 --- /dev/null +++ b/scripts/2.5/node_modules/inherits/inherits.js @@ -0,0 +1,9 @@ +try { + var util = require('util'); + /* istanbul ignore next */ + if (typeof util.inherits !== 'function') throw ''; + module.exports = util.inherits; +} catch (e) { + /* istanbul ignore next */ + module.exports = require('./inherits_browser.js'); +} diff --git a/scripts/2.5/node_modules/inherits/inherits_browser.js b/scripts/2.5/node_modules/inherits/inherits_browser.js new file mode 100644 index 00000000..86bbb3dc --- /dev/null +++ b/scripts/2.5/node_modules/inherits/inherits_browser.js @@ -0,0 +1,27 @@ +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }) + } + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } + } +} diff --git a/scripts/2.5/node_modules/inherits/package.json b/scripts/2.5/node_modules/inherits/package.json new file mode 100644 index 00000000..1b984ce0 --- /dev/null +++ b/scripts/2.5/node_modules/inherits/package.json @@ -0,0 +1,61 @@ +{ + "_from": "inherits@^2.0.3", + "_id": "inherits@2.0.4", + "_inBundle": false, + "_integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "_location": "/inherits", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "inherits@^2.0.3", + "name": "inherits", + "escapedName": "inherits", + "rawSpec": "^2.0.3", + "saveSpec": null, + "fetchSpec": "^2.0.3" + }, + "_requiredBy": [ + "/util" + ], + "_resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "_shasum": "0fa2c64f932917c3433a0ded55363aae37416b7c", + "_spec": "inherits@^2.0.3", + "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/2.5/node_modules/util", + "browser": "./inherits_browser.js", + "bugs": { + "url": "https://github.com/isaacs/inherits/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "Browser-friendly inheritance fully compatible with standard node.js inherits()", + "devDependencies": { + "tap": "^14.2.4" + }, + "files": [ + "inherits.js", + "inherits_browser.js" + ], + "homepage": "https://github.com/isaacs/inherits#readme", + "keywords": [ + "inheritance", + "class", + "klass", + "oop", + "object-oriented", + "inherits", + "browser", + "browserify" + ], + "license": "ISC", + "main": "./inherits.js", + "name": "inherits", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/inherits.git" + }, + "scripts": { + "test": "tap" + }, + "version": "2.0.4" +} diff --git a/scripts/2.5/node_modules/is-arguments/.editorconfig b/scripts/2.5/node_modules/is-arguments/.editorconfig new file mode 100644 index 00000000..bc228f82 --- /dev/null +++ b/scripts/2.5/node_modules/is-arguments/.editorconfig @@ -0,0 +1,20 @@ +root = true + +[*] +indent_style = tab +indent_size = 4 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true +max_line_length = 150 + +[CHANGELOG.md] +indent_style = space +indent_size = 2 + +[*.json] +max_line_length = off + +[Makefile] +max_line_length = off diff --git a/scripts/2.5/node_modules/is-arguments/.eslintrc b/scripts/2.5/node_modules/is-arguments/.eslintrc new file mode 100644 index 00000000..6d42c6ed --- /dev/null +++ b/scripts/2.5/node_modules/is-arguments/.eslintrc @@ -0,0 +1,10 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "id-length": [2, { "min": 1, "max": 25 }], + "operator-linebreak": [2, "after"] + } +} diff --git a/scripts/2.5/node_modules/is-arguments/.jscs.json b/scripts/2.5/node_modules/is-arguments/.jscs.json new file mode 100644 index 00000000..b4d9b8b4 --- /dev/null +++ b/scripts/2.5/node_modules/is-arguments/.jscs.json @@ -0,0 +1,176 @@ +{ + "es3": true, + + "additionalRules": [], + + "requireSemicolons": true, + + "disallowMultipleSpaces": true, + + "disallowIdentifierNames": [], + + "requireCurlyBraces": { + "allExcept": [], + "keywords": ["if", "else", "for", "while", "do", "try", "catch"] + }, + + "requireSpaceAfterKeywords": ["if", "else", "for", "while", "do", "switch", "return", "try", "catch", "function"], + + "disallowSpaceAfterKeywords": [], + + "disallowSpaceBeforeComma": true, + "disallowSpaceAfterComma": false, + "disallowSpaceBeforeSemicolon": true, + + "disallowNodeTypes": [ + "DebuggerStatement", + "ForInStatement", + "LabeledStatement", + "SwitchCase", + "SwitchStatement", + "WithStatement" + ], + + "requireObjectKeysOnNewLine": { "allExcept": ["sameLine"] }, + + "requireSpacesInAnonymousFunctionExpression": { "beforeOpeningRoundBrace": true, "beforeOpeningCurlyBrace": true }, + "requireSpacesInNamedFunctionExpression": { "beforeOpeningCurlyBrace": true }, + "disallowSpacesInNamedFunctionExpression": { "beforeOpeningRoundBrace": true }, + "requireSpacesInFunctionDeclaration": { "beforeOpeningCurlyBrace": true }, + "disallowSpacesInFunctionDeclaration": { "beforeOpeningRoundBrace": true }, + + "requireSpaceBetweenArguments": true, + + "disallowSpacesInsideParentheses": true, + + "disallowSpacesInsideArrayBrackets": true, + + "disallowQuotedKeysInObjects": { "allExcept": ["reserved"] }, + + "disallowSpaceAfterObjectKeys": true, + + "requireCommaBeforeLineBreak": true, + + "disallowSpaceAfterPrefixUnaryOperators": ["++", "--", "+", "-", "~", "!"], + "requireSpaceAfterPrefixUnaryOperators": [], + + "disallowSpaceBeforePostfixUnaryOperators": ["++", "--"], + "requireSpaceBeforePostfixUnaryOperators": [], + + "disallowSpaceBeforeBinaryOperators": [], + "requireSpaceBeforeBinaryOperators": ["+", "-", "/", "*", "=", "==", "===", "!=", "!=="], + + "requireSpaceAfterBinaryOperators": ["+", "-", "/", "*", "=", "==", "===", "!=", "!=="], + "disallowSpaceAfterBinaryOperators": [], + + "disallowImplicitTypeConversion": ["binary", "string"], + + "disallowKeywords": ["with", "eval"], + + "requireKeywordsOnNewLine": [], + "disallowKeywordsOnNewLine": ["else"], + + "requireLineFeedAtFileEnd": true, + + "disallowTrailingWhitespace": true, + + "disallowTrailingComma": true, + + "excludeFiles": ["node_modules/**", "vendor/**"], + + "disallowMultipleLineStrings": true, + + "requireDotNotation": { "allExcept": ["keywords"] }, + + "requireParenthesesAroundIIFE": true, + + "validateLineBreaks": "LF", + + "validateQuoteMarks": { + "escape": true, + "mark": "'" + }, + + "disallowOperatorBeforeLineBreak": [], + + "requireSpaceBeforeKeywords": [ + "do", + "for", + "if", + "else", + "switch", + "case", + "try", + "catch", + "finally", + "while", + "with", + "return" + ], + + "validateAlignedFunctionParameters": { + "lineBreakAfterOpeningBraces": true, + "lineBreakBeforeClosingBraces": true + }, + + "requirePaddingNewLinesBeforeExport": true, + + "validateNewlineAfterArrayElements": { + "maximum": 1 + }, + + "requirePaddingNewLinesAfterUseStrict": true, + + "disallowArrowFunctions": true, + + "disallowMultiLineTernary": true, + + "validateOrderInObjectKeys": "asc-insensitive", + + "disallowIdenticalDestructuringNames": true, + + "disallowNestedTernaries": { "maxLevel": 1 }, + + "requireSpaceAfterComma": { "allExcept": ["trailing"] }, + "requireAlignedMultilineParams": false, + + "requireSpacesInGenerator": { + "afterStar": true + }, + + "disallowSpacesInGenerator": { + "beforeStar": true + }, + + "disallowVar": false, + + "requireArrayDestructuring": false, + + "requireEnhancedObjectLiterals": false, + + "requireObjectDestructuring": false, + + "requireEarlyReturn": false, + + "requireCapitalizedConstructorsNew": { + "allExcept": ["Function", "String", "Object", "Symbol", "Number", "Date", "RegExp", "Error", "Boolean", "Array"] + }, + + "requireImportAlphabetized": false, + + "requireSpaceBeforeObjectValues": true, + "requireSpaceBeforeDestructuredValues": true, + + "disallowSpacesInsideTemplateStringPlaceholders": true, + + "disallowArrayDestructuringReturn": false, + + "requireNewlineBeforeSingleStatementsInIf": false, + + "disallowUnusedVariables": true, + + "requireSpacesInsideImportedObjectBraces": true, + + "requireUseStrict": true +} + diff --git a/scripts/2.5/node_modules/is-arguments/.travis.yml b/scripts/2.5/node_modules/is-arguments/.travis.yml new file mode 100644 index 00000000..db517853 --- /dev/null +++ b/scripts/2.5/node_modules/is-arguments/.travis.yml @@ -0,0 +1,248 @@ +language: node_js +os: + - linux +node_js: + - "11.1" + - "10.13" + - "9.11" + - "8.12" + - "7.10" + - "6.14" + - "5.12" + - "4.9" + - "iojs-v3.3" + - "iojs-v2.5" + - "iojs-v1.8" + - "0.12" + - "0.10" + - "0.8" +before_install: + - 'case "${TRAVIS_NODE_VERSION}" in 0.*) export NPM_CONFIG_STRICT_SSL=false ;; esac' + - 'nvm install-latest-npm' +install: + - 'if [ "${TRAVIS_NODE_VERSION}" = "0.6" ] || [ "${TRAVIS_NODE_VERSION}" = "0.9" ]; then nvm install --latest-npm 0.8 && npm install && nvm use "${TRAVIS_NODE_VERSION}"; else npm install; fi;' +script: + - 'if [ -n "${PRETEST-}" ]; then npm run pretest ; fi' + - 'if [ -n "${POSTTEST-}" ]; then npm run posttest ; fi' + - 'if [ -n "${COVERAGE-}" ]; then npm run coverage ; fi' + - 'if [ -n "${TEST-}" ]; then npm run tests-only ; fi' +sudo: false +env: + - TEST=true +matrix: + fast_finish: true + include: + - node_js: "lts/*" + env: PRETEST=true + - node_js: "lts/*" + env: POSTTEST=true + - node_js: "4" + env: COVERAGE=true + - node_js: "11.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.12" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.13" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.12" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v3.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v3.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v3.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.4" + env: TEST=true ALLOW_FAILURE=true + allow_failures: + - os: osx + - env: TEST=true ALLOW_FAILURE=true + - env: COVERAGE=true diff --git a/scripts/2.5/node_modules/is-arguments/CHANGELOG.md b/scripts/2.5/node_modules/is-arguments/CHANGELOG.md new file mode 100644 index 00000000..8e2a361a --- /dev/null +++ b/scripts/2.5/node_modules/is-arguments/CHANGELOG.md @@ -0,0 +1,32 @@ +1.0.4 / 2018-11-05 +================== + * [Fix] Fix errors about `in` operator (#22) + +1.0.3 / 2018-11-02 +================== + * [Fix] add awareness of Symbol.toStringTag (#20) + * [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape`, `jscs`, `nsp` + * [Tests] up to `node` `v11.1`, `v10.13`, `v9.11`, `v8.12`, `v7.10`, `v6.14`, `v5.11`, `v4.8`; use `nvm install-latest-npm`; pin included builds to LTS. + +1.0.2 / 2015-09-21 +================== + * [Docs] Switch from vb.teelaun.ch to versionbadg.es for the npm version badge SVG. + * [Enhancement] In modern engines, only export the "is standard arguments" check. + * [Fix] `toString` as a variable name breaks in some older browsers. + * [Dev Deps] update `covert`, `jscs`, `eslint` + * [Tests] up to `io.js` `v3.3`, `node` `v4.1` + +1.0.1 / 2015-04-29 +================== + * [Docs] clean up README; add badges + * [Dev Deps] update `tape`, `covert` + * [Tests] add `npm run lint` + +1.0.0 / 2014-01-14 +================== + * Bump to v1.0 + +0.1.0 / 2014-01-14 +================== + * Initial release. + diff --git a/scripts/2.5/node_modules/is-arguments/LICENSE b/scripts/2.5/node_modules/is-arguments/LICENSE new file mode 100644 index 00000000..47b7b507 --- /dev/null +++ b/scripts/2.5/node_modules/is-arguments/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2014 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/scripts/2.5/node_modules/is-arguments/README.md b/scripts/2.5/node_modules/is-arguments/README.md new file mode 100644 index 00000000..b5353bc3 --- /dev/null +++ b/scripts/2.5/node_modules/is-arguments/README.md @@ -0,0 +1,49 @@ +#is-arguments [![Version Badge][2]][1] + +[![Build Status][3]][4] +[![dependency status][5]][6] +[![dev dependency status][7]][8] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][11]][1] + +[![browser support][9]][10] + +Is this an arguments object? It's a harder question than you think. + +## Example + +```js +var isArguments = require('is-arguments'); +var assert = require('assert'); + +assert.equal(isArguments({}), false); +assert.equal(isArguments([]), false); +(function () { + assert.equal(isArguments(arguments), true); +}()) +``` + +## Caveats +If you have modified an actual `arguments` object by giving it a `Symbol.toStringTag` property, then this package will return `false`. + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[1]: https://npmjs.org/package/is-arguments +[2]: http://versionbadg.es/ljharb/is-arguments.svg +[3]: https://travis-ci.org/ljharb/is-arguments.svg +[4]: https://travis-ci.org/ljharb/is-arguments +[5]: https://david-dm.org/ljharb/is-arguments.svg +[6]: https://david-dm.org/ljharb/is-arguments +[7]: https://david-dm.org/ljharb/is-arguments/dev-status.svg +[8]: https://david-dm.org/ljharb/is-arguments#info=devDependencies +[9]: https://ci.testling.com/ljharb/is-arguments.png +[10]: https://ci.testling.com/ljharb/is-arguments +[11]: https://nodei.co/npm/is-arguments.png?downloads=true&stars=true +[license-image]: http://img.shields.io/npm/l/is-arguments.svg +[license-url]: LICENSE +[downloads-image]: http://img.shields.io/npm/dm/is-arguments.svg +[downloads-url]: http://npm-stat.com/charts.html?package=is-arguments + diff --git a/scripts/2.5/node_modules/is-arguments/index.js b/scripts/2.5/node_modules/is-arguments/index.js new file mode 100644 index 00000000..84cc200f --- /dev/null +++ b/scripts/2.5/node_modules/is-arguments/index.js @@ -0,0 +1,31 @@ +'use strict'; + +var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol'; +var toStr = Object.prototype.toString; + +var isStandardArguments = function isArguments(value) { + if (hasToStringTag && value && typeof value === 'object' && Symbol.toStringTag in value) { + return false; + } + return toStr.call(value) === '[object Arguments]'; +}; + +var isLegacyArguments = function isArguments(value) { + if (isStandardArguments(value)) { + return true; + } + return value !== null && + typeof value === 'object' && + typeof value.length === 'number' && + value.length >= 0 && + toStr.call(value) !== '[object Array]' && + toStr.call(value.callee) === '[object Function]'; +}; + +var supportsStandardArguments = (function () { + return isStandardArguments(arguments); +}()); + +isStandardArguments.isLegacyArguments = isLegacyArguments; // for tests + +module.exports = supportsStandardArguments ? isStandardArguments : isLegacyArguments; diff --git a/scripts/2.5/node_modules/is-arguments/package.json b/scripts/2.5/node_modules/is-arguments/package.json new file mode 100644 index 00000000..e754d7d3 --- /dev/null +++ b/scripts/2.5/node_modules/is-arguments/package.json @@ -0,0 +1,101 @@ +{ + "_from": "is-arguments@^1.0.4", + "_id": "is-arguments@1.0.4", + "_inBundle": false, + "_integrity": "sha512-xPh0Rmt8NE65sNzvyUmWgI1tz3mKq74lGA0mL8LYZcoIzKOzDh6HmrYm3d18k60nHerC8A9Km8kYu87zfSFnLA==", + "_location": "/is-arguments", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "is-arguments@^1.0.4", + "name": "is-arguments", + "escapedName": "is-arguments", + "rawSpec": "^1.0.4", + "saveSpec": null, + "fetchSpec": "^1.0.4" + }, + "_requiredBy": [ + "/util" + ], + "_resolved": "https://registry.npmjs.org/is-arguments/-/is-arguments-1.0.4.tgz", + "_shasum": "3faf966c7cba0ff437fb31f6250082fcf0448cf3", + "_spec": "is-arguments@^1.0.4", + "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/2.5/node_modules/util", + "author": { + "name": "Jordan Harband", + "email": "ljharb@gmail.com", + "url": "http://ljharb.codes" + }, + "bugs": { + "url": "https://github.com/ljharb/is-arguments/issues" + }, + "bundleDependencies": false, + "contributors": [ + { + "name": "Jordan Harband", + "email": "ljharb@gmail.com", + "url": "http://ljharb.codes" + } + ], + "dependencies": {}, + "deprecated": false, + "description": "Is this an arguments object? It's a harder question than you think.", + "devDependencies": { + "@ljharb/eslint-config": "^13.0.0", + "covert": "^1.1.0", + "eslint": "^5.8.0", + "jscs": "^3.0.7", + "nsp": "^3.2.1", + "tape": "^4.9.1" + }, + "engines": { + "node": ">= 0.4" + }, + "homepage": "https://github.com/ljharb/is-arguments", + "keywords": [ + "arguments", + "js", + "javascript", + "is-arguments", + "is", + "object" + ], + "license": "MIT", + "main": "index.js", + "name": "is-arguments", + "repository": { + "type": "git", + "url": "git://github.com/ljharb/is-arguments.git" + }, + "scripts": { + "coverage": "covert test.js", + "eslint": "eslint *.js", + "jscs": "jscs *.js", + "lint": "npm run --silent jscs && npm run --silent eslint", + "posttest": "npm run --silent security", + "pretest": "npm run --silent lint", + "security": "nsp check", + "test": "npm run --silent tests-only", + "tests-only": "node test.js" + }, + "testling": { + "files": "test.js", + "browsers": [ + "iexplore/6.0..latest", + "firefox/3.0..6.0", + "firefox/15.0..latest", + "firefox/nightly", + "chrome/4.0..10.0", + "chrome/20.0..latest", + "chrome/canary", + "opera/10.0..latest", + "opera/next", + "safari/4.0..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2" + ] + }, + "version": "1.0.4" +} diff --git a/scripts/2.5/node_modules/is-arguments/test.js b/scripts/2.5/node_modules/is-arguments/test.js new file mode 100644 index 00000000..fca78d83 --- /dev/null +++ b/scripts/2.5/node_modules/is-arguments/test.js @@ -0,0 +1,44 @@ +'use strict'; + +var test = require('tape'); +var isArguments = require('./'); +var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol'; + +test('primitives', function (t) { + t.notOk(isArguments([]), 'array is not arguments'); + t.notOk(isArguments({}), 'object is not arguments'); + t.notOk(isArguments(''), 'empty string is not arguments'); + t.notOk(isArguments('foo'), 'string is not arguments'); + t.notOk(isArguments({ length: 2 }), 'naive array-like is not arguments'); + t.end(); +}); + +test('arguments object', function (t) { + t.ok(isArguments(arguments), 'arguments is arguments'); + t.notOk(isArguments(Array.prototype.slice.call(arguments)), 'sliced arguments is not arguments'); + t.end(); +}); + +test('old-style arguments object', function (t) { + var isLegacyArguments = isArguments.isLegacyArguments || isArguments; + var fakeOldArguments = { + callee: function () {}, + length: 3 + }; + t.ok(isLegacyArguments(fakeOldArguments), 'old-style arguments is arguments'); + t.end(); +}); + +test('Symbol.toStringTag', { skip: !hasToStringTag }, function (t) { + var obj = {}; + obj[Symbol.toStringTag] = 'Arguments'; + t.notOk(isArguments(obj), 'object with faked toStringTag is not arguments'); + + var args = (function () { + return arguments; + }()); + args[Symbol.toStringTag] = 'Arguments'; + t.notOk(isArguments(obj), 'real arguments with faked toStringTag is not arguments'); + + t.end(); +}); diff --git a/scripts/2.5/node_modules/is-callable/.editorconfig b/scripts/2.5/node_modules/is-callable/.editorconfig new file mode 100644 index 00000000..bc228f82 --- /dev/null +++ b/scripts/2.5/node_modules/is-callable/.editorconfig @@ -0,0 +1,20 @@ +root = true + +[*] +indent_style = tab +indent_size = 4 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true +max_line_length = 150 + +[CHANGELOG.md] +indent_style = space +indent_size = 2 + +[*.json] +max_line_length = off + +[Makefile] +max_line_length = off diff --git a/scripts/2.5/node_modules/is-callable/.eslintrc b/scripts/2.5/node_modules/is-callable/.eslintrc new file mode 100644 index 00000000..db619b50 --- /dev/null +++ b/scripts/2.5/node_modules/is-callable/.eslintrc @@ -0,0 +1,11 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "id-length": 0, + "max-statements": [2, 12], + "max-statements-per-line": [2, { "max": 2 }] + } +} diff --git a/scripts/2.5/node_modules/is-callable/.istanbul.yml b/scripts/2.5/node_modules/is-callable/.istanbul.yml new file mode 100644 index 00000000..9affe0bc --- /dev/null +++ b/scripts/2.5/node_modules/is-callable/.istanbul.yml @@ -0,0 +1,47 @@ +verbose: false +instrumentation: + root: . + extensions: + - .js + - .jsx + default-excludes: true + excludes: [] + variable: __coverage__ + compact: true + preserve-comments: false + complete-copy: false + save-baseline: false + baseline-file: ./coverage/coverage-baseline.raw.json + include-all-sources: false + include-pid: false + es-modules: false + auto-wrap: false +reporting: + print: summary + reports: + - html + dir: ./coverage + summarizer: pkg + report-config: {} + watermarks: + statements: [50, 80] + functions: [50, 80] + branches: [50, 80] + lines: [50, 80] +hooks: + hook-run-in-context: false + post-require-hook: null + handle-sigint: false +check: + global: + statements: 100 + lines: 100 + branches: 100 + functions: 100 + excludes: [] + each: + statements: 100 + lines: 100 + branches: 100 + functions: 100 + excludes: [] diff --git a/scripts/2.5/node_modules/is-callable/.jscs.json b/scripts/2.5/node_modules/is-callable/.jscs.json new file mode 100644 index 00000000..b4d9b8b4 --- /dev/null +++ b/scripts/2.5/node_modules/is-callable/.jscs.json @@ -0,0 +1,176 @@ +{ + "es3": true, + + "additionalRules": [], + + "requireSemicolons": true, + + "disallowMultipleSpaces": true, + + "disallowIdentifierNames": [], + + "requireCurlyBraces": { + "allExcept": [], + "keywords": ["if", "else", "for", "while", "do", "try", "catch"] + }, + + "requireSpaceAfterKeywords": ["if", "else", "for", "while", "do", "switch", "return", "try", "catch", "function"], + + "disallowSpaceAfterKeywords": [], + + "disallowSpaceBeforeComma": true, + "disallowSpaceAfterComma": false, + "disallowSpaceBeforeSemicolon": true, + + "disallowNodeTypes": [ + "DebuggerStatement", + "ForInStatement", + "LabeledStatement", + "SwitchCase", + "SwitchStatement", + "WithStatement" + ], + + "requireObjectKeysOnNewLine": { "allExcept": ["sameLine"] }, + + "requireSpacesInAnonymousFunctionExpression": { "beforeOpeningRoundBrace": true, "beforeOpeningCurlyBrace": true }, + "requireSpacesInNamedFunctionExpression": { "beforeOpeningCurlyBrace": true }, + "disallowSpacesInNamedFunctionExpression": { "beforeOpeningRoundBrace": true }, + "requireSpacesInFunctionDeclaration": { "beforeOpeningCurlyBrace": true }, + "disallowSpacesInFunctionDeclaration": { "beforeOpeningRoundBrace": true }, + + "requireSpaceBetweenArguments": true, + + "disallowSpacesInsideParentheses": true, + + "disallowSpacesInsideArrayBrackets": true, + + "disallowQuotedKeysInObjects": { "allExcept": ["reserved"] }, + + "disallowSpaceAfterObjectKeys": true, + + "requireCommaBeforeLineBreak": true, + + "disallowSpaceAfterPrefixUnaryOperators": ["++", "--", "+", "-", "~", "!"], + "requireSpaceAfterPrefixUnaryOperators": [], + + "disallowSpaceBeforePostfixUnaryOperators": ["++", "--"], + "requireSpaceBeforePostfixUnaryOperators": [], + + "disallowSpaceBeforeBinaryOperators": [], + "requireSpaceBeforeBinaryOperators": ["+", "-", "/", "*", "=", "==", "===", "!=", "!=="], + + "requireSpaceAfterBinaryOperators": ["+", "-", "/", "*", "=", "==", "===", "!=", "!=="], + "disallowSpaceAfterBinaryOperators": [], + + "disallowImplicitTypeConversion": ["binary", "string"], + + "disallowKeywords": ["with", "eval"], + + "requireKeywordsOnNewLine": [], + "disallowKeywordsOnNewLine": ["else"], + + "requireLineFeedAtFileEnd": true, + + "disallowTrailingWhitespace": true, + + "disallowTrailingComma": true, + + "excludeFiles": ["node_modules/**", "vendor/**"], + + "disallowMultipleLineStrings": true, + + "requireDotNotation": { "allExcept": ["keywords"] }, + + "requireParenthesesAroundIIFE": true, + + "validateLineBreaks": "LF", + + "validateQuoteMarks": { + "escape": true, + "mark": "'" + }, + + "disallowOperatorBeforeLineBreak": [], + + "requireSpaceBeforeKeywords": [ + "do", + "for", + "if", + "else", + "switch", + "case", + "try", + "catch", + "finally", + "while", + "with", + "return" + ], + + "validateAlignedFunctionParameters": { + "lineBreakAfterOpeningBraces": true, + "lineBreakBeforeClosingBraces": true + }, + + "requirePaddingNewLinesBeforeExport": true, + + "validateNewlineAfterArrayElements": { + "maximum": 1 + }, + + "requirePaddingNewLinesAfterUseStrict": true, + + "disallowArrowFunctions": true, + + "disallowMultiLineTernary": true, + + "validateOrderInObjectKeys": "asc-insensitive", + + "disallowIdenticalDestructuringNames": true, + + "disallowNestedTernaries": { "maxLevel": 1 }, + + "requireSpaceAfterComma": { "allExcept": ["trailing"] }, + "requireAlignedMultilineParams": false, + + "requireSpacesInGenerator": { + "afterStar": true + }, + + "disallowSpacesInGenerator": { + "beforeStar": true + }, + + "disallowVar": false, + + "requireArrayDestructuring": false, + + "requireEnhancedObjectLiterals": false, + + "requireObjectDestructuring": false, + + "requireEarlyReturn": false, + + "requireCapitalizedConstructorsNew": { + "allExcept": ["Function", "String", "Object", "Symbol", "Number", "Date", "RegExp", "Error", "Boolean", "Array"] + }, + + "requireImportAlphabetized": false, + + "requireSpaceBeforeObjectValues": true, + "requireSpaceBeforeDestructuredValues": true, + + "disallowSpacesInsideTemplateStringPlaceholders": true, + + "disallowArrayDestructuringReturn": false, + + "requireNewlineBeforeSingleStatementsInIf": false, + + "disallowUnusedVariables": true, + + "requireSpacesInsideImportedObjectBraces": true, + + "requireUseStrict": true +} + diff --git a/scripts/2.5/node_modules/is-callable/.travis.yml b/scripts/2.5/node_modules/is-callable/.travis.yml new file mode 100644 index 00000000..767256c8 --- /dev/null +++ b/scripts/2.5/node_modules/is-callable/.travis.yml @@ -0,0 +1,225 @@ +language: node_js +os: + - linux +node_js: + - "10.4" + - "9.11" + - "8.11" + - "7.10" + - "6.14" + - "5.12" + - "4.9" + - "iojs-v3.3" + - "iojs-v2.5" + - "iojs-v1.8" + - "0.12" + - "0.10" + - "0.8" +before_install: + - 'case "${TRAVIS_NODE_VERSION}" in 0.*) export NPM_CONFIG_STRICT_SSL=false ;; esac' + - 'nvm install-latest-npm' +install: + - 'if [ "${TRAVIS_NODE_VERSION}" = "0.6" ] || [ "${TRAVIS_NODE_VERSION}" = "0.9" ]; then nvm install --latest-npm 0.8 && npm install && nvm use "${TRAVIS_NODE_VERSION}"; else npm install; fi;' +script: + - 'if [ -n "${PRETEST-}" ]; then npm run pretest ; fi' + - 'if [ -n "${POSTTEST-}" ]; then npm run posttest ; fi' + - 'if [ -n "${COVERAGE-}" ]; then npm run coverage ; fi' + - 'if [ -n "${TEST-}" ]; then npm run tests-only ; fi' +sudo: false +env: + - TEST=true +matrix: + fast_finish: true + include: + - node_js: "lts/*" + env: PRETEST=true + - node_js: "lts/*" + env: POSTTEST=true + - node_js: "4" + env: COVERAGE=true + - node_js: "10.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.13" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.12" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v3.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v3.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v3.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.4" + env: TEST=true ALLOW_FAILURE=true + allow_failures: + - os: osx + - env: TEST=true ALLOW_FAILURE=true + - env: COVERAGE=true diff --git a/scripts/2.5/node_modules/is-callable/CHANGELOG.md b/scripts/2.5/node_modules/is-callable/CHANGELOG.md new file mode 100644 index 00000000..58286a05 --- /dev/null +++ b/scripts/2.5/node_modules/is-callable/CHANGELOG.md @@ -0,0 +1,56 @@ +1.1.4 / 2018-07-02 +================= + * [Fix] improve `class` and arrow function detection (#30, #31) + * [Tests] on all latest node minors; improve matrix + * [Dev Deps] update all dev deps + +1.1.3 / 2016-02-27 +================= + * [Fix] ensure “class “ doesn’t screw up “class” detection + * [Tests] up to `node` `v5.7`, `v4.3` + * [Dev Deps] update to `eslint` v2, `@ljharb/eslint-config`, `jscs` + +1.1.2 / 2016-01-15 +================= + * [Fix] Make sure comments don’t screw up “class” detection (#4) + * [Tests] up to `node` `v5.3` + * [Tests] Add `parallelshell`, run both `--es-staging` and stock tests at once + * [Dev Deps] update `tape`, `jscs`, `nsp`, `eslint`, `@ljharb/eslint-config` + * [Refactor] convert `isNonES6ClassFn` into `isES6ClassFn` + +1.1.1 / 2015-11-30 +================= + * [Fix] do not throw when a non-function has a function in its [[Prototype]] (#2) + * [Dev Deps] update `tape`, `eslint`, `@ljharb/eslint-config`, `jscs`, `nsp`, `semver` + * [Tests] up to `node` `v5.1` + * [Tests] no longer allow node 0.8 to fail. + * [Tests] fix npm upgrades in older nodes + +1.1.0 / 2015-10-02 +================= + * [Fix] Some browsers report TypedArray constructors as `typeof object` + * [New] return false for "class" constructors, when possible. + * [Tests] up to `io.js` `v3.3`, `node` `v4.1` + * [Dev Deps] update `eslint`, `editorconfig-tools`, `nsp`, `tape`, `semver`, `jscs`, `covert`, `make-arrow-function` + * [Docs] Switch from vb.teelaun.ch to versionbadg.es for the npm version badge SVG + +1.0.4 / 2015-01-30 +================= + * If @@toStringTag is not present, use the old-school Object#toString test. + +1.0.3 / 2015-01-29 +================= + * Add tests to ensure arrow functions are callable. + * Refactor to aid optimization of non-try/catch code. + +1.0.2 / 2015-01-29 +================= + * Fix broken package.json + +1.0.1 / 2015-01-29 +================= + * Add early exit for typeof not "function" + +1.0.0 / 2015-01-29 +================= + * Initial release. diff --git a/scripts/2.5/node_modules/is-callable/LICENSE b/scripts/2.5/node_modules/is-callable/LICENSE new file mode 100644 index 00000000..b43df444 --- /dev/null +++ b/scripts/2.5/node_modules/is-callable/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/scripts/2.5/node_modules/is-callable/Makefile b/scripts/2.5/node_modules/is-callable/Makefile new file mode 100644 index 00000000..b9e4fe1a --- /dev/null +++ b/scripts/2.5/node_modules/is-callable/Makefile @@ -0,0 +1,61 @@ +# Since we rely on paths relative to the makefile location, abort if make isn't being run from there. +$(if $(findstring /,$(MAKEFILE_LIST)),$(error Please only invoke this makefile from the directory it resides in)) + + # The files that need updating when incrementing the version number. +VERSIONED_FILES := *.js *.json README* + + +# Add the local npm packages' bin folder to the PATH, so that `make` can find them, when invoked directly. +# Note that rather than using `$(npm bin)` the 'node_modules/.bin' path component is hard-coded, so that invocation works even from an environment +# where npm is (temporarily) unavailable due to having deactivated an nvm instance loaded into the calling shell in order to avoid interference with tests. +export PATH := $(shell printf '%s' "$$PWD/node_modules/.bin:$$PATH") +UTILS := semver +# Make sure that all required utilities can be located. +UTIL_CHECK := $(or $(shell PATH="$(PATH)" which $(UTILS) >/dev/null && echo 'ok'),$(error Did you forget to run `npm install` after cloning the repo? At least one of the required supporting utilities not found: $(UTILS))) + +# Default target (by virtue of being the first non '.'-prefixed in the file). +.PHONY: _no-target-specified +_no-target-specified: + $(error Please specify the target to make - `make list` shows targets. Alternatively, use `npm test` to run the default tests; `npm run` shows all tests) + +# Lists all targets defined in this makefile. +.PHONY: list +list: + @$(MAKE) -pRrn : -f $(MAKEFILE_LIST) 2>/dev/null | awk -v RS= -F: '/^# File/,/^# Finished Make data base/ {if ($$1 !~ "^[#.]") {print $$1}}' | command grep -v -e '^[^[:alnum:]]' -e '^$@$$command ' | sort + +# All-tests target: invokes the specified test suites for ALL shells defined in $(SHELLS). +.PHONY: test +test: + @npm test + +.PHONY: _ensure-tag +_ensure-tag: +ifndef TAG + $(error Please invoke with `make TAG= release`, where is either an increment specifier (patch, minor, major, prepatch, preminor, premajor, prerelease), or an explicit major.minor.patch version number) +endif + +CHANGELOG_ERROR = $(error No CHANGELOG specified) +.PHONY: _ensure-changelog +_ensure-changelog: + @ (git status -sb --porcelain | command grep -E '^( M|[MA] ) CHANGELOG.md' > /dev/null) || (echo no CHANGELOG.md specified && exit 2) + +# Ensures that the git workspace is clean. +.PHONY: _ensure-clean +_ensure-clean: + @[ -z "$$((git status --porcelain --untracked-files=no || echo err) | command grep -v 'CHANGELOG.md')" ] || { echo "Workspace is not clean; please commit changes first." >&2; exit 2; } + +# Makes a release; invoke with `make TAG= release`. +.PHONY: release +release: _ensure-tag _ensure-changelog _ensure-clean + @old_ver=`git describe --abbrev=0 --tags --match 'v[0-9]*.[0-9]*.[0-9]*'` || { echo "Failed to determine current version." >&2; exit 1; }; old_ver=$${old_ver#v}; \ + new_ver=`echo "$(TAG)" | sed 's/^v//'`; new_ver=$${new_ver:-patch}; \ + if printf "$$new_ver" | command grep -q '^[0-9]'; then \ + semver "$$new_ver" >/dev/null || { echo 'Invalid version number specified: $(TAG) - must be major.minor.patch' >&2; exit 2; }; \ + semver -r "> $$old_ver" "$$new_ver" >/dev/null || { echo 'Invalid version number specified: $(TAG) - must be HIGHER than current one.' >&2; exit 2; } \ + else \ + new_ver=`semver -i "$$new_ver" "$$old_ver"` || { echo 'Invalid version-increment specifier: $(TAG)' >&2; exit 2; } \ + fi; \ + printf "=== Bumping version **$$old_ver** to **$$new_ver** before committing and tagging:\n=== TYPE 'proceed' TO PROCEED, anything else to abort: " && read response && [ "$$response" = 'proceed' ] || { echo 'Aborted.' >&2; exit 2; }; \ + replace "$$old_ver" "$$new_ver" -- $(VERSIONED_FILES) && \ + git commit -m "v$$new_ver" $(VERSIONED_FILES) CHANGELOG.md && \ + git tag -a -m "v$$new_ver" "v$$new_ver" diff --git a/scripts/2.5/node_modules/is-callable/README.md b/scripts/2.5/node_modules/is-callable/README.md new file mode 100644 index 00000000..0cb65879 --- /dev/null +++ b/scripts/2.5/node_modules/is-callable/README.md @@ -0,0 +1,59 @@ +# is-callable [![Version Badge][2]][1] + +[![Build Status][3]][4] +[![dependency status][5]][6] +[![dev dependency status][7]][8] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][11]][1] + +[![browser support][9]][10] + +Is this JS value callable? Works with Functions and GeneratorFunctions, despite ES6 @@toStringTag. + +## Example + +```js +var isCallable = require('is-callable'); +var assert = require('assert'); + +assert.notOk(isCallable(undefined)); +assert.notOk(isCallable(null)); +assert.notOk(isCallable(false)); +assert.notOk(isCallable(true)); +assert.notOk(isCallable([])); +assert.notOk(isCallable({})); +assert.notOk(isCallable(/a/g)); +assert.notOk(isCallable(new RegExp('a', 'g'))); +assert.notOk(isCallable(new Date())); +assert.notOk(isCallable(42)); +assert.notOk(isCallable(NaN)); +assert.notOk(isCallable(Infinity)); +assert.notOk(isCallable(new Number(42))); +assert.notOk(isCallable('foo')); +assert.notOk(isCallable(Object('foo'))); + +assert.ok(isCallable(function () {})); +assert.ok(isCallable(function* () {})); +assert.ok(isCallable(x => x * x)); +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[1]: https://npmjs.org/package/is-callable +[2]: http://versionbadg.es/ljharb/is-callable.svg +[3]: https://travis-ci.org/ljharb/is-callable.svg +[4]: https://travis-ci.org/ljharb/is-callable +[5]: https://david-dm.org/ljharb/is-callable.svg +[6]: https://david-dm.org/ljharb/is-callable +[7]: https://david-dm.org/ljharb/is-callable/dev-status.svg +[8]: https://david-dm.org/ljharb/is-callable#info=devDependencies +[9]: https://ci.testling.com/ljharb/is-callable.png +[10]: https://ci.testling.com/ljharb/is-callable +[11]: https://nodei.co/npm/is-callable.png?downloads=true&stars=true +[license-image]: http://img.shields.io/npm/l/is-callable.svg +[license-url]: LICENSE +[downloads-image]: http://img.shields.io/npm/dm/is-callable.svg +[downloads-url]: http://npm-stat.com/charts.html?package=is-callable diff --git a/scripts/2.5/node_modules/is-callable/index.js b/scripts/2.5/node_modules/is-callable/index.js new file mode 100644 index 00000000..d9820b51 --- /dev/null +++ b/scripts/2.5/node_modules/is-callable/index.js @@ -0,0 +1,37 @@ +'use strict'; + +var fnToStr = Function.prototype.toString; + +var constructorRegex = /^\s*class\b/; +var isES6ClassFn = function isES6ClassFunction(value) { + try { + var fnStr = fnToStr.call(value); + return constructorRegex.test(fnStr); + } catch (e) { + return false; // not a function + } +}; + +var tryFunctionObject = function tryFunctionToStr(value) { + try { + if (isES6ClassFn(value)) { return false; } + fnToStr.call(value); + return true; + } catch (e) { + return false; + } +}; +var toStr = Object.prototype.toString; +var fnClass = '[object Function]'; +var genClass = '[object GeneratorFunction]'; +var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol'; + +module.exports = function isCallable(value) { + if (!value) { return false; } + if (typeof value !== 'function' && typeof value !== 'object') { return false; } + if (typeof value === 'function' && !value.prototype) { return true; } + if (hasToStringTag) { return tryFunctionObject(value); } + if (isES6ClassFn(value)) { return false; } + var strClass = toStr.call(value); + return strClass === fnClass || strClass === genClass; +}; diff --git a/scripts/2.5/node_modules/is-callable/package.json b/scripts/2.5/node_modules/is-callable/package.json new file mode 100644 index 00000000..3ef5dc5d --- /dev/null +++ b/scripts/2.5/node_modules/is-callable/package.json @@ -0,0 +1,124 @@ +{ + "_from": "is-callable@^1.1.4", + "_id": "is-callable@1.1.4", + "_inBundle": false, + "_integrity": "sha512-r5p9sxJjYnArLjObpjA4xu5EKI3CuKHkJXMhT7kwbpUyIFD1n5PMAsoPvWnvtZiNz7LjkYDRZhd7FlI0eMijEA==", + "_location": "/is-callable", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "is-callable@^1.1.4", + "name": "is-callable", + "escapedName": "is-callable", + "rawSpec": "^1.1.4", + "saveSpec": null, + "fetchSpec": "^1.1.4" + }, + "_requiredBy": [ + "/es-abstract", + "/es-to-primitive" + ], + "_resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.1.4.tgz", + "_shasum": "1e1adf219e1eeb684d691f9d6a05ff0d30a24d75", + "_spec": "is-callable@^1.1.4", + "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/2.5/node_modules/es-abstract", + "author": { + "name": "Jordan Harband", + "email": "ljharb@gmail.com", + "url": "http://ljharb.codes" + }, + "bugs": { + "url": "https://github.com/ljharb/is-callable/issues" + }, + "bundleDependencies": false, + "contributors": [ + { + "name": "Jordan Harband", + "email": "ljharb@gmail.com", + "url": "http://ljharb.codes" + } + ], + "dependencies": {}, + "deprecated": false, + "description": "Is this JS value callable? Works with Functions and GeneratorFunctions, despite ES6 @@toStringTag.", + "devDependencies": { + "@ljharb/eslint-config": "^12.2.1", + "covert": "^1.1.0", + "editorconfig-tools": "^0.1.1", + "eslint": "^4.19.1", + "foreach": "^2.0.5", + "istanbul": "1.1.0-alpha.1", + "istanbul-merge": "^1.1.1", + "jscs": "^3.0.7", + "make-arrow-function": "^1.1.0", + "make-generator-function": "^1.1.0", + "nsp": "^3.2.1", + "rimraf": "^2.6.2", + "semver": "^5.5.0", + "tape": "^4.9.1" + }, + "engines": { + "node": ">= 0.4" + }, + "homepage": "https://github.com/ljharb/is-callable#readme", + "keywords": [ + "Function", + "function", + "callable", + "generator", + "generator function", + "arrow", + "arrow function", + "ES6", + "toStringTag", + "@@toStringTag" + ], + "license": "MIT", + "main": "index.js", + "name": "is-callable", + "repository": { + "type": "git", + "url": "git://github.com/ljharb/is-callable.git" + }, + "scripts": { + "coverage": "npm run --silent istanbul", + "covert": "covert test.js", + "covert:quiet": "covert test.js --quiet", + "eslint": "eslint *.js", + "istanbul": "npm run --silent istanbul:clean && npm run --silent istanbul:std && npm run --silent istanbul:harmony && npm run --silent istanbul:merge && istanbul check", + "istanbul:clean": "rimraf coverage coverage-std coverage-harmony", + "istanbul:harmony": "node --harmony ./node_modules/istanbul/lib/cli.js cover test.js --dir coverage-harmony", + "istanbul:merge": "istanbul-merge --out coverage/coverage.raw.json coverage-harmony/coverage.raw.json coverage-std/coverage.raw.json && istanbul report html", + "istanbul:std": "istanbul cover test.js --report html --dir coverage-std", + "jscs": "jscs *.js", + "lint": "npm run jscs && npm run eslint", + "posttest": "npm run --silent security", + "prelint": "editorconfig-tools check *", + "pretest": "npm run --silent lint", + "security": "nsp check", + "test": "npm run --silent tests-only", + "test:staging": "node --es-staging test.js", + "test:stock": "node test.js", + "tests-only": "npm run --silent test:stock && npm run --silent test:staging" + }, + "testling": { + "files": "test.js", + "browsers": [ + "iexplore/6.0..latest", + "firefox/3.0..6.0", + "firefox/15.0..latest", + "firefox/nightly", + "chrome/4.0..10.0", + "chrome/20.0..latest", + "chrome/canary", + "opera/10.0..latest", + "opera/next", + "safari/4.0..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2" + ] + }, + "version": "1.1.4" +} diff --git a/scripts/2.5/node_modules/is-callable/test.js b/scripts/2.5/node_modules/is-callable/test.js new file mode 100644 index 00000000..f5be51d8 --- /dev/null +++ b/scripts/2.5/node_modules/is-callable/test.js @@ -0,0 +1,158 @@ +'use strict'; + +/* eslint no-magic-numbers: 1 */ + +var test = require('tape'); +var isCallable = require('./'); +var hasSymbols = typeof Symbol === 'function' && typeof Symbol('foo') === 'symbol'; +var genFn = require('make-generator-function'); +var arrowFn = require('make-arrow-function')(); +var weirdlyCommentedArrowFn; +var asyncFn; +var asyncArrowFn; +try { + /* eslint no-new-func: 0 */ + weirdlyCommentedArrowFn = Function('return cl/*/**/=>/**/ass - 1;')(); + asyncFn = Function('return async function foo() {};')(); + asyncArrowFn = Function('return async () => {};')(); +} catch (e) { /**/ } +var forEach = require('foreach'); + +var noop = function () {}; +var classFake = function classFake() { }; // eslint-disable-line func-name-matching +var returnClass = function () { return ' class '; }; +var return3 = function () { return 3; }; +/* for coverage */ +noop(); +classFake(); +returnClass(); +return3(); +/* end for coverage */ + +var invokeFunction = function invokeFunctionString(str) { + var result; + try { + /* eslint-disable no-new-func */ + var fn = Function(str); + /* eslint-enable no-new-func */ + result = fn(); + } catch (e) {} + return result; +}; + +var classConstructor = invokeFunction('"use strict"; return class Foo {}'); + +var commentedClass = invokeFunction('"use strict"; return class/*kkk*/\n//blah\n Bar\n//blah\n {}'); +var commentedClassOneLine = invokeFunction('"use strict"; return class/**/A{}'); +var classAnonymous = invokeFunction('"use strict"; return class{}'); +var classAnonymousCommentedOneLine = invokeFunction('"use strict"; return class/*/*/{}'); + +test('not callables', function (t) { + t.test('non-number/string primitives', function (st) { + st.notOk(isCallable(), 'undefined is not callable'); + st.notOk(isCallable(null), 'null is not callable'); + st.notOk(isCallable(false), 'false is not callable'); + st.notOk(isCallable(true), 'true is not callable'); + st.end(); + }); + + t.notOk(isCallable([]), 'array is not callable'); + t.notOk(isCallable({}), 'object is not callable'); + t.notOk(isCallable(/a/g), 'regex literal is not callable'); + t.notOk(isCallable(new RegExp('a', 'g')), 'regex object is not callable'); + t.notOk(isCallable(new Date()), 'new Date() is not callable'); + + t.test('numbers', function (st) { + st.notOk(isCallable(42), 'number is not callable'); + st.notOk(isCallable(Object(42)), 'number object is not callable'); + st.notOk(isCallable(NaN), 'NaN is not callable'); + st.notOk(isCallable(Infinity), 'Infinity is not callable'); + st.end(); + }); + + t.test('strings', function (st) { + st.notOk(isCallable('foo'), 'string primitive is not callable'); + st.notOk(isCallable(Object('foo')), 'string object is not callable'); + st.end(); + }); + + t.test('non-function with function in its [[Prototype]] chain', function (st) { + var Foo = function Bar() {}; + Foo.prototype = noop; + st.equal(true, isCallable(Foo), 'sanity check: Foo is callable'); + st.equal(false, isCallable(new Foo()), 'instance of Foo is not callable'); + st.end(); + }); + + t.end(); +}); + +test('@@toStringTag', { skip: !hasSymbols || !Symbol.toStringTag }, function (t) { + var fakeFunction = { + toString: function () { return String(return3); }, + valueOf: return3 + }; + fakeFunction[Symbol.toStringTag] = 'Function'; + t.equal(String(fakeFunction), String(return3)); + t.equal(Number(fakeFunction), return3()); + t.notOk(isCallable(fakeFunction), 'fake Function with @@toStringTag "Function" is not callable'); + t.end(); +}); + +var typedArrayNames = [ + 'Int8Array', + 'Uint8Array', + 'Uint8ClampedArray', + 'Int16Array', + 'Uint16Array', + 'Int32Array', + 'Uint32Array', + 'Float32Array', + 'Float64Array' +]; + +test('Functions', function (t) { + t.ok(isCallable(noop), 'function is callable'); + t.ok(isCallable(classFake), 'function with name containing "class" is callable'); + t.ok(isCallable(returnClass), 'function with string " class " is callable'); + t.ok(isCallable(isCallable), 'isCallable is callable'); + t.end(); +}); + +test('Typed Arrays', function (st) { + forEach(typedArrayNames, function (typedArray) { + /* istanbul ignore if : covered in node 0.6 */ + if (typeof global[typedArray] === 'undefined') { + st.comment('# SKIP typed array "' + typedArray + '" not supported'); + } else { + st.ok(isCallable(global[typedArray]), typedArray + ' is callable'); + } + }); + st.end(); +}); + +test('Generators', { skip: !genFn }, function (t) { + t.ok(isCallable(genFn), 'generator function is callable'); + t.end(); +}); + +test('Arrow functions', { skip: !arrowFn }, function (t) { + t.ok(isCallable(arrowFn), 'arrow function is callable'); + t.ok(isCallable(weirdlyCommentedArrowFn), 'weirdly commented arrow functions are callable'); + t.end(); +}); + +test('"Class" constructors', { skip: !classConstructor || !commentedClass || !commentedClassOneLine || !classAnonymous }, function (t) { + t.notOk(isCallable(classConstructor), 'class constructors are not callable'); + t.notOk(isCallable(commentedClass), 'class constructors with comments in the signature are not callable'); + t.notOk(isCallable(commentedClassOneLine), 'one-line class constructors with comments in the signature are not callable'); + t.notOk(isCallable(classAnonymous), 'anonymous class constructors are not callable'); + t.notOk(isCallable(classAnonymousCommentedOneLine), 'anonymous one-line class constructors with comments in the signature are not callable'); + t.end(); +}); + +test('`async function`s', { skip: !asyncFn }, function (t) { + t.ok(isCallable(asyncFn), '`async function`s are callable'); + t.ok(isCallable(asyncArrowFn), '`async` arrow functions are callable'); + t.end(); +}); diff --git a/scripts/2.5/node_modules/is-date-object/.eslintrc b/scripts/2.5/node_modules/is-date-object/.eslintrc new file mode 100644 index 00000000..1228f975 --- /dev/null +++ b/scripts/2.5/node_modules/is-date-object/.eslintrc @@ -0,0 +1,9 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "max-statements": [2, 12] + } +} diff --git a/scripts/2.5/node_modules/is-date-object/.jscs.json b/scripts/2.5/node_modules/is-date-object/.jscs.json new file mode 100644 index 00000000..040bb680 --- /dev/null +++ b/scripts/2.5/node_modules/is-date-object/.jscs.json @@ -0,0 +1,122 @@ +{ + "es3": true, + + "additionalRules": [], + + "requireSemicolons": true, + + "disallowMultipleSpaces": true, + + "disallowIdentifierNames": [], + + "requireCurlyBraces": ["if", "else", "for", "while", "do", "try", "catch"], + + "requireSpaceAfterKeywords": ["if", "else", "for", "while", "do", "switch", "return", "try", "catch", "function"], + + "disallowSpaceAfterKeywords": [], + + "disallowSpaceBeforeComma": true, + "disallowSpaceBeforeSemicolon": true, + + "disallowNodeTypes": [ + "DebuggerStatement", + "ForInStatement", + "LabeledStatement", + "SwitchCase", + "SwitchStatement", + "WithStatement" + ], + + "requireSpacesInAnonymousFunctionExpression": { "beforeOpeningRoundBrace": true, "beforeOpeningCurlyBrace": true }, + "requireSpacesInNamedFunctionExpression": { "beforeOpeningCurlyBrace": true }, + "disallowSpacesInNamedFunctionExpression": { "beforeOpeningRoundBrace": true }, + "requireSpacesInFunctionDeclaration": { "beforeOpeningCurlyBrace": true }, + "disallowSpacesInFunctionDeclaration": { "beforeOpeningRoundBrace": true }, + + "requireSpaceBetweenArguments": true, + + "disallowSpacesInsideParentheses": true, + + "disallowSpacesInsideArrayBrackets": true, + + "disallowQuotedKeysInObjects": "allButReserved", + + "disallowSpaceAfterObjectKeys": true, + + "requireCommaBeforeLineBreak": true, + + "disallowSpaceAfterPrefixUnaryOperators": ["++", "--", "+", "-", "~", "!"], + "requireSpaceAfterPrefixUnaryOperators": [], + + "disallowSpaceBeforePostfixUnaryOperators": ["++", "--"], + "requireSpaceBeforePostfixUnaryOperators": [], + + "disallowSpaceBeforeBinaryOperators": [], + "requireSpaceBeforeBinaryOperators": ["+", "-", "/", "*", "=", "==", "===", "!=", "!=="], + + "requireSpaceAfterBinaryOperators": ["+", "-", "/", "*", "=", "==", "===", "!=", "!=="], + "disallowSpaceAfterBinaryOperators": [], + + "disallowImplicitTypeConversion": ["binary", "string"], + + "disallowKeywords": ["with", "eval"], + + "requireKeywordsOnNewLine": [], + "disallowKeywordsOnNewLine": ["else"], + + "requireLineFeedAtFileEnd": true, + + "disallowTrailingWhitespace": true, + + "disallowTrailingComma": true, + + "excludeFiles": ["node_modules/**", "vendor/**"], + + "disallowMultipleLineStrings": true, + + "requireDotNotation": true, + + "requireParenthesesAroundIIFE": true, + + "validateLineBreaks": "LF", + + "validateQuoteMarks": { + "escape": true, + "mark": "'" + }, + + "disallowOperatorBeforeLineBreak": [], + + "requireSpaceBeforeKeywords": [ + "do", + "for", + "if", + "else", + "switch", + "case", + "try", + "catch", + "finally", + "while", + "with", + "return" + ], + + "validateAlignedFunctionParameters": { + "lineBreakAfterOpeningBraces": true, + "lineBreakBeforeClosingBraces": true + }, + + "requirePaddingNewLinesBeforeExport": true, + + "validateNewlineAfterArrayElements": { + "maximum": 1 + }, + + "requirePaddingNewLinesAfterUseStrict": true, + + "disallowArrowFunctions": true, + + "validateOrderInObjectKeys": "asc-insensitive" +} + diff --git a/scripts/2.5/node_modules/is-date-object/.npmignore b/scripts/2.5/node_modules/is-date-object/.npmignore new file mode 100644 index 00000000..59d842ba --- /dev/null +++ b/scripts/2.5/node_modules/is-date-object/.npmignore @@ -0,0 +1,28 @@ +# Logs +logs +*.log + +# Runtime data +pids +*.pid +*.seed + +# Directory for instrumented libs generated by jscoverage/JSCover +lib-cov + +# Coverage directory used by tools like istanbul +coverage + +# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) +.grunt + +# Compiled binary addons (http://nodejs.org/api/addons.html) +build/Release + +# Dependency directory +# Commenting this out is preferred by some people, see +# https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git- +node_modules + +# Users Environment Variables +.lock-wscript diff --git a/scripts/2.5/node_modules/is-date-object/.travis.yml b/scripts/2.5/node_modules/is-date-object/.travis.yml new file mode 100644 index 00000000..4c29ed58 --- /dev/null +++ b/scripts/2.5/node_modules/is-date-object/.travis.yml @@ -0,0 +1,58 @@ +language: node_js +node_js: + - "4.1" + - "4.0" + - "iojs-v3.3" + - "iojs-v3.2" + - "iojs-v3.1" + - "iojs-v3.0" + - "iojs-v2.5" + - "iojs-v2.4" + - "iojs-v2.3" + - "iojs-v2.2" + - "iojs-v2.1" + - "iojs-v2.0" + - "iojs-v1.8" + - "iojs-v1.7" + - "iojs-v1.6" + - "iojs-v1.5" + - "iojs-v1.4" + - "iojs-v1.3" + - "iojs-v1.2" + - "iojs-v1.1" + - "iojs-v1.0" + - "0.12" + - "0.11" + - "0.10" + - "0.9" + - "0.8" + - "0.6" + - "0.4" +before_install: + - '[ "${TRAVIS_NODE_VERSION}" = "0.6" ] || npm install -g npm@1.4.28 && npm install -g npm' +sudo: false +matrix: + fast_finish: true + allow_failures: + - node_js: "4.0" + - node_js: "iojs-v3.2" + - node_js: "iojs-v3.1" + - node_js: "iojs-v3.0" + - node_js: "iojs-v2.4" + - node_js: "iojs-v2.3" + - node_js: "iojs-v2.2" + - node_js: "iojs-v2.1" + - node_js: "iojs-v2.0" + - node_js: "iojs-v1.7" + - node_js: "iojs-v1.6" + - node_js: "iojs-v1.5" + - node_js: "iojs-v1.4" + - node_js: "iojs-v1.3" + - node_js: "iojs-v1.2" + - node_js: "iojs-v1.1" + - node_js: "iojs-v1.0" + - node_js: "0.11" + - node_js: "0.9" + - node_js: "0.8" + - node_js: "0.6" + - node_js: "0.4" diff --git a/scripts/2.5/node_modules/is-date-object/CHANGELOG.md b/scripts/2.5/node_modules/is-date-object/CHANGELOG.md new file mode 100644 index 00000000..4a7eab61 --- /dev/null +++ b/scripts/2.5/node_modules/is-date-object/CHANGELOG.md @@ -0,0 +1,10 @@ +1.0.1 / 2015-09-27 +================= + * [Fix] If `@@toStringTag` is not present, use the old-school `Object#toString` test + * [Docs] Switch from vb.teelaun.ch to versionbadg.es for the npm version badge SVG + * [Dev Deps] update `is`, `eslint`, `@ljharb/eslint-config`, `semver`, `tape`, `jscs`, `nsp`, `covert` + * [Tests] up to `io.js` `v3.3`, `node` `v4.1` + +1.0.0 / 2015-01-28 +================= + * Initial release. diff --git a/scripts/2.5/node_modules/is-date-object/LICENSE b/scripts/2.5/node_modules/is-date-object/LICENSE new file mode 100644 index 00000000..b43df444 --- /dev/null +++ b/scripts/2.5/node_modules/is-date-object/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/scripts/2.5/node_modules/is-date-object/Makefile b/scripts/2.5/node_modules/is-date-object/Makefile new file mode 100644 index 00000000..b9e4fe1a --- /dev/null +++ b/scripts/2.5/node_modules/is-date-object/Makefile @@ -0,0 +1,61 @@ +# Since we rely on paths relative to the makefile location, abort if make isn't being run from there. +$(if $(findstring /,$(MAKEFILE_LIST)),$(error Please only invoke this makefile from the directory it resides in)) + + # The files that need updating when incrementing the version number. +VERSIONED_FILES := *.js *.json README* + + +# Add the local npm packages' bin folder to the PATH, so that `make` can find them, when invoked directly. +# Note that rather than using `$(npm bin)` the 'node_modules/.bin' path component is hard-coded, so that invocation works even from an environment +# where npm is (temporarily) unavailable due to having deactivated an nvm instance loaded into the calling shell in order to avoid interference with tests. +export PATH := $(shell printf '%s' "$$PWD/node_modules/.bin:$$PATH") +UTILS := semver +# Make sure that all required utilities can be located. +UTIL_CHECK := $(or $(shell PATH="$(PATH)" which $(UTILS) >/dev/null && echo 'ok'),$(error Did you forget to run `npm install` after cloning the repo? At least one of the required supporting utilities not found: $(UTILS))) + +# Default target (by virtue of being the first non '.'-prefixed in the file). +.PHONY: _no-target-specified +_no-target-specified: + $(error Please specify the target to make - `make list` shows targets. Alternatively, use `npm test` to run the default tests; `npm run` shows all tests) + +# Lists all targets defined in this makefile. +.PHONY: list +list: + @$(MAKE) -pRrn : -f $(MAKEFILE_LIST) 2>/dev/null | awk -v RS= -F: '/^# File/,/^# Finished Make data base/ {if ($$1 !~ "^[#.]") {print $$1}}' | command grep -v -e '^[^[:alnum:]]' -e '^$@$$command ' | sort + +# All-tests target: invokes the specified test suites for ALL shells defined in $(SHELLS). +.PHONY: test +test: + @npm test + +.PHONY: _ensure-tag +_ensure-tag: +ifndef TAG + $(error Please invoke with `make TAG= release`, where is either an increment specifier (patch, minor, major, prepatch, preminor, premajor, prerelease), or an explicit major.minor.patch version number) +endif + +CHANGELOG_ERROR = $(error No CHANGELOG specified) +.PHONY: _ensure-changelog +_ensure-changelog: + @ (git status -sb --porcelain | command grep -E '^( M|[MA] ) CHANGELOG.md' > /dev/null) || (echo no CHANGELOG.md specified && exit 2) + +# Ensures that the git workspace is clean. +.PHONY: _ensure-clean +_ensure-clean: + @[ -z "$$((git status --porcelain --untracked-files=no || echo err) | command grep -v 'CHANGELOG.md')" ] || { echo "Workspace is not clean; please commit changes first." >&2; exit 2; } + +# Makes a release; invoke with `make TAG= release`. +.PHONY: release +release: _ensure-tag _ensure-changelog _ensure-clean + @old_ver=`git describe --abbrev=0 --tags --match 'v[0-9]*.[0-9]*.[0-9]*'` || { echo "Failed to determine current version." >&2; exit 1; }; old_ver=$${old_ver#v}; \ + new_ver=`echo "$(TAG)" | sed 's/^v//'`; new_ver=$${new_ver:-patch}; \ + if printf "$$new_ver" | command grep -q '^[0-9]'; then \ + semver "$$new_ver" >/dev/null || { echo 'Invalid version number specified: $(TAG) - must be major.minor.patch' >&2; exit 2; }; \ + semver -r "> $$old_ver" "$$new_ver" >/dev/null || { echo 'Invalid version number specified: $(TAG) - must be HIGHER than current one.' >&2; exit 2; } \ + else \ + new_ver=`semver -i "$$new_ver" "$$old_ver"` || { echo 'Invalid version-increment specifier: $(TAG)' >&2; exit 2; } \ + fi; \ + printf "=== Bumping version **$$old_ver** to **$$new_ver** before committing and tagging:\n=== TYPE 'proceed' TO PROCEED, anything else to abort: " && read response && [ "$$response" = 'proceed' ] || { echo 'Aborted.' >&2; exit 2; }; \ + replace "$$old_ver" "$$new_ver" -- $(VERSIONED_FILES) && \ + git commit -m "v$$new_ver" $(VERSIONED_FILES) CHANGELOG.md && \ + git tag -a -m "v$$new_ver" "v$$new_ver" diff --git a/scripts/2.5/node_modules/is-date-object/README.md b/scripts/2.5/node_modules/is-date-object/README.md new file mode 100644 index 00000000..55b0c596 --- /dev/null +++ b/scripts/2.5/node_modules/is-date-object/README.md @@ -0,0 +1,53 @@ +# is-date-object [![Version Badge][2]][1] + +[![Build Status][3]][4] +[![dependency status][5]][6] +[![dev dependency status][7]][8] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][11]][1] + +[![browser support][9]][10] + +Is this value a JS Date object? This module works cross-realm/iframe, and despite ES6 @@toStringTag. + +## Example + +```js +var isDate = require('is-date-object'); +var assert = require('assert'); + +assert.notOk(isDate(undefined)); +assert.notOk(isDate(null)); +assert.notOk(isDate(false)); +assert.notOk(isDate(true)); +assert.notOk(isDate(42)); +assert.notOk(isDate('foo')); +assert.notOk(isDate(function () {})); +assert.notOk(isDate([])); +assert.notOk(isDate({})); +assert.notOk(isDate(/a/g)); +assert.notOk(isDate(new RegExp('a', 'g'))); + +assert.ok(isDate(new Date())); +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[1]: https://npmjs.org/package/is-date-object +[2]: http://versionbadg.es/ljharb/is-date-object.svg +[3]: https://travis-ci.org/ljharb/is-date-object.svg +[4]: https://travis-ci.org/ljharb/is-date-object +[5]: https://david-dm.org/ljharb/is-date-object.svg +[6]: https://david-dm.org/ljharb/is-date-object +[7]: https://david-dm.org/ljharb/is-date-object/dev-status.svg +[8]: https://david-dm.org/ljharb/is-date-object#info=devDependencies +[9]: https://ci.testling.com/ljharb/is-date-object.png +[10]: https://ci.testling.com/ljharb/is-date-object +[11]: https://nodei.co/npm/is-date-object.png?downloads=true&stars=true +[license-image]: http://img.shields.io/npm/l/is-date-object.svg +[license-url]: LICENSE +[downloads-image]: http://img.shields.io/npm/dm/is-date-object.svg +[downloads-url]: http://npm-stat.com/charts.html?package=is-date-object diff --git a/scripts/2.5/node_modules/is-date-object/index.js b/scripts/2.5/node_modules/is-date-object/index.js new file mode 100644 index 00000000..fe0d7ecd --- /dev/null +++ b/scripts/2.5/node_modules/is-date-object/index.js @@ -0,0 +1,20 @@ +'use strict'; + +var getDay = Date.prototype.getDay; +var tryDateObject = function tryDateObject(value) { + try { + getDay.call(value); + return true; + } catch (e) { + return false; + } +}; + +var toStr = Object.prototype.toString; +var dateClass = '[object Date]'; +var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol'; + +module.exports = function isDateObject(value) { + if (typeof value !== 'object' || value === null) { return false; } + return hasToStringTag ? tryDateObject(value) : toStr.call(value) === dateClass; +}; diff --git a/scripts/2.5/node_modules/is-date-object/package.json b/scripts/2.5/node_modules/is-date-object/package.json new file mode 100644 index 00000000..f4e8b3cc --- /dev/null +++ b/scripts/2.5/node_modules/is-date-object/package.json @@ -0,0 +1,93 @@ +{ + "_from": "is-date-object@^1.0.1", + "_id": "is-date-object@1.0.1", + "_inBundle": false, + "_integrity": "sha1-mqIOtq7rv/d/vTPnTKAbM1gdOhY=", + "_location": "/is-date-object", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "is-date-object@^1.0.1", + "name": "is-date-object", + "escapedName": "is-date-object", + "rawSpec": "^1.0.1", + "saveSpec": null, + "fetchSpec": "^1.0.1" + }, + "_requiredBy": [ + "/es-to-primitive" + ], + "_resolved": "https://registry.npmjs.org/is-date-object/-/is-date-object-1.0.1.tgz", + "_shasum": "9aa20eb6aeebbff77fbd33e74ca01b33581d3a16", + "_spec": "is-date-object@^1.0.1", + "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/2.5/node_modules/es-to-primitive", + "author": { + "name": "Jordan Harband" + }, + "bugs": { + "url": "https://github.com/ljharb/is-date-object/issues" + }, + "bundleDependencies": false, + "dependencies": {}, + "deprecated": false, + "description": "Is this value a JS Date object? This module works cross-realm/iframe, and despite ES6 @@toStringTag.", + "devDependencies": { + "@ljharb/eslint-config": "^1.2.0", + "covert": "^1.1.0", + "eslint": "^1.5.1", + "foreach": "^2.0.5", + "indexof": "^0.0.1", + "is": "^3.1.0", + "jscs": "^2.1.1", + "nsp": "^1.1.0", + "semver": "^5.0.3", + "tape": "^4.2.0" + }, + "engines": { + "node": ">= 0.4" + }, + "homepage": "https://github.com/ljharb/is-date-object#readme", + "keywords": [ + "Date", + "ES6", + "toStringTag", + "@@toStringTag", + "Date object" + ], + "license": "MIT", + "main": "index.js", + "name": "is-date-object", + "repository": { + "type": "git", + "url": "git://github.com/ljharb/is-date-object.git" + }, + "scripts": { + "coverage": "covert test.js", + "coverage-quiet": "covert test.js --quiet", + "eslint": "eslint test.js *.js", + "jscs": "jscs test.js *.js", + "lint": "npm run jscs && npm run eslint", + "security": "nsp package", + "test": "npm run lint && node --harmony --es-staging test.js && npm run security" + }, + "testling": { + "files": "test.js", + "browsers": [ + "iexplore/6.0..latest", + "firefox/3.0..6.0", + "firefox/15.0..latest", + "firefox/nightly", + "chrome/4.0..10.0", + "chrome/20.0..latest", + "chrome/canary", + "opera/10.0..latest", + "opera/next", + "safari/4.0..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2" + ] + }, + "version": "1.0.1" +} diff --git a/scripts/2.5/node_modules/is-date-object/test.js b/scripts/2.5/node_modules/is-date-object/test.js new file mode 100644 index 00000000..29f0917b --- /dev/null +++ b/scripts/2.5/node_modules/is-date-object/test.js @@ -0,0 +1,33 @@ +'use strict'; + +var test = require('tape'); +var isDate = require('./'); +var hasSymbols = typeof Symbol === 'function' && typeof Symbol() === 'symbol'; + +test('not Dates', function (t) { + t.notOk(isDate(), 'undefined is not Date'); + t.notOk(isDate(null), 'null is not Date'); + t.notOk(isDate(false), 'false is not Date'); + t.notOk(isDate(true), 'true is not Date'); + t.notOk(isDate(42), 'number is not Date'); + t.notOk(isDate('foo'), 'string is not Date'); + t.notOk(isDate([]), 'array is not Date'); + t.notOk(isDate({}), 'object is not Date'); + t.notOk(isDate(function () {}), 'function is not Date'); + t.notOk(isDate(/a/g), 'regex literal is not Date'); + t.notOk(isDate(new RegExp('a', 'g')), 'regex object is not Date'); + t.end(); +}); + +test('@@toStringTag', { skip: !hasSymbols || !Symbol.toStringTag }, function (t) { + var realDate = new Date(); + var fakeDate = { toString: function () { return String(realDate); }, valueOf: function () { return realDate.getTime(); } }; + fakeDate[Symbol.toStringTag] = 'Date'; + t.notOk(isDate(fakeDate), 'fake Date with @@toStringTag "Date" is not Date'); + t.end(); +}); + +test('Dates', function (t) { + t.ok(isDate(new Date()), 'new Date() is Date'); + t.end(); +}); diff --git a/scripts/2.5/node_modules/is-generator-function/.editorconfig b/scripts/2.5/node_modules/is-generator-function/.editorconfig new file mode 100644 index 00000000..ac29adef --- /dev/null +++ b/scripts/2.5/node_modules/is-generator-function/.editorconfig @@ -0,0 +1,20 @@ +root = true + +[*] +indent_style = tab +indent_size = 4 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true +max_line_length = 120 + +[CHANGELOG.md] +indent_style = space +indent_size = 2 + +[*.json] +max_line_length = off + +[Makefile] +max_line_length = off diff --git a/scripts/2.5/node_modules/is-generator-function/.eslintrc b/scripts/2.5/node_modules/is-generator-function/.eslintrc new file mode 100644 index 00000000..484e4d71 --- /dev/null +++ b/scripts/2.5/node_modules/is-generator-function/.eslintrc @@ -0,0 +1,9 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "no-new-func": [1] + } +} diff --git a/scripts/2.5/node_modules/is-generator-function/.jscs.json b/scripts/2.5/node_modules/is-generator-function/.jscs.json new file mode 100644 index 00000000..c62f2c19 --- /dev/null +++ b/scripts/2.5/node_modules/is-generator-function/.jscs.json @@ -0,0 +1,176 @@ +{ + "es3": true, + + "additionalRules": [], + + "requireSemicolons": true, + + "disallowMultipleSpaces": true, + + "disallowIdentifierNames": [], + + "requireCurlyBraces": { + "allExcept": [], + "keywords": ["if", "else", "for", "while", "do", "try", "catch"] + }, + + "requireSpaceAfterKeywords": ["if", "else", "for", "while", "do", "switch", "return", "try", "catch", "function"], + + "disallowSpaceAfterKeywords": [], + + "disallowSpaceBeforeComma": true, + "disallowSpaceAfterComma": false, + "disallowSpaceBeforeSemicolon": true, + + "disallowNodeTypes": [ + "DebuggerStatement", + "ForInStatement", + "LabeledStatement", + "SwitchCase", + "SwitchStatement", + "WithStatement" + ], + + "requireObjectKeysOnNewLine": { "allExcept": ["sameLine"] }, + + "requireSpacesInAnonymousFunctionExpression": { "beforeOpeningRoundBrace": true, "beforeOpeningCurlyBrace": true }, + "requireSpacesInNamedFunctionExpression": { "beforeOpeningCurlyBrace": true }, + "disallowSpacesInNamedFunctionExpression": { "beforeOpeningRoundBrace": true }, + "requireSpacesInFunctionDeclaration": { "beforeOpeningCurlyBrace": true }, + "disallowSpacesInFunctionDeclaration": { "beforeOpeningRoundBrace": true }, + + "requireSpaceBetweenArguments": true, + + "disallowSpacesInsideParentheses": true, + + "disallowSpacesInsideArrayBrackets": true, + + "disallowQuotedKeysInObjects": { "allExcept": ["reserved"] }, + + "disallowSpaceAfterObjectKeys": true, + + "requireCommaBeforeLineBreak": true, + + "disallowSpaceAfterPrefixUnaryOperators": ["++", "--", "+", "-", "~", "!"], + "requireSpaceAfterPrefixUnaryOperators": [], + + "disallowSpaceBeforePostfixUnaryOperators": ["++", "--"], + "requireSpaceBeforePostfixUnaryOperators": [], + + "disallowSpaceBeforeBinaryOperators": [], + "requireSpaceBeforeBinaryOperators": ["+", "-", "/", "*", "=", "==", "===", "!=", "!=="], + + "requireSpaceAfterBinaryOperators": ["+", "-", "/", "*", "=", "==", "===", "!=", "!=="], + "disallowSpaceAfterBinaryOperators": [], + + "disallowImplicitTypeConversion": ["binary", "string"], + + "disallowKeywords": ["with", "eval"], + + "requireKeywordsOnNewLine": [], + "disallowKeywordsOnNewLine": ["else"], + + "requireLineFeedAtFileEnd": true, + + "disallowTrailingWhitespace": true, + + "disallowTrailingComma": true, + + "excludeFiles": ["node_modules/**", "vendor/**"], + + "disallowMultipleLineStrings": true, + + "requireDotNotation": { "allExcept": ["keywords"] }, + + "requireParenthesesAroundIIFE": true, + + "validateLineBreaks": "LF", + + "validateQuoteMarks": { + "escape": true, + "mark": "'" + }, + + "disallowOperatorBeforeLineBreak": [], + + "requireSpaceBeforeKeywords": [ + "do", + "for", + "if", + "else", + "switch", + "case", + "try", + "catch", + "finally", + "while", + "with", + "return" + ], + + "validateAlignedFunctionParameters": { + "lineBreakAfterOpeningBraces": true, + "lineBreakBeforeClosingBraces": true + }, + + "requirePaddingNewLinesBeforeExport": true, + + "validateNewlineAfterArrayElements": { + "maximum": 2 + }, + + "requirePaddingNewLinesAfterUseStrict": true, + + "disallowArrowFunctions": true, + + "disallowMultiLineTernary": true, + + "validateOrderInObjectKeys": "asc-insensitive", + + "disallowIdenticalDestructuringNames": true, + + "disallowNestedTernaries": { "maxLevel": 1 }, + + "requireSpaceAfterComma": { "allExcept": ["trailing"] }, + "requireAlignedMultilineParams": false, + + "requireSpacesInGenerator": { + "afterStar": true + }, + + "disallowSpacesInGenerator": { + "beforeStar": true + }, + + "disallowVar": false, + + "requireArrayDestructuring": false, + + "requireEnhancedObjectLiterals": false, + + "requireObjectDestructuring": false, + + "requireEarlyReturn": false, + + "requireCapitalizedConstructorsNew": { + "allExcept": ["Function", "String", "Object", "Symbol", "Number", "Date", "RegExp", "Error", "Boolean", "Array"] + }, + + "requireImportAlphabetized": false, + + "requireSpaceBeforeObjectValues": true, + "requireSpaceBeforeDestructuredValues": true, + + "disallowSpacesInsideTemplateStringPlaceholders": true, + + "disallowArrayDestructuringReturn": false, + + "requireNewlineBeforeSingleStatementsInIf": false, + + "disallowUnusedVariables": true, + + "requireSpacesInsideImportedObjectBraces": true, + + "requireUseStrict": true +} + diff --git a/scripts/2.5/node_modules/is-generator-function/.nvmrc b/scripts/2.5/node_modules/is-generator-function/.nvmrc new file mode 100644 index 00000000..64f5a0a6 --- /dev/null +++ b/scripts/2.5/node_modules/is-generator-function/.nvmrc @@ -0,0 +1 @@ +node diff --git a/scripts/2.5/node_modules/is-generator-function/.travis.yml b/scripts/2.5/node_modules/is-generator-function/.travis.yml new file mode 100644 index 00000000..7ead9e94 --- /dev/null +++ b/scripts/2.5/node_modules/is-generator-function/.travis.yml @@ -0,0 +1,191 @@ +language: node_js +os: + - linux +node_js: + - "9.3" + - "8.9" + - "7.10" + - "6.12" + - "5.12" + - "4.8" + - "iojs-v3.3" + - "iojs-v2.5" + - "iojs-v1.8" + - "0.12" + - "0.10" + - "0.8" +before_install: + - 'nvm install-latest-npm' +install: + - 'if [ "${TRAVIS_NODE_VERSION}" = "0.6" ] || [ "${TRAVIS_NODE_VERSION}" = "0.9" ]; then nvm install --latest-npm 0.8 && npm install && nvm use "${TRAVIS_NODE_VERSION}"; else npm install; fi;' +script: + - 'if [ -n "${PRETEST-}" ]; then npm run pretest ; fi' + - 'if [ -n "${POSTTEST-}" ]; then npm run posttest ; fi' + - 'if [ -n "${COVERAGE-}" ]; then npm run coverage ; fi' + - 'if [ -n "${TEST-}" ]; then npm run tests-only ; fi' +sudo: false +env: + - TEST=true +matrix: + fast_finish: true + include: + - node_js: "lts/*" + env: PRETEST=true + - node_js: "lts/*" + env: POSTTEST=true + - node_js: "8" + env: COVERAGE=true + - node_js: "4" + env: COVERAGE=true + - node_js: "9.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v3.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v3.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v3.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.4" + env: TEST=true ALLOW_FAILURE=true + allow_failures: + - os: osx + - env: TEST=true ALLOW_FAILURE=true + - env: COVERAGE=true diff --git a/scripts/2.5/node_modules/is-generator-function/CHANGELOG.md b/scripts/2.5/node_modules/is-generator-function/CHANGELOG.md new file mode 100644 index 00000000..983f5181 --- /dev/null +++ b/scripts/2.5/node_modules/is-generator-function/CHANGELOG.md @@ -0,0 +1,44 @@ +1.0.7 / 2017-12-27 +================= + * [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `core-js`, `nsp`, `semver`, `tape` + * [Tests] up to `node` `v9.3`, `v8.9`, `v6.12`; pin included builds to LTS; use `nvm install-latest-npm` + * [Tests] run tests with uglify-register + +1.0.6 / 2016-12-20 +================= + * [Fix] fix `is-generator-function` in an env without native generators, with core-js (https://github.com/ljharb/is-equal/issues/33) + +1.0.5 / 2016-12-19 +================= + * [Fix] account for Safari 10 which reports the wrong toString on generator functions + * [Refactor] remove useless `Object#toString` check + * [Dev Deps] update everything; add linting + * [Tests] use pretest/posttest for linting/security + * [Tests] on all minors of node and io.js + +1.0.4 / 2015-03-03 +================= + * Add support for concise generator methods (#2) This is a patch change since concise methods are not in any actual released engines yet. + * Test on latest `io.js` + * Update `semver` + +1.0.3 / 2015-01-31 +================= + * Speed up travis-ci tests + * Run tests against a faked @@toStringTag + * Bail out early when typeof is not "function" + +1.0.2 / 2015-01-20 +================= + * Update `jscs`, `tape` + * Fix tests in newer v8 (and io.js) where Object#toString.call of a generator is GeneratorFunction, not Function + +1.0.1 / 2014-12-14 +================= + * Update `jscs`, `tape` + * Tweaks to README + * Use `make-generator-function` in tests + +1.0.0 / 2014-08-09 +================= + * Initial release. diff --git a/scripts/2.5/node_modules/is-generator-function/LICENSE b/scripts/2.5/node_modules/is-generator-function/LICENSE new file mode 100644 index 00000000..47b7b507 --- /dev/null +++ b/scripts/2.5/node_modules/is-generator-function/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2014 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/scripts/2.5/node_modules/is-generator-function/Makefile b/scripts/2.5/node_modules/is-generator-function/Makefile new file mode 100644 index 00000000..ccca6f1c --- /dev/null +++ b/scripts/2.5/node_modules/is-generator-function/Makefile @@ -0,0 +1,61 @@ +# Since we rely on paths relative to the makefile location, abort if make isn't being run from there. +$(if $(findstring /,$(MAKEFILE_LIST)),$(error Please only invoke this makefile from the directory it resides in)) + + # The files that need updating when incrementing the version number. +VERSIONED_FILES := *.js */*.js *.json README* + + +# Add the local npm packages' bin folder to the PATH, so that `make` can find them, when invoked directly. +# Note that rather than using `$(npm bin)` the 'node_modules/.bin' path component is hard-coded, so that invocation works even from an environment +# where npm is (temporarily) unavailable due to having deactivated an nvm instance loaded into the calling shell in order to avoid interference with tests. +export PATH := $(shell printf '%s' "$$PWD/node_modules/.bin:$$PATH") +UTILS := semver replace +# Make sure that all required utilities can be located. +UTIL_CHECK := $(or $(shell PATH="$(PATH)" which $(UTILS) >/dev/null && echo 'ok'),$(error Did you forget to run `npm install` after cloning the repo? At least one of the required supporting utilities not found: $(UTILS))) + +# Default target (by virtue of being the first non '.'-prefixed in the file). +.PHONY: _no-target-specified +_no-target-specified: + $(error Please specify the target to make - `make list` shows targets. Alternatively, use `npm test` to run the default tests; `npm run` shows all tests) + +# Lists all targets defined in this makefile. +.PHONY: list +list: + @$(MAKE) -pRrn : -f $(MAKEFILE_LIST) 2>/dev/null | awk -v RS= -F: '/^# File/,/^# Finished Make data base/ {if ($$1 !~ "^[#.]") {print $$1}}' | command grep -v -e '^[^[:alnum:]]' -e '^$@$$command ' | sort + +# All-tests target: invokes the specified test suites for ALL shells defined in $(SHELLS). +.PHONY: test +test: + @npm test + +.PHONY: _ensure-tag +_ensure-tag: +ifndef TAG + $(error Please invoke with `make TAG= release`, where is either an increment specifier (patch, minor, major, prepatch, preminor, premajor, prerelease), or an explicit major.minor.patch version number) +endif + +CHANGELOG_ERROR = $(error No CHANGELOG specified) +.PHONY: _ensure-changelog +_ensure-changelog: + @ (git status -sb --porcelain | command grep -E '^( M|[MA] ) CHANGELOG.md' > /dev/null) || (echo no CHANGELOG.md specified && exit 2) + +# Ensures that the git workspace is clean. +.PHONY: _ensure-clean +_ensure-clean: + @[ -z "$$((git status --porcelain --untracked-files=no || echo err) | command grep -v 'CHANGELOG.md')" ] || { echo "Workspace is not clean; please commit changes first." >&2; exit 2; } + +# Makes a release; invoke with `make TAG= release`. +.PHONY: release +release: _ensure-tag _ensure-changelog _ensure-clean + @old_ver=`git describe --abbrev=0 --tags --match 'v[0-9]*.[0-9]*.[0-9]*'` || { echo "Failed to determine current version." >&2; exit 1; }; old_ver=$${old_ver#v}; \ + new_ver=`echo "$(TAG)" | sed 's/^v//'`; new_ver=$${new_ver:-patch}; \ + if printf "$$new_ver" | command grep -q '^[0-9]'; then \ + semver "$$new_ver" >/dev/null || { echo 'Invalid version number specified: $(TAG) - must be major.minor.patch' >&2; exit 2; }; \ + semver -r "> $$old_ver" "$$new_ver" >/dev/null || { echo 'Invalid version number specified: $(TAG) - must be HIGHER than current one.' >&2; exit 2; } \ + else \ + new_ver=`semver -i "$$new_ver" "$$old_ver"` || { echo 'Invalid version-increment specifier: $(TAG)' >&2; exit 2; } \ + fi; \ + printf "=== Bumping version **$$old_ver** to **$$new_ver** before committing and tagging:\n=== TYPE 'proceed' TO PROCEED, anything else to abort: " && read response && [ "$$response" = 'proceed' ] || { echo 'Aborted.' >&2; exit 2; }; \ + replace "$$old_ver" "$$new_ver" -- $(VERSIONED_FILES) && \ + git commit -m "v$$new_ver" $(VERSIONED_FILES) CHANGELOG.md && \ + git tag -a -m "v$$new_ver" "v$$new_ver" diff --git a/scripts/2.5/node_modules/is-generator-function/README.md b/scripts/2.5/node_modules/is-generator-function/README.md new file mode 100644 index 00000000..027facf4 --- /dev/null +++ b/scripts/2.5/node_modules/is-generator-function/README.md @@ -0,0 +1,42 @@ +# is-generator-function [![Version Badge][2]][1] + +[![Build Status][3]][4] +[![dependency status][5]][6] +[![dev dependency status][7]][8] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][11]][1] + +[![browser support][9]][10] + +Is this a native generator function? + +## Example + +```js +var isGeneratorFunction = require('is-generator-function'); +assert(!isGeneratorFunction(function () {})); +assert(!isGeneratorFunction(null)); +assert(isGeneratorFunction(function* () { yield 42; return Infinity; })); +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[1]: https://npmjs.org/package/is-generator-function +[2]: http://versionbadg.es/ljharb/is-generator-function.svg +[3]: https://travis-ci.org/ljharb/is-generator-function.svg +[4]: https://travis-ci.org/ljharb/is-generator-function +[5]: https://david-dm.org/ljharb/is-generator-function.svg +[6]: https://david-dm.org/ljharb/is-generator-function +[7]: https://david-dm.org/ljharb/is-generator-function/dev-status.svg +[8]: https://david-dm.org/ljharb/is-generator-function#info=devDependencies +[9]: https://ci.testling.com/ljharb/is-generator-function.png +[10]: https://ci.testling.com/ljharb/is-generator-function +[11]: https://nodei.co/npm/is-generator-function.png?downloads=true&stars=true +[license-image]: http://img.shields.io/npm/l/is-generator-function.svg +[license-url]: LICENSE +[downloads-image]: http://img.shields.io/npm/dm/is-generator-function.svg +[downloads-url]: http://npm-stat.com/charts.html?package=is-generator-function + diff --git a/scripts/2.5/node_modules/is-generator-function/index.js b/scripts/2.5/node_modules/is-generator-function/index.js new file mode 100644 index 00000000..306a299c --- /dev/null +++ b/scripts/2.5/node_modules/is-generator-function/index.js @@ -0,0 +1,32 @@ +'use strict'; + +var toStr = Object.prototype.toString; +var fnToStr = Function.prototype.toString; +var isFnRegex = /^\s*(?:function)?\*/; +var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol'; +var getProto = Object.getPrototypeOf; +var getGeneratorFunc = function () { // eslint-disable-line consistent-return + if (!hasToStringTag) { + return false; + } + try { + return Function('return function*() {}')(); + } catch (e) { + } +}; +var generatorFunc = getGeneratorFunc(); +var GeneratorFunction = generatorFunc ? getProto(generatorFunc) : {}; + +module.exports = function isGeneratorFunction(fn) { + if (typeof fn !== 'function') { + return false; + } + if (isFnRegex.test(fnToStr.call(fn))) { + return true; + } + if (!hasToStringTag) { + var str = toStr.call(fn); + return str === '[object GeneratorFunction]'; + } + return getProto(fn) === GeneratorFunction; +}; diff --git a/scripts/2.5/node_modules/is-generator-function/package.json b/scripts/2.5/node_modules/is-generator-function/package.json new file mode 100644 index 00000000..f10bbbff --- /dev/null +++ b/scripts/2.5/node_modules/is-generator-function/package.json @@ -0,0 +1,101 @@ +{ + "_from": "is-generator-function@^1.0.7", + "_id": "is-generator-function@1.0.7", + "_inBundle": false, + "_integrity": "sha512-YZc5EwyO4f2kWCax7oegfuSr9mFz1ZvieNYBEjmukLxgXfBUbxAWGVF7GZf0zidYtoBl3WvC07YK0wT76a+Rtw==", + "_location": "/is-generator-function", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "is-generator-function@^1.0.7", + "name": "is-generator-function", + "escapedName": "is-generator-function", + "rawSpec": "^1.0.7", + "saveSpec": null, + "fetchSpec": "^1.0.7" + }, + "_requiredBy": [ + "/util" + ], + "_resolved": "https://registry.npmjs.org/is-generator-function/-/is-generator-function-1.0.7.tgz", + "_shasum": "d2132e529bb0000a7f80794d4bdf5cd5e5813522", + "_spec": "is-generator-function@^1.0.7", + "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/2.5/node_modules/util", + "author": { + "name": "Jordan Harband" + }, + "bugs": { + "url": "https://github.com/ljharb/is-generator-function/issues" + }, + "bundleDependencies": false, + "dependencies": {}, + "deprecated": false, + "description": "Determine if a function is a native generator function.", + "devDependencies": { + "@ljharb/eslint-config": "^12.2.1", + "core-js": "^2.5.3", + "covert": "^1.1.0", + "eslint": "^4.14.0", + "jscs": "^3.0.7", + "make-generator-function": "^1.1.0", + "nsp": "^3.1.0", + "replace": "^0.3.0", + "semver": "^5.4.1", + "tape": "^4.8.0", + "uglify-register": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "homepage": "https://github.com/ljharb/is-generator-function#readme", + "keywords": [ + "generator", + "generator function", + "es6", + "es2015", + "yield", + "function", + "function*" + ], + "license": "MIT", + "main": "index.js", + "name": "is-generator-function", + "repository": { + "type": "git", + "url": "git://github.com/ljharb/is-generator-function.git" + }, + "scripts": { + "coverage": "covert test", + "eslint": "eslint *.js */*.js", + "jscs": "jscs *.js */*.js", + "lint": "npm run jscs && npm run eslint", + "posttest": "npm run security", + "posttests-only": "npm run test:corejs && npm run test:uglified", + "pretest": "npm run lint", + "security": "nsp check", + "test": "npm run tests-only", + "test:corejs": "node test/corejs", + "test:uglified": "node test/uglified", + "tests-only": "node --es-staging --harmony test" + }, + "testling": { + "files": "test/index.js", + "browsers": [ + "iexplore/6.0..latest", + "firefox/3.0..6.0", + "firefox/15.0..latest", + "firefox/nightly", + "chrome/4.0..10.0", + "chrome/20.0..latest", + "chrome/canary", + "opera/10.0..latest", + "opera/next", + "safari/4.0..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2" + ] + }, + "version": "1.0.7" +} diff --git a/scripts/2.5/node_modules/is-generator-function/test/.eslintrc b/scripts/2.5/node_modules/is-generator-function/test/.eslintrc new file mode 100644 index 00000000..168cdf85 --- /dev/null +++ b/scripts/2.5/node_modules/is-generator-function/test/.eslintrc @@ -0,0 +1,5 @@ +{ + "rules": { + "max-statements-per-line": [2, { "max": 2 }] + } +} diff --git a/scripts/2.5/node_modules/is-generator-function/test/corejs.js b/scripts/2.5/node_modules/is-generator-function/test/corejs.js new file mode 100644 index 00000000..73f0c89c --- /dev/null +++ b/scripts/2.5/node_modules/is-generator-function/test/corejs.js @@ -0,0 +1,5 @@ +'use strict'; + +require('core-js'); + +require('./'); diff --git a/scripts/2.5/node_modules/is-generator-function/test/index.js b/scripts/2.5/node_modules/is-generator-function/test/index.js new file mode 100644 index 00000000..a33cc2b7 --- /dev/null +++ b/scripts/2.5/node_modules/is-generator-function/test/index.js @@ -0,0 +1,94 @@ +'use strict'; + +/* globals window */ + +var test = require('tape'); +var isGeneratorFunction = require('../index'); +var generatorFunc = require('make-generator-function'); +var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol'; + +var forEach = function (arr, func) { + var i; + for (i = 0; i < arr.length; ++i) { + func(arr[i], i, arr); + } +}; + +test('returns false for non-functions', function (t) { + var nonFuncs = [ + true, + false, + null, + undefined, + {}, + [], + /a/g, + 'string', + 42, + new Date() + ]; + t.plan(nonFuncs.length); + forEach(nonFuncs, function (nonFunc) { + t.notOk(isGeneratorFunction(nonFunc), nonFunc + ' is not a function'); + }); + t.end(); +}); + +test('returns false for non-generator functions', function (t) { + var func = function () {}; + t.notOk(isGeneratorFunction(func), 'anonymous function is not an generator function'); + + var namedFunc = function foo() {}; + t.notOk(isGeneratorFunction(namedFunc), 'named function is not an generator function'); + + if (typeof window === 'undefined') { + t.skip('window.alert is not an generator function'); + } else { + t.notOk(isGeneratorFunction(window.alert), 'window.alert is not an generator function'); + } + t.end(); +}); + +test('returns false for non-generator function with faked toString', function (t) { + var func = function () {}; + func.toString = function () { return 'function* () { return "TOTALLY REAL I SWEAR!"; }'; }; + + t.notEqual(String(func), Function.prototype.toString.apply(func), 'faked toString is not real toString'); + t.notOk(isGeneratorFunction(func), 'anonymous function with faked toString is not a generator function'); + t.end(); +}); + +test('returns false for non-generator function with faked @@toStringTag', { skip: !hasToStringTag }, function (t) { + var fakeGenFunction = { + toString: function () { return String(generatorFunc); }, + valueOf: function () { return generatorFunc; } + }; + fakeGenFunction[Symbol.toStringTag] = 'GeneratorFunction'; + t.notOk(isGeneratorFunction(fakeGenFunction), 'fake GeneratorFunction with @@toStringTag "GeneratorFunction" is not a generator function'); + t.end(); +}); + +test('returns true for generator functions', function (t) { + if (generatorFunc) { + t.ok(isGeneratorFunction(generatorFunc), 'generator function is generator function'); + } else { + t.skip('generator function is generator function - this environment does not support ES6 generator functions. Please run `node --harmony`, or use a supporting browser.'); + } + t.end(); +}); + +test('concise methods', { skip: !generatorFunc || !generatorFunc.concise }, function (t) { + t.test('returns true for concise generator methods', function (st) { + st.ok(isGeneratorFunction(generatorFunc.concise), 'concise generator method is generator function'); + st.end(); + }); + + t.test('returns false for concise non-generator methods', function (st) { + var conciseMethod = Function('return { concise() {} }.concise;')(); + st.equal(typeof conciseMethod, 'function', 'assert: concise method exists'); + st.notOk(isGeneratorFunction(conciseMethod), 'concise non-generator method is not generator function'); + st.end(); + }); + + t.end(); +}); diff --git a/scripts/2.5/node_modules/is-generator-function/test/uglified.js b/scripts/2.5/node_modules/is-generator-function/test/uglified.js new file mode 100644 index 00000000..fd82b553 --- /dev/null +++ b/scripts/2.5/node_modules/is-generator-function/test/uglified.js @@ -0,0 +1,8 @@ +'use strict'; + +require('uglify-register/api').register({ + exclude: [/\/node_modules\//, /\/test\//], + uglify: { mangle: true } +}); + +require('./'); diff --git a/scripts/2.5/node_modules/is-nan/.eslintrc b/scripts/2.5/node_modules/is-nan/.eslintrc new file mode 100644 index 00000000..ad448ec6 --- /dev/null +++ b/scripts/2.5/node_modules/is-nan/.eslintrc @@ -0,0 +1,9 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "no-extra-parens": [2] + } +} diff --git a/scripts/2.5/node_modules/is-nan/.jscs.json b/scripts/2.5/node_modules/is-nan/.jscs.json new file mode 100644 index 00000000..854b398f --- /dev/null +++ b/scripts/2.5/node_modules/is-nan/.jscs.json @@ -0,0 +1,124 @@ +{ + "es3": true, + + "additionalRules": [], + + "requireSemicolons": true, + + "disallowMultipleSpaces": true, + + "disallowIdentifierNames": [], + + "requireCurlyBraces": ["if", "else", "for", "while", "do", "try", "catch"], + + "requireSpaceAfterKeywords": ["if", "else", "for", "while", "do", "switch", "return", "try", "catch", "function"], + + "disallowSpaceAfterKeywords": [], + + "disallowSpaceBeforeComma": true, + "disallowSpaceBeforeSemicolon": true, + + "disallowNodeTypes": [ + "DebuggerStatement", + "ForInStatement", + "LabeledStatement", + "SwitchCase", + "SwitchStatement", + "WithStatement" + ], + + "requireObjectKeysOnNewLine": true, + + "requireSpacesInAnonymousFunctionExpression": { "beforeOpeningRoundBrace": true, "beforeOpeningCurlyBrace": true }, + "requireSpacesInNamedFunctionExpression": { "beforeOpeningCurlyBrace": true }, + "disallowSpacesInNamedFunctionExpression": { "beforeOpeningRoundBrace": true }, + "requireSpacesInFunctionDeclaration": { "beforeOpeningCurlyBrace": true }, + "disallowSpacesInFunctionDeclaration": { "beforeOpeningRoundBrace": true }, + + "requireSpaceBetweenArguments": true, + + "disallowSpacesInsideParentheses": true, + + "disallowSpacesInsideArrayBrackets": true, + + "disallowQuotedKeysInObjects": "allButReserved", + + "disallowSpaceAfterObjectKeys": true, + + "requireCommaBeforeLineBreak": true, + + "disallowSpaceAfterPrefixUnaryOperators": ["++", "--", "+", "-", "~", "!"], + "requireSpaceAfterPrefixUnaryOperators": [], + + "disallowSpaceBeforePostfixUnaryOperators": ["++", "--"], + "requireSpaceBeforePostfixUnaryOperators": [], + + "disallowSpaceBeforeBinaryOperators": [], + "requireSpaceBeforeBinaryOperators": ["+", "-", "/", "*", "=", "==", "===", "!=", "!=="], + + "requireSpaceAfterBinaryOperators": ["+", "-", "/", "*", "=", "==", "===", "!=", "!=="], + "disallowSpaceAfterBinaryOperators": [], + + "disallowImplicitTypeConversion": ["binary", "string"], + + "disallowKeywords": ["with", "eval"], + + "requireKeywordsOnNewLine": [], + "disallowKeywordsOnNewLine": ["else"], + + "requireLineFeedAtFileEnd": true, + + "disallowTrailingWhitespace": true, + + "disallowTrailingComma": true, + + "excludeFiles": ["node_modules/**", "vendor/**"], + + "disallowMultipleLineStrings": true, + + "requireDotNotation": true, + + "requireParenthesesAroundIIFE": true, + + "validateLineBreaks": "LF", + + "validateQuoteMarks": { + "escape": true, + "mark": "'" + }, + + "disallowOperatorBeforeLineBreak": [], + + "requireSpaceBeforeKeywords": [ + "do", + "for", + "if", + "else", + "switch", + "case", + "try", + "catch", + "finally", + "while", + "with", + "return" + ], + + "validateAlignedFunctionParameters": { + "lineBreakAfterOpeningBraces": true, + "lineBreakBeforeClosingBraces": true + }, + + "requirePaddingNewLinesBeforeExport": true, + + "validateNewlineAfterArrayElements": { + "maximum": 1 + }, + + "requirePaddingNewLinesAfterUseStrict": true, + + "disallowArrowFunctions": true, + + "validateOrderInObjectKeys": "asc-insensitive" +} + diff --git a/scripts/2.5/node_modules/is-nan/.npmignore b/scripts/2.5/node_modules/is-nan/.npmignore new file mode 100644 index 00000000..a72b52eb --- /dev/null +++ b/scripts/2.5/node_modules/is-nan/.npmignore @@ -0,0 +1,15 @@ +lib-cov +*.seed +*.log +*.csv +*.dat +*.out +*.pid +*.gz + +pids +logs +results + +npm-debug.log +node_modules diff --git a/scripts/2.5/node_modules/is-nan/.travis.yml b/scripts/2.5/node_modules/is-nan/.travis.yml new file mode 100644 index 00000000..feec7eef --- /dev/null +++ b/scripts/2.5/node_modules/is-nan/.travis.yml @@ -0,0 +1,49 @@ +language: node_js +node_js: + - "iojs-v3.0" + - "iojs-v2.5" + - "iojs-v2.4" + - "iojs-v2.3" + - "iojs-v2.2" + - "iojs-v2.1" + - "iojs-v2.0" + - "iojs-v1.8" + - "iojs-v1.7" + - "iojs-v1.6" + - "iojs-v1.5" + - "iojs-v1.4" + - "iojs-v1.3" + - "iojs-v1.2" + - "iojs-v1.1" + - "iojs-v1.0" + - "0.12" + - "0.11" + - "0.10" + - "0.9" + - "0.8" + - "0.6" + - "0.4" +before_install: + - '[ "${TRAVIS_NODE_VERSION}" = "0.6" ] || npm install -g npm@1.4.28 && npm install -g npm' +sudo: false +matrix: + fast_finish: true + allow_failures: + - node_js: "iojs-v2.4" + - node_js: "iojs-v2.3" + - node_js: "iojs-v2.2" + - node_js: "iojs-v2.1" + - node_js: "iojs-v2.0" + - node_js: "iojs-v1.7" + - node_js: "iojs-v1.6" + - node_js: "iojs-v1.5" + - node_js: "iojs-v1.4" + - node_js: "iojs-v1.3" + - node_js: "iojs-v1.2" + - node_js: "iojs-v1.1" + - node_js: "iojs-v1.0" + - node_js: "0.11" + - node_js: "0.9" + - node_js: "0.8" + - node_js: "0.6" + - node_js: "0.4" diff --git a/scripts/2.5/node_modules/is-nan/CHANGELOG.md b/scripts/2.5/node_modules/is-nan/CHANGELOG.md new file mode 100644 index 00000000..a10639ef --- /dev/null +++ b/scripts/2.5/node_modules/is-nan/CHANGELOG.md @@ -0,0 +1,27 @@ +1.2.1 / 2015-08-16 +================= + * [Docs] Update readme + +1.2.0 / 2015-08-16 +================= + * [New] Implement the [es-shim API](es-shims/api) interface + * [Dev Deps] update `eslint`, `tape`, `es5-shim`, `@ljharb/eslint-config` + * [Tests] up to `io.js` `v3.0` + * [Docs] Switch from vb.teelaun.ch to versionbadg.es for the npm version badge SVG + * [Security] Add `npm run security` + +1.1.0 / 2015-06-24 +================= + * Add a "shim" method + * Add `npm run eslint` + * Test latest `node` and `io.js` on `travis-ci` + * Add license and download badges to README + * Update `tape`, `covert`, `jscs` + +1.0.1 / 2014-07-05 +================= + * Oops, jscs should be a devDependency + +1.0.0 / 2014-07-05 +================= + * Initial release. diff --git a/scripts/2.5/node_modules/is-nan/LICENSE b/scripts/2.5/node_modules/is-nan/LICENSE new file mode 100644 index 00000000..47b7b507 --- /dev/null +++ b/scripts/2.5/node_modules/is-nan/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2014 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/scripts/2.5/node_modules/is-nan/README.md b/scripts/2.5/node_modules/is-nan/README.md new file mode 100644 index 00000000..5beebc95 --- /dev/null +++ b/scripts/2.5/node_modules/is-nan/README.md @@ -0,0 +1,56 @@ +#is-nan [![Version Badge][2]][1] + +[![Build Status][3]][4] +[![dependency status][5]][6] +[![dev dependency status][7]][8] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][11]][1] + +[![browser support][9]][10] + +ES6-compliant shim for Number.isNaN - the global isNaN returns false positives. + +This package implements the [es-shim API](https://github.com/es-shims/api) interface. It works in an ES3-supported environment and complies with the [spec](http://www.ecma-international.org/ecma-262/6.0/#sec-number.isnan). + +## Example + +```js +Number.isNaN = require('is-nan'); +var assert = require('assert'); + +assert.notOk(Number.isNaN(undefined)); +assert.notOk(Number.isNaN(null)); +assert.notOk(Number.isNaN(false)); +assert.notOk(Number.isNaN(true)); +assert.notOk(Number.isNaN(0)); +assert.notOk(Number.isNaN(42)); +assert.notOk(Number.isNaN(Infinity)); +assert.notOk(Number.isNaN(-Infinity)); +assert.notOk(Number.isNaN('foo')); +assert.notOk(Number.isNaN(function () {})); +assert.notOk(Number.isNaN([])); +assert.notOk(Number.isNaN({})); + +assert.ok(Number.isNaN(NaN)); +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[1]: https://npmjs.org/package/is-nan +[2]: http://versionbadg.es/ljharb/is-nan.svg +[3]: https://travis-ci.org/ljharb/is-nan.svg +[4]: https://travis-ci.org/ljharb/is-nan +[5]: https://david-dm.org/ljharb/is-nan.svg +[6]: https://david-dm.org/ljharb/is-nan +[7]: https://david-dm.org/ljharb/is-nan/dev-status.svg +[8]: https://david-dm.org/ljharb/is-nan#info=devDependencies +[9]: https://ci.testling.com/ljharb/is-nan.png +[10]: https://ci.testling.com/ljharb/is-nan +[11]: https://nodei.co/npm/is-nan.png?downloads=true&stars=true +[license-image]: http://img.shields.io/npm/l/is-nan.svg +[license-url]: LICENSE +[downloads-image]: http://img.shields.io/npm/dm/is-nan.svg +[downloads-url]: http://npm-stat.com/charts.html?package=is-nan diff --git a/scripts/2.5/node_modules/is-nan/implementation.js b/scripts/2.5/node_modules/is-nan/implementation.js new file mode 100644 index 00000000..6200b6b7 --- /dev/null +++ b/scripts/2.5/node_modules/is-nan/implementation.js @@ -0,0 +1,7 @@ +'use strict'; + +/* http://www.ecma-international.org/ecma-262/6.0/#sec-number.isnan */ + +module.exports = function isNaN(value) { + return value !== value; +}; diff --git a/scripts/2.5/node_modules/is-nan/index.js b/scripts/2.5/node_modules/is-nan/index.js new file mode 100644 index 00000000..5b327213 --- /dev/null +++ b/scripts/2.5/node_modules/is-nan/index.js @@ -0,0 +1,17 @@ +'use strict'; + +var define = require('define-properties'); + +var implementation = require('./implementation'); +var getPolyfill = require('./polyfill'); +var shim = require('./shim'); + +/* http://www.ecma-international.org/ecma-262/6.0/#sec-number.isnan */ + +define(implementation, { + getPolyfill: getPolyfill, + implementation: implementation, + shim: shim +}); + +module.exports = implementation; diff --git a/scripts/2.5/node_modules/is-nan/package.json b/scripts/2.5/node_modules/is-nan/package.json new file mode 100644 index 00000000..213ed48e --- /dev/null +++ b/scripts/2.5/node_modules/is-nan/package.json @@ -0,0 +1,101 @@ +{ + "_from": "is-nan@^1.2.1", + "_id": "is-nan@1.2.1", + "_inBundle": false, + "_integrity": "sha1-n69ltvttskt/XAYoR16nH5iEAeI=", + "_location": "/is-nan", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "is-nan@^1.2.1", + "name": "is-nan", + "escapedName": "is-nan", + "rawSpec": "^1.2.1", + "saveSpec": null, + "fetchSpec": "^1.2.1" + }, + "_requiredBy": [ + "/assert" + ], + "_resolved": "https://registry.npmjs.org/is-nan/-/is-nan-1.2.1.tgz", + "_shasum": "9faf65b6fb6db24b7f5c0628475ea71f988401e2", + "_spec": "is-nan@^1.2.1", + "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/2.5/node_modules/assert", + "author": { + "name": "Jordan Harband" + }, + "bugs": { + "url": "https://github.com/ljharb/is-nan/issues" + }, + "bundleDependencies": false, + "dependencies": { + "define-properties": "^1.1.1" + }, + "deprecated": false, + "description": "ES6-compliant shim for Number.isNaN - the global isNaN returns false positives.", + "devDependencies": { + "@es-shims/api": "^1.0.0", + "@ljharb/eslint-config": "^1.0.4", + "covert": "^1.1.0", + "es5-shim": "^4.1.10", + "eslint": "^1.1.0", + "jscs": "^2.1.0", + "nsp": "^1.0.3", + "tape": "^4.2.0" + }, + "engines": { + "node": ">= 0.4" + }, + "homepage": "https://github.com/ljharb/is-nan", + "keywords": [ + "is", + "NaN", + "not a number", + "number", + "isNaN", + "ES6", + "shim", + "polyfill", + "es-shim API" + ], + "license": "MIT", + "main": "index.js", + "name": "is-nan", + "repository": { + "type": "git", + "url": "git://github.com/ljharb/is-nan.git" + }, + "scripts": { + "coverage": "covert test/*.js", + "coverage-quiet": "covert test/*.js --quiet", + "eslint": "eslint *.js test/*.js", + "jscs": "jscs *.js test/*.js", + "lint": "npm run jscs && npm run eslint", + "security": "nsp package", + "test": "npm run lint && es-shim-api && npm run tests-only && npm run security", + "test:function": "node test/index.js", + "test:shimmed": "node test/shimmed.js", + "tests-only": "npm run test:function && npm run test:shimmed" + }, + "testling": { + "files": "test.js", + "browsers": [ + "iexplore/6.0..latest", + "firefox/3.0..6.0", + "firefox/15.0..latest", + "firefox/nightly", + "chrome/4.0..10.0", + "chrome/20.0..latest", + "chrome/canary", + "opera/10.0..12.0", + "opera/15.0..latest", + "opera/next", + "safari/4.0..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2" + ] + }, + "version": "1.2.1" +} diff --git a/scripts/2.5/node_modules/is-nan/polyfill.js b/scripts/2.5/node_modules/is-nan/polyfill.js new file mode 100644 index 00000000..2fa5886a --- /dev/null +++ b/scripts/2.5/node_modules/is-nan/polyfill.js @@ -0,0 +1,10 @@ +'use strict'; + +var implementation = require('./implementation'); + +module.exports = function getPolyfill() { + if (Number.isNaN && Number.isNaN(NaN) && !Number.isNaN('a')) { + return Number.isNaN; + } + return implementation; +}; diff --git a/scripts/2.5/node_modules/is-nan/shim.js b/scripts/2.5/node_modules/is-nan/shim.js new file mode 100644 index 00000000..abaa4954 --- /dev/null +++ b/scripts/2.5/node_modules/is-nan/shim.js @@ -0,0 +1,12 @@ +'use strict'; + +var define = require('define-properties'); +var getPolyfill = require('./polyfill'); + +/* http://www.ecma-international.org/ecma-262/6.0/#sec-number.isnan */ + +module.exports = function shimNumberIsNaN() { + var polyfill = getPolyfill(); + define(Number, { isNaN: polyfill }, { isNaN: function () { return Number.isNaN !== polyfill; } }); + return polyfill; +}; diff --git a/scripts/2.5/node_modules/is-nan/test/index.js b/scripts/2.5/node_modules/is-nan/test/index.js new file mode 100644 index 00000000..0711154c --- /dev/null +++ b/scripts/2.5/node_modules/is-nan/test/index.js @@ -0,0 +1,10 @@ +'use strict'; + +var numberIsNaN = require('../'); +var test = require('tape'); + +test('as a function', function (t) { + require('./tests')(numberIsNaN, t); + + t.end(); +}); diff --git a/scripts/2.5/node_modules/is-nan/test/shimmed.js b/scripts/2.5/node_modules/is-nan/test/shimmed.js new file mode 100644 index 00000000..ab1353cb --- /dev/null +++ b/scripts/2.5/node_modules/is-nan/test/shimmed.js @@ -0,0 +1,28 @@ +'use strict'; + +require('es5-shim'); + +var numberIsNaN = require('../'); +numberIsNaN.shim(); + +var test = require('tape'); +var defineProperties = require('define-properties'); +var isEnumerable = Object.prototype.propertyIsEnumerable; +var functionsHaveNames = function f() {}.name === 'f'; + +test('shimmed', function (t) { + t.equal(Number.isNaN.length, 1, 'Number.isNaN has a length of 1'); + t.test('Function name', { skip: !functionsHaveNames }, function (st) { + st.equal(Number.isNaN.name, 'isNaN', 'Number.isNaN has name "isNaN"'); + st.end(); + }); + + t.test('enumerability', { skip: !defineProperties.supportsDescriptors }, function (et) { + et.equal(false, isEnumerable.call(Number, 'isNaN'), 'Number.isNaN is not enumerable'); + et.end(); + }); + + require('./tests')(Number.isNaN, t); + + t.end(); +}); diff --git a/scripts/2.5/node_modules/is-nan/test/tests.js b/scripts/2.5/node_modules/is-nan/test/tests.js new file mode 100644 index 00000000..33d2dc37 --- /dev/null +++ b/scripts/2.5/node_modules/is-nan/test/tests.js @@ -0,0 +1,36 @@ +'use strict'; + +module.exports = function (numberIsNaN, t) { + t.test('not NaN', function (st) { + st.test('primitives', function (sst) { + sst.notOk(numberIsNaN(), 'undefined is not NaN'); + sst.notOk(numberIsNaN(null), 'null is not NaN'); + sst.notOk(numberIsNaN(false), 'false is not NaN'); + sst.notOk(numberIsNaN(true), 'true is not NaN'); + sst.notOk(numberIsNaN(0), 'positive zero is not NaN'); + sst.notOk(numberIsNaN(Infinity), 'Infinity is not NaN'); + sst.notOk(numberIsNaN(-Infinity), '-Infinity is not NaN'); + sst.notOk(numberIsNaN('foo'), 'string is not NaN'); + sst.notOk(numberIsNaN('NaN'), 'string NaN is not NaN'); + sst.end(); + }); + + st.notOk(numberIsNaN([]), 'array is not NaN'); + st.notOk(numberIsNaN({}), 'object is not NaN'); + st.notOk(numberIsNaN(function () {}), 'function is not NaN'); + + st.test('valueOf', function (vt) { + var obj = { valueOf: function () { return NaN; } }; + vt.ok(numberIsNaN(Number(obj)), 'object with valueOf of NaN, converted to Number, is NaN'); + vt.notOk(numberIsNaN(obj), 'object with valueOf of NaN is not NaN'); + vt.end(); + }); + + st.end(); + }); + + t.test('NaN literal', function (st) { + st.ok(numberIsNaN(NaN), 'NaN is NaN'); + st.end(); + }); +}; diff --git a/scripts/2.5/node_modules/is-regex/.eslintrc b/scripts/2.5/node_modules/is-regex/.eslintrc new file mode 100644 index 00000000..fbb8e9de --- /dev/null +++ b/scripts/2.5/node_modules/is-regex/.eslintrc @@ -0,0 +1,9 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "id-length": [1] + } +} diff --git a/scripts/2.5/node_modules/is-regex/.jscs.json b/scripts/2.5/node_modules/is-regex/.jscs.json new file mode 100644 index 00000000..3d099c4b --- /dev/null +++ b/scripts/2.5/node_modules/is-regex/.jscs.json @@ -0,0 +1,176 @@ +{ + "es3": true, + + "additionalRules": [], + + "requireSemicolons": true, + + "disallowMultipleSpaces": true, + + "disallowIdentifierNames": [], + + "requireCurlyBraces": { + "allExcept": [], + "keywords": ["if", "else", "for", "while", "do", "try", "catch"] + }, + + "requireSpaceAfterKeywords": ["if", "else", "for", "while", "do", "switch", "return", "try", "catch", "function"], + + "disallowSpaceAfterKeywords": [], + + "disallowSpaceBeforeComma": true, + "disallowSpaceAfterComma": false, + "disallowSpaceBeforeSemicolon": true, + + "disallowNodeTypes": [ + "DebuggerStatement", + "ForInStatement", + "LabeledStatement", + "SwitchCase", + "SwitchStatement", + "WithStatement" + ], + + "requireObjectKeysOnNewLine": { "allExcept": ["sameLine"] }, + + "requireSpacesInAnonymousFunctionExpression": { "beforeOpeningRoundBrace": true, "beforeOpeningCurlyBrace": true }, + "requireSpacesInNamedFunctionExpression": { "beforeOpeningCurlyBrace": true }, + "disallowSpacesInNamedFunctionExpression": { "beforeOpeningRoundBrace": true }, + "requireSpacesInFunctionDeclaration": { "beforeOpeningCurlyBrace": true }, + "disallowSpacesInFunctionDeclaration": { "beforeOpeningRoundBrace": true }, + + "requireSpaceBetweenArguments": true, + + "disallowSpacesInsideParentheses": true, + + "disallowSpacesInsideArrayBrackets": true, + + "disallowQuotedKeysInObjects": { "allExcept": ["reserved"] }, + + "disallowSpaceAfterObjectKeys": true, + + "requireCommaBeforeLineBreak": true, + + "disallowSpaceAfterPrefixUnaryOperators": ["++", "--", "+", "-", "~", "!"], + "requireSpaceAfterPrefixUnaryOperators": [], + + "disallowSpaceBeforePostfixUnaryOperators": ["++", "--"], + "requireSpaceBeforePostfixUnaryOperators": [], + + "disallowSpaceBeforeBinaryOperators": [], + "requireSpaceBeforeBinaryOperators": ["+", "-", "/", "*", "=", "==", "===", "!=", "!=="], + + "requireSpaceAfterBinaryOperators": ["+", "-", "/", "*", "=", "==", "===", "!=", "!=="], + "disallowSpaceAfterBinaryOperators": [], + + "disallowImplicitTypeConversion": ["binary", "string"], + + "disallowKeywords": ["with", "eval"], + + "requireKeywordsOnNewLine": [], + "disallowKeywordsOnNewLine": ["else"], + + "requireLineFeedAtFileEnd": true, + + "disallowTrailingWhitespace": true, + + "disallowTrailingComma": true, + + "excludeFiles": ["node_modules/**", "vendor/**"], + + "disallowMultipleLineStrings": true, + + "requireDotNotation": { "allExcept": ["keywords"] }, + + "requireParenthesesAroundIIFE": true, + + "validateLineBreaks": "LF", + + "validateQuoteMarks": { + "escape": true, + "mark": "'" + }, + + "disallowOperatorBeforeLineBreak": [], + + "requireSpaceBeforeKeywords": [ + "do", + "for", + "if", + "else", + "switch", + "case", + "try", + "catch", + "finally", + "while", + "with", + "return" + ], + + "validateAlignedFunctionParameters": { + "lineBreakAfterOpeningBraces": true, + "lineBreakBeforeClosingBraces": true + }, + + "requirePaddingNewLinesBeforeExport": true, + + "validateNewlineAfterArrayElements": { + "maximum": 1 + }, + + "requirePaddingNewLinesAfterUseStrict": true, + + "disallowArrowFunctions": true, + + "disallowMultiLineTernary": true, + + "validateOrderInObjectKeys": "asc-insensitive", + + "disallowIdenticalDestructuringNames": true, + + "disallowNestedTernaries": { "maxLevel": 1 }, + + "requireSpaceAfterComma": { "allExcept": ["trailing"] }, + "requireAlignedMultilineParams": false, + + "requireSpacesInGenerator": { + "afterStar": true + }, + + "disallowSpacesInGenerator": { + "beforeStar": true + }, + + "disallowVar": false, + + "requireArrayDestructuring": false, + + "requireEnhancedObjectLiterals": false, + + "requireObjectDestructuring": false, + + "requireEarlyReturn": false, + + "requireCapitalizedConstructorsNew": { + "allExcept": ["Function", "String", "Object", "Symbol", "Number", "Date", "RegExp", "Error", "Boolean", "Array"] + }, + + "requireImportAlphabetized": false, + + "requireSpaceBeforeObjectValues": true, + "requireSpaceBeforeDestructuredValues": true, + + "disallowSpacesInsideTemplateStringPlaceholders": true, + + "disallowArrayDestructuringReturn": false, + + "requireNewlineBeforeSingleStatementsInIf": false, + + "disallowUnusedVariables": true, + + "requireSpacesInsideImportedObjectBraces": true, + + "requireUseStrict": true +} + diff --git a/scripts/2.5/node_modules/is-regex/.npmignore b/scripts/2.5/node_modules/is-regex/.npmignore new file mode 100644 index 00000000..a72b52eb --- /dev/null +++ b/scripts/2.5/node_modules/is-regex/.npmignore @@ -0,0 +1,15 @@ +lib-cov +*.seed +*.log +*.csv +*.dat +*.out +*.pid +*.gz + +pids +logs +results + +npm-debug.log +node_modules diff --git a/scripts/2.5/node_modules/is-regex/.travis.yml b/scripts/2.5/node_modules/is-regex/.travis.yml new file mode 100644 index 00000000..41137a89 --- /dev/null +++ b/scripts/2.5/node_modules/is-regex/.travis.yml @@ -0,0 +1,165 @@ +language: node_js +os: + - linux +node_js: + - "7.5" + - "6.9" + - "5.12" + - "4.7" + - "iojs-v3.3" + - "iojs-v2.5" + - "iojs-v1.8" + - "0.12" + - "0.10" + - "0.8" +before_install: + - 'if [ "${TRAVIS_NODE_VERSION}" = "0.6" ]; then npm install -g npm@1.3 ; elif [ "${TRAVIS_NODE_VERSION}" != "0.9" ]; then case "$(npm --version)" in 1.*) npm install -g npm@1.4.28 ;; 2.*) npm install -g npm@2 ;; esac ; fi' + - 'if [ "${TRAVIS_NODE_VERSION}" != "0.6" ] && [ "${TRAVIS_NODE_VERSION}" != "0.9" ]; then npm install -g npm; fi' +script: + - 'if [ -n "${PRETEST-}" ]; then npm run pretest ; fi' + - 'if [ -n "${POSTTEST-}" ]; then npm run posttest ; fi' + - 'if [ -n "${COVERAGE-}" ]; then npm run coverage ; fi' + - 'if [ -n "${TEST-}" ]; then npm run tests-only ; fi' +sudo: false +env: + - TEST=true +matrix: + fast_finish: true + include: + - node_js: "node" + env: PRETEST=true + - node_js: "node" + env: POSTTEST=true + - node_js: "7.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v3.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v3.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v3.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7" + env: TEST=true + os: osx + - node_js: "6" + env: TEST=true + os: osx + - node_js: "5" + env: TEST=true + os: osx + - node_js: "4" + env: TEST=true + os: osx + - node_js: "iojs" + env: TEST=true + os: osx + - node_js: "0.12" + env: TEST=true + os: osx + - node_js: "0.10" + env: TEST=true + os: osx + - node_js: "0.8" + env: TEST=true + os: osx + allow_failures: + - os: osx + - env: TEST=true ALLOW_FAILURE=true diff --git a/scripts/2.5/node_modules/is-regex/CHANGELOG.md b/scripts/2.5/node_modules/is-regex/CHANGELOG.md new file mode 100644 index 00000000..6d738000 --- /dev/null +++ b/scripts/2.5/node_modules/is-regex/CHANGELOG.md @@ -0,0 +1,27 @@ +1.0.4 / 2016-02-18 +================= + * [Fix] ensure that `lastIndex` is not mutated (#3) + * [Refactor] when try/catch is needed, bail early if the value lacks an own `lastIndex` data property + * [Refactor] use an early return instead of a ternary + * [Refactor] bail earlier when the value is falsy + * Switch from vb.teelaun.ch to versionbadg.es for the npm version badge SVG + * [Dev Deps] update `tape`, `jscs`, `editorconfig-tools`, `eslint`, `semver`, `replace`, `nsp`, `covert`, `@ljharb/eslint-config` + * [Tests] on all the node and io.js versions; improve test matri + * [Tests] Fix tests for faked @@toStringTag + +1.0.3 / 2015-01-29 +================= + * If @@toStringTag is not present, use the old-school Object#toString test. + +1.0.2 / 2015-01-29 +================= + * Improve optimization by separating the try/catch, and bailing out early when not typeof "object". + +1.0.1 / 2015-01-28 +================= + * Update `jscs`, `tape`, `covert` + * Use RegExp#exec to test if something is a regex, which works even with ES6 @@toStringTag. + +1.0.0 / 2014-05-19 +================= + * Initial release. diff --git a/scripts/2.5/node_modules/is-regex/LICENSE b/scripts/2.5/node_modules/is-regex/LICENSE new file mode 100644 index 00000000..47b7b507 --- /dev/null +++ b/scripts/2.5/node_modules/is-regex/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2014 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/scripts/2.5/node_modules/is-regex/Makefile b/scripts/2.5/node_modules/is-regex/Makefile new file mode 100644 index 00000000..b9e4fe1a --- /dev/null +++ b/scripts/2.5/node_modules/is-regex/Makefile @@ -0,0 +1,61 @@ +# Since we rely on paths relative to the makefile location, abort if make isn't being run from there. +$(if $(findstring /,$(MAKEFILE_LIST)),$(error Please only invoke this makefile from the directory it resides in)) + + # The files that need updating when incrementing the version number. +VERSIONED_FILES := *.js *.json README* + + +# Add the local npm packages' bin folder to the PATH, so that `make` can find them, when invoked directly. +# Note that rather than using `$(npm bin)` the 'node_modules/.bin' path component is hard-coded, so that invocation works even from an environment +# where npm is (temporarily) unavailable due to having deactivated an nvm instance loaded into the calling shell in order to avoid interference with tests. +export PATH := $(shell printf '%s' "$$PWD/node_modules/.bin:$$PATH") +UTILS := semver +# Make sure that all required utilities can be located. +UTIL_CHECK := $(or $(shell PATH="$(PATH)" which $(UTILS) >/dev/null && echo 'ok'),$(error Did you forget to run `npm install` after cloning the repo? At least one of the required supporting utilities not found: $(UTILS))) + +# Default target (by virtue of being the first non '.'-prefixed in the file). +.PHONY: _no-target-specified +_no-target-specified: + $(error Please specify the target to make - `make list` shows targets. Alternatively, use `npm test` to run the default tests; `npm run` shows all tests) + +# Lists all targets defined in this makefile. +.PHONY: list +list: + @$(MAKE) -pRrn : -f $(MAKEFILE_LIST) 2>/dev/null | awk -v RS= -F: '/^# File/,/^# Finished Make data base/ {if ($$1 !~ "^[#.]") {print $$1}}' | command grep -v -e '^[^[:alnum:]]' -e '^$@$$command ' | sort + +# All-tests target: invokes the specified test suites for ALL shells defined in $(SHELLS). +.PHONY: test +test: + @npm test + +.PHONY: _ensure-tag +_ensure-tag: +ifndef TAG + $(error Please invoke with `make TAG= release`, where is either an increment specifier (patch, minor, major, prepatch, preminor, premajor, prerelease), or an explicit major.minor.patch version number) +endif + +CHANGELOG_ERROR = $(error No CHANGELOG specified) +.PHONY: _ensure-changelog +_ensure-changelog: + @ (git status -sb --porcelain | command grep -E '^( M|[MA] ) CHANGELOG.md' > /dev/null) || (echo no CHANGELOG.md specified && exit 2) + +# Ensures that the git workspace is clean. +.PHONY: _ensure-clean +_ensure-clean: + @[ -z "$$((git status --porcelain --untracked-files=no || echo err) | command grep -v 'CHANGELOG.md')" ] || { echo "Workspace is not clean; please commit changes first." >&2; exit 2; } + +# Makes a release; invoke with `make TAG= release`. +.PHONY: release +release: _ensure-tag _ensure-changelog _ensure-clean + @old_ver=`git describe --abbrev=0 --tags --match 'v[0-9]*.[0-9]*.[0-9]*'` || { echo "Failed to determine current version." >&2; exit 1; }; old_ver=$${old_ver#v}; \ + new_ver=`echo "$(TAG)" | sed 's/^v//'`; new_ver=$${new_ver:-patch}; \ + if printf "$$new_ver" | command grep -q '^[0-9]'; then \ + semver "$$new_ver" >/dev/null || { echo 'Invalid version number specified: $(TAG) - must be major.minor.patch' >&2; exit 2; }; \ + semver -r "> $$old_ver" "$$new_ver" >/dev/null || { echo 'Invalid version number specified: $(TAG) - must be HIGHER than current one.' >&2; exit 2; } \ + else \ + new_ver=`semver -i "$$new_ver" "$$old_ver"` || { echo 'Invalid version-increment specifier: $(TAG)' >&2; exit 2; } \ + fi; \ + printf "=== Bumping version **$$old_ver** to **$$new_ver** before committing and tagging:\n=== TYPE 'proceed' TO PROCEED, anything else to abort: " && read response && [ "$$response" = 'proceed' ] || { echo 'Aborted.' >&2; exit 2; }; \ + replace "$$old_ver" "$$new_ver" -- $(VERSIONED_FILES) && \ + git commit -m "v$$new_ver" $(VERSIONED_FILES) CHANGELOG.md && \ + git tag -a -m "v$$new_ver" "v$$new_ver" diff --git a/scripts/2.5/node_modules/is-regex/README.md b/scripts/2.5/node_modules/is-regex/README.md new file mode 100644 index 00000000..05baa0eb --- /dev/null +++ b/scripts/2.5/node_modules/is-regex/README.md @@ -0,0 +1,54 @@ +#is-regex [![Version Badge][2]][1] + +[![Build Status][3]][4] +[![dependency status][5]][6] +[![dev dependency status][7]][8] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][11]][1] + +[![browser support][9]][10] + +Is this value a JS regex? +This module works cross-realm/iframe, and despite ES6 @@toStringTag. + +## Example + +```js +var isRegex = require('is-regex'); +var assert = require('assert'); + +assert.notOk(isRegex(undefined)); +assert.notOk(isRegex(null)); +assert.notOk(isRegex(false)); +assert.notOk(isRegex(true)); +assert.notOk(isRegex(42)); +assert.notOk(isRegex('foo')); +assert.notOk(isRegex(function () {})); +assert.notOk(isRegex([])); +assert.notOk(isRegex({})); + +assert.ok(isRegex(/a/g)); +assert.ok(isRegex(new RegExp('a', 'g'))); +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[1]: https://npmjs.org/package/is-regex +[2]: http://versionbadg.es/ljharb/is-regex.svg +[3]: https://travis-ci.org/ljharb/is-regex.svg +[4]: https://travis-ci.org/ljharb/is-regex +[5]: https://david-dm.org/ljharb/is-regex.svg +[6]: https://david-dm.org/ljharb/is-regex +[7]: https://david-dm.org/ljharb/is-regex/dev-status.svg +[8]: https://david-dm.org/ljharb/is-regex#info=devDependencies +[9]: https://ci.testling.com/ljharb/is-regex.png +[10]: https://ci.testling.com/ljharb/is-regex +[11]: https://nodei.co/npm/is-regex.png?downloads=true&stars=true +[license-image]: http://img.shields.io/npm/l/is-regex.svg +[license-url]: LICENSE +[downloads-image]: http://img.shields.io/npm/dm/is-regex.svg +[downloads-url]: http://npm-stat.com/charts.html?package=is-regex + diff --git a/scripts/2.5/node_modules/is-regex/index.js b/scripts/2.5/node_modules/is-regex/index.js new file mode 100644 index 00000000..be651339 --- /dev/null +++ b/scripts/2.5/node_modules/is-regex/index.js @@ -0,0 +1,39 @@ +'use strict'; + +var has = require('has'); +var regexExec = RegExp.prototype.exec; +var gOPD = Object.getOwnPropertyDescriptor; + +var tryRegexExecCall = function tryRegexExec(value) { + try { + var lastIndex = value.lastIndex; + value.lastIndex = 0; + + regexExec.call(value); + return true; + } catch (e) { + return false; + } finally { + value.lastIndex = lastIndex; + } +}; +var toStr = Object.prototype.toString; +var regexClass = '[object RegExp]'; +var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol'; + +module.exports = function isRegex(value) { + if (!value || typeof value !== 'object') { + return false; + } + if (!hasToStringTag) { + return toStr.call(value) === regexClass; + } + + var descriptor = gOPD(value, 'lastIndex'); + var hasLastIndexDataProperty = descriptor && has(descriptor, 'value'); + if (!hasLastIndexDataProperty) { + return false; + } + + return tryRegexExecCall(value); +}; diff --git a/scripts/2.5/node_modules/is-regex/package.json b/scripts/2.5/node_modules/is-regex/package.json new file mode 100644 index 00000000..8e3bd384 --- /dev/null +++ b/scripts/2.5/node_modules/is-regex/package.json @@ -0,0 +1,100 @@ +{ + "_from": "is-regex@^1.0.4", + "_id": "is-regex@1.0.4", + "_inBundle": false, + "_integrity": "sha1-VRdIm1RwkbCTDglWVM7SXul+lJE=", + "_location": "/is-regex", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "is-regex@^1.0.4", + "name": "is-regex", + "escapedName": "is-regex", + "rawSpec": "^1.0.4", + "saveSpec": null, + "fetchSpec": "^1.0.4" + }, + "_requiredBy": [ + "/es-abstract" + ], + "_resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.0.4.tgz", + "_shasum": "5517489b547091b0930e095654ced25ee97e9491", + "_spec": "is-regex@^1.0.4", + "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/2.5/node_modules/es-abstract", + "author": { + "name": "Jordan Harband" + }, + "bugs": { + "url": "https://github.com/ljharb/is-regex/issues" + }, + "bundleDependencies": false, + "dependencies": { + "has": "^1.0.1" + }, + "deprecated": false, + "description": "Is this value a JS regex? Works cross-realm/iframe, and despite ES6 @@toStringTag", + "devDependencies": { + "@ljharb/eslint-config": "^11.0.0", + "covert": "^1.1.0", + "editorconfig-tools": "^0.1.1", + "eslint": "^3.15.0", + "jscs": "^3.0.7", + "nsp": "^2.6.2", + "replace": "^0.3.0", + "semver": "^5.3.0", + "tape": "^4.6.3" + }, + "engines": { + "node": ">= 0.4" + }, + "homepage": "https://github.com/ljharb/is-regex", + "keywords": [ + "regex", + "regexp", + "is", + "regular expression", + "regular", + "expression" + ], + "license": "MIT", + "main": "index.js", + "name": "is-regex", + "repository": { + "type": "git", + "url": "git://github.com/ljharb/is-regex.git" + }, + "scripts": { + "coverage": "covert test.js", + "coverage-quiet": "covert test.js --quiet", + "eccheck": "editorconfig-tools check *.js **/*.js > /dev/null", + "eslint": "eslint test.js *.js", + "jscs": "jscs *.js", + "lint": "npm run jscs && npm run eslint", + "posttest": "npm run security", + "pretest": "npm run lint", + "security": "nsp check", + "test": "npm run tests-only", + "tests-only": "node --harmony --es-staging test.js" + }, + "testling": { + "files": "test.js", + "browsers": [ + "iexplore/6.0..latest", + "firefox/3.0..6.0", + "firefox/15.0..latest", + "firefox/nightly", + "chrome/4.0..10.0", + "chrome/20.0..latest", + "chrome/canary", + "opera/10.0..12.0", + "opera/15.0..latest", + "opera/next", + "safari/4.0..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2" + ] + }, + "version": "1.0.4" +} diff --git a/scripts/2.5/node_modules/is-regex/test.js b/scripts/2.5/node_modules/is-regex/test.js new file mode 100644 index 00000000..8d390038 --- /dev/null +++ b/scripts/2.5/node_modules/is-regex/test.js @@ -0,0 +1,58 @@ +'use strict'; + +var test = require('tape'); +var isRegex = require('./'); +var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol'; + +test('not regexes', function (t) { + t.notOk(isRegex(), 'undefined is not regex'); + t.notOk(isRegex(null), 'null is not regex'); + t.notOk(isRegex(false), 'false is not regex'); + t.notOk(isRegex(true), 'true is not regex'); + t.notOk(isRegex(42), 'number is not regex'); + t.notOk(isRegex('foo'), 'string is not regex'); + t.notOk(isRegex([]), 'array is not regex'); + t.notOk(isRegex({}), 'object is not regex'); + t.notOk(isRegex(function () {}), 'function is not regex'); + t.end(); +}); + +test('@@toStringTag', { skip: !hasToStringTag }, function (t) { + var regex = /a/g; + var fakeRegex = { + toString: function () { return String(regex); }, + valueOf: function () { return regex; } + }; + fakeRegex[Symbol.toStringTag] = 'RegExp'; + t.notOk(isRegex(fakeRegex), 'fake RegExp with @@toStringTag "RegExp" is not regex'); + t.end(); +}); + +test('regexes', function (t) { + t.ok(isRegex(/a/g), 'regex literal is regex'); + t.ok(isRegex(new RegExp('a', 'g')), 'regex object is regex'); + t.end(); +}); + +test('does not mutate regexes', function (t) { + t.test('lastIndex is a marker object', function (st) { + var regex = /a/; + var marker = {}; + regex.lastIndex = marker; + st.equal(regex.lastIndex, marker, 'lastIndex is the marker object'); + st.ok(isRegex(regex), 'is regex'); + st.equal(regex.lastIndex, marker, 'lastIndex is the marker object after isRegex'); + st.end(); + }); + + t.test('lastIndex is nonzero', function (st) { + var regex = /a/; + regex.lastIndex = 3; + st.equal(regex.lastIndex, 3, 'lastIndex is 3'); + st.ok(isRegex(regex), 'is regex'); + st.equal(regex.lastIndex, 3, 'lastIndex is 3 after isRegex'); + st.end(); + }); + + t.end(); +}); diff --git a/scripts/2.5/node_modules/is-symbol/.editorconfig b/scripts/2.5/node_modules/is-symbol/.editorconfig new file mode 100644 index 00000000..eaa21416 --- /dev/null +++ b/scripts/2.5/node_modules/is-symbol/.editorconfig @@ -0,0 +1,13 @@ +root = true + +[*] +indent_style = tab; +insert_final_newline = true; +quote_type = auto; +space_after_anonymous_functions = true; +space_after_control_statements = true; +spaces_around_operators = true; +trim_trailing_whitespace = true; +spaces_in_brackets = false; +end_of_line = lf; + diff --git a/scripts/2.5/node_modules/is-symbol/.eslintrc b/scripts/2.5/node_modules/is-symbol/.eslintrc new file mode 100644 index 00000000..5f511fd0 --- /dev/null +++ b/scripts/2.5/node_modules/is-symbol/.eslintrc @@ -0,0 +1,9 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "max-statements": [2, 14] + } +} diff --git a/scripts/2.5/node_modules/is-symbol/.jscs.json b/scripts/2.5/node_modules/is-symbol/.jscs.json new file mode 100644 index 00000000..b4d9b8b4 --- /dev/null +++ b/scripts/2.5/node_modules/is-symbol/.jscs.json @@ -0,0 +1,176 @@ +{ + "es3": true, + + "additionalRules": [], + + "requireSemicolons": true, + + "disallowMultipleSpaces": true, + + "disallowIdentifierNames": [], + + "requireCurlyBraces": { + "allExcept": [], + "keywords": ["if", "else", "for", "while", "do", "try", "catch"] + }, + + "requireSpaceAfterKeywords": ["if", "else", "for", "while", "do", "switch", "return", "try", "catch", "function"], + + "disallowSpaceAfterKeywords": [], + + "disallowSpaceBeforeComma": true, + "disallowSpaceAfterComma": false, + "disallowSpaceBeforeSemicolon": true, + + "disallowNodeTypes": [ + "DebuggerStatement", + "ForInStatement", + "LabeledStatement", + "SwitchCase", + "SwitchStatement", + "WithStatement" + ], + + "requireObjectKeysOnNewLine": { "allExcept": ["sameLine"] }, + + "requireSpacesInAnonymousFunctionExpression": { "beforeOpeningRoundBrace": true, "beforeOpeningCurlyBrace": true }, + "requireSpacesInNamedFunctionExpression": { "beforeOpeningCurlyBrace": true }, + "disallowSpacesInNamedFunctionExpression": { "beforeOpeningRoundBrace": true }, + "requireSpacesInFunctionDeclaration": { "beforeOpeningCurlyBrace": true }, + "disallowSpacesInFunctionDeclaration": { "beforeOpeningRoundBrace": true }, + + "requireSpaceBetweenArguments": true, + + "disallowSpacesInsideParentheses": true, + + "disallowSpacesInsideArrayBrackets": true, + + "disallowQuotedKeysInObjects": { "allExcept": ["reserved"] }, + + "disallowSpaceAfterObjectKeys": true, + + "requireCommaBeforeLineBreak": true, + + "disallowSpaceAfterPrefixUnaryOperators": ["++", "--", "+", "-", "~", "!"], + "requireSpaceAfterPrefixUnaryOperators": [], + + "disallowSpaceBeforePostfixUnaryOperators": ["++", "--"], + "requireSpaceBeforePostfixUnaryOperators": [], + + "disallowSpaceBeforeBinaryOperators": [], + "requireSpaceBeforeBinaryOperators": ["+", "-", "/", "*", "=", "==", "===", "!=", "!=="], + + "requireSpaceAfterBinaryOperators": ["+", "-", "/", "*", "=", "==", "===", "!=", "!=="], + "disallowSpaceAfterBinaryOperators": [], + + "disallowImplicitTypeConversion": ["binary", "string"], + + "disallowKeywords": ["with", "eval"], + + "requireKeywordsOnNewLine": [], + "disallowKeywordsOnNewLine": ["else"], + + "requireLineFeedAtFileEnd": true, + + "disallowTrailingWhitespace": true, + + "disallowTrailingComma": true, + + "excludeFiles": ["node_modules/**", "vendor/**"], + + "disallowMultipleLineStrings": true, + + "requireDotNotation": { "allExcept": ["keywords"] }, + + "requireParenthesesAroundIIFE": true, + + "validateLineBreaks": "LF", + + "validateQuoteMarks": { + "escape": true, + "mark": "'" + }, + + "disallowOperatorBeforeLineBreak": [], + + "requireSpaceBeforeKeywords": [ + "do", + "for", + "if", + "else", + "switch", + "case", + "try", + "catch", + "finally", + "while", + "with", + "return" + ], + + "validateAlignedFunctionParameters": { + "lineBreakAfterOpeningBraces": true, + "lineBreakBeforeClosingBraces": true + }, + + "requirePaddingNewLinesBeforeExport": true, + + "validateNewlineAfterArrayElements": { + "maximum": 1 + }, + + "requirePaddingNewLinesAfterUseStrict": true, + + "disallowArrowFunctions": true, + + "disallowMultiLineTernary": true, + + "validateOrderInObjectKeys": "asc-insensitive", + + "disallowIdenticalDestructuringNames": true, + + "disallowNestedTernaries": { "maxLevel": 1 }, + + "requireSpaceAfterComma": { "allExcept": ["trailing"] }, + "requireAlignedMultilineParams": false, + + "requireSpacesInGenerator": { + "afterStar": true + }, + + "disallowSpacesInGenerator": { + "beforeStar": true + }, + + "disallowVar": false, + + "requireArrayDestructuring": false, + + "requireEnhancedObjectLiterals": false, + + "requireObjectDestructuring": false, + + "requireEarlyReturn": false, + + "requireCapitalizedConstructorsNew": { + "allExcept": ["Function", "String", "Object", "Symbol", "Number", "Date", "RegExp", "Error", "Boolean", "Array"] + }, + + "requireImportAlphabetized": false, + + "requireSpaceBeforeObjectValues": true, + "requireSpaceBeforeDestructuredValues": true, + + "disallowSpacesInsideTemplateStringPlaceholders": true, + + "disallowArrayDestructuringReturn": false, + + "requireNewlineBeforeSingleStatementsInIf": false, + + "disallowUnusedVariables": true, + + "requireSpacesInsideImportedObjectBraces": true, + + "requireUseStrict": true +} + diff --git a/scripts/2.5/node_modules/is-symbol/.nvmrc b/scripts/2.5/node_modules/is-symbol/.nvmrc new file mode 100644 index 00000000..64f5a0a6 --- /dev/null +++ b/scripts/2.5/node_modules/is-symbol/.nvmrc @@ -0,0 +1 @@ +node diff --git a/scripts/2.5/node_modules/is-symbol/.travis.yml b/scripts/2.5/node_modules/is-symbol/.travis.yml new file mode 100644 index 00000000..c671d5ea --- /dev/null +++ b/scripts/2.5/node_modules/is-symbol/.travis.yml @@ -0,0 +1,241 @@ +language: node_js +os: + - linux +node_js: + - "10.11" + - "9.11" + - "8.12" + - "7.10" + - "6.14" + - "5.12" + - "4.9" + - "iojs-v3.3" + - "iojs-v2.5" + - "iojs-v1.8" + - "0.12" + - "0.10" + - "0.8" +before_install: + - 'case "${TRAVIS_NODE_VERSION}" in 0.*) export NPM_CONFIG_STRICT_SSL=false ;; esac' + - 'nvm install-latest-npm' +install: + - 'if [ "${TRAVIS_NODE_VERSION}" = "0.6" ] || [ "${TRAVIS_NODE_VERSION}" = "0.9" ]; then nvm install --latest-npm 0.8 && npm install && nvm use "${TRAVIS_NODE_VERSION}"; else npm install; fi;' +script: + - 'if [ -n "${PRETEST-}" ]; then npm run pretest ; fi' + - 'if [ -n "${POSTTEST-}" ]; then npm run posttest ; fi' + - 'if [ -n "${COVERAGE-}" ]; then npm run coverage ; fi' + - 'if [ -n "${TEST-}" ]; then npm run tests-only ; fi' +sudo: false +env: + - TEST=true +matrix: + fast_finish: true + include: + - node_js: "lts/*" + env: PRETEST=true + - node_js: "lts/*" + env: POSTTEST=true + - node_js: "4" + env: COVERAGE=true + - node_js: "10.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.13" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.12" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v3.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v3.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v3.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.4" + env: TEST=true ALLOW_FAILURE=true + allow_failures: + - os: osx + - env: TEST=true ALLOW_FAILURE=true + - env: COVERAGE=true diff --git a/scripts/2.5/node_modules/is-symbol/CHANGELOG.md b/scripts/2.5/node_modules/is-symbol/CHANGELOG.md new file mode 100644 index 00000000..a7b8baf8 --- /dev/null +++ b/scripts/2.5/node_modules/is-symbol/CHANGELOG.md @@ -0,0 +1,12 @@ +1.0.2 / 2018-09-20 +================= + * [Refactor] use `has-symbols` and `object-inspect` + * [Tests] test on all the node minor versions + +1.0.1 / 2015-01-26 +================= + * Corrected description + +1.0.0 / 2015-01-24 +================= + * Initial release diff --git a/scripts/2.5/node_modules/is-symbol/LICENSE b/scripts/2.5/node_modules/is-symbol/LICENSE new file mode 100644 index 00000000..b43df444 --- /dev/null +++ b/scripts/2.5/node_modules/is-symbol/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/scripts/2.5/node_modules/is-symbol/Makefile b/scripts/2.5/node_modules/is-symbol/Makefile new file mode 100644 index 00000000..b9e4fe1a --- /dev/null +++ b/scripts/2.5/node_modules/is-symbol/Makefile @@ -0,0 +1,61 @@ +# Since we rely on paths relative to the makefile location, abort if make isn't being run from there. +$(if $(findstring /,$(MAKEFILE_LIST)),$(error Please only invoke this makefile from the directory it resides in)) + + # The files that need updating when incrementing the version number. +VERSIONED_FILES := *.js *.json README* + + +# Add the local npm packages' bin folder to the PATH, so that `make` can find them, when invoked directly. +# Note that rather than using `$(npm bin)` the 'node_modules/.bin' path component is hard-coded, so that invocation works even from an environment +# where npm is (temporarily) unavailable due to having deactivated an nvm instance loaded into the calling shell in order to avoid interference with tests. +export PATH := $(shell printf '%s' "$$PWD/node_modules/.bin:$$PATH") +UTILS := semver +# Make sure that all required utilities can be located. +UTIL_CHECK := $(or $(shell PATH="$(PATH)" which $(UTILS) >/dev/null && echo 'ok'),$(error Did you forget to run `npm install` after cloning the repo? At least one of the required supporting utilities not found: $(UTILS))) + +# Default target (by virtue of being the first non '.'-prefixed in the file). +.PHONY: _no-target-specified +_no-target-specified: + $(error Please specify the target to make - `make list` shows targets. Alternatively, use `npm test` to run the default tests; `npm run` shows all tests) + +# Lists all targets defined in this makefile. +.PHONY: list +list: + @$(MAKE) -pRrn : -f $(MAKEFILE_LIST) 2>/dev/null | awk -v RS= -F: '/^# File/,/^# Finished Make data base/ {if ($$1 !~ "^[#.]") {print $$1}}' | command grep -v -e '^[^[:alnum:]]' -e '^$@$$command ' | sort + +# All-tests target: invokes the specified test suites for ALL shells defined in $(SHELLS). +.PHONY: test +test: + @npm test + +.PHONY: _ensure-tag +_ensure-tag: +ifndef TAG + $(error Please invoke with `make TAG= release`, where is either an increment specifier (patch, minor, major, prepatch, preminor, premajor, prerelease), or an explicit major.minor.patch version number) +endif + +CHANGELOG_ERROR = $(error No CHANGELOG specified) +.PHONY: _ensure-changelog +_ensure-changelog: + @ (git status -sb --porcelain | command grep -E '^( M|[MA] ) CHANGELOG.md' > /dev/null) || (echo no CHANGELOG.md specified && exit 2) + +# Ensures that the git workspace is clean. +.PHONY: _ensure-clean +_ensure-clean: + @[ -z "$$((git status --porcelain --untracked-files=no || echo err) | command grep -v 'CHANGELOG.md')" ] || { echo "Workspace is not clean; please commit changes first." >&2; exit 2; } + +# Makes a release; invoke with `make TAG= release`. +.PHONY: release +release: _ensure-tag _ensure-changelog _ensure-clean + @old_ver=`git describe --abbrev=0 --tags --match 'v[0-9]*.[0-9]*.[0-9]*'` || { echo "Failed to determine current version." >&2; exit 1; }; old_ver=$${old_ver#v}; \ + new_ver=`echo "$(TAG)" | sed 's/^v//'`; new_ver=$${new_ver:-patch}; \ + if printf "$$new_ver" | command grep -q '^[0-9]'; then \ + semver "$$new_ver" >/dev/null || { echo 'Invalid version number specified: $(TAG) - must be major.minor.patch' >&2; exit 2; }; \ + semver -r "> $$old_ver" "$$new_ver" >/dev/null || { echo 'Invalid version number specified: $(TAG) - must be HIGHER than current one.' >&2; exit 2; } \ + else \ + new_ver=`semver -i "$$new_ver" "$$old_ver"` || { echo 'Invalid version-increment specifier: $(TAG)' >&2; exit 2; } \ + fi; \ + printf "=== Bumping version **$$old_ver** to **$$new_ver** before committing and tagging:\n=== TYPE 'proceed' TO PROCEED, anything else to abort: " && read response && [ "$$response" = 'proceed' ] || { echo 'Aborted.' >&2; exit 2; }; \ + replace "$$old_ver" "$$new_ver" -- $(VERSIONED_FILES) && \ + git commit -m "v$$new_ver" $(VERSIONED_FILES) CHANGELOG.md && \ + git tag -a -m "v$$new_ver" "v$$new_ver" diff --git a/scripts/2.5/node_modules/is-symbol/README.md b/scripts/2.5/node_modules/is-symbol/README.md new file mode 100644 index 00000000..8544c8c0 --- /dev/null +++ b/scripts/2.5/node_modules/is-symbol/README.md @@ -0,0 +1,46 @@ +#is-symbol [![Version Badge][2]][1] + +[![Build Status][3]][4] +[![dependency status][5]][6] +[![dev dependency status][7]][8] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][11]][1] + +[![browser support][9]][10] + +Is this an ES6 Symbol value? + +## Example + +```js +var isSymbol = require('is-symbol'); +assert(!isSymbol(function () {})); +assert(!isSymbol(null)); +assert(!isSymbol(function* () { yield 42; return Infinity; }); + +assert(isSymbol(Symbol.iterator)); +assert(isSymbol(Symbol('foo'))); +assert(isSymbol(Symbol.for('foo'))); +assert(isSymbol(Object(Symbol('foo')))); +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[1]: https://npmjs.org/package/is-symbol +[2]: http://versionbadg.es/ljharb/is-symbol.svg +[3]: https://travis-ci.org/ljharb/is-symbol.svg +[4]: https://travis-ci.org/ljharb/is-symbol +[5]: https://david-dm.org/ljharb/is-symbol.svg +[6]: https://david-dm.org/ljharb/is-symbol +[7]: https://david-dm.org/ljharb/is-symbol/dev-status.svg +[8]: https://david-dm.org/ljharb/is-symbol#info=devDependencies +[9]: https://ci.testling.com/ljharb/is-symbol.png +[10]: https://ci.testling.com/ljharb/is-symbol +[11]: https://nodei.co/npm/is-symbol.png?downloads=true&stars=true +[license-image]: http://img.shields.io/npm/l/is-symbol.svg +[license-url]: LICENSE +[downloads-image]: http://img.shields.io/npm/dm/is-symbol.svg +[downloads-url]: http://npm-stat.com/charts.html?package=is-symbol diff --git a/scripts/2.5/node_modules/is-symbol/index.js b/scripts/2.5/node_modules/is-symbol/index.js new file mode 100644 index 00000000..3d653e27 --- /dev/null +++ b/scripts/2.5/node_modules/is-symbol/index.js @@ -0,0 +1,35 @@ +'use strict'; + +var toStr = Object.prototype.toString; +var hasSymbols = require('has-symbols')(); + +if (hasSymbols) { + var symToStr = Symbol.prototype.toString; + var symStringRegex = /^Symbol\(.*\)$/; + var isSymbolObject = function isRealSymbolObject(value) { + if (typeof value.valueOf() !== 'symbol') { + return false; + } + return symStringRegex.test(symToStr.call(value)); + }; + + module.exports = function isSymbol(value) { + if (typeof value === 'symbol') { + return true; + } + if (toStr.call(value) !== '[object Symbol]') { + return false; + } + try { + return isSymbolObject(value); + } catch (e) { + return false; + } + }; +} else { + + module.exports = function isSymbol(value) { + // this environment does not support Symbols. + return false && value; + }; +} diff --git a/scripts/2.5/node_modules/is-symbol/package.json b/scripts/2.5/node_modules/is-symbol/package.json new file mode 100644 index 00000000..ccab591a --- /dev/null +++ b/scripts/2.5/node_modules/is-symbol/package.json @@ -0,0 +1,96 @@ +{ + "_from": "is-symbol@^1.0.2", + "_id": "is-symbol@1.0.2", + "_inBundle": false, + "_integrity": "sha512-HS8bZ9ox60yCJLH9snBpIwv9pYUAkcuLhSA1oero1UB5y9aiQpRA8y2ex945AOtCZL1lJDeIk3G5LthswI46Lw==", + "_location": "/is-symbol", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "is-symbol@^1.0.2", + "name": "is-symbol", + "escapedName": "is-symbol", + "rawSpec": "^1.0.2", + "saveSpec": null, + "fetchSpec": "^1.0.2" + }, + "_requiredBy": [ + "/es-to-primitive" + ], + "_resolved": "https://registry.npmjs.org/is-symbol/-/is-symbol-1.0.2.tgz", + "_shasum": "a055f6ae57192caee329e7a860118b497a950f38", + "_spec": "is-symbol@^1.0.2", + "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/2.5/node_modules/es-to-primitive", + "author": { + "name": "Jordan Harband" + }, + "bugs": { + "url": "https://github.com/ljharb/is-symbol/issues" + }, + "bundleDependencies": false, + "dependencies": { + "has-symbols": "^1.0.0" + }, + "deprecated": false, + "description": "Determine if a value is an ES6 Symbol or not.", + "devDependencies": { + "@ljharb/eslint-config": "^12.2.1", + "covert": "^1.1.0", + "eslint": "^4.19.1", + "jscs": "^3.0.7", + "nsp": "^3.2.1", + "object-inspect": "^1.6.0", + "safe-publish-latest": "^1.1.2", + "semver": "^5.5.0", + "tape": "^4.9.0" + }, + "engines": { + "node": ">= 0.4" + }, + "homepage": "https://github.com/ljharb/is-symbol#readme", + "keywords": [ + "symbol", + "es6", + "is", + "Symbol" + ], + "license": "MIT", + "main": "index.js", + "name": "is-symbol", + "repository": { + "type": "git", + "url": "git://github.com/ljharb/is-symbol.git" + }, + "scripts": { + "coverage": "covert test", + "eslint": "eslint *.js */*.js", + "jscs": "jscs *.js */*.js", + "lint": "npm run jscs && npm run eslint", + "posttest": "npm run security", + "prepublish": "safe-publish-latest", + "pretest": "npm run lint", + "security": "nsp check", + "test": "npm run tests-only", + "tests-only": "node --es-staging --harmony test" + }, + "testling": { + "files": "test/index.js", + "browsers": [ + "iexplore/6.0..latest", + "firefox/3.0..6.0", + "firefox/15.0..latest", + "firefox/nightly", + "chrome/4.0..10.0", + "chrome/20.0..latest", + "chrome/canary", + "opera/10.0..latest", + "opera/next", + "safari/4.0..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2" + ] + }, + "version": "1.0.2" +} diff --git a/scripts/2.5/node_modules/is-symbol/test/.eslintrc b/scripts/2.5/node_modules/is-symbol/test/.eslintrc new file mode 100644 index 00000000..1ac0d47b --- /dev/null +++ b/scripts/2.5/node_modules/is-symbol/test/.eslintrc @@ -0,0 +1,7 @@ +{ + "rules": { + "max-statements-per-line": [2, { "max": 2 }], + "no-restricted-properties": 0, + "symbol-description": 0, + } +} diff --git a/scripts/2.5/node_modules/is-symbol/test/index.js b/scripts/2.5/node_modules/is-symbol/test/index.js new file mode 100644 index 00000000..e01f035c --- /dev/null +++ b/scripts/2.5/node_modules/is-symbol/test/index.js @@ -0,0 +1,92 @@ +'use strict'; + +var test = require('tape'); +var isSymbol = require('../index'); + +var forEach = function (arr, func) { + var i; + for (i = 0; i < arr.length; ++i) { + func(arr[i], i, arr); + } +}; + +var hasSymbols = require('has-symbols')(); +var inspect = require('object-inspect'); +var debug = function (v, m) { return inspect(v) + ' ' + m; }; + +test('non-symbol values', function (t) { + var nonSymbols = [ + true, + false, + Object(true), + Object(false), + null, + undefined, + {}, + [], + /a/g, + 'string', + 42, + new Date(), + function () {}, + NaN + ]; + t.plan(nonSymbols.length); + forEach(nonSymbols, function (nonSymbol) { + t.equal(false, isSymbol(nonSymbol), debug(nonSymbol, 'is not a symbol')); + }); + t.end(); +}); + +test('faked symbol values', function (t) { + t.test('real symbol valueOf', { skip: !hasSymbols }, function (st) { + var fakeSymbol = { valueOf: function () { return Symbol('foo'); } }; + st.equal(false, isSymbol(fakeSymbol), 'object with valueOf returning a symbol is not a symbol'); + st.end(); + }); + + t.test('faked @@toStringTag', { skip: !hasSymbols || !Symbol.toStringTag }, function (st) { + var fakeSymbol = { valueOf: function () { return Symbol('foo'); } }; + fakeSymbol[Symbol.toStringTag] = 'Symbol'; + st.equal(false, isSymbol(fakeSymbol), 'object with fake Symbol @@toStringTag and valueOf returning a symbol is not a symbol'); + var notSoFakeSymbol = { valueOf: function () { return 42; } }; + notSoFakeSymbol[Symbol.toStringTag] = 'Symbol'; + st.equal(false, isSymbol(notSoFakeSymbol), 'object with fake Symbol @@toStringTag and valueOf not returning a symbol is not a symbol'); + st.end(); + }); + + var fakeSymbolString = { toString: function () { return 'Symbol(foo)'; } }; + t.equal(false, isSymbol(fakeSymbolString), 'object with toString returning Symbol(foo) is not a symbol'); + + t.end(); +}); + +test('Symbol support', { skip: !hasSymbols }, function (t) { + t.test('well-known Symbols', function (st) { + var isWellKnown = function filterer(name) { + return name !== 'for' && name !== 'keyFor' && !(name in filterer); + }; + var wellKnownSymbols = Object.getOwnPropertyNames(Symbol).filter(isWellKnown); + wellKnownSymbols.forEach(function (name) { + var sym = Symbol[name]; + st.equal(true, isSymbol(sym), debug(sym, ' is a symbol')); + }); + st.end(); + }); + + t.test('user-created symbols', function (st) { + var symbols = [ + Symbol(), + Symbol('foo'), + Symbol['for']('foo'), + Object(Symbol('object')) + ]; + symbols.forEach(function (sym) { + st.equal(true, isSymbol(sym), debug(sym, ' is a symbol')); + }); + st.end(); + }); + + t.end(); +}); + diff --git a/scripts/2.5/node_modules/memory-pager/.travis.yml b/scripts/2.5/node_modules/memory-pager/.travis.yml new file mode 100644 index 00000000..1c4ab31e --- /dev/null +++ b/scripts/2.5/node_modules/memory-pager/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - '4' + - '6' diff --git a/scripts/2.5/node_modules/memory-pager/LICENSE b/scripts/2.5/node_modules/memory-pager/LICENSE new file mode 100644 index 00000000..56fce089 --- /dev/null +++ b/scripts/2.5/node_modules/memory-pager/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2017 Mathias Buus + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/scripts/2.5/node_modules/memory-pager/README.md b/scripts/2.5/node_modules/memory-pager/README.md new file mode 100644 index 00000000..aed17614 --- /dev/null +++ b/scripts/2.5/node_modules/memory-pager/README.md @@ -0,0 +1,65 @@ +# memory-pager + +Access memory using small fixed sized buffers instead of allocating a huge buffer. +Useful if you are implementing sparse data structures (such as large bitfield). + +![travis](https://travis-ci.org/mafintosh/memory-pager.svg?branch=master) + +``` +npm install memory-pager +``` + +## Usage + +``` js +var pager = require('paged-memory') + +var pages = pager(1024) // use 1kb per page + +var page = pages.get(10) // get page #10 + +console.log(page.offset) // 10240 +console.log(page.buffer) // a blank 1kb buffer +``` + +## API + +#### `var pages = pager(pageSize)` + +Create a new pager. `pageSize` defaults to `1024`. + +#### `var page = pages.get(pageNumber, [noAllocate])` + +Get a page. The page will be allocated at first access. + +Optionally you can set the `noAllocate` flag which will make the +method return undefined if no page has been allocated already + +A page looks like this + +``` js +{ + offset: byteOffset, + buffer: bufferWithPageSize +} +``` + +#### `pages.set(pageNumber, buffer)` + +Explicitly set the buffer for a page. + +#### `pages.updated(page)` + +Mark a page as updated. + +#### `pages.lastUpdate()` + +Get the last page that was updated. + +#### `var buf = pages.toBuffer()` + +Concat all pages allocated pages into a single buffer + +## License + +MIT diff --git a/scripts/2.5/node_modules/memory-pager/index.js b/scripts/2.5/node_modules/memory-pager/index.js new file mode 100644 index 00000000..687f346f --- /dev/null +++ b/scripts/2.5/node_modules/memory-pager/index.js @@ -0,0 +1,160 @@ +module.exports = Pager + +function Pager (pageSize, opts) { + if (!(this instanceof Pager)) return new Pager(pageSize, opts) + + this.length = 0 + this.updates = [] + this.path = new Uint16Array(4) + this.pages = new Array(32768) + this.maxPages = this.pages.length + this.level = 0 + this.pageSize = pageSize || 1024 + this.deduplicate = opts ? opts.deduplicate : null + this.zeros = this.deduplicate ? alloc(this.deduplicate.length) : null +} + +Pager.prototype.updated = function (page) { + while (this.deduplicate && page.buffer[page.deduplicate] === this.deduplicate[page.deduplicate]) { + page.deduplicate++ + if (page.deduplicate === this.deduplicate.length) { + page.deduplicate = 0 + if (page.buffer.equals && page.buffer.equals(this.deduplicate)) page.buffer = this.deduplicate + break + } + } + if (page.updated || !this.updates) return + page.updated = true + this.updates.push(page) +} + +Pager.prototype.lastUpdate = function () { + if (!this.updates || !this.updates.length) return null + var page = this.updates.pop() + page.updated = false + return page +} + +Pager.prototype._array = function (i, noAllocate) { + if (i >= this.maxPages) { + if (noAllocate) return + grow(this, i) + } + + factor(i, this.path) + + var arr = this.pages + + for (var j = this.level; j > 0; j--) { + var p = this.path[j] + var next = arr[p] + + if (!next) { + if (noAllocate) return + next = arr[p] = new Array(32768) + } + + arr = next + } + + return arr +} + +Pager.prototype.get = function (i, noAllocate) { + var arr = this._array(i, noAllocate) + var first = this.path[0] + var page = arr && arr[first] + + if (!page && !noAllocate) { + page = arr[first] = new Page(i, alloc(this.pageSize)) + if (i >= this.length) this.length = i + 1 + } + + if (page && page.buffer === this.deduplicate && this.deduplicate && !noAllocate) { + page.buffer = copy(page.buffer) + page.deduplicate = 0 + } + + return page +} + +Pager.prototype.set = function (i, buf) { + var arr = this._array(i, false) + var first = this.path[0] + + if (i >= this.length) this.length = i + 1 + + if (!buf || (this.zeros && buf.equals && buf.equals(this.zeros))) { + arr[first] = undefined + return + } + + if (this.deduplicate && buf.equals && buf.equals(this.deduplicate)) { + buf = this.deduplicate + } + + var page = arr[first] + var b = truncate(buf, this.pageSize) + + if (page) page.buffer = b + else arr[first] = new Page(i, b) +} + +Pager.prototype.toBuffer = function () { + var list = new Array(this.length) + var empty = alloc(this.pageSize) + var ptr = 0 + + while (ptr < list.length) { + var arr = this._array(ptr, true) + for (var i = 0; i < 32768 && ptr < list.length; i++) { + list[ptr++] = (arr && arr[i]) ? arr[i].buffer : empty + } + } + + return Buffer.concat(list) +} + +function grow (pager, index) { + while (pager.maxPages < index) { + var old = pager.pages + pager.pages = new Array(32768) + pager.pages[0] = old + pager.level++ + pager.maxPages *= 32768 + } +} + +function truncate (buf, len) { + if (buf.length === len) return buf + if (buf.length > len) return buf.slice(0, len) + var cpy = alloc(len) + buf.copy(cpy) + return cpy +} + +function alloc (size) { + if (Buffer.alloc) return Buffer.alloc(size) + var buf = new Buffer(size) + buf.fill(0) + return buf +} + +function copy (buf) { + var cpy = Buffer.allocUnsafe ? Buffer.allocUnsafe(buf.length) : new Buffer(buf.length) + buf.copy(cpy) + return cpy +} + +function Page (i, buf) { + this.offset = i * buf.length + this.buffer = buf + this.updated = false + this.deduplicate = 0 +} + +function factor (n, out) { + n = (n - (out[0] = (n & 32767))) / 32768 + n = (n - (out[1] = (n & 32767))) / 32768 + out[3] = ((n - (out[2] = (n & 32767))) / 32768) & 32767 +} diff --git a/scripts/2.5/node_modules/memory-pager/package.json b/scripts/2.5/node_modules/memory-pager/package.json new file mode 100644 index 00000000..4b40665a --- /dev/null +++ b/scripts/2.5/node_modules/memory-pager/package.json @@ -0,0 +1,52 @@ +{ + "_from": "memory-pager@^1.0.2", + "_id": "memory-pager@1.5.0", + "_inBundle": false, + "_integrity": "sha512-ZS4Bp4r/Zoeq6+NLJpP+0Zzm0pR8whtGPf1XExKLJBAczGMnSi3It14OiNCStjQjM6NU1okjQGSxgEZN8eBYKg==", + "_location": "/memory-pager", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "memory-pager@^1.0.2", + "name": "memory-pager", + "escapedName": "memory-pager", + "rawSpec": "^1.0.2", + "saveSpec": null, + "fetchSpec": "^1.0.2" + }, + "_requiredBy": [ + "/sparse-bitfield" + ], + "_resolved": "https://registry.npmjs.org/memory-pager/-/memory-pager-1.5.0.tgz", + "_shasum": "d8751655d22d384682741c972f2c3d6dfa3e66b5", + "_spec": "memory-pager@^1.0.2", + "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/2.5/node_modules/sparse-bitfield", + "author": { + "name": "Mathias Buus", + "url": "@mafintosh" + }, + "bugs": { + "url": "https://github.com/mafintosh/memory-pager/issues" + }, + "bundleDependencies": false, + "dependencies": {}, + "deprecated": false, + "description": "Access memory using small fixed sized buffers", + "devDependencies": { + "standard": "^9.0.0", + "tape": "^4.6.3" + }, + "homepage": "https://github.com/mafintosh/memory-pager", + "license": "MIT", + "main": "index.js", + "name": "memory-pager", + "repository": { + "type": "git", + "url": "git+https://github.com/mafintosh/memory-pager.git" + }, + "scripts": { + "test": "standard && tape test.js" + }, + "version": "1.5.0" +} diff --git a/scripts/2.5/node_modules/memory-pager/test.js b/scripts/2.5/node_modules/memory-pager/test.js new file mode 100644 index 00000000..16382100 --- /dev/null +++ b/scripts/2.5/node_modules/memory-pager/test.js @@ -0,0 +1,80 @@ +var tape = require('tape') +var pager = require('./') + +tape('get page', function (t) { + var pages = pager(1024) + + var page = pages.get(0) + + t.same(page.offset, 0) + t.same(page.buffer, Buffer.alloc(1024)) + t.end() +}) + +tape('get page twice', function (t) { + var pages = pager(1024) + t.same(pages.length, 0) + + var page = pages.get(0) + + t.same(page.offset, 0) + t.same(page.buffer, Buffer.alloc(1024)) + t.same(pages.length, 1) + + var other = pages.get(0) + + t.same(other, page) + t.end() +}) + +tape('get no mutable page', function (t) { + var pages = pager(1024) + + t.ok(!pages.get(141, true)) + t.ok(pages.get(141)) + t.ok(pages.get(141, true)) + + t.end() +}) + +tape('get far out page', function (t) { + var pages = pager(1024) + + var page = pages.get(1000000) + + t.same(page.offset, 1000000 * 1024) + t.same(page.buffer, Buffer.alloc(1024)) + t.same(pages.length, 1000000 + 1) + + var other = pages.get(1) + + t.same(other.offset, 1024) + t.same(other.buffer, Buffer.alloc(1024)) + t.same(pages.length, 1000000 + 1) + t.ok(other !== page) + + t.end() +}) + +tape('updates', function (t) { + var pages = pager(1024) + + t.same(pages.lastUpdate(), null) + + var page = pages.get(10) + + page.buffer[42] = 1 + pages.updated(page) + + t.same(pages.lastUpdate(), page) + t.same(pages.lastUpdate(), null) + + page.buffer[42] = 2 + pages.updated(page) + pages.updated(page) + + t.same(pages.lastUpdate(), page) + t.same(pages.lastUpdate(), null) + + t.end() +}) diff --git a/scripts/2.5/node_modules/mongodb/HISTORY.md b/scripts/2.5/node_modules/mongodb/HISTORY.md new file mode 100644 index 00000000..73cbab99 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/HISTORY.md @@ -0,0 +1,2485 @@ +# Change Log + +All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. + + +## [3.3.3](https://github.com/mongodb/node-mongodb-native/compare/v3.3.2...v3.3.3) (2019-10-16) + + +### Bug Fixes + +* **change_stream:** emit 'close' event if reconnecting failed ([f24c084](https://github.com/mongodb/node-mongodb-native/commit/f24c084)) +* **ChangeStream:** remove startAtOperationTime once we have resumeToken ([362afd8](https://github.com/mongodb/node-mongodb-native/commit/362afd8)) +* **connect:** Switch new Buffer(size) -> Buffer.alloc(size) ([da90c3a](https://github.com/mongodb/node-mongodb-native/commit/da90c3a)) +* **MongoClient:** only check own properties for valid options ([9cde4b9](https://github.com/mongodb/node-mongodb-native/commit/9cde4b9)) +* **mongos:** disconnect proxies which are not mongos instances ([ee53983](https://github.com/mongodb/node-mongodb-native/commit/ee53983)) +* **mongos:** force close servers during reconnect flow ([186263f](https://github.com/mongodb/node-mongodb-native/commit/186263f)) +* **monitoring:** correct spelling mistake for heartbeat event ([21aa117](https://github.com/mongodb/node-mongodb-native/commit/21aa117)) +* **replset:** correct server leak on initial connect ([da39d1e](https://github.com/mongodb/node-mongodb-native/commit/da39d1e)) +* **replset:** destroy primary before removing from replsetstate ([45ac09a](https://github.com/mongodb/node-mongodb-native/commit/45ac09a)) +* **replset:** destroy servers that are removed during SDAM flow ([9ea0190](https://github.com/mongodb/node-mongodb-native/commit/9ea0190)) +* **saslprep:** add in missing saslprep dependency ([41f1165](https://github.com/mongodb/node-mongodb-native/commit/41f1165)) +* **topology:** don't early abort server selection on network errors ([2b6a359](https://github.com/mongodb/node-mongodb-native/commit/2b6a359)) +* **topology:** don't emit server closed event on network error ([194dcf0](https://github.com/mongodb/node-mongodb-native/commit/194dcf0)) +* **topology:** include all BSON types in ctor for bson-ext support ([aa4c832](https://github.com/mongodb/node-mongodb-native/commit/aa4c832)) +* **topology:** respect the `force` parameter for topology close ([d6e8936](https://github.com/mongodb/node-mongodb-native/commit/d6e8936)) + +### Features + +* **Update:** add the ability to specify a pipeline to an update command ([#2017](https://github.com/mongodb/node-mongodb-native/issues/2017)) ([44a4110](https://github.com/mongodb/node-mongodb-native/commit/44a4110)) +* **urlParser:** default useNewUrlParser to true ([52d76e3](https://github.com/mongodb/node-mongodb-native/commit/52d76e3)) + + +## [3.2.7](https://github.com/mongodb/node-mongodb-native/compare/v3.2.6...v3.2.7) (2019-06-04) + + +### Bug Fixes + +* **core:** updating core to version 3.2.7 ([2f91466](https://github.com/mongodb/node-mongodb-native/commit/2f91466)) +* **findOneAndReplace:** throw error if atomic operators provided for findOneAndReplace ([6a860a3](https://github.com/mongodb/node-mongodb-native/commit/6a860a3)) + + + + +## [3.3.2](https://github.com/mongodb/node-mongodb-native/compare/v3.3.1...v3.3.2) (2019-08-28) + + +### Bug Fixes + +* **change-stream:** default to server default batch size ([b3ae4c5](https://github.com/mongodb/node-mongodb-native/commit/b3ae4c5)) +* **execute-operation:** return promise on session support check ([a976c14](https://github.com/mongodb/node-mongodb-native/commit/a976c14)) +* **gridfs-stream:** ensure `close` is emitted after last chunk ([ae94cb9](https://github.com/mongodb/node-mongodb-native/commit/ae94cb9)) + + + + +## [3.3.1](https://github.com/mongodb/node-mongodb-native/compare/v3.3.0...v3.3.1) (2019-08-23) + + +### Bug Fixes + +* **find:** respect client-level provided read preference ([fec4f15](https://github.com/mongodb/node-mongodb-native/commit/fec4f15)) +* correct inverted defaults for unified topology ([cf598e1](https://github.com/mongodb/node-mongodb-native/commit/cf598e1)) + + + + +# [3.3.0](https://github.com/mongodb/node-mongodb-native/compare/v3.3.0-alpha1...v3.3.0) (2019-08-13) + + +### Bug Fixes + +* **aggregate-operation:** move type assertions to constructor ([25b27ff](https://github.com/mongodb/node-mongodb-native/commit/25b27ff)) +* **autoEncryption:** tear down mongocryptd client when main client closes ([fe2f57e](https://github.com/mongodb/node-mongodb-native/commit/fe2f57e)) +* **autoEncryption:** use new url parser for autoEncryption client ([d3670c2](https://github.com/mongodb/node-mongodb-native/commit/d3670c2)) +* **Bulk:** change BulkWriteError message to first item from writeErrors ([#2013](https://github.com/mongodb/node-mongodb-native/issues/2013)) ([6bcf1e4](https://github.com/mongodb/node-mongodb-native/commit/6bcf1e4)) +* **change_stream:** emit 'close' event if reconnecting failed ([41aba90](https://github.com/mongodb/node-mongodb-native/commit/41aba90)) +* **change_stream:** emit close event after cursor is closed during error ([c2d80b2](https://github.com/mongodb/node-mongodb-native/commit/c2d80b2)) +* **change-streams:** don't copy irrelevant resume options ([f190072](https://github.com/mongodb/node-mongodb-native/commit/f190072)) +* **changestream:** removes all event listeners on close ([30eeeb5](https://github.com/mongodb/node-mongodb-native/commit/30eeeb5)) +* **ChangeStream:** remove startAtOperationTime once we have resumeToken ([8d27e6e](https://github.com/mongodb/node-mongodb-native/commit/8d27e6e)) +* **ClientSessions:** initialize clientOptions and cluster time ([b95d64e](https://github.com/mongodb/node-mongodb-native/commit/b95d64e)) +* **connect:** don't treat 'connect' as an error event ([170a011](https://github.com/mongodb/node-mongodb-native/commit/170a011)) +* **connect:** fixed syntax issue in connect error handler ([ff7166d](https://github.com/mongodb/node-mongodb-native/commit/ff7166d)) +* **connections_stepdown_tests:** use correct version of mongo for tests ([ce2c9af](https://github.com/mongodb/node-mongodb-native/commit/ce2c9af)) +* **createCollection:** Db.createCollection should pass readConcern to new collection ([#2026](https://github.com/mongodb/node-mongodb-native/issues/2026)) ([6145d4b](https://github.com/mongodb/node-mongodb-native/commit/6145d4b)) +* **cursor:** do not truncate an existing Long ([317055b](https://github.com/mongodb/node-mongodb-native/commit/317055b)), closes [mongodb-js/mongodb-core#441](https://github.com/mongodb-js/mongodb-core/issues/441) +* **distinct:** return full response if `full` option was specified ([95a7d05](https://github.com/mongodb/node-mongodb-native/commit/95a7d05)) +* **MongoClient:** allow Object.prototype items as db names ([dc6fc37](https://github.com/mongodb/node-mongodb-native/commit/dc6fc37)) +* **MongoClient:** only check own properties for valid options ([c9dc717](https://github.com/mongodb/node-mongodb-native/commit/c9dc717)) +* **OpMsg:** cap requestIds at 0x7fffffff ([c0e87d5](https://github.com/mongodb/node-mongodb-native/commit/c0e87d5)) +* **read-operations:** send sessions on all read operations ([4d45c8a](https://github.com/mongodb/node-mongodb-native/commit/4d45c8a)) +* **ReadPreference:** improve ReadPreference error message and remove irrelevant sharding test ([dd34ce4](https://github.com/mongodb/node-mongodb-native/commit/dd34ce4)) +* **ReadPreference:** only allow valid ReadPreference modes ([06bbef2](https://github.com/mongodb/node-mongodb-native/commit/06bbef2)) +* **replset:** correct legacy max staleness calculation ([2eab8aa](https://github.com/mongodb/node-mongodb-native/commit/2eab8aa)) +* **replset:** introduce a fixed-time server selection loop ([cf53299](https://github.com/mongodb/node-mongodb-native/commit/cf53299)) +* **server:** emit "first connect" error if initial connect fails due to ECONNREFUSED ([#2016](https://github.com/mongodb/node-mongodb-native/issues/2016)) ([5a7b15b](https://github.com/mongodb/node-mongodb-native/commit/5a7b15b)) +* **serverSelection:** make sure to pass session to serverSelection ([eb5cc6b](https://github.com/mongodb/node-mongodb-native/commit/eb5cc6b)) +* **sessions:** ensure an error is thrown when attempting sharded transactions ([3a1fdc1](https://github.com/mongodb/node-mongodb-native/commit/3a1fdc1)) +* **topology:** add new error for retryWrites on MMAPv1 ([392f5a6](https://github.com/mongodb/node-mongodb-native/commit/392f5a6)) +* don't check non-unified topologies for session support check ([2bccd3f](https://github.com/mongodb/node-mongodb-native/commit/2bccd3f)) +* maintain internal database name on collection rename ([884d46f](https://github.com/mongodb/node-mongodb-native/commit/884d46f)) +* only check for transaction state if session exists ([360975a](https://github.com/mongodb/node-mongodb-native/commit/360975a)) +* preserve aggregate explain support for legacy servers ([032b204](https://github.com/mongodb/node-mongodb-native/commit/032b204)) +* read concern only supported for `mapReduce` without inline ([51a36f3](https://github.com/mongodb/node-mongodb-native/commit/51a36f3)) +* reintroduce support for 2.6 listIndexes ([c3bfc05](https://github.com/mongodb/node-mongodb-native/commit/c3bfc05)) +* return `executeOperation` for explain, if promise is desired ([b4a7ad7](https://github.com/mongodb/node-mongodb-native/commit/b4a7ad7)) +* validate atomic operations in all update methods ([88bb77e](https://github.com/mongodb/node-mongodb-native/commit/88bb77e)) +* **transactions:** fix error message for attempting sharded ([eb5dfc9](https://github.com/mongodb/node-mongodb-native/commit/eb5dfc9)) +* **transactions:** fix sharded transaction error logic ([083e18a](https://github.com/mongodb/node-mongodb-native/commit/083e18a)) + + +### Features + +* **Aggregate:** support ReadConcern in aggregates with $out ([21cdcf0](https://github.com/mongodb/node-mongodb-native/commit/21cdcf0)) +* **AutoEncryption:** improve error message for missing mongodb-client-encryption ([583f29f](https://github.com/mongodb/node-mongodb-native/commit/583f29f)) +* **ChangeStream:** adds new resume functionality to ChangeStreams ([9ec9b8f](https://github.com/mongodb/node-mongodb-native/commit/9ec9b8f)) +* **ChangeStreamCursor:** introduce new cursor type for change streams ([8813eb0](https://github.com/mongodb/node-mongodb-native/commit/8813eb0)) +* **cryptdConnectionString:** makes mongocryptd uri configurable ([#2049](https://github.com/mongodb/node-mongodb-native/issues/2049)) ([a487be4](https://github.com/mongodb/node-mongodb-native/commit/a487be4)) +* **eachAsync:** dedupe async iteration with a common helper ([c296f3a](https://github.com/mongodb/node-mongodb-native/commit/c296f3a)) +* **execute-operation:** allow execution with server selection ([36bc1fd](https://github.com/mongodb/node-mongodb-native/commit/36bc1fd)) +* **pool:** add support for resetting the connection pool ([2d1ff40](https://github.com/mongodb/node-mongodb-native/commit/2d1ff40)) +* **sessions:** track dirty state of sessions, drop after use ([f61df16](https://github.com/mongodb/node-mongodb-native/commit/f61df16)) +* add concept of `data-bearing` type to `ServerDescription` ([852e14f](https://github.com/mongodb/node-mongodb-native/commit/852e14f)) +* **transaction:** allow applications to set maxTimeMS for commitTransaction ([b3948aa](https://github.com/mongodb/node-mongodb-native/commit/b3948aa)) +* **Update:** add the ability to specify a pipeline to an update command ([#2017](https://github.com/mongodb/node-mongodb-native/issues/2017)) ([dc1387e](https://github.com/mongodb/node-mongodb-native/commit/dc1387e)) +* add `known`, `data-bearing` filters to `TopologyDescription` ([d0ccb56](https://github.com/mongodb/node-mongodb-native/commit/d0ccb56)) +* perform selection before cursor operation execution if needed ([808cf37](https://github.com/mongodb/node-mongodb-native/commit/808cf37)) +* perform selection before operation execution if needed ([1a25876](https://github.com/mongodb/node-mongodb-native/commit/1a25876)) +* support explain operations in `CommandOperationV2` ([86f5ba5](https://github.com/mongodb/node-mongodb-native/commit/86f5ba5)) +* support operations passed to a `Cursor` or subclass ([b78bb89](https://github.com/mongodb/node-mongodb-native/commit/b78bb89)) + + + + +## [3.2.7](https://github.com/mongodb/node-mongodb-native/compare/v3.2.6...v3.2.7) (2019-06-04) + + +### Bug Fixes + +* **core:** updating core to version 3.2.7 ([2f91466](https://github.com/mongodb/node-mongodb-native/commit/2f91466)) +* **findOneAndReplace:** throw error if atomic operators provided for findOneAndReplace ([6a860a3](https://github.com/mongodb/node-mongodb-native/commit/6a860a3)) + + + + +## [3.2.6](https://github.com/mongodb/node-mongodb-native/compare/v3.2.5...v3.2.6) (2019-05-24) + + + + +## [3.2.5](https://github.com/mongodb/node-mongodb-native/compare/v3.2.4...v3.2.5) (2019-05-17) + + +### Bug Fixes + +* **core:** updating core to 3.2.5 ([a2766c1](https://github.com/mongodb/node-mongodb-native/commit/a2766c1)) + + + + +## [3.2.4](https://github.com/mongodb/node-mongodb-native/compare/v3.2.2...v3.2.4) (2019-05-08) + + +### Bug Fixes + +* **aggregation:** fix field name typo ([4235d04](https://github.com/mongodb/node-mongodb-native/commit/4235d04)) +* **async:** rewrote asyncGenerator in node < 10 syntax ([49c8cef](https://github.com/mongodb/node-mongodb-native/commit/49c8cef)) +* **BulkOp:** run unordered bulk ops in serial ([f548bd7](https://github.com/mongodb/node-mongodb-native/commit/f548bd7)) +* **bulkWrite:** fix issue with bulkWrite continuing w/ callback ([2a4a42c](https://github.com/mongodb/node-mongodb-native/commit/2a4a42c)) +* **docs:** correctly document that default for `sslValidate` is false ([1f8e7fa](https://github.com/mongodb/node-mongodb-native/commit/1f8e7fa)) +* **gridfs-stream:** honor chunk size ([9eeb114](https://github.com/mongodb/node-mongodb-native/commit/9eeb114)) +* **unified-topology:** only clone pool size if provided ([8dc2416](https://github.com/mongodb/node-mongodb-native/commit/8dc2416)) + + +### Features + +* update to mongodb-core v3.2.3 ([1c5357a](https://github.com/mongodb/node-mongodb-native/commit/1c5357a)) +* **core:** update to mongodb-core v3.2.4 ([2059260](https://github.com/mongodb/node-mongodb-native/commit/2059260)) +* **lib:** implement executeOperationV2 ([67d4edf](https://github.com/mongodb/node-mongodb-native/commit/67d4edf)) + + + + +## [3.2.3](https://github.com/mongodb/node-mongodb-native/compare/v3.2.2...v3.2.3) (2019-04-05) + + +### Bug Fixes + +* **aggregation:** fix field name typo ([4235d04](https://github.com/mongodb/node-mongodb-native/commit/4235d04)) +* **async:** rewrote asyncGenerator in node < 10 syntax ([49c8cef](https://github.com/mongodb/node-mongodb-native/commit/49c8cef)) +* **bulkWrite:** fix issue with bulkWrite continuing w/ callback ([2a4a42c](https://github.com/mongodb/node-mongodb-native/commit/2a4a42c)) +* **docs:** correctly document that default for `sslValidate` is false ([1f8e7fa](https://github.com/mongodb/node-mongodb-native/commit/1f8e7fa)) + + +### Features + +* update to mongodb-core v3.2.3 ([1c5357a](https://github.com/mongodb/node-mongodb-native/commit/1c5357a)) + + + + +## [3.2.2](https://github.com/mongodb/node-mongodb-native/compare/v3.2.1...v3.2.2) (2019-03-22) + + +### Bug Fixes + +* **asyncIterator:** stronger guard against importing async generator ([e0826fb](https://github.com/mongodb/node-mongodb-native/commit/e0826fb)) + + +### Features + +* update to mongodb-core v3.2.2 ([868cfc3](https://github.com/mongodb/node-mongodb-native/commit/868cfc3)) + + + + +## [3.2.1](https://github.com/mongodb/node-mongodb-native/compare/v3.2.0...v3.2.1) (2019-03-21) + + +### Features + +* **core:** update to mongodb-core v3.2.1 ([30b0100](https://github.com/mongodb/node-mongodb-native/commit/30b0100)) + + + + +# [3.2.0](https://github.com/mongodb/node-mongodb-native/compare/v3.1.13...v3.2.0) (2019-03-21) + + +### Bug Fixes + +* **aggregate:** do not send batchSize for aggregation with $out ([ddb8d90](https://github.com/mongodb/node-mongodb-native/commit/ddb8d90)) +* **bulkWrite:** always count undefined values in bson size for bulk ([436d340](https://github.com/mongodb/node-mongodb-native/commit/436d340)) +* **db_ops:** rename db to add user on ([79931af](https://github.com/mongodb/node-mongodb-native/commit/79931af)) +* **mongo_client_ops:** only skip authentication if no authMechanism is specified ([3b6957d](https://github.com/mongodb/node-mongodb-native/commit/3b6957d)) +* **mongo-client:** ensure close callback is called with client ([f39e881](https://github.com/mongodb/node-mongodb-native/commit/f39e881)) + + +### Features + +* **core:** pin to mongodb-core v3.2.0 ([22af15a](https://github.com/mongodb/node-mongodb-native/commit/22af15a)) +* **Cursor:** adds support for AsyncIterator in cursors ([b972c1e](https://github.com/mongodb/node-mongodb-native/commit/b972c1e)) +* **db:** add database-level aggregation ([b629b21](https://github.com/mongodb/node-mongodb-native/commit/b629b21)) +* **mongo-client:** remove deprecated `logout` and print warning ([542859d](https://github.com/mongodb/node-mongodb-native/commit/542859d)) +* **topology-base:** support passing callbacks to `close` method ([7c111e0](https://github.com/mongodb/node-mongodb-native/commit/7c111e0)) +* **transactions:** support pinning mongos for sharded txns ([3886127](https://github.com/mongodb/node-mongodb-native/commit/3886127)) +* **unified-sdam:** backport unified SDAM to master for v3.2.0 ([79f33ca](https://github.com/mongodb/node-mongodb-native/commit/79f33ca)) + + + + +## [3.1.13](https://github.com/mongodb/node-mongodb-native/compare/v3.1.12...v3.1.13) (2019-01-23) + + +### Bug Fixes + +* restore ability to webpack by removing `makeLazyLoader` ([050267d](https://github.com/mongodb/node-mongodb-native/commit/050267d)) +* **bulk:** honor ignoreUndefined in initializeUnorderedBulkOp ([e806be4](https://github.com/mongodb/node-mongodb-native/commit/e806be4)) +* **changeStream:** properly handle changeStream event mid-close ([#1902](https://github.com/mongodb/node-mongodb-native/issues/1902)) ([5ad9fa9](https://github.com/mongodb/node-mongodb-native/commit/5ad9fa9)) +* **db_ops:** ensure we async resolve errors in createCollection ([210c71d](https://github.com/mongodb/node-mongodb-native/commit/210c71d)) + + + + +## [3.1.12](https://github.com/mongodb/node-mongodb-native/compare/v3.1.11...v3.1.12) (2019-01-16) + + +### Features + +* **core:** update to mongodb-core v3.1.11 ([9bef6e7](https://github.com/mongodb/node-mongodb-native/commit/9bef6e7)) + + + + +## [3.1.11](https://github.com/mongodb/node-mongodb-native/compare/v3.1.10...v3.1.11) (2019-01-15) + + +### Bug Fixes + +* **bulk:** fix error propagation in empty bulk.execute ([a3adb3f](https://github.com/mongodb/node-mongodb-native/commit/a3adb3f)) +* **bulk:** make sure that any error in bulk write is propagated ([bedc2d2](https://github.com/mongodb/node-mongodb-native/commit/bedc2d2)) +* **bulk:** properly calculate batch size for bulk writes ([aafe71b](https://github.com/mongodb/node-mongodb-native/commit/aafe71b)) +* **operations:** do not call require in a hot path ([ff82ff4](https://github.com/mongodb/node-mongodb-native/commit/ff82ff4)) + + + + +## [3.1.10](https://github.com/mongodb/node-mongodb-native/compare/v3.1.9...v3.1.10) (2018-11-16) + + +### Bug Fixes + +* **auth:** remember to default to admin database ([c7dec28](https://github.com/mongodb/node-mongodb-native/commit/c7dec28)) + + +### Features + +* **core:** update to mongodb-core v3.1.9 ([bd3355b](https://github.com/mongodb/node-mongodb-native/commit/bd3355b)) + + + + +## [3.1.9](https://github.com/mongodb/node-mongodb-native/compare/v3.1.8...v3.1.9) (2018-11-06) + + +### Bug Fixes + +* **db:** move db constants to other file to avoid circular ref ([#1858](https://github.com/mongodb/node-mongodb-native/issues/1858)) ([239036f](https://github.com/mongodb/node-mongodb-native/commit/239036f)) +* **estimated-document-count:** support options other than maxTimeMs ([36c3c7d](https://github.com/mongodb/node-mongodb-native/commit/36c3c7d)) + + +### Features + +* **core:** update to mongodb-core v3.1.8 ([80d7c79](https://github.com/mongodb/node-mongodb-native/commit/80d7c79)) + + + + +## [3.1.8](https://github.com/mongodb/node-mongodb-native/compare/v3.1.7...v3.1.8) (2018-10-10) + + +### Bug Fixes + +* **connect:** use reported default databse from new uri parser ([811f8f8](https://github.com/mongodb/node-mongodb-native/commit/811f8f8)) + + +### Features + +* **core:** update to mongodb-core v3.1.7 ([dbfc905](https://github.com/mongodb/node-mongodb-native/commit/dbfc905)) + + + + +## [3.1.7](https://github.com/mongodb/node-mongodb-native/compare/v3.1.6...v3.1.7) (2018-10-09) + + +### Features + +* **core:** update mongodb-core to v3.1.6 ([61b054e](https://github.com/mongodb/node-mongodb-native/commit/61b054e)) + + + + +## [3.1.6](https://github.com/mongodb/node-mongodb-native/compare/v3.1.5...v3.1.6) (2018-09-15) + + +### Features + +* **core:** update to core v3.1.5 ([c5f823d](https://github.com/mongodb/node-mongodb-native/commit/c5f823d)) + + + + +## [3.1.5](https://github.com/mongodb/node-mongodb-native/compare/v3.1.4...v3.1.5) (2018-09-14) + + +### Bug Fixes + +* **cursor:** allow `$meta` based sort when passing an array to `sort()` ([f93a8c3](https://github.com/mongodb/node-mongodb-native/commit/f93a8c3)) +* **utils:** only set retryWrites to true for valid operations ([3b725ef](https://github.com/mongodb/node-mongodb-native/commit/3b725ef)) + + +### Features + +* **core:** bump core to v3.1.4 ([805d58a](https://github.com/mongodb/node-mongodb-native/commit/805d58a)) + + + + +## [3.1.4](https://github.com/mongodb/node-mongodb-native/compare/v3.1.3...v3.1.4) (2018-08-25) + + +### Bug Fixes + +* **buffer:** use safe-buffer polyfill to maintain compatibility ([327da95](https://github.com/mongodb/node-mongodb-native/commit/327da95)) +* **change-stream:** properly support resumablity in stream mode ([c43a34b](https://github.com/mongodb/node-mongodb-native/commit/c43a34b)) +* **connect:** correct replacement of topology on connect callback ([918a1e0](https://github.com/mongodb/node-mongodb-native/commit/918a1e0)) +* **cursor:** remove deprecated notice on forEach ([a474158](https://github.com/mongodb/node-mongodb-native/commit/a474158)) +* **url-parser:** bail early on validation when using domain socket ([3cb3da3](https://github.com/mongodb/node-mongodb-native/commit/3cb3da3)) + + +### Features + +* **client-ops:** allow bypassing creation of topologies on connect ([fe39b93](https://github.com/mongodb/node-mongodb-native/commit/fe39b93)) +* **core:** update mongodb-core to 3.1.3 ([a029047](https://github.com/mongodb/node-mongodb-native/commit/a029047)) +* **test:** use connection strings for all calls to `newClient` ([1dac18f](https://github.com/mongodb/node-mongodb-native/commit/1dac18f)) + + + + +## [3.1.3](https://github.com/mongodb/node-mongodb-native/compare/v3.1.2...v3.1.3) (2018-08-13) + + +### Features + +* **core:** update to mongodb-core 3.1.2 ([337cb79](https://github.com/mongodb/node-mongodb-native/commit/337cb79)) + + + + +## [3.1.2](https://github.com/mongodb/node-mongodb-native/compare/v3.0.6...v3.1.2) (2018-08-13) + + +### Bug Fixes + +* **aggregate:** support user-provided `batchSize` ([ad10dee](https://github.com/mongodb/node-mongodb-native/commit/ad10dee)) +* **buffer:** replace deprecated Buffer constructor ([759dd85](https://github.com/mongodb/node-mongodb-native/commit/759dd85)) +* **bulk:** fixing retryable writes for mass-change ops ([0604036](https://github.com/mongodb/node-mongodb-native/commit/0604036)) +* **bulk:** handle MongoWriteConcernErrors ([12ff392](https://github.com/mongodb/node-mongodb-native/commit/12ff392)) +* **change_stream:** do not check isGetMore if error[mongoErrorContextSymbol] is undefined ([#1720](https://github.com/mongodb/node-mongodb-native/issues/1720)) ([844c2c8](https://github.com/mongodb/node-mongodb-native/commit/844c2c8)) +* **change-stream:** fix change stream resuming with promises ([3063f00](https://github.com/mongodb/node-mongodb-native/commit/3063f00)) +* **client-ops:** return transform map to map rather than function ([cfb7d83](https://github.com/mongodb/node-mongodb-native/commit/cfb7d83)) +* **collection:** correctly shallow clone passed in options ([7727700](https://github.com/mongodb/node-mongodb-native/commit/7727700)) +* **collection:** countDocuments throws error when query doesn't match docs ([09c7d8e](https://github.com/mongodb/node-mongodb-native/commit/09c7d8e)) +* **collection:** depend on `resolveReadPreference` for inheritance ([a649e35](https://github.com/mongodb/node-mongodb-native/commit/a649e35)) +* **collection:** ensure findAndModify always use readPreference primary ([86344f4](https://github.com/mongodb/node-mongodb-native/commit/86344f4)) +* **collection:** isCapped returns false instead of undefined ([b8471f1](https://github.com/mongodb/node-mongodb-native/commit/b8471f1)) +* **collection:** only send bypassDocumentValidation if true ([fdb828b](https://github.com/mongodb/node-mongodb-native/commit/fdb828b)) +* **count-documents:** return callback on error case ([fca1185](https://github.com/mongodb/node-mongodb-native/commit/fca1185)) +* **cursor:** cursor count with collation fix ([71879c3](https://github.com/mongodb/node-mongodb-native/commit/71879c3)) +* **cursor:** cursor hasNext returns false when exhausted ([184b817](https://github.com/mongodb/node-mongodb-native/commit/184b817)) +* **cursor:** cursor.count not respecting parent readPreference ([5a9fdf0](https://github.com/mongodb/node-mongodb-native/commit/5a9fdf0)) +* **cursor:** set readPreference for cursor.count ([13d776f](https://github.com/mongodb/node-mongodb-native/commit/13d776f)) +* **db:** don't send session down to createIndex command ([559c195](https://github.com/mongodb/node-mongodb-native/commit/559c195)) +* **db:** throw readable error when creating `_id` with background: true ([b3ff3ed](https://github.com/mongodb/node-mongodb-native/commit/b3ff3ed)) +* **db_ops:** call collection.find() with correct parameters ([#1795](https://github.com/mongodb/node-mongodb-native/issues/1795)) ([36e92f1](https://github.com/mongodb/node-mongodb-native/commit/36e92f1)) +* **db_ops:** fix two incorrectly named variables ([15dc808](https://github.com/mongodb/node-mongodb-native/commit/15dc808)) +* **findOneAndUpdate:** ensure that update documents contain atomic operators ([eb68074](https://github.com/mongodb/node-mongodb-native/commit/eb68074)) +* **index:** export MongoNetworkError ([98ab29e](https://github.com/mongodb/node-mongodb-native/commit/98ab29e)) +* **mongo_client:** translate options for connectWithUrl ([78f6977](https://github.com/mongodb/node-mongodb-native/commit/78f6977)) +* **mongo-client:** pass arguments to ctor when new keyword is used ([d6c3417](https://github.com/mongodb/node-mongodb-native/commit/d6c3417)) +* **mongos:** bubble up close events after the first one ([#1713](https://github.com/mongodb/node-mongodb-native/issues/1713)) ([3e91d77](https://github.com/mongodb/node-mongodb-native/commit/3e91d77)), closes [Automattic/mongoose#6249](https://github.com/Automattic/mongoose/issues/6249) [#1685](https://github.com/mongodb/node-mongodb-native/issues/1685) +* **parallelCollectionScan:** do not use implicit sessions on cursors ([2de470a](https://github.com/mongodb/node-mongodb-native/commit/2de470a)) +* **retryWrites:** fixes more bulk ops to not use retryWrites ([69e5254](https://github.com/mongodb/node-mongodb-native/commit/69e5254)) +* **server:** remove unnecessary print statement ([2bcbc12](https://github.com/mongodb/node-mongodb-native/commit/2bcbc12)) +* **teardown:** properly destroy a topology when initial connect fails ([b8d2f1d](https://github.com/mongodb/node-mongodb-native/commit/b8d2f1d)) +* **topology-base:** sending `endSessions` is always skipped now ([a276cbe](https://github.com/mongodb/node-mongodb-native/commit/a276cbe)) +* **txns:** omit writeConcern when in a transaction ([b88c938](https://github.com/mongodb/node-mongodb-native/commit/b88c938)) +* **utils:** restructure inheritance rules for read preferences ([6a7dac1](https://github.com/mongodb/node-mongodb-native/commit/6a7dac1)) + + +### Features + +* **auth:** add support for SCRAM-SHA-256 ([f53195d](https://github.com/mongodb/node-mongodb-native/commit/f53195d)) +* **changeStream:** Adding new 4.0 ChangeStream features ([2cb4894](https://github.com/mongodb/node-mongodb-native/commit/2cb4894)) +* **changeStream:** allow resuming on getMore errors ([4ba5adc](https://github.com/mongodb/node-mongodb-native/commit/4ba5adc)) +* **changeStream:** expanding changeStream resumable errors ([49fbafd](https://github.com/mongodb/node-mongodb-native/commit/49fbafd)) +* **ChangeStream:** update default startAtOperationTime ([50a9f65](https://github.com/mongodb/node-mongodb-native/commit/50a9f65)) +* **collection:** add colleciton level document mapping/unmapping ([d03335e](https://github.com/mongodb/node-mongodb-native/commit/d03335e)) +* **collection:** Implement new count API ([a5240ae](https://github.com/mongodb/node-mongodb-native/commit/a5240ae)) +* **Collection:** warn if callback is not function in find and findOne ([cddaba0](https://github.com/mongodb/node-mongodb-native/commit/cddaba0)) +* **core:** bump core dependency to v3.1.0 ([4937240](https://github.com/mongodb/node-mongodb-native/commit/4937240)) +* **cursor:** new cursor.transformStream method ([397fcd2](https://github.com/mongodb/node-mongodb-native/commit/397fcd2)) +* **deprecation:** create deprecation function ([4f907a0](https://github.com/mongodb/node-mongodb-native/commit/4f907a0)) +* **deprecation:** wrap deprecated functions ([a5d0f1d](https://github.com/mongodb/node-mongodb-native/commit/a5d0f1d)) +* **GridFS:** add option to disable md5 in file upload ([704a88e](https://github.com/mongodb/node-mongodb-native/commit/704a88e)) +* **listCollections:** add support for nameOnly option ([d2d0367](https://github.com/mongodb/node-mongodb-native/commit/d2d0367)) +* **parallelCollectionScan:** does not allow user to pass a session ([4da9e03](https://github.com/mongodb/node-mongodb-native/commit/4da9e03)) +* **read-preference:** add transaction to inheritance rules ([18ca41d](https://github.com/mongodb/node-mongodb-native/commit/18ca41d)) +* **read-preference:** unify means of read preference resolution ([#1738](https://github.com/mongodb/node-mongodb-native/issues/1738)) ([2995e11](https://github.com/mongodb/node-mongodb-native/commit/2995e11)) +* **urlParser:** use core URL parser ([c1c5d8d](https://github.com/mongodb/node-mongodb-native/commit/c1c5d8d)) +* **withSession:** add top level helper for session lifetime ([9976b86](https://github.com/mongodb/node-mongodb-native/commit/9976b86)) + + +### Reverts + +* **collection:** reverting collection-mapping features ([7298c76](https://github.com/mongodb/node-mongodb-native/commit/7298c76)), closes [#1698](https://github.com/mongodb/node-mongodb-native/issues/1698) [mongodb/js-bson#253](https://github.com/mongodb/js-bson/issues/253) + + + + +## [3.1.1](https://github.com/mongodb/node-mongodb-native/compare/v3.1.0...v3.1.1) (2018-07-05) + + +### Bug Fixes + +* **client-ops:** return transform map to map rather than function ([b8b4bfa](https://github.com/mongodb/node-mongodb-native/commit/b8b4bfa)) +* **collection:** correctly shallow clone passed in options ([2e6c4fa](https://github.com/mongodb/node-mongodb-native/commit/2e6c4fa)) +* **collection:** countDocuments throws error when query doesn't match docs ([4e83556](https://github.com/mongodb/node-mongodb-native/commit/4e83556)) +* **server:** remove unnecessary print statement ([20e11b3](https://github.com/mongodb/node-mongodb-native/commit/20e11b3)) + + + + +# [3.1.0](https://github.com/mongodb/node-mongodb-native/compare/v3.0.6...v3.1.0) (2018-06-27) + + +### Bug Fixes + +* **aggregate:** support user-provided `batchSize` ([ad10dee](https://github.com/mongodb/node-mongodb-native/commit/ad10dee)) +* **bulk:** fixing retryable writes for mass-change ops ([0604036](https://github.com/mongodb/node-mongodb-native/commit/0604036)) +* **bulk:** handle MongoWriteConcernErrors ([12ff392](https://github.com/mongodb/node-mongodb-native/commit/12ff392)) +* **change_stream:** do not check isGetMore if error[mongoErrorContextSymbol] is undefined ([#1720](https://github.com/mongodb/node-mongodb-native/issues/1720)) ([844c2c8](https://github.com/mongodb/node-mongodb-native/commit/844c2c8)) +* **change-stream:** fix change stream resuming with promises ([3063f00](https://github.com/mongodb/node-mongodb-native/commit/3063f00)) +* **collection:** depend on `resolveReadPreference` for inheritance ([a649e35](https://github.com/mongodb/node-mongodb-native/commit/a649e35)) +* **collection:** only send bypassDocumentValidation if true ([fdb828b](https://github.com/mongodb/node-mongodb-native/commit/fdb828b)) +* **cursor:** cursor count with collation fix ([71879c3](https://github.com/mongodb/node-mongodb-native/commit/71879c3)) +* **cursor:** cursor hasNext returns false when exhausted ([184b817](https://github.com/mongodb/node-mongodb-native/commit/184b817)) +* **cursor:** cursor.count not respecting parent readPreference ([5a9fdf0](https://github.com/mongodb/node-mongodb-native/commit/5a9fdf0)) +* **db:** don't send session down to createIndex command ([559c195](https://github.com/mongodb/node-mongodb-native/commit/559c195)) +* **db:** throw readable error when creating `_id` with background: true ([b3ff3ed](https://github.com/mongodb/node-mongodb-native/commit/b3ff3ed)) +* **findOneAndUpdate:** ensure that update documents contain atomic operators ([eb68074](https://github.com/mongodb/node-mongodb-native/commit/eb68074)) +* **index:** export MongoNetworkError ([98ab29e](https://github.com/mongodb/node-mongodb-native/commit/98ab29e)) +* **mongo-client:** pass arguments to ctor when new keyword is used ([d6c3417](https://github.com/mongodb/node-mongodb-native/commit/d6c3417)) +* **mongos:** bubble up close events after the first one ([#1713](https://github.com/mongodb/node-mongodb-native/issues/1713)) ([3e91d77](https://github.com/mongodb/node-mongodb-native/commit/3e91d77)), closes [Automattic/mongoose#6249](https://github.com/Automattic/mongoose/issues/6249) [#1685](https://github.com/mongodb/node-mongodb-native/issues/1685) +* **parallelCollectionScan:** do not use implicit sessions on cursors ([2de470a](https://github.com/mongodb/node-mongodb-native/commit/2de470a)) +* **retryWrites:** fixes more bulk ops to not use retryWrites ([69e5254](https://github.com/mongodb/node-mongodb-native/commit/69e5254)) +* **topology-base:** sending `endSessions` is always skipped now ([a276cbe](https://github.com/mongodb/node-mongodb-native/commit/a276cbe)) +* **txns:** omit writeConcern when in a transaction ([b88c938](https://github.com/mongodb/node-mongodb-native/commit/b88c938)) +* **utils:** restructure inheritance rules for read preferences ([6a7dac1](https://github.com/mongodb/node-mongodb-native/commit/6a7dac1)) + + +### Features + +* **auth:** add support for SCRAM-SHA-256 ([f53195d](https://github.com/mongodb/node-mongodb-native/commit/f53195d)) +* **changeStream:** Adding new 4.0 ChangeStream features ([2cb4894](https://github.com/mongodb/node-mongodb-native/commit/2cb4894)) +* **changeStream:** allow resuming on getMore errors ([4ba5adc](https://github.com/mongodb/node-mongodb-native/commit/4ba5adc)) +* **changeStream:** expanding changeStream resumable errors ([49fbafd](https://github.com/mongodb/node-mongodb-native/commit/49fbafd)) +* **ChangeStream:** update default startAtOperationTime ([50a9f65](https://github.com/mongodb/node-mongodb-native/commit/50a9f65)) +* **collection:** add colleciton level document mapping/unmapping ([d03335e](https://github.com/mongodb/node-mongodb-native/commit/d03335e)) +* **collection:** Implement new count API ([a5240ae](https://github.com/mongodb/node-mongodb-native/commit/a5240ae)) +* **Collection:** warn if callback is not function in find and findOne ([cddaba0](https://github.com/mongodb/node-mongodb-native/commit/cddaba0)) +* **core:** bump core dependency to v3.1.0 ([855bfdb](https://github.com/mongodb/node-mongodb-native/commit/855bfdb)) +* **cursor:** new cursor.transformStream method ([397fcd2](https://github.com/mongodb/node-mongodb-native/commit/397fcd2)) +* **GridFS:** add option to disable md5 in file upload ([704a88e](https://github.com/mongodb/node-mongodb-native/commit/704a88e)) +* **listCollections:** add support for nameOnly option ([d2d0367](https://github.com/mongodb/node-mongodb-native/commit/d2d0367)) +* **parallelCollectionScan:** does not allow user to pass a session ([4da9e03](https://github.com/mongodb/node-mongodb-native/commit/4da9e03)) +* **read-preference:** add transaction to inheritance rules ([18ca41d](https://github.com/mongodb/node-mongodb-native/commit/18ca41d)) +* **read-preference:** unify means of read preference resolution ([#1738](https://github.com/mongodb/node-mongodb-native/issues/1738)) ([2995e11](https://github.com/mongodb/node-mongodb-native/commit/2995e11)) +* **urlParser:** use core URL parser ([c1c5d8d](https://github.com/mongodb/node-mongodb-native/commit/c1c5d8d)) +* **withSession:** add top level helper for session lifetime ([9976b86](https://github.com/mongodb/node-mongodb-native/commit/9976b86)) + + +### Reverts + +* **collection:** reverting collection-mapping features ([7298c76](https://github.com/mongodb/node-mongodb-native/commit/7298c76)), closes [#1698](https://github.com/mongodb/node-mongodb-native/issues/1698) [mongodb/js-bson#253](https://github.com/mongodb/js-bson/issues/253) + + + + +## [3.0.6](https://github.com/mongodb/node-mongodb-native/compare/v3.0.5...v3.0.6) (2018-04-09) + + +### Bug Fixes + +* **db:** ensure `dropDatabase` always uses primary read preference ([e62e5c9](https://github.com/mongodb/node-mongodb-native/commit/e62e5c9)) +* **driverBench:** driverBench has default options object now ([c557817](https://github.com/mongodb/node-mongodb-native/commit/c557817)) + + +### Features + +* **command-monitoring:** support enabling command monitoring ([5903680](https://github.com/mongodb/node-mongodb-native/commit/5903680)) +* **core:** update to mongodb-core v3.0.6 ([cfdd0ae](https://github.com/mongodb/node-mongodb-native/commit/cfdd0ae)) +* **driverBench:** Implementing DriverBench ([d10fbad](https://github.com/mongodb/node-mongodb-native/commit/d10fbad)) + + + + +## [3.0.5](https://github.com/mongodb/node-mongodb-native/compare/v3.0.4...v3.0.5) (2018-03-23) + + +### Bug Fixes + +* **AggregationCursor:** adding session tracking to AggregationCursor ([baca5b7](https://github.com/mongodb/node-mongodb-native/commit/baca5b7)) +* **Collection:** fix session leak in parallelCollectonScan ([3331ec9](https://github.com/mongodb/node-mongodb-native/commit/3331ec9)) +* **comments:** adding fixes for PR comments ([ee110ac](https://github.com/mongodb/node-mongodb-native/commit/ee110ac)) +* **url_parser:** support a default database on mongodb+srv uris ([6d39b2a](https://github.com/mongodb/node-mongodb-native/commit/6d39b2a)) + + +### Features + +* **sessions:** adding implicit cursor session support ([a81245b](https://github.com/mongodb/node-mongodb-native/commit/a81245b)) + + + + +## [3.0.4](https://github.com/mongodb/node-mongodb-native/compare/v3.0.2...v3.0.4) (2018-03-05) + + +### Bug Fixes + +* **collection:** fix error when calling remove with no args ([#1657](https://github.com/mongodb/node-mongodb-native/issues/1657)) ([4c9b0f8](https://github.com/mongodb/node-mongodb-native/commit/4c9b0f8)) +* **executeOperation:** don't mutate options passed to commands ([934a43a](https://github.com/mongodb/node-mongodb-native/commit/934a43a)) +* **jsdoc:** mark db.collection callback as optional + typo fix ([#1658](https://github.com/mongodb/node-mongodb-native/issues/1658)) ([c519b9b](https://github.com/mongodb/node-mongodb-native/commit/c519b9b)) +* **sessions:** move active session tracking to topology base ([#1665](https://github.com/mongodb/node-mongodb-native/issues/1665)) ([b1f296f](https://github.com/mongodb/node-mongodb-native/commit/b1f296f)) +* **utils:** fixes executeOperation to clean up sessions ([04e6ef6](https://github.com/mongodb/node-mongodb-native/commit/04e6ef6)) + + +### Features + +* **default-db:** use dbName from uri if none provided ([23b1938](https://github.com/mongodb/node-mongodb-native/commit/23b1938)) +* **mongodb-core:** update to mongodb-core 3.0.4 ([1fdbaa5](https://github.com/mongodb/node-mongodb-native/commit/1fdbaa5)) + + + + +## [3.0.3](https://github.com/mongodb/node-mongodb-native/compare/v3.0.2...v3.0.3) (2018-02-23) + + +### Bug Fixes + +* **collection:** fix error when calling remove with no args ([#1657](https://github.com/mongodb/node-mongodb-native/issues/1657)) ([4c9b0f8](https://github.com/mongodb/node-mongodb-native/commit/4c9b0f8)) +* **executeOperation:** don't mutate options passed to commands ([934a43a](https://github.com/mongodb/node-mongodb-native/commit/934a43a)) +* **jsdoc:** mark db.collection callback as optional + typo fix ([#1658](https://github.com/mongodb/node-mongodb-native/issues/1658)) ([c519b9b](https://github.com/mongodb/node-mongodb-native/commit/c519b9b)) +* **sessions:** move active session tracking to topology base ([#1665](https://github.com/mongodb/node-mongodb-native/issues/1665)) ([b1f296f](https://github.com/mongodb/node-mongodb-native/commit/b1f296f)) + + + + +## [3.0.2](https://github.com/mongodb/node-mongodb-native/compare/v3.0.1...v3.0.2) (2018-01-29) + + +### Bug Fixes + +* **collection:** ensure dynamic require of `db` is wrapped in parentheses ([efa78f0](https://github.com/mongodb/node-mongodb-native/commit/efa78f0)) +* **db:** only callback with MongoError NODE-1293 ([#1652](https://github.com/mongodb/node-mongodb-native/issues/1652)) ([45bc722](https://github.com/mongodb/node-mongodb-native/commit/45bc722)) +* **topology base:** allow more than 10 event listeners ([#1630](https://github.com/mongodb/node-mongodb-native/issues/1630)) ([d9fb750](https://github.com/mongodb/node-mongodb-native/commit/d9fb750)) +* **url parser:** preserve auth creds when composing conn string ([#1640](https://github.com/mongodb/node-mongodb-native/issues/1640)) ([eddca5e](https://github.com/mongodb/node-mongodb-native/commit/eddca5e)) + + +### Features + +* **bulk:** forward 'checkKeys' option for ordered and unordered bulk operations ([421a6b2](https://github.com/mongodb/node-mongodb-native/commit/421a6b2)) +* **collection:** expose `dbName` property of collection ([6fd05c1](https://github.com/mongodb/node-mongodb-native/commit/6fd05c1)) + + + + +## [3.0.1](https://github.com/mongodb/node-mongodb-native/compare/v3.0.0...v3.0.1) (2017-12-24) + +* update mongodb-core to 3.0.1 + + +# [3.0.0](https://github.com/mongodb/node-mongodb-native/compare/v3.0.0-rc0...v3.0.0) (2017-12-24) + + +### Bug Fixes + +* **aggregate:** remove support for inline results for aggregate ([#1620](https://github.com/mongodb/node-mongodb-native/issues/1620)) ([84457ec](https://github.com/mongodb/node-mongodb-native/commit/84457ec)) +* **topologies:** unify topologies connect API ([#1615](https://github.com/mongodb/node-mongodb-native/issues/1615)) ([0fb4658](https://github.com/mongodb/node-mongodb-native/commit/0fb4658)) + + +### Features + +* **keepAlive:** make keepAlive options consistent ([#1612](https://github.com/mongodb/node-mongodb-native/issues/1612)) ([f608f44](https://github.com/mongodb/node-mongodb-native/commit/f608f44)) + + +### BREAKING CHANGES + +* **topologies:** Function signature for `.connect` method on replset and mongos has changed. You shouldn't have been using this anyway, but if you were, you only should pass `options` and `callback`. + +Part of NODE-1089 +* **keepAlive:** option `keepAlive` is now split into boolean `keepAlive` and +number `keepAliveInitialDelay` + +Fixes NODE-998 + + + + +# [3.0.0-rc0](https://github.com/mongodb/node-mongodb-native/compare/v2.2.31...v3.0.0-rc0) (2017-12-05) + + +### Bug Fixes + +* **aggregation:** ensure that the `cursor` key is always present ([f16f314](https://github.com/mongodb/node-mongodb-native/commit/f16f314)) +* **apm:** give users access to raw server responses ([88b206b](https://github.com/mongodb/node-mongodb-native/commit/88b206b)) +* **apm:** only rebuilt cursor if reply is non-null ([96052c8](https://github.com/mongodb/node-mongodb-native/commit/96052c8)) +* **apm:** rebuild lost `cursor` info on pre-OP_QUERY responses ([4242d49](https://github.com/mongodb/node-mongodb-native/commit/4242d49)) +* **bulk-unordered:** add check for ignoreUndefined ([f38641a](https://github.com/mongodb/node-mongodb-native/commit/f38641a)) +* **change stream examples:** use timeouts, cleanup ([c5fec5f](https://github.com/mongodb/node-mongodb-native/commit/c5fec5f)) +* **change-streams:** ensure a majority read concern on initial agg ([23011e9](https://github.com/mongodb/node-mongodb-native/commit/23011e9)) +* **changeStreams:** fixing node4 issue with util.inherits ([#1587](https://github.com/mongodb/node-mongodb-native/issues/1587)) ([168bb3d](https://github.com/mongodb/node-mongodb-native/commit/168bb3d)) +* **collection:** allow { upsert: 1 } for findOneAndUpdate() and update() ([5bcedd6](https://github.com/mongodb/node-mongodb-native/commit/5bcedd6)) +* **collection:** allow passing `noCursorTimeout` as an option to `find()` ([e9c4ffc](https://github.com/mongodb/node-mongodb-native/commit/e9c4ffc)) +* **collection:** make the parameters of findOne very explicit ([3054f1a](https://github.com/mongodb/node-mongodb-native/commit/3054f1a)) +* **cursor:** `hasNext` should propagate errors when using callback ([6339625](https://github.com/mongodb/node-mongodb-native/commit/6339625)) +* **cursor:** close readable on `null` response for dead cursor ([6aca2c5](https://github.com/mongodb/node-mongodb-native/commit/6aca2c5)) +* **dns txt records:** check options are set ([e5caf4f](https://github.com/mongodb/node-mongodb-native/commit/e5caf4f)) +* **docs:** Represent each valid option in docs in both places ([fde6e5d](https://github.com/mongodb/node-mongodb-native/commit/fde6e5d)) +* **grid-store:** add missing callback ([66a9a05](https://github.com/mongodb/node-mongodb-native/commit/66a9a05)) +* **grid-store:** move into callback scope ([b53f65f](https://github.com/mongodb/node-mongodb-native/commit/b53f65f)) +* **GridFS:** fix TypeError: doc.data.length is not a function ([#1570](https://github.com/mongodb/node-mongodb-native/issues/1570)) ([22a4628](https://github.com/mongodb/node-mongodb-native/commit/22a4628)) +* **list-collections:** ensure default of primary ReadPreference ([4a0cfeb](https://github.com/mongodb/node-mongodb-native/commit/4a0cfeb)) +* **mongo client:** close client before calling done ([c828aab](https://github.com/mongodb/node-mongodb-native/commit/c828aab)) +* **mongo client:** do not connect if url parse error ([cd10084](https://github.com/mongodb/node-mongodb-native/commit/cd10084)) +* **mongo client:** send error to cb ([eafc9e2](https://github.com/mongodb/node-mongodb-native/commit/eafc9e2)) +* **mongo-client:** move to inside of callback ([68b0fca](https://github.com/mongodb/node-mongodb-native/commit/68b0fca)) +* **mongo-client:** options should not be passed to `connect` ([474ac65](https://github.com/mongodb/node-mongodb-native/commit/474ac65)) +* **tests:** migrate 2.x tests to 3.x ([3a5232a](https://github.com/mongodb/node-mongodb-native/commit/3a5232a)) +* **updateOne/updateMany:** ensure that update documents contain atomic operators ([8b4255a](https://github.com/mongodb/node-mongodb-native/commit/8b4255a)) +* **url parser:** add check for options as cb ([52b6039](https://github.com/mongodb/node-mongodb-native/commit/52b6039)) +* **url parser:** compare srv address and parent domains ([daa186d](https://github.com/mongodb/node-mongodb-native/commit/daa186d)) +* **url parser:** compare string from first period on ([9e5d77e](https://github.com/mongodb/node-mongodb-native/commit/9e5d77e)) +* **url parser:** default to ssl true for mongodb+srv ([0fbca4b](https://github.com/mongodb/node-mongodb-native/commit/0fbca4b)) +* **url parser:** error when multiple hostnames used ([c1aa681](https://github.com/mongodb/node-mongodb-native/commit/c1aa681)) +* **url parser:** keep original uri options and default to ssl true ([e876a72](https://github.com/mongodb/node-mongodb-native/commit/e876a72)) +* **url parser:** log instead of throw error for unsupported url options ([155de2d](https://github.com/mongodb/node-mongodb-native/commit/155de2d)) +* **url parser:** make sure uri has 3 parts ([aa9871b](https://github.com/mongodb/node-mongodb-native/commit/aa9871b)) +* **url parser:** only 1 txt record allowed with 2 possible options ([d9f4218](https://github.com/mongodb/node-mongodb-native/commit/d9f4218)) +* **url parser:** only check for multiple hostnames with srv protocol ([5542bcc](https://github.com/mongodb/node-mongodb-native/commit/5542bcc)) +* **url parser:** remove .only from test ([642e39e](https://github.com/mongodb/node-mongodb-native/commit/642e39e)) +* **url parser:** return callback ([6096afc](https://github.com/mongodb/node-mongodb-native/commit/6096afc)) +* **url parser:** support single text record with multiple strings ([356fa57](https://github.com/mongodb/node-mongodb-native/commit/356fa57)) +* **url parser:** try catch bug, not actually returning from try loop ([758892b](https://github.com/mongodb/node-mongodb-native/commit/758892b)) +* **url parser:** use warn instead of info ([40ed27d](https://github.com/mongodb/node-mongodb-native/commit/40ed27d)) +* **url-parser:** remove comment, send error to cb ([d44420b](https://github.com/mongodb/node-mongodb-native/commit/d44420b)) + + +### Features + +* **aggregate:** support hit field for aggregate command ([aa7da15](https://github.com/mongodb/node-mongodb-native/commit/aa7da15)) +* **aggregation:** adds support for comment in aggregation command ([#1571](https://github.com/mongodb/node-mongodb-native/issues/1571)) ([4ac475c](https://github.com/mongodb/node-mongodb-native/commit/4ac475c)) +* **aggregation:** fail aggregation on explain + readConcern/writeConcern ([e0ca1b4](https://github.com/mongodb/node-mongodb-native/commit/e0ca1b4)) +* **causal-consistency:** support `afterClusterTime` in readConcern ([a9097f7](https://github.com/mongodb/node-mongodb-native/commit/a9097f7)) +* **change-streams:** add support for change streams ([c02d25c](https://github.com/mongodb/node-mongodb-native/commit/c02d25c)) +* **collection:** updating find API ([f26362d](https://github.com/mongodb/node-mongodb-native/commit/f26362d)) +* **execute-operation:** implementation for common op execution ([67c344f](https://github.com/mongodb/node-mongodb-native/commit/67c344f)) +* **listDatabases:** add support for nameOnly option to listDatabases ([eb79b5a](https://github.com/mongodb/node-mongodb-native/commit/eb79b5a)) +* **maxTimeMS:** adding maxTimeMS option to createIndexes and dropIndexes ([90d4a63](https://github.com/mongodb/node-mongodb-native/commit/90d4a63)) +* **mongo-client:** implement `MongoClient.prototype.startSession` ([bce5adf](https://github.com/mongodb/node-mongodb-native/commit/bce5adf)) +* **retryable-writes:** add support for `retryWrites` cs option ([2321870](https://github.com/mongodb/node-mongodb-native/commit/2321870)) +* **sessions:** MongoClient will now track sessions and release ([6829f47](https://github.com/mongodb/node-mongodb-native/commit/6829f47)) +* **sessions:** support passing sessions via objects in all methods ([a531f05](https://github.com/mongodb/node-mongodb-native/commit/a531f05)) +* **shared:** add helper utilities for assertion and suite setup ([b6cc34e](https://github.com/mongodb/node-mongodb-native/commit/b6cc34e)) +* **ssl:** adds missing ssl options ssl options for `ciphers` and `ecdhCurve` ([441b7b1](https://github.com/mongodb/node-mongodb-native/commit/441b7b1)) +* **test-shared:** add `notEqual` assertion ([41d93fd](https://github.com/mongodb/node-mongodb-native/commit/41d93fd)) +* **test-shared:** add `strictEqual` assertion method ([cad8e19](https://github.com/mongodb/node-mongodb-native/commit/cad8e19)) +* **topologies:** expose underlaying `logicalSessionTimeoutMinutes' ([1609a37](https://github.com/mongodb/node-mongodb-native/commit/1609a37)) +* **url parser:** better error message for slash in hostname ([457bc29](https://github.com/mongodb/node-mongodb-native/commit/457bc29)) + + +### BREAKING CHANGES + +* **aggregation:** If you use aggregation, and try to use the explain flag while you +have a readConcern or writeConcern, your query will fail +* **collection:** `find` and `findOne` no longer support the `fields` parameter. +You can achieve the same results as the `fields` parameter by +either using `Cursor.prototype.project`, or by passing the `projection` +property in on the `options` object. Additionally, `find` does not +support individual options like `skip` and `limit` as positional +parameters. You must pass in these parameters in the `options` object + + + +3.0.0 2017-??-?? +---------------- +* NODE-1043 URI-escaping authentication and hostname details in connection string + +2.2.31 2017-08-08 +----------------- +* update mongodb-core to 2.2.15 +* allow auth option in MongoClient.connect +* remove duplicate option `promoteLongs` from MongoClient's `connect` +* bulk operations should not throw an error on empty batch + +2.2.30 2017-07-07 +----------------- +* Update mongodb-core to 2.2.14 +* MongoClient + * add `appname` to list of valid option names + * added test for passing appname as option +* NODE-1052 ensure user options are applied while parsing connection string uris + +2.2.29 2017-06-19 +----------------- +* Update mongodb-core to 2.1.13 + * NODE-1039 ensure we force destroy server instances, forcing queue to be flushed. + * Use actual server type in standalone SDAM events. +* Allow multiple map calls (Issue #1521, https://github.com/Robbilie). +* Clone insertMany options before mutating (Issue #1522, https://github.com/vkarpov15). +* NODE-1034 Fix GridStore issue caused by Node 8.0.0 breaking backward compatible fs.read API. +* NODE-1026, use operator instead of skip function in order to avoid useless fetch stage. + +2.2.28 2017-06-02 +----------------- +* Update mongodb-core to 2.1.12 + * NODE-1019 Set keepAlive to 300 seconds or 1/2 of socketTimeout if socketTimeout < keepAlive. + * Minor fix to report the correct state on error. + * NODE-1020 'family' was added to options to provide high priority for ipv6 addresses (Issue #1518, https://github.com/firej). + * Fix require_optional loading of bson-ext. + * Ensure no errors are thrown by replset if topology is destroyed before it finished connecting. + * NODE-999 SDAM fixes for Mongos and single Server event emitting. + * NODE-1014 Set socketTimeout to default to 360 seconds. + * NODE-1019 Set keepAlive to 300 seconds or 1/2 of socketTimeout if socketTimeout < keepAlive. +* Just handle Collection name errors distinctly from general callback errors avoiding double callbacks in Db.collection. +* NODE-999 SDAM fixes for Mongos and single Server event emitting. +* NODE-1000 Added guard condition for upload.js checkDone function in case of race condition caused by late arriving chunk write. + +2.2.27 2017-05-22 +----------------- +* Updated mongodb-core to 2.1.11 + * NODE-987 Clear out old intervalIds on when calling topologyMonitor. + * NODE-987 Moved filtering to pingServer method and added test case. + * Check for connection destroyed just before writing out and flush out operations correctly if it is (Issue #179, https://github.com/jmholzinger). + * NODE-989 Refactored Replicaset monitoring to correcly monitor newly added servers, Also extracted setTimeout and setInterval to use custom wrappers Timeout and Interval. +* NODE-985 Deprecated Db.authenticate and Admin.authenticate and moved auth methods into authenticate.js to ensure MongoClient.connect does not print deprecation warnings. +* NODE-988 Merged readConcern and hint correctly on collection(...).find(...).count() +* Fix passing the readConcern option to MongoClient.connect (Issue #1514, https://github.com/bausmeier). +* NODE-996 Propegate all events up to a MongoClient instance. +* Allow saving doc with null `_id` (Issue #1517, https://github.com/vkarpov15). +* NODE-993 Expose hasNext for command cursor and add docs for both CommandCursor and Aggregation Cursor. + +2.2.26 2017-04-18 +----------------- +* Updated mongodb-core to 2.1.10 + * NODE-981 delegate auth to replset/mongos if inTopology is set. + * NODE-978 Wrap connection.end in try/catch for node 0.10.x issue causing exceptions to be thrown, Also surfaced getConnection for mongos and replset. + * Remove dynamic require (Issue #175, https://github.com/tellnes). + * NODE-696 Handle interrupted error for createIndexes. + * Fixed isse when user is executing find command using Server.command and it get interpreted as a wire protcol message, #172. + * NODE-966 promoteValues not being promoted correctly to getMore. + * Merged in fix for flushing out monitoring operations. +* NODE-983 Add cursorId to aggregate and listCollections commands (Issue, #1510). +* Mark group and profilingInfo as deprecated methods +* NODE-956 DOCS Examples. +* Update readable-stream to version 2.2.7. +* NODE-978 Added test case to uncover connection.end issue for node 0.10.x. +* NODE-972 Fix(db): don't remove database name if collectionName == dbName (Issue, #1502) +* Fixed merging of writeConcerns on db.collection method. +* NODE-970 mix in readPreference for strict mode listCollections callback. +* NODE-966 added testcase for promoteValues being applied to getMore commands. +* NODE-962 Merge in ignoreUndefined from collection level for find/findOne. +* Remove multi option from updateMany tests/docs (Issue #1499, https://github.com/spratt). +* NODE-963 Correctly handle cursor.count when using APM. + +2.2.25 2017-03-17 +----------------- +* Don't rely on global toString() for checking if object (Issue #1494, https://github.com/vkarpov15). +* Remove obsolete option uri_decode_auth (Issue #1488, https://github.com/kamagatos). +* NODE-936 Correctly translate ReadPreference to CoreReadPreference for mongos queries. +* Exposed BSONRegExp type. +* NODE-950 push correct index for INSERT ops (https://github.com/mbroadst). +* NODE-951 Added support for sslCRL option and added a test case for it. +* NODE-953 Made batchSize issue general at cursor level. +* NODE-954 Remove write concern from reindex helper as it will not be supported in 3.6. +* Updated mongodb-core to 2.1.9. + * Return lastIsMaster correctly when connecting with secondaryOnlyConnectionAllowed is set to true and only a secondary is available in replica state. + * Clone options when passed to wireProtocol handler to avoid intermittent modifications causing errors. + * Ensure SSL error propegates better for Replset connections when there is a SSL validation error. + * NODE-957 Fixed issue where < batchSize not causing cursor to be closed on execution of first batch. + * NODE-958 Store reconnectConnection on pool object to allow destroy to close immediately. + +2.2.24 2017-02-14 +----------------- +* NODE-935, NODE-931 Make MongoClient strict options validation optional and instead print annoying console.warn entries. + +2.2.23 2017-02-13 +----------------- +* Updated mongodb-core to 2.1.8. + * NODE-925 ensure we reschedule operations while pool is < poolSize while pool is growing and there are no connections with not currently performing work. + * NODE-927 fixes issue where authentication was performed against arbiter instances. + * NODE-915 Normalize all host names to avoid comparison issues. + * Fixed issue where pool.destroy would never finish due to a single operation not being executed and keeping it open. +* NODE-931 Validates all the options for MongoClient.connect and fixes missing connection settings. +* NODE-929 Update SSL tutorial to correctly reflect the non-need for server/mongos/replset subobjects +* Fix sensitive command check (Issue #1473, https://github.com/Annoraaq) + +2.2.22 2017-01-24 +----------------- +* Updated mongodb-core to 2.1.7. + * NODE-919 ReplicaSet connection does not close immediately (Issue #156). + * NODE-901 Fixed bug when normalizing host names. + * NODE-909 Fixed readPreference issue caused by direct connection to primary. + * NODE-910 Fixed issue when bufferMaxEntries == 0 and read preference set to nearest. +* Add missing unref implementations for replset, mongos (Issue #1455, https://github.com/zbjornson) + +2.2.21 2017-01-13 +----------------- +* Updated mongodb-core to 2.1.6. + * NODE-908 Keep auth contexts in replset and mongos topology to ensure correct application of authentication credentials when primary is first server to be detected causing an immediate connect event to happen. + +2.2.20 2017-01-11 +----------------- +* Updated mongodb-core to 2.1.5 to include bson 1.0.4 and bson-ext 1.0.4 due to Buffer.from being broken in early node 4.x versions. + +2.2.19 2017-01-03 +----------------- +* Corrupted Npm release fix. + +2.2.18 2017-01-03 +----------------- +* Updated mongodb-core to 2.1.4 to fix bson ObjectId toString issue with utils.inspect messing with toString parameters in node 6. + +2.2.17 2017-01-02 +----------------- +* updated createCollection doc options and linked to create command. +* Updated mongodb-core to 2.1.3. + * Monitoring operations are re-scheduled in pool if it cannot find a connection that does not already have scheduled work on it, this is to avoid the monitoring socket timeout being applied to any existing operations on the socket due to pipelining + * Moved replicaset monitoring away from serial mode and to parallel mode. + * updated bson and bson-ext dependencies to 1.0.2. + +2.2.16 2016-12-13 +----------------- +* NODE-899 reversed upsertedId change to bring back old behavior. + +2.2.15 2016-12-10 +----------------- +* Updated mongodb-core to 2.1.2. + * Delay topologyMonitoring on successful attemptReconnect as no need to run a full scan immediately. + * Emit reconnect event in primary joining when in connected status for a replicaset (Fixes mongoose reconnect issue). + +2.2.14 2016-12-08 +----------------- +* Updated mongodb-core to 2.1.1. +* NODE-892 Passthrough options.readPreference to mongodb-core ReplSet instance. + +2.2.13 2016-12-05 +----------------- +* Updated mongodb-core to 2.1.0. +* NODE-889 Fixed issue where legacy killcursor wire protocol messages would not be sent when APM is enabled. +* Expose parserType as property on topology objects. + +2.2.12 2016-11-29 +----------------- +* Updated mongodb-core to 2.0.14. + * Updated bson library to 0.5.7. + * Dont leak connection.workItems elments when killCursor is called (Issue #150, https://github.com/mdlavin). + * Remove unnecessary errors formatting (Issue #149, https://github.com/akryvomaz). + * Only check isConnected against availableConnections (Issue #142). + * NODE-838 Provide better error message on failed to connect on first retry for Mongos topology. + * Set default servername to host is not passed through for sni. + * Made monitoring happen on exclusive connection and using connectionTimeout to handle the wait time before failure (Issue #148). + * NODE-859 Make minimum value of maxStalenessSeconds 90 seconds. + * NODE-852 Fix Kerberos module deprecations on linux and windows and release new kerberos version. + * NODE-850 Update Max Staleness implementation. + * NODE-849 username no longer required for MONGODB-X509 auth. + * NODE-848 BSON Regex flags must be alphabetically ordered. + * NODE-846 Create notice for all third party libraries. + * NODE-843 Executing bulk operations overwrites write concern parameter. + * NODE-842 Re-sync SDAM and SDAM Monitoring tests from Specs repo. + * NODE-840 Resync CRUD spec tests. + * Unescapable while(true) loop (Issue #152). +* NODE-864 close event not emits during network issues using single server topology. +* Introduced maxStalenessSeconds. +* NODE-840 Added CRUD specification test cases and fix minor issues with upserts reporting matchedCount > 0. +* Don't ignore Db-level authSource when using auth method. (https://github.com/donaldguy). + +2.2.11 2016-10-21 +----------------- +* Updated mongodb-core to 2.0.13. + - Fire callback when topology was destroyed (Issue #147, https://github.com/vkarpov15). + - Refactoring to support pipelining ala 1.4.x branch will retaining the benefits of the growing/shrinking pool (Issue #146). + - Fix typo in serverHeartbeatFailed event name (Issue #143, https://github.com/jakesjews). + - NODE-798 Driver hangs on count command in replica set with one member (Issue #141, https://github.com/isayme). +* Updated bson library to 0.5.6. + - Included cyclic dependency detection +* Fix typo in serverHeartbeatFailed event name (Issue #1418, https://github.com/jakesjews). +* NODE-824, readPreference "nearest" does not work when specified at collection level. +* NODE-822, GridFSBucketWriteStream end method does not handle optional parameters. +* NODE-823, GridFSBucketWriteStream end: callback is invoked with invalid parameters. +* NODE-829, Using Start/End offset option in GridFSBucketReadStream doesn't return the right sized buffer. + +2.2.10 2016-09-15 +----------------- +* Updated mongodb-core to 2.0.12. +* fix debug logging message not printing server name. +* fixed application metadata being sent by wrong ismaster. +* NODE-812 Fixed mongos stall due to proxy monitoring ismaster failure causing reconnect. +* NODE-818 Replicaset timeouts in initial connect sequence can "no primary found". +* Updated bson library to 0.5.5. +* Added DBPointer up conversion to DBRef. +* MongoDB 3.4-RC Pass **appname** through MongoClient.connect uri or options to allow metadata to be passed. +* MongoDB 3.4-RC Pass collation options on update, findOne, find, createIndex, aggregate. +* MongoDB 3.4-RC Allow write concerns to be passed to all supporting server commands. +* MongoDB 3.4-RC Allow passing of **servername** as SSL options to support SNI. + +2.2.9 2016-08-29 +---------------- +* Updated mongodb-core to 2.0.11. +* NODE-803, Fixed issue in how the latency window is calculated for Mongos topology causing issues for single proxy connections. +* Avoid timeout in attemptReconnect causing multiple attemptReconnect attempts to happen (Issue #134, https://github.com/dead-horse). +* Ensure promoteBuffers is propegated in same fashion as promoteValues and promoteLongs. +* Don't treat ObjectId as object for mapReduce scope (Issue #1397, https://github.com/vkarpov15). + +2.2.8 2016-08-23 +---------------- +* Updated mongodb-core to 2.0.10. +* Added promoteValues flag (default to true) to allow user to specify they only want wrapped BSON values back instead of promotion to native types. +* Do not close mongos proxy connection on failed ismaster check in ha process (Issue #130). + +2.2.7 2016-08-19 +---------------- +* If only a single mongos is provided in the seedlist, fix issue where it would be assigned as single standalone server instead of mongos topology (Issue #130). +* Updated mongodb-core to 2.0.9. +* Allow promoteLongs to be passed in through Response.parse method and overrides default set on the connection. +* NODE-798 Driver hangs on count command in replica set with one member. +* Allow promoteLongs to be passed in through Response.parse method and overrides default set on the connection. +* Allow passing in servername for TLS connections for SNI support. + +2.2.6 2016-08-16 +---------------- +* Updated mongodb-core to 2.0.8. +* Allow execution of store operations independent of having both a primary and secondary available (Issue #123). +* Fixed command execution issue for mongos to ensure buffering of commands when no mongos available. +* Allow passing in an array of tags to ReadPreference constructor (Issue #1382, https://github.com/vkarpov15) +* Added hashed connection names and fullResult. +* Updated bson library to 0.5.3. +* Enable maxTimeMS in count, distinct, findAndModify. + +2.2.5 2016-07-28 +---------------- +* Updated mongodb-core to 2.0.7. +* Allow primary to be returned when secondaryPreferred is passed (Issue #117, https://github.com/dhendo). +* Added better warnings when passing in illegal seed list members to a Mongos topology. +* Minor attemptReconnect bug that would cause multiple attemptReconnect to run in parallel. +* Fix wrong opType passed to disconnectHandler.add (Issue #121, https://github.com/adrian-gierakowski) +* Implemented domain backward comp support enabled via domainsEnabled options on Server/ReplSet/Mongos and MongoClient.connect. + +2.2.4 2016-07-19 +---------------- +* NPM corrupted upload fix. + +2.2.3 2016-07-19 +---------------- +* Updated mongodb-core to 2.0.6. +* Destroy connection on socket timeout due to newer node versions not closing the socket. + +2.2.2 2016-07-15 +---------------- +* Updated mongodb-core to 2.0.5. +* Minor fixes to handle faster MongoClient connectivity from the driver, allowing single server instances to detect if they are a proxy. +* Added numberOfConsecutiveTimeouts to pool that will destroy the pool if the number of consecutive timeouts > reconnectTries. +* Print warning if seedlist servers host name does not match the one provided in it's ismaster.me field for Replicaset members. +* Fix issue where Replicaset connection would not succeeed if there the replicaset was a single primary server setup. + +2.2.1 2016-07-11 +---------------- +* Updated mongodb-core to 2.0.4. +* handle situation where user is providing seedlist names that do not match host list. fix allows for a single full discovery connection sweep before erroring out. +* NODE-747 Polyfill for Object.assign for 0.12.x or 0.10.x. +* NODE-746 Improves replicaset errors for wrong setName. + +2.2.0 2016-07-05 +---------------- +* Updated mongodb-core to 2.0.3. +* Moved all authentication and handling of growing/shrinking of pool connections into actual pool. +* All authentication methods now handle both auth/reauthenticate and logout events. +* Introduced logout method to get rid of onAll option for logout command. +* Updated bson to 0.5.0 that includes Decimal128 support. +* Fixed logger error serialization issue. +* Documentation fixes. +* Implemented Server Selection Specification test suite. +* Added warning level to logger. +* Added warning message when sockeTimeout < haInterval for Replset/Mongos. +* Mongos emits close event on no proxies available or when reconnect attempt fails. +* Replset emits close event when no servers available or when attemptReconnect fails to reconnect. +* Don't throw in auth methods but return error in callback. + +2.1.21 2016-05-30 +----------------- +* Updated mongodb-core to 1.3.21. +* Pool gets stuck if a connection marked for immediateRelease times out (Issue #99, https://github.com/nbrachet). +* Make authentication process retry up to authenticationRetries at authenticationRetryIntervalMS interval. +* Made ismaster replicaset calls operate with connectTimeout or monitorSocketTimeout to lower impact of big socketTimeouts on monitoring performance. +* Make sure connections mark as "immediateRelease" don't linger the inUserConnections list. Otherwise, after that connection times out, getAll() incorrectly returns more connections than are effectively present, causing the pool to not get restarted by reconnectServer. (Issue #99, https://github.com/nbrachet). +* Make cursor getMore or killCursor correctly trigger pool reconnect to single server if pool has not been destroyed. +* Make ismaster monitoring for single server connection default to avoid user confusion due to change in behavior. + +2.1.20 2016-05-25 +----------------- +* Refactored MongoClient options handling to simplify the logic, unifying it. +* NODE-707 Implemented openUploadStreamWithId on GridFS to allow for custom fileIds so users are able to customize shard key and shard distribution. +* NODE-710 Allow setting driver loggerLevel and logger function from MongoClient options. +* Updated mongodb-core to 1.3.20. +* Minor fix for SSL errors on connection attempts, minor fix to reconnect handler for the server. +* Don't write to socket before having registered the callback for commands, work around for windows issuing error events twice on node.js when socket gets destroyed by firewall. +* Fix minor issue where connectingServers would not be removed correctly causing single server connections to not auto-reconnect. + +2.1.19 2016-05-17 +---------------- +* Handle situation where a server connection in a replicaset sometimes fails to be destroyed properly due to being in the middle of authentication when the destroy method is called on the replicaset causing it to be orphaned and never collected. +* Ensure replicaset topology destroy is never called by SDAM. +* Ensure all paths are correctly returned on inspectServer in replset. +* Updated mongodb-core to 1.3.19 to fix minor connectivity issue on quick open/close of MongoClient connections on auth enabled mongodb Replicasets. + +2.1.18 2016-04-27 +----------------- +* Updated mongodb-core to 1.3.18 to fix Node 6.0 issues. + +2.1.17 2016-04-26 +----------------- +* Updated mongodb-core to 1.3.16 to work around issue with early versions of node 0.10.x due to missing unref method on ClearText streams. +* INT-1308: Allow listIndexes to inherit readPreference from Collection or DB. +* Fix timeout issue using new flags #1361. +* Updated mongodb-core to 1.3.17. +* Better handling of unique createIndex error. +* Emit error only if db instance has an error listener. +* DEFAULT authMechanism; don't throw error if explicitly set by user. + +2.1.16 2016-04-06 +----------------- +* Updated mongodb-core to 1.3.16. + +2.1.15 2016-04-06 +----------------- +* Updated mongodb-core to 1.3.15. +* Set ssl, sslValidate etc to mongosOptions on url_parser (Issue #1352, https://github.com/rubenstolk). +- NODE-687 Fixed issue where a server object failed to be destroyed if the replicaset state did not update successfully. This could leave active connections accumulating over time. +- Fixed some situations where all connections are flushed due to a single connection in the connection pool closing. + +2.1.14 2016-03-29 +----------------- +* Updated mongodb-core to 1.3.13. +* Handle missing cursor on getMore when going through a mongos proxy by pinning to socket connection and not server. + +2.1.13 2016-03-29 +----------------- +* Updated mongodb-core to 1.3.12. + +2.1.12 2016-03-29 +----------------- +* Updated mongodb-core to 1.3.11. +* Mongos setting acceptableLatencyMS exposed to control the latency women for mongos selection. +* Mongos pickProxies fall back to closest mongos if no proxies meet latency window specified. +* isConnected method for mongos uses same selection code as getServer. +* Exceptions in cursor getServer trapped and correctly delegated to high level handler. + +2.1.11 2016-03-23 +----------------- +* Updated mongodb-core to 1.3.10. +* Introducing simplified connections settings. + +2.1.10 2016-03-21 +----------------- +* Updated mongodb-core to 1.3.9. +* Fixing issue that prevented mapReduce stats from being resolved (Issue #1351, https://github.com/davidgtonge) +* Forwards SDAM monitoring events from mongodb-core. + +2.1.9 2016-03-16 +---------------- +* Updated mongodb-core to 1.3.7 to fix intermittent race condition that causes some users to experience big amounts of socket connections. +* Makde bson parser in ordered/unordered bulk be directly from mongodb-core to avoid intermittent null error on mongoose. + +2.1.8 2016-03-14 +---------------- +* Updated mongodb-core to 1.3.5. +* NODE-660 TypeError: Cannot read property 'noRelease' of undefined. +* Harden MessageHandler in server.js to avoid issues where we cannot find a callback for an operation. +* Ensure RequestId can never be larger than Max Number integer size. +* NODE-661 typo in url_parser.js resulting in replSetServerOptions is not defined when connecting over ssl. +* Confusing error with invalid partial index filter (Issue #1341, https://github.com/vkarpov15). +* NODE-669 Should only error out promise for bulkWrite when error is a driver level error not a write error or write concern error. +* NODE-662 shallow copy options on methods that are not currently doing it to avoid passed in options mutiation. +* NODE-663 added lookup helper on aggregation cursor. +* NODE-585 Result object specified incorrectly for findAndModify?. +* NODE-666 harden validation for findAndModify CRUD methods. + +2.1.7 2016-02-09 +---------------- +* NODE-656 fixed corner case where cursor count command could be left without a connection available. +* NODE-658 Work around issue that bufferMaxEntries:-1 for js gets interpreted wrongly due to double nature of Javascript numbers. +* Fix: GridFS always returns the oldest version due to incorrect field name (Issue #1338, https://github.com/mdebruijne). +* NODE-655 GridFS stream support for cancelling upload streams and download streams (Issue #1339, https://github.com/vkarpov15). +* NODE-657 insertOne don`t return promise in some cases. +* Added destroy alias for abort function on GridFSBucketWriteStream. + +2.1.6 2016-02-05 +---------------- +* Updated mongodb-core to 1.3.1. + +2.1.5 2016-02-04 +---------------- +* Updated mongodb-core to 1.3.0. +* Added raw support for the command function on topologies. +* Fixed issue where raw results that fell on batchSize boundaries failed (Issue #72) +* Copy over all the properties to the callback returned from bindToDomain, (Issue #72) +* Added connection hash id to be able to reference connection host/name without leaking it outside of driver. +* NODE-638, Cannot authenticate database user with utf-8 password. +* Refactored pool to be worker queue based, minimizing the impact a slow query have on throughput as long as # slow queries < # connections in the pool. +* Pool now grows and shrinks correctly depending on demand not causing a full pool reconnect. +* Improvements in monitoring of a Replicaset where in certain situations the inquiry process could get exited. +* Switched to using Array.push instead of concat for use cases of a lot of documents. +* Fixed issue where re-authentication could loose the credentials if whole Replicaset disconnected at once. +* Added peer optional dependencies support using require_optional module. +* Bug is listCollections for collection names that start with db name (Issue #1333, https://github.com/flyingfisher) +* Emit error before closing stream (Issue #1335, https://github.com/eagleeye) + +2.1.4 2016-01-12 +---------------- +* Restricted node engine to >0.10.3 (https://jira.mongodb.org/browse/NODE-635). +* Multiple database names ignored without a warning (https://jira.mongodb.org/browse/NODE-636, Issue #1324, https://github.com/yousefhamza). +* Convert custom readPreference objects in collection.js (Issue #1326, https://github.com/Machyne). + +2.1.3 2016-01-04 +---------------- +* Updated mongodb-core to 1.2.31. +* Allow connection to secondary if primaryPreferred or secondaryPreferred (Issue #70, https://github.com/leichter) + +2.1.2 2015-12-23 +---------------- +* Updated mongodb-core to 1.2.30. +* Pool allocates size + 1 connections when using replicasets, reserving additional pool connection for monitoring exclusively. +* Fixes bug when all replicaset members are down, that would cause it to fail to reconnect using the originally provided seedlist. + +2.1.1 2015-12-13 +---------------- +* Surfaced checkServerIdentity options for MongoClient, Server, ReplSet and Mongos to allow for control of the checkServerIdentity method available in Node.s 0.12.x or higher. +* Added readPreference support to listCollections and listIndexes helpers. +* Updated mongodb-core to 1.2.28. + +2.1.0 2015-12-06 +---------------- +* Implements the connection string specification, https://github.com/mongodb/specifications/blob/master/source/connection-string/connection-string-spec.rst. +* Implements the new GridFS specification, https://github.com/mongodb/specifications/blob/master/source/gridfs/gridfs-spec.rst. +* Full MongoDB 3.2 support. +* NODE-601 Added maxAwaitTimeMS support for 3.2 getMore to allow for custom timeouts on tailable cursors. +* Updated mongodb-core to 1.2.26. +* Return destination in GridStore pipe function. +* NODE-606 better error handling on destroyed topology for db.js methods. +* Added isDestroyed method to server, replset and mongos topologies. +* Upgraded test suite to run using mongodb-topology-manager. + +2.0.53 2015-12-23 +----------------- +* Updated mongodb-core to 1.2.30. +* Pool allocates size + 1 connections when using replicasets, reserving additional pool connection for monitoring exclusively. +* Fixes bug when all replicaset members are down, that would cause it to fail to reconnect using the originally provided seedlist. + +2.0.52 2015-12-14 +----------------- +* removed remove from Gridstore.close. + +2.0.51 2015-12-13 +----------------- +* Surfaced checkServerIdentity options for MongoClient, Server, ReplSet and Mongos to allow for control of the checkServerIdentity method available in Node.s 0.12.x or higher. +* Added readPreference support to listCollections and listIndexes helpers. +* Updated mongodb-core to 1.2.28. + +2.0.50 2015-12-06 +----------------- +* Updated mongodb-core to 1.2.26. + +2.0.49 2015-11-20 +----------------- +* Updated mongodb-core to 1.2.24 with several fixes. + * Fix Automattic/mongoose#3481; flush callbacks on error, (Issue #57, https://github.com/vkarpov15). + * $explain query for wire protocol 2.6 and 2.4 does not set number of returned documents to -1 but to 0. + * ismaster runs against admin.$cmd instead of system.$cmd. + * Fixes to handle getMore command errors for MongoDB 3.2 + * Allows the process to properly close upon a Db.close() call on the replica set by shutting down the haTimer and closing arbiter connections. + +2.0.48 2015-11-07 +----------------- +* GridFS no longer performs any deletes when writing a brand new file that does not have any previous .fs.chunks or .fs.files documents. +* Updated mongodb-core to 1.2.21. +* Hardened the checking for replicaset equality checks. +* OpReplay flag correctly set on Wire protocol query. +* Mongos load balancing added, introduced localThresholdMS to control the feature. +* Kerberos now a peerDependency, making it not install it by default in Node 5.0 or higher. + +2.0.47 2015-10-28 +----------------- +* Updated mongodb-core to 1.2.20. +* Fixed bug in arbiter connection capping code. +* NODE-599 correctly handle arrays of server tags in order of priority. +* Fix for 2.6 wire protocol handler related to readPreference handling. +* Added maxAwaitTimeMS support for 3.2 getMore to allow for custom timeouts on tailable cursors. +* Make CoreCursor check for $err before saying that 'next' succeeded (Issue #53, https://github.com/vkarpov15). + +2.0.46 2015-10-15 +----------------- +* Updated mongodb-core to 1.2.19. +* NODE-578 Order of sort fields is lost for numeric field names. +* Expose BSON Map (ES6 Map or polyfill). +* Minor fixes for APM support to pass extended APM test suite. + +2.0.45 2015-09-30 +----------------- +* NODE-566 Fix issue with rewind on capped collections causing cursor state to be reset on connection loss. + +2.0.44 2015-09-28 +----------------- +* Bug fixes for APM upconverting of legacy INSERT/UPDATE/REMOVE wire protocol messages. +* NODE-562, fixed issue where a Replicaset MongoDB URI with a single seed and replSet name set would cause a single direct connection instead of topology discovery. +* Updated mongodb-core to 1.2.14. +* NODE-563 Introduced options.ignoreUndefined for db class and MongoClient db options, made serialize undefined to null default again but allowing for overrides on insert/update/delete operations. +* Use handleCallback if result is an error for count queries. (Issue #1298, https://github.com/agclever) +* Rewind cursor to correctly force reconnect on capped collections when first query comes back empty. +* NODE-571 added code 59 to legacy server errors when SCRAM-SHA-1 mechanism fails. +* NODE-572 Remove examples that use the second parameter to `find()`. + +2.0.43 2015-09-14 +----------------- +* Propagate timeout event correctly to db instances. +* Application Monitoring API (APM) implemented. +* NOT providing replSet name in MongoClient connection URI will force single server connection. Fixes issue where it was impossible to directly connect to a replicaset member server. +* Updated mongodb-core to 1.2.12. +* NODE-541 Initial Support "read committed" isolation level where "committed" means confimed by the voting majority of a replica set. +* GridStore doesn't share readPreference setting from connection string. (Issue #1295, https://github.com/zhangyaoxing) +* fixed forceServerObjectId calls (Issue #1292, https://github.com/d-mon-) +* Pass promise library through to DB function (Issue #1294, https://github.com/RovingCodeMonkey) + +2.0.42 2015-08-18 +----------------- +* Added test case to exercise all non-crud methods on mongos topologies, fixed numberOfConnectedServers on mongos topology instance. + +2.0.41 2015-08-14 +----------------- +* Added missing Mongos.prototype.parserType function. +* Updated mongodb-core to 1.2.10. + +2.0.40 2015-07-14 +----------------- +* Updated mongodb-core to 1.2.9 for 2.4 wire protocol error handler fix. +* NODE-525 Reset connectionTimeout after it's overwritten by tls.connect. +* NODE-518 connectTimeoutMS is doubled in 2.0.39. +* NODE-506 Ensures that errors from bulk unordered and ordered are instanceof Error (Issue #1282, https://github.com/owenallenaz). +* NODE-526 Unique index not throwing duplicate key error. +* NODE-528 Ignore undefined fields in Collection.find(). +* NODE-527 The API example for collection.createIndex shows Db.createIndex functionality. + +2.0.39 2015-07-14 +----------------- +* Updated mongodb-core to 1.2.6 for NODE-505. + +2.0.38 2015-07-14 +----------------- +* NODE-505 Query fails to find records that have a 'result' property with an array value. + +2.0.37 2015-07-14 +----------------- +* NODE-504 Collection * Default options when using promiseLibrary. +* NODE-500 Accidental repeat of hostname in seed list multiplies total connections persistently. +* Updated mongodb-core to 1.2.5 to fix NODE-492. + +2.0.36 2015-07-07 +----------------- +* Fully promisified allowing the use of ES6 generators and libraries like co. Also allows for BYOP (Bring your own promises). +* NODE-493 updated mongodb-core to 1.2.4 to ensure we cannot DDOS the mongod or mongos process on large connection pool sizes. + +2.0.35 2015-06-17 +----------------- +* Upgraded to mongodb-core 1.2.2 including removing warnings when C++ bson parser is not available and a fix for SCRAM authentication. + +2.0.34 2015-06-17 +----------------- +* Upgraded to mongodb-core 1.2.1 speeding up serialization and removing the need for the c++ bson extension. +* NODE-486 fixed issue related to limit and skip when calling toArray in 2.0 driver. +* NODE-483 throw error if capabilities of topology is queries before topology has performed connection setup. +* NODE-482 fixed issue where MongoClient.connect would incorrectly identify a replset seed list server as a non replicaset member. +* NODE-487 fixed issue where killcursor command was not being sent correctly on limit and skip queries. + +2.0.33 2015-05-20 +----------------- +* Bumped mongodb-core to 1.1.32. + +2.0.32 2015-05-19 +----------------- +* NODE-463 db.close immediately executes its callback. +* Don't only emit server close event once (Issue #1276, https://github.com/vkarpov15). +* NODE-464 Updated mongodb-core to 1.1.31 that uses a single socket connection to arbiters and hidden servers as well as emitting all event correctly. + +2.0.31 2015-05-08 +----------------- +* NODE-461 Tripping on error "no chunks found for file, possibly corrupt" when there is no error. + +2.0.30 2015-05-07 +----------------- +* NODE-460 fix; don't set authMechanism for user in db.authenticate() to avoid mongoose authentication issue. + +2.0.29 2015-05-07 +----------------- +* NODE-444 Possible memory leak, too many listeners added. +* NODE-459 Auth failure using Node 0.8.28, MongoDB 3.0.2 & mongodb-node-native 1.4.35. +* Bumped mongodb-core to 1.1.26. + +2.0.28 2015-04-24 +----------------- +* Bumped mongodb-core to 1.1.25 +* Added Cursor.prototype.setCursorOption to allow for setting node specific cursor options for tailable cursors. +* NODE-430 Cursor.count() opts argument masked by var opts = {} +* NODE-406 Implemented Cursor.prototype.map function tapping into MongoClient cursor transforms. +* NODE-438 replaceOne is not returning the result.ops property as described in the docs. +* NODE-433 _read, pipe and write all open gridstore automatically if not open. +* NODE-426 ensure drain event is emitted after write function returns, fixes intermittent issues in writing files to gridstore. +* NODE-440 GridStoreStream._read() doesn't check GridStore.read() error. +* Always use readPreference = primary for findAndModify command (ignore passed in read preferences) (Issue #1274, https://github.com/vkarpov15). +* Minor fix in GridStore.exists for dealing with regular expressions searches. + +2.0.27 2015-04-07 +----------------- +* NODE-410 Correctly handle issue with pause/resume in Node 0.10.x that causes exceptions when using the Node 0.12.0 style streams. + +2.0.26 2015-04-07 +----------------- +* Implements the Common Index specification Standard API at https://github.com/mongodb/specifications/blob/master/source/index-management.rst. +* NODE-408 Expose GridStore.currentChunk.chunkNumber. + +2.0.25 2015-03-26 +----------------- +* Upgraded mongodb-core to 1.1.21, making the C++ bson code an optional dependency to the bson module. + +2.0.24 2015-03-24 +----------------- +* NODE-395 Socket Not Closing, db.close called before full set finished initalizing leading to server connections in progress not being closed properly. +* Upgraded mongodb-core to 1.1.20. + +2.0.23 2015-03-21 +----------------- +* NODE-380 Correctly return MongoError from toError method. +* Fixed issue where addCursorFlag was not correctly setting the flag on the command for mongodb-core. +* NODE-388 Changed length from method to property on order.js/unordered.js bulk operations. +* Upgraded mongodb-core to 1.1.19. + +2.0.22 2015-03-16 +----------------- +* NODE-377, fixed issue where tags would correctly be checked on secondary and nearest to filter out eligible server candidates. +* Upgraded mongodb-core to 1.1.17. + +2.0.21 2015-03-06 +----------------- +* Upgraded mongodb-core to 1.1.16 making sslValidate default to true to force validation on connection unless overriden by the user. + +2.0.20 2015-03-04 +----------------- +* Updated mongodb-core 1.1.15 to relax pickserver method. + +2.0.19 2015-03-03 +----------------- +* NODE-376 Fixes issue * Unordered batch incorrectly tracks batch size when switching batch types (Issue #1261, https://github.com/meirgottlieb) +* NODE-379 Fixes bug in cursor.count() that causes the result to always be zero for dotted collection names (Issue #1262, https://github.com/vsivsi) +* Expose MongoError from mongodb-core (Issue #1260, https://github.com/tjconcept) + +2.0.18 2015-02-27 +----------------- +* Bumped mongodb-core 1.1.14 to ensure passives are correctly added as secondaries. + +2.0.17 2015-02-27 +----------------- +* NODE-336 Added length function to ordered and unordered bulk operations to be able know the amount of current operations in bulk. +* Bumped mongodb-core 1.1.13 to ensure passives are correctly added as secondaries. + +2.0.16 2015-02-16 +----------------- +* listCollection now returns filtered result correctly removing db name for 2.6 or earlier servers. +* Bumped mongodb-core 1.1.12 to correctly work for node 0.12.0 and io.js. +* Add ability to get collection name from cursor (Issue #1253, https://github.com/vkarpov15) + +2.0.15 2015-02-02 +----------------- +* Unified behavior of listCollections results so 3.0 and pre 3.0 return same type of results. +* Bumped mongodb-core to 1.1.11 to support per document tranforms in cursors as well as relaxing the setName requirement. +* NODE-360 Aggregation cursor and command correctly passing down the maxTimeMS property. +* Added ~1.0 mongodb-tools module for test running. +* Remove the required setName for replicaset connections, if not set it will pick the first setName returned. + +2.0.14 2015-01-21 +----------------- +* Fixed some MongoClient.connect options pass through issues and added test coverage. +* Bumped mongodb-core to 1.1.9 including fixes for io.js + +2.0.13 2015-01-09 +----------------- +* Bumped mongodb-core to 1.1.8. +* Optimized query path for performance, moving Object.defineProperty outside of constructors. + +2.0.12 2014-12-22 +----------------- +* Minor fixes to listCollections to ensure correct querying of a collection when using a string. + +2.0.11 2014-12-19 +----------------- +* listCollections filters out index namespaces on < 2.8 correctly +* Bumped mongo-client to 1.1.7 + +2.0.10 2014-12-18 +----------------- +* NODE-328 fixed db.open return when no callback available issue and added test. +* NODE-327 Refactored listCollections to return cursor to support 2.8. +* NODE-327 Added listIndexes method and refactored internal methods to use the new command helper. +* NODE-335 Cannot create index for nested objects fixed by relaxing key checking for createIndex helper. +* Enable setting of connectTimeoutMS (Issue #1235, https://github.com/vkarpov15) +* Bumped mongo-client to 1.1.6 + +2.0.9 2014-12-01 +---------------- +* Bumped mongodb-core to 1.1.3 fixing global leaked variables and introducing strict across all classes. +* All classes are now strict (Issue #1233) +* NODE-324 Refactored insert/update/remove and all other crud opts to rely on internal methods to avoid any recursion. +* Fixed recursion issues in debug logging due to JSON.stringify() +* Documentation fixes (Issue #1232, https://github.com/wsmoak) +* Fix writeConcern in Db.prototype.ensureIndex (Issue #1231, https://github.com/Qard) + +2.0.8 2014-11-28 +---------------- +* NODE-322 Finished up prototype refactoring of Db class. +* NODE-322 Exposed Cursor in index.js for New Relic. + +2.0.7 2014-11-20 +---------------- +* Bumped mongodb-core to 1.1.2 fixing a UTF8 encoding issue for collection names. +* NODE-318 collection.update error while setting a function with serializeFunctions option. +* Documentation fixes. + +2.0.6 2014-11-14 +---------------- +* Refactored code to be prototype based instead of privileged methods. +* Bumped mongodb-core to 1.1.1 to take advantage of the prototype based refactorings. +* Implemented missing aspects of the CRUD specification. +* Fixed documentation issues. +* Fixed global leak REFERENCE_BY_ID in gridfs grid_store (Issue #1225, https://github.com/j) +* Fix LearnBoost/mongoose#2313: don't let user accidentally clobber geoNear params (Issue #1223, https://github.com/vkarpov15) + +2.0.5 2014-10-29 +---------------- +* Minor fixes to documentation and generation of documentation. +* NODE-306 (No results in aggregation cursor when collection name contains a dot), Merged code for cursor and aggregation cursor. + +2.0.4 2014-10-23 +---------------- +* Allow for single replicaset seed list with no setName specified (Issue #1220, https://github.com/imaman) +* Made each rewind on each call allowing for re-using the cursor. +* Fixed issue where incorrect iterations would happen on each for extensive batchSizes. +* NODE-301 specifying maxTimeMS on find causes all fields to be omitted from result. + +2.0.3 2014-10-14 +---------------- +* NODE-297 Aggregate Broken for case of pipeline with no options. + +2.0.2 2014-10-08 +---------------- +* Bumped mongodb-core to 1.0.2. +* Fixed bson module dependency issue by relying on the mongodb-core one. +* Use findOne instead of find followed by nextObject (Issue #1216, https://github.com/sergeyksv) + +2.0.1 2014-10-07 +---------------- +* Dependency fix + +2.0.0 2014-10-07 +---------------- +* First release of 2.0 driver + +2.0.0-alpha2 2014-10-02 +----------------------- +* CRUD API (insertOne, insertMany, updateOne, updateMany, removeOne, removeMany, bulkWrite, findOneAndDelete, findOneAndUpdate, findOneAndReplace) +* Cluster Management Spec compatible. + +2.0.0-alpha1 2014-09-08 +----------------------- +* Insert method allows only up 1000 pr batch for legacy as well as 2.6 mode +* Streaming behavior is 0.10.x or higher with backwards compatibility using readable-stream npm package +* Gridfs stream only available through .stream() method due to overlapping names on Gridstore object and streams in 0.10.x and higher of node +* remove third result on update and remove and return the whole result document instead (getting rid of the weird 3 result parameters) + * Might break some application +* Returns the actual mongodb-core result instead of just the number of records changed for insert/update/remove +* MongoClient only has the connect method (no ability instantiate with Server, ReplSet or similar) +* Removed Grid class +* GridStore only supports w+ for metadata updates, no appending to file as it's not thread safe and can cause corruption of the data + + seek will fail if attempt to use with w or w+ + + write will fail if attempted with w+ or r + + w+ only works for updating metadata on a file +* Cursor toArray and each resets and re-runs the cursor +* FindAndModify returns whole result document instead of just value +* Extend cursor to allow for setting all the options via methods instead of dealing with the current messed up find +* Removed db.dereference method +* Removed db.cursorInfo method +* Removed db.stats method +* Removed db.collectionNames not needed anymore as it's just a specialized case of listCollections +* Removed db.collectionInfo removed due to not being compatible with new storage engines in 2.8 as they need to use the listCollections command due to system collections not working for namespaces. +* Added db.listCollections to replace several methods above + +1.4.10 2014-09-04 +----------------- +* Fixed BSON and Kerberos compilation issues +* Bumped BSON to ~0.2 always installing latest BSON 0.2.x series +* Fixed Kerberos and bumped to 0.0.4 + +1.4.9 2014-08-26 +---------------- +* Check _bsonType for Binary (Issue #1202, https://github.com/mchapman) +* Remove duplicate Cursor constructor (Issue #1201, https://github.com/KenPowers) +* Added missing parameter in the documentation (Issue #1199, https://github.com/wpjunior) +* Documented third parameter on the update callback(Issue #1196, https://github.com/gabmontes) +* NODE-240 Operations on SSL connection hang on node 0.11.x +* NODE-235 writeResult is not being passed on when error occurs in insert +* NODE-229 Allow count to work with query hints +* NODE-233 collection.save() does not support fullResult +* NODE-244 Should parseError also emit a `disconnected` event? +* NODE-246 Cursors are inefficiently constructed and consequently cannot be promisified. +* NODE-248 Crash with X509 auth +* NODE-252 Uncaught Exception in Base.__executeAllServerSpecificErrorCallbacks +* Bumped BSON parser to 0.2.12 + + +1.4.8 2014-08-01 +---------------- +* NODE-205 correctly emit authenticate event +* NODE-210 ensure no undefined connection error when checking server state +* NODE-212 correctly inherit socketTimeoutMS from replicaset when HA process adds new servers or reconnects to existing ones +* NODE-220 don't throw error if ensureIndex errors out in Gridstore +* Updated bson to 0.2.11 to ensure correct toBSON behavior when returning non object in nested classes +* Fixed test running filters +* Wrap debug log in a call to format (Issue #1187, https://github.com/andyroyle) +* False option values should not trigger w:1 (Issue #1186, https://github.com/jsdevel) +* Fix aggregatestream.close(Issue #1194, https://github.com/jonathanong) +* Fixed parsing issue for w:0 in url parser when in connection string +* Modified collection.geoNear to support a geoJSON point or legacy coordinate pair (Issue #1198, https://github.com/mmacmillan) + +1.4.7 2014-06-18 +---------------- +* Make callbacks to be executed in right domain when server comes back up (Issue #1184, https://github.com/anton-kotenko) +* Fix issue where currentOp query against mongos would fail due to mongos passing through $readPreference field to mongod (CS-X) + +1.4.6 2014-06-12 +---------------- +* Added better support for MongoClient IP6 parsing (Issue #1181, https://github.com/micovery) +* Remove options check on index creation (Issue #1179, Issue #1183, https://github.com/jdesboeufs, https://github.com/rubenvereecken) +* Added missing type check before calling optional callback function (Issue #1180) + +1.4.5 2014-05-21 +---------------- +* Added fullResult flag to insert/update/remove which will pass raw result document back. Document contents will vary depending on the server version the driver is talking to. No attempt is made to coerce a joint response. +* Fix to avoid MongoClient.connect hanging during auth when secondaries building indexes pre 2.6. +* return the destination stream in GridStore.pipe (Issue #1176, https://github.com/iamdoron) + +1.4.4 2014-05-13 +---------------- +* Bumped BSON version to use the NaN 1.0 package, fixed strict comparison issue for ObjectID +* Removed leaking global variable (Issue #1174, https://github.com/dainis) +* MongoClient respects connectTimeoutMS for initial discovery process (NODE-185) +* Fix bug with return messages larger than 16MB but smaller than max BSON Message Size (NODE-184) + +1.4.3 2014-05-01 +---------------- +* Clone options for commands to avoid polluting original options passed from Mongoose (Issue #1171, https://github.com/vkarpov15) +* Made geoNear and geoHaystackSearch only clean out allowed options from command generation (Issue #1167) +* Fixed typo for allowDiskUse (Issue #1168, https://github.com/joaofranca) +* A 'mapReduce' function changed 'function' to instance '\' of 'Code' class (Issue #1165, https://github.com/exabugs) +* Made findAndModify set sort only when explicitly set (Issue #1163, https://github.com/sars) +* Rewriting a gridStore file by id should use a new filename if provided (Issue #1169, https://github.com/vsivsi) + +1.4.2 2014-04-15 +---------------- +* Fix for inheritance of readPreferences from MongoClient NODE-168/NODE-169 +* Merged in fix for ping strategy to avoid hitting non-pinged servers (Issue #1161, https://github.com/vaseker) +* Merged in fix for correct debug output for connection messages (Issue #1158, https://github.com/vaseker) +* Fixed global variable leak (Issue #1160, https://github.com/vaseker) + +1.4.1 2014-04-09 +---------------- +* Correctly emit joined event when primary change +* Add _id to documents correctly when using bulk operations + +1.4.0 2014-04-03 +---------------- +* All node exceptions will no longer be caught if on('error') is defined +* Added X509 auth support +* Fix for MongoClient connection timeout issue (NODE-97) +* Pass through error messages from parseError instead of just text (Issue #1125) +* Close db connection on error (Issue #1128, https://github.com/benighted) +* Fixed documentation generation +* Added aggregation cursor for 2.6 and emulated cursor for pre 2.6 (uses stream2) +* New Bulk API implementation using write commands for 2.6 and down converts for pre 2.6 +* Insert/Update/Remove using new write commands when available +* Added support for new roles based API's in 2.6 for addUser/removeUser +* Added bufferMaxEntries to start failing if the buffer hits the specified number of entries +* Upgraded BSON parser to version 0.2.7 to work with < 0.11.10 C++ API changes +* Support for OP_LOG_REPLAY flag (NODE-94) +* Fixes for SSL HA ping and discovery. +* Uses createIndexes if available for ensureIndex/createIndex +* Added parallelCollectionScan method to collection returning CommandCursor instances for cursors +* Made CommandCursor behave as Readable stream. +* Only Db honors readPreference settings, removed Server.js legacy readPreference settings due to user confusion. +* Reconnect event emitted by ReplSet/Mongos/Server after reconnect and before replaying of buffered operations. +* GridFS buildMongoObject returns error on illegal md5 (NODE-157, https://github.com/iantocristian) +* Default GridFS chunk size changed to (255 * 1024) bytes to optimize for collections defaulting to power of 2 sizes on 2.6. +* Refactored commands to all go through command function ensuring consistent command execution. +* Fixed issues where readPreferences where not correctly passed to mongos. +* Catch error == null and make err detection more prominent (NODE-130) +* Allow reads from arbiter for single server connection (NODE-117) +* Handle error coming back with no documents (NODE-130) +* Correctly use close parameter in Gridstore.write() (NODE-125) +* Throw an error on a bulk find with no selector (NODE-129, https://github.com/vkarpov15) +* Use a shallow copy of options in find() (NODE-124, https://github.com/vkarpov15) +* Fix statistical strategy (NODE-158, https://github.com/vkarpov15) +* GridFS off-by-one bug in lastChunkNumber() causes uncaught throw and data loss (Issue #1154, https://github.com/vsivsi) +* GridStore drops passed `aliases` option, always results in `null` value in GridFS files (Issue #1152, https://github.com/vsivsi) +* Remove superfluous connect object copying in index.js (Issue #1145, https://github.com/thomseddon) +* Do not return false when the connection buffer is still empty (Issue #1143, https://github.com/eknkc) +* Check ReadPreference object on ReplSet.canRead (Issue #1142, https://github.com/eknkc) +* Fix unpack error on _executeQueryCommand (Issue #1141, https://github.com/eknkc) +* Close db on failed connect so node can exit (Issue #1128, https://github.com/benighted) +* Fix global leak with _write_concern (Issue #1126, https://github.com/shanejonas) + +1.3.19 2013-08-21 +----------------- +* Correctly rethrowing errors after change from event emission to callbacks, compatibility with 0.10.X domains without breaking 0.8.X support. +* Small fix to return the entire findAndModify result as the third parameter (Issue #1068) +* No removal of "close" event handlers on server reconnect, emits "reconnect" event when reconnection happens. Reconnect Only applies for single server connections as of now as semantics for ReplSet and Mongos is not clear (Issue #1056) + +1.3.18 2013-08-10 +----------------- +* Fixed issue when throwing exceptions in MongoClient.connect/Db.open (Issue #1057) +* Fixed an issue where _events is not cleaned up correctly causing a slow steady memory leak. + +1.3.17 2013-08-07 +----------------- +* Ignore return commands that have no registered callback +* Made collection.count not use the db.command function +* Fix throw exception on ping command (Issue #1055) + +1.3.16 2013-08-02 +----------------- +* Fixes connection issue where lots of connections would happen if a server is in recovery mode during connection (Issue #1050, NODE-50, NODE-51) +* Bug in unlink mulit filename (Issue #1054) + +1.3.15 2013-08-01 +----------------- +* Memory leak issue due to node Issue #4390 where _events[id] is set to undefined instead of deleted leading to leaks in the Event Emitter over time + +1.3.14 2013-08-01 +----------------- +* Fixed issue with checkKeys where it would error on X.X + +1.3.13 2013-07-31 +----------------- +* Added override for checkKeys on insert/update (Warning will expose you to injection attacks) (Issue #1046) +* BSON size checking now done pre serialization (Issue #1037) +* Added isConnected returns false when no connection Pool exists (Issue #1043) +* Unified command handling to ensure same handling (Issue #1041, #1042) +* Correctly emit "open" and "fullsetup" across all Db's associated with Mongos, ReplSet or Server (Issue #1040) +* Correctly handles bug in authentication when attempting to connect to a recovering node in a replicaset. +* Correctly remove recovering servers from available servers in replicaset. Piggybacks on the ping command. +* Removed findAndModify chaining to be compliant with behavior in other official drivers and to fix a known mongos issue. +* Fixed issue with Kerberos authentication on Windows for re-authentication. +* Fixed Mongos failover behavior to correctly throw out old servers. +* Ensure stored queries/write ops are executed correctly after connection timeout +* Added promoteLongs option for to allow for overriding the promotion of Longs to Numbers and return the actual Long. + +1.3.12 2013-07-19 +----------------- +* Fixed issue where timeouts sometimes would behave wrongly (Issue #1032) +* Fixed bug with callback third parameter on some commands (Issue #1033) +* Fixed possible issue where killcursor command might leave hanging functions +* Fixed issue where Mongos was not correctly removing dead servers from the pool of eligable servers +* Throw error if dbName or collection name contains null character (at command level and at collection level) +* Updated bson parser to 0.2.1 with security fix and non-promotion of Long values to javascript Numbers (once a long always a long) + +1.3.11 2013-07-04 +----------------- +* Fixed errors on geoNear and geoSearch (Issue #1024, https://github.com/ebensing) +* Add driver version to export (Issue #1021, https://github.com/aheckmann) +* Add text to readpreference obedient commands (Issue #1019) +* Drivers should check the query failure bit even on getmore response (Issue #1018) +* Map reduce has incorrect expectations of 'inline' value for 'out' option (Issue #1016, https://github.com/rcotter) +* Support SASL PLAIN authentication (Issue #1009) +* Ability to use different Service Name on the driver for Kerberos Authentication (Issue #1008) +* Remove unnecessary octal literal to allow the code to run in strict mode (Issue #1005, https://github.com/jamesallardice) +* Proper handling of recovering nodes (when they go into recovery and when they return from recovery, Issue #1027) + +1.3.10 2013-06-17 +----------------- +* Guard against possible undefined in server::canCheckoutWriter (Issue #992, https://github.com/willyaranda) +* Fixed some duplicate test names (Issue #993, https://github.com/kawanet) +* Introduced write and read concerns for GridFS (Issue #996) +* Fixed commands not correctly respecting Collection level read preference (Issue #995, #999) +* Fixed issue with pool size on replicaset connections (Issue #1000) +* Execute all query commands on master switch (Issue #1002, https://github.com/fogaztuc) + +1.3.9 2013-06-05 +---------------- +* Fixed memory leak when findAndModify errors out on w>1 and chained callbacks not properly cleaned up. + +1.3.8 2013-05-31 +---------------- +* Fixed issue with socket death on windows where it emits error event instead of close event (Issue #987) +* Emit authenticate event on db after authenticate method has finished on db instance (Issue #984) +* Allows creation of MongoClient and do new MongoClient().connect(..). Emits open event when connection correct allowing for apps to react on event. + +1.3.7 2013-05-29 +---------------- +* After reconnect, tailable getMores go on inconsistent connections (Issue #981, #982, https://github.com/glasser) +* Updated Bson to 0.1.9 to fix ARM support (Issue #985) + +1.3.6 2013-05-21 +---------------- +* Fixed issue where single server reconnect attempt would throw due to missing options variable (Issue #979) +* Fixed issue where difference in ismaster server name and seed list caused connections issues, (Issue #976) + +1.3.5 2013-05-14 +---------------- +* Fixed issue where HA for replicaset would pick the same broken connection when attempting to ping the replicaset causing the replicaset to never recover. + +1.3.4 2013-05-14 +---------------- +* Fixed bug where options not correctly passed in for uri parser (Issue #973, https://github.com/supershabam) +* Fixed bug when passing a named index hint (Issue #974) + +1.3.3 2013-05-09 +---------------- +* Fixed auto-reconnect issue with single server instance. + +1.3.2 2013-05-08 +---------------- +* Fixes for an issue where replicaset would be pronounced dead when high priority primary caused double elections. + +1.3.1 2013-05-06 +---------------- +* Fix for replicaset consisting of primary/secondary/arbiter with priority applied failing to reconnect properly +* Applied auth before server instance is set as connected when single server connection +* Throw error if array of documents passed to save method + +1.3.0 2013-04-25 +---------------- +* Whole High availability handling for Replicaset, Server and Mongos connections refactored to ensure better handling of failover cases. +* Fixed issue where findAndModify would not correctly skip issuing of chained getLastError (Issue #941) +* Fixed throw error issue on errors with findAndModify during write out operation (Issue #939, https://github.com/autopulated) +* Gridstore.prototype.writeFile now returns gridstore object correctly (Issue #938) +* Kerberos support is now an optional module that allows for use of GSSAPI authentication using MongoDB Subscriber edition +* Fixed issue where cursor.toArray could blow the stack on node 0.10.X (#950) + +1.2.14 2013-03-14 +----------------- +* Refactored test suite to speed up running of replicaset tests +* Fix of async error handling when error happens in callback (Issue #909, https://github.com/medikoo) +* Corrected a slaveOk setting issue (Issue #906, #905) +* Fixed HA issue where ping's would not go to correct server on HA server connection failure. +* Uses setImmediate if on 0.10 otherwise nextTick for cursor stream +* Fixed race condition in Cursor stream (NODE-31) +* Fixed issues related to node 0.10 and process.nextTick now correctly using setImmediate where needed on node 0.10 +* Added support for maxMessageSizeBytes if available (DRIVERS-1) +* Added support for authSource (2.4) to MongoClient URL and db.authenticate method (DRIVER-69/NODE-34) +* Fixed issue in GridStore seek and GridStore read to correctly work on multiple seeks (Issue #895) + +1.2.13 2013-02-22 +----------------- +* Allow strategy 'none' for repliaset if no strategy wanted (will default to round robin selection of servers on a set readPreference) +* Fixed missing MongoErrors on some cursor methods (Issue #882) +* Correctly returning a null for the db instance on MongoClient.connect when auth fails (Issue #890) +* Added dropTarget option support for renameCollection/rename (Issue #891, help from https://github.com/jbottigliero) +* Fixed issue where connection using MongoClient.connect would fail if first server did not exist (Issue #885) + +1.2.12 2013-02-13 +----------------- +* Added limit/skip options to Collection.count (Issue #870) +* Added applySkipLimit option to Cursor.count (Issue #870) +* Enabled ping strategy as default for Replicaset if none specified (Issue #876) +* Should correctly pick nearest server for SECONDARY/SECONDARY_PREFERRED/NEAREST (Issue #878) + +1.2.11 2013-01-29 +----------------- +* Added fixes for handling type 2 binary due to PHP driver (Issue #864) +* Moved callBackStore to Base class to have single unified store (Issue #866) +* Ping strategy now reuses sockets unless they are closed by the server to avoid overhead + +1.2.10 2013-01-25 +----------------- +* Merged in SSL support for 2.4 supporting certificate validation and presenting certificates to the server. +* Only open a new HA socket when previous one dead (Issue #859, #857) +* Minor fixes + +1.2.9 2013-01-15 +---------------- +* Fixed bug in SSL support for MongoClient/Db.connect when discovering servers (Issue #849) +* Connection string with no db specified should default to admin db (Issue #848) +* Support port passed as string to Server class (Issue #844) +* Removed noOpen support for MongoClient/Db.connect as auto discovery of servers for Mongod/Mongos makes it not possible (Issue #842) +* Included toError wrapper code moved to utils.js file (Issue #839, #840) +* Rewrote cursor handling to avoid process.nextTick using trampoline instead to avoid stack overflow, speedup about 40% + +1.2.8 2013-01-07 +---------------- +* Accept function in a Map Reduce scope object not only a function string (Issue #826, https://github.com/aheckmann) +* Typo in db.authenticate caused a check (for provided connection) to return false, causing a connection AND onAll=true to be passed into __executeQueryCommand downstream (Issue #831, https://github.com/m4tty) +* Allow gridfs objects to use non ObjectID ids (Issue #825, https://github.com/nailgun) +* Removed the double wrap, by not passing an Error object to the wrap function (Issue #832, https://github.com/m4tty) +* Fix connection leak (gh-827) for HA replicaset health checks (Issue #833, https://github.com/aheckmann) +* Modified findOne to use nextObject instead of toArray avoiding a nextTick operation (Issue #836) +* Fixes for cursor stream to avoid multiple getmore issues when one in progress (Issue #818) +* Fixes .open replaying all backed up commands correctly if called after operations performed, (Issue #829 and #823) + +1.2.7 2012-12-23 +---------------- +* Rolled back batches as they hang in certain situations +* Fixes for NODE-25, keep reading from secondaries when primary goes down + +1.2.6 2012-12-21 +---------------- +* domain sockets shouldn't require a port arg (Issue #815, https://github.com/aheckmann) +* Cannot read property 'info' of null (Issue #809, https://github.com/thesmart) +* Cursor.each should work in batches (Issue #804, https://github.com/Swatinem) +* Cursor readPreference bug for non-supported read preferences (Issue #817) + +1.2.5 2012-12-12 +---------------- +* Fixed ssl regression, added more test coverage (Issue #800) +* Added better error reporting to the Db.connect if no valid serverConfig setup found (Issue #798) + +1.2.4 2012-12-11 +---------------- +* Fix to ensure authentication is correctly applied across all secondaries when using MongoClient. + +1.2.3 2012-12-10 +---------------- +* Fix for new replicaset members correctly authenticating when being added (Issue #791, https://github.com/m4tty) +* Fixed seek issue in gridstore when using stream (Issue #790) + +1.2.2 2012-12-03 +---------------- +* Fix for journal write concern not correctly being passed under some circumstances. +* Fixed correct behavior and re-auth for servers that get stepped down (Issue #779). + +1.2.1 2012-11-30 +---------------- +* Fix for double callback on insert with w:0 specified (Issue #783) +* Small cleanup of urlparser. + +1.2.0 2012-11-27 +---------------- +* Honor connectTimeoutMS option for replicasets (Issue #750, https://github.com/aheckmann) +* Fix ping strategy regression (Issue #738, https://github.com/aheckmann) +* Small cleanup of code (Issue #753, https://github.com/sokra/node-mongodb-native) +* Fixed index declaration using objects/arrays from other contexts (Issue #755, https://github.com/sokra/node-mongodb-native) +* Intermittent (and rare) null callback exception when using ReplicaSets (Issue #752) +* Force correct setting of read_secondary based on the read preference (Issue #741) +* If using read preferences with secondaries queries will not fail if primary is down (Issue #744) +* noOpen connection for Db.connect removed as not compatible with autodetection of Mongo type +* Mongos connection with auth not working (Issue #737) +* Use the connect method directly from the require. require('mongodb')("mongodb://localhost:27017/db") +* new MongoClient introduced as the point of connecting to MongoDB's instead of the Db + * open/close/db/connect methods implemented +* Implemented common URL connection format using MongoClient.connect allowing for simialar interface across all drivers. +* Fixed a bug with aggregation helper not properly accepting readPreference + +1.1.11 2012-10-10 +----------------- +* Removed strict mode and introduced normal handling of safe at DB level. + +1.1.10 2012-10-08 +----------------- +* fix Admin.serverStatus (Issue #723, https://github.com/Contra) +* logging on connection open/close(Issue #721, https://github.com/asiletto) +* more fixes for windows bson install (Issue #724) + +1.1.9 2012-10-05 +---------------- +* Updated bson to 0.1.5 to fix build problem on sunos/windows. + +1.1.8 2012-10-01 +---------------- +* Fixed db.eval to correctly handle system.js global javascript functions (Issue #709) +* Cleanup of non-closing connections (Issue #706) +* More cleanup of connections under replicaset (Issue #707, https://github.com/elbert3) +* Set keepalive on as default, override if not needed +* Cleanup of jsbon install to correctly build without install.js script (https://github.com/shtylman) +* Added domain socket support new Server("/tmp/mongodb.sock") style + +1.1.7 2012-09-10 +---------------- +* Protect against starting PingStrategy being called more than once (Issue #694, https://github.com/aheckmann) +* Make PingStrategy interval configurable (was 1 second, relaxed to 5) (Issue #693, https://github.com/aheckmann) +* Made PingStrategy api more consistant, callback to start/stop methods are optional (Issue #693, https://github.com/aheckmann) +* Proper stopping of strategy on replicaset stop +* Throw error when gridstore file is not found in read mode (Issue #702, https://github.com/jbrumwell) +* Cursor stream resume now using nextTick to avoid duplicated records (Issue #696) + +1.1.6 2012-09-01 +---------------- +* Fix for readPreference NEAREST for replicasets (Issue #693, https://github.com/aheckmann) +* Emit end correctly on stream cursor (Issue #692, https://github.com/Raynos) + +1.1.5 2012-08-29 +---------------- +* Fix for eval on replicaset Issue #684 +* Use helpful error msg when native parser not compiled (Issue #685, https://github.com/aheckmann) +* Arbiter connect hotfix (Issue #681, https://github.com/fengmk2) +* Upgraded bson parser to 0.1.2 using gyp, deprecated support for node 0.4.X +* Added name parameter to createIndex/ensureIndex to be able to override index names larger than 128 bytes +* Added exhaust option for find for feature completion (not recommended for normal use) +* Added tailableRetryInterval to find for tailable cursors to allow to control getMore retry time interval +* Fixes for read preferences when using MongoS to correctly handle no read preference set when iterating over a cursor (Issue #686) + +1.1.4 2012-08-12 +---------------- +* Added Mongos connection type with a fallback list for mongos proxies, supports ha (on by default) and will attempt to reconnect to failed proxies. +* Documents can now have a toBSON method that lets the user control the serialization behavior for documents being saved. +* Gridstore instance object now works as a readstream or writestream (thanks to code from Aaron heckmann (https://github.com/aheckmann/gridfs-stream)). +* Fix gridfs readstream (Issue #607, https://github.com/tedeh). +* Added disableDriverBSONSizeCheck property to Server.js for people who wish to push the inserts to the limit (Issue #609). +* Fixed bug where collection.group keyf given as Code is processed as a regular object (Issue #608, https://github.com/rrusso2007). +* Case mismatch between driver's ObjectID and mongo's ObjectId, allow both (Issue #618). +* Cleanup map reduce (Issue #614, https://github.com/aheckmann). +* Add proper error handling to gridfs (Issue #615, https://github.com/aheckmann). +* Ensure cursor is using same connection for all operations to avoid potential jump of servers when using replicasets. +* Date identification handled correctly in bson js parser when running in vm context. +* Documentation updates +* GridStore filename not set on read (Issue #621) +* Optimizations on the C++ bson parser to fix a potential memory leak and avoid non-needed calls +* Added support for awaitdata for tailable cursors (Issue #624) +* Implementing read preference setting at collection and cursor level + * collection.find().setReadPreference(Server.SECONDARY_PREFERRED) + * db.collection("some", {readPreference:Server.SECONDARY}) +* Replicaset now returns when the master is discovered on db.open and lets the rest of the connections happen asynchronous. + * ReplSet/ReplSetServers emits "fullsetup" when all servers have been connected to +* Prevent callback from executing more than once in getMore function (Issue #631, https://github.com/shankar0306) +* Corrupt bson messages now errors out to all callbacks and closes up connections correctly, Issue #634 +* Replica set member status update when primary changes bug (Issue #635, https://github.com/alinsilvian) +* Fixed auth to work better when multiple connections are involved. +* Default connection pool size increased to 5 connections. +* Fixes for the ReadStream class to work properly with 0.8 of Node.js +* Added explain function support to aggregation helper +* Added socketTimeoutMS and connectTimeoutMS to socket options for repl_set.js and server.js +* Fixed addUser to correctly handle changes in 2.2 for getLastError authentication required +* Added index to gridstore chunks on file_id (Issue #649, https://github.com/jacobbubu) +* Fixed Always emit db events (Issue #657) +* Close event not correctly resets DB openCalled variable to allow reconnect +* Added open event on connection established for replicaset, mongos and server +* Much faster BSON C++ parser thanks to Lucasfilm Singapore. +* Refactoring of replicaset connection logic to simplify the code. +* Add `options.connectArbiter` to decide connect arbiters or not (Issue #675) +* Minor optimization for findAndModify when not using j,w or fsync for safe + +1.0.2 2012-05-15 +---------------- +* Reconnect functionality for replicaset fix for mongodb 2.0.5 + +1.0.1 2012-05-12 +---------------- +* Passing back getLastError object as 3rd parameter on findAndModify command. +* Fixed a bunch of performance regressions in objectId and cursor. +* Fixed issue #600 allowing for single document delete to be passed in remove command. + +1.0.0 2012-04-25 +---------------- +* Fixes to handling of failover on server error +* Only emits error messages if there are error listeners to avoid uncaught events +* Server.isConnected using the server state variable not the connection pool state + +0.9.9.8 2012-04-12 +------------------ +* _id=0 is being turned into an ObjectID (Issue #551) +* fix for error in GridStore write method (Issue #559) +* Fix for reading a GridStore from arbitrary, non-chunk aligned offsets, added test (Issue #563, https://github.com/subroutine) +* Modified limitRequest to allow negative limits to pass through to Mongo, added test (Issue #561) +* Corrupt GridFS files when chunkSize < fileSize, fixed concurrency issue (Issue #555) +* Handle dead tailable cursors (Issue #568, https://github.com/aheckmann) +* Connection pools handles closing themselves down and clearing the state +* Check bson size of documents against maxBsonSize and throw client error instead of server error, (Issue #553) +* Returning update status document at the end of the callback for updates, (Issue #569) +* Refactor use of Arguments object to gain performance (Issue #574, https://github.com/AaronAsAChimp) + +0.9.9.7 2012-03-16 +------------------ +* Stats not returned from map reduce with inline results (Issue #542) +* Re-enable testing of whether or not the callback is called in the multi-chunk seek, fix small GridStore bug (Issue #543, https://github.com/pgebheim) +* Streaming large files from GridFS causes truncation (Issue #540) +* Make callback type checks agnostic to V8 context boundaries (Issue #545) +* Correctly throw error if an attempt is made to execute an insert/update/remove/createIndex/ensureIndex with safe enabled and no callback +* Db.open throws if the application attemps to call open again without calling close first + +0.9.9.6 2012-03-12 +------------------ +* BSON parser is externalized in it's own repository, currently using git master +* Fixes for Replicaset connectivity issue (Issue #537) +* Fixed issues with node 0.4.X vs 0.6.X (Issue #534) +* Removed SimpleEmitter and replaced with standard EventEmitter +* GridStore.seek fails to change chunks and call callback when in read mode (Issue #532) + +0.9.9.5 2012-03-07 +------------------ +* Merged in replSetGetStatus helper to admin class (Issue #515, https://github.com/mojodna) +* Merged in serverStatus helper to admin class (Issue #516, https://github.com/mojodna) +* Fixed memory leak in C++ bson parser (Issue #526) +* Fix empty MongoError "message" property (Issue #530, https://github.com/aheckmann) +* Cannot save files with the same file name to GridFS (Issue #531) + +0.9.9.4 2012-02-26 +------------------ +* bugfix for findAndModify: Error: corrupt bson message < 5 bytes long (Issue #519) + +0.9.9.3 2012-02-23 +------------------ +* document: save callback arguments are both undefined, (Issue #518) +* Native BSON parser install error with npm, (Issue #517) + +0.9.9.2 2012-02-17 +------------------ +* Improved detection of Buffers using Buffer.isBuffer instead of instanceof. +* Added wrap error around db.dropDatabase to catch all errors (Issue #512) +* Added aggregate helper to collection, only for MongoDB >= 2.1 + +0.9.9.1 2012-02-15 +------------------ +* Better handling of safe when using some commands such as createIndex, ensureIndex, addUser, removeUser, createCollection. +* Mapreduce now throws error if out parameter is not specified. + +0.9.9 2012-02-13 +---------------- +* Added createFromTime method on ObjectID to allow for queries against _id more easily using the timestamp. +* Db.close(true) now makes connection unusable as it's been force closed by app. +* Fixed mapReduce and group functions to correctly send slaveOk on queries. +* Fixes for find method to correctly work with find(query, fields, callback) (Issue #506). +* A fix for connection error handling when using the SSL on MongoDB. + +0.9.8-7 2012-02-06 +------------------ +* Simplified findOne to use the find command instead of the custom code (Issue #498). +* BSON JS parser not also checks for _bsonType variable in case BSON object is in weird scope (Issue #495). + +0.9.8-6 2012-02-04 +------------------ +* Removed the check for replicaset change code as it will never work with node.js. + +0.9.8-5 2012-02-02 +------------------ +* Added geoNear command to Collection. +* Added geoHaystackSearch command to Collection. +* Added indexes command to collection to retrieve the indexes on a Collection. +* Added stats command to collection to retrieve the statistics on a Collection. +* Added listDatabases command to admin object to allow retrieval of all available dbs. +* Changed createCreateIndexCommand to work better with options. +* Fixed dereference method on Db class to correctly dereference Db reference objects. +* Moved connect object onto Db class(Db.connect) as well as keeping backward compatibility. +* Removed writeBuffer method from gridstore, write handles switching automatically now. +* Changed readBuffer to read on Gridstore, Gridstore now only supports Binary Buffers no Strings anymore. +* Moved Long class to bson directory. + +0.9.8-4 2012-01-28 +------------------ +* Added reIndex command to collection and db level. +* Added support for $returnKey, $maxScan, $min, $max, $showDiskLoc, $comment to cursor and find/findOne methods. +* Added dropDups and v option to createIndex and ensureIndex. +* Added isCapped method to Collection. +* Added indexExists method to Collection. +* Added findAndRemove method to Collection. +* Fixed bug for replicaset connection when no active servers in the set. +* Fixed bug for replicaset connections when errors occur during connection. +* Merged in patch for BSON Number handling from Lee Salzman, did some small fixes and added test coverage. + +0.9.8-3 2012-01-21 +------------------ +* Workaround for issue with Object.defineProperty (Issue #484) +* ObjectID generation with date does not set rest of fields to zero (Issue #482) + +0.9.8-2 2012-01-20 +------------------ +* Fixed a missing this in the ReplSetServers constructor. + +0.9.8-1 2012-01-17 +------------------ +* FindAndModify bug fix for duplicate errors (Issue #481) + +0.9.8 2012-01-17 +---------------- +* Replicasets now correctly adjusts to live changes in the replicaset configuration on the servers, reconnecting correctly. + * Set the interval for checking for changes setting the replicaSetCheckInterval property when creating the ReplSetServers instance or on db.serverConfig.replicaSetCheckInterval. (default 1000 miliseconds) +* Fixes formattedOrderClause in collection.js to accept a plain hash as a parameter (Issue #469) https://github.com/tedeh +* Removed duplicate code for formattedOrderClause and moved to utils module +* Pass in poolSize for ReplSetServers to set default poolSize for new replicaset members +* Bug fix for BSON JS deserializer. Isolating the eval functions in separate functions to avoid V8 deoptimizations +* Correct handling of illegal BSON messages during deserialization +* Fixed Infinite loop when reading GridFs file with no chunks (Issue #471) +* Correctly update existing user password when using addUser (Issue #470) + +0.9.7.3-5 2012-01-04 +-------------------- +* Fix for RegExp serialization for 0.4.X where typeof /regexp/ == 'function' vs in 0.6.X typeof /regexp/ == 'object' +* Don't allow keepAlive and setNoDelay for 0.4.X as it throws errors + +0.9.7.3-4 2012-01-04 +-------------------- +* Chased down potential memory leak on findAndModify, Issue #467 (node.js removeAllListeners leaves the key in the _events object, node.js bug on eventlistener?, leads to extremely slow memory leak on listener object) +* Sanity checks for GridFS performance with benchmark added + +0.9.7.3-3 2012-01-04 +-------------------- +* Bug fixes for performance issues going form 0.9.6.X to 0.9.7.X on linux +* BSON bug fixes for performance + +0.9.7.3-2 2012-01-02 +-------------------- +* Fixed up documentation to reflect the preferred way of instantiating bson types +* GC bug fix for JS bson parser to avoid stop-and-go GC collection + +0.9.7.3-1 2012-01-02 +-------------------- +* Fix to make db.bson_serializer and db.bson_deserializer work as it did previously + +0.9.7.3 2011-12-30 +-------------------- +* Moved BSON_BINARY_SUBTYPE_DEFAULT from BSON object to Binary object and removed the BSON_BINARY_ prefixes +* Removed Native BSON types, C++ parser uses JS types (faster due to cost of crossing the JS-C++ barrier for each call) +* Added build fix for 0.4.X branch of Node.js where GetOwnPropertyNames is not defined in v8 +* Fix for wire protocol parser for corner situation where the message is larger than the maximum socket buffer in node.js (Issue #464, #461, #447) +* Connection pool status set to connected on poolReady, isConnected returns false on anything but connected status (Issue #455) + +0.9.7.2-5 2011-12-22 +-------------------- +* Brand spanking new Streaming Cursor support Issue #458 (https://github.com/christkv/node-mongodb-native/pull/458) thanks to Mr Aaron Heckmann + +0.9.7.2-4 2011-12-21 +-------------------- +* Refactoring of callback code to work around performance regression on linux +* Fixed group function to correctly use the command mode as default + +0.9.7.2-3 2011-12-18 +-------------------- +* Fixed error handling for findAndModify while still working for mongodb 1.8.6 (Issue #450). +* Allow for force send query to primary, pass option (read:'primary') on find command. + * ``find({a:1}, {read:'primary'}).toArray(function(err, items) {});`` + +0.9.7.2-2 2011-12-16 +-------------------- +* Fixes infinite streamRecords QueryFailure fix when using Mongos (Issue #442) + +0.9.7.2-1 2011-12-16 +-------------------- +* ~10% perf improvement for ObjectId#toHexString (Issue #448, https://github.com/aheckmann) +* Only using process.nextTick on errors emitted on callbacks not on all parsing, reduces number of ticks in the driver +* Changed parsing off bson messages to use process.nextTick to do bson parsing in batches if the message is over 10K as to yield more time to the event look increasing concurrency on big mongoreply messages with multiple documents + +0.9.7.2 2011-12-15 +------------------ +* Added SSL support for future version of mongodb (VERY VERY EXPERIMENTAL) + * pass in the ssl:true option to the server or replicaset server config to enable + * a bug either in mongodb or node.js does not allow for more than 1 connection pr db instance (poolSize:1). +* Added getTimestamp() method to objectID that returns a date object +* Added finalize function to collection.group + * function group (keys, condition, initial, reduce, finalize, command, callback) +* Reaper no longer using setTimeout to handle reaping. Triggering is done in the general flow leading to predictable behavior. + * reaperInterval, set interval for reaper (default 10000 miliseconds) + * reaperTimeout, set timeout for calls (default 30000 miliseconds) + * reaper, enable/disable reaper (default false) +* Work around for issues with findAndModify during high concurrency load, insure that the behavior is the same across the 1.8.X branch and 2.X branch of MongoDb +* Reworked multiple db's sharing same connection pool to behave correctly on error, timeout and close +* EnsureIndex command can be executed without a callback (Issue #438) +* Eval function no accepts options including nolock (Issue #432) + * eval(code, parameters, options, callback) (where options = {nolock:true}) + +0.9.7.1-4 2011-11-27 +-------------------- +* Replaced install.sh with install.js to install correctly on all supported os's + +0.9.7.1-3 2011-11-27 +-------------------- +* Fixes incorrect scope for ensureIndex error wrapping (Issue #419) https://github.com/ritch + +0.9.7.1-2 2011-11-27 +-------------------- +* Set statistical selection strategy as default for secondary choice. + +0.9.7.1-1 2011-11-27 +-------------------- +* Better handling of single server reconnect (fixes some bugs) +* Better test coverage of single server failure +* Correct handling of callbacks on replicaset servers when firewall dropping packets, correct reconnect + +0.9.7.1 2011-11-24 +------------------ +* Better handling of dead server for single server instances +* FindOne and find treats selector == null as {}, Issue #403 +* Possible to pass in a strategy for the replicaset to pick secondary reader node + * parameter strategy + * ping (default), pings the servers and picks the one with the lowest ping time + * statistical, measures each request and pick the one with the lowest mean and std deviation +* Set replicaset read preference replicaset.setReadPreference() + * Server.READ_PRIMARY (use primary server for reads) + * Server.READ_SECONDARY (from a secondary server (uses the strategy set)) + * tags, {object of tags} +* Added replay of commands issued to a closed connection when the connection is re-established +* Fix isConnected and close on unopened connections. Issue #409, fix by (https://github.com/sethml) +* Moved reaper to db.open instead of constructor (Issue #406) +* Allows passing through of socket connection settings to Server or ReplSetServer under the option socketOptions + * timeout = set seconds before connection times out (default 0) + * noDelay = Disables the Nagle algorithm (default true) + * keepAlive = Set if keepAlive is used (default 0, which means no keepAlive, set higher than 0 for keepAlive) + * encoding = ['ascii', 'utf8', or 'base64'] (default null) +* Fixes for handling of errors during shutdown off a socket connection +* Correctly applies socket options including timeout +* Cleanup of test management code to close connections correctly +* Handle parser errors better, closing down the connection and emitting an error +* Correctly emit errors from server.js only wrapping errors that are strings + +0.9.7 2011-11-10 +---------------- +* Added priority setting to replicaset manager +* Added correct handling of passive servers in replicaset +* Reworked socket code for simpler clearer handling +* Correct handling of connections in test helpers +* Added control of retries on failure + * control with parameters retryMiliSeconds and numberOfRetries when creating a db instance +* Added reaper that will timeout and cleanup queries that never return + * control with parameters reaperInterval and reaperTimeout when creating a db instance +* Refactored test helper classes for replicaset tests +* Allows raw (no bson parser mode for insert, update, remove, find and findOne) + * control raw mode passing in option raw:true on the commands + * will return buffers with the binary bson objects +* Fixed memory leak in cursor.toArray +* Fixed bug in command creation for mongodb server with wrong scope of call +* Added db(dbName) method to db.js to allow for reuse of connections against other databases +* Serialization of functions in an object is off by default, override with parameter + * serializeFunctions [true/false] on db level, collection level or individual insert/update/findAndModify +* Added Long.fromString to c++ class and fixed minor bug in the code (Test case for $gt operator on 64-bit integers, Issue #394) +* FindOne and find now share same code execution and will work in the same manner, Issue #399 +* Fix for tailable cursors, Issue #384 +* Fix for Cursor rewind broken, Issue #389 +* Allow Gridstore.exist to query using regexp, Issue #387, fix by (https://github.com/kaij) +* Updated documentation on https://github.com/christkv/node-mongodb-native +* Fixed toJSON methods across all objects for BSON, Binary return Base64 Encoded data + +0.9.6-22 2011-10-15 +------------------- +* Fixed bug in js bson parser that could cause wrong object size on serialization, Issue #370 +* Fixed bug in findAndModify that did not throw error on replicaset timeout, Issue #373 + +0.9.6-21 2011-10-05 +------------------- +* Reworked reconnect code to work correctly +* Handling errors in different parts of the code to ensure that it does not lock the connection +* Consistent error handling for Object.createFromHexString for JS and C++ + +0.9.6-20 2011-10-04 +------------------- +* Reworked bson.js parser to get rid off Array.shift() due to it allocating new memory for each call. Speedup varies between 5-15% depending on doc +* Reworked bson.cc to throw error when trying to serialize js bson types +* Added MinKey, MaxKey and Double support for JS and C++ parser +* Reworked socket handling code to emit errors on unparsable messages +* Added logger option for Db class, lets you pass in a function in the shape + { + log : function(message, object) {}, + error : function(errorMessage, errorObject) {}, + debug : function(debugMessage, object) {}, + } + + Usage is new Db(new Server(..), {logger: loggerInstance}) + +0.9.6-19 2011-09-29 +------------------- +* Fixing compatibility issues between C++ bson parser and js parser +* Added Symbol support to C++ parser +* Fixed socket handling bug for seldom misaligned message from mongodb +* Correctly handles serialization of functions using the C++ bson parser + +0.9.6-18 2011-09-22 +------------------- +* Fixed bug in waitForConnection that would lead to 100% cpu usage, Issue #352 + +0.9.6-17 2011-09-21 +------------------- +* Fixed broken exception test causing bamboo to hang +* Handling correctly command+lastError when both return results as in findAndModify, Issue #351 + +0.9.6-16 2011-09-14 +------------------- +* Fixing a bunch of issues with compatibility with MongoDB 2.0.X branch. Some fairly big changes in behavior from 1.8.X to 2.0.X on the server. +* Error Connection MongoDB V2.0.0 with Auth=true, Issue #348 + +0.9.6-15 2011-09-09 +------------------- +* Fixed issue where pools would not be correctly cleaned up after an error, Issue #345 +* Fixed authentication issue with secondary servers in Replicaset, Issue #334 +* Duplicate replica-set servers when omitting port, Issue #341 +* Fixing findAndModify to correctly work with Replicasets ensuring proper error handling, Issue #336 +* Merged in code from (https://github.com/aheckmann) that checks for global variable leaks + +0.9.6-14 2011-09-05 +------------------- +* Minor fixes for error handling in cursor streaming (https://github.com/sethml), Issue #332 +* Minor doc fixes +* Some more cursor sort tests added, Issue #333 +* Fixes to work with 0.5.X branch +* Fix Db not removing reconnect listener from serverConfig, (https://github.com/sbrekken), Issue #337 +* Removed node_events.h includes (https://github.com/jannehietamaki), Issue #339 +* Implement correct safe/strict mode for findAndModify. + +0.9.6-13 2011-08-24 +------------------- +* Db names correctly error checked for illegal characters + +0.9.6-12 2011-08-24 +------------------- +* Nasty bug in GridFS if you changed the default chunk size +* Fixed error handling bug in findOne + +0.9.6-11 2011-08-23 +------------------- +* Timeout option not correctly making it to the cursor, Issue #320, Fix from (https://github.com/year2013) +* Fixes for memory leaks when using buffers and C++ parser +* Fixes to make tests pass on 0.5.X +* Cleanup of bson.js to remove duplicated code paths +* Fix for errors occurring in ensureIndex, Issue #326 +* Removing require.paths to make tests work with the 0.5.X branch + +0.9.6-10 2011-08-11 +------------------- +* Specific type Double for capped collections (https://github.com/mbostock), Issue #312 +* Decorating Errors with all all object info from Mongo (https://github.com/laurie71), Issue #308 +* Implementing fixes for mongodb 1.9.1 and higher to make tests pass +* Admin validateCollection now takes an options argument for you to pass in full option +* Implemented keepGoing parameter for mongodb 1.9.1 or higher, Issue #310 +* Added test for read_secondary count issue, merged in fix from (https://github.com/year2013), Issue #317 + +0.9.6-9 +------- +* Bug fix for bson parsing the key '':'' correctly without crashing + +0.9.6-8 +------- +* Changed to using node.js crypto library MD5 digest +* Connect method support documented mongodb: syntax by (https://github.com/sethml) +* Support Symbol type for BSON, serializes to it's own type Symbol, Issue #302, #288 +* Code object without scope serializing to correct BSON type +* Lot's of fixes to avoid double callbacks (https://github.com/aheckmann) Issue #304 +* Long deserializes as Number for values in the range -2^53 to 2^53, Issue #305 (https://github.com/sethml) +* Fixed C++ parser to reflect JS parser handling of long deserialization +* Bson small optimizations + +0.9.6-7 2011-07-13 +------------------ +* JS Bson deserialization bug #287 + +0.9.6-6 2011-07-12 +------------------ +* FindAndModify not returning error message as other methods Issue #277 +* Added test coverage for $push, $pushAll and $inc atomic operations +* Correct Error handling for non 12/24 bit ids on Pure JS ObjectID class Issue #276 +* Fixed terrible deserialization bug in js bson code #285 +* Fix by andrewjstone to avoid throwing errors when this.primary not defined + +0.9.6-5 2011-07-06 +------------------ +* Rewritten BSON js parser now faster than the C parser on my core2duo laptop +* Added option full to indexInformation to get all index info Issue #265 +* Passing in ObjectID for new Gridstore works correctly Issue #272 + +0.9.6-4 2011-07-01 +------------------ +* Added test and bug fix for insert/update/remove without callback supplied + +0.9.6-3 2011-07-01 +------------------ +* Added simple grid class called Grid with put, get, delete methods +* Fixed writeBuffer/readBuffer methods on GridStore so they work correctly +* Automatic handling of buffers when using write method on GridStore +* GridStore now accepts a ObjectID instead of file name for write and read methods +* GridStore.list accepts id option to return of file ids instead of filenames +* GridStore close method returns document for the file allowing user to reference _id field + +0.9.6-2 2011-06-30 +------------------ +* Fixes for reconnect logic for server object (replays auth correctly) +* More testcases for auth +* Fixes in error handling for replicaset +* Fixed bug with safe parameter that would fail to execute safe when passing w or wtimeout +* Fixed slaveOk bug for findOne method +* Implemented auth support for replicaset and test cases +* Fixed error when not passing in rs_name + +0.9.6-1 2011-06-25 +------------------ +* Fixes for test to run properly using c++ bson parser +* Fixes for dbref in native parser (correctly handles ref without db component) +* Connection fixes for replicasets to avoid runtime conditions in cygwin (https://github.com/vincentcr) +* Fixes for timestamp in js bson parser (distinct timestamp type now) + +0.9.6 2011-06-21 +---------------- +* Worked around npm version handling bug +* Race condition fix for cygwin (https://github.com/vincentcr) + +0.9.5-1 2011-06-21 +------------------ +* Extracted Timestamp as separate class for bson js parser to avoid instanceof problems +* Fixed driver strict mode issue + +0.9.5 2011-06-20 +---------------- +* Replicaset support (failover and reading from secondary servers) +* Removed ServerPair and ServerCluster +* Added connection pool functionality +* Fixed serious bug in C++ bson parser where bytes > 127 would generate 2 byte sequences +* Allows for forcing the server to assign ObjectID's using the option {forceServerObjectId: true} + +0.6.8 +----- +* Removed multiple message concept from bson +* Changed db.open(db) to be db.open(err, db) + +0.1 2010-01-30 +-------------- +* Initial release support of driver using native node.js interface +* Supports gridfs specification +* Supports admin functionality diff --git a/scripts/2.5/node_modules/mongodb/LICENSE.md b/scripts/2.5/node_modules/mongodb/LICENSE.md new file mode 100644 index 00000000..ad410e11 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/LICENSE.md @@ -0,0 +1,201 @@ +Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/scripts/2.5/node_modules/mongodb/README.md b/scripts/2.5/node_modules/mongodb/README.md new file mode 100644 index 00000000..672ccf39 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/README.md @@ -0,0 +1,499 @@ +[![npm](https://nodei.co/npm/mongodb.png?downloads=true&downloadRank=true)](https://nodei.co/npm/mongodb/) [![npm](https://nodei.co/npm-dl/mongodb.png?months=6&height=3)](https://nodei.co/npm/mongodb/) + +[![Build Status](https://secure.travis-ci.org/mongodb/node-mongodb-native.svg?branch=2.1)](http://travis-ci.org/mongodb/node-mongodb-native) +[![Coverage Status](https://coveralls.io/repos/github/mongodb/node-mongodb-native/badge.svg?branch=2.1)](https://coveralls.io/github/mongodb/node-mongodb-native?branch=2.1) +[![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/mongodb/node-mongodb-native?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) + +# Description + +The official [MongoDB](https://www.mongodb.com/) driver for Node.js. Provides a high-level API on top of [mongodb-core](https://www.npmjs.com/package/mongodb-core) that is meant for end users. + +**NOTE: v3.x was recently released with breaking API changes. You can find a list of changes [here](CHANGES_3.0.0.md).** + +## MongoDB Node.JS Driver + +| what | where | +|---------------|------------------------------------------------| +| documentation | http://mongodb.github.io/node-mongodb-native | +| api-doc | http://mongodb.github.io/node-mongodb-native/3.1/api | +| source | https://github.com/mongodb/node-mongodb-native | +| mongodb | http://www.mongodb.org | + +### Bugs / Feature Requests + +Think you’ve found a bug? Want to see a new feature in `node-mongodb-native`? Please open a +case in our issue management tool, JIRA: + +- Create an account and login [jira.mongodb.org](https://jira.mongodb.org). +- Navigate to the NODE project [jira.mongodb.org/browse/NODE](https://jira.mongodb.org/browse/NODE). +- Click **Create Issue** - Please provide as much information as possible about the issue type and how to reproduce it. + +Bug reports in JIRA for all driver projects (i.e. NODE, PYTHON, CSHARP, JAVA) and the +Core Server (i.e. SERVER) project are **public**. + +### Support / Feedback + +For issues with, questions about, or feedback for the Node.js driver, please look into our [support channels](http://www.mongodb.org/about/support). Please do not email any of the driver developers directly with issues or questions - you're more likely to get an answer on the [mongodb-user](http://groups.google.com/group/mongodb-user>) list on Google Groups. + +### Change Log + +Change history can be found in [`HISTORY.md`](HISTORY.md). + +### Compatibility + +For version compatibility matrices, please refer to the following links: + + * [MongoDB](https://docs.mongodb.com/ecosystem/drivers/driver-compatibility-reference/#reference-compatibility-mongodb-node) + * [NodeJS](https://docs.mongodb.com/ecosystem/drivers/driver-compatibility-reference/#reference-compatibility-language-node) + +# Installation + +The recommended way to get started using the Node.js 3.0 driver is by using the `npm` (Node Package Manager) to install the dependency in your project. + +## MongoDB Driver + +Given that you have created your own project using `npm init` we install the MongoDB driver and its dependencies by executing the following `npm` command. + +```bash +npm install mongodb --save +``` + +This will download the MongoDB driver and add a dependency entry in your `package.json` file. + +You can also use the [Yarn](https://yarnpkg.com/en) package manager. + +## Troubleshooting + +The MongoDB driver depends on several other packages. These are: + +* [mongodb-core](https://github.com/mongodb-js/mongodb-core) +* [bson](https://github.com/mongodb/js-bson) +* [kerberos](https://github.com/mongodb-js/kerberos) +* [node-gyp](https://github.com/nodejs/node-gyp) + +The `kerberos` package is a C++ extension that requires a build environment to be installed on your system. You must be able to build Node.js itself in order to compile and install the `kerberos` module. Furthermore, the `kerberos` module requires the MIT Kerberos package to correctly compile on UNIX operating systems. Consult your UNIX operation system package manager for what libraries to install. + +**Windows already contains the SSPI API used for Kerberos authentication. However, you will need to install a full compiler tool chain using Visual Studio C++ to correctly install the Kerberos extension.** + +### Diagnosing on UNIX + +If you don’t have the build-essentials, this module won’t build. In the case of Linux, you will need gcc, g++, Node.js with all the headers and Python. The easiest way to figure out what’s missing is by trying to build the Kerberos project. You can do this by performing the following steps. + +```bash +git clone https://github.com/mongodb-js/kerberos +cd kerberos +npm install +``` + +If all the steps complete, you have the right toolchain installed. If you get the error "node-gyp not found," you need to install `node-gyp` globally: + +```bash +npm install -g node-gyp +``` + +If it correctly compiles and runs the tests you are golden. We can now try to install the `mongod` driver by performing the following command. + +```bash +cd yourproject +npm install mongodb --save +``` + +If it still fails the next step is to examine the npm log. Rerun the command but in this case in verbose mode. + +```bash +npm --loglevel verbose install mongodb +``` + +This will print out all the steps npm is performing while trying to install the module. + +### Diagnosing on Windows + +A compiler tool chain known to work for compiling `kerberos` on Windows is the following. + +* Visual Studio C++ 2010 (do not use higher versions) +* Windows 7 64bit SDK +* Python 2.7 or higher + +Open the Visual Studio command prompt. Ensure `node.exe` is in your path and install `node-gyp`. + +```bash +npm install -g node-gyp +``` + +Next, you will have to build the project manually to test it. Clone the repo, install dependencies and rebuild: + +```bash +git clone https://github.com/christkv/kerberos.git +cd kerberos +npm install +node-gyp rebuild +``` + +This should rebuild the driver successfully if you have everything set up correctly. + +### Other possible issues + +Your Python installation might be hosed making gyp break. Test your deployment environment first by trying to build Node.js itself on the server in question, as this should unearth any issues with broken packages (and there are a lot of broken packages out there). + +Another tip is to ensure your user has write permission to wherever the Node.js modules are being installed. + +## Quick Start + +This guide will show you how to set up a simple application using Node.js and MongoDB. Its scope is only how to set up the driver and perform the simple CRUD operations. For more in-depth coverage, see the [tutorials](docs/reference/content/tutorials/main.md). + +### Create the `package.json` file + +First, create a directory where your application will live. + +```bash +mkdir myproject +cd myproject +``` + +Enter the following command and answer the questions to create the initial structure for your new project: + +```bash +npm init +``` + +Next, install the driver dependency. + +```bash +npm install mongodb --save +``` + +You should see **NPM** download a lot of files. Once it's done you'll find all the downloaded packages under the **node_modules** directory. + +### Start a MongoDB Server + +For complete MongoDB installation instructions, see [the manual](https://docs.mongodb.org/manual/installation/). + +1. Download the right MongoDB version from [MongoDB](https://www.mongodb.org/downloads) +2. Create a database directory (in this case under **/data**). +3. Install and start a ``mongod`` process. + +```bash +mongod --dbpath=/data +``` + +You should see the **mongod** process start up and print some status information. + +### Connect to MongoDB + +Create a new **app.js** file and add the following code to try out some basic CRUD +operations using the MongoDB driver. + +Add code to connect to the server and the database **myproject**: + +```js +const MongoClient = require('mongodb').MongoClient; +const assert = require('assert'); + +// Connection URL +const url = 'mongodb://localhost:27017'; + +// Database Name +const dbName = 'myproject'; + +// Use connect method to connect to the server +MongoClient.connect(url, function(err, client) { + assert.equal(null, err); + console.log("Connected successfully to server"); + + const db = client.db(dbName); + + client.close(); +}); +``` + +Run your app from the command line with: + +```bash +node app.js +``` + +The application should print **Connected successfully to server** to the console. + +### Insert a Document + +Add to **app.js** the following function which uses the **insertMany** +method to add three documents to the **documents** collection. + +```js +const insertDocuments = function(db, callback) { + // Get the documents collection + const collection = db.collection('documents'); + // Insert some documents + collection.insertMany([ + {a : 1}, {a : 2}, {a : 3} + ], function(err, result) { + assert.equal(err, null); + assert.equal(3, result.result.n); + assert.equal(3, result.ops.length); + console.log("Inserted 3 documents into the collection"); + callback(result); + }); +} +``` + +The **insert** command returns an object with the following fields: + +* **result** Contains the result document from MongoDB +* **ops** Contains the documents inserted with added **_id** fields +* **connection** Contains the connection used to perform the insert + +Add the following code to call the **insertDocuments** function: + +```js +const MongoClient = require('mongodb').MongoClient; +const assert = require('assert'); + +// Connection URL +const url = 'mongodb://localhost:27017'; + +// Database Name +const dbName = 'myproject'; + +// Use connect method to connect to the server +MongoClient.connect(url, function(err, client) { + assert.equal(null, err); + console.log("Connected successfully to server"); + + const db = client.db(dbName); + + insertDocuments(db, function() { + client.close(); + }); +}); +``` + +Run the updated **app.js** file: + +```bash +node app.js +``` + +The operation returns the following output: + +```bash +Connected successfully to server +Inserted 3 documents into the collection +``` + +### Find All Documents + +Add a query that returns all the documents. + +```js +const findDocuments = function(db, callback) { + // Get the documents collection + const collection = db.collection('documents'); + // Find some documents + collection.find({}).toArray(function(err, docs) { + assert.equal(err, null); + console.log("Found the following records"); + console.log(docs) + callback(docs); + }); +} +``` + +This query returns all the documents in the **documents** collection. Add the **findDocument** method to the **MongoClient.connect** callback: + +```js +const MongoClient = require('mongodb').MongoClient; +const assert = require('assert'); + +// Connection URL +const url = 'mongodb://localhost:27017'; + +// Database Name +const dbName = 'myproject'; + +// Use connect method to connect to the server +MongoClient.connect(url, function(err, client) { + assert.equal(null, err); + console.log("Connected correctly to server"); + + const db = client.db(dbName); + + insertDocuments(db, function() { + findDocuments(db, function() { + client.close(); + }); + }); +}); +``` + +### Find Documents with a Query Filter + +Add a query filter to find only documents which meet the query criteria. + +```js +const findDocuments = function(db, callback) { + // Get the documents collection + const collection = db.collection('documents'); + // Find some documents + collection.find({'a': 3}).toArray(function(err, docs) { + assert.equal(err, null); + console.log("Found the following records"); + console.log(docs); + callback(docs); + }); +} +``` + +Only the documents which match ``'a' : 3`` should be returned. + +### Update a document + +The following operation updates a document in the **documents** collection. + +```js +const updateDocument = function(db, callback) { + // Get the documents collection + const collection = db.collection('documents'); + // Update document where a is 2, set b equal to 1 + collection.updateOne({ a : 2 } + , { $set: { b : 1 } }, function(err, result) { + assert.equal(err, null); + assert.equal(1, result.result.n); + console.log("Updated the document with the field a equal to 2"); + callback(result); + }); +} +``` + +The method updates the first document where the field **a** is equal to **2** by adding a new field **b** to the document set to **1**. Next, update the callback function from **MongoClient.connect** to include the update method. + +```js +const MongoClient = require('mongodb').MongoClient; +const assert = require('assert'); + +// Connection URL +const url = 'mongodb://localhost:27017'; + +// Database Name +const dbName = 'myproject'; + +// Use connect method to connect to the server +MongoClient.connect(url, function(err, client) { + assert.equal(null, err); + console.log("Connected successfully to server"); + + const db = client.db(dbName); + + insertDocuments(db, function() { + updateDocument(db, function() { + client.close(); + }); + }); +}); +``` + +### Remove a document + +Remove the document where the field **a** is equal to **3**. + +```js +const removeDocument = function(db, callback) { + // Get the documents collection + const collection = db.collection('documents'); + // Delete document where a is 3 + collection.deleteOne({ a : 3 }, function(err, result) { + assert.equal(err, null); + assert.equal(1, result.result.n); + console.log("Removed the document with the field a equal to 3"); + callback(result); + }); +} +``` + +Add the new method to the **MongoClient.connect** callback function. + +```js +const MongoClient = require('mongodb').MongoClient; +const assert = require('assert'); + +// Connection URL +const url = 'mongodb://localhost:27017'; + +// Database Name +const dbName = 'myproject'; + +// Use connect method to connect to the server +MongoClient.connect(url, function(err, client) { + assert.equal(null, err); + console.log("Connected successfully to server"); + + const db = client.db(dbName); + + insertDocuments(db, function() { + updateDocument(db, function() { + removeDocument(db, function() { + client.close(); + }); + }); + }); +}); +``` + +### Index a Collection + +[Indexes](https://docs.mongodb.org/manual/indexes/) can improve your application's +performance. The following function creates an index on the **a** field in the +**documents** collection. + +```js +const indexCollection = function(db, callback) { + db.collection('documents').createIndex( + { "a": 1 }, + null, + function(err, results) { + console.log(results); + callback(); + } + ); +}; +``` + +Add the ``indexCollection`` method to your app: + +```js +const MongoClient = require('mongodb').MongoClient; +const assert = require('assert'); + +// Connection URL +const url = 'mongodb://localhost:27017'; + +const dbName = 'myproject'; + +// Use connect method to connect to the server +MongoClient.connect(url, function(err, client) { + assert.equal(null, err); + console.log("Connected successfully to server"); + + const db = client.db(dbName); + + insertDocuments(db, function() { + indexCollection(db, function() { + client.close(); + }); + }); +}); +``` + +For more detailed information, see the [tutorials](docs/reference/content/tutorials/main.md). + +## Next Steps + + * [MongoDB Documentation](http://mongodb.org) + * [Read about Schemas](http://learnmongodbthehardway.com) + * [Star us on GitHub](https://github.com/mongodb/node-mongodb-native) + +## License + +[Apache 2.0](LICENSE.md) + +© 2009-2012 Christian Amor Kvalheim +© 2012-present MongoDB [Contributors](CONTRIBUTORS.md) diff --git a/scripts/2.5/node_modules/mongodb/index.js b/scripts/2.5/node_modules/mongodb/index.js new file mode 100644 index 00000000..3ce36f59 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/index.js @@ -0,0 +1,68 @@ +'use strict'; + +// Core module +const core = require('./lib/core'); +const Instrumentation = require('./lib/apm'); + +// Set up the connect function +const connect = require('./lib/mongo_client').connect; + +// Expose error class +connect.MongoError = core.MongoError; +connect.MongoNetworkError = core.MongoNetworkError; +connect.MongoTimeoutError = core.MongoTimeoutError; + +// Actual driver classes exported +connect.Admin = require('./lib/admin'); +connect.MongoClient = require('./lib/mongo_client'); +connect.Db = require('./lib/db'); +connect.Collection = require('./lib/collection'); +connect.Server = require('./lib/topologies/server'); +connect.ReplSet = require('./lib/topologies/replset'); +connect.Mongos = require('./lib/topologies/mongos'); +connect.ReadPreference = core.ReadPreference; +connect.GridStore = require('./lib/gridfs/grid_store'); +connect.Chunk = require('./lib/gridfs/chunk'); +connect.Logger = core.Logger; +connect.AggregationCursor = require('./lib/aggregation_cursor'); +connect.CommandCursor = require('./lib/command_cursor'); +connect.Cursor = require('./lib/cursor'); +connect.GridFSBucket = require('./lib/gridfs-stream'); +// Exported to be used in tests not to be used anywhere else +connect.CoreServer = core.Server; +connect.CoreConnection = core.Connection; + +// BSON types exported +connect.Binary = core.BSON.Binary; +connect.Code = core.BSON.Code; +connect.Map = core.BSON.Map; +connect.DBRef = core.BSON.DBRef; +connect.Double = core.BSON.Double; +connect.Int32 = core.BSON.Int32; +connect.Long = core.BSON.Long; +connect.MinKey = core.BSON.MinKey; +connect.MaxKey = core.BSON.MaxKey; +connect.ObjectID = core.BSON.ObjectID; +connect.ObjectId = core.BSON.ObjectID; +connect.Symbol = core.BSON.Symbol; +connect.Timestamp = core.BSON.Timestamp; +connect.BSONRegExp = core.BSON.BSONRegExp; +connect.Decimal128 = core.BSON.Decimal128; + +// Add connect method +connect.connect = connect; + +// Set up the instrumentation method +connect.instrument = function(options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + + const instrumentation = new Instrumentation(); + instrumentation.instrument(connect.MongoClient, callback); + return instrumentation; +}; + +// Set our exports to be the connect function +module.exports = connect; diff --git a/scripts/2.5/node_modules/mongodb/lib/admin.js b/scripts/2.5/node_modules/mongodb/lib/admin.js new file mode 100644 index 00000000..716844bb --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/admin.js @@ -0,0 +1,293 @@ +'use strict'; + +const applyWriteConcern = require('./utils').applyWriteConcern; + +const AddUserOperation = require('./operations/add_user'); +const ExecuteDbAdminCommandOperation = require('./operations/execute_db_admin_command'); +const RemoveUserOperation = require('./operations/remove_user'); +const ValidateCollectionOperation = require('./operations/validate_collection'); +const ListDatabasesOperation = require('./operations/list_databases'); + +const executeOperation = require('./operations/execute_operation'); + +/** + * @fileOverview The **Admin** class is an internal class that allows convenient access to + * the admin functionality and commands for MongoDB. + * + * **ADMIN Cannot directly be instantiated** + * @example + * const MongoClient = require('mongodb').MongoClient; + * const test = require('assert'); + * // Connection url + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * + * // Connect using MongoClient + * MongoClient.connect(url, function(err, client) { + * // Use the admin database for the operation + * const adminDb = client.db(dbName).admin(); + * + * // List all the available databases + * adminDb.listDatabases(function(err, dbs) { + * test.equal(null, err); + * test.ok(dbs.databases.length > 0); + * client.close(); + * }); + * }); + */ + +/** + * Create a new Admin instance (INTERNAL TYPE, do not instantiate directly) + * @class + * @return {Admin} a collection instance. + */ +function Admin(db, topology, promiseLibrary) { + if (!(this instanceof Admin)) return new Admin(db, topology); + + // Internal state + this.s = { + db: db, + topology: topology, + promiseLibrary: promiseLibrary + }; +} + +/** + * The callback format for results + * @callback Admin~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {object} result The result object if the command was executed successfully. + */ + +/** + * Execute a command + * @method + * @param {object} command The command hash + * @param {object} [options] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query. + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.command = function(command, options, callback) { + const args = Array.prototype.slice.call(arguments, 1); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + options = args.length ? args.shift() : {}; + + const commandOperation = new ExecuteDbAdminCommandOperation(this.s.db, command, options); + + return executeOperation(this.s.db.s.topology, commandOperation, callback); +}; + +/** + * Retrieve the server information for the current + * instance of the db client + * + * @param {Object} [options] optional parameters for this operation + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.buildInfo = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const cmd = { buildinfo: 1 }; + + const buildInfoOperation = new ExecuteDbAdminCommandOperation(this.s.db, cmd, options); + + return executeOperation(this.s.db.s.topology, buildInfoOperation, callback); +}; + +/** + * Retrieve the server information for the current + * instance of the db client + * + * @param {Object} [options] optional parameters for this operation + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.serverInfo = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const cmd = { buildinfo: 1 }; + + const serverInfoOperation = new ExecuteDbAdminCommandOperation(this.s.db, cmd, options); + + return executeOperation(this.s.db.s.topology, serverInfoOperation, callback); +}; + +/** + * Retrieve this db's server status. + * + * @param {Object} [options] optional parameters for this operation + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.serverStatus = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const serverStatusOperation = new ExecuteDbAdminCommandOperation( + this.s.db, + { serverStatus: 1 }, + options + ); + + return executeOperation(this.s.db.s.topology, serverStatusOperation, callback); +}; + +/** + * Ping the MongoDB server and retrieve results + * + * @param {Object} [options] optional parameters for this operation + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.ping = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const cmd = { ping: 1 }; + + const pingOperation = new ExecuteDbAdminCommandOperation(this.s.db, cmd, options); + + return executeOperation(this.s.db.s.topology, pingOperation, callback); +}; + +/** + * Add a user to the database. + * @method + * @param {string} username The username. + * @param {string} password The password. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.fsync=false] Specify a file sync write concern. + * @param {object} [options.customData] Custom data associated with the user (only Mongodb 2.6 or higher) + * @param {object[]} [options.roles] Roles associated with the created user (only Mongodb 2.6 or higher) + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.addUser = function(username, password, options, callback) { + const args = Array.prototype.slice.call(arguments, 2); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + + // Special case where there is no password ($external users) + if (typeof username === 'string' && password != null && typeof password === 'object') { + options = password; + password = null; + } + + options = args.length ? args.shift() : {}; + options = Object.assign({}, options); + // Get the options + options = applyWriteConcern(options, { db: this.s.db }); + // Set the db name to admin + options.dbName = 'admin'; + + const addUserOperation = new AddUserOperation(this.s.db, username, password, options); + + return executeOperation(this.s.db.s.topology, addUserOperation, callback); +}; + +/** + * Remove a user from a database + * @method + * @param {string} username The username. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.fsync=false] Specify a file sync write concern. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.removeUser = function(username, options, callback) { + const args = Array.prototype.slice.call(arguments, 1); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + + options = args.length ? args.shift() : {}; + options = Object.assign({}, options); + // Get the options + options = applyWriteConcern(options, { db: this.s.db }); + // Set the db name + options.dbName = 'admin'; + + const removeUserOperation = new RemoveUserOperation(this.s.db, username, options); + + return executeOperation(this.s.db.s.topology, removeUserOperation, callback); +}; + +/** + * Validate an existing collection + * + * @param {string} collectionName The name of the collection to validate. + * @param {object} [options] Optional settings. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Admin~resultCallback} [callback] The command result callback. + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.validateCollection = function(collectionName, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const validateCollectionOperation = new ValidateCollectionOperation( + this, + collectionName, + options + ); + + return executeOperation(this.s.db.s.topology, validateCollectionOperation, callback); +}; + +/** + * List the available databases + * + * @param {object} [options] Optional settings. + * @param {boolean} [options.nameOnly=false] Whether the command should return only db names, or names and size info. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Admin~resultCallback} [callback] The command result callback. + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.listDatabases = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeOperation( + this.s.db.s.topology, + new ListDatabasesOperation(this.s.db, options), + callback + ); +}; + +/** + * Get ReplicaSet status + * + * @param {Object} [options] optional parameters for this operation + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Admin~resultCallback} [callback] The command result callback. + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.replSetGetStatus = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const replSetGetStatusOperation = new ExecuteDbAdminCommandOperation( + this.s.db, + { replSetGetStatus: 1 }, + options + ); + + return executeOperation(this.s.db.s.topology, replSetGetStatusOperation, callback); +}; + +module.exports = Admin; diff --git a/scripts/2.5/node_modules/mongodb/lib/aggregation_cursor.js b/scripts/2.5/node_modules/mongodb/lib/aggregation_cursor.js new file mode 100644 index 00000000..b0977c69 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/aggregation_cursor.js @@ -0,0 +1,370 @@ +'use strict'; + +const MongoError = require('./core').MongoError; +const Cursor = require('./cursor'); +const CursorState = require('./core/cursor').CursorState; +const deprecate = require('util').deprecate; + +/** + * @fileOverview The **AggregationCursor** class is an internal class that embodies an aggregation cursor on MongoDB + * allowing for iteration over the results returned from the underlying query. It supports + * one by one document iteration, conversion to an array or can be iterated as a Node 4.X + * or higher stream + * + * **AGGREGATIONCURSOR Cannot directly be instantiated** + * @example + * const MongoClient = require('mongodb').MongoClient; + * const test = require('assert'); + * // Connection url + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, client) { + * // Create a collection we want to drop later + * const col = client.db(dbName).collection('createIndexExample1'); + * // Insert a bunch of documents + * col.insert([{a:1, b:1} + * , {a:2, b:2}, {a:3, b:3} + * , {a:4, b:4}], {w:1}, function(err, result) { + * test.equal(null, err); + * // Show that duplicate records got dropped + * col.aggregation({}, {cursor: {}}).toArray(function(err, items) { + * test.equal(null, err); + * test.equal(4, items.length); + * client.close(); + * }); + * }); + * }); + */ + +/** + * Namespace provided by the browser. + * @external Readable + */ + +/** + * Creates a new Aggregation Cursor instance (INTERNAL TYPE, do not instantiate directly) + * @class AggregationCursor + * @extends external:Readable + * @fires AggregationCursor#data + * @fires AggregationCursor#end + * @fires AggregationCursor#close + * @fires AggregationCursor#readable + * @return {AggregationCursor} an AggregationCursor instance. + */ +class AggregationCursor extends Cursor { + constructor(topology, operation, options) { + super(topology, operation, options); + } + + /** + * Set the batch size for the cursor. + * @method + * @param {number} value The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. + * @throws {MongoError} + * @return {AggregationCursor} + */ + batchSize(value) { + if (this.s.state === CursorState.CLOSED || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + if (typeof value !== 'number') { + throw MongoError.create({ message: 'batchSize requires an integer', driver: true }); + } + + this.operation.options.batchSize = value; + this.setCursorBatchSize(value); + return this; + } + + /** + * Add a geoNear stage to the aggregation pipeline + * @method + * @param {object} document The geoNear stage document. + * @return {AggregationCursor} + */ + geoNear(document) { + this.operation.addToPipeline({ $geoNear: document }); + return this; + } + + /** + * Add a group stage to the aggregation pipeline + * @method + * @param {object} document The group stage document. + * @return {AggregationCursor} + */ + group(document) { + this.operation.addToPipeline({ $group: document }); + return this; + } + + /** + * Add a limit stage to the aggregation pipeline + * @method + * @param {number} value The state limit value. + * @return {AggregationCursor} + */ + limit(value) { + this.operation.addToPipeline({ $limit: value }); + return this; + } + + /** + * Add a match stage to the aggregation pipeline + * @method + * @param {object} document The match stage document. + * @return {AggregationCursor} + */ + match(document) { + this.operation.addToPipeline({ $match: document }); + return this; + } + + /** + * Add a maxTimeMS stage to the aggregation pipeline + * @method + * @param {number} value The state maxTimeMS value. + * @return {AggregationCursor} + */ + maxTimeMS(value) { + this.operation.options.maxTimeMS = value; + return this; + } + + /** + * Add a out stage to the aggregation pipeline + * @method + * @param {number} destination The destination name. + * @return {AggregationCursor} + */ + out(destination) { + this.operation.addToPipeline({ $out: destination }); + return this; + } + + /** + * Add a project stage to the aggregation pipeline + * @method + * @param {object} document The project stage document. + * @return {AggregationCursor} + */ + project(document) { + this.operation.addToPipeline({ $project: document }); + return this; + } + + /** + * Add a lookup stage to the aggregation pipeline + * @method + * @param {object} document The lookup stage document. + * @return {AggregationCursor} + */ + lookup(document) { + this.operation.addToPipeline({ $lookup: document }); + return this; + } + + /** + * Add a redact stage to the aggregation pipeline + * @method + * @param {object} document The redact stage document. + * @return {AggregationCursor} + */ + redact(document) { + this.operation.addToPipeline({ $redact: document }); + return this; + } + + /** + * Add a skip stage to the aggregation pipeline + * @method + * @param {number} value The state skip value. + * @return {AggregationCursor} + */ + skip(value) { + this.operation.addToPipeline({ $skip: value }); + return this; + } + + /** + * Add a sort stage to the aggregation pipeline + * @method + * @param {object} document The sort stage document. + * @return {AggregationCursor} + */ + sort(document) { + this.operation.addToPipeline({ $sort: document }); + return this; + } + + /** + * Add a unwind stage to the aggregation pipeline + * @method + * @param {number} field The unwind field name. + * @return {AggregationCursor} + */ + unwind(field) { + this.operation.addToPipeline({ $unwind: field }); + return this; + } + + /** + * Return the cursor logger + * @method + * @return {Logger} return the cursor logger + * @ignore + */ + getLogger() { + return this.logger; + } +} + +// aliases +AggregationCursor.prototype.get = AggregationCursor.prototype.toArray; + +// deprecated methods +deprecate( + AggregationCursor.prototype.geoNear, + 'The `$geoNear` stage is deprecated in MongoDB 4.0, and removed in version 4.2.' +); + +/** + * AggregationCursor stream data event, fired for each document in the cursor. + * + * @event AggregationCursor#data + * @type {object} + */ + +/** + * AggregationCursor stream end event + * + * @event AggregationCursor#end + * @type {null} + */ + +/** + * AggregationCursor stream close event + * + * @event AggregationCursor#close + * @type {null} + */ + +/** + * AggregationCursor stream readable event + * + * @event AggregationCursor#readable + * @type {null} + */ + +/** + * Get the next available document from the cursor, returns null if no more documents are available. + * @function AggregationCursor.prototype.next + * @param {AggregationCursor~resultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ + +/** + * Check if there is any document still available in the cursor + * @function AggregationCursor.prototype.hasNext + * @param {AggregationCursor~resultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ + +/** + * The callback format for results + * @callback AggregationCursor~toArrayResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {object[]} documents All the documents the satisfy the cursor. + */ + +/** + * Returns an array of documents. The caller is responsible for making sure that there + * is enough memory to store the results. Note that the array only contain partial + * results when this cursor had been previously accessed. In that case, + * cursor.rewind() can be used to reset the cursor. + * @method AggregationCursor.prototype.toArray + * @param {AggregationCursor~toArrayResultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ + +/** + * The callback format for results + * @callback AggregationCursor~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {(object|null)} result The result object if the command was executed successfully. + */ + +/** + * Iterates over all the documents for this cursor. As with **{cursor.toArray}**, + * not all of the elements will be iterated if this cursor had been previously accessed. + * In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike + * **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements + * at any given time if batch size is specified. Otherwise, the caller is responsible + * for making sure that the entire result can fit the memory. + * @method AggregationCursor.prototype.each + * @deprecated + * @param {AggregationCursor~resultCallback} callback The result callback. + * @throws {MongoError} + * @return {null} + */ + +/** + * Close the cursor, sending a AggregationCursor command and emitting close. + * @method AggregationCursor.prototype.close + * @param {AggregationCursor~resultCallback} [callback] The result callback. + * @return {Promise} returns Promise if no callback passed + */ + +/** + * Is the cursor closed + * @method AggregationCursor.prototype.isClosed + * @return {boolean} + */ + +/** + * Execute the explain for the cursor + * @method AggregationCursor.prototype.explain + * @param {AggregationCursor~resultCallback} [callback] The result callback. + * @return {Promise} returns Promise if no callback passed + */ + +/** + * Clone the cursor + * @function AggregationCursor.prototype.clone + * @return {AggregationCursor} + */ + +/** + * Resets the cursor + * @function AggregationCursor.prototype.rewind + * @return {AggregationCursor} + */ + +/** + * The callback format for the forEach iterator method + * @callback AggregationCursor~iteratorCallback + * @param {Object} doc An emitted document for the iterator + */ + +/** + * The callback error format for the forEach iterator method + * @callback AggregationCursor~endCallback + * @param {MongoError} error An error instance representing the error during the execution. + */ + +/** + * Iterates over all the documents for this cursor using the iterator, callback pattern. + * @method AggregationCursor.prototype.forEach + * @param {AggregationCursor~iteratorCallback} iterator The iteration callback. + * @param {AggregationCursor~endCallback} callback The end callback. + * @throws {MongoError} + * @return {null} + */ + +module.exports = AggregationCursor; diff --git a/scripts/2.5/node_modules/mongodb/lib/apm.js b/scripts/2.5/node_modules/mongodb/lib/apm.js new file mode 100644 index 00000000..f78e4aaf --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/apm.js @@ -0,0 +1,31 @@ +'use strict'; +const EventEmitter = require('events').EventEmitter; + +class Instrumentation extends EventEmitter { + constructor() { + super(); + } + + instrument(MongoClient, callback) { + // store a reference to the original functions + this.$MongoClient = MongoClient; + const $prototypeConnect = (this.$prototypeConnect = MongoClient.prototype.connect); + + const instrumentation = this; + MongoClient.prototype.connect = function(callback) { + this.s.options.monitorCommands = true; + this.on('commandStarted', event => instrumentation.emit('started', event)); + this.on('commandSucceeded', event => instrumentation.emit('succeeded', event)); + this.on('commandFailed', event => instrumentation.emit('failed', event)); + return $prototypeConnect.call(this, callback); + }; + + if (typeof callback === 'function') callback(null, this); + } + + uninstrument() { + this.$MongoClient.prototype.connect = this.$prototypeConnect; + } +} + +module.exports = Instrumentation; diff --git a/scripts/2.5/node_modules/mongodb/lib/async/.eslintrc b/scripts/2.5/node_modules/mongodb/lib/async/.eslintrc new file mode 100644 index 00000000..93b2f643 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/async/.eslintrc @@ -0,0 +1,5 @@ +{ + "parserOptions": { + "ecmaVersion": 2018 + } +} diff --git a/scripts/2.5/node_modules/mongodb/lib/async/async_iterator.js b/scripts/2.5/node_modules/mongodb/lib/async/async_iterator.js new file mode 100644 index 00000000..6021aadf --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/async/async_iterator.js @@ -0,0 +1,33 @@ +'use strict'; + +// async function* asyncIterator() { +// while (true) { +// const value = await this.next(); +// if (!value) { +// await this.close(); +// return; +// } + +// yield value; +// } +// } + +// TODO: change this to the async generator function above +function asyncIterator() { + const cursor = this; + + return { + next: function() { + return Promise.resolve() + .then(() => cursor.next()) + .then(value => { + if (!value) { + return cursor.close().then(() => ({ value, done: true })); + } + return { value, done: false }; + }); + } + }; +} + +exports.asyncIterator = asyncIterator; diff --git a/scripts/2.5/node_modules/mongodb/lib/bulk/common.js b/scripts/2.5/node_modules/mongodb/lib/bulk/common.js new file mode 100644 index 00000000..8f99c252 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/bulk/common.js @@ -0,0 +1,1239 @@ +'use strict'; + +const Long = require('../core').BSON.Long; +const MongoError = require('../core').MongoError; +const ObjectID = require('../core').BSON.ObjectID; +const BSON = require('../core').BSON; +const MongoWriteConcernError = require('../core').MongoWriteConcernError; +const toError = require('../utils').toError; +const handleCallback = require('../utils').handleCallback; +const applyRetryableWrites = require('../utils').applyRetryableWrites; +const applyWriteConcern = require('../utils').applyWriteConcern; +const executeLegacyOperation = require('../utils').executeLegacyOperation; +const isPromiseLike = require('../utils').isPromiseLike; + +// Error codes +const WRITE_CONCERN_ERROR = 64; + +// Insert types +const INSERT = 1; +const UPDATE = 2; +const REMOVE = 3; + +const bson = new BSON([ + BSON.Binary, + BSON.Code, + BSON.DBRef, + BSON.Decimal128, + BSON.Double, + BSON.Int32, + BSON.Long, + BSON.Map, + BSON.MaxKey, + BSON.MinKey, + BSON.ObjectId, + BSON.BSONRegExp, + BSON.Symbol, + BSON.Timestamp +]); + +/** + * Keeps the state of a unordered batch so we can rewrite the results + * correctly after command execution + * @ignore + */ +class Batch { + constructor(batchType, originalZeroIndex) { + this.originalZeroIndex = originalZeroIndex; + this.currentIndex = 0; + this.originalIndexes = []; + this.batchType = batchType; + this.operations = []; + this.size = 0; + this.sizeBytes = 0; + } +} + +/** + * @classdesc + * The result of a bulk write. + */ +class BulkWriteResult { + /** + * Create a new BulkWriteResult instance + * + * **NOTE:** Internal Type, do not instantiate directly + */ + constructor(bulkResult) { + this.result = bulkResult; + } + + /** + * Evaluates to true if the bulk operation correctly executes + * @type {boolean} + */ + get ok() { + return this.result.ok; + } + + /** + * The number of inserted documents + * @type {number} + */ + get nInserted() { + return this.result.nInserted; + } + + /** + * Number of upserted documents + * @type {number} + */ + get nUpserted() { + return this.result.nUpserted; + } + + /** + * Number of matched documents + * @type {number} + */ + get nMatched() { + return this.result.nMatched; + } + + /** + * Number of documents updated physically on disk + * @type {number} + */ + get nModified() { + return this.result.nModified; + } + + /** + * Number of removed documents + * @type {number} + */ + get nRemoved() { + return this.result.nRemoved; + } + + /** + * Returns an array of all inserted ids + * + * @return {object[]} + */ + getInsertedIds() { + return this.result.insertedIds; + } + + /** + * Returns an array of all upserted ids + * + * @return {object[]} + */ + getUpsertedIds() { + return this.result.upserted; + } + + /** + * Returns the upserted id at the given index + * + * @param {number} index the number of the upserted id to return, returns undefined if no result for passed in index + * @return {object} + */ + getUpsertedIdAt(index) { + return this.result.upserted[index]; + } + + /** + * Returns raw internal result + * + * @return {object} + */ + getRawResponse() { + return this.result; + } + + /** + * Returns true if the bulk operation contains a write error + * + * @return {boolean} + */ + hasWriteErrors() { + return this.result.writeErrors.length > 0; + } + + /** + * Returns the number of write errors off the bulk operation + * + * @return {number} + */ + getWriteErrorCount() { + return this.result.writeErrors.length; + } + + /** + * Returns a specific write error object + * + * @param {number} index of the write error to return, returns null if there is no result for passed in index + * @return {WriteError} + */ + getWriteErrorAt(index) { + if (index < this.result.writeErrors.length) { + return this.result.writeErrors[index]; + } + return null; + } + + /** + * Retrieve all write errors + * + * @return {WriteError[]} + */ + getWriteErrors() { + return this.result.writeErrors; + } + + /** + * Retrieve lastOp if available + * + * @return {object} + */ + getLastOp() { + return this.result.lastOp; + } + + /** + * Retrieve the write concern error if any + * + * @return {WriteConcernError} + */ + getWriteConcernError() { + if (this.result.writeConcernErrors.length === 0) { + return null; + } else if (this.result.writeConcernErrors.length === 1) { + // Return the error + return this.result.writeConcernErrors[0]; + } else { + // Combine the errors + let errmsg = ''; + for (let i = 0; i < this.result.writeConcernErrors.length; i++) { + const err = this.result.writeConcernErrors[i]; + errmsg = errmsg + err.errmsg; + + // TODO: Something better + if (i === 0) errmsg = errmsg + ' and '; + } + + return new WriteConcernError({ errmsg: errmsg, code: WRITE_CONCERN_ERROR }); + } + } + + /** + * @return {object} + */ + toJSON() { + return this.result; + } + + /** + * @return {string} + */ + toString() { + return `BulkWriteResult(${this.toJSON(this.result)})`; + } + + /** + * @return {boolean} + */ + isOk() { + return this.result.ok === 1; + } +} + +/** + * @classdesc An error representing a failure by the server to apply the requested write concern to the bulk operation. + */ +class WriteConcernError { + /** + * Create a new WriteConcernError instance + * + * **NOTE:** Internal Type, do not instantiate directly + */ + constructor(err) { + this.err = err; + } + + /** + * Write concern error code. + * @type {number} + */ + get code() { + return this.err.code; + } + + /** + * Write concern error message. + * @type {string} + */ + get errmsg() { + return this.err.errmsg; + } + + /** + * @return {object} + */ + toJSON() { + return { code: this.err.code, errmsg: this.err.errmsg }; + } + + /** + * @return {string} + */ + toString() { + return `WriteConcernError(${this.err.errmsg})`; + } +} + +/** + * @classdesc An error that occurred during a BulkWrite on the server. + */ +class WriteError { + /** + * Create a new WriteError instance + * + * **NOTE:** Internal Type, do not instantiate directly + */ + constructor(err) { + this.err = err; + } + + /** + * WriteError code. + * @type {number} + */ + get code() { + return this.err.code; + } + + /** + * WriteError original bulk operation index. + * @type {number} + */ + get index() { + return this.err.index; + } + + /** + * WriteError message. + * @type {string} + */ + get errmsg() { + return this.err.errmsg; + } + + /** + * Returns the underlying operation that caused the error + * @return {object} + */ + getOperation() { + return this.err.op; + } + + /** + * @return {object} + */ + toJSON() { + return { code: this.err.code, index: this.err.index, errmsg: this.err.errmsg, op: this.err.op }; + } + + /** + * @return {string} + */ + toString() { + return `WriteError(${JSON.stringify(this.toJSON())})`; + } +} + +/** + * Merges results into shared data structure + * @ignore + */ +function mergeBatchResults(batch, bulkResult, err, result) { + // If we have an error set the result to be the err object + if (err) { + result = err; + } else if (result && result.result) { + result = result.result; + } else if (result == null) { + return; + } + + // Do we have a top level error stop processing and return + if (result.ok === 0 && bulkResult.ok === 1) { + bulkResult.ok = 0; + + const writeError = { + index: 0, + code: result.code || 0, + errmsg: result.message, + op: batch.operations[0] + }; + + bulkResult.writeErrors.push(new WriteError(writeError)); + return; + } else if (result.ok === 0 && bulkResult.ok === 0) { + return; + } + + // Deal with opTime if available + if (result.opTime || result.lastOp) { + const opTime = result.lastOp || result.opTime; + let lastOpTS = null; + let lastOpT = null; + + // We have a time stamp + if (opTime && opTime._bsontype === 'Timestamp') { + if (bulkResult.lastOp == null) { + bulkResult.lastOp = opTime; + } else if (opTime.greaterThan(bulkResult.lastOp)) { + bulkResult.lastOp = opTime; + } + } else { + // Existing TS + if (bulkResult.lastOp) { + lastOpTS = + typeof bulkResult.lastOp.ts === 'number' + ? Long.fromNumber(bulkResult.lastOp.ts) + : bulkResult.lastOp.ts; + lastOpT = + typeof bulkResult.lastOp.t === 'number' + ? Long.fromNumber(bulkResult.lastOp.t) + : bulkResult.lastOp.t; + } + + // Current OpTime TS + const opTimeTS = typeof opTime.ts === 'number' ? Long.fromNumber(opTime.ts) : opTime.ts; + const opTimeT = typeof opTime.t === 'number' ? Long.fromNumber(opTime.t) : opTime.t; + + // Compare the opTime's + if (bulkResult.lastOp == null) { + bulkResult.lastOp = opTime; + } else if (opTimeTS.greaterThan(lastOpTS)) { + bulkResult.lastOp = opTime; + } else if (opTimeTS.equals(lastOpTS)) { + if (opTimeT.greaterThan(lastOpT)) { + bulkResult.lastOp = opTime; + } + } + } + } + + // If we have an insert Batch type + if (batch.batchType === INSERT && result.n) { + bulkResult.nInserted = bulkResult.nInserted + result.n; + } + + // If we have an insert Batch type + if (batch.batchType === REMOVE && result.n) { + bulkResult.nRemoved = bulkResult.nRemoved + result.n; + } + + let nUpserted = 0; + + // We have an array of upserted values, we need to rewrite the indexes + if (Array.isArray(result.upserted)) { + nUpserted = result.upserted.length; + + for (let i = 0; i < result.upserted.length; i++) { + bulkResult.upserted.push({ + index: result.upserted[i].index + batch.originalZeroIndex, + _id: result.upserted[i]._id + }); + } + } else if (result.upserted) { + nUpserted = 1; + + bulkResult.upserted.push({ + index: batch.originalZeroIndex, + _id: result.upserted + }); + } + + // If we have an update Batch type + if (batch.batchType === UPDATE && result.n) { + const nModified = result.nModified; + bulkResult.nUpserted = bulkResult.nUpserted + nUpserted; + bulkResult.nMatched = bulkResult.nMatched + (result.n - nUpserted); + + if (typeof nModified === 'number') { + bulkResult.nModified = bulkResult.nModified + nModified; + } else { + bulkResult.nModified = null; + } + } + + if (Array.isArray(result.writeErrors)) { + for (let i = 0; i < result.writeErrors.length; i++) { + const writeError = { + index: batch.originalZeroIndex + result.writeErrors[i].index, + code: result.writeErrors[i].code, + errmsg: result.writeErrors[i].errmsg, + op: batch.operations[result.writeErrors[i].index] + }; + + bulkResult.writeErrors.push(new WriteError(writeError)); + } + } + + if (result.writeConcernError) { + bulkResult.writeConcernErrors.push(new WriteConcernError(result.writeConcernError)); + } +} + +function executeCommands(bulkOperation, options, callback) { + if (bulkOperation.s.batches.length === 0) { + return handleCallback(callback, null, new BulkWriteResult(bulkOperation.s.bulkResult)); + } + + const batch = bulkOperation.s.batches.shift(); + + function resultHandler(err, result) { + // Error is a driver related error not a bulk op error, terminate + if (((err && err.driver) || (err && err.message)) && !(err instanceof MongoWriteConcernError)) { + return handleCallback(callback, err); + } + + // If we have and error + if (err) err.ok = 0; + if (err instanceof MongoWriteConcernError) { + return handleMongoWriteConcernError(batch, bulkOperation.s.bulkResult, err, callback); + } + + // Merge the results together + const writeResult = new BulkWriteResult(bulkOperation.s.bulkResult); + const mergeResult = mergeBatchResults(batch, bulkOperation.s.bulkResult, err, result); + if (mergeResult != null) { + return handleCallback(callback, null, writeResult); + } + + if (bulkOperation.handleWriteError(callback, writeResult)) return; + + // Execute the next command in line + executeCommands(bulkOperation, options, callback); + } + + bulkOperation.finalOptionsHandler({ options, batch, resultHandler }, callback); +} + +/** + * handles write concern error + * + * @ignore + * @param {object} batch + * @param {object} bulkResult + * @param {boolean} ordered + * @param {WriteConcernError} err + * @param {function} callback + */ +function handleMongoWriteConcernError(batch, bulkResult, err, callback) { + mergeBatchResults(batch, bulkResult, null, err.result); + + const wrappedWriteConcernError = new WriteConcernError({ + errmsg: err.result.writeConcernError.errmsg, + code: err.result.writeConcernError.result + }); + return handleCallback( + callback, + new BulkWriteError(toError(wrappedWriteConcernError), new BulkWriteResult(bulkResult)), + null + ); +} + +/** + * @classdesc An error indicating an unsuccessful Bulk Write + */ +class BulkWriteError extends MongoError { + /** + * Creates a new BulkWriteError + * + * @param {Error|string|object} message The error message + * @param {BulkWriteResult} result The result of the bulk write operation + * @extends {MongoError} + */ + constructor(error, result) { + const message = error.err || error.errmsg || error.errMessage || error; + super(message); + + Object.assign(this, error); + + this.name = 'BulkWriteError'; + this.result = result; + } +} + +/** + * @classdesc A builder object that is returned from {@link BulkOperationBase#find}. + * Is used to build a write operation that involves a query filter. + */ +class FindOperators { + /** + * Creates a new FindOperators object. + * + * **NOTE:** Internal Type, do not instantiate directly + * @param {OrderedBulkOperation|UnorderedBulkOperation} bulkOperation + */ + constructor(bulkOperation) { + this.s = bulkOperation.s; + } + + /** + * Add a multiple update operation to the bulk operation + * + * @method + * @param {object} updateDocument An update field for an update operation. See {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-u u documentation} + * @throws {MongoError} If operation cannot be added to bulk write + * @return {OrderedBulkOperation|UnorderedBulkOperation} A reference to the parent BulkOperation + */ + update(updateDocument) { + // Perform upsert + const upsert = typeof this.s.currentOp.upsert === 'boolean' ? this.s.currentOp.upsert : false; + + // Establish the update command + const document = { + q: this.s.currentOp.selector, + u: updateDocument, + multi: true, + upsert: upsert + }; + + // Clear out current Op + this.s.currentOp = null; + return this.s.options.addToOperationsList(this, UPDATE, document); + } + + /** + * Add a single update operation to the bulk operation + * + * @method + * @param {object} updateDocument An update field for an update operation. See {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-u u documentation} + * @throws {MongoError} If operation cannot be added to bulk write + * @return {OrderedBulkOperation|UnorderedBulkOperation} A reference to the parent BulkOperation + */ + updateOne(updateDocument) { + // Perform upsert + const upsert = typeof this.s.currentOp.upsert === 'boolean' ? this.s.currentOp.upsert : false; + + // Establish the update command + const document = { + q: this.s.currentOp.selector, + u: updateDocument, + multi: false, + upsert: upsert + }; + + // Clear out current Op + this.s.currentOp = null; + return this.s.options.addToOperationsList(this, UPDATE, document); + } + + /** + * Add a replace one operation to the bulk operation + * + * @method + * @param {object} updateDocument the new document to replace the existing one with + * @throws {MongoError} If operation cannot be added to bulk write + * @return {OrderedBulkOperation|UnorderedBulkOperation} A reference to the parent BulkOperation + */ + replaceOne(updateDocument) { + this.updateOne(updateDocument); + } + + /** + * Upsert modifier for update bulk operation, noting that this operation is an upsert. + * + * @method + * @throws {MongoError} If operation cannot be added to bulk write + * @return {FindOperators} reference to self + */ + upsert() { + this.s.currentOp.upsert = true; + return this; + } + + /** + * Add a delete one operation to the bulk operation + * + * @method + * @throws {MongoError} If operation cannot be added to bulk write + * @return {OrderedBulkOperation|UnorderedBulkOperation} A reference to the parent BulkOperation + */ + deleteOne() { + // Establish the update command + const document = { + q: this.s.currentOp.selector, + limit: 1 + }; + + // Clear out current Op + this.s.currentOp = null; + return this.s.options.addToOperationsList(this, REMOVE, document); + } + + /** + * Add a delete many operation to the bulk operation + * + * @method + * @throws {MongoError} If operation cannot be added to bulk write + * @return {OrderedBulkOperation|UnorderedBulkOperation} A reference to the parent BulkOperation + */ + delete() { + // Establish the update command + const document = { + q: this.s.currentOp.selector, + limit: 0 + }; + + // Clear out current Op + this.s.currentOp = null; + return this.s.options.addToOperationsList(this, REMOVE, document); + } + + /** + * backwards compatability for deleteOne + */ + removeOne() { + return this.deleteOne(); + } + + /** + * backwards compatability for delete + */ + remove() { + return this.delete(); + } +} + +/** + * @classdesc Parent class to OrderedBulkOperation and UnorderedBulkOperation + * + * **NOTE:** Internal Type, do not instantiate directly + */ +class BulkOperationBase { + /** + * Create a new OrderedBulkOperation or UnorderedBulkOperation instance + * @property {number} length Get the number of operations in the bulk. + */ + constructor(topology, collection, options, isOrdered) { + // determine whether bulkOperation is ordered or unordered + this.isOrdered = isOrdered; + + options = options == null ? {} : options; + // TODO Bring from driver information in isMaster + // Get the namespace for the write operations + const namespace = collection.s.namespace; + // Used to mark operation as executed + const executed = false; + + // Current item + const currentOp = null; + + // Handle to the bson serializer, used to calculate running sizes + const bson = topology.bson; + + // Set max byte size + const isMaster = topology.lastIsMaster(); + const maxBatchSizeBytes = + isMaster && isMaster.maxBsonObjectSize ? isMaster.maxBsonObjectSize : 1024 * 1024 * 16; + const maxWriteBatchSize = + isMaster && isMaster.maxWriteBatchSize ? isMaster.maxWriteBatchSize : 1000; + + // Calculates the largest possible size of an Array key, represented as a BSON string + // element. This calculation: + // 1 byte for BSON type + // # of bytes = length of (string representation of (maxWriteBatchSize - 1)) + // + 1 bytes for null terminator + const maxKeySize = (maxWriteBatchSize - 1).toString(10).length + 2; + + // Final options for retryable writes and write concern + let finalOptions = Object.assign({}, options); + finalOptions = applyRetryableWrites(finalOptions, collection.s.db); + finalOptions = applyWriteConcern(finalOptions, { collection: collection }, options); + const writeConcern = finalOptions.writeConcern; + + // Get the promiseLibrary + const promiseLibrary = options.promiseLibrary || Promise; + + // Final results + const bulkResult = { + ok: 1, + writeErrors: [], + writeConcernErrors: [], + insertedIds: [], + nInserted: 0, + nUpserted: 0, + nMatched: 0, + nModified: 0, + nRemoved: 0, + upserted: [] + }; + + // Internal state + this.s = { + // Final result + bulkResult: bulkResult, + // Current batch state + currentBatch: null, + currentIndex: 0, + // ordered specific + currentBatchSize: 0, + currentBatchSizeBytes: 0, + // unordered specific + currentInsertBatch: null, + currentUpdateBatch: null, + currentRemoveBatch: null, + batches: [], + // Write concern + writeConcern: writeConcern, + // Max batch size options + maxBatchSizeBytes: maxBatchSizeBytes, + maxWriteBatchSize: maxWriteBatchSize, + maxKeySize, + // Namespace + namespace: namespace, + // BSON + bson: bson, + // Topology + topology: topology, + // Options + options: finalOptions, + // Current operation + currentOp: currentOp, + // Executed + executed: executed, + // Collection + collection: collection, + // Promise Library + promiseLibrary: promiseLibrary, + // Fundamental error + err: null, + // check keys + checkKeys: typeof options.checkKeys === 'boolean' ? options.checkKeys : true + }; + + // bypass Validation + if (options.bypassDocumentValidation === true) { + this.s.bypassDocumentValidation = true; + } + } + + /** + * Add a single insert document to the bulk operation + * + * @param {object} document the document to insert + * @throws {MongoError} + * @return {BulkOperationBase} A reference to self + * + * @example + * const bulkOp = collection.initializeOrderedBulkOp(); + * // Adds three inserts to the bulkOp. + * bulkOp + * .insert({ a: 1 }) + * .insert({ b: 2 }) + * .insert({ c: 3 }); + * await bulkOp.execute(); + */ + insert(document) { + if (this.s.collection.s.db.options.forceServerObjectId !== true && document._id == null) + document._id = new ObjectID(); + return this.s.options.addToOperationsList(this, INSERT, document); + } + + /** + * Builds a find operation for an update/updateOne/delete/deleteOne/replaceOne. + * Returns a builder object used to complete the definition of the operation. + * + * @method + * @param {object} selector The selector for the bulk operation. See {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-q q documentation} + * @throws {MongoError} if a selector is not specified + * @return {FindOperators} A helper object with which the write operation can be defined. + * + * @example + * const bulkOp = collection.initializeOrderedBulkOp(); + * + * // Add an updateOne to the bulkOp + * bulkOp.find({ a: 1 }).updateOne({ $set: { b: 2 } }); + * + * // Add an updateMany to the bulkOp + * bulkOp.find({ c: 3 }).update({ $set: { d: 4 } }); + * + * // Add an upsert + * bulkOp.find({ e: 5 }).upsert().updateOne({ $set: { f: 6 } }); + * + * // Add a deletion + * bulkOp.find({ g: 7 }).deleteOne(); + * + * // Add a multi deletion + * bulkOp.find({ h: 8 }).delete(); + * + * // Add a replaceOne + * bulkOp.find({ i: 9 }).replaceOne({ j: 10 }); + * + * // Update using a pipeline (requires Mongodb 4.2 or higher) + * bulk.find({ k: 11, y: { $exists: true }, z: { $exists: true } }).updateOne([ + * { $set: { total: { $sum: [ '$y', '$z' ] } } } + * ]); + * + * // All of the ops will now be executed + * await bulkOp.execute(); + */ + find(selector) { + if (!selector) { + throw toError('Bulk find operation must specify a selector'); + } + + // Save a current selector + this.s.currentOp = { + selector: selector + }; + + return new FindOperators(this); + } + + /** + * Specifies a raw operation to perform in the bulk write. + * + * @method + * @param {object} op The raw operation to perform. + * @return {BulkOperationBase} A reference to self + */ + raw(op) { + const key = Object.keys(op)[0]; + + // Set up the force server object id + const forceServerObjectId = + typeof this.s.options.forceServerObjectId === 'boolean' + ? this.s.options.forceServerObjectId + : this.s.collection.s.db.options.forceServerObjectId; + + // Update operations + if ( + (op.updateOne && op.updateOne.q) || + (op.updateMany && op.updateMany.q) || + (op.replaceOne && op.replaceOne.q) + ) { + op[key].multi = op.updateOne || op.replaceOne ? false : true; + return this.s.options.addToOperationsList(this, UPDATE, op[key]); + } + + // Crud spec update format + if (op.updateOne || op.updateMany || op.replaceOne) { + const multi = op.updateOne || op.replaceOne ? false : true; + const operation = { + q: op[key].filter, + u: op[key].update || op[key].replacement, + multi: multi + }; + if (this.isOrdered) { + operation.upsert = op[key].upsert ? true : false; + if (op.collation) operation.collation = op.collation; + } else { + if (op[key].upsert) operation.upsert = true; + } + if (op[key].arrayFilters) operation.arrayFilters = op[key].arrayFilters; + return this.s.options.addToOperationsList(this, UPDATE, operation); + } + + // Remove operations + if ( + op.removeOne || + op.removeMany || + (op.deleteOne && op.deleteOne.q) || + (op.deleteMany && op.deleteMany.q) + ) { + op[key].limit = op.removeOne ? 1 : 0; + return this.s.options.addToOperationsList(this, REMOVE, op[key]); + } + + // Crud spec delete operations, less efficient + if (op.deleteOne || op.deleteMany) { + const limit = op.deleteOne ? 1 : 0; + const operation = { q: op[key].filter, limit: limit }; + if (this.isOrdered) { + if (op.collation) operation.collation = op.collation; + } + return this.s.options.addToOperationsList(this, REMOVE, operation); + } + + // Insert operations + if (op.insertOne && op.insertOne.document == null) { + if (forceServerObjectId !== true && op.insertOne._id == null) + op.insertOne._id = new ObjectID(); + return this.s.options.addToOperationsList(this, INSERT, op.insertOne); + } else if (op.insertOne && op.insertOne.document) { + if (forceServerObjectId !== true && op.insertOne.document._id == null) + op.insertOne.document._id = new ObjectID(); + return this.s.options.addToOperationsList(this, INSERT, op.insertOne.document); + } + + if (op.insertMany) { + for (let i = 0; i < op.insertMany.length; i++) { + if (forceServerObjectId !== true && op.insertMany[i]._id == null) + op.insertMany[i]._id = new ObjectID(); + this.s.options.addToOperationsList(this, INSERT, op.insertMany[i]); + } + + return; + } + + // No valid type of operation + throw toError( + 'bulkWrite only supports insertOne, insertMany, updateOne, updateMany, removeOne, removeMany, deleteOne, deleteMany' + ); + } + + /** + * helper function to assist with promiseOrCallback behavior + * @ignore + * @param {*} err + * @param {*} callback + */ + _handleEarlyError(err, callback) { + if (typeof callback === 'function') { + callback(err, null); + return; + } + + return this.s.promiseLibrary.reject(err); + } + + /** + * An internal helper method. Do not invoke directly. Will be going away in the future + * + * @ignore + * @method + * @param {class} bulk either OrderedBulkOperation or UnorderdBulkOperation + * @param {object} writeConcern + * @param {object} options + * @param {function} callback + */ + bulkExecute(_writeConcern, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + if (typeof _writeConcern === 'function') { + callback = _writeConcern; + } else if (_writeConcern && typeof _writeConcern === 'object') { + this.s.writeConcern = _writeConcern; + } + + if (this.s.executed) { + const executedError = toError('batch cannot be re-executed'); + return this._handleEarlyError(executedError, callback); + } + + // If we have current batch + if (this.isOrdered) { + if (this.s.currentBatch) this.s.batches.push(this.s.currentBatch); + } else { + if (this.s.currentInsertBatch) this.s.batches.push(this.s.currentInsertBatch); + if (this.s.currentUpdateBatch) this.s.batches.push(this.s.currentUpdateBatch); + if (this.s.currentRemoveBatch) this.s.batches.push(this.s.currentRemoveBatch); + } + // If we have no operations in the bulk raise an error + if (this.s.batches.length === 0) { + const emptyBatchError = toError('Invalid Operation, no operations specified'); + return this._handleEarlyError(emptyBatchError, callback); + } + return { options, callback }; + } + + /** + * The callback format for results + * @callback BulkOperationBase~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {BulkWriteResult} result The bulk write result. + */ + + /** + * Execute the bulk operation + * + * @method + * @param {WriteConcern} [_writeConcern] Optional write concern. Can also be specified through options. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.fsync=false] Specify a file sync write concern. + * @param {BulkOperationBase~resultCallback} [callback] A callback that will be invoked when bulkWrite finishes/errors + * @throws {MongoError} Throws error if the bulk object has already been executed + * @throws {MongoError} Throws error if the bulk object does not have any operations + * @return {Promise|void} returns Promise if no callback passed + */ + execute(_writeConcern, options, callback) { + const ret = this.bulkExecute(_writeConcern, options, callback); + if (!ret || isPromiseLike(ret)) { + return ret; + } + + options = ret.options; + callback = ret.callback; + + return executeLegacyOperation(this.s.topology, executeCommands, [this, options, callback]); + } + + /** + * Handles final options before executing command + * + * An internal method. Do not invoke. Will not be accessible in the future + * + * @ignore + * @param {object} config + * @param {object} config.options + * @param {number} config.batch + * @param {function} config.resultHandler + * @param {function} callback + */ + finalOptionsHandler(config, callback) { + const finalOptions = Object.assign({ ordered: this.isOrdered }, config.options); + if (this.s.writeConcern != null) { + finalOptions.writeConcern = this.s.writeConcern; + } + + if (finalOptions.bypassDocumentValidation !== true) { + delete finalOptions.bypassDocumentValidation; + } + + // Set an operationIf if provided + if (this.operationId) { + config.resultHandler.operationId = this.operationId; + } + + // Serialize functions + if (this.s.options.serializeFunctions) { + finalOptions.serializeFunctions = true; + } + + // Ignore undefined + if (this.s.options.ignoreUndefined) { + finalOptions.ignoreUndefined = true; + } + + // Is the bypassDocumentValidation options specific + if (this.s.bypassDocumentValidation === true) { + finalOptions.bypassDocumentValidation = true; + } + + // Is the checkKeys option disabled + if (this.s.checkKeys === false) { + finalOptions.checkKeys = false; + } + + if (finalOptions.retryWrites) { + if (config.batch.batchType === UPDATE) { + finalOptions.retryWrites = + finalOptions.retryWrites && !config.batch.operations.some(op => op.multi); + } + + if (config.batch.batchType === REMOVE) { + finalOptions.retryWrites = + finalOptions.retryWrites && !config.batch.operations.some(op => op.limit === 0); + } + } + + try { + if (config.batch.batchType === INSERT) { + this.s.topology.insert( + this.s.namespace, + config.batch.operations, + finalOptions, + config.resultHandler + ); + } else if (config.batch.batchType === UPDATE) { + this.s.topology.update( + this.s.namespace, + config.batch.operations, + finalOptions, + config.resultHandler + ); + } else if (config.batch.batchType === REMOVE) { + this.s.topology.remove( + this.s.namespace, + config.batch.operations, + finalOptions, + config.resultHandler + ); + } + } catch (err) { + // Force top level error + err.ok = 0; + // Merge top level error and return + handleCallback(callback, null, mergeBatchResults(config.batch, this.s.bulkResult, err, null)); + } + } + + /** + * Handles the write error before executing commands + * + * An internal helper method. Do not invoke directly. Will be going away in the future + * + * @ignore + * @param {function} callback + * @param {BulkWriteResult} writeResult + * @param {class} self either OrderedBulkOperation or UnorderdBulkOperation + */ + handleWriteError(callback, writeResult) { + if (this.s.bulkResult.writeErrors.length > 0) { + if (this.s.bulkResult.writeErrors.length === 1) { + handleCallback( + callback, + new BulkWriteError(toError(this.s.bulkResult.writeErrors[0]), writeResult), + null + ); + return true; + } + + const msg = this.s.bulkResult.writeErrors[0].errmsg + ? this.s.bulkResult.writeErrors[0].errmsg + : 'write operation failed'; + + handleCallback( + callback, + new BulkWriteError( + toError({ + message: msg, + code: this.s.bulkResult.writeErrors[0].code, + writeErrors: this.s.bulkResult.writeErrors + }), + writeResult + ), + null + ); + return true; + } else if (writeResult.getWriteConcernError()) { + handleCallback( + callback, + new BulkWriteError(toError(writeResult.getWriteConcernError()), writeResult), + null + ); + return true; + } + } +} + +Object.defineProperty(BulkOperationBase.prototype, 'length', { + enumerable: true, + get: function() { + return this.s.currentIndex; + } +}); + +// Exports symbols +module.exports = { + Batch, + BulkOperationBase, + bson, + INSERT: INSERT, + UPDATE: UPDATE, + REMOVE: REMOVE, + BulkWriteError +}; diff --git a/scripts/2.5/node_modules/mongodb/lib/bulk/ordered.js b/scripts/2.5/node_modules/mongodb/lib/bulk/ordered.js new file mode 100644 index 00000000..e2507b86 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/bulk/ordered.js @@ -0,0 +1,105 @@ +'use strict'; + +const common = require('./common'); +const BulkOperationBase = common.BulkOperationBase; +const Batch = common.Batch; +const bson = common.bson; +const utils = require('../utils'); +const toError = utils.toError; + +/** + * Add to internal list of Operations + * + * @ignore + * @param {OrderedBulkOperation} bulkOperation + * @param {number} docType number indicating the document type + * @param {object} document + * @return {OrderedBulkOperation} + */ +function addToOperationsList(bulkOperation, docType, document) { + // Get the bsonSize + const bsonSize = bson.calculateObjectSize(document, { + checkKeys: false, + + // Since we don't know what the user selected for BSON options here, + // err on the safe side, and check the size with ignoreUndefined: false. + ignoreUndefined: false + }); + + // Throw error if the doc is bigger than the max BSON size + if (bsonSize >= bulkOperation.s.maxBatchSizeBytes) + throw toError('document is larger than the maximum size ' + bulkOperation.s.maxBatchSizeBytes); + + // Create a new batch object if we don't have a current one + if (bulkOperation.s.currentBatch == null) + bulkOperation.s.currentBatch = new Batch(docType, bulkOperation.s.currentIndex); + + const maxKeySize = bulkOperation.s.maxKeySize; + + // Check if we need to create a new batch + if ( + bulkOperation.s.currentBatchSize + 1 >= bulkOperation.s.maxWriteBatchSize || + bulkOperation.s.currentBatchSizeBytes + maxKeySize + bsonSize >= + bulkOperation.s.maxBatchSizeBytes || + bulkOperation.s.currentBatch.batchType !== docType + ) { + // Save the batch to the execution stack + bulkOperation.s.batches.push(bulkOperation.s.currentBatch); + + // Create a new batch + bulkOperation.s.currentBatch = new Batch(docType, bulkOperation.s.currentIndex); + + // Reset the current size trackers + bulkOperation.s.currentBatchSize = 0; + bulkOperation.s.currentBatchSizeBytes = 0; + } + + if (docType === common.INSERT) { + bulkOperation.s.bulkResult.insertedIds.push({ + index: bulkOperation.s.currentIndex, + _id: document._id + }); + } + + // We have an array of documents + if (Array.isArray(document)) { + throw toError('operation passed in cannot be an Array'); + } + + bulkOperation.s.currentBatch.originalIndexes.push(bulkOperation.s.currentIndex); + bulkOperation.s.currentBatch.operations.push(document); + bulkOperation.s.currentBatchSize += 1; + bulkOperation.s.currentBatchSizeBytes += maxKeySize + bsonSize; + bulkOperation.s.currentIndex += 1; + + // Return bulkOperation + return bulkOperation; +} + +/** + * Create a new OrderedBulkOperation instance (INTERNAL TYPE, do not instantiate directly) + * @class + * @extends BulkOperationBase + * @property {number} length Get the number of operations in the bulk. + * @return {OrderedBulkOperation} a OrderedBulkOperation instance. + */ +class OrderedBulkOperation extends BulkOperationBase { + constructor(topology, collection, options) { + options = options || {}; + options = Object.assign(options, { addToOperationsList }); + + super(topology, collection, options, true); + } +} + +/** + * Returns an unordered batch object + * @ignore + */ +function initializeOrderedBulkOp(topology, collection, options) { + return new OrderedBulkOperation(topology, collection, options); +} + +initializeOrderedBulkOp.OrderedBulkOperation = OrderedBulkOperation; +module.exports = initializeOrderedBulkOp; +module.exports.Bulk = OrderedBulkOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/bulk/unordered.js b/scripts/2.5/node_modules/mongodb/lib/bulk/unordered.js new file mode 100644 index 00000000..999de3c4 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/bulk/unordered.js @@ -0,0 +1,118 @@ +'use strict'; + +const common = require('./common'); +const BulkOperationBase = common.BulkOperationBase; +const Batch = common.Batch; +const bson = common.bson; +const utils = require('../utils'); +const toError = utils.toError; + +/** + * Add to internal list of Operations + * + * @ignore + * @param {UnorderedBulkOperation} bulkOperation + * @param {number} docType number indicating the document type + * @param {object} document + * @return {UnorderedBulkOperation} + */ +function addToOperationsList(bulkOperation, docType, document) { + // Get the bsonSize + const bsonSize = bson.calculateObjectSize(document, { + checkKeys: false, + + // Since we don't know what the user selected for BSON options here, + // err on the safe side, and check the size with ignoreUndefined: false. + ignoreUndefined: false + }); + // Throw error if the doc is bigger than the max BSON size + if (bsonSize >= bulkOperation.s.maxBatchSizeBytes) + throw toError('document is larger than the maximum size ' + bulkOperation.s.maxBatchSizeBytes); + // Holds the current batch + bulkOperation.s.currentBatch = null; + // Get the right type of batch + if (docType === common.INSERT) { + bulkOperation.s.currentBatch = bulkOperation.s.currentInsertBatch; + } else if (docType === common.UPDATE) { + bulkOperation.s.currentBatch = bulkOperation.s.currentUpdateBatch; + } else if (docType === common.REMOVE) { + bulkOperation.s.currentBatch = bulkOperation.s.currentRemoveBatch; + } + + const maxKeySize = bulkOperation.s.maxKeySize; + + // Create a new batch object if we don't have a current one + if (bulkOperation.s.currentBatch == null) + bulkOperation.s.currentBatch = new Batch(docType, bulkOperation.s.currentIndex); + + // Check if we need to create a new batch + if ( + bulkOperation.s.currentBatch.size + 1 >= bulkOperation.s.maxWriteBatchSize || + bulkOperation.s.currentBatch.sizeBytes + maxKeySize + bsonSize >= + bulkOperation.s.maxBatchSizeBytes || + bulkOperation.s.currentBatch.batchType !== docType + ) { + // Save the batch to the execution stack + bulkOperation.s.batches.push(bulkOperation.s.currentBatch); + + // Create a new batch + bulkOperation.s.currentBatch = new Batch(docType, bulkOperation.s.currentIndex); + } + + // We have an array of documents + if (Array.isArray(document)) { + throw toError('operation passed in cannot be an Array'); + } + + bulkOperation.s.currentBatch.operations.push(document); + bulkOperation.s.currentBatch.originalIndexes.push(bulkOperation.s.currentIndex); + bulkOperation.s.currentIndex = bulkOperation.s.currentIndex + 1; + + // Save back the current Batch to the right type + if (docType === common.INSERT) { + bulkOperation.s.currentInsertBatch = bulkOperation.s.currentBatch; + bulkOperation.s.bulkResult.insertedIds.push({ + index: bulkOperation.s.bulkResult.insertedIds.length, + _id: document._id + }); + } else if (docType === common.UPDATE) { + bulkOperation.s.currentUpdateBatch = bulkOperation.s.currentBatch; + } else if (docType === common.REMOVE) { + bulkOperation.s.currentRemoveBatch = bulkOperation.s.currentBatch; + } + + // Update current batch size + bulkOperation.s.currentBatch.size += 1; + bulkOperation.s.currentBatch.sizeBytes += maxKeySize + bsonSize; + + // Return bulkOperation + return bulkOperation; +} + +/** + * Create a new UnorderedBulkOperation instance (INTERNAL TYPE, do not instantiate directly) + * @class + * @extends BulkOperationBase + * @property {number} length Get the number of operations in the bulk. + * @return {UnorderedBulkOperation} a UnorderedBulkOperation instance. + */ +class UnorderedBulkOperation extends BulkOperationBase { + constructor(topology, collection, options) { + options = options || {}; + options = Object.assign(options, { addToOperationsList }); + + super(topology, collection, options, false); + } +} + +/** + * Returns an unordered batch object + * @ignore + */ +function initializeUnorderedBulkOp(topology, collection, options) { + return new UnorderedBulkOperation(topology, collection, options); +} + +initializeUnorderedBulkOp.UnorderedBulkOperation = UnorderedBulkOperation; +module.exports = initializeUnorderedBulkOp; +module.exports.Bulk = UnorderedBulkOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/change_stream.js b/scripts/2.5/node_modules/mongodb/lib/change_stream.js new file mode 100644 index 00000000..4cc779de --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/change_stream.js @@ -0,0 +1,576 @@ +'use strict'; + +const EventEmitter = require('events'); +const isResumableError = require('./error').isResumableError; +const MongoError = require('./core').MongoError; +const Cursor = require('./cursor'); +const relayEvents = require('./core/utils').relayEvents; +const maxWireVersion = require('./core/utils').maxWireVersion; +const AggregateOperation = require('./operations/aggregate'); + +const CHANGE_STREAM_OPTIONS = ['resumeAfter', 'startAfter', 'startAtOperationTime', 'fullDocument']; +const CURSOR_OPTIONS = ['batchSize', 'maxAwaitTimeMS', 'collation', 'readPreference'].concat( + CHANGE_STREAM_OPTIONS +); + +const CHANGE_DOMAIN_TYPES = { + COLLECTION: Symbol('Collection'), + DATABASE: Symbol('Database'), + CLUSTER: Symbol('Cluster') +}; + +/** + * @typedef ResumeToken + * @description Represents the logical starting point for a new or resuming {@link ChangeStream} on the server. + * @see https://docs.mongodb.com/master/changeStreams/#change-stream-resume-token + */ + +/** + * @typedef OperationTime + * @description Represents a specific point in time on a server. Can be retrieved by using {@link Db#command} + * @see https://docs.mongodb.com/manual/reference/method/db.runCommand/#response + */ + +/** + * @typedef ChangeStreamOptions + * @description Options that can be passed to a ChangeStream. Note that startAfter, resumeAfter, and startAtOperationTime are all mutually exclusive, and the server will error if more than one is specified. + * @property {string} [fullDocument='default'] Allowed values: ‘default’, ‘updateLookup’. When set to ‘updateLookup’, the change stream will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred. + * @property {number} [maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a change stream query. + * @property {ResumeToken} [resumeAfter] Allows you to start a changeStream after a specified event. See {@link https://docs.mongodb.com/master/changeStreams/#resumeafter-for-change-streams|ChangeStream documentation}. + * @property {ResumeToken} [startAfter] Similar to resumeAfter, but will allow you to start after an invalidated event. See {@link https://docs.mongodb.com/master/changeStreams/#startafter-for-change-streams|ChangeStream documentation}. + * @property {OperationTime} [startAtOperationTime] Will start the changeStream after the specified operationTime. + * @property {number} [batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. + * @property {object} [collation] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. + * @property {ReadPreference} [readPreference] The read preference. Defaults to the read preference of the database or collection. See {@link https://docs.mongodb.com/manual/reference/read-preference|read preference documentation}. + */ + +/** + * Creates a new Change Stream instance. Normally created using {@link Collection#watch|Collection.watch()}. + * @class ChangeStream + * @since 3.0.0 + * @param {(MongoClient|Db|Collection)} parent The parent object that created this change stream + * @param {Array} pipeline An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents + * @param {ChangeStreamOptions} [options] Optional settings + * @fires ChangeStream#close + * @fires ChangeStream#change + * @fires ChangeStream#end + * @fires ChangeStream#error + * @fires ChangeStream#resumeTokenChanged + * @return {ChangeStream} a ChangeStream instance. + */ +class ChangeStream extends EventEmitter { + constructor(parent, pipeline, options) { + super(); + const Collection = require('./collection'); + const Db = require('./db'); + const MongoClient = require('./mongo_client'); + + this.pipeline = pipeline || []; + this.options = options || {}; + + this.parent = parent; + this.namespace = parent.s.namespace; + if (parent instanceof Collection) { + this.type = CHANGE_DOMAIN_TYPES.COLLECTION; + this.topology = parent.s.db.serverConfig; + } else if (parent instanceof Db) { + this.type = CHANGE_DOMAIN_TYPES.DATABASE; + this.topology = parent.serverConfig; + } else if (parent instanceof MongoClient) { + this.type = CHANGE_DOMAIN_TYPES.CLUSTER; + this.topology = parent.topology; + } else { + throw new TypeError( + 'parent provided to ChangeStream constructor is not an instance of Collection, Db, or MongoClient' + ); + } + + this.promiseLibrary = parent.s.promiseLibrary; + if (!this.options.readPreference && parent.s.readPreference) { + this.options.readPreference = parent.s.readPreference; + } + + // Create contained Change Stream cursor + this.cursor = createChangeStreamCursor(this, options); + + // Listen for any `change` listeners being added to ChangeStream + this.on('newListener', eventName => { + if (eventName === 'change' && this.cursor && this.listenerCount('change') === 0) { + this.cursor.on('data', change => + processNewChange({ changeStream: this, change, eventEmitter: true }) + ); + } + }); + + // Listen for all `change` listeners being removed from ChangeStream + this.on('removeListener', eventName => { + if (eventName === 'change' && this.listenerCount('change') === 0 && this.cursor) { + this.cursor.removeAllListeners('data'); + } + }); + } + + /** + * @property {ResumeToken} resumeToken + * The cached resume token that will be used to resume + * after the most recently returned change. + */ + get resumeToken() { + return this.cursor.resumeToken; + } + + /** + * Check if there is any document still available in the Change Stream + * @function ChangeStream.prototype.hasNext + * @param {ChangeStream~resultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ + hasNext(callback) { + return this.cursor.hasNext(callback); + } + + /** + * Get the next available document from the Change Stream, returns null if no more documents are available. + * @function ChangeStream.prototype.next + * @param {ChangeStream~resultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ + next(callback) { + var self = this; + if (this.isClosed()) { + if (callback) return callback(new Error('Change Stream is not open.'), null); + return self.promiseLibrary.reject(new Error('Change Stream is not open.')); + } + + return this.cursor + .next() + .then(change => processNewChange({ changeStream: self, change, callback })) + .catch(error => processNewChange({ changeStream: self, error, callback })); + } + + /** + * Is the cursor closed + * @method ChangeStream.prototype.isClosed + * @return {boolean} + */ + isClosed() { + if (this.cursor) { + return this.cursor.isClosed(); + } + return true; + } + + /** + * Close the Change Stream + * @method ChangeStream.prototype.close + * @param {ChangeStream~resultCallback} [callback] The result callback. + * @return {Promise} returns Promise if no callback passed + */ + close(callback) { + if (!this.cursor) { + if (callback) return callback(); + return this.promiseLibrary.resolve(); + } + + // Tidy up the existing cursor + const cursor = this.cursor; + + if (callback) { + return cursor.close(err => { + ['data', 'close', 'end', 'error'].forEach(event => cursor.removeAllListeners(event)); + delete this.cursor; + + return callback(err); + }); + } + + const PromiseCtor = this.promiseLibrary || Promise; + return new PromiseCtor((resolve, reject) => { + cursor.close(err => { + ['data', 'close', 'end', 'error'].forEach(event => cursor.removeAllListeners(event)); + delete this.cursor; + + if (err) return reject(err); + resolve(); + }); + }); + } + + /** + * This method pulls all the data out of a readable stream, and writes it to the supplied destination, automatically managing the flow so that the destination is not overwhelmed by a fast readable stream. + * @method + * @param {Writable} destination The destination for writing data + * @param {object} [options] {@link https://nodejs.org/api/stream.html#stream_readable_pipe_destination_options|Pipe options} + * @return {null} + */ + pipe(destination, options) { + if (!this.pipeDestinations) { + this.pipeDestinations = []; + } + this.pipeDestinations.push(destination); + return this.cursor.pipe(destination, options); + } + + /** + * This method will remove the hooks set up for a previous pipe() call. + * @param {Writable} [destination] The destination for writing data + * @return {null} + */ + unpipe(destination) { + if (this.pipeDestinations && this.pipeDestinations.indexOf(destination) > -1) { + this.pipeDestinations.splice(this.pipeDestinations.indexOf(destination), 1); + } + return this.cursor.unpipe(destination); + } + + /** + * Return a modified Readable stream including a possible transform method. + * @method + * @param {object} [options] Optional settings. + * @param {function} [options.transform] A transformation method applied to each document emitted by the stream. + * @return {Cursor} + */ + stream(options) { + this.streamOptions = options; + return this.cursor.stream(options); + } + + /** + * This method will cause a stream in flowing mode to stop emitting data events. Any data that becomes available will remain in the internal buffer. + * @return {null} + */ + pause() { + return this.cursor.pause(); + } + + /** + * This method will cause the readable stream to resume emitting data events. + * @return {null} + */ + resume() { + return this.cursor.resume(); + } +} + +class ChangeStreamCursor extends Cursor { + constructor(topology, operation, options) { + super(topology, operation, options); + + options = options || {}; + this._resumeToken = null; + this.startAtOperationTime = options.startAtOperationTime; + + if (options.startAfter) { + this.resumeToken = options.startAfter; + } else if (options.resumeAfter) { + this.resumeToken = options.resumeAfter; + } + } + + set resumeToken(token) { + this._resumeToken = token; + this.emit('resumeTokenChanged', token); + } + + get resumeToken() { + return this._resumeToken; + } + + get resumeOptions() { + const result = {}; + for (const optionName of CURSOR_OPTIONS) { + if (this.options[optionName]) result[optionName] = this.options[optionName]; + } + + if (this.resumeToken || this.startAtOperationTime) { + ['resumeAfter', 'startAfter', 'startAtOperationTime'].forEach(key => delete result[key]); + + if (this.resumeToken) { + result.resumeAfter = this.resumeToken; + } else if (this.startAtOperationTime && maxWireVersion(this.server) >= 7) { + result.startAtOperationTime = this.startAtOperationTime; + } + } + + return result; + } + + _initializeCursor(callback) { + super._initializeCursor((err, result) => { + if (err) { + callback(err, null); + return; + } + + const response = result.documents[0]; + + if ( + this.startAtOperationTime == null && + this.resumeAfter == null && + this.startAfter == null && + maxWireVersion(this.server) >= 7 + ) { + this.startAtOperationTime = response.operationTime; + } + + const cursor = response.cursor; + if (cursor.postBatchResumeToken) { + this.cursorState.postBatchResumeToken = cursor.postBatchResumeToken; + + if (cursor.firstBatch.length === 0) { + this.resumeToken = cursor.postBatchResumeToken; + } + } + + this.emit('response'); + callback(err, result); + }); + } + + _getMore(callback) { + super._getMore((err, response) => { + if (err) { + callback(err, null); + return; + } + + const cursor = response.cursor; + if (cursor.postBatchResumeToken) { + this.cursorState.postBatchResumeToken = cursor.postBatchResumeToken; + + if (cursor.nextBatch.length === 0) { + this.resumeToken = cursor.postBatchResumeToken; + } + } + + this.emit('response'); + callback(err, response); + }); + } +} + +/** + * @event ChangeStreamCursor#response + * internal event DO NOT USE + * @ignore + */ + +// Create a new change stream cursor based on self's configuration +function createChangeStreamCursor(self, options) { + const changeStreamStageOptions = { fullDocument: options.fullDocument || 'default' }; + applyKnownOptions(changeStreamStageOptions, options, CHANGE_STREAM_OPTIONS); + if (self.type === CHANGE_DOMAIN_TYPES.CLUSTER) { + changeStreamStageOptions.allChangesForCluster = true; + } + + const pipeline = [{ $changeStream: changeStreamStageOptions }].concat(self.pipeline); + const cursorOptions = applyKnownOptions({}, options, CURSOR_OPTIONS); + const changeStreamCursor = new ChangeStreamCursor( + self.topology, + new AggregateOperation(self.parent, pipeline, options), + cursorOptions + ); + + relayEvents(changeStreamCursor, self, ['resumeTokenChanged', 'end', 'close']); + + /** + * Fired for each new matching change in the specified namespace. Attaching a `change` + * event listener to a Change Stream will switch the stream into flowing mode. Data will + * then be passed as soon as it is available. + * + * @event ChangeStream#change + * @type {object} + */ + if (self.listenerCount('change') > 0) { + changeStreamCursor.on('data', function(change) { + processNewChange({ changeStream: self, change, eventEmitter: true }); + }); + } + + /** + * Change stream close event + * + * @event ChangeStream#close + * @type {null} + */ + + /** + * Change stream end event + * + * @event ChangeStream#end + * @type {null} + */ + + /** + * Emitted each time the change stream stores a new resume token. + * + * @event ChangeStream#resumeTokenChanged + * @type {ResumeToken} + */ + + /** + * Fired when the stream encounters an error. + * + * @event ChangeStream#error + * @type {Error} + */ + changeStreamCursor.on('error', function(error) { + processNewChange({ changeStream: self, error, eventEmitter: true }); + }); + + if (self.pipeDestinations) { + const cursorStream = changeStreamCursor.stream(self.streamOptions); + for (let pipeDestination in self.pipeDestinations) { + cursorStream.pipe(pipeDestination); + } + } + + return changeStreamCursor; +} + +function applyKnownOptions(target, source, optionNames) { + optionNames.forEach(name => { + if (source[name]) { + target[name] = source[name]; + } + }); + + return target; +} + +// This method performs a basic server selection loop, satisfying the requirements of +// ChangeStream resumability until the new SDAM layer can be used. +const SELECTION_TIMEOUT = 30000; +function waitForTopologyConnected(topology, options, callback) { + setTimeout(() => { + if (options && options.start == null) options.start = process.hrtime(); + const start = options.start || process.hrtime(); + const timeout = options.timeout || SELECTION_TIMEOUT; + const readPreference = options.readPreference; + + if (topology.isConnected({ readPreference })) return callback(null, null); + const hrElapsed = process.hrtime(start); + const elapsed = (hrElapsed[0] * 1e9 + hrElapsed[1]) / 1e6; + if (elapsed > timeout) return callback(new MongoError('Timed out waiting for connection')); + waitForTopologyConnected(topology, options, callback); + }, 3000); // this is an arbitrary wait time to allow SDAM to transition +} + +// Handle new change events. This method brings together the routes from the callback, event emitter, and promise ways of using ChangeStream. +function processNewChange(args) { + const changeStream = args.changeStream; + const error = args.error; + const change = args.change; + const callback = args.callback; + const eventEmitter = args.eventEmitter || false; + + // If the changeStream is closed, then it should not process a change. + if (changeStream.isClosed()) { + // We do not error in the eventEmitter case. + if (eventEmitter) { + return; + } + + const error = new MongoError('ChangeStream is closed'); + return typeof callback === 'function' + ? callback(error, null) + : changeStream.promiseLibrary.reject(error); + } + + const cursor = changeStream.cursor; + const topology = changeStream.topology; + const options = changeStream.cursor.options; + + if (error) { + if (isResumableError(error) && !changeStream.attemptingResume) { + changeStream.attemptingResume = true; + + // stop listening to all events from old cursor + ['data', 'close', 'end', 'error'].forEach(event => + changeStream.cursor.removeAllListeners(event) + ); + + // close internal cursor, ignore errors + changeStream.cursor.close(); + + // attempt recreating the cursor + if (eventEmitter) { + waitForTopologyConnected(topology, { readPreference: options.readPreference }, err => { + if (err) { + changeStream.emit('error', err); + changeStream.emit('close'); + return; + } + changeStream.cursor = createChangeStreamCursor(changeStream, cursor.resumeOptions); + }); + + return; + } + + if (callback) { + waitForTopologyConnected(topology, { readPreference: options.readPreference }, err => { + if (err) return callback(err, null); + + changeStream.cursor = createChangeStreamCursor(changeStream, cursor.resumeOptions); + changeStream.next(callback); + }); + + return; + } + + return new Promise((resolve, reject) => { + waitForTopologyConnected(topology, { readPreference: options.readPreference }, err => { + if (err) return reject(err); + resolve(); + }); + }) + .then( + () => (changeStream.cursor = createChangeStreamCursor(changeStream, cursor.resumeOptions)) + ) + .then(() => changeStream.next()); + } + + if (eventEmitter) return changeStream.emit('error', error); + if (typeof callback === 'function') return callback(error, null); + return changeStream.promiseLibrary.reject(error); + } + + changeStream.attemptingResume = false; + + if (change && !change._id) { + const noResumeTokenError = new Error( + 'A change stream document has been received that lacks a resume token (_id).' + ); + + if (eventEmitter) return changeStream.emit('error', noResumeTokenError); + if (typeof callback === 'function') return callback(noResumeTokenError, null); + return changeStream.promiseLibrary.reject(noResumeTokenError); + } + + // cache the resume token + if (cursor.bufferedCount() === 0 && cursor.cursorState.postBatchResumeToken) { + cursor.resumeToken = cursor.cursorState.postBatchResumeToken; + } else { + cursor.resumeToken = change._id; + } + + // wipe the startAtOperationTime if there was one so that there won't be a conflict + // between resumeToken and startAtOperationTime if we need to reconnect the cursor + changeStream.options.startAtOperationTime = undefined; + + // Return the change + if (eventEmitter) return changeStream.emit('change', change); + if (typeof callback === 'function') return callback(error, change); + return changeStream.promiseLibrary.resolve(change); +} + +/** + * The callback format for results + * @callback ChangeStream~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {(object|null)} result The result object if the command was executed successfully. + */ + +module.exports = ChangeStream; diff --git a/scripts/2.5/node_modules/mongodb/lib/collection.js b/scripts/2.5/node_modules/mongodb/lib/collection.js new file mode 100644 index 00000000..49edbdbe --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/collection.js @@ -0,0 +1,2113 @@ +'use strict'; + +const deprecate = require('util').deprecate; +const deprecateOptions = require('./utils').deprecateOptions; +const checkCollectionName = require('./utils').checkCollectionName; +const ObjectID = require('./core').BSON.ObjectID; +const MongoError = require('./core').MongoError; +const toError = require('./utils').toError; +const normalizeHintField = require('./utils').normalizeHintField; +const decorateCommand = require('./utils').decorateCommand; +const decorateWithCollation = require('./utils').decorateWithCollation; +const decorateWithReadConcern = require('./utils').decorateWithReadConcern; +const formattedOrderClause = require('./utils').formattedOrderClause; +const ReadPreference = require('./core').ReadPreference; +const unordered = require('./bulk/unordered'); +const ordered = require('./bulk/ordered'); +const ChangeStream = require('./change_stream'); +const executeLegacyOperation = require('./utils').executeLegacyOperation; +const resolveReadPreference = require('./utils').resolveReadPreference; +const WriteConcern = require('./write_concern'); +const ReadConcern = require('./read_concern'); +const MongoDBNamespace = require('./utils').MongoDBNamespace; +const AggregationCursor = require('./aggregation_cursor'); +const CommandCursor = require('./command_cursor'); + +// Operations +const checkForAtomicOperators = require('./operations/collection_ops').checkForAtomicOperators; +const ensureIndex = require('./operations/collection_ops').ensureIndex; +const group = require('./operations/collection_ops').group; +const parallelCollectionScan = require('./operations/collection_ops').parallelCollectionScan; +const removeDocuments = require('./operations/common_functions').removeDocuments; +const save = require('./operations/collection_ops').save; +const updateDocuments = require('./operations/common_functions').updateDocuments; + +const AggregateOperation = require('./operations/aggregate'); +const BulkWriteOperation = require('./operations/bulk_write'); +const CountDocumentsOperation = require('./operations/count_documents'); +const CreateIndexOperation = require('./operations/create_index'); +const CreateIndexesOperation = require('./operations/create_indexes'); +const DeleteManyOperation = require('./operations/delete_many'); +const DeleteOneOperation = require('./operations/delete_one'); +const DistinctOperation = require('./operations/distinct'); +const DropCollectionOperation = require('./operations/drop').DropCollectionOperation; +const DropIndexOperation = require('./operations/drop_index'); +const DropIndexesOperation = require('./operations/drop_indexes'); +const EstimatedDocumentCountOperation = require('./operations/estimated_document_count'); +const FindOperation = require('./operations/find'); +const FindOneOperation = require('./operations/find_one'); +const FindAndModifyOperation = require('./operations/find_and_modify'); +const FindOneAndDeleteOperation = require('./operations/find_one_and_delete'); +const FindOneAndReplaceOperation = require('./operations/find_one_and_replace'); +const FindOneAndUpdateOperation = require('./operations/find_one_and_update'); +const GeoHaystackSearchOperation = require('./operations/geo_haystack_search'); +const IndexesOperation = require('./operations/indexes'); +const IndexExistsOperation = require('./operations/index_exists'); +const IndexInformationOperation = require('./operations/index_information'); +const InsertManyOperation = require('./operations/insert_many'); +const InsertOneOperation = require('./operations/insert_one'); +const IsCappedOperation = require('./operations/is_capped'); +const ListIndexesOperation = require('./operations/list_indexes'); +const MapReduceOperation = require('./operations/map_reduce'); +const OptionsOperation = require('./operations/options_operation'); +const RenameOperation = require('./operations/rename'); +const ReIndexOperation = require('./operations/re_index'); +const ReplaceOneOperation = require('./operations/replace_one'); +const StatsOperation = require('./operations/stats'); +const UpdateManyOperation = require('./operations/update_many'); +const UpdateOneOperation = require('./operations/update_one'); + +const executeOperation = require('./operations/execute_operation'); + +/** + * @fileOverview The **Collection** class is an internal class that embodies a MongoDB collection + * allowing for insert/update/remove/find and other command operation on that MongoDB collection. + * + * **COLLECTION Cannot directly be instantiated** + * @example + * const MongoClient = require('mongodb').MongoClient; + * const test = require('assert'); + * // Connection url + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, client) { + * // Create a collection we want to drop later + * const col = client.db(dbName).collection('createIndexExample1'); + * // Show that duplicate records got dropped + * col.find({}).toArray(function(err, items) { + * test.equal(null, err); + * test.equal(4, items.length); + * client.close(); + * }); + * }); + */ + +const mergeKeys = ['ignoreUndefined']; + +/** + * Create a new Collection instance (INTERNAL TYPE, do not instantiate directly) + * @class + * @property {string} collectionName Get the collection name. + * @property {string} namespace Get the full collection namespace. + * @property {object} writeConcern The current write concern values. + * @property {object} readConcern The current read concern values. + * @property {object} hint Get current index hint for collection. + * @return {Collection} a Collection instance. + */ +function Collection(db, topology, dbName, name, pkFactory, options) { + checkCollectionName(name); + + // Unpack variables + const internalHint = null; + const slaveOk = options == null || options.slaveOk == null ? db.slaveOk : options.slaveOk; + const serializeFunctions = + options == null || options.serializeFunctions == null + ? db.s.options.serializeFunctions + : options.serializeFunctions; + const raw = options == null || options.raw == null ? db.s.options.raw : options.raw; + const promoteLongs = + options == null || options.promoteLongs == null + ? db.s.options.promoteLongs + : options.promoteLongs; + const promoteValues = + options == null || options.promoteValues == null + ? db.s.options.promoteValues + : options.promoteValues; + const promoteBuffers = + options == null || options.promoteBuffers == null + ? db.s.options.promoteBuffers + : options.promoteBuffers; + const collectionHint = null; + + const namespace = new MongoDBNamespace(dbName, name); + + // Get the promiseLibrary + const promiseLibrary = options.promiseLibrary || Promise; + + // Set custom primary key factory if provided + pkFactory = pkFactory == null ? ObjectID : pkFactory; + + // Internal state + this.s = { + // Set custom primary key factory if provided + pkFactory: pkFactory, + // Db + db: db, + // Topology + topology: topology, + // Options + options: options, + // Namespace + namespace: namespace, + // Read preference + readPreference: ReadPreference.fromOptions(options), + // SlaveOK + slaveOk: slaveOk, + // Serialize functions + serializeFunctions: serializeFunctions, + // Raw + raw: raw, + // promoteLongs + promoteLongs: promoteLongs, + // promoteValues + promoteValues: promoteValues, + // promoteBuffers + promoteBuffers: promoteBuffers, + // internalHint + internalHint: internalHint, + // collectionHint + collectionHint: collectionHint, + // Promise library + promiseLibrary: promiseLibrary, + // Read Concern + readConcern: ReadConcern.fromOptions(options), + // Write Concern + writeConcern: WriteConcern.fromOptions(options) + }; +} + +Object.defineProperty(Collection.prototype, 'dbName', { + enumerable: true, + get: function() { + return this.s.namespace.db; + } +}); + +Object.defineProperty(Collection.prototype, 'collectionName', { + enumerable: true, + get: function() { + return this.s.namespace.collection; + } +}); + +Object.defineProperty(Collection.prototype, 'namespace', { + enumerable: true, + get: function() { + return this.s.namespace.toString(); + } +}); + +Object.defineProperty(Collection.prototype, 'readConcern', { + enumerable: true, + get: function() { + if (this.s.readConcern == null) { + return this.s.db.readConcern; + } + return this.s.readConcern; + } +}); + +Object.defineProperty(Collection.prototype, 'readPreference', { + enumerable: true, + get: function() { + if (this.s.readPreference == null) { + return this.s.db.readPreference; + } + + return this.s.readPreference; + } +}); + +Object.defineProperty(Collection.prototype, 'writeConcern', { + enumerable: true, + get: function() { + if (this.s.writeConcern == null) { + return this.s.db.writeConcern; + } + return this.s.writeConcern; + } +}); + +/** + * @ignore + */ +Object.defineProperty(Collection.prototype, 'hint', { + enumerable: true, + get: function() { + return this.s.collectionHint; + }, + set: function(v) { + this.s.collectionHint = normalizeHintField(v); + } +}); + +const DEPRECATED_FIND_OPTIONS = ['maxScan', 'fields', 'snapshot']; + +/** + * Creates a cursor for a query that can be used to iterate over results from MongoDB + * @method + * @param {object} [query={}] The cursor query object. + * @param {object} [options] Optional settings. + * @param {number} [options.limit=0] Sets the limit of documents returned in the query. + * @param {(array|object)} [options.sort] Set to sort the documents coming back from the query. Array of indexes, [['a', 1]] etc. + * @param {object} [options.projection] The fields to return in the query. Object of fields to include or exclude (not both), {'a':1} + * @param {object} [options.fields] **Deprecated** Use `options.projection` instead + * @param {number} [options.skip=0] Set to skip N documents ahead in your query (useful for pagination). + * @param {Object} [options.hint] Tell the query to use specific indexes in the query. Object of indexes to use, {'_id':1} + * @param {boolean} [options.explain=false] Explain the query instead of returning the data. + * @param {boolean} [options.snapshot=false] DEPRECATED: Snapshot query. + * @param {boolean} [options.timeout=false] Specify if the cursor can timeout. + * @param {boolean} [options.tailable=false] Specify if the cursor is tailable. + * @param {number} [options.batchSize=1000] Set the batchSize for the getMoreCommand when iterating over the query results. + * @param {boolean} [options.returnKey=false] Only return the index key. + * @param {number} [options.maxScan] DEPRECATED: Limit the number of items to scan. + * @param {number} [options.min] Set index bounds. + * @param {number} [options.max] Set index bounds. + * @param {boolean} [options.showDiskLoc=false] Show disk location of results. + * @param {string} [options.comment] You can put a $comment field on a query to make looking in the profiler logs simpler. + * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. + * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution. + * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. + * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {boolean} [options.partial=false] Specify if the cursor should return partial results when querying against a sharded system + * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query. + * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). + * @param {ClientSession} [options.session] optional session to use for this operation + * @throws {MongoError} + * @return {Cursor} + */ +Collection.prototype.find = deprecateOptions( + { + name: 'collection.find', + deprecatedOptions: DEPRECATED_FIND_OPTIONS, + optionsIndex: 1 + }, + function(query, options, callback) { + if (typeof callback === 'object') { + // TODO(MAJOR): throw in the future + console.warn('Third parameter to `find()` must be a callback or undefined'); + } + + let selector = query; + // figuring out arguments + if (typeof callback !== 'function') { + if (typeof options === 'function') { + callback = options; + options = undefined; + } else if (options == null) { + callback = typeof selector === 'function' ? selector : undefined; + selector = typeof selector === 'object' ? selector : undefined; + } + } + + // Ensure selector is not null + selector = selector == null ? {} : selector; + // Validate correctness off the selector + const object = selector; + if (Buffer.isBuffer(object)) { + const object_size = object[0] | (object[1] << 8) | (object[2] << 16) | (object[3] << 24); + if (object_size !== object.length) { + const error = new Error( + 'query selector raw message size does not match message header size [' + + object.length + + '] != [' + + object_size + + ']' + ); + error.name = 'MongoError'; + throw error; + } + } + + // Check special case where we are using an objectId + if (selector != null && selector._bsontype === 'ObjectID') { + selector = { _id: selector }; + } + + if (!options) options = {}; + + let projection = options.projection || options.fields; + + if (projection && !Buffer.isBuffer(projection) && Array.isArray(projection)) { + projection = projection.length + ? projection.reduce((result, field) => { + result[field] = 1; + return result; + }, {}) + : { _id: 1 }; + } + + // Make a shallow copy of options + let newOptions = Object.assign({}, options); + + // Make a shallow copy of the collection options + for (let key in this.s.options) { + if (mergeKeys.indexOf(key) !== -1) { + newOptions[key] = this.s.options[key]; + } + } + + // Unpack options + newOptions.skip = options.skip ? options.skip : 0; + newOptions.limit = options.limit ? options.limit : 0; + newOptions.raw = typeof options.raw === 'boolean' ? options.raw : this.s.raw; + newOptions.hint = + options.hint != null ? normalizeHintField(options.hint) : this.s.collectionHint; + newOptions.timeout = typeof options.timeout === 'undefined' ? undefined : options.timeout; + // // If we have overridden slaveOk otherwise use the default db setting + newOptions.slaveOk = options.slaveOk != null ? options.slaveOk : this.s.db.slaveOk; + + // Add read preference if needed + newOptions.readPreference = resolveReadPreference(this, newOptions); + + // Set slave ok to true if read preference different from primary + if ( + newOptions.readPreference != null && + (newOptions.readPreference !== 'primary' || newOptions.readPreference.mode !== 'primary') + ) { + newOptions.slaveOk = true; + } + + // Ensure the query is an object + if (selector != null && typeof selector !== 'object') { + throw MongoError.create({ message: 'query selector must be an object', driver: true }); + } + + // Build the find command + const findCommand = { + find: this.s.namespace.toString(), + limit: newOptions.limit, + skip: newOptions.skip, + query: selector + }; + + // Ensure we use the right await data option + if (typeof newOptions.awaitdata === 'boolean') { + newOptions.awaitData = newOptions.awaitdata; + } + + // Translate to new command option noCursorTimeout + if (typeof newOptions.timeout === 'boolean') newOptions.noCursorTimeout = newOptions.timeout; + + decorateCommand(findCommand, newOptions, ['session', 'collation']); + + if (projection) findCommand.fields = projection; + + // Add db object to the new options + newOptions.db = this.s.db; + + // Add the promise library + newOptions.promiseLibrary = this.s.promiseLibrary; + + // Set raw if available at collection level + if (newOptions.raw == null && typeof this.s.raw === 'boolean') newOptions.raw = this.s.raw; + // Set promoteLongs if available at collection level + if (newOptions.promoteLongs == null && typeof this.s.promoteLongs === 'boolean') + newOptions.promoteLongs = this.s.promoteLongs; + if (newOptions.promoteValues == null && typeof this.s.promoteValues === 'boolean') + newOptions.promoteValues = this.s.promoteValues; + if (newOptions.promoteBuffers == null && typeof this.s.promoteBuffers === 'boolean') + newOptions.promoteBuffers = this.s.promoteBuffers; + + // Sort options + if (findCommand.sort) { + findCommand.sort = formattedOrderClause(findCommand.sort); + } + + // Set the readConcern + decorateWithReadConcern(findCommand, this, options); + + // Decorate find command with collation options + try { + decorateWithCollation(findCommand, this, options); + } catch (err) { + if (typeof callback === 'function') return callback(err, null); + throw err; + } + + const cursor = this.s.topology.cursor( + new FindOperation(this, this.s.namespace, findCommand, newOptions), + newOptions + ); + + // TODO: remove this when NODE-2074 is resolved + if (typeof callback === 'function') { + callback(null, cursor); + return; + } + + return cursor; + } +); + +/** + * Inserts a single document into MongoDB. If documents passed in do not contain the **_id** field, + * one will be added to each of the documents missing it by the driver, mutating the document. This behavior + * can be overridden by setting the **forceServerObjectId** flag. + * + * @method + * @param {object} doc Document to insert. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~insertOneWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.insertOne = function(doc, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + // Add ignoreUndefined + if (this.s.options.ignoreUndefined) { + options = Object.assign({}, options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + const insertOneOperation = new InsertOneOperation(this, doc, options); + + return executeOperation(this.s.topology, insertOneOperation, callback); +}; + +/** + * Inserts an array of documents into MongoDB. If documents passed in do not contain the **_id** field, + * one will be added to each of the documents missing it by the driver, mutating the document. This behavior + * can be overridden by setting the **forceServerObjectId** flag. + * + * @method + * @param {object[]} docs Documents to insert. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {boolean} [options.ordered=true] If true, when an insert fails, don't execute the remaining writes. If false, continue with remaining inserts when one fails. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~insertWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.insertMany = function(docs, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options ? Object.assign({}, options) : { ordered: true }; + + const insertManyOperation = new InsertManyOperation(this, docs, options); + + return executeOperation(this.s.topology, insertManyOperation, callback); +}; + +/** + * @typedef {Object} Collection~BulkWriteOpResult + * @property {number} insertedCount Number of documents inserted. + * @property {number} matchedCount Number of documents matched for update. + * @property {number} modifiedCount Number of documents modified. + * @property {number} deletedCount Number of documents deleted. + * @property {number} upsertedCount Number of documents upserted. + * @property {object} insertedIds Inserted document generated Id's, hash key is the index of the originating operation + * @property {object} upsertedIds Upserted document generated Id's, hash key is the index of the originating operation + * @property {object} result The command result object. + */ + +/** + * The callback format for inserts + * @callback Collection~bulkWriteOpCallback + * @param {BulkWriteError} error An error instance representing the error during the execution. + * @param {Collection~BulkWriteOpResult} result The result object if the command was executed successfully. + */ + +/** + * Perform a bulkWrite operation without a fluent API + * + * Legal operation types are + * + * { insertOne: { document: { a: 1 } } } + * + * { updateOne: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } } + * + * { updateMany: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } } + * + * { updateMany: { filter: {}, update: {$set: {"a.$[i].x": 5}}, arrayFilters: [{ "i.x": 5 }]} } + * + * { deleteOne: { filter: {c:1} } } + * + * { deleteMany: { filter: {c:1} } } + * + * { replaceOne: { filter: {c:3}, replacement: {c:4}, upsert:true}} + * + * If documents passed in do not contain the **_id** field, + * one will be added to each of the documents missing it by the driver, mutating the document. This behavior + * can be overridden by setting the **forceServerObjectId** flag. + * + * @method + * @param {object[]} operations Bulk operations to perform. + * @param {object} [options] Optional settings. + * @param {object[]} [options.arrayFilters] Determines which array elements to modify for update operation in MongoDB 3.6 or higher. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {boolean} [options.ordered=true] Execute write operation in ordered or unordered fashion. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~bulkWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.bulkWrite = function(operations, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || { ordered: true }; + + if (!Array.isArray(operations)) { + throw MongoError.create({ message: 'operations must be an array of documents', driver: true }); + } + + const bulkWriteOperation = new BulkWriteOperation(this, operations, options); + + return executeOperation(this.s.topology, bulkWriteOperation, callback); +}; + +/** + * @typedef {Object} Collection~WriteOpResult + * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany + * @property {object} connection The connection object used for the operation. + * @property {object} result The command result object. + */ + +/** + * The callback format for inserts + * @callback Collection~writeOpCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection~WriteOpResult} result The result object if the command was executed successfully. + */ + +/** + * @typedef {Object} Collection~insertWriteOpResult + * @property {Number} insertedCount The total amount of documents inserted. + * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany + * @property {Object.} insertedIds Map of the index of the inserted document to the id of the inserted document. + * @property {object} connection The connection object used for the operation. + * @property {object} result The raw command result object returned from MongoDB (content might vary by server version). + * @property {Number} result.ok Is 1 if the command executed correctly. + * @property {Number} result.n The total count of documents inserted. + */ + +/** + * @typedef {Object} Collection~insertOneWriteOpResult + * @property {Number} insertedCount The total amount of documents inserted. + * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany + * @property {ObjectId} insertedId The driver generated ObjectId for the insert operation. + * @property {object} connection The connection object used for the operation. + * @property {object} result The raw command result object returned from MongoDB (content might vary by server version). + * @property {Number} result.ok Is 1 if the command executed correctly. + * @property {Number} result.n The total count of documents inserted. + */ + +/** + * The callback format for inserts + * @callback Collection~insertWriteOpCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection~insertWriteOpResult} result The result object if the command was executed successfully. + */ + +/** + * The callback format for inserts + * @callback Collection~insertOneWriteOpCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection~insertOneWriteOpResult} result The result object if the command was executed successfully. + */ + +/** + * Inserts a single document or a an array of documents into MongoDB. If documents passed in do not contain the **_id** field, + * one will be added to each of the documents missing it by the driver, mutating the document. This behavior + * can be overridden by setting the **forceServerObjectId** flag. + * + * @method + * @param {(object|object[])} docs Documents to insert. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~insertWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + * @deprecated Use insertOne, insertMany or bulkWrite + */ +Collection.prototype.insert = deprecate(function(docs, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || { ordered: false }; + docs = !Array.isArray(docs) ? [docs] : docs; + + if (options.keepGoing === true) { + options.ordered = false; + } + + return this.insertMany(docs, options, callback); +}, 'collection.insert is deprecated. Use insertOne, insertMany or bulkWrite instead.'); + +/** + * @typedef {Object} Collection~updateWriteOpResult + * @property {Object} result The raw result returned from MongoDB. Will vary depending on server version. + * @property {Number} result.ok Is 1 if the command executed correctly. + * @property {Number} result.n The total count of documents scanned. + * @property {Number} result.nModified The total count of documents modified. + * @property {Object} connection The connection object used for the operation. + * @property {Number} matchedCount The number of documents that matched the filter. + * @property {Number} modifiedCount The number of documents that were modified. + * @property {Number} upsertedCount The number of documents upserted. + * @property {Object} upsertedId The upserted id. + * @property {ObjectId} upsertedId._id The upserted _id returned from the server. + * @property {Object} message + * @property {object[]} [ops] In a response to {@link Collection#replaceOne replaceOne}, contains the new value of the document on the server. This is the same document that was originally passed in, and is only here for legacy purposes. + */ + +/** + * The callback format for inserts + * @callback Collection~updateWriteOpCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection~updateWriteOpResult} result The result object if the command was executed successfully. + */ + +/** + * Update a single document in a collection + * @method + * @param {object} filter The Filter used to select the document to update + * @param {object} update The update operations to be applied to the document + * @param {object} [options] Optional settings. + * @param {boolean} [options.upsert=false] Update operation is an upsert. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {Array} [options.arrayFilters] optional list of array filters referenced in filtered positional operators + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~updateWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.updateOne = function(filter, update, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const err = checkForAtomicOperators(update); + if (err) { + if (typeof callback === 'function') return callback(err); + return this.s.promiseLibrary.reject(err); + } + + options = Object.assign({}, options); + + // Add ignoreUndefined + if (this.s.options.ignoreUndefined) { + options = Object.assign({}, options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + const updateOneOperation = new UpdateOneOperation(this, filter, update, options); + + return executeOperation(this.s.topology, updateOneOperation, callback); +}; + +/** + * Replace a document in a collection with another document + * @method + * @param {object} filter The Filter used to select the document to replace + * @param {object} doc The Document that replaces the matching document + * @param {object} [options] Optional settings. + * @param {boolean} [options.upsert=false] Update operation is an upsert. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~updateWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.replaceOne = function(filter, doc, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = Object.assign({}, options); + + // Add ignoreUndefined + if (this.s.options.ignoreUndefined) { + options = Object.assign({}, options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + const replaceOneOperation = new ReplaceOneOperation(this, filter, doc, options); + + return executeOperation(this.s.topology, replaceOneOperation, callback); +}; + +/** + * Update multiple documents in a collection + * @method + * @param {object} filter The Filter used to select the documents to update + * @param {object} update The update operations to be applied to the documents + * @param {object} [options] Optional settings. + * @param {boolean} [options.upsert=false] Update operation is an upsert. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {Array} [options.arrayFilters] optional list of array filters referenced in filtered positional operators + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~updateWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.updateMany = function(filter, update, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const err = checkForAtomicOperators(update); + if (err) { + if (typeof callback === 'function') return callback(err); + return this.s.promiseLibrary.reject(err); + } + + options = Object.assign({}, options); + + // Add ignoreUndefined + if (this.s.options.ignoreUndefined) { + options = Object.assign({}, options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + const updateManyOperation = new UpdateManyOperation(this, filter, update, options); + + return executeOperation(this.s.topology, updateManyOperation, callback); +}; + +/** + * Updates documents. + * @method + * @param {object} selector The selector for the update operation. + * @param {object} update The update operations to be applied to the documents + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.upsert=false] Update operation is an upsert. + * @param {boolean} [options.multi=false] Update one/all documents with operation. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). + * @param {Array} [options.arrayFilters] optional list of array filters referenced in filtered positional operators + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~writeOpCallback} [callback] The command result callback + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + * @deprecated use updateOne, updateMany or bulkWrite + */ +Collection.prototype.update = deprecate(function(selector, update, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + // Add ignoreUndefined + if (this.s.options.ignoreUndefined) { + options = Object.assign({}, options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + return executeLegacyOperation(this.s.topology, updateDocuments, [ + this, + selector, + update, + options, + callback + ]); +}, 'collection.update is deprecated. Use updateOne, updateMany, or bulkWrite instead.'); + +/** + * @typedef {Object} Collection~deleteWriteOpResult + * @property {Object} result The raw result returned from MongoDB. Will vary depending on server version. + * @property {Number} result.ok Is 1 if the command executed correctly. + * @property {Number} result.n The total count of documents deleted. + * @property {Object} connection The connection object used for the operation. + * @property {Number} deletedCount The number of documents deleted. + */ + +/** + * The callback format for inserts + * @callback Collection~deleteWriteOpCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection~deleteWriteOpResult} result The result object if the command was executed successfully. + */ + +/** + * Delete a document from a collection + * @method + * @param {object} filter The Filter used to select the document to remove + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~deleteWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.deleteOne = function(filter, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = Object.assign({}, options); + + // Add ignoreUndefined + if (this.s.options.ignoreUndefined) { + options = Object.assign({}, options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + const deleteOneOperation = new DeleteOneOperation(this, filter, options); + + return executeOperation(this.s.topology, deleteOneOperation, callback); +}; + +Collection.prototype.removeOne = Collection.prototype.deleteOne; + +/** + * Delete multiple documents from a collection + * @method + * @param {object} filter The Filter used to select the documents to remove + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~deleteWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.deleteMany = function(filter, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = Object.assign({}, options); + + // Add ignoreUndefined + if (this.s.options.ignoreUndefined) { + options = Object.assign({}, options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + const deleteManyOperation = new DeleteManyOperation(this, filter, options); + + return executeOperation(this.s.topology, deleteManyOperation, callback); +}; + +Collection.prototype.removeMany = Collection.prototype.deleteMany; + +/** + * Remove documents. + * @method + * @param {object} selector The selector for the update operation. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.single=false] Removes the first document found. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~writeOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + * @deprecated use deleteOne, deleteMany or bulkWrite + */ +Collection.prototype.remove = deprecate(function(selector, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + // Add ignoreUndefined + if (this.s.options.ignoreUndefined) { + options = Object.assign({}, options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + return executeLegacyOperation(this.s.topology, removeDocuments, [ + this, + selector, + options, + callback + ]); +}, 'collection.remove is deprecated. Use deleteOne, deleteMany, or bulkWrite instead.'); + +/** + * Save a document. Simple full document replacement function. Not recommended for efficiency, use atomic + * operators and update instead for more efficient operations. + * @method + * @param {object} doc Document to save + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~writeOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + * @deprecated use insertOne, insertMany, updateOne or updateMany + */ +Collection.prototype.save = deprecate(function(doc, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + // Add ignoreUndefined + if (this.s.options.ignoreUndefined) { + options = Object.assign({}, options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + return executeLegacyOperation(this.s.topology, save, [this, doc, options, callback]); +}, 'collection.save is deprecated. Use insertOne, insertMany, updateOne, or updateMany instead.'); + +/** + * The callback format for results + * @callback Collection~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {object} result The result object if the command was executed successfully. + */ + +/** + * The callback format for an aggregation call + * @callback Collection~aggregationCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {AggregationCursor} cursor The cursor if the aggregation command was executed successfully. + */ + +/** + * Fetches the first document that matches the query + * @method + * @param {object} query Query for find Operation + * @param {object} [options] Optional settings. + * @param {number} [options.limit=0] Sets the limit of documents returned in the query. + * @param {(array|object)} [options.sort] Set to sort the documents coming back from the query. Array of indexes, [['a', 1]] etc. + * @param {object} [options.projection] The fields to return in the query. Object of fields to include or exclude (not both), {'a':1} + * @param {object} [options.fields] **Deprecated** Use `options.projection` instead + * @param {number} [options.skip=0] Set to skip N documents ahead in your query (useful for pagination). + * @param {Object} [options.hint] Tell the query to use specific indexes in the query. Object of indexes to use, {'_id':1} + * @param {boolean} [options.explain=false] Explain the query instead of returning the data. + * @param {boolean} [options.snapshot=false] DEPRECATED: Snapshot query. + * @param {boolean} [options.timeout=false] Specify if the cursor can timeout. + * @param {boolean} [options.tailable=false] Specify if the cursor is tailable. + * @param {number} [options.batchSize=1] Set the batchSize for the getMoreCommand when iterating over the query results. + * @param {boolean} [options.returnKey=false] Only return the index key. + * @param {number} [options.maxScan] DEPRECATED: Limit the number of items to scan. + * @param {number} [options.min] Set index bounds. + * @param {number} [options.max] Set index bounds. + * @param {boolean} [options.showDiskLoc=false] Show disk location of results. + * @param {string} [options.comment] You can put a $comment field on a query to make looking in the profiler logs simpler. + * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. + * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution. + * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. + * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {boolean} [options.partial=false] Specify if the cursor should return partial results when querying against a sharded system + * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query. + * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.findOne = deprecateOptions( + { + name: 'collection.find', + deprecatedOptions: DEPRECATED_FIND_OPTIONS, + optionsIndex: 1 + }, + function(query, options, callback) { + if (typeof callback === 'object') { + // TODO(MAJOR): throw in the future + console.warn('Third parameter to `findOne()` must be a callback or undefined'); + } + + if (typeof query === 'function') (callback = query), (query = {}), (options = {}); + if (typeof options === 'function') (callback = options), (options = {}); + query = query || {}; + options = options || {}; + + const findOneOperation = new FindOneOperation(this, query, options); + + return executeOperation(this.s.topology, findOneOperation, callback); + } +); + +/** + * The callback format for the collection method, must be used if strict is specified + * @callback Collection~collectionResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection} collection The collection instance. + */ + +/** + * Rename the collection. + * + * @method + * @param {string} newName New name of of the collection. + * @param {object} [options] Optional settings. + * @param {boolean} [options.dropTarget=false] Drop the target name collection if it previously exists. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~collectionResultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.rename = function(newName, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = Object.assign({}, options, { readPreference: ReadPreference.PRIMARY }); + + const renameOperation = new RenameOperation(this, newName, options); + + return executeOperation(this.s.topology, renameOperation, callback); +}; + +/** + * Drop the collection from the database, removing it permanently. New accesses will create a new collection. + * + * @method + * @param {object} [options] Optional settings. + * @param {WriteConcern} [options.writeConcern] A full WriteConcern object + * @param {(number|string)} [options.w] The write concern + * @param {number} [options.wtimeout] The write concern timeout + * @param {boolean} [options.j] The journal write concern + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.drop = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const dropCollectionOperation = new DropCollectionOperation( + this.s.db, + this.collectionName, + options + ); + + return executeOperation(this.s.topology, dropCollectionOperation, callback); +}; + +/** + * Returns the options of the collection. + * + * @method + * @param {Object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.options = function(opts, callback) { + if (typeof opts === 'function') (callback = opts), (opts = {}); + opts = opts || {}; + + const optionsOperation = new OptionsOperation(this, opts); + + return executeOperation(this.s.topology, optionsOperation, callback); +}; + +/** + * Returns if the collection is a capped collection + * + * @method + * @param {Object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.isCapped = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const isCappedOperation = new IsCappedOperation(this, options); + + return executeOperation(this.s.topology, isCappedOperation, callback); +}; + +/** + * Creates an index on the db and collection collection. + * @method + * @param {(string|array|object)} fieldOrSpec Defines the index. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.unique=false] Creates an unique index. + * @param {boolean} [options.sparse=false] Creates a sparse index. + * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. + * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value + * @param {number} [options.min] For geospatial indexes set the lower bound for the co-ordinates. + * @param {number} [options.max] For geospatial indexes set the high bound for the co-ordinates. + * @param {number} [options.v] Specify the format version of the indexes. + * @param {number} [options.expireAfterSeconds] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) + * @param {string} [options.name] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) + * @param {object} [options.partialFilterExpression] Creates a partial index based on the given filter object (MongoDB 3.2 or higher) + * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + * @example + * const collection = client.db('foo').collection('bar'); + * + * await collection.createIndex({ a: 1, b: -1 }); + * + * // Alternate syntax for { c: 1, d: -1 } that ensures order of indexes + * await collection.createIndex([ [c, 1], [d, -1] ]); + * + * // Equivalent to { e: 1 } + * await collection.createIndex('e'); + * + * // Equivalent to { f: 1, g: 1 } + * await collection.createIndex(['f', 'g']) + * + * // Equivalent to { h: 1, i: -1 } + * await collection.createIndex([ { h: 1 }, { i: -1 } ]); + * + * // Equivalent to { j: 1, k: -1, l: 2d } + * await collection.createIndex(['j', ['k', -1], { l: '2d' }]) + */ +Collection.prototype.createIndex = function(fieldOrSpec, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const createIndexOperation = new CreateIndexOperation( + this.s.db, + this.collectionName, + fieldOrSpec, + options + ); + + return executeOperation(this.s.topology, createIndexOperation, callback); +}; + +/** + * @typedef {object} Collection~IndexDefinition + * @description A definition for an index. Used by the createIndex command. + * @see https://docs.mongodb.com/manual/reference/command/createIndexes/ + */ + +/** + * Creates multiple indexes in the collection, this method is only supported for + * MongoDB 2.6 or higher. Earlier version of MongoDB will throw a command not supported + * error. + * + * **Note**: Unlike {@link Collection#createIndex createIndex}, this function takes in raw index specifications. + * Index specifications are defined {@link http://docs.mongodb.org/manual/reference/command/createIndexes/ here}. + * + * @method + * @param {Collection~IndexDefinition[]} indexSpecs An array of index specifications to be created + * @param {Object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + * @example + * const collection = client.db('foo').collection('bar'); + * await collection.createIndexes([ + * // Simple index on field fizz + * { + * key: { fizz: 1 }, + * } + * // wildcard index + * { + * key: { '$**': 1 } + * }, + * // named index on darmok and jalad + * { + * key: { darmok: 1, jalad: -1 } + * name: 'tanagra' + * } + * ]); + */ +Collection.prototype.createIndexes = function(indexSpecs, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + + options = options ? Object.assign({}, options) : {}; + if (typeof options.maxTimeMS !== 'number') delete options.maxTimeMS; + + const createIndexesOperation = new CreateIndexesOperation(this, indexSpecs, options); + + return executeOperation(this.s.topology, createIndexesOperation, callback); +}; + +/** + * Drops an index from this collection. + * @method + * @param {string} indexName Name of the index to drop. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query. + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.dropIndex = function(indexName, options, callback) { + const args = Array.prototype.slice.call(arguments, 1); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + + options = args.length ? args.shift() || {} : {}; + // Run only against primary + options.readPreference = ReadPreference.PRIMARY; + + const dropIndexOperation = new DropIndexOperation(this, indexName, options); + + return executeOperation(this.s.topology, dropIndexOperation, callback); +}; + +/** + * Drops all indexes from this collection. + * @method + * @param {Object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query. + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.dropIndexes = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options ? Object.assign({}, options) : {}; + + if (typeof options.maxTimeMS !== 'number') delete options.maxTimeMS; + + const dropIndexesOperation = new DropIndexesOperation(this, options); + + return executeOperation(this.s.topology, dropIndexesOperation, callback); +}; + +/** + * Drops all indexes from this collection. + * @method + * @deprecated use dropIndexes + * @param {Collection~resultCallback} callback The command result callback + * @return {Promise} returns Promise if no [callback] passed + */ +Collection.prototype.dropAllIndexes = deprecate( + Collection.prototype.dropIndexes, + 'collection.dropAllIndexes is deprecated. Use dropIndexes instead.' +); + +/** + * Reindex all indexes on the collection + * Warning: reIndex is a blocking operation (indexes are rebuilt in the foreground) and will be slow for large collections. + * @method + * @param {Object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.reIndex = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const reIndexOperation = new ReIndexOperation(this, options); + + return executeOperation(this.s.topology, reIndexOperation, callback); +}; + +/** + * Get the list of all indexes information for the collection. + * + * @method + * @param {object} [options] Optional settings. + * @param {number} [options.batchSize=1000] The batchSize for the returned command cursor or if pre 2.8 the systems batch collection + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {ClientSession} [options.session] optional session to use for this operation + * @return {CommandCursor} + */ +Collection.prototype.listIndexes = function(options) { + const cursor = new CommandCursor( + this.s.topology, + new ListIndexesOperation(this, options), + options + ); + + return cursor; +}; + +/** + * Ensures that an index exists, if it does not it creates it + * @method + * @deprecated use createIndexes instead + * @param {(string|object)} fieldOrSpec Defines the index. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.unique=false] Creates an unique index. + * @param {boolean} [options.sparse=false] Creates a sparse index. + * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. + * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value + * @param {number} [options.min] For geospatial indexes set the lower bound for the co-ordinates. + * @param {number} [options.max] For geospatial indexes set the high bound for the co-ordinates. + * @param {number} [options.v] Specify the format version of the indexes. + * @param {number} [options.expireAfterSeconds] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) + * @param {number} [options.name] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) + * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.ensureIndex = deprecate(function(fieldOrSpec, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeLegacyOperation(this.s.topology, ensureIndex, [ + this, + fieldOrSpec, + options, + callback + ]); +}, 'collection.ensureIndex is deprecated. Use createIndexes instead.'); + +/** + * Checks if one or more indexes exist on the collection, fails on first non-existing index + * @method + * @param {(string|array)} indexes One or more index names to check. + * @param {Object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.indexExists = function(indexes, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const indexExistsOperation = new IndexExistsOperation(this, indexes, options); + + return executeOperation(this.s.topology, indexExistsOperation, callback); +}; + +/** + * Retrieves this collections index info. + * @method + * @param {object} [options] Optional settings. + * @param {boolean} [options.full=false] Returns the full raw index information. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.indexInformation = function(options, callback) { + const args = Array.prototype.slice.call(arguments, 0); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + options = args.length ? args.shift() || {} : {}; + + const indexInformationOperation = new IndexInformationOperation( + this.s.db, + this.collectionName, + options + ); + + return executeOperation(this.s.topology, indexInformationOperation, callback); +}; + +/** + * The callback format for results + * @callback Collection~countCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {number} result The count of documents that matched the query. + */ + +/** + * An estimated count of matching documents in the db to a query. + * + * **NOTE:** This method has been deprecated, since it does not provide an accurate count of the documents + * in a collection. To obtain an accurate count of documents in the collection, use {@link Collection#countDocuments countDocuments}. + * To obtain an estimated count of all documents in the collection, use {@link Collection#estimatedDocumentCount estimatedDocumentCount}. + * + * @method + * @param {object} [query={}] The query for the count. + * @param {object} [options] Optional settings. + * @param {boolean} [options.limit] The limit of documents to count. + * @param {boolean} [options.skip] The number of documents to skip for the count. + * @param {string} [options.hint] An index name hint for the query. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~countCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + * @deprecated use {@link Collection#countDocuments countDocuments} or {@link Collection#estimatedDocumentCount estimatedDocumentCount} instead + */ +Collection.prototype.count = deprecate(function(query, options, callback) { + const args = Array.prototype.slice.call(arguments, 0); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + query = args.length ? args.shift() || {} : {}; + options = args.length ? args.shift() || {} : {}; + + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeOperation( + this.s.topology, + new EstimatedDocumentCountOperation(this, query, options), + callback + ); +}, 'collection.count is deprecated, and will be removed in a future version.' + + ' Use Collection.countDocuments or Collection.estimatedDocumentCount instead'); + +/** + * Gets an estimate of the count of documents in a collection using collection metadata. + * + * @method + * @param {object} [options] Optional settings. + * @param {number} [options.maxTimeMS] The maximum amount of time to allow the operation to run. + * @param {Collection~countCallback} [callback] The command result callback. + * @return {Promise} returns Promise if no callback passed. + */ +Collection.prototype.estimatedDocumentCount = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const estimatedDocumentCountOperation = new EstimatedDocumentCountOperation(this, options); + + return executeOperation(this.s.topology, estimatedDocumentCountOperation, callback); +}; + +/** + * Gets the number of documents matching the filter. + * For a fast count of the total documents in a collection see {@link Collection#estimatedDocumentCount estimatedDocumentCount}. + * **Note**: When migrating from {@link Collection#count count} to {@link Collection#countDocuments countDocuments} + * the following query operators must be replaced: + * + * | Operator | Replacement | + * | -------- | ----------- | + * | `$where` | [`$expr`][1] | + * | `$near` | [`$geoWithin`][2] with [`$center`][3] | + * | `$nearSphere` | [`$geoWithin`][2] with [`$centerSphere`][4] | + * + * [1]: https://docs.mongodb.com/manual/reference/operator/query/expr/ + * [2]: https://docs.mongodb.com/manual/reference/operator/query/geoWithin/ + * [3]: https://docs.mongodb.com/manual/reference/operator/query/center/#op._S_center + * [4]: https://docs.mongodb.com/manual/reference/operator/query/centerSphere/#op._S_centerSphere + * + * @param {object} [query] the query for the count + * @param {object} [options] Optional settings. + * @param {object} [options.collation] Specifies a collation. + * @param {string|object} [options.hint] The index to use. + * @param {number} [options.limit] The maximum number of document to count. + * @param {number} [options.maxTimeMS] The maximum amount of time to allow the operation to run. + * @param {number} [options.skip] The number of documents to skip before counting. + * @param {Collection~countCallback} [callback] The command result callback. + * @return {Promise} returns Promise if no callback passed. + * @see https://docs.mongodb.com/manual/reference/operator/query/expr/ + * @see https://docs.mongodb.com/manual/reference/operator/query/geoWithin/ + * @see https://docs.mongodb.com/manual/reference/operator/query/center/#op._S_center + * @see https://docs.mongodb.com/manual/reference/operator/query/centerSphere/#op._S_centerSphere + */ + +Collection.prototype.countDocuments = function(query, options, callback) { + const args = Array.prototype.slice.call(arguments, 0); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + query = args.length ? args.shift() || {} : {}; + options = args.length ? args.shift() || {} : {}; + + const countDocumentsOperation = new CountDocumentsOperation(this, query, options); + + return executeOperation(this.s.topology, countDocumentsOperation, callback); +}; + +/** + * The distinct command returns a list of distinct values for the given key across a collection. + * @method + * @param {string} key Field of the document to find distinct values for. + * @param {object} query The query for filtering the set of documents to which we apply the distinct filter. + * @param {object} [options] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.distinct = function(key, query, options, callback) { + const args = Array.prototype.slice.call(arguments, 1); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + const queryOption = args.length ? args.shift() || {} : {}; + const optionsOption = args.length ? args.shift() || {} : {}; + + const distinctOperation = new DistinctOperation(this, key, queryOption, optionsOption); + + return executeOperation(this.s.topology, distinctOperation, callback); +}; + +/** + * Retrieve all the indexes on the collection. + * @method + * @param {Object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.indexes = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const indexesOperation = new IndexesOperation(this, options); + + return executeOperation(this.s.topology, indexesOperation, callback); +}; + +/** + * Get all the collection statistics. + * + * @method + * @param {object} [options] Optional settings. + * @param {number} [options.scale] Divide the returned sizes by scale value. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The collection result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.stats = function(options, callback) { + const args = Array.prototype.slice.call(arguments, 0); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + options = args.length ? args.shift() || {} : {}; + + const statsOperation = new StatsOperation(this, options); + + return executeOperation(this.s.topology, statsOperation, callback); +}; + +/** + * @typedef {Object} Collection~findAndModifyWriteOpResult + * @property {object} value Document returned from the `findAndModify` command. If no documents were found, `value` will be `null` by default (`returnOriginal: true`), even if a document was upserted; if `returnOriginal` was false, the upserted document will be returned in that case. + * @property {object} lastErrorObject The raw lastErrorObject returned from the command. See {@link https://docs.mongodb.com/manual/reference/command/findAndModify/index.html#lasterrorobject|findAndModify command documentation}. + * @property {Number} ok Is 1 if the command executed correctly. + */ + +/** + * The callback format for inserts + * @callback Collection~findAndModifyCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection~findAndModifyWriteOpResult} result The result object if the command was executed successfully. + */ + +/** + * Find a document and delete it in one atomic operation. Requires a write lock for the duration of the operation. + * + * @method + * @param {object} filter The Filter used to select the document to remove + * @param {object} [options] Optional settings. + * @param {object} [options.projection] Limits the fields to return for all matching documents. + * @param {object} [options.sort] Determines which document the operation modifies if the query selects multiple documents. + * @param {number} [options.maxTimeMS] The maximum amount of time to allow the query to run. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~findAndModifyCallback} [callback] The collection result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.findOneAndDelete = function(filter, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + // Basic validation + if (filter == null || typeof filter !== 'object') + throw toError('filter parameter must be an object'); + + const findOneAndDeleteOperation = new FindOneAndDeleteOperation(this, filter, options); + + return executeOperation(this.s.topology, findOneAndDeleteOperation, callback); +}; + +/** + * Find a document and replace it in one atomic operation. Requires a write lock for the duration of the operation. + * + * @method + * @param {object} filter The Filter used to select the document to replace + * @param {object} replacement The Document that replaces the matching document + * @param {object} [options] Optional settings. + * @param {object} [options.projection] Limits the fields to return for all matching documents. + * @param {object} [options.sort] Determines which document the operation modifies if the query selects multiple documents. + * @param {number} [options.maxTimeMS] The maximum amount of time to allow the query to run. + * @param {boolean} [options.upsert=false] Upsert the document if it does not exist. + * @param {boolean} [options.returnOriginal=true] When false, returns the updated document rather than the original. The default is true. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~findAndModifyCallback} [callback] The collection result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.findOneAndReplace = function(filter, replacement, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + // Basic validation + if (filter == null || typeof filter !== 'object') + throw toError('filter parameter must be an object'); + if (replacement == null || typeof replacement !== 'object') + throw toError('replacement parameter must be an object'); + + // Check that there are no atomic operators + const keys = Object.keys(replacement); + + if (keys[0] && keys[0][0] === '$') { + throw toError('The replacement document must not contain atomic operators.'); + } + + const findOneAndReplaceOperation = new FindOneAndReplaceOperation( + this, + filter, + replacement, + options + ); + + return executeOperation(this.s.topology, findOneAndReplaceOperation, callback); +}; + +/** + * Find a document and update it in one atomic operation. Requires a write lock for the duration of the operation. + * + * @method + * @param {object} filter The Filter used to select the document to update + * @param {object} update Update operations to be performed on the document + * @param {object} [options] Optional settings. + * @param {object} [options.projection] Limits the fields to return for all matching documents. + * @param {object} [options.sort] Determines which document the operation modifies if the query selects multiple documents. + * @param {number} [options.maxTimeMS] The maximum amount of time to allow the query to run. + * @param {boolean} [options.upsert=false] Upsert the document if it does not exist. + * @param {boolean} [options.returnOriginal=true] When false, returns the updated document rather than the original. The default is true. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Array} [options.arrayFilters] optional list of array filters referenced in filtered positional operators + * @param {Collection~findAndModifyCallback} [callback] The collection result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.findOneAndUpdate = function(filter, update, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + // Basic validation + if (filter == null || typeof filter !== 'object') + throw toError('filter parameter must be an object'); + if (update == null || typeof update !== 'object') + throw toError('update parameter must be an object'); + + const err = checkForAtomicOperators(update); + if (err) { + if (typeof callback === 'function') return callback(err); + return this.s.promiseLibrary.reject(err); + } + + const findOneAndUpdateOperation = new FindOneAndUpdateOperation(this, filter, update, options); + + return executeOperation(this.s.topology, findOneAndUpdateOperation, callback); +}; + +/** + * Find and update a document. + * @method + * @param {object} query Query object to locate the object to modify. + * @param {array} sort If multiple docs match, choose the first one in the specified sort order as the object to manipulate. + * @param {object} doc The fields/vals to be updated. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.remove=false] Set to true to remove the object before returning. + * @param {boolean} [options.upsert=false] Perform an upsert operation. + * @param {boolean} [options.new=false] Set to true if you want to return the modified object rather than the original. Ignored for remove. + * @param {object} [options.projection] Object containing the field projection for the result returned from the operation. + * @param {object} [options.fields] **Deprecated** Use `options.projection` instead + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Array} [options.arrayFilters] optional list of array filters referenced in filtered positional operators + * @param {Collection~findAndModifyCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + * @deprecated use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead + */ +Collection.prototype.findAndModify = deprecate( + _findAndModify, + 'collection.findAndModify is deprecated. Use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead.' +); + +/** + * @ignore + */ + +Collection.prototype._findAndModify = _findAndModify; + +function _findAndModify(query, sort, doc, options, callback) { + const args = Array.prototype.slice.call(arguments, 1); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + sort = args.length ? args.shift() || [] : []; + doc = args.length ? args.shift() : null; + options = args.length ? args.shift() || {} : {}; + + // Clone options + options = Object.assign({}, options); + // Force read preference primary + options.readPreference = ReadPreference.PRIMARY; + + return executeOperation( + this.s.topology, + new FindAndModifyOperation(this, query, sort, doc, options), + callback + ); +} + +/** + * Find and remove a document. + * @method + * @param {object} query Query object to locate the object to modify. + * @param {array} sort If multiple docs match, choose the first one in the specified sort order as the object to manipulate. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + * @deprecated use findOneAndDelete instead + */ +Collection.prototype.findAndRemove = deprecate(function(query, sort, options, callback) { + const args = Array.prototype.slice.call(arguments, 1); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + sort = args.length ? args.shift() || [] : []; + options = args.length ? args.shift() || {} : {}; + + // Add the remove option + options.remove = true; + + return executeOperation( + this.s.topology, + new FindAndModifyOperation(this, query, sort, null, options), + callback + ); +}, 'collection.findAndRemove is deprecated. Use findOneAndDelete instead.'); + +/** + * Execute an aggregation framework pipeline against the collection, needs MongoDB >= 2.2 + * @method + * @param {object} [pipeline=[]] Array containing all the aggregation framework commands for the execution. + * @param {object} [options] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {object} [options.cursor] Return the query as cursor, on 2.6 > it returns as a real cursor on pre 2.6 it returns as an emulated cursor. + * @param {number} [options.cursor.batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. + * @param {boolean} [options.explain=false] Explain returns the aggregation execution plan (requires mongodb 2.6 >). + * @param {boolean} [options.allowDiskUse=false] allowDiskUse lets the server know if it can use disk to store temporary results for the aggregation (requires mongodb 2.6 >). + * @param {number} [options.maxTimeMS] maxTimeMS specifies a cumulative time limit in milliseconds for processing operations on the cursor. MongoDB interrupts the operation at the earliest following interrupt point. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. + * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution. + * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. + * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. + * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). + * @param {string} [options.comment] Add a comment to an aggregation command + * @param {string|object} [options.hint] Add an index selection hint to an aggregation command + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~aggregationCallback} callback The command result callback + * @return {(null|AggregationCursor)} + */ +Collection.prototype.aggregate = function(pipeline, options, callback) { + if (Array.isArray(pipeline)) { + // Set up callback if one is provided + if (typeof options === 'function') { + callback = options; + options = {}; + } + + // If we have no options or callback we are doing + // a cursor based aggregation + if (options == null && callback == null) { + options = {}; + } + } else { + // Aggregation pipeline passed as arguments on the method + const args = Array.prototype.slice.call(arguments, 0); + // Get the callback + callback = args.pop(); + // Get the possible options object + const opts = args[args.length - 1]; + // If it contains any of the admissible options pop it of the args + options = + opts && + (opts.readPreference || + opts.explain || + opts.cursor || + opts.out || + opts.maxTimeMS || + opts.hint || + opts.allowDiskUse) + ? args.pop() + : {}; + // Left over arguments is the pipeline + pipeline = args; + } + + const cursor = new AggregationCursor( + this.s.topology, + new AggregateOperation(this, pipeline, options), + options + ); + + // TODO: remove this when NODE-2074 is resolved + if (typeof callback === 'function') { + callback(null, cursor); + return; + } + + return cursor; +}; + +/** + * Create a new Change Stream, watching for new changes (insertions, updates, replacements, deletions, and invalidations) in this collection. + * @method + * @since 3.0.0 + * @param {Array} [pipeline] An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents. + * @param {object} [options] Optional settings + * @param {string} [options.fullDocument='default'] Allowed values: ‘default’, ‘updateLookup’. When set to ‘updateLookup’, the change stream will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred. + * @param {object} [options.resumeAfter] Specifies the logical starting point for the new change stream. This should be the _id field from a previously returned change stream document. + * @param {number} [options.maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a change stream query + * @param {number} [options.batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. + * @param {object} [options.collation] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. + * @param {ReadPreference} [options.readPreference] The read preference. Defaults to the read preference of the database or collection. See {@link https://docs.mongodb.com/manual/reference/read-preference|read preference documentation}. + * @param {Timestamp} [options.startAtOperationTime] receive change events that occur after the specified timestamp + * @param {ClientSession} [options.session] optional session to use for this operation + * @return {ChangeStream} a ChangeStream instance. + */ +Collection.prototype.watch = function(pipeline, options) { + pipeline = pipeline || []; + options = options || {}; + + // Allow optionally not specifying a pipeline + if (!Array.isArray(pipeline)) { + options = pipeline; + pipeline = []; + } + + return new ChangeStream(this, pipeline, options); +}; + +/** + * The callback format for results + * @callback Collection~parallelCollectionScanCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Cursor[]} cursors A list of cursors returned allowing for parallel reading of collection. + */ + +/** + * Return N number of parallel cursors for a collection allowing parallel reading of entire collection. There are + * no ordering guarantees for returned results. + * @method + * @param {object} [options] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {number} [options.batchSize=1000] Set the batchSize for the getMoreCommand when iterating over the query results. + * @param {number} [options.numCursors=1] The maximum number of parallel command cursors to return (the number of returned cursors will be in the range 1:numCursors) + * @param {boolean} [options.raw=false] Return all BSON documents as Raw Buffer documents. + * @param {Collection~parallelCollectionScanCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.parallelCollectionScan = deprecate(function(options, callback) { + if (typeof options === 'function') (callback = options), (options = { numCursors: 1 }); + // Set number of cursors to 1 + options.numCursors = options.numCursors || 1; + options.batchSize = options.batchSize || 1000; + + options = Object.assign({}, options); + // Ensure we have the right read preference inheritance + options.readPreference = resolveReadPreference(this, options); + + // Add a promiseLibrary + options.promiseLibrary = this.s.promiseLibrary; + + if (options.session) { + options.session = undefined; + } + + return executeLegacyOperation( + this.s.topology, + parallelCollectionScan, + [this, options, callback], + { skipSessions: true } + ); +}, 'parallelCollectionScan is deprecated in MongoDB v4.1'); + +/** + * Execute a geo search using a geo haystack index on a collection. + * + * @method + * @param {number} x Point to search on the x axis, ensure the indexes are ordered in the same order. + * @param {number} y Point to search on the y axis, ensure the indexes are ordered in the same order. + * @param {object} [options] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {number} [options.maxDistance] Include results up to maxDistance from the point. + * @param {object} [options.search] Filter the results by a query. + * @param {number} [options.limit=false] Max number of results to return. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.geoHaystackSearch = function(x, y, options, callback) { + const args = Array.prototype.slice.call(arguments, 2); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + options = args.length ? args.shift() || {} : {}; + + const geoHaystackSearchOperation = new GeoHaystackSearchOperation(this, x, y, options); + + return executeOperation(this.s.topology, geoHaystackSearchOperation, callback); +}; + +/** + * Run a group command across a collection + * + * @method + * @param {(object|array|function|code)} keys An object, array or function expressing the keys to group by. + * @param {object} condition An optional condition that must be true for a row to be considered. + * @param {object} initial Initial value of the aggregation counter object. + * @param {(function|Code)} reduce The reduce function aggregates (reduces) the objects iterated + * @param {(function|Code)} finalize An optional function to be run on each item in the result set just before the item is returned. + * @param {boolean} command Specify if you wish to run using the internal group command or using eval, default is true. + * @param {object} [options] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + * @deprecated MongoDB 3.6 or higher no longer supports the group command. We recommend rewriting using the aggregation framework. + */ +Collection.prototype.group = deprecate(function( + keys, + condition, + initial, + reduce, + finalize, + command, + options, + callback +) { + const args = Array.prototype.slice.call(arguments, 3); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + reduce = args.length ? args.shift() : null; + finalize = args.length ? args.shift() : null; + command = args.length ? args.shift() : null; + options = args.length ? args.shift() || {} : {}; + + // Make sure we are backward compatible + if (!(typeof finalize === 'function')) { + command = finalize; + finalize = null; + } + + if ( + !Array.isArray(keys) && + keys instanceof Object && + typeof keys !== 'function' && + !(keys._bsontype === 'Code') + ) { + keys = Object.keys(keys); + } + + if (typeof reduce === 'function') { + reduce = reduce.toString(); + } + + if (typeof finalize === 'function') { + finalize = finalize.toString(); + } + + // Set up the command as default + command = command == null ? true : command; + + return executeLegacyOperation(this.s.topology, group, [ + this, + keys, + condition, + initial, + reduce, + finalize, + command, + options, + callback + ]); +}, +'MongoDB 3.6 or higher no longer supports the group command. We recommend rewriting using the aggregation framework.'); + +/** + * Run Map Reduce across a collection. Be aware that the inline option for out will return an array of results not a collection. + * + * @method + * @param {(function|string)} map The mapping function. + * @param {(function|string)} reduce The reduce function. + * @param {object} [options] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {object} [options.out] Sets the output target for the map reduce job. *{inline:1} | {replace:'collectionName'} | {merge:'collectionName'} | {reduce:'collectionName'}* + * @param {object} [options.query] Query filter object. + * @param {object} [options.sort] Sorts the input objects using this key. Useful for optimization, like sorting by the emit key for fewer reduces. + * @param {number} [options.limit] Number of objects to return from collection. + * @param {boolean} [options.keeptemp=false] Keep temporary data. + * @param {(function|string)} [options.finalize] Finalize function. + * @param {object} [options.scope] Can pass in variables that can be access from map/reduce/finalize. + * @param {boolean} [options.jsMode=false] It is possible to make the execution stay in JS. Provided in MongoDB > 2.0.X. + * @param {boolean} [options.verbose=false] Provide statistics on job execution time. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The command result callback + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.mapReduce = function(map, reduce, options, callback) { + if ('function' === typeof options) (callback = options), (options = {}); + // Out must allways be defined (make sure we don't break weirdly on pre 1.8+ servers) + if (null == options.out) { + throw new Error( + 'the out option parameter must be defined, see mongodb docs for possible values' + ); + } + + if ('function' === typeof map) { + map = map.toString(); + } + + if ('function' === typeof reduce) { + reduce = reduce.toString(); + } + + if ('function' === typeof options.finalize) { + options.finalize = options.finalize.toString(); + } + const mapReduceOperation = new MapReduceOperation(this, map, reduce, options); + + return executeOperation(this.s.topology, mapReduceOperation, callback); +}; + +/** + * Initiate an Out of order batch write operation. All operations will be buffered into insert/update/remove commands executed out of order. + * + * @method + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session] optional session to use for this operation + * @return {UnorderedBulkOperation} + */ +Collection.prototype.initializeUnorderedBulkOp = function(options) { + options = options || {}; + // Give function's options precedence over session options. + if (options.ignoreUndefined == null) { + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + options.promiseLibrary = this.s.promiseLibrary; + return unordered(this.s.topology, this, options); +}; + +/** + * Initiate an In order bulk write operation. Operations will be serially executed in the order they are added, creating a new operation for each switch in types. + * + * @method + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {OrderedBulkOperation} callback The command result callback + * @return {null} + */ +Collection.prototype.initializeOrderedBulkOp = function(options) { + options = options || {}; + // Give function's options precedence over session's options. + if (options.ignoreUndefined == null) { + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + options.promiseLibrary = this.s.promiseLibrary; + return ordered(this.s.topology, this, options); +}; + +/** + * Return the db logger + * @method + * @return {Logger} return the db logger + * @ignore + */ +Collection.prototype.getLogger = function() { + return this.s.db.s.logger; +}; + +module.exports = Collection; diff --git a/scripts/2.5/node_modules/mongodb/lib/command_cursor.js b/scripts/2.5/node_modules/mongodb/lib/command_cursor.js new file mode 100644 index 00000000..cd0f9d7a --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/command_cursor.js @@ -0,0 +1,269 @@ +'use strict'; + +const ReadPreference = require('./core').ReadPreference; +const MongoError = require('./core').MongoError; +const Cursor = require('./cursor'); +const CursorState = require('./core/cursor').CursorState; + +/** + * @fileOverview The **CommandCursor** class is an internal class that embodies a + * generalized cursor based on a MongoDB command allowing for iteration over the + * results returned. It supports one by one document iteration, conversion to an + * array or can be iterated as a Node 0.10.X or higher stream + * + * **CommandCursor Cannot directly be instantiated** + * @example + * const MongoClient = require('mongodb').MongoClient; + * const test = require('assert'); + * // Connection url + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, client) { + * // Create a collection we want to drop later + * const col = client.db(dbName).collection('listCollectionsExample1'); + * // Insert a bunch of documents + * col.insert([{a:1, b:1} + * , {a:2, b:2}, {a:3, b:3} + * , {a:4, b:4}], {w:1}, function(err, result) { + * test.equal(null, err); + * // List the database collections available + * db.listCollections().toArray(function(err, items) { + * test.equal(null, err); + * client.close(); + * }); + * }); + * }); + */ + +/** + * Namespace provided by the browser. + * @external Readable + */ + +/** + * Creates a new Command Cursor instance (INTERNAL TYPE, do not instantiate directly) + * @class CommandCursor + * @extends external:Readable + * @fires CommandCursor#data + * @fires CommandCursor#end + * @fires CommandCursor#close + * @fires CommandCursor#readable + * @return {CommandCursor} an CommandCursor instance. + */ +class CommandCursor extends Cursor { + constructor(topology, ns, cmd, options) { + super(topology, ns, cmd, options); + } + + /** + * Set the ReadPreference for the cursor. + * @method + * @param {(string|ReadPreference)} readPreference The new read preference for the cursor. + * @throws {MongoError} + * @return {Cursor} + */ + setReadPreference(readPreference) { + if (this.s.state === CursorState.CLOSED || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + if (this.s.state !== CursorState.INIT) { + throw MongoError.create({ + message: 'cannot change cursor readPreference after cursor has been accessed', + driver: true + }); + } + + if (readPreference instanceof ReadPreference) { + this.options.readPreference = readPreference; + } else if (typeof readPreference === 'string') { + this.options.readPreference = new ReadPreference(readPreference); + } else { + throw new TypeError('Invalid read preference: ' + readPreference); + } + + return this; + } + + /** + * Set the batch size for the cursor. + * @method + * @param {number} value The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/find/|find command documentation}. + * @throws {MongoError} + * @return {CommandCursor} + */ + batchSize(value) { + if (this.s.state === CursorState.CLOSED || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + if (typeof value !== 'number') { + throw MongoError.create({ message: 'batchSize requires an integer', driver: true }); + } + + if (this.cmd.cursor) { + this.cmd.cursor.batchSize = value; + } + + this.setCursorBatchSize(value); + return this; + } + + /** + * Add a maxTimeMS stage to the aggregation pipeline + * @method + * @param {number} value The state maxTimeMS value. + * @return {CommandCursor} + */ + maxTimeMS(value) { + if (this.topology.lastIsMaster().minWireVersion > 2) { + this.cmd.maxTimeMS = value; + } + + return this; + } + + /** + * Return the cursor logger + * @method + * @return {Logger} return the cursor logger + * @ignore + */ + getLogger() { + return this.logger; + } +} + +// aliases +CommandCursor.prototype.get = CommandCursor.prototype.toArray; + +/** + * CommandCursor stream data event, fired for each document in the cursor. + * + * @event CommandCursor#data + * @type {object} + */ + +/** + * CommandCursor stream end event + * + * @event CommandCursor#end + * @type {null} + */ + +/** + * CommandCursor stream close event + * + * @event CommandCursor#close + * @type {null} + */ + +/** + * CommandCursor stream readable event + * + * @event CommandCursor#readable + * @type {null} + */ + +/** + * Get the next available document from the cursor, returns null if no more documents are available. + * @function CommandCursor.prototype.next + * @param {CommandCursor~resultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ + +/** + * Check if there is any document still available in the cursor + * @function CommandCursor.prototype.hasNext + * @param {CommandCursor~resultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ + +/** + * The callback format for results + * @callback CommandCursor~toArrayResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {object[]} documents All the documents the satisfy the cursor. + */ + +/** + * Returns an array of documents. The caller is responsible for making sure that there + * is enough memory to store the results. Note that the array only contain partial + * results when this cursor had been previously accessed. + * @method CommandCursor.prototype.toArray + * @param {CommandCursor~toArrayResultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ + +/** + * The callback format for results + * @callback CommandCursor~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {(object|null)} result The result object if the command was executed successfully. + */ + +/** + * Iterates over all the documents for this cursor. As with **{cursor.toArray}**, + * not all of the elements will be iterated if this cursor had been previously accessed. + * In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike + * **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements + * at any given time if batch size is specified. Otherwise, the caller is responsible + * for making sure that the entire result can fit the memory. + * @method CommandCursor.prototype.each + * @param {CommandCursor~resultCallback} callback The result callback. + * @throws {MongoError} + * @return {null} + */ + +/** + * Close the cursor, sending a KillCursor command and emitting close. + * @method CommandCursor.prototype.close + * @param {CommandCursor~resultCallback} [callback] The result callback. + * @return {Promise} returns Promise if no callback passed + */ + +/** + * Is the cursor closed + * @method CommandCursor.prototype.isClosed + * @return {boolean} + */ + +/** + * Clone the cursor + * @function CommandCursor.prototype.clone + * @return {CommandCursor} + */ + +/** + * Resets the cursor + * @function CommandCursor.prototype.rewind + * @return {CommandCursor} + */ + +/** + * The callback format for the forEach iterator method + * @callback CommandCursor~iteratorCallback + * @param {Object} doc An emitted document for the iterator + */ + +/** + * The callback error format for the forEach iterator method + * @callback CommandCursor~endCallback + * @param {MongoError} error An error instance representing the error during the execution. + */ + +/* + * Iterates over all the documents for this cursor using the iterator, callback pattern. + * @method CommandCursor.prototype.forEach + * @param {CommandCursor~iteratorCallback} iterator The iteration callback. + * @param {CommandCursor~endCallback} callback The end callback. + * @throws {MongoError} + * @return {null} + */ + +module.exports = CommandCursor; diff --git a/scripts/2.5/node_modules/mongodb/lib/constants.js b/scripts/2.5/node_modules/mongodb/lib/constants.js new file mode 100644 index 00000000..d6cc68ad --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/constants.js @@ -0,0 +1,10 @@ +'use strict'; + +module.exports = { + SYSTEM_NAMESPACE_COLLECTION: 'system.namespaces', + SYSTEM_INDEX_COLLECTION: 'system.indexes', + SYSTEM_PROFILE_COLLECTION: 'system.profile', + SYSTEM_USER_COLLECTION: 'system.users', + SYSTEM_COMMAND_COLLECTION: '$cmd', + SYSTEM_JS_COLLECTION: 'system.js' +}; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/auth/auth_provider.js b/scripts/2.5/node_modules/mongodb/lib/core/auth/auth_provider.js new file mode 100644 index 00000000..7597b728 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/core/auth/auth_provider.js @@ -0,0 +1,158 @@ +'use strict'; + +const MongoError = require('../error').MongoError; + +/** + * Creates a new AuthProvider, which dictates how to authenticate for a given + * mechanism. + * @class + */ +class AuthProvider { + constructor(bson) { + this.bson = bson; + this.authStore = []; + } + + /** + * Authenticate + * @method + * @param {SendAuthCommand} sendAuthCommand Writes an auth command directly to a specific connection + * @param {Connection[]} connections Connections to authenticate using this authenticator + * @param {MongoCredentials} credentials Authentication credentials + * @param {authResultCallback} callback The callback to return the result from the authentication + */ + auth(sendAuthCommand, connections, credentials, callback) { + // Total connections + let count = connections.length; + + if (count === 0) { + callback(null, null); + return; + } + + // Valid connections + let numberOfValidConnections = 0; + let errorObject = null; + + const execute = connection => { + this._authenticateSingleConnection(sendAuthCommand, connection, credentials, (err, r) => { + // Adjust count + count = count - 1; + + // If we have an error + if (err) { + errorObject = new MongoError(err); + } else if (r && (r.$err || r.errmsg)) { + errorObject = new MongoError(r); + } else { + numberOfValidConnections = numberOfValidConnections + 1; + } + + // Still authenticating against other connections. + if (count !== 0) { + return; + } + + // We have authenticated all connections + if (numberOfValidConnections > 0) { + // Store the auth details + this.addCredentials(credentials); + // Return correct authentication + callback(null, true); + } else { + if (errorObject == null) { + errorObject = new MongoError(`failed to authenticate using ${credentials.mechanism}`); + } + callback(errorObject, false); + } + }); + }; + + const executeInNextTick = _connection => process.nextTick(() => execute(_connection)); + + // For each connection we need to authenticate + while (connections.length > 0) { + executeInNextTick(connections.shift()); + } + } + + /** + * Implementation of a single connection authenticating. Is meant to be overridden. + * Will error if called directly + * @ignore + */ + _authenticateSingleConnection(/*sendAuthCommand, connection, credentials, callback*/) { + throw new Error('_authenticateSingleConnection must be overridden'); + } + + /** + * Adds credentials to store only if it does not exist + * @param {MongoCredentials} credentials credentials to add to store + */ + addCredentials(credentials) { + const found = this.authStore.some(cred => cred.equals(credentials)); + + if (!found) { + this.authStore.push(credentials); + } + } + + /** + * Re authenticate pool + * @method + * @param {SendAuthCommand} sendAuthCommand Writes an auth command directly to a specific connection + * @param {Connection[]} connections Connections to authenticate using this authenticator + * @param {authResultCallback} callback The callback to return the result from the authentication + */ + reauthenticate(sendAuthCommand, connections, callback) { + const authStore = this.authStore.slice(0); + let count = authStore.length; + if (count === 0) { + return callback(null, null); + } + + for (let i = 0; i < authStore.length; i++) { + this.auth(sendAuthCommand, connections, authStore[i], function(err) { + count = count - 1; + if (count === 0) { + callback(err, null); + } + }); + } + } + + /** + * Remove credentials that have been previously stored in the auth provider + * @method + * @param {string} source Name of database we are removing authStore details about + * @return {object} + */ + logout(source) { + this.authStore = this.authStore.filter(credentials => credentials.source !== source); + } +} + +/** + * A function that writes authentication commands to a specific connection + * @callback SendAuthCommand + * @param {Connection} connection The connection to write to + * @param {Command} command A command with a toBin method that can be written to a connection + * @param {AuthWriteCallback} callback Callback called when command response is received + */ + +/** + * A callback for a specific auth command + * @callback AuthWriteCallback + * @param {Error} err If command failed, an error from the server + * @param {object} r The response from the server + */ + +/** + * This is a result from an authentication strategy + * + * @callback authResultCallback + * @param {error} error An error object. Set to null if no error present + * @param {boolean} result The result of the authentication process + */ + +module.exports = { AuthProvider }; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/auth/defaultAuthProviders.js b/scripts/2.5/node_modules/mongodb/lib/core/auth/defaultAuthProviders.js new file mode 100644 index 00000000..fc5f4c28 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/core/auth/defaultAuthProviders.js @@ -0,0 +1,29 @@ +'use strict'; + +const MongoCR = require('./mongocr'); +const X509 = require('./x509'); +const Plain = require('./plain'); +const GSSAPI = require('./gssapi'); +const SSPI = require('./sspi'); +const ScramSHA1 = require('./scram').ScramSHA1; +const ScramSHA256 = require('./scram').ScramSHA256; + +/** + * Returns the default authentication providers. + * + * @param {BSON} bson Bson definition + * @returns {Object} a mapping of auth names to auth types + */ +function defaultAuthProviders(bson) { + return { + mongocr: new MongoCR(bson), + x509: new X509(bson), + plain: new Plain(bson), + gssapi: new GSSAPI(bson), + sspi: new SSPI(bson), + 'scram-sha-1': new ScramSHA1(bson), + 'scram-sha-256': new ScramSHA256(bson) + }; +} + +module.exports = { defaultAuthProviders }; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/auth/gssapi.js b/scripts/2.5/node_modules/mongodb/lib/core/auth/gssapi.js new file mode 100644 index 00000000..936fb65a --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/core/auth/gssapi.js @@ -0,0 +1,241 @@ +'use strict'; + +const AuthProvider = require('./auth_provider').AuthProvider; +const retrieveKerberos = require('../utils').retrieveKerberos; +let kerberos; + +/** + * Creates a new GSSAPI authentication mechanism + * @class + * @extends AuthProvider + */ +class GSSAPI extends AuthProvider { + /** + * Implementation of authentication for a single connection + * @override + */ + _authenticateSingleConnection(sendAuthCommand, connection, credentials, callback) { + const source = credentials.source; + const username = credentials.username; + const password = credentials.password; + const mechanismProperties = credentials.mechanismProperties; + const gssapiServiceName = + mechanismProperties['gssapiservicename'] || + mechanismProperties['gssapiServiceName'] || + 'mongodb'; + + GSSAPIInitialize( + this, + kerberos.processes.MongoAuthProcess, + source, + username, + password, + source, + gssapiServiceName, + sendAuthCommand, + connection, + mechanismProperties, + callback + ); + } + + /** + * Authenticate + * @override + * @method + */ + auth(sendAuthCommand, connections, credentials, callback) { + if (kerberos == null) { + try { + kerberos = retrieveKerberos(); + } catch (e) { + return callback(e, null); + } + } + + super.auth(sendAuthCommand, connections, credentials, callback); + } +} + +// +// Initialize step +var GSSAPIInitialize = function( + self, + MongoAuthProcess, + db, + username, + password, + authdb, + gssapiServiceName, + sendAuthCommand, + connection, + options, + callback +) { + // Create authenticator + var mongo_auth_process = new MongoAuthProcess( + connection.host, + connection.port, + gssapiServiceName, + options + ); + + // Perform initialization + mongo_auth_process.init(username, password, function(err) { + if (err) return callback(err, false); + + // Perform the first step + mongo_auth_process.transition('', function(err, payload) { + if (err) return callback(err, false); + + // Call the next db step + MongoDBGSSAPIFirstStep( + self, + mongo_auth_process, + payload, + db, + username, + password, + authdb, + sendAuthCommand, + connection, + callback + ); + }); + }); +}; + +// +// Perform first step against mongodb +var MongoDBGSSAPIFirstStep = function( + self, + mongo_auth_process, + payload, + db, + username, + password, + authdb, + sendAuthCommand, + connection, + callback +) { + // Build the sasl start command + var command = { + saslStart: 1, + mechanism: 'GSSAPI', + payload: payload, + autoAuthorize: 1 + }; + + // Write the commmand on the connection + sendAuthCommand(connection, '$external.$cmd', command, (err, doc) => { + if (err) return callback(err, false); + // Execute mongodb transition + mongo_auth_process.transition(doc.payload, function(err, payload) { + if (err) return callback(err, false); + + // MongoDB API Second Step + MongoDBGSSAPISecondStep( + self, + mongo_auth_process, + payload, + doc, + db, + username, + password, + authdb, + sendAuthCommand, + connection, + callback + ); + }); + }); +}; + +// +// Perform first step against mongodb +var MongoDBGSSAPISecondStep = function( + self, + mongo_auth_process, + payload, + doc, + db, + username, + password, + authdb, + sendAuthCommand, + connection, + callback +) { + // Build Authentication command to send to MongoDB + var command = { + saslContinue: 1, + conversationId: doc.conversationId, + payload: payload + }; + + // Execute the command + // Write the commmand on the connection + sendAuthCommand(connection, '$external.$cmd', command, (err, doc) => { + if (err) return callback(err, false); + // Call next transition for kerberos + mongo_auth_process.transition(doc.payload, function(err, payload) { + if (err) return callback(err, false); + + // Call the last and third step + MongoDBGSSAPIThirdStep( + self, + mongo_auth_process, + payload, + doc, + db, + username, + password, + authdb, + sendAuthCommand, + connection, + callback + ); + }); + }); +}; + +var MongoDBGSSAPIThirdStep = function( + self, + mongo_auth_process, + payload, + doc, + db, + username, + password, + authdb, + sendAuthCommand, + connection, + callback +) { + // Build final command + var command = { + saslContinue: 1, + conversationId: doc.conversationId, + payload: payload + }; + + // Execute the command + sendAuthCommand(connection, '$external.$cmd', command, (err, r) => { + if (err) return callback(err, false); + mongo_auth_process.transition(null, function(err) { + if (err) return callback(err, null); + callback(null, r); + }); + }); +}; + +/** + * This is a result from a authentication strategy + * + * @callback authResultCallback + * @param {error} error An error object. Set to null if no error present + * @param {boolean} result The result of the authentication process + */ + +module.exports = GSSAPI; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/auth/mongo_credentials.js b/scripts/2.5/node_modules/mongodb/lib/core/auth/mongo_credentials.js new file mode 100644 index 00000000..13c00b14 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/core/auth/mongo_credentials.js @@ -0,0 +1,81 @@ +'use strict'; + +// Resolves the default auth mechanism according to +// https://github.com/mongodb/specifications/blob/master/source/auth/auth.rst +function getDefaultAuthMechanism(ismaster) { + if (ismaster) { + // If ismaster contains saslSupportedMechs, use scram-sha-256 + // if it is available, else scram-sha-1 + if (Array.isArray(ismaster.saslSupportedMechs)) { + return ismaster.saslSupportedMechs.indexOf('SCRAM-SHA-256') >= 0 + ? 'scram-sha-256' + : 'scram-sha-1'; + } + + // Fallback to legacy selection method. If wire version >= 3, use scram-sha-1 + if (ismaster.maxWireVersion >= 3) { + return 'scram-sha-1'; + } + } + + // Default for wireprotocol < 3 + return 'mongocr'; +} + +/** + * A representation of the credentials used by MongoDB + * @class + * @property {string} mechanism The method used to authenticate + * @property {string} [username] The username used for authentication + * @property {string} [password] The password used for authentication + * @property {string} [source] The database that the user should authenticate against + * @property {object} [mechanismProperties] Special properties used by some types of auth mechanisms + */ +class MongoCredentials { + /** + * Creates a new MongoCredentials object + * @param {object} [options] + * @param {string} [options.username] The username used for authentication + * @param {string} [options.password] The password used for authentication + * @param {string} [options.source] The database that the user should authenticate against + * @param {string} [options.mechanism] The method used to authenticate + * @param {object} [options.mechanismProperties] Special properties used by some types of auth mechanisms + */ + constructor(options) { + options = options || {}; + this.username = options.username; + this.password = options.password; + this.source = options.source || options.db; + this.mechanism = options.mechanism || 'default'; + this.mechanismProperties = options.mechanismProperties; + } + + /** + * Determines if two MongoCredentials objects are equivalent + * @param {MongoCredentials} other another MongoCredentials object + * @returns {boolean} true if the two objects are equal. + */ + equals(other) { + return ( + this.mechanism === other.mechanism && + this.username === other.username && + this.password === other.password && + this.source === other.source + ); + } + + /** + * If the authentication mechanism is set to "default", resolves the authMechanism + * based on the server version and server supported sasl mechanisms. + * + * @param {Object} [ismaster] An ismaster response from the server + */ + resolveAuthMechanism(ismaster) { + // If the mechanism is not "default", then it does not need to be resolved + if (this.mechanism.toLowerCase() === 'default') { + this.mechanism = getDefaultAuthMechanism(ismaster); + } + } +} + +module.exports = { MongoCredentials }; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/auth/mongocr.js b/scripts/2.5/node_modules/mongodb/lib/core/auth/mongocr.js new file mode 100644 index 00000000..be8fcb6b --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/core/auth/mongocr.js @@ -0,0 +1,51 @@ +'use strict'; + +const crypto = require('crypto'); +const AuthProvider = require('./auth_provider').AuthProvider; + +/** + * Creates a new MongoCR authentication mechanism + * + * @extends AuthProvider + */ +class MongoCR extends AuthProvider { + /** + * Implementation of authentication for a single connection + * @override + */ + _authenticateSingleConnection(sendAuthCommand, connection, credentials, callback) { + const username = credentials.username; + const password = credentials.password; + const source = credentials.source; + + sendAuthCommand(connection, `${source}.$cmd`, { getnonce: 1 }, (err, r) => { + let nonce = null; + let key = null; + + // Get nonce + if (err == null) { + nonce = r.nonce; + // Use node md5 generator + let md5 = crypto.createHash('md5'); + // Generate keys used for authentication + md5.update(username + ':mongo:' + password, 'utf8'); + const hash_password = md5.digest('hex'); + // Final key + md5 = crypto.createHash('md5'); + md5.update(nonce + username + hash_password, 'utf8'); + key = md5.digest('hex'); + } + + const authenticateCommand = { + authenticate: 1, + user: username, + nonce, + key + }; + + sendAuthCommand(connection, `${source}.$cmd`, authenticateCommand, callback); + }); + } +} + +module.exports = MongoCR; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/auth/plain.js b/scripts/2.5/node_modules/mongodb/lib/core/auth/plain.js new file mode 100644 index 00000000..240de758 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/core/auth/plain.js @@ -0,0 +1,35 @@ +'use strict'; + +const retrieveBSON = require('../connection/utils').retrieveBSON; +const AuthProvider = require('./auth_provider').AuthProvider; + +// TODO: can we get the Binary type from this.bson instead? +const BSON = retrieveBSON(); +const Binary = BSON.Binary; + +/** + * Creates a new Plain authentication mechanism + * + * @extends AuthProvider + */ +class Plain extends AuthProvider { + /** + * Implementation of authentication for a single connection + * @override + */ + _authenticateSingleConnection(sendAuthCommand, connection, credentials, callback) { + const username = credentials.username; + const password = credentials.password; + const payload = new Binary(`\x00${username}\x00${password}`); + const command = { + saslStart: 1, + mechanism: 'PLAIN', + payload: payload, + autoAuthorize: 1 + }; + + sendAuthCommand(connection, '$external.$cmd', command, callback); + } +} + +module.exports = Plain; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/auth/scram.js b/scripts/2.5/node_modules/mongodb/lib/core/auth/scram.js new file mode 100644 index 00000000..ac8853eb --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/core/auth/scram.js @@ -0,0 +1,293 @@ +'use strict'; + +const crypto = require('crypto'); +const Buffer = require('safe-buffer').Buffer; +const retrieveBSON = require('../connection/utils').retrieveBSON; +const MongoError = require('../error').MongoError; +const AuthProvider = require('./auth_provider').AuthProvider; + +const BSON = retrieveBSON(); +const Binary = BSON.Binary; + +let saslprep; +try { + saslprep = require('saslprep'); +} catch (e) { + // don't do anything; +} + +var parsePayload = function(payload) { + var dict = {}; + var parts = payload.split(','); + + for (var i = 0; i < parts.length; i++) { + var valueParts = parts[i].split('='); + dict[valueParts[0]] = valueParts[1]; + } + + return dict; +}; + +var passwordDigest = function(username, password) { + if (typeof username !== 'string') throw new MongoError('username must be a string'); + if (typeof password !== 'string') throw new MongoError('password must be a string'); + if (password.length === 0) throw new MongoError('password cannot be empty'); + // Use node md5 generator + var md5 = crypto.createHash('md5'); + // Generate keys used for authentication + md5.update(username + ':mongo:' + password, 'utf8'); + return md5.digest('hex'); +}; + +// XOR two buffers +function xor(a, b) { + if (!Buffer.isBuffer(a)) a = Buffer.from(a); + if (!Buffer.isBuffer(b)) b = Buffer.from(b); + const length = Math.max(a.length, b.length); + const res = []; + + for (let i = 0; i < length; i += 1) { + res.push(a[i] ^ b[i]); + } + + return Buffer.from(res).toString('base64'); +} + +function H(method, text) { + return crypto + .createHash(method) + .update(text) + .digest(); +} + +function HMAC(method, key, text) { + return crypto + .createHmac(method, key) + .update(text) + .digest(); +} + +var _hiCache = {}; +var _hiCacheCount = 0; +var _hiCachePurge = function() { + _hiCache = {}; + _hiCacheCount = 0; +}; + +const hiLengthMap = { + sha256: 32, + sha1: 20 +}; + +function HI(data, salt, iterations, cryptoMethod) { + // omit the work if already generated + const key = [data, salt.toString('base64'), iterations].join('_'); + if (_hiCache[key] !== undefined) { + return _hiCache[key]; + } + + // generate the salt + const saltedData = crypto.pbkdf2Sync( + data, + salt, + iterations, + hiLengthMap[cryptoMethod], + cryptoMethod + ); + + // cache a copy to speed up the next lookup, but prevent unbounded cache growth + if (_hiCacheCount >= 200) { + _hiCachePurge(); + } + + _hiCache[key] = saltedData; + _hiCacheCount += 1; + return saltedData; +} + +/** + * Creates a new ScramSHA authentication mechanism + * @class + * @extends AuthProvider + */ +class ScramSHA extends AuthProvider { + constructor(bson, cryptoMethod) { + super(bson); + this.cryptoMethod = cryptoMethod || 'sha1'; + } + + static _getError(err, r) { + if (err) { + return err; + } + + if (r.$err || r.errmsg) { + return new MongoError(r); + } + } + + /** + * @ignore + */ + _executeScram(sendAuthCommand, connection, credentials, nonce, callback) { + let username = credentials.username; + const password = credentials.password; + const db = credentials.source; + + const cryptoMethod = this.cryptoMethod; + let mechanism = 'SCRAM-SHA-1'; + let processedPassword; + + if (cryptoMethod === 'sha256') { + mechanism = 'SCRAM-SHA-256'; + + processedPassword = saslprep ? saslprep(password) : password; + } else { + try { + processedPassword = passwordDigest(username, password); + } catch (e) { + return callback(e); + } + } + + // Clean up the user + username = username.replace('=', '=3D').replace(',', '=2C'); + + // NOTE: This is done b/c Javascript uses UTF-16, but the server is hashing in UTF-8. + // Since the username is not sasl-prep-d, we need to do this here. + const firstBare = Buffer.concat([ + Buffer.from('n=', 'utf8'), + Buffer.from(username, 'utf8'), + Buffer.from(',r=', 'utf8'), + Buffer.from(nonce, 'utf8') + ]); + + // Build command structure + const saslStartCmd = { + saslStart: 1, + mechanism, + payload: new Binary(Buffer.concat([Buffer.from('n,,', 'utf8'), firstBare])), + autoAuthorize: 1 + }; + + // Write the commmand on the connection + sendAuthCommand(connection, `${db}.$cmd`, saslStartCmd, (err, r) => { + let tmpError = ScramSHA._getError(err, r); + if (tmpError) { + return callback(tmpError, null); + } + + const payload = Buffer.isBuffer(r.payload) ? new Binary(r.payload) : r.payload; + const dict = parsePayload(payload.value()); + const iterations = parseInt(dict.i, 10); + const salt = dict.s; + const rnonce = dict.r; + + // Set up start of proof + const withoutProof = `c=biws,r=${rnonce}`; + const saltedPassword = HI( + processedPassword, + Buffer.from(salt, 'base64'), + iterations, + cryptoMethod + ); + + if (iterations && iterations < 4096) { + const error = new MongoError(`Server returned an invalid iteration count ${iterations}`); + return callback(error, false); + } + + const clientKey = HMAC(cryptoMethod, saltedPassword, 'Client Key'); + const storedKey = H(cryptoMethod, clientKey); + const authMessage = [firstBare, payload.value().toString('base64'), withoutProof].join(','); + + const clientSignature = HMAC(cryptoMethod, storedKey, authMessage); + const clientProof = `p=${xor(clientKey, clientSignature)}`; + const clientFinal = [withoutProof, clientProof].join(','); + const saslContinueCmd = { + saslContinue: 1, + conversationId: r.conversationId, + payload: new Binary(Buffer.from(clientFinal)) + }; + + sendAuthCommand(connection, `${db}.$cmd`, saslContinueCmd, (err, r) => { + if (!r || r.done !== false) { + return callback(err, r); + } + + const retrySaslContinueCmd = { + saslContinue: 1, + conversationId: r.conversationId, + payload: Buffer.alloc(0) + }; + + sendAuthCommand(connection, `${db}.$cmd`, retrySaslContinueCmd, callback); + }); + }); + } + + /** + * Implementation of authentication for a single connection + * @override + */ + _authenticateSingleConnection(sendAuthCommand, connection, credentials, callback) { + // Create a random nonce + crypto.randomBytes(24, (err, buff) => { + if (err) { + return callback(err, null); + } + + return this._executeScram( + sendAuthCommand, + connection, + credentials, + buff.toString('base64'), + callback + ); + }); + } + + /** + * Authenticate + * @override + * @method + */ + auth(sendAuthCommand, connections, credentials, callback) { + this._checkSaslprep(); + super.auth(sendAuthCommand, connections, credentials, callback); + } + + _checkSaslprep() { + const cryptoMethod = this.cryptoMethod; + + if (cryptoMethod === 'sha256') { + if (!saslprep) { + console.warn('Warning: no saslprep library specified. Passwords will not be sanitized'); + } + } + } +} + +/** + * Creates a new ScramSHA1 authentication mechanism + * @class + * @extends ScramSHA + */ +class ScramSHA1 extends ScramSHA { + constructor(bson) { + super(bson, 'sha1'); + } +} + +/** + * Creates a new ScramSHA256 authentication mechanism + * @class + * @extends ScramSHA + */ +class ScramSHA256 extends ScramSHA { + constructor(bson) { + super(bson, 'sha256'); + } +} + +module.exports = { ScramSHA1, ScramSHA256 }; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/auth/sspi.js b/scripts/2.5/node_modules/mongodb/lib/core/auth/sspi.js new file mode 100644 index 00000000..8a3f5448 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/core/auth/sspi.js @@ -0,0 +1,131 @@ +'use strict'; + +const AuthProvider = require('./auth_provider').AuthProvider; +const retrieveKerberos = require('../utils').retrieveKerberos; +let kerberos; + +/** + * Creates a new SSPI authentication mechanism + * @class + * @extends AuthProvider + */ +class SSPI extends AuthProvider { + /** + * Implementation of authentication for a single connection + * @override + */ + _authenticateSingleConnection(sendAuthCommand, connection, credentials, callback) { + // TODO: Destructure this + const username = credentials.username; + const password = credentials.password; + const mechanismProperties = credentials.mechanismProperties; + const gssapiServiceName = + mechanismProperties['gssapiservicename'] || + mechanismProperties['gssapiServiceName'] || + 'mongodb'; + + SSIPAuthenticate( + this, + kerberos.processes.MongoAuthProcess, + username, + password, + gssapiServiceName, + sendAuthCommand, + connection, + mechanismProperties, + callback + ); + } + + /** + * Authenticate + * @override + * @method + */ + auth(sendAuthCommand, connections, credentials, callback) { + if (kerberos == null) { + try { + kerberos = retrieveKerberos(); + } catch (e) { + return callback(e, null); + } + } + + super.auth(sendAuthCommand, connections, credentials, callback); + } +} + +function SSIPAuthenticate( + self, + MongoAuthProcess, + username, + password, + gssapiServiceName, + sendAuthCommand, + connection, + options, + callback +) { + const authProcess = new MongoAuthProcess( + connection.host, + connection.port, + gssapiServiceName, + options + ); + + function authCommand(command, authCb) { + sendAuthCommand(connection, '$external.$cmd', command, authCb); + } + + authProcess.init(username, password, err => { + if (err) return callback(err, false); + + authProcess.transition('', (err, payload) => { + if (err) return callback(err, false); + + const command = { + saslStart: 1, + mechanism: 'GSSAPI', + payload, + autoAuthorize: 1 + }; + + authCommand(command, (err, doc) => { + if (err) return callback(err, false); + + authProcess.transition(doc.payload, (err, payload) => { + if (err) return callback(err, false); + const command = { + saslContinue: 1, + conversationId: doc.conversationId, + payload + }; + + authCommand(command, (err, doc) => { + if (err) return callback(err, false); + + authProcess.transition(doc.payload, (err, payload) => { + if (err) return callback(err, false); + const command = { + saslContinue: 1, + conversationId: doc.conversationId, + payload + }; + + authCommand(command, (err, response) => { + if (err) return callback(err, false); + + authProcess.transition(null, err => { + if (err) return callback(err, null); + callback(null, response); + }); + }); + }); + }); + }); + }); + }); + }); +} + +module.exports = SSPI; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/auth/x509.js b/scripts/2.5/node_modules/mongodb/lib/core/auth/x509.js new file mode 100644 index 00000000..10d5b588 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/core/auth/x509.js @@ -0,0 +1,26 @@ +'use strict'; + +const AuthProvider = require('./auth_provider').AuthProvider; + +/** + * Creates a new X509 authentication mechanism + * @class + * @extends AuthProvider + */ +class X509 extends AuthProvider { + /** + * Implementation of authentication for a single connection + * @override + */ + _authenticateSingleConnection(sendAuthCommand, connection, credentials, callback) { + const username = credentials.username; + const command = { authenticate: 1, mechanism: 'MONGODB-X509' }; + if (username) { + command.user = username; + } + + sendAuthCommand(connection, '$external.$cmd', command, callback); + } +} + +module.exports = X509; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/connection/apm.js b/scripts/2.5/node_modules/mongodb/lib/core/connection/apm.js new file mode 100644 index 00000000..defc59a1 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/core/connection/apm.js @@ -0,0 +1,236 @@ +'use strict'; +const Msg = require('../connection/msg').Msg; +const KillCursor = require('../connection/commands').KillCursor; +const GetMore = require('../connection/commands').GetMore; +const calculateDurationInMs = require('../utils').calculateDurationInMs; + +/** Commands that we want to redact because of the sensitive nature of their contents */ +const SENSITIVE_COMMANDS = new Set([ + 'authenticate', + 'saslStart', + 'saslContinue', + 'getnonce', + 'createUser', + 'updateUser', + 'copydbgetnonce', + 'copydbsaslstart', + 'copydb' +]); + +// helper methods +const extractCommandName = commandDoc => Object.keys(commandDoc)[0]; +const namespace = command => command.ns; +const databaseName = command => command.ns.split('.')[0]; +const collectionName = command => command.ns.split('.')[1]; +const generateConnectionId = pool => `${pool.options.host}:${pool.options.port}`; +const maybeRedact = (commandName, result) => (SENSITIVE_COMMANDS.has(commandName) ? {} : result); + +const LEGACY_FIND_QUERY_MAP = { + $query: 'filter', + $orderby: 'sort', + $hint: 'hint', + $comment: 'comment', + $maxScan: 'maxScan', + $max: 'max', + $min: 'min', + $returnKey: 'returnKey', + $showDiskLoc: 'showRecordId', + $maxTimeMS: 'maxTimeMS', + $snapshot: 'snapshot' +}; + +const LEGACY_FIND_OPTIONS_MAP = { + numberToSkip: 'skip', + numberToReturn: 'batchSize', + returnFieldsSelector: 'projection' +}; + +const OP_QUERY_KEYS = [ + 'tailable', + 'oplogReplay', + 'noCursorTimeout', + 'awaitData', + 'partial', + 'exhaust' +]; + +/** + * Extract the actual command from the query, possibly upconverting if it's a legacy + * format + * + * @param {Object} command the command + */ +const extractCommand = command => { + if (command instanceof GetMore) { + return { + getMore: command.cursorId, + collection: collectionName(command), + batchSize: command.numberToReturn + }; + } + + if (command instanceof KillCursor) { + return { + killCursors: collectionName(command), + cursors: command.cursorIds + }; + } + + if (command instanceof Msg) { + return command.command; + } + + if (command.query && command.query.$query) { + let result; + if (command.ns === 'admin.$cmd') { + // upconvert legacy command + result = Object.assign({}, command.query.$query); + } else { + // upconvert legacy find command + result = { find: collectionName(command) }; + Object.keys(LEGACY_FIND_QUERY_MAP).forEach(key => { + if (typeof command.query[key] !== 'undefined') + result[LEGACY_FIND_QUERY_MAP[key]] = command.query[key]; + }); + } + + Object.keys(LEGACY_FIND_OPTIONS_MAP).forEach(key => { + if (typeof command[key] !== 'undefined') result[LEGACY_FIND_OPTIONS_MAP[key]] = command[key]; + }); + + OP_QUERY_KEYS.forEach(key => { + if (command[key]) result[key] = command[key]; + }); + + if (typeof command.pre32Limit !== 'undefined') { + result.limit = command.pre32Limit; + } + + if (command.query.$explain) { + return { explain: result }; + } + + return result; + } + + return command.query ? command.query : command; +}; + +const extractReply = (command, reply) => { + if (command instanceof GetMore) { + return { + ok: 1, + cursor: { + id: reply.message.cursorId, + ns: namespace(command), + nextBatch: reply.message.documents + } + }; + } + + if (command instanceof KillCursor) { + return { + ok: 1, + cursorsUnknown: command.cursorIds + }; + } + + // is this a legacy find command? + if (command.query && typeof command.query.$query !== 'undefined') { + return { + ok: 1, + cursor: { + id: reply.message.cursorId, + ns: namespace(command), + firstBatch: reply.message.documents + } + }; + } + + // in the event of a `noResponse` command, just return + if (reply === null) return reply; + + return reply.result; +}; + +/** An event indicating the start of a given command */ +class CommandStartedEvent { + /** + * Create a started event + * + * @param {Pool} pool the pool that originated the command + * @param {Object} command the command + */ + constructor(pool, command) { + const cmd = extractCommand(command); + const commandName = extractCommandName(cmd); + + // NOTE: remove in major revision, this is not spec behavior + if (SENSITIVE_COMMANDS.has(commandName)) { + this.commandObj = {}; + this.commandObj[commandName] = true; + } + + Object.assign(this, { + command: cmd, + databaseName: databaseName(command), + commandName, + requestId: command.requestId, + connectionId: generateConnectionId(pool) + }); + } +} + +/** An event indicating the success of a given command */ +class CommandSucceededEvent { + /** + * Create a succeeded event + * + * @param {Pool} pool the pool that originated the command + * @param {Object} command the command + * @param {Object} reply the reply for this command from the server + * @param {Array} started a high resolution tuple timestamp of when the command was first sent, to calculate duration + */ + constructor(pool, command, reply, started) { + const cmd = extractCommand(command); + const commandName = extractCommandName(cmd); + + Object.assign(this, { + duration: calculateDurationInMs(started), + commandName, + reply: maybeRedact(commandName, extractReply(command, reply)), + requestId: command.requestId, + connectionId: generateConnectionId(pool) + }); + } +} + +/** An event indicating the failure of a given command */ +class CommandFailedEvent { + /** + * Create a failure event + * + * @param {Pool} pool the pool that originated the command + * @param {Object} command the command + * @param {MongoError|Object} error the generated error or a server error response + * @param {Array} started a high resolution tuple timestamp of when the command was first sent, to calculate duration + */ + constructor(pool, command, error, started) { + const cmd = extractCommand(command); + const commandName = extractCommandName(cmd); + + Object.assign(this, { + duration: calculateDurationInMs(started), + commandName, + failure: maybeRedact(commandName, error), + requestId: command.requestId, + connectionId: generateConnectionId(pool) + }); + } +} + +module.exports = { + CommandStartedEvent, + CommandSucceededEvent, + CommandFailedEvent +}; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/connection/command_result.js b/scripts/2.5/node_modules/mongodb/lib/core/connection/command_result.js new file mode 100644 index 00000000..762aa3f1 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/core/connection/command_result.js @@ -0,0 +1,36 @@ +'use strict'; + +/** + * Creates a new CommandResult instance + * @class + * @param {object} result CommandResult object + * @param {Connection} connection A connection instance associated with this result + * @return {CommandResult} A cursor instance + */ +var CommandResult = function(result, connection, message) { + this.result = result; + this.connection = connection; + this.message = message; +}; + +/** + * Convert CommandResult to JSON + * @method + * @return {object} + */ +CommandResult.prototype.toJSON = function() { + let result = Object.assign({}, this, this.result); + delete result.message; + return result; +}; + +/** + * Convert CommandResult to String representation + * @method + * @return {string} + */ +CommandResult.prototype.toString = function() { + return JSON.stringify(this.toJSON()); +}; + +module.exports = CommandResult; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/connection/commands.js b/scripts/2.5/node_modules/mongodb/lib/core/connection/commands.js new file mode 100644 index 00000000..b24ff848 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/core/connection/commands.js @@ -0,0 +1,507 @@ +'use strict'; + +var retrieveBSON = require('./utils').retrieveBSON; +var BSON = retrieveBSON(); +var Long = BSON.Long; +const Buffer = require('safe-buffer').Buffer; + +// Incrementing request id +var _requestId = 0; + +// Wire command operation ids +var opcodes = require('../wireprotocol/shared').opcodes; + +// Query flags +var OPTS_TAILABLE_CURSOR = 2; +var OPTS_SLAVE = 4; +var OPTS_OPLOG_REPLAY = 8; +var OPTS_NO_CURSOR_TIMEOUT = 16; +var OPTS_AWAIT_DATA = 32; +var OPTS_EXHAUST = 64; +var OPTS_PARTIAL = 128; + +// Response flags +var CURSOR_NOT_FOUND = 1; +var QUERY_FAILURE = 2; +var SHARD_CONFIG_STALE = 4; +var AWAIT_CAPABLE = 8; + +/************************************************************** + * QUERY + **************************************************************/ +var Query = function(bson, ns, query, options) { + var self = this; + // Basic options needed to be passed in + if (ns == null) throw new Error('ns must be specified for query'); + if (query == null) throw new Error('query must be specified for query'); + + // Validate that we are not passing 0x00 in the collection name + if (ns.indexOf('\x00') !== -1) { + throw new Error('namespace cannot contain a null character'); + } + + // Basic options + this.bson = bson; + this.ns = ns; + this.query = query; + + // Additional options + this.numberToSkip = options.numberToSkip || 0; + this.numberToReturn = options.numberToReturn || 0; + this.returnFieldSelector = options.returnFieldSelector || null; + this.requestId = Query.getRequestId(); + + // special case for pre-3.2 find commands, delete ASAP + this.pre32Limit = options.pre32Limit; + + // Serialization option + this.serializeFunctions = + typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + this.ignoreUndefined = + typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : false; + this.maxBsonSize = options.maxBsonSize || 1024 * 1024 * 16; + this.checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : true; + this.batchSize = self.numberToReturn; + + // Flags + this.tailable = false; + this.slaveOk = typeof options.slaveOk === 'boolean' ? options.slaveOk : false; + this.oplogReplay = false; + this.noCursorTimeout = false; + this.awaitData = false; + this.exhaust = false; + this.partial = false; +}; + +// +// Assign a new request Id +Query.prototype.incRequestId = function() { + this.requestId = _requestId++; +}; + +// +// Assign a new request Id +Query.nextRequestId = function() { + return _requestId + 1; +}; + +// +// Uses a single allocated buffer for the process, avoiding multiple memory allocations +Query.prototype.toBin = function() { + var self = this; + var buffers = []; + var projection = null; + + // Set up the flags + var flags = 0; + if (this.tailable) { + flags |= OPTS_TAILABLE_CURSOR; + } + + if (this.slaveOk) { + flags |= OPTS_SLAVE; + } + + if (this.oplogReplay) { + flags |= OPTS_OPLOG_REPLAY; + } + + if (this.noCursorTimeout) { + flags |= OPTS_NO_CURSOR_TIMEOUT; + } + + if (this.awaitData) { + flags |= OPTS_AWAIT_DATA; + } + + if (this.exhaust) { + flags |= OPTS_EXHAUST; + } + + if (this.partial) { + flags |= OPTS_PARTIAL; + } + + // If batchSize is different to self.numberToReturn + if (self.batchSize !== self.numberToReturn) self.numberToReturn = self.batchSize; + + // Allocate write protocol header buffer + var header = Buffer.alloc( + 4 * 4 + // Header + 4 + // Flags + Buffer.byteLength(self.ns) + + 1 + // namespace + 4 + // numberToSkip + 4 // numberToReturn + ); + + // Add header to buffers + buffers.push(header); + + // Serialize the query + var query = self.bson.serialize(this.query, { + checkKeys: this.checkKeys, + serializeFunctions: this.serializeFunctions, + ignoreUndefined: this.ignoreUndefined + }); + + // Add query document + buffers.push(query); + + if (self.returnFieldSelector && Object.keys(self.returnFieldSelector).length > 0) { + // Serialize the projection document + projection = self.bson.serialize(this.returnFieldSelector, { + checkKeys: this.checkKeys, + serializeFunctions: this.serializeFunctions, + ignoreUndefined: this.ignoreUndefined + }); + // Add projection document + buffers.push(projection); + } + + // Total message size + var totalLength = header.length + query.length + (projection ? projection.length : 0); + + // Set up the index + var index = 4; + + // Write total document length + header[3] = (totalLength >> 24) & 0xff; + header[2] = (totalLength >> 16) & 0xff; + header[1] = (totalLength >> 8) & 0xff; + header[0] = totalLength & 0xff; + + // Write header information requestId + header[index + 3] = (this.requestId >> 24) & 0xff; + header[index + 2] = (this.requestId >> 16) & 0xff; + header[index + 1] = (this.requestId >> 8) & 0xff; + header[index] = this.requestId & 0xff; + index = index + 4; + + // Write header information responseTo + header[index + 3] = (0 >> 24) & 0xff; + header[index + 2] = (0 >> 16) & 0xff; + header[index + 1] = (0 >> 8) & 0xff; + header[index] = 0 & 0xff; + index = index + 4; + + // Write header information OP_QUERY + header[index + 3] = (opcodes.OP_QUERY >> 24) & 0xff; + header[index + 2] = (opcodes.OP_QUERY >> 16) & 0xff; + header[index + 1] = (opcodes.OP_QUERY >> 8) & 0xff; + header[index] = opcodes.OP_QUERY & 0xff; + index = index + 4; + + // Write header information flags + header[index + 3] = (flags >> 24) & 0xff; + header[index + 2] = (flags >> 16) & 0xff; + header[index + 1] = (flags >> 8) & 0xff; + header[index] = flags & 0xff; + index = index + 4; + + // Write collection name + index = index + header.write(this.ns, index, 'utf8') + 1; + header[index - 1] = 0; + + // Write header information flags numberToSkip + header[index + 3] = (this.numberToSkip >> 24) & 0xff; + header[index + 2] = (this.numberToSkip >> 16) & 0xff; + header[index + 1] = (this.numberToSkip >> 8) & 0xff; + header[index] = this.numberToSkip & 0xff; + index = index + 4; + + // Write header information flags numberToReturn + header[index + 3] = (this.numberToReturn >> 24) & 0xff; + header[index + 2] = (this.numberToReturn >> 16) & 0xff; + header[index + 1] = (this.numberToReturn >> 8) & 0xff; + header[index] = this.numberToReturn & 0xff; + index = index + 4; + + // Return the buffers + return buffers; +}; + +Query.getRequestId = function() { + return ++_requestId; +}; + +/************************************************************** + * GETMORE + **************************************************************/ +var GetMore = function(bson, ns, cursorId, opts) { + opts = opts || {}; + this.numberToReturn = opts.numberToReturn || 0; + this.requestId = _requestId++; + this.bson = bson; + this.ns = ns; + this.cursorId = cursorId; +}; + +// +// Uses a single allocated buffer for the process, avoiding multiple memory allocations +GetMore.prototype.toBin = function() { + var length = 4 + Buffer.byteLength(this.ns) + 1 + 4 + 8 + 4 * 4; + // Create command buffer + var index = 0; + // Allocate buffer + var _buffer = Buffer.alloc(length); + + // Write header information + // index = write32bit(index, _buffer, length); + _buffer[index + 3] = (length >> 24) & 0xff; + _buffer[index + 2] = (length >> 16) & 0xff; + _buffer[index + 1] = (length >> 8) & 0xff; + _buffer[index] = length & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, requestId); + _buffer[index + 3] = (this.requestId >> 24) & 0xff; + _buffer[index + 2] = (this.requestId >> 16) & 0xff; + _buffer[index + 1] = (this.requestId >> 8) & 0xff; + _buffer[index] = this.requestId & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, 0); + _buffer[index + 3] = (0 >> 24) & 0xff; + _buffer[index + 2] = (0 >> 16) & 0xff; + _buffer[index + 1] = (0 >> 8) & 0xff; + _buffer[index] = 0 & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, OP_GETMORE); + _buffer[index + 3] = (opcodes.OP_GETMORE >> 24) & 0xff; + _buffer[index + 2] = (opcodes.OP_GETMORE >> 16) & 0xff; + _buffer[index + 1] = (opcodes.OP_GETMORE >> 8) & 0xff; + _buffer[index] = opcodes.OP_GETMORE & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, 0); + _buffer[index + 3] = (0 >> 24) & 0xff; + _buffer[index + 2] = (0 >> 16) & 0xff; + _buffer[index + 1] = (0 >> 8) & 0xff; + _buffer[index] = 0 & 0xff; + index = index + 4; + + // Write collection name + index = index + _buffer.write(this.ns, index, 'utf8') + 1; + _buffer[index - 1] = 0; + + // Write batch size + // index = write32bit(index, _buffer, numberToReturn); + _buffer[index + 3] = (this.numberToReturn >> 24) & 0xff; + _buffer[index + 2] = (this.numberToReturn >> 16) & 0xff; + _buffer[index + 1] = (this.numberToReturn >> 8) & 0xff; + _buffer[index] = this.numberToReturn & 0xff; + index = index + 4; + + // Write cursor id + // index = write32bit(index, _buffer, cursorId.getLowBits()); + _buffer[index + 3] = (this.cursorId.getLowBits() >> 24) & 0xff; + _buffer[index + 2] = (this.cursorId.getLowBits() >> 16) & 0xff; + _buffer[index + 1] = (this.cursorId.getLowBits() >> 8) & 0xff; + _buffer[index] = this.cursorId.getLowBits() & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, cursorId.getHighBits()); + _buffer[index + 3] = (this.cursorId.getHighBits() >> 24) & 0xff; + _buffer[index + 2] = (this.cursorId.getHighBits() >> 16) & 0xff; + _buffer[index + 1] = (this.cursorId.getHighBits() >> 8) & 0xff; + _buffer[index] = this.cursorId.getHighBits() & 0xff; + index = index + 4; + + // Return buffer + return _buffer; +}; + +/************************************************************** + * KILLCURSOR + **************************************************************/ +var KillCursor = function(bson, ns, cursorIds) { + this.ns = ns; + this.requestId = _requestId++; + this.cursorIds = cursorIds; +}; + +// +// Uses a single allocated buffer for the process, avoiding multiple memory allocations +KillCursor.prototype.toBin = function() { + var length = 4 + 4 + 4 * 4 + this.cursorIds.length * 8; + + // Create command buffer + var index = 0; + var _buffer = Buffer.alloc(length); + + // Write header information + // index = write32bit(index, _buffer, length); + _buffer[index + 3] = (length >> 24) & 0xff; + _buffer[index + 2] = (length >> 16) & 0xff; + _buffer[index + 1] = (length >> 8) & 0xff; + _buffer[index] = length & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, requestId); + _buffer[index + 3] = (this.requestId >> 24) & 0xff; + _buffer[index + 2] = (this.requestId >> 16) & 0xff; + _buffer[index + 1] = (this.requestId >> 8) & 0xff; + _buffer[index] = this.requestId & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, 0); + _buffer[index + 3] = (0 >> 24) & 0xff; + _buffer[index + 2] = (0 >> 16) & 0xff; + _buffer[index + 1] = (0 >> 8) & 0xff; + _buffer[index] = 0 & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, OP_KILL_CURSORS); + _buffer[index + 3] = (opcodes.OP_KILL_CURSORS >> 24) & 0xff; + _buffer[index + 2] = (opcodes.OP_KILL_CURSORS >> 16) & 0xff; + _buffer[index + 1] = (opcodes.OP_KILL_CURSORS >> 8) & 0xff; + _buffer[index] = opcodes.OP_KILL_CURSORS & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, 0); + _buffer[index + 3] = (0 >> 24) & 0xff; + _buffer[index + 2] = (0 >> 16) & 0xff; + _buffer[index + 1] = (0 >> 8) & 0xff; + _buffer[index] = 0 & 0xff; + index = index + 4; + + // Write batch size + // index = write32bit(index, _buffer, this.cursorIds.length); + _buffer[index + 3] = (this.cursorIds.length >> 24) & 0xff; + _buffer[index + 2] = (this.cursorIds.length >> 16) & 0xff; + _buffer[index + 1] = (this.cursorIds.length >> 8) & 0xff; + _buffer[index] = this.cursorIds.length & 0xff; + index = index + 4; + + // Write all the cursor ids into the array + for (var i = 0; i < this.cursorIds.length; i++) { + // Write cursor id + // index = write32bit(index, _buffer, cursorIds[i].getLowBits()); + _buffer[index + 3] = (this.cursorIds[i].getLowBits() >> 24) & 0xff; + _buffer[index + 2] = (this.cursorIds[i].getLowBits() >> 16) & 0xff; + _buffer[index + 1] = (this.cursorIds[i].getLowBits() >> 8) & 0xff; + _buffer[index] = this.cursorIds[i].getLowBits() & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, cursorIds[i].getHighBits()); + _buffer[index + 3] = (this.cursorIds[i].getHighBits() >> 24) & 0xff; + _buffer[index + 2] = (this.cursorIds[i].getHighBits() >> 16) & 0xff; + _buffer[index + 1] = (this.cursorIds[i].getHighBits() >> 8) & 0xff; + _buffer[index] = this.cursorIds[i].getHighBits() & 0xff; + index = index + 4; + } + + // Return buffer + return _buffer; +}; + +var Response = function(bson, message, msgHeader, msgBody, opts) { + opts = opts || { promoteLongs: true, promoteValues: true, promoteBuffers: false }; + this.parsed = false; + this.raw = message; + this.data = msgBody; + this.bson = bson; + this.opts = opts; + + // Read the message header + this.length = msgHeader.length; + this.requestId = msgHeader.requestId; + this.responseTo = msgHeader.responseTo; + this.opCode = msgHeader.opCode; + this.fromCompressed = msgHeader.fromCompressed; + + // Read the message body + this.responseFlags = msgBody.readInt32LE(0); + this.cursorId = new Long(msgBody.readInt32LE(4), msgBody.readInt32LE(8)); + this.startingFrom = msgBody.readInt32LE(12); + this.numberReturned = msgBody.readInt32LE(16); + + // Preallocate document array + this.documents = new Array(this.numberReturned); + + // Flag values + this.cursorNotFound = (this.responseFlags & CURSOR_NOT_FOUND) !== 0; + this.queryFailure = (this.responseFlags & QUERY_FAILURE) !== 0; + this.shardConfigStale = (this.responseFlags & SHARD_CONFIG_STALE) !== 0; + this.awaitCapable = (this.responseFlags & AWAIT_CAPABLE) !== 0; + this.promoteLongs = typeof opts.promoteLongs === 'boolean' ? opts.promoteLongs : true; + this.promoteValues = typeof opts.promoteValues === 'boolean' ? opts.promoteValues : true; + this.promoteBuffers = typeof opts.promoteBuffers === 'boolean' ? opts.promoteBuffers : false; +}; + +Response.prototype.isParsed = function() { + return this.parsed; +}; + +Response.prototype.parse = function(options) { + // Don't parse again if not needed + if (this.parsed) return; + options = options || {}; + + // Allow the return of raw documents instead of parsing + var raw = options.raw || false; + var documentsReturnedIn = options.documentsReturnedIn || null; + var promoteLongs = + typeof options.promoteLongs === 'boolean' ? options.promoteLongs : this.opts.promoteLongs; + var promoteValues = + typeof options.promoteValues === 'boolean' ? options.promoteValues : this.opts.promoteValues; + var promoteBuffers = + typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : this.opts.promoteBuffers; + var bsonSize, _options; + + // Set up the options + _options = { + promoteLongs: promoteLongs, + promoteValues: promoteValues, + promoteBuffers: promoteBuffers + }; + + // Position within OP_REPLY at which documents start + // (See https://docs.mongodb.com/manual/reference/mongodb-wire-protocol/#wire-op-reply) + this.index = 20; + + // + // Parse Body + // + for (var i = 0; i < this.numberReturned; i++) { + bsonSize = + this.data[this.index] | + (this.data[this.index + 1] << 8) | + (this.data[this.index + 2] << 16) | + (this.data[this.index + 3] << 24); + + // If we have raw results specified slice the return document + if (raw) { + this.documents[i] = this.data.slice(this.index, this.index + bsonSize); + } else { + this.documents[i] = this.bson.deserialize( + this.data.slice(this.index, this.index + bsonSize), + _options + ); + } + + // Adjust the index + this.index = this.index + bsonSize; + } + + if (this.documents.length === 1 && documentsReturnedIn != null && raw) { + const fieldsAsRaw = {}; + fieldsAsRaw[documentsReturnedIn] = true; + _options.fieldsAsRaw = fieldsAsRaw; + + const doc = this.bson.deserialize(this.documents[0], _options); + this.documents = [doc]; + } + + // Set parsed + this.parsed = true; +}; + +module.exports = { + Query: Query, + GetMore: GetMore, + Response: Response, + KillCursor: KillCursor +}; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/connection/connect.js b/scripts/2.5/node_modules/mongodb/lib/core/connection/connect.js new file mode 100644 index 00000000..e1a643e0 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/core/connection/connect.js @@ -0,0 +1,370 @@ +'use strict'; +const net = require('net'); +const tls = require('tls'); +const Connection = require('./connection'); +const Query = require('./commands').Query; +const createClientInfo = require('../topologies/shared').createClientInfo; +const MongoError = require('../error').MongoError; +const MongoNetworkError = require('../error').MongoNetworkError; +const defaultAuthProviders = require('../auth/defaultAuthProviders').defaultAuthProviders; +const WIRE_CONSTANTS = require('../wireprotocol/constants'); +const MAX_SUPPORTED_WIRE_VERSION = WIRE_CONSTANTS.MAX_SUPPORTED_WIRE_VERSION; +const MAX_SUPPORTED_SERVER_VERSION = WIRE_CONSTANTS.MAX_SUPPORTED_SERVER_VERSION; +const MIN_SUPPORTED_WIRE_VERSION = WIRE_CONSTANTS.MIN_SUPPORTED_WIRE_VERSION; +const MIN_SUPPORTED_SERVER_VERSION = WIRE_CONSTANTS.MIN_SUPPORTED_SERVER_VERSION; +let AUTH_PROVIDERS; + +function connect(options, callback) { + if (AUTH_PROVIDERS == null) { + AUTH_PROVIDERS = defaultAuthProviders(options.bson); + } + + if (options.family !== void 0) { + makeConnection(options.family, options, (err, socket) => { + if (err) { + callback(err, socket); // in the error case, `socket` is the originating error event name + return; + } + + performInitialHandshake(new Connection(socket, options), options, callback); + }); + + return; + } + + return makeConnection(6, options, (err, ipv6Socket) => { + if (err) { + makeConnection(4, options, (err, ipv4Socket) => { + if (err) { + callback(err, ipv4Socket); // in the error case, `ipv4Socket` is the originating error event name + return; + } + + performInitialHandshake(new Connection(ipv4Socket, options), options, callback); + }); + + return; + } + + performInitialHandshake(new Connection(ipv6Socket, options), options, callback); + }); +} + +function getSaslSupportedMechs(options) { + if (!(options && options.credentials)) { + return {}; + } + + const credentials = options.credentials; + + // TODO: revisit whether or not items like `options.user` and `options.dbName` should be checked here + const authMechanism = credentials.mechanism; + const authSource = credentials.source || options.dbName || 'admin'; + const user = credentials.username || options.user; + + if (typeof authMechanism === 'string' && authMechanism.toUpperCase() !== 'DEFAULT') { + return {}; + } + + if (!user) { + return {}; + } + + return { saslSupportedMechs: `${authSource}.${user}` }; +} + +function checkSupportedServer(ismaster, options) { + const serverVersionHighEnough = + ismaster && + typeof ismaster.maxWireVersion === 'number' && + ismaster.maxWireVersion >= MIN_SUPPORTED_WIRE_VERSION; + const serverVersionLowEnough = + ismaster && + typeof ismaster.minWireVersion === 'number' && + ismaster.minWireVersion <= MAX_SUPPORTED_WIRE_VERSION; + + if (serverVersionHighEnough) { + if (serverVersionLowEnough) { + return null; + } + + const message = `Server at ${options.host}:${options.port} reports minimum wire version ${ + ismaster.minWireVersion + }, but this version of the Node.js Driver requires at most ${MAX_SUPPORTED_WIRE_VERSION} (MongoDB ${MAX_SUPPORTED_SERVER_VERSION})`; + return new MongoError(message); + } + + const message = `Server at ${options.host}:${ + options.port + } reports maximum wire version ${ismaster.maxWireVersion || + 0}, but this version of the Node.js Driver requires at least ${MIN_SUPPORTED_WIRE_VERSION} (MongoDB ${MIN_SUPPORTED_SERVER_VERSION})`; + return new MongoError(message); +} + +function performInitialHandshake(conn, options, _callback) { + const callback = function(err, ret) { + if (err && conn) { + conn.destroy(); + } + _callback(err, ret); + }; + + let compressors = []; + if (options.compression && options.compression.compressors) { + compressors = options.compression.compressors; + } + + const handshakeDoc = Object.assign( + { + ismaster: true, + client: createClientInfo(options), + compression: compressors + }, + getSaslSupportedMechs(options) + ); + + const start = new Date().getTime(); + runCommand(conn, 'admin.$cmd', handshakeDoc, options, (err, ismaster) => { + if (err) { + callback(err, null); + return; + } + + if (ismaster.ok === 0) { + callback(new MongoError(ismaster), null); + return; + } + + const supportedServerErr = checkSupportedServer(ismaster, options); + if (supportedServerErr) { + callback(supportedServerErr, null); + return; + } + + // resolve compression + if (ismaster.compression) { + const agreedCompressors = compressors.filter( + compressor => ismaster.compression.indexOf(compressor) !== -1 + ); + + if (agreedCompressors.length) { + conn.agreedCompressor = agreedCompressors[0]; + } + + if (options.compression && options.compression.zlibCompressionLevel) { + conn.zlibCompressionLevel = options.compression.zlibCompressionLevel; + } + } + + // NOTE: This is metadata attached to the connection while porting away from + // handshake being done in the `Server` class. Likely, it should be + // relocated, or at very least restructured. + conn.ismaster = ismaster; + conn.lastIsMasterMS = new Date().getTime() - start; + + const credentials = options.credentials; + if (!ismaster.arbiterOnly && credentials) { + credentials.resolveAuthMechanism(ismaster); + authenticate(conn, credentials, callback); + return; + } + + callback(null, conn); + }); +} + +const LEGAL_SSL_SOCKET_OPTIONS = [ + 'pfx', + 'key', + 'passphrase', + 'cert', + 'ca', + 'ciphers', + 'NPNProtocols', + 'ALPNProtocols', + 'servername', + 'ecdhCurve', + 'secureProtocol', + 'secureContext', + 'session', + 'minDHSize', + 'crl', + 'rejectUnauthorized' +]; + +function parseConnectOptions(family, options) { + const host = typeof options.host === 'string' ? options.host : 'localhost'; + if (host.indexOf('/') !== -1) { + return { path: host }; + } + + const result = { + family, + host, + port: typeof options.port === 'number' ? options.port : 27017, + rejectUnauthorized: false + }; + + return result; +} + +function parseSslOptions(family, options) { + const result = parseConnectOptions(family, options); + + // Merge in valid SSL options + for (const name in options) { + if (options[name] != null && LEGAL_SSL_SOCKET_OPTIONS.indexOf(name) !== -1) { + result[name] = options[name]; + } + } + + // Override checkServerIdentity behavior + if (options.checkServerIdentity === false) { + // Skip the identiy check by retuning undefined as per node documents + // https://nodejs.org/api/tls.html#tls_tls_connect_options_callback + result.checkServerIdentity = function() { + return undefined; + }; + } else if (typeof options.checkServerIdentity === 'function') { + result.checkServerIdentity = options.checkServerIdentity; + } + + // Set default sni servername to be the same as host + if (result.servername == null) { + result.servername = result.host; + } + + return result; +} + +function makeConnection(family, options, _callback) { + const useSsl = typeof options.ssl === 'boolean' ? options.ssl : false; + const keepAlive = typeof options.keepAlive === 'boolean' ? options.keepAlive : true; + let keepAliveInitialDelay = + typeof options.keepAliveInitialDelay === 'number' ? options.keepAliveInitialDelay : 300000; + const noDelay = typeof options.noDelay === 'boolean' ? options.noDelay : true; + const connectionTimeout = + typeof options.connectionTimeout === 'number' ? options.connectionTimeout : 30000; + const socketTimeout = typeof options.socketTimeout === 'number' ? options.socketTimeout : 360000; + const rejectUnauthorized = + typeof options.rejectUnauthorized === 'boolean' ? options.rejectUnauthorized : true; + + if (keepAliveInitialDelay > socketTimeout) { + keepAliveInitialDelay = Math.round(socketTimeout / 2); + } + + let socket; + const callback = function(err, ret) { + if (err && socket) { + socket.destroy(); + } + _callback(err, ret); + }; + + try { + if (useSsl) { + socket = tls.connect(parseSslOptions(family, options)); + if (typeof socket.disableRenegotiation === 'function') { + socket.disableRenegotiation(); + } + } else { + socket = net.createConnection(parseConnectOptions(family, options)); + } + } catch (err) { + return callback(err); + } + + socket.setKeepAlive(keepAlive, keepAliveInitialDelay); + socket.setTimeout(connectionTimeout); + socket.setNoDelay(noDelay); + + const errorEvents = ['error', 'close', 'timeout', 'parseError']; + function errorHandler(eventName) { + return err => { + errorEvents.forEach(event => socket.removeAllListeners(event)); + socket.removeListener('connect', connectHandler); + callback(connectionFailureError(eventName, err), eventName); + }; + } + + function connectHandler() { + errorEvents.forEach(event => socket.removeAllListeners(event)); + if (socket.authorizationError && rejectUnauthorized) { + return callback(socket.authorizationError); + } + + socket.setTimeout(socketTimeout); + callback(null, socket); + } + + socket.once('error', errorHandler('error')); + socket.once('close', errorHandler('close')); + socket.once('timeout', errorHandler('timeout')); + socket.once('parseError', errorHandler('parseError')); + socket.once('connect', connectHandler); +} + +const CONNECTION_ERROR_EVENTS = ['error', 'close', 'timeout', 'parseError']; +function runCommand(conn, ns, command, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + const socketTimeout = typeof options.socketTimeout === 'number' ? options.socketTimeout : 360000; + const bson = conn.options.bson; + const query = new Query(bson, ns, command, { + numberToSkip: 0, + numberToReturn: 1 + }); + + function errorHandler(err) { + conn.resetSocketTimeout(); + CONNECTION_ERROR_EVENTS.forEach(eventName => conn.removeListener(eventName, errorHandler)); + conn.removeListener('message', messageHandler); + callback(err, null); + } + + function messageHandler(msg) { + if (msg.responseTo !== query.requestId) { + return; + } + + conn.resetSocketTimeout(); + CONNECTION_ERROR_EVENTS.forEach(eventName => conn.removeListener(eventName, errorHandler)); + conn.removeListener('message', messageHandler); + + msg.parse({ promoteValues: true }); + callback(null, msg.documents[0]); + } + + conn.setSocketTimeout(socketTimeout); + CONNECTION_ERROR_EVENTS.forEach(eventName => conn.once(eventName, errorHandler)); + conn.on('message', messageHandler); + conn.write(query.toBin()); +} + +function authenticate(conn, credentials, callback) { + const mechanism = credentials.mechanism; + if (!AUTH_PROVIDERS[mechanism]) { + callback(new MongoError(`authMechanism '${mechanism}' not supported`)); + return; + } + + const provider = AUTH_PROVIDERS[mechanism]; + provider.auth(runCommand, [conn], credentials, err => { + if (err) return callback(err); + callback(null, conn); + }); +} + +function connectionFailureError(type, err) { + switch (type) { + case 'error': + return new MongoNetworkError(err); + case 'timeout': + return new MongoNetworkError(`connection timed out`); + case 'close': + return new MongoNetworkError(`connection closed`); + default: + return new MongoNetworkError(`unknown network error`); + } +} + +module.exports = connect; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/connection/connection.js b/scripts/2.5/node_modules/mongodb/lib/core/connection/connection.js new file mode 100644 index 00000000..6f6ca6ad --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/core/connection/connection.js @@ -0,0 +1,628 @@ +'use strict'; + +const EventEmitter = require('events').EventEmitter; +const crypto = require('crypto'); +const debugOptions = require('./utils').debugOptions; +const parseHeader = require('../wireprotocol/shared').parseHeader; +const decompress = require('../wireprotocol/compression').decompress; +const Response = require('./commands').Response; +const BinMsg = require('./msg').BinMsg; +const MongoNetworkError = require('../error').MongoNetworkError; +const MongoError = require('../error').MongoError; +const Logger = require('./logger'); +const OP_COMPRESSED = require('../wireprotocol/shared').opcodes.OP_COMPRESSED; +const OP_MSG = require('../wireprotocol/shared').opcodes.OP_MSG; +const MESSAGE_HEADER_SIZE = require('../wireprotocol/shared').MESSAGE_HEADER_SIZE; +const Buffer = require('safe-buffer').Buffer; + +let _id = 0; + +const DEFAULT_MAX_BSON_MESSAGE_SIZE = 1024 * 1024 * 16 * 4; +const DEBUG_FIELDS = [ + 'host', + 'port', + 'size', + 'keepAlive', + 'keepAliveInitialDelay', + 'noDelay', + 'connectionTimeout', + 'socketTimeout', + 'ssl', + 'ca', + 'crl', + 'cert', + 'rejectUnauthorized', + 'promoteLongs', + 'promoteValues', + 'promoteBuffers', + 'checkServerIdentity' +]; + +let connectionAccountingSpy = undefined; +let connectionAccounting = false; +let connections = {}; + +/** + * A class representing a single connection to a MongoDB server + * + * @fires Connection#connect + * @fires Connection#close + * @fires Connection#error + * @fires Connection#timeout + * @fires Connection#parseError + * @fires Connection#message + */ +class Connection extends EventEmitter { + /** + * Creates a new Connection instance + * + * **NOTE**: Internal class, do not instantiate directly + * + * @param {Socket} socket The socket this connection wraps + * @param {Object} options Various settings + * @param {object} options.bson An implementation of bson serialize and deserialize + * @param {string} [options.host='localhost'] The host the socket is connected to + * @param {number} [options.port=27017] The port used for the socket connection + * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled + * @param {number} [options.keepAliveInitialDelay=300000] Initial delay before TCP keep alive enabled + * @param {number} [options.connectionTimeout=30000] TCP Connection timeout setting + * @param {number} [options.socketTimeout=360000] TCP Socket timeout setting + * @param {boolean} [options.promoteLongs] Convert Long values from the db into Numbers if they fit into 53 bits + * @param {boolean} [options.promoteValues] Promotes BSON values to native types where possible, set to false to only receive wrapper types. + * @param {boolean} [options.promoteBuffers] Promotes Binary BSON values to native Node Buffers. + * @param {number} [options.maxBsonMessageSize=0x4000000] Largest possible size of a BSON message (for legacy purposes) + */ + constructor(socket, options) { + super(); + + options = options || {}; + if (!options.bson) { + throw new TypeError('must pass in valid bson parser'); + } + + this.id = _id++; + this.options = options; + this.logger = Logger('Connection', options); + this.bson = options.bson; + this.tag = options.tag; + this.maxBsonMessageSize = options.maxBsonMessageSize || DEFAULT_MAX_BSON_MESSAGE_SIZE; + + this.port = options.port || 27017; + this.host = options.host || 'localhost'; + this.socketTimeout = typeof options.socketTimeout === 'number' ? options.socketTimeout : 360000; + + // These values are inspected directly in tests, but maybe not necessary to keep around + this.keepAlive = typeof options.keepAlive === 'boolean' ? options.keepAlive : true; + this.keepAliveInitialDelay = + typeof options.keepAliveInitialDelay === 'number' ? options.keepAliveInitialDelay : 300000; + this.connectionTimeout = + typeof options.connectionTimeout === 'number' ? options.connectionTimeout : 30000; + if (this.keepAliveInitialDelay > this.socketTimeout) { + this.keepAliveInitialDelay = Math.round(this.socketTimeout / 2); + } + + // Debug information + if (this.logger.isDebug()) { + this.logger.debug( + `creating connection ${this.id} with options [${JSON.stringify( + debugOptions(DEBUG_FIELDS, options) + )}]` + ); + } + + // Response options + this.responseOptions = { + promoteLongs: typeof options.promoteLongs === 'boolean' ? options.promoteLongs : true, + promoteValues: typeof options.promoteValues === 'boolean' ? options.promoteValues : true, + promoteBuffers: typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : false + }; + + // Flushing + this.flushing = false; + this.queue = []; + + // Internal state + this.writeStream = null; + this.destroyed = false; + + // Create hash method + const hash = crypto.createHash('sha1'); + hash.update(this.address); + this.hashedName = hash.digest('hex'); + + // All operations in flight on the connection + this.workItems = []; + + // setup socket + this.socket = socket; + this.socket.once('error', errorHandler(this)); + this.socket.once('timeout', timeoutHandler(this)); + this.socket.once('close', closeHandler(this)); + this.socket.on('data', dataHandler(this)); + + if (connectionAccounting) { + addConnection(this.id, this); + } + } + + setSocketTimeout(value) { + if (this.socket) { + this.socket.setTimeout(value); + } + } + + resetSocketTimeout() { + if (this.socket) { + this.socket.setTimeout(this.socketTimeout); + } + } + + static enableConnectionAccounting(spy) { + if (spy) { + connectionAccountingSpy = spy; + } + + connectionAccounting = true; + connections = {}; + } + + static disableConnectionAccounting() { + connectionAccounting = false; + connectionAccountingSpy = undefined; + } + + static connections() { + return connections; + } + + get address() { + return `${this.host}:${this.port}`; + } + + /** + * Unref this connection + * @method + * @return {boolean} + */ + unref() { + if (this.socket == null) { + this.once('connect', () => this.socket.unref()); + return; + } + + this.socket.unref(); + } + + /** + * Destroy connection + * @method + */ + destroy(options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + + options = Object.assign({ force: false }, options); + + if (connectionAccounting) { + deleteConnection(this.id); + } + + if (this.socket == null) { + this.destroyed = true; + return; + } + + if (options.force) { + this.socket.destroy(); + this.destroyed = true; + if (typeof callback === 'function') callback(null, null); + return; + } + + this.socket.end(err => { + this.destroyed = true; + if (typeof callback === 'function') callback(err, null); + }); + } + + /** + * Write to connection + * @method + * @param {Command} command Command to write out need to implement toBin and toBinUnified + */ + write(buffer) { + // Debug Log + if (this.logger.isDebug()) { + if (!Array.isArray(buffer)) { + this.logger.debug(`writing buffer [${buffer.toString('hex')}] to ${this.address}`); + } else { + for (let i = 0; i < buffer.length; i++) + this.logger.debug(`writing buffer [${buffer[i].toString('hex')}] to ${this.address}`); + } + } + + // Double check that the connection is not destroyed + if (this.socket.destroyed === false) { + // Write out the command + if (!Array.isArray(buffer)) { + this.socket.write(buffer, 'binary'); + return true; + } + + // Iterate over all buffers and write them in order to the socket + for (let i = 0; i < buffer.length; i++) { + this.socket.write(buffer[i], 'binary'); + } + + return true; + } + + // Connection is destroyed return write failed + return false; + } + + /** + * Return id of connection as a string + * @method + * @return {string} + */ + toString() { + return '' + this.id; + } + + /** + * Return json object of connection + * @method + * @return {object} + */ + toJSON() { + return { id: this.id, host: this.host, port: this.port }; + } + + /** + * Is the connection connected + * @method + * @return {boolean} + */ + isConnected() { + if (this.destroyed) return false; + return !this.socket.destroyed && this.socket.writable; + } +} + +function deleteConnection(id) { + // console.log("=== deleted connection " + id + " :: " + (connections[id] ? connections[id].port : '')) + delete connections[id]; + + if (connectionAccountingSpy) { + connectionAccountingSpy.deleteConnection(id); + } +} + +function addConnection(id, connection) { + // console.log("=== added connection " + id + " :: " + connection.port) + connections[id] = connection; + + if (connectionAccountingSpy) { + connectionAccountingSpy.addConnection(id, connection); + } +} + +// +// Connection handlers +function errorHandler(conn) { + return function(err) { + if (connectionAccounting) deleteConnection(conn.id); + // Debug information + if (conn.logger.isDebug()) { + conn.logger.debug( + `connection ${conn.id} for [${conn.address}] errored out with [${JSON.stringify(err)}]` + ); + } + + conn.emit('error', new MongoNetworkError(err), conn); + }; +} + +function timeoutHandler(conn) { + return function() { + if (connectionAccounting) deleteConnection(conn.id); + + if (conn.logger.isDebug()) { + conn.logger.debug(`connection ${conn.id} for [${conn.address}] timed out`); + } + + conn.emit( + 'timeout', + new MongoNetworkError(`connection ${conn.id} to ${conn.address} timed out`), + conn + ); + }; +} + +function closeHandler(conn) { + return function(hadError) { + if (connectionAccounting) deleteConnection(conn.id); + + if (conn.logger.isDebug()) { + conn.logger.debug(`connection ${conn.id} with for [${conn.address}] closed`); + } + + if (!hadError) { + conn.emit( + 'close', + new MongoNetworkError(`connection ${conn.id} to ${conn.address} closed`), + conn + ); + } + }; +} + +// Handle a message once it is received +function processMessage(conn, message) { + const msgHeader = parseHeader(message); + if (msgHeader.opCode !== OP_COMPRESSED) { + const ResponseConstructor = msgHeader.opCode === OP_MSG ? BinMsg : Response; + conn.emit( + 'message', + new ResponseConstructor( + conn.bson, + message, + msgHeader, + message.slice(MESSAGE_HEADER_SIZE), + conn.responseOptions + ), + conn + ); + + return; + } + + msgHeader.fromCompressed = true; + let index = MESSAGE_HEADER_SIZE; + msgHeader.opCode = message.readInt32LE(index); + index += 4; + msgHeader.length = message.readInt32LE(index); + index += 4; + const compressorID = message[index]; + index++; + + decompress(compressorID, message.slice(index), (err, decompressedMsgBody) => { + if (err) { + conn.emit('error', err); + return; + } + + if (decompressedMsgBody.length !== msgHeader.length) { + conn.emit( + 'error', + new MongoError( + 'Decompressing a compressed message from the server failed. The message is corrupt.' + ) + ); + + return; + } + + const ResponseConstructor = msgHeader.opCode === OP_MSG ? BinMsg : Response; + conn.emit( + 'message', + new ResponseConstructor( + conn.bson, + message, + msgHeader, + decompressedMsgBody, + conn.responseOptions + ), + conn + ); + }); +} + +function dataHandler(conn) { + return function(data) { + // Parse until we are done with the data + while (data.length > 0) { + // If we still have bytes to read on the current message + if (conn.bytesRead > 0 && conn.sizeOfMessage > 0) { + // Calculate the amount of remaining bytes + const remainingBytesToRead = conn.sizeOfMessage - conn.bytesRead; + // Check if the current chunk contains the rest of the message + if (remainingBytesToRead > data.length) { + // Copy the new data into the exiting buffer (should have been allocated when we know the message size) + data.copy(conn.buffer, conn.bytesRead); + // Adjust the number of bytes read so it point to the correct index in the buffer + conn.bytesRead = conn.bytesRead + data.length; + + // Reset state of buffer + data = Buffer.alloc(0); + } else { + // Copy the missing part of the data into our current buffer + data.copy(conn.buffer, conn.bytesRead, 0, remainingBytesToRead); + // Slice the overflow into a new buffer that we will then re-parse + data = data.slice(remainingBytesToRead); + + // Emit current complete message + const emitBuffer = conn.buffer; + // Reset state of buffer + conn.buffer = null; + conn.sizeOfMessage = 0; + conn.bytesRead = 0; + conn.stubBuffer = null; + + processMessage(conn, emitBuffer); + } + } else { + // Stub buffer is kept in case we don't get enough bytes to determine the + // size of the message (< 4 bytes) + if (conn.stubBuffer != null && conn.stubBuffer.length > 0) { + // If we have enough bytes to determine the message size let's do it + if (conn.stubBuffer.length + data.length > 4) { + // Prepad the data + const newData = Buffer.alloc(conn.stubBuffer.length + data.length); + conn.stubBuffer.copy(newData, 0); + data.copy(newData, conn.stubBuffer.length); + // Reassign for parsing + data = newData; + + // Reset state of buffer + conn.buffer = null; + conn.sizeOfMessage = 0; + conn.bytesRead = 0; + conn.stubBuffer = null; + } else { + // Add the the bytes to the stub buffer + const newStubBuffer = Buffer.alloc(conn.stubBuffer.length + data.length); + // Copy existing stub buffer + conn.stubBuffer.copy(newStubBuffer, 0); + // Copy missing part of the data + data.copy(newStubBuffer, conn.stubBuffer.length); + // Exit parsing loop + data = Buffer.alloc(0); + } + } else { + if (data.length > 4) { + // Retrieve the message size + const sizeOfMessage = data[0] | (data[1] << 8) | (data[2] << 16) | (data[3] << 24); + // If we have a negative sizeOfMessage emit error and return + if (sizeOfMessage < 0 || sizeOfMessage > conn.maxBsonMessageSize) { + const errorObject = { + err: 'socketHandler', + trace: '', + bin: conn.buffer, + parseState: { + sizeOfMessage: sizeOfMessage, + bytesRead: conn.bytesRead, + stubBuffer: conn.stubBuffer + } + }; + // We got a parse Error fire it off then keep going + conn.emit('parseError', errorObject, conn); + return; + } + + // Ensure that the size of message is larger than 0 and less than the max allowed + if ( + sizeOfMessage > 4 && + sizeOfMessage < conn.maxBsonMessageSize && + sizeOfMessage > data.length + ) { + conn.buffer = Buffer.alloc(sizeOfMessage); + // Copy all the data into the buffer + data.copy(conn.buffer, 0); + // Update bytes read + conn.bytesRead = data.length; + // Update sizeOfMessage + conn.sizeOfMessage = sizeOfMessage; + // Ensure stub buffer is null + conn.stubBuffer = null; + // Exit parsing loop + data = Buffer.alloc(0); + } else if ( + sizeOfMessage > 4 && + sizeOfMessage < conn.maxBsonMessageSize && + sizeOfMessage === data.length + ) { + const emitBuffer = data; + // Reset state of buffer + conn.buffer = null; + conn.sizeOfMessage = 0; + conn.bytesRead = 0; + conn.stubBuffer = null; + // Exit parsing loop + data = Buffer.alloc(0); + // Emit the message + processMessage(conn, emitBuffer); + } else if (sizeOfMessage <= 4 || sizeOfMessage > conn.maxBsonMessageSize) { + const errorObject = { + err: 'socketHandler', + trace: null, + bin: data, + parseState: { + sizeOfMessage: sizeOfMessage, + bytesRead: 0, + buffer: null, + stubBuffer: null + } + }; + // We got a parse Error fire it off then keep going + conn.emit('parseError', errorObject, conn); + + // Clear out the state of the parser + conn.buffer = null; + conn.sizeOfMessage = 0; + conn.bytesRead = 0; + conn.stubBuffer = null; + // Exit parsing loop + data = Buffer.alloc(0); + } else { + const emitBuffer = data.slice(0, sizeOfMessage); + // Reset state of buffer + conn.buffer = null; + conn.sizeOfMessage = 0; + conn.bytesRead = 0; + conn.stubBuffer = null; + // Copy rest of message + data = data.slice(sizeOfMessage); + // Emit the message + processMessage(conn, emitBuffer); + } + } else { + // Create a buffer that contains the space for the non-complete message + conn.stubBuffer = Buffer.alloc(data.length); + // Copy the data to the stub buffer + data.copy(conn.stubBuffer, 0); + // Exit parsing loop + data = Buffer.alloc(0); + } + } + } + } + }; +} + +/** + * A server connect event, used to verify that the connection is up and running + * + * @event Connection#connect + * @type {Connection} + */ + +/** + * The server connection closed, all pool connections closed + * + * @event Connection#close + * @type {Connection} + */ + +/** + * The server connection caused an error, all pool connections closed + * + * @event Connection#error + * @type {Connection} + */ + +/** + * The server connection timed out, all pool connections closed + * + * @event Connection#timeout + * @type {Connection} + */ + +/** + * The driver experienced an invalid message, all pool connections closed + * + * @event Connection#parseError + * @type {Connection} + */ + +/** + * An event emitted each time the connection receives a parsed message from the wire + * + * @event Connection#message + * @type {Connection} + */ + +module.exports = Connection; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/connection/logger.js b/scripts/2.5/node_modules/mongodb/lib/core/connection/logger.js new file mode 100644 index 00000000..eb11e43d --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/core/connection/logger.js @@ -0,0 +1,246 @@ +'use strict'; + +var f = require('util').format, + MongoError = require('../error').MongoError; + +// Filters for classes +var classFilters = {}; +var filteredClasses = {}; +var level = null; +// Save the process id +var pid = process.pid; +// current logger +var currentLogger = null; + +/** + * Creates a new Logger instance + * @class + * @param {string} className The Class name associated with the logging instance + * @param {object} [options=null] Optional settings. + * @param {Function} [options.logger=null] Custom logger function; + * @param {string} [options.loggerLevel=error] Override default global log level. + * @return {Logger} a Logger instance. + */ +var Logger = function(className, options) { + if (!(this instanceof Logger)) return new Logger(className, options); + options = options || {}; + + // Current reference + this.className = className; + + // Current logger + if (options.logger) { + currentLogger = options.logger; + } else if (currentLogger == null) { + currentLogger = console.log; + } + + // Set level of logging, default is error + if (options.loggerLevel) { + level = options.loggerLevel || 'error'; + } + + // Add all class names + if (filteredClasses[this.className] == null) classFilters[this.className] = true; +}; + +/** + * Log a message at the debug level + * @method + * @param {string} message The message to log + * @param {object} object additional meta data to log + * @return {null} + */ +Logger.prototype.debug = function(message, object) { + if ( + this.isDebug() && + ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) || + (Object.keys(filteredClasses).length === 0 && classFilters[this.className])) + ) { + var dateTime = new Date().getTime(); + var msg = f('[%s-%s:%s] %s %s', 'DEBUG', this.className, pid, dateTime, message); + var state = { + type: 'debug', + message: message, + className: this.className, + pid: pid, + date: dateTime + }; + if (object) state.meta = object; + currentLogger(msg, state); + } +}; + +/** + * Log a message at the warn level + * @method + * @param {string} message The message to log + * @param {object} object additional meta data to log + * @return {null} + */ +(Logger.prototype.warn = function(message, object) { + if ( + this.isWarn() && + ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) || + (Object.keys(filteredClasses).length === 0 && classFilters[this.className])) + ) { + var dateTime = new Date().getTime(); + var msg = f('[%s-%s:%s] %s %s', 'WARN', this.className, pid, dateTime, message); + var state = { + type: 'warn', + message: message, + className: this.className, + pid: pid, + date: dateTime + }; + if (object) state.meta = object; + currentLogger(msg, state); + } +}), + /** + * Log a message at the info level + * @method + * @param {string} message The message to log + * @param {object} object additional meta data to log + * @return {null} + */ + (Logger.prototype.info = function(message, object) { + if ( + this.isInfo() && + ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) || + (Object.keys(filteredClasses).length === 0 && classFilters[this.className])) + ) { + var dateTime = new Date().getTime(); + var msg = f('[%s-%s:%s] %s %s', 'INFO', this.className, pid, dateTime, message); + var state = { + type: 'info', + message: message, + className: this.className, + pid: pid, + date: dateTime + }; + if (object) state.meta = object; + currentLogger(msg, state); + } + }), + /** + * Log a message at the error level + * @method + * @param {string} message The message to log + * @param {object} object additional meta data to log + * @return {null} + */ + (Logger.prototype.error = function(message, object) { + if ( + this.isError() && + ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) || + (Object.keys(filteredClasses).length === 0 && classFilters[this.className])) + ) { + var dateTime = new Date().getTime(); + var msg = f('[%s-%s:%s] %s %s', 'ERROR', this.className, pid, dateTime, message); + var state = { + type: 'error', + message: message, + className: this.className, + pid: pid, + date: dateTime + }; + if (object) state.meta = object; + currentLogger(msg, state); + } + }), + /** + * Is the logger set at info level + * @method + * @return {boolean} + */ + (Logger.prototype.isInfo = function() { + return level === 'info' || level === 'debug'; + }), + /** + * Is the logger set at error level + * @method + * @return {boolean} + */ + (Logger.prototype.isError = function() { + return level === 'error' || level === 'info' || level === 'debug'; + }), + /** + * Is the logger set at error level + * @method + * @return {boolean} + */ + (Logger.prototype.isWarn = function() { + return level === 'error' || level === 'warn' || level === 'info' || level === 'debug'; + }), + /** + * Is the logger set at debug level + * @method + * @return {boolean} + */ + (Logger.prototype.isDebug = function() { + return level === 'debug'; + }); + +/** + * Resets the logger to default settings, error and no filtered classes + * @method + * @return {null} + */ +Logger.reset = function() { + level = 'error'; + filteredClasses = {}; +}; + +/** + * Get the current logger function + * @method + * @return {function} + */ +Logger.currentLogger = function() { + return currentLogger; +}; + +/** + * Set the current logger function + * @method + * @param {function} logger Logger function. + * @return {null} + */ +Logger.setCurrentLogger = function(logger) { + if (typeof logger !== 'function') throw new MongoError('current logger must be a function'); + currentLogger = logger; +}; + +/** + * Set what classes to log. + * @method + * @param {string} type The type of filter (currently only class) + * @param {string[]} values The filters to apply + * @return {null} + */ +Logger.filter = function(type, values) { + if (type === 'class' && Array.isArray(values)) { + filteredClasses = {}; + + values.forEach(function(x) { + filteredClasses[x] = true; + }); + } +}; + +/** + * Set the current log level + * @method + * @param {string} level Set current log level (debug, info, error) + * @return {null} + */ +Logger.setLevel = function(_level) { + if (_level !== 'info' && _level !== 'error' && _level !== 'debug' && _level !== 'warn') { + throw new Error(f('%s is an illegal logging level', _level)); + } + + level = _level; +}; + +module.exports = Logger; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/connection/msg.js b/scripts/2.5/node_modules/mongodb/lib/core/connection/msg.js new file mode 100644 index 00000000..7bee3c5e --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/core/connection/msg.js @@ -0,0 +1,221 @@ +'use strict'; + +// Implementation of OP_MSG spec: +// https://github.com/mongodb/specifications/blob/master/source/message/OP_MSG.rst +// +// struct Section { +// uint8 payloadType; +// union payload { +// document document; // payloadType == 0 +// struct sequence { // payloadType == 1 +// int32 size; +// cstring identifier; +// document* documents; +// }; +// }; +// }; + +// struct OP_MSG { +// struct MsgHeader { +// int32 messageLength; +// int32 requestID; +// int32 responseTo; +// int32 opCode = 2013; +// }; +// uint32 flagBits; +// Section+ sections; +// [uint32 checksum;] +// }; + +const Buffer = require('safe-buffer').Buffer; +const opcodes = require('../wireprotocol/shared').opcodes; +const databaseNamespace = require('../wireprotocol/shared').databaseNamespace; +const ReadPreference = require('../topologies/read_preference'); + +// Incrementing request id +let _requestId = 0; + +// Msg Flags +const OPTS_CHECKSUM_PRESENT = 1; +const OPTS_MORE_TO_COME = 2; +const OPTS_EXHAUST_ALLOWED = 1 << 16; + +class Msg { + constructor(bson, ns, command, options) { + // Basic options needed to be passed in + if (command == null) throw new Error('query must be specified for query'); + + // Basic options + this.bson = bson; + this.ns = ns; + this.command = command; + this.command.$db = databaseNamespace(ns); + + if (options.readPreference && options.readPreference.mode !== ReadPreference.PRIMARY) { + this.command.$readPreference = options.readPreference.toJSON(); + } + + // Ensure empty options + this.options = options || {}; + + // Additional options + this.requestId = Msg.getRequestId(); + + // Serialization option + this.serializeFunctions = + typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + this.ignoreUndefined = + typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : false; + this.checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; + this.maxBsonSize = options.maxBsonSize || 1024 * 1024 * 16; + + // flags + this.checksumPresent = false; + this.moreToCome = options.moreToCome || false; + this.exhaustAllowed = false; + } + + toBin() { + const buffers = []; + let flags = 0; + + if (this.checksumPresent) { + flags |= OPTS_CHECKSUM_PRESENT; + } + + if (this.moreToCome) { + flags |= OPTS_MORE_TO_COME; + } + + if (this.exhaustAllowed) { + flags |= OPTS_EXHAUST_ALLOWED; + } + + const header = Buffer.alloc( + 4 * 4 + // Header + 4 // Flags + ); + + buffers.push(header); + + let totalLength = header.length; + const command = this.command; + totalLength += this.makeDocumentSegment(buffers, command); + + header.writeInt32LE(totalLength, 0); // messageLength + header.writeInt32LE(this.requestId, 4); // requestID + header.writeInt32LE(0, 8); // responseTo + header.writeInt32LE(opcodes.OP_MSG, 12); // opCode + header.writeUInt32LE(flags, 16); // flags + return buffers; + } + + makeDocumentSegment(buffers, document) { + const payloadTypeBuffer = Buffer.alloc(1); + payloadTypeBuffer[0] = 0; + + const documentBuffer = this.serializeBson(document); + buffers.push(payloadTypeBuffer); + buffers.push(documentBuffer); + + return payloadTypeBuffer.length + documentBuffer.length; + } + + serializeBson(document) { + return this.bson.serialize(document, { + checkKeys: this.checkKeys, + serializeFunctions: this.serializeFunctions, + ignoreUndefined: this.ignoreUndefined + }); + } +} + +Msg.getRequestId = function() { + _requestId = (_requestId + 1) & 0x7fffffff; + return _requestId; +}; + +class BinMsg { + constructor(bson, message, msgHeader, msgBody, opts) { + opts = opts || { promoteLongs: true, promoteValues: true, promoteBuffers: false }; + this.parsed = false; + this.raw = message; + this.data = msgBody; + this.bson = bson; + this.opts = opts; + + // Read the message header + this.length = msgHeader.length; + this.requestId = msgHeader.requestId; + this.responseTo = msgHeader.responseTo; + this.opCode = msgHeader.opCode; + this.fromCompressed = msgHeader.fromCompressed; + + // Read response flags + this.responseFlags = msgBody.readInt32LE(0); + this.checksumPresent = (this.responseFlags & OPTS_CHECKSUM_PRESENT) !== 0; + this.moreToCome = (this.responseFlags & OPTS_MORE_TO_COME) !== 0; + this.exhaustAllowed = (this.responseFlags & OPTS_EXHAUST_ALLOWED) !== 0; + this.promoteLongs = typeof opts.promoteLongs === 'boolean' ? opts.promoteLongs : true; + this.promoteValues = typeof opts.promoteValues === 'boolean' ? opts.promoteValues : true; + this.promoteBuffers = typeof opts.promoteBuffers === 'boolean' ? opts.promoteBuffers : false; + + this.documents = []; + } + + isParsed() { + return this.parsed; + } + + parse(options) { + // Don't parse again if not needed + if (this.parsed) return; + options = options || {}; + + this.index = 4; + // Allow the return of raw documents instead of parsing + const raw = options.raw || false; + const documentsReturnedIn = options.documentsReturnedIn || null; + const promoteLongs = + typeof options.promoteLongs === 'boolean' ? options.promoteLongs : this.opts.promoteLongs; + const promoteValues = + typeof options.promoteValues === 'boolean' ? options.promoteValues : this.opts.promoteValues; + const promoteBuffers = + typeof options.promoteBuffers === 'boolean' + ? options.promoteBuffers + : this.opts.promoteBuffers; + + // Set up the options + const _options = { + promoteLongs: promoteLongs, + promoteValues: promoteValues, + promoteBuffers: promoteBuffers + }; + + while (this.index < this.data.length) { + const payloadType = this.data.readUInt8(this.index++); + if (payloadType === 1) { + console.error('TYPE 1'); + } else if (payloadType === 0) { + const bsonSize = this.data.readUInt32LE(this.index); + const bin = this.data.slice(this.index, this.index + bsonSize); + this.documents.push(raw ? bin : this.bson.deserialize(bin, _options)); + + this.index += bsonSize; + } + } + + if (this.documents.length === 1 && documentsReturnedIn != null && raw) { + const fieldsAsRaw = {}; + fieldsAsRaw[documentsReturnedIn] = true; + _options.fieldsAsRaw = fieldsAsRaw; + + const doc = this.bson.deserialize(this.documents[0], _options); + this.documents = [doc]; + } + + this.parsed = true; + } +} + +module.exports = { Msg, BinMsg }; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/connection/pool.js b/scripts/2.5/node_modules/mongodb/lib/core/connection/pool.js new file mode 100644 index 00000000..adc85900 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/core/connection/pool.js @@ -0,0 +1,1256 @@ +'use strict'; + +const inherits = require('util').inherits; +const EventEmitter = require('events').EventEmitter; +const MongoError = require('../error').MongoError; +const MongoTimeoutError = require('../error').MongoTimeoutError; +const MongoWriteConcernError = require('../error').MongoWriteConcernError; +const Logger = require('./logger'); +const f = require('util').format; +const Msg = require('./msg').Msg; +const CommandResult = require('./command_result'); +const MESSAGE_HEADER_SIZE = require('../wireprotocol/shared').MESSAGE_HEADER_SIZE; +const COMPRESSION_DETAILS_SIZE = require('../wireprotocol/shared').COMPRESSION_DETAILS_SIZE; +const opcodes = require('../wireprotocol/shared').opcodes; +const compress = require('../wireprotocol/compression').compress; +const compressorIDs = require('../wireprotocol/compression').compressorIDs; +const uncompressibleCommands = require('../wireprotocol/compression').uncompressibleCommands; +const apm = require('./apm'); +const Buffer = require('safe-buffer').Buffer; +const connect = require('./connect'); +const updateSessionFromResponse = require('../sessions').updateSessionFromResponse; +const eachAsync = require('../utils').eachAsync; + +var DISCONNECTED = 'disconnected'; +var CONNECTING = 'connecting'; +var CONNECTED = 'connected'; +var DESTROYING = 'destroying'; +var DESTROYED = 'destroyed'; + +const CONNECTION_EVENTS = new Set([ + 'error', + 'close', + 'timeout', + 'parseError', + 'connect', + 'message' +]); + +var _id = 0; + +/** + * Creates a new Pool instance + * @class + * @param {string} options.host The server host + * @param {number} options.port The server port + * @param {number} [options.size=5] Max server connection pool size + * @param {number} [options.minSize=0] Minimum server connection pool size + * @param {boolean} [options.reconnect=true] Server will attempt to reconnect on loss of connection + * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times + * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries + * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled + * @param {number} [options.keepAliveInitialDelay=300000] Initial delay before TCP keep alive enabled + * @param {boolean} [options.noDelay=true] TCP Connection no delay + * @param {number} [options.connectionTimeout=30000] TCP Connection timeout setting + * @param {number} [options.socketTimeout=360000] TCP Socket timeout setting + * @param {number} [options.monitoringSocketTimeout=30000] TCP Socket timeout setting for replicaset monitoring socket + * @param {boolean} [options.ssl=false] Use SSL for connection + * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. + * @param {Buffer} [options.ca] SSL Certificate store binary buffer + * @param {Buffer} [options.crl] SSL Certificate revocation store binary buffer + * @param {Buffer} [options.cert] SSL Certificate binary buffer + * @param {Buffer} [options.key] SSL Key file binary buffer + * @param {string} [options.passphrase] SSL Certificate pass phrase + * @param {boolean} [options.rejectUnauthorized=false] Reject unauthorized server certificates + * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits + * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. + * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. + * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. + * @fires Pool#connect + * @fires Pool#close + * @fires Pool#error + * @fires Pool#timeout + * @fires Pool#parseError + * @return {Pool} A cursor instance + */ +var Pool = function(topology, options) { + // Add event listener + EventEmitter.call(this); + + // Store topology for later use + this.topology = topology; + + // Add the options + this.options = Object.assign( + { + // Host and port settings + host: 'localhost', + port: 27017, + // Pool default max size + size: 5, + // Pool default min size + minSize: 0, + // socket settings + connectionTimeout: 30000, + socketTimeout: 360000, + keepAlive: true, + keepAliveInitialDelay: 300000, + noDelay: true, + // SSL Settings + ssl: false, + checkServerIdentity: true, + ca: null, + crl: null, + cert: null, + key: null, + passphrase: null, + rejectUnauthorized: false, + promoteLongs: true, + promoteValues: true, + promoteBuffers: false, + // Reconnection options + reconnect: true, + reconnectInterval: 1000, + reconnectTries: 30, + // Enable domains + domainsEnabled: false, + // feature flag for determining if we are running with the unified topology or not + legacyCompatMode: true + }, + options + ); + + // Identification information + this.id = _id++; + // Current reconnect retries + this.retriesLeft = this.options.reconnectTries; + this.reconnectId = null; + this.reconnectError = null; + // No bson parser passed in + if ( + !options.bson || + (options.bson && + (typeof options.bson.serialize !== 'function' || + typeof options.bson.deserialize !== 'function')) + ) { + throw new Error('must pass in valid bson parser'); + } + + // Logger instance + this.logger = Logger('Pool', options); + // Pool state + this.state = DISCONNECTED; + // Connections + this.availableConnections = []; + this.inUseConnections = []; + this.connectingConnections = 0; + // Currently executing + this.executing = false; + // Operation work queue + this.queue = []; + + // Number of consecutive timeouts caught + this.numberOfConsecutiveTimeouts = 0; + // Current pool Index + this.connectionIndex = 0; + + // event handlers + const pool = this; + this._messageHandler = messageHandler(this); + this._connectionCloseHandler = function(err) { + const connection = this; + connectionFailureHandler(pool, 'close', err, connection); + }; + + this._connectionErrorHandler = function(err) { + const connection = this; + connectionFailureHandler(pool, 'error', err, connection); + }; + + this._connectionTimeoutHandler = function(err) { + const connection = this; + connectionFailureHandler(pool, 'timeout', err, connection); + }; + + this._connectionParseErrorHandler = function(err) { + const connection = this; + connectionFailureHandler(pool, 'parseError', err, connection); + }; +}; + +inherits(Pool, EventEmitter); + +Object.defineProperty(Pool.prototype, 'size', { + enumerable: true, + get: function() { + return this.options.size; + } +}); + +Object.defineProperty(Pool.prototype, 'minSize', { + enumerable: true, + get: function() { + return this.options.minSize; + } +}); + +Object.defineProperty(Pool.prototype, 'connectionTimeout', { + enumerable: true, + get: function() { + return this.options.connectionTimeout; + } +}); + +Object.defineProperty(Pool.prototype, 'socketTimeout', { + enumerable: true, + get: function() { + return this.options.socketTimeout; + } +}); + +// clears all pool state +function resetPoolState(pool) { + pool.inUseConnections = []; + pool.availableConnections = []; + pool.connectingConnections = 0; + pool.executing = false; + pool.numberOfConsecutiveTimeouts = 0; + pool.connectionIndex = 0; + pool.retriesLeft = pool.options.reconnectTries; + pool.reconnectId = null; +} + +function stateTransition(self, newState) { + var legalTransitions = { + disconnected: [CONNECTING, DESTROYING, DISCONNECTED], + connecting: [CONNECTING, DESTROYING, CONNECTED, DISCONNECTED], + connected: [CONNECTED, DISCONNECTED, DESTROYING], + destroying: [DESTROYING, DESTROYED], + destroyed: [DESTROYED] + }; + + // Get current state + var legalStates = legalTransitions[self.state]; + if (legalStates && legalStates.indexOf(newState) !== -1) { + self.emit('stateChanged', self.state, newState); + self.state = newState; + } else { + self.logger.error( + f( + 'Pool with id [%s] failed attempted illegal state transition from [%s] to [%s] only following state allowed [%s]', + self.id, + self.state, + newState, + legalStates + ) + ); + } +} + +function connectionFailureHandler(pool, event, err, conn) { + if (conn) { + if (conn._connectionFailHandled) return; + conn._connectionFailHandled = true; + conn.destroy(); + + // Remove the connection + removeConnection(pool, conn); + + // Flush all work Items on this connection + while (conn.workItems.length > 0) { + const workItem = conn.workItems.shift(); + if (workItem.cb) workItem.cb(err); + } + } + + // Did we catch a timeout, increment the numberOfConsecutiveTimeouts + if (event === 'timeout') { + pool.numberOfConsecutiveTimeouts = pool.numberOfConsecutiveTimeouts + 1; + + // Have we timed out more than reconnectTries in a row ? + // Force close the pool as we are trying to connect to tcp sink hole + if (pool.numberOfConsecutiveTimeouts > pool.options.reconnectTries) { + pool.numberOfConsecutiveTimeouts = 0; + // Destroy all connections and pool + pool.destroy(true); + // Emit close event + return pool.emit('close', pool); + } + } + + // No more socket available propegate the event + if (pool.socketCount() === 0) { + if (pool.state !== DESTROYED && pool.state !== DESTROYING) { + stateTransition(pool, DISCONNECTED); + } + + // Do not emit error events, they are always close events + // do not trigger the low level error handler in node + event = event === 'error' ? 'close' : event; + pool.emit(event, err); + } + + // Start reconnection attempts + if (!pool.reconnectId && pool.options.reconnect) { + pool.reconnectError = err; + pool.reconnectId = setTimeout(attemptReconnect(pool), pool.options.reconnectInterval); + } + + // Do we need to do anything to maintain the minimum pool size + const totalConnections = totalConnectionCount(pool); + if (totalConnections < pool.minSize) { + createConnection(pool); + } +} + +function attemptReconnect(pool, callback) { + return function() { + pool.emit('attemptReconnect', pool); + + if (pool.state === DESTROYED || pool.state === DESTROYING) { + if (typeof callback === 'function') { + callback(new MongoError('Cannot create connection when pool is destroyed')); + } + + return; + } + + pool.retriesLeft = pool.retriesLeft - 1; + if (pool.retriesLeft <= 0) { + pool.destroy(); + + const error = new MongoTimeoutError( + `failed to reconnect after ${pool.options.reconnectTries} attempts with interval ${ + pool.options.reconnectInterval + } ms`, + pool.reconnectError + ); + + pool.emit('reconnectFailed', error); + if (typeof callback === 'function') { + callback(error); + } + + return; + } + + // clear the reconnect id on retry + pool.reconnectId = null; + + // now retry creating a connection + createConnection(pool, (err, conn) => { + if (err == null) { + pool.reconnectId = null; + pool.retriesLeft = pool.options.reconnectTries; + pool.emit('reconnect', pool); + } + + if (typeof callback === 'function') { + callback(err, conn); + } + }); + }; +} + +function moveConnectionBetween(connection, from, to) { + var index = from.indexOf(connection); + // Move the connection from connecting to available + if (index !== -1) { + from.splice(index, 1); + to.push(connection); + } +} + +function messageHandler(self) { + return function(message, connection) { + // workItem to execute + var workItem = null; + + // Locate the workItem + for (var i = 0; i < connection.workItems.length; i++) { + if (connection.workItems[i].requestId === message.responseTo) { + // Get the callback + workItem = connection.workItems[i]; + // Remove from list of workItems + connection.workItems.splice(i, 1); + } + } + + if (workItem && workItem.monitoring) { + moveConnectionBetween(connection, self.inUseConnections, self.availableConnections); + } + + // Reset timeout counter + self.numberOfConsecutiveTimeouts = 0; + + // Reset the connection timeout if we modified it for + // this operation + if (workItem && workItem.socketTimeout) { + connection.resetSocketTimeout(); + } + + // Log if debug enabled + if (self.logger.isDebug()) { + self.logger.debug( + f( + 'message [%s] received from %s:%s', + message.raw.toString('hex'), + self.options.host, + self.options.port + ) + ); + } + + function handleOperationCallback(self, cb, err, result) { + // No domain enabled + if (!self.options.domainsEnabled) { + return process.nextTick(function() { + return cb(err, result); + }); + } + + // Domain enabled just call the callback + cb(err, result); + } + + // Keep executing, ensure current message handler does not stop execution + if (!self.executing) { + process.nextTick(function() { + _execute(self)(); + }); + } + + // Time to dispatch the message if we have a callback + if (workItem && !workItem.immediateRelease) { + try { + // Parse the message according to the provided options + message.parse(workItem); + } catch (err) { + return handleOperationCallback(self, workItem.cb, new MongoError(err)); + } + + if (message.documents[0]) { + const document = message.documents[0]; + const session = workItem.session; + if (session) { + updateSessionFromResponse(session, document); + } + + if (document.$clusterTime) { + self.topology.clusterTime = document.$clusterTime; + } + } + + // Establish if we have an error + if (workItem.command && message.documents[0]) { + const responseDoc = message.documents[0]; + + if (responseDoc.writeConcernError) { + const err = new MongoWriteConcernError(responseDoc.writeConcernError, responseDoc); + return handleOperationCallback(self, workItem.cb, err); + } + + if (responseDoc.ok === 0 || responseDoc.$err || responseDoc.errmsg || responseDoc.code) { + return handleOperationCallback(self, workItem.cb, new MongoError(responseDoc)); + } + } + + // Add the connection details + message.hashedName = connection.hashedName; + + // Return the documents + handleOperationCallback( + self, + workItem.cb, + null, + new CommandResult(workItem.fullResult ? message : message.documents[0], connection, message) + ); + } + }; +} + +/** + * Return the total socket count in the pool. + * @method + * @return {Number} The number of socket available. + */ +Pool.prototype.socketCount = function() { + return this.availableConnections.length + this.inUseConnections.length; + // + this.connectingConnections.length; +}; + +function totalConnectionCount(pool) { + return ( + pool.availableConnections.length + pool.inUseConnections.length + pool.connectingConnections + ); +} + +/** + * Return all pool connections + * @method + * @return {Connection[]} The pool connections + */ +Pool.prototype.allConnections = function() { + return this.availableConnections.concat(this.inUseConnections); +}; + +/** + * Get a pool connection (round-robin) + * @method + * @return {Connection} + */ +Pool.prototype.get = function() { + return this.allConnections()[0]; +}; + +/** + * Is the pool connected + * @method + * @return {boolean} + */ +Pool.prototype.isConnected = function() { + // We are in a destroyed state + if (this.state === DESTROYED || this.state === DESTROYING) { + return false; + } + + // Get connections + var connections = this.availableConnections.concat(this.inUseConnections); + + // Check if we have any connected connections + for (var i = 0; i < connections.length; i++) { + if (connections[i].isConnected()) return true; + } + + // Not connected + return false; +}; + +/** + * Was the pool destroyed + * @method + * @return {boolean} + */ +Pool.prototype.isDestroyed = function() { + return this.state === DESTROYED || this.state === DESTROYING; +}; + +/** + * Is the pool in a disconnected state + * @method + * @return {boolean} + */ +Pool.prototype.isDisconnected = function() { + return this.state === DISCONNECTED; +}; + +/** + * Connect pool + */ +Pool.prototype.connect = function() { + if (this.state !== DISCONNECTED) { + throw new MongoError('connection in unlawful state ' + this.state); + } + + stateTransition(this, CONNECTING); + createConnection(this, (err, conn) => { + if (err) { + if (this.state === CONNECTING) { + this.emit('error', err); + } + + this.destroy(); + return; + } + + stateTransition(this, CONNECTED); + this.emit('connect', this, conn); + + // create min connections + if (this.minSize) { + for (let i = 0; i < this.minSize; i++) { + createConnection(this); + } + } + }); +}; + +/** + * Authenticate using a specified mechanism + * @param {authResultCallback} callback A callback function + */ +Pool.prototype.auth = function(credentials, callback) { + if (typeof callback === 'function') callback(null, null); +}; + +/** + * Logout all users against a database + * @param {authResultCallback} callback A callback function + */ +Pool.prototype.logout = function(dbName, callback) { + if (typeof callback === 'function') callback(null, null); +}; + +/** + * Unref the pool + * @method + */ +Pool.prototype.unref = function() { + // Get all the known connections + var connections = this.availableConnections.concat(this.inUseConnections); + + connections.forEach(function(c) { + c.unref(); + }); +}; + +// Destroy the connections +function destroy(self, connections, options, callback) { + eachAsync( + connections, + (conn, cb) => { + for (const eventName of CONNECTION_EVENTS) { + conn.removeAllListeners(eventName); + } + + conn.destroy(options, cb); + }, + err => { + if (err) { + if (typeof callback === 'function') callback(err, null); + return; + } + + resetPoolState(self); + self.queue = []; + + stateTransition(self, DESTROYED); + if (typeof callback === 'function') callback(null, null); + } + ); +} + +/** + * Destroy pool + * @method + */ +Pool.prototype.destroy = function(force, callback) { + var self = this; + // Do not try again if the pool is already dead + if (this.state === DESTROYED || self.state === DESTROYING) { + if (typeof callback === 'function') callback(null, null); + return; + } + + // Set state to destroyed + stateTransition(this, DESTROYING); + + // Are we force closing + if (force) { + // Get all the known connections + var connections = self.availableConnections.concat(self.inUseConnections); + + // Flush any remaining work items with + // an error + while (self.queue.length > 0) { + var workItem = self.queue.shift(); + if (typeof workItem.cb === 'function') { + workItem.cb(new MongoError('Pool was force destroyed')); + } + } + + // Destroy the topology + return destroy(self, connections, { force: true }, callback); + } + + // Clear out the reconnect if set + if (this.reconnectId) { + clearTimeout(this.reconnectId); + } + + // Wait for the operations to drain before we close the pool + function checkStatus() { + flushMonitoringOperations(self.queue); + + if (self.queue.length === 0) { + // Get all the known connections + var connections = self.availableConnections.concat(self.inUseConnections); + + // Check if we have any in flight operations + for (var i = 0; i < connections.length; i++) { + // There is an operation still in flight, reschedule a + // check waiting for it to drain + if (connections[i].workItems.length > 0) { + return setTimeout(checkStatus, 1); + } + } + + destroy(self, connections, { force: false }, callback); + // } else if (self.queue.length > 0 && !this.reconnectId) { + } else { + // Ensure we empty the queue + _execute(self)(); + // Set timeout + setTimeout(checkStatus, 1); + } + } + + // Initiate drain of operations + checkStatus(); +}; + +/** + * Reset all connections of this pool + * + * @param {function} [callback] + */ +Pool.prototype.reset = function(callback) { + const connections = this.availableConnections.concat(this.inUseConnections); + eachAsync( + connections, + (conn, cb) => { + for (const eventName of CONNECTION_EVENTS) { + conn.removeAllListeners(eventName); + } + + conn.destroy({ force: true }, cb); + }, + err => { + if (err) { + if (typeof callback === 'function') { + callback(err, null); + return; + } + } + + resetPoolState(this); + + // create an initial connection, and kick off execution again + createConnection(this); + + if (typeof callback === 'function') { + callback(null, null); + } + } + ); +}; + +// Prepare the buffer that Pool.prototype.write() uses to send to the server +function serializeCommand(self, command, callback) { + const originalCommandBuffer = command.toBin(); + + // Check whether we and the server have agreed to use a compressor + const shouldCompress = !!self.options.agreedCompressor; + if (!shouldCompress || !canCompress(command)) { + return callback(null, originalCommandBuffer); + } + + // Transform originalCommandBuffer into OP_COMPRESSED + const concatenatedOriginalCommandBuffer = Buffer.concat(originalCommandBuffer); + const messageToBeCompressed = concatenatedOriginalCommandBuffer.slice(MESSAGE_HEADER_SIZE); + + // Extract information needed for OP_COMPRESSED from the uncompressed message + const originalCommandOpCode = concatenatedOriginalCommandBuffer.readInt32LE(12); + + // Compress the message body + compress(self, messageToBeCompressed, function(err, compressedMessage) { + if (err) return callback(err, null); + + // Create the msgHeader of OP_COMPRESSED + const msgHeader = Buffer.alloc(MESSAGE_HEADER_SIZE); + msgHeader.writeInt32LE( + MESSAGE_HEADER_SIZE + COMPRESSION_DETAILS_SIZE + compressedMessage.length, + 0 + ); // messageLength + msgHeader.writeInt32LE(command.requestId, 4); // requestID + msgHeader.writeInt32LE(0, 8); // responseTo (zero) + msgHeader.writeInt32LE(opcodes.OP_COMPRESSED, 12); // opCode + + // Create the compression details of OP_COMPRESSED + const compressionDetails = Buffer.alloc(COMPRESSION_DETAILS_SIZE); + compressionDetails.writeInt32LE(originalCommandOpCode, 0); // originalOpcode + compressionDetails.writeInt32LE(messageToBeCompressed.length, 4); // Size of the uncompressed compressedMessage, excluding the MsgHeader + compressionDetails.writeUInt8(compressorIDs[self.options.agreedCompressor], 8); // compressorID + + return callback(null, [msgHeader, compressionDetails, compressedMessage]); + }); +} + +/** + * Write a message to MongoDB + * @method + * @return {Connection} + */ +Pool.prototype.write = function(command, options, cb) { + var self = this; + // Ensure we have a callback + if (typeof options === 'function') { + cb = options; + } + + // Always have options + options = options || {}; + + // We need to have a callback function unless the message returns no response + if (!(typeof cb === 'function') && !options.noResponse) { + throw new MongoError('write method must provide a callback'); + } + + // Pool was destroyed error out + if (this.state === DESTROYED || this.state === DESTROYING) { + // Callback with an error + if (cb) { + try { + cb(new MongoError('pool destroyed')); + } catch (err) { + process.nextTick(function() { + throw err; + }); + } + } + + return; + } + + if (this.options.domainsEnabled && process.domain && typeof cb === 'function') { + // if we have a domain bind to it + var oldCb = cb; + cb = process.domain.bind(function() { + // v8 - argumentsToArray one-liner + var args = new Array(arguments.length); + for (var i = 0; i < arguments.length; i++) { + args[i] = arguments[i]; + } + // bounce off event loop so domain switch takes place + process.nextTick(function() { + oldCb.apply(null, args); + }); + }); + } + + // Do we have an operation + var operation = { + cb: cb, + raw: false, + promoteLongs: true, + promoteValues: true, + promoteBuffers: false, + fullResult: false + }; + + // Set the options for the parsing + operation.promoteLongs = typeof options.promoteLongs === 'boolean' ? options.promoteLongs : true; + operation.promoteValues = + typeof options.promoteValues === 'boolean' ? options.promoteValues : true; + operation.promoteBuffers = + typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : false; + operation.raw = typeof options.raw === 'boolean' ? options.raw : false; + operation.immediateRelease = + typeof options.immediateRelease === 'boolean' ? options.immediateRelease : false; + operation.documentsReturnedIn = options.documentsReturnedIn; + operation.command = typeof options.command === 'boolean' ? options.command : false; + operation.fullResult = typeof options.fullResult === 'boolean' ? options.fullResult : false; + operation.noResponse = typeof options.noResponse === 'boolean' ? options.noResponse : false; + operation.session = options.session || null; + + // Optional per operation socketTimeout + operation.socketTimeout = options.socketTimeout; + operation.monitoring = options.monitoring; + // Custom socket Timeout + if (options.socketTimeout) { + operation.socketTimeout = options.socketTimeout; + } + + // Get the requestId + operation.requestId = command.requestId; + + // If command monitoring is enabled we need to modify the callback here + if (self.options.monitorCommands) { + this.emit('commandStarted', new apm.CommandStartedEvent(this, command)); + + operation.started = process.hrtime(); + operation.cb = (err, reply) => { + if (err) { + self.emit( + 'commandFailed', + new apm.CommandFailedEvent(this, command, err, operation.started) + ); + } else { + if (reply && reply.result && (reply.result.ok === 0 || reply.result.$err)) { + self.emit( + 'commandFailed', + new apm.CommandFailedEvent(this, command, reply.result, operation.started) + ); + } else { + self.emit( + 'commandSucceeded', + new apm.CommandSucceededEvent(this, command, reply, operation.started) + ); + } + } + + if (typeof cb === 'function') cb(err, reply); + }; + } + + // Prepare the operation buffer + serializeCommand(self, command, (err, serializedBuffers) => { + if (err) throw err; + + // Set the operation's buffer to the serialization of the commands + operation.buffer = serializedBuffers; + + // If we have a monitoring operation schedule as the very first operation + // Otherwise add to back of queue + if (options.monitoring) { + self.queue.unshift(operation); + } else { + self.queue.push(operation); + } + + // Attempt to execute the operation + if (!self.executing) { + process.nextTick(function() { + _execute(self)(); + }); + } + }); +}; + +// Return whether a command contains an uncompressible command term +// Will return true if command contains no uncompressible command terms +function canCompress(command) { + const commandDoc = command instanceof Msg ? command.command : command.query; + const commandName = Object.keys(commandDoc)[0]; + return uncompressibleCommands.indexOf(commandName) === -1; +} + +// Remove connection method +function remove(connection, connections) { + for (var i = 0; i < connections.length; i++) { + if (connections[i] === connection) { + connections.splice(i, 1); + return true; + } + } +} + +function removeConnection(self, connection) { + if (remove(connection, self.availableConnections)) return; + if (remove(connection, self.inUseConnections)) return; +} + +function createConnection(pool, callback) { + if (pool.state === DESTROYED || pool.state === DESTROYING) { + if (typeof callback === 'function') { + callback(new MongoError('Cannot create connection when pool is destroyed')); + } + + return; + } + + pool.connectingConnections++; + connect(pool.options, (err, connection) => { + pool.connectingConnections--; + + if (err) { + if (pool.logger.isDebug()) { + pool.logger.debug(`connection attempt failed with error [${JSON.stringify(err)}]`); + } + + if (pool.options.legacyCompatMode === false) { + // The unified topology uses the reported `error` from a pool to track what error + // reason is returned to the user during selection timeout. We only want to emit + // this if the pool is active because the listeners are removed on destruction. + if (pool.state !== DESTROYED && pool.state !== DESTROYING) { + pool.emit('error', err); + } + } + + // check if reconnect is enabled, and attempt retry if so + if (!pool.reconnectId && pool.options.reconnect) { + if (pool.state === CONNECTING && pool.options.legacyCompatMode) { + callback(err); + return; + } + + pool.reconnectError = err; + pool.reconnectId = setTimeout( + attemptReconnect(pool, callback), + pool.options.reconnectInterval + ); + + return; + } + + if (typeof callback === 'function') { + callback(err); + } + + return; + } + + // the pool might have been closed since we started creating the connection + if (pool.state === DESTROYED || pool.state === DESTROYING) { + if (typeof callback === 'function') { + callback(new MongoError('Pool was destroyed after connection creation')); + } + + connection.destroy(); + return; + } + + // otherwise, connect relevant event handlers and add it to our available connections + connection.on('error', pool._connectionErrorHandler); + connection.on('close', pool._connectionCloseHandler); + connection.on('timeout', pool._connectionTimeoutHandler); + connection.on('parseError', pool._connectionParseErrorHandler); + connection.on('message', pool._messageHandler); + + pool.availableConnections.push(connection); + + // if a callback was provided, return the connection + if (typeof callback === 'function') { + callback(null, connection); + } + + // immediately execute any waiting work + _execute(pool)(); + }); +} + +function flushMonitoringOperations(queue) { + for (var i = 0; i < queue.length; i++) { + if (queue[i].monitoring) { + var workItem = queue[i]; + queue.splice(i, 1); + workItem.cb( + new MongoError({ message: 'no connection available for monitoring', driver: true }) + ); + } + } +} + +function _execute(self) { + return function() { + if (self.state === DESTROYED) return; + // Already executing, skip + if (self.executing) return; + // Set pool as executing + self.executing = true; + + // New pool connections are in progress, wait them to finish + // before executing any more operation to ensure distribution of + // operations + if (self.connectingConnections > 0) { + self.executing = false; + return; + } + + // As long as we have available connections + // eslint-disable-next-line + while (true) { + // Total availble connections + const totalConnections = totalConnectionCount(self); + + // No available connections available, flush any monitoring ops + if (self.availableConnections.length === 0) { + // Flush any monitoring operations + flushMonitoringOperations(self.queue); + break; + } + + // No queue break + if (self.queue.length === 0) { + break; + } + + var connection = null; + const connections = self.availableConnections.filter(conn => conn.workItems.length === 0); + + // No connection found that has no work on it, just pick one for pipelining + if (connections.length === 0) { + connection = + self.availableConnections[self.connectionIndex++ % self.availableConnections.length]; + } else { + connection = connections[self.connectionIndex++ % connections.length]; + } + + // Is the connection connected + if (!connection.isConnected()) { + // Remove the disconnected connection + removeConnection(self, connection); + // Flush any monitoring operations in the queue, failing fast + flushMonitoringOperations(self.queue); + break; + } + + // Get the next work item + var workItem = self.queue.shift(); + + // If we are monitoring we need to use a connection that is not + // running another operation to avoid socket timeout changes + // affecting an existing operation + if (workItem.monitoring) { + var foundValidConnection = false; + + for (let i = 0; i < self.availableConnections.length; i++) { + // If the connection is connected + // And there are no pending workItems on it + // Then we can safely use it for monitoring. + if ( + self.availableConnections[i].isConnected() && + self.availableConnections[i].workItems.length === 0 + ) { + foundValidConnection = true; + connection = self.availableConnections[i]; + break; + } + } + + // No safe connection found, attempt to grow the connections + // if possible and break from the loop + if (!foundValidConnection) { + // Put workItem back on the queue + self.queue.unshift(workItem); + + // Attempt to grow the pool if it's not yet maxsize + if (totalConnections < self.options.size && self.queue.length > 0) { + // Create a new connection + createConnection(self); + } + + // Re-execute the operation + setTimeout(function() { + _execute(self)(); + }, 10); + + break; + } + } + + // Don't execute operation until we have a full pool + if (totalConnections < self.options.size) { + // Connection has work items, then put it back on the queue + // and create a new connection + if (connection.workItems.length > 0) { + // Lets put the workItem back on the list + self.queue.unshift(workItem); + // Create a new connection + createConnection(self); + // Break from the loop + break; + } + } + + // Get actual binary commands + var buffer = workItem.buffer; + + // If we are monitoring take the connection of the availableConnections + if (workItem.monitoring) { + moveConnectionBetween(connection, self.availableConnections, self.inUseConnections); + } + + // Track the executing commands on the mongo server + // as long as there is an expected response + if (!workItem.noResponse) { + connection.workItems.push(workItem); + } + + // We have a custom socketTimeout + if (!workItem.immediateRelease && typeof workItem.socketTimeout === 'number') { + connection.setSocketTimeout(workItem.socketTimeout); + } + + // Capture if write was successful + var writeSuccessful = true; + + // Put operation on the wire + if (Array.isArray(buffer)) { + for (let i = 0; i < buffer.length; i++) { + writeSuccessful = connection.write(buffer[i]); + } + } else { + writeSuccessful = connection.write(buffer); + } + + // if the command is designated noResponse, call the callback immeditely + if (workItem.noResponse && typeof workItem.cb === 'function') { + workItem.cb(null, null); + } + + if (writeSuccessful === false) { + // If write not successful put back on queue + self.queue.unshift(workItem); + // Remove the disconnected connection + removeConnection(self, connection); + // Flush any monitoring operations in the queue, failing fast + flushMonitoringOperations(self.queue); + break; + } + } + + self.executing = false; + }; +} + +// Make execution loop available for testing +Pool._execute = _execute; + +/** + * A server connect event, used to verify that the connection is up and running + * + * @event Pool#connect + * @type {Pool} + */ + +/** + * A server reconnect event, used to verify that pool reconnected. + * + * @event Pool#reconnect + * @type {Pool} + */ + +/** + * The server connection closed, all pool connections closed + * + * @event Pool#close + * @type {Pool} + */ + +/** + * The server connection caused an error, all pool connections closed + * + * @event Pool#error + * @type {Pool} + */ + +/** + * The server connection timed out, all pool connections closed + * + * @event Pool#timeout + * @type {Pool} + */ + +/** + * The driver experienced an invalid message, all pool connections closed + * + * @event Pool#parseError + * @type {Pool} + */ + +/** + * The driver attempted to reconnect + * + * @event Pool#attemptReconnect + * @type {Pool} + */ + +/** + * The driver exhausted all reconnect attempts + * + * @event Pool#reconnectFailed + * @type {Pool} + */ + +module.exports = Pool; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/connection/utils.js b/scripts/2.5/node_modules/mongodb/lib/core/connection/utils.js new file mode 100644 index 00000000..2f3d889f --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/core/connection/utils.js @@ -0,0 +1,57 @@ +'use strict'; + +const require_optional = require('require_optional'); + +function debugOptions(debugFields, options) { + var finaloptions = {}; + debugFields.forEach(function(n) { + finaloptions[n] = options[n]; + }); + + return finaloptions; +} + +function retrieveBSON() { + var BSON = require('bson'); + BSON.native = false; + + try { + var optionalBSON = require_optional('bson-ext'); + if (optionalBSON) { + optionalBSON.native = true; + return optionalBSON; + } + } catch (err) {} // eslint-disable-line + + return BSON; +} + +// Throw an error if an attempt to use Snappy is made when Snappy is not installed +function noSnappyWarning() { + throw new Error( + 'Attempted to use Snappy compression, but Snappy is not installed. Install or disable Snappy compression and try again.' + ); +} + +// Facilitate loading Snappy optionally +function retrieveSnappy() { + var snappy = null; + try { + snappy = require_optional('snappy'); + } catch (error) {} // eslint-disable-line + if (!snappy) { + snappy = { + compress: noSnappyWarning, + uncompress: noSnappyWarning, + compressSync: noSnappyWarning, + uncompressSync: noSnappyWarning + }; + } + return snappy; +} + +module.exports = { + debugOptions, + retrieveBSON, + retrieveSnappy +}; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/cursor.js b/scripts/2.5/node_modules/mongodb/lib/core/cursor.js new file mode 100644 index 00000000..f5272182 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/core/cursor.js @@ -0,0 +1,886 @@ +'use strict'; + +const Logger = require('./connection/logger'); +const retrieveBSON = require('./connection/utils').retrieveBSON; +const MongoError = require('./error').MongoError; +const MongoNetworkError = require('./error').MongoNetworkError; +const mongoErrorContextSymbol = require('./error').mongoErrorContextSymbol; +const collationNotSupported = require('./utils').collationNotSupported; +const ReadPreference = require('./topologies/read_preference'); +const isUnifiedTopology = require('./utils').isUnifiedTopology; +const executeOperation = require('../operations/execute_operation'); +const Readable = require('stream').Readable; +const SUPPORTS = require('../utils').SUPPORTS; +const MongoDBNamespace = require('../utils').MongoDBNamespace; +const OperationBase = require('../operations/operation').OperationBase; + +const BSON = retrieveBSON(); +const Long = BSON.Long; + +// Possible states for a cursor +const CursorState = { + INIT: 0, + OPEN: 1, + CLOSED: 2, + GET_MORE: 3 +}; + +// +// Handle callback (including any exceptions thrown) +function handleCallback(callback, err, result) { + try { + callback(err, result); + } catch (err) { + process.nextTick(function() { + throw err; + }); + } +} + +/** + * This is a cursor results callback + * + * @callback resultCallback + * @param {error} error An error object. Set to null if no error present + * @param {object} document + */ + +/** + * @fileOverview The **Cursor** class is an internal class that embodies a cursor on MongoDB + * allowing for iteration over the results returned from the underlying query. + * + * **CURSORS Cannot directly be instantiated** + */ + +/** + * The core cursor class. All cursors in the driver build off of this one. + * + * @property {number} cursorBatchSize The current cursorBatchSize for the cursor + * @property {number} cursorLimit The current cursorLimit for the cursor + * @property {number} cursorSkip The current cursorSkip for the cursor + */ +class CoreCursor extends Readable { + /** + * Create a new core `Cursor` instance. + * **NOTE** Not to be instantiated directly + * + * @param {object} topology The server topology instance. + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {{object}|Long} cmd The selector (can be a command or a cursorId) + * @param {object} [options=null] Optional settings. + * @param {object} [options.batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/find/| find command documentation} and {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. + * @param {array} [options.documents=[]] Initial documents list for cursor + * @param {object} [options.transforms=null] Transform methods for the cursor results + * @param {function} [options.transforms.query] Transform the value returned from the initial query + * @param {function} [options.transforms.doc] Transform each document returned from Cursor.prototype._next + */ + constructor(topology, ns, cmd, options) { + super({ objectMode: true }); + options = options || {}; + + if (ns instanceof OperationBase) { + this.operation = ns; + ns = this.operation.ns.toString(); + options = this.operation.options; + cmd = this.operation.cmd ? this.operation.cmd : {}; + } + + // Cursor pool + this.pool = null; + // Cursor server + this.server = null; + + // Do we have a not connected handler + this.disconnectHandler = options.disconnectHandler; + + // Set local values + this.bson = topology.s.bson; + this.ns = ns; + this.namespace = MongoDBNamespace.fromString(ns); + this.cmd = cmd; + this.options = options; + this.topology = topology; + + // All internal state + this.cursorState = { + cursorId: null, + cmd, + documents: options.documents || [], + cursorIndex: 0, + dead: false, + killed: false, + init: false, + notified: false, + limit: options.limit || cmd.limit || 0, + skip: options.skip || cmd.skip || 0, + batchSize: options.batchSize || cmd.batchSize || 1000, + currentLimit: 0, + // Result field name if not a cursor (contains the array of results) + transforms: options.transforms, + raw: options.raw || (cmd && cmd.raw) + }; + + if (typeof options.session === 'object') { + this.cursorState.session = options.session; + } + + // Add promoteLong to cursor state + const topologyOptions = topology.s.options; + if (typeof topologyOptions.promoteLongs === 'boolean') { + this.cursorState.promoteLongs = topologyOptions.promoteLongs; + } else if (typeof options.promoteLongs === 'boolean') { + this.cursorState.promoteLongs = options.promoteLongs; + } + + // Add promoteValues to cursor state + if (typeof topologyOptions.promoteValues === 'boolean') { + this.cursorState.promoteValues = topologyOptions.promoteValues; + } else if (typeof options.promoteValues === 'boolean') { + this.cursorState.promoteValues = options.promoteValues; + } + + // Add promoteBuffers to cursor state + if (typeof topologyOptions.promoteBuffers === 'boolean') { + this.cursorState.promoteBuffers = topologyOptions.promoteBuffers; + } else if (typeof options.promoteBuffers === 'boolean') { + this.cursorState.promoteBuffers = options.promoteBuffers; + } + + if (topologyOptions.reconnect) { + this.cursorState.reconnect = topologyOptions.reconnect; + } + + // Logger + this.logger = Logger('Cursor', topologyOptions); + + // + // Did we pass in a cursor id + if (typeof cmd === 'number') { + this.cursorState.cursorId = Long.fromNumber(cmd); + this.cursorState.lastCursorId = this.cursorState.cursorId; + } else if (cmd instanceof Long) { + this.cursorState.cursorId = cmd; + this.cursorState.lastCursorId = cmd; + } + + // TODO: remove as part of NODE-2104 + if (this.operation) { + this.operation.cursorState = this.cursorState; + } + } + + setCursorBatchSize(value) { + this.cursorState.batchSize = value; + } + + cursorBatchSize() { + return this.cursorState.batchSize; + } + + setCursorLimit(value) { + this.cursorState.limit = value; + } + + cursorLimit() { + return this.cursorState.limit; + } + + setCursorSkip(value) { + this.cursorState.skip = value; + } + + cursorSkip() { + return this.cursorState.skip; + } + + /** + * Retrieve the next document from the cursor + * @method + * @param {resultCallback} callback A callback function + */ + _next(callback) { + nextFunction(this, callback); + } + + /** + * Clone the cursor + * @method + * @return {Cursor} + */ + clone() { + return this.topology.cursor(this.ns, this.cmd, this.options); + } + + /** + * Checks if the cursor is dead + * @method + * @return {boolean} A boolean signifying if the cursor is dead or not + */ + isDead() { + return this.cursorState.dead === true; + } + + /** + * Checks if the cursor was killed by the application + * @method + * @return {boolean} A boolean signifying if the cursor was killed by the application + */ + isKilled() { + return this.cursorState.killed === true; + } + + /** + * Checks if the cursor notified it's caller about it's death + * @method + * @return {boolean} A boolean signifying if the cursor notified the callback + */ + isNotified() { + return this.cursorState.notified === true; + } + + /** + * Returns current buffered documents length + * @method + * @return {number} The number of items in the buffered documents + */ + bufferedCount() { + return this.cursorState.documents.length - this.cursorState.cursorIndex; + } + + /** + * Returns current buffered documents + * @method + * @return {Array} An array of buffered documents + */ + readBufferedDocuments(number) { + const unreadDocumentsLength = this.cursorState.documents.length - this.cursorState.cursorIndex; + const length = number < unreadDocumentsLength ? number : unreadDocumentsLength; + let elements = this.cursorState.documents.slice( + this.cursorState.cursorIndex, + this.cursorState.cursorIndex + length + ); + + // Transform the doc with passed in transformation method if provided + if (this.cursorState.transforms && typeof this.cursorState.transforms.doc === 'function') { + // Transform all the elements + for (let i = 0; i < elements.length; i++) { + elements[i] = this.cursorState.transforms.doc(elements[i]); + } + } + + // Ensure we do not return any more documents than the limit imposed + // Just return the number of elements up to the limit + if ( + this.cursorState.limit > 0 && + this.cursorState.currentLimit + elements.length > this.cursorState.limit + ) { + elements = elements.slice(0, this.cursorState.limit - this.cursorState.currentLimit); + this.kill(); + } + + // Adjust current limit + this.cursorState.currentLimit = this.cursorState.currentLimit + elements.length; + this.cursorState.cursorIndex = this.cursorState.cursorIndex + elements.length; + + // Return elements + return elements; + } + + /** + * Resets local state for this cursor instance, and issues a `killCursors` command to the server + * + * @param {resultCallback} callback A callback function + */ + kill(callback) { + // Set cursor to dead + this.cursorState.dead = true; + this.cursorState.killed = true; + // Remove documents + this.cursorState.documents = []; + + // If no cursor id just return + if ( + this.cursorState.cursorId == null || + this.cursorState.cursorId.isZero() || + this.cursorState.init === false + ) { + if (callback) callback(null, null); + return; + } + + this.server.killCursors(this.ns, this.cursorState, callback); + } + + /** + * Resets the cursor + */ + rewind() { + if (this.cursorState.init) { + if (!this.cursorState.dead) { + this.kill(); + } + + this.cursorState.currentLimit = 0; + this.cursorState.init = false; + this.cursorState.dead = false; + this.cursorState.killed = false; + this.cursorState.notified = false; + this.cursorState.documents = []; + this.cursorState.cursorId = null; + this.cursorState.cursorIndex = 0; + } + } + + // Internal methods + _read() { + if ((this.s && this.s.state === CursorState.CLOSED) || this.isDead()) { + return this.push(null); + } + + // Get the next item + this._next((err, result) => { + if (err) { + if (this.listeners('error') && this.listeners('error').length > 0) { + this.emit('error', err); + } + if (!this.isDead()) this.close(); + + // Emit end event + this.emit('end'); + return this.emit('finish'); + } + + // If we provided a transformation method + if ( + this.cursorState.streamOptions && + typeof this.cursorState.streamOptions.transform === 'function' && + result != null + ) { + return this.push(this.cursorState.streamOptions.transform(result)); + } + + // If we provided a map function + if ( + this.cursorState.transforms && + typeof this.cursorState.transforms.doc === 'function' && + result != null + ) { + return this.push(this.cursorState.transforms.doc(result)); + } + + // Return the result + this.push(result); + + if (result === null && this.isDead()) { + this.once('end', () => { + this.close(); + this.emit('finish'); + }); + } + }); + } + + _endSession(options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + options = options || {}; + + const session = this.cursorState.session; + + if (session && (options.force || session.owner === this)) { + this.cursorState.session = undefined; + + if (this.operation) { + this.operation.clearSession(); + } + + session.endSession(callback); + return true; + } + + if (callback) { + callback(); + } + + return false; + } + + _getMore(callback) { + if (this.logger.isDebug()) { + this.logger.debug(`schedule getMore call for query [${JSON.stringify(this.query)}]`); + } + + // Set the current batchSize + let batchSize = this.cursorState.batchSize; + if ( + this.cursorState.limit > 0 && + this.cursorState.currentLimit + batchSize > this.cursorState.limit + ) { + batchSize = this.cursorState.limit - this.cursorState.currentLimit; + } + + this.server.getMore(this.ns, this.cursorState, batchSize, this.options, callback); + } + + _initializeCursor(callback) { + const cursor = this; + + // NOTE: this goes away once cursors use `executeOperation` + if (isUnifiedTopology(cursor.topology) && cursor.topology.shouldCheckForSessionSupport()) { + cursor.topology.selectServer(ReadPreference.primaryPreferred, err => { + if (err) { + callback(err); + return; + } + + cursor._next(callback); + }); + + return; + } + + function done(err, result) { + if ( + cursor.cursorState.cursorId && + cursor.cursorState.cursorId.isZero() && + cursor._endSession + ) { + cursor._endSession(); + } + + if ( + cursor.cursorState.documents.length === 0 && + cursor.cursorState.cursorId && + cursor.cursorState.cursorId.isZero() && + !cursor.cmd.tailable && + !cursor.cmd.awaitData + ) { + return setCursorNotified(cursor, callback); + } + + callback(err, result); + } + + const queryCallback = (err, r) => { + if (err) { + return done(err); + } + + const result = r.message; + if (result.queryFailure) { + return done(new MongoError(result.documents[0]), null); + } + + // Check if we have a command cursor + if ( + Array.isArray(result.documents) && + result.documents.length === 1 && + (!cursor.cmd.find || (cursor.cmd.find && cursor.cmd.virtual === false)) && + (typeof result.documents[0].cursor !== 'string' || + result.documents[0]['$err'] || + result.documents[0]['errmsg'] || + Array.isArray(result.documents[0].result)) + ) { + // We have an error document, return the error + if (result.documents[0]['$err'] || result.documents[0]['errmsg']) { + return done(new MongoError(result.documents[0]), null); + } + + // We have a cursor document + if (result.documents[0].cursor != null && typeof result.documents[0].cursor !== 'string') { + const id = result.documents[0].cursor.id; + // If we have a namespace change set the new namespace for getmores + if (result.documents[0].cursor.ns) { + cursor.ns = result.documents[0].cursor.ns; + } + // Promote id to long if needed + cursor.cursorState.cursorId = typeof id === 'number' ? Long.fromNumber(id) : id; + cursor.cursorState.lastCursorId = cursor.cursorState.cursorId; + cursor.cursorState.operationTime = result.documents[0].operationTime; + + // If we have a firstBatch set it + if (Array.isArray(result.documents[0].cursor.firstBatch)) { + cursor.cursorState.documents = result.documents[0].cursor.firstBatch; //.reverse(); + } + + // Return after processing command cursor + return done(null, result); + } + + if (Array.isArray(result.documents[0].result)) { + cursor.cursorState.documents = result.documents[0].result; + cursor.cursorState.cursorId = Long.ZERO; + return done(null, result); + } + } + + // Otherwise fall back to regular find path + const cursorId = result.cursorId || 0; + cursor.cursorState.cursorId = cursorId instanceof Long ? cursorId : Long.fromNumber(cursorId); + cursor.cursorState.documents = result.documents; + cursor.cursorState.lastCursorId = result.cursorId; + + // Transform the results with passed in transformation method if provided + if ( + cursor.cursorState.transforms && + typeof cursor.cursorState.transforms.query === 'function' + ) { + cursor.cursorState.documents = cursor.cursorState.transforms.query(result); + } + + done(null, result); + }; + + if (cursor.operation) { + if (cursor.logger.isDebug()) { + cursor.logger.debug( + `issue initial query [${JSON.stringify(cursor.cmd)}] with flags [${JSON.stringify( + cursor.query + )}]` + ); + } + + executeOperation(cursor.topology, cursor.operation, (err, result) => { + if (err) { + done(err); + return; + } + + cursor.server = cursor.operation.server; + cursor.cursorState.init = true; + + // NOTE: this is a special internal method for cloning a cursor, consider removing + if (cursor.cursorState.cursorId != null) { + return done(); + } + + queryCallback(err, result); + }); + + return; + } + + // Very explicitly choose what is passed to selectServer + const serverSelectOptions = {}; + if (cursor.cursorState.session) { + serverSelectOptions.session = cursor.cursorState.session; + } + + if (cursor.operation) { + serverSelectOptions.readPreference = cursor.operation.readPreference; + } else if (cursor.options.readPreference) { + serverSelectOptions.readPreference = cursor.options.readPreference; + } + + return cursor.topology.selectServer(serverSelectOptions, (err, server) => { + if (err) { + const disconnectHandler = cursor.disconnectHandler; + if (disconnectHandler != null) { + return disconnectHandler.addObjectAndMethod( + 'cursor', + cursor, + 'next', + [callback], + callback + ); + } + + return callback(err); + } + + cursor.server = server; + cursor.cursorState.init = true; + if (collationNotSupported(cursor.server, cursor.cmd)) { + return callback(new MongoError(`server ${cursor.server.name} does not support collation`)); + } + + // NOTE: this is a special internal method for cloning a cursor, consider removing + if (cursor.cursorState.cursorId != null) { + return done(); + } + + if (cursor.logger.isDebug()) { + cursor.logger.debug( + `issue initial query [${JSON.stringify(cursor.cmd)}] with flags [${JSON.stringify( + cursor.query + )}]` + ); + } + + if (cursor.cmd.find != null) { + server.query(cursor.ns, cursor.cmd, cursor.cursorState, cursor.options, queryCallback); + return; + } + + const commandOptions = Object.assign({ session: cursor.cursorState.session }, cursor.options); + server.command(cursor.ns, cursor.cmd, commandOptions, queryCallback); + }); + } +} + +if (SUPPORTS.ASYNC_ITERATOR) { + CoreCursor.prototype[Symbol.asyncIterator] = require('../async/async_iterator').asyncIterator; +} + +/** + * Validate if the pool is dead and return error + */ +function isConnectionDead(self, callback) { + if (self.pool && self.pool.isDestroyed()) { + self.cursorState.killed = true; + const err = new MongoNetworkError( + `connection to host ${self.pool.host}:${self.pool.port} was destroyed` + ); + + _setCursorNotifiedImpl(self, () => callback(err)); + return true; + } + + return false; +} + +/** + * Validate if the cursor is dead but was not explicitly killed by user + */ +function isCursorDeadButNotkilled(self, callback) { + // Cursor is dead but not marked killed, return null + if (self.cursorState.dead && !self.cursorState.killed) { + self.cursorState.killed = true; + setCursorNotified(self, callback); + return true; + } + + return false; +} + +/** + * Validate if the cursor is dead and was killed by user + */ +function isCursorDeadAndKilled(self, callback) { + if (self.cursorState.dead && self.cursorState.killed) { + handleCallback(callback, new MongoError('cursor is dead')); + return true; + } + + return false; +} + +/** + * Validate if the cursor was killed by the user + */ +function isCursorKilled(self, callback) { + if (self.cursorState.killed) { + setCursorNotified(self, callback); + return true; + } + + return false; +} + +/** + * Mark cursor as being dead and notified + */ +function setCursorDeadAndNotified(self, callback) { + self.cursorState.dead = true; + setCursorNotified(self, callback); +} + +/** + * Mark cursor as being notified + */ +function setCursorNotified(self, callback) { + _setCursorNotifiedImpl(self, () => handleCallback(callback, null, null)); +} + +function _setCursorNotifiedImpl(self, callback) { + self.cursorState.notified = true; + self.cursorState.documents = []; + self.cursorState.cursorIndex = 0; + + if (self._endSession) { + self._endSession(undefined, () => callback()); + return; + } + + return callback(); +} + +function nextFunction(self, callback) { + // We have notified about it + if (self.cursorState.notified) { + return callback(new Error('cursor is exhausted')); + } + + // Cursor is killed return null + if (isCursorKilled(self, callback)) return; + + // Cursor is dead but not marked killed, return null + if (isCursorDeadButNotkilled(self, callback)) return; + + // We have a dead and killed cursor, attempting to call next should error + if (isCursorDeadAndKilled(self, callback)) return; + + // We have just started the cursor + if (!self.cursorState.init) { + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if (!self.topology.isConnected(self.options)) { + // Only need this for single server, because repl sets and mongos + // will always continue trying to reconnect + if (self.topology._type === 'server' && !self.topology.s.options.reconnect) { + // Reconnect is disabled, so we'll never reconnect + return callback(new MongoError('no connection available')); + } + + if (self.disconnectHandler != null) { + if (self.topology.isDestroyed()) { + // Topology was destroyed, so don't try to wait for it to reconnect + return callback(new MongoError('Topology was destroyed')); + } + + self.disconnectHandler.addObjectAndMethod('cursor', self, 'next', [callback], callback); + return; + } + } + + self._initializeCursor((err, result) => { + if (err || result === null) { + callback(err, result); + return; + } + + nextFunction(self, callback); + }); + + return; + } + + if (self.cursorState.limit > 0 && self.cursorState.currentLimit >= self.cursorState.limit) { + // Ensure we kill the cursor on the server + self.kill(); + // Set cursor in dead and notified state + return setCursorDeadAndNotified(self, callback); + } else if ( + self.cursorState.cursorIndex === self.cursorState.documents.length && + !Long.ZERO.equals(self.cursorState.cursorId) + ) { + // Ensure an empty cursor state + self.cursorState.documents = []; + self.cursorState.cursorIndex = 0; + + // Check if topology is destroyed + if (self.topology.isDestroyed()) + return callback( + new MongoNetworkError('connection destroyed, not possible to instantiate cursor') + ); + + // Check if connection is dead and return if not possible to + // execute a getMore on this connection + if (isConnectionDead(self, callback)) return; + + // Execute the next get more + self._getMore(function(err, doc, connection) { + if (err) { + if (err instanceof MongoError) { + err[mongoErrorContextSymbol].isGetMore = true; + } + + return handleCallback(callback, err); + } + + if (self.cursorState.cursorId && self.cursorState.cursorId.isZero() && self._endSession) { + self._endSession(); + } + + // Save the returned connection to ensure all getMore's fire over the same connection + self.connection = connection; + + // Tailable cursor getMore result, notify owner about it + // No attempt is made here to retry, this is left to the user of the + // core module to handle to keep core simple + if ( + self.cursorState.documents.length === 0 && + self.cmd.tailable && + Long.ZERO.equals(self.cursorState.cursorId) + ) { + // No more documents in the tailed cursor + return handleCallback( + callback, + new MongoError({ + message: 'No more documents in tailed cursor', + tailable: self.cmd.tailable, + awaitData: self.cmd.awaitData + }) + ); + } else if ( + self.cursorState.documents.length === 0 && + self.cmd.tailable && + !Long.ZERO.equals(self.cursorState.cursorId) + ) { + return nextFunction(self, callback); + } + + if (self.cursorState.limit > 0 && self.cursorState.currentLimit >= self.cursorState.limit) { + return setCursorDeadAndNotified(self, callback); + } + + nextFunction(self, callback); + }); + } else if ( + self.cursorState.documents.length === self.cursorState.cursorIndex && + self.cmd.tailable && + Long.ZERO.equals(self.cursorState.cursorId) + ) { + return handleCallback( + callback, + new MongoError({ + message: 'No more documents in tailed cursor', + tailable: self.cmd.tailable, + awaitData: self.cmd.awaitData + }) + ); + } else if ( + self.cursorState.documents.length === self.cursorState.cursorIndex && + Long.ZERO.equals(self.cursorState.cursorId) + ) { + setCursorDeadAndNotified(self, callback); + } else { + if (self.cursorState.limit > 0 && self.cursorState.currentLimit >= self.cursorState.limit) { + // Ensure we kill the cursor on the server + self.kill(); + // Set cursor in dead and notified state + return setCursorDeadAndNotified(self, callback); + } + + // Increment the current cursor limit + self.cursorState.currentLimit += 1; + + // Get the document + let doc = self.cursorState.documents[self.cursorState.cursorIndex++]; + + // Doc overflow + if (!doc || doc.$err) { + // Ensure we kill the cursor on the server + self.kill(); + // Set cursor in dead and notified state + return setCursorDeadAndNotified(self, function() { + handleCallback(callback, new MongoError(doc ? doc.$err : undefined)); + }); + } + + // Transform the doc with passed in transformation method if provided + if (self.cursorState.transforms && typeof self.cursorState.transforms.doc === 'function') { + doc = self.cursorState.transforms.doc(doc); + } + + // Return the document + handleCallback(callback, null, doc); + } +} + +module.exports = { + CursorState, + CoreCursor +}; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/error.js b/scripts/2.5/node_modules/mongodb/lib/core/error.js new file mode 100644 index 00000000..d35fbbef --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/core/error.js @@ -0,0 +1,237 @@ +'use strict'; + +const mongoErrorContextSymbol = Symbol('mongoErrorContextSymbol'); +const maxWireVersion = require('./utils').maxWireVersion; + +/** + * Creates a new MongoError + * + * @augments Error + * @param {Error|string|object} message The error message + * @property {string} message The error message + * @property {string} stack The error call stack + */ +class MongoError extends Error { + constructor(message) { + if (message instanceof Error) { + super(message.message); + this.stack = message.stack; + } else { + if (typeof message === 'string') { + super(message); + } else { + super(message.message || message.errmsg || message.$err || 'n/a'); + for (var name in message) { + this[name] = message[name]; + } + } + + Error.captureStackTrace(this, this.constructor); + } + + this.name = 'MongoError'; + this[mongoErrorContextSymbol] = this[mongoErrorContextSymbol] || {}; + } + + /** + * Creates a new MongoError object + * + * @param {Error|string|object} options The options used to create the error. + * @return {MongoError} A MongoError instance + * @deprecated Use `new MongoError()` instead. + */ + static create(options) { + return new MongoError(options); + } + + hasErrorLabel(label) { + return this.errorLabels && this.errorLabels.indexOf(label) !== -1; + } +} + +/** + * Creates a new MongoNetworkError + * + * @param {Error|string|object} message The error message + * @property {string} message The error message + * @property {string} stack The error call stack + */ +class MongoNetworkError extends MongoError { + constructor(message) { + super(message); + this.name = 'MongoNetworkError'; + + // This is added as part of the transactions specification + this.errorLabels = ['TransientTransactionError']; + } +} + +/** + * An error used when attempting to parse a value (like a connection string) + * + * @param {Error|string|object} message The error message + * @property {string} message The error message + */ +class MongoParseError extends MongoError { + constructor(message) { + super(message); + this.name = 'MongoParseError'; + } +} + +/** + * An error signifying a timeout event + * + * @param {Error|string|object} message The error message + * @param {string|object} [reason] The reason the timeout occured + * @property {string} message The error message + * @property {string} [reason] An optional reason context for the timeout, generally an error saved during flow of monitoring and selecting servers + */ +class MongoTimeoutError extends MongoError { + constructor(message, reason) { + super(message); + this.name = 'MongoTimeoutError'; + if (reason != null) { + this.reason = reason; + } + } +} + +function makeWriteConcernResultObject(input) { + const output = Object.assign({}, input); + + if (output.ok === 0) { + output.ok = 1; + delete output.errmsg; + delete output.code; + delete output.codeName; + } + + return output; +} + +/** + * An error thrown when the server reports a writeConcernError + * + * @param {Error|string|object} message The error message + * @param {object} result The result document (provided if ok: 1) + * @property {string} message The error message + * @property {object} [result] The result document (provided if ok: 1) + */ +class MongoWriteConcernError extends MongoError { + constructor(message, result) { + super(message); + this.name = 'MongoWriteConcernError'; + + if (result != null) { + this.result = makeWriteConcernResultObject(result); + } + } +} + +// see: https://github.com/mongodb/specifications/blob/master/source/retryable-writes/retryable-writes.rst#terms +const RETRYABLE_ERROR_CODES = new Set([ + 6, // HostUnreachable + 7, // HostNotFound + 89, // NetworkTimeout + 91, // ShutdownInProgress + 189, // PrimarySteppedDown + 9001, // SocketException + 10107, // NotMaster + 11600, // InterruptedAtShutdown + 11602, // InterruptedDueToReplStateChange + 13435, // NotMasterNoSlaveOk + 13436 // NotMasterOrSecondary +]); + +/** + * Determines whether an error is something the driver should attempt to retry + * + * @param {MongoError|Error} error + */ +function isRetryableError(error) { + return ( + RETRYABLE_ERROR_CODES.has(error.code) || + error instanceof MongoNetworkError || + error.message.match(/not master/) || + error.message.match(/node is recovering/) + ); +} + +const SDAM_RECOVERING_CODES = new Set([ + 91, // ShutdownInProgress + 189, // PrimarySteppedDown + 11600, // InterruptedAtShutdown + 11602, // InterruptedDueToReplStateChange + 13436 // NotMasterOrSecondary +]); + +const SDAM_NOTMASTER_CODES = new Set([ + 10107, // NotMaster + 13435 // NotMasterNoSlaveOk +]); + +const SDAM_NODE_SHUTTING_DOWN_ERROR_CODES = new Set([ + 11600, // InterruptedAtShutdown + 91 // ShutdownInProgress +]); + +function isRecoveringError(err) { + if (err.code && SDAM_RECOVERING_CODES.has(err.code)) { + return true; + } + + return err.message.match(/not master or secondary/) || err.message.match(/node is recovering/); +} + +function isNotMasterError(err) { + if (err.code && SDAM_NOTMASTER_CODES.has(err.code)) { + return true; + } + + if (isRecoveringError(err)) { + return false; + } + + return err.message.match(/not master/); +} + +function isNodeShuttingDownError(err) { + return err.code && SDAM_NODE_SHUTTING_DOWN_ERROR_CODES.has(err.code); +} + +/** + * Determines whether SDAM can recover from a given error. If it cannot + * then the pool will be cleared, and server state will completely reset + * locally. + * + * @see https://github.com/mongodb/specifications/blob/master/source/server-discovery-and-monitoring/server-discovery-and-monitoring.rst#not-master-and-node-is-recovering + * @param {MongoError|Error} error + * @param {Server} server + */ +function isSDAMUnrecoverableError(error, server) { + if (error instanceof MongoParseError) { + return true; + } + + if (isRecoveringError(error) || isNotMasterError(error)) { + if (maxWireVersion(server) >= 8 && !isNodeShuttingDownError(error)) { + return false; + } + + return true; + } + + return false; +} + +module.exports = { + MongoError, + MongoNetworkError, + MongoParseError, + MongoTimeoutError, + MongoWriteConcernError, + mongoErrorContextSymbol, + isRetryableError, + isSDAMUnrecoverableError +}; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/index.js b/scripts/2.5/node_modules/mongodb/lib/core/index.js new file mode 100644 index 00000000..8d1ca8f5 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/core/index.js @@ -0,0 +1,50 @@ +'use strict'; + +let BSON = require('bson'); +const require_optional = require('require_optional'); +const EJSON = require('./utils').retrieveEJSON(); + +try { + // Attempt to grab the native BSON parser + const BSONNative = require_optional('bson-ext'); + // If we got the native parser, use it instead of the + // Javascript one + if (BSONNative) { + BSON = BSONNative; + } +} catch (err) {} // eslint-disable-line + +module.exports = { + // Errors + MongoError: require('./error').MongoError, + MongoNetworkError: require('./error').MongoNetworkError, + MongoParseError: require('./error').MongoParseError, + MongoTimeoutError: require('./error').MongoTimeoutError, + MongoWriteConcernError: require('./error').MongoWriteConcernError, + mongoErrorContextSymbol: require('./error').mongoErrorContextSymbol, + // Core + Connection: require('./connection/connection'), + Server: require('./topologies/server'), + ReplSet: require('./topologies/replset'), + Mongos: require('./topologies/mongos'), + Logger: require('./connection/logger'), + Cursor: require('./cursor').CoreCursor, + ReadPreference: require('./topologies/read_preference'), + Sessions: require('./sessions'), + BSON: BSON, + EJSON: EJSON, + Topology: require('./sdam/topology'), + // Raw operations + Query: require('./connection/commands').Query, + // Auth mechanisms + MongoCredentials: require('./auth/mongo_credentials').MongoCredentials, + defaultAuthProviders: require('./auth/defaultAuthProviders').defaultAuthProviders, + MongoCR: require('./auth/mongocr'), + X509: require('./auth/x509'), + Plain: require('./auth/plain'), + GSSAPI: require('./auth/gssapi'), + ScramSHA1: require('./auth/scram').ScramSHA1, + ScramSHA256: require('./auth/scram').ScramSHA256, + // Utilities + parseConnectionString: require('./uri_parser') +}; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/sdam/monitoring.js b/scripts/2.5/node_modules/mongodb/lib/core/sdam/monitoring.js new file mode 100644 index 00000000..15f081c8 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/core/sdam/monitoring.js @@ -0,0 +1,235 @@ +'use strict'; + +const ServerDescription = require('./server_description').ServerDescription; +const calculateDurationInMs = require('../utils').calculateDurationInMs; + +// pulled from `Server` implementation +const STATE_DISCONNECTED = 'disconnected'; +const STATE_DISCONNECTING = 'disconnecting'; + +/** + * Published when server description changes, but does NOT include changes to the RTT. + * + * @property {Object} topologyId A unique identifier for the topology + * @property {ServerAddress} address The address (host/port pair) of the server + * @property {ServerDescription} previousDescription The previous server description + * @property {ServerDescription} newDescription The new server description + */ +class ServerDescriptionChangedEvent { + constructor(topologyId, address, previousDescription, newDescription) { + Object.assign(this, { topologyId, address, previousDescription, newDescription }); + } +} + +/** + * Published when server is initialized. + * + * @property {Object} topologyId A unique identifier for the topology + * @property {ServerAddress} address The address (host/port pair) of the server + */ +class ServerOpeningEvent { + constructor(topologyId, address) { + Object.assign(this, { topologyId, address }); + } +} + +/** + * Published when server is closed. + * + * @property {ServerAddress} address The address (host/port pair) of the server + * @property {Object} topologyId A unique identifier for the topology + */ +class ServerClosedEvent { + constructor(topologyId, address) { + Object.assign(this, { topologyId, address }); + } +} + +/** + * Published when topology description changes. + * + * @property {Object} topologyId + * @property {TopologyDescription} previousDescription The old topology description + * @property {TopologyDescription} newDescription The new topology description + */ +class TopologyDescriptionChangedEvent { + constructor(topologyId, previousDescription, newDescription) { + Object.assign(this, { topologyId, previousDescription, newDescription }); + } +} + +/** + * Published when topology is initialized. + * + * @param {Object} topologyId A unique identifier for the topology + */ +class TopologyOpeningEvent { + constructor(topologyId) { + Object.assign(this, { topologyId }); + } +} + +/** + * Published when topology is closed. + * + * @param {Object} topologyId A unique identifier for the topology + */ +class TopologyClosedEvent { + constructor(topologyId) { + Object.assign(this, { topologyId }); + } +} + +/** + * Fired when the server monitor’s ismaster command is started - immediately before + * the ismaster command is serialized into raw BSON and written to the socket. + * + * @property {Object} connectionId The connection id for the command + */ +class ServerHeartbeatStartedEvent { + constructor(connectionId) { + Object.assign(this, { connectionId }); + } +} + +/** + * Fired when the server monitor’s ismaster succeeds. + * + * @param {Number} duration The execution time of the event in ms + * @param {Object} reply The command reply + * @param {Object} connectionId The connection id for the command + */ +class ServerHeartbeatSucceededEvent { + constructor(duration, reply, connectionId) { + Object.assign(this, { duration, reply, connectionId }); + } +} + +/** + * Fired when the server monitor’s ismaster fails, either with an “ok: 0” or a socket exception. + * + * @param {Number} duration The execution time of the event in ms + * @param {MongoError|Object} failure The command failure + * @param {Object} connectionId The connection id for the command + */ +class ServerHeartbeatFailedEvent { + constructor(duration, failure, connectionId) { + Object.assign(this, { duration, failure, connectionId }); + } +} + +/** + * Performs a server check as described by the SDAM spec. + * + * NOTE: This method automatically reschedules itself, so that there is always an active + * monitoring process + * + * @param {Server} server The server to monitor + */ +function monitorServer(server, options) { + options = options || {}; + const heartbeatFrequencyMS = options.heartbeatFrequencyMS || 10000; + + if (options.initial === true) { + server.s.monitorId = setTimeout(() => monitorServer(server), heartbeatFrequencyMS); + return; + } + + // executes a single check of a server + const checkServer = callback => { + let start = process.hrtime(); + + // emit a signal indicating we have started the heartbeat + server.emit('serverHeartbeatStarted', new ServerHeartbeatStartedEvent(server.name)); + + // NOTE: legacy monitoring event + process.nextTick(() => server.emit('monitoring', server)); + + server.command( + 'admin.$cmd', + { ismaster: true }, + { + monitoring: true, + socketTimeout: server.s.options.connectionTimeout || 2000 + }, + (err, result) => { + let duration = calculateDurationInMs(start); + + if (err) { + server.emit( + 'serverHeartbeatFailed', + new ServerHeartbeatFailedEvent(duration, err, server.name) + ); + + return callback(err, null); + } + + const isMaster = result.result; + server.emit( + 'serverHeartbeatSucceeded', + new ServerHeartbeatSucceededEvent(duration, isMaster, server.name) + ); + + return callback(null, isMaster); + } + ); + }; + + const successHandler = isMaster => { + server.s.monitoring = false; + + // emit an event indicating that our description has changed + server.emit('descriptionReceived', new ServerDescription(server.description.address, isMaster)); + if (server.s.state === STATE_DISCONNECTED || server.s.state === STATE_DISCONNECTING) { + return; + } + + // schedule the next monitoring process + server.s.monitorId = setTimeout(() => monitorServer(server), heartbeatFrequencyMS); + }; + + // run the actual monitoring loop + server.s.monitoring = true; + checkServer((err, isMaster) => { + if (!err) { + successHandler(isMaster); + return; + } + + // According to the SDAM specification's "Network error during server check" section, if + // an ismaster call fails we reset the server's pool. If a server was once connected, + // change its type to `Unknown` only after retrying once. + server.s.pool.reset(() => { + // otherwise re-attempt monitoring once + checkServer((error, isMaster) => { + if (error) { + server.s.monitoring = false; + + // we revert to an `Unknown` by emitting a default description with no isMaster + server.emit( + 'descriptionReceived', + new ServerDescription(server.description.address, null, { error }) + ); + + // we do not reschedule monitoring in this case + return; + } + + successHandler(isMaster); + }); + }); + }); +} + +module.exports = { + ServerDescriptionChangedEvent, + ServerOpeningEvent, + ServerClosedEvent, + TopologyDescriptionChangedEvent, + TopologyOpeningEvent, + TopologyClosedEvent, + ServerHeartbeatStartedEvent, + ServerHeartbeatSucceededEvent, + ServerHeartbeatFailedEvent, + monitorServer +}; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/sdam/server.js b/scripts/2.5/node_modules/mongodb/lib/core/sdam/server.js new file mode 100644 index 00000000..abb1570a --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/core/sdam/server.js @@ -0,0 +1,511 @@ +'use strict'; +const EventEmitter = require('events'); +const MongoError = require('../error').MongoError; +const Pool = require('../connection/pool'); +const relayEvents = require('../utils').relayEvents; +const wireProtocol = require('../wireprotocol'); +const BSON = require('../connection/utils').retrieveBSON(); +const createClientInfo = require('../topologies/shared').createClientInfo; +const Logger = require('../connection/logger'); +const ServerDescription = require('./server_description').ServerDescription; +const ReadPreference = require('../topologies/read_preference'); +const monitorServer = require('./monitoring').monitorServer; +const MongoParseError = require('../error').MongoParseError; +const MongoNetworkError = require('../error').MongoNetworkError; +const collationNotSupported = require('../utils').collationNotSupported; +const debugOptions = require('../connection/utils').debugOptions; +const isSDAMUnrecoverableError = require('../error').isSDAMUnrecoverableError; + +// Used for filtering out fields for logging +const DEBUG_FIELDS = [ + 'reconnect', + 'reconnectTries', + 'reconnectInterval', + 'emitError', + 'cursorFactory', + 'host', + 'port', + 'size', + 'keepAlive', + 'keepAliveInitialDelay', + 'noDelay', + 'connectionTimeout', + 'checkServerIdentity', + 'socketTimeout', + 'ssl', + 'ca', + 'crl', + 'cert', + 'key', + 'rejectUnauthorized', + 'promoteLongs', + 'promoteValues', + 'promoteBuffers', + 'servername' +]; + +const STATE_DISCONNECTING = 'disconnecting'; +const STATE_DISCONNECTED = 'disconnected'; +const STATE_CONNECTING = 'connecting'; +const STATE_CONNECTED = 'connected'; + +/** + * + * @fires Server#serverHeartbeatStarted + * @fires Server#serverHeartbeatSucceeded + * @fires Server#serverHeartbeatFailed + */ +class Server extends EventEmitter { + /** + * Create a server + * + * @param {ServerDescription} description + * @param {Object} options + */ + constructor(description, options, topology) { + super(); + + this.s = { + // the server description + description, + // a saved copy of the incoming options + options, + // the server logger + logger: Logger('Server', options), + // the bson parser + bson: + options.bson || + new BSON([ + BSON.Binary, + BSON.Code, + BSON.DBRef, + BSON.Decimal128, + BSON.Double, + BSON.Int32, + BSON.Long, + BSON.Map, + BSON.MaxKey, + BSON.MinKey, + BSON.ObjectId, + BSON.BSONRegExp, + BSON.Symbol, + BSON.Timestamp + ]), + // client metadata for the initial handshake + clientInfo: createClientInfo(options), + // state variable to determine if there is an active server check in progress + monitoring: false, + // the implementation of the monitoring method + monitorFunction: options.monitorFunction || monitorServer, + // the connection pool + pool: null, + // the server state + state: STATE_DISCONNECTED, + credentials: options.credentials, + topology + }; + } + + get description() { + return this.s.description; + } + + get name() { + return this.s.description.address; + } + + get autoEncrypter() { + if (this.s.options && this.s.options.autoEncrypter) { + return this.s.options.autoEncrypter; + } + return null; + } + + /** + * Initiate server connect + */ + connect(options) { + options = options || {}; + + // do not allow connect to be called on anything that's not disconnected + if (this.s.pool && !this.s.pool.isDisconnected() && !this.s.pool.isDestroyed()) { + throw new MongoError(`Server instance in invalid state ${this.s.pool.state}`); + } + + // create a pool + const addressParts = this.description.address.split(':'); + const poolOptions = Object.assign( + { host: addressParts[0], port: parseInt(addressParts[1], 10) }, + this.s.options, + options, + { bson: this.s.bson } + ); + + // NOTE: this should only be the case if we are connecting to a single server + poolOptions.reconnect = true; + poolOptions.legacyCompatMode = false; + + this.s.pool = new Pool(this, poolOptions); + + // setup listeners + this.s.pool.on('connect', connectEventHandler(this)); + this.s.pool.on('close', errorEventHandler(this)); + this.s.pool.on('error', errorEventHandler(this)); + this.s.pool.on('parseError', parseErrorEventHandler(this)); + + // it is unclear whether consumers should even know about these events + // this.s.pool.on('timeout', timeoutEventHandler(this)); + // this.s.pool.on('reconnect', reconnectEventHandler(this)); + // this.s.pool.on('reconnectFailed', errorEventHandler(this)); + + // relay all command monitoring events + relayEvents(this.s.pool, this, ['commandStarted', 'commandSucceeded', 'commandFailed']); + + this.s.state = STATE_CONNECTING; + + // If auth settings have been provided, use them + if (options.auth) { + this.s.pool.connect.apply(this.s.pool, options.auth); + return; + } + + this.s.pool.connect(); + } + + /** + * Destroy the server connection + * + * @param {Boolean} [options.force=false] Force destroy the pool + */ + destroy(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = Object.assign({}, { force: false }, options); + + this.s.state = STATE_DISCONNECTING; + const done = err => { + this.emit('closed'); + this.s.state = STATE_DISCONNECTED; + if (typeof callback === 'function') { + callback(err, null); + } + }; + + if (!this.s.pool) { + return done(); + } + + ['close', 'error', 'timeout', 'parseError', 'connect'].forEach(event => { + this.s.pool.removeAllListeners(event); + }); + + if (this.s.monitorId) { + clearTimeout(this.s.monitorId); + } + + this.s.pool.destroy(options.force, done); + } + + /** + * Immediately schedule monitoring of this server. If there already an attempt being made + * this will be a no-op. + */ + monitor(options) { + options = options || {}; + if (this.s.state !== STATE_CONNECTED || this.s.monitoring) return; + if (this.s.monitorId) clearTimeout(this.s.monitorId); + this.s.monitorFunction(this, options); + } + + /** + * Execute a command + * + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object} cmd The command hash + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.checkKeys=false] Specify if the bson parser should validate keys. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {Boolean} [options.fullResult=false] Return the full envelope instead of just the result document. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {opResultCallback} callback A callback function + */ + command(ns, cmd, options, callback) { + if (typeof options === 'function') { + (callback = options), (options = {}), (options = options || {}); + } + + const error = basicReadValidations(this, options); + if (error) { + return callback(error, null); + } + + // Clone the options + options = Object.assign({}, options, { wireProtocolCommand: false }); + + // Debug log + if (this.s.logger.isDebug()) { + this.s.logger.debug( + `executing command [${JSON.stringify({ + ns, + cmd, + options: debugOptions(DEBUG_FIELDS, options) + })}] against ${this.name}` + ); + } + + // error if collation not supported + if (collationNotSupported(this, cmd)) { + callback(new MongoError(`server ${this.name} does not support collation`)); + return; + } + + wireProtocol.command(this, ns, cmd, options, (err, result) => { + if (err) { + if (options.session && err instanceof MongoNetworkError) { + options.session.serverSession.isDirty = true; + } + + if (isSDAMUnrecoverableError(err, this)) { + this.emit('error', err); + } + } + + callback(err, result); + }); + } + + /** + * Execute a query against the server + * + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object} cmd The command document for the query + * @param {object} options Optional settings + * @param {function} callback + */ + query(ns, cmd, cursorState, options, callback) { + wireProtocol.query(this, ns, cmd, cursorState, options, (err, result) => { + if (err) { + if (options.session && err instanceof MongoNetworkError) { + options.session.serverSession.isDirty = true; + } + + if (isSDAMUnrecoverableError(err, this)) { + this.emit('error', err); + } + } + + callback(err, result); + }); + } + + /** + * Execute a `getMore` against the server + * + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object} cursorState State data associated with the cursor calling this method + * @param {object} options Optional settings + * @param {function} callback + */ + getMore(ns, cursorState, batchSize, options, callback) { + wireProtocol.getMore(this, ns, cursorState, batchSize, options, (err, result) => { + if (err) { + if (options.session && err instanceof MongoNetworkError) { + options.session.serverSession.isDirty = true; + } + + if (isSDAMUnrecoverableError(err, this)) { + this.emit('error', err); + } + } + + callback(err, result); + }); + } + + /** + * Execute a `killCursors` command against the server + * + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object} cursorState State data associated with the cursor calling this method + * @param {function} callback + */ + killCursors(ns, cursorState, callback) { + wireProtocol.killCursors(this, ns, cursorState, (err, result) => { + if (err && isSDAMUnrecoverableError(err, this)) { + this.emit('error', err); + } + + if (typeof callback === 'function') { + callback(err, result); + } + }); + } + + /** + * Insert one or more documents + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of documents to insert + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {opResultCallback} callback A callback function + */ + insert(ns, ops, options, callback) { + executeWriteOperation({ server: this, op: 'insert', ns, ops }, options, callback); + } + + /** + * Perform one or more update operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of updates + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {opResultCallback} callback A callback function + */ + update(ns, ops, options, callback) { + executeWriteOperation({ server: this, op: 'update', ns, ops }, options, callback); + } + + /** + * Perform one or more remove operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of removes + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {opResultCallback} callback A callback function + */ + remove(ns, ops, options, callback) { + executeWriteOperation({ server: this, op: 'remove', ns, ops }, options, callback); + } +} + +Object.defineProperty(Server.prototype, 'clusterTime', { + get: function() { + return this.s.topology.clusterTime; + }, + set: function(clusterTime) { + this.s.topology.clusterTime = clusterTime; + } +}); + +function basicWriteValidations(server) { + if (!server.s.pool) { + return new MongoError('server instance is not connected'); + } + + if (server.s.pool.isDestroyed()) { + return new MongoError('server instance pool was destroyed'); + } + + return null; +} + +function basicReadValidations(server, options) { + const error = basicWriteValidations(server, options); + if (error) { + return error; + } + + if (options.readPreference && !(options.readPreference instanceof ReadPreference)) { + return new MongoError('readPreference must be an instance of ReadPreference'); + } +} + +function executeWriteOperation(args, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + // TODO: once we drop Node 4, use destructuring either here or in arguments. + const server = args.server; + const op = args.op; + const ns = args.ns; + const ops = Array.isArray(args.ops) ? args.ops : [args.ops]; + + const error = basicWriteValidations(server, options); + if (error) { + callback(error, null); + return; + } + + if (collationNotSupported(server, options)) { + callback(new MongoError(`server ${server.name} does not support collation`)); + return; + } + + return wireProtocol[op](server, ns, ops, options, (err, result) => { + if (err) { + if (options.session && err instanceof MongoNetworkError) { + options.session.serverSession.isDirty = true; + } + + if (isSDAMUnrecoverableError(err, server)) { + server.emit('error', err); + } + } + + callback(err, result); + }); +} + +function connectEventHandler(server) { + return function(pool, conn) { + const ismaster = conn.ismaster; + server.s.lastIsMasterMS = conn.lastIsMasterMS; + if (conn.agreedCompressor) { + server.s.pool.options.agreedCompressor = conn.agreedCompressor; + } + + if (conn.zlibCompressionLevel) { + server.s.pool.options.zlibCompressionLevel = conn.zlibCompressionLevel; + } + + if (conn.ismaster.$clusterTime) { + const $clusterTime = conn.ismaster.$clusterTime; + server.s.sclusterTime = $clusterTime; + } + + // log the connection event if requested + if (server.s.logger.isInfo()) { + server.s.logger.info( + `server ${server.name} connected with ismaster [${JSON.stringify(ismaster)}]` + ); + } + + // emit an event indicating that our description has changed + server.emit('descriptionReceived', new ServerDescription(server.description.address, ismaster)); + + // we are connected and handshaked (guaranteed by the pool) + server.s.state = STATE_CONNECTED; + server.emit('connect', server); + }; +} + +function errorEventHandler(server) { + return function(err) { + if (err) { + server.emit('error', new MongoNetworkError(err)); + } + + server.emit('close'); + }; +} + +function parseErrorEventHandler(server) { + return function(err) { + server.s.state = STATE_DISCONNECTED; + server.emit('error', new MongoParseError(err)); + }; +} + +module.exports = Server; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/sdam/server_description.js b/scripts/2.5/node_modules/mongodb/lib/core/sdam/server_description.js new file mode 100644 index 00000000..41a5cf5b --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/core/sdam/server_description.js @@ -0,0 +1,163 @@ +'use strict'; + +// An enumeration of server types we know about +const ServerType = { + Standalone: 'Standalone', + Mongos: 'Mongos', + PossiblePrimary: 'PossiblePrimary', + RSPrimary: 'RSPrimary', + RSSecondary: 'RSSecondary', + RSArbiter: 'RSArbiter', + RSOther: 'RSOther', + RSGhost: 'RSGhost', + Unknown: 'Unknown' +}; + +const WRITABLE_SERVER_TYPES = new Set([ + ServerType.RSPrimary, + ServerType.Standalone, + ServerType.Mongos +]); + +const DATA_BEARING_SERVER_TYPES = new Set([ + ServerType.RSPrimary, + ServerType.RSSecondary, + ServerType.Mongos, + ServerType.Standalone +]); + +const ISMASTER_FIELDS = [ + 'minWireVersion', + 'maxWireVersion', + 'maxBsonObjectSize', + 'maxMessageSizeBytes', + 'maxWriteBatchSize', + 'compression', + 'me', + 'hosts', + 'passives', + 'arbiters', + 'tags', + 'setName', + 'setVersion', + 'electionId', + 'primary', + 'logicalSessionTimeoutMinutes', + 'saslSupportedMechs', + '__nodejs_mock_server__', + '$clusterTime' +]; + +/** + * The client's view of a single server, based on the most recent ismaster outcome. + * + * Internal type, not meant to be directly instantiated + */ +class ServerDescription { + /** + * Create a ServerDescription + * @param {String} address The address of the server + * @param {Object} [ismaster] An optional ismaster response for this server + * @param {Object} [options] Optional settings + * @param {Number} [options.roundTripTime] The round trip time to ping this server (in ms) + */ + constructor(address, ismaster, options) { + options = options || {}; + ismaster = Object.assign( + { + minWireVersion: 0, + maxWireVersion: 0, + hosts: [], + passives: [], + arbiters: [], + tags: [] + }, + ismaster + ); + + this.address = address; + this.error = options.error || null; + this.roundTripTime = options.roundTripTime || 0; + this.lastUpdateTime = Date.now(); + this.lastWriteDate = ismaster.lastWrite ? ismaster.lastWrite.lastWriteDate : null; + this.opTime = ismaster.lastWrite ? ismaster.lastWrite.opTime : null; + this.type = parseServerType(ismaster); + + // direct mappings + ISMASTER_FIELDS.forEach(field => { + if (typeof ismaster[field] !== 'undefined') this[field] = ismaster[field]; + }); + + // normalize case for hosts + if (this.me) this.me = this.me.toLowerCase(); + this.hosts = this.hosts.map(host => host.toLowerCase()); + this.passives = this.passives.map(host => host.toLowerCase()); + this.arbiters = this.arbiters.map(host => host.toLowerCase()); + } + + get allHosts() { + return this.hosts.concat(this.arbiters).concat(this.passives); + } + + /** + * @return {Boolean} Is this server available for reads + */ + get isReadable() { + return this.type === ServerType.RSSecondary || this.isWritable; + } + + /** + * @return {Boolean} Is this server data bearing + */ + get isDataBearing() { + return DATA_BEARING_SERVER_TYPES.has(this.type); + } + + /** + * @return {Boolean} Is this server available for writes + */ + get isWritable() { + return WRITABLE_SERVER_TYPES.has(this.type); + } +} + +/** + * Parses an `ismaster` message and determines the server type + * + * @param {Object} ismaster The `ismaster` message to parse + * @return {ServerType} + */ +function parseServerType(ismaster) { + if (!ismaster || !ismaster.ok) { + return ServerType.Unknown; + } + + if (ismaster.isreplicaset) { + return ServerType.RSGhost; + } + + if (ismaster.msg && ismaster.msg === 'isdbgrid') { + return ServerType.Mongos; + } + + if (ismaster.setName) { + if (ismaster.hidden) { + return ServerType.RSOther; + } else if (ismaster.ismaster) { + return ServerType.RSPrimary; + } else if (ismaster.secondary) { + return ServerType.RSSecondary; + } else if (ismaster.arbiterOnly) { + return ServerType.RSArbiter; + } else { + return ServerType.RSOther; + } + } + + return ServerType.Standalone; +} + +module.exports = { + ServerDescription, + ServerType +}; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/sdam/server_selectors.js b/scripts/2.5/node_modules/mongodb/lib/core/sdam/server_selectors.js new file mode 100644 index 00000000..f26d419e --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/core/sdam/server_selectors.js @@ -0,0 +1,244 @@ +'use strict'; +const ServerType = require('./server_description').ServerType; +const TopologyType = require('./topology_description').TopologyType; +const ReadPreference = require('../topologies/read_preference'); +const MongoError = require('../error').MongoError; + +// max staleness constants +const IDLE_WRITE_PERIOD = 10000; +const SMALLEST_MAX_STALENESS_SECONDS = 90; + +/** + * Returns a server selector that selects for writable servers + */ +function writableServerSelector() { + return function(topologyDescription, servers) { + return latencyWindowReducer(topologyDescription, servers.filter(s => s.isWritable)); + }; +} + +/** + * Reduces the passed in array of servers by the rules of the "Max Staleness" specification + * found here: https://github.com/mongodb/specifications/blob/master/source/max-staleness/max-staleness.rst + * + * @param {ReadPreference} readPreference The read preference providing max staleness guidance + * @param {topologyDescription} topologyDescription The topology description + * @param {ServerDescription[]} servers The list of server descriptions to be reduced + * @return {ServerDescription[]} The list of servers that satisfy the requirements of max staleness + */ +function maxStalenessReducer(readPreference, topologyDescription, servers) { + if (readPreference.maxStalenessSeconds == null || readPreference.maxStalenessSeconds < 0) { + return servers; + } + + const maxStaleness = readPreference.maxStalenessSeconds; + const maxStalenessVariance = + (topologyDescription.heartbeatFrequencyMS + IDLE_WRITE_PERIOD) / 1000; + if (maxStaleness < maxStalenessVariance) { + throw new MongoError(`maxStalenessSeconds must be at least ${maxStalenessVariance} seconds`); + } + + if (maxStaleness < SMALLEST_MAX_STALENESS_SECONDS) { + throw new MongoError( + `maxStalenessSeconds must be at least ${SMALLEST_MAX_STALENESS_SECONDS} seconds` + ); + } + + if (topologyDescription.type === TopologyType.ReplicaSetWithPrimary) { + const primary = servers.filter(primaryFilter)[0]; + return servers.reduce((result, server) => { + const stalenessMS = + server.lastUpdateTime - + server.lastWriteDate - + (primary.lastUpdateTime - primary.lastWriteDate) + + topologyDescription.heartbeatFrequencyMS; + + const staleness = stalenessMS / 1000; + if (staleness <= readPreference.maxStalenessSeconds) result.push(server); + return result; + }, []); + } else if (topologyDescription.type === TopologyType.ReplicaSetNoPrimary) { + const sMax = servers.reduce((max, s) => (s.lastWriteDate > max.lastWriteDate ? s : max)); + return servers.reduce((result, server) => { + const stalenessMS = + sMax.lastWriteDate - server.lastWriteDate + topologyDescription.heartbeatFrequencyMS; + + const staleness = stalenessMS / 1000; + if (staleness <= readPreference.maxStalenessSeconds) result.push(server); + return result; + }, []); + } + + return servers; +} + +/** + * Determines whether a server's tags match a given set of tags + * + * @param {String[]} tagSet The requested tag set to match + * @param {String[]} serverTags The server's tags + */ +function tagSetMatch(tagSet, serverTags) { + const keys = Object.keys(tagSet); + const serverTagKeys = Object.keys(serverTags); + for (let i = 0; i < keys.length; ++i) { + const key = keys[i]; + if (serverTagKeys.indexOf(key) === -1 || serverTags[key] !== tagSet[key]) { + return false; + } + } + + return true; +} + +/** + * Reduces a set of server descriptions based on tags requested by the read preference + * + * @param {ReadPreference} readPreference The read preference providing the requested tags + * @param {ServerDescription[]} servers The list of server descriptions to reduce + * @return {ServerDescription[]} The list of servers matching the requested tags + */ +function tagSetReducer(readPreference, servers) { + if ( + readPreference.tags == null || + (Array.isArray(readPreference.tags) && readPreference.tags.length === 0) + ) { + return servers; + } + + for (let i = 0; i < readPreference.tags.length; ++i) { + const tagSet = readPreference.tags[i]; + const serversMatchingTagset = servers.reduce((matched, server) => { + if (tagSetMatch(tagSet, server.tags)) matched.push(server); + return matched; + }, []); + + if (serversMatchingTagset.length) { + return serversMatchingTagset; + } + } + + return []; +} + +/** + * Reduces a list of servers to ensure they fall within an acceptable latency window. This is + * further specified in the "Server Selection" specification, found here: + * https://github.com/mongodb/specifications/blob/master/source/server-selection/server-selection.rst + * + * @param {topologyDescription} topologyDescription The topology description + * @param {ServerDescription[]} servers The list of servers to reduce + * @returns {ServerDescription[]} The servers which fall within an acceptable latency window + */ +function latencyWindowReducer(topologyDescription, servers) { + const low = servers.reduce( + (min, server) => (min === -1 ? server.roundTripTime : Math.min(server.roundTripTime, min)), + -1 + ); + + const high = low + topologyDescription.localThresholdMS; + + return servers.reduce((result, server) => { + if (server.roundTripTime <= high && server.roundTripTime >= low) result.push(server); + return result; + }, []); +} + +// filters +function primaryFilter(server) { + return server.type === ServerType.RSPrimary; +} + +function secondaryFilter(server) { + return server.type === ServerType.RSSecondary; +} + +function nearestFilter(server) { + return server.type === ServerType.RSSecondary || server.type === ServerType.RSPrimary; +} + +function knownFilter(server) { + return server.type !== ServerType.Unknown; +} + +/** + * Returns a function which selects servers based on a provided read preference + * + * @param {ReadPreference} readPreference The read preference to select with + */ +function readPreferenceServerSelector(readPreference) { + if (!readPreference.isValid()) { + throw new TypeError('Invalid read preference specified'); + } + + return function(topologyDescription, servers) { + const commonWireVersion = topologyDescription.commonWireVersion; + if ( + commonWireVersion && + (readPreference.minWireVersion && readPreference.minWireVersion > commonWireVersion) + ) { + throw new MongoError( + `Minimum wire version '${ + readPreference.minWireVersion + }' required, but found '${commonWireVersion}'` + ); + } + + if ( + topologyDescription.type === TopologyType.Single || + topologyDescription.type === TopologyType.Sharded + ) { + return latencyWindowReducer(topologyDescription, servers.filter(knownFilter)); + } + + if (readPreference.mode === ReadPreference.PRIMARY) { + return servers.filter(primaryFilter); + } + + if (readPreference.mode === ReadPreference.SECONDARY) { + return latencyWindowReducer( + topologyDescription, + tagSetReducer( + readPreference, + maxStalenessReducer(readPreference, topologyDescription, servers) + ) + ).filter(secondaryFilter); + } else if (readPreference.mode === ReadPreference.NEAREST) { + return latencyWindowReducer( + topologyDescription, + tagSetReducer( + readPreference, + maxStalenessReducer(readPreference, topologyDescription, servers) + ) + ).filter(nearestFilter); + } else if (readPreference.mode === ReadPreference.SECONDARY_PREFERRED) { + const result = latencyWindowReducer( + topologyDescription, + tagSetReducer( + readPreference, + maxStalenessReducer(readPreference, topologyDescription, servers) + ) + ).filter(secondaryFilter); + + return result.length === 0 ? servers.filter(primaryFilter) : result; + } else if (readPreference.mode === ReadPreference.PRIMARY_PREFERRED) { + const result = servers.filter(primaryFilter); + if (result.length) { + return result; + } + + return latencyWindowReducer( + topologyDescription, + tagSetReducer( + readPreference, + maxStalenessReducer(readPreference, topologyDescription, servers) + ) + ).filter(secondaryFilter); + } + }; +} + +module.exports = { + writableServerSelector, + readPreferenceServerSelector +}; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/sdam/srv_polling.js b/scripts/2.5/node_modules/mongodb/lib/core/sdam/srv_polling.js new file mode 100644 index 00000000..115ae45c --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/core/sdam/srv_polling.js @@ -0,0 +1,135 @@ +'use strict'; + +const Logger = require('../connection/logger'); +const EventEmitter = require('events').EventEmitter; +const dns = require('dns'); +/** + * Determines whether a provided address matches the provided parent domain in order + * to avoid certain attack vectors. + * + * @param {String} srvAddress The address to check against a domain + * @param {String} parentDomain The domain to check the provided address against + * @return {Boolean} Whether the provided address matches the parent domain + */ +function matchesParentDomain(srvAddress, parentDomain) { + const regex = /^.*?\./; + const srv = `.${srvAddress.replace(regex, '')}`; + const parent = `.${parentDomain.replace(regex, '')}`; + return srv.endsWith(parent); +} + +class SrvPollingEvent { + constructor(srvRecords) { + this.srvRecords = srvRecords; + } + + addresses() { + return new Set(this.srvRecords.map(record => `${record.name}:${record.port}`)); + } +} + +class SrvPoller extends EventEmitter { + /** + * @param {object} options + * @param {string} options.srvHost + * @param {number} [options.heartbeatFrequencyMS] + * @param {function} [options.logger] + * @param {string} [options.loggerLevel] + */ + constructor(options) { + super(); + + if (!options || !options.srvHost) { + throw new TypeError('options for SrvPoller must exist and include srvHost'); + } + + this.srvHost = options.srvHost; + this.rescanSrvIntervalMS = 60000; + this.heartbeatFrequencyMS = options.heartbeatFrequencyMS || 10000; + this.logger = Logger('srvPoller', options); + + this.haMode = false; + this.generation = 0; + + this._timeout = null; + } + + get srvAddress() { + return `_mongodb._tcp.${this.srvHost}`; + } + + get intervalMS() { + return this.haMode ? this.heartbeatFrequencyMS : this.rescanSrvIntervalMs; + } + + start() { + if (!this._timeout) { + this.schedule(); + } + } + + stop() { + if (this._timeout) { + clearTimeout(this._timeout); + this.generation += 1; + this._timeout = null; + } + } + + schedule() { + clearTimeout(this._timeout); + this._timeout = setTimeout(() => this._poll(), this.intervalMS); + } + + success(srvRecords) { + this.haMode = false; + this.schedule(); + this.emit('srvRecordDiscovery', new SrvPollingEvent(srvRecords)); + } + + failure(message, obj) { + this.logger.warn(message, obj); + this.haMode = true; + this.schedule(); + } + + parentDomainMismatch(srvRecord) { + this.logger.warn( + `parent domain mismatch on SRV record (${srvRecord.name}:${srvRecord.port})`, + srvRecord + ); + } + + _poll() { + const generation = this.generation; + dns.resolveSrv(this.srvAddress, (err, srvRecords) => { + if (generation !== this.generation) { + return; + } + + if (err) { + this.failure('DNS error', err); + return; + } + + const finalAddresses = []; + srvRecords.forEach(record => { + if (matchesParentDomain(record.name, this.srvHost)) { + finalAddresses.push(record); + } else { + this.parentDomainMismatch(record); + } + }); + + if (!finalAddresses.length) { + this.failure('No valid addresses found at host'); + return; + } + + this.success(finalAddresses); + }); + } +} + +module.exports.SrvPollingEvent = SrvPollingEvent; +module.exports.SrvPoller = SrvPoller; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/sdam/topology.js b/scripts/2.5/node_modules/mongodb/lib/core/sdam/topology.js new file mode 100644 index 00000000..5dab4b36 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/core/sdam/topology.js @@ -0,0 +1,1186 @@ +'use strict'; +const EventEmitter = require('events'); +const ServerDescription = require('./server_description').ServerDescription; +const ServerType = require('./server_description').ServerType; +const TopologyDescription = require('./topology_description').TopologyDescription; +const TopologyType = require('./topology_description').TopologyType; +const monitoring = require('./monitoring'); +const calculateDurationInMs = require('../utils').calculateDurationInMs; +const MongoTimeoutError = require('../error').MongoTimeoutError; +const Server = require('./server'); +const relayEvents = require('../utils').relayEvents; +const ReadPreference = require('../topologies/read_preference'); +const readPreferenceServerSelector = require('./server_selectors').readPreferenceServerSelector; +const writableServerSelector = require('./server_selectors').writableServerSelector; +const isRetryableWritesSupported = require('../topologies/shared').isRetryableWritesSupported; +const CoreCursor = require('../cursor').CoreCursor; +const deprecate = require('util').deprecate; +const BSON = require('../connection/utils').retrieveBSON(); +const createCompressionInfo = require('../topologies/shared').createCompressionInfo; +const isRetryableError = require('../error').isRetryableError; +const isSDAMUnrecoverableError = require('../error').isSDAMUnrecoverableError; +const ClientSession = require('../sessions').ClientSession; +const createClientInfo = require('../topologies/shared').createClientInfo; +const MongoError = require('../error').MongoError; +const resolveClusterTime = require('../topologies/shared').resolveClusterTime; +const SrvPoller = require('./srv_polling').SrvPoller; +const getMMAPError = require('../topologies/shared').getMMAPError; + +// Global state +let globalTopologyCounter = 0; + +// Constants +const TOPOLOGY_DEFAULTS = { + localThresholdMS: 15, + serverSelectionTimeoutMS: 30000, + heartbeatFrequencyMS: 10000, + minHeartbeatFrequencyMS: 500 +}; + +// events that we relay to the `Topology` +const SERVER_RELAY_EVENTS = [ + 'serverHeartbeatStarted', + 'serverHeartbeatSucceeded', + 'serverHeartbeatFailed', + 'commandStarted', + 'commandSucceeded', + 'commandFailed', + + // NOTE: Legacy events + 'monitoring' +]; + +// all events we listen to from `Server` instances +const LOCAL_SERVER_EVENTS = SERVER_RELAY_EVENTS.concat([ + 'error', + 'connect', + 'descriptionReceived', + 'close', + 'ended' +]); + +/** + * A container of server instances representing a connection to a MongoDB topology. + * + * @fires Topology#serverOpening + * @fires Topology#serverClosed + * @fires Topology#serverDescriptionChanged + * @fires Topology#topologyOpening + * @fires Topology#topologyClosed + * @fires Topology#topologyDescriptionChanged + * @fires Topology#serverHeartbeatStarted + * @fires Topology#serverHeartbeatSucceeded + * @fires Topology#serverHeartbeatFailed + */ +class Topology extends EventEmitter { + /** + * Create a topology + * + * @param {Array|String} [seedlist] a string list, or array of Server instances to connect to + * @param {Object} [options] Optional settings + * @param {Number} [options.localThresholdMS=15] The size of the latency window for selecting among multiple suitable servers + * @param {Number} [options.serverSelectionTimeoutMS=30000] How long to block for server selection before throwing an error + * @param {Number} [options.heartbeatFrequencyMS=10000] The frequency with which topology updates are scheduled + */ + constructor(seedlist, options) { + super(); + if (typeof options === 'undefined' && typeof seedlist !== 'string') { + options = seedlist; + seedlist = []; + + // this is for legacy single server constructor support + if (options.host) { + seedlist.push({ host: options.host, port: options.port }); + } + } + + seedlist = seedlist || []; + if (typeof seedlist === 'string') { + seedlist = parseStringSeedlist(seedlist); + } + + options = Object.assign({}, TOPOLOGY_DEFAULTS, options); + + const topologyType = topologyTypeFromSeedlist(seedlist, options); + const topologyId = globalTopologyCounter++; + const serverDescriptions = seedlist.reduce((result, seed) => { + if (seed.domain_socket) seed.host = seed.domain_socket; + const address = seed.port ? `${seed.host}:${seed.port}` : `${seed.host}:27017`; + result.set(address, new ServerDescription(address)); + return result; + }, new Map()); + + this.s = { + // the id of this topology + id: topologyId, + // passed in options + options, + // initial seedlist of servers to connect to + seedlist: seedlist, + // the topology description + description: new TopologyDescription( + topologyType, + serverDescriptions, + options.replicaSet, + null, + null, + null, + options + ), + serverSelectionTimeoutMS: options.serverSelectionTimeoutMS, + heartbeatFrequencyMS: options.heartbeatFrequencyMS, + minHeartbeatIntervalMS: options.minHeartbeatIntervalMS, + // allow users to override the cursor factory + Cursor: options.cursorFactory || CoreCursor, + // the bson parser + bson: + options.bson || + new BSON([ + BSON.Binary, + BSON.Code, + BSON.DBRef, + BSON.Decimal128, + BSON.Double, + BSON.Int32, + BSON.Long, + BSON.Map, + BSON.MaxKey, + BSON.MinKey, + BSON.ObjectId, + BSON.BSONRegExp, + BSON.Symbol, + BSON.Timestamp + ]), + // a map of server instances to normalized addresses + servers: new Map(), + // Server Session Pool + sessionPool: null, + // Active client sessions + sessions: new Set(), + // Promise library + promiseLibrary: options.promiseLibrary || Promise, + credentials: options.credentials, + clusterTime: null, + + // timer management + monitorTimers: [], + iterationTimers: [] + }; + + // amend options for server instance creation + this.s.options.compression = { compressors: createCompressionInfo(options) }; + + // add client info + this.s.clientInfo = createClientInfo(options); + + if (options.srvHost) { + this.s.srvPoller = + options.srvPoller || + new SrvPoller({ + heartbeatFrequencyMS: this.s.heartbeatFrequencyMS, + srvHost: options.srvHost, // TODO: GET THIS + logger: options.logger, + loggerLevel: options.loggerLevel + }); + this.s.detectTopologyDescriptionChange = ev => { + const previousType = ev.previousDescription.type; + const newType = ev.newDescription.type; + + if (previousType !== TopologyType.Sharded && newType === TopologyType.Sharded) { + this.s.handleSrvPolling = srvPollingHandler(this); + this.s.srvPoller.on('srvRecordDiscovery', this.s.handleSrvPolling); + this.s.srvPoller.start(); + } + }; + + this.on('topologyDescriptionChanged', this.s.detectTopologyDescriptionChange); + } + } + + /** + * @return A `TopologyDescription` for this topology + */ + get description() { + return this.s.description; + } + + get parserType() { + return BSON.native ? 'c++' : 'js'; + } + + /** + * All raw connections + * @method + * @return {Connection[]} + */ + connections() { + return Array.from(this.s.servers.values()).reduce((result, server) => { + return result.concat(server.s.pool.allConnections()); + }, []); + } + + /** + * Initiate server connect + * + * @param {Object} [options] Optional settings + * @param {Array} [options.auth=null] Array of auth options to apply on connect + * @param {function} [callback] An optional callback called once on the first connected server + */ + connect(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + // emit SDAM monitoring events + this.emit('topologyOpening', new monitoring.TopologyOpeningEvent(this.s.id)); + + // emit an event for the topology change + this.emit( + 'topologyDescriptionChanged', + new monitoring.TopologyDescriptionChangedEvent( + this.s.id, + new TopologyDescription(TopologyType.Unknown), // initial is always Unknown + this.s.description + ) + ); + + connectServers(this, Array.from(this.s.description.servers.values())); + this.s.connected = true; + + // otherwise, wait for a server to properly connect based on user provided read preference, + // or primary. + + translateReadPreference(options); + const readPreference = options.readPreference || ReadPreference.primary; + + this.selectServer(readPreferenceServerSelector(readPreference), options, (err, server) => { + if (err) { + if (typeof callback === 'function') { + callback(err, null); + } else { + this.emit('error', err); + } + + return; + } + + const errorHandler = err => { + server.removeListener('connect', connectHandler); + if (typeof callback === 'function') callback(err, null); + }; + + const connectHandler = (_, err) => { + server.removeListener('error', errorHandler); + this.emit('open', err, this); + this.emit('connect', this); + + if (typeof callback === 'function') callback(err, this); + }; + + const STATE_CONNECTING = 1; + if (server.s.state === STATE_CONNECTING) { + server.once('error', errorHandler); + server.once('connect', connectHandler); + return; + } + + connectHandler(); + }); + } + + /** + * Close this topology + */ + close(options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + + if (typeof options === 'boolean') { + options = { force: options }; + } + + options = options || {}; + + // clear all existing monitor timers + this.s.monitorTimers.map(timer => clearTimeout(timer)); + this.s.monitorTimers = []; + + this.s.iterationTimers.map(timer => clearTimeout(timer)); + this.s.iterationTimers = []; + + if (this.s.sessionPool) { + this.s.sessions.forEach(session => session.endSession()); + this.s.sessionPool.endAllPooledSessions(); + } + + if (this.s.srvPoller) { + this.s.srvPoller.stop(); + if (this.s.handleSrvPolling) { + this.s.srvPoller.removeListener('srvRecordDiscovery', this.s.handleSrvPolling); + delete this.s.handleSrvPolling; + } + } + + if (this.s.detectTopologyDescriptionChange) { + this.removeListener('topologyDescriptionChanged', this.s.detectTopologyDescriptionChange); + delete this.s.detectTopologyDescriptionChange; + } + + const servers = this.s.servers; + if (servers.size === 0) { + this.s.connected = false; + if (typeof callback === 'function') { + callback(null, null); + } + + return; + } + + // destroy all child servers + let destroyed = 0; + servers.forEach(server => + destroyServer(server, this, options, () => { + destroyed++; + if (destroyed === servers.size) { + // emit an event for close + this.emit('topologyClosed', new monitoring.TopologyClosedEvent(this.s.id)); + + this.s.connected = false; + if (typeof callback === 'function') { + callback(null, null); + } + } + }) + ); + } + + /** + * Selects a server according to the selection predicate provided + * + * @param {function} [selector] An optional selector to select servers by, defaults to a random selection within a latency window + * @param {object} [options] Optional settings related to server selection + * @param {number} [options.serverSelectionTimeoutMS] How long to block for server selection before throwing an error + * @param {function} callback The callback used to indicate success or failure + * @return {Server} An instance of a `Server` meeting the criteria of the predicate provided + */ + selectServer(selector, options, callback) { + if (typeof options === 'function') { + callback = options; + if (typeof selector !== 'function') { + options = selector; + + let readPreference; + if (selector instanceof ReadPreference) { + readPreference = selector; + } else { + translateReadPreference(options); + readPreference = options.readPreference || ReadPreference.primary; + } + + selector = readPreferenceServerSelector(readPreference); + } else { + options = {}; + } + } + + options = Object.assign( + {}, + { serverSelectionTimeoutMS: this.s.serverSelectionTimeoutMS }, + options + ); + + const isSharded = this.description.type === TopologyType.Sharded; + const session = options.session; + const transaction = session && session.transaction; + + if (isSharded && transaction && transaction.server) { + callback(null, transaction.server); + return; + } + + // clear out any existing iteration timers + this.s.iterationTimers.map(timer => clearTimeout(timer)); + this.s.iterationTimers = []; + + selectServers( + this, + selector, + options.serverSelectionTimeoutMS, + process.hrtime(), + (err, servers) => { + if (err) return callback(err, null); + + const selectedServer = randomSelection(servers); + if (isSharded && transaction && transaction.isActive) { + transaction.pinServer(selectedServer); + } + + callback(null, selectedServer); + } + ); + } + + // Sessions related methods + + /** + * @return Whether the topology should initiate selection to determine session support + */ + shouldCheckForSessionSupport() { + return ( + (this.description.type === TopologyType.Single && !this.description.hasKnownServers) || + !this.description.hasDataBearingServers + ); + } + + /** + * @return Whether sessions are supported on the current topology + */ + hasSessionSupport() { + return this.description.logicalSessionTimeoutMinutes != null; + } + + /** + * Start a logical session + */ + startSession(options, clientOptions) { + const session = new ClientSession(this, this.s.sessionPool, options, clientOptions); + session.once('ended', () => { + this.s.sessions.delete(session); + }); + + this.s.sessions.add(session); + return session; + } + + /** + * Send endSessions command(s) with the given session ids + * + * @param {Array} sessions The sessions to end + * @param {function} [callback] + */ + endSessions(sessions, callback) { + if (!Array.isArray(sessions)) { + sessions = [sessions]; + } + + this.command( + 'admin.$cmd', + { endSessions: sessions }, + { readPreference: ReadPreference.primaryPreferred, noResponse: true }, + () => { + // intentionally ignored, per spec + if (typeof callback === 'function') callback(); + } + ); + } + + /** + * Update the internal TopologyDescription with a ServerDescription + * + * @param {object} serverDescription The server to update in the internal list of server descriptions + */ + serverUpdateHandler(serverDescription) { + if (!this.s.description.hasServer(serverDescription.address)) { + return; + } + + // these will be used for monitoring events later + const previousTopologyDescription = this.s.description; + const previousServerDescription = this.s.description.servers.get(serverDescription.address); + + // first update the TopologyDescription + this.s.description = this.s.description.update(serverDescription); + if (this.s.description.compatibilityError) { + this.emit('error', new MongoError(this.s.description.compatibilityError)); + return; + } + + // emit monitoring events for this change + this.emit( + 'serverDescriptionChanged', + new monitoring.ServerDescriptionChangedEvent( + this.s.id, + serverDescription.address, + previousServerDescription, + this.s.description.servers.get(serverDescription.address) + ) + ); + + // update server list from updated descriptions + updateServers(this, serverDescription); + + // Driver Sessions Spec: "Whenever a driver receives a cluster time from + // a server it MUST compare it to the current highest seen cluster time + // for the deployment. If the new cluster time is higher than the + // highest seen cluster time it MUST become the new highest seen cluster + // time. Two cluster times are compared using only the BsonTimestamp + // value of the clusterTime embedded field." + const clusterTime = serverDescription.$clusterTime; + if (clusterTime) { + resolveClusterTime(this, clusterTime); + } + + this.emit( + 'topologyDescriptionChanged', + new monitoring.TopologyDescriptionChangedEvent( + this.s.id, + previousTopologyDescription, + this.s.description + ) + ); + } + + auth(credentials, callback) { + if (typeof credentials === 'function') (callback = credentials), (credentials = null); + if (typeof callback === 'function') callback(null, true); + } + + logout(callback) { + if (typeof callback === 'function') callback(null, true); + } + + // Basic operation support. Eventually this should be moved into command construction + // during the command refactor. + + /** + * Insert one or more documents + * + * @param {String} ns The full qualified namespace for this operation + * @param {Array} ops An array of documents to insert + * @param {Boolean} [options.ordered=true] Execute in order or out of order + * @param {Object} [options.writeConcern] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields + * @param {ClientSession} [options.session] Session to use for the operation + * @param {boolean} [options.retryWrites] Enable retryable writes for this operation + * @param {opResultCallback} callback A callback function + */ + insert(ns, ops, options, callback) { + executeWriteOperation({ topology: this, op: 'insert', ns, ops }, options, callback); + } + + /** + * Perform one or more update operations + * + * @param {string} ns The fully qualified namespace for this operation + * @param {array} ops An array of updates + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields + * @param {ClientSession} [options.session] Session to use for the operation + * @param {boolean} [options.retryWrites] Enable retryable writes for this operation + * @param {opResultCallback} callback A callback function + */ + update(ns, ops, options, callback) { + executeWriteOperation({ topology: this, op: 'update', ns, ops }, options, callback); + } + + /** + * Perform one or more remove operations + * + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of removes + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {boolean} [options.retryWrites] Enable retryable writes for this operation + * @param {opResultCallback} callback A callback function + */ + remove(ns, ops, options, callback) { + executeWriteOperation({ topology: this, op: 'remove', ns, ops }, options, callback); + } + + /** + * Execute a command + * + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object} cmd The command hash + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Connection} [options.connection] Specify connection object to execute command against + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {opResultCallback} callback A callback function + */ + command(ns, cmd, options, callback) { + if (typeof options === 'function') { + (callback = options), (options = {}), (options = options || {}); + } + + translateReadPreference(options); + const readPreference = options.readPreference || ReadPreference.primary; + + this.selectServer(readPreferenceServerSelector(readPreference), options, (err, server) => { + if (err) { + callback(err, null); + return; + } + + const willRetryWrite = + !options.retrying && + !!options.retryWrites && + options.session && + isRetryableWritesSupported(this) && + !options.session.inTransaction() && + isWriteCommand(cmd); + + const cb = (err, result) => { + if (!err) return callback(null, result); + if (!isRetryableError(err)) { + return callback(err); + } + + if (willRetryWrite) { + const newOptions = Object.assign({}, options, { retrying: true }); + return this.command(ns, cmd, newOptions, callback); + } + + return callback(err); + }; + + // increment and assign txnNumber + if (willRetryWrite) { + options.session.incrementTransactionNumber(); + options.willRetryWrite = willRetryWrite; + } + + server.command(ns, cmd, options, cb); + }); + } + + /** + * Create a new cursor + * + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object|Long} cmd Can be either a command returning a cursor or a cursorId + * @param {object} [options] Options for the cursor + * @param {object} [options.batchSize=0] Batchsize for the operation + * @param {array} [options.documents=[]] Initial documents list for cursor + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {object} [options.topology] The internal topology of the created cursor + * @returns {Cursor} + */ + cursor(ns, cmd, options) { + options = options || {}; + const topology = options.topology || this; + const CursorClass = options.cursorFactory || this.s.Cursor; + translateReadPreference(options); + + return new CursorClass(topology, ns, cmd, options); + } + + get clientInfo() { + return this.s.clientInfo; + } + + // Legacy methods for compat with old topology types + isConnected() { + // console.log('not implemented: `isConnected`'); + return true; + } + + isDestroyed() { + // console.log('not implemented: `isDestroyed`'); + return false; + } + + unref() { + console.log('not implemented: `unref`'); + } + + // NOTE: There are many places in code where we explicitly check the last isMaster + // to do feature support detection. This should be done any other way, but for + // now we will just return the first isMaster seen, which should suffice. + lastIsMaster() { + const serverDescriptions = Array.from(this.description.servers.values()); + if (serverDescriptions.length === 0) return {}; + + const sd = serverDescriptions.filter(sd => sd.type !== ServerType.Unknown)[0]; + const result = sd || { maxWireVersion: this.description.commonWireVersion }; + return result; + } + + get logicalSessionTimeoutMinutes() { + return this.description.logicalSessionTimeoutMinutes; + } + + get bson() { + return this.s.bson; + } +} + +Object.defineProperty(Topology.prototype, 'clusterTime', { + enumerable: true, + get: function() { + return this.s.clusterTime; + }, + set: function(clusterTime) { + this.s.clusterTime = clusterTime; + } +}); + +// legacy aliases +Topology.prototype.destroy = deprecate( + Topology.prototype.close, + 'destroy() is deprecated, please use close() instead' +); + +const RETRYABLE_WRITE_OPERATIONS = ['findAndModify', 'insert', 'update', 'delete']; +function isWriteCommand(command) { + return RETRYABLE_WRITE_OPERATIONS.some(op => command[op]); +} + +/** + * Destroys a server, and removes all event listeners from the instance + * + * @param {Server} server + */ +function destroyServer(server, topology, options, callback) { + options = options || {}; + LOCAL_SERVER_EVENTS.forEach(event => server.removeAllListeners(event)); + + server.destroy(options, () => { + topology.emit( + 'serverClosed', + new monitoring.ServerClosedEvent(topology.s.id, server.description.address) + ); + + if (typeof callback === 'function') callback(null, null); + }); +} + +/** + * Parses a basic seedlist in string form + * + * @param {string} seedlist The seedlist to parse + */ +function parseStringSeedlist(seedlist) { + return seedlist.split(',').map(seed => ({ + host: seed.split(':')[0], + port: seed.split(':')[1] || 27017 + })); +} + +function topologyTypeFromSeedlist(seedlist, options) { + const replicaSet = options.replicaSet || options.setName || options.rs_name; + if (seedlist.length === 1 && !replicaSet) return TopologyType.Single; + if (replicaSet) return TopologyType.ReplicaSetNoPrimary; + return TopologyType.Unknown; +} + +function randomSelection(array) { + return array[Math.floor(Math.random() * array.length)]; +} + +/** + * Selects servers using the provided selector + * + * @private + * @param {Topology} topology The topology to select servers from + * @param {function} selector The actual predicate used for selecting servers + * @param {Number} timeout The max time we are willing wait for selection + * @param {Number} start A high precision timestamp for the start of the selection process + * @param {function} callback The callback used to convey errors or the resultant servers + */ +function selectServers(topology, selector, timeout, start, callback) { + const duration = calculateDurationInMs(start); + if (duration >= timeout) { + return callback( + new MongoTimeoutError(`Server selection timed out after ${timeout} ms`), + topology.description.error + ); + } + + // ensure we are connected + if (!topology.s.connected) { + topology.connect(); + + // we want to make sure we're still within the requested timeout window + const failToConnectTimer = setTimeout(() => { + topology.removeListener('connect', connectHandler); + callback( + new MongoTimeoutError('Server selection timed out waiting to connect'), + topology.description.error + ); + }, timeout - duration); + + const connectHandler = () => { + clearTimeout(failToConnectTimer); + selectServers(topology, selector, timeout, process.hrtime(), callback); + }; + + topology.once('connect', connectHandler); + return; + } + + // otherwise, attempt server selection + const serverDescriptions = Array.from(topology.description.servers.values()); + let descriptions; + + // support server selection by options with readPreference + if (typeof selector === 'object') { + const readPreference = selector.readPreference + ? selector.readPreference + : ReadPreference.primary; + + selector = readPreferenceServerSelector(readPreference); + } + + try { + descriptions = selector + ? selector(topology.description, serverDescriptions) + : serverDescriptions; + } catch (e) { + return callback(e, null); + } + + if (descriptions.length) { + const servers = descriptions.map(description => topology.s.servers.get(description.address)); + return callback(null, servers); + } + + const retrySelection = () => { + // clear all existing monitor timers + topology.s.monitorTimers.map(timer => clearTimeout(timer)); + topology.s.monitorTimers = []; + + // ensure all server monitors attempt monitoring soon + topology.s.servers.forEach(server => { + const timer = setTimeout( + () => server.monitor({ heartbeatFrequencyMS: topology.description.heartbeatFrequencyMS }), + TOPOLOGY_DEFAULTS.minHeartbeatFrequencyMS + ); + + topology.s.monitorTimers.push(timer); + }); + + const descriptionChangedHandler = () => { + // successful iteration, clear the check timer + clearTimeout(iterationTimer); + topology.s.iterationTimers.splice(timerIndex, 1); + + // topology description has changed due to monitoring, reattempt server selection + selectServers(topology, selector, timeout, start, callback); + }; + + const iterationTimer = setTimeout(() => { + topology.removeListener('topologyDescriptionChanged', descriptionChangedHandler); + callback( + new MongoTimeoutError( + `Server selection timed out after ${timeout} ms`, + topology.description.error + ) + ); + }, timeout - duration); + + // track this timer in case we need to clean it up outside this loop + const timerIndex = topology.s.iterationTimers.push(iterationTimer); + + topology.once('topologyDescriptionChanged', descriptionChangedHandler); + }; + + retrySelection(); +} + +function createAndConnectServer(topology, serverDescription) { + topology.emit( + 'serverOpening', + new monitoring.ServerOpeningEvent(topology.s.id, serverDescription.address) + ); + + const server = new Server(serverDescription, topology.s.options, topology); + relayEvents(server, topology, SERVER_RELAY_EVENTS); + + server.once('connect', serverConnectEventHandler(server, topology)); + server.on('descriptionReceived', topology.serverUpdateHandler.bind(topology)); + server.on('error', serverErrorEventHandler(server, topology)); + server.on('close', () => topology.emit('close', server)); + server.connect(); + return server; +} + +/** + * Create `Server` instances for all initially known servers, connect them, and assign + * them to the passed in `Topology`. + * + * @param {Topology} topology The topology responsible for the servers + * @param {ServerDescription[]} serverDescriptions A list of server descriptions to connect + */ +function connectServers(topology, serverDescriptions) { + topology.s.servers = serverDescriptions.reduce((servers, serverDescription) => { + const server = createAndConnectServer(topology, serverDescription); + servers.set(serverDescription.address, server); + return servers; + }, new Map()); +} + +function updateServers(topology, incomingServerDescription) { + // update the internal server's description + if (incomingServerDescription && topology.s.servers.has(incomingServerDescription.address)) { + const server = topology.s.servers.get(incomingServerDescription.address); + server.s.description = incomingServerDescription; + } + + // add new servers for all descriptions we currently don't know about locally + for (const serverDescription of topology.description.servers.values()) { + if (!topology.s.servers.has(serverDescription.address)) { + const server = createAndConnectServer(topology, serverDescription); + topology.s.servers.set(serverDescription.address, server); + } + } + + // for all servers no longer known, remove their descriptions and destroy their instances + for (const entry of topology.s.servers) { + const serverAddress = entry[0]; + if (topology.description.hasServer(serverAddress)) { + continue; + } + + const server = topology.s.servers.get(serverAddress); + topology.s.servers.delete(serverAddress); + + // prepare server for garbage collection + destroyServer(server, topology); + } +} + +function serverConnectEventHandler(server, topology) { + return function(/* isMaster, err */) { + server.monitor({ + initial: true, + heartbeatFrequencyMS: topology.description.heartbeatFrequencyMS + }); + }; +} + +function serverErrorEventHandler(server /*, topology */) { + return function(err) { + if (isSDAMUnrecoverableError(err, server)) { + resetServerState(server, err, { clearPool: true }); + return; + } + + resetServerState(server, err); + }; +} + +function executeWriteOperation(args, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + // TODO: once we drop Node 4, use destructuring either here or in arguments. + const topology = args.topology; + const op = args.op; + const ns = args.ns; + const ops = args.ops; + + const willRetryWrite = + !args.retrying && + !!options.retryWrites && + options.session && + isRetryableWritesSupported(topology) && + !options.session.inTransaction(); + + topology.selectServer(writableServerSelector(), options, (err, server) => { + if (err) { + callback(err, null); + return; + } + + const handler = (err, result) => { + if (!err) return callback(null, result); + if (!isRetryableError(err)) { + err = getMMAPError(err); + return callback(err); + } + + if (willRetryWrite) { + const newArgs = Object.assign({}, args, { retrying: true }); + return executeWriteOperation(newArgs, options, callback); + } + + return callback(err); + }; + + if (callback.operationId) { + handler.operationId = callback.operationId; + } + + // increment and assign txnNumber + if (willRetryWrite) { + options.session.incrementTransactionNumber(); + options.willRetryWrite = willRetryWrite; + } + + // execute the write operation + server[op](ns, ops, options, handler); + }); +} + +/** + * Resets the internal state of this server to `Unknown` by simulating an empty ismaster + * + * @private + * @param {Server} server + * @param {MongoError} error The error that caused the state reset + * @param {object} [options] Optional settings + * @param {boolean} [options.clearPool=false] Pool should be cleared out on state reset + */ +function resetServerState(server, error, options) { + options = Object.assign({}, { clearPool: false }, options); + + function resetState() { + server.emit( + 'descriptionReceived', + new ServerDescription(server.description.address, null, { error }) + ); + + process.nextTick(() => server.monitor()); + } + + if (options.clearPool && server.s.pool) { + server.s.pool.reset(() => resetState()); + return; + } + + resetState(); +} + +function translateReadPreference(options) { + if (options.readPreference == null) { + return; + } + + let r = options.readPreference; + if (typeof r === 'string') { + options.readPreference = new ReadPreference(r); + } else if (r && !(r instanceof ReadPreference) && typeof r === 'object') { + const mode = r.mode || r.preference; + if (mode && typeof mode === 'string') { + options.readPreference = new ReadPreference(mode, r.tags, { + maxStalenessSeconds: r.maxStalenessSeconds + }); + } + } else if (!(r instanceof ReadPreference)) { + throw new TypeError('Invalid read preference: ' + r); + } + + return options; +} + +function srvPollingHandler(topology) { + return function handleSrvPolling(ev) { + const previousTopologyDescription = topology.s.description; + topology.s.description = topology.s.description.updateFromSrvPollingEvent(ev); + if (topology.s.description === previousTopologyDescription) { + // Nothing changed, so return + return; + } + + updateServers(topology); + + topology.emit( + 'topologyDescriptionChanged', + new monitoring.TopologyDescriptionChangedEvent( + topology.s.id, + previousTopologyDescription, + topology.s.description + ) + ); + }; +} + +/** + * A server opening SDAM monitoring event + * + * @event Topology#serverOpening + * @type {ServerOpeningEvent} + */ + +/** + * A server closed SDAM monitoring event + * + * @event Topology#serverClosed + * @type {ServerClosedEvent} + */ + +/** + * A server description SDAM change monitoring event + * + * @event Topology#serverDescriptionChanged + * @type {ServerDescriptionChangedEvent} + */ + +/** + * A topology open SDAM event + * + * @event Topology#topologyOpening + * @type {TopologyOpeningEvent} + */ + +/** + * A topology closed SDAM event + * + * @event Topology#topologyClosed + * @type {TopologyClosedEvent} + */ + +/** + * A topology structure SDAM change event + * + * @event Topology#topologyDescriptionChanged + * @type {TopologyDescriptionChangedEvent} + */ + +/** + * A topology serverHeartbeatStarted SDAM event + * + * @event Topology#serverHeartbeatStarted + * @type {ServerHeartbeatStartedEvent} + */ + +/** + * A topology serverHeartbeatFailed SDAM event + * + * @event Topology#serverHeartbeatFailed + * @type {ServerHearbeatFailedEvent} + */ + +/** + * A topology serverHeartbeatSucceeded SDAM change event + * + * @event Topology#serverHeartbeatSucceeded + * @type {ServerHeartbeatSucceededEvent} + */ + +/** + * An event emitted indicating a command was started, if command monitoring is enabled + * + * @event Topology#commandStarted + * @type {object} + */ + +/** + * An event emitted indicating a command succeeded, if command monitoring is enabled + * + * @event Topology#commandSucceeded + * @type {object} + */ + +/** + * An event emitted indicating a command failed, if command monitoring is enabled + * + * @event Topology#commandFailed + * @type {object} + */ + +module.exports = Topology; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/sdam/topology_description.js b/scripts/2.5/node_modules/mongodb/lib/core/sdam/topology_description.js new file mode 100644 index 00000000..a94fb678 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/core/sdam/topology_description.js @@ -0,0 +1,408 @@ +'use strict'; +const ServerType = require('./server_description').ServerType; +const ServerDescription = require('./server_description').ServerDescription; +const WIRE_CONSTANTS = require('../wireprotocol/constants'); + +// contstants related to compatability checks +const MIN_SUPPORTED_SERVER_VERSION = WIRE_CONSTANTS.MIN_SUPPORTED_SERVER_VERSION; +const MAX_SUPPORTED_SERVER_VERSION = WIRE_CONSTANTS.MAX_SUPPORTED_SERVER_VERSION; +const MIN_SUPPORTED_WIRE_VERSION = WIRE_CONSTANTS.MIN_SUPPORTED_WIRE_VERSION; +const MAX_SUPPORTED_WIRE_VERSION = WIRE_CONSTANTS.MAX_SUPPORTED_WIRE_VERSION; + +// An enumeration of topology types we know about +const TopologyType = { + Single: 'Single', + ReplicaSetNoPrimary: 'ReplicaSetNoPrimary', + ReplicaSetWithPrimary: 'ReplicaSetWithPrimary', + Sharded: 'Sharded', + Unknown: 'Unknown' +}; + +// Representation of a deployment of servers +class TopologyDescription { + /** + * Create a TopologyDescription + * + * @param {string} topologyType + * @param {Map} serverDescriptions the a map of address to ServerDescription + * @param {string} setName + * @param {number} maxSetVersion + * @param {ObjectId} maxElectionId + */ + constructor( + topologyType, + serverDescriptions, + setName, + maxSetVersion, + maxElectionId, + commonWireVersion, + options, + error + ) { + options = options || {}; + + // TODO: consider assigning all these values to a temporary value `s` which + // we use `Object.freeze` on, ensuring the internal state of this type + // is immutable. + this.type = topologyType || TopologyType.Unknown; + this.setName = setName || null; + this.maxSetVersion = maxSetVersion || null; + this.maxElectionId = maxElectionId || null; + this.servers = serverDescriptions || new Map(); + this.stale = false; + this.compatible = true; + this.compatibilityError = null; + this.logicalSessionTimeoutMinutes = null; + this.heartbeatFrequencyMS = options.heartbeatFrequencyMS || 0; + this.localThresholdMS = options.localThresholdMS || 0; + this.options = options; + this.error = error; + this.commonWireVersion = commonWireVersion || null; + + // determine server compatibility + for (const serverDescription of this.servers.values()) { + if (serverDescription.type === ServerType.Unknown) continue; + + if (serverDescription.minWireVersion > MAX_SUPPORTED_WIRE_VERSION) { + this.compatible = false; + this.compatibilityError = `Server at ${serverDescription.address} requires wire version ${ + serverDescription.minWireVersion + }, but this version of the driver only supports up to ${MAX_SUPPORTED_WIRE_VERSION} (MongoDB ${MAX_SUPPORTED_SERVER_VERSION})`; + } + + if (serverDescription.maxWireVersion < MIN_SUPPORTED_WIRE_VERSION) { + this.compatible = false; + this.compatibilityError = `Server at ${serverDescription.address} reports wire version ${ + serverDescription.maxWireVersion + }, but this version of the driver requires at least ${MIN_SUPPORTED_WIRE_VERSION} (MongoDB ${MIN_SUPPORTED_SERVER_VERSION}).`; + break; + } + } + + // Whenever a client updates the TopologyDescription from an ismaster response, it MUST set + // TopologyDescription.logicalSessionTimeoutMinutes to the smallest logicalSessionTimeoutMinutes + // value among ServerDescriptions of all data-bearing server types. If any have a null + // logicalSessionTimeoutMinutes, then TopologyDescription.logicalSessionTimeoutMinutes MUST be + // set to null. + const readableServers = Array.from(this.servers.values()).filter(s => s.isReadable); + this.logicalSessionTimeoutMinutes = readableServers.reduce((result, server) => { + if (server.logicalSessionTimeoutMinutes == null) return null; + if (result == null) return server.logicalSessionTimeoutMinutes; + return Math.min(result, server.logicalSessionTimeoutMinutes); + }, null); + } + + /** + * Returns a new TopologyDescription based on the SrvPollingEvent + * @param {SrvPollingEvent} ev The event + */ + updateFromSrvPollingEvent(ev) { + const newAddresses = ev.addresses(); + const serverDescriptions = new Map(this.servers); + for (const server of this.servers) { + if (newAddresses.has(server[0])) { + newAddresses.delete(server[0]); + } else { + serverDescriptions.delete(server[0]); + } + } + + if (serverDescriptions.size === this.servers.size && newAddresses.size === 0) { + return this; + } + + for (const address of newAddresses) { + serverDescriptions.set(address, new ServerDescription(address)); + } + + return new TopologyDescription( + this.type, + serverDescriptions, + this.setName, + this.maxSetVersion, + this.maxElectionId, + this.commonWireVersion, + this.options, + null + ); + } + + /** + * Returns a copy of this description updated with a given ServerDescription + * + * @param {ServerDescription} serverDescription + */ + update(serverDescription) { + const address = serverDescription.address; + // NOTE: there are a number of prime targets for refactoring here + // once we support destructuring assignments + + // potentially mutated values + let topologyType = this.type; + let setName = this.setName; + let maxSetVersion = this.maxSetVersion; + let maxElectionId = this.maxElectionId; + let commonWireVersion = this.commonWireVersion; + let error = serverDescription.error || this.error; + + const serverType = serverDescription.type; + let serverDescriptions = new Map(this.servers); + + // update common wire version + if (serverDescription.maxWireVersion !== 0) { + if (commonWireVersion == null) { + commonWireVersion = serverDescription.maxWireVersion; + } else { + commonWireVersion = Math.min(commonWireVersion, serverDescription.maxWireVersion); + } + } + + // update the actual server description + serverDescriptions.set(address, serverDescription); + + if (topologyType === TopologyType.Single) { + // once we are defined as single, that never changes + return new TopologyDescription( + TopologyType.Single, + serverDescriptions, + setName, + maxSetVersion, + maxElectionId, + commonWireVersion, + this.options, + error + ); + } + + if (topologyType === TopologyType.Unknown) { + if (serverType === ServerType.Standalone) { + serverDescriptions.delete(address); + } else { + topologyType = topologyTypeForServerType(serverType); + } + } + + if (topologyType === TopologyType.Sharded) { + if ([ServerType.Mongos, ServerType.Unknown].indexOf(serverType) === -1) { + serverDescriptions.delete(address); + } + } + + if (topologyType === TopologyType.ReplicaSetNoPrimary) { + if ([ServerType.Mongos, ServerType.Unknown].indexOf(serverType) >= 0) { + serverDescriptions.delete(address); + } + + if (serverType === ServerType.RSPrimary) { + const result = updateRsFromPrimary( + serverDescriptions, + setName, + serverDescription, + maxSetVersion, + maxElectionId + ); + + (topologyType = result[0]), + (setName = result[1]), + (maxSetVersion = result[2]), + (maxElectionId = result[3]); + } else if ( + [ServerType.RSSecondary, ServerType.RSArbiter, ServerType.RSOther].indexOf(serverType) >= 0 + ) { + const result = updateRsNoPrimaryFromMember(serverDescriptions, setName, serverDescription); + (topologyType = result[0]), (setName = result[1]); + } + } + + if (topologyType === TopologyType.ReplicaSetWithPrimary) { + if ([ServerType.Standalone, ServerType.Mongos].indexOf(serverType) >= 0) { + serverDescriptions.delete(address); + topologyType = checkHasPrimary(serverDescriptions); + } else if (serverType === ServerType.RSPrimary) { + const result = updateRsFromPrimary( + serverDescriptions, + setName, + serverDescription, + maxSetVersion, + maxElectionId + ); + + (topologyType = result[0]), + (setName = result[1]), + (maxSetVersion = result[2]), + (maxElectionId = result[3]); + } else if ( + [ServerType.RSSecondary, ServerType.RSArbiter, ServerType.RSOther].indexOf(serverType) >= 0 + ) { + topologyType = updateRsWithPrimaryFromMember( + serverDescriptions, + setName, + serverDescription + ); + } else { + topologyType = checkHasPrimary(serverDescriptions); + } + } + + return new TopologyDescription( + topologyType, + serverDescriptions, + setName, + maxSetVersion, + maxElectionId, + commonWireVersion, + this.options, + error + ); + } + + /** + * Determines if the topology description has any known servers + */ + get hasKnownServers() { + return Array.from(this.servers.values()).some(sd => sd.type !== ServerDescription.Unknown); + } + + /** + * Determines if this topology description has a data-bearing server available. + */ + get hasDataBearingServers() { + return Array.from(this.servers.values()).some(sd => sd.isDataBearing); + } + + /** + * Determines if the topology has a definition for the provided address + * + * @param {String} address + * @return {Boolean} Whether the topology knows about this server + */ + hasServer(address) { + return this.servers.has(address); + } +} + +function topologyTypeForServerType(serverType) { + if (serverType === ServerType.Mongos) return TopologyType.Sharded; + if (serverType === ServerType.RSPrimary) return TopologyType.ReplicaSetWithPrimary; + return TopologyType.ReplicaSetNoPrimary; +} + +function updateRsFromPrimary( + serverDescriptions, + setName, + serverDescription, + maxSetVersion, + maxElectionId +) { + setName = setName || serverDescription.setName; + if (setName !== serverDescription.setName) { + serverDescriptions.delete(serverDescription.address); + return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId]; + } + + const electionIdOID = serverDescription.electionId ? serverDescription.electionId.$oid : null; + const maxElectionIdOID = maxElectionId ? maxElectionId.$oid : null; + if (serverDescription.setVersion != null && electionIdOID != null) { + if (maxSetVersion != null && maxElectionIdOID != null) { + if (maxSetVersion > serverDescription.setVersion || maxElectionIdOID > electionIdOID) { + // this primary is stale, we must remove it + serverDescriptions.set( + serverDescription.address, + new ServerDescription(serverDescription.address) + ); + + return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId]; + } + } + + maxElectionId = serverDescription.electionId; + } + + if ( + serverDescription.setVersion != null && + (maxSetVersion == null || serverDescription.setVersion > maxSetVersion) + ) { + maxSetVersion = serverDescription.setVersion; + } + + // We've heard from the primary. Is it the same primary as before? + for (const address of serverDescriptions.keys()) { + const server = serverDescriptions.get(address); + + if (server.type === ServerType.RSPrimary && server.address !== serverDescription.address) { + // Reset old primary's type to Unknown. + serverDescriptions.set(address, new ServerDescription(server.address)); + + // There can only be one primary + break; + } + } + + // Discover new hosts from this primary's response. + serverDescription.allHosts.forEach(address => { + if (!serverDescriptions.has(address)) { + serverDescriptions.set(address, new ServerDescription(address)); + } + }); + + // Remove hosts not in the response. + const currentAddresses = Array.from(serverDescriptions.keys()); + const responseAddresses = serverDescription.allHosts; + currentAddresses.filter(addr => responseAddresses.indexOf(addr) === -1).forEach(address => { + serverDescriptions.delete(address); + }); + + return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId]; +} + +function updateRsWithPrimaryFromMember(serverDescriptions, setName, serverDescription) { + if (setName == null) { + throw new TypeError('setName is required'); + } + + if ( + setName !== serverDescription.setName || + (serverDescription.me && serverDescription.address !== serverDescription.me) + ) { + serverDescriptions.delete(serverDescription.address); + } + + return checkHasPrimary(serverDescriptions); +} + +function updateRsNoPrimaryFromMember(serverDescriptions, setName, serverDescription) { + let topologyType = TopologyType.ReplicaSetNoPrimary; + + setName = setName || serverDescription.setName; + if (setName !== serverDescription.setName) { + serverDescriptions.delete(serverDescription.address); + return [topologyType, setName]; + } + + serverDescription.allHosts.forEach(address => { + if (!serverDescriptions.has(address)) { + serverDescriptions.set(address, new ServerDescription(address)); + } + }); + + if (serverDescription.me && serverDescription.address !== serverDescription.me) { + serverDescriptions.delete(serverDescription.address); + } + + return [topologyType, setName]; +} + +function checkHasPrimary(serverDescriptions) { + for (const addr of serverDescriptions.keys()) { + if (serverDescriptions.get(addr).type === ServerType.RSPrimary) { + return TopologyType.ReplicaSetWithPrimary; + } + } + + return TopologyType.ReplicaSetNoPrimary; +} + +module.exports = { + TopologyType, + TopologyDescription +}; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/sessions.js b/scripts/2.5/node_modules/mongodb/lib/core/sessions.js new file mode 100644 index 00000000..d15015c8 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/core/sessions.js @@ -0,0 +1,767 @@ +'use strict'; + +const retrieveBSON = require('./connection/utils').retrieveBSON; +const EventEmitter = require('events'); +const BSON = retrieveBSON(); +const Binary = BSON.Binary; +const uuidV4 = require('./utils').uuidV4; +const MongoError = require('./error').MongoError; +const isRetryableError = require('././error').isRetryableError; +const MongoNetworkError = require('./error').MongoNetworkError; +const MongoWriteConcernError = require('./error').MongoWriteConcernError; +const Transaction = require('./transactions').Transaction; +const TxnState = require('./transactions').TxnState; +const isPromiseLike = require('./utils').isPromiseLike; +const ReadPreference = require('./topologies/read_preference'); +const isTransactionCommand = require('./transactions').isTransactionCommand; +const resolveClusterTime = require('./topologies/shared').resolveClusterTime; +const isSharded = require('./wireprotocol/shared').isSharded; +const maxWireVersion = require('./utils').maxWireVersion; + +const minWireVersionForShardedTransactions = 8; + +function assertAlive(session, callback) { + if (session.serverSession == null) { + const error = new MongoError('Cannot use a session that has ended'); + if (typeof callback === 'function') { + callback(error, null); + return false; + } + + throw error; + } + + return true; +} + +/** + * Options to pass when creating a Client Session + * @typedef {Object} SessionOptions + * @property {boolean} [causalConsistency=true] Whether causal consistency should be enabled on this session + * @property {TransactionOptions} [defaultTransactionOptions] The default TransactionOptions to use for transactions started on this session. + */ + +/** + * A BSON document reflecting the lsid of a {@link ClientSession} + * @typedef {Object} SessionId + */ + +/** + * A class representing a client session on the server + * WARNING: not meant to be instantiated directly. + * @class + * @hideconstructor + */ +class ClientSession extends EventEmitter { + /** + * Create a client session. + * WARNING: not meant to be instantiated directly + * + * @param {Topology} topology The current client's topology (Internal Class) + * @param {ServerSessionPool} sessionPool The server session pool (Internal Class) + * @param {SessionOptions} [options] Optional settings + * @param {Object} [clientOptions] Optional settings provided when creating a client in the porcelain driver + */ + constructor(topology, sessionPool, options, clientOptions) { + super(); + + if (topology == null) { + throw new Error('ClientSession requires a topology'); + } + + if (sessionPool == null || !(sessionPool instanceof ServerSessionPool)) { + throw new Error('ClientSession requires a ServerSessionPool'); + } + + options = options || {}; + clientOptions = clientOptions || {}; + + this.topology = topology; + this.sessionPool = sessionPool; + this.hasEnded = false; + this.serverSession = sessionPool.acquire(); + this.clientOptions = clientOptions; + + this.supports = { + causalConsistency: + typeof options.causalConsistency !== 'undefined' ? options.causalConsistency : true + }; + + this.clusterTime = options.initialClusterTime; + + this.operationTime = null; + this.explicit = !!options.explicit; + this.owner = options.owner; + this.defaultTransactionOptions = Object.assign({}, options.defaultTransactionOptions); + this.transaction = new Transaction(); + } + + /** + * The server id associated with this session + * @type {SessionId} + */ + get id() { + return this.serverSession.id; + } + + /** + * Ends this session on the server + * + * @param {Object} [options] Optional settings. Currently reserved for future use + * @param {Function} [callback] Optional callback for completion of this operation + */ + endSession(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + if (this.hasEnded) { + if (typeof callback === 'function') callback(null, null); + return; + } + + if (this.serverSession && this.inTransaction()) { + this.abortTransaction(); // pass in callback? + } + + // mark the session as ended, and emit a signal + this.hasEnded = true; + this.emit('ended', this); + + // release the server session back to the pool + this.sessionPool.release(this.serverSession); + this.serverSession = null; + + // spec indicates that we should ignore all errors for `endSessions` + if (typeof callback === 'function') callback(null, null); + } + + /** + * Advances the operationTime for a ClientSession. + * + * @param {Timestamp} operationTime the `BSON.Timestamp` of the operation type it is desired to advance to + */ + advanceOperationTime(operationTime) { + if (this.operationTime == null) { + this.operationTime = operationTime; + return; + } + + if (operationTime.greaterThan(this.operationTime)) { + this.operationTime = operationTime; + } + } + + /** + * Used to determine if this session equals another + * @param {ClientSession} session + * @return {boolean} true if the sessions are equal + */ + equals(session) { + if (!(session instanceof ClientSession)) { + return false; + } + + return this.id.id.buffer.equals(session.id.id.buffer); + } + + /** + * Increment the transaction number on the internal ServerSession + */ + incrementTransactionNumber() { + this.serverSession.txnNumber++; + } + + /** + * @returns {boolean} whether this session is currently in a transaction or not + */ + inTransaction() { + return this.transaction.isActive; + } + + /** + * Starts a new transaction with the given options. + * + * @param {TransactionOptions} options Options for the transaction + */ + startTransaction(options) { + assertAlive(this); + if (this.inTransaction()) { + throw new MongoError('Transaction already in progress'); + } + + const topologyMaxWireVersion = maxWireVersion(this.topology); + if ( + isSharded(this.topology) && + topologyMaxWireVersion != null && + topologyMaxWireVersion < minWireVersionForShardedTransactions + ) { + throw new MongoError('Transactions are not supported on sharded clusters in MongoDB < 4.2.'); + } + + // increment txnNumber + this.incrementTransactionNumber(); + + // create transaction state + this.transaction = new Transaction( + Object.assign({}, this.clientOptions, options || this.defaultTransactionOptions) + ); + + this.transaction.transition(TxnState.STARTING_TRANSACTION); + } + + /** + * Commits the currently active transaction in this session. + * + * @param {Function} [callback] optional callback for completion of this operation + * @return {Promise} A promise is returned if no callback is provided + */ + commitTransaction(callback) { + if (typeof callback === 'function') { + endTransaction(this, 'commitTransaction', callback); + return; + } + + return new Promise((resolve, reject) => { + endTransaction( + this, + 'commitTransaction', + (err, reply) => (err ? reject(err) : resolve(reply)) + ); + }); + } + + /** + * Aborts the currently active transaction in this session. + * + * @param {Function} [callback] optional callback for completion of this operation + * @return {Promise} A promise is returned if no callback is provided + */ + abortTransaction(callback) { + if (typeof callback === 'function') { + endTransaction(this, 'abortTransaction', callback); + return; + } + + return new Promise((resolve, reject) => { + endTransaction( + this, + 'abortTransaction', + (err, reply) => (err ? reject(err) : resolve(reply)) + ); + }); + } + + /** + * This is here to ensure that ClientSession is never serialized to BSON. + * @ignore + */ + toBSON() { + throw new Error('ClientSession cannot be serialized to BSON.'); + } + + /** + * A user provided function to be run within a transaction + * + * @callback WithTransactionCallback + * @param {ClientSession} session The parent session of the transaction running the operation. This should be passed into each operation within the lambda. + * @returns {Promise} The resulting Promise of operations run within this transaction + */ + + /** + * Runs a provided lambda within a transaction, retrying either the commit operation + * or entire transaction as needed (and when the error permits) to better ensure that + * the transaction can complete successfully. + * + * IMPORTANT: This method requires the user to return a Promise, all lambdas that do not + * return a Promise will result in undefined behavior. + * + * @param {WithTransactionCallback} fn + * @param {TransactionOptions} [options] Optional settings for the transaction + */ + withTransaction(fn, options) { + const startTime = Date.now(); + return attemptTransaction(this, startTime, fn, options); + } +} + +const MAX_WITH_TRANSACTION_TIMEOUT = 120000; +const UNSATISFIABLE_WRITE_CONCERN_CODE = 100; +const UNKNOWN_REPL_WRITE_CONCERN_CODE = 79; +const MAX_TIME_MS_EXPIRED_CODE = 50; +const NON_DETERMINISTIC_WRITE_CONCERN_ERRORS = new Set([ + 'CannotSatisfyWriteConcern', + 'UnknownReplWriteConcern', + 'UnsatisfiableWriteConcern' +]); + +function hasNotTimedOut(startTime, max) { + return Date.now() - startTime < max; +} + +function isUnknownTransactionCommitResult(err) { + return ( + isMaxTimeMSExpiredError(err) || + (!NON_DETERMINISTIC_WRITE_CONCERN_ERRORS.has(err.codeName) && + err.code !== UNSATISFIABLE_WRITE_CONCERN_CODE && + err.code !== UNKNOWN_REPL_WRITE_CONCERN_CODE) + ); +} + +function isMaxTimeMSExpiredError(err) { + return ( + err.code === MAX_TIME_MS_EXPIRED_CODE || + (err.writeConcernError && err.writeConcernError.code === MAX_TIME_MS_EXPIRED_CODE) + ); +} + +function attemptTransactionCommit(session, startTime, fn, options) { + return session.commitTransaction().catch(err => { + if ( + err instanceof MongoError && + hasNotTimedOut(startTime, MAX_WITH_TRANSACTION_TIMEOUT) && + !isMaxTimeMSExpiredError(err) + ) { + if (err.hasErrorLabel('UnknownTransactionCommitResult')) { + return attemptTransactionCommit(session, startTime, fn, options); + } + + if (err.hasErrorLabel('TransientTransactionError')) { + return attemptTransaction(session, startTime, fn, options); + } + } + + throw err; + }); +} + +const USER_EXPLICIT_TXN_END_STATES = new Set([ + TxnState.NO_TRANSACTION, + TxnState.TRANSACTION_COMMITTED, + TxnState.TRANSACTION_ABORTED +]); + +function userExplicitlyEndedTransaction(session) { + return USER_EXPLICIT_TXN_END_STATES.has(session.transaction.state); +} + +function attemptTransaction(session, startTime, fn, options) { + session.startTransaction(options); + + let promise; + try { + promise = fn(session); + } catch (err) { + promise = Promise.reject(err); + } + + if (!isPromiseLike(promise)) { + session.abortTransaction(); + throw new TypeError('Function provided to `withTransaction` must return a Promise'); + } + + return promise + .then(() => { + if (userExplicitlyEndedTransaction(session)) { + return; + } + + return attemptTransactionCommit(session, startTime, fn, options); + }) + .catch(err => { + function maybeRetryOrThrow(err) { + if ( + err instanceof MongoError && + err.hasErrorLabel('TransientTransactionError') && + hasNotTimedOut(startTime, MAX_WITH_TRANSACTION_TIMEOUT) + ) { + return attemptTransaction(session, startTime, fn, options); + } + + if (isMaxTimeMSExpiredError(err)) { + if (err.errorLabels == null) { + err.errorLabels = []; + } + err.errorLabels.push('UnknownTransactionCommitResult'); + } + + throw err; + } + + if (session.transaction.isActive) { + return session.abortTransaction().then(() => maybeRetryOrThrow(err)); + } + + return maybeRetryOrThrow(err); + }); +} + +function endTransaction(session, commandName, callback) { + if (!assertAlive(session, callback)) { + // checking result in case callback was called + return; + } + + // handle any initial problematic cases + let txnState = session.transaction.state; + + if (txnState === TxnState.NO_TRANSACTION) { + callback(new MongoError('No transaction started')); + return; + } + + if (commandName === 'commitTransaction') { + if ( + txnState === TxnState.STARTING_TRANSACTION || + txnState === TxnState.TRANSACTION_COMMITTED_EMPTY + ) { + // the transaction was never started, we can safely exit here + session.transaction.transition(TxnState.TRANSACTION_COMMITTED_EMPTY); + callback(null, null); + return; + } + + if (txnState === TxnState.TRANSACTION_ABORTED) { + callback(new MongoError('Cannot call commitTransaction after calling abortTransaction')); + return; + } + } else { + if (txnState === TxnState.STARTING_TRANSACTION) { + // the transaction was never started, we can safely exit here + session.transaction.transition(TxnState.TRANSACTION_ABORTED); + callback(null, null); + return; + } + + if (txnState === TxnState.TRANSACTION_ABORTED) { + callback(new MongoError('Cannot call abortTransaction twice')); + return; + } + + if ( + txnState === TxnState.TRANSACTION_COMMITTED || + txnState === TxnState.TRANSACTION_COMMITTED_EMPTY + ) { + callback(new MongoError('Cannot call abortTransaction after calling commitTransaction')); + return; + } + } + + // construct and send the command + const command = { [commandName]: 1 }; + + // apply a writeConcern if specified + let writeConcern; + if (session.transaction.options.writeConcern) { + writeConcern = Object.assign({}, session.transaction.options.writeConcern); + } else if (session.clientOptions && session.clientOptions.w) { + writeConcern = { w: session.clientOptions.w }; + } + + if (txnState === TxnState.TRANSACTION_COMMITTED) { + writeConcern = Object.assign({ wtimeout: 10000 }, writeConcern, { w: 'majority' }); + } + + if (writeConcern) { + Object.assign(command, { writeConcern }); + } + + if (commandName === 'commitTransaction' && session.transaction.options.maxTimeMS) { + Object.assign(command, { maxTimeMS: session.transaction.options.maxTimeMS }); + } + + function commandHandler(e, r) { + if (commandName === 'commitTransaction') { + session.transaction.transition(TxnState.TRANSACTION_COMMITTED); + + if ( + e && + (e instanceof MongoNetworkError || + e instanceof MongoWriteConcernError || + isRetryableError(e) || + isMaxTimeMSExpiredError(e)) + ) { + if (e.errorLabels) { + const idx = e.errorLabels.indexOf('TransientTransactionError'); + if (idx !== -1) { + e.errorLabels.splice(idx, 1); + } + } else { + e.errorLabels = []; + } + + if (isUnknownTransactionCommitResult(e)) { + e.errorLabels.push('UnknownTransactionCommitResult'); + + // per txns spec, must unpin session in this case + session.transaction.unpinServer(); + } + } + } else { + session.transaction.transition(TxnState.TRANSACTION_ABORTED); + } + + callback(e, r); + } + + // The spec indicates that we should ignore all errors on `abortTransaction` + function transactionError(err) { + return commandName === 'commitTransaction' ? err : null; + } + + if ( + // Assumption here that commandName is "commitTransaction" or "abortTransaction" + session.transaction.recoveryToken && + supportsRecoveryToken(session) + ) { + command.recoveryToken = session.transaction.recoveryToken; + } + + // send the command + session.topology.command('admin.$cmd', command, { session }, (err, reply) => { + if (err && isRetryableError(err)) { + // SPEC-1185: apply majority write concern when retrying commitTransaction + if (command.commitTransaction) { + // per txns spec, must unpin session in this case + session.transaction.unpinServer(); + + command.writeConcern = Object.assign({ wtimeout: 10000 }, command.writeConcern, { + w: 'majority' + }); + } + + return session.topology.command('admin.$cmd', command, { session }, (_err, _reply) => + commandHandler(transactionError(_err), _reply) + ); + } + + commandHandler(transactionError(err), reply); + }); +} + +function supportsRecoveryToken(session) { + const topology = session.topology; + return !!topology.s.options.useRecoveryToken; +} + +/** + * Reflects the existence of a session on the server. Can be reused by the session pool. + * WARNING: not meant to be instantiated directly. For internal use only. + * @ignore + */ +class ServerSession { + constructor() { + this.id = { id: new Binary(uuidV4(), Binary.SUBTYPE_UUID) }; + this.lastUse = Date.now(); + this.txnNumber = 0; + this.isDirty = false; + } + + /** + * Determines if the server session has timed out. + * @ignore + * @param {Date} sessionTimeoutMinutes The server's "logicalSessionTimeoutMinutes" + * @return {boolean} true if the session has timed out. + */ + hasTimedOut(sessionTimeoutMinutes) { + // Take the difference of the lastUse timestamp and now, which will result in a value in + // milliseconds, and then convert milliseconds to minutes to compare to `sessionTimeoutMinutes` + const idleTimeMinutes = Math.round( + (((Date.now() - this.lastUse) % 86400000) % 3600000) / 60000 + ); + + return idleTimeMinutes > sessionTimeoutMinutes - 1; + } +} + +/** + * Maintains a pool of Server Sessions. + * For internal use only + * @ignore + */ +class ServerSessionPool { + constructor(topology) { + if (topology == null) { + throw new Error('ServerSessionPool requires a topology'); + } + + this.topology = topology; + this.sessions = []; + } + + /** + * Ends all sessions in the session pool. + * @ignore + */ + endAllPooledSessions() { + if (this.sessions.length) { + this.topology.endSessions(this.sessions.map(session => session.id)); + this.sessions = []; + } + } + + /** + * Acquire a Server Session from the pool. + * Iterates through each session in the pool, removing any stale sessions + * along the way. The first non-stale session found is removed from the + * pool and returned. If no non-stale session is found, a new ServerSession + * is created. + * @ignore + * @returns {ServerSession} + */ + acquire() { + const sessionTimeoutMinutes = this.topology.logicalSessionTimeoutMinutes; + while (this.sessions.length) { + const session = this.sessions.shift(); + if (!session.hasTimedOut(sessionTimeoutMinutes)) { + return session; + } + } + + return new ServerSession(); + } + + /** + * Release a session to the session pool + * Adds the session back to the session pool if the session has not timed out yet. + * This method also removes any stale sessions from the pool. + * @ignore + * @param {ServerSession} session The session to release to the pool + */ + release(session) { + const sessionTimeoutMinutes = this.topology.logicalSessionTimeoutMinutes; + while (this.sessions.length) { + const pooledSession = this.sessions[this.sessions.length - 1]; + if (pooledSession.hasTimedOut(sessionTimeoutMinutes)) { + this.sessions.pop(); + } else { + break; + } + } + + if (!session.hasTimedOut(sessionTimeoutMinutes)) { + if (session.isDirty) { + return; + } + + // otherwise, readd this session to the session pool + this.sessions.unshift(session); + } + } +} + +// TODO: this should be codified in command construction +// @see https://github.com/mongodb/specifications/blob/master/source/read-write-concern/read-write-concern.rst#read-concern +function commandSupportsReadConcern(command, options) { + if ( + command.aggregate || + command.count || + command.distinct || + command.find || + command.parallelCollectionScan || + command.geoNear || + command.geoSearch + ) { + return true; + } + + if (command.mapReduce && options.out && (options.out.inline === 1 || options.out === 'inline')) { + return true; + } + + return false; +} + +/** + * Optionally decorate a command with sessions specific keys + * + * @param {ClientSession} session the session tracking transaction state + * @param {Object} command the command to decorate + * @param {Object} topology the topology for tracking the cluster time + * @param {Object} [options] Optional settings passed to calling operation + * @return {MongoError|null} An error, if some error condition was met + */ +function applySession(session, command, options) { + const serverSession = session.serverSession; + if (serverSession == null) { + // TODO: merge this with `assertAlive`, did not want to throw a try/catch here + return new MongoError('Cannot use a session that has ended'); + } + + // mark the last use of this session, and apply the `lsid` + serverSession.lastUse = Date.now(); + command.lsid = serverSession.id; + + // first apply non-transaction-specific sessions data + const inTransaction = session.inTransaction() || isTransactionCommand(command); + const isRetryableWrite = options.willRetryWrite; + const shouldApplyReadConcern = commandSupportsReadConcern(command); + + if (serverSession.txnNumber && (isRetryableWrite || inTransaction)) { + command.txnNumber = BSON.Long.fromNumber(serverSession.txnNumber); + } + + // now attempt to apply transaction-specific sessions data + if (!inTransaction) { + if (session.transaction.state !== TxnState.NO_TRANSACTION) { + session.transaction.transition(TxnState.NO_TRANSACTION); + } + + // TODO: the following should only be applied to read operation per spec. + // for causal consistency + if (session.supports.causalConsistency && session.operationTime && shouldApplyReadConcern) { + command.readConcern = command.readConcern || {}; + Object.assign(command.readConcern, { afterClusterTime: session.operationTime }); + } + + return; + } + + if (options.readPreference && !options.readPreference.equals(ReadPreference.primary)) { + return new MongoError( + `Read preference in a transaction must be primary, not: ${options.readPreference.mode}` + ); + } + + // `autocommit` must always be false to differentiate from retryable writes + command.autocommit = false; + + if (session.transaction.state === TxnState.STARTING_TRANSACTION) { + session.transaction.transition(TxnState.TRANSACTION_IN_PROGRESS); + command.startTransaction = true; + + const readConcern = + session.transaction.options.readConcern || session.clientOptions.readConcern; + if (readConcern) { + command.readConcern = readConcern; + } + + if (session.supports.causalConsistency && session.operationTime) { + command.readConcern = command.readConcern || {}; + Object.assign(command.readConcern, { afterClusterTime: session.operationTime }); + } + } +} + +function updateSessionFromResponse(session, document) { + if (document.$clusterTime) { + resolveClusterTime(session, document.$clusterTime); + } + + if (document.operationTime && session && session.supports.causalConsistency) { + session.advanceOperationTime(document.operationTime); + } + + if (document.recoveryToken && session && session.inTransaction()) { + session.transaction._recoveryToken = document.recoveryToken; + } +} + +module.exports = { + ClientSession, + ServerSession, + ServerSessionPool, + TxnState, + applySession, + updateSessionFromResponse, + commandSupportsReadConcern +}; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/tools/smoke_plugin.js b/scripts/2.5/node_modules/mongodb/lib/core/tools/smoke_plugin.js new file mode 100644 index 00000000..22d02986 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/core/tools/smoke_plugin.js @@ -0,0 +1,61 @@ +'use strict'; + +var fs = require('fs'); + +/* Note: because this plugin uses process.on('uncaughtException'), only one + * of these can exist at any given time. This plugin and anything else that + * uses process.on('uncaughtException') will conflict. */ +exports.attachToRunner = function(runner, outputFile) { + var smokeOutput = { results: [] }; + var runningTests = {}; + + var integraPlugin = { + beforeTest: function(test, callback) { + test.startTime = Date.now(); + runningTests[test.name] = test; + callback(); + }, + afterTest: function(test, callback) { + smokeOutput.results.push({ + status: test.status, + start: test.startTime, + end: Date.now(), + test_file: test.name, + exit_code: 0, + url: '' + }); + delete runningTests[test.name]; + callback(); + }, + beforeExit: function(obj, callback) { + fs.writeFile(outputFile, JSON.stringify(smokeOutput), function() { + callback(); + }); + } + }; + + // In case of exception, make sure we write file + process.on('uncaughtException', function(err) { + // Mark all currently running tests as failed + for (var testName in runningTests) { + smokeOutput.results.push({ + status: 'fail', + start: runningTests[testName].startTime, + end: Date.now(), + test_file: testName, + exit_code: 0, + url: '' + }); + } + + // write file + fs.writeFileSync(outputFile, JSON.stringify(smokeOutput)); + + // Standard NodeJS uncaught exception handler + console.error(err.stack); + process.exit(1); + }); + + runner.plugin(integraPlugin); + return integraPlugin; +}; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/topologies/mongos.js b/scripts/2.5/node_modules/mongodb/lib/core/topologies/mongos.js new file mode 100644 index 00000000..681b01fd --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/core/topologies/mongos.js @@ -0,0 +1,1392 @@ +'use strict'; + +const inherits = require('util').inherits; +const f = require('util').format; +const EventEmitter = require('events').EventEmitter; +const CoreCursor = require('../cursor').CoreCursor; +const Logger = require('../connection/logger'); +const retrieveBSON = require('../connection/utils').retrieveBSON; +const MongoError = require('../error').MongoError; +const Server = require('./server'); +const clone = require('./shared').clone; +const diff = require('./shared').diff; +const cloneOptions = require('./shared').cloneOptions; +const createClientInfo = require('./shared').createClientInfo; +const SessionMixins = require('./shared').SessionMixins; +const isRetryableWritesSupported = require('./shared').isRetryableWritesSupported; +const relayEvents = require('../utils').relayEvents; +const isRetryableError = require('../error').isRetryableError; +const BSON = retrieveBSON(); +const getMMAPError = require('./shared').getMMAPError; + +/** + * @fileOverview The **Mongos** class is a class that represents a Mongos Proxy topology and is + * used to construct connections. + */ + +// +// States +var DISCONNECTED = 'disconnected'; +var CONNECTING = 'connecting'; +var CONNECTED = 'connected'; +var UNREFERENCED = 'unreferenced'; +var DESTROYING = 'destroying'; +var DESTROYED = 'destroyed'; + +function stateTransition(self, newState) { + var legalTransitions = { + disconnected: [CONNECTING, DESTROYING, DESTROYED, DISCONNECTED], + connecting: [CONNECTING, DESTROYING, DESTROYED, CONNECTED, DISCONNECTED], + connected: [CONNECTED, DISCONNECTED, DESTROYING, DESTROYED, UNREFERENCED], + unreferenced: [UNREFERENCED, DESTROYING, DESTROYED], + destroyed: [DESTROYED] + }; + + // Get current state + var legalStates = legalTransitions[self.state]; + if (legalStates && legalStates.indexOf(newState) !== -1) { + self.state = newState; + } else { + self.s.logger.error( + f( + 'Mongos with id [%s] failed attempted illegal state transition from [%s] to [%s] only following state allowed [%s]', + self.id, + self.state, + newState, + legalStates + ) + ); + } +} + +// +// ReplSet instance id +var id = 1; +var handlers = ['connect', 'close', 'error', 'timeout', 'parseError']; + +/** + * Creates a new Mongos instance + * @class + * @param {array} seedlist A list of seeds for the replicaset + * @param {number} [options.haInterval=5000] The High availability period for replicaset inquiry + * @param {Cursor} [options.cursorFactory=Cursor] The cursor factory class used for all query cursors + * @param {number} [options.size=5] Server connection pool size + * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled + * @param {number} [options.keepAliveInitialDelay=0] Initial delay before TCP keep alive enabled + * @param {number} [options.localThresholdMS=15] Cutoff latency point in MS for MongoS proxy selection + * @param {boolean} [options.noDelay=true] TCP Connection no delay + * @param {number} [options.connectionTimeout=1000] TCP Connection timeout setting + * @param {number} [options.socketTimeout=0] TCP Socket timeout setting + * @param {boolean} [options.ssl=false] Use SSL for connection + * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. + * @param {Buffer} [options.ca] SSL Certificate store binary buffer + * @param {Buffer} [options.crl] SSL Certificate revocation store binary buffer + * @param {Buffer} [options.cert] SSL Certificate binary buffer + * @param {Buffer} [options.key] SSL Key file binary buffer + * @param {string} [options.passphrase] SSL Certificate pass phrase + * @param {string} [options.servername=null] String containing the server name requested via TLS SNI. + * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates + * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits + * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. + * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. + * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. + * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology + * @return {Mongos} A cursor instance + * @fires Mongos#connect + * @fires Mongos#reconnect + * @fires Mongos#joined + * @fires Mongos#left + * @fires Mongos#failed + * @fires Mongos#fullsetup + * @fires Mongos#all + * @fires Mongos#serverHeartbeatStarted + * @fires Mongos#serverHeartbeatSucceeded + * @fires Mongos#serverHeartbeatFailed + * @fires Mongos#topologyOpening + * @fires Mongos#topologyClosed + * @fires Mongos#topologyDescriptionChanged + * @property {string} type the topology type. + * @property {string} parserType the parser type used (c++ or js). + */ +var Mongos = function(seedlist, options) { + options = options || {}; + + // Get replSet Id + this.id = id++; + + // Internal state + this.s = { + options: Object.assign({}, options), + // BSON instance + bson: + options.bson || + new BSON([ + BSON.Binary, + BSON.Code, + BSON.DBRef, + BSON.Decimal128, + BSON.Double, + BSON.Int32, + BSON.Long, + BSON.Map, + BSON.MaxKey, + BSON.MinKey, + BSON.ObjectId, + BSON.BSONRegExp, + BSON.Symbol, + BSON.Timestamp + ]), + // Factory overrides + Cursor: options.cursorFactory || CoreCursor, + // Logger instance + logger: Logger('Mongos', options), + // Seedlist + seedlist: seedlist, + // Ha interval + haInterval: options.haInterval ? options.haInterval : 10000, + // Disconnect handler + disconnectHandler: options.disconnectHandler, + // Server selection index + index: 0, + // Connect function options passed in + connectOptions: {}, + // Are we running in debug mode + debug: typeof options.debug === 'boolean' ? options.debug : false, + // localThresholdMS + localThresholdMS: options.localThresholdMS || 15, + // Client info + clientInfo: createClientInfo(options) + }; + + // Set the client info + this.s.options.clientInfo = createClientInfo(options); + + // Log info warning if the socketTimeout < haInterval as it will cause + // a lot of recycled connections to happen. + if ( + this.s.logger.isWarn() && + this.s.options.socketTimeout !== 0 && + this.s.options.socketTimeout < this.s.haInterval + ) { + this.s.logger.warn( + f( + 'warning socketTimeout %s is less than haInterval %s. This might cause unnecessary server reconnections due to socket timeouts', + this.s.options.socketTimeout, + this.s.haInterval + ) + ); + } + + // Disconnected state + this.state = DISCONNECTED; + + // Current proxies we are connecting to + this.connectingProxies = []; + // Currently connected proxies + this.connectedProxies = []; + // Disconnected proxies + this.disconnectedProxies = []; + // Index of proxy to run operations against + this.index = 0; + // High availability timeout id + this.haTimeoutId = null; + // Last ismaster + this.ismaster = null; + + // Description of the Replicaset + this.topologyDescription = { + topologyType: 'Unknown', + servers: [] + }; + + // Highest clusterTime seen in responses from the current deployment + this.clusterTime = null; + + // Add event listener + EventEmitter.call(this); +}; + +inherits(Mongos, EventEmitter); +Object.assign(Mongos.prototype, SessionMixins); + +Object.defineProperty(Mongos.prototype, 'type', { + enumerable: true, + get: function() { + return 'mongos'; + } +}); + +Object.defineProperty(Mongos.prototype, 'parserType', { + enumerable: true, + get: function() { + return BSON.native ? 'c++' : 'js'; + } +}); + +Object.defineProperty(Mongos.prototype, 'logicalSessionTimeoutMinutes', { + enumerable: true, + get: function() { + if (!this.ismaster) return null; + return this.ismaster.logicalSessionTimeoutMinutes || null; + } +}); + +/** + * Emit event if it exists + * @method + */ +function emitSDAMEvent(self, event, description) { + if (self.listeners(event).length > 0) { + self.emit(event, description); + } +} + +const SERVER_EVENTS = ['serverDescriptionChanged', 'error', 'close', 'timeout', 'parseError']; +function destroyServer(server, options, callback) { + options = options || {}; + SERVER_EVENTS.forEach(event => server.removeAllListeners(event)); + server.destroy(options, callback); +} + +/** + * Initiate server connect + */ +Mongos.prototype.connect = function(options) { + var self = this; + // Add any connect level options to the internal state + this.s.connectOptions = options || {}; + + // Set connecting state + stateTransition(this, CONNECTING); + + // Create server instances + var servers = this.s.seedlist.map(function(x) { + const server = new Server( + Object.assign({}, self.s.options, x, options, { + reconnect: false, + monitoring: false, + parent: self, + clientInfo: clone(self.s.clientInfo) + }) + ); + + relayEvents(server, self, ['serverDescriptionChanged']); + return server; + }); + + // Emit the topology opening event + emitSDAMEvent(this, 'topologyOpening', { topologyId: this.id }); + + // Start all server connections + connectProxies(self, servers); +}; + +/** + * Authenticate the topology. + * @method + * @param {MongoCredentials} credentials The credentials for authentication we are using + * @param {authResultCallback} callback A callback function + */ +Mongos.prototype.auth = function(credentials, callback) { + if (typeof callback === 'function') callback(null, null); +}; + +function handleEvent(self) { + return function() { + if (self.state === DESTROYED || self.state === DESTROYING) { + return; + } + + // Move to list of disconnectedProxies + moveServerFrom(self.connectedProxies, self.disconnectedProxies, this); + // Emit the initial topology + emitTopologyDescriptionChanged(self); + // Emit the left signal + self.emit('left', 'mongos', this); + // Emit the sdam event + self.emit('serverClosed', { + topologyId: self.id, + address: this.name + }); + }; +} + +function handleInitialConnectEvent(self, event) { + return function() { + var _this = this; + + // Destroy the instance + if (self.state === DESTROYED) { + // Emit the initial topology + emitTopologyDescriptionChanged(self); + // Move from connectingProxies + moveServerFrom(self.connectingProxies, self.disconnectedProxies, this); + return this.destroy(); + } + + // Check the type of server + if (event === 'connect') { + // Get last known ismaster + self.ismaster = _this.lastIsMaster(); + + // Is this not a proxy, remove t + if (self.ismaster.msg === 'isdbgrid') { + // Add to the connectd list + for (let i = 0; i < self.connectedProxies.length; i++) { + if (self.connectedProxies[i].name === _this.name) { + // Move from connectingProxies + moveServerFrom(self.connectingProxies, self.disconnectedProxies, _this); + // Emit the initial topology + emitTopologyDescriptionChanged(self); + _this.destroy(); + return self.emit('failed', _this); + } + } + + // Remove the handlers + for (let i = 0; i < handlers.length; i++) { + _this.removeAllListeners(handlers[i]); + } + + // Add stable state handlers + _this.on('error', handleEvent(self, 'error')); + _this.on('close', handleEvent(self, 'close')); + _this.on('timeout', handleEvent(self, 'timeout')); + _this.on('parseError', handleEvent(self, 'parseError')); + + // Move from connecting proxies connected + moveServerFrom(self.connectingProxies, self.connectedProxies, _this); + // Emit the joined event + self.emit('joined', 'mongos', _this); + } else { + // Print warning if we did not find a mongos proxy + if (self.s.logger.isWarn()) { + var message = 'expected mongos proxy, but found replicaset member mongod for server %s'; + // We have a standalone server + if (!self.ismaster.hosts) { + message = 'expected mongos proxy, but found standalone mongod for server %s'; + } + + self.s.logger.warn(f(message, _this.name)); + } + + // This is not a mongos proxy, destroy and remove it completely + _this.destroy(true); + removeProxyFrom(self.connectingProxies, _this); + // Emit the left event + self.emit('left', 'server', _this); + // Emit failed event + self.emit('failed', _this); + } + } else { + moveServerFrom(self.connectingProxies, self.disconnectedProxies, this); + // Emit the left event + self.emit('left', 'mongos', this); + // Emit failed event + self.emit('failed', this); + } + + // Emit the initial topology + emitTopologyDescriptionChanged(self); + + // Trigger topologyMonitor + if (self.connectingProxies.length === 0) { + // Emit connected if we are connected + if (self.connectedProxies.length > 0 && self.state === CONNECTING) { + // Set the state to connected + stateTransition(self, CONNECTED); + // Emit the connect event + self.emit('connect', self); + self.emit('fullsetup', self); + self.emit('all', self); + } else if (self.disconnectedProxies.length === 0) { + // Print warning if we did not find a mongos proxy + if (self.s.logger.isWarn()) { + self.s.logger.warn( + f('no mongos proxies found in seed list, did you mean to connect to a replicaset') + ); + } + + // Emit the error that no proxies were found + return self.emit('error', new MongoError('no mongos proxies found in seed list')); + } + + // Topology monitor + topologyMonitor(self, { firstConnect: true }); + } + }; +} + +function connectProxies(self, servers) { + // Update connectingProxies + self.connectingProxies = self.connectingProxies.concat(servers); + + // Index used to interleaf the server connects, avoiding + // runtime issues on io constrained vm's + var timeoutInterval = 0; + + function connect(server, timeoutInterval) { + setTimeout(function() { + // Emit opening server event + self.emit('serverOpening', { + topologyId: self.id, + address: server.name + }); + + // Emit the initial topology + emitTopologyDescriptionChanged(self); + + // Add event handlers + server.once('close', handleInitialConnectEvent(self, 'close')); + server.once('timeout', handleInitialConnectEvent(self, 'timeout')); + server.once('parseError', handleInitialConnectEvent(self, 'parseError')); + server.once('error', handleInitialConnectEvent(self, 'error')); + server.once('connect', handleInitialConnectEvent(self, 'connect')); + + // Command Monitoring events + relayEvents(server, self, ['commandStarted', 'commandSucceeded', 'commandFailed']); + + // Start connection + server.connect(self.s.connectOptions); + }, timeoutInterval); + } + + // Start all the servers + servers.forEach(server => connect(server, timeoutInterval++)); +} + +function pickProxy(self, session) { + // TODO: Destructure :) + const transaction = session && session.transaction; + + if (transaction && transaction.server) { + if (transaction.server.isConnected()) { + return transaction.server; + } else { + transaction.unpinServer(); + } + } + + // Get the currently connected Proxies + var connectedProxies = self.connectedProxies.slice(0); + + // Set lower bound + var lowerBoundLatency = Number.MAX_VALUE; + + // Determine the lower bound for the Proxies + for (var i = 0; i < connectedProxies.length; i++) { + if (connectedProxies[i].lastIsMasterMS < lowerBoundLatency) { + lowerBoundLatency = connectedProxies[i].lastIsMasterMS; + } + } + + // Filter out the possible servers + connectedProxies = connectedProxies.filter(function(server) { + if ( + server.lastIsMasterMS <= lowerBoundLatency + self.s.localThresholdMS && + server.isConnected() + ) { + return true; + } + }); + + let proxy; + + // We have no connectedProxies pick first of the connected ones + if (connectedProxies.length === 0) { + proxy = self.connectedProxies[0]; + } else { + // Get proxy + proxy = connectedProxies[self.index % connectedProxies.length]; + // Update the index + self.index = (self.index + 1) % connectedProxies.length; + } + + if (transaction && transaction.isActive && proxy && proxy.isConnected()) { + transaction.pinServer(proxy); + } + + // Return the proxy + return proxy; +} + +function moveServerFrom(from, to, proxy) { + for (var i = 0; i < from.length; i++) { + if (from[i].name === proxy.name) { + from.splice(i, 1); + } + } + + for (i = 0; i < to.length; i++) { + if (to[i].name === proxy.name) { + to.splice(i, 1); + } + } + + to.push(proxy); +} + +function removeProxyFrom(from, proxy) { + for (var i = 0; i < from.length; i++) { + if (from[i].name === proxy.name) { + from.splice(i, 1); + } + } +} + +function reconnectProxies(self, proxies, callback) { + // Count lefts + var count = proxies.length; + + // Handle events + var _handleEvent = function(self, event) { + return function() { + var _self = this; + count = count - 1; + + // Destroyed + if (self.state === DESTROYED || self.state === DESTROYING || self.state === UNREFERENCED) { + moveServerFrom(self.connectingProxies, self.disconnectedProxies, _self); + return this.destroy(); + } + + if (event === 'connect') { + // Destroyed + if (self.state === DESTROYED || self.state === DESTROYING || self.state === UNREFERENCED) { + moveServerFrom(self.connectingProxies, self.disconnectedProxies, _self); + return _self.destroy(); + } + + // Remove the handlers + for (var i = 0; i < handlers.length; i++) { + _self.removeAllListeners(handlers[i]); + } + + // Add stable state handlers + _self.on('error', handleEvent(self, 'error')); + _self.on('close', handleEvent(self, 'close')); + _self.on('timeout', handleEvent(self, 'timeout')); + _self.on('parseError', handleEvent(self, 'parseError')); + + // Move to the connected servers + moveServerFrom(self.connectingProxies, self.connectedProxies, _self); + // Emit topology Change + emitTopologyDescriptionChanged(self); + // Emit joined event + self.emit('joined', 'mongos', _self); + } else { + // Move from connectingProxies + moveServerFrom(self.connectingProxies, self.disconnectedProxies, _self); + this.destroy(); + } + + // Are we done finish up callback + if (count === 0) { + callback(); + } + }; + }; + + // No new servers + if (count === 0) { + return callback(); + } + + // Execute method + function execute(_server, i) { + setTimeout(function() { + // Destroyed + if (self.state === DESTROYED || self.state === DESTROYING || self.state === UNREFERENCED) { + return; + } + + // Create a new server instance + var server = new Server( + Object.assign({}, self.s.options, { + host: _server.name.split(':')[0], + port: parseInt(_server.name.split(':')[1], 10), + reconnect: false, + monitoring: false, + parent: self, + clientInfo: clone(self.s.clientInfo) + }) + ); + + destroyServer(_server, { force: true }); + removeProxyFrom(self.disconnectedProxies, _server); + + // Relay the server description change + relayEvents(server, self, ['serverDescriptionChanged']); + + // Emit opening server event + self.emit('serverOpening', { + topologyId: server.s.topologyId !== -1 ? server.s.topologyId : self.id, + address: server.name + }); + + // Add temp handlers + server.once('connect', _handleEvent(self, 'connect')); + server.once('close', _handleEvent(self, 'close')); + server.once('timeout', _handleEvent(self, 'timeout')); + server.once('error', _handleEvent(self, 'error')); + server.once('parseError', _handleEvent(self, 'parseError')); + + // Command Monitoring events + relayEvents(server, self, ['commandStarted', 'commandSucceeded', 'commandFailed']); + + // Connect to proxy + self.connectingProxies.push(server); + server.connect(self.s.connectOptions); + }, i); + } + + // Create new instances + for (var i = 0; i < proxies.length; i++) { + execute(proxies[i], i); + } +} + +function topologyMonitor(self, options) { + options = options || {}; + + // no need to set up the monitor if we're already closed + if (self.state === DESTROYED || self.state === DESTROYING || self.state === UNREFERENCED) { + return; + } + + // Set momitoring timeout + self.haTimeoutId = setTimeout(function() { + if (self.state === DESTROYED || self.state === DESTROYING || self.state === UNREFERENCED) { + return; + } + + // If we have a primary and a disconnect handler, execute + // buffered operations + if (self.isConnected() && self.s.disconnectHandler) { + self.s.disconnectHandler.execute(); + } + + // Get the connectingServers + var proxies = self.connectedProxies.slice(0); + // Get the count + var count = proxies.length; + + // If the count is zero schedule a new fast + function pingServer(_self, _server, cb) { + // Measure running time + var start = new Date().getTime(); + + // Emit the server heartbeat start + emitSDAMEvent(self, 'serverHeartbeatStarted', { connectionId: _server.name }); + + // Execute ismaster + _server.command( + 'admin.$cmd', + { + ismaster: true + }, + { + monitoring: true, + socketTimeout: self.s.options.connectionTimeout || 2000 + }, + function(err, r) { + if ( + self.state === DESTROYED || + self.state === DESTROYING || + self.state === UNREFERENCED + ) { + // Move from connectingProxies + moveServerFrom(self.connectedProxies, self.disconnectedProxies, _server); + _server.destroy(); + return cb(err, r); + } + + // Calculate latency + var latencyMS = new Date().getTime() - start; + + // We had an error, remove it from the state + if (err) { + // Emit the server heartbeat failure + emitSDAMEvent(self, 'serverHeartbeatFailed', { + durationMS: latencyMS, + failure: err, + connectionId: _server.name + }); + // Move from connected proxies to disconnected proxies + moveServerFrom(self.connectedProxies, self.disconnectedProxies, _server); + } else { + // Update the server ismaster + _server.ismaster = r.result; + _server.lastIsMasterMS = latencyMS; + + // Server heart beat event + emitSDAMEvent(self, 'serverHeartbeatSucceeded', { + durationMS: latencyMS, + reply: r.result, + connectionId: _server.name + }); + } + + cb(err, r); + } + ); + } + + // No proxies initiate monitor again + if (proxies.length === 0) { + // Emit close event if any listeners registered + if (self.listeners('close').length > 0 && self.state === CONNECTING) { + self.emit('error', new MongoError('no mongos proxy available')); + } else { + self.emit('close', self); + } + + // Attempt to connect to any unknown servers + return reconnectProxies(self, self.disconnectedProxies, function() { + if (self.state === DESTROYED || self.state === DESTROYING || self.state === UNREFERENCED) { + return; + } + + // Are we connected ? emit connect event + if (self.state === CONNECTING && options.firstConnect) { + self.emit('connect', self); + self.emit('fullsetup', self); + self.emit('all', self); + } else if (self.isConnected()) { + self.emit('reconnect', self); + } else if (!self.isConnected() && self.listeners('close').length > 0) { + self.emit('close', self); + } + + // Perform topology monitor + topologyMonitor(self); + }); + } + + // Ping all servers + for (var i = 0; i < proxies.length; i++) { + pingServer(self, proxies[i], function() { + count = count - 1; + + if (count === 0) { + if ( + self.state === DESTROYED || + self.state === DESTROYING || + self.state === UNREFERENCED + ) { + return; + } + + // Attempt to connect to any unknown servers + reconnectProxies(self, self.disconnectedProxies, function() { + if ( + self.state === DESTROYED || + self.state === DESTROYING || + self.state === UNREFERENCED + ) { + return; + } + + // Perform topology monitor + topologyMonitor(self); + }); + } + }); + } + }, self.s.haInterval); +} + +/** + * Returns the last known ismaster document for this server + * @method + * @return {object} + */ +Mongos.prototype.lastIsMaster = function() { + return this.ismaster; +}; + +/** + * Unref all connections belong to this server + * @method + */ +Mongos.prototype.unref = function() { + // Transition state + stateTransition(this, UNREFERENCED); + // Get all proxies + var proxies = this.connectedProxies.concat(this.connectingProxies); + proxies.forEach(function(x) { + x.unref(); + }); + + clearTimeout(this.haTimeoutId); +}; + +/** + * Destroy the server connection + * @param {boolean} [options.force=false] Force destroy the pool + * @method + */ +Mongos.prototype.destroy = function(options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + + options = options || {}; + + stateTransition(this, DESTROYING); + if (this.haTimeoutId) { + clearTimeout(this.haTimeoutId); + } + + const proxies = this.connectedProxies.concat(this.connectingProxies); + let serverCount = proxies.length; + const serverDestroyed = () => { + serverCount--; + if (serverCount > 0) { + return; + } + + emitTopologyDescriptionChanged(this); + emitSDAMEvent(this, 'topologyClosed', { topologyId: this.id }); + stateTransition(this, DESTROYED); + if (typeof callback === 'function') { + callback(null, null); + } + }; + + if (serverCount === 0) { + serverDestroyed(); + return; + } + + // Destroy all connecting servers + proxies.forEach(server => { + // Emit the sdam event + this.emit('serverClosed', { + topologyId: this.id, + address: server.name + }); + + destroyServer(server, options, serverDestroyed); + moveServerFrom(this.connectedProxies, this.disconnectedProxies, server); + }); +}; + +/** + * Figure out if the server is connected + * @method + * @return {boolean} + */ +Mongos.prototype.isConnected = function() { + return this.connectedProxies.length > 0; +}; + +/** + * Figure out if the server instance was destroyed by calling destroy + * @method + * @return {boolean} + */ +Mongos.prototype.isDestroyed = function() { + return this.state === DESTROYED; +}; + +// +// Operations +// + +function executeWriteOperation(args, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + // TODO: once we drop Node 4, use destructuring either here or in arguments. + const self = args.self; + const op = args.op; + const ns = args.ns; + const ops = args.ops; + + // Pick a server + let server = pickProxy(self, options.session); + // No server found error out + if (!server) return callback(new MongoError('no mongos proxy available')); + + const willRetryWrite = + !args.retrying && + !!options.retryWrites && + options.session && + isRetryableWritesSupported(self) && + !options.session.inTransaction(); + + const handler = (err, result) => { + if (!err) return callback(null, result); + if (!isRetryableError(err) || !willRetryWrite) { + err = getMMAPError(err); + return callback(err); + } + + // Pick another server + server = pickProxy(self, options.session); + + // No server found error out with original error + if (!server) { + return callback(err); + } + + const newArgs = Object.assign({}, args, { retrying: true }); + return executeWriteOperation(newArgs, options, callback); + }; + + if (callback.operationId) { + handler.operationId = callback.operationId; + } + + // increment and assign txnNumber + if (willRetryWrite) { + options.session.incrementTransactionNumber(); + options.willRetryWrite = willRetryWrite; + } + + // rerun the operation + server[op](ns, ops, options, handler); +} + +/** + * Insert one or more documents + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of documents to insert + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {boolean} [options.retryWrites] Enable retryable writes for this operation + * @param {opResultCallback} callback A callback function + */ +Mongos.prototype.insert = function(ns, ops, options, callback) { + if (typeof options === 'function') { + (callback = options), (options = {}), (options = options || {}); + } + + if (this.state === DESTROYED) { + return callback(new MongoError(f('topology was destroyed'))); + } + + // Not connected but we have a disconnecthandler + if (!this.isConnected() && this.s.disconnectHandler != null) { + return this.s.disconnectHandler.add('insert', ns, ops, options, callback); + } + + // No mongos proxy available + if (!this.isConnected()) { + return callback(new MongoError('no mongos proxy available')); + } + + // Execute write operation + executeWriteOperation({ self: this, op: 'insert', ns, ops }, options, callback); +}; + +/** + * Perform one or more update operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of updates + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {boolean} [options.retryWrites] Enable retryable writes for this operation + * @param {opResultCallback} callback A callback function + */ +Mongos.prototype.update = function(ns, ops, options, callback) { + if (typeof options === 'function') { + (callback = options), (options = {}), (options = options || {}); + } + + if (this.state === DESTROYED) { + return callback(new MongoError(f('topology was destroyed'))); + } + + // Not connected but we have a disconnecthandler + if (!this.isConnected() && this.s.disconnectHandler != null) { + return this.s.disconnectHandler.add('update', ns, ops, options, callback); + } + + // No mongos proxy available + if (!this.isConnected()) { + return callback(new MongoError('no mongos proxy available')); + } + + // Execute write operation + executeWriteOperation({ self: this, op: 'update', ns, ops }, options, callback); +}; + +/** + * Perform one or more remove operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of removes + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {boolean} [options.retryWrites] Enable retryable writes for this operation + * @param {opResultCallback} callback A callback function + */ +Mongos.prototype.remove = function(ns, ops, options, callback) { + if (typeof options === 'function') { + (callback = options), (options = {}), (options = options || {}); + } + + if (this.state === DESTROYED) { + return callback(new MongoError(f('topology was destroyed'))); + } + + // Not connected but we have a disconnecthandler + if (!this.isConnected() && this.s.disconnectHandler != null) { + return this.s.disconnectHandler.add('remove', ns, ops, options, callback); + } + + // No mongos proxy available + if (!this.isConnected()) { + return callback(new MongoError('no mongos proxy available')); + } + + // Execute write operation + executeWriteOperation({ self: this, op: 'remove', ns, ops }, options, callback); +}; + +const RETRYABLE_WRITE_OPERATIONS = ['findAndModify', 'insert', 'update', 'delete']; + +function isWriteCommand(command) { + return RETRYABLE_WRITE_OPERATIONS.some(op => command[op]); +} + +/** + * Execute a command + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object} cmd The command hash + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Connection} [options.connection] Specify connection object to execute command against + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {opResultCallback} callback A callback function + */ +Mongos.prototype.command = function(ns, cmd, options, callback) { + if (typeof options === 'function') { + (callback = options), (options = {}), (options = options || {}); + } + + if (this.state === DESTROYED) { + return callback(new MongoError(f('topology was destroyed'))); + } + + var self = this; + + // Pick a proxy + var server = pickProxy(self, options.session); + + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if ((server == null || !server.isConnected()) && this.s.disconnectHandler != null) { + return this.s.disconnectHandler.add('command', ns, cmd, options, callback); + } + + // No server returned we had an error + if (server == null) { + return callback(new MongoError('no mongos proxy available')); + } + + // Cloned options + var clonedOptions = cloneOptions(options); + clonedOptions.topology = self; + + const willRetryWrite = + !options.retrying && + options.retryWrites && + options.session && + isRetryableWritesSupported(self) && + !options.session.inTransaction() && + isWriteCommand(cmd); + + const cb = (err, result) => { + if (!err) return callback(null, result); + if (!isRetryableError(err)) { + return callback(err); + } + + if (willRetryWrite) { + const newOptions = Object.assign({}, clonedOptions, { retrying: true }); + return this.command(ns, cmd, newOptions, callback); + } + + return callback(err); + }; + + // increment and assign txnNumber + if (willRetryWrite) { + options.session.incrementTransactionNumber(); + options.willRetryWrite = willRetryWrite; + } + + // Execute the command + server.command(ns, cmd, clonedOptions, cb); +}; + +/** + * Get a new cursor + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object|Long} cmd Can be either a command returning a cursor or a cursorId + * @param {object} [options] Options for the cursor + * @param {object} [options.batchSize=0] Batchsize for the operation + * @param {array} [options.documents=[]] Initial documents list for cursor + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {object} [options.topology] The internal topology of the created cursor + * @returns {Cursor} + */ +Mongos.prototype.cursor = function(ns, cmd, options) { + options = options || {}; + const topology = options.topology || this; + + // Set up final cursor type + var FinalCursor = options.cursorFactory || this.s.Cursor; + + // Return the cursor + return new FinalCursor(topology, ns, cmd, options); +}; + +/** + * Selects a server + * + * @method + * @param {function} selector Unused + * @param {ReadPreference} [options.readPreference] Unused + * @param {ClientSession} [options.session] Specify a session if it is being used + * @param {function} callback + */ +Mongos.prototype.selectServer = function(selector, options, callback) { + if (typeof selector === 'function' && typeof callback === 'undefined') + (callback = selector), (selector = undefined), (options = {}); + if (typeof options === 'function') + (callback = options), (options = selector), (selector = undefined); + options = options || {}; + + const server = pickProxy(this, options.session); + if (server == null) { + callback(new MongoError('server selection failed')); + return; + } + + if (this.s.debug) this.emit('pickedServer', null, server); + callback(null, server); +}; + +/** + * All raw connections + * @method + * @return {Connection[]} + */ +Mongos.prototype.connections = function() { + var connections = []; + + for (var i = 0; i < this.connectedProxies.length; i++) { + connections = connections.concat(this.connectedProxies[i].connections()); + } + + return connections; +}; + +function emitTopologyDescriptionChanged(self) { + if (self.listeners('topologyDescriptionChanged').length > 0) { + var topology = 'Unknown'; + if (self.connectedProxies.length > 0) { + topology = 'Sharded'; + } + + // Generate description + var description = { + topologyType: topology, + servers: [] + }; + + // All proxies + var proxies = self.disconnectedProxies.concat(self.connectingProxies); + + // Add all the disconnected proxies + description.servers = description.servers.concat( + proxies.map(function(x) { + var description = x.getDescription(); + description.type = 'Unknown'; + return description; + }) + ); + + // Add all the connected proxies + description.servers = description.servers.concat( + self.connectedProxies.map(function(x) { + var description = x.getDescription(); + description.type = 'Mongos'; + return description; + }) + ); + + // Get the diff + var diffResult = diff(self.topologyDescription, description); + + // Create the result + var result = { + topologyId: self.id, + previousDescription: self.topologyDescription, + newDescription: description, + diff: diffResult + }; + + // Emit the topologyDescription change + if (diffResult.servers.length > 0) { + self.emit('topologyDescriptionChanged', result); + } + + // Set the new description + self.topologyDescription = description; + } +} + +/** + * A mongos connect event, used to verify that the connection is up and running + * + * @event Mongos#connect + * @type {Mongos} + */ + +/** + * A mongos reconnect event, used to verify that the mongos topology has reconnected + * + * @event Mongos#reconnect + * @type {Mongos} + */ + +/** + * A mongos fullsetup event, used to signal that all topology members have been contacted. + * + * @event Mongos#fullsetup + * @type {Mongos} + */ + +/** + * A mongos all event, used to signal that all topology members have been contacted. + * + * @event Mongos#all + * @type {Mongos} + */ + +/** + * A server member left the mongos list + * + * @event Mongos#left + * @type {Mongos} + * @param {string} type The type of member that left (mongos) + * @param {Server} server The server object that left + */ + +/** + * A server member joined the mongos list + * + * @event Mongos#joined + * @type {Mongos} + * @param {string} type The type of member that left (mongos) + * @param {Server} server The server object that joined + */ + +/** + * A server opening SDAM monitoring event + * + * @event Mongos#serverOpening + * @type {object} + */ + +/** + * A server closed SDAM monitoring event + * + * @event Mongos#serverClosed + * @type {object} + */ + +/** + * A server description SDAM change monitoring event + * + * @event Mongos#serverDescriptionChanged + * @type {object} + */ + +/** + * A topology open SDAM event + * + * @event Mongos#topologyOpening + * @type {object} + */ + +/** + * A topology closed SDAM event + * + * @event Mongos#topologyClosed + * @type {object} + */ + +/** + * A topology structure SDAM change event + * + * @event Mongos#topologyDescriptionChanged + * @type {object} + */ + +/** + * A topology serverHeartbeatStarted SDAM event + * + * @event Mongos#serverHeartbeatStarted + * @type {object} + */ + +/** + * A topology serverHeartbeatFailed SDAM event + * + * @event Mongos#serverHeartbeatFailed + * @type {object} + */ + +/** + * A topology serverHeartbeatSucceeded SDAM change event + * + * @event Mongos#serverHeartbeatSucceeded + * @type {object} + */ + +/** + * An event emitted indicating a command was started, if command monitoring is enabled + * + * @event Mongos#commandStarted + * @type {object} + */ + +/** + * An event emitted indicating a command succeeded, if command monitoring is enabled + * + * @event Mongos#commandSucceeded + * @type {object} + */ + +/** + * An event emitted indicating a command failed, if command monitoring is enabled + * + * @event Mongos#commandFailed + * @type {object} + */ + +module.exports = Mongos; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/topologies/read_preference.js b/scripts/2.5/node_modules/mongodb/lib/core/topologies/read_preference.js new file mode 100644 index 00000000..a813ec4f --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/core/topologies/read_preference.js @@ -0,0 +1,202 @@ +'use strict'; + +/** + * The **ReadPreference** class is a class that represents a MongoDB ReadPreference and is + * used to construct connections. + * @class + * @param {string} mode A string describing the read preference mode (primary|primaryPreferred|secondary|secondaryPreferred|nearest) + * @param {array} tags The tags object + * @param {object} [options] Additional read preference options + * @param {number} [options.maxStalenessSeconds] Max secondary read staleness in seconds, Minimum value is 90 seconds. + * @see https://docs.mongodb.com/manual/core/read-preference/ + * @return {ReadPreference} + */ +const ReadPreference = function(mode, tags, options) { + if (!ReadPreference.isValid(mode)) { + throw new TypeError(`Invalid read preference mode ${mode}`); + } + + // TODO(major): tags MUST be an array of tagsets + if (tags && !Array.isArray(tags)) { + console.warn( + 'ReadPreference tags must be an array, this will change in the next major version' + ); + + if (typeof tags.maxStalenessSeconds !== 'undefined') { + // this is likely an options object + options = tags; + tags = undefined; + } else { + tags = [tags]; + } + } + + this.mode = mode; + this.tags = tags; + + options = options || {}; + if (options.maxStalenessSeconds != null) { + if (options.maxStalenessSeconds <= 0) { + throw new TypeError('maxStalenessSeconds must be a positive integer'); + } + + this.maxStalenessSeconds = options.maxStalenessSeconds; + + // NOTE: The minimum required wire version is 5 for this read preference. If the existing + // topology has a lower value then a MongoError will be thrown during server selection. + this.minWireVersion = 5; + } + + if (this.mode === ReadPreference.PRIMARY) { + if (this.tags && Array.isArray(this.tags) && this.tags.length > 0) { + throw new TypeError('Primary read preference cannot be combined with tags'); + } + + if (this.maxStalenessSeconds) { + throw new TypeError('Primary read preference cannot be combined with maxStalenessSeconds'); + } + } +}; + +// Support the deprecated `preference` property introduced in the porcelain layer +Object.defineProperty(ReadPreference.prototype, 'preference', { + enumerable: true, + get: function() { + return this.mode; + } +}); + +/* + * Read preference mode constants + */ +ReadPreference.PRIMARY = 'primary'; +ReadPreference.PRIMARY_PREFERRED = 'primaryPreferred'; +ReadPreference.SECONDARY = 'secondary'; +ReadPreference.SECONDARY_PREFERRED = 'secondaryPreferred'; +ReadPreference.NEAREST = 'nearest'; + +const VALID_MODES = [ + ReadPreference.PRIMARY, + ReadPreference.PRIMARY_PREFERRED, + ReadPreference.SECONDARY, + ReadPreference.SECONDARY_PREFERRED, + ReadPreference.NEAREST, + null +]; + +/** + * Construct a ReadPreference given an options object. + * + * @param {object} options The options object from which to extract the read preference. + * @return {ReadPreference} + */ +ReadPreference.fromOptions = function(options) { + const readPreference = options.readPreference; + const readPreferenceTags = options.readPreferenceTags; + + if (readPreference == null) { + return null; + } + + if (typeof readPreference === 'string') { + return new ReadPreference(readPreference, readPreferenceTags); + } else if (!(readPreference instanceof ReadPreference) && typeof readPreference === 'object') { + const mode = readPreference.mode || readPreference.preference; + if (mode && typeof mode === 'string') { + return new ReadPreference(mode, readPreference.tags, { + maxStalenessSeconds: readPreference.maxStalenessSeconds + }); + } + } + + return readPreference; +}; + +/** + * Validate if a mode is legal + * + * @method + * @param {string} mode The string representing the read preference mode. + * @return {boolean} True if a mode is valid + */ +ReadPreference.isValid = function(mode) { + return VALID_MODES.indexOf(mode) !== -1; +}; + +/** + * Validate if a mode is legal + * + * @method + * @param {string} mode The string representing the read preference mode. + * @return {boolean} True if a mode is valid + */ +ReadPreference.prototype.isValid = function(mode) { + return ReadPreference.isValid(typeof mode === 'string' ? mode : this.mode); +}; + +const needSlaveOk = ['primaryPreferred', 'secondary', 'secondaryPreferred', 'nearest']; + +/** + * Indicates that this readPreference needs the "slaveOk" bit when sent over the wire + * @method + * @return {boolean} + * @see https://docs.mongodb.com/manual/reference/mongodb-wire-protocol/#op-query + */ +ReadPreference.prototype.slaveOk = function() { + return needSlaveOk.indexOf(this.mode) !== -1; +}; + +/** + * Are the two read preference equal + * @method + * @param {ReadPreference} readPreference The read preference with which to check equality + * @return {boolean} True if the two ReadPreferences are equivalent + */ +ReadPreference.prototype.equals = function(readPreference) { + return readPreference.mode === this.mode; +}; + +/** + * Return JSON representation + * @method + * @return {Object} A JSON representation of the ReadPreference + */ +ReadPreference.prototype.toJSON = function() { + const readPreference = { mode: this.mode }; + if (Array.isArray(this.tags)) readPreference.tags = this.tags; + if (this.maxStalenessSeconds) readPreference.maxStalenessSeconds = this.maxStalenessSeconds; + return readPreference; +}; + +/** + * Primary read preference + * @member + * @type {ReadPreference} + */ +ReadPreference.primary = new ReadPreference('primary'); +/** + * Primary Preferred read preference + * @member + * @type {ReadPreference} + */ +ReadPreference.primaryPreferred = new ReadPreference('primaryPreferred'); +/** + * Secondary read preference + * @member + * @type {ReadPreference} + */ +ReadPreference.secondary = new ReadPreference('secondary'); +/** + * Secondary Preferred read preference + * @member + * @type {ReadPreference} + */ +ReadPreference.secondaryPreferred = new ReadPreference('secondaryPreferred'); +/** + * Nearest read preference + * @member + * @type {ReadPreference} + */ +ReadPreference.nearest = new ReadPreference('nearest'); + +module.exports = ReadPreference; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/topologies/replset.js b/scripts/2.5/node_modules/mongodb/lib/core/topologies/replset.js new file mode 100644 index 00000000..89403ea4 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/core/topologies/replset.js @@ -0,0 +1,1553 @@ +'use strict'; + +const inherits = require('util').inherits; +const f = require('util').format; +const EventEmitter = require('events').EventEmitter; +const ReadPreference = require('./read_preference'); +const CoreCursor = require('../cursor').CoreCursor; +const retrieveBSON = require('../connection/utils').retrieveBSON; +const Logger = require('../connection/logger'); +const MongoError = require('../error').MongoError; +const Server = require('./server'); +const ReplSetState = require('./replset_state'); +const clone = require('./shared').clone; +const Timeout = require('./shared').Timeout; +const Interval = require('./shared').Interval; +const createClientInfo = require('./shared').createClientInfo; +const SessionMixins = require('./shared').SessionMixins; +const isRetryableWritesSupported = require('./shared').isRetryableWritesSupported; +const relayEvents = require('../utils').relayEvents; +const isRetryableError = require('../error').isRetryableError; +const BSON = retrieveBSON(); +const calculateDurationInMs = require('../utils').calculateDurationInMs; +const getMMAPError = require('./shared').getMMAPError; + +// +// States +var DISCONNECTED = 'disconnected'; +var CONNECTING = 'connecting'; +var CONNECTED = 'connected'; +var UNREFERENCED = 'unreferenced'; +var DESTROYED = 'destroyed'; + +function stateTransition(self, newState) { + var legalTransitions = { + disconnected: [CONNECTING, DESTROYED, DISCONNECTED], + connecting: [CONNECTING, DESTROYED, CONNECTED, DISCONNECTED], + connected: [CONNECTED, DISCONNECTED, DESTROYED, UNREFERENCED], + unreferenced: [UNREFERENCED, DESTROYED], + destroyed: [DESTROYED] + }; + + // Get current state + var legalStates = legalTransitions[self.state]; + if (legalStates && legalStates.indexOf(newState) !== -1) { + self.state = newState; + } else { + self.s.logger.error( + f( + 'Pool with id [%s] failed attempted illegal state transition from [%s] to [%s] only following state allowed [%s]', + self.id, + self.state, + newState, + legalStates + ) + ); + } +} + +// +// ReplSet instance id +var id = 1; +var handlers = ['connect', 'close', 'error', 'timeout', 'parseError']; + +/** + * Creates a new Replset instance + * @class + * @param {array} seedlist A list of seeds for the replicaset + * @param {boolean} options.setName The Replicaset set name + * @param {boolean} [options.secondaryOnlyConnectionAllowed=false] Allow connection to a secondary only replicaset + * @param {number} [options.haInterval=10000] The High availability period for replicaset inquiry + * @param {boolean} [options.emitError=false] Server will emit errors events + * @param {Cursor} [options.cursorFactory=Cursor] The cursor factory class used for all query cursors + * @param {number} [options.size=5] Server connection pool size + * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled + * @param {number} [options.keepAliveInitialDelay=0] Initial delay before TCP keep alive enabled + * @param {boolean} [options.noDelay=true] TCP Connection no delay + * @param {number} [options.connectionTimeout=10000] TCP Connection timeout setting + * @param {number} [options.socketTimeout=0] TCP Socket timeout setting + * @param {boolean} [options.ssl=false] Use SSL for connection + * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. + * @param {Buffer} [options.ca] SSL Certificate store binary buffer + * @param {Buffer} [options.crl] SSL Certificate revocation store binary buffer + * @param {Buffer} [options.cert] SSL Certificate binary buffer + * @param {Buffer} [options.key] SSL Key file binary buffer + * @param {string} [options.passphrase] SSL Certificate pass phrase + * @param {string} [options.servername=null] String containing the server name requested via TLS SNI. + * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates + * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits + * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. + * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. + * @param {number} [options.pingInterval=5000] Ping interval to check the response time to the different servers + * @param {number} [options.localThresholdMS=15] Cutoff latency point in MS for Replicaset member selection + * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. + * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology + * @return {ReplSet} A cursor instance + * @fires ReplSet#connect + * @fires ReplSet#ha + * @fires ReplSet#joined + * @fires ReplSet#left + * @fires ReplSet#failed + * @fires ReplSet#fullsetup + * @fires ReplSet#all + * @fires ReplSet#error + * @fires ReplSet#serverHeartbeatStarted + * @fires ReplSet#serverHeartbeatSucceeded + * @fires ReplSet#serverHeartbeatFailed + * @fires ReplSet#topologyOpening + * @fires ReplSet#topologyClosed + * @fires ReplSet#topologyDescriptionChanged + * @property {string} type the topology type. + * @property {string} parserType the parser type used (c++ or js). + */ +var ReplSet = function(seedlist, options) { + var self = this; + options = options || {}; + + // Validate seedlist + if (!Array.isArray(seedlist)) throw new MongoError('seedlist must be an array'); + // Validate list + if (seedlist.length === 0) throw new MongoError('seedlist must contain at least one entry'); + // Validate entries + seedlist.forEach(function(e) { + if (typeof e.host !== 'string' || typeof e.port !== 'number') + throw new MongoError('seedlist entry must contain a host and port'); + }); + + // Add event listener + EventEmitter.call(this); + + // Get replSet Id + this.id = id++; + + // Get the localThresholdMS + var localThresholdMS = options.localThresholdMS || 15; + // Backward compatibility + if (options.acceptableLatency) localThresholdMS = options.acceptableLatency; + + // Create a logger + var logger = Logger('ReplSet', options); + + // Internal state + this.s = { + options: Object.assign({}, options), + // BSON instance + bson: + options.bson || + new BSON([ + BSON.Binary, + BSON.Code, + BSON.DBRef, + BSON.Decimal128, + BSON.Double, + BSON.Int32, + BSON.Long, + BSON.Map, + BSON.MaxKey, + BSON.MinKey, + BSON.ObjectId, + BSON.BSONRegExp, + BSON.Symbol, + BSON.Timestamp + ]), + // Factory overrides + Cursor: options.cursorFactory || CoreCursor, + // Logger instance + logger: logger, + // Seedlist + seedlist: seedlist, + // Replicaset state + replicaSetState: new ReplSetState({ + id: this.id, + setName: options.setName, + acceptableLatency: localThresholdMS, + heartbeatFrequencyMS: options.haInterval ? options.haInterval : 10000, + logger: logger + }), + // Current servers we are connecting to + connectingServers: [], + // Ha interval + haInterval: options.haInterval ? options.haInterval : 10000, + // Minimum heartbeat frequency used if we detect a server close + minHeartbeatFrequencyMS: 500, + // Disconnect handler + disconnectHandler: options.disconnectHandler, + // Server selection index + index: 0, + // Connect function options passed in + connectOptions: {}, + // Are we running in debug mode + debug: typeof options.debug === 'boolean' ? options.debug : false, + // Client info + clientInfo: createClientInfo(options) + }; + + // Add handler for topology change + this.s.replicaSetState.on('topologyDescriptionChanged', function(r) { + self.emit('topologyDescriptionChanged', r); + }); + + // Log info warning if the socketTimeout < haInterval as it will cause + // a lot of recycled connections to happen. + if ( + this.s.logger.isWarn() && + this.s.options.socketTimeout !== 0 && + this.s.options.socketTimeout < this.s.haInterval + ) { + this.s.logger.warn( + f( + 'warning socketTimeout %s is less than haInterval %s. This might cause unnecessary server reconnections due to socket timeouts', + this.s.options.socketTimeout, + this.s.haInterval + ) + ); + } + + // Add forwarding of events from state handler + var types = ['joined', 'left']; + types.forEach(function(x) { + self.s.replicaSetState.on(x, function(t, s) { + self.emit(x, t, s); + }); + }); + + // Connect stat + this.initialConnectState = { + connect: false, + fullsetup: false, + all: false + }; + + // Disconnected state + this.state = DISCONNECTED; + this.haTimeoutId = null; + // Last ismaster + this.ismaster = null; + // Contains the intervalId + this.intervalIds = []; + + // Highest clusterTime seen in responses from the current deployment + this.clusterTime = null; +}; + +inherits(ReplSet, EventEmitter); +Object.assign(ReplSet.prototype, SessionMixins); + +Object.defineProperty(ReplSet.prototype, 'type', { + enumerable: true, + get: function() { + return 'replset'; + } +}); + +Object.defineProperty(ReplSet.prototype, 'parserType', { + enumerable: true, + get: function() { + return BSON.native ? 'c++' : 'js'; + } +}); + +Object.defineProperty(ReplSet.prototype, 'logicalSessionTimeoutMinutes', { + enumerable: true, + get: function() { + return this.s.replicaSetState.logicalSessionTimeoutMinutes || null; + } +}); + +function rexecuteOperations(self) { + // If we have a primary and a disconnect handler, execute + // buffered operations + if (self.s.replicaSetState.hasPrimaryAndSecondary() && self.s.disconnectHandler) { + self.s.disconnectHandler.execute(); + } else if (self.s.replicaSetState.hasPrimary() && self.s.disconnectHandler) { + self.s.disconnectHandler.execute({ executePrimary: true }); + } else if (self.s.replicaSetState.hasSecondary() && self.s.disconnectHandler) { + self.s.disconnectHandler.execute({ executeSecondary: true }); + } +} + +function connectNewServers(self, servers, callback) { + // Count lefts + var count = servers.length; + var error = null; + + // Handle events + var _handleEvent = function(self, event) { + return function(err) { + var _self = this; + count = count - 1; + + // Destroyed + if (self.state === DESTROYED || self.state === UNREFERENCED) { + return this.destroy({ force: true }); + } + + if (event === 'connect') { + // Destroyed + if (self.state === DESTROYED || self.state === UNREFERENCED) { + return _self.destroy({ force: true }); + } + + // Update the state + var result = self.s.replicaSetState.update(_self); + // Update the state with the new server + if (result) { + // Primary lastIsMaster store it + if (_self.lastIsMaster() && _self.lastIsMaster().ismaster) { + self.ismaster = _self.lastIsMaster(); + } + + // Remove the handlers + for (let i = 0; i < handlers.length; i++) { + _self.removeAllListeners(handlers[i]); + } + + // Add stable state handlers + _self.on('error', handleEvent(self, 'error')); + _self.on('close', handleEvent(self, 'close')); + _self.on('timeout', handleEvent(self, 'timeout')); + _self.on('parseError', handleEvent(self, 'parseError')); + + // Enalbe the monitoring of the new server + monitorServer(_self.lastIsMaster().me, self, {}); + + // Rexecute any stalled operation + rexecuteOperations(self); + } else { + _self.destroy({ force: true }); + } + } else if (event === 'error') { + error = err; + } + + // Rexecute any stalled operation + rexecuteOperations(self); + + // Are we done finish up callback + if (count === 0) { + callback(error); + } + }; + }; + + // No new servers + if (count === 0) return callback(); + + // Execute method + function execute(_server, i) { + setTimeout(function() { + // Destroyed + if (self.state === DESTROYED || self.state === UNREFERENCED) { + return; + } + + // Create a new server instance + var server = new Server( + Object.assign({}, self.s.options, { + host: _server.split(':')[0], + port: parseInt(_server.split(':')[1], 10), + reconnect: false, + monitoring: false, + parent: self, + clientInfo: clone(self.s.clientInfo) + }) + ); + + // Add temp handlers + server.once('connect', _handleEvent(self, 'connect')); + server.once('close', _handleEvent(self, 'close')); + server.once('timeout', _handleEvent(self, 'timeout')); + server.once('error', _handleEvent(self, 'error')); + server.once('parseError', _handleEvent(self, 'parseError')); + + // SDAM Monitoring events + server.on('serverOpening', e => self.emit('serverOpening', e)); + server.on('serverDescriptionChanged', e => self.emit('serverDescriptionChanged', e)); + server.on('serverClosed', e => self.emit('serverClosed', e)); + + // Command Monitoring events + relayEvents(server, self, ['commandStarted', 'commandSucceeded', 'commandFailed']); + + self.s.connectingServers.push(server); + server.connect(self.s.connectOptions); + }, i); + } + + // Create new instances + for (var i = 0; i < servers.length; i++) { + execute(servers[i], i); + } +} + +// Ping the server +var pingServer = function(self, server, cb) { + // Measure running time + var start = new Date().getTime(); + + // Emit the server heartbeat start + emitSDAMEvent(self, 'serverHeartbeatStarted', { connectionId: server.name }); + + // Execute ismaster + // Set the socketTimeout for a monitoring message to a low number + // Ensuring ismaster calls are timed out quickly + server.command( + 'admin.$cmd', + { + ismaster: true + }, + { + monitoring: true, + socketTimeout: self.s.options.connectionTimeout || 2000 + }, + function(err, r) { + if (self.state === DESTROYED || self.state === UNREFERENCED) { + server.destroy({ force: true }); + return cb(err, r); + } + + // Calculate latency + var latencyMS = new Date().getTime() - start; + + // Set the last updatedTime + var hrtime = process.hrtime(); + server.lastUpdateTime = (hrtime[0] * 1e9 + hrtime[1]) / 1e6; + + // We had an error, remove it from the state + if (err) { + // Emit the server heartbeat failure + emitSDAMEvent(self, 'serverHeartbeatFailed', { + durationMS: latencyMS, + failure: err, + connectionId: server.name + }); + + // Remove server from the state + self.s.replicaSetState.remove(server); + } else { + // Update the server ismaster + server.ismaster = r.result; + + // Check if we have a lastWriteDate convert it to MS + // and store on the server instance for later use + if (server.ismaster.lastWrite && server.ismaster.lastWrite.lastWriteDate) { + server.lastWriteDate = server.ismaster.lastWrite.lastWriteDate.getTime(); + } + + // Do we have a brand new server + if (server.lastIsMasterMS === -1) { + server.lastIsMasterMS = latencyMS; + } else if (server.lastIsMasterMS) { + // After the first measurement, average RTT MUST be computed using an + // exponentially-weighted moving average formula, with a weighting factor (alpha) of 0.2. + // If the prior average is denoted old_rtt, then the new average (new_rtt) is + // computed from a new RTT measurement (x) using the following formula: + // alpha = 0.2 + // new_rtt = alpha * x + (1 - alpha) * old_rtt + server.lastIsMasterMS = 0.2 * latencyMS + (1 - 0.2) * server.lastIsMasterMS; + } + + if (self.s.replicaSetState.update(server)) { + // Primary lastIsMaster store it + if (server.lastIsMaster() && server.lastIsMaster().ismaster) { + self.ismaster = server.lastIsMaster(); + } + } + + // Server heart beat event + emitSDAMEvent(self, 'serverHeartbeatSucceeded', { + durationMS: latencyMS, + reply: r.result, + connectionId: server.name + }); + } + + // Calculate the staleness for this server + self.s.replicaSetState.updateServerMaxStaleness(server, self.s.haInterval); + + // Callback + cb(err, r); + } + ); +}; + +// Each server is monitored in parallel in their own timeout loop +var monitorServer = function(host, self, options) { + // If this is not the initial scan + // Is this server already being monitoried, then skip monitoring + if (!options.haInterval) { + for (var i = 0; i < self.intervalIds.length; i++) { + if (self.intervalIds[i].__host === host) { + return; + } + } + } + + // Get the haInterval + var _process = options.haInterval ? Timeout : Interval; + var _haInterval = options.haInterval ? options.haInterval : self.s.haInterval; + + // Create the interval + var intervalId = new _process(function() { + if (self.state === DESTROYED || self.state === UNREFERENCED) { + // clearInterval(intervalId); + intervalId.stop(); + return; + } + + // Do we already have server connection available for this host + var _server = self.s.replicaSetState.get(host); + + // Check if we have a known server connection and reuse + if (_server) { + // Ping the server + return pingServer(self, _server, function(err) { + if (err) { + // NOTE: should something happen here? + return; + } + + if (self.state === DESTROYED || self.state === UNREFERENCED) { + intervalId.stop(); + return; + } + + // Filter out all called intervaliIds + self.intervalIds = self.intervalIds.filter(function(intervalId) { + return intervalId.isRunning(); + }); + + // Initial sweep + if (_process === Timeout) { + if ( + self.state === CONNECTING && + ((self.s.replicaSetState.hasSecondary() && + self.s.options.secondaryOnlyConnectionAllowed) || + self.s.replicaSetState.hasPrimary()) + ) { + self.state = CONNECTED; + + // Emit connected sign + process.nextTick(function() { + self.emit('connect', self); + }); + + // Start topology interval check + topologyMonitor(self, {}); + } + } else { + if ( + self.state === DISCONNECTED && + ((self.s.replicaSetState.hasSecondary() && + self.s.options.secondaryOnlyConnectionAllowed) || + self.s.replicaSetState.hasPrimary()) + ) { + self.state = CONNECTED; + + // Rexecute any stalled operation + rexecuteOperations(self); + + // Emit connected sign + process.nextTick(function() { + self.emit('reconnect', self); + }); + } + } + + if ( + self.initialConnectState.connect && + !self.initialConnectState.fullsetup && + self.s.replicaSetState.hasPrimaryAndSecondary() + ) { + // Set initial connect state + self.initialConnectState.fullsetup = true; + self.initialConnectState.all = true; + + process.nextTick(function() { + self.emit('fullsetup', self); + self.emit('all', self); + }); + } + }); + } + }, _haInterval); + + // Start the interval + intervalId.start(); + // Add the intervalId host name + intervalId.__host = host; + // Add the intervalId to our list of intervalIds + self.intervalIds.push(intervalId); +}; + +function topologyMonitor(self, options) { + if (self.state === DESTROYED || self.state === UNREFERENCED) return; + options = options || {}; + + // Get the servers + var servers = Object.keys(self.s.replicaSetState.set); + + // Get the haInterval + var _process = options.haInterval ? Timeout : Interval; + var _haInterval = options.haInterval ? options.haInterval : self.s.haInterval; + + if (_process === Timeout) { + return connectNewServers(self, self.s.replicaSetState.unknownServers, function(err) { + // Don't emit errors if the connection was already + if (self.state === DESTROYED || self.state === UNREFERENCED) { + return; + } + + if (!self.s.replicaSetState.hasPrimary() && !self.s.options.secondaryOnlyConnectionAllowed) { + if (err) { + return self.emit('error', err); + } + + self.emit( + 'error', + new MongoError('no primary found in replicaset or invalid replica set name') + ); + return self.destroy({ force: true }); + } else if ( + !self.s.replicaSetState.hasSecondary() && + self.s.options.secondaryOnlyConnectionAllowed + ) { + if (err) { + return self.emit('error', err); + } + + self.emit( + 'error', + new MongoError('no secondary found in replicaset or invalid replica set name') + ); + return self.destroy({ force: true }); + } + + for (var i = 0; i < servers.length; i++) { + monitorServer(servers[i], self, options); + } + }); + } else { + for (var i = 0; i < servers.length; i++) { + monitorServer(servers[i], self, options); + } + } + + // Run the reconnect process + function executeReconnect(self) { + return function() { + if (self.state === DESTROYED || self.state === UNREFERENCED) { + return; + } + + connectNewServers(self, self.s.replicaSetState.unknownServers, function() { + var monitoringFrequencey = self.s.replicaSetState.hasPrimary() + ? _haInterval + : self.s.minHeartbeatFrequencyMS; + + // Create a timeout + self.intervalIds.push(new Timeout(executeReconnect(self), monitoringFrequencey).start()); + }); + }; + } + + // Decide what kind of interval to use + var intervalTime = !self.s.replicaSetState.hasPrimary() + ? self.s.minHeartbeatFrequencyMS + : _haInterval; + + self.intervalIds.push(new Timeout(executeReconnect(self), intervalTime).start()); +} + +function addServerToList(list, server) { + for (var i = 0; i < list.length; i++) { + if (list[i].name.toLowerCase() === server.name.toLowerCase()) return true; + } + + list.push(server); +} + +function handleEvent(self, event) { + return function() { + if (self.state === DESTROYED || self.state === UNREFERENCED) return; + // Debug log + if (self.s.logger.isDebug()) { + self.s.logger.debug( + f('handleEvent %s from server %s in replset with id %s', event, this.name, self.id) + ); + } + + // Remove from the replicaset state + self.s.replicaSetState.remove(this); + + // Are we in a destroyed state return + if (self.state === DESTROYED || self.state === UNREFERENCED) return; + + // If no primary and secondary available + if ( + !self.s.replicaSetState.hasPrimary() && + !self.s.replicaSetState.hasSecondary() && + self.s.options.secondaryOnlyConnectionAllowed + ) { + stateTransition(self, DISCONNECTED); + } else if (!self.s.replicaSetState.hasPrimary()) { + stateTransition(self, DISCONNECTED); + } + + addServerToList(self.s.connectingServers, this); + }; +} + +function shouldTriggerConnect(self) { + const isConnecting = self.state === CONNECTING; + const hasPrimary = self.s.replicaSetState.hasPrimary(); + const hasSecondary = self.s.replicaSetState.hasSecondary(); + const secondaryOnlyConnectionAllowed = self.s.options.secondaryOnlyConnectionAllowed; + const readPreferenceSecondary = + self.s.connectOptions.readPreference && + self.s.connectOptions.readPreference.equals(ReadPreference.secondary); + + return ( + (isConnecting && + ((readPreferenceSecondary && hasSecondary) || (!readPreferenceSecondary && hasPrimary))) || + (hasSecondary && secondaryOnlyConnectionAllowed) + ); +} + +function handleInitialConnectEvent(self, event) { + return function() { + var _this = this; + // Debug log + if (self.s.logger.isDebug()) { + self.s.logger.debug( + f( + 'handleInitialConnectEvent %s from server %s in replset with id %s', + event, + this.name, + self.id + ) + ); + } + + // Destroy the instance + if (self.state === DESTROYED || self.state === UNREFERENCED) { + return this.destroy({ force: true }); + } + + // Check the type of server + if (event === 'connect') { + // Update the state + var result = self.s.replicaSetState.update(_this); + if (result === true) { + // Primary lastIsMaster store it + if (_this.lastIsMaster() && _this.lastIsMaster().ismaster) { + self.ismaster = _this.lastIsMaster(); + } + + // Debug log + if (self.s.logger.isDebug()) { + self.s.logger.debug( + f( + 'handleInitialConnectEvent %s from server %s in replset with id %s has state [%s]', + event, + _this.name, + self.id, + JSON.stringify(self.s.replicaSetState.set) + ) + ); + } + + // Remove the handlers + for (let i = 0; i < handlers.length; i++) { + _this.removeAllListeners(handlers[i]); + } + + // Add stable state handlers + _this.on('error', handleEvent(self, 'error')); + _this.on('close', handleEvent(self, 'close')); + _this.on('timeout', handleEvent(self, 'timeout')); + _this.on('parseError', handleEvent(self, 'parseError')); + + // Do we have a primary or primaryAndSecondary + if (shouldTriggerConnect(self)) { + // We are connected + self.state = CONNECTED; + + // Set initial connect state + self.initialConnectState.connect = true; + // Emit connect event + process.nextTick(function() { + self.emit('connect', self); + }); + + topologyMonitor(self, {}); + } + } else if (result instanceof MongoError) { + _this.destroy({ force: true }); + self.destroy({ force: true }); + return self.emit('error', result); + } else { + _this.destroy({ force: true }); + } + } else { + // Emit failure to connect + self.emit('failed', this); + + addServerToList(self.s.connectingServers, this); + // Remove from the state + self.s.replicaSetState.remove(this); + } + + if ( + self.initialConnectState.connect && + !self.initialConnectState.fullsetup && + self.s.replicaSetState.hasPrimaryAndSecondary() + ) { + // Set initial connect state + self.initialConnectState.fullsetup = true; + self.initialConnectState.all = true; + + process.nextTick(function() { + self.emit('fullsetup', self); + self.emit('all', self); + }); + } + + // Remove from the list from connectingServers + for (var i = 0; i < self.s.connectingServers.length; i++) { + if (self.s.connectingServers[i].equals(this)) { + self.s.connectingServers.splice(i, 1); + } + } + + // Trigger topologyMonitor + if (self.s.connectingServers.length === 0 && self.state === CONNECTING) { + topologyMonitor(self, { haInterval: 1 }); + } + }; +} + +function connectServers(self, servers) { + // Update connectingServers + self.s.connectingServers = self.s.connectingServers.concat(servers); + + // Index used to interleaf the server connects, avoiding + // runtime issues on io constrained vm's + var timeoutInterval = 0; + + function connect(server, timeoutInterval) { + setTimeout(function() { + // Add the server to the state + if (self.s.replicaSetState.update(server)) { + // Primary lastIsMaster store it + if (server.lastIsMaster() && server.lastIsMaster().ismaster) { + self.ismaster = server.lastIsMaster(); + } + } + + // Add event handlers + server.once('close', handleInitialConnectEvent(self, 'close')); + server.once('timeout', handleInitialConnectEvent(self, 'timeout')); + server.once('parseError', handleInitialConnectEvent(self, 'parseError')); + server.once('error', handleInitialConnectEvent(self, 'error')); + server.once('connect', handleInitialConnectEvent(self, 'connect')); + + // SDAM Monitoring events + server.on('serverOpening', e => self.emit('serverOpening', e)); + server.on('serverDescriptionChanged', e => self.emit('serverDescriptionChanged', e)); + server.on('serverClosed', e => self.emit('serverClosed', e)); + + // Command Monitoring events + relayEvents(server, self, ['commandStarted', 'commandSucceeded', 'commandFailed']); + + // Start connection + server.connect(self.s.connectOptions); + }, timeoutInterval); + } + + // Start all the servers + while (servers.length > 0) { + connect(servers.shift(), timeoutInterval++); + } +} + +/** + * Emit event if it exists + * @method + */ +function emitSDAMEvent(self, event, description) { + if (self.listeners(event).length > 0) { + self.emit(event, description); + } +} + +/** + * Initiate server connect + */ +ReplSet.prototype.connect = function(options) { + var self = this; + // Add any connect level options to the internal state + this.s.connectOptions = options || {}; + + // Set connecting state + stateTransition(this, CONNECTING); + + // Create server instances + var servers = this.s.seedlist.map(function(x) { + return new Server( + Object.assign({}, self.s.options, x, options, { + reconnect: false, + monitoring: false, + parent: self, + clientInfo: clone(self.s.clientInfo) + }) + ); + }); + + // Error out as high availbility interval must be < than socketTimeout + if ( + this.s.options.socketTimeout > 0 && + this.s.options.socketTimeout <= this.s.options.haInterval + ) { + return self.emit( + 'error', + new MongoError( + f( + 'haInterval [%s] MS must be set to less than socketTimeout [%s] MS', + this.s.options.haInterval, + this.s.options.socketTimeout + ) + ) + ); + } + + // Emit the topology opening event + emitSDAMEvent(this, 'topologyOpening', { topologyId: this.id }); + // Start all server connections + connectServers(self, servers); +}; + +/** + * Authenticate the topology. + * @method + * @param {MongoCredentials} credentials The credentials for authentication we are using + * @param {authResultCallback} callback A callback function + */ +ReplSet.prototype.auth = function(credentials, callback) { + if (typeof callback === 'function') callback(null, null); +}; + +/** + * Destroy the server connection + * @param {boolean} [options.force=false] Force destroy the pool + * @method + */ +ReplSet.prototype.destroy = function(options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + + options = options || {}; + + let destroyCount = this.s.connectingServers.length + 1; // +1 for the callback from `replicaSetState.destroy` + const serverDestroyed = () => { + destroyCount--; + if (destroyCount > 0) { + return; + } + + // Emit toplogy closing event + emitSDAMEvent(this, 'topologyClosed', { topologyId: this.id }); + + // Transition state + stateTransition(this, DESTROYED); + + if (typeof callback === 'function') { + callback(null, null); + } + }; + + // Clear out any monitoring process + if (this.haTimeoutId) clearTimeout(this.haTimeoutId); + + // Clear out all monitoring + for (var i = 0; i < this.intervalIds.length; i++) { + this.intervalIds[i].stop(); + } + + // Reset list of intervalIds + this.intervalIds = []; + + if (destroyCount === 0) { + serverDestroyed(); + return; + } + + // Destroy the replicaset + this.s.replicaSetState.destroy(options, serverDestroyed); + + // Destroy all connecting servers + this.s.connectingServers.forEach(function(x) { + x.destroy(options, serverDestroyed); + }); +}; + +/** + * Unref all connections belong to this server + * @method + */ +ReplSet.prototype.unref = function() { + // Transition state + stateTransition(this, UNREFERENCED); + + this.s.replicaSetState.allServers().forEach(function(x) { + x.unref(); + }); + + clearTimeout(this.haTimeoutId); +}; + +/** + * Returns the last known ismaster document for this server + * @method + * @return {object} + */ +ReplSet.prototype.lastIsMaster = function() { + // If secondaryOnlyConnectionAllowed and no primary but secondary + // return the secondaries ismaster result. + if ( + this.s.options.secondaryOnlyConnectionAllowed && + !this.s.replicaSetState.hasPrimary() && + this.s.replicaSetState.hasSecondary() + ) { + return this.s.replicaSetState.secondaries[0].lastIsMaster(); + } + + return this.s.replicaSetState.primary + ? this.s.replicaSetState.primary.lastIsMaster() + : this.ismaster; +}; + +/** + * All raw connections + * @method + * @return {Connection[]} + */ +ReplSet.prototype.connections = function() { + var servers = this.s.replicaSetState.allServers(); + var connections = []; + for (var i = 0; i < servers.length; i++) { + connections = connections.concat(servers[i].connections()); + } + + return connections; +}; + +/** + * Figure out if the server is connected + * @method + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @return {boolean} + */ +ReplSet.prototype.isConnected = function(options) { + options = options || {}; + + // If we specified a read preference check if we are connected to something + // than can satisfy this + if (options.readPreference && options.readPreference.equals(ReadPreference.secondary)) { + return this.s.replicaSetState.hasSecondary(); + } + + if (options.readPreference && options.readPreference.equals(ReadPreference.primary)) { + return this.s.replicaSetState.hasPrimary(); + } + + if (options.readPreference && options.readPreference.equals(ReadPreference.primaryPreferred)) { + return this.s.replicaSetState.hasSecondary() || this.s.replicaSetState.hasPrimary(); + } + + if (options.readPreference && options.readPreference.equals(ReadPreference.secondaryPreferred)) { + return this.s.replicaSetState.hasSecondary() || this.s.replicaSetState.hasPrimary(); + } + + if (this.s.options.secondaryOnlyConnectionAllowed && this.s.replicaSetState.hasSecondary()) { + return true; + } + + return this.s.replicaSetState.hasPrimary(); +}; + +/** + * Figure out if the replicaset instance was destroyed by calling destroy + * @method + * @return {boolean} + */ +ReplSet.prototype.isDestroyed = function() { + return this.state === DESTROYED; +}; + +const SERVER_SELECTION_TIMEOUT_MS = 10000; // hardcoded `serverSelectionTimeoutMS` for legacy topology +const SERVER_SELECTION_INTERVAL_MS = 1000; // time to wait between selection attempts +/** + * Selects a server + * + * @method + * @param {function} selector Unused + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {ClientSession} [options.session] Unused + * @param {function} callback + */ +ReplSet.prototype.selectServer = function(selector, options, callback) { + if (typeof selector === 'function' && typeof callback === 'undefined') + (callback = selector), (selector = undefined), (options = {}); + if (typeof options === 'function') (callback = options), (options = selector); + options = options || {}; + + let readPreference; + if (selector instanceof ReadPreference) { + readPreference = selector; + } else { + readPreference = options.readPreference || ReadPreference.primary; + } + + let lastError; + const start = process.hrtime(); + const _selectServer = () => { + if (calculateDurationInMs(start) >= SERVER_SELECTION_TIMEOUT_MS) { + if (lastError != null) { + callback(lastError, null); + } else { + callback(new MongoError('Server selection timed out')); + } + + return; + } + + const server = this.s.replicaSetState.pickServer(readPreference); + if (server == null) { + setTimeout(_selectServer, SERVER_SELECTION_INTERVAL_MS); + return; + } + + if (!(server instanceof Server)) { + lastError = server; + setTimeout(_selectServer, SERVER_SELECTION_INTERVAL_MS); + return; + } + + if (this.s.debug) this.emit('pickedServer', options.readPreference, server); + callback(null, server); + }; + + _selectServer(); +}; + +/** + * Get all connected servers + * @method + * @return {Server[]} + */ +ReplSet.prototype.getServers = function() { + return this.s.replicaSetState.allServers(); +}; + +// +// Execute write operation +function executeWriteOperation(args, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + // TODO: once we drop Node 4, use destructuring either here or in arguments. + const self = args.self; + const op = args.op; + const ns = args.ns; + const ops = args.ops; + + if (self.state === DESTROYED) { + return callback(new MongoError(f('topology was destroyed'))); + } + + const willRetryWrite = + !args.retrying && + !!options.retryWrites && + options.session && + isRetryableWritesSupported(self) && + !options.session.inTransaction(); + + if (!self.s.replicaSetState.hasPrimary()) { + if (self.s.disconnectHandler) { + // Not connected but we have a disconnecthandler + return self.s.disconnectHandler.add(op, ns, ops, options, callback); + } else if (!willRetryWrite) { + // No server returned we had an error + return callback(new MongoError('no primary server found')); + } + } + + const handler = (err, result) => { + if (!err) return callback(null, result); + if (!isRetryableError(err)) { + err = getMMAPError(err); + return callback(err); + } + + if (willRetryWrite) { + const newArgs = Object.assign({}, args, { retrying: true }); + return executeWriteOperation(newArgs, options, callback); + } + + // Per SDAM, remove primary from replicaset + if (self.s.replicaSetState.primary) { + self.s.replicaSetState.primary.destroy(); + self.s.replicaSetState.remove(self.s.replicaSetState.primary, { force: true }); + } + + return callback(err); + }; + + if (callback.operationId) { + handler.operationId = callback.operationId; + } + + // increment and assign txnNumber + if (willRetryWrite) { + options.session.incrementTransactionNumber(); + options.willRetryWrite = willRetryWrite; + } + + self.s.replicaSetState.primary[op](ns, ops, options, handler); +} + +/** + * Insert one or more documents + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of documents to insert + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {boolean} [options.retryWrites] Enable retryable writes for this operation + * @param {opResultCallback} callback A callback function + */ +ReplSet.prototype.insert = function(ns, ops, options, callback) { + // Execute write operation + executeWriteOperation({ self: this, op: 'insert', ns, ops }, options, callback); +}; + +/** + * Perform one or more update operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of updates + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {boolean} [options.retryWrites] Enable retryable writes for this operation + * @param {opResultCallback} callback A callback function + */ +ReplSet.prototype.update = function(ns, ops, options, callback) { + // Execute write operation + executeWriteOperation({ self: this, op: 'update', ns, ops }, options, callback); +}; + +/** + * Perform one or more remove operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of removes + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {boolean} [options.retryWrites] Enable retryable writes for this operation + * @param {opResultCallback} callback A callback function + */ +ReplSet.prototype.remove = function(ns, ops, options, callback) { + // Execute write operation + executeWriteOperation({ self: this, op: 'remove', ns, ops }, options, callback); +}; + +const RETRYABLE_WRITE_OPERATIONS = ['findAndModify', 'insert', 'update', 'delete']; + +function isWriteCommand(command) { + return RETRYABLE_WRITE_OPERATIONS.some(op => command[op]); +} + +/** + * Execute a command + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object} cmd The command hash + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Connection} [options.connection] Specify connection object to execute command against + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {opResultCallback} callback A callback function + */ +ReplSet.prototype.command = function(ns, cmd, options, callback) { + if (typeof options === 'function') { + (callback = options), (options = {}), (options = options || {}); + } + + if (this.state === DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + var self = this; + + // Establish readPreference + var readPreference = options.readPreference ? options.readPreference : ReadPreference.primary; + + // If the readPreference is primary and we have no primary, store it + if ( + readPreference.preference === 'primary' && + !this.s.replicaSetState.hasPrimary() && + this.s.disconnectHandler != null + ) { + return this.s.disconnectHandler.add('command', ns, cmd, options, callback); + } else if ( + readPreference.preference === 'secondary' && + !this.s.replicaSetState.hasSecondary() && + this.s.disconnectHandler != null + ) { + return this.s.disconnectHandler.add('command', ns, cmd, options, callback); + } else if ( + readPreference.preference !== 'primary' && + !this.s.replicaSetState.hasSecondary() && + !this.s.replicaSetState.hasPrimary() && + this.s.disconnectHandler != null + ) { + return this.s.disconnectHandler.add('command', ns, cmd, options, callback); + } + + // Pick a server + var server = this.s.replicaSetState.pickServer(readPreference); + // We received an error, return it + if (!(server instanceof Server)) return callback(server); + // Emit debug event + if (self.s.debug) self.emit('pickedServer', ReadPreference.primary, server); + + // No server returned we had an error + if (server == null) { + return callback( + new MongoError( + f('no server found that matches the provided readPreference %s', readPreference) + ) + ); + } + + const willRetryWrite = + !options.retrying && + !!options.retryWrites && + options.session && + isRetryableWritesSupported(self) && + !options.session.inTransaction() && + isWriteCommand(cmd); + + const cb = (err, result) => { + if (!err) return callback(null, result); + if (!isRetryableError(err)) { + return callback(err); + } + + if (willRetryWrite) { + const newOptions = Object.assign({}, options, { retrying: true }); + return this.command(ns, cmd, newOptions, callback); + } + + // Per SDAM, remove primary from replicaset + if (this.s.replicaSetState.primary) { + this.s.replicaSetState.primary.destroy(); + this.s.replicaSetState.remove(this.s.replicaSetState.primary, { force: true }); + } + + return callback(err); + }; + + // increment and assign txnNumber + if (willRetryWrite) { + options.session.incrementTransactionNumber(); + options.willRetryWrite = willRetryWrite; + } + + // Execute the command + server.command(ns, cmd, options, cb); +}; + +/** + * Get a new cursor + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object|Long} cmd Can be either a command returning a cursor or a cursorId + * @param {object} [options] Options for the cursor + * @param {object} [options.batchSize=0] Batchsize for the operation + * @param {array} [options.documents=[]] Initial documents list for cursor + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {object} [options.topology] The internal topology of the created cursor + * @returns {Cursor} + */ +ReplSet.prototype.cursor = function(ns, cmd, options) { + options = options || {}; + const topology = options.topology || this; + + // Set up final cursor type + var FinalCursor = options.cursorFactory || this.s.Cursor; + + // Return the cursor + return new FinalCursor(topology, ns, cmd, options); +}; + +/** + * A replset connect event, used to verify that the connection is up and running + * + * @event ReplSet#connect + * @type {ReplSet} + */ + +/** + * A replset reconnect event, used to verify that the topology reconnected + * + * @event ReplSet#reconnect + * @type {ReplSet} + */ + +/** + * A replset fullsetup event, used to signal that all topology members have been contacted. + * + * @event ReplSet#fullsetup + * @type {ReplSet} + */ + +/** + * A replset all event, used to signal that all topology members have been contacted. + * + * @event ReplSet#all + * @type {ReplSet} + */ + +/** + * A replset failed event, used to signal that initial replset connection failed. + * + * @event ReplSet#failed + * @type {ReplSet} + */ + +/** + * A server member left the replicaset + * + * @event ReplSet#left + * @type {function} + * @param {string} type The type of member that left (primary|secondary|arbiter) + * @param {Server} server The server object that left + */ + +/** + * A server member joined the replicaset + * + * @event ReplSet#joined + * @type {function} + * @param {string} type The type of member that joined (primary|secondary|arbiter) + * @param {Server} server The server object that joined + */ + +/** + * A server opening SDAM monitoring event + * + * @event ReplSet#serverOpening + * @type {object} + */ + +/** + * A server closed SDAM monitoring event + * + * @event ReplSet#serverClosed + * @type {object} + */ + +/** + * A server description SDAM change monitoring event + * + * @event ReplSet#serverDescriptionChanged + * @type {object} + */ + +/** + * A topology open SDAM event + * + * @event ReplSet#topologyOpening + * @type {object} + */ + +/** + * A topology closed SDAM event + * + * @event ReplSet#topologyClosed + * @type {object} + */ + +/** + * A topology structure SDAM change event + * + * @event ReplSet#topologyDescriptionChanged + * @type {object} + */ + +/** + * A topology serverHeartbeatStarted SDAM event + * + * @event ReplSet#serverHeartbeatStarted + * @type {object} + */ + +/** + * A topology serverHeartbeatFailed SDAM event + * + * @event ReplSet#serverHeartbeatFailed + * @type {object} + */ + +/** + * A topology serverHeartbeatSucceeded SDAM change event + * + * @event ReplSet#serverHeartbeatSucceeded + * @type {object} + */ + +/** + * An event emitted indicating a command was started, if command monitoring is enabled + * + * @event ReplSet#commandStarted + * @type {object} + */ + +/** + * An event emitted indicating a command succeeded, if command monitoring is enabled + * + * @event ReplSet#commandSucceeded + * @type {object} + */ + +/** + * An event emitted indicating a command failed, if command monitoring is enabled + * + * @event ReplSet#commandFailed + * @type {object} + */ + +module.exports = ReplSet; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/topologies/replset_state.js b/scripts/2.5/node_modules/mongodb/lib/core/topologies/replset_state.js new file mode 100644 index 00000000..24c16d6d --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/core/topologies/replset_state.js @@ -0,0 +1,1121 @@ +'use strict'; + +var inherits = require('util').inherits, + f = require('util').format, + diff = require('./shared').diff, + EventEmitter = require('events').EventEmitter, + Logger = require('../connection/logger'), + ReadPreference = require('./read_preference'), + MongoError = require('../error').MongoError, + Buffer = require('safe-buffer').Buffer; + +var TopologyType = { + Single: 'Single', + ReplicaSetNoPrimary: 'ReplicaSetNoPrimary', + ReplicaSetWithPrimary: 'ReplicaSetWithPrimary', + Sharded: 'Sharded', + Unknown: 'Unknown' +}; + +var ServerType = { + Standalone: 'Standalone', + Mongos: 'Mongos', + PossiblePrimary: 'PossiblePrimary', + RSPrimary: 'RSPrimary', + RSSecondary: 'RSSecondary', + RSArbiter: 'RSArbiter', + RSOther: 'RSOther', + RSGhost: 'RSGhost', + Unknown: 'Unknown' +}; + +var ReplSetState = function(options) { + options = options || {}; + // Add event listener + EventEmitter.call(this); + // Topology state + this.topologyType = TopologyType.ReplicaSetNoPrimary; + this.setName = options.setName; + + // Server set + this.set = {}; + + // Unpacked options + this.id = options.id; + this.setName = options.setName; + + // Replicaset logger + this.logger = options.logger || Logger('ReplSet', options); + + // Server selection index + this.index = 0; + // Acceptable latency + this.acceptableLatency = options.acceptableLatency || 15; + + // heartbeatFrequencyMS + this.heartbeatFrequencyMS = options.heartbeatFrequencyMS || 10000; + + // Server side + this.primary = null; + this.secondaries = []; + this.arbiters = []; + this.passives = []; + this.ghosts = []; + // Current unknown hosts + this.unknownServers = []; + // In set status + this.set = {}; + // Status + this.maxElectionId = null; + this.maxSetVersion = 0; + // Description of the Replicaset + this.replicasetDescription = { + topologyType: 'Unknown', + servers: [] + }; + + this.logicalSessionTimeoutMinutes = undefined; +}; + +inherits(ReplSetState, EventEmitter); + +ReplSetState.prototype.hasPrimaryAndSecondary = function() { + return this.primary != null && this.secondaries.length > 0; +}; + +ReplSetState.prototype.hasPrimaryOrSecondary = function() { + return this.hasPrimary() || this.hasSecondary(); +}; + +ReplSetState.prototype.hasPrimary = function() { + return this.primary != null; +}; + +ReplSetState.prototype.hasSecondary = function() { + return this.secondaries.length > 0; +}; + +ReplSetState.prototype.get = function(host) { + var servers = this.allServers(); + + for (var i = 0; i < servers.length; i++) { + if (servers[i].name.toLowerCase() === host.toLowerCase()) { + return servers[i]; + } + } + + return null; +}; + +ReplSetState.prototype.allServers = function(options) { + options = options || {}; + var servers = this.primary ? [this.primary] : []; + servers = servers.concat(this.secondaries); + if (!options.ignoreArbiters) servers = servers.concat(this.arbiters); + servers = servers.concat(this.passives); + return servers; +}; + +ReplSetState.prototype.destroy = function(options, callback) { + const serversToDestroy = this.secondaries + .concat(this.arbiters) + .concat(this.passives) + .concat(this.ghosts); + if (this.primary) serversToDestroy.push(this.primary); + + let serverCount = serversToDestroy.length; + const serverDestroyed = () => { + serverCount--; + if (serverCount > 0) { + return; + } + + // Clear out the complete state + this.secondaries = []; + this.arbiters = []; + this.passives = []; + this.ghosts = []; + this.unknownServers = []; + this.set = {}; + this.primary = null; + + // Emit the topology changed + emitTopologyDescriptionChanged(this); + + if (typeof callback === 'function') { + callback(null, null); + } + }; + + if (serverCount === 0) { + serverDestroyed(); + return; + } + + serversToDestroy.forEach(server => server.destroy(options, serverDestroyed)); +}; + +ReplSetState.prototype.remove = function(server, options) { + options = options || {}; + + // Get the server name and lowerCase it + var serverName = server.name.toLowerCase(); + + // Only remove if the current server is not connected + var servers = this.primary ? [this.primary] : []; + servers = servers.concat(this.secondaries); + servers = servers.concat(this.arbiters); + servers = servers.concat(this.passives); + + // Check if it's active and this is just a failed connection attempt + for (var i = 0; i < servers.length; i++) { + if ( + !options.force && + servers[i].equals(server) && + servers[i].isConnected && + servers[i].isConnected() + ) { + return; + } + } + + // If we have it in the set remove it + if (this.set[serverName]) { + this.set[serverName].type = ServerType.Unknown; + this.set[serverName].electionId = null; + this.set[serverName].setName = null; + this.set[serverName].setVersion = null; + } + + // Remove type + var removeType = null; + + // Remove from any lists + if (this.primary && this.primary.equals(server)) { + this.primary = null; + this.topologyType = TopologyType.ReplicaSetNoPrimary; + removeType = 'primary'; + } + + // Remove from any other server lists + removeType = removeFrom(server, this.secondaries) ? 'secondary' : removeType; + removeType = removeFrom(server, this.arbiters) ? 'arbiter' : removeType; + removeType = removeFrom(server, this.passives) ? 'secondary' : removeType; + removeFrom(server, this.ghosts); + removeFrom(server, this.unknownServers); + + // Push to unknownServers + this.unknownServers.push(serverName); + + // Do we have a removeType + if (removeType) { + this.emit('left', removeType, server); + } +}; + +const isArbiter = ismaster => ismaster.arbiterOnly && ismaster.setName; + +ReplSetState.prototype.update = function(server) { + var self = this; + // Get the current ismaster + var ismaster = server.lastIsMaster(); + + // Get the server name and lowerCase it + var serverName = server.name.toLowerCase(); + + // + // Add any hosts + // + if (ismaster) { + // Join all the possible new hosts + var hosts = Array.isArray(ismaster.hosts) ? ismaster.hosts : []; + hosts = hosts.concat(Array.isArray(ismaster.arbiters) ? ismaster.arbiters : []); + hosts = hosts.concat(Array.isArray(ismaster.passives) ? ismaster.passives : []); + hosts = hosts.map(function(s) { + return s.toLowerCase(); + }); + + // Add all hosts as unknownServers + for (var i = 0; i < hosts.length; i++) { + // Add to the list of unknown server + if ( + this.unknownServers.indexOf(hosts[i]) === -1 && + (!this.set[hosts[i]] || this.set[hosts[i]].type === ServerType.Unknown) + ) { + this.unknownServers.push(hosts[i].toLowerCase()); + } + + if (!this.set[hosts[i]]) { + this.set[hosts[i]] = { + type: ServerType.Unknown, + electionId: null, + setName: null, + setVersion: null + }; + } + } + } + + // + // Unknown server + // + if (!ismaster && !inList(ismaster, server, this.unknownServers)) { + self.set[serverName] = { + type: ServerType.Unknown, + setVersion: null, + electionId: null, + setName: null + }; + // Update set information about the server instance + self.set[serverName].type = ServerType.Unknown; + self.set[serverName].electionId = ismaster ? ismaster.electionId : ismaster; + self.set[serverName].setName = ismaster ? ismaster.setName : ismaster; + self.set[serverName].setVersion = ismaster ? ismaster.setVersion : ismaster; + + if (self.unknownServers.indexOf(server.name) === -1) { + self.unknownServers.push(serverName); + } + + // Set the topology + return false; + } + + // Update logicalSessionTimeoutMinutes + if (ismaster.logicalSessionTimeoutMinutes !== undefined && !isArbiter(ismaster)) { + if ( + self.logicalSessionTimeoutMinutes === undefined || + ismaster.logicalSessionTimeoutMinutes === null + ) { + self.logicalSessionTimeoutMinutes = ismaster.logicalSessionTimeoutMinutes; + } else { + self.logicalSessionTimeoutMinutes = Math.min( + self.logicalSessionTimeoutMinutes, + ismaster.logicalSessionTimeoutMinutes + ); + } + } + + // + // Is this a mongos + // + if (ismaster && ismaster.msg === 'isdbgrid') { + if (this.primary && this.primary.name === serverName) { + this.primary = null; + this.topologyType = TopologyType.ReplicaSetNoPrimary; + } + + return false; + } + + // A RSGhost instance + if (ismaster.isreplicaset) { + self.set[serverName] = { + type: ServerType.RSGhost, + setVersion: null, + electionId: null, + setName: ismaster.setName + }; + + if (this.primary && this.primary.name === serverName) { + this.primary = null; + } + + // Set the topology + this.topologyType = this.primary + ? TopologyType.ReplicaSetWithPrimary + : TopologyType.ReplicaSetNoPrimary; + if (ismaster.setName) this.setName = ismaster.setName; + + // Set the topology + return false; + } + + // A RSOther instance + if ( + (ismaster.setName && ismaster.hidden) || + (ismaster.setName && + !ismaster.ismaster && + !ismaster.secondary && + !ismaster.arbiterOnly && + !ismaster.passive) + ) { + self.set[serverName] = { + type: ServerType.RSOther, + setVersion: null, + electionId: null, + setName: ismaster.setName + }; + + // Set the topology + this.topologyType = this.primary + ? TopologyType.ReplicaSetWithPrimary + : TopologyType.ReplicaSetNoPrimary; + if (ismaster.setName) this.setName = ismaster.setName; + return false; + } + + // + // Standalone server, destroy and return + // + if (ismaster && ismaster.ismaster && !ismaster.setName) { + this.topologyType = this.primary ? TopologyType.ReplicaSetWithPrimary : TopologyType.Unknown; + this.remove(server, { force: true }); + return false; + } + + // + // Server in maintanance mode + // + if (ismaster && !ismaster.ismaster && !ismaster.secondary && !ismaster.arbiterOnly) { + this.remove(server, { force: true }); + return false; + } + + // + // If the .me field does not match the passed in server + // + if (ismaster.me && ismaster.me.toLowerCase() !== serverName) { + if (this.logger.isWarn()) { + this.logger.warn( + f( + 'the seedlist server was removed due to its address %s not matching its ismaster.me address %s', + server.name, + ismaster.me + ) + ); + } + + // Delete from the set + delete this.set[serverName]; + // Delete unknown servers + removeFrom(server, self.unknownServers); + + // Destroy the instance + server.destroy({ force: true }); + + // Set the type of topology we have + if (this.primary && !this.primary.equals(server)) { + this.topologyType = TopologyType.ReplicaSetWithPrimary; + } else { + this.topologyType = TopologyType.ReplicaSetNoPrimary; + } + + // + // We have a potential primary + // + if (!this.primary && ismaster.primary) { + this.set[ismaster.primary.toLowerCase()] = { + type: ServerType.PossiblePrimary, + setName: null, + electionId: null, + setVersion: null + }; + } + + return false; + } + + // + // Primary handling + // + if (!this.primary && ismaster.ismaster && ismaster.setName) { + var ismasterElectionId = server.lastIsMaster().electionId; + if (this.setName && this.setName !== ismaster.setName) { + this.topologyType = TopologyType.ReplicaSetNoPrimary; + return new MongoError( + f( + 'setName from ismaster does not match provided connection setName [%s] != [%s]', + ismaster.setName, + this.setName + ) + ); + } + + if (!this.maxElectionId && ismasterElectionId) { + this.maxElectionId = ismasterElectionId; + } else if (this.maxElectionId && ismasterElectionId) { + var result = compareObjectIds(this.maxElectionId, ismasterElectionId); + // Get the electionIds + var ismasterSetVersion = server.lastIsMaster().setVersion; + + if (result === 1) { + this.topologyType = TopologyType.ReplicaSetNoPrimary; + return false; + } else if (result === 0 && ismasterSetVersion) { + if (ismasterSetVersion < this.maxSetVersion) { + this.topologyType = TopologyType.ReplicaSetNoPrimary; + return false; + } + } + + this.maxSetVersion = ismasterSetVersion; + this.maxElectionId = ismasterElectionId; + } + + // Hande normalization of server names + var normalizedHosts = ismaster.hosts.map(function(x) { + return x.toLowerCase(); + }); + var locationIndex = normalizedHosts.indexOf(serverName); + + // Validate that the server exists in the host list + if (locationIndex !== -1) { + self.primary = server; + self.set[serverName] = { + type: ServerType.RSPrimary, + setVersion: ismaster.setVersion, + electionId: ismaster.electionId, + setName: ismaster.setName + }; + + // Set the topology + this.topologyType = TopologyType.ReplicaSetWithPrimary; + if (ismaster.setName) this.setName = ismaster.setName; + removeFrom(server, self.unknownServers); + removeFrom(server, self.secondaries); + removeFrom(server, self.passives); + self.emit('joined', 'primary', server); + } else { + this.topologyType = TopologyType.ReplicaSetNoPrimary; + } + + emitTopologyDescriptionChanged(self); + return true; + } else if (ismaster.ismaster && ismaster.setName) { + // Get the electionIds + var currentElectionId = self.set[self.primary.name.toLowerCase()].electionId; + var currentSetVersion = self.set[self.primary.name.toLowerCase()].setVersion; + var currentSetName = self.set[self.primary.name.toLowerCase()].setName; + ismasterElectionId = server.lastIsMaster().electionId; + ismasterSetVersion = server.lastIsMaster().setVersion; + var ismasterSetName = server.lastIsMaster().setName; + + // Is it the same server instance + if (this.primary.equals(server) && currentSetName === ismasterSetName) { + return false; + } + + // If we do not have the same rs name + if (currentSetName && currentSetName !== ismasterSetName) { + if (!this.primary.equals(server)) { + this.topologyType = TopologyType.ReplicaSetWithPrimary; + } else { + this.topologyType = TopologyType.ReplicaSetNoPrimary; + } + + return false; + } + + // Check if we need to replace the server + if (currentElectionId && ismasterElectionId) { + result = compareObjectIds(currentElectionId, ismasterElectionId); + + if (result === 1) { + return false; + } else if (result === 0 && currentSetVersion > ismasterSetVersion) { + return false; + } + } else if (!currentElectionId && ismasterElectionId && ismasterSetVersion) { + if (ismasterSetVersion < this.maxSetVersion) { + return false; + } + } + + if (!this.maxElectionId && ismasterElectionId) { + this.maxElectionId = ismasterElectionId; + } else if (this.maxElectionId && ismasterElectionId) { + result = compareObjectIds(this.maxElectionId, ismasterElectionId); + + if (result === 1) { + return false; + } else if (result === 0 && currentSetVersion && ismasterSetVersion) { + if (ismasterSetVersion < this.maxSetVersion) { + return false; + } + } else { + if (ismasterSetVersion < this.maxSetVersion) { + return false; + } + } + + this.maxElectionId = ismasterElectionId; + this.maxSetVersion = ismasterSetVersion; + } else { + this.maxSetVersion = ismasterSetVersion; + } + + // Modify the entry to unknown + self.set[self.primary.name.toLowerCase()] = { + type: ServerType.Unknown, + setVersion: null, + electionId: null, + setName: null + }; + + // Signal primary left + self.emit('left', 'primary', this.primary); + // Destroy the instance + self.primary.destroy({ force: true }); + // Set the new instance + self.primary = server; + // Set the set information + self.set[serverName] = { + type: ServerType.RSPrimary, + setVersion: ismaster.setVersion, + electionId: ismaster.electionId, + setName: ismaster.setName + }; + + // Set the topology + this.topologyType = TopologyType.ReplicaSetWithPrimary; + if (ismaster.setName) this.setName = ismaster.setName; + removeFrom(server, self.unknownServers); + removeFrom(server, self.secondaries); + removeFrom(server, self.passives); + self.emit('joined', 'primary', server); + emitTopologyDescriptionChanged(self); + return true; + } + + // A possible instance + if (!this.primary && ismaster.primary) { + self.set[ismaster.primary.toLowerCase()] = { + type: ServerType.PossiblePrimary, + setVersion: null, + electionId: null, + setName: null + }; + } + + // + // Secondary handling + // + if ( + ismaster.secondary && + ismaster.setName && + !inList(ismaster, server, this.secondaries) && + this.setName && + this.setName === ismaster.setName + ) { + addToList(self, ServerType.RSSecondary, ismaster, server, this.secondaries); + // Set the topology + this.topologyType = this.primary + ? TopologyType.ReplicaSetWithPrimary + : TopologyType.ReplicaSetNoPrimary; + if (ismaster.setName) this.setName = ismaster.setName; + removeFrom(server, self.unknownServers); + + // Remove primary + if (this.primary && this.primary.name.toLowerCase() === serverName) { + server.destroy({ force: true }); + this.primary = null; + self.emit('left', 'primary', server); + } + + // Emit secondary joined replicaset + self.emit('joined', 'secondary', server); + emitTopologyDescriptionChanged(self); + return true; + } + + // + // Arbiter handling + // + if ( + isArbiter(ismaster) && + !inList(ismaster, server, this.arbiters) && + this.setName && + this.setName === ismaster.setName + ) { + addToList(self, ServerType.RSArbiter, ismaster, server, this.arbiters); + // Set the topology + this.topologyType = this.primary + ? TopologyType.ReplicaSetWithPrimary + : TopologyType.ReplicaSetNoPrimary; + if (ismaster.setName) this.setName = ismaster.setName; + removeFrom(server, self.unknownServers); + self.emit('joined', 'arbiter', server); + emitTopologyDescriptionChanged(self); + return true; + } + + // + // Passive handling + // + if ( + ismaster.passive && + ismaster.setName && + !inList(ismaster, server, this.passives) && + this.setName && + this.setName === ismaster.setName + ) { + addToList(self, ServerType.RSSecondary, ismaster, server, this.passives); + // Set the topology + this.topologyType = this.primary + ? TopologyType.ReplicaSetWithPrimary + : TopologyType.ReplicaSetNoPrimary; + if (ismaster.setName) this.setName = ismaster.setName; + removeFrom(server, self.unknownServers); + + // Remove primary + if (this.primary && this.primary.name.toLowerCase() === serverName) { + server.destroy({ force: true }); + this.primary = null; + self.emit('left', 'primary', server); + } + + self.emit('joined', 'secondary', server); + emitTopologyDescriptionChanged(self); + return true; + } + + // + // Remove the primary + // + if (this.set[serverName] && this.set[serverName].type === ServerType.RSPrimary) { + self.emit('left', 'primary', this.primary); + this.primary.destroy({ force: true }); + this.primary = null; + this.topologyType = TopologyType.ReplicaSetNoPrimary; + return false; + } + + this.topologyType = this.primary + ? TopologyType.ReplicaSetWithPrimary + : TopologyType.ReplicaSetNoPrimary; + return false; +}; + +/** + * Recalculate single server max staleness + * @method + */ +ReplSetState.prototype.updateServerMaxStaleness = function(server, haInterval) { + // Locate the max secondary lastwrite + var max = 0; + // Go over all secondaries + for (var i = 0; i < this.secondaries.length; i++) { + max = Math.max(max, this.secondaries[i].lastWriteDate); + } + + // Perform this servers staleness calculation + if (server.ismaster.maxWireVersion >= 5 && server.ismaster.secondary && this.hasPrimary()) { + server.staleness = + server.lastUpdateTime - + server.lastWriteDate - + (this.primary.lastUpdateTime - this.primary.lastWriteDate) + + haInterval; + } else if (server.ismaster.maxWireVersion >= 5 && server.ismaster.secondary) { + server.staleness = max - server.lastWriteDate + haInterval; + } +}; + +/** + * Recalculate all the staleness values for secodaries + * @method + */ +ReplSetState.prototype.updateSecondariesMaxStaleness = function(haInterval) { + for (var i = 0; i < this.secondaries.length; i++) { + this.updateServerMaxStaleness(this.secondaries[i], haInterval); + } +}; + +/** + * Pick a server by the passed in ReadPreference + * @method + * @param {ReadPreference} readPreference The ReadPreference instance to use + */ +ReplSetState.prototype.pickServer = function(readPreference) { + // If no read Preference set to primary by default + readPreference = readPreference || ReadPreference.primary; + + // maxStalenessSeconds is not allowed with a primary read + if (readPreference.preference === 'primary' && readPreference.maxStalenessSeconds != null) { + return new MongoError('primary readPreference incompatible with maxStalenessSeconds'); + } + + // Check if we have any non compatible servers for maxStalenessSeconds + var allservers = this.primary ? [this.primary] : []; + allservers = allservers.concat(this.secondaries); + + // Does any of the servers not support the right wire protocol version + // for maxStalenessSeconds when maxStalenessSeconds specified on readPreference. Then error out + if (readPreference.maxStalenessSeconds != null) { + for (var i = 0; i < allservers.length; i++) { + if (allservers[i].ismaster.maxWireVersion < 5) { + return new MongoError( + 'maxStalenessSeconds not supported by at least one of the replicaset members' + ); + } + } + } + + // Do we have the nearest readPreference + if (readPreference.preference === 'nearest' && readPreference.maxStalenessSeconds == null) { + return pickNearest(this, readPreference); + } else if ( + readPreference.preference === 'nearest' && + readPreference.maxStalenessSeconds != null + ) { + return pickNearestMaxStalenessSeconds(this, readPreference); + } + + // Get all the secondaries + var secondaries = this.secondaries; + + // Check if we can satisfy and of the basic read Preferences + if (readPreference.equals(ReadPreference.secondary) && secondaries.length === 0) { + return new MongoError('no secondary server available'); + } + + if ( + readPreference.equals(ReadPreference.secondaryPreferred) && + secondaries.length === 0 && + this.primary == null + ) { + return new MongoError('no secondary or primary server available'); + } + + if (readPreference.equals(ReadPreference.primary) && this.primary == null) { + return new MongoError('no primary server available'); + } + + // Secondary preferred or just secondaries + if ( + readPreference.equals(ReadPreference.secondaryPreferred) || + readPreference.equals(ReadPreference.secondary) + ) { + if (secondaries.length > 0 && readPreference.maxStalenessSeconds == null) { + // Pick nearest of any other servers available + var server = pickNearest(this, readPreference); + // No server in the window return primary + if (server) { + return server; + } + } else if (secondaries.length > 0 && readPreference.maxStalenessSeconds != null) { + // Pick nearest of any other servers available + server = pickNearestMaxStalenessSeconds(this, readPreference); + // No server in the window return primary + if (server) { + return server; + } + } + + if (readPreference.equals(ReadPreference.secondaryPreferred)) { + return this.primary; + } + + return null; + } + + // Primary preferred + if (readPreference.equals(ReadPreference.primaryPreferred)) { + server = null; + + // We prefer the primary if it's available + if (this.primary) { + return this.primary; + } + + // Pick a secondary + if (secondaries.length > 0 && readPreference.maxStalenessSeconds == null) { + server = pickNearest(this, readPreference); + } else if (secondaries.length > 0 && readPreference.maxStalenessSeconds != null) { + server = pickNearestMaxStalenessSeconds(this, readPreference); + } + + // Did we find a server + if (server) return server; + } + + // Return the primary + return this.primary; +}; + +// +// Filter serves by tags +var filterByTags = function(readPreference, servers) { + if (readPreference.tags == null) return servers; + var filteredServers = []; + var tagsArray = Array.isArray(readPreference.tags) ? readPreference.tags : [readPreference.tags]; + + // Iterate over the tags + for (var j = 0; j < tagsArray.length; j++) { + var tags = tagsArray[j]; + + // Iterate over all the servers + for (var i = 0; i < servers.length; i++) { + var serverTag = servers[i].lastIsMaster().tags || {}; + + // Did we find the a matching server + var found = true; + // Check if the server is valid + for (var name in tags) { + if (serverTag[name] !== tags[name]) { + found = false; + } + } + + // Add to candidate list + if (found) { + filteredServers.push(servers[i]); + } + } + } + + // Returned filtered servers + return filteredServers; +}; + +function pickNearestMaxStalenessSeconds(self, readPreference) { + // Only get primary and secondaries as seeds + var servers = []; + + // Get the maxStalenessMS + var maxStalenessMS = readPreference.maxStalenessSeconds * 1000; + + // Check if the maxStalenessMS > 90 seconds + if (maxStalenessMS < 90 * 1000) { + return new MongoError('maxStalenessSeconds must be set to at least 90 seconds'); + } + + // Add primary to list if not a secondary read preference + if ( + self.primary && + readPreference.preference !== 'secondary' && + readPreference.preference !== 'secondaryPreferred' + ) { + servers.push(self.primary); + } + + // Add all the secondaries + for (var i = 0; i < self.secondaries.length; i++) { + servers.push(self.secondaries[i]); + } + + // If we have a secondaryPreferred readPreference and no server add the primary + if (self.primary && servers.length === 0 && readPreference.preference !== 'secondaryPreferred') { + servers.push(self.primary); + } + + // Filter by tags + servers = filterByTags(readPreference, servers); + + // Filter by latency + servers = servers.filter(function(s) { + return s.staleness <= maxStalenessMS; + }); + + // Sort by time + servers.sort(function(a, b) { + return a.lastIsMasterMS - b.lastIsMasterMS; + }); + + // No servers, default to primary + if (servers.length === 0) { + return null; + } + + // Ensure index does not overflow the number of available servers + self.index = self.index % servers.length; + + // Get the server + var server = servers[self.index]; + // Add to the index + self.index = self.index + 1; + // Return the first server of the sorted and filtered list + return server; +} + +function pickNearest(self, readPreference) { + // Only get primary and secondaries as seeds + var servers = []; + + // Add primary to list if not a secondary read preference + if ( + self.primary && + readPreference.preference !== 'secondary' && + readPreference.preference !== 'secondaryPreferred' + ) { + servers.push(self.primary); + } + + // Add all the secondaries + for (var i = 0; i < self.secondaries.length; i++) { + servers.push(self.secondaries[i]); + } + + // If we have a secondaryPreferred readPreference and no server add the primary + if (servers.length === 0 && self.primary && readPreference.preference !== 'secondaryPreferred') { + servers.push(self.primary); + } + + // Filter by tags + servers = filterByTags(readPreference, servers); + + // Sort by time + servers.sort(function(a, b) { + return a.lastIsMasterMS - b.lastIsMasterMS; + }); + + // Locate lowest time (picked servers are lowest time + acceptable Latency margin) + var lowest = servers.length > 0 ? servers[0].lastIsMasterMS : 0; + + // Filter by latency + servers = servers.filter(function(s) { + return s.lastIsMasterMS <= lowest + self.acceptableLatency; + }); + + // No servers, default to primary + if (servers.length === 0) { + return null; + } + + // Ensure index does not overflow the number of available servers + self.index = self.index % servers.length; + // Get the server + var server = servers[self.index]; + // Add to the index + self.index = self.index + 1; + // Return the first server of the sorted and filtered list + return server; +} + +function inList(ismaster, server, list) { + for (var i = 0; i < list.length; i++) { + if (list[i] && list[i].name && list[i].name.toLowerCase() === server.name.toLowerCase()) + return true; + } + + return false; +} + +function addToList(self, type, ismaster, server, list) { + var serverName = server.name.toLowerCase(); + // Update set information about the server instance + self.set[serverName].type = type; + self.set[serverName].electionId = ismaster ? ismaster.electionId : ismaster; + self.set[serverName].setName = ismaster ? ismaster.setName : ismaster; + self.set[serverName].setVersion = ismaster ? ismaster.setVersion : ismaster; + // Add to the list + list.push(server); +} + +function compareObjectIds(id1, id2) { + var a = Buffer.from(id1.toHexString(), 'hex'); + var b = Buffer.from(id2.toHexString(), 'hex'); + + if (a === b) { + return 0; + } + + if (typeof Buffer.compare === 'function') { + return Buffer.compare(a, b); + } + + var x = a.length; + var y = b.length; + var len = Math.min(x, y); + + for (var i = 0; i < len; i++) { + if (a[i] !== b[i]) { + break; + } + } + + if (i !== len) { + x = a[i]; + y = b[i]; + } + + return x < y ? -1 : y < x ? 1 : 0; +} + +function removeFrom(server, list) { + for (var i = 0; i < list.length; i++) { + if (list[i].equals && list[i].equals(server)) { + list.splice(i, 1); + return true; + } else if (typeof list[i] === 'string' && list[i].toLowerCase() === server.name.toLowerCase()) { + list.splice(i, 1); + return true; + } + } + + return false; +} + +function emitTopologyDescriptionChanged(self) { + if (self.listeners('topologyDescriptionChanged').length > 0) { + var topology = 'Unknown'; + var setName = self.setName; + + if (self.hasPrimaryAndSecondary()) { + topology = 'ReplicaSetWithPrimary'; + } else if (!self.hasPrimary() && self.hasSecondary()) { + topology = 'ReplicaSetNoPrimary'; + } + + // Generate description + var description = { + topologyType: topology, + setName: setName, + servers: [] + }; + + // Add the primary to the list + if (self.hasPrimary()) { + var desc = self.primary.getDescription(); + desc.type = 'RSPrimary'; + description.servers.push(desc); + } + + // Add all the secondaries + description.servers = description.servers.concat( + self.secondaries.map(function(x) { + var description = x.getDescription(); + description.type = 'RSSecondary'; + return description; + }) + ); + + // Add all the arbiters + description.servers = description.servers.concat( + self.arbiters.map(function(x) { + var description = x.getDescription(); + description.type = 'RSArbiter'; + return description; + }) + ); + + // Add all the passives + description.servers = description.servers.concat( + self.passives.map(function(x) { + var description = x.getDescription(); + description.type = 'RSSecondary'; + return description; + }) + ); + + // Get the diff + var diffResult = diff(self.replicasetDescription, description); + + // Create the result + var result = { + topologyId: self.id, + previousDescription: self.replicasetDescription, + newDescription: description, + diff: diffResult + }; + + // Emit the topologyDescription change + // if(diffResult.servers.length > 0) { + self.emit('topologyDescriptionChanged', result); + // } + + // Set the new description + self.replicasetDescription = description; + } +} + +module.exports = ReplSetState; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/topologies/server.js b/scripts/2.5/node_modules/mongodb/lib/core/topologies/server.js new file mode 100644 index 00000000..c2f86421 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/core/topologies/server.js @@ -0,0 +1,989 @@ +'use strict'; + +var inherits = require('util').inherits, + f = require('util').format, + EventEmitter = require('events').EventEmitter, + ReadPreference = require('./read_preference'), + Logger = require('../connection/logger'), + debugOptions = require('../connection/utils').debugOptions, + retrieveBSON = require('../connection/utils').retrieveBSON, + Pool = require('../connection/pool'), + MongoError = require('../error').MongoError, + MongoNetworkError = require('../error').MongoNetworkError, + wireProtocol = require('../wireprotocol'), + CoreCursor = require('../cursor').CoreCursor, + sdam = require('./shared'), + createClientInfo = require('./shared').createClientInfo, + createCompressionInfo = require('./shared').createCompressionInfo, + resolveClusterTime = require('./shared').resolveClusterTime, + SessionMixins = require('./shared').SessionMixins, + relayEvents = require('../utils').relayEvents; + +const collationNotSupported = require('../utils').collationNotSupported; + +// Used for filtering out fields for loggin +var debugFields = [ + 'reconnect', + 'reconnectTries', + 'reconnectInterval', + 'emitError', + 'cursorFactory', + 'host', + 'port', + 'size', + 'keepAlive', + 'keepAliveInitialDelay', + 'noDelay', + 'connectionTimeout', + 'checkServerIdentity', + 'socketTimeout', + 'ssl', + 'ca', + 'crl', + 'cert', + 'key', + 'rejectUnauthorized', + 'promoteLongs', + 'promoteValues', + 'promoteBuffers', + 'servername' +]; + +// Server instance id +var id = 0; +var serverAccounting = false; +var servers = {}; +var BSON = retrieveBSON(); + +/** + * Creates a new Server instance + * @class + * @param {boolean} [options.reconnect=true] Server will attempt to reconnect on loss of connection + * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times + * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries + * @param {number} [options.monitoring=true] Enable the server state monitoring (calling ismaster at monitoringInterval) + * @param {number} [options.monitoringInterval=5000] The interval of calling ismaster when monitoring is enabled. + * @param {Cursor} [options.cursorFactory=Cursor] The cursor factory class used for all query cursors + * @param {string} options.host The server host + * @param {number} options.port The server port + * @param {number} [options.size=5] Server connection pool size + * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled + * @param {number} [options.keepAliveInitialDelay=300000] Initial delay before TCP keep alive enabled + * @param {boolean} [options.noDelay=true] TCP Connection no delay + * @param {number} [options.connectionTimeout=30000] TCP Connection timeout setting + * @param {number} [options.socketTimeout=360000] TCP Socket timeout setting + * @param {boolean} [options.ssl=false] Use SSL for connection + * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. + * @param {Buffer} [options.ca] SSL Certificate store binary buffer + * @param {Buffer} [options.crl] SSL Certificate revocation store binary buffer + * @param {Buffer} [options.cert] SSL Certificate binary buffer + * @param {Buffer} [options.key] SSL Key file binary buffer + * @param {string} [options.passphrase] SSL Certificate pass phrase + * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates + * @param {string} [options.servername=null] String containing the server name requested via TLS SNI. + * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits + * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. + * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. + * @param {string} [options.appname=null] Application name, passed in on ismaster call and logged in mongod server logs. Maximum size 128 bytes. + * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. + * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology + * @return {Server} A cursor instance + * @fires Server#connect + * @fires Server#close + * @fires Server#error + * @fires Server#timeout + * @fires Server#parseError + * @fires Server#reconnect + * @fires Server#reconnectFailed + * @fires Server#serverHeartbeatStarted + * @fires Server#serverHeartbeatSucceeded + * @fires Server#serverHeartbeatFailed + * @fires Server#topologyOpening + * @fires Server#topologyClosed + * @fires Server#topologyDescriptionChanged + * @property {string} type the topology type. + * @property {string} parserType the parser type used (c++ or js). + */ +var Server = function(options) { + options = options || {}; + + // Add event listener + EventEmitter.call(this); + + // Server instance id + this.id = id++; + + // Internal state + this.s = { + // Options + options: options, + // Logger + logger: Logger('Server', options), + // Factory overrides + Cursor: options.cursorFactory || CoreCursor, + // BSON instance + bson: + options.bson || + new BSON([ + BSON.Binary, + BSON.Code, + BSON.DBRef, + BSON.Decimal128, + BSON.Double, + BSON.Int32, + BSON.Long, + BSON.Map, + BSON.MaxKey, + BSON.MinKey, + BSON.ObjectId, + BSON.BSONRegExp, + BSON.Symbol, + BSON.Timestamp + ]), + // Pool + pool: null, + // Disconnect handler + disconnectHandler: options.disconnectHandler, + // Monitor thread (keeps the connection alive) + monitoring: typeof options.monitoring === 'boolean' ? options.monitoring : true, + // Is the server in a topology + inTopology: !!options.parent, + // Monitoring timeout + monitoringInterval: + typeof options.monitoringInterval === 'number' ? options.monitoringInterval : 5000, + // Topology id + topologyId: -1, + compression: { compressors: createCompressionInfo(options) }, + // Optional parent topology + parent: options.parent + }; + + // If this is a single deployment we need to track the clusterTime here + if (!this.s.parent) { + this.s.clusterTime = null; + } + + // Curent ismaster + this.ismaster = null; + // Current ping time + this.lastIsMasterMS = -1; + // The monitoringProcessId + this.monitoringProcessId = null; + // Initial connection + this.initialConnect = true; + // Default type + this._type = 'server'; + // Set the client info + this.clientInfo = createClientInfo(options); + + // Max Stalleness values + // last time we updated the ismaster state + this.lastUpdateTime = 0; + // Last write time + this.lastWriteDate = 0; + // Stalleness + this.staleness = 0; +}; + +inherits(Server, EventEmitter); +Object.assign(Server.prototype, SessionMixins); + +Object.defineProperty(Server.prototype, 'type', { + enumerable: true, + get: function() { + return this._type; + } +}); + +Object.defineProperty(Server.prototype, 'parserType', { + enumerable: true, + get: function() { + return BSON.native ? 'c++' : 'js'; + } +}); + +Object.defineProperty(Server.prototype, 'logicalSessionTimeoutMinutes', { + enumerable: true, + get: function() { + if (!this.ismaster) return null; + return this.ismaster.logicalSessionTimeoutMinutes || null; + } +}); + +// In single server deployments we track the clusterTime directly on the topology, however +// in Mongos and ReplSet deployments we instead need to delegate the clusterTime up to the +// tracking objects so we can ensure we are gossiping the maximum time received from the +// server. +Object.defineProperty(Server.prototype, 'clusterTime', { + enumerable: true, + set: function(clusterTime) { + const settings = this.s.parent ? this.s.parent : this.s; + resolveClusterTime(settings, clusterTime); + }, + get: function() { + const settings = this.s.parent ? this.s.parent : this.s; + return settings.clusterTime || null; + } +}); + +Server.enableServerAccounting = function() { + serverAccounting = true; + servers = {}; +}; + +Server.disableServerAccounting = function() { + serverAccounting = false; +}; + +Server.servers = function() { + return servers; +}; + +Object.defineProperty(Server.prototype, 'name', { + enumerable: true, + get: function() { + return this.s.options.host + ':' + this.s.options.port; + } +}); + +function disconnectHandler(self, type, ns, cmd, options, callback) { + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if ( + !self.s.pool.isConnected() && + self.s.options.reconnect && + self.s.disconnectHandler != null && + !options.monitoring + ) { + self.s.disconnectHandler.add(type, ns, cmd, options, callback); + return true; + } + + // If we have no connection error + if (!self.s.pool.isConnected()) { + callback(new MongoError(f('no connection available to server %s', self.name))); + return true; + } +} + +function monitoringProcess(self) { + return function() { + // Pool was destroyed do not continue process + if (self.s.pool.isDestroyed()) return; + // Emit monitoring Process event + self.emit('monitoring', self); + // Perform ismaster call + // Get start time + var start = new Date().getTime(); + + // Execute the ismaster query + self.command( + 'admin.$cmd', + { ismaster: true }, + { + socketTimeout: + typeof self.s.options.connectionTimeout !== 'number' + ? 2000 + : self.s.options.connectionTimeout, + monitoring: true + }, + (err, result) => { + // Set initial lastIsMasterMS + self.lastIsMasterMS = new Date().getTime() - start; + if (self.s.pool.isDestroyed()) return; + // Update the ismaster view if we have a result + if (result) { + self.ismaster = result.result; + } + // Re-schedule the monitoring process + self.monitoringProcessId = setTimeout(monitoringProcess(self), self.s.monitoringInterval); + } + ); + }; +} + +var eventHandler = function(self, event) { + return function(err, conn) { + // Log information of received information if in info mode + if (self.s.logger.isInfo()) { + var object = err instanceof MongoError ? JSON.stringify(err) : {}; + self.s.logger.info( + f('server %s fired event %s out with message %s', self.name, event, object) + ); + } + + // Handle connect event + if (event === 'connect') { + self.initialConnect = false; + self.ismaster = conn.ismaster; + self.lastIsMasterMS = conn.lastIsMasterMS; + if (conn.agreedCompressor) { + self.s.pool.options.agreedCompressor = conn.agreedCompressor; + } + + if (conn.zlibCompressionLevel) { + self.s.pool.options.zlibCompressionLevel = conn.zlibCompressionLevel; + } + + if (conn.ismaster.$clusterTime) { + const $clusterTime = conn.ismaster.$clusterTime; + self.clusterTime = $clusterTime; + } + + // It's a proxy change the type so + // the wireprotocol will send $readPreference + if (self.ismaster.msg === 'isdbgrid') { + self._type = 'mongos'; + } + + // Have we defined self monitoring + if (self.s.monitoring) { + self.monitoringProcessId = setTimeout(monitoringProcess(self), self.s.monitoringInterval); + } + + // Emit server description changed if something listening + sdam.emitServerDescriptionChanged(self, { + address: self.name, + arbiters: [], + hosts: [], + passives: [], + type: sdam.getTopologyType(self) + }); + + if (!self.s.inTopology) { + // Emit topology description changed if something listening + sdam.emitTopologyDescriptionChanged(self, { + topologyType: 'Single', + servers: [ + { + address: self.name, + arbiters: [], + hosts: [], + passives: [], + type: sdam.getTopologyType(self) + } + ] + }); + } + + // Log the ismaster if available + if (self.s.logger.isInfo()) { + self.s.logger.info( + f('server %s connected with ismaster [%s]', self.name, JSON.stringify(self.ismaster)) + ); + } + + // Emit connect + self.emit('connect', self); + } else if ( + event === 'error' || + event === 'parseError' || + event === 'close' || + event === 'timeout' || + event === 'reconnect' || + event === 'attemptReconnect' || + 'reconnectFailed' + ) { + // Remove server instance from accounting + if ( + serverAccounting && + ['close', 'timeout', 'error', 'parseError', 'reconnectFailed'].indexOf(event) !== -1 + ) { + // Emit toplogy opening event if not in topology + if (!self.s.inTopology) { + self.emit('topologyOpening', { topologyId: self.id }); + } + + delete servers[self.id]; + } + + if (event === 'close') { + // Closing emits a server description changed event going to unknown. + sdam.emitServerDescriptionChanged(self, { + address: self.name, + arbiters: [], + hosts: [], + passives: [], + type: 'Unknown' + }); + } + + // Reconnect failed return error + if (event === 'reconnectFailed') { + self.emit('reconnectFailed', err); + // Emit error if any listeners + if (self.listeners('error').length > 0) { + self.emit('error', err); + } + // Terminate + return; + } + + // On first connect fail + if ( + ['disconnected', 'connecting'].indexOf(self.s.pool.state) !== -1 && + self.initialConnect && + ['close', 'timeout', 'error', 'parseError'].indexOf(event) !== -1 + ) { + self.initialConnect = false; + return self.emit( + 'error', + new MongoNetworkError( + f('failed to connect to server [%s] on first connect [%s]', self.name, err) + ) + ); + } + + // Reconnect event, emit the server + if (event === 'reconnect') { + // Reconnecting emits a server description changed event going from unknown to the + // current server type. + sdam.emitServerDescriptionChanged(self, { + address: self.name, + arbiters: [], + hosts: [], + passives: [], + type: sdam.getTopologyType(self) + }); + return self.emit(event, self); + } + + // Emit the event + self.emit(event, err); + } + }; +}; + +/** + * Initiate server connect + */ +Server.prototype.connect = function(options) { + var self = this; + options = options || {}; + + // Set the connections + if (serverAccounting) servers[this.id] = this; + + // Do not allow connect to be called on anything that's not disconnected + if (self.s.pool && !self.s.pool.isDisconnected() && !self.s.pool.isDestroyed()) { + throw new MongoError(f('server instance in invalid state %s', self.s.pool.state)); + } + + // Create a pool + self.s.pool = new Pool(this, Object.assign(self.s.options, options, { bson: this.s.bson })); + + // Set up listeners + self.s.pool.on('close', eventHandler(self, 'close')); + self.s.pool.on('error', eventHandler(self, 'error')); + self.s.pool.on('timeout', eventHandler(self, 'timeout')); + self.s.pool.on('parseError', eventHandler(self, 'parseError')); + self.s.pool.on('connect', eventHandler(self, 'connect')); + self.s.pool.on('reconnect', eventHandler(self, 'reconnect')); + self.s.pool.on('reconnectFailed', eventHandler(self, 'reconnectFailed')); + + // Set up listeners for command monitoring + relayEvents(self.s.pool, self, ['commandStarted', 'commandSucceeded', 'commandFailed']); + + // Emit toplogy opening event if not in topology + if (!self.s.inTopology) { + this.emit('topologyOpening', { topologyId: self.id }); + } + + // Emit opening server event + self.emit('serverOpening', { + topologyId: self.s.topologyId !== -1 ? self.s.topologyId : self.id, + address: self.name + }); + + self.s.pool.connect(); +}; + +/** + * Authenticate the topology. + * @method + * @param {MongoCredentials} credentials The credentials for authentication we are using + * @param {authResultCallback} callback A callback function + */ +Server.prototype.auth = function(credentials, callback) { + if (typeof callback === 'function') callback(null, null); +}; + +/** + * Get the server description + * @method + * @return {object} + */ +Server.prototype.getDescription = function() { + var ismaster = this.ismaster || {}; + var description = { + type: sdam.getTopologyType(this), + address: this.name + }; + + // Add fields if available + if (ismaster.hosts) description.hosts = ismaster.hosts; + if (ismaster.arbiters) description.arbiters = ismaster.arbiters; + if (ismaster.passives) description.passives = ismaster.passives; + if (ismaster.setName) description.setName = ismaster.setName; + return description; +}; + +/** + * Returns the last known ismaster document for this server + * @method + * @return {object} + */ +Server.prototype.lastIsMaster = function() { + return this.ismaster; +}; + +/** + * Unref all connections belong to this server + * @method + */ +Server.prototype.unref = function() { + this.s.pool.unref(); +}; + +/** + * Figure out if the server is connected + * @method + * @return {boolean} + */ +Server.prototype.isConnected = function() { + if (!this.s.pool) return false; + return this.s.pool.isConnected(); +}; + +/** + * Figure out if the server instance was destroyed by calling destroy + * @method + * @return {boolean} + */ +Server.prototype.isDestroyed = function() { + if (!this.s.pool) return false; + return this.s.pool.isDestroyed(); +}; + +function basicWriteValidations(self) { + if (!self.s.pool) return new MongoError('server instance is not connected'); + if (self.s.pool.isDestroyed()) return new MongoError('server instance pool was destroyed'); +} + +function basicReadValidations(self, options) { + basicWriteValidations(self, options); + + if (options.readPreference && !(options.readPreference instanceof ReadPreference)) { + throw new Error('readPreference must be an instance of ReadPreference'); + } +} + +/** + * Execute a command + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object} cmd The command hash + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.checkKeys=false] Specify if the bson parser should validate keys. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {Boolean} [options.fullResult=false] Return the full envelope instead of just the result document. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {opResultCallback} callback A callback function + */ +Server.prototype.command = function(ns, cmd, options, callback) { + var self = this; + if (typeof options === 'function') { + (callback = options), (options = {}), (options = options || {}); + } + + var result = basicReadValidations(self, options); + if (result) return callback(result); + + // Clone the options + options = Object.assign({}, options, { wireProtocolCommand: false }); + + // Debug log + if (self.s.logger.isDebug()) + self.s.logger.debug( + f( + 'executing command [%s] against %s', + JSON.stringify({ + ns: ns, + cmd: cmd, + options: debugOptions(debugFields, options) + }), + self.name + ) + ); + + // If we are not connected or have a disconnectHandler specified + if (disconnectHandler(self, 'command', ns, cmd, options, callback)) return; + + // error if collation not supported + if (collationNotSupported(this, cmd)) { + return callback(new MongoError(`server ${this.name} does not support collation`)); + } + + wireProtocol.command(self, ns, cmd, options, callback); +}; + +/** + * Execute a query against the server + * + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object} cmd The command document for the query + * @param {object} options Optional settings + * @param {function} callback + */ +Server.prototype.query = function(ns, cmd, cursorState, options, callback) { + wireProtocol.query(this, ns, cmd, cursorState, options, callback); +}; + +/** + * Execute a `getMore` against the server + * + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object} cursorState State data associated with the cursor calling this method + * @param {object} options Optional settings + * @param {function} callback + */ +Server.prototype.getMore = function(ns, cursorState, batchSize, options, callback) { + wireProtocol.getMore(this, ns, cursorState, batchSize, options, callback); +}; + +/** + * Execute a `killCursors` command against the server + * + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object} cursorState State data associated with the cursor calling this method + * @param {function} callback + */ +Server.prototype.killCursors = function(ns, cursorState, callback) { + wireProtocol.killCursors(this, ns, cursorState, callback); +}; + +/** + * Insert one or more documents + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of documents to insert + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {opResultCallback} callback A callback function + */ +Server.prototype.insert = function(ns, ops, options, callback) { + var self = this; + if (typeof options === 'function') { + (callback = options), (options = {}), (options = options || {}); + } + + var result = basicWriteValidations(self, options); + if (result) return callback(result); + + // If we are not connected or have a disconnectHandler specified + if (disconnectHandler(self, 'insert', ns, ops, options, callback)) return; + + // Setup the docs as an array + ops = Array.isArray(ops) ? ops : [ops]; + + // Execute write + return wireProtocol.insert(self, ns, ops, options, callback); +}; + +/** + * Perform one or more update operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of updates + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {opResultCallback} callback A callback function + */ +Server.prototype.update = function(ns, ops, options, callback) { + var self = this; + if (typeof options === 'function') { + (callback = options), (options = {}), (options = options || {}); + } + + var result = basicWriteValidations(self, options); + if (result) return callback(result); + + // If we are not connected or have a disconnectHandler specified + if (disconnectHandler(self, 'update', ns, ops, options, callback)) return; + + // error if collation not supported + if (collationNotSupported(this, options)) { + return callback(new MongoError(`server ${this.name} does not support collation`)); + } + + // Setup the docs as an array + ops = Array.isArray(ops) ? ops : [ops]; + // Execute write + return wireProtocol.update(self, ns, ops, options, callback); +}; + +/** + * Perform one or more remove operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of removes + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {opResultCallback} callback A callback function + */ +Server.prototype.remove = function(ns, ops, options, callback) { + var self = this; + if (typeof options === 'function') { + (callback = options), (options = {}), (options = options || {}); + } + + var result = basicWriteValidations(self, options); + if (result) return callback(result); + + // If we are not connected or have a disconnectHandler specified + if (disconnectHandler(self, 'remove', ns, ops, options, callback)) return; + + // error if collation not supported + if (collationNotSupported(this, options)) { + return callback(new MongoError(`server ${this.name} does not support collation`)); + } + + // Setup the docs as an array + ops = Array.isArray(ops) ? ops : [ops]; + // Execute write + return wireProtocol.remove(self, ns, ops, options, callback); +}; + +/** + * Get a new cursor + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object|Long} cmd Can be either a command returning a cursor or a cursorId + * @param {object} [options] Options for the cursor + * @param {object} [options.batchSize=0] Batchsize for the operation + * @param {array} [options.documents=[]] Initial documents list for cursor + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {object} [options.topology] The internal topology of the created cursor + * @returns {Cursor} + */ +Server.prototype.cursor = function(ns, cmd, options) { + options = options || {}; + const topology = options.topology || this; + + // Set up final cursor type + var FinalCursor = options.cursorFactory || this.s.Cursor; + + // Return the cursor + return new FinalCursor(topology, ns, cmd, options); +}; + +/** + * Compare two server instances + * @method + * @param {Server} server Server to compare equality against + * @return {boolean} + */ +Server.prototype.equals = function(server) { + if (typeof server === 'string') return this.name.toLowerCase() === server.toLowerCase(); + if (server.name) return this.name.toLowerCase() === server.name.toLowerCase(); + return false; +}; + +/** + * All raw connections + * @method + * @return {Connection[]} + */ +Server.prototype.connections = function() { + return this.s.pool.allConnections(); +}; + +/** + * Selects a server + * @method + * @param {function} selector Unused + * @param {ReadPreference} [options.readPreference] Unused + * @param {ClientSession} [options.session] Unused + * @return {Server} + */ +Server.prototype.selectServer = function(selector, options, callback) { + if (typeof selector === 'function' && typeof callback === 'undefined') + (callback = selector), (selector = undefined), (options = {}); + if (typeof options === 'function') + (callback = options), (options = selector), (selector = undefined); + + callback(null, this); +}; + +var listeners = ['close', 'error', 'timeout', 'parseError', 'connect']; + +/** + * Destroy the server connection + * @method + * @param {boolean} [options.emitClose=false] Emit close event on destroy + * @param {boolean} [options.emitDestroy=false] Emit destroy event on destroy + * @param {boolean} [options.force=false] Force destroy the pool + */ +Server.prototype.destroy = function(options, callback) { + if (this._destroyed) { + if (typeof callback === 'function') callback(null, null); + return; + } + + if (typeof options === 'function') { + callback = options; + options = {}; + } + + options = options || {}; + var self = this; + + // Set the connections + if (serverAccounting) delete servers[this.id]; + + // Destroy the monitoring process if any + if (this.monitoringProcessId) { + clearTimeout(this.monitoringProcessId); + } + + // No pool, return + if (!self.s.pool) { + this._destroyed = true; + if (typeof callback === 'function') callback(null, null); + return; + } + + // Emit close event + if (options.emitClose) { + self.emit('close', self); + } + + // Emit destroy event + if (options.emitDestroy) { + self.emit('destroy', self); + } + + // Remove all listeners + listeners.forEach(function(event) { + self.s.pool.removeAllListeners(event); + }); + + // Emit opening server event + if (self.listeners('serverClosed').length > 0) + self.emit('serverClosed', { + topologyId: self.s.topologyId !== -1 ? self.s.topologyId : self.id, + address: self.name + }); + + // Emit toplogy opening event if not in topology + if (self.listeners('topologyClosed').length > 0 && !self.s.inTopology) { + self.emit('topologyClosed', { topologyId: self.id }); + } + + if (self.s.logger.isDebug()) { + self.s.logger.debug(f('destroy called on server %s', self.name)); + } + + // Destroy the pool + this.s.pool.destroy(options.force, callback); + this._destroyed = true; +}; + +/** + * A server connect event, used to verify that the connection is up and running + * + * @event Server#connect + * @type {Server} + */ + +/** + * A server reconnect event, used to verify that the server topology has reconnected + * + * @event Server#reconnect + * @type {Server} + */ + +/** + * A server opening SDAM monitoring event + * + * @event Server#serverOpening + * @type {object} + */ + +/** + * A server closed SDAM monitoring event + * + * @event Server#serverClosed + * @type {object} + */ + +/** + * A server description SDAM change monitoring event + * + * @event Server#serverDescriptionChanged + * @type {object} + */ + +/** + * A topology open SDAM event + * + * @event Server#topologyOpening + * @type {object} + */ + +/** + * A topology closed SDAM event + * + * @event Server#topologyClosed + * @type {object} + */ + +/** + * A topology structure SDAM change event + * + * @event Server#topologyDescriptionChanged + * @type {object} + */ + +/** + * Server reconnect failed + * + * @event Server#reconnectFailed + * @type {Error} + */ + +/** + * Server connection pool closed + * + * @event Server#close + * @type {object} + */ + +/** + * Server connection pool caused an error + * + * @event Server#error + * @type {Error} + */ + +/** + * Server destroyed was called + * + * @event Server#destroy + * @type {Server} + */ + +module.exports = Server; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/topologies/shared.js b/scripts/2.5/node_modules/mongodb/lib/core/topologies/shared.js new file mode 100644 index 00000000..8e227bad --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/core/topologies/shared.js @@ -0,0 +1,476 @@ +'use strict'; + +const os = require('os'); +const f = require('util').format; +const ReadPreference = require('./read_preference'); +const Buffer = require('safe-buffer').Buffer; +const TopologyType = require('../sdam/topology_description').TopologyType; +const MongoError = require('../error').MongoError; + +const MMAPv1_RETRY_WRITES_ERROR_CODE = 20; + +/** + * Emit event if it exists + * @method + */ +function emitSDAMEvent(self, event, description) { + if (self.listeners(event).length > 0) { + self.emit(event, description); + } +} + +// Get package.json variable +var driverVersion = require('../../../package.json').version; +var nodejsversion = f('Node.js %s, %s', process.version, os.endianness()); +var type = os.type(); +var name = process.platform; +var architecture = process.arch; +var release = os.release(); + +function createClientInfo(options) { + // Build default client information + var clientInfo = options.clientInfo + ? clone(options.clientInfo) + : { + driver: { + name: 'nodejs-core', + version: driverVersion + }, + os: { + type: type, + name: name, + architecture: architecture, + version: release + } + }; + + // Is platform specified + if (clientInfo.platform && clientInfo.platform.indexOf('mongodb-core') === -1) { + clientInfo.platform = f('%s, mongodb-core: %s', clientInfo.platform, driverVersion); + } else if (!clientInfo.platform) { + clientInfo.platform = nodejsversion; + } + + // Do we have an application specific string + if (options.appname) { + // Cut at 128 bytes + var buffer = Buffer.from(options.appname); + // Return the truncated appname + var appname = buffer.length > 128 ? buffer.slice(0, 128).toString('utf8') : options.appname; + // Add to the clientInfo + clientInfo.application = { name: appname }; + } + + return clientInfo; +} + +function createCompressionInfo(options) { + if (!options.compression || !options.compression.compressors) { + return []; + } + + // Check that all supplied compressors are valid + options.compression.compressors.forEach(function(compressor) { + if (compressor !== 'snappy' && compressor !== 'zlib') { + throw new Error('compressors must be at least one of snappy or zlib'); + } + }); + + return options.compression.compressors; +} + +function clone(object) { + return JSON.parse(JSON.stringify(object)); +} + +var getPreviousDescription = function(self) { + if (!self.s.serverDescription) { + self.s.serverDescription = { + address: self.name, + arbiters: [], + hosts: [], + passives: [], + type: 'Unknown' + }; + } + + return self.s.serverDescription; +}; + +var emitServerDescriptionChanged = function(self, description) { + if (self.listeners('serverDescriptionChanged').length > 0) { + // Emit the server description changed events + self.emit('serverDescriptionChanged', { + topologyId: self.s.topologyId !== -1 ? self.s.topologyId : self.id, + address: self.name, + previousDescription: getPreviousDescription(self), + newDescription: description + }); + + self.s.serverDescription = description; + } +}; + +var getPreviousTopologyDescription = function(self) { + if (!self.s.topologyDescription) { + self.s.topologyDescription = { + topologyType: 'Unknown', + servers: [ + { + address: self.name, + arbiters: [], + hosts: [], + passives: [], + type: 'Unknown' + } + ] + }; + } + + return self.s.topologyDescription; +}; + +var emitTopologyDescriptionChanged = function(self, description) { + if (self.listeners('topologyDescriptionChanged').length > 0) { + // Emit the server description changed events + self.emit('topologyDescriptionChanged', { + topologyId: self.s.topologyId !== -1 ? self.s.topologyId : self.id, + address: self.name, + previousDescription: getPreviousTopologyDescription(self), + newDescription: description + }); + + self.s.serverDescription = description; + } +}; + +var changedIsMaster = function(self, currentIsmaster, ismaster) { + var currentType = getTopologyType(self, currentIsmaster); + var newType = getTopologyType(self, ismaster); + if (newType !== currentType) return true; + return false; +}; + +var getTopologyType = function(self, ismaster) { + if (!ismaster) { + ismaster = self.ismaster; + } + + if (!ismaster) return 'Unknown'; + if (ismaster.ismaster && ismaster.msg === 'isdbgrid') return 'Mongos'; + if (ismaster.ismaster && !ismaster.hosts) return 'Standalone'; + if (ismaster.ismaster) return 'RSPrimary'; + if (ismaster.secondary) return 'RSSecondary'; + if (ismaster.arbiterOnly) return 'RSArbiter'; + return 'Unknown'; +}; + +var inquireServerState = function(self) { + return function(callback) { + if (self.s.state === 'destroyed') return; + // Record response time + var start = new Date().getTime(); + + // emitSDAMEvent + emitSDAMEvent(self, 'serverHeartbeatStarted', { connectionId: self.name }); + + // Attempt to execute ismaster command + self.command('admin.$cmd', { ismaster: true }, { monitoring: true }, function(err, r) { + if (!err) { + // Legacy event sender + self.emit('ismaster', r, self); + + // Calculate latencyMS + var latencyMS = new Date().getTime() - start; + + // Server heart beat event + emitSDAMEvent(self, 'serverHeartbeatSucceeded', { + durationMS: latencyMS, + reply: r.result, + connectionId: self.name + }); + + // Did the server change + if (changedIsMaster(self, self.s.ismaster, r.result)) { + // Emit server description changed if something listening + emitServerDescriptionChanged(self, { + address: self.name, + arbiters: [], + hosts: [], + passives: [], + type: !self.s.inTopology ? 'Standalone' : getTopologyType(self) + }); + } + + // Updat ismaster view + self.s.ismaster = r.result; + + // Set server response time + self.s.isMasterLatencyMS = latencyMS; + } else { + emitSDAMEvent(self, 'serverHeartbeatFailed', { + durationMS: latencyMS, + failure: err, + connectionId: self.name + }); + } + + // Peforming an ismaster monitoring callback operation + if (typeof callback === 'function') { + return callback(err, r); + } + + // Perform another sweep + self.s.inquireServerStateTimeout = setTimeout(inquireServerState(self), self.s.haInterval); + }); + }; +}; + +// +// Clone the options +var cloneOptions = function(options) { + var opts = {}; + for (var name in options) { + opts[name] = options[name]; + } + return opts; +}; + +function Interval(fn, time) { + var timer = false; + + this.start = function() { + if (!this.isRunning()) { + timer = setInterval(fn, time); + } + + return this; + }; + + this.stop = function() { + clearInterval(timer); + timer = false; + return this; + }; + + this.isRunning = function() { + return timer !== false; + }; +} + +function Timeout(fn, time) { + var timer = false; + + this.start = function() { + if (!this.isRunning()) { + timer = setTimeout(fn, time); + } + return this; + }; + + this.stop = function() { + clearTimeout(timer); + timer = false; + return this; + }; + + this.isRunning = function() { + if (timer && timer._called) return false; + return timer !== false; + }; +} + +function diff(previous, current) { + // Difference document + var diff = { + servers: [] + }; + + // Previous entry + if (!previous) { + previous = { servers: [] }; + } + + // Check if we have any previous servers missing in the current ones + for (var i = 0; i < previous.servers.length; i++) { + var found = false; + + for (var j = 0; j < current.servers.length; j++) { + if (current.servers[j].address.toLowerCase() === previous.servers[i].address.toLowerCase()) { + found = true; + break; + } + } + + if (!found) { + // Add to the diff + diff.servers.push({ + address: previous.servers[i].address, + from: previous.servers[i].type, + to: 'Unknown' + }); + } + } + + // Check if there are any severs that don't exist + for (j = 0; j < current.servers.length; j++) { + found = false; + + // Go over all the previous servers + for (i = 0; i < previous.servers.length; i++) { + if (previous.servers[i].address.toLowerCase() === current.servers[j].address.toLowerCase()) { + found = true; + break; + } + } + + // Add the server to the diff + if (!found) { + diff.servers.push({ + address: current.servers[j].address, + from: 'Unknown', + to: current.servers[j].type + }); + } + } + + // Got through all the servers + for (i = 0; i < previous.servers.length; i++) { + var prevServer = previous.servers[i]; + + // Go through all current servers + for (j = 0; j < current.servers.length; j++) { + var currServer = current.servers[j]; + + // Matching server + if (prevServer.address.toLowerCase() === currServer.address.toLowerCase()) { + // We had a change in state + if (prevServer.type !== currServer.type) { + diff.servers.push({ + address: prevServer.address, + from: prevServer.type, + to: currServer.type + }); + } + } + } + } + + // Return difference + return diff; +} + +/** + * Shared function to determine clusterTime for a given topology + * + * @param {*} topology + * @param {*} clusterTime + */ +function resolveClusterTime(topology, $clusterTime) { + if (topology.clusterTime == null) { + topology.clusterTime = $clusterTime; + } else { + if ($clusterTime.clusterTime.greaterThan(topology.clusterTime.clusterTime)) { + topology.clusterTime = $clusterTime; + } + } +} + +// NOTE: this is a temporary move until the topologies can be more formally refactored +// to share code. +const SessionMixins = { + endSessions: function(sessions, callback) { + if (!Array.isArray(sessions)) { + sessions = [sessions]; + } + + // TODO: + // When connected to a sharded cluster the endSessions command + // can be sent to any mongos. When connected to a replica set the + // endSessions command MUST be sent to the primary if the primary + // is available, otherwise it MUST be sent to any available secondary. + // Is it enough to use: ReadPreference.primaryPreferred ? + this.command( + 'admin.$cmd', + { endSessions: sessions }, + { readPreference: ReadPreference.primaryPreferred }, + () => { + // intentionally ignored, per spec + if (typeof callback === 'function') callback(); + } + ); + } +}; + +function topologyType(topology) { + if (topology.description) { + return topology.description.type; + } + + if (topology.type === 'mongos') { + return TopologyType.Sharded; + } else if (topology.type === 'replset') { + return TopologyType.ReplicaSetWithPrimary; + } + + return TopologyType.Single; +} + +const RETRYABLE_WIRE_VERSION = 6; + +/** + * Determines whether the provided topology supports retryable writes + * + * @param {Mongos|Replset} topology + */ +const isRetryableWritesSupported = function(topology) { + const maxWireVersion = topology.lastIsMaster().maxWireVersion; + if (maxWireVersion < RETRYABLE_WIRE_VERSION) { + return false; + } + + if (!topology.logicalSessionTimeoutMinutes) { + return false; + } + + if (topologyType(topology) === TopologyType.Single) { + return false; + } + + return true; +}; + +const MMAPv1_RETRY_WRITES_ERROR_MESSAGE = + 'This MongoDB deployment does not support retryable writes. Please add retryWrites=false to your connection string.'; + +function getMMAPError(err) { + if (err.code !== MMAPv1_RETRY_WRITES_ERROR_CODE || !err.errmsg.includes('Transaction numbers')) { + return err; + } + + // According to the retryable writes spec, we must replace the error message in this case. + // We need to replace err.message so the thrown message is correct and we need to replace err.errmsg to meet the spec requirement. + const newErr = new MongoError({ + message: MMAPv1_RETRY_WRITES_ERROR_MESSAGE, + errmsg: MMAPv1_RETRY_WRITES_ERROR_MESSAGE, + originalError: err + }); + return newErr; +} + +module.exports.SessionMixins = SessionMixins; +module.exports.resolveClusterTime = resolveClusterTime; +module.exports.inquireServerState = inquireServerState; +module.exports.getTopologyType = getTopologyType; +module.exports.emitServerDescriptionChanged = emitServerDescriptionChanged; +module.exports.emitTopologyDescriptionChanged = emitTopologyDescriptionChanged; +module.exports.cloneOptions = cloneOptions; +module.exports.createClientInfo = createClientInfo; +module.exports.createCompressionInfo = createCompressionInfo; +module.exports.clone = clone; +module.exports.diff = diff; +module.exports.Interval = Interval; +module.exports.Timeout = Timeout; +module.exports.isRetryableWritesSupported = isRetryableWritesSupported; +module.exports.getMMAPError = getMMAPError; +module.exports.topologyType = topologyType; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/transactions.js b/scripts/2.5/node_modules/mongodb/lib/core/transactions.js new file mode 100644 index 00000000..891a8734 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/core/transactions.js @@ -0,0 +1,168 @@ +'use strict'; +const MongoError = require('./error').MongoError; + +let TxnState; +let stateMachine; + +(() => { + const NO_TRANSACTION = 'NO_TRANSACTION'; + const STARTING_TRANSACTION = 'STARTING_TRANSACTION'; + const TRANSACTION_IN_PROGRESS = 'TRANSACTION_IN_PROGRESS'; + const TRANSACTION_COMMITTED = 'TRANSACTION_COMMITTED'; + const TRANSACTION_COMMITTED_EMPTY = 'TRANSACTION_COMMITTED_EMPTY'; + const TRANSACTION_ABORTED = 'TRANSACTION_ABORTED'; + + TxnState = { + NO_TRANSACTION, + STARTING_TRANSACTION, + TRANSACTION_IN_PROGRESS, + TRANSACTION_COMMITTED, + TRANSACTION_COMMITTED_EMPTY, + TRANSACTION_ABORTED + }; + + stateMachine = { + [NO_TRANSACTION]: [NO_TRANSACTION, STARTING_TRANSACTION], + [STARTING_TRANSACTION]: [ + TRANSACTION_IN_PROGRESS, + TRANSACTION_COMMITTED, + TRANSACTION_COMMITTED_EMPTY, + TRANSACTION_ABORTED + ], + [TRANSACTION_IN_PROGRESS]: [ + TRANSACTION_IN_PROGRESS, + TRANSACTION_COMMITTED, + TRANSACTION_ABORTED + ], + [TRANSACTION_COMMITTED]: [ + TRANSACTION_COMMITTED, + TRANSACTION_COMMITTED_EMPTY, + STARTING_TRANSACTION, + NO_TRANSACTION + ], + [TRANSACTION_ABORTED]: [STARTING_TRANSACTION, NO_TRANSACTION], + [TRANSACTION_COMMITTED_EMPTY]: [TRANSACTION_COMMITTED_EMPTY, NO_TRANSACTION] + }; +})(); + +/** + * The MongoDB ReadConcern, which allows for control of the consistency and isolation properties + * of the data read from replica sets and replica set shards. + * @typedef {Object} ReadConcern + * @property {'local'|'available'|'majority'|'linearizable'|'snapshot'} level The readConcern Level + * @see https://docs.mongodb.com/manual/reference/read-concern/ + */ + +/** + * A MongoDB WriteConcern, which describes the level of acknowledgement + * requested from MongoDB for write operations. + * @typedef {Object} WriteConcern + * @property {number|'majority'|string} [w=1] requests acknowledgement that the write operation has + * propagated to a specified number of mongod hosts + * @property {boolean} [j=false] requests acknowledgement from MongoDB that the write operation has + * been written to the journal + * @property {number} [wtimeout] a time limit, in milliseconds, for the write concern + * @see https://docs.mongodb.com/manual/reference/write-concern/ + */ + +/** + * Configuration options for a transaction. + * @typedef {Object} TransactionOptions + * @property {ReadConcern} [readConcern] A default read concern for commands in this transaction + * @property {WriteConcern} [writeConcern] A default writeConcern for commands in this transaction + * @property {ReadPreference} [readPreference] A default read preference for commands in this transaction + */ + +/** + * A class maintaining state related to a server transaction. Internal Only + * @ignore + */ +class Transaction { + /** + * Create a transaction + * + * @ignore + * @param {TransactionOptions} [options] Optional settings + */ + constructor(options) { + options = options || {}; + + this.state = TxnState.NO_TRANSACTION; + this.options = {}; + + if (options.writeConcern || typeof options.w !== 'undefined') { + const w = options.writeConcern ? options.writeConcern.w : options.w; + if (w <= 0) { + throw new MongoError('Transactions do not support unacknowledged write concern'); + } + + this.options.writeConcern = options.writeConcern ? options.writeConcern : { w: options.w }; + } + + if (options.readConcern) this.options.readConcern = options.readConcern; + if (options.readPreference) this.options.readPreference = options.readPreference; + if (options.maxCommitTimeMS) this.options.maxTimeMS = options.maxCommitTimeMS; + + // TODO: This isn't technically necessary + this._pinnedServer = undefined; + this._recoveryToken = undefined; + } + + get server() { + return this._pinnedServer; + } + + get recoveryToken() { + return this._recoveryToken; + } + + get isPinned() { + return !!this.server; + } + + /** + * @ignore + * @return Whether this session is presently in a transaction + */ + get isActive() { + return ( + [TxnState.STARTING_TRANSACTION, TxnState.TRANSACTION_IN_PROGRESS].indexOf(this.state) !== -1 + ); + } + + /** + * Transition the transaction in the state machine + * @ignore + * @param {TxnState} state The new state to transition to + */ + transition(nextState) { + const nextStates = stateMachine[this.state]; + if (nextStates && nextStates.indexOf(nextState) !== -1) { + this.state = nextState; + if (this.state === TxnState.NO_TRANSACTION || this.state === TxnState.STARTING_TRANSACTION) { + this.unpinServer(); + } + return; + } + + throw new MongoError( + `Attempted illegal state transition from [${this.state}] to [${nextState}]` + ); + } + + pinServer(server) { + if (this.isActive) { + this._pinnedServer = server; + } + } + + unpinServer() { + this._pinnedServer = undefined; + } +} + +function isTransactionCommand(command) { + return !!(command.commitTransaction || command.abortTransaction); +} + +module.exports = { TxnState, Transaction, isTransactionCommand }; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/uri_parser.js b/scripts/2.5/node_modules/mongodb/lib/core/uri_parser.js new file mode 100644 index 00000000..1530d88d --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/core/uri_parser.js @@ -0,0 +1,637 @@ +'use strict'; +const URL = require('url'); +const qs = require('querystring'); +const dns = require('dns'); +const MongoParseError = require('./error').MongoParseError; +const ReadPreference = require('./topologies/read_preference'); + +/** + * The following regular expression validates a connection string and breaks the + * provide string into the following capture groups: [protocol, username, password, hosts] + */ +const HOSTS_RX = /(mongodb(?:\+srv|)):\/\/(?: (?:[^:]*) (?: : ([^@]*) )? @ )?([^/?]*)(?:\/|)(.*)/; + +/** + * Determines whether a provided address matches the provided parent domain in order + * to avoid certain attack vectors. + * + * @param {String} srvAddress The address to check against a domain + * @param {String} parentDomain The domain to check the provided address against + * @return {Boolean} Whether the provided address matches the parent domain + */ +function matchesParentDomain(srvAddress, parentDomain) { + const regex = /^.*?\./; + const srv = `.${srvAddress.replace(regex, '')}`; + const parent = `.${parentDomain.replace(regex, '')}`; + return srv.endsWith(parent); +} + +/** + * Lookup a `mongodb+srv` connection string, combine the parts and reparse it as a normal + * connection string. + * + * @param {string} uri The connection string to parse + * @param {object} options Optional user provided connection string options + * @param {function} callback + */ +function parseSrvConnectionString(uri, options, callback) { + const result = URL.parse(uri, true); + + if (result.hostname.split('.').length < 3) { + return callback(new MongoParseError('URI does not have hostname, domain name and tld')); + } + + result.domainLength = result.hostname.split('.').length; + if (result.pathname && result.pathname.match(',')) { + return callback(new MongoParseError('Invalid URI, cannot contain multiple hostnames')); + } + + if (result.port) { + return callback(new MongoParseError(`Ports not accepted with '${PROTOCOL_MONGODB_SRV}' URIs`)); + } + + // Resolve the SRV record and use the result as the list of hosts to connect to. + const lookupAddress = result.host; + dns.resolveSrv(`_mongodb._tcp.${lookupAddress}`, (err, addresses) => { + if (err) return callback(err); + + if (addresses.length === 0) { + return callback(new MongoParseError('No addresses found at host')); + } + + for (let i = 0; i < addresses.length; i++) { + if (!matchesParentDomain(addresses[i].name, result.hostname, result.domainLength)) { + return callback( + new MongoParseError('Server record does not share hostname with parent URI') + ); + } + } + + // Convert the original URL to a non-SRV URL. + result.protocol = 'mongodb'; + result.host = addresses.map(address => `${address.name}:${address.port}`).join(','); + + // Default to SSL true if it's not specified. + if ( + !('ssl' in options) && + (!result.search || !('ssl' in result.query) || result.query.ssl === null) + ) { + result.query.ssl = true; + } + + // Resolve TXT record and add options from there if they exist. + dns.resolveTxt(lookupAddress, (err, record) => { + if (err) { + if (err.code !== 'ENODATA') { + return callback(err); + } + record = null; + } + + if (record) { + if (record.length > 1) { + return callback(new MongoParseError('Multiple text records not allowed')); + } + + record = qs.parse(record[0].join('')); + if (Object.keys(record).some(key => key !== 'authSource' && key !== 'replicaSet')) { + return callback( + new MongoParseError('Text record must only set `authSource` or `replicaSet`') + ); + } + + Object.assign(result.query, record); + } + + // Set completed options back into the URL object. + result.search = qs.stringify(result.query); + + const finalString = URL.format(result); + parseConnectionString(finalString, options, (err, ret) => { + if (err) { + callback(err); + return; + } + + callback(null, Object.assign({}, ret, { srvHost: lookupAddress })); + }); + }); + }); +} + +/** + * Parses a query string item according to the connection string spec + * + * @param {string} key The key for the parsed value + * @param {Array|String} value The value to parse + * @return {Array|Object|String} The parsed value + */ +function parseQueryStringItemValue(key, value) { + if (Array.isArray(value)) { + // deduplicate and simplify arrays + value = value.filter((v, idx) => value.indexOf(v) === idx); + if (value.length === 1) value = value[0]; + } else if (value.indexOf(':') > 0) { + value = value.split(',').reduce((result, pair) => { + const parts = pair.split(':'); + result[parts[0]] = parseQueryStringItemValue(key, parts[1]); + return result; + }, {}); + } else if (value.indexOf(',') > 0) { + value = value.split(',').map(v => { + return parseQueryStringItemValue(key, v); + }); + } else if (value.toLowerCase() === 'true' || value.toLowerCase() === 'false') { + value = value.toLowerCase() === 'true'; + } else if (!Number.isNaN(value) && !STRING_OPTIONS.has(key)) { + const numericValue = parseFloat(value); + if (!Number.isNaN(numericValue)) { + value = parseFloat(value); + } + } + + return value; +} + +// Options that are known boolean types +const BOOLEAN_OPTIONS = new Set([ + 'slaveok', + 'slave_ok', + 'sslvalidate', + 'fsync', + 'safe', + 'retrywrites', + 'j' +]); + +// Known string options, only used to bypass Number coercion in `parseQueryStringItemValue` +const STRING_OPTIONS = new Set(['authsource', 'replicaset']); + +// Supported text representations of auth mechanisms +// NOTE: this list exists in native already, if it is merged here we should deduplicate +const AUTH_MECHANISMS = new Set([ + 'GSSAPI', + 'MONGODB-X509', + 'MONGODB-CR', + 'DEFAULT', + 'SCRAM-SHA-1', + 'SCRAM-SHA-256', + 'PLAIN' +]); + +// Lookup table used to translate normalized (lower-cased) forms of connection string +// options to their expected camelCase version +const CASE_TRANSLATION = { + replicaset: 'replicaSet', + connecttimeoutms: 'connectTimeoutMS', + sockettimeoutms: 'socketTimeoutMS', + maxpoolsize: 'maxPoolSize', + minpoolsize: 'minPoolSize', + maxidletimems: 'maxIdleTimeMS', + waitqueuemultiple: 'waitQueueMultiple', + waitqueuetimeoutms: 'waitQueueTimeoutMS', + wtimeoutms: 'wtimeoutMS', + readconcern: 'readConcern', + readconcernlevel: 'readConcernLevel', + readpreference: 'readPreference', + maxstalenessseconds: 'maxStalenessSeconds', + readpreferencetags: 'readPreferenceTags', + authsource: 'authSource', + authmechanism: 'authMechanism', + authmechanismproperties: 'authMechanismProperties', + gssapiservicename: 'gssapiServiceName', + localthresholdms: 'localThresholdMS', + serverselectiontimeoutms: 'serverSelectionTimeoutMS', + serverselectiontryonce: 'serverSelectionTryOnce', + heartbeatfrequencyms: 'heartbeatFrequencyMS', + retrywrites: 'retryWrites', + uuidrepresentation: 'uuidRepresentation', + zlibcompressionlevel: 'zlibCompressionLevel', + tlsallowinvalidcertificates: 'tlsAllowInvalidCertificates', + tlsallowinvalidhostnames: 'tlsAllowInvalidHostnames', + tlsinsecure: 'tlsInsecure', + tlscafile: 'tlsCAFile', + tlscertificatekeyfile: 'tlsCertificateKeyFile', + tlscertificatekeyfilepassword: 'tlsCertificateKeyFilePassword', + wtimeout: 'wTimeoutMS', + j: 'journal' +}; + +/** + * Sets the value for `key`, allowing for any required translation + * + * @param {object} obj The object to set the key on + * @param {string} key The key to set the value for + * @param {*} value The value to set + * @param {object} options The options used for option parsing + */ +function applyConnectionStringOption(obj, key, value, options) { + // simple key translation + if (key === 'journal') { + key = 'j'; + } else if (key === 'wtimeoutms') { + key = 'wtimeout'; + } + + // more complicated translation + if (BOOLEAN_OPTIONS.has(key)) { + value = value === 'true' || value === true; + } else if (key === 'appname') { + value = decodeURIComponent(value); + } else if (key === 'readconcernlevel') { + obj['readConcernLevel'] = value; + key = 'readconcern'; + value = { level: value }; + } + + // simple validation + if (key === 'compressors') { + value = Array.isArray(value) ? value : [value]; + + if (!value.every(c => c === 'snappy' || c === 'zlib')) { + throw new MongoParseError( + 'Value for `compressors` must be at least one of: `snappy`, `zlib`' + ); + } + } + + if (key === 'authmechanism' && !AUTH_MECHANISMS.has(value)) { + throw new MongoParseError( + 'Value for `authMechanism` must be one of: `DEFAULT`, `GSSAPI`, `PLAIN`, `MONGODB-X509`, `SCRAM-SHA-1`, `SCRAM-SHA-256`' + ); + } + + if (key === 'readpreference' && !ReadPreference.isValid(value)) { + throw new MongoParseError( + 'Value for `readPreference` must be one of: `primary`, `primaryPreferred`, `secondary`, `secondaryPreferred`, `nearest`' + ); + } + + if (key === 'zlibcompressionlevel' && (value < -1 || value > 9)) { + throw new MongoParseError('zlibCompressionLevel must be an integer between -1 and 9'); + } + + // special cases + if (key === 'compressors' || key === 'zlibcompressionlevel') { + obj.compression = obj.compression || {}; + obj = obj.compression; + } + + if (key === 'authmechanismproperties') { + if (typeof value.SERVICE_NAME === 'string') obj.gssapiServiceName = value.SERVICE_NAME; + if (typeof value.SERVICE_REALM === 'string') obj.gssapiServiceRealm = value.SERVICE_REALM; + if (typeof value.CANONICALIZE_HOST_NAME !== 'undefined') { + obj.gssapiCanonicalizeHostName = value.CANONICALIZE_HOST_NAME; + } + } + + if (key === 'readpreferencetags' && Array.isArray(value)) { + value = splitArrayOfMultipleReadPreferenceTags(value); + } + + // set the actual value + if (options.caseTranslate && CASE_TRANSLATION[key]) { + obj[CASE_TRANSLATION[key]] = value; + return; + } + + obj[key] = value; +} + +const USERNAME_REQUIRED_MECHANISMS = new Set([ + 'GSSAPI', + 'MONGODB-CR', + 'PLAIN', + 'SCRAM-SHA-1', + 'SCRAM-SHA-256' +]); + +function splitArrayOfMultipleReadPreferenceTags(value) { + const parsedTags = []; + + for (let i = 0; i < value.length; i++) { + parsedTags[i] = {}; + value[i].split(',').forEach(individualTag => { + const splitTag = individualTag.split(':'); + parsedTags[i][splitTag[0]] = splitTag[1]; + }); + } + + return parsedTags; +} + +/** + * Modifies the parsed connection string object taking into account expectations we + * have for authentication-related options. + * + * @param {object} parsed The parsed connection string result + * @return The parsed connection string result possibly modified for auth expectations + */ +function applyAuthExpectations(parsed) { + if (parsed.options == null) { + return; + } + + const options = parsed.options; + const authSource = options.authsource || options.authSource; + if (authSource != null) { + parsed.auth = Object.assign({}, parsed.auth, { db: authSource }); + } + + const authMechanism = options.authmechanism || options.authMechanism; + if (authMechanism != null) { + if ( + USERNAME_REQUIRED_MECHANISMS.has(authMechanism) && + (!parsed.auth || parsed.auth.username == null) + ) { + throw new MongoParseError(`Username required for mechanism \`${authMechanism}\``); + } + + if (authMechanism === 'GSSAPI') { + if (authSource != null && authSource !== '$external') { + throw new MongoParseError( + `Invalid source \`${authSource}\` for mechanism \`${authMechanism}\` specified.` + ); + } + + parsed.auth = Object.assign({}, parsed.auth, { db: '$external' }); + } + + if (authMechanism === 'MONGODB-X509') { + if (parsed.auth && parsed.auth.password != null) { + throw new MongoParseError(`Password not allowed for mechanism \`${authMechanism}\``); + } + + if (authSource != null && authSource !== '$external') { + throw new MongoParseError( + `Invalid source \`${authSource}\` for mechanism \`${authMechanism}\` specified.` + ); + } + + parsed.auth = Object.assign({}, parsed.auth, { db: '$external' }); + } + + if (authMechanism === 'PLAIN') { + if (parsed.auth && parsed.auth.db == null) { + parsed.auth = Object.assign({}, parsed.auth, { db: '$external' }); + } + } + } + + // default to `admin` if nothing else was resolved + if (parsed.auth && parsed.auth.db == null) { + parsed.auth = Object.assign({}, parsed.auth, { db: 'admin' }); + } + + return parsed; +} + +/** + * Parses a query string according the connection string spec. + * + * @param {String} query The query string to parse + * @param {object} [options] The options used for options parsing + * @return {Object|Error} The parsed query string as an object, or an error if one was encountered + */ +function parseQueryString(query, options) { + const result = {}; + let parsedQueryString = qs.parse(query); + + checkTLSOptions(parsedQueryString); + + for (const key in parsedQueryString) { + const value = parsedQueryString[key]; + if (value === '' || value == null) { + throw new MongoParseError('Incomplete key value pair for option'); + } + + const normalizedKey = key.toLowerCase(); + const parsedValue = parseQueryStringItemValue(normalizedKey, value); + applyConnectionStringOption(result, normalizedKey, parsedValue, options); + } + + // special cases for known deprecated options + if (result.wtimeout && result.wtimeoutms) { + delete result.wtimeout; + console.warn('Unsupported option `wtimeout` specified'); + } + + return Object.keys(result).length ? result : null; +} + +/** + * Checks a query string for invalid tls options according to the URI options spec. + * + * @param {string} queryString The query string to check + * @throws {MongoParseError} + */ +function checkTLSOptions(queryString) { + const queryStringKeys = Object.keys(queryString); + if ( + queryStringKeys.indexOf('tlsInsecure') !== -1 && + (queryStringKeys.indexOf('tlsAllowInvalidCertificates') !== -1 || + queryStringKeys.indexOf('tlsAllowInvalidHostnames') !== -1) + ) { + throw new MongoParseError( + 'The `tlsInsecure` option cannot be used with `tlsAllowInvalidCertificates` or `tlsAllowInvalidHostnames`.' + ); + } + + const tlsValue = assertTlsOptionsAreEqual('tls', queryString, queryStringKeys); + const sslValue = assertTlsOptionsAreEqual('ssl', queryString, queryStringKeys); + + if (tlsValue != null && sslValue != null) { + if (tlsValue !== sslValue) { + throw new MongoParseError('All values of `tls` and `ssl` must be the same.'); + } + } +} + +/** + * Checks a query string to ensure all tls/ssl options are the same. + * + * @param {string} key The key (tls or ssl) to check + * @param {string} queryString The query string to check + * @throws {MongoParseError} + * @return The value of the tls/ssl option + */ +function assertTlsOptionsAreEqual(optionName, queryString, queryStringKeys) { + const queryStringHasTLSOption = queryStringKeys.indexOf(optionName) !== -1; + + let optionValue; + if (Array.isArray(queryString[optionName])) { + optionValue = queryString[optionName][0]; + } else { + optionValue = queryString[optionName]; + } + + if (queryStringHasTLSOption) { + if (Array.isArray(queryString[optionName])) { + const firstValue = queryString[optionName][0]; + queryString[optionName].forEach(tlsValue => { + if (tlsValue !== firstValue) { + throw new MongoParseError('All values of ${optionName} must be the same.'); + } + }); + } + } + + return optionValue; +} + +const PROTOCOL_MONGODB = 'mongodb'; +const PROTOCOL_MONGODB_SRV = 'mongodb+srv'; +const SUPPORTED_PROTOCOLS = [PROTOCOL_MONGODB, PROTOCOL_MONGODB_SRV]; + +/** + * Parses a MongoDB connection string + * + * @param {*} uri the MongoDB connection string to parse + * @param {object} [options] Optional settings. + * @param {boolean} [options.caseTranslate] Whether the parser should translate options back into camelCase after normalization + * @param {parseCallback} callback + */ +function parseConnectionString(uri, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = Object.assign({}, { caseTranslate: true }, options); + + // Check for bad uris before we parse + try { + URL.parse(uri); + } catch (e) { + return callback(new MongoParseError('URI malformed, cannot be parsed')); + } + + const cap = uri.match(HOSTS_RX); + if (!cap) { + return callback(new MongoParseError('Invalid connection string')); + } + + const protocol = cap[1]; + if (SUPPORTED_PROTOCOLS.indexOf(protocol) === -1) { + return callback(new MongoParseError('Invalid protocol provided')); + } + + if (protocol === PROTOCOL_MONGODB_SRV) { + return parseSrvConnectionString(uri, options, callback); + } + + const dbAndQuery = cap[4].split('?'); + const db = dbAndQuery.length > 0 ? dbAndQuery[0] : null; + const query = dbAndQuery.length > 1 ? dbAndQuery[1] : null; + + let parsedOptions; + try { + parsedOptions = parseQueryString(query, options); + } catch (parseError) { + return callback(parseError); + } + + parsedOptions = Object.assign({}, parsedOptions, options); + const auth = { username: null, password: null, db: db && db !== '' ? qs.unescape(db) : null }; + if (parsedOptions.auth) { + // maintain support for legacy options passed into `MongoClient` + if (parsedOptions.auth.username) auth.username = parsedOptions.auth.username; + if (parsedOptions.auth.user) auth.username = parsedOptions.auth.user; + if (parsedOptions.auth.password) auth.password = parsedOptions.auth.password; + } else { + if (parsedOptions.username) auth.username = parsedOptions.username; + if (parsedOptions.user) auth.username = parsedOptions.user; + if (parsedOptions.password) auth.password = parsedOptions.password; + } + + if (cap[4].split('?')[0].indexOf('@') !== -1) { + return callback(new MongoParseError('Unescaped slash in userinfo section')); + } + + const authorityParts = cap[3].split('@'); + if (authorityParts.length > 2) { + return callback(new MongoParseError('Unescaped at-sign in authority section')); + } + + if (authorityParts.length > 1) { + const authParts = authorityParts.shift().split(':'); + if (authParts.length > 2) { + return callback(new MongoParseError('Unescaped colon in authority section')); + } + + if (!auth.username) auth.username = qs.unescape(authParts[0]); + if (!auth.password) auth.password = authParts[1] ? qs.unescape(authParts[1]) : null; + } + + let hostParsingError = null; + const hosts = authorityParts + .shift() + .split(',') + .map(host => { + let parsedHost = URL.parse(`mongodb://${host}`); + if (parsedHost.path === '/:') { + hostParsingError = new MongoParseError('Double colon in host identifier'); + return null; + } + + // heuristically determine if we're working with a domain socket + if (host.match(/\.sock/)) { + parsedHost.hostname = qs.unescape(host); + parsedHost.port = null; + } + + if (Number.isNaN(parsedHost.port)) { + hostParsingError = new MongoParseError('Invalid port (non-numeric string)'); + return; + } + + const result = { + host: parsedHost.hostname, + port: parsedHost.port ? parseInt(parsedHost.port) : 27017 + }; + + if (result.port === 0) { + hostParsingError = new MongoParseError('Invalid port (zero) with hostname'); + return; + } + + if (result.port > 65535) { + hostParsingError = new MongoParseError('Invalid port (larger than 65535) with hostname'); + return; + } + + if (result.port < 0) { + hostParsingError = new MongoParseError('Invalid port (negative number)'); + return; + } + + return result; + }) + .filter(host => !!host); + + if (hostParsingError) { + return callback(hostParsingError); + } + + if (hosts.length === 0 || hosts[0].host === '' || hosts[0].host === null) { + return callback(new MongoParseError('No hostname or hostnames provided in connection string')); + } + + const result = { + hosts: hosts, + auth: auth.db || auth.username ? auth : null, + options: Object.keys(parsedOptions).length ? parsedOptions : null + }; + + if (result.auth && result.auth.db) { + result.defaultDatabase = result.auth.db; + } else { + result.defaultDatabase = 'test'; + } + + try { + applyAuthExpectations(result); + } catch (authError) { + return callback(authError); + } + + callback(null, result); +} + +module.exports = parseConnectionString; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/utils.js b/scripts/2.5/node_modules/mongodb/lib/core/utils.js new file mode 100644 index 00000000..7581bf25 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/core/utils.js @@ -0,0 +1,177 @@ +'use strict'; + +const crypto = require('crypto'); +const requireOptional = require('require_optional'); + +/** + * Generate a UUIDv4 + */ +const uuidV4 = () => { + const result = crypto.randomBytes(16); + result[6] = (result[6] & 0x0f) | 0x40; + result[8] = (result[8] & 0x3f) | 0x80; + return result; +}; + +/** + * Returns the duration calculated from two high resolution timers in milliseconds + * + * @param {Object} started A high resolution timestamp created from `process.hrtime()` + * @returns {Number} The duration in milliseconds + */ +const calculateDurationInMs = started => { + const hrtime = process.hrtime(started); + return (hrtime[0] * 1e9 + hrtime[1]) / 1e6; +}; + +/** + * Relays events for a given listener and emitter + * + * @param {EventEmitter} listener the EventEmitter to listen to the events from + * @param {EventEmitter} emitter the EventEmitter to relay the events to + */ +function relayEvents(listener, emitter, events) { + events.forEach(eventName => listener.on(eventName, event => emitter.emit(eventName, event))); +} + +function retrieveKerberos() { + let kerberos; + + try { + kerberos = requireOptional('kerberos'); + } catch (err) { + if (err.code === 'MODULE_NOT_FOUND') { + throw new Error('The `kerberos` module was not found. Please install it and try again.'); + } + + throw err; + } + + return kerberos; +} + +// Throw an error if an attempt to use EJSON is made when it is not installed +const noEJSONError = function() { + throw new Error('The `mongodb-extjson` module was not found. Please install it and try again.'); +}; + +// Facilitate loading EJSON optionally +function retrieveEJSON() { + let EJSON = null; + try { + EJSON = requireOptional('mongodb-extjson'); + } catch (error) {} // eslint-disable-line + if (!EJSON) { + EJSON = { + parse: noEJSONError, + deserialize: noEJSONError, + serialize: noEJSONError, + stringify: noEJSONError, + setBSONModule: noEJSONError, + BSON: noEJSONError + }; + } + + return EJSON; +} + +/** + * A helper function for determining `maxWireVersion` between legacy and new topology + * instances + * + * @private + * @param {(Topology|Server)} topologyOrServer + */ +function maxWireVersion(topologyOrServer) { + if (topologyOrServer.ismaster) { + return topologyOrServer.ismaster.maxWireVersion; + } + + if (typeof topologyOrServer.lastIsMaster === 'function') { + const lastIsMaster = topologyOrServer.lastIsMaster(); + if (lastIsMaster) { + return lastIsMaster.maxWireVersion; + } + } + + if (topologyOrServer.description) { + return topologyOrServer.description.maxWireVersion; + } + + return null; +} + +/* + * Checks that collation is supported by server. + * + * @param {Server} [server] to check against + * @param {object} [cmd] object where collation may be specified + * @param {function} [callback] callback function + * @return true if server does not support collation + */ +function collationNotSupported(server, cmd) { + return cmd && cmd.collation && maxWireVersion(server) < 5; +} + +/** + * Checks if a given value is a Promise + * + * @param {*} maybePromise + * @return true if the provided value is a Promise + */ +function isPromiseLike(maybePromise) { + return maybePromise && typeof maybePromise.then === 'function'; +} + +/** + * Applies the function `eachFn` to each item in `arr`, in parallel. + * + * @param {array} arr an array of items to asynchronusly iterate over + * @param {function} eachFn A function to call on each item of the array. The callback signature is `(item, callback)`, where the callback indicates iteration is complete. + * @param {function} callback The callback called after every item has been iterated + */ +function eachAsync(arr, eachFn, callback) { + if (arr.length === 0) { + callback(null); + return; + } + + const length = arr.length; + let completed = 0; + function eachCallback(err) { + if (err) { + callback(err, null); + return; + } + + if (++completed === length) { + callback(null); + } + } + + for (let idx = 0; idx < length; ++idx) { + try { + eachFn(arr[idx], eachCallback); + } catch (err) { + callback(err); + return; + } + } +} + +function isUnifiedTopology(topology) { + return topology.description != null; +} + +module.exports = { + uuidV4, + calculateDurationInMs, + relayEvents, + collationNotSupported, + retrieveEJSON, + retrieveKerberos, + maxWireVersion, + isPromiseLike, + eachAsync, + isUnifiedTopology +}; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/wireprotocol/command.js b/scripts/2.5/node_modules/mongodb/lib/core/wireprotocol/command.js new file mode 100644 index 00000000..47107c62 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/core/wireprotocol/command.js @@ -0,0 +1,170 @@ +'use strict'; + +const Query = require('../connection/commands').Query; +const Msg = require('../connection/msg').Msg; +const MongoError = require('../error').MongoError; +const getReadPreference = require('./shared').getReadPreference; +const isSharded = require('./shared').isSharded; +const databaseNamespace = require('./shared').databaseNamespace; +const isTransactionCommand = require('../transactions').isTransactionCommand; +const applySession = require('../sessions').applySession; + +function isClientEncryptionEnabled(server) { + return server.autoEncrypter; +} + +function command(server, ns, cmd, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + if (cmd == null) { + return callback(new MongoError(`command ${JSON.stringify(cmd)} does not return a cursor`)); + } + + if (!isClientEncryptionEnabled(server)) { + _command(server, ns, cmd, options, callback); + return; + } + + _cryptCommand(server, ns, cmd, options, callback); +} + +function _command(server, ns, cmd, options, callback) { + const bson = server.s.bson; + const pool = server.s.pool; + const readPreference = getReadPreference(cmd, options); + const shouldUseOpMsg = supportsOpMsg(server); + const session = options.session; + + let clusterTime = server.clusterTime; + let finalCmd = Object.assign({}, cmd); + if (hasSessionSupport(server) && session) { + if ( + session.clusterTime && + session.clusterTime.clusterTime.greaterThan(clusterTime.clusterTime) + ) { + clusterTime = session.clusterTime; + } + + const err = applySession(session, finalCmd, options); + if (err) { + return callback(err); + } + } + + // if we have a known cluster time, gossip it + if (clusterTime) { + finalCmd.$clusterTime = clusterTime; + } + + if ( + isSharded(server) && + !shouldUseOpMsg && + readPreference && + readPreference.preference !== 'primary' + ) { + finalCmd = { + $query: finalCmd, + $readPreference: readPreference.toJSON() + }; + } + + const commandOptions = Object.assign( + { + command: true, + numberToSkip: 0, + numberToReturn: -1, + checkKeys: false + }, + options + ); + + // This value is not overridable + commandOptions.slaveOk = readPreference.slaveOk(); + + const cmdNs = `${databaseNamespace(ns)}.$cmd`; + const message = shouldUseOpMsg + ? new Msg(bson, cmdNs, finalCmd, commandOptions) + : new Query(bson, cmdNs, finalCmd, commandOptions); + + const inTransaction = session && (session.inTransaction() || isTransactionCommand(finalCmd)); + const commandResponseHandler = inTransaction + ? function(err) { + if ( + !cmd.commitTransaction && + err && + err instanceof MongoError && + err.hasErrorLabel('TransientTransactionError') + ) { + session.transaction.unpinServer(); + } + + return callback.apply(null, arguments); + } + : callback; + + try { + pool.write(message, commandOptions, commandResponseHandler); + } catch (err) { + commandResponseHandler(err); + } +} + +function hasSessionSupport(topology) { + if (topology == null) return false; + if (topology.description) { + return topology.description.maxWireVersion >= 6; + } + + return topology.ismaster == null ? false : topology.ismaster.maxWireVersion >= 6; +} + +function supportsOpMsg(topologyOrServer) { + const description = topologyOrServer.ismaster + ? topologyOrServer.ismaster + : topologyOrServer.description; + + if (description == null) { + return false; + } + + return description.maxWireVersion >= 6 && description.__nodejs_mock_server__ == null; +} + +function _cryptCommand(server, ns, cmd, options, callback) { + const shouldBypassAutoEncryption = !!server.s.options.bypassAutoEncryption; + const autoEncrypter = server.autoEncrypter; + function commandResponseHandler(err, response) { + if (err || response == null) { + callback(err, response); + return; + } + + autoEncrypter.decrypt(response.result, (err, decrypted) => { + if (err) { + callback(err, null); + return; + } + + response.result = decrypted; + response.message.documents = [decrypted]; + callback(null, response); + }); + } + + if (shouldBypassAutoEncryption) { + _command(server, ns, cmd, options, commandResponseHandler); + return; + } + + autoEncrypter.encrypt(ns, cmd, (err, encrypted) => { + if (err) { + callback(err, null); + return; + } + + _command(server, ns, encrypted, options, commandResponseHandler); + }); +} + +module.exports = command; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/wireprotocol/compression.js b/scripts/2.5/node_modules/mongodb/lib/core/wireprotocol/compression.js new file mode 100644 index 00000000..4b908e63 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/core/wireprotocol/compression.js @@ -0,0 +1,73 @@ +'use strict'; + +var Snappy = require('../connection/utils').retrieveSnappy(), + zlib = require('zlib'); + +var compressorIDs = { + snappy: 1, + zlib: 2 +}; + +var uncompressibleCommands = [ + 'ismaster', + 'saslStart', + 'saslContinue', + 'getnonce', + 'authenticate', + 'createUser', + 'updateUser', + 'copydbSaslStart', + 'copydbgetnonce', + 'copydb' +]; + +// Facilitate compressing a message using an agreed compressor +var compress = function(self, dataToBeCompressed, callback) { + switch (self.options.agreedCompressor) { + case 'snappy': + Snappy.compress(dataToBeCompressed, callback); + break; + case 'zlib': + // Determine zlibCompressionLevel + var zlibOptions = {}; + if (self.options.zlibCompressionLevel) { + zlibOptions.level = self.options.zlibCompressionLevel; + } + zlib.deflate(dataToBeCompressed, zlibOptions, callback); + break; + default: + throw new Error( + 'Attempt to compress message using unknown compressor "' + + self.options.agreedCompressor + + '".' + ); + } +}; + +// Decompress a message using the given compressor +var decompress = function(compressorID, compressedData, callback) { + if (compressorID < 0 || compressorID > compressorIDs.length) { + throw new Error( + 'Server sent message compressed using an unsupported compressor. (Received compressor ID ' + + compressorID + + ')' + ); + } + switch (compressorID) { + case compressorIDs.snappy: + Snappy.uncompress(compressedData, callback); + break; + case compressorIDs.zlib: + zlib.inflate(compressedData, callback); + break; + default: + callback(null, compressedData); + } +}; + +module.exports = { + compressorIDs: compressorIDs, + uncompressibleCommands: uncompressibleCommands, + compress: compress, + decompress: decompress +}; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/wireprotocol/constants.js b/scripts/2.5/node_modules/mongodb/lib/core/wireprotocol/constants.js new file mode 100644 index 00000000..df2293b5 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/core/wireprotocol/constants.js @@ -0,0 +1,13 @@ +'use strict'; + +const MIN_SUPPORTED_SERVER_VERSION = '2.6'; +const MAX_SUPPORTED_SERVER_VERSION = '4.2'; +const MIN_SUPPORTED_WIRE_VERSION = 2; +const MAX_SUPPORTED_WIRE_VERSION = 8; + +module.exports = { + MIN_SUPPORTED_SERVER_VERSION, + MAX_SUPPORTED_SERVER_VERSION, + MIN_SUPPORTED_WIRE_VERSION, + MAX_SUPPORTED_WIRE_VERSION +}; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/wireprotocol/get_more.js b/scripts/2.5/node_modules/mongodb/lib/core/wireprotocol/get_more.js new file mode 100644 index 00000000..b2db3202 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/core/wireprotocol/get_more.js @@ -0,0 +1,90 @@ +'use strict'; + +const GetMore = require('../connection/commands').GetMore; +const retrieveBSON = require('../connection/utils').retrieveBSON; +const MongoError = require('../error').MongoError; +const MongoNetworkError = require('../error').MongoNetworkError; +const BSON = retrieveBSON(); +const Long = BSON.Long; +const collectionNamespace = require('./shared').collectionNamespace; +const maxWireVersion = require('../utils').maxWireVersion; +const applyCommonQueryOptions = require('./shared').applyCommonQueryOptions; +const command = require('./command'); + +function getMore(server, ns, cursorState, batchSize, options, callback) { + options = options || {}; + + const wireVersion = maxWireVersion(server); + function queryCallback(err, result) { + if (err) return callback(err); + const response = result.message; + + // If we have a timed out query or a cursor that was killed + if (response.cursorNotFound) { + return callback(new MongoNetworkError('cursor killed or timed out'), null); + } + + if (wireVersion < 4) { + const cursorId = + typeof response.cursorId === 'number' + ? Long.fromNumber(response.cursorId) + : response.cursorId; + + cursorState.documents = response.documents; + cursorState.cursorId = cursorId; + + callback(null, null, response.connection); + return; + } + + // We have an error detected + if (response.documents[0].ok === 0) { + return callback(new MongoError(response.documents[0])); + } + + // Ensure we have a Long valid cursor id + const cursorId = + typeof response.documents[0].cursor.id === 'number' + ? Long.fromNumber(response.documents[0].cursor.id) + : response.documents[0].cursor.id; + + cursorState.documents = response.documents[0].cursor.nextBatch; + cursorState.cursorId = cursorId; + + callback(null, response.documents[0], response.connection); + } + + if (wireVersion < 4) { + const bson = server.s.bson; + const getMoreOp = new GetMore(bson, ns, cursorState.cursorId, { numberToReturn: batchSize }); + const queryOptions = applyCommonQueryOptions({}, cursorState); + server.s.pool.write(getMoreOp, queryOptions, queryCallback); + return; + } + + const getMoreCmd = { + getMore: cursorState.cursorId, + collection: collectionNamespace(ns), + batchSize: Math.abs(batchSize) + }; + + if (cursorState.cmd.tailable && typeof cursorState.cmd.maxAwaitTimeMS === 'number') { + getMoreCmd.maxTimeMS = cursorState.cmd.maxAwaitTimeMS; + } + + const commandOptions = Object.assign( + { + returnFieldSelector: null, + documentsReturnedIn: 'nextBatch' + }, + options + ); + + if (cursorState.session) { + commandOptions.session = cursorState.session; + } + + command(server, ns, getMoreCmd, commandOptions, queryCallback); +} + +module.exports = getMore; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/wireprotocol/index.js b/scripts/2.5/node_modules/mongodb/lib/core/wireprotocol/index.js new file mode 100644 index 00000000..b6ffda7c --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/core/wireprotocol/index.js @@ -0,0 +1,18 @@ +'use strict'; +const writeCommand = require('./write_command'); + +module.exports = { + insert: function insert(server, ns, ops, options, callback) { + writeCommand(server, 'insert', 'documents', ns, ops, options, callback); + }, + update: function update(server, ns, ops, options, callback) { + writeCommand(server, 'update', 'updates', ns, ops, options, callback); + }, + remove: function remove(server, ns, ops, options, callback) { + writeCommand(server, 'delete', 'deletes', ns, ops, options, callback); + }, + killCursors: require('./kill_cursors'), + getMore: require('./get_more'), + query: require('./query'), + command: require('./command') +}; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/wireprotocol/kill_cursors.js b/scripts/2.5/node_modules/mongodb/lib/core/wireprotocol/kill_cursors.js new file mode 100644 index 00000000..bb134773 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/core/wireprotocol/kill_cursors.js @@ -0,0 +1,70 @@ +'use strict'; + +const KillCursor = require('../connection/commands').KillCursor; +const MongoError = require('../error').MongoError; +const MongoNetworkError = require('../error').MongoNetworkError; +const collectionNamespace = require('./shared').collectionNamespace; +const maxWireVersion = require('../utils').maxWireVersion; +const command = require('./command'); + +function killCursors(server, ns, cursorState, callback) { + callback = typeof callback === 'function' ? callback : () => {}; + const cursorId = cursorState.cursorId; + + if (maxWireVersion(server) < 4) { + const bson = server.s.bson; + const pool = server.s.pool; + const killCursor = new KillCursor(bson, ns, [cursorId]); + const options = { + immediateRelease: true, + noResponse: true + }; + + if (typeof cursorState.session === 'object') { + options.session = cursorState.session; + } + + if (pool && pool.isConnected()) { + try { + pool.write(killCursor, options, callback); + } catch (err) { + if (typeof callback === 'function') { + callback(err, null); + } else { + console.warn(err); + } + } + } + + return; + } + + const killCursorCmd = { + killCursors: collectionNamespace(ns), + cursors: [cursorId] + }; + + const options = {}; + if (typeof cursorState.session === 'object') options.session = cursorState.session; + + command(server, ns, killCursorCmd, options, (err, result) => { + if (err) { + return callback(err); + } + + const response = result.message; + if (response.cursorNotFound) { + return callback(new MongoNetworkError('cursor killed or timed out'), null); + } + + if (!Array.isArray(response.documents) || response.documents.length === 0) { + return callback( + new MongoError(`invalid killCursors result returned for cursor id ${cursorId}`) + ); + } + + callback(null, response.documents[0]); + }); +} + +module.exports = killCursors; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/wireprotocol/query.js b/scripts/2.5/node_modules/mongodb/lib/core/wireprotocol/query.js new file mode 100644 index 00000000..c501b506 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/core/wireprotocol/query.js @@ -0,0 +1,231 @@ +'use strict'; + +const Query = require('../connection/commands').Query; +const MongoError = require('../error').MongoError; +const getReadPreference = require('./shared').getReadPreference; +const collectionNamespace = require('./shared').collectionNamespace; +const isSharded = require('./shared').isSharded; +const maxWireVersion = require('../utils').maxWireVersion; +const applyCommonQueryOptions = require('./shared').applyCommonQueryOptions; +const command = require('./command'); + +function query(server, ns, cmd, cursorState, options, callback) { + options = options || {}; + if (cursorState.cursorId != null) { + return callback(); + } + + if (cmd == null) { + return callback(new MongoError(`command ${JSON.stringify(cmd)} does not return a cursor`)); + } + + if (maxWireVersion(server) < 4) { + const query = prepareLegacyFindQuery(server, ns, cmd, cursorState, options); + const queryOptions = applyCommonQueryOptions({}, cursorState); + if (typeof query.documentsReturnedIn === 'string') { + queryOptions.documentsReturnedIn = query.documentsReturnedIn; + } + + server.s.pool.write(query, queryOptions, callback); + return; + } + + const readPreference = getReadPreference(cmd, options); + const findCmd = prepareFindCommand(server, ns, cmd, cursorState, options); + + // NOTE: This actually modifies the passed in cmd, and our code _depends_ on this + // side-effect. Change this ASAP + cmd.virtual = false; + + const commandOptions = Object.assign( + { + documentsReturnedIn: 'firstBatch', + numberToReturn: 1, + slaveOk: readPreference.slaveOk() + }, + options + ); + + if (cmd.readPreference) { + commandOptions.readPreference = readPreference; + } + + if (cursorState.session) { + commandOptions.session = cursorState.session; + } + + command(server, ns, findCmd, commandOptions, callback); +} + +function prepareFindCommand(server, ns, cmd, cursorState) { + cursorState.batchSize = cmd.batchSize || cursorState.batchSize; + let findCmd = { + find: collectionNamespace(ns) + }; + + if (cmd.query) { + if (cmd.query['$query']) { + findCmd.filter = cmd.query['$query']; + } else { + findCmd.filter = cmd.query; + } + } + + let sortValue = cmd.sort; + if (Array.isArray(sortValue)) { + const sortObject = {}; + + if (sortValue.length > 0 && !Array.isArray(sortValue[0])) { + let sortDirection = sortValue[1]; + if (sortDirection === 'asc') { + sortDirection = 1; + } else if (sortDirection === 'desc') { + sortDirection = -1; + } + + sortObject[sortValue[0]] = sortDirection; + } else { + for (let i = 0; i < sortValue.length; i++) { + let sortDirection = sortValue[i][1]; + if (sortDirection === 'asc') { + sortDirection = 1; + } else if (sortDirection === 'desc') { + sortDirection = -1; + } + + sortObject[sortValue[i][0]] = sortDirection; + } + } + + sortValue = sortObject; + } + + if (cmd.sort) findCmd.sort = sortValue; + if (cmd.fields) findCmd.projection = cmd.fields; + if (cmd.hint) findCmd.hint = cmd.hint; + if (cmd.skip) findCmd.skip = cmd.skip; + if (cmd.limit) findCmd.limit = cmd.limit; + if (cmd.limit < 0) { + findCmd.limit = Math.abs(cmd.limit); + findCmd.singleBatch = true; + } + + if (typeof cmd.batchSize === 'number') { + if (cmd.batchSize < 0) { + if (cmd.limit !== 0 && Math.abs(cmd.batchSize) < Math.abs(cmd.limit)) { + findCmd.limit = Math.abs(cmd.batchSize); + } + + findCmd.singleBatch = true; + } + + findCmd.batchSize = Math.abs(cmd.batchSize); + } + + if (cmd.comment) findCmd.comment = cmd.comment; + if (cmd.maxScan) findCmd.maxScan = cmd.maxScan; + if (cmd.maxTimeMS) findCmd.maxTimeMS = cmd.maxTimeMS; + if (cmd.min) findCmd.min = cmd.min; + if (cmd.max) findCmd.max = cmd.max; + findCmd.returnKey = cmd.returnKey ? cmd.returnKey : false; + findCmd.showRecordId = cmd.showDiskLoc ? cmd.showDiskLoc : false; + if (cmd.snapshot) findCmd.snapshot = cmd.snapshot; + if (cmd.tailable) findCmd.tailable = cmd.tailable; + if (cmd.oplogReplay) findCmd.oplogReplay = cmd.oplogReplay; + if (cmd.noCursorTimeout) findCmd.noCursorTimeout = cmd.noCursorTimeout; + if (cmd.awaitData) findCmd.awaitData = cmd.awaitData; + if (cmd.awaitdata) findCmd.awaitData = cmd.awaitdata; + if (cmd.partial) findCmd.partial = cmd.partial; + if (cmd.collation) findCmd.collation = cmd.collation; + if (cmd.readConcern) findCmd.readConcern = cmd.readConcern; + + // If we have explain, we need to rewrite the find command + // to wrap it in the explain command + if (cmd.explain) { + findCmd = { + explain: findCmd + }; + } + + return findCmd; +} + +function prepareLegacyFindQuery(server, ns, cmd, cursorState, options) { + options = options || {}; + const bson = server.s.bson; + const readPreference = getReadPreference(cmd, options); + cursorState.batchSize = cmd.batchSize || cursorState.batchSize; + + let numberToReturn = 0; + if ( + cursorState.limit < 0 || + (cursorState.limit !== 0 && cursorState.limit < cursorState.batchSize) || + (cursorState.limit > 0 && cursorState.batchSize === 0) + ) { + numberToReturn = cursorState.limit; + } else { + numberToReturn = cursorState.batchSize; + } + + const numberToSkip = cursorState.skip || 0; + + const findCmd = {}; + if (isSharded(server) && readPreference) { + findCmd['$readPreference'] = readPreference.toJSON(); + } + + if (cmd.sort) findCmd['$orderby'] = cmd.sort; + if (cmd.hint) findCmd['$hint'] = cmd.hint; + if (cmd.snapshot) findCmd['$snapshot'] = cmd.snapshot; + if (typeof cmd.returnKey !== 'undefined') findCmd['$returnKey'] = cmd.returnKey; + if (cmd.maxScan) findCmd['$maxScan'] = cmd.maxScan; + if (cmd.min) findCmd['$min'] = cmd.min; + if (cmd.max) findCmd['$max'] = cmd.max; + if (typeof cmd.showDiskLoc !== 'undefined') findCmd['$showDiskLoc'] = cmd.showDiskLoc; + if (cmd.comment) findCmd['$comment'] = cmd.comment; + if (cmd.maxTimeMS) findCmd['$maxTimeMS'] = cmd.maxTimeMS; + if (cmd.explain) { + // nToReturn must be 0 (match all) or negative (match N and close cursor) + // nToReturn > 0 will give explain results equivalent to limit(0) + numberToReturn = -Math.abs(cmd.limit || 0); + findCmd['$explain'] = true; + } + + findCmd['$query'] = cmd.query; + if (cmd.readConcern && cmd.readConcern.level !== 'local') { + throw new MongoError( + `server find command does not support a readConcern level of ${cmd.readConcern.level}` + ); + } + + if (cmd.readConcern) { + cmd = Object.assign({}, cmd); + delete cmd['readConcern']; + } + + const serializeFunctions = + typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + const ignoreUndefined = + typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : false; + + const query = new Query(bson, ns, findCmd, { + numberToSkip: numberToSkip, + numberToReturn: numberToReturn, + pre32Limit: typeof cmd.limit !== 'undefined' ? cmd.limit : undefined, + checkKeys: false, + returnFieldSelector: cmd.fields, + serializeFunctions: serializeFunctions, + ignoreUndefined: ignoreUndefined + }); + + if (typeof cmd.tailable === 'boolean') query.tailable = cmd.tailable; + if (typeof cmd.oplogReplay === 'boolean') query.oplogReplay = cmd.oplogReplay; + if (typeof cmd.noCursorTimeout === 'boolean') query.noCursorTimeout = cmd.noCursorTimeout; + if (typeof cmd.awaitData === 'boolean') query.awaitData = cmd.awaitData; + if (typeof cmd.partial === 'boolean') query.partial = cmd.partial; + + query.slaveOk = readPreference.slaveOk(); + return query; +} + +module.exports = query; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/wireprotocol/shared.js b/scripts/2.5/node_modules/mongodb/lib/core/wireprotocol/shared.js new file mode 100644 index 00000000..2574aade --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/core/wireprotocol/shared.js @@ -0,0 +1,115 @@ +'use strict'; + +const ReadPreference = require('../topologies/read_preference'); +const MongoError = require('../error').MongoError; +const ServerType = require('../sdam/server_description').ServerType; +const TopologyDescription = require('../sdam/topology_description').TopologyDescription; + +const MESSAGE_HEADER_SIZE = 16; +const COMPRESSION_DETAILS_SIZE = 9; // originalOpcode + uncompressedSize, compressorID + +// OPCODE Numbers +// Defined at https://docs.mongodb.com/manual/reference/mongodb-wire-protocol/#request-opcodes +var opcodes = { + OP_REPLY: 1, + OP_UPDATE: 2001, + OP_INSERT: 2002, + OP_QUERY: 2004, + OP_GETMORE: 2005, + OP_DELETE: 2006, + OP_KILL_CURSORS: 2007, + OP_COMPRESSED: 2012, + OP_MSG: 2013 +}; + +var getReadPreference = function(cmd, options) { + // Default to command version of the readPreference + var readPreference = cmd.readPreference || new ReadPreference('primary'); + // If we have an option readPreference override the command one + if (options.readPreference) { + readPreference = options.readPreference; + } + + if (typeof readPreference === 'string') { + readPreference = new ReadPreference(readPreference); + } + + if (!(readPreference instanceof ReadPreference)) { + throw new MongoError('read preference must be a ReadPreference instance'); + } + + return readPreference; +}; + +// Parses the header of a wire protocol message +var parseHeader = function(message) { + return { + length: message.readInt32LE(0), + requestId: message.readInt32LE(4), + responseTo: message.readInt32LE(8), + opCode: message.readInt32LE(12) + }; +}; + +function applyCommonQueryOptions(queryOptions, options) { + Object.assign(queryOptions, { + raw: typeof options.raw === 'boolean' ? options.raw : false, + promoteLongs: typeof options.promoteLongs === 'boolean' ? options.promoteLongs : true, + promoteValues: typeof options.promoteValues === 'boolean' ? options.promoteValues : true, + promoteBuffers: typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : false, + monitoring: typeof options.monitoring === 'boolean' ? options.monitoring : false, + fullResult: typeof options.fullResult === 'boolean' ? options.fullResult : false + }); + + if (typeof options.socketTimeout === 'number') { + queryOptions.socketTimeout = options.socketTimeout; + } + + if (options.session) { + queryOptions.session = options.session; + } + + if (typeof options.documentsReturnedIn === 'string') { + queryOptions.documentsReturnedIn = options.documentsReturnedIn; + } + + return queryOptions; +} + +function isSharded(topologyOrServer) { + if (topologyOrServer.type === 'mongos') return true; + if (topologyOrServer.description && topologyOrServer.description.type === ServerType.Mongos) { + return true; + } + + // NOTE: This is incredibly inefficient, and should be removed once command construction + // happens based on `Server` not `Topology`. + if (topologyOrServer.description && topologyOrServer.description instanceof TopologyDescription) { + const servers = Array.from(topologyOrServer.description.servers.values()); + return servers.some(server => server.type === ServerType.Mongos); + } + + return false; +} + +function databaseNamespace(ns) { + return ns.split('.')[0]; +} +function collectionNamespace(ns) { + return ns + .split('.') + .slice(1) + .join('.'); +} + +module.exports = { + getReadPreference, + MESSAGE_HEADER_SIZE, + COMPRESSION_DETAILS_SIZE, + opcodes, + parseHeader, + applyCommonQueryOptions, + isSharded, + databaseNamespace, + collectionNamespace +}; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/wireprotocol/write_command.js b/scripts/2.5/node_modules/mongodb/lib/core/wireprotocol/write_command.js new file mode 100644 index 00000000..e334d518 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/core/wireprotocol/write_command.js @@ -0,0 +1,50 @@ +'use strict'; + +const MongoError = require('../error').MongoError; +const collectionNamespace = require('./shared').collectionNamespace; +const command = require('./command'); + +function writeCommand(server, type, opsField, ns, ops, options, callback) { + if (ops.length === 0) throw new MongoError(`${type} must contain at least one document`); + if (typeof options === 'function') { + callback = options; + options = {}; + } + + options = options || {}; + const ordered = typeof options.ordered === 'boolean' ? options.ordered : true; + const writeConcern = options.writeConcern; + + const writeCommand = {}; + writeCommand[type] = collectionNamespace(ns); + writeCommand[opsField] = ops; + writeCommand.ordered = ordered; + + if (writeConcern && Object.keys(writeConcern).length > 0) { + writeCommand.writeConcern = writeConcern; + } + + if (options.collation) { + for (let i = 0; i < writeCommand[opsField].length; i++) { + if (!writeCommand[opsField][i].collation) { + writeCommand[opsField][i].collation = options.collation; + } + } + } + + if (options.bypassDocumentValidation === true) { + writeCommand.bypassDocumentValidation = options.bypassDocumentValidation; + } + + const commandOptions = Object.assign( + { + checkKeys: type === 'insert', + numberToReturn: 1 + }, + options + ); + + command(server, ns, writeCommand, commandOptions, callback); +} + +module.exports = writeCommand; diff --git a/scripts/2.5/node_modules/mongodb/lib/cursor.js b/scripts/2.5/node_modules/mongodb/lib/cursor.js new file mode 100644 index 00000000..bed709be --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/cursor.js @@ -0,0 +1,1089 @@ +'use strict'; + +const Transform = require('stream').Transform; +const PassThrough = require('stream').PassThrough; +const deprecate = require('util').deprecate; +const handleCallback = require('./utils').handleCallback; +const ReadPreference = require('./core').ReadPreference; +const MongoError = require('./core').MongoError; +const CoreCursor = require('./core/cursor').CoreCursor; +const CursorState = require('./core/cursor').CursorState; +const Map = require('./core').BSON.Map; + +const each = require('./operations/cursor_ops').each; + +const CountOperation = require('./operations/count'); +const ExplainOperation = require('./operations/explain'); +const HasNextOperation = require('./operations/has_next'); +const NextOperation = require('./operations/next'); +const ToArrayOperation = require('./operations/to_array'); + +const executeOperation = require('./operations/execute_operation'); + +/** + * @fileOverview The **Cursor** class is an internal class that embodies a cursor on MongoDB + * allowing for iteration over the results returned from the underlying query. It supports + * one by one document iteration, conversion to an array or can be iterated as a Node 4.X + * or higher stream + * + * **CURSORS Cannot directly be instantiated** + * @example + * const MongoClient = require('mongodb').MongoClient; + * const test = require('assert'); + * // Connection url + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, client) { + * // Create a collection we want to drop later + * const col = client.db(dbName).collection('createIndexExample1'); + * // Insert a bunch of documents + * col.insert([{a:1, b:1} + * , {a:2, b:2}, {a:3, b:3} + * , {a:4, b:4}], {w:1}, function(err, result) { + * test.equal(null, err); + * // Show that duplicate records got dropped + * col.find({}).toArray(function(err, items) { + * test.equal(null, err); + * test.equal(4, items.length); + * client.close(); + * }); + * }); + * }); + */ + +/** + * Namespace provided by the code module + * @external CoreCursor + * @external Readable + */ + +// Flags allowed for cursor +const flags = ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'exhaust', 'partial']; +const fields = ['numberOfRetries', 'tailableRetryInterval']; + +/** + * Creates a new Cursor instance (INTERNAL TYPE, do not instantiate directly) + * @class Cursor + * @extends external:CoreCursor + * @extends external:Readable + * @property {string} sortValue Cursor query sort setting. + * @property {boolean} timeout Is Cursor able to time out. + * @property {ReadPreference} readPreference Get cursor ReadPreference. + * @fires Cursor#data + * @fires Cursor#end + * @fires Cursor#close + * @fires Cursor#readable + * @return {Cursor} a Cursor instance. + * @example + * Cursor cursor options. + * + * collection.find({}).project({a:1}) // Create a projection of field a + * collection.find({}).skip(1).limit(10) // Skip 1 and limit 10 + * collection.find({}).batchSize(5) // Set batchSize on cursor to 5 + * collection.find({}).filter({a:1}) // Set query on the cursor + * collection.find({}).comment('add a comment') // Add a comment to the query, allowing to correlate queries + * collection.find({}).addCursorFlag('tailable', true) // Set cursor as tailable + * collection.find({}).addCursorFlag('oplogReplay', true) // Set cursor as oplogReplay + * collection.find({}).addCursorFlag('noCursorTimeout', true) // Set cursor as noCursorTimeout + * collection.find({}).addCursorFlag('awaitData', true) // Set cursor as awaitData + * collection.find({}).addCursorFlag('partial', true) // Set cursor as partial + * collection.find({}).addQueryModifier('$orderby', {a:1}) // Set $orderby {a:1} + * collection.find({}).max(10) // Set the cursor max + * collection.find({}).maxTimeMS(1000) // Set the cursor maxTimeMS + * collection.find({}).min(100) // Set the cursor min + * collection.find({}).returnKey(true) // Set the cursor returnKey + * collection.find({}).setReadPreference(ReadPreference.PRIMARY) // Set the cursor readPreference + * collection.find({}).showRecordId(true) // Set the cursor showRecordId + * collection.find({}).sort([['a', 1]]) // Sets the sort order of the cursor query + * collection.find({}).hint('a_1') // Set the cursor hint + * + * All options are chainable, so one can do the following. + * + * collection.find({}).maxTimeMS(1000).maxScan(100).skip(1).toArray(..) + */ +class Cursor extends CoreCursor { + constructor(topology, ns, cmd, options) { + super(topology, ns, cmd, options); + if (this.operation) { + options = this.operation.options; + } + + // Tailable cursor options + const numberOfRetries = options.numberOfRetries || 5; + const tailableRetryInterval = options.tailableRetryInterval || 500; + const currentNumberOfRetries = numberOfRetries; + + // Get the promiseLibrary + const promiseLibrary = options.promiseLibrary || Promise; + + // Internal cursor state + this.s = { + // Tailable cursor options + numberOfRetries: numberOfRetries, + tailableRetryInterval: tailableRetryInterval, + currentNumberOfRetries: currentNumberOfRetries, + // State + state: CursorState.INIT, + // Promise library + promiseLibrary, + // Current doc + currentDoc: null, + // explicitlyIgnoreSession + explicitlyIgnoreSession: !!options.explicitlyIgnoreSession + }; + + // Optional ClientSession + if (!options.explicitlyIgnoreSession && options.session) { + this.cursorState.session = options.session; + } + + // Translate correctly + if (this.options.noCursorTimeout === true) { + this.addCursorFlag('noCursorTimeout', true); + } + + // Get the batchSize + let batchSize = 1000; + if (this.cmd.cursor && this.cmd.cursor.batchSize) { + batchSize = this.cmd.cursor.batchSize; + } else if (options.cursor && options.cursor.batchSize) { + batchSize = options.cursor.batchSize; + } else if (typeof options.batchSize === 'number') { + batchSize = options.batchSize; + } + + // Set the batchSize + this.setCursorBatchSize(batchSize); + } + + get readPreference() { + if (this.operation) { + return this.operation.readPreference; + } + + return this.options.readPreference; + } + + get sortValue() { + return this.cmd.sort; + } + + _initializeCursor(callback) { + if (this.operation && this.operation.session != null) { + this.cursorState.session = this.operation.session; + } else { + // implicitly create a session if one has not been provided + if ( + !this.s.explicitlyIgnoreSession && + !this.cursorState.session && + this.topology.hasSessionSupport() + ) { + this.cursorState.session = this.topology.startSession({ owner: this }); + + if (this.operation) { + this.operation.session = this.cursorState.session; + } + } + } + + super._initializeCursor(callback); + } + + /** + * Check if there is any document still available in the cursor + * @method + * @param {Cursor~resultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ + hasNext(callback) { + const hasNextOperation = new HasNextOperation(this); + + return executeOperation(this.topology, hasNextOperation, callback); + } + + /** + * Get the next available document from the cursor, returns null if no more documents are available. + * @method + * @param {Cursor~resultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ + next(callback) { + const nextOperation = new NextOperation(this); + + return executeOperation(this.topology, nextOperation, callback); + } + + /** + * Set the cursor query + * @method + * @param {object} filter The filter object used for the cursor. + * @return {Cursor} + */ + filter(filter) { + if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + this.cmd.query = filter; + return this; + } + + /** + * Set the cursor maxScan + * @method + * @param {object} maxScan Constrains the query to only scan the specified number of documents when fulfilling the query + * @deprecated as of MongoDB 4.0 + * @return {Cursor} + */ + maxScan(maxScan) { + if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + this.cmd.maxScan = maxScan; + return this; + } + + /** + * Set the cursor hint + * @method + * @param {object} hint If specified, then the query system will only consider plans using the hinted index. + * @return {Cursor} + */ + hint(hint) { + if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + this.cmd.hint = hint; + return this; + } + + /** + * Set the cursor min + * @method + * @param {object} min Specify a $min value to specify the inclusive lower bound for a specific index in order to constrain the results of find(). The $min specifies the lower bound for all keys of a specific index in order. + * @return {Cursor} + */ + min(min) { + if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + this.cmd.min = min; + return this; + } + + /** + * Set the cursor max + * @method + * @param {object} max Specify a $max value to specify the exclusive upper bound for a specific index in order to constrain the results of find(). The $max specifies the upper bound for all keys of a specific index in order. + * @return {Cursor} + */ + max(max) { + if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + this.cmd.max = max; + return this; + } + + /** + * Set the cursor returnKey. If set to true, modifies the cursor to only return the index field or fields for the results of the query, rather than documents. If set to true and the query does not use an index to perform the read operation, the returned documents will not contain any fields. + * @method + * @param {bool} returnKey the returnKey value. + * @return {Cursor} + */ + returnKey(value) { + if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + this.cmd.returnKey = value; + return this; + } + + /** + * Set the cursor showRecordId + * @method + * @param {object} showRecordId The $showDiskLoc option has now been deprecated and replaced with the showRecordId field. $showDiskLoc will still be accepted for OP_QUERY stye find. + * @return {Cursor} + */ + showRecordId(value) { + if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + this.cmd.showDiskLoc = value; + return this; + } + + /** + * Set the cursor snapshot + * @method + * @param {object} snapshot The $snapshot operator prevents the cursor from returning a document more than once because an intervening write operation results in a move of the document. + * @deprecated as of MongoDB 4.0 + * @return {Cursor} + */ + snapshot(value) { + if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + this.cmd.snapshot = value; + return this; + } + + /** + * Set a node.js specific cursor option + * @method + * @param {string} field The cursor option to set ['numberOfRetries', 'tailableRetryInterval']. + * @param {object} value The field value. + * @throws {MongoError} + * @return {Cursor} + */ + setCursorOption(field, value) { + if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + if (fields.indexOf(field) === -1) { + throw MongoError.create({ + message: `option ${field} is not a supported option ${fields}`, + driver: true + }); + } + + this.s[field] = value; + if (field === 'numberOfRetries') this.s.currentNumberOfRetries = value; + return this; + } + + /** + * Add a cursor flag to the cursor + * @method + * @param {string} flag The flag to set, must be one of following ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'partial']. + * @param {boolean} value The flag boolean value. + * @throws {MongoError} + * @return {Cursor} + */ + addCursorFlag(flag, value) { + if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + if (flags.indexOf(flag) === -1) { + throw MongoError.create({ + message: `flag ${flag} is not a supported flag ${flags}`, + driver: true + }); + } + + if (typeof value !== 'boolean') { + throw MongoError.create({ message: `flag ${flag} must be a boolean value`, driver: true }); + } + + this.cmd[flag] = value; + return this; + } + + /** + * Add a query modifier to the cursor query + * @method + * @param {string} name The query modifier (must start with $, such as $orderby etc) + * @param {string|boolean|number} value The modifier value. + * @throws {MongoError} + * @return {Cursor} + */ + addQueryModifier(name, value) { + if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + if (name[0] !== '$') { + throw MongoError.create({ message: `${name} is not a valid query modifier`, driver: true }); + } + + // Strip of the $ + const field = name.substr(1); + // Set on the command + this.cmd[field] = value; + // Deal with the special case for sort + if (field === 'orderby') this.cmd.sort = this.cmd[field]; + return this; + } + + /** + * Add a comment to the cursor query allowing for tracking the comment in the log. + * @method + * @param {string} value The comment attached to this query. + * @throws {MongoError} + * @return {Cursor} + */ + comment(value) { + if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + this.cmd.comment = value; + return this; + } + + /** + * Set a maxAwaitTimeMS on a tailing cursor query to allow to customize the timeout value for the option awaitData (Only supported on MongoDB 3.2 or higher, ignored otherwise) + * @method + * @param {number} value Number of milliseconds to wait before aborting the tailed query. + * @throws {MongoError} + * @return {Cursor} + */ + maxAwaitTimeMS(value) { + if (typeof value !== 'number') { + throw MongoError.create({ message: 'maxAwaitTimeMS must be a number', driver: true }); + } + + if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + this.cmd.maxAwaitTimeMS = value; + return this; + } + + /** + * Set a maxTimeMS on the cursor query, allowing for hard timeout limits on queries (Only supported on MongoDB 2.6 or higher) + * @method + * @param {number} value Number of milliseconds to wait before aborting the query. + * @throws {MongoError} + * @return {Cursor} + */ + maxTimeMS(value) { + if (typeof value !== 'number') { + throw MongoError.create({ message: 'maxTimeMS must be a number', driver: true }); + } + + if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + this.cmd.maxTimeMS = value; + return this; + } + + /** + * Sets a field projection for the query. + * @method + * @param {object} value The field projection object. + * @throws {MongoError} + * @return {Cursor} + */ + project(value) { + if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + this.cmd.fields = value; + return this; + } + + /** + * Sets the sort order of the cursor query. + * @method + * @param {(string|array|object)} keyOrList The key or keys set for the sort. + * @param {number} [direction] The direction of the sorting (1 or -1). + * @throws {MongoError} + * @return {Cursor} + */ + sort(keyOrList, direction) { + if (this.options.tailable) { + throw MongoError.create({ message: "Tailable cursor doesn't support sorting", driver: true }); + } + + if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + let order = keyOrList; + + // We have an array of arrays, we need to preserve the order of the sort + // so we will us a Map + if (Array.isArray(order) && Array.isArray(order[0])) { + order = new Map( + order.map(x => { + const value = [x[0], null]; + if (x[1] === 'asc') { + value[1] = 1; + } else if (x[1] === 'desc') { + value[1] = -1; + } else if (x[1] === 1 || x[1] === -1 || x[1].$meta) { + value[1] = x[1]; + } else { + throw new MongoError( + "Illegal sort clause, must be of the form [['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]" + ); + } + + return value; + }) + ); + } + + if (direction != null) { + order = [[keyOrList, direction]]; + } + + this.cmd.sort = order; + return this; + } + + /** + * Set the batch size for the cursor. + * @method + * @param {number} value The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/find/|find command documentation}. + * @throws {MongoError} + * @return {Cursor} + */ + batchSize(value) { + if (this.options.tailable) { + throw MongoError.create({ + message: "Tailable cursor doesn't support batchSize", + driver: true + }); + } + + if (this.s.state === CursorState.CLOSED || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + if (typeof value !== 'number') { + throw MongoError.create({ message: 'batchSize requires an integer', driver: true }); + } + + this.cmd.batchSize = value; + this.setCursorBatchSize(value); + return this; + } + + /** + * Set the collation options for the cursor. + * @method + * @param {object} value The cursor collation options (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). + * @throws {MongoError} + * @return {Cursor} + */ + collation(value) { + this.cmd.collation = value; + return this; + } + + /** + * Set the limit for the cursor. + * @method + * @param {number} value The limit for the cursor query. + * @throws {MongoError} + * @return {Cursor} + */ + limit(value) { + if (this.options.tailable) { + throw MongoError.create({ message: "Tailable cursor doesn't support limit", driver: true }); + } + + if (this.s.state === CursorState.OPEN || this.s.state === CursorState.CLOSED || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + if (typeof value !== 'number') { + throw MongoError.create({ message: 'limit requires an integer', driver: true }); + } + + this.cmd.limit = value; + this.setCursorLimit(value); + return this; + } + + /** + * Set the skip for the cursor. + * @method + * @param {number} value The skip for the cursor query. + * @throws {MongoError} + * @return {Cursor} + */ + skip(value) { + if (this.options.tailable) { + throw MongoError.create({ message: "Tailable cursor doesn't support skip", driver: true }); + } + + if (this.s.state === CursorState.OPEN || this.s.state === CursorState.CLOSED || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + if (typeof value !== 'number') { + throw MongoError.create({ message: 'skip requires an integer', driver: true }); + } + + this.cmd.skip = value; + this.setCursorSkip(value); + return this; + } + + /** + * The callback format for results + * @callback Cursor~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {(object|null|boolean)} result The result object if the command was executed successfully. + */ + + /** + * Clone the cursor + * @function external:CoreCursor#clone + * @return {Cursor} + */ + + /** + * Resets the cursor + * @function external:CoreCursor#rewind + * @return {null} + */ + + /** + * Iterates over all the documents for this cursor. As with **{cursor.toArray}**, + * not all of the elements will be iterated if this cursor had been previously accessed. + * In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike + * **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements + * at any given time if batch size is specified. Otherwise, the caller is responsible + * for making sure that the entire result can fit the memory. + * @method + * @deprecated + * @param {Cursor~resultCallback} callback The result callback. + * @throws {MongoError} + * @return {null} + */ + each(callback) { + // Rewind cursor state + this.rewind(); + // Set current cursor to INIT + this.s.state = CursorState.INIT; + // Run the query + each(this, callback); + } + + /** + * The callback format for the forEach iterator method + * @callback Cursor~iteratorCallback + * @param {Object} doc An emitted document for the iterator + */ + + /** + * The callback error format for the forEach iterator method + * @callback Cursor~endCallback + * @param {MongoError} error An error instance representing the error during the execution. + */ + + /** + * Iterates over all the documents for this cursor using the iterator, callback pattern. + * @method + * @param {Cursor~iteratorCallback} iterator The iteration callback. + * @param {Cursor~endCallback} callback The end callback. + * @throws {MongoError} + * @return {Promise} if no callback supplied + */ + forEach(iterator, callback) { + // Rewind cursor state + this.rewind(); + + // Set current cursor to INIT + this.s.state = CursorState.INIT; + + if (typeof callback === 'function') { + each(this, (err, doc) => { + if (err) { + callback(err); + return false; + } + if (doc != null) { + iterator(doc); + return true; + } + if (doc == null && callback) { + const internalCallback = callback; + callback = null; + internalCallback(null); + return false; + } + }); + } else { + return new this.s.promiseLibrary((fulfill, reject) => { + each(this, (err, doc) => { + if (err) { + reject(err); + return false; + } else if (doc == null) { + fulfill(null); + return false; + } else { + iterator(doc); + return true; + } + }); + }); + } + } + + /** + * Set the ReadPreference for the cursor. + * @method + * @param {(string|ReadPreference)} readPreference The new read preference for the cursor. + * @throws {MongoError} + * @return {Cursor} + */ + setReadPreference(readPreference) { + if (this.s.state !== CursorState.INIT) { + throw MongoError.create({ + message: 'cannot change cursor readPreference after cursor has been accessed', + driver: true + }); + } + + if (readPreference instanceof ReadPreference) { + this.options.readPreference = readPreference; + } else if (typeof readPreference === 'string') { + this.options.readPreference = new ReadPreference(readPreference); + } else { + throw new TypeError('Invalid read preference: ' + readPreference); + } + + return this; + } + + /** + * The callback format for results + * @callback Cursor~toArrayResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {object[]} documents All the documents the satisfy the cursor. + */ + + /** + * Returns an array of documents. The caller is responsible for making sure that there + * is enough memory to store the results. Note that the array only contains partial + * results when this cursor had been previously accessed. In that case, + * cursor.rewind() can be used to reset the cursor. + * @method + * @param {Cursor~toArrayResultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ + toArray(callback) { + if (this.options.tailable) { + throw MongoError.create({ + message: 'Tailable cursor cannot be converted to array', + driver: true + }); + } + + const toArrayOperation = new ToArrayOperation(this); + + return executeOperation(this.topology, toArrayOperation, callback); + } + + /** + * The callback format for results + * @callback Cursor~countResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {number} count The count of documents. + */ + + /** + * Get the count of documents for this cursor + * @method + * @param {boolean} [applySkipLimit=true] Should the count command apply limit and skip settings on the cursor or in the passed in options. + * @param {object} [options] Optional settings. + * @param {number} [options.skip] The number of documents to skip. + * @param {number} [options.limit] The maximum amounts to count before aborting. + * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query. + * @param {string} [options.hint] An index name hint for the query. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {Cursor~countResultCallback} [callback] The result callback. + * @return {Promise} returns Promise if no callback passed + */ + count(applySkipLimit, opts, callback) { + if (this.cmd.query == null) + throw MongoError.create({ + message: 'count can only be used with find command', + driver: true + }); + if (typeof opts === 'function') (callback = opts), (opts = {}); + opts = opts || {}; + + if (typeof applySkipLimit === 'function') { + callback = applySkipLimit; + applySkipLimit = true; + } + + if (this.cursorState.session) { + opts = Object.assign({}, opts, { session: this.cursorState.session }); + } + + const countOperation = new CountOperation(this, applySkipLimit, opts); + + return executeOperation(this.topology, countOperation, callback); + } + + /** + * Close the cursor, sending a KillCursor command and emitting close. + * @method + * @param {object} [options] Optional settings. + * @param {boolean} [options.skipKillCursors] Bypass calling killCursors when closing the cursor. + * @param {Cursor~resultCallback} [callback] The result callback. + * @return {Promise} returns Promise if no callback passed + */ + close(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = Object.assign({}, { skipKillCursors: false }, options); + + this.s.state = CursorState.CLOSED; + if (!options.skipKillCursors) { + // Kill the cursor + this.kill(); + } + + const completeClose = () => { + // Emit the close event for the cursor + this.emit('close'); + + // Callback if provided + if (typeof callback === 'function') { + return handleCallback(callback, null, this); + } + + // Return a Promise + return new this.s.promiseLibrary(resolve => { + resolve(); + }); + }; + + if (this.cursorState.session) { + if (typeof callback === 'function') { + return this._endSession(() => completeClose()); + } + + return new this.s.promiseLibrary(resolve => { + this._endSession(() => completeClose().then(resolve)); + }); + } + + return completeClose(); + } + + /** + * Map all documents using the provided function + * @method + * @param {function} [transform] The mapping transformation method. + * @return {Cursor} + */ + map(transform) { + if (this.cursorState.transforms && this.cursorState.transforms.doc) { + const oldTransform = this.cursorState.transforms.doc; + this.cursorState.transforms.doc = doc => { + return transform(oldTransform(doc)); + }; + } else { + this.cursorState.transforms = { doc: transform }; + } + + return this; + } + + /** + * Is the cursor closed + * @method + * @return {boolean} + */ + isClosed() { + return this.isDead(); + } + + destroy(err) { + if (err) this.emit('error', err); + this.pause(); + this.close(); + } + + /** + * Return a modified Readable stream including a possible transform method. + * @method + * @param {object} [options] Optional settings. + * @param {function} [options.transform] A transformation method applied to each document emitted by the stream. + * @return {Cursor} + * TODO: replace this method with transformStream in next major release + */ + stream(options) { + this.cursorState.streamOptions = options || {}; + return this; + } + + /** + * Return a modified Readable stream that applies a given transform function, if supplied. If none supplied, + * returns a stream of unmodified docs. + * @method + * @param {object} [options] Optional settings. + * @param {function} [options.transform] A transformation method applied to each document emitted by the stream. + * @return {stream} + */ + transformStream(options) { + const streamOptions = options || {}; + if (typeof streamOptions.transform === 'function') { + const stream = new Transform({ + objectMode: true, + transform: function(chunk, encoding, callback) { + this.push(streamOptions.transform(chunk)); + callback(); + } + }); + + return this.pipe(stream); + } + + return this.pipe(new PassThrough({ objectMode: true })); + } + + /** + * Execute the explain for the cursor + * @method + * @param {Cursor~resultCallback} [callback] The result callback. + * @return {Promise} returns Promise if no callback passed + */ + explain(callback) { + // NOTE: the next line includes a special case for operations which do not + // subclass `CommandOperationV2`. To be removed asap. + if (this.operation && this.operation.cmd == null) { + this.operation.options.explain = true; + this.operation.fullResponse = false; + return executeOperation(this.topology, this.operation, callback); + } + + this.cmd.explain = true; + + // Do we have a readConcern + if (this.cmd.readConcern) { + delete this.cmd['readConcern']; + } + + const explainOperation = new ExplainOperation(this); + + return executeOperation(this.topology, explainOperation, callback); + } + + /** + * Return the cursor logger + * @method + * @return {Logger} return the cursor logger + * @ignore + */ + getLogger() { + return this.logger; + } +} + +/** + * Cursor stream data event, fired for each document in the cursor. + * + * @event Cursor#data + * @type {object} + */ + +/** + * Cursor stream end event + * + * @event Cursor#end + * @type {null} + */ + +/** + * Cursor stream close event + * + * @event Cursor#close + * @type {null} + */ + +/** + * Cursor stream readable event + * + * @event Cursor#readable + * @type {null} + */ + +// aliases +Cursor.prototype.maxTimeMs = Cursor.prototype.maxTimeMS; + +// deprecated methods +deprecate(Cursor.prototype.each, 'Cursor.each is deprecated. Use Cursor.forEach instead.'); +deprecate( + Cursor.prototype.maxScan, + 'Cursor.maxScan is deprecated, and will be removed in a later version' +); + +deprecate( + Cursor.prototype.snapshot, + 'Cursor Snapshot is deprecated, and will be removed in a later version' +); + +/** + * The read() method pulls some data out of the internal buffer and returns it. If there is no data available, then it will return null. + * @function external:Readable#read + * @param {number} size Optional argument to specify how much data to read. + * @return {(String | Buffer | null)} + */ + +/** + * Call this function to cause the stream to return strings of the specified encoding instead of Buffer objects. + * @function external:Readable#setEncoding + * @param {string} encoding The encoding to use. + * @return {null} + */ + +/** + * This method will cause the readable stream to resume emitting data events. + * @function external:Readable#resume + * @return {null} + */ + +/** + * This method will cause a stream in flowing-mode to stop emitting data events. Any data that becomes available will remain in the internal buffer. + * @function external:Readable#pause + * @return {null} + */ + +/** + * This method pulls all the data out of a readable stream, and writes it to the supplied destination, automatically managing the flow so that the destination is not overwhelmed by a fast readable stream. + * @function external:Readable#pipe + * @param {Writable} destination The destination for writing data + * @param {object} [options] Pipe options + * @return {null} + */ + +/** + * This method will remove the hooks set up for a previous pipe() call. + * @function external:Readable#unpipe + * @param {Writable} [destination] The destination for writing data + * @return {null} + */ + +/** + * This is useful in certain cases where a stream is being consumed by a parser, which needs to "un-consume" some data that it has optimistically pulled out of the source, so that the stream can be passed on to some other party. + * @function external:Readable#unshift + * @param {(Buffer|string)} chunk Chunk of data to unshift onto the read queue. + * @return {null} + */ + +/** + * Versions of Node prior to v0.10 had streams that did not implement the entire Streams API as it is today. (See "Compatibility" below for more information.) + * @function external:Readable#wrap + * @param {Stream} stream An "old style" readable stream. + * @return {null} + */ + +module.exports = Cursor; diff --git a/scripts/2.5/node_modules/mongodb/lib/db.js b/scripts/2.5/node_modules/mongodb/lib/db.js new file mode 100644 index 00000000..5e68734a --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/db.js @@ -0,0 +1,1029 @@ +'use strict'; + +const EventEmitter = require('events').EventEmitter; +const inherits = require('util').inherits; +const getSingleProperty = require('./utils').getSingleProperty; +const CommandCursor = require('./command_cursor'); +const handleCallback = require('./utils').handleCallback; +const filterOptions = require('./utils').filterOptions; +const toError = require('./utils').toError; +const ReadPreference = require('./core').ReadPreference; +const MongoError = require('./core').MongoError; +const ObjectID = require('./core').ObjectID; +const Logger = require('./core').Logger; +const Collection = require('./collection'); +const mergeOptionsAndWriteConcern = require('./utils').mergeOptionsAndWriteConcern; +const executeLegacyOperation = require('./utils').executeLegacyOperation; +const resolveReadPreference = require('./utils').resolveReadPreference; +const ChangeStream = require('./change_stream'); +const deprecate = require('util').deprecate; +const deprecateOptions = require('./utils').deprecateOptions; +const MongoDBNamespace = require('./utils').MongoDBNamespace; +const CONSTANTS = require('./constants'); +const WriteConcern = require('./write_concern'); +const ReadConcern = require('./read_concern'); +const AggregationCursor = require('./aggregation_cursor'); + +// Operations +const createListener = require('./operations/db_ops').createListener; +const ensureIndex = require('./operations/db_ops').ensureIndex; +const evaluate = require('./operations/db_ops').evaluate; +const profilingInfo = require('./operations/db_ops').profilingInfo; +const validateDatabaseName = require('./operations/db_ops').validateDatabaseName; + +const AggregateOperation = require('./operations/aggregate'); +const AddUserOperation = require('./operations/add_user'); +const CollectionsOperation = require('./operations/collections'); +const CommandOperation = require('./operations/command'); +const CreateCollectionOperation = require('./operations/create_collection'); +const CreateIndexOperation = require('./operations/create_index'); +const DropCollectionOperation = require('./operations/drop').DropCollectionOperation; +const DropDatabaseOperation = require('./operations/drop').DropDatabaseOperation; +const ExecuteDbAdminCommandOperation = require('./operations/execute_db_admin_command'); +const IndexInformationOperation = require('./operations/index_information'); +const ListCollectionsOperation = require('./operations/list_collections'); +const ProfilingLevelOperation = require('./operations/profiling_level'); +const RemoveUserOperation = require('./operations/remove_user'); +const RenameOperation = require('./operations/rename'); +const SetProfilingLevelOperation = require('./operations/set_profiling_level'); + +const executeOperation = require('./operations/execute_operation'); + +/** + * @fileOverview The **Db** class is a class that represents a MongoDB Database. + * + * @example + * const MongoClient = require('mongodb').MongoClient; + * // Connection url + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, client) { + * // Select the database by name + * const testDb = client.db(dbName); + * client.close(); + * }); + */ + +// Allowed parameters +const legalOptionNames = [ + 'w', + 'wtimeout', + 'fsync', + 'j', + 'readPreference', + 'readPreferenceTags', + 'native_parser', + 'forceServerObjectId', + 'pkFactory', + 'serializeFunctions', + 'raw', + 'bufferMaxEntries', + 'authSource', + 'ignoreUndefined', + 'promoteLongs', + 'promiseLibrary', + 'readConcern', + 'retryMiliSeconds', + 'numberOfRetries', + 'parentDb', + 'noListener', + 'loggerLevel', + 'logger', + 'promoteBuffers', + 'promoteLongs', + 'promoteValues', + 'compression', + 'retryWrites' +]; + +/** + * Creates a new Db instance + * @class + * @param {string} databaseName The name of the database this instance represents. + * @param {(Server|ReplSet|Mongos)} topology The server topology for the database. + * @param {object} [options] Optional settings. + * @param {string} [options.authSource] If the database authentication is dependent on another databaseName. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. + * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution. + * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. + * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. + * @param {number} [options.bufferMaxEntries=-1] Sets a cap on how many operations the driver will buffer up before giving up on getting a working connection, default is -1 which is unlimited. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {object} [options.pkFactory] A primary key factory object for generation of custom _id keys. + * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {object} [options.readConcern] Specify a read concern for the collection. (only MongoDB 3.2 or higher supported) + * @param {ReadConcernLevel} [options.readConcern.level='local'] Specify a read concern level for the collection operations (only MongoDB 3.2 or higher supported) + * @property {(Server|ReplSet|Mongos)} serverConfig Get the current db topology. + * @property {number} bufferMaxEntries Current bufferMaxEntries value for the database + * @property {string} databaseName The name of the database this instance represents. + * @property {object} options The options associated with the db instance. + * @property {boolean} native_parser The current value of the parameter native_parser. + * @property {boolean} slaveOk The current slaveOk value for the db instance. + * @property {object} writeConcern The current write concern values. + * @property {object} topology Access the topology object (single server, replicaset or mongos). + * @fires Db#close + * @fires Db#reconnect + * @fires Db#error + * @fires Db#timeout + * @fires Db#parseError + * @fires Db#fullsetup + * @return {Db} a Db instance. + */ +function Db(databaseName, topology, options) { + options = options || {}; + if (!(this instanceof Db)) return new Db(databaseName, topology, options); + EventEmitter.call(this); + + // Get the promiseLibrary + const promiseLibrary = options.promiseLibrary || Promise; + + // Filter the options + options = filterOptions(options, legalOptionNames); + + // Ensure we put the promiseLib in the options + options.promiseLibrary = promiseLibrary; + + // Internal state of the db object + this.s = { + // DbCache + dbCache: {}, + // Children db's + children: [], + // Topology + topology: topology, + // Options + options: options, + // Logger instance + logger: Logger('Db', options), + // Get the bson parser + bson: topology ? topology.bson : null, + // Unpack read preference + readPreference: ReadPreference.fromOptions(options), + // Set buffermaxEntries + bufferMaxEntries: typeof options.bufferMaxEntries === 'number' ? options.bufferMaxEntries : -1, + // Parent db (if chained) + parentDb: options.parentDb || null, + // Set up the primary key factory or fallback to ObjectID + pkFactory: options.pkFactory || ObjectID, + // Get native parser + nativeParser: options.nativeParser || options.native_parser, + // Promise library + promiseLibrary: promiseLibrary, + // No listener + noListener: typeof options.noListener === 'boolean' ? options.noListener : false, + // ReadConcern + readConcern: ReadConcern.fromOptions(options), + writeConcern: WriteConcern.fromOptions(options), + // Namespace + namespace: new MongoDBNamespace(databaseName) + }; + + // Ensure we have a valid db name + validateDatabaseName(databaseName); + + // Add a read Only property + getSingleProperty(this, 'serverConfig', this.s.topology); + getSingleProperty(this, 'bufferMaxEntries', this.s.bufferMaxEntries); + getSingleProperty(this, 'databaseName', this.s.namespace.db); + + // This is a child db, do not register any listeners + if (options.parentDb) return; + if (this.s.noListener) return; + + // Add listeners + topology.on('error', createListener(this, 'error', this)); + topology.on('timeout', createListener(this, 'timeout', this)); + topology.on('close', createListener(this, 'close', this)); + topology.on('parseError', createListener(this, 'parseError', this)); + topology.once('open', createListener(this, 'open', this)); + topology.once('fullsetup', createListener(this, 'fullsetup', this)); + topology.once('all', createListener(this, 'all', this)); + topology.on('reconnect', createListener(this, 'reconnect', this)); +} + +inherits(Db, EventEmitter); + +// Topology +Object.defineProperty(Db.prototype, 'topology', { + enumerable: true, + get: function() { + return this.s.topology; + } +}); + +// Options +Object.defineProperty(Db.prototype, 'options', { + enumerable: true, + get: function() { + return this.s.options; + } +}); + +// slaveOk specified +Object.defineProperty(Db.prototype, 'slaveOk', { + enumerable: true, + get: function() { + if ( + this.s.options.readPreference != null && + (this.s.options.readPreference !== 'primary' || + this.s.options.readPreference.mode !== 'primary') + ) { + return true; + } + return false; + } +}); + +Object.defineProperty(Db.prototype, 'readConcern', { + enumerable: true, + get: function() { + return this.s.readConcern; + } +}); + +Object.defineProperty(Db.prototype, 'readPreference', { + enumerable: true, + get: function() { + if (this.s.readPreference == null) { + // TODO: check client + return ReadPreference.primary; + } + + return this.s.readPreference; + } +}); + +// get the write Concern +Object.defineProperty(Db.prototype, 'writeConcern', { + enumerable: true, + get: function() { + return this.s.writeConcern; + } +}); + +Object.defineProperty(Db.prototype, 'namespace', { + enumerable: true, + get: function() { + return this.s.namespace.toString(); + } +}); + +/** + * Execute a command + * @method + * @param {object} command The command hash + * @param {object} [options] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.command = function(command, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = Object.assign({}, options); + + const commandOperation = new CommandOperation(this, options, null, command); + + return executeOperation(this.s.topology, commandOperation, callback); +}; + +/** + * Execute an aggregation framework pipeline against the database, needs MongoDB >= 3.6 + * @method + * @param {object} [pipeline=[]] Array containing all the aggregation framework commands for the execution. + * @param {object} [options] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {object} [options.cursor] Return the query as cursor, on 2.6 > it returns as a real cursor on pre 2.6 it returns as an emulated cursor. + * @param {number} [options.cursor.batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. + * @param {boolean} [options.explain=false] Explain returns the aggregation execution plan (requires mongodb 2.6 >). + * @param {boolean} [options.allowDiskUse=false] allowDiskUse lets the server know if it can use disk to store temporary results for the aggregation (requires mongodb 2.6 >). + * @param {number} [options.maxTimeMS] maxTimeMS specifies a cumulative time limit in milliseconds for processing operations on the cursor. MongoDB interrupts the operation at the earliest following interrupt point. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. + * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution. + * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. + * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. + * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). + * @param {string} [options.comment] Add a comment to an aggregation command + * @param {string|object} [options.hint] Add an index selection hint to an aggregation command + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Database~aggregationCallback} callback The command result callback + * @return {(null|AggregationCursor)} + */ +Db.prototype.aggregate = function(pipeline, options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + + // If we have no options or callback we are doing + // a cursor based aggregation + if (options == null && callback == null) { + options = {}; + } + + const cursor = new AggregationCursor( + this.s.topology, + new AggregateOperation(this, pipeline, options), + options + ); + + // TODO: remove this when NODE-2074 is resolved + if (typeof callback === 'function') { + callback(null, cursor); + return; + } + + return cursor; +}; + +/** + * Return the Admin db instance + * @method + * @return {Admin} return the new Admin db instance + */ +Db.prototype.admin = function() { + const Admin = require('./admin'); + + return new Admin(this, this.s.topology, this.s.promiseLibrary); +}; + +/** + * The callback format for the collection method, must be used if strict is specified + * @callback Db~collectionResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection} collection The collection instance. + */ + +/** + * The callback format for an aggregation call + * @callback Database~aggregationCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {AggregationCursor} cursor The cursor if the aggregation command was executed successfully. + */ + +const collectionKeys = [ + 'pkFactory', + 'readPreference', + 'serializeFunctions', + 'strict', + 'readConcern', + 'ignoreUndefined', + 'promoteValues', + 'promoteBuffers', + 'promoteLongs' +]; + +/** + * Fetch a specific collection (containing the actual collection information). If the application does not use strict mode you + * can use it without a callback in the following way: `const collection = db.collection('mycollection');` + * + * @method + * @param {string} name the collection name we wish to access. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. + * @param {object} [options.pkFactory] A primary key factory object for generation of custom _id keys. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {boolean} [options.strict=false] Returns an error if the collection does not exist + * @param {object} [options.readConcern] Specify a read concern for the collection. (only MongoDB 3.2 or higher supported) + * @param {ReadConcernLevel} [options.readConcern.level='local'] Specify a read concern level for the collection operations (only MongoDB 3.2 or higher supported) + * @param {Db~collectionResultCallback} [callback] The collection result callback + * @return {Collection} return the new Collection instance if not in strict mode + */ +Db.prototype.collection = function(name, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + options = Object.assign({}, options); + + // Set the promise library + options.promiseLibrary = this.s.promiseLibrary; + + // If we have not set a collection level readConcern set the db level one + options.readConcern = options.readConcern + ? new ReadConcern(options.readConcern.level) + : this.readConcern; + + // Do we have ignoreUndefined set + if (this.s.options.ignoreUndefined) { + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + // Merge in all needed options and ensure correct writeConcern merging from db level + options = mergeOptionsAndWriteConcern(options, this.s.options, collectionKeys, true); + + // Execute + if (options == null || !options.strict) { + try { + const collection = new Collection( + this, + this.s.topology, + this.databaseName, + name, + this.s.pkFactory, + options + ); + if (callback) callback(null, collection); + return collection; + } catch (err) { + if (err instanceof MongoError && callback) return callback(err); + throw err; + } + } + + // Strict mode + if (typeof callback !== 'function') { + throw toError(`A callback is required in strict mode. While getting collection ${name}`); + } + + // Did the user destroy the topology + if (this.serverConfig && this.serverConfig.isDestroyed()) { + return callback(new MongoError('topology was destroyed')); + } + + const listCollectionOptions = Object.assign({}, options, { nameOnly: true }); + + // Strict mode + this.listCollections({ name: name }, listCollectionOptions).toArray((err, collections) => { + if (err != null) return handleCallback(callback, err, null); + if (collections.length === 0) + return handleCallback( + callback, + toError(`Collection ${name} does not exist. Currently in strict mode.`), + null + ); + + try { + return handleCallback( + callback, + null, + new Collection(this, this.s.topology, this.databaseName, name, this.s.pkFactory, options) + ); + } catch (err) { + return handleCallback(callback, err, null); + } + }); +}; + +/** + * Create a new collection on a server with the specified options. Use this to create capped collections. + * More information about command options available at https://docs.mongodb.com/manual/reference/command/create/ + * + * @method + * @param {string} name the collection name we wish to access. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. + * @param {object} [options.pkFactory] A primary key factory object for generation of custom _id keys. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {boolean} [options.strict=false] Returns an error if the collection does not exist + * @param {boolean} [options.capped=false] Create a capped collection. + * @param {boolean} [options.autoIndexId=true] DEPRECATED: Create an index on the _id field of the document, True by default on MongoDB 2.6 - 3.0 + * @param {number} [options.size] The size of the capped collection in bytes. + * @param {number} [options.max] The maximum number of documents in the capped collection. + * @param {number} [options.flags] Optional. Available for the MMAPv1 storage engine only to set the usePowerOf2Sizes and the noPadding flag. + * @param {object} [options.storageEngine] Allows users to specify configuration to the storage engine on a per-collection basis when creating a collection on MongoDB 3.0 or higher. + * @param {object} [options.validator] Allows users to specify validation rules or expressions for the collection. For more information, see Document Validation on MongoDB 3.2 or higher. + * @param {string} [options.validationLevel] Determines how strictly MongoDB applies the validation rules to existing documents during an update on MongoDB 3.2 or higher. + * @param {string} [options.validationAction] Determines whether to error on invalid documents or just warn about the violations but allow invalid documents to be inserted on MongoDB 3.2 or higher. + * @param {object} [options.indexOptionDefaults] Allows users to specify a default configuration for indexes when creating a collection on MongoDB 3.2 or higher. + * @param {string} [options.viewOn] The name of the source collection or view from which to create the view. The name is not the full namespace of the collection or view; i.e. does not include the database name and implies the same database as the view to create on MongoDB 3.4 or higher. + * @param {array} [options.pipeline] An array that consists of the aggregation pipeline stage. Creates the view by applying the specified pipeline to the viewOn collection or view on MongoDB 3.4 or higher. + * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~collectionResultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.createCollection = deprecateOptions( + { + name: 'Db.createCollection', + deprecatedOptions: ['autoIndexId'], + optionsIndex: 1 + }, + function(name, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + options.promiseLibrary = options.promiseLibrary || this.s.promiseLibrary; + options.readConcern = options.readConcern + ? new ReadConcern(options.readConcern.level) + : this.readConcern; + const createCollectionOperation = new CreateCollectionOperation(this, name, options); + + return executeOperation(this.s.topology, createCollectionOperation, callback); + } +); + +/** + * Get all the db statistics. + * + * @method + * @param {object} [options] Optional settings. + * @param {number} [options.scale] Divide the returned sizes by scale value. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~resultCallback} [callback] The collection result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.stats = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + // Build command object + const commandObject = { dbStats: true }; + // Check if we have the scale value + if (options['scale'] != null) commandObject['scale'] = options['scale']; + + // If we have a readPreference set + if (options.readPreference == null && this.s.readPreference) { + options.readPreference = this.s.readPreference; + } + + const statsOperation = new CommandOperation(this, options, null, commandObject); + + // Execute the command + return executeOperation(this.s.topology, statsOperation, callback); +}; + +/** + * Get the list of all collection information for the specified db. + * + * @method + * @param {object} [filter={}] Query to filter collections by + * @param {object} [options] Optional settings. + * @param {boolean} [options.nameOnly=false] Since 4.0: If true, will only return the collection name in the response, and will omit additional info + * @param {number} [options.batchSize=1000] The batchSize for the returned command cursor or if pre 2.8 the systems batch collection + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {ClientSession} [options.session] optional session to use for this operation + * @return {CommandCursor} + */ +Db.prototype.listCollections = function(filter, options) { + filter = filter || {}; + options = options || {}; + + return new CommandCursor( + this.s.topology, + new ListCollectionsOperation(this, filter, options), + options + ); +}; + +/** + * Evaluate JavaScript on the server + * + * @method + * @param {Code} code JavaScript to execute on server. + * @param {(object|array)} parameters The parameters for the call. + * @param {object} [options] Optional settings. + * @param {boolean} [options.nolock=false] Tell MongoDB not to block on the evaluation of the javascript. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~resultCallback} [callback] The results callback + * @deprecated Eval is deprecated on MongoDB 3.2 and forward + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.eval = deprecate(function(code, parameters, options, callback) { + const args = Array.prototype.slice.call(arguments, 1); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + parameters = args.length ? args.shift() : parameters; + options = args.length ? args.shift() || {} : {}; + + return executeLegacyOperation(this.s.topology, evaluate, [ + this, + code, + parameters, + options, + callback + ]); +}, 'Db.eval is deprecated as of MongoDB version 3.2'); + +/** + * Rename a collection. + * + * @method + * @param {string} fromCollection Name of current collection to rename. + * @param {string} toCollection New name of of the collection. + * @param {object} [options] Optional settings. + * @param {boolean} [options.dropTarget=false] Drop the target name collection if it previously exists. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~collectionResultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.renameCollection = function(fromCollection, toCollection, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = Object.assign({}, options, { readPreference: ReadPreference.PRIMARY }); + + // Add return new collection + options.new_collection = true; + + const renameOperation = new RenameOperation( + this.collection(fromCollection), + toCollection, + options + ); + + return executeOperation(this.s.topology, renameOperation, callback); +}; + +/** + * Drop a collection from the database, removing it permanently. New accesses will create a new collection. + * + * @method + * @param {string} name Name of collection to drop + * @param {Object} [options] Optional settings + * @param {WriteConcern} [options.writeConcern] A full WriteConcern object + * @param {(number|string)} [options.w] The write concern + * @param {number} [options.wtimeout] The write concern timeout + * @param {boolean} [options.j] The journal write concern + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~resultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.dropCollection = function(name, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const dropCollectionOperation = new DropCollectionOperation(this, name, options); + + return executeOperation(this.s.topology, dropCollectionOperation, callback); +}; + +/** + * Drop a database, removing it permanently from the server. + * + * @method + * @param {Object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~resultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.dropDatabase = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const dropDatabaseOperation = new DropDatabaseOperation(this, options); + + return executeOperation(this.s.topology, dropDatabaseOperation, callback); +}; + +/** + * Fetch all collections for the current db. + * + * @method + * @param {Object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~collectionsResultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.collections = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const collectionsOperation = new CollectionsOperation(this, options); + + return executeOperation(this.s.topology, collectionsOperation, callback); +}; + +/** + * Runs a command on the database as admin. + * @method + * @param {object} command The command hash + * @param {object} [options] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.executeDbAdminCommand = function(selector, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + options.readPreference = resolveReadPreference(this, options); + + const executeDbAdminCommandOperation = new ExecuteDbAdminCommandOperation( + this, + selector, + options + ); + + return executeOperation(this.s.topology, executeDbAdminCommandOperation, callback); +}; + +/** + * Creates an index on the db and collection. + * @method + * @param {string} name Name of the collection to create the index on. + * @param {(string|object)} fieldOrSpec Defines the index. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.unique=false] Creates an unique index. + * @param {boolean} [options.sparse=false] Creates a sparse index. + * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. + * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value + * @param {number} [options.min] For geospatial indexes set the lower bound for the co-ordinates. + * @param {number} [options.max] For geospatial indexes set the high bound for the co-ordinates. + * @param {number} [options.v] Specify the format version of the indexes. + * @param {number} [options.expireAfterSeconds] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) + * @param {string} [options.name] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) + * @param {object} [options.partialFilterExpression] Creates a partial index based on the given filter object (MongoDB 3.2 or higher) + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.createIndex = function(name, fieldOrSpec, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options ? Object.assign({}, options) : {}; + + const createIndexOperation = new CreateIndexOperation(this, name, fieldOrSpec, options); + + return executeOperation(this.s.topology, createIndexOperation, callback); +}; + +/** + * Ensures that an index exists, if it does not it creates it + * @method + * @deprecated since version 2.0 + * @param {string} name The index name + * @param {(string|object)} fieldOrSpec Defines the index. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.unique=false] Creates an unique index. + * @param {boolean} [options.sparse=false] Creates a sparse index. + * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. + * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value + * @param {number} [options.min] For geospatial indexes set the lower bound for the co-ordinates. + * @param {number} [options.max] For geospatial indexes set the high bound for the co-ordinates. + * @param {number} [options.v] Specify the format version of the indexes. + * @param {number} [options.expireAfterSeconds] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) + * @param {number} [options.name] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.ensureIndex = deprecate(function(name, fieldOrSpec, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeLegacyOperation(this.s.topology, ensureIndex, [ + this, + name, + fieldOrSpec, + options, + callback + ]); +}, 'Db.ensureIndex is deprecated as of MongoDB version 3.0 / driver version 2.0'); + +Db.prototype.addChild = function(db) { + if (this.s.parentDb) return this.s.parentDb.addChild(db); + this.s.children.push(db); +}; + +/** + * Add a user to the database. + * @method + * @param {string} username The username. + * @param {string} password The password. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {object} [options.customData] Custom data associated with the user (only Mongodb 2.6 or higher) + * @param {object[]} [options.roles] Roles associated with the created user (only Mongodb 2.6 or higher) + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.addUser = function(username, password, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + // Special case where there is no password ($external users) + if (typeof username === 'string' && password != null && typeof password === 'object') { + options = password; + password = null; + } + + const addUserOperation = new AddUserOperation(this, username, password, options); + + return executeOperation(this.s.topology, addUserOperation, callback); +}; + +/** + * Remove a user from a database + * @method + * @param {string} username The username. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.removeUser = function(username, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const removeUserOperation = new RemoveUserOperation(this, username, options); + + return executeOperation(this.s.topology, removeUserOperation, callback); +}; + +/** + * Set the current profiling level of MongoDB + * + * @param {string} level The new profiling level (off, slow_only, all). + * @param {Object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~resultCallback} [callback] The command result callback. + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.setProfilingLevel = function(level, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const setProfilingLevelOperation = new SetProfilingLevelOperation(this, level, options); + + return executeOperation(this.s.topology, setProfilingLevelOperation, callback); +}; + +/** + * Retrieve the current profiling information for MongoDB + * + * @param {Object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~resultCallback} [callback] The command result callback. + * @return {Promise} returns Promise if no callback passed + * @deprecated Query the system.profile collection directly. + */ +Db.prototype.profilingInfo = deprecate(function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeLegacyOperation(this.s.topology, profilingInfo, [this, options, callback]); +}, 'Db.profilingInfo is deprecated. Query the system.profile collection directly.'); + +/** + * Retrieve the current profiling Level for MongoDB + * + * @param {Object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.profilingLevel = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const profilingLevelOperation = new ProfilingLevelOperation(this, options); + + return executeOperation(this.s.topology, profilingLevelOperation, callback); +}; + +/** + * Retrieves this collections index info. + * @method + * @param {string} name The name of the collection. + * @param {object} [options] Optional settings. + * @param {boolean} [options.full=false] Returns the full raw index information. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.indexInformation = function(name, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const indexInformationOperation = new IndexInformationOperation(this, name, options); + + return executeOperation(this.s.topology, indexInformationOperation, callback); +}; + +/** + * Unref all sockets + * @method + */ +Db.prototype.unref = function() { + this.s.topology.unref(); +}; + +/** + * Create a new Change Stream, watching for new changes (insertions, updates, replacements, deletions, and invalidations) in this database. Will ignore all changes to system collections. + * @method + * @since 3.1.0 + * @param {Array} [pipeline] An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents. + * @param {object} [options] Optional settings + * @param {string} [options.fullDocument='default'] Allowed values: ‘default’, ‘updateLookup’. When set to ‘updateLookup’, the change stream will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred. + * @param {object} [options.resumeAfter] Specifies the logical starting point for the new change stream. This should be the _id field from a previously returned change stream document. + * @param {number} [options.maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a change stream query + * @param {number} [options.batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. + * @param {object} [options.collation] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. + * @param {ReadPreference} [options.readPreference] The read preference. Defaults to the read preference of the database. See {@link https://docs.mongodb.com/manual/reference/read-preference|read preference documentation}. + * @param {Timestamp} [options.startAtOperationTime] receive change events that occur after the specified timestamp + * @param {ClientSession} [options.session] optional session to use for this operation + * @return {ChangeStream} a ChangeStream instance. + */ +Db.prototype.watch = function(pipeline, options) { + pipeline = pipeline || []; + options = options || {}; + + // Allow optionally not specifying a pipeline + if (!Array.isArray(pipeline)) { + options = pipeline; + pipeline = []; + } + + return new ChangeStream(this, pipeline, options); +}; + +/** + * Return the db logger + * @method + * @return {Logger} return the db logger + * @ignore + */ +Db.prototype.getLogger = function() { + return this.s.logger; +}; + +/** + * Db close event + * + * Emitted after a socket closed against a single server or mongos proxy. + * + * @event Db#close + * @type {MongoError} + */ + +/** + * Db reconnect event + * + * * Server: Emitted when the driver has reconnected and re-authenticated. + * * ReplicaSet: N/A + * * Mongos: Emitted when the driver reconnects and re-authenticates successfully against a Mongos. + * + * @event Db#reconnect + * @type {object} + */ + +/** + * Db error event + * + * Emitted after an error occurred against a single server or mongos proxy. + * + * @event Db#error + * @type {MongoError} + */ + +/** + * Db timeout event + * + * Emitted after a socket timeout occurred against a single server or mongos proxy. + * + * @event Db#timeout + * @type {MongoError} + */ + +/** + * Db parseError event + * + * The parseError event is emitted if the driver detects illegal or corrupt BSON being received from the server. + * + * @event Db#parseError + * @type {MongoError} + */ + +/** + * Db fullsetup event, emitted when all servers in the topology have been connected to at start up time. + * + * * Server: Emitted when the driver has connected to the single server and has authenticated. + * * ReplSet: Emitted after the driver has attempted to connect to all replicaset members. + * * Mongos: Emitted after the driver has attempted to connect to all mongos proxies. + * + * @event Db#fullsetup + * @type {Db} + */ + +// Constants +Db.SYSTEM_NAMESPACE_COLLECTION = CONSTANTS.SYSTEM_NAMESPACE_COLLECTION; +Db.SYSTEM_INDEX_COLLECTION = CONSTANTS.SYSTEM_INDEX_COLLECTION; +Db.SYSTEM_PROFILE_COLLECTION = CONSTANTS.SYSTEM_PROFILE_COLLECTION; +Db.SYSTEM_USER_COLLECTION = CONSTANTS.SYSTEM_USER_COLLECTION; +Db.SYSTEM_COMMAND_COLLECTION = CONSTANTS.SYSTEM_COMMAND_COLLECTION; +Db.SYSTEM_JS_COLLECTION = CONSTANTS.SYSTEM_JS_COLLECTION; + +module.exports = Db; diff --git a/scripts/2.5/node_modules/mongodb/lib/dynamic_loaders.js b/scripts/2.5/node_modules/mongodb/lib/dynamic_loaders.js new file mode 100644 index 00000000..c4610023 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/dynamic_loaders.js @@ -0,0 +1,32 @@ +'use strict'; + +let collection; +let cursor; +let db; + +function loadCollection() { + if (!collection) { + collection = require('./collection'); + } + return collection; +} + +function loadCursor() { + if (!cursor) { + cursor = require('./cursor'); + } + return cursor; +} + +function loadDb() { + if (!db) { + db = require('./db'); + } + return db; +} + +module.exports = { + loadCollection, + loadCursor, + loadDb +}; diff --git a/scripts/2.5/node_modules/mongodb/lib/error.js b/scripts/2.5/node_modules/mongodb/lib/error.js new file mode 100644 index 00000000..4d104e9b --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/error.js @@ -0,0 +1,45 @@ +'use strict'; + +const MongoNetworkError = require('./core').MongoNetworkError; +const mongoErrorContextSymbol = require('./core').mongoErrorContextSymbol; + +const GET_MORE_NON_RESUMABLE_CODES = new Set([ + 136, // CappedPositionLost + 237, // CursorKilled + 11601 // Interrupted +]); + +// From spec@https://github.com/mongodb/specifications/blob/7a2e93d85935ee4b1046a8d2ad3514c657dc74fa/source/change-streams/change-streams.rst#resumable-error: +// +// An error is considered resumable if it meets any of the following criteria: +// - any error encountered which is not a server error (e.g. a timeout error or network error) +// - any server error response from a getMore command excluding those containing the error label +// NonRetryableChangeStreamError and those containing the following error codes: +// - Interrupted: 11601 +// - CappedPositionLost: 136 +// - CursorKilled: 237 +// +// An error on an aggregate command is not a resumable error. Only errors on a getMore command may be considered resumable errors. + +function isGetMoreError(error) { + if (error[mongoErrorContextSymbol]) { + return error[mongoErrorContextSymbol].isGetMore; + } +} + +function isResumableError(error) { + if (!isGetMoreError(error)) { + return false; + } + + if (error instanceof MongoNetworkError) { + return true; + } + + return !( + GET_MORE_NON_RESUMABLE_CODES.has(error.code) || + error.hasErrorLabel('NonRetryableChangeStreamError') + ); +} + +module.exports = { GET_MORE_NON_RESUMABLE_CODES, isResumableError }; diff --git a/scripts/2.5/node_modules/mongodb/lib/gridfs-stream/download.js b/scripts/2.5/node_modules/mongodb/lib/gridfs-stream/download.js new file mode 100644 index 00000000..dfb1de57 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/gridfs-stream/download.js @@ -0,0 +1,421 @@ +'use strict'; + +var stream = require('stream'), + util = require('util'); + +module.exports = GridFSBucketReadStream; + +/** + * A readable stream that enables you to read buffers from GridFS. + * + * Do not instantiate this class directly. Use `openDownloadStream()` instead. + * + * @class + * @param {Collection} chunks Handle for chunks collection + * @param {Collection} files Handle for files collection + * @param {Object} readPreference The read preference to use + * @param {Object} filter The query to use to find the file document + * @param {Object} [options] Optional settings. + * @param {Number} [options.sort] Optional sort for the file find query + * @param {Number} [options.skip] Optional skip for the file find query + * @param {Number} [options.start] Optional 0-based offset in bytes to start streaming from + * @param {Number} [options.end] Optional 0-based offset in bytes to stop streaming before + * @fires GridFSBucketReadStream#error + * @fires GridFSBucketReadStream#file + * @return {GridFSBucketReadStream} a GridFSBucketReadStream instance. + */ + +function GridFSBucketReadStream(chunks, files, readPreference, filter, options) { + this.s = { + bytesRead: 0, + chunks: chunks, + cursor: null, + expected: 0, + files: files, + filter: filter, + init: false, + expectedEnd: 0, + file: null, + options: options, + readPreference: readPreference + }; + + stream.Readable.call(this); +} + +util.inherits(GridFSBucketReadStream, stream.Readable); + +/** + * An error occurred + * + * @event GridFSBucketReadStream#error + * @type {Error} + */ + +/** + * Fires when the stream loaded the file document corresponding to the + * provided id. + * + * @event GridFSBucketReadStream#file + * @type {object} + */ + +/** + * Emitted when a chunk of data is available to be consumed. + * + * @event GridFSBucketReadStream#data + * @type {object} + */ + +/** + * Fired when the stream is exhausted (no more data events). + * + * @event GridFSBucketReadStream#end + * @type {object} + */ + +/** + * Fired when the stream is exhausted and the underlying cursor is killed + * + * @event GridFSBucketReadStream#close + * @type {object} + */ + +/** + * Reads from the cursor and pushes to the stream. + * @method + */ + +GridFSBucketReadStream.prototype._read = function() { + var _this = this; + if (this.destroyed) { + return; + } + + waitForFile(_this, function() { + doRead(_this); + }); +}; + +/** + * Sets the 0-based offset in bytes to start streaming from. Throws + * an error if this stream has entered flowing mode + * (e.g. if you've already called `on('data')`) + * @method + * @param {Number} start Offset in bytes to start reading at + * @return {GridFSBucketReadStream} + */ + +GridFSBucketReadStream.prototype.start = function(start) { + throwIfInitialized(this); + this.s.options.start = start; + return this; +}; + +/** + * Sets the 0-based offset in bytes to start streaming from. Throws + * an error if this stream has entered flowing mode + * (e.g. if you've already called `on('data')`) + * @method + * @param {Number} end Offset in bytes to stop reading at + * @return {GridFSBucketReadStream} + */ + +GridFSBucketReadStream.prototype.end = function(end) { + throwIfInitialized(this); + this.s.options.end = end; + return this; +}; + +/** + * Marks this stream as aborted (will never push another `data` event) + * and kills the underlying cursor. Will emit the 'end' event, and then + * the 'close' event once the cursor is successfully killed. + * + * @method + * @param {GridFSBucket~errorCallback} [callback] called when the cursor is successfully closed or an error occurred. + * @fires GridFSBucketWriteStream#close + * @fires GridFSBucketWriteStream#end + */ + +GridFSBucketReadStream.prototype.abort = function(callback) { + var _this = this; + this.push(null); + this.destroyed = true; + if (this.s.cursor) { + this.s.cursor.close(function(error) { + _this.emit('close'); + callback && callback(error); + }); + } else { + if (!this.s.init) { + // If not initialized, fire close event because we will never + // get a cursor + _this.emit('close'); + } + callback && callback(); + } +}; + +/** + * @ignore + */ + +function throwIfInitialized(self) { + if (self.s.init) { + throw new Error('You cannot change options after the stream has entered' + 'flowing mode!'); + } +} + +/** + * @ignore + */ + +function doRead(_this) { + if (_this.destroyed) { + return; + } + + _this.s.cursor.next(function(error, doc) { + if (_this.destroyed) { + return; + } + if (error) { + return __handleError(_this, error); + } + if (!doc) { + _this.push(null); + + process.nextTick(() => { + _this.s.cursor.close(function(error) { + if (error) { + __handleError(_this, error); + return; + } + + _this.emit('close'); + }); + }); + + return; + } + + var bytesRemaining = _this.s.file.length - _this.s.bytesRead; + var expectedN = _this.s.expected++; + var expectedLength = Math.min(_this.s.file.chunkSize, bytesRemaining); + + if (doc.n > expectedN) { + var errmsg = 'ChunkIsMissing: Got unexpected n: ' + doc.n + ', expected: ' + expectedN; + return __handleError(_this, new Error(errmsg)); + } + + if (doc.n < expectedN) { + errmsg = 'ExtraChunk: Got unexpected n: ' + doc.n + ', expected: ' + expectedN; + return __handleError(_this, new Error(errmsg)); + } + + var buf = Buffer.isBuffer(doc.data) ? doc.data : doc.data.buffer; + + if (buf.length !== expectedLength) { + if (bytesRemaining <= 0) { + errmsg = 'ExtraChunk: Got unexpected n: ' + doc.n; + return __handleError(_this, new Error(errmsg)); + } + + errmsg = + 'ChunkIsWrongSize: Got unexpected length: ' + buf.length + ', expected: ' + expectedLength; + return __handleError(_this, new Error(errmsg)); + } + + _this.s.bytesRead += buf.length; + + if (buf.length === 0) { + return _this.push(null); + } + + var sliceStart = null; + var sliceEnd = null; + + if (_this.s.bytesToSkip != null) { + sliceStart = _this.s.bytesToSkip; + _this.s.bytesToSkip = 0; + } + + const atEndOfStream = expectedN === _this.s.expectedEnd - 1; + const bytesLeftToRead = _this.s.options.end - _this.s.bytesToSkip; + if (atEndOfStream && _this.s.bytesToTrim != null) { + sliceEnd = _this.s.file.chunkSize - _this.s.bytesToTrim; + } else if (_this.s.options.end && bytesLeftToRead < doc.data.length()) { + sliceEnd = bytesLeftToRead; + } + + if (sliceStart != null || sliceEnd != null) { + buf = buf.slice(sliceStart || 0, sliceEnd || buf.length); + } + + _this.push(buf); + }); +} + +/** + * @ignore + */ + +function init(self) { + var findOneOptions = {}; + if (self.s.readPreference) { + findOneOptions.readPreference = self.s.readPreference; + } + if (self.s.options && self.s.options.sort) { + findOneOptions.sort = self.s.options.sort; + } + if (self.s.options && self.s.options.skip) { + findOneOptions.skip = self.s.options.skip; + } + + self.s.files.findOne(self.s.filter, findOneOptions, function(error, doc) { + if (error) { + return __handleError(self, error); + } + if (!doc) { + var identifier = self.s.filter._id ? self.s.filter._id.toString() : self.s.filter.filename; + var errmsg = 'FileNotFound: file ' + identifier + ' was not found'; + var err = new Error(errmsg); + err.code = 'ENOENT'; + return __handleError(self, err); + } + + // If document is empty, kill the stream immediately and don't + // execute any reads + if (doc.length <= 0) { + self.push(null); + return; + } + + if (self.destroyed) { + // If user destroys the stream before we have a cursor, wait + // until the query is done to say we're 'closed' because we can't + // cancel a query. + self.emit('close'); + return; + } + + self.s.bytesToSkip = handleStartOption(self, doc, self.s.options); + + var filter = { files_id: doc._id }; + + // Currently (MongoDB 3.4.4) skip function does not support the index, + // it needs to retrieve all the documents first and then skip them. (CS-25811) + // As work around we use $gte on the "n" field. + if (self.s.options && self.s.options.start != null) { + var skip = Math.floor(self.s.options.start / doc.chunkSize); + if (skip > 0) { + filter['n'] = { $gte: skip }; + } + } + self.s.cursor = self.s.chunks.find(filter).sort({ n: 1 }); + + if (self.s.readPreference) { + self.s.cursor.setReadPreference(self.s.readPreference); + } + + self.s.expectedEnd = Math.ceil(doc.length / doc.chunkSize); + self.s.file = doc; + self.s.bytesToTrim = handleEndOption(self, doc, self.s.cursor, self.s.options); + self.emit('file', doc); + }); +} + +/** + * @ignore + */ + +function waitForFile(_this, callback) { + if (_this.s.file) { + return callback(); + } + + if (!_this.s.init) { + init(_this); + _this.s.init = true; + } + + _this.once('file', function() { + callback(); + }); +} + +/** + * @ignore + */ + +function handleStartOption(stream, doc, options) { + if (options && options.start != null) { + if (options.start > doc.length) { + throw new Error( + 'Stream start (' + + options.start + + ') must not be ' + + 'more than the length of the file (' + + doc.length + + ')' + ); + } + if (options.start < 0) { + throw new Error('Stream start (' + options.start + ') must not be ' + 'negative'); + } + if (options.end != null && options.end < options.start) { + throw new Error( + 'Stream start (' + + options.start + + ') must not be ' + + 'greater than stream end (' + + options.end + + ')' + ); + } + + stream.s.bytesRead = Math.floor(options.start / doc.chunkSize) * doc.chunkSize; + stream.s.expected = Math.floor(options.start / doc.chunkSize); + + return options.start - stream.s.bytesRead; + } +} + +/** + * @ignore + */ + +function handleEndOption(stream, doc, cursor, options) { + if (options && options.end != null) { + if (options.end > doc.length) { + throw new Error( + 'Stream end (' + + options.end + + ') must not be ' + + 'more than the length of the file (' + + doc.length + + ')' + ); + } + if (options.start < 0) { + throw new Error('Stream end (' + options.end + ') must not be ' + 'negative'); + } + + var start = options.start != null ? Math.floor(options.start / doc.chunkSize) : 0; + + cursor.limit(Math.ceil(options.end / doc.chunkSize) - start); + + stream.s.expectedEnd = Math.ceil(options.end / doc.chunkSize); + + return Math.ceil(options.end / doc.chunkSize) * doc.chunkSize - options.end; + } +} + +/** + * @ignore + */ + +function __handleError(_this, error) { + _this.emit('error', error); +} diff --git a/scripts/2.5/node_modules/mongodb/lib/gridfs-stream/index.js b/scripts/2.5/node_modules/mongodb/lib/gridfs-stream/index.js new file mode 100644 index 00000000..93b45ebf --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/gridfs-stream/index.js @@ -0,0 +1,358 @@ +'use strict'; + +var Emitter = require('events').EventEmitter; +var GridFSBucketReadStream = require('./download'); +var GridFSBucketWriteStream = require('./upload'); +var shallowClone = require('../utils').shallowClone; +var toError = require('../utils').toError; +var util = require('util'); +var executeLegacyOperation = require('../utils').executeLegacyOperation; + +var DEFAULT_GRIDFS_BUCKET_OPTIONS = { + bucketName: 'fs', + chunkSizeBytes: 255 * 1024 +}; + +module.exports = GridFSBucket; + +/** + * Constructor for a streaming GridFS interface + * @class + * @param {Db} db A db handle + * @param {object} [options] Optional settings. + * @param {string} [options.bucketName="fs"] The 'files' and 'chunks' collections will be prefixed with the bucket name followed by a dot. + * @param {number} [options.chunkSizeBytes=255 * 1024] Number of bytes stored in each chunk. Defaults to 255KB + * @param {object} [options.writeConcern] Optional write concern to be passed to write operations, for instance `{ w: 1 }` + * @param {object} [options.readPreference] Optional read preference to be passed to read operations + * @fires GridFSBucketWriteStream#index + * @return {GridFSBucket} + */ + +function GridFSBucket(db, options) { + Emitter.apply(this); + this.setMaxListeners(0); + + if (options && typeof options === 'object') { + options = shallowClone(options); + var keys = Object.keys(DEFAULT_GRIDFS_BUCKET_OPTIONS); + for (var i = 0; i < keys.length; ++i) { + if (!options[keys[i]]) { + options[keys[i]] = DEFAULT_GRIDFS_BUCKET_OPTIONS[keys[i]]; + } + } + } else { + options = DEFAULT_GRIDFS_BUCKET_OPTIONS; + } + + this.s = { + db: db, + options: options, + _chunksCollection: db.collection(options.bucketName + '.chunks'), + _filesCollection: db.collection(options.bucketName + '.files'), + checkedIndexes: false, + calledOpenUploadStream: false, + promiseLibrary: db.s.promiseLibrary || Promise + }; +} + +util.inherits(GridFSBucket, Emitter); + +/** + * When the first call to openUploadStream is made, the upload stream will + * check to see if it needs to create the proper indexes on the chunks and + * files collections. This event is fired either when 1) it determines that + * no index creation is necessary, 2) when it successfully creates the + * necessary indexes. + * + * @event GridFSBucket#index + * @type {Error} + */ + +/** + * Returns a writable stream (GridFSBucketWriteStream) for writing + * buffers to GridFS. The stream's 'id' property contains the resulting + * file's id. + * @method + * @param {string} filename The value of the 'filename' key in the files doc + * @param {object} [options] Optional settings. + * @param {number} [options.chunkSizeBytes] Optional overwrite this bucket's chunkSizeBytes for this file + * @param {object} [options.metadata] Optional object to store in the file document's `metadata` field + * @param {string} [options.contentType] Optional string to store in the file document's `contentType` field + * @param {array} [options.aliases] Optional array of strings to store in the file document's `aliases` field + * @param {boolean} [options.disableMD5=false] If true, disables adding an md5 field to file data + * @return {GridFSBucketWriteStream} + */ + +GridFSBucket.prototype.openUploadStream = function(filename, options) { + if (options) { + options = shallowClone(options); + } else { + options = {}; + } + if (!options.chunkSizeBytes) { + options.chunkSizeBytes = this.s.options.chunkSizeBytes; + } + return new GridFSBucketWriteStream(this, filename, options); +}; + +/** + * Returns a writable stream (GridFSBucketWriteStream) for writing + * buffers to GridFS for a custom file id. The stream's 'id' property contains the resulting + * file's id. + * @method + * @param {string|number|object} id A custom id used to identify the file + * @param {string} filename The value of the 'filename' key in the files doc + * @param {object} [options] Optional settings. + * @param {number} [options.chunkSizeBytes] Optional overwrite this bucket's chunkSizeBytes for this file + * @param {object} [options.metadata] Optional object to store in the file document's `metadata` field + * @param {string} [options.contentType] Optional string to store in the file document's `contentType` field + * @param {array} [options.aliases] Optional array of strings to store in the file document's `aliases` field + * @param {boolean} [options.disableMD5=false] If true, disables adding an md5 field to file data + * @return {GridFSBucketWriteStream} + */ + +GridFSBucket.prototype.openUploadStreamWithId = function(id, filename, options) { + if (options) { + options = shallowClone(options); + } else { + options = {}; + } + + if (!options.chunkSizeBytes) { + options.chunkSizeBytes = this.s.options.chunkSizeBytes; + } + + options.id = id; + + return new GridFSBucketWriteStream(this, filename, options); +}; + +/** + * Returns a readable stream (GridFSBucketReadStream) for streaming file + * data from GridFS. + * @method + * @param {ObjectId} id The id of the file doc + * @param {Object} [options] Optional settings. + * @param {Number} [options.start] Optional 0-based offset in bytes to start streaming from + * @param {Number} [options.end] Optional 0-based offset in bytes to stop streaming before + * @return {GridFSBucketReadStream} + */ + +GridFSBucket.prototype.openDownloadStream = function(id, options) { + var filter = { _id: id }; + options = { + start: options && options.start, + end: options && options.end + }; + + return new GridFSBucketReadStream( + this.s._chunksCollection, + this.s._filesCollection, + this.s.options.readPreference, + filter, + options + ); +}; + +/** + * Deletes a file with the given id + * @method + * @param {ObjectId} id The id of the file doc + * @param {GridFSBucket~errorCallback} [callback] + */ + +GridFSBucket.prototype.delete = function(id, callback) { + return executeLegacyOperation(this.s.db.s.topology, _delete, [this, id, callback], { + skipSessions: true + }); +}; + +/** + * @ignore + */ + +function _delete(_this, id, callback) { + _this.s._filesCollection.deleteOne({ _id: id }, function(error, res) { + if (error) { + return callback(error); + } + + _this.s._chunksCollection.deleteMany({ files_id: id }, function(error) { + if (error) { + return callback(error); + } + + // Delete orphaned chunks before returning FileNotFound + if (!res.result.n) { + var errmsg = 'FileNotFound: no file with id ' + id + ' found'; + return callback(new Error(errmsg)); + } + + callback(); + }); + }); +} + +/** + * Convenience wrapper around find on the files collection + * @method + * @param {Object} filter + * @param {Object} [options] Optional settings for cursor + * @param {number} [options.batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/find|find command documentation}. + * @param {number} [options.limit] Optional limit for cursor + * @param {number} [options.maxTimeMS] Optional maxTimeMS for cursor + * @param {boolean} [options.noCursorTimeout] Optionally set cursor's `noCursorTimeout` flag + * @param {number} [options.skip] Optional skip for cursor + * @param {object} [options.sort] Optional sort for cursor + * @return {Cursor} + */ + +GridFSBucket.prototype.find = function(filter, options) { + filter = filter || {}; + options = options || {}; + + var cursor = this.s._filesCollection.find(filter); + + if (options.batchSize != null) { + cursor.batchSize(options.batchSize); + } + if (options.limit != null) { + cursor.limit(options.limit); + } + if (options.maxTimeMS != null) { + cursor.maxTimeMS(options.maxTimeMS); + } + if (options.noCursorTimeout != null) { + cursor.addCursorFlag('noCursorTimeout', options.noCursorTimeout); + } + if (options.skip != null) { + cursor.skip(options.skip); + } + if (options.sort != null) { + cursor.sort(options.sort); + } + + return cursor; +}; + +/** + * Returns a readable stream (GridFSBucketReadStream) for streaming the + * file with the given name from GridFS. If there are multiple files with + * the same name, this will stream the most recent file with the given name + * (as determined by the `uploadDate` field). You can set the `revision` + * option to change this behavior. + * @method + * @param {String} filename The name of the file to stream + * @param {Object} [options] Optional settings + * @param {number} [options.revision=-1] The revision number relative to the oldest file with the given filename. 0 gets you the oldest file, 1 gets you the 2nd oldest, -1 gets you the newest. + * @param {Number} [options.start] Optional 0-based offset in bytes to start streaming from + * @param {Number} [options.end] Optional 0-based offset in bytes to stop streaming before + * @return {GridFSBucketReadStream} + */ + +GridFSBucket.prototype.openDownloadStreamByName = function(filename, options) { + var sort = { uploadDate: -1 }; + var skip = null; + if (options && options.revision != null) { + if (options.revision >= 0) { + sort = { uploadDate: 1 }; + skip = options.revision; + } else { + skip = -options.revision - 1; + } + } + + var filter = { filename: filename }; + options = { + sort: sort, + skip: skip, + start: options && options.start, + end: options && options.end + }; + return new GridFSBucketReadStream( + this.s._chunksCollection, + this.s._filesCollection, + this.s.options.readPreference, + filter, + options + ); +}; + +/** + * Renames the file with the given _id to the given string + * @method + * @param {ObjectId} id the id of the file to rename + * @param {String} filename new name for the file + * @param {GridFSBucket~errorCallback} [callback] + */ + +GridFSBucket.prototype.rename = function(id, filename, callback) { + return executeLegacyOperation(this.s.db.s.topology, _rename, [this, id, filename, callback], { + skipSessions: true + }); +}; + +/** + * @ignore + */ + +function _rename(_this, id, filename, callback) { + var filter = { _id: id }; + var update = { $set: { filename: filename } }; + _this.s._filesCollection.updateOne(filter, update, function(error, res) { + if (error) { + return callback(error); + } + if (!res.result.n) { + return callback(toError('File with id ' + id + ' not found')); + } + callback(); + }); +} + +/** + * Removes this bucket's files collection, followed by its chunks collection. + * @method + * @param {GridFSBucket~errorCallback} [callback] + */ + +GridFSBucket.prototype.drop = function(callback) { + return executeLegacyOperation(this.s.db.s.topology, _drop, [this, callback], { + skipSessions: true + }); +}; + +/** + * Return the db logger + * @method + * @return {Logger} return the db logger + * @ignore + */ +GridFSBucket.prototype.getLogger = function() { + return this.s.db.s.logger; +}; + +/** + * @ignore + */ + +function _drop(_this, callback) { + _this.s._filesCollection.drop(function(error) { + if (error) { + return callback(error); + } + _this.s._chunksCollection.drop(function(error) { + if (error) { + return callback(error); + } + + return callback(); + }); + }); +} + +/** + * Callback format for all GridFSBucket methods that can accept a callback. + * @callback GridFSBucket~errorCallback + * @param {MongoError} error An error instance representing any errors that occurred + */ diff --git a/scripts/2.5/node_modules/mongodb/lib/gridfs-stream/upload.js b/scripts/2.5/node_modules/mongodb/lib/gridfs-stream/upload.js new file mode 100644 index 00000000..3733f2cb --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/gridfs-stream/upload.js @@ -0,0 +1,538 @@ +'use strict'; + +var core = require('../core'); +var crypto = require('crypto'); +var stream = require('stream'); +var util = require('util'); +var Buffer = require('safe-buffer').Buffer; + +var ERROR_NAMESPACE_NOT_FOUND = 26; + +module.exports = GridFSBucketWriteStream; + +/** + * A writable stream that enables you to write buffers to GridFS. + * + * Do not instantiate this class directly. Use `openUploadStream()` instead. + * + * @class + * @param {GridFSBucket} bucket Handle for this stream's corresponding bucket + * @param {string} filename The value of the 'filename' key in the files doc + * @param {object} [options] Optional settings. + * @param {string|number|object} [options.id] Custom file id for the GridFS file. + * @param {number} [options.chunkSizeBytes] The chunk size to use, in bytes + * @param {number} [options.w] The write concern + * @param {number} [options.wtimeout] The write concern timeout + * @param {number} [options.j] The journal write concern + * @param {boolean} [options.disableMD5=false] If true, disables adding an md5 field to file data + * @fires GridFSBucketWriteStream#error + * @fires GridFSBucketWriteStream#finish + * @return {GridFSBucketWriteStream} a GridFSBucketWriteStream instance. + */ + +function GridFSBucketWriteStream(bucket, filename, options) { + options = options || {}; + this.bucket = bucket; + this.chunks = bucket.s._chunksCollection; + this.filename = filename; + this.files = bucket.s._filesCollection; + this.options = options; + // Signals the write is all done + this.done = false; + + this.id = options.id ? options.id : core.BSON.ObjectId(); + this.chunkSizeBytes = this.options.chunkSizeBytes; + this.bufToStore = Buffer.alloc(this.chunkSizeBytes); + this.length = 0; + this.md5 = !options.disableMD5 && crypto.createHash('md5'); + this.n = 0; + this.pos = 0; + this.state = { + streamEnd: false, + outstandingRequests: 0, + errored: false, + aborted: false, + promiseLibrary: this.bucket.s.promiseLibrary + }; + + if (!this.bucket.s.calledOpenUploadStream) { + this.bucket.s.calledOpenUploadStream = true; + + var _this = this; + checkIndexes(this, function() { + _this.bucket.s.checkedIndexes = true; + _this.bucket.emit('index'); + }); + } +} + +util.inherits(GridFSBucketWriteStream, stream.Writable); + +/** + * An error occurred + * + * @event GridFSBucketWriteStream#error + * @type {Error} + */ + +/** + * `end()` was called and the write stream successfully wrote the file + * metadata and all the chunks to MongoDB. + * + * @event GridFSBucketWriteStream#finish + * @type {object} + */ + +/** + * Write a buffer to the stream. + * + * @method + * @param {Buffer} chunk Buffer to write + * @param {String} encoding Optional encoding for the buffer + * @param {Function} callback Function to call when the chunk was added to the buffer, or if the entire chunk was persisted to MongoDB if this chunk caused a flush. + * @return {Boolean} False if this write required flushing a chunk to MongoDB. True otherwise. + */ + +GridFSBucketWriteStream.prototype.write = function(chunk, encoding, callback) { + var _this = this; + return waitForIndexes(this, function() { + return doWrite(_this, chunk, encoding, callback); + }); +}; + +/** + * Places this write stream into an aborted state (all future writes fail) + * and deletes all chunks that have already been written. + * + * @method + * @param {GridFSBucket~errorCallback} callback called when chunks are successfully removed or error occurred + * @return {Promise} if no callback specified + */ + +GridFSBucketWriteStream.prototype.abort = function(callback) { + if (this.state.streamEnd) { + var error = new Error('Cannot abort a stream that has already completed'); + if (typeof callback === 'function') { + return callback(error); + } + return this.state.promiseLibrary.reject(error); + } + if (this.state.aborted) { + error = new Error('Cannot call abort() on a stream twice'); + if (typeof callback === 'function') { + return callback(error); + } + return this.state.promiseLibrary.reject(error); + } + this.state.aborted = true; + this.chunks.deleteMany({ files_id: this.id }, function(error) { + if (typeof callback === 'function') callback(error); + }); +}; + +/** + * Tells the stream that no more data will be coming in. The stream will + * persist the remaining data to MongoDB, write the files document, and + * then emit a 'finish' event. + * + * @method + * @param {Buffer} chunk Buffer to write + * @param {String} encoding Optional encoding for the buffer + * @param {Function} callback Function to call when all files and chunks have been persisted to MongoDB + */ + +GridFSBucketWriteStream.prototype.end = function(chunk, encoding, callback) { + var _this = this; + if (typeof chunk === 'function') { + (callback = chunk), (chunk = null), (encoding = null); + } else if (typeof encoding === 'function') { + (callback = encoding), (encoding = null); + } + + if (checkAborted(this, callback)) { + return; + } + this.state.streamEnd = true; + + if (callback) { + this.once('finish', function(result) { + callback(null, result); + }); + } + + if (!chunk) { + waitForIndexes(this, function() { + writeRemnant(_this); + }); + return; + } + + this.write(chunk, encoding, function() { + writeRemnant(_this); + }); +}; + +/** + * @ignore + */ + +function __handleError(_this, error, callback) { + if (_this.state.errored) { + return; + } + _this.state.errored = true; + if (callback) { + return callback(error); + } + _this.emit('error', error); +} + +/** + * @ignore + */ + +function createChunkDoc(filesId, n, data) { + return { + _id: core.BSON.ObjectId(), + files_id: filesId, + n: n, + data: data + }; +} + +/** + * @ignore + */ + +function checkChunksIndex(_this, callback) { + _this.chunks.listIndexes().toArray(function(error, indexes) { + if (error) { + // Collection doesn't exist so create index + if (error.code === ERROR_NAMESPACE_NOT_FOUND) { + var index = { files_id: 1, n: 1 }; + _this.chunks.createIndex(index, { background: false, unique: true }, function(error) { + if (error) { + return callback(error); + } + + callback(); + }); + return; + } + return callback(error); + } + + var hasChunksIndex = false; + indexes.forEach(function(index) { + if (index.key) { + var keys = Object.keys(index.key); + if (keys.length === 2 && index.key.files_id === 1 && index.key.n === 1) { + hasChunksIndex = true; + } + } + }); + + if (hasChunksIndex) { + callback(); + } else { + index = { files_id: 1, n: 1 }; + var indexOptions = getWriteOptions(_this); + + indexOptions.background = false; + indexOptions.unique = true; + + _this.chunks.createIndex(index, indexOptions, function(error) { + if (error) { + return callback(error); + } + + callback(); + }); + } + }); +} + +/** + * @ignore + */ + +function checkDone(_this, callback) { + if (_this.done) return true; + if (_this.state.streamEnd && _this.state.outstandingRequests === 0 && !_this.state.errored) { + // Set done so we dont' trigger duplicate createFilesDoc + _this.done = true; + // Create a new files doc + var filesDoc = createFilesDoc( + _this.id, + _this.length, + _this.chunkSizeBytes, + _this.md5 && _this.md5.digest('hex'), + _this.filename, + _this.options.contentType, + _this.options.aliases, + _this.options.metadata + ); + + if (checkAborted(_this, callback)) { + return false; + } + + _this.files.insertOne(filesDoc, getWriteOptions(_this), function(error) { + if (error) { + return __handleError(_this, error, callback); + } + _this.emit('finish', filesDoc); + }); + + return true; + } + + return false; +} + +/** + * @ignore + */ + +function checkIndexes(_this, callback) { + _this.files.findOne({}, { _id: 1 }, function(error, doc) { + if (error) { + return callback(error); + } + if (doc) { + return callback(); + } + + _this.files.listIndexes().toArray(function(error, indexes) { + if (error) { + // Collection doesn't exist so create index + if (error.code === ERROR_NAMESPACE_NOT_FOUND) { + var index = { filename: 1, uploadDate: 1 }; + _this.files.createIndex(index, { background: false }, function(error) { + if (error) { + return callback(error); + } + + checkChunksIndex(_this, callback); + }); + return; + } + return callback(error); + } + + var hasFileIndex = false; + indexes.forEach(function(index) { + var keys = Object.keys(index.key); + if (keys.length === 2 && index.key.filename === 1 && index.key.uploadDate === 1) { + hasFileIndex = true; + } + }); + + if (hasFileIndex) { + checkChunksIndex(_this, callback); + } else { + index = { filename: 1, uploadDate: 1 }; + + var indexOptions = getWriteOptions(_this); + + indexOptions.background = false; + + _this.files.createIndex(index, indexOptions, function(error) { + if (error) { + return callback(error); + } + + checkChunksIndex(_this, callback); + }); + } + }); + }); +} + +/** + * @ignore + */ + +function createFilesDoc(_id, length, chunkSize, md5, filename, contentType, aliases, metadata) { + var ret = { + _id: _id, + length: length, + chunkSize: chunkSize, + uploadDate: new Date(), + filename: filename + }; + + if (md5) { + ret.md5 = md5; + } + + if (contentType) { + ret.contentType = contentType; + } + + if (aliases) { + ret.aliases = aliases; + } + + if (metadata) { + ret.metadata = metadata; + } + + return ret; +} + +/** + * @ignore + */ + +function doWrite(_this, chunk, encoding, callback) { + if (checkAborted(_this, callback)) { + return false; + } + + var inputBuf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding); + + _this.length += inputBuf.length; + + // Input is small enough to fit in our buffer + if (_this.pos + inputBuf.length < _this.chunkSizeBytes) { + inputBuf.copy(_this.bufToStore, _this.pos); + _this.pos += inputBuf.length; + + callback && callback(); + + // Note that we reverse the typical semantics of write's return value + // to be compatible with node's `.pipe()` function. + // True means client can keep writing. + return true; + } + + // Otherwise, buffer is too big for current chunk, so we need to flush + // to MongoDB. + var inputBufRemaining = inputBuf.length; + var spaceRemaining = _this.chunkSizeBytes - _this.pos; + var numToCopy = Math.min(spaceRemaining, inputBuf.length); + var outstandingRequests = 0; + while (inputBufRemaining > 0) { + var inputBufPos = inputBuf.length - inputBufRemaining; + inputBuf.copy(_this.bufToStore, _this.pos, inputBufPos, inputBufPos + numToCopy); + _this.pos += numToCopy; + spaceRemaining -= numToCopy; + if (spaceRemaining === 0) { + if (_this.md5) { + _this.md5.update(_this.bufToStore); + } + var doc = createChunkDoc(_this.id, _this.n, _this.bufToStore); + ++_this.state.outstandingRequests; + ++outstandingRequests; + + if (checkAborted(_this, callback)) { + return false; + } + + _this.chunks.insertOne(doc, getWriteOptions(_this), function(error) { + if (error) { + return __handleError(_this, error); + } + --_this.state.outstandingRequests; + --outstandingRequests; + + if (!outstandingRequests) { + _this.emit('drain', doc); + callback && callback(); + checkDone(_this); + } + }); + + spaceRemaining = _this.chunkSizeBytes; + _this.pos = 0; + ++_this.n; + } + inputBufRemaining -= numToCopy; + numToCopy = Math.min(spaceRemaining, inputBufRemaining); + } + + // Note that we reverse the typical semantics of write's return value + // to be compatible with node's `.pipe()` function. + // False means the client should wait for the 'drain' event. + return false; +} + +/** + * @ignore + */ + +function getWriteOptions(_this) { + var obj = {}; + if (_this.options.writeConcern) { + obj.w = _this.options.writeConcern.w; + obj.wtimeout = _this.options.writeConcern.wtimeout; + obj.j = _this.options.writeConcern.j; + } + return obj; +} + +/** + * @ignore + */ + +function waitForIndexes(_this, callback) { + if (_this.bucket.s.checkedIndexes) { + return callback(false); + } + + _this.bucket.once('index', function() { + callback(true); + }); + + return true; +} + +/** + * @ignore + */ + +function writeRemnant(_this, callback) { + // Buffer is empty, so don't bother to insert + if (_this.pos === 0) { + return checkDone(_this, callback); + } + + ++_this.state.outstandingRequests; + + // Create a new buffer to make sure the buffer isn't bigger than it needs + // to be. + var remnant = Buffer.alloc(_this.pos); + _this.bufToStore.copy(remnant, 0, 0, _this.pos); + if (_this.md5) { + _this.md5.update(remnant); + } + var doc = createChunkDoc(_this.id, _this.n, remnant); + + // If the stream was aborted, do not write remnant + if (checkAborted(_this, callback)) { + return false; + } + + _this.chunks.insertOne(doc, getWriteOptions(_this), function(error) { + if (error) { + return __handleError(_this, error); + } + --_this.state.outstandingRequests; + checkDone(_this); + }); +} + +/** + * @ignore + */ + +function checkAborted(_this, callback) { + if (_this.state.aborted) { + if (typeof callback === 'function') { + callback(new Error('this stream has been aborted')); + } + return true; + } + return false; +} diff --git a/scripts/2.5/node_modules/mongodb/lib/gridfs/chunk.js b/scripts/2.5/node_modules/mongodb/lib/gridfs/chunk.js new file mode 100644 index 00000000..d276d720 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/gridfs/chunk.js @@ -0,0 +1,236 @@ +'use strict'; + +var Binary = require('../core').BSON.Binary, + ObjectID = require('../core').BSON.ObjectID; + +var Buffer = require('safe-buffer').Buffer; + +/** + * Class for representing a single chunk in GridFS. + * + * @class + * + * @param file {GridStore} The {@link GridStore} object holding this chunk. + * @param mongoObject {object} The mongo object representation of this chunk. + * + * @throws Error when the type of data field for {@link mongoObject} is not + * supported. Currently supported types for data field are instances of + * {@link String}, {@link Array}, {@link Binary} and {@link Binary} + * from the bson module + * + * @see Chunk#buildMongoObject + */ +var Chunk = function(file, mongoObject, writeConcern) { + if (!(this instanceof Chunk)) return new Chunk(file, mongoObject); + + this.file = file; + var mongoObjectFinal = mongoObject == null ? {} : mongoObject; + this.writeConcern = writeConcern || { w: 1 }; + this.objectId = mongoObjectFinal._id == null ? new ObjectID() : mongoObjectFinal._id; + this.chunkNumber = mongoObjectFinal.n == null ? 0 : mongoObjectFinal.n; + this.data = new Binary(); + + if (typeof mongoObjectFinal.data === 'string') { + var buffer = Buffer.alloc(mongoObjectFinal.data.length); + buffer.write(mongoObjectFinal.data, 0, mongoObjectFinal.data.length, 'binary'); + this.data = new Binary(buffer); + } else if (Array.isArray(mongoObjectFinal.data)) { + buffer = Buffer.alloc(mongoObjectFinal.data.length); + var data = mongoObjectFinal.data.join(''); + buffer.write(data, 0, data.length, 'binary'); + this.data = new Binary(buffer); + } else if (mongoObjectFinal.data && mongoObjectFinal.data._bsontype === 'Binary') { + this.data = mongoObjectFinal.data; + } else if (!Buffer.isBuffer(mongoObjectFinal.data) && !(mongoObjectFinal.data == null)) { + throw Error('Illegal chunk format'); + } + + // Update position + this.internalPosition = 0; +}; + +/** + * Writes a data to this object and advance the read/write head. + * + * @param data {string} the data to write + * @param callback {function(*, GridStore)} This will be called after executing + * this method. The first parameter will contain null and the second one + * will contain a reference to this object. + */ +Chunk.prototype.write = function(data, callback) { + this.data.write(data, this.internalPosition, data.length, 'binary'); + this.internalPosition = this.data.length(); + if (callback != null) return callback(null, this); + return this; +}; + +/** + * Reads data and advances the read/write head. + * + * @param length {number} The length of data to read. + * + * @return {string} The data read if the given length will not exceed the end of + * the chunk. Returns an empty String otherwise. + */ +Chunk.prototype.read = function(length) { + // Default to full read if no index defined + length = length == null || length === 0 ? this.length() : length; + + if (this.length() - this.internalPosition + 1 >= length) { + var data = this.data.read(this.internalPosition, length); + this.internalPosition = this.internalPosition + length; + return data; + } else { + return ''; + } +}; + +Chunk.prototype.readSlice = function(length) { + if (this.length() - this.internalPosition >= length) { + var data = null; + if (this.data.buffer != null) { + //Pure BSON + data = this.data.buffer.slice(this.internalPosition, this.internalPosition + length); + } else { + //Native BSON + data = Buffer.alloc(length); + length = this.data.readInto(data, this.internalPosition); + } + this.internalPosition = this.internalPosition + length; + return data; + } else { + return null; + } +}; + +/** + * Checks if the read/write head is at the end. + * + * @return {boolean} Whether the read/write head has reached the end of this + * chunk. + */ +Chunk.prototype.eof = function() { + return this.internalPosition === this.length() ? true : false; +}; + +/** + * Reads one character from the data of this chunk and advances the read/write + * head. + * + * @return {string} a single character data read if the the read/write head is + * not at the end of the chunk. Returns an empty String otherwise. + */ +Chunk.prototype.getc = function() { + return this.read(1); +}; + +/** + * Clears the contents of the data in this chunk and resets the read/write head + * to the initial position. + */ +Chunk.prototype.rewind = function() { + this.internalPosition = 0; + this.data = new Binary(); +}; + +/** + * Saves this chunk to the database. Also overwrites existing entries having the + * same id as this chunk. + * + * @param callback {function(*, GridStore)} This will be called after executing + * this method. The first parameter will contain null and the second one + * will contain a reference to this object. + */ +Chunk.prototype.save = function(options, callback) { + var self = this; + if (typeof options === 'function') { + callback = options; + options = {}; + } + + self.file.chunkCollection(function(err, collection) { + if (err) return callback(err); + + // Merge the options + var writeOptions = { upsert: true }; + for (var name in options) writeOptions[name] = options[name]; + for (name in self.writeConcern) writeOptions[name] = self.writeConcern[name]; + + if (self.data.length() > 0) { + self.buildMongoObject(function(mongoObject) { + var options = { forceServerObjectId: true }; + for (var name in self.writeConcern) { + options[name] = self.writeConcern[name]; + } + + collection.replaceOne({ _id: self.objectId }, mongoObject, writeOptions, function(err) { + callback(err, self); + }); + }); + } else { + callback(null, self); + } + // }); + }); +}; + +/** + * Creates a mongoDB object representation of this chunk. + * + * @param callback {function(Object)} This will be called after executing this + * method. The object will be passed to the first parameter and will have + * the structure: + * + *

+ *        {
+ *          '_id' : , // {number} id for this chunk
+ *          'files_id' : , // {number} foreign key to the file collection
+ *          'n' : , // {number} chunk number
+ *          'data' : , // {bson#Binary} the chunk data itself
+ *        }
+ *        
+ * + * @see MongoDB GridFS Chunk Object Structure + */ +Chunk.prototype.buildMongoObject = function(callback) { + var mongoObject = { + files_id: this.file.fileId, + n: this.chunkNumber, + data: this.data + }; + // If we are saving using a specific ObjectId + if (this.objectId != null) mongoObject._id = this.objectId; + + callback(mongoObject); +}; + +/** + * @return {number} the length of the data + */ +Chunk.prototype.length = function() { + return this.data.length(); +}; + +/** + * The position of the read/write head + * @name position + * @lends Chunk# + * @field + */ +Object.defineProperty(Chunk.prototype, 'position', { + enumerable: true, + get: function() { + return this.internalPosition; + }, + set: function(value) { + this.internalPosition = value; + } +}); + +/** + * The default chunk size + * @constant + */ +Chunk.DEFAULT_CHUNK_SIZE = 1024 * 255; + +module.exports = Chunk; diff --git a/scripts/2.5/node_modules/mongodb/lib/gridfs/grid_store.js b/scripts/2.5/node_modules/mongodb/lib/gridfs/grid_store.js new file mode 100644 index 00000000..c8ccb850 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/gridfs/grid_store.js @@ -0,0 +1,1913 @@ +'use strict'; + +/** + * @fileOverview GridFS is a tool for MongoDB to store files to the database. + * Because of the restrictions of the object size the database can hold, a + * facility to split a file into several chunks is needed. The {@link GridStore} + * class offers a simplified api to interact with files while managing the + * chunks of split files behind the scenes. More information about GridFS can be + * found here. + * + * @example + * const MongoClient = require('mongodb').MongoClient; + * const GridStore = require('mongodb').GridStore; + * const ObjectID = require('mongodb').ObjectID; + * const test = require('assert'); + * // Connection url + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, client) { + * const db = client.db(dbName); + * const gridStore = new GridStore(db, null, "w"); + * gridStore.open(function(err, gridStore) { + * gridStore.write("hello world!", function(err, gridStore) { + * gridStore.close(function(err, result) { + * // Let's read the file using object Id + * GridStore.read(db, result._id, function(err, data) { + * test.equal('hello world!', data); + * client.close(); + * test.done(); + * }); + * }); + * }); + * }); + * }); + */ +const Chunk = require('./chunk'); +const ObjectID = require('../core').BSON.ObjectID; +const ReadPreference = require('../core').ReadPreference; +const Buffer = require('safe-buffer').Buffer; +const fs = require('fs'); +const f = require('util').format; +const util = require('util'); +const MongoError = require('../core').MongoError; +const inherits = util.inherits; +const Duplex = require('stream').Duplex; +const shallowClone = require('../utils').shallowClone; +const executeLegacyOperation = require('../utils').executeLegacyOperation; +const deprecate = require('util').deprecate; + +var REFERENCE_BY_FILENAME = 0, + REFERENCE_BY_ID = 1; + +const deprecationFn = deprecate(() => {}, +'GridStore is deprecated, and will be removed in a future version. Please use GridFSBucket instead'); + +/** + * Namespace provided by the core module + * @external Duplex + */ + +/** + * Create a new GridStore instance + * + * Modes + * - **"r"** - read only. This is the default mode. + * - **"w"** - write in truncate mode. Existing data will be overwritten. + * + * @class + * @param {Db} db A database instance to interact with. + * @param {object} [id] optional unique id for this file + * @param {string} [filename] optional filename for this file, no unique constrain on the field + * @param {string} mode set the mode for this file. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.fsync=false] Specify a file sync write concern. + * @param {string} [options.root] Root collection to use. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**. + * @param {string} [options.content_type] MIME type of the file. Defaults to **{GridStore.DEFAULT_CONTENT_TYPE}**. + * @param {number} [options.chunk_size=261120] Size for the chunk. Defaults to **{Chunk.DEFAULT_CHUNK_SIZE}**. + * @param {object} [options.metadata] Arbitrary data the user wants to store. + * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @property {number} chunkSize Get the gridstore chunk size. + * @property {number} md5 The md5 checksum for this file. + * @property {number} chunkNumber The current chunk number the gridstore has materialized into memory + * @return {GridStore} a GridStore instance. + * @deprecated Use GridFSBucket API instead + */ +var GridStore = function GridStore(db, id, filename, mode, options) { + deprecationFn(); + if (!(this instanceof GridStore)) return new GridStore(db, id, filename, mode, options); + this.db = db; + + // Handle options + if (typeof options === 'undefined') options = {}; + // Handle mode + if (typeof mode === 'undefined') { + mode = filename; + filename = undefined; + } else if (typeof mode === 'object') { + options = mode; + mode = filename; + filename = undefined; + } + + if (id && id._bsontype === 'ObjectID') { + this.referenceBy = REFERENCE_BY_ID; + this.fileId = id; + this.filename = filename; + } else if (typeof filename === 'undefined') { + this.referenceBy = REFERENCE_BY_FILENAME; + this.filename = id; + if (mode.indexOf('w') != null) { + this.fileId = new ObjectID(); + } + } else { + this.referenceBy = REFERENCE_BY_ID; + this.fileId = id; + this.filename = filename; + } + + // Set up the rest + this.mode = mode == null ? 'r' : mode; + this.options = options || {}; + + // Opened + this.isOpen = false; + + // Set the root if overridden + this.root = + this.options['root'] == null ? GridStore.DEFAULT_ROOT_COLLECTION : this.options['root']; + this.position = 0; + this.readPreference = + this.options.readPreference || db.options.readPreference || ReadPreference.primary; + this.writeConcern = _getWriteConcern(db, this.options); + // Set default chunk size + this.internalChunkSize = + this.options['chunkSize'] == null ? Chunk.DEFAULT_CHUNK_SIZE : this.options['chunkSize']; + + // Get the promiseLibrary + var promiseLibrary = this.options.promiseLibrary || Promise; + + // Set the promiseLibrary + this.promiseLibrary = promiseLibrary; + + Object.defineProperty(this, 'chunkSize', { + enumerable: true, + get: function() { + return this.internalChunkSize; + }, + set: function(value) { + if (!(this.mode[0] === 'w' && this.position === 0 && this.uploadDate == null)) { + this.internalChunkSize = this.internalChunkSize; + } else { + this.internalChunkSize = value; + } + } + }); + + Object.defineProperty(this, 'md5', { + enumerable: true, + get: function() { + return this.internalMd5; + } + }); + + Object.defineProperty(this, 'chunkNumber', { + enumerable: true, + get: function() { + return this.currentChunk && this.currentChunk.chunkNumber + ? this.currentChunk.chunkNumber + : null; + } + }); +}; + +/** + * The callback format for the Gridstore.open method + * @callback GridStore~openCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {GridStore} gridStore The GridStore instance if the open method was successful. + */ + +/** + * Opens the file from the database and initialize this object. Also creates a + * new one if file does not exist. + * + * @method + * @param {object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~openCallback} [callback] this will be called after executing this method + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.open = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + if (this.mode !== 'w' && this.mode !== 'w+' && this.mode !== 'r') { + throw MongoError.create({ message: 'Illegal mode ' + this.mode, driver: true }); + } + + return executeLegacyOperation(this.db.s.topology, open, [this, options, callback], { + skipSessions: true + }); +}; + +var open = function(self, options, callback) { + // Get the write concern + var writeConcern = _getWriteConcern(self.db, self.options); + + // If we are writing we need to ensure we have the right indexes for md5's + if (self.mode === 'w' || self.mode === 'w+') { + // Get files collection + var collection = self.collection(); + // Put index on filename + collection.ensureIndex([['filename', 1]], writeConcern, function() { + // Get chunk collection + var chunkCollection = self.chunkCollection(); + // Make an unique index for compatibility with mongo-cxx-driver:legacy + var chunkIndexOptions = shallowClone(writeConcern); + chunkIndexOptions.unique = true; + // Ensure index on chunk collection + chunkCollection.ensureIndex([['files_id', 1], ['n', 1]], chunkIndexOptions, function() { + // Open the connection + _open(self, writeConcern, function(err, r) { + if (err) return callback(err); + self.isOpen = true; + callback(err, r); + }); + }); + }); + } else { + // Open the gridstore + _open(self, writeConcern, function(err, r) { + if (err) return callback(err); + self.isOpen = true; + callback(err, r); + }); + } +}; + +/** + * Verify if the file is at EOF. + * + * @method + * @return {boolean} true if the read/write head is at the end of this file. + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.eof = function() { + return this.position === this.length ? true : false; +}; + +/** + * The callback result format. + * @callback GridStore~resultCallback + * @param {object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {MongoError} error An error instance representing the error during the execution. + * @param {object} result The result from the callback. + */ + +/** + * Retrieves a single character from this file. + * + * @method + * @param {GridStore~resultCallback} [callback] this gets called after this method is executed. Passes null to the first parameter and the character read to the second or null to the second if the read/write head is at the end of the file. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.getc = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeLegacyOperation(this.db.s.topology, getc, [this, options, callback], { + skipSessions: true + }); +}; + +var getc = function(self, options, callback) { + if (self.eof()) { + callback(null, null); + } else if (self.currentChunk.eof()) { + nthChunk(self, self.currentChunk.chunkNumber + 1, function(err, chunk) { + self.currentChunk = chunk; + self.position = self.position + 1; + callback(err, self.currentChunk.getc()); + }); + } else { + self.position = self.position + 1; + callback(null, self.currentChunk.getc()); + } +}; + +/** + * Writes a string to the file with a newline character appended at the end if + * the given string does not have one. + * + * @method + * @param {string} string the string to write. + * @param {object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.puts = function(string, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + var finalString = string.match(/\n$/) == null ? string + '\n' : string; + return executeLegacyOperation( + this.db.s.topology, + this.write.bind(this), + [finalString, options, callback], + { skipSessions: true } + ); +}; + +/** + * Return a modified Readable stream including a possible transform method. + * + * @method + * @return {GridStoreStream} + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.stream = function() { + return new GridStoreStream(this); +}; + +/** + * Writes some data. This method will work properly only if initialized with mode "w" or "w+". + * + * @method + * @param {(string|Buffer)} data the data to write. + * @param {boolean} [close] closes this file after writing if set to true. + * @param {object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.write = function write(data, close, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeLegacyOperation( + this.db.s.topology, + _writeNormal, + [this, data, close, options, callback], + { skipSessions: true } + ); +}; + +/** + * Handles the destroy part of a stream + * + * @method + * @result {null} + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.destroy = function destroy() { + // close and do not emit any more events. queued data is not sent. + if (!this.writable) return; + this.readable = false; + if (this.writable) { + this.writable = false; + this._q.length = 0; + this.emit('close'); + } +}; + +/** + * Stores a file from the file system to the GridFS database. + * + * @method + * @param {(string|Buffer|FileHandle)} file the file to store. + * @param {object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.writeFile = function(file, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeLegacyOperation(this.db.s.topology, writeFile, [this, file, options, callback], { + skipSessions: true + }); +}; + +var writeFile = function(self, file, options, callback) { + if (typeof file === 'string') { + fs.open(file, 'r', function(err, fd) { + if (err) return callback(err); + self.writeFile(fd, callback); + }); + return; + } + + self.open(function(err, self) { + if (err) return callback(err, self); + + fs.fstat(file, function(err, stats) { + if (err) return callback(err, self); + + var offset = 0; + var index = 0; + + // Write a chunk + var writeChunk = function() { + // Allocate the buffer + var _buffer = Buffer.alloc(self.chunkSize); + // Read the file + fs.read(file, _buffer, 0, _buffer.length, offset, function(err, bytesRead, data) { + if (err) return callback(err, self); + + offset = offset + bytesRead; + + // Create a new chunk for the data + var chunk = new Chunk(self, { n: index++ }, self.writeConcern); + chunk.write(data.slice(0, bytesRead), function(err, chunk) { + if (err) return callback(err, self); + + chunk.save({}, function(err) { + if (err) return callback(err, self); + + self.position = self.position + bytesRead; + + // Point to current chunk + self.currentChunk = chunk; + + if (offset >= stats.size) { + fs.close(file, function(err) { + if (err) return callback(err); + + self.close(function(err) { + if (err) return callback(err, self); + return callback(null, self); + }); + }); + } else { + return process.nextTick(writeChunk); + } + }); + }); + }); + }; + + // Process the first write + process.nextTick(writeChunk); + }); + }); +}; + +/** + * Saves this file to the database. This will overwrite the old entry if it + * already exists. This will work properly only if mode was initialized to + * "w" or "w+". + * + * @method + * @param {object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.close = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeLegacyOperation(this.db.s.topology, close, [this, options, callback], { + skipSessions: true + }); +}; + +var close = function(self, options, callback) { + if (self.mode[0] === 'w') { + // Set up options + options = Object.assign({}, self.writeConcern, options); + + if (self.currentChunk != null && self.currentChunk.position > 0) { + self.currentChunk.save({}, function(err) { + if (err && typeof callback === 'function') return callback(err); + + self.collection(function(err, files) { + if (err && typeof callback === 'function') return callback(err); + + // Build the mongo object + if (self.uploadDate != null) { + buildMongoObject(self, function(err, mongoObject) { + if (err) { + if (typeof callback === 'function') return callback(err); + else throw err; + } + + files.save(mongoObject, options, function(err) { + if (typeof callback === 'function') callback(err, mongoObject); + }); + }); + } else { + self.uploadDate = new Date(); + buildMongoObject(self, function(err, mongoObject) { + if (err) { + if (typeof callback === 'function') return callback(err); + else throw err; + } + + files.save(mongoObject, options, function(err) { + if (typeof callback === 'function') callback(err, mongoObject); + }); + }); + } + }); + }); + } else { + self.collection(function(err, files) { + if (err && typeof callback === 'function') return callback(err); + + self.uploadDate = new Date(); + buildMongoObject(self, function(err, mongoObject) { + if (err) { + if (typeof callback === 'function') return callback(err); + else throw err; + } + + files.save(mongoObject, options, function(err) { + if (typeof callback === 'function') callback(err, mongoObject); + }); + }); + }); + } + } else if (self.mode[0] === 'r') { + if (typeof callback === 'function') callback(null, null); + } else { + if (typeof callback === 'function') + callback(MongoError.create({ message: f('Illegal mode %s', self.mode), driver: true })); + } +}; + +/** + * The collection callback format. + * @callback GridStore~collectionCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection} collection The collection from the command execution. + */ + +/** + * Retrieve this file's chunks collection. + * + * @method + * @param {GridStore~collectionCallback} callback the command callback. + * @return {Collection} + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.chunkCollection = function(callback) { + if (typeof callback === 'function') return this.db.collection(this.root + '.chunks', callback); + return this.db.collection(this.root + '.chunks'); +}; + +/** + * Deletes all the chunks of this file in the database. + * + * @method + * @param {object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~resultCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.unlink = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeLegacyOperation(this.db.s.topology, unlink, [this, options, callback], { + skipSessions: true + }); +}; + +var unlink = function(self, options, callback) { + deleteChunks(self, function(err) { + if (err !== null) { + err.message = 'at deleteChunks: ' + err.message; + return callback(err); + } + + self.collection(function(err, collection) { + if (err !== null) { + err.message = 'at collection: ' + err.message; + return callback(err); + } + + collection.remove({ _id: self.fileId }, self.writeConcern, function(err) { + callback(err, self); + }); + }); + }); +}; + +/** + * Retrieves the file collection associated with this object. + * + * @method + * @param {GridStore~collectionCallback} callback the command callback. + * @return {Collection} + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.collection = function(callback) { + if (typeof callback === 'function') this.db.collection(this.root + '.files', callback); + return this.db.collection(this.root + '.files'); +}; + +/** + * The readlines callback format. + * @callback GridStore~readlinesCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {string[]} strings The array of strings returned. + */ + +/** + * Read the entire file as a list of strings splitting by the provided separator. + * + * @method + * @param {string} [separator] The character to be recognized as the newline separator. + * @param {object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~readlinesCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.readlines = function(separator, options, callback) { + var args = Array.prototype.slice.call(arguments, 0); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + separator = args.length ? args.shift() : '\n'; + separator = separator || '\n'; + options = args.length ? args.shift() : {}; + + return executeLegacyOperation( + this.db.s.topology, + readlines, + [this, separator, options, callback], + { skipSessions: true } + ); +}; + +var readlines = function(self, separator, options, callback) { + self.read(function(err, data) { + if (err) return callback(err); + + var items = data.toString().split(separator); + items = items.length > 0 ? items.splice(0, items.length - 1) : []; + for (var i = 0; i < items.length; i++) { + items[i] = items[i] + separator; + } + + callback(null, items); + }); +}; + +/** + * Deletes all the chunks of this file in the database if mode was set to "w" or + * "w+" and resets the read/write head to the initial position. + * + * @method + * @param {object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.rewind = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeLegacyOperation(this.db.s.topology, rewind, [this, options, callback], { + skipSessions: true + }); +}; + +var rewind = function(self, options, callback) { + if (self.currentChunk.chunkNumber !== 0) { + if (self.mode[0] === 'w') { + deleteChunks(self, function(err) { + if (err) return callback(err); + self.currentChunk = new Chunk(self, { n: 0 }, self.writeConcern); + self.position = 0; + callback(null, self); + }); + } else { + self.currentChunk(0, function(err, chunk) { + if (err) return callback(err); + self.currentChunk = chunk; + self.currentChunk.rewind(); + self.position = 0; + callback(null, self); + }); + } + } else { + self.currentChunk.rewind(); + self.position = 0; + callback(null, self); + } +}; + +/** + * The read callback format. + * @callback GridStore~readCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Buffer} data The data read from the GridStore object + */ + +/** + * Retrieves the contents of this file and advances the read/write head. Works with Buffers only. + * + * There are 3 signatures for this method: + * + * (callback) + * (length, callback) + * (length, buffer, callback) + * + * @method + * @param {number} [length] the number of characters to read. Reads all the characters from the read/write head to the EOF if not specified. + * @param {(string|Buffer)} [buffer] a string to hold temporary data. This is used for storing the string data read so far when recursively calling this method. + * @param {object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~readCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.read = function(length, buffer, options, callback) { + var args = Array.prototype.slice.call(arguments, 0); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + length = args.length ? args.shift() : null; + buffer = args.length ? args.shift() : null; + options = args.length ? args.shift() : {}; + + return executeLegacyOperation( + this.db.s.topology, + read, + [this, length, buffer, options, callback], + { skipSessions: true } + ); +}; + +var read = function(self, length, buffer, options, callback) { + // The data is a c-terminated string and thus the length - 1 + var finalLength = length == null ? self.length - self.position : length; + var finalBuffer = buffer == null ? Buffer.alloc(finalLength) : buffer; + // Add a index to buffer to keep track of writing position or apply current index + finalBuffer._index = buffer != null && buffer._index != null ? buffer._index : 0; + + if (self.currentChunk.length() - self.currentChunk.position + finalBuffer._index >= finalLength) { + var slice = self.currentChunk.readSlice(finalLength - finalBuffer._index); + // Copy content to final buffer + slice.copy(finalBuffer, finalBuffer._index); + // Update internal position + self.position = self.position + finalBuffer.length; + // Check if we don't have a file at all + if (finalLength === 0 && finalBuffer.length === 0) + return callback(MongoError.create({ message: 'File does not exist', driver: true }), null); + // Else return data + return callback(null, finalBuffer); + } + + // Read the next chunk + slice = self.currentChunk.readSlice(self.currentChunk.length() - self.currentChunk.position); + // Copy content to final buffer + slice.copy(finalBuffer, finalBuffer._index); + // Update index position + finalBuffer._index += slice.length; + + // Load next chunk and read more + nthChunk(self, self.currentChunk.chunkNumber + 1, function(err, chunk) { + if (err) return callback(err); + + if (chunk.length() > 0) { + self.currentChunk = chunk; + self.read(length, finalBuffer, callback); + } else { + if (finalBuffer._index > 0) { + callback(null, finalBuffer); + } else { + callback( + MongoError.create({ + message: 'no chunks found for file, possibly corrupt', + driver: true + }), + null + ); + } + } + }); +}; + +/** + * The tell callback format. + * @callback GridStore~tellCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {number} position The current read position in the GridStore. + */ + +/** + * Retrieves the position of the read/write head of this file. + * + * @method + * @param {number} [length] the number of characters to read. Reads all the characters from the read/write head to the EOF if not specified. + * @param {(string|Buffer)} [buffer] a string to hold temporary data. This is used for storing the string data read so far when recursively calling this method. + * @param {object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~tellCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.tell = function(callback) { + var self = this; + // We provided a callback leg + if (typeof callback === 'function') return callback(null, this.position); + // Return promise + return new self.promiseLibrary(function(resolve) { + resolve(self.position); + }); +}; + +/** + * The tell callback format. + * @callback GridStore~gridStoreCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {GridStore} gridStore The gridStore. + */ + +/** + * Moves the read/write head to a new location. + * + * There are 3 signatures for this method + * + * Seek Location Modes + * - **GridStore.IO_SEEK_SET**, **(default)** set the position from the start of the file. + * - **GridStore.IO_SEEK_CUR**, set the position from the current position in the file. + * - **GridStore.IO_SEEK_END**, set the position from the end of the file. + * + * @method + * @param {number} [position] the position to seek to + * @param {number} [seekLocation] seek mode. Use one of the Seek Location modes. + * @param {object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~gridStoreCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.seek = function(position, seekLocation, options, callback) { + var args = Array.prototype.slice.call(arguments, 1); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + seekLocation = args.length ? args.shift() : null; + options = args.length ? args.shift() : {}; + + return executeLegacyOperation( + this.db.s.topology, + seek, + [this, position, seekLocation, options, callback], + { skipSessions: true } + ); +}; + +var seek = function(self, position, seekLocation, options, callback) { + // Seek only supports read mode + if (self.mode !== 'r') { + return callback( + MongoError.create({ message: 'seek is only supported for mode r', driver: true }) + ); + } + + var seekLocationFinal = seekLocation == null ? GridStore.IO_SEEK_SET : seekLocation; + var finalPosition = position; + var targetPosition = 0; + + // Calculate the position + if (seekLocationFinal === GridStore.IO_SEEK_CUR) { + targetPosition = self.position + finalPosition; + } else if (seekLocationFinal === GridStore.IO_SEEK_END) { + targetPosition = self.length + finalPosition; + } else { + targetPosition = finalPosition; + } + + // Get the chunk + var newChunkNumber = Math.floor(targetPosition / self.chunkSize); + var seekChunk = function() { + nthChunk(self, newChunkNumber, function(err, chunk) { + if (err) return callback(err, null); + if (chunk == null) return callback(new Error('no chunk found')); + + // Set the current chunk + self.currentChunk = chunk; + self.position = targetPosition; + self.currentChunk.position = self.position % self.chunkSize; + callback(err, self); + }); + }; + + seekChunk(); +}; + +/** + * @ignore + */ +var _open = function(self, options, callback) { + var collection = self.collection(); + // Create the query + var query = + self.referenceBy === REFERENCE_BY_ID ? { _id: self.fileId } : { filename: self.filename }; + query = null == self.fileId && self.filename == null ? null : query; + options.readPreference = self.readPreference; + + // Fetch the chunks + if (query != null) { + collection.findOne(query, options, function(err, doc) { + if (err) { + return error(err); + } + + // Check if the collection for the files exists otherwise prepare the new one + if (doc != null) { + self.fileId = doc._id; + // Prefer a new filename over the existing one if this is a write + self.filename = + self.mode === 'r' || self.filename === undefined ? doc.filename : self.filename; + self.contentType = doc.contentType; + self.internalChunkSize = doc.chunkSize; + self.uploadDate = doc.uploadDate; + self.aliases = doc.aliases; + self.length = doc.length; + self.metadata = doc.metadata; + self.internalMd5 = doc.md5; + } else if (self.mode !== 'r') { + self.fileId = self.fileId == null ? new ObjectID() : self.fileId; + self.contentType = GridStore.DEFAULT_CONTENT_TYPE; + self.internalChunkSize = + self.internalChunkSize == null ? Chunk.DEFAULT_CHUNK_SIZE : self.internalChunkSize; + self.length = 0; + } else { + self.length = 0; + var txtId = self.fileId._bsontype === 'ObjectID' ? self.fileId.toHexString() : self.fileId; + return error( + MongoError.create({ + message: f( + 'file with id %s not opened for writing', + self.referenceBy === REFERENCE_BY_ID ? txtId : self.filename + ), + driver: true + }), + self + ); + } + + // Process the mode of the object + if (self.mode === 'r') { + nthChunk(self, 0, options, function(err, chunk) { + if (err) return error(err); + self.currentChunk = chunk; + self.position = 0; + callback(null, self); + }); + } else if (self.mode === 'w' && doc) { + // Delete any existing chunks + deleteChunks(self, options, function(err) { + if (err) return error(err); + self.currentChunk = new Chunk(self, { n: 0 }, self.writeConcern); + self.contentType = + self.options['content_type'] == null ? self.contentType : self.options['content_type']; + self.internalChunkSize = + self.options['chunk_size'] == null + ? self.internalChunkSize + : self.options['chunk_size']; + self.metadata = + self.options['metadata'] == null ? self.metadata : self.options['metadata']; + self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; + self.position = 0; + callback(null, self); + }); + } else if (self.mode === 'w') { + self.currentChunk = new Chunk(self, { n: 0 }, self.writeConcern); + self.contentType = + self.options['content_type'] == null ? self.contentType : self.options['content_type']; + self.internalChunkSize = + self.options['chunk_size'] == null ? self.internalChunkSize : self.options['chunk_size']; + self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata']; + self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; + self.position = 0; + callback(null, self); + } else if (self.mode === 'w+') { + nthChunk(self, lastChunkNumber(self), options, function(err, chunk) { + if (err) return error(err); + // Set the current chunk + self.currentChunk = chunk == null ? new Chunk(self, { n: 0 }, self.writeConcern) : chunk; + self.currentChunk.position = self.currentChunk.data.length(); + self.metadata = + self.options['metadata'] == null ? self.metadata : self.options['metadata']; + self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; + self.position = self.length; + callback(null, self); + }); + } + }); + } else { + // Write only mode + self.fileId = null == self.fileId ? new ObjectID() : self.fileId; + self.contentType = GridStore.DEFAULT_CONTENT_TYPE; + self.internalChunkSize = + self.internalChunkSize == null ? Chunk.DEFAULT_CHUNK_SIZE : self.internalChunkSize; + self.length = 0; + + // No file exists set up write mode + if (self.mode === 'w') { + // Delete any existing chunks + deleteChunks(self, options, function(err) { + if (err) return error(err); + self.currentChunk = new Chunk(self, { n: 0 }, self.writeConcern); + self.contentType = + self.options['content_type'] == null ? self.contentType : self.options['content_type']; + self.internalChunkSize = + self.options['chunk_size'] == null ? self.internalChunkSize : self.options['chunk_size']; + self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata']; + self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; + self.position = 0; + callback(null, self); + }); + } else if (self.mode === 'w+') { + nthChunk(self, lastChunkNumber(self), options, function(err, chunk) { + if (err) return error(err); + // Set the current chunk + self.currentChunk = chunk == null ? new Chunk(self, { n: 0 }, self.writeConcern) : chunk; + self.currentChunk.position = self.currentChunk.data.length(); + self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata']; + self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; + self.position = self.length; + callback(null, self); + }); + } + } + + // only pass error to callback once + function error(err) { + if (error.err) return; + callback((error.err = err)); + } +}; + +/** + * @ignore + */ +var writeBuffer = function(self, buffer, close, callback) { + if (typeof close === 'function') { + callback = close; + close = null; + } + var finalClose = typeof close === 'boolean' ? close : false; + + if (self.mode !== 'w') { + callback( + MongoError.create({ + message: f( + 'file with id %s not opened for writing', + self.referenceBy === REFERENCE_BY_ID ? self.referenceBy : self.filename + ), + driver: true + }), + null + ); + } else { + if (self.currentChunk.position + buffer.length >= self.chunkSize) { + // Write out the current Chunk and then keep writing until we have less data left than a chunkSize left + // to a new chunk (recursively) + var previousChunkNumber = self.currentChunk.chunkNumber; + var leftOverDataSize = self.chunkSize - self.currentChunk.position; + var firstChunkData = buffer.slice(0, leftOverDataSize); + var leftOverData = buffer.slice(leftOverDataSize); + // A list of chunks to write out + var chunksToWrite = [self.currentChunk.write(firstChunkData)]; + // If we have more data left than the chunk size let's keep writing new chunks + while (leftOverData.length >= self.chunkSize) { + // Create a new chunk and write to it + var newChunk = new Chunk(self, { n: previousChunkNumber + 1 }, self.writeConcern); + firstChunkData = leftOverData.slice(0, self.chunkSize); + leftOverData = leftOverData.slice(self.chunkSize); + // Update chunk number + previousChunkNumber = previousChunkNumber + 1; + // Write data + newChunk.write(firstChunkData); + // Push chunk to save list + chunksToWrite.push(newChunk); + } + + // Set current chunk with remaining data + self.currentChunk = new Chunk(self, { n: previousChunkNumber + 1 }, self.writeConcern); + // If we have left over data write it + if (leftOverData.length > 0) self.currentChunk.write(leftOverData); + + // Update the position for the gridstore + self.position = self.position + buffer.length; + // Total number of chunks to write + var numberOfChunksToWrite = chunksToWrite.length; + + for (var i = 0; i < chunksToWrite.length; i++) { + chunksToWrite[i].save({}, function(err) { + if (err) return callback(err); + + numberOfChunksToWrite = numberOfChunksToWrite - 1; + + if (numberOfChunksToWrite <= 0) { + // We care closing the file before returning + if (finalClose) { + return self.close(function(err) { + callback(err, self); + }); + } + + // Return normally + return callback(null, self); + } + }); + } + } else { + // Update the position for the gridstore + self.position = self.position + buffer.length; + // We have less data than the chunk size just write it and callback + self.currentChunk.write(buffer); + // We care closing the file before returning + if (finalClose) { + return self.close(function(err) { + callback(err, self); + }); + } + // Return normally + return callback(null, self); + } + } +}; + +/** + * Creates a mongoDB object representation of this object. + * + *

+ *        {
+ *          '_id' : , // {number} id for this file
+ *          'filename' : , // {string} name for this file
+ *          'contentType' : , // {string} mime type for this file
+ *          'length' : , // {number} size of this file?
+ *          'chunksize' : , // {number} chunk size used by this file
+ *          'uploadDate' : , // {Date}
+ *          'aliases' : , // {array of string}
+ *          'metadata' : , // {string}
+ *        }
+ *        
+ * + * @ignore + */ +var buildMongoObject = function(self, callback) { + // Calcuate the length + var mongoObject = { + _id: self.fileId, + filename: self.filename, + contentType: self.contentType, + length: self.position ? self.position : 0, + chunkSize: self.chunkSize, + uploadDate: self.uploadDate, + aliases: self.aliases, + metadata: self.metadata + }; + + var md5Command = { filemd5: self.fileId, root: self.root }; + self.db.command(md5Command, function(err, results) { + if (err) return callback(err); + + mongoObject.md5 = results.md5; + callback(null, mongoObject); + }); +}; + +/** + * Gets the nth chunk of this file. + * @ignore + */ +var nthChunk = function(self, chunkNumber, options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + + options = options || self.writeConcern; + options.readPreference = self.readPreference; + // Get the nth chunk + self + .chunkCollection() + .findOne({ files_id: self.fileId, n: chunkNumber }, options, function(err, chunk) { + if (err) return callback(err); + + var finalChunk = chunk == null ? {} : chunk; + callback(null, new Chunk(self, finalChunk, self.writeConcern)); + }); +}; + +/** + * @ignore + */ +var lastChunkNumber = function(self) { + return Math.floor((self.length ? self.length - 1 : 0) / self.chunkSize); +}; + +/** + * Deletes all the chunks of this file in the database. + * + * @ignore + */ +var deleteChunks = function(self, options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + + options = options || self.writeConcern; + + if (self.fileId != null) { + self.chunkCollection().remove({ files_id: self.fileId }, options, function(err) { + if (err) return callback(err, false); + callback(null, true); + }); + } else { + callback(null, true); + } +}; + +/** + * The collection to be used for holding the files and chunks collection. + * + * @classconstant DEFAULT_ROOT_COLLECTION + */ +GridStore.DEFAULT_ROOT_COLLECTION = 'fs'; + +/** + * Default file mime type + * + * @classconstant DEFAULT_CONTENT_TYPE + */ +GridStore.DEFAULT_CONTENT_TYPE = 'binary/octet-stream'; + +/** + * Seek mode where the given length is absolute. + * + * @classconstant IO_SEEK_SET + */ +GridStore.IO_SEEK_SET = 0; + +/** + * Seek mode where the given length is an offset to the current read/write head. + * + * @classconstant IO_SEEK_CUR + */ +GridStore.IO_SEEK_CUR = 1; + +/** + * Seek mode where the given length is an offset to the end of the file. + * + * @classconstant IO_SEEK_END + */ +GridStore.IO_SEEK_END = 2; + +/** + * Checks if a file exists in the database. + * + * @method + * @static + * @param {Db} db the database to query. + * @param {string} name The name of the file to look for. + * @param {string} [rootCollection] The root collection that holds the files and chunks collection. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**. + * @param {object} [options] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~resultCallback} [callback] result from exists. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.exist = function(db, fileIdObject, rootCollection, options, callback) { + var args = Array.prototype.slice.call(arguments, 2); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + rootCollection = args.length ? args.shift() : null; + options = args.length ? args.shift() : {}; + options = options || {}; + + return executeLegacyOperation( + db.s.topology, + exists, + [db, fileIdObject, rootCollection, options, callback], + { skipSessions: true } + ); +}; + +var exists = function(db, fileIdObject, rootCollection, options, callback) { + // Establish read preference + var readPreference = options.readPreference || ReadPreference.PRIMARY; + // Fetch collection + var rootCollectionFinal = + rootCollection != null ? rootCollection : GridStore.DEFAULT_ROOT_COLLECTION; + db.collection(rootCollectionFinal + '.files', function(err, collection) { + if (err) return callback(err); + + // Build query + var query = + typeof fileIdObject === 'string' || + Object.prototype.toString.call(fileIdObject) === '[object RegExp]' + ? { filename: fileIdObject } + : { _id: fileIdObject }; // Attempt to locate file + + // We have a specific query + if ( + fileIdObject != null && + typeof fileIdObject === 'object' && + Object.prototype.toString.call(fileIdObject) !== '[object RegExp]' + ) { + query = fileIdObject; + } + + // Check if the entry exists + collection.findOne(query, { readPreference: readPreference }, function(err, item) { + if (err) return callback(err); + callback(null, item == null ? false : true); + }); + }); +}; + +/** + * Gets the list of files stored in the GridFS. + * + * @method + * @static + * @param {Db} db the database to query. + * @param {string} [rootCollection] The root collection that holds the files and chunks collection. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**. + * @param {object} [options] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~resultCallback} [callback] result from exists. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.list = function(db, rootCollection, options, callback) { + var args = Array.prototype.slice.call(arguments, 1); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + rootCollection = args.length ? args.shift() : null; + options = args.length ? args.shift() : {}; + options = options || {}; + + return executeLegacyOperation(db.s.topology, list, [db, rootCollection, options, callback], { + skipSessions: true + }); +}; + +var list = function(db, rootCollection, options, callback) { + // Ensure we have correct values + if (rootCollection != null && typeof rootCollection === 'object') { + options = rootCollection; + rootCollection = null; + } + + // Establish read preference + var readPreference = options.readPreference || ReadPreference.primary; + // Check if we are returning by id not filename + var byId = options['id'] != null ? options['id'] : false; + // Fetch item + var rootCollectionFinal = + rootCollection != null ? rootCollection : GridStore.DEFAULT_ROOT_COLLECTION; + var items = []; + db.collection(rootCollectionFinal + '.files', function(err, collection) { + if (err) return callback(err); + + collection.find({}, { readPreference: readPreference }, function(err, cursor) { + if (err) return callback(err); + + cursor.each(function(err, item) { + if (item != null) { + items.push(byId ? item._id : item.filename); + } else { + callback(err, items); + } + }); + }); + }); +}; + +/** + * Reads the contents of a file. + * + * This method has the following signatures + * + * (db, name, callback) + * (db, name, length, callback) + * (db, name, length, offset, callback) + * (db, name, length, offset, options, callback) + * + * @method + * @static + * @param {Db} db the database to query. + * @param {string} name The name of the file. + * @param {number} [length] The size of data to read. + * @param {number} [offset] The offset from the head of the file of which to start reading from. + * @param {object} [options] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~readCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.read = function(db, name, length, offset, options, callback) { + var args = Array.prototype.slice.call(arguments, 2); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + length = args.length ? args.shift() : null; + offset = args.length ? args.shift() : null; + options = args.length ? args.shift() : null; + options = options || {}; + + return executeLegacyOperation( + db.s.topology, + readStatic, + [db, name, length, offset, options, callback], + { skipSessions: true } + ); +}; + +var readStatic = function(db, name, length, offset, options, callback) { + new GridStore(db, name, 'r', options).open(function(err, gridStore) { + if (err) return callback(err); + // Make sure we are not reading out of bounds + if (offset && offset >= gridStore.length) + return callback('offset larger than size of file', null); + if (length && length > gridStore.length) + return callback('length is larger than the size of the file', null); + if (offset && length && offset + length > gridStore.length) + return callback('offset and length is larger than the size of the file', null); + + if (offset != null) { + gridStore.seek(offset, function(err, gridStore) { + if (err) return callback(err); + gridStore.read(length, callback); + }); + } else { + gridStore.read(length, callback); + } + }); +}; + +/** + * Read the entire file as a list of strings splitting by the provided separator. + * + * @method + * @static + * @param {Db} db the database to query. + * @param {(String|object)} name the name of the file. + * @param {string} [separator] The character to be recognized as the newline separator. + * @param {object} [options] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~readlinesCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.readlines = function(db, name, separator, options, callback) { + var args = Array.prototype.slice.call(arguments, 2); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + separator = args.length ? args.shift() : null; + options = args.length ? args.shift() : null; + options = options || {}; + + return executeLegacyOperation( + db.s.topology, + readlinesStatic, + [db, name, separator, options, callback], + { skipSessions: true } + ); +}; + +var readlinesStatic = function(db, name, separator, options, callback) { + var finalSeperator = separator == null ? '\n' : separator; + new GridStore(db, name, 'r', options).open(function(err, gridStore) { + if (err) return callback(err); + gridStore.readlines(finalSeperator, callback); + }); +}; + +/** + * Deletes the chunks and metadata information of a file from GridFS. + * + * @method + * @static + * @param {Db} db The database to query. + * @param {(string|array)} names The name/names of the files to delete. + * @param {object} [options] Optional settings. + * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~resultCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.unlink = function(db, names, options, callback) { + var args = Array.prototype.slice.call(arguments, 2); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + options = args.length ? args.shift() : {}; + options = options || {}; + + return executeLegacyOperation(db.s.topology, unlinkStatic, [this, db, names, options, callback], { + skipSessions: true + }); +}; + +var unlinkStatic = function(self, db, names, options, callback) { + // Get the write concern + var writeConcern = _getWriteConcern(db, options); + + // List of names + if (names.constructor === Array) { + var tc = 0; + for (var i = 0; i < names.length; i++) { + ++tc; + GridStore.unlink(db, names[i], options, function() { + if (--tc === 0) { + callback(null, self); + } + }); + } + } else { + new GridStore(db, names, 'w', options).open(function(err, gridStore) { + if (err) return callback(err); + deleteChunks(gridStore, function(err) { + if (err) return callback(err); + gridStore.collection(function(err, collection) { + if (err) return callback(err); + collection.remove({ _id: gridStore.fileId }, writeConcern, function(err) { + callback(err, self); + }); + }); + }); + }); + } +}; + +/** + * @ignore + */ +var _writeNormal = function(self, data, close, options, callback) { + // If we have a buffer write it using the writeBuffer method + if (Buffer.isBuffer(data)) { + return writeBuffer(self, data, close, callback); + } else { + return writeBuffer(self, Buffer.from(data, 'binary'), close, callback); + } +}; + +/** + * @ignore + */ +var _setWriteConcernHash = function(options) { + var finalOptions = {}; + if (options.w != null) finalOptions.w = options.w; + if (options.journal === true) finalOptions.j = options.journal; + if (options.j === true) finalOptions.j = options.j; + if (options.fsync === true) finalOptions.fsync = options.fsync; + if (options.wtimeout != null) finalOptions.wtimeout = options.wtimeout; + return finalOptions; +}; + +/** + * @ignore + */ +var _getWriteConcern = function(self, options) { + // Final options + var finalOptions = { w: 1 }; + options = options || {}; + + // Local options verification + if ( + options.w != null || + typeof options.j === 'boolean' || + typeof options.journal === 'boolean' || + typeof options.fsync === 'boolean' + ) { + finalOptions = _setWriteConcernHash(options); + } else if (options.safe != null && typeof options.safe === 'object') { + finalOptions = _setWriteConcernHash(options.safe); + } else if (typeof options.safe === 'boolean') { + finalOptions = { w: options.safe ? 1 : 0 }; + } else if ( + self.options.w != null || + typeof self.options.j === 'boolean' || + typeof self.options.journal === 'boolean' || + typeof self.options.fsync === 'boolean' + ) { + finalOptions = _setWriteConcernHash(self.options); + } else if ( + self.safe && + (self.safe.w != null || + typeof self.safe.j === 'boolean' || + typeof self.safe.journal === 'boolean' || + typeof self.safe.fsync === 'boolean') + ) { + finalOptions = _setWriteConcernHash(self.safe); + } else if (typeof self.safe === 'boolean') { + finalOptions = { w: self.safe ? 1 : 0 }; + } + + // Ensure we don't have an invalid combination of write concerns + if ( + finalOptions.w < 1 && + (finalOptions.journal === true || finalOptions.j === true || finalOptions.fsync === true) + ) + throw MongoError.create({ + message: 'No acknowledgement using w < 1 cannot be combined with journal:true or fsync:true', + driver: true + }); + + // Return the options + return finalOptions; +}; + +/** + * Create a new GridStoreStream instance (INTERNAL TYPE, do not instantiate directly) + * + * @class + * @extends external:Duplex + * @return {GridStoreStream} a GridStoreStream instance. + * @deprecated Use GridFSBucket API instead + */ +var GridStoreStream = function(gs) { + // Initialize the duplex stream + Duplex.call(this); + + // Get the gridstore + this.gs = gs; + + // End called + this.endCalled = false; + + // If we have a seek + this.totalBytesToRead = this.gs.length - this.gs.position; + this.seekPosition = this.gs.position; +}; + +// +// Inherit duplex +inherits(GridStoreStream, Duplex); + +GridStoreStream.prototype._pipe = GridStoreStream.prototype.pipe; + +// Set up override +GridStoreStream.prototype.pipe = function(destination) { + var self = this; + + // Only open gridstore if not already open + if (!self.gs.isOpen) { + self.gs.open(function(err) { + if (err) return self.emit('error', err); + self.totalBytesToRead = self.gs.length - self.gs.position; + self._pipe.apply(self, [destination]); + }); + } else { + self.totalBytesToRead = self.gs.length - self.gs.position; + self._pipe.apply(self, [destination]); + } + + return destination; +}; + +// Called by stream +GridStoreStream.prototype._read = function() { + var self = this; + + var read = function() { + // Read data + self.gs.read(length, function(err, buffer) { + if (err && !self.endCalled) return self.emit('error', err); + + // Stream is closed + if (self.endCalled || buffer == null) return self.push(null); + // Remove bytes read + if (buffer.length <= self.totalBytesToRead) { + self.totalBytesToRead = self.totalBytesToRead - buffer.length; + self.push(buffer); + } else if (buffer.length > self.totalBytesToRead) { + self.totalBytesToRead = self.totalBytesToRead - buffer._index; + self.push(buffer.slice(0, buffer._index)); + } + + // Finished reading + if (self.totalBytesToRead <= 0) { + self.endCalled = true; + } + }); + }; + + // Set read length + var length = + self.gs.length < self.gs.chunkSize ? self.gs.length - self.seekPosition : self.gs.chunkSize; + if (!self.gs.isOpen) { + self.gs.open(function(err) { + self.totalBytesToRead = self.gs.length - self.gs.position; + if (err) return self.emit('error', err); + read(); + }); + } else { + read(); + } +}; + +GridStoreStream.prototype.destroy = function() { + this.pause(); + this.endCalled = true; + this.gs.close(); + this.emit('end'); +}; + +GridStoreStream.prototype.write = function(chunk) { + var self = this; + if (self.endCalled) + return self.emit( + 'error', + MongoError.create({ message: 'attempting to write to stream after end called', driver: true }) + ); + // Do we have to open the gridstore + if (!self.gs.isOpen) { + self.gs.open(function() { + self.gs.isOpen = true; + self.gs.write(chunk, function() { + process.nextTick(function() { + self.emit('drain'); + }); + }); + }); + return false; + } else { + self.gs.write(chunk, function() { + self.emit('drain'); + }); + return true; + } +}; + +GridStoreStream.prototype.end = function(chunk, encoding, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 0); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + chunk = args.length ? args.shift() : null; + encoding = args.length ? args.shift() : null; + self.endCalled = true; + + if (chunk) { + self.gs.write(chunk, function() { + self.gs.close(function() { + if (typeof callback === 'function') callback(); + self.emit('end'); + }); + }); + } + + self.gs.close(function() { + if (typeof callback === 'function') callback(); + self.emit('end'); + }); +}; + +/** + * The read() method pulls some data out of the internal buffer and returns it. If there is no data available, then it will return null. + * @function external:Duplex#read + * @param {number} size Optional argument to specify how much data to read. + * @return {(String | Buffer | null)} + */ + +/** + * Call this function to cause the stream to return strings of the specified encoding instead of Buffer objects. + * @function external:Duplex#setEncoding + * @param {string} encoding The encoding to use. + * @return {null} + */ + +/** + * This method will cause the readable stream to resume emitting data events. + * @function external:Duplex#resume + * @return {null} + */ + +/** + * This method will cause a stream in flowing-mode to stop emitting data events. Any data that becomes available will remain in the internal buffer. + * @function external:Duplex#pause + * @return {null} + */ + +/** + * This method pulls all the data out of a readable stream, and writes it to the supplied destination, automatically managing the flow so that the destination is not overwhelmed by a fast readable stream. + * @function external:Duplex#pipe + * @param {Writable} destination The destination for writing data + * @param {object} [options] Pipe options + * @return {null} + */ + +/** + * This method will remove the hooks set up for a previous pipe() call. + * @function external:Duplex#unpipe + * @param {Writable} [destination] The destination for writing data + * @return {null} + */ + +/** + * This is useful in certain cases where a stream is being consumed by a parser, which needs to "un-consume" some data that it has optimistically pulled out of the source, so that the stream can be passed on to some other party. + * @function external:Duplex#unshift + * @param {(Buffer|string)} chunk Chunk of data to unshift onto the read queue. + * @return {null} + */ + +/** + * Versions of Node prior to v0.10 had streams that did not implement the entire Streams API as it is today. (See "Compatibility" below for more information.) + * @function external:Duplex#wrap + * @param {Stream} stream An "old style" readable stream. + * @return {null} + */ + +/** + * This method writes some data to the underlying system, and calls the supplied callback once the data has been fully handled. + * @function external:Duplex#write + * @param {(string|Buffer)} chunk The data to write + * @param {string} encoding The encoding, if chunk is a String + * @param {function} callback Callback for when this chunk of data is flushed + * @return {boolean} + */ + +/** + * Call this method when no more data will be written to the stream. If supplied, the callback is attached as a listener on the finish event. + * @function external:Duplex#end + * @param {(string|Buffer)} chunk The data to write + * @param {string} encoding The encoding, if chunk is a String + * @param {function} callback Callback for when this chunk of data is flushed + * @return {null} + */ + +/** + * GridStoreStream stream data event, fired for each document in the cursor. + * + * @event GridStoreStream#data + * @type {object} + */ + +/** + * GridStoreStream stream end event + * + * @event GridStoreStream#end + * @type {null} + */ + +/** + * GridStoreStream stream close event + * + * @event GridStoreStream#close + * @type {null} + */ + +/** + * GridStoreStream stream readable event + * + * @event GridStoreStream#readable + * @type {null} + */ + +/** + * GridStoreStream stream drain event + * + * @event GridStoreStream#drain + * @type {null} + */ + +/** + * GridStoreStream stream finish event + * + * @event GridStoreStream#finish + * @type {null} + */ + +/** + * GridStoreStream stream pipe event + * + * @event GridStoreStream#pipe + * @type {null} + */ + +/** + * GridStoreStream stream unpipe event + * + * @event GridStoreStream#unpipe + * @type {null} + */ + +/** + * GridStoreStream stream error event + * + * @event GridStoreStream#error + * @type {null} + */ + +/** + * @ignore + */ +module.exports = GridStore; diff --git a/scripts/2.5/node_modules/mongodb/lib/mongo_client.js b/scripts/2.5/node_modules/mongodb/lib/mongo_client.js new file mode 100644 index 00000000..703eda64 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/mongo_client.js @@ -0,0 +1,479 @@ +'use strict'; + +const ChangeStream = require('./change_stream'); +const Db = require('./db'); +const EventEmitter = require('events').EventEmitter; +const executeOperation = require('./operations/execute_operation'); +const inherits = require('util').inherits; +const MongoError = require('./core').MongoError; +const deprecate = require('util').deprecate; +const WriteConcern = require('./write_concern'); +const MongoDBNamespace = require('./utils').MongoDBNamespace; +const ReadPreference = require('./core/topologies/read_preference'); + +// Operations +const ConnectOperation = require('./operations/connect'); +const CloseOperation = require('./operations/close'); + +/** + * @fileOverview The **MongoClient** class is a class that allows for making Connections to MongoDB. + * + * @example + * // Connect using a MongoClient instance + * const MongoClient = require('mongodb').MongoClient; + * const test = require('assert'); + * // Connection url + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * // Connect using MongoClient + * const mongoClient = new MongoClient(url); + * mongoClient.connect(function(err, client) { + * const db = client.db(dbName); + * client.close(); + * }); + * + * @example + * // Connect using the MongoClient.connect static method + * const MongoClient = require('mongodb').MongoClient; + * const test = require('assert'); + * // Connection url + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, client) { + * const db = client.db(dbName); + * client.close(); + * }); + */ + +/** + * A string specifying the level of a ReadConcern + * @typedef {'local'|'available'|'majority'|'linearizable'|'snapshot'} ReadConcernLevel + * @see https://docs.mongodb.com/manual/reference/read-concern/index.html#read-concern-levels + */ + +/** + * Configuration options for a automatic client encryption. + * + * **NOTE**: Support for client side encryption is in beta. Backwards-breaking changes may be made before the final release. + * + * @typedef {Object} AutoEncryptionOptions + * @property {MongoClient} [keyVaultClient] A `MongoClient` used to fetch keys from a key vault + * @property {string} [keyVaultNamespace] The namespace where keys are stored in the key vault + * @property {object} [kmsProviders] Provider details for the desired Key Management Service to use for encryption + * @property {object} [kmsProviders.aws] Optional settings for the AWS KMS provider + * @property {string} [kmsProviders.aws.accessKeyId] The access key used for the AWS KMS provider + * @property {string} [kmsProviders.aws.secretAccessKey] The secret access key used for the AWS KMS provider + * @property {object} [kmsProviders.local] Optional settings for the local KMS provider + * @property {string} [kmsProviders.local.key] The master key used to encrypt/decrypt data keys + * @property {object} [schemaMap] A map of namespaces to a local JSON schema for encryption + * @property {boolean} [bypassAutoEncryption] Allows the user to bypass auto encryption, maintaining implicit decryption + * @property {object} [extraOptions] Extra options related to the mongocryptd process + * @property {string} [extraOptions.mongocryptURI] A local process the driver communicates with to determine how to encrypt values in a command. Defaults to "mongodb://%2Fvar%2Fmongocryptd.sock" if domain sockets are available or "mongodb://localhost:27020" otherwise + * @property {boolean} [extraOptions.mongocryptdBypassSpawn=false] If true, autoEncryption will not attempt to spawn a mongocryptd before connecting + * @property {string} [extraOptions.mongocryptdSpawnPath] The path to the mongocryptd executable on the system + * @property {string[]} [extraOptions.mongocryptdSpawnArgs] Command line arguments to use when auto-spawning a mongocryptd + */ + +/** + * Creates a new MongoClient instance + * @class + * @param {string} url The connection URI string + * @param {object} [options] Optional settings + * @param {number} [options.poolSize=5] The maximum size of the individual server pool + * @param {boolean} [options.ssl=false] Enable SSL connection. + * @param {boolean} [options.sslValidate=false] Validate mongod server certificate against Certificate Authority + * @param {buffer} [options.sslCA=undefined] SSL Certificate store binary buffer + * @param {buffer} [options.sslCert=undefined] SSL Certificate binary buffer + * @param {buffer} [options.sslKey=undefined] SSL Key file binary buffer + * @param {string} [options.sslPass=undefined] SSL Certificate pass phrase + * @param {buffer} [options.sslCRL=undefined] SSL Certificate revocation list binary buffer + * @param {boolean} [options.autoReconnect=true] Enable autoReconnect for single server instances + * @param {boolean} [options.noDelay=true] TCP Connection no delay + * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled + * @param {number} [options.keepAliveInitialDelay=30000] The number of milliseconds to wait before initiating keepAlive on the TCP socket + * @param {number} [options.connectTimeoutMS=30000] TCP Connection timeout setting + * @param {number} [options.family] Version of IP stack. Can be 4, 6 or null (default). + * If null, will attempt to connect with IPv6, and will fall back to IPv4 on failure + * @param {number} [options.socketTimeoutMS=360000] TCP Socket timeout setting + * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times + * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries + * @param {boolean} [options.ha=true] Control if high availability monitoring runs for Replicaset or Mongos proxies + * @param {number} [options.haInterval=10000] The High availability period for replicaset inquiry + * @param {string} [options.replicaSet=undefined] The Replicaset set name + * @param {number} [options.secondaryAcceptableLatencyMS=15] Cutoff latency point in MS for Replicaset member selection + * @param {number} [options.acceptableLatencyMS=15] Cutoff latency point in MS for Mongos proxies selection + * @param {boolean} [options.connectWithNoPrimary=false] Sets if the driver should connect even if no primary is available + * @param {string} [options.authSource=undefined] Define the database to authenticate against + * @param {(number|string)} [options.w] The write concern + * @param {number} [options.wtimeout] The write concern timeout + * @param {boolean} [options.j=false] Specify a journal write concern + * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields + * @param {boolean} [options.raw=false] Return document results as raw BSON buffers + * @param {number} [options.bufferMaxEntries=-1] Sets a cap on how many operations the driver will buffer up before giving up on getting a working connection, default is -1 which is unlimited + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST) + * @param {object} [options.pkFactory] A primary key factory object for generation of custom _id keys + * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {object} [options.readConcern] Specify a read concern for the collection (only MongoDB 3.2 or higher supported) + * @param {ReadConcernLevel} [options.readConcern.level='local'] Specify a read concern level for the collection operations (only MongoDB 3.2 or higher supported) + * @param {number} [options.maxStalenessSeconds=undefined] The max staleness to secondary reads (values under 10 seconds cannot be guaranteed) + * @param {string} [options.loggerLevel=undefined] The logging level (error/warn/info/debug) + * @param {object} [options.logger=undefined] Custom logger object + * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types + * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers + * @param {boolean} [options.promoteLongs=true] Promotes long values to number if they fit inside the 53 bits resolution + * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit + * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function + * @param {object} [options.validateOptions=false] Validate MongoClient passed in options for correctness + * @param {string} [options.appname=undefined] The name of the application that created this MongoClient instance. MongoDB 3.4 and newer will print this value in the server log upon establishing each connection. It is also recorded in the slow query log and profile collections + * @param {string} [options.auth.user=undefined] The username for auth + * @param {string} [options.auth.password=undefined] The password for auth + * @param {string} [options.authMechanism=undefined] Mechanism for authentication: MDEFAULT, GSSAPI, PLAIN, MONGODB-X509, or SCRAM-SHA-1 + * @param {object} [options.compression] Type of compression to use: snappy or zlib + * @param {boolean} [options.fsync=false] Specify a file sync write concern + * @param {array} [options.readPreferenceTags] Read preference tags + * @param {number} [options.numberOfRetries=5] The number of retries for a tailable cursor + * @param {boolean} [options.auto_reconnect=true] Enable auto reconnecting for single server instances + * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this client + * @param {number} [options.minSize] If present, the connection pool will be initialized with minSize connections, and will never dip below minSize connections + * @param {boolean} [options.useNewUrlParser=true] Determines whether or not to use the new url parser. Enables the new, spec-compliant, url parser shipped in the core driver. This url parser fixes a number of problems with the original parser, and aims to outright replace that parser in the near future. Defaults to true, and must be explicitly set to false to use the legacy url parser. + * @param {boolean} [options.useUnifiedTopology] Enables the new unified topology layer + * @param {AutoEncryptionOptions} [options.autoEncryption] Optionally enable client side auto encryption + * @param {MongoClient~connectCallback} [callback] The command result callback + * @return {MongoClient} a MongoClient instance + */ +function MongoClient(url, options) { + if (!(this instanceof MongoClient)) return new MongoClient(url, options); + // Set up event emitter + EventEmitter.call(this); + + // The internal state + this.s = { + url: url, + options: options || {}, + promiseLibrary: null, + dbCache: new Map(), + sessions: new Set(), + writeConcern: WriteConcern.fromOptions(options), + namespace: new MongoDBNamespace('admin') + }; + + // Get the promiseLibrary + const promiseLibrary = this.s.options.promiseLibrary || Promise; + + // Add the promise to the internal state + this.s.promiseLibrary = promiseLibrary; +} + +/** + * @ignore + */ +inherits(MongoClient, EventEmitter); + +Object.defineProperty(MongoClient.prototype, 'writeConcern', { + enumerable: true, + get: function() { + return this.s.writeConcern; + } +}); + +Object.defineProperty(MongoClient.prototype, 'readPreference', { + enumerable: true, + get: function() { + return ReadPreference.primary; + } +}); + +/** + * The callback format for results + * @callback MongoClient~connectCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {MongoClient} client The connected client. + */ + +/** + * Connect to MongoDB using a url as documented at + * + * docs.mongodb.org/manual/reference/connection-string/ + * + * Note that for replicasets the replicaSet query parameter is required in the 2.0 driver + * + * @method + * @param {MongoClient~connectCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +MongoClient.prototype.connect = function(callback) { + if (typeof callback === 'string') { + throw new TypeError('`connect` only accepts a callback'); + } + + const operation = new ConnectOperation(this); + + return executeOperation(this, operation, callback); +}; + +MongoClient.prototype.logout = deprecate(function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + if (typeof callback === 'function') callback(null, true); +}, 'Multiple authentication is prohibited on a connected client, please only authenticate once per MongoClient'); + +/** + * Close the db and its underlying connections + * @method + * @param {boolean} [force=false] Force close, emitting no events + * @param {Db~noResultCallback} [callback] The result callback + * @return {Promise} returns Promise if no callback passed + */ +MongoClient.prototype.close = function(force, callback) { + if (typeof force === 'function') (callback = force), (force = false); + const operation = new CloseOperation(this, force); + return executeOperation(this, operation, callback); +}; + +/** + * Create a new Db instance sharing the current socket connections. Be aware that the new db instances are + * related in a parent-child relationship to the original instance so that events are correctly emitted on child + * db instances. Child db instances are cached so performing db('db1') twice will return the same instance. + * You can control these behaviors with the options noListener and returnNonCachedInstance. + * + * @method + * @param {string} [dbName] The name of the database we want to use. If not provided, use database name from connection string. + * @param {object} [options] Optional settings. + * @param {boolean} [options.noListener=false] Do not make the db an event listener to the original connection. + * @param {boolean} [options.returnNonCachedInstance=false] Control if you want to return a cached instance or have a new one created + * @return {Db} + */ +MongoClient.prototype.db = function(dbName, options) { + options = options || {}; + + // Default to db from connection string if not provided + if (!dbName) { + dbName = this.s.options.dbName; + } + + // Copy the options and add out internal override of the not shared flag + const finalOptions = Object.assign({}, this.s.options, options); + + // Do we have the db in the cache already + if (this.s.dbCache.has(dbName) && finalOptions.returnNonCachedInstance !== true) { + return this.s.dbCache.get(dbName); + } + + // Add promiseLibrary + finalOptions.promiseLibrary = this.s.promiseLibrary; + + // If no topology throw an error message + if (!this.topology) { + throw new MongoError('MongoClient must be connected before calling MongoClient.prototype.db'); + } + + // Return the db object + const db = new Db(dbName, this.topology, finalOptions); + + // Add the db to the cache + this.s.dbCache.set(dbName, db); + // Return the database + return db; +}; + +/** + * Check if MongoClient is connected + * + * @method + * @param {object} [options] Optional settings. + * @param {boolean} [options.noListener=false] Do not make the db an event listener to the original connection. + * @param {boolean} [options.returnNonCachedInstance=false] Control if you want to return a cached instance or have a new one created + * @return {boolean} + */ +MongoClient.prototype.isConnected = function(options) { + options = options || {}; + + if (!this.topology) return false; + return this.topology.isConnected(options); +}; + +/** + * Connect to MongoDB using a url as documented at + * + * docs.mongodb.org/manual/reference/connection-string/ + * + * Note that for replicasets the replicaSet query parameter is required in the 2.0 driver + * + * @method + * @static + * @param {string} url The connection URI string + * @param {object} [options] Optional settings + * @param {number} [options.poolSize=5] The maximum size of the individual server pool + * @param {boolean} [options.ssl=false] Enable SSL connection. + * @param {boolean} [options.sslValidate=false] Validate mongod server certificate against Certificate Authority + * @param {buffer} [options.sslCA=undefined] SSL Certificate store binary buffer + * @param {buffer} [options.sslCert=undefined] SSL Certificate binary buffer + * @param {buffer} [options.sslKey=undefined] SSL Key file binary buffer + * @param {string} [options.sslPass=undefined] SSL Certificate pass phrase + * @param {buffer} [options.sslCRL=undefined] SSL Certificate revocation list binary buffer + * @param {boolean} [options.autoReconnect=true] Enable autoReconnect for single server instances + * @param {boolean} [options.noDelay=true] TCP Connection no delay + * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled + * @param {boolean} [options.keepAliveInitialDelay=30000] The number of milliseconds to wait before initiating keepAlive on the TCP socket + * @param {number} [options.connectTimeoutMS=30000] TCP Connection timeout setting + * @param {number} [options.family] Version of IP stack. Can be 4, 6 or null (default). + * If null, will attempt to connect with IPv6, and will fall back to IPv4 on failure + * @param {number} [options.socketTimeoutMS=360000] TCP Socket timeout setting + * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times + * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries + * @param {boolean} [options.ha=true] Control if high availability monitoring runs for Replicaset or Mongos proxies + * @param {number} [options.haInterval=10000] The High availability period for replicaset inquiry + * @param {string} [options.replicaSet=undefined] The Replicaset set name + * @param {number} [options.secondaryAcceptableLatencyMS=15] Cutoff latency point in MS for Replicaset member selection + * @param {number} [options.acceptableLatencyMS=15] Cutoff latency point in MS for Mongos proxies selection + * @param {boolean} [options.connectWithNoPrimary=false] Sets if the driver should connect even if no primary is available + * @param {string} [options.authSource=undefined] Define the database to authenticate against + * @param {(number|string)} [options.w] The write concern + * @param {number} [options.wtimeout] The write concern timeout + * @param {boolean} [options.j=false] Specify a journal write concern + * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields + * @param {boolean} [options.raw=false] Return document results as raw BSON buffers + * @param {number} [options.bufferMaxEntries=-1] Sets a cap on how many operations the driver will buffer up before giving up on getting a working connection, default is -1 which is unlimited + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST) + * @param {object} [options.pkFactory] A primary key factory object for generation of custom _id keys + * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {object} [options.readConcern] Specify a read concern for the collection (only MongoDB 3.2 or higher supported) + * @param {ReadConcernLevel} [options.readConcern.level='local'] Specify a read concern level for the collection operations (only MongoDB 3.2 or higher supported) + * @param {number} [options.maxStalenessSeconds=undefined] The max staleness to secondary reads (values under 10 seconds cannot be guaranteed) + * @param {string} [options.loggerLevel=undefined] The logging level (error/warn/info/debug) + * @param {object} [options.logger=undefined] Custom logger object + * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types + * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers + * @param {boolean} [options.promoteLongs=true] Promotes long values to number if they fit inside the 53 bits resolution + * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit + * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function + * @param {object} [options.validateOptions=false] Validate MongoClient passed in options for correctness + * @param {string} [options.appname=undefined] The name of the application that created this MongoClient instance. MongoDB 3.4 and newer will print this value in the server log upon establishing each connection. It is also recorded in the slow query log and profile collections + * @param {string} [options.auth.user=undefined] The username for auth + * @param {string} [options.auth.password=undefined] The password for auth + * @param {string} [options.authMechanism=undefined] Mechanism for authentication: MDEFAULT, GSSAPI, PLAIN, MONGODB-X509, or SCRAM-SHA-1 + * @param {object} [options.compression] Type of compression to use: snappy or zlib + * @param {boolean} [options.fsync=false] Specify a file sync write concern + * @param {array} [options.readPreferenceTags] Read preference tags + * @param {number} [options.numberOfRetries=5] The number of retries for a tailable cursor + * @param {boolean} [options.auto_reconnect=true] Enable auto reconnecting for single server instances + * @param {number} [options.minSize] If present, the connection pool will be initialized with minSize connections, and will never dip below minSize connections + * @param {MongoClient~connectCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +MongoClient.connect = function(url, options, callback) { + const args = Array.prototype.slice.call(arguments, 1); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + options = args.length ? args.shift() : null; + options = options || {}; + + // Create client + const mongoClient = new MongoClient(url, options); + // Execute the connect method + return mongoClient.connect(callback); +}; + +/** + * Starts a new session on the server + * + * @param {SessionOptions} [options] optional settings for a driver session + * @return {ClientSession} the newly established session + */ +MongoClient.prototype.startSession = function(options) { + options = Object.assign({ explicit: true }, options); + if (!this.topology) { + throw new MongoError('Must connect to a server before calling this method'); + } + + if (!this.topology.hasSessionSupport()) { + throw new MongoError('Current topology does not support sessions'); + } + + return this.topology.startSession(options, this.s.options); +}; + +/** + * Runs a given operation with an implicitly created session. The lifetime of the session + * will be handled without the need for user interaction. + * + * NOTE: presently the operation MUST return a Promise (either explicit or implicity as an async function) + * + * @param {Object} [options] Optional settings to be appled to implicitly created session + * @param {Function} operation An operation to execute with an implicitly created session. The signature of this MUST be `(session) => {}` + * @return {Promise} + */ +MongoClient.prototype.withSession = function(options, operation) { + if (typeof options === 'function') (operation = options), (options = undefined); + const session = this.startSession(options); + + let cleanupHandler = (err, result, opts) => { + // prevent multiple calls to cleanupHandler + cleanupHandler = () => { + throw new ReferenceError('cleanupHandler was called too many times'); + }; + + opts = Object.assign({ throw: true }, opts); + session.endSession(); + + if (err) { + if (opts.throw) throw err; + return Promise.reject(err); + } + }; + + try { + const result = operation(session); + return Promise.resolve(result) + .then(result => cleanupHandler(null, result)) + .catch(err => cleanupHandler(err, null, { throw: true })); + } catch (err) { + return cleanupHandler(err, null, { throw: false }); + } +}; +/** + * Create a new Change Stream, watching for new changes (insertions, updates, replacements, deletions, and invalidations) in this cluster. Will ignore all changes to system collections, as well as the local, admin, + * and config databases. + * @method + * @since 3.1.0 + * @param {Array} [pipeline] An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents. + * @param {object} [options] Optional settings + * @param {string} [options.fullDocument='default'] Allowed values: ‘default’, ‘updateLookup’. When set to ‘updateLookup’, the change stream will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred. + * @param {object} [options.resumeAfter] Specifies the logical starting point for the new change stream. This should be the _id field from a previously returned change stream document. + * @param {number} [options.maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a change stream query + * @param {number} [options.batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. + * @param {object} [options.collation] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. + * @param {ReadPreference} [options.readPreference] The read preference. See {@link https://docs.mongodb.com/manual/reference/read-preference|read preference documentation}. + * @param {Timestamp} [options.startAtOperationTime] receive change events that occur after the specified timestamp + * @param {ClientSession} [options.session] optional session to use for this operation + * @return {ChangeStream} a ChangeStream instance. + */ +MongoClient.prototype.watch = function(pipeline, options) { + pipeline = pipeline || []; + options = options || {}; + + // Allow optionally not specifying a pipeline + if (!Array.isArray(pipeline)) { + options = pipeline; + pipeline = []; + } + + return new ChangeStream(this, pipeline, options); +}; + +/** + * Return the mongo client logger + * @method + * @return {Logger} return the mongo client logger + * @ignore + */ +MongoClient.prototype.getLogger = function() { + return this.s.options.logger; +}; + +module.exports = MongoClient; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/add_user.js b/scripts/2.5/node_modules/mongodb/lib/operations/add_user.js new file mode 100644 index 00000000..1f3f3a6f --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/operations/add_user.js @@ -0,0 +1,96 @@ +'use strict'; + +const Aspect = require('./operation').Aspect; +const CommandOperation = require('./command'); +const defineAspects = require('./operation').defineAspects; +const crypto = require('crypto'); +const handleCallback = require('../utils').handleCallback; +const toError = require('../utils').toError; + +class AddUserOperation extends CommandOperation { + constructor(db, username, password, options) { + super(db, options); + + this.username = username; + this.password = password; + } + + _buildCommand() { + const db = this.db; + const username = this.username; + const password = this.password; + const options = this.options; + + // Get additional values + let roles = Array.isArray(options.roles) ? options.roles : []; + + // If not roles defined print deprecated message + // TODO: handle deprecation properly + if (roles.length === 0) { + console.log('Creating a user without roles is deprecated in MongoDB >= 2.6'); + } + + // Check the db name and add roles if needed + if ( + (db.databaseName.toLowerCase() === 'admin' || options.dbName === 'admin') && + !Array.isArray(options.roles) + ) { + roles = ['root']; + } else if (!Array.isArray(options.roles)) { + roles = ['dbOwner']; + } + + const digestPassword = db.s.topology.lastIsMaster().maxWireVersion >= 7; + + let userPassword = password; + + if (!digestPassword) { + // Use node md5 generator + const md5 = crypto.createHash('md5'); + // Generate keys used for authentication + md5.update(username + ':mongo:' + password); + userPassword = md5.digest('hex'); + } + + // Build the command to execute + const command = { + createUser: username, + customData: options.customData || {}, + roles: roles, + digestPassword + }; + + // No password + if (typeof password === 'string') { + command.pwd = userPassword; + } + + return command; + } + + execute(callback) { + const options = this.options; + + // Error out if digestPassword set + if (options.digestPassword != null) { + return callback( + toError( + "The digestPassword option is not supported via add_user. Please use db.command('createUser', ...) instead for this option." + ) + ); + } + + // Attempt to execute auth command + super.execute((err, r) => { + if (!err) { + return handleCallback(callback, err, r); + } + + return handleCallback(callback, err, null); + }); + } +} + +defineAspects(AddUserOperation, Aspect.WRITE_OPERATION); + +module.exports = AddUserOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/admin_ops.js b/scripts/2.5/node_modules/mongodb/lib/operations/admin_ops.js new file mode 100644 index 00000000..b08071c3 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/operations/admin_ops.js @@ -0,0 +1,62 @@ +'use strict'; + +const executeCommand = require('./db_ops').executeCommand; +const executeDbAdminCommand = require('./db_ops').executeDbAdminCommand; + +/** + * Get ReplicaSet status + * + * @param {Admin} a collection instance. + * @param {Object} [options] Optional settings. See Admin.prototype.replSetGetStatus for a list of options. + * @param {Admin~resultCallback} [callback] The command result callback. + */ +function replSetGetStatus(admin, options, callback) { + executeDbAdminCommand(admin.s.db, { replSetGetStatus: 1 }, options, callback); +} + +/** + * Retrieve this db's server status. + * + * @param {Admin} a collection instance. + * @param {Object} [options] Optional settings. See Admin.prototype.serverStatus for a list of options. + * @param {Admin~resultCallback} [callback] The command result callback + */ +function serverStatus(admin, options, callback) { + executeDbAdminCommand(admin.s.db, { serverStatus: 1 }, options, callback); +} + +/** + * Validate an existing collection + * + * @param {Admin} a collection instance. + * @param {string} collectionName The name of the collection to validate. + * @param {Object} [options] Optional settings. See Admin.prototype.validateCollection for a list of options. + * @param {Admin~resultCallback} [callback] The command result callback. + */ +function validateCollection(admin, collectionName, options, callback) { + const command = { validate: collectionName }; + const keys = Object.keys(options); + + // Decorate command with extra options + for (let i = 0; i < keys.length; i++) { + if (options.hasOwnProperty(keys[i]) && keys[i] !== 'session') { + command[keys[i]] = options[keys[i]]; + } + } + + executeCommand(admin.s.db, command, options, (err, doc) => { + if (err != null) return callback(err, null); + + if (doc.ok === 0) return callback(new Error('Error with validate command'), null); + if (doc.result != null && doc.result.constructor !== String) + return callback(new Error('Error with validation data'), null); + if (doc.result != null && doc.result.match(/exception|corrupt/) != null) + return callback(new Error('Error: invalid collection ' + collectionName), null); + if (doc.valid != null && !doc.valid) + return callback(new Error('Error: invalid collection ' + collectionName), null); + + return callback(null, doc); + }); +} + +module.exports = { replSetGetStatus, serverStatus, validateCollection }; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/aggregate.js b/scripts/2.5/node_modules/mongodb/lib/operations/aggregate.js new file mode 100644 index 00000000..e0f2da84 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/operations/aggregate.js @@ -0,0 +1,106 @@ +'use strict'; + +const CommandOperationV2 = require('./command_v2'); +const MongoError = require('../core').MongoError; +const maxWireVersion = require('../core/utils').maxWireVersion; +const ReadPreference = require('../core').ReadPreference; +const Aspect = require('./operation').Aspect; +const defineAspects = require('./operation').defineAspects; + +const DB_AGGREGATE_COLLECTION = 1; +const MIN_WIRE_VERSION_$OUT_READ_CONCERN_SUPPORT = 8; + +class AggregateOperation extends CommandOperationV2 { + constructor(parent, pipeline, options) { + super(parent, options, { fullResponse: true }); + + this.target = + parent.s.namespace && parent.s.namespace.collection + ? parent.s.namespace.collection + : DB_AGGREGATE_COLLECTION; + + this.pipeline = pipeline; + + // determine if we have a write stage, override read preference if so + this.hasWriteStage = false; + if (typeof options.out === 'string') { + this.pipeline = this.pipeline.concat({ $out: options.out }); + this.hasWriteStage = true; + } else if (pipeline.length > 0) { + const finalStage = pipeline[pipeline.length - 1]; + if (finalStage.$out || finalStage.$merge) { + this.hasWriteStage = true; + } + } + + if (this.hasWriteStage) { + this.readPreference = ReadPreference.primary; + } + + if (options.explain && (this.readConcern || this.writeConcern)) { + throw new MongoError( + '"explain" cannot be used on an aggregate call with readConcern/writeConcern' + ); + } + + if (options.cursor != null && typeof options.cursor !== 'object') { + throw new MongoError('cursor options must be an object'); + } + } + + get canRetryRead() { + return !this.hasWriteStage; + } + + addToPipeline(stage) { + this.pipeline.push(stage); + } + + execute(server, callback) { + const options = this.options; + const serverWireVersion = maxWireVersion(server); + const command = { aggregate: this.target, pipeline: this.pipeline }; + + if (this.hasWriteStage && serverWireVersion < MIN_WIRE_VERSION_$OUT_READ_CONCERN_SUPPORT) { + this.readConcern = null; + } + + if (serverWireVersion >= 5) { + if (this.hasWriteStage && this.writeConcern) { + Object.assign(command, { writeConcern: this.writeConcern }); + } + } + + if (options.bypassDocumentValidation === true) { + command.bypassDocumentValidation = options.bypassDocumentValidation; + } + + if (typeof options.allowDiskUse === 'boolean') { + command.allowDiskUse = options.allowDiskUse; + } + + if (options.hint) { + command.hint = options.hint; + } + + if (options.explain) { + options.full = false; + command.explain = options.explain; + } + + command.cursor = options.cursor || {}; + if (options.batchSize && !this.hasWriteStage) { + command.cursor.batchSize = options.batchSize; + } + + super.executeCommand(server, command, callback); + } +} + +defineAspects(AggregateOperation, [ + Aspect.READ_OPERATION, + Aspect.RETRYABLE, + Aspect.EXECUTE_WITH_SELECTION +]); + +module.exports = AggregateOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/bulk_write.js b/scripts/2.5/node_modules/mongodb/lib/operations/bulk_write.js new file mode 100644 index 00000000..8f14f021 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/operations/bulk_write.js @@ -0,0 +1,104 @@ +'use strict'; + +const applyRetryableWrites = require('../utils').applyRetryableWrites; +const applyWriteConcern = require('../utils').applyWriteConcern; +const MongoError = require('../core').MongoError; +const OperationBase = require('./operation').OperationBase; + +class BulkWriteOperation extends OperationBase { + constructor(collection, operations, options) { + super(options); + + this.collection = collection; + this.operations = operations; + } + + execute(callback) { + const coll = this.collection; + const operations = this.operations; + let options = this.options; + + // Add ignoreUndfined + if (coll.s.options.ignoreUndefined) { + options = Object.assign({}, options); + options.ignoreUndefined = coll.s.options.ignoreUndefined; + } + + // Create the bulk operation + const bulk = + options.ordered === true || options.ordered == null + ? coll.initializeOrderedBulkOp(options) + : coll.initializeUnorderedBulkOp(options); + + // Do we have a collation + let collation = false; + + // for each op go through and add to the bulk + try { + for (let i = 0; i < operations.length; i++) { + // Get the operation type + const key = Object.keys(operations[i])[0]; + // Check if we have a collation + if (operations[i][key].collation) { + collation = true; + } + + // Pass to the raw bulk + bulk.raw(operations[i]); + } + } catch (err) { + return callback(err, null); + } + + // Final options for retryable writes and write concern + let finalOptions = Object.assign({}, options); + finalOptions = applyRetryableWrites(finalOptions, coll.s.db); + finalOptions = applyWriteConcern(finalOptions, { db: coll.s.db, collection: coll }, options); + + const writeCon = finalOptions.writeConcern ? finalOptions.writeConcern : {}; + const capabilities = coll.s.topology.capabilities(); + + // Did the user pass in a collation, check if our write server supports it + if (collation && capabilities && !capabilities.commandsTakeCollation) { + return callback(new MongoError('server/primary/mongos does not support collation')); + } + + // Execute the bulk + bulk.execute(writeCon, finalOptions, (err, r) => { + // We have connection level error + if (!r && err) { + return callback(err, null); + } + + r.insertedCount = r.nInserted; + r.matchedCount = r.nMatched; + r.modifiedCount = r.nModified || 0; + r.deletedCount = r.nRemoved; + r.upsertedCount = r.getUpsertedIds().length; + r.upsertedIds = {}; + r.insertedIds = {}; + + // Update the n + r.n = r.insertedCount; + + // Inserted documents + const inserted = r.getInsertedIds(); + // Map inserted ids + for (let i = 0; i < inserted.length; i++) { + r.insertedIds[inserted[i].index] = inserted[i]._id; + } + + // Upserted documents + const upserted = r.getUpsertedIds(); + // Map upserted ids + for (let i = 0; i < upserted.length; i++) { + r.upsertedIds[upserted[i].index] = upserted[i]._id; + } + + // Return the results + callback(null, r); + }); + } +} + +module.exports = BulkWriteOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/close.js b/scripts/2.5/node_modules/mongodb/lib/operations/close.js new file mode 100644 index 00000000..57fdef6f --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/operations/close.js @@ -0,0 +1,46 @@ +'use strict'; + +const Aspect = require('./operation').Aspect; +const defineAspects = require('./operation').defineAspects; +const OperationBase = require('./operation').OperationBase; + +class CloseOperation extends OperationBase { + constructor(client, force) { + super(); + this.client = client; + this.force = force; + } + + execute(callback) { + const client = this.client; + const force = this.force; + const completeClose = err => { + client.emit('close', client); + for (const item of client.s.dbCache) { + item[1].emit('close', client); + } + + client.removeAllListeners('close'); + callback(err, null); + }; + + if (client.topology == null) { + completeClose(); + return; + } + + client.topology.close(force, err => { + const autoEncrypter = client.topology.s.options.autoEncrypter; + if (!autoEncrypter) { + completeClose(err); + return; + } + + autoEncrypter.teardown(force, err2 => completeClose(err || err2)); + }); + } +} + +defineAspects(CloseOperation, [Aspect.SKIP_SESSION]); + +module.exports = CloseOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/collection_ops.js b/scripts/2.5/node_modules/mongodb/lib/operations/collection_ops.js new file mode 100644 index 00000000..df5995d7 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/operations/collection_ops.js @@ -0,0 +1,374 @@ +'use strict'; + +const applyWriteConcern = require('../utils').applyWriteConcern; +const Code = require('../core').BSON.Code; +const createIndexDb = require('./db_ops').createIndex; +const decorateWithCollation = require('../utils').decorateWithCollation; +const decorateWithReadConcern = require('../utils').decorateWithReadConcern; +const ensureIndexDb = require('./db_ops').ensureIndex; +const evaluate = require('./db_ops').evaluate; +const executeCommand = require('./db_ops').executeCommand; +const resolveReadPreference = require('../utils').resolveReadPreference; +const handleCallback = require('../utils').handleCallback; +const indexInformationDb = require('./db_ops').indexInformation; +const Long = require('../core').BSON.Long; +const MongoError = require('../core').MongoError; +const ReadPreference = require('../core').ReadPreference; +const toError = require('../utils').toError; +const insertDocuments = require('./common_functions').insertDocuments; +const updateDocuments = require('./common_functions').updateDocuments; + +/** + * Group function helper + * @ignore + */ +// var groupFunction = function () { +// var c = db[ns].find(condition); +// var map = new Map(); +// var reduce_function = reduce; +// +// while (c.hasNext()) { +// var obj = c.next(); +// var key = {}; +// +// for (var i = 0, len = keys.length; i < len; ++i) { +// var k = keys[i]; +// key[k] = obj[k]; +// } +// +// var aggObj = map.get(key); +// +// if (aggObj == null) { +// var newObj = Object.extend({}, key); +// aggObj = Object.extend(newObj, initial); +// map.put(key, aggObj); +// } +// +// reduce_function(obj, aggObj); +// } +// +// return { "result": map.values() }; +// }.toString(); +const groupFunction = + 'function () {\nvar c = db[ns].find(condition);\nvar map = new Map();\nvar reduce_function = reduce;\n\nwhile (c.hasNext()) {\nvar obj = c.next();\nvar key = {};\n\nfor (var i = 0, len = keys.length; i < len; ++i) {\nvar k = keys[i];\nkey[k] = obj[k];\n}\n\nvar aggObj = map.get(key);\n\nif (aggObj == null) {\nvar newObj = Object.extend({}, key);\naggObj = Object.extend(newObj, initial);\nmap.put(key, aggObj);\n}\n\nreduce_function(obj, aggObj);\n}\n\nreturn { "result": map.values() };\n}'; + +// Check the update operation to ensure it has atomic operators. +function checkForAtomicOperators(update) { + if (Array.isArray(update)) { + return update.reduce((err, u) => err || checkForAtomicOperators(u), null); + } + + const keys = Object.keys(update); + + // same errors as the server would give for update doc lacking atomic operators + if (keys.length === 0) { + return toError('The update operation document must contain at least one atomic operator.'); + } + + if (keys[0][0] !== '$') { + return toError('the update operation document must contain atomic operators.'); + } +} + +/** + * Create an index on the db and collection. + * + * @method + * @param {Collection} a Collection instance. + * @param {(string|object)} fieldOrSpec Defines the index. + * @param {object} [options] Optional settings. See Collection.prototype.createIndex for a list of options. + * @param {Collection~resultCallback} [callback] The command result callback + */ +function createIndex(coll, fieldOrSpec, options, callback) { + createIndexDb(coll.s.db, coll.collectionName, fieldOrSpec, options, callback); +} + +/** + * Create multiple indexes in the collection. This method is only supported for + * MongoDB 2.6 or higher. Earlier version of MongoDB will throw a command not supported + * error. Index specifications are defined at http://docs.mongodb.org/manual/reference/command/createIndexes/. + * + * @method + * @param {Collection} a Collection instance. + * @param {array} indexSpecs An array of index specifications to be created + * @param {Object} [options] Optional settings. See Collection.prototype.createIndexes for a list of options. + * @param {Collection~resultCallback} [callback] The command result callback + */ +function createIndexes(coll, indexSpecs, options, callback) { + const capabilities = coll.s.topology.capabilities(); + + // Ensure we generate the correct name if the parameter is not set + for (let i = 0; i < indexSpecs.length; i++) { + if (indexSpecs[i].name == null) { + const keys = []; + + // Did the user pass in a collation, check if our write server supports it + if (indexSpecs[i].collation && capabilities && !capabilities.commandsTakeCollation) { + return callback(new MongoError('server/primary/mongos does not support collation')); + } + + for (let name in indexSpecs[i].key) { + keys.push(`${name}_${indexSpecs[i].key[name]}`); + } + + // Set the name + indexSpecs[i].name = keys.join('_'); + } + } + + options = Object.assign({}, options, { readPreference: ReadPreference.PRIMARY }); + + // Execute the index + executeCommand( + coll.s.db, + { + createIndexes: coll.collectionName, + indexes: indexSpecs + }, + options, + callback + ); +} + +/** + * Ensure that an index exists. If the index does not exist, this function creates it. + * + * @method + * @param {Collection} a Collection instance. + * @param {(string|object)} fieldOrSpec Defines the index. + * @param {object} [options] Optional settings. See Collection.prototype.ensureIndex for a list of options. + * @param {Collection~resultCallback} [callback] The command result callback + */ +function ensureIndex(coll, fieldOrSpec, options, callback) { + ensureIndexDb(coll.s.db, coll.collectionName, fieldOrSpec, options, callback); +} + +/** + * Run a group command across a collection. + * + * @method + * @param {Collection} a Collection instance. + * @param {(object|array|function|code)} keys An object, array or function expressing the keys to group by. + * @param {object} condition An optional condition that must be true for a row to be considered. + * @param {object} initial Initial value of the aggregation counter object. + * @param {(function|Code)} reduce The reduce function aggregates (reduces) the objects iterated + * @param {(function|Code)} finalize An optional function to be run on each item in the result set just before the item is returned. + * @param {boolean} command Specify if you wish to run using the internal group command or using eval, default is true. + * @param {object} [options] Optional settings. See Collection.prototype.group for a list of options. + * @param {Collection~resultCallback} [callback] The command result callback + * @deprecated MongoDB 3.6 or higher will no longer support the group command. We recommend rewriting using the aggregation framework. + */ +function group(coll, keys, condition, initial, reduce, finalize, command, options, callback) { + // Execute using the command + if (command) { + const reduceFunction = reduce && reduce._bsontype === 'Code' ? reduce : new Code(reduce); + + const selector = { + group: { + ns: coll.collectionName, + $reduce: reduceFunction, + cond: condition, + initial: initial, + out: 'inline' + } + }; + + // if finalize is defined + if (finalize != null) selector.group['finalize'] = finalize; + // Set up group selector + if ('function' === typeof keys || (keys && keys._bsontype === 'Code')) { + selector.group.$keyf = keys && keys._bsontype === 'Code' ? keys : new Code(keys); + } else { + const hash = {}; + keys.forEach(key => { + hash[key] = 1; + }); + selector.group.key = hash; + } + + options = Object.assign({}, options); + // Ensure we have the right read preference inheritance + options.readPreference = resolveReadPreference(coll, options); + + // Do we have a readConcern specified + decorateWithReadConcern(selector, coll, options); + + // Have we specified collation + try { + decorateWithCollation(selector, coll, options); + } catch (err) { + return callback(err, null); + } + + // Execute command + executeCommand(coll.s.db, selector, options, (err, result) => { + if (err) return handleCallback(callback, err, null); + handleCallback(callback, null, result.retval); + }); + } else { + // Create execution scope + const scope = reduce != null && reduce._bsontype === 'Code' ? reduce.scope : {}; + + scope.ns = coll.collectionName; + scope.keys = keys; + scope.condition = condition; + scope.initial = initial; + + // Pass in the function text to execute within mongodb. + const groupfn = groupFunction.replace(/ reduce;/, reduce.toString() + ';'); + + evaluate(coll.s.db, new Code(groupfn, scope), null, options, (err, results) => { + if (err) return handleCallback(callback, err, null); + handleCallback(callback, null, results.result || results); + }); + } +} + +/** + * Retrieve all the indexes on the collection. + * + * @method + * @param {Collection} a Collection instance. + * @param {Object} [options] Optional settings. See Collection.prototype.indexes for a list of options. + * @param {Collection~resultCallback} [callback] The command result callback + */ +function indexes(coll, options, callback) { + options = Object.assign({}, { full: true }, options); + indexInformationDb(coll.s.db, coll.collectionName, options, callback); +} + +/** + * Check if one or more indexes exist on the collection. This fails on the first index that doesn't exist. + * + * @method + * @param {Collection} a Collection instance. + * @param {(string|array)} indexes One or more index names to check. + * @param {Object} [options] Optional settings. See Collection.prototype.indexExists for a list of options. + * @param {Collection~resultCallback} [callback] The command result callback + */ +function indexExists(coll, indexes, options, callback) { + indexInformation(coll, options, (err, indexInformation) => { + // If we have an error return + if (err != null) return handleCallback(callback, err, null); + // Let's check for the index names + if (!Array.isArray(indexes)) + return handleCallback(callback, null, indexInformation[indexes] != null); + // Check in list of indexes + for (let i = 0; i < indexes.length; i++) { + if (indexInformation[indexes[i]] == null) { + return handleCallback(callback, null, false); + } + } + + // All keys found return true + return handleCallback(callback, null, true); + }); +} + +/** + * Retrieve this collection's index info. + * + * @method + * @param {Collection} a Collection instance. + * @param {object} [options] Optional settings. See Collection.prototype.indexInformation for a list of options. + * @param {Collection~resultCallback} [callback] The command result callback + */ +function indexInformation(coll, options, callback) { + indexInformationDb(coll.s.db, coll.collectionName, options, callback); +} + +/** + * Return N parallel cursors for a collection to allow parallel reading of the entire collection. There are + * no ordering guarantees for returned results. + * + * @method + * @param {Collection} a Collection instance. + * @param {object} [options] Optional settings. See Collection.prototype.parallelCollectionScan for a list of options. + * @param {Collection~parallelCollectionScanCallback} [callback] The command result callback + */ +function parallelCollectionScan(coll, options, callback) { + // Create command object + const commandObject = { + parallelCollectionScan: coll.collectionName, + numCursors: options.numCursors + }; + + // Do we have a readConcern specified + decorateWithReadConcern(commandObject, coll, options); + + // Store the raw value + const raw = options.raw; + delete options['raw']; + + // Execute the command + executeCommand(coll.s.db, commandObject, options, (err, result) => { + if (err) return handleCallback(callback, err, null); + if (result == null) + return handleCallback( + callback, + new Error('no result returned for parallelCollectionScan'), + null + ); + + options = Object.assign({ explicitlyIgnoreSession: true }, options); + + const cursors = []; + // Add the raw back to the option + if (raw) options.raw = raw; + // Create command cursors for each item + for (let i = 0; i < result.cursors.length; i++) { + const rawId = result.cursors[i].cursor.id; + // Convert cursorId to Long if needed + const cursorId = typeof rawId === 'number' ? Long.fromNumber(rawId) : rawId; + // Add a command cursor + cursors.push(coll.s.topology.cursor(coll.namespace, cursorId, options)); + } + + handleCallback(callback, null, cursors); + }); +} + +/** + * Save a document. + * + * @method + * @param {Collection} a Collection instance. + * @param {object} doc Document to save + * @param {object} [options] Optional settings. See Collection.prototype.save for a list of options. + * @param {Collection~writeOpCallback} [callback] The command result callback + * @deprecated use insertOne, insertMany, updateOne or updateMany + */ +function save(coll, doc, options, callback) { + // Get the write concern options + const finalOptions = applyWriteConcern( + Object.assign({}, options), + { db: coll.s.db, collection: coll }, + options + ); + // Establish if we need to perform an insert or update + if (doc._id != null) { + finalOptions.upsert = true; + return updateDocuments(coll, { _id: doc._id }, doc, finalOptions, callback); + } + + // Insert the document + insertDocuments(coll, [doc], finalOptions, (err, result) => { + if (callback == null) return; + if (doc == null) return handleCallback(callback, null, null); + if (err) return handleCallback(callback, err, null); + handleCallback(callback, null, result); + }); +} + +module.exports = { + checkForAtomicOperators, + createIndex, + createIndexes, + ensureIndex, + group, + indexes, + indexExists, + indexInformation, + parallelCollectionScan, + save +}; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/collections.js b/scripts/2.5/node_modules/mongodb/lib/operations/collections.js new file mode 100644 index 00000000..eac690a2 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/operations/collections.js @@ -0,0 +1,55 @@ +'use strict'; + +const OperationBase = require('./operation').OperationBase; +const handleCallback = require('../utils').handleCallback; + +let collection; +function loadCollection() { + if (!collection) { + collection = require('../collection'); + } + return collection; +} + +class CollectionsOperation extends OperationBase { + constructor(db, options) { + super(options); + + this.db = db; + } + + execute(callback) { + const db = this.db; + let options = this.options; + + let Collection = loadCollection(); + + options = Object.assign({}, options, { nameOnly: true }); + // Let's get the collection names + db.listCollections({}, options).toArray((err, documents) => { + if (err != null) return handleCallback(callback, err, null); + // Filter collections removing any illegal ones + documents = documents.filter(doc => { + return doc.name.indexOf('$') === -1; + }); + + // Return the collection objects + handleCallback( + callback, + null, + documents.map(d => { + return new Collection( + db, + db.s.topology, + db.databaseName, + d.name, + db.s.pkFactory, + db.s.options + ); + }) + ); + }); + } +} + +module.exports = CollectionsOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/command.js b/scripts/2.5/node_modules/mongodb/lib/operations/command.js new file mode 100644 index 00000000..3c795bef --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/operations/command.js @@ -0,0 +1,120 @@ +'use strict'; + +const Aspect = require('./operation').Aspect; +const OperationBase = require('./operation').OperationBase; +const applyWriteConcern = require('../utils').applyWriteConcern; +const debugOptions = require('../utils').debugOptions; +const handleCallback = require('../utils').handleCallback; +const MongoError = require('../core').MongoError; +const ReadPreference = require('../core').ReadPreference; +const resolveReadPreference = require('../utils').resolveReadPreference; +const MongoDBNamespace = require('../utils').MongoDBNamespace; + +const debugFields = [ + 'authSource', + 'w', + 'wtimeout', + 'j', + 'native_parser', + 'forceServerObjectId', + 'serializeFunctions', + 'raw', + 'promoteLongs', + 'promoteValues', + 'promoteBuffers', + 'bufferMaxEntries', + 'numberOfRetries', + 'retryMiliSeconds', + 'readPreference', + 'pkFactory', + 'parentDb', + 'promiseLibrary', + 'noListener' +]; + +class CommandOperation extends OperationBase { + constructor(db, options, collection, command) { + super(options); + + if (!this.hasAspect(Aspect.WRITE_OPERATION)) { + if (collection != null) { + this.options.readPreference = resolveReadPreference(collection, options); + } else { + this.options.readPreference = resolveReadPreference(db, options); + } + } else { + if (collection != null) { + applyWriteConcern(this.options, { db, coll: collection }, this.options); + } else { + applyWriteConcern(this.options, { db }, this.options); + } + this.options.readPreference = ReadPreference.primary; + } + + this.db = db; + + if (command != null) { + this.command = command; + } + + if (collection != null) { + this.collection = collection; + } + } + + _buildCommand() { + if (this.command != null) { + return this.command; + } + } + + execute(callback) { + const db = this.db; + const options = Object.assign({}, this.options); + + // Did the user destroy the topology + if (db.serverConfig && db.serverConfig.isDestroyed()) { + return callback(new MongoError('topology was destroyed')); + } + + let command; + try { + command = this._buildCommand(); + } catch (e) { + return callback(e); + } + + // Get the db name we are executing against + const dbName = options.dbName || options.authdb || db.databaseName; + + // Convert the readPreference if its not a write + if (this.hasAspect(Aspect.WRITE_OPERATION)) { + if (options.writeConcern && (!options.session || !options.session.inTransaction())) { + command.writeConcern = options.writeConcern; + } + } + + // Debug information + if (db.s.logger.isDebug()) { + db.s.logger.debug( + `executing command ${JSON.stringify( + command + )} against ${dbName}.$cmd with options [${JSON.stringify( + debugOptions(debugFields, options) + )}]` + ); + } + + const namespace = + this.namespace != null ? this.namespace : new MongoDBNamespace(dbName, '$cmd'); + + // Execute command + db.s.topology.command(namespace, command, options, (err, result) => { + if (err) return handleCallback(callback, err); + if (options.full) return handleCallback(callback, null, result); + handleCallback(callback, null, result.result); + }); + } +} + +module.exports = CommandOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/command_v2.js b/scripts/2.5/node_modules/mongodb/lib/operations/command_v2.js new file mode 100644 index 00000000..8df703fd --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/operations/command_v2.js @@ -0,0 +1,109 @@ +'use strict'; + +const Aspect = require('./operation').Aspect; +const OperationBase = require('./operation').OperationBase; +const resolveReadPreference = require('../utils').resolveReadPreference; +const ReadConcern = require('../read_concern'); +const WriteConcern = require('../write_concern'); +const maxWireVersion = require('../core/utils').maxWireVersion; +const commandSupportsReadConcern = require('../core/sessions').commandSupportsReadConcern; +const MongoError = require('../error').MongoError; + +const SUPPORTS_WRITE_CONCERN_AND_COLLATION = 5; + +class CommandOperationV2 extends OperationBase { + constructor(parent, options, operationOptions) { + super(options); + + this.ns = parent.s.namespace.withCollection('$cmd'); + this.readPreference = resolveReadPreference(parent, this.options); + this.readConcern = resolveReadConcern(parent, this.options); + this.writeConcern = resolveWriteConcern(parent, this.options); + this.explain = false; + + if (operationOptions && typeof operationOptions.fullResponse === 'boolean') { + this.fullResponse = true; + } + + // TODO: A lot of our code depends on having the read preference in the options. This should + // go away, but also requires massive test rewrites. + this.options.readPreference = this.readPreference; + + // TODO(NODE-2056): make logger another "inheritable" property + if (parent.s.logger) { + this.logger = parent.s.logger; + } else if (parent.s.db && parent.s.db.logger) { + this.logger = parent.s.db.logger; + } + } + + executeCommand(server, cmd, callback) { + // TODO: consider making this a non-enumerable property + this.server = server; + + const options = this.options; + const serverWireVersion = maxWireVersion(server); + const inTransaction = this.session && this.session.inTransaction(); + + if (this.readConcern && commandSupportsReadConcern(cmd) && !inTransaction) { + Object.assign(cmd, { readConcern: this.readConcern }); + } + + if (options.collation && serverWireVersion < SUPPORTS_WRITE_CONCERN_AND_COLLATION) { + callback( + new MongoError( + `Server ${ + server.name + }, which reports wire version ${serverWireVersion}, does not support collation` + ) + ); + return; + } + + if (serverWireVersion >= SUPPORTS_WRITE_CONCERN_AND_COLLATION) { + if (this.writeConcern && this.hasAspect(Aspect.WRITE_OPERATION)) { + Object.assign(cmd, { writeConcern: this.writeConcern }); + } + + if (options.collation && typeof options.collation === 'object') { + Object.assign(cmd, { collation: options.collation }); + } + } + + if (typeof options.maxTimeMS === 'number') { + cmd.maxTimeMS = options.maxTimeMS; + } + + if (typeof options.comment === 'string') { + cmd.comment = options.comment; + } + + if (this.logger && this.logger.isDebug()) { + this.logger.debug(`executing command ${JSON.stringify(cmd)} against ${this.ns}`); + } + + server.command(this.ns.toString(), cmd, this.options, (err, result) => { + if (err) { + callback(err, null); + return; + } + + if (this.fullResponse) { + callback(null, result); + return; + } + + callback(null, result.result); + }); + } +} + +function resolveWriteConcern(parent, options) { + return WriteConcern.fromOptions(options) || parent.writeConcern; +} + +function resolveReadConcern(parent, options) { + return ReadConcern.fromOptions(options) || parent.readConcern; +} + +module.exports = CommandOperationV2; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/common_functions.js b/scripts/2.5/node_modules/mongodb/lib/operations/common_functions.js new file mode 100644 index 00000000..20c2bc9a --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/operations/common_functions.js @@ -0,0 +1,406 @@ +'use strict'; + +const applyRetryableWrites = require('../utils').applyRetryableWrites; +const applyWriteConcern = require('../utils').applyWriteConcern; +const decorateWithCollation = require('../utils').decorateWithCollation; +const decorateWithReadConcern = require('../utils').decorateWithReadConcern; +const executeCommand = require('./db_ops').executeCommand; +const formattedOrderClause = require('../utils').formattedOrderClause; +const handleCallback = require('../utils').handleCallback; +const MongoError = require('../core').MongoError; +const ReadPreference = require('../core').ReadPreference; +const toError = require('../utils').toError; +const CursorState = require('../core/cursor').CursorState; + +/** + * Build the count command. + * + * @method + * @param {collectionOrCursor} an instance of a collection or cursor + * @param {object} query The query for the count. + * @param {object} [options] Optional settings. See Collection.prototype.count and Cursor.prototype.count for a list of options. + */ +function buildCountCommand(collectionOrCursor, query, options) { + const skip = options.skip; + const limit = options.limit; + let hint = options.hint; + const maxTimeMS = options.maxTimeMS; + query = query || {}; + + // Final query + const cmd = { + count: options.collectionName, + query: query + }; + + if (collectionOrCursor.s.numberOfRetries) { + // collectionOrCursor is a cursor + if (collectionOrCursor.options.hint) { + hint = collectionOrCursor.options.hint; + } else if (collectionOrCursor.cmd.hint) { + hint = collectionOrCursor.cmd.hint; + } + decorateWithCollation(cmd, collectionOrCursor, collectionOrCursor.cmd); + } else { + decorateWithCollation(cmd, collectionOrCursor, options); + } + + // Add limit, skip and maxTimeMS if defined + if (typeof skip === 'number') cmd.skip = skip; + if (typeof limit === 'number') cmd.limit = limit; + if (typeof maxTimeMS === 'number') cmd.maxTimeMS = maxTimeMS; + if (hint) cmd.hint = hint; + + // Do we have a readConcern specified + decorateWithReadConcern(cmd, collectionOrCursor); + + return cmd; +} + +function deleteCallback(err, r, callback) { + if (callback == null) return; + if (err && callback) return callback(err); + if (r == null) return callback(null, { result: { ok: 1 } }); + r.deletedCount = r.result.n; + if (callback) callback(null, r); +} + +/** + * Find and update a document. + * + * @method + * @param {Collection} a Collection instance. + * @param {object} query Query object to locate the object to modify. + * @param {array} sort If multiple docs match, choose the first one in the specified sort order as the object to manipulate. + * @param {object} doc The fields/vals to be updated. + * @param {object} [options] Optional settings. See Collection.prototype.findAndModify for a list of options. + * @param {Collection~findAndModifyCallback} [callback] The command result callback + * @deprecated use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead + */ +function findAndModify(coll, query, sort, doc, options, callback) { + // Create findAndModify command object + const queryObject = { + findAndModify: coll.collectionName, + query: query + }; + + sort = formattedOrderClause(sort); + if (sort) { + queryObject.sort = sort; + } + + queryObject.new = options.new ? true : false; + queryObject.remove = options.remove ? true : false; + queryObject.upsert = options.upsert ? true : false; + + const projection = options.projection || options.fields; + + if (projection) { + queryObject.fields = projection; + } + + if (options.arrayFilters) { + queryObject.arrayFilters = options.arrayFilters; + delete options.arrayFilters; + } + + if (doc && !options.remove) { + queryObject.update = doc; + } + + if (options.maxTimeMS) queryObject.maxTimeMS = options.maxTimeMS; + + // Either use override on the function, or go back to default on either the collection + // level or db + options.serializeFunctions = options.serializeFunctions || coll.s.serializeFunctions; + + // No check on the documents + options.checkKeys = false; + + // Final options for retryable writes and write concern + let finalOptions = Object.assign({}, options); + finalOptions = applyRetryableWrites(finalOptions, coll.s.db); + finalOptions = applyWriteConcern(finalOptions, { db: coll.s.db, collection: coll }, options); + + // Decorate the findAndModify command with the write Concern + if (finalOptions.writeConcern) { + queryObject.writeConcern = finalOptions.writeConcern; + } + + // Have we specified bypassDocumentValidation + if (finalOptions.bypassDocumentValidation === true) { + queryObject.bypassDocumentValidation = finalOptions.bypassDocumentValidation; + } + + finalOptions.readPreference = ReadPreference.primary; + + // Have we specified collation + try { + decorateWithCollation(queryObject, coll, finalOptions); + } catch (err) { + return callback(err, null); + } + + // Execute the command + executeCommand(coll.s.db, queryObject, finalOptions, (err, result) => { + if (err) return handleCallback(callback, err, null); + + return handleCallback(callback, null, result); + }); +} + +/** + * Retrieves this collections index info. + * + * @method + * @param {Db} db The Db instance on which to retrieve the index info. + * @param {string} name The name of the collection. + * @param {object} [options] Optional settings. See Db.prototype.indexInformation for a list of options. + * @param {Db~resultCallback} [callback] The command result callback + */ +function indexInformation(db, name, options, callback) { + // If we specified full information + const full = options['full'] == null ? false : options['full']; + + // Did the user destroy the topology + if (db.serverConfig && db.serverConfig.isDestroyed()) + return callback(new MongoError('topology was destroyed')); + // Process all the results from the index command and collection + function processResults(indexes) { + // Contains all the information + let info = {}; + // Process all the indexes + for (let i = 0; i < indexes.length; i++) { + const index = indexes[i]; + // Let's unpack the object + info[index.name] = []; + for (let name in index.key) { + info[index.name].push([name, index.key[name]]); + } + } + + return info; + } + + // Get the list of indexes of the specified collection + db + .collection(name) + .listIndexes(options) + .toArray((err, indexes) => { + if (err) return callback(toError(err)); + if (!Array.isArray(indexes)) return handleCallback(callback, null, []); + if (full) return handleCallback(callback, null, indexes); + handleCallback(callback, null, processResults(indexes)); + }); +} + +function prepareDocs(coll, docs, options) { + const forceServerObjectId = + typeof options.forceServerObjectId === 'boolean' + ? options.forceServerObjectId + : coll.s.db.options.forceServerObjectId; + + // no need to modify the docs if server sets the ObjectId + if (forceServerObjectId === true) { + return docs; + } + + return docs.map(doc => { + if (forceServerObjectId !== true && doc._id == null) { + doc._id = coll.s.pkFactory.createPk(); + } + + return doc; + }); +} + +// Get the next available document from the cursor, returns null if no more documents are available. +function nextObject(cursor, callback) { + if (cursor.s.state === CursorState.CLOSED || (cursor.isDead && cursor.isDead())) { + return handleCallback( + callback, + MongoError.create({ message: 'Cursor is closed', driver: true }) + ); + } + + if (cursor.s.state === CursorState.INIT && cursor.cmd && cursor.cmd.sort) { + try { + cursor.cmd.sort = formattedOrderClause(cursor.cmd.sort); + } catch (err) { + return handleCallback(callback, err); + } + } + + // Get the next object + cursor._next((err, doc) => { + cursor.s.state = CursorState.OPEN; + if (err) return handleCallback(callback, err); + handleCallback(callback, null, doc); + }); +} + +function insertDocuments(coll, docs, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + // Ensure we are operating on an array op docs + docs = Array.isArray(docs) ? docs : [docs]; + + // Final options for retryable writes and write concern + let finalOptions = Object.assign({}, options); + finalOptions = applyRetryableWrites(finalOptions, coll.s.db); + finalOptions = applyWriteConcern(finalOptions, { db: coll.s.db, collection: coll }, options); + + // If keep going set unordered + if (finalOptions.keepGoing === true) finalOptions.ordered = false; + finalOptions.serializeFunctions = options.serializeFunctions || coll.s.serializeFunctions; + + docs = prepareDocs(coll, docs, options); + + // File inserts + coll.s.topology.insert(coll.s.namespace, docs, finalOptions, (err, result) => { + if (callback == null) return; + if (err) return handleCallback(callback, err); + if (result == null) return handleCallback(callback, null, null); + if (result.result.code) return handleCallback(callback, toError(result.result)); + if (result.result.writeErrors) + return handleCallback(callback, toError(result.result.writeErrors[0])); + // Add docs to the list + result.ops = docs; + // Return the results + handleCallback(callback, null, result); + }); +} + +function removeDocuments(coll, selector, options, callback) { + if (typeof options === 'function') { + (callback = options), (options = {}); + } else if (typeof selector === 'function') { + callback = selector; + options = {}; + selector = {}; + } + + // Create an empty options object if the provided one is null + options = options || {}; + + // Final options for retryable writes and write concern + let finalOptions = Object.assign({}, options); + finalOptions = applyRetryableWrites(finalOptions, coll.s.db); + finalOptions = applyWriteConcern(finalOptions, { db: coll.s.db, collection: coll }, options); + + // If selector is null set empty + if (selector == null) selector = {}; + + // Build the op + const op = { q: selector, limit: 0 }; + if (options.single) { + op.limit = 1; + } else if (finalOptions.retryWrites) { + finalOptions.retryWrites = false; + } + + // Have we specified collation + try { + decorateWithCollation(finalOptions, coll, options); + } catch (err) { + return callback(err, null); + } + + // Execute the remove + coll.s.topology.remove(coll.s.namespace, [op], finalOptions, (err, result) => { + if (callback == null) return; + if (err) return handleCallback(callback, err, null); + if (result == null) return handleCallback(callback, null, null); + if (result.result.code) return handleCallback(callback, toError(result.result)); + if (result.result.writeErrors) { + return handleCallback(callback, toError(result.result.writeErrors[0])); + } + + // Return the results + handleCallback(callback, null, result); + }); +} + +function updateDocuments(coll, selector, document, options, callback) { + if ('function' === typeof options) (callback = options), (options = null); + if (options == null) options = {}; + if (!('function' === typeof callback)) callback = null; + + // If we are not providing a selector or document throw + if (selector == null || typeof selector !== 'object') + return callback(toError('selector must be a valid JavaScript object')); + if (document == null || typeof document !== 'object') + return callback(toError('document must be a valid JavaScript object')); + + // Final options for retryable writes and write concern + let finalOptions = Object.assign({}, options); + finalOptions = applyRetryableWrites(finalOptions, coll.s.db); + finalOptions = applyWriteConcern(finalOptions, { db: coll.s.db, collection: coll }, options); + + // Do we return the actual result document + // Either use override on the function, or go back to default on either the collection + // level or db + finalOptions.serializeFunctions = options.serializeFunctions || coll.s.serializeFunctions; + + // Execute the operation + const op = { q: selector, u: document }; + op.upsert = options.upsert !== void 0 ? !!options.upsert : false; + op.multi = options.multi !== void 0 ? !!options.multi : false; + + if (finalOptions.arrayFilters) { + op.arrayFilters = finalOptions.arrayFilters; + delete finalOptions.arrayFilters; + } + + if (finalOptions.retryWrites && op.multi) { + finalOptions.retryWrites = false; + } + + // Have we specified collation + try { + decorateWithCollation(finalOptions, coll, options); + } catch (err) { + return callback(err, null); + } + + // Update options + coll.s.topology.update(coll.s.namespace, [op], finalOptions, (err, result) => { + if (callback == null) return; + if (err) return handleCallback(callback, err, null); + if (result == null) return handleCallback(callback, null, null); + if (result.result.code) return handleCallback(callback, toError(result.result)); + if (result.result.writeErrors) + return handleCallback(callback, toError(result.result.writeErrors[0])); + // Return the results + handleCallback(callback, null, result); + }); +} + +function updateCallback(err, r, callback) { + if (callback == null) return; + if (err) return callback(err); + if (r == null) return callback(null, { result: { ok: 1 } }); + r.modifiedCount = r.result.nModified != null ? r.result.nModified : r.result.n; + r.upsertedId = + Array.isArray(r.result.upserted) && r.result.upserted.length > 0 + ? r.result.upserted[0] // FIXME(major): should be `r.result.upserted[0]._id` + : null; + r.upsertedCount = + Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0; + r.matchedCount = + Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? 0 : r.result.n; + callback(null, r); +} + +module.exports = { + buildCountCommand, + deleteCallback, + findAndModify, + indexInformation, + nextObject, + prepareDocs, + insertDocuments, + removeDocuments, + updateDocuments, + updateCallback +}; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/connect.js b/scripts/2.5/node_modules/mongodb/lib/operations/connect.js new file mode 100644 index 00000000..e8f25187 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/operations/connect.js @@ -0,0 +1,709 @@ +'use strict'; + +const OperationBase = require('./operation').OperationBase; +const defineAspects = require('./operation').defineAspects; +const Aspect = require('./operation').Aspect; +const deprecate = require('util').deprecate; +const Logger = require('../core').Logger; +const MongoCredentials = require('../core').MongoCredentials; +const MongoError = require('../core').MongoError; +const Mongos = require('../topologies/mongos'); +const NativeTopology = require('../topologies/native_topology'); +const parse = require('../core').parseConnectionString; +const ReadConcern = require('../read_concern'); +const ReadPreference = require('../core').ReadPreference; +const ReplSet = require('../topologies/replset'); +const Server = require('../topologies/server'); +const ServerSessionPool = require('../core').Sessions.ServerSessionPool; + +let client; +function loadClient() { + if (!client) { + client = require('../mongo_client'); + } + return client; +} + +const legacyParse = deprecate( + require('../url_parser'), + 'current URL string parser is deprecated, and will be removed in a future version. ' + + 'To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.' +); + +const AUTH_MECHANISM_INTERNAL_MAP = { + DEFAULT: 'default', + 'MONGODB-CR': 'mongocr', + PLAIN: 'plain', + 'MONGODB-X509': 'x509', + 'SCRAM-SHA-1': 'scram-sha-1', + 'SCRAM-SHA-256': 'scram-sha-256' +}; + +const monitoringEvents = [ + 'timeout', + 'close', + 'serverOpening', + 'serverDescriptionChanged', + 'serverHeartbeatStarted', + 'serverHeartbeatSucceeded', + 'serverHeartbeatFailed', + 'serverClosed', + 'topologyOpening', + 'topologyClosed', + 'topologyDescriptionChanged', + 'commandStarted', + 'commandSucceeded', + 'commandFailed', + 'joined', + 'left', + 'ping', + 'ha', + 'all', + 'fullsetup', + 'open' +]; + +const VALID_AUTH_MECHANISMS = new Set([ + 'DEFAULT', + 'MONGODB-CR', + 'PLAIN', + 'MONGODB-X509', + 'SCRAM-SHA-1', + 'SCRAM-SHA-256', + 'GSSAPI' +]); + +const validOptionNames = [ + 'poolSize', + 'ssl', + 'sslValidate', + 'sslCA', + 'sslCert', + 'sslKey', + 'sslPass', + 'sslCRL', + 'autoReconnect', + 'noDelay', + 'keepAlive', + 'keepAliveInitialDelay', + 'connectTimeoutMS', + 'family', + 'socketTimeoutMS', + 'reconnectTries', + 'reconnectInterval', + 'ha', + 'haInterval', + 'replicaSet', + 'secondaryAcceptableLatencyMS', + 'acceptableLatencyMS', + 'connectWithNoPrimary', + 'authSource', + 'w', + 'wtimeout', + 'j', + 'forceServerObjectId', + 'serializeFunctions', + 'ignoreUndefined', + 'raw', + 'bufferMaxEntries', + 'readPreference', + 'pkFactory', + 'promiseLibrary', + 'readConcern', + 'maxStalenessSeconds', + 'loggerLevel', + 'logger', + 'promoteValues', + 'promoteBuffers', + 'promoteLongs', + 'domainsEnabled', + 'checkServerIdentity', + 'validateOptions', + 'appname', + 'auth', + 'user', + 'password', + 'authMechanism', + 'compression', + 'fsync', + 'readPreferenceTags', + 'numberOfRetries', + 'auto_reconnect', + 'minSize', + 'monitorCommands', + 'retryWrites', + 'retryReads', + 'useNewUrlParser', + 'useUnifiedTopology', + 'serverSelectionTimeoutMS', + 'useRecoveryToken', + 'autoEncryption' +]; + +const ignoreOptionNames = ['native_parser']; +const legacyOptionNames = ['server', 'replset', 'replSet', 'mongos', 'db']; + +// Validate options object +function validOptions(options) { + const _validOptions = validOptionNames.concat(legacyOptionNames); + + for (const name in options) { + if (ignoreOptionNames.indexOf(name) !== -1) { + continue; + } + + if (_validOptions.indexOf(name) === -1) { + if (options.validateOptions) { + return new MongoError(`option ${name} is not supported`); + } else { + console.warn(`the options [${name}] is not supported`); + } + } + + if (legacyOptionNames.indexOf(name) !== -1) { + console.warn( + `the server/replset/mongos/db options are deprecated, ` + + `all their options are supported at the top level of the options object [${validOptionNames}]` + ); + } + } +} + +const LEGACY_OPTIONS_MAP = validOptionNames.reduce((obj, name) => { + obj[name.toLowerCase()] = name; + return obj; +}, {}); + +class ConnectOperation extends OperationBase { + constructor(mongoClient) { + super(); + + this.mongoClient = mongoClient; + } + + execute(callback) { + const mongoClient = this.mongoClient; + const err = validOptions(mongoClient.s.options); + + // Did we have a validation error + if (err) return callback(err); + // Fallback to callback based connect + connect(mongoClient, mongoClient.s.url, mongoClient.s.options, err => { + if (err) return callback(err); + callback(null, mongoClient); + }); + } +} +defineAspects(ConnectOperation, [Aspect.SKIP_SESSION]); + +function addListeners(mongoClient, topology) { + topology.on('authenticated', createListener(mongoClient, 'authenticated')); + topology.on('error', createListener(mongoClient, 'error')); + topology.on('timeout', createListener(mongoClient, 'timeout')); + topology.on('close', createListener(mongoClient, 'close')); + topology.on('parseError', createListener(mongoClient, 'parseError')); + topology.once('open', createListener(mongoClient, 'open')); + topology.once('fullsetup', createListener(mongoClient, 'fullsetup')); + topology.once('all', createListener(mongoClient, 'all')); + topology.on('reconnect', createListener(mongoClient, 'reconnect')); +} + +function assignTopology(client, topology) { + client.topology = topology; + topology.s.sessionPool = + topology instanceof NativeTopology + ? new ServerSessionPool(topology) + : new ServerSessionPool(topology.s.coreTopology); +} + +// Clear out all events +function clearAllEvents(topology) { + monitoringEvents.forEach(event => topology.removeAllListeners(event)); +} + +// Collect all events in order from SDAM +function collectEvents(mongoClient, topology) { + let MongoClient = loadClient(); + const collectedEvents = []; + + if (mongoClient instanceof MongoClient) { + monitoringEvents.forEach(event => { + topology.on(event, (object1, object2) => { + if (event === 'open') { + collectedEvents.push({ event: event, object1: mongoClient }); + } else { + collectedEvents.push({ event: event, object1: object1, object2: object2 }); + } + }); + }); + } + + return collectedEvents; +} + +const emitDeprecationForNonUnifiedTopology = deprecate(() => {}, +'current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. ' + 'To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.'); + +function connect(mongoClient, url, options, callback) { + options = Object.assign({}, options); + + // If callback is null throw an exception + if (callback == null) { + throw new Error('no callback function provided'); + } + + let didRequestAuthentication = false; + const logger = Logger('MongoClient', options); + + // Did we pass in a Server/ReplSet/Mongos + if (url instanceof Server || url instanceof ReplSet || url instanceof Mongos) { + return connectWithUrl(mongoClient, url, options, connectCallback); + } + + const useNewUrlParser = options.useNewUrlParser !== false; + + const parseFn = useNewUrlParser ? parse : legacyParse; + const transform = useNewUrlParser ? transformUrlOptions : legacyTransformUrlOptions; + + parseFn(url, options, (err, _object) => { + // Do not attempt to connect if parsing error + if (err) return callback(err); + + // Flatten + const object = transform(_object); + + // Parse the string + const _finalOptions = createUnifiedOptions(object, options); + + // Check if we have connection and socket timeout set + if (_finalOptions.socketTimeoutMS == null) _finalOptions.socketTimeoutMS = 360000; + if (_finalOptions.connectTimeoutMS == null) _finalOptions.connectTimeoutMS = 30000; + if (_finalOptions.retryWrites == null) _finalOptions.retryWrites = true; + if (_finalOptions.useRecoveryToken == null) _finalOptions.useRecoveryToken = true; + if (_finalOptions.readPreference == null) _finalOptions.readPreference = 'primary'; + + if (_finalOptions.db_options && _finalOptions.db_options.auth) { + delete _finalOptions.db_options.auth; + } + + // Store the merged options object + mongoClient.s.options = _finalOptions; + + // Failure modes + if (object.servers.length === 0) { + return callback(new Error('connection string must contain at least one seed host')); + } + + if (_finalOptions.auth && !_finalOptions.credentials) { + try { + didRequestAuthentication = true; + _finalOptions.credentials = generateCredentials( + mongoClient, + _finalOptions.auth.user, + _finalOptions.auth.password, + _finalOptions + ); + } catch (err) { + return callback(err); + } + } + + if (_finalOptions.useUnifiedTopology) { + return createTopology(mongoClient, 'unified', _finalOptions, connectCallback); + } + + emitDeprecationForNonUnifiedTopology(); + + // Do we have a replicaset then skip discovery and go straight to connectivity + if (_finalOptions.replicaSet || _finalOptions.rs_name) { + return createTopology(mongoClient, 'replicaset', _finalOptions, connectCallback); + } else if (object.servers.length > 1) { + return createTopology(mongoClient, 'mongos', _finalOptions, connectCallback); + } else { + return createServer(mongoClient, _finalOptions, connectCallback); + } + }); + + function connectCallback(err, topology) { + const warningMessage = `seed list contains no mongos proxies, replicaset connections requires the parameter replicaSet to be supplied in the URI or options object, mongodb://server:port/db?replicaSet=name`; + if (err && err.message === 'no mongos proxies found in seed list') { + if (logger.isWarn()) { + logger.warn(warningMessage); + } + + // Return a more specific error message for MongoClient.connect + return callback(new MongoError(warningMessage)); + } + + if (didRequestAuthentication) { + mongoClient.emit('authenticated', null, true); + } + + // Return the error and db instance + callback(err, topology); + } +} + +function connectWithUrl(mongoClient, url, options, connectCallback) { + // Set the topology + assignTopology(mongoClient, url); + + // Add listeners + addListeners(mongoClient, url); + + // Propagate the events to the client + relayEvents(mongoClient, url); + + let finalOptions = Object.assign({}, options); + + // If we have a readPreference passed in by the db options, convert it from a string + if (typeof options.readPreference === 'string' || typeof options.read_preference === 'string') { + finalOptions.readPreference = new ReadPreference( + options.readPreference || options.read_preference + ); + } + + const isDoingAuth = finalOptions.user || finalOptions.password || finalOptions.authMechanism; + if (isDoingAuth && !finalOptions.credentials) { + try { + finalOptions.credentials = generateCredentials( + mongoClient, + finalOptions.user, + finalOptions.password, + finalOptions + ); + } catch (err) { + return connectCallback(err, url); + } + } + + return url.connect(finalOptions, connectCallback); +} + +function createListener(mongoClient, event) { + const eventSet = new Set(['all', 'fullsetup', 'open', 'reconnect']); + return (v1, v2) => { + if (eventSet.has(event)) { + return mongoClient.emit(event, mongoClient); + } + + mongoClient.emit(event, v1, v2); + }; +} + +function createServer(mongoClient, options, callback) { + // Pass in the promise library + options.promiseLibrary = mongoClient.s.promiseLibrary; + + // Set default options + const servers = translateOptions(options); + + const server = servers[0]; + + // Propagate the events to the client + const collectedEvents = collectEvents(mongoClient, server); + + // Connect to topology + server.connect(options, (err, topology) => { + if (err) { + server.close(true); + return callback(err); + } + // Clear out all the collected event listeners + clearAllEvents(server); + + // Relay all the events + relayEvents(mongoClient, server); + // Add listeners + addListeners(mongoClient, server); + // Check if we are really speaking to a mongos + const ismaster = topology.lastIsMaster(); + + // Set the topology + assignTopology(mongoClient, topology); + + // Do we actually have a mongos + if (ismaster && ismaster.msg === 'isdbgrid') { + // Destroy the current connection + topology.close(); + // Create mongos connection instead + return createTopology(mongoClient, 'mongos', options, callback); + } + + // Fire all the events + replayEvents(mongoClient, collectedEvents); + // Otherwise callback + callback(err, topology); + }); +} + +function createTopology(mongoClient, topologyType, options, callback) { + // Pass in the promise library + options.promiseLibrary = mongoClient.s.promiseLibrary; + + const translationOptions = {}; + if (topologyType === 'unified') translationOptions.createServers = false; + + // Set default options + const servers = translateOptions(options, translationOptions); + + // Create the topology + let topology; + if (topologyType === 'mongos') { + topology = new Mongos(servers, options); + } else if (topologyType === 'replicaset') { + topology = new ReplSet(servers, options); + } else if (topologyType === 'unified') { + topology = new NativeTopology(options.servers, options); + } + + // Add listeners + addListeners(mongoClient, topology); + + // Propagate the events to the client + relayEvents(mongoClient, topology); + + // Open the connection + assignTopology(mongoClient, topology); + topology.connect(options, err => { + if (err) { + topology.close(true); + return callback(err); + } + + if (options.autoEncryption == null) { + callback(null, topology); + return; + } + + // setup for client side encryption + let AutoEncrypter; + try { + require.resolve('mongodb-client-encryption'); + } catch (err) { + callback( + new MongoError( + 'Auto-encryption requested, but the module is not installed. Please add `mongodb-client-encryption` as a dependency of your project' + ) + ); + return; + } + try { + AutoEncrypter = require('mongodb-client-encryption')(require('../../index')).AutoEncrypter; + } catch (err) { + callback(err); + return; + } + + const mongoCryptOptions = Object.assign({}, options.autoEncryption); + topology.s.options.autoEncrypter = new AutoEncrypter(mongoClient, mongoCryptOptions); + topology.s.options.autoEncrypter.init(err => { + if (err) return callback(err, null); + callback(null, topology); + }); + }); +} + +function createUnifiedOptions(finalOptions, options) { + const childOptions = [ + 'mongos', + 'server', + 'db', + 'replset', + 'db_options', + 'server_options', + 'rs_options', + 'mongos_options' + ]; + const noMerge = ['readconcern', 'compression']; + + for (const name in options) { + if (noMerge.indexOf(name.toLowerCase()) !== -1) { + finalOptions[name] = options[name]; + } else if (childOptions.indexOf(name.toLowerCase()) !== -1) { + finalOptions = mergeOptions(finalOptions, options[name], false); + } else { + if ( + options[name] && + typeof options[name] === 'object' && + !Buffer.isBuffer(options[name]) && + !Array.isArray(options[name]) + ) { + finalOptions = mergeOptions(finalOptions, options[name], true); + } else { + finalOptions[name] = options[name]; + } + } + } + + return finalOptions; +} + +function generateCredentials(client, username, password, options) { + options = Object.assign({}, options); + + // the default db to authenticate against is 'self' + // if authententicate is called from a retry context, it may be another one, like admin + const source = options.authSource || options.authdb || options.dbName; + + // authMechanism + const authMechanismRaw = options.authMechanism || 'DEFAULT'; + const authMechanism = authMechanismRaw.toUpperCase(); + + if (!VALID_AUTH_MECHANISMS.has(authMechanism)) { + throw MongoError.create({ + message: `authentication mechanism ${authMechanismRaw} not supported', options.authMechanism`, + driver: true + }); + } + + if (authMechanism === 'GSSAPI') { + return new MongoCredentials({ + mechanism: process.platform === 'win32' ? 'sspi' : 'gssapi', + mechanismProperties: options, + source, + username, + password + }); + } + + return new MongoCredentials({ + mechanism: AUTH_MECHANISM_INTERNAL_MAP[authMechanism], + source, + username, + password + }); +} + +function legacyTransformUrlOptions(object) { + return mergeOptions(createUnifiedOptions({}, object), object, false); +} + +function mergeOptions(target, source, flatten) { + for (const name in source) { + if (source[name] && typeof source[name] === 'object' && flatten) { + target = mergeOptions(target, source[name], flatten); + } else { + target[name] = source[name]; + } + } + + return target; +} + +function relayEvents(mongoClient, topology) { + const serverOrCommandEvents = [ + 'serverOpening', + 'serverDescriptionChanged', + 'serverHeartbeatStarted', + 'serverHeartbeatSucceeded', + 'serverHeartbeatFailed', + 'serverClosed', + 'topologyOpening', + 'topologyClosed', + 'topologyDescriptionChanged', + 'commandStarted', + 'commandSucceeded', + 'commandFailed', + 'joined', + 'left', + 'ping', + 'ha' + ]; + + serverOrCommandEvents.forEach(event => { + topology.on(event, (object1, object2) => { + mongoClient.emit(event, object1, object2); + }); + }); +} + +// +// Replay any events due to single server connection switching to Mongos +// +function replayEvents(mongoClient, events) { + for (let i = 0; i < events.length; i++) { + mongoClient.emit(events[i].event, events[i].object1, events[i].object2); + } +} + +function transformUrlOptions(_object) { + let object = Object.assign({ servers: _object.hosts }, _object.options); + for (let name in object) { + const camelCaseName = LEGACY_OPTIONS_MAP[name]; + if (camelCaseName) { + object[camelCaseName] = object[name]; + } + } + + const hasUsername = _object.auth && _object.auth.username; + const hasAuthMechanism = _object.options && _object.options.authMechanism; + if (hasUsername || hasAuthMechanism) { + object.auth = Object.assign({}, _object.auth); + if (object.auth.db) { + object.authSource = object.authSource || object.auth.db; + } + + if (object.auth.username) { + object.auth.user = object.auth.username; + } + } + + if (_object.defaultDatabase) { + object.dbName = _object.defaultDatabase; + } + + if (object.maxPoolSize) { + object.poolSize = object.maxPoolSize; + } + + if (object.readConcernLevel) { + object.readConcern = new ReadConcern(object.readConcernLevel); + } + + if (object.wTimeoutMS) { + object.wtimeout = object.wTimeoutMS; + } + + if (_object.srvHost) { + object.srvHost = _object.srvHost; + } + + return object; +} + +function translateOptions(options, translationOptions) { + translationOptions = Object.assign({}, { createServers: true }, translationOptions); + + // If we have a readPreference passed in by the db options + if (typeof options.readPreference === 'string' || typeof options.read_preference === 'string') { + options.readPreference = new ReadPreference(options.readPreference || options.read_preference); + } + + // Do we have readPreference tags, add them + if (options.readPreference && (options.readPreferenceTags || options.read_preference_tags)) { + options.readPreference.tags = options.readPreferenceTags || options.read_preference_tags; + } + + // Do we have maxStalenessSeconds + if (options.maxStalenessSeconds) { + options.readPreference.maxStalenessSeconds = options.maxStalenessSeconds; + } + + // Set the socket and connection timeouts + if (options.socketTimeoutMS == null) options.socketTimeoutMS = 360000; + if (options.connectTimeoutMS == null) options.connectTimeoutMS = 30000; + + if (!translationOptions.createServers) { + return; + } + + // Create server instances + return options.servers.map(serverObj => { + return serverObj.domain_socket + ? new Server(serverObj.domain_socket, 27017, options) + : new Server(serverObj.host, serverObj.port, options); + }); +} + +module.exports = ConnectOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/count.js b/scripts/2.5/node_modules/mongodb/lib/operations/count.js new file mode 100644 index 00000000..5bf03f08 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/operations/count.js @@ -0,0 +1,72 @@ +'use strict'; + +const Aspect = require('./operation').Aspect; +const buildCountCommand = require('./common_functions').buildCountCommand; +const defineAspects = require('./operation').defineAspects; +const OperationBase = require('./operation').OperationBase; + +class CountOperation extends OperationBase { + constructor(cursor, applySkipLimit, options) { + super(options); + + this.cursor = cursor; + this.applySkipLimit = applySkipLimit; + } + + execute(callback) { + const cursor = this.cursor; + const applySkipLimit = this.applySkipLimit; + const options = this.options; + + if (applySkipLimit) { + if (typeof cursor.cursorSkip() === 'number') options.skip = cursor.cursorSkip(); + if (typeof cursor.cursorLimit() === 'number') options.limit = cursor.cursorLimit(); + } + + // Ensure we have the right read preference inheritance + if (options.readPreference) { + cursor.setReadPreference(options.readPreference); + } + + if ( + typeof options.maxTimeMS !== 'number' && + cursor.cmd && + typeof cursor.cmd.maxTimeMS === 'number' + ) { + options.maxTimeMS = cursor.cmd.maxTimeMS; + } + + let finalOptions = {}; + finalOptions.skip = options.skip; + finalOptions.limit = options.limit; + finalOptions.hint = options.hint; + finalOptions.maxTimeMS = options.maxTimeMS; + + // Command + finalOptions.collectionName = cursor.namespace.collection; + + let command; + try { + command = buildCountCommand(cursor, cursor.cmd.query, finalOptions); + } catch (err) { + return callback(err); + } + + // Set cursor server to the same as the topology + cursor.server = cursor.topology.s.coreTopology; + + // Execute the command + cursor.topology.command( + cursor.namespace.withCollection('$cmd'), + command, + cursor.options, + (err, result) => { + callback(err, result ? result.result.n : null); + } + ); + } +} + +defineAspects(CountOperation, Aspect.SKIP_SESSION); + +module.exports = CountOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/count_documents.js b/scripts/2.5/node_modules/mongodb/lib/operations/count_documents.js new file mode 100644 index 00000000..d043abfa --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/operations/count_documents.js @@ -0,0 +1,41 @@ +'use strict'; + +const AggregateOperation = require('./aggregate'); + +class CountDocumentsOperation extends AggregateOperation { + constructor(collection, query, options) { + const pipeline = [{ $match: query }]; + if (typeof options.skip === 'number') { + pipeline.push({ $skip: options.skip }); + } + + if (typeof options.limit === 'number') { + pipeline.push({ $limit: options.limit }); + } + + pipeline.push({ $group: { _id: 1, n: { $sum: 1 } } }); + + super(collection, pipeline, options); + } + + execute(server, callback) { + super.execute(server, (err, result) => { + if (err) { + callback(err, null); + return; + } + + // NOTE: We're avoiding creating a cursor here to reduce the callstack. + const response = result.result; + if (response.cursor == null || response.cursor.firstBatch == null) { + callback(null, 0); + return; + } + + const docs = response.cursor.firstBatch; + callback(null, docs.length ? docs[0].n : 0); + }); + } +} + +module.exports = CountDocumentsOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/create_collection.js b/scripts/2.5/node_modules/mongodb/lib/operations/create_collection.js new file mode 100644 index 00000000..35c3a6f0 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/operations/create_collection.js @@ -0,0 +1,118 @@ +'use strict'; + +const Aspect = require('./operation').Aspect; +const defineAspects = require('./operation').defineAspects; +const CommandOperation = require('./command'); +const applyWriteConcern = require('../utils').applyWriteConcern; +const handleCallback = require('../utils').handleCallback; +const loadCollection = require('../dynamic_loaders').loadCollection; +const MongoError = require('../core').MongoError; +const ReadPreference = require('../core').ReadPreference; + +// Filter out any write concern options +const illegalCommandFields = [ + 'w', + 'wtimeout', + 'j', + 'fsync', + 'autoIndexId', + 'strict', + 'serializeFunctions', + 'pkFactory', + 'raw', + 'readPreference', + 'session', + 'readConcern', + 'writeConcern' +]; + +class CreateCollectionOperation extends CommandOperation { + constructor(db, name, options) { + super(db, options); + + this.name = name; + } + + _buildCommand() { + const name = this.name; + const options = this.options; + + // Create collection command + const cmd = { create: name }; + // Add all optional parameters + for (let n in options) { + if ( + options[n] != null && + typeof options[n] !== 'function' && + illegalCommandFields.indexOf(n) === -1 + ) { + cmd[n] = options[n]; + } + } + + return cmd; + } + + execute(callback) { + const db = this.db; + const name = this.name; + const options = this.options; + + let Collection = loadCollection(); + + // Did the user destroy the topology + if (db.serverConfig && db.serverConfig.isDestroyed()) { + return callback(new MongoError('topology was destroyed')); + } + + let listCollectionOptions = Object.assign({}, options, { nameOnly: true }); + listCollectionOptions = applyWriteConcern(listCollectionOptions, { db }, listCollectionOptions); + + // Check if we have the name + db + .listCollections({ name }, listCollectionOptions) + .setReadPreference(ReadPreference.PRIMARY) + .toArray((err, collections) => { + if (err != null) return handleCallback(callback, err, null); + if (collections.length > 0 && listCollectionOptions.strict) { + return handleCallback( + callback, + MongoError.create({ + message: `Collection ${name} already exists. Currently in strict mode.`, + driver: true + }), + null + ); + } else if (collections.length > 0) { + try { + return handleCallback( + callback, + null, + new Collection(db, db.s.topology, db.databaseName, name, db.s.pkFactory, options) + ); + } catch (err) { + return handleCallback(callback, err); + } + } + + // Execute command + super.execute(err => { + if (err) return handleCallback(callback, err); + + try { + return handleCallback( + callback, + null, + new Collection(db, db.s.topology, db.databaseName, name, db.s.pkFactory, options) + ); + } catch (err) { + return handleCallback(callback, err); + } + }); + }); + } +} + +defineAspects(CreateCollectionOperation, Aspect.WRITE_OPERATION); + +module.exports = CreateCollectionOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/create_index.js b/scripts/2.5/node_modules/mongodb/lib/operations/create_index.js new file mode 100644 index 00000000..98bba71e --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/operations/create_index.js @@ -0,0 +1,92 @@ +'use strict'; + +const Aspect = require('./operation').Aspect; +const CommandOperation = require('./command'); +const defineAspects = require('./operation').defineAspects; +const handleCallback = require('../utils').handleCallback; +const MongoError = require('../core').MongoError; +const parseIndexOptions = require('../utils').parseIndexOptions; + +const keysToOmit = new Set([ + 'name', + 'key', + 'writeConcern', + 'w', + 'wtimeout', + 'j', + 'fsync', + 'readPreference', + 'session' +]); + +class CreateIndexOperation extends CommandOperation { + constructor(db, name, fieldOrSpec, options) { + super(db, options); + + // Build the index + const indexParameters = parseIndexOptions(fieldOrSpec); + // Generate the index name + const indexName = typeof options.name === 'string' ? options.name : indexParameters.name; + // Set up the index + const indexesObject = { name: indexName, key: indexParameters.fieldHash }; + + this.name = name; + this.fieldOrSpec = fieldOrSpec; + this.indexes = indexesObject; + } + + _buildCommand() { + const options = this.options; + const name = this.name; + const indexes = this.indexes; + + // merge all the options + for (let optionName in options) { + if (!keysToOmit.has(optionName)) { + indexes[optionName] = options[optionName]; + } + } + + // Create command, apply write concern to command + const cmd = { createIndexes: name, indexes: [indexes] }; + + return cmd; + } + + execute(callback) { + const db = this.db; + const options = this.options; + const indexes = this.indexes; + + // Get capabilities + const capabilities = db.s.topology.capabilities(); + + // Did the user pass in a collation, check if our write server supports it + if (options.collation && capabilities && !capabilities.commandsTakeCollation) { + // Create a new error + const error = new MongoError('server/primary/mongos does not support collation'); + error.code = 67; + // Return the error + return callback(error); + } + + // Ensure we have a callback + if (options.writeConcern && typeof callback !== 'function') { + throw MongoError.create({ + message: 'Cannot use a writeConcern without a provided callback', + driver: true + }); + } + + // Attempt to run using createIndexes command + super.execute((err, result) => { + if (err == null) return handleCallback(callback, err, indexes.name); + + return handleCallback(callback, err, result); + }); + } +} + +defineAspects(CreateIndexOperation, Aspect.WRITE_OPERATION); + +module.exports = CreateIndexOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/create_indexes.js b/scripts/2.5/node_modules/mongodb/lib/operations/create_indexes.js new file mode 100644 index 00000000..46228e8c --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/operations/create_indexes.js @@ -0,0 +1,61 @@ +'use strict'; + +const Aspect = require('./operation').Aspect; +const defineAspects = require('./operation').defineAspects; +const OperationBase = require('./operation').OperationBase; +const executeCommand = require('./db_ops').executeCommand; +const MongoError = require('../core').MongoError; +const ReadPreference = require('../core').ReadPreference; + +class CreateIndexesOperation extends OperationBase { + constructor(collection, indexSpecs, options) { + super(options); + + this.collection = collection; + this.indexSpecs = indexSpecs; + } + + execute(callback) { + const coll = this.collection; + const indexSpecs = this.indexSpecs; + let options = this.options; + + const capabilities = coll.s.topology.capabilities(); + + // Ensure we generate the correct name if the parameter is not set + for (let i = 0; i < indexSpecs.length; i++) { + if (indexSpecs[i].name == null) { + const keys = []; + + // Did the user pass in a collation, check if our write server supports it + if (indexSpecs[i].collation && capabilities && !capabilities.commandsTakeCollation) { + return callback(new MongoError('server/primary/mongos does not support collation')); + } + + for (let name in indexSpecs[i].key) { + keys.push(`${name}_${indexSpecs[i].key[name]}`); + } + + // Set the name + indexSpecs[i].name = keys.join('_'); + } + } + + options = Object.assign({}, options, { readPreference: ReadPreference.PRIMARY }); + + // Execute the index + executeCommand( + coll.s.db, + { + createIndexes: coll.collectionName, + indexes: indexSpecs + }, + options, + callback + ); + } +} + +defineAspects(CreateIndexesOperation, Aspect.WRITE_OPERATION); + +module.exports = CreateIndexesOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/cursor_ops.js b/scripts/2.5/node_modules/mongodb/lib/operations/cursor_ops.js new file mode 100644 index 00000000..513624ff --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/operations/cursor_ops.js @@ -0,0 +1,239 @@ +'use strict'; + +const buildCountCommand = require('./collection_ops').buildCountCommand; +const formattedOrderClause = require('../utils').formattedOrderClause; +const handleCallback = require('../utils').handleCallback; +const MongoError = require('../core').MongoError; +const push = Array.prototype.push; +const CursorState = require('../core/cursor').CursorState; + +/** + * Get the count of documents for this cursor. + * + * @method + * @param {Cursor} cursor The Cursor instance on which to count. + * @param {boolean} [applySkipLimit=true] Specifies whether the count command apply limit and skip settings should be applied on the cursor or in the provided options. + * @param {object} [options] Optional settings. See Cursor.prototype.count for a list of options. + * @param {Cursor~countResultCallback} [callback] The result callback. + */ +function count(cursor, applySkipLimit, opts, callback) { + if (applySkipLimit) { + if (typeof cursor.cursorSkip() === 'number') opts.skip = cursor.cursorSkip(); + if (typeof cursor.cursorLimit() === 'number') opts.limit = cursor.cursorLimit(); + } + + // Ensure we have the right read preference inheritance + if (opts.readPreference) { + cursor.setReadPreference(opts.readPreference); + } + + if ( + typeof opts.maxTimeMS !== 'number' && + cursor.cmd && + typeof cursor.cmd.maxTimeMS === 'number' + ) { + opts.maxTimeMS = cursor.cmd.maxTimeMS; + } + + let options = {}; + options.skip = opts.skip; + options.limit = opts.limit; + options.hint = opts.hint; + options.maxTimeMS = opts.maxTimeMS; + + // Command + options.collectionName = cursor.namespace.collection; + + let command; + try { + command = buildCountCommand(cursor, cursor.cmd.query, options); + } catch (err) { + return callback(err); + } + + // Set cursor server to the same as the topology + cursor.server = cursor.topology.s.coreTopology; + + // Execute the command + cursor.topology.command( + cursor.namespace.withCollection('$cmd'), + command, + cursor.options, + (err, result) => { + callback(err, result ? result.result.n : null); + } + ); +} + +/** + * Iterates over all the documents for this cursor. See Cursor.prototype.each for more information. + * + * @method + * @deprecated + * @param {Cursor} cursor The Cursor instance on which to run. + * @param {Cursor~resultCallback} callback The result callback. + */ +function each(cursor, callback) { + if (!callback) throw MongoError.create({ message: 'callback is mandatory', driver: true }); + if (cursor.isNotified()) return; + if (cursor.s.state === CursorState.CLOSED || cursor.isDead()) { + return handleCallback( + callback, + MongoError.create({ message: 'Cursor is closed', driver: true }) + ); + } + + if (cursor.s.state === CursorState.INIT) { + cursor.s.state = CursorState.OPEN; + } + + // Define function to avoid global scope escape + let fn = null; + // Trampoline all the entries + if (cursor.bufferedCount() > 0) { + while ((fn = loop(cursor, callback))) fn(cursor, callback); + each(cursor, callback); + } else { + cursor.next((err, item) => { + if (err) return handleCallback(callback, err); + if (item == null) { + return cursor.close({ skipKillCursors: true }, () => handleCallback(callback, null, null)); + } + + if (handleCallback(callback, null, item) === false) return; + each(cursor, callback); + }); + } +} + +/** + * Check if there is any document still available in the cursor. + * + * @method + * @param {Cursor} cursor The Cursor instance on which to run. + * @param {Cursor~resultCallback} [callback] The result callback. + */ +function hasNext(cursor, callback) { + if (cursor.s.currentDoc) { + return callback(null, true); + } + + if (cursor.isNotified()) { + return callback(null, false); + } + + nextObject(cursor, (err, doc) => { + if (err) return callback(err, null); + if (cursor.s.state === CursorState.CLOSED || cursor.isDead()) { + return callback(null, false); + } + + if (!doc) return callback(null, false); + cursor.s.currentDoc = doc; + callback(null, true); + }); +} + +// Trampoline emptying the number of retrieved items +// without incurring a nextTick operation +function loop(cursor, callback) { + // No more items we are done + if (cursor.bufferedCount() === 0) return; + // Get the next document + cursor._next(callback); + // Loop + return loop; +} + +/** + * Get the next available document from the cursor. Returns null if no more documents are available. + * + * @method + * @param {Cursor} cursor The Cursor instance from which to get the next document. + * @param {Cursor~resultCallback} [callback] The result callback. + */ +function next(cursor, callback) { + // Return the currentDoc if someone called hasNext first + if (cursor.s.currentDoc) { + const doc = cursor.s.currentDoc; + cursor.s.currentDoc = null; + return callback(null, doc); + } + + // Return the next object + nextObject(cursor, callback); +} + +// Get the next available document from the cursor, returns null if no more documents are available. +function nextObject(cursor, callback) { + if (cursor.s.state === CursorState.CLOSED || (cursor.isDead && cursor.isDead())) + return handleCallback( + callback, + MongoError.create({ message: 'Cursor is closed', driver: true }) + ); + if (cursor.s.state === CursorState.INIT && cursor.cmd.sort) { + try { + cursor.cmd.sort = formattedOrderClause(cursor.cmd.sort); + } catch (err) { + return handleCallback(callback, err); + } + } + + // Get the next object + cursor._next((err, doc) => { + cursor.s.state = CursorState.OPEN; + if (err) return handleCallback(callback, err); + handleCallback(callback, null, doc); + }); +} + +/** + * Returns an array of documents. See Cursor.prototype.toArray for more information. + * + * @method + * @param {Cursor} cursor The Cursor instance from which to get the next document. + * @param {Cursor~toArrayResultCallback} [callback] The result callback. + */ +function toArray(cursor, callback) { + const items = []; + + // Reset cursor + cursor.rewind(); + cursor.s.state = CursorState.INIT; + + // Fetch all the documents + const fetchDocs = () => { + cursor._next((err, doc) => { + if (err) { + return cursor._endSession + ? cursor._endSession(() => handleCallback(callback, err)) + : handleCallback(callback, err); + } + if (doc == null) { + return cursor.close({ skipKillCursors: true }, () => handleCallback(callback, null, items)); + } + + // Add doc to items + items.push(doc); + + // Get all buffered objects + if (cursor.bufferedCount() > 0) { + let docs = cursor.readBufferedDocuments(cursor.bufferedCount()); + + // Transform the doc if transform method added + if (cursor.s.transforms && typeof cursor.s.transforms.doc === 'function') { + docs = docs.map(cursor.s.transforms.doc); + } + + push.apply(items, docs); + } + + // Attempt a fetch + fetchDocs(); + }); + }; + + fetchDocs(); +} + +module.exports = { count, each, hasNext, next, toArray }; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/db_ops.js b/scripts/2.5/node_modules/mongodb/lib/operations/db_ops.js new file mode 100644 index 00000000..08037620 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/operations/db_ops.js @@ -0,0 +1,831 @@ +'use strict'; + +const applyWriteConcern = require('../utils').applyWriteConcern; +const Code = require('../core').BSON.Code; +const resolveReadPreference = require('../utils').resolveReadPreference; +const crypto = require('crypto'); +const debugOptions = require('../utils').debugOptions; +const handleCallback = require('../utils').handleCallback; +const MongoError = require('../core').MongoError; +const parseIndexOptions = require('../utils').parseIndexOptions; +const ReadPreference = require('../core').ReadPreference; +const toError = require('../utils').toError; +const CONSTANTS = require('../constants'); +const MongoDBNamespace = require('../utils').MongoDBNamespace; + +const count = require('./collection_ops').count; +const findOne = require('./collection_ops').findOne; +const remove = require('./collection_ops').remove; +const updateOne = require('./collection_ops').updateOne; + +let collection; +function loadCollection() { + if (!collection) { + collection = require('../collection'); + } + return collection; +} +let db; +function loadDb() { + if (!db) { + db = require('../db'); + } + return db; +} + +const debugFields = [ + 'authSource', + 'w', + 'wtimeout', + 'j', + 'native_parser', + 'forceServerObjectId', + 'serializeFunctions', + 'raw', + 'promoteLongs', + 'promoteValues', + 'promoteBuffers', + 'bufferMaxEntries', + 'numberOfRetries', + 'retryMiliSeconds', + 'readPreference', + 'pkFactory', + 'parentDb', + 'promiseLibrary', + 'noListener' +]; + +/** + * Add a user to the database. + * @method + * @param {Db} db The Db instance on which to add a user. + * @param {string} username The username. + * @param {string} password The password. + * @param {object} [options] Optional settings. See Db.prototype.addUser for a list of options. + * @param {Db~resultCallback} [callback] The command result callback + */ +function addUser(db, username, password, options, callback) { + let Db = loadDb(); + + // Did the user destroy the topology + if (db.serverConfig && db.serverConfig.isDestroyed()) + return callback(new MongoError('topology was destroyed')); + // Attempt to execute auth command + executeAuthCreateUserCommand(db, username, password, options, (err, r) => { + // We need to perform the backward compatible insert operation + if (err && err.code === -5000) { + const finalOptions = applyWriteConcern(Object.assign({}, options), { db }, options); + + // Use node md5 generator + const md5 = crypto.createHash('md5'); + // Generate keys used for authentication + md5.update(username + ':mongo:' + password); + const userPassword = md5.digest('hex'); + + // If we have another db set + const dbToUse = options.dbName ? new Db(options.dbName, db.s.topology, db.s.options) : db; + + // Fetch a user collection + const collection = dbToUse.collection(CONSTANTS.SYSTEM_USER_COLLECTION); + + // Check if we are inserting the first user + count(collection, {}, finalOptions, (err, count) => { + // We got an error (f.ex not authorized) + if (err != null) return handleCallback(callback, err, null); + // Check if the user exists and update i + const findOptions = Object.assign({ projection: { dbName: 1 } }, finalOptions); + collection.find({ user: username }, findOptions).toArray(err => { + // We got an error (f.ex not authorized) + if (err != null) return handleCallback(callback, err, null); + // Add command keys + finalOptions.upsert = true; + + // We have a user, let's update the password or upsert if not + updateOne( + collection, + { user: username }, + { $set: { user: username, pwd: userPassword } }, + finalOptions, + err => { + if (count === 0 && err) + return handleCallback(callback, null, [{ user: username, pwd: userPassword }]); + if (err) return handleCallback(callback, err, null); + handleCallback(callback, null, [{ user: username, pwd: userPassword }]); + } + ); + }); + }); + + return; + } + + if (err) return handleCallback(callback, err); + handleCallback(callback, err, r); + }); +} + +/** + * Fetch all collections for the current db. + * + * @method + * @param {Db} db The Db instance on which to fetch collections. + * @param {object} [options] Optional settings. See Db.prototype.collections for a list of options. + * @param {Db~collectionsResultCallback} [callback] The results callback + */ +function collections(db, options, callback) { + let Collection = loadCollection(); + + options = Object.assign({}, options, { nameOnly: true }); + // Let's get the collection names + db.listCollections({}, options).toArray((err, documents) => { + if (err != null) return handleCallback(callback, err, null); + // Filter collections removing any illegal ones + documents = documents.filter(doc => { + return doc.name.indexOf('$') === -1; + }); + + // Return the collection objects + handleCallback( + callback, + null, + documents.map(d => { + return new Collection( + db, + db.s.topology, + db.databaseName, + d.name, + db.s.pkFactory, + db.s.options + ); + }) + ); + }); +} + +/** + * Creates an index on the db and collection. + * @method + * @param {Db} db The Db instance on which to create an index. + * @param {string} name Name of the collection to create the index on. + * @param {(string|object)} fieldOrSpec Defines the index. + * @param {object} [options] Optional settings. See Db.prototype.createIndex for a list of options. + * @param {Db~resultCallback} [callback] The command result callback + */ +function createIndex(db, name, fieldOrSpec, options, callback) { + // Get the write concern options + let finalOptions = Object.assign({}, { readPreference: ReadPreference.PRIMARY }, options); + finalOptions = applyWriteConcern(finalOptions, { db }, options); + + // Ensure we have a callback + if (finalOptions.writeConcern && typeof callback !== 'function') { + throw MongoError.create({ + message: 'Cannot use a writeConcern without a provided callback', + driver: true + }); + } + + // Did the user destroy the topology + if (db.serverConfig && db.serverConfig.isDestroyed()) + return callback(new MongoError('topology was destroyed')); + + // Attempt to run using createIndexes command + createIndexUsingCreateIndexes(db, name, fieldOrSpec, finalOptions, (err, result) => { + if (err == null) return handleCallback(callback, err, result); + + /** + * The following errors mean that the server recognized `createIndex` as a command so we don't need to fallback to an insert: + * 67 = 'CannotCreateIndex' (malformed index options) + * 85 = 'IndexOptionsConflict' (index already exists with different options) + * 86 = 'IndexKeySpecsConflict' (index already exists with the same name) + * 11000 = 'DuplicateKey' (couldn't build unique index because of dupes) + * 11600 = 'InterruptedAtShutdown' (interrupted at shutdown) + * 197 = 'InvalidIndexSpecificationOption' (`_id` with `background: true`) + */ + if ( + err.code === 67 || + err.code === 11000 || + err.code === 85 || + err.code === 86 || + err.code === 11600 || + err.code === 197 + ) { + return handleCallback(callback, err, result); + } + + // Create command + const doc = createCreateIndexCommand(db, name, fieldOrSpec, options); + // Set no key checking + finalOptions.checkKeys = false; + // Insert document + db.s.topology.insert( + db.s.namespace.withCollection(CONSTANTS.SYSTEM_INDEX_COLLECTION), + doc, + finalOptions, + (err, result) => { + if (callback == null) return; + if (err) return handleCallback(callback, err); + if (result == null) return handleCallback(callback, null, null); + if (result.result.writeErrors) + return handleCallback(callback, MongoError.create(result.result.writeErrors[0]), null); + handleCallback(callback, null, doc.name); + } + ); + }); +} + +// Add listeners to topology +function createListener(db, e, object) { + function listener(err) { + if (object.listeners(e).length > 0) { + object.emit(e, err, db); + + // Emit on all associated db's if available + for (let i = 0; i < db.s.children.length; i++) { + db.s.children[i].emit(e, err, db.s.children[i]); + } + } + } + return listener; +} + +/** + * Drop a collection from the database, removing it permanently. New accesses will create a new collection. + * + * @method + * @param {Db} db The Db instance on which to drop the collection. + * @param {string} name Name of collection to drop + * @param {Object} [options] Optional settings. See Db.prototype.dropCollection for a list of options. + * @param {Db~resultCallback} [callback] The results callback + */ +function dropCollection(db, name, options, callback) { + executeCommand(db, name, options, (err, result) => { + // Did the user destroy the topology + if (db.serverConfig && db.serverConfig.isDestroyed()) { + return callback(new MongoError('topology was destroyed')); + } + + if (err) return handleCallback(callback, err); + if (result.ok) return handleCallback(callback, null, true); + handleCallback(callback, null, false); + }); +} + +/** + * Drop a database, removing it permanently from the server. + * + * @method + * @param {Db} db The Db instance to drop. + * @param {Object} cmd The command document. + * @param {Object} [options] Optional settings. See Db.prototype.dropDatabase for a list of options. + * @param {Db~resultCallback} [callback] The results callback + */ +function dropDatabase(db, cmd, options, callback) { + executeCommand(db, cmd, options, (err, result) => { + // Did the user destroy the topology + if (db.serverConfig && db.serverConfig.isDestroyed()) { + return callback(new MongoError('topology was destroyed')); + } + + if (callback == null) return; + if (err) return handleCallback(callback, err, null); + handleCallback(callback, null, result.ok ? true : false); + }); +} + +/** + * Ensures that an index exists. If it does not, creates it. + * + * @method + * @param {Db} db The Db instance on which to ensure the index. + * @param {string} name The index name + * @param {(string|object)} fieldOrSpec Defines the index. + * @param {object} [options] Optional settings. See Db.prototype.ensureIndex for a list of options. + * @param {Db~resultCallback} [callback] The command result callback + */ +function ensureIndex(db, name, fieldOrSpec, options, callback) { + // Get the write concern options + const finalOptions = applyWriteConcern({}, { db }, options); + // Create command + const selector = createCreateIndexCommand(db, name, fieldOrSpec, options); + const index_name = selector.name; + + // Did the user destroy the topology + if (db.serverConfig && db.serverConfig.isDestroyed()) + return callback(new MongoError('topology was destroyed')); + + // Merge primary readPreference + finalOptions.readPreference = ReadPreference.PRIMARY; + + // Check if the index already exists + indexInformation(db, name, finalOptions, (err, indexInformation) => { + if (err != null && err.code !== 26) return handleCallback(callback, err, null); + // If the index does not exist, create it + if (indexInformation == null || !indexInformation[index_name]) { + createIndex(db, name, fieldOrSpec, options, callback); + } else { + if (typeof callback === 'function') return handleCallback(callback, null, index_name); + } + }); +} + +/** + * Evaluate JavaScript on the server + * + * @method + * @param {Db} db The Db instance. + * @param {Code} code JavaScript to execute on server. + * @param {(object|array)} parameters The parameters for the call. + * @param {object} [options] Optional settings. See Db.prototype.eval for a list of options. + * @param {Db~resultCallback} [callback] The results callback + * @deprecated Eval is deprecated on MongoDB 3.2 and forward + */ +function evaluate(db, code, parameters, options, callback) { + let finalCode = code; + let finalParameters = []; + + // Did the user destroy the topology + if (db.serverConfig && db.serverConfig.isDestroyed()) + return callback(new MongoError('topology was destroyed')); + + // If not a code object translate to one + if (!(finalCode && finalCode._bsontype === 'Code')) finalCode = new Code(finalCode); + // Ensure the parameters are correct + if (parameters != null && !Array.isArray(parameters) && typeof parameters !== 'function') { + finalParameters = [parameters]; + } else if (parameters != null && Array.isArray(parameters) && typeof parameters !== 'function') { + finalParameters = parameters; + } + + // Create execution selector + let cmd = { $eval: finalCode, args: finalParameters }; + // Check if the nolock parameter is passed in + if (options['nolock']) { + cmd['nolock'] = options['nolock']; + } + + // Set primary read preference + options.readPreference = new ReadPreference(ReadPreference.PRIMARY); + + // Execute the command + executeCommand(db, cmd, options, (err, result) => { + if (err) return handleCallback(callback, err, null); + if (result && result.ok === 1) return handleCallback(callback, null, result.retval); + if (result) + return handleCallback( + callback, + MongoError.create({ message: `eval failed: ${result.errmsg}`, driver: true }), + null + ); + handleCallback(callback, err, result); + }); +} + +/** + * Execute a command + * + * @method + * @param {Db} db The Db instance on which to execute the command. + * @param {object} command The command hash + * @param {object} [options] Optional settings. See Db.prototype.command for a list of options. + * @param {Db~resultCallback} [callback] The command result callback + */ +function executeCommand(db, command, options, callback) { + // Did the user destroy the topology + if (db.serverConfig && db.serverConfig.isDestroyed()) + return callback(new MongoError('topology was destroyed')); + // Get the db name we are executing against + const dbName = options.dbName || options.authdb || db.databaseName; + + // Convert the readPreference if its not a write + options.readPreference = resolveReadPreference(db, options); + + // Debug information + if (db.s.logger.isDebug()) + db.s.logger.debug( + `executing command ${JSON.stringify( + command + )} against ${dbName}.$cmd with options [${JSON.stringify( + debugOptions(debugFields, options) + )}]` + ); + + // Execute command + db.s.topology.command(db.s.namespace.withCollection('$cmd'), command, options, (err, result) => { + if (err) return handleCallback(callback, err); + if (options.full) return handleCallback(callback, null, result); + handleCallback(callback, null, result.result); + }); +} + +/** + * Runs a command on the database as admin. + * + * @method + * @param {Db} db The Db instance on which to execute the command. + * @param {object} command The command hash + * @param {object} [options] Optional settings. See Db.prototype.executeDbAdminCommand for a list of options. + * @param {Db~resultCallback} [callback] The command result callback + */ +function executeDbAdminCommand(db, command, options, callback) { + const namespace = new MongoDBNamespace('admin', '$cmd'); + + db.s.topology.command(namespace, command, options, (err, result) => { + // Did the user destroy the topology + if (db.serverConfig && db.serverConfig.isDestroyed()) { + return callback(new MongoError('topology was destroyed')); + } + + if (err) return handleCallback(callback, err); + handleCallback(callback, null, result.result); + }); +} + +/** + * Retrieves this collections index info. + * + * @method + * @param {Db} db The Db instance on which to retrieve the index info. + * @param {string} name The name of the collection. + * @param {object} [options] Optional settings. See Db.prototype.indexInformation for a list of options. + * @param {Db~resultCallback} [callback] The command result callback + */ +function indexInformation(db, name, options, callback) { + // If we specified full information + const full = options['full'] == null ? false : options['full']; + + // Did the user destroy the topology + if (db.serverConfig && db.serverConfig.isDestroyed()) + return callback(new MongoError('topology was destroyed')); + // Process all the results from the index command and collection + function processResults(indexes) { + // Contains all the information + let info = {}; + // Process all the indexes + for (let i = 0; i < indexes.length; i++) { + const index = indexes[i]; + // Let's unpack the object + info[index.name] = []; + for (let name in index.key) { + info[index.name].push([name, index.key[name]]); + } + } + + return info; + } + + // Get the list of indexes of the specified collection + db + .collection(name) + .listIndexes(options) + .toArray((err, indexes) => { + if (err) return callback(toError(err)); + if (!Array.isArray(indexes)) return handleCallback(callback, null, []); + if (full) return handleCallback(callback, null, indexes); + handleCallback(callback, null, processResults(indexes)); + }); +} + +/** + * Retrieve the current profiling information for MongoDB + * + * @method + * @param {Db} db The Db instance on which to retrieve the profiling info. + * @param {Object} [options] Optional settings. See Db.protoype.profilingInfo for a list of options. + * @param {Db~resultCallback} [callback] The command result callback. + * @deprecated Query the system.profile collection directly. + */ +function profilingInfo(db, options, callback) { + try { + db + .collection('system.profile') + .find({}, options) + .toArray(callback); + } catch (err) { + return callback(err, null); + } +} + +/** + * Remove a user from a database + * + * @method + * @param {Db} db The Db instance on which to remove the user. + * @param {string} username The username. + * @param {object} [options] Optional settings. See Db.prototype.removeUser for a list of options. + * @param {Db~resultCallback} [callback] The command result callback + */ +function removeUser(db, username, options, callback) { + let Db = loadDb(); + + // Attempt to execute command + executeAuthRemoveUserCommand(db, username, options, (err, result) => { + if (err && err.code === -5000) { + const finalOptions = applyWriteConcern(Object.assign({}, options), { db }, options); + // If we have another db set + const db = options.dbName ? new Db(options.dbName, db.s.topology, db.s.options) : db; + + // Fetch a user collection + const collection = db.collection(CONSTANTS.SYSTEM_USER_COLLECTION); + + // Locate the user + findOne(collection, { user: username }, finalOptions, (err, user) => { + if (user == null) return handleCallback(callback, err, false); + remove(collection, { user: username }, finalOptions, err => { + handleCallback(callback, err, true); + }); + }); + + return; + } + + if (err) return handleCallback(callback, err); + handleCallback(callback, err, result); + }); +} + +// Validate the database name +function validateDatabaseName(databaseName) { + if (typeof databaseName !== 'string') + throw MongoError.create({ message: 'database name must be a string', driver: true }); + if (databaseName.length === 0) + throw MongoError.create({ message: 'database name cannot be the empty string', driver: true }); + if (databaseName === '$external') return; + + const invalidChars = [' ', '.', '$', '/', '\\']; + for (let i = 0; i < invalidChars.length; i++) { + if (databaseName.indexOf(invalidChars[i]) !== -1) + throw MongoError.create({ + message: "database names cannot contain the character '" + invalidChars[i] + "'", + driver: true + }); + } +} + +/** + * Create the command object for Db.prototype.createIndex. + * + * @param {Db} db The Db instance on which to create the command. + * @param {string} name Name of the collection to create the index on. + * @param {(string|object)} fieldOrSpec Defines the index. + * @param {Object} [options] Optional settings. See Db.prototype.createIndex for a list of options. + * @return {Object} The insert command object. + */ +function createCreateIndexCommand(db, name, fieldOrSpec, options) { + const indexParameters = parseIndexOptions(fieldOrSpec); + const fieldHash = indexParameters.fieldHash; + + // Generate the index name + const indexName = typeof options.name === 'string' ? options.name : indexParameters.name; + const selector = { + ns: db.s.namespace.withCollection(name).toString(), + key: fieldHash, + name: indexName + }; + + // Ensure we have a correct finalUnique + const finalUnique = options == null || 'object' === typeof options ? false : options; + // Set up options + options = options == null || typeof options === 'boolean' ? {} : options; + + // Add all the options + const keysToOmit = Object.keys(selector); + for (let optionName in options) { + if (keysToOmit.indexOf(optionName) === -1) { + selector[optionName] = options[optionName]; + } + } + + if (selector['unique'] == null) selector['unique'] = finalUnique; + + // Remove any write concern operations + const removeKeys = ['w', 'wtimeout', 'j', 'fsync', 'readPreference', 'session']; + for (let i = 0; i < removeKeys.length; i++) { + delete selector[removeKeys[i]]; + } + + // Return the command creation selector + return selector; +} + +/** + * Create index using the createIndexes command. + * + * @param {Db} db The Db instance on which to execute the command. + * @param {string} name Name of the collection to create the index on. + * @param {(string|object)} fieldOrSpec Defines the index. + * @param {Object} [options] Optional settings. See Db.prototype.createIndex for a list of options. + * @param {Db~resultCallback} [callback] The command result callback. + */ +function createIndexUsingCreateIndexes(db, name, fieldOrSpec, options, callback) { + // Build the index + const indexParameters = parseIndexOptions(fieldOrSpec); + // Generate the index name + const indexName = typeof options.name === 'string' ? options.name : indexParameters.name; + // Set up the index + const indexes = [{ name: indexName, key: indexParameters.fieldHash }]; + // merge all the options + const keysToOmit = Object.keys(indexes[0]).concat([ + 'writeConcern', + 'w', + 'wtimeout', + 'j', + 'fsync', + 'readPreference', + 'session' + ]); + + for (let optionName in options) { + if (keysToOmit.indexOf(optionName) === -1) { + indexes[0][optionName] = options[optionName]; + } + } + + // Get capabilities + const capabilities = db.s.topology.capabilities(); + + // Did the user pass in a collation, check if our write server supports it + if (indexes[0].collation && capabilities && !capabilities.commandsTakeCollation) { + // Create a new error + const error = new MongoError('server/primary/mongos does not support collation'); + error.code = 67; + // Return the error + return callback(error); + } + + // Create command, apply write concern to command + const cmd = applyWriteConcern({ createIndexes: name, indexes }, { db }, options); + + // ReadPreference primary + options.readPreference = ReadPreference.PRIMARY; + + // Build the command + executeCommand(db, cmd, options, (err, result) => { + if (err) return handleCallback(callback, err, null); + if (result.ok === 0) return handleCallback(callback, toError(result), null); + // Return the indexName for backward compatibility + handleCallback(callback, null, indexName); + }); +} + +/** + * Run the createUser command. + * + * @param {Db} db The Db instance on which to execute the command. + * @param {string} username The username of the user to add. + * @param {string} password The password of the user to add. + * @param {object} [options] Optional settings. See Db.prototype.addUser for a list of options. + * @param {Db~resultCallback} [callback] The command result callback + */ +function executeAuthCreateUserCommand(db, username, password, options, callback) { + // Special case where there is no password ($external users) + if (typeof username === 'string' && password != null && typeof password === 'object') { + options = password; + password = null; + } + + // Unpack all options + if (typeof options === 'function') { + callback = options; + options = {}; + } + + // Error out if we digestPassword set + if (options.digestPassword != null) { + return callback( + toError( + "The digestPassword option is not supported via add_user. Please use db.command('createUser', ...) instead for this option." + ) + ); + } + + // Get additional values + const customData = options.customData != null ? options.customData : {}; + let roles = Array.isArray(options.roles) ? options.roles : []; + const maxTimeMS = typeof options.maxTimeMS === 'number' ? options.maxTimeMS : null; + + // If not roles defined print deprecated message + if (roles.length === 0) { + console.log('Creating a user without roles is deprecated in MongoDB >= 2.6'); + } + + // Get the error options + const commandOptions = { writeCommand: true }; + if (options['dbName']) commandOptions.dbName = options['dbName']; + + // Add maxTimeMS to options if set + if (maxTimeMS != null) commandOptions.maxTimeMS = maxTimeMS; + + // Check the db name and add roles if needed + if ( + (db.databaseName.toLowerCase() === 'admin' || options.dbName === 'admin') && + !Array.isArray(options.roles) + ) { + roles = ['root']; + } else if (!Array.isArray(options.roles)) { + roles = ['dbOwner']; + } + + const digestPassword = db.s.topology.lastIsMaster().maxWireVersion >= 7; + + // Build the command to execute + let command = { + createUser: username, + customData: customData, + roles: roles, + digestPassword + }; + + // Apply write concern to command + command = applyWriteConcern(command, { db }, options); + + let userPassword = password; + + if (!digestPassword) { + // Use node md5 generator + const md5 = crypto.createHash('md5'); + // Generate keys used for authentication + md5.update(username + ':mongo:' + password); + userPassword = md5.digest('hex'); + } + + // No password + if (typeof password === 'string') { + command.pwd = userPassword; + } + + // Force write using primary + commandOptions.readPreference = ReadPreference.primary; + + // Execute the command + executeCommand(db, command, commandOptions, (err, result) => { + if (err && err.ok === 0 && err.code === undefined) + return handleCallback(callback, { code: -5000 }, null); + if (err) return handleCallback(callback, err, null); + handleCallback( + callback, + !result.ok ? toError(result) : null, + result.ok ? [{ user: username, pwd: '' }] : null + ); + }); +} + +/** + * Run the dropUser command. + * + * @param {Db} db The Db instance on which to execute the command. + * @param {string} username The username of the user to remove. + * @param {object} [options] Optional settings. See Db.prototype.removeUser for a list of options. + * @param {Db~resultCallback} [callback] The command result callback + */ +function executeAuthRemoveUserCommand(db, username, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + // Did the user destroy the topology + if (db.serverConfig && db.serverConfig.isDestroyed()) + return callback(new MongoError('topology was destroyed')); + // Get the error options + const commandOptions = { writeCommand: true }; + if (options['dbName']) commandOptions.dbName = options['dbName']; + + // Get additional values + const maxTimeMS = typeof options.maxTimeMS === 'number' ? options.maxTimeMS : null; + + // Add maxTimeMS to options if set + if (maxTimeMS != null) commandOptions.maxTimeMS = maxTimeMS; + + // Build the command to execute + let command = { + dropUser: username + }; + + // Apply write concern to command + command = applyWriteConcern(command, { db }, options); + + // Force write using primary + commandOptions.readPreference = ReadPreference.primary; + + // Execute the command + executeCommand(db, command, commandOptions, (err, result) => { + if (err && !err.ok && err.code === undefined) return handleCallback(callback, { code: -5000 }); + if (err) return handleCallback(callback, err, null); + handleCallback(callback, null, result.ok ? true : false); + }); +} + +module.exports = { + addUser, + collections, + createListener, + createIndex, + dropCollection, + dropDatabase, + ensureIndex, + evaluate, + executeCommand, + executeDbAdminCommand, + indexInformation, + profilingInfo, + removeUser, + validateDatabaseName +}; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/delete_many.js b/scripts/2.5/node_modules/mongodb/lib/operations/delete_many.js new file mode 100644 index 00000000..d881f67d --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/operations/delete_many.js @@ -0,0 +1,25 @@ +'use strict'; + +const OperationBase = require('./operation').OperationBase; +const deleteCallback = require('./common_functions').deleteCallback; +const removeDocuments = require('./common_functions').removeDocuments; + +class DeleteManyOperation extends OperationBase { + constructor(collection, filter, options) { + super(options); + + this.collection = collection; + this.filter = filter; + } + + execute(callback) { + const coll = this.collection; + const filter = this.filter; + const options = this.options; + + options.single = false; + removeDocuments(coll, filter, options, (err, r) => deleteCallback(err, r, callback)); + } +} + +module.exports = DeleteManyOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/delete_one.js b/scripts/2.5/node_modules/mongodb/lib/operations/delete_one.js new file mode 100644 index 00000000..b05597fd --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/operations/delete_one.js @@ -0,0 +1,25 @@ +'use strict'; + +const OperationBase = require('./operation').OperationBase; +const deleteCallback = require('./common_functions').deleteCallback; +const removeDocuments = require('./common_functions').removeDocuments; + +class DeleteOneOperation extends OperationBase { + constructor(collection, filter, options) { + super(options); + + this.collection = collection; + this.filter = filter; + } + + execute(callback) { + const coll = this.collection; + const filter = this.filter; + const options = this.options; + + options.single = true; + removeDocuments(coll, filter, options, (err, r) => deleteCallback(err, r, callback)); + } +} + +module.exports = DeleteOneOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/distinct.js b/scripts/2.5/node_modules/mongodb/lib/operations/distinct.js new file mode 100644 index 00000000..dcf4f7e2 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/operations/distinct.js @@ -0,0 +1,85 @@ +'use strict'; + +const Aspect = require('./operation').Aspect; +const defineAspects = require('./operation').defineAspects; +const CommandOperationV2 = require('./command_v2'); +const decorateWithCollation = require('../utils').decorateWithCollation; +const decorateWithReadConcern = require('../utils').decorateWithReadConcern; + +/** + * Return a list of distinct values for the given key across a collection. + * + * @class + * @property {Collection} a Collection instance. + * @property {string} key Field of the document to find distinct values for. + * @property {object} query The query for filtering the set of documents to which we apply the distinct filter. + * @property {object} [options] Optional settings. See Collection.prototype.distinct for a list of options. + */ +class DistinctOperation extends CommandOperationV2 { + /** + * Construct a Distinct operation. + * + * @param {Collection} a Collection instance. + * @param {string} key Field of the document to find distinct values for. + * @param {object} query The query for filtering the set of documents to which we apply the distinct filter. + * @param {object} [options] Optional settings. See Collection.prototype.distinct for a list of options. + */ + constructor(collection, key, query, options) { + super(collection, options); + + this.collection = collection; + this.key = key; + this.query = query; + } + + /** + * Execute the operation. + * + * @param {Collection~resultCallback} [callback] The command result callback + */ + execute(server, callback) { + const coll = this.collection; + const key = this.key; + const query = this.query; + const options = this.options; + + // Distinct command + const cmd = { + distinct: coll.collectionName, + key: key, + query: query + }; + + // Add maxTimeMS if defined + if (typeof options.maxTimeMS === 'number') { + cmd.maxTimeMS = options.maxTimeMS; + } + + // Do we have a readConcern specified + decorateWithReadConcern(cmd, coll, options); + + // Have we specified collation + try { + decorateWithCollation(cmd, coll, options); + } catch (err) { + return callback(err, null); + } + + super.executeCommand(server, cmd, (err, result) => { + if (err) { + callback(err); + return; + } + + callback(null, this.options.full ? result : result.values); + }); + } +} + +defineAspects(DistinctOperation, [ + Aspect.READ_OPERATION, + Aspect.RETRYABLE, + Aspect.EXECUTE_WITH_SELECTION +]); + +module.exports = DistinctOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/drop.js b/scripts/2.5/node_modules/mongodb/lib/operations/drop.js new file mode 100644 index 00000000..be03716f --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/operations/drop.js @@ -0,0 +1,53 @@ +'use strict'; + +const Aspect = require('./operation').Aspect; +const CommandOperation = require('./command'); +const defineAspects = require('./operation').defineAspects; +const handleCallback = require('../utils').handleCallback; + +class DropOperation extends CommandOperation { + constructor(db, options) { + const finalOptions = Object.assign({}, options, db.s.options); + + if (options.session) { + finalOptions.session = options.session; + } + + super(db, finalOptions); + } + + execute(callback) { + super.execute((err, result) => { + if (err) return handleCallback(callback, err); + if (result.ok) return handleCallback(callback, null, true); + handleCallback(callback, null, false); + }); + } +} + +defineAspects(DropOperation, Aspect.WRITE_OPERATION); + +class DropCollectionOperation extends DropOperation { + constructor(db, name, options) { + super(db, options); + + this.name = name; + this.namespace = `${db.namespace}.${name}`; + } + + _buildCommand() { + return { drop: this.name }; + } +} + +class DropDatabaseOperation extends DropOperation { + _buildCommand() { + return { dropDatabase: 1 }; + } +} + +module.exports = { + DropOperation, + DropCollectionOperation, + DropDatabaseOperation +}; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/drop_index.js b/scripts/2.5/node_modules/mongodb/lib/operations/drop_index.js new file mode 100644 index 00000000..a6ca783d --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/operations/drop_index.js @@ -0,0 +1,42 @@ +'use strict'; + +const Aspect = require('./operation').Aspect; +const defineAspects = require('./operation').defineAspects; +const CommandOperation = require('./command'); +const applyWriteConcern = require('../utils').applyWriteConcern; +const handleCallback = require('../utils').handleCallback; + +class DropIndexOperation extends CommandOperation { + constructor(collection, indexName, options) { + super(collection.s.db, options, collection); + + this.collection = collection; + this.indexName = indexName; + } + + _buildCommand() { + const collection = this.collection; + const indexName = this.indexName; + const options = this.options; + + let cmd = { dropIndexes: collection.collectionName, index: indexName }; + + // Decorate command with writeConcern if supported + cmd = applyWriteConcern(cmd, { db: collection.s.db, collection }, options); + + return cmd; + } + + execute(callback) { + // Execute command + super.execute((err, result) => { + if (typeof callback !== 'function') return; + if (err) return handleCallback(callback, err, null); + handleCallback(callback, null, result); + }); + } +} + +defineAspects(DropIndexOperation, Aspect.WRITE_OPERATION); + +module.exports = DropIndexOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/drop_indexes.js b/scripts/2.5/node_modules/mongodb/lib/operations/drop_indexes.js new file mode 100644 index 00000000..ed404ee9 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/operations/drop_indexes.js @@ -0,0 +1,23 @@ +'use strict'; + +const Aspect = require('./operation').Aspect; +const defineAspects = require('./operation').defineAspects; +const DropIndexOperation = require('./drop_index'); +const handleCallback = require('../utils').handleCallback; + +class DropIndexesOperation extends DropIndexOperation { + constructor(collection, options) { + super(collection, '*', options); + } + + execute(callback) { + super.execute(err => { + if (err) return handleCallback(callback, err, false); + handleCallback(callback, null, true); + }); + } +} + +defineAspects(DropIndexesOperation, Aspect.WRITE_OPERATION); + +module.exports = DropIndexesOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/estimated_document_count.js b/scripts/2.5/node_modules/mongodb/lib/operations/estimated_document_count.js new file mode 100644 index 00000000..e2d65563 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/operations/estimated_document_count.js @@ -0,0 +1,58 @@ +'use strict'; + +const Aspect = require('./operation').Aspect; +const defineAspects = require('./operation').defineAspects; +const CommandOperationV2 = require('./command_v2'); + +class EstimatedDocumentCountOperation extends CommandOperationV2 { + constructor(collection, query, options) { + if (typeof options === 'undefined') { + options = query; + query = undefined; + } + + super(collection, options); + this.collectionName = collection.s.namespace.collection; + if (query) { + this.query = query; + } + } + + execute(server, callback) { + const options = this.options; + const cmd = { count: this.collectionName }; + + if (this.query) { + cmd.query = this.query; + } + + if (typeof options.skip === 'number') { + cmd.skip = options.skip; + } + + if (typeof options.limit === 'number') { + cmd.limit = options.limit; + } + + if (options.hint) { + cmd.hint = options.hint; + } + + super.executeCommand(server, cmd, (err, response) => { + if (err) { + callback(err); + return; + } + + callback(null, response.n); + }); + } +} + +defineAspects(EstimatedDocumentCountOperation, [ + Aspect.READ_OPERATION, + Aspect.RETRYABLE, + Aspect.EXECUTE_WITH_SELECTION +]); + +module.exports = EstimatedDocumentCountOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/execute_db_admin_command.js b/scripts/2.5/node_modules/mongodb/lib/operations/execute_db_admin_command.js new file mode 100644 index 00000000..d15fc8e6 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/operations/execute_db_admin_command.js @@ -0,0 +1,34 @@ +'use strict'; + +const OperationBase = require('./operation').OperationBase; +const handleCallback = require('../utils').handleCallback; +const MongoError = require('../core').MongoError; +const MongoDBNamespace = require('../utils').MongoDBNamespace; + +class ExecuteDbAdminCommandOperation extends OperationBase { + constructor(db, selector, options) { + super(options); + + this.db = db; + this.selector = selector; + } + + execute(callback) { + const db = this.db; + const selector = this.selector; + const options = this.options; + + const namespace = new MongoDBNamespace('admin', '$cmd'); + db.s.topology.command(namespace, selector, options, (err, result) => { + // Did the user destroy the topology + if (db.serverConfig && db.serverConfig.isDestroyed()) { + return callback(new MongoError('topology was destroyed')); + } + + if (err) return handleCallback(callback, err); + handleCallback(callback, null, result.result); + }); + } +} + +module.exports = ExecuteDbAdminCommandOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/execute_operation.js b/scripts/2.5/node_modules/mongodb/lib/operations/execute_operation.js new file mode 100644 index 00000000..e23a80c0 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/operations/execute_operation.js @@ -0,0 +1,198 @@ +'use strict'; + +const MongoError = require('../core/error').MongoError; +const Aspect = require('./operation').Aspect; +const OperationBase = require('./operation').OperationBase; +const ReadPreference = require('../core/topologies/read_preference'); +const isRetryableError = require('../core/error').isRetryableError; +const maxWireVersion = require('../core/utils').maxWireVersion; +const isUnifiedTopology = require('../core/utils').isUnifiedTopology; + +/** + * Executes the given operation with provided arguments. + * + * This method reduces large amounts of duplication in the entire codebase by providing + * a single point for determining whether callbacks or promises should be used. Additionally + * it allows for a single point of entry to provide features such as implicit sessions, which + * are required by the Driver Sessions specification in the event that a ClientSession is + * not provided + * + * @param {object} topology The topology to execute this operation on + * @param {Operation} operation The operation to execute + * @param {function} callback The command result callback + */ +function executeOperation(topology, operation, callback) { + if (topology == null) { + throw new TypeError('This method requires a valid topology instance'); + } + + if (!(operation instanceof OperationBase)) { + throw new TypeError('This method requires a valid operation instance'); + } + + if ( + isUnifiedTopology(topology) && + !operation.hasAspect(Aspect.SKIP_SESSION) && + topology.shouldCheckForSessionSupport() + ) { + return selectServerForSessionSupport(topology, operation, callback); + } + + const Promise = topology.s.promiseLibrary; + + // The driver sessions spec mandates that we implicitly create sessions for operations + // that are not explicitly provided with a session. + let session, owner; + if (!operation.hasAspect(Aspect.SKIP_SESSION) && topology.hasSessionSupport()) { + if (operation.session == null) { + owner = Symbol(); + session = topology.startSession({ owner }); + operation.session = session; + } else if (operation.session.hasEnded) { + throw new MongoError('Use of expired sessions is not permitted'); + } + } + + const makeExecuteCallback = (resolve, reject) => + function executeCallback(err, result) { + if (session && session.owner === owner) { + session.endSession(() => { + if (operation.session === session) { + operation.clearSession(); + } + if (err) return reject(err); + resolve(result); + }); + } else { + if (err) return reject(err); + resolve(result); + } + }; + + // Execute using callback + if (typeof callback === 'function') { + const handler = makeExecuteCallback( + result => callback(null, result), + err => callback(err, null) + ); + + try { + if (operation.hasAspect(Aspect.EXECUTE_WITH_SELECTION)) { + return executeWithServerSelection(topology, operation, handler); + } else { + return operation.execute(handler); + } + } catch (e) { + handler(e); + throw e; + } + } + + return new Promise(function(resolve, reject) { + const handler = makeExecuteCallback(resolve, reject); + + try { + if (operation.hasAspect(Aspect.EXECUTE_WITH_SELECTION)) { + return executeWithServerSelection(topology, operation, handler); + } else { + return operation.execute(handler); + } + } catch (e) { + handler(e); + } + }); +} + +function supportsRetryableReads(server) { + return maxWireVersion(server) >= 6; +} + +function executeWithServerSelection(topology, operation, callback) { + const readPreference = operation.readPreference || ReadPreference.primary; + const inTransaction = operation.session && operation.session.inTransaction(); + + if (inTransaction && !readPreference.equals(ReadPreference.primary)) { + callback( + new MongoError( + `Read preference in a transaction must be primary, not: ${readPreference.mode}` + ) + ); + + return; + } + + const serverSelectionOptions = { + readPreference, + session: operation.session + }; + + function callbackWithRetry(err, result) { + if (err == null) { + return callback(null, result); + } + + if (!isRetryableError(err)) { + return callback(err); + } + + // select a new server, and attempt to retry the operation + topology.selectServer(serverSelectionOptions, (err, server) => { + if (err || !supportsRetryableReads(server)) { + callback(err, null); + return; + } + + operation.execute(server, callback); + }); + } + + // select a server, and execute the operation against it + topology.selectServer(serverSelectionOptions, (err, server) => { + if (err) { + callback(err, null); + return; + } + + const shouldRetryReads = + topology.s.options.retryReads !== false && + (operation.session && !inTransaction) && + supportsRetryableReads(server) && + operation.canRetryRead; + + if (operation.hasAspect(Aspect.RETRYABLE) && shouldRetryReads) { + operation.execute(server, callbackWithRetry); + return; + } + + operation.execute(server, callback); + }); +} + +// TODO: This is only supported for unified topology, it should go away once +// we remove support for legacy topology types. +function selectServerForSessionSupport(topology, operation, callback) { + const Promise = topology.s.promiseLibrary; + + let result; + if (typeof callback !== 'function') { + result = new Promise((resolve, reject) => { + callback = (err, result) => { + if (err) return reject(err); + resolve(result); + }; + }); + } + + topology.selectServer(ReadPreference.primaryPreferred, err => { + if (err) { + callback(err); + return; + } + + executeOperation(topology, operation, callback); + }); + + return result; +} + +module.exports = executeOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/explain.js b/scripts/2.5/node_modules/mongodb/lib/operations/explain.js new file mode 100644 index 00000000..44f3b483 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/operations/explain.js @@ -0,0 +1,23 @@ +'use strict'; + +const Aspect = require('./operation').Aspect; +const CoreCursor = require('../core/cursor').CoreCursor; +const defineAspects = require('./operation').defineAspects; +const OperationBase = require('./operation').OperationBase; + +class ExplainOperation extends OperationBase { + constructor(cursor) { + super(); + + this.cursor = cursor; + } + + execute() { + const cursor = this.cursor; + return CoreCursor.prototype._next.apply(cursor, arguments); + } +} + +defineAspects(ExplainOperation, Aspect.SKIP_SESSION); + +module.exports = ExplainOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/find.js b/scripts/2.5/node_modules/mongodb/lib/operations/find.js new file mode 100644 index 00000000..6838213c --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/operations/find.js @@ -0,0 +1,35 @@ +'use strict'; + +const OperationBase = require('./operation').OperationBase; +const Aspect = require('./operation').Aspect; +const defineAspects = require('./operation').defineAspects; +const resolveReadPreference = require('../utils').resolveReadPreference; + +class FindOperation extends OperationBase { + constructor(collection, ns, command, options) { + super(options); + + this.ns = ns; + this.cmd = command; + this.readPreference = resolveReadPreference(collection, this.options); + } + + execute(server, callback) { + // copied from `CommandOperationV2`, to be subclassed in the future + this.server = server; + + const cursorState = this.cursorState || {}; + + // TOOD: use `MongoDBNamespace` through and through + server.query(this.ns.toString(), this.cmd, cursorState, this.options, callback); + } +} + +defineAspects(FindOperation, [ + Aspect.READ_OPERATION, + Aspect.RETRYABLE, + Aspect.EXECUTE_WITH_SELECTION, + Aspect.SKIP_SESSION +]); + +module.exports = FindOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/find_and_modify.js b/scripts/2.5/node_modules/mongodb/lib/operations/find_and_modify.js new file mode 100644 index 00000000..8965eb48 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/operations/find_and_modify.js @@ -0,0 +1,98 @@ +'use strict'; + +const OperationBase = require('./operation').OperationBase; +const applyRetryableWrites = require('../utils').applyRetryableWrites; +const applyWriteConcern = require('../utils').applyWriteConcern; +const decorateWithCollation = require('../utils').decorateWithCollation; +const executeCommand = require('./db_ops').executeCommand; +const formattedOrderClause = require('../utils').formattedOrderClause; +const handleCallback = require('../utils').handleCallback; +const ReadPreference = require('../core').ReadPreference; + +class FindAndModifyOperation extends OperationBase { + constructor(collection, query, sort, doc, options) { + super(options); + + this.collection = collection; + this.query = query; + this.sort = sort; + this.doc = doc; + } + + execute(callback) { + const coll = this.collection; + const query = this.query; + const sort = formattedOrderClause(this.sort); + const doc = this.doc; + let options = this.options; + + // Create findAndModify command object + const queryObject = { + findAndModify: coll.collectionName, + query: query + }; + + if (sort) { + queryObject.sort = sort; + } + + queryObject.new = options.new ? true : false; + queryObject.remove = options.remove ? true : false; + queryObject.upsert = options.upsert ? true : false; + + const projection = options.projection || options.fields; + + if (projection) { + queryObject.fields = projection; + } + + if (options.arrayFilters) { + queryObject.arrayFilters = options.arrayFilters; + } + + if (doc && !options.remove) { + queryObject.update = doc; + } + + if (options.maxTimeMS) queryObject.maxTimeMS = options.maxTimeMS; + + // Either use override on the function, or go back to default on either the collection + // level or db + options.serializeFunctions = options.serializeFunctions || coll.s.serializeFunctions; + + // No check on the documents + options.checkKeys = false; + + // Final options for retryable writes and write concern + options = applyRetryableWrites(options, coll.s.db); + options = applyWriteConcern(options, { db: coll.s.db, collection: coll }, options); + + // Decorate the findAndModify command with the write Concern + if (options.writeConcern) { + queryObject.writeConcern = options.writeConcern; + } + + // Have we specified bypassDocumentValidation + if (options.bypassDocumentValidation === true) { + queryObject.bypassDocumentValidation = options.bypassDocumentValidation; + } + + options.readPreference = ReadPreference.primary; + + // Have we specified collation + try { + decorateWithCollation(queryObject, coll, options); + } catch (err) { + return callback(err, null); + } + + // Execute the command + executeCommand(coll.s.db, queryObject, options, (err, result) => { + if (err) return handleCallback(callback, err, null); + + return handleCallback(callback, null, result); + }); + } +} + +module.exports = FindAndModifyOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/find_one.js b/scripts/2.5/node_modules/mongodb/lib/operations/find_one.js new file mode 100644 index 00000000..d3037a6d --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/operations/find_one.js @@ -0,0 +1,33 @@ +'use strict'; + +const handleCallback = require('../utils').handleCallback; +const OperationBase = require('./operation').OperationBase; +const toError = require('../utils').toError; + +class FindOneOperation extends OperationBase { + constructor(collection, query, options) { + super(options); + + this.collection = collection; + this.query = query; + } + + execute(callback) { + const coll = this.collection; + const query = this.query; + const options = this.options; + + const cursor = coll + .find(query, options) + .limit(-1) + .batchSize(1); + + // Return the item + cursor.next((err, item) => { + if (err != null) return handleCallback(callback, toError(err), null); + handleCallback(callback, null, item); + }); + } +} + +module.exports = FindOneOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/find_one_and_delete.js b/scripts/2.5/node_modules/mongodb/lib/operations/find_one_and_delete.js new file mode 100644 index 00000000..1c7527dd --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/operations/find_one_and_delete.js @@ -0,0 +1,16 @@ +'use strict'; + +const FindAndModifyOperation = require('./find_and_modify'); + +class FindOneAndDeleteOperation extends FindAndModifyOperation { + constructor(collection, filter, options) { + // Final options + const finalOptions = Object.assign({}, options); + finalOptions.fields = options.projection; + finalOptions.remove = true; + + super(collection, filter, finalOptions.sort, null, finalOptions); + } +} + +module.exports = FindOneAndDeleteOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/find_one_and_replace.js b/scripts/2.5/node_modules/mongodb/lib/operations/find_one_and_replace.js new file mode 100644 index 00000000..ae37df5d --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/operations/find_one_and_replace.js @@ -0,0 +1,18 @@ +'use strict'; + +const FindAndModifyOperation = require('./find_and_modify'); + +class FindOneAndReplaceOperation extends FindAndModifyOperation { + constructor(collection, filter, replacement, options) { + // Final options + const finalOptions = Object.assign({}, options); + finalOptions.fields = options.projection; + finalOptions.update = true; + finalOptions.new = options.returnOriginal !== void 0 ? !options.returnOriginal : false; + finalOptions.upsert = options.upsert !== void 0 ? !!options.upsert : false; + + super(collection, filter, finalOptions.sort, replacement, finalOptions); + } +} + +module.exports = FindOneAndReplaceOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/find_one_and_update.js b/scripts/2.5/node_modules/mongodb/lib/operations/find_one_and_update.js new file mode 100644 index 00000000..6a199652 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/operations/find_one_and_update.js @@ -0,0 +1,19 @@ +'use strict'; + +const FindAndModifyOperation = require('./find_and_modify'); + +class FindOneAndUpdateOperation extends FindAndModifyOperation { + constructor(collection, filter, update, options) { + // Final options + const finalOptions = Object.assign({}, options); + finalOptions.fields = options.projection; + finalOptions.update = true; + finalOptions.new = + typeof options.returnOriginal === 'boolean' ? !options.returnOriginal : false; + finalOptions.upsert = typeof options.upsert === 'boolean' ? options.upsert : false; + + super(collection, filter, finalOptions.sort, update, finalOptions); + } +} + +module.exports = FindOneAndUpdateOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/geo_haystack_search.js b/scripts/2.5/node_modules/mongodb/lib/operations/geo_haystack_search.js new file mode 100644 index 00000000..edd1fb17 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/operations/geo_haystack_search.js @@ -0,0 +1,79 @@ +'use strict'; + +const Aspect = require('./operation').Aspect; +const defineAspects = require('./operation').defineAspects; +const OperationBase = require('./operation').OperationBase; +const decorateCommand = require('../utils').decorateCommand; +const decorateWithReadConcern = require('../utils').decorateWithReadConcern; +const executeCommand = require('./db_ops').executeCommand; +const handleCallback = require('../utils').handleCallback; +const resolveReadPreference = require('../utils').resolveReadPreference; +const toError = require('../utils').toError; + +/** + * Execute a geo search using a geo haystack index on a collection. + * + * @class + * @property {Collection} a Collection instance. + * @property {number} x Point to search on the x axis, ensure the indexes are ordered in the same order. + * @property {number} y Point to search on the y axis, ensure the indexes are ordered in the same order. + * @property {object} [options] Optional settings. See Collection.prototype.geoHaystackSearch for a list of options. + */ +class GeoHaystackSearchOperation extends OperationBase { + /** + * Construct a GeoHaystackSearch operation. + * + * @param {Collection} a Collection instance. + * @param {number} x Point to search on the x axis, ensure the indexes are ordered in the same order. + * @param {number} y Point to search on the y axis, ensure the indexes are ordered in the same order. + * @param {object} [options] Optional settings. See Collection.prototype.geoHaystackSearch for a list of options. + */ + constructor(collection, x, y, options) { + super(options); + + this.collection = collection; + this.x = x; + this.y = y; + } + + /** + * Execute the operation. + * + * @param {Collection~resultCallback} [callback] The command result callback + */ + execute(callback) { + const coll = this.collection; + const x = this.x; + const y = this.y; + let options = this.options; + + // Build command object + let commandObject = { + geoSearch: coll.collectionName, + near: [x, y] + }; + + // Remove read preference from hash if it exists + commandObject = decorateCommand(commandObject, options, ['readPreference', 'session']); + + options = Object.assign({}, options); + // Ensure we have the right read preference inheritance + options.readPreference = resolveReadPreference(coll, options); + + // Do we have a readConcern specified + decorateWithReadConcern(commandObject, coll, options); + + // Execute the command + executeCommand(coll.s.db, commandObject, options, (err, res) => { + if (err) return handleCallback(callback, err); + if (res.err || res.errmsg) handleCallback(callback, toError(res)); + // should we only be returning res.results here? Not sure if the user + // should see the other return information + handleCallback(callback, null, res); + }); + } +} + +defineAspects(GeoHaystackSearchOperation, Aspect.READ_OPERATION); + +module.exports = GeoHaystackSearchOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/has_next.js b/scripts/2.5/node_modules/mongodb/lib/operations/has_next.js new file mode 100644 index 00000000..b2e4b861 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/operations/has_next.js @@ -0,0 +1,40 @@ +'use strict'; + +const Aspect = require('./operation').Aspect; +const defineAspects = require('./operation').defineAspects; +const loadCursor = require('../dynamic_loaders').loadCursor; +const OperationBase = require('./operation').OperationBase; +const nextObject = require('./common_functions').nextObject; + +class HasNextOperation extends OperationBase { + constructor(cursor) { + super(); + + this.cursor = cursor; + } + + execute(callback) { + const cursor = this.cursor; + let Cursor = loadCursor(); + + if (cursor.s.currentDoc) { + return callback(null, true); + } + + if (cursor.isNotified()) { + return callback(null, false); + } + + nextObject(cursor, (err, doc) => { + if (err) return callback(err, null); + if (cursor.s.state === Cursor.CLOSED || cursor.isDead()) return callback(null, false); + if (!doc) return callback(null, false); + cursor.s.currentDoc = doc; + callback(null, true); + }); + } +} + +defineAspects(HasNextOperation, Aspect.SKIP_SESSION); + +module.exports = HasNextOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/index_exists.js b/scripts/2.5/node_modules/mongodb/lib/operations/index_exists.js new file mode 100644 index 00000000..bd9dc0e9 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/operations/index_exists.js @@ -0,0 +1,39 @@ +'use strict'; + +const OperationBase = require('./operation').OperationBase; +const handleCallback = require('../utils').handleCallback; +const indexInformationDb = require('./db_ops').indexInformation; + +class IndexExistsOperation extends OperationBase { + constructor(collection, indexes, options) { + super(options); + + this.collection = collection; + this.indexes = indexes; + } + + execute(callback) { + const coll = this.collection; + const indexes = this.indexes; + const options = this.options; + + indexInformationDb(coll.s.db, coll.collectionName, options, (err, indexInformation) => { + // If we have an error return + if (err != null) return handleCallback(callback, err, null); + // Let's check for the index names + if (!Array.isArray(indexes)) + return handleCallback(callback, null, indexInformation[indexes] != null); + // Check in list of indexes + for (let i = 0; i < indexes.length; i++) { + if (indexInformation[indexes[i]] == null) { + return handleCallback(callback, null, false); + } + } + + // All keys found return true + return handleCallback(callback, null, true); + }); + } +} + +module.exports = IndexExistsOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/index_information.js b/scripts/2.5/node_modules/mongodb/lib/operations/index_information.js new file mode 100644 index 00000000..b18a603f --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/operations/index_information.js @@ -0,0 +1,23 @@ +'use strict'; + +const OperationBase = require('./operation').OperationBase; +const indexInformation = require('./common_functions').indexInformation; + +class IndexInformationOperation extends OperationBase { + constructor(db, name, options) { + super(options); + + this.db = db; + this.name = name; + } + + execute(callback) { + const db = this.db; + const name = this.name; + const options = this.options; + + indexInformation(db, name, options, callback); + } +} + +module.exports = IndexInformationOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/indexes.js b/scripts/2.5/node_modules/mongodb/lib/operations/indexes.js new file mode 100644 index 00000000..e29a88aa --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/operations/indexes.js @@ -0,0 +1,22 @@ +'use strict'; + +const OperationBase = require('./operation').OperationBase; +const indexInformation = require('./common_functions').indexInformation; + +class IndexesOperation extends OperationBase { + constructor(collection, options) { + super(options); + + this.collection = collection; + } + + execute(callback) { + const coll = this.collection; + let options = this.options; + + options = Object.assign({}, { full: true }, options); + indexInformation(coll.s.db, coll.collectionName, options, callback); + } +} + +module.exports = IndexesOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/insert_many.js b/scripts/2.5/node_modules/mongodb/lib/operations/insert_many.js new file mode 100644 index 00000000..460a535d --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/operations/insert_many.js @@ -0,0 +1,63 @@ +'use strict'; + +const OperationBase = require('./operation').OperationBase; +const BulkWriteOperation = require('./bulk_write'); +const MongoError = require('../core').MongoError; +const prepareDocs = require('./common_functions').prepareDocs; + +class InsertManyOperation extends OperationBase { + constructor(collection, docs, options) { + super(options); + + this.collection = collection; + this.docs = docs; + } + + execute(callback) { + const coll = this.collection; + let docs = this.docs; + const options = this.options; + + if (!Array.isArray(docs)) { + return callback( + MongoError.create({ message: 'docs parameter must be an array of documents', driver: true }) + ); + } + + // If keep going set unordered + options['serializeFunctions'] = options['serializeFunctions'] || coll.s.serializeFunctions; + + docs = prepareDocs(coll, docs, options); + + // Generate the bulk write operations + const operations = [ + { + insertMany: docs + } + ]; + + const bulkWriteOperation = new BulkWriteOperation(coll, operations, options); + + bulkWriteOperation.execute((err, result) => { + if (err) return callback(err, null); + callback(null, mapInsertManyResults(docs, result)); + }); + } +} + +function mapInsertManyResults(docs, r) { + const finalResult = { + result: { ok: 1, n: r.insertedCount }, + ops: docs, + insertedCount: r.insertedCount, + insertedIds: r.insertedIds + }; + + if (r.getLastOp()) { + finalResult.result.opTime = r.getLastOp(); + } + + return finalResult; +} + +module.exports = InsertManyOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/insert_one.js b/scripts/2.5/node_modules/mongodb/lib/operations/insert_one.js new file mode 100644 index 00000000..5e708801 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/operations/insert_one.js @@ -0,0 +1,39 @@ +'use strict'; + +const MongoError = require('../core').MongoError; +const OperationBase = require('./operation').OperationBase; +const insertDocuments = require('./common_functions').insertDocuments; + +class InsertOneOperation extends OperationBase { + constructor(collection, doc, options) { + super(options); + + this.collection = collection; + this.doc = doc; + } + + execute(callback) { + const coll = this.collection; + const doc = this.doc; + const options = this.options; + + if (Array.isArray(doc)) { + return callback( + MongoError.create({ message: 'doc parameter must be an object', driver: true }) + ); + } + + insertDocuments(coll, [doc], options, (err, r) => { + if (callback == null) return; + if (err && callback) return callback(err); + // Workaround for pre 2.6 servers + if (r == null) return callback(null, { result: { ok: 1 } }); + // Add values to top level to ensure crud spec compatibility + r.insertedCount = r.result.n; + r.insertedId = doc._id; + if (callback) callback(null, r); + }); + } +} + +module.exports = InsertOneOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/is_capped.js b/scripts/2.5/node_modules/mongodb/lib/operations/is_capped.js new file mode 100644 index 00000000..3bfd9ffa --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/operations/is_capped.js @@ -0,0 +1,19 @@ +'use strict'; + +const OptionsOperation = require('./options_operation'); +const handleCallback = require('../utils').handleCallback; + +class IsCappedOperation extends OptionsOperation { + constructor(collection, options) { + super(collection, options); + } + + execute(callback) { + super.execute((err, document) => { + if (err) return handleCallback(callback, err); + handleCallback(callback, null, !!(document && document.capped)); + }); + } +} + +module.exports = IsCappedOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/list_collections.js b/scripts/2.5/node_modules/mongodb/lib/operations/list_collections.js new file mode 100644 index 00000000..ee01d31e --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/operations/list_collections.js @@ -0,0 +1,106 @@ +'use strict'; + +const CommandOperationV2 = require('./command_v2'); +const Aspect = require('./operation').Aspect; +const defineAspects = require('./operation').defineAspects; +const maxWireVersion = require('../core/utils').maxWireVersion; +const CONSTANTS = require('../constants'); + +const LIST_COLLECTIONS_WIRE_VERSION = 3; + +function listCollectionsTransforms(databaseName) { + const matching = `${databaseName}.`; + + return { + doc: doc => { + const index = doc.name.indexOf(matching); + // Remove database name if available + if (doc.name && index === 0) { + doc.name = doc.name.substr(index + matching.length); + } + + return doc; + } + }; +} + +class ListCollectionsOperation extends CommandOperationV2 { + constructor(db, filter, options) { + super(db, options, { fullResponse: true }); + + this.db = db; + this.filter = filter; + this.nameOnly = !!this.options.nameOnly; + + if (typeof this.options.batchSize === 'number') { + this.batchSize = this.options.batchSize; + } + } + + execute(server, callback) { + if (maxWireVersion(server) < LIST_COLLECTIONS_WIRE_VERSION) { + let filter = this.filter; + const databaseName = this.db.s.namespace.db; + + // If we have legacy mode and have not provided a full db name filter it + if ( + typeof filter.name === 'string' && + !new RegExp('^' + databaseName + '\\.').test(filter.name) + ) { + filter = Object.assign({}, filter); + filter.name = this.db.s.namespace.withCollection(filter.name).toString(); + } + + // No filter, filter by current database + if (filter == null) { + filter.name = `/${databaseName}/`; + } + + // Rewrite the filter to use $and to filter out indexes + if (filter.name) { + filter = { $and: [{ name: filter.name }, { name: /^((?!\$).)*$/ }] }; + } else { + filter = { name: /^((?!\$).)*$/ }; + } + + const transforms = listCollectionsTransforms(databaseName); + server.query( + `${databaseName}.${CONSTANTS.SYSTEM_NAMESPACE_COLLECTION}`, + { query: filter }, + { batchSize: this.batchSize || 1000 }, + {}, + (err, result) => { + if ( + result && + result.message && + result.message.documents && + Array.isArray(result.message.documents) + ) { + result.message.documents = result.message.documents.map(transforms.doc); + } + + callback(err, result); + } + ); + + return; + } + + const command = { + listCollections: 1, + filter: this.filter, + cursor: this.batchSize ? { batchSize: this.batchSize } : {}, + nameOnly: this.nameOnly + }; + + return super.executeCommand(server, command, callback); + } +} + +defineAspects(ListCollectionsOperation, [ + Aspect.READ_OPERATION, + Aspect.RETRYABLE, + Aspect.EXECUTE_WITH_SELECTION +]); + +module.exports = ListCollectionsOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/list_databases.js b/scripts/2.5/node_modules/mongodb/lib/operations/list_databases.js new file mode 100644 index 00000000..62b2606f --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/operations/list_databases.js @@ -0,0 +1,38 @@ +'use strict'; + +const CommandOperationV2 = require('./command_v2'); +const Aspect = require('./operation').Aspect; +const defineAspects = require('./operation').defineAspects; +const MongoDBNamespace = require('../utils').MongoDBNamespace; + +class ListDatabasesOperation extends CommandOperationV2 { + constructor(db, options) { + super(db, options); + this.ns = new MongoDBNamespace('admin', '$cmd'); + } + + execute(server, callback) { + const cmd = { listDatabases: 1 }; + if (this.options.nameOnly) { + cmd.nameOnly = Number(cmd.nameOnly); + } + + if (this.options.filter) { + cmd.filter = this.options.filter; + } + + if (typeof this.options.authorizedDatabases === 'boolean') { + cmd.authorizedDatabases = this.options.authorizedDatabases; + } + + super.executeCommand(server, cmd, callback); + } +} + +defineAspects(ListDatabasesOperation, [ + Aspect.READ_OPERATION, + Aspect.RETRYABLE, + Aspect.EXECUTE_WITH_SELECTION +]); + +module.exports = ListDatabasesOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/list_indexes.js b/scripts/2.5/node_modules/mongodb/lib/operations/list_indexes.js new file mode 100644 index 00000000..302a31b7 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/operations/list_indexes.js @@ -0,0 +1,42 @@ +'use strict'; + +const CommandOperationV2 = require('./command_v2'); +const Aspect = require('./operation').Aspect; +const defineAspects = require('./operation').defineAspects; +const maxWireVersion = require('../core/utils').maxWireVersion; + +const LIST_INDEXES_WIRE_VERSION = 3; + +class ListIndexesOperation extends CommandOperationV2 { + constructor(collection, options) { + super(collection, options, { fullResponse: true }); + + this.collectionNamespace = collection.s.namespace; + } + + execute(server, callback) { + const serverWireVersion = maxWireVersion(server); + if (serverWireVersion < LIST_INDEXES_WIRE_VERSION) { + const systemIndexesNS = this.collectionNamespace.withCollection('system.indexes').toString(); + const collectionNS = this.collectionNamespace.toString(); + + server.query(systemIndexesNS, { query: { ns: collectionNS } }, {}, this.options, callback); + return; + } + + const cursor = this.options.batchSize ? { batchSize: this.options.batchSize } : {}; + super.executeCommand( + server, + { listIndexes: this.collectionNamespace.collection, cursor }, + callback + ); + } +} + +defineAspects(ListIndexesOperation, [ + Aspect.READ_OPERATION, + Aspect.RETRYABLE, + Aspect.EXECUTE_WITH_SELECTION +]); + +module.exports = ListIndexesOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/map_reduce.js b/scripts/2.5/node_modules/mongodb/lib/operations/map_reduce.js new file mode 100644 index 00000000..613f3f73 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/operations/map_reduce.js @@ -0,0 +1,189 @@ +'use strict'; + +const applyWriteConcern = require('../utils').applyWriteConcern; +const Code = require('../core').BSON.Code; +const decorateWithCollation = require('../utils').decorateWithCollation; +const decorateWithReadConcern = require('../utils').decorateWithReadConcern; +const executeCommand = require('./db_ops').executeCommand; +const handleCallback = require('../utils').handleCallback; +const isObject = require('../utils').isObject; +const loadDb = require('../dynamic_loaders').loadDb; +const OperationBase = require('./operation').OperationBase; +const resolveReadPreference = require('../utils').resolveReadPreference; +const toError = require('../utils').toError; + +const exclusionList = [ + 'readPreference', + 'session', + 'bypassDocumentValidation', + 'w', + 'wtimeout', + 'j', + 'writeConcern' +]; + +/** + * Run Map Reduce across a collection. Be aware that the inline option for out will return an array of results not a collection. + * + * @class + * @property {Collection} a Collection instance. + * @property {(function|string)} map The mapping function. + * @property {(function|string)} reduce The reduce function. + * @property {object} [options] Optional settings. See Collection.prototype.mapReduce for a list of options. + */ +class MapReduceOperation extends OperationBase { + /** + * Constructs a MapReduce operation. + * + * @param {Collection} a Collection instance. + * @param {(function|string)} map The mapping function. + * @param {(function|string)} reduce The reduce function. + * @param {object} [options] Optional settings. See Collection.prototype.mapReduce for a list of options. + */ + constructor(collection, map, reduce, options) { + super(options); + + this.collection = collection; + this.map = map; + this.reduce = reduce; + } + + /** + * Execute the operation. + * + * @param {Collection~resultCallback} [callback] The command result callback + */ + execute(callback) { + const coll = this.collection; + const map = this.map; + const reduce = this.reduce; + let options = this.options; + + const mapCommandHash = { + mapreduce: coll.collectionName, + map: map, + reduce: reduce + }; + + // Add any other options passed in + for (let n in options) { + if ('scope' === n) { + mapCommandHash[n] = processScope(options[n]); + } else { + // Only include if not in exclusion list + if (exclusionList.indexOf(n) === -1) { + mapCommandHash[n] = options[n]; + } + } + } + + options = Object.assign({}, options); + + // Ensure we have the right read preference inheritance + options.readPreference = resolveReadPreference(coll, options); + + // If we have a read preference and inline is not set as output fail hard + if ( + options.readPreference !== false && + options.readPreference !== 'primary' && + options['out'] && + (options['out'].inline !== 1 && options['out'] !== 'inline') + ) { + // Force readPreference to primary + options.readPreference = 'primary'; + // Decorate command with writeConcern if supported + applyWriteConcern(mapCommandHash, { db: coll.s.db, collection: coll }, options); + } else { + decorateWithReadConcern(mapCommandHash, coll, options); + } + + // Is bypassDocumentValidation specified + if (options.bypassDocumentValidation === true) { + mapCommandHash.bypassDocumentValidation = options.bypassDocumentValidation; + } + + // Have we specified collation + try { + decorateWithCollation(mapCommandHash, coll, options); + } catch (err) { + return callback(err, null); + } + + // Execute command + executeCommand(coll.s.db, mapCommandHash, options, (err, result) => { + if (err) return handleCallback(callback, err); + // Check if we have an error + if (1 !== result.ok || result.err || result.errmsg) { + return handleCallback(callback, toError(result)); + } + + // Create statistics value + const stats = {}; + if (result.timeMillis) stats['processtime'] = result.timeMillis; + if (result.counts) stats['counts'] = result.counts; + if (result.timing) stats['timing'] = result.timing; + + // invoked with inline? + if (result.results) { + // If we wish for no verbosity + if (options['verbose'] == null || !options['verbose']) { + return handleCallback(callback, null, result.results); + } + + return handleCallback(callback, null, { results: result.results, stats: stats }); + } + + // The returned collection + let collection = null; + + // If we have an object it's a different db + if (result.result != null && typeof result.result === 'object') { + const doc = result.result; + // Return a collection from another db + let Db = loadDb(); + collection = new Db(doc.db, coll.s.db.s.topology, coll.s.db.s.options).collection( + doc.collection + ); + } else { + // Create a collection object that wraps the result collection + collection = coll.s.db.collection(result.result); + } + + // If we wish for no verbosity + if (options['verbose'] == null || !options['verbose']) { + return handleCallback(callback, err, collection); + } + + // Return stats as third set of values + handleCallback(callback, err, { collection: collection, stats: stats }); + }); + } +} + +/** + * Functions that are passed as scope args must + * be converted to Code instances. + * @ignore + */ +function processScope(scope) { + if (!isObject(scope) || scope._bsontype === 'ObjectID') { + return scope; + } + + const keys = Object.keys(scope); + let key; + const new_scope = {}; + + for (let i = keys.length - 1; i >= 0; i--) { + key = keys[i]; + if ('function' === typeof scope[key]) { + new_scope[key] = new Code(String(scope[key])); + } else { + new_scope[key] = processScope(scope[key]); + } + } + + return new_scope; +} + +module.exports = MapReduceOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/next.js b/scripts/2.5/node_modules/mongodb/lib/operations/next.js new file mode 100644 index 00000000..72bc4eb9 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/operations/next.js @@ -0,0 +1,32 @@ +'use strict'; + +const Aspect = require('./operation').Aspect; +const defineAspects = require('./operation').defineAspects; +const OperationBase = require('./operation').OperationBase; +const nextObject = require('./common_functions').nextObject; + +class NextOperation extends OperationBase { + constructor(cursor) { + super(); + + this.cursor = cursor; + } + + execute(callback) { + const cursor = this.cursor; + + // Return the currentDoc if someone called hasNext first + if (cursor.s.currentDoc) { + const doc = cursor.s.currentDoc; + cursor.s.currentDoc = null; + return callback(null, doc); + } + + // Return the next object + nextObject(cursor, callback); + } +} + +defineAspects(NextOperation, Aspect.SKIP_SESSION); + +module.exports = NextOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/operation.js b/scripts/2.5/node_modules/mongodb/lib/operations/operation.js new file mode 100644 index 00000000..471627ad --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/operations/operation.js @@ -0,0 +1,67 @@ +'use strict'; + +const Aspect = { + READ_OPERATION: Symbol('READ_OPERATION'), + SKIP_SESSION: Symbol('SKIP_SESSION'), + WRITE_OPERATION: Symbol('WRITE_OPERATION'), + RETRYABLE: Symbol('RETRYABLE'), + EXECUTE_WITH_SELECTION: Symbol('EXECUTE_WITH_SELECTION') +}; + +/** + * This class acts as a parent class for any operation and is responsible for setting this.options, + * as well as setting and getting a session. + * Additionally, this class implements `hasAspect`, which determines whether an operation has + * a specific aspect, including `SKIP_SESSION` and other aspects to encode retryability + * and other functionality. + */ +class OperationBase { + constructor(options) { + this.options = Object.assign({}, options); + } + + hasAspect(aspect) { + if (this.constructor.aspects == null) { + return false; + } + return this.constructor.aspects.has(aspect); + } + + set session(session) { + Object.assign(this.options, { session }); + } + + get session() { + return this.options.session; + } + + clearSession() { + delete this.options.session; + } + + get canRetryRead() { + return true; + } + + execute() { + throw new TypeError('`execute` must be implemented for OperationBase subclasses'); + } +} + +function defineAspects(operation, aspects) { + if (!Array.isArray(aspects) && !(aspects instanceof Set)) { + aspects = [aspects]; + } + aspects = new Set(aspects); + Object.defineProperty(operation, 'aspects', { + value: aspects, + writable: false + }); + return aspects; +} + +module.exports = { + Aspect, + defineAspects, + OperationBase +}; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/options_operation.js b/scripts/2.5/node_modules/mongodb/lib/operations/options_operation.js new file mode 100644 index 00000000..9a739a51 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/operations/options_operation.js @@ -0,0 +1,32 @@ +'use strict'; + +const OperationBase = require('./operation').OperationBase; +const handleCallback = require('../utils').handleCallback; +const MongoError = require('../core').MongoError; + +class OptionsOperation extends OperationBase { + constructor(collection, options) { + super(options); + + this.collection = collection; + } + + execute(callback) { + const coll = this.collection; + const opts = this.options; + + coll.s.db.listCollections({ name: coll.collectionName }, opts).toArray((err, collections) => { + if (err) return handleCallback(callback, err); + if (collections.length === 0) { + return handleCallback( + callback, + MongoError.create({ message: `collection ${coll.namespace} not found`, driver: true }) + ); + } + + handleCallback(callback, err, collections[0].options || null); + }); + } +} + +module.exports = OptionsOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/profiling_level.js b/scripts/2.5/node_modules/mongodb/lib/operations/profiling_level.js new file mode 100644 index 00000000..3f7639b4 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/operations/profiling_level.js @@ -0,0 +1,31 @@ +'use strict'; + +const CommandOperation = require('./command'); + +class ProfilingLevelOperation extends CommandOperation { + constructor(db, command, options) { + super(db, options); + } + + _buildCommand() { + const command = { profile: -1 }; + + return command; + } + + execute(callback) { + super.execute((err, doc) => { + if (err == null && doc.ok === 1) { + const was = doc.was; + if (was === 0) return callback(null, 'off'); + if (was === 1) return callback(null, 'slow_only'); + if (was === 2) return callback(null, 'all'); + return callback(new Error('Error: illegal profiling level value ' + was), null); + } else { + err != null ? callback(err, null) : callback(new Error('Error with profile command'), null); + } + }); + } +} + +module.exports = ProfilingLevelOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/re_index.js b/scripts/2.5/node_modules/mongodb/lib/operations/re_index.js new file mode 100644 index 00000000..89437fe3 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/operations/re_index.js @@ -0,0 +1,28 @@ +'use strict'; + +const CommandOperation = require('./command'); +const handleCallback = require('../utils').handleCallback; + +class ReIndexOperation extends CommandOperation { + constructor(collection, options) { + super(collection.s.db, options, collection); + } + + _buildCommand() { + const collection = this.collection; + + const cmd = { reIndex: collection.collectionName }; + + return cmd; + } + + execute(callback) { + super.execute((err, result) => { + if (callback == null) return; + if (err) return handleCallback(callback, err, null); + handleCallback(callback, null, result.ok ? true : false); + }); + } +} + +module.exports = ReIndexOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/remove_user.js b/scripts/2.5/node_modules/mongodb/lib/operations/remove_user.js new file mode 100644 index 00000000..9a59744d --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/operations/remove_user.js @@ -0,0 +1,52 @@ +'use strict'; + +const Aspect = require('./operation').Aspect; +const CommandOperation = require('./command'); +const defineAspects = require('./operation').defineAspects; +const handleCallback = require('../utils').handleCallback; +const WriteConcern = require('../write_concern'); + +class RemoveUserOperation extends CommandOperation { + constructor(db, username, options) { + const commandOptions = {}; + + const writeConcern = WriteConcern.fromOptions(options); + if (writeConcern != null) { + commandOptions.writeConcern = writeConcern; + } + + if (options.dbName) { + commandOptions.dbName = options.dbName; + } + + // Add maxTimeMS to options if set + if (typeof options.maxTimeMS === 'number') { + commandOptions.maxTimeMS = options.maxTimeMS; + } + + super(db, commandOptions); + + this.username = username; + } + + _buildCommand() { + const username = this.username; + + // Build the command to execute + const command = { dropUser: username }; + + return command; + } + + execute(callback) { + // Attempt to execute command + super.execute((err, result) => { + if (err) return handleCallback(callback, err, null); + handleCallback(callback, err, result.ok ? true : false); + }); + } +} + +defineAspects(RemoveUserOperation, [Aspect.WRITE_OPERATION, Aspect.SKIP_SESSIONS]); + +module.exports = RemoveUserOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/rename.js b/scripts/2.5/node_modules/mongodb/lib/operations/rename.js new file mode 100644 index 00000000..8098fe6b --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/operations/rename.js @@ -0,0 +1,61 @@ +'use strict'; + +const OperationBase = require('./operation').OperationBase; +const applyWriteConcern = require('../utils').applyWriteConcern; +const checkCollectionName = require('../utils').checkCollectionName; +const executeDbAdminCommand = require('./db_ops').executeDbAdminCommand; +const handleCallback = require('../utils').handleCallback; +const loadCollection = require('../dynamic_loaders').loadCollection; +const toError = require('../utils').toError; + +class RenameOperation extends OperationBase { + constructor(collection, newName, options) { + super(options); + + this.collection = collection; + this.newName = newName; + } + + execute(callback) { + const coll = this.collection; + const newName = this.newName; + const options = this.options; + + let Collection = loadCollection(); + // Check the collection name + checkCollectionName(newName); + // Build the command + const renameCollection = coll.namespace; + const toCollection = coll.s.namespace.withCollection(newName).toString(); + const dropTarget = typeof options.dropTarget === 'boolean' ? options.dropTarget : false; + const cmd = { renameCollection: renameCollection, to: toCollection, dropTarget: dropTarget }; + + // Decorate command with writeConcern if supported + applyWriteConcern(cmd, { db: coll.s.db, collection: coll }, options); + + // Execute against admin + executeDbAdminCommand(coll.s.db.admin().s.db, cmd, options, (err, doc) => { + if (err) return handleCallback(callback, err, null); + // We have an error + if (doc.errmsg) return handleCallback(callback, toError(doc), null); + try { + return handleCallback( + callback, + null, + new Collection( + coll.s.db, + coll.s.topology, + coll.s.namespace.db, + newName, + coll.s.pkFactory, + coll.s.options + ) + ); + } catch (err) { + return handleCallback(callback, toError(err), null); + } + }); + } +} + +module.exports = RenameOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/replace_one.js b/scripts/2.5/node_modules/mongodb/lib/operations/replace_one.js new file mode 100644 index 00000000..a5aa7608 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/operations/replace_one.js @@ -0,0 +1,47 @@ +'use strict'; + +const OperationBase = require('./operation').OperationBase; +const updateDocuments = require('./common_functions').updateDocuments; + +class ReplaceOneOperation extends OperationBase { + constructor(collection, filter, doc, options) { + super(options); + + this.collection = collection; + this.filter = filter; + this.doc = doc; + } + + execute(callback) { + const coll = this.collection; + const filter = this.filter; + const doc = this.doc; + const options = this.options; + + // Set single document update + options.multi = false; + + // Execute update + updateDocuments(coll, filter, doc, options, (err, r) => replaceCallback(err, r, doc, callback)); + } +} + +function replaceCallback(err, r, doc, callback) { + if (callback == null) return; + if (err && callback) return callback(err); + if (r == null) return callback(null, { result: { ok: 1 } }); + + r.modifiedCount = r.result.nModified != null ? r.result.nModified : r.result.n; + r.upsertedId = + Array.isArray(r.result.upserted) && r.result.upserted.length > 0 + ? r.result.upserted[0] // FIXME(major): should be `r.result.upserted[0]._id` + : null; + r.upsertedCount = + Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0; + r.matchedCount = + Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? 0 : r.result.n; + r.ops = [doc]; // TODO: Should we still have this? + if (callback) callback(null, r); +} + +module.exports = ReplaceOneOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/set_profiling_level.js b/scripts/2.5/node_modules/mongodb/lib/operations/set_profiling_level.js new file mode 100644 index 00000000..b31cc130 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/operations/set_profiling_level.js @@ -0,0 +1,48 @@ +'use strict'; + +const CommandOperation = require('./command'); +const levelValues = new Set(['off', 'slow_only', 'all']); + +class SetProfilingLevelOperation extends CommandOperation { + constructor(db, level, options) { + let profile = 0; + + if (level === 'off') { + profile = 0; + } else if (level === 'slow_only') { + profile = 1; + } else if (level === 'all') { + profile = 2; + } + + super(db, options); + this.level = level; + this.profile = profile; + } + + _buildCommand() { + const profile = this.profile; + + // Set up the profile number + const command = { profile }; + + return command; + } + + execute(callback) { + const level = this.level; + + if (!levelValues.has(level)) { + return callback(new Error('Error: illegal profiling level value ' + level)); + } + + super.execute((err, doc) => { + if (err == null && doc.ok === 1) return callback(null, level); + return err != null + ? callback(err, null) + : callback(new Error('Error with profile command'), null); + }); + } +} + +module.exports = SetProfilingLevelOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/stats.js b/scripts/2.5/node_modules/mongodb/lib/operations/stats.js new file mode 100644 index 00000000..ff79126e --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/operations/stats.js @@ -0,0 +1,45 @@ +'use strict'; + +const Aspect = require('./operation').Aspect; +const CommandOperation = require('./command'); +const defineAspects = require('./operation').defineAspects; + +/** + * Get all the collection statistics. + * + * @class + * @property {Collection} a Collection instance. + * @property {object} [options] Optional settings. See Collection.prototype.stats for a list of options. + */ +class StatsOperation extends CommandOperation { + /** + * Construct a Stats operation. + * + * @param {Collection} a Collection instance. + * @param {object} [options] Optional settings. See Collection.prototype.stats for a list of options. + */ + constructor(collection, options) { + super(collection.s.db, options, collection); + } + + _buildCommand() { + const collection = this.collection; + const options = this.options; + + // Build command object + const command = { + collStats: collection.collectionName + }; + + // Check if we have the scale value + if (options['scale'] != null) { + command['scale'] = options['scale']; + } + + return command; + } +} + +defineAspects(StatsOperation, Aspect.READ_OPERATION); + +module.exports = StatsOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/to_array.js b/scripts/2.5/node_modules/mongodb/lib/operations/to_array.js new file mode 100644 index 00000000..db6d1a07 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/operations/to_array.js @@ -0,0 +1,66 @@ +'use strict'; + +const Aspect = require('./operation').Aspect; +const defineAspects = require('./operation').defineAspects; +const handleCallback = require('../utils').handleCallback; +const CursorState = require('../core/cursor').CursorState; +const OperationBase = require('./operation').OperationBase; +const push = Array.prototype.push; + +class ToArrayOperation extends OperationBase { + constructor(cursor) { + super(); + + this.cursor = cursor; + } + + execute(callback) { + const cursor = this.cursor; + const items = []; + + // Reset cursor + cursor.rewind(); + cursor.s.state = CursorState.INIT; + + // Fetch all the documents + const fetchDocs = () => { + cursor._next((err, doc) => { + if (err) { + return cursor._endSession + ? cursor._endSession(() => handleCallback(callback, err)) + : handleCallback(callback, err); + } + + if (doc == null) { + return cursor.close({ skipKillCursors: true }, () => + handleCallback(callback, null, items) + ); + } + + // Add doc to items + items.push(doc); + + // Get all buffered objects + if (cursor.bufferedCount() > 0) { + let docs = cursor.readBufferedDocuments(cursor.bufferedCount()); + + // Transform the doc if transform method added + if (cursor.s.transforms && typeof cursor.s.transforms.doc === 'function') { + docs = docs.map(cursor.s.transforms.doc); + } + + push.apply(items, docs); + } + + // Attempt a fetch + fetchDocs(); + }); + }; + + fetchDocs(); + } +} + +defineAspects(ToArrayOperation, Aspect.SKIP_SESSION); + +module.exports = ToArrayOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/update_many.js b/scripts/2.5/node_modules/mongodb/lib/operations/update_many.js new file mode 100644 index 00000000..9a18d253 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/operations/update_many.js @@ -0,0 +1,29 @@ +'use strict'; + +const OperationBase = require('./operation').OperationBase; +const updateCallback = require('./common_functions').updateCallback; +const updateDocuments = require('./common_functions').updateDocuments; + +class UpdateManyOperation extends OperationBase { + constructor(collection, filter, update, options) { + super(options); + + this.collection = collection; + this.filter = filter; + this.update = update; + } + + execute(callback) { + const coll = this.collection; + const filter = this.filter; + const update = this.update; + const options = this.options; + + // Set single document update + options.multi = true; + // Execute update + updateDocuments(coll, filter, update, options, (err, r) => updateCallback(err, r, callback)); + } +} + +module.exports = UpdateManyOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/update_one.js b/scripts/2.5/node_modules/mongodb/lib/operations/update_one.js new file mode 100644 index 00000000..b1c1bc16 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/operations/update_one.js @@ -0,0 +1,44 @@ +'use strict'; + +const OperationBase = require('./operation').OperationBase; +const updateDocuments = require('./common_functions').updateDocuments; + +class UpdateOneOperation extends OperationBase { + constructor(collection, filter, update, options) { + super(options); + + this.collection = collection; + this.filter = filter; + this.update = update; + } + + execute(callback) { + const coll = this.collection; + const filter = this.filter; + const update = this.update; + const options = this.options; + + // Set single document update + options.multi = false; + // Execute update + updateDocuments(coll, filter, update, options, (err, r) => updateCallback(err, r, callback)); + } +} + +function updateCallback(err, r, callback) { + if (callback == null) return; + if (err) return callback(err); + if (r == null) return callback(null, { result: { ok: 1 } }); + r.modifiedCount = r.result.nModified != null ? r.result.nModified : r.result.n; + r.upsertedId = + Array.isArray(r.result.upserted) && r.result.upserted.length > 0 + ? r.result.upserted[0] // FIXME(major): should be `r.result.upserted[0]._id` + : null; + r.upsertedCount = + Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0; + r.matchedCount = + Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? 0 : r.result.n; + callback(null, r); +} + +module.exports = UpdateOneOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/validate_collection.js b/scripts/2.5/node_modules/mongodb/lib/operations/validate_collection.js new file mode 100644 index 00000000..133c6c4b --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/operations/validate_collection.js @@ -0,0 +1,40 @@ +'use strict'; + +const CommandOperation = require('./command'); + +class ValidateCollectionOperation extends CommandOperation { + constructor(admin, collectionName, options) { + // Decorate command with extra options + let command = { validate: collectionName }; + const keys = Object.keys(options); + for (let i = 0; i < keys.length; i++) { + if (options.hasOwnProperty(keys[i]) && keys[i] !== 'session') { + command[keys[i]] = options[keys[i]]; + } + } + + super(admin.s.db, options, null, command); + + this.collectionName; + } + + execute(callback) { + const collectionName = this.collectionName; + + super.execute((err, doc) => { + if (err != null) return callback(err, null); + + if (doc.ok === 0) return callback(new Error('Error with validate command'), null); + if (doc.result != null && doc.result.constructor !== String) + return callback(new Error('Error with validation data'), null); + if (doc.result != null && doc.result.match(/exception|corrupt/) != null) + return callback(new Error('Error: invalid collection ' + collectionName), null); + if (doc.valid != null && !doc.valid) + return callback(new Error('Error: invalid collection ' + collectionName), null); + + return callback(null, doc); + }); + } +} + +module.exports = ValidateCollectionOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/read_concern.js b/scripts/2.5/node_modules/mongodb/lib/read_concern.js new file mode 100644 index 00000000..b48b8e0e --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/read_concern.js @@ -0,0 +1,61 @@ +'use strict'; + +/** + * The **ReadConcern** class is a class that represents a MongoDB ReadConcern. + * @class + * @property {string} level The read concern level + * @see https://docs.mongodb.com/manual/reference/read-concern/index.html + */ +class ReadConcern { + /** + * Constructs a ReadConcern from the read concern properties. + * @param {string} [level] The read concern level ({'local'|'available'|'majority'|'linearizable'|'snapshot'}) + */ + constructor(level) { + if (level != null) { + this.level = level; + } + } + + /** + * Construct a ReadConcern given an options object. + * + * @param {object} options The options object from which to extract the write concern. + * @return {ReadConcern} + */ + static fromOptions(options) { + if (options == null) { + return; + } + + if (options.readConcern) { + if (options.readConcern instanceof ReadConcern) { + return options.readConcern; + } + + return new ReadConcern(options.readConcern.level); + } + + if (options.level) { + return new ReadConcern(options.level); + } + } + + static get MAJORITY() { + return 'majority'; + } + + static get AVAILABLE() { + return 'available'; + } + + static get LINEARIZABLE() { + return 'linearizable'; + } + + static get SNAPSHOT() { + return 'snapshot'; + } +} + +module.exports = ReadConcern; diff --git a/scripts/2.5/node_modules/mongodb/lib/topologies/mongos.js b/scripts/2.5/node_modules/mongodb/lib/topologies/mongos.js new file mode 100644 index 00000000..ec14f485 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/topologies/mongos.js @@ -0,0 +1,452 @@ +'use strict'; + +const TopologyBase = require('./topology_base').TopologyBase; +const MongoError = require('../core').MongoError; +const CMongos = require('../core').Mongos; +const Cursor = require('../cursor'); +const Server = require('./server'); +const Store = require('./topology_base').Store; +const MAX_JS_INT = require('../utils').MAX_JS_INT; +const translateOptions = require('../utils').translateOptions; +const filterOptions = require('../utils').filterOptions; +const mergeOptions = require('../utils').mergeOptions; + +/** + * @fileOverview The **Mongos** class is a class that represents a Mongos Proxy topology and is + * used to construct connections. + * + * **Mongos Should not be used, use MongoClient.connect** + */ + +// Allowed parameters +var legalOptionNames = [ + 'ha', + 'haInterval', + 'acceptableLatencyMS', + 'poolSize', + 'ssl', + 'checkServerIdentity', + 'sslValidate', + 'sslCA', + 'sslCRL', + 'sslCert', + 'ciphers', + 'ecdhCurve', + 'sslKey', + 'sslPass', + 'socketOptions', + 'bufferMaxEntries', + 'store', + 'auto_reconnect', + 'autoReconnect', + 'emitError', + 'keepAlive', + 'keepAliveInitialDelay', + 'noDelay', + 'connectTimeoutMS', + 'socketTimeoutMS', + 'loggerLevel', + 'logger', + 'reconnectTries', + 'appname', + 'domainsEnabled', + 'servername', + 'promoteLongs', + 'promoteValues', + 'promoteBuffers', + 'promiseLibrary', + 'monitorCommands' +]; + +/** + * Creates a new Mongos instance + * @class + * @deprecated + * @param {Server[]} servers A seedlist of servers participating in the replicaset. + * @param {object} [options] Optional settings. + * @param {booelan} [options.ha=true] Turn on high availability monitoring. + * @param {number} [options.haInterval=5000] Time between each replicaset status check. + * @param {number} [options.poolSize=5] Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons. + * @param {number} [options.acceptableLatencyMS=15] Cutoff latency point in MS for MongoS proxy selection + * @param {boolean} [options.ssl=false] Use ssl connection (needs to have a mongod server with ssl support) + * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. + * @param {boolean} [options.sslValidate=false] Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {array} [options.sslCA] Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {array} [options.sslCRL] Array of revocation certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {string} [options.ciphers] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. + * @param {string} [options.ecdhCurve] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. + * @param {(Buffer|string)} [options.sslCert] String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {(Buffer|string)} [options.sslKey] String or buffer containing the certificate private key we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {(Buffer|string)} [options.sslPass] String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {string} [options.servername] String containing the server name requested via TLS SNI. + * @param {object} [options.socketOptions] Socket options + * @param {boolean} [options.socketOptions.noDelay=true] TCP Socket NoDelay option. + * @param {boolean} [options.socketOptions.keepAlive=true] TCP Connection keep alive enabled + * @param {number} [options.socketOptions.keepAliveInitialDelay=30000] The number of milliseconds to wait before initiating keepAlive on the TCP socket + * @param {number} [options.socketOptions.connectTimeoutMS=0] TCP Connection timeout setting + * @param {number} [options.socketOptions.socketTimeoutMS=0] TCP Socket timeout setting + * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. + * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology + * @fires Mongos#connect + * @fires Mongos#ha + * @fires Mongos#joined + * @fires Mongos#left + * @fires Mongos#fullsetup + * @fires Mongos#open + * @fires Mongos#close + * @fires Mongos#error + * @fires Mongos#timeout + * @fires Mongos#parseError + * @fires Mongos#commandStarted + * @fires Mongos#commandSucceeded + * @fires Mongos#commandFailed + * @property {string} parserType the parser type used (c++ or js). + * @return {Mongos} a Mongos instance. + */ +class Mongos extends TopologyBase { + constructor(servers, options) { + super(); + + options = options || {}; + var self = this; + + // Filter the options + options = filterOptions(options, legalOptionNames); + + // Ensure all the instances are Server + for (var i = 0; i < servers.length; i++) { + if (!(servers[i] instanceof Server)) { + throw MongoError.create({ + message: 'all seed list instances must be of the Server type', + driver: true + }); + } + } + + // Stored options + var storeOptions = { + force: false, + bufferMaxEntries: + typeof options.bufferMaxEntries === 'number' ? options.bufferMaxEntries : MAX_JS_INT + }; + + // Shared global store + var store = options.store || new Store(self, storeOptions); + + // Build seed list + var seedlist = servers.map(function(x) { + return { host: x.host, port: x.port }; + }); + + // Get the reconnect option + var reconnect = typeof options.auto_reconnect === 'boolean' ? options.auto_reconnect : true; + reconnect = typeof options.autoReconnect === 'boolean' ? options.autoReconnect : reconnect; + + // Clone options + var clonedOptions = mergeOptions( + {}, + { + disconnectHandler: store, + cursorFactory: Cursor, + reconnect: reconnect, + emitError: typeof options.emitError === 'boolean' ? options.emitError : true, + size: typeof options.poolSize === 'number' ? options.poolSize : 5, + monitorCommands: + typeof options.monitorCommands === 'boolean' ? options.monitorCommands : false + } + ); + + // Translate any SSL options and other connectivity options + clonedOptions = translateOptions(clonedOptions, options); + + // Socket options + var socketOptions = + options.socketOptions && Object.keys(options.socketOptions).length > 0 + ? options.socketOptions + : options; + + // Translate all the options to the core types + clonedOptions = translateOptions(clonedOptions, socketOptions); + + // Build default client information + clonedOptions.clientInfo = this.clientInfo; + // Do we have an application specific string + if (options.appname) { + clonedOptions.clientInfo.application = { name: options.appname }; + } + + // Internal state + this.s = { + // Create the Mongos + coreTopology: new CMongos(seedlist, clonedOptions), + // Server capabilities + sCapabilities: null, + // Debug turned on + debug: clonedOptions.debug, + // Store option defaults + storeOptions: storeOptions, + // Cloned options + clonedOptions: clonedOptions, + // Actual store of callbacks + store: store, + // Options + options: options, + // Server Session Pool + sessionPool: null, + // Active client sessions + sessions: new Set(), + // Promise library + promiseLibrary: options.promiseLibrary || Promise + }; + } + + // Connect + connect(_options, callback) { + var self = this; + if ('function' === typeof _options) (callback = _options), (_options = {}); + if (_options == null) _options = {}; + if (!('function' === typeof callback)) callback = null; + _options = Object.assign({}, this.s.clonedOptions, _options); + self.s.options = _options; + + // Update bufferMaxEntries + self.s.storeOptions.bufferMaxEntries = + typeof _options.bufferMaxEntries === 'number' ? _options.bufferMaxEntries : -1; + + // Error handler + var connectErrorHandler = function() { + return function(err) { + // Remove all event handlers + var events = ['timeout', 'error', 'close']; + events.forEach(function(e) { + self.removeListener(e, connectErrorHandler); + }); + + self.s.coreTopology.removeListener('connect', connectErrorHandler); + // Force close the topology + self.close(true); + + // Try to callback + try { + callback(err); + } catch (err) { + process.nextTick(function() { + throw err; + }); + } + }; + }; + + // Actual handler + var errorHandler = function(event) { + return function(err) { + if (event !== 'error') { + self.emit(event, err); + } + }; + }; + + // Error handler + var reconnectHandler = function() { + self.emit('reconnect'); + self.s.store.execute(); + }; + + // relay the event + var relay = function(event) { + return function(t, server) { + self.emit(event, t, server); + }; + }; + + // Connect handler + var connectHandler = function() { + // Clear out all the current handlers left over + var events = ['timeout', 'error', 'close', 'fullsetup']; + events.forEach(function(e) { + self.s.coreTopology.removeAllListeners(e); + }); + + // Set up listeners + self.s.coreTopology.on('timeout', errorHandler('timeout')); + self.s.coreTopology.on('error', errorHandler('error')); + self.s.coreTopology.on('close', errorHandler('close')); + + // Set up serverConfig listeners + self.s.coreTopology.on('fullsetup', function() { + self.emit('fullsetup', self); + }); + + // Emit open event + self.emit('open', null, self); + + // Return correctly + try { + callback(null, self); + } catch (err) { + process.nextTick(function() { + throw err; + }); + } + }; + + // Clear out all the current handlers left over + var events = [ + 'timeout', + 'error', + 'close', + 'serverOpening', + 'serverDescriptionChanged', + 'serverHeartbeatStarted', + 'serverHeartbeatSucceeded', + 'serverHeartbeatFailed', + 'serverClosed', + 'topologyOpening', + 'topologyClosed', + 'topologyDescriptionChanged', + 'commandStarted', + 'commandSucceeded', + 'commandFailed' + ]; + events.forEach(function(e) { + self.s.coreTopology.removeAllListeners(e); + }); + + // Set up SDAM listeners + self.s.coreTopology.on('serverDescriptionChanged', relay('serverDescriptionChanged')); + self.s.coreTopology.on('serverHeartbeatStarted', relay('serverHeartbeatStarted')); + self.s.coreTopology.on('serverHeartbeatSucceeded', relay('serverHeartbeatSucceeded')); + self.s.coreTopology.on('serverHeartbeatFailed', relay('serverHeartbeatFailed')); + self.s.coreTopology.on('serverOpening', relay('serverOpening')); + self.s.coreTopology.on('serverClosed', relay('serverClosed')); + self.s.coreTopology.on('topologyOpening', relay('topologyOpening')); + self.s.coreTopology.on('topologyClosed', relay('topologyClosed')); + self.s.coreTopology.on('topologyDescriptionChanged', relay('topologyDescriptionChanged')); + self.s.coreTopology.on('commandStarted', relay('commandStarted')); + self.s.coreTopology.on('commandSucceeded', relay('commandSucceeded')); + self.s.coreTopology.on('commandFailed', relay('commandFailed')); + + // Set up listeners + self.s.coreTopology.once('timeout', connectErrorHandler('timeout')); + self.s.coreTopology.once('error', connectErrorHandler('error')); + self.s.coreTopology.once('close', connectErrorHandler('close')); + self.s.coreTopology.once('connect', connectHandler); + // Join and leave events + self.s.coreTopology.on('joined', relay('joined')); + self.s.coreTopology.on('left', relay('left')); + + // Reconnect server + self.s.coreTopology.on('reconnect', reconnectHandler); + + // Start connection + self.s.coreTopology.connect(_options); + } +} + +Object.defineProperty(Mongos.prototype, 'haInterval', { + enumerable: true, + get: function() { + return this.s.coreTopology.s.haInterval; + } +}); + +/** + * A mongos connect event, used to verify that the connection is up and running + * + * @event Mongos#connect + * @type {Mongos} + */ + +/** + * The mongos high availability event + * + * @event Mongos#ha + * @type {function} + * @param {string} type The stage in the high availability event (start|end) + * @param {boolean} data.norepeat This is a repeating high availability process or a single execution only + * @param {number} data.id The id for this high availability request + * @param {object} data.state An object containing the information about the current replicaset + */ + +/** + * A server member left the mongos set + * + * @event Mongos#left + * @type {function} + * @param {string} type The type of member that left (primary|secondary|arbiter) + * @param {Server} server The server object that left + */ + +/** + * A server member joined the mongos set + * + * @event Mongos#joined + * @type {function} + * @param {string} type The type of member that joined (primary|secondary|arbiter) + * @param {Server} server The server object that joined + */ + +/** + * Mongos fullsetup event, emitted when all proxies in the topology have been connected to. + * + * @event Mongos#fullsetup + * @type {Mongos} + */ + +/** + * Mongos open event, emitted when mongos can start processing commands. + * + * @event Mongos#open + * @type {Mongos} + */ + +/** + * Mongos close event + * + * @event Mongos#close + * @type {object} + */ + +/** + * Mongos error event, emitted if there is an error listener. + * + * @event Mongos#error + * @type {MongoError} + */ + +/** + * Mongos timeout event + * + * @event Mongos#timeout + * @type {object} + */ + +/** + * Mongos parseError event + * + * @event Mongos#parseError + * @type {object} + */ + +/** + * An event emitted indicating a command was started, if command monitoring is enabled + * + * @event Mongos#commandStarted + * @type {object} + */ + +/** + * An event emitted indicating a command succeeded, if command monitoring is enabled + * + * @event Mongos#commandSucceeded + * @type {object} + */ + +/** + * An event emitted indicating a command failed, if command monitoring is enabled + * + * @event Mongos#commandFailed + * @type {object} + */ + +module.exports = Mongos; diff --git a/scripts/2.5/node_modules/mongodb/lib/topologies/native_topology.js b/scripts/2.5/node_modules/mongodb/lib/topologies/native_topology.js new file mode 100644 index 00000000..51574878 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/topologies/native_topology.js @@ -0,0 +1,72 @@ +'use strict'; + +const Topology = require('../core').Topology; +const ServerCapabilities = require('./topology_base').ServerCapabilities; +const Cursor = require('../cursor'); +const translateOptions = require('../utils').translateOptions; + +class NativeTopology extends Topology { + constructor(servers, options) { + options = options || {}; + + let clonedOptions = Object.assign( + {}, + { + cursorFactory: Cursor, + reconnect: false, + emitError: typeof options.emitError === 'boolean' ? options.emitError : true, + size: typeof options.poolSize === 'number' ? options.poolSize : 5, + monitorCommands: + typeof options.monitorCommands === 'boolean' ? options.monitorCommands : false + } + ); + + // Translate any SSL options and other connectivity options + clonedOptions = translateOptions(clonedOptions, options); + + // Socket options + var socketOptions = + options.socketOptions && Object.keys(options.socketOptions).length > 0 + ? options.socketOptions + : options; + + // Translate all the options to the core types + clonedOptions = translateOptions(clonedOptions, socketOptions); + + super(servers, clonedOptions); + + // Do we have an application specific string + if (options.appname) { + this.s.clientInfo.application = { name: options.appname }; + } + } + + capabilities() { + if (this.s.sCapabilities) return this.s.sCapabilities; + if (this.lastIsMaster() == null) return null; + this.s.sCapabilities = new ServerCapabilities(this.lastIsMaster()); + return this.s.sCapabilities; + } + + // Command + command(ns, cmd, options, callback) { + super.command(ns.toString(), cmd, options, callback); + } + + // Insert + insert(ns, ops, options, callback) { + super.insert(ns.toString(), ops, options, callback); + } + + // Update + update(ns, ops, options, callback) { + super.update(ns.toString(), ops, options, callback); + } + + // Remove + remove(ns, ops, options, callback) { + super.remove(ns.toString(), ops, options, callback); + } +} + +module.exports = NativeTopology; diff --git a/scripts/2.5/node_modules/mongodb/lib/topologies/replset.js b/scripts/2.5/node_modules/mongodb/lib/topologies/replset.js new file mode 100644 index 00000000..44e83d11 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/topologies/replset.js @@ -0,0 +1,496 @@ +'use strict'; + +const Server = require('./server'); +const Cursor = require('../cursor'); +const MongoError = require('../core').MongoError; +const TopologyBase = require('./topology_base').TopologyBase; +const Store = require('./topology_base').Store; +const CReplSet = require('../core').ReplSet; +const MAX_JS_INT = require('../utils').MAX_JS_INT; +const translateOptions = require('../utils').translateOptions; +const filterOptions = require('../utils').filterOptions; +const mergeOptions = require('../utils').mergeOptions; + +/** + * @fileOverview The **ReplSet** class is a class that represents a Replicaset topology and is + * used to construct connections. + * + * **ReplSet Should not be used, use MongoClient.connect** + */ + +// Allowed parameters +var legalOptionNames = [ + 'ha', + 'haInterval', + 'replicaSet', + 'rs_name', + 'secondaryAcceptableLatencyMS', + 'connectWithNoPrimary', + 'poolSize', + 'ssl', + 'checkServerIdentity', + 'sslValidate', + 'sslCA', + 'sslCert', + 'ciphers', + 'ecdhCurve', + 'sslCRL', + 'sslKey', + 'sslPass', + 'socketOptions', + 'bufferMaxEntries', + 'store', + 'auto_reconnect', + 'autoReconnect', + 'emitError', + 'keepAlive', + 'keepAliveInitialDelay', + 'noDelay', + 'connectTimeoutMS', + 'socketTimeoutMS', + 'strategy', + 'debug', + 'family', + 'loggerLevel', + 'logger', + 'reconnectTries', + 'appname', + 'domainsEnabled', + 'servername', + 'promoteLongs', + 'promoteValues', + 'promoteBuffers', + 'maxStalenessSeconds', + 'promiseLibrary', + 'minSize', + 'monitorCommands' +]; + +/** + * Creates a new ReplSet instance + * @class + * @deprecated + * @param {Server[]} servers A seedlist of servers participating in the replicaset. + * @param {object} [options] Optional settings. + * @param {boolean} [options.ha=true] Turn on high availability monitoring. + * @param {number} [options.haInterval=10000] Time between each replicaset status check. + * @param {string} [options.replicaSet] The name of the replicaset to connect to. + * @param {number} [options.secondaryAcceptableLatencyMS=15] Sets the range of servers to pick when using NEAREST (lowest ping ms + the latency fence, ex: range of 1 to (1 + 15) ms) + * @param {boolean} [options.connectWithNoPrimary=false] Sets if the driver should connect even if no primary is available + * @param {number} [options.poolSize=5] Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons. + * @param {boolean} [options.ssl=false] Use ssl connection (needs to have a mongod server with ssl support) + * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. + * @param {boolean} [options.sslValidate=false] Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {array} [options.sslCA] Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {array} [options.sslCRL] Array of revocation certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {(Buffer|string)} [options.sslCert] String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher. + * @param {string} [options.ciphers] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. + * @param {string} [options.ecdhCurve] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. + * @param {(Buffer|string)} [options.sslKey] String or buffer containing the certificate private key we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {(Buffer|string)} [options.sslPass] String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {string} [options.servername] String containing the server name requested via TLS SNI. + * @param {object} [options.socketOptions] Socket options + * @param {boolean} [options.socketOptions.noDelay=true] TCP Socket NoDelay option. + * @param {boolean} [options.socketOptions.keepAlive=true] TCP Connection keep alive enabled + * @param {number} [options.socketOptions.keepAliveInitialDelay=30000] The number of milliseconds to wait before initiating keepAlive on the TCP socket + * @param {number} [options.socketOptions.connectTimeoutMS=10000] TCP Connection timeout setting + * @param {number} [options.socketOptions.socketTimeoutMS=0] TCP Socket timeout setting + * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. + * @param {number} [options.maxStalenessSeconds=undefined] The max staleness to secondary reads (values under 10 seconds cannot be guaranteed); + * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology + * @fires ReplSet#connect + * @fires ReplSet#ha + * @fires ReplSet#joined + * @fires ReplSet#left + * @fires ReplSet#fullsetup + * @fires ReplSet#open + * @fires ReplSet#close + * @fires ReplSet#error + * @fires ReplSet#timeout + * @fires ReplSet#parseError + * @fires ReplSet#commandStarted + * @fires ReplSet#commandSucceeded + * @fires ReplSet#commandFailed + * @property {string} parserType the parser type used (c++ or js). + * @return {ReplSet} a ReplSet instance. + */ +class ReplSet extends TopologyBase { + constructor(servers, options) { + super(); + + options = options || {}; + var self = this; + + // Filter the options + options = filterOptions(options, legalOptionNames); + + // Ensure all the instances are Server + for (var i = 0; i < servers.length; i++) { + if (!(servers[i] instanceof Server)) { + throw MongoError.create({ + message: 'all seed list instances must be of the Server type', + driver: true + }); + } + } + + // Stored options + var storeOptions = { + force: false, + bufferMaxEntries: + typeof options.bufferMaxEntries === 'number' ? options.bufferMaxEntries : MAX_JS_INT + }; + + // Shared global store + var store = options.store || new Store(self, storeOptions); + + // Build seed list + var seedlist = servers.map(function(x) { + return { host: x.host, port: x.port }; + }); + + // Clone options + var clonedOptions = mergeOptions( + {}, + { + disconnectHandler: store, + cursorFactory: Cursor, + reconnect: false, + emitError: typeof options.emitError === 'boolean' ? options.emitError : true, + size: typeof options.poolSize === 'number' ? options.poolSize : 5, + monitorCommands: + typeof options.monitorCommands === 'boolean' ? options.monitorCommands : false + } + ); + + // Translate any SSL options and other connectivity options + clonedOptions = translateOptions(clonedOptions, options); + + // Socket options + var socketOptions = + options.socketOptions && Object.keys(options.socketOptions).length > 0 + ? options.socketOptions + : options; + + // Translate all the options to the core types + clonedOptions = translateOptions(clonedOptions, socketOptions); + + // Build default client information + clonedOptions.clientInfo = this.clientInfo; + // Do we have an application specific string + if (options.appname) { + clonedOptions.clientInfo.application = { name: options.appname }; + } + + // Create the ReplSet + var coreTopology = new CReplSet(seedlist, clonedOptions); + + // Listen to reconnect event + coreTopology.on('reconnect', function() { + self.emit('reconnect'); + store.execute(); + }); + + // Internal state + this.s = { + // Replicaset + coreTopology: coreTopology, + // Server capabilities + sCapabilities: null, + // Debug tag + tag: options.tag, + // Store options + storeOptions: storeOptions, + // Cloned options + clonedOptions: clonedOptions, + // Store + store: store, + // Options + options: options, + // Server Session Pool + sessionPool: null, + // Active client sessions + sessions: new Set(), + // Promise library + promiseLibrary: options.promiseLibrary || Promise + }; + + // Debug + if (clonedOptions.debug) { + // Last ismaster + Object.defineProperty(this, 'replset', { + enumerable: true, + get: function() { + return coreTopology; + } + }); + } + } + + // Connect method + connect(_options, callback) { + var self = this; + if ('function' === typeof _options) (callback = _options), (_options = {}); + if (_options == null) _options = {}; + if (!('function' === typeof callback)) callback = null; + _options = Object.assign({}, this.s.clonedOptions, _options); + self.s.options = _options; + + // Update bufferMaxEntries + self.s.storeOptions.bufferMaxEntries = + typeof _options.bufferMaxEntries === 'number' ? _options.bufferMaxEntries : -1; + + // Actual handler + var errorHandler = function(event) { + return function(err) { + if (event !== 'error') { + self.emit(event, err); + } + }; + }; + + // Clear out all the current handlers left over + var events = [ + 'timeout', + 'error', + 'close', + 'serverOpening', + 'serverDescriptionChanged', + 'serverHeartbeatStarted', + 'serverHeartbeatSucceeded', + 'serverHeartbeatFailed', + 'serverClosed', + 'topologyOpening', + 'topologyClosed', + 'topologyDescriptionChanged', + 'commandStarted', + 'commandSucceeded', + 'commandFailed', + 'joined', + 'left', + 'ping', + 'ha' + ]; + events.forEach(function(e) { + self.s.coreTopology.removeAllListeners(e); + }); + + // relay the event + var relay = function(event) { + return function(t, server) { + self.emit(event, t, server); + }; + }; + + // Replset events relay + var replsetRelay = function(event) { + return function(t, server) { + self.emit(event, t, server.lastIsMaster(), server); + }; + }; + + // Relay ha + var relayHa = function(t, state) { + self.emit('ha', t, state); + + if (t === 'start') { + self.emit('ha_connect', t, state); + } else if (t === 'end') { + self.emit('ha_ismaster', t, state); + } + }; + + // Set up serverConfig listeners + self.s.coreTopology.on('joined', replsetRelay('joined')); + self.s.coreTopology.on('left', relay('left')); + self.s.coreTopology.on('ping', relay('ping')); + self.s.coreTopology.on('ha', relayHa); + + // Set up SDAM listeners + self.s.coreTopology.on('serverDescriptionChanged', relay('serverDescriptionChanged')); + self.s.coreTopology.on('serverHeartbeatStarted', relay('serverHeartbeatStarted')); + self.s.coreTopology.on('serverHeartbeatSucceeded', relay('serverHeartbeatSucceeded')); + self.s.coreTopology.on('serverHeartbeatFailed', relay('serverHeartbeatFailed')); + self.s.coreTopology.on('serverOpening', relay('serverOpening')); + self.s.coreTopology.on('serverClosed', relay('serverClosed')); + self.s.coreTopology.on('topologyOpening', relay('topologyOpening')); + self.s.coreTopology.on('topologyClosed', relay('topologyClosed')); + self.s.coreTopology.on('topologyDescriptionChanged', relay('topologyDescriptionChanged')); + self.s.coreTopology.on('commandStarted', relay('commandStarted')); + self.s.coreTopology.on('commandSucceeded', relay('commandSucceeded')); + self.s.coreTopology.on('commandFailed', relay('commandFailed')); + + self.s.coreTopology.on('fullsetup', function() { + self.emit('fullsetup', self, self); + }); + + self.s.coreTopology.on('all', function() { + self.emit('all', null, self); + }); + + // Connect handler + var connectHandler = function() { + // Set up listeners + self.s.coreTopology.once('timeout', errorHandler('timeout')); + self.s.coreTopology.once('error', errorHandler('error')); + self.s.coreTopology.once('close', errorHandler('close')); + + // Emit open event + self.emit('open', null, self); + + // Return correctly + try { + callback(null, self); + } catch (err) { + process.nextTick(function() { + throw err; + }); + } + }; + + // Error handler + var connectErrorHandler = function() { + return function(err) { + ['timeout', 'error', 'close'].forEach(function(e) { + self.s.coreTopology.removeListener(e, connectErrorHandler); + }); + + self.s.coreTopology.removeListener('connect', connectErrorHandler); + // Destroy the replset + self.s.coreTopology.destroy(); + + // Try to callback + try { + callback(err); + } catch (err) { + if (!self.s.coreTopology.isConnected()) + process.nextTick(function() { + throw err; + }); + } + }; + }; + + // Set up listeners + self.s.coreTopology.once('timeout', connectErrorHandler('timeout')); + self.s.coreTopology.once('error', connectErrorHandler('error')); + self.s.coreTopology.once('close', connectErrorHandler('close')); + self.s.coreTopology.once('connect', connectHandler); + + // Start connection + self.s.coreTopology.connect(_options); + } + + close(forceClosed, callback) { + ['timeout', 'error', 'close', 'joined', 'left'].forEach(e => this.removeAllListeners(e)); + super.close(forceClosed, callback); + } +} + +Object.defineProperty(ReplSet.prototype, 'haInterval', { + enumerable: true, + get: function() { + return this.s.coreTopology.s.haInterval; + } +}); + +/** + * A replset connect event, used to verify that the connection is up and running + * + * @event ReplSet#connect + * @type {ReplSet} + */ + +/** + * The replset high availability event + * + * @event ReplSet#ha + * @type {function} + * @param {string} type The stage in the high availability event (start|end) + * @param {boolean} data.norepeat This is a repeating high availability process or a single execution only + * @param {number} data.id The id for this high availability request + * @param {object} data.state An object containing the information about the current replicaset + */ + +/** + * A server member left the replicaset + * + * @event ReplSet#left + * @type {function} + * @param {string} type The type of member that left (primary|secondary|arbiter) + * @param {Server} server The server object that left + */ + +/** + * A server member joined the replicaset + * + * @event ReplSet#joined + * @type {function} + * @param {string} type The type of member that joined (primary|secondary|arbiter) + * @param {Server} server The server object that joined + */ + +/** + * ReplSet open event, emitted when replicaset can start processing commands. + * + * @event ReplSet#open + * @type {Replset} + */ + +/** + * ReplSet fullsetup event, emitted when all servers in the topology have been connected to. + * + * @event ReplSet#fullsetup + * @type {Replset} + */ + +/** + * ReplSet close event + * + * @event ReplSet#close + * @type {object} + */ + +/** + * ReplSet error event, emitted if there is an error listener. + * + * @event ReplSet#error + * @type {MongoError} + */ + +/** + * ReplSet timeout event + * + * @event ReplSet#timeout + * @type {object} + */ + +/** + * ReplSet parseError event + * + * @event ReplSet#parseError + * @type {object} + */ + +/** + * An event emitted indicating a command was started, if command monitoring is enabled + * + * @event ReplSet#commandStarted + * @type {object} + */ + +/** + * An event emitted indicating a command succeeded, if command monitoring is enabled + * + * @event ReplSet#commandSucceeded + * @type {object} + */ + +/** + * An event emitted indicating a command failed, if command monitoring is enabled + * + * @event ReplSet#commandFailed + * @type {object} + */ + +module.exports = ReplSet; diff --git a/scripts/2.5/node_modules/mongodb/lib/topologies/server.js b/scripts/2.5/node_modules/mongodb/lib/topologies/server.js new file mode 100644 index 00000000..9bbe4350 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/topologies/server.js @@ -0,0 +1,455 @@ +'use strict'; + +const CServer = require('../core').Server; +const Cursor = require('../cursor'); +const TopologyBase = require('./topology_base').TopologyBase; +const Store = require('./topology_base').Store; +const MongoError = require('../core').MongoError; +const MAX_JS_INT = require('../utils').MAX_JS_INT; +const translateOptions = require('../utils').translateOptions; +const filterOptions = require('../utils').filterOptions; +const mergeOptions = require('../utils').mergeOptions; + +/** + * @fileOverview The **Server** class is a class that represents a single server topology and is + * used to construct connections. + * + * **Server Should not be used, use MongoClient.connect** + */ + +// Allowed parameters +var legalOptionNames = [ + 'ha', + 'haInterval', + 'acceptableLatencyMS', + 'poolSize', + 'ssl', + 'checkServerIdentity', + 'sslValidate', + 'sslCA', + 'sslCRL', + 'sslCert', + 'ciphers', + 'ecdhCurve', + 'sslKey', + 'sslPass', + 'socketOptions', + 'bufferMaxEntries', + 'store', + 'auto_reconnect', + 'autoReconnect', + 'emitError', + 'keepAlive', + 'keepAliveInitialDelay', + 'noDelay', + 'connectTimeoutMS', + 'socketTimeoutMS', + 'family', + 'loggerLevel', + 'logger', + 'reconnectTries', + 'reconnectInterval', + 'monitoring', + 'appname', + 'domainsEnabled', + 'servername', + 'promoteLongs', + 'promoteValues', + 'promoteBuffers', + 'compression', + 'promiseLibrary', + 'monitorCommands' +]; + +/** + * Creates a new Server instance + * @class + * @deprecated + * @param {string} host The host for the server, can be either an IP4, IP6 or domain socket style host. + * @param {number} [port] The server port if IP4. + * @param {object} [options] Optional settings. + * @param {number} [options.poolSize=5] Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons. + * @param {boolean} [options.ssl=false] Use ssl connection (needs to have a mongod server with ssl support) + * @param {boolean} [options.sslValidate=false] Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. + * @param {array} [options.sslCA] Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {array} [options.sslCRL] Array of revocation certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {(Buffer|string)} [options.sslCert] String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {string} [options.ciphers] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. + * @param {string} [options.ecdhCurve] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. + * @param {(Buffer|string)} [options.sslKey] String or buffer containing the certificate private key we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {(Buffer|string)} [options.sslPass] String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {string} [options.servername] String containing the server name requested via TLS SNI. + * @param {object} [options.socketOptions] Socket options + * @param {boolean} [options.socketOptions.autoReconnect=true] Reconnect on error. + * @param {boolean} [options.socketOptions.noDelay=true] TCP Socket NoDelay option. + * @param {boolean} [options.socketOptions.keepAlive=true] TCP Connection keep alive enabled + * @param {number} [options.socketOptions.keepAliveInitialDelay=30000] The number of milliseconds to wait before initiating keepAlive on the TCP socket + * @param {number} [options.socketOptions.connectTimeoutMS=0] TCP Connection timeout setting + * @param {number} [options.socketOptions.socketTimeoutMS=0] TCP Socket timeout setting + * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times + * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries + * @param {boolean} [options.monitoring=true] Triggers the server instance to call ismaster + * @param {number} [options.haInterval=10000] The interval of calling ismaster when monitoring is enabled. + * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. + * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology + * @fires Server#connect + * @fires Server#close + * @fires Server#error + * @fires Server#timeout + * @fires Server#parseError + * @fires Server#reconnect + * @fires Server#commandStarted + * @fires Server#commandSucceeded + * @fires Server#commandFailed + * @property {string} parserType the parser type used (c++ or js). + * @return {Server} a Server instance. + */ +class Server extends TopologyBase { + constructor(host, port, options) { + super(); + var self = this; + + // Filter the options + options = filterOptions(options, legalOptionNames); + + // Promise library + const promiseLibrary = options.promiseLibrary; + + // Stored options + var storeOptions = { + force: false, + bufferMaxEntries: + typeof options.bufferMaxEntries === 'number' ? options.bufferMaxEntries : MAX_JS_INT + }; + + // Shared global store + var store = options.store || new Store(self, storeOptions); + + // Detect if we have a socket connection + if (host.indexOf('/') !== -1) { + if (port != null && typeof port === 'object') { + options = port; + port = null; + } + } else if (port == null) { + throw MongoError.create({ message: 'port must be specified', driver: true }); + } + + // Get the reconnect option + var reconnect = typeof options.auto_reconnect === 'boolean' ? options.auto_reconnect : true; + reconnect = typeof options.autoReconnect === 'boolean' ? options.autoReconnect : reconnect; + + // Clone options + var clonedOptions = mergeOptions( + {}, + { + host: host, + port: port, + disconnectHandler: store, + cursorFactory: Cursor, + reconnect: reconnect, + emitError: typeof options.emitError === 'boolean' ? options.emitError : true, + size: typeof options.poolSize === 'number' ? options.poolSize : 5, + monitorCommands: + typeof options.monitorCommands === 'boolean' ? options.monitorCommands : false + } + ); + + // Translate any SSL options and other connectivity options + clonedOptions = translateOptions(clonedOptions, options); + + // Socket options + var socketOptions = + options.socketOptions && Object.keys(options.socketOptions).length > 0 + ? options.socketOptions + : options; + + // Translate all the options to the core types + clonedOptions = translateOptions(clonedOptions, socketOptions); + + // Build default client information + clonedOptions.clientInfo = this.clientInfo; + // Do we have an application specific string + if (options.appname) { + clonedOptions.clientInfo.application = { name: options.appname }; + } + + // Define the internal properties + this.s = { + // Create an instance of a server instance from core module + coreTopology: new CServer(clonedOptions), + // Server capabilities + sCapabilities: null, + // Cloned options + clonedOptions: clonedOptions, + // Reconnect + reconnect: clonedOptions.reconnect, + // Emit error + emitError: clonedOptions.emitError, + // Pool size + poolSize: clonedOptions.size, + // Store Options + storeOptions: storeOptions, + // Store + store: store, + // Host + host: host, + // Port + port: port, + // Options + options: options, + // Server Session Pool + sessionPool: null, + // Active client sessions + sessions: new Set(), + // Promise library + promiseLibrary: promiseLibrary || Promise + }; + } + + // Connect + connect(_options, callback) { + var self = this; + if ('function' === typeof _options) (callback = _options), (_options = {}); + if (_options == null) _options = this.s.clonedOptions; + if (!('function' === typeof callback)) callback = null; + _options = Object.assign({}, this.s.clonedOptions, _options); + self.s.options = _options; + + // Update bufferMaxEntries + self.s.storeOptions.bufferMaxEntries = + typeof _options.bufferMaxEntries === 'number' ? _options.bufferMaxEntries : -1; + + // Error handler + var connectErrorHandler = function() { + return function(err) { + // Remove all event handlers + var events = ['timeout', 'error', 'close']; + events.forEach(function(e) { + self.s.coreTopology.removeListener(e, connectHandlers[e]); + }); + + self.s.coreTopology.removeListener('connect', connectErrorHandler); + + // Try to callback + try { + callback(err); + } catch (err) { + process.nextTick(function() { + throw err; + }); + } + }; + }; + + // Actual handler + var errorHandler = function(event) { + return function(err) { + if (event !== 'error') { + self.emit(event, err); + } + }; + }; + + // Error handler + var reconnectHandler = function() { + self.emit('reconnect', self); + self.s.store.execute(); + }; + + // Reconnect failed + var reconnectFailedHandler = function(err) { + self.emit('reconnectFailed', err); + self.s.store.flush(err); + }; + + // Destroy called on topology, perform cleanup + var destroyHandler = function() { + self.s.store.flush(); + }; + + // relay the event + var relay = function(event) { + return function(t, server) { + self.emit(event, t, server); + }; + }; + + // Connect handler + var connectHandler = function() { + // Clear out all the current handlers left over + ['timeout', 'error', 'close', 'destroy'].forEach(function(e) { + self.s.coreTopology.removeAllListeners(e); + }); + + // Set up listeners + self.s.coreTopology.on('timeout', errorHandler('timeout')); + self.s.coreTopology.once('error', errorHandler('error')); + self.s.coreTopology.on('close', errorHandler('close')); + // Only called on destroy + self.s.coreTopology.on('destroy', destroyHandler); + + // Emit open event + self.emit('open', null, self); + + // Return correctly + try { + callback(null, self); + } catch (err) { + process.nextTick(function() { + throw err; + }); + } + }; + + // Set up listeners + var connectHandlers = { + timeout: connectErrorHandler('timeout'), + error: connectErrorHandler('error'), + close: connectErrorHandler('close') + }; + + // Clear out all the current handlers left over + [ + 'timeout', + 'error', + 'close', + 'serverOpening', + 'serverDescriptionChanged', + 'serverHeartbeatStarted', + 'serverHeartbeatSucceeded', + 'serverHeartbeatFailed', + 'serverClosed', + 'topologyOpening', + 'topologyClosed', + 'topologyDescriptionChanged', + 'commandStarted', + 'commandSucceeded', + 'commandFailed' + ].forEach(function(e) { + self.s.coreTopology.removeAllListeners(e); + }); + + // Add the event handlers + self.s.coreTopology.once('timeout', connectHandlers.timeout); + self.s.coreTopology.once('error', connectHandlers.error); + self.s.coreTopology.once('close', connectHandlers.close); + self.s.coreTopology.once('connect', connectHandler); + // Reconnect server + self.s.coreTopology.on('reconnect', reconnectHandler); + self.s.coreTopology.on('reconnectFailed', reconnectFailedHandler); + + // Set up SDAM listeners + self.s.coreTopology.on('serverDescriptionChanged', relay('serverDescriptionChanged')); + self.s.coreTopology.on('serverHeartbeatStarted', relay('serverHeartbeatStarted')); + self.s.coreTopology.on('serverHeartbeatSucceeded', relay('serverHeartbeatSucceeded')); + self.s.coreTopology.on('serverHeartbeatFailed', relay('serverHeartbeatFailed')); + self.s.coreTopology.on('serverOpening', relay('serverOpening')); + self.s.coreTopology.on('serverClosed', relay('serverClosed')); + self.s.coreTopology.on('topologyOpening', relay('topologyOpening')); + self.s.coreTopology.on('topologyClosed', relay('topologyClosed')); + self.s.coreTopology.on('topologyDescriptionChanged', relay('topologyDescriptionChanged')); + self.s.coreTopology.on('commandStarted', relay('commandStarted')); + self.s.coreTopology.on('commandSucceeded', relay('commandSucceeded')); + self.s.coreTopology.on('commandFailed', relay('commandFailed')); + self.s.coreTopology.on('attemptReconnect', relay('attemptReconnect')); + self.s.coreTopology.on('monitoring', relay('monitoring')); + + // Start connection + self.s.coreTopology.connect(_options); + } +} + +Object.defineProperty(Server.prototype, 'poolSize', { + enumerable: true, + get: function() { + return this.s.coreTopology.connections().length; + } +}); + +Object.defineProperty(Server.prototype, 'autoReconnect', { + enumerable: true, + get: function() { + return this.s.reconnect; + } +}); + +Object.defineProperty(Server.prototype, 'host', { + enumerable: true, + get: function() { + return this.s.host; + } +}); + +Object.defineProperty(Server.prototype, 'port', { + enumerable: true, + get: function() { + return this.s.port; + } +}); + +/** + * Server connect event + * + * @event Server#connect + * @type {object} + */ + +/** + * Server close event + * + * @event Server#close + * @type {object} + */ + +/** + * Server reconnect event + * + * @event Server#reconnect + * @type {object} + */ + +/** + * Server error event + * + * @event Server#error + * @type {MongoError} + */ + +/** + * Server timeout event + * + * @event Server#timeout + * @type {object} + */ + +/** + * Server parseError event + * + * @event Server#parseError + * @type {object} + */ + +/** + * An event emitted indicating a command was started, if command monitoring is enabled + * + * @event Server#commandStarted + * @type {object} + */ + +/** + * An event emitted indicating a command succeeded, if command monitoring is enabled + * + * @event Server#commandSucceeded + * @type {object} + */ + +/** + * An event emitted indicating a command failed, if command monitoring is enabled + * + * @event Server#commandFailed + * @type {object} + */ + +module.exports = Server; diff --git a/scripts/2.5/node_modules/mongodb/lib/topologies/topology_base.js b/scripts/2.5/node_modules/mongodb/lib/topologies/topology_base.js new file mode 100644 index 00000000..e74cb9ff --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/topologies/topology_base.js @@ -0,0 +1,438 @@ +'use strict'; + +const EventEmitter = require('events'), + MongoError = require('../core').MongoError, + f = require('util').format, + os = require('os'), + translateReadPreference = require('../utils').translateReadPreference, + ClientSession = require('../core').Sessions.ClientSession; + +// The store of ops +var Store = function(topology, storeOptions) { + var self = this; + var storedOps = []; + storeOptions = storeOptions || { force: false, bufferMaxEntries: -1 }; + + // Internal state + this.s = { + storedOps: storedOps, + storeOptions: storeOptions, + topology: topology + }; + + Object.defineProperty(this, 'length', { + enumerable: true, + get: function() { + return self.s.storedOps.length; + } + }); +}; + +Store.prototype.add = function(opType, ns, ops, options, callback) { + if (this.s.storeOptions.force) { + return callback(MongoError.create({ message: 'db closed by application', driver: true })); + } + + if (this.s.storeOptions.bufferMaxEntries === 0) { + return callback( + MongoError.create({ + message: f( + 'no connection available for operation and number of stored operation > %s', + this.s.storeOptions.bufferMaxEntries + ), + driver: true + }) + ); + } + + if ( + this.s.storeOptions.bufferMaxEntries > 0 && + this.s.storedOps.length > this.s.storeOptions.bufferMaxEntries + ) { + while (this.s.storedOps.length > 0) { + var op = this.s.storedOps.shift(); + op.c( + MongoError.create({ + message: f( + 'no connection available for operation and number of stored operation > %s', + this.s.storeOptions.bufferMaxEntries + ), + driver: true + }) + ); + } + + return; + } + + this.s.storedOps.push({ t: opType, n: ns, o: ops, op: options, c: callback }); +}; + +Store.prototype.addObjectAndMethod = function(opType, object, method, params, callback) { + if (this.s.storeOptions.force) { + return callback(MongoError.create({ message: 'db closed by application', driver: true })); + } + + if (this.s.storeOptions.bufferMaxEntries === 0) { + return callback( + MongoError.create({ + message: f( + 'no connection available for operation and number of stored operation > %s', + this.s.storeOptions.bufferMaxEntries + ), + driver: true + }) + ); + } + + if ( + this.s.storeOptions.bufferMaxEntries > 0 && + this.s.storedOps.length > this.s.storeOptions.bufferMaxEntries + ) { + while (this.s.storedOps.length > 0) { + var op = this.s.storedOps.shift(); + op.c( + MongoError.create({ + message: f( + 'no connection available for operation and number of stored operation > %s', + this.s.storeOptions.bufferMaxEntries + ), + driver: true + }) + ); + } + + return; + } + + this.s.storedOps.push({ t: opType, m: method, o: object, p: params, c: callback }); +}; + +Store.prototype.flush = function(err) { + while (this.s.storedOps.length > 0) { + this.s.storedOps + .shift() + .c( + err || + MongoError.create({ message: f('no connection available for operation'), driver: true }) + ); + } +}; + +var primaryOptions = ['primary', 'primaryPreferred', 'nearest', 'secondaryPreferred']; +var secondaryOptions = ['secondary', 'secondaryPreferred']; + +Store.prototype.execute = function(options) { + options = options || {}; + // Get current ops + var ops = this.s.storedOps; + // Reset the ops + this.s.storedOps = []; + + // Unpack options + var executePrimary = typeof options.executePrimary === 'boolean' ? options.executePrimary : true; + var executeSecondary = + typeof options.executeSecondary === 'boolean' ? options.executeSecondary : true; + + // Execute all the stored ops + while (ops.length > 0) { + var op = ops.shift(); + + if (op.t === 'cursor') { + if (executePrimary && executeSecondary) { + op.o[op.m].apply(op.o, op.p); + } else if ( + executePrimary && + op.o.options && + op.o.options.readPreference && + primaryOptions.indexOf(op.o.options.readPreference.mode) !== -1 + ) { + op.o[op.m].apply(op.o, op.p); + } else if ( + !executePrimary && + executeSecondary && + op.o.options && + op.o.options.readPreference && + secondaryOptions.indexOf(op.o.options.readPreference.mode) !== -1 + ) { + op.o[op.m].apply(op.o, op.p); + } + } else if (op.t === 'auth') { + this.s.topology[op.t].apply(this.s.topology, op.o); + } else { + if (executePrimary && executeSecondary) { + this.s.topology[op.t](op.n, op.o, op.op, op.c); + } else if ( + executePrimary && + op.op && + op.op.readPreference && + primaryOptions.indexOf(op.op.readPreference.mode) !== -1 + ) { + this.s.topology[op.t](op.n, op.o, op.op, op.c); + } else if ( + !executePrimary && + executeSecondary && + op.op && + op.op.readPreference && + secondaryOptions.indexOf(op.op.readPreference.mode) !== -1 + ) { + this.s.topology[op.t](op.n, op.o, op.op, op.c); + } + } + } +}; + +Store.prototype.all = function() { + return this.s.storedOps; +}; + +// Server capabilities +var ServerCapabilities = function(ismaster) { + var setup_get_property = function(object, name, value) { + Object.defineProperty(object, name, { + enumerable: true, + get: function() { + return value; + } + }); + }; + + // Capabilities + var aggregationCursor = false; + var writeCommands = false; + var textSearch = false; + var authCommands = false; + var listCollections = false; + var listIndexes = false; + var maxNumberOfDocsInBatch = ismaster.maxWriteBatchSize || 1000; + var commandsTakeWriteConcern = false; + var commandsTakeCollation = false; + + if (ismaster.minWireVersion >= 0) { + textSearch = true; + } + + if (ismaster.maxWireVersion >= 1) { + aggregationCursor = true; + authCommands = true; + } + + if (ismaster.maxWireVersion >= 2) { + writeCommands = true; + } + + if (ismaster.maxWireVersion >= 3) { + listCollections = true; + listIndexes = true; + } + + if (ismaster.maxWireVersion >= 5) { + commandsTakeWriteConcern = true; + commandsTakeCollation = true; + } + + // If no min or max wire version set to 0 + if (ismaster.minWireVersion == null) { + ismaster.minWireVersion = 0; + } + + if (ismaster.maxWireVersion == null) { + ismaster.maxWireVersion = 0; + } + + // Map up read only parameters + setup_get_property(this, 'hasAggregationCursor', aggregationCursor); + setup_get_property(this, 'hasWriteCommands', writeCommands); + setup_get_property(this, 'hasTextSearch', textSearch); + setup_get_property(this, 'hasAuthCommands', authCommands); + setup_get_property(this, 'hasListCollectionsCommand', listCollections); + setup_get_property(this, 'hasListIndexesCommand', listIndexes); + setup_get_property(this, 'minWireVersion', ismaster.minWireVersion); + setup_get_property(this, 'maxWireVersion', ismaster.maxWireVersion); + setup_get_property(this, 'maxNumberOfDocsInBatch', maxNumberOfDocsInBatch); + setup_get_property(this, 'commandsTakeWriteConcern', commandsTakeWriteConcern); + setup_get_property(this, 'commandsTakeCollation', commandsTakeCollation); +}; + +// Get package.json variable +const driverVersion = require('../../package.json').version, + nodejsversion = f('Node.js %s, %s', process.version, os.endianness()), + type = os.type(), + name = process.platform, + architecture = process.arch, + release = os.release(); + +class TopologyBase extends EventEmitter { + constructor() { + super(); + + // Build default client information + this.clientInfo = { + driver: { + name: 'nodejs', + version: driverVersion + }, + os: { + type: type, + name: name, + architecture: architecture, + version: release + }, + platform: nodejsversion + }; + + this.setMaxListeners(Infinity); + } + + // Sessions related methods + hasSessionSupport() { + return this.logicalSessionTimeoutMinutes != null; + } + + startSession(options, clientOptions) { + const session = new ClientSession(this, this.s.sessionPool, options, clientOptions); + + session.once('ended', () => { + this.s.sessions.delete(session); + }); + + this.s.sessions.add(session); + return session; + } + + endSessions(sessions, callback) { + return this.s.coreTopology.endSessions(sessions, callback); + } + + // Server capabilities + capabilities() { + if (this.s.sCapabilities) return this.s.sCapabilities; + if (this.s.coreTopology.lastIsMaster() == null) return null; + this.s.sCapabilities = new ServerCapabilities(this.s.coreTopology.lastIsMaster()); + return this.s.sCapabilities; + } + + // Command + command(ns, cmd, options, callback) { + this.s.coreTopology.command(ns.toString(), cmd, translateReadPreference(options), callback); + } + + // Insert + insert(ns, ops, options, callback) { + this.s.coreTopology.insert(ns.toString(), ops, options, callback); + } + + // Update + update(ns, ops, options, callback) { + this.s.coreTopology.update(ns.toString(), ops, options, callback); + } + + // Remove + remove(ns, ops, options, callback) { + this.s.coreTopology.remove(ns.toString(), ops, options, callback); + } + + // IsConnected + isConnected(options) { + options = options || {}; + options = translateReadPreference(options); + + return this.s.coreTopology.isConnected(options); + } + + // IsDestroyed + isDestroyed() { + return this.s.coreTopology.isDestroyed(); + } + + // Cursor + cursor(ns, cmd, options) { + options = options || {}; + options = translateReadPreference(options); + options.disconnectHandler = this.s.store; + options.topology = this; + + return this.s.coreTopology.cursor(ns, cmd, options); + } + + lastIsMaster() { + return this.s.coreTopology.lastIsMaster(); + } + + selectServer(selector, options, callback) { + return this.s.coreTopology.selectServer(selector, options, callback); + } + + /** + * Unref all sockets + * @method + */ + unref() { + return this.s.coreTopology.unref(); + } + + /** + * All raw connections + * @method + * @return {array} + */ + connections() { + return this.s.coreTopology.connections(); + } + + close(forceClosed, callback) { + // If we have sessions, we want to individually move them to the session pool, + // and then send a single endSessions call. + this.s.sessions.forEach(session => session.endSession()); + + if (this.s.sessionPool) { + this.s.sessionPool.endAllPooledSessions(); + } + + // We need to wash out all stored processes + if (forceClosed === true) { + this.s.storeOptions.force = forceClosed; + this.s.store.flush(); + } + + this.s.coreTopology.destroy( + { + force: typeof forceClosed === 'boolean' ? forceClosed : false + }, + callback + ); + } +} + +// Properties +Object.defineProperty(TopologyBase.prototype, 'bson', { + enumerable: true, + get: function() { + return this.s.coreTopology.s.bson; + } +}); + +Object.defineProperty(TopologyBase.prototype, 'parserType', { + enumerable: true, + get: function() { + return this.s.coreTopology.parserType; + } +}); + +Object.defineProperty(TopologyBase.prototype, 'logicalSessionTimeoutMinutes', { + enumerable: true, + get: function() { + return this.s.coreTopology.logicalSessionTimeoutMinutes; + } +}); + +Object.defineProperty(TopologyBase.prototype, 'type', { + enumerable: true, + get: function() { + return this.s.coreTopology.type; + } +}); + +exports.Store = Store; +exports.ServerCapabilities = ServerCapabilities; +exports.TopologyBase = TopologyBase; diff --git a/scripts/2.5/node_modules/mongodb/lib/url_parser.js b/scripts/2.5/node_modules/mongodb/lib/url_parser.js new file mode 100644 index 00000000..c0f10b46 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/url_parser.js @@ -0,0 +1,623 @@ +'use strict'; + +const ReadPreference = require('./core').ReadPreference, + parser = require('url'), + f = require('util').format, + Logger = require('./core').Logger, + dns = require('dns'); +const ReadConcern = require('./read_concern'); + +module.exports = function(url, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + let result; + try { + result = parser.parse(url, true); + } catch (e) { + return callback(new Error('URL malformed, cannot be parsed')); + } + + if (result.protocol !== 'mongodb:' && result.protocol !== 'mongodb+srv:') { + return callback(new Error('Invalid schema, expected `mongodb` or `mongodb+srv`')); + } + + if (result.protocol === 'mongodb:') { + return parseHandler(url, options, callback); + } + + // Otherwise parse this as an SRV record + if (result.hostname.split('.').length < 3) { + return callback(new Error('URI does not have hostname, domain name and tld')); + } + + result.domainLength = result.hostname.split('.').length; + + if (result.pathname && result.pathname.match(',')) { + return callback(new Error('Invalid URI, cannot contain multiple hostnames')); + } + + if (result.port) { + return callback(new Error('Ports not accepted with `mongodb+srv` URIs')); + } + + let srvAddress = `_mongodb._tcp.${result.host}`; + dns.resolveSrv(srvAddress, function(err, addresses) { + if (err) return callback(err); + + if (addresses.length === 0) { + return callback(new Error('No addresses found at host')); + } + + for (let i = 0; i < addresses.length; i++) { + if (!matchesParentDomain(addresses[i].name, result.hostname, result.domainLength)) { + return callback(new Error('Server record does not share hostname with parent URI')); + } + } + + let base = result.auth ? `mongodb://${result.auth}@` : `mongodb://`; + let connectionStrings = addresses.map(function(address, i) { + if (i === 0) return `${base}${address.name}:${address.port}`; + else return `${address.name}:${address.port}`; + }); + + let connectionString = connectionStrings.join(',') + '/'; + let connectionStringOptions = []; + + // Add the default database if needed + if (result.path) { + let defaultDb = result.path.slice(1); + if (defaultDb.indexOf('?') !== -1) { + defaultDb = defaultDb.slice(0, defaultDb.indexOf('?')); + } + + connectionString += defaultDb; + } + + // Default to SSL true + if (!options.ssl && !result.search) { + connectionStringOptions.push('ssl=true'); + } else if (!options.ssl && result.search && !result.search.match('ssl')) { + connectionStringOptions.push('ssl=true'); + } + + // Keep original uri options + if (result.search) { + connectionStringOptions.push(result.search.replace('?', '')); + } + + dns.resolveTxt(result.host, function(err, record) { + if (err && err.code !== 'ENODATA') return callback(err); + if (err && err.code === 'ENODATA') record = null; + + if (record) { + if (record.length > 1) { + return callback(new Error('Multiple text records not allowed')); + } + + record = record[0]; + if (record.length > 1) record = record.join(''); + else record = record[0]; + + if (!record.includes('authSource') && !record.includes('replicaSet')) { + return callback(new Error('Text record must only set `authSource` or `replicaSet`')); + } + + connectionStringOptions.push(record); + } + + // Add any options to the connection string + if (connectionStringOptions.length) { + connectionString += `?${connectionStringOptions.join('&')}`; + } + + parseHandler(connectionString, options, callback); + }); + }); +}; + +function matchesParentDomain(srvAddress, parentDomain) { + let regex = /^.*?\./; + let srv = `.${srvAddress.replace(regex, '')}`; + let parent = `.${parentDomain.replace(regex, '')}`; + if (srv.endsWith(parent)) return true; + else return false; +} + +function parseHandler(address, options, callback) { + let result, err; + try { + result = parseConnectionString(address, options); + } catch (e) { + err = e; + } + + return err ? callback(err, null) : callback(null, result); +} + +function parseConnectionString(url, options) { + // Variables + let connection_part = ''; + let auth_part = ''; + let query_string_part = ''; + let dbName = 'admin'; + + // Url parser result + let result = parser.parse(url, true); + if ((result.hostname == null || result.hostname === '') && url.indexOf('.sock') === -1) { + throw new Error('No hostname or hostnames provided in connection string'); + } + + if (result.port === '0') { + throw new Error('Invalid port (zero) with hostname'); + } + + if (!isNaN(parseInt(result.port, 10)) && parseInt(result.port, 10) > 65535) { + throw new Error('Invalid port (larger than 65535) with hostname'); + } + + if ( + result.path && + result.path.length > 0 && + result.path[0] !== '/' && + url.indexOf('.sock') === -1 + ) { + throw new Error('Missing delimiting slash between hosts and options'); + } + + if (result.query) { + for (let name in result.query) { + if (name.indexOf('::') !== -1) { + throw new Error('Double colon in host identifier'); + } + + if (result.query[name] === '') { + throw new Error('Query parameter ' + name + ' is an incomplete value pair'); + } + } + } + + if (result.auth) { + let parts = result.auth.split(':'); + if (url.indexOf(result.auth) !== -1 && parts.length > 2) { + throw new Error('Username with password containing an unescaped colon'); + } + + if (url.indexOf(result.auth) !== -1 && result.auth.indexOf('@') !== -1) { + throw new Error('Username containing an unescaped at-sign'); + } + } + + // Remove query + let clean = url.split('?').shift(); + + // Extract the list of hosts + let strings = clean.split(','); + let hosts = []; + + for (let i = 0; i < strings.length; i++) { + let hostString = strings[i]; + + if (hostString.indexOf('mongodb') !== -1) { + if (hostString.indexOf('@') !== -1) { + hosts.push(hostString.split('@').pop()); + } else { + hosts.push(hostString.substr('mongodb://'.length)); + } + } else if (hostString.indexOf('/') !== -1) { + hosts.push(hostString.split('/').shift()); + } else if (hostString.indexOf('/') === -1) { + hosts.push(hostString.trim()); + } + } + + for (let i = 0; i < hosts.length; i++) { + let r = parser.parse(f('mongodb://%s', hosts[i].trim())); + if (r.path && r.path.indexOf('.sock') !== -1) continue; + if (r.path && r.path.indexOf(':') !== -1) { + // Not connecting to a socket so check for an extra slash in the hostname. + // Using String#split as perf is better than match. + if (r.path.split('/').length > 1 && r.path.indexOf('::') === -1) { + throw new Error('Slash in host identifier'); + } else { + throw new Error('Double colon in host identifier'); + } + } + } + + // If we have a ? mark cut the query elements off + if (url.indexOf('?') !== -1) { + query_string_part = url.substr(url.indexOf('?') + 1); + connection_part = url.substring('mongodb://'.length, url.indexOf('?')); + } else { + connection_part = url.substring('mongodb://'.length); + } + + // Check if we have auth params + if (connection_part.indexOf('@') !== -1) { + auth_part = connection_part.split('@')[0]; + connection_part = connection_part.split('@')[1]; + } + + // Check there is not more than one unescaped slash + if (connection_part.split('/').length > 2) { + throw new Error( + "Unsupported host '" + + connection_part.split('?')[0] + + "', hosts must be URL encoded and contain at most one unencoded slash" + ); + } + + // Check if the connection string has a db + if (connection_part.indexOf('.sock') !== -1) { + if (connection_part.indexOf('.sock/') !== -1) { + dbName = connection_part.split('.sock/')[1]; + // Check if multiple database names provided, or just an illegal trailing backslash + if (dbName.indexOf('/') !== -1) { + if (dbName.split('/').length === 2 && dbName.split('/')[1].length === 0) { + throw new Error('Illegal trailing backslash after database name'); + } + throw new Error('More than 1 database name in URL'); + } + connection_part = connection_part.split( + '/', + connection_part.indexOf('.sock') + '.sock'.length + ); + } + } else if (connection_part.indexOf('/') !== -1) { + // Check if multiple database names provided, or just an illegal trailing backslash + if (connection_part.split('/').length > 2) { + if (connection_part.split('/')[2].length === 0) { + throw new Error('Illegal trailing backslash after database name'); + } + throw new Error('More than 1 database name in URL'); + } + dbName = connection_part.split('/')[1]; + connection_part = connection_part.split('/')[0]; + } + + // URI decode the host information + connection_part = decodeURIComponent(connection_part); + + // Result object + let object = {}; + + // Pick apart the authentication part of the string + let authPart = auth_part || ''; + let auth = authPart.split(':', 2); + + // Decode the authentication URI components and verify integrity + let user = decodeURIComponent(auth[0]); + if (auth[0] !== encodeURIComponent(user)) { + throw new Error('Username contains an illegal unescaped character'); + } + auth[0] = user; + + if (auth[1]) { + let pass = decodeURIComponent(auth[1]); + if (auth[1] !== encodeURIComponent(pass)) { + throw new Error('Password contains an illegal unescaped character'); + } + auth[1] = pass; + } + + // Add auth to final object if we have 2 elements + if (auth.length === 2) object.auth = { user: auth[0], password: auth[1] }; + // if user provided auth options, use that + if (options && options.auth != null) object.auth = options.auth; + + // Variables used for temporary storage + let hostPart; + let urlOptions; + let servers; + let compression; + let serverOptions = { socketOptions: {} }; + let dbOptions = { read_preference_tags: [] }; + let replSetServersOptions = { socketOptions: {} }; + let mongosOptions = { socketOptions: {} }; + // Add server options to final object + object.server_options = serverOptions; + object.db_options = dbOptions; + object.rs_options = replSetServersOptions; + object.mongos_options = mongosOptions; + + // Let's check if we are using a domain socket + if (url.match(/\.sock/)) { + // Split out the socket part + let domainSocket = url.substring( + url.indexOf('mongodb://') + 'mongodb://'.length, + url.lastIndexOf('.sock') + '.sock'.length + ); + // Clean out any auth stuff if any + if (domainSocket.indexOf('@') !== -1) domainSocket = domainSocket.split('@')[1]; + domainSocket = decodeURIComponent(domainSocket); + servers = [{ domain_socket: domainSocket }]; + } else { + // Split up the db + hostPart = connection_part; + // Deduplicate servers + let deduplicatedServers = {}; + + // Parse all server results + servers = hostPart + .split(',') + .map(function(h) { + let _host, _port, ipv6match; + //check if it matches [IPv6]:port, where the port number is optional + if ((ipv6match = /\[([^\]]+)\](?::(.+))?/.exec(h))) { + _host = ipv6match[1]; + _port = parseInt(ipv6match[2], 10) || 27017; + } else { + //otherwise assume it's IPv4, or plain hostname + let hostPort = h.split(':', 2); + _host = hostPort[0] || 'localhost'; + _port = hostPort[1] != null ? parseInt(hostPort[1], 10) : 27017; + // Check for localhost?safe=true style case + if (_host.indexOf('?') !== -1) _host = _host.split(/\?/)[0]; + } + + // No entry returned for duplicate server + if (deduplicatedServers[_host + '_' + _port]) return null; + deduplicatedServers[_host + '_' + _port] = 1; + + // Return the mapped object + return { host: _host, port: _port }; + }) + .filter(function(x) { + return x != null; + }); + } + + // Get the db name + object.dbName = dbName || 'admin'; + // Split up all the options + urlOptions = (query_string_part || '').split(/[&;]/); + // Ugh, we have to figure out which options go to which constructor manually. + urlOptions.forEach(function(opt) { + if (!opt) return; + var splitOpt = opt.split('='), + name = splitOpt[0], + value = splitOpt[1]; + + // Options implementations + switch (name) { + case 'slaveOk': + case 'slave_ok': + serverOptions.slave_ok = value === 'true'; + dbOptions.slaveOk = value === 'true'; + break; + case 'maxPoolSize': + case 'poolSize': + serverOptions.poolSize = parseInt(value, 10); + replSetServersOptions.poolSize = parseInt(value, 10); + break; + case 'appname': + object.appname = decodeURIComponent(value); + break; + case 'autoReconnect': + case 'auto_reconnect': + serverOptions.auto_reconnect = value === 'true'; + break; + case 'ssl': + if (value === 'prefer') { + serverOptions.ssl = value; + replSetServersOptions.ssl = value; + mongosOptions.ssl = value; + break; + } + serverOptions.ssl = value === 'true'; + replSetServersOptions.ssl = value === 'true'; + mongosOptions.ssl = value === 'true'; + break; + case 'sslValidate': + serverOptions.sslValidate = value === 'true'; + replSetServersOptions.sslValidate = value === 'true'; + mongosOptions.sslValidate = value === 'true'; + break; + case 'replicaSet': + case 'rs_name': + replSetServersOptions.rs_name = value; + break; + case 'reconnectWait': + replSetServersOptions.reconnectWait = parseInt(value, 10); + break; + case 'retries': + replSetServersOptions.retries = parseInt(value, 10); + break; + case 'readSecondary': + case 'read_secondary': + replSetServersOptions.read_secondary = value === 'true'; + break; + case 'fsync': + dbOptions.fsync = value === 'true'; + break; + case 'journal': + dbOptions.j = value === 'true'; + break; + case 'safe': + dbOptions.safe = value === 'true'; + break; + case 'nativeParser': + case 'native_parser': + dbOptions.native_parser = value === 'true'; + break; + case 'readConcernLevel': + dbOptions.readConcern = new ReadConcern(value); + break; + case 'connectTimeoutMS': + serverOptions.socketOptions.connectTimeoutMS = parseInt(value, 10); + replSetServersOptions.socketOptions.connectTimeoutMS = parseInt(value, 10); + mongosOptions.socketOptions.connectTimeoutMS = parseInt(value, 10); + break; + case 'socketTimeoutMS': + serverOptions.socketOptions.socketTimeoutMS = parseInt(value, 10); + replSetServersOptions.socketOptions.socketTimeoutMS = parseInt(value, 10); + mongosOptions.socketOptions.socketTimeoutMS = parseInt(value, 10); + break; + case 'w': + dbOptions.w = parseInt(value, 10); + if (isNaN(dbOptions.w)) dbOptions.w = value; + break; + case 'authSource': + dbOptions.authSource = value; + break; + case 'gssapiServiceName': + dbOptions.gssapiServiceName = value; + break; + case 'authMechanism': + if (value === 'GSSAPI') { + // If no password provided decode only the principal + if (object.auth == null) { + let urlDecodeAuthPart = decodeURIComponent(authPart); + if (urlDecodeAuthPart.indexOf('@') === -1) + throw new Error('GSSAPI requires a provided principal'); + object.auth = { user: urlDecodeAuthPart, password: null }; + } else { + object.auth.user = decodeURIComponent(object.auth.user); + } + } else if (value === 'MONGODB-X509') { + object.auth = { user: decodeURIComponent(authPart) }; + } + + // Only support GSSAPI or MONGODB-CR for now + if ( + value !== 'GSSAPI' && + value !== 'MONGODB-X509' && + value !== 'MONGODB-CR' && + value !== 'DEFAULT' && + value !== 'SCRAM-SHA-1' && + value !== 'SCRAM-SHA-256' && + value !== 'PLAIN' + ) + throw new Error( + 'Only DEFAULT, GSSAPI, PLAIN, MONGODB-X509, or SCRAM-SHA-1 is supported by authMechanism' + ); + + // Authentication mechanism + dbOptions.authMechanism = value; + break; + case 'authMechanismProperties': + { + // Split up into key, value pairs + let values = value.split(','); + let o = {}; + // For each value split into key, value + values.forEach(function(x) { + let v = x.split(':'); + o[v[0]] = v[1]; + }); + + // Set all authMechanismProperties + dbOptions.authMechanismProperties = o; + // Set the service name value + if (typeof o.SERVICE_NAME === 'string') dbOptions.gssapiServiceName = o.SERVICE_NAME; + if (typeof o.SERVICE_REALM === 'string') dbOptions.gssapiServiceRealm = o.SERVICE_REALM; + if (typeof o.CANONICALIZE_HOST_NAME === 'string') + dbOptions.gssapiCanonicalizeHostName = + o.CANONICALIZE_HOST_NAME === 'true' ? true : false; + } + break; + case 'wtimeoutMS': + dbOptions.wtimeout = parseInt(value, 10); + break; + case 'readPreference': + if (!ReadPreference.isValid(value)) + throw new Error( + 'readPreference must be either primary/primaryPreferred/secondary/secondaryPreferred/nearest' + ); + dbOptions.readPreference = value; + break; + case 'maxStalenessSeconds': + dbOptions.maxStalenessSeconds = parseInt(value, 10); + break; + case 'readPreferenceTags': + { + // Decode the value + value = decodeURIComponent(value); + // Contains the tag object + let tagObject = {}; + if (value == null || value === '') { + dbOptions.read_preference_tags.push(tagObject); + break; + } + + // Split up the tags + let tags = value.split(/,/); + for (let i = 0; i < tags.length; i++) { + let parts = tags[i].trim().split(/:/); + tagObject[parts[0]] = parts[1]; + } + + // Set the preferences tags + dbOptions.read_preference_tags.push(tagObject); + } + break; + case 'compressors': + { + compression = serverOptions.compression || {}; + let compressors = value.split(','); + if ( + !compressors.every(function(compressor) { + return compressor === 'snappy' || compressor === 'zlib'; + }) + ) { + throw new Error('Compressors must be at least one of snappy or zlib'); + } + + compression.compressors = compressors; + serverOptions.compression = compression; + } + break; + case 'zlibCompressionLevel': + { + compression = serverOptions.compression || {}; + let zlibCompressionLevel = parseInt(value, 10); + if (zlibCompressionLevel < -1 || zlibCompressionLevel > 9) { + throw new Error('zlibCompressionLevel must be an integer between -1 and 9'); + } + + compression.zlibCompressionLevel = zlibCompressionLevel; + serverOptions.compression = compression; + } + break; + case 'retryWrites': + dbOptions.retryWrites = value === 'true'; + break; + case 'minSize': + dbOptions.minSize = parseInt(value, 10); + break; + default: + { + let logger = Logger('URL Parser'); + logger.warn(`${name} is not supported as a connection string option`); + } + break; + } + }); + + // No tags: should be null (not []) + if (dbOptions.read_preference_tags.length === 0) { + dbOptions.read_preference_tags = null; + } + + // Validate if there are an invalid write concern combinations + if ( + (dbOptions.w === -1 || dbOptions.w === 0) && + (dbOptions.journal === true || dbOptions.fsync === true || dbOptions.safe === true) + ) + throw new Error('w set to -1 or 0 cannot be combined with safe/w/journal/fsync'); + + // If no read preference set it to primary + if (!dbOptions.readPreference) { + dbOptions.readPreference = 'primary'; + } + + // make sure that user-provided options are applied with priority + dbOptions = Object.assign(dbOptions, options); + + // Add servers to result + object.servers = servers; + + // Returned parsed object + return object; +} diff --git a/scripts/2.5/node_modules/mongodb/lib/utils.js b/scripts/2.5/node_modules/mongodb/lib/utils.js new file mode 100644 index 00000000..98dee668 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/utils.js @@ -0,0 +1,716 @@ +'use strict'; + +const MongoError = require('./core/error').MongoError; +const ReadPreference = require('./core/topologies/read_preference'); +const WriteConcern = require('./write_concern'); + +var shallowClone = function(obj) { + var copy = {}; + for (var name in obj) copy[name] = obj[name]; + return copy; +}; + +// Figure out the read preference +var translateReadPreference = function(options) { + var r = null; + if (options.readPreference) { + r = options.readPreference; + } else { + return options; + } + + if (typeof r === 'string') { + options.readPreference = new ReadPreference(r); + } else if (r && !(r instanceof ReadPreference) && typeof r === 'object') { + const mode = r.mode || r.preference; + if (mode && typeof mode === 'string') { + options.readPreference = new ReadPreference(mode, r.tags, { + maxStalenessSeconds: r.maxStalenessSeconds + }); + } + } else if (!(r instanceof ReadPreference)) { + throw new TypeError('Invalid read preference: ' + r); + } + + return options; +}; + +// Set simple property +var getSingleProperty = function(obj, name, value) { + Object.defineProperty(obj, name, { + enumerable: true, + get: function() { + return value; + } + }); +}; + +var formatSortValue = (exports.formatSortValue = function(sortDirection) { + var value = ('' + sortDirection).toLowerCase(); + + switch (value) { + case 'ascending': + case 'asc': + case '1': + return 1; + case 'descending': + case 'desc': + case '-1': + return -1; + default: + throw new Error( + 'Illegal sort clause, must be of the form ' + + "[['field1', '(ascending|descending)'], " + + "['field2', '(ascending|descending)']]" + ); + } +}); + +var formattedOrderClause = (exports.formattedOrderClause = function(sortValue) { + var orderBy = {}; + if (sortValue == null) return null; + if (Array.isArray(sortValue)) { + if (sortValue.length === 0) { + return null; + } + + for (var i = 0; i < sortValue.length; i++) { + if (sortValue[i].constructor === String) { + orderBy[sortValue[i]] = 1; + } else { + orderBy[sortValue[i][0]] = formatSortValue(sortValue[i][1]); + } + } + } else if (sortValue != null && typeof sortValue === 'object') { + orderBy = sortValue; + } else if (typeof sortValue === 'string') { + orderBy[sortValue] = 1; + } else { + throw new Error( + 'Illegal sort clause, must be of the form ' + + "[['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]" + ); + } + + return orderBy; +}); + +var checkCollectionName = function checkCollectionName(collectionName) { + if ('string' !== typeof collectionName) { + throw new MongoError('collection name must be a String'); + } + + if (!collectionName || collectionName.indexOf('..') !== -1) { + throw new MongoError('collection names cannot be empty'); + } + + if ( + collectionName.indexOf('$') !== -1 && + collectionName.match(/((^\$cmd)|(oplog\.\$main))/) == null + ) { + throw new MongoError("collection names must not contain '$'"); + } + + if (collectionName.match(/^\.|\.$/) != null) { + throw new MongoError("collection names must not start or end with '.'"); + } + + // Validate that we are not passing 0x00 in the collection name + if (collectionName.indexOf('\x00') !== -1) { + throw new MongoError('collection names cannot contain a null character'); + } +}; + +var handleCallback = function(callback, err, value1, value2) { + try { + if (callback == null) return; + + if (callback) { + return value2 ? callback(err, value1, value2) : callback(err, value1); + } + } catch (err) { + process.nextTick(function() { + throw err; + }); + return false; + } + + return true; +}; + +/** + * Wrap a Mongo error document in an Error instance + * @ignore + * @api private + */ +var toError = function(error) { + if (error instanceof Error) return error; + + var msg = error.err || error.errmsg || error.errMessage || error; + var e = MongoError.create({ message: msg, driver: true }); + + // Get all object keys + var keys = typeof error === 'object' ? Object.keys(error) : []; + + for (var i = 0; i < keys.length; i++) { + try { + e[keys[i]] = error[keys[i]]; + } catch (err) { + // continue + } + } + + return e; +}; + +/** + * @ignore + */ +var normalizeHintField = function normalizeHintField(hint) { + var finalHint = null; + + if (typeof hint === 'string') { + finalHint = hint; + } else if (Array.isArray(hint)) { + finalHint = {}; + + hint.forEach(function(param) { + finalHint[param] = 1; + }); + } else if (hint != null && typeof hint === 'object') { + finalHint = {}; + for (var name in hint) { + finalHint[name] = hint[name]; + } + } + + return finalHint; +}; + +/** + * Create index name based on field spec + * + * @ignore + * @api private + */ +var parseIndexOptions = function(fieldOrSpec) { + var fieldHash = {}; + var indexes = []; + var keys; + + // Get all the fields accordingly + if ('string' === typeof fieldOrSpec) { + // 'type' + indexes.push(fieldOrSpec + '_' + 1); + fieldHash[fieldOrSpec] = 1; + } else if (Array.isArray(fieldOrSpec)) { + fieldOrSpec.forEach(function(f) { + if ('string' === typeof f) { + // [{location:'2d'}, 'type'] + indexes.push(f + '_' + 1); + fieldHash[f] = 1; + } else if (Array.isArray(f)) { + // [['location', '2d'],['type', 1]] + indexes.push(f[0] + '_' + (f[1] || 1)); + fieldHash[f[0]] = f[1] || 1; + } else if (isObject(f)) { + // [{location:'2d'}, {type:1}] + keys = Object.keys(f); + keys.forEach(function(k) { + indexes.push(k + '_' + f[k]); + fieldHash[k] = f[k]; + }); + } else { + // undefined (ignore) + } + }); + } else if (isObject(fieldOrSpec)) { + // {location:'2d', type:1} + keys = Object.keys(fieldOrSpec); + keys.forEach(function(key) { + indexes.push(key + '_' + fieldOrSpec[key]); + fieldHash[key] = fieldOrSpec[key]; + }); + } + + return { + name: indexes.join('_'), + keys: keys, + fieldHash: fieldHash + }; +}; + +var isObject = (exports.isObject = function(arg) { + return '[object Object]' === Object.prototype.toString.call(arg); +}); + +var debugOptions = function(debugFields, options) { + var finaloptions = {}; + debugFields.forEach(function(n) { + finaloptions[n] = options[n]; + }); + + return finaloptions; +}; + +var decorateCommand = function(command, options, exclude) { + for (var name in options) { + if (exclude.indexOf(name) === -1) command[name] = options[name]; + } + + return command; +}; + +var mergeOptions = function(target, source) { + for (var name in source) { + target[name] = source[name]; + } + + return target; +}; + +// Merge options with translation +var translateOptions = function(target, source) { + var translations = { + // SSL translation options + sslCA: 'ca', + sslCRL: 'crl', + sslValidate: 'rejectUnauthorized', + sslKey: 'key', + sslCert: 'cert', + sslPass: 'passphrase', + // SocketTimeout translation options + socketTimeoutMS: 'socketTimeout', + connectTimeoutMS: 'connectionTimeout', + // Replicaset options + replicaSet: 'setName', + rs_name: 'setName', + secondaryAcceptableLatencyMS: 'acceptableLatency', + connectWithNoPrimary: 'secondaryOnlyConnectionAllowed', + // Mongos options + acceptableLatencyMS: 'localThresholdMS' + }; + + for (var name in source) { + if (translations[name]) { + target[translations[name]] = source[name]; + } else { + target[name] = source[name]; + } + } + + return target; +}; + +var filterOptions = function(options, names) { + var filterOptions = {}; + + for (var name in options) { + if (names.indexOf(name) !== -1) filterOptions[name] = options[name]; + } + + // Filtered options + return filterOptions; +}; + +// Write concern keys +var writeConcernKeys = ['w', 'j', 'wtimeout', 'fsync']; + +// Merge the write concern options +var mergeOptionsAndWriteConcern = function(targetOptions, sourceOptions, keys, mergeWriteConcern) { + // Mix in any allowed options + for (var i = 0; i < keys.length; i++) { + if (!targetOptions[keys[i]] && sourceOptions[keys[i]] !== undefined) { + targetOptions[keys[i]] = sourceOptions[keys[i]]; + } + } + + // No merging of write concern + if (!mergeWriteConcern) return targetOptions; + + // Found no write Concern options + var found = false; + for (i = 0; i < writeConcernKeys.length; i++) { + if (targetOptions[writeConcernKeys[i]]) { + found = true; + break; + } + } + + if (!found) { + for (i = 0; i < writeConcernKeys.length; i++) { + if (sourceOptions[writeConcernKeys[i]]) { + targetOptions[writeConcernKeys[i]] = sourceOptions[writeConcernKeys[i]]; + } + } + } + + return targetOptions; +}; + +/** + * Executes the given operation with provided arguments. + * + * This method reduces large amounts of duplication in the entire codebase by providing + * a single point for determining whether callbacks or promises should be used. Additionally + * it allows for a single point of entry to provide features such as implicit sessions, which + * are required by the Driver Sessions specification in the event that a ClientSession is + * not provided + * + * @param {object} topology The topology to execute this operation on + * @param {function} operation The operation to execute + * @param {array} args Arguments to apply the provided operation + * @param {object} [options] Options that modify the behavior of the method + */ +const executeLegacyOperation = (topology, operation, args, options) => { + if (topology == null) { + throw new TypeError('This method requires a valid topology instance'); + } + + if (!Array.isArray(args)) { + throw new TypeError('This method requires an array of arguments to apply'); + } + + options = options || {}; + const Promise = topology.s.promiseLibrary; + let callback = args[args.length - 1]; + + // The driver sessions spec mandates that we implicitly create sessions for operations + // that are not explicitly provided with a session. + let session, opOptions, owner; + if (!options.skipSessions && topology.hasSessionSupport()) { + opOptions = args[args.length - 2]; + if (opOptions == null || opOptions.session == null) { + owner = Symbol(); + session = topology.startSession({ owner }); + const optionsIndex = args.length - 2; + args[optionsIndex] = Object.assign({}, args[optionsIndex], { session: session }); + } else if (opOptions.session && opOptions.session.hasEnded) { + throw new MongoError('Use of expired sessions is not permitted'); + } + } + + const makeExecuteCallback = (resolve, reject) => + function executeCallback(err, result) { + if (session && session.owner === owner && !options.returnsCursor) { + session.endSession(() => { + delete opOptions.session; + if (err) return reject(err); + resolve(result); + }); + } else { + if (err) return reject(err); + resolve(result); + } + }; + + // Execute using callback + if (typeof callback === 'function') { + callback = args.pop(); + const handler = makeExecuteCallback( + result => callback(null, result), + err => callback(err, null) + ); + args.push(handler); + + try { + return operation.apply(null, args); + } catch (e) { + handler(e); + throw e; + } + } + + // Return a Promise + if (args[args.length - 1] != null) { + throw new TypeError('final argument to `executeLegacyOperation` must be a callback'); + } + + return new Promise(function(resolve, reject) { + const handler = makeExecuteCallback(resolve, reject); + args[args.length - 1] = handler; + + try { + return operation.apply(null, args); + } catch (e) { + handler(e); + } + }); +}; + +/** + * Applies retryWrites: true to a command if retryWrites is set on the command's database. + * + * @param {object} target The target command to which we will apply retryWrites. + * @param {object} db The database from which we can inherit a retryWrites value. + */ +function applyRetryableWrites(target, db) { + if (db && db.s.options.retryWrites) { + target.retryWrites = true; + } + + return target; +} + +/** + * Applies a write concern to a command based on well defined inheritance rules, optionally + * detecting support for the write concern in the first place. + * + * @param {Object} target the target command we will be applying the write concern to + * @param {Object} sources sources where we can inherit default write concerns from + * @param {Object} [options] optional settings passed into a command for write concern overrides + * @returns {Object} the (now) decorated target + */ +function applyWriteConcern(target, sources, options) { + options = options || {}; + const db = sources.db; + const coll = sources.collection; + + if (options.session && options.session.inTransaction()) { + // writeConcern is not allowed within a multi-statement transaction + if (target.writeConcern) { + delete target.writeConcern; + } + + return target; + } + + const writeConcern = WriteConcern.fromOptions(options); + if (writeConcern) { + return Object.assign(target, { writeConcern }); + } + + if (coll && coll.writeConcern) { + return Object.assign(target, { writeConcern: Object.assign({}, coll.writeConcern) }); + } + + if (db && db.writeConcern) { + return Object.assign(target, { writeConcern: Object.assign({}, db.writeConcern) }); + } + + return target; +} + +/** + * Resolves a read preference based on well-defined inheritance rules. This method will not only + * determine the read preference (if there is one), but will also ensure the returned value is a + * properly constructed instance of `ReadPreference`. + * + * @param {Collection|Db|MongoClient} parent The parent of the operation on which to determine the read + * preference, used for determining the inherited read preference. + * @param {Object} options The options passed into the method, potentially containing a read preference + * @returns {(ReadPreference|null)} The resolved read preference + */ +function resolveReadPreference(parent, options) { + options = options || {}; + const session = options.session; + + const inheritedReadPreference = parent.readPreference; + + let readPreference; + if (options.readPreference) { + readPreference = ReadPreference.fromOptions(options); + } else if (session && session.inTransaction() && session.transaction.options.readPreference) { + // The transaction’s read preference MUST override all other user configurable read preferences. + readPreference = session.transaction.options.readPreference; + } else if (inheritedReadPreference != null) { + readPreference = inheritedReadPreference; + } else { + throw new Error('No readPreference was provided or inherited.'); + } + + return typeof readPreference === 'string' ? new ReadPreference(readPreference) : readPreference; +} + +/** + * Checks if a given value is a Promise + * + * @param {*} maybePromise + * @return true if the provided value is a Promise + */ +function isPromiseLike(maybePromise) { + return maybePromise && typeof maybePromise.then === 'function'; +} + +/** + * Applies collation to a given command. + * + * @param {object} [command] the command on which to apply collation + * @param {(Cursor|Collection)} [target] target of command + * @param {object} [options] options containing collation settings + */ +function decorateWithCollation(command, target, options) { + const topology = (target.s && target.s.topology) || target.topology; + + if (!topology) { + throw new TypeError('parameter "target" is missing a topology'); + } + + const capabilities = topology.capabilities(); + if (options.collation && typeof options.collation === 'object') { + if (capabilities && capabilities.commandsTakeCollation) { + command.collation = options.collation; + } else { + throw new MongoError(`Current topology does not support collation`); + } + } +} + +/** + * Applies a read concern to a given command. + * + * @param {object} command the command on which to apply the read concern + * @param {Collection} coll the parent collection of the operation calling this method + */ +function decorateWithReadConcern(command, coll, options) { + if (options && options.session && options.session.inTransaction()) { + return; + } + let readConcern = Object.assign({}, command.readConcern || {}); + if (coll.s.readConcern) { + Object.assign(readConcern, coll.s.readConcern); + } + + if (Object.keys(readConcern).length > 0) { + Object.assign(command, { readConcern: readConcern }); + } +} + +const emitProcessWarning = msg => process.emitWarning(msg, 'DeprecationWarning'); +const emitConsoleWarning = msg => console.error(msg); +const emitDeprecationWarning = process.emitWarning ? emitProcessWarning : emitConsoleWarning; + +/** + * Default message handler for generating deprecation warnings. + * + * @param {string} name function name + * @param {string} option option name + * @return {string} warning message + * @ignore + * @api private + */ +function defaultMsgHandler(name, option) { + return `${name} option [${option}] is deprecated and will be removed in a later version.`; +} + +/** + * Deprecates a given function's options. + * + * @param {object} config configuration for deprecation + * @param {string} config.name function name + * @param {Array} config.deprecatedOptions options to deprecate + * @param {number} config.optionsIndex index of options object in function arguments array + * @param {function} [config.msgHandler] optional custom message handler to generate warnings + * @param {function} fn the target function of deprecation + * @return {function} modified function that warns once per deprecated option, and executes original function + * @ignore + * @api private + */ +function deprecateOptions(config, fn) { + if (process.noDeprecation === true) { + return fn; + } + + const msgHandler = config.msgHandler ? config.msgHandler : defaultMsgHandler; + + const optionsWarned = new Set(); + function deprecated() { + const options = arguments[config.optionsIndex]; + + // ensure options is a valid, non-empty object, otherwise short-circuit + if (!isObject(options) || Object.keys(options).length === 0) { + return fn.apply(this, arguments); + } + + config.deprecatedOptions.forEach(deprecatedOption => { + if (options.hasOwnProperty(deprecatedOption) && !optionsWarned.has(deprecatedOption)) { + optionsWarned.add(deprecatedOption); + const msg = msgHandler(config.name, deprecatedOption); + emitDeprecationWarning(msg); + if (this && this.getLogger) { + const logger = this.getLogger(); + if (logger) { + logger.warn(msg); + } + } + } + }); + + return fn.apply(this, arguments); + } + + // These lines copied from https://github.com/nodejs/node/blob/25e5ae41688676a5fd29b2e2e7602168eee4ceb5/lib/internal/util.js#L73-L80 + // The wrapper will keep the same prototype as fn to maintain prototype chain + Object.setPrototypeOf(deprecated, fn); + if (fn.prototype) { + // Setting this (rather than using Object.setPrototype, as above) ensures + // that calling the unwrapped constructor gives an instanceof the wrapped + // constructor. + deprecated.prototype = fn.prototype; + } + + return deprecated; +} + +const SUPPORTS = {}; +// Test asyncIterator support +try { + require('./async/async_iterator'); + SUPPORTS.ASYNC_ITERATOR = true; +} catch (e) { + SUPPORTS.ASYNC_ITERATOR = false; +} + +class MongoDBNamespace { + constructor(db, collection) { + this.db = db; + this.collection = collection; + } + + toString() { + return this.collection ? `${this.db}.${this.collection}` : this.db; + } + + withCollection(collection) { + return new MongoDBNamespace(this.db, collection); + } + + static fromString(namespace) { + if (!namespace) { + throw new Error(`Cannot parse namespace from "${namespace}"`); + } + + const index = namespace.indexOf('.'); + return new MongoDBNamespace(namespace.substring(0, index), namespace.substring(index + 1)); + } +} + +module.exports = { + filterOptions, + mergeOptions, + translateOptions, + shallowClone, + getSingleProperty, + checkCollectionName, + toError, + formattedOrderClause, + parseIndexOptions, + normalizeHintField, + handleCallback, + decorateCommand, + isObject, + debugOptions, + MAX_JS_INT: Number.MAX_SAFE_INTEGER + 1, + mergeOptionsAndWriteConcern, + translateReadPreference, + executeLegacyOperation, + applyRetryableWrites, + applyWriteConcern, + isPromiseLike, + decorateWithCollation, + decorateWithReadConcern, + deprecateOptions, + SUPPORTS, + MongoDBNamespace, + resolveReadPreference +}; diff --git a/scripts/2.5/node_modules/mongodb/lib/write_concern.js b/scripts/2.5/node_modules/mongodb/lib/write_concern.js new file mode 100644 index 00000000..79b0f092 --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/lib/write_concern.js @@ -0,0 +1,66 @@ +'use strict'; + +/** + * The **WriteConcern** class is a class that represents a MongoDB WriteConcern. + * @class + * @property {(number|string)} w The write concern + * @property {number} wtimeout The write concern timeout + * @property {boolean} j The journal write concern + * @property {boolean} fsync The file sync write concern + * @see https://docs.mongodb.com/manual/reference/write-concern/index.html + */ +class WriteConcern { + /** + * Constructs a WriteConcern from the write concern properties. + * @param {(number|string)} [w] The write concern + * @param {number} [wtimeout] The write concern timeout + * @param {boolean} [j] The journal write concern + * @param {boolean} [fsync] The file sync write concern + */ + constructor(w, wtimeout, j, fsync) { + if (w != null) { + this.w = w; + } + if (wtimeout != null) { + this.wtimeout = wtimeout; + } + if (j != null) { + this.j = j; + } + if (fsync != null) { + this.fsync = fsync; + } + } + + /** + * Construct a WriteConcern given an options object. + * + * @param {object} options The options object from which to extract the write concern. + * @return {WriteConcern} + */ + static fromOptions(options) { + if ( + options == null || + (options.writeConcern == null && + options.w == null && + options.wtimeout == null && + options.j == null && + options.fsync == null) + ) { + return; + } + + if (options.writeConcern) { + return new WriteConcern( + options.writeConcern.w, + options.writeConcern.wtimeout, + options.writeConcern.j, + options.writeConcern.fsync + ); + } + + return new WriteConcern(options.w, options.wtimeout, options.j, options.fsync); + } +} + +module.exports = WriteConcern; diff --git a/scripts/2.5/node_modules/mongodb/package.json b/scripts/2.5/node_modules/mongodb/package.json new file mode 100644 index 00000000..ad87330b --- /dev/null +++ b/scripts/2.5/node_modules/mongodb/package.json @@ -0,0 +1,104 @@ +{ + "_from": "mongodb", + "_id": "mongodb@3.3.3", + "_inBundle": false, + "_integrity": "sha512-MdRnoOjstmnrKJsK8PY0PjP6fyF/SBS4R8coxmhsfEU7tQ46/J6j+aSHF2n4c2/H8B+Hc/Klbfp8vggZfI0mmA==", + "_location": "/mongodb", + "_phantomChildren": {}, + "_requested": { + "type": "tag", + "registry": true, + "raw": "mongodb", + "name": "mongodb", + "escapedName": "mongodb", + "rawSpec": "", + "saveSpec": null, + "fetchSpec": "latest" + }, + "_requiredBy": [ + "#USER", + "/" + ], + "_resolved": "https://registry.npmjs.org/mongodb/-/mongodb-3.3.3.tgz", + "_shasum": "509cad2225a1c56c65a331ed73a0d5d4ed5cbe67", + "_spec": "mongodb", + "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/2.5", + "bugs": { + "url": "https://github.com/mongodb/node-mongodb-native/issues" + }, + "bundleDependencies": false, + "dependencies": { + "bson": "^1.1.1", + "require_optional": "^1.0.1", + "safe-buffer": "^5.1.2", + "saslprep": "^1.0.0" + }, + "deprecated": false, + "description": "The official MongoDB driver for Node.js", + "devDependencies": { + "bluebird": "3.5.0", + "chai": "^4.1.1", + "chai-subset": "^1.6.0", + "chalk": "^2.4.2", + "co": "4.6.0", + "coveralls": "^2.11.6", + "eslint": "^4.5.0", + "eslint-plugin-prettier": "^2.2.0", + "istanbul": "^0.4.5", + "jsdoc": "3.5.5", + "lodash.camelcase": "^4.3.0", + "mocha": "5.2.0", + "mocha-sinon": "^2.1.0", + "mongodb-extjson": "^2.1.1", + "mongodb-mock-server": "^1.0.1", + "prettier": "~1.12.0", + "semver": "^5.5.0", + "sinon": "^4.3.0", + "sinon-chai": "^3.2.0", + "snappy": "^6.1.2", + "standard-version": "^4.4.0", + "worker-farm": "^1.5.0", + "wtfnode": "^0.8.0" + }, + "engines": { + "node": ">=4" + }, + "files": [ + "index.js", + "lib" + ], + "homepage": "https://github.com/mongodb/node-mongodb-native", + "keywords": [ + "mongodb", + "driver", + "official" + ], + "license": "Apache-2.0", + "main": "index.js", + "name": "mongodb", + "optionalDependencies": { + "saslprep": "^1.0.0" + }, + "peerOptionalDependencies": { + "kerberos": "^1.1.0", + "mongodb-client-encryption": "^1.0.0", + "mongodb-extjson": "^2.1.2", + "snappy": "^6.1.1", + "bson-ext": "^2.0.0" + }, + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/mongodb/node-mongodb-native.git" + }, + "scripts": { + "atlas": "node ./test/atlas_connectivity_tests.js", + "bench": "node test/driverBench/", + "coverage": "istanbul cover mongodb-test-runner -- -t 60000 test/core test/unit test/functional", + "format": "prettier --print-width 100 --tab-width 2 --single-quote --write 'test/**/*.js' 'lib/**/*.js'", + "generate-evergreen": "node .evergreen/generate_evergreen_tasks.js", + "lint": "eslint lib test", + "release": "standard-version -i HISTORY.md", + "test": "npm run lint && mocha --recursive test/functional test/unit test/core" + }, + "version": "3.3.3" +} diff --git a/scripts/2.5/node_modules/object-inspect/.nycrc b/scripts/2.5/node_modules/object-inspect/.nycrc new file mode 100644 index 00000000..e7064202 --- /dev/null +++ b/scripts/2.5/node_modules/object-inspect/.nycrc @@ -0,0 +1,17 @@ +{ + "all": true, + "check-coverage": true, + "instrumentation": false, + "sourceMap": false, + "reporter": "html", + "lines": 94.94, + "statements": 94.25, + "functions": 96, + "branches": 91.02, + "exclude": [ + "coverage", + "example", + "test", + "test-core-js.js" + ] +} diff --git a/scripts/2.5/node_modules/object-inspect/.travis.yml b/scripts/2.5/node_modules/object-inspect/.travis.yml new file mode 100644 index 00000000..f17c43ba --- /dev/null +++ b/scripts/2.5/node_modules/object-inspect/.travis.yml @@ -0,0 +1,216 @@ +language: node_js +os: + - linux +node_js: + - "10.0" + - "9.11" + - "8.11" + - "7.10" + - "6.14" + - "5.12" + - "4.9" + - "iojs-v3.3" + - "iojs-v2.5" + - "iojs-v1.8" + - "0.12" + - "0.10" + - "0.8" + - "0.6" +before_install: + - 'case "${TRAVIS_NODE_VERSION}" in 0.*) export NPM_CONFIG_STRICT_SSL=false ;; esac' + - 'nvm install-latest-npm' +install: + - 'if [ "${TRAVIS_NODE_VERSION}" = "0.6" ] || [ "${TRAVIS_NODE_VERSION}" = "0.9" ]; then nvm install --latest-npm 0.8 && npm install && nvm use "${TRAVIS_NODE_VERSION}"; else npm install; fi;' +script: + - 'if [ -n "${PRETEST-}" ]; then npm run pretest ; fi' + - 'if [ -n "${POSTTEST-}" ]; then npm run posttest ; fi' + - 'if [ -n "${COVERAGE-}" ]; then npm run coverage ; fi' + - 'if [ -n "${TEST-}" ]; then npm run tests-only ; fi' + - 'if [ -n "${BIGINT-}" ]; then npm run test:bigint ; fi' +sudo: false +env: + - TEST=true +matrix: + fast_finish: true + include: + - node_js: "10.0" + env: BIGINT=true + - node_js: "node" + env: COVERAGE=true + - node_js: "9.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.13" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.12" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v3.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v3.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v3.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.4" + env: TEST=true ALLOW_FAILURE=true + allow_failures: + - os: osx + - env: TEST=true ALLOW_FAILURE=true diff --git a/scripts/2.5/node_modules/object-inspect/LICENSE b/scripts/2.5/node_modules/object-inspect/LICENSE new file mode 100644 index 00000000..ee27ba4b --- /dev/null +++ b/scripts/2.5/node_modules/object-inspect/LICENSE @@ -0,0 +1,18 @@ +This software is released under the MIT license: + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/scripts/2.5/node_modules/object-inspect/example/all.js b/scripts/2.5/node_modules/object-inspect/example/all.js new file mode 100644 index 00000000..a2c4d606 --- /dev/null +++ b/scripts/2.5/node_modules/object-inspect/example/all.js @@ -0,0 +1,19 @@ +var inspect = require('../'); +var Buffer = require('safer-buffer').Buffer; + +var holes = [ 'a', 'b' ]; +holes[4] = 'e', holes[6] = 'g'; +var obj = { + a: 1, + b: [ 3, 4, undefined, null ], + c: undefined, + d: null, + e: { + regex: /^x/i, + buf: Buffer.from('abc'), + holes: holes + }, + now: new Date +}; +obj.self = obj; +console.log(inspect(obj)); diff --git a/scripts/2.5/node_modules/object-inspect/example/circular.js b/scripts/2.5/node_modules/object-inspect/example/circular.js new file mode 100644 index 00000000..1006d0c0 --- /dev/null +++ b/scripts/2.5/node_modules/object-inspect/example/circular.js @@ -0,0 +1,4 @@ +var inspect = require('../'); +var obj = { a: 1, b: [3,4] }; +obj.c = obj; +console.log(inspect(obj)); diff --git a/scripts/2.5/node_modules/object-inspect/example/fn.js b/scripts/2.5/node_modules/object-inspect/example/fn.js new file mode 100644 index 00000000..4c00ba6d --- /dev/null +++ b/scripts/2.5/node_modules/object-inspect/example/fn.js @@ -0,0 +1,3 @@ +var inspect = require('../'); +var obj = [ 1, 2, function f (n) { return n + 5 }, 4 ]; +console.log(inspect(obj)); diff --git a/scripts/2.5/node_modules/object-inspect/example/inspect.js b/scripts/2.5/node_modules/object-inspect/example/inspect.js new file mode 100644 index 00000000..b5ad4d19 --- /dev/null +++ b/scripts/2.5/node_modules/object-inspect/example/inspect.js @@ -0,0 +1,7 @@ +var inspect = require('../'); + +var d = document.createElement('div'); +d.setAttribute('id', 'beep'); +d.innerHTML = 'woooiiiii'; + +console.log(inspect([ d, { a: 3, b : 4, c: [5,6,[7,[8,[9]]]] } ])); diff --git a/scripts/2.5/node_modules/object-inspect/index.js b/scripts/2.5/node_modules/object-inspect/index.js new file mode 100644 index 00000000..62069e3a --- /dev/null +++ b/scripts/2.5/node_modules/object-inspect/index.js @@ -0,0 +1,257 @@ +var hasMap = typeof Map === 'function' && Map.prototype; +var mapSizeDescriptor = Object.getOwnPropertyDescriptor && hasMap ? Object.getOwnPropertyDescriptor(Map.prototype, 'size') : null; +var mapSize = hasMap && mapSizeDescriptor && typeof mapSizeDescriptor.get === 'function' ? mapSizeDescriptor.get : null; +var mapForEach = hasMap && Map.prototype.forEach; +var hasSet = typeof Set === 'function' && Set.prototype; +var setSizeDescriptor = Object.getOwnPropertyDescriptor && hasSet ? Object.getOwnPropertyDescriptor(Set.prototype, 'size') : null; +var setSize = hasSet && setSizeDescriptor && typeof setSizeDescriptor.get === 'function' ? setSizeDescriptor.get : null; +var setForEach = hasSet && Set.prototype.forEach; +var booleanValueOf = Boolean.prototype.valueOf; +var objectToString = Object.prototype.toString; +var bigIntValueOf = typeof BigInt === 'function' ? BigInt.prototype.valueOf : null; + +var inspectCustom = require('./util.inspect').custom; +var inspectSymbol = (inspectCustom && isSymbol(inspectCustom)) ? inspectCustom : null; + +module.exports = function inspect_ (obj, opts, depth, seen) { + if (!opts) opts = {}; + + if (has(opts, 'quoteStyle') && (opts.quoteStyle !== 'single' && opts.quoteStyle !== 'double')) { + throw new TypeError('option "quoteStyle" must be "single" or "double"'); + } + + if (typeof obj === 'undefined') { + return 'undefined'; + } + if (obj === null) { + return 'null'; + } + if (typeof obj === 'boolean') { + return obj ? 'true' : 'false'; + } + + if (typeof obj === 'string') { + return inspectString(obj, opts); + } + if (typeof obj === 'number') { + if (obj === 0) { + return Infinity / obj > 0 ? '0' : '-0'; + } + return String(obj); + } + if (typeof obj === 'bigint') { + return String(obj) + 'n'; + } + + var maxDepth = typeof opts.depth === 'undefined' ? 5 : opts.depth; + if (typeof depth === 'undefined') depth = 0; + if (depth >= maxDepth && maxDepth > 0 && typeof obj === 'object') { + return '[Object]'; + } + + if (typeof seen === 'undefined') seen = []; + else if (indexOf(seen, obj) >= 0) { + return '[Circular]'; + } + + function inspect (value, from) { + if (from) { + seen = seen.slice(); + seen.push(from); + } + return inspect_(value, opts, depth + 1, seen); + } + + if (typeof obj === 'function') { + var name = nameOf(obj); + return '[Function' + (name ? ': ' + name : '') + ']'; + } + if (isSymbol(obj)) { + var symString = Symbol.prototype.toString.call(obj); + return typeof obj === 'object' ? markBoxed(symString) : symString; + } + if (isElement(obj)) { + var s = '<' + String(obj.nodeName).toLowerCase(); + var attrs = obj.attributes || []; + for (var i = 0; i < attrs.length; i++) { + s += ' ' + attrs[i].name + '=' + wrapQuotes(quote(attrs[i].value), 'double', opts); + } + s += '>'; + if (obj.childNodes && obj.childNodes.length) s += '...'; + s += ''; + return s; + } + if (isArray(obj)) { + if (obj.length === 0) return '[]'; + return '[ ' + arrObjKeys(obj, inspect).join(', ') + ' ]'; + } + if (isError(obj)) { + var parts = arrObjKeys(obj, inspect); + if (parts.length === 0) return '[' + String(obj) + ']'; + return '{ [' + String(obj) + '] ' + parts.join(', ') + ' }'; + } + if (typeof obj === 'object') { + if (inspectSymbol && typeof obj[inspectSymbol] === 'function') { + return obj[inspectSymbol](); + } else if (typeof obj.inspect === 'function') { + return obj.inspect(); + } + } + if (isMap(obj)) { + var parts = []; + mapForEach.call(obj, function (value, key) { + parts.push(inspect(key, obj) + ' => ' + inspect(value, obj)); + }); + return collectionOf('Map', mapSize.call(obj), parts); + } + if (isSet(obj)) { + var parts = []; + setForEach.call(obj, function (value ) { + parts.push(inspect(value, obj)); + }); + return collectionOf('Set', setSize.call(obj), parts); + } + if (isNumber(obj)) { + return markBoxed(inspect(Number(obj))); + } + if (isBigInt(obj)) { + return markBoxed(inspect(bigIntValueOf.call(obj))); + } + if (isBoolean(obj)) { + return markBoxed(booleanValueOf.call(obj)); + } + if (isString(obj)) { + return markBoxed(inspect(String(obj))); + } + if (!isDate(obj) && !isRegExp(obj)) { + var xs = arrObjKeys(obj, inspect); + if (xs.length === 0) return '{}'; + return '{ ' + xs.join(', ') + ' }'; + } + return String(obj); +}; + +function wrapQuotes (s, defaultStyle, opts) { + var quoteChar = (opts.quoteStyle || defaultStyle) === 'double' ? '"' : "'"; + return quoteChar + s + quoteChar; +} + +function quote (s) { + return String(s).replace(/"/g, '"'); +} + +function isArray (obj) { return toStr(obj) === '[object Array]'; } +function isDate (obj) { return toStr(obj) === '[object Date]'; } +function isRegExp (obj) { return toStr(obj) === '[object RegExp]'; } +function isError (obj) { return toStr(obj) === '[object Error]'; } +function isSymbol (obj) { return toStr(obj) === '[object Symbol]'; } +function isString (obj) { return toStr(obj) === '[object String]'; } +function isNumber (obj) { return toStr(obj) === '[object Number]'; } +function isBigInt (obj) { return toStr(obj) === '[object BigInt]'; } +function isBoolean (obj) { return toStr(obj) === '[object Boolean]'; } + +var hasOwn = Object.prototype.hasOwnProperty || function (key) { return key in this; }; +function has (obj, key) { + return hasOwn.call(obj, key); +} + +function toStr (obj) { + return objectToString.call(obj); +} + +function nameOf (f) { + if (f.name) return f.name; + var m = String(f).match(/^function\s*([\w$]+)/); + if (m) return m[1]; +} + +function indexOf (xs, x) { + if (xs.indexOf) return xs.indexOf(x); + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; +} + +function isMap (x) { + if (!mapSize) { + return false; + } + try { + mapSize.call(x); + try { + setSize.call(x); + } catch (s) { + return true; + } + return x instanceof Map; // core-js workaround, pre-v2.5.0 + } catch (e) {} + return false; +} + +function isSet (x) { + if (!setSize) { + return false; + } + try { + setSize.call(x); + try { + mapSize.call(x); + } catch (m) { + return true; + } + return x instanceof Set; // core-js workaround, pre-v2.5.0 + } catch (e) {} + return false; +} + +function isElement (x) { + if (!x || typeof x !== 'object') return false; + if (typeof HTMLElement !== 'undefined' && x instanceof HTMLElement) { + return true; + } + return typeof x.nodeName === 'string' + && typeof x.getAttribute === 'function' + ; +} + +function inspectString (str, opts) { + var s = str.replace(/(['\\])/g, '\\$1').replace(/[\x00-\x1f]/g, lowbyte); + return wrapQuotes(s, 'single', opts); +} + +function lowbyte (c) { + var n = c.charCodeAt(0); + var x = { 8: 'b', 9: 't', 10: 'n', 12: 'f', 13: 'r' }[n]; + if (x) return '\\' + x; + return '\\x' + (n < 0x10 ? '0' : '') + n.toString(16); +} + +function markBoxed (str) { + return 'Object(' + str + ')'; +} + +function collectionOf (type, size, entries) { + return type + ' (' + size + ') {' + entries.join(', ') + '}'; +} + +function arrObjKeys (obj, inspect) { + var isArr = isArray(obj); + var xs = []; + if (isArr) { + xs.length = obj.length; + for (var i = 0; i < obj.length; i++) { + xs[i] = has(obj, i) ? inspect(obj[i], obj) : ''; + } + } + for (var key in obj) { + if (!has(obj, key)) continue; + if (isArr && String(Number(key)) === key && key < obj.length) continue; + if (/[^\w$]/.test(key)) { + xs.push(inspect(key, obj) + ': ' + inspect(obj[key], obj)); + } else { + xs.push(key + ': ' + inspect(obj[key], obj)); + } + } + return xs; +} diff --git a/scripts/2.5/node_modules/object-inspect/package.json b/scripts/2.5/node_modules/object-inspect/package.json new file mode 100644 index 00000000..fe4e997e --- /dev/null +++ b/scripts/2.5/node_modules/object-inspect/package.json @@ -0,0 +1,84 @@ +{ + "_from": "object-inspect@^1.6.0", + "_id": "object-inspect@1.6.0", + "_inBundle": false, + "_integrity": "sha512-GJzfBZ6DgDAmnuaM3104jR4s1Myxr3Y3zfIyN4z3UdqN69oSRacNK8UhnobDdC+7J2AHCjGwxQubNJfE70SXXQ==", + "_location": "/object-inspect", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "object-inspect@^1.6.0", + "name": "object-inspect", + "escapedName": "object-inspect", + "rawSpec": "^1.6.0", + "saveSpec": null, + "fetchSpec": "^1.6.0" + }, + "_requiredBy": [ + "/es-abstract" + ], + "_resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.6.0.tgz", + "_shasum": "c70b6cbf72f274aab4c34c0c82f5167bf82cf15b", + "_spec": "object-inspect@^1.6.0", + "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/2.5/node_modules/es-abstract", + "author": { + "name": "James Halliday", + "email": "mail@substack.net", + "url": "http://substack.net" + }, + "browser": { + "./util.inspect.js": false + }, + "bugs": { + "url": "https://github.com/substack/object-inspect/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "string representations of objects in node and the browser", + "devDependencies": { + "core-js": "^2.5.5", + "nyc": "^10.3.2", + "tape": "^4.9.0" + }, + "homepage": "https://github.com/substack/object-inspect", + "keywords": [ + "inspect", + "util.inspect", + "object", + "stringify", + "pretty" + ], + "license": "MIT", + "main": "index.js", + "name": "object-inspect", + "repository": { + "type": "git", + "url": "git://github.com/substack/object-inspect.git" + }, + "scripts": { + "coverage": "nyc npm run tests-only", + "posttest": "npm run test:bigint", + "pretests-only": "node test-core-js", + "test": "npm run tests-only", + "test:bigint": "node --harmony-bigint test/bigint", + "tests-only": "tape test/*.js" + }, + "testling": { + "files": [ + "test/*.js", + "test/browser/*.js" + ], + "browsers": [ + "ie/6..latest", + "chrome/latest", + "firefox/latest", + "safari/latest", + "opera/latest", + "iphone/latest", + "ipad/latest", + "android/latest" + ] + }, + "version": "1.6.0" +} diff --git a/scripts/2.5/node_modules/object-inspect/readme.markdown b/scripts/2.5/node_modules/object-inspect/readme.markdown new file mode 100644 index 00000000..744eeb59 --- /dev/null +++ b/scripts/2.5/node_modules/object-inspect/readme.markdown @@ -0,0 +1,61 @@ +# object-inspect + +string representations of objects in node and the browser + +[![testling badge](https://ci.testling.com/substack/object-inspect.png)](https://ci.testling.com/substack/object-inspect) + +[![build status](https://secure.travis-ci.org/substack/object-inspect.png)](http://travis-ci.org/substack/object-inspect) + +# example + +## circular + +``` js +var inspect = require('object-inspect'); +var obj = { a: 1, b: [3,4] }; +obj.c = obj; +console.log(inspect(obj)); +``` + +## dom element + +``` js +var inspect = require('object-inspect'); + +var d = document.createElement('div'); +d.setAttribute('id', 'beep'); +d.innerHTML = 'woooiiiii'; + +console.log(inspect([ d, { a: 3, b : 4, c: [5,6,[7,[8,[9]]]] } ])); +``` + +output: + +``` +[
...
, { a: 3, b: 4, c: [ 5, 6, [ 7, [ 8, [ ... ] ] ] ] } ] +``` + +# methods + +``` js +var inspect = require('object-inspect') +``` + +## var s = inspect(obj, opts={}) + +Return a string `s` with the string representation of `obj` up to a depth of `opts.depth`. + +Additional options: + - `quoteStyle`: must be "single" or "double", if present + +# install + +With [npm](https://npmjs.org) do: + +``` +npm install object-inspect +``` + +# license + +MIT diff --git a/scripts/2.5/node_modules/object-inspect/test-core-js.js b/scripts/2.5/node_modules/object-inspect/test-core-js.js new file mode 100644 index 00000000..12c4e2ae --- /dev/null +++ b/scripts/2.5/node_modules/object-inspect/test-core-js.js @@ -0,0 +1,16 @@ +'use strict'; + +require('core-js'); + +var inspect = require('./'); +var test = require('tape'); + +test('Maps', function (t) { + t.equal(inspect(new Map([[1, 2]])), 'Map (1) {1 => 2}'); + t.end(); +}); + +test('Sets', function (t) { + t.equal(inspect(new Set([[1, 2]])), 'Set (1) {[ 1, 2 ]}'); + t.end(); +}); diff --git a/scripts/2.5/node_modules/object-inspect/test/bigint.js b/scripts/2.5/node_modules/object-inspect/test/bigint.js new file mode 100644 index 00000000..c9d918bf --- /dev/null +++ b/scripts/2.5/node_modules/object-inspect/test/bigint.js @@ -0,0 +1,30 @@ +var inspect = require('../'); +var test = require('tape'); + +test('bigint', { skip: typeof BigInt === 'undefined' }, function (t) { + t.test('primitives', function (st) { + st.plan(3); + + st.equal(inspect(BigInt(-256)), '-256n'); + st.equal(inspect(BigInt(0)), '0n'); + st.equal(inspect(BigInt(256)), '256n'); + }); + + t.test('objects', function (st) { + st.plan(3); + + st.equal(inspect(Object(BigInt(-256))), 'Object(-256n)'); + st.equal(inspect(Object(BigInt(0))), 'Object(0n)'); + st.equal(inspect(Object(BigInt(256))), 'Object(256n)'); + }); + + t.test('syntactic primitives', function (st) { + st.plan(3); + + st.equal(inspect(Function('return -256n')()), '-256n'); + st.equal(inspect(Function('return 0n')()), '0n'); + st.equal(inspect(Function('return 256n')()), '256n'); + }); + + t.end(); +}); diff --git a/scripts/2.5/node_modules/object-inspect/test/browser/dom.js b/scripts/2.5/node_modules/object-inspect/test/browser/dom.js new file mode 100644 index 00000000..18a3d709 --- /dev/null +++ b/scripts/2.5/node_modules/object-inspect/test/browser/dom.js @@ -0,0 +1,15 @@ +var inspect = require('../../'); +var test = require('tape'); + +test('dom element', function (t) { + t.plan(1); + + var d = document.createElement('div'); + d.setAttribute('id', 'beep'); + d.innerHTML = 'woooiiiii'; + + t.equal( + inspect([ d, { a: 3, b : 4, c: [5,6,[7,[8,[9]]]] } ]), + '[
...
, { a: 3, b: 4, c: [ 5, 6, [ 7, [ 8, [Object] ] ] ] } ]' + ); +}); diff --git a/scripts/2.5/node_modules/object-inspect/test/circular.js b/scripts/2.5/node_modules/object-inspect/test/circular.js new file mode 100644 index 00000000..28598a7f --- /dev/null +++ b/scripts/2.5/node_modules/object-inspect/test/circular.js @@ -0,0 +1,9 @@ +var inspect = require('../'); +var test = require('tape'); + +test('circular', function (t) { + t.plan(1); + var obj = { a: 1, b: [3,4] }; + obj.c = obj; + t.equal(inspect(obj), '{ a: 1, b: [ 3, 4 ], c: [Circular] }'); +}); diff --git a/scripts/2.5/node_modules/object-inspect/test/deep.js b/scripts/2.5/node_modules/object-inspect/test/deep.js new file mode 100644 index 00000000..a8dbb58f --- /dev/null +++ b/scripts/2.5/node_modules/object-inspect/test/deep.js @@ -0,0 +1,9 @@ +var inspect = require('../'); +var test = require('tape'); + +test('deep', function (t) { + t.plan(2); + var obj = [ [ [ [ [ [ 500 ] ] ] ] ] ]; + t.equal(inspect(obj), '[ [ [ [ [ [Object] ] ] ] ] ]'); + t.equal(inspect(obj, { depth: 2 }), '[ [ [Object] ] ]'); +}); diff --git a/scripts/2.5/node_modules/object-inspect/test/element.js b/scripts/2.5/node_modules/object-inspect/test/element.js new file mode 100644 index 00000000..a36f4656 --- /dev/null +++ b/scripts/2.5/node_modules/object-inspect/test/element.js @@ -0,0 +1,53 @@ +var inspect = require('../'); +var test = require('tape'); + +test('element', function (t) { + t.plan(3); + var elem = { + nodeName: 'div', + attributes: [ { name: 'class', value: 'row' } ], + getAttribute: function (key) {}, + childNodes: [] + }; + var obj = [ 1, elem, 3 ]; + t.deepEqual(inspect(obj), '[ 1,
, 3 ]'); + t.deepEqual(inspect(obj, { quoteStyle: 'single' }), "[ 1,
, 3 ]"); + t.deepEqual(inspect(obj, { quoteStyle: 'double' }), '[ 1,
, 3 ]'); +}); + +test('element no attr', function (t) { + t.plan(1); + var elem = { + nodeName: 'div', + getAttribute: function (key) {}, + childNodes: [] + }; + var obj = [ 1, elem, 3 ]; + t.deepEqual(inspect(obj), '[ 1,
, 3 ]'); +}); + +test('element with contents', function (t) { + t.plan(1); + var elem = { + nodeName: 'div', + getAttribute: function (key) {}, + childNodes: [ { nodeName: 'b' } ] + }; + var obj = [ 1, elem, 3 ]; + t.deepEqual(inspect(obj), '[ 1,
...
, 3 ]'); +}); + +test('element instance', function (t) { + t.plan(1); + var h = global.HTMLElement; + global.HTMLElement = function (name, attr) { + this.nodeName = name; + this.attributes = attr; + }; + global.HTMLElement.prototype.getAttribute = function () {}; + + var elem = new(global.HTMLElement)('div', []); + var obj = [ 1, elem, 3 ]; + t.deepEqual(inspect(obj), '[ 1,
, 3 ]'); + global.HTMLElement = h; +}); diff --git a/scripts/2.5/node_modules/object-inspect/test/err.js b/scripts/2.5/node_modules/object-inspect/test/err.js new file mode 100644 index 00000000..0f313438 --- /dev/null +++ b/scripts/2.5/node_modules/object-inspect/test/err.js @@ -0,0 +1,29 @@ +var inspect = require('../'); +var test = require('tape'); + +test('type error', function (t) { + t.plan(1); + var aerr = new TypeError; + aerr.foo = 555; + aerr.bar = [1,2,3]; + + var berr = new TypeError('tuv'); + berr.baz = 555; + + var cerr = new SyntaxError; + cerr.message = 'whoa'; + cerr['a-b'] = 5; + + var obj = [ + new TypeError, + new TypeError('xxx'), + aerr, berr, cerr + ]; + t.equal(inspect(obj), '[ ' + [ + '[TypeError]', + '[TypeError: xxx]', + '{ [TypeError] foo: 555, bar: [ 1, 2, 3 ] }', + '{ [TypeError: tuv] baz: 555 }', + '{ [SyntaxError: whoa] message: \'whoa\', \'a-b\': 5 }' + ].join(', ') + ' ]'); +}); diff --git a/scripts/2.5/node_modules/object-inspect/test/fn.js b/scripts/2.5/node_modules/object-inspect/test/fn.js new file mode 100644 index 00000000..c7d5712b --- /dev/null +++ b/scripts/2.5/node_modules/object-inspect/test/fn.js @@ -0,0 +1,28 @@ +var inspect = require('../'); +var test = require('tape'); + +test('function', function (t) { + t.plan(1); + var obj = [ 1, 2, function f (n) {}, 4 ]; + t.equal(inspect(obj), '[ 1, 2, [Function: f], 4 ]'); +}); + +test('function name', function (t) { + t.plan(1); + var f = (function () { + return function () {}; + }()); + f.toString = function () { return 'function xxx () {}' }; + var obj = [ 1, 2, f, 4 ]; + t.equal(inspect(obj), '[ 1, 2, [Function: xxx], 4 ]'); +}); + +test('anon function', function (t) { + var f = (function () { + return function () {}; + }()); + var obj = [ 1, 2, f, 4 ]; + t.equal(inspect(obj), '[ 1, 2, [Function], 4 ]'); + + t.end(); +}); diff --git a/scripts/2.5/node_modules/object-inspect/test/has.js b/scripts/2.5/node_modules/object-inspect/test/has.js new file mode 100644 index 00000000..e1970b31 --- /dev/null +++ b/scripts/2.5/node_modules/object-inspect/test/has.js @@ -0,0 +1,31 @@ +var inspect = require('../'); +var test = require('tape'); + +var withoutProperty = function (object, property, fn) { + var original; + if (Object.getOwnPropertyDescriptor) { + original = Object.getOwnPropertyDescriptor(object, property); + } else { + original = object[property]; + } + delete object[property]; + try { + fn(); + } finally { + if (Object.getOwnPropertyDescriptor) { + Object.defineProperty(object, property, original); + } else { + object[property] = original; + } + } +}; + +test('when Object#hasOwnProperty is deleted', function (t) { + t.plan(1); + var arr = [1, , 3]; + Array.prototype[1] = 2; // this is needed to account for "in" vs "hasOwnProperty" + withoutProperty(Object.prototype, 'hasOwnProperty', function () { + t.equal(inspect(arr), '[ 1, , 3 ]'); + }); + delete Array.prototype[1]; +}); diff --git a/scripts/2.5/node_modules/object-inspect/test/holes.js b/scripts/2.5/node_modules/object-inspect/test/holes.js new file mode 100644 index 00000000..ae54de46 --- /dev/null +++ b/scripts/2.5/node_modules/object-inspect/test/holes.js @@ -0,0 +1,15 @@ +var test = require('tape'); +var inspect = require('../'); + +var xs = [ 'a', 'b' ]; +xs[5] = 'f'; +xs[7] = 'j'; +xs[8] = 'k'; + +test('holes', function (t) { + t.plan(1); + t.equal( + inspect(xs), + "[ 'a', 'b', , , , 'f', , 'j', 'k' ]" + ); +}); diff --git a/scripts/2.5/node_modules/object-inspect/test/inspect.js b/scripts/2.5/node_modules/object-inspect/test/inspect.js new file mode 100644 index 00000000..12e231af --- /dev/null +++ b/scripts/2.5/node_modules/object-inspect/test/inspect.js @@ -0,0 +1,8 @@ +var inspect = require('../'); +var test = require('tape'); + +test('inspect', function (t) { + t.plan(1); + var obj = [ { inspect: function () { return '!XYZ¡' } }, [] ]; + t.equal(inspect(obj), '[ !XYZ¡, [] ]'); +}); diff --git a/scripts/2.5/node_modules/object-inspect/test/lowbyte.js b/scripts/2.5/node_modules/object-inspect/test/lowbyte.js new file mode 100644 index 00000000..debd59cb --- /dev/null +++ b/scripts/2.5/node_modules/object-inspect/test/lowbyte.js @@ -0,0 +1,12 @@ +var test = require('tape'); +var inspect = require('../'); + +var obj = { x: 'a\r\nb', y: '\5! \x1f \022' }; + +test('interpolate low bytes', function (t) { + t.plan(1); + t.equal( + inspect(obj), + "{ x: 'a\\r\\nb', y: '\\x05! \\x1f \\x12' }" + ); +}); diff --git a/scripts/2.5/node_modules/object-inspect/test/number.js b/scripts/2.5/node_modules/object-inspect/test/number.js new file mode 100644 index 00000000..448304e5 --- /dev/null +++ b/scripts/2.5/node_modules/object-inspect/test/number.js @@ -0,0 +1,12 @@ +var inspect = require('../'); +var test = require('tape'); + +test('negative zero', function (t) { + t.equal(inspect(0), '0', 'inspect(0) === "0"'); + t.equal(inspect(Object(0)), 'Object(0)', 'inspect(Object(0)) === "Object(0)"'); + + t.equal(inspect(-0), '-0', 'inspect(-0) === "-0"'); + t.equal(inspect(Object(-0)), 'Object(-0)', 'inspect(Object(-0)) === "Object(-0)"'); + + t.end(); +}); diff --git a/scripts/2.5/node_modules/object-inspect/test/quoteStyle.js b/scripts/2.5/node_modules/object-inspect/test/quoteStyle.js new file mode 100644 index 00000000..ae4d734b --- /dev/null +++ b/scripts/2.5/node_modules/object-inspect/test/quoteStyle.js @@ -0,0 +1,17 @@ +'use strict'; + +var inspect = require('../'); +var test = require('tape'); + +test('quoteStyle option', function (t) { + t['throws'](function () { inspect(null, { quoteStyle: false }); }, 'false is not a valid value'); + t['throws'](function () { inspect(null, { quoteStyle: true }); }, 'true is not a valid value'); + t['throws'](function () { inspect(null, { quoteStyle: '' }); }, '"" is not a valid value'); + t['throws'](function () { inspect(null, { quoteStyle: {} }); }, '{} is not a valid value'); + t['throws'](function () { inspect(null, { quoteStyle: [] }); }, '[] is not a valid value'); + t['throws'](function () { inspect(null, { quoteStyle: 42 }); }, '42 is not a valid value'); + t['throws'](function () { inspect(null, { quoteStyle: NaN }); }, 'NaN is not a valid value'); + t['throws'](function () { inspect(null, { quoteStyle: function () {} }); }, 'a function is not a valid value'); + + t.end(); +}); diff --git a/scripts/2.5/node_modules/object-inspect/test/undef.js b/scripts/2.5/node_modules/object-inspect/test/undef.js new file mode 100644 index 00000000..833238f8 --- /dev/null +++ b/scripts/2.5/node_modules/object-inspect/test/undef.js @@ -0,0 +1,12 @@ +var test = require('tape'); +var inspect = require('../'); + +var obj = { a: 1, b: [ 3, 4, undefined, null ], c: undefined, d: null }; + +test('undef and null', function (t) { + t.plan(1); + t.equal( + inspect(obj), + '{ a: 1, b: [ 3, 4, undefined, null ], c: undefined, d: null }' + ); +}); diff --git a/scripts/2.5/node_modules/object-inspect/test/values.js b/scripts/2.5/node_modules/object-inspect/test/values.js new file mode 100644 index 00000000..3e1954ba --- /dev/null +++ b/scripts/2.5/node_modules/object-inspect/test/values.js @@ -0,0 +1,136 @@ +var inspect = require('../'); +var test = require('tape'); + +test('values', function (t) { + t.plan(1); + var obj = [ {}, [], { 'a-b': 5 } ]; + t.equal(inspect(obj), '[ {}, [], { \'a-b\': 5 } ]'); +}); + +test('arrays with properties', function (t) { + t.plan(1); + var arr = [3]; + arr.foo = 'bar'; + var obj = [1, 2, arr]; + obj.baz = 'quux'; + obj.index = -1; + t.equal(inspect(obj), '[ 1, 2, [ 3, foo: \'bar\' ], baz: \'quux\', index: -1 ]'); +}); + +test('has', function (t) { + t.plan(1); + var has = Object.prototype.hasOwnProperty; + delete Object.prototype.hasOwnProperty; + t.equal(inspect({ a: 1, b: 2 }), '{ a: 1, b: 2 }'); + Object.prototype.hasOwnProperty = has; +}); + +test('indexOf seen', function (t) { + t.plan(1); + var xs = [ 1, 2, 3, {} ]; + xs.push(xs); + + var seen = []; + seen.indexOf = undefined; + + t.equal( + inspect(xs, {}, 0, seen), + '[ 1, 2, 3, {}, [Circular] ]' + ); +}); + +test('seen seen', function (t) { + t.plan(1); + var xs = [ 1, 2, 3 ]; + + var seen = [ xs ]; + seen.indexOf = undefined; + + t.equal( + inspect(xs, {}, 0, seen), + '[Circular]' + ); +}); + +test('seen seen seen', function (t) { + t.plan(1); + var xs = [ 1, 2, 3 ]; + + var seen = [ 5, xs ]; + seen.indexOf = undefined; + + t.equal( + inspect(xs, {}, 0, seen), + '[Circular]' + ); +}); + +test('symbols', { skip: typeof Symbol !== 'function' }, function (t) { + var sym = Symbol('foo'); + t.equal(inspect(sym), 'Symbol(foo)', 'Symbol("foo") should be "Symbol(foo)"'); + t.equal(inspect(Object(sym)), 'Object(Symbol(foo))', 'Object(Symbol("foo")) should be "Object(Symbol(foo))"'); + t.end(); +}); + +test('Map', { skip: typeof Map !== 'function' }, function (t) { + var map = new Map(); + map.set({ a: 1 }, ['b']); + map.set(3, NaN); + var expectedString = 'Map (2) {' + inspect({ a: 1 }) + ' => ' + inspect(['b']) + ', 3 => NaN}'; + t.equal(inspect(map), expectedString, 'new Map([[{ a: 1 }, ["b"]], [3, NaN]]) should show size and contents'); + t.equal(inspect(new Map()), 'Map (0) {}', 'empty Map should show as empty'); + + var nestedMap = new Map(); + nestedMap.set(nestedMap, map); + t.equal(inspect(nestedMap), 'Map (1) {[Circular] => ' + expectedString + '}', 'Map containing a Map should work'); + + t.end(); +}); + +test('Set', { skip: typeof Set !== 'function' }, function (t) { + var set = new Set(); + set.add({ a: 1 }); + set.add(['b']); + var expectedString = 'Set (2) {' + inspect({ a: 1 }) + ', ' + inspect(['b']) + '}'; + t.equal(inspect(set), expectedString, 'new Set([{ a: 1 }, ["b"]]) should show size and contents'); + t.equal(inspect(new Set()), 'Set (0) {}', 'empty Set should show as empty'); + + var nestedSet = new Set(); + nestedSet.add(set); + nestedSet.add(nestedSet); + t.equal(inspect(nestedSet), 'Set (2) {' + expectedString + ', [Circular]}', 'Set containing a Set should work'); + + t.end(); +}); + +test('Strings', function (t) { + var str = 'abc'; + + t.equal(inspect(str), "'" + str + "'", 'primitive string shows as such'); + t.equal(inspect(str, { quoteStyle: 'single' }), "'" + str + "'", 'primitive string shows as such, single quoted'); + t.equal(inspect(str, { quoteStyle: 'double' }), '"' + str + '"', 'primitive string shows as such, double quoted'); + t.equal(inspect(Object(str)), 'Object(' + inspect(str) + ')', 'String object shows as such'); + t.equal(inspect(Object(str), { quoteStyle: 'single' }), 'Object(' + inspect(str, { quoteStyle: 'single' }) + ')', 'String object shows as such, single quoted'); + t.equal(inspect(Object(str), { quoteStyle: 'double' }), 'Object(' + inspect(str, { quoteStyle: 'double' }) + ')', 'String object shows as such, double quoted'); + + t.end(); +}); + +test('Numbers', function (t) { + var num = 42; + + t.equal(inspect(num), String(num), 'primitive number shows as such'); + t.equal(inspect(Object(num)), 'Object(' + inspect(num) + ')', 'Number object shows as such'); + + t.end(); +}); + +test('Booleans', function (t) { + t.equal(inspect(true), String(true), 'primitive true shows as such'); + t.equal(inspect(Object(true)), 'Object(' + inspect(true) + ')', 'Boolean object true shows as such'); + + t.equal(inspect(false), String(false), 'primitive false shows as such'); + t.equal(inspect(Object(false)), 'Object(' + inspect(false) + ')', 'Boolean false object shows as such'); + + t.end(); +}); diff --git a/scripts/2.5/node_modules/object-inspect/util.inspect.js b/scripts/2.5/node_modules/object-inspect/util.inspect.js new file mode 100644 index 00000000..7784fab5 --- /dev/null +++ b/scripts/2.5/node_modules/object-inspect/util.inspect.js @@ -0,0 +1 @@ +module.exports = require('util').inspect; diff --git a/scripts/2.5/node_modules/object-is/.jscs.json b/scripts/2.5/node_modules/object-is/.jscs.json new file mode 100644 index 00000000..97ab933d --- /dev/null +++ b/scripts/2.5/node_modules/object-is/.jscs.json @@ -0,0 +1,55 @@ +{ + "requireCurlyBraces": ["if", "else", "for", "while", "do", "try", "catch"], + + "requireSpaceAfterKeywords": ["if", "else", "for", "while", "do", "switch", "return", "try", "catch", "function"], + + "disallowSpaceAfterKeywords": [], + + "requireSpacesInAnonymousFunctionExpression": { "beforeOpeningRoundBrace": true, "beforeOpeningCurlyBrace": true }, + "requireSpacesInNamedFunctionExpression": { "beforeOpeningCurlyBrace": true }, + "disallowSpacesInNamedFunctionExpression": { "beforeOpeningRoundBrace": true }, + "requireSpacesInFunctionDeclaration": { "beforeOpeningCurlyBrace": true }, + "disallowSpacesInFunctionDeclaration": { "beforeOpeningRoundBrace": true }, + + "disallowSpacesInsideParentheses": true, + + "disallowSpacesInsideArrayBrackets": true, + + "disallowQuotedKeysInObjects": "allButReserved", + + "disallowSpaceAfterObjectKeys": true, + + "requireCommaBeforeLineBreak": true, + + "disallowSpaceAfterPrefixUnaryOperators": ["++", "--", "+", "-", "~", "!"], + "requireSpaceAfterPrefixUnaryOperators": [], + + "disallowSpaceBeforePostfixUnaryOperators": ["++", "--"], + "requireSpaceBeforePostfixUnaryOperators": [], + + "disallowSpaceBeforeBinaryOperators": [], + "requireSpaceBeforeBinaryOperators": ["+", "-", "/", "*", "=", "==", "===", "!=", "!=="], + + "requireSpaceAfterBinaryOperators": ["+", "-", "/", "*", "=", "==", "===", "!=", "!=="], + "disallowSpaceAfterBinaryOperators": [], + + "disallowImplicitTypeConversion": ["binary", "string"], + + "disallowKeywords": ["with", "eval"], + + "validateLineBreaks": "LF", + + "requireKeywordsOnNewLine": [], + "disallowKeywordsOnNewLine": ["else"], + + "requireLineFeedAtFileEnd": true, + + "disallowTrailingWhitespace": true, + + "excludeFiles": ["node_modules/**", "vendor/**"], + + "disallowMultipleLineStrings": true, + + "additionalRules": [] +} + diff --git a/scripts/2.5/node_modules/object-is/.npmignore b/scripts/2.5/node_modules/object-is/.npmignore new file mode 100644 index 00000000..a72b52eb --- /dev/null +++ b/scripts/2.5/node_modules/object-is/.npmignore @@ -0,0 +1,15 @@ +lib-cov +*.seed +*.log +*.csv +*.dat +*.out +*.pid +*.gz + +pids +logs +results + +npm-debug.log +node_modules diff --git a/scripts/2.5/node_modules/object-is/.travis.yml b/scripts/2.5/node_modules/object-is/.travis.yml new file mode 100644 index 00000000..912080aa --- /dev/null +++ b/scripts/2.5/node_modules/object-is/.travis.yml @@ -0,0 +1,18 @@ +language: node_js +node_js: + - "0.11" + - "0.10" + - "0.9" + - "0.8" + - "0.6" + - "0.4" +before_install: + - '[ "${TRAVIS_NODE_VERSION}" == "0.6" ] || npm install -g npm@~1.4.6' +matrix: + fast_finish: true + allow_failures: + - node_js: "0.11" + - node_js: "0.9" + - node_js: "0.6" + - node_js: "0.4" + diff --git a/scripts/2.5/node_modules/object-is/LICENSE b/scripts/2.5/node_modules/object-is/LICENSE new file mode 100644 index 00000000..47b7b507 --- /dev/null +++ b/scripts/2.5/node_modules/object-is/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2014 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/scripts/2.5/node_modules/object-is/README.md b/scripts/2.5/node_modules/object-is/README.md new file mode 100644 index 00000000..4398954d --- /dev/null +++ b/scripts/2.5/node_modules/object-is/README.md @@ -0,0 +1,54 @@ +#object-is [![Version Badge][2]][1] + +[![Build Status][3]][4] [![dependency status][5]][6] [![dev dependency status][7]][8] + +[![npm badge][11]][1] + +[![browser support][9]][10] + +ES6-compliant shim for Object.is - differentiates between -0 and +0, and can compare to NaN. + +Essentially, Object.is returns the same value as === - but true for NaN, and false for -0 and +0. + +## Example + +```js +Object.is = require('object-is'); +var assert = require('assert'); + +assert.ok(Object.is()); +assert.ok(Object.is(undefined)); +assert.ok(Object.is(undefined, undefined)); +assert.ok(Object.is(null, null)); +assert.ok(Object.is(true, true)); +assert.ok(Object.is(false, false)); +assert.ok(Object.is('foo', 'foo')); + +var arr = [1, 2]; +assert.ok(Object.is(arr, arr)); +assert.notOk(Object.is(arr, [1, 2])); + +assert.ok(Object.is(0, 0)); +assert.ok(Object.is(-0, -0)); +assert.notOk(Object.is(0, -0)); + +assert.ok(Object.is(NaN, NaN)); +assert.ok(Object.is(Infinity, Infinity)); +assert.ok(Object.is(-Infinity, -Infinity)); +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[1]: https://npmjs.org/package/object-is +[2]: http://vb.teelaun.ch/ljharb/object-is.svg +[3]: https://travis-ci.org/ljharb/object-is.svg +[4]: https://travis-ci.org/ljharb/object-is +[5]: https://david-dm.org/ljharb/object-is.svg +[6]: https://david-dm.org/ljharb/object-is +[7]: https://david-dm.org/ljharb/object-is/dev-status.svg +[8]: https://david-dm.org/ljharb/object-is#info=devDependencies +[9]: https://ci.testling.com/ljharb/object-is.png +[10]: https://ci.testling.com/ljharb/object-is +[11]: https://nodei.co/npm/object-is.png?downloads=true&stars=true + diff --git a/scripts/2.5/node_modules/object-is/index.js b/scripts/2.5/node_modules/object-is/index.js new file mode 100644 index 00000000..60f1cdc3 --- /dev/null +++ b/scripts/2.5/node_modules/object-is/index.js @@ -0,0 +1,19 @@ +"use strict"; + +/* https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.is */ + +var NumberIsNaN = function (value) { + return value !== value; +}; + +module.exports = function is(a, b) { + if (a === 0 && b === 0) { + return 1 / a === 1 / b; + } else if (a === b) { + return true; + } else if (NumberIsNaN(a) && NumberIsNaN(b)) { + return true; + } + return false; +}; + diff --git a/scripts/2.5/node_modules/object-is/package.json b/scripts/2.5/node_modules/object-is/package.json new file mode 100644 index 00000000..cc6dbc84 --- /dev/null +++ b/scripts/2.5/node_modules/object-is/package.json @@ -0,0 +1,86 @@ +{ + "_from": "object-is@^1.0.1", + "_id": "object-is@1.0.1", + "_inBundle": false, + "_integrity": "sha1-CqYOyZiaCz7Xlc9NBvYs8a1lObY=", + "_location": "/object-is", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "object-is@^1.0.1", + "name": "object-is", + "escapedName": "object-is", + "rawSpec": "^1.0.1", + "saveSpec": null, + "fetchSpec": "^1.0.1" + }, + "_requiredBy": [ + "/assert" + ], + "_resolved": "https://registry.npmjs.org/object-is/-/object-is-1.0.1.tgz", + "_shasum": "0aa60ec9989a0b3ed795cf4d06f62cf1ad6539b6", + "_spec": "object-is@^1.0.1", + "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/2.5/node_modules/assert", + "author": { + "name": "Jordan Harband" + }, + "bugs": { + "url": "https://github.com/ljharb/object-is/issues" + }, + "bundleDependencies": false, + "dependencies": {}, + "deprecated": false, + "description": "ES6-compliant shim for Object.is - differentiates between -0 and +0", + "devDependencies": { + "covert": "~1.0.0", + "jscs": "~1.5.9", + "tape": "~2.14.0" + }, + "engines": { + "node": ">= 0.4" + }, + "homepage": "https://github.com/ljharb/object-is", + "keywords": [ + "is", + "Object.is", + "equality", + "sameValueZero", + "ES6", + "shim", + "polyfill" + ], + "license": "MIT", + "main": "index.js", + "name": "object-is", + "repository": { + "type": "git", + "url": "git://github.com/ljharb/object-is.git" + }, + "scripts": { + "coverage": "covert test.js", + "coverage-quiet": "covert test.js --quiet", + "lint": "jscs *.js", + "test": "npm run lint && node test.js && npm run coverage-quiet" + }, + "testling": { + "files": "test.js", + "browsers": [ + "iexplore/6.0..latest", + "firefox/3.0..6.0", + "firefox/15.0..latest", + "firefox/nightly", + "chrome/4.0..10.0", + "chrome/20.0..latest", + "chrome/canary", + "opera/10.0..12.0", + "opera/15.0..latest", + "opera/next", + "safari/4.0..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2" + ] + }, + "version": "1.0.1" +} diff --git a/scripts/2.5/node_modules/object-is/test.js b/scripts/2.5/node_modules/object-is/test.js new file mode 100644 index 00000000..2a5e1c02 --- /dev/null +++ b/scripts/2.5/node_modules/object-is/test.js @@ -0,0 +1,50 @@ +"use strict"; + +var test = require('tape'); +var is = require('./'); + +test('works with primitives', function (t) { + t.ok(is(), 'two absent args are the same'); + t.ok(is(undefined), 'undefined & one absent arg are the same'); + t.ok(is(undefined, undefined), 'undefined is undefined'); + t.ok(is(null, null), 'null is null'); + t.ok(is(true, true), 'true is true'); + t.ok(is(false, false), 'false is false'); + t.notOk(is(true, false), 'true is not false'); + t.end(); +}); + +test('works with NaN', function (t) { + t.ok(is(NaN, NaN), 'NaN is NaN'); + t.end(); +}); + +test('differentiates zeroes', function (t) { + t.ok(is(0, 0), '+0 is +0'); + t.ok(is(-0, -0), '-0 is -0'); + t.notOk(is(0, -0), '+0 is not -0'); + t.end(); +}); + +test('nonzero numbers', function (t) { + t.ok(is(Infinity, Infinity), 'infinity is infinity'); + t.ok(is(-Infinity, -Infinity), 'infinity is infinity'); + t.ok(is(42, 42), '42 is 42'); + t.notOk(is(42, -42), '42 is not -42'); + t.end(); +}); + +test('strings', function (t) { + t.ok(is('', ''), 'empty string is empty string'); + t.ok(is('foo', 'foo'), 'string is string'); + t.notOk(is('foo', 'bar'), 'string is not different string'); + t.end(); +}); + +test('objects', function (t) { + var obj = {}; + t.ok(is(obj, obj), 'object is same object'); + t.notOk(is(obj, {}), 'object is not different object'); + t.end(); +}); + diff --git a/scripts/2.5/node_modules/object-keys/.editorconfig b/scripts/2.5/node_modules/object-keys/.editorconfig new file mode 100644 index 00000000..eaa21416 --- /dev/null +++ b/scripts/2.5/node_modules/object-keys/.editorconfig @@ -0,0 +1,13 @@ +root = true + +[*] +indent_style = tab; +insert_final_newline = true; +quote_type = auto; +space_after_anonymous_functions = true; +space_after_control_statements = true; +spaces_around_operators = true; +trim_trailing_whitespace = true; +spaces_in_brackets = false; +end_of_line = lf; + diff --git a/scripts/2.5/node_modules/object-keys/.eslintrc b/scripts/2.5/node_modules/object-keys/.eslintrc new file mode 100644 index 00000000..9a8d5b0e --- /dev/null +++ b/scripts/2.5/node_modules/object-keys/.eslintrc @@ -0,0 +1,17 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "complexity": [2, 23], + "id-length": [2, { "min": 1, "max": 40 }], + "max-params": [2, 3], + "max-statements": [2, 23], + "max-statements-per-line": [2, { "max": 2 }], + "no-extra-parens": [1], + "no-invalid-this": [1], + "no-restricted-syntax": [2, "BreakStatement", "ContinueStatement", "LabeledStatement", "WithStatement"], + "operator-linebreak": [2, "after"] + } +} diff --git a/scripts/2.5/node_modules/object-keys/.travis.yml b/scripts/2.5/node_modules/object-keys/.travis.yml new file mode 100644 index 00000000..94a6ce42 --- /dev/null +++ b/scripts/2.5/node_modules/object-keys/.travis.yml @@ -0,0 +1,277 @@ +language: node_js +os: + - linux +node_js: + - "11.8" + - "10.15" + - "9.11" + - "8.15" + - "7.10" + - "6.16" + - "5.12" + - "4.9" + - "iojs-v3.3" + - "iojs-v2.5" + - "iojs-v1.8" + - "0.12" + - "0.10" + - "0.8" +before_install: + - 'case "${TRAVIS_NODE_VERSION}" in 0.*) export NPM_CONFIG_STRICT_SSL=false ;; esac' + - 'nvm install-latest-npm' +install: + - 'if [ "${TRAVIS_NODE_VERSION}" = "0.6" ] || [ "${TRAVIS_NODE_VERSION}" = "0.9" ]; then nvm install --latest-npm 0.8 && npm install && nvm use "${TRAVIS_NODE_VERSION}"; else npm install; fi;' +script: + - 'if [ -n "${PRETEST-}" ]; then npm run pretest ; fi' + - 'if [ -n "${POSTTEST-}" ]; then npm run posttest ; fi' + - 'if [ -n "${COVERAGE-}" ]; then npm run coverage ; fi' + - 'if [ -n "${TEST-}" ]; then npm run tests-only ; fi' +sudo: false +env: + - TEST=true +matrix: + fast_finish: true + include: + - node_js: "lts/*" + env: PRETEST=true + - node_js: "lts/*" + env: POSTTEST=true + - node_js: "4" + env: COVERAGE=true + - node_js: "11.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.14" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.13" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.12" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.14" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.13" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.12" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.15" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.14" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.13" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.12" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v3.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v3.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v3.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.4" + env: TEST=true ALLOW_FAILURE=true + allow_failures: + - os: osx + - env: TEST=true ALLOW_FAILURE=true + - env: COVERAGE=true + - env: POSTTEST=true diff --git a/scripts/2.5/node_modules/object-keys/CHANGELOG.md b/scripts/2.5/node_modules/object-keys/CHANGELOG.md new file mode 100644 index 00000000..b7d92df2 --- /dev/null +++ b/scripts/2.5/node_modules/object-keys/CHANGELOG.md @@ -0,0 +1,232 @@ +1.1.1 / 2019-04-06 +================= + * [Fix] exclude deprecated Firefox keys (#53) + +1.1.0 / 2019-02-10 +================= + * [New] [Refactor] move full implementation to `implementation` entry point + * [Refactor] only evaluate the implementation if `Object.keys` is not present + * [Tests] up to `node` `v11.8`, `v10.15`, `v8.15`, `v6.16` + * [Tests] remove jscs + * [Tests] switch to `npm audit` from `nsp` + +1.0.12 / 2018-06-18 +================= + * [Fix] avoid accessing `window.applicationCache`, to avoid issues with latest Chrome on HTTP (#46) + +1.0.11 / 2016-07-05 +================= + * [Fix] exclude keys regarding the style (eg. `pageYOffset`) on `window` to avoid reflow (#32) + +1.0.10 / 2016-07-04 +================= + * [Fix] exclude `height` and `width` keys on `window` to avoid reflow (#31) + * [Fix] In IE 6, `window.external` makes `Object.keys` throw + * [Tests] up to `node` `v6.2`, `v5.10`, `v4.4` + * [Tests] use pretest/posttest for linting/security + * [Dev Deps] update `tape`, `jscs`, `nsp`, `eslint`, `@ljharb/eslint-config` + * [Dev Deps] remove unused eccheck script + dep + +1.0.9 / 2015-10-19 +================= + * [Fix] Blacklist 'frame' property on window (#16, #17) + * [Dev Deps] update `jscs`, `eslint`, `@ljharb/eslint-config` + +1.0.8 / 2015-10-14 +================= + * [Fix] wrap automation equality bug checking in try/catch, per [es5-shim#327](https://github.com/es-shims/es5-shim/issues/327) + * [Fix] Blacklist 'window.frameElement' per [es5-shim#322](https://github.com/es-shims/es5-shim/issues/322) + * [Docs] Switch from vb.teelaun.ch to versionbadg.es for the npm version badge SVG + * [Tests] up to `io.js` `v3.3`, `node` `v4.2` + * [Dev Deps] update `eslint`, `tape`, `@ljharb/eslint-config`, `jscs` + +1.0.7 / 2015-07-18 +================= + * [Fix] A proper fix for 176f03335e90d5c8d0d8125a99f27819c9b9cdad / https://github.com/es-shims/es5-shim/issues/275 that doesn't break dontEnum/constructor fixes in IE 8. + * [Fix] Remove deprecation message in Chrome by touching deprecated window properties (#15) + * [Tests] Improve test output for automation equality bugfix + * [Tests] Test on `io.js` `v2.4` + +1.0.6 / 2015-07-09 +================= + * [Fix] Use an object lookup rather than ES5's `indexOf` (#14) + * [Tests] ES3 browsers don't have `Array.isArray` + * [Tests] Fix `no-shadow` rule, as well as an IE 8 bug caused by engine NFE shadowing bugs. + +1.0.5 / 2015-07-03 +================= + * [Fix] Fix a flabbergasting IE 8 bug where `localStorage.constructor.prototype === localStorage` throws + * [Tests] Test up to `io.js` `v2.3` + * [Dev Deps] Update `nsp`, `eslint` + +1.0.4 / 2015-05-23 +================= + * Fix a Safari 5.0 bug with `Object.keys` not working with `arguments` + * Test on latest `node` and `io.js` + * Update `jscs`, `tape`, `eslint`, `nsp`, `is`, `editorconfig-tools`, `covert` + +1.0.3 / 2015-01-06 +================= + * Revert "Make `object-keys` more robust against later environment tampering" to maintain ES3 compliance + +1.0.2 / 2014-12-28 +================= + * Update lots of dev dependencies + * Tweaks to README + * Make `object-keys` more robust against later environment tampering + +1.0.1 / 2014-09-03 +================= + * Update URLs and badges in README + +1.0.0 / 2014-08-26 +================= + * v1.0.0 + +0.6.1 / 2014-08-25 +================= + * v0.6.1 + * Updating dependencies (tape, covert, is) + * Update badges in readme + * Use separate var statements + +0.6.0 / 2014-04-23 +================= + * v0.6.0 + * Updating dependencies (tape, covert) + * Make sure boxed primitives, and arguments objects, work properly in ES3 browsers + * Improve test matrix: test all node versions, but only latest two stables are a failure + * Remove internal foreach shim. + +0.5.1 / 2014-03-09 +================= + * 0.5.1 + * Updating dependencies (tape, covert, is) + * Removing forEach from the module (but keeping it in tests) + +0.5.0 / 2014-01-30 +================= + * 0.5.0 + * Explicitly returning the shim, instead of returning native Object.keys when present + * Adding a changelog. + * Cleaning up IIFE wrapping + * Testing on node 0.4 through 0.11 + +0.4.0 / 2013-08-14 +================== + + * v0.4.0 + * In Chrome 4-10 and Safari 4, typeof (new RegExp) === 'function' + * If it's a string, make sure to use charAt instead of brackets. + * Only use Function#call if necessary. + * Making sure the context tests actually run. + * Better function detection + * Adding the android browser + * Fixing testling files + * Updating tape + * Removing the "is" dependency. + * Making an isArguments shim. + * Adding a local forEach shim and tests. + * Updating paths. + * Moving the shim test. + * v0.3.0 + +0.3.0 / 2013-05-18 +================== + + * README tweak. + * Fixing constructor enum issue. Fixes [#5](https://github.com/ljharb/object-keys/issues/5). + * Adding a test for [#5](https://github.com/ljharb/object-keys/issues/5) + * Updating readme. + * Updating dependencies. + * Giving credit to lodash. + * Make sure that a prototype's constructor property is not enumerable. Fixes [#3](https://github.com/ljharb/object-keys/issues/3). + * Adding additional tests to handle arguments objects, and to skip "prototype" in functions. Fixes [#2](https://github.com/ljharb/object-keys/issues/2). + * Fixing a typo on this test for [#3](https://github.com/ljharb/object-keys/issues/3). + * Adding node 0.10 to travis. + * Adding an IE < 9 test per [#3](https://github.com/ljharb/object-keys/issues/3) + * Adding an iOS 5 mobile Safari test per [#2](https://github.com/ljharb/object-keys/issues/2) + * Moving "indexof" and "is" to be dev dependencies. + * Making sure the shim works with functions. + * Flattening the tests. + +0.2.0 / 2013-05-10 +================== + + * v0.2.0 + * Object.keys should work with arrays. + +0.1.8 / 2013-05-10 +================== + + * v0.1.8 + * Upgrading dependencies. + * Using a simpler check. + * Fixing a bug in hasDontEnumBug browsers. + * Using the newest tape! + * Fixing this error test. + * "undefined" is probably a reserved word in ES3. + * Better test message. + +0.1.7 / 2013-04-17 +================== + + * Upgrading "is" once more. + * The key "null" is breaking some browsers. + +0.1.6 / 2013-04-17 +================== + + * v0.1.6 + * Upgrading "is" + +0.1.5 / 2013-04-14 +================== + + * Bumping version. + * Adding more testling browsers. + * Updating "is" + +0.1.4 / 2013-04-08 +================== + + * Using "is" instead of "is-extended". + +0.1.3 / 2013-04-07 +================== + + * Using "foreach" instead of my own shim. + * Removing "tap"; I'll just wait for "tape" to fix its node 0.10 bug. + +0.1.2 / 2013-04-03 +================== + + * Adding dependency status; moving links to an index at the bottom. + * Upgrading is-extended; version 0.1.2 + * Adding an npm version badge. + +0.1.1 / 2013-04-01 +================== + + * Adding Travis CI. + * Bumping the version. + * Adding indexOf since IE sucks. + * Adding a forEach shim since older browsers don't have Array#forEach. + * Upgrading tape - 0.3.2 uses Array#map + * Using explicit end instead of plan. + * Can't test with Array.isArray in older browsers. + * Using is-extended. + * Fixing testling files. + * JSHint/JSLint-ing. + * Removing an unused object. + * Using strict mode. + +0.1.0 / 2013-03-30 +================== + + * Changing the exports should have meant a higher version bump. + * Oops, fixing the repo URL. + * Adding more tests. + * 0.0.2 + * Merge branch 'export_one_thing'; closes [#1](https://github.com/ljharb/object-keys/issues/1) + * Move shim export to a separate file. diff --git a/scripts/2.5/node_modules/object-keys/LICENSE b/scripts/2.5/node_modules/object-keys/LICENSE new file mode 100644 index 00000000..28553fdd --- /dev/null +++ b/scripts/2.5/node_modules/object-keys/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (C) 2013 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. \ No newline at end of file diff --git a/scripts/2.5/node_modules/object-keys/README.md b/scripts/2.5/node_modules/object-keys/README.md new file mode 100644 index 00000000..ed4c2770 --- /dev/null +++ b/scripts/2.5/node_modules/object-keys/README.md @@ -0,0 +1,76 @@ +#object-keys [![Version Badge][npm-version-svg]][package-url] + +[![Build Status][travis-svg]][travis-url] +[![dependency status][deps-svg]][deps-url] +[![dev dependency status][dev-deps-svg]][dev-deps-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +[![browser support][testling-svg]][testling-url] + +An Object.keys shim. Invoke its "shim" method to shim Object.keys if it is unavailable. + +Most common usage: +```js +var keys = Object.keys || require('object-keys'); +``` + +## Example + +```js +var keys = require('object-keys'); +var assert = require('assert'); +var obj = { + a: true, + b: true, + c: true +}; + +assert.deepEqual(keys(obj), ['a', 'b', 'c']); +``` + +```js +var keys = require('object-keys'); +var assert = require('assert'); +/* when Object.keys is not present */ +delete Object.keys; +var shimmedKeys = keys.shim(); +assert.equal(shimmedKeys, keys); +assert.deepEqual(Object.keys(obj), keys(obj)); +``` + +```js +var keys = require('object-keys'); +var assert = require('assert'); +/* when Object.keys is present */ +var shimmedKeys = keys.shim(); +assert.equal(shimmedKeys, Object.keys); +assert.deepEqual(Object.keys(obj), keys(obj)); +``` + +## Source +Implementation taken directly from [es5-shim][es5-shim-url], with modifications, including from [lodash][lodash-url]. + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.org/package/object-keys +[npm-version-svg]: http://versionbadg.es/ljharb/object-keys.svg +[travis-svg]: https://travis-ci.org/ljharb/object-keys.svg +[travis-url]: https://travis-ci.org/ljharb/object-keys +[deps-svg]: https://david-dm.org/ljharb/object-keys.svg +[deps-url]: https://david-dm.org/ljharb/object-keys +[dev-deps-svg]: https://david-dm.org/ljharb/object-keys/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/object-keys#info=devDependencies +[testling-svg]: https://ci.testling.com/ljharb/object-keys.png +[testling-url]: https://ci.testling.com/ljharb/object-keys +[es5-shim-url]: https://github.com/es-shims/es5-shim/blob/master/es5-shim.js#L542-589 +[lodash-url]: https://github.com/lodash/lodash +[npm-badge-png]: https://nodei.co/npm/object-keys.png?downloads=true&stars=true +[license-image]: http://img.shields.io/npm/l/object-keys.svg +[license-url]: LICENSE +[downloads-image]: http://img.shields.io/npm/dm/object-keys.svg +[downloads-url]: http://npm-stat.com/charts.html?package=object-keys + diff --git a/scripts/2.5/node_modules/object-keys/implementation.js b/scripts/2.5/node_modules/object-keys/implementation.js new file mode 100644 index 00000000..5b329861 --- /dev/null +++ b/scripts/2.5/node_modules/object-keys/implementation.js @@ -0,0 +1,122 @@ +'use strict'; + +var keysShim; +if (!Object.keys) { + // modified from https://github.com/es-shims/es5-shim + var has = Object.prototype.hasOwnProperty; + var toStr = Object.prototype.toString; + var isArgs = require('./isArguments'); // eslint-disable-line global-require + var isEnumerable = Object.prototype.propertyIsEnumerable; + var hasDontEnumBug = !isEnumerable.call({ toString: null }, 'toString'); + var hasProtoEnumBug = isEnumerable.call(function () {}, 'prototype'); + var dontEnums = [ + 'toString', + 'toLocaleString', + 'valueOf', + 'hasOwnProperty', + 'isPrototypeOf', + 'propertyIsEnumerable', + 'constructor' + ]; + var equalsConstructorPrototype = function (o) { + var ctor = o.constructor; + return ctor && ctor.prototype === o; + }; + var excludedKeys = { + $applicationCache: true, + $console: true, + $external: true, + $frame: true, + $frameElement: true, + $frames: true, + $innerHeight: true, + $innerWidth: true, + $onmozfullscreenchange: true, + $onmozfullscreenerror: true, + $outerHeight: true, + $outerWidth: true, + $pageXOffset: true, + $pageYOffset: true, + $parent: true, + $scrollLeft: true, + $scrollTop: true, + $scrollX: true, + $scrollY: true, + $self: true, + $webkitIndexedDB: true, + $webkitStorageInfo: true, + $window: true + }; + var hasAutomationEqualityBug = (function () { + /* global window */ + if (typeof window === 'undefined') { return false; } + for (var k in window) { + try { + if (!excludedKeys['$' + k] && has.call(window, k) && window[k] !== null && typeof window[k] === 'object') { + try { + equalsConstructorPrototype(window[k]); + } catch (e) { + return true; + } + } + } catch (e) { + return true; + } + } + return false; + }()); + var equalsConstructorPrototypeIfNotBuggy = function (o) { + /* global window */ + if (typeof window === 'undefined' || !hasAutomationEqualityBug) { + return equalsConstructorPrototype(o); + } + try { + return equalsConstructorPrototype(o); + } catch (e) { + return false; + } + }; + + keysShim = function keys(object) { + var isObject = object !== null && typeof object === 'object'; + var isFunction = toStr.call(object) === '[object Function]'; + var isArguments = isArgs(object); + var isString = isObject && toStr.call(object) === '[object String]'; + var theKeys = []; + + if (!isObject && !isFunction && !isArguments) { + throw new TypeError('Object.keys called on a non-object'); + } + + var skipProto = hasProtoEnumBug && isFunction; + if (isString && object.length > 0 && !has.call(object, 0)) { + for (var i = 0; i < object.length; ++i) { + theKeys.push(String(i)); + } + } + + if (isArguments && object.length > 0) { + for (var j = 0; j < object.length; ++j) { + theKeys.push(String(j)); + } + } else { + for (var name in object) { + if (!(skipProto && name === 'prototype') && has.call(object, name)) { + theKeys.push(String(name)); + } + } + } + + if (hasDontEnumBug) { + var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object); + + for (var k = 0; k < dontEnums.length; ++k) { + if (!(skipConstructor && dontEnums[k] === 'constructor') && has.call(object, dontEnums[k])) { + theKeys.push(dontEnums[k]); + } + } + } + return theKeys; + }; +} +module.exports = keysShim; diff --git a/scripts/2.5/node_modules/object-keys/index.js b/scripts/2.5/node_modules/object-keys/index.js new file mode 100644 index 00000000..a43807d2 --- /dev/null +++ b/scripts/2.5/node_modules/object-keys/index.js @@ -0,0 +1,32 @@ +'use strict'; + +var slice = Array.prototype.slice; +var isArgs = require('./isArguments'); + +var origKeys = Object.keys; +var keysShim = origKeys ? function keys(o) { return origKeys(o); } : require('./implementation'); + +var originalKeys = Object.keys; + +keysShim.shim = function shimObjectKeys() { + if (Object.keys) { + var keysWorksWithArguments = (function () { + // Safari 5.0 bug + var args = Object.keys(arguments); + return args && args.length === arguments.length; + }(1, 2)); + if (!keysWorksWithArguments) { + Object.keys = function keys(object) { // eslint-disable-line func-name-matching + if (isArgs(object)) { + return originalKeys(slice.call(object)); + } + return originalKeys(object); + }; + } + } else { + Object.keys = keysShim; + } + return Object.keys || keysShim; +}; + +module.exports = keysShim; diff --git a/scripts/2.5/node_modules/object-keys/isArguments.js b/scripts/2.5/node_modules/object-keys/isArguments.js new file mode 100644 index 00000000..f2a2a901 --- /dev/null +++ b/scripts/2.5/node_modules/object-keys/isArguments.js @@ -0,0 +1,17 @@ +'use strict'; + +var toStr = Object.prototype.toString; + +module.exports = function isArguments(value) { + var str = toStr.call(value); + var isArgs = str === '[object Arguments]'; + if (!isArgs) { + isArgs = str !== '[object Array]' && + value !== null && + typeof value === 'object' && + typeof value.length === 'number' && + value.length >= 0 && + toStr.call(value.callee) === '[object Function]'; + } + return isArgs; +}; diff --git a/scripts/2.5/node_modules/object-keys/package.json b/scripts/2.5/node_modules/object-keys/package.json new file mode 100644 index 00000000..a1575607 --- /dev/null +++ b/scripts/2.5/node_modules/object-keys/package.json @@ -0,0 +1,118 @@ +{ + "_from": "object-keys@^1.0.12", + "_id": "object-keys@1.1.1", + "_inBundle": false, + "_integrity": "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==", + "_location": "/object-keys", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "object-keys@^1.0.12", + "name": "object-keys", + "escapedName": "object-keys", + "rawSpec": "^1.0.12", + "saveSpec": null, + "fetchSpec": "^1.0.12" + }, + "_requiredBy": [ + "/define-properties", + "/es-abstract" + ], + "_resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz", + "_shasum": "1c47f272df277f3b1daf061677d9c82e2322c60e", + "_spec": "object-keys@^1.0.12", + "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/2.5/node_modules/define-properties", + "author": { + "name": "Jordan Harband", + "email": "ljharb@gmail.com", + "url": "http://ljharb.codes" + }, + "bugs": { + "url": "https://github.com/ljharb/object-keys/issues" + }, + "bundleDependencies": false, + "contributors": [ + { + "name": "Jordan Harband", + "email": "ljharb@gmail.com", + "url": "http://ljharb.codes" + }, + { + "name": "Raynos", + "email": "raynos2@gmail.com" + }, + { + "name": "Nathan Rajlich", + "email": "nathan@tootallnate.net" + }, + { + "name": "Ivan Starkov", + "email": "istarkov@gmail.com" + }, + { + "name": "Gary Katsevman", + "email": "git@gkatsev.com" + } + ], + "dependencies": {}, + "deprecated": false, + "description": "An Object.keys replacement, in case Object.keys is not available. From https://github.com/es-shims/es5-shim", + "devDependencies": { + "@ljharb/eslint-config": "^13.1.1", + "covert": "^1.1.1", + "eslint": "^5.13.0", + "foreach": "^2.0.5", + "indexof": "^0.0.1", + "is": "^3.3.0", + "tape": "^4.9.2" + }, + "engines": { + "node": ">= 0.4" + }, + "homepage": "https://github.com/ljharb/object-keys#readme", + "keywords": [ + "Object.keys", + "keys", + "ES5", + "shim" + ], + "license": "MIT", + "main": "index.js", + "name": "object-keys", + "repository": { + "type": "git", + "url": "git://github.com/ljharb/object-keys.git" + }, + "scripts": { + "audit": "npm audit", + "coverage": "covert test/*.js", + "coverage-quiet": "covert test/*.js --quiet", + "lint": "eslint .", + "postaudit": "rm package-lock.json", + "posttest": "npm run --silent audit", + "preaudit": "npm install --package-lock --package-lock-only", + "pretest": "npm run --silent lint", + "test": "npm run --silent tests-only", + "tests-only": "node test/index.js" + }, + "testling": { + "files": "test/index.js", + "browsers": [ + "iexplore/6.0..latest", + "firefox/3.0..6.0", + "firefox/15.0..latest", + "firefox/nightly", + "chrome/4.0..10.0", + "chrome/20.0..latest", + "chrome/canary", + "opera/10.0..latest", + "opera/next", + "safari/4.0..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2" + ] + }, + "version": "1.1.1" +} diff --git a/scripts/2.5/node_modules/object-keys/test/index.js b/scripts/2.5/node_modules/object-keys/test/index.js new file mode 100644 index 00000000..5402465a --- /dev/null +++ b/scripts/2.5/node_modules/object-keys/test/index.js @@ -0,0 +1,5 @@ +'use strict'; + +require('./isArguments'); + +require('./shim'); diff --git a/scripts/2.5/node_modules/object.entries/.editorconfig b/scripts/2.5/node_modules/object.entries/.editorconfig new file mode 100644 index 00000000..bc228f82 --- /dev/null +++ b/scripts/2.5/node_modules/object.entries/.editorconfig @@ -0,0 +1,20 @@ +root = true + +[*] +indent_style = tab +indent_size = 4 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true +max_line_length = 150 + +[CHANGELOG.md] +indent_style = space +indent_size = 2 + +[*.json] +max_line_length = off + +[Makefile] +max_line_length = off diff --git a/scripts/2.5/node_modules/object.entries/.eslintrc b/scripts/2.5/node_modules/object.entries/.eslintrc new file mode 100644 index 00000000..3378618b --- /dev/null +++ b/scripts/2.5/node_modules/object.entries/.eslintrc @@ -0,0 +1,11 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "new-cap": [2, { "capIsNewExceptions": ["RequireObjectCoercible"] }], + "no-magic-numbers": [0], + "no-restricted-syntax": [2, "BreakStatement", "ContinueStatement", "DebuggerStatement", "LabeledStatement", "WithStatement"] + } +} diff --git a/scripts/2.5/node_modules/object.entries/.travis.yml b/scripts/2.5/node_modules/object.entries/.travis.yml new file mode 100644 index 00000000..2056556d --- /dev/null +++ b/scripts/2.5/node_modules/object.entries/.travis.yml @@ -0,0 +1,269 @@ +language: node_js +os: + - linux +node_js: + - "11.6" + - "10.15" + - "9.11" + - "8.15" + - "7.10" + - "6.16" + - "5.12" + - "4.9" + - "iojs-v3.3" + - "iojs-v2.5" + - "iojs-v1.8" + - "0.12" + - "0.10" + - "0.8" +before_install: + - 'case "${TRAVIS_NODE_VERSION}" in 0.*) export NPM_CONFIG_STRICT_SSL=false ;; esac' + - 'nvm install-latest-npm' +install: + - 'if [ "${TRAVIS_NODE_VERSION}" = "0.6" ] || [ "${TRAVIS_NODE_VERSION}" = "0.9" ]; then nvm install --latest-npm 0.8 && npm install && nvm use "${TRAVIS_NODE_VERSION}"; else npm install; fi;' +script: + - 'if [ -n "${PRETEST-}" ]; then npm run pretest ; fi' + - 'if [ -n "${POSTTEST-}" ]; then npm run posttest ; fi' + - 'if [ -n "${COVERAGE-}" ]; then npm run coverage ; fi' + - 'if [ -n "${TEST-}" ]; then npm run tests-only ; fi' +sudo: false +env: + - TEST=true +matrix: + fast_finish: true + include: + - node_js: "lts/*" + env: PRETEST=true + - node_js: "lts/*" + env: POSTTEST=true + - node_js: "11.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.14" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.13" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.12" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.14" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.13" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.12" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.15" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.14" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.13" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.12" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v3.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v3.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v3.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.4" + env: TEST=true ALLOW_FAILURE=true + allow_failures: + - os: osx + - env: TEST=true ALLOW_FAILURE=true diff --git a/scripts/2.5/node_modules/object.entries/CHANGELOG.md b/scripts/2.5/node_modules/object.entries/CHANGELOG.md new file mode 100644 index 00000000..35e6c3d1 --- /dev/null +++ b/scripts/2.5/node_modules/object.entries/CHANGELOG.md @@ -0,0 +1,33 @@ +1.1.0 / 2019-01-01 +================= + * [New] add `auto` entry point` + * [meta] exclude test.html from the npm package + * [Deps] update `define-properties`, `es-abstract`, `function-bind`, `has` + * [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `covert`, `tape` + * [Tests] up to `node` `v11.6`, `v10.15`, `v9.11`, `v8.15`, `v7.10`, `v6.16`, `v4.9`; use `nvm install-latest-npm` + * [Tests] use `npm audit` instead of `nsp` + * [Tests] remove `jscs` + +1.0.4 / 2016-12-04 +================= + * [Deps] update `es-abstract`, `function-bind`, `define-properties` + * [Dev Deps] update `tape`, `jscs`, `nsp`, `eslint`, `@ljharb/eslint-config` + * [Tests] up to `node` `v7.2`, `v6.9`, `v4.6`; improve test matrix. + +1.0.3 / 2015-10-06 +================= + * [Fix] Not-yet-visited keys made non-enumerable on a `[[Get]]` must not show up in the output (https://github.com/ljharb/proposal-object-values-entries/issues/5) + +1.0.2 / 2015-09-25 +================= + * [Fix] Not-yet-visited keys deleted on a `[[Get]]` must not show up in the output (#1) + +1.0.1 / 2015-09-21 +================= + * [Docs] update version badge URL + * [Tests] on `io.js` `v3.3`, up to `node` `v4.1` + * [Dev Deps] update `eslint`, `@ljharb/eslint-config` + +1.0.0 / 2015-09-02 +================= + * v1.0.0 diff --git a/scripts/2.5/node_modules/object.entries/LICENSE b/scripts/2.5/node_modules/object.entries/LICENSE new file mode 100644 index 00000000..b43df444 --- /dev/null +++ b/scripts/2.5/node_modules/object.entries/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/scripts/2.5/node_modules/object.entries/README.md b/scripts/2.5/node_modules/object.entries/README.md new file mode 100644 index 00000000..f0cdbfdc --- /dev/null +++ b/scripts/2.5/node_modules/object.entries/README.md @@ -0,0 +1,59 @@ +# object.entries [![Version Badge][npm-version-svg]][package-url] + +[![Build Status][travis-svg]][travis-url] +[![dependency status][deps-svg]][deps-url] +[![dev dependency status][dev-deps-svg]][dev-deps-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +[![browser support][testling-svg]][testling-url] + +An ES2017 spec-compliant `Object.entries` shim. Invoke its "shim" method to shim `Object.entries` if it is unavailable or noncompliant. + +This package implements the [es-shim API](https://github.com/es-shims/api) interface. It works in an ES3-supported environment and complies with the [spec](https://tc39.github.io/ecma262/#sec-object.entries). + +Most common usage: +```js +var assert = require('assert'); +var entries = require('object.entries'); + +var obj = { a: 1, b: 2, c: 3 }; +var expected = [['a', 1], ['b', 2], ['c', 3]]; + +if (typeof Symbol === 'function' && typeof Symbol() === 'symbol') { + // for environments with Symbol support + var sym = Symbol(); + obj[sym] = 4; + obj.d = sym; + expected.push(['d', sym]); +} + +assert.deepEqual(entries(obj), expected); + +if (!Object.entries) { + entries.shim(); +} + +assert.deepEqual(Object.entries(obj), expected); +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.com/package/object.entries +[npm-version-svg]: http://versionbadg.es/es-shims/Object.entries.svg +[travis-svg]: https://travis-ci.org/es-shims/Object.entries.svg +[travis-url]: https://travis-ci.org/es-shims/Object.entries +[deps-svg]: https://david-dm.org/es-shims/Object.entries.svg +[deps-url]: https://david-dm.org/es-shims/Object.entries +[dev-deps-svg]: https://david-dm.org/es-shims/Object.entries/dev-status.svg +[dev-deps-url]: https://david-dm.org/es-shims/Object.entries#info=devDependencies +[testling-svg]: https://ci.testling.com/es-shims/Object.entries.png +[testling-url]: https://ci.testling.com/es-shims/Object.entries +[npm-badge-png]: https://nodei.co/npm/object.entries.png?downloads=true&stars=true +[license-image]: http://img.shields.io/npm/l/object.entries.svg +[license-url]: LICENSE +[downloads-image]: http://img.shields.io/npm/dm/object.entries.svg +[downloads-url]: http://npm-stat.com/charts.html?package=object.entries diff --git a/scripts/2.5/node_modules/object.entries/auto.js b/scripts/2.5/node_modules/object.entries/auto.js new file mode 100644 index 00000000..8ebf606c --- /dev/null +++ b/scripts/2.5/node_modules/object.entries/auto.js @@ -0,0 +1,3 @@ +'use strict'; + +require('./shim')(); diff --git a/scripts/2.5/node_modules/object.entries/implementation.js b/scripts/2.5/node_modules/object.entries/implementation.js new file mode 100644 index 00000000..0310246d --- /dev/null +++ b/scripts/2.5/node_modules/object.entries/implementation.js @@ -0,0 +1,17 @@ +'use strict'; + +var ES = require('es-abstract/es7'); +var has = require('has'); +var bind = require('function-bind'); +var isEnumerable = bind.call(Function.call, Object.prototype.propertyIsEnumerable); + +module.exports = function entries(O) { + var obj = ES.RequireObjectCoercible(O); + var entrys = []; + for (var key in obj) { + if (has(obj, key) && isEnumerable(obj, key)) { + entrys.push([key, obj[key]]); + } + } + return entrys; +}; diff --git a/scripts/2.5/node_modules/object.entries/index.js b/scripts/2.5/node_modules/object.entries/index.js new file mode 100644 index 00000000..b8ba0910 --- /dev/null +++ b/scripts/2.5/node_modules/object.entries/index.js @@ -0,0 +1,17 @@ +'use strict'; + +var define = require('define-properties'); + +var implementation = require('./implementation'); +var getPolyfill = require('./polyfill'); +var shim = require('./shim'); + +var polyfill = getPolyfill(); + +define(polyfill, { + getPolyfill: getPolyfill, + implementation: implementation, + shim: shim +}); + +module.exports = polyfill; diff --git a/scripts/2.5/node_modules/object.entries/package.json b/scripts/2.5/node_modules/object.entries/package.json new file mode 100644 index 00000000..e33d9f21 --- /dev/null +++ b/scripts/2.5/node_modules/object.entries/package.json @@ -0,0 +1,107 @@ +{ + "_from": "object.entries@^1.1.0", + "_id": "object.entries@1.1.0", + "_inBundle": false, + "_integrity": "sha512-l+H6EQ8qzGRxbkHOd5I/aHRhHDKoQXQ8g0BYt4uSweQU1/J6dZUOyWh9a2Vky35YCKjzmgxOzta2hH6kf9HuXA==", + "_location": "/object.entries", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "object.entries@^1.1.0", + "name": "object.entries", + "escapedName": "object.entries", + "rawSpec": "^1.1.0", + "saveSpec": null, + "fetchSpec": "^1.1.0" + }, + "_requiredBy": [ + "/util" + ], + "_resolved": "https://registry.npmjs.org/object.entries/-/object.entries-1.1.0.tgz", + "_shasum": "2024fc6d6ba246aee38bdb0ffd5cfbcf371b7519", + "_spec": "object.entries@^1.1.0", + "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/2.5/node_modules/util", + "author": { + "name": "Jordan Harband" + }, + "bugs": { + "url": "https://github.com/es-shims/Object.entries/issues" + }, + "bundleDependencies": false, + "dependencies": { + "define-properties": "^1.1.3", + "es-abstract": "^1.12.0", + "function-bind": "^1.1.1", + "has": "^1.0.3" + }, + "deprecated": false, + "description": "ES2017 spec-compliant Object.entries shim.", + "devDependencies": { + "@es-shims/api": "^2.1.2", + "@ljharb/eslint-config": "^13.1.1", + "array-map": "^0.0.0", + "covert": "^1.1.1", + "eslint": "^5.11.1", + "tape": "^4.9.2" + }, + "engines": { + "node": ">= 0.4" + }, + "homepage": "https://github.com/es-shims/Object.entries#readme", + "keywords": [ + "Object.entries", + "Object.values", + "Object.keys", + "entries", + "values", + "ES7", + "ES8", + "ES2017", + "shim", + "object", + "keys", + "polyfill", + "es-shim API" + ], + "license": "MIT", + "main": "index.js", + "name": "object.entries", + "repository": { + "type": "git", + "url": "git://github.com/es-shims/Object.entries.git" + }, + "scripts": { + "audit": "npm audit", + "coverage": "covert test/*.js", + "coverage-quiet": "covert test/*.js --quiet", + "lint": "eslint .", + "postaudit": "rm package-lock.json", + "posttest": "npm run audit", + "preaudit": "npm install --package-lock-only --package-lock", + "pretest": "npm run --silent lint", + "test": "npm run --silent tests-only", + "test:module": "node test/index.js", + "test:shimmed": "node test/shimmed.js", + "tests-only": "es-shim-api && npm run --silent test:shimmed && npm run --silent test:module" + }, + "testling": { + "files": "test/index.js", + "browsers": [ + "iexplore/9.0..latest", + "firefox/4.0..6.0", + "firefox/15.0..latest", + "firefox/nightly", + "chrome/4.0..10.0", + "chrome/20.0..latest", + "chrome/canary", + "opera/11.6..latest", + "opera/next", + "safari/5.0..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2" + ] + }, + "version": "1.1.0" +} diff --git a/scripts/2.5/node_modules/object.entries/polyfill.js b/scripts/2.5/node_modules/object.entries/polyfill.js new file mode 100644 index 00000000..32e3238f --- /dev/null +++ b/scripts/2.5/node_modules/object.entries/polyfill.js @@ -0,0 +1,7 @@ +'use strict'; + +var implementation = require('./implementation'); + +module.exports = function getPolyfill() { + return typeof Object.entries === 'function' ? Object.entries : implementation; +}; diff --git a/scripts/2.5/node_modules/object.entries/shim.js b/scripts/2.5/node_modules/object.entries/shim.js new file mode 100644 index 00000000..135defef --- /dev/null +++ b/scripts/2.5/node_modules/object.entries/shim.js @@ -0,0 +1,14 @@ +'use strict'; + +var getPolyfill = require('./polyfill'); +var define = require('define-properties'); + +module.exports = function shimEntries() { + var polyfill = getPolyfill(); + define(Object, { entries: polyfill }, { + entries: function testEntries() { + return Object.entries !== polyfill; + } + }); + return polyfill; +}; diff --git a/scripts/2.5/node_modules/object.entries/test/.eslintrc b/scripts/2.5/node_modules/object.entries/test/.eslintrc new file mode 100644 index 00000000..5bddce79 --- /dev/null +++ b/scripts/2.5/node_modules/object.entries/test/.eslintrc @@ -0,0 +1,11 @@ +{ + "rules": { + "array-bracket-newline": 0, + "max-lines-per-function": 0, + "max-nested-callbacks": [2, 3], + "max-statements": [2, 12], + "max-statements-per-line": [2, { "max": 3 }], + "no-invalid-this": [1], + "object-curly-newline": 0, + } +} diff --git a/scripts/2.5/node_modules/object.entries/test/index.js b/scripts/2.5/node_modules/object.entries/test/index.js new file mode 100644 index 00000000..1859a3f8 --- /dev/null +++ b/scripts/2.5/node_modules/object.entries/test/index.js @@ -0,0 +1,17 @@ +'use strict'; + +var entries = require('../'); +var test = require('tape'); +var runTests = require('./tests'); + +test('as a function', function (t) { + t.test('bad array/this value', function (st) { + st['throws'](function () { entries(undefined); }, TypeError, 'undefined is not an object'); + st['throws'](function () { entries(null); }, TypeError, 'null is not an object'); + st.end(); + }); + + runTests(entries, t); + + t.end(); +}); diff --git a/scripts/2.5/node_modules/object.entries/test/shimmed.js b/scripts/2.5/node_modules/object.entries/test/shimmed.js new file mode 100644 index 00000000..3f1d3770 --- /dev/null +++ b/scripts/2.5/node_modules/object.entries/test/shimmed.js @@ -0,0 +1,36 @@ +'use strict'; + +var entries = require('../'); +entries.shim(); + +var test = require('tape'); +var defineProperties = require('define-properties'); +var isEnumerable = Object.prototype.propertyIsEnumerable; +var functionsHaveNames = function f() {}.name === 'f'; + +var runTests = require('./tests'); + +test('shimmed', function (t) { + t.equal(Object.entries.length, 1, 'Object.entries has a length of 1'); + t.test('Function name', { skip: !functionsHaveNames }, function (st) { + st.equal(Object.entries.name, 'entries', 'Object.entries has name "entries"'); + st.end(); + }); + + t.test('enumerability', { skip: !defineProperties.supportsDescriptors }, function (et) { + et.equal(false, isEnumerable.call(Object, 'entries'), 'Object.entries is not enumerable'); + et.end(); + }); + + var supportsStrictMode = (function () { return typeof this === 'undefined'; }()); + + t.test('bad object value', { skip: !supportsStrictMode }, function (st) { + st['throws'](function () { return Object.entries(undefined); }, TypeError, 'undefined is not an object'); + st['throws'](function () { return Object.entries(null); }, TypeError, 'null is not an object'); + st.end(); + }); + + runTests(Object.entries, t); + + t.end(); +}); diff --git a/scripts/2.5/node_modules/object.entries/test/tests.js b/scripts/2.5/node_modules/object.entries/test/tests.js new file mode 100644 index 00000000..03b8613e --- /dev/null +++ b/scripts/2.5/node_modules/object.entries/test/tests.js @@ -0,0 +1,84 @@ +'use strict'; + +/* global Symbol */ + +var keys = require('object-keys'); +var map = require('array-map'); +var define = require('define-properties'); + +var hasSymbols = typeof Symbol === 'function' && typeof Symbol('foo') === 'symbol'; + +module.exports = function (entries, t) { + var a = {}; + var b = {}; + var c = {}; + var obj = { a: a, b: b, c: c }; + + t.deepEqual(entries(obj), [['a', a], ['b', b], ['c', c]], 'basic support'); + t.deepEqual(entries({ a: a, b: a, c: c }), [['a', a], ['b', a], ['c', c]], 'duplicate entries are included'); + + t.test('entries are in the same order as keys', function (st) { + var object = { a: a, b: b }; + object[0] = 3; + object.c = c; + object[1] = 4; + delete object[0]; + var objKeys = keys(object); + var objEntries = map(objKeys, function (key) { + return [key, object[key]]; + }); + st.deepEqual(entries(object), objEntries, 'entries match key order'); + st.end(); + }); + + t.test('non-enumerable properties are omitted', { skip: !Object.defineProperty }, function (st) { + var object = { a: a, b: b }; + Object.defineProperty(object, 'c', { enumerable: false, value: c }); + st.deepEqual(entries(object), [['a', a], ['b', b]], 'non-enumerable property‘s value is omitted'); + st.end(); + }); + + t.test('inherited properties are omitted', function (st) { + var F = function G() {}; + F.prototype.a = a; + var f = new F(); + f.b = b; + st.deepEqual(entries(f), [['b', b]], 'only own properties are included'); + st.end(); + }); + + t.test('Symbol properties are omitted', { skip: !hasSymbols }, function (st) { + var object = { a: a, b: b, c: c }; + var enumSym = Symbol('enum'); + var nonEnumSym = Symbol('non enum'); + object[enumSym] = enumSym; + object.d = enumSym; + Object.defineProperty(object, nonEnumSym, { enumerable: false, value: nonEnumSym }); + st.deepEqual(entries(object), [['a', a], ['b', b], ['c', c], ['d', enumSym]], 'symbol properties are omitted'); + st.end(); + }); + + t.test('not-yet-visited keys deleted on [[Get]] must not show up in output', { skip: !define.supportsDescriptors }, function (st) { + var o = { a: 1, b: 2, c: 3 }; + Object.defineProperty(o, 'a', { + get: function () { + delete this.b; + return 1; + } + }); + st.deepEqual(entries(o), [['a', 1], ['c', 3]], 'when "b" is deleted prior to being visited, it should not show up'); + st.end(); + }); + + t.test('not-yet-visited keys made non-enumerable on [[Get]] must not show up in output', { skip: !define.supportsDescriptors }, function (st) { + var o = { a: 'A', b: 'B' }; + Object.defineProperty(o, 'a', { + get: function () { + Object.defineProperty(o, 'b', { enumerable: false }); + return 'A'; + } + }); + st.deepEqual(entries(o), [['a', 'A']], 'when "b" is made non-enumerable prior to being visited, it should not show up'); + st.end(); + }); +}; diff --git a/scripts/2.5/node_modules/require_optional/.npmignore b/scripts/2.5/node_modules/require_optional/.npmignore new file mode 100644 index 00000000..e920c167 --- /dev/null +++ b/scripts/2.5/node_modules/require_optional/.npmignore @@ -0,0 +1,33 @@ +# Logs +logs +*.log +npm-debug.log* + +# Runtime data +pids +*.pid +*.seed + +# Directory for instrumented libs generated by jscoverage/JSCover +lib-cov + +# Coverage directory used by tools like istanbul +coverage + +# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) +.grunt + +# node-waf configuration +.lock-wscript + +# Compiled binary addons (http://nodejs.org/api/addons.html) +build/Release + +# Dependency directory +node_modules + +# Optional npm cache directory +.npm + +# Optional REPL history +.node_repl_history diff --git a/scripts/2.5/node_modules/require_optional/.travis.yml b/scripts/2.5/node_modules/require_optional/.travis.yml new file mode 100644 index 00000000..72903c34 --- /dev/null +++ b/scripts/2.5/node_modules/require_optional/.travis.yml @@ -0,0 +1,9 @@ +language: node_js +node_js: + - "0.10" + - "0.12" + - "4" + - "6" + - "7" + - "8" +sudo: false diff --git a/scripts/2.5/node_modules/require_optional/HISTORY.md b/scripts/2.5/node_modules/require_optional/HISTORY.md new file mode 100644 index 00000000..7bee02fc --- /dev/null +++ b/scripts/2.5/node_modules/require_optional/HISTORY.md @@ -0,0 +1,7 @@ +1.0.1 03-02-2016 +================ +* Fix dependency resolution issue when a component in peerOptionalDependencies is installed at the level of the module declaring in peerOptionalDependencies. + +1.0.0 03-02-2016 +================ +* Initial release allowing us to optionally resolve dependencies in the package.json file under the peerOptionalDependencies tag. \ No newline at end of file diff --git a/scripts/2.5/node_modules/require_optional/LICENSE b/scripts/2.5/node_modules/require_optional/LICENSE new file mode 100644 index 00000000..8dada3ed --- /dev/null +++ b/scripts/2.5/node_modules/require_optional/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/scripts/2.5/node_modules/require_optional/README.md b/scripts/2.5/node_modules/require_optional/README.md new file mode 100644 index 00000000..c0323f06 --- /dev/null +++ b/scripts/2.5/node_modules/require_optional/README.md @@ -0,0 +1,2 @@ +# require_optional +Work around the problem that we do not have a optionalPeerDependencies concept in node.js making it a hassle to optionally include native modules diff --git a/scripts/2.5/node_modules/require_optional/index.js b/scripts/2.5/node_modules/require_optional/index.js new file mode 100644 index 00000000..3710319f --- /dev/null +++ b/scripts/2.5/node_modules/require_optional/index.js @@ -0,0 +1,128 @@ +var path = require('path'), + fs = require('fs'), + f = require('util').format, + resolveFrom = require('resolve-from'), + semver = require('semver'); + +var exists = fs.existsSync || path.existsSync; + +// Find the location of a package.json file near or above the given location +var find_package_json = function(location) { + var found = false; + + while(!found) { + if (exists(location + '/package.json')) { + found = location; + } else if (location !== '/') { + location = path.dirname(location); + } else { + return false; + } + } + + return location; +} + +// Find the package.json object of the module closest up the module call tree that contains name in that module's peerOptionalDependencies +var find_package_json_with_name = function(name) { + // Walk up the module call tree until we find a module containing name in its peerOptionalDependencies + var currentModule = module; + var found = false; + while (currentModule) { + // Check currentModule has a package.json + location = currentModule.filename; + var location = find_package_json(location) + if (!location) { + currentModule = currentModule.parent; + continue; + } + + // Read the package.json file + var object = JSON.parse(fs.readFileSync(f('%s/package.json', location))); + // Is the name defined by interal file references + var parts = name.split(/\//); + + // Check whether this package.json contains peerOptionalDependencies containing the name we're searching for + if (!object.peerOptionalDependencies || (object.peerOptionalDependencies && !object.peerOptionalDependencies[parts[0]])) { + currentModule = currentModule.parent; + continue; + } + found = true; + break; + } + + // Check whether name has been found in currentModule's peerOptionalDependencies + if (!found) { + throw new Error(f('no optional dependency [%s] defined in peerOptionalDependencies in any package.json', parts[0])); + } + + return { + object: object, + parts: parts + } +} + +var require_optional = function(name, options) { + options = options || {}; + options.strict = typeof options.strict == 'boolean' ? options.strict : true; + + var res = find_package_json_with_name(name) + var object = res.object; + var parts = res.parts; + + // Unpack the expected version + var expectedVersions = object.peerOptionalDependencies[parts[0]]; + // The resolved package + var moduleEntry = undefined; + // Module file + var moduleEntryFile = name; + + try { + // Validate if it's possible to read the module + moduleEntry = require(moduleEntryFile); + } catch(err) { + // Attempt to resolve in top level package + try { + // Get the module entry file + moduleEntryFile = resolveFrom(process.cwd(), name); + if(moduleEntryFile == null) return undefined; + // Attempt to resolve the module + moduleEntry = require(moduleEntryFile); + } catch(err) { + if(err.code === 'MODULE_NOT_FOUND') return undefined; + } + } + + // Resolve the location of the module's package.json file + var location = find_package_json(require.resolve(moduleEntryFile)); + if(!location) { + throw new Error('package.json can not be located'); + } + + // Read the module file + var dependentOnModule = JSON.parse(fs.readFileSync(f('%s/package.json', location))); + // Get the version + var version = dependentOnModule.version; + // Validate if the found module satisfies the version id + if(semver.satisfies(version, expectedVersions) == false + && options.strict) { + var error = new Error(f('optional dependency [%s] found but version [%s] did not satisfy constraint [%s]', parts[0], version, expectedVersions)); + error.code = 'OPTIONAL_MODULE_NOT_FOUND'; + throw error; + } + + // Satifies the module requirement + return moduleEntry; +} + +require_optional.exists = function(name) { + try { + var m = require_optional(name); + if(m === undefined) return false; + return true; + } catch(err) { + return false; + } +} + +module.exports = require_optional; diff --git a/scripts/2.5/node_modules/require_optional/package.json b/scripts/2.5/node_modules/require_optional/package.json new file mode 100644 index 00000000..962396b0 --- /dev/null +++ b/scripts/2.5/node_modules/require_optional/package.json @@ -0,0 +1,67 @@ +{ + "_from": "require_optional@^1.0.1", + "_id": "require_optional@1.0.1", + "_inBundle": false, + "_integrity": "sha512-qhM/y57enGWHAe3v/NcwML6a3/vfESLe/sGM2dII+gEO0BpKRUkWZow/tyloNqJyN6kXSl3RyyM8Ll5D/sJP8g==", + "_location": "/require_optional", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "require_optional@^1.0.1", + "name": "require_optional", + "escapedName": "require_optional", + "rawSpec": "^1.0.1", + "saveSpec": null, + "fetchSpec": "^1.0.1" + }, + "_requiredBy": [ + "/mongodb" + ], + "_resolved": "https://registry.npmjs.org/require_optional/-/require_optional-1.0.1.tgz", + "_shasum": "4cf35a4247f64ca3df8c2ef208cc494b1ca8fc2e", + "_spec": "require_optional@^1.0.1", + "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/2.5/node_modules/mongodb", + "author": { + "name": "Christian Kvalheim Amor" + }, + "bugs": { + "url": "https://github.com/christkv/require_optional/issues" + }, + "bundleDependencies": false, + "dependencies": { + "resolve-from": "^2.0.0", + "semver": "^5.1.0" + }, + "deprecated": false, + "description": "Allows you declare optionalPeerDependencies that can be satisfied by the top level module but ignored if they are not.", + "devDependencies": { + "bson": "0.4.21", + "co": "4.6.0", + "es6-promise": "^3.0.2", + "mocha": "^2.4.5" + }, + "homepage": "https://github.com/christkv/require_optional", + "keywords": [ + "optional", + "require", + "optionalPeerDependencies" + ], + "license": "Apache-2.0", + "main": "index.js", + "name": "require_optional", + "peerOptionalDependencies": { + "co": ">=5.6.0", + "es6-promise": "^3.0.2", + "es6-promise2": "^4.0.2", + "bson": "0.4.21" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/christkv/require_optional.git" + }, + "scripts": { + "test": "mocha" + }, + "version": "1.0.1" +} diff --git a/scripts/2.5/node_modules/require_optional/test/nestedTest/index.js b/scripts/2.5/node_modules/require_optional/test/nestedTest/index.js new file mode 100644 index 00000000..76de2ab4 --- /dev/null +++ b/scripts/2.5/node_modules/require_optional/test/nestedTest/index.js @@ -0,0 +1,8 @@ +var require_optional = require('../../') + +function findPackage(packageName) { + var pkg = require_optional(packageName); + return pkg; +} + +module.exports.findPackage = findPackage diff --git a/scripts/2.5/node_modules/require_optional/test/nestedTest/package.json b/scripts/2.5/node_modules/require_optional/test/nestedTest/package.json new file mode 100644 index 00000000..4c456a6b --- /dev/null +++ b/scripts/2.5/node_modules/require_optional/test/nestedTest/package.json @@ -0,0 +1,11 @@ +{ + "name": "nestedtest", + "version": "1.0.0", + "description": "A dummy package that facilitates testing that require_optional correctly walks up the module call stack", + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "author": "Sebastian Hallum Clarke", + "license": "ISC" +} diff --git a/scripts/2.5/node_modules/require_optional/test/require_optional_tests.js b/scripts/2.5/node_modules/require_optional/test/require_optional_tests.js new file mode 100644 index 00000000..c9cc2a36 --- /dev/null +++ b/scripts/2.5/node_modules/require_optional/test/require_optional_tests.js @@ -0,0 +1,59 @@ +var assert = require('assert'), + require_optional = require('../'), + nestedTest = require('./nestedTest'); + +describe('Require Optional', function() { + describe('top level require', function() { + it('should correctly require co library', function() { + var promise = require_optional('es6-promise'); + assert.ok(promise); + }); + + it('should fail to require es6-promise library', function() { + try { + require_optional('co'); + } catch(e) { + assert.equal('OPTIONAL_MODULE_NOT_FOUND', e.code); + return; + } + + assert.ok(false); + }); + + it('should ignore optional library not defined', function() { + assert.equal(undefined, require_optional('es6-promise2')); + }); + }); + + describe('internal module file require', function() { + it('should correctly require co library', function() { + var Long = require_optional('bson/lib/bson/long.js'); + assert.ok(Long); + }); + }); + + describe('top level resolve', function() { + it('should correctly use exists method', function() { + assert.equal(false, require_optional.exists('co')); + assert.equal(true, require_optional.exists('es6-promise')); + assert.equal(true, require_optional.exists('bson/lib/bson/long.js')); + assert.equal(false, require_optional.exists('es6-promise2')); + }); + }); + + describe('require_optional inside dependencies', function() { + it('should correctly walk up module call stack searching for peerOptionalDependencies', function() { + assert.ok(nestedTest.findPackage('bson')) + }); + it('should return null when a package is defined in top-level package.json but not installed', function() { + assert.equal(null, nestedTest.findPackage('es6-promise2')) + }); + it('should error when searching for an optional dependency that is not defined in any ancestor package.json', function() { + try { + nestedTest.findPackage('bison') + } catch (err) { + assert.equal(err.message, 'no optional dependency [bison] defined in peerOptionalDependencies in any package.json') + } + }) + }); +}); diff --git a/scripts/2.5/node_modules/resolve-from/index.js b/scripts/2.5/node_modules/resolve-from/index.js new file mode 100644 index 00000000..434159f1 --- /dev/null +++ b/scripts/2.5/node_modules/resolve-from/index.js @@ -0,0 +1,23 @@ +'use strict'; +var path = require('path'); +var Module = require('module'); + +module.exports = function (fromDir, moduleId) { + if (typeof fromDir !== 'string' || typeof moduleId !== 'string') { + throw new TypeError('Expected `fromDir` and `moduleId` to be a string'); + } + + fromDir = path.resolve(fromDir); + + var fromFile = path.join(fromDir, 'noop.js'); + + try { + return Module._resolveFilename(moduleId, { + id: fromFile, + filename: fromFile, + paths: Module._nodeModulePaths(fromDir) + }); + } catch (err) { + return null; + } +}; diff --git a/scripts/2.5/node_modules/resolve-from/license b/scripts/2.5/node_modules/resolve-from/license new file mode 100644 index 00000000..654d0bfe --- /dev/null +++ b/scripts/2.5/node_modules/resolve-from/license @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/scripts/2.5/node_modules/resolve-from/package.json b/scripts/2.5/node_modules/resolve-from/package.json new file mode 100644 index 00000000..d0d20afd --- /dev/null +++ b/scripts/2.5/node_modules/resolve-from/package.json @@ -0,0 +1,66 @@ +{ + "_from": "resolve-from@^2.0.0", + "_id": "resolve-from@2.0.0", + "_inBundle": false, + "_integrity": "sha1-lICrIOlP+h2egKgEx+oUdhGWa1c=", + "_location": "/resolve-from", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "resolve-from@^2.0.0", + "name": "resolve-from", + "escapedName": "resolve-from", + "rawSpec": "^2.0.0", + "saveSpec": null, + "fetchSpec": "^2.0.0" + }, + "_requiredBy": [ + "/require_optional" + ], + "_resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-2.0.0.tgz", + "_shasum": "9480ab20e94ffa1d9e80a804c7ea147611966b57", + "_spec": "resolve-from@^2.0.0", + "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/2.5/node_modules/require_optional", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "bugs": { + "url": "https://github.com/sindresorhus/resolve-from/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "Resolve the path of a module like require.resolve() but from a given path", + "devDependencies": { + "ava": "*", + "xo": "*" + }, + "engines": { + "node": ">=0.10.0" + }, + "files": [ + "index.js" + ], + "homepage": "https://github.com/sindresorhus/resolve-from#readme", + "keywords": [ + "require", + "resolve", + "path", + "module", + "from", + "like", + "path" + ], + "license": "MIT", + "name": "resolve-from", + "repository": { + "type": "git", + "url": "git+https://github.com/sindresorhus/resolve-from.git" + }, + "scripts": { + "test": "xo && ava" + }, + "version": "2.0.0" +} diff --git a/scripts/2.5/node_modules/resolve-from/readme.md b/scripts/2.5/node_modules/resolve-from/readme.md new file mode 100644 index 00000000..bb4ca91e --- /dev/null +++ b/scripts/2.5/node_modules/resolve-from/readme.md @@ -0,0 +1,58 @@ +# resolve-from [![Build Status](https://travis-ci.org/sindresorhus/resolve-from.svg?branch=master)](https://travis-ci.org/sindresorhus/resolve-from) + +> Resolve the path of a module like [`require.resolve()`](http://nodejs.org/api/globals.html#globals_require_resolve) but from a given path + +Unlike `require.resolve()` it returns `null` instead of throwing when the module can't be found. + + +## Install + +``` +$ npm install --save resolve-from +``` + + +## Usage + +```js +const resolveFrom = require('resolve-from'); + +// there's a file at `./foo/bar.js` + +resolveFrom('foo', './bar'); +//=> '/Users/sindresorhus/dev/test/foo/bar.js' +``` + + +## API + +### resolveFrom(fromDir, moduleId) + +#### fromDir + +Type: `string` + +Directory to resolve from. + +#### moduleId + +Type: `string` + +What you would use in `require()`. + + +## Tip + +Create a partial using a bound function if you want to require from the same `fromDir` multiple times: + +```js +const resolveFromFoo = resolveFrom.bind(null, 'foo'); + +resolveFromFoo('./bar'); +resolveFromFoo('./baz'); +``` + + +## License + +MIT © [Sindre Sorhus](http://sindresorhus.com) diff --git a/scripts/2.5/node_modules/safe-buffer/LICENSE b/scripts/2.5/node_modules/safe-buffer/LICENSE new file mode 100644 index 00000000..0c068cee --- /dev/null +++ b/scripts/2.5/node_modules/safe-buffer/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Feross Aboukhadijeh + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/scripts/2.5/node_modules/safe-buffer/README.md b/scripts/2.5/node_modules/safe-buffer/README.md new file mode 100644 index 00000000..356e3519 --- /dev/null +++ b/scripts/2.5/node_modules/safe-buffer/README.md @@ -0,0 +1,586 @@ +# safe-buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] + +[travis-image]: https://img.shields.io/travis/feross/safe-buffer/master.svg +[travis-url]: https://travis-ci.org/feross/safe-buffer +[npm-image]: https://img.shields.io/npm/v/safe-buffer.svg +[npm-url]: https://npmjs.org/package/safe-buffer +[downloads-image]: https://img.shields.io/npm/dm/safe-buffer.svg +[downloads-url]: https://npmjs.org/package/safe-buffer +[standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg +[standard-url]: https://standardjs.com + +#### Safer Node.js Buffer API + +**Use the new Node.js Buffer APIs (`Buffer.from`, `Buffer.alloc`, +`Buffer.allocUnsafe`, `Buffer.allocUnsafeSlow`) in all versions of Node.js.** + +**Uses the built-in implementation when available.** + +## install + +``` +npm install safe-buffer +``` + +[Get supported safe-buffer with the Tidelift Subscription](https://tidelift.com/subscription/pkg/npm-safe-buffer?utm_source=npm-safe-buffer&utm_medium=referral&utm_campaign=readme) + +## usage + +The goal of this package is to provide a safe replacement for the node.js `Buffer`. + +It's a drop-in replacement for `Buffer`. You can use it by adding one `require` line to +the top of your node.js modules: + +```js +var Buffer = require('safe-buffer').Buffer + +// Existing buffer code will continue to work without issues: + +new Buffer('hey', 'utf8') +new Buffer([1, 2, 3], 'utf8') +new Buffer(obj) +new Buffer(16) // create an uninitialized buffer (potentially unsafe) + +// But you can use these new explicit APIs to make clear what you want: + +Buffer.from('hey', 'utf8') // convert from many types to a Buffer +Buffer.alloc(16) // create a zero-filled buffer (safe) +Buffer.allocUnsafe(16) // create an uninitialized buffer (potentially unsafe) +``` + +## api + +### Class Method: Buffer.from(array) + + +* `array` {Array} + +Allocates a new `Buffer` using an `array` of octets. + +```js +const buf = Buffer.from([0x62,0x75,0x66,0x66,0x65,0x72]); + // creates a new Buffer containing ASCII bytes + // ['b','u','f','f','e','r'] +``` + +A `TypeError` will be thrown if `array` is not an `Array`. + +### Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]]) + + +* `arrayBuffer` {ArrayBuffer} The `.buffer` property of a `TypedArray` or + a `new ArrayBuffer()` +* `byteOffset` {Number} Default: `0` +* `length` {Number} Default: `arrayBuffer.length - byteOffset` + +When passed a reference to the `.buffer` property of a `TypedArray` instance, +the newly created `Buffer` will share the same allocated memory as the +TypedArray. + +```js +const arr = new Uint16Array(2); +arr[0] = 5000; +arr[1] = 4000; + +const buf = Buffer.from(arr.buffer); // shares the memory with arr; + +console.log(buf); + // Prints: + +// changing the TypedArray changes the Buffer also +arr[1] = 6000; + +console.log(buf); + // Prints: +``` + +The optional `byteOffset` and `length` arguments specify a memory range within +the `arrayBuffer` that will be shared by the `Buffer`. + +```js +const ab = new ArrayBuffer(10); +const buf = Buffer.from(ab, 0, 2); +console.log(buf.length); + // Prints: 2 +``` + +A `TypeError` will be thrown if `arrayBuffer` is not an `ArrayBuffer`. + +### Class Method: Buffer.from(buffer) + + +* `buffer` {Buffer} + +Copies the passed `buffer` data onto a new `Buffer` instance. + +```js +const buf1 = Buffer.from('buffer'); +const buf2 = Buffer.from(buf1); + +buf1[0] = 0x61; +console.log(buf1.toString()); + // 'auffer' +console.log(buf2.toString()); + // 'buffer' (copy is not changed) +``` + +A `TypeError` will be thrown if `buffer` is not a `Buffer`. + +### Class Method: Buffer.from(str[, encoding]) + + +* `str` {String} String to encode. +* `encoding` {String} Encoding to use, Default: `'utf8'` + +Creates a new `Buffer` containing the given JavaScript string `str`. If +provided, the `encoding` parameter identifies the character encoding. +If not provided, `encoding` defaults to `'utf8'`. + +```js +const buf1 = Buffer.from('this is a tést'); +console.log(buf1.toString()); + // prints: this is a tést +console.log(buf1.toString('ascii')); + // prints: this is a tC)st + +const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex'); +console.log(buf2.toString()); + // prints: this is a tést +``` + +A `TypeError` will be thrown if `str` is not a string. + +### Class Method: Buffer.alloc(size[, fill[, encoding]]) + + +* `size` {Number} +* `fill` {Value} Default: `undefined` +* `encoding` {String} Default: `utf8` + +Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the +`Buffer` will be *zero-filled*. + +```js +const buf = Buffer.alloc(5); +console.log(buf); + // +``` + +The `size` must be less than or equal to the value of +`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is +`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will +be created if a `size` less than or equal to 0 is specified. + +If `fill` is specified, the allocated `Buffer` will be initialized by calling +`buf.fill(fill)`. See [`buf.fill()`][] for more information. + +```js +const buf = Buffer.alloc(5, 'a'); +console.log(buf); + // +``` + +If both `fill` and `encoding` are specified, the allocated `Buffer` will be +initialized by calling `buf.fill(fill, encoding)`. For example: + +```js +const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); +console.log(buf); + // +``` + +Calling `Buffer.alloc(size)` can be significantly slower than the alternative +`Buffer.allocUnsafe(size)` but ensures that the newly created `Buffer` instance +contents will *never contain sensitive data*. + +A `TypeError` will be thrown if `size` is not a number. + +### Class Method: Buffer.allocUnsafe(size) + + +* `size` {Number} + +Allocates a new *non-zero-filled* `Buffer` of `size` bytes. The `size` must +be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit +architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is +thrown. A zero-length Buffer will be created if a `size` less than or equal to +0 is specified. + +The underlying memory for `Buffer` instances created in this way is *not +initialized*. The contents of the newly created `Buffer` are unknown and +*may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such +`Buffer` instances to zeroes. + +```js +const buf = Buffer.allocUnsafe(5); +console.log(buf); + // + // (octets will be different, every time) +buf.fill(0); +console.log(buf); + // +``` + +A `TypeError` will be thrown if `size` is not a number. + +Note that the `Buffer` module pre-allocates an internal `Buffer` instance of +size `Buffer.poolSize` that is used as a pool for the fast allocation of new +`Buffer` instances created using `Buffer.allocUnsafe(size)` (and the deprecated +`new Buffer(size)` constructor) only when `size` is less than or equal to +`Buffer.poolSize >> 1` (floor of `Buffer.poolSize` divided by two). The default +value of `Buffer.poolSize` is `8192` but can be modified. + +Use of this pre-allocated internal memory pool is a key difference between +calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`. +Specifically, `Buffer.alloc(size, fill)` will *never* use the internal Buffer +pool, while `Buffer.allocUnsafe(size).fill(fill)` *will* use the internal +Buffer pool if `size` is less than or equal to half `Buffer.poolSize`. The +difference is subtle but can be important when an application requires the +additional performance that `Buffer.allocUnsafe(size)` provides. + +### Class Method: Buffer.allocUnsafeSlow(size) + + +* `size` {Number} + +Allocates a new *non-zero-filled* and non-pooled `Buffer` of `size` bytes. The +`size` must be less than or equal to the value of +`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is +`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will +be created if a `size` less than or equal to 0 is specified. + +The underlying memory for `Buffer` instances created in this way is *not +initialized*. The contents of the newly created `Buffer` are unknown and +*may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such +`Buffer` instances to zeroes. + +When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances, +allocations under 4KB are, by default, sliced from a single pre-allocated +`Buffer`. This allows applications to avoid the garbage collection overhead of +creating many individually allocated Buffers. This approach improves both +performance and memory usage by eliminating the need to track and cleanup as +many `Persistent` objects. + +However, in the case where a developer may need to retain a small chunk of +memory from a pool for an indeterminate amount of time, it may be appropriate +to create an un-pooled Buffer instance using `Buffer.allocUnsafeSlow()` then +copy out the relevant bits. + +```js +// need to keep around a few small chunks of memory +const store = []; + +socket.on('readable', () => { + const data = socket.read(); + // allocate for retained data + const sb = Buffer.allocUnsafeSlow(10); + // copy the data into the new allocation + data.copy(sb, 0, 0, 10); + store.push(sb); +}); +``` + +Use of `Buffer.allocUnsafeSlow()` should be used only as a last resort *after* +a developer has observed undue memory retention in their applications. + +A `TypeError` will be thrown if `size` is not a number. + +### All the Rest + +The rest of the `Buffer` API is exactly the same as in node.js. +[See the docs](https://nodejs.org/api/buffer.html). + + +## Related links + +- [Node.js issue: Buffer(number) is unsafe](https://github.com/nodejs/node/issues/4660) +- [Node.js Enhancement Proposal: Buffer.from/Buffer.alloc/Buffer.zalloc/Buffer() soft-deprecate](https://github.com/nodejs/node-eps/pull/4) + +## Why is `Buffer` unsafe? + +Today, the node.js `Buffer` constructor is overloaded to handle many different argument +types like `String`, `Array`, `Object`, `TypedArrayView` (`Uint8Array`, etc.), +`ArrayBuffer`, and also `Number`. + +The API is optimized for convenience: you can throw any type at it, and it will try to do +what you want. + +Because the Buffer constructor is so powerful, you often see code like this: + +```js +// Convert UTF-8 strings to hex +function toHex (str) { + return new Buffer(str).toString('hex') +} +``` + +***But what happens if `toHex` is called with a `Number` argument?*** + +### Remote Memory Disclosure + +If an attacker can make your program call the `Buffer` constructor with a `Number` +argument, then they can make it allocate uninitialized memory from the node.js process. +This could potentially disclose TLS private keys, user data, or database passwords. + +When the `Buffer` constructor is passed a `Number` argument, it returns an +**UNINITIALIZED** block of memory of the specified `size`. When you create a `Buffer` like +this, you **MUST** overwrite the contents before returning it to the user. + +From the [node.js docs](https://nodejs.org/api/buffer.html#buffer_new_buffer_size): + +> `new Buffer(size)` +> +> - `size` Number +> +> The underlying memory for `Buffer` instances created in this way is not initialized. +> **The contents of a newly created `Buffer` are unknown and could contain sensitive +> data.** Use `buf.fill(0)` to initialize a Buffer to zeroes. + +(Emphasis our own.) + +Whenever the programmer intended to create an uninitialized `Buffer` you often see code +like this: + +```js +var buf = new Buffer(16) + +// Immediately overwrite the uninitialized buffer with data from another buffer +for (var i = 0; i < buf.length; i++) { + buf[i] = otherBuf[i] +} +``` + + +### Would this ever be a problem in real code? + +Yes. It's surprisingly common to forget to check the type of your variables in a +dynamically-typed language like JavaScript. + +Usually the consequences of assuming the wrong type is that your program crashes with an +uncaught exception. But the failure mode for forgetting to check the type of arguments to +the `Buffer` constructor is more catastrophic. + +Here's an example of a vulnerable service that takes a JSON payload and converts it to +hex: + +```js +// Take a JSON payload {str: "some string"} and convert it to hex +var server = http.createServer(function (req, res) { + var data = '' + req.setEncoding('utf8') + req.on('data', function (chunk) { + data += chunk + }) + req.on('end', function () { + var body = JSON.parse(data) + res.end(new Buffer(body.str).toString('hex')) + }) +}) + +server.listen(8080) +``` + +In this example, an http client just has to send: + +```json +{ + "str": 1000 +} +``` + +and it will get back 1,000 bytes of uninitialized memory from the server. + +This is a very serious bug. It's similar in severity to the +[the Heartbleed bug](http://heartbleed.com/) that allowed disclosure of OpenSSL process +memory by remote attackers. + + +### Which real-world packages were vulnerable? + +#### [`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht) + +[Mathias Buus](https://github.com/mafintosh) and I +([Feross Aboukhadijeh](http://feross.org/)) found this issue in one of our own packages, +[`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht). The bug would allow +anyone on the internet to send a series of messages to a user of `bittorrent-dht` and get +them to reveal 20 bytes at a time of uninitialized memory from the node.js process. + +Here's +[the commit](https://github.com/feross/bittorrent-dht/commit/6c7da04025d5633699800a99ec3fbadf70ad35b8) +that fixed it. We released a new fixed version, created a +[Node Security Project disclosure](https://nodesecurity.io/advisories/68), and deprecated all +vulnerable versions on npm so users will get a warning to upgrade to a newer version. + +#### [`ws`](https://www.npmjs.com/package/ws) + +That got us wondering if there were other vulnerable packages. Sure enough, within a short +period of time, we found the same issue in [`ws`](https://www.npmjs.com/package/ws), the +most popular WebSocket implementation in node.js. + +If certain APIs were called with `Number` parameters instead of `String` or `Buffer` as +expected, then uninitialized server memory would be disclosed to the remote peer. + +These were the vulnerable methods: + +```js +socket.send(number) +socket.ping(number) +socket.pong(number) +``` + +Here's a vulnerable socket server with some echo functionality: + +```js +server.on('connection', function (socket) { + socket.on('message', function (message) { + message = JSON.parse(message) + if (message.type === 'echo') { + socket.send(message.data) // send back the user's message + } + }) +}) +``` + +`socket.send(number)` called on the server, will disclose server memory. + +Here's [the release](https://github.com/websockets/ws/releases/tag/1.0.1) where the issue +was fixed, with a more detailed explanation. Props to +[Arnout Kazemier](https://github.com/3rd-Eden) for the quick fix. Here's the +[Node Security Project disclosure](https://nodesecurity.io/advisories/67). + + +### What's the solution? + +It's important that node.js offers a fast way to get memory otherwise performance-critical +applications would needlessly get a lot slower. + +But we need a better way to *signal our intent* as programmers. **When we want +uninitialized memory, we should request it explicitly.** + +Sensitive functionality should not be packed into a developer-friendly API that loosely +accepts many different types. This type of API encourages the lazy practice of passing +variables in without checking the type very carefully. + +#### A new API: `Buffer.allocUnsafe(number)` + +The functionality of creating buffers with uninitialized memory should be part of another +API. We propose `Buffer.allocUnsafe(number)`. This way, it's not part of an API that +frequently gets user input of all sorts of different types passed into it. + +```js +var buf = Buffer.allocUnsafe(16) // careful, uninitialized memory! + +// Immediately overwrite the uninitialized buffer with data from another buffer +for (var i = 0; i < buf.length; i++) { + buf[i] = otherBuf[i] +} +``` + + +### How do we fix node.js core? + +We sent [a PR to node.js core](https://github.com/nodejs/node/pull/4514) (merged as +`semver-major`) which defends against one case: + +```js +var str = 16 +new Buffer(str, 'utf8') +``` + +In this situation, it's implied that the programmer intended the first argument to be a +string, since they passed an encoding as a second argument. Today, node.js will allocate +uninitialized memory in the case of `new Buffer(number, encoding)`, which is probably not +what the programmer intended. + +But this is only a partial solution, since if the programmer does `new Buffer(variable)` +(without an `encoding` parameter) there's no way to know what they intended. If `variable` +is sometimes a number, then uninitialized memory will sometimes be returned. + +### What's the real long-term fix? + +We could deprecate and remove `new Buffer(number)` and use `Buffer.allocUnsafe(number)` when +we need uninitialized memory. But that would break 1000s of packages. + +~~We believe the best solution is to:~~ + +~~1. Change `new Buffer(number)` to return safe, zeroed-out memory~~ + +~~2. Create a new API for creating uninitialized Buffers. We propose: `Buffer.allocUnsafe(number)`~~ + +#### Update + +We now support adding three new APIs: + +- `Buffer.from(value)` - convert from any type to a buffer +- `Buffer.alloc(size)` - create a zero-filled buffer +- `Buffer.allocUnsafe(size)` - create an uninitialized buffer with given size + +This solves the core problem that affected `ws` and `bittorrent-dht` which is +`Buffer(variable)` getting tricked into taking a number argument. + +This way, existing code continues working and the impact on the npm ecosystem will be +minimal. Over time, npm maintainers can migrate performance-critical code to use +`Buffer.allocUnsafe(number)` instead of `new Buffer(number)`. + + +### Conclusion + +We think there's a serious design issue with the `Buffer` API as it exists today. It +promotes insecure software by putting high-risk functionality into a convenient API +with friendly "developer ergonomics". + +This wasn't merely a theoretical exercise because we found the issue in some of the +most popular npm packages. + +Fortunately, there's an easy fix that can be applied today. Use `safe-buffer` in place of +`buffer`. + +```js +var Buffer = require('safe-buffer').Buffer +``` + +Eventually, we hope that node.js core can switch to this new, safer behavior. We believe +the impact on the ecosystem would be minimal since it's not a breaking change. +Well-maintained, popular packages would be updated to use `Buffer.alloc` quickly, while +older, insecure packages would magically become safe from this attack vector. + + +## links + +- [Node.js PR: buffer: throw if both length and enc are passed](https://github.com/nodejs/node/pull/4514) +- [Node Security Project disclosure for `ws`](https://nodesecurity.io/advisories/67) +- [Node Security Project disclosure for`bittorrent-dht`](https://nodesecurity.io/advisories/68) + + +## credit + +The original issues in `bittorrent-dht` +([disclosure](https://nodesecurity.io/advisories/68)) and +`ws` ([disclosure](https://nodesecurity.io/advisories/67)) were discovered by +[Mathias Buus](https://github.com/mafintosh) and +[Feross Aboukhadijeh](http://feross.org/). + +Thanks to [Adam Baldwin](https://github.com/evilpacket) for helping disclose these issues +and for his work running the [Node Security Project](https://nodesecurity.io/). + +Thanks to [John Hiesey](https://github.com/jhiesey) for proofreading this README and +auditing the code. + + +## license + +MIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org) diff --git a/scripts/2.5/node_modules/safe-buffer/index.d.ts b/scripts/2.5/node_modules/safe-buffer/index.d.ts new file mode 100644 index 00000000..e9fed809 --- /dev/null +++ b/scripts/2.5/node_modules/safe-buffer/index.d.ts @@ -0,0 +1,187 @@ +declare module "safe-buffer" { + export class Buffer { + length: number + write(string: string, offset?: number, length?: number, encoding?: string): number; + toString(encoding?: string, start?: number, end?: number): string; + toJSON(): { type: 'Buffer', data: any[] }; + equals(otherBuffer: Buffer): boolean; + compare(otherBuffer: Buffer, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number; + copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; + slice(start?: number, end?: number): Buffer; + writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readUInt8(offset: number, noAssert?: boolean): number; + readUInt16LE(offset: number, noAssert?: boolean): number; + readUInt16BE(offset: number, noAssert?: boolean): number; + readUInt32LE(offset: number, noAssert?: boolean): number; + readUInt32BE(offset: number, noAssert?: boolean): number; + readInt8(offset: number, noAssert?: boolean): number; + readInt16LE(offset: number, noAssert?: boolean): number; + readInt16BE(offset: number, noAssert?: boolean): number; + readInt32LE(offset: number, noAssert?: boolean): number; + readInt32BE(offset: number, noAssert?: boolean): number; + readFloatLE(offset: number, noAssert?: boolean): number; + readFloatBE(offset: number, noAssert?: boolean): number; + readDoubleLE(offset: number, noAssert?: boolean): number; + readDoubleBE(offset: number, noAssert?: boolean): number; + swap16(): Buffer; + swap32(): Buffer; + swap64(): Buffer; + writeUInt8(value: number, offset: number, noAssert?: boolean): number; + writeUInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeInt8(value: number, offset: number, noAssert?: boolean): number; + writeInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeFloatLE(value: number, offset: number, noAssert?: boolean): number; + writeFloatBE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleLE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleBE(value: number, offset: number, noAssert?: boolean): number; + fill(value: any, offset?: number, end?: number): this; + indexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + lastIndexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean; + + /** + * Allocates a new buffer containing the given {str}. + * + * @param str String to store in buffer. + * @param encoding encoding to use, optional. Default is 'utf8' + */ + constructor (str: string, encoding?: string); + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + */ + constructor (size: number); + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + */ + constructor (array: Uint8Array); + /** + * Produces a Buffer backed by the same allocated memory as + * the given {ArrayBuffer}. + * + * + * @param arrayBuffer The ArrayBuffer with which to share memory. + */ + constructor (arrayBuffer: ArrayBuffer); + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + */ + constructor (array: any[]); + /** + * Copies the passed {buffer} data onto a new {Buffer} instance. + * + * @param buffer The buffer to copy. + */ + constructor (buffer: Buffer); + prototype: Buffer; + /** + * Allocates a new Buffer using an {array} of octets. + * + * @param array + */ + static from(array: any[]): Buffer; + /** + * When passed a reference to the .buffer property of a TypedArray instance, + * the newly created Buffer will share the same allocated memory as the TypedArray. + * The optional {byteOffset} and {length} arguments specify a memory range + * within the {arrayBuffer} that will be shared by the Buffer. + * + * @param arrayBuffer The .buffer property of a TypedArray or a new ArrayBuffer() + * @param byteOffset + * @param length + */ + static from(arrayBuffer: ArrayBuffer, byteOffset?: number, length?: number): Buffer; + /** + * Copies the passed {buffer} data onto a new Buffer instance. + * + * @param buffer + */ + static from(buffer: Buffer): Buffer; + /** + * Creates a new Buffer containing the given JavaScript string {str}. + * If provided, the {encoding} parameter identifies the character encoding. + * If not provided, {encoding} defaults to 'utf8'. + * + * @param str + */ + static from(str: string, encoding?: string): Buffer; + /** + * Returns true if {obj} is a Buffer + * + * @param obj object to test. + */ + static isBuffer(obj: any): obj is Buffer; + /** + * Returns true if {encoding} is a valid encoding argument. + * Valid string encodings in Node 0.12: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' + * + * @param encoding string to test. + */ + static isEncoding(encoding: string): boolean; + /** + * Gives the actual byte length of a string. encoding defaults to 'utf8'. + * This is not the same as String.prototype.length since that returns the number of characters in a string. + * + * @param string string to test. + * @param encoding encoding used to evaluate (defaults to 'utf8') + */ + static byteLength(string: string, encoding?: string): number; + /** + * Returns a buffer which is the result of concatenating all the buffers in the list together. + * + * If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer. + * If the list has exactly one item, then the first item of the list is returned. + * If the list has more than one item, then a new Buffer is created. + * + * @param list An array of Buffer objects to concatenate + * @param totalLength Total length of the buffers when concatenated. + * If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly. + */ + static concat(list: Buffer[], totalLength?: number): Buffer; + /** + * The same as buf1.compare(buf2). + */ + static compare(buf1: Buffer, buf2: Buffer): number; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @param fill if specified, buffer will be initialized by calling buf.fill(fill). + * If parameter is omitted, buffer will be filled with zeros. + * @param encoding encoding used for call to buf.fill while initalizing + */ + static alloc(size: number, fill?: string | Buffer | number, encoding?: string): Buffer; + /** + * Allocates a new buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + static allocUnsafe(size: number): Buffer; + /** + * Allocates a new non-pooled buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + static allocUnsafeSlow(size: number): Buffer; + } +} \ No newline at end of file diff --git a/scripts/2.5/node_modules/safe-buffer/index.js b/scripts/2.5/node_modules/safe-buffer/index.js new file mode 100644 index 00000000..054c8d30 --- /dev/null +++ b/scripts/2.5/node_modules/safe-buffer/index.js @@ -0,0 +1,64 @@ +/* eslint-disable node/no-deprecated-api */ +var buffer = require('buffer') +var Buffer = buffer.Buffer + +// alternative to using Object.keys for old browsers +function copyProps (src, dst) { + for (var key in src) { + dst[key] = src[key] + } +} +if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { + module.exports = buffer +} else { + // Copy properties from require('buffer') + copyProps(buffer, exports) + exports.Buffer = SafeBuffer +} + +function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) +} + +SafeBuffer.prototype = Object.create(Buffer.prototype) + +// Copy static methods from Buffer +copyProps(Buffer, SafeBuffer) + +SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') + } + return Buffer(arg, encodingOrOffset, length) +} + +SafeBuffer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + var buf = Buffer(size) + if (fill !== undefined) { + if (typeof encoding === 'string') { + buf.fill(fill, encoding) + } else { + buf.fill(fill) + } + } else { + buf.fill(0) + } + return buf +} + +SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return Buffer(size) +} + +SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return buffer.SlowBuffer(size) +} diff --git a/scripts/2.5/node_modules/safe-buffer/package.json b/scripts/2.5/node_modules/safe-buffer/package.json new file mode 100644 index 00000000..b54facc5 --- /dev/null +++ b/scripts/2.5/node_modules/safe-buffer/package.json @@ -0,0 +1,62 @@ +{ + "_from": "safe-buffer@^5.1.2", + "_id": "safe-buffer@5.2.0", + "_inBundle": false, + "_integrity": "sha512-fZEwUGbVl7kouZs1jCdMLdt95hdIv0ZeHg6L7qPeciMZhZ+/gdesW4wgTARkrFWEpspjEATAzUGPG8N2jJiwbg==", + "_location": "/safe-buffer", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "safe-buffer@^5.1.2", + "name": "safe-buffer", + "escapedName": "safe-buffer", + "rawSpec": "^5.1.2", + "saveSpec": null, + "fetchSpec": "^5.1.2" + }, + "_requiredBy": [ + "/mongodb" + ], + "_resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.0.tgz", + "_shasum": "b74daec49b1148f88c64b68d49b1e815c1f2f519", + "_spec": "safe-buffer@^5.1.2", + "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/2.5/node_modules/mongodb", + "author": { + "name": "Feross Aboukhadijeh", + "email": "feross@feross.org", + "url": "http://feross.org" + }, + "bugs": { + "url": "https://github.com/feross/safe-buffer/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "Safer Node.js Buffer API", + "devDependencies": { + "standard": "*", + "tape": "^4.0.0" + }, + "homepage": "https://github.com/feross/safe-buffer", + "keywords": [ + "buffer", + "buffer allocate", + "node security", + "safe", + "safe-buffer", + "security", + "uninitialized" + ], + "license": "MIT", + "main": "index.js", + "name": "safe-buffer", + "repository": { + "type": "git", + "url": "git://github.com/feross/safe-buffer.git" + }, + "scripts": { + "test": "standard && tape test/*.js" + }, + "types": "index.d.ts", + "version": "5.2.0" +} diff --git a/scripts/2.5/node_modules/saslprep/.editorconfig b/scripts/2.5/node_modules/saslprep/.editorconfig new file mode 100644 index 00000000..d1d8a417 --- /dev/null +++ b/scripts/2.5/node_modules/saslprep/.editorconfig @@ -0,0 +1,10 @@ +# http://editorconfig.org +root = true + +[*] +indent_style = space +indent_size = 2 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true diff --git a/scripts/2.5/node_modules/saslprep/.gitattributes b/scripts/2.5/node_modules/saslprep/.gitattributes new file mode 100644 index 00000000..3ba45360 --- /dev/null +++ b/scripts/2.5/node_modules/saslprep/.gitattributes @@ -0,0 +1 @@ +*.mem binary diff --git a/scripts/2.5/node_modules/saslprep/.travis.yml b/scripts/2.5/node_modules/saslprep/.travis.yml new file mode 100644 index 00000000..0bca8265 --- /dev/null +++ b/scripts/2.5/node_modules/saslprep/.travis.yml @@ -0,0 +1,10 @@ +sudo: false +language: node_js +node_js: + - "6" + - "8" + - "10" + - "12" + +before_install: +- npm install -g npm@6 diff --git a/scripts/2.5/node_modules/saslprep/CHANGELOG.md b/scripts/2.5/node_modules/saslprep/CHANGELOG.md new file mode 100644 index 00000000..77980787 --- /dev/null +++ b/scripts/2.5/node_modules/saslprep/CHANGELOG.md @@ -0,0 +1,19 @@ +# Change Log +All notable changes to the "saslprep" package will be documented in this file. + +## [1.0.3] - 2019-05-01 + +- Correctly get code points >U+FFFF ([#5](https://github.com/reklatsmasters/saslprep/pull/5)) +- Fix perfomance downgrades from [#5](https://github.com/reklatsmasters/saslprep/pull/5). + +## [1.0.2] - 2018-09-13 + +- Reduced initialization time ([#3](https://github.com/reklatsmasters/saslprep/issues/3)) + +## [1.0.1] - 2018-06-20 + +- Reduced stack overhead of range creation ([#2](https://github.com/reklatsmasters/saslprep/pull/2)) + +## [1.0.0] - 2017-06-21 + +- First release diff --git a/scripts/2.5/node_modules/saslprep/LICENSE b/scripts/2.5/node_modules/saslprep/LICENSE new file mode 100644 index 00000000..481c7a50 --- /dev/null +++ b/scripts/2.5/node_modules/saslprep/LICENSE @@ -0,0 +1,22 @@ +Copyright (c) 2014 Dmitry Tsvettsikh + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/scripts/2.5/node_modules/saslprep/code-points.mem b/scripts/2.5/node_modules/saslprep/code-points.mem new file mode 100644 index 0000000000000000000000000000000000000000..4781b066802688bdf954d2e89bcfac967db29c09 GIT binary patch literal 419864 zcmeI*O^9Si9RTop)4e+(t{DX(dsufSM8xBQfdsOo2lf&{@FWO&5cZ;Y@FWHe%nKV~ z@sxvzw;c53DIgdRk!c;t<{;##B4%51h#=^gL^8Y6+hx^z-92x{*9;3Umv`GA&vUy%enler!HTQKkA3&c=OSJMn7j|JGjl-d;Iey^#7>ZH0(RWYm^YJNA>kJ59aOu`p6X{MHRe9bu8cD2oYvN=9*ybv z%TyjdGTZ46aN&^<{xI6U)O2~U(!G+Yl0gPYRjbu8Wx~a<(#z+pIGvPkC#O7E&NgnV zIeue)&FW_ULfI&__U^^i@bTrer0O33=x2+%W4?Qo^)pjbsxinkv-K<<-Z9O6ZEyaQ zcB_@u#{%W}q9N0;ypzw%<*<}a^^Ob|R8?1xx0U*l{Mfi-J@SG5+xHJnzAqkVA73p) zfWWZ=`LSE4W4mY|K!5-N0t5&UATSizd-XW}{r>FO4Bx#OzCAE{nLD@VvjcA?1PBnA ze}O7c;{B8P-)Ji&@Gu01QMDYyI+%*sOCglv+~@Yqqm#Pz_SKwJ*n6ekt-IE7xb$i{ z#vJ7-%1?!2rG0Ri^X0*sx?FU--CIQw%Y*Zsb~)W#QAMFvj~+Qsr{Zh=QgU=xwFC$d zAV7cs0RjXF5FkK+009C72oNAZfB*pkrx2*aLB}2IZvhtFBipAEvDq7W9J^}&<>l~& z=Z6hT7u&hviF4icy{;$Z#$Rfh)bDEDcnTt22oNAJj{^NkPm$UP5FkK+009C72oNAZ zfB*pk1PBlya5e=N=WpRu-1tFH?r+Uep=aLS_2t}!1M%`E=_N&nH;IH{&FT4 zVA2E#5FkK+009C72oNAZfB*pk1PBlyK!5-N0tDtqVE;Gx53TDIQTIm zIQs(S*`MN>nqk~d)2W{+PVszkrlxK(QxGVpFoq#!SYT-_Rh1zb5B|v}x z0RjXF5FkK+009C72oNAZfB*pk1PBlyK!5;&ITaB9pVN)CECK`w5FkK+009C72oNAZ zfB*pk1PBlyK!5-N0t5&USSSJU|ApFaizPsS009C72oNAZfB*pk1PBlyK!5-N0t5&U zAV7csfjJcr|DV&1wJZVz2oNAZfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF5LhUI)_PiQ zY@~%+y~PqBK!5-N0t5&UAV7cs0RjXF5FkK+009C72oNAZfB=E{5NI_*|FQ%K5FkK+ z009C72oNAZfB*pk1PBlyK!5-N0t5&UAV7e?Yzp*ebJ}K2fB*pk1PBlyK!5-N0t5&U zAV7cs0RjXF5FkK+009C72s8ykSewfEzdsXvos!llv!K)XN+!bACMEW{kJW7s~i{EW^`xUX5|{=UXrRtoY&_gwz< zRvE$%TJf3i_%h&Xxb|Z>^W9wXR6Vl#j!mc_rtE>35?{Z6IbwcGK;>nSRoF zHt&;$O2P80zs-^hqp)?4qhw2`7#YP=_?Tw>wDeltgbe?$_^GM=@ z?HoDm9erzgM=HMNFC|BJRZD;X0RjXF5FkK+009C72oNAZfB*pk1PBlya0-DOe>pzY z-vZ3vILv9#>4l5=+gV#xaVim;YNYBg{{HIj=YJUg^!l*j-g~>b;hnpk&0)>Sr{)*n zj_ut&1&%HR2oRWKfn%Q^H4q>`fB*pk1PBlyK!5-N0t5&UAVA>E3Jm7>U0X{dK!5-N z0t5&U__zX7c= character.codePointAt(0); +const first = x => x[0]; +const last = x => x[x.length - 1]; + +/** + * Convert provided string into an array of Unicode Code Points. + * Based on https://stackoverflow.com/a/21409165/1556249 + * and https://www.npmjs.com/package/code-point-at. + * @param {string} input + * @returns {number[]} + */ +function toCodePoints(input) { + const codepoints = []; + const size = input.length; + + for (let i = 0; i < size; i += 1) { + const before = input.charCodeAt(i); + + if (before >= 0xd800 && before <= 0xdbff && size > i + 1) { + const next = input.charCodeAt(i + 1); + + if (next >= 0xdc00 && next <= 0xdfff) { + codepoints.push((before - 0xd800) * 0x400 + next - 0xdc00 + 0x10000); + i += 1; + continue; + } + } + + codepoints.push(before); + } + + return codepoints; +} + +/** + * SASLprep. + * @param {string} input + * @param {Object} opts + * @param {boolean} opts.allowUnassigned + * @returns {string} + */ +function saslprep(input, opts = {}) { + if (typeof input !== 'string') { + throw new TypeError('Expected string.'); + } + + if (input.length === 0) { + return ''; + } + + // 1. Map + const mapped_input = toCodePoints(input) + // 1.1 mapping to space + .map(character => (mapping2space.get(character) ? 0x20 : character)) + // 1.2 mapping to nothing + .filter(character => !mapping2nothing.get(character)); + + // 2. Normalize + const normalized_input = String.fromCodePoint + .apply(null, mapped_input) + .normalize('NFKC'); + + const normalized_map = toCodePoints(normalized_input); + + // 3. Prohibit + const hasProhibited = normalized_map.some(character => + prohibited_characters.get(character) + ); + + if (hasProhibited) { + throw new Error( + 'Prohibited character, see https://tools.ietf.org/html/rfc4013#section-2.3' + ); + } + + // Unassigned Code Points + if (opts.allowUnassigned !== true) { + const hasUnassigned = normalized_map.some(character => + unassigned_code_points.get(character) + ); + + if (hasUnassigned) { + throw new Error( + 'Unassigned code point, see https://tools.ietf.org/html/rfc4013#section-2.5' + ); + } + } + + // 4. check bidi + + const hasBidiRAL = normalized_map.some(character => + bidirectional_r_al.get(character) + ); + + const hasBidiL = normalized_map.some(character => + bidirectional_l.get(character) + ); + + // 4.1 If a string contains any RandALCat character, the string MUST NOT + // contain any LCat character. + if (hasBidiRAL && hasBidiL) { + throw new Error( + 'String must not contain RandALCat and LCat at the same time,' + + ' see https://tools.ietf.org/html/rfc3454#section-6' + ); + } + + /** + * 4.2 If a string contains any RandALCat character, a RandALCat + * character MUST be the first character of the string, and a + * RandALCat character MUST be the last character of the string. + */ + + const isFirstBidiRAL = bidirectional_r_al.get( + getCodePoint(first(normalized_input)) + ); + const isLastBidiRAL = bidirectional_r_al.get( + getCodePoint(last(normalized_input)) + ); + + if (hasBidiRAL && !(isFirstBidiRAL && isLastBidiRAL)) { + throw new Error( + 'Bidirectional RandALCat character must be the first and the last' + + ' character of the string, see https://tools.ietf.org/html/rfc3454#section-6' + ); + } + + return normalized_input; +} diff --git a/scripts/2.5/node_modules/saslprep/lib/code-points.js b/scripts/2.5/node_modules/saslprep/lib/code-points.js new file mode 100644 index 00000000..222182c8 --- /dev/null +++ b/scripts/2.5/node_modules/saslprep/lib/code-points.js @@ -0,0 +1,996 @@ +'use strict'; + +const { range } = require('./util'); + +/** + * A.1 Unassigned code points in Unicode 3.2 + * @link https://tools.ietf.org/html/rfc3454#appendix-A.1 + */ +const unassigned_code_points = new Set([ + 0x0221, + ...range(0x0234, 0x024f), + ...range(0x02ae, 0x02af), + ...range(0x02ef, 0x02ff), + ...range(0x0350, 0x035f), + ...range(0x0370, 0x0373), + ...range(0x0376, 0x0379), + ...range(0x037b, 0x037d), + ...range(0x037f, 0x0383), + 0x038b, + 0x038d, + 0x03a2, + 0x03cf, + ...range(0x03f7, 0x03ff), + 0x0487, + 0x04cf, + ...range(0x04f6, 0x04f7), + ...range(0x04fa, 0x04ff), + ...range(0x0510, 0x0530), + ...range(0x0557, 0x0558), + 0x0560, + 0x0588, + ...range(0x058b, 0x0590), + 0x05a2, + 0x05ba, + ...range(0x05c5, 0x05cf), + ...range(0x05eb, 0x05ef), + ...range(0x05f5, 0x060b), + ...range(0x060d, 0x061a), + ...range(0x061c, 0x061e), + 0x0620, + ...range(0x063b, 0x063f), + ...range(0x0656, 0x065f), + ...range(0x06ee, 0x06ef), + 0x06ff, + 0x070e, + ...range(0x072d, 0x072f), + ...range(0x074b, 0x077f), + ...range(0x07b2, 0x0900), + 0x0904, + ...range(0x093a, 0x093b), + ...range(0x094e, 0x094f), + ...range(0x0955, 0x0957), + ...range(0x0971, 0x0980), + 0x0984, + ...range(0x098d, 0x098e), + ...range(0x0991, 0x0992), + 0x09a9, + 0x09b1, + ...range(0x09b3, 0x09b5), + ...range(0x09ba, 0x09bb), + 0x09bd, + ...range(0x09c5, 0x09c6), + ...range(0x09c9, 0x09ca), + ...range(0x09ce, 0x09d6), + ...range(0x09d8, 0x09db), + 0x09de, + ...range(0x09e4, 0x09e5), + ...range(0x09fb, 0x0a01), + ...range(0x0a03, 0x0a04), + ...range(0x0a0b, 0x0a0e), + ...range(0x0a11, 0x0a12), + 0x0a29, + 0x0a31, + 0x0a34, + 0x0a37, + ...range(0x0a3a, 0x0a3b), + 0x0a3d, + ...range(0x0a43, 0x0a46), + ...range(0x0a49, 0x0a4a), + ...range(0x0a4e, 0x0a58), + 0x0a5d, + ...range(0x0a5f, 0x0a65), + ...range(0x0a75, 0x0a80), + 0x0a84, + 0x0a8c, + 0x0a8e, + 0x0a92, + 0x0aa9, + 0x0ab1, + 0x0ab4, + ...range(0x0aba, 0x0abb), + 0x0ac6, + 0x0aca, + ...range(0x0ace, 0x0acf), + ...range(0x0ad1, 0x0adf), + ...range(0x0ae1, 0x0ae5), + ...range(0x0af0, 0x0b00), + 0x0b04, + ...range(0x0b0d, 0x0b0e), + ...range(0x0b11, 0x0b12), + 0x0b29, + 0x0b31, + ...range(0x0b34, 0x0b35), + ...range(0x0b3a, 0x0b3b), + ...range(0x0b44, 0x0b46), + ...range(0x0b49, 0x0b4a), + ...range(0x0b4e, 0x0b55), + ...range(0x0b58, 0x0b5b), + 0x0b5e, + ...range(0x0b62, 0x0b65), + ...range(0x0b71, 0x0b81), + 0x0b84, + ...range(0x0b8b, 0x0b8d), + 0x0b91, + ...range(0x0b96, 0x0b98), + 0x0b9b, + 0x0b9d, + ...range(0x0ba0, 0x0ba2), + ...range(0x0ba5, 0x0ba7), + ...range(0x0bab, 0x0bad), + 0x0bb6, + ...range(0x0bba, 0x0bbd), + ...range(0x0bc3, 0x0bc5), + 0x0bc9, + ...range(0x0bce, 0x0bd6), + ...range(0x0bd8, 0x0be6), + ...range(0x0bf3, 0x0c00), + 0x0c04, + 0x0c0d, + 0x0c11, + 0x0c29, + 0x0c34, + ...range(0x0c3a, 0x0c3d), + 0x0c45, + 0x0c49, + ...range(0x0c4e, 0x0c54), + ...range(0x0c57, 0x0c5f), + ...range(0x0c62, 0x0c65), + ...range(0x0c70, 0x0c81), + 0x0c84, + 0x0c8d, + 0x0c91, + 0x0ca9, + 0x0cb4, + ...range(0x0cba, 0x0cbd), + 0x0cc5, + 0x0cc9, + ...range(0x0cce, 0x0cd4), + ...range(0x0cd7, 0x0cdd), + 0x0cdf, + ...range(0x0ce2, 0x0ce5), + ...range(0x0cf0, 0x0d01), + 0x0d04, + 0x0d0d, + 0x0d11, + 0x0d29, + ...range(0x0d3a, 0x0d3d), + ...range(0x0d44, 0x0d45), + 0x0d49, + ...range(0x0d4e, 0x0d56), + ...range(0x0d58, 0x0d5f), + ...range(0x0d62, 0x0d65), + ...range(0x0d70, 0x0d81), + 0x0d84, + ...range(0x0d97, 0x0d99), + 0x0db2, + 0x0dbc, + ...range(0x0dbe, 0x0dbf), + ...range(0x0dc7, 0x0dc9), + ...range(0x0dcb, 0x0dce), + 0x0dd5, + 0x0dd7, + ...range(0x0de0, 0x0df1), + ...range(0x0df5, 0x0e00), + ...range(0x0e3b, 0x0e3e), + ...range(0x0e5c, 0x0e80), + 0x0e83, + ...range(0x0e85, 0x0e86), + 0x0e89, + ...range(0x0e8b, 0x0e8c), + ...range(0x0e8e, 0x0e93), + 0x0e98, + 0x0ea0, + 0x0ea4, + 0x0ea6, + ...range(0x0ea8, 0x0ea9), + 0x0eac, + 0x0eba, + ...range(0x0ebe, 0x0ebf), + 0x0ec5, + 0x0ec7, + ...range(0x0ece, 0x0ecf), + ...range(0x0eda, 0x0edb), + ...range(0x0ede, 0x0eff), + 0x0f48, + ...range(0x0f6b, 0x0f70), + ...range(0x0f8c, 0x0f8f), + 0x0f98, + 0x0fbd, + ...range(0x0fcd, 0x0fce), + ...range(0x0fd0, 0x0fff), + 0x1022, + 0x1028, + 0x102b, + ...range(0x1033, 0x1035), + ...range(0x103a, 0x103f), + ...range(0x105a, 0x109f), + ...range(0x10c6, 0x10cf), + ...range(0x10f9, 0x10fa), + ...range(0x10fc, 0x10ff), + ...range(0x115a, 0x115e), + ...range(0x11a3, 0x11a7), + ...range(0x11fa, 0x11ff), + 0x1207, + 0x1247, + 0x1249, + ...range(0x124e, 0x124f), + 0x1257, + 0x1259, + ...range(0x125e, 0x125f), + 0x1287, + 0x1289, + ...range(0x128e, 0x128f), + 0x12af, + 0x12b1, + ...range(0x12b6, 0x12b7), + 0x12bf, + 0x12c1, + ...range(0x12c6, 0x12c7), + 0x12cf, + 0x12d7, + 0x12ef, + 0x130f, + 0x1311, + ...range(0x1316, 0x1317), + 0x131f, + 0x1347, + ...range(0x135b, 0x1360), + ...range(0x137d, 0x139f), + ...range(0x13f5, 0x1400), + ...range(0x1677, 0x167f), + ...range(0x169d, 0x169f), + ...range(0x16f1, 0x16ff), + 0x170d, + ...range(0x1715, 0x171f), + ...range(0x1737, 0x173f), + ...range(0x1754, 0x175f), + 0x176d, + 0x1771, + ...range(0x1774, 0x177f), + ...range(0x17dd, 0x17df), + ...range(0x17ea, 0x17ff), + 0x180f, + ...range(0x181a, 0x181f), + ...range(0x1878, 0x187f), + ...range(0x18aa, 0x1dff), + ...range(0x1e9c, 0x1e9f), + ...range(0x1efa, 0x1eff), + ...range(0x1f16, 0x1f17), + ...range(0x1f1e, 0x1f1f), + ...range(0x1f46, 0x1f47), + ...range(0x1f4e, 0x1f4f), + 0x1f58, + 0x1f5a, + 0x1f5c, + 0x1f5e, + ...range(0x1f7e, 0x1f7f), + 0x1fb5, + 0x1fc5, + ...range(0x1fd4, 0x1fd5), + 0x1fdc, + ...range(0x1ff0, 0x1ff1), + 0x1ff5, + 0x1fff, + ...range(0x2053, 0x2056), + ...range(0x2058, 0x205e), + ...range(0x2064, 0x2069), + ...range(0x2072, 0x2073), + ...range(0x208f, 0x209f), + ...range(0x20b2, 0x20cf), + ...range(0x20eb, 0x20ff), + ...range(0x213b, 0x213c), + ...range(0x214c, 0x2152), + ...range(0x2184, 0x218f), + ...range(0x23cf, 0x23ff), + ...range(0x2427, 0x243f), + ...range(0x244b, 0x245f), + 0x24ff, + ...range(0x2614, 0x2615), + 0x2618, + ...range(0x267e, 0x267f), + ...range(0x268a, 0x2700), + 0x2705, + ...range(0x270a, 0x270b), + 0x2728, + 0x274c, + 0x274e, + ...range(0x2753, 0x2755), + 0x2757, + ...range(0x275f, 0x2760), + ...range(0x2795, 0x2797), + 0x27b0, + ...range(0x27bf, 0x27cf), + ...range(0x27ec, 0x27ef), + ...range(0x2b00, 0x2e7f), + 0x2e9a, + ...range(0x2ef4, 0x2eff), + ...range(0x2fd6, 0x2fef), + ...range(0x2ffc, 0x2fff), + 0x3040, + ...range(0x3097, 0x3098), + ...range(0x3100, 0x3104), + ...range(0x312d, 0x3130), + 0x318f, + ...range(0x31b8, 0x31ef), + ...range(0x321d, 0x321f), + ...range(0x3244, 0x3250), + ...range(0x327c, 0x327e), + ...range(0x32cc, 0x32cf), + 0x32ff, + ...range(0x3377, 0x337a), + ...range(0x33de, 0x33df), + 0x33ff, + ...range(0x4db6, 0x4dff), + ...range(0x9fa6, 0x9fff), + ...range(0xa48d, 0xa48f), + ...range(0xa4c7, 0xabff), + ...range(0xd7a4, 0xd7ff), + ...range(0xfa2e, 0xfa2f), + ...range(0xfa6b, 0xfaff), + ...range(0xfb07, 0xfb12), + ...range(0xfb18, 0xfb1c), + 0xfb37, + 0xfb3d, + 0xfb3f, + 0xfb42, + 0xfb45, + ...range(0xfbb2, 0xfbd2), + ...range(0xfd40, 0xfd4f), + ...range(0xfd90, 0xfd91), + ...range(0xfdc8, 0xfdcf), + ...range(0xfdfd, 0xfdff), + ...range(0xfe10, 0xfe1f), + ...range(0xfe24, 0xfe2f), + ...range(0xfe47, 0xfe48), + 0xfe53, + 0xfe67, + ...range(0xfe6c, 0xfe6f), + 0xfe75, + ...range(0xfefd, 0xfefe), + 0xff00, + ...range(0xffbf, 0xffc1), + ...range(0xffc8, 0xffc9), + ...range(0xffd0, 0xffd1), + ...range(0xffd8, 0xffd9), + ...range(0xffdd, 0xffdf), + 0xffe7, + ...range(0xffef, 0xfff8), + ...range(0x10000, 0x102ff), + 0x1031f, + ...range(0x10324, 0x1032f), + ...range(0x1034b, 0x103ff), + ...range(0x10426, 0x10427), + ...range(0x1044e, 0x1cfff), + ...range(0x1d0f6, 0x1d0ff), + ...range(0x1d127, 0x1d129), + ...range(0x1d1de, 0x1d3ff), + 0x1d455, + 0x1d49d, + ...range(0x1d4a0, 0x1d4a1), + ...range(0x1d4a3, 0x1d4a4), + ...range(0x1d4a7, 0x1d4a8), + 0x1d4ad, + 0x1d4ba, + 0x1d4bc, + 0x1d4c1, + 0x1d4c4, + 0x1d506, + ...range(0x1d50b, 0x1d50c), + 0x1d515, + 0x1d51d, + 0x1d53a, + 0x1d53f, + 0x1d545, + ...range(0x1d547, 0x1d549), + 0x1d551, + ...range(0x1d6a4, 0x1d6a7), + ...range(0x1d7ca, 0x1d7cd), + ...range(0x1d800, 0x1fffd), + ...range(0x2a6d7, 0x2f7ff), + ...range(0x2fa1e, 0x2fffd), + ...range(0x30000, 0x3fffd), + ...range(0x40000, 0x4fffd), + ...range(0x50000, 0x5fffd), + ...range(0x60000, 0x6fffd), + ...range(0x70000, 0x7fffd), + ...range(0x80000, 0x8fffd), + ...range(0x90000, 0x9fffd), + ...range(0xa0000, 0xafffd), + ...range(0xb0000, 0xbfffd), + ...range(0xc0000, 0xcfffd), + ...range(0xd0000, 0xdfffd), + 0xe0000, + ...range(0xe0002, 0xe001f), + ...range(0xe0080, 0xefffd), +]); + +/** + * B.1 Commonly mapped to nothing + * @link https://tools.ietf.org/html/rfc3454#appendix-B.1 + */ +const commonly_mapped_to_nothing = new Set([ + 0x00ad, + 0x034f, + 0x1806, + 0x180b, + 0x180c, + 0x180d, + 0x200b, + 0x200c, + 0x200d, + 0x2060, + 0xfe00, + 0xfe01, + 0xfe02, + 0xfe03, + 0xfe04, + 0xfe05, + 0xfe06, + 0xfe07, + 0xfe08, + 0xfe09, + 0xfe0a, + 0xfe0b, + 0xfe0c, + 0xfe0d, + 0xfe0e, + 0xfe0f, + 0xfeff, +]); + +/** + * C.1.2 Non-ASCII space characters + * @link https://tools.ietf.org/html/rfc3454#appendix-C.1.2 + */ +const non_ASCII_space_characters = new Set([ + 0x00a0 /* NO-BREAK SPACE */, + 0x1680 /* OGHAM SPACE MARK */, + 0x2000 /* EN QUAD */, + 0x2001 /* EM QUAD */, + 0x2002 /* EN SPACE */, + 0x2003 /* EM SPACE */, + 0x2004 /* THREE-PER-EM SPACE */, + 0x2005 /* FOUR-PER-EM SPACE */, + 0x2006 /* SIX-PER-EM SPACE */, + 0x2007 /* FIGURE SPACE */, + 0x2008 /* PUNCTUATION SPACE */, + 0x2009 /* THIN SPACE */, + 0x200a /* HAIR SPACE */, + 0x200b /* ZERO WIDTH SPACE */, + 0x202f /* NARROW NO-BREAK SPACE */, + 0x205f /* MEDIUM MATHEMATICAL SPACE */, + 0x3000 /* IDEOGRAPHIC SPACE */, +]); + +/** + * 2.3. Prohibited Output + * @type {Set} + */ +const prohibited_characters = new Set([ + ...non_ASCII_space_characters, + + /** + * C.2.1 ASCII control characters + * @link https://tools.ietf.org/html/rfc3454#appendix-C.2.1 + */ + ...range(0, 0x001f) /* [CONTROL CHARACTERS] */, + 0x007f /* DELETE */, + + /** + * C.2.2 Non-ASCII control characters + * @link https://tools.ietf.org/html/rfc3454#appendix-C.2.2 + */ + ...range(0x0080, 0x009f) /* [CONTROL CHARACTERS] */, + 0x06dd /* ARABIC END OF AYAH */, + 0x070f /* SYRIAC ABBREVIATION MARK */, + 0x180e /* MONGOLIAN VOWEL SEPARATOR */, + 0x200c /* ZERO WIDTH NON-JOINER */, + 0x200d /* ZERO WIDTH JOINER */, + 0x2028 /* LINE SEPARATOR */, + 0x2029 /* PARAGRAPH SEPARATOR */, + 0x2060 /* WORD JOINER */, + 0x2061 /* FUNCTION APPLICATION */, + 0x2062 /* INVISIBLE TIMES */, + 0x2063 /* INVISIBLE SEPARATOR */, + ...range(0x206a, 0x206f) /* [CONTROL CHARACTERS] */, + 0xfeff /* ZERO WIDTH NO-BREAK SPACE */, + ...range(0xfff9, 0xfffc) /* [CONTROL CHARACTERS] */, + ...range(0x1d173, 0x1d17a) /* [MUSICAL CONTROL CHARACTERS] */, + + /** + * C.3 Private use + * @link https://tools.ietf.org/html/rfc3454#appendix-C.3 + */ + ...range(0xe000, 0xf8ff) /* [PRIVATE USE, PLANE 0] */, + ...range(0xf0000, 0xffffd) /* [PRIVATE USE, PLANE 15] */, + ...range(0x100000, 0x10fffd) /* [PRIVATE USE, PLANE 16] */, + + /** + * C.4 Non-character code points + * @link https://tools.ietf.org/html/rfc3454#appendix-C.4 + */ + ...range(0xfdd0, 0xfdef) /* [NONCHARACTER CODE POINTS] */, + ...range(0xfffe, 0xffff) /* [NONCHARACTER CODE POINTS] */, + ...range(0x1fffe, 0x1ffff) /* [NONCHARACTER CODE POINTS] */, + ...range(0x2fffe, 0x2ffff) /* [NONCHARACTER CODE POINTS] */, + ...range(0x3fffe, 0x3ffff) /* [NONCHARACTER CODE POINTS] */, + ...range(0x4fffe, 0x4ffff) /* [NONCHARACTER CODE POINTS] */, + ...range(0x5fffe, 0x5ffff) /* [NONCHARACTER CODE POINTS] */, + ...range(0x6fffe, 0x6ffff) /* [NONCHARACTER CODE POINTS] */, + ...range(0x7fffe, 0x7ffff) /* [NONCHARACTER CODE POINTS] */, + ...range(0x8fffe, 0x8ffff) /* [NONCHARACTER CODE POINTS] */, + ...range(0x9fffe, 0x9ffff) /* [NONCHARACTER CODE POINTS] */, + ...range(0xafffe, 0xaffff) /* [NONCHARACTER CODE POINTS] */, + ...range(0xbfffe, 0xbffff) /* [NONCHARACTER CODE POINTS] */, + ...range(0xcfffe, 0xcffff) /* [NONCHARACTER CODE POINTS] */, + ...range(0xdfffe, 0xdffff) /* [NONCHARACTER CODE POINTS] */, + ...range(0xefffe, 0xeffff) /* [NONCHARACTER CODE POINTS] */, + ...range(0x10fffe, 0x10ffff) /* [NONCHARACTER CODE POINTS] */, + + /** + * C.5 Surrogate codes + * @link https://tools.ietf.org/html/rfc3454#appendix-C.5 + */ + ...range(0xd800, 0xdfff), + + /** + * C.6 Inappropriate for plain text + * @link https://tools.ietf.org/html/rfc3454#appendix-C.6 + */ + 0xfff9 /* INTERLINEAR ANNOTATION ANCHOR */, + 0xfffa /* INTERLINEAR ANNOTATION SEPARATOR */, + 0xfffb /* INTERLINEAR ANNOTATION TERMINATOR */, + 0xfffc /* OBJECT REPLACEMENT CHARACTER */, + 0xfffd /* REPLACEMENT CHARACTER */, + + /** + * C.7 Inappropriate for canonical representation + * @link https://tools.ietf.org/html/rfc3454#appendix-C.7 + */ + ...range(0x2ff0, 0x2ffb) /* [IDEOGRAPHIC DESCRIPTION CHARACTERS] */, + + /** + * C.8 Change display properties or are deprecated + * @link https://tools.ietf.org/html/rfc3454#appendix-C.8 + */ + 0x0340 /* COMBINING GRAVE TONE MARK */, + 0x0341 /* COMBINING ACUTE TONE MARK */, + 0x200e /* LEFT-TO-RIGHT MARK */, + 0x200f /* RIGHT-TO-LEFT MARK */, + 0x202a /* LEFT-TO-RIGHT EMBEDDING */, + 0x202b /* RIGHT-TO-LEFT EMBEDDING */, + 0x202c /* POP DIRECTIONAL FORMATTING */, + 0x202d /* LEFT-TO-RIGHT OVERRIDE */, + 0x202e /* RIGHT-TO-LEFT OVERRIDE */, + 0x206a /* INHIBIT SYMMETRIC SWAPPING */, + 0x206b /* ACTIVATE SYMMETRIC SWAPPING */, + 0x206c /* INHIBIT ARABIC FORM SHAPING */, + 0x206d /* ACTIVATE ARABIC FORM SHAPING */, + 0x206e /* NATIONAL DIGIT SHAPES */, + 0x206f /* NOMINAL DIGIT SHAPES */, + + /** + * C.9 Tagging characters + * @link https://tools.ietf.org/html/rfc3454#appendix-C.9 + */ + 0xe0001 /* LANGUAGE TAG */, + ...range(0xe0020, 0xe007f) /* [TAGGING CHARACTERS] */, +]); + +/** + * D.1 Characters with bidirectional property "R" or "AL" + * @link https://tools.ietf.org/html/rfc3454#appendix-D.1 + */ +const bidirectional_r_al = new Set([ + 0x05be, + 0x05c0, + 0x05c3, + ...range(0x05d0, 0x05ea), + ...range(0x05f0, 0x05f4), + 0x061b, + 0x061f, + ...range(0x0621, 0x063a), + ...range(0x0640, 0x064a), + ...range(0x066d, 0x066f), + ...range(0x0671, 0x06d5), + 0x06dd, + ...range(0x06e5, 0x06e6), + ...range(0x06fa, 0x06fe), + ...range(0x0700, 0x070d), + 0x0710, + ...range(0x0712, 0x072c), + ...range(0x0780, 0x07a5), + 0x07b1, + 0x200f, + 0xfb1d, + ...range(0xfb1f, 0xfb28), + ...range(0xfb2a, 0xfb36), + ...range(0xfb38, 0xfb3c), + 0xfb3e, + ...range(0xfb40, 0xfb41), + ...range(0xfb43, 0xfb44), + ...range(0xfb46, 0xfbb1), + ...range(0xfbd3, 0xfd3d), + ...range(0xfd50, 0xfd8f), + ...range(0xfd92, 0xfdc7), + ...range(0xfdf0, 0xfdfc), + ...range(0xfe70, 0xfe74), + ...range(0xfe76, 0xfefc), +]); + +/** + * D.2 Characters with bidirectional property "L" + * @link https://tools.ietf.org/html/rfc3454#appendix-D.2 + */ +const bidirectional_l = new Set([ + ...range(0x0041, 0x005a), + ...range(0x0061, 0x007a), + 0x00aa, + 0x00b5, + 0x00ba, + ...range(0x00c0, 0x00d6), + ...range(0x00d8, 0x00f6), + ...range(0x00f8, 0x0220), + ...range(0x0222, 0x0233), + ...range(0x0250, 0x02ad), + ...range(0x02b0, 0x02b8), + ...range(0x02bb, 0x02c1), + ...range(0x02d0, 0x02d1), + ...range(0x02e0, 0x02e4), + 0x02ee, + 0x037a, + 0x0386, + ...range(0x0388, 0x038a), + 0x038c, + ...range(0x038e, 0x03a1), + ...range(0x03a3, 0x03ce), + ...range(0x03d0, 0x03f5), + ...range(0x0400, 0x0482), + ...range(0x048a, 0x04ce), + ...range(0x04d0, 0x04f5), + ...range(0x04f8, 0x04f9), + ...range(0x0500, 0x050f), + ...range(0x0531, 0x0556), + ...range(0x0559, 0x055f), + ...range(0x0561, 0x0587), + 0x0589, + 0x0903, + ...range(0x0905, 0x0939), + ...range(0x093d, 0x0940), + ...range(0x0949, 0x094c), + 0x0950, + ...range(0x0958, 0x0961), + ...range(0x0964, 0x0970), + ...range(0x0982, 0x0983), + ...range(0x0985, 0x098c), + ...range(0x098f, 0x0990), + ...range(0x0993, 0x09a8), + ...range(0x09aa, 0x09b0), + 0x09b2, + ...range(0x09b6, 0x09b9), + ...range(0x09be, 0x09c0), + ...range(0x09c7, 0x09c8), + ...range(0x09cb, 0x09cc), + 0x09d7, + ...range(0x09dc, 0x09dd), + ...range(0x09df, 0x09e1), + ...range(0x09e6, 0x09f1), + ...range(0x09f4, 0x09fa), + ...range(0x0a05, 0x0a0a), + ...range(0x0a0f, 0x0a10), + ...range(0x0a13, 0x0a28), + ...range(0x0a2a, 0x0a30), + ...range(0x0a32, 0x0a33), + ...range(0x0a35, 0x0a36), + ...range(0x0a38, 0x0a39), + ...range(0x0a3e, 0x0a40), + ...range(0x0a59, 0x0a5c), + 0x0a5e, + ...range(0x0a66, 0x0a6f), + ...range(0x0a72, 0x0a74), + 0x0a83, + ...range(0x0a85, 0x0a8b), + 0x0a8d, + ...range(0x0a8f, 0x0a91), + ...range(0x0a93, 0x0aa8), + ...range(0x0aaa, 0x0ab0), + ...range(0x0ab2, 0x0ab3), + ...range(0x0ab5, 0x0ab9), + ...range(0x0abd, 0x0ac0), + 0x0ac9, + ...range(0x0acb, 0x0acc), + 0x0ad0, + 0x0ae0, + ...range(0x0ae6, 0x0aef), + ...range(0x0b02, 0x0b03), + ...range(0x0b05, 0x0b0c), + ...range(0x0b0f, 0x0b10), + ...range(0x0b13, 0x0b28), + ...range(0x0b2a, 0x0b30), + ...range(0x0b32, 0x0b33), + ...range(0x0b36, 0x0b39), + ...range(0x0b3d, 0x0b3e), + 0x0b40, + ...range(0x0b47, 0x0b48), + ...range(0x0b4b, 0x0b4c), + 0x0b57, + ...range(0x0b5c, 0x0b5d), + ...range(0x0b5f, 0x0b61), + ...range(0x0b66, 0x0b70), + 0x0b83, + ...range(0x0b85, 0x0b8a), + ...range(0x0b8e, 0x0b90), + ...range(0x0b92, 0x0b95), + ...range(0x0b99, 0x0b9a), + 0x0b9c, + ...range(0x0b9e, 0x0b9f), + ...range(0x0ba3, 0x0ba4), + ...range(0x0ba8, 0x0baa), + ...range(0x0bae, 0x0bb5), + ...range(0x0bb7, 0x0bb9), + ...range(0x0bbe, 0x0bbf), + ...range(0x0bc1, 0x0bc2), + ...range(0x0bc6, 0x0bc8), + ...range(0x0bca, 0x0bcc), + 0x0bd7, + ...range(0x0be7, 0x0bf2), + ...range(0x0c01, 0x0c03), + ...range(0x0c05, 0x0c0c), + ...range(0x0c0e, 0x0c10), + ...range(0x0c12, 0x0c28), + ...range(0x0c2a, 0x0c33), + ...range(0x0c35, 0x0c39), + ...range(0x0c41, 0x0c44), + ...range(0x0c60, 0x0c61), + ...range(0x0c66, 0x0c6f), + ...range(0x0c82, 0x0c83), + ...range(0x0c85, 0x0c8c), + ...range(0x0c8e, 0x0c90), + ...range(0x0c92, 0x0ca8), + ...range(0x0caa, 0x0cb3), + ...range(0x0cb5, 0x0cb9), + 0x0cbe, + ...range(0x0cc0, 0x0cc4), + ...range(0x0cc7, 0x0cc8), + ...range(0x0cca, 0x0ccb), + ...range(0x0cd5, 0x0cd6), + 0x0cde, + ...range(0x0ce0, 0x0ce1), + ...range(0x0ce6, 0x0cef), + ...range(0x0d02, 0x0d03), + ...range(0x0d05, 0x0d0c), + ...range(0x0d0e, 0x0d10), + ...range(0x0d12, 0x0d28), + ...range(0x0d2a, 0x0d39), + ...range(0x0d3e, 0x0d40), + ...range(0x0d46, 0x0d48), + ...range(0x0d4a, 0x0d4c), + 0x0d57, + ...range(0x0d60, 0x0d61), + ...range(0x0d66, 0x0d6f), + ...range(0x0d82, 0x0d83), + ...range(0x0d85, 0x0d96), + ...range(0x0d9a, 0x0db1), + ...range(0x0db3, 0x0dbb), + 0x0dbd, + ...range(0x0dc0, 0x0dc6), + ...range(0x0dcf, 0x0dd1), + ...range(0x0dd8, 0x0ddf), + ...range(0x0df2, 0x0df4), + ...range(0x0e01, 0x0e30), + ...range(0x0e32, 0x0e33), + ...range(0x0e40, 0x0e46), + ...range(0x0e4f, 0x0e5b), + ...range(0x0e81, 0x0e82), + 0x0e84, + ...range(0x0e87, 0x0e88), + 0x0e8a, + 0x0e8d, + ...range(0x0e94, 0x0e97), + ...range(0x0e99, 0x0e9f), + ...range(0x0ea1, 0x0ea3), + 0x0ea5, + 0x0ea7, + ...range(0x0eaa, 0x0eab), + ...range(0x0ead, 0x0eb0), + ...range(0x0eb2, 0x0eb3), + 0x0ebd, + ...range(0x0ec0, 0x0ec4), + 0x0ec6, + ...range(0x0ed0, 0x0ed9), + ...range(0x0edc, 0x0edd), + ...range(0x0f00, 0x0f17), + ...range(0x0f1a, 0x0f34), + 0x0f36, + 0x0f38, + ...range(0x0f3e, 0x0f47), + ...range(0x0f49, 0x0f6a), + 0x0f7f, + 0x0f85, + ...range(0x0f88, 0x0f8b), + ...range(0x0fbe, 0x0fc5), + ...range(0x0fc7, 0x0fcc), + 0x0fcf, + ...range(0x1000, 0x1021), + ...range(0x1023, 0x1027), + ...range(0x1029, 0x102a), + 0x102c, + 0x1031, + 0x1038, + ...range(0x1040, 0x1057), + ...range(0x10a0, 0x10c5), + ...range(0x10d0, 0x10f8), + 0x10fb, + ...range(0x1100, 0x1159), + ...range(0x115f, 0x11a2), + ...range(0x11a8, 0x11f9), + ...range(0x1200, 0x1206), + ...range(0x1208, 0x1246), + 0x1248, + ...range(0x124a, 0x124d), + ...range(0x1250, 0x1256), + 0x1258, + ...range(0x125a, 0x125d), + ...range(0x1260, 0x1286), + 0x1288, + ...range(0x128a, 0x128d), + ...range(0x1290, 0x12ae), + 0x12b0, + ...range(0x12b2, 0x12b5), + ...range(0x12b8, 0x12be), + 0x12c0, + ...range(0x12c2, 0x12c5), + ...range(0x12c8, 0x12ce), + ...range(0x12d0, 0x12d6), + ...range(0x12d8, 0x12ee), + ...range(0x12f0, 0x130e), + 0x1310, + ...range(0x1312, 0x1315), + ...range(0x1318, 0x131e), + ...range(0x1320, 0x1346), + ...range(0x1348, 0x135a), + ...range(0x1361, 0x137c), + ...range(0x13a0, 0x13f4), + ...range(0x1401, 0x1676), + ...range(0x1681, 0x169a), + ...range(0x16a0, 0x16f0), + ...range(0x1700, 0x170c), + ...range(0x170e, 0x1711), + ...range(0x1720, 0x1731), + ...range(0x1735, 0x1736), + ...range(0x1740, 0x1751), + ...range(0x1760, 0x176c), + ...range(0x176e, 0x1770), + ...range(0x1780, 0x17b6), + ...range(0x17be, 0x17c5), + ...range(0x17c7, 0x17c8), + ...range(0x17d4, 0x17da), + 0x17dc, + ...range(0x17e0, 0x17e9), + ...range(0x1810, 0x1819), + ...range(0x1820, 0x1877), + ...range(0x1880, 0x18a8), + ...range(0x1e00, 0x1e9b), + ...range(0x1ea0, 0x1ef9), + ...range(0x1f00, 0x1f15), + ...range(0x1f18, 0x1f1d), + ...range(0x1f20, 0x1f45), + ...range(0x1f48, 0x1f4d), + ...range(0x1f50, 0x1f57), + 0x1f59, + 0x1f5b, + 0x1f5d, + ...range(0x1f5f, 0x1f7d), + ...range(0x1f80, 0x1fb4), + ...range(0x1fb6, 0x1fbc), + 0x1fbe, + ...range(0x1fc2, 0x1fc4), + ...range(0x1fc6, 0x1fcc), + ...range(0x1fd0, 0x1fd3), + ...range(0x1fd6, 0x1fdb), + ...range(0x1fe0, 0x1fec), + ...range(0x1ff2, 0x1ff4), + ...range(0x1ff6, 0x1ffc), + 0x200e, + 0x2071, + 0x207f, + 0x2102, + 0x2107, + ...range(0x210a, 0x2113), + 0x2115, + ...range(0x2119, 0x211d), + 0x2124, + 0x2126, + 0x2128, + ...range(0x212a, 0x212d), + ...range(0x212f, 0x2131), + ...range(0x2133, 0x2139), + ...range(0x213d, 0x213f), + ...range(0x2145, 0x2149), + ...range(0x2160, 0x2183), + ...range(0x2336, 0x237a), + 0x2395, + ...range(0x249c, 0x24e9), + ...range(0x3005, 0x3007), + ...range(0x3021, 0x3029), + ...range(0x3031, 0x3035), + ...range(0x3038, 0x303c), + ...range(0x3041, 0x3096), + ...range(0x309d, 0x309f), + ...range(0x30a1, 0x30fa), + ...range(0x30fc, 0x30ff), + ...range(0x3105, 0x312c), + ...range(0x3131, 0x318e), + ...range(0x3190, 0x31b7), + ...range(0x31f0, 0x321c), + ...range(0x3220, 0x3243), + ...range(0x3260, 0x327b), + ...range(0x327f, 0x32b0), + ...range(0x32c0, 0x32cb), + ...range(0x32d0, 0x32fe), + ...range(0x3300, 0x3376), + ...range(0x337b, 0x33dd), + ...range(0x33e0, 0x33fe), + ...range(0x3400, 0x4db5), + ...range(0x4e00, 0x9fa5), + ...range(0xa000, 0xa48c), + ...range(0xac00, 0xd7a3), + ...range(0xd800, 0xfa2d), + ...range(0xfa30, 0xfa6a), + ...range(0xfb00, 0xfb06), + ...range(0xfb13, 0xfb17), + ...range(0xff21, 0xff3a), + ...range(0xff41, 0xff5a), + ...range(0xff66, 0xffbe), + ...range(0xffc2, 0xffc7), + ...range(0xffca, 0xffcf), + ...range(0xffd2, 0xffd7), + ...range(0xffda, 0xffdc), + ...range(0x10300, 0x1031e), + ...range(0x10320, 0x10323), + ...range(0x10330, 0x1034a), + ...range(0x10400, 0x10425), + ...range(0x10428, 0x1044d), + ...range(0x1d000, 0x1d0f5), + ...range(0x1d100, 0x1d126), + ...range(0x1d12a, 0x1d166), + ...range(0x1d16a, 0x1d172), + ...range(0x1d183, 0x1d184), + ...range(0x1d18c, 0x1d1a9), + ...range(0x1d1ae, 0x1d1dd), + ...range(0x1d400, 0x1d454), + ...range(0x1d456, 0x1d49c), + ...range(0x1d49e, 0x1d49f), + 0x1d4a2, + ...range(0x1d4a5, 0x1d4a6), + ...range(0x1d4a9, 0x1d4ac), + ...range(0x1d4ae, 0x1d4b9), + 0x1d4bb, + ...range(0x1d4bd, 0x1d4c0), + ...range(0x1d4c2, 0x1d4c3), + ...range(0x1d4c5, 0x1d505), + ...range(0x1d507, 0x1d50a), + ...range(0x1d50d, 0x1d514), + ...range(0x1d516, 0x1d51c), + ...range(0x1d51e, 0x1d539), + ...range(0x1d53b, 0x1d53e), + ...range(0x1d540, 0x1d544), + 0x1d546, + ...range(0x1d54a, 0x1d550), + ...range(0x1d552, 0x1d6a3), + ...range(0x1d6a8, 0x1d7c9), + ...range(0x20000, 0x2a6d6), + ...range(0x2f800, 0x2fa1d), + ...range(0xf0000, 0xffffd), + ...range(0x100000, 0x10fffd), +]); + +module.exports = { + unassigned_code_points, + commonly_mapped_to_nothing, + non_ASCII_space_characters, + prohibited_characters, + bidirectional_r_al, + bidirectional_l, +}; diff --git a/scripts/2.5/node_modules/saslprep/lib/memory-code-points.js b/scripts/2.5/node_modules/saslprep/lib/memory-code-points.js new file mode 100644 index 00000000..cb0289c8 --- /dev/null +++ b/scripts/2.5/node_modules/saslprep/lib/memory-code-points.js @@ -0,0 +1,39 @@ +'use strict'; + +const fs = require('fs'); +const path = require('path'); +const bitfield = require('sparse-bitfield'); + +/* eslint-disable-next-line security/detect-non-literal-fs-filename */ +const memory = fs.readFileSync(path.resolve(__dirname, '../code-points.mem')); +let offset = 0; + +/** + * Loads each code points sequence from buffer. + * @returns {bitfield} + */ +function read() { + const size = memory.readUInt32BE(offset); + offset += 4; + + const codepoints = memory.slice(offset, offset + size); + offset += size; + + return bitfield({ buffer: codepoints }); +} + +const unassigned_code_points = read(); +const commonly_mapped_to_nothing = read(); +const non_ASCII_space_characters = read(); +const prohibited_characters = read(); +const bidirectional_r_al = read(); +const bidirectional_l = read(); + +module.exports = { + unassigned_code_points, + commonly_mapped_to_nothing, + non_ASCII_space_characters, + prohibited_characters, + bidirectional_r_al, + bidirectional_l, +}; diff --git a/scripts/2.5/node_modules/saslprep/lib/util.js b/scripts/2.5/node_modules/saslprep/lib/util.js new file mode 100644 index 00000000..506bdc99 --- /dev/null +++ b/scripts/2.5/node_modules/saslprep/lib/util.js @@ -0,0 +1,21 @@ +'use strict'; + +/** + * Create an array of numbers. + * @param {number} from + * @param {number} to + * @returns {number[]} + */ +function range(from, to) { + // TODO: make this inlined. + const list = new Array(to - from + 1); + + for (let i = 0; i < list.length; i += 1) { + list[i] = from + i; + } + return list; +} + +module.exports = { + range, +}; diff --git a/scripts/2.5/node_modules/saslprep/package.json b/scripts/2.5/node_modules/saslprep/package.json new file mode 100644 index 00000000..ab6adaf5 --- /dev/null +++ b/scripts/2.5/node_modules/saslprep/package.json @@ -0,0 +1,100 @@ +{ + "_from": "saslprep@^1.0.0", + "_id": "saslprep@1.0.3", + "_inBundle": false, + "_integrity": "sha512-/MY/PEMbk2SuY5sScONwhUDsV2p77Znkb/q3nSVstq/yQzYJOH/Azh29p9oJLsl3LnQwSvZDKagDGBsBwSooag==", + "_location": "/saslprep", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "saslprep@^1.0.0", + "name": "saslprep", + "escapedName": "saslprep", + "rawSpec": "^1.0.0", + "saveSpec": null, + "fetchSpec": "^1.0.0" + }, + "_requiredBy": [ + "/mongodb" + ], + "_resolved": "https://registry.npmjs.org/saslprep/-/saslprep-1.0.3.tgz", + "_shasum": "4c02f946b56cf54297e347ba1093e7acac4cf226", + "_spec": "saslprep@^1.0.0", + "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/2.5/node_modules/mongodb", + "author": { + "name": "Dmitry Tsvettsikh", + "email": "me@reklatsmasters.com" + }, + "bugs": { + "url": "https://github.com/reklatsmasters/saslprep/issues" + }, + "bundleDependencies": false, + "dependencies": { + "sparse-bitfield": "^3.0.3" + }, + "deprecated": false, + "description": "SASLprep: Stringprep Profile for User Names and Passwords, rfc4013.", + "devDependencies": { + "@nodertc/eslint-config": "^0.2.1", + "eslint": "^5.16.0", + "jest": "^23.6.0", + "prettier": "^1.14.3" + }, + "engines": { + "node": ">=6" + }, + "eslintConfig": { + "extends": "@nodertc", + "rules": { + "camelcase": "off", + "no-continue": "off" + }, + "overrides": [ + { + "files": [ + "test/*.js" + ], + "env": { + "jest": true + }, + "rules": { + "require-jsdoc": "off" + } + } + ] + }, + "homepage": "https://github.com/reklatsmasters/saslprep#readme", + "jest": { + "modulePaths": [ + "" + ], + "testMatch": [ + "**/test/*.js" + ], + "testPathIgnorePatterns": [ + "/node_modules/" + ] + }, + "keywords": [ + "sasl", + "saslprep", + "stringprep", + "rfc4013", + "4013" + ], + "license": "MIT", + "main": "index.js", + "name": "saslprep", + "repository": { + "type": "git", + "url": "git+https://github.com/reklatsmasters/saslprep.git" + }, + "scripts": { + "gen-code-points": "node generate-code-points.js > code-points.mem", + "lint": "npx eslint --quiet .", + "test": "npm run lint && npm run unit-test", + "unit-test": "npx jest" + }, + "version": "1.0.3" +} diff --git a/scripts/2.5/node_modules/saslprep/readme.md b/scripts/2.5/node_modules/saslprep/readme.md new file mode 100644 index 00000000..8ff3d70d --- /dev/null +++ b/scripts/2.5/node_modules/saslprep/readme.md @@ -0,0 +1,31 @@ +# saslprep +[![Build Status](https://travis-ci.org/reklatsmasters/saslprep.svg?branch=master)](https://travis-ci.org/reklatsmasters/saslprep) +[![npm](https://img.shields.io/npm/v/saslprep.svg)](https://npmjs.org/package/saslprep) +[![node](https://img.shields.io/node/v/saslprep.svg)](https://npmjs.org/package/saslprep) +[![license](https://img.shields.io/npm/l/saslprep.svg)](https://npmjs.org/package/saslprep) +[![downloads](https://img.shields.io/npm/dm/saslprep.svg)](https://npmjs.org/package/saslprep) + +Stringprep Profile for User Names and Passwords, [rfc4013](https://tools.ietf.org/html/rfc4013) + +### Usage + +```js +const saslprep = require('saslprep') + +saslprep('password\u00AD') // password +saslprep('password\u0007') // Error: prohibited character +``` + +### API + +##### `saslprep(input: String, opts: Options): String` + +Normalize user name or password. + +##### `Options.allowUnassigned: bool` + +A special behavior for unassigned code points, see https://tools.ietf.org/html/rfc4013#section-2.5. Disabled by default. + +## License + +MIT, 2017-2019 (c) Dmitriy Tsvettsikh diff --git a/scripts/2.5/node_modules/saslprep/test/index.js b/scripts/2.5/node_modules/saslprep/test/index.js new file mode 100644 index 00000000..80c71af5 --- /dev/null +++ b/scripts/2.5/node_modules/saslprep/test/index.js @@ -0,0 +1,76 @@ +'use strict'; + +const saslprep = require('..'); + +const chr = String.fromCodePoint; + +test('should work with liatin letters', () => { + const str = 'user'; + expect(saslprep(str)).toEqual(str); +}); + +test('should work be case preserved', () => { + const str = 'USER'; + expect(saslprep(str)).toEqual(str); +}); + +test('should work with high code points (> U+FFFF)', () => { + const str = '\uD83D\uDE00'; + expect(saslprep(str, { allowUnassigned: true })).toEqual(str); +}); + +test('should remove `mapped to nothing` characters', () => { + expect(saslprep('I\u00ADX')).toEqual('IX'); +}); + +test('should replace `Non-ASCII space characters` with space', () => { + expect(saslprep('a\u00A0b')).toEqual('a\u0020b'); +}); + +test('should normalize as NFKC', () => { + expect(saslprep('\u00AA')).toEqual('a'); + expect(saslprep('\u2168')).toEqual('IX'); +}); + +test('should throws when prohibited characters', () => { + // C.2.1 ASCII control characters + expect(() => saslprep('a\u007Fb')).toThrow(); + + // C.2.2 Non-ASCII control characters + expect(() => saslprep('a\u06DDb')).toThrow(); + + // C.3 Private use + expect(() => saslprep('a\uE000b')).toThrow(); + + // C.4 Non-character code points + expect(() => saslprep(`a${chr(0x1fffe)}b`)).toThrow(); + + // C.5 Surrogate codes + expect(() => saslprep('a\uD800b')).toThrow(); + + // C.6 Inappropriate for plain text + expect(() => saslprep('a\uFFF9b')).toThrow(); + + // C.7 Inappropriate for canonical representation + expect(() => saslprep('a\u2FF0b')).toThrow(); + + // C.8 Change display properties or are deprecated + expect(() => saslprep('a\u200Eb')).toThrow(); + + // C.9 Tagging characters + expect(() => saslprep(`a${chr(0xe0001)}b`)).toThrow(); +}); + +test('should not containt RandALCat and LCat bidi', () => { + expect(() => saslprep('a\u06DD\u00AAb')).toThrow(); +}); + +test('RandALCat should be first and last', () => { + expect(() => saslprep('\u0627\u0031\u0628')).not.toThrow(); + expect(() => saslprep('\u0627\u0031')).toThrow(); +}); + +test('should handle unassigned code points', () => { + expect(() => saslprep('a\u0487')).toThrow(); + expect(() => saslprep('a\u0487', { allowUnassigned: true })).not.toThrow(); +}); diff --git a/scripts/2.5/node_modules/saslprep/test/util.js b/scripts/2.5/node_modules/saslprep/test/util.js new file mode 100644 index 00000000..355db3f8 --- /dev/null +++ b/scripts/2.5/node_modules/saslprep/test/util.js @@ -0,0 +1,16 @@ +'use strict'; + +const { setFlagsFromString } = require('v8'); +const { range } = require('../lib/util'); + +// 984 by default. +setFlagsFromString('--stack_size=500'); + +test('should work', () => { + const list = range(1, 3); + expect(list).toEqual([1, 2, 3]); +}); + +test('should work for large ranges', () => { + expect(() => range(1, 1e6)).not.toThrow(); +}); diff --git a/scripts/2.5/node_modules/semver/CHANGELOG.md b/scripts/2.5/node_modules/semver/CHANGELOG.md new file mode 100644 index 00000000..66304fdd --- /dev/null +++ b/scripts/2.5/node_modules/semver/CHANGELOG.md @@ -0,0 +1,39 @@ +# changes log + +## 5.7 + +* Add `minVersion` method + +## 5.6 + +* Move boolean `loose` param to an options object, with + backwards-compatibility protection. +* Add ability to opt out of special prerelease version handling with + the `includePrerelease` option flag. + +## 5.5 + +* Add version coercion capabilities + +## 5.4 + +* Add intersection checking + +## 5.3 + +* Add `minSatisfying` method + +## 5.2 + +* Add `prerelease(v)` that returns prerelease components + +## 5.1 + +* Add Backus-Naur for ranges +* Remove excessively cute inspection methods + +## 5.0 + +* Remove AMD/Browserified build artifacts +* Fix ltr and gtr when using the `*` range +* Fix for range `*` with a prerelease identifier diff --git a/scripts/2.5/node_modules/semver/LICENSE b/scripts/2.5/node_modules/semver/LICENSE new file mode 100644 index 00000000..19129e31 --- /dev/null +++ b/scripts/2.5/node_modules/semver/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/scripts/2.5/node_modules/semver/README.md b/scripts/2.5/node_modules/semver/README.md new file mode 100644 index 00000000..f8dfa5a0 --- /dev/null +++ b/scripts/2.5/node_modules/semver/README.md @@ -0,0 +1,412 @@ +semver(1) -- The semantic versioner for npm +=========================================== + +## Install + +```bash +npm install --save semver +```` + +## Usage + +As a node module: + +```js +const semver = require('semver') + +semver.valid('1.2.3') // '1.2.3' +semver.valid('a.b.c') // null +semver.clean(' =v1.2.3 ') // '1.2.3' +semver.satisfies('1.2.3', '1.x || >=2.5.0 || 5.0.0 - 7.2.3') // true +semver.gt('1.2.3', '9.8.7') // false +semver.lt('1.2.3', '9.8.7') // true +semver.minVersion('>=1.0.0') // '1.0.0' +semver.valid(semver.coerce('v2')) // '2.0.0' +semver.valid(semver.coerce('42.6.7.9.3-alpha')) // '42.6.7' +``` + +As a command-line utility: + +``` +$ semver -h + +A JavaScript implementation of the https://semver.org/ specification +Copyright Isaac Z. Schlueter + +Usage: semver [options] [ [...]] +Prints valid versions sorted by SemVer precedence + +Options: +-r --range + Print versions that match the specified range. + +-i --increment [] + Increment a version by the specified level. Level can + be one of: major, minor, patch, premajor, preminor, + prepatch, or prerelease. Default level is 'patch'. + Only one version may be specified. + +--preid + Identifier to be used to prefix premajor, preminor, + prepatch or prerelease version increments. + +-l --loose + Interpret versions and ranges loosely + +-p --include-prerelease + Always include prerelease versions in range matching + +-c --coerce + Coerce a string into SemVer if possible + (does not imply --loose) + +Program exits successfully if any valid version satisfies +all supplied ranges, and prints all satisfying versions. + +If no satisfying versions are found, then exits failure. + +Versions are printed in ascending order, so supplying +multiple versions to the utility will just sort them. +``` + +## Versions + +A "version" is described by the `v2.0.0` specification found at +. + +A leading `"="` or `"v"` character is stripped off and ignored. + +## Ranges + +A `version range` is a set of `comparators` which specify versions +that satisfy the range. + +A `comparator` is composed of an `operator` and a `version`. The set +of primitive `operators` is: + +* `<` Less than +* `<=` Less than or equal to +* `>` Greater than +* `>=` Greater than or equal to +* `=` Equal. If no operator is specified, then equality is assumed, + so this operator is optional, but MAY be included. + +For example, the comparator `>=1.2.7` would match the versions +`1.2.7`, `1.2.8`, `2.5.3`, and `1.3.9`, but not the versions `1.2.6` +or `1.1.0`. + +Comparators can be joined by whitespace to form a `comparator set`, +which is satisfied by the **intersection** of all of the comparators +it includes. + +A range is composed of one or more comparator sets, joined by `||`. A +version matches a range if and only if every comparator in at least +one of the `||`-separated comparator sets is satisfied by the version. + +For example, the range `>=1.2.7 <1.3.0` would match the versions +`1.2.7`, `1.2.8`, and `1.2.99`, but not the versions `1.2.6`, `1.3.0`, +or `1.1.0`. + +The range `1.2.7 || >=1.2.9 <2.0.0` would match the versions `1.2.7`, +`1.2.9`, and `1.4.6`, but not the versions `1.2.8` or `2.0.0`. + +### Prerelease Tags + +If a version has a prerelease tag (for example, `1.2.3-alpha.3`) then +it will only be allowed to satisfy comparator sets if at least one +comparator with the same `[major, minor, patch]` tuple also has a +prerelease tag. + +For example, the range `>1.2.3-alpha.3` would be allowed to match the +version `1.2.3-alpha.7`, but it would *not* be satisfied by +`3.4.5-alpha.9`, even though `3.4.5-alpha.9` is technically "greater +than" `1.2.3-alpha.3` according to the SemVer sort rules. The version +range only accepts prerelease tags on the `1.2.3` version. The +version `3.4.5` *would* satisfy the range, because it does not have a +prerelease flag, and `3.4.5` is greater than `1.2.3-alpha.7`. + +The purpose for this behavior is twofold. First, prerelease versions +frequently are updated very quickly, and contain many breaking changes +that are (by the author's design) not yet fit for public consumption. +Therefore, by default, they are excluded from range matching +semantics. + +Second, a user who has opted into using a prerelease version has +clearly indicated the intent to use *that specific* set of +alpha/beta/rc versions. By including a prerelease tag in the range, +the user is indicating that they are aware of the risk. However, it +is still not appropriate to assume that they have opted into taking a +similar risk on the *next* set of prerelease versions. + +Note that this behavior can be suppressed (treating all prerelease +versions as if they were normal versions, for the purpose of range +matching) by setting the `includePrerelease` flag on the options +object to any +[functions](https://github.com/npm/node-semver#functions) that do +range matching. + +#### Prerelease Identifiers + +The method `.inc` takes an additional `identifier` string argument that +will append the value of the string as a prerelease identifier: + +```javascript +semver.inc('1.2.3', 'prerelease', 'beta') +// '1.2.4-beta.0' +``` + +command-line example: + +```bash +$ semver 1.2.3 -i prerelease --preid beta +1.2.4-beta.0 +``` + +Which then can be used to increment further: + +```bash +$ semver 1.2.4-beta.0 -i prerelease +1.2.4-beta.1 +``` + +### Advanced Range Syntax + +Advanced range syntax desugars to primitive comparators in +deterministic ways. + +Advanced ranges may be combined in the same way as primitive +comparators using white space or `||`. + +#### Hyphen Ranges `X.Y.Z - A.B.C` + +Specifies an inclusive set. + +* `1.2.3 - 2.3.4` := `>=1.2.3 <=2.3.4` + +If a partial version is provided as the first version in the inclusive +range, then the missing pieces are replaced with zeroes. + +* `1.2 - 2.3.4` := `>=1.2.0 <=2.3.4` + +If a partial version is provided as the second version in the +inclusive range, then all versions that start with the supplied parts +of the tuple are accepted, but nothing that would be greater than the +provided tuple parts. + +* `1.2.3 - 2.3` := `>=1.2.3 <2.4.0` +* `1.2.3 - 2` := `>=1.2.3 <3.0.0` + +#### X-Ranges `1.2.x` `1.X` `1.2.*` `*` + +Any of `X`, `x`, or `*` may be used to "stand in" for one of the +numeric values in the `[major, minor, patch]` tuple. + +* `*` := `>=0.0.0` (Any version satisfies) +* `1.x` := `>=1.0.0 <2.0.0` (Matching major version) +* `1.2.x` := `>=1.2.0 <1.3.0` (Matching major and minor versions) + +A partial version range is treated as an X-Range, so the special +character is in fact optional. + +* `""` (empty string) := `*` := `>=0.0.0` +* `1` := `1.x.x` := `>=1.0.0 <2.0.0` +* `1.2` := `1.2.x` := `>=1.2.0 <1.3.0` + +#### Tilde Ranges `~1.2.3` `~1.2` `~1` + +Allows patch-level changes if a minor version is specified on the +comparator. Allows minor-level changes if not. + +* `~1.2.3` := `>=1.2.3 <1.(2+1).0` := `>=1.2.3 <1.3.0` +* `~1.2` := `>=1.2.0 <1.(2+1).0` := `>=1.2.0 <1.3.0` (Same as `1.2.x`) +* `~1` := `>=1.0.0 <(1+1).0.0` := `>=1.0.0 <2.0.0` (Same as `1.x`) +* `~0.2.3` := `>=0.2.3 <0.(2+1).0` := `>=0.2.3 <0.3.0` +* `~0.2` := `>=0.2.0 <0.(2+1).0` := `>=0.2.0 <0.3.0` (Same as `0.2.x`) +* `~0` := `>=0.0.0 <(0+1).0.0` := `>=0.0.0 <1.0.0` (Same as `0.x`) +* `~1.2.3-beta.2` := `>=1.2.3-beta.2 <1.3.0` Note that prereleases in + the `1.2.3` version will be allowed, if they are greater than or + equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but + `1.2.4-beta.2` would not, because it is a prerelease of a + different `[major, minor, patch]` tuple. + +#### Caret Ranges `^1.2.3` `^0.2.5` `^0.0.4` + +Allows changes that do not modify the left-most non-zero digit in the +`[major, minor, patch]` tuple. In other words, this allows patch and +minor updates for versions `1.0.0` and above, patch updates for +versions `0.X >=0.1.0`, and *no* updates for versions `0.0.X`. + +Many authors treat a `0.x` version as if the `x` were the major +"breaking-change" indicator. + +Caret ranges are ideal when an author may make breaking changes +between `0.2.4` and `0.3.0` releases, which is a common practice. +However, it presumes that there will *not* be breaking changes between +`0.2.4` and `0.2.5`. It allows for changes that are presumed to be +additive (but non-breaking), according to commonly observed practices. + +* `^1.2.3` := `>=1.2.3 <2.0.0` +* `^0.2.3` := `>=0.2.3 <0.3.0` +* `^0.0.3` := `>=0.0.3 <0.0.4` +* `^1.2.3-beta.2` := `>=1.2.3-beta.2 <2.0.0` Note that prereleases in + the `1.2.3` version will be allowed, if they are greater than or + equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but + `1.2.4-beta.2` would not, because it is a prerelease of a + different `[major, minor, patch]` tuple. +* `^0.0.3-beta` := `>=0.0.3-beta <0.0.4` Note that prereleases in the + `0.0.3` version *only* will be allowed, if they are greater than or + equal to `beta`. So, `0.0.3-pr.2` would be allowed. + +When parsing caret ranges, a missing `patch` value desugars to the +number `0`, but will allow flexibility within that value, even if the +major and minor versions are both `0`. + +* `^1.2.x` := `>=1.2.0 <2.0.0` +* `^0.0.x` := `>=0.0.0 <0.1.0` +* `^0.0` := `>=0.0.0 <0.1.0` + +A missing `minor` and `patch` values will desugar to zero, but also +allow flexibility within those values, even if the major version is +zero. + +* `^1.x` := `>=1.0.0 <2.0.0` +* `^0.x` := `>=0.0.0 <1.0.0` + +### Range Grammar + +Putting all this together, here is a Backus-Naur grammar for ranges, +for the benefit of parser authors: + +```bnf +range-set ::= range ( logical-or range ) * +logical-or ::= ( ' ' ) * '||' ( ' ' ) * +range ::= hyphen | simple ( ' ' simple ) * | '' +hyphen ::= partial ' - ' partial +simple ::= primitive | partial | tilde | caret +primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial +partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? +xr ::= 'x' | 'X' | '*' | nr +nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * +tilde ::= '~' partial +caret ::= '^' partial +qualifier ::= ( '-' pre )? ( '+' build )? +pre ::= parts +build ::= parts +parts ::= part ( '.' part ) * +part ::= nr | [-0-9A-Za-z]+ +``` + +## Functions + +All methods and classes take a final `options` object argument. All +options in this object are `false` by default. The options supported +are: + +- `loose` Be more forgiving about not-quite-valid semver strings. + (Any resulting output will always be 100% strict compliant, of + course.) For backwards compatibility reasons, if the `options` + argument is a boolean value instead of an object, it is interpreted + to be the `loose` param. +- `includePrerelease` Set to suppress the [default + behavior](https://github.com/npm/node-semver#prerelease-tags) of + excluding prerelease tagged versions from ranges unless they are + explicitly opted into. + +Strict-mode Comparators and Ranges will be strict about the SemVer +strings that they parse. + +* `valid(v)`: Return the parsed version, or null if it's not valid. +* `inc(v, release)`: Return the version incremented by the release + type (`major`, `premajor`, `minor`, `preminor`, `patch`, + `prepatch`, or `prerelease`), or null if it's not valid + * `premajor` in one call will bump the version up to the next major + version and down to a prerelease of that major version. + `preminor`, and `prepatch` work the same way. + * If called from a non-prerelease version, the `prerelease` will work the + same as `prepatch`. It increments the patch version, then makes a + prerelease. If the input version is already a prerelease it simply + increments it. +* `prerelease(v)`: Returns an array of prerelease components, or null + if none exist. Example: `prerelease('1.2.3-alpha.1') -> ['alpha', 1]` +* `major(v)`: Return the major version number. +* `minor(v)`: Return the minor version number. +* `patch(v)`: Return the patch version number. +* `intersects(r1, r2, loose)`: Return true if the two supplied ranges + or comparators intersect. +* `parse(v)`: Attempt to parse a string as a semantic version, returning either + a `SemVer` object or `null`. + +### Comparison + +* `gt(v1, v2)`: `v1 > v2` +* `gte(v1, v2)`: `v1 >= v2` +* `lt(v1, v2)`: `v1 < v2` +* `lte(v1, v2)`: `v1 <= v2` +* `eq(v1, v2)`: `v1 == v2` This is true if they're logically equivalent, + even if they're not the exact same string. You already know how to + compare strings. +* `neq(v1, v2)`: `v1 != v2` The opposite of `eq`. +* `cmp(v1, comparator, v2)`: Pass in a comparison string, and it'll call + the corresponding function above. `"==="` and `"!=="` do simple + string comparison, but are included for completeness. Throws if an + invalid comparison string is provided. +* `compare(v1, v2)`: Return `0` if `v1 == v2`, or `1` if `v1` is greater, or `-1` if + `v2` is greater. Sorts in ascending order if passed to `Array.sort()`. +* `rcompare(v1, v2)`: The reverse of compare. Sorts an array of versions + in descending order when passed to `Array.sort()`. +* `diff(v1, v2)`: Returns difference between two versions by the release type + (`major`, `premajor`, `minor`, `preminor`, `patch`, `prepatch`, or `prerelease`), + or null if the versions are the same. + +### Comparators + +* `intersects(comparator)`: Return true if the comparators intersect + +### Ranges + +* `validRange(range)`: Return the valid range or null if it's not valid +* `satisfies(version, range)`: Return true if the version satisfies the + range. +* `maxSatisfying(versions, range)`: Return the highest version in the list + that satisfies the range, or `null` if none of them do. +* `minSatisfying(versions, range)`: Return the lowest version in the list + that satisfies the range, or `null` if none of them do. +* `minVersion(range)`: Return the lowest version that can possibly match + the given range. +* `gtr(version, range)`: Return `true` if version is greater than all the + versions possible in the range. +* `ltr(version, range)`: Return `true` if version is less than all the + versions possible in the range. +* `outside(version, range, hilo)`: Return true if the version is outside + the bounds of the range in either the high or low direction. The + `hilo` argument must be either the string `'>'` or `'<'`. (This is + the function called by `gtr` and `ltr`.) +* `intersects(range)`: Return true if any of the ranges comparators intersect + +Note that, since ranges may be non-contiguous, a version might not be +greater than a range, less than a range, *or* satisfy a range! For +example, the range `1.2 <1.2.9 || >2.0.0` would have a hole from `1.2.9` +until `2.0.0`, so the version `1.2.10` would not be greater than the +range (because `2.0.1` satisfies, which is higher), nor less than the +range (since `1.2.8` satisfies, which is lower), and it also does not +satisfy the range. + +If you want to know if a version satisfies or does not satisfy a +range, use the `satisfies(version, range)` function. + +### Coercion + +* `coerce(version)`: Coerces a string to semver if possible + +This aims to provide a very forgiving translation of a non-semver string to +semver. It looks for the first digit in a string, and consumes all +remaining characters which satisfy at least a partial semver (e.g., `1`, +`1.2`, `1.2.3`) up to the max permitted length (256 characters). Longer +versions are simply truncated (`4.6.3.9.2-alpha2` becomes `4.6.3`). All +surrounding text is simply ignored (`v3.4 replaces v3.3.1` becomes +`3.4.0`). Only text which lacks digits will fail coercion (`version one` +is not valid). The maximum length for any semver component considered for +coercion is 16 characters; longer components will be ignored +(`10000000000000000.4.7.4` becomes `4.7.4`). The maximum value for any +semver component is `Number.MAX_SAFE_INTEGER || (2**53 - 1)`; higher value +components are invalid (`9999999999999999.4.7.4` is likely invalid). diff --git a/scripts/2.5/node_modules/semver/bin/semver b/scripts/2.5/node_modules/semver/bin/semver new file mode 100755 index 00000000..801e77f1 --- /dev/null +++ b/scripts/2.5/node_modules/semver/bin/semver @@ -0,0 +1,160 @@ +#!/usr/bin/env node +// Standalone semver comparison program. +// Exits successfully and prints matching version(s) if +// any supplied version is valid and passes all tests. + +var argv = process.argv.slice(2) + +var versions = [] + +var range = [] + +var inc = null + +var version = require('../package.json').version + +var loose = false + +var includePrerelease = false + +var coerce = false + +var identifier + +var semver = require('../semver') + +var reverse = false + +var options = {} + +main() + +function main () { + if (!argv.length) return help() + while (argv.length) { + var a = argv.shift() + var indexOfEqualSign = a.indexOf('=') + if (indexOfEqualSign !== -1) { + a = a.slice(0, indexOfEqualSign) + argv.unshift(a.slice(indexOfEqualSign + 1)) + } + switch (a) { + case '-rv': case '-rev': case '--rev': case '--reverse': + reverse = true + break + case '-l': case '--loose': + loose = true + break + case '-p': case '--include-prerelease': + includePrerelease = true + break + case '-v': case '--version': + versions.push(argv.shift()) + break + case '-i': case '--inc': case '--increment': + switch (argv[0]) { + case 'major': case 'minor': case 'patch': case 'prerelease': + case 'premajor': case 'preminor': case 'prepatch': + inc = argv.shift() + break + default: + inc = 'patch' + break + } + break + case '--preid': + identifier = argv.shift() + break + case '-r': case '--range': + range.push(argv.shift()) + break + case '-c': case '--coerce': + coerce = true + break + case '-h': case '--help': case '-?': + return help() + default: + versions.push(a) + break + } + } + + var options = { loose: loose, includePrerelease: includePrerelease } + + versions = versions.map(function (v) { + return coerce ? (semver.coerce(v) || { version: v }).version : v + }).filter(function (v) { + return semver.valid(v) + }) + if (!versions.length) return fail() + if (inc && (versions.length !== 1 || range.length)) { return failInc() } + + for (var i = 0, l = range.length; i < l; i++) { + versions = versions.filter(function (v) { + return semver.satisfies(v, range[i], options) + }) + if (!versions.length) return fail() + } + return success(versions) +} + +function failInc () { + console.error('--inc can only be used on a single version with no range') + fail() +} + +function fail () { process.exit(1) } + +function success () { + var compare = reverse ? 'rcompare' : 'compare' + versions.sort(function (a, b) { + return semver[compare](a, b, options) + }).map(function (v) { + return semver.clean(v, options) + }).map(function (v) { + return inc ? semver.inc(v, inc, options, identifier) : v + }).forEach(function (v, i, _) { console.log(v) }) +} + +function help () { + console.log(['SemVer ' + version, + '', + 'A JavaScript implementation of the https://semver.org/ specification', + 'Copyright Isaac Z. Schlueter', + '', + 'Usage: semver [options] [ [...]]', + 'Prints valid versions sorted by SemVer precedence', + '', + 'Options:', + '-r --range ', + ' Print versions that match the specified range.', + '', + '-i --increment []', + ' Increment a version by the specified level. Level can', + ' be one of: major, minor, patch, premajor, preminor,', + " prepatch, or prerelease. Default level is 'patch'.", + ' Only one version may be specified.', + '', + '--preid ', + ' Identifier to be used to prefix premajor, preminor,', + ' prepatch or prerelease version increments.', + '', + '-l --loose', + ' Interpret versions and ranges loosely', + '', + '-p --include-prerelease', + ' Always include prerelease versions in range matching', + '', + '-c --coerce', + ' Coerce a string into SemVer if possible', + ' (does not imply --loose)', + '', + 'Program exits successfully if any valid version satisfies', + 'all supplied ranges, and prints all satisfying versions.', + '', + 'If no satisfying versions are found, then exits failure.', + '', + 'Versions are printed in ascending order, so supplying', + 'multiple versions to the utility will just sort them.' + ].join('\n')) +} diff --git a/scripts/2.5/node_modules/semver/package.json b/scripts/2.5/node_modules/semver/package.json new file mode 100644 index 00000000..61475155 --- /dev/null +++ b/scripts/2.5/node_modules/semver/package.json @@ -0,0 +1,60 @@ +{ + "_from": "semver@^5.1.0", + "_id": "semver@5.7.1", + "_inBundle": false, + "_integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==", + "_location": "/semver", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "semver@^5.1.0", + "name": "semver", + "escapedName": "semver", + "rawSpec": "^5.1.0", + "saveSpec": null, + "fetchSpec": "^5.1.0" + }, + "_requiredBy": [ + "/require_optional" + ], + "_resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz", + "_shasum": "a954f931aeba508d307bbf069eff0c01c96116f7", + "_spec": "semver@^5.1.0", + "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/2.5/node_modules/require_optional", + "bin": { + "semver": "./bin/semver" + }, + "bugs": { + "url": "https://github.com/npm/node-semver/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "The semantic version parser used by npm.", + "devDependencies": { + "tap": "^13.0.0-rc.18" + }, + "files": [ + "bin", + "range.bnf", + "semver.js" + ], + "homepage": "https://github.com/npm/node-semver#readme", + "license": "ISC", + "main": "semver.js", + "name": "semver", + "repository": { + "type": "git", + "url": "git+https://github.com/npm/node-semver.git" + }, + "scripts": { + "postpublish": "git push origin --all; git push origin --tags", + "postversion": "npm publish", + "preversion": "npm test", + "test": "tap" + }, + "tap": { + "check-coverage": true + }, + "version": "5.7.1" +} diff --git a/scripts/2.5/node_modules/semver/range.bnf b/scripts/2.5/node_modules/semver/range.bnf new file mode 100644 index 00000000..d4c6ae0d --- /dev/null +++ b/scripts/2.5/node_modules/semver/range.bnf @@ -0,0 +1,16 @@ +range-set ::= range ( logical-or range ) * +logical-or ::= ( ' ' ) * '||' ( ' ' ) * +range ::= hyphen | simple ( ' ' simple ) * | '' +hyphen ::= partial ' - ' partial +simple ::= primitive | partial | tilde | caret +primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial +partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? +xr ::= 'x' | 'X' | '*' | nr +nr ::= '0' | [1-9] ( [0-9] ) * +tilde ::= '~' partial +caret ::= '^' partial +qualifier ::= ( '-' pre )? ( '+' build )? +pre ::= parts +build ::= parts +parts ::= part ( '.' part ) * +part ::= nr | [-0-9A-Za-z]+ diff --git a/scripts/2.5/node_modules/semver/semver.js b/scripts/2.5/node_modules/semver/semver.js new file mode 100644 index 00000000..d315d5d6 --- /dev/null +++ b/scripts/2.5/node_modules/semver/semver.js @@ -0,0 +1,1483 @@ +exports = module.exports = SemVer + +var debug +/* istanbul ignore next */ +if (typeof process === 'object' && + process.env && + process.env.NODE_DEBUG && + /\bsemver\b/i.test(process.env.NODE_DEBUG)) { + debug = function () { + var args = Array.prototype.slice.call(arguments, 0) + args.unshift('SEMVER') + console.log.apply(console, args) + } +} else { + debug = function () {} +} + +// Note: this is the semver.org version of the spec that it implements +// Not necessarily the package version of this code. +exports.SEMVER_SPEC_VERSION = '2.0.0' + +var MAX_LENGTH = 256 +var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || + /* istanbul ignore next */ 9007199254740991 + +// Max safe segment length for coercion. +var MAX_SAFE_COMPONENT_LENGTH = 16 + +// The actual regexps go on exports.re +var re = exports.re = [] +var src = exports.src = [] +var R = 0 + +// The following Regular Expressions can be used for tokenizing, +// validating, and parsing SemVer version strings. + +// ## Numeric Identifier +// A single `0`, or a non-zero digit followed by zero or more digits. + +var NUMERICIDENTIFIER = R++ +src[NUMERICIDENTIFIER] = '0|[1-9]\\d*' +var NUMERICIDENTIFIERLOOSE = R++ +src[NUMERICIDENTIFIERLOOSE] = '[0-9]+' + +// ## Non-numeric Identifier +// Zero or more digits, followed by a letter or hyphen, and then zero or +// more letters, digits, or hyphens. + +var NONNUMERICIDENTIFIER = R++ +src[NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*' + +// ## Main Version +// Three dot-separated numeric identifiers. + +var MAINVERSION = R++ +src[MAINVERSION] = '(' + src[NUMERICIDENTIFIER] + ')\\.' + + '(' + src[NUMERICIDENTIFIER] + ')\\.' + + '(' + src[NUMERICIDENTIFIER] + ')' + +var MAINVERSIONLOOSE = R++ +src[MAINVERSIONLOOSE] = '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + + '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + + '(' + src[NUMERICIDENTIFIERLOOSE] + ')' + +// ## Pre-release Version Identifier +// A numeric identifier, or a non-numeric identifier. + +var PRERELEASEIDENTIFIER = R++ +src[PRERELEASEIDENTIFIER] = '(?:' + src[NUMERICIDENTIFIER] + + '|' + src[NONNUMERICIDENTIFIER] + ')' + +var PRERELEASEIDENTIFIERLOOSE = R++ +src[PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[NUMERICIDENTIFIERLOOSE] + + '|' + src[NONNUMERICIDENTIFIER] + ')' + +// ## Pre-release Version +// Hyphen, followed by one or more dot-separated pre-release version +// identifiers. + +var PRERELEASE = R++ +src[PRERELEASE] = '(?:-(' + src[PRERELEASEIDENTIFIER] + + '(?:\\.' + src[PRERELEASEIDENTIFIER] + ')*))' + +var PRERELEASELOOSE = R++ +src[PRERELEASELOOSE] = '(?:-?(' + src[PRERELEASEIDENTIFIERLOOSE] + + '(?:\\.' + src[PRERELEASEIDENTIFIERLOOSE] + ')*))' + +// ## Build Metadata Identifier +// Any combination of digits, letters, or hyphens. + +var BUILDIDENTIFIER = R++ +src[BUILDIDENTIFIER] = '[0-9A-Za-z-]+' + +// ## Build Metadata +// Plus sign, followed by one or more period-separated build metadata +// identifiers. + +var BUILD = R++ +src[BUILD] = '(?:\\+(' + src[BUILDIDENTIFIER] + + '(?:\\.' + src[BUILDIDENTIFIER] + ')*))' + +// ## Full Version String +// A main version, followed optionally by a pre-release version and +// build metadata. + +// Note that the only major, minor, patch, and pre-release sections of +// the version string are capturing groups. The build metadata is not a +// capturing group, because it should not ever be used in version +// comparison. + +var FULL = R++ +var FULLPLAIN = 'v?' + src[MAINVERSION] + + src[PRERELEASE] + '?' + + src[BUILD] + '?' + +src[FULL] = '^' + FULLPLAIN + '$' + +// like full, but allows v1.2.3 and =1.2.3, which people do sometimes. +// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty +// common in the npm registry. +var LOOSEPLAIN = '[v=\\s]*' + src[MAINVERSIONLOOSE] + + src[PRERELEASELOOSE] + '?' + + src[BUILD] + '?' + +var LOOSE = R++ +src[LOOSE] = '^' + LOOSEPLAIN + '$' + +var GTLT = R++ +src[GTLT] = '((?:<|>)?=?)' + +// Something like "2.*" or "1.2.x". +// Note that "x.x" is a valid xRange identifer, meaning "any version" +// Only the first item is strictly required. +var XRANGEIDENTIFIERLOOSE = R++ +src[XRANGEIDENTIFIERLOOSE] = src[NUMERICIDENTIFIERLOOSE] + '|x|X|\\*' +var XRANGEIDENTIFIER = R++ +src[XRANGEIDENTIFIER] = src[NUMERICIDENTIFIER] + '|x|X|\\*' + +var XRANGEPLAIN = R++ +src[XRANGEPLAIN] = '[v=\\s]*(' + src[XRANGEIDENTIFIER] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + + '(?:' + src[PRERELEASE] + ')?' + + src[BUILD] + '?' + + ')?)?' + +var XRANGEPLAINLOOSE = R++ +src[XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[XRANGEIDENTIFIERLOOSE] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + + '(?:' + src[PRERELEASELOOSE] + ')?' + + src[BUILD] + '?' + + ')?)?' + +var XRANGE = R++ +src[XRANGE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAIN] + '$' +var XRANGELOOSE = R++ +src[XRANGELOOSE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAINLOOSE] + '$' + +// Coercion. +// Extract anything that could conceivably be a part of a valid semver +var COERCE = R++ +src[COERCE] = '(?:^|[^\\d])' + + '(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' + + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + + '(?:$|[^\\d])' + +// Tilde ranges. +// Meaning is "reasonably at or greater than" +var LONETILDE = R++ +src[LONETILDE] = '(?:~>?)' + +var TILDETRIM = R++ +src[TILDETRIM] = '(\\s*)' + src[LONETILDE] + '\\s+' +re[TILDETRIM] = new RegExp(src[TILDETRIM], 'g') +var tildeTrimReplace = '$1~' + +var TILDE = R++ +src[TILDE] = '^' + src[LONETILDE] + src[XRANGEPLAIN] + '$' +var TILDELOOSE = R++ +src[TILDELOOSE] = '^' + src[LONETILDE] + src[XRANGEPLAINLOOSE] + '$' + +// Caret ranges. +// Meaning is "at least and backwards compatible with" +var LONECARET = R++ +src[LONECARET] = '(?:\\^)' + +var CARETTRIM = R++ +src[CARETTRIM] = '(\\s*)' + src[LONECARET] + '\\s+' +re[CARETTRIM] = new RegExp(src[CARETTRIM], 'g') +var caretTrimReplace = '$1^' + +var CARET = R++ +src[CARET] = '^' + src[LONECARET] + src[XRANGEPLAIN] + '$' +var CARETLOOSE = R++ +src[CARETLOOSE] = '^' + src[LONECARET] + src[XRANGEPLAINLOOSE] + '$' + +// A simple gt/lt/eq thing, or just "" to indicate "any version" +var COMPARATORLOOSE = R++ +src[COMPARATORLOOSE] = '^' + src[GTLT] + '\\s*(' + LOOSEPLAIN + ')$|^$' +var COMPARATOR = R++ +src[COMPARATOR] = '^' + src[GTLT] + '\\s*(' + FULLPLAIN + ')$|^$' + +// An expression to strip any whitespace between the gtlt and the thing +// it modifies, so that `> 1.2.3` ==> `>1.2.3` +var COMPARATORTRIM = R++ +src[COMPARATORTRIM] = '(\\s*)' + src[GTLT] + + '\\s*(' + LOOSEPLAIN + '|' + src[XRANGEPLAIN] + ')' + +// this one has to use the /g flag +re[COMPARATORTRIM] = new RegExp(src[COMPARATORTRIM], 'g') +var comparatorTrimReplace = '$1$2$3' + +// Something like `1.2.3 - 1.2.4` +// Note that these all use the loose form, because they'll be +// checked against either the strict or loose comparator form +// later. +var HYPHENRANGE = R++ +src[HYPHENRANGE] = '^\\s*(' + src[XRANGEPLAIN] + ')' + + '\\s+-\\s+' + + '(' + src[XRANGEPLAIN] + ')' + + '\\s*$' + +var HYPHENRANGELOOSE = R++ +src[HYPHENRANGELOOSE] = '^\\s*(' + src[XRANGEPLAINLOOSE] + ')' + + '\\s+-\\s+' + + '(' + src[XRANGEPLAINLOOSE] + ')' + + '\\s*$' + +// Star ranges basically just allow anything at all. +var STAR = R++ +src[STAR] = '(<|>)?=?\\s*\\*' + +// Compile to actual regexp objects. +// All are flag-free, unless they were created above with a flag. +for (var i = 0; i < R; i++) { + debug(i, src[i]) + if (!re[i]) { + re[i] = new RegExp(src[i]) + } +} + +exports.parse = parse +function parse (version, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } + + if (version instanceof SemVer) { + return version + } + + if (typeof version !== 'string') { + return null + } + + if (version.length > MAX_LENGTH) { + return null + } + + var r = options.loose ? re[LOOSE] : re[FULL] + if (!r.test(version)) { + return null + } + + try { + return new SemVer(version, options) + } catch (er) { + return null + } +} + +exports.valid = valid +function valid (version, options) { + var v = parse(version, options) + return v ? v.version : null +} + +exports.clean = clean +function clean (version, options) { + var s = parse(version.trim().replace(/^[=v]+/, ''), options) + return s ? s.version : null +} + +exports.SemVer = SemVer + +function SemVer (version, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } + if (version instanceof SemVer) { + if (version.loose === options.loose) { + return version + } else { + version = version.version + } + } else if (typeof version !== 'string') { + throw new TypeError('Invalid Version: ' + version) + } + + if (version.length > MAX_LENGTH) { + throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters') + } + + if (!(this instanceof SemVer)) { + return new SemVer(version, options) + } + + debug('SemVer', version, options) + this.options = options + this.loose = !!options.loose + + var m = version.trim().match(options.loose ? re[LOOSE] : re[FULL]) + + if (!m) { + throw new TypeError('Invalid Version: ' + version) + } + + this.raw = version + + // these are actually numbers + this.major = +m[1] + this.minor = +m[2] + this.patch = +m[3] + + if (this.major > MAX_SAFE_INTEGER || this.major < 0) { + throw new TypeError('Invalid major version') + } + + if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { + throw new TypeError('Invalid minor version') + } + + if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { + throw new TypeError('Invalid patch version') + } + + // numberify any prerelease numeric ids + if (!m[4]) { + this.prerelease = [] + } else { + this.prerelease = m[4].split('.').map(function (id) { + if (/^[0-9]+$/.test(id)) { + var num = +id + if (num >= 0 && num < MAX_SAFE_INTEGER) { + return num + } + } + return id + }) + } + + this.build = m[5] ? m[5].split('.') : [] + this.format() +} + +SemVer.prototype.format = function () { + this.version = this.major + '.' + this.minor + '.' + this.patch + if (this.prerelease.length) { + this.version += '-' + this.prerelease.join('.') + } + return this.version +} + +SemVer.prototype.toString = function () { + return this.version +} + +SemVer.prototype.compare = function (other) { + debug('SemVer.compare', this.version, this.options, other) + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + return this.compareMain(other) || this.comparePre(other) +} + +SemVer.prototype.compareMain = function (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + return compareIdentifiers(this.major, other.major) || + compareIdentifiers(this.minor, other.minor) || + compareIdentifiers(this.patch, other.patch) +} + +SemVer.prototype.comparePre = function (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + // NOT having a prerelease is > having one + if (this.prerelease.length && !other.prerelease.length) { + return -1 + } else if (!this.prerelease.length && other.prerelease.length) { + return 1 + } else if (!this.prerelease.length && !other.prerelease.length) { + return 0 + } + + var i = 0 + do { + var a = this.prerelease[i] + var b = other.prerelease[i] + debug('prerelease compare', i, a, b) + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) +} + +// preminor will bump the version up to the next minor release, and immediately +// down to pre-release. premajor and prepatch work the same way. +SemVer.prototype.inc = function (release, identifier) { + switch (release) { + case 'premajor': + this.prerelease.length = 0 + this.patch = 0 + this.minor = 0 + this.major++ + this.inc('pre', identifier) + break + case 'preminor': + this.prerelease.length = 0 + this.patch = 0 + this.minor++ + this.inc('pre', identifier) + break + case 'prepatch': + // If this is already a prerelease, it will bump to the next version + // drop any prereleases that might already exist, since they are not + // relevant at this point. + this.prerelease.length = 0 + this.inc('patch', identifier) + this.inc('pre', identifier) + break + // If the input is a non-prerelease version, this acts the same as + // prepatch. + case 'prerelease': + if (this.prerelease.length === 0) { + this.inc('patch', identifier) + } + this.inc('pre', identifier) + break + + case 'major': + // If this is a pre-major version, bump up to the same major version. + // Otherwise increment major. + // 1.0.0-5 bumps to 1.0.0 + // 1.1.0 bumps to 2.0.0 + if (this.minor !== 0 || + this.patch !== 0 || + this.prerelease.length === 0) { + this.major++ + } + this.minor = 0 + this.patch = 0 + this.prerelease = [] + break + case 'minor': + // If this is a pre-minor version, bump up to the same minor version. + // Otherwise increment minor. + // 1.2.0-5 bumps to 1.2.0 + // 1.2.1 bumps to 1.3.0 + if (this.patch !== 0 || this.prerelease.length === 0) { + this.minor++ + } + this.patch = 0 + this.prerelease = [] + break + case 'patch': + // If this is not a pre-release version, it will increment the patch. + // If it is a pre-release it will bump up to the same patch version. + // 1.2.0-5 patches to 1.2.0 + // 1.2.0 patches to 1.2.1 + if (this.prerelease.length === 0) { + this.patch++ + } + this.prerelease = [] + break + // This probably shouldn't be used publicly. + // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction. + case 'pre': + if (this.prerelease.length === 0) { + this.prerelease = [0] + } else { + var i = this.prerelease.length + while (--i >= 0) { + if (typeof this.prerelease[i] === 'number') { + this.prerelease[i]++ + i = -2 + } + } + if (i === -1) { + // didn't increment anything + this.prerelease.push(0) + } + } + if (identifier) { + // 1.2.0-beta.1 bumps to 1.2.0-beta.2, + // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 + if (this.prerelease[0] === identifier) { + if (isNaN(this.prerelease[1])) { + this.prerelease = [identifier, 0] + } + } else { + this.prerelease = [identifier, 0] + } + } + break + + default: + throw new Error('invalid increment argument: ' + release) + } + this.format() + this.raw = this.version + return this +} + +exports.inc = inc +function inc (version, release, loose, identifier) { + if (typeof (loose) === 'string') { + identifier = loose + loose = undefined + } + + try { + return new SemVer(version, loose).inc(release, identifier).version + } catch (er) { + return null + } +} + +exports.diff = diff +function diff (version1, version2) { + if (eq(version1, version2)) { + return null + } else { + var v1 = parse(version1) + var v2 = parse(version2) + var prefix = '' + if (v1.prerelease.length || v2.prerelease.length) { + prefix = 'pre' + var defaultResult = 'prerelease' + } + for (var key in v1) { + if (key === 'major' || key === 'minor' || key === 'patch') { + if (v1[key] !== v2[key]) { + return prefix + key + } + } + } + return defaultResult // may be undefined + } +} + +exports.compareIdentifiers = compareIdentifiers + +var numeric = /^[0-9]+$/ +function compareIdentifiers (a, b) { + var anum = numeric.test(a) + var bnum = numeric.test(b) + + if (anum && bnum) { + a = +a + b = +b + } + + return a === b ? 0 + : (anum && !bnum) ? -1 + : (bnum && !anum) ? 1 + : a < b ? -1 + : 1 +} + +exports.rcompareIdentifiers = rcompareIdentifiers +function rcompareIdentifiers (a, b) { + return compareIdentifiers(b, a) +} + +exports.major = major +function major (a, loose) { + return new SemVer(a, loose).major +} + +exports.minor = minor +function minor (a, loose) { + return new SemVer(a, loose).minor +} + +exports.patch = patch +function patch (a, loose) { + return new SemVer(a, loose).patch +} + +exports.compare = compare +function compare (a, b, loose) { + return new SemVer(a, loose).compare(new SemVer(b, loose)) +} + +exports.compareLoose = compareLoose +function compareLoose (a, b) { + return compare(a, b, true) +} + +exports.rcompare = rcompare +function rcompare (a, b, loose) { + return compare(b, a, loose) +} + +exports.sort = sort +function sort (list, loose) { + return list.sort(function (a, b) { + return exports.compare(a, b, loose) + }) +} + +exports.rsort = rsort +function rsort (list, loose) { + return list.sort(function (a, b) { + return exports.rcompare(a, b, loose) + }) +} + +exports.gt = gt +function gt (a, b, loose) { + return compare(a, b, loose) > 0 +} + +exports.lt = lt +function lt (a, b, loose) { + return compare(a, b, loose) < 0 +} + +exports.eq = eq +function eq (a, b, loose) { + return compare(a, b, loose) === 0 +} + +exports.neq = neq +function neq (a, b, loose) { + return compare(a, b, loose) !== 0 +} + +exports.gte = gte +function gte (a, b, loose) { + return compare(a, b, loose) >= 0 +} + +exports.lte = lte +function lte (a, b, loose) { + return compare(a, b, loose) <= 0 +} + +exports.cmp = cmp +function cmp (a, op, b, loose) { + switch (op) { + case '===': + if (typeof a === 'object') + a = a.version + if (typeof b === 'object') + b = b.version + return a === b + + case '!==': + if (typeof a === 'object') + a = a.version + if (typeof b === 'object') + b = b.version + return a !== b + + case '': + case '=': + case '==': + return eq(a, b, loose) + + case '!=': + return neq(a, b, loose) + + case '>': + return gt(a, b, loose) + + case '>=': + return gte(a, b, loose) + + case '<': + return lt(a, b, loose) + + case '<=': + return lte(a, b, loose) + + default: + throw new TypeError('Invalid operator: ' + op) + } +} + +exports.Comparator = Comparator +function Comparator (comp, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } + + if (comp instanceof Comparator) { + if (comp.loose === !!options.loose) { + return comp + } else { + comp = comp.value + } + } + + if (!(this instanceof Comparator)) { + return new Comparator(comp, options) + } + + debug('comparator', comp, options) + this.options = options + this.loose = !!options.loose + this.parse(comp) + + if (this.semver === ANY) { + this.value = '' + } else { + this.value = this.operator + this.semver.version + } + + debug('comp', this) +} + +var ANY = {} +Comparator.prototype.parse = function (comp) { + var r = this.options.loose ? re[COMPARATORLOOSE] : re[COMPARATOR] + var m = comp.match(r) + + if (!m) { + throw new TypeError('Invalid comparator: ' + comp) + } + + this.operator = m[1] + if (this.operator === '=') { + this.operator = '' + } + + // if it literally is just '>' or '' then allow anything. + if (!m[2]) { + this.semver = ANY + } else { + this.semver = new SemVer(m[2], this.options.loose) + } +} + +Comparator.prototype.toString = function () { + return this.value +} + +Comparator.prototype.test = function (version) { + debug('Comparator.test', version, this.options.loose) + + if (this.semver === ANY) { + return true + } + + if (typeof version === 'string') { + version = new SemVer(version, this.options) + } + + return cmp(version, this.operator, this.semver, this.options) +} + +Comparator.prototype.intersects = function (comp, options) { + if (!(comp instanceof Comparator)) { + throw new TypeError('a Comparator is required') + } + + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } + + var rangeTmp + + if (this.operator === '') { + rangeTmp = new Range(comp.value, options) + return satisfies(this.value, rangeTmp, options) + } else if (comp.operator === '') { + rangeTmp = new Range(this.value, options) + return satisfies(comp.semver, rangeTmp, options) + } + + var sameDirectionIncreasing = + (this.operator === '>=' || this.operator === '>') && + (comp.operator === '>=' || comp.operator === '>') + var sameDirectionDecreasing = + (this.operator === '<=' || this.operator === '<') && + (comp.operator === '<=' || comp.operator === '<') + var sameSemVer = this.semver.version === comp.semver.version + var differentDirectionsInclusive = + (this.operator === '>=' || this.operator === '<=') && + (comp.operator === '>=' || comp.operator === '<=') + var oppositeDirectionsLessThan = + cmp(this.semver, '<', comp.semver, options) && + ((this.operator === '>=' || this.operator === '>') && + (comp.operator === '<=' || comp.operator === '<')) + var oppositeDirectionsGreaterThan = + cmp(this.semver, '>', comp.semver, options) && + ((this.operator === '<=' || this.operator === '<') && + (comp.operator === '>=' || comp.operator === '>')) + + return sameDirectionIncreasing || sameDirectionDecreasing || + (sameSemVer && differentDirectionsInclusive) || + oppositeDirectionsLessThan || oppositeDirectionsGreaterThan +} + +exports.Range = Range +function Range (range, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } + + if (range instanceof Range) { + if (range.loose === !!options.loose && + range.includePrerelease === !!options.includePrerelease) { + return range + } else { + return new Range(range.raw, options) + } + } + + if (range instanceof Comparator) { + return new Range(range.value, options) + } + + if (!(this instanceof Range)) { + return new Range(range, options) + } + + this.options = options + this.loose = !!options.loose + this.includePrerelease = !!options.includePrerelease + + // First, split based on boolean or || + this.raw = range + this.set = range.split(/\s*\|\|\s*/).map(function (range) { + return this.parseRange(range.trim()) + }, this).filter(function (c) { + // throw out any that are not relevant for whatever reason + return c.length + }) + + if (!this.set.length) { + throw new TypeError('Invalid SemVer Range: ' + range) + } + + this.format() +} + +Range.prototype.format = function () { + this.range = this.set.map(function (comps) { + return comps.join(' ').trim() + }).join('||').trim() + return this.range +} + +Range.prototype.toString = function () { + return this.range +} + +Range.prototype.parseRange = function (range) { + var loose = this.options.loose + range = range.trim() + // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` + var hr = loose ? re[HYPHENRANGELOOSE] : re[HYPHENRANGE] + range = range.replace(hr, hyphenReplace) + debug('hyphen replace', range) + // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` + range = range.replace(re[COMPARATORTRIM], comparatorTrimReplace) + debug('comparator trim', range, re[COMPARATORTRIM]) + + // `~ 1.2.3` => `~1.2.3` + range = range.replace(re[TILDETRIM], tildeTrimReplace) + + // `^ 1.2.3` => `^1.2.3` + range = range.replace(re[CARETTRIM], caretTrimReplace) + + // normalize spaces + range = range.split(/\s+/).join(' ') + + // At this point, the range is completely trimmed and + // ready to be split into comparators. + + var compRe = loose ? re[COMPARATORLOOSE] : re[COMPARATOR] + var set = range.split(' ').map(function (comp) { + return parseComparator(comp, this.options) + }, this).join(' ').split(/\s+/) + if (this.options.loose) { + // in loose mode, throw out any that are not valid comparators + set = set.filter(function (comp) { + return !!comp.match(compRe) + }) + } + set = set.map(function (comp) { + return new Comparator(comp, this.options) + }, this) + + return set +} + +Range.prototype.intersects = function (range, options) { + if (!(range instanceof Range)) { + throw new TypeError('a Range is required') + } + + return this.set.some(function (thisComparators) { + return thisComparators.every(function (thisComparator) { + return range.set.some(function (rangeComparators) { + return rangeComparators.every(function (rangeComparator) { + return thisComparator.intersects(rangeComparator, options) + }) + }) + }) + }) +} + +// Mostly just for testing and legacy API reasons +exports.toComparators = toComparators +function toComparators (range, options) { + return new Range(range, options).set.map(function (comp) { + return comp.map(function (c) { + return c.value + }).join(' ').trim().split(' ') + }) +} + +// comprised of xranges, tildes, stars, and gtlt's at this point. +// already replaced the hyphen ranges +// turn into a set of JUST comparators. +function parseComparator (comp, options) { + debug('comp', comp, options) + comp = replaceCarets(comp, options) + debug('caret', comp) + comp = replaceTildes(comp, options) + debug('tildes', comp) + comp = replaceXRanges(comp, options) + debug('xrange', comp) + comp = replaceStars(comp, options) + debug('stars', comp) + return comp +} + +function isX (id) { + return !id || id.toLowerCase() === 'x' || id === '*' +} + +// ~, ~> --> * (any, kinda silly) +// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0 +// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0 +// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0 +// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0 +// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0 +function replaceTildes (comp, options) { + return comp.trim().split(/\s+/).map(function (comp) { + return replaceTilde(comp, options) + }).join(' ') +} + +function replaceTilde (comp, options) { + var r = options.loose ? re[TILDELOOSE] : re[TILDE] + return comp.replace(r, function (_, M, m, p, pr) { + debug('tilde', comp, _, M, m, p, pr) + var ret + + if (isX(M)) { + ret = '' + } else if (isX(m)) { + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' + } else if (isX(p)) { + // ~1.2 == >=1.2.0 <1.3.0 + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' + } else if (pr) { + debug('replaceTilde pr', pr) + ret = '>=' + M + '.' + m + '.' + p + '-' + pr + + ' <' + M + '.' + (+m + 1) + '.0' + } else { + // ~1.2.3 == >=1.2.3 <1.3.0 + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + (+m + 1) + '.0' + } + + debug('tilde return', ret) + return ret + }) +} + +// ^ --> * (any, kinda silly) +// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0 +// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0 +// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0 +// ^1.2.3 --> >=1.2.3 <2.0.0 +// ^1.2.0 --> >=1.2.0 <2.0.0 +function replaceCarets (comp, options) { + return comp.trim().split(/\s+/).map(function (comp) { + return replaceCaret(comp, options) + }).join(' ') +} + +function replaceCaret (comp, options) { + debug('caret', comp, options) + var r = options.loose ? re[CARETLOOSE] : re[CARET] + return comp.replace(r, function (_, M, m, p, pr) { + debug('caret', comp, _, M, m, p, pr) + var ret + + if (isX(M)) { + ret = '' + } else if (isX(m)) { + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' + } else if (isX(p)) { + if (M === '0') { + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' + } else { + ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0' + } + } else if (pr) { + debug('replaceCaret pr', pr) + if (M === '0') { + if (m === '0') { + ret = '>=' + M + '.' + m + '.' + p + '-' + pr + + ' <' + M + '.' + m + '.' + (+p + 1) + } else { + ret = '>=' + M + '.' + m + '.' + p + '-' + pr + + ' <' + M + '.' + (+m + 1) + '.0' + } + } else { + ret = '>=' + M + '.' + m + '.' + p + '-' + pr + + ' <' + (+M + 1) + '.0.0' + } + } else { + debug('no pr') + if (M === '0') { + if (m === '0') { + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + m + '.' + (+p + 1) + } else { + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + (+m + 1) + '.0' + } + } else { + ret = '>=' + M + '.' + m + '.' + p + + ' <' + (+M + 1) + '.0.0' + } + } + + debug('caret return', ret) + return ret + }) +} + +function replaceXRanges (comp, options) { + debug('replaceXRanges', comp, options) + return comp.split(/\s+/).map(function (comp) { + return replaceXRange(comp, options) + }).join(' ') +} + +function replaceXRange (comp, options) { + comp = comp.trim() + var r = options.loose ? re[XRANGELOOSE] : re[XRANGE] + return comp.replace(r, function (ret, gtlt, M, m, p, pr) { + debug('xRange', comp, ret, gtlt, M, m, p, pr) + var xM = isX(M) + var xm = xM || isX(m) + var xp = xm || isX(p) + var anyX = xp + + if (gtlt === '=' && anyX) { + gtlt = '' + } + + if (xM) { + if (gtlt === '>' || gtlt === '<') { + // nothing is allowed + ret = '<0.0.0' + } else { + // nothing is forbidden + ret = '*' + } + } else if (gtlt && anyX) { + // we know patch is an x, because we have any x at all. + // replace X with 0 + if (xm) { + m = 0 + } + p = 0 + + if (gtlt === '>') { + // >1 => >=2.0.0 + // >1.2 => >=1.3.0 + // >1.2.3 => >= 1.2.4 + gtlt = '>=' + if (xm) { + M = +M + 1 + m = 0 + p = 0 + } else { + m = +m + 1 + p = 0 + } + } else if (gtlt === '<=') { + // <=0.7.x is actually <0.8.0, since any 0.7.x should + // pass. Similarly, <=7.x is actually <8.0.0, etc. + gtlt = '<' + if (xm) { + M = +M + 1 + } else { + m = +m + 1 + } + } + + ret = gtlt + M + '.' + m + '.' + p + } else if (xm) { + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' + } else if (xp) { + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' + } + + debug('xRange return', ret) + + return ret + }) +} + +// Because * is AND-ed with everything else in the comparator, +// and '' means "any version", just remove the *s entirely. +function replaceStars (comp, options) { + debug('replaceStars', comp, options) + // Looseness is ignored here. star is always as loose as it gets! + return comp.trim().replace(re[STAR], '') +} + +// This function is passed to string.replace(re[HYPHENRANGE]) +// M, m, patch, prerelease, build +// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 +// 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do +// 1.2 - 3.4 => >=1.2.0 <3.5.0 +function hyphenReplace ($0, + from, fM, fm, fp, fpr, fb, + to, tM, tm, tp, tpr, tb) { + if (isX(fM)) { + from = '' + } else if (isX(fm)) { + from = '>=' + fM + '.0.0' + } else if (isX(fp)) { + from = '>=' + fM + '.' + fm + '.0' + } else { + from = '>=' + from + } + + if (isX(tM)) { + to = '' + } else if (isX(tm)) { + to = '<' + (+tM + 1) + '.0.0' + } else if (isX(tp)) { + to = '<' + tM + '.' + (+tm + 1) + '.0' + } else if (tpr) { + to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr + } else { + to = '<=' + to + } + + return (from + ' ' + to).trim() +} + +// if ANY of the sets match ALL of its comparators, then pass +Range.prototype.test = function (version) { + if (!version) { + return false + } + + if (typeof version === 'string') { + version = new SemVer(version, this.options) + } + + for (var i = 0; i < this.set.length; i++) { + if (testSet(this.set[i], version, this.options)) { + return true + } + } + return false +} + +function testSet (set, version, options) { + for (var i = 0; i < set.length; i++) { + if (!set[i].test(version)) { + return false + } + } + + if (version.prerelease.length && !options.includePrerelease) { + // Find the set of versions that are allowed to have prereleases + // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 + // That should allow `1.2.3-pr.2` to pass. + // However, `1.2.4-alpha.notready` should NOT be allowed, + // even though it's within the range set by the comparators. + for (i = 0; i < set.length; i++) { + debug(set[i].semver) + if (set[i].semver === ANY) { + continue + } + + if (set[i].semver.prerelease.length > 0) { + var allowed = set[i].semver + if (allowed.major === version.major && + allowed.minor === version.minor && + allowed.patch === version.patch) { + return true + } + } + } + + // Version has a -pre, but it's not one of the ones we like. + return false + } + + return true +} + +exports.satisfies = satisfies +function satisfies (version, range, options) { + try { + range = new Range(range, options) + } catch (er) { + return false + } + return range.test(version) +} + +exports.maxSatisfying = maxSatisfying +function maxSatisfying (versions, range, options) { + var max = null + var maxSV = null + try { + var rangeObj = new Range(range, options) + } catch (er) { + return null + } + versions.forEach(function (v) { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!max || maxSV.compare(v) === -1) { + // compare(max, v, true) + max = v + maxSV = new SemVer(max, options) + } + } + }) + return max +} + +exports.minSatisfying = minSatisfying +function minSatisfying (versions, range, options) { + var min = null + var minSV = null + try { + var rangeObj = new Range(range, options) + } catch (er) { + return null + } + versions.forEach(function (v) { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!min || minSV.compare(v) === 1) { + // compare(min, v, true) + min = v + minSV = new SemVer(min, options) + } + } + }) + return min +} + +exports.minVersion = minVersion +function minVersion (range, loose) { + range = new Range(range, loose) + + var minver = new SemVer('0.0.0') + if (range.test(minver)) { + return minver + } + + minver = new SemVer('0.0.0-0') + if (range.test(minver)) { + return minver + } + + minver = null + for (var i = 0; i < range.set.length; ++i) { + var comparators = range.set[i] + + comparators.forEach(function (comparator) { + // Clone to avoid manipulating the comparator's semver object. + var compver = new SemVer(comparator.semver.version) + switch (comparator.operator) { + case '>': + if (compver.prerelease.length === 0) { + compver.patch++ + } else { + compver.prerelease.push(0) + } + compver.raw = compver.format() + /* fallthrough */ + case '': + case '>=': + if (!minver || gt(minver, compver)) { + minver = compver + } + break + case '<': + case '<=': + /* Ignore maximum versions */ + break + /* istanbul ignore next */ + default: + throw new Error('Unexpected operation: ' + comparator.operator) + } + }) + } + + if (minver && range.test(minver)) { + return minver + } + + return null +} + +exports.validRange = validRange +function validRange (range, options) { + try { + // Return '*' instead of '' so that truthiness works. + // This will throw if it's invalid anyway + return new Range(range, options).range || '*' + } catch (er) { + return null + } +} + +// Determine if version is less than all the versions possible in the range +exports.ltr = ltr +function ltr (version, range, options) { + return outside(version, range, '<', options) +} + +// Determine if version is greater than all the versions possible in the range. +exports.gtr = gtr +function gtr (version, range, options) { + return outside(version, range, '>', options) +} + +exports.outside = outside +function outside (version, range, hilo, options) { + version = new SemVer(version, options) + range = new Range(range, options) + + var gtfn, ltefn, ltfn, comp, ecomp + switch (hilo) { + case '>': + gtfn = gt + ltefn = lte + ltfn = lt + comp = '>' + ecomp = '>=' + break + case '<': + gtfn = lt + ltefn = gte + ltfn = gt + comp = '<' + ecomp = '<=' + break + default: + throw new TypeError('Must provide a hilo val of "<" or ">"') + } + + // If it satisifes the range it is not outside + if (satisfies(version, range, options)) { + return false + } + + // From now on, variable terms are as if we're in "gtr" mode. + // but note that everything is flipped for the "ltr" function. + + for (var i = 0; i < range.set.length; ++i) { + var comparators = range.set[i] + + var high = null + var low = null + + comparators.forEach(function (comparator) { + if (comparator.semver === ANY) { + comparator = new Comparator('>=0.0.0') + } + high = high || comparator + low = low || comparator + if (gtfn(comparator.semver, high.semver, options)) { + high = comparator + } else if (ltfn(comparator.semver, low.semver, options)) { + low = comparator + } + }) + + // If the edge version comparator has a operator then our version + // isn't outside it + if (high.operator === comp || high.operator === ecomp) { + return false + } + + // If the lowest version comparator has an operator and our version + // is less than it then it isn't higher than the range + if ((!low.operator || low.operator === comp) && + ltefn(version, low.semver)) { + return false + } else if (low.operator === ecomp && ltfn(version, low.semver)) { + return false + } + } + return true +} + +exports.prerelease = prerelease +function prerelease (version, options) { + var parsed = parse(version, options) + return (parsed && parsed.prerelease.length) ? parsed.prerelease : null +} + +exports.intersects = intersects +function intersects (r1, r2, options) { + r1 = new Range(r1, options) + r2 = new Range(r2, options) + return r1.intersects(r2) +} + +exports.coerce = coerce +function coerce (version) { + if (version instanceof SemVer) { + return version + } + + if (typeof version !== 'string') { + return null + } + + var match = version.match(re[COERCE]) + + if (match == null) { + return null + } + + return parse(match[1] + + '.' + (match[2] || '0') + + '.' + (match[3] || '0')) +} diff --git a/scripts/2.5/node_modules/sparse-bitfield/.npmignore b/scripts/2.5/node_modules/sparse-bitfield/.npmignore new file mode 100644 index 00000000..3c3629e6 --- /dev/null +++ b/scripts/2.5/node_modules/sparse-bitfield/.npmignore @@ -0,0 +1 @@ +node_modules diff --git a/scripts/2.5/node_modules/sparse-bitfield/.travis.yml b/scripts/2.5/node_modules/sparse-bitfield/.travis.yml new file mode 100644 index 00000000..c0428217 --- /dev/null +++ b/scripts/2.5/node_modules/sparse-bitfield/.travis.yml @@ -0,0 +1,6 @@ +language: node_js +node_js: + - '0.10' + - '0.12' + - '4.0' + - '5.0' diff --git a/scripts/2.5/node_modules/sparse-bitfield/LICENSE b/scripts/2.5/node_modules/sparse-bitfield/LICENSE new file mode 100644 index 00000000..bae9da7b --- /dev/null +++ b/scripts/2.5/node_modules/sparse-bitfield/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2016 Mathias Buus + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/scripts/2.5/node_modules/sparse-bitfield/README.md b/scripts/2.5/node_modules/sparse-bitfield/README.md new file mode 100644 index 00000000..7b6b8f9e --- /dev/null +++ b/scripts/2.5/node_modules/sparse-bitfield/README.md @@ -0,0 +1,62 @@ +# sparse-bitfield + +Bitfield implementation that allocates a series of 1kb buffers to support sparse bitfields +without allocating a massive buffer. If you want to simple implementation of a flat bitfield +see the [bitfield](https://github.com/fb55/bitfield) module. + +This module is mostly useful if you need a big bitfield where you won't nessecarily set every bit. + +``` +npm install sparse-bitfield +``` + +[![build status](http://img.shields.io/travis/mafintosh/sparse-bitfield.svg?style=flat)](http://travis-ci.org/mafintosh/sparse-bitfield) + +## Usage + +``` js +var bitfield = require('sparse-bitfield') +var bits = bitfield() + +bits.set(0, true) // set first bit +bits.set(1, true) // set second bit +bits.set(1000000000000, true) // set the 1.000.000.000.000th bit +``` + +Running the above example will allocate two 1kb buffers internally. +Each 1kb buffer can hold information about 8192 bits so the first one will be used to store information about the first two bits and the second will be used to store the 1.000.000.000.000th bit. + +## API + +#### `var bits = bitfield([options])` + +Create a new bitfield. Options include + +``` js +{ + pageSize: 1024, // how big should the partial buffers be + buffer: anExistingBitfield, + trackUpdates: false // track when pages are being updated in the pager +} +``` + +#### `bits.set(index, value)` + +Set a bit to true or false. + +#### `bits.get(index)` + +Get the value of a bit. + +#### `bits.pages` + +A [memory-pager](https://github.com/mafintosh/memory-pager) instance that is managing the underlying memory. +If you set `trackUpdates` to true in the constructor you can use `.lastUpdate()` on this instance to get the last updated memory page. + +#### `var buffer = bits.toBuffer()` + +Get a single buffer representing the entire bitfield. + +## License + +MIT diff --git a/scripts/2.5/node_modules/sparse-bitfield/index.js b/scripts/2.5/node_modules/sparse-bitfield/index.js new file mode 100644 index 00000000..ff458c97 --- /dev/null +++ b/scripts/2.5/node_modules/sparse-bitfield/index.js @@ -0,0 +1,95 @@ +var pager = require('memory-pager') + +module.exports = Bitfield + +function Bitfield (opts) { + if (!(this instanceof Bitfield)) return new Bitfield(opts) + if (!opts) opts = {} + if (Buffer.isBuffer(opts)) opts = {buffer: opts} + + this.pageOffset = opts.pageOffset || 0 + this.pageSize = opts.pageSize || 1024 + this.pages = opts.pages || pager(this.pageSize) + + this.byteLength = this.pages.length * this.pageSize + this.length = 8 * this.byteLength + + if (!powerOfTwo(this.pageSize)) throw new Error('The page size should be a power of two') + + this._trackUpdates = !!opts.trackUpdates + this._pageMask = this.pageSize - 1 + + if (opts.buffer) { + for (var i = 0; i < opts.buffer.length; i += this.pageSize) { + this.pages.set(i / this.pageSize, opts.buffer.slice(i, i + this.pageSize)) + } + this.byteLength = opts.buffer.length + this.length = 8 * this.byteLength + } +} + +Bitfield.prototype.get = function (i) { + var o = i & 7 + var j = (i - o) / 8 + + return !!(this.getByte(j) & (128 >> o)) +} + +Bitfield.prototype.getByte = function (i) { + var o = i & this._pageMask + var j = (i - o) / this.pageSize + var page = this.pages.get(j, true) + + return page ? page.buffer[o + this.pageOffset] : 0 +} + +Bitfield.prototype.set = function (i, v) { + var o = i & 7 + var j = (i - o) / 8 + var b = this.getByte(j) + + return this.setByte(j, v ? b | (128 >> o) : b & (255 ^ (128 >> o))) +} + +Bitfield.prototype.toBuffer = function () { + var all = alloc(this.pages.length * this.pageSize) + + for (var i = 0; i < this.pages.length; i++) { + var next = this.pages.get(i, true) + var allOffset = i * this.pageSize + if (next) next.buffer.copy(all, allOffset, this.pageOffset, this.pageOffset + this.pageSize) + } + + return all +} + +Bitfield.prototype.setByte = function (i, b) { + var o = i & this._pageMask + var j = (i - o) / this.pageSize + var page = this.pages.get(j, false) + + o += this.pageOffset + + if (page.buffer[o] === b) return false + page.buffer[o] = b + + if (i >= this.byteLength) { + this.byteLength = i + 1 + this.length = this.byteLength * 8 + } + + if (this._trackUpdates) this.pages.updated(page) + + return true +} + +function alloc (n) { + if (Buffer.alloc) return Buffer.alloc(n) + var b = new Buffer(n) + b.fill(0) + return b +} + +function powerOfTwo (x) { + return !(x & (x - 1)) +} diff --git a/scripts/2.5/node_modules/sparse-bitfield/package.json b/scripts/2.5/node_modules/sparse-bitfield/package.json new file mode 100644 index 00000000..1df0ac00 --- /dev/null +++ b/scripts/2.5/node_modules/sparse-bitfield/package.json @@ -0,0 +1,55 @@ +{ + "_from": "sparse-bitfield@^3.0.3", + "_id": "sparse-bitfield@3.0.3", + "_inBundle": false, + "_integrity": "sha1-/0rm5oZWBWuks+eSqzM004JzyhE=", + "_location": "/sparse-bitfield", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "sparse-bitfield@^3.0.3", + "name": "sparse-bitfield", + "escapedName": "sparse-bitfield", + "rawSpec": "^3.0.3", + "saveSpec": null, + "fetchSpec": "^3.0.3" + }, + "_requiredBy": [ + "/saslprep" + ], + "_resolved": "https://registry.npmjs.org/sparse-bitfield/-/sparse-bitfield-3.0.3.tgz", + "_shasum": "ff4ae6e68656056ba4b3e792ab3334d38273ca11", + "_spec": "sparse-bitfield@^3.0.3", + "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/2.5/node_modules/saslprep", + "author": { + "name": "Mathias Buus", + "url": "@mafintosh" + }, + "bugs": { + "url": "https://github.com/mafintosh/sparse-bitfield/issues" + }, + "bundleDependencies": false, + "dependencies": { + "memory-pager": "^1.0.2" + }, + "deprecated": false, + "description": "Bitfield that allocates a series of small buffers to support sparse bits without allocating a massive buffer", + "devDependencies": { + "buffer-alloc": "^1.1.0", + "standard": "^9.0.0", + "tape": "^4.6.3" + }, + "homepage": "https://github.com/mafintosh/sparse-bitfield", + "license": "MIT", + "main": "index.js", + "name": "sparse-bitfield", + "repository": { + "type": "git", + "url": "git+https://github.com/mafintosh/sparse-bitfield.git" + }, + "scripts": { + "test": "standard && tape test.js" + }, + "version": "3.0.3" +} diff --git a/scripts/2.5/node_modules/sparse-bitfield/test.js b/scripts/2.5/node_modules/sparse-bitfield/test.js new file mode 100644 index 00000000..ae42ef46 --- /dev/null +++ b/scripts/2.5/node_modules/sparse-bitfield/test.js @@ -0,0 +1,79 @@ +var alloc = require('buffer-alloc') +var tape = require('tape') +var bitfield = require('./') + +tape('set and get', function (t) { + var bits = bitfield() + + t.same(bits.get(0), false, 'first bit is false') + bits.set(0, true) + t.same(bits.get(0), true, 'first bit is true') + t.same(bits.get(1), false, 'second bit is false') + bits.set(0, false) + t.same(bits.get(0), false, 'first bit is reset') + t.end() +}) + +tape('set large and get', function (t) { + var bits = bitfield() + + t.same(bits.get(9999999999999), false, 'large bit is false') + bits.set(9999999999999, true) + t.same(bits.get(9999999999999), true, 'large bit is true') + t.same(bits.get(9999999999999 + 1), false, 'large bit + 1 is false') + bits.set(9999999999999, false) + t.same(bits.get(9999999999999), false, 'large bit is reset') + t.end() +}) + +tape('get and set buffer', function (t) { + var bits = bitfield({trackUpdates: true}) + + t.same(bits.pages.get(0, true), undefined) + t.same(bits.pages.get(Math.floor(9999999999999 / 8 / 1024), true), undefined) + bits.set(9999999999999, true) + + var bits2 = bitfield() + var upd = bits.pages.lastUpdate() + bits2.pages.set(Math.floor(upd.offset / 1024), upd.buffer) + t.same(bits2.get(9999999999999), true, 'bit is set') + t.end() +}) + +tape('toBuffer', function (t) { + var bits = bitfield() + + t.same(bits.toBuffer(), alloc(0)) + + bits.set(0, true) + + t.same(bits.toBuffer(), bits.pages.get(0).buffer) + + bits.set(9000, true) + + t.same(bits.toBuffer(), Buffer.concat([bits.pages.get(0).buffer, bits.pages.get(1).buffer])) + t.end() +}) + +tape('pass in buffer', function (t) { + var bits = bitfield() + + bits.set(0, true) + bits.set(9000, true) + + var clone = bitfield(bits.toBuffer()) + + t.same(clone.get(0), true) + t.same(clone.get(9000), true) + t.end() +}) + +tape('set small buffer', function (t) { + var buf = alloc(1) + buf[0] = 255 + var bits = bitfield(buf) + + t.same(bits.get(0), true) + t.same(bits.pages.get(0).buffer.length, bits.pageSize) + t.end() +}) diff --git a/scripts/2.5/node_modules/string.prototype.trimleft/.editorconfig b/scripts/2.5/node_modules/string.prototype.trimleft/.editorconfig new file mode 100644 index 00000000..bc228f82 --- /dev/null +++ b/scripts/2.5/node_modules/string.prototype.trimleft/.editorconfig @@ -0,0 +1,20 @@ +root = true + +[*] +indent_style = tab +indent_size = 4 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true +max_line_length = 150 + +[CHANGELOG.md] +indent_style = space +indent_size = 2 + +[*.json] +max_line_length = off + +[Makefile] +max_line_length = off diff --git a/scripts/2.5/node_modules/string.prototype.trimleft/.eslintrc b/scripts/2.5/node_modules/string.prototype.trimleft/.eslintrc new file mode 100644 index 00000000..1fa95428 --- /dev/null +++ b/scripts/2.5/node_modules/string.prototype.trimleft/.eslintrc @@ -0,0 +1,15 @@ +{ + "root": true, + + "extends": "@ljharb", + + "overrides": [ + { + "files": "test/*", + "rules": { + "id-length": 0, + "no-invalid-this": 1, + }, + }, + ], +} diff --git a/scripts/2.5/node_modules/string.prototype.trimleft/.travis.yml b/scripts/2.5/node_modules/string.prototype.trimleft/.travis.yml new file mode 100644 index 00000000..87a3b02c --- /dev/null +++ b/scripts/2.5/node_modules/string.prototype.trimleft/.travis.yml @@ -0,0 +1,317 @@ +language: node_js +os: + - linux +node_js: + - "12.10" + - "11.15" + - "10.16" + - "9.11" + - "8.16" + - "7.10" + - "6.17" + - "5.12" + - "4.9" + - "iojs-v3.3" + - "iojs-v2.5" + - "iojs-v1.8" + - "0.12" + - "0.10" + - "0.8" +before_install: + - 'case "${TRAVIS_NODE_VERSION}" in 0.*) export NPM_CONFIG_STRICT_SSL=false ;; esac' + - 'nvm install-latest-npm' +install: + - 'if [ "${TRAVIS_NODE_VERSION}" = "0.6" ] || [ "${TRAVIS_NODE_VERSION}" = "0.9" ]; then nvm install --latest-npm 0.8 && npm install && nvm use "${TRAVIS_NODE_VERSION}"; else npm install; fi;' +script: + - 'if [ -n "${PRETEST-}" ]; then npm run pretest ; fi' + - 'if [ -n "${POSTTEST-}" ]; then npm run posttest ; fi' + - 'if [ -n "${COVERAGE-}" ]; then npm run coverage ; fi' + - 'if [ -n "${TEST-}" ]; then npm run tests-only ; fi' +sudo: false +env: + - TEST=true +matrix: + fast_finish: true + include: + - node_js: "lts/*" + env: PRETEST=true + - node_js: "lts/*" + env: POSTTEST=true + - node_js: "4" + env: COVERAGE=true + - node_js: "12.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "12.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "12.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "12.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "12.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "12.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "12.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "12.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "12.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "12.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.14" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.13" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.12" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.15" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.14" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.13" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.12" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.15" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.14" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.13" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.12" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.16" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.15" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.14" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.13" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.12" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v3.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v3.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v3.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.4" + env: TEST=true ALLOW_FAILURE=true + allow_failures: + - os: osx + - env: TEST=true ALLOW_FAILURE=true + - env: COVERAGE=true diff --git a/scripts/2.5/node_modules/string.prototype.trimleft/CHANGELOG.md b/scripts/2.5/node_modules/string.prototype.trimleft/CHANGELOG.md new file mode 100644 index 00000000..535068f2 --- /dev/null +++ b/scripts/2.5/node_modules/string.prototype.trimleft/CHANGELOG.md @@ -0,0 +1,30 @@ +2.1.0 / 2019-09-09 +================= + * [New] add `auto` entry point + * [Deps] update `function-bind`, `define-properties` + * [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `covert`, `tape`, `@es-shims/api` + * [meta] clean up scripts + * [meta] Only apps should have lockfiles + * [Tests] up to `node` `v12.10`, `v11.15`, `v10.16`, `v9.11`, `v8.16`, `v7.10`, `v6.17`, `v5.10`, `v4.9`; use `nvm install-latest-npm` + * [Tests] allow a name of `trimLeft` or `trimStart` + * [Tests] fix tests for the mongolian vowel separator + * [Tests] use `functions-have-names` + * [Tests] use `npx aud` instead of `nsp` or `npm audit` with hoops + * [Tests] remove `jscs` + * [Tests] use pretest/posttest for linting/security + +2.0.0 / 2016-02-06 +================= + * [Breaking] conform to the es-shim API + * [Deps] update `define-properties` + * [Dev Deps] update `tape`, `jscs`, `nsp`, `eslint`, `@ljharb/eslint-config` + * [Tests] up to `node` `v5.5` + * [Tests] fix npm upgrades on older nodes + +1.0.1 / 2015-07-29 +================= + * Fix deps mistakenly being dev deps + +1.0.0 / 2015-07-29 +================= + * v1.0.0 diff --git a/scripts/2.5/node_modules/string.prototype.trimleft/LICENSE b/scripts/2.5/node_modules/string.prototype.trimleft/LICENSE new file mode 100644 index 00000000..b43df444 --- /dev/null +++ b/scripts/2.5/node_modules/string.prototype.trimleft/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/scripts/2.5/node_modules/string.prototype.trimleft/README.md b/scripts/2.5/node_modules/string.prototype.trimleft/README.md new file mode 100644 index 00000000..bd3f82f9 --- /dev/null +++ b/scripts/2.5/node_modules/string.prototype.trimleft/README.md @@ -0,0 +1,47 @@ +String.prototype.trimLeft [![Version Badge][npm-version-svg]][package-url] + +[![Build Status][travis-svg]][travis-url] +[![dependency status][deps-svg]][deps-url] +[![dev dependency status][dev-deps-svg]][dev-deps-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +[![browser support][testling-svg]][testling-url] + +A spec-proposal-compliant `String.prototype.trimLeft` shim. Invoke its "shim" method to shim `String.prototype.trimLeft` if it is unavailable. + +This package implements the [es-shim API](https://github.com/es-shims/api) interface. It works in an ES3-supported environment and complies with the [spec](http://www.ecma-international.org/ecma-262/6.0/#sec-object.assign). In an ES6 environment, it will also work properly with `Symbol`s. + +Most common usage: +```js +var trimLeft = require('string.prototype.trimleft'); + +assert(trimLeft(' \t\na \t\n') === 'a \t\n'); + +if (!String.prototype.trimLeft) { + trimLeft.shim(); +} + +assert(trimLeft(' \t\na \t\n') === ' \t\na \t\n'.trimLeft()); +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.com/package/string.prototype.trimleft +[npm-version-svg]: http://vb.teelaun.ch/es-shims/String.prototype.trimLeft.svg +[travis-svg]: https://travis-ci.org/es-shims/String.prototype.trimLeft.svg +[travis-url]: https://travis-ci.org/es-shims/String.prototype.trimLeft +[deps-svg]: https://david-dm.org/es-shims/String.prototype.trimLeft.svg +[deps-url]: https://david-dm.org/es-shims/String.prototype.trimLeft +[dev-deps-svg]: https://david-dm.org/es-shims/String.prototype.trimLeft/dev-status.svg +[dev-deps-url]: https://david-dm.org/es-shims/String.prototype.trimLeft#info=devDependencies +[testling-svg]: https://ci.testling.com/es-shims/String.prototype.trimLeft.png +[testling-url]: https://ci.testling.com/es-shims/String.prototype.trimLeft +[npm-badge-png]: https://nodei.co/npm/string.prototype.trimleft.png?downloads=true&stars=true +[license-image]: http://img.shields.io/npm/l/string.prototype.trimleft.svg +[license-url]: LICENSE +[downloads-image]: http://img.shields.io/npm/dm/string.prototype.trimleft.svg +[downloads-url]: http://npm-stat.com/charts.html?package=string.prototype.trimleft diff --git a/scripts/2.5/node_modules/string.prototype.trimleft/auto.js b/scripts/2.5/node_modules/string.prototype.trimleft/auto.js new file mode 100644 index 00000000..8ebf606c --- /dev/null +++ b/scripts/2.5/node_modules/string.prototype.trimleft/auto.js @@ -0,0 +1,3 @@ +'use strict'; + +require('./shim')(); diff --git a/scripts/2.5/node_modules/string.prototype.trimleft/implementation.js b/scripts/2.5/node_modules/string.prototype.trimleft/implementation.js new file mode 100644 index 00000000..5df533ea --- /dev/null +++ b/scripts/2.5/node_modules/string.prototype.trimleft/implementation.js @@ -0,0 +1,12 @@ +'use strict'; + +var bind = require('function-bind'); +var replace = bind.call(Function.call, String.prototype.replace); + +/* eslint-disable no-control-regex */ +var leftWhitespace = /^[\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF]*/; +/* eslint-enable no-control-regex */ + +module.exports = function trimLeft() { + return replace(this, leftWhitespace, ''); +}; diff --git a/scripts/2.5/node_modules/string.prototype.trimleft/index.js b/scripts/2.5/node_modules/string.prototype.trimleft/index.js new file mode 100644 index 00000000..7fe48cf5 --- /dev/null +++ b/scripts/2.5/node_modules/string.prototype.trimleft/index.js @@ -0,0 +1,18 @@ +'use strict'; + +var bind = require('function-bind'); +var define = require('define-properties'); + +var implementation = require('./implementation'); +var getPolyfill = require('./polyfill'); +var shim = require('./shim'); + +var bound = bind.call(Function.call, getPolyfill()); + +define(bound, { + getPolyfill: getPolyfill, + implementation: implementation, + shim: shim +}); + +module.exports = bound; diff --git a/scripts/2.5/node_modules/string.prototype.trimleft/package.json b/scripts/2.5/node_modules/string.prototype.trimleft/package.json new file mode 100644 index 00000000..e5a3ea3b --- /dev/null +++ b/scripts/2.5/node_modules/string.prototype.trimleft/package.json @@ -0,0 +1,97 @@ +{ + "_from": "string.prototype.trimleft@^2.1.0", + "_id": "string.prototype.trimleft@2.1.0", + "_inBundle": false, + "_integrity": "sha512-FJ6b7EgdKxxbDxc79cOlok6Afd++TTs5szo+zJTUyow3ycrRfJVE2pq3vcN53XexvKZu/DJMDfeI/qMiZTrjTw==", + "_location": "/string.prototype.trimleft", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "string.prototype.trimleft@^2.1.0", + "name": "string.prototype.trimleft", + "escapedName": "string.prototype.trimleft", + "rawSpec": "^2.1.0", + "saveSpec": null, + "fetchSpec": "^2.1.0" + }, + "_requiredBy": [ + "/es-abstract" + ], + "_resolved": "https://registry.npmjs.org/string.prototype.trimleft/-/string.prototype.trimleft-2.1.0.tgz", + "_shasum": "6cc47f0d7eb8d62b0f3701611715a3954591d634", + "_spec": "string.prototype.trimleft@^2.1.0", + "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/2.5/node_modules/es-abstract", + "author": { + "name": "Jordan Harband" + }, + "bugs": { + "url": "https://github.com/es-shims/String.prototype.trimLeft/issues" + }, + "bundleDependencies": false, + "dependencies": { + "define-properties": "^1.1.3", + "function-bind": "^1.1.1" + }, + "deprecated": false, + "description": "ES7 spec-compliant String.prototype.trimLeft shim.", + "devDependencies": { + "@es-shims/api": "^2.1.2", + "@ljharb/eslint-config": "^14.1.0", + "covert": "^1.1.1", + "eslint": "^6.3.0", + "functions-have-names": "^1.1.1", + "tape": "^4.11.0" + }, + "engines": { + "node": ">= 0.4" + }, + "homepage": "https://github.com/es-shims/String.prototype.trimLeft#readme", + "keywords": [ + "String.prototype.trimLeft", + "string", + "ES7", + "shim", + "trim", + "trimLeft", + "trimRight", + "polyfill", + "es-shim API" + ], + "license": "MIT", + "main": "index.js", + "name": "string.prototype.trimleft", + "repository": { + "type": "git", + "url": "git://github.com/es-shims/String.prototype.trimLeft.git" + }, + "scripts": { + "coverage": "covert test/*.js", + "lint": "eslint .", + "posttest": "npx aud", + "pretest": "npm run lint && es-shim-api --bound", + "test": "npm run tests-only", + "test:module": "node test", + "test:shimmed": "node test/shimmed", + "tests-only": "npm run --silent test:shimmed && npm run --silent test:module" + }, + "testling": { + "files": "test/index.js", + "browsers": [ + "iexplore/9.0..latest", + "firefox/4.0..6.0", + "firefox/15.0..latest", + "firefox/nightly", + "chrome/4.0..10.0", + "chrome/20.0..latest", + "chrome/canary", + "opera/11.6..latest", + "opera/next", + "safari/5.0..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2" + ] + }, + "version": "2.1.0" +} diff --git a/scripts/2.5/node_modules/string.prototype.trimleft/polyfill.js b/scripts/2.5/node_modules/string.prototype.trimleft/polyfill.js new file mode 100644 index 00000000..dc33a23e --- /dev/null +++ b/scripts/2.5/node_modules/string.prototype.trimleft/polyfill.js @@ -0,0 +1,14 @@ +'use strict'; + +var implementation = require('./implementation'); + +module.exports = function getPolyfill() { + if (!String.prototype.trimLeft) { + return implementation; + } + var zeroWidthSpace = '\u200b'; + if (zeroWidthSpace.trimLeft() !== zeroWidthSpace) { + return implementation; + } + return String.prototype.trimLeft; +}; diff --git a/scripts/2.5/node_modules/string.prototype.trimleft/shim.js b/scripts/2.5/node_modules/string.prototype.trimleft/shim.js new file mode 100644 index 00000000..23314f04 --- /dev/null +++ b/scripts/2.5/node_modules/string.prototype.trimleft/shim.js @@ -0,0 +1,14 @@ +'use strict'; + +var define = require('define-properties'); +var getPolyfill = require('./polyfill'); + +module.exports = function shimTrimLeft() { + var polyfill = getPolyfill(); + define( + String.prototype, + { trimLeft: polyfill }, + { trimLeft: function () { return String.prototype.trimLeft !== polyfill; } } + ); + return polyfill; +}; diff --git a/scripts/2.5/node_modules/string.prototype.trimleft/test/index.js b/scripts/2.5/node_modules/string.prototype.trimleft/test/index.js new file mode 100644 index 00000000..99795074 --- /dev/null +++ b/scripts/2.5/node_modules/string.prototype.trimleft/test/index.js @@ -0,0 +1,18 @@ +'use strict'; + +var trimLeft = require('../'); +var test = require('tape'); + +var runTests = require('./tests'); + +test('as a function', function (t) { + t.test('bad array/this value', function (st) { + st['throws'](function () { trimLeft(undefined, 'a'); }, TypeError, 'undefined is not an object'); + st['throws'](function () { trimLeft(null, 'a'); }, TypeError, 'null is not an object'); + st.end(); + }); + + runTests(trimLeft, t); + + t.end(); +}); diff --git a/scripts/2.5/node_modules/string.prototype.trimleft/test/shimmed.js b/scripts/2.5/node_modules/string.prototype.trimleft/test/shimmed.js new file mode 100644 index 00000000..c2ebfd43 --- /dev/null +++ b/scripts/2.5/node_modules/string.prototype.trimleft/test/shimmed.js @@ -0,0 +1,37 @@ +'use strict'; + +var trimLeft = require('../'); +trimLeft.shim(); + +var runTests = require('./tests'); + +var test = require('tape'); +var defineProperties = require('define-properties'); +var bind = require('function-bind'); +var isEnumerable = Object.prototype.propertyIsEnumerable; +var functionsHaveNames = require('functions-have-names')(); + +test('shimmed', function (t) { + t.equal(String.prototype.trimLeft.length, 0, 'String#trimLeft has a length of 0'); + t.test('Function name', { skip: !functionsHaveNames }, function (st) { + st.equal((/^(?:trimLeft|trimStart)$/).test(String.prototype.trimLeft.name), true, 'String#trimLeft has name "trimLeft" or "trimStart"'); + st.end(); + }); + + t.test('enumerability', { skip: !defineProperties.supportsDescriptors }, function (et) { + et.equal(false, isEnumerable.call(String.prototype, 'trimLeft'), 'String#trimLeft is not enumerable'); + et.end(); + }); + + var supportsStrictMode = (function () { return typeof this === 'undefined'; }()); + + t.test('bad string/this value', { skip: !supportsStrictMode }, function (st) { + st['throws'](function () { return trimLeft(undefined, 'a'); }, TypeError, 'undefined is not an object'); + st['throws'](function () { return trimLeft(null, 'a'); }, TypeError, 'null is not an object'); + st.end(); + }); + + runTests(bind.call(Function.call, String.prototype.trimLeft), t); + + t.end(); +}); diff --git a/scripts/2.5/node_modules/string.prototype.trimleft/test/tests.js b/scripts/2.5/node_modules/string.prototype.trimleft/test/tests.js new file mode 100644 index 00000000..fe7926ac --- /dev/null +++ b/scripts/2.5/node_modules/string.prototype.trimleft/test/tests.js @@ -0,0 +1,26 @@ +'use strict'; + +module.exports = function (trimLeft, t) { + t.test('normal cases', function (st) { + st.equal(trimLeft(' \t\na \t\n'), 'a \t\n', 'strips whitespace off the left side'); + st.equal(trimLeft('a'), 'a', 'noop when no whitespace'); + + var allWhitespaceChars = '\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF'; + st.equal(trimLeft(allWhitespaceChars + 'a' + allWhitespaceChars), 'a' + allWhitespaceChars, 'all expected whitespace chars are trimmed'); + + st.end(); + }); + + // see https://codeblog.jonskeet.uk/2014/12/01/when-is-an-identifier-not-an-identifier-attack-of-the-mongolian-vowel-separator/ + var mongolianVowelSeparator = '\u180E'; + t.test('unicode >= 4 && < 6.3', { skip: !(/^\s$/).test(mongolianVowelSeparator) }, function (st) { + st.equal(trimLeft(mongolianVowelSeparator + 'a' + mongolianVowelSeparator), 'a' + mongolianVowelSeparator, 'mongolian vowel separator is whitespace'); + st.end(); + }); + + t.test('zero-width spaces', function (st) { + var zeroWidth = '\u200b'; + st.equal(trimLeft(zeroWidth), zeroWidth, 'zero width space does not trim'); + st.end(); + }); +}; diff --git a/scripts/2.5/node_modules/string.prototype.trimright/.editorconfig b/scripts/2.5/node_modules/string.prototype.trimright/.editorconfig new file mode 100644 index 00000000..bc228f82 --- /dev/null +++ b/scripts/2.5/node_modules/string.prototype.trimright/.editorconfig @@ -0,0 +1,20 @@ +root = true + +[*] +indent_style = tab +indent_size = 4 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true +max_line_length = 150 + +[CHANGELOG.md] +indent_style = space +indent_size = 2 + +[*.json] +max_line_length = off + +[Makefile] +max_line_length = off diff --git a/scripts/2.5/node_modules/string.prototype.trimright/.eslintrc b/scripts/2.5/node_modules/string.prototype.trimright/.eslintrc new file mode 100644 index 00000000..1fa95428 --- /dev/null +++ b/scripts/2.5/node_modules/string.prototype.trimright/.eslintrc @@ -0,0 +1,15 @@ +{ + "root": true, + + "extends": "@ljharb", + + "overrides": [ + { + "files": "test/*", + "rules": { + "id-length": 0, + "no-invalid-this": 1, + }, + }, + ], +} diff --git a/scripts/2.5/node_modules/string.prototype.trimright/.travis.yml b/scripts/2.5/node_modules/string.prototype.trimright/.travis.yml new file mode 100644 index 00000000..87a3b02c --- /dev/null +++ b/scripts/2.5/node_modules/string.prototype.trimright/.travis.yml @@ -0,0 +1,317 @@ +language: node_js +os: + - linux +node_js: + - "12.10" + - "11.15" + - "10.16" + - "9.11" + - "8.16" + - "7.10" + - "6.17" + - "5.12" + - "4.9" + - "iojs-v3.3" + - "iojs-v2.5" + - "iojs-v1.8" + - "0.12" + - "0.10" + - "0.8" +before_install: + - 'case "${TRAVIS_NODE_VERSION}" in 0.*) export NPM_CONFIG_STRICT_SSL=false ;; esac' + - 'nvm install-latest-npm' +install: + - 'if [ "${TRAVIS_NODE_VERSION}" = "0.6" ] || [ "${TRAVIS_NODE_VERSION}" = "0.9" ]; then nvm install --latest-npm 0.8 && npm install && nvm use "${TRAVIS_NODE_VERSION}"; else npm install; fi;' +script: + - 'if [ -n "${PRETEST-}" ]; then npm run pretest ; fi' + - 'if [ -n "${POSTTEST-}" ]; then npm run posttest ; fi' + - 'if [ -n "${COVERAGE-}" ]; then npm run coverage ; fi' + - 'if [ -n "${TEST-}" ]; then npm run tests-only ; fi' +sudo: false +env: + - TEST=true +matrix: + fast_finish: true + include: + - node_js: "lts/*" + env: PRETEST=true + - node_js: "lts/*" + env: POSTTEST=true + - node_js: "4" + env: COVERAGE=true + - node_js: "12.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "12.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "12.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "12.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "12.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "12.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "12.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "12.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "12.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "12.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.14" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.13" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.12" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "11.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.15" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.14" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.13" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.12" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.15" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.14" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.13" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.12" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.16" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.15" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.14" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.13" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.12" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v3.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v3.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v3.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.4" + env: TEST=true ALLOW_FAILURE=true + allow_failures: + - os: osx + - env: TEST=true ALLOW_FAILURE=true + - env: COVERAGE=true diff --git a/scripts/2.5/node_modules/string.prototype.trimright/CHANGELOG.md b/scripts/2.5/node_modules/string.prototype.trimright/CHANGELOG.md new file mode 100644 index 00000000..535068f2 --- /dev/null +++ b/scripts/2.5/node_modules/string.prototype.trimright/CHANGELOG.md @@ -0,0 +1,30 @@ +2.1.0 / 2019-09-09 +================= + * [New] add `auto` entry point + * [Deps] update `function-bind`, `define-properties` + * [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `covert`, `tape`, `@es-shims/api` + * [meta] clean up scripts + * [meta] Only apps should have lockfiles + * [Tests] up to `node` `v12.10`, `v11.15`, `v10.16`, `v9.11`, `v8.16`, `v7.10`, `v6.17`, `v5.10`, `v4.9`; use `nvm install-latest-npm` + * [Tests] allow a name of `trimLeft` or `trimStart` + * [Tests] fix tests for the mongolian vowel separator + * [Tests] use `functions-have-names` + * [Tests] use `npx aud` instead of `nsp` or `npm audit` with hoops + * [Tests] remove `jscs` + * [Tests] use pretest/posttest for linting/security + +2.0.0 / 2016-02-06 +================= + * [Breaking] conform to the es-shim API + * [Deps] update `define-properties` + * [Dev Deps] update `tape`, `jscs`, `nsp`, `eslint`, `@ljharb/eslint-config` + * [Tests] up to `node` `v5.5` + * [Tests] fix npm upgrades on older nodes + +1.0.1 / 2015-07-29 +================= + * Fix deps mistakenly being dev deps + +1.0.0 / 2015-07-29 +================= + * v1.0.0 diff --git a/scripts/2.5/node_modules/string.prototype.trimright/LICENSE b/scripts/2.5/node_modules/string.prototype.trimright/LICENSE new file mode 100644 index 00000000..b43df444 --- /dev/null +++ b/scripts/2.5/node_modules/string.prototype.trimright/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/scripts/2.5/node_modules/string.prototype.trimright/README.md b/scripts/2.5/node_modules/string.prototype.trimright/README.md new file mode 100644 index 00000000..6d736f50 --- /dev/null +++ b/scripts/2.5/node_modules/string.prototype.trimright/README.md @@ -0,0 +1,47 @@ +String.prototype.trimRight [![Version Badge][npm-version-svg]][package-url] + +[![Build Status][travis-svg]][travis-url] +[![dependency status][deps-svg]][deps-url] +[![dev dependency status][dev-deps-svg]][dev-deps-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +[![browser support][testling-svg]][testling-url] + +A spec-proposal-compliant `String.prototype.trimRight` shim. Invoke its "shim" method to shim `String.prototype.trimRight` if it is unavailable. + +This package implements the [es-shim API](https://github.com/es-shims/api) interface. It works in an ES3-supported environment and complies with the [spec](http://www.ecma-international.org/ecma-262/6.0/#sec-object.assign). In an ES6 environment, it will also work properly with `Symbol`s. + +Most common usage: +```js +var trimRight = require('string.prototype.trimright'); + +assert(trimRight(' \t\na \t\n') === 'a \t\n'); + +if (!String.prototype.trimRight) { + trimRight.shim(); +} + +assert(trimRight(' \t\na \t\n ') === ' \t\na \t\n '.trimRight()); +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.com/package/string.prototype.trimright +[npm-version-svg]: http://vb.teelaun.ch/es-shims/String.prototype.trimRight.svg +[travis-svg]: https://travis-ci.org/es-shims/String.prototype.trimRight.svg +[travis-url]: https://travis-ci.org/es-shims/String.prototype.trimRight +[deps-svg]: https://david-dm.org/es-shims/String.prototype.trimRight.svg +[deps-url]: https://david-dm.org/es-shims/String.prototype.trimRight +[dev-deps-svg]: https://david-dm.org/es-shims/String.prototype.trimRight/dev-status.svg +[dev-deps-url]: https://david-dm.org/es-shims/String.prototype.trimRight#info=devDependencies +[testling-svg]: https://ci.testling.com/es-shims/String.prototype.trimRight.png +[testling-url]: https://ci.testling.com/es-shims/String.prototype.trimRight +[npm-badge-png]: https://nodei.co/npm/string.prototype.trimright.png?downloads=true&stars=true +[license-image]: http://img.shields.io/npm/l/string.prototype.trimright.svg +[license-url]: LICENSE +[downloads-image]: http://img.shields.io/npm/dm/string.prototype.trimright.svg +[downloads-url]: http://npm-stat.com/charts.html?package=string.prototype.trimright diff --git a/scripts/2.5/node_modules/string.prototype.trimright/auto.js b/scripts/2.5/node_modules/string.prototype.trimright/auto.js new file mode 100644 index 00000000..8ebf606c --- /dev/null +++ b/scripts/2.5/node_modules/string.prototype.trimright/auto.js @@ -0,0 +1,3 @@ +'use strict'; + +require('./shim')(); diff --git a/scripts/2.5/node_modules/string.prototype.trimright/implementation.js b/scripts/2.5/node_modules/string.prototype.trimright/implementation.js new file mode 100644 index 00000000..ce995545 --- /dev/null +++ b/scripts/2.5/node_modules/string.prototype.trimright/implementation.js @@ -0,0 +1,12 @@ +'use strict'; + +var bind = require('function-bind'); +var replace = bind.call(Function.call, String.prototype.replace); + +/* eslint-disable no-control-regex */ +var rightWhitespace = /[\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF]*$/; +/* eslint-enable no-control-regex */ + +module.exports = function trimRight() { + return replace(this, rightWhitespace, ''); +}; diff --git a/scripts/2.5/node_modules/string.prototype.trimright/index.js b/scripts/2.5/node_modules/string.prototype.trimright/index.js new file mode 100644 index 00000000..7fe48cf5 --- /dev/null +++ b/scripts/2.5/node_modules/string.prototype.trimright/index.js @@ -0,0 +1,18 @@ +'use strict'; + +var bind = require('function-bind'); +var define = require('define-properties'); + +var implementation = require('./implementation'); +var getPolyfill = require('./polyfill'); +var shim = require('./shim'); + +var bound = bind.call(Function.call, getPolyfill()); + +define(bound, { + getPolyfill: getPolyfill, + implementation: implementation, + shim: shim +}); + +module.exports = bound; diff --git a/scripts/2.5/node_modules/string.prototype.trimright/package.json b/scripts/2.5/node_modules/string.prototype.trimright/package.json new file mode 100644 index 00000000..38dfc66d --- /dev/null +++ b/scripts/2.5/node_modules/string.prototype.trimright/package.json @@ -0,0 +1,97 @@ +{ + "_from": "string.prototype.trimright@^2.1.0", + "_id": "string.prototype.trimright@2.1.0", + "_inBundle": false, + "_integrity": "sha512-fXZTSV55dNBwv16uw+hh5jkghxSnc5oHq+5K/gXgizHwAvMetdAJlHqqoFC1FSDVPYWLkAKl2cxpUT41sV7nSg==", + "_location": "/string.prototype.trimright", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "string.prototype.trimright@^2.1.0", + "name": "string.prototype.trimright", + "escapedName": "string.prototype.trimright", + "rawSpec": "^2.1.0", + "saveSpec": null, + "fetchSpec": "^2.1.0" + }, + "_requiredBy": [ + "/es-abstract" + ], + "_resolved": "https://registry.npmjs.org/string.prototype.trimright/-/string.prototype.trimright-2.1.0.tgz", + "_shasum": "669d164be9df9b6f7559fa8e89945b168a5a6c58", + "_spec": "string.prototype.trimright@^2.1.0", + "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/2.5/node_modules/es-abstract", + "author": { + "name": "Jordan Harband" + }, + "bugs": { + "url": "https://github.com/es-shims/String.prototype.trimRight/issues" + }, + "bundleDependencies": false, + "dependencies": { + "define-properties": "^1.1.3", + "function-bind": "^1.1.1" + }, + "deprecated": false, + "description": "ES7 spec-compliant String.prototype.trimRight shim.", + "devDependencies": { + "@es-shims/api": "^2.1.2", + "@ljharb/eslint-config": "^14.1.0", + "covert": "^1.1.1", + "eslint": "^6.3.0", + "functions-have-names": "^1.1.1", + "tape": "^4.11.0" + }, + "engines": { + "node": ">= 0.4" + }, + "homepage": "https://github.com/es-shims/String.prototype.trimRight#readme", + "keywords": [ + "String.prototype.trimRight", + "string", + "ES7", + "shim", + "trim", + "trimLeft", + "trimRight", + "polyfill", + "es-shim API" + ], + "license": "MIT", + "main": "index.js", + "name": "string.prototype.trimright", + "repository": { + "type": "git", + "url": "git://github.com/es-shims/String.prototype.trimRight.git" + }, + "scripts": { + "coverage": "covert test/*.js", + "lint": "eslint .", + "posttest": "npx aud", + "pretest": "npm run lint && es-shim-api --bound", + "test": "npm run tests-only", + "test:module": "node test", + "test:shimmed": "node test/shimmed", + "tests-only": "npm run test:shimmed && npm run test:module" + }, + "testling": { + "files": "test/index.js", + "browsers": [ + "iexplore/9.0..latest", + "firefox/4.0..6.0", + "firefox/15.0..latest", + "firefox/nightly", + "chrome/4.0..10.0", + "chrome/20.0..latest", + "chrome/canary", + "opera/11.6..latest", + "opera/next", + "safari/5.0..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2" + ] + }, + "version": "2.1.0" +} diff --git a/scripts/2.5/node_modules/string.prototype.trimright/polyfill.js b/scripts/2.5/node_modules/string.prototype.trimright/polyfill.js new file mode 100644 index 00000000..7c2aa99b --- /dev/null +++ b/scripts/2.5/node_modules/string.prototype.trimright/polyfill.js @@ -0,0 +1,14 @@ +'use strict'; + +var implementation = require('./implementation'); + +module.exports = function getPolyfill() { + if (!String.prototype.trimRight) { + return implementation; + } + var zeroWidthSpace = '\u200b'; + if (zeroWidthSpace.trimRight() !== zeroWidthSpace) { + return implementation; + } + return String.prototype.trimRight; +}; diff --git a/scripts/2.5/node_modules/string.prototype.trimright/shim.js b/scripts/2.5/node_modules/string.prototype.trimright/shim.js new file mode 100644 index 00000000..e073afec --- /dev/null +++ b/scripts/2.5/node_modules/string.prototype.trimright/shim.js @@ -0,0 +1,14 @@ +'use strict'; + +var define = require('define-properties'); +var getPolyfill = require('./polyfill'); + +module.exports = function shimTrimRight() { + var polyfill = getPolyfill(); + define( + String.prototype, + { trimRight: polyfill }, + { trimRight: function () { return String.prototype.trimRight !== polyfill; } } + ); + return polyfill; +}; diff --git a/scripts/2.5/node_modules/string.prototype.trimright/test/index.js b/scripts/2.5/node_modules/string.prototype.trimright/test/index.js new file mode 100644 index 00000000..84e5e3df --- /dev/null +++ b/scripts/2.5/node_modules/string.prototype.trimright/test/index.js @@ -0,0 +1,17 @@ +'use strict'; + +var trimRight = require('../'); +var test = require('tape'); +var runTests = require('./tests'); + +test('as a function', function (t) { + t.test('bad array/this value', function (st) { + st['throws'](function () { trimRight(undefined, 'a'); }, TypeError, 'undefined is not an object'); + st['throws'](function () { trimRight(null, 'a'); }, TypeError, 'null is not an object'); + st.end(); + }); + + runTests(trimRight, t); + + t.end(); +}); diff --git a/scripts/2.5/node_modules/string.prototype.trimright/test/shimmed.js b/scripts/2.5/node_modules/string.prototype.trimright/test/shimmed.js new file mode 100644 index 00000000..92287efd --- /dev/null +++ b/scripts/2.5/node_modules/string.prototype.trimright/test/shimmed.js @@ -0,0 +1,37 @@ +'use strict'; + +var trimRight = require('../'); +trimRight.shim(); + +var runTests = require('./tests'); + +var test = require('tape'); +var defineProperties = require('define-properties'); +var bind = require('function-bind'); +var isEnumerable = Object.prototype.propertyIsEnumerable; +var functionsHaveNames = require('functions-have-names')(); + +test('shimmed', function (t) { + t.equal(String.prototype.trimRight.length, 0, 'String#trimRight has a length of 0'); + t.test('Function name', { skip: !functionsHaveNames }, function (st) { + st.equal((/^(?:trimRight|trimEnd)$/).test(String.prototype.trimRight.name), true, 'String#trimRight has name "trimRight" or "trimEnd"'); + st.end(); + }); + + t.test('enumerability', { skip: !defineProperties.supportsDescriptors }, function (et) { + et.equal(false, isEnumerable.call(String.prototype, 'trimRight'), 'String#trimRight is not enumerable'); + et.end(); + }); + + var supportsStrictMode = (function () { return typeof this === 'undefined'; }()); + + t.test('bad string/this value', { skip: !supportsStrictMode }, function (st) { + st['throws'](function () { return trimRight(undefined, 'a'); }, TypeError, 'undefined is not an object'); + st['throws'](function () { return trimRight(null, 'a'); }, TypeError, 'null is not an object'); + st.end(); + }); + + runTests(bind.call(Function.call, String.prototype.trimRight), t); + + t.end(); +}); diff --git a/scripts/2.5/node_modules/string.prototype.trimright/test/tests.js b/scripts/2.5/node_modules/string.prototype.trimright/test/tests.js new file mode 100644 index 00000000..b62a413d --- /dev/null +++ b/scripts/2.5/node_modules/string.prototype.trimright/test/tests.js @@ -0,0 +1,26 @@ +'use strict'; + +module.exports = function (trimRight, t) { + t.test('normal cases', function (st) { + st.equal(trimRight(' \t\na \t\n'), ' \t\na', 'strips whitespace off the left side'); + st.equal(trimRight('a'), 'a', 'noop when no whitespace'); + + var allWhitespaceChars = '\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF'; + st.equal(trimRight(allWhitespaceChars + 'a' + allWhitespaceChars), allWhitespaceChars + 'a', 'all expected whitespace chars are trimmed'); + + st.end(); + }); + + // see https://codeblog.jonskeet.uk/2014/12/01/when-is-an-identifier-not-an-identifier-attack-of-the-mongolian-vowel-separator/ + var mongolianVowelSeparator = '\u180E'; + t.test('unicode >= 4 && < 6.3', { skip: !(/^\s$/).test(mongolianVowelSeparator) }, function (st) { + st.equal(trimRight(mongolianVowelSeparator + 'a' + mongolianVowelSeparator), mongolianVowelSeparator + 'a', 'mongolian vowel separator is whitespace'); + st.end(); + }); + + t.test('zero-width spaces', function (st) { + var zeroWidth = '\u200b'; + st.equal(trimRight(zeroWidth), zeroWidth, 'zero width space does not trim'); + st.end(); + }); +}; diff --git a/scripts/2.5/node_modules/util/CHANGELOG.md b/scripts/2.5/node_modules/util/CHANGELOG.md new file mode 100644 index 00000000..c96019f7 --- /dev/null +++ b/scripts/2.5/node_modules/util/CHANGELOG.md @@ -0,0 +1,22 @@ +# util change log + +All notable changes to this project will be documented in this file. + +This project adheres to [Semantic Versioning](http://semver.org/). + +## 0.12.1 +* Update `util.debuglog` compatibility to Node 10.4.0. ([@goto-bus-stop](https://github.com/goto-bus-stop) in [#27](https://github.com/browserify/node-util/pull/27)) +* Allow newer versions of `inherits`. ([@snyamathi](https://github.com/snyamathi) in [#39](https://github.com/browserify/node-util/pull/39)) + +## 0.12.0 +* Add `util.types`. ([@lukechilds](https://github.com/lukechilds) in [#32](https://github.com/browserify/node-util/pull/35)) + +## 0.11.1 +* Fix an infinite loop in `util.deprecate` some build configurations. ([@bernardmcmanus](https://github.com/bernardmcmanus) in [#12](https://github.com/browserify/node-util/pull/12)) + +## 0.11.0 +* Add `util.promisify`. +* Add `util.callbackify`. + +## 0.10.4 +* Update `inherits` dependency. diff --git a/scripts/2.5/node_modules/util/LICENSE b/scripts/2.5/node_modules/util/LICENSE new file mode 100644 index 00000000..e3d4e695 --- /dev/null +++ b/scripts/2.5/node_modules/util/LICENSE @@ -0,0 +1,18 @@ +Copyright Joyent, Inc. and other Node contributors. All rights reserved. +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. diff --git a/scripts/2.5/node_modules/util/README.md b/scripts/2.5/node_modules/util/README.md new file mode 100644 index 00000000..eb630582 --- /dev/null +++ b/scripts/2.5/node_modules/util/README.md @@ -0,0 +1,48 @@ +# util [![Build Status](https://travis-ci.org/browserify/node-util.png?branch=master)](https://travis-ci.org/browserify/node-util) + +> Node.js's [util][util] module for all engines. + +This implements the Node.js [`util`][util] module for environments that do not have it, like browsers. + +## Install + +You usually do not have to install `util` yourself. If your code runs in Node.js, `util` is built in. If your code runs in the browser, bundlers like [browserify](https://github.com/browserify/browserify) or [webpack](https://github.com/webpack/webpack) also include the `util` module. + +But if none of those apply, with npm do: + +```shell +npm install util +``` + +## Usage + +```javascript +var util = require('util') +var EventEmitter = require('events') + +function MyClass() { EventEmitter.call(this) } +util.inherits(MyClass, EventEmitter) +``` + +## Browser Support + +The `util` module uses ES5 features. If you need to support very old browsers like IE8, use a shim like [`es5-shim`](https://www.npmjs.com/package/es5-shim). You need both the shim and the sham versions of `es5-shim`. + +To use `util.promisify` and `util.callbackify`, Promises must already be available. If you need to support browsers like IE11 that do not support Promises, use a shim. [es6-promise](https://github.com/stefanpenner/es6-promise) is a popular one but there are many others available on npm. + +## API + +See the [Node.js util docs][util]. `util` currently supports the Node 8 LTS API. However, some of the methods are outdated. The `inspect` and `format` methods included in this module are a lot more simple and barebones than the ones in Node.js. + +## Contributing + +PRs are very welcome! The main way to contribute to `util` is by porting features, bugfixes and tests from Node.js. Ideally, code contributions to this module are copy-pasted from Node.js and transpiled to ES5, rather than reimplemented from scratch. Matching the Node.js code as closely as possible makes maintenance simpler when new changes land in Node.js. +This module intends to provide exactly the same API as Node.js, so features that are not available in the core `util` module will not be accepted. Feature requests should instead be directed at [nodejs/node](https://github.com/nodejs/node) and will be added to this module once they are implemented in Node.js. + +If there is a difference in behaviour between Node.js's `util` module and this module, please open an issue! + +## License + +[MIT](./LICENSE) + +[util]: https://nodejs.org/docs/latest-v8.x/api/util.html diff --git a/scripts/2.5/node_modules/util/package.json b/scripts/2.5/node_modules/util/package.json new file mode 100644 index 00000000..4feaba66 --- /dev/null +++ b/scripts/2.5/node_modules/util/package.json @@ -0,0 +1,73 @@ +{ + "_from": "util@^0.12.0", + "_id": "util@0.12.1", + "_inBundle": false, + "_integrity": "sha512-MREAtYOp+GTt9/+kwf00IYoHZyjM8VU4aVrkzUlejyqaIjd2GztVl5V9hGXKlvBKE3gENn/FMfHE5v6hElXGcQ==", + "_location": "/util", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "util@^0.12.0", + "name": "util", + "escapedName": "util", + "rawSpec": "^0.12.0", + "saveSpec": null, + "fetchSpec": "^0.12.0" + }, + "_requiredBy": [ + "/assert" + ], + "_resolved": "https://registry.npmjs.org/util/-/util-0.12.1.tgz", + "_shasum": "f908e7b633e7396c764e694dd14e716256ce8ade", + "_spec": "util@^0.12.0", + "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/2.5/node_modules/assert", + "author": { + "name": "Joyent", + "url": "http://www.joyent.com" + }, + "browser": { + "./support/isBuffer.js": "./support/isBufferBrowser.js" + }, + "bugs": { + "url": "https://github.com/browserify/node-util/issues" + }, + "bundleDependencies": false, + "dependencies": { + "inherits": "^2.0.3", + "is-arguments": "^1.0.4", + "is-generator-function": "^1.0.7", + "object.entries": "^1.1.0", + "safe-buffer": "^5.1.2" + }, + "deprecated": false, + "description": "Node.js's util module for all engines", + "devDependencies": { + "airtap": "~1.0.0", + "is-async-supported": "~1.2.0", + "object.assign": "~4.1.0", + "run-series": "~1.1.4", + "tape": "~4.9.0" + }, + "files": [ + "util.js", + "support" + ], + "homepage": "https://github.com/browserify/node-util", + "keywords": [ + "util" + ], + "license": "MIT", + "main": "./util.js", + "name": "util", + "repository": { + "type": "git", + "url": "git://github.com/browserify/node-util.git" + }, + "scripts": { + "test": "node test/node/index.js", + "test:browsers": "airtap test/browser/index.js", + "test:browsers:local": "npm run test:browsers -- --local" + }, + "version": "0.12.1" +} diff --git a/scripts/2.5/node_modules/util/support/isBuffer.js b/scripts/2.5/node_modules/util/support/isBuffer.js new file mode 100644 index 00000000..ace9ac00 --- /dev/null +++ b/scripts/2.5/node_modules/util/support/isBuffer.js @@ -0,0 +1,3 @@ +module.exports = function isBuffer(arg) { + return arg instanceof Buffer; +} diff --git a/scripts/2.5/node_modules/util/support/isBufferBrowser.js b/scripts/2.5/node_modules/util/support/isBufferBrowser.js new file mode 100644 index 00000000..0e1bee1e --- /dev/null +++ b/scripts/2.5/node_modules/util/support/isBufferBrowser.js @@ -0,0 +1,6 @@ +module.exports = function isBuffer(arg) { + return arg && typeof arg === 'object' + && typeof arg.copy === 'function' + && typeof arg.fill === 'function' + && typeof arg.readUInt8 === 'function'; +} \ No newline at end of file diff --git a/scripts/2.5/node_modules/util/support/types.js b/scripts/2.5/node_modules/util/support/types.js new file mode 100644 index 00000000..b1fedf26 --- /dev/null +++ b/scripts/2.5/node_modules/util/support/types.js @@ -0,0 +1,422 @@ +// Currently in sync with Node.js lib/internal/util/types.js +// https://github.com/nodejs/node/commit/112cc7c27551254aa2b17098fb774867f05ed0d9 + +'use strict'; + +var isBuffer = require('./isBuffer'); + +var isArgumentsObject = require('is-arguments'); +var isGeneratorFunction = require('is-generator-function'); + +function uncurryThis(f) { + return f.call.bind(f); +} + +var BigIntSupported = typeof BigInt !== 'undefined'; +var SymbolSupported = typeof Symbol !== 'undefined'; +var SymbolToStringTagSupported = SymbolSupported && typeof Symbol.toStringTag !== 'undefined'; +var Uint8ArraySupported = typeof Uint8Array !== 'undefined'; +var ArrayBufferSupported = typeof ArrayBuffer !== 'undefined'; + +if (Uint8ArraySupported && SymbolToStringTagSupported) { + var TypedArrayPrototype = Object.getPrototypeOf(Uint8Array.prototype); + + var TypedArrayProto_toStringTag = + uncurryThis( + Object.getOwnPropertyDescriptor(TypedArrayPrototype, + Symbol.toStringTag).get); + +} + +var ObjectToString = uncurryThis(Object.prototype.toString); + +var numberValue = uncurryThis(Number.prototype.valueOf); +var stringValue = uncurryThis(String.prototype.valueOf); +var booleanValue = uncurryThis(Boolean.prototype.valueOf); + +if (BigIntSupported) { + var bigIntValue = uncurryThis(BigInt.prototype.valueOf); +} + +if (SymbolSupported) { + var symbolValue = uncurryThis(Symbol.prototype.valueOf); +} + +function checkBoxedPrimitive(value, prototypeValueOf) { + if (typeof value !== 'object') { + return false; + } + try { + prototypeValueOf(value); + return true; + } catch(e) { + return false; + } +} + +exports.isArgumentsObject = isArgumentsObject; + +exports.isGeneratorFunction = isGeneratorFunction; + +// Taken from here and modified for better browser support +// https://github.com/sindresorhus/p-is-promise/blob/cda35a513bda03f977ad5cde3a079d237e82d7ef/index.js +function isPromise(input) { + return ( + ( + typeof Promise !== 'undefined' && + input instanceof Promise + ) || + ( + input !== null && + typeof input === 'object' && + typeof input.then === 'function' && + typeof input.catch === 'function' + ) + ); +} +exports.isPromise = isPromise; + +function isArrayBufferView(value) { + if (ArrayBufferSupported && ArrayBuffer.isView) { + return ArrayBuffer.isView(value); + } + + return ( + isTypedArray(value) || + isDataView(value) + ); +} +exports.isArrayBufferView = isArrayBufferView; + +function isTypedArray(value) { + if (Uint8ArraySupported && SymbolToStringTagSupported) { + return TypedArrayProto_toStringTag(value) !== undefined; + } else { + return ( + isUint8Array(value) || + isUint8ClampedArray(value) || + isUint16Array(value) || + isUint32Array(value) || + isInt8Array(value) || + isInt16Array(value) || + isInt32Array(value) || + isFloat32Array(value) || + isFloat64Array(value) || + isBigInt64Array(value) || + isBigUint64Array(value) + ); + } +} +exports.isTypedArray = isTypedArray; + +function isUint8Array(value) { + if (Uint8ArraySupported && SymbolToStringTagSupported) { + return TypedArrayProto_toStringTag(value) === 'Uint8Array'; + } else { + return ( + ObjectToString(value) === '[object Uint8Array]' || + // If it's a Buffer instance _and_ has a `.buffer` property, + // this is an ArrayBuffer based buffer; thus it's an Uint8Array + // (Old Node.js had a custom non-Uint8Array implementation) + isBuffer(value) && value.buffer !== undefined + ); + } +} +exports.isUint8Array = isUint8Array; + +function isUint8ClampedArray(value) { + if (Uint8ArraySupported && SymbolToStringTagSupported) { + return TypedArrayProto_toStringTag(value) === 'Uint8ClampedArray'; + } else { + return ObjectToString(value) === '[object Uint8ClampedArray]'; + } +} +exports.isUint8ClampedArray = isUint8ClampedArray; + +function isUint16Array(value) { + if (Uint8ArraySupported && SymbolToStringTagSupported) { + return TypedArrayProto_toStringTag(value) === 'Uint16Array'; + } else { + return ObjectToString(value) === '[object Uint16Array]'; + } +} +exports.isUint16Array = isUint16Array; + +function isUint32Array(value) { + if (Uint8ArraySupported && SymbolToStringTagSupported) { + return TypedArrayProto_toStringTag(value) === 'Uint32Array'; + } else { + return ObjectToString(value) === '[object Uint32Array]'; + } +} +exports.isUint32Array = isUint32Array; + +function isInt8Array(value) { + if (Uint8ArraySupported && SymbolToStringTagSupported) { + return TypedArrayProto_toStringTag(value) === 'Int8Array'; + } else { + return ObjectToString(value) === '[object Int8Array]'; + } +} +exports.isInt8Array = isInt8Array; + +function isInt16Array(value) { + if (Uint8ArraySupported && SymbolToStringTagSupported) { + return TypedArrayProto_toStringTag(value) === 'Int16Array'; + } else { + return ObjectToString(value) === '[object Int16Array]'; + } +} +exports.isInt16Array = isInt16Array; + +function isInt32Array(value) { + if (Uint8ArraySupported && SymbolToStringTagSupported) { + return TypedArrayProto_toStringTag(value) === 'Int32Array'; + } else { + return ObjectToString(value) === '[object Int32Array]'; + } +} +exports.isInt32Array = isInt32Array; + +function isFloat32Array(value) { + if (Uint8ArraySupported && SymbolToStringTagSupported) { + return TypedArrayProto_toStringTag(value) === 'Float32Array'; + } else { + return ObjectToString(value) === '[object Float32Array]'; + } +} +exports.isFloat32Array = isFloat32Array; + +function isFloat64Array(value) { + if (Uint8ArraySupported && SymbolToStringTagSupported) { + return TypedArrayProto_toStringTag(value) === 'Float64Array'; + } else { + return ObjectToString(value) === '[object Float64Array]'; + } +} +exports.isFloat64Array = isFloat64Array; + +function isBigInt64Array(value) { + if (Uint8ArraySupported && SymbolToStringTagSupported) { + return TypedArrayProto_toStringTag(value) === 'BigInt64Array'; + } else { + return ObjectToString(value) === '[object BigInt64Array]'; + } +} +exports.isBigInt64Array = isBigInt64Array; + +function isBigUint64Array(value) { + if (Uint8ArraySupported && SymbolToStringTagSupported) { + return TypedArrayProto_toStringTag(value) === 'BigUint64Array'; + } else { + return ObjectToString(value) === '[object BigUint64Array]'; + } +} +exports.isBigUint64Array = isBigUint64Array; + +function isMapToString(value) { + return ObjectToString(value) === '[object Map]'; +} +isMapToString.working = ( + typeof Map !== 'undefined' && + isMapToString(new Map()) +); + +function isMap(value) { + if (typeof Map === 'undefined') { + return false; + } + + return isMapToString.working + ? isMapToString(value) + : value instanceof Map; +} +exports.isMap = isMap; + +function isSetToString(value) { + return ObjectToString(value) === '[object Set]'; +} +isSetToString.working = ( + typeof Set !== 'undefined' && + isSetToString(new Set()) +); +function isSet(value) { + if (typeof Set === 'undefined') { + return false; + } + + return isSetToString.working + ? isSetToString(value) + : value instanceof Set; +} +exports.isSet = isSet; + +function isWeakMapToString(value) { + return ObjectToString(value) === '[object WeakMap]'; +} +isWeakMapToString.working = ( + typeof WeakMap !== 'undefined' && + isWeakMapToString(new WeakMap()) +); +function isWeakMap(value) { + if (typeof WeakMap === 'undefined') { + return false; + } + + return isWeakMapToString.working + ? isWeakMapToString(value) + : value instanceof WeakMap; +} +exports.isWeakMap = isWeakMap; + +function isWeakSetToString(value) { + return ObjectToString(value) === '[object WeakSet]'; +} +isWeakSetToString.working = ( + typeof WeakSet !== 'undefined' && + isWeakSetToString(new WeakSet()) +); +function isWeakSet(value) { + return isWeakSetToString(value); + if (typeof WeakSet === 'undefined') { + return false; + } + + return isWeakSetToString.working + ? isWeakSetToString(value) + : value instanceof WeakSet; +} +exports.isWeakSet = isWeakSet; + +function isArrayBufferToString(value) { + return ObjectToString(value) === '[object ArrayBuffer]'; +} +isArrayBufferToString.working = ( + typeof ArrayBuffer !== 'undefined' && + isArrayBufferToString(new ArrayBuffer()) +); +function isArrayBuffer(value) { + if (typeof ArrayBuffer === 'undefined') { + return false; + } + + return isArrayBufferToString.working + ? isArrayBufferToString(value) + : value instanceof ArrayBuffer; +} +exports.isArrayBuffer = isArrayBuffer; + +function isDataViewToString(value) { + return ObjectToString(value) === '[object DataView]'; +} +isDataViewToString.working = ( + typeof ArrayBuffer !== 'undefined' && + typeof DataView !== 'undefined' && + isDataViewToString(new DataView(new ArrayBuffer(1), 0, 1)) +); +function isDataView(value) { + if (typeof DataView === 'undefined') { + return false; + } + + return isDataViewToString.working + ? isDataViewToString(value) + : value instanceof DataView; +} +exports.isDataView = isDataView; + +function isSharedArrayBufferToString(value) { + return ObjectToString(value) === '[object SharedArrayBuffer]'; +} +isSharedArrayBufferToString.working = ( + typeof SharedArrayBuffer !== 'undefined' && + isSharedArrayBufferToString(new SharedArrayBuffer()) +); +function isSharedArrayBuffer(value) { + if (typeof SharedArrayBuffer === 'undefined') { + return false; + } + + return isSharedArrayBufferToString.working + ? isSharedArrayBufferToString(value) + : value instanceof SharedArrayBuffer; +} +exports.isSharedArrayBuffer = isSharedArrayBuffer; + +function isAsyncFunction(value) { + return ObjectToString(value) === '[object AsyncFunction]'; +} +exports.isAsyncFunction = isAsyncFunction; + +function isMapIterator(value) { + return ObjectToString(value) === '[object Map Iterator]'; +} +exports.isMapIterator = isMapIterator; + +function isSetIterator(value) { + return ObjectToString(value) === '[object Set Iterator]'; +} +exports.isSetIterator = isSetIterator; + +function isGeneratorObject(value) { + return ObjectToString(value) === '[object Generator]'; +} +exports.isGeneratorObject = isGeneratorObject; + +function isWebAssemblyCompiledModule(value) { + return ObjectToString(value) === '[object WebAssembly.Module]'; +} +exports.isWebAssemblyCompiledModule = isWebAssemblyCompiledModule; + +function isNumberObject(value) { + return checkBoxedPrimitive(value, numberValue); +} +exports.isNumberObject = isNumberObject; + +function isStringObject(value) { + return checkBoxedPrimitive(value, stringValue); +} +exports.isStringObject = isStringObject; + +function isBooleanObject(value) { + return checkBoxedPrimitive(value, booleanValue); +} +exports.isBooleanObject = isBooleanObject; + +function isBigIntObject(value) { + return BigIntSupported && checkBoxedPrimitive(value, bigIntValue); +} +exports.isBigIntObject = isBigIntObject; + +function isSymbolObject(value) { + return SymbolSupported && checkBoxedPrimitive(value, symbolValue); +} +exports.isSymbolObject = isSymbolObject; + +function isBoxedPrimitive(value) { + return ( + isNumberObject(value) || + isStringObject(value) || + isBooleanObject(value) || + isBigIntObject(value) || + isSymbolObject(value) + ); +} +exports.isBoxedPrimitive = isBoxedPrimitive; + +function isAnyArrayBuffer(value) { + return Uint8ArraySupported && ( + isArrayBuffer(value) || + isSharedArrayBuffer(value) + ); +} +exports.isAnyArrayBuffer = isAnyArrayBuffer; + +['isProxy', 'isExternal', 'isModuleNamespaceObject'].forEach(function(method) { + Object.defineProperty(exports, method, { + enumerable: false, + value: function() { + throw new Error(method + ' is not supported in userland'); + } + }); +}); diff --git a/scripts/2.5/node_modules/util/util.js b/scripts/2.5/node_modules/util/util.js new file mode 100644 index 00000000..6eea6572 --- /dev/null +++ b/scripts/2.5/node_modules/util/util.js @@ -0,0 +1,715 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors || + function getOwnPropertyDescriptors(obj) { + var keys = Object.keys(obj); + var descriptors = {}; + for (var i = 0; i < keys.length; i++) { + descriptors[keys[i]] = Object.getOwnPropertyDescriptor(obj, keys[i]); + } + return descriptors; + }; + +var formatRegExp = /%[sdj%]/g; +exports.format = function(f) { + if (!isString(f)) { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); + } + return objects.join(' '); + } + + var i = 1; + var args = arguments; + var len = args.length; + var str = String(f).replace(formatRegExp, function(x) { + if (x === '%%') return '%'; + if (i >= len) return x; + switch (x) { + case '%s': return String(args[i++]); + case '%d': return Number(args[i++]); + case '%j': + try { + return JSON.stringify(args[i++]); + } catch (_) { + return '[Circular]'; + } + default: + return x; + } + }); + for (var x = args[i]; i < len; x = args[++i]) { + if (isNull(x) || !isObject(x)) { + str += ' ' + x; + } else { + str += ' ' + inspect(x); + } + } + return str; +}; + + +// Mark that a method should not be used. +// Returns a modified function which warns once by default. +// If --no-deprecation is set, then it is a no-op. +exports.deprecate = function(fn, msg) { + if (typeof process !== 'undefined' && process.noDeprecation === true) { + return fn; + } + + // Allow for deprecating things in the process of starting up. + if (typeof process === 'undefined') { + return function() { + return exports.deprecate(fn, msg).apply(this, arguments); + }; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (process.throwDeprecation) { + throw new Error(msg); + } else if (process.traceDeprecation) { + console.trace(msg); + } else { + console.error(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; +}; + + +var debugs = {}; +var debugEnvRegex = /^$/; + +if (process.env.NODE_DEBUG) { + var debugEnv = process.env.NODE_DEBUG; + debugEnv = debugEnv.replace(/[|\\{}()[\]^$+?.]/g, '\\$&') + .replace(/\*/g, '.*') + .replace(/,/g, '$|^') + .toUpperCase(); + debugEnvRegex = new RegExp('^' + debugEnv + '$', 'i'); +} +exports.debuglog = function(set) { + set = set.toUpperCase(); + if (!debugs[set]) { + if (debugEnvRegex.test(set)) { + var pid = process.pid; + debugs[set] = function() { + var msg = exports.format.apply(exports, arguments); + console.error('%s %d: %s', set, pid, msg); + }; + } else { + debugs[set] = function() {}; + } + } + return debugs[set]; +}; + + +/** + * Echos the value of a value. Trys to print the value out + * in the best way possible given the different types. + * + * @param {Object} obj The object to print out. + * @param {Object} opts Optional options object that alters the output. + */ +/* legacy: obj, showHidden, depth, colors*/ +function inspect(obj, opts) { + // default options + var ctx = { + seen: [], + stylize: stylizeNoColor + }; + // legacy... + if (arguments.length >= 3) ctx.depth = arguments[2]; + if (arguments.length >= 4) ctx.colors = arguments[3]; + if (isBoolean(opts)) { + // legacy... + ctx.showHidden = opts; + } else if (opts) { + // got an "options" object + exports._extend(ctx, opts); + } + // set default options + if (isUndefined(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined(ctx.depth)) ctx.depth = 2; + if (isUndefined(ctx.colors)) ctx.colors = false; + if (isUndefined(ctx.customInspect)) ctx.customInspect = true; + if (ctx.colors) ctx.stylize = stylizeWithColor; + return formatValue(ctx, obj, ctx.depth); +} +exports.inspect = inspect; + + +// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics +inspect.colors = { + 'bold' : [1, 22], + 'italic' : [3, 23], + 'underline' : [4, 24], + 'inverse' : [7, 27], + 'white' : [37, 39], + 'grey' : [90, 39], + 'black' : [30, 39], + 'blue' : [34, 39], + 'cyan' : [36, 39], + 'green' : [32, 39], + 'magenta' : [35, 39], + 'red' : [31, 39], + 'yellow' : [33, 39] +}; + +// Don't use 'blue' not visible on cmd.exe +inspect.styles = { + 'special': 'cyan', + 'number': 'yellow', + 'boolean': 'yellow', + 'undefined': 'grey', + 'null': 'bold', + 'string': 'green', + 'date': 'magenta', + // "name": intentionally not styling + 'regexp': 'red' +}; + + +function stylizeWithColor(str, styleType) { + var style = inspect.styles[styleType]; + + if (style) { + return '\u001b[' + inspect.colors[style][0] + 'm' + str + + '\u001b[' + inspect.colors[style][1] + 'm'; + } else { + return str; + } +} + + +function stylizeNoColor(str, styleType) { + return str; +} + + +function arrayToHash(array) { + var hash = {}; + + array.forEach(function(val, idx) { + hash[val] = true; + }); + + return hash; +} + + +function formatValue(ctx, value, recurseTimes) { + // Provide a hook for user-specified inspect functions. + // Check that value is an object with an inspect function on it + if (ctx.customInspect && + value && + isFunction(value.inspect) && + // Filter out the util module, it's inspect function is special + value.inspect !== exports.inspect && + // Also filter out any prototype objects using the circular check. + !(value.constructor && value.constructor.prototype === value)) { + var ret = value.inspect(recurseTimes, ctx); + if (!isString(ret)) { + ret = formatValue(ctx, ret, recurseTimes); + } + return ret; + } + + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } + + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); + + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } + + // IE doesn't make error fields non-enumerable + // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx + if (isError(value) + && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { + return formatError(value); + } + + // Some type of object without properties can be shortcutted. + if (keys.length === 0) { + if (isFunction(value)) { + var name = value.name ? ': ' + value.name : ''; + return ctx.stylize('[Function' + name + ']', 'special'); + } + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } + if (isDate(value)) { + return ctx.stylize(Date.prototype.toString.call(value), 'date'); + } + if (isError(value)) { + return formatError(value); + } + } + + var base = '', array = false, braces = ['{', '}']; + + // Make Array say that they are Array + if (isArray(value)) { + array = true; + braces = ['[', ']']; + } + + // Make functions say that they are functions + if (isFunction(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; + } + + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } + + // Make dates with properties first say the date + if (isDate(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); + } + + // Make error with message first say the error + if (isError(value)) { + base = ' ' + formatError(value); + } + + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } + + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); + } + } + + ctx.seen.push(value); + + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + } else { + output = keys.map(function(key) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); + }); + } + + ctx.seen.pop(); + + return reduceToSingleString(output, base, braces); +} + + +function formatPrimitive(ctx, value) { + if (isUndefined(value)) + return ctx.stylize('undefined', 'undefined'); + if (isString(value)) { + var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + '\''; + return ctx.stylize(simple, 'string'); + } + if (isNumber(value)) + return ctx.stylize('' + value, 'number'); + if (isBoolean(value)) + return ctx.stylize('' + value, 'boolean'); + // For some reason typeof null is "object", so special case here. + if (isNull(value)) + return ctx.stylize('null', 'null'); +} + + +function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; +} + + +function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { + var output = []; + for (var i = 0, l = value.length; i < l; ++i) { + if (hasOwnProperty(value, String(i))) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + String(i), true)); + } else { + output.push(''); + } + } + keys.forEach(function(key) { + if (!key.match(/^\d+$/)) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + key, true)); + } + }); + return output; +} + + +function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { + var name, str, desc; + desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; + if (desc.get) { + if (desc.set) { + str = ctx.stylize('[Getter/Setter]', 'special'); + } else { + str = ctx.stylize('[Getter]', 'special'); + } + } else { + if (desc.set) { + str = ctx.stylize('[Setter]', 'special'); + } + } + if (!hasOwnProperty(visibleKeys, key)) { + name = '[' + key + ']'; + } + if (!str) { + if (ctx.seen.indexOf(desc.value) < 0) { + if (isNull(recurseTimes)) { + str = formatValue(ctx, desc.value, null); + } else { + str = formatValue(ctx, desc.value, recurseTimes - 1); + } + if (str.indexOf('\n') > -1) { + if (array) { + str = str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n').substr(2); + } else { + str = '\n' + str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n'); + } + } + } else { + str = ctx.stylize('[Circular]', 'special'); + } + } + if (isUndefined(name)) { + if (array && key.match(/^\d+$/)) { + return str; + } + name = JSON.stringify('' + key); + if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { + name = name.substr(1, name.length - 2); + name = ctx.stylize(name, 'name'); + } else { + name = name.replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'"); + name = ctx.stylize(name, 'string'); + } + } + + return name + ': ' + str; +} + + +function reduceToSingleString(output, base, braces) { + var numLinesEst = 0; + var length = output.reduce(function(prev, cur) { + numLinesEst++; + if (cur.indexOf('\n') >= 0) numLinesEst++; + return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; + }, 0); + + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; + } + + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; +} + + +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. +exports.types = require('./support/types'); + +function isArray(ar) { + return Array.isArray(ar); +} +exports.isArray = isArray; + +function isBoolean(arg) { + return typeof arg === 'boolean'; +} +exports.isBoolean = isBoolean; + +function isNull(arg) { + return arg === null; +} +exports.isNull = isNull; + +function isNullOrUndefined(arg) { + return arg == null; +} +exports.isNullOrUndefined = isNullOrUndefined; + +function isNumber(arg) { + return typeof arg === 'number'; +} +exports.isNumber = isNumber; + +function isString(arg) { + return typeof arg === 'string'; +} +exports.isString = isString; + +function isSymbol(arg) { + return typeof arg === 'symbol'; +} +exports.isSymbol = isSymbol; + +function isUndefined(arg) { + return arg === void 0; +} +exports.isUndefined = isUndefined; + +function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; +exports.types.isRegExp = isRegExp; + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +exports.isObject = isObject; + +function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; +} +exports.isDate = isDate; +exports.types.isDate = isDate; + +function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); +} +exports.isError = isError; +exports.types.isNativeError = isError; + +function isFunction(arg) { + return typeof arg === 'function'; +} +exports.isFunction = isFunction; + +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; +} +exports.isPrimitive = isPrimitive; + +exports.isBuffer = require('./support/isBuffer'); + +function objectToString(o) { + return Object.prototype.toString.call(o); +} + + +function pad(n) { + return n < 10 ? '0' + n.toString(10) : n.toString(10); +} + + +var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', + 'Oct', 'Nov', 'Dec']; + +// 26 Feb 16:19:34 +function timestamp() { + var d = new Date(); + var time = [pad(d.getHours()), + pad(d.getMinutes()), + pad(d.getSeconds())].join(':'); + return [d.getDate(), months[d.getMonth()], time].join(' '); +} + + +// log is just a thin wrapper to console.log that prepends a timestamp +exports.log = function() { + console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); +}; + + +/** + * Inherit the prototype methods from one constructor into another. + * + * The Function.prototype.inherits from lang.js rewritten as a standalone + * function (not on Function.prototype). NOTE: If this file is to be loaded + * during bootstrapping this function needs to be rewritten using some native + * functions as prototype setup using normal JavaScript does not work as + * expected during bootstrapping (see mirror.js in r114903). + * + * @param {function} ctor Constructor function which needs to inherit the + * prototype. + * @param {function} superCtor Constructor function to inherit prototype from. + */ +exports.inherits = require('inherits'); + +exports._extend = function(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject(add)) return origin; + + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; + } + return origin; +}; + +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} + +var kCustomPromisifiedSymbol = typeof Symbol !== 'undefined' ? Symbol('util.promisify.custom') : undefined; + +exports.promisify = function promisify(original) { + if (typeof original !== 'function') + throw new TypeError('The "original" argument must be of type Function'); + + if (kCustomPromisifiedSymbol && original[kCustomPromisifiedSymbol]) { + var fn = original[kCustomPromisifiedSymbol]; + if (typeof fn !== 'function') { + throw new TypeError('The "util.promisify.custom" argument must be of type Function'); + } + Object.defineProperty(fn, kCustomPromisifiedSymbol, { + value: fn, enumerable: false, writable: false, configurable: true + }); + return fn; + } + + function fn() { + var promiseResolve, promiseReject; + var promise = new Promise(function (resolve, reject) { + promiseResolve = resolve; + promiseReject = reject; + }); + + var args = []; + for (var i = 0; i < arguments.length; i++) { + args.push(arguments[i]); + } + args.push(function (err, value) { + if (err) { + promiseReject(err); + } else { + promiseResolve(value); + } + }); + + try { + original.apply(this, args); + } catch (err) { + promiseReject(err); + } + + return promise; + } + + Object.setPrototypeOf(fn, Object.getPrototypeOf(original)); + + if (kCustomPromisifiedSymbol) Object.defineProperty(fn, kCustomPromisifiedSymbol, { + value: fn, enumerable: false, writable: false, configurable: true + }); + return Object.defineProperties( + fn, + getOwnPropertyDescriptors(original) + ); +} + +exports.promisify.custom = kCustomPromisifiedSymbol + +function callbackifyOnRejected(reason, cb) { + // `!reason` guard inspired by bluebird (Ref: https://goo.gl/t5IS6M). + // Because `null` is a special error value in callbacks which means "no error + // occurred", we error-wrap so the callback consumer can distinguish between + // "the promise rejected with null" or "the promise fulfilled with undefined". + if (!reason) { + var newReason = new Error('Promise was rejected with a falsy value'); + newReason.reason = reason; + reason = newReason; + } + return cb(reason); +} + +function callbackify(original) { + if (typeof original !== 'function') { + throw new TypeError('The "original" argument must be of type Function'); + } + + // We DO NOT return the promise as it gives the user a false sense that + // the promise is actually somehow related to the callback's execution + // and that the callback throwing will reject the promise. + function callbackified() { + var args = []; + for (var i = 0; i < arguments.length; i++) { + args.push(arguments[i]); + } + + var maybeCb = args.pop(); + if (typeof maybeCb !== 'function') { + throw new TypeError('The last argument must be of type Function'); + } + var self = this; + var cb = function() { + return maybeCb.apply(self, arguments); + }; + // In true node style we process the callback on `nextTick` with all the + // implications (stack, `uncaughtException`, `async_hooks`) + original.apply(this, args) + .then(function(ret) { process.nextTick(cb.bind(null, null, ret)) }, + function(rej) { process.nextTick(callbackifyOnRejected.bind(null, rej, cb)) }); + } + + Object.setPrototypeOf(callbackified, Object.getPrototypeOf(original)); + Object.defineProperties(callbackified, + getOwnPropertyDescriptors(original)); + return callbackified; +} +exports.callbackify = callbackify; diff --git a/scripts/node_modules/.bin/semver b/scripts/node_modules/.bin/semver new file mode 120000 index 00000000..317eb293 --- /dev/null +++ b/scripts/node_modules/.bin/semver @@ -0,0 +1 @@ +../semver/bin/semver \ No newline at end of file diff --git a/scripts/node_modules/bson/HISTORY.md b/scripts/node_modules/bson/HISTORY.md new file mode 100644 index 00000000..0da8acef --- /dev/null +++ b/scripts/node_modules/bson/HISTORY.md @@ -0,0 +1,268 @@ + +## [1.1.1](https://github.com/mongodb/js-bson/compare/v1.1.0...v1.1.1) (2019-03-08) + + +### Bug Fixes + +* **object-id:** support 4.x->1.x interop for MinKey and ObjectId ([53419a5](https://github.com/mongodb/js-bson/commit/53419a5)) + + +### Features + +* replace new Buffer with modern versions ([24aefba](https://github.com/mongodb/js-bson/commit/24aefba)) + + + + +# [1.1.0](https://github.com/mongodb/js-bson/compare/v1.0.9...v1.1.0) (2018-08-13) + + +### Bug Fixes + +* **serializer:** do not use checkKeys for $clusterTime ([573e141](https://github.com/mongodb/js-bson/commit/573e141)) + + + + +## [1.0.9](https://github.com/mongodb/js-bson/compare/v1.0.8...v1.0.9) (2018-06-07) + + +### Bug Fixes + +* **serializer:** remove use of `const` ([5feb12f](https://github.com/mongodb/js-bson/commit/5feb12f)) + + + + +## [1.0.7](https://github.com/mongodb/js-bson/compare/v1.0.6...v1.0.7) (2018-06-06) + + +### Bug Fixes + +* **binary:** add type checking for buffer ([26b05b5](https://github.com/mongodb/js-bson/commit/26b05b5)) +* **bson:** fix custom inspect property ([080323b](https://github.com/mongodb/js-bson/commit/080323b)) +* **readme:** clarify documentation about deserialize methods ([20f764c](https://github.com/mongodb/js-bson/commit/20f764c)) +* **serialization:** normalize function stringification ([1320c10](https://github.com/mongodb/js-bson/commit/1320c10)) + + + + +## [1.0.6](https://github.com/mongodb/js-bson/compare/v1.0.5...v1.0.6) (2018-03-12) + + +### Features + +* **serialization:** support arbitrary sizes for the internal serialization buffer ([abe97bc](https://github.com/mongodb/js-bson/commit/abe97bc)) + + + + +## 1.0.5 (2018-02-26) + + +### Bug Fixes + +* **decimal128:** add basic guard against REDOS attacks ([bd61c45](https://github.com/mongodb/js-bson/commit/bd61c45)) +* **objectid:** if pid is 1, use random value ([e188ae6](https://github.com/mongodb/js-bson/commit/e188ae6)) + + + +1.0.4 2016-01-11 +---------------- +- #204 remove Buffer.from as it's partially broken in early 4.x.x. series of node releases. + +1.0.3 2016-01-03 +---------------- +- Fixed toString for ObjectId so it will work with inspect. + +1.0.2 2016-01-02 +---------------- +- Minor optimizations for ObjectID to use Buffer.from where available. + +1.0.1 2016-12-06 +---------------- +- Reverse behavior for undefined to be serialized as NULL. MongoDB 3.4 does not allow for undefined comparisons. + +1.0.0 2016-12-06 +---------------- +- Introduced new BSON API and documentation. + +0.5.7 2016-11-18 +----------------- +- NODE-848 BSON Regex flags must be alphabetically ordered. + +0.5.6 2016-10-19 +----------------- +- NODE-833, Detects cyclic dependencies in documents and throws error if one is found. +- Fix(deserializer): corrected the check for (size + index) comparison… (Issue #195, https://github.com/JoelParke). + +0.5.5 2016-09-15 +----------------- +- Added DBPointer up conversion to DBRef + +0.5.4 2016-08-23 +----------------- +- Added promoteValues flag (default to true) allowing user to specify if deserialization should be into wrapper classes only. + +0.5.3 2016-07-11 +----------------- +- Throw error if ObjectId is not a string or a buffer. + +0.5.2 2016-07-11 +----------------- +- All values encoded big-endian style for ObjectId. + +0.5.1 2016-07-11 +----------------- +- Fixed encoding/decoding issue in ObjectId timestamp generation. +- Removed BinaryParser dependency from the serializer/deserializer. + +0.5.0 2016-07-05 +----------------- +- Added Decimal128 type and extended test suite to include entire bson corpus. + +0.4.23 2016-04-08 +----------------- +- Allow for proper detection of ObjectId or objects that look like ObjectId, improving compatibility across third party libraries. +- Remove one package from dependency due to having been pulled from NPM. + +0.4.22 2016-03-04 +----------------- +- Fix "TypeError: data.copy is not a function" in Electron (Issue #170, https://github.com/kangas). +- Fixed issue with undefined type on deserializing. + +0.4.21 2016-01-12 +----------------- +- Minor optimizations to avoid non needed object creation. + +0.4.20 2015-10-15 +----------------- +- Added bower file to repository. +- Fixed browser pid sometimes set greater than 0xFFFF on browsers (Issue #155, https://github.com/rahatarmanahmed) + +0.4.19 2015-10-15 +----------------- +- Remove all support for bson-ext. + +0.4.18 2015-10-15 +----------------- +- ObjectID equality check should return boolean instead of throwing exception for invalid oid string #139 +- add option for deserializing binary into Buffer object #116 + +0.4.17 2015-10-15 +----------------- +- Validate regexp string for null bytes and throw if there is one. + +0.4.16 2015-10-07 +----------------- +- Fixed issue with return statement in Map.js. + +0.4.15 2015-10-06 +----------------- +- Exposed Map correctly via index.js file. + +0.4.14 2015-10-06 +----------------- +- Exposed Map correctly via bson.js file. + +0.4.13 2015-10-06 +----------------- +- Added ES6 Map type serialization as well as a polyfill for ES5. + +0.4.12 2015-09-18 +----------------- +- Made ignore undefined an optional parameter. + +0.4.11 2015-08-06 +----------------- +- Minor fix for invalid key checking. + +0.4.10 2015-08-06 +----------------- +- NODE-38 Added new BSONRegExp type to allow direct serialization to MongoDB type. +- Some performance improvements by in lining code. + +0.4.9 2015-08-06 +---------------- +- Undefined fields are omitted from serialization in objects. + +0.4.8 2015-07-14 +---------------- +- Fixed size validation to ensure we can deserialize from dumped files. + +0.4.7 2015-06-26 +---------------- +- Added ability to instruct deserializer to return raw BSON buffers for named array fields. +- Minor deserialization optimization by moving inlined function out. + +0.4.6 2015-06-17 +---------------- +- Fixed serializeWithBufferAndIndex bug. + +0.4.5 2015-06-17 +---------------- +- Removed any references to the shared buffer to avoid non GC collectible bson instances. + +0.4.4 2015-06-17 +---------------- +- Fixed rethrowing of error when not RangeError. + +0.4.3 2015-06-17 +---------------- +- Start buffer at 64K and double as needed, meaning we keep a low memory profile until needed. + +0.4.2 2015-06-16 +---------------- +- More fixes for corrupt Bson + +0.4.1 2015-06-16 +---------------- +- More fixes for corrupt Bson + +0.4.0 2015-06-16 +---------------- +- New JS serializer serializing into a single buffer then copying out the new buffer. Performance is similar to current C++ parser. +- Removed bson-ext extension dependency for now. + +0.3.2 2015-03-27 +---------------- +- Removed node-gyp from install script in package.json. + +0.3.1 2015-03-27 +---------------- +- Return pure js version on native() call if failed to initialize. + +0.3.0 2015-03-26 +---------------- +- Pulled out all C++ code into bson-ext and made it an optional dependency. + +0.2.21 2015-03-21 +----------------- +- Updated Nan to 1.7.0 to support io.js and node 0.12.0 + +0.2.19 2015-02-16 +----------------- +- Updated Nan to 1.6.2 to support io.js and node 0.12.0 + +0.2.18 2015-01-20 +----------------- +- Updated Nan to 1.5.1 to support io.js + +0.2.16 2014-12-17 +----------------- +- Made pid cycle on 0xffff to avoid weird overflows on creation of ObjectID's + +0.2.12 2014-08-24 +----------------- +- Fixes for fortify review of c++ extension +- toBSON correctly allows returns of non objects + +0.2.3 2013-10-01 +---------------- +- Drying of ObjectId code for generation of id (Issue #54, https://github.com/moredip) +- Fixed issue where corrupt CString's could cause endless loop +- Support for Node 0.11.X > (Issue #49, https://github.com/kkoopa) + +0.1.4 2012-09-25 +---------------- +- Added precompiled c++ native extensions for win32 ia32 and x64 diff --git a/scripts/node_modules/bson/LICENSE.md b/scripts/node_modules/bson/LICENSE.md new file mode 100644 index 00000000..261eeb9e --- /dev/null +++ b/scripts/node_modules/bson/LICENSE.md @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/scripts/node_modules/bson/README.md b/scripts/node_modules/bson/README.md new file mode 100644 index 00000000..06883410 --- /dev/null +++ b/scripts/node_modules/bson/README.md @@ -0,0 +1,170 @@ +# BSON parser + +BSON is short for Bin­ary JSON and is the bin­ary-en­coded seri­al­iz­a­tion of JSON-like doc­u­ments. You can learn more about it in [the specification](http://bsonspec.org). + +This browser version of the BSON parser is compiled using [webpack](https://webpack.js.org/) and the current version is pre-compiled in the `browser_build` directory. + +This is the default BSON parser, however, there is a C++ Node.js addon version as well that does not support the browser. It can be found at [mongod-js/bson-ext](https://github.com/mongodb-js/bson-ext). + +## Usage + +To build a new version perform the following operations: + +``` +npm install +npm run build +``` + +A simple example of how to use BSON in the browser: + +```html + + + +``` + +A simple example of how to use BSON in `Node.js`: + +```js +// Get BSON parser class +var BSON = require('bson') +// Get the Long type +var Long = BSON.Long; +// Create a bson parser instance +var bson = new BSON(); + +// Serialize document +var doc = { long: Long.fromNumber(100) } + +// Serialize a document +var data = bson.serialize(doc) +console.log('data:', data) + +// Deserialize the resulting Buffer +var doc_2 = bson.deserialize(data) +console.log('doc_2:', doc_2) +``` + +## Installation + +`npm install bson` + +## API + +### BSON types + +For all BSON types documentation, please refer to the following sources: + * [MongoDB BSON Type Reference](https://docs.mongodb.com/manual/reference/bson-types/) + * [BSON Spec](https://bsonspec.org/) + +### BSON serialization and deserialiation + +**`new BSON()`** - Creates a new BSON serializer/deserializer you can use to serialize and deserialize BSON. + +#### BSON.serialize + +The BSON `serialize` method takes a JavaScript object and an optional options object and returns a Node.js Buffer. + + * `BSON.serialize(object, options)` + * @param {Object} object the JavaScript object to serialize. + * @param {Boolean} [options.checkKeys=false] the serializer will check if keys are valid. + * @param {Boolean} [options.serializeFunctions=false] serialize the JavaScript functions. + * @param {Boolean} [options.ignoreUndefined=true] + * @return {Buffer} returns a Buffer instance. + +#### BSON.serializeWithBufferAndIndex + +The BSON `serializeWithBufferAndIndex` method takes an object, a target buffer instance and an optional options object and returns the end serialization index in the final buffer. + + * `BSON.serializeWithBufferAndIndex(object, buffer, options)` + * @param {Object} object the JavaScript object to serialize. + * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. + * @param {Boolean} [options.checkKeys=false] the serializer will check if keys are valid. + * @param {Boolean} [options.serializeFunctions=false] serialize the JavaScript functions. + * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields. + * @param {Number} [options.index=0] the index in the buffer where we wish to start serializing into. + * @return {Number} returns the index pointing to the last written byte in the buffer. + +#### BSON.calculateObjectSize + +The BSON `calculateObjectSize` method takes a JavaScript object and an optional options object and returns the size of the BSON object. + + * `BSON.calculateObjectSize(object, options)` + * @param {Object} object the JavaScript object to serialize. + * @param {Boolean} [options.serializeFunctions=false] serialize the JavaScript functions. + * @param {Boolean} [options.ignoreUndefined=true] + * @return {Buffer} returns a Buffer instance. + +#### BSON.deserialize + +The BSON `deserialize` method takes a Node.js Buffer and an optional options object and returns a deserialized JavaScript object. + + * `BSON.deserialize(buffer, options)` + * @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized. + * @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse. + * @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function. + * @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits + * @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a Node.js Buffer instance. + * @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types. + * @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer. + * @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances. + * @return {Object} returns the deserialized Javascript Object. + +#### BSON.deserializeStream + +The BSON `deserializeStream` method takes a Node.js Buffer, `startIndex` and allow more control over deserialization of a Buffer containing concatenated BSON documents. + + * `BSON.deserializeStream(buffer, startIndex, numberOfDocuments, documents, docStartIndex, options)` + * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. + * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. + * @param {Number} numberOfDocuments number of documents to deserialize. + * @param {Array} documents an array where to store the deserialized documents. + * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. + * @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized. + * @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse. + * @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function. + * @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits + * @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a Node.js Buffer instance. + * @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types. + * @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer. + * @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances. + * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. + +## FAQ + +#### Why does `undefined` get converted to `null`? + +The `undefined` BSON type has been [deprecated for many years](http://bsonspec.org/spec.html), so this library has dropped support for it. Use the `ignoreUndefined` option (for example, from the [driver](http://mongodb.github.io/node-mongodb-native/2.2/api/MongoClient.html#connect) ) to instead remove `undefined` keys. + +#### How do I add custom serialization logic? + +This library looks for `toBSON()` functions on every path, and calls the `toBSON()` function to get the value to serialize. + +```javascript +var bson = new BSON(); + +class CustomSerialize { + toBSON() { + return 42; + } +} + +const obj = { answer: new CustomSerialize() }; +// "{ answer: 42 }" +console.log(bson.deserialize(bson.serialize(obj))); +``` diff --git a/scripts/node_modules/bson/bower.json b/scripts/node_modules/bson/bower.json new file mode 100644 index 00000000..b32140ea --- /dev/null +++ b/scripts/node_modules/bson/bower.json @@ -0,0 +1,25 @@ +{ + "name": "bson", + "description": "A bson parser for node.js and the browser", + "keywords": [ + "mongodb", + "bson", + "parser" + ], + "author": "Christian Amor Kvalheim ", + "main": "./browser_build/bson.js", + "license": "Apache-2.0", + "moduleType": [ + "globals", + "node" + ], + "ignore": [ + "**/.*", + "alternate_parsers", + "benchmarks", + "bower_components", + "node_modules", + "test", + "tools" + ] +} diff --git a/scripts/node_modules/bson/browser_build/bson.js b/scripts/node_modules/bson/browser_build/bson.js new file mode 100644 index 00000000..e601c992 --- /dev/null +++ b/scripts/node_modules/bson/browser_build/bson.js @@ -0,0 +1,17769 @@ +(function webpackUniversalModuleDefinition(root, factory) { + if(typeof exports === 'object' && typeof module === 'object') + module.exports = factory(); + else if(typeof define === 'function' && define.amd) + define([], factory); + else { + var a = factory(); + for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i]; + } +})(this, function() { +return /******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; + +/******/ // The require function +/******/ function __webpack_require__(moduleId) { + +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) +/******/ return installedModules[moduleId].exports; + +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ exports: {}, +/******/ id: moduleId, +/******/ loaded: false +/******/ }; + +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); + +/******/ // Flag the module as loaded +/******/ module.loaded = true; + +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } + + +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; + +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; + +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = "/"; + +/******/ // Load entry module and return exports +/******/ return __webpack_require__(0); +/******/ }) +/************************************************************************/ +/******/ ([ +/* 0 */ +/***/ (function(module, exports, __webpack_require__) { + + __webpack_require__(1); + module.exports = __webpack_require__(327); + + +/***/ }), +/* 1 */ +/***/ (function(module, exports, __webpack_require__) { + + /* WEBPACK VAR INJECTION */(function(global) {"use strict"; + + __webpack_require__(2); + + __webpack_require__(323); + + __webpack_require__(324); + + if (global._babelPolyfill) { + throw new Error("only one instance of babel-polyfill is allowed"); + } + global._babelPolyfill = true; + + var DEFINE_PROPERTY = "defineProperty"; + function define(O, key, value) { + O[key] || Object[DEFINE_PROPERTY](O, key, { + writable: true, + configurable: true, + value: value + }); + } + + define(String.prototype, "padLeft", "".padStart); + define(String.prototype, "padRight", "".padEnd); + + "pop,reverse,shift,keys,values,entries,indexOf,every,some,forEach,map,filter,find,findIndex,includes,join,slice,concat,push,splice,unshift,sort,lastIndexOf,reduce,reduceRight,copyWithin,fill".split(",").forEach(function (key) { + [][key] && define(Array, key, Function.call.bind([][key])); + }); + /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) + +/***/ }), +/* 2 */ +/***/ (function(module, exports, __webpack_require__) { + + __webpack_require__(3); + __webpack_require__(51); + __webpack_require__(52); + __webpack_require__(53); + __webpack_require__(54); + __webpack_require__(56); + __webpack_require__(59); + __webpack_require__(60); + __webpack_require__(61); + __webpack_require__(62); + __webpack_require__(63); + __webpack_require__(64); + __webpack_require__(65); + __webpack_require__(66); + __webpack_require__(67); + __webpack_require__(69); + __webpack_require__(71); + __webpack_require__(73); + __webpack_require__(75); + __webpack_require__(78); + __webpack_require__(79); + __webpack_require__(80); + __webpack_require__(84); + __webpack_require__(86); + __webpack_require__(88); + __webpack_require__(91); + __webpack_require__(92); + __webpack_require__(93); + __webpack_require__(94); + __webpack_require__(96); + __webpack_require__(97); + __webpack_require__(98); + __webpack_require__(99); + __webpack_require__(100); + __webpack_require__(101); + __webpack_require__(102); + __webpack_require__(104); + __webpack_require__(105); + __webpack_require__(106); + __webpack_require__(108); + __webpack_require__(109); + __webpack_require__(110); + __webpack_require__(112); + __webpack_require__(114); + __webpack_require__(115); + __webpack_require__(116); + __webpack_require__(117); + __webpack_require__(118); + __webpack_require__(119); + __webpack_require__(120); + __webpack_require__(121); + __webpack_require__(122); + __webpack_require__(123); + __webpack_require__(124); + __webpack_require__(125); + __webpack_require__(126); + __webpack_require__(131); + __webpack_require__(132); + __webpack_require__(136); + __webpack_require__(137); + __webpack_require__(138); + __webpack_require__(139); + __webpack_require__(141); + __webpack_require__(142); + __webpack_require__(143); + __webpack_require__(144); + __webpack_require__(145); + __webpack_require__(146); + __webpack_require__(147); + __webpack_require__(148); + __webpack_require__(149); + __webpack_require__(150); + __webpack_require__(151); + __webpack_require__(152); + __webpack_require__(153); + __webpack_require__(154); + __webpack_require__(155); + __webpack_require__(157); + __webpack_require__(158); + __webpack_require__(160); + __webpack_require__(161); + __webpack_require__(167); + __webpack_require__(168); + __webpack_require__(170); + __webpack_require__(171); + __webpack_require__(172); + __webpack_require__(176); + __webpack_require__(177); + __webpack_require__(178); + __webpack_require__(179); + __webpack_require__(180); + __webpack_require__(182); + __webpack_require__(183); + __webpack_require__(184); + __webpack_require__(185); + __webpack_require__(188); + __webpack_require__(190); + __webpack_require__(191); + __webpack_require__(192); + __webpack_require__(194); + __webpack_require__(196); + __webpack_require__(198); + __webpack_require__(199); + __webpack_require__(200); + __webpack_require__(202); + __webpack_require__(203); + __webpack_require__(204); + __webpack_require__(205); + __webpack_require__(216); + __webpack_require__(220); + __webpack_require__(221); + __webpack_require__(223); + __webpack_require__(224); + __webpack_require__(228); + __webpack_require__(229); + __webpack_require__(231); + __webpack_require__(232); + __webpack_require__(233); + __webpack_require__(234); + __webpack_require__(235); + __webpack_require__(236); + __webpack_require__(237); + __webpack_require__(238); + __webpack_require__(239); + __webpack_require__(240); + __webpack_require__(241); + __webpack_require__(242); + __webpack_require__(243); + __webpack_require__(244); + __webpack_require__(245); + __webpack_require__(246); + __webpack_require__(247); + __webpack_require__(248); + __webpack_require__(249); + __webpack_require__(251); + __webpack_require__(252); + __webpack_require__(253); + __webpack_require__(254); + __webpack_require__(255); + __webpack_require__(257); + __webpack_require__(258); + __webpack_require__(259); + __webpack_require__(261); + __webpack_require__(262); + __webpack_require__(263); + __webpack_require__(264); + __webpack_require__(265); + __webpack_require__(266); + __webpack_require__(267); + __webpack_require__(268); + __webpack_require__(270); + __webpack_require__(271); + __webpack_require__(273); + __webpack_require__(274); + __webpack_require__(275); + __webpack_require__(276); + __webpack_require__(279); + __webpack_require__(280); + __webpack_require__(282); + __webpack_require__(283); + __webpack_require__(284); + __webpack_require__(285); + __webpack_require__(287); + __webpack_require__(288); + __webpack_require__(289); + __webpack_require__(290); + __webpack_require__(291); + __webpack_require__(292); + __webpack_require__(293); + __webpack_require__(294); + __webpack_require__(295); + __webpack_require__(296); + __webpack_require__(298); + __webpack_require__(299); + __webpack_require__(300); + __webpack_require__(301); + __webpack_require__(302); + __webpack_require__(303); + __webpack_require__(304); + __webpack_require__(305); + __webpack_require__(306); + __webpack_require__(307); + __webpack_require__(308); + __webpack_require__(310); + __webpack_require__(311); + __webpack_require__(312); + __webpack_require__(313); + __webpack_require__(314); + __webpack_require__(315); + __webpack_require__(316); + __webpack_require__(317); + __webpack_require__(318); + __webpack_require__(319); + __webpack_require__(320); + __webpack_require__(321); + __webpack_require__(322); + module.exports = __webpack_require__(9); + + +/***/ }), +/* 3 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // ECMAScript 6 symbols shim + var global = __webpack_require__(4); + var has = __webpack_require__(5); + var DESCRIPTORS = __webpack_require__(6); + var $export = __webpack_require__(8); + var redefine = __webpack_require__(18); + var META = __webpack_require__(22).KEY; + var $fails = __webpack_require__(7); + var shared = __webpack_require__(23); + var setToStringTag = __webpack_require__(25); + var uid = __webpack_require__(19); + var wks = __webpack_require__(26); + var wksExt = __webpack_require__(27); + var wksDefine = __webpack_require__(28); + var enumKeys = __webpack_require__(29); + var isArray = __webpack_require__(44); + var anObject = __webpack_require__(12); + var isObject = __webpack_require__(13); + var toIObject = __webpack_require__(32); + var toPrimitive = __webpack_require__(16); + var createDesc = __webpack_require__(17); + var _create = __webpack_require__(45); + var gOPNExt = __webpack_require__(48); + var $GOPD = __webpack_require__(50); + var $DP = __webpack_require__(11); + var $keys = __webpack_require__(30); + var gOPD = $GOPD.f; + var dP = $DP.f; + var gOPN = gOPNExt.f; + var $Symbol = global.Symbol; + var $JSON = global.JSON; + var _stringify = $JSON && $JSON.stringify; + var PROTOTYPE = 'prototype'; + var HIDDEN = wks('_hidden'); + var TO_PRIMITIVE = wks('toPrimitive'); + var isEnum = {}.propertyIsEnumerable; + var SymbolRegistry = shared('symbol-registry'); + var AllSymbols = shared('symbols'); + var OPSymbols = shared('op-symbols'); + var ObjectProto = Object[PROTOTYPE]; + var USE_NATIVE = typeof $Symbol == 'function'; + var QObject = global.QObject; + // Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173 + var setter = !QObject || !QObject[PROTOTYPE] || !QObject[PROTOTYPE].findChild; + + // fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687 + var setSymbolDesc = DESCRIPTORS && $fails(function () { + return _create(dP({}, 'a', { + get: function () { return dP(this, 'a', { value: 7 }).a; } + })).a != 7; + }) ? function (it, key, D) { + var protoDesc = gOPD(ObjectProto, key); + if (protoDesc) delete ObjectProto[key]; + dP(it, key, D); + if (protoDesc && it !== ObjectProto) dP(ObjectProto, key, protoDesc); + } : dP; + + var wrap = function (tag) { + var sym = AllSymbols[tag] = _create($Symbol[PROTOTYPE]); + sym._k = tag; + return sym; + }; + + var isSymbol = USE_NATIVE && typeof $Symbol.iterator == 'symbol' ? function (it) { + return typeof it == 'symbol'; + } : function (it) { + return it instanceof $Symbol; + }; + + var $defineProperty = function defineProperty(it, key, D) { + if (it === ObjectProto) $defineProperty(OPSymbols, key, D); + anObject(it); + key = toPrimitive(key, true); + anObject(D); + if (has(AllSymbols, key)) { + if (!D.enumerable) { + if (!has(it, HIDDEN)) dP(it, HIDDEN, createDesc(1, {})); + it[HIDDEN][key] = true; + } else { + if (has(it, HIDDEN) && it[HIDDEN][key]) it[HIDDEN][key] = false; + D = _create(D, { enumerable: createDesc(0, false) }); + } return setSymbolDesc(it, key, D); + } return dP(it, key, D); + }; + var $defineProperties = function defineProperties(it, P) { + anObject(it); + var keys = enumKeys(P = toIObject(P)); + var i = 0; + var l = keys.length; + var key; + while (l > i) $defineProperty(it, key = keys[i++], P[key]); + return it; + }; + var $create = function create(it, P) { + return P === undefined ? _create(it) : $defineProperties(_create(it), P); + }; + var $propertyIsEnumerable = function propertyIsEnumerable(key) { + var E = isEnum.call(this, key = toPrimitive(key, true)); + if (this === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key)) return false; + return E || !has(this, key) || !has(AllSymbols, key) || has(this, HIDDEN) && this[HIDDEN][key] ? E : true; + }; + var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(it, key) { + it = toIObject(it); + key = toPrimitive(key, true); + if (it === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key)) return; + var D = gOPD(it, key); + if (D && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key])) D.enumerable = true; + return D; + }; + var $getOwnPropertyNames = function getOwnPropertyNames(it) { + var names = gOPN(toIObject(it)); + var result = []; + var i = 0; + var key; + while (names.length > i) { + if (!has(AllSymbols, key = names[i++]) && key != HIDDEN && key != META) result.push(key); + } return result; + }; + var $getOwnPropertySymbols = function getOwnPropertySymbols(it) { + var IS_OP = it === ObjectProto; + var names = gOPN(IS_OP ? OPSymbols : toIObject(it)); + var result = []; + var i = 0; + var key; + while (names.length > i) { + if (has(AllSymbols, key = names[i++]) && (IS_OP ? has(ObjectProto, key) : true)) result.push(AllSymbols[key]); + } return result; + }; + + // 19.4.1.1 Symbol([description]) + if (!USE_NATIVE) { + $Symbol = function Symbol() { + if (this instanceof $Symbol) throw TypeError('Symbol is not a constructor!'); + var tag = uid(arguments.length > 0 ? arguments[0] : undefined); + var $set = function (value) { + if (this === ObjectProto) $set.call(OPSymbols, value); + if (has(this, HIDDEN) && has(this[HIDDEN], tag)) this[HIDDEN][tag] = false; + setSymbolDesc(this, tag, createDesc(1, value)); + }; + if (DESCRIPTORS && setter) setSymbolDesc(ObjectProto, tag, { configurable: true, set: $set }); + return wrap(tag); + }; + redefine($Symbol[PROTOTYPE], 'toString', function toString() { + return this._k; + }); + + $GOPD.f = $getOwnPropertyDescriptor; + $DP.f = $defineProperty; + __webpack_require__(49).f = gOPNExt.f = $getOwnPropertyNames; + __webpack_require__(43).f = $propertyIsEnumerable; + __webpack_require__(42).f = $getOwnPropertySymbols; + + if (DESCRIPTORS && !__webpack_require__(24)) { + redefine(ObjectProto, 'propertyIsEnumerable', $propertyIsEnumerable, true); + } + + wksExt.f = function (name) { + return wrap(wks(name)); + }; + } + + $export($export.G + $export.W + $export.F * !USE_NATIVE, { Symbol: $Symbol }); + + for (var es6Symbols = ( + // 19.4.2.2, 19.4.2.3, 19.4.2.4, 19.4.2.6, 19.4.2.8, 19.4.2.9, 19.4.2.10, 19.4.2.11, 19.4.2.12, 19.4.2.13, 19.4.2.14 + 'hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables' + ).split(','), j = 0; es6Symbols.length > j;)wks(es6Symbols[j++]); + + for (var wellKnownSymbols = $keys(wks.store), k = 0; wellKnownSymbols.length > k;) wksDefine(wellKnownSymbols[k++]); + + $export($export.S + $export.F * !USE_NATIVE, 'Symbol', { + // 19.4.2.1 Symbol.for(key) + 'for': function (key) { + return has(SymbolRegistry, key += '') + ? SymbolRegistry[key] + : SymbolRegistry[key] = $Symbol(key); + }, + // 19.4.2.5 Symbol.keyFor(sym) + keyFor: function keyFor(sym) { + if (!isSymbol(sym)) throw TypeError(sym + ' is not a symbol!'); + for (var key in SymbolRegistry) if (SymbolRegistry[key] === sym) return key; + }, + useSetter: function () { setter = true; }, + useSimple: function () { setter = false; } + }); + + $export($export.S + $export.F * !USE_NATIVE, 'Object', { + // 19.1.2.2 Object.create(O [, Properties]) + create: $create, + // 19.1.2.4 Object.defineProperty(O, P, Attributes) + defineProperty: $defineProperty, + // 19.1.2.3 Object.defineProperties(O, Properties) + defineProperties: $defineProperties, + // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P) + getOwnPropertyDescriptor: $getOwnPropertyDescriptor, + // 19.1.2.7 Object.getOwnPropertyNames(O) + getOwnPropertyNames: $getOwnPropertyNames, + // 19.1.2.8 Object.getOwnPropertySymbols(O) + getOwnPropertySymbols: $getOwnPropertySymbols + }); + + // 24.3.2 JSON.stringify(value [, replacer [, space]]) + $JSON && $export($export.S + $export.F * (!USE_NATIVE || $fails(function () { + var S = $Symbol(); + // MS Edge converts symbol values to JSON as {} + // WebKit converts symbol values to JSON as null + // V8 throws on boxed symbols + return _stringify([S]) != '[null]' || _stringify({ a: S }) != '{}' || _stringify(Object(S)) != '{}'; + })), 'JSON', { + stringify: function stringify(it) { + var args = [it]; + var i = 1; + var replacer, $replacer; + while (arguments.length > i) args.push(arguments[i++]); + $replacer = replacer = args[1]; + if (!isObject(replacer) && it === undefined || isSymbol(it)) return; // IE8 returns string on undefined + if (!isArray(replacer)) replacer = function (key, value) { + if (typeof $replacer == 'function') value = $replacer.call(this, key, value); + if (!isSymbol(value)) return value; + }; + args[1] = replacer; + return _stringify.apply($JSON, args); + } + }); + + // 19.4.3.4 Symbol.prototype[@@toPrimitive](hint) + $Symbol[PROTOTYPE][TO_PRIMITIVE] || __webpack_require__(10)($Symbol[PROTOTYPE], TO_PRIMITIVE, $Symbol[PROTOTYPE].valueOf); + // 19.4.3.5 Symbol.prototype[@@toStringTag] + setToStringTag($Symbol, 'Symbol'); + // 20.2.1.9 Math[@@toStringTag] + setToStringTag(Math, 'Math', true); + // 24.3.3 JSON[@@toStringTag] + setToStringTag(global.JSON, 'JSON', true); + + +/***/ }), +/* 4 */ +/***/ (function(module, exports) { + + // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 + var global = module.exports = typeof window != 'undefined' && window.Math == Math + ? window : typeof self != 'undefined' && self.Math == Math ? self + // eslint-disable-next-line no-new-func + : Function('return this')(); + if (typeof __g == 'number') __g = global; // eslint-disable-line no-undef + + +/***/ }), +/* 5 */ +/***/ (function(module, exports) { + + var hasOwnProperty = {}.hasOwnProperty; + module.exports = function (it, key) { + return hasOwnProperty.call(it, key); + }; + + +/***/ }), +/* 6 */ +/***/ (function(module, exports, __webpack_require__) { + + // Thank's IE8 for his funny defineProperty + module.exports = !__webpack_require__(7)(function () { + return Object.defineProperty({}, 'a', { get: function () { return 7; } }).a != 7; + }); + + +/***/ }), +/* 7 */ +/***/ (function(module, exports) { + + module.exports = function (exec) { + try { + return !!exec(); + } catch (e) { + return true; + } + }; + + +/***/ }), +/* 8 */ +/***/ (function(module, exports, __webpack_require__) { + + var global = __webpack_require__(4); + var core = __webpack_require__(9); + var hide = __webpack_require__(10); + var redefine = __webpack_require__(18); + var ctx = __webpack_require__(20); + var PROTOTYPE = 'prototype'; + + var $export = function (type, name, source) { + var IS_FORCED = type & $export.F; + var IS_GLOBAL = type & $export.G; + var IS_STATIC = type & $export.S; + var IS_PROTO = type & $export.P; + var IS_BIND = type & $export.B; + var target = IS_GLOBAL ? global : IS_STATIC ? global[name] || (global[name] = {}) : (global[name] || {})[PROTOTYPE]; + var exports = IS_GLOBAL ? core : core[name] || (core[name] = {}); + var expProto = exports[PROTOTYPE] || (exports[PROTOTYPE] = {}); + var key, own, out, exp; + if (IS_GLOBAL) source = name; + for (key in source) { + // contains in native + own = !IS_FORCED && target && target[key] !== undefined; + // export native or passed + out = (own ? target : source)[key]; + // bind timers to global for call from export context + exp = IS_BIND && own ? ctx(out, global) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out; + // extend global + if (target) redefine(target, key, out, type & $export.U); + // export + if (exports[key] != out) hide(exports, key, exp); + if (IS_PROTO && expProto[key] != out) expProto[key] = out; + } + }; + global.core = core; + // type bitmap + $export.F = 1; // forced + $export.G = 2; // global + $export.S = 4; // static + $export.P = 8; // proto + $export.B = 16; // bind + $export.W = 32; // wrap + $export.U = 64; // safe + $export.R = 128; // real proto method for `library` + module.exports = $export; + + +/***/ }), +/* 9 */ +/***/ (function(module, exports) { + + var core = module.exports = { version: '2.5.7' }; + if (typeof __e == 'number') __e = core; // eslint-disable-line no-undef + + +/***/ }), +/* 10 */ +/***/ (function(module, exports, __webpack_require__) { + + var dP = __webpack_require__(11); + var createDesc = __webpack_require__(17); + module.exports = __webpack_require__(6) ? function (object, key, value) { + return dP.f(object, key, createDesc(1, value)); + } : function (object, key, value) { + object[key] = value; + return object; + }; + + +/***/ }), +/* 11 */ +/***/ (function(module, exports, __webpack_require__) { + + var anObject = __webpack_require__(12); + var IE8_DOM_DEFINE = __webpack_require__(14); + var toPrimitive = __webpack_require__(16); + var dP = Object.defineProperty; + + exports.f = __webpack_require__(6) ? Object.defineProperty : function defineProperty(O, P, Attributes) { + anObject(O); + P = toPrimitive(P, true); + anObject(Attributes); + if (IE8_DOM_DEFINE) try { + return dP(O, P, Attributes); + } catch (e) { /* empty */ } + if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported!'); + if ('value' in Attributes) O[P] = Attributes.value; + return O; + }; + + +/***/ }), +/* 12 */ +/***/ (function(module, exports, __webpack_require__) { + + var isObject = __webpack_require__(13); + module.exports = function (it) { + if (!isObject(it)) throw TypeError(it + ' is not an object!'); + return it; + }; + + +/***/ }), +/* 13 */ +/***/ (function(module, exports) { + + module.exports = function (it) { + return typeof it === 'object' ? it !== null : typeof it === 'function'; + }; + + +/***/ }), +/* 14 */ +/***/ (function(module, exports, __webpack_require__) { + + module.exports = !__webpack_require__(6) && !__webpack_require__(7)(function () { + return Object.defineProperty(__webpack_require__(15)('div'), 'a', { get: function () { return 7; } }).a != 7; + }); + + +/***/ }), +/* 15 */ +/***/ (function(module, exports, __webpack_require__) { + + var isObject = __webpack_require__(13); + var document = __webpack_require__(4).document; + // typeof document.createElement is 'object' in old IE + var is = isObject(document) && isObject(document.createElement); + module.exports = function (it) { + return is ? document.createElement(it) : {}; + }; + + +/***/ }), +/* 16 */ +/***/ (function(module, exports, __webpack_require__) { + + // 7.1.1 ToPrimitive(input [, PreferredType]) + var isObject = __webpack_require__(13); + // instead of the ES6 spec version, we didn't implement @@toPrimitive case + // and the second argument - flag - preferred type is a string + module.exports = function (it, S) { + if (!isObject(it)) return it; + var fn, val; + if (S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val; + if (typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it))) return val; + if (!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val; + throw TypeError("Can't convert object to primitive value"); + }; + + +/***/ }), +/* 17 */ +/***/ (function(module, exports) { + + module.exports = function (bitmap, value) { + return { + enumerable: !(bitmap & 1), + configurable: !(bitmap & 2), + writable: !(bitmap & 4), + value: value + }; + }; + + +/***/ }), +/* 18 */ +/***/ (function(module, exports, __webpack_require__) { + + var global = __webpack_require__(4); + var hide = __webpack_require__(10); + var has = __webpack_require__(5); + var SRC = __webpack_require__(19)('src'); + var TO_STRING = 'toString'; + var $toString = Function[TO_STRING]; + var TPL = ('' + $toString).split(TO_STRING); + + __webpack_require__(9).inspectSource = function (it) { + return $toString.call(it); + }; + + (module.exports = function (O, key, val, safe) { + var isFunction = typeof val == 'function'; + if (isFunction) has(val, 'name') || hide(val, 'name', key); + if (O[key] === val) return; + if (isFunction) has(val, SRC) || hide(val, SRC, O[key] ? '' + O[key] : TPL.join(String(key))); + if (O === global) { + O[key] = val; + } else if (!safe) { + delete O[key]; + hide(O, key, val); + } else if (O[key]) { + O[key] = val; + } else { + hide(O, key, val); + } + // add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative + })(Function.prototype, TO_STRING, function toString() { + return typeof this == 'function' && this[SRC] || $toString.call(this); + }); + + +/***/ }), +/* 19 */ +/***/ (function(module, exports) { + + var id = 0; + var px = Math.random(); + module.exports = function (key) { + return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36)); + }; + + +/***/ }), +/* 20 */ +/***/ (function(module, exports, __webpack_require__) { + + // optional / simple context binding + var aFunction = __webpack_require__(21); + module.exports = function (fn, that, length) { + aFunction(fn); + if (that === undefined) return fn; + switch (length) { + case 1: return function (a) { + return fn.call(that, a); + }; + case 2: return function (a, b) { + return fn.call(that, a, b); + }; + case 3: return function (a, b, c) { + return fn.call(that, a, b, c); + }; + } + return function (/* ...args */) { + return fn.apply(that, arguments); + }; + }; + + +/***/ }), +/* 21 */ +/***/ (function(module, exports) { + + module.exports = function (it) { + if (typeof it != 'function') throw TypeError(it + ' is not a function!'); + return it; + }; + + +/***/ }), +/* 22 */ +/***/ (function(module, exports, __webpack_require__) { + + var META = __webpack_require__(19)('meta'); + var isObject = __webpack_require__(13); + var has = __webpack_require__(5); + var setDesc = __webpack_require__(11).f; + var id = 0; + var isExtensible = Object.isExtensible || function () { + return true; + }; + var FREEZE = !__webpack_require__(7)(function () { + return isExtensible(Object.preventExtensions({})); + }); + var setMeta = function (it) { + setDesc(it, META, { value: { + i: 'O' + ++id, // object ID + w: {} // weak collections IDs + } }); + }; + var fastKey = function (it, create) { + // return primitive with prefix + if (!isObject(it)) return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it; + if (!has(it, META)) { + // can't set metadata to uncaught frozen object + if (!isExtensible(it)) return 'F'; + // not necessary to add metadata + if (!create) return 'E'; + // add missing metadata + setMeta(it); + // return object ID + } return it[META].i; + }; + var getWeak = function (it, create) { + if (!has(it, META)) { + // can't set metadata to uncaught frozen object + if (!isExtensible(it)) return true; + // not necessary to add metadata + if (!create) return false; + // add missing metadata + setMeta(it); + // return hash weak collections IDs + } return it[META].w; + }; + // add metadata on freeze-family methods calling + var onFreeze = function (it) { + if (FREEZE && meta.NEED && isExtensible(it) && !has(it, META)) setMeta(it); + return it; + }; + var meta = module.exports = { + KEY: META, + NEED: false, + fastKey: fastKey, + getWeak: getWeak, + onFreeze: onFreeze + }; + + +/***/ }), +/* 23 */ +/***/ (function(module, exports, __webpack_require__) { + + var core = __webpack_require__(9); + var global = __webpack_require__(4); + var SHARED = '__core-js_shared__'; + var store = global[SHARED] || (global[SHARED] = {}); + + (module.exports = function (key, value) { + return store[key] || (store[key] = value !== undefined ? value : {}); + })('versions', []).push({ + version: core.version, + mode: __webpack_require__(24) ? 'pure' : 'global', + copyright: '© 2018 Denis Pushkarev (zloirock.ru)' + }); + + +/***/ }), +/* 24 */ +/***/ (function(module, exports) { + + module.exports = false; + + +/***/ }), +/* 25 */ +/***/ (function(module, exports, __webpack_require__) { + + var def = __webpack_require__(11).f; + var has = __webpack_require__(5); + var TAG = __webpack_require__(26)('toStringTag'); + + module.exports = function (it, tag, stat) { + if (it && !has(it = stat ? it : it.prototype, TAG)) def(it, TAG, { configurable: true, value: tag }); + }; + + +/***/ }), +/* 26 */ +/***/ (function(module, exports, __webpack_require__) { + + var store = __webpack_require__(23)('wks'); + var uid = __webpack_require__(19); + var Symbol = __webpack_require__(4).Symbol; + var USE_SYMBOL = typeof Symbol == 'function'; + + var $exports = module.exports = function (name) { + return store[name] || (store[name] = + USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)('Symbol.' + name)); + }; + + $exports.store = store; + + +/***/ }), +/* 27 */ +/***/ (function(module, exports, __webpack_require__) { + + exports.f = __webpack_require__(26); + + +/***/ }), +/* 28 */ +/***/ (function(module, exports, __webpack_require__) { + + var global = __webpack_require__(4); + var core = __webpack_require__(9); + var LIBRARY = __webpack_require__(24); + var wksExt = __webpack_require__(27); + var defineProperty = __webpack_require__(11).f; + module.exports = function (name) { + var $Symbol = core.Symbol || (core.Symbol = LIBRARY ? {} : global.Symbol || {}); + if (name.charAt(0) != '_' && !(name in $Symbol)) defineProperty($Symbol, name, { value: wksExt.f(name) }); + }; + + +/***/ }), +/* 29 */ +/***/ (function(module, exports, __webpack_require__) { + + // all enumerable object keys, includes symbols + var getKeys = __webpack_require__(30); + var gOPS = __webpack_require__(42); + var pIE = __webpack_require__(43); + module.exports = function (it) { + var result = getKeys(it); + var getSymbols = gOPS.f; + if (getSymbols) { + var symbols = getSymbols(it); + var isEnum = pIE.f; + var i = 0; + var key; + while (symbols.length > i) if (isEnum.call(it, key = symbols[i++])) result.push(key); + } return result; + }; + + +/***/ }), +/* 30 */ +/***/ (function(module, exports, __webpack_require__) { + + // 19.1.2.14 / 15.2.3.14 Object.keys(O) + var $keys = __webpack_require__(31); + var enumBugKeys = __webpack_require__(41); + + module.exports = Object.keys || function keys(O) { + return $keys(O, enumBugKeys); + }; + + +/***/ }), +/* 31 */ +/***/ (function(module, exports, __webpack_require__) { + + var has = __webpack_require__(5); + var toIObject = __webpack_require__(32); + var arrayIndexOf = __webpack_require__(36)(false); + var IE_PROTO = __webpack_require__(40)('IE_PROTO'); + + module.exports = function (object, names) { + var O = toIObject(object); + var i = 0; + var result = []; + var key; + for (key in O) if (key != IE_PROTO) has(O, key) && result.push(key); + // Don't enum bug & hidden keys + while (names.length > i) if (has(O, key = names[i++])) { + ~arrayIndexOf(result, key) || result.push(key); + } + return result; + }; + + +/***/ }), +/* 32 */ +/***/ (function(module, exports, __webpack_require__) { + + // to indexed object, toObject with fallback for non-array-like ES3 strings + var IObject = __webpack_require__(33); + var defined = __webpack_require__(35); + module.exports = function (it) { + return IObject(defined(it)); + }; + + +/***/ }), +/* 33 */ +/***/ (function(module, exports, __webpack_require__) { + + // fallback for non-array-like ES3 and non-enumerable old V8 strings + var cof = __webpack_require__(34); + // eslint-disable-next-line no-prototype-builtins + module.exports = Object('z').propertyIsEnumerable(0) ? Object : function (it) { + return cof(it) == 'String' ? it.split('') : Object(it); + }; + + +/***/ }), +/* 34 */ +/***/ (function(module, exports) { + + var toString = {}.toString; + + module.exports = function (it) { + return toString.call(it).slice(8, -1); + }; + + +/***/ }), +/* 35 */ +/***/ (function(module, exports) { + + // 7.2.1 RequireObjectCoercible(argument) + module.exports = function (it) { + if (it == undefined) throw TypeError("Can't call method on " + it); + return it; + }; + + +/***/ }), +/* 36 */ +/***/ (function(module, exports, __webpack_require__) { + + // false -> Array#indexOf + // true -> Array#includes + var toIObject = __webpack_require__(32); + var toLength = __webpack_require__(37); + var toAbsoluteIndex = __webpack_require__(39); + module.exports = function (IS_INCLUDES) { + return function ($this, el, fromIndex) { + var O = toIObject($this); + var length = toLength(O.length); + var index = toAbsoluteIndex(fromIndex, length); + var value; + // Array#includes uses SameValueZero equality algorithm + // eslint-disable-next-line no-self-compare + if (IS_INCLUDES && el != el) while (length > index) { + value = O[index++]; + // eslint-disable-next-line no-self-compare + if (value != value) return true; + // Array#indexOf ignores holes, Array#includes - not + } else for (;length > index; index++) if (IS_INCLUDES || index in O) { + if (O[index] === el) return IS_INCLUDES || index || 0; + } return !IS_INCLUDES && -1; + }; + }; + + +/***/ }), +/* 37 */ +/***/ (function(module, exports, __webpack_require__) { + + // 7.1.15 ToLength + var toInteger = __webpack_require__(38); + var min = Math.min; + module.exports = function (it) { + return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991 + }; + + +/***/ }), +/* 38 */ +/***/ (function(module, exports) { + + // 7.1.4 ToInteger + var ceil = Math.ceil; + var floor = Math.floor; + module.exports = function (it) { + return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it); + }; + + +/***/ }), +/* 39 */ +/***/ (function(module, exports, __webpack_require__) { + + var toInteger = __webpack_require__(38); + var max = Math.max; + var min = Math.min; + module.exports = function (index, length) { + index = toInteger(index); + return index < 0 ? max(index + length, 0) : min(index, length); + }; + + +/***/ }), +/* 40 */ +/***/ (function(module, exports, __webpack_require__) { + + var shared = __webpack_require__(23)('keys'); + var uid = __webpack_require__(19); + module.exports = function (key) { + return shared[key] || (shared[key] = uid(key)); + }; + + +/***/ }), +/* 41 */ +/***/ (function(module, exports) { + + // IE 8- don't enum bug keys + module.exports = ( + 'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf' + ).split(','); + + +/***/ }), +/* 42 */ +/***/ (function(module, exports) { + + exports.f = Object.getOwnPropertySymbols; + + +/***/ }), +/* 43 */ +/***/ (function(module, exports) { + + exports.f = {}.propertyIsEnumerable; + + +/***/ }), +/* 44 */ +/***/ (function(module, exports, __webpack_require__) { + + // 7.2.2 IsArray(argument) + var cof = __webpack_require__(34); + module.exports = Array.isArray || function isArray(arg) { + return cof(arg) == 'Array'; + }; + + +/***/ }), +/* 45 */ +/***/ (function(module, exports, __webpack_require__) { + + // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) + var anObject = __webpack_require__(12); + var dPs = __webpack_require__(46); + var enumBugKeys = __webpack_require__(41); + var IE_PROTO = __webpack_require__(40)('IE_PROTO'); + var Empty = function () { /* empty */ }; + var PROTOTYPE = 'prototype'; + + // Create object with fake `null` prototype: use iframe Object with cleared prototype + var createDict = function () { + // Thrash, waste and sodomy: IE GC bug + var iframe = __webpack_require__(15)('iframe'); + var i = enumBugKeys.length; + var lt = '<'; + var gt = '>'; + var iframeDocument; + iframe.style.display = 'none'; + __webpack_require__(47).appendChild(iframe); + iframe.src = 'javascript:'; // eslint-disable-line no-script-url + // createDict = iframe.contentWindow.Object; + // html.removeChild(iframe); + iframeDocument = iframe.contentWindow.document; + iframeDocument.open(); + iframeDocument.write(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt); + iframeDocument.close(); + createDict = iframeDocument.F; + while (i--) delete createDict[PROTOTYPE][enumBugKeys[i]]; + return createDict(); + }; + + module.exports = Object.create || function create(O, Properties) { + var result; + if (O !== null) { + Empty[PROTOTYPE] = anObject(O); + result = new Empty(); + Empty[PROTOTYPE] = null; + // add "__proto__" for Object.getPrototypeOf polyfill + result[IE_PROTO] = O; + } else result = createDict(); + return Properties === undefined ? result : dPs(result, Properties); + }; + + +/***/ }), +/* 46 */ +/***/ (function(module, exports, __webpack_require__) { + + var dP = __webpack_require__(11); + var anObject = __webpack_require__(12); + var getKeys = __webpack_require__(30); + + module.exports = __webpack_require__(6) ? Object.defineProperties : function defineProperties(O, Properties) { + anObject(O); + var keys = getKeys(Properties); + var length = keys.length; + var i = 0; + var P; + while (length > i) dP.f(O, P = keys[i++], Properties[P]); + return O; + }; + + +/***/ }), +/* 47 */ +/***/ (function(module, exports, __webpack_require__) { + + var document = __webpack_require__(4).document; + module.exports = document && document.documentElement; + + +/***/ }), +/* 48 */ +/***/ (function(module, exports, __webpack_require__) { + + // fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window + var toIObject = __webpack_require__(32); + var gOPN = __webpack_require__(49).f; + var toString = {}.toString; + + var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames + ? Object.getOwnPropertyNames(window) : []; + + var getWindowNames = function (it) { + try { + return gOPN(it); + } catch (e) { + return windowNames.slice(); + } + }; + + module.exports.f = function getOwnPropertyNames(it) { + return windowNames && toString.call(it) == '[object Window]' ? getWindowNames(it) : gOPN(toIObject(it)); + }; + + +/***/ }), +/* 49 */ +/***/ (function(module, exports, __webpack_require__) { + + // 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O) + var $keys = __webpack_require__(31); + var hiddenKeys = __webpack_require__(41).concat('length', 'prototype'); + + exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) { + return $keys(O, hiddenKeys); + }; + + +/***/ }), +/* 50 */ +/***/ (function(module, exports, __webpack_require__) { + + var pIE = __webpack_require__(43); + var createDesc = __webpack_require__(17); + var toIObject = __webpack_require__(32); + var toPrimitive = __webpack_require__(16); + var has = __webpack_require__(5); + var IE8_DOM_DEFINE = __webpack_require__(14); + var gOPD = Object.getOwnPropertyDescriptor; + + exports.f = __webpack_require__(6) ? gOPD : function getOwnPropertyDescriptor(O, P) { + O = toIObject(O); + P = toPrimitive(P, true); + if (IE8_DOM_DEFINE) try { + return gOPD(O, P); + } catch (e) { /* empty */ } + if (has(O, P)) return createDesc(!pIE.f.call(O, P), O[P]); + }; + + +/***/ }), +/* 51 */ +/***/ (function(module, exports, __webpack_require__) { + + var $export = __webpack_require__(8); + // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) + $export($export.S, 'Object', { create: __webpack_require__(45) }); + + +/***/ }), +/* 52 */ +/***/ (function(module, exports, __webpack_require__) { + + var $export = __webpack_require__(8); + // 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes) + $export($export.S + $export.F * !__webpack_require__(6), 'Object', { defineProperty: __webpack_require__(11).f }); + + +/***/ }), +/* 53 */ +/***/ (function(module, exports, __webpack_require__) { + + var $export = __webpack_require__(8); + // 19.1.2.3 / 15.2.3.7 Object.defineProperties(O, Properties) + $export($export.S + $export.F * !__webpack_require__(6), 'Object', { defineProperties: __webpack_require__(46) }); + + +/***/ }), +/* 54 */ +/***/ (function(module, exports, __webpack_require__) { + + // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P) + var toIObject = __webpack_require__(32); + var $getOwnPropertyDescriptor = __webpack_require__(50).f; + + __webpack_require__(55)('getOwnPropertyDescriptor', function () { + return function getOwnPropertyDescriptor(it, key) { + return $getOwnPropertyDescriptor(toIObject(it), key); + }; + }); + + +/***/ }), +/* 55 */ +/***/ (function(module, exports, __webpack_require__) { + + // most Object methods by ES6 should accept primitives + var $export = __webpack_require__(8); + var core = __webpack_require__(9); + var fails = __webpack_require__(7); + module.exports = function (KEY, exec) { + var fn = (core.Object || {})[KEY] || Object[KEY]; + var exp = {}; + exp[KEY] = exec(fn); + $export($export.S + $export.F * fails(function () { fn(1); }), 'Object', exp); + }; + + +/***/ }), +/* 56 */ +/***/ (function(module, exports, __webpack_require__) { + + // 19.1.2.9 Object.getPrototypeOf(O) + var toObject = __webpack_require__(57); + var $getPrototypeOf = __webpack_require__(58); + + __webpack_require__(55)('getPrototypeOf', function () { + return function getPrototypeOf(it) { + return $getPrototypeOf(toObject(it)); + }; + }); + + +/***/ }), +/* 57 */ +/***/ (function(module, exports, __webpack_require__) { + + // 7.1.13 ToObject(argument) + var defined = __webpack_require__(35); + module.exports = function (it) { + return Object(defined(it)); + }; + + +/***/ }), +/* 58 */ +/***/ (function(module, exports, __webpack_require__) { + + // 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O) + var has = __webpack_require__(5); + var toObject = __webpack_require__(57); + var IE_PROTO = __webpack_require__(40)('IE_PROTO'); + var ObjectProto = Object.prototype; + + module.exports = Object.getPrototypeOf || function (O) { + O = toObject(O); + if (has(O, IE_PROTO)) return O[IE_PROTO]; + if (typeof O.constructor == 'function' && O instanceof O.constructor) { + return O.constructor.prototype; + } return O instanceof Object ? ObjectProto : null; + }; + + +/***/ }), +/* 59 */ +/***/ (function(module, exports, __webpack_require__) { + + // 19.1.2.14 Object.keys(O) + var toObject = __webpack_require__(57); + var $keys = __webpack_require__(30); + + __webpack_require__(55)('keys', function () { + return function keys(it) { + return $keys(toObject(it)); + }; + }); + + +/***/ }), +/* 60 */ +/***/ (function(module, exports, __webpack_require__) { + + // 19.1.2.7 Object.getOwnPropertyNames(O) + __webpack_require__(55)('getOwnPropertyNames', function () { + return __webpack_require__(48).f; + }); + + +/***/ }), +/* 61 */ +/***/ (function(module, exports, __webpack_require__) { + + // 19.1.2.5 Object.freeze(O) + var isObject = __webpack_require__(13); + var meta = __webpack_require__(22).onFreeze; + + __webpack_require__(55)('freeze', function ($freeze) { + return function freeze(it) { + return $freeze && isObject(it) ? $freeze(meta(it)) : it; + }; + }); + + +/***/ }), +/* 62 */ +/***/ (function(module, exports, __webpack_require__) { + + // 19.1.2.17 Object.seal(O) + var isObject = __webpack_require__(13); + var meta = __webpack_require__(22).onFreeze; + + __webpack_require__(55)('seal', function ($seal) { + return function seal(it) { + return $seal && isObject(it) ? $seal(meta(it)) : it; + }; + }); + + +/***/ }), +/* 63 */ +/***/ (function(module, exports, __webpack_require__) { + + // 19.1.2.15 Object.preventExtensions(O) + var isObject = __webpack_require__(13); + var meta = __webpack_require__(22).onFreeze; + + __webpack_require__(55)('preventExtensions', function ($preventExtensions) { + return function preventExtensions(it) { + return $preventExtensions && isObject(it) ? $preventExtensions(meta(it)) : it; + }; + }); + + +/***/ }), +/* 64 */ +/***/ (function(module, exports, __webpack_require__) { + + // 19.1.2.12 Object.isFrozen(O) + var isObject = __webpack_require__(13); + + __webpack_require__(55)('isFrozen', function ($isFrozen) { + return function isFrozen(it) { + return isObject(it) ? $isFrozen ? $isFrozen(it) : false : true; + }; + }); + + +/***/ }), +/* 65 */ +/***/ (function(module, exports, __webpack_require__) { + + // 19.1.2.13 Object.isSealed(O) + var isObject = __webpack_require__(13); + + __webpack_require__(55)('isSealed', function ($isSealed) { + return function isSealed(it) { + return isObject(it) ? $isSealed ? $isSealed(it) : false : true; + }; + }); + + +/***/ }), +/* 66 */ +/***/ (function(module, exports, __webpack_require__) { + + // 19.1.2.11 Object.isExtensible(O) + var isObject = __webpack_require__(13); + + __webpack_require__(55)('isExtensible', function ($isExtensible) { + return function isExtensible(it) { + return isObject(it) ? $isExtensible ? $isExtensible(it) : true : false; + }; + }); + + +/***/ }), +/* 67 */ +/***/ (function(module, exports, __webpack_require__) { + + // 19.1.3.1 Object.assign(target, source) + var $export = __webpack_require__(8); + + $export($export.S + $export.F, 'Object', { assign: __webpack_require__(68) }); + + +/***/ }), +/* 68 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // 19.1.2.1 Object.assign(target, source, ...) + var getKeys = __webpack_require__(30); + var gOPS = __webpack_require__(42); + var pIE = __webpack_require__(43); + var toObject = __webpack_require__(57); + var IObject = __webpack_require__(33); + var $assign = Object.assign; + + // should work with symbols and should have deterministic property order (V8 bug) + module.exports = !$assign || __webpack_require__(7)(function () { + var A = {}; + var B = {}; + // eslint-disable-next-line no-undef + var S = Symbol(); + var K = 'abcdefghijklmnopqrst'; + A[S] = 7; + K.split('').forEach(function (k) { B[k] = k; }); + return $assign({}, A)[S] != 7 || Object.keys($assign({}, B)).join('') != K; + }) ? function assign(target, source) { // eslint-disable-line no-unused-vars + var T = toObject(target); + var aLen = arguments.length; + var index = 1; + var getSymbols = gOPS.f; + var isEnum = pIE.f; + while (aLen > index) { + var S = IObject(arguments[index++]); + var keys = getSymbols ? getKeys(S).concat(getSymbols(S)) : getKeys(S); + var length = keys.length; + var j = 0; + var key; + while (length > j) if (isEnum.call(S, key = keys[j++])) T[key] = S[key]; + } return T; + } : $assign; + + +/***/ }), +/* 69 */ +/***/ (function(module, exports, __webpack_require__) { + + // 19.1.3.10 Object.is(value1, value2) + var $export = __webpack_require__(8); + $export($export.S, 'Object', { is: __webpack_require__(70) }); + + +/***/ }), +/* 70 */ +/***/ (function(module, exports) { + + // 7.2.9 SameValue(x, y) + module.exports = Object.is || function is(x, y) { + // eslint-disable-next-line no-self-compare + return x === y ? x !== 0 || 1 / x === 1 / y : x != x && y != y; + }; + + +/***/ }), +/* 71 */ +/***/ (function(module, exports, __webpack_require__) { + + // 19.1.3.19 Object.setPrototypeOf(O, proto) + var $export = __webpack_require__(8); + $export($export.S, 'Object', { setPrototypeOf: __webpack_require__(72).set }); + + +/***/ }), +/* 72 */ +/***/ (function(module, exports, __webpack_require__) { + + // Works with __proto__ only. Old v8 can't work with null proto objects. + /* eslint-disable no-proto */ + var isObject = __webpack_require__(13); + var anObject = __webpack_require__(12); + var check = function (O, proto) { + anObject(O); + if (!isObject(proto) && proto !== null) throw TypeError(proto + ": can't set as prototype!"); + }; + module.exports = { + set: Object.setPrototypeOf || ('__proto__' in {} ? // eslint-disable-line + function (test, buggy, set) { + try { + set = __webpack_require__(20)(Function.call, __webpack_require__(50).f(Object.prototype, '__proto__').set, 2); + set(test, []); + buggy = !(test instanceof Array); + } catch (e) { buggy = true; } + return function setPrototypeOf(O, proto) { + check(O, proto); + if (buggy) O.__proto__ = proto; + else set(O, proto); + return O; + }; + }({}, false) : undefined), + check: check + }; + + +/***/ }), +/* 73 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // 19.1.3.6 Object.prototype.toString() + var classof = __webpack_require__(74); + var test = {}; + test[__webpack_require__(26)('toStringTag')] = 'z'; + if (test + '' != '[object z]') { + __webpack_require__(18)(Object.prototype, 'toString', function toString() { + return '[object ' + classof(this) + ']'; + }, true); + } + + +/***/ }), +/* 74 */ +/***/ (function(module, exports, __webpack_require__) { + + // getting tag from 19.1.3.6 Object.prototype.toString() + var cof = __webpack_require__(34); + var TAG = __webpack_require__(26)('toStringTag'); + // ES3 wrong here + var ARG = cof(function () { return arguments; }()) == 'Arguments'; + + // fallback for IE11 Script Access Denied error + var tryGet = function (it, key) { + try { + return it[key]; + } catch (e) { /* empty */ } + }; + + module.exports = function (it) { + var O, T, B; + return it === undefined ? 'Undefined' : it === null ? 'Null' + // @@toStringTag case + : typeof (T = tryGet(O = Object(it), TAG)) == 'string' ? T + // builtinTag case + : ARG ? cof(O) + // ES3 arguments fallback + : (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B; + }; + + +/***/ }), +/* 75 */ +/***/ (function(module, exports, __webpack_require__) { + + // 19.2.3.2 / 15.3.4.5 Function.prototype.bind(thisArg, args...) + var $export = __webpack_require__(8); + + $export($export.P, 'Function', { bind: __webpack_require__(76) }); + + +/***/ }), +/* 76 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var aFunction = __webpack_require__(21); + var isObject = __webpack_require__(13); + var invoke = __webpack_require__(77); + var arraySlice = [].slice; + var factories = {}; + + var construct = function (F, len, args) { + if (!(len in factories)) { + for (var n = [], i = 0; i < len; i++) n[i] = 'a[' + i + ']'; + // eslint-disable-next-line no-new-func + factories[len] = Function('F,a', 'return new F(' + n.join(',') + ')'); + } return factories[len](F, args); + }; + + module.exports = Function.bind || function bind(that /* , ...args */) { + var fn = aFunction(this); + var partArgs = arraySlice.call(arguments, 1); + var bound = function (/* args... */) { + var args = partArgs.concat(arraySlice.call(arguments)); + return this instanceof bound ? construct(fn, args.length, args) : invoke(fn, args, that); + }; + if (isObject(fn.prototype)) bound.prototype = fn.prototype; + return bound; + }; + + +/***/ }), +/* 77 */ +/***/ (function(module, exports) { + + // fast apply, http://jsperf.lnkit.com/fast-apply/5 + module.exports = function (fn, args, that) { + var un = that === undefined; + switch (args.length) { + case 0: return un ? fn() + : fn.call(that); + case 1: return un ? fn(args[0]) + : fn.call(that, args[0]); + case 2: return un ? fn(args[0], args[1]) + : fn.call(that, args[0], args[1]); + case 3: return un ? fn(args[0], args[1], args[2]) + : fn.call(that, args[0], args[1], args[2]); + case 4: return un ? fn(args[0], args[1], args[2], args[3]) + : fn.call(that, args[0], args[1], args[2], args[3]); + } return fn.apply(that, args); + }; + + +/***/ }), +/* 78 */ +/***/ (function(module, exports, __webpack_require__) { + + var dP = __webpack_require__(11).f; + var FProto = Function.prototype; + var nameRE = /^\s*function ([^ (]*)/; + var NAME = 'name'; + + // 19.2.4.2 name + NAME in FProto || __webpack_require__(6) && dP(FProto, NAME, { + configurable: true, + get: function () { + try { + return ('' + this).match(nameRE)[1]; + } catch (e) { + return ''; + } + } + }); + + +/***/ }), +/* 79 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var isObject = __webpack_require__(13); + var getPrototypeOf = __webpack_require__(58); + var HAS_INSTANCE = __webpack_require__(26)('hasInstance'); + var FunctionProto = Function.prototype; + // 19.2.3.6 Function.prototype[@@hasInstance](V) + if (!(HAS_INSTANCE in FunctionProto)) __webpack_require__(11).f(FunctionProto, HAS_INSTANCE, { value: function (O) { + if (typeof this != 'function' || !isObject(O)) return false; + if (!isObject(this.prototype)) return O instanceof this; + // for environment w/o native `@@hasInstance` logic enough `instanceof`, but add this: + while (O = getPrototypeOf(O)) if (this.prototype === O) return true; + return false; + } }); + + +/***/ }), +/* 80 */ +/***/ (function(module, exports, __webpack_require__) { + + var $export = __webpack_require__(8); + var $parseInt = __webpack_require__(81); + // 18.2.5 parseInt(string, radix) + $export($export.G + $export.F * (parseInt != $parseInt), { parseInt: $parseInt }); + + +/***/ }), +/* 81 */ +/***/ (function(module, exports, __webpack_require__) { + + var $parseInt = __webpack_require__(4).parseInt; + var $trim = __webpack_require__(82).trim; + var ws = __webpack_require__(83); + var hex = /^[-+]?0[xX]/; + + module.exports = $parseInt(ws + '08') !== 8 || $parseInt(ws + '0x16') !== 22 ? function parseInt(str, radix) { + var string = $trim(String(str), 3); + return $parseInt(string, (radix >>> 0) || (hex.test(string) ? 16 : 10)); + } : $parseInt; + + +/***/ }), +/* 82 */ +/***/ (function(module, exports, __webpack_require__) { + + var $export = __webpack_require__(8); + var defined = __webpack_require__(35); + var fails = __webpack_require__(7); + var spaces = __webpack_require__(83); + var space = '[' + spaces + ']'; + var non = '\u200b\u0085'; + var ltrim = RegExp('^' + space + space + '*'); + var rtrim = RegExp(space + space + '*$'); + + var exporter = function (KEY, exec, ALIAS) { + var exp = {}; + var FORCE = fails(function () { + return !!spaces[KEY]() || non[KEY]() != non; + }); + var fn = exp[KEY] = FORCE ? exec(trim) : spaces[KEY]; + if (ALIAS) exp[ALIAS] = fn; + $export($export.P + $export.F * FORCE, 'String', exp); + }; + + // 1 -> String#trimLeft + // 2 -> String#trimRight + // 3 -> String#trim + var trim = exporter.trim = function (string, TYPE) { + string = String(defined(string)); + if (TYPE & 1) string = string.replace(ltrim, ''); + if (TYPE & 2) string = string.replace(rtrim, ''); + return string; + }; + + module.exports = exporter; + + +/***/ }), +/* 83 */ +/***/ (function(module, exports) { + + module.exports = '\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003' + + '\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF'; + + +/***/ }), +/* 84 */ +/***/ (function(module, exports, __webpack_require__) { + + var $export = __webpack_require__(8); + var $parseFloat = __webpack_require__(85); + // 18.2.4 parseFloat(string) + $export($export.G + $export.F * (parseFloat != $parseFloat), { parseFloat: $parseFloat }); + + +/***/ }), +/* 85 */ +/***/ (function(module, exports, __webpack_require__) { + + var $parseFloat = __webpack_require__(4).parseFloat; + var $trim = __webpack_require__(82).trim; + + module.exports = 1 / $parseFloat(__webpack_require__(83) + '-0') !== -Infinity ? function parseFloat(str) { + var string = $trim(String(str), 3); + var result = $parseFloat(string); + return result === 0 && string.charAt(0) == '-' ? -0 : result; + } : $parseFloat; + + +/***/ }), +/* 86 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var global = __webpack_require__(4); + var has = __webpack_require__(5); + var cof = __webpack_require__(34); + var inheritIfRequired = __webpack_require__(87); + var toPrimitive = __webpack_require__(16); + var fails = __webpack_require__(7); + var gOPN = __webpack_require__(49).f; + var gOPD = __webpack_require__(50).f; + var dP = __webpack_require__(11).f; + var $trim = __webpack_require__(82).trim; + var NUMBER = 'Number'; + var $Number = global[NUMBER]; + var Base = $Number; + var proto = $Number.prototype; + // Opera ~12 has broken Object#toString + var BROKEN_COF = cof(__webpack_require__(45)(proto)) == NUMBER; + var TRIM = 'trim' in String.prototype; + + // 7.1.3 ToNumber(argument) + var toNumber = function (argument) { + var it = toPrimitive(argument, false); + if (typeof it == 'string' && it.length > 2) { + it = TRIM ? it.trim() : $trim(it, 3); + var first = it.charCodeAt(0); + var third, radix, maxCode; + if (first === 43 || first === 45) { + third = it.charCodeAt(2); + if (third === 88 || third === 120) return NaN; // Number('+0x1') should be NaN, old V8 fix + } else if (first === 48) { + switch (it.charCodeAt(1)) { + case 66: case 98: radix = 2; maxCode = 49; break; // fast equal /^0b[01]+$/i + case 79: case 111: radix = 8; maxCode = 55; break; // fast equal /^0o[0-7]+$/i + default: return +it; + } + for (var digits = it.slice(2), i = 0, l = digits.length, code; i < l; i++) { + code = digits.charCodeAt(i); + // parseInt parses a string to a first unavailable symbol + // but ToNumber should return NaN if a string contains unavailable symbols + if (code < 48 || code > maxCode) return NaN; + } return parseInt(digits, radix); + } + } return +it; + }; + + if (!$Number(' 0o1') || !$Number('0b1') || $Number('+0x1')) { + $Number = function Number(value) { + var it = arguments.length < 1 ? 0 : value; + var that = this; + return that instanceof $Number + // check on 1..constructor(foo) case + && (BROKEN_COF ? fails(function () { proto.valueOf.call(that); }) : cof(that) != NUMBER) + ? inheritIfRequired(new Base(toNumber(it)), that, $Number) : toNumber(it); + }; + for (var keys = __webpack_require__(6) ? gOPN(Base) : ( + // ES3: + 'MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,' + + // ES6 (in case, if modules with ES6 Number statics required before): + 'EPSILON,isFinite,isInteger,isNaN,isSafeInteger,MAX_SAFE_INTEGER,' + + 'MIN_SAFE_INTEGER,parseFloat,parseInt,isInteger' + ).split(','), j = 0, key; keys.length > j; j++) { + if (has(Base, key = keys[j]) && !has($Number, key)) { + dP($Number, key, gOPD(Base, key)); + } + } + $Number.prototype = proto; + proto.constructor = $Number; + __webpack_require__(18)(global, NUMBER, $Number); + } + + +/***/ }), +/* 87 */ +/***/ (function(module, exports, __webpack_require__) { + + var isObject = __webpack_require__(13); + var setPrototypeOf = __webpack_require__(72).set; + module.exports = function (that, target, C) { + var S = target.constructor; + var P; + if (S !== C && typeof S == 'function' && (P = S.prototype) !== C.prototype && isObject(P) && setPrototypeOf) { + setPrototypeOf(that, P); + } return that; + }; + + +/***/ }), +/* 88 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var toInteger = __webpack_require__(38); + var aNumberValue = __webpack_require__(89); + var repeat = __webpack_require__(90); + var $toFixed = 1.0.toFixed; + var floor = Math.floor; + var data = [0, 0, 0, 0, 0, 0]; + var ERROR = 'Number.toFixed: incorrect invocation!'; + var ZERO = '0'; + + var multiply = function (n, c) { + var i = -1; + var c2 = c; + while (++i < 6) { + c2 += n * data[i]; + data[i] = c2 % 1e7; + c2 = floor(c2 / 1e7); + } + }; + var divide = function (n) { + var i = 6; + var c = 0; + while (--i >= 0) { + c += data[i]; + data[i] = floor(c / n); + c = (c % n) * 1e7; + } + }; + var numToString = function () { + var i = 6; + var s = ''; + while (--i >= 0) { + if (s !== '' || i === 0 || data[i] !== 0) { + var t = String(data[i]); + s = s === '' ? t : s + repeat.call(ZERO, 7 - t.length) + t; + } + } return s; + }; + var pow = function (x, n, acc) { + return n === 0 ? acc : n % 2 === 1 ? pow(x, n - 1, acc * x) : pow(x * x, n / 2, acc); + }; + var log = function (x) { + var n = 0; + var x2 = x; + while (x2 >= 4096) { + n += 12; + x2 /= 4096; + } + while (x2 >= 2) { + n += 1; + x2 /= 2; + } return n; + }; + + $export($export.P + $export.F * (!!$toFixed && ( + 0.00008.toFixed(3) !== '0.000' || + 0.9.toFixed(0) !== '1' || + 1.255.toFixed(2) !== '1.25' || + 1000000000000000128.0.toFixed(0) !== '1000000000000000128' + ) || !__webpack_require__(7)(function () { + // V8 ~ Android 4.3- + $toFixed.call({}); + })), 'Number', { + toFixed: function toFixed(fractionDigits) { + var x = aNumberValue(this, ERROR); + var f = toInteger(fractionDigits); + var s = ''; + var m = ZERO; + var e, z, j, k; + if (f < 0 || f > 20) throw RangeError(ERROR); + // eslint-disable-next-line no-self-compare + if (x != x) return 'NaN'; + if (x <= -1e21 || x >= 1e21) return String(x); + if (x < 0) { + s = '-'; + x = -x; + } + if (x > 1e-21) { + e = log(x * pow(2, 69, 1)) - 69; + z = e < 0 ? x * pow(2, -e, 1) : x / pow(2, e, 1); + z *= 0x10000000000000; + e = 52 - e; + if (e > 0) { + multiply(0, z); + j = f; + while (j >= 7) { + multiply(1e7, 0); + j -= 7; + } + multiply(pow(10, j, 1), 0); + j = e - 1; + while (j >= 23) { + divide(1 << 23); + j -= 23; + } + divide(1 << j); + multiply(1, 1); + divide(2); + m = numToString(); + } else { + multiply(0, z); + multiply(1 << -e, 0); + m = numToString() + repeat.call(ZERO, f); + } + } + if (f > 0) { + k = m.length; + m = s + (k <= f ? '0.' + repeat.call(ZERO, f - k) + m : m.slice(0, k - f) + '.' + m.slice(k - f)); + } else { + m = s + m; + } return m; + } + }); + + +/***/ }), +/* 89 */ +/***/ (function(module, exports, __webpack_require__) { + + var cof = __webpack_require__(34); + module.exports = function (it, msg) { + if (typeof it != 'number' && cof(it) != 'Number') throw TypeError(msg); + return +it; + }; + + +/***/ }), +/* 90 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var toInteger = __webpack_require__(38); + var defined = __webpack_require__(35); + + module.exports = function repeat(count) { + var str = String(defined(this)); + var res = ''; + var n = toInteger(count); + if (n < 0 || n == Infinity) throw RangeError("Count can't be negative"); + for (;n > 0; (n >>>= 1) && (str += str)) if (n & 1) res += str; + return res; + }; + + +/***/ }), +/* 91 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var $fails = __webpack_require__(7); + var aNumberValue = __webpack_require__(89); + var $toPrecision = 1.0.toPrecision; + + $export($export.P + $export.F * ($fails(function () { + // IE7- + return $toPrecision.call(1, undefined) !== '1'; + }) || !$fails(function () { + // V8 ~ Android 4.3- + $toPrecision.call({}); + })), 'Number', { + toPrecision: function toPrecision(precision) { + var that = aNumberValue(this, 'Number#toPrecision: incorrect invocation!'); + return precision === undefined ? $toPrecision.call(that) : $toPrecision.call(that, precision); + } + }); + + +/***/ }), +/* 92 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.1.2.1 Number.EPSILON + var $export = __webpack_require__(8); + + $export($export.S, 'Number', { EPSILON: Math.pow(2, -52) }); + + +/***/ }), +/* 93 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.1.2.2 Number.isFinite(number) + var $export = __webpack_require__(8); + var _isFinite = __webpack_require__(4).isFinite; + + $export($export.S, 'Number', { + isFinite: function isFinite(it) { + return typeof it == 'number' && _isFinite(it); + } + }); + + +/***/ }), +/* 94 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.1.2.3 Number.isInteger(number) + var $export = __webpack_require__(8); + + $export($export.S, 'Number', { isInteger: __webpack_require__(95) }); + + +/***/ }), +/* 95 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.1.2.3 Number.isInteger(number) + var isObject = __webpack_require__(13); + var floor = Math.floor; + module.exports = function isInteger(it) { + return !isObject(it) && isFinite(it) && floor(it) === it; + }; + + +/***/ }), +/* 96 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.1.2.4 Number.isNaN(number) + var $export = __webpack_require__(8); + + $export($export.S, 'Number', { + isNaN: function isNaN(number) { + // eslint-disable-next-line no-self-compare + return number != number; + } + }); + + +/***/ }), +/* 97 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.1.2.5 Number.isSafeInteger(number) + var $export = __webpack_require__(8); + var isInteger = __webpack_require__(95); + var abs = Math.abs; + + $export($export.S, 'Number', { + isSafeInteger: function isSafeInteger(number) { + return isInteger(number) && abs(number) <= 0x1fffffffffffff; + } + }); + + +/***/ }), +/* 98 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.1.2.6 Number.MAX_SAFE_INTEGER + var $export = __webpack_require__(8); + + $export($export.S, 'Number', { MAX_SAFE_INTEGER: 0x1fffffffffffff }); + + +/***/ }), +/* 99 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.1.2.10 Number.MIN_SAFE_INTEGER + var $export = __webpack_require__(8); + + $export($export.S, 'Number', { MIN_SAFE_INTEGER: -0x1fffffffffffff }); + + +/***/ }), +/* 100 */ +/***/ (function(module, exports, __webpack_require__) { + + var $export = __webpack_require__(8); + var $parseFloat = __webpack_require__(85); + // 20.1.2.12 Number.parseFloat(string) + $export($export.S + $export.F * (Number.parseFloat != $parseFloat), 'Number', { parseFloat: $parseFloat }); + + +/***/ }), +/* 101 */ +/***/ (function(module, exports, __webpack_require__) { + + var $export = __webpack_require__(8); + var $parseInt = __webpack_require__(81); + // 20.1.2.13 Number.parseInt(string, radix) + $export($export.S + $export.F * (Number.parseInt != $parseInt), 'Number', { parseInt: $parseInt }); + + +/***/ }), +/* 102 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.2.2.3 Math.acosh(x) + var $export = __webpack_require__(8); + var log1p = __webpack_require__(103); + var sqrt = Math.sqrt; + var $acosh = Math.acosh; + + $export($export.S + $export.F * !($acosh + // V8 bug: https://code.google.com/p/v8/issues/detail?id=3509 + && Math.floor($acosh(Number.MAX_VALUE)) == 710 + // Tor Browser bug: Math.acosh(Infinity) -> NaN + && $acosh(Infinity) == Infinity + ), 'Math', { + acosh: function acosh(x) { + return (x = +x) < 1 ? NaN : x > 94906265.62425156 + ? Math.log(x) + Math.LN2 + : log1p(x - 1 + sqrt(x - 1) * sqrt(x + 1)); + } + }); + + +/***/ }), +/* 103 */ +/***/ (function(module, exports) { + + // 20.2.2.20 Math.log1p(x) + module.exports = Math.log1p || function log1p(x) { + return (x = +x) > -1e-8 && x < 1e-8 ? x - x * x / 2 : Math.log(1 + x); + }; + + +/***/ }), +/* 104 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.2.2.5 Math.asinh(x) + var $export = __webpack_require__(8); + var $asinh = Math.asinh; + + function asinh(x) { + return !isFinite(x = +x) || x == 0 ? x : x < 0 ? -asinh(-x) : Math.log(x + Math.sqrt(x * x + 1)); + } + + // Tor Browser bug: Math.asinh(0) -> -0 + $export($export.S + $export.F * !($asinh && 1 / $asinh(0) > 0), 'Math', { asinh: asinh }); + + +/***/ }), +/* 105 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.2.2.7 Math.atanh(x) + var $export = __webpack_require__(8); + var $atanh = Math.atanh; + + // Tor Browser bug: Math.atanh(-0) -> 0 + $export($export.S + $export.F * !($atanh && 1 / $atanh(-0) < 0), 'Math', { + atanh: function atanh(x) { + return (x = +x) == 0 ? x : Math.log((1 + x) / (1 - x)) / 2; + } + }); + + +/***/ }), +/* 106 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.2.2.9 Math.cbrt(x) + var $export = __webpack_require__(8); + var sign = __webpack_require__(107); + + $export($export.S, 'Math', { + cbrt: function cbrt(x) { + return sign(x = +x) * Math.pow(Math.abs(x), 1 / 3); + } + }); + + +/***/ }), +/* 107 */ +/***/ (function(module, exports) { + + // 20.2.2.28 Math.sign(x) + module.exports = Math.sign || function sign(x) { + // eslint-disable-next-line no-self-compare + return (x = +x) == 0 || x != x ? x : x < 0 ? -1 : 1; + }; + + +/***/ }), +/* 108 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.2.2.11 Math.clz32(x) + var $export = __webpack_require__(8); + + $export($export.S, 'Math', { + clz32: function clz32(x) { + return (x >>>= 0) ? 31 - Math.floor(Math.log(x + 0.5) * Math.LOG2E) : 32; + } + }); + + +/***/ }), +/* 109 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.2.2.12 Math.cosh(x) + var $export = __webpack_require__(8); + var exp = Math.exp; + + $export($export.S, 'Math', { + cosh: function cosh(x) { + return (exp(x = +x) + exp(-x)) / 2; + } + }); + + +/***/ }), +/* 110 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.2.2.14 Math.expm1(x) + var $export = __webpack_require__(8); + var $expm1 = __webpack_require__(111); + + $export($export.S + $export.F * ($expm1 != Math.expm1), 'Math', { expm1: $expm1 }); + + +/***/ }), +/* 111 */ +/***/ (function(module, exports) { + + // 20.2.2.14 Math.expm1(x) + var $expm1 = Math.expm1; + module.exports = (!$expm1 + // Old FF bug + || $expm1(10) > 22025.465794806719 || $expm1(10) < 22025.4657948067165168 + // Tor Browser bug + || $expm1(-2e-17) != -2e-17 + ) ? function expm1(x) { + return (x = +x) == 0 ? x : x > -1e-6 && x < 1e-6 ? x + x * x / 2 : Math.exp(x) - 1; + } : $expm1; + + +/***/ }), +/* 112 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.2.2.16 Math.fround(x) + var $export = __webpack_require__(8); + + $export($export.S, 'Math', { fround: __webpack_require__(113) }); + + +/***/ }), +/* 113 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.2.2.16 Math.fround(x) + var sign = __webpack_require__(107); + var pow = Math.pow; + var EPSILON = pow(2, -52); + var EPSILON32 = pow(2, -23); + var MAX32 = pow(2, 127) * (2 - EPSILON32); + var MIN32 = pow(2, -126); + + var roundTiesToEven = function (n) { + return n + 1 / EPSILON - 1 / EPSILON; + }; + + module.exports = Math.fround || function fround(x) { + var $abs = Math.abs(x); + var $sign = sign(x); + var a, result; + if ($abs < MIN32) return $sign * roundTiesToEven($abs / MIN32 / EPSILON32) * MIN32 * EPSILON32; + a = (1 + EPSILON32 / EPSILON) * $abs; + result = a - (a - $abs); + // eslint-disable-next-line no-self-compare + if (result > MAX32 || result != result) return $sign * Infinity; + return $sign * result; + }; + + +/***/ }), +/* 114 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.2.2.17 Math.hypot([value1[, value2[, … ]]]) + var $export = __webpack_require__(8); + var abs = Math.abs; + + $export($export.S, 'Math', { + hypot: function hypot(value1, value2) { // eslint-disable-line no-unused-vars + var sum = 0; + var i = 0; + var aLen = arguments.length; + var larg = 0; + var arg, div; + while (i < aLen) { + arg = abs(arguments[i++]); + if (larg < arg) { + div = larg / arg; + sum = sum * div * div + 1; + larg = arg; + } else if (arg > 0) { + div = arg / larg; + sum += div * div; + } else sum += arg; + } + return larg === Infinity ? Infinity : larg * Math.sqrt(sum); + } + }); + + +/***/ }), +/* 115 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.2.2.18 Math.imul(x, y) + var $export = __webpack_require__(8); + var $imul = Math.imul; + + // some WebKit versions fails with big numbers, some has wrong arity + $export($export.S + $export.F * __webpack_require__(7)(function () { + return $imul(0xffffffff, 5) != -5 || $imul.length != 2; + }), 'Math', { + imul: function imul(x, y) { + var UINT16 = 0xffff; + var xn = +x; + var yn = +y; + var xl = UINT16 & xn; + var yl = UINT16 & yn; + return 0 | xl * yl + ((UINT16 & xn >>> 16) * yl + xl * (UINT16 & yn >>> 16) << 16 >>> 0); + } + }); + + +/***/ }), +/* 116 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.2.2.21 Math.log10(x) + var $export = __webpack_require__(8); + + $export($export.S, 'Math', { + log10: function log10(x) { + return Math.log(x) * Math.LOG10E; + } + }); + + +/***/ }), +/* 117 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.2.2.20 Math.log1p(x) + var $export = __webpack_require__(8); + + $export($export.S, 'Math', { log1p: __webpack_require__(103) }); + + +/***/ }), +/* 118 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.2.2.22 Math.log2(x) + var $export = __webpack_require__(8); + + $export($export.S, 'Math', { + log2: function log2(x) { + return Math.log(x) / Math.LN2; + } + }); + + +/***/ }), +/* 119 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.2.2.28 Math.sign(x) + var $export = __webpack_require__(8); + + $export($export.S, 'Math', { sign: __webpack_require__(107) }); + + +/***/ }), +/* 120 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.2.2.30 Math.sinh(x) + var $export = __webpack_require__(8); + var expm1 = __webpack_require__(111); + var exp = Math.exp; + + // V8 near Chromium 38 has a problem with very small numbers + $export($export.S + $export.F * __webpack_require__(7)(function () { + return !Math.sinh(-2e-17) != -2e-17; + }), 'Math', { + sinh: function sinh(x) { + return Math.abs(x = +x) < 1 + ? (expm1(x) - expm1(-x)) / 2 + : (exp(x - 1) - exp(-x - 1)) * (Math.E / 2); + } + }); + + +/***/ }), +/* 121 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.2.2.33 Math.tanh(x) + var $export = __webpack_require__(8); + var expm1 = __webpack_require__(111); + var exp = Math.exp; + + $export($export.S, 'Math', { + tanh: function tanh(x) { + var a = expm1(x = +x); + var b = expm1(-x); + return a == Infinity ? 1 : b == Infinity ? -1 : (a - b) / (exp(x) + exp(-x)); + } + }); + + +/***/ }), +/* 122 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.2.2.34 Math.trunc(x) + var $export = __webpack_require__(8); + + $export($export.S, 'Math', { + trunc: function trunc(it) { + return (it > 0 ? Math.floor : Math.ceil)(it); + } + }); + + +/***/ }), +/* 123 */ +/***/ (function(module, exports, __webpack_require__) { + + var $export = __webpack_require__(8); + var toAbsoluteIndex = __webpack_require__(39); + var fromCharCode = String.fromCharCode; + var $fromCodePoint = String.fromCodePoint; + + // length should be 1, old FF problem + $export($export.S + $export.F * (!!$fromCodePoint && $fromCodePoint.length != 1), 'String', { + // 21.1.2.2 String.fromCodePoint(...codePoints) + fromCodePoint: function fromCodePoint(x) { // eslint-disable-line no-unused-vars + var res = []; + var aLen = arguments.length; + var i = 0; + var code; + while (aLen > i) { + code = +arguments[i++]; + if (toAbsoluteIndex(code, 0x10ffff) !== code) throw RangeError(code + ' is not a valid code point'); + res.push(code < 0x10000 + ? fromCharCode(code) + : fromCharCode(((code -= 0x10000) >> 10) + 0xd800, code % 0x400 + 0xdc00) + ); + } return res.join(''); + } + }); + + +/***/ }), +/* 124 */ +/***/ (function(module, exports, __webpack_require__) { + + var $export = __webpack_require__(8); + var toIObject = __webpack_require__(32); + var toLength = __webpack_require__(37); + + $export($export.S, 'String', { + // 21.1.2.4 String.raw(callSite, ...substitutions) + raw: function raw(callSite) { + var tpl = toIObject(callSite.raw); + var len = toLength(tpl.length); + var aLen = arguments.length; + var res = []; + var i = 0; + while (len > i) { + res.push(String(tpl[i++])); + if (i < aLen) res.push(String(arguments[i])); + } return res.join(''); + } + }); + + +/***/ }), +/* 125 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // 21.1.3.25 String.prototype.trim() + __webpack_require__(82)('trim', function ($trim) { + return function trim() { + return $trim(this, 3); + }; + }); + + +/***/ }), +/* 126 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $at = __webpack_require__(127)(true); + + // 21.1.3.27 String.prototype[@@iterator]() + __webpack_require__(128)(String, 'String', function (iterated) { + this._t = String(iterated); // target + this._i = 0; // next index + // 21.1.5.2.1 %StringIteratorPrototype%.next() + }, function () { + var O = this._t; + var index = this._i; + var point; + if (index >= O.length) return { value: undefined, done: true }; + point = $at(O, index); + this._i += point.length; + return { value: point, done: false }; + }); + + +/***/ }), +/* 127 */ +/***/ (function(module, exports, __webpack_require__) { + + var toInteger = __webpack_require__(38); + var defined = __webpack_require__(35); + // true -> String#at + // false -> String#codePointAt + module.exports = function (TO_STRING) { + return function (that, pos) { + var s = String(defined(that)); + var i = toInteger(pos); + var l = s.length; + var a, b; + if (i < 0 || i >= l) return TO_STRING ? '' : undefined; + a = s.charCodeAt(i); + return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff + ? TO_STRING ? s.charAt(i) : a + : TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000; + }; + }; + + +/***/ }), +/* 128 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var LIBRARY = __webpack_require__(24); + var $export = __webpack_require__(8); + var redefine = __webpack_require__(18); + var hide = __webpack_require__(10); + var Iterators = __webpack_require__(129); + var $iterCreate = __webpack_require__(130); + var setToStringTag = __webpack_require__(25); + var getPrototypeOf = __webpack_require__(58); + var ITERATOR = __webpack_require__(26)('iterator'); + var BUGGY = !([].keys && 'next' in [].keys()); // Safari has buggy iterators w/o `next` + var FF_ITERATOR = '@@iterator'; + var KEYS = 'keys'; + var VALUES = 'values'; + + var returnThis = function () { return this; }; + + module.exports = function (Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED) { + $iterCreate(Constructor, NAME, next); + var getMethod = function (kind) { + if (!BUGGY && kind in proto) return proto[kind]; + switch (kind) { + case KEYS: return function keys() { return new Constructor(this, kind); }; + case VALUES: return function values() { return new Constructor(this, kind); }; + } return function entries() { return new Constructor(this, kind); }; + }; + var TAG = NAME + ' Iterator'; + var DEF_VALUES = DEFAULT == VALUES; + var VALUES_BUG = false; + var proto = Base.prototype; + var $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT]; + var $default = $native || getMethod(DEFAULT); + var $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined; + var $anyNative = NAME == 'Array' ? proto.entries || $native : $native; + var methods, key, IteratorPrototype; + // Fix native + if ($anyNative) { + IteratorPrototype = getPrototypeOf($anyNative.call(new Base())); + if (IteratorPrototype !== Object.prototype && IteratorPrototype.next) { + // Set @@toStringTag to native iterators + setToStringTag(IteratorPrototype, TAG, true); + // fix for some old engines + if (!LIBRARY && typeof IteratorPrototype[ITERATOR] != 'function') hide(IteratorPrototype, ITERATOR, returnThis); + } + } + // fix Array#{values, @@iterator}.name in V8 / FF + if (DEF_VALUES && $native && $native.name !== VALUES) { + VALUES_BUG = true; + $default = function values() { return $native.call(this); }; + } + // Define iterator + if ((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])) { + hide(proto, ITERATOR, $default); + } + // Plug for library + Iterators[NAME] = $default; + Iterators[TAG] = returnThis; + if (DEFAULT) { + methods = { + values: DEF_VALUES ? $default : getMethod(VALUES), + keys: IS_SET ? $default : getMethod(KEYS), + entries: $entries + }; + if (FORCED) for (key in methods) { + if (!(key in proto)) redefine(proto, key, methods[key]); + } else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods); + } + return methods; + }; + + +/***/ }), +/* 129 */ +/***/ (function(module, exports) { + + module.exports = {}; + + +/***/ }), +/* 130 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var create = __webpack_require__(45); + var descriptor = __webpack_require__(17); + var setToStringTag = __webpack_require__(25); + var IteratorPrototype = {}; + + // 25.1.2.1.1 %IteratorPrototype%[@@iterator]() + __webpack_require__(10)(IteratorPrototype, __webpack_require__(26)('iterator'), function () { return this; }); + + module.exports = function (Constructor, NAME, next) { + Constructor.prototype = create(IteratorPrototype, { next: descriptor(1, next) }); + setToStringTag(Constructor, NAME + ' Iterator'); + }; + + +/***/ }), +/* 131 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var $at = __webpack_require__(127)(false); + $export($export.P, 'String', { + // 21.1.3.3 String.prototype.codePointAt(pos) + codePointAt: function codePointAt(pos) { + return $at(this, pos); + } + }); + + +/***/ }), +/* 132 */ +/***/ (function(module, exports, __webpack_require__) { + + // 21.1.3.6 String.prototype.endsWith(searchString [, endPosition]) + 'use strict'; + var $export = __webpack_require__(8); + var toLength = __webpack_require__(37); + var context = __webpack_require__(133); + var ENDS_WITH = 'endsWith'; + var $endsWith = ''[ENDS_WITH]; + + $export($export.P + $export.F * __webpack_require__(135)(ENDS_WITH), 'String', { + endsWith: function endsWith(searchString /* , endPosition = @length */) { + var that = context(this, searchString, ENDS_WITH); + var endPosition = arguments.length > 1 ? arguments[1] : undefined; + var len = toLength(that.length); + var end = endPosition === undefined ? len : Math.min(toLength(endPosition), len); + var search = String(searchString); + return $endsWith + ? $endsWith.call(that, search, end) + : that.slice(end - search.length, end) === search; + } + }); + + +/***/ }), +/* 133 */ +/***/ (function(module, exports, __webpack_require__) { + + // helper for String#{startsWith, endsWith, includes} + var isRegExp = __webpack_require__(134); + var defined = __webpack_require__(35); + + module.exports = function (that, searchString, NAME) { + if (isRegExp(searchString)) throw TypeError('String#' + NAME + " doesn't accept regex!"); + return String(defined(that)); + }; + + +/***/ }), +/* 134 */ +/***/ (function(module, exports, __webpack_require__) { + + // 7.2.8 IsRegExp(argument) + var isObject = __webpack_require__(13); + var cof = __webpack_require__(34); + var MATCH = __webpack_require__(26)('match'); + module.exports = function (it) { + var isRegExp; + return isObject(it) && ((isRegExp = it[MATCH]) !== undefined ? !!isRegExp : cof(it) == 'RegExp'); + }; + + +/***/ }), +/* 135 */ +/***/ (function(module, exports, __webpack_require__) { + + var MATCH = __webpack_require__(26)('match'); + module.exports = function (KEY) { + var re = /./; + try { + '/./'[KEY](re); + } catch (e) { + try { + re[MATCH] = false; + return !'/./'[KEY](re); + } catch (f) { /* empty */ } + } return true; + }; + + +/***/ }), +/* 136 */ +/***/ (function(module, exports, __webpack_require__) { + + // 21.1.3.7 String.prototype.includes(searchString, position = 0) + 'use strict'; + var $export = __webpack_require__(8); + var context = __webpack_require__(133); + var INCLUDES = 'includes'; + + $export($export.P + $export.F * __webpack_require__(135)(INCLUDES), 'String', { + includes: function includes(searchString /* , position = 0 */) { + return !!~context(this, searchString, INCLUDES) + .indexOf(searchString, arguments.length > 1 ? arguments[1] : undefined); + } + }); + + +/***/ }), +/* 137 */ +/***/ (function(module, exports, __webpack_require__) { + + var $export = __webpack_require__(8); + + $export($export.P, 'String', { + // 21.1.3.13 String.prototype.repeat(count) + repeat: __webpack_require__(90) + }); + + +/***/ }), +/* 138 */ +/***/ (function(module, exports, __webpack_require__) { + + // 21.1.3.18 String.prototype.startsWith(searchString [, position ]) + 'use strict'; + var $export = __webpack_require__(8); + var toLength = __webpack_require__(37); + var context = __webpack_require__(133); + var STARTS_WITH = 'startsWith'; + var $startsWith = ''[STARTS_WITH]; + + $export($export.P + $export.F * __webpack_require__(135)(STARTS_WITH), 'String', { + startsWith: function startsWith(searchString /* , position = 0 */) { + var that = context(this, searchString, STARTS_WITH); + var index = toLength(Math.min(arguments.length > 1 ? arguments[1] : undefined, that.length)); + var search = String(searchString); + return $startsWith + ? $startsWith.call(that, search, index) + : that.slice(index, index + search.length) === search; + } + }); + + +/***/ }), +/* 139 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // B.2.3.2 String.prototype.anchor(name) + __webpack_require__(140)('anchor', function (createHTML) { + return function anchor(name) { + return createHTML(this, 'a', 'name', name); + }; + }); + + +/***/ }), +/* 140 */ +/***/ (function(module, exports, __webpack_require__) { + + var $export = __webpack_require__(8); + var fails = __webpack_require__(7); + var defined = __webpack_require__(35); + var quot = /"/g; + // B.2.3.2.1 CreateHTML(string, tag, attribute, value) + var createHTML = function (string, tag, attribute, value) { + var S = String(defined(string)); + var p1 = '<' + tag; + if (attribute !== '') p1 += ' ' + attribute + '="' + String(value).replace(quot, '"') + '"'; + return p1 + '>' + S + ''; + }; + module.exports = function (NAME, exec) { + var O = {}; + O[NAME] = exec(createHTML); + $export($export.P + $export.F * fails(function () { + var test = ''[NAME]('"'); + return test !== test.toLowerCase() || test.split('"').length > 3; + }), 'String', O); + }; + + +/***/ }), +/* 141 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // B.2.3.3 String.prototype.big() + __webpack_require__(140)('big', function (createHTML) { + return function big() { + return createHTML(this, 'big', '', ''); + }; + }); + + +/***/ }), +/* 142 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // B.2.3.4 String.prototype.blink() + __webpack_require__(140)('blink', function (createHTML) { + return function blink() { + return createHTML(this, 'blink', '', ''); + }; + }); + + +/***/ }), +/* 143 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // B.2.3.5 String.prototype.bold() + __webpack_require__(140)('bold', function (createHTML) { + return function bold() { + return createHTML(this, 'b', '', ''); + }; + }); + + +/***/ }), +/* 144 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // B.2.3.6 String.prototype.fixed() + __webpack_require__(140)('fixed', function (createHTML) { + return function fixed() { + return createHTML(this, 'tt', '', ''); + }; + }); + + +/***/ }), +/* 145 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // B.2.3.7 String.prototype.fontcolor(color) + __webpack_require__(140)('fontcolor', function (createHTML) { + return function fontcolor(color) { + return createHTML(this, 'font', 'color', color); + }; + }); + + +/***/ }), +/* 146 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // B.2.3.8 String.prototype.fontsize(size) + __webpack_require__(140)('fontsize', function (createHTML) { + return function fontsize(size) { + return createHTML(this, 'font', 'size', size); + }; + }); + + +/***/ }), +/* 147 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // B.2.3.9 String.prototype.italics() + __webpack_require__(140)('italics', function (createHTML) { + return function italics() { + return createHTML(this, 'i', '', ''); + }; + }); + + +/***/ }), +/* 148 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // B.2.3.10 String.prototype.link(url) + __webpack_require__(140)('link', function (createHTML) { + return function link(url) { + return createHTML(this, 'a', 'href', url); + }; + }); + + +/***/ }), +/* 149 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // B.2.3.11 String.prototype.small() + __webpack_require__(140)('small', function (createHTML) { + return function small() { + return createHTML(this, 'small', '', ''); + }; + }); + + +/***/ }), +/* 150 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // B.2.3.12 String.prototype.strike() + __webpack_require__(140)('strike', function (createHTML) { + return function strike() { + return createHTML(this, 'strike', '', ''); + }; + }); + + +/***/ }), +/* 151 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // B.2.3.13 String.prototype.sub() + __webpack_require__(140)('sub', function (createHTML) { + return function sub() { + return createHTML(this, 'sub', '', ''); + }; + }); + + +/***/ }), +/* 152 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // B.2.3.14 String.prototype.sup() + __webpack_require__(140)('sup', function (createHTML) { + return function sup() { + return createHTML(this, 'sup', '', ''); + }; + }); + + +/***/ }), +/* 153 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.3.3.1 / 15.9.4.4 Date.now() + var $export = __webpack_require__(8); + + $export($export.S, 'Date', { now: function () { return new Date().getTime(); } }); + + +/***/ }), +/* 154 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var toObject = __webpack_require__(57); + var toPrimitive = __webpack_require__(16); + + $export($export.P + $export.F * __webpack_require__(7)(function () { + return new Date(NaN).toJSON() !== null + || Date.prototype.toJSON.call({ toISOString: function () { return 1; } }) !== 1; + }), 'Date', { + // eslint-disable-next-line no-unused-vars + toJSON: function toJSON(key) { + var O = toObject(this); + var pv = toPrimitive(O); + return typeof pv == 'number' && !isFinite(pv) ? null : O.toISOString(); + } + }); + + +/***/ }), +/* 155 */ +/***/ (function(module, exports, __webpack_require__) { + + // 20.3.4.36 / 15.9.5.43 Date.prototype.toISOString() + var $export = __webpack_require__(8); + var toISOString = __webpack_require__(156); + + // PhantomJS / old WebKit has a broken implementations + $export($export.P + $export.F * (Date.prototype.toISOString !== toISOString), 'Date', { + toISOString: toISOString + }); + + +/***/ }), +/* 156 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // 20.3.4.36 / 15.9.5.43 Date.prototype.toISOString() + var fails = __webpack_require__(7); + var getTime = Date.prototype.getTime; + var $toISOString = Date.prototype.toISOString; + + var lz = function (num) { + return num > 9 ? num : '0' + num; + }; + + // PhantomJS / old WebKit has a broken implementations + module.exports = (fails(function () { + return $toISOString.call(new Date(-5e13 - 1)) != '0385-07-25T07:06:39.999Z'; + }) || !fails(function () { + $toISOString.call(new Date(NaN)); + })) ? function toISOString() { + if (!isFinite(getTime.call(this))) throw RangeError('Invalid time value'); + var d = this; + var y = d.getUTCFullYear(); + var m = d.getUTCMilliseconds(); + var s = y < 0 ? '-' : y > 9999 ? '+' : ''; + return s + ('00000' + Math.abs(y)).slice(s ? -6 : -4) + + '-' + lz(d.getUTCMonth() + 1) + '-' + lz(d.getUTCDate()) + + 'T' + lz(d.getUTCHours()) + ':' + lz(d.getUTCMinutes()) + + ':' + lz(d.getUTCSeconds()) + '.' + (m > 99 ? m : '0' + lz(m)) + 'Z'; + } : $toISOString; + + +/***/ }), +/* 157 */ +/***/ (function(module, exports, __webpack_require__) { + + var DateProto = Date.prototype; + var INVALID_DATE = 'Invalid Date'; + var TO_STRING = 'toString'; + var $toString = DateProto[TO_STRING]; + var getTime = DateProto.getTime; + if (new Date(NaN) + '' != INVALID_DATE) { + __webpack_require__(18)(DateProto, TO_STRING, function toString() { + var value = getTime.call(this); + // eslint-disable-next-line no-self-compare + return value === value ? $toString.call(this) : INVALID_DATE; + }); + } + + +/***/ }), +/* 158 */ +/***/ (function(module, exports, __webpack_require__) { + + var TO_PRIMITIVE = __webpack_require__(26)('toPrimitive'); + var proto = Date.prototype; + + if (!(TO_PRIMITIVE in proto)) __webpack_require__(10)(proto, TO_PRIMITIVE, __webpack_require__(159)); + + +/***/ }), +/* 159 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var anObject = __webpack_require__(12); + var toPrimitive = __webpack_require__(16); + var NUMBER = 'number'; + + module.exports = function (hint) { + if (hint !== 'string' && hint !== NUMBER && hint !== 'default') throw TypeError('Incorrect hint'); + return toPrimitive(anObject(this), hint != NUMBER); + }; + + +/***/ }), +/* 160 */ +/***/ (function(module, exports, __webpack_require__) { + + // 22.1.2.2 / 15.4.3.2 Array.isArray(arg) + var $export = __webpack_require__(8); + + $export($export.S, 'Array', { isArray: __webpack_require__(44) }); + + +/***/ }), +/* 161 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var ctx = __webpack_require__(20); + var $export = __webpack_require__(8); + var toObject = __webpack_require__(57); + var call = __webpack_require__(162); + var isArrayIter = __webpack_require__(163); + var toLength = __webpack_require__(37); + var createProperty = __webpack_require__(164); + var getIterFn = __webpack_require__(165); + + $export($export.S + $export.F * !__webpack_require__(166)(function (iter) { Array.from(iter); }), 'Array', { + // 22.1.2.1 Array.from(arrayLike, mapfn = undefined, thisArg = undefined) + from: function from(arrayLike /* , mapfn = undefined, thisArg = undefined */) { + var O = toObject(arrayLike); + var C = typeof this == 'function' ? this : Array; + var aLen = arguments.length; + var mapfn = aLen > 1 ? arguments[1] : undefined; + var mapping = mapfn !== undefined; + var index = 0; + var iterFn = getIterFn(O); + var length, result, step, iterator; + if (mapping) mapfn = ctx(mapfn, aLen > 2 ? arguments[2] : undefined, 2); + // if object isn't iterable or it's array with default iterator - use simple case + if (iterFn != undefined && !(C == Array && isArrayIter(iterFn))) { + for (iterator = iterFn.call(O), result = new C(); !(step = iterator.next()).done; index++) { + createProperty(result, index, mapping ? call(iterator, mapfn, [step.value, index], true) : step.value); + } + } else { + length = toLength(O.length); + for (result = new C(length); length > index; index++) { + createProperty(result, index, mapping ? mapfn(O[index], index) : O[index]); + } + } + result.length = index; + return result; + } + }); + + +/***/ }), +/* 162 */ +/***/ (function(module, exports, __webpack_require__) { + + // call something on iterator step with safe closing on error + var anObject = __webpack_require__(12); + module.exports = function (iterator, fn, value, entries) { + try { + return entries ? fn(anObject(value)[0], value[1]) : fn(value); + // 7.4.6 IteratorClose(iterator, completion) + } catch (e) { + var ret = iterator['return']; + if (ret !== undefined) anObject(ret.call(iterator)); + throw e; + } + }; + + +/***/ }), +/* 163 */ +/***/ (function(module, exports, __webpack_require__) { + + // check on default Array iterator + var Iterators = __webpack_require__(129); + var ITERATOR = __webpack_require__(26)('iterator'); + var ArrayProto = Array.prototype; + + module.exports = function (it) { + return it !== undefined && (Iterators.Array === it || ArrayProto[ITERATOR] === it); + }; + + +/***/ }), +/* 164 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $defineProperty = __webpack_require__(11); + var createDesc = __webpack_require__(17); + + module.exports = function (object, index, value) { + if (index in object) $defineProperty.f(object, index, createDesc(0, value)); + else object[index] = value; + }; + + +/***/ }), +/* 165 */ +/***/ (function(module, exports, __webpack_require__) { + + var classof = __webpack_require__(74); + var ITERATOR = __webpack_require__(26)('iterator'); + var Iterators = __webpack_require__(129); + module.exports = __webpack_require__(9).getIteratorMethod = function (it) { + if (it != undefined) return it[ITERATOR] + || it['@@iterator'] + || Iterators[classof(it)]; + }; + + +/***/ }), +/* 166 */ +/***/ (function(module, exports, __webpack_require__) { + + var ITERATOR = __webpack_require__(26)('iterator'); + var SAFE_CLOSING = false; + + try { + var riter = [7][ITERATOR](); + riter['return'] = function () { SAFE_CLOSING = true; }; + // eslint-disable-next-line no-throw-literal + Array.from(riter, function () { throw 2; }); + } catch (e) { /* empty */ } + + module.exports = function (exec, skipClosing) { + if (!skipClosing && !SAFE_CLOSING) return false; + var safe = false; + try { + var arr = [7]; + var iter = arr[ITERATOR](); + iter.next = function () { return { done: safe = true }; }; + arr[ITERATOR] = function () { return iter; }; + exec(arr); + } catch (e) { /* empty */ } + return safe; + }; + + +/***/ }), +/* 167 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var createProperty = __webpack_require__(164); + + // WebKit Array.of isn't generic + $export($export.S + $export.F * __webpack_require__(7)(function () { + function F() { /* empty */ } + return !(Array.of.call(F) instanceof F); + }), 'Array', { + // 22.1.2.3 Array.of( ...items) + of: function of(/* ...args */) { + var index = 0; + var aLen = arguments.length; + var result = new (typeof this == 'function' ? this : Array)(aLen); + while (aLen > index) createProperty(result, index, arguments[index++]); + result.length = aLen; + return result; + } + }); + + +/***/ }), +/* 168 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // 22.1.3.13 Array.prototype.join(separator) + var $export = __webpack_require__(8); + var toIObject = __webpack_require__(32); + var arrayJoin = [].join; + + // fallback for not array-like strings + $export($export.P + $export.F * (__webpack_require__(33) != Object || !__webpack_require__(169)(arrayJoin)), 'Array', { + join: function join(separator) { + return arrayJoin.call(toIObject(this), separator === undefined ? ',' : separator); + } + }); + + +/***/ }), +/* 169 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var fails = __webpack_require__(7); + + module.exports = function (method, arg) { + return !!method && fails(function () { + // eslint-disable-next-line no-useless-call + arg ? method.call(null, function () { /* empty */ }, 1) : method.call(null); + }); + }; + + +/***/ }), +/* 170 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var html = __webpack_require__(47); + var cof = __webpack_require__(34); + var toAbsoluteIndex = __webpack_require__(39); + var toLength = __webpack_require__(37); + var arraySlice = [].slice; + + // fallback for not array-like ES3 strings and DOM objects + $export($export.P + $export.F * __webpack_require__(7)(function () { + if (html) arraySlice.call(html); + }), 'Array', { + slice: function slice(begin, end) { + var len = toLength(this.length); + var klass = cof(this); + end = end === undefined ? len : end; + if (klass == 'Array') return arraySlice.call(this, begin, end); + var start = toAbsoluteIndex(begin, len); + var upTo = toAbsoluteIndex(end, len); + var size = toLength(upTo - start); + var cloned = new Array(size); + var i = 0; + for (; i < size; i++) cloned[i] = klass == 'String' + ? this.charAt(start + i) + : this[start + i]; + return cloned; + } + }); + + +/***/ }), +/* 171 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var aFunction = __webpack_require__(21); + var toObject = __webpack_require__(57); + var fails = __webpack_require__(7); + var $sort = [].sort; + var test = [1, 2, 3]; + + $export($export.P + $export.F * (fails(function () { + // IE8- + test.sort(undefined); + }) || !fails(function () { + // V8 bug + test.sort(null); + // Old WebKit + }) || !__webpack_require__(169)($sort)), 'Array', { + // 22.1.3.25 Array.prototype.sort(comparefn) + sort: function sort(comparefn) { + return comparefn === undefined + ? $sort.call(toObject(this)) + : $sort.call(toObject(this), aFunction(comparefn)); + } + }); + + +/***/ }), +/* 172 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var $forEach = __webpack_require__(173)(0); + var STRICT = __webpack_require__(169)([].forEach, true); + + $export($export.P + $export.F * !STRICT, 'Array', { + // 22.1.3.10 / 15.4.4.18 Array.prototype.forEach(callbackfn [, thisArg]) + forEach: function forEach(callbackfn /* , thisArg */) { + return $forEach(this, callbackfn, arguments[1]); + } + }); + + +/***/ }), +/* 173 */ +/***/ (function(module, exports, __webpack_require__) { + + // 0 -> Array#forEach + // 1 -> Array#map + // 2 -> Array#filter + // 3 -> Array#some + // 4 -> Array#every + // 5 -> Array#find + // 6 -> Array#findIndex + var ctx = __webpack_require__(20); + var IObject = __webpack_require__(33); + var toObject = __webpack_require__(57); + var toLength = __webpack_require__(37); + var asc = __webpack_require__(174); + module.exports = function (TYPE, $create) { + var IS_MAP = TYPE == 1; + var IS_FILTER = TYPE == 2; + var IS_SOME = TYPE == 3; + var IS_EVERY = TYPE == 4; + var IS_FIND_INDEX = TYPE == 6; + var NO_HOLES = TYPE == 5 || IS_FIND_INDEX; + var create = $create || asc; + return function ($this, callbackfn, that) { + var O = toObject($this); + var self = IObject(O); + var f = ctx(callbackfn, that, 3); + var length = toLength(self.length); + var index = 0; + var result = IS_MAP ? create($this, length) : IS_FILTER ? create($this, 0) : undefined; + var val, res; + for (;length > index; index++) if (NO_HOLES || index in self) { + val = self[index]; + res = f(val, index, O); + if (TYPE) { + if (IS_MAP) result[index] = res; // map + else if (res) switch (TYPE) { + case 3: return true; // some + case 5: return val; // find + case 6: return index; // findIndex + case 2: result.push(val); // filter + } else if (IS_EVERY) return false; // every + } + } + return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : result; + }; + }; + + +/***/ }), +/* 174 */ +/***/ (function(module, exports, __webpack_require__) { + + // 9.4.2.3 ArraySpeciesCreate(originalArray, length) + var speciesConstructor = __webpack_require__(175); + + module.exports = function (original, length) { + return new (speciesConstructor(original))(length); + }; + + +/***/ }), +/* 175 */ +/***/ (function(module, exports, __webpack_require__) { + + var isObject = __webpack_require__(13); + var isArray = __webpack_require__(44); + var SPECIES = __webpack_require__(26)('species'); + + module.exports = function (original) { + var C; + if (isArray(original)) { + C = original.constructor; + // cross-realm fallback + if (typeof C == 'function' && (C === Array || isArray(C.prototype))) C = undefined; + if (isObject(C)) { + C = C[SPECIES]; + if (C === null) C = undefined; + } + } return C === undefined ? Array : C; + }; + + +/***/ }), +/* 176 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var $map = __webpack_require__(173)(1); + + $export($export.P + $export.F * !__webpack_require__(169)([].map, true), 'Array', { + // 22.1.3.15 / 15.4.4.19 Array.prototype.map(callbackfn [, thisArg]) + map: function map(callbackfn /* , thisArg */) { + return $map(this, callbackfn, arguments[1]); + } + }); + + +/***/ }), +/* 177 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var $filter = __webpack_require__(173)(2); + + $export($export.P + $export.F * !__webpack_require__(169)([].filter, true), 'Array', { + // 22.1.3.7 / 15.4.4.20 Array.prototype.filter(callbackfn [, thisArg]) + filter: function filter(callbackfn /* , thisArg */) { + return $filter(this, callbackfn, arguments[1]); + } + }); + + +/***/ }), +/* 178 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var $some = __webpack_require__(173)(3); + + $export($export.P + $export.F * !__webpack_require__(169)([].some, true), 'Array', { + // 22.1.3.23 / 15.4.4.17 Array.prototype.some(callbackfn [, thisArg]) + some: function some(callbackfn /* , thisArg */) { + return $some(this, callbackfn, arguments[1]); + } + }); + + +/***/ }), +/* 179 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var $every = __webpack_require__(173)(4); + + $export($export.P + $export.F * !__webpack_require__(169)([].every, true), 'Array', { + // 22.1.3.5 / 15.4.4.16 Array.prototype.every(callbackfn [, thisArg]) + every: function every(callbackfn /* , thisArg */) { + return $every(this, callbackfn, arguments[1]); + } + }); + + +/***/ }), +/* 180 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var $reduce = __webpack_require__(181); + + $export($export.P + $export.F * !__webpack_require__(169)([].reduce, true), 'Array', { + // 22.1.3.18 / 15.4.4.21 Array.prototype.reduce(callbackfn [, initialValue]) + reduce: function reduce(callbackfn /* , initialValue */) { + return $reduce(this, callbackfn, arguments.length, arguments[1], false); + } + }); + + +/***/ }), +/* 181 */ +/***/ (function(module, exports, __webpack_require__) { + + var aFunction = __webpack_require__(21); + var toObject = __webpack_require__(57); + var IObject = __webpack_require__(33); + var toLength = __webpack_require__(37); + + module.exports = function (that, callbackfn, aLen, memo, isRight) { + aFunction(callbackfn); + var O = toObject(that); + var self = IObject(O); + var length = toLength(O.length); + var index = isRight ? length - 1 : 0; + var i = isRight ? -1 : 1; + if (aLen < 2) for (;;) { + if (index in self) { + memo = self[index]; + index += i; + break; + } + index += i; + if (isRight ? index < 0 : length <= index) { + throw TypeError('Reduce of empty array with no initial value'); + } + } + for (;isRight ? index >= 0 : length > index; index += i) if (index in self) { + memo = callbackfn(memo, self[index], index, O); + } + return memo; + }; + + +/***/ }), +/* 182 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var $reduce = __webpack_require__(181); + + $export($export.P + $export.F * !__webpack_require__(169)([].reduceRight, true), 'Array', { + // 22.1.3.19 / 15.4.4.22 Array.prototype.reduceRight(callbackfn [, initialValue]) + reduceRight: function reduceRight(callbackfn /* , initialValue */) { + return $reduce(this, callbackfn, arguments.length, arguments[1], true); + } + }); + + +/***/ }), +/* 183 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var $indexOf = __webpack_require__(36)(false); + var $native = [].indexOf; + var NEGATIVE_ZERO = !!$native && 1 / [1].indexOf(1, -0) < 0; + + $export($export.P + $export.F * (NEGATIVE_ZERO || !__webpack_require__(169)($native)), 'Array', { + // 22.1.3.11 / 15.4.4.14 Array.prototype.indexOf(searchElement [, fromIndex]) + indexOf: function indexOf(searchElement /* , fromIndex = 0 */) { + return NEGATIVE_ZERO + // convert -0 to +0 + ? $native.apply(this, arguments) || 0 + : $indexOf(this, searchElement, arguments[1]); + } + }); + + +/***/ }), +/* 184 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var toIObject = __webpack_require__(32); + var toInteger = __webpack_require__(38); + var toLength = __webpack_require__(37); + var $native = [].lastIndexOf; + var NEGATIVE_ZERO = !!$native && 1 / [1].lastIndexOf(1, -0) < 0; + + $export($export.P + $export.F * (NEGATIVE_ZERO || !__webpack_require__(169)($native)), 'Array', { + // 22.1.3.14 / 15.4.4.15 Array.prototype.lastIndexOf(searchElement [, fromIndex]) + lastIndexOf: function lastIndexOf(searchElement /* , fromIndex = @[*-1] */) { + // convert -0 to +0 + if (NEGATIVE_ZERO) return $native.apply(this, arguments) || 0; + var O = toIObject(this); + var length = toLength(O.length); + var index = length - 1; + if (arguments.length > 1) index = Math.min(index, toInteger(arguments[1])); + if (index < 0) index = length + index; + for (;index >= 0; index--) if (index in O) if (O[index] === searchElement) return index || 0; + return -1; + } + }); + + +/***/ }), +/* 185 */ +/***/ (function(module, exports, __webpack_require__) { + + // 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length) + var $export = __webpack_require__(8); + + $export($export.P, 'Array', { copyWithin: __webpack_require__(186) }); + + __webpack_require__(187)('copyWithin'); + + +/***/ }), +/* 186 */ +/***/ (function(module, exports, __webpack_require__) { + + // 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length) + 'use strict'; + var toObject = __webpack_require__(57); + var toAbsoluteIndex = __webpack_require__(39); + var toLength = __webpack_require__(37); + + module.exports = [].copyWithin || function copyWithin(target /* = 0 */, start /* = 0, end = @length */) { + var O = toObject(this); + var len = toLength(O.length); + var to = toAbsoluteIndex(target, len); + var from = toAbsoluteIndex(start, len); + var end = arguments.length > 2 ? arguments[2] : undefined; + var count = Math.min((end === undefined ? len : toAbsoluteIndex(end, len)) - from, len - to); + var inc = 1; + if (from < to && to < from + count) { + inc = -1; + from += count - 1; + to += count - 1; + } + while (count-- > 0) { + if (from in O) O[to] = O[from]; + else delete O[to]; + to += inc; + from += inc; + } return O; + }; + + +/***/ }), +/* 187 */ +/***/ (function(module, exports, __webpack_require__) { + + // 22.1.3.31 Array.prototype[@@unscopables] + var UNSCOPABLES = __webpack_require__(26)('unscopables'); + var ArrayProto = Array.prototype; + if (ArrayProto[UNSCOPABLES] == undefined) __webpack_require__(10)(ArrayProto, UNSCOPABLES, {}); + module.exports = function (key) { + ArrayProto[UNSCOPABLES][key] = true; + }; + + +/***/ }), +/* 188 */ +/***/ (function(module, exports, __webpack_require__) { + + // 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length) + var $export = __webpack_require__(8); + + $export($export.P, 'Array', { fill: __webpack_require__(189) }); + + __webpack_require__(187)('fill'); + + +/***/ }), +/* 189 */ +/***/ (function(module, exports, __webpack_require__) { + + // 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length) + 'use strict'; + var toObject = __webpack_require__(57); + var toAbsoluteIndex = __webpack_require__(39); + var toLength = __webpack_require__(37); + module.exports = function fill(value /* , start = 0, end = @length */) { + var O = toObject(this); + var length = toLength(O.length); + var aLen = arguments.length; + var index = toAbsoluteIndex(aLen > 1 ? arguments[1] : undefined, length); + var end = aLen > 2 ? arguments[2] : undefined; + var endPos = end === undefined ? length : toAbsoluteIndex(end, length); + while (endPos > index) O[index++] = value; + return O; + }; + + +/***/ }), +/* 190 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // 22.1.3.8 Array.prototype.find(predicate, thisArg = undefined) + var $export = __webpack_require__(8); + var $find = __webpack_require__(173)(5); + var KEY = 'find'; + var forced = true; + // Shouldn't skip holes + if (KEY in []) Array(1)[KEY](function () { forced = false; }); + $export($export.P + $export.F * forced, 'Array', { + find: function find(callbackfn /* , that = undefined */) { + return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); + } + }); + __webpack_require__(187)(KEY); + + +/***/ }), +/* 191 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // 22.1.3.9 Array.prototype.findIndex(predicate, thisArg = undefined) + var $export = __webpack_require__(8); + var $find = __webpack_require__(173)(6); + var KEY = 'findIndex'; + var forced = true; + // Shouldn't skip holes + if (KEY in []) Array(1)[KEY](function () { forced = false; }); + $export($export.P + $export.F * forced, 'Array', { + findIndex: function findIndex(callbackfn /* , that = undefined */) { + return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); + } + }); + __webpack_require__(187)(KEY); + + +/***/ }), +/* 192 */ +/***/ (function(module, exports, __webpack_require__) { + + __webpack_require__(193)('Array'); + + +/***/ }), +/* 193 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var global = __webpack_require__(4); + var dP = __webpack_require__(11); + var DESCRIPTORS = __webpack_require__(6); + var SPECIES = __webpack_require__(26)('species'); + + module.exports = function (KEY) { + var C = global[KEY]; + if (DESCRIPTORS && C && !C[SPECIES]) dP.f(C, SPECIES, { + configurable: true, + get: function () { return this; } + }); + }; + + +/***/ }), +/* 194 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var addToUnscopables = __webpack_require__(187); + var step = __webpack_require__(195); + var Iterators = __webpack_require__(129); + var toIObject = __webpack_require__(32); + + // 22.1.3.4 Array.prototype.entries() + // 22.1.3.13 Array.prototype.keys() + // 22.1.3.29 Array.prototype.values() + // 22.1.3.30 Array.prototype[@@iterator]() + module.exports = __webpack_require__(128)(Array, 'Array', function (iterated, kind) { + this._t = toIObject(iterated); // target + this._i = 0; // next index + this._k = kind; // kind + // 22.1.5.2.1 %ArrayIteratorPrototype%.next() + }, function () { + var O = this._t; + var kind = this._k; + var index = this._i++; + if (!O || index >= O.length) { + this._t = undefined; + return step(1); + } + if (kind == 'keys') return step(0, index); + if (kind == 'values') return step(0, O[index]); + return step(0, [index, O[index]]); + }, 'values'); + + // argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7) + Iterators.Arguments = Iterators.Array; + + addToUnscopables('keys'); + addToUnscopables('values'); + addToUnscopables('entries'); + + +/***/ }), +/* 195 */ +/***/ (function(module, exports) { + + module.exports = function (done, value) { + return { value: value, done: !!done }; + }; + + +/***/ }), +/* 196 */ +/***/ (function(module, exports, __webpack_require__) { + + var global = __webpack_require__(4); + var inheritIfRequired = __webpack_require__(87); + var dP = __webpack_require__(11).f; + var gOPN = __webpack_require__(49).f; + var isRegExp = __webpack_require__(134); + var $flags = __webpack_require__(197); + var $RegExp = global.RegExp; + var Base = $RegExp; + var proto = $RegExp.prototype; + var re1 = /a/g; + var re2 = /a/g; + // "new" creates a new object, old webkit buggy here + var CORRECT_NEW = new $RegExp(re1) !== re1; + + if (__webpack_require__(6) && (!CORRECT_NEW || __webpack_require__(7)(function () { + re2[__webpack_require__(26)('match')] = false; + // RegExp constructor can alter flags and IsRegExp works correct with @@match + return $RegExp(re1) != re1 || $RegExp(re2) == re2 || $RegExp(re1, 'i') != '/a/i'; + }))) { + $RegExp = function RegExp(p, f) { + var tiRE = this instanceof $RegExp; + var piRE = isRegExp(p); + var fiU = f === undefined; + return !tiRE && piRE && p.constructor === $RegExp && fiU ? p + : inheritIfRequired(CORRECT_NEW + ? new Base(piRE && !fiU ? p.source : p, f) + : Base((piRE = p instanceof $RegExp) ? p.source : p, piRE && fiU ? $flags.call(p) : f) + , tiRE ? this : proto, $RegExp); + }; + var proxy = function (key) { + key in $RegExp || dP($RegExp, key, { + configurable: true, + get: function () { return Base[key]; }, + set: function (it) { Base[key] = it; } + }); + }; + for (var keys = gOPN(Base), i = 0; keys.length > i;) proxy(keys[i++]); + proto.constructor = $RegExp; + $RegExp.prototype = proto; + __webpack_require__(18)(global, 'RegExp', $RegExp); + } + + __webpack_require__(193)('RegExp'); + + +/***/ }), +/* 197 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // 21.2.5.3 get RegExp.prototype.flags + var anObject = __webpack_require__(12); + module.exports = function () { + var that = anObject(this); + var result = ''; + if (that.global) result += 'g'; + if (that.ignoreCase) result += 'i'; + if (that.multiline) result += 'm'; + if (that.unicode) result += 'u'; + if (that.sticky) result += 'y'; + return result; + }; + + +/***/ }), +/* 198 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + __webpack_require__(199); + var anObject = __webpack_require__(12); + var $flags = __webpack_require__(197); + var DESCRIPTORS = __webpack_require__(6); + var TO_STRING = 'toString'; + var $toString = /./[TO_STRING]; + + var define = function (fn) { + __webpack_require__(18)(RegExp.prototype, TO_STRING, fn, true); + }; + + // 21.2.5.14 RegExp.prototype.toString() + if (__webpack_require__(7)(function () { return $toString.call({ source: 'a', flags: 'b' }) != '/a/b'; })) { + define(function toString() { + var R = anObject(this); + return '/'.concat(R.source, '/', + 'flags' in R ? R.flags : !DESCRIPTORS && R instanceof RegExp ? $flags.call(R) : undefined); + }); + // FF44- RegExp#toString has a wrong name + } else if ($toString.name != TO_STRING) { + define(function toString() { + return $toString.call(this); + }); + } + + +/***/ }), +/* 199 */ +/***/ (function(module, exports, __webpack_require__) { + + // 21.2.5.3 get RegExp.prototype.flags() + if (__webpack_require__(6) && /./g.flags != 'g') __webpack_require__(11).f(RegExp.prototype, 'flags', { + configurable: true, + get: __webpack_require__(197) + }); + + +/***/ }), +/* 200 */ +/***/ (function(module, exports, __webpack_require__) { + + // @@match logic + __webpack_require__(201)('match', 1, function (defined, MATCH, $match) { + // 21.1.3.11 String.prototype.match(regexp) + return [function match(regexp) { + 'use strict'; + var O = defined(this); + var fn = regexp == undefined ? undefined : regexp[MATCH]; + return fn !== undefined ? fn.call(regexp, O) : new RegExp(regexp)[MATCH](String(O)); + }, $match]; + }); + + +/***/ }), +/* 201 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var hide = __webpack_require__(10); + var redefine = __webpack_require__(18); + var fails = __webpack_require__(7); + var defined = __webpack_require__(35); + var wks = __webpack_require__(26); + + module.exports = function (KEY, length, exec) { + var SYMBOL = wks(KEY); + var fns = exec(defined, SYMBOL, ''[KEY]); + var strfn = fns[0]; + var rxfn = fns[1]; + if (fails(function () { + var O = {}; + O[SYMBOL] = function () { return 7; }; + return ''[KEY](O) != 7; + })) { + redefine(String.prototype, KEY, strfn); + hide(RegExp.prototype, SYMBOL, length == 2 + // 21.2.5.8 RegExp.prototype[@@replace](string, replaceValue) + // 21.2.5.11 RegExp.prototype[@@split](string, limit) + ? function (string, arg) { return rxfn.call(string, this, arg); } + // 21.2.5.6 RegExp.prototype[@@match](string) + // 21.2.5.9 RegExp.prototype[@@search](string) + : function (string) { return rxfn.call(string, this); } + ); + } + }; + + +/***/ }), +/* 202 */ +/***/ (function(module, exports, __webpack_require__) { + + // @@replace logic + __webpack_require__(201)('replace', 2, function (defined, REPLACE, $replace) { + // 21.1.3.14 String.prototype.replace(searchValue, replaceValue) + return [function replace(searchValue, replaceValue) { + 'use strict'; + var O = defined(this); + var fn = searchValue == undefined ? undefined : searchValue[REPLACE]; + return fn !== undefined + ? fn.call(searchValue, O, replaceValue) + : $replace.call(String(O), searchValue, replaceValue); + }, $replace]; + }); + + +/***/ }), +/* 203 */ +/***/ (function(module, exports, __webpack_require__) { + + // @@search logic + __webpack_require__(201)('search', 1, function (defined, SEARCH, $search) { + // 21.1.3.15 String.prototype.search(regexp) + return [function search(regexp) { + 'use strict'; + var O = defined(this); + var fn = regexp == undefined ? undefined : regexp[SEARCH]; + return fn !== undefined ? fn.call(regexp, O) : new RegExp(regexp)[SEARCH](String(O)); + }, $search]; + }); + + +/***/ }), +/* 204 */ +/***/ (function(module, exports, __webpack_require__) { + + // @@split logic + __webpack_require__(201)('split', 2, function (defined, SPLIT, $split) { + 'use strict'; + var isRegExp = __webpack_require__(134); + var _split = $split; + var $push = [].push; + var $SPLIT = 'split'; + var LENGTH = 'length'; + var LAST_INDEX = 'lastIndex'; + if ( + 'abbc'[$SPLIT](/(b)*/)[1] == 'c' || + 'test'[$SPLIT](/(?:)/, -1)[LENGTH] != 4 || + 'ab'[$SPLIT](/(?:ab)*/)[LENGTH] != 2 || + '.'[$SPLIT](/(.?)(.?)/)[LENGTH] != 4 || + '.'[$SPLIT](/()()/)[LENGTH] > 1 || + ''[$SPLIT](/.?/)[LENGTH] + ) { + var NPCG = /()??/.exec('')[1] === undefined; // nonparticipating capturing group + // based on es5-shim implementation, need to rework it + $split = function (separator, limit) { + var string = String(this); + if (separator === undefined && limit === 0) return []; + // If `separator` is not a regex, use native split + if (!isRegExp(separator)) return _split.call(string, separator, limit); + var output = []; + var flags = (separator.ignoreCase ? 'i' : '') + + (separator.multiline ? 'm' : '') + + (separator.unicode ? 'u' : '') + + (separator.sticky ? 'y' : ''); + var lastLastIndex = 0; + var splitLimit = limit === undefined ? 4294967295 : limit >>> 0; + // Make `global` and avoid `lastIndex` issues by working with a copy + var separatorCopy = new RegExp(separator.source, flags + 'g'); + var separator2, match, lastIndex, lastLength, i; + // Doesn't need flags gy, but they don't hurt + if (!NPCG) separator2 = new RegExp('^' + separatorCopy.source + '$(?!\\s)', flags); + while (match = separatorCopy.exec(string)) { + // `separatorCopy.lastIndex` is not reliable cross-browser + lastIndex = match.index + match[0][LENGTH]; + if (lastIndex > lastLastIndex) { + output.push(string.slice(lastLastIndex, match.index)); + // Fix browsers whose `exec` methods don't consistently return `undefined` for NPCG + // eslint-disable-next-line no-loop-func + if (!NPCG && match[LENGTH] > 1) match[0].replace(separator2, function () { + for (i = 1; i < arguments[LENGTH] - 2; i++) if (arguments[i] === undefined) match[i] = undefined; + }); + if (match[LENGTH] > 1 && match.index < string[LENGTH]) $push.apply(output, match.slice(1)); + lastLength = match[0][LENGTH]; + lastLastIndex = lastIndex; + if (output[LENGTH] >= splitLimit) break; + } + if (separatorCopy[LAST_INDEX] === match.index) separatorCopy[LAST_INDEX]++; // Avoid an infinite loop + } + if (lastLastIndex === string[LENGTH]) { + if (lastLength || !separatorCopy.test('')) output.push(''); + } else output.push(string.slice(lastLastIndex)); + return output[LENGTH] > splitLimit ? output.slice(0, splitLimit) : output; + }; + // Chakra, V8 + } else if ('0'[$SPLIT](undefined, 0)[LENGTH]) { + $split = function (separator, limit) { + return separator === undefined && limit === 0 ? [] : _split.call(this, separator, limit); + }; + } + // 21.1.3.17 String.prototype.split(separator, limit) + return [function split(separator, limit) { + var O = defined(this); + var fn = separator == undefined ? undefined : separator[SPLIT]; + return fn !== undefined ? fn.call(separator, O, limit) : $split.call(String(O), separator, limit); + }, $split]; + }); + + +/***/ }), +/* 205 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var LIBRARY = __webpack_require__(24); + var global = __webpack_require__(4); + var ctx = __webpack_require__(20); + var classof = __webpack_require__(74); + var $export = __webpack_require__(8); + var isObject = __webpack_require__(13); + var aFunction = __webpack_require__(21); + var anInstance = __webpack_require__(206); + var forOf = __webpack_require__(207); + var speciesConstructor = __webpack_require__(208); + var task = __webpack_require__(209).set; + var microtask = __webpack_require__(210)(); + var newPromiseCapabilityModule = __webpack_require__(211); + var perform = __webpack_require__(212); + var userAgent = __webpack_require__(213); + var promiseResolve = __webpack_require__(214); + var PROMISE = 'Promise'; + var TypeError = global.TypeError; + var process = global.process; + var versions = process && process.versions; + var v8 = versions && versions.v8 || ''; + var $Promise = global[PROMISE]; + var isNode = classof(process) == 'process'; + var empty = function () { /* empty */ }; + var Internal, newGenericPromiseCapability, OwnPromiseCapability, Wrapper; + var newPromiseCapability = newGenericPromiseCapability = newPromiseCapabilityModule.f; + + var USE_NATIVE = !!function () { + try { + // correct subclassing with @@species support + var promise = $Promise.resolve(1); + var FakePromise = (promise.constructor = {})[__webpack_require__(26)('species')] = function (exec) { + exec(empty, empty); + }; + // unhandled rejections tracking support, NodeJS Promise without it fails @@species test + return (isNode || typeof PromiseRejectionEvent == 'function') + && promise.then(empty) instanceof FakePromise + // v8 6.6 (Node 10 and Chrome 66) have a bug with resolving custom thenables + // https://bugs.chromium.org/p/chromium/issues/detail?id=830565 + // we can't detect it synchronously, so just check versions + && v8.indexOf('6.6') !== 0 + && userAgent.indexOf('Chrome/66') === -1; + } catch (e) { /* empty */ } + }(); + + // helpers + var isThenable = function (it) { + var then; + return isObject(it) && typeof (then = it.then) == 'function' ? then : false; + }; + var notify = function (promise, isReject) { + if (promise._n) return; + promise._n = true; + var chain = promise._c; + microtask(function () { + var value = promise._v; + var ok = promise._s == 1; + var i = 0; + var run = function (reaction) { + var handler = ok ? reaction.ok : reaction.fail; + var resolve = reaction.resolve; + var reject = reaction.reject; + var domain = reaction.domain; + var result, then, exited; + try { + if (handler) { + if (!ok) { + if (promise._h == 2) onHandleUnhandled(promise); + promise._h = 1; + } + if (handler === true) result = value; + else { + if (domain) domain.enter(); + result = handler(value); // may throw + if (domain) { + domain.exit(); + exited = true; + } + } + if (result === reaction.promise) { + reject(TypeError('Promise-chain cycle')); + } else if (then = isThenable(result)) { + then.call(result, resolve, reject); + } else resolve(result); + } else reject(value); + } catch (e) { + if (domain && !exited) domain.exit(); + reject(e); + } + }; + while (chain.length > i) run(chain[i++]); // variable length - can't use forEach + promise._c = []; + promise._n = false; + if (isReject && !promise._h) onUnhandled(promise); + }); + }; + var onUnhandled = function (promise) { + task.call(global, function () { + var value = promise._v; + var unhandled = isUnhandled(promise); + var result, handler, console; + if (unhandled) { + result = perform(function () { + if (isNode) { + process.emit('unhandledRejection', value, promise); + } else if (handler = global.onunhandledrejection) { + handler({ promise: promise, reason: value }); + } else if ((console = global.console) && console.error) { + console.error('Unhandled promise rejection', value); + } + }); + // Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should + promise._h = isNode || isUnhandled(promise) ? 2 : 1; + } promise._a = undefined; + if (unhandled && result.e) throw result.v; + }); + }; + var isUnhandled = function (promise) { + return promise._h !== 1 && (promise._a || promise._c).length === 0; + }; + var onHandleUnhandled = function (promise) { + task.call(global, function () { + var handler; + if (isNode) { + process.emit('rejectionHandled', promise); + } else if (handler = global.onrejectionhandled) { + handler({ promise: promise, reason: promise._v }); + } + }); + }; + var $reject = function (value) { + var promise = this; + if (promise._d) return; + promise._d = true; + promise = promise._w || promise; // unwrap + promise._v = value; + promise._s = 2; + if (!promise._a) promise._a = promise._c.slice(); + notify(promise, true); + }; + var $resolve = function (value) { + var promise = this; + var then; + if (promise._d) return; + promise._d = true; + promise = promise._w || promise; // unwrap + try { + if (promise === value) throw TypeError("Promise can't be resolved itself"); + if (then = isThenable(value)) { + microtask(function () { + var wrapper = { _w: promise, _d: false }; // wrap + try { + then.call(value, ctx($resolve, wrapper, 1), ctx($reject, wrapper, 1)); + } catch (e) { + $reject.call(wrapper, e); + } + }); + } else { + promise._v = value; + promise._s = 1; + notify(promise, false); + } + } catch (e) { + $reject.call({ _w: promise, _d: false }, e); // wrap + } + }; + + // constructor polyfill + if (!USE_NATIVE) { + // 25.4.3.1 Promise(executor) + $Promise = function Promise(executor) { + anInstance(this, $Promise, PROMISE, '_h'); + aFunction(executor); + Internal.call(this); + try { + executor(ctx($resolve, this, 1), ctx($reject, this, 1)); + } catch (err) { + $reject.call(this, err); + } + }; + // eslint-disable-next-line no-unused-vars + Internal = function Promise(executor) { + this._c = []; // <- awaiting reactions + this._a = undefined; // <- checked in isUnhandled reactions + this._s = 0; // <- state + this._d = false; // <- done + this._v = undefined; // <- value + this._h = 0; // <- rejection state, 0 - default, 1 - handled, 2 - unhandled + this._n = false; // <- notify + }; + Internal.prototype = __webpack_require__(215)($Promise.prototype, { + // 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected) + then: function then(onFulfilled, onRejected) { + var reaction = newPromiseCapability(speciesConstructor(this, $Promise)); + reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true; + reaction.fail = typeof onRejected == 'function' && onRejected; + reaction.domain = isNode ? process.domain : undefined; + this._c.push(reaction); + if (this._a) this._a.push(reaction); + if (this._s) notify(this, false); + return reaction.promise; + }, + // 25.4.5.1 Promise.prototype.catch(onRejected) + 'catch': function (onRejected) { + return this.then(undefined, onRejected); + } + }); + OwnPromiseCapability = function () { + var promise = new Internal(); + this.promise = promise; + this.resolve = ctx($resolve, promise, 1); + this.reject = ctx($reject, promise, 1); + }; + newPromiseCapabilityModule.f = newPromiseCapability = function (C) { + return C === $Promise || C === Wrapper + ? new OwnPromiseCapability(C) + : newGenericPromiseCapability(C); + }; + } + + $export($export.G + $export.W + $export.F * !USE_NATIVE, { Promise: $Promise }); + __webpack_require__(25)($Promise, PROMISE); + __webpack_require__(193)(PROMISE); + Wrapper = __webpack_require__(9)[PROMISE]; + + // statics + $export($export.S + $export.F * !USE_NATIVE, PROMISE, { + // 25.4.4.5 Promise.reject(r) + reject: function reject(r) { + var capability = newPromiseCapability(this); + var $$reject = capability.reject; + $$reject(r); + return capability.promise; + } + }); + $export($export.S + $export.F * (LIBRARY || !USE_NATIVE), PROMISE, { + // 25.4.4.6 Promise.resolve(x) + resolve: function resolve(x) { + return promiseResolve(LIBRARY && this === Wrapper ? $Promise : this, x); + } + }); + $export($export.S + $export.F * !(USE_NATIVE && __webpack_require__(166)(function (iter) { + $Promise.all(iter)['catch'](empty); + })), PROMISE, { + // 25.4.4.1 Promise.all(iterable) + all: function all(iterable) { + var C = this; + var capability = newPromiseCapability(C); + var resolve = capability.resolve; + var reject = capability.reject; + var result = perform(function () { + var values = []; + var index = 0; + var remaining = 1; + forOf(iterable, false, function (promise) { + var $index = index++; + var alreadyCalled = false; + values.push(undefined); + remaining++; + C.resolve(promise).then(function (value) { + if (alreadyCalled) return; + alreadyCalled = true; + values[$index] = value; + --remaining || resolve(values); + }, reject); + }); + --remaining || resolve(values); + }); + if (result.e) reject(result.v); + return capability.promise; + }, + // 25.4.4.4 Promise.race(iterable) + race: function race(iterable) { + var C = this; + var capability = newPromiseCapability(C); + var reject = capability.reject; + var result = perform(function () { + forOf(iterable, false, function (promise) { + C.resolve(promise).then(capability.resolve, reject); + }); + }); + if (result.e) reject(result.v); + return capability.promise; + } + }); + + +/***/ }), +/* 206 */ +/***/ (function(module, exports) { + + module.exports = function (it, Constructor, name, forbiddenField) { + if (!(it instanceof Constructor) || (forbiddenField !== undefined && forbiddenField in it)) { + throw TypeError(name + ': incorrect invocation!'); + } return it; + }; + + +/***/ }), +/* 207 */ +/***/ (function(module, exports, __webpack_require__) { + + var ctx = __webpack_require__(20); + var call = __webpack_require__(162); + var isArrayIter = __webpack_require__(163); + var anObject = __webpack_require__(12); + var toLength = __webpack_require__(37); + var getIterFn = __webpack_require__(165); + var BREAK = {}; + var RETURN = {}; + var exports = module.exports = function (iterable, entries, fn, that, ITERATOR) { + var iterFn = ITERATOR ? function () { return iterable; } : getIterFn(iterable); + var f = ctx(fn, that, entries ? 2 : 1); + var index = 0; + var length, step, iterator, result; + if (typeof iterFn != 'function') throw TypeError(iterable + ' is not iterable!'); + // fast case for arrays with default iterator + if (isArrayIter(iterFn)) for (length = toLength(iterable.length); length > index; index++) { + result = entries ? f(anObject(step = iterable[index])[0], step[1]) : f(iterable[index]); + if (result === BREAK || result === RETURN) return result; + } else for (iterator = iterFn.call(iterable); !(step = iterator.next()).done;) { + result = call(iterator, f, step.value, entries); + if (result === BREAK || result === RETURN) return result; + } + }; + exports.BREAK = BREAK; + exports.RETURN = RETURN; + + +/***/ }), +/* 208 */ +/***/ (function(module, exports, __webpack_require__) { + + // 7.3.20 SpeciesConstructor(O, defaultConstructor) + var anObject = __webpack_require__(12); + var aFunction = __webpack_require__(21); + var SPECIES = __webpack_require__(26)('species'); + module.exports = function (O, D) { + var C = anObject(O).constructor; + var S; + return C === undefined || (S = anObject(C)[SPECIES]) == undefined ? D : aFunction(S); + }; + + +/***/ }), +/* 209 */ +/***/ (function(module, exports, __webpack_require__) { + + var ctx = __webpack_require__(20); + var invoke = __webpack_require__(77); + var html = __webpack_require__(47); + var cel = __webpack_require__(15); + var global = __webpack_require__(4); + var process = global.process; + var setTask = global.setImmediate; + var clearTask = global.clearImmediate; + var MessageChannel = global.MessageChannel; + var Dispatch = global.Dispatch; + var counter = 0; + var queue = {}; + var ONREADYSTATECHANGE = 'onreadystatechange'; + var defer, channel, port; + var run = function () { + var id = +this; + // eslint-disable-next-line no-prototype-builtins + if (queue.hasOwnProperty(id)) { + var fn = queue[id]; + delete queue[id]; + fn(); + } + }; + var listener = function (event) { + run.call(event.data); + }; + // Node.js 0.9+ & IE10+ has setImmediate, otherwise: + if (!setTask || !clearTask) { + setTask = function setImmediate(fn) { + var args = []; + var i = 1; + while (arguments.length > i) args.push(arguments[i++]); + queue[++counter] = function () { + // eslint-disable-next-line no-new-func + invoke(typeof fn == 'function' ? fn : Function(fn), args); + }; + defer(counter); + return counter; + }; + clearTask = function clearImmediate(id) { + delete queue[id]; + }; + // Node.js 0.8- + if (__webpack_require__(34)(process) == 'process') { + defer = function (id) { + process.nextTick(ctx(run, id, 1)); + }; + // Sphere (JS game engine) Dispatch API + } else if (Dispatch && Dispatch.now) { + defer = function (id) { + Dispatch.now(ctx(run, id, 1)); + }; + // Browsers with MessageChannel, includes WebWorkers + } else if (MessageChannel) { + channel = new MessageChannel(); + port = channel.port2; + channel.port1.onmessage = listener; + defer = ctx(port.postMessage, port, 1); + // Browsers with postMessage, skip WebWorkers + // IE8 has postMessage, but it's sync & typeof its postMessage is 'object' + } else if (global.addEventListener && typeof postMessage == 'function' && !global.importScripts) { + defer = function (id) { + global.postMessage(id + '', '*'); + }; + global.addEventListener('message', listener, false); + // IE8- + } else if (ONREADYSTATECHANGE in cel('script')) { + defer = function (id) { + html.appendChild(cel('script'))[ONREADYSTATECHANGE] = function () { + html.removeChild(this); + run.call(id); + }; + }; + // Rest old browsers + } else { + defer = function (id) { + setTimeout(ctx(run, id, 1), 0); + }; + } + } + module.exports = { + set: setTask, + clear: clearTask + }; + + +/***/ }), +/* 210 */ +/***/ (function(module, exports, __webpack_require__) { + + var global = __webpack_require__(4); + var macrotask = __webpack_require__(209).set; + var Observer = global.MutationObserver || global.WebKitMutationObserver; + var process = global.process; + var Promise = global.Promise; + var isNode = __webpack_require__(34)(process) == 'process'; + + module.exports = function () { + var head, last, notify; + + var flush = function () { + var parent, fn; + if (isNode && (parent = process.domain)) parent.exit(); + while (head) { + fn = head.fn; + head = head.next; + try { + fn(); + } catch (e) { + if (head) notify(); + else last = undefined; + throw e; + } + } last = undefined; + if (parent) parent.enter(); + }; + + // Node.js + if (isNode) { + notify = function () { + process.nextTick(flush); + }; + // browsers with MutationObserver, except iOS Safari - https://github.com/zloirock/core-js/issues/339 + } else if (Observer && !(global.navigator && global.navigator.standalone)) { + var toggle = true; + var node = document.createTextNode(''); + new Observer(flush).observe(node, { characterData: true }); // eslint-disable-line no-new + notify = function () { + node.data = toggle = !toggle; + }; + // environments with maybe non-completely correct, but existent Promise + } else if (Promise && Promise.resolve) { + // Promise.resolve without an argument throws an error in LG WebOS 2 + var promise = Promise.resolve(undefined); + notify = function () { + promise.then(flush); + }; + // for other environments - macrotask based on: + // - setImmediate + // - MessageChannel + // - window.postMessag + // - onreadystatechange + // - setTimeout + } else { + notify = function () { + // strange IE + webpack dev server bug - use .call(global) + macrotask.call(global, flush); + }; + } + + return function (fn) { + var task = { fn: fn, next: undefined }; + if (last) last.next = task; + if (!head) { + head = task; + notify(); + } last = task; + }; + }; + + +/***/ }), +/* 211 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // 25.4.1.5 NewPromiseCapability(C) + var aFunction = __webpack_require__(21); + + function PromiseCapability(C) { + var resolve, reject; + this.promise = new C(function ($$resolve, $$reject) { + if (resolve !== undefined || reject !== undefined) throw TypeError('Bad Promise constructor'); + resolve = $$resolve; + reject = $$reject; + }); + this.resolve = aFunction(resolve); + this.reject = aFunction(reject); + } + + module.exports.f = function (C) { + return new PromiseCapability(C); + }; + + +/***/ }), +/* 212 */ +/***/ (function(module, exports) { + + module.exports = function (exec) { + try { + return { e: false, v: exec() }; + } catch (e) { + return { e: true, v: e }; + } + }; + + +/***/ }), +/* 213 */ +/***/ (function(module, exports, __webpack_require__) { + + var global = __webpack_require__(4); + var navigator = global.navigator; + + module.exports = navigator && navigator.userAgent || ''; + + +/***/ }), +/* 214 */ +/***/ (function(module, exports, __webpack_require__) { + + var anObject = __webpack_require__(12); + var isObject = __webpack_require__(13); + var newPromiseCapability = __webpack_require__(211); + + module.exports = function (C, x) { + anObject(C); + if (isObject(x) && x.constructor === C) return x; + var promiseCapability = newPromiseCapability.f(C); + var resolve = promiseCapability.resolve; + resolve(x); + return promiseCapability.promise; + }; + + +/***/ }), +/* 215 */ +/***/ (function(module, exports, __webpack_require__) { + + var redefine = __webpack_require__(18); + module.exports = function (target, src, safe) { + for (var key in src) redefine(target, key, src[key], safe); + return target; + }; + + +/***/ }), +/* 216 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var strong = __webpack_require__(217); + var validate = __webpack_require__(218); + var MAP = 'Map'; + + // 23.1 Map Objects + module.exports = __webpack_require__(219)(MAP, function (get) { + return function Map() { return get(this, arguments.length > 0 ? arguments[0] : undefined); }; + }, { + // 23.1.3.6 Map.prototype.get(key) + get: function get(key) { + var entry = strong.getEntry(validate(this, MAP), key); + return entry && entry.v; + }, + // 23.1.3.9 Map.prototype.set(key, value) + set: function set(key, value) { + return strong.def(validate(this, MAP), key === 0 ? 0 : key, value); + } + }, strong, true); + + +/***/ }), +/* 217 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var dP = __webpack_require__(11).f; + var create = __webpack_require__(45); + var redefineAll = __webpack_require__(215); + var ctx = __webpack_require__(20); + var anInstance = __webpack_require__(206); + var forOf = __webpack_require__(207); + var $iterDefine = __webpack_require__(128); + var step = __webpack_require__(195); + var setSpecies = __webpack_require__(193); + var DESCRIPTORS = __webpack_require__(6); + var fastKey = __webpack_require__(22).fastKey; + var validate = __webpack_require__(218); + var SIZE = DESCRIPTORS ? '_s' : 'size'; + + var getEntry = function (that, key) { + // fast case + var index = fastKey(key); + var entry; + if (index !== 'F') return that._i[index]; + // frozen object case + for (entry = that._f; entry; entry = entry.n) { + if (entry.k == key) return entry; + } + }; + + module.exports = { + getConstructor: function (wrapper, NAME, IS_MAP, ADDER) { + var C = wrapper(function (that, iterable) { + anInstance(that, C, NAME, '_i'); + that._t = NAME; // collection type + that._i = create(null); // index + that._f = undefined; // first entry + that._l = undefined; // last entry + that[SIZE] = 0; // size + if (iterable != undefined) forOf(iterable, IS_MAP, that[ADDER], that); + }); + redefineAll(C.prototype, { + // 23.1.3.1 Map.prototype.clear() + // 23.2.3.2 Set.prototype.clear() + clear: function clear() { + for (var that = validate(this, NAME), data = that._i, entry = that._f; entry; entry = entry.n) { + entry.r = true; + if (entry.p) entry.p = entry.p.n = undefined; + delete data[entry.i]; + } + that._f = that._l = undefined; + that[SIZE] = 0; + }, + // 23.1.3.3 Map.prototype.delete(key) + // 23.2.3.4 Set.prototype.delete(value) + 'delete': function (key) { + var that = validate(this, NAME); + var entry = getEntry(that, key); + if (entry) { + var next = entry.n; + var prev = entry.p; + delete that._i[entry.i]; + entry.r = true; + if (prev) prev.n = next; + if (next) next.p = prev; + if (that._f == entry) that._f = next; + if (that._l == entry) that._l = prev; + that[SIZE]--; + } return !!entry; + }, + // 23.2.3.6 Set.prototype.forEach(callbackfn, thisArg = undefined) + // 23.1.3.5 Map.prototype.forEach(callbackfn, thisArg = undefined) + forEach: function forEach(callbackfn /* , that = undefined */) { + validate(this, NAME); + var f = ctx(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3); + var entry; + while (entry = entry ? entry.n : this._f) { + f(entry.v, entry.k, this); + // revert to the last existing entry + while (entry && entry.r) entry = entry.p; + } + }, + // 23.1.3.7 Map.prototype.has(key) + // 23.2.3.7 Set.prototype.has(value) + has: function has(key) { + return !!getEntry(validate(this, NAME), key); + } + }); + if (DESCRIPTORS) dP(C.prototype, 'size', { + get: function () { + return validate(this, NAME)[SIZE]; + } + }); + return C; + }, + def: function (that, key, value) { + var entry = getEntry(that, key); + var prev, index; + // change existing entry + if (entry) { + entry.v = value; + // create new entry + } else { + that._l = entry = { + i: index = fastKey(key, true), // <- index + k: key, // <- key + v: value, // <- value + p: prev = that._l, // <- previous entry + n: undefined, // <- next entry + r: false // <- removed + }; + if (!that._f) that._f = entry; + if (prev) prev.n = entry; + that[SIZE]++; + // add to index + if (index !== 'F') that._i[index] = entry; + } return that; + }, + getEntry: getEntry, + setStrong: function (C, NAME, IS_MAP) { + // add .keys, .values, .entries, [@@iterator] + // 23.1.3.4, 23.1.3.8, 23.1.3.11, 23.1.3.12, 23.2.3.5, 23.2.3.8, 23.2.3.10, 23.2.3.11 + $iterDefine(C, NAME, function (iterated, kind) { + this._t = validate(iterated, NAME); // target + this._k = kind; // kind + this._l = undefined; // previous + }, function () { + var that = this; + var kind = that._k; + var entry = that._l; + // revert to the last existing entry + while (entry && entry.r) entry = entry.p; + // get next entry + if (!that._t || !(that._l = entry = entry ? entry.n : that._t._f)) { + // or finish the iteration + that._t = undefined; + return step(1); + } + // return step by kind + if (kind == 'keys') return step(0, entry.k); + if (kind == 'values') return step(0, entry.v); + return step(0, [entry.k, entry.v]); + }, IS_MAP ? 'entries' : 'values', !IS_MAP, true); + + // add [@@species], 23.1.2.2, 23.2.2.2 + setSpecies(NAME); + } + }; + + +/***/ }), +/* 218 */ +/***/ (function(module, exports, __webpack_require__) { + + var isObject = __webpack_require__(13); + module.exports = function (it, TYPE) { + if (!isObject(it) || it._t !== TYPE) throw TypeError('Incompatible receiver, ' + TYPE + ' required!'); + return it; + }; + + +/***/ }), +/* 219 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var global = __webpack_require__(4); + var $export = __webpack_require__(8); + var redefine = __webpack_require__(18); + var redefineAll = __webpack_require__(215); + var meta = __webpack_require__(22); + var forOf = __webpack_require__(207); + var anInstance = __webpack_require__(206); + var isObject = __webpack_require__(13); + var fails = __webpack_require__(7); + var $iterDetect = __webpack_require__(166); + var setToStringTag = __webpack_require__(25); + var inheritIfRequired = __webpack_require__(87); + + module.exports = function (NAME, wrapper, methods, common, IS_MAP, IS_WEAK) { + var Base = global[NAME]; + var C = Base; + var ADDER = IS_MAP ? 'set' : 'add'; + var proto = C && C.prototype; + var O = {}; + var fixMethod = function (KEY) { + var fn = proto[KEY]; + redefine(proto, KEY, + KEY == 'delete' ? function (a) { + return IS_WEAK && !isObject(a) ? false : fn.call(this, a === 0 ? 0 : a); + } : KEY == 'has' ? function has(a) { + return IS_WEAK && !isObject(a) ? false : fn.call(this, a === 0 ? 0 : a); + } : KEY == 'get' ? function get(a) { + return IS_WEAK && !isObject(a) ? undefined : fn.call(this, a === 0 ? 0 : a); + } : KEY == 'add' ? function add(a) { fn.call(this, a === 0 ? 0 : a); return this; } + : function set(a, b) { fn.call(this, a === 0 ? 0 : a, b); return this; } + ); + }; + if (typeof C != 'function' || !(IS_WEAK || proto.forEach && !fails(function () { + new C().entries().next(); + }))) { + // create collection constructor + C = common.getConstructor(wrapper, NAME, IS_MAP, ADDER); + redefineAll(C.prototype, methods); + meta.NEED = true; + } else { + var instance = new C(); + // early implementations not supports chaining + var HASNT_CHAINING = instance[ADDER](IS_WEAK ? {} : -0, 1) != instance; + // V8 ~ Chromium 40- weak-collections throws on primitives, but should return false + var THROWS_ON_PRIMITIVES = fails(function () { instance.has(1); }); + // most early implementations doesn't supports iterables, most modern - not close it correctly + var ACCEPT_ITERABLES = $iterDetect(function (iter) { new C(iter); }); // eslint-disable-line no-new + // for early implementations -0 and +0 not the same + var BUGGY_ZERO = !IS_WEAK && fails(function () { + // V8 ~ Chromium 42- fails only with 5+ elements + var $instance = new C(); + var index = 5; + while (index--) $instance[ADDER](index, index); + return !$instance.has(-0); + }); + if (!ACCEPT_ITERABLES) { + C = wrapper(function (target, iterable) { + anInstance(target, C, NAME); + var that = inheritIfRequired(new Base(), target, C); + if (iterable != undefined) forOf(iterable, IS_MAP, that[ADDER], that); + return that; + }); + C.prototype = proto; + proto.constructor = C; + } + if (THROWS_ON_PRIMITIVES || BUGGY_ZERO) { + fixMethod('delete'); + fixMethod('has'); + IS_MAP && fixMethod('get'); + } + if (BUGGY_ZERO || HASNT_CHAINING) fixMethod(ADDER); + // weak collections should not contains .clear method + if (IS_WEAK && proto.clear) delete proto.clear; + } + + setToStringTag(C, NAME); + + O[NAME] = C; + $export($export.G + $export.W + $export.F * (C != Base), O); + + if (!IS_WEAK) common.setStrong(C, NAME, IS_MAP); + + return C; + }; + + +/***/ }), +/* 220 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var strong = __webpack_require__(217); + var validate = __webpack_require__(218); + var SET = 'Set'; + + // 23.2 Set Objects + module.exports = __webpack_require__(219)(SET, function (get) { + return function Set() { return get(this, arguments.length > 0 ? arguments[0] : undefined); }; + }, { + // 23.2.3.1 Set.prototype.add(value) + add: function add(value) { + return strong.def(validate(this, SET), value = value === 0 ? 0 : value, value); + } + }, strong); + + +/***/ }), +/* 221 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var each = __webpack_require__(173)(0); + var redefine = __webpack_require__(18); + var meta = __webpack_require__(22); + var assign = __webpack_require__(68); + var weak = __webpack_require__(222); + var isObject = __webpack_require__(13); + var fails = __webpack_require__(7); + var validate = __webpack_require__(218); + var WEAK_MAP = 'WeakMap'; + var getWeak = meta.getWeak; + var isExtensible = Object.isExtensible; + var uncaughtFrozenStore = weak.ufstore; + var tmp = {}; + var InternalMap; + + var wrapper = function (get) { + return function WeakMap() { + return get(this, arguments.length > 0 ? arguments[0] : undefined); + }; + }; + + var methods = { + // 23.3.3.3 WeakMap.prototype.get(key) + get: function get(key) { + if (isObject(key)) { + var data = getWeak(key); + if (data === true) return uncaughtFrozenStore(validate(this, WEAK_MAP)).get(key); + return data ? data[this._i] : undefined; + } + }, + // 23.3.3.5 WeakMap.prototype.set(key, value) + set: function set(key, value) { + return weak.def(validate(this, WEAK_MAP), key, value); + } + }; + + // 23.3 WeakMap Objects + var $WeakMap = module.exports = __webpack_require__(219)(WEAK_MAP, wrapper, methods, weak, true, true); + + // IE11 WeakMap frozen keys fix + if (fails(function () { return new $WeakMap().set((Object.freeze || Object)(tmp), 7).get(tmp) != 7; })) { + InternalMap = weak.getConstructor(wrapper, WEAK_MAP); + assign(InternalMap.prototype, methods); + meta.NEED = true; + each(['delete', 'has', 'get', 'set'], function (key) { + var proto = $WeakMap.prototype; + var method = proto[key]; + redefine(proto, key, function (a, b) { + // store frozen objects on internal weakmap shim + if (isObject(a) && !isExtensible(a)) { + if (!this._f) this._f = new InternalMap(); + var result = this._f[key](a, b); + return key == 'set' ? this : result; + // store all the rest on native weakmap + } return method.call(this, a, b); + }); + }); + } + + +/***/ }), +/* 222 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var redefineAll = __webpack_require__(215); + var getWeak = __webpack_require__(22).getWeak; + var anObject = __webpack_require__(12); + var isObject = __webpack_require__(13); + var anInstance = __webpack_require__(206); + var forOf = __webpack_require__(207); + var createArrayMethod = __webpack_require__(173); + var $has = __webpack_require__(5); + var validate = __webpack_require__(218); + var arrayFind = createArrayMethod(5); + var arrayFindIndex = createArrayMethod(6); + var id = 0; + + // fallback for uncaught frozen keys + var uncaughtFrozenStore = function (that) { + return that._l || (that._l = new UncaughtFrozenStore()); + }; + var UncaughtFrozenStore = function () { + this.a = []; + }; + var findUncaughtFrozen = function (store, key) { + return arrayFind(store.a, function (it) { + return it[0] === key; + }); + }; + UncaughtFrozenStore.prototype = { + get: function (key) { + var entry = findUncaughtFrozen(this, key); + if (entry) return entry[1]; + }, + has: function (key) { + return !!findUncaughtFrozen(this, key); + }, + set: function (key, value) { + var entry = findUncaughtFrozen(this, key); + if (entry) entry[1] = value; + else this.a.push([key, value]); + }, + 'delete': function (key) { + var index = arrayFindIndex(this.a, function (it) { + return it[0] === key; + }); + if (~index) this.a.splice(index, 1); + return !!~index; + } + }; + + module.exports = { + getConstructor: function (wrapper, NAME, IS_MAP, ADDER) { + var C = wrapper(function (that, iterable) { + anInstance(that, C, NAME, '_i'); + that._t = NAME; // collection type + that._i = id++; // collection id + that._l = undefined; // leak store for uncaught frozen objects + if (iterable != undefined) forOf(iterable, IS_MAP, that[ADDER], that); + }); + redefineAll(C.prototype, { + // 23.3.3.2 WeakMap.prototype.delete(key) + // 23.4.3.3 WeakSet.prototype.delete(value) + 'delete': function (key) { + if (!isObject(key)) return false; + var data = getWeak(key); + if (data === true) return uncaughtFrozenStore(validate(this, NAME))['delete'](key); + return data && $has(data, this._i) && delete data[this._i]; + }, + // 23.3.3.4 WeakMap.prototype.has(key) + // 23.4.3.4 WeakSet.prototype.has(value) + has: function has(key) { + if (!isObject(key)) return false; + var data = getWeak(key); + if (data === true) return uncaughtFrozenStore(validate(this, NAME)).has(key); + return data && $has(data, this._i); + } + }); + return C; + }, + def: function (that, key, value) { + var data = getWeak(anObject(key), true); + if (data === true) uncaughtFrozenStore(that).set(key, value); + else data[that._i] = value; + return that; + }, + ufstore: uncaughtFrozenStore + }; + + +/***/ }), +/* 223 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var weak = __webpack_require__(222); + var validate = __webpack_require__(218); + var WEAK_SET = 'WeakSet'; + + // 23.4 WeakSet Objects + __webpack_require__(219)(WEAK_SET, function (get) { + return function WeakSet() { return get(this, arguments.length > 0 ? arguments[0] : undefined); }; + }, { + // 23.4.3.1 WeakSet.prototype.add(value) + add: function add(value) { + return weak.def(validate(this, WEAK_SET), value, true); + } + }, weak, false, true); + + +/***/ }), +/* 224 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var $typed = __webpack_require__(225); + var buffer = __webpack_require__(226); + var anObject = __webpack_require__(12); + var toAbsoluteIndex = __webpack_require__(39); + var toLength = __webpack_require__(37); + var isObject = __webpack_require__(13); + var ArrayBuffer = __webpack_require__(4).ArrayBuffer; + var speciesConstructor = __webpack_require__(208); + var $ArrayBuffer = buffer.ArrayBuffer; + var $DataView = buffer.DataView; + var $isView = $typed.ABV && ArrayBuffer.isView; + var $slice = $ArrayBuffer.prototype.slice; + var VIEW = $typed.VIEW; + var ARRAY_BUFFER = 'ArrayBuffer'; + + $export($export.G + $export.W + $export.F * (ArrayBuffer !== $ArrayBuffer), { ArrayBuffer: $ArrayBuffer }); + + $export($export.S + $export.F * !$typed.CONSTR, ARRAY_BUFFER, { + // 24.1.3.1 ArrayBuffer.isView(arg) + isView: function isView(it) { + return $isView && $isView(it) || isObject(it) && VIEW in it; + } + }); + + $export($export.P + $export.U + $export.F * __webpack_require__(7)(function () { + return !new $ArrayBuffer(2).slice(1, undefined).byteLength; + }), ARRAY_BUFFER, { + // 24.1.4.3 ArrayBuffer.prototype.slice(start, end) + slice: function slice(start, end) { + if ($slice !== undefined && end === undefined) return $slice.call(anObject(this), start); // FF fix + var len = anObject(this).byteLength; + var first = toAbsoluteIndex(start, len); + var fin = toAbsoluteIndex(end === undefined ? len : end, len); + var result = new (speciesConstructor(this, $ArrayBuffer))(toLength(fin - first)); + var viewS = new $DataView(this); + var viewT = new $DataView(result); + var index = 0; + while (first < fin) { + viewT.setUint8(index++, viewS.getUint8(first++)); + } return result; + } + }); + + __webpack_require__(193)(ARRAY_BUFFER); + + +/***/ }), +/* 225 */ +/***/ (function(module, exports, __webpack_require__) { + + var global = __webpack_require__(4); + var hide = __webpack_require__(10); + var uid = __webpack_require__(19); + var TYPED = uid('typed_array'); + var VIEW = uid('view'); + var ABV = !!(global.ArrayBuffer && global.DataView); + var CONSTR = ABV; + var i = 0; + var l = 9; + var Typed; + + var TypedArrayConstructors = ( + 'Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array' + ).split(','); + + while (i < l) { + if (Typed = global[TypedArrayConstructors[i++]]) { + hide(Typed.prototype, TYPED, true); + hide(Typed.prototype, VIEW, true); + } else CONSTR = false; + } + + module.exports = { + ABV: ABV, + CONSTR: CONSTR, + TYPED: TYPED, + VIEW: VIEW + }; + + +/***/ }), +/* 226 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var global = __webpack_require__(4); + var DESCRIPTORS = __webpack_require__(6); + var LIBRARY = __webpack_require__(24); + var $typed = __webpack_require__(225); + var hide = __webpack_require__(10); + var redefineAll = __webpack_require__(215); + var fails = __webpack_require__(7); + var anInstance = __webpack_require__(206); + var toInteger = __webpack_require__(38); + var toLength = __webpack_require__(37); + var toIndex = __webpack_require__(227); + var gOPN = __webpack_require__(49).f; + var dP = __webpack_require__(11).f; + var arrayFill = __webpack_require__(189); + var setToStringTag = __webpack_require__(25); + var ARRAY_BUFFER = 'ArrayBuffer'; + var DATA_VIEW = 'DataView'; + var PROTOTYPE = 'prototype'; + var WRONG_LENGTH = 'Wrong length!'; + var WRONG_INDEX = 'Wrong index!'; + var $ArrayBuffer = global[ARRAY_BUFFER]; + var $DataView = global[DATA_VIEW]; + var Math = global.Math; + var RangeError = global.RangeError; + // eslint-disable-next-line no-shadow-restricted-names + var Infinity = global.Infinity; + var BaseBuffer = $ArrayBuffer; + var abs = Math.abs; + var pow = Math.pow; + var floor = Math.floor; + var log = Math.log; + var LN2 = Math.LN2; + var BUFFER = 'buffer'; + var BYTE_LENGTH = 'byteLength'; + var BYTE_OFFSET = 'byteOffset'; + var $BUFFER = DESCRIPTORS ? '_b' : BUFFER; + var $LENGTH = DESCRIPTORS ? '_l' : BYTE_LENGTH; + var $OFFSET = DESCRIPTORS ? '_o' : BYTE_OFFSET; + + // IEEE754 conversions based on https://github.com/feross/ieee754 + function packIEEE754(value, mLen, nBytes) { + var buffer = new Array(nBytes); + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var rt = mLen === 23 ? pow(2, -24) - pow(2, -77) : 0; + var i = 0; + var s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0; + var e, m, c; + value = abs(value); + // eslint-disable-next-line no-self-compare + if (value != value || value === Infinity) { + // eslint-disable-next-line no-self-compare + m = value != value ? 1 : 0; + e = eMax; + } else { + e = floor(log(value) / LN2); + if (value * (c = pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value += rt / c; + } else { + value += rt * pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * pow(2, mLen); + e = e + eBias; + } else { + m = value * pow(2, eBias - 1) * pow(2, mLen); + e = 0; + } + } + for (; mLen >= 8; buffer[i++] = m & 255, m /= 256, mLen -= 8); + e = e << mLen | m; + eLen += mLen; + for (; eLen > 0; buffer[i++] = e & 255, e /= 256, eLen -= 8); + buffer[--i] |= s * 128; + return buffer; + } + function unpackIEEE754(buffer, mLen, nBytes) { + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var nBits = eLen - 7; + var i = nBytes - 1; + var s = buffer[i--]; + var e = s & 127; + var m; + s >>= 7; + for (; nBits > 0; e = e * 256 + buffer[i], i--, nBits -= 8); + m = e & (1 << -nBits) - 1; + e >>= -nBits; + nBits += mLen; + for (; nBits > 0; m = m * 256 + buffer[i], i--, nBits -= 8); + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : s ? -Infinity : Infinity; + } else { + m = m + pow(2, mLen); + e = e - eBias; + } return (s ? -1 : 1) * m * pow(2, e - mLen); + } + + function unpackI32(bytes) { + return bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0]; + } + function packI8(it) { + return [it & 0xff]; + } + function packI16(it) { + return [it & 0xff, it >> 8 & 0xff]; + } + function packI32(it) { + return [it & 0xff, it >> 8 & 0xff, it >> 16 & 0xff, it >> 24 & 0xff]; + } + function packF64(it) { + return packIEEE754(it, 52, 8); + } + function packF32(it) { + return packIEEE754(it, 23, 4); + } + + function addGetter(C, key, internal) { + dP(C[PROTOTYPE], key, { get: function () { return this[internal]; } }); + } + + function get(view, bytes, index, isLittleEndian) { + var numIndex = +index; + var intIndex = toIndex(numIndex); + if (intIndex + bytes > view[$LENGTH]) throw RangeError(WRONG_INDEX); + var store = view[$BUFFER]._b; + var start = intIndex + view[$OFFSET]; + var pack = store.slice(start, start + bytes); + return isLittleEndian ? pack : pack.reverse(); + } + function set(view, bytes, index, conversion, value, isLittleEndian) { + var numIndex = +index; + var intIndex = toIndex(numIndex); + if (intIndex + bytes > view[$LENGTH]) throw RangeError(WRONG_INDEX); + var store = view[$BUFFER]._b; + var start = intIndex + view[$OFFSET]; + var pack = conversion(+value); + for (var i = 0; i < bytes; i++) store[start + i] = pack[isLittleEndian ? i : bytes - i - 1]; + } + + if (!$typed.ABV) { + $ArrayBuffer = function ArrayBuffer(length) { + anInstance(this, $ArrayBuffer, ARRAY_BUFFER); + var byteLength = toIndex(length); + this._b = arrayFill.call(new Array(byteLength), 0); + this[$LENGTH] = byteLength; + }; + + $DataView = function DataView(buffer, byteOffset, byteLength) { + anInstance(this, $DataView, DATA_VIEW); + anInstance(buffer, $ArrayBuffer, DATA_VIEW); + var bufferLength = buffer[$LENGTH]; + var offset = toInteger(byteOffset); + if (offset < 0 || offset > bufferLength) throw RangeError('Wrong offset!'); + byteLength = byteLength === undefined ? bufferLength - offset : toLength(byteLength); + if (offset + byteLength > bufferLength) throw RangeError(WRONG_LENGTH); + this[$BUFFER] = buffer; + this[$OFFSET] = offset; + this[$LENGTH] = byteLength; + }; + + if (DESCRIPTORS) { + addGetter($ArrayBuffer, BYTE_LENGTH, '_l'); + addGetter($DataView, BUFFER, '_b'); + addGetter($DataView, BYTE_LENGTH, '_l'); + addGetter($DataView, BYTE_OFFSET, '_o'); + } + + redefineAll($DataView[PROTOTYPE], { + getInt8: function getInt8(byteOffset) { + return get(this, 1, byteOffset)[0] << 24 >> 24; + }, + getUint8: function getUint8(byteOffset) { + return get(this, 1, byteOffset)[0]; + }, + getInt16: function getInt16(byteOffset /* , littleEndian */) { + var bytes = get(this, 2, byteOffset, arguments[1]); + return (bytes[1] << 8 | bytes[0]) << 16 >> 16; + }, + getUint16: function getUint16(byteOffset /* , littleEndian */) { + var bytes = get(this, 2, byteOffset, arguments[1]); + return bytes[1] << 8 | bytes[0]; + }, + getInt32: function getInt32(byteOffset /* , littleEndian */) { + return unpackI32(get(this, 4, byteOffset, arguments[1])); + }, + getUint32: function getUint32(byteOffset /* , littleEndian */) { + return unpackI32(get(this, 4, byteOffset, arguments[1])) >>> 0; + }, + getFloat32: function getFloat32(byteOffset /* , littleEndian */) { + return unpackIEEE754(get(this, 4, byteOffset, arguments[1]), 23, 4); + }, + getFloat64: function getFloat64(byteOffset /* , littleEndian */) { + return unpackIEEE754(get(this, 8, byteOffset, arguments[1]), 52, 8); + }, + setInt8: function setInt8(byteOffset, value) { + set(this, 1, byteOffset, packI8, value); + }, + setUint8: function setUint8(byteOffset, value) { + set(this, 1, byteOffset, packI8, value); + }, + setInt16: function setInt16(byteOffset, value /* , littleEndian */) { + set(this, 2, byteOffset, packI16, value, arguments[2]); + }, + setUint16: function setUint16(byteOffset, value /* , littleEndian */) { + set(this, 2, byteOffset, packI16, value, arguments[2]); + }, + setInt32: function setInt32(byteOffset, value /* , littleEndian */) { + set(this, 4, byteOffset, packI32, value, arguments[2]); + }, + setUint32: function setUint32(byteOffset, value /* , littleEndian */) { + set(this, 4, byteOffset, packI32, value, arguments[2]); + }, + setFloat32: function setFloat32(byteOffset, value /* , littleEndian */) { + set(this, 4, byteOffset, packF32, value, arguments[2]); + }, + setFloat64: function setFloat64(byteOffset, value /* , littleEndian */) { + set(this, 8, byteOffset, packF64, value, arguments[2]); + } + }); + } else { + if (!fails(function () { + $ArrayBuffer(1); + }) || !fails(function () { + new $ArrayBuffer(-1); // eslint-disable-line no-new + }) || fails(function () { + new $ArrayBuffer(); // eslint-disable-line no-new + new $ArrayBuffer(1.5); // eslint-disable-line no-new + new $ArrayBuffer(NaN); // eslint-disable-line no-new + return $ArrayBuffer.name != ARRAY_BUFFER; + })) { + $ArrayBuffer = function ArrayBuffer(length) { + anInstance(this, $ArrayBuffer); + return new BaseBuffer(toIndex(length)); + }; + var ArrayBufferProto = $ArrayBuffer[PROTOTYPE] = BaseBuffer[PROTOTYPE]; + for (var keys = gOPN(BaseBuffer), j = 0, key; keys.length > j;) { + if (!((key = keys[j++]) in $ArrayBuffer)) hide($ArrayBuffer, key, BaseBuffer[key]); + } + if (!LIBRARY) ArrayBufferProto.constructor = $ArrayBuffer; + } + // iOS Safari 7.x bug + var view = new $DataView(new $ArrayBuffer(2)); + var $setInt8 = $DataView[PROTOTYPE].setInt8; + view.setInt8(0, 2147483648); + view.setInt8(1, 2147483649); + if (view.getInt8(0) || !view.getInt8(1)) redefineAll($DataView[PROTOTYPE], { + setInt8: function setInt8(byteOffset, value) { + $setInt8.call(this, byteOffset, value << 24 >> 24); + }, + setUint8: function setUint8(byteOffset, value) { + $setInt8.call(this, byteOffset, value << 24 >> 24); + } + }, true); + } + setToStringTag($ArrayBuffer, ARRAY_BUFFER); + setToStringTag($DataView, DATA_VIEW); + hide($DataView[PROTOTYPE], $typed.VIEW, true); + exports[ARRAY_BUFFER] = $ArrayBuffer; + exports[DATA_VIEW] = $DataView; + + +/***/ }), +/* 227 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://tc39.github.io/ecma262/#sec-toindex + var toInteger = __webpack_require__(38); + var toLength = __webpack_require__(37); + module.exports = function (it) { + if (it === undefined) return 0; + var number = toInteger(it); + var length = toLength(number); + if (number !== length) throw RangeError('Wrong length!'); + return length; + }; + + +/***/ }), +/* 228 */ +/***/ (function(module, exports, __webpack_require__) { + + var $export = __webpack_require__(8); + $export($export.G + $export.W + $export.F * !__webpack_require__(225).ABV, { + DataView: __webpack_require__(226).DataView + }); + + +/***/ }), +/* 229 */ +/***/ (function(module, exports, __webpack_require__) { + + __webpack_require__(230)('Int8', 1, function (init) { + return function Int8Array(data, byteOffset, length) { + return init(this, data, byteOffset, length); + }; + }); + + +/***/ }), +/* 230 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + if (__webpack_require__(6)) { + var LIBRARY = __webpack_require__(24); + var global = __webpack_require__(4); + var fails = __webpack_require__(7); + var $export = __webpack_require__(8); + var $typed = __webpack_require__(225); + var $buffer = __webpack_require__(226); + var ctx = __webpack_require__(20); + var anInstance = __webpack_require__(206); + var propertyDesc = __webpack_require__(17); + var hide = __webpack_require__(10); + var redefineAll = __webpack_require__(215); + var toInteger = __webpack_require__(38); + var toLength = __webpack_require__(37); + var toIndex = __webpack_require__(227); + var toAbsoluteIndex = __webpack_require__(39); + var toPrimitive = __webpack_require__(16); + var has = __webpack_require__(5); + var classof = __webpack_require__(74); + var isObject = __webpack_require__(13); + var toObject = __webpack_require__(57); + var isArrayIter = __webpack_require__(163); + var create = __webpack_require__(45); + var getPrototypeOf = __webpack_require__(58); + var gOPN = __webpack_require__(49).f; + var getIterFn = __webpack_require__(165); + var uid = __webpack_require__(19); + var wks = __webpack_require__(26); + var createArrayMethod = __webpack_require__(173); + var createArrayIncludes = __webpack_require__(36); + var speciesConstructor = __webpack_require__(208); + var ArrayIterators = __webpack_require__(194); + var Iterators = __webpack_require__(129); + var $iterDetect = __webpack_require__(166); + var setSpecies = __webpack_require__(193); + var arrayFill = __webpack_require__(189); + var arrayCopyWithin = __webpack_require__(186); + var $DP = __webpack_require__(11); + var $GOPD = __webpack_require__(50); + var dP = $DP.f; + var gOPD = $GOPD.f; + var RangeError = global.RangeError; + var TypeError = global.TypeError; + var Uint8Array = global.Uint8Array; + var ARRAY_BUFFER = 'ArrayBuffer'; + var SHARED_BUFFER = 'Shared' + ARRAY_BUFFER; + var BYTES_PER_ELEMENT = 'BYTES_PER_ELEMENT'; + var PROTOTYPE = 'prototype'; + var ArrayProto = Array[PROTOTYPE]; + var $ArrayBuffer = $buffer.ArrayBuffer; + var $DataView = $buffer.DataView; + var arrayForEach = createArrayMethod(0); + var arrayFilter = createArrayMethod(2); + var arraySome = createArrayMethod(3); + var arrayEvery = createArrayMethod(4); + var arrayFind = createArrayMethod(5); + var arrayFindIndex = createArrayMethod(6); + var arrayIncludes = createArrayIncludes(true); + var arrayIndexOf = createArrayIncludes(false); + var arrayValues = ArrayIterators.values; + var arrayKeys = ArrayIterators.keys; + var arrayEntries = ArrayIterators.entries; + var arrayLastIndexOf = ArrayProto.lastIndexOf; + var arrayReduce = ArrayProto.reduce; + var arrayReduceRight = ArrayProto.reduceRight; + var arrayJoin = ArrayProto.join; + var arraySort = ArrayProto.sort; + var arraySlice = ArrayProto.slice; + var arrayToString = ArrayProto.toString; + var arrayToLocaleString = ArrayProto.toLocaleString; + var ITERATOR = wks('iterator'); + var TAG = wks('toStringTag'); + var TYPED_CONSTRUCTOR = uid('typed_constructor'); + var DEF_CONSTRUCTOR = uid('def_constructor'); + var ALL_CONSTRUCTORS = $typed.CONSTR; + var TYPED_ARRAY = $typed.TYPED; + var VIEW = $typed.VIEW; + var WRONG_LENGTH = 'Wrong length!'; + + var $map = createArrayMethod(1, function (O, length) { + return allocate(speciesConstructor(O, O[DEF_CONSTRUCTOR]), length); + }); + + var LITTLE_ENDIAN = fails(function () { + // eslint-disable-next-line no-undef + return new Uint8Array(new Uint16Array([1]).buffer)[0] === 1; + }); + + var FORCED_SET = !!Uint8Array && !!Uint8Array[PROTOTYPE].set && fails(function () { + new Uint8Array(1).set({}); + }); + + var toOffset = function (it, BYTES) { + var offset = toInteger(it); + if (offset < 0 || offset % BYTES) throw RangeError('Wrong offset!'); + return offset; + }; + + var validate = function (it) { + if (isObject(it) && TYPED_ARRAY in it) return it; + throw TypeError(it + ' is not a typed array!'); + }; + + var allocate = function (C, length) { + if (!(isObject(C) && TYPED_CONSTRUCTOR in C)) { + throw TypeError('It is not a typed array constructor!'); + } return new C(length); + }; + + var speciesFromList = function (O, list) { + return fromList(speciesConstructor(O, O[DEF_CONSTRUCTOR]), list); + }; + + var fromList = function (C, list) { + var index = 0; + var length = list.length; + var result = allocate(C, length); + while (length > index) result[index] = list[index++]; + return result; + }; + + var addGetter = function (it, key, internal) { + dP(it, key, { get: function () { return this._d[internal]; } }); + }; + + var $from = function from(source /* , mapfn, thisArg */) { + var O = toObject(source); + var aLen = arguments.length; + var mapfn = aLen > 1 ? arguments[1] : undefined; + var mapping = mapfn !== undefined; + var iterFn = getIterFn(O); + var i, length, values, result, step, iterator; + if (iterFn != undefined && !isArrayIter(iterFn)) { + for (iterator = iterFn.call(O), values = [], i = 0; !(step = iterator.next()).done; i++) { + values.push(step.value); + } O = values; + } + if (mapping && aLen > 2) mapfn = ctx(mapfn, arguments[2], 2); + for (i = 0, length = toLength(O.length), result = allocate(this, length); length > i; i++) { + result[i] = mapping ? mapfn(O[i], i) : O[i]; + } + return result; + }; + + var $of = function of(/* ...items */) { + var index = 0; + var length = arguments.length; + var result = allocate(this, length); + while (length > index) result[index] = arguments[index++]; + return result; + }; + + // iOS Safari 6.x fails here + var TO_LOCALE_BUG = !!Uint8Array && fails(function () { arrayToLocaleString.call(new Uint8Array(1)); }); + + var $toLocaleString = function toLocaleString() { + return arrayToLocaleString.apply(TO_LOCALE_BUG ? arraySlice.call(validate(this)) : validate(this), arguments); + }; + + var proto = { + copyWithin: function copyWithin(target, start /* , end */) { + return arrayCopyWithin.call(validate(this), target, start, arguments.length > 2 ? arguments[2] : undefined); + }, + every: function every(callbackfn /* , thisArg */) { + return arrayEvery(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined); + }, + fill: function fill(value /* , start, end */) { // eslint-disable-line no-unused-vars + return arrayFill.apply(validate(this), arguments); + }, + filter: function filter(callbackfn /* , thisArg */) { + return speciesFromList(this, arrayFilter(validate(this), callbackfn, + arguments.length > 1 ? arguments[1] : undefined)); + }, + find: function find(predicate /* , thisArg */) { + return arrayFind(validate(this), predicate, arguments.length > 1 ? arguments[1] : undefined); + }, + findIndex: function findIndex(predicate /* , thisArg */) { + return arrayFindIndex(validate(this), predicate, arguments.length > 1 ? arguments[1] : undefined); + }, + forEach: function forEach(callbackfn /* , thisArg */) { + arrayForEach(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined); + }, + indexOf: function indexOf(searchElement /* , fromIndex */) { + return arrayIndexOf(validate(this), searchElement, arguments.length > 1 ? arguments[1] : undefined); + }, + includes: function includes(searchElement /* , fromIndex */) { + return arrayIncludes(validate(this), searchElement, arguments.length > 1 ? arguments[1] : undefined); + }, + join: function join(separator) { // eslint-disable-line no-unused-vars + return arrayJoin.apply(validate(this), arguments); + }, + lastIndexOf: function lastIndexOf(searchElement /* , fromIndex */) { // eslint-disable-line no-unused-vars + return arrayLastIndexOf.apply(validate(this), arguments); + }, + map: function map(mapfn /* , thisArg */) { + return $map(validate(this), mapfn, arguments.length > 1 ? arguments[1] : undefined); + }, + reduce: function reduce(callbackfn /* , initialValue */) { // eslint-disable-line no-unused-vars + return arrayReduce.apply(validate(this), arguments); + }, + reduceRight: function reduceRight(callbackfn /* , initialValue */) { // eslint-disable-line no-unused-vars + return arrayReduceRight.apply(validate(this), arguments); + }, + reverse: function reverse() { + var that = this; + var length = validate(that).length; + var middle = Math.floor(length / 2); + var index = 0; + var value; + while (index < middle) { + value = that[index]; + that[index++] = that[--length]; + that[length] = value; + } return that; + }, + some: function some(callbackfn /* , thisArg */) { + return arraySome(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined); + }, + sort: function sort(comparefn) { + return arraySort.call(validate(this), comparefn); + }, + subarray: function subarray(begin, end) { + var O = validate(this); + var length = O.length; + var $begin = toAbsoluteIndex(begin, length); + return new (speciesConstructor(O, O[DEF_CONSTRUCTOR]))( + O.buffer, + O.byteOffset + $begin * O.BYTES_PER_ELEMENT, + toLength((end === undefined ? length : toAbsoluteIndex(end, length)) - $begin) + ); + } + }; + + var $slice = function slice(start, end) { + return speciesFromList(this, arraySlice.call(validate(this), start, end)); + }; + + var $set = function set(arrayLike /* , offset */) { + validate(this); + var offset = toOffset(arguments[1], 1); + var length = this.length; + var src = toObject(arrayLike); + var len = toLength(src.length); + var index = 0; + if (len + offset > length) throw RangeError(WRONG_LENGTH); + while (index < len) this[offset + index] = src[index++]; + }; + + var $iterators = { + entries: function entries() { + return arrayEntries.call(validate(this)); + }, + keys: function keys() { + return arrayKeys.call(validate(this)); + }, + values: function values() { + return arrayValues.call(validate(this)); + } + }; + + var isTAIndex = function (target, key) { + return isObject(target) + && target[TYPED_ARRAY] + && typeof key != 'symbol' + && key in target + && String(+key) == String(key); + }; + var $getDesc = function getOwnPropertyDescriptor(target, key) { + return isTAIndex(target, key = toPrimitive(key, true)) + ? propertyDesc(2, target[key]) + : gOPD(target, key); + }; + var $setDesc = function defineProperty(target, key, desc) { + if (isTAIndex(target, key = toPrimitive(key, true)) + && isObject(desc) + && has(desc, 'value') + && !has(desc, 'get') + && !has(desc, 'set') + // TODO: add validation descriptor w/o calling accessors + && !desc.configurable + && (!has(desc, 'writable') || desc.writable) + && (!has(desc, 'enumerable') || desc.enumerable) + ) { + target[key] = desc.value; + return target; + } return dP(target, key, desc); + }; + + if (!ALL_CONSTRUCTORS) { + $GOPD.f = $getDesc; + $DP.f = $setDesc; + } + + $export($export.S + $export.F * !ALL_CONSTRUCTORS, 'Object', { + getOwnPropertyDescriptor: $getDesc, + defineProperty: $setDesc + }); + + if (fails(function () { arrayToString.call({}); })) { + arrayToString = arrayToLocaleString = function toString() { + return arrayJoin.call(this); + }; + } + + var $TypedArrayPrototype$ = redefineAll({}, proto); + redefineAll($TypedArrayPrototype$, $iterators); + hide($TypedArrayPrototype$, ITERATOR, $iterators.values); + redefineAll($TypedArrayPrototype$, { + slice: $slice, + set: $set, + constructor: function () { /* noop */ }, + toString: arrayToString, + toLocaleString: $toLocaleString + }); + addGetter($TypedArrayPrototype$, 'buffer', 'b'); + addGetter($TypedArrayPrototype$, 'byteOffset', 'o'); + addGetter($TypedArrayPrototype$, 'byteLength', 'l'); + addGetter($TypedArrayPrototype$, 'length', 'e'); + dP($TypedArrayPrototype$, TAG, { + get: function () { return this[TYPED_ARRAY]; } + }); + + // eslint-disable-next-line max-statements + module.exports = function (KEY, BYTES, wrapper, CLAMPED) { + CLAMPED = !!CLAMPED; + var NAME = KEY + (CLAMPED ? 'Clamped' : '') + 'Array'; + var GETTER = 'get' + KEY; + var SETTER = 'set' + KEY; + var TypedArray = global[NAME]; + var Base = TypedArray || {}; + var TAC = TypedArray && getPrototypeOf(TypedArray); + var FORCED = !TypedArray || !$typed.ABV; + var O = {}; + var TypedArrayPrototype = TypedArray && TypedArray[PROTOTYPE]; + var getter = function (that, index) { + var data = that._d; + return data.v[GETTER](index * BYTES + data.o, LITTLE_ENDIAN); + }; + var setter = function (that, index, value) { + var data = that._d; + if (CLAMPED) value = (value = Math.round(value)) < 0 ? 0 : value > 0xff ? 0xff : value & 0xff; + data.v[SETTER](index * BYTES + data.o, value, LITTLE_ENDIAN); + }; + var addElement = function (that, index) { + dP(that, index, { + get: function () { + return getter(this, index); + }, + set: function (value) { + return setter(this, index, value); + }, + enumerable: true + }); + }; + if (FORCED) { + TypedArray = wrapper(function (that, data, $offset, $length) { + anInstance(that, TypedArray, NAME, '_d'); + var index = 0; + var offset = 0; + var buffer, byteLength, length, klass; + if (!isObject(data)) { + length = toIndex(data); + byteLength = length * BYTES; + buffer = new $ArrayBuffer(byteLength); + } else if (data instanceof $ArrayBuffer || (klass = classof(data)) == ARRAY_BUFFER || klass == SHARED_BUFFER) { + buffer = data; + offset = toOffset($offset, BYTES); + var $len = data.byteLength; + if ($length === undefined) { + if ($len % BYTES) throw RangeError(WRONG_LENGTH); + byteLength = $len - offset; + if (byteLength < 0) throw RangeError(WRONG_LENGTH); + } else { + byteLength = toLength($length) * BYTES; + if (byteLength + offset > $len) throw RangeError(WRONG_LENGTH); + } + length = byteLength / BYTES; + } else if (TYPED_ARRAY in data) { + return fromList(TypedArray, data); + } else { + return $from.call(TypedArray, data); + } + hide(that, '_d', { + b: buffer, + o: offset, + l: byteLength, + e: length, + v: new $DataView(buffer) + }); + while (index < length) addElement(that, index++); + }); + TypedArrayPrototype = TypedArray[PROTOTYPE] = create($TypedArrayPrototype$); + hide(TypedArrayPrototype, 'constructor', TypedArray); + } else if (!fails(function () { + TypedArray(1); + }) || !fails(function () { + new TypedArray(-1); // eslint-disable-line no-new + }) || !$iterDetect(function (iter) { + new TypedArray(); // eslint-disable-line no-new + new TypedArray(null); // eslint-disable-line no-new + new TypedArray(1.5); // eslint-disable-line no-new + new TypedArray(iter); // eslint-disable-line no-new + }, true)) { + TypedArray = wrapper(function (that, data, $offset, $length) { + anInstance(that, TypedArray, NAME); + var klass; + // `ws` module bug, temporarily remove validation length for Uint8Array + // https://github.com/websockets/ws/pull/645 + if (!isObject(data)) return new Base(toIndex(data)); + if (data instanceof $ArrayBuffer || (klass = classof(data)) == ARRAY_BUFFER || klass == SHARED_BUFFER) { + return $length !== undefined + ? new Base(data, toOffset($offset, BYTES), $length) + : $offset !== undefined + ? new Base(data, toOffset($offset, BYTES)) + : new Base(data); + } + if (TYPED_ARRAY in data) return fromList(TypedArray, data); + return $from.call(TypedArray, data); + }); + arrayForEach(TAC !== Function.prototype ? gOPN(Base).concat(gOPN(TAC)) : gOPN(Base), function (key) { + if (!(key in TypedArray)) hide(TypedArray, key, Base[key]); + }); + TypedArray[PROTOTYPE] = TypedArrayPrototype; + if (!LIBRARY) TypedArrayPrototype.constructor = TypedArray; + } + var $nativeIterator = TypedArrayPrototype[ITERATOR]; + var CORRECT_ITER_NAME = !!$nativeIterator + && ($nativeIterator.name == 'values' || $nativeIterator.name == undefined); + var $iterator = $iterators.values; + hide(TypedArray, TYPED_CONSTRUCTOR, true); + hide(TypedArrayPrototype, TYPED_ARRAY, NAME); + hide(TypedArrayPrototype, VIEW, true); + hide(TypedArrayPrototype, DEF_CONSTRUCTOR, TypedArray); + + if (CLAMPED ? new TypedArray(1)[TAG] != NAME : !(TAG in TypedArrayPrototype)) { + dP(TypedArrayPrototype, TAG, { + get: function () { return NAME; } + }); + } + + O[NAME] = TypedArray; + + $export($export.G + $export.W + $export.F * (TypedArray != Base), O); + + $export($export.S, NAME, { + BYTES_PER_ELEMENT: BYTES + }); + + $export($export.S + $export.F * fails(function () { Base.of.call(TypedArray, 1); }), NAME, { + from: $from, + of: $of + }); + + if (!(BYTES_PER_ELEMENT in TypedArrayPrototype)) hide(TypedArrayPrototype, BYTES_PER_ELEMENT, BYTES); + + $export($export.P, NAME, proto); + + setSpecies(NAME); + + $export($export.P + $export.F * FORCED_SET, NAME, { set: $set }); + + $export($export.P + $export.F * !CORRECT_ITER_NAME, NAME, $iterators); + + if (!LIBRARY && TypedArrayPrototype.toString != arrayToString) TypedArrayPrototype.toString = arrayToString; + + $export($export.P + $export.F * fails(function () { + new TypedArray(1).slice(); + }), NAME, { slice: $slice }); + + $export($export.P + $export.F * (fails(function () { + return [1, 2].toLocaleString() != new TypedArray([1, 2]).toLocaleString(); + }) || !fails(function () { + TypedArrayPrototype.toLocaleString.call([1, 2]); + })), NAME, { toLocaleString: $toLocaleString }); + + Iterators[NAME] = CORRECT_ITER_NAME ? $nativeIterator : $iterator; + if (!LIBRARY && !CORRECT_ITER_NAME) hide(TypedArrayPrototype, ITERATOR, $iterator); + }; + } else module.exports = function () { /* empty */ }; + + +/***/ }), +/* 231 */ +/***/ (function(module, exports, __webpack_require__) { + + __webpack_require__(230)('Uint8', 1, function (init) { + return function Uint8Array(data, byteOffset, length) { + return init(this, data, byteOffset, length); + }; + }); + + +/***/ }), +/* 232 */ +/***/ (function(module, exports, __webpack_require__) { + + __webpack_require__(230)('Uint8', 1, function (init) { + return function Uint8ClampedArray(data, byteOffset, length) { + return init(this, data, byteOffset, length); + }; + }, true); + + +/***/ }), +/* 233 */ +/***/ (function(module, exports, __webpack_require__) { + + __webpack_require__(230)('Int16', 2, function (init) { + return function Int16Array(data, byteOffset, length) { + return init(this, data, byteOffset, length); + }; + }); + + +/***/ }), +/* 234 */ +/***/ (function(module, exports, __webpack_require__) { + + __webpack_require__(230)('Uint16', 2, function (init) { + return function Uint16Array(data, byteOffset, length) { + return init(this, data, byteOffset, length); + }; + }); + + +/***/ }), +/* 235 */ +/***/ (function(module, exports, __webpack_require__) { + + __webpack_require__(230)('Int32', 4, function (init) { + return function Int32Array(data, byteOffset, length) { + return init(this, data, byteOffset, length); + }; + }); + + +/***/ }), +/* 236 */ +/***/ (function(module, exports, __webpack_require__) { + + __webpack_require__(230)('Uint32', 4, function (init) { + return function Uint32Array(data, byteOffset, length) { + return init(this, data, byteOffset, length); + }; + }); + + +/***/ }), +/* 237 */ +/***/ (function(module, exports, __webpack_require__) { + + __webpack_require__(230)('Float32', 4, function (init) { + return function Float32Array(data, byteOffset, length) { + return init(this, data, byteOffset, length); + }; + }); + + +/***/ }), +/* 238 */ +/***/ (function(module, exports, __webpack_require__) { + + __webpack_require__(230)('Float64', 8, function (init) { + return function Float64Array(data, byteOffset, length) { + return init(this, data, byteOffset, length); + }; + }); + + +/***/ }), +/* 239 */ +/***/ (function(module, exports, __webpack_require__) { + + // 26.1.1 Reflect.apply(target, thisArgument, argumentsList) + var $export = __webpack_require__(8); + var aFunction = __webpack_require__(21); + var anObject = __webpack_require__(12); + var rApply = (__webpack_require__(4).Reflect || {}).apply; + var fApply = Function.apply; + // MS Edge argumentsList argument is optional + $export($export.S + $export.F * !__webpack_require__(7)(function () { + rApply(function () { /* empty */ }); + }), 'Reflect', { + apply: function apply(target, thisArgument, argumentsList) { + var T = aFunction(target); + var L = anObject(argumentsList); + return rApply ? rApply(T, thisArgument, L) : fApply.call(T, thisArgument, L); + } + }); + + +/***/ }), +/* 240 */ +/***/ (function(module, exports, __webpack_require__) { + + // 26.1.2 Reflect.construct(target, argumentsList [, newTarget]) + var $export = __webpack_require__(8); + var create = __webpack_require__(45); + var aFunction = __webpack_require__(21); + var anObject = __webpack_require__(12); + var isObject = __webpack_require__(13); + var fails = __webpack_require__(7); + var bind = __webpack_require__(76); + var rConstruct = (__webpack_require__(4).Reflect || {}).construct; + + // MS Edge supports only 2 arguments and argumentsList argument is optional + // FF Nightly sets third argument as `new.target`, but does not create `this` from it + var NEW_TARGET_BUG = fails(function () { + function F() { /* empty */ } + return !(rConstruct(function () { /* empty */ }, [], F) instanceof F); + }); + var ARGS_BUG = !fails(function () { + rConstruct(function () { /* empty */ }); + }); + + $export($export.S + $export.F * (NEW_TARGET_BUG || ARGS_BUG), 'Reflect', { + construct: function construct(Target, args /* , newTarget */) { + aFunction(Target); + anObject(args); + var newTarget = arguments.length < 3 ? Target : aFunction(arguments[2]); + if (ARGS_BUG && !NEW_TARGET_BUG) return rConstruct(Target, args, newTarget); + if (Target == newTarget) { + // w/o altered newTarget, optimization for 0-4 arguments + switch (args.length) { + case 0: return new Target(); + case 1: return new Target(args[0]); + case 2: return new Target(args[0], args[1]); + case 3: return new Target(args[0], args[1], args[2]); + case 4: return new Target(args[0], args[1], args[2], args[3]); + } + // w/o altered newTarget, lot of arguments case + var $args = [null]; + $args.push.apply($args, args); + return new (bind.apply(Target, $args))(); + } + // with altered newTarget, not support built-in constructors + var proto = newTarget.prototype; + var instance = create(isObject(proto) ? proto : Object.prototype); + var result = Function.apply.call(Target, instance, args); + return isObject(result) ? result : instance; + } + }); + + +/***/ }), +/* 241 */ +/***/ (function(module, exports, __webpack_require__) { + + // 26.1.3 Reflect.defineProperty(target, propertyKey, attributes) + var dP = __webpack_require__(11); + var $export = __webpack_require__(8); + var anObject = __webpack_require__(12); + var toPrimitive = __webpack_require__(16); + + // MS Edge has broken Reflect.defineProperty - throwing instead of returning false + $export($export.S + $export.F * __webpack_require__(7)(function () { + // eslint-disable-next-line no-undef + Reflect.defineProperty(dP.f({}, 1, { value: 1 }), 1, { value: 2 }); + }), 'Reflect', { + defineProperty: function defineProperty(target, propertyKey, attributes) { + anObject(target); + propertyKey = toPrimitive(propertyKey, true); + anObject(attributes); + try { + dP.f(target, propertyKey, attributes); + return true; + } catch (e) { + return false; + } + } + }); + + +/***/ }), +/* 242 */ +/***/ (function(module, exports, __webpack_require__) { + + // 26.1.4 Reflect.deleteProperty(target, propertyKey) + var $export = __webpack_require__(8); + var gOPD = __webpack_require__(50).f; + var anObject = __webpack_require__(12); + + $export($export.S, 'Reflect', { + deleteProperty: function deleteProperty(target, propertyKey) { + var desc = gOPD(anObject(target), propertyKey); + return desc && !desc.configurable ? false : delete target[propertyKey]; + } + }); + + +/***/ }), +/* 243 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // 26.1.5 Reflect.enumerate(target) + var $export = __webpack_require__(8); + var anObject = __webpack_require__(12); + var Enumerate = function (iterated) { + this._t = anObject(iterated); // target + this._i = 0; // next index + var keys = this._k = []; // keys + var key; + for (key in iterated) keys.push(key); + }; + __webpack_require__(130)(Enumerate, 'Object', function () { + var that = this; + var keys = that._k; + var key; + do { + if (that._i >= keys.length) return { value: undefined, done: true }; + } while (!((key = keys[that._i++]) in that._t)); + return { value: key, done: false }; + }); + + $export($export.S, 'Reflect', { + enumerate: function enumerate(target) { + return new Enumerate(target); + } + }); + + +/***/ }), +/* 244 */ +/***/ (function(module, exports, __webpack_require__) { + + // 26.1.6 Reflect.get(target, propertyKey [, receiver]) + var gOPD = __webpack_require__(50); + var getPrototypeOf = __webpack_require__(58); + var has = __webpack_require__(5); + var $export = __webpack_require__(8); + var isObject = __webpack_require__(13); + var anObject = __webpack_require__(12); + + function get(target, propertyKey /* , receiver */) { + var receiver = arguments.length < 3 ? target : arguments[2]; + var desc, proto; + if (anObject(target) === receiver) return target[propertyKey]; + if (desc = gOPD.f(target, propertyKey)) return has(desc, 'value') + ? desc.value + : desc.get !== undefined + ? desc.get.call(receiver) + : undefined; + if (isObject(proto = getPrototypeOf(target))) return get(proto, propertyKey, receiver); + } + + $export($export.S, 'Reflect', { get: get }); + + +/***/ }), +/* 245 */ +/***/ (function(module, exports, __webpack_require__) { + + // 26.1.7 Reflect.getOwnPropertyDescriptor(target, propertyKey) + var gOPD = __webpack_require__(50); + var $export = __webpack_require__(8); + var anObject = __webpack_require__(12); + + $export($export.S, 'Reflect', { + getOwnPropertyDescriptor: function getOwnPropertyDescriptor(target, propertyKey) { + return gOPD.f(anObject(target), propertyKey); + } + }); + + +/***/ }), +/* 246 */ +/***/ (function(module, exports, __webpack_require__) { + + // 26.1.8 Reflect.getPrototypeOf(target) + var $export = __webpack_require__(8); + var getProto = __webpack_require__(58); + var anObject = __webpack_require__(12); + + $export($export.S, 'Reflect', { + getPrototypeOf: function getPrototypeOf(target) { + return getProto(anObject(target)); + } + }); + + +/***/ }), +/* 247 */ +/***/ (function(module, exports, __webpack_require__) { + + // 26.1.9 Reflect.has(target, propertyKey) + var $export = __webpack_require__(8); + + $export($export.S, 'Reflect', { + has: function has(target, propertyKey) { + return propertyKey in target; + } + }); + + +/***/ }), +/* 248 */ +/***/ (function(module, exports, __webpack_require__) { + + // 26.1.10 Reflect.isExtensible(target) + var $export = __webpack_require__(8); + var anObject = __webpack_require__(12); + var $isExtensible = Object.isExtensible; + + $export($export.S, 'Reflect', { + isExtensible: function isExtensible(target) { + anObject(target); + return $isExtensible ? $isExtensible(target) : true; + } + }); + + +/***/ }), +/* 249 */ +/***/ (function(module, exports, __webpack_require__) { + + // 26.1.11 Reflect.ownKeys(target) + var $export = __webpack_require__(8); + + $export($export.S, 'Reflect', { ownKeys: __webpack_require__(250) }); + + +/***/ }), +/* 250 */ +/***/ (function(module, exports, __webpack_require__) { + + // all object keys, includes non-enumerable and symbols + var gOPN = __webpack_require__(49); + var gOPS = __webpack_require__(42); + var anObject = __webpack_require__(12); + var Reflect = __webpack_require__(4).Reflect; + module.exports = Reflect && Reflect.ownKeys || function ownKeys(it) { + var keys = gOPN.f(anObject(it)); + var getSymbols = gOPS.f; + return getSymbols ? keys.concat(getSymbols(it)) : keys; + }; + + +/***/ }), +/* 251 */ +/***/ (function(module, exports, __webpack_require__) { + + // 26.1.12 Reflect.preventExtensions(target) + var $export = __webpack_require__(8); + var anObject = __webpack_require__(12); + var $preventExtensions = Object.preventExtensions; + + $export($export.S, 'Reflect', { + preventExtensions: function preventExtensions(target) { + anObject(target); + try { + if ($preventExtensions) $preventExtensions(target); + return true; + } catch (e) { + return false; + } + } + }); + + +/***/ }), +/* 252 */ +/***/ (function(module, exports, __webpack_require__) { + + // 26.1.13 Reflect.set(target, propertyKey, V [, receiver]) + var dP = __webpack_require__(11); + var gOPD = __webpack_require__(50); + var getPrototypeOf = __webpack_require__(58); + var has = __webpack_require__(5); + var $export = __webpack_require__(8); + var createDesc = __webpack_require__(17); + var anObject = __webpack_require__(12); + var isObject = __webpack_require__(13); + + function set(target, propertyKey, V /* , receiver */) { + var receiver = arguments.length < 4 ? target : arguments[3]; + var ownDesc = gOPD.f(anObject(target), propertyKey); + var existingDescriptor, proto; + if (!ownDesc) { + if (isObject(proto = getPrototypeOf(target))) { + return set(proto, propertyKey, V, receiver); + } + ownDesc = createDesc(0); + } + if (has(ownDesc, 'value')) { + if (ownDesc.writable === false || !isObject(receiver)) return false; + if (existingDescriptor = gOPD.f(receiver, propertyKey)) { + if (existingDescriptor.get || existingDescriptor.set || existingDescriptor.writable === false) return false; + existingDescriptor.value = V; + dP.f(receiver, propertyKey, existingDescriptor); + } else dP.f(receiver, propertyKey, createDesc(0, V)); + return true; + } + return ownDesc.set === undefined ? false : (ownDesc.set.call(receiver, V), true); + } + + $export($export.S, 'Reflect', { set: set }); + + +/***/ }), +/* 253 */ +/***/ (function(module, exports, __webpack_require__) { + + // 26.1.14 Reflect.setPrototypeOf(target, proto) + var $export = __webpack_require__(8); + var setProto = __webpack_require__(72); + + if (setProto) $export($export.S, 'Reflect', { + setPrototypeOf: function setPrototypeOf(target, proto) { + setProto.check(target, proto); + try { + setProto.set(target, proto); + return true; + } catch (e) { + return false; + } + } + }); + + +/***/ }), +/* 254 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // https://github.com/tc39/Array.prototype.includes + var $export = __webpack_require__(8); + var $includes = __webpack_require__(36)(true); + + $export($export.P, 'Array', { + includes: function includes(el /* , fromIndex = 0 */) { + return $includes(this, el, arguments.length > 1 ? arguments[1] : undefined); + } + }); + + __webpack_require__(187)('includes'); + + +/***/ }), +/* 255 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // https://tc39.github.io/proposal-flatMap/#sec-Array.prototype.flatMap + var $export = __webpack_require__(8); + var flattenIntoArray = __webpack_require__(256); + var toObject = __webpack_require__(57); + var toLength = __webpack_require__(37); + var aFunction = __webpack_require__(21); + var arraySpeciesCreate = __webpack_require__(174); + + $export($export.P, 'Array', { + flatMap: function flatMap(callbackfn /* , thisArg */) { + var O = toObject(this); + var sourceLen, A; + aFunction(callbackfn); + sourceLen = toLength(O.length); + A = arraySpeciesCreate(O, 0); + flattenIntoArray(A, O, O, sourceLen, 0, 1, callbackfn, arguments[1]); + return A; + } + }); + + __webpack_require__(187)('flatMap'); + + +/***/ }), +/* 256 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // https://tc39.github.io/proposal-flatMap/#sec-FlattenIntoArray + var isArray = __webpack_require__(44); + var isObject = __webpack_require__(13); + var toLength = __webpack_require__(37); + var ctx = __webpack_require__(20); + var IS_CONCAT_SPREADABLE = __webpack_require__(26)('isConcatSpreadable'); + + function flattenIntoArray(target, original, source, sourceLen, start, depth, mapper, thisArg) { + var targetIndex = start; + var sourceIndex = 0; + var mapFn = mapper ? ctx(mapper, thisArg, 3) : false; + var element, spreadable; + + while (sourceIndex < sourceLen) { + if (sourceIndex in source) { + element = mapFn ? mapFn(source[sourceIndex], sourceIndex, original) : source[sourceIndex]; + + spreadable = false; + if (isObject(element)) { + spreadable = element[IS_CONCAT_SPREADABLE]; + spreadable = spreadable !== undefined ? !!spreadable : isArray(element); + } + + if (spreadable && depth > 0) { + targetIndex = flattenIntoArray(target, original, element, toLength(element.length), targetIndex, depth - 1) - 1; + } else { + if (targetIndex >= 0x1fffffffffffff) throw TypeError(); + target[targetIndex] = element; + } + + targetIndex++; + } + sourceIndex++; + } + return targetIndex; + } + + module.exports = flattenIntoArray; + + +/***/ }), +/* 257 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // https://tc39.github.io/proposal-flatMap/#sec-Array.prototype.flatten + var $export = __webpack_require__(8); + var flattenIntoArray = __webpack_require__(256); + var toObject = __webpack_require__(57); + var toLength = __webpack_require__(37); + var toInteger = __webpack_require__(38); + var arraySpeciesCreate = __webpack_require__(174); + + $export($export.P, 'Array', { + flatten: function flatten(/* depthArg = 1 */) { + var depthArg = arguments[0]; + var O = toObject(this); + var sourceLen = toLength(O.length); + var A = arraySpeciesCreate(O, 0); + flattenIntoArray(A, O, O, sourceLen, 0, depthArg === undefined ? 1 : toInteger(depthArg)); + return A; + } + }); + + __webpack_require__(187)('flatten'); + + +/***/ }), +/* 258 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // https://github.com/mathiasbynens/String.prototype.at + var $export = __webpack_require__(8); + var $at = __webpack_require__(127)(true); + + $export($export.P, 'String', { + at: function at(pos) { + return $at(this, pos); + } + }); + + +/***/ }), +/* 259 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // https://github.com/tc39/proposal-string-pad-start-end + var $export = __webpack_require__(8); + var $pad = __webpack_require__(260); + var userAgent = __webpack_require__(213); + + // https://github.com/zloirock/core-js/issues/280 + $export($export.P + $export.F * /Version\/10\.\d+(\.\d+)? Safari\//.test(userAgent), 'String', { + padStart: function padStart(maxLength /* , fillString = ' ' */) { + return $pad(this, maxLength, arguments.length > 1 ? arguments[1] : undefined, true); + } + }); + + +/***/ }), +/* 260 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://github.com/tc39/proposal-string-pad-start-end + var toLength = __webpack_require__(37); + var repeat = __webpack_require__(90); + var defined = __webpack_require__(35); + + module.exports = function (that, maxLength, fillString, left) { + var S = String(defined(that)); + var stringLength = S.length; + var fillStr = fillString === undefined ? ' ' : String(fillString); + var intMaxLength = toLength(maxLength); + if (intMaxLength <= stringLength || fillStr == '') return S; + var fillLen = intMaxLength - stringLength; + var stringFiller = repeat.call(fillStr, Math.ceil(fillLen / fillStr.length)); + if (stringFiller.length > fillLen) stringFiller = stringFiller.slice(0, fillLen); + return left ? stringFiller + S : S + stringFiller; + }; + + +/***/ }), +/* 261 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // https://github.com/tc39/proposal-string-pad-start-end + var $export = __webpack_require__(8); + var $pad = __webpack_require__(260); + var userAgent = __webpack_require__(213); + + // https://github.com/zloirock/core-js/issues/280 + $export($export.P + $export.F * /Version\/10\.\d+(\.\d+)? Safari\//.test(userAgent), 'String', { + padEnd: function padEnd(maxLength /* , fillString = ' ' */) { + return $pad(this, maxLength, arguments.length > 1 ? arguments[1] : undefined, false); + } + }); + + +/***/ }), +/* 262 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // https://github.com/sebmarkbage/ecmascript-string-left-right-trim + __webpack_require__(82)('trimLeft', function ($trim) { + return function trimLeft() { + return $trim(this, 1); + }; + }, 'trimStart'); + + +/***/ }), +/* 263 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // https://github.com/sebmarkbage/ecmascript-string-left-right-trim + __webpack_require__(82)('trimRight', function ($trim) { + return function trimRight() { + return $trim(this, 2); + }; + }, 'trimEnd'); + + +/***/ }), +/* 264 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // https://tc39.github.io/String.prototype.matchAll/ + var $export = __webpack_require__(8); + var defined = __webpack_require__(35); + var toLength = __webpack_require__(37); + var isRegExp = __webpack_require__(134); + var getFlags = __webpack_require__(197); + var RegExpProto = RegExp.prototype; + + var $RegExpStringIterator = function (regexp, string) { + this._r = regexp; + this._s = string; + }; + + __webpack_require__(130)($RegExpStringIterator, 'RegExp String', function next() { + var match = this._r.exec(this._s); + return { value: match, done: match === null }; + }); + + $export($export.P, 'String', { + matchAll: function matchAll(regexp) { + defined(this); + if (!isRegExp(regexp)) throw TypeError(regexp + ' is not a regexp!'); + var S = String(this); + var flags = 'flags' in RegExpProto ? String(regexp.flags) : getFlags.call(regexp); + var rx = new RegExp(regexp.source, ~flags.indexOf('g') ? flags : 'g' + flags); + rx.lastIndex = toLength(regexp.lastIndex); + return new $RegExpStringIterator(rx, S); + } + }); + + +/***/ }), +/* 265 */ +/***/ (function(module, exports, __webpack_require__) { + + __webpack_require__(28)('asyncIterator'); + + +/***/ }), +/* 266 */ +/***/ (function(module, exports, __webpack_require__) { + + __webpack_require__(28)('observable'); + + +/***/ }), +/* 267 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://github.com/tc39/proposal-object-getownpropertydescriptors + var $export = __webpack_require__(8); + var ownKeys = __webpack_require__(250); + var toIObject = __webpack_require__(32); + var gOPD = __webpack_require__(50); + var createProperty = __webpack_require__(164); + + $export($export.S, 'Object', { + getOwnPropertyDescriptors: function getOwnPropertyDescriptors(object) { + var O = toIObject(object); + var getDesc = gOPD.f; + var keys = ownKeys(O); + var result = {}; + var i = 0; + var key, desc; + while (keys.length > i) { + desc = getDesc(O, key = keys[i++]); + if (desc !== undefined) createProperty(result, key, desc); + } + return result; + } + }); + + +/***/ }), +/* 268 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://github.com/tc39/proposal-object-values-entries + var $export = __webpack_require__(8); + var $values = __webpack_require__(269)(false); + + $export($export.S, 'Object', { + values: function values(it) { + return $values(it); + } + }); + + +/***/ }), +/* 269 */ +/***/ (function(module, exports, __webpack_require__) { + + var getKeys = __webpack_require__(30); + var toIObject = __webpack_require__(32); + var isEnum = __webpack_require__(43).f; + module.exports = function (isEntries) { + return function (it) { + var O = toIObject(it); + var keys = getKeys(O); + var length = keys.length; + var i = 0; + var result = []; + var key; + while (length > i) if (isEnum.call(O, key = keys[i++])) { + result.push(isEntries ? [key, O[key]] : O[key]); + } return result; + }; + }; + + +/***/ }), +/* 270 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://github.com/tc39/proposal-object-values-entries + var $export = __webpack_require__(8); + var $entries = __webpack_require__(269)(true); + + $export($export.S, 'Object', { + entries: function entries(it) { + return $entries(it); + } + }); + + +/***/ }), +/* 271 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var toObject = __webpack_require__(57); + var aFunction = __webpack_require__(21); + var $defineProperty = __webpack_require__(11); + + // B.2.2.2 Object.prototype.__defineGetter__(P, getter) + __webpack_require__(6) && $export($export.P + __webpack_require__(272), 'Object', { + __defineGetter__: function __defineGetter__(P, getter) { + $defineProperty.f(toObject(this), P, { get: aFunction(getter), enumerable: true, configurable: true }); + } + }); + + +/***/ }), +/* 272 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // Forced replacement prototype accessors methods + module.exports = __webpack_require__(24) || !__webpack_require__(7)(function () { + var K = Math.random(); + // In FF throws only define methods + // eslint-disable-next-line no-undef, no-useless-call + __defineSetter__.call(null, K, function () { /* empty */ }); + delete __webpack_require__(4)[K]; + }); + + +/***/ }), +/* 273 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var toObject = __webpack_require__(57); + var aFunction = __webpack_require__(21); + var $defineProperty = __webpack_require__(11); + + // B.2.2.3 Object.prototype.__defineSetter__(P, setter) + __webpack_require__(6) && $export($export.P + __webpack_require__(272), 'Object', { + __defineSetter__: function __defineSetter__(P, setter) { + $defineProperty.f(toObject(this), P, { set: aFunction(setter), enumerable: true, configurable: true }); + } + }); + + +/***/ }), +/* 274 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var toObject = __webpack_require__(57); + var toPrimitive = __webpack_require__(16); + var getPrototypeOf = __webpack_require__(58); + var getOwnPropertyDescriptor = __webpack_require__(50).f; + + // B.2.2.4 Object.prototype.__lookupGetter__(P) + __webpack_require__(6) && $export($export.P + __webpack_require__(272), 'Object', { + __lookupGetter__: function __lookupGetter__(P) { + var O = toObject(this); + var K = toPrimitive(P, true); + var D; + do { + if (D = getOwnPropertyDescriptor(O, K)) return D.get; + } while (O = getPrototypeOf(O)); + } + }); + + +/***/ }), +/* 275 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + var $export = __webpack_require__(8); + var toObject = __webpack_require__(57); + var toPrimitive = __webpack_require__(16); + var getPrototypeOf = __webpack_require__(58); + var getOwnPropertyDescriptor = __webpack_require__(50).f; + + // B.2.2.5 Object.prototype.__lookupSetter__(P) + __webpack_require__(6) && $export($export.P + __webpack_require__(272), 'Object', { + __lookupSetter__: function __lookupSetter__(P) { + var O = toObject(this); + var K = toPrimitive(P, true); + var D; + do { + if (D = getOwnPropertyDescriptor(O, K)) return D.set; + } while (O = getPrototypeOf(O)); + } + }); + + +/***/ }), +/* 276 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://github.com/DavidBruant/Map-Set.prototype.toJSON + var $export = __webpack_require__(8); + + $export($export.P + $export.R, 'Map', { toJSON: __webpack_require__(277)('Map') }); + + +/***/ }), +/* 277 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://github.com/DavidBruant/Map-Set.prototype.toJSON + var classof = __webpack_require__(74); + var from = __webpack_require__(278); + module.exports = function (NAME) { + return function toJSON() { + if (classof(this) != NAME) throw TypeError(NAME + "#toJSON isn't generic"); + return from(this); + }; + }; + + +/***/ }), +/* 278 */ +/***/ (function(module, exports, __webpack_require__) { + + var forOf = __webpack_require__(207); + + module.exports = function (iter, ITERATOR) { + var result = []; + forOf(iter, false, result.push, result, ITERATOR); + return result; + }; + + +/***/ }), +/* 279 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://github.com/DavidBruant/Map-Set.prototype.toJSON + var $export = __webpack_require__(8); + + $export($export.P + $export.R, 'Set', { toJSON: __webpack_require__(277)('Set') }); + + +/***/ }), +/* 280 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://tc39.github.io/proposal-setmap-offrom/#sec-map.of + __webpack_require__(281)('Map'); + + +/***/ }), +/* 281 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // https://tc39.github.io/proposal-setmap-offrom/ + var $export = __webpack_require__(8); + + module.exports = function (COLLECTION) { + $export($export.S, COLLECTION, { of: function of() { + var length = arguments.length; + var A = new Array(length); + while (length--) A[length] = arguments[length]; + return new this(A); + } }); + }; + + +/***/ }), +/* 282 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://tc39.github.io/proposal-setmap-offrom/#sec-set.of + __webpack_require__(281)('Set'); + + +/***/ }), +/* 283 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://tc39.github.io/proposal-setmap-offrom/#sec-weakmap.of + __webpack_require__(281)('WeakMap'); + + +/***/ }), +/* 284 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://tc39.github.io/proposal-setmap-offrom/#sec-weakset.of + __webpack_require__(281)('WeakSet'); + + +/***/ }), +/* 285 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://tc39.github.io/proposal-setmap-offrom/#sec-map.from + __webpack_require__(286)('Map'); + + +/***/ }), +/* 286 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // https://tc39.github.io/proposal-setmap-offrom/ + var $export = __webpack_require__(8); + var aFunction = __webpack_require__(21); + var ctx = __webpack_require__(20); + var forOf = __webpack_require__(207); + + module.exports = function (COLLECTION) { + $export($export.S, COLLECTION, { from: function from(source /* , mapFn, thisArg */) { + var mapFn = arguments[1]; + var mapping, A, n, cb; + aFunction(this); + mapping = mapFn !== undefined; + if (mapping) aFunction(mapFn); + if (source == undefined) return new this(); + A = []; + if (mapping) { + n = 0; + cb = ctx(mapFn, arguments[2], 2); + forOf(source, false, function (nextItem) { + A.push(cb(nextItem, n++)); + }); + } else { + forOf(source, false, A.push, A); + } + return new this(A); + } }); + }; + + +/***/ }), +/* 287 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://tc39.github.io/proposal-setmap-offrom/#sec-set.from + __webpack_require__(286)('Set'); + + +/***/ }), +/* 288 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://tc39.github.io/proposal-setmap-offrom/#sec-weakmap.from + __webpack_require__(286)('WeakMap'); + + +/***/ }), +/* 289 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://tc39.github.io/proposal-setmap-offrom/#sec-weakset.from + __webpack_require__(286)('WeakSet'); + + +/***/ }), +/* 290 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://github.com/tc39/proposal-global + var $export = __webpack_require__(8); + + $export($export.G, { global: __webpack_require__(4) }); + + +/***/ }), +/* 291 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://github.com/tc39/proposal-global + var $export = __webpack_require__(8); + + $export($export.S, 'System', { global: __webpack_require__(4) }); + + +/***/ }), +/* 292 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://github.com/ljharb/proposal-is-error + var $export = __webpack_require__(8); + var cof = __webpack_require__(34); + + $export($export.S, 'Error', { + isError: function isError(it) { + return cof(it) === 'Error'; + } + }); + + +/***/ }), +/* 293 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://rwaldron.github.io/proposal-math-extensions/ + var $export = __webpack_require__(8); + + $export($export.S, 'Math', { + clamp: function clamp(x, lower, upper) { + return Math.min(upper, Math.max(lower, x)); + } + }); + + +/***/ }), +/* 294 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://rwaldron.github.io/proposal-math-extensions/ + var $export = __webpack_require__(8); + + $export($export.S, 'Math', { DEG_PER_RAD: Math.PI / 180 }); + + +/***/ }), +/* 295 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://rwaldron.github.io/proposal-math-extensions/ + var $export = __webpack_require__(8); + var RAD_PER_DEG = 180 / Math.PI; + + $export($export.S, 'Math', { + degrees: function degrees(radians) { + return radians * RAD_PER_DEG; + } + }); + + +/***/ }), +/* 296 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://rwaldron.github.io/proposal-math-extensions/ + var $export = __webpack_require__(8); + var scale = __webpack_require__(297); + var fround = __webpack_require__(113); + + $export($export.S, 'Math', { + fscale: function fscale(x, inLow, inHigh, outLow, outHigh) { + return fround(scale(x, inLow, inHigh, outLow, outHigh)); + } + }); + + +/***/ }), +/* 297 */ +/***/ (function(module, exports) { + + // https://rwaldron.github.io/proposal-math-extensions/ + module.exports = Math.scale || function scale(x, inLow, inHigh, outLow, outHigh) { + if ( + arguments.length === 0 + // eslint-disable-next-line no-self-compare + || x != x + // eslint-disable-next-line no-self-compare + || inLow != inLow + // eslint-disable-next-line no-self-compare + || inHigh != inHigh + // eslint-disable-next-line no-self-compare + || outLow != outLow + // eslint-disable-next-line no-self-compare + || outHigh != outHigh + ) return NaN; + if (x === Infinity || x === -Infinity) return x; + return (x - inLow) * (outHigh - outLow) / (inHigh - inLow) + outLow; + }; + + +/***/ }), +/* 298 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://gist.github.com/BrendanEich/4294d5c212a6d2254703 + var $export = __webpack_require__(8); + + $export($export.S, 'Math', { + iaddh: function iaddh(x0, x1, y0, y1) { + var $x0 = x0 >>> 0; + var $x1 = x1 >>> 0; + var $y0 = y0 >>> 0; + return $x1 + (y1 >>> 0) + (($x0 & $y0 | ($x0 | $y0) & ~($x0 + $y0 >>> 0)) >>> 31) | 0; + } + }); + + +/***/ }), +/* 299 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://gist.github.com/BrendanEich/4294d5c212a6d2254703 + var $export = __webpack_require__(8); + + $export($export.S, 'Math', { + isubh: function isubh(x0, x1, y0, y1) { + var $x0 = x0 >>> 0; + var $x1 = x1 >>> 0; + var $y0 = y0 >>> 0; + return $x1 - (y1 >>> 0) - ((~$x0 & $y0 | ~($x0 ^ $y0) & $x0 - $y0 >>> 0) >>> 31) | 0; + } + }); + + +/***/ }), +/* 300 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://gist.github.com/BrendanEich/4294d5c212a6d2254703 + var $export = __webpack_require__(8); + + $export($export.S, 'Math', { + imulh: function imulh(u, v) { + var UINT16 = 0xffff; + var $u = +u; + var $v = +v; + var u0 = $u & UINT16; + var v0 = $v & UINT16; + var u1 = $u >> 16; + var v1 = $v >> 16; + var t = (u1 * v0 >>> 0) + (u0 * v0 >>> 16); + return u1 * v1 + (t >> 16) + ((u0 * v1 >>> 0) + (t & UINT16) >> 16); + } + }); + + +/***/ }), +/* 301 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://rwaldron.github.io/proposal-math-extensions/ + var $export = __webpack_require__(8); + + $export($export.S, 'Math', { RAD_PER_DEG: 180 / Math.PI }); + + +/***/ }), +/* 302 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://rwaldron.github.io/proposal-math-extensions/ + var $export = __webpack_require__(8); + var DEG_PER_RAD = Math.PI / 180; + + $export($export.S, 'Math', { + radians: function radians(degrees) { + return degrees * DEG_PER_RAD; + } + }); + + +/***/ }), +/* 303 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://rwaldron.github.io/proposal-math-extensions/ + var $export = __webpack_require__(8); + + $export($export.S, 'Math', { scale: __webpack_require__(297) }); + + +/***/ }), +/* 304 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://gist.github.com/BrendanEich/4294d5c212a6d2254703 + var $export = __webpack_require__(8); + + $export($export.S, 'Math', { + umulh: function umulh(u, v) { + var UINT16 = 0xffff; + var $u = +u; + var $v = +v; + var u0 = $u & UINT16; + var v0 = $v & UINT16; + var u1 = $u >>> 16; + var v1 = $v >>> 16; + var t = (u1 * v0 >>> 0) + (u0 * v0 >>> 16); + return u1 * v1 + (t >>> 16) + ((u0 * v1 >>> 0) + (t & UINT16) >>> 16); + } + }); + + +/***/ }), +/* 305 */ +/***/ (function(module, exports, __webpack_require__) { + + // http://jfbastien.github.io/papers/Math.signbit.html + var $export = __webpack_require__(8); + + $export($export.S, 'Math', { signbit: function signbit(x) { + // eslint-disable-next-line no-self-compare + return (x = +x) != x ? x : x == 0 ? 1 / x == Infinity : x > 0; + } }); + + +/***/ }), +/* 306 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://github.com/tc39/proposal-promise-finally + 'use strict'; + var $export = __webpack_require__(8); + var core = __webpack_require__(9); + var global = __webpack_require__(4); + var speciesConstructor = __webpack_require__(208); + var promiseResolve = __webpack_require__(214); + + $export($export.P + $export.R, 'Promise', { 'finally': function (onFinally) { + var C = speciesConstructor(this, core.Promise || global.Promise); + var isFunction = typeof onFinally == 'function'; + return this.then( + isFunction ? function (x) { + return promiseResolve(C, onFinally()).then(function () { return x; }); + } : onFinally, + isFunction ? function (e) { + return promiseResolve(C, onFinally()).then(function () { throw e; }); + } : onFinally + ); + } }); + + +/***/ }), +/* 307 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // https://github.com/tc39/proposal-promise-try + var $export = __webpack_require__(8); + var newPromiseCapability = __webpack_require__(211); + var perform = __webpack_require__(212); + + $export($export.S, 'Promise', { 'try': function (callbackfn) { + var promiseCapability = newPromiseCapability.f(this); + var result = perform(callbackfn); + (result.e ? promiseCapability.reject : promiseCapability.resolve)(result.v); + return promiseCapability.promise; + } }); + + +/***/ }), +/* 308 */ +/***/ (function(module, exports, __webpack_require__) { + + var metadata = __webpack_require__(309); + var anObject = __webpack_require__(12); + var toMetaKey = metadata.key; + var ordinaryDefineOwnMetadata = metadata.set; + + metadata.exp({ defineMetadata: function defineMetadata(metadataKey, metadataValue, target, targetKey) { + ordinaryDefineOwnMetadata(metadataKey, metadataValue, anObject(target), toMetaKey(targetKey)); + } }); + + +/***/ }), +/* 309 */ +/***/ (function(module, exports, __webpack_require__) { + + var Map = __webpack_require__(216); + var $export = __webpack_require__(8); + var shared = __webpack_require__(23)('metadata'); + var store = shared.store || (shared.store = new (__webpack_require__(221))()); + + var getOrCreateMetadataMap = function (target, targetKey, create) { + var targetMetadata = store.get(target); + if (!targetMetadata) { + if (!create) return undefined; + store.set(target, targetMetadata = new Map()); + } + var keyMetadata = targetMetadata.get(targetKey); + if (!keyMetadata) { + if (!create) return undefined; + targetMetadata.set(targetKey, keyMetadata = new Map()); + } return keyMetadata; + }; + var ordinaryHasOwnMetadata = function (MetadataKey, O, P) { + var metadataMap = getOrCreateMetadataMap(O, P, false); + return metadataMap === undefined ? false : metadataMap.has(MetadataKey); + }; + var ordinaryGetOwnMetadata = function (MetadataKey, O, P) { + var metadataMap = getOrCreateMetadataMap(O, P, false); + return metadataMap === undefined ? undefined : metadataMap.get(MetadataKey); + }; + var ordinaryDefineOwnMetadata = function (MetadataKey, MetadataValue, O, P) { + getOrCreateMetadataMap(O, P, true).set(MetadataKey, MetadataValue); + }; + var ordinaryOwnMetadataKeys = function (target, targetKey) { + var metadataMap = getOrCreateMetadataMap(target, targetKey, false); + var keys = []; + if (metadataMap) metadataMap.forEach(function (_, key) { keys.push(key); }); + return keys; + }; + var toMetaKey = function (it) { + return it === undefined || typeof it == 'symbol' ? it : String(it); + }; + var exp = function (O) { + $export($export.S, 'Reflect', O); + }; + + module.exports = { + store: store, + map: getOrCreateMetadataMap, + has: ordinaryHasOwnMetadata, + get: ordinaryGetOwnMetadata, + set: ordinaryDefineOwnMetadata, + keys: ordinaryOwnMetadataKeys, + key: toMetaKey, + exp: exp + }; + + +/***/ }), +/* 310 */ +/***/ (function(module, exports, __webpack_require__) { + + var metadata = __webpack_require__(309); + var anObject = __webpack_require__(12); + var toMetaKey = metadata.key; + var getOrCreateMetadataMap = metadata.map; + var store = metadata.store; + + metadata.exp({ deleteMetadata: function deleteMetadata(metadataKey, target /* , targetKey */) { + var targetKey = arguments.length < 3 ? undefined : toMetaKey(arguments[2]); + var metadataMap = getOrCreateMetadataMap(anObject(target), targetKey, false); + if (metadataMap === undefined || !metadataMap['delete'](metadataKey)) return false; + if (metadataMap.size) return true; + var targetMetadata = store.get(target); + targetMetadata['delete'](targetKey); + return !!targetMetadata.size || store['delete'](target); + } }); + + +/***/ }), +/* 311 */ +/***/ (function(module, exports, __webpack_require__) { + + var metadata = __webpack_require__(309); + var anObject = __webpack_require__(12); + var getPrototypeOf = __webpack_require__(58); + var ordinaryHasOwnMetadata = metadata.has; + var ordinaryGetOwnMetadata = metadata.get; + var toMetaKey = metadata.key; + + var ordinaryGetMetadata = function (MetadataKey, O, P) { + var hasOwn = ordinaryHasOwnMetadata(MetadataKey, O, P); + if (hasOwn) return ordinaryGetOwnMetadata(MetadataKey, O, P); + var parent = getPrototypeOf(O); + return parent !== null ? ordinaryGetMetadata(MetadataKey, parent, P) : undefined; + }; + + metadata.exp({ getMetadata: function getMetadata(metadataKey, target /* , targetKey */) { + return ordinaryGetMetadata(metadataKey, anObject(target), arguments.length < 3 ? undefined : toMetaKey(arguments[2])); + } }); + + +/***/ }), +/* 312 */ +/***/ (function(module, exports, __webpack_require__) { + + var Set = __webpack_require__(220); + var from = __webpack_require__(278); + var metadata = __webpack_require__(309); + var anObject = __webpack_require__(12); + var getPrototypeOf = __webpack_require__(58); + var ordinaryOwnMetadataKeys = metadata.keys; + var toMetaKey = metadata.key; + + var ordinaryMetadataKeys = function (O, P) { + var oKeys = ordinaryOwnMetadataKeys(O, P); + var parent = getPrototypeOf(O); + if (parent === null) return oKeys; + var pKeys = ordinaryMetadataKeys(parent, P); + return pKeys.length ? oKeys.length ? from(new Set(oKeys.concat(pKeys))) : pKeys : oKeys; + }; + + metadata.exp({ getMetadataKeys: function getMetadataKeys(target /* , targetKey */) { + return ordinaryMetadataKeys(anObject(target), arguments.length < 2 ? undefined : toMetaKey(arguments[1])); + } }); + + +/***/ }), +/* 313 */ +/***/ (function(module, exports, __webpack_require__) { + + var metadata = __webpack_require__(309); + var anObject = __webpack_require__(12); + var ordinaryGetOwnMetadata = metadata.get; + var toMetaKey = metadata.key; + + metadata.exp({ getOwnMetadata: function getOwnMetadata(metadataKey, target /* , targetKey */) { + return ordinaryGetOwnMetadata(metadataKey, anObject(target) + , arguments.length < 3 ? undefined : toMetaKey(arguments[2])); + } }); + + +/***/ }), +/* 314 */ +/***/ (function(module, exports, __webpack_require__) { + + var metadata = __webpack_require__(309); + var anObject = __webpack_require__(12); + var ordinaryOwnMetadataKeys = metadata.keys; + var toMetaKey = metadata.key; + + metadata.exp({ getOwnMetadataKeys: function getOwnMetadataKeys(target /* , targetKey */) { + return ordinaryOwnMetadataKeys(anObject(target), arguments.length < 2 ? undefined : toMetaKey(arguments[1])); + } }); + + +/***/ }), +/* 315 */ +/***/ (function(module, exports, __webpack_require__) { + + var metadata = __webpack_require__(309); + var anObject = __webpack_require__(12); + var getPrototypeOf = __webpack_require__(58); + var ordinaryHasOwnMetadata = metadata.has; + var toMetaKey = metadata.key; + + var ordinaryHasMetadata = function (MetadataKey, O, P) { + var hasOwn = ordinaryHasOwnMetadata(MetadataKey, O, P); + if (hasOwn) return true; + var parent = getPrototypeOf(O); + return parent !== null ? ordinaryHasMetadata(MetadataKey, parent, P) : false; + }; + + metadata.exp({ hasMetadata: function hasMetadata(metadataKey, target /* , targetKey */) { + return ordinaryHasMetadata(metadataKey, anObject(target), arguments.length < 3 ? undefined : toMetaKey(arguments[2])); + } }); + + +/***/ }), +/* 316 */ +/***/ (function(module, exports, __webpack_require__) { + + var metadata = __webpack_require__(309); + var anObject = __webpack_require__(12); + var ordinaryHasOwnMetadata = metadata.has; + var toMetaKey = metadata.key; + + metadata.exp({ hasOwnMetadata: function hasOwnMetadata(metadataKey, target /* , targetKey */) { + return ordinaryHasOwnMetadata(metadataKey, anObject(target) + , arguments.length < 3 ? undefined : toMetaKey(arguments[2])); + } }); + + +/***/ }), +/* 317 */ +/***/ (function(module, exports, __webpack_require__) { + + var $metadata = __webpack_require__(309); + var anObject = __webpack_require__(12); + var aFunction = __webpack_require__(21); + var toMetaKey = $metadata.key; + var ordinaryDefineOwnMetadata = $metadata.set; + + $metadata.exp({ metadata: function metadata(metadataKey, metadataValue) { + return function decorator(target, targetKey) { + ordinaryDefineOwnMetadata( + metadataKey, metadataValue, + (targetKey !== undefined ? anObject : aFunction)(target), + toMetaKey(targetKey) + ); + }; + } }); + + +/***/ }), +/* 318 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://github.com/rwaldron/tc39-notes/blob/master/es6/2014-09/sept-25.md#510-globalasap-for-enqueuing-a-microtask + var $export = __webpack_require__(8); + var microtask = __webpack_require__(210)(); + var process = __webpack_require__(4).process; + var isNode = __webpack_require__(34)(process) == 'process'; + + $export($export.G, { + asap: function asap(fn) { + var domain = isNode && process.domain; + microtask(domain ? domain.bind(fn) : fn); + } + }); + + +/***/ }), +/* 319 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + // https://github.com/zenparsing/es-observable + var $export = __webpack_require__(8); + var global = __webpack_require__(4); + var core = __webpack_require__(9); + var microtask = __webpack_require__(210)(); + var OBSERVABLE = __webpack_require__(26)('observable'); + var aFunction = __webpack_require__(21); + var anObject = __webpack_require__(12); + var anInstance = __webpack_require__(206); + var redefineAll = __webpack_require__(215); + var hide = __webpack_require__(10); + var forOf = __webpack_require__(207); + var RETURN = forOf.RETURN; + + var getMethod = function (fn) { + return fn == null ? undefined : aFunction(fn); + }; + + var cleanupSubscription = function (subscription) { + var cleanup = subscription._c; + if (cleanup) { + subscription._c = undefined; + cleanup(); + } + }; + + var subscriptionClosed = function (subscription) { + return subscription._o === undefined; + }; + + var closeSubscription = function (subscription) { + if (!subscriptionClosed(subscription)) { + subscription._o = undefined; + cleanupSubscription(subscription); + } + }; + + var Subscription = function (observer, subscriber) { + anObject(observer); + this._c = undefined; + this._o = observer; + observer = new SubscriptionObserver(this); + try { + var cleanup = subscriber(observer); + var subscription = cleanup; + if (cleanup != null) { + if (typeof cleanup.unsubscribe === 'function') cleanup = function () { subscription.unsubscribe(); }; + else aFunction(cleanup); + this._c = cleanup; + } + } catch (e) { + observer.error(e); + return; + } if (subscriptionClosed(this)) cleanupSubscription(this); + }; + + Subscription.prototype = redefineAll({}, { + unsubscribe: function unsubscribe() { closeSubscription(this); } + }); + + var SubscriptionObserver = function (subscription) { + this._s = subscription; + }; + + SubscriptionObserver.prototype = redefineAll({}, { + next: function next(value) { + var subscription = this._s; + if (!subscriptionClosed(subscription)) { + var observer = subscription._o; + try { + var m = getMethod(observer.next); + if (m) return m.call(observer, value); + } catch (e) { + try { + closeSubscription(subscription); + } finally { + throw e; + } + } + } + }, + error: function error(value) { + var subscription = this._s; + if (subscriptionClosed(subscription)) throw value; + var observer = subscription._o; + subscription._o = undefined; + try { + var m = getMethod(observer.error); + if (!m) throw value; + value = m.call(observer, value); + } catch (e) { + try { + cleanupSubscription(subscription); + } finally { + throw e; + } + } cleanupSubscription(subscription); + return value; + }, + complete: function complete(value) { + var subscription = this._s; + if (!subscriptionClosed(subscription)) { + var observer = subscription._o; + subscription._o = undefined; + try { + var m = getMethod(observer.complete); + value = m ? m.call(observer, value) : undefined; + } catch (e) { + try { + cleanupSubscription(subscription); + } finally { + throw e; + } + } cleanupSubscription(subscription); + return value; + } + } + }); + + var $Observable = function Observable(subscriber) { + anInstance(this, $Observable, 'Observable', '_f')._f = aFunction(subscriber); + }; + + redefineAll($Observable.prototype, { + subscribe: function subscribe(observer) { + return new Subscription(observer, this._f); + }, + forEach: function forEach(fn) { + var that = this; + return new (core.Promise || global.Promise)(function (resolve, reject) { + aFunction(fn); + var subscription = that.subscribe({ + next: function (value) { + try { + return fn(value); + } catch (e) { + reject(e); + subscription.unsubscribe(); + } + }, + error: reject, + complete: resolve + }); + }); + } + }); + + redefineAll($Observable, { + from: function from(x) { + var C = typeof this === 'function' ? this : $Observable; + var method = getMethod(anObject(x)[OBSERVABLE]); + if (method) { + var observable = anObject(method.call(x)); + return observable.constructor === C ? observable : new C(function (observer) { + return observable.subscribe(observer); + }); + } + return new C(function (observer) { + var done = false; + microtask(function () { + if (!done) { + try { + if (forOf(x, false, function (it) { + observer.next(it); + if (done) return RETURN; + }) === RETURN) return; + } catch (e) { + if (done) throw e; + observer.error(e); + return; + } observer.complete(); + } + }); + return function () { done = true; }; + }); + }, + of: function of() { + for (var i = 0, l = arguments.length, items = new Array(l); i < l;) items[i] = arguments[i++]; + return new (typeof this === 'function' ? this : $Observable)(function (observer) { + var done = false; + microtask(function () { + if (!done) { + for (var j = 0; j < items.length; ++j) { + observer.next(items[j]); + if (done) return; + } observer.complete(); + } + }); + return function () { done = true; }; + }); + } + }); + + hide($Observable.prototype, OBSERVABLE, function () { return this; }); + + $export($export.G, { Observable: $Observable }); + + __webpack_require__(193)('Observable'); + + +/***/ }), +/* 320 */ +/***/ (function(module, exports, __webpack_require__) { + + // ie9- setTimeout & setInterval additional parameters fix + var global = __webpack_require__(4); + var $export = __webpack_require__(8); + var userAgent = __webpack_require__(213); + var slice = [].slice; + var MSIE = /MSIE .\./.test(userAgent); // <- dirty ie9- check + var wrap = function (set) { + return function (fn, time /* , ...args */) { + var boundArgs = arguments.length > 2; + var args = boundArgs ? slice.call(arguments, 2) : false; + return set(boundArgs ? function () { + // eslint-disable-next-line no-new-func + (typeof fn == 'function' ? fn : Function(fn)).apply(this, args); + } : fn, time); + }; + }; + $export($export.G + $export.B + $export.F * MSIE, { + setTimeout: wrap(global.setTimeout), + setInterval: wrap(global.setInterval) + }); + + +/***/ }), +/* 321 */ +/***/ (function(module, exports, __webpack_require__) { + + var $export = __webpack_require__(8); + var $task = __webpack_require__(209); + $export($export.G + $export.B, { + setImmediate: $task.set, + clearImmediate: $task.clear + }); + + +/***/ }), +/* 322 */ +/***/ (function(module, exports, __webpack_require__) { + + var $iterators = __webpack_require__(194); + var getKeys = __webpack_require__(30); + var redefine = __webpack_require__(18); + var global = __webpack_require__(4); + var hide = __webpack_require__(10); + var Iterators = __webpack_require__(129); + var wks = __webpack_require__(26); + var ITERATOR = wks('iterator'); + var TO_STRING_TAG = wks('toStringTag'); + var ArrayValues = Iterators.Array; + + var DOMIterables = { + CSSRuleList: true, // TODO: Not spec compliant, should be false. + CSSStyleDeclaration: false, + CSSValueList: false, + ClientRectList: false, + DOMRectList: false, + DOMStringList: false, + DOMTokenList: true, + DataTransferItemList: false, + FileList: false, + HTMLAllCollection: false, + HTMLCollection: false, + HTMLFormElement: false, + HTMLSelectElement: false, + MediaList: true, // TODO: Not spec compliant, should be false. + MimeTypeArray: false, + NamedNodeMap: false, + NodeList: true, + PaintRequestList: false, + Plugin: false, + PluginArray: false, + SVGLengthList: false, + SVGNumberList: false, + SVGPathSegList: false, + SVGPointList: false, + SVGStringList: false, + SVGTransformList: false, + SourceBufferList: false, + StyleSheetList: true, // TODO: Not spec compliant, should be false. + TextTrackCueList: false, + TextTrackList: false, + TouchList: false + }; + + for (var collections = getKeys(DOMIterables), i = 0; i < collections.length; i++) { + var NAME = collections[i]; + var explicit = DOMIterables[NAME]; + var Collection = global[NAME]; + var proto = Collection && Collection.prototype; + var key; + if (proto) { + if (!proto[ITERATOR]) hide(proto, ITERATOR, ArrayValues); + if (!proto[TO_STRING_TAG]) hide(proto, TO_STRING_TAG, NAME); + Iterators[NAME] = ArrayValues; + if (explicit) for (key in $iterators) if (!proto[key]) redefine(proto, key, $iterators[key], true); + } + } + + +/***/ }), +/* 323 */ +/***/ (function(module, exports) { + + /* WEBPACK VAR INJECTION */(function(global) {/** + * Copyright (c) 2014, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * https://raw.github.com/facebook/regenerator/master/LICENSE file. An + * additional grant of patent rights can be found in the PATENTS file in + * the same directory. + */ + + !(function(global) { + "use strict"; + + var Op = Object.prototype; + var hasOwn = Op.hasOwnProperty; + var undefined; // More compressible than void 0. + var $Symbol = typeof Symbol === "function" ? Symbol : {}; + var iteratorSymbol = $Symbol.iterator || "@@iterator"; + var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator"; + var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; + + var inModule = typeof module === "object"; + var runtime = global.regeneratorRuntime; + if (runtime) { + if (inModule) { + // If regeneratorRuntime is defined globally and we're in a module, + // make the exports object identical to regeneratorRuntime. + module.exports = runtime; + } + // Don't bother evaluating the rest of this file if the runtime was + // already defined globally. + return; + } + + // Define the runtime globally (as expected by generated code) as either + // module.exports (if we're in a module) or a new, empty object. + runtime = global.regeneratorRuntime = inModule ? module.exports : {}; + + function wrap(innerFn, outerFn, self, tryLocsList) { + // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator. + var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator; + var generator = Object.create(protoGenerator.prototype); + var context = new Context(tryLocsList || []); + + // The ._invoke method unifies the implementations of the .next, + // .throw, and .return methods. + generator._invoke = makeInvokeMethod(innerFn, self, context); + + return generator; + } + runtime.wrap = wrap; + + // Try/catch helper to minimize deoptimizations. Returns a completion + // record like context.tryEntries[i].completion. This interface could + // have been (and was previously) designed to take a closure to be + // invoked without arguments, but in all the cases we care about we + // already have an existing method we want to call, so there's no need + // to create a new function object. We can even get away with assuming + // the method takes exactly one argument, since that happens to be true + // in every case, so we don't have to touch the arguments object. The + // only additional allocation required is the completion record, which + // has a stable shape and so hopefully should be cheap to allocate. + function tryCatch(fn, obj, arg) { + try { + return { type: "normal", arg: fn.call(obj, arg) }; + } catch (err) { + return { type: "throw", arg: err }; + } + } + + var GenStateSuspendedStart = "suspendedStart"; + var GenStateSuspendedYield = "suspendedYield"; + var GenStateExecuting = "executing"; + var GenStateCompleted = "completed"; + + // Returning this object from the innerFn has the same effect as + // breaking out of the dispatch switch statement. + var ContinueSentinel = {}; + + // Dummy constructor functions that we use as the .constructor and + // .constructor.prototype properties for functions that return Generator + // objects. For full spec compliance, you may wish to configure your + // minifier not to mangle the names of these two functions. + function Generator() {} + function GeneratorFunction() {} + function GeneratorFunctionPrototype() {} + + // This is a polyfill for %IteratorPrototype% for environments that + // don't natively support it. + var IteratorPrototype = {}; + IteratorPrototype[iteratorSymbol] = function () { + return this; + }; + + var getProto = Object.getPrototypeOf; + var NativeIteratorPrototype = getProto && getProto(getProto(values([]))); + if (NativeIteratorPrototype && + NativeIteratorPrototype !== Op && + hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) { + // This environment has a native %IteratorPrototype%; use it instead + // of the polyfill. + IteratorPrototype = NativeIteratorPrototype; + } + + var Gp = GeneratorFunctionPrototype.prototype = + Generator.prototype = Object.create(IteratorPrototype); + GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype; + GeneratorFunctionPrototype.constructor = GeneratorFunction; + GeneratorFunctionPrototype[toStringTagSymbol] = + GeneratorFunction.displayName = "GeneratorFunction"; + + // Helper for defining the .next, .throw, and .return methods of the + // Iterator interface in terms of a single ._invoke method. + function defineIteratorMethods(prototype) { + ["next", "throw", "return"].forEach(function(method) { + prototype[method] = function(arg) { + return this._invoke(method, arg); + }; + }); + } + + runtime.isGeneratorFunction = function(genFun) { + var ctor = typeof genFun === "function" && genFun.constructor; + return ctor + ? ctor === GeneratorFunction || + // For the native GeneratorFunction constructor, the best we can + // do is to check its .name property. + (ctor.displayName || ctor.name) === "GeneratorFunction" + : false; + }; + + runtime.mark = function(genFun) { + if (Object.setPrototypeOf) { + Object.setPrototypeOf(genFun, GeneratorFunctionPrototype); + } else { + genFun.__proto__ = GeneratorFunctionPrototype; + if (!(toStringTagSymbol in genFun)) { + genFun[toStringTagSymbol] = "GeneratorFunction"; + } + } + genFun.prototype = Object.create(Gp); + return genFun; + }; + + // Within the body of any async function, `await x` is transformed to + // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test + // `hasOwn.call(value, "__await")` to determine if the yielded value is + // meant to be awaited. + runtime.awrap = function(arg) { + return { __await: arg }; + }; + + function AsyncIterator(generator) { + function invoke(method, arg, resolve, reject) { + var record = tryCatch(generator[method], generator, arg); + if (record.type === "throw") { + reject(record.arg); + } else { + var result = record.arg; + var value = result.value; + if (value && + typeof value === "object" && + hasOwn.call(value, "__await")) { + return Promise.resolve(value.__await).then(function(value) { + invoke("next", value, resolve, reject); + }, function(err) { + invoke("throw", err, resolve, reject); + }); + } + + return Promise.resolve(value).then(function(unwrapped) { + // When a yielded Promise is resolved, its final value becomes + // the .value of the Promise<{value,done}> result for the + // current iteration. If the Promise is rejected, however, the + // result for this iteration will be rejected with the same + // reason. Note that rejections of yielded Promises are not + // thrown back into the generator function, as is the case + // when an awaited Promise is rejected. This difference in + // behavior between yield and await is important, because it + // allows the consumer to decide what to do with the yielded + // rejection (swallow it and continue, manually .throw it back + // into the generator, abandon iteration, whatever). With + // await, by contrast, there is no opportunity to examine the + // rejection reason outside the generator function, so the + // only option is to throw it from the await expression, and + // let the generator function handle the exception. + result.value = unwrapped; + resolve(result); + }, reject); + } + } + + if (typeof global.process === "object" && global.process.domain) { + invoke = global.process.domain.bind(invoke); + } + + var previousPromise; + + function enqueue(method, arg) { + function callInvokeWithMethodAndArg() { + return new Promise(function(resolve, reject) { + invoke(method, arg, resolve, reject); + }); + } + + return previousPromise = + // If enqueue has been called before, then we want to wait until + // all previous Promises have been resolved before calling invoke, + // so that results are always delivered in the correct order. If + // enqueue has not been called before, then it is important to + // call invoke immediately, without waiting on a callback to fire, + // so that the async generator function has the opportunity to do + // any necessary setup in a predictable way. This predictability + // is why the Promise constructor synchronously invokes its + // executor callback, and why async functions synchronously + // execute code before the first await. Since we implement simple + // async functions in terms of async generators, it is especially + // important to get this right, even though it requires care. + previousPromise ? previousPromise.then( + callInvokeWithMethodAndArg, + // Avoid propagating failures to Promises returned by later + // invocations of the iterator. + callInvokeWithMethodAndArg + ) : callInvokeWithMethodAndArg(); + } + + // Define the unified helper method that is used to implement .next, + // .throw, and .return (see defineIteratorMethods). + this._invoke = enqueue; + } + + defineIteratorMethods(AsyncIterator.prototype); + AsyncIterator.prototype[asyncIteratorSymbol] = function () { + return this; + }; + runtime.AsyncIterator = AsyncIterator; + + // Note that simple async functions are implemented on top of + // AsyncIterator objects; they just return a Promise for the value of + // the final result produced by the iterator. + runtime.async = function(innerFn, outerFn, self, tryLocsList) { + var iter = new AsyncIterator( + wrap(innerFn, outerFn, self, tryLocsList) + ); + + return runtime.isGeneratorFunction(outerFn) + ? iter // If outerFn is a generator, return the full iterator. + : iter.next().then(function(result) { + return result.done ? result.value : iter.next(); + }); + }; + + function makeInvokeMethod(innerFn, self, context) { + var state = GenStateSuspendedStart; + + return function invoke(method, arg) { + if (state === GenStateExecuting) { + throw new Error("Generator is already running"); + } + + if (state === GenStateCompleted) { + if (method === "throw") { + throw arg; + } + + // Be forgiving, per 25.3.3.3.3 of the spec: + // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume + return doneResult(); + } + + context.method = method; + context.arg = arg; + + while (true) { + var delegate = context.delegate; + if (delegate) { + var delegateResult = maybeInvokeDelegate(delegate, context); + if (delegateResult) { + if (delegateResult === ContinueSentinel) continue; + return delegateResult; + } + } + + if (context.method === "next") { + // Setting context._sent for legacy support of Babel's + // function.sent implementation. + context.sent = context._sent = context.arg; + + } else if (context.method === "throw") { + if (state === GenStateSuspendedStart) { + state = GenStateCompleted; + throw context.arg; + } + + context.dispatchException(context.arg); + + } else if (context.method === "return") { + context.abrupt("return", context.arg); + } + + state = GenStateExecuting; + + var record = tryCatch(innerFn, self, context); + if (record.type === "normal") { + // If an exception is thrown from innerFn, we leave state === + // GenStateExecuting and loop back for another invocation. + state = context.done + ? GenStateCompleted + : GenStateSuspendedYield; + + if (record.arg === ContinueSentinel) { + continue; + } + + return { + value: record.arg, + done: context.done + }; + + } else if (record.type === "throw") { + state = GenStateCompleted; + // Dispatch the exception by looping back around to the + // context.dispatchException(context.arg) call above. + context.method = "throw"; + context.arg = record.arg; + } + } + }; + } + + // Call delegate.iterator[context.method](context.arg) and handle the + // result, either by returning a { value, done } result from the + // delegate iterator, or by modifying context.method and context.arg, + // setting context.delegate to null, and returning the ContinueSentinel. + function maybeInvokeDelegate(delegate, context) { + var method = delegate.iterator[context.method]; + if (method === undefined) { + // A .throw or .return when the delegate iterator has no .throw + // method always terminates the yield* loop. + context.delegate = null; + + if (context.method === "throw") { + if (delegate.iterator.return) { + // If the delegate iterator has a return method, give it a + // chance to clean up. + context.method = "return"; + context.arg = undefined; + maybeInvokeDelegate(delegate, context); + + if (context.method === "throw") { + // If maybeInvokeDelegate(context) changed context.method from + // "return" to "throw", let that override the TypeError below. + return ContinueSentinel; + } + } + + context.method = "throw"; + context.arg = new TypeError( + "The iterator does not provide a 'throw' method"); + } + + return ContinueSentinel; + } + + var record = tryCatch(method, delegate.iterator, context.arg); + + if (record.type === "throw") { + context.method = "throw"; + context.arg = record.arg; + context.delegate = null; + return ContinueSentinel; + } + + var info = record.arg; + + if (! info) { + context.method = "throw"; + context.arg = new TypeError("iterator result is not an object"); + context.delegate = null; + return ContinueSentinel; + } + + if (info.done) { + // Assign the result of the finished delegate to the temporary + // variable specified by delegate.resultName (see delegateYield). + context[delegate.resultName] = info.value; + + // Resume execution at the desired location (see delegateYield). + context.next = delegate.nextLoc; + + // If context.method was "throw" but the delegate handled the + // exception, let the outer generator proceed normally. If + // context.method was "next", forget context.arg since it has been + // "consumed" by the delegate iterator. If context.method was + // "return", allow the original .return call to continue in the + // outer generator. + if (context.method !== "return") { + context.method = "next"; + context.arg = undefined; + } + + } else { + // Re-yield the result returned by the delegate method. + return info; + } + + // The delegate iterator is finished, so forget it and continue with + // the outer generator. + context.delegate = null; + return ContinueSentinel; + } + + // Define Generator.prototype.{next,throw,return} in terms of the + // unified ._invoke helper method. + defineIteratorMethods(Gp); + + Gp[toStringTagSymbol] = "Generator"; + + // A Generator should always return itself as the iterator object when the + // @@iterator function is called on it. Some browsers' implementations of the + // iterator prototype chain incorrectly implement this, causing the Generator + // object to not be returned from this call. This ensures that doesn't happen. + // See https://github.com/facebook/regenerator/issues/274 for more details. + Gp[iteratorSymbol] = function() { + return this; + }; + + Gp.toString = function() { + return "[object Generator]"; + }; + + function pushTryEntry(locs) { + var entry = { tryLoc: locs[0] }; + + if (1 in locs) { + entry.catchLoc = locs[1]; + } + + if (2 in locs) { + entry.finallyLoc = locs[2]; + entry.afterLoc = locs[3]; + } + + this.tryEntries.push(entry); + } + + function resetTryEntry(entry) { + var record = entry.completion || {}; + record.type = "normal"; + delete record.arg; + entry.completion = record; + } + + function Context(tryLocsList) { + // The root entry object (effectively a try statement without a catch + // or a finally block) gives us a place to store values thrown from + // locations where there is no enclosing try statement. + this.tryEntries = [{ tryLoc: "root" }]; + tryLocsList.forEach(pushTryEntry, this); + this.reset(true); + } + + runtime.keys = function(object) { + var keys = []; + for (var key in object) { + keys.push(key); + } + keys.reverse(); + + // Rather than returning an object with a next method, we keep + // things simple and return the next function itself. + return function next() { + while (keys.length) { + var key = keys.pop(); + if (key in object) { + next.value = key; + next.done = false; + return next; + } + } + + // To avoid creating an additional object, we just hang the .value + // and .done properties off the next function object itself. This + // also ensures that the minifier will not anonymize the function. + next.done = true; + return next; + }; + }; + + function values(iterable) { + if (iterable) { + var iteratorMethod = iterable[iteratorSymbol]; + if (iteratorMethod) { + return iteratorMethod.call(iterable); + } + + if (typeof iterable.next === "function") { + return iterable; + } + + if (!isNaN(iterable.length)) { + var i = -1, next = function next() { + while (++i < iterable.length) { + if (hasOwn.call(iterable, i)) { + next.value = iterable[i]; + next.done = false; + return next; + } + } + + next.value = undefined; + next.done = true; + + return next; + }; + + return next.next = next; + } + } + + // Return an iterator with no values. + return { next: doneResult }; + } + runtime.values = values; + + function doneResult() { + return { value: undefined, done: true }; + } + + Context.prototype = { + constructor: Context, + + reset: function(skipTempReset) { + this.prev = 0; + this.next = 0; + // Resetting context._sent for legacy support of Babel's + // function.sent implementation. + this.sent = this._sent = undefined; + this.done = false; + this.delegate = null; + + this.method = "next"; + this.arg = undefined; + + this.tryEntries.forEach(resetTryEntry); + + if (!skipTempReset) { + for (var name in this) { + // Not sure about the optimal order of these conditions: + if (name.charAt(0) === "t" && + hasOwn.call(this, name) && + !isNaN(+name.slice(1))) { + this[name] = undefined; + } + } + } + }, + + stop: function() { + this.done = true; + + var rootEntry = this.tryEntries[0]; + var rootRecord = rootEntry.completion; + if (rootRecord.type === "throw") { + throw rootRecord.arg; + } + + return this.rval; + }, + + dispatchException: function(exception) { + if (this.done) { + throw exception; + } + + var context = this; + function handle(loc, caught) { + record.type = "throw"; + record.arg = exception; + context.next = loc; + + if (caught) { + // If the dispatched exception was caught by a catch block, + // then let that catch block handle the exception normally. + context.method = "next"; + context.arg = undefined; + } + + return !! caught; + } + + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + var record = entry.completion; + + if (entry.tryLoc === "root") { + // Exception thrown outside of any try block that could handle + // it, so set the completion value of the entire function to + // throw the exception. + return handle("end"); + } + + if (entry.tryLoc <= this.prev) { + var hasCatch = hasOwn.call(entry, "catchLoc"); + var hasFinally = hasOwn.call(entry, "finallyLoc"); + + if (hasCatch && hasFinally) { + if (this.prev < entry.catchLoc) { + return handle(entry.catchLoc, true); + } else if (this.prev < entry.finallyLoc) { + return handle(entry.finallyLoc); + } + + } else if (hasCatch) { + if (this.prev < entry.catchLoc) { + return handle(entry.catchLoc, true); + } + + } else if (hasFinally) { + if (this.prev < entry.finallyLoc) { + return handle(entry.finallyLoc); + } + + } else { + throw new Error("try statement without catch or finally"); + } + } + } + }, + + abrupt: function(type, arg) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + if (entry.tryLoc <= this.prev && + hasOwn.call(entry, "finallyLoc") && + this.prev < entry.finallyLoc) { + var finallyEntry = entry; + break; + } + } + + if (finallyEntry && + (type === "break" || + type === "continue") && + finallyEntry.tryLoc <= arg && + arg <= finallyEntry.finallyLoc) { + // Ignore the finally entry if control is not jumping to a + // location outside the try/catch block. + finallyEntry = null; + } + + var record = finallyEntry ? finallyEntry.completion : {}; + record.type = type; + record.arg = arg; + + if (finallyEntry) { + this.method = "next"; + this.next = finallyEntry.finallyLoc; + return ContinueSentinel; + } + + return this.complete(record); + }, + + complete: function(record, afterLoc) { + if (record.type === "throw") { + throw record.arg; + } + + if (record.type === "break" || + record.type === "continue") { + this.next = record.arg; + } else if (record.type === "return") { + this.rval = this.arg = record.arg; + this.method = "return"; + this.next = "end"; + } else if (record.type === "normal" && afterLoc) { + this.next = afterLoc; + } + + return ContinueSentinel; + }, + + finish: function(finallyLoc) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + if (entry.finallyLoc === finallyLoc) { + this.complete(entry.completion, entry.afterLoc); + resetTryEntry(entry); + return ContinueSentinel; + } + } + }, + + "catch": function(tryLoc) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + if (entry.tryLoc === tryLoc) { + var record = entry.completion; + if (record.type === "throw") { + var thrown = record.arg; + resetTryEntry(entry); + } + return thrown; + } + } + + // The context.catch method must only be called with a location + // argument that corresponds to a known catch block. + throw new Error("illegal catch attempt"); + }, + + delegateYield: function(iterable, resultName, nextLoc) { + this.delegate = { + iterator: values(iterable), + resultName: resultName, + nextLoc: nextLoc + }; + + if (this.method === "next") { + // Deliberately forget the last sent value so that we don't + // accidentally pass it on to the delegate. + this.arg = undefined; + } + + return ContinueSentinel; + } + }; + })( + // Among the various tricks for obtaining a reference to the global + // object, this seems to be the most reliable technique that does not + // use indirect eval (which violates Content Security Policy). + typeof global === "object" ? global : + typeof window === "object" ? window : + typeof self === "object" ? self : this + ); + + /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) + +/***/ }), +/* 324 */ +/***/ (function(module, exports, __webpack_require__) { + + __webpack_require__(325); + module.exports = __webpack_require__(9).RegExp.escape; + + +/***/ }), +/* 325 */ +/***/ (function(module, exports, __webpack_require__) { + + // https://github.com/benjamingr/RexExp.escape + var $export = __webpack_require__(8); + var $re = __webpack_require__(326)(/[\\^$*+?.()|[\]{}]/g, '\\$&'); + + $export($export.S, 'RegExp', { escape: function escape(it) { return $re(it); } }); + + +/***/ }), +/* 326 */ +/***/ (function(module, exports) { + + module.exports = function (regExp, replace) { + var replacer = replace === Object(replace) ? function (part) { + return replace[part]; + } : replace; + return function (it) { + return String(it).replace(regExp, replacer); + }; + }; + + +/***/ }), +/* 327 */ +/***/ (function(module, exports, __webpack_require__) { + + var BSON = __webpack_require__(328), + Binary = __webpack_require__(351), + Code = __webpack_require__(346), + DBRef = __webpack_require__(350), + Decimal128 = __webpack_require__(347), + Double = __webpack_require__(331), + Int32 = __webpack_require__(345), + Long = __webpack_require__(330), + Map = __webpack_require__(329), + MaxKey = __webpack_require__(349), + MinKey = __webpack_require__(348), + ObjectId = __webpack_require__(333), + BSONRegExp = __webpack_require__(343), + Symbol = __webpack_require__(344), + Timestamp = __webpack_require__(332); + + // BSON MAX VALUES + BSON.BSON_INT32_MAX = 0x7fffffff; + BSON.BSON_INT32_MIN = -0x80000000; + + BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; + BSON.BSON_INT64_MIN = -Math.pow(2, 63); + + // JS MAX PRECISE VALUES + BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. + BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. + + // Add BSON types to function creation + BSON.Binary = Binary; + BSON.Code = Code; + BSON.DBRef = DBRef; + BSON.Decimal128 = Decimal128; + BSON.Double = Double; + BSON.Int32 = Int32; + BSON.Long = Long; + BSON.Map = Map; + BSON.MaxKey = MaxKey; + BSON.MinKey = MinKey; + BSON.ObjectId = ObjectId; + BSON.ObjectID = ObjectId; + BSON.BSONRegExp = BSONRegExp; + BSON.Symbol = Symbol; + BSON.Timestamp = Timestamp; + + // Return the BSON + module.exports = BSON; + +/***/ }), +/* 328 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + + var Map = __webpack_require__(329), + Long = __webpack_require__(330), + Double = __webpack_require__(331), + Timestamp = __webpack_require__(332), + ObjectID = __webpack_require__(333), + BSONRegExp = __webpack_require__(343), + Symbol = __webpack_require__(344), + Int32 = __webpack_require__(345), + Code = __webpack_require__(346), + Decimal128 = __webpack_require__(347), + MinKey = __webpack_require__(348), + MaxKey = __webpack_require__(349), + DBRef = __webpack_require__(350), + Binary = __webpack_require__(351); + + // Parts of the parser + var deserialize = __webpack_require__(352), + serializer = __webpack_require__(353), + calculateObjectSize = __webpack_require__(355), + utils = __webpack_require__(339); + + /** + * @ignore + * @api private + */ + // Default Max Size + var MAXSIZE = 1024 * 1024 * 17; + + // Current Internal Temporary Serialization Buffer + var buffer = utils.allocBuffer(MAXSIZE); + + var BSON = function () {}; + + /** + * Serialize a Javascript object. + * + * @param {Object} object the Javascript object to serialize. + * @param {Boolean} [options.checkKeys] the serializer will check if keys are valid. + * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. + * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. + * @param {Number} [options.minInternalBufferSize=1024*1024*17] minimum size of the internal temporary serialization buffer **(default:1024*1024*17)**. + * @return {Buffer} returns the Buffer object containing the serialized object. + * @api public + */ + BSON.prototype.serialize = function serialize(object, options) { + options = options || {}; + // Unpack the options + var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; + var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; + var minInternalBufferSize = typeof options.minInternalBufferSize === 'number' ? options.minInternalBufferSize : MAXSIZE; + + // Resize the internal serialization buffer if needed + if (buffer.length < minInternalBufferSize) { + buffer = utils.allocBuffer(minInternalBufferSize); + } + + // Attempt to serialize + var serializationIndex = serializer(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, []); + // Create the final buffer + var finishedBuffer = utils.allocBuffer(serializationIndex); + // Copy into the finished buffer + buffer.copy(finishedBuffer, 0, 0, finishedBuffer.length); + // Return the buffer + return finishedBuffer; + }; + + /** + * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. + * + * @param {Object} object the Javascript object to serialize. + * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. + * @param {Boolean} [options.checkKeys] the serializer will check if keys are valid. + * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. + * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. + * @param {Number} [options.index] the index in the buffer where we wish to start serializing into. + * @return {Number} returns the index pointing to the last written byte in the buffer. + * @api public + */ + BSON.prototype.serializeWithBufferAndIndex = function (object, finalBuffer, options) { + options = options || {}; + // Unpack the options + var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; + var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; + var startIndex = typeof options.index === 'number' ? options.index : 0; + + // Attempt to serialize + var serializationIndex = serializer(finalBuffer, object, checkKeys, startIndex || 0, 0, serializeFunctions, ignoreUndefined); + + // Return the index + return serializationIndex - 1; + }; + + /** + * Deserialize data as BSON. + * + * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. + * @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized. + * @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse. + * @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function. + * @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits + * @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a node.js Buffer instance. + * @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types. + * @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer. + * @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances. + * @return {Object} returns the deserialized Javascript Object. + * @api public + */ + BSON.prototype.deserialize = function (buffer, options) { + return deserialize(buffer, options); + }; + + /** + * Calculate the bson size for a passed in Javascript object. + * + * @param {Object} object the Javascript object to calculate the BSON byte size for. + * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. + * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. + * @return {Number} returns the number of bytes the BSON object will take up. + * @api public + */ + BSON.prototype.calculateObjectSize = function (object, options) { + options = options || {}; + + var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; + + return calculateObjectSize(object, serializeFunctions, ignoreUndefined); + }; + + /** + * Deserialize stream data as BSON documents. + * + * @param {Buffer} data the buffer containing the serialized set of BSON documents. + * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. + * @param {Number} numberOfDocuments number of documents to deserialize. + * @param {Array} documents an array where to store the deserialized documents. + * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. + * @param {Object} [options] additional options used for the deserialization. + * @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized. + * @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse. + * @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function. + * @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits + * @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a node.js Buffer instance. + * @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types. + * @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer. + * @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances. + * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. + * @api public + */ + BSON.prototype.deserializeStream = function (data, startIndex, numberOfDocuments, documents, docStartIndex, options) { + options = options != null ? options : {}; + var index = startIndex; + // Loop over all documents + for (var i = 0; i < numberOfDocuments; i++) { + // Find size of the document + var size = data[index] | data[index + 1] << 8 | data[index + 2] << 16 | data[index + 3] << 24; + // Update options with index + options['index'] = index; + // Parse the document at this point + documents[docStartIndex + i] = this.deserialize(data, options); + // Adjust index by the document size + index = index + size; + } + + // Return object containing end index of parsing and list of documents + return index; + }; + + /** + * @ignore + * @api private + */ + // BSON MAX VALUES + BSON.BSON_INT32_MAX = 0x7fffffff; + BSON.BSON_INT32_MIN = -0x80000000; + + BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; + BSON.BSON_INT64_MIN = -Math.pow(2, 63); + + // JS MAX PRECISE VALUES + BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. + BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. + + // Internal long versions + // var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. + // var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. + + /** + * Number BSON Type + * + * @classconstant BSON_DATA_NUMBER + **/ + BSON.BSON_DATA_NUMBER = 1; + /** + * String BSON Type + * + * @classconstant BSON_DATA_STRING + **/ + BSON.BSON_DATA_STRING = 2; + /** + * Object BSON Type + * + * @classconstant BSON_DATA_OBJECT + **/ + BSON.BSON_DATA_OBJECT = 3; + /** + * Array BSON Type + * + * @classconstant BSON_DATA_ARRAY + **/ + BSON.BSON_DATA_ARRAY = 4; + /** + * Binary BSON Type + * + * @classconstant BSON_DATA_BINARY + **/ + BSON.BSON_DATA_BINARY = 5; + /** + * ObjectID BSON Type + * + * @classconstant BSON_DATA_OID + **/ + BSON.BSON_DATA_OID = 7; + /** + * Boolean BSON Type + * + * @classconstant BSON_DATA_BOOLEAN + **/ + BSON.BSON_DATA_BOOLEAN = 8; + /** + * Date BSON Type + * + * @classconstant BSON_DATA_DATE + **/ + BSON.BSON_DATA_DATE = 9; + /** + * null BSON Type + * + * @classconstant BSON_DATA_NULL + **/ + BSON.BSON_DATA_NULL = 10; + /** + * RegExp BSON Type + * + * @classconstant BSON_DATA_REGEXP + **/ + BSON.BSON_DATA_REGEXP = 11; + /** + * Code BSON Type + * + * @classconstant BSON_DATA_CODE + **/ + BSON.BSON_DATA_CODE = 13; + /** + * Symbol BSON Type + * + * @classconstant BSON_DATA_SYMBOL + **/ + BSON.BSON_DATA_SYMBOL = 14; + /** + * Code with Scope BSON Type + * + * @classconstant BSON_DATA_CODE_W_SCOPE + **/ + BSON.BSON_DATA_CODE_W_SCOPE = 15; + /** + * 32 bit Integer BSON Type + * + * @classconstant BSON_DATA_INT + **/ + BSON.BSON_DATA_INT = 16; + /** + * Timestamp BSON Type + * + * @classconstant BSON_DATA_TIMESTAMP + **/ + BSON.BSON_DATA_TIMESTAMP = 17; + /** + * Long BSON Type + * + * @classconstant BSON_DATA_LONG + **/ + BSON.BSON_DATA_LONG = 18; + /** + * MinKey BSON Type + * + * @classconstant BSON_DATA_MIN_KEY + **/ + BSON.BSON_DATA_MIN_KEY = 0xff; + /** + * MaxKey BSON Type + * + * @classconstant BSON_DATA_MAX_KEY + **/ + BSON.BSON_DATA_MAX_KEY = 0x7f; + + /** + * Binary Default Type + * + * @classconstant BSON_BINARY_SUBTYPE_DEFAULT + **/ + BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; + /** + * Binary Function Type + * + * @classconstant BSON_BINARY_SUBTYPE_FUNCTION + **/ + BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; + /** + * Binary Byte Array Type + * + * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY + **/ + BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; + /** + * Binary UUID Type + * + * @classconstant BSON_BINARY_SUBTYPE_UUID + **/ + BSON.BSON_BINARY_SUBTYPE_UUID = 3; + /** + * Binary MD5 Type + * + * @classconstant BSON_BINARY_SUBTYPE_MD5 + **/ + BSON.BSON_BINARY_SUBTYPE_MD5 = 4; + /** + * Binary User Defined Type + * + * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED + **/ + BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; + + // Return BSON + module.exports = BSON; + module.exports.Code = Code; + module.exports.Map = Map; + module.exports.Symbol = Symbol; + module.exports.BSON = BSON; + module.exports.DBRef = DBRef; + module.exports.Binary = Binary; + module.exports.ObjectID = ObjectID; + module.exports.Long = Long; + module.exports.Timestamp = Timestamp; + module.exports.Double = Double; + module.exports.Int32 = Int32; + module.exports.MinKey = MinKey; + module.exports.MaxKey = MaxKey; + module.exports.BSONRegExp = BSONRegExp; + module.exports.Decimal128 = Decimal128; + +/***/ }), +/* 329 */ +/***/ (function(module, exports) { + + /* WEBPACK VAR INJECTION */(function(global) {'use strict'; + + // We have an ES6 Map available, return the native instance + + if (typeof global.Map !== 'undefined') { + module.exports = global.Map; + module.exports.Map = global.Map; + } else { + // We will return a polyfill + var Map = function (array) { + this._keys = []; + this._values = {}; + + for (var i = 0; i < array.length; i++) { + if (array[i] == null) continue; // skip null and undefined + var entry = array[i]; + var key = entry[0]; + var value = entry[1]; + // Add the key to the list of keys in order + this._keys.push(key); + // Add the key and value to the values dictionary with a point + // to the location in the ordered keys list + this._values[key] = { v: value, i: this._keys.length - 1 }; + } + }; + + Map.prototype.clear = function () { + this._keys = []; + this._values = {}; + }; + + Map.prototype.delete = function (key) { + var value = this._values[key]; + if (value == null) return false; + // Delete entry + delete this._values[key]; + // Remove the key from the ordered keys list + this._keys.splice(value.i, 1); + return true; + }; + + Map.prototype.entries = function () { + var self = this; + var index = 0; + + return { + next: function () { + var key = self._keys[index++]; + return { + value: key !== undefined ? [key, self._values[key].v] : undefined, + done: key !== undefined ? false : true + }; + } + }; + }; + + Map.prototype.forEach = function (callback, self) { + self = self || this; + + for (var i = 0; i < this._keys.length; i++) { + var key = this._keys[i]; + // Call the forEach callback + callback.call(self, this._values[key].v, key, self); + } + }; + + Map.prototype.get = function (key) { + return this._values[key] ? this._values[key].v : undefined; + }; + + Map.prototype.has = function (key) { + return this._values[key] != null; + }; + + Map.prototype.keys = function () { + var self = this; + var index = 0; + + return { + next: function () { + var key = self._keys[index++]; + return { + value: key !== undefined ? key : undefined, + done: key !== undefined ? false : true + }; + } + }; + }; + + Map.prototype.set = function (key, value) { + if (this._values[key]) { + this._values[key].v = value; + return this; + } + + // Add the key to the list of keys in order + this._keys.push(key); + // Add the key and value to the values dictionary with a point + // to the location in the ordered keys list + this._values[key] = { v: value, i: this._keys.length - 1 }; + return this; + }; + + Map.prototype.values = function () { + var self = this; + var index = 0; + + return { + next: function () { + var key = self._keys[index++]; + return { + value: key !== undefined ? self._values[key].v : undefined, + done: key !== undefined ? false : true + }; + } + }; + }; + + // Last ismaster + Object.defineProperty(Map.prototype, 'size', { + enumerable: true, + get: function () { + return this._keys.length; + } + }); + + module.exports = Map; + module.exports.Map = Map; + } + /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) + +/***/ }), +/* 330 */ +/***/ (function(module, exports) { + + // Licensed under the Apache License, Version 2.0 (the "License"); + // you may not use this file except in compliance with the License. + // You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + // Copyright 2009 Google Inc. All Rights Reserved + + /** + * Defines a Long class for representing a 64-bit two's-complement + * integer value, which faithfully simulates the behavior of a Java "Long". This + * implementation is derived from LongLib in GWT. + * + * Constructs a 64-bit two's-complement integer, given its low and high 32-bit + * values as *signed* integers. See the from* functions below for more + * convenient ways of constructing Longs. + * + * The internal representation of a Long is the two given signed, 32-bit values. + * We use 32-bit pieces because these are the size of integers on which + * Javascript performs bit-operations. For operations like addition and + * multiplication, we split each number into 16-bit pieces, which can easily be + * multiplied within Javascript's floating-point representation without overflow + * or change in sign. + * + * In the algorithms below, we frequently reduce the negative case to the + * positive case by negating the input(s) and then post-processing the result. + * Note that we must ALWAYS check specially whether those values are MIN_VALUE + * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as + * a positive number, it overflows back into a negative). Not handling this + * case would often result in infinite recursion. + * + * @class + * @param {number} low the low (signed) 32 bits of the Long. + * @param {number} high the high (signed) 32 bits of the Long. + * @return {Long} + */ + function Long(low, high) { + if (!(this instanceof Long)) return new Long(low, high); + + this._bsontype = 'Long'; + /** + * @type {number} + * @ignore + */ + this.low_ = low | 0; // force into 32 signed bits. + + /** + * @type {number} + * @ignore + */ + this.high_ = high | 0; // force into 32 signed bits. + } + + /** + * Return the int value. + * + * @method + * @return {number} the value, assuming it is a 32-bit integer. + */ + Long.prototype.toInt = function () { + return this.low_; + }; + + /** + * Return the Number value. + * + * @method + * @return {number} the closest floating-point representation to this value. + */ + Long.prototype.toNumber = function () { + return this.high_ * Long.TWO_PWR_32_DBL_ + this.getLowBitsUnsigned(); + }; + + /** + * Return the JSON value. + * + * @method + * @return {string} the JSON representation. + */ + Long.prototype.toJSON = function () { + return this.toString(); + }; + + /** + * Return the String value. + * + * @method + * @param {number} [opt_radix] the radix in which the text should be written. + * @return {string} the textual representation of this value. + */ + Long.prototype.toString = function (opt_radix) { + var radix = opt_radix || 10; + if (radix < 2 || 36 < radix) { + throw Error('radix out of range: ' + radix); + } + + if (this.isZero()) { + return '0'; + } + + if (this.isNegative()) { + if (this.equals(Long.MIN_VALUE)) { + // We need to change the Long value before it can be negated, so we remove + // the bottom-most digit in this base and then recurse to do the rest. + var radixLong = Long.fromNumber(radix); + var div = this.div(radixLong); + var rem = div.multiply(radixLong).subtract(this); + return div.toString(radix) + rem.toInt().toString(radix); + } else { + return '-' + this.negate().toString(radix); + } + } + + // Do several (6) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = Long.fromNumber(Math.pow(radix, 6)); + + rem = this; + var result = ''; + + while (!rem.isZero()) { + var remDiv = rem.div(radixToPower); + var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); + var digits = intval.toString(radix); + + rem = remDiv; + if (rem.isZero()) { + return digits + result; + } else { + while (digits.length < 6) { + digits = '0' + digits; + } + result = '' + digits + result; + } + } + }; + + /** + * Return the high 32-bits value. + * + * @method + * @return {number} the high 32-bits as a signed value. + */ + Long.prototype.getHighBits = function () { + return this.high_; + }; + + /** + * Return the low 32-bits value. + * + * @method + * @return {number} the low 32-bits as a signed value. + */ + Long.prototype.getLowBits = function () { + return this.low_; + }; + + /** + * Return the low unsigned 32-bits value. + * + * @method + * @return {number} the low 32-bits as an unsigned value. + */ + Long.prototype.getLowBitsUnsigned = function () { + return this.low_ >= 0 ? this.low_ : Long.TWO_PWR_32_DBL_ + this.low_; + }; + + /** + * Returns the number of bits needed to represent the absolute value of this Long. + * + * @method + * @return {number} Returns the number of bits needed to represent the absolute value of this Long. + */ + Long.prototype.getNumBitsAbs = function () { + if (this.isNegative()) { + if (this.equals(Long.MIN_VALUE)) { + return 64; + } else { + return this.negate().getNumBitsAbs(); + } + } else { + var val = this.high_ !== 0 ? this.high_ : this.low_; + for (var bit = 31; bit > 0; bit--) { + if ((val & 1 << bit) !== 0) { + break; + } + } + return this.high_ !== 0 ? bit + 33 : bit + 1; + } + }; + + /** + * Return whether this value is zero. + * + * @method + * @return {boolean} whether this value is zero. + */ + Long.prototype.isZero = function () { + return this.high_ === 0 && this.low_ === 0; + }; + + /** + * Return whether this value is negative. + * + * @method + * @return {boolean} whether this value is negative. + */ + Long.prototype.isNegative = function () { + return this.high_ < 0; + }; + + /** + * Return whether this value is odd. + * + * @method + * @return {boolean} whether this value is odd. + */ + Long.prototype.isOdd = function () { + return (this.low_ & 1) === 1; + }; + + /** + * Return whether this Long equals the other + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long equals the other + */ + Long.prototype.equals = function (other) { + return this.high_ === other.high_ && this.low_ === other.low_; + }; + + /** + * Return whether this Long does not equal the other. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long does not equal the other. + */ + Long.prototype.notEquals = function (other) { + return this.high_ !== other.high_ || this.low_ !== other.low_; + }; + + /** + * Return whether this Long is less than the other. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long is less than the other. + */ + Long.prototype.lessThan = function (other) { + return this.compare(other) < 0; + }; + + /** + * Return whether this Long is less than or equal to the other. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long is less than or equal to the other. + */ + Long.prototype.lessThanOrEqual = function (other) { + return this.compare(other) <= 0; + }; + + /** + * Return whether this Long is greater than the other. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long is greater than the other. + */ + Long.prototype.greaterThan = function (other) { + return this.compare(other) > 0; + }; + + /** + * Return whether this Long is greater than or equal to the other. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long is greater than or equal to the other. + */ + Long.prototype.greaterThanOrEqual = function (other) { + return this.compare(other) >= 0; + }; + + /** + * Compares this Long with the given one. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. + */ + Long.prototype.compare = function (other) { + if (this.equals(other)) { + return 0; + } + + var thisNeg = this.isNegative(); + var otherNeg = other.isNegative(); + if (thisNeg && !otherNeg) { + return -1; + } + if (!thisNeg && otherNeg) { + return 1; + } + + // at this point, the signs are the same, so subtraction will not overflow + if (this.subtract(other).isNegative()) { + return -1; + } else { + return 1; + } + }; + + /** + * The negation of this value. + * + * @method + * @return {Long} the negation of this value. + */ + Long.prototype.negate = function () { + if (this.equals(Long.MIN_VALUE)) { + return Long.MIN_VALUE; + } else { + return this.not().add(Long.ONE); + } + }; + + /** + * Returns the sum of this and the given Long. + * + * @method + * @param {Long} other Long to add to this one. + * @return {Long} the sum of this and the given Long. + */ + Long.prototype.add = function (other) { + // Divide each number into 4 chunks of 16 bits, and then sum the chunks. + + var a48 = this.high_ >>> 16; + var a32 = this.high_ & 0xffff; + var a16 = this.low_ >>> 16; + var a00 = this.low_ & 0xffff; + + var b48 = other.high_ >>> 16; + var b32 = other.high_ & 0xffff; + var b16 = other.low_ >>> 16; + var b00 = other.low_ & 0xffff; + + var c48 = 0, + c32 = 0, + c16 = 0, + c00 = 0; + c00 += a00 + b00; + c16 += c00 >>> 16; + c00 &= 0xffff; + c16 += a16 + b16; + c32 += c16 >>> 16; + c16 &= 0xffff; + c32 += a32 + b32; + c48 += c32 >>> 16; + c32 &= 0xffff; + c48 += a48 + b48; + c48 &= 0xffff; + return Long.fromBits(c16 << 16 | c00, c48 << 16 | c32); + }; + + /** + * Returns the difference of this and the given Long. + * + * @method + * @param {Long} other Long to subtract from this. + * @return {Long} the difference of this and the given Long. + */ + Long.prototype.subtract = function (other) { + return this.add(other.negate()); + }; + + /** + * Returns the product of this and the given Long. + * + * @method + * @param {Long} other Long to multiply with this. + * @return {Long} the product of this and the other. + */ + Long.prototype.multiply = function (other) { + if (this.isZero()) { + return Long.ZERO; + } else if (other.isZero()) { + return Long.ZERO; + } + + if (this.equals(Long.MIN_VALUE)) { + return other.isOdd() ? Long.MIN_VALUE : Long.ZERO; + } else if (other.equals(Long.MIN_VALUE)) { + return this.isOdd() ? Long.MIN_VALUE : Long.ZERO; + } + + if (this.isNegative()) { + if (other.isNegative()) { + return this.negate().multiply(other.negate()); + } else { + return this.negate().multiply(other).negate(); + } + } else if (other.isNegative()) { + return this.multiply(other.negate()).negate(); + } + + // If both Longs are small, use float multiplication + if (this.lessThan(Long.TWO_PWR_24_) && other.lessThan(Long.TWO_PWR_24_)) { + return Long.fromNumber(this.toNumber() * other.toNumber()); + } + + // Divide each Long into 4 chunks of 16 bits, and then add up 4x4 products. + // We can skip products that would overflow. + + var a48 = this.high_ >>> 16; + var a32 = this.high_ & 0xffff; + var a16 = this.low_ >>> 16; + var a00 = this.low_ & 0xffff; + + var b48 = other.high_ >>> 16; + var b32 = other.high_ & 0xffff; + var b16 = other.low_ >>> 16; + var b00 = other.low_ & 0xffff; + + var c48 = 0, + c32 = 0, + c16 = 0, + c00 = 0; + c00 += a00 * b00; + c16 += c00 >>> 16; + c00 &= 0xffff; + c16 += a16 * b00; + c32 += c16 >>> 16; + c16 &= 0xffff; + c16 += a00 * b16; + c32 += c16 >>> 16; + c16 &= 0xffff; + c32 += a32 * b00; + c48 += c32 >>> 16; + c32 &= 0xffff; + c32 += a16 * b16; + c48 += c32 >>> 16; + c32 &= 0xffff; + c32 += a00 * b32; + c48 += c32 >>> 16; + c32 &= 0xffff; + c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; + c48 &= 0xffff; + return Long.fromBits(c16 << 16 | c00, c48 << 16 | c32); + }; + + /** + * Returns this Long divided by the given one. + * + * @method + * @param {Long} other Long by which to divide. + * @return {Long} this Long divided by the given one. + */ + Long.prototype.div = function (other) { + if (other.isZero()) { + throw Error('division by zero'); + } else if (this.isZero()) { + return Long.ZERO; + } + + if (this.equals(Long.MIN_VALUE)) { + if (other.equals(Long.ONE) || other.equals(Long.NEG_ONE)) { + return Long.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE + } else if (other.equals(Long.MIN_VALUE)) { + return Long.ONE; + } else { + // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. + var halfThis = this.shiftRight(1); + var approx = halfThis.div(other).shiftLeft(1); + if (approx.equals(Long.ZERO)) { + return other.isNegative() ? Long.ONE : Long.NEG_ONE; + } else { + var rem = this.subtract(other.multiply(approx)); + var result = approx.add(rem.div(other)); + return result; + } + } + } else if (other.equals(Long.MIN_VALUE)) { + return Long.ZERO; + } + + if (this.isNegative()) { + if (other.isNegative()) { + return this.negate().div(other.negate()); + } else { + return this.negate().div(other).negate(); + } + } else if (other.isNegative()) { + return this.div(other.negate()).negate(); + } + + // Repeat the following until the remainder is less than other: find a + // floating-point that approximates remainder / other *from below*, add this + // into the result, and subtract it from the remainder. It is critical that + // the approximate value is less than or equal to the real value so that the + // remainder never becomes negative. + var res = Long.ZERO; + rem = this; + while (rem.greaterThanOrEqual(other)) { + // Approximate the result of division. This may be a little greater or + // smaller than the actual value. + approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); + + // We will tweak the approximate result by changing it in the 48-th digit or + // the smallest non-fractional digit, whichever is larger. + var log2 = Math.ceil(Math.log(approx) / Math.LN2); + var delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48); + + // Decrease the approximation until it is smaller than the remainder. Note + // that if it is too large, the product overflows and is negative. + var approxRes = Long.fromNumber(approx); + var approxRem = approxRes.multiply(other); + while (approxRem.isNegative() || approxRem.greaterThan(rem)) { + approx -= delta; + approxRes = Long.fromNumber(approx); + approxRem = approxRes.multiply(other); + } + + // We know the answer can't be zero... and actually, zero would cause + // infinite recursion since we would make no progress. + if (approxRes.isZero()) { + approxRes = Long.ONE; + } + + res = res.add(approxRes); + rem = rem.subtract(approxRem); + } + return res; + }; + + /** + * Returns this Long modulo the given one. + * + * @method + * @param {Long} other Long by which to mod. + * @return {Long} this Long modulo the given one. + */ + Long.prototype.modulo = function (other) { + return this.subtract(this.div(other).multiply(other)); + }; + + /** + * The bitwise-NOT of this value. + * + * @method + * @return {Long} the bitwise-NOT of this value. + */ + Long.prototype.not = function () { + return Long.fromBits(~this.low_, ~this.high_); + }; + + /** + * Returns the bitwise-AND of this Long and the given one. + * + * @method + * @param {Long} other the Long with which to AND. + * @return {Long} the bitwise-AND of this and the other. + */ + Long.prototype.and = function (other) { + return Long.fromBits(this.low_ & other.low_, this.high_ & other.high_); + }; + + /** + * Returns the bitwise-OR of this Long and the given one. + * + * @method + * @param {Long} other the Long with which to OR. + * @return {Long} the bitwise-OR of this and the other. + */ + Long.prototype.or = function (other) { + return Long.fromBits(this.low_ | other.low_, this.high_ | other.high_); + }; + + /** + * Returns the bitwise-XOR of this Long and the given one. + * + * @method + * @param {Long} other the Long with which to XOR. + * @return {Long} the bitwise-XOR of this and the other. + */ + Long.prototype.xor = function (other) { + return Long.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); + }; + + /** + * Returns this Long with bits shifted to the left by the given amount. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Long} this shifted to the left by the given amount. + */ + Long.prototype.shiftLeft = function (numBits) { + numBits &= 63; + if (numBits === 0) { + return this; + } else { + var low = this.low_; + if (numBits < 32) { + var high = this.high_; + return Long.fromBits(low << numBits, high << numBits | low >>> 32 - numBits); + } else { + return Long.fromBits(0, low << numBits - 32); + } + } + }; + + /** + * Returns this Long with bits shifted to the right by the given amount. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Long} this shifted to the right by the given amount. + */ + Long.prototype.shiftRight = function (numBits) { + numBits &= 63; + if (numBits === 0) { + return this; + } else { + var high = this.high_; + if (numBits < 32) { + var low = this.low_; + return Long.fromBits(low >>> numBits | high << 32 - numBits, high >> numBits); + } else { + return Long.fromBits(high >> numBits - 32, high >= 0 ? 0 : -1); + } + } + }; + + /** + * Returns this Long with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Long} this shifted to the right by the given amount, with zeros placed into the new leading bits. + */ + Long.prototype.shiftRightUnsigned = function (numBits) { + numBits &= 63; + if (numBits === 0) { + return this; + } else { + var high = this.high_; + if (numBits < 32) { + var low = this.low_; + return Long.fromBits(low >>> numBits | high << 32 - numBits, high >>> numBits); + } else if (numBits === 32) { + return Long.fromBits(high, 0); + } else { + return Long.fromBits(high >>> numBits - 32, 0); + } + } + }; + + /** + * Returns a Long representing the given (32-bit) integer value. + * + * @method + * @param {number} value the 32-bit integer in question. + * @return {Long} the corresponding Long value. + */ + Long.fromInt = function (value) { + if (-128 <= value && value < 128) { + var cachedObj = Long.INT_CACHE_[value]; + if (cachedObj) { + return cachedObj; + } + } + + var obj = new Long(value | 0, value < 0 ? -1 : 0); + if (-128 <= value && value < 128) { + Long.INT_CACHE_[value] = obj; + } + return obj; + }; + + /** + * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. + * + * @method + * @param {number} value the number in question. + * @return {Long} the corresponding Long value. + */ + Long.fromNumber = function (value) { + if (isNaN(value) || !isFinite(value)) { + return Long.ZERO; + } else if (value <= -Long.TWO_PWR_63_DBL_) { + return Long.MIN_VALUE; + } else if (value + 1 >= Long.TWO_PWR_63_DBL_) { + return Long.MAX_VALUE; + } else if (value < 0) { + return Long.fromNumber(-value).negate(); + } else { + return new Long(value % Long.TWO_PWR_32_DBL_ | 0, value / Long.TWO_PWR_32_DBL_ | 0); + } + }; + + /** + * Returns a Long representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. + * + * @method + * @param {number} lowBits the low 32-bits. + * @param {number} highBits the high 32-bits. + * @return {Long} the corresponding Long value. + */ + Long.fromBits = function (lowBits, highBits) { + return new Long(lowBits, highBits); + }; + + /** + * Returns a Long representation of the given string, written using the given radix. + * + * @method + * @param {string} str the textual representation of the Long. + * @param {number} opt_radix the radix in which the text is written. + * @return {Long} the corresponding Long value. + */ + Long.fromString = function (str, opt_radix) { + if (str.length === 0) { + throw Error('number format error: empty string'); + } + + var radix = opt_radix || 10; + if (radix < 2 || 36 < radix) { + throw Error('radix out of range: ' + radix); + } + + if (str.charAt(0) === '-') { + return Long.fromString(str.substring(1), radix).negate(); + } else if (str.indexOf('-') >= 0) { + throw Error('number format error: interior "-" character: ' + str); + } + + // Do several (8) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = Long.fromNumber(Math.pow(radix, 8)); + + var result = Long.ZERO; + for (var i = 0; i < str.length; i += 8) { + var size = Math.min(8, str.length - i); + var value = parseInt(str.substring(i, i + size), radix); + if (size < 8) { + var power = Long.fromNumber(Math.pow(radix, size)); + result = result.multiply(power).add(Long.fromNumber(value)); + } else { + result = result.multiply(radixToPower); + result = result.add(Long.fromNumber(value)); + } + } + return result; + }; + + // NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the + // from* methods on which they depend. + + /** + * A cache of the Long representations of small integer values. + * @type {Object} + * @ignore + */ + Long.INT_CACHE_ = {}; + + // NOTE: the compiler should inline these constant values below and then remove + // these variables, so there should be no runtime penalty for these. + + /** + * Number used repeated below in calculations. This must appear before the + * first call to any from* function below. + * @type {number} + * @ignore + */ + Long.TWO_PWR_16_DBL_ = 1 << 16; + + /** + * @type {number} + * @ignore + */ + Long.TWO_PWR_24_DBL_ = 1 << 24; + + /** + * @type {number} + * @ignore + */ + Long.TWO_PWR_32_DBL_ = Long.TWO_PWR_16_DBL_ * Long.TWO_PWR_16_DBL_; + + /** + * @type {number} + * @ignore + */ + Long.TWO_PWR_31_DBL_ = Long.TWO_PWR_32_DBL_ / 2; + + /** + * @type {number} + * @ignore + */ + Long.TWO_PWR_48_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_16_DBL_; + + /** + * @type {number} + * @ignore + */ + Long.TWO_PWR_64_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_32_DBL_; + + /** + * @type {number} + * @ignore + */ + Long.TWO_PWR_63_DBL_ = Long.TWO_PWR_64_DBL_ / 2; + + /** @type {Long} */ + Long.ZERO = Long.fromInt(0); + + /** @type {Long} */ + Long.ONE = Long.fromInt(1); + + /** @type {Long} */ + Long.NEG_ONE = Long.fromInt(-1); + + /** @type {Long} */ + Long.MAX_VALUE = Long.fromBits(0xffffffff | 0, 0x7fffffff | 0); + + /** @type {Long} */ + Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0); + + /** + * @type {Long} + * @ignore + */ + Long.TWO_PWR_24_ = Long.fromInt(1 << 24); + + /** + * Expose. + */ + module.exports = Long; + module.exports.Long = Long; + +/***/ }), +/* 331 */ +/***/ (function(module, exports) { + + /** + * A class representation of the BSON Double type. + * + * @class + * @param {number} value the number we want to represent as a double. + * @return {Double} + */ + function Double(value) { + if (!(this instanceof Double)) return new Double(value); + + this._bsontype = 'Double'; + this.value = value; + } + + /** + * Access the number value. + * + * @method + * @return {number} returns the wrapped double number. + */ + Double.prototype.valueOf = function () { + return this.value; + }; + + /** + * @ignore + */ + Double.prototype.toJSON = function () { + return this.value; + }; + + module.exports = Double; + module.exports.Double = Double; + +/***/ }), +/* 332 */ +/***/ (function(module, exports) { + + // Licensed under the Apache License, Version 2.0 (the "License"); + // you may not use this file except in compliance with the License. + // You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + // Copyright 2009 Google Inc. All Rights Reserved + + /** + * This type is for INTERNAL use in MongoDB only and should not be used in applications. + * The appropriate corresponding type is the JavaScript Date type. + * + * Defines a Timestamp class for representing a 64-bit two's-complement + * integer value, which faithfully simulates the behavior of a Java "Timestamp". This + * implementation is derived from TimestampLib in GWT. + * + * Constructs a 64-bit two's-complement integer, given its low and high 32-bit + * values as *signed* integers. See the from* functions below for more + * convenient ways of constructing Timestamps. + * + * The internal representation of a Timestamp is the two given signed, 32-bit values. + * We use 32-bit pieces because these are the size of integers on which + * Javascript performs bit-operations. For operations like addition and + * multiplication, we split each number into 16-bit pieces, which can easily be + * multiplied within Javascript's floating-point representation without overflow + * or change in sign. + * + * In the algorithms below, we frequently reduce the negative case to the + * positive case by negating the input(s) and then post-processing the result. + * Note that we must ALWAYS check specially whether those values are MIN_VALUE + * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as + * a positive number, it overflows back into a negative). Not handling this + * case would often result in infinite recursion. + * + * @class + * @param {number} low the low (signed) 32 bits of the Timestamp. + * @param {number} high the high (signed) 32 bits of the Timestamp. + */ + function Timestamp(low, high) { + if (!(this instanceof Timestamp)) return new Timestamp(low, high); + this._bsontype = 'Timestamp'; + /** + * @type {number} + * @ignore + */ + this.low_ = low | 0; // force into 32 signed bits. + + /** + * @type {number} + * @ignore + */ + this.high_ = high | 0; // force into 32 signed bits. + } + + /** + * Return the int value. + * + * @return {number} the value, assuming it is a 32-bit integer. + */ + Timestamp.prototype.toInt = function () { + return this.low_; + }; + + /** + * Return the Number value. + * + * @method + * @return {number} the closest floating-point representation to this value. + */ + Timestamp.prototype.toNumber = function () { + return this.high_ * Timestamp.TWO_PWR_32_DBL_ + this.getLowBitsUnsigned(); + }; + + /** + * Return the JSON value. + * + * @method + * @return {string} the JSON representation. + */ + Timestamp.prototype.toJSON = function () { + return this.toString(); + }; + + /** + * Return the String value. + * + * @method + * @param {number} [opt_radix] the radix in which the text should be written. + * @return {string} the textual representation of this value. + */ + Timestamp.prototype.toString = function (opt_radix) { + var radix = opt_radix || 10; + if (radix < 2 || 36 < radix) { + throw Error('radix out of range: ' + radix); + } + + if (this.isZero()) { + return '0'; + } + + if (this.isNegative()) { + if (this.equals(Timestamp.MIN_VALUE)) { + // We need to change the Timestamp value before it can be negated, so we remove + // the bottom-most digit in this base and then recurse to do the rest. + var radixTimestamp = Timestamp.fromNumber(radix); + var div = this.div(radixTimestamp); + var rem = div.multiply(radixTimestamp).subtract(this); + return div.toString(radix) + rem.toInt().toString(radix); + } else { + return '-' + this.negate().toString(radix); + } + } + + // Do several (6) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = Timestamp.fromNumber(Math.pow(radix, 6)); + + rem = this; + var result = ''; + + while (!rem.isZero()) { + var remDiv = rem.div(radixToPower); + var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); + var digits = intval.toString(radix); + + rem = remDiv; + if (rem.isZero()) { + return digits + result; + } else { + while (digits.length < 6) { + digits = '0' + digits; + } + result = '' + digits + result; + } + } + }; + + /** + * Return the high 32-bits value. + * + * @method + * @return {number} the high 32-bits as a signed value. + */ + Timestamp.prototype.getHighBits = function () { + return this.high_; + }; + + /** + * Return the low 32-bits value. + * + * @method + * @return {number} the low 32-bits as a signed value. + */ + Timestamp.prototype.getLowBits = function () { + return this.low_; + }; + + /** + * Return the low unsigned 32-bits value. + * + * @method + * @return {number} the low 32-bits as an unsigned value. + */ + Timestamp.prototype.getLowBitsUnsigned = function () { + return this.low_ >= 0 ? this.low_ : Timestamp.TWO_PWR_32_DBL_ + this.low_; + }; + + /** + * Returns the number of bits needed to represent the absolute value of this Timestamp. + * + * @method + * @return {number} Returns the number of bits needed to represent the absolute value of this Timestamp. + */ + Timestamp.prototype.getNumBitsAbs = function () { + if (this.isNegative()) { + if (this.equals(Timestamp.MIN_VALUE)) { + return 64; + } else { + return this.negate().getNumBitsAbs(); + } + } else { + var val = this.high_ !== 0 ? this.high_ : this.low_; + for (var bit = 31; bit > 0; bit--) { + if ((val & 1 << bit) !== 0) { + break; + } + } + return this.high_ !== 0 ? bit + 33 : bit + 1; + } + }; + + /** + * Return whether this value is zero. + * + * @method + * @return {boolean} whether this value is zero. + */ + Timestamp.prototype.isZero = function () { + return this.high_ === 0 && this.low_ === 0; + }; + + /** + * Return whether this value is negative. + * + * @method + * @return {boolean} whether this value is negative. + */ + Timestamp.prototype.isNegative = function () { + return this.high_ < 0; + }; + + /** + * Return whether this value is odd. + * + * @method + * @return {boolean} whether this value is odd. + */ + Timestamp.prototype.isOdd = function () { + return (this.low_ & 1) === 1; + }; + + /** + * Return whether this Timestamp equals the other + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp equals the other + */ + Timestamp.prototype.equals = function (other) { + return this.high_ === other.high_ && this.low_ === other.low_; + }; + + /** + * Return whether this Timestamp does not equal the other. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp does not equal the other. + */ + Timestamp.prototype.notEquals = function (other) { + return this.high_ !== other.high_ || this.low_ !== other.low_; + }; + + /** + * Return whether this Timestamp is less than the other. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp is less than the other. + */ + Timestamp.prototype.lessThan = function (other) { + return this.compare(other) < 0; + }; + + /** + * Return whether this Timestamp is less than or equal to the other. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp is less than or equal to the other. + */ + Timestamp.prototype.lessThanOrEqual = function (other) { + return this.compare(other) <= 0; + }; + + /** + * Return whether this Timestamp is greater than the other. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp is greater than the other. + */ + Timestamp.prototype.greaterThan = function (other) { + return this.compare(other) > 0; + }; + + /** + * Return whether this Timestamp is greater than or equal to the other. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp is greater than or equal to the other. + */ + Timestamp.prototype.greaterThanOrEqual = function (other) { + return this.compare(other) >= 0; + }; + + /** + * Compares this Timestamp with the given one. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. + */ + Timestamp.prototype.compare = function (other) { + if (this.equals(other)) { + return 0; + } + + var thisNeg = this.isNegative(); + var otherNeg = other.isNegative(); + if (thisNeg && !otherNeg) { + return -1; + } + if (!thisNeg && otherNeg) { + return 1; + } + + // at this point, the signs are the same, so subtraction will not overflow + if (this.subtract(other).isNegative()) { + return -1; + } else { + return 1; + } + }; + + /** + * The negation of this value. + * + * @method + * @return {Timestamp} the negation of this value. + */ + Timestamp.prototype.negate = function () { + if (this.equals(Timestamp.MIN_VALUE)) { + return Timestamp.MIN_VALUE; + } else { + return this.not().add(Timestamp.ONE); + } + }; + + /** + * Returns the sum of this and the given Timestamp. + * + * @method + * @param {Timestamp} other Timestamp to add to this one. + * @return {Timestamp} the sum of this and the given Timestamp. + */ + Timestamp.prototype.add = function (other) { + // Divide each number into 4 chunks of 16 bits, and then sum the chunks. + + var a48 = this.high_ >>> 16; + var a32 = this.high_ & 0xffff; + var a16 = this.low_ >>> 16; + var a00 = this.low_ & 0xffff; + + var b48 = other.high_ >>> 16; + var b32 = other.high_ & 0xffff; + var b16 = other.low_ >>> 16; + var b00 = other.low_ & 0xffff; + + var c48 = 0, + c32 = 0, + c16 = 0, + c00 = 0; + c00 += a00 + b00; + c16 += c00 >>> 16; + c00 &= 0xffff; + c16 += a16 + b16; + c32 += c16 >>> 16; + c16 &= 0xffff; + c32 += a32 + b32; + c48 += c32 >>> 16; + c32 &= 0xffff; + c48 += a48 + b48; + c48 &= 0xffff; + return Timestamp.fromBits(c16 << 16 | c00, c48 << 16 | c32); + }; + + /** + * Returns the difference of this and the given Timestamp. + * + * @method + * @param {Timestamp} other Timestamp to subtract from this. + * @return {Timestamp} the difference of this and the given Timestamp. + */ + Timestamp.prototype.subtract = function (other) { + return this.add(other.negate()); + }; + + /** + * Returns the product of this and the given Timestamp. + * + * @method + * @param {Timestamp} other Timestamp to multiply with this. + * @return {Timestamp} the product of this and the other. + */ + Timestamp.prototype.multiply = function (other) { + if (this.isZero()) { + return Timestamp.ZERO; + } else if (other.isZero()) { + return Timestamp.ZERO; + } + + if (this.equals(Timestamp.MIN_VALUE)) { + return other.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; + } else if (other.equals(Timestamp.MIN_VALUE)) { + return this.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; + } + + if (this.isNegative()) { + if (other.isNegative()) { + return this.negate().multiply(other.negate()); + } else { + return this.negate().multiply(other).negate(); + } + } else if (other.isNegative()) { + return this.multiply(other.negate()).negate(); + } + + // If both Timestamps are small, use float multiplication + if (this.lessThan(Timestamp.TWO_PWR_24_) && other.lessThan(Timestamp.TWO_PWR_24_)) { + return Timestamp.fromNumber(this.toNumber() * other.toNumber()); + } + + // Divide each Timestamp into 4 chunks of 16 bits, and then add up 4x4 products. + // We can skip products that would overflow. + + var a48 = this.high_ >>> 16; + var a32 = this.high_ & 0xffff; + var a16 = this.low_ >>> 16; + var a00 = this.low_ & 0xffff; + + var b48 = other.high_ >>> 16; + var b32 = other.high_ & 0xffff; + var b16 = other.low_ >>> 16; + var b00 = other.low_ & 0xffff; + + var c48 = 0, + c32 = 0, + c16 = 0, + c00 = 0; + c00 += a00 * b00; + c16 += c00 >>> 16; + c00 &= 0xffff; + c16 += a16 * b00; + c32 += c16 >>> 16; + c16 &= 0xffff; + c16 += a00 * b16; + c32 += c16 >>> 16; + c16 &= 0xffff; + c32 += a32 * b00; + c48 += c32 >>> 16; + c32 &= 0xffff; + c32 += a16 * b16; + c48 += c32 >>> 16; + c32 &= 0xffff; + c32 += a00 * b32; + c48 += c32 >>> 16; + c32 &= 0xffff; + c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; + c48 &= 0xffff; + return Timestamp.fromBits(c16 << 16 | c00, c48 << 16 | c32); + }; + + /** + * Returns this Timestamp divided by the given one. + * + * @method + * @param {Timestamp} other Timestamp by which to divide. + * @return {Timestamp} this Timestamp divided by the given one. + */ + Timestamp.prototype.div = function (other) { + if (other.isZero()) { + throw Error('division by zero'); + } else if (this.isZero()) { + return Timestamp.ZERO; + } + + if (this.equals(Timestamp.MIN_VALUE)) { + if (other.equals(Timestamp.ONE) || other.equals(Timestamp.NEG_ONE)) { + return Timestamp.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE + } else if (other.equals(Timestamp.MIN_VALUE)) { + return Timestamp.ONE; + } else { + // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. + var halfThis = this.shiftRight(1); + var approx = halfThis.div(other).shiftLeft(1); + if (approx.equals(Timestamp.ZERO)) { + return other.isNegative() ? Timestamp.ONE : Timestamp.NEG_ONE; + } else { + var rem = this.subtract(other.multiply(approx)); + var result = approx.add(rem.div(other)); + return result; + } + } + } else if (other.equals(Timestamp.MIN_VALUE)) { + return Timestamp.ZERO; + } + + if (this.isNegative()) { + if (other.isNegative()) { + return this.negate().div(other.negate()); + } else { + return this.negate().div(other).negate(); + } + } else if (other.isNegative()) { + return this.div(other.negate()).negate(); + } + + // Repeat the following until the remainder is less than other: find a + // floating-point that approximates remainder / other *from below*, add this + // into the result, and subtract it from the remainder. It is critical that + // the approximate value is less than or equal to the real value so that the + // remainder never becomes negative. + var res = Timestamp.ZERO; + rem = this; + while (rem.greaterThanOrEqual(other)) { + // Approximate the result of division. This may be a little greater or + // smaller than the actual value. + approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); + + // We will tweak the approximate result by changing it in the 48-th digit or + // the smallest non-fractional digit, whichever is larger. + var log2 = Math.ceil(Math.log(approx) / Math.LN2); + var delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48); + + // Decrease the approximation until it is smaller than the remainder. Note + // that if it is too large, the product overflows and is negative. + var approxRes = Timestamp.fromNumber(approx); + var approxRem = approxRes.multiply(other); + while (approxRem.isNegative() || approxRem.greaterThan(rem)) { + approx -= delta; + approxRes = Timestamp.fromNumber(approx); + approxRem = approxRes.multiply(other); + } + + // We know the answer can't be zero... and actually, zero would cause + // infinite recursion since we would make no progress. + if (approxRes.isZero()) { + approxRes = Timestamp.ONE; + } + + res = res.add(approxRes); + rem = rem.subtract(approxRem); + } + return res; + }; + + /** + * Returns this Timestamp modulo the given one. + * + * @method + * @param {Timestamp} other Timestamp by which to mod. + * @return {Timestamp} this Timestamp modulo the given one. + */ + Timestamp.prototype.modulo = function (other) { + return this.subtract(this.div(other).multiply(other)); + }; + + /** + * The bitwise-NOT of this value. + * + * @method + * @return {Timestamp} the bitwise-NOT of this value. + */ + Timestamp.prototype.not = function () { + return Timestamp.fromBits(~this.low_, ~this.high_); + }; + + /** + * Returns the bitwise-AND of this Timestamp and the given one. + * + * @method + * @param {Timestamp} other the Timestamp with which to AND. + * @return {Timestamp} the bitwise-AND of this and the other. + */ + Timestamp.prototype.and = function (other) { + return Timestamp.fromBits(this.low_ & other.low_, this.high_ & other.high_); + }; + + /** + * Returns the bitwise-OR of this Timestamp and the given one. + * + * @method + * @param {Timestamp} other the Timestamp with which to OR. + * @return {Timestamp} the bitwise-OR of this and the other. + */ + Timestamp.prototype.or = function (other) { + return Timestamp.fromBits(this.low_ | other.low_, this.high_ | other.high_); + }; + + /** + * Returns the bitwise-XOR of this Timestamp and the given one. + * + * @method + * @param {Timestamp} other the Timestamp with which to XOR. + * @return {Timestamp} the bitwise-XOR of this and the other. + */ + Timestamp.prototype.xor = function (other) { + return Timestamp.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); + }; + + /** + * Returns this Timestamp with bits shifted to the left by the given amount. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Timestamp} this shifted to the left by the given amount. + */ + Timestamp.prototype.shiftLeft = function (numBits) { + numBits &= 63; + if (numBits === 0) { + return this; + } else { + var low = this.low_; + if (numBits < 32) { + var high = this.high_; + return Timestamp.fromBits(low << numBits, high << numBits | low >>> 32 - numBits); + } else { + return Timestamp.fromBits(0, low << numBits - 32); + } + } + }; + + /** + * Returns this Timestamp with bits shifted to the right by the given amount. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Timestamp} this shifted to the right by the given amount. + */ + Timestamp.prototype.shiftRight = function (numBits) { + numBits &= 63; + if (numBits === 0) { + return this; + } else { + var high = this.high_; + if (numBits < 32) { + var low = this.low_; + return Timestamp.fromBits(low >>> numBits | high << 32 - numBits, high >> numBits); + } else { + return Timestamp.fromBits(high >> numBits - 32, high >= 0 ? 0 : -1); + } + } + }; + + /** + * Returns this Timestamp with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Timestamp} this shifted to the right by the given amount, with zeros placed into the new leading bits. + */ + Timestamp.prototype.shiftRightUnsigned = function (numBits) { + numBits &= 63; + if (numBits === 0) { + return this; + } else { + var high = this.high_; + if (numBits < 32) { + var low = this.low_; + return Timestamp.fromBits(low >>> numBits | high << 32 - numBits, high >>> numBits); + } else if (numBits === 32) { + return Timestamp.fromBits(high, 0); + } else { + return Timestamp.fromBits(high >>> numBits - 32, 0); + } + } + }; + + /** + * Returns a Timestamp representing the given (32-bit) integer value. + * + * @method + * @param {number} value the 32-bit integer in question. + * @return {Timestamp} the corresponding Timestamp value. + */ + Timestamp.fromInt = function (value) { + if (-128 <= value && value < 128) { + var cachedObj = Timestamp.INT_CACHE_[value]; + if (cachedObj) { + return cachedObj; + } + } + + var obj = new Timestamp(value | 0, value < 0 ? -1 : 0); + if (-128 <= value && value < 128) { + Timestamp.INT_CACHE_[value] = obj; + } + return obj; + }; + + /** + * Returns a Timestamp representing the given value, provided that it is a finite number. Otherwise, zero is returned. + * + * @method + * @param {number} value the number in question. + * @return {Timestamp} the corresponding Timestamp value. + */ + Timestamp.fromNumber = function (value) { + if (isNaN(value) || !isFinite(value)) { + return Timestamp.ZERO; + } else if (value <= -Timestamp.TWO_PWR_63_DBL_) { + return Timestamp.MIN_VALUE; + } else if (value + 1 >= Timestamp.TWO_PWR_63_DBL_) { + return Timestamp.MAX_VALUE; + } else if (value < 0) { + return Timestamp.fromNumber(-value).negate(); + } else { + return new Timestamp(value % Timestamp.TWO_PWR_32_DBL_ | 0, value / Timestamp.TWO_PWR_32_DBL_ | 0); + } + }; + + /** + * Returns a Timestamp representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. + * + * @method + * @param {number} lowBits the low 32-bits. + * @param {number} highBits the high 32-bits. + * @return {Timestamp} the corresponding Timestamp value. + */ + Timestamp.fromBits = function (lowBits, highBits) { + return new Timestamp(lowBits, highBits); + }; + + /** + * Returns a Timestamp representation of the given string, written using the given radix. + * + * @method + * @param {string} str the textual representation of the Timestamp. + * @param {number} opt_radix the radix in which the text is written. + * @return {Timestamp} the corresponding Timestamp value. + */ + Timestamp.fromString = function (str, opt_radix) { + if (str.length === 0) { + throw Error('number format error: empty string'); + } + + var radix = opt_radix || 10; + if (radix < 2 || 36 < radix) { + throw Error('radix out of range: ' + radix); + } + + if (str.charAt(0) === '-') { + return Timestamp.fromString(str.substring(1), radix).negate(); + } else if (str.indexOf('-') >= 0) { + throw Error('number format error: interior "-" character: ' + str); + } + + // Do several (8) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = Timestamp.fromNumber(Math.pow(radix, 8)); + + var result = Timestamp.ZERO; + for (var i = 0; i < str.length; i += 8) { + var size = Math.min(8, str.length - i); + var value = parseInt(str.substring(i, i + size), radix); + if (size < 8) { + var power = Timestamp.fromNumber(Math.pow(radix, size)); + result = result.multiply(power).add(Timestamp.fromNumber(value)); + } else { + result = result.multiply(radixToPower); + result = result.add(Timestamp.fromNumber(value)); + } + } + return result; + }; + + // NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the + // from* methods on which they depend. + + /** + * A cache of the Timestamp representations of small integer values. + * @type {Object} + * @ignore + */ + Timestamp.INT_CACHE_ = {}; + + // NOTE: the compiler should inline these constant values below and then remove + // these variables, so there should be no runtime penalty for these. + + /** + * Number used repeated below in calculations. This must appear before the + * first call to any from* function below. + * @type {number} + * @ignore + */ + Timestamp.TWO_PWR_16_DBL_ = 1 << 16; + + /** + * @type {number} + * @ignore + */ + Timestamp.TWO_PWR_24_DBL_ = 1 << 24; + + /** + * @type {number} + * @ignore + */ + Timestamp.TWO_PWR_32_DBL_ = Timestamp.TWO_PWR_16_DBL_ * Timestamp.TWO_PWR_16_DBL_; + + /** + * @type {number} + * @ignore + */ + Timestamp.TWO_PWR_31_DBL_ = Timestamp.TWO_PWR_32_DBL_ / 2; + + /** + * @type {number} + * @ignore + */ + Timestamp.TWO_PWR_48_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_16_DBL_; + + /** + * @type {number} + * @ignore + */ + Timestamp.TWO_PWR_64_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_32_DBL_; + + /** + * @type {number} + * @ignore + */ + Timestamp.TWO_PWR_63_DBL_ = Timestamp.TWO_PWR_64_DBL_ / 2; + + /** @type {Timestamp} */ + Timestamp.ZERO = Timestamp.fromInt(0); + + /** @type {Timestamp} */ + Timestamp.ONE = Timestamp.fromInt(1); + + /** @type {Timestamp} */ + Timestamp.NEG_ONE = Timestamp.fromInt(-1); + + /** @type {Timestamp} */ + Timestamp.MAX_VALUE = Timestamp.fromBits(0xffffffff | 0, 0x7fffffff | 0); + + /** @type {Timestamp} */ + Timestamp.MIN_VALUE = Timestamp.fromBits(0, 0x80000000 | 0); + + /** + * @type {Timestamp} + * @ignore + */ + Timestamp.TWO_PWR_24_ = Timestamp.fromInt(1 << 24); + + /** + * Expose. + */ + module.exports = Timestamp; + module.exports.Timestamp = Timestamp; + +/***/ }), +/* 333 */ +/***/ (function(module, exports, __webpack_require__) { + + /* WEBPACK VAR INJECTION */(function(Buffer, process) {// Custom inspect property name / symbol. + var inspect = 'inspect'; + + var utils = __webpack_require__(339); + + /** + * Machine id. + * + * Create a random 3-byte value (i.e. unique for this + * process). Other drivers use a md5 of the machine id here, but + * that would mean an asyc call to gethostname, so we don't bother. + * @ignore + */ + var MACHINE_ID = parseInt(Math.random() * 0xffffff, 10); + + // Regular expression that checks for hex value + var checkForHexRegExp = new RegExp('^[0-9a-fA-F]{24}$'); + + // Check if buffer exists + try { + if (Buffer && Buffer.from) { + var hasBufferType = true; + inspect = __webpack_require__(340).inspect.custom || 'inspect'; + } + } catch (err) { + hasBufferType = false; + } + + /** + * Create a new ObjectID instance + * + * @class + * @param {(string|number)} id Can be a 24 byte hex string, 12 byte binary string or a Number. + * @property {number} generationTime The generation time of this ObjectId instance + * @return {ObjectID} instance of ObjectID. + */ + var ObjectID = function ObjectID(id) { + // Duck-typing to support ObjectId from different npm packages + if (id instanceof ObjectID) return id; + if (!(this instanceof ObjectID)) return new ObjectID(id); + + this._bsontype = 'ObjectID'; + + // The most common usecase (blank id, new objectId instance) + if (id == null || typeof id === 'number') { + // Generate a new id + this.id = this.generate(id); + // If we are caching the hex string + if (ObjectID.cacheHexString) this.__id = this.toString('hex'); + // Return the object + return; + } + + // Check if the passed in id is valid + var valid = ObjectID.isValid(id); + + // Throw an error if it's not a valid setup + if (!valid && id != null) { + throw new Error('Argument passed in must be a single String of 12 bytes or a string of 24 hex characters'); + } else if (valid && typeof id === 'string' && id.length === 24 && hasBufferType) { + return new ObjectID(utils.toBuffer(id, 'hex')); + } else if (valid && typeof id === 'string' && id.length === 24) { + return ObjectID.createFromHexString(id); + } else if (id != null && id.length === 12) { + // assume 12 byte string + this.id = id; + } else if (id != null && id.toHexString) { + // Duck-typing to support ObjectId from different npm packages + return id; + } else { + throw new Error('Argument passed in must be a single String of 12 bytes or a string of 24 hex characters'); + } + + if (ObjectID.cacheHexString) this.__id = this.toString('hex'); + }; + + // Allow usage of ObjectId as well as ObjectID + // var ObjectId = ObjectID; + + // Precomputed hex table enables speedy hex string conversion + var hexTable = []; + for (var i = 0; i < 256; i++) { + hexTable[i] = (i <= 15 ? '0' : '') + i.toString(16); + } + + /** + * Return the ObjectID id as a 24 byte hex string representation + * + * @method + * @return {string} return the 24 byte hex string representation. + */ + ObjectID.prototype.toHexString = function () { + if (ObjectID.cacheHexString && this.__id) return this.__id; + + var hexString = ''; + if (!this.id || !this.id.length) { + throw new Error('invalid ObjectId, ObjectId.id must be either a string or a Buffer, but is [' + JSON.stringify(this.id) + ']'); + } + + if (this.id instanceof _Buffer) { + hexString = convertToHex(this.id); + if (ObjectID.cacheHexString) this.__id = hexString; + return hexString; + } + + for (var i = 0; i < this.id.length; i++) { + hexString += hexTable[this.id.charCodeAt(i)]; + } + + if (ObjectID.cacheHexString) this.__id = hexString; + return hexString; + }; + + /** + * Update the ObjectID index used in generating new ObjectID's on the driver + * + * @method + * @return {number} returns next index value. + * @ignore + */ + ObjectID.prototype.get_inc = function () { + return ObjectID.index = (ObjectID.index + 1) % 0xffffff; + }; + + /** + * Update the ObjectID index used in generating new ObjectID's on the driver + * + * @method + * @return {number} returns next index value. + * @ignore + */ + ObjectID.prototype.getInc = function () { + return this.get_inc(); + }; + + /** + * Generate a 12 byte id buffer used in ObjectID's + * + * @method + * @param {number} [time] optional parameter allowing to pass in a second based timestamp. + * @return {Buffer} return the 12 byte id buffer string. + */ + ObjectID.prototype.generate = function (time) { + if ('number' !== typeof time) { + time = ~~(Date.now() / 1000); + } + + // Use pid + var pid = (typeof process === 'undefined' || process.pid === 1 ? Math.floor(Math.random() * 100000) : process.pid) % 0xffff; + var inc = this.get_inc(); + // Buffer used + var buffer = utils.allocBuffer(12); + // Encode time + buffer[3] = time & 0xff; + buffer[2] = time >> 8 & 0xff; + buffer[1] = time >> 16 & 0xff; + buffer[0] = time >> 24 & 0xff; + // Encode machine + buffer[6] = MACHINE_ID & 0xff; + buffer[5] = MACHINE_ID >> 8 & 0xff; + buffer[4] = MACHINE_ID >> 16 & 0xff; + // Encode pid + buffer[8] = pid & 0xff; + buffer[7] = pid >> 8 & 0xff; + // Encode index + buffer[11] = inc & 0xff; + buffer[10] = inc >> 8 & 0xff; + buffer[9] = inc >> 16 & 0xff; + // Return the buffer + return buffer; + }; + + /** + * Converts the id into a 24 byte hex string for printing + * + * @param {String} format The Buffer toString format parameter. + * @return {String} return the 24 byte hex string representation. + * @ignore + */ + ObjectID.prototype.toString = function (format) { + // Is the id a buffer then use the buffer toString method to return the format + if (this.id && this.id.copy) { + return this.id.toString(typeof format === 'string' ? format : 'hex'); + } + + // if(this.buffer ) + return this.toHexString(); + }; + + /** + * Converts to a string representation of this Id. + * + * @return {String} return the 24 byte hex string representation. + * @ignore + */ + ObjectID.prototype[inspect] = ObjectID.prototype.toString; + + /** + * Converts to its JSON representation. + * + * @return {String} return the 24 byte hex string representation. + * @ignore + */ + ObjectID.prototype.toJSON = function () { + return this.toHexString(); + }; + + /** + * Compares the equality of this ObjectID with `otherID`. + * + * @method + * @param {object} otherID ObjectID instance to compare against. + * @return {boolean} the result of comparing two ObjectID's + */ + ObjectID.prototype.equals = function equals(otherId) { + // var id; + + if (otherId instanceof ObjectID) { + return this.toString() === otherId.toString(); + } else if (typeof otherId === 'string' && ObjectID.isValid(otherId) && otherId.length === 12 && this.id instanceof _Buffer) { + return otherId === this.id.toString('binary'); + } else if (typeof otherId === 'string' && ObjectID.isValid(otherId) && otherId.length === 24) { + return otherId.toLowerCase() === this.toHexString(); + } else if (typeof otherId === 'string' && ObjectID.isValid(otherId) && otherId.length === 12) { + return otherId === this.id; + } else if (otherId != null && (otherId instanceof ObjectID || otherId.toHexString)) { + return otherId.toHexString() === this.toHexString(); + } else { + return false; + } + }; + + /** + * Returns the generation date (accurate up to the second) that this ID was generated. + * + * @method + * @return {date} the generation date + */ + ObjectID.prototype.getTimestamp = function () { + var timestamp = new Date(); + var time = this.id[3] | this.id[2] << 8 | this.id[1] << 16 | this.id[0] << 24; + timestamp.setTime(Math.floor(time) * 1000); + return timestamp; + }; + + /** + * @ignore + */ + ObjectID.index = ~~(Math.random() * 0xffffff); + + /** + * @ignore + */ + ObjectID.createPk = function createPk() { + return new ObjectID(); + }; + + /** + * Creates an ObjectID from a second based number, with the rest of the ObjectID zeroed out. Used for comparisons or sorting the ObjectID. + * + * @method + * @param {number} time an integer number representing a number of seconds. + * @return {ObjectID} return the created ObjectID + */ + ObjectID.createFromTime = function createFromTime(time) { + var buffer = utils.toBuffer([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); + // Encode time into first 4 bytes + buffer[3] = time & 0xff; + buffer[2] = time >> 8 & 0xff; + buffer[1] = time >> 16 & 0xff; + buffer[0] = time >> 24 & 0xff; + // Return the new objectId + return new ObjectID(buffer); + }; + + // Lookup tables + //var encodeLookup = '0123456789abcdef'.split(''); + var decodeLookup = []; + i = 0; + while (i < 10) decodeLookup[0x30 + i] = i++; + while (i < 16) decodeLookup[0x41 - 10 + i] = decodeLookup[0x61 - 10 + i] = i++; + + var _Buffer = Buffer; + var convertToHex = function (bytes) { + return bytes.toString('hex'); + }; + + /** + * Creates an ObjectID from a hex string representation of an ObjectID. + * + * @method + * @param {string} hexString create a ObjectID from a passed in 24 byte hexstring. + * @return {ObjectID} return the created ObjectID + */ + ObjectID.createFromHexString = function createFromHexString(string) { + // Throw an error if it's not a valid setup + if (typeof string === 'undefined' || string != null && string.length !== 24) { + throw new Error('Argument passed in must be a single String of 12 bytes or a string of 24 hex characters'); + } + + // Use Buffer.from method if available + if (hasBufferType) return new ObjectID(utils.toBuffer(string, 'hex')); + + // Calculate lengths + var array = new _Buffer(12); + var n = 0; + var i = 0; + + while (i < 24) { + array[n++] = decodeLookup[string.charCodeAt(i++)] << 4 | decodeLookup[string.charCodeAt(i++)]; + } + + return new ObjectID(array); + }; + + /** + * Checks if a value is a valid bson ObjectId + * + * @method + * @return {boolean} return true if the value is a valid bson ObjectId, return false otherwise. + */ + ObjectID.isValid = function isValid(id) { + if (id == null) return false; + + if (typeof id === 'number') { + return true; + } + + if (typeof id === 'string') { + return id.length === 12 || id.length === 24 && checkForHexRegExp.test(id); + } + + if (id instanceof ObjectID) { + return true; + } + + if (id instanceof _Buffer) { + return true; + } + + // Duck-Typing detection of ObjectId like objects + if (id.toHexString) { + return id.id.length === 12 || id.id.length === 24 && checkForHexRegExp.test(id.id); + } + + return false; + }; + + /** + * @ignore + */ + Object.defineProperty(ObjectID.prototype, 'generationTime', { + enumerable: true, + get: function () { + return this.id[3] | this.id[2] << 8 | this.id[1] << 16 | this.id[0] << 24; + }, + set: function (value) { + // Encode time into first 4 bytes + this.id[3] = value & 0xff; + this.id[2] = value >> 8 & 0xff; + this.id[1] = value >> 16 & 0xff; + this.id[0] = value >> 24 & 0xff; + } + }); + + /** + * Expose. + */ + module.exports = ObjectID; + module.exports.ObjectID = ObjectID; + module.exports.ObjectId = ObjectID; + /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(334).Buffer, __webpack_require__(338))) + +/***/ }), +/* 334 */ +/***/ (function(module, exports, __webpack_require__) { + + /* WEBPACK VAR INJECTION */(function(global) {/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ + /* eslint-disable no-proto */ + + 'use strict' + + var base64 = __webpack_require__(335) + var ieee754 = __webpack_require__(336) + var isArray = __webpack_require__(337) + + exports.Buffer = Buffer + exports.SlowBuffer = SlowBuffer + exports.INSPECT_MAX_BYTES = 50 + + /** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Use Object implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * Due to various browser bugs, sometimes the Object implementation will be used even + * when the browser supports typed arrays. + * + * Note: + * + * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, + * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. + * + * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. + * + * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of + * incorrect length in some situations. + + * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they + * get the Object implementation, which is slower but behaves correctly. + */ + Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined + ? global.TYPED_ARRAY_SUPPORT + : typedArraySupport() + + /* + * Export kMaxLength after typed array support is determined. + */ + exports.kMaxLength = kMaxLength() + + function typedArraySupport () { + try { + var arr = new Uint8Array(1) + arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }} + return arr.foo() === 42 && // typed array instances can be augmented + typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray` + arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray` + } catch (e) { + return false + } + } + + function kMaxLength () { + return Buffer.TYPED_ARRAY_SUPPORT + ? 0x7fffffff + : 0x3fffffff + } + + function createBuffer (that, length) { + if (kMaxLength() < length) { + throw new RangeError('Invalid typed array length') + } + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = new Uint8Array(length) + that.__proto__ = Buffer.prototype + } else { + // Fallback: Return an object instance of the Buffer class + if (that === null) { + that = new Buffer(length) + } + that.length = length + } + + return that + } + + /** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + + function Buffer (arg, encodingOrOffset, length) { + if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { + return new Buffer(arg, encodingOrOffset, length) + } + + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new Error( + 'If encoding is specified then the first argument must be a string' + ) + } + return allocUnsafe(this, arg) + } + return from(this, arg, encodingOrOffset, length) + } + + Buffer.poolSize = 8192 // not used by this implementation + + // TODO: Legacy, not needed anymore. Remove in next major version. + Buffer._augment = function (arr) { + arr.__proto__ = Buffer.prototype + return arr + } + + function from (that, value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } + + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + return fromArrayBuffer(that, value, encodingOrOffset, length) + } + + if (typeof value === 'string') { + return fromString(that, value, encodingOrOffset) + } + + return fromObject(that, value) + } + + /** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ + Buffer.from = function (value, encodingOrOffset, length) { + return from(null, value, encodingOrOffset, length) + } + + if (Buffer.TYPED_ARRAY_SUPPORT) { + Buffer.prototype.__proto__ = Uint8Array.prototype + Buffer.__proto__ = Uint8Array + if (typeof Symbol !== 'undefined' && Symbol.species && + Buffer[Symbol.species] === Buffer) { + // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 + Object.defineProperty(Buffer, Symbol.species, { + value: null, + configurable: true + }) + } + } + + function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be a number') + } else if (size < 0) { + throw new RangeError('"size" argument must not be negative') + } + } + + function alloc (that, size, fill, encoding) { + assertSize(size) + if (size <= 0) { + return createBuffer(that, size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(that, size).fill(fill, encoding) + : createBuffer(that, size).fill(fill) + } + return createBuffer(that, size) + } + + /** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ + Buffer.alloc = function (size, fill, encoding) { + return alloc(null, size, fill, encoding) + } + + function allocUnsafe (that, size) { + assertSize(size) + that = createBuffer(that, size < 0 ? 0 : checked(size) | 0) + if (!Buffer.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < size; ++i) { + that[i] = 0 + } + } + return that + } + + /** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ + Buffer.allocUnsafe = function (size) { + return allocUnsafe(null, size) + } + /** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ + Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(null, size) + } + + function fromString (that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8' + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') + } + + var length = byteLength(string, encoding) | 0 + that = createBuffer(that, length) + + var actual = that.write(string, encoding) + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + that = that.slice(0, actual) + } + + return that + } + + function fromArrayLike (that, array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0 + that = createBuffer(that, length) + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255 + } + return that + } + + function fromArrayBuffer (that, array, byteOffset, length) { + array.byteLength // this throws if `array` is not a valid ArrayBuffer + + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('\'offset\' is out of bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('\'length\' is out of bounds') + } + + if (byteOffset === undefined && length === undefined) { + array = new Uint8Array(array) + } else if (length === undefined) { + array = new Uint8Array(array, byteOffset) + } else { + array = new Uint8Array(array, byteOffset, length) + } + + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = array + that.__proto__ = Buffer.prototype + } else { + // Fallback: Return an object instance of the Buffer class + that = fromArrayLike(that, array) + } + return that + } + + function fromObject (that, obj) { + if (Buffer.isBuffer(obj)) { + var len = checked(obj.length) | 0 + that = createBuffer(that, len) + + if (that.length === 0) { + return that + } + + obj.copy(that, 0, 0, len) + return that + } + + if (obj) { + if ((typeof ArrayBuffer !== 'undefined' && + obj.buffer instanceof ArrayBuffer) || 'length' in obj) { + if (typeof obj.length !== 'number' || isnan(obj.length)) { + return createBuffer(that, 0) + } + return fromArrayLike(that, obj) + } + + if (obj.type === 'Buffer' && isArray(obj.data)) { + return fromArrayLike(that, obj.data) + } + } + + throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') + } + + function checked (length) { + // Note: cannot use `length < kMaxLength()` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= kMaxLength()) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + kMaxLength().toString(16) + ' bytes') + } + return length | 0 + } + + function SlowBuffer (length) { + if (+length != length) { // eslint-disable-line eqeqeq + length = 0 + } + return Buffer.alloc(+length) + } + + Buffer.isBuffer = function isBuffer (b) { + return !!(b != null && b._isBuffer) + } + + Buffer.compare = function compare (a, b) { + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + throw new TypeError('Arguments must be Buffers') + } + + if (a === b) return 0 + + var x = a.length + var y = b.length + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i] + y = b[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 + } + + Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } + } + + Buffer.concat = function concat (list, length) { + if (!isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + var i + if (length === undefined) { + length = 0 + for (i = 0; i < list.length; ++i) { + length += list[i].length + } + } + + var buffer = Buffer.allocUnsafe(length) + var pos = 0 + for (i = 0; i < list.length; ++i) { + var buf = list[i] + if (!Buffer.isBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos) + pos += buf.length + } + return buffer + } + + function byteLength (string, encoding) { + if (Buffer.isBuffer(string)) { + return string.length + } + if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && + (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + string = '' + string + } + + var len = string.length + if (len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + case undefined: + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) return utf8ToBytes(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } + } + Buffer.byteLength = byteLength + + function slowToString (encoding, start, end) { + var loweredCase = false + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0 + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length + } + + if (end <= 0) { + return '' + } + + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0 + start >>>= 0 + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8' + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase() + loweredCase = true + } + } + } + + // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect + // Buffer instances. + Buffer.prototype._isBuffer = true + + function swap (b, n, m) { + var i = b[n] + b[n] = b[m] + b[m] = i + } + + Buffer.prototype.swap16 = function swap16 () { + var len = this.length + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1) + } + return this + } + + Buffer.prototype.swap32 = function swap32 () { + var len = this.length + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3) + swap(this, i + 1, i + 2) + } + return this + } + + Buffer.prototype.swap64 = function swap64 () { + var len = this.length + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7) + swap(this, i + 1, i + 6) + swap(this, i + 2, i + 5) + swap(this, i + 3, i + 4) + } + return this + } + + Buffer.prototype.toString = function toString () { + var length = this.length | 0 + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) + } + + Buffer.prototype.equals = function equals (b) { + if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 + } + + Buffer.prototype.inspect = function inspect () { + var str = '' + var max = exports.INSPECT_MAX_BYTES + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') + if (this.length > max) str += ' ... ' + } + return '' + } + + Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (!Buffer.isBuffer(target)) { + throw new TypeError('Argument must be a Buffer') + } + + if (start === undefined) { + start = 0 + } + if (end === undefined) { + end = target ? target.length : 0 + } + if (thisStart === undefined) { + thisStart = 0 + } + if (thisEnd === undefined) { + thisEnd = this.length + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0 + end >>>= 0 + thisStart >>>= 0 + thisEnd >>>= 0 + + if (this === target) return 0 + + var x = thisEnd - thisStart + var y = end - start + var len = Math.min(x, y) + + var thisCopy = this.slice(thisStart, thisEnd) + var targetCopy = target.slice(start, end) + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i] + y = targetCopy[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 + } + + // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, + // OR the last index of `val` in `buffer` at offset <= `byteOffset`. + // + // Arguments: + // - buffer - a Buffer to search + // - val - a string, Buffer, or number + // - byteOffset - an index into `buffer`; will be clamped to an int32 + // - encoding - an optional encoding, relevant is val is a string + // - dir - true for indexOf, false for lastIndexOf + function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset + byteOffset = 0 + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000 + } + byteOffset = +byteOffset // Coerce to Number. + if (isNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1) + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1 + } else if (byteOffset < 0) { + if (dir) byteOffset = 0 + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding) + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (Buffer.isBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF // Search for a byte value [0-255] + if (Buffer.TYPED_ARRAY_SUPPORT && + typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') + } + + function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1 + var arrLength = arr.length + var valLength = val.length + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase() + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2 + arrLength /= 2 + valLength /= 2 + byteOffset /= 2 + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + var i + if (dir) { + var foundIndex = -1 + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex + foundIndex = -1 + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength + for (i = byteOffset; i >= 0; i--) { + var found = true + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false + break + } + } + if (found) return i + } + } + + return -1 + } + + Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 + } + + Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) + } + + Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) + } + + function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0 + var remaining = buf.length - offset + if (!length) { + length = remaining + } else { + length = Number(length) + if (length > remaining) { + length = remaining + } + } + + // must be an even number of digits + var strLen = string.length + if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') + + if (length > strLen / 2) { + length = strLen / 2 + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16) + if (isNaN(parsed)) return i + buf[offset + i] = parsed + } + return i + } + + function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) + } + + function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) + } + + function latin1Write (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) + } + + function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) + } + + function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) + } + + Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8' + length = this.length + offset = 0 + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset + length = this.length + offset = 0 + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset | 0 + if (isFinite(length)) { + length = length | 0 + if (encoding === undefined) encoding = 'utf8' + } else { + encoding = length + length = undefined + } + // legacy write(string, encoding, offset, length) - remove in v0.13 + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + var remaining = this.length - offset + if (length === undefined || length > remaining) length = remaining + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8' + + var loweredCase = false + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + return asciiWrite(this, string, offset, length) + + case 'latin1': + case 'binary': + return latin1Write(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } + } + + Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } + } + + function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return base64.fromByteArray(buf) + } else { + return base64.fromByteArray(buf.slice(start, end)) + } + } + + function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end) + var res = [] + + var i = start + while (i < end) { + var firstByte = buf[i] + var codePoint = null + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1 + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte + } + break + case 2: + secondByte = buf[i + 1] + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint + } + } + break + case 3: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint + } + } + break + case 4: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + fourthByte = buf[i + 3] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD + bytesPerSequence = 1 + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000 + res.push(codePoint >>> 10 & 0x3FF | 0xD800) + codePoint = 0xDC00 | codePoint & 0x3FF + } + + res.push(codePoint) + i += bytesPerSequence + } + + return decodeCodePointsArray(res) + } + + // Based on http://stackoverflow.com/a/22747272/680742, the browser with + // the lowest limit is Chrome, with 0x10000 args. + // We go 1 magnitude less, for safety + var MAX_ARGUMENTS_LENGTH = 0x1000 + + function decodeCodePointsArray (codePoints) { + var len = codePoints.length + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + var res = '' + var i = 0 + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ) + } + return res + } + + function asciiSlice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F) + } + return ret + } + + function latin1Slice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]) + } + return ret + } + + function hexSlice (buf, start, end) { + var len = buf.length + + if (!start || start < 0) start = 0 + if (!end || end < 0 || end > len) end = len + + var out = '' + for (var i = start; i < end; ++i) { + out += toHex(buf[i]) + } + return out + } + + function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end) + var res = '' + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256) + } + return res + } + + Buffer.prototype.slice = function slice (start, end) { + var len = this.length + start = ~~start + end = end === undefined ? len : ~~end + + if (start < 0) { + start += len + if (start < 0) start = 0 + } else if (start > len) { + start = len + } + + if (end < 0) { + end += len + if (end < 0) end = 0 + } else if (end > len) { + end = len + } + + if (end < start) end = start + + var newBuf + if (Buffer.TYPED_ARRAY_SUPPORT) { + newBuf = this.subarray(start, end) + newBuf.__proto__ = Buffer.prototype + } else { + var sliceLen = end - start + newBuf = new Buffer(sliceLen, undefined) + for (var i = 0; i < sliceLen; ++i) { + newBuf[i] = this[i + start] + } + } + + return newBuf + } + + /* + * Need to make sure that buffer isn't trying to write out of bounds. + */ + function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') + } + + Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + + return val + } + + Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) { + checkOffset(offset, byteLength, this.length) + } + + var val = this[offset + --byteLength] + var mul = 1 + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul + } + + return val + } + + Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length) + return this[offset] + } + + Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + return this[offset] | (this[offset + 1] << 8) + } + + Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + return (this[offset] << 8) | this[offset + 1] + } + + Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) + } + + Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) + } + + Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val + } + + Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var i = byteLength + var mul = 1 + var val = this[offset + --i] + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val + } + + Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length) + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) + } + + Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset] | (this[offset + 1] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val + } + + Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset + 1] | (this[offset] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val + } + + Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) + } + + Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) + } + + Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, true, 23, 4) + } + + Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, false, 23, 4) + } + + Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, true, 52, 8) + } + + Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, false, 52, 8) + } + + function checkInt (buf, value, offset, ext, max, min) { + if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') + } + + Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + var mul = 1 + var i = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength + } + + Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + var i = byteLength - 1 + var mul = 1 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength + } + + Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) + this[offset] = (value & 0xff) + return offset + 1 + } + + function objectWriteUInt16 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffff + value + 1 + for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { + buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> + (littleEndian ? i : 1 - i) * 8 + } + } + + Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + } else { + objectWriteUInt16(this, value, offset, true) + } + return offset + 2 + } + + Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + } else { + objectWriteUInt16(this, value, offset, false) + } + return offset + 2 + } + + function objectWriteUInt32 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffffffff + value + 1 + for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { + buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff + } + } + + Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset + 3] = (value >>> 24) + this[offset + 2] = (value >>> 16) + this[offset + 1] = (value >>> 8) + this[offset] = (value & 0xff) + } else { + objectWriteUInt32(this, value, offset, true) + } + return offset + 4 + } + + Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + } else { + objectWriteUInt32(this, value, offset, false) + } + return offset + 4 + } + + Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = 0 + var mul = 1 + var sub = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength + } + + Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = byteLength - 1 + var mul = 1 + var sub = 0 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength + } + + Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) + if (value < 0) value = 0xff + value + 1 + this[offset] = (value & 0xff) + return offset + 1 + } + + Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + } else { + objectWriteUInt16(this, value, offset, true) + } + return offset + 2 + } + + Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + } else { + objectWriteUInt16(this, value, offset, false) + } + return offset + 2 + } + + Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + this[offset + 2] = (value >>> 16) + this[offset + 3] = (value >>> 24) + } else { + objectWriteUInt32(this, value, offset, true) + } + return offset + 4 + } + + Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (value < 0) value = 0xffffffff + value + 1 + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + } else { + objectWriteUInt32(this, value, offset, false) + } + return offset + 4 + } + + function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') + } + + function writeFloat (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) + } + ieee754.write(buf, value, offset, littleEndian, 23, 4) + return offset + 4 + } + + Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) + } + + Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) + } + + function writeDouble (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) + } + ieee754.write(buf, value, offset, littleEndian, 52, 8) + return offset + 8 + } + + Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) + } + + Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) + } + + // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) + Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!start) start = 0 + if (!end && end !== 0) end = this.length + if (targetStart >= target.length) targetStart = target.length + if (!targetStart) targetStart = 0 + if (end > 0 && end < start) end = start + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start + } + + var len = end - start + var i + + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start] + } + } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { + // ascending copy from start + for (i = 0; i < len; ++i) { + target[i + targetStart] = this[i + start] + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, start + len), + targetStart + ) + } + + return len + } + + // Usage: + // buffer.fill(number[, offset[, end]]) + // buffer.fill(buffer[, offset[, end]]) + // buffer.fill(string[, offset[, end]][, encoding]) + Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start + start = 0 + end = this.length + } else if (typeof end === 'string') { + encoding = end + end = this.length + } + if (val.length === 1) { + var code = val.charCodeAt(0) + if (code < 256) { + val = code + } + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + } else if (typeof val === 'number') { + val = val & 255 + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0 + end = end === undefined ? this.length : end >>> 0 + + if (!val) val = 0 + + var i + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val + } + } else { + var bytes = Buffer.isBuffer(val) + ? val + : utf8ToBytes(new Buffer(val, encoding).toString()) + var len = bytes.length + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len] + } + } + + return this + } + + // HELPER FUNCTIONS + // ================ + + var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g + + function base64clean (str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = stringtrim(str).replace(INVALID_BASE64_RE, '') + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '=' + } + return str + } + + function stringtrim (str) { + if (str.trim) return str.trim() + return str.replace(/^\s+|\s+$/g, '') + } + + function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) + } + + function utf8ToBytes (string, units) { + units = units || Infinity + var codePoint + var length = string.length + var leadSurrogate = null + var bytes = [] + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i) + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } + + // valid lead + leadSurrogate = codePoint + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + leadSurrogate = codePoint + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + } + + leadSurrogate = null + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint) + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else { + throw new Error('Invalid code point') + } + } + + return bytes + } + + function asciiToBytes (str) { + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF) + } + return byteArray + } + + function utf16leToBytes (str, units) { + var c, hi, lo + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i) + hi = c >> 8 + lo = c % 256 + byteArray.push(lo) + byteArray.push(hi) + } + + return byteArray + } + + function base64ToBytes (str) { + return base64.toByteArray(base64clean(str)) + } + + function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i] + } + return i + } + + function isnan (val) { + return val !== val // eslint-disable-line no-self-compare + } + + /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) + +/***/ }), +/* 335 */ +/***/ (function(module, exports) { + + 'use strict' + + exports.byteLength = byteLength + exports.toByteArray = toByteArray + exports.fromByteArray = fromByteArray + + var lookup = [] + var revLookup = [] + var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array + + var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' + for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i] + revLookup[code.charCodeAt(i)] = i + } + + // Support decoding URL-safe base64 strings, as Node.js does. + // See: https://en.wikipedia.org/wiki/Base64#URL_applications + revLookup['-'.charCodeAt(0)] = 62 + revLookup['_'.charCodeAt(0)] = 63 + + function getLens (b64) { + var len = b64.length + + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // Trim off extra bytes after placeholder bytes are found + // See: https://github.com/beatgammit/base64-js/issues/42 + var validLen = b64.indexOf('=') + if (validLen === -1) validLen = len + + var placeHoldersLen = validLen === len + ? 0 + : 4 - (validLen % 4) + + return [validLen, placeHoldersLen] + } + + // base64 is 4/3 + up to two characters of the original data + function byteLength (b64) { + var lens = getLens(b64) + var validLen = lens[0] + var placeHoldersLen = lens[1] + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen + } + + function _byteLength (b64, validLen, placeHoldersLen) { + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen + } + + function toByteArray (b64) { + var tmp + var lens = getLens(b64) + var validLen = lens[0] + var placeHoldersLen = lens[1] + + var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)) + + var curByte = 0 + + // if there are placeholders, only get up to the last complete 4 chars + var len = placeHoldersLen > 0 + ? validLen - 4 + : validLen + + for (var i = 0; i < len; i += 4) { + tmp = + (revLookup[b64.charCodeAt(i)] << 18) | + (revLookup[b64.charCodeAt(i + 1)] << 12) | + (revLookup[b64.charCodeAt(i + 2)] << 6) | + revLookup[b64.charCodeAt(i + 3)] + arr[curByte++] = (tmp >> 16) & 0xFF + arr[curByte++] = (tmp >> 8) & 0xFF + arr[curByte++] = tmp & 0xFF + } + + if (placeHoldersLen === 2) { + tmp = + (revLookup[b64.charCodeAt(i)] << 2) | + (revLookup[b64.charCodeAt(i + 1)] >> 4) + arr[curByte++] = tmp & 0xFF + } + + if (placeHoldersLen === 1) { + tmp = + (revLookup[b64.charCodeAt(i)] << 10) | + (revLookup[b64.charCodeAt(i + 1)] << 4) | + (revLookup[b64.charCodeAt(i + 2)] >> 2) + arr[curByte++] = (tmp >> 8) & 0xFF + arr[curByte++] = tmp & 0xFF + } + + return arr + } + + function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + + lookup[num >> 12 & 0x3F] + + lookup[num >> 6 & 0x3F] + + lookup[num & 0x3F] + } + + function encodeChunk (uint8, start, end) { + var tmp + var output = [] + for (var i = start; i < end; i += 3) { + tmp = + ((uint8[i] << 16) & 0xFF0000) + + ((uint8[i + 1] << 8) & 0xFF00) + + (uint8[i + 2] & 0xFF) + output.push(tripletToBase64(tmp)) + } + return output.join('') + } + + function fromByteArray (uint8) { + var tmp + var len = uint8.length + var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes + var parts = [] + var maxChunkLength = 16383 // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk( + uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength) + )) + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1] + parts.push( + lookup[tmp >> 2] + + lookup[(tmp << 4) & 0x3F] + + '==' + ) + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + uint8[len - 1] + parts.push( + lookup[tmp >> 10] + + lookup[(tmp >> 4) & 0x3F] + + lookup[(tmp << 2) & 0x3F] + + '=' + ) + } + + return parts.join('') + } + + +/***/ }), +/* 336 */ +/***/ (function(module, exports) { + + exports.read = function (buffer, offset, isLE, mLen, nBytes) { + var e, m + var eLen = (nBytes * 8) - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var nBits = -7 + var i = isLE ? (nBytes - 1) : 0 + var d = isLE ? -1 : 1 + var s = buffer[offset + i] + + i += d + + e = s & ((1 << (-nBits)) - 1) + s >>= (-nBits) + nBits += eLen + for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1) + e >>= (-nBits) + nBits += mLen + for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen) + e = e - eBias + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) + } + + exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c + var eLen = (nBytes * 8) - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) + var i = isLE ? 0 : (nBytes - 1) + var d = isLE ? 1 : -1 + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 + + value = Math.abs(value) + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0 + e = eMax + } else { + e = Math.floor(Math.log(value) / Math.LN2) + if (value * (c = Math.pow(2, -e)) < 1) { + e-- + c *= 2 + } + if (e + eBias >= 1) { + value += rt / c + } else { + value += rt * Math.pow(2, 1 - eBias) + } + if (value * c >= 2) { + e++ + c /= 2 + } + + if (e + eBias >= eMax) { + m = 0 + e = eMax + } else if (e + eBias >= 1) { + m = ((value * c) - 1) * Math.pow(2, mLen) + e = e + eBias + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) + e = 0 + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m + eLen += mLen + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128 + } + + +/***/ }), +/* 337 */ +/***/ (function(module, exports) { + + var toString = {}.toString; + + module.exports = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; + }; + + +/***/ }), +/* 338 */ +/***/ (function(module, exports) { + + // shim for using process in browser + var process = module.exports = {}; + + // cached from whatever global is present so that test runners that stub it + // don't break things. But we need to wrap it in a try catch in case it is + // wrapped in strict mode code which doesn't define any globals. It's inside a + // function because try/catches deoptimize in certain engines. + + var cachedSetTimeout; + var cachedClearTimeout; + + function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); + } + function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); + } + (function () { + try { + if (typeof setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } else { + cachedSetTimeout = defaultSetTimout; + } + } catch (e) { + cachedSetTimeout = defaultSetTimout; + } + try { + if (typeof clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; + } + } catch (e) { + cachedClearTimeout = defaultClearTimeout; + } + } ()) + function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + + } + function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + + } + var queue = []; + var draining = false; + var currentQueue; + var queueIndex = -1; + + function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } + } + + function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); + } + + process.nextTick = function (fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } + }; + + // v8 likes predictible objects + function Item(fun, array) { + this.fun = fun; + this.array = array; + } + Item.prototype.run = function () { + this.fun.apply(null, this.array); + }; + process.title = 'browser'; + process.browser = true; + process.env = {}; + process.argv = []; + process.version = ''; // empty string to avoid regexp issues + process.versions = {}; + + function noop() {} + + process.on = noop; + process.addListener = noop; + process.once = noop; + process.off = noop; + process.removeListener = noop; + process.removeAllListeners = noop; + process.emit = noop; + process.prependListener = noop; + process.prependOnceListener = noop; + + process.listeners = function (name) { return [] } + + process.binding = function (name) { + throw new Error('process.binding is not supported'); + }; + + process.cwd = function () { return '/' }; + process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); + }; + process.umask = function() { return 0; }; + + +/***/ }), +/* 339 */ +/***/ (function(module, exports, __webpack_require__) { + + /* WEBPACK VAR INJECTION */(function(Buffer) {'use strict'; + + /** + * Normalizes our expected stringified form of a function across versions of node + * @param {Function} fn The function to stringify + */ + + function normalizedFunctionString(fn) { + return fn.toString().replace(/function *\(/, 'function ('); + } + + function newBuffer(item, encoding) { + return new Buffer(item, encoding); + } + + function allocBuffer() { + return Buffer.alloc.apply(Buffer, arguments); + } + + function toBuffer() { + return Buffer.from.apply(Buffer, arguments); + } + + module.exports = { + normalizedFunctionString: normalizedFunctionString, + allocBuffer: typeof Buffer.alloc === 'function' ? allocBuffer : newBuffer, + toBuffer: typeof Buffer.from === 'function' ? toBuffer : newBuffer + }; + /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(334).Buffer)) + +/***/ }), +/* 340 */ +/***/ (function(module, exports, __webpack_require__) { + + /* WEBPACK VAR INJECTION */(function(global, process) {// Copyright Joyent, Inc. and other Node contributors. + // + // Permission is hereby granted, free of charge, to any person obtaining a + // copy of this software and associated documentation files (the + // "Software"), to deal in the Software without restriction, including + // without limitation the rights to use, copy, modify, merge, publish, + // distribute, sublicense, and/or sell copies of the Software, and to permit + // persons to whom the Software is furnished to do so, subject to the + // following conditions: + // + // The above copyright notice and this permission notice shall be included + // in all copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + // USE OR OTHER DEALINGS IN THE SOFTWARE. + + var formatRegExp = /%[sdj%]/g; + exports.format = function(f) { + if (!isString(f)) { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); + } + return objects.join(' '); + } + + var i = 1; + var args = arguments; + var len = args.length; + var str = String(f).replace(formatRegExp, function(x) { + if (x === '%%') return '%'; + if (i >= len) return x; + switch (x) { + case '%s': return String(args[i++]); + case '%d': return Number(args[i++]); + case '%j': + try { + return JSON.stringify(args[i++]); + } catch (_) { + return '[Circular]'; + } + default: + return x; + } + }); + for (var x = args[i]; i < len; x = args[++i]) { + if (isNull(x) || !isObject(x)) { + str += ' ' + x; + } else { + str += ' ' + inspect(x); + } + } + return str; + }; + + + // Mark that a method should not be used. + // Returns a modified function which warns once by default. + // If --no-deprecation is set, then it is a no-op. + exports.deprecate = function(fn, msg) { + // Allow for deprecating things in the process of starting up. + if (isUndefined(global.process)) { + return function() { + return exports.deprecate(fn, msg).apply(this, arguments); + }; + } + + if (process.noDeprecation === true) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (process.throwDeprecation) { + throw new Error(msg); + } else if (process.traceDeprecation) { + console.trace(msg); + } else { + console.error(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; + }; + + + var debugs = {}; + var debugEnviron; + exports.debuglog = function(set) { + if (isUndefined(debugEnviron)) + debugEnviron = process.env.NODE_DEBUG || ''; + set = set.toUpperCase(); + if (!debugs[set]) { + if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { + var pid = process.pid; + debugs[set] = function() { + var msg = exports.format.apply(exports, arguments); + console.error('%s %d: %s', set, pid, msg); + }; + } else { + debugs[set] = function() {}; + } + } + return debugs[set]; + }; + + + /** + * Echos the value of a value. Trys to print the value out + * in the best way possible given the different types. + * + * @param {Object} obj The object to print out. + * @param {Object} opts Optional options object that alters the output. + */ + /* legacy: obj, showHidden, depth, colors*/ + function inspect(obj, opts) { + // default options + var ctx = { + seen: [], + stylize: stylizeNoColor + }; + // legacy... + if (arguments.length >= 3) ctx.depth = arguments[2]; + if (arguments.length >= 4) ctx.colors = arguments[3]; + if (isBoolean(opts)) { + // legacy... + ctx.showHidden = opts; + } else if (opts) { + // got an "options" object + exports._extend(ctx, opts); + } + // set default options + if (isUndefined(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined(ctx.depth)) ctx.depth = 2; + if (isUndefined(ctx.colors)) ctx.colors = false; + if (isUndefined(ctx.customInspect)) ctx.customInspect = true; + if (ctx.colors) ctx.stylize = stylizeWithColor; + return formatValue(ctx, obj, ctx.depth); + } + exports.inspect = inspect; + + + // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics + inspect.colors = { + 'bold' : [1, 22], + 'italic' : [3, 23], + 'underline' : [4, 24], + 'inverse' : [7, 27], + 'white' : [37, 39], + 'grey' : [90, 39], + 'black' : [30, 39], + 'blue' : [34, 39], + 'cyan' : [36, 39], + 'green' : [32, 39], + 'magenta' : [35, 39], + 'red' : [31, 39], + 'yellow' : [33, 39] + }; + + // Don't use 'blue' not visible on cmd.exe + inspect.styles = { + 'special': 'cyan', + 'number': 'yellow', + 'boolean': 'yellow', + 'undefined': 'grey', + 'null': 'bold', + 'string': 'green', + 'date': 'magenta', + // "name": intentionally not styling + 'regexp': 'red' + }; + + + function stylizeWithColor(str, styleType) { + var style = inspect.styles[styleType]; + + if (style) { + return '\u001b[' + inspect.colors[style][0] + 'm' + str + + '\u001b[' + inspect.colors[style][1] + 'm'; + } else { + return str; + } + } + + + function stylizeNoColor(str, styleType) { + return str; + } + + + function arrayToHash(array) { + var hash = {}; + + array.forEach(function(val, idx) { + hash[val] = true; + }); + + return hash; + } + + + function formatValue(ctx, value, recurseTimes) { + // Provide a hook for user-specified inspect functions. + // Check that value is an object with an inspect function on it + if (ctx.customInspect && + value && + isFunction(value.inspect) && + // Filter out the util module, it's inspect function is special + value.inspect !== exports.inspect && + // Also filter out any prototype objects using the circular check. + !(value.constructor && value.constructor.prototype === value)) { + var ret = value.inspect(recurseTimes, ctx); + if (!isString(ret)) { + ret = formatValue(ctx, ret, recurseTimes); + } + return ret; + } + + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } + + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); + + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } + + // IE doesn't make error fields non-enumerable + // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx + if (isError(value) + && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { + return formatError(value); + } + + // Some type of object without properties can be shortcutted. + if (keys.length === 0) { + if (isFunction(value)) { + var name = value.name ? ': ' + value.name : ''; + return ctx.stylize('[Function' + name + ']', 'special'); + } + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } + if (isDate(value)) { + return ctx.stylize(Date.prototype.toString.call(value), 'date'); + } + if (isError(value)) { + return formatError(value); + } + } + + var base = '', array = false, braces = ['{', '}']; + + // Make Array say that they are Array + if (isArray(value)) { + array = true; + braces = ['[', ']']; + } + + // Make functions say that they are functions + if (isFunction(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; + } + + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } + + // Make dates with properties first say the date + if (isDate(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); + } + + // Make error with message first say the error + if (isError(value)) { + base = ' ' + formatError(value); + } + + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } + + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); + } + } + + ctx.seen.push(value); + + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + } else { + output = keys.map(function(key) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); + }); + } + + ctx.seen.pop(); + + return reduceToSingleString(output, base, braces); + } + + + function formatPrimitive(ctx, value) { + if (isUndefined(value)) + return ctx.stylize('undefined', 'undefined'); + if (isString(value)) { + var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + '\''; + return ctx.stylize(simple, 'string'); + } + if (isNumber(value)) + return ctx.stylize('' + value, 'number'); + if (isBoolean(value)) + return ctx.stylize('' + value, 'boolean'); + // For some reason typeof null is "object", so special case here. + if (isNull(value)) + return ctx.stylize('null', 'null'); + } + + + function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; + } + + + function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { + var output = []; + for (var i = 0, l = value.length; i < l; ++i) { + if (hasOwnProperty(value, String(i))) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + String(i), true)); + } else { + output.push(''); + } + } + keys.forEach(function(key) { + if (!key.match(/^\d+$/)) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + key, true)); + } + }); + return output; + } + + + function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { + var name, str, desc; + desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; + if (desc.get) { + if (desc.set) { + str = ctx.stylize('[Getter/Setter]', 'special'); + } else { + str = ctx.stylize('[Getter]', 'special'); + } + } else { + if (desc.set) { + str = ctx.stylize('[Setter]', 'special'); + } + } + if (!hasOwnProperty(visibleKeys, key)) { + name = '[' + key + ']'; + } + if (!str) { + if (ctx.seen.indexOf(desc.value) < 0) { + if (isNull(recurseTimes)) { + str = formatValue(ctx, desc.value, null); + } else { + str = formatValue(ctx, desc.value, recurseTimes - 1); + } + if (str.indexOf('\n') > -1) { + if (array) { + str = str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n').substr(2); + } else { + str = '\n' + str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n'); + } + } + } else { + str = ctx.stylize('[Circular]', 'special'); + } + } + if (isUndefined(name)) { + if (array && key.match(/^\d+$/)) { + return str; + } + name = JSON.stringify('' + key); + if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { + name = name.substr(1, name.length - 2); + name = ctx.stylize(name, 'name'); + } else { + name = name.replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'"); + name = ctx.stylize(name, 'string'); + } + } + + return name + ': ' + str; + } + + + function reduceToSingleString(output, base, braces) { + var numLinesEst = 0; + var length = output.reduce(function(prev, cur) { + numLinesEst++; + if (cur.indexOf('\n') >= 0) numLinesEst++; + return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; + }, 0); + + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; + } + + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; + } + + + // NOTE: These type checking functions intentionally don't use `instanceof` + // because it is fragile and can be easily faked with `Object.create()`. + function isArray(ar) { + return Array.isArray(ar); + } + exports.isArray = isArray; + + function isBoolean(arg) { + return typeof arg === 'boolean'; + } + exports.isBoolean = isBoolean; + + function isNull(arg) { + return arg === null; + } + exports.isNull = isNull; + + function isNullOrUndefined(arg) { + return arg == null; + } + exports.isNullOrUndefined = isNullOrUndefined; + + function isNumber(arg) { + return typeof arg === 'number'; + } + exports.isNumber = isNumber; + + function isString(arg) { + return typeof arg === 'string'; + } + exports.isString = isString; + + function isSymbol(arg) { + return typeof arg === 'symbol'; + } + exports.isSymbol = isSymbol; + + function isUndefined(arg) { + return arg === void 0; + } + exports.isUndefined = isUndefined; + + function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; + } + exports.isRegExp = isRegExp; + + function isObject(arg) { + return typeof arg === 'object' && arg !== null; + } + exports.isObject = isObject; + + function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; + } + exports.isDate = isDate; + + function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); + } + exports.isError = isError; + + function isFunction(arg) { + return typeof arg === 'function'; + } + exports.isFunction = isFunction; + + function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; + } + exports.isPrimitive = isPrimitive; + + exports.isBuffer = __webpack_require__(341); + + function objectToString(o) { + return Object.prototype.toString.call(o); + } + + + function pad(n) { + return n < 10 ? '0' + n.toString(10) : n.toString(10); + } + + + var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', + 'Oct', 'Nov', 'Dec']; + + // 26 Feb 16:19:34 + function timestamp() { + var d = new Date(); + var time = [pad(d.getHours()), + pad(d.getMinutes()), + pad(d.getSeconds())].join(':'); + return [d.getDate(), months[d.getMonth()], time].join(' '); + } + + + // log is just a thin wrapper to console.log that prepends a timestamp + exports.log = function() { + console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); + }; + + + /** + * Inherit the prototype methods from one constructor into another. + * + * The Function.prototype.inherits from lang.js rewritten as a standalone + * function (not on Function.prototype). NOTE: If this file is to be loaded + * during bootstrapping this function needs to be rewritten using some native + * functions as prototype setup using normal JavaScript does not work as + * expected during bootstrapping (see mirror.js in r114903). + * + * @param {function} ctor Constructor function which needs to inherit the + * prototype. + * @param {function} superCtor Constructor function to inherit prototype from. + */ + exports.inherits = __webpack_require__(342); + + exports._extend = function(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject(add)) return origin; + + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; + } + return origin; + }; + + function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); + } + + /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()), __webpack_require__(338))) + +/***/ }), +/* 341 */ +/***/ (function(module, exports) { + + module.exports = function isBuffer(arg) { + return arg && typeof arg === 'object' + && typeof arg.copy === 'function' + && typeof arg.fill === 'function' + && typeof arg.readUInt8 === 'function'; + } + +/***/ }), +/* 342 */ +/***/ (function(module, exports) { + + if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; + } else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } + } + + +/***/ }), +/* 343 */ +/***/ (function(module, exports) { + + /** + * A class representation of the BSON RegExp type. + * + * @class + * @return {BSONRegExp} A MinKey instance + */ + function BSONRegExp(pattern, options) { + if (!(this instanceof BSONRegExp)) return new BSONRegExp(); + + // Execute + this._bsontype = 'BSONRegExp'; + this.pattern = pattern || ''; + this.options = options || ''; + + // Validate options + for (var i = 0; i < this.options.length; i++) { + if (!(this.options[i] === 'i' || this.options[i] === 'm' || this.options[i] === 'x' || this.options[i] === 'l' || this.options[i] === 's' || this.options[i] === 'u')) { + throw new Error('the regular expression options [' + this.options[i] + '] is not supported'); + } + } + } + + module.exports = BSONRegExp; + module.exports.BSONRegExp = BSONRegExp; + +/***/ }), +/* 344 */ +/***/ (function(module, exports, __webpack_require__) { + + /* WEBPACK VAR INJECTION */(function(Buffer) {// Custom inspect property name / symbol. + var inspect = Buffer ? __webpack_require__(340).inspect.custom || 'inspect' : 'inspect'; + + /** + * A class representation of the BSON Symbol type. + * + * @class + * @deprecated + * @param {string} value the string representing the symbol. + * @return {Symbol} + */ + function Symbol(value) { + if (!(this instanceof Symbol)) return new Symbol(value); + this._bsontype = 'Symbol'; + this.value = value; + } + + /** + * Access the wrapped string value. + * + * @method + * @return {String} returns the wrapped string. + */ + Symbol.prototype.valueOf = function () { + return this.value; + }; + + /** + * @ignore + */ + Symbol.prototype.toString = function () { + return this.value; + }; + + /** + * @ignore + */ + Symbol.prototype[inspect] = function () { + return this.value; + }; + + /** + * @ignore + */ + Symbol.prototype.toJSON = function () { + return this.value; + }; + + module.exports = Symbol; + module.exports.Symbol = Symbol; + /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(334).Buffer)) + +/***/ }), +/* 345 */ +/***/ (function(module, exports) { + + /** + * A class representation of a BSON Int32 type. + * + * @class + * @param {number} value the number we want to represent as an int32. + * @return {Int32} + */ + var Int32 = function (value) { + if (!(this instanceof Int32)) return new Int32(value); + + this._bsontype = 'Int32'; + this.value = value; + }; + + /** + * Access the number value. + * + * @method + * @return {number} returns the wrapped int32 number. + */ + Int32.prototype.valueOf = function () { + return this.value; + }; + + /** + * @ignore + */ + Int32.prototype.toJSON = function () { + return this.value; + }; + + module.exports = Int32; + module.exports.Int32 = Int32; + +/***/ }), +/* 346 */ +/***/ (function(module, exports) { + + /** + * A class representation of the BSON Code type. + * + * @class + * @param {(string|function)} code a string or function. + * @param {Object} [scope] an optional scope for the function. + * @return {Code} + */ + var Code = function Code(code, scope) { + if (!(this instanceof Code)) return new Code(code, scope); + this._bsontype = 'Code'; + this.code = code; + this.scope = scope; + }; + + /** + * @ignore + */ + Code.prototype.toJSON = function () { + return { scope: this.scope, code: this.code }; + }; + + module.exports = Code; + module.exports.Code = Code; + +/***/ }), +/* 347 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + + var Long = __webpack_require__(330); + + var PARSE_STRING_REGEXP = /^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/; + var PARSE_INF_REGEXP = /^(\+|-)?(Infinity|inf)$/i; + var PARSE_NAN_REGEXP = /^(\+|-)?NaN$/i; + + var EXPONENT_MAX = 6111; + var EXPONENT_MIN = -6176; + var EXPONENT_BIAS = 6176; + var MAX_DIGITS = 34; + + // Nan value bits as 32 bit values (due to lack of longs) + var NAN_BUFFER = [0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00].reverse(); + // Infinity value bits 32 bit values (due to lack of longs) + var INF_NEGATIVE_BUFFER = [0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00].reverse(); + var INF_POSITIVE_BUFFER = [0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00].reverse(); + + var EXPONENT_REGEX = /^([-+])?(\d+)?$/; + + var utils = __webpack_require__(339); + + // Detect if the value is a digit + var isDigit = function (value) { + return !isNaN(parseInt(value, 10)); + }; + + // Divide two uint128 values + var divideu128 = function (value) { + var DIVISOR = Long.fromNumber(1000 * 1000 * 1000); + var _rem = Long.fromNumber(0); + var i = 0; + + if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) { + return { quotient: value, rem: _rem }; + } + + for (i = 0; i <= 3; i++) { + // Adjust remainder to match value of next dividend + _rem = _rem.shiftLeft(32); + // Add the divided to _rem + _rem = _rem.add(new Long(value.parts[i], 0)); + value.parts[i] = _rem.div(DIVISOR).low_; + _rem = _rem.modulo(DIVISOR); + } + + return { quotient: value, rem: _rem }; + }; + + // Multiply two Long values and return the 128 bit value + var multiply64x2 = function (left, right) { + if (!left && !right) { + return { high: Long.fromNumber(0), low: Long.fromNumber(0) }; + } + + var leftHigh = left.shiftRightUnsigned(32); + var leftLow = new Long(left.getLowBits(), 0); + var rightHigh = right.shiftRightUnsigned(32); + var rightLow = new Long(right.getLowBits(), 0); + + var productHigh = leftHigh.multiply(rightHigh); + var productMid = leftHigh.multiply(rightLow); + var productMid2 = leftLow.multiply(rightHigh); + var productLow = leftLow.multiply(rightLow); + + productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); + productMid = new Long(productMid.getLowBits(), 0).add(productMid2).add(productLow.shiftRightUnsigned(32)); + + productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); + productLow = productMid.shiftLeft(32).add(new Long(productLow.getLowBits(), 0)); + + // Return the 128 bit result + return { high: productHigh, low: productLow }; + }; + + var lessThan = function (left, right) { + // Make values unsigned + var uhleft = left.high_ >>> 0; + var uhright = right.high_ >>> 0; + + // Compare high bits first + if (uhleft < uhright) { + return true; + } else if (uhleft === uhright) { + var ulleft = left.low_ >>> 0; + var ulright = right.low_ >>> 0; + if (ulleft < ulright) return true; + } + + return false; + }; + + // var longtoHex = function(value) { + // var buffer = utils.allocBuffer(8); + // var index = 0; + // // Encode the low 64 bits of the decimal + // // Encode low bits + // buffer[index++] = value.low_ & 0xff; + // buffer[index++] = (value.low_ >> 8) & 0xff; + // buffer[index++] = (value.low_ >> 16) & 0xff; + // buffer[index++] = (value.low_ >> 24) & 0xff; + // // Encode high bits + // buffer[index++] = value.high_ & 0xff; + // buffer[index++] = (value.high_ >> 8) & 0xff; + // buffer[index++] = (value.high_ >> 16) & 0xff; + // buffer[index++] = (value.high_ >> 24) & 0xff; + // return buffer.reverse().toString('hex'); + // }; + + // var int32toHex = function(value) { + // var buffer = utils.allocBuffer(4); + // var index = 0; + // // Encode the low 64 bits of the decimal + // // Encode low bits + // buffer[index++] = value & 0xff; + // buffer[index++] = (value >> 8) & 0xff; + // buffer[index++] = (value >> 16) & 0xff; + // buffer[index++] = (value >> 24) & 0xff; + // return buffer.reverse().toString('hex'); + // }; + + /** + * A class representation of the BSON Decimal128 type. + * + * @class + * @param {Buffer} bytes a buffer containing the raw Decimal128 bytes. + * @return {Double} + */ + var Decimal128 = function (bytes) { + this._bsontype = 'Decimal128'; + this.bytes = bytes; + }; + + /** + * Create a Decimal128 instance from a string representation + * + * @method + * @param {string} string a numeric string representation. + * @return {Decimal128} returns a Decimal128 instance. + */ + Decimal128.fromString = function (string) { + // Parse state tracking + var isNegative = false; + var sawRadix = false; + var foundNonZero = false; + + // Total number of significant digits (no leading or trailing zero) + var significantDigits = 0; + // Total number of significand digits read + var nDigitsRead = 0; + // Total number of digits (no leading zeros) + var nDigits = 0; + // The number of the digits after radix + var radixPosition = 0; + // The index of the first non-zero in *str* + var firstNonZero = 0; + + // Digits Array + var digits = [0]; + // The number of digits in digits + var nDigitsStored = 0; + // Insertion pointer for digits + var digitsInsert = 0; + // The index of the first non-zero digit + var firstDigit = 0; + // The index of the last digit + var lastDigit = 0; + + // Exponent + var exponent = 0; + // loop index over array + var i = 0; + // The high 17 digits of the significand + var significandHigh = [0, 0]; + // The low 17 digits of the significand + var significandLow = [0, 0]; + // The biased exponent + var biasedExponent = 0; + + // Read index + var index = 0; + + // Trim the string + string = string.trim(); + + // Naively prevent against REDOS attacks. + // TODO: implementing a custom parsing for this, or refactoring the regex would yield + // further gains. + if (string.length >= 7000) { + throw new Error('' + string + ' not a valid Decimal128 string'); + } + + // Results + var stringMatch = string.match(PARSE_STRING_REGEXP); + var infMatch = string.match(PARSE_INF_REGEXP); + var nanMatch = string.match(PARSE_NAN_REGEXP); + + // Validate the string + if (!stringMatch && !infMatch && !nanMatch || string.length === 0) { + throw new Error('' + string + ' not a valid Decimal128 string'); + } + + // Check if we have an illegal exponent format + if (stringMatch && stringMatch[4] && stringMatch[2] === undefined) { + throw new Error('' + string + ' not a valid Decimal128 string'); + } + + // Get the negative or positive sign + if (string[index] === '+' || string[index] === '-') { + isNegative = string[index++] === '-'; + } + + // Check if user passed Infinity or NaN + if (!isDigit(string[index]) && string[index] !== '.') { + if (string[index] === 'i' || string[index] === 'I') { + return new Decimal128(utils.toBuffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); + } else if (string[index] === 'N') { + return new Decimal128(utils.toBuffer(NAN_BUFFER)); + } + } + + // Read all the digits + while (isDigit(string[index]) || string[index] === '.') { + if (string[index] === '.') { + if (sawRadix) { + return new Decimal128(utils.toBuffer(NAN_BUFFER)); + } + + sawRadix = true; + index = index + 1; + continue; + } + + if (nDigitsStored < 34) { + if (string[index] !== '0' || foundNonZero) { + if (!foundNonZero) { + firstNonZero = nDigitsRead; + } + + foundNonZero = true; + + // Only store 34 digits + digits[digitsInsert++] = parseInt(string[index], 10); + nDigitsStored = nDigitsStored + 1; + } + } + + if (foundNonZero) { + nDigits = nDigits + 1; + } + + if (sawRadix) { + radixPosition = radixPosition + 1; + } + + nDigitsRead = nDigitsRead + 1; + index = index + 1; + } + + if (sawRadix && !nDigitsRead) { + throw new Error('' + string + ' not a valid Decimal128 string'); + } + + // Read exponent if exists + if (string[index] === 'e' || string[index] === 'E') { + // Read exponent digits + var match = string.substr(++index).match(EXPONENT_REGEX); + + // No digits read + if (!match || !match[2]) { + return new Decimal128(utils.toBuffer(NAN_BUFFER)); + } + + // Get exponent + exponent = parseInt(match[0], 10); + + // Adjust the index + index = index + match[0].length; + } + + // Return not a number + if (string[index]) { + return new Decimal128(utils.toBuffer(NAN_BUFFER)); + } + + // Done reading input + // Find first non-zero digit in digits + firstDigit = 0; + + if (!nDigitsStored) { + firstDigit = 0; + lastDigit = 0; + digits[0] = 0; + nDigits = 1; + nDigitsStored = 1; + significantDigits = 0; + } else { + lastDigit = nDigitsStored - 1; + significantDigits = nDigits; + + if (exponent !== 0 && significantDigits !== 1) { + while (string[firstNonZero + significantDigits - 1] === '0') { + significantDigits = significantDigits - 1; + } + } + } + + // Normalization of exponent + // Correct exponent based on radix position, and shift significand as needed + // to represent user input + + // Overflow prevention + if (exponent <= radixPosition && radixPosition - exponent > 1 << 14) { + exponent = EXPONENT_MIN; + } else { + exponent = exponent - radixPosition; + } + + // Attempt to normalize the exponent + while (exponent > EXPONENT_MAX) { + // Shift exponent to significand and decrease + lastDigit = lastDigit + 1; + + if (lastDigit - firstDigit > MAX_DIGITS) { + // Check if we have a zero then just hard clamp, otherwise fail + var digitsString = digits.join(''); + if (digitsString.match(/^0+$/)) { + exponent = EXPONENT_MAX; + break; + } else { + return new Decimal128(utils.toBuffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); + } + } + + exponent = exponent - 1; + } + + while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) { + // Shift last digit + if (lastDigit === 0) { + exponent = EXPONENT_MIN; + significantDigits = 0; + break; + } + + if (nDigitsStored < nDigits) { + // adjust to match digits not stored + nDigits = nDigits - 1; + } else { + // adjust to round + lastDigit = lastDigit - 1; + } + + if (exponent < EXPONENT_MAX) { + exponent = exponent + 1; + } else { + // Check if we have a zero then just hard clamp, otherwise fail + digitsString = digits.join(''); + if (digitsString.match(/^0+$/)) { + exponent = EXPONENT_MAX; + break; + } else { + return new Decimal128(utils.toBuffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); + } + } + } + + // Round + // We've normalized the exponent, but might still need to round. + if (lastDigit - firstDigit + 1 < significantDigits && string[significantDigits] !== '0') { + var endOfString = nDigitsRead; + + // If we have seen a radix point, 'string' is 1 longer than we have + // documented with ndigits_read, so inc the position of the first nonzero + // digit and the position that digits are read to. + if (sawRadix && exponent === EXPONENT_MIN) { + firstNonZero = firstNonZero + 1; + endOfString = endOfString + 1; + } + + var roundDigit = parseInt(string[firstNonZero + lastDigit + 1], 10); + var roundBit = 0; + + if (roundDigit >= 5) { + roundBit = 1; + + if (roundDigit === 5) { + roundBit = digits[lastDigit] % 2 === 1; + + for (i = firstNonZero + lastDigit + 2; i < endOfString; i++) { + if (parseInt(string[i], 10)) { + roundBit = 1; + break; + } + } + } + } + + if (roundBit) { + var dIdx = lastDigit; + + for (; dIdx >= 0; dIdx--) { + if (++digits[dIdx] > 9) { + digits[dIdx] = 0; + + // overflowed most significant digit + if (dIdx === 0) { + if (exponent < EXPONENT_MAX) { + exponent = exponent + 1; + digits[dIdx] = 1; + } else { + return new Decimal128(utils.toBuffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); + } + } + } else { + break; + } + } + } + } + + // Encode significand + // The high 17 digits of the significand + significandHigh = Long.fromNumber(0); + // The low 17 digits of the significand + significandLow = Long.fromNumber(0); + + // read a zero + if (significantDigits === 0) { + significandHigh = Long.fromNumber(0); + significandLow = Long.fromNumber(0); + } else if (lastDigit - firstDigit < 17) { + dIdx = firstDigit; + significandLow = Long.fromNumber(digits[dIdx++]); + significandHigh = new Long(0, 0); + + for (; dIdx <= lastDigit; dIdx++) { + significandLow = significandLow.multiply(Long.fromNumber(10)); + significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); + } + } else { + dIdx = firstDigit; + significandHigh = Long.fromNumber(digits[dIdx++]); + + for (; dIdx <= lastDigit - 17; dIdx++) { + significandHigh = significandHigh.multiply(Long.fromNumber(10)); + significandHigh = significandHigh.add(Long.fromNumber(digits[dIdx])); + } + + significandLow = Long.fromNumber(digits[dIdx++]); + + for (; dIdx <= lastDigit; dIdx++) { + significandLow = significandLow.multiply(Long.fromNumber(10)); + significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); + } + } + + var significand = multiply64x2(significandHigh, Long.fromString('100000000000000000')); + + significand.low = significand.low.add(significandLow); + + if (lessThan(significand.low, significandLow)) { + significand.high = significand.high.add(Long.fromNumber(1)); + } + + // Biased exponent + biasedExponent = exponent + EXPONENT_BIAS; + var dec = { low: Long.fromNumber(0), high: Long.fromNumber(0) }; + + // Encode combination, exponent, and significand. + if (significand.high.shiftRightUnsigned(49).and(Long.fromNumber(1)).equals(Long.fromNumber)) { + // Encode '11' into bits 1 to 3 + dec.high = dec.high.or(Long.fromNumber(0x3).shiftLeft(61)); + dec.high = dec.high.or(Long.fromNumber(biasedExponent).and(Long.fromNumber(0x3fff).shiftLeft(47))); + dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x7fffffffffff))); + } else { + dec.high = dec.high.or(Long.fromNumber(biasedExponent & 0x3fff).shiftLeft(49)); + dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x1ffffffffffff))); + } + + dec.low = significand.low; + + // Encode sign + if (isNegative) { + dec.high = dec.high.or(Long.fromString('9223372036854775808')); + } + + // Encode into a buffer + var buffer = utils.allocBuffer(16); + index = 0; + + // Encode the low 64 bits of the decimal + // Encode low bits + buffer[index++] = dec.low.low_ & 0xff; + buffer[index++] = dec.low.low_ >> 8 & 0xff; + buffer[index++] = dec.low.low_ >> 16 & 0xff; + buffer[index++] = dec.low.low_ >> 24 & 0xff; + // Encode high bits + buffer[index++] = dec.low.high_ & 0xff; + buffer[index++] = dec.low.high_ >> 8 & 0xff; + buffer[index++] = dec.low.high_ >> 16 & 0xff; + buffer[index++] = dec.low.high_ >> 24 & 0xff; + + // Encode the high 64 bits of the decimal + // Encode low bits + buffer[index++] = dec.high.low_ & 0xff; + buffer[index++] = dec.high.low_ >> 8 & 0xff; + buffer[index++] = dec.high.low_ >> 16 & 0xff; + buffer[index++] = dec.high.low_ >> 24 & 0xff; + // Encode high bits + buffer[index++] = dec.high.high_ & 0xff; + buffer[index++] = dec.high.high_ >> 8 & 0xff; + buffer[index++] = dec.high.high_ >> 16 & 0xff; + buffer[index++] = dec.high.high_ >> 24 & 0xff; + + // Return the new Decimal128 + return new Decimal128(buffer); + }; + + // Extract least significant 5 bits + var COMBINATION_MASK = 0x1f; + // Extract least significant 14 bits + var EXPONENT_MASK = 0x3fff; + // Value of combination field for Inf + var COMBINATION_INFINITY = 30; + // Value of combination field for NaN + var COMBINATION_NAN = 31; + // Value of combination field for NaN + // var COMBINATION_SNAN = 32; + // decimal128 exponent bias + EXPONENT_BIAS = 6176; + + /** + * Create a string representation of the raw Decimal128 value + * + * @method + * @return {string} returns a Decimal128 string representation. + */ + Decimal128.prototype.toString = function () { + // Note: bits in this routine are referred to starting at 0, + // from the sign bit, towards the coefficient. + + // bits 0 - 31 + var high; + // bits 32 - 63 + var midh; + // bits 64 - 95 + var midl; + // bits 96 - 127 + var low; + // bits 1 - 5 + var combination; + // decoded biased exponent (14 bits) + var biased_exponent; + // the number of significand digits + var significand_digits = 0; + // the base-10 digits in the significand + var significand = new Array(36); + for (var i = 0; i < significand.length; i++) significand[i] = 0; + // read pointer into significand + var index = 0; + + // unbiased exponent + var exponent; + // the exponent if scientific notation is used + var scientific_exponent; + + // true if the number is zero + var is_zero = false; + + // the most signifcant significand bits (50-46) + var significand_msb; + // temporary storage for significand decoding + var significand128 = { parts: new Array(4) }; + // indexing variables + i; + var j, k; + + // Output string + var string = []; + + // Unpack index + index = 0; + + // Buffer reference + var buffer = this.bytes; + + // Unpack the low 64bits into a long + low = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + midl = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + + // Unpack the high 64bits into a long + midh = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + high = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + + // Unpack index + index = 0; + + // Create the state of the decimal + var dec = { + low: new Long(low, midl), + high: new Long(midh, high) + }; + + if (dec.high.lessThan(Long.ZERO)) { + string.push('-'); + } + + // Decode combination field and exponent + combination = high >> 26 & COMBINATION_MASK; + + if (combination >> 3 === 3) { + // Check for 'special' values + if (combination === COMBINATION_INFINITY) { + return string.join('') + 'Infinity'; + } else if (combination === COMBINATION_NAN) { + return 'NaN'; + } else { + biased_exponent = high >> 15 & EXPONENT_MASK; + significand_msb = 0x08 + (high >> 14 & 0x01); + } + } else { + significand_msb = high >> 14 & 0x07; + biased_exponent = high >> 17 & EXPONENT_MASK; + } + + exponent = biased_exponent - EXPONENT_BIAS; + + // Create string of significand digits + + // Convert the 114-bit binary number represented by + // (significand_high, significand_low) to at most 34 decimal + // digits through modulo and division. + significand128.parts[0] = (high & 0x3fff) + ((significand_msb & 0xf) << 14); + significand128.parts[1] = midh; + significand128.parts[2] = midl; + significand128.parts[3] = low; + + if (significand128.parts[0] === 0 && significand128.parts[1] === 0 && significand128.parts[2] === 0 && significand128.parts[3] === 0) { + is_zero = true; + } else { + for (k = 3; k >= 0; k--) { + var least_digits = 0; + // Peform the divide + var result = divideu128(significand128); + significand128 = result.quotient; + least_digits = result.rem.low_; + + // We now have the 9 least significant digits (in base 2). + // Convert and output to string. + if (!least_digits) continue; + + for (j = 8; j >= 0; j--) { + // significand[k * 9 + j] = Math.round(least_digits % 10); + significand[k * 9 + j] = least_digits % 10; + // least_digits = Math.round(least_digits / 10); + least_digits = Math.floor(least_digits / 10); + } + } + } + + // Output format options: + // Scientific - [-]d.dddE(+/-)dd or [-]dE(+/-)dd + // Regular - ddd.ddd + + if (is_zero) { + significand_digits = 1; + significand[index] = 0; + } else { + significand_digits = 36; + i = 0; + + while (!significand[index]) { + i++; + significand_digits = significand_digits - 1; + index = index + 1; + } + } + + scientific_exponent = significand_digits - 1 + exponent; + + // The scientific exponent checks are dictated by the string conversion + // specification and are somewhat arbitrary cutoffs. + // + // We must check exponent > 0, because if this is the case, the number + // has trailing zeros. However, we *cannot* output these trailing zeros, + // because doing so would change the precision of the value, and would + // change stored data if the string converted number is round tripped. + + if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) { + // Scientific format + string.push(significand[index++]); + significand_digits = significand_digits - 1; + + if (significand_digits) { + string.push('.'); + } + + for (i = 0; i < significand_digits; i++) { + string.push(significand[index++]); + } + + // Exponent + string.push('E'); + if (scientific_exponent > 0) { + string.push('+' + scientific_exponent); + } else { + string.push(scientific_exponent); + } + } else { + // Regular format with no decimal place + if (exponent >= 0) { + for (i = 0; i < significand_digits; i++) { + string.push(significand[index++]); + } + } else { + var radix_position = significand_digits + exponent; + + // non-zero digits before radix + if (radix_position > 0) { + for (i = 0; i < radix_position; i++) { + string.push(significand[index++]); + } + } else { + string.push('0'); + } + + string.push('.'); + // add leading zeros after radix + while (radix_position++ < 0) { + string.push('0'); + } + + for (i = 0; i < significand_digits - Math.max(radix_position - 1, 0); i++) { + string.push(significand[index++]); + } + } + } + + return string.join(''); + }; + + Decimal128.prototype.toJSON = function () { + return { $numberDecimal: this.toString() }; + }; + + module.exports = Decimal128; + module.exports.Decimal128 = Decimal128; + +/***/ }), +/* 348 */ +/***/ (function(module, exports) { + + /** + * A class representation of the BSON MinKey type. + * + * @class + * @return {MinKey} A MinKey instance + */ + function MinKey() { + if (!(this instanceof MinKey)) return new MinKey(); + + this._bsontype = 'MinKey'; + } + + module.exports = MinKey; + module.exports.MinKey = MinKey; + +/***/ }), +/* 349 */ +/***/ (function(module, exports) { + + /** + * A class representation of the BSON MaxKey type. + * + * @class + * @return {MaxKey} A MaxKey instance + */ + function MaxKey() { + if (!(this instanceof MaxKey)) return new MaxKey(); + + this._bsontype = 'MaxKey'; + } + + module.exports = MaxKey; + module.exports.MaxKey = MaxKey; + +/***/ }), +/* 350 */ +/***/ (function(module, exports) { + + /** + * A class representation of the BSON DBRef type. + * + * @class + * @param {string} namespace the collection name. + * @param {ObjectID} oid the reference ObjectID. + * @param {string} [db] optional db name, if omitted the reference is local to the current db. + * @return {DBRef} + */ + function DBRef(namespace, oid, db) { + if (!(this instanceof DBRef)) return new DBRef(namespace, oid, db); + + this._bsontype = 'DBRef'; + this.namespace = namespace; + this.oid = oid; + this.db = db; + } + + /** + * @ignore + * @api private + */ + DBRef.prototype.toJSON = function () { + return { + $ref: this.namespace, + $id: this.oid, + $db: this.db == null ? '' : this.db + }; + }; + + module.exports = DBRef; + module.exports.DBRef = DBRef; + +/***/ }), +/* 351 */ +/***/ (function(module, exports, __webpack_require__) { + + /* WEBPACK VAR INJECTION */(function(global) {/** + * Module dependencies. + * @ignore + */ + + // Test if we're in Node via presence of "global" not absence of "window" + // to support hybrid environments like Electron + if (typeof global !== 'undefined') { + var Buffer = __webpack_require__(334).Buffer; // TODO just use global Buffer + } + + var utils = __webpack_require__(339); + + /** + * A class representation of the BSON Binary type. + * + * Sub types + * - **BSON.BSON_BINARY_SUBTYPE_DEFAULT**, default BSON type. + * - **BSON.BSON_BINARY_SUBTYPE_FUNCTION**, BSON function type. + * - **BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY**, BSON byte array type. + * - **BSON.BSON_BINARY_SUBTYPE_UUID**, BSON uuid type. + * - **BSON.BSON_BINARY_SUBTYPE_MD5**, BSON md5 type. + * - **BSON.BSON_BINARY_SUBTYPE_USER_DEFINED**, BSON user defined type. + * + * @class + * @param {Buffer} buffer a buffer object containing the binary data. + * @param {Number} [subType] the option binary type. + * @return {Binary} + */ + function Binary(buffer, subType) { + if (!(this instanceof Binary)) return new Binary(buffer, subType); + + if (buffer != null && !(typeof buffer === 'string') && !Buffer.isBuffer(buffer) && !(buffer instanceof Uint8Array) && !Array.isArray(buffer)) { + throw new Error('only String, Buffer, Uint8Array or Array accepted'); + } + + this._bsontype = 'Binary'; + + if (buffer instanceof Number) { + this.sub_type = buffer; + this.position = 0; + } else { + this.sub_type = subType == null ? BSON_BINARY_SUBTYPE_DEFAULT : subType; + this.position = 0; + } + + if (buffer != null && !(buffer instanceof Number)) { + // Only accept Buffer, Uint8Array or Arrays + if (typeof buffer === 'string') { + // Different ways of writing the length of the string for the different types + if (typeof Buffer !== 'undefined') { + this.buffer = utils.toBuffer(buffer); + } else if (typeof Uint8Array !== 'undefined' || Object.prototype.toString.call(buffer) === '[object Array]') { + this.buffer = writeStringToArray(buffer); + } else { + throw new Error('only String, Buffer, Uint8Array or Array accepted'); + } + } else { + this.buffer = buffer; + } + this.position = buffer.length; + } else { + if (typeof Buffer !== 'undefined') { + this.buffer = utils.allocBuffer(Binary.BUFFER_SIZE); + } else if (typeof Uint8Array !== 'undefined') { + this.buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE)); + } else { + this.buffer = new Array(Binary.BUFFER_SIZE); + } + // Set position to start of buffer + this.position = 0; + } + } + + /** + * Updates this binary with byte_value. + * + * @method + * @param {string} byte_value a single byte we wish to write. + */ + Binary.prototype.put = function put(byte_value) { + // If it's a string and a has more than one character throw an error + if (byte_value['length'] != null && typeof byte_value !== 'number' && byte_value.length !== 1) throw new Error('only accepts single character String, Uint8Array or Array'); + if (typeof byte_value !== 'number' && byte_value < 0 || byte_value > 255) throw new Error('only accepts number in a valid unsigned byte range 0-255'); + + // Decode the byte value once + var decoded_byte = null; + if (typeof byte_value === 'string') { + decoded_byte = byte_value.charCodeAt(0); + } else if (byte_value['length'] != null) { + decoded_byte = byte_value[0]; + } else { + decoded_byte = byte_value; + } + + if (this.buffer.length > this.position) { + this.buffer[this.position++] = decoded_byte; + } else { + if (typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer)) { + // Create additional overflow buffer + var buffer = utils.allocBuffer(Binary.BUFFER_SIZE + this.buffer.length); + // Combine the two buffers together + this.buffer.copy(buffer, 0, 0, this.buffer.length); + this.buffer = buffer; + this.buffer[this.position++] = decoded_byte; + } else { + buffer = null; + // Create a new buffer (typed or normal array) + if (Object.prototype.toString.call(this.buffer) === '[object Uint8Array]') { + buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE + this.buffer.length)); + } else { + buffer = new Array(Binary.BUFFER_SIZE + this.buffer.length); + } + + // We need to copy all the content to the new array + for (var i = 0; i < this.buffer.length; i++) { + buffer[i] = this.buffer[i]; + } + + // Reassign the buffer + this.buffer = buffer; + // Write the byte + this.buffer[this.position++] = decoded_byte; + } + } + }; + + /** + * Writes a buffer or string to the binary. + * + * @method + * @param {(Buffer|string)} string a string or buffer to be written to the Binary BSON object. + * @param {number} offset specify the binary of where to write the content. + * @return {null} + */ + Binary.prototype.write = function write(string, offset) { + offset = typeof offset === 'number' ? offset : this.position; + + // If the buffer is to small let's extend the buffer + if (this.buffer.length < offset + string.length) { + var buffer = null; + // If we are in node.js + if (typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer)) { + buffer = utils.allocBuffer(this.buffer.length + string.length); + this.buffer.copy(buffer, 0, 0, this.buffer.length); + } else if (Object.prototype.toString.call(this.buffer) === '[object Uint8Array]') { + // Create a new buffer + buffer = new Uint8Array(new ArrayBuffer(this.buffer.length + string.length)); + // Copy the content + for (var i = 0; i < this.position; i++) { + buffer[i] = this.buffer[i]; + } + } + + // Assign the new buffer + this.buffer = buffer; + } + + if (typeof Buffer !== 'undefined' && Buffer.isBuffer(string) && Buffer.isBuffer(this.buffer)) { + string.copy(this.buffer, offset, 0, string.length); + this.position = offset + string.length > this.position ? offset + string.length : this.position; + // offset = string.length + } else if (typeof Buffer !== 'undefined' && typeof string === 'string' && Buffer.isBuffer(this.buffer)) { + this.buffer.write(string, offset, 'binary'); + this.position = offset + string.length > this.position ? offset + string.length : this.position; + // offset = string.length; + } else if (Object.prototype.toString.call(string) === '[object Uint8Array]' || Object.prototype.toString.call(string) === '[object Array]' && typeof string !== 'string') { + for (i = 0; i < string.length; i++) { + this.buffer[offset++] = string[i]; + } + + this.position = offset > this.position ? offset : this.position; + } else if (typeof string === 'string') { + for (i = 0; i < string.length; i++) { + this.buffer[offset++] = string.charCodeAt(i); + } + + this.position = offset > this.position ? offset : this.position; + } + }; + + /** + * Reads **length** bytes starting at **position**. + * + * @method + * @param {number} position read from the given position in the Binary. + * @param {number} length the number of bytes to read. + * @return {Buffer} + */ + Binary.prototype.read = function read(position, length) { + length = length && length > 0 ? length : this.position; + + // Let's return the data based on the type we have + if (this.buffer['slice']) { + return this.buffer.slice(position, position + length); + } else { + // Create a buffer to keep the result + var buffer = typeof Uint8Array !== 'undefined' ? new Uint8Array(new ArrayBuffer(length)) : new Array(length); + for (var i = 0; i < length; i++) { + buffer[i] = this.buffer[position++]; + } + } + // Return the buffer + return buffer; + }; + + /** + * Returns the value of this binary as a string. + * + * @method + * @return {string} + */ + Binary.prototype.value = function value(asRaw) { + asRaw = asRaw == null ? false : asRaw; + + // Optimize to serialize for the situation where the data == size of buffer + if (asRaw && typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer) && this.buffer.length === this.position) return this.buffer; + + // If it's a node.js buffer object + if (typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer)) { + return asRaw ? this.buffer.slice(0, this.position) : this.buffer.toString('binary', 0, this.position); + } else { + if (asRaw) { + // we support the slice command use it + if (this.buffer['slice'] != null) { + return this.buffer.slice(0, this.position); + } else { + // Create a new buffer to copy content to + var newBuffer = Object.prototype.toString.call(this.buffer) === '[object Uint8Array]' ? new Uint8Array(new ArrayBuffer(this.position)) : new Array(this.position); + // Copy content + for (var i = 0; i < this.position; i++) { + newBuffer[i] = this.buffer[i]; + } + // Return the buffer + return newBuffer; + } + } else { + return convertArraytoUtf8BinaryString(this.buffer, 0, this.position); + } + } + }; + + /** + * Length. + * + * @method + * @return {number} the length of the binary. + */ + Binary.prototype.length = function length() { + return this.position; + }; + + /** + * @ignore + */ + Binary.prototype.toJSON = function () { + return this.buffer != null ? this.buffer.toString('base64') : ''; + }; + + /** + * @ignore + */ + Binary.prototype.toString = function (format) { + return this.buffer != null ? this.buffer.slice(0, this.position).toString(format) : ''; + }; + + /** + * Binary default subtype + * @ignore + */ + var BSON_BINARY_SUBTYPE_DEFAULT = 0; + + /** + * @ignore + */ + var writeStringToArray = function (data) { + // Create a buffer + var buffer = typeof Uint8Array !== 'undefined' ? new Uint8Array(new ArrayBuffer(data.length)) : new Array(data.length); + // Write the content to the buffer + for (var i = 0; i < data.length; i++) { + buffer[i] = data.charCodeAt(i); + } + // Write the string to the buffer + return buffer; + }; + + /** + * Convert Array ot Uint8Array to Binary String + * + * @ignore + */ + var convertArraytoUtf8BinaryString = function (byteArray, startIndex, endIndex) { + var result = ''; + for (var i = startIndex; i < endIndex; i++) { + result = result + String.fromCharCode(byteArray[i]); + } + return result; + }; + + Binary.BUFFER_SIZE = 256; + + /** + * Default BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ + Binary.SUBTYPE_DEFAULT = 0; + /** + * Function BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ + Binary.SUBTYPE_FUNCTION = 1; + /** + * Byte Array BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ + Binary.SUBTYPE_BYTE_ARRAY = 2; + /** + * OLD UUID BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ + Binary.SUBTYPE_UUID_OLD = 3; + /** + * UUID BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ + Binary.SUBTYPE_UUID = 4; + /** + * MD5 BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ + Binary.SUBTYPE_MD5 = 5; + /** + * User BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ + Binary.SUBTYPE_USER_DEFINED = 128; + + /** + * Expose. + */ + module.exports = Binary; + module.exports.Binary = Binary; + /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) + +/***/ }), +/* 352 */ +/***/ (function(module, exports, __webpack_require__) { + + 'use strict'; + + var Long = __webpack_require__(330).Long, + Double = __webpack_require__(331).Double, + Timestamp = __webpack_require__(332).Timestamp, + ObjectID = __webpack_require__(333).ObjectID, + Symbol = __webpack_require__(344).Symbol, + Code = __webpack_require__(346).Code, + MinKey = __webpack_require__(348).MinKey, + MaxKey = __webpack_require__(349).MaxKey, + Decimal128 = __webpack_require__(347), + Int32 = __webpack_require__(345), + DBRef = __webpack_require__(350).DBRef, + BSONRegExp = __webpack_require__(343).BSONRegExp, + Binary = __webpack_require__(351).Binary; + + var utils = __webpack_require__(339); + + var deserialize = function (buffer, options, isArray) { + options = options == null ? {} : options; + var index = options && options.index ? options.index : 0; + // Read the document size + var size = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; + + // Ensure buffer is valid size + if (size < 5 || buffer.length < size || size + index > buffer.length) { + throw new Error('corrupt bson message'); + } + + // Illegal end value + if (buffer[index + size - 1] !== 0) { + throw new Error("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00"); + } + + // Start deserializtion + return deserializeObject(buffer, index, options, isArray); + }; + + var deserializeObject = function (buffer, index, options, isArray) { + var evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions']; + var cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions']; + var cacheFunctionsCrc32 = options['cacheFunctionsCrc32'] == null ? false : options['cacheFunctionsCrc32']; + + if (!cacheFunctionsCrc32) var crc32 = null; + + var fieldsAsRaw = options['fieldsAsRaw'] == null ? null : options['fieldsAsRaw']; + + // Return raw bson buffer instead of parsing it + var raw = options['raw'] == null ? false : options['raw']; + + // Return BSONRegExp objects instead of native regular expressions + var bsonRegExp = typeof options['bsonRegExp'] === 'boolean' ? options['bsonRegExp'] : false; + + // Controls the promotion of values vs wrapper classes + var promoteBuffers = options['promoteBuffers'] == null ? false : options['promoteBuffers']; + var promoteLongs = options['promoteLongs'] == null ? true : options['promoteLongs']; + var promoteValues = options['promoteValues'] == null ? true : options['promoteValues']; + + // Set the start index + var startIndex = index; + + // Validate that we have at least 4 bytes of buffer + if (buffer.length < 5) throw new Error('corrupt bson message < 5 bytes long'); + + // Read the document size + var size = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + + // Ensure buffer is valid size + if (size < 5 || size > buffer.length) throw new Error('corrupt bson message'); + + // Create holding object + var object = isArray ? [] : {}; + // Used for arrays to skip having to perform utf8 decoding + var arrayIndex = 0; + + var done = false; + + // While we have more left data left keep parsing + // while (buffer[index + 1] !== 0) { + while (!done) { + // Read the type + var elementType = buffer[index++]; + // If we get a zero it's the last byte, exit + if (elementType === 0) break; + + // Get the start search index + var i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); + var name = isArray ? arrayIndex++ : buffer.toString('utf8', index, i); + + index = i + 1; + + if (elementType === BSON.BSON_DATA_STRING) { + var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + if (stringSize <= 0 || stringSize > buffer.length - index || buffer[index + stringSize - 1] !== 0) throw new Error('bad string length in bson'); + object[name] = buffer.toString('utf8', index, index + stringSize - 1); + index = index + stringSize; + } else if (elementType === BSON.BSON_DATA_OID) { + var oid = utils.allocBuffer(12); + buffer.copy(oid, 0, index, index + 12); + object[name] = new ObjectID(oid); + index = index + 12; + } else if (elementType === BSON.BSON_DATA_INT && promoteValues === false) { + object[name] = new Int32(buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24); + } else if (elementType === BSON.BSON_DATA_INT) { + object[name] = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + } else if (elementType === BSON.BSON_DATA_NUMBER && promoteValues === false) { + object[name] = new Double(buffer.readDoubleLE(index)); + index = index + 8; + } else if (elementType === BSON.BSON_DATA_NUMBER) { + object[name] = buffer.readDoubleLE(index); + index = index + 8; + } else if (elementType === BSON.BSON_DATA_DATE) { + var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + object[name] = new Date(new Long(lowBits, highBits).toNumber()); + } else if (elementType === BSON.BSON_DATA_BOOLEAN) { + if (buffer[index] !== 0 && buffer[index] !== 1) throw new Error('illegal boolean type value'); + object[name] = buffer[index++] === 1; + } else if (elementType === BSON.BSON_DATA_OBJECT) { + var _index = index; + var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; + if (objectSize <= 0 || objectSize > buffer.length - index) throw new Error('bad embedded document length in bson'); + + // We have a raw value + if (raw) { + object[name] = buffer.slice(index, index + objectSize); + } else { + object[name] = deserializeObject(buffer, _index, options, false); + } + + index = index + objectSize; + } else if (elementType === BSON.BSON_DATA_ARRAY) { + _index = index; + objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; + var arrayOptions = options; + + // Stop index + var stopIndex = index + objectSize; + + // All elements of array to be returned as raw bson + if (fieldsAsRaw && fieldsAsRaw[name]) { + arrayOptions = {}; + for (var n in options) arrayOptions[n] = options[n]; + arrayOptions['raw'] = true; + } + + object[name] = deserializeObject(buffer, _index, arrayOptions, true); + index = index + objectSize; + + if (buffer[index - 1] !== 0) throw new Error('invalid array terminator byte'); + if (index !== stopIndex) throw new Error('corrupted array bson'); + } else if (elementType === BSON.BSON_DATA_UNDEFINED) { + object[name] = undefined; + } else if (elementType === BSON.BSON_DATA_NULL) { + object[name] = null; + } else if (elementType === BSON.BSON_DATA_LONG) { + // Unpack the low and high bits + lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + var long = new Long(lowBits, highBits); + // Promote the long if possible + if (promoteLongs && promoteValues === true) { + object[name] = long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) ? long.toNumber() : long; + } else { + object[name] = long; + } + } else if (elementType === BSON.BSON_DATA_DECIMAL128) { + // Buffer to contain the decimal bytes + var bytes = utils.allocBuffer(16); + // Copy the next 16 bytes into the bytes buffer + buffer.copy(bytes, 0, index, index + 16); + // Update index + index = index + 16; + // Assign the new Decimal128 value + var decimal128 = new Decimal128(bytes); + // If we have an alternative mapper use that + object[name] = decimal128.toObject ? decimal128.toObject() : decimal128; + } else if (elementType === BSON.BSON_DATA_BINARY) { + var binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + var totalBinarySize = binarySize; + var subType = buffer[index++]; + + // Did we have a negative binary size, throw + if (binarySize < 0) throw new Error('Negative binary type element size found'); + + // Is the length longer than the document + if (binarySize > buffer.length) throw new Error('Binary type size larger than document size'); + + // Decode as raw Buffer object if options specifies it + if (buffer['slice'] != null) { + // If we have subtype 2 skip the 4 bytes for the size + if (subType === Binary.SUBTYPE_BYTE_ARRAY) { + binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + if (binarySize < 0) throw new Error('Negative binary type element size found for subtype 0x02'); + if (binarySize > totalBinarySize - 4) throw new Error('Binary type with subtype 0x02 contains to long binary size'); + if (binarySize < totalBinarySize - 4) throw new Error('Binary type with subtype 0x02 contains to short binary size'); + } + + if (promoteBuffers && promoteValues) { + object[name] = buffer.slice(index, index + binarySize); + } else { + object[name] = new Binary(buffer.slice(index, index + binarySize), subType); + } + } else { + var _buffer = typeof Uint8Array !== 'undefined' ? new Uint8Array(new ArrayBuffer(binarySize)) : new Array(binarySize); + // If we have subtype 2 skip the 4 bytes for the size + if (subType === Binary.SUBTYPE_BYTE_ARRAY) { + binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + if (binarySize < 0) throw new Error('Negative binary type element size found for subtype 0x02'); + if (binarySize > totalBinarySize - 4) throw new Error('Binary type with subtype 0x02 contains to long binary size'); + if (binarySize < totalBinarySize - 4) throw new Error('Binary type with subtype 0x02 contains to short binary size'); + } + + // Copy the data + for (i = 0; i < binarySize; i++) { + _buffer[i] = buffer[index + i]; + } + + if (promoteBuffers && promoteValues) { + object[name] = _buffer; + } else { + object[name] = new Binary(_buffer, subType); + } + } + + // Update the index + index = index + binarySize; + } else if (elementType === BSON.BSON_DATA_REGEXP && bsonRegExp === false) { + // Get the start search index + i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); + // Return the C string + var source = buffer.toString('utf8', index, i); + // Create the regexp + index = i + 1; + + // Get the start search index + i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); + // Return the C string + var regExpOptions = buffer.toString('utf8', index, i); + index = i + 1; + + // For each option add the corresponding one for javascript + var optionsArray = new Array(regExpOptions.length); + + // Parse options + for (i = 0; i < regExpOptions.length; i++) { + switch (regExpOptions[i]) { + case 'm': + optionsArray[i] = 'm'; + break; + case 's': + optionsArray[i] = 'g'; + break; + case 'i': + optionsArray[i] = 'i'; + break; + } + } + + object[name] = new RegExp(source, optionsArray.join('')); + } else if (elementType === BSON.BSON_DATA_REGEXP && bsonRegExp === true) { + // Get the start search index + i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); + // Return the C string + source = buffer.toString('utf8', index, i); + index = i + 1; + + // Get the start search index + i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); + // Return the C string + regExpOptions = buffer.toString('utf8', index, i); + index = i + 1; + + // Set the object + object[name] = new BSONRegExp(source, regExpOptions); + } else if (elementType === BSON.BSON_DATA_SYMBOL) { + stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + if (stringSize <= 0 || stringSize > buffer.length - index || buffer[index + stringSize - 1] !== 0) throw new Error('bad string length in bson'); + object[name] = new Symbol(buffer.toString('utf8', index, index + stringSize - 1)); + index = index + stringSize; + } else if (elementType === BSON.BSON_DATA_TIMESTAMP) { + lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + object[name] = new Timestamp(lowBits, highBits); + } else if (elementType === BSON.BSON_DATA_MIN_KEY) { + object[name] = new MinKey(); + } else if (elementType === BSON.BSON_DATA_MAX_KEY) { + object[name] = new MaxKey(); + } else if (elementType === BSON.BSON_DATA_CODE) { + stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + if (stringSize <= 0 || stringSize > buffer.length - index || buffer[index + stringSize - 1] !== 0) throw new Error('bad string length in bson'); + var functionString = buffer.toString('utf8', index, index + stringSize - 1); + + // If we are evaluating the functions + if (evalFunctions) { + // If we have cache enabled let's look for the md5 of the function in the cache + if (cacheFunctions) { + var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; + // Got to do this to avoid V8 deoptimizing the call due to finding eval + object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); + } else { + object[name] = isolateEval(functionString); + } + } else { + object[name] = new Code(functionString); + } + + // Update parse index position + index = index + stringSize; + } else if (elementType === BSON.BSON_DATA_CODE_W_SCOPE) { + var totalSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + + // Element cannot be shorter than totalSize + stringSize + documentSize + terminator + if (totalSize < 4 + 4 + 4 + 1) { + throw new Error('code_w_scope total size shorter minimum expected length'); + } + + // Get the code string size + stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Check if we have a valid string + if (stringSize <= 0 || stringSize > buffer.length - index || buffer[index + stringSize - 1] !== 0) throw new Error('bad string length in bson'); + + // Javascript function + functionString = buffer.toString('utf8', index, index + stringSize - 1); + // Update parse index position + index = index + stringSize; + // Parse the element + _index = index; + // Decode the size of the object document + objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; + // Decode the scope object + var scopeObject = deserializeObject(buffer, _index, options, false); + // Adjust the index + index = index + objectSize; + + // Check if field length is to short + if (totalSize < 4 + 4 + objectSize + stringSize) { + throw new Error('code_w_scope total size is to short, truncating scope'); + } + + // Check if totalSize field is to long + if (totalSize > 4 + 4 + objectSize + stringSize) { + throw new Error('code_w_scope total size is to long, clips outer document'); + } + + // If we are evaluating the functions + if (evalFunctions) { + // If we have cache enabled let's look for the md5 of the function in the cache + if (cacheFunctions) { + hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; + // Got to do this to avoid V8 deoptimizing the call due to finding eval + object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); + } else { + object[name] = isolateEval(functionString); + } + + object[name].scope = scopeObject; + } else { + object[name] = new Code(functionString, scopeObject); + } + } else if (elementType === BSON.BSON_DATA_DBPOINTER) { + // Get the code string size + stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Check if we have a valid string + if (stringSize <= 0 || stringSize > buffer.length - index || buffer[index + stringSize - 1] !== 0) throw new Error('bad string length in bson'); + // Namespace + var namespace = buffer.toString('utf8', index, index + stringSize - 1); + // Update parse index position + index = index + stringSize; + + // Read the oid + var oidBuffer = utils.allocBuffer(12); + buffer.copy(oidBuffer, 0, index, index + 12); + oid = new ObjectID(oidBuffer); + + // Update the index + index = index + 12; + + // Split the namespace + var parts = namespace.split('.'); + var db = parts.shift(); + var collection = parts.join('.'); + // Upgrade to DBRef type + object[name] = new DBRef(collection, oid, db); + } else { + throw new Error('Detected unknown BSON type ' + elementType.toString(16) + ' for fieldname "' + name + '", are you using the latest BSON parser'); + } + } + + // Check if the deserialization was against a valid array/object + if (size !== index - startIndex) { + if (isArray) throw new Error('corrupt array bson'); + throw new Error('corrupt object bson'); + } + + // Check if we have a db ref object + if (object['$id'] != null) object = new DBRef(object['$ref'], object['$id'], object['$db']); + return object; + }; + + /** + * Ensure eval is isolated. + * + * @ignore + * @api private + */ + var isolateEvalWithHash = function (functionCache, hash, functionString, object) { + // Contains the value we are going to set + var value = null; + + // Check for cache hit, eval if missing and return cached function + if (functionCache[hash] == null) { + eval('value = ' + functionString); + functionCache[hash] = value; + } + // Set the object + return functionCache[hash].bind(object); + }; + + /** + * Ensure eval is isolated. + * + * @ignore + * @api private + */ + var isolateEval = function (functionString) { + // Contains the value we are going to set + var value = null; + // Eval the function + eval('value = ' + functionString); + return value; + }; + + var BSON = {}; + + /** + * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 + * + * @ignore + * @api private + */ + var functionCache = BSON.functionCache = {}; + + /** + * Number BSON Type + * + * @classconstant BSON_DATA_NUMBER + **/ + BSON.BSON_DATA_NUMBER = 1; + /** + * String BSON Type + * + * @classconstant BSON_DATA_STRING + **/ + BSON.BSON_DATA_STRING = 2; + /** + * Object BSON Type + * + * @classconstant BSON_DATA_OBJECT + **/ + BSON.BSON_DATA_OBJECT = 3; + /** + * Array BSON Type + * + * @classconstant BSON_DATA_ARRAY + **/ + BSON.BSON_DATA_ARRAY = 4; + /** + * Binary BSON Type + * + * @classconstant BSON_DATA_BINARY + **/ + BSON.BSON_DATA_BINARY = 5; + /** + * Binary BSON Type + * + * @classconstant BSON_DATA_UNDEFINED + **/ + BSON.BSON_DATA_UNDEFINED = 6; + /** + * ObjectID BSON Type + * + * @classconstant BSON_DATA_OID + **/ + BSON.BSON_DATA_OID = 7; + /** + * Boolean BSON Type + * + * @classconstant BSON_DATA_BOOLEAN + **/ + BSON.BSON_DATA_BOOLEAN = 8; + /** + * Date BSON Type + * + * @classconstant BSON_DATA_DATE + **/ + BSON.BSON_DATA_DATE = 9; + /** + * null BSON Type + * + * @classconstant BSON_DATA_NULL + **/ + BSON.BSON_DATA_NULL = 10; + /** + * RegExp BSON Type + * + * @classconstant BSON_DATA_REGEXP + **/ + BSON.BSON_DATA_REGEXP = 11; + /** + * Code BSON Type + * + * @classconstant BSON_DATA_DBPOINTER + **/ + BSON.BSON_DATA_DBPOINTER = 12; + /** + * Code BSON Type + * + * @classconstant BSON_DATA_CODE + **/ + BSON.BSON_DATA_CODE = 13; + /** + * Symbol BSON Type + * + * @classconstant BSON_DATA_SYMBOL + **/ + BSON.BSON_DATA_SYMBOL = 14; + /** + * Code with Scope BSON Type + * + * @classconstant BSON_DATA_CODE_W_SCOPE + **/ + BSON.BSON_DATA_CODE_W_SCOPE = 15; + /** + * 32 bit Integer BSON Type + * + * @classconstant BSON_DATA_INT + **/ + BSON.BSON_DATA_INT = 16; + /** + * Timestamp BSON Type + * + * @classconstant BSON_DATA_TIMESTAMP + **/ + BSON.BSON_DATA_TIMESTAMP = 17; + /** + * Long BSON Type + * + * @classconstant BSON_DATA_LONG + **/ + BSON.BSON_DATA_LONG = 18; + /** + * Long BSON Type + * + * @classconstant BSON_DATA_DECIMAL128 + **/ + BSON.BSON_DATA_DECIMAL128 = 19; + /** + * MinKey BSON Type + * + * @classconstant BSON_DATA_MIN_KEY + **/ + BSON.BSON_DATA_MIN_KEY = 0xff; + /** + * MaxKey BSON Type + * + * @classconstant BSON_DATA_MAX_KEY + **/ + BSON.BSON_DATA_MAX_KEY = 0x7f; + + /** + * Binary Default Type + * + * @classconstant BSON_BINARY_SUBTYPE_DEFAULT + **/ + BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; + /** + * Binary Function Type + * + * @classconstant BSON_BINARY_SUBTYPE_FUNCTION + **/ + BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; + /** + * Binary Byte Array Type + * + * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY + **/ + BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; + /** + * Binary UUID Type + * + * @classconstant BSON_BINARY_SUBTYPE_UUID + **/ + BSON.BSON_BINARY_SUBTYPE_UUID = 3; + /** + * Binary MD5 Type + * + * @classconstant BSON_BINARY_SUBTYPE_MD5 + **/ + BSON.BSON_BINARY_SUBTYPE_MD5 = 4; + /** + * Binary User Defined Type + * + * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED + **/ + BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; + + // BSON MAX VALUES + BSON.BSON_INT32_MAX = 0x7fffffff; + BSON.BSON_INT32_MIN = -0x80000000; + + BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; + BSON.BSON_INT64_MIN = -Math.pow(2, 63); + + // JS MAX PRECISE VALUES + BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. + BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. + + // Internal long versions + var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. + var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. + + module.exports = deserialize; + +/***/ }), +/* 353 */ +/***/ (function(module, exports, __webpack_require__) { + + /* WEBPACK VAR INJECTION */(function(Buffer) {'use strict'; + + var writeIEEE754 = __webpack_require__(354).writeIEEE754, + Long = __webpack_require__(330).Long, + Map = __webpack_require__(329), + Binary = __webpack_require__(351).Binary; + + var normalizedFunctionString = __webpack_require__(339).normalizedFunctionString; + + // try { + // var _Buffer = Uint8Array; + // } catch (e) { + // _Buffer = Buffer; + // } + + var regexp = /\x00/; // eslint-disable-line no-control-regex + var ignoreKeys = ['$db', '$ref', '$id', '$clusterTime']; + + // To ensure that 0.4 of node works correctly + var isDate = function isDate(d) { + return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; + }; + + var isRegExp = function isRegExp(d) { + return Object.prototype.toString.call(d) === '[object RegExp]'; + }; + + var serializeString = function (buffer, key, value, index, isArray) { + // Encode String type + buffer[index++] = BSON.BSON_DATA_STRING; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Write the string + var size = buffer.write(value, index + 4, 'utf8'); + // Write the size of the string to buffer + buffer[index + 3] = size + 1 >> 24 & 0xff; + buffer[index + 2] = size + 1 >> 16 & 0xff; + buffer[index + 1] = size + 1 >> 8 & 0xff; + buffer[index] = size + 1 & 0xff; + // Update index + index = index + 4 + size; + // Write zero + buffer[index++] = 0; + return index; + }; + + var serializeNumber = function (buffer, key, value, index, isArray) { + // We have an integer value + if (Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { + // If the value fits in 32 bits encode as int, if it fits in a double + // encode it as a double, otherwise long + if (value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { + // Set int type 32 bits or less + buffer[index++] = BSON.BSON_DATA_INT; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the int value + buffer[index++] = value & 0xff; + buffer[index++] = value >> 8 & 0xff; + buffer[index++] = value >> 16 & 0xff; + buffer[index++] = value >> 24 & 0xff; + } else if (value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { + // Encode as double + buffer[index++] = BSON.BSON_DATA_NUMBER; + // Number of written bytes + numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write float + writeIEEE754(buffer, value, index, 'little', 52, 8); + // Ajust index + index = index + 8; + } else { + // Set long type + buffer[index++] = BSON.BSON_DATA_LONG; + // Number of written bytes + numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + var longVal = Long.fromNumber(value); + var lowBits = longVal.getLowBits(); + var highBits = longVal.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = lowBits >> 8 & 0xff; + buffer[index++] = lowBits >> 16 & 0xff; + buffer[index++] = lowBits >> 24 & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = highBits >> 8 & 0xff; + buffer[index++] = highBits >> 16 & 0xff; + buffer[index++] = highBits >> 24 & 0xff; + } + } else { + // Encode as double + buffer[index++] = BSON.BSON_DATA_NUMBER; + // Number of written bytes + numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write float + writeIEEE754(buffer, value, index, 'little', 52, 8); + // Ajust index + index = index + 8; + } + + return index; + }; + + var serializeNull = function (buffer, key, value, index, isArray) { + // Set long type + buffer[index++] = BSON.BSON_DATA_NULL; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + return index; + }; + + var serializeBoolean = function (buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_BOOLEAN; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Encode the boolean value + buffer[index++] = value ? 1 : 0; + return index; + }; + + var serializeDate = function (buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_DATE; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + // Write the date + var dateInMilis = Long.fromNumber(value.getTime()); + var lowBits = dateInMilis.getLowBits(); + var highBits = dateInMilis.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = lowBits >> 8 & 0xff; + buffer[index++] = lowBits >> 16 & 0xff; + buffer[index++] = lowBits >> 24 & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = highBits >> 8 & 0xff; + buffer[index++] = highBits >> 16 & 0xff; + buffer[index++] = highBits >> 24 & 0xff; + return index; + }; + + var serializeRegExp = function (buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_REGEXP; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + if (value.source && value.source.match(regexp) != null) { + throw Error('value ' + value.source + ' must not contain null bytes'); + } + // Adjust the index + index = index + buffer.write(value.source, index, 'utf8'); + // Write zero + buffer[index++] = 0x00; + // Write the parameters + if (value.global) buffer[index++] = 0x73; // s + if (value.ignoreCase) buffer[index++] = 0x69; // i + if (value.multiline) buffer[index++] = 0x6d; // m + // Add ending zero + buffer[index++] = 0x00; + return index; + }; + + var serializeBSONRegExp = function (buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_REGEXP; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + // Check the pattern for 0 bytes + if (value.pattern.match(regexp) != null) { + // The BSON spec doesn't allow keys with null bytes because keys are + // null-terminated. + throw Error('pattern ' + value.pattern + ' must not contain null bytes'); + } + + // Adjust the index + index = index + buffer.write(value.pattern, index, 'utf8'); + // Write zero + buffer[index++] = 0x00; + // Write the options + index = index + buffer.write(value.options.split('').sort().join(''), index, 'utf8'); + // Add ending zero + buffer[index++] = 0x00; + return index; + }; + + var serializeMinMax = function (buffer, key, value, index, isArray) { + // Write the type of either min or max key + if (value === null) { + buffer[index++] = BSON.BSON_DATA_NULL; + } else if (value._bsontype === 'MinKey') { + buffer[index++] = BSON.BSON_DATA_MIN_KEY; + } else { + buffer[index++] = BSON.BSON_DATA_MAX_KEY; + } + + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + return index; + }; + + var serializeObjectId = function (buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_OID; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + // Write the objectId into the shared buffer + if (typeof value.id === 'string') { + buffer.write(value.id, index, 'binary'); + } else if (value.id && value.id.copy) { + value.id.copy(buffer, index, 0, 12); + } else { + throw new Error('object [' + JSON.stringify(value) + '] is not a valid ObjectId'); + } + + // Ajust index + return index + 12; + }; + + var serializeBuffer = function (buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_BINARY; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Get size of the buffer (current write point) + var size = value.length; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = size >> 8 & 0xff; + buffer[index++] = size >> 16 & 0xff; + buffer[index++] = size >> 24 & 0xff; + // Write the default subtype + buffer[index++] = BSON.BSON_BINARY_SUBTYPE_DEFAULT; + // Copy the content form the binary field to the buffer + value.copy(buffer, index, 0, size); + // Adjust the index + index = index + size; + return index; + }; + + var serializeObject = function (buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, isArray, path) { + for (var i = 0; i < path.length; i++) { + if (path[i] === value) throw new Error('cyclic dependency detected'); + } + + // Push value to stack + path.push(value); + // Write the type + buffer[index++] = Array.isArray(value) ? BSON.BSON_DATA_ARRAY : BSON.BSON_DATA_OBJECT; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + var endIndex = serializeInto(buffer, value, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path); + // Pop stack + path.pop(); + // Write size + return endIndex; + }; + + var serializeDecimal128 = function (buffer, key, value, index, isArray) { + buffer[index++] = BSON.BSON_DATA_DECIMAL128; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the data from the value + value.bytes.copy(buffer, index, 0, 16); + return index + 16; + }; + + var serializeLong = function (buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = value._bsontype === 'Long' ? BSON.BSON_DATA_LONG : BSON.BSON_DATA_TIMESTAMP; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the date + var lowBits = value.getLowBits(); + var highBits = value.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = lowBits >> 8 & 0xff; + buffer[index++] = lowBits >> 16 & 0xff; + buffer[index++] = lowBits >> 24 & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = highBits >> 8 & 0xff; + buffer[index++] = highBits >> 16 & 0xff; + buffer[index++] = highBits >> 24 & 0xff; + return index; + }; + + var serializeInt32 = function (buffer, key, value, index, isArray) { + // Set int type 32 bits or less + buffer[index++] = BSON.BSON_DATA_INT; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the int value + buffer[index++] = value & 0xff; + buffer[index++] = value >> 8 & 0xff; + buffer[index++] = value >> 16 & 0xff; + buffer[index++] = value >> 24 & 0xff; + return index; + }; + + var serializeDouble = function (buffer, key, value, index, isArray) { + // Encode as double + buffer[index++] = BSON.BSON_DATA_NUMBER; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write float + writeIEEE754(buffer, value, index, 'little', 52, 8); + // Ajust index + index = index + 8; + return index; + }; + + var serializeFunction = function (buffer, key, value, index, checkKeys, depth, isArray) { + buffer[index++] = BSON.BSON_DATA_CODE; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Function string + var functionString = normalizedFunctionString(value); + + // Write the string + var size = buffer.write(functionString, index + 4, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = size & 0xff; + buffer[index + 1] = size >> 8 & 0xff; + buffer[index + 2] = size >> 16 & 0xff; + buffer[index + 3] = size >> 24 & 0xff; + // Update index + index = index + 4 + size - 1; + // Write zero + buffer[index++] = 0; + return index; + }; + + var serializeCode = function (buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, isArray) { + if (value.scope && typeof value.scope === 'object') { + // Write the type + buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + // Starting index + var startIndex = index; + + // Serialize the function + // Get the function string + var functionString = typeof value.code === 'string' ? value.code : value.code.toString(); + // Index adjustment + index = index + 4; + // Write string into buffer + var codeSize = buffer.write(functionString, index + 4, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = codeSize & 0xff; + buffer[index + 1] = codeSize >> 8 & 0xff; + buffer[index + 2] = codeSize >> 16 & 0xff; + buffer[index + 3] = codeSize >> 24 & 0xff; + // Write end 0 + buffer[index + 4 + codeSize - 1] = 0; + // Write the + index = index + codeSize + 4; + + // + // Serialize the scope value + var endIndex = serializeInto(buffer, value.scope, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined); + index = endIndex - 1; + + // Writ the total + var totalSize = endIndex - startIndex; + + // Write the total size of the object + buffer[startIndex++] = totalSize & 0xff; + buffer[startIndex++] = totalSize >> 8 & 0xff; + buffer[startIndex++] = totalSize >> 16 & 0xff; + buffer[startIndex++] = totalSize >> 24 & 0xff; + // Write trailing zero + buffer[index++] = 0; + } else { + buffer[index++] = BSON.BSON_DATA_CODE; + // Number of written bytes + numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Function string + functionString = value.code.toString(); + // Write the string + var size = buffer.write(functionString, index + 4, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = size & 0xff; + buffer[index + 1] = size >> 8 & 0xff; + buffer[index + 2] = size >> 16 & 0xff; + buffer[index + 3] = size >> 24 & 0xff; + // Update index + index = index + 4 + size - 1; + // Write zero + buffer[index++] = 0; + } + + return index; + }; + + var serializeBinary = function (buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_BINARY; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Extract the buffer + var data = value.value(true); + // Calculate size + var size = value.position; + // Add the deprecated 02 type 4 bytes of size to total + if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) size = size + 4; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = size >> 8 & 0xff; + buffer[index++] = size >> 16 & 0xff; + buffer[index++] = size >> 24 & 0xff; + // Write the subtype to the buffer + buffer[index++] = value.sub_type; + + // If we have binary type 2 the 4 first bytes are the size + if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { + size = size - 4; + buffer[index++] = size & 0xff; + buffer[index++] = size >> 8 & 0xff; + buffer[index++] = size >> 16 & 0xff; + buffer[index++] = size >> 24 & 0xff; + } + + // Write the data to the object + data.copy(buffer, index, 0, value.position); + // Adjust the index + index = index + value.position; + return index; + }; + + var serializeSymbol = function (buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_SYMBOL; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the string + var size = buffer.write(value.value, index + 4, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = size & 0xff; + buffer[index + 1] = size >> 8 & 0xff; + buffer[index + 2] = size >> 16 & 0xff; + buffer[index + 3] = size >> 24 & 0xff; + // Update index + index = index + 4 + size - 1; + // Write zero + buffer[index++] = 0x00; + return index; + }; + + var serializeDBRef = function (buffer, key, value, index, depth, serializeFunctions, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_OBJECT; + // Number of written bytes + var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); + + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + var startIndex = index; + var endIndex; + + // Serialize object + if (null != value.db) { + endIndex = serializeInto(buffer, { + $ref: value.namespace, + $id: value.oid, + $db: value.db + }, false, index, depth + 1, serializeFunctions); + } else { + endIndex = serializeInto(buffer, { + $ref: value.namespace, + $id: value.oid + }, false, index, depth + 1, serializeFunctions); + } + + // Calculate object size + var size = endIndex - startIndex; + // Write the size + buffer[startIndex++] = size & 0xff; + buffer[startIndex++] = size >> 8 & 0xff; + buffer[startIndex++] = size >> 16 & 0xff; + buffer[startIndex++] = size >> 24 & 0xff; + // Set index + return endIndex; + }; + + var serializeInto = function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializeFunctions, ignoreUndefined, path) { + startingIndex = startingIndex || 0; + path = path || []; + + // Push the object to the path + path.push(object); + + // Start place to serialize into + var index = startingIndex + 4; + // var self = this; + + // Special case isArray + if (Array.isArray(object)) { + // Get object keys + for (var i = 0; i < object.length; i++) { + var key = '' + i; + var value = object[i]; + + // Is there an override value + if (value && value.toBSON) { + if (typeof value.toBSON !== 'function') throw new Error('toBSON is not a function'); + value = value.toBSON(); + } + + var type = typeof value; + if (type === 'string') { + index = serializeString(buffer, key, value, index, true); + } else if (type === 'number') { + index = serializeNumber(buffer, key, value, index, true); + } else if (type === 'boolean') { + index = serializeBoolean(buffer, key, value, index, true); + } else if (value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index, true); + } else if (value === undefined) { + index = serializeNull(buffer, key, value, index, true); + } else if (value === null) { + index = serializeNull(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'ObjectID' || value['_bsontype'] === 'ObjectId') { + index = serializeObjectId(buffer, key, value, index, true); + } else if (Buffer.isBuffer(value)) { + index = serializeBuffer(buffer, key, value, index, true); + } else if (value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index, true); + } else if (type === 'object' && value['_bsontype'] == null) { + index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, true, path); + } else if (type === 'object' && value['_bsontype'] === 'Decimal128') { + index = serializeDecimal128(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { + index = serializeLong(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'Double') { + index = serializeDouble(buffer, key, value, index, true); + } else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions, true); + } else if (value['_bsontype'] === 'Code') { + index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, true); + } else if (value['_bsontype'] === 'Binary') { + index = serializeBinary(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'Symbol') { + index = serializeSymbol(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, true); + } else if (value['_bsontype'] === 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'Int32') { + index = serializeInt32(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { + index = serializeMinMax(buffer, key, value, index, true); + } + } + } else if (object instanceof Map) { + var iterator = object.entries(); + var done = false; + + while (!done) { + // Unpack the next entry + var entry = iterator.next(); + done = entry.done; + // Are we done, then skip and terminate + if (done) continue; + + // Get the entry values + key = entry.value[0]; + value = entry.value[1]; + + // Check the type of the value + type = typeof value; + + // Check the key and throw error if it's illegal + if (typeof key === 'string' && ignoreKeys.indexOf(key) === -1) { + if (key.match(regexp) != null) { + // The BSON spec doesn't allow keys with null bytes because keys are + // null-terminated. + throw Error('key ' + key + ' must not contain null bytes'); + } + + if (checkKeys) { + if ('$' === key[0]) { + throw Error('key ' + key + " must not start with '$'"); + } else if (~key.indexOf('.')) { + throw Error('key ' + key + " must not contain '.'"); + } + } + } + + if (type === 'string') { + index = serializeString(buffer, key, value, index); + } else if (type === 'number') { + index = serializeNumber(buffer, key, value, index); + } else if (type === 'boolean') { + index = serializeBoolean(buffer, key, value, index); + } else if (value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index); + // } else if (value === undefined && ignoreUndefined === true) { + } else if (value === null || value === undefined && ignoreUndefined === false) { + index = serializeNull(buffer, key, value, index); + } else if (value['_bsontype'] === 'ObjectID' || value['_bsontype'] === 'ObjectId') { + index = serializeObjectId(buffer, key, value, index); + } else if (Buffer.isBuffer(value)) { + index = serializeBuffer(buffer, key, value, index); + } else if (value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index); + } else if (type === 'object' && value['_bsontype'] == null) { + index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, false, path); + } else if (type === 'object' && value['_bsontype'] === 'Decimal128') { + index = serializeDecimal128(buffer, key, value, index); + } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { + index = serializeLong(buffer, key, value, index); + } else if (value['_bsontype'] === 'Double') { + index = serializeDouble(buffer, key, value, index); + } else if (value['_bsontype'] === 'Code') { + index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); + } else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); + } else if (value['_bsontype'] === 'Binary') { + index = serializeBinary(buffer, key, value, index); + } else if (value['_bsontype'] === 'Symbol') { + index = serializeSymbol(buffer, key, value, index); + } else if (value['_bsontype'] === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); + } else if (value['_bsontype'] === 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index); + } else if (value['_bsontype'] === 'Int32') { + index = serializeInt32(buffer, key, value, index); + } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { + index = serializeMinMax(buffer, key, value, index); + } + } + } else { + // Did we provide a custom serialization method + if (object.toBSON) { + if (typeof object.toBSON !== 'function') throw new Error('toBSON is not a function'); + object = object.toBSON(); + if (object != null && typeof object !== 'object') throw new Error('toBSON function did not return an object'); + } + + // Iterate over all the keys + for (key in object) { + value = object[key]; + // Is there an override value + if (value && value.toBSON) { + if (typeof value.toBSON !== 'function') throw new Error('toBSON is not a function'); + value = value.toBSON(); + } + + // Check the type of the value + type = typeof value; + + // Check the key and throw error if it's illegal + if (typeof key === 'string' && ignoreKeys.indexOf(key) === -1) { + if (key.match(regexp) != null) { + // The BSON spec doesn't allow keys with null bytes because keys are + // null-terminated. + throw Error('key ' + key + ' must not contain null bytes'); + } + + if (checkKeys) { + if ('$' === key[0]) { + throw Error('key ' + key + " must not start with '$'"); + } else if (~key.indexOf('.')) { + throw Error('key ' + key + " must not contain '.'"); + } + } + } + + if (type === 'string') { + index = serializeString(buffer, key, value, index); + } else if (type === 'number') { + index = serializeNumber(buffer, key, value, index); + } else if (type === 'boolean') { + index = serializeBoolean(buffer, key, value, index); + } else if (value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index); + } else if (value === undefined) { + if (ignoreUndefined === false) index = serializeNull(buffer, key, value, index); + } else if (value === null) { + index = serializeNull(buffer, key, value, index); + } else if (value['_bsontype'] === 'ObjectID' || value['_bsontype'] === 'ObjectId') { + index = serializeObjectId(buffer, key, value, index); + } else if (Buffer.isBuffer(value)) { + index = serializeBuffer(buffer, key, value, index); + } else if (value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index); + } else if (type === 'object' && value['_bsontype'] == null) { + index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, false, path); + } else if (type === 'object' && value['_bsontype'] === 'Decimal128') { + index = serializeDecimal128(buffer, key, value, index); + } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { + index = serializeLong(buffer, key, value, index); + } else if (value['_bsontype'] === 'Double') { + index = serializeDouble(buffer, key, value, index); + } else if (value['_bsontype'] === 'Code') { + index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); + } else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); + } else if (value['_bsontype'] === 'Binary') { + index = serializeBinary(buffer, key, value, index); + } else if (value['_bsontype'] === 'Symbol') { + index = serializeSymbol(buffer, key, value, index); + } else if (value['_bsontype'] === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); + } else if (value['_bsontype'] === 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index); + } else if (value['_bsontype'] === 'Int32') { + index = serializeInt32(buffer, key, value, index); + } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { + index = serializeMinMax(buffer, key, value, index); + } + } + } + + // Remove the path + path.pop(); + + // Final padding byte for object + buffer[index++] = 0x00; + + // Final size + var size = index - startingIndex; + // Write the size of the object + buffer[startingIndex++] = size & 0xff; + buffer[startingIndex++] = size >> 8 & 0xff; + buffer[startingIndex++] = size >> 16 & 0xff; + buffer[startingIndex++] = size >> 24 & 0xff; + return index; + }; + + var BSON = {}; + + /** + * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 + * + * @ignore + * @api private + */ + // var functionCache = (BSON.functionCache = {}); + + /** + * Number BSON Type + * + * @classconstant BSON_DATA_NUMBER + **/ + BSON.BSON_DATA_NUMBER = 1; + /** + * String BSON Type + * + * @classconstant BSON_DATA_STRING + **/ + BSON.BSON_DATA_STRING = 2; + /** + * Object BSON Type + * + * @classconstant BSON_DATA_OBJECT + **/ + BSON.BSON_DATA_OBJECT = 3; + /** + * Array BSON Type + * + * @classconstant BSON_DATA_ARRAY + **/ + BSON.BSON_DATA_ARRAY = 4; + /** + * Binary BSON Type + * + * @classconstant BSON_DATA_BINARY + **/ + BSON.BSON_DATA_BINARY = 5; + /** + * ObjectID BSON Type, deprecated + * + * @classconstant BSON_DATA_UNDEFINED + **/ + BSON.BSON_DATA_UNDEFINED = 6; + /** + * ObjectID BSON Type + * + * @classconstant BSON_DATA_OID + **/ + BSON.BSON_DATA_OID = 7; + /** + * Boolean BSON Type + * + * @classconstant BSON_DATA_BOOLEAN + **/ + BSON.BSON_DATA_BOOLEAN = 8; + /** + * Date BSON Type + * + * @classconstant BSON_DATA_DATE + **/ + BSON.BSON_DATA_DATE = 9; + /** + * null BSON Type + * + * @classconstant BSON_DATA_NULL + **/ + BSON.BSON_DATA_NULL = 10; + /** + * RegExp BSON Type + * + * @classconstant BSON_DATA_REGEXP + **/ + BSON.BSON_DATA_REGEXP = 11; + /** + * Code BSON Type + * + * @classconstant BSON_DATA_CODE + **/ + BSON.BSON_DATA_CODE = 13; + /** + * Symbol BSON Type + * + * @classconstant BSON_DATA_SYMBOL + **/ + BSON.BSON_DATA_SYMBOL = 14; + /** + * Code with Scope BSON Type + * + * @classconstant BSON_DATA_CODE_W_SCOPE + **/ + BSON.BSON_DATA_CODE_W_SCOPE = 15; + /** + * 32 bit Integer BSON Type + * + * @classconstant BSON_DATA_INT + **/ + BSON.BSON_DATA_INT = 16; + /** + * Timestamp BSON Type + * + * @classconstant BSON_DATA_TIMESTAMP + **/ + BSON.BSON_DATA_TIMESTAMP = 17; + /** + * Long BSON Type + * + * @classconstant BSON_DATA_LONG + **/ + BSON.BSON_DATA_LONG = 18; + /** + * Long BSON Type + * + * @classconstant BSON_DATA_DECIMAL128 + **/ + BSON.BSON_DATA_DECIMAL128 = 19; + /** + * MinKey BSON Type + * + * @classconstant BSON_DATA_MIN_KEY + **/ + BSON.BSON_DATA_MIN_KEY = 0xff; + /** + * MaxKey BSON Type + * + * @classconstant BSON_DATA_MAX_KEY + **/ + BSON.BSON_DATA_MAX_KEY = 0x7f; + /** + * Binary Default Type + * + * @classconstant BSON_BINARY_SUBTYPE_DEFAULT + **/ + BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; + /** + * Binary Function Type + * + * @classconstant BSON_BINARY_SUBTYPE_FUNCTION + **/ + BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; + /** + * Binary Byte Array Type + * + * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY + **/ + BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; + /** + * Binary UUID Type + * + * @classconstant BSON_BINARY_SUBTYPE_UUID + **/ + BSON.BSON_BINARY_SUBTYPE_UUID = 3; + /** + * Binary MD5 Type + * + * @classconstant BSON_BINARY_SUBTYPE_MD5 + **/ + BSON.BSON_BINARY_SUBTYPE_MD5 = 4; + /** + * Binary User Defined Type + * + * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED + **/ + BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; + + // BSON MAX VALUES + BSON.BSON_INT32_MAX = 0x7fffffff; + BSON.BSON_INT32_MIN = -0x80000000; + + BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; + BSON.BSON_INT64_MIN = -Math.pow(2, 63); + + // JS MAX PRECISE VALUES + BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. + BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. + + // Internal long versions + // var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. + // var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. + + module.exports = serializeInto; + /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(334).Buffer)) + +/***/ }), +/* 354 */ +/***/ (function(module, exports) { + + // Copyright (c) 2008, Fair Oaks Labs, Inc. + // All rights reserved. + // + // Redistribution and use in source and binary forms, with or without + // modification, are permitted provided that the following conditions are met: + // + // * Redistributions of source code must retain the above copyright notice, + // this list of conditions and the following disclaimer. + // + // * Redistributions in binary form must reproduce the above copyright notice, + // this list of conditions and the following disclaimer in the documentation + // and/or other materials provided with the distribution. + // + // * Neither the name of Fair Oaks Labs, Inc. nor the names of its contributors + // may be used to endorse or promote products derived from this software + // without specific prior written permission. + // + // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + // POSSIBILITY OF SUCH DAMAGE. + // + // + // Modifications to writeIEEE754 to support negative zeroes made by Brian White + + var readIEEE754 = function (buffer, offset, endian, mLen, nBytes) { + var e, + m, + bBE = endian === 'big', + eLen = nBytes * 8 - mLen - 1, + eMax = (1 << eLen) - 1, + eBias = eMax >> 1, + nBits = -7, + i = bBE ? 0 : nBytes - 1, + d = bBE ? 1 : -1, + s = buffer[offset + i]; + + i += d; + + e = s & (1 << -nBits) - 1; + s >>= -nBits; + nBits += eLen; + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8); + + m = e & (1 << -nBits) - 1; + e >>= -nBits; + nBits += mLen; + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8); + + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : (s ? -1 : 1) * Infinity; + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen); + }; + + var writeIEEE754 = function (buffer, value, offset, endian, mLen, nBytes) { + var e, + m, + c, + bBE = endian === 'big', + eLen = nBytes * 8 - mLen - 1, + eMax = (1 << eLen) - 1, + eBias = eMax >> 1, + rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0, + i = bBE ? nBytes - 1 : 0, + d = bBE ? -1 : 1, + s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0; + + value = Math.abs(value); + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8); + + e = e << mLen | m; + eLen += mLen; + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8); + + buffer[offset + i - d] |= s * 128; + }; + + exports.readIEEE754 = readIEEE754; + exports.writeIEEE754 = writeIEEE754; + +/***/ }), +/* 355 */ +/***/ (function(module, exports, __webpack_require__) { + + /* WEBPACK VAR INJECTION */(function(Buffer) {'use strict'; + + var Long = __webpack_require__(330).Long, + Double = __webpack_require__(331).Double, + Timestamp = __webpack_require__(332).Timestamp, + ObjectID = __webpack_require__(333).ObjectID, + Symbol = __webpack_require__(344).Symbol, + BSONRegExp = __webpack_require__(343).BSONRegExp, + Code = __webpack_require__(346).Code, + Decimal128 = __webpack_require__(347), + MinKey = __webpack_require__(348).MinKey, + MaxKey = __webpack_require__(349).MaxKey, + DBRef = __webpack_require__(350).DBRef, + Binary = __webpack_require__(351).Binary; + + var normalizedFunctionString = __webpack_require__(339).normalizedFunctionString; + + // To ensure that 0.4 of node works correctly + var isDate = function isDate(d) { + return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; + }; + + var calculateObjectSize = function calculateObjectSize(object, serializeFunctions, ignoreUndefined) { + var totalLength = 4 + 1; + + if (Array.isArray(object)) { + for (var i = 0; i < object.length; i++) { + totalLength += calculateElement(i.toString(), object[i], serializeFunctions, true, ignoreUndefined); + } + } else { + // If we have toBSON defined, override the current object + if (object.toBSON) { + object = object.toBSON(); + } + + // Calculate size + for (var key in object) { + totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined); + } + } + + return totalLength; + }; + + /** + * @ignore + * @api private + */ + function calculateElement(name, value, serializeFunctions, isArray, ignoreUndefined) { + // If we have toBSON defined, override the current object + if (value && value.toBSON) { + value = value.toBSON(); + } + + switch (typeof value) { + case 'string': + return 1 + Buffer.byteLength(name, 'utf8') + 1 + 4 + Buffer.byteLength(value, 'utf8') + 1; + case 'number': + if (Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { + if (value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { + // 32 bit + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (4 + 1); + } else { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); + } + } else { + // 64 bit + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); + } + case 'undefined': + if (isArray || !ignoreUndefined) return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1; + return 0; + case 'boolean': + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (1 + 1); + case 'object': + if (value == null || value instanceof MinKey || value instanceof MaxKey || value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1; + } else if (value instanceof ObjectID || value['_bsontype'] === 'ObjectID' || value['_bsontype'] === 'ObjectId') { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (12 + 1); + } else if (value instanceof Date || isDate(value)) { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); + } else if (typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (1 + 4 + 1) + value.length; + } else if (value instanceof Long || value instanceof Double || value instanceof Timestamp || value['_bsontype'] === 'Long' || value['_bsontype'] === 'Double' || value['_bsontype'] === 'Timestamp') { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); + } else if (value instanceof Decimal128 || value['_bsontype'] === 'Decimal128') { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (16 + 1); + } else if (value instanceof Code || value['_bsontype'] === 'Code') { + // Calculate size depending on the availability of a scope + if (value.scope != null && Object.keys(value.scope).length > 0) { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + 4 + 4 + Buffer.byteLength(value.code.toString(), 'utf8') + 1 + calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined); + } else { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + 4 + Buffer.byteLength(value.code.toString(), 'utf8') + 1; + } + } else if (value instanceof Binary || value['_bsontype'] === 'Binary') { + // Check what kind of subtype we have + if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (value.position + 1 + 4 + 1 + 4); + } else { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (value.position + 1 + 4 + 1); + } + } else if (value instanceof Symbol || value['_bsontype'] === 'Symbol') { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + Buffer.byteLength(value.value, 'utf8') + 4 + 1 + 1; + } else if (value instanceof DBRef || value['_bsontype'] === 'DBRef') { + // Set up correct object for serialization + var ordered_values = { + $ref: value.namespace, + $id: value.oid + }; + + // Add db reference if it exists + if (null != value.db) { + ordered_values['$db'] = value.db; + } + + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + calculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined); + } else if (value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]') { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + Buffer.byteLength(value.source, 'utf8') + 1 + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1; + } else if (value instanceof BSONRegExp || value['_bsontype'] === 'BSONRegExp') { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + Buffer.byteLength(value.pattern, 'utf8') + 1 + Buffer.byteLength(value.options, 'utf8') + 1; + } else { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + calculateObjectSize(value, serializeFunctions, ignoreUndefined) + 1; + } + case 'function': + // WTF for 0.4.X where typeof /someregexp/ === 'function' + if (value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]' || String.call(value) === '[object RegExp]') { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + Buffer.byteLength(value.source, 'utf8') + 1 + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1; + } else { + if (serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + 4 + 4 + Buffer.byteLength(normalizedFunctionString(value), 'utf8') + 1 + calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined); + } else if (serializeFunctions) { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + 4 + Buffer.byteLength(normalizedFunctionString(value), 'utf8') + 1; + } + } + } + + return 0; + } + + var BSON = {}; + + // BSON MAX VALUES + BSON.BSON_INT32_MAX = 0x7fffffff; + BSON.BSON_INT32_MIN = -0x80000000; + + // JS MAX PRECISE VALUES + BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. + BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. + + module.exports = calculateObjectSize; + /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(334).Buffer)) + +/***/ }) +/******/ ]) +}); +; \ No newline at end of file diff --git a/scripts/node_modules/bson/browser_build/package.json b/scripts/node_modules/bson/browser_build/package.json new file mode 100644 index 00000000..980db7f9 --- /dev/null +++ b/scripts/node_modules/bson/browser_build/package.json @@ -0,0 +1,8 @@ +{ "name" : "bson" +, "description" : "A bson parser for node.js and the browser" +, "main": "../" +, "directories" : { "lib" : "../lib/bson" } +, "engines" : { "node" : ">=0.6.0" } +, "licenses" : [ { "type" : "Apache License, Version 2.0" + , "url" : "http://www.apache.org/licenses/LICENSE-2.0" } ] +} diff --git a/scripts/node_modules/bson/index.js b/scripts/node_modules/bson/index.js new file mode 100644 index 00000000..6502552d --- /dev/null +++ b/scripts/node_modules/bson/index.js @@ -0,0 +1,46 @@ +var BSON = require('./lib/bson/bson'), + Binary = require('./lib/bson/binary'), + Code = require('./lib/bson/code'), + DBRef = require('./lib/bson/db_ref'), + Decimal128 = require('./lib/bson/decimal128'), + Double = require('./lib/bson/double'), + Int32 = require('./lib/bson/int_32'), + Long = require('./lib/bson/long'), + Map = require('./lib/bson/map'), + MaxKey = require('./lib/bson/max_key'), + MinKey = require('./lib/bson/min_key'), + ObjectId = require('./lib/bson/objectid'), + BSONRegExp = require('./lib/bson/regexp'), + Symbol = require('./lib/bson/symbol'), + Timestamp = require('./lib/bson/timestamp'); + +// BSON MAX VALUES +BSON.BSON_INT32_MAX = 0x7fffffff; +BSON.BSON_INT32_MIN = -0x80000000; + +BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; +BSON.BSON_INT64_MIN = -Math.pow(2, 63); + +// JS MAX PRECISE VALUES +BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. +BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. + +// Add BSON types to function creation +BSON.Binary = Binary; +BSON.Code = Code; +BSON.DBRef = DBRef; +BSON.Decimal128 = Decimal128; +BSON.Double = Double; +BSON.Int32 = Int32; +BSON.Long = Long; +BSON.Map = Map; +BSON.MaxKey = MaxKey; +BSON.MinKey = MinKey; +BSON.ObjectId = ObjectId; +BSON.ObjectID = ObjectId; +BSON.BSONRegExp = BSONRegExp; +BSON.Symbol = Symbol; +BSON.Timestamp = Timestamp; + +// Return the BSON +module.exports = BSON; diff --git a/scripts/node_modules/bson/lib/bson/binary.js b/scripts/node_modules/bson/lib/bson/binary.js new file mode 100644 index 00000000..6d190bca --- /dev/null +++ b/scripts/node_modules/bson/lib/bson/binary.js @@ -0,0 +1,384 @@ +/** + * Module dependencies. + * @ignore + */ + +// Test if we're in Node via presence of "global" not absence of "window" +// to support hybrid environments like Electron +if (typeof global !== 'undefined') { + var Buffer = require('buffer').Buffer; // TODO just use global Buffer +} + +var utils = require('./parser/utils'); + +/** + * A class representation of the BSON Binary type. + * + * Sub types + * - **BSON.BSON_BINARY_SUBTYPE_DEFAULT**, default BSON type. + * - **BSON.BSON_BINARY_SUBTYPE_FUNCTION**, BSON function type. + * - **BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY**, BSON byte array type. + * - **BSON.BSON_BINARY_SUBTYPE_UUID**, BSON uuid type. + * - **BSON.BSON_BINARY_SUBTYPE_MD5**, BSON md5 type. + * - **BSON.BSON_BINARY_SUBTYPE_USER_DEFINED**, BSON user defined type. + * + * @class + * @param {Buffer} buffer a buffer object containing the binary data. + * @param {Number} [subType] the option binary type. + * @return {Binary} + */ +function Binary(buffer, subType) { + if (!(this instanceof Binary)) return new Binary(buffer, subType); + + if ( + buffer != null && + !(typeof buffer === 'string') && + !Buffer.isBuffer(buffer) && + !(buffer instanceof Uint8Array) && + !Array.isArray(buffer) + ) { + throw new Error('only String, Buffer, Uint8Array or Array accepted'); + } + + this._bsontype = 'Binary'; + + if (buffer instanceof Number) { + this.sub_type = buffer; + this.position = 0; + } else { + this.sub_type = subType == null ? BSON_BINARY_SUBTYPE_DEFAULT : subType; + this.position = 0; + } + + if (buffer != null && !(buffer instanceof Number)) { + // Only accept Buffer, Uint8Array or Arrays + if (typeof buffer === 'string') { + // Different ways of writing the length of the string for the different types + if (typeof Buffer !== 'undefined') { + this.buffer = utils.toBuffer(buffer); + } else if ( + typeof Uint8Array !== 'undefined' || + Object.prototype.toString.call(buffer) === '[object Array]' + ) { + this.buffer = writeStringToArray(buffer); + } else { + throw new Error('only String, Buffer, Uint8Array or Array accepted'); + } + } else { + this.buffer = buffer; + } + this.position = buffer.length; + } else { + if (typeof Buffer !== 'undefined') { + this.buffer = utils.allocBuffer(Binary.BUFFER_SIZE); + } else if (typeof Uint8Array !== 'undefined') { + this.buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE)); + } else { + this.buffer = new Array(Binary.BUFFER_SIZE); + } + // Set position to start of buffer + this.position = 0; + } +} + +/** + * Updates this binary with byte_value. + * + * @method + * @param {string} byte_value a single byte we wish to write. + */ +Binary.prototype.put = function put(byte_value) { + // If it's a string and a has more than one character throw an error + if (byte_value['length'] != null && typeof byte_value !== 'number' && byte_value.length !== 1) + throw new Error('only accepts single character String, Uint8Array or Array'); + if ((typeof byte_value !== 'number' && byte_value < 0) || byte_value > 255) + throw new Error('only accepts number in a valid unsigned byte range 0-255'); + + // Decode the byte value once + var decoded_byte = null; + if (typeof byte_value === 'string') { + decoded_byte = byte_value.charCodeAt(0); + } else if (byte_value['length'] != null) { + decoded_byte = byte_value[0]; + } else { + decoded_byte = byte_value; + } + + if (this.buffer.length > this.position) { + this.buffer[this.position++] = decoded_byte; + } else { + if (typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer)) { + // Create additional overflow buffer + var buffer = utils.allocBuffer(Binary.BUFFER_SIZE + this.buffer.length); + // Combine the two buffers together + this.buffer.copy(buffer, 0, 0, this.buffer.length); + this.buffer = buffer; + this.buffer[this.position++] = decoded_byte; + } else { + buffer = null; + // Create a new buffer (typed or normal array) + if (Object.prototype.toString.call(this.buffer) === '[object Uint8Array]') { + buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE + this.buffer.length)); + } else { + buffer = new Array(Binary.BUFFER_SIZE + this.buffer.length); + } + + // We need to copy all the content to the new array + for (var i = 0; i < this.buffer.length; i++) { + buffer[i] = this.buffer[i]; + } + + // Reassign the buffer + this.buffer = buffer; + // Write the byte + this.buffer[this.position++] = decoded_byte; + } + } +}; + +/** + * Writes a buffer or string to the binary. + * + * @method + * @param {(Buffer|string)} string a string or buffer to be written to the Binary BSON object. + * @param {number} offset specify the binary of where to write the content. + * @return {null} + */ +Binary.prototype.write = function write(string, offset) { + offset = typeof offset === 'number' ? offset : this.position; + + // If the buffer is to small let's extend the buffer + if (this.buffer.length < offset + string.length) { + var buffer = null; + // If we are in node.js + if (typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer)) { + buffer = utils.allocBuffer(this.buffer.length + string.length); + this.buffer.copy(buffer, 0, 0, this.buffer.length); + } else if (Object.prototype.toString.call(this.buffer) === '[object Uint8Array]') { + // Create a new buffer + buffer = new Uint8Array(new ArrayBuffer(this.buffer.length + string.length)); + // Copy the content + for (var i = 0; i < this.position; i++) { + buffer[i] = this.buffer[i]; + } + } + + // Assign the new buffer + this.buffer = buffer; + } + + if (typeof Buffer !== 'undefined' && Buffer.isBuffer(string) && Buffer.isBuffer(this.buffer)) { + string.copy(this.buffer, offset, 0, string.length); + this.position = offset + string.length > this.position ? offset + string.length : this.position; + // offset = string.length + } else if ( + typeof Buffer !== 'undefined' && + typeof string === 'string' && + Buffer.isBuffer(this.buffer) + ) { + this.buffer.write(string, offset, 'binary'); + this.position = offset + string.length > this.position ? offset + string.length : this.position; + // offset = string.length; + } else if ( + Object.prototype.toString.call(string) === '[object Uint8Array]' || + (Object.prototype.toString.call(string) === '[object Array]' && typeof string !== 'string') + ) { + for (i = 0; i < string.length; i++) { + this.buffer[offset++] = string[i]; + } + + this.position = offset > this.position ? offset : this.position; + } else if (typeof string === 'string') { + for (i = 0; i < string.length; i++) { + this.buffer[offset++] = string.charCodeAt(i); + } + + this.position = offset > this.position ? offset : this.position; + } +}; + +/** + * Reads **length** bytes starting at **position**. + * + * @method + * @param {number} position read from the given position in the Binary. + * @param {number} length the number of bytes to read. + * @return {Buffer} + */ +Binary.prototype.read = function read(position, length) { + length = length && length > 0 ? length : this.position; + + // Let's return the data based on the type we have + if (this.buffer['slice']) { + return this.buffer.slice(position, position + length); + } else { + // Create a buffer to keep the result + var buffer = + typeof Uint8Array !== 'undefined' + ? new Uint8Array(new ArrayBuffer(length)) + : new Array(length); + for (var i = 0; i < length; i++) { + buffer[i] = this.buffer[position++]; + } + } + // Return the buffer + return buffer; +}; + +/** + * Returns the value of this binary as a string. + * + * @method + * @return {string} + */ +Binary.prototype.value = function value(asRaw) { + asRaw = asRaw == null ? false : asRaw; + + // Optimize to serialize for the situation where the data == size of buffer + if ( + asRaw && + typeof Buffer !== 'undefined' && + Buffer.isBuffer(this.buffer) && + this.buffer.length === this.position + ) + return this.buffer; + + // If it's a node.js buffer object + if (typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer)) { + return asRaw + ? this.buffer.slice(0, this.position) + : this.buffer.toString('binary', 0, this.position); + } else { + if (asRaw) { + // we support the slice command use it + if (this.buffer['slice'] != null) { + return this.buffer.slice(0, this.position); + } else { + // Create a new buffer to copy content to + var newBuffer = + Object.prototype.toString.call(this.buffer) === '[object Uint8Array]' + ? new Uint8Array(new ArrayBuffer(this.position)) + : new Array(this.position); + // Copy content + for (var i = 0; i < this.position; i++) { + newBuffer[i] = this.buffer[i]; + } + // Return the buffer + return newBuffer; + } + } else { + return convertArraytoUtf8BinaryString(this.buffer, 0, this.position); + } + } +}; + +/** + * Length. + * + * @method + * @return {number} the length of the binary. + */ +Binary.prototype.length = function length() { + return this.position; +}; + +/** + * @ignore + */ +Binary.prototype.toJSON = function() { + return this.buffer != null ? this.buffer.toString('base64') : ''; +}; + +/** + * @ignore + */ +Binary.prototype.toString = function(format) { + return this.buffer != null ? this.buffer.slice(0, this.position).toString(format) : ''; +}; + +/** + * Binary default subtype + * @ignore + */ +var BSON_BINARY_SUBTYPE_DEFAULT = 0; + +/** + * @ignore + */ +var writeStringToArray = function(data) { + // Create a buffer + var buffer = + typeof Uint8Array !== 'undefined' + ? new Uint8Array(new ArrayBuffer(data.length)) + : new Array(data.length); + // Write the content to the buffer + for (var i = 0; i < data.length; i++) { + buffer[i] = data.charCodeAt(i); + } + // Write the string to the buffer + return buffer; +}; + +/** + * Convert Array ot Uint8Array to Binary String + * + * @ignore + */ +var convertArraytoUtf8BinaryString = function(byteArray, startIndex, endIndex) { + var result = ''; + for (var i = startIndex; i < endIndex; i++) { + result = result + String.fromCharCode(byteArray[i]); + } + return result; +}; + +Binary.BUFFER_SIZE = 256; + +/** + * Default BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_DEFAULT = 0; +/** + * Function BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_FUNCTION = 1; +/** + * Byte Array BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_BYTE_ARRAY = 2; +/** + * OLD UUID BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_UUID_OLD = 3; +/** + * UUID BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_UUID = 4; +/** + * MD5 BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_MD5 = 5; +/** + * User BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_USER_DEFINED = 128; + +/** + * Expose. + */ +module.exports = Binary; +module.exports.Binary = Binary; diff --git a/scripts/node_modules/bson/lib/bson/bson.js b/scripts/node_modules/bson/lib/bson/bson.js new file mode 100644 index 00000000..912c5b92 --- /dev/null +++ b/scripts/node_modules/bson/lib/bson/bson.js @@ -0,0 +1,386 @@ +'use strict'; + +var Map = require('./map'), + Long = require('./long'), + Double = require('./double'), + Timestamp = require('./timestamp'), + ObjectID = require('./objectid'), + BSONRegExp = require('./regexp'), + Symbol = require('./symbol'), + Int32 = require('./int_32'), + Code = require('./code'), + Decimal128 = require('./decimal128'), + MinKey = require('./min_key'), + MaxKey = require('./max_key'), + DBRef = require('./db_ref'), + Binary = require('./binary'); + +// Parts of the parser +var deserialize = require('./parser/deserializer'), + serializer = require('./parser/serializer'), + calculateObjectSize = require('./parser/calculate_size'), + utils = require('./parser/utils'); + +/** + * @ignore + * @api private + */ +// Default Max Size +var MAXSIZE = 1024 * 1024 * 17; + +// Current Internal Temporary Serialization Buffer +var buffer = utils.allocBuffer(MAXSIZE); + +var BSON = function() {}; + +/** + * Serialize a Javascript object. + * + * @param {Object} object the Javascript object to serialize. + * @param {Boolean} [options.checkKeys] the serializer will check if keys are valid. + * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. + * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. + * @param {Number} [options.minInternalBufferSize=1024*1024*17] minimum size of the internal temporary serialization buffer **(default:1024*1024*17)**. + * @return {Buffer} returns the Buffer object containing the serialized object. + * @api public + */ +BSON.prototype.serialize = function serialize(object, options) { + options = options || {}; + // Unpack the options + var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; + var serializeFunctions = + typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + var ignoreUndefined = + typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; + var minInternalBufferSize = + typeof options.minInternalBufferSize === 'number' ? options.minInternalBufferSize : MAXSIZE; + + // Resize the internal serialization buffer if needed + if (buffer.length < minInternalBufferSize) { + buffer = utils.allocBuffer(minInternalBufferSize); + } + + // Attempt to serialize + var serializationIndex = serializer( + buffer, + object, + checkKeys, + 0, + 0, + serializeFunctions, + ignoreUndefined, + [] + ); + // Create the final buffer + var finishedBuffer = utils.allocBuffer(serializationIndex); + // Copy into the finished buffer + buffer.copy(finishedBuffer, 0, 0, finishedBuffer.length); + // Return the buffer + return finishedBuffer; +}; + +/** + * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. + * + * @param {Object} object the Javascript object to serialize. + * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. + * @param {Boolean} [options.checkKeys] the serializer will check if keys are valid. + * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. + * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. + * @param {Number} [options.index] the index in the buffer where we wish to start serializing into. + * @return {Number} returns the index pointing to the last written byte in the buffer. + * @api public + */ +BSON.prototype.serializeWithBufferAndIndex = function(object, finalBuffer, options) { + options = options || {}; + // Unpack the options + var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; + var serializeFunctions = + typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + var ignoreUndefined = + typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; + var startIndex = typeof options.index === 'number' ? options.index : 0; + + // Attempt to serialize + var serializationIndex = serializer( + finalBuffer, + object, + checkKeys, + startIndex || 0, + 0, + serializeFunctions, + ignoreUndefined + ); + + // Return the index + return serializationIndex - 1; +}; + +/** + * Deserialize data as BSON. + * + * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. + * @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized. + * @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse. + * @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function. + * @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits + * @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a node.js Buffer instance. + * @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types. + * @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer. + * @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances. + * @return {Object} returns the deserialized Javascript Object. + * @api public + */ +BSON.prototype.deserialize = function(buffer, options) { + return deserialize(buffer, options); +}; + +/** + * Calculate the bson size for a passed in Javascript object. + * + * @param {Object} object the Javascript object to calculate the BSON byte size for. + * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. + * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. + * @return {Number} returns the number of bytes the BSON object will take up. + * @api public + */ +BSON.prototype.calculateObjectSize = function(object, options) { + options = options || {}; + + var serializeFunctions = + typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + var ignoreUndefined = + typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; + + return calculateObjectSize(object, serializeFunctions, ignoreUndefined); +}; + +/** + * Deserialize stream data as BSON documents. + * + * @param {Buffer} data the buffer containing the serialized set of BSON documents. + * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. + * @param {Number} numberOfDocuments number of documents to deserialize. + * @param {Array} documents an array where to store the deserialized documents. + * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. + * @param {Object} [options] additional options used for the deserialization. + * @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized. + * @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse. + * @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function. + * @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits + * @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a node.js Buffer instance. + * @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types. + * @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer. + * @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances. + * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. + * @api public + */ +BSON.prototype.deserializeStream = function( + data, + startIndex, + numberOfDocuments, + documents, + docStartIndex, + options +) { + options = options != null ? options : {}; + var index = startIndex; + // Loop over all documents + for (var i = 0; i < numberOfDocuments; i++) { + // Find size of the document + var size = + data[index] | (data[index + 1] << 8) | (data[index + 2] << 16) | (data[index + 3] << 24); + // Update options with index + options['index'] = index; + // Parse the document at this point + documents[docStartIndex + i] = this.deserialize(data, options); + // Adjust index by the document size + index = index + size; + } + + // Return object containing end index of parsing and list of documents + return index; +}; + +/** + * @ignore + * @api private + */ +// BSON MAX VALUES +BSON.BSON_INT32_MAX = 0x7fffffff; +BSON.BSON_INT32_MIN = -0x80000000; + +BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; +BSON.BSON_INT64_MIN = -Math.pow(2, 63); + +// JS MAX PRECISE VALUES +BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. +BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. + +// Internal long versions +// var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. +// var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. + +/** + * Number BSON Type + * + * @classconstant BSON_DATA_NUMBER + **/ +BSON.BSON_DATA_NUMBER = 1; +/** + * String BSON Type + * + * @classconstant BSON_DATA_STRING + **/ +BSON.BSON_DATA_STRING = 2; +/** + * Object BSON Type + * + * @classconstant BSON_DATA_OBJECT + **/ +BSON.BSON_DATA_OBJECT = 3; +/** + * Array BSON Type + * + * @classconstant BSON_DATA_ARRAY + **/ +BSON.BSON_DATA_ARRAY = 4; +/** + * Binary BSON Type + * + * @classconstant BSON_DATA_BINARY + **/ +BSON.BSON_DATA_BINARY = 5; +/** + * ObjectID BSON Type + * + * @classconstant BSON_DATA_OID + **/ +BSON.BSON_DATA_OID = 7; +/** + * Boolean BSON Type + * + * @classconstant BSON_DATA_BOOLEAN + **/ +BSON.BSON_DATA_BOOLEAN = 8; +/** + * Date BSON Type + * + * @classconstant BSON_DATA_DATE + **/ +BSON.BSON_DATA_DATE = 9; +/** + * null BSON Type + * + * @classconstant BSON_DATA_NULL + **/ +BSON.BSON_DATA_NULL = 10; +/** + * RegExp BSON Type + * + * @classconstant BSON_DATA_REGEXP + **/ +BSON.BSON_DATA_REGEXP = 11; +/** + * Code BSON Type + * + * @classconstant BSON_DATA_CODE + **/ +BSON.BSON_DATA_CODE = 13; +/** + * Symbol BSON Type + * + * @classconstant BSON_DATA_SYMBOL + **/ +BSON.BSON_DATA_SYMBOL = 14; +/** + * Code with Scope BSON Type + * + * @classconstant BSON_DATA_CODE_W_SCOPE + **/ +BSON.BSON_DATA_CODE_W_SCOPE = 15; +/** + * 32 bit Integer BSON Type + * + * @classconstant BSON_DATA_INT + **/ +BSON.BSON_DATA_INT = 16; +/** + * Timestamp BSON Type + * + * @classconstant BSON_DATA_TIMESTAMP + **/ +BSON.BSON_DATA_TIMESTAMP = 17; +/** + * Long BSON Type + * + * @classconstant BSON_DATA_LONG + **/ +BSON.BSON_DATA_LONG = 18; +/** + * MinKey BSON Type + * + * @classconstant BSON_DATA_MIN_KEY + **/ +BSON.BSON_DATA_MIN_KEY = 0xff; +/** + * MaxKey BSON Type + * + * @classconstant BSON_DATA_MAX_KEY + **/ +BSON.BSON_DATA_MAX_KEY = 0x7f; + +/** + * Binary Default Type + * + * @classconstant BSON_BINARY_SUBTYPE_DEFAULT + **/ +BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; +/** + * Binary Function Type + * + * @classconstant BSON_BINARY_SUBTYPE_FUNCTION + **/ +BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; +/** + * Binary Byte Array Type + * + * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY + **/ +BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; +/** + * Binary UUID Type + * + * @classconstant BSON_BINARY_SUBTYPE_UUID + **/ +BSON.BSON_BINARY_SUBTYPE_UUID = 3; +/** + * Binary MD5 Type + * + * @classconstant BSON_BINARY_SUBTYPE_MD5 + **/ +BSON.BSON_BINARY_SUBTYPE_MD5 = 4; +/** + * Binary User Defined Type + * + * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED + **/ +BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; + +// Return BSON +module.exports = BSON; +module.exports.Code = Code; +module.exports.Map = Map; +module.exports.Symbol = Symbol; +module.exports.BSON = BSON; +module.exports.DBRef = DBRef; +module.exports.Binary = Binary; +module.exports.ObjectID = ObjectID; +module.exports.Long = Long; +module.exports.Timestamp = Timestamp; +module.exports.Double = Double; +module.exports.Int32 = Int32; +module.exports.MinKey = MinKey; +module.exports.MaxKey = MaxKey; +module.exports.BSONRegExp = BSONRegExp; +module.exports.Decimal128 = Decimal128; diff --git a/scripts/node_modules/bson/lib/bson/code.js b/scripts/node_modules/bson/lib/bson/code.js new file mode 100644 index 00000000..c2984cd5 --- /dev/null +++ b/scripts/node_modules/bson/lib/bson/code.js @@ -0,0 +1,24 @@ +/** + * A class representation of the BSON Code type. + * + * @class + * @param {(string|function)} code a string or function. + * @param {Object} [scope] an optional scope for the function. + * @return {Code} + */ +var Code = function Code(code, scope) { + if (!(this instanceof Code)) return new Code(code, scope); + this._bsontype = 'Code'; + this.code = code; + this.scope = scope; +}; + +/** + * @ignore + */ +Code.prototype.toJSON = function() { + return { scope: this.scope, code: this.code }; +}; + +module.exports = Code; +module.exports.Code = Code; diff --git a/scripts/node_modules/bson/lib/bson/db_ref.js b/scripts/node_modules/bson/lib/bson/db_ref.js new file mode 100644 index 00000000..f95795b1 --- /dev/null +++ b/scripts/node_modules/bson/lib/bson/db_ref.js @@ -0,0 +1,32 @@ +/** + * A class representation of the BSON DBRef type. + * + * @class + * @param {string} namespace the collection name. + * @param {ObjectID} oid the reference ObjectID. + * @param {string} [db] optional db name, if omitted the reference is local to the current db. + * @return {DBRef} + */ +function DBRef(namespace, oid, db) { + if (!(this instanceof DBRef)) return new DBRef(namespace, oid, db); + + this._bsontype = 'DBRef'; + this.namespace = namespace; + this.oid = oid; + this.db = db; +} + +/** + * @ignore + * @api private + */ +DBRef.prototype.toJSON = function() { + return { + $ref: this.namespace, + $id: this.oid, + $db: this.db == null ? '' : this.db + }; +}; + +module.exports = DBRef; +module.exports.DBRef = DBRef; diff --git a/scripts/node_modules/bson/lib/bson/decimal128.js b/scripts/node_modules/bson/lib/bson/decimal128.js new file mode 100644 index 00000000..924513f4 --- /dev/null +++ b/scripts/node_modules/bson/lib/bson/decimal128.js @@ -0,0 +1,820 @@ +'use strict'; + +var Long = require('./long'); + +var PARSE_STRING_REGEXP = /^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/; +var PARSE_INF_REGEXP = /^(\+|-)?(Infinity|inf)$/i; +var PARSE_NAN_REGEXP = /^(\+|-)?NaN$/i; + +var EXPONENT_MAX = 6111; +var EXPONENT_MIN = -6176; +var EXPONENT_BIAS = 6176; +var MAX_DIGITS = 34; + +// Nan value bits as 32 bit values (due to lack of longs) +var NAN_BUFFER = [ + 0x7c, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00 +].reverse(); +// Infinity value bits 32 bit values (due to lack of longs) +var INF_NEGATIVE_BUFFER = [ + 0xf8, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00 +].reverse(); +var INF_POSITIVE_BUFFER = [ + 0x78, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00 +].reverse(); + +var EXPONENT_REGEX = /^([-+])?(\d+)?$/; + +var utils = require('./parser/utils'); + +// Detect if the value is a digit +var isDigit = function(value) { + return !isNaN(parseInt(value, 10)); +}; + +// Divide two uint128 values +var divideu128 = function(value) { + var DIVISOR = Long.fromNumber(1000 * 1000 * 1000); + var _rem = Long.fromNumber(0); + var i = 0; + + if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) { + return { quotient: value, rem: _rem }; + } + + for (i = 0; i <= 3; i++) { + // Adjust remainder to match value of next dividend + _rem = _rem.shiftLeft(32); + // Add the divided to _rem + _rem = _rem.add(new Long(value.parts[i], 0)); + value.parts[i] = _rem.div(DIVISOR).low_; + _rem = _rem.modulo(DIVISOR); + } + + return { quotient: value, rem: _rem }; +}; + +// Multiply two Long values and return the 128 bit value +var multiply64x2 = function(left, right) { + if (!left && !right) { + return { high: Long.fromNumber(0), low: Long.fromNumber(0) }; + } + + var leftHigh = left.shiftRightUnsigned(32); + var leftLow = new Long(left.getLowBits(), 0); + var rightHigh = right.shiftRightUnsigned(32); + var rightLow = new Long(right.getLowBits(), 0); + + var productHigh = leftHigh.multiply(rightHigh); + var productMid = leftHigh.multiply(rightLow); + var productMid2 = leftLow.multiply(rightHigh); + var productLow = leftLow.multiply(rightLow); + + productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); + productMid = new Long(productMid.getLowBits(), 0) + .add(productMid2) + .add(productLow.shiftRightUnsigned(32)); + + productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); + productLow = productMid.shiftLeft(32).add(new Long(productLow.getLowBits(), 0)); + + // Return the 128 bit result + return { high: productHigh, low: productLow }; +}; + +var lessThan = function(left, right) { + // Make values unsigned + var uhleft = left.high_ >>> 0; + var uhright = right.high_ >>> 0; + + // Compare high bits first + if (uhleft < uhright) { + return true; + } else if (uhleft === uhright) { + var ulleft = left.low_ >>> 0; + var ulright = right.low_ >>> 0; + if (ulleft < ulright) return true; + } + + return false; +}; + +// var longtoHex = function(value) { +// var buffer = utils.allocBuffer(8); +// var index = 0; +// // Encode the low 64 bits of the decimal +// // Encode low bits +// buffer[index++] = value.low_ & 0xff; +// buffer[index++] = (value.low_ >> 8) & 0xff; +// buffer[index++] = (value.low_ >> 16) & 0xff; +// buffer[index++] = (value.low_ >> 24) & 0xff; +// // Encode high bits +// buffer[index++] = value.high_ & 0xff; +// buffer[index++] = (value.high_ >> 8) & 0xff; +// buffer[index++] = (value.high_ >> 16) & 0xff; +// buffer[index++] = (value.high_ >> 24) & 0xff; +// return buffer.reverse().toString('hex'); +// }; + +// var int32toHex = function(value) { +// var buffer = utils.allocBuffer(4); +// var index = 0; +// // Encode the low 64 bits of the decimal +// // Encode low bits +// buffer[index++] = value & 0xff; +// buffer[index++] = (value >> 8) & 0xff; +// buffer[index++] = (value >> 16) & 0xff; +// buffer[index++] = (value >> 24) & 0xff; +// return buffer.reverse().toString('hex'); +// }; + +/** + * A class representation of the BSON Decimal128 type. + * + * @class + * @param {Buffer} bytes a buffer containing the raw Decimal128 bytes. + * @return {Double} + */ +var Decimal128 = function(bytes) { + this._bsontype = 'Decimal128'; + this.bytes = bytes; +}; + +/** + * Create a Decimal128 instance from a string representation + * + * @method + * @param {string} string a numeric string representation. + * @return {Decimal128} returns a Decimal128 instance. + */ +Decimal128.fromString = function(string) { + // Parse state tracking + var isNegative = false; + var sawRadix = false; + var foundNonZero = false; + + // Total number of significant digits (no leading or trailing zero) + var significantDigits = 0; + // Total number of significand digits read + var nDigitsRead = 0; + // Total number of digits (no leading zeros) + var nDigits = 0; + // The number of the digits after radix + var radixPosition = 0; + // The index of the first non-zero in *str* + var firstNonZero = 0; + + // Digits Array + var digits = [0]; + // The number of digits in digits + var nDigitsStored = 0; + // Insertion pointer for digits + var digitsInsert = 0; + // The index of the first non-zero digit + var firstDigit = 0; + // The index of the last digit + var lastDigit = 0; + + // Exponent + var exponent = 0; + // loop index over array + var i = 0; + // The high 17 digits of the significand + var significandHigh = [0, 0]; + // The low 17 digits of the significand + var significandLow = [0, 0]; + // The biased exponent + var biasedExponent = 0; + + // Read index + var index = 0; + + // Trim the string + string = string.trim(); + + // Naively prevent against REDOS attacks. + // TODO: implementing a custom parsing for this, or refactoring the regex would yield + // further gains. + if (string.length >= 7000) { + throw new Error('' + string + ' not a valid Decimal128 string'); + } + + // Results + var stringMatch = string.match(PARSE_STRING_REGEXP); + var infMatch = string.match(PARSE_INF_REGEXP); + var nanMatch = string.match(PARSE_NAN_REGEXP); + + // Validate the string + if ((!stringMatch && !infMatch && !nanMatch) || string.length === 0) { + throw new Error('' + string + ' not a valid Decimal128 string'); + } + + // Check if we have an illegal exponent format + if (stringMatch && stringMatch[4] && stringMatch[2] === undefined) { + throw new Error('' + string + ' not a valid Decimal128 string'); + } + + // Get the negative or positive sign + if (string[index] === '+' || string[index] === '-') { + isNegative = string[index++] === '-'; + } + + // Check if user passed Infinity or NaN + if (!isDigit(string[index]) && string[index] !== '.') { + if (string[index] === 'i' || string[index] === 'I') { + return new Decimal128(utils.toBuffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); + } else if (string[index] === 'N') { + return new Decimal128(utils.toBuffer(NAN_BUFFER)); + } + } + + // Read all the digits + while (isDigit(string[index]) || string[index] === '.') { + if (string[index] === '.') { + if (sawRadix) { + return new Decimal128(utils.toBuffer(NAN_BUFFER)); + } + + sawRadix = true; + index = index + 1; + continue; + } + + if (nDigitsStored < 34) { + if (string[index] !== '0' || foundNonZero) { + if (!foundNonZero) { + firstNonZero = nDigitsRead; + } + + foundNonZero = true; + + // Only store 34 digits + digits[digitsInsert++] = parseInt(string[index], 10); + nDigitsStored = nDigitsStored + 1; + } + } + + if (foundNonZero) { + nDigits = nDigits + 1; + } + + if (sawRadix) { + radixPosition = radixPosition + 1; + } + + nDigitsRead = nDigitsRead + 1; + index = index + 1; + } + + if (sawRadix && !nDigitsRead) { + throw new Error('' + string + ' not a valid Decimal128 string'); + } + + // Read exponent if exists + if (string[index] === 'e' || string[index] === 'E') { + // Read exponent digits + var match = string.substr(++index).match(EXPONENT_REGEX); + + // No digits read + if (!match || !match[2]) { + return new Decimal128(utils.toBuffer(NAN_BUFFER)); + } + + // Get exponent + exponent = parseInt(match[0], 10); + + // Adjust the index + index = index + match[0].length; + } + + // Return not a number + if (string[index]) { + return new Decimal128(utils.toBuffer(NAN_BUFFER)); + } + + // Done reading input + // Find first non-zero digit in digits + firstDigit = 0; + + if (!nDigitsStored) { + firstDigit = 0; + lastDigit = 0; + digits[0] = 0; + nDigits = 1; + nDigitsStored = 1; + significantDigits = 0; + } else { + lastDigit = nDigitsStored - 1; + significantDigits = nDigits; + + if (exponent !== 0 && significantDigits !== 1) { + while (string[firstNonZero + significantDigits - 1] === '0') { + significantDigits = significantDigits - 1; + } + } + } + + // Normalization of exponent + // Correct exponent based on radix position, and shift significand as needed + // to represent user input + + // Overflow prevention + if (exponent <= radixPosition && radixPosition - exponent > 1 << 14) { + exponent = EXPONENT_MIN; + } else { + exponent = exponent - radixPosition; + } + + // Attempt to normalize the exponent + while (exponent > EXPONENT_MAX) { + // Shift exponent to significand and decrease + lastDigit = lastDigit + 1; + + if (lastDigit - firstDigit > MAX_DIGITS) { + // Check if we have a zero then just hard clamp, otherwise fail + var digitsString = digits.join(''); + if (digitsString.match(/^0+$/)) { + exponent = EXPONENT_MAX; + break; + } else { + return new Decimal128(utils.toBuffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); + } + } + + exponent = exponent - 1; + } + + while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) { + // Shift last digit + if (lastDigit === 0) { + exponent = EXPONENT_MIN; + significantDigits = 0; + break; + } + + if (nDigitsStored < nDigits) { + // adjust to match digits not stored + nDigits = nDigits - 1; + } else { + // adjust to round + lastDigit = lastDigit - 1; + } + + if (exponent < EXPONENT_MAX) { + exponent = exponent + 1; + } else { + // Check if we have a zero then just hard clamp, otherwise fail + digitsString = digits.join(''); + if (digitsString.match(/^0+$/)) { + exponent = EXPONENT_MAX; + break; + } else { + return new Decimal128(utils.toBuffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); + } + } + } + + // Round + // We've normalized the exponent, but might still need to round. + if (lastDigit - firstDigit + 1 < significantDigits && string[significantDigits] !== '0') { + var endOfString = nDigitsRead; + + // If we have seen a radix point, 'string' is 1 longer than we have + // documented with ndigits_read, so inc the position of the first nonzero + // digit and the position that digits are read to. + if (sawRadix && exponent === EXPONENT_MIN) { + firstNonZero = firstNonZero + 1; + endOfString = endOfString + 1; + } + + var roundDigit = parseInt(string[firstNonZero + lastDigit + 1], 10); + var roundBit = 0; + + if (roundDigit >= 5) { + roundBit = 1; + + if (roundDigit === 5) { + roundBit = digits[lastDigit] % 2 === 1; + + for (i = firstNonZero + lastDigit + 2; i < endOfString; i++) { + if (parseInt(string[i], 10)) { + roundBit = 1; + break; + } + } + } + } + + if (roundBit) { + var dIdx = lastDigit; + + for (; dIdx >= 0; dIdx--) { + if (++digits[dIdx] > 9) { + digits[dIdx] = 0; + + // overflowed most significant digit + if (dIdx === 0) { + if (exponent < EXPONENT_MAX) { + exponent = exponent + 1; + digits[dIdx] = 1; + } else { + return new Decimal128( + utils.toBuffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER) + ); + } + } + } else { + break; + } + } + } + } + + // Encode significand + // The high 17 digits of the significand + significandHigh = Long.fromNumber(0); + // The low 17 digits of the significand + significandLow = Long.fromNumber(0); + + // read a zero + if (significantDigits === 0) { + significandHigh = Long.fromNumber(0); + significandLow = Long.fromNumber(0); + } else if (lastDigit - firstDigit < 17) { + dIdx = firstDigit; + significandLow = Long.fromNumber(digits[dIdx++]); + significandHigh = new Long(0, 0); + + for (; dIdx <= lastDigit; dIdx++) { + significandLow = significandLow.multiply(Long.fromNumber(10)); + significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); + } + } else { + dIdx = firstDigit; + significandHigh = Long.fromNumber(digits[dIdx++]); + + for (; dIdx <= lastDigit - 17; dIdx++) { + significandHigh = significandHigh.multiply(Long.fromNumber(10)); + significandHigh = significandHigh.add(Long.fromNumber(digits[dIdx])); + } + + significandLow = Long.fromNumber(digits[dIdx++]); + + for (; dIdx <= lastDigit; dIdx++) { + significandLow = significandLow.multiply(Long.fromNumber(10)); + significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); + } + } + + var significand = multiply64x2(significandHigh, Long.fromString('100000000000000000')); + + significand.low = significand.low.add(significandLow); + + if (lessThan(significand.low, significandLow)) { + significand.high = significand.high.add(Long.fromNumber(1)); + } + + // Biased exponent + biasedExponent = exponent + EXPONENT_BIAS; + var dec = { low: Long.fromNumber(0), high: Long.fromNumber(0) }; + + // Encode combination, exponent, and significand. + if ( + significand.high + .shiftRightUnsigned(49) + .and(Long.fromNumber(1)) + .equals(Long.fromNumber) + ) { + // Encode '11' into bits 1 to 3 + dec.high = dec.high.or(Long.fromNumber(0x3).shiftLeft(61)); + dec.high = dec.high.or( + Long.fromNumber(biasedExponent).and(Long.fromNumber(0x3fff).shiftLeft(47)) + ); + dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x7fffffffffff))); + } else { + dec.high = dec.high.or(Long.fromNumber(biasedExponent & 0x3fff).shiftLeft(49)); + dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x1ffffffffffff))); + } + + dec.low = significand.low; + + // Encode sign + if (isNegative) { + dec.high = dec.high.or(Long.fromString('9223372036854775808')); + } + + // Encode into a buffer + var buffer = utils.allocBuffer(16); + index = 0; + + // Encode the low 64 bits of the decimal + // Encode low bits + buffer[index++] = dec.low.low_ & 0xff; + buffer[index++] = (dec.low.low_ >> 8) & 0xff; + buffer[index++] = (dec.low.low_ >> 16) & 0xff; + buffer[index++] = (dec.low.low_ >> 24) & 0xff; + // Encode high bits + buffer[index++] = dec.low.high_ & 0xff; + buffer[index++] = (dec.low.high_ >> 8) & 0xff; + buffer[index++] = (dec.low.high_ >> 16) & 0xff; + buffer[index++] = (dec.low.high_ >> 24) & 0xff; + + // Encode the high 64 bits of the decimal + // Encode low bits + buffer[index++] = dec.high.low_ & 0xff; + buffer[index++] = (dec.high.low_ >> 8) & 0xff; + buffer[index++] = (dec.high.low_ >> 16) & 0xff; + buffer[index++] = (dec.high.low_ >> 24) & 0xff; + // Encode high bits + buffer[index++] = dec.high.high_ & 0xff; + buffer[index++] = (dec.high.high_ >> 8) & 0xff; + buffer[index++] = (dec.high.high_ >> 16) & 0xff; + buffer[index++] = (dec.high.high_ >> 24) & 0xff; + + // Return the new Decimal128 + return new Decimal128(buffer); +}; + +// Extract least significant 5 bits +var COMBINATION_MASK = 0x1f; +// Extract least significant 14 bits +var EXPONENT_MASK = 0x3fff; +// Value of combination field for Inf +var COMBINATION_INFINITY = 30; +// Value of combination field for NaN +var COMBINATION_NAN = 31; +// Value of combination field for NaN +// var COMBINATION_SNAN = 32; +// decimal128 exponent bias +EXPONENT_BIAS = 6176; + +/** + * Create a string representation of the raw Decimal128 value + * + * @method + * @return {string} returns a Decimal128 string representation. + */ +Decimal128.prototype.toString = function() { + // Note: bits in this routine are referred to starting at 0, + // from the sign bit, towards the coefficient. + + // bits 0 - 31 + var high; + // bits 32 - 63 + var midh; + // bits 64 - 95 + var midl; + // bits 96 - 127 + var low; + // bits 1 - 5 + var combination; + // decoded biased exponent (14 bits) + var biased_exponent; + // the number of significand digits + var significand_digits = 0; + // the base-10 digits in the significand + var significand = new Array(36); + for (var i = 0; i < significand.length; i++) significand[i] = 0; + // read pointer into significand + var index = 0; + + // unbiased exponent + var exponent; + // the exponent if scientific notation is used + var scientific_exponent; + + // true if the number is zero + var is_zero = false; + + // the most signifcant significand bits (50-46) + var significand_msb; + // temporary storage for significand decoding + var significand128 = { parts: new Array(4) }; + // indexing variables + i; + var j, k; + + // Output string + var string = []; + + // Unpack index + index = 0; + + // Buffer reference + var buffer = this.bytes; + + // Unpack the low 64bits into a long + low = + buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + midl = + buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + + // Unpack the high 64bits into a long + midh = + buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + high = + buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + + // Unpack index + index = 0; + + // Create the state of the decimal + var dec = { + low: new Long(low, midl), + high: new Long(midh, high) + }; + + if (dec.high.lessThan(Long.ZERO)) { + string.push('-'); + } + + // Decode combination field and exponent + combination = (high >> 26) & COMBINATION_MASK; + + if (combination >> 3 === 3) { + // Check for 'special' values + if (combination === COMBINATION_INFINITY) { + return string.join('') + 'Infinity'; + } else if (combination === COMBINATION_NAN) { + return 'NaN'; + } else { + biased_exponent = (high >> 15) & EXPONENT_MASK; + significand_msb = 0x08 + ((high >> 14) & 0x01); + } + } else { + significand_msb = (high >> 14) & 0x07; + biased_exponent = (high >> 17) & EXPONENT_MASK; + } + + exponent = biased_exponent - EXPONENT_BIAS; + + // Create string of significand digits + + // Convert the 114-bit binary number represented by + // (significand_high, significand_low) to at most 34 decimal + // digits through modulo and division. + significand128.parts[0] = (high & 0x3fff) + ((significand_msb & 0xf) << 14); + significand128.parts[1] = midh; + significand128.parts[2] = midl; + significand128.parts[3] = low; + + if ( + significand128.parts[0] === 0 && + significand128.parts[1] === 0 && + significand128.parts[2] === 0 && + significand128.parts[3] === 0 + ) { + is_zero = true; + } else { + for (k = 3; k >= 0; k--) { + var least_digits = 0; + // Peform the divide + var result = divideu128(significand128); + significand128 = result.quotient; + least_digits = result.rem.low_; + + // We now have the 9 least significant digits (in base 2). + // Convert and output to string. + if (!least_digits) continue; + + for (j = 8; j >= 0; j--) { + // significand[k * 9 + j] = Math.round(least_digits % 10); + significand[k * 9 + j] = least_digits % 10; + // least_digits = Math.round(least_digits / 10); + least_digits = Math.floor(least_digits / 10); + } + } + } + + // Output format options: + // Scientific - [-]d.dddE(+/-)dd or [-]dE(+/-)dd + // Regular - ddd.ddd + + if (is_zero) { + significand_digits = 1; + significand[index] = 0; + } else { + significand_digits = 36; + i = 0; + + while (!significand[index]) { + i++; + significand_digits = significand_digits - 1; + index = index + 1; + } + } + + scientific_exponent = significand_digits - 1 + exponent; + + // The scientific exponent checks are dictated by the string conversion + // specification and are somewhat arbitrary cutoffs. + // + // We must check exponent > 0, because if this is the case, the number + // has trailing zeros. However, we *cannot* output these trailing zeros, + // because doing so would change the precision of the value, and would + // change stored data if the string converted number is round tripped. + + if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) { + // Scientific format + string.push(significand[index++]); + significand_digits = significand_digits - 1; + + if (significand_digits) { + string.push('.'); + } + + for (i = 0; i < significand_digits; i++) { + string.push(significand[index++]); + } + + // Exponent + string.push('E'); + if (scientific_exponent > 0) { + string.push('+' + scientific_exponent); + } else { + string.push(scientific_exponent); + } + } else { + // Regular format with no decimal place + if (exponent >= 0) { + for (i = 0; i < significand_digits; i++) { + string.push(significand[index++]); + } + } else { + var radix_position = significand_digits + exponent; + + // non-zero digits before radix + if (radix_position > 0) { + for (i = 0; i < radix_position; i++) { + string.push(significand[index++]); + } + } else { + string.push('0'); + } + + string.push('.'); + // add leading zeros after radix + while (radix_position++ < 0) { + string.push('0'); + } + + for (i = 0; i < significand_digits - Math.max(radix_position - 1, 0); i++) { + string.push(significand[index++]); + } + } + } + + return string.join(''); +}; + +Decimal128.prototype.toJSON = function() { + return { $numberDecimal: this.toString() }; +}; + +module.exports = Decimal128; +module.exports.Decimal128 = Decimal128; diff --git a/scripts/node_modules/bson/lib/bson/double.js b/scripts/node_modules/bson/lib/bson/double.js new file mode 100644 index 00000000..523c21f8 --- /dev/null +++ b/scripts/node_modules/bson/lib/bson/double.js @@ -0,0 +1,33 @@ +/** + * A class representation of the BSON Double type. + * + * @class + * @param {number} value the number we want to represent as a double. + * @return {Double} + */ +function Double(value) { + if (!(this instanceof Double)) return new Double(value); + + this._bsontype = 'Double'; + this.value = value; +} + +/** + * Access the number value. + * + * @method + * @return {number} returns the wrapped double number. + */ +Double.prototype.valueOf = function() { + return this.value; +}; + +/** + * @ignore + */ +Double.prototype.toJSON = function() { + return this.value; +}; + +module.exports = Double; +module.exports.Double = Double; diff --git a/scripts/node_modules/bson/lib/bson/float_parser.js b/scripts/node_modules/bson/lib/bson/float_parser.js new file mode 100644 index 00000000..0054a2f6 --- /dev/null +++ b/scripts/node_modules/bson/lib/bson/float_parser.js @@ -0,0 +1,124 @@ +// Copyright (c) 2008, Fair Oaks Labs, Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * Neither the name of Fair Oaks Labs, Inc. nor the names of its contributors +// may be used to endorse or promote products derived from this software +// without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// +// +// Modifications to writeIEEE754 to support negative zeroes made by Brian White + +var readIEEE754 = function(buffer, offset, endian, mLen, nBytes) { + var e, + m, + bBE = endian === 'big', + eLen = nBytes * 8 - mLen - 1, + eMax = (1 << eLen) - 1, + eBias = eMax >> 1, + nBits = -7, + i = bBE ? 0 : nBytes - 1, + d = bBE ? 1 : -1, + s = buffer[offset + i]; + + i += d; + + e = s & ((1 << -nBits) - 1); + s >>= -nBits; + nBits += eLen; + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8); + + m = e & ((1 << -nBits) - 1); + e >>= -nBits; + nBits += mLen; + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8); + + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : (s ? -1 : 1) * Infinity; + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen); +}; + +var writeIEEE754 = function(buffer, value, offset, endian, mLen, nBytes) { + var e, + m, + c, + bBE = endian === 'big', + eLen = nBytes * 8 - mLen - 1, + eMax = (1 << eLen) - 1, + eBias = eMax >> 1, + rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0, + i = bBE ? nBytes - 1 : 0, + d = bBE ? -1 : 1, + s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; + + value = Math.abs(value); + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8); + + e = (e << mLen) | m; + eLen += mLen; + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8); + + buffer[offset + i - d] |= s * 128; +}; + +exports.readIEEE754 = readIEEE754; +exports.writeIEEE754 = writeIEEE754; diff --git a/scripts/node_modules/bson/lib/bson/int_32.js b/scripts/node_modules/bson/lib/bson/int_32.js new file mode 100644 index 00000000..85dbdec6 --- /dev/null +++ b/scripts/node_modules/bson/lib/bson/int_32.js @@ -0,0 +1,33 @@ +/** + * A class representation of a BSON Int32 type. + * + * @class + * @param {number} value the number we want to represent as an int32. + * @return {Int32} + */ +var Int32 = function(value) { + if (!(this instanceof Int32)) return new Int32(value); + + this._bsontype = 'Int32'; + this.value = value; +}; + +/** + * Access the number value. + * + * @method + * @return {number} returns the wrapped int32 number. + */ +Int32.prototype.valueOf = function() { + return this.value; +}; + +/** + * @ignore + */ +Int32.prototype.toJSON = function() { + return this.value; +}; + +module.exports = Int32; +module.exports.Int32 = Int32; diff --git a/scripts/node_modules/bson/lib/bson/long.js b/scripts/node_modules/bson/lib/bson/long.js new file mode 100644 index 00000000..78215aa3 --- /dev/null +++ b/scripts/node_modules/bson/lib/bson/long.js @@ -0,0 +1,851 @@ +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Copyright 2009 Google Inc. All Rights Reserved + +/** + * Defines a Long class for representing a 64-bit two's-complement + * integer value, which faithfully simulates the behavior of a Java "Long". This + * implementation is derived from LongLib in GWT. + * + * Constructs a 64-bit two's-complement integer, given its low and high 32-bit + * values as *signed* integers. See the from* functions below for more + * convenient ways of constructing Longs. + * + * The internal representation of a Long is the two given signed, 32-bit values. + * We use 32-bit pieces because these are the size of integers on which + * Javascript performs bit-operations. For operations like addition and + * multiplication, we split each number into 16-bit pieces, which can easily be + * multiplied within Javascript's floating-point representation without overflow + * or change in sign. + * + * In the algorithms below, we frequently reduce the negative case to the + * positive case by negating the input(s) and then post-processing the result. + * Note that we must ALWAYS check specially whether those values are MIN_VALUE + * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as + * a positive number, it overflows back into a negative). Not handling this + * case would often result in infinite recursion. + * + * @class + * @param {number} low the low (signed) 32 bits of the Long. + * @param {number} high the high (signed) 32 bits of the Long. + * @return {Long} + */ +function Long(low, high) { + if (!(this instanceof Long)) return new Long(low, high); + + this._bsontype = 'Long'; + /** + * @type {number} + * @ignore + */ + this.low_ = low | 0; // force into 32 signed bits. + + /** + * @type {number} + * @ignore + */ + this.high_ = high | 0; // force into 32 signed bits. +} + +/** + * Return the int value. + * + * @method + * @return {number} the value, assuming it is a 32-bit integer. + */ +Long.prototype.toInt = function() { + return this.low_; +}; + +/** + * Return the Number value. + * + * @method + * @return {number} the closest floating-point representation to this value. + */ +Long.prototype.toNumber = function() { + return this.high_ * Long.TWO_PWR_32_DBL_ + this.getLowBitsUnsigned(); +}; + +/** + * Return the JSON value. + * + * @method + * @return {string} the JSON representation. + */ +Long.prototype.toJSON = function() { + return this.toString(); +}; + +/** + * Return the String value. + * + * @method + * @param {number} [opt_radix] the radix in which the text should be written. + * @return {string} the textual representation of this value. + */ +Long.prototype.toString = function(opt_radix) { + var radix = opt_radix || 10; + if (radix < 2 || 36 < radix) { + throw Error('radix out of range: ' + radix); + } + + if (this.isZero()) { + return '0'; + } + + if (this.isNegative()) { + if (this.equals(Long.MIN_VALUE)) { + // We need to change the Long value before it can be negated, so we remove + // the bottom-most digit in this base and then recurse to do the rest. + var radixLong = Long.fromNumber(radix); + var div = this.div(radixLong); + var rem = div.multiply(radixLong).subtract(this); + return div.toString(radix) + rem.toInt().toString(radix); + } else { + return '-' + this.negate().toString(radix); + } + } + + // Do several (6) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = Long.fromNumber(Math.pow(radix, 6)); + + rem = this; + var result = ''; + + while (!rem.isZero()) { + var remDiv = rem.div(radixToPower); + var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); + var digits = intval.toString(radix); + + rem = remDiv; + if (rem.isZero()) { + return digits + result; + } else { + while (digits.length < 6) { + digits = '0' + digits; + } + result = '' + digits + result; + } + } +}; + +/** + * Return the high 32-bits value. + * + * @method + * @return {number} the high 32-bits as a signed value. + */ +Long.prototype.getHighBits = function() { + return this.high_; +}; + +/** + * Return the low 32-bits value. + * + * @method + * @return {number} the low 32-bits as a signed value. + */ +Long.prototype.getLowBits = function() { + return this.low_; +}; + +/** + * Return the low unsigned 32-bits value. + * + * @method + * @return {number} the low 32-bits as an unsigned value. + */ +Long.prototype.getLowBitsUnsigned = function() { + return this.low_ >= 0 ? this.low_ : Long.TWO_PWR_32_DBL_ + this.low_; +}; + +/** + * Returns the number of bits needed to represent the absolute value of this Long. + * + * @method + * @return {number} Returns the number of bits needed to represent the absolute value of this Long. + */ +Long.prototype.getNumBitsAbs = function() { + if (this.isNegative()) { + if (this.equals(Long.MIN_VALUE)) { + return 64; + } else { + return this.negate().getNumBitsAbs(); + } + } else { + var val = this.high_ !== 0 ? this.high_ : this.low_; + for (var bit = 31; bit > 0; bit--) { + if ((val & (1 << bit)) !== 0) { + break; + } + } + return this.high_ !== 0 ? bit + 33 : bit + 1; + } +}; + +/** + * Return whether this value is zero. + * + * @method + * @return {boolean} whether this value is zero. + */ +Long.prototype.isZero = function() { + return this.high_ === 0 && this.low_ === 0; +}; + +/** + * Return whether this value is negative. + * + * @method + * @return {boolean} whether this value is negative. + */ +Long.prototype.isNegative = function() { + return this.high_ < 0; +}; + +/** + * Return whether this value is odd. + * + * @method + * @return {boolean} whether this value is odd. + */ +Long.prototype.isOdd = function() { + return (this.low_ & 1) === 1; +}; + +/** + * Return whether this Long equals the other + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long equals the other + */ +Long.prototype.equals = function(other) { + return this.high_ === other.high_ && this.low_ === other.low_; +}; + +/** + * Return whether this Long does not equal the other. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long does not equal the other. + */ +Long.prototype.notEquals = function(other) { + return this.high_ !== other.high_ || this.low_ !== other.low_; +}; + +/** + * Return whether this Long is less than the other. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long is less than the other. + */ +Long.prototype.lessThan = function(other) { + return this.compare(other) < 0; +}; + +/** + * Return whether this Long is less than or equal to the other. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long is less than or equal to the other. + */ +Long.prototype.lessThanOrEqual = function(other) { + return this.compare(other) <= 0; +}; + +/** + * Return whether this Long is greater than the other. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long is greater than the other. + */ +Long.prototype.greaterThan = function(other) { + return this.compare(other) > 0; +}; + +/** + * Return whether this Long is greater than or equal to the other. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long is greater than or equal to the other. + */ +Long.prototype.greaterThanOrEqual = function(other) { + return this.compare(other) >= 0; +}; + +/** + * Compares this Long with the given one. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. + */ +Long.prototype.compare = function(other) { + if (this.equals(other)) { + return 0; + } + + var thisNeg = this.isNegative(); + var otherNeg = other.isNegative(); + if (thisNeg && !otherNeg) { + return -1; + } + if (!thisNeg && otherNeg) { + return 1; + } + + // at this point, the signs are the same, so subtraction will not overflow + if (this.subtract(other).isNegative()) { + return -1; + } else { + return 1; + } +}; + +/** + * The negation of this value. + * + * @method + * @return {Long} the negation of this value. + */ +Long.prototype.negate = function() { + if (this.equals(Long.MIN_VALUE)) { + return Long.MIN_VALUE; + } else { + return this.not().add(Long.ONE); + } +}; + +/** + * Returns the sum of this and the given Long. + * + * @method + * @param {Long} other Long to add to this one. + * @return {Long} the sum of this and the given Long. + */ +Long.prototype.add = function(other) { + // Divide each number into 4 chunks of 16 bits, and then sum the chunks. + + var a48 = this.high_ >>> 16; + var a32 = this.high_ & 0xffff; + var a16 = this.low_ >>> 16; + var a00 = this.low_ & 0xffff; + + var b48 = other.high_ >>> 16; + var b32 = other.high_ & 0xffff; + var b16 = other.low_ >>> 16; + var b00 = other.low_ & 0xffff; + + var c48 = 0, + c32 = 0, + c16 = 0, + c00 = 0; + c00 += a00 + b00; + c16 += c00 >>> 16; + c00 &= 0xffff; + c16 += a16 + b16; + c32 += c16 >>> 16; + c16 &= 0xffff; + c32 += a32 + b32; + c48 += c32 >>> 16; + c32 &= 0xffff; + c48 += a48 + b48; + c48 &= 0xffff; + return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32); +}; + +/** + * Returns the difference of this and the given Long. + * + * @method + * @param {Long} other Long to subtract from this. + * @return {Long} the difference of this and the given Long. + */ +Long.prototype.subtract = function(other) { + return this.add(other.negate()); +}; + +/** + * Returns the product of this and the given Long. + * + * @method + * @param {Long} other Long to multiply with this. + * @return {Long} the product of this and the other. + */ +Long.prototype.multiply = function(other) { + if (this.isZero()) { + return Long.ZERO; + } else if (other.isZero()) { + return Long.ZERO; + } + + if (this.equals(Long.MIN_VALUE)) { + return other.isOdd() ? Long.MIN_VALUE : Long.ZERO; + } else if (other.equals(Long.MIN_VALUE)) { + return this.isOdd() ? Long.MIN_VALUE : Long.ZERO; + } + + if (this.isNegative()) { + if (other.isNegative()) { + return this.negate().multiply(other.negate()); + } else { + return this.negate() + .multiply(other) + .negate(); + } + } else if (other.isNegative()) { + return this.multiply(other.negate()).negate(); + } + + // If both Longs are small, use float multiplication + if (this.lessThan(Long.TWO_PWR_24_) && other.lessThan(Long.TWO_PWR_24_)) { + return Long.fromNumber(this.toNumber() * other.toNumber()); + } + + // Divide each Long into 4 chunks of 16 bits, and then add up 4x4 products. + // We can skip products that would overflow. + + var a48 = this.high_ >>> 16; + var a32 = this.high_ & 0xffff; + var a16 = this.low_ >>> 16; + var a00 = this.low_ & 0xffff; + + var b48 = other.high_ >>> 16; + var b32 = other.high_ & 0xffff; + var b16 = other.low_ >>> 16; + var b00 = other.low_ & 0xffff; + + var c48 = 0, + c32 = 0, + c16 = 0, + c00 = 0; + c00 += a00 * b00; + c16 += c00 >>> 16; + c00 &= 0xffff; + c16 += a16 * b00; + c32 += c16 >>> 16; + c16 &= 0xffff; + c16 += a00 * b16; + c32 += c16 >>> 16; + c16 &= 0xffff; + c32 += a32 * b00; + c48 += c32 >>> 16; + c32 &= 0xffff; + c32 += a16 * b16; + c48 += c32 >>> 16; + c32 &= 0xffff; + c32 += a00 * b32; + c48 += c32 >>> 16; + c32 &= 0xffff; + c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; + c48 &= 0xffff; + return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32); +}; + +/** + * Returns this Long divided by the given one. + * + * @method + * @param {Long} other Long by which to divide. + * @return {Long} this Long divided by the given one. + */ +Long.prototype.div = function(other) { + if (other.isZero()) { + throw Error('division by zero'); + } else if (this.isZero()) { + return Long.ZERO; + } + + if (this.equals(Long.MIN_VALUE)) { + if (other.equals(Long.ONE) || other.equals(Long.NEG_ONE)) { + return Long.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE + } else if (other.equals(Long.MIN_VALUE)) { + return Long.ONE; + } else { + // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. + var halfThis = this.shiftRight(1); + var approx = halfThis.div(other).shiftLeft(1); + if (approx.equals(Long.ZERO)) { + return other.isNegative() ? Long.ONE : Long.NEG_ONE; + } else { + var rem = this.subtract(other.multiply(approx)); + var result = approx.add(rem.div(other)); + return result; + } + } + } else if (other.equals(Long.MIN_VALUE)) { + return Long.ZERO; + } + + if (this.isNegative()) { + if (other.isNegative()) { + return this.negate().div(other.negate()); + } else { + return this.negate() + .div(other) + .negate(); + } + } else if (other.isNegative()) { + return this.div(other.negate()).negate(); + } + + // Repeat the following until the remainder is less than other: find a + // floating-point that approximates remainder / other *from below*, add this + // into the result, and subtract it from the remainder. It is critical that + // the approximate value is less than or equal to the real value so that the + // remainder never becomes negative. + var res = Long.ZERO; + rem = this; + while (rem.greaterThanOrEqual(other)) { + // Approximate the result of division. This may be a little greater or + // smaller than the actual value. + approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); + + // We will tweak the approximate result by changing it in the 48-th digit or + // the smallest non-fractional digit, whichever is larger. + var log2 = Math.ceil(Math.log(approx) / Math.LN2); + var delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48); + + // Decrease the approximation until it is smaller than the remainder. Note + // that if it is too large, the product overflows and is negative. + var approxRes = Long.fromNumber(approx); + var approxRem = approxRes.multiply(other); + while (approxRem.isNegative() || approxRem.greaterThan(rem)) { + approx -= delta; + approxRes = Long.fromNumber(approx); + approxRem = approxRes.multiply(other); + } + + // We know the answer can't be zero... and actually, zero would cause + // infinite recursion since we would make no progress. + if (approxRes.isZero()) { + approxRes = Long.ONE; + } + + res = res.add(approxRes); + rem = rem.subtract(approxRem); + } + return res; +}; + +/** + * Returns this Long modulo the given one. + * + * @method + * @param {Long} other Long by which to mod. + * @return {Long} this Long modulo the given one. + */ +Long.prototype.modulo = function(other) { + return this.subtract(this.div(other).multiply(other)); +}; + +/** + * The bitwise-NOT of this value. + * + * @method + * @return {Long} the bitwise-NOT of this value. + */ +Long.prototype.not = function() { + return Long.fromBits(~this.low_, ~this.high_); +}; + +/** + * Returns the bitwise-AND of this Long and the given one. + * + * @method + * @param {Long} other the Long with which to AND. + * @return {Long} the bitwise-AND of this and the other. + */ +Long.prototype.and = function(other) { + return Long.fromBits(this.low_ & other.low_, this.high_ & other.high_); +}; + +/** + * Returns the bitwise-OR of this Long and the given one. + * + * @method + * @param {Long} other the Long with which to OR. + * @return {Long} the bitwise-OR of this and the other. + */ +Long.prototype.or = function(other) { + return Long.fromBits(this.low_ | other.low_, this.high_ | other.high_); +}; + +/** + * Returns the bitwise-XOR of this Long and the given one. + * + * @method + * @param {Long} other the Long with which to XOR. + * @return {Long} the bitwise-XOR of this and the other. + */ +Long.prototype.xor = function(other) { + return Long.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); +}; + +/** + * Returns this Long with bits shifted to the left by the given amount. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Long} this shifted to the left by the given amount. + */ +Long.prototype.shiftLeft = function(numBits) { + numBits &= 63; + if (numBits === 0) { + return this; + } else { + var low = this.low_; + if (numBits < 32) { + var high = this.high_; + return Long.fromBits(low << numBits, (high << numBits) | (low >>> (32 - numBits))); + } else { + return Long.fromBits(0, low << (numBits - 32)); + } + } +}; + +/** + * Returns this Long with bits shifted to the right by the given amount. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Long} this shifted to the right by the given amount. + */ +Long.prototype.shiftRight = function(numBits) { + numBits &= 63; + if (numBits === 0) { + return this; + } else { + var high = this.high_; + if (numBits < 32) { + var low = this.low_; + return Long.fromBits((low >>> numBits) | (high << (32 - numBits)), high >> numBits); + } else { + return Long.fromBits(high >> (numBits - 32), high >= 0 ? 0 : -1); + } + } +}; + +/** + * Returns this Long with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Long} this shifted to the right by the given amount, with zeros placed into the new leading bits. + */ +Long.prototype.shiftRightUnsigned = function(numBits) { + numBits &= 63; + if (numBits === 0) { + return this; + } else { + var high = this.high_; + if (numBits < 32) { + var low = this.low_; + return Long.fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits); + } else if (numBits === 32) { + return Long.fromBits(high, 0); + } else { + return Long.fromBits(high >>> (numBits - 32), 0); + } + } +}; + +/** + * Returns a Long representing the given (32-bit) integer value. + * + * @method + * @param {number} value the 32-bit integer in question. + * @return {Long} the corresponding Long value. + */ +Long.fromInt = function(value) { + if (-128 <= value && value < 128) { + var cachedObj = Long.INT_CACHE_[value]; + if (cachedObj) { + return cachedObj; + } + } + + var obj = new Long(value | 0, value < 0 ? -1 : 0); + if (-128 <= value && value < 128) { + Long.INT_CACHE_[value] = obj; + } + return obj; +}; + +/** + * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. + * + * @method + * @param {number} value the number in question. + * @return {Long} the corresponding Long value. + */ +Long.fromNumber = function(value) { + if (isNaN(value) || !isFinite(value)) { + return Long.ZERO; + } else if (value <= -Long.TWO_PWR_63_DBL_) { + return Long.MIN_VALUE; + } else if (value + 1 >= Long.TWO_PWR_63_DBL_) { + return Long.MAX_VALUE; + } else if (value < 0) { + return Long.fromNumber(-value).negate(); + } else { + return new Long((value % Long.TWO_PWR_32_DBL_) | 0, (value / Long.TWO_PWR_32_DBL_) | 0); + } +}; + +/** + * Returns a Long representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. + * + * @method + * @param {number} lowBits the low 32-bits. + * @param {number} highBits the high 32-bits. + * @return {Long} the corresponding Long value. + */ +Long.fromBits = function(lowBits, highBits) { + return new Long(lowBits, highBits); +}; + +/** + * Returns a Long representation of the given string, written using the given radix. + * + * @method + * @param {string} str the textual representation of the Long. + * @param {number} opt_radix the radix in which the text is written. + * @return {Long} the corresponding Long value. + */ +Long.fromString = function(str, opt_radix) { + if (str.length === 0) { + throw Error('number format error: empty string'); + } + + var radix = opt_radix || 10; + if (radix < 2 || 36 < radix) { + throw Error('radix out of range: ' + radix); + } + + if (str.charAt(0) === '-') { + return Long.fromString(str.substring(1), radix).negate(); + } else if (str.indexOf('-') >= 0) { + throw Error('number format error: interior "-" character: ' + str); + } + + // Do several (8) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = Long.fromNumber(Math.pow(radix, 8)); + + var result = Long.ZERO; + for (var i = 0; i < str.length; i += 8) { + var size = Math.min(8, str.length - i); + var value = parseInt(str.substring(i, i + size), radix); + if (size < 8) { + var power = Long.fromNumber(Math.pow(radix, size)); + result = result.multiply(power).add(Long.fromNumber(value)); + } else { + result = result.multiply(radixToPower); + result = result.add(Long.fromNumber(value)); + } + } + return result; +}; + +// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the +// from* methods on which they depend. + +/** + * A cache of the Long representations of small integer values. + * @type {Object} + * @ignore + */ +Long.INT_CACHE_ = {}; + +// NOTE: the compiler should inline these constant values below and then remove +// these variables, so there should be no runtime penalty for these. + +/** + * Number used repeated below in calculations. This must appear before the + * first call to any from* function below. + * @type {number} + * @ignore + */ +Long.TWO_PWR_16_DBL_ = 1 << 16; + +/** + * @type {number} + * @ignore + */ +Long.TWO_PWR_24_DBL_ = 1 << 24; + +/** + * @type {number} + * @ignore + */ +Long.TWO_PWR_32_DBL_ = Long.TWO_PWR_16_DBL_ * Long.TWO_PWR_16_DBL_; + +/** + * @type {number} + * @ignore + */ +Long.TWO_PWR_31_DBL_ = Long.TWO_PWR_32_DBL_ / 2; + +/** + * @type {number} + * @ignore + */ +Long.TWO_PWR_48_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_16_DBL_; + +/** + * @type {number} + * @ignore + */ +Long.TWO_PWR_64_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_32_DBL_; + +/** + * @type {number} + * @ignore + */ +Long.TWO_PWR_63_DBL_ = Long.TWO_PWR_64_DBL_ / 2; + +/** @type {Long} */ +Long.ZERO = Long.fromInt(0); + +/** @type {Long} */ +Long.ONE = Long.fromInt(1); + +/** @type {Long} */ +Long.NEG_ONE = Long.fromInt(-1); + +/** @type {Long} */ +Long.MAX_VALUE = Long.fromBits(0xffffffff | 0, 0x7fffffff | 0); + +/** @type {Long} */ +Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0); + +/** + * @type {Long} + * @ignore + */ +Long.TWO_PWR_24_ = Long.fromInt(1 << 24); + +/** + * Expose. + */ +module.exports = Long; +module.exports.Long = Long; diff --git a/scripts/node_modules/bson/lib/bson/map.js b/scripts/node_modules/bson/lib/bson/map.js new file mode 100644 index 00000000..7edb4f2a --- /dev/null +++ b/scripts/node_modules/bson/lib/bson/map.js @@ -0,0 +1,128 @@ +'use strict'; + +// We have an ES6 Map available, return the native instance +if (typeof global.Map !== 'undefined') { + module.exports = global.Map; + module.exports.Map = global.Map; +} else { + // We will return a polyfill + var Map = function(array) { + this._keys = []; + this._values = {}; + + for (var i = 0; i < array.length; i++) { + if (array[i] == null) continue; // skip null and undefined + var entry = array[i]; + var key = entry[0]; + var value = entry[1]; + // Add the key to the list of keys in order + this._keys.push(key); + // Add the key and value to the values dictionary with a point + // to the location in the ordered keys list + this._values[key] = { v: value, i: this._keys.length - 1 }; + } + }; + + Map.prototype.clear = function() { + this._keys = []; + this._values = {}; + }; + + Map.prototype.delete = function(key) { + var value = this._values[key]; + if (value == null) return false; + // Delete entry + delete this._values[key]; + // Remove the key from the ordered keys list + this._keys.splice(value.i, 1); + return true; + }; + + Map.prototype.entries = function() { + var self = this; + var index = 0; + + return { + next: function() { + var key = self._keys[index++]; + return { + value: key !== undefined ? [key, self._values[key].v] : undefined, + done: key !== undefined ? false : true + }; + } + }; + }; + + Map.prototype.forEach = function(callback, self) { + self = self || this; + + for (var i = 0; i < this._keys.length; i++) { + var key = this._keys[i]; + // Call the forEach callback + callback.call(self, this._values[key].v, key, self); + } + }; + + Map.prototype.get = function(key) { + return this._values[key] ? this._values[key].v : undefined; + }; + + Map.prototype.has = function(key) { + return this._values[key] != null; + }; + + Map.prototype.keys = function() { + var self = this; + var index = 0; + + return { + next: function() { + var key = self._keys[index++]; + return { + value: key !== undefined ? key : undefined, + done: key !== undefined ? false : true + }; + } + }; + }; + + Map.prototype.set = function(key, value) { + if (this._values[key]) { + this._values[key].v = value; + return this; + } + + // Add the key to the list of keys in order + this._keys.push(key); + // Add the key and value to the values dictionary with a point + // to the location in the ordered keys list + this._values[key] = { v: value, i: this._keys.length - 1 }; + return this; + }; + + Map.prototype.values = function() { + var self = this; + var index = 0; + + return { + next: function() { + var key = self._keys[index++]; + return { + value: key !== undefined ? self._values[key].v : undefined, + done: key !== undefined ? false : true + }; + } + }; + }; + + // Last ismaster + Object.defineProperty(Map.prototype, 'size', { + enumerable: true, + get: function() { + return this._keys.length; + } + }); + + module.exports = Map; + module.exports.Map = Map; +} diff --git a/scripts/node_modules/bson/lib/bson/max_key.js b/scripts/node_modules/bson/lib/bson/max_key.js new file mode 100644 index 00000000..eebca7bc --- /dev/null +++ b/scripts/node_modules/bson/lib/bson/max_key.js @@ -0,0 +1,14 @@ +/** + * A class representation of the BSON MaxKey type. + * + * @class + * @return {MaxKey} A MaxKey instance + */ +function MaxKey() { + if (!(this instanceof MaxKey)) return new MaxKey(); + + this._bsontype = 'MaxKey'; +} + +module.exports = MaxKey; +module.exports.MaxKey = MaxKey; diff --git a/scripts/node_modules/bson/lib/bson/min_key.js b/scripts/node_modules/bson/lib/bson/min_key.js new file mode 100644 index 00000000..15f45228 --- /dev/null +++ b/scripts/node_modules/bson/lib/bson/min_key.js @@ -0,0 +1,14 @@ +/** + * A class representation of the BSON MinKey type. + * + * @class + * @return {MinKey} A MinKey instance + */ +function MinKey() { + if (!(this instanceof MinKey)) return new MinKey(); + + this._bsontype = 'MinKey'; +} + +module.exports = MinKey; +module.exports.MinKey = MinKey; diff --git a/scripts/node_modules/bson/lib/bson/objectid.js b/scripts/node_modules/bson/lib/bson/objectid.js new file mode 100644 index 00000000..79de40d2 --- /dev/null +++ b/scripts/node_modules/bson/lib/bson/objectid.js @@ -0,0 +1,389 @@ +// Custom inspect property name / symbol. +var inspect = 'inspect'; + +var utils = require('./parser/utils'); + +/** + * Machine id. + * + * Create a random 3-byte value (i.e. unique for this + * process). Other drivers use a md5 of the machine id here, but + * that would mean an asyc call to gethostname, so we don't bother. + * @ignore + */ +var MACHINE_ID = parseInt(Math.random() * 0xffffff, 10); + +// Regular expression that checks for hex value +var checkForHexRegExp = new RegExp('^[0-9a-fA-F]{24}$'); + +// Check if buffer exists +try { + if (Buffer && Buffer.from) { + var hasBufferType = true; + inspect = require('util').inspect.custom || 'inspect'; + } +} catch (err) { + hasBufferType = false; +} + +/** +* Create a new ObjectID instance +* +* @class +* @param {(string|number)} id Can be a 24 byte hex string, 12 byte binary string or a Number. +* @property {number} generationTime The generation time of this ObjectId instance +* @return {ObjectID} instance of ObjectID. +*/ +var ObjectID = function ObjectID(id) { + // Duck-typing to support ObjectId from different npm packages + if (id instanceof ObjectID) return id; + if (!(this instanceof ObjectID)) return new ObjectID(id); + + this._bsontype = 'ObjectID'; + + // The most common usecase (blank id, new objectId instance) + if (id == null || typeof id === 'number') { + // Generate a new id + this.id = this.generate(id); + // If we are caching the hex string + if (ObjectID.cacheHexString) this.__id = this.toString('hex'); + // Return the object + return; + } + + // Check if the passed in id is valid + var valid = ObjectID.isValid(id); + + // Throw an error if it's not a valid setup + if (!valid && id != null) { + throw new Error( + 'Argument passed in must be a single String of 12 bytes or a string of 24 hex characters' + ); + } else if (valid && typeof id === 'string' && id.length === 24 && hasBufferType) { + return new ObjectID(utils.toBuffer(id, 'hex')); + } else if (valid && typeof id === 'string' && id.length === 24) { + return ObjectID.createFromHexString(id); + } else if (id != null && id.length === 12) { + // assume 12 byte string + this.id = id; + } else if (id != null && id.toHexString) { + // Duck-typing to support ObjectId from different npm packages + return id; + } else { + throw new Error( + 'Argument passed in must be a single String of 12 bytes or a string of 24 hex characters' + ); + } + + if (ObjectID.cacheHexString) this.__id = this.toString('hex'); +}; + +// Allow usage of ObjectId as well as ObjectID +// var ObjectId = ObjectID; + +// Precomputed hex table enables speedy hex string conversion +var hexTable = []; +for (var i = 0; i < 256; i++) { + hexTable[i] = (i <= 15 ? '0' : '') + i.toString(16); +} + +/** +* Return the ObjectID id as a 24 byte hex string representation +* +* @method +* @return {string} return the 24 byte hex string representation. +*/ +ObjectID.prototype.toHexString = function() { + if (ObjectID.cacheHexString && this.__id) return this.__id; + + var hexString = ''; + if (!this.id || !this.id.length) { + throw new Error( + 'invalid ObjectId, ObjectId.id must be either a string or a Buffer, but is [' + + JSON.stringify(this.id) + + ']' + ); + } + + if (this.id instanceof _Buffer) { + hexString = convertToHex(this.id); + if (ObjectID.cacheHexString) this.__id = hexString; + return hexString; + } + + for (var i = 0; i < this.id.length; i++) { + hexString += hexTable[this.id.charCodeAt(i)]; + } + + if (ObjectID.cacheHexString) this.__id = hexString; + return hexString; +}; + +/** +* Update the ObjectID index used in generating new ObjectID's on the driver +* +* @method +* @return {number} returns next index value. +* @ignore +*/ +ObjectID.prototype.get_inc = function() { + return (ObjectID.index = (ObjectID.index + 1) % 0xffffff); +}; + +/** +* Update the ObjectID index used in generating new ObjectID's on the driver +* +* @method +* @return {number} returns next index value. +* @ignore +*/ +ObjectID.prototype.getInc = function() { + return this.get_inc(); +}; + +/** +* Generate a 12 byte id buffer used in ObjectID's +* +* @method +* @param {number} [time] optional parameter allowing to pass in a second based timestamp. +* @return {Buffer} return the 12 byte id buffer string. +*/ +ObjectID.prototype.generate = function(time) { + if ('number' !== typeof time) { + time = ~~(Date.now() / 1000); + } + + // Use pid + var pid = + (typeof process === 'undefined' || process.pid === 1 + ? Math.floor(Math.random() * 100000) + : process.pid) % 0xffff; + var inc = this.get_inc(); + // Buffer used + var buffer = utils.allocBuffer(12); + // Encode time + buffer[3] = time & 0xff; + buffer[2] = (time >> 8) & 0xff; + buffer[1] = (time >> 16) & 0xff; + buffer[0] = (time >> 24) & 0xff; + // Encode machine + buffer[6] = MACHINE_ID & 0xff; + buffer[5] = (MACHINE_ID >> 8) & 0xff; + buffer[4] = (MACHINE_ID >> 16) & 0xff; + // Encode pid + buffer[8] = pid & 0xff; + buffer[7] = (pid >> 8) & 0xff; + // Encode index + buffer[11] = inc & 0xff; + buffer[10] = (inc >> 8) & 0xff; + buffer[9] = (inc >> 16) & 0xff; + // Return the buffer + return buffer; +}; + +/** +* Converts the id into a 24 byte hex string for printing +* +* @param {String} format The Buffer toString format parameter. +* @return {String} return the 24 byte hex string representation. +* @ignore +*/ +ObjectID.prototype.toString = function(format) { + // Is the id a buffer then use the buffer toString method to return the format + if (this.id && this.id.copy) { + return this.id.toString(typeof format === 'string' ? format : 'hex'); + } + + // if(this.buffer ) + return this.toHexString(); +}; + +/** +* Converts to a string representation of this Id. +* +* @return {String} return the 24 byte hex string representation. +* @ignore +*/ +ObjectID.prototype[inspect] = ObjectID.prototype.toString; + +/** +* Converts to its JSON representation. +* +* @return {String} return the 24 byte hex string representation. +* @ignore +*/ +ObjectID.prototype.toJSON = function() { + return this.toHexString(); +}; + +/** +* Compares the equality of this ObjectID with `otherID`. +* +* @method +* @param {object} otherID ObjectID instance to compare against. +* @return {boolean} the result of comparing two ObjectID's +*/ +ObjectID.prototype.equals = function equals(otherId) { + // var id; + + if (otherId instanceof ObjectID) { + return this.toString() === otherId.toString(); + } else if ( + typeof otherId === 'string' && + ObjectID.isValid(otherId) && + otherId.length === 12 && + this.id instanceof _Buffer + ) { + return otherId === this.id.toString('binary'); + } else if (typeof otherId === 'string' && ObjectID.isValid(otherId) && otherId.length === 24) { + return otherId.toLowerCase() === this.toHexString(); + } else if (typeof otherId === 'string' && ObjectID.isValid(otherId) && otherId.length === 12) { + return otherId === this.id; + } else if (otherId != null && (otherId instanceof ObjectID || otherId.toHexString)) { + return otherId.toHexString() === this.toHexString(); + } else { + return false; + } +}; + +/** +* Returns the generation date (accurate up to the second) that this ID was generated. +* +* @method +* @return {date} the generation date +*/ +ObjectID.prototype.getTimestamp = function() { + var timestamp = new Date(); + var time = this.id[3] | (this.id[2] << 8) | (this.id[1] << 16) | (this.id[0] << 24); + timestamp.setTime(Math.floor(time) * 1000); + return timestamp; +}; + +/** +* @ignore +*/ +ObjectID.index = ~~(Math.random() * 0xffffff); + +/** +* @ignore +*/ +ObjectID.createPk = function createPk() { + return new ObjectID(); +}; + +/** +* Creates an ObjectID from a second based number, with the rest of the ObjectID zeroed out. Used for comparisons or sorting the ObjectID. +* +* @method +* @param {number} time an integer number representing a number of seconds. +* @return {ObjectID} return the created ObjectID +*/ +ObjectID.createFromTime = function createFromTime(time) { + var buffer = utils.toBuffer([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); + // Encode time into first 4 bytes + buffer[3] = time & 0xff; + buffer[2] = (time >> 8) & 0xff; + buffer[1] = (time >> 16) & 0xff; + buffer[0] = (time >> 24) & 0xff; + // Return the new objectId + return new ObjectID(buffer); +}; + +// Lookup tables +//var encodeLookup = '0123456789abcdef'.split(''); +var decodeLookup = []; +i = 0; +while (i < 10) decodeLookup[0x30 + i] = i++; +while (i < 16) decodeLookup[0x41 - 10 + i] = decodeLookup[0x61 - 10 + i] = i++; + +var _Buffer = Buffer; +var convertToHex = function(bytes) { + return bytes.toString('hex'); +}; + +/** +* Creates an ObjectID from a hex string representation of an ObjectID. +* +* @method +* @param {string} hexString create a ObjectID from a passed in 24 byte hexstring. +* @return {ObjectID} return the created ObjectID +*/ +ObjectID.createFromHexString = function createFromHexString(string) { + // Throw an error if it's not a valid setup + if (typeof string === 'undefined' || (string != null && string.length !== 24)) { + throw new Error( + 'Argument passed in must be a single String of 12 bytes or a string of 24 hex characters' + ); + } + + // Use Buffer.from method if available + if (hasBufferType) return new ObjectID(utils.toBuffer(string, 'hex')); + + // Calculate lengths + var array = new _Buffer(12); + var n = 0; + var i = 0; + + while (i < 24) { + array[n++] = (decodeLookup[string.charCodeAt(i++)] << 4) | decodeLookup[string.charCodeAt(i++)]; + } + + return new ObjectID(array); +}; + +/** +* Checks if a value is a valid bson ObjectId +* +* @method +* @return {boolean} return true if the value is a valid bson ObjectId, return false otherwise. +*/ +ObjectID.isValid = function isValid(id) { + if (id == null) return false; + + if (typeof id === 'number') { + return true; + } + + if (typeof id === 'string') { + return id.length === 12 || (id.length === 24 && checkForHexRegExp.test(id)); + } + + if (id instanceof ObjectID) { + return true; + } + + if (id instanceof _Buffer) { + return true; + } + + // Duck-Typing detection of ObjectId like objects + if (id.toHexString) { + return id.id.length === 12 || (id.id.length === 24 && checkForHexRegExp.test(id.id)); + } + + return false; +}; + +/** +* @ignore +*/ +Object.defineProperty(ObjectID.prototype, 'generationTime', { + enumerable: true, + get: function() { + return this.id[3] | (this.id[2] << 8) | (this.id[1] << 16) | (this.id[0] << 24); + }, + set: function(value) { + // Encode time into first 4 bytes + this.id[3] = value & 0xff; + this.id[2] = (value >> 8) & 0xff; + this.id[1] = (value >> 16) & 0xff; + this.id[0] = (value >> 24) & 0xff; + } +}); + +/** + * Expose. + */ +module.exports = ObjectID; +module.exports.ObjectID = ObjectID; +module.exports.ObjectId = ObjectID; diff --git a/scripts/node_modules/bson/lib/bson/parser/calculate_size.js b/scripts/node_modules/bson/lib/bson/parser/calculate_size.js new file mode 100644 index 00000000..7e0026ca --- /dev/null +++ b/scripts/node_modules/bson/lib/bson/parser/calculate_size.js @@ -0,0 +1,255 @@ +'use strict'; + +var Long = require('../long').Long, + Double = require('../double').Double, + Timestamp = require('../timestamp').Timestamp, + ObjectID = require('../objectid').ObjectID, + Symbol = require('../symbol').Symbol, + BSONRegExp = require('../regexp').BSONRegExp, + Code = require('../code').Code, + Decimal128 = require('../decimal128'), + MinKey = require('../min_key').MinKey, + MaxKey = require('../max_key').MaxKey, + DBRef = require('../db_ref').DBRef, + Binary = require('../binary').Binary; + +var normalizedFunctionString = require('./utils').normalizedFunctionString; + +// To ensure that 0.4 of node works correctly +var isDate = function isDate(d) { + return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; +}; + +var calculateObjectSize = function calculateObjectSize( + object, + serializeFunctions, + ignoreUndefined +) { + var totalLength = 4 + 1; + + if (Array.isArray(object)) { + for (var i = 0; i < object.length; i++) { + totalLength += calculateElement( + i.toString(), + object[i], + serializeFunctions, + true, + ignoreUndefined + ); + } + } else { + // If we have toBSON defined, override the current object + if (object.toBSON) { + object = object.toBSON(); + } + + // Calculate size + for (var key in object) { + totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined); + } + } + + return totalLength; +}; + +/** + * @ignore + * @api private + */ +function calculateElement(name, value, serializeFunctions, isArray, ignoreUndefined) { + // If we have toBSON defined, override the current object + if (value && value.toBSON) { + value = value.toBSON(); + } + + switch (typeof value) { + case 'string': + return 1 + Buffer.byteLength(name, 'utf8') + 1 + 4 + Buffer.byteLength(value, 'utf8') + 1; + case 'number': + if (Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { + if (value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { + // 32 bit + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (4 + 1); + } else { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); + } + } else { + // 64 bit + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); + } + case 'undefined': + if (isArray || !ignoreUndefined) + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1; + return 0; + case 'boolean': + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (1 + 1); + case 'object': + if ( + value == null || + value instanceof MinKey || + value instanceof MaxKey || + value['_bsontype'] === 'MinKey' || + value['_bsontype'] === 'MaxKey' + ) { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1; + } else if (value instanceof ObjectID || value['_bsontype'] === 'ObjectID' || value['_bsontype'] === 'ObjectId') { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (12 + 1); + } else if (value instanceof Date || isDate(value)) { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); + } else if (typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (1 + 4 + 1) + value.length + ); + } else if ( + value instanceof Long || + value instanceof Double || + value instanceof Timestamp || + value['_bsontype'] === 'Long' || + value['_bsontype'] === 'Double' || + value['_bsontype'] === 'Timestamp' + ) { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); + } else if (value instanceof Decimal128 || value['_bsontype'] === 'Decimal128') { + return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (16 + 1); + } else if (value instanceof Code || value['_bsontype'] === 'Code') { + // Calculate size depending on the availability of a scope + if (value.scope != null && Object.keys(value.scope).length > 0) { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + 4 + + 4 + + Buffer.byteLength(value.code.toString(), 'utf8') + + 1 + + calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined) + ); + } else { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + 4 + + Buffer.byteLength(value.code.toString(), 'utf8') + + 1 + ); + } + } else if (value instanceof Binary || value['_bsontype'] === 'Binary') { + // Check what kind of subtype we have + if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + (value.position + 1 + 4 + 1 + 4) + ); + } else { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (value.position + 1 + 4 + 1) + ); + } + } else if (value instanceof Symbol || value['_bsontype'] === 'Symbol') { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + Buffer.byteLength(value.value, 'utf8') + + 4 + + 1 + + 1 + ); + } else if (value instanceof DBRef || value['_bsontype'] === 'DBRef') { + // Set up correct object for serialization + var ordered_values = { + $ref: value.namespace, + $id: value.oid + }; + + // Add db reference if it exists + if (null != value.db) { + ordered_values['$db'] = value.db; + } + + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + calculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined) + ); + } else if ( + value instanceof RegExp || + Object.prototype.toString.call(value) === '[object RegExp]' + ) { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + Buffer.byteLength(value.source, 'utf8') + + 1 + + (value.global ? 1 : 0) + + (value.ignoreCase ? 1 : 0) + + (value.multiline ? 1 : 0) + + 1 + ); + } else if (value instanceof BSONRegExp || value['_bsontype'] === 'BSONRegExp') { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + Buffer.byteLength(value.pattern, 'utf8') + + 1 + + Buffer.byteLength(value.options, 'utf8') + + 1 + ); + } else { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + calculateObjectSize(value, serializeFunctions, ignoreUndefined) + + 1 + ); + } + case 'function': + // WTF for 0.4.X where typeof /someregexp/ === 'function' + if ( + value instanceof RegExp || + Object.prototype.toString.call(value) === '[object RegExp]' || + String.call(value) === '[object RegExp]' + ) { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + Buffer.byteLength(value.source, 'utf8') + + 1 + + (value.global ? 1 : 0) + + (value.ignoreCase ? 1 : 0) + + (value.multiline ? 1 : 0) + + 1 + ); + } else { + if (serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + 4 + + 4 + + Buffer.byteLength(normalizedFunctionString(value), 'utf8') + + 1 + + calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined) + ); + } else if (serializeFunctions) { + return ( + (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + + 1 + + 4 + + Buffer.byteLength(normalizedFunctionString(value), 'utf8') + + 1 + ); + } + } + } + + return 0; +} + +var BSON = {}; + +// BSON MAX VALUES +BSON.BSON_INT32_MAX = 0x7fffffff; +BSON.BSON_INT32_MIN = -0x80000000; + +// JS MAX PRECISE VALUES +BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. +BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. + +module.exports = calculateObjectSize; diff --git a/scripts/node_modules/bson/lib/bson/parser/deserializer.js b/scripts/node_modules/bson/lib/bson/parser/deserializer.js new file mode 100644 index 00000000..be3c8654 --- /dev/null +++ b/scripts/node_modules/bson/lib/bson/parser/deserializer.js @@ -0,0 +1,782 @@ +'use strict'; + +var Long = require('../long').Long, + Double = require('../double').Double, + Timestamp = require('../timestamp').Timestamp, + ObjectID = require('../objectid').ObjectID, + Symbol = require('../symbol').Symbol, + Code = require('../code').Code, + MinKey = require('../min_key').MinKey, + MaxKey = require('../max_key').MaxKey, + Decimal128 = require('../decimal128'), + Int32 = require('../int_32'), + DBRef = require('../db_ref').DBRef, + BSONRegExp = require('../regexp').BSONRegExp, + Binary = require('../binary').Binary; + +var utils = require('./utils'); + +var deserialize = function(buffer, options, isArray) { + options = options == null ? {} : options; + var index = options && options.index ? options.index : 0; + // Read the document size + var size = + buffer[index] | + (buffer[index + 1] << 8) | + (buffer[index + 2] << 16) | + (buffer[index + 3] << 24); + + // Ensure buffer is valid size + if (size < 5 || buffer.length < size || size + index > buffer.length) { + throw new Error('corrupt bson message'); + } + + // Illegal end value + if (buffer[index + size - 1] !== 0) { + throw new Error("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00"); + } + + // Start deserializtion + return deserializeObject(buffer, index, options, isArray); +}; + +var deserializeObject = function(buffer, index, options, isArray) { + var evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions']; + var cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions']; + var cacheFunctionsCrc32 = + options['cacheFunctionsCrc32'] == null ? false : options['cacheFunctionsCrc32']; + + if (!cacheFunctionsCrc32) var crc32 = null; + + var fieldsAsRaw = options['fieldsAsRaw'] == null ? null : options['fieldsAsRaw']; + + // Return raw bson buffer instead of parsing it + var raw = options['raw'] == null ? false : options['raw']; + + // Return BSONRegExp objects instead of native regular expressions + var bsonRegExp = typeof options['bsonRegExp'] === 'boolean' ? options['bsonRegExp'] : false; + + // Controls the promotion of values vs wrapper classes + var promoteBuffers = options['promoteBuffers'] == null ? false : options['promoteBuffers']; + var promoteLongs = options['promoteLongs'] == null ? true : options['promoteLongs']; + var promoteValues = options['promoteValues'] == null ? true : options['promoteValues']; + + // Set the start index + var startIndex = index; + + // Validate that we have at least 4 bytes of buffer + if (buffer.length < 5) throw new Error('corrupt bson message < 5 bytes long'); + + // Read the document size + var size = + buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + + // Ensure buffer is valid size + if (size < 5 || size > buffer.length) throw new Error('corrupt bson message'); + + // Create holding object + var object = isArray ? [] : {}; + // Used for arrays to skip having to perform utf8 decoding + var arrayIndex = 0; + + var done = false; + + // While we have more left data left keep parsing + // while (buffer[index + 1] !== 0) { + while (!done) { + // Read the type + var elementType = buffer[index++]; + // If we get a zero it's the last byte, exit + if (elementType === 0) break; + + // Get the start search index + var i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); + var name = isArray ? arrayIndex++ : buffer.toString('utf8', index, i); + + index = i + 1; + + if (elementType === BSON.BSON_DATA_STRING) { + var stringSize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + if ( + stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0 + ) + throw new Error('bad string length in bson'); + object[name] = buffer.toString('utf8', index, index + stringSize - 1); + index = index + stringSize; + } else if (elementType === BSON.BSON_DATA_OID) { + var oid = utils.allocBuffer(12); + buffer.copy(oid, 0, index, index + 12); + object[name] = new ObjectID(oid); + index = index + 12; + } else if (elementType === BSON.BSON_DATA_INT && promoteValues === false) { + object[name] = new Int32( + buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24) + ); + } else if (elementType === BSON.BSON_DATA_INT) { + object[name] = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + } else if (elementType === BSON.BSON_DATA_NUMBER && promoteValues === false) { + object[name] = new Double(buffer.readDoubleLE(index)); + index = index + 8; + } else if (elementType === BSON.BSON_DATA_NUMBER) { + object[name] = buffer.readDoubleLE(index); + index = index + 8; + } else if (elementType === BSON.BSON_DATA_DATE) { + var lowBits = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + var highBits = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + object[name] = new Date(new Long(lowBits, highBits).toNumber()); + } else if (elementType === BSON.BSON_DATA_BOOLEAN) { + if (buffer[index] !== 0 && buffer[index] !== 1) throw new Error('illegal boolean type value'); + object[name] = buffer[index++] === 1; + } else if (elementType === BSON.BSON_DATA_OBJECT) { + var _index = index; + var objectSize = + buffer[index] | + (buffer[index + 1] << 8) | + (buffer[index + 2] << 16) | + (buffer[index + 3] << 24); + if (objectSize <= 0 || objectSize > buffer.length - index) + throw new Error('bad embedded document length in bson'); + + // We have a raw value + if (raw) { + object[name] = buffer.slice(index, index + objectSize); + } else { + object[name] = deserializeObject(buffer, _index, options, false); + } + + index = index + objectSize; + } else if (elementType === BSON.BSON_DATA_ARRAY) { + _index = index; + objectSize = + buffer[index] | + (buffer[index + 1] << 8) | + (buffer[index + 2] << 16) | + (buffer[index + 3] << 24); + var arrayOptions = options; + + // Stop index + var stopIndex = index + objectSize; + + // All elements of array to be returned as raw bson + if (fieldsAsRaw && fieldsAsRaw[name]) { + arrayOptions = {}; + for (var n in options) arrayOptions[n] = options[n]; + arrayOptions['raw'] = true; + } + + object[name] = deserializeObject(buffer, _index, arrayOptions, true); + index = index + objectSize; + + if (buffer[index - 1] !== 0) throw new Error('invalid array terminator byte'); + if (index !== stopIndex) throw new Error('corrupted array bson'); + } else if (elementType === BSON.BSON_DATA_UNDEFINED) { + object[name] = undefined; + } else if (elementType === BSON.BSON_DATA_NULL) { + object[name] = null; + } else if (elementType === BSON.BSON_DATA_LONG) { + // Unpack the low and high bits + lowBits = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + highBits = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + var long = new Long(lowBits, highBits); + // Promote the long if possible + if (promoteLongs && promoteValues === true) { + object[name] = + long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) + ? long.toNumber() + : long; + } else { + object[name] = long; + } + } else if (elementType === BSON.BSON_DATA_DECIMAL128) { + // Buffer to contain the decimal bytes + var bytes = utils.allocBuffer(16); + // Copy the next 16 bytes into the bytes buffer + buffer.copy(bytes, 0, index, index + 16); + // Update index + index = index + 16; + // Assign the new Decimal128 value + var decimal128 = new Decimal128(bytes); + // If we have an alternative mapper use that + object[name] = decimal128.toObject ? decimal128.toObject() : decimal128; + } else if (elementType === BSON.BSON_DATA_BINARY) { + var binarySize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + var totalBinarySize = binarySize; + var subType = buffer[index++]; + + // Did we have a negative binary size, throw + if (binarySize < 0) throw new Error('Negative binary type element size found'); + + // Is the length longer than the document + if (binarySize > buffer.length) throw new Error('Binary type size larger than document size'); + + // Decode as raw Buffer object if options specifies it + if (buffer['slice'] != null) { + // If we have subtype 2 skip the 4 bytes for the size + if (subType === Binary.SUBTYPE_BYTE_ARRAY) { + binarySize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + if (binarySize < 0) + throw new Error('Negative binary type element size found for subtype 0x02'); + if (binarySize > totalBinarySize - 4) + throw new Error('Binary type with subtype 0x02 contains to long binary size'); + if (binarySize < totalBinarySize - 4) + throw new Error('Binary type with subtype 0x02 contains to short binary size'); + } + + if (promoteBuffers && promoteValues) { + object[name] = buffer.slice(index, index + binarySize); + } else { + object[name] = new Binary(buffer.slice(index, index + binarySize), subType); + } + } else { + var _buffer = + typeof Uint8Array !== 'undefined' + ? new Uint8Array(new ArrayBuffer(binarySize)) + : new Array(binarySize); + // If we have subtype 2 skip the 4 bytes for the size + if (subType === Binary.SUBTYPE_BYTE_ARRAY) { + binarySize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + if (binarySize < 0) + throw new Error('Negative binary type element size found for subtype 0x02'); + if (binarySize > totalBinarySize - 4) + throw new Error('Binary type with subtype 0x02 contains to long binary size'); + if (binarySize < totalBinarySize - 4) + throw new Error('Binary type with subtype 0x02 contains to short binary size'); + } + + // Copy the data + for (i = 0; i < binarySize; i++) { + _buffer[i] = buffer[index + i]; + } + + if (promoteBuffers && promoteValues) { + object[name] = _buffer; + } else { + object[name] = new Binary(_buffer, subType); + } + } + + // Update the index + index = index + binarySize; + } else if (elementType === BSON.BSON_DATA_REGEXP && bsonRegExp === false) { + // Get the start search index + i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); + // Return the C string + var source = buffer.toString('utf8', index, i); + // Create the regexp + index = i + 1; + + // Get the start search index + i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); + // Return the C string + var regExpOptions = buffer.toString('utf8', index, i); + index = i + 1; + + // For each option add the corresponding one for javascript + var optionsArray = new Array(regExpOptions.length); + + // Parse options + for (i = 0; i < regExpOptions.length; i++) { + switch (regExpOptions[i]) { + case 'm': + optionsArray[i] = 'm'; + break; + case 's': + optionsArray[i] = 'g'; + break; + case 'i': + optionsArray[i] = 'i'; + break; + } + } + + object[name] = new RegExp(source, optionsArray.join('')); + } else if (elementType === BSON.BSON_DATA_REGEXP && bsonRegExp === true) { + // Get the start search index + i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); + // Return the C string + source = buffer.toString('utf8', index, i); + index = i + 1; + + // Get the start search index + i = index; + // Locate the end of the c string + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + // If are at the end of the buffer there is a problem with the document + if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); + // Return the C string + regExpOptions = buffer.toString('utf8', index, i); + index = i + 1; + + // Set the object + object[name] = new BSONRegExp(source, regExpOptions); + } else if (elementType === BSON.BSON_DATA_SYMBOL) { + stringSize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + if ( + stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0 + ) + throw new Error('bad string length in bson'); + object[name] = new Symbol(buffer.toString('utf8', index, index + stringSize - 1)); + index = index + stringSize; + } else if (elementType === BSON.BSON_DATA_TIMESTAMP) { + lowBits = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + highBits = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + object[name] = new Timestamp(lowBits, highBits); + } else if (elementType === BSON.BSON_DATA_MIN_KEY) { + object[name] = new MinKey(); + } else if (elementType === BSON.BSON_DATA_MAX_KEY) { + object[name] = new MaxKey(); + } else if (elementType === BSON.BSON_DATA_CODE) { + stringSize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + if ( + stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0 + ) + throw new Error('bad string length in bson'); + var functionString = buffer.toString('utf8', index, index + stringSize - 1); + + // If we are evaluating the functions + if (evalFunctions) { + // If we have cache enabled let's look for the md5 of the function in the cache + if (cacheFunctions) { + var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; + // Got to do this to avoid V8 deoptimizing the call due to finding eval + object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); + } else { + object[name] = isolateEval(functionString); + } + } else { + object[name] = new Code(functionString); + } + + // Update parse index position + index = index + stringSize; + } else if (elementType === BSON.BSON_DATA_CODE_W_SCOPE) { + var totalSize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + + // Element cannot be shorter than totalSize + stringSize + documentSize + terminator + if (totalSize < 4 + 4 + 4 + 1) { + throw new Error('code_w_scope total size shorter minimum expected length'); + } + + // Get the code string size + stringSize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + // Check if we have a valid string + if ( + stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0 + ) + throw new Error('bad string length in bson'); + + // Javascript function + functionString = buffer.toString('utf8', index, index + stringSize - 1); + // Update parse index position + index = index + stringSize; + // Parse the element + _index = index; + // Decode the size of the object document + objectSize = + buffer[index] | + (buffer[index + 1] << 8) | + (buffer[index + 2] << 16) | + (buffer[index + 3] << 24); + // Decode the scope object + var scopeObject = deserializeObject(buffer, _index, options, false); + // Adjust the index + index = index + objectSize; + + // Check if field length is to short + if (totalSize < 4 + 4 + objectSize + stringSize) { + throw new Error('code_w_scope total size is to short, truncating scope'); + } + + // Check if totalSize field is to long + if (totalSize > 4 + 4 + objectSize + stringSize) { + throw new Error('code_w_scope total size is to long, clips outer document'); + } + + // If we are evaluating the functions + if (evalFunctions) { + // If we have cache enabled let's look for the md5 of the function in the cache + if (cacheFunctions) { + hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; + // Got to do this to avoid V8 deoptimizing the call due to finding eval + object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); + } else { + object[name] = isolateEval(functionString); + } + + object[name].scope = scopeObject; + } else { + object[name] = new Code(functionString, scopeObject); + } + } else if (elementType === BSON.BSON_DATA_DBPOINTER) { + // Get the code string size + stringSize = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + // Check if we have a valid string + if ( + stringSize <= 0 || + stringSize > buffer.length - index || + buffer[index + stringSize - 1] !== 0 + ) + throw new Error('bad string length in bson'); + // Namespace + var namespace = buffer.toString('utf8', index, index + stringSize - 1); + // Update parse index position + index = index + stringSize; + + // Read the oid + var oidBuffer = utils.allocBuffer(12); + buffer.copy(oidBuffer, 0, index, index + 12); + oid = new ObjectID(oidBuffer); + + // Update the index + index = index + 12; + + // Split the namespace + var parts = namespace.split('.'); + var db = parts.shift(); + var collection = parts.join('.'); + // Upgrade to DBRef type + object[name] = new DBRef(collection, oid, db); + } else { + throw new Error( + 'Detected unknown BSON type ' + + elementType.toString(16) + + ' for fieldname "' + + name + + '", are you using the latest BSON parser' + ); + } + } + + // Check if the deserialization was against a valid array/object + if (size !== index - startIndex) { + if (isArray) throw new Error('corrupt array bson'); + throw new Error('corrupt object bson'); + } + + // Check if we have a db ref object + if (object['$id'] != null) object = new DBRef(object['$ref'], object['$id'], object['$db']); + return object; +}; + +/** + * Ensure eval is isolated. + * + * @ignore + * @api private + */ +var isolateEvalWithHash = function(functionCache, hash, functionString, object) { + // Contains the value we are going to set + var value = null; + + // Check for cache hit, eval if missing and return cached function + if (functionCache[hash] == null) { + eval('value = ' + functionString); + functionCache[hash] = value; + } + // Set the object + return functionCache[hash].bind(object); +}; + +/** + * Ensure eval is isolated. + * + * @ignore + * @api private + */ +var isolateEval = function(functionString) { + // Contains the value we are going to set + var value = null; + // Eval the function + eval('value = ' + functionString); + return value; +}; + +var BSON = {}; + +/** + * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 + * + * @ignore + * @api private + */ +var functionCache = (BSON.functionCache = {}); + +/** + * Number BSON Type + * + * @classconstant BSON_DATA_NUMBER + **/ +BSON.BSON_DATA_NUMBER = 1; +/** + * String BSON Type + * + * @classconstant BSON_DATA_STRING + **/ +BSON.BSON_DATA_STRING = 2; +/** + * Object BSON Type + * + * @classconstant BSON_DATA_OBJECT + **/ +BSON.BSON_DATA_OBJECT = 3; +/** + * Array BSON Type + * + * @classconstant BSON_DATA_ARRAY + **/ +BSON.BSON_DATA_ARRAY = 4; +/** + * Binary BSON Type + * + * @classconstant BSON_DATA_BINARY + **/ +BSON.BSON_DATA_BINARY = 5; +/** + * Binary BSON Type + * + * @classconstant BSON_DATA_UNDEFINED + **/ +BSON.BSON_DATA_UNDEFINED = 6; +/** + * ObjectID BSON Type + * + * @classconstant BSON_DATA_OID + **/ +BSON.BSON_DATA_OID = 7; +/** + * Boolean BSON Type + * + * @classconstant BSON_DATA_BOOLEAN + **/ +BSON.BSON_DATA_BOOLEAN = 8; +/** + * Date BSON Type + * + * @classconstant BSON_DATA_DATE + **/ +BSON.BSON_DATA_DATE = 9; +/** + * null BSON Type + * + * @classconstant BSON_DATA_NULL + **/ +BSON.BSON_DATA_NULL = 10; +/** + * RegExp BSON Type + * + * @classconstant BSON_DATA_REGEXP + **/ +BSON.BSON_DATA_REGEXP = 11; +/** + * Code BSON Type + * + * @classconstant BSON_DATA_DBPOINTER + **/ +BSON.BSON_DATA_DBPOINTER = 12; +/** + * Code BSON Type + * + * @classconstant BSON_DATA_CODE + **/ +BSON.BSON_DATA_CODE = 13; +/** + * Symbol BSON Type + * + * @classconstant BSON_DATA_SYMBOL + **/ +BSON.BSON_DATA_SYMBOL = 14; +/** + * Code with Scope BSON Type + * + * @classconstant BSON_DATA_CODE_W_SCOPE + **/ +BSON.BSON_DATA_CODE_W_SCOPE = 15; +/** + * 32 bit Integer BSON Type + * + * @classconstant BSON_DATA_INT + **/ +BSON.BSON_DATA_INT = 16; +/** + * Timestamp BSON Type + * + * @classconstant BSON_DATA_TIMESTAMP + **/ +BSON.BSON_DATA_TIMESTAMP = 17; +/** + * Long BSON Type + * + * @classconstant BSON_DATA_LONG + **/ +BSON.BSON_DATA_LONG = 18; +/** + * Long BSON Type + * + * @classconstant BSON_DATA_DECIMAL128 + **/ +BSON.BSON_DATA_DECIMAL128 = 19; +/** + * MinKey BSON Type + * + * @classconstant BSON_DATA_MIN_KEY + **/ +BSON.BSON_DATA_MIN_KEY = 0xff; +/** + * MaxKey BSON Type + * + * @classconstant BSON_DATA_MAX_KEY + **/ +BSON.BSON_DATA_MAX_KEY = 0x7f; + +/** + * Binary Default Type + * + * @classconstant BSON_BINARY_SUBTYPE_DEFAULT + **/ +BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; +/** + * Binary Function Type + * + * @classconstant BSON_BINARY_SUBTYPE_FUNCTION + **/ +BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; +/** + * Binary Byte Array Type + * + * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY + **/ +BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; +/** + * Binary UUID Type + * + * @classconstant BSON_BINARY_SUBTYPE_UUID + **/ +BSON.BSON_BINARY_SUBTYPE_UUID = 3; +/** + * Binary MD5 Type + * + * @classconstant BSON_BINARY_SUBTYPE_MD5 + **/ +BSON.BSON_BINARY_SUBTYPE_MD5 = 4; +/** + * Binary User Defined Type + * + * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED + **/ +BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; + +// BSON MAX VALUES +BSON.BSON_INT32_MAX = 0x7fffffff; +BSON.BSON_INT32_MIN = -0x80000000; + +BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; +BSON.BSON_INT64_MIN = -Math.pow(2, 63); + +// JS MAX PRECISE VALUES +BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. +BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. + +// Internal long versions +var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. +var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. + +module.exports = deserialize; diff --git a/scripts/node_modules/bson/lib/bson/parser/serializer.js b/scripts/node_modules/bson/lib/bson/parser/serializer.js new file mode 100644 index 00000000..e4ff2bd9 --- /dev/null +++ b/scripts/node_modules/bson/lib/bson/parser/serializer.js @@ -0,0 +1,1182 @@ +'use strict'; + +var writeIEEE754 = require('../float_parser').writeIEEE754, + Long = require('../long').Long, + Map = require('../map'), + Binary = require('../binary').Binary; + +var normalizedFunctionString = require('./utils').normalizedFunctionString; + +// try { +// var _Buffer = Uint8Array; +// } catch (e) { +// _Buffer = Buffer; +// } + +var regexp = /\x00/; // eslint-disable-line no-control-regex +var ignoreKeys = ['$db', '$ref', '$id', '$clusterTime']; + +// To ensure that 0.4 of node works correctly +var isDate = function isDate(d) { + return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; +}; + +var isRegExp = function isRegExp(d) { + return Object.prototype.toString.call(d) === '[object RegExp]'; +}; + +var serializeString = function(buffer, key, value, index, isArray) { + // Encode String type + buffer[index++] = BSON.BSON_DATA_STRING; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Write the string + var size = buffer.write(value, index + 4, 'utf8'); + // Write the size of the string to buffer + buffer[index + 3] = ((size + 1) >> 24) & 0xff; + buffer[index + 2] = ((size + 1) >> 16) & 0xff; + buffer[index + 1] = ((size + 1) >> 8) & 0xff; + buffer[index] = (size + 1) & 0xff; + // Update index + index = index + 4 + size; + // Write zero + buffer[index++] = 0; + return index; +}; + +var serializeNumber = function(buffer, key, value, index, isArray) { + // We have an integer value + if (Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { + // If the value fits in 32 bits encode as int, if it fits in a double + // encode it as a double, otherwise long + if (value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { + // Set int type 32 bits or less + buffer[index++] = BSON.BSON_DATA_INT; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the int value + buffer[index++] = value & 0xff; + buffer[index++] = (value >> 8) & 0xff; + buffer[index++] = (value >> 16) & 0xff; + buffer[index++] = (value >> 24) & 0xff; + } else if (value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { + // Encode as double + buffer[index++] = BSON.BSON_DATA_NUMBER; + // Number of written bytes + numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write float + writeIEEE754(buffer, value, index, 'little', 52, 8); + // Ajust index + index = index + 8; + } else { + // Set long type + buffer[index++] = BSON.BSON_DATA_LONG; + // Number of written bytes + numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + var longVal = Long.fromNumber(value); + var lowBits = longVal.getLowBits(); + var highBits = longVal.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = (highBits >> 8) & 0xff; + buffer[index++] = (highBits >> 16) & 0xff; + buffer[index++] = (highBits >> 24) & 0xff; + } + } else { + // Encode as double + buffer[index++] = BSON.BSON_DATA_NUMBER; + // Number of written bytes + numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write float + writeIEEE754(buffer, value, index, 'little', 52, 8); + // Ajust index + index = index + 8; + } + + return index; +}; + +var serializeNull = function(buffer, key, value, index, isArray) { + // Set long type + buffer[index++] = BSON.BSON_DATA_NULL; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + return index; +}; + +var serializeBoolean = function(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_BOOLEAN; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Encode the boolean value + buffer[index++] = value ? 1 : 0; + return index; +}; + +var serializeDate = function(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_DATE; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + // Write the date + var dateInMilis = Long.fromNumber(value.getTime()); + var lowBits = dateInMilis.getLowBits(); + var highBits = dateInMilis.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = (highBits >> 8) & 0xff; + buffer[index++] = (highBits >> 16) & 0xff; + buffer[index++] = (highBits >> 24) & 0xff; + return index; +}; + +var serializeRegExp = function(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_REGEXP; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + if (value.source && value.source.match(regexp) != null) { + throw Error('value ' + value.source + ' must not contain null bytes'); + } + // Adjust the index + index = index + buffer.write(value.source, index, 'utf8'); + // Write zero + buffer[index++] = 0x00; + // Write the parameters + if (value.global) buffer[index++] = 0x73; // s + if (value.ignoreCase) buffer[index++] = 0x69; // i + if (value.multiline) buffer[index++] = 0x6d; // m + // Add ending zero + buffer[index++] = 0x00; + return index; +}; + +var serializeBSONRegExp = function(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_REGEXP; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + // Check the pattern for 0 bytes + if (value.pattern.match(regexp) != null) { + // The BSON spec doesn't allow keys with null bytes because keys are + // null-terminated. + throw Error('pattern ' + value.pattern + ' must not contain null bytes'); + } + + // Adjust the index + index = index + buffer.write(value.pattern, index, 'utf8'); + // Write zero + buffer[index++] = 0x00; + // Write the options + index = + index + + buffer.write( + value.options + .split('') + .sort() + .join(''), + index, + 'utf8' + ); + // Add ending zero + buffer[index++] = 0x00; + return index; +}; + +var serializeMinMax = function(buffer, key, value, index, isArray) { + // Write the type of either min or max key + if (value === null) { + buffer[index++] = BSON.BSON_DATA_NULL; + } else if (value._bsontype === 'MinKey') { + buffer[index++] = BSON.BSON_DATA_MIN_KEY; + } else { + buffer[index++] = BSON.BSON_DATA_MAX_KEY; + } + + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + return index; +}; + +var serializeObjectId = function(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_OID; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + // Write the objectId into the shared buffer + if (typeof value.id === 'string') { + buffer.write(value.id, index, 'binary'); + } else if (value.id && value.id.copy) { + value.id.copy(buffer, index, 0, 12); + } else { + throw new Error('object [' + JSON.stringify(value) + '] is not a valid ObjectId'); + } + + // Ajust index + return index + 12; +}; + +var serializeBuffer = function(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_BINARY; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Get size of the buffer (current write point) + var size = value.length; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write the default subtype + buffer[index++] = BSON.BSON_BINARY_SUBTYPE_DEFAULT; + // Copy the content form the binary field to the buffer + value.copy(buffer, index, 0, size); + // Adjust the index + index = index + size; + return index; +}; + +var serializeObject = function( + buffer, + key, + value, + index, + checkKeys, + depth, + serializeFunctions, + ignoreUndefined, + isArray, + path +) { + for (var i = 0; i < path.length; i++) { + if (path[i] === value) throw new Error('cyclic dependency detected'); + } + + // Push value to stack + path.push(value); + // Write the type + buffer[index++] = Array.isArray(value) ? BSON.BSON_DATA_ARRAY : BSON.BSON_DATA_OBJECT; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + var endIndex = serializeInto( + buffer, + value, + checkKeys, + index, + depth + 1, + serializeFunctions, + ignoreUndefined, + path + ); + // Pop stack + path.pop(); + // Write size + return endIndex; +}; + +var serializeDecimal128 = function(buffer, key, value, index, isArray) { + buffer[index++] = BSON.BSON_DATA_DECIMAL128; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the data from the value + value.bytes.copy(buffer, index, 0, 16); + return index + 16; +}; + +var serializeLong = function(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = value._bsontype === 'Long' ? BSON.BSON_DATA_LONG : BSON.BSON_DATA_TIMESTAMP; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the date + var lowBits = value.getLowBits(); + var highBits = value.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = (highBits >> 8) & 0xff; + buffer[index++] = (highBits >> 16) & 0xff; + buffer[index++] = (highBits >> 24) & 0xff; + return index; +}; + +var serializeInt32 = function(buffer, key, value, index, isArray) { + // Set int type 32 bits or less + buffer[index++] = BSON.BSON_DATA_INT; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the int value + buffer[index++] = value & 0xff; + buffer[index++] = (value >> 8) & 0xff; + buffer[index++] = (value >> 16) & 0xff; + buffer[index++] = (value >> 24) & 0xff; + return index; +}; + +var serializeDouble = function(buffer, key, value, index, isArray) { + // Encode as double + buffer[index++] = BSON.BSON_DATA_NUMBER; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write float + writeIEEE754(buffer, value, index, 'little', 52, 8); + // Ajust index + index = index + 8; + return index; +}; + +var serializeFunction = function(buffer, key, value, index, checkKeys, depth, isArray) { + buffer[index++] = BSON.BSON_DATA_CODE; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Function string + var functionString = normalizedFunctionString(value); + + // Write the string + var size = buffer.write(functionString, index + 4, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = size & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 3] = (size >> 24) & 0xff; + // Update index + index = index + 4 + size - 1; + // Write zero + buffer[index++] = 0; + return index; +}; + +var serializeCode = function( + buffer, + key, + value, + index, + checkKeys, + depth, + serializeFunctions, + ignoreUndefined, + isArray +) { + if (value.scope && typeof value.scope === 'object') { + // Write the type + buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + // Starting index + var startIndex = index; + + // Serialize the function + // Get the function string + var functionString = typeof value.code === 'string' ? value.code : value.code.toString(); + // Index adjustment + index = index + 4; + // Write string into buffer + var codeSize = buffer.write(functionString, index + 4, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = codeSize & 0xff; + buffer[index + 1] = (codeSize >> 8) & 0xff; + buffer[index + 2] = (codeSize >> 16) & 0xff; + buffer[index + 3] = (codeSize >> 24) & 0xff; + // Write end 0 + buffer[index + 4 + codeSize - 1] = 0; + // Write the + index = index + codeSize + 4; + + // + // Serialize the scope value + var endIndex = serializeInto( + buffer, + value.scope, + checkKeys, + index, + depth + 1, + serializeFunctions, + ignoreUndefined + ); + index = endIndex - 1; + + // Writ the total + var totalSize = endIndex - startIndex; + + // Write the total size of the object + buffer[startIndex++] = totalSize & 0xff; + buffer[startIndex++] = (totalSize >> 8) & 0xff; + buffer[startIndex++] = (totalSize >> 16) & 0xff; + buffer[startIndex++] = (totalSize >> 24) & 0xff; + // Write trailing zero + buffer[index++] = 0; + } else { + buffer[index++] = BSON.BSON_DATA_CODE; + // Number of written bytes + numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Function string + functionString = value.code.toString(); + // Write the string + var size = buffer.write(functionString, index + 4, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = size & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 3] = (size >> 24) & 0xff; + // Update index + index = index + 4 + size - 1; + // Write zero + buffer[index++] = 0; + } + + return index; +}; + +var serializeBinary = function(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_BINARY; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Extract the buffer + var data = value.value(true); + // Calculate size + var size = value.position; + // Add the deprecated 02 type 4 bytes of size to total + if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) size = size + 4; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write the subtype to the buffer + buffer[index++] = value.sub_type; + + // If we have binary type 2 the 4 first bytes are the size + if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { + size = size - 4; + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + } + + // Write the data to the object + data.copy(buffer, index, 0, value.position); + // Adjust the index + index = index + value.position; + return index; +}; + +var serializeSymbol = function(buffer, key, value, index, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_SYMBOL; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the string + var size = buffer.write(value.value, index + 4, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = size & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 3] = (size >> 24) & 0xff; + // Update index + index = index + 4 + size - 1; + // Write zero + buffer[index++] = 0x00; + return index; +}; + +var serializeDBRef = function(buffer, key, value, index, depth, serializeFunctions, isArray) { + // Write the type + buffer[index++] = BSON.BSON_DATA_OBJECT; + // Number of written bytes + var numberOfWrittenBytes = !isArray + ? buffer.write(key, index, 'utf8') + : buffer.write(key, index, 'ascii'); + + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + var startIndex = index; + var endIndex; + + // Serialize object + if (null != value.db) { + endIndex = serializeInto( + buffer, + { + $ref: value.namespace, + $id: value.oid, + $db: value.db + }, + false, + index, + depth + 1, + serializeFunctions + ); + } else { + endIndex = serializeInto( + buffer, + { + $ref: value.namespace, + $id: value.oid + }, + false, + index, + depth + 1, + serializeFunctions + ); + } + + // Calculate object size + var size = endIndex - startIndex; + // Write the size + buffer[startIndex++] = size & 0xff; + buffer[startIndex++] = (size >> 8) & 0xff; + buffer[startIndex++] = (size >> 16) & 0xff; + buffer[startIndex++] = (size >> 24) & 0xff; + // Set index + return endIndex; +}; + +var serializeInto = function serializeInto( + buffer, + object, + checkKeys, + startingIndex, + depth, + serializeFunctions, + ignoreUndefined, + path +) { + startingIndex = startingIndex || 0; + path = path || []; + + // Push the object to the path + path.push(object); + + // Start place to serialize into + var index = startingIndex + 4; + // var self = this; + + // Special case isArray + if (Array.isArray(object)) { + // Get object keys + for (var i = 0; i < object.length; i++) { + var key = '' + i; + var value = object[i]; + + // Is there an override value + if (value && value.toBSON) { + if (typeof value.toBSON !== 'function') throw new Error('toBSON is not a function'); + value = value.toBSON(); + } + + var type = typeof value; + if (type === 'string') { + index = serializeString(buffer, key, value, index, true); + } else if (type === 'number') { + index = serializeNumber(buffer, key, value, index, true); + } else if (type === 'boolean') { + index = serializeBoolean(buffer, key, value, index, true); + } else if (value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index, true); + } else if (value === undefined) { + index = serializeNull(buffer, key, value, index, true); + } else if (value === null) { + index = serializeNull(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'ObjectID' || value['_bsontype'] === 'ObjectId') { + index = serializeObjectId(buffer, key, value, index, true); + } else if (Buffer.isBuffer(value)) { + index = serializeBuffer(buffer, key, value, index, true); + } else if (value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index, true); + } else if (type === 'object' && value['_bsontype'] == null) { + index = serializeObject( + buffer, + key, + value, + index, + checkKeys, + depth, + serializeFunctions, + ignoreUndefined, + true, + path + ); + } else if (type === 'object' && value['_bsontype'] === 'Decimal128') { + index = serializeDecimal128(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { + index = serializeLong(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'Double') { + index = serializeDouble(buffer, key, value, index, true); + } else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction( + buffer, + key, + value, + index, + checkKeys, + depth, + serializeFunctions, + true + ); + } else if (value['_bsontype'] === 'Code') { + index = serializeCode( + buffer, + key, + value, + index, + checkKeys, + depth, + serializeFunctions, + ignoreUndefined, + true + ); + } else if (value['_bsontype'] === 'Binary') { + index = serializeBinary(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'Symbol') { + index = serializeSymbol(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, true); + } else if (value['_bsontype'] === 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'Int32') { + index = serializeInt32(buffer, key, value, index, true); + } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { + index = serializeMinMax(buffer, key, value, index, true); + } + } + } else if (object instanceof Map) { + var iterator = object.entries(); + var done = false; + + while (!done) { + // Unpack the next entry + var entry = iterator.next(); + done = entry.done; + // Are we done, then skip and terminate + if (done) continue; + + // Get the entry values + key = entry.value[0]; + value = entry.value[1]; + + // Check the type of the value + type = typeof value; + + // Check the key and throw error if it's illegal + if (typeof key === 'string' && ignoreKeys.indexOf(key) === -1) { + if (key.match(regexp) != null) { + // The BSON spec doesn't allow keys with null bytes because keys are + // null-terminated. + throw Error('key ' + key + ' must not contain null bytes'); + } + + if (checkKeys) { + if ('$' === key[0]) { + throw Error('key ' + key + " must not start with '$'"); + } else if (~key.indexOf('.')) { + throw Error('key ' + key + " must not contain '.'"); + } + } + } + + if (type === 'string') { + index = serializeString(buffer, key, value, index); + } else if (type === 'number') { + index = serializeNumber(buffer, key, value, index); + } else if (type === 'boolean') { + index = serializeBoolean(buffer, key, value, index); + } else if (value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index); + // } else if (value === undefined && ignoreUndefined === true) { + } else if (value === null || (value === undefined && ignoreUndefined === false)) { + index = serializeNull(buffer, key, value, index); + } else if (value['_bsontype'] === 'ObjectID' || value['_bsontype'] === 'ObjectId') { + index = serializeObjectId(buffer, key, value, index); + } else if (Buffer.isBuffer(value)) { + index = serializeBuffer(buffer, key, value, index); + } else if (value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index); + } else if (type === 'object' && value['_bsontype'] == null) { + index = serializeObject( + buffer, + key, + value, + index, + checkKeys, + depth, + serializeFunctions, + ignoreUndefined, + false, + path + ); + } else if (type === 'object' && value['_bsontype'] === 'Decimal128') { + index = serializeDecimal128(buffer, key, value, index); + } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { + index = serializeLong(buffer, key, value, index); + } else if (value['_bsontype'] === 'Double') { + index = serializeDouble(buffer, key, value, index); + } else if (value['_bsontype'] === 'Code') { + index = serializeCode( + buffer, + key, + value, + index, + checkKeys, + depth, + serializeFunctions, + ignoreUndefined + ); + } else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); + } else if (value['_bsontype'] === 'Binary') { + index = serializeBinary(buffer, key, value, index); + } else if (value['_bsontype'] === 'Symbol') { + index = serializeSymbol(buffer, key, value, index); + } else if (value['_bsontype'] === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); + } else if (value['_bsontype'] === 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index); + } else if (value['_bsontype'] === 'Int32') { + index = serializeInt32(buffer, key, value, index); + } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { + index = serializeMinMax(buffer, key, value, index); + } + } + } else { + // Did we provide a custom serialization method + if (object.toBSON) { + if (typeof object.toBSON !== 'function') throw new Error('toBSON is not a function'); + object = object.toBSON(); + if (object != null && typeof object !== 'object') + throw new Error('toBSON function did not return an object'); + } + + // Iterate over all the keys + for (key in object) { + value = object[key]; + // Is there an override value + if (value && value.toBSON) { + if (typeof value.toBSON !== 'function') throw new Error('toBSON is not a function'); + value = value.toBSON(); + } + + // Check the type of the value + type = typeof value; + + // Check the key and throw error if it's illegal + if (typeof key === 'string' && ignoreKeys.indexOf(key) === -1) { + if (key.match(regexp) != null) { + // The BSON spec doesn't allow keys with null bytes because keys are + // null-terminated. + throw Error('key ' + key + ' must not contain null bytes'); + } + + if (checkKeys) { + if ('$' === key[0]) { + throw Error('key ' + key + " must not start with '$'"); + } else if (~key.indexOf('.')) { + throw Error('key ' + key + " must not contain '.'"); + } + } + } + + if (type === 'string') { + index = serializeString(buffer, key, value, index); + } else if (type === 'number') { + index = serializeNumber(buffer, key, value, index); + } else if (type === 'boolean') { + index = serializeBoolean(buffer, key, value, index); + } else if (value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index); + } else if (value === undefined) { + if (ignoreUndefined === false) index = serializeNull(buffer, key, value, index); + } else if (value === null) { + index = serializeNull(buffer, key, value, index); + } else if (value['_bsontype'] === 'ObjectID' || value['_bsontype'] === 'ObjectId') { + index = serializeObjectId(buffer, key, value, index); + } else if (Buffer.isBuffer(value)) { + index = serializeBuffer(buffer, key, value, index); + } else if (value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index); + } else if (type === 'object' && value['_bsontype'] == null) { + index = serializeObject( + buffer, + key, + value, + index, + checkKeys, + depth, + serializeFunctions, + ignoreUndefined, + false, + path + ); + } else if (type === 'object' && value['_bsontype'] === 'Decimal128') { + index = serializeDecimal128(buffer, key, value, index); + } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { + index = serializeLong(buffer, key, value, index); + } else if (value['_bsontype'] === 'Double') { + index = serializeDouble(buffer, key, value, index); + } else if (value['_bsontype'] === 'Code') { + index = serializeCode( + buffer, + key, + value, + index, + checkKeys, + depth, + serializeFunctions, + ignoreUndefined + ); + } else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); + } else if (value['_bsontype'] === 'Binary') { + index = serializeBinary(buffer, key, value, index); + } else if (value['_bsontype'] === 'Symbol') { + index = serializeSymbol(buffer, key, value, index); + } else if (value['_bsontype'] === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); + } else if (value['_bsontype'] === 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index); + } else if (value['_bsontype'] === 'Int32') { + index = serializeInt32(buffer, key, value, index); + } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { + index = serializeMinMax(buffer, key, value, index); + } + } + } + + // Remove the path + path.pop(); + + // Final padding byte for object + buffer[index++] = 0x00; + + // Final size + var size = index - startingIndex; + // Write the size of the object + buffer[startingIndex++] = size & 0xff; + buffer[startingIndex++] = (size >> 8) & 0xff; + buffer[startingIndex++] = (size >> 16) & 0xff; + buffer[startingIndex++] = (size >> 24) & 0xff; + return index; +}; + +var BSON = {}; + +/** + * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 + * + * @ignore + * @api private + */ +// var functionCache = (BSON.functionCache = {}); + +/** + * Number BSON Type + * + * @classconstant BSON_DATA_NUMBER + **/ +BSON.BSON_DATA_NUMBER = 1; +/** + * String BSON Type + * + * @classconstant BSON_DATA_STRING + **/ +BSON.BSON_DATA_STRING = 2; +/** + * Object BSON Type + * + * @classconstant BSON_DATA_OBJECT + **/ +BSON.BSON_DATA_OBJECT = 3; +/** + * Array BSON Type + * + * @classconstant BSON_DATA_ARRAY + **/ +BSON.BSON_DATA_ARRAY = 4; +/** + * Binary BSON Type + * + * @classconstant BSON_DATA_BINARY + **/ +BSON.BSON_DATA_BINARY = 5; +/** + * ObjectID BSON Type, deprecated + * + * @classconstant BSON_DATA_UNDEFINED + **/ +BSON.BSON_DATA_UNDEFINED = 6; +/** + * ObjectID BSON Type + * + * @classconstant BSON_DATA_OID + **/ +BSON.BSON_DATA_OID = 7; +/** + * Boolean BSON Type + * + * @classconstant BSON_DATA_BOOLEAN + **/ +BSON.BSON_DATA_BOOLEAN = 8; +/** + * Date BSON Type + * + * @classconstant BSON_DATA_DATE + **/ +BSON.BSON_DATA_DATE = 9; +/** + * null BSON Type + * + * @classconstant BSON_DATA_NULL + **/ +BSON.BSON_DATA_NULL = 10; +/** + * RegExp BSON Type + * + * @classconstant BSON_DATA_REGEXP + **/ +BSON.BSON_DATA_REGEXP = 11; +/** + * Code BSON Type + * + * @classconstant BSON_DATA_CODE + **/ +BSON.BSON_DATA_CODE = 13; +/** + * Symbol BSON Type + * + * @classconstant BSON_DATA_SYMBOL + **/ +BSON.BSON_DATA_SYMBOL = 14; +/** + * Code with Scope BSON Type + * + * @classconstant BSON_DATA_CODE_W_SCOPE + **/ +BSON.BSON_DATA_CODE_W_SCOPE = 15; +/** + * 32 bit Integer BSON Type + * + * @classconstant BSON_DATA_INT + **/ +BSON.BSON_DATA_INT = 16; +/** + * Timestamp BSON Type + * + * @classconstant BSON_DATA_TIMESTAMP + **/ +BSON.BSON_DATA_TIMESTAMP = 17; +/** + * Long BSON Type + * + * @classconstant BSON_DATA_LONG + **/ +BSON.BSON_DATA_LONG = 18; +/** + * Long BSON Type + * + * @classconstant BSON_DATA_DECIMAL128 + **/ +BSON.BSON_DATA_DECIMAL128 = 19; +/** + * MinKey BSON Type + * + * @classconstant BSON_DATA_MIN_KEY + **/ +BSON.BSON_DATA_MIN_KEY = 0xff; +/** + * MaxKey BSON Type + * + * @classconstant BSON_DATA_MAX_KEY + **/ +BSON.BSON_DATA_MAX_KEY = 0x7f; +/** + * Binary Default Type + * + * @classconstant BSON_BINARY_SUBTYPE_DEFAULT + **/ +BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; +/** + * Binary Function Type + * + * @classconstant BSON_BINARY_SUBTYPE_FUNCTION + **/ +BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; +/** + * Binary Byte Array Type + * + * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY + **/ +BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; +/** + * Binary UUID Type + * + * @classconstant BSON_BINARY_SUBTYPE_UUID + **/ +BSON.BSON_BINARY_SUBTYPE_UUID = 3; +/** + * Binary MD5 Type + * + * @classconstant BSON_BINARY_SUBTYPE_MD5 + **/ +BSON.BSON_BINARY_SUBTYPE_MD5 = 4; +/** + * Binary User Defined Type + * + * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED + **/ +BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; + +// BSON MAX VALUES +BSON.BSON_INT32_MAX = 0x7fffffff; +BSON.BSON_INT32_MIN = -0x80000000; + +BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; +BSON.BSON_INT64_MIN = -Math.pow(2, 63); + +// JS MAX PRECISE VALUES +BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. +BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. + +// Internal long versions +// var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. +// var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. + +module.exports = serializeInto; diff --git a/scripts/node_modules/bson/lib/bson/parser/utils.js b/scripts/node_modules/bson/lib/bson/parser/utils.js new file mode 100644 index 00000000..6faa4396 --- /dev/null +++ b/scripts/node_modules/bson/lib/bson/parser/utils.js @@ -0,0 +1,28 @@ +'use strict'; + +/** + * Normalizes our expected stringified form of a function across versions of node + * @param {Function} fn The function to stringify + */ +function normalizedFunctionString(fn) { + return fn.toString().replace(/function *\(/, 'function ('); +} + +function newBuffer(item, encoding) { + return new Buffer(item, encoding); +} + +function allocBuffer() { + return Buffer.alloc.apply(Buffer, arguments); +} + +function toBuffer() { + return Buffer.from.apply(Buffer, arguments); +} + +module.exports = { + normalizedFunctionString: normalizedFunctionString, + allocBuffer: typeof Buffer.alloc === 'function' ? allocBuffer : newBuffer, + toBuffer: typeof Buffer.from === 'function' ? toBuffer : newBuffer +}; + diff --git a/scripts/node_modules/bson/lib/bson/regexp.js b/scripts/node_modules/bson/lib/bson/regexp.js new file mode 100644 index 00000000..108f0166 --- /dev/null +++ b/scripts/node_modules/bson/lib/bson/regexp.js @@ -0,0 +1,33 @@ +/** + * A class representation of the BSON RegExp type. + * + * @class + * @return {BSONRegExp} A MinKey instance + */ +function BSONRegExp(pattern, options) { + if (!(this instanceof BSONRegExp)) return new BSONRegExp(); + + // Execute + this._bsontype = 'BSONRegExp'; + this.pattern = pattern || ''; + this.options = options || ''; + + // Validate options + for (var i = 0; i < this.options.length; i++) { + if ( + !( + this.options[i] === 'i' || + this.options[i] === 'm' || + this.options[i] === 'x' || + this.options[i] === 'l' || + this.options[i] === 's' || + this.options[i] === 'u' + ) + ) { + throw new Error('the regular expression options [' + this.options[i] + '] is not supported'); + } + } +} + +module.exports = BSONRegExp; +module.exports.BSONRegExp = BSONRegExp; diff --git a/scripts/node_modules/bson/lib/bson/symbol.js b/scripts/node_modules/bson/lib/bson/symbol.js new file mode 100644 index 00000000..ba20cabe --- /dev/null +++ b/scripts/node_modules/bson/lib/bson/symbol.js @@ -0,0 +1,50 @@ +// Custom inspect property name / symbol. +var inspect = Buffer ? require('util').inspect.custom || 'inspect' : 'inspect'; + +/** + * A class representation of the BSON Symbol type. + * + * @class + * @deprecated + * @param {string} value the string representing the symbol. + * @return {Symbol} + */ +function Symbol(value) { + if (!(this instanceof Symbol)) return new Symbol(value); + this._bsontype = 'Symbol'; + this.value = value; +} + +/** + * Access the wrapped string value. + * + * @method + * @return {String} returns the wrapped string. + */ +Symbol.prototype.valueOf = function() { + return this.value; +}; + +/** + * @ignore + */ +Symbol.prototype.toString = function() { + return this.value; +}; + +/** + * @ignore + */ +Symbol.prototype[inspect] = function() { + return this.value; +}; + +/** + * @ignore + */ +Symbol.prototype.toJSON = function() { + return this.value; +}; + +module.exports = Symbol; +module.exports.Symbol = Symbol; diff --git a/scripts/node_modules/bson/lib/bson/timestamp.js b/scripts/node_modules/bson/lib/bson/timestamp.js new file mode 100644 index 00000000..dc61a6cc --- /dev/null +++ b/scripts/node_modules/bson/lib/bson/timestamp.js @@ -0,0 +1,854 @@ +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Copyright 2009 Google Inc. All Rights Reserved + +/** + * This type is for INTERNAL use in MongoDB only and should not be used in applications. + * The appropriate corresponding type is the JavaScript Date type. + * + * Defines a Timestamp class for representing a 64-bit two's-complement + * integer value, which faithfully simulates the behavior of a Java "Timestamp". This + * implementation is derived from TimestampLib in GWT. + * + * Constructs a 64-bit two's-complement integer, given its low and high 32-bit + * values as *signed* integers. See the from* functions below for more + * convenient ways of constructing Timestamps. + * + * The internal representation of a Timestamp is the two given signed, 32-bit values. + * We use 32-bit pieces because these are the size of integers on which + * Javascript performs bit-operations. For operations like addition and + * multiplication, we split each number into 16-bit pieces, which can easily be + * multiplied within Javascript's floating-point representation without overflow + * or change in sign. + * + * In the algorithms below, we frequently reduce the negative case to the + * positive case by negating the input(s) and then post-processing the result. + * Note that we must ALWAYS check specially whether those values are MIN_VALUE + * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as + * a positive number, it overflows back into a negative). Not handling this + * case would often result in infinite recursion. + * + * @class + * @param {number} low the low (signed) 32 bits of the Timestamp. + * @param {number} high the high (signed) 32 bits of the Timestamp. + */ +function Timestamp(low, high) { + if (!(this instanceof Timestamp)) return new Timestamp(low, high); + this._bsontype = 'Timestamp'; + /** + * @type {number} + * @ignore + */ + this.low_ = low | 0; // force into 32 signed bits. + + /** + * @type {number} + * @ignore + */ + this.high_ = high | 0; // force into 32 signed bits. +} + +/** + * Return the int value. + * + * @return {number} the value, assuming it is a 32-bit integer. + */ +Timestamp.prototype.toInt = function() { + return this.low_; +}; + +/** + * Return the Number value. + * + * @method + * @return {number} the closest floating-point representation to this value. + */ +Timestamp.prototype.toNumber = function() { + return this.high_ * Timestamp.TWO_PWR_32_DBL_ + this.getLowBitsUnsigned(); +}; + +/** + * Return the JSON value. + * + * @method + * @return {string} the JSON representation. + */ +Timestamp.prototype.toJSON = function() { + return this.toString(); +}; + +/** + * Return the String value. + * + * @method + * @param {number} [opt_radix] the radix in which the text should be written. + * @return {string} the textual representation of this value. + */ +Timestamp.prototype.toString = function(opt_radix) { + var radix = opt_radix || 10; + if (radix < 2 || 36 < radix) { + throw Error('radix out of range: ' + radix); + } + + if (this.isZero()) { + return '0'; + } + + if (this.isNegative()) { + if (this.equals(Timestamp.MIN_VALUE)) { + // We need to change the Timestamp value before it can be negated, so we remove + // the bottom-most digit in this base and then recurse to do the rest. + var radixTimestamp = Timestamp.fromNumber(radix); + var div = this.div(radixTimestamp); + var rem = div.multiply(radixTimestamp).subtract(this); + return div.toString(radix) + rem.toInt().toString(radix); + } else { + return '-' + this.negate().toString(radix); + } + } + + // Do several (6) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = Timestamp.fromNumber(Math.pow(radix, 6)); + + rem = this; + var result = ''; + + while (!rem.isZero()) { + var remDiv = rem.div(radixToPower); + var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); + var digits = intval.toString(radix); + + rem = remDiv; + if (rem.isZero()) { + return digits + result; + } else { + while (digits.length < 6) { + digits = '0' + digits; + } + result = '' + digits + result; + } + } +}; + +/** + * Return the high 32-bits value. + * + * @method + * @return {number} the high 32-bits as a signed value. + */ +Timestamp.prototype.getHighBits = function() { + return this.high_; +}; + +/** + * Return the low 32-bits value. + * + * @method + * @return {number} the low 32-bits as a signed value. + */ +Timestamp.prototype.getLowBits = function() { + return this.low_; +}; + +/** + * Return the low unsigned 32-bits value. + * + * @method + * @return {number} the low 32-bits as an unsigned value. + */ +Timestamp.prototype.getLowBitsUnsigned = function() { + return this.low_ >= 0 ? this.low_ : Timestamp.TWO_PWR_32_DBL_ + this.low_; +}; + +/** + * Returns the number of bits needed to represent the absolute value of this Timestamp. + * + * @method + * @return {number} Returns the number of bits needed to represent the absolute value of this Timestamp. + */ +Timestamp.prototype.getNumBitsAbs = function() { + if (this.isNegative()) { + if (this.equals(Timestamp.MIN_VALUE)) { + return 64; + } else { + return this.negate().getNumBitsAbs(); + } + } else { + var val = this.high_ !== 0 ? this.high_ : this.low_; + for (var bit = 31; bit > 0; bit--) { + if ((val & (1 << bit)) !== 0) { + break; + } + } + return this.high_ !== 0 ? bit + 33 : bit + 1; + } +}; + +/** + * Return whether this value is zero. + * + * @method + * @return {boolean} whether this value is zero. + */ +Timestamp.prototype.isZero = function() { + return this.high_ === 0 && this.low_ === 0; +}; + +/** + * Return whether this value is negative. + * + * @method + * @return {boolean} whether this value is negative. + */ +Timestamp.prototype.isNegative = function() { + return this.high_ < 0; +}; + +/** + * Return whether this value is odd. + * + * @method + * @return {boolean} whether this value is odd. + */ +Timestamp.prototype.isOdd = function() { + return (this.low_ & 1) === 1; +}; + +/** + * Return whether this Timestamp equals the other + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp equals the other + */ +Timestamp.prototype.equals = function(other) { + return this.high_ === other.high_ && this.low_ === other.low_; +}; + +/** + * Return whether this Timestamp does not equal the other. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp does not equal the other. + */ +Timestamp.prototype.notEquals = function(other) { + return this.high_ !== other.high_ || this.low_ !== other.low_; +}; + +/** + * Return whether this Timestamp is less than the other. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp is less than the other. + */ +Timestamp.prototype.lessThan = function(other) { + return this.compare(other) < 0; +}; + +/** + * Return whether this Timestamp is less than or equal to the other. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp is less than or equal to the other. + */ +Timestamp.prototype.lessThanOrEqual = function(other) { + return this.compare(other) <= 0; +}; + +/** + * Return whether this Timestamp is greater than the other. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp is greater than the other. + */ +Timestamp.prototype.greaterThan = function(other) { + return this.compare(other) > 0; +}; + +/** + * Return whether this Timestamp is greater than or equal to the other. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp is greater than or equal to the other. + */ +Timestamp.prototype.greaterThanOrEqual = function(other) { + return this.compare(other) >= 0; +}; + +/** + * Compares this Timestamp with the given one. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. + */ +Timestamp.prototype.compare = function(other) { + if (this.equals(other)) { + return 0; + } + + var thisNeg = this.isNegative(); + var otherNeg = other.isNegative(); + if (thisNeg && !otherNeg) { + return -1; + } + if (!thisNeg && otherNeg) { + return 1; + } + + // at this point, the signs are the same, so subtraction will not overflow + if (this.subtract(other).isNegative()) { + return -1; + } else { + return 1; + } +}; + +/** + * The negation of this value. + * + * @method + * @return {Timestamp} the negation of this value. + */ +Timestamp.prototype.negate = function() { + if (this.equals(Timestamp.MIN_VALUE)) { + return Timestamp.MIN_VALUE; + } else { + return this.not().add(Timestamp.ONE); + } +}; + +/** + * Returns the sum of this and the given Timestamp. + * + * @method + * @param {Timestamp} other Timestamp to add to this one. + * @return {Timestamp} the sum of this and the given Timestamp. + */ +Timestamp.prototype.add = function(other) { + // Divide each number into 4 chunks of 16 bits, and then sum the chunks. + + var a48 = this.high_ >>> 16; + var a32 = this.high_ & 0xffff; + var a16 = this.low_ >>> 16; + var a00 = this.low_ & 0xffff; + + var b48 = other.high_ >>> 16; + var b32 = other.high_ & 0xffff; + var b16 = other.low_ >>> 16; + var b00 = other.low_ & 0xffff; + + var c48 = 0, + c32 = 0, + c16 = 0, + c00 = 0; + c00 += a00 + b00; + c16 += c00 >>> 16; + c00 &= 0xffff; + c16 += a16 + b16; + c32 += c16 >>> 16; + c16 &= 0xffff; + c32 += a32 + b32; + c48 += c32 >>> 16; + c32 &= 0xffff; + c48 += a48 + b48; + c48 &= 0xffff; + return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32); +}; + +/** + * Returns the difference of this and the given Timestamp. + * + * @method + * @param {Timestamp} other Timestamp to subtract from this. + * @return {Timestamp} the difference of this and the given Timestamp. + */ +Timestamp.prototype.subtract = function(other) { + return this.add(other.negate()); +}; + +/** + * Returns the product of this and the given Timestamp. + * + * @method + * @param {Timestamp} other Timestamp to multiply with this. + * @return {Timestamp} the product of this and the other. + */ +Timestamp.prototype.multiply = function(other) { + if (this.isZero()) { + return Timestamp.ZERO; + } else if (other.isZero()) { + return Timestamp.ZERO; + } + + if (this.equals(Timestamp.MIN_VALUE)) { + return other.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; + } else if (other.equals(Timestamp.MIN_VALUE)) { + return this.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; + } + + if (this.isNegative()) { + if (other.isNegative()) { + return this.negate().multiply(other.negate()); + } else { + return this.negate() + .multiply(other) + .negate(); + } + } else if (other.isNegative()) { + return this.multiply(other.negate()).negate(); + } + + // If both Timestamps are small, use float multiplication + if (this.lessThan(Timestamp.TWO_PWR_24_) && other.lessThan(Timestamp.TWO_PWR_24_)) { + return Timestamp.fromNumber(this.toNumber() * other.toNumber()); + } + + // Divide each Timestamp into 4 chunks of 16 bits, and then add up 4x4 products. + // We can skip products that would overflow. + + var a48 = this.high_ >>> 16; + var a32 = this.high_ & 0xffff; + var a16 = this.low_ >>> 16; + var a00 = this.low_ & 0xffff; + + var b48 = other.high_ >>> 16; + var b32 = other.high_ & 0xffff; + var b16 = other.low_ >>> 16; + var b00 = other.low_ & 0xffff; + + var c48 = 0, + c32 = 0, + c16 = 0, + c00 = 0; + c00 += a00 * b00; + c16 += c00 >>> 16; + c00 &= 0xffff; + c16 += a16 * b00; + c32 += c16 >>> 16; + c16 &= 0xffff; + c16 += a00 * b16; + c32 += c16 >>> 16; + c16 &= 0xffff; + c32 += a32 * b00; + c48 += c32 >>> 16; + c32 &= 0xffff; + c32 += a16 * b16; + c48 += c32 >>> 16; + c32 &= 0xffff; + c32 += a00 * b32; + c48 += c32 >>> 16; + c32 &= 0xffff; + c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; + c48 &= 0xffff; + return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32); +}; + +/** + * Returns this Timestamp divided by the given one. + * + * @method + * @param {Timestamp} other Timestamp by which to divide. + * @return {Timestamp} this Timestamp divided by the given one. + */ +Timestamp.prototype.div = function(other) { + if (other.isZero()) { + throw Error('division by zero'); + } else if (this.isZero()) { + return Timestamp.ZERO; + } + + if (this.equals(Timestamp.MIN_VALUE)) { + if (other.equals(Timestamp.ONE) || other.equals(Timestamp.NEG_ONE)) { + return Timestamp.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE + } else if (other.equals(Timestamp.MIN_VALUE)) { + return Timestamp.ONE; + } else { + // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. + var halfThis = this.shiftRight(1); + var approx = halfThis.div(other).shiftLeft(1); + if (approx.equals(Timestamp.ZERO)) { + return other.isNegative() ? Timestamp.ONE : Timestamp.NEG_ONE; + } else { + var rem = this.subtract(other.multiply(approx)); + var result = approx.add(rem.div(other)); + return result; + } + } + } else if (other.equals(Timestamp.MIN_VALUE)) { + return Timestamp.ZERO; + } + + if (this.isNegative()) { + if (other.isNegative()) { + return this.negate().div(other.negate()); + } else { + return this.negate() + .div(other) + .negate(); + } + } else if (other.isNegative()) { + return this.div(other.negate()).negate(); + } + + // Repeat the following until the remainder is less than other: find a + // floating-point that approximates remainder / other *from below*, add this + // into the result, and subtract it from the remainder. It is critical that + // the approximate value is less than or equal to the real value so that the + // remainder never becomes negative. + var res = Timestamp.ZERO; + rem = this; + while (rem.greaterThanOrEqual(other)) { + // Approximate the result of division. This may be a little greater or + // smaller than the actual value. + approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); + + // We will tweak the approximate result by changing it in the 48-th digit or + // the smallest non-fractional digit, whichever is larger. + var log2 = Math.ceil(Math.log(approx) / Math.LN2); + var delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48); + + // Decrease the approximation until it is smaller than the remainder. Note + // that if it is too large, the product overflows and is negative. + var approxRes = Timestamp.fromNumber(approx); + var approxRem = approxRes.multiply(other); + while (approxRem.isNegative() || approxRem.greaterThan(rem)) { + approx -= delta; + approxRes = Timestamp.fromNumber(approx); + approxRem = approxRes.multiply(other); + } + + // We know the answer can't be zero... and actually, zero would cause + // infinite recursion since we would make no progress. + if (approxRes.isZero()) { + approxRes = Timestamp.ONE; + } + + res = res.add(approxRes); + rem = rem.subtract(approxRem); + } + return res; +}; + +/** + * Returns this Timestamp modulo the given one. + * + * @method + * @param {Timestamp} other Timestamp by which to mod. + * @return {Timestamp} this Timestamp modulo the given one. + */ +Timestamp.prototype.modulo = function(other) { + return this.subtract(this.div(other).multiply(other)); +}; + +/** + * The bitwise-NOT of this value. + * + * @method + * @return {Timestamp} the bitwise-NOT of this value. + */ +Timestamp.prototype.not = function() { + return Timestamp.fromBits(~this.low_, ~this.high_); +}; + +/** + * Returns the bitwise-AND of this Timestamp and the given one. + * + * @method + * @param {Timestamp} other the Timestamp with which to AND. + * @return {Timestamp} the bitwise-AND of this and the other. + */ +Timestamp.prototype.and = function(other) { + return Timestamp.fromBits(this.low_ & other.low_, this.high_ & other.high_); +}; + +/** + * Returns the bitwise-OR of this Timestamp and the given one. + * + * @method + * @param {Timestamp} other the Timestamp with which to OR. + * @return {Timestamp} the bitwise-OR of this and the other. + */ +Timestamp.prototype.or = function(other) { + return Timestamp.fromBits(this.low_ | other.low_, this.high_ | other.high_); +}; + +/** + * Returns the bitwise-XOR of this Timestamp and the given one. + * + * @method + * @param {Timestamp} other the Timestamp with which to XOR. + * @return {Timestamp} the bitwise-XOR of this and the other. + */ +Timestamp.prototype.xor = function(other) { + return Timestamp.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); +}; + +/** + * Returns this Timestamp with bits shifted to the left by the given amount. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Timestamp} this shifted to the left by the given amount. + */ +Timestamp.prototype.shiftLeft = function(numBits) { + numBits &= 63; + if (numBits === 0) { + return this; + } else { + var low = this.low_; + if (numBits < 32) { + var high = this.high_; + return Timestamp.fromBits(low << numBits, (high << numBits) | (low >>> (32 - numBits))); + } else { + return Timestamp.fromBits(0, low << (numBits - 32)); + } + } +}; + +/** + * Returns this Timestamp with bits shifted to the right by the given amount. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Timestamp} this shifted to the right by the given amount. + */ +Timestamp.prototype.shiftRight = function(numBits) { + numBits &= 63; + if (numBits === 0) { + return this; + } else { + var high = this.high_; + if (numBits < 32) { + var low = this.low_; + return Timestamp.fromBits((low >>> numBits) | (high << (32 - numBits)), high >> numBits); + } else { + return Timestamp.fromBits(high >> (numBits - 32), high >= 0 ? 0 : -1); + } + } +}; + +/** + * Returns this Timestamp with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Timestamp} this shifted to the right by the given amount, with zeros placed into the new leading bits. + */ +Timestamp.prototype.shiftRightUnsigned = function(numBits) { + numBits &= 63; + if (numBits === 0) { + return this; + } else { + var high = this.high_; + if (numBits < 32) { + var low = this.low_; + return Timestamp.fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits); + } else if (numBits === 32) { + return Timestamp.fromBits(high, 0); + } else { + return Timestamp.fromBits(high >>> (numBits - 32), 0); + } + } +}; + +/** + * Returns a Timestamp representing the given (32-bit) integer value. + * + * @method + * @param {number} value the 32-bit integer in question. + * @return {Timestamp} the corresponding Timestamp value. + */ +Timestamp.fromInt = function(value) { + if (-128 <= value && value < 128) { + var cachedObj = Timestamp.INT_CACHE_[value]; + if (cachedObj) { + return cachedObj; + } + } + + var obj = new Timestamp(value | 0, value < 0 ? -1 : 0); + if (-128 <= value && value < 128) { + Timestamp.INT_CACHE_[value] = obj; + } + return obj; +}; + +/** + * Returns a Timestamp representing the given value, provided that it is a finite number. Otherwise, zero is returned. + * + * @method + * @param {number} value the number in question. + * @return {Timestamp} the corresponding Timestamp value. + */ +Timestamp.fromNumber = function(value) { + if (isNaN(value) || !isFinite(value)) { + return Timestamp.ZERO; + } else if (value <= -Timestamp.TWO_PWR_63_DBL_) { + return Timestamp.MIN_VALUE; + } else if (value + 1 >= Timestamp.TWO_PWR_63_DBL_) { + return Timestamp.MAX_VALUE; + } else if (value < 0) { + return Timestamp.fromNumber(-value).negate(); + } else { + return new Timestamp( + (value % Timestamp.TWO_PWR_32_DBL_) | 0, + (value / Timestamp.TWO_PWR_32_DBL_) | 0 + ); + } +}; + +/** + * Returns a Timestamp representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. + * + * @method + * @param {number} lowBits the low 32-bits. + * @param {number} highBits the high 32-bits. + * @return {Timestamp} the corresponding Timestamp value. + */ +Timestamp.fromBits = function(lowBits, highBits) { + return new Timestamp(lowBits, highBits); +}; + +/** + * Returns a Timestamp representation of the given string, written using the given radix. + * + * @method + * @param {string} str the textual representation of the Timestamp. + * @param {number} opt_radix the radix in which the text is written. + * @return {Timestamp} the corresponding Timestamp value. + */ +Timestamp.fromString = function(str, opt_radix) { + if (str.length === 0) { + throw Error('number format error: empty string'); + } + + var radix = opt_radix || 10; + if (radix < 2 || 36 < radix) { + throw Error('radix out of range: ' + radix); + } + + if (str.charAt(0) === '-') { + return Timestamp.fromString(str.substring(1), radix).negate(); + } else if (str.indexOf('-') >= 0) { + throw Error('number format error: interior "-" character: ' + str); + } + + // Do several (8) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = Timestamp.fromNumber(Math.pow(radix, 8)); + + var result = Timestamp.ZERO; + for (var i = 0; i < str.length; i += 8) { + var size = Math.min(8, str.length - i); + var value = parseInt(str.substring(i, i + size), radix); + if (size < 8) { + var power = Timestamp.fromNumber(Math.pow(radix, size)); + result = result.multiply(power).add(Timestamp.fromNumber(value)); + } else { + result = result.multiply(radixToPower); + result = result.add(Timestamp.fromNumber(value)); + } + } + return result; +}; + +// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the +// from* methods on which they depend. + +/** + * A cache of the Timestamp representations of small integer values. + * @type {Object} + * @ignore + */ +Timestamp.INT_CACHE_ = {}; + +// NOTE: the compiler should inline these constant values below and then remove +// these variables, so there should be no runtime penalty for these. + +/** + * Number used repeated below in calculations. This must appear before the + * first call to any from* function below. + * @type {number} + * @ignore + */ +Timestamp.TWO_PWR_16_DBL_ = 1 << 16; + +/** + * @type {number} + * @ignore + */ +Timestamp.TWO_PWR_24_DBL_ = 1 << 24; + +/** + * @type {number} + * @ignore + */ +Timestamp.TWO_PWR_32_DBL_ = Timestamp.TWO_PWR_16_DBL_ * Timestamp.TWO_PWR_16_DBL_; + +/** + * @type {number} + * @ignore + */ +Timestamp.TWO_PWR_31_DBL_ = Timestamp.TWO_PWR_32_DBL_ / 2; + +/** + * @type {number} + * @ignore + */ +Timestamp.TWO_PWR_48_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_16_DBL_; + +/** + * @type {number} + * @ignore + */ +Timestamp.TWO_PWR_64_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_32_DBL_; + +/** + * @type {number} + * @ignore + */ +Timestamp.TWO_PWR_63_DBL_ = Timestamp.TWO_PWR_64_DBL_ / 2; + +/** @type {Timestamp} */ +Timestamp.ZERO = Timestamp.fromInt(0); + +/** @type {Timestamp} */ +Timestamp.ONE = Timestamp.fromInt(1); + +/** @type {Timestamp} */ +Timestamp.NEG_ONE = Timestamp.fromInt(-1); + +/** @type {Timestamp} */ +Timestamp.MAX_VALUE = Timestamp.fromBits(0xffffffff | 0, 0x7fffffff | 0); + +/** @type {Timestamp} */ +Timestamp.MIN_VALUE = Timestamp.fromBits(0, 0x80000000 | 0); + +/** + * @type {Timestamp} + * @ignore + */ +Timestamp.TWO_PWR_24_ = Timestamp.fromInt(1 << 24); + +/** + * Expose. + */ +module.exports = Timestamp; +module.exports.Timestamp = Timestamp; diff --git a/scripts/node_modules/bson/package.json b/scripts/node_modules/bson/package.json new file mode 100644 index 00000000..d37778ab --- /dev/null +++ b/scripts/node_modules/bson/package.json @@ -0,0 +1,87 @@ +{ + "_from": "bson@^1.1.1", + "_id": "bson@1.1.1", + "_inBundle": false, + "_integrity": "sha512-jCGVYLoYMHDkOsbwJZBCqwMHyH4c+wzgI9hG7Z6SZJRXWr+x58pdIbm2i9a/jFGCkRJqRUr8eoI7lDWa0hTkxg==", + "_location": "/bson", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "bson@^1.1.1", + "name": "bson", + "escapedName": "bson", + "rawSpec": "^1.1.1", + "saveSpec": null, + "fetchSpec": "^1.1.1" + }, + "_requiredBy": [ + "/mongodb" + ], + "_resolved": "https://registry.npmjs.org/bson/-/bson-1.1.1.tgz", + "_shasum": "4330f5e99104c4e751e7351859e2d408279f2f13", + "_spec": "bson@^1.1.1", + "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/node_modules/mongodb", + "author": { + "name": "Christian Amor Kvalheim", + "email": "christkv@gmail.com" + }, + "browser": "lib/bson/bson.js", + "bugs": { + "url": "https://github.com/mongodb/js-bson/issues" + }, + "bundleDependencies": false, + "config": { + "native": false + }, + "contributors": [], + "deprecated": false, + "description": "A bson parser for node.js and the browser", + "devDependencies": { + "babel-core": "^6.14.0", + "babel-loader": "^6.2.5", + "babel-polyfill": "^6.13.0", + "babel-preset-es2015": "^6.14.0", + "babel-preset-stage-0": "^6.5.0", + "babel-register": "^6.14.0", + "benchmark": "1.0.0", + "colors": "1.1.0", + "conventional-changelog-cli": "^1.3.5", + "nodeunit": "0.9.0", + "webpack": "^1.13.2", + "webpack-polyfills-plugin": "0.0.9" + }, + "directories": { + "lib": "./lib/bson" + }, + "engines": { + "node": ">=0.6.19" + }, + "files": [ + "lib", + "index.js", + "browser_build", + "bower.json" + ], + "homepage": "https://github.com/mongodb/js-bson#readme", + "keywords": [ + "mongodb", + "bson", + "parser" + ], + "license": "Apache-2.0", + "main": "./index", + "name": "bson", + "repository": { + "type": "git", + "url": "git+https://github.com/mongodb/js-bson.git" + }, + "scripts": { + "build": "webpack --config ./webpack.dist.config.js", + "changelog": "conventional-changelog -p angular -i HISTORY.md -s", + "format": "prettier --print-width 100 --tab-width 2 --single-quote --write 'test/**/*.js' 'lib/**/*.js'", + "lint": "eslint lib test", + "test": "nodeunit ./test/node" + }, + "version": "1.1.1" +} diff --git a/scripts/node_modules/memory-pager/.travis.yml b/scripts/node_modules/memory-pager/.travis.yml new file mode 100644 index 00000000..1c4ab31e --- /dev/null +++ b/scripts/node_modules/memory-pager/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - '4' + - '6' diff --git a/scripts/node_modules/memory-pager/LICENSE b/scripts/node_modules/memory-pager/LICENSE new file mode 100644 index 00000000..56fce089 --- /dev/null +++ b/scripts/node_modules/memory-pager/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2017 Mathias Buus + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/scripts/node_modules/memory-pager/README.md b/scripts/node_modules/memory-pager/README.md new file mode 100644 index 00000000..aed17614 --- /dev/null +++ b/scripts/node_modules/memory-pager/README.md @@ -0,0 +1,65 @@ +# memory-pager + +Access memory using small fixed sized buffers instead of allocating a huge buffer. +Useful if you are implementing sparse data structures (such as large bitfield). + +![travis](https://travis-ci.org/mafintosh/memory-pager.svg?branch=master) + +``` +npm install memory-pager +``` + +## Usage + +``` js +var pager = require('paged-memory') + +var pages = pager(1024) // use 1kb per page + +var page = pages.get(10) // get page #10 + +console.log(page.offset) // 10240 +console.log(page.buffer) // a blank 1kb buffer +``` + +## API + +#### `var pages = pager(pageSize)` + +Create a new pager. `pageSize` defaults to `1024`. + +#### `var page = pages.get(pageNumber, [noAllocate])` + +Get a page. The page will be allocated at first access. + +Optionally you can set the `noAllocate` flag which will make the +method return undefined if no page has been allocated already + +A page looks like this + +``` js +{ + offset: byteOffset, + buffer: bufferWithPageSize +} +``` + +#### `pages.set(pageNumber, buffer)` + +Explicitly set the buffer for a page. + +#### `pages.updated(page)` + +Mark a page as updated. + +#### `pages.lastUpdate()` + +Get the last page that was updated. + +#### `var buf = pages.toBuffer()` + +Concat all pages allocated pages into a single buffer + +## License + +MIT diff --git a/scripts/node_modules/memory-pager/index.js b/scripts/node_modules/memory-pager/index.js new file mode 100644 index 00000000..687f346f --- /dev/null +++ b/scripts/node_modules/memory-pager/index.js @@ -0,0 +1,160 @@ +module.exports = Pager + +function Pager (pageSize, opts) { + if (!(this instanceof Pager)) return new Pager(pageSize, opts) + + this.length = 0 + this.updates = [] + this.path = new Uint16Array(4) + this.pages = new Array(32768) + this.maxPages = this.pages.length + this.level = 0 + this.pageSize = pageSize || 1024 + this.deduplicate = opts ? opts.deduplicate : null + this.zeros = this.deduplicate ? alloc(this.deduplicate.length) : null +} + +Pager.prototype.updated = function (page) { + while (this.deduplicate && page.buffer[page.deduplicate] === this.deduplicate[page.deduplicate]) { + page.deduplicate++ + if (page.deduplicate === this.deduplicate.length) { + page.deduplicate = 0 + if (page.buffer.equals && page.buffer.equals(this.deduplicate)) page.buffer = this.deduplicate + break + } + } + if (page.updated || !this.updates) return + page.updated = true + this.updates.push(page) +} + +Pager.prototype.lastUpdate = function () { + if (!this.updates || !this.updates.length) return null + var page = this.updates.pop() + page.updated = false + return page +} + +Pager.prototype._array = function (i, noAllocate) { + if (i >= this.maxPages) { + if (noAllocate) return + grow(this, i) + } + + factor(i, this.path) + + var arr = this.pages + + for (var j = this.level; j > 0; j--) { + var p = this.path[j] + var next = arr[p] + + if (!next) { + if (noAllocate) return + next = arr[p] = new Array(32768) + } + + arr = next + } + + return arr +} + +Pager.prototype.get = function (i, noAllocate) { + var arr = this._array(i, noAllocate) + var first = this.path[0] + var page = arr && arr[first] + + if (!page && !noAllocate) { + page = arr[first] = new Page(i, alloc(this.pageSize)) + if (i >= this.length) this.length = i + 1 + } + + if (page && page.buffer === this.deduplicate && this.deduplicate && !noAllocate) { + page.buffer = copy(page.buffer) + page.deduplicate = 0 + } + + return page +} + +Pager.prototype.set = function (i, buf) { + var arr = this._array(i, false) + var first = this.path[0] + + if (i >= this.length) this.length = i + 1 + + if (!buf || (this.zeros && buf.equals && buf.equals(this.zeros))) { + arr[first] = undefined + return + } + + if (this.deduplicate && buf.equals && buf.equals(this.deduplicate)) { + buf = this.deduplicate + } + + var page = arr[first] + var b = truncate(buf, this.pageSize) + + if (page) page.buffer = b + else arr[first] = new Page(i, b) +} + +Pager.prototype.toBuffer = function () { + var list = new Array(this.length) + var empty = alloc(this.pageSize) + var ptr = 0 + + while (ptr < list.length) { + var arr = this._array(ptr, true) + for (var i = 0; i < 32768 && ptr < list.length; i++) { + list[ptr++] = (arr && arr[i]) ? arr[i].buffer : empty + } + } + + return Buffer.concat(list) +} + +function grow (pager, index) { + while (pager.maxPages < index) { + var old = pager.pages + pager.pages = new Array(32768) + pager.pages[0] = old + pager.level++ + pager.maxPages *= 32768 + } +} + +function truncate (buf, len) { + if (buf.length === len) return buf + if (buf.length > len) return buf.slice(0, len) + var cpy = alloc(len) + buf.copy(cpy) + return cpy +} + +function alloc (size) { + if (Buffer.alloc) return Buffer.alloc(size) + var buf = new Buffer(size) + buf.fill(0) + return buf +} + +function copy (buf) { + var cpy = Buffer.allocUnsafe ? Buffer.allocUnsafe(buf.length) : new Buffer(buf.length) + buf.copy(cpy) + return cpy +} + +function Page (i, buf) { + this.offset = i * buf.length + this.buffer = buf + this.updated = false + this.deduplicate = 0 +} + +function factor (n, out) { + n = (n - (out[0] = (n & 32767))) / 32768 + n = (n - (out[1] = (n & 32767))) / 32768 + out[3] = ((n - (out[2] = (n & 32767))) / 32768) & 32767 +} diff --git a/scripts/node_modules/memory-pager/package.json b/scripts/node_modules/memory-pager/package.json new file mode 100644 index 00000000..4d426e44 --- /dev/null +++ b/scripts/node_modules/memory-pager/package.json @@ -0,0 +1,52 @@ +{ + "_from": "memory-pager@^1.0.2", + "_id": "memory-pager@1.5.0", + "_inBundle": false, + "_integrity": "sha512-ZS4Bp4r/Zoeq6+NLJpP+0Zzm0pR8whtGPf1XExKLJBAczGMnSi3It14OiNCStjQjM6NU1okjQGSxgEZN8eBYKg==", + "_location": "/memory-pager", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "memory-pager@^1.0.2", + "name": "memory-pager", + "escapedName": "memory-pager", + "rawSpec": "^1.0.2", + "saveSpec": null, + "fetchSpec": "^1.0.2" + }, + "_requiredBy": [ + "/sparse-bitfield" + ], + "_resolved": "https://registry.npmjs.org/memory-pager/-/memory-pager-1.5.0.tgz", + "_shasum": "d8751655d22d384682741c972f2c3d6dfa3e66b5", + "_spec": "memory-pager@^1.0.2", + "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/node_modules/sparse-bitfield", + "author": { + "name": "Mathias Buus", + "url": "@mafintosh" + }, + "bugs": { + "url": "https://github.com/mafintosh/memory-pager/issues" + }, + "bundleDependencies": false, + "dependencies": {}, + "deprecated": false, + "description": "Access memory using small fixed sized buffers", + "devDependencies": { + "standard": "^9.0.0", + "tape": "^4.6.3" + }, + "homepage": "https://github.com/mafintosh/memory-pager", + "license": "MIT", + "main": "index.js", + "name": "memory-pager", + "repository": { + "type": "git", + "url": "git+https://github.com/mafintosh/memory-pager.git" + }, + "scripts": { + "test": "standard && tape test.js" + }, + "version": "1.5.0" +} diff --git a/scripts/node_modules/memory-pager/test.js b/scripts/node_modules/memory-pager/test.js new file mode 100644 index 00000000..16382100 --- /dev/null +++ b/scripts/node_modules/memory-pager/test.js @@ -0,0 +1,80 @@ +var tape = require('tape') +var pager = require('./') + +tape('get page', function (t) { + var pages = pager(1024) + + var page = pages.get(0) + + t.same(page.offset, 0) + t.same(page.buffer, Buffer.alloc(1024)) + t.end() +}) + +tape('get page twice', function (t) { + var pages = pager(1024) + t.same(pages.length, 0) + + var page = pages.get(0) + + t.same(page.offset, 0) + t.same(page.buffer, Buffer.alloc(1024)) + t.same(pages.length, 1) + + var other = pages.get(0) + + t.same(other, page) + t.end() +}) + +tape('get no mutable page', function (t) { + var pages = pager(1024) + + t.ok(!pages.get(141, true)) + t.ok(pages.get(141)) + t.ok(pages.get(141, true)) + + t.end() +}) + +tape('get far out page', function (t) { + var pages = pager(1024) + + var page = pages.get(1000000) + + t.same(page.offset, 1000000 * 1024) + t.same(page.buffer, Buffer.alloc(1024)) + t.same(pages.length, 1000000 + 1) + + var other = pages.get(1) + + t.same(other.offset, 1024) + t.same(other.buffer, Buffer.alloc(1024)) + t.same(pages.length, 1000000 + 1) + t.ok(other !== page) + + t.end() +}) + +tape('updates', function (t) { + var pages = pager(1024) + + t.same(pages.lastUpdate(), null) + + var page = pages.get(10) + + page.buffer[42] = 1 + pages.updated(page) + + t.same(pages.lastUpdate(), page) + t.same(pages.lastUpdate(), null) + + page.buffer[42] = 2 + pages.updated(page) + pages.updated(page) + + t.same(pages.lastUpdate(), page) + t.same(pages.lastUpdate(), null) + + t.end() +}) diff --git a/scripts/node_modules/mongodb/HISTORY.md b/scripts/node_modules/mongodb/HISTORY.md new file mode 100644 index 00000000..73cbab99 --- /dev/null +++ b/scripts/node_modules/mongodb/HISTORY.md @@ -0,0 +1,2485 @@ +# Change Log + +All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. + + +## [3.3.3](https://github.com/mongodb/node-mongodb-native/compare/v3.3.2...v3.3.3) (2019-10-16) + + +### Bug Fixes + +* **change_stream:** emit 'close' event if reconnecting failed ([f24c084](https://github.com/mongodb/node-mongodb-native/commit/f24c084)) +* **ChangeStream:** remove startAtOperationTime once we have resumeToken ([362afd8](https://github.com/mongodb/node-mongodb-native/commit/362afd8)) +* **connect:** Switch new Buffer(size) -> Buffer.alloc(size) ([da90c3a](https://github.com/mongodb/node-mongodb-native/commit/da90c3a)) +* **MongoClient:** only check own properties for valid options ([9cde4b9](https://github.com/mongodb/node-mongodb-native/commit/9cde4b9)) +* **mongos:** disconnect proxies which are not mongos instances ([ee53983](https://github.com/mongodb/node-mongodb-native/commit/ee53983)) +* **mongos:** force close servers during reconnect flow ([186263f](https://github.com/mongodb/node-mongodb-native/commit/186263f)) +* **monitoring:** correct spelling mistake for heartbeat event ([21aa117](https://github.com/mongodb/node-mongodb-native/commit/21aa117)) +* **replset:** correct server leak on initial connect ([da39d1e](https://github.com/mongodb/node-mongodb-native/commit/da39d1e)) +* **replset:** destroy primary before removing from replsetstate ([45ac09a](https://github.com/mongodb/node-mongodb-native/commit/45ac09a)) +* **replset:** destroy servers that are removed during SDAM flow ([9ea0190](https://github.com/mongodb/node-mongodb-native/commit/9ea0190)) +* **saslprep:** add in missing saslprep dependency ([41f1165](https://github.com/mongodb/node-mongodb-native/commit/41f1165)) +* **topology:** don't early abort server selection on network errors ([2b6a359](https://github.com/mongodb/node-mongodb-native/commit/2b6a359)) +* **topology:** don't emit server closed event on network error ([194dcf0](https://github.com/mongodb/node-mongodb-native/commit/194dcf0)) +* **topology:** include all BSON types in ctor for bson-ext support ([aa4c832](https://github.com/mongodb/node-mongodb-native/commit/aa4c832)) +* **topology:** respect the `force` parameter for topology close ([d6e8936](https://github.com/mongodb/node-mongodb-native/commit/d6e8936)) + +### Features + +* **Update:** add the ability to specify a pipeline to an update command ([#2017](https://github.com/mongodb/node-mongodb-native/issues/2017)) ([44a4110](https://github.com/mongodb/node-mongodb-native/commit/44a4110)) +* **urlParser:** default useNewUrlParser to true ([52d76e3](https://github.com/mongodb/node-mongodb-native/commit/52d76e3)) + + +## [3.2.7](https://github.com/mongodb/node-mongodb-native/compare/v3.2.6...v3.2.7) (2019-06-04) + + +### Bug Fixes + +* **core:** updating core to version 3.2.7 ([2f91466](https://github.com/mongodb/node-mongodb-native/commit/2f91466)) +* **findOneAndReplace:** throw error if atomic operators provided for findOneAndReplace ([6a860a3](https://github.com/mongodb/node-mongodb-native/commit/6a860a3)) + + + + +## [3.3.2](https://github.com/mongodb/node-mongodb-native/compare/v3.3.1...v3.3.2) (2019-08-28) + + +### Bug Fixes + +* **change-stream:** default to server default batch size ([b3ae4c5](https://github.com/mongodb/node-mongodb-native/commit/b3ae4c5)) +* **execute-operation:** return promise on session support check ([a976c14](https://github.com/mongodb/node-mongodb-native/commit/a976c14)) +* **gridfs-stream:** ensure `close` is emitted after last chunk ([ae94cb9](https://github.com/mongodb/node-mongodb-native/commit/ae94cb9)) + + + + +## [3.3.1](https://github.com/mongodb/node-mongodb-native/compare/v3.3.0...v3.3.1) (2019-08-23) + + +### Bug Fixes + +* **find:** respect client-level provided read preference ([fec4f15](https://github.com/mongodb/node-mongodb-native/commit/fec4f15)) +* correct inverted defaults for unified topology ([cf598e1](https://github.com/mongodb/node-mongodb-native/commit/cf598e1)) + + + + +# [3.3.0](https://github.com/mongodb/node-mongodb-native/compare/v3.3.0-alpha1...v3.3.0) (2019-08-13) + + +### Bug Fixes + +* **aggregate-operation:** move type assertions to constructor ([25b27ff](https://github.com/mongodb/node-mongodb-native/commit/25b27ff)) +* **autoEncryption:** tear down mongocryptd client when main client closes ([fe2f57e](https://github.com/mongodb/node-mongodb-native/commit/fe2f57e)) +* **autoEncryption:** use new url parser for autoEncryption client ([d3670c2](https://github.com/mongodb/node-mongodb-native/commit/d3670c2)) +* **Bulk:** change BulkWriteError message to first item from writeErrors ([#2013](https://github.com/mongodb/node-mongodb-native/issues/2013)) ([6bcf1e4](https://github.com/mongodb/node-mongodb-native/commit/6bcf1e4)) +* **change_stream:** emit 'close' event if reconnecting failed ([41aba90](https://github.com/mongodb/node-mongodb-native/commit/41aba90)) +* **change_stream:** emit close event after cursor is closed during error ([c2d80b2](https://github.com/mongodb/node-mongodb-native/commit/c2d80b2)) +* **change-streams:** don't copy irrelevant resume options ([f190072](https://github.com/mongodb/node-mongodb-native/commit/f190072)) +* **changestream:** removes all event listeners on close ([30eeeb5](https://github.com/mongodb/node-mongodb-native/commit/30eeeb5)) +* **ChangeStream:** remove startAtOperationTime once we have resumeToken ([8d27e6e](https://github.com/mongodb/node-mongodb-native/commit/8d27e6e)) +* **ClientSessions:** initialize clientOptions and cluster time ([b95d64e](https://github.com/mongodb/node-mongodb-native/commit/b95d64e)) +* **connect:** don't treat 'connect' as an error event ([170a011](https://github.com/mongodb/node-mongodb-native/commit/170a011)) +* **connect:** fixed syntax issue in connect error handler ([ff7166d](https://github.com/mongodb/node-mongodb-native/commit/ff7166d)) +* **connections_stepdown_tests:** use correct version of mongo for tests ([ce2c9af](https://github.com/mongodb/node-mongodb-native/commit/ce2c9af)) +* **createCollection:** Db.createCollection should pass readConcern to new collection ([#2026](https://github.com/mongodb/node-mongodb-native/issues/2026)) ([6145d4b](https://github.com/mongodb/node-mongodb-native/commit/6145d4b)) +* **cursor:** do not truncate an existing Long ([317055b](https://github.com/mongodb/node-mongodb-native/commit/317055b)), closes [mongodb-js/mongodb-core#441](https://github.com/mongodb-js/mongodb-core/issues/441) +* **distinct:** return full response if `full` option was specified ([95a7d05](https://github.com/mongodb/node-mongodb-native/commit/95a7d05)) +* **MongoClient:** allow Object.prototype items as db names ([dc6fc37](https://github.com/mongodb/node-mongodb-native/commit/dc6fc37)) +* **MongoClient:** only check own properties for valid options ([c9dc717](https://github.com/mongodb/node-mongodb-native/commit/c9dc717)) +* **OpMsg:** cap requestIds at 0x7fffffff ([c0e87d5](https://github.com/mongodb/node-mongodb-native/commit/c0e87d5)) +* **read-operations:** send sessions on all read operations ([4d45c8a](https://github.com/mongodb/node-mongodb-native/commit/4d45c8a)) +* **ReadPreference:** improve ReadPreference error message and remove irrelevant sharding test ([dd34ce4](https://github.com/mongodb/node-mongodb-native/commit/dd34ce4)) +* **ReadPreference:** only allow valid ReadPreference modes ([06bbef2](https://github.com/mongodb/node-mongodb-native/commit/06bbef2)) +* **replset:** correct legacy max staleness calculation ([2eab8aa](https://github.com/mongodb/node-mongodb-native/commit/2eab8aa)) +* **replset:** introduce a fixed-time server selection loop ([cf53299](https://github.com/mongodb/node-mongodb-native/commit/cf53299)) +* **server:** emit "first connect" error if initial connect fails due to ECONNREFUSED ([#2016](https://github.com/mongodb/node-mongodb-native/issues/2016)) ([5a7b15b](https://github.com/mongodb/node-mongodb-native/commit/5a7b15b)) +* **serverSelection:** make sure to pass session to serverSelection ([eb5cc6b](https://github.com/mongodb/node-mongodb-native/commit/eb5cc6b)) +* **sessions:** ensure an error is thrown when attempting sharded transactions ([3a1fdc1](https://github.com/mongodb/node-mongodb-native/commit/3a1fdc1)) +* **topology:** add new error for retryWrites on MMAPv1 ([392f5a6](https://github.com/mongodb/node-mongodb-native/commit/392f5a6)) +* don't check non-unified topologies for session support check ([2bccd3f](https://github.com/mongodb/node-mongodb-native/commit/2bccd3f)) +* maintain internal database name on collection rename ([884d46f](https://github.com/mongodb/node-mongodb-native/commit/884d46f)) +* only check for transaction state if session exists ([360975a](https://github.com/mongodb/node-mongodb-native/commit/360975a)) +* preserve aggregate explain support for legacy servers ([032b204](https://github.com/mongodb/node-mongodb-native/commit/032b204)) +* read concern only supported for `mapReduce` without inline ([51a36f3](https://github.com/mongodb/node-mongodb-native/commit/51a36f3)) +* reintroduce support for 2.6 listIndexes ([c3bfc05](https://github.com/mongodb/node-mongodb-native/commit/c3bfc05)) +* return `executeOperation` for explain, if promise is desired ([b4a7ad7](https://github.com/mongodb/node-mongodb-native/commit/b4a7ad7)) +* validate atomic operations in all update methods ([88bb77e](https://github.com/mongodb/node-mongodb-native/commit/88bb77e)) +* **transactions:** fix error message for attempting sharded ([eb5dfc9](https://github.com/mongodb/node-mongodb-native/commit/eb5dfc9)) +* **transactions:** fix sharded transaction error logic ([083e18a](https://github.com/mongodb/node-mongodb-native/commit/083e18a)) + + +### Features + +* **Aggregate:** support ReadConcern in aggregates with $out ([21cdcf0](https://github.com/mongodb/node-mongodb-native/commit/21cdcf0)) +* **AutoEncryption:** improve error message for missing mongodb-client-encryption ([583f29f](https://github.com/mongodb/node-mongodb-native/commit/583f29f)) +* **ChangeStream:** adds new resume functionality to ChangeStreams ([9ec9b8f](https://github.com/mongodb/node-mongodb-native/commit/9ec9b8f)) +* **ChangeStreamCursor:** introduce new cursor type for change streams ([8813eb0](https://github.com/mongodb/node-mongodb-native/commit/8813eb0)) +* **cryptdConnectionString:** makes mongocryptd uri configurable ([#2049](https://github.com/mongodb/node-mongodb-native/issues/2049)) ([a487be4](https://github.com/mongodb/node-mongodb-native/commit/a487be4)) +* **eachAsync:** dedupe async iteration with a common helper ([c296f3a](https://github.com/mongodb/node-mongodb-native/commit/c296f3a)) +* **execute-operation:** allow execution with server selection ([36bc1fd](https://github.com/mongodb/node-mongodb-native/commit/36bc1fd)) +* **pool:** add support for resetting the connection pool ([2d1ff40](https://github.com/mongodb/node-mongodb-native/commit/2d1ff40)) +* **sessions:** track dirty state of sessions, drop after use ([f61df16](https://github.com/mongodb/node-mongodb-native/commit/f61df16)) +* add concept of `data-bearing` type to `ServerDescription` ([852e14f](https://github.com/mongodb/node-mongodb-native/commit/852e14f)) +* **transaction:** allow applications to set maxTimeMS for commitTransaction ([b3948aa](https://github.com/mongodb/node-mongodb-native/commit/b3948aa)) +* **Update:** add the ability to specify a pipeline to an update command ([#2017](https://github.com/mongodb/node-mongodb-native/issues/2017)) ([dc1387e](https://github.com/mongodb/node-mongodb-native/commit/dc1387e)) +* add `known`, `data-bearing` filters to `TopologyDescription` ([d0ccb56](https://github.com/mongodb/node-mongodb-native/commit/d0ccb56)) +* perform selection before cursor operation execution if needed ([808cf37](https://github.com/mongodb/node-mongodb-native/commit/808cf37)) +* perform selection before operation execution if needed ([1a25876](https://github.com/mongodb/node-mongodb-native/commit/1a25876)) +* support explain operations in `CommandOperationV2` ([86f5ba5](https://github.com/mongodb/node-mongodb-native/commit/86f5ba5)) +* support operations passed to a `Cursor` or subclass ([b78bb89](https://github.com/mongodb/node-mongodb-native/commit/b78bb89)) + + + + +## [3.2.7](https://github.com/mongodb/node-mongodb-native/compare/v3.2.6...v3.2.7) (2019-06-04) + + +### Bug Fixes + +* **core:** updating core to version 3.2.7 ([2f91466](https://github.com/mongodb/node-mongodb-native/commit/2f91466)) +* **findOneAndReplace:** throw error if atomic operators provided for findOneAndReplace ([6a860a3](https://github.com/mongodb/node-mongodb-native/commit/6a860a3)) + + + + +## [3.2.6](https://github.com/mongodb/node-mongodb-native/compare/v3.2.5...v3.2.6) (2019-05-24) + + + + +## [3.2.5](https://github.com/mongodb/node-mongodb-native/compare/v3.2.4...v3.2.5) (2019-05-17) + + +### Bug Fixes + +* **core:** updating core to 3.2.5 ([a2766c1](https://github.com/mongodb/node-mongodb-native/commit/a2766c1)) + + + + +## [3.2.4](https://github.com/mongodb/node-mongodb-native/compare/v3.2.2...v3.2.4) (2019-05-08) + + +### Bug Fixes + +* **aggregation:** fix field name typo ([4235d04](https://github.com/mongodb/node-mongodb-native/commit/4235d04)) +* **async:** rewrote asyncGenerator in node < 10 syntax ([49c8cef](https://github.com/mongodb/node-mongodb-native/commit/49c8cef)) +* **BulkOp:** run unordered bulk ops in serial ([f548bd7](https://github.com/mongodb/node-mongodb-native/commit/f548bd7)) +* **bulkWrite:** fix issue with bulkWrite continuing w/ callback ([2a4a42c](https://github.com/mongodb/node-mongodb-native/commit/2a4a42c)) +* **docs:** correctly document that default for `sslValidate` is false ([1f8e7fa](https://github.com/mongodb/node-mongodb-native/commit/1f8e7fa)) +* **gridfs-stream:** honor chunk size ([9eeb114](https://github.com/mongodb/node-mongodb-native/commit/9eeb114)) +* **unified-topology:** only clone pool size if provided ([8dc2416](https://github.com/mongodb/node-mongodb-native/commit/8dc2416)) + + +### Features + +* update to mongodb-core v3.2.3 ([1c5357a](https://github.com/mongodb/node-mongodb-native/commit/1c5357a)) +* **core:** update to mongodb-core v3.2.4 ([2059260](https://github.com/mongodb/node-mongodb-native/commit/2059260)) +* **lib:** implement executeOperationV2 ([67d4edf](https://github.com/mongodb/node-mongodb-native/commit/67d4edf)) + + + + +## [3.2.3](https://github.com/mongodb/node-mongodb-native/compare/v3.2.2...v3.2.3) (2019-04-05) + + +### Bug Fixes + +* **aggregation:** fix field name typo ([4235d04](https://github.com/mongodb/node-mongodb-native/commit/4235d04)) +* **async:** rewrote asyncGenerator in node < 10 syntax ([49c8cef](https://github.com/mongodb/node-mongodb-native/commit/49c8cef)) +* **bulkWrite:** fix issue with bulkWrite continuing w/ callback ([2a4a42c](https://github.com/mongodb/node-mongodb-native/commit/2a4a42c)) +* **docs:** correctly document that default for `sslValidate` is false ([1f8e7fa](https://github.com/mongodb/node-mongodb-native/commit/1f8e7fa)) + + +### Features + +* update to mongodb-core v3.2.3 ([1c5357a](https://github.com/mongodb/node-mongodb-native/commit/1c5357a)) + + + + +## [3.2.2](https://github.com/mongodb/node-mongodb-native/compare/v3.2.1...v3.2.2) (2019-03-22) + + +### Bug Fixes + +* **asyncIterator:** stronger guard against importing async generator ([e0826fb](https://github.com/mongodb/node-mongodb-native/commit/e0826fb)) + + +### Features + +* update to mongodb-core v3.2.2 ([868cfc3](https://github.com/mongodb/node-mongodb-native/commit/868cfc3)) + + + + +## [3.2.1](https://github.com/mongodb/node-mongodb-native/compare/v3.2.0...v3.2.1) (2019-03-21) + + +### Features + +* **core:** update to mongodb-core v3.2.1 ([30b0100](https://github.com/mongodb/node-mongodb-native/commit/30b0100)) + + + + +# [3.2.0](https://github.com/mongodb/node-mongodb-native/compare/v3.1.13...v3.2.0) (2019-03-21) + + +### Bug Fixes + +* **aggregate:** do not send batchSize for aggregation with $out ([ddb8d90](https://github.com/mongodb/node-mongodb-native/commit/ddb8d90)) +* **bulkWrite:** always count undefined values in bson size for bulk ([436d340](https://github.com/mongodb/node-mongodb-native/commit/436d340)) +* **db_ops:** rename db to add user on ([79931af](https://github.com/mongodb/node-mongodb-native/commit/79931af)) +* **mongo_client_ops:** only skip authentication if no authMechanism is specified ([3b6957d](https://github.com/mongodb/node-mongodb-native/commit/3b6957d)) +* **mongo-client:** ensure close callback is called with client ([f39e881](https://github.com/mongodb/node-mongodb-native/commit/f39e881)) + + +### Features + +* **core:** pin to mongodb-core v3.2.0 ([22af15a](https://github.com/mongodb/node-mongodb-native/commit/22af15a)) +* **Cursor:** adds support for AsyncIterator in cursors ([b972c1e](https://github.com/mongodb/node-mongodb-native/commit/b972c1e)) +* **db:** add database-level aggregation ([b629b21](https://github.com/mongodb/node-mongodb-native/commit/b629b21)) +* **mongo-client:** remove deprecated `logout` and print warning ([542859d](https://github.com/mongodb/node-mongodb-native/commit/542859d)) +* **topology-base:** support passing callbacks to `close` method ([7c111e0](https://github.com/mongodb/node-mongodb-native/commit/7c111e0)) +* **transactions:** support pinning mongos for sharded txns ([3886127](https://github.com/mongodb/node-mongodb-native/commit/3886127)) +* **unified-sdam:** backport unified SDAM to master for v3.2.0 ([79f33ca](https://github.com/mongodb/node-mongodb-native/commit/79f33ca)) + + + + +## [3.1.13](https://github.com/mongodb/node-mongodb-native/compare/v3.1.12...v3.1.13) (2019-01-23) + + +### Bug Fixes + +* restore ability to webpack by removing `makeLazyLoader` ([050267d](https://github.com/mongodb/node-mongodb-native/commit/050267d)) +* **bulk:** honor ignoreUndefined in initializeUnorderedBulkOp ([e806be4](https://github.com/mongodb/node-mongodb-native/commit/e806be4)) +* **changeStream:** properly handle changeStream event mid-close ([#1902](https://github.com/mongodb/node-mongodb-native/issues/1902)) ([5ad9fa9](https://github.com/mongodb/node-mongodb-native/commit/5ad9fa9)) +* **db_ops:** ensure we async resolve errors in createCollection ([210c71d](https://github.com/mongodb/node-mongodb-native/commit/210c71d)) + + + + +## [3.1.12](https://github.com/mongodb/node-mongodb-native/compare/v3.1.11...v3.1.12) (2019-01-16) + + +### Features + +* **core:** update to mongodb-core v3.1.11 ([9bef6e7](https://github.com/mongodb/node-mongodb-native/commit/9bef6e7)) + + + + +## [3.1.11](https://github.com/mongodb/node-mongodb-native/compare/v3.1.10...v3.1.11) (2019-01-15) + + +### Bug Fixes + +* **bulk:** fix error propagation in empty bulk.execute ([a3adb3f](https://github.com/mongodb/node-mongodb-native/commit/a3adb3f)) +* **bulk:** make sure that any error in bulk write is propagated ([bedc2d2](https://github.com/mongodb/node-mongodb-native/commit/bedc2d2)) +* **bulk:** properly calculate batch size for bulk writes ([aafe71b](https://github.com/mongodb/node-mongodb-native/commit/aafe71b)) +* **operations:** do not call require in a hot path ([ff82ff4](https://github.com/mongodb/node-mongodb-native/commit/ff82ff4)) + + + + +## [3.1.10](https://github.com/mongodb/node-mongodb-native/compare/v3.1.9...v3.1.10) (2018-11-16) + + +### Bug Fixes + +* **auth:** remember to default to admin database ([c7dec28](https://github.com/mongodb/node-mongodb-native/commit/c7dec28)) + + +### Features + +* **core:** update to mongodb-core v3.1.9 ([bd3355b](https://github.com/mongodb/node-mongodb-native/commit/bd3355b)) + + + + +## [3.1.9](https://github.com/mongodb/node-mongodb-native/compare/v3.1.8...v3.1.9) (2018-11-06) + + +### Bug Fixes + +* **db:** move db constants to other file to avoid circular ref ([#1858](https://github.com/mongodb/node-mongodb-native/issues/1858)) ([239036f](https://github.com/mongodb/node-mongodb-native/commit/239036f)) +* **estimated-document-count:** support options other than maxTimeMs ([36c3c7d](https://github.com/mongodb/node-mongodb-native/commit/36c3c7d)) + + +### Features + +* **core:** update to mongodb-core v3.1.8 ([80d7c79](https://github.com/mongodb/node-mongodb-native/commit/80d7c79)) + + + + +## [3.1.8](https://github.com/mongodb/node-mongodb-native/compare/v3.1.7...v3.1.8) (2018-10-10) + + +### Bug Fixes + +* **connect:** use reported default databse from new uri parser ([811f8f8](https://github.com/mongodb/node-mongodb-native/commit/811f8f8)) + + +### Features + +* **core:** update to mongodb-core v3.1.7 ([dbfc905](https://github.com/mongodb/node-mongodb-native/commit/dbfc905)) + + + + +## [3.1.7](https://github.com/mongodb/node-mongodb-native/compare/v3.1.6...v3.1.7) (2018-10-09) + + +### Features + +* **core:** update mongodb-core to v3.1.6 ([61b054e](https://github.com/mongodb/node-mongodb-native/commit/61b054e)) + + + + +## [3.1.6](https://github.com/mongodb/node-mongodb-native/compare/v3.1.5...v3.1.6) (2018-09-15) + + +### Features + +* **core:** update to core v3.1.5 ([c5f823d](https://github.com/mongodb/node-mongodb-native/commit/c5f823d)) + + + + +## [3.1.5](https://github.com/mongodb/node-mongodb-native/compare/v3.1.4...v3.1.5) (2018-09-14) + + +### Bug Fixes + +* **cursor:** allow `$meta` based sort when passing an array to `sort()` ([f93a8c3](https://github.com/mongodb/node-mongodb-native/commit/f93a8c3)) +* **utils:** only set retryWrites to true for valid operations ([3b725ef](https://github.com/mongodb/node-mongodb-native/commit/3b725ef)) + + +### Features + +* **core:** bump core to v3.1.4 ([805d58a](https://github.com/mongodb/node-mongodb-native/commit/805d58a)) + + + + +## [3.1.4](https://github.com/mongodb/node-mongodb-native/compare/v3.1.3...v3.1.4) (2018-08-25) + + +### Bug Fixes + +* **buffer:** use safe-buffer polyfill to maintain compatibility ([327da95](https://github.com/mongodb/node-mongodb-native/commit/327da95)) +* **change-stream:** properly support resumablity in stream mode ([c43a34b](https://github.com/mongodb/node-mongodb-native/commit/c43a34b)) +* **connect:** correct replacement of topology on connect callback ([918a1e0](https://github.com/mongodb/node-mongodb-native/commit/918a1e0)) +* **cursor:** remove deprecated notice on forEach ([a474158](https://github.com/mongodb/node-mongodb-native/commit/a474158)) +* **url-parser:** bail early on validation when using domain socket ([3cb3da3](https://github.com/mongodb/node-mongodb-native/commit/3cb3da3)) + + +### Features + +* **client-ops:** allow bypassing creation of topologies on connect ([fe39b93](https://github.com/mongodb/node-mongodb-native/commit/fe39b93)) +* **core:** update mongodb-core to 3.1.3 ([a029047](https://github.com/mongodb/node-mongodb-native/commit/a029047)) +* **test:** use connection strings for all calls to `newClient` ([1dac18f](https://github.com/mongodb/node-mongodb-native/commit/1dac18f)) + + + + +## [3.1.3](https://github.com/mongodb/node-mongodb-native/compare/v3.1.2...v3.1.3) (2018-08-13) + + +### Features + +* **core:** update to mongodb-core 3.1.2 ([337cb79](https://github.com/mongodb/node-mongodb-native/commit/337cb79)) + + + + +## [3.1.2](https://github.com/mongodb/node-mongodb-native/compare/v3.0.6...v3.1.2) (2018-08-13) + + +### Bug Fixes + +* **aggregate:** support user-provided `batchSize` ([ad10dee](https://github.com/mongodb/node-mongodb-native/commit/ad10dee)) +* **buffer:** replace deprecated Buffer constructor ([759dd85](https://github.com/mongodb/node-mongodb-native/commit/759dd85)) +* **bulk:** fixing retryable writes for mass-change ops ([0604036](https://github.com/mongodb/node-mongodb-native/commit/0604036)) +* **bulk:** handle MongoWriteConcernErrors ([12ff392](https://github.com/mongodb/node-mongodb-native/commit/12ff392)) +* **change_stream:** do not check isGetMore if error[mongoErrorContextSymbol] is undefined ([#1720](https://github.com/mongodb/node-mongodb-native/issues/1720)) ([844c2c8](https://github.com/mongodb/node-mongodb-native/commit/844c2c8)) +* **change-stream:** fix change stream resuming with promises ([3063f00](https://github.com/mongodb/node-mongodb-native/commit/3063f00)) +* **client-ops:** return transform map to map rather than function ([cfb7d83](https://github.com/mongodb/node-mongodb-native/commit/cfb7d83)) +* **collection:** correctly shallow clone passed in options ([7727700](https://github.com/mongodb/node-mongodb-native/commit/7727700)) +* **collection:** countDocuments throws error when query doesn't match docs ([09c7d8e](https://github.com/mongodb/node-mongodb-native/commit/09c7d8e)) +* **collection:** depend on `resolveReadPreference` for inheritance ([a649e35](https://github.com/mongodb/node-mongodb-native/commit/a649e35)) +* **collection:** ensure findAndModify always use readPreference primary ([86344f4](https://github.com/mongodb/node-mongodb-native/commit/86344f4)) +* **collection:** isCapped returns false instead of undefined ([b8471f1](https://github.com/mongodb/node-mongodb-native/commit/b8471f1)) +* **collection:** only send bypassDocumentValidation if true ([fdb828b](https://github.com/mongodb/node-mongodb-native/commit/fdb828b)) +* **count-documents:** return callback on error case ([fca1185](https://github.com/mongodb/node-mongodb-native/commit/fca1185)) +* **cursor:** cursor count with collation fix ([71879c3](https://github.com/mongodb/node-mongodb-native/commit/71879c3)) +* **cursor:** cursor hasNext returns false when exhausted ([184b817](https://github.com/mongodb/node-mongodb-native/commit/184b817)) +* **cursor:** cursor.count not respecting parent readPreference ([5a9fdf0](https://github.com/mongodb/node-mongodb-native/commit/5a9fdf0)) +* **cursor:** set readPreference for cursor.count ([13d776f](https://github.com/mongodb/node-mongodb-native/commit/13d776f)) +* **db:** don't send session down to createIndex command ([559c195](https://github.com/mongodb/node-mongodb-native/commit/559c195)) +* **db:** throw readable error when creating `_id` with background: true ([b3ff3ed](https://github.com/mongodb/node-mongodb-native/commit/b3ff3ed)) +* **db_ops:** call collection.find() with correct parameters ([#1795](https://github.com/mongodb/node-mongodb-native/issues/1795)) ([36e92f1](https://github.com/mongodb/node-mongodb-native/commit/36e92f1)) +* **db_ops:** fix two incorrectly named variables ([15dc808](https://github.com/mongodb/node-mongodb-native/commit/15dc808)) +* **findOneAndUpdate:** ensure that update documents contain atomic operators ([eb68074](https://github.com/mongodb/node-mongodb-native/commit/eb68074)) +* **index:** export MongoNetworkError ([98ab29e](https://github.com/mongodb/node-mongodb-native/commit/98ab29e)) +* **mongo_client:** translate options for connectWithUrl ([78f6977](https://github.com/mongodb/node-mongodb-native/commit/78f6977)) +* **mongo-client:** pass arguments to ctor when new keyword is used ([d6c3417](https://github.com/mongodb/node-mongodb-native/commit/d6c3417)) +* **mongos:** bubble up close events after the first one ([#1713](https://github.com/mongodb/node-mongodb-native/issues/1713)) ([3e91d77](https://github.com/mongodb/node-mongodb-native/commit/3e91d77)), closes [Automattic/mongoose#6249](https://github.com/Automattic/mongoose/issues/6249) [#1685](https://github.com/mongodb/node-mongodb-native/issues/1685) +* **parallelCollectionScan:** do not use implicit sessions on cursors ([2de470a](https://github.com/mongodb/node-mongodb-native/commit/2de470a)) +* **retryWrites:** fixes more bulk ops to not use retryWrites ([69e5254](https://github.com/mongodb/node-mongodb-native/commit/69e5254)) +* **server:** remove unnecessary print statement ([2bcbc12](https://github.com/mongodb/node-mongodb-native/commit/2bcbc12)) +* **teardown:** properly destroy a topology when initial connect fails ([b8d2f1d](https://github.com/mongodb/node-mongodb-native/commit/b8d2f1d)) +* **topology-base:** sending `endSessions` is always skipped now ([a276cbe](https://github.com/mongodb/node-mongodb-native/commit/a276cbe)) +* **txns:** omit writeConcern when in a transaction ([b88c938](https://github.com/mongodb/node-mongodb-native/commit/b88c938)) +* **utils:** restructure inheritance rules for read preferences ([6a7dac1](https://github.com/mongodb/node-mongodb-native/commit/6a7dac1)) + + +### Features + +* **auth:** add support for SCRAM-SHA-256 ([f53195d](https://github.com/mongodb/node-mongodb-native/commit/f53195d)) +* **changeStream:** Adding new 4.0 ChangeStream features ([2cb4894](https://github.com/mongodb/node-mongodb-native/commit/2cb4894)) +* **changeStream:** allow resuming on getMore errors ([4ba5adc](https://github.com/mongodb/node-mongodb-native/commit/4ba5adc)) +* **changeStream:** expanding changeStream resumable errors ([49fbafd](https://github.com/mongodb/node-mongodb-native/commit/49fbafd)) +* **ChangeStream:** update default startAtOperationTime ([50a9f65](https://github.com/mongodb/node-mongodb-native/commit/50a9f65)) +* **collection:** add colleciton level document mapping/unmapping ([d03335e](https://github.com/mongodb/node-mongodb-native/commit/d03335e)) +* **collection:** Implement new count API ([a5240ae](https://github.com/mongodb/node-mongodb-native/commit/a5240ae)) +* **Collection:** warn if callback is not function in find and findOne ([cddaba0](https://github.com/mongodb/node-mongodb-native/commit/cddaba0)) +* **core:** bump core dependency to v3.1.0 ([4937240](https://github.com/mongodb/node-mongodb-native/commit/4937240)) +* **cursor:** new cursor.transformStream method ([397fcd2](https://github.com/mongodb/node-mongodb-native/commit/397fcd2)) +* **deprecation:** create deprecation function ([4f907a0](https://github.com/mongodb/node-mongodb-native/commit/4f907a0)) +* **deprecation:** wrap deprecated functions ([a5d0f1d](https://github.com/mongodb/node-mongodb-native/commit/a5d0f1d)) +* **GridFS:** add option to disable md5 in file upload ([704a88e](https://github.com/mongodb/node-mongodb-native/commit/704a88e)) +* **listCollections:** add support for nameOnly option ([d2d0367](https://github.com/mongodb/node-mongodb-native/commit/d2d0367)) +* **parallelCollectionScan:** does not allow user to pass a session ([4da9e03](https://github.com/mongodb/node-mongodb-native/commit/4da9e03)) +* **read-preference:** add transaction to inheritance rules ([18ca41d](https://github.com/mongodb/node-mongodb-native/commit/18ca41d)) +* **read-preference:** unify means of read preference resolution ([#1738](https://github.com/mongodb/node-mongodb-native/issues/1738)) ([2995e11](https://github.com/mongodb/node-mongodb-native/commit/2995e11)) +* **urlParser:** use core URL parser ([c1c5d8d](https://github.com/mongodb/node-mongodb-native/commit/c1c5d8d)) +* **withSession:** add top level helper for session lifetime ([9976b86](https://github.com/mongodb/node-mongodb-native/commit/9976b86)) + + +### Reverts + +* **collection:** reverting collection-mapping features ([7298c76](https://github.com/mongodb/node-mongodb-native/commit/7298c76)), closes [#1698](https://github.com/mongodb/node-mongodb-native/issues/1698) [mongodb/js-bson#253](https://github.com/mongodb/js-bson/issues/253) + + + + +## [3.1.1](https://github.com/mongodb/node-mongodb-native/compare/v3.1.0...v3.1.1) (2018-07-05) + + +### Bug Fixes + +* **client-ops:** return transform map to map rather than function ([b8b4bfa](https://github.com/mongodb/node-mongodb-native/commit/b8b4bfa)) +* **collection:** correctly shallow clone passed in options ([2e6c4fa](https://github.com/mongodb/node-mongodb-native/commit/2e6c4fa)) +* **collection:** countDocuments throws error when query doesn't match docs ([4e83556](https://github.com/mongodb/node-mongodb-native/commit/4e83556)) +* **server:** remove unnecessary print statement ([20e11b3](https://github.com/mongodb/node-mongodb-native/commit/20e11b3)) + + + + +# [3.1.0](https://github.com/mongodb/node-mongodb-native/compare/v3.0.6...v3.1.0) (2018-06-27) + + +### Bug Fixes + +* **aggregate:** support user-provided `batchSize` ([ad10dee](https://github.com/mongodb/node-mongodb-native/commit/ad10dee)) +* **bulk:** fixing retryable writes for mass-change ops ([0604036](https://github.com/mongodb/node-mongodb-native/commit/0604036)) +* **bulk:** handle MongoWriteConcernErrors ([12ff392](https://github.com/mongodb/node-mongodb-native/commit/12ff392)) +* **change_stream:** do not check isGetMore if error[mongoErrorContextSymbol] is undefined ([#1720](https://github.com/mongodb/node-mongodb-native/issues/1720)) ([844c2c8](https://github.com/mongodb/node-mongodb-native/commit/844c2c8)) +* **change-stream:** fix change stream resuming with promises ([3063f00](https://github.com/mongodb/node-mongodb-native/commit/3063f00)) +* **collection:** depend on `resolveReadPreference` for inheritance ([a649e35](https://github.com/mongodb/node-mongodb-native/commit/a649e35)) +* **collection:** only send bypassDocumentValidation if true ([fdb828b](https://github.com/mongodb/node-mongodb-native/commit/fdb828b)) +* **cursor:** cursor count with collation fix ([71879c3](https://github.com/mongodb/node-mongodb-native/commit/71879c3)) +* **cursor:** cursor hasNext returns false when exhausted ([184b817](https://github.com/mongodb/node-mongodb-native/commit/184b817)) +* **cursor:** cursor.count not respecting parent readPreference ([5a9fdf0](https://github.com/mongodb/node-mongodb-native/commit/5a9fdf0)) +* **db:** don't send session down to createIndex command ([559c195](https://github.com/mongodb/node-mongodb-native/commit/559c195)) +* **db:** throw readable error when creating `_id` with background: true ([b3ff3ed](https://github.com/mongodb/node-mongodb-native/commit/b3ff3ed)) +* **findOneAndUpdate:** ensure that update documents contain atomic operators ([eb68074](https://github.com/mongodb/node-mongodb-native/commit/eb68074)) +* **index:** export MongoNetworkError ([98ab29e](https://github.com/mongodb/node-mongodb-native/commit/98ab29e)) +* **mongo-client:** pass arguments to ctor when new keyword is used ([d6c3417](https://github.com/mongodb/node-mongodb-native/commit/d6c3417)) +* **mongos:** bubble up close events after the first one ([#1713](https://github.com/mongodb/node-mongodb-native/issues/1713)) ([3e91d77](https://github.com/mongodb/node-mongodb-native/commit/3e91d77)), closes [Automattic/mongoose#6249](https://github.com/Automattic/mongoose/issues/6249) [#1685](https://github.com/mongodb/node-mongodb-native/issues/1685) +* **parallelCollectionScan:** do not use implicit sessions on cursors ([2de470a](https://github.com/mongodb/node-mongodb-native/commit/2de470a)) +* **retryWrites:** fixes more bulk ops to not use retryWrites ([69e5254](https://github.com/mongodb/node-mongodb-native/commit/69e5254)) +* **topology-base:** sending `endSessions` is always skipped now ([a276cbe](https://github.com/mongodb/node-mongodb-native/commit/a276cbe)) +* **txns:** omit writeConcern when in a transaction ([b88c938](https://github.com/mongodb/node-mongodb-native/commit/b88c938)) +* **utils:** restructure inheritance rules for read preferences ([6a7dac1](https://github.com/mongodb/node-mongodb-native/commit/6a7dac1)) + + +### Features + +* **auth:** add support for SCRAM-SHA-256 ([f53195d](https://github.com/mongodb/node-mongodb-native/commit/f53195d)) +* **changeStream:** Adding new 4.0 ChangeStream features ([2cb4894](https://github.com/mongodb/node-mongodb-native/commit/2cb4894)) +* **changeStream:** allow resuming on getMore errors ([4ba5adc](https://github.com/mongodb/node-mongodb-native/commit/4ba5adc)) +* **changeStream:** expanding changeStream resumable errors ([49fbafd](https://github.com/mongodb/node-mongodb-native/commit/49fbafd)) +* **ChangeStream:** update default startAtOperationTime ([50a9f65](https://github.com/mongodb/node-mongodb-native/commit/50a9f65)) +* **collection:** add colleciton level document mapping/unmapping ([d03335e](https://github.com/mongodb/node-mongodb-native/commit/d03335e)) +* **collection:** Implement new count API ([a5240ae](https://github.com/mongodb/node-mongodb-native/commit/a5240ae)) +* **Collection:** warn if callback is not function in find and findOne ([cddaba0](https://github.com/mongodb/node-mongodb-native/commit/cddaba0)) +* **core:** bump core dependency to v3.1.0 ([855bfdb](https://github.com/mongodb/node-mongodb-native/commit/855bfdb)) +* **cursor:** new cursor.transformStream method ([397fcd2](https://github.com/mongodb/node-mongodb-native/commit/397fcd2)) +* **GridFS:** add option to disable md5 in file upload ([704a88e](https://github.com/mongodb/node-mongodb-native/commit/704a88e)) +* **listCollections:** add support for nameOnly option ([d2d0367](https://github.com/mongodb/node-mongodb-native/commit/d2d0367)) +* **parallelCollectionScan:** does not allow user to pass a session ([4da9e03](https://github.com/mongodb/node-mongodb-native/commit/4da9e03)) +* **read-preference:** add transaction to inheritance rules ([18ca41d](https://github.com/mongodb/node-mongodb-native/commit/18ca41d)) +* **read-preference:** unify means of read preference resolution ([#1738](https://github.com/mongodb/node-mongodb-native/issues/1738)) ([2995e11](https://github.com/mongodb/node-mongodb-native/commit/2995e11)) +* **urlParser:** use core URL parser ([c1c5d8d](https://github.com/mongodb/node-mongodb-native/commit/c1c5d8d)) +* **withSession:** add top level helper for session lifetime ([9976b86](https://github.com/mongodb/node-mongodb-native/commit/9976b86)) + + +### Reverts + +* **collection:** reverting collection-mapping features ([7298c76](https://github.com/mongodb/node-mongodb-native/commit/7298c76)), closes [#1698](https://github.com/mongodb/node-mongodb-native/issues/1698) [mongodb/js-bson#253](https://github.com/mongodb/js-bson/issues/253) + + + + +## [3.0.6](https://github.com/mongodb/node-mongodb-native/compare/v3.0.5...v3.0.6) (2018-04-09) + + +### Bug Fixes + +* **db:** ensure `dropDatabase` always uses primary read preference ([e62e5c9](https://github.com/mongodb/node-mongodb-native/commit/e62e5c9)) +* **driverBench:** driverBench has default options object now ([c557817](https://github.com/mongodb/node-mongodb-native/commit/c557817)) + + +### Features + +* **command-monitoring:** support enabling command monitoring ([5903680](https://github.com/mongodb/node-mongodb-native/commit/5903680)) +* **core:** update to mongodb-core v3.0.6 ([cfdd0ae](https://github.com/mongodb/node-mongodb-native/commit/cfdd0ae)) +* **driverBench:** Implementing DriverBench ([d10fbad](https://github.com/mongodb/node-mongodb-native/commit/d10fbad)) + + + + +## [3.0.5](https://github.com/mongodb/node-mongodb-native/compare/v3.0.4...v3.0.5) (2018-03-23) + + +### Bug Fixes + +* **AggregationCursor:** adding session tracking to AggregationCursor ([baca5b7](https://github.com/mongodb/node-mongodb-native/commit/baca5b7)) +* **Collection:** fix session leak in parallelCollectonScan ([3331ec9](https://github.com/mongodb/node-mongodb-native/commit/3331ec9)) +* **comments:** adding fixes for PR comments ([ee110ac](https://github.com/mongodb/node-mongodb-native/commit/ee110ac)) +* **url_parser:** support a default database on mongodb+srv uris ([6d39b2a](https://github.com/mongodb/node-mongodb-native/commit/6d39b2a)) + + +### Features + +* **sessions:** adding implicit cursor session support ([a81245b](https://github.com/mongodb/node-mongodb-native/commit/a81245b)) + + + + +## [3.0.4](https://github.com/mongodb/node-mongodb-native/compare/v3.0.2...v3.0.4) (2018-03-05) + + +### Bug Fixes + +* **collection:** fix error when calling remove with no args ([#1657](https://github.com/mongodb/node-mongodb-native/issues/1657)) ([4c9b0f8](https://github.com/mongodb/node-mongodb-native/commit/4c9b0f8)) +* **executeOperation:** don't mutate options passed to commands ([934a43a](https://github.com/mongodb/node-mongodb-native/commit/934a43a)) +* **jsdoc:** mark db.collection callback as optional + typo fix ([#1658](https://github.com/mongodb/node-mongodb-native/issues/1658)) ([c519b9b](https://github.com/mongodb/node-mongodb-native/commit/c519b9b)) +* **sessions:** move active session tracking to topology base ([#1665](https://github.com/mongodb/node-mongodb-native/issues/1665)) ([b1f296f](https://github.com/mongodb/node-mongodb-native/commit/b1f296f)) +* **utils:** fixes executeOperation to clean up sessions ([04e6ef6](https://github.com/mongodb/node-mongodb-native/commit/04e6ef6)) + + +### Features + +* **default-db:** use dbName from uri if none provided ([23b1938](https://github.com/mongodb/node-mongodb-native/commit/23b1938)) +* **mongodb-core:** update to mongodb-core 3.0.4 ([1fdbaa5](https://github.com/mongodb/node-mongodb-native/commit/1fdbaa5)) + + + + +## [3.0.3](https://github.com/mongodb/node-mongodb-native/compare/v3.0.2...v3.0.3) (2018-02-23) + + +### Bug Fixes + +* **collection:** fix error when calling remove with no args ([#1657](https://github.com/mongodb/node-mongodb-native/issues/1657)) ([4c9b0f8](https://github.com/mongodb/node-mongodb-native/commit/4c9b0f8)) +* **executeOperation:** don't mutate options passed to commands ([934a43a](https://github.com/mongodb/node-mongodb-native/commit/934a43a)) +* **jsdoc:** mark db.collection callback as optional + typo fix ([#1658](https://github.com/mongodb/node-mongodb-native/issues/1658)) ([c519b9b](https://github.com/mongodb/node-mongodb-native/commit/c519b9b)) +* **sessions:** move active session tracking to topology base ([#1665](https://github.com/mongodb/node-mongodb-native/issues/1665)) ([b1f296f](https://github.com/mongodb/node-mongodb-native/commit/b1f296f)) + + + + +## [3.0.2](https://github.com/mongodb/node-mongodb-native/compare/v3.0.1...v3.0.2) (2018-01-29) + + +### Bug Fixes + +* **collection:** ensure dynamic require of `db` is wrapped in parentheses ([efa78f0](https://github.com/mongodb/node-mongodb-native/commit/efa78f0)) +* **db:** only callback with MongoError NODE-1293 ([#1652](https://github.com/mongodb/node-mongodb-native/issues/1652)) ([45bc722](https://github.com/mongodb/node-mongodb-native/commit/45bc722)) +* **topology base:** allow more than 10 event listeners ([#1630](https://github.com/mongodb/node-mongodb-native/issues/1630)) ([d9fb750](https://github.com/mongodb/node-mongodb-native/commit/d9fb750)) +* **url parser:** preserve auth creds when composing conn string ([#1640](https://github.com/mongodb/node-mongodb-native/issues/1640)) ([eddca5e](https://github.com/mongodb/node-mongodb-native/commit/eddca5e)) + + +### Features + +* **bulk:** forward 'checkKeys' option for ordered and unordered bulk operations ([421a6b2](https://github.com/mongodb/node-mongodb-native/commit/421a6b2)) +* **collection:** expose `dbName` property of collection ([6fd05c1](https://github.com/mongodb/node-mongodb-native/commit/6fd05c1)) + + + + +## [3.0.1](https://github.com/mongodb/node-mongodb-native/compare/v3.0.0...v3.0.1) (2017-12-24) + +* update mongodb-core to 3.0.1 + + +# [3.0.0](https://github.com/mongodb/node-mongodb-native/compare/v3.0.0-rc0...v3.0.0) (2017-12-24) + + +### Bug Fixes + +* **aggregate:** remove support for inline results for aggregate ([#1620](https://github.com/mongodb/node-mongodb-native/issues/1620)) ([84457ec](https://github.com/mongodb/node-mongodb-native/commit/84457ec)) +* **topologies:** unify topologies connect API ([#1615](https://github.com/mongodb/node-mongodb-native/issues/1615)) ([0fb4658](https://github.com/mongodb/node-mongodb-native/commit/0fb4658)) + + +### Features + +* **keepAlive:** make keepAlive options consistent ([#1612](https://github.com/mongodb/node-mongodb-native/issues/1612)) ([f608f44](https://github.com/mongodb/node-mongodb-native/commit/f608f44)) + + +### BREAKING CHANGES + +* **topologies:** Function signature for `.connect` method on replset and mongos has changed. You shouldn't have been using this anyway, but if you were, you only should pass `options` and `callback`. + +Part of NODE-1089 +* **keepAlive:** option `keepAlive` is now split into boolean `keepAlive` and +number `keepAliveInitialDelay` + +Fixes NODE-998 + + + + +# [3.0.0-rc0](https://github.com/mongodb/node-mongodb-native/compare/v2.2.31...v3.0.0-rc0) (2017-12-05) + + +### Bug Fixes + +* **aggregation:** ensure that the `cursor` key is always present ([f16f314](https://github.com/mongodb/node-mongodb-native/commit/f16f314)) +* **apm:** give users access to raw server responses ([88b206b](https://github.com/mongodb/node-mongodb-native/commit/88b206b)) +* **apm:** only rebuilt cursor if reply is non-null ([96052c8](https://github.com/mongodb/node-mongodb-native/commit/96052c8)) +* **apm:** rebuild lost `cursor` info on pre-OP_QUERY responses ([4242d49](https://github.com/mongodb/node-mongodb-native/commit/4242d49)) +* **bulk-unordered:** add check for ignoreUndefined ([f38641a](https://github.com/mongodb/node-mongodb-native/commit/f38641a)) +* **change stream examples:** use timeouts, cleanup ([c5fec5f](https://github.com/mongodb/node-mongodb-native/commit/c5fec5f)) +* **change-streams:** ensure a majority read concern on initial agg ([23011e9](https://github.com/mongodb/node-mongodb-native/commit/23011e9)) +* **changeStreams:** fixing node4 issue with util.inherits ([#1587](https://github.com/mongodb/node-mongodb-native/issues/1587)) ([168bb3d](https://github.com/mongodb/node-mongodb-native/commit/168bb3d)) +* **collection:** allow { upsert: 1 } for findOneAndUpdate() and update() ([5bcedd6](https://github.com/mongodb/node-mongodb-native/commit/5bcedd6)) +* **collection:** allow passing `noCursorTimeout` as an option to `find()` ([e9c4ffc](https://github.com/mongodb/node-mongodb-native/commit/e9c4ffc)) +* **collection:** make the parameters of findOne very explicit ([3054f1a](https://github.com/mongodb/node-mongodb-native/commit/3054f1a)) +* **cursor:** `hasNext` should propagate errors when using callback ([6339625](https://github.com/mongodb/node-mongodb-native/commit/6339625)) +* **cursor:** close readable on `null` response for dead cursor ([6aca2c5](https://github.com/mongodb/node-mongodb-native/commit/6aca2c5)) +* **dns txt records:** check options are set ([e5caf4f](https://github.com/mongodb/node-mongodb-native/commit/e5caf4f)) +* **docs:** Represent each valid option in docs in both places ([fde6e5d](https://github.com/mongodb/node-mongodb-native/commit/fde6e5d)) +* **grid-store:** add missing callback ([66a9a05](https://github.com/mongodb/node-mongodb-native/commit/66a9a05)) +* **grid-store:** move into callback scope ([b53f65f](https://github.com/mongodb/node-mongodb-native/commit/b53f65f)) +* **GridFS:** fix TypeError: doc.data.length is not a function ([#1570](https://github.com/mongodb/node-mongodb-native/issues/1570)) ([22a4628](https://github.com/mongodb/node-mongodb-native/commit/22a4628)) +* **list-collections:** ensure default of primary ReadPreference ([4a0cfeb](https://github.com/mongodb/node-mongodb-native/commit/4a0cfeb)) +* **mongo client:** close client before calling done ([c828aab](https://github.com/mongodb/node-mongodb-native/commit/c828aab)) +* **mongo client:** do not connect if url parse error ([cd10084](https://github.com/mongodb/node-mongodb-native/commit/cd10084)) +* **mongo client:** send error to cb ([eafc9e2](https://github.com/mongodb/node-mongodb-native/commit/eafc9e2)) +* **mongo-client:** move to inside of callback ([68b0fca](https://github.com/mongodb/node-mongodb-native/commit/68b0fca)) +* **mongo-client:** options should not be passed to `connect` ([474ac65](https://github.com/mongodb/node-mongodb-native/commit/474ac65)) +* **tests:** migrate 2.x tests to 3.x ([3a5232a](https://github.com/mongodb/node-mongodb-native/commit/3a5232a)) +* **updateOne/updateMany:** ensure that update documents contain atomic operators ([8b4255a](https://github.com/mongodb/node-mongodb-native/commit/8b4255a)) +* **url parser:** add check for options as cb ([52b6039](https://github.com/mongodb/node-mongodb-native/commit/52b6039)) +* **url parser:** compare srv address and parent domains ([daa186d](https://github.com/mongodb/node-mongodb-native/commit/daa186d)) +* **url parser:** compare string from first period on ([9e5d77e](https://github.com/mongodb/node-mongodb-native/commit/9e5d77e)) +* **url parser:** default to ssl true for mongodb+srv ([0fbca4b](https://github.com/mongodb/node-mongodb-native/commit/0fbca4b)) +* **url parser:** error when multiple hostnames used ([c1aa681](https://github.com/mongodb/node-mongodb-native/commit/c1aa681)) +* **url parser:** keep original uri options and default to ssl true ([e876a72](https://github.com/mongodb/node-mongodb-native/commit/e876a72)) +* **url parser:** log instead of throw error for unsupported url options ([155de2d](https://github.com/mongodb/node-mongodb-native/commit/155de2d)) +* **url parser:** make sure uri has 3 parts ([aa9871b](https://github.com/mongodb/node-mongodb-native/commit/aa9871b)) +* **url parser:** only 1 txt record allowed with 2 possible options ([d9f4218](https://github.com/mongodb/node-mongodb-native/commit/d9f4218)) +* **url parser:** only check for multiple hostnames with srv protocol ([5542bcc](https://github.com/mongodb/node-mongodb-native/commit/5542bcc)) +* **url parser:** remove .only from test ([642e39e](https://github.com/mongodb/node-mongodb-native/commit/642e39e)) +* **url parser:** return callback ([6096afc](https://github.com/mongodb/node-mongodb-native/commit/6096afc)) +* **url parser:** support single text record with multiple strings ([356fa57](https://github.com/mongodb/node-mongodb-native/commit/356fa57)) +* **url parser:** try catch bug, not actually returning from try loop ([758892b](https://github.com/mongodb/node-mongodb-native/commit/758892b)) +* **url parser:** use warn instead of info ([40ed27d](https://github.com/mongodb/node-mongodb-native/commit/40ed27d)) +* **url-parser:** remove comment, send error to cb ([d44420b](https://github.com/mongodb/node-mongodb-native/commit/d44420b)) + + +### Features + +* **aggregate:** support hit field for aggregate command ([aa7da15](https://github.com/mongodb/node-mongodb-native/commit/aa7da15)) +* **aggregation:** adds support for comment in aggregation command ([#1571](https://github.com/mongodb/node-mongodb-native/issues/1571)) ([4ac475c](https://github.com/mongodb/node-mongodb-native/commit/4ac475c)) +* **aggregation:** fail aggregation on explain + readConcern/writeConcern ([e0ca1b4](https://github.com/mongodb/node-mongodb-native/commit/e0ca1b4)) +* **causal-consistency:** support `afterClusterTime` in readConcern ([a9097f7](https://github.com/mongodb/node-mongodb-native/commit/a9097f7)) +* **change-streams:** add support for change streams ([c02d25c](https://github.com/mongodb/node-mongodb-native/commit/c02d25c)) +* **collection:** updating find API ([f26362d](https://github.com/mongodb/node-mongodb-native/commit/f26362d)) +* **execute-operation:** implementation for common op execution ([67c344f](https://github.com/mongodb/node-mongodb-native/commit/67c344f)) +* **listDatabases:** add support for nameOnly option to listDatabases ([eb79b5a](https://github.com/mongodb/node-mongodb-native/commit/eb79b5a)) +* **maxTimeMS:** adding maxTimeMS option to createIndexes and dropIndexes ([90d4a63](https://github.com/mongodb/node-mongodb-native/commit/90d4a63)) +* **mongo-client:** implement `MongoClient.prototype.startSession` ([bce5adf](https://github.com/mongodb/node-mongodb-native/commit/bce5adf)) +* **retryable-writes:** add support for `retryWrites` cs option ([2321870](https://github.com/mongodb/node-mongodb-native/commit/2321870)) +* **sessions:** MongoClient will now track sessions and release ([6829f47](https://github.com/mongodb/node-mongodb-native/commit/6829f47)) +* **sessions:** support passing sessions via objects in all methods ([a531f05](https://github.com/mongodb/node-mongodb-native/commit/a531f05)) +* **shared:** add helper utilities for assertion and suite setup ([b6cc34e](https://github.com/mongodb/node-mongodb-native/commit/b6cc34e)) +* **ssl:** adds missing ssl options ssl options for `ciphers` and `ecdhCurve` ([441b7b1](https://github.com/mongodb/node-mongodb-native/commit/441b7b1)) +* **test-shared:** add `notEqual` assertion ([41d93fd](https://github.com/mongodb/node-mongodb-native/commit/41d93fd)) +* **test-shared:** add `strictEqual` assertion method ([cad8e19](https://github.com/mongodb/node-mongodb-native/commit/cad8e19)) +* **topologies:** expose underlaying `logicalSessionTimeoutMinutes' ([1609a37](https://github.com/mongodb/node-mongodb-native/commit/1609a37)) +* **url parser:** better error message for slash in hostname ([457bc29](https://github.com/mongodb/node-mongodb-native/commit/457bc29)) + + +### BREAKING CHANGES + +* **aggregation:** If you use aggregation, and try to use the explain flag while you +have a readConcern or writeConcern, your query will fail +* **collection:** `find` and `findOne` no longer support the `fields` parameter. +You can achieve the same results as the `fields` parameter by +either using `Cursor.prototype.project`, or by passing the `projection` +property in on the `options` object. Additionally, `find` does not +support individual options like `skip` and `limit` as positional +parameters. You must pass in these parameters in the `options` object + + + +3.0.0 2017-??-?? +---------------- +* NODE-1043 URI-escaping authentication and hostname details in connection string + +2.2.31 2017-08-08 +----------------- +* update mongodb-core to 2.2.15 +* allow auth option in MongoClient.connect +* remove duplicate option `promoteLongs` from MongoClient's `connect` +* bulk operations should not throw an error on empty batch + +2.2.30 2017-07-07 +----------------- +* Update mongodb-core to 2.2.14 +* MongoClient + * add `appname` to list of valid option names + * added test for passing appname as option +* NODE-1052 ensure user options are applied while parsing connection string uris + +2.2.29 2017-06-19 +----------------- +* Update mongodb-core to 2.1.13 + * NODE-1039 ensure we force destroy server instances, forcing queue to be flushed. + * Use actual server type in standalone SDAM events. +* Allow multiple map calls (Issue #1521, https://github.com/Robbilie). +* Clone insertMany options before mutating (Issue #1522, https://github.com/vkarpov15). +* NODE-1034 Fix GridStore issue caused by Node 8.0.0 breaking backward compatible fs.read API. +* NODE-1026, use operator instead of skip function in order to avoid useless fetch stage. + +2.2.28 2017-06-02 +----------------- +* Update mongodb-core to 2.1.12 + * NODE-1019 Set keepAlive to 300 seconds or 1/2 of socketTimeout if socketTimeout < keepAlive. + * Minor fix to report the correct state on error. + * NODE-1020 'family' was added to options to provide high priority for ipv6 addresses (Issue #1518, https://github.com/firej). + * Fix require_optional loading of bson-ext. + * Ensure no errors are thrown by replset if topology is destroyed before it finished connecting. + * NODE-999 SDAM fixes for Mongos and single Server event emitting. + * NODE-1014 Set socketTimeout to default to 360 seconds. + * NODE-1019 Set keepAlive to 300 seconds or 1/2 of socketTimeout if socketTimeout < keepAlive. +* Just handle Collection name errors distinctly from general callback errors avoiding double callbacks in Db.collection. +* NODE-999 SDAM fixes for Mongos and single Server event emitting. +* NODE-1000 Added guard condition for upload.js checkDone function in case of race condition caused by late arriving chunk write. + +2.2.27 2017-05-22 +----------------- +* Updated mongodb-core to 2.1.11 + * NODE-987 Clear out old intervalIds on when calling topologyMonitor. + * NODE-987 Moved filtering to pingServer method and added test case. + * Check for connection destroyed just before writing out and flush out operations correctly if it is (Issue #179, https://github.com/jmholzinger). + * NODE-989 Refactored Replicaset monitoring to correcly monitor newly added servers, Also extracted setTimeout and setInterval to use custom wrappers Timeout and Interval. +* NODE-985 Deprecated Db.authenticate and Admin.authenticate and moved auth methods into authenticate.js to ensure MongoClient.connect does not print deprecation warnings. +* NODE-988 Merged readConcern and hint correctly on collection(...).find(...).count() +* Fix passing the readConcern option to MongoClient.connect (Issue #1514, https://github.com/bausmeier). +* NODE-996 Propegate all events up to a MongoClient instance. +* Allow saving doc with null `_id` (Issue #1517, https://github.com/vkarpov15). +* NODE-993 Expose hasNext for command cursor and add docs for both CommandCursor and Aggregation Cursor. + +2.2.26 2017-04-18 +----------------- +* Updated mongodb-core to 2.1.10 + * NODE-981 delegate auth to replset/mongos if inTopology is set. + * NODE-978 Wrap connection.end in try/catch for node 0.10.x issue causing exceptions to be thrown, Also surfaced getConnection for mongos and replset. + * Remove dynamic require (Issue #175, https://github.com/tellnes). + * NODE-696 Handle interrupted error for createIndexes. + * Fixed isse when user is executing find command using Server.command and it get interpreted as a wire protcol message, #172. + * NODE-966 promoteValues not being promoted correctly to getMore. + * Merged in fix for flushing out monitoring operations. +* NODE-983 Add cursorId to aggregate and listCollections commands (Issue, #1510). +* Mark group and profilingInfo as deprecated methods +* NODE-956 DOCS Examples. +* Update readable-stream to version 2.2.7. +* NODE-978 Added test case to uncover connection.end issue for node 0.10.x. +* NODE-972 Fix(db): don't remove database name if collectionName == dbName (Issue, #1502) +* Fixed merging of writeConcerns on db.collection method. +* NODE-970 mix in readPreference for strict mode listCollections callback. +* NODE-966 added testcase for promoteValues being applied to getMore commands. +* NODE-962 Merge in ignoreUndefined from collection level for find/findOne. +* Remove multi option from updateMany tests/docs (Issue #1499, https://github.com/spratt). +* NODE-963 Correctly handle cursor.count when using APM. + +2.2.25 2017-03-17 +----------------- +* Don't rely on global toString() for checking if object (Issue #1494, https://github.com/vkarpov15). +* Remove obsolete option uri_decode_auth (Issue #1488, https://github.com/kamagatos). +* NODE-936 Correctly translate ReadPreference to CoreReadPreference for mongos queries. +* Exposed BSONRegExp type. +* NODE-950 push correct index for INSERT ops (https://github.com/mbroadst). +* NODE-951 Added support for sslCRL option and added a test case for it. +* NODE-953 Made batchSize issue general at cursor level. +* NODE-954 Remove write concern from reindex helper as it will not be supported in 3.6. +* Updated mongodb-core to 2.1.9. + * Return lastIsMaster correctly when connecting with secondaryOnlyConnectionAllowed is set to true and only a secondary is available in replica state. + * Clone options when passed to wireProtocol handler to avoid intermittent modifications causing errors. + * Ensure SSL error propegates better for Replset connections when there is a SSL validation error. + * NODE-957 Fixed issue where < batchSize not causing cursor to be closed on execution of first batch. + * NODE-958 Store reconnectConnection on pool object to allow destroy to close immediately. + +2.2.24 2017-02-14 +----------------- +* NODE-935, NODE-931 Make MongoClient strict options validation optional and instead print annoying console.warn entries. + +2.2.23 2017-02-13 +----------------- +* Updated mongodb-core to 2.1.8. + * NODE-925 ensure we reschedule operations while pool is < poolSize while pool is growing and there are no connections with not currently performing work. + * NODE-927 fixes issue where authentication was performed against arbiter instances. + * NODE-915 Normalize all host names to avoid comparison issues. + * Fixed issue where pool.destroy would never finish due to a single operation not being executed and keeping it open. +* NODE-931 Validates all the options for MongoClient.connect and fixes missing connection settings. +* NODE-929 Update SSL tutorial to correctly reflect the non-need for server/mongos/replset subobjects +* Fix sensitive command check (Issue #1473, https://github.com/Annoraaq) + +2.2.22 2017-01-24 +----------------- +* Updated mongodb-core to 2.1.7. + * NODE-919 ReplicaSet connection does not close immediately (Issue #156). + * NODE-901 Fixed bug when normalizing host names. + * NODE-909 Fixed readPreference issue caused by direct connection to primary. + * NODE-910 Fixed issue when bufferMaxEntries == 0 and read preference set to nearest. +* Add missing unref implementations for replset, mongos (Issue #1455, https://github.com/zbjornson) + +2.2.21 2017-01-13 +----------------- +* Updated mongodb-core to 2.1.6. + * NODE-908 Keep auth contexts in replset and mongos topology to ensure correct application of authentication credentials when primary is first server to be detected causing an immediate connect event to happen. + +2.2.20 2017-01-11 +----------------- +* Updated mongodb-core to 2.1.5 to include bson 1.0.4 and bson-ext 1.0.4 due to Buffer.from being broken in early node 4.x versions. + +2.2.19 2017-01-03 +----------------- +* Corrupted Npm release fix. + +2.2.18 2017-01-03 +----------------- +* Updated mongodb-core to 2.1.4 to fix bson ObjectId toString issue with utils.inspect messing with toString parameters in node 6. + +2.2.17 2017-01-02 +----------------- +* updated createCollection doc options and linked to create command. +* Updated mongodb-core to 2.1.3. + * Monitoring operations are re-scheduled in pool if it cannot find a connection that does not already have scheduled work on it, this is to avoid the monitoring socket timeout being applied to any existing operations on the socket due to pipelining + * Moved replicaset monitoring away from serial mode and to parallel mode. + * updated bson and bson-ext dependencies to 1.0.2. + +2.2.16 2016-12-13 +----------------- +* NODE-899 reversed upsertedId change to bring back old behavior. + +2.2.15 2016-12-10 +----------------- +* Updated mongodb-core to 2.1.2. + * Delay topologyMonitoring on successful attemptReconnect as no need to run a full scan immediately. + * Emit reconnect event in primary joining when in connected status for a replicaset (Fixes mongoose reconnect issue). + +2.2.14 2016-12-08 +----------------- +* Updated mongodb-core to 2.1.1. +* NODE-892 Passthrough options.readPreference to mongodb-core ReplSet instance. + +2.2.13 2016-12-05 +----------------- +* Updated mongodb-core to 2.1.0. +* NODE-889 Fixed issue where legacy killcursor wire protocol messages would not be sent when APM is enabled. +* Expose parserType as property on topology objects. + +2.2.12 2016-11-29 +----------------- +* Updated mongodb-core to 2.0.14. + * Updated bson library to 0.5.7. + * Dont leak connection.workItems elments when killCursor is called (Issue #150, https://github.com/mdlavin). + * Remove unnecessary errors formatting (Issue #149, https://github.com/akryvomaz). + * Only check isConnected against availableConnections (Issue #142). + * NODE-838 Provide better error message on failed to connect on first retry for Mongos topology. + * Set default servername to host is not passed through for sni. + * Made monitoring happen on exclusive connection and using connectionTimeout to handle the wait time before failure (Issue #148). + * NODE-859 Make minimum value of maxStalenessSeconds 90 seconds. + * NODE-852 Fix Kerberos module deprecations on linux and windows and release new kerberos version. + * NODE-850 Update Max Staleness implementation. + * NODE-849 username no longer required for MONGODB-X509 auth. + * NODE-848 BSON Regex flags must be alphabetically ordered. + * NODE-846 Create notice for all third party libraries. + * NODE-843 Executing bulk operations overwrites write concern parameter. + * NODE-842 Re-sync SDAM and SDAM Monitoring tests from Specs repo. + * NODE-840 Resync CRUD spec tests. + * Unescapable while(true) loop (Issue #152). +* NODE-864 close event not emits during network issues using single server topology. +* Introduced maxStalenessSeconds. +* NODE-840 Added CRUD specification test cases and fix minor issues with upserts reporting matchedCount > 0. +* Don't ignore Db-level authSource when using auth method. (https://github.com/donaldguy). + +2.2.11 2016-10-21 +----------------- +* Updated mongodb-core to 2.0.13. + - Fire callback when topology was destroyed (Issue #147, https://github.com/vkarpov15). + - Refactoring to support pipelining ala 1.4.x branch will retaining the benefits of the growing/shrinking pool (Issue #146). + - Fix typo in serverHeartbeatFailed event name (Issue #143, https://github.com/jakesjews). + - NODE-798 Driver hangs on count command in replica set with one member (Issue #141, https://github.com/isayme). +* Updated bson library to 0.5.6. + - Included cyclic dependency detection +* Fix typo in serverHeartbeatFailed event name (Issue #1418, https://github.com/jakesjews). +* NODE-824, readPreference "nearest" does not work when specified at collection level. +* NODE-822, GridFSBucketWriteStream end method does not handle optional parameters. +* NODE-823, GridFSBucketWriteStream end: callback is invoked with invalid parameters. +* NODE-829, Using Start/End offset option in GridFSBucketReadStream doesn't return the right sized buffer. + +2.2.10 2016-09-15 +----------------- +* Updated mongodb-core to 2.0.12. +* fix debug logging message not printing server name. +* fixed application metadata being sent by wrong ismaster. +* NODE-812 Fixed mongos stall due to proxy monitoring ismaster failure causing reconnect. +* NODE-818 Replicaset timeouts in initial connect sequence can "no primary found". +* Updated bson library to 0.5.5. +* Added DBPointer up conversion to DBRef. +* MongoDB 3.4-RC Pass **appname** through MongoClient.connect uri or options to allow metadata to be passed. +* MongoDB 3.4-RC Pass collation options on update, findOne, find, createIndex, aggregate. +* MongoDB 3.4-RC Allow write concerns to be passed to all supporting server commands. +* MongoDB 3.4-RC Allow passing of **servername** as SSL options to support SNI. + +2.2.9 2016-08-29 +---------------- +* Updated mongodb-core to 2.0.11. +* NODE-803, Fixed issue in how the latency window is calculated for Mongos topology causing issues for single proxy connections. +* Avoid timeout in attemptReconnect causing multiple attemptReconnect attempts to happen (Issue #134, https://github.com/dead-horse). +* Ensure promoteBuffers is propegated in same fashion as promoteValues and promoteLongs. +* Don't treat ObjectId as object for mapReduce scope (Issue #1397, https://github.com/vkarpov15). + +2.2.8 2016-08-23 +---------------- +* Updated mongodb-core to 2.0.10. +* Added promoteValues flag (default to true) to allow user to specify they only want wrapped BSON values back instead of promotion to native types. +* Do not close mongos proxy connection on failed ismaster check in ha process (Issue #130). + +2.2.7 2016-08-19 +---------------- +* If only a single mongos is provided in the seedlist, fix issue where it would be assigned as single standalone server instead of mongos topology (Issue #130). +* Updated mongodb-core to 2.0.9. +* Allow promoteLongs to be passed in through Response.parse method and overrides default set on the connection. +* NODE-798 Driver hangs on count command in replica set with one member. +* Allow promoteLongs to be passed in through Response.parse method and overrides default set on the connection. +* Allow passing in servername for TLS connections for SNI support. + +2.2.6 2016-08-16 +---------------- +* Updated mongodb-core to 2.0.8. +* Allow execution of store operations independent of having both a primary and secondary available (Issue #123). +* Fixed command execution issue for mongos to ensure buffering of commands when no mongos available. +* Allow passing in an array of tags to ReadPreference constructor (Issue #1382, https://github.com/vkarpov15) +* Added hashed connection names and fullResult. +* Updated bson library to 0.5.3. +* Enable maxTimeMS in count, distinct, findAndModify. + +2.2.5 2016-07-28 +---------------- +* Updated mongodb-core to 2.0.7. +* Allow primary to be returned when secondaryPreferred is passed (Issue #117, https://github.com/dhendo). +* Added better warnings when passing in illegal seed list members to a Mongos topology. +* Minor attemptReconnect bug that would cause multiple attemptReconnect to run in parallel. +* Fix wrong opType passed to disconnectHandler.add (Issue #121, https://github.com/adrian-gierakowski) +* Implemented domain backward comp support enabled via domainsEnabled options on Server/ReplSet/Mongos and MongoClient.connect. + +2.2.4 2016-07-19 +---------------- +* NPM corrupted upload fix. + +2.2.3 2016-07-19 +---------------- +* Updated mongodb-core to 2.0.6. +* Destroy connection on socket timeout due to newer node versions not closing the socket. + +2.2.2 2016-07-15 +---------------- +* Updated mongodb-core to 2.0.5. +* Minor fixes to handle faster MongoClient connectivity from the driver, allowing single server instances to detect if they are a proxy. +* Added numberOfConsecutiveTimeouts to pool that will destroy the pool if the number of consecutive timeouts > reconnectTries. +* Print warning if seedlist servers host name does not match the one provided in it's ismaster.me field for Replicaset members. +* Fix issue where Replicaset connection would not succeeed if there the replicaset was a single primary server setup. + +2.2.1 2016-07-11 +---------------- +* Updated mongodb-core to 2.0.4. +* handle situation where user is providing seedlist names that do not match host list. fix allows for a single full discovery connection sweep before erroring out. +* NODE-747 Polyfill for Object.assign for 0.12.x or 0.10.x. +* NODE-746 Improves replicaset errors for wrong setName. + +2.2.0 2016-07-05 +---------------- +* Updated mongodb-core to 2.0.3. +* Moved all authentication and handling of growing/shrinking of pool connections into actual pool. +* All authentication methods now handle both auth/reauthenticate and logout events. +* Introduced logout method to get rid of onAll option for logout command. +* Updated bson to 0.5.0 that includes Decimal128 support. +* Fixed logger error serialization issue. +* Documentation fixes. +* Implemented Server Selection Specification test suite. +* Added warning level to logger. +* Added warning message when sockeTimeout < haInterval for Replset/Mongos. +* Mongos emits close event on no proxies available or when reconnect attempt fails. +* Replset emits close event when no servers available or when attemptReconnect fails to reconnect. +* Don't throw in auth methods but return error in callback. + +2.1.21 2016-05-30 +----------------- +* Updated mongodb-core to 1.3.21. +* Pool gets stuck if a connection marked for immediateRelease times out (Issue #99, https://github.com/nbrachet). +* Make authentication process retry up to authenticationRetries at authenticationRetryIntervalMS interval. +* Made ismaster replicaset calls operate with connectTimeout or monitorSocketTimeout to lower impact of big socketTimeouts on monitoring performance. +* Make sure connections mark as "immediateRelease" don't linger the inUserConnections list. Otherwise, after that connection times out, getAll() incorrectly returns more connections than are effectively present, causing the pool to not get restarted by reconnectServer. (Issue #99, https://github.com/nbrachet). +* Make cursor getMore or killCursor correctly trigger pool reconnect to single server if pool has not been destroyed. +* Make ismaster monitoring for single server connection default to avoid user confusion due to change in behavior. + +2.1.20 2016-05-25 +----------------- +* Refactored MongoClient options handling to simplify the logic, unifying it. +* NODE-707 Implemented openUploadStreamWithId on GridFS to allow for custom fileIds so users are able to customize shard key and shard distribution. +* NODE-710 Allow setting driver loggerLevel and logger function from MongoClient options. +* Updated mongodb-core to 1.3.20. +* Minor fix for SSL errors on connection attempts, minor fix to reconnect handler for the server. +* Don't write to socket before having registered the callback for commands, work around for windows issuing error events twice on node.js when socket gets destroyed by firewall. +* Fix minor issue where connectingServers would not be removed correctly causing single server connections to not auto-reconnect. + +2.1.19 2016-05-17 +---------------- +* Handle situation where a server connection in a replicaset sometimes fails to be destroyed properly due to being in the middle of authentication when the destroy method is called on the replicaset causing it to be orphaned and never collected. +* Ensure replicaset topology destroy is never called by SDAM. +* Ensure all paths are correctly returned on inspectServer in replset. +* Updated mongodb-core to 1.3.19 to fix minor connectivity issue on quick open/close of MongoClient connections on auth enabled mongodb Replicasets. + +2.1.18 2016-04-27 +----------------- +* Updated mongodb-core to 1.3.18 to fix Node 6.0 issues. + +2.1.17 2016-04-26 +----------------- +* Updated mongodb-core to 1.3.16 to work around issue with early versions of node 0.10.x due to missing unref method on ClearText streams. +* INT-1308: Allow listIndexes to inherit readPreference from Collection or DB. +* Fix timeout issue using new flags #1361. +* Updated mongodb-core to 1.3.17. +* Better handling of unique createIndex error. +* Emit error only if db instance has an error listener. +* DEFAULT authMechanism; don't throw error if explicitly set by user. + +2.1.16 2016-04-06 +----------------- +* Updated mongodb-core to 1.3.16. + +2.1.15 2016-04-06 +----------------- +* Updated mongodb-core to 1.3.15. +* Set ssl, sslValidate etc to mongosOptions on url_parser (Issue #1352, https://github.com/rubenstolk). +- NODE-687 Fixed issue where a server object failed to be destroyed if the replicaset state did not update successfully. This could leave active connections accumulating over time. +- Fixed some situations where all connections are flushed due to a single connection in the connection pool closing. + +2.1.14 2016-03-29 +----------------- +* Updated mongodb-core to 1.3.13. +* Handle missing cursor on getMore when going through a mongos proxy by pinning to socket connection and not server. + +2.1.13 2016-03-29 +----------------- +* Updated mongodb-core to 1.3.12. + +2.1.12 2016-03-29 +----------------- +* Updated mongodb-core to 1.3.11. +* Mongos setting acceptableLatencyMS exposed to control the latency women for mongos selection. +* Mongos pickProxies fall back to closest mongos if no proxies meet latency window specified. +* isConnected method for mongos uses same selection code as getServer. +* Exceptions in cursor getServer trapped and correctly delegated to high level handler. + +2.1.11 2016-03-23 +----------------- +* Updated mongodb-core to 1.3.10. +* Introducing simplified connections settings. + +2.1.10 2016-03-21 +----------------- +* Updated mongodb-core to 1.3.9. +* Fixing issue that prevented mapReduce stats from being resolved (Issue #1351, https://github.com/davidgtonge) +* Forwards SDAM monitoring events from mongodb-core. + +2.1.9 2016-03-16 +---------------- +* Updated mongodb-core to 1.3.7 to fix intermittent race condition that causes some users to experience big amounts of socket connections. +* Makde bson parser in ordered/unordered bulk be directly from mongodb-core to avoid intermittent null error on mongoose. + +2.1.8 2016-03-14 +---------------- +* Updated mongodb-core to 1.3.5. +* NODE-660 TypeError: Cannot read property 'noRelease' of undefined. +* Harden MessageHandler in server.js to avoid issues where we cannot find a callback for an operation. +* Ensure RequestId can never be larger than Max Number integer size. +* NODE-661 typo in url_parser.js resulting in replSetServerOptions is not defined when connecting over ssl. +* Confusing error with invalid partial index filter (Issue #1341, https://github.com/vkarpov15). +* NODE-669 Should only error out promise for bulkWrite when error is a driver level error not a write error or write concern error. +* NODE-662 shallow copy options on methods that are not currently doing it to avoid passed in options mutiation. +* NODE-663 added lookup helper on aggregation cursor. +* NODE-585 Result object specified incorrectly for findAndModify?. +* NODE-666 harden validation for findAndModify CRUD methods. + +2.1.7 2016-02-09 +---------------- +* NODE-656 fixed corner case where cursor count command could be left without a connection available. +* NODE-658 Work around issue that bufferMaxEntries:-1 for js gets interpreted wrongly due to double nature of Javascript numbers. +* Fix: GridFS always returns the oldest version due to incorrect field name (Issue #1338, https://github.com/mdebruijne). +* NODE-655 GridFS stream support for cancelling upload streams and download streams (Issue #1339, https://github.com/vkarpov15). +* NODE-657 insertOne don`t return promise in some cases. +* Added destroy alias for abort function on GridFSBucketWriteStream. + +2.1.6 2016-02-05 +---------------- +* Updated mongodb-core to 1.3.1. + +2.1.5 2016-02-04 +---------------- +* Updated mongodb-core to 1.3.0. +* Added raw support for the command function on topologies. +* Fixed issue where raw results that fell on batchSize boundaries failed (Issue #72) +* Copy over all the properties to the callback returned from bindToDomain, (Issue #72) +* Added connection hash id to be able to reference connection host/name without leaking it outside of driver. +* NODE-638, Cannot authenticate database user with utf-8 password. +* Refactored pool to be worker queue based, minimizing the impact a slow query have on throughput as long as # slow queries < # connections in the pool. +* Pool now grows and shrinks correctly depending on demand not causing a full pool reconnect. +* Improvements in monitoring of a Replicaset where in certain situations the inquiry process could get exited. +* Switched to using Array.push instead of concat for use cases of a lot of documents. +* Fixed issue where re-authentication could loose the credentials if whole Replicaset disconnected at once. +* Added peer optional dependencies support using require_optional module. +* Bug is listCollections for collection names that start with db name (Issue #1333, https://github.com/flyingfisher) +* Emit error before closing stream (Issue #1335, https://github.com/eagleeye) + +2.1.4 2016-01-12 +---------------- +* Restricted node engine to >0.10.3 (https://jira.mongodb.org/browse/NODE-635). +* Multiple database names ignored without a warning (https://jira.mongodb.org/browse/NODE-636, Issue #1324, https://github.com/yousefhamza). +* Convert custom readPreference objects in collection.js (Issue #1326, https://github.com/Machyne). + +2.1.3 2016-01-04 +---------------- +* Updated mongodb-core to 1.2.31. +* Allow connection to secondary if primaryPreferred or secondaryPreferred (Issue #70, https://github.com/leichter) + +2.1.2 2015-12-23 +---------------- +* Updated mongodb-core to 1.2.30. +* Pool allocates size + 1 connections when using replicasets, reserving additional pool connection for monitoring exclusively. +* Fixes bug when all replicaset members are down, that would cause it to fail to reconnect using the originally provided seedlist. + +2.1.1 2015-12-13 +---------------- +* Surfaced checkServerIdentity options for MongoClient, Server, ReplSet and Mongos to allow for control of the checkServerIdentity method available in Node.s 0.12.x or higher. +* Added readPreference support to listCollections and listIndexes helpers. +* Updated mongodb-core to 1.2.28. + +2.1.0 2015-12-06 +---------------- +* Implements the connection string specification, https://github.com/mongodb/specifications/blob/master/source/connection-string/connection-string-spec.rst. +* Implements the new GridFS specification, https://github.com/mongodb/specifications/blob/master/source/gridfs/gridfs-spec.rst. +* Full MongoDB 3.2 support. +* NODE-601 Added maxAwaitTimeMS support for 3.2 getMore to allow for custom timeouts on tailable cursors. +* Updated mongodb-core to 1.2.26. +* Return destination in GridStore pipe function. +* NODE-606 better error handling on destroyed topology for db.js methods. +* Added isDestroyed method to server, replset and mongos topologies. +* Upgraded test suite to run using mongodb-topology-manager. + +2.0.53 2015-12-23 +----------------- +* Updated mongodb-core to 1.2.30. +* Pool allocates size + 1 connections when using replicasets, reserving additional pool connection for monitoring exclusively. +* Fixes bug when all replicaset members are down, that would cause it to fail to reconnect using the originally provided seedlist. + +2.0.52 2015-12-14 +----------------- +* removed remove from Gridstore.close. + +2.0.51 2015-12-13 +----------------- +* Surfaced checkServerIdentity options for MongoClient, Server, ReplSet and Mongos to allow for control of the checkServerIdentity method available in Node.s 0.12.x or higher. +* Added readPreference support to listCollections and listIndexes helpers. +* Updated mongodb-core to 1.2.28. + +2.0.50 2015-12-06 +----------------- +* Updated mongodb-core to 1.2.26. + +2.0.49 2015-11-20 +----------------- +* Updated mongodb-core to 1.2.24 with several fixes. + * Fix Automattic/mongoose#3481; flush callbacks on error, (Issue #57, https://github.com/vkarpov15). + * $explain query for wire protocol 2.6 and 2.4 does not set number of returned documents to -1 but to 0. + * ismaster runs against admin.$cmd instead of system.$cmd. + * Fixes to handle getMore command errors for MongoDB 3.2 + * Allows the process to properly close upon a Db.close() call on the replica set by shutting down the haTimer and closing arbiter connections. + +2.0.48 2015-11-07 +----------------- +* GridFS no longer performs any deletes when writing a brand new file that does not have any previous .fs.chunks or .fs.files documents. +* Updated mongodb-core to 1.2.21. +* Hardened the checking for replicaset equality checks. +* OpReplay flag correctly set on Wire protocol query. +* Mongos load balancing added, introduced localThresholdMS to control the feature. +* Kerberos now a peerDependency, making it not install it by default in Node 5.0 or higher. + +2.0.47 2015-10-28 +----------------- +* Updated mongodb-core to 1.2.20. +* Fixed bug in arbiter connection capping code. +* NODE-599 correctly handle arrays of server tags in order of priority. +* Fix for 2.6 wire protocol handler related to readPreference handling. +* Added maxAwaitTimeMS support for 3.2 getMore to allow for custom timeouts on tailable cursors. +* Make CoreCursor check for $err before saying that 'next' succeeded (Issue #53, https://github.com/vkarpov15). + +2.0.46 2015-10-15 +----------------- +* Updated mongodb-core to 1.2.19. +* NODE-578 Order of sort fields is lost for numeric field names. +* Expose BSON Map (ES6 Map or polyfill). +* Minor fixes for APM support to pass extended APM test suite. + +2.0.45 2015-09-30 +----------------- +* NODE-566 Fix issue with rewind on capped collections causing cursor state to be reset on connection loss. + +2.0.44 2015-09-28 +----------------- +* Bug fixes for APM upconverting of legacy INSERT/UPDATE/REMOVE wire protocol messages. +* NODE-562, fixed issue where a Replicaset MongoDB URI with a single seed and replSet name set would cause a single direct connection instead of topology discovery. +* Updated mongodb-core to 1.2.14. +* NODE-563 Introduced options.ignoreUndefined for db class and MongoClient db options, made serialize undefined to null default again but allowing for overrides on insert/update/delete operations. +* Use handleCallback if result is an error for count queries. (Issue #1298, https://github.com/agclever) +* Rewind cursor to correctly force reconnect on capped collections when first query comes back empty. +* NODE-571 added code 59 to legacy server errors when SCRAM-SHA-1 mechanism fails. +* NODE-572 Remove examples that use the second parameter to `find()`. + +2.0.43 2015-09-14 +----------------- +* Propagate timeout event correctly to db instances. +* Application Monitoring API (APM) implemented. +* NOT providing replSet name in MongoClient connection URI will force single server connection. Fixes issue where it was impossible to directly connect to a replicaset member server. +* Updated mongodb-core to 1.2.12. +* NODE-541 Initial Support "read committed" isolation level where "committed" means confimed by the voting majority of a replica set. +* GridStore doesn't share readPreference setting from connection string. (Issue #1295, https://github.com/zhangyaoxing) +* fixed forceServerObjectId calls (Issue #1292, https://github.com/d-mon-) +* Pass promise library through to DB function (Issue #1294, https://github.com/RovingCodeMonkey) + +2.0.42 2015-08-18 +----------------- +* Added test case to exercise all non-crud methods on mongos topologies, fixed numberOfConnectedServers on mongos topology instance. + +2.0.41 2015-08-14 +----------------- +* Added missing Mongos.prototype.parserType function. +* Updated mongodb-core to 1.2.10. + +2.0.40 2015-07-14 +----------------- +* Updated mongodb-core to 1.2.9 for 2.4 wire protocol error handler fix. +* NODE-525 Reset connectionTimeout after it's overwritten by tls.connect. +* NODE-518 connectTimeoutMS is doubled in 2.0.39. +* NODE-506 Ensures that errors from bulk unordered and ordered are instanceof Error (Issue #1282, https://github.com/owenallenaz). +* NODE-526 Unique index not throwing duplicate key error. +* NODE-528 Ignore undefined fields in Collection.find(). +* NODE-527 The API example for collection.createIndex shows Db.createIndex functionality. + +2.0.39 2015-07-14 +----------------- +* Updated mongodb-core to 1.2.6 for NODE-505. + +2.0.38 2015-07-14 +----------------- +* NODE-505 Query fails to find records that have a 'result' property with an array value. + +2.0.37 2015-07-14 +----------------- +* NODE-504 Collection * Default options when using promiseLibrary. +* NODE-500 Accidental repeat of hostname in seed list multiplies total connections persistently. +* Updated mongodb-core to 1.2.5 to fix NODE-492. + +2.0.36 2015-07-07 +----------------- +* Fully promisified allowing the use of ES6 generators and libraries like co. Also allows for BYOP (Bring your own promises). +* NODE-493 updated mongodb-core to 1.2.4 to ensure we cannot DDOS the mongod or mongos process on large connection pool sizes. + +2.0.35 2015-06-17 +----------------- +* Upgraded to mongodb-core 1.2.2 including removing warnings when C++ bson parser is not available and a fix for SCRAM authentication. + +2.0.34 2015-06-17 +----------------- +* Upgraded to mongodb-core 1.2.1 speeding up serialization and removing the need for the c++ bson extension. +* NODE-486 fixed issue related to limit and skip when calling toArray in 2.0 driver. +* NODE-483 throw error if capabilities of topology is queries before topology has performed connection setup. +* NODE-482 fixed issue where MongoClient.connect would incorrectly identify a replset seed list server as a non replicaset member. +* NODE-487 fixed issue where killcursor command was not being sent correctly on limit and skip queries. + +2.0.33 2015-05-20 +----------------- +* Bumped mongodb-core to 1.1.32. + +2.0.32 2015-05-19 +----------------- +* NODE-463 db.close immediately executes its callback. +* Don't only emit server close event once (Issue #1276, https://github.com/vkarpov15). +* NODE-464 Updated mongodb-core to 1.1.31 that uses a single socket connection to arbiters and hidden servers as well as emitting all event correctly. + +2.0.31 2015-05-08 +----------------- +* NODE-461 Tripping on error "no chunks found for file, possibly corrupt" when there is no error. + +2.0.30 2015-05-07 +----------------- +* NODE-460 fix; don't set authMechanism for user in db.authenticate() to avoid mongoose authentication issue. + +2.0.29 2015-05-07 +----------------- +* NODE-444 Possible memory leak, too many listeners added. +* NODE-459 Auth failure using Node 0.8.28, MongoDB 3.0.2 & mongodb-node-native 1.4.35. +* Bumped mongodb-core to 1.1.26. + +2.0.28 2015-04-24 +----------------- +* Bumped mongodb-core to 1.1.25 +* Added Cursor.prototype.setCursorOption to allow for setting node specific cursor options for tailable cursors. +* NODE-430 Cursor.count() opts argument masked by var opts = {} +* NODE-406 Implemented Cursor.prototype.map function tapping into MongoClient cursor transforms. +* NODE-438 replaceOne is not returning the result.ops property as described in the docs. +* NODE-433 _read, pipe and write all open gridstore automatically if not open. +* NODE-426 ensure drain event is emitted after write function returns, fixes intermittent issues in writing files to gridstore. +* NODE-440 GridStoreStream._read() doesn't check GridStore.read() error. +* Always use readPreference = primary for findAndModify command (ignore passed in read preferences) (Issue #1274, https://github.com/vkarpov15). +* Minor fix in GridStore.exists for dealing with regular expressions searches. + +2.0.27 2015-04-07 +----------------- +* NODE-410 Correctly handle issue with pause/resume in Node 0.10.x that causes exceptions when using the Node 0.12.0 style streams. + +2.0.26 2015-04-07 +----------------- +* Implements the Common Index specification Standard API at https://github.com/mongodb/specifications/blob/master/source/index-management.rst. +* NODE-408 Expose GridStore.currentChunk.chunkNumber. + +2.0.25 2015-03-26 +----------------- +* Upgraded mongodb-core to 1.1.21, making the C++ bson code an optional dependency to the bson module. + +2.0.24 2015-03-24 +----------------- +* NODE-395 Socket Not Closing, db.close called before full set finished initalizing leading to server connections in progress not being closed properly. +* Upgraded mongodb-core to 1.1.20. + +2.0.23 2015-03-21 +----------------- +* NODE-380 Correctly return MongoError from toError method. +* Fixed issue where addCursorFlag was not correctly setting the flag on the command for mongodb-core. +* NODE-388 Changed length from method to property on order.js/unordered.js bulk operations. +* Upgraded mongodb-core to 1.1.19. + +2.0.22 2015-03-16 +----------------- +* NODE-377, fixed issue where tags would correctly be checked on secondary and nearest to filter out eligible server candidates. +* Upgraded mongodb-core to 1.1.17. + +2.0.21 2015-03-06 +----------------- +* Upgraded mongodb-core to 1.1.16 making sslValidate default to true to force validation on connection unless overriden by the user. + +2.0.20 2015-03-04 +----------------- +* Updated mongodb-core 1.1.15 to relax pickserver method. + +2.0.19 2015-03-03 +----------------- +* NODE-376 Fixes issue * Unordered batch incorrectly tracks batch size when switching batch types (Issue #1261, https://github.com/meirgottlieb) +* NODE-379 Fixes bug in cursor.count() that causes the result to always be zero for dotted collection names (Issue #1262, https://github.com/vsivsi) +* Expose MongoError from mongodb-core (Issue #1260, https://github.com/tjconcept) + +2.0.18 2015-02-27 +----------------- +* Bumped mongodb-core 1.1.14 to ensure passives are correctly added as secondaries. + +2.0.17 2015-02-27 +----------------- +* NODE-336 Added length function to ordered and unordered bulk operations to be able know the amount of current operations in bulk. +* Bumped mongodb-core 1.1.13 to ensure passives are correctly added as secondaries. + +2.0.16 2015-02-16 +----------------- +* listCollection now returns filtered result correctly removing db name for 2.6 or earlier servers. +* Bumped mongodb-core 1.1.12 to correctly work for node 0.12.0 and io.js. +* Add ability to get collection name from cursor (Issue #1253, https://github.com/vkarpov15) + +2.0.15 2015-02-02 +----------------- +* Unified behavior of listCollections results so 3.0 and pre 3.0 return same type of results. +* Bumped mongodb-core to 1.1.11 to support per document tranforms in cursors as well as relaxing the setName requirement. +* NODE-360 Aggregation cursor and command correctly passing down the maxTimeMS property. +* Added ~1.0 mongodb-tools module for test running. +* Remove the required setName for replicaset connections, if not set it will pick the first setName returned. + +2.0.14 2015-01-21 +----------------- +* Fixed some MongoClient.connect options pass through issues and added test coverage. +* Bumped mongodb-core to 1.1.9 including fixes for io.js + +2.0.13 2015-01-09 +----------------- +* Bumped mongodb-core to 1.1.8. +* Optimized query path for performance, moving Object.defineProperty outside of constructors. + +2.0.12 2014-12-22 +----------------- +* Minor fixes to listCollections to ensure correct querying of a collection when using a string. + +2.0.11 2014-12-19 +----------------- +* listCollections filters out index namespaces on < 2.8 correctly +* Bumped mongo-client to 1.1.7 + +2.0.10 2014-12-18 +----------------- +* NODE-328 fixed db.open return when no callback available issue and added test. +* NODE-327 Refactored listCollections to return cursor to support 2.8. +* NODE-327 Added listIndexes method and refactored internal methods to use the new command helper. +* NODE-335 Cannot create index for nested objects fixed by relaxing key checking for createIndex helper. +* Enable setting of connectTimeoutMS (Issue #1235, https://github.com/vkarpov15) +* Bumped mongo-client to 1.1.6 + +2.0.9 2014-12-01 +---------------- +* Bumped mongodb-core to 1.1.3 fixing global leaked variables and introducing strict across all classes. +* All classes are now strict (Issue #1233) +* NODE-324 Refactored insert/update/remove and all other crud opts to rely on internal methods to avoid any recursion. +* Fixed recursion issues in debug logging due to JSON.stringify() +* Documentation fixes (Issue #1232, https://github.com/wsmoak) +* Fix writeConcern in Db.prototype.ensureIndex (Issue #1231, https://github.com/Qard) + +2.0.8 2014-11-28 +---------------- +* NODE-322 Finished up prototype refactoring of Db class. +* NODE-322 Exposed Cursor in index.js for New Relic. + +2.0.7 2014-11-20 +---------------- +* Bumped mongodb-core to 1.1.2 fixing a UTF8 encoding issue for collection names. +* NODE-318 collection.update error while setting a function with serializeFunctions option. +* Documentation fixes. + +2.0.6 2014-11-14 +---------------- +* Refactored code to be prototype based instead of privileged methods. +* Bumped mongodb-core to 1.1.1 to take advantage of the prototype based refactorings. +* Implemented missing aspects of the CRUD specification. +* Fixed documentation issues. +* Fixed global leak REFERENCE_BY_ID in gridfs grid_store (Issue #1225, https://github.com/j) +* Fix LearnBoost/mongoose#2313: don't let user accidentally clobber geoNear params (Issue #1223, https://github.com/vkarpov15) + +2.0.5 2014-10-29 +---------------- +* Minor fixes to documentation and generation of documentation. +* NODE-306 (No results in aggregation cursor when collection name contains a dot), Merged code for cursor and aggregation cursor. + +2.0.4 2014-10-23 +---------------- +* Allow for single replicaset seed list with no setName specified (Issue #1220, https://github.com/imaman) +* Made each rewind on each call allowing for re-using the cursor. +* Fixed issue where incorrect iterations would happen on each for extensive batchSizes. +* NODE-301 specifying maxTimeMS on find causes all fields to be omitted from result. + +2.0.3 2014-10-14 +---------------- +* NODE-297 Aggregate Broken for case of pipeline with no options. + +2.0.2 2014-10-08 +---------------- +* Bumped mongodb-core to 1.0.2. +* Fixed bson module dependency issue by relying on the mongodb-core one. +* Use findOne instead of find followed by nextObject (Issue #1216, https://github.com/sergeyksv) + +2.0.1 2014-10-07 +---------------- +* Dependency fix + +2.0.0 2014-10-07 +---------------- +* First release of 2.0 driver + +2.0.0-alpha2 2014-10-02 +----------------------- +* CRUD API (insertOne, insertMany, updateOne, updateMany, removeOne, removeMany, bulkWrite, findOneAndDelete, findOneAndUpdate, findOneAndReplace) +* Cluster Management Spec compatible. + +2.0.0-alpha1 2014-09-08 +----------------------- +* Insert method allows only up 1000 pr batch for legacy as well as 2.6 mode +* Streaming behavior is 0.10.x or higher with backwards compatibility using readable-stream npm package +* Gridfs stream only available through .stream() method due to overlapping names on Gridstore object and streams in 0.10.x and higher of node +* remove third result on update and remove and return the whole result document instead (getting rid of the weird 3 result parameters) + * Might break some application +* Returns the actual mongodb-core result instead of just the number of records changed for insert/update/remove +* MongoClient only has the connect method (no ability instantiate with Server, ReplSet or similar) +* Removed Grid class +* GridStore only supports w+ for metadata updates, no appending to file as it's not thread safe and can cause corruption of the data + + seek will fail if attempt to use with w or w+ + + write will fail if attempted with w+ or r + + w+ only works for updating metadata on a file +* Cursor toArray and each resets and re-runs the cursor +* FindAndModify returns whole result document instead of just value +* Extend cursor to allow for setting all the options via methods instead of dealing with the current messed up find +* Removed db.dereference method +* Removed db.cursorInfo method +* Removed db.stats method +* Removed db.collectionNames not needed anymore as it's just a specialized case of listCollections +* Removed db.collectionInfo removed due to not being compatible with new storage engines in 2.8 as they need to use the listCollections command due to system collections not working for namespaces. +* Added db.listCollections to replace several methods above + +1.4.10 2014-09-04 +----------------- +* Fixed BSON and Kerberos compilation issues +* Bumped BSON to ~0.2 always installing latest BSON 0.2.x series +* Fixed Kerberos and bumped to 0.0.4 + +1.4.9 2014-08-26 +---------------- +* Check _bsonType for Binary (Issue #1202, https://github.com/mchapman) +* Remove duplicate Cursor constructor (Issue #1201, https://github.com/KenPowers) +* Added missing parameter in the documentation (Issue #1199, https://github.com/wpjunior) +* Documented third parameter on the update callback(Issue #1196, https://github.com/gabmontes) +* NODE-240 Operations on SSL connection hang on node 0.11.x +* NODE-235 writeResult is not being passed on when error occurs in insert +* NODE-229 Allow count to work with query hints +* NODE-233 collection.save() does not support fullResult +* NODE-244 Should parseError also emit a `disconnected` event? +* NODE-246 Cursors are inefficiently constructed and consequently cannot be promisified. +* NODE-248 Crash with X509 auth +* NODE-252 Uncaught Exception in Base.__executeAllServerSpecificErrorCallbacks +* Bumped BSON parser to 0.2.12 + + +1.4.8 2014-08-01 +---------------- +* NODE-205 correctly emit authenticate event +* NODE-210 ensure no undefined connection error when checking server state +* NODE-212 correctly inherit socketTimeoutMS from replicaset when HA process adds new servers or reconnects to existing ones +* NODE-220 don't throw error if ensureIndex errors out in Gridstore +* Updated bson to 0.2.11 to ensure correct toBSON behavior when returning non object in nested classes +* Fixed test running filters +* Wrap debug log in a call to format (Issue #1187, https://github.com/andyroyle) +* False option values should not trigger w:1 (Issue #1186, https://github.com/jsdevel) +* Fix aggregatestream.close(Issue #1194, https://github.com/jonathanong) +* Fixed parsing issue for w:0 in url parser when in connection string +* Modified collection.geoNear to support a geoJSON point or legacy coordinate pair (Issue #1198, https://github.com/mmacmillan) + +1.4.7 2014-06-18 +---------------- +* Make callbacks to be executed in right domain when server comes back up (Issue #1184, https://github.com/anton-kotenko) +* Fix issue where currentOp query against mongos would fail due to mongos passing through $readPreference field to mongod (CS-X) + +1.4.6 2014-06-12 +---------------- +* Added better support for MongoClient IP6 parsing (Issue #1181, https://github.com/micovery) +* Remove options check on index creation (Issue #1179, Issue #1183, https://github.com/jdesboeufs, https://github.com/rubenvereecken) +* Added missing type check before calling optional callback function (Issue #1180) + +1.4.5 2014-05-21 +---------------- +* Added fullResult flag to insert/update/remove which will pass raw result document back. Document contents will vary depending on the server version the driver is talking to. No attempt is made to coerce a joint response. +* Fix to avoid MongoClient.connect hanging during auth when secondaries building indexes pre 2.6. +* return the destination stream in GridStore.pipe (Issue #1176, https://github.com/iamdoron) + +1.4.4 2014-05-13 +---------------- +* Bumped BSON version to use the NaN 1.0 package, fixed strict comparison issue for ObjectID +* Removed leaking global variable (Issue #1174, https://github.com/dainis) +* MongoClient respects connectTimeoutMS for initial discovery process (NODE-185) +* Fix bug with return messages larger than 16MB but smaller than max BSON Message Size (NODE-184) + +1.4.3 2014-05-01 +---------------- +* Clone options for commands to avoid polluting original options passed from Mongoose (Issue #1171, https://github.com/vkarpov15) +* Made geoNear and geoHaystackSearch only clean out allowed options from command generation (Issue #1167) +* Fixed typo for allowDiskUse (Issue #1168, https://github.com/joaofranca) +* A 'mapReduce' function changed 'function' to instance '\' of 'Code' class (Issue #1165, https://github.com/exabugs) +* Made findAndModify set sort only when explicitly set (Issue #1163, https://github.com/sars) +* Rewriting a gridStore file by id should use a new filename if provided (Issue #1169, https://github.com/vsivsi) + +1.4.2 2014-04-15 +---------------- +* Fix for inheritance of readPreferences from MongoClient NODE-168/NODE-169 +* Merged in fix for ping strategy to avoid hitting non-pinged servers (Issue #1161, https://github.com/vaseker) +* Merged in fix for correct debug output for connection messages (Issue #1158, https://github.com/vaseker) +* Fixed global variable leak (Issue #1160, https://github.com/vaseker) + +1.4.1 2014-04-09 +---------------- +* Correctly emit joined event when primary change +* Add _id to documents correctly when using bulk operations + +1.4.0 2014-04-03 +---------------- +* All node exceptions will no longer be caught if on('error') is defined +* Added X509 auth support +* Fix for MongoClient connection timeout issue (NODE-97) +* Pass through error messages from parseError instead of just text (Issue #1125) +* Close db connection on error (Issue #1128, https://github.com/benighted) +* Fixed documentation generation +* Added aggregation cursor for 2.6 and emulated cursor for pre 2.6 (uses stream2) +* New Bulk API implementation using write commands for 2.6 and down converts for pre 2.6 +* Insert/Update/Remove using new write commands when available +* Added support for new roles based API's in 2.6 for addUser/removeUser +* Added bufferMaxEntries to start failing if the buffer hits the specified number of entries +* Upgraded BSON parser to version 0.2.7 to work with < 0.11.10 C++ API changes +* Support for OP_LOG_REPLAY flag (NODE-94) +* Fixes for SSL HA ping and discovery. +* Uses createIndexes if available for ensureIndex/createIndex +* Added parallelCollectionScan method to collection returning CommandCursor instances for cursors +* Made CommandCursor behave as Readable stream. +* Only Db honors readPreference settings, removed Server.js legacy readPreference settings due to user confusion. +* Reconnect event emitted by ReplSet/Mongos/Server after reconnect and before replaying of buffered operations. +* GridFS buildMongoObject returns error on illegal md5 (NODE-157, https://github.com/iantocristian) +* Default GridFS chunk size changed to (255 * 1024) bytes to optimize for collections defaulting to power of 2 sizes on 2.6. +* Refactored commands to all go through command function ensuring consistent command execution. +* Fixed issues where readPreferences where not correctly passed to mongos. +* Catch error == null and make err detection more prominent (NODE-130) +* Allow reads from arbiter for single server connection (NODE-117) +* Handle error coming back with no documents (NODE-130) +* Correctly use close parameter in Gridstore.write() (NODE-125) +* Throw an error on a bulk find with no selector (NODE-129, https://github.com/vkarpov15) +* Use a shallow copy of options in find() (NODE-124, https://github.com/vkarpov15) +* Fix statistical strategy (NODE-158, https://github.com/vkarpov15) +* GridFS off-by-one bug in lastChunkNumber() causes uncaught throw and data loss (Issue #1154, https://github.com/vsivsi) +* GridStore drops passed `aliases` option, always results in `null` value in GridFS files (Issue #1152, https://github.com/vsivsi) +* Remove superfluous connect object copying in index.js (Issue #1145, https://github.com/thomseddon) +* Do not return false when the connection buffer is still empty (Issue #1143, https://github.com/eknkc) +* Check ReadPreference object on ReplSet.canRead (Issue #1142, https://github.com/eknkc) +* Fix unpack error on _executeQueryCommand (Issue #1141, https://github.com/eknkc) +* Close db on failed connect so node can exit (Issue #1128, https://github.com/benighted) +* Fix global leak with _write_concern (Issue #1126, https://github.com/shanejonas) + +1.3.19 2013-08-21 +----------------- +* Correctly rethrowing errors after change from event emission to callbacks, compatibility with 0.10.X domains without breaking 0.8.X support. +* Small fix to return the entire findAndModify result as the third parameter (Issue #1068) +* No removal of "close" event handlers on server reconnect, emits "reconnect" event when reconnection happens. Reconnect Only applies for single server connections as of now as semantics for ReplSet and Mongos is not clear (Issue #1056) + +1.3.18 2013-08-10 +----------------- +* Fixed issue when throwing exceptions in MongoClient.connect/Db.open (Issue #1057) +* Fixed an issue where _events is not cleaned up correctly causing a slow steady memory leak. + +1.3.17 2013-08-07 +----------------- +* Ignore return commands that have no registered callback +* Made collection.count not use the db.command function +* Fix throw exception on ping command (Issue #1055) + +1.3.16 2013-08-02 +----------------- +* Fixes connection issue where lots of connections would happen if a server is in recovery mode during connection (Issue #1050, NODE-50, NODE-51) +* Bug in unlink mulit filename (Issue #1054) + +1.3.15 2013-08-01 +----------------- +* Memory leak issue due to node Issue #4390 where _events[id] is set to undefined instead of deleted leading to leaks in the Event Emitter over time + +1.3.14 2013-08-01 +----------------- +* Fixed issue with checkKeys where it would error on X.X + +1.3.13 2013-07-31 +----------------- +* Added override for checkKeys on insert/update (Warning will expose you to injection attacks) (Issue #1046) +* BSON size checking now done pre serialization (Issue #1037) +* Added isConnected returns false when no connection Pool exists (Issue #1043) +* Unified command handling to ensure same handling (Issue #1041, #1042) +* Correctly emit "open" and "fullsetup" across all Db's associated with Mongos, ReplSet or Server (Issue #1040) +* Correctly handles bug in authentication when attempting to connect to a recovering node in a replicaset. +* Correctly remove recovering servers from available servers in replicaset. Piggybacks on the ping command. +* Removed findAndModify chaining to be compliant with behavior in other official drivers and to fix a known mongos issue. +* Fixed issue with Kerberos authentication on Windows for re-authentication. +* Fixed Mongos failover behavior to correctly throw out old servers. +* Ensure stored queries/write ops are executed correctly after connection timeout +* Added promoteLongs option for to allow for overriding the promotion of Longs to Numbers and return the actual Long. + +1.3.12 2013-07-19 +----------------- +* Fixed issue where timeouts sometimes would behave wrongly (Issue #1032) +* Fixed bug with callback third parameter on some commands (Issue #1033) +* Fixed possible issue where killcursor command might leave hanging functions +* Fixed issue where Mongos was not correctly removing dead servers from the pool of eligable servers +* Throw error if dbName or collection name contains null character (at command level and at collection level) +* Updated bson parser to 0.2.1 with security fix and non-promotion of Long values to javascript Numbers (once a long always a long) + +1.3.11 2013-07-04 +----------------- +* Fixed errors on geoNear and geoSearch (Issue #1024, https://github.com/ebensing) +* Add driver version to export (Issue #1021, https://github.com/aheckmann) +* Add text to readpreference obedient commands (Issue #1019) +* Drivers should check the query failure bit even on getmore response (Issue #1018) +* Map reduce has incorrect expectations of 'inline' value for 'out' option (Issue #1016, https://github.com/rcotter) +* Support SASL PLAIN authentication (Issue #1009) +* Ability to use different Service Name on the driver for Kerberos Authentication (Issue #1008) +* Remove unnecessary octal literal to allow the code to run in strict mode (Issue #1005, https://github.com/jamesallardice) +* Proper handling of recovering nodes (when they go into recovery and when they return from recovery, Issue #1027) + +1.3.10 2013-06-17 +----------------- +* Guard against possible undefined in server::canCheckoutWriter (Issue #992, https://github.com/willyaranda) +* Fixed some duplicate test names (Issue #993, https://github.com/kawanet) +* Introduced write and read concerns for GridFS (Issue #996) +* Fixed commands not correctly respecting Collection level read preference (Issue #995, #999) +* Fixed issue with pool size on replicaset connections (Issue #1000) +* Execute all query commands on master switch (Issue #1002, https://github.com/fogaztuc) + +1.3.9 2013-06-05 +---------------- +* Fixed memory leak when findAndModify errors out on w>1 and chained callbacks not properly cleaned up. + +1.3.8 2013-05-31 +---------------- +* Fixed issue with socket death on windows where it emits error event instead of close event (Issue #987) +* Emit authenticate event on db after authenticate method has finished on db instance (Issue #984) +* Allows creation of MongoClient and do new MongoClient().connect(..). Emits open event when connection correct allowing for apps to react on event. + +1.3.7 2013-05-29 +---------------- +* After reconnect, tailable getMores go on inconsistent connections (Issue #981, #982, https://github.com/glasser) +* Updated Bson to 0.1.9 to fix ARM support (Issue #985) + +1.3.6 2013-05-21 +---------------- +* Fixed issue where single server reconnect attempt would throw due to missing options variable (Issue #979) +* Fixed issue where difference in ismaster server name and seed list caused connections issues, (Issue #976) + +1.3.5 2013-05-14 +---------------- +* Fixed issue where HA for replicaset would pick the same broken connection when attempting to ping the replicaset causing the replicaset to never recover. + +1.3.4 2013-05-14 +---------------- +* Fixed bug where options not correctly passed in for uri parser (Issue #973, https://github.com/supershabam) +* Fixed bug when passing a named index hint (Issue #974) + +1.3.3 2013-05-09 +---------------- +* Fixed auto-reconnect issue with single server instance. + +1.3.2 2013-05-08 +---------------- +* Fixes for an issue where replicaset would be pronounced dead when high priority primary caused double elections. + +1.3.1 2013-05-06 +---------------- +* Fix for replicaset consisting of primary/secondary/arbiter with priority applied failing to reconnect properly +* Applied auth before server instance is set as connected when single server connection +* Throw error if array of documents passed to save method + +1.3.0 2013-04-25 +---------------- +* Whole High availability handling for Replicaset, Server and Mongos connections refactored to ensure better handling of failover cases. +* Fixed issue where findAndModify would not correctly skip issuing of chained getLastError (Issue #941) +* Fixed throw error issue on errors with findAndModify during write out operation (Issue #939, https://github.com/autopulated) +* Gridstore.prototype.writeFile now returns gridstore object correctly (Issue #938) +* Kerberos support is now an optional module that allows for use of GSSAPI authentication using MongoDB Subscriber edition +* Fixed issue where cursor.toArray could blow the stack on node 0.10.X (#950) + +1.2.14 2013-03-14 +----------------- +* Refactored test suite to speed up running of replicaset tests +* Fix of async error handling when error happens in callback (Issue #909, https://github.com/medikoo) +* Corrected a slaveOk setting issue (Issue #906, #905) +* Fixed HA issue where ping's would not go to correct server on HA server connection failure. +* Uses setImmediate if on 0.10 otherwise nextTick for cursor stream +* Fixed race condition in Cursor stream (NODE-31) +* Fixed issues related to node 0.10 and process.nextTick now correctly using setImmediate where needed on node 0.10 +* Added support for maxMessageSizeBytes if available (DRIVERS-1) +* Added support for authSource (2.4) to MongoClient URL and db.authenticate method (DRIVER-69/NODE-34) +* Fixed issue in GridStore seek and GridStore read to correctly work on multiple seeks (Issue #895) + +1.2.13 2013-02-22 +----------------- +* Allow strategy 'none' for repliaset if no strategy wanted (will default to round robin selection of servers on a set readPreference) +* Fixed missing MongoErrors on some cursor methods (Issue #882) +* Correctly returning a null for the db instance on MongoClient.connect when auth fails (Issue #890) +* Added dropTarget option support for renameCollection/rename (Issue #891, help from https://github.com/jbottigliero) +* Fixed issue where connection using MongoClient.connect would fail if first server did not exist (Issue #885) + +1.2.12 2013-02-13 +----------------- +* Added limit/skip options to Collection.count (Issue #870) +* Added applySkipLimit option to Cursor.count (Issue #870) +* Enabled ping strategy as default for Replicaset if none specified (Issue #876) +* Should correctly pick nearest server for SECONDARY/SECONDARY_PREFERRED/NEAREST (Issue #878) + +1.2.11 2013-01-29 +----------------- +* Added fixes for handling type 2 binary due to PHP driver (Issue #864) +* Moved callBackStore to Base class to have single unified store (Issue #866) +* Ping strategy now reuses sockets unless they are closed by the server to avoid overhead + +1.2.10 2013-01-25 +----------------- +* Merged in SSL support for 2.4 supporting certificate validation and presenting certificates to the server. +* Only open a new HA socket when previous one dead (Issue #859, #857) +* Minor fixes + +1.2.9 2013-01-15 +---------------- +* Fixed bug in SSL support for MongoClient/Db.connect when discovering servers (Issue #849) +* Connection string with no db specified should default to admin db (Issue #848) +* Support port passed as string to Server class (Issue #844) +* Removed noOpen support for MongoClient/Db.connect as auto discovery of servers for Mongod/Mongos makes it not possible (Issue #842) +* Included toError wrapper code moved to utils.js file (Issue #839, #840) +* Rewrote cursor handling to avoid process.nextTick using trampoline instead to avoid stack overflow, speedup about 40% + +1.2.8 2013-01-07 +---------------- +* Accept function in a Map Reduce scope object not only a function string (Issue #826, https://github.com/aheckmann) +* Typo in db.authenticate caused a check (for provided connection) to return false, causing a connection AND onAll=true to be passed into __executeQueryCommand downstream (Issue #831, https://github.com/m4tty) +* Allow gridfs objects to use non ObjectID ids (Issue #825, https://github.com/nailgun) +* Removed the double wrap, by not passing an Error object to the wrap function (Issue #832, https://github.com/m4tty) +* Fix connection leak (gh-827) for HA replicaset health checks (Issue #833, https://github.com/aheckmann) +* Modified findOne to use nextObject instead of toArray avoiding a nextTick operation (Issue #836) +* Fixes for cursor stream to avoid multiple getmore issues when one in progress (Issue #818) +* Fixes .open replaying all backed up commands correctly if called after operations performed, (Issue #829 and #823) + +1.2.7 2012-12-23 +---------------- +* Rolled back batches as they hang in certain situations +* Fixes for NODE-25, keep reading from secondaries when primary goes down + +1.2.6 2012-12-21 +---------------- +* domain sockets shouldn't require a port arg (Issue #815, https://github.com/aheckmann) +* Cannot read property 'info' of null (Issue #809, https://github.com/thesmart) +* Cursor.each should work in batches (Issue #804, https://github.com/Swatinem) +* Cursor readPreference bug for non-supported read preferences (Issue #817) + +1.2.5 2012-12-12 +---------------- +* Fixed ssl regression, added more test coverage (Issue #800) +* Added better error reporting to the Db.connect if no valid serverConfig setup found (Issue #798) + +1.2.4 2012-12-11 +---------------- +* Fix to ensure authentication is correctly applied across all secondaries when using MongoClient. + +1.2.3 2012-12-10 +---------------- +* Fix for new replicaset members correctly authenticating when being added (Issue #791, https://github.com/m4tty) +* Fixed seek issue in gridstore when using stream (Issue #790) + +1.2.2 2012-12-03 +---------------- +* Fix for journal write concern not correctly being passed under some circumstances. +* Fixed correct behavior and re-auth for servers that get stepped down (Issue #779). + +1.2.1 2012-11-30 +---------------- +* Fix for double callback on insert with w:0 specified (Issue #783) +* Small cleanup of urlparser. + +1.2.0 2012-11-27 +---------------- +* Honor connectTimeoutMS option for replicasets (Issue #750, https://github.com/aheckmann) +* Fix ping strategy regression (Issue #738, https://github.com/aheckmann) +* Small cleanup of code (Issue #753, https://github.com/sokra/node-mongodb-native) +* Fixed index declaration using objects/arrays from other contexts (Issue #755, https://github.com/sokra/node-mongodb-native) +* Intermittent (and rare) null callback exception when using ReplicaSets (Issue #752) +* Force correct setting of read_secondary based on the read preference (Issue #741) +* If using read preferences with secondaries queries will not fail if primary is down (Issue #744) +* noOpen connection for Db.connect removed as not compatible with autodetection of Mongo type +* Mongos connection with auth not working (Issue #737) +* Use the connect method directly from the require. require('mongodb')("mongodb://localhost:27017/db") +* new MongoClient introduced as the point of connecting to MongoDB's instead of the Db + * open/close/db/connect methods implemented +* Implemented common URL connection format using MongoClient.connect allowing for simialar interface across all drivers. +* Fixed a bug with aggregation helper not properly accepting readPreference + +1.1.11 2012-10-10 +----------------- +* Removed strict mode and introduced normal handling of safe at DB level. + +1.1.10 2012-10-08 +----------------- +* fix Admin.serverStatus (Issue #723, https://github.com/Contra) +* logging on connection open/close(Issue #721, https://github.com/asiletto) +* more fixes for windows bson install (Issue #724) + +1.1.9 2012-10-05 +---------------- +* Updated bson to 0.1.5 to fix build problem on sunos/windows. + +1.1.8 2012-10-01 +---------------- +* Fixed db.eval to correctly handle system.js global javascript functions (Issue #709) +* Cleanup of non-closing connections (Issue #706) +* More cleanup of connections under replicaset (Issue #707, https://github.com/elbert3) +* Set keepalive on as default, override if not needed +* Cleanup of jsbon install to correctly build without install.js script (https://github.com/shtylman) +* Added domain socket support new Server("/tmp/mongodb.sock") style + +1.1.7 2012-09-10 +---------------- +* Protect against starting PingStrategy being called more than once (Issue #694, https://github.com/aheckmann) +* Make PingStrategy interval configurable (was 1 second, relaxed to 5) (Issue #693, https://github.com/aheckmann) +* Made PingStrategy api more consistant, callback to start/stop methods are optional (Issue #693, https://github.com/aheckmann) +* Proper stopping of strategy on replicaset stop +* Throw error when gridstore file is not found in read mode (Issue #702, https://github.com/jbrumwell) +* Cursor stream resume now using nextTick to avoid duplicated records (Issue #696) + +1.1.6 2012-09-01 +---------------- +* Fix for readPreference NEAREST for replicasets (Issue #693, https://github.com/aheckmann) +* Emit end correctly on stream cursor (Issue #692, https://github.com/Raynos) + +1.1.5 2012-08-29 +---------------- +* Fix for eval on replicaset Issue #684 +* Use helpful error msg when native parser not compiled (Issue #685, https://github.com/aheckmann) +* Arbiter connect hotfix (Issue #681, https://github.com/fengmk2) +* Upgraded bson parser to 0.1.2 using gyp, deprecated support for node 0.4.X +* Added name parameter to createIndex/ensureIndex to be able to override index names larger than 128 bytes +* Added exhaust option for find for feature completion (not recommended for normal use) +* Added tailableRetryInterval to find for tailable cursors to allow to control getMore retry time interval +* Fixes for read preferences when using MongoS to correctly handle no read preference set when iterating over a cursor (Issue #686) + +1.1.4 2012-08-12 +---------------- +* Added Mongos connection type with a fallback list for mongos proxies, supports ha (on by default) and will attempt to reconnect to failed proxies. +* Documents can now have a toBSON method that lets the user control the serialization behavior for documents being saved. +* Gridstore instance object now works as a readstream or writestream (thanks to code from Aaron heckmann (https://github.com/aheckmann/gridfs-stream)). +* Fix gridfs readstream (Issue #607, https://github.com/tedeh). +* Added disableDriverBSONSizeCheck property to Server.js for people who wish to push the inserts to the limit (Issue #609). +* Fixed bug where collection.group keyf given as Code is processed as a regular object (Issue #608, https://github.com/rrusso2007). +* Case mismatch between driver's ObjectID and mongo's ObjectId, allow both (Issue #618). +* Cleanup map reduce (Issue #614, https://github.com/aheckmann). +* Add proper error handling to gridfs (Issue #615, https://github.com/aheckmann). +* Ensure cursor is using same connection for all operations to avoid potential jump of servers when using replicasets. +* Date identification handled correctly in bson js parser when running in vm context. +* Documentation updates +* GridStore filename not set on read (Issue #621) +* Optimizations on the C++ bson parser to fix a potential memory leak and avoid non-needed calls +* Added support for awaitdata for tailable cursors (Issue #624) +* Implementing read preference setting at collection and cursor level + * collection.find().setReadPreference(Server.SECONDARY_PREFERRED) + * db.collection("some", {readPreference:Server.SECONDARY}) +* Replicaset now returns when the master is discovered on db.open and lets the rest of the connections happen asynchronous. + * ReplSet/ReplSetServers emits "fullsetup" when all servers have been connected to +* Prevent callback from executing more than once in getMore function (Issue #631, https://github.com/shankar0306) +* Corrupt bson messages now errors out to all callbacks and closes up connections correctly, Issue #634 +* Replica set member status update when primary changes bug (Issue #635, https://github.com/alinsilvian) +* Fixed auth to work better when multiple connections are involved. +* Default connection pool size increased to 5 connections. +* Fixes for the ReadStream class to work properly with 0.8 of Node.js +* Added explain function support to aggregation helper +* Added socketTimeoutMS and connectTimeoutMS to socket options for repl_set.js and server.js +* Fixed addUser to correctly handle changes in 2.2 for getLastError authentication required +* Added index to gridstore chunks on file_id (Issue #649, https://github.com/jacobbubu) +* Fixed Always emit db events (Issue #657) +* Close event not correctly resets DB openCalled variable to allow reconnect +* Added open event on connection established for replicaset, mongos and server +* Much faster BSON C++ parser thanks to Lucasfilm Singapore. +* Refactoring of replicaset connection logic to simplify the code. +* Add `options.connectArbiter` to decide connect arbiters or not (Issue #675) +* Minor optimization for findAndModify when not using j,w or fsync for safe + +1.0.2 2012-05-15 +---------------- +* Reconnect functionality for replicaset fix for mongodb 2.0.5 + +1.0.1 2012-05-12 +---------------- +* Passing back getLastError object as 3rd parameter on findAndModify command. +* Fixed a bunch of performance regressions in objectId and cursor. +* Fixed issue #600 allowing for single document delete to be passed in remove command. + +1.0.0 2012-04-25 +---------------- +* Fixes to handling of failover on server error +* Only emits error messages if there are error listeners to avoid uncaught events +* Server.isConnected using the server state variable not the connection pool state + +0.9.9.8 2012-04-12 +------------------ +* _id=0 is being turned into an ObjectID (Issue #551) +* fix for error in GridStore write method (Issue #559) +* Fix for reading a GridStore from arbitrary, non-chunk aligned offsets, added test (Issue #563, https://github.com/subroutine) +* Modified limitRequest to allow negative limits to pass through to Mongo, added test (Issue #561) +* Corrupt GridFS files when chunkSize < fileSize, fixed concurrency issue (Issue #555) +* Handle dead tailable cursors (Issue #568, https://github.com/aheckmann) +* Connection pools handles closing themselves down and clearing the state +* Check bson size of documents against maxBsonSize and throw client error instead of server error, (Issue #553) +* Returning update status document at the end of the callback for updates, (Issue #569) +* Refactor use of Arguments object to gain performance (Issue #574, https://github.com/AaronAsAChimp) + +0.9.9.7 2012-03-16 +------------------ +* Stats not returned from map reduce with inline results (Issue #542) +* Re-enable testing of whether or not the callback is called in the multi-chunk seek, fix small GridStore bug (Issue #543, https://github.com/pgebheim) +* Streaming large files from GridFS causes truncation (Issue #540) +* Make callback type checks agnostic to V8 context boundaries (Issue #545) +* Correctly throw error if an attempt is made to execute an insert/update/remove/createIndex/ensureIndex with safe enabled and no callback +* Db.open throws if the application attemps to call open again without calling close first + +0.9.9.6 2012-03-12 +------------------ +* BSON parser is externalized in it's own repository, currently using git master +* Fixes for Replicaset connectivity issue (Issue #537) +* Fixed issues with node 0.4.X vs 0.6.X (Issue #534) +* Removed SimpleEmitter and replaced with standard EventEmitter +* GridStore.seek fails to change chunks and call callback when in read mode (Issue #532) + +0.9.9.5 2012-03-07 +------------------ +* Merged in replSetGetStatus helper to admin class (Issue #515, https://github.com/mojodna) +* Merged in serverStatus helper to admin class (Issue #516, https://github.com/mojodna) +* Fixed memory leak in C++ bson parser (Issue #526) +* Fix empty MongoError "message" property (Issue #530, https://github.com/aheckmann) +* Cannot save files with the same file name to GridFS (Issue #531) + +0.9.9.4 2012-02-26 +------------------ +* bugfix for findAndModify: Error: corrupt bson message < 5 bytes long (Issue #519) + +0.9.9.3 2012-02-23 +------------------ +* document: save callback arguments are both undefined, (Issue #518) +* Native BSON parser install error with npm, (Issue #517) + +0.9.9.2 2012-02-17 +------------------ +* Improved detection of Buffers using Buffer.isBuffer instead of instanceof. +* Added wrap error around db.dropDatabase to catch all errors (Issue #512) +* Added aggregate helper to collection, only for MongoDB >= 2.1 + +0.9.9.1 2012-02-15 +------------------ +* Better handling of safe when using some commands such as createIndex, ensureIndex, addUser, removeUser, createCollection. +* Mapreduce now throws error if out parameter is not specified. + +0.9.9 2012-02-13 +---------------- +* Added createFromTime method on ObjectID to allow for queries against _id more easily using the timestamp. +* Db.close(true) now makes connection unusable as it's been force closed by app. +* Fixed mapReduce and group functions to correctly send slaveOk on queries. +* Fixes for find method to correctly work with find(query, fields, callback) (Issue #506). +* A fix for connection error handling when using the SSL on MongoDB. + +0.9.8-7 2012-02-06 +------------------ +* Simplified findOne to use the find command instead of the custom code (Issue #498). +* BSON JS parser not also checks for _bsonType variable in case BSON object is in weird scope (Issue #495). + +0.9.8-6 2012-02-04 +------------------ +* Removed the check for replicaset change code as it will never work with node.js. + +0.9.8-5 2012-02-02 +------------------ +* Added geoNear command to Collection. +* Added geoHaystackSearch command to Collection. +* Added indexes command to collection to retrieve the indexes on a Collection. +* Added stats command to collection to retrieve the statistics on a Collection. +* Added listDatabases command to admin object to allow retrieval of all available dbs. +* Changed createCreateIndexCommand to work better with options. +* Fixed dereference method on Db class to correctly dereference Db reference objects. +* Moved connect object onto Db class(Db.connect) as well as keeping backward compatibility. +* Removed writeBuffer method from gridstore, write handles switching automatically now. +* Changed readBuffer to read on Gridstore, Gridstore now only supports Binary Buffers no Strings anymore. +* Moved Long class to bson directory. + +0.9.8-4 2012-01-28 +------------------ +* Added reIndex command to collection and db level. +* Added support for $returnKey, $maxScan, $min, $max, $showDiskLoc, $comment to cursor and find/findOne methods. +* Added dropDups and v option to createIndex and ensureIndex. +* Added isCapped method to Collection. +* Added indexExists method to Collection. +* Added findAndRemove method to Collection. +* Fixed bug for replicaset connection when no active servers in the set. +* Fixed bug for replicaset connections when errors occur during connection. +* Merged in patch for BSON Number handling from Lee Salzman, did some small fixes and added test coverage. + +0.9.8-3 2012-01-21 +------------------ +* Workaround for issue with Object.defineProperty (Issue #484) +* ObjectID generation with date does not set rest of fields to zero (Issue #482) + +0.9.8-2 2012-01-20 +------------------ +* Fixed a missing this in the ReplSetServers constructor. + +0.9.8-1 2012-01-17 +------------------ +* FindAndModify bug fix for duplicate errors (Issue #481) + +0.9.8 2012-01-17 +---------------- +* Replicasets now correctly adjusts to live changes in the replicaset configuration on the servers, reconnecting correctly. + * Set the interval for checking for changes setting the replicaSetCheckInterval property when creating the ReplSetServers instance or on db.serverConfig.replicaSetCheckInterval. (default 1000 miliseconds) +* Fixes formattedOrderClause in collection.js to accept a plain hash as a parameter (Issue #469) https://github.com/tedeh +* Removed duplicate code for formattedOrderClause and moved to utils module +* Pass in poolSize for ReplSetServers to set default poolSize for new replicaset members +* Bug fix for BSON JS deserializer. Isolating the eval functions in separate functions to avoid V8 deoptimizations +* Correct handling of illegal BSON messages during deserialization +* Fixed Infinite loop when reading GridFs file with no chunks (Issue #471) +* Correctly update existing user password when using addUser (Issue #470) + +0.9.7.3-5 2012-01-04 +-------------------- +* Fix for RegExp serialization for 0.4.X where typeof /regexp/ == 'function' vs in 0.6.X typeof /regexp/ == 'object' +* Don't allow keepAlive and setNoDelay for 0.4.X as it throws errors + +0.9.7.3-4 2012-01-04 +-------------------- +* Chased down potential memory leak on findAndModify, Issue #467 (node.js removeAllListeners leaves the key in the _events object, node.js bug on eventlistener?, leads to extremely slow memory leak on listener object) +* Sanity checks for GridFS performance with benchmark added + +0.9.7.3-3 2012-01-04 +-------------------- +* Bug fixes for performance issues going form 0.9.6.X to 0.9.7.X on linux +* BSON bug fixes for performance + +0.9.7.3-2 2012-01-02 +-------------------- +* Fixed up documentation to reflect the preferred way of instantiating bson types +* GC bug fix for JS bson parser to avoid stop-and-go GC collection + +0.9.7.3-1 2012-01-02 +-------------------- +* Fix to make db.bson_serializer and db.bson_deserializer work as it did previously + +0.9.7.3 2011-12-30 +-------------------- +* Moved BSON_BINARY_SUBTYPE_DEFAULT from BSON object to Binary object and removed the BSON_BINARY_ prefixes +* Removed Native BSON types, C++ parser uses JS types (faster due to cost of crossing the JS-C++ barrier for each call) +* Added build fix for 0.4.X branch of Node.js where GetOwnPropertyNames is not defined in v8 +* Fix for wire protocol parser for corner situation where the message is larger than the maximum socket buffer in node.js (Issue #464, #461, #447) +* Connection pool status set to connected on poolReady, isConnected returns false on anything but connected status (Issue #455) + +0.9.7.2-5 2011-12-22 +-------------------- +* Brand spanking new Streaming Cursor support Issue #458 (https://github.com/christkv/node-mongodb-native/pull/458) thanks to Mr Aaron Heckmann + +0.9.7.2-4 2011-12-21 +-------------------- +* Refactoring of callback code to work around performance regression on linux +* Fixed group function to correctly use the command mode as default + +0.9.7.2-3 2011-12-18 +-------------------- +* Fixed error handling for findAndModify while still working for mongodb 1.8.6 (Issue #450). +* Allow for force send query to primary, pass option (read:'primary') on find command. + * ``find({a:1}, {read:'primary'}).toArray(function(err, items) {});`` + +0.9.7.2-2 2011-12-16 +-------------------- +* Fixes infinite streamRecords QueryFailure fix when using Mongos (Issue #442) + +0.9.7.2-1 2011-12-16 +-------------------- +* ~10% perf improvement for ObjectId#toHexString (Issue #448, https://github.com/aheckmann) +* Only using process.nextTick on errors emitted on callbacks not on all parsing, reduces number of ticks in the driver +* Changed parsing off bson messages to use process.nextTick to do bson parsing in batches if the message is over 10K as to yield more time to the event look increasing concurrency on big mongoreply messages with multiple documents + +0.9.7.2 2011-12-15 +------------------ +* Added SSL support for future version of mongodb (VERY VERY EXPERIMENTAL) + * pass in the ssl:true option to the server or replicaset server config to enable + * a bug either in mongodb or node.js does not allow for more than 1 connection pr db instance (poolSize:1). +* Added getTimestamp() method to objectID that returns a date object +* Added finalize function to collection.group + * function group (keys, condition, initial, reduce, finalize, command, callback) +* Reaper no longer using setTimeout to handle reaping. Triggering is done in the general flow leading to predictable behavior. + * reaperInterval, set interval for reaper (default 10000 miliseconds) + * reaperTimeout, set timeout for calls (default 30000 miliseconds) + * reaper, enable/disable reaper (default false) +* Work around for issues with findAndModify during high concurrency load, insure that the behavior is the same across the 1.8.X branch and 2.X branch of MongoDb +* Reworked multiple db's sharing same connection pool to behave correctly on error, timeout and close +* EnsureIndex command can be executed without a callback (Issue #438) +* Eval function no accepts options including nolock (Issue #432) + * eval(code, parameters, options, callback) (where options = {nolock:true}) + +0.9.7.1-4 2011-11-27 +-------------------- +* Replaced install.sh with install.js to install correctly on all supported os's + +0.9.7.1-3 2011-11-27 +-------------------- +* Fixes incorrect scope for ensureIndex error wrapping (Issue #419) https://github.com/ritch + +0.9.7.1-2 2011-11-27 +-------------------- +* Set statistical selection strategy as default for secondary choice. + +0.9.7.1-1 2011-11-27 +-------------------- +* Better handling of single server reconnect (fixes some bugs) +* Better test coverage of single server failure +* Correct handling of callbacks on replicaset servers when firewall dropping packets, correct reconnect + +0.9.7.1 2011-11-24 +------------------ +* Better handling of dead server for single server instances +* FindOne and find treats selector == null as {}, Issue #403 +* Possible to pass in a strategy for the replicaset to pick secondary reader node + * parameter strategy + * ping (default), pings the servers and picks the one with the lowest ping time + * statistical, measures each request and pick the one with the lowest mean and std deviation +* Set replicaset read preference replicaset.setReadPreference() + * Server.READ_PRIMARY (use primary server for reads) + * Server.READ_SECONDARY (from a secondary server (uses the strategy set)) + * tags, {object of tags} +* Added replay of commands issued to a closed connection when the connection is re-established +* Fix isConnected and close on unopened connections. Issue #409, fix by (https://github.com/sethml) +* Moved reaper to db.open instead of constructor (Issue #406) +* Allows passing through of socket connection settings to Server or ReplSetServer under the option socketOptions + * timeout = set seconds before connection times out (default 0) + * noDelay = Disables the Nagle algorithm (default true) + * keepAlive = Set if keepAlive is used (default 0, which means no keepAlive, set higher than 0 for keepAlive) + * encoding = ['ascii', 'utf8', or 'base64'] (default null) +* Fixes for handling of errors during shutdown off a socket connection +* Correctly applies socket options including timeout +* Cleanup of test management code to close connections correctly +* Handle parser errors better, closing down the connection and emitting an error +* Correctly emit errors from server.js only wrapping errors that are strings + +0.9.7 2011-11-10 +---------------- +* Added priority setting to replicaset manager +* Added correct handling of passive servers in replicaset +* Reworked socket code for simpler clearer handling +* Correct handling of connections in test helpers +* Added control of retries on failure + * control with parameters retryMiliSeconds and numberOfRetries when creating a db instance +* Added reaper that will timeout and cleanup queries that never return + * control with parameters reaperInterval and reaperTimeout when creating a db instance +* Refactored test helper classes for replicaset tests +* Allows raw (no bson parser mode for insert, update, remove, find and findOne) + * control raw mode passing in option raw:true on the commands + * will return buffers with the binary bson objects +* Fixed memory leak in cursor.toArray +* Fixed bug in command creation for mongodb server with wrong scope of call +* Added db(dbName) method to db.js to allow for reuse of connections against other databases +* Serialization of functions in an object is off by default, override with parameter + * serializeFunctions [true/false] on db level, collection level or individual insert/update/findAndModify +* Added Long.fromString to c++ class and fixed minor bug in the code (Test case for $gt operator on 64-bit integers, Issue #394) +* FindOne and find now share same code execution and will work in the same manner, Issue #399 +* Fix for tailable cursors, Issue #384 +* Fix for Cursor rewind broken, Issue #389 +* Allow Gridstore.exist to query using regexp, Issue #387, fix by (https://github.com/kaij) +* Updated documentation on https://github.com/christkv/node-mongodb-native +* Fixed toJSON methods across all objects for BSON, Binary return Base64 Encoded data + +0.9.6-22 2011-10-15 +------------------- +* Fixed bug in js bson parser that could cause wrong object size on serialization, Issue #370 +* Fixed bug in findAndModify that did not throw error on replicaset timeout, Issue #373 + +0.9.6-21 2011-10-05 +------------------- +* Reworked reconnect code to work correctly +* Handling errors in different parts of the code to ensure that it does not lock the connection +* Consistent error handling for Object.createFromHexString for JS and C++ + +0.9.6-20 2011-10-04 +------------------- +* Reworked bson.js parser to get rid off Array.shift() due to it allocating new memory for each call. Speedup varies between 5-15% depending on doc +* Reworked bson.cc to throw error when trying to serialize js bson types +* Added MinKey, MaxKey and Double support for JS and C++ parser +* Reworked socket handling code to emit errors on unparsable messages +* Added logger option for Db class, lets you pass in a function in the shape + { + log : function(message, object) {}, + error : function(errorMessage, errorObject) {}, + debug : function(debugMessage, object) {}, + } + + Usage is new Db(new Server(..), {logger: loggerInstance}) + +0.9.6-19 2011-09-29 +------------------- +* Fixing compatibility issues between C++ bson parser and js parser +* Added Symbol support to C++ parser +* Fixed socket handling bug for seldom misaligned message from mongodb +* Correctly handles serialization of functions using the C++ bson parser + +0.9.6-18 2011-09-22 +------------------- +* Fixed bug in waitForConnection that would lead to 100% cpu usage, Issue #352 + +0.9.6-17 2011-09-21 +------------------- +* Fixed broken exception test causing bamboo to hang +* Handling correctly command+lastError when both return results as in findAndModify, Issue #351 + +0.9.6-16 2011-09-14 +------------------- +* Fixing a bunch of issues with compatibility with MongoDB 2.0.X branch. Some fairly big changes in behavior from 1.8.X to 2.0.X on the server. +* Error Connection MongoDB V2.0.0 with Auth=true, Issue #348 + +0.9.6-15 2011-09-09 +------------------- +* Fixed issue where pools would not be correctly cleaned up after an error, Issue #345 +* Fixed authentication issue with secondary servers in Replicaset, Issue #334 +* Duplicate replica-set servers when omitting port, Issue #341 +* Fixing findAndModify to correctly work with Replicasets ensuring proper error handling, Issue #336 +* Merged in code from (https://github.com/aheckmann) that checks for global variable leaks + +0.9.6-14 2011-09-05 +------------------- +* Minor fixes for error handling in cursor streaming (https://github.com/sethml), Issue #332 +* Minor doc fixes +* Some more cursor sort tests added, Issue #333 +* Fixes to work with 0.5.X branch +* Fix Db not removing reconnect listener from serverConfig, (https://github.com/sbrekken), Issue #337 +* Removed node_events.h includes (https://github.com/jannehietamaki), Issue #339 +* Implement correct safe/strict mode for findAndModify. + +0.9.6-13 2011-08-24 +------------------- +* Db names correctly error checked for illegal characters + +0.9.6-12 2011-08-24 +------------------- +* Nasty bug in GridFS if you changed the default chunk size +* Fixed error handling bug in findOne + +0.9.6-11 2011-08-23 +------------------- +* Timeout option not correctly making it to the cursor, Issue #320, Fix from (https://github.com/year2013) +* Fixes for memory leaks when using buffers and C++ parser +* Fixes to make tests pass on 0.5.X +* Cleanup of bson.js to remove duplicated code paths +* Fix for errors occurring in ensureIndex, Issue #326 +* Removing require.paths to make tests work with the 0.5.X branch + +0.9.6-10 2011-08-11 +------------------- +* Specific type Double for capped collections (https://github.com/mbostock), Issue #312 +* Decorating Errors with all all object info from Mongo (https://github.com/laurie71), Issue #308 +* Implementing fixes for mongodb 1.9.1 and higher to make tests pass +* Admin validateCollection now takes an options argument for you to pass in full option +* Implemented keepGoing parameter for mongodb 1.9.1 or higher, Issue #310 +* Added test for read_secondary count issue, merged in fix from (https://github.com/year2013), Issue #317 + +0.9.6-9 +------- +* Bug fix for bson parsing the key '':'' correctly without crashing + +0.9.6-8 +------- +* Changed to using node.js crypto library MD5 digest +* Connect method support documented mongodb: syntax by (https://github.com/sethml) +* Support Symbol type for BSON, serializes to it's own type Symbol, Issue #302, #288 +* Code object without scope serializing to correct BSON type +* Lot's of fixes to avoid double callbacks (https://github.com/aheckmann) Issue #304 +* Long deserializes as Number for values in the range -2^53 to 2^53, Issue #305 (https://github.com/sethml) +* Fixed C++ parser to reflect JS parser handling of long deserialization +* Bson small optimizations + +0.9.6-7 2011-07-13 +------------------ +* JS Bson deserialization bug #287 + +0.9.6-6 2011-07-12 +------------------ +* FindAndModify not returning error message as other methods Issue #277 +* Added test coverage for $push, $pushAll and $inc atomic operations +* Correct Error handling for non 12/24 bit ids on Pure JS ObjectID class Issue #276 +* Fixed terrible deserialization bug in js bson code #285 +* Fix by andrewjstone to avoid throwing errors when this.primary not defined + +0.9.6-5 2011-07-06 +------------------ +* Rewritten BSON js parser now faster than the C parser on my core2duo laptop +* Added option full to indexInformation to get all index info Issue #265 +* Passing in ObjectID for new Gridstore works correctly Issue #272 + +0.9.6-4 2011-07-01 +------------------ +* Added test and bug fix for insert/update/remove without callback supplied + +0.9.6-3 2011-07-01 +------------------ +* Added simple grid class called Grid with put, get, delete methods +* Fixed writeBuffer/readBuffer methods on GridStore so they work correctly +* Automatic handling of buffers when using write method on GridStore +* GridStore now accepts a ObjectID instead of file name for write and read methods +* GridStore.list accepts id option to return of file ids instead of filenames +* GridStore close method returns document for the file allowing user to reference _id field + +0.9.6-2 2011-06-30 +------------------ +* Fixes for reconnect logic for server object (replays auth correctly) +* More testcases for auth +* Fixes in error handling for replicaset +* Fixed bug with safe parameter that would fail to execute safe when passing w or wtimeout +* Fixed slaveOk bug for findOne method +* Implemented auth support for replicaset and test cases +* Fixed error when not passing in rs_name + +0.9.6-1 2011-06-25 +------------------ +* Fixes for test to run properly using c++ bson parser +* Fixes for dbref in native parser (correctly handles ref without db component) +* Connection fixes for replicasets to avoid runtime conditions in cygwin (https://github.com/vincentcr) +* Fixes for timestamp in js bson parser (distinct timestamp type now) + +0.9.6 2011-06-21 +---------------- +* Worked around npm version handling bug +* Race condition fix for cygwin (https://github.com/vincentcr) + +0.9.5-1 2011-06-21 +------------------ +* Extracted Timestamp as separate class for bson js parser to avoid instanceof problems +* Fixed driver strict mode issue + +0.9.5 2011-06-20 +---------------- +* Replicaset support (failover and reading from secondary servers) +* Removed ServerPair and ServerCluster +* Added connection pool functionality +* Fixed serious bug in C++ bson parser where bytes > 127 would generate 2 byte sequences +* Allows for forcing the server to assign ObjectID's using the option {forceServerObjectId: true} + +0.6.8 +----- +* Removed multiple message concept from bson +* Changed db.open(db) to be db.open(err, db) + +0.1 2010-01-30 +-------------- +* Initial release support of driver using native node.js interface +* Supports gridfs specification +* Supports admin functionality diff --git a/scripts/node_modules/mongodb/LICENSE.md b/scripts/node_modules/mongodb/LICENSE.md new file mode 100644 index 00000000..ad410e11 --- /dev/null +++ b/scripts/node_modules/mongodb/LICENSE.md @@ -0,0 +1,201 @@ +Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/scripts/node_modules/mongodb/README.md b/scripts/node_modules/mongodb/README.md new file mode 100644 index 00000000..672ccf39 --- /dev/null +++ b/scripts/node_modules/mongodb/README.md @@ -0,0 +1,499 @@ +[![npm](https://nodei.co/npm/mongodb.png?downloads=true&downloadRank=true)](https://nodei.co/npm/mongodb/) [![npm](https://nodei.co/npm-dl/mongodb.png?months=6&height=3)](https://nodei.co/npm/mongodb/) + +[![Build Status](https://secure.travis-ci.org/mongodb/node-mongodb-native.svg?branch=2.1)](http://travis-ci.org/mongodb/node-mongodb-native) +[![Coverage Status](https://coveralls.io/repos/github/mongodb/node-mongodb-native/badge.svg?branch=2.1)](https://coveralls.io/github/mongodb/node-mongodb-native?branch=2.1) +[![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/mongodb/node-mongodb-native?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) + +# Description + +The official [MongoDB](https://www.mongodb.com/) driver for Node.js. Provides a high-level API on top of [mongodb-core](https://www.npmjs.com/package/mongodb-core) that is meant for end users. + +**NOTE: v3.x was recently released with breaking API changes. You can find a list of changes [here](CHANGES_3.0.0.md).** + +## MongoDB Node.JS Driver + +| what | where | +|---------------|------------------------------------------------| +| documentation | http://mongodb.github.io/node-mongodb-native | +| api-doc | http://mongodb.github.io/node-mongodb-native/3.1/api | +| source | https://github.com/mongodb/node-mongodb-native | +| mongodb | http://www.mongodb.org | + +### Bugs / Feature Requests + +Think you’ve found a bug? Want to see a new feature in `node-mongodb-native`? Please open a +case in our issue management tool, JIRA: + +- Create an account and login [jira.mongodb.org](https://jira.mongodb.org). +- Navigate to the NODE project [jira.mongodb.org/browse/NODE](https://jira.mongodb.org/browse/NODE). +- Click **Create Issue** - Please provide as much information as possible about the issue type and how to reproduce it. + +Bug reports in JIRA for all driver projects (i.e. NODE, PYTHON, CSHARP, JAVA) and the +Core Server (i.e. SERVER) project are **public**. + +### Support / Feedback + +For issues with, questions about, or feedback for the Node.js driver, please look into our [support channels](http://www.mongodb.org/about/support). Please do not email any of the driver developers directly with issues or questions - you're more likely to get an answer on the [mongodb-user](http://groups.google.com/group/mongodb-user>) list on Google Groups. + +### Change Log + +Change history can be found in [`HISTORY.md`](HISTORY.md). + +### Compatibility + +For version compatibility matrices, please refer to the following links: + + * [MongoDB](https://docs.mongodb.com/ecosystem/drivers/driver-compatibility-reference/#reference-compatibility-mongodb-node) + * [NodeJS](https://docs.mongodb.com/ecosystem/drivers/driver-compatibility-reference/#reference-compatibility-language-node) + +# Installation + +The recommended way to get started using the Node.js 3.0 driver is by using the `npm` (Node Package Manager) to install the dependency in your project. + +## MongoDB Driver + +Given that you have created your own project using `npm init` we install the MongoDB driver and its dependencies by executing the following `npm` command. + +```bash +npm install mongodb --save +``` + +This will download the MongoDB driver and add a dependency entry in your `package.json` file. + +You can also use the [Yarn](https://yarnpkg.com/en) package manager. + +## Troubleshooting + +The MongoDB driver depends on several other packages. These are: + +* [mongodb-core](https://github.com/mongodb-js/mongodb-core) +* [bson](https://github.com/mongodb/js-bson) +* [kerberos](https://github.com/mongodb-js/kerberos) +* [node-gyp](https://github.com/nodejs/node-gyp) + +The `kerberos` package is a C++ extension that requires a build environment to be installed on your system. You must be able to build Node.js itself in order to compile and install the `kerberos` module. Furthermore, the `kerberos` module requires the MIT Kerberos package to correctly compile on UNIX operating systems. Consult your UNIX operation system package manager for what libraries to install. + +**Windows already contains the SSPI API used for Kerberos authentication. However, you will need to install a full compiler tool chain using Visual Studio C++ to correctly install the Kerberos extension.** + +### Diagnosing on UNIX + +If you don’t have the build-essentials, this module won’t build. In the case of Linux, you will need gcc, g++, Node.js with all the headers and Python. The easiest way to figure out what’s missing is by trying to build the Kerberos project. You can do this by performing the following steps. + +```bash +git clone https://github.com/mongodb-js/kerberos +cd kerberos +npm install +``` + +If all the steps complete, you have the right toolchain installed. If you get the error "node-gyp not found," you need to install `node-gyp` globally: + +```bash +npm install -g node-gyp +``` + +If it correctly compiles and runs the tests you are golden. We can now try to install the `mongod` driver by performing the following command. + +```bash +cd yourproject +npm install mongodb --save +``` + +If it still fails the next step is to examine the npm log. Rerun the command but in this case in verbose mode. + +```bash +npm --loglevel verbose install mongodb +``` + +This will print out all the steps npm is performing while trying to install the module. + +### Diagnosing on Windows + +A compiler tool chain known to work for compiling `kerberos` on Windows is the following. + +* Visual Studio C++ 2010 (do not use higher versions) +* Windows 7 64bit SDK +* Python 2.7 or higher + +Open the Visual Studio command prompt. Ensure `node.exe` is in your path and install `node-gyp`. + +```bash +npm install -g node-gyp +``` + +Next, you will have to build the project manually to test it. Clone the repo, install dependencies and rebuild: + +```bash +git clone https://github.com/christkv/kerberos.git +cd kerberos +npm install +node-gyp rebuild +``` + +This should rebuild the driver successfully if you have everything set up correctly. + +### Other possible issues + +Your Python installation might be hosed making gyp break. Test your deployment environment first by trying to build Node.js itself on the server in question, as this should unearth any issues with broken packages (and there are a lot of broken packages out there). + +Another tip is to ensure your user has write permission to wherever the Node.js modules are being installed. + +## Quick Start + +This guide will show you how to set up a simple application using Node.js and MongoDB. Its scope is only how to set up the driver and perform the simple CRUD operations. For more in-depth coverage, see the [tutorials](docs/reference/content/tutorials/main.md). + +### Create the `package.json` file + +First, create a directory where your application will live. + +```bash +mkdir myproject +cd myproject +``` + +Enter the following command and answer the questions to create the initial structure for your new project: + +```bash +npm init +``` + +Next, install the driver dependency. + +```bash +npm install mongodb --save +``` + +You should see **NPM** download a lot of files. Once it's done you'll find all the downloaded packages under the **node_modules** directory. + +### Start a MongoDB Server + +For complete MongoDB installation instructions, see [the manual](https://docs.mongodb.org/manual/installation/). + +1. Download the right MongoDB version from [MongoDB](https://www.mongodb.org/downloads) +2. Create a database directory (in this case under **/data**). +3. Install and start a ``mongod`` process. + +```bash +mongod --dbpath=/data +``` + +You should see the **mongod** process start up and print some status information. + +### Connect to MongoDB + +Create a new **app.js** file and add the following code to try out some basic CRUD +operations using the MongoDB driver. + +Add code to connect to the server and the database **myproject**: + +```js +const MongoClient = require('mongodb').MongoClient; +const assert = require('assert'); + +// Connection URL +const url = 'mongodb://localhost:27017'; + +// Database Name +const dbName = 'myproject'; + +// Use connect method to connect to the server +MongoClient.connect(url, function(err, client) { + assert.equal(null, err); + console.log("Connected successfully to server"); + + const db = client.db(dbName); + + client.close(); +}); +``` + +Run your app from the command line with: + +```bash +node app.js +``` + +The application should print **Connected successfully to server** to the console. + +### Insert a Document + +Add to **app.js** the following function which uses the **insertMany** +method to add three documents to the **documents** collection. + +```js +const insertDocuments = function(db, callback) { + // Get the documents collection + const collection = db.collection('documents'); + // Insert some documents + collection.insertMany([ + {a : 1}, {a : 2}, {a : 3} + ], function(err, result) { + assert.equal(err, null); + assert.equal(3, result.result.n); + assert.equal(3, result.ops.length); + console.log("Inserted 3 documents into the collection"); + callback(result); + }); +} +``` + +The **insert** command returns an object with the following fields: + +* **result** Contains the result document from MongoDB +* **ops** Contains the documents inserted with added **_id** fields +* **connection** Contains the connection used to perform the insert + +Add the following code to call the **insertDocuments** function: + +```js +const MongoClient = require('mongodb').MongoClient; +const assert = require('assert'); + +// Connection URL +const url = 'mongodb://localhost:27017'; + +// Database Name +const dbName = 'myproject'; + +// Use connect method to connect to the server +MongoClient.connect(url, function(err, client) { + assert.equal(null, err); + console.log("Connected successfully to server"); + + const db = client.db(dbName); + + insertDocuments(db, function() { + client.close(); + }); +}); +``` + +Run the updated **app.js** file: + +```bash +node app.js +``` + +The operation returns the following output: + +```bash +Connected successfully to server +Inserted 3 documents into the collection +``` + +### Find All Documents + +Add a query that returns all the documents. + +```js +const findDocuments = function(db, callback) { + // Get the documents collection + const collection = db.collection('documents'); + // Find some documents + collection.find({}).toArray(function(err, docs) { + assert.equal(err, null); + console.log("Found the following records"); + console.log(docs) + callback(docs); + }); +} +``` + +This query returns all the documents in the **documents** collection. Add the **findDocument** method to the **MongoClient.connect** callback: + +```js +const MongoClient = require('mongodb').MongoClient; +const assert = require('assert'); + +// Connection URL +const url = 'mongodb://localhost:27017'; + +// Database Name +const dbName = 'myproject'; + +// Use connect method to connect to the server +MongoClient.connect(url, function(err, client) { + assert.equal(null, err); + console.log("Connected correctly to server"); + + const db = client.db(dbName); + + insertDocuments(db, function() { + findDocuments(db, function() { + client.close(); + }); + }); +}); +``` + +### Find Documents with a Query Filter + +Add a query filter to find only documents which meet the query criteria. + +```js +const findDocuments = function(db, callback) { + // Get the documents collection + const collection = db.collection('documents'); + // Find some documents + collection.find({'a': 3}).toArray(function(err, docs) { + assert.equal(err, null); + console.log("Found the following records"); + console.log(docs); + callback(docs); + }); +} +``` + +Only the documents which match ``'a' : 3`` should be returned. + +### Update a document + +The following operation updates a document in the **documents** collection. + +```js +const updateDocument = function(db, callback) { + // Get the documents collection + const collection = db.collection('documents'); + // Update document where a is 2, set b equal to 1 + collection.updateOne({ a : 2 } + , { $set: { b : 1 } }, function(err, result) { + assert.equal(err, null); + assert.equal(1, result.result.n); + console.log("Updated the document with the field a equal to 2"); + callback(result); + }); +} +``` + +The method updates the first document where the field **a** is equal to **2** by adding a new field **b** to the document set to **1**. Next, update the callback function from **MongoClient.connect** to include the update method. + +```js +const MongoClient = require('mongodb').MongoClient; +const assert = require('assert'); + +// Connection URL +const url = 'mongodb://localhost:27017'; + +// Database Name +const dbName = 'myproject'; + +// Use connect method to connect to the server +MongoClient.connect(url, function(err, client) { + assert.equal(null, err); + console.log("Connected successfully to server"); + + const db = client.db(dbName); + + insertDocuments(db, function() { + updateDocument(db, function() { + client.close(); + }); + }); +}); +``` + +### Remove a document + +Remove the document where the field **a** is equal to **3**. + +```js +const removeDocument = function(db, callback) { + // Get the documents collection + const collection = db.collection('documents'); + // Delete document where a is 3 + collection.deleteOne({ a : 3 }, function(err, result) { + assert.equal(err, null); + assert.equal(1, result.result.n); + console.log("Removed the document with the field a equal to 3"); + callback(result); + }); +} +``` + +Add the new method to the **MongoClient.connect** callback function. + +```js +const MongoClient = require('mongodb').MongoClient; +const assert = require('assert'); + +// Connection URL +const url = 'mongodb://localhost:27017'; + +// Database Name +const dbName = 'myproject'; + +// Use connect method to connect to the server +MongoClient.connect(url, function(err, client) { + assert.equal(null, err); + console.log("Connected successfully to server"); + + const db = client.db(dbName); + + insertDocuments(db, function() { + updateDocument(db, function() { + removeDocument(db, function() { + client.close(); + }); + }); + }); +}); +``` + +### Index a Collection + +[Indexes](https://docs.mongodb.org/manual/indexes/) can improve your application's +performance. The following function creates an index on the **a** field in the +**documents** collection. + +```js +const indexCollection = function(db, callback) { + db.collection('documents').createIndex( + { "a": 1 }, + null, + function(err, results) { + console.log(results); + callback(); + } + ); +}; +``` + +Add the ``indexCollection`` method to your app: + +```js +const MongoClient = require('mongodb').MongoClient; +const assert = require('assert'); + +// Connection URL +const url = 'mongodb://localhost:27017'; + +const dbName = 'myproject'; + +// Use connect method to connect to the server +MongoClient.connect(url, function(err, client) { + assert.equal(null, err); + console.log("Connected successfully to server"); + + const db = client.db(dbName); + + insertDocuments(db, function() { + indexCollection(db, function() { + client.close(); + }); + }); +}); +``` + +For more detailed information, see the [tutorials](docs/reference/content/tutorials/main.md). + +## Next Steps + + * [MongoDB Documentation](http://mongodb.org) + * [Read about Schemas](http://learnmongodbthehardway.com) + * [Star us on GitHub](https://github.com/mongodb/node-mongodb-native) + +## License + +[Apache 2.0](LICENSE.md) + +© 2009-2012 Christian Amor Kvalheim +© 2012-present MongoDB [Contributors](CONTRIBUTORS.md) diff --git a/scripts/node_modules/mongodb/index.js b/scripts/node_modules/mongodb/index.js new file mode 100644 index 00000000..3ce36f59 --- /dev/null +++ b/scripts/node_modules/mongodb/index.js @@ -0,0 +1,68 @@ +'use strict'; + +// Core module +const core = require('./lib/core'); +const Instrumentation = require('./lib/apm'); + +// Set up the connect function +const connect = require('./lib/mongo_client').connect; + +// Expose error class +connect.MongoError = core.MongoError; +connect.MongoNetworkError = core.MongoNetworkError; +connect.MongoTimeoutError = core.MongoTimeoutError; + +// Actual driver classes exported +connect.Admin = require('./lib/admin'); +connect.MongoClient = require('./lib/mongo_client'); +connect.Db = require('./lib/db'); +connect.Collection = require('./lib/collection'); +connect.Server = require('./lib/topologies/server'); +connect.ReplSet = require('./lib/topologies/replset'); +connect.Mongos = require('./lib/topologies/mongos'); +connect.ReadPreference = core.ReadPreference; +connect.GridStore = require('./lib/gridfs/grid_store'); +connect.Chunk = require('./lib/gridfs/chunk'); +connect.Logger = core.Logger; +connect.AggregationCursor = require('./lib/aggregation_cursor'); +connect.CommandCursor = require('./lib/command_cursor'); +connect.Cursor = require('./lib/cursor'); +connect.GridFSBucket = require('./lib/gridfs-stream'); +// Exported to be used in tests not to be used anywhere else +connect.CoreServer = core.Server; +connect.CoreConnection = core.Connection; + +// BSON types exported +connect.Binary = core.BSON.Binary; +connect.Code = core.BSON.Code; +connect.Map = core.BSON.Map; +connect.DBRef = core.BSON.DBRef; +connect.Double = core.BSON.Double; +connect.Int32 = core.BSON.Int32; +connect.Long = core.BSON.Long; +connect.MinKey = core.BSON.MinKey; +connect.MaxKey = core.BSON.MaxKey; +connect.ObjectID = core.BSON.ObjectID; +connect.ObjectId = core.BSON.ObjectID; +connect.Symbol = core.BSON.Symbol; +connect.Timestamp = core.BSON.Timestamp; +connect.BSONRegExp = core.BSON.BSONRegExp; +connect.Decimal128 = core.BSON.Decimal128; + +// Add connect method +connect.connect = connect; + +// Set up the instrumentation method +connect.instrument = function(options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + + const instrumentation = new Instrumentation(); + instrumentation.instrument(connect.MongoClient, callback); + return instrumentation; +}; + +// Set our exports to be the connect function +module.exports = connect; diff --git a/scripts/node_modules/mongodb/lib/admin.js b/scripts/node_modules/mongodb/lib/admin.js new file mode 100644 index 00000000..716844bb --- /dev/null +++ b/scripts/node_modules/mongodb/lib/admin.js @@ -0,0 +1,293 @@ +'use strict'; + +const applyWriteConcern = require('./utils').applyWriteConcern; + +const AddUserOperation = require('./operations/add_user'); +const ExecuteDbAdminCommandOperation = require('./operations/execute_db_admin_command'); +const RemoveUserOperation = require('./operations/remove_user'); +const ValidateCollectionOperation = require('./operations/validate_collection'); +const ListDatabasesOperation = require('./operations/list_databases'); + +const executeOperation = require('./operations/execute_operation'); + +/** + * @fileOverview The **Admin** class is an internal class that allows convenient access to + * the admin functionality and commands for MongoDB. + * + * **ADMIN Cannot directly be instantiated** + * @example + * const MongoClient = require('mongodb').MongoClient; + * const test = require('assert'); + * // Connection url + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * + * // Connect using MongoClient + * MongoClient.connect(url, function(err, client) { + * // Use the admin database for the operation + * const adminDb = client.db(dbName).admin(); + * + * // List all the available databases + * adminDb.listDatabases(function(err, dbs) { + * test.equal(null, err); + * test.ok(dbs.databases.length > 0); + * client.close(); + * }); + * }); + */ + +/** + * Create a new Admin instance (INTERNAL TYPE, do not instantiate directly) + * @class + * @return {Admin} a collection instance. + */ +function Admin(db, topology, promiseLibrary) { + if (!(this instanceof Admin)) return new Admin(db, topology); + + // Internal state + this.s = { + db: db, + topology: topology, + promiseLibrary: promiseLibrary + }; +} + +/** + * The callback format for results + * @callback Admin~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {object} result The result object if the command was executed successfully. + */ + +/** + * Execute a command + * @method + * @param {object} command The command hash + * @param {object} [options] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query. + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.command = function(command, options, callback) { + const args = Array.prototype.slice.call(arguments, 1); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + options = args.length ? args.shift() : {}; + + const commandOperation = new ExecuteDbAdminCommandOperation(this.s.db, command, options); + + return executeOperation(this.s.db.s.topology, commandOperation, callback); +}; + +/** + * Retrieve the server information for the current + * instance of the db client + * + * @param {Object} [options] optional parameters for this operation + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.buildInfo = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const cmd = { buildinfo: 1 }; + + const buildInfoOperation = new ExecuteDbAdminCommandOperation(this.s.db, cmd, options); + + return executeOperation(this.s.db.s.topology, buildInfoOperation, callback); +}; + +/** + * Retrieve the server information for the current + * instance of the db client + * + * @param {Object} [options] optional parameters for this operation + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.serverInfo = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const cmd = { buildinfo: 1 }; + + const serverInfoOperation = new ExecuteDbAdminCommandOperation(this.s.db, cmd, options); + + return executeOperation(this.s.db.s.topology, serverInfoOperation, callback); +}; + +/** + * Retrieve this db's server status. + * + * @param {Object} [options] optional parameters for this operation + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.serverStatus = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const serverStatusOperation = new ExecuteDbAdminCommandOperation( + this.s.db, + { serverStatus: 1 }, + options + ); + + return executeOperation(this.s.db.s.topology, serverStatusOperation, callback); +}; + +/** + * Ping the MongoDB server and retrieve results + * + * @param {Object} [options] optional parameters for this operation + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.ping = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const cmd = { ping: 1 }; + + const pingOperation = new ExecuteDbAdminCommandOperation(this.s.db, cmd, options); + + return executeOperation(this.s.db.s.topology, pingOperation, callback); +}; + +/** + * Add a user to the database. + * @method + * @param {string} username The username. + * @param {string} password The password. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.fsync=false] Specify a file sync write concern. + * @param {object} [options.customData] Custom data associated with the user (only Mongodb 2.6 or higher) + * @param {object[]} [options.roles] Roles associated with the created user (only Mongodb 2.6 or higher) + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.addUser = function(username, password, options, callback) { + const args = Array.prototype.slice.call(arguments, 2); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + + // Special case where there is no password ($external users) + if (typeof username === 'string' && password != null && typeof password === 'object') { + options = password; + password = null; + } + + options = args.length ? args.shift() : {}; + options = Object.assign({}, options); + // Get the options + options = applyWriteConcern(options, { db: this.s.db }); + // Set the db name to admin + options.dbName = 'admin'; + + const addUserOperation = new AddUserOperation(this.s.db, username, password, options); + + return executeOperation(this.s.db.s.topology, addUserOperation, callback); +}; + +/** + * Remove a user from a database + * @method + * @param {string} username The username. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.fsync=false] Specify a file sync write concern. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.removeUser = function(username, options, callback) { + const args = Array.prototype.slice.call(arguments, 1); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + + options = args.length ? args.shift() : {}; + options = Object.assign({}, options); + // Get the options + options = applyWriteConcern(options, { db: this.s.db }); + // Set the db name + options.dbName = 'admin'; + + const removeUserOperation = new RemoveUserOperation(this.s.db, username, options); + + return executeOperation(this.s.db.s.topology, removeUserOperation, callback); +}; + +/** + * Validate an existing collection + * + * @param {string} collectionName The name of the collection to validate. + * @param {object} [options] Optional settings. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Admin~resultCallback} [callback] The command result callback. + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.validateCollection = function(collectionName, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const validateCollectionOperation = new ValidateCollectionOperation( + this, + collectionName, + options + ); + + return executeOperation(this.s.db.s.topology, validateCollectionOperation, callback); +}; + +/** + * List the available databases + * + * @param {object} [options] Optional settings. + * @param {boolean} [options.nameOnly=false] Whether the command should return only db names, or names and size info. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Admin~resultCallback} [callback] The command result callback. + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.listDatabases = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeOperation( + this.s.db.s.topology, + new ListDatabasesOperation(this.s.db, options), + callback + ); +}; + +/** + * Get ReplicaSet status + * + * @param {Object} [options] optional parameters for this operation + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Admin~resultCallback} [callback] The command result callback. + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.replSetGetStatus = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const replSetGetStatusOperation = new ExecuteDbAdminCommandOperation( + this.s.db, + { replSetGetStatus: 1 }, + options + ); + + return executeOperation(this.s.db.s.topology, replSetGetStatusOperation, callback); +}; + +module.exports = Admin; diff --git a/scripts/node_modules/mongodb/lib/aggregation_cursor.js b/scripts/node_modules/mongodb/lib/aggregation_cursor.js new file mode 100644 index 00000000..b0977c69 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/aggregation_cursor.js @@ -0,0 +1,370 @@ +'use strict'; + +const MongoError = require('./core').MongoError; +const Cursor = require('./cursor'); +const CursorState = require('./core/cursor').CursorState; +const deprecate = require('util').deprecate; + +/** + * @fileOverview The **AggregationCursor** class is an internal class that embodies an aggregation cursor on MongoDB + * allowing for iteration over the results returned from the underlying query. It supports + * one by one document iteration, conversion to an array or can be iterated as a Node 4.X + * or higher stream + * + * **AGGREGATIONCURSOR Cannot directly be instantiated** + * @example + * const MongoClient = require('mongodb').MongoClient; + * const test = require('assert'); + * // Connection url + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, client) { + * // Create a collection we want to drop later + * const col = client.db(dbName).collection('createIndexExample1'); + * // Insert a bunch of documents + * col.insert([{a:1, b:1} + * , {a:2, b:2}, {a:3, b:3} + * , {a:4, b:4}], {w:1}, function(err, result) { + * test.equal(null, err); + * // Show that duplicate records got dropped + * col.aggregation({}, {cursor: {}}).toArray(function(err, items) { + * test.equal(null, err); + * test.equal(4, items.length); + * client.close(); + * }); + * }); + * }); + */ + +/** + * Namespace provided by the browser. + * @external Readable + */ + +/** + * Creates a new Aggregation Cursor instance (INTERNAL TYPE, do not instantiate directly) + * @class AggregationCursor + * @extends external:Readable + * @fires AggregationCursor#data + * @fires AggregationCursor#end + * @fires AggregationCursor#close + * @fires AggregationCursor#readable + * @return {AggregationCursor} an AggregationCursor instance. + */ +class AggregationCursor extends Cursor { + constructor(topology, operation, options) { + super(topology, operation, options); + } + + /** + * Set the batch size for the cursor. + * @method + * @param {number} value The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. + * @throws {MongoError} + * @return {AggregationCursor} + */ + batchSize(value) { + if (this.s.state === CursorState.CLOSED || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + if (typeof value !== 'number') { + throw MongoError.create({ message: 'batchSize requires an integer', driver: true }); + } + + this.operation.options.batchSize = value; + this.setCursorBatchSize(value); + return this; + } + + /** + * Add a geoNear stage to the aggregation pipeline + * @method + * @param {object} document The geoNear stage document. + * @return {AggregationCursor} + */ + geoNear(document) { + this.operation.addToPipeline({ $geoNear: document }); + return this; + } + + /** + * Add a group stage to the aggregation pipeline + * @method + * @param {object} document The group stage document. + * @return {AggregationCursor} + */ + group(document) { + this.operation.addToPipeline({ $group: document }); + return this; + } + + /** + * Add a limit stage to the aggregation pipeline + * @method + * @param {number} value The state limit value. + * @return {AggregationCursor} + */ + limit(value) { + this.operation.addToPipeline({ $limit: value }); + return this; + } + + /** + * Add a match stage to the aggregation pipeline + * @method + * @param {object} document The match stage document. + * @return {AggregationCursor} + */ + match(document) { + this.operation.addToPipeline({ $match: document }); + return this; + } + + /** + * Add a maxTimeMS stage to the aggregation pipeline + * @method + * @param {number} value The state maxTimeMS value. + * @return {AggregationCursor} + */ + maxTimeMS(value) { + this.operation.options.maxTimeMS = value; + return this; + } + + /** + * Add a out stage to the aggregation pipeline + * @method + * @param {number} destination The destination name. + * @return {AggregationCursor} + */ + out(destination) { + this.operation.addToPipeline({ $out: destination }); + return this; + } + + /** + * Add a project stage to the aggregation pipeline + * @method + * @param {object} document The project stage document. + * @return {AggregationCursor} + */ + project(document) { + this.operation.addToPipeline({ $project: document }); + return this; + } + + /** + * Add a lookup stage to the aggregation pipeline + * @method + * @param {object} document The lookup stage document. + * @return {AggregationCursor} + */ + lookup(document) { + this.operation.addToPipeline({ $lookup: document }); + return this; + } + + /** + * Add a redact stage to the aggregation pipeline + * @method + * @param {object} document The redact stage document. + * @return {AggregationCursor} + */ + redact(document) { + this.operation.addToPipeline({ $redact: document }); + return this; + } + + /** + * Add a skip stage to the aggregation pipeline + * @method + * @param {number} value The state skip value. + * @return {AggregationCursor} + */ + skip(value) { + this.operation.addToPipeline({ $skip: value }); + return this; + } + + /** + * Add a sort stage to the aggregation pipeline + * @method + * @param {object} document The sort stage document. + * @return {AggregationCursor} + */ + sort(document) { + this.operation.addToPipeline({ $sort: document }); + return this; + } + + /** + * Add a unwind stage to the aggregation pipeline + * @method + * @param {number} field The unwind field name. + * @return {AggregationCursor} + */ + unwind(field) { + this.operation.addToPipeline({ $unwind: field }); + return this; + } + + /** + * Return the cursor logger + * @method + * @return {Logger} return the cursor logger + * @ignore + */ + getLogger() { + return this.logger; + } +} + +// aliases +AggregationCursor.prototype.get = AggregationCursor.prototype.toArray; + +// deprecated methods +deprecate( + AggregationCursor.prototype.geoNear, + 'The `$geoNear` stage is deprecated in MongoDB 4.0, and removed in version 4.2.' +); + +/** + * AggregationCursor stream data event, fired for each document in the cursor. + * + * @event AggregationCursor#data + * @type {object} + */ + +/** + * AggregationCursor stream end event + * + * @event AggregationCursor#end + * @type {null} + */ + +/** + * AggregationCursor stream close event + * + * @event AggregationCursor#close + * @type {null} + */ + +/** + * AggregationCursor stream readable event + * + * @event AggregationCursor#readable + * @type {null} + */ + +/** + * Get the next available document from the cursor, returns null if no more documents are available. + * @function AggregationCursor.prototype.next + * @param {AggregationCursor~resultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ + +/** + * Check if there is any document still available in the cursor + * @function AggregationCursor.prototype.hasNext + * @param {AggregationCursor~resultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ + +/** + * The callback format for results + * @callback AggregationCursor~toArrayResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {object[]} documents All the documents the satisfy the cursor. + */ + +/** + * Returns an array of documents. The caller is responsible for making sure that there + * is enough memory to store the results. Note that the array only contain partial + * results when this cursor had been previously accessed. In that case, + * cursor.rewind() can be used to reset the cursor. + * @method AggregationCursor.prototype.toArray + * @param {AggregationCursor~toArrayResultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ + +/** + * The callback format for results + * @callback AggregationCursor~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {(object|null)} result The result object if the command was executed successfully. + */ + +/** + * Iterates over all the documents for this cursor. As with **{cursor.toArray}**, + * not all of the elements will be iterated if this cursor had been previously accessed. + * In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike + * **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements + * at any given time if batch size is specified. Otherwise, the caller is responsible + * for making sure that the entire result can fit the memory. + * @method AggregationCursor.prototype.each + * @deprecated + * @param {AggregationCursor~resultCallback} callback The result callback. + * @throws {MongoError} + * @return {null} + */ + +/** + * Close the cursor, sending a AggregationCursor command and emitting close. + * @method AggregationCursor.prototype.close + * @param {AggregationCursor~resultCallback} [callback] The result callback. + * @return {Promise} returns Promise if no callback passed + */ + +/** + * Is the cursor closed + * @method AggregationCursor.prototype.isClosed + * @return {boolean} + */ + +/** + * Execute the explain for the cursor + * @method AggregationCursor.prototype.explain + * @param {AggregationCursor~resultCallback} [callback] The result callback. + * @return {Promise} returns Promise if no callback passed + */ + +/** + * Clone the cursor + * @function AggregationCursor.prototype.clone + * @return {AggregationCursor} + */ + +/** + * Resets the cursor + * @function AggregationCursor.prototype.rewind + * @return {AggregationCursor} + */ + +/** + * The callback format for the forEach iterator method + * @callback AggregationCursor~iteratorCallback + * @param {Object} doc An emitted document for the iterator + */ + +/** + * The callback error format for the forEach iterator method + * @callback AggregationCursor~endCallback + * @param {MongoError} error An error instance representing the error during the execution. + */ + +/** + * Iterates over all the documents for this cursor using the iterator, callback pattern. + * @method AggregationCursor.prototype.forEach + * @param {AggregationCursor~iteratorCallback} iterator The iteration callback. + * @param {AggregationCursor~endCallback} callback The end callback. + * @throws {MongoError} + * @return {null} + */ + +module.exports = AggregationCursor; diff --git a/scripts/node_modules/mongodb/lib/apm.js b/scripts/node_modules/mongodb/lib/apm.js new file mode 100644 index 00000000..f78e4aaf --- /dev/null +++ b/scripts/node_modules/mongodb/lib/apm.js @@ -0,0 +1,31 @@ +'use strict'; +const EventEmitter = require('events').EventEmitter; + +class Instrumentation extends EventEmitter { + constructor() { + super(); + } + + instrument(MongoClient, callback) { + // store a reference to the original functions + this.$MongoClient = MongoClient; + const $prototypeConnect = (this.$prototypeConnect = MongoClient.prototype.connect); + + const instrumentation = this; + MongoClient.prototype.connect = function(callback) { + this.s.options.monitorCommands = true; + this.on('commandStarted', event => instrumentation.emit('started', event)); + this.on('commandSucceeded', event => instrumentation.emit('succeeded', event)); + this.on('commandFailed', event => instrumentation.emit('failed', event)); + return $prototypeConnect.call(this, callback); + }; + + if (typeof callback === 'function') callback(null, this); + } + + uninstrument() { + this.$MongoClient.prototype.connect = this.$prototypeConnect; + } +} + +module.exports = Instrumentation; diff --git a/scripts/node_modules/mongodb/lib/async/.eslintrc b/scripts/node_modules/mongodb/lib/async/.eslintrc new file mode 100644 index 00000000..93b2f643 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/async/.eslintrc @@ -0,0 +1,5 @@ +{ + "parserOptions": { + "ecmaVersion": 2018 + } +} diff --git a/scripts/node_modules/mongodb/lib/async/async_iterator.js b/scripts/node_modules/mongodb/lib/async/async_iterator.js new file mode 100644 index 00000000..6021aadf --- /dev/null +++ b/scripts/node_modules/mongodb/lib/async/async_iterator.js @@ -0,0 +1,33 @@ +'use strict'; + +// async function* asyncIterator() { +// while (true) { +// const value = await this.next(); +// if (!value) { +// await this.close(); +// return; +// } + +// yield value; +// } +// } + +// TODO: change this to the async generator function above +function asyncIterator() { + const cursor = this; + + return { + next: function() { + return Promise.resolve() + .then(() => cursor.next()) + .then(value => { + if (!value) { + return cursor.close().then(() => ({ value, done: true })); + } + return { value, done: false }; + }); + } + }; +} + +exports.asyncIterator = asyncIterator; diff --git a/scripts/node_modules/mongodb/lib/bulk/common.js b/scripts/node_modules/mongodb/lib/bulk/common.js new file mode 100644 index 00000000..8f99c252 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/bulk/common.js @@ -0,0 +1,1239 @@ +'use strict'; + +const Long = require('../core').BSON.Long; +const MongoError = require('../core').MongoError; +const ObjectID = require('../core').BSON.ObjectID; +const BSON = require('../core').BSON; +const MongoWriteConcernError = require('../core').MongoWriteConcernError; +const toError = require('../utils').toError; +const handleCallback = require('../utils').handleCallback; +const applyRetryableWrites = require('../utils').applyRetryableWrites; +const applyWriteConcern = require('../utils').applyWriteConcern; +const executeLegacyOperation = require('../utils').executeLegacyOperation; +const isPromiseLike = require('../utils').isPromiseLike; + +// Error codes +const WRITE_CONCERN_ERROR = 64; + +// Insert types +const INSERT = 1; +const UPDATE = 2; +const REMOVE = 3; + +const bson = new BSON([ + BSON.Binary, + BSON.Code, + BSON.DBRef, + BSON.Decimal128, + BSON.Double, + BSON.Int32, + BSON.Long, + BSON.Map, + BSON.MaxKey, + BSON.MinKey, + BSON.ObjectId, + BSON.BSONRegExp, + BSON.Symbol, + BSON.Timestamp +]); + +/** + * Keeps the state of a unordered batch so we can rewrite the results + * correctly after command execution + * @ignore + */ +class Batch { + constructor(batchType, originalZeroIndex) { + this.originalZeroIndex = originalZeroIndex; + this.currentIndex = 0; + this.originalIndexes = []; + this.batchType = batchType; + this.operations = []; + this.size = 0; + this.sizeBytes = 0; + } +} + +/** + * @classdesc + * The result of a bulk write. + */ +class BulkWriteResult { + /** + * Create a new BulkWriteResult instance + * + * **NOTE:** Internal Type, do not instantiate directly + */ + constructor(bulkResult) { + this.result = bulkResult; + } + + /** + * Evaluates to true if the bulk operation correctly executes + * @type {boolean} + */ + get ok() { + return this.result.ok; + } + + /** + * The number of inserted documents + * @type {number} + */ + get nInserted() { + return this.result.nInserted; + } + + /** + * Number of upserted documents + * @type {number} + */ + get nUpserted() { + return this.result.nUpserted; + } + + /** + * Number of matched documents + * @type {number} + */ + get nMatched() { + return this.result.nMatched; + } + + /** + * Number of documents updated physically on disk + * @type {number} + */ + get nModified() { + return this.result.nModified; + } + + /** + * Number of removed documents + * @type {number} + */ + get nRemoved() { + return this.result.nRemoved; + } + + /** + * Returns an array of all inserted ids + * + * @return {object[]} + */ + getInsertedIds() { + return this.result.insertedIds; + } + + /** + * Returns an array of all upserted ids + * + * @return {object[]} + */ + getUpsertedIds() { + return this.result.upserted; + } + + /** + * Returns the upserted id at the given index + * + * @param {number} index the number of the upserted id to return, returns undefined if no result for passed in index + * @return {object} + */ + getUpsertedIdAt(index) { + return this.result.upserted[index]; + } + + /** + * Returns raw internal result + * + * @return {object} + */ + getRawResponse() { + return this.result; + } + + /** + * Returns true if the bulk operation contains a write error + * + * @return {boolean} + */ + hasWriteErrors() { + return this.result.writeErrors.length > 0; + } + + /** + * Returns the number of write errors off the bulk operation + * + * @return {number} + */ + getWriteErrorCount() { + return this.result.writeErrors.length; + } + + /** + * Returns a specific write error object + * + * @param {number} index of the write error to return, returns null if there is no result for passed in index + * @return {WriteError} + */ + getWriteErrorAt(index) { + if (index < this.result.writeErrors.length) { + return this.result.writeErrors[index]; + } + return null; + } + + /** + * Retrieve all write errors + * + * @return {WriteError[]} + */ + getWriteErrors() { + return this.result.writeErrors; + } + + /** + * Retrieve lastOp if available + * + * @return {object} + */ + getLastOp() { + return this.result.lastOp; + } + + /** + * Retrieve the write concern error if any + * + * @return {WriteConcernError} + */ + getWriteConcernError() { + if (this.result.writeConcernErrors.length === 0) { + return null; + } else if (this.result.writeConcernErrors.length === 1) { + // Return the error + return this.result.writeConcernErrors[0]; + } else { + // Combine the errors + let errmsg = ''; + for (let i = 0; i < this.result.writeConcernErrors.length; i++) { + const err = this.result.writeConcernErrors[i]; + errmsg = errmsg + err.errmsg; + + // TODO: Something better + if (i === 0) errmsg = errmsg + ' and '; + } + + return new WriteConcernError({ errmsg: errmsg, code: WRITE_CONCERN_ERROR }); + } + } + + /** + * @return {object} + */ + toJSON() { + return this.result; + } + + /** + * @return {string} + */ + toString() { + return `BulkWriteResult(${this.toJSON(this.result)})`; + } + + /** + * @return {boolean} + */ + isOk() { + return this.result.ok === 1; + } +} + +/** + * @classdesc An error representing a failure by the server to apply the requested write concern to the bulk operation. + */ +class WriteConcernError { + /** + * Create a new WriteConcernError instance + * + * **NOTE:** Internal Type, do not instantiate directly + */ + constructor(err) { + this.err = err; + } + + /** + * Write concern error code. + * @type {number} + */ + get code() { + return this.err.code; + } + + /** + * Write concern error message. + * @type {string} + */ + get errmsg() { + return this.err.errmsg; + } + + /** + * @return {object} + */ + toJSON() { + return { code: this.err.code, errmsg: this.err.errmsg }; + } + + /** + * @return {string} + */ + toString() { + return `WriteConcernError(${this.err.errmsg})`; + } +} + +/** + * @classdesc An error that occurred during a BulkWrite on the server. + */ +class WriteError { + /** + * Create a new WriteError instance + * + * **NOTE:** Internal Type, do not instantiate directly + */ + constructor(err) { + this.err = err; + } + + /** + * WriteError code. + * @type {number} + */ + get code() { + return this.err.code; + } + + /** + * WriteError original bulk operation index. + * @type {number} + */ + get index() { + return this.err.index; + } + + /** + * WriteError message. + * @type {string} + */ + get errmsg() { + return this.err.errmsg; + } + + /** + * Returns the underlying operation that caused the error + * @return {object} + */ + getOperation() { + return this.err.op; + } + + /** + * @return {object} + */ + toJSON() { + return { code: this.err.code, index: this.err.index, errmsg: this.err.errmsg, op: this.err.op }; + } + + /** + * @return {string} + */ + toString() { + return `WriteError(${JSON.stringify(this.toJSON())})`; + } +} + +/** + * Merges results into shared data structure + * @ignore + */ +function mergeBatchResults(batch, bulkResult, err, result) { + // If we have an error set the result to be the err object + if (err) { + result = err; + } else if (result && result.result) { + result = result.result; + } else if (result == null) { + return; + } + + // Do we have a top level error stop processing and return + if (result.ok === 0 && bulkResult.ok === 1) { + bulkResult.ok = 0; + + const writeError = { + index: 0, + code: result.code || 0, + errmsg: result.message, + op: batch.operations[0] + }; + + bulkResult.writeErrors.push(new WriteError(writeError)); + return; + } else if (result.ok === 0 && bulkResult.ok === 0) { + return; + } + + // Deal with opTime if available + if (result.opTime || result.lastOp) { + const opTime = result.lastOp || result.opTime; + let lastOpTS = null; + let lastOpT = null; + + // We have a time stamp + if (opTime && opTime._bsontype === 'Timestamp') { + if (bulkResult.lastOp == null) { + bulkResult.lastOp = opTime; + } else if (opTime.greaterThan(bulkResult.lastOp)) { + bulkResult.lastOp = opTime; + } + } else { + // Existing TS + if (bulkResult.lastOp) { + lastOpTS = + typeof bulkResult.lastOp.ts === 'number' + ? Long.fromNumber(bulkResult.lastOp.ts) + : bulkResult.lastOp.ts; + lastOpT = + typeof bulkResult.lastOp.t === 'number' + ? Long.fromNumber(bulkResult.lastOp.t) + : bulkResult.lastOp.t; + } + + // Current OpTime TS + const opTimeTS = typeof opTime.ts === 'number' ? Long.fromNumber(opTime.ts) : opTime.ts; + const opTimeT = typeof opTime.t === 'number' ? Long.fromNumber(opTime.t) : opTime.t; + + // Compare the opTime's + if (bulkResult.lastOp == null) { + bulkResult.lastOp = opTime; + } else if (opTimeTS.greaterThan(lastOpTS)) { + bulkResult.lastOp = opTime; + } else if (opTimeTS.equals(lastOpTS)) { + if (opTimeT.greaterThan(lastOpT)) { + bulkResult.lastOp = opTime; + } + } + } + } + + // If we have an insert Batch type + if (batch.batchType === INSERT && result.n) { + bulkResult.nInserted = bulkResult.nInserted + result.n; + } + + // If we have an insert Batch type + if (batch.batchType === REMOVE && result.n) { + bulkResult.nRemoved = bulkResult.nRemoved + result.n; + } + + let nUpserted = 0; + + // We have an array of upserted values, we need to rewrite the indexes + if (Array.isArray(result.upserted)) { + nUpserted = result.upserted.length; + + for (let i = 0; i < result.upserted.length; i++) { + bulkResult.upserted.push({ + index: result.upserted[i].index + batch.originalZeroIndex, + _id: result.upserted[i]._id + }); + } + } else if (result.upserted) { + nUpserted = 1; + + bulkResult.upserted.push({ + index: batch.originalZeroIndex, + _id: result.upserted + }); + } + + // If we have an update Batch type + if (batch.batchType === UPDATE && result.n) { + const nModified = result.nModified; + bulkResult.nUpserted = bulkResult.nUpserted + nUpserted; + bulkResult.nMatched = bulkResult.nMatched + (result.n - nUpserted); + + if (typeof nModified === 'number') { + bulkResult.nModified = bulkResult.nModified + nModified; + } else { + bulkResult.nModified = null; + } + } + + if (Array.isArray(result.writeErrors)) { + for (let i = 0; i < result.writeErrors.length; i++) { + const writeError = { + index: batch.originalZeroIndex + result.writeErrors[i].index, + code: result.writeErrors[i].code, + errmsg: result.writeErrors[i].errmsg, + op: batch.operations[result.writeErrors[i].index] + }; + + bulkResult.writeErrors.push(new WriteError(writeError)); + } + } + + if (result.writeConcernError) { + bulkResult.writeConcernErrors.push(new WriteConcernError(result.writeConcernError)); + } +} + +function executeCommands(bulkOperation, options, callback) { + if (bulkOperation.s.batches.length === 0) { + return handleCallback(callback, null, new BulkWriteResult(bulkOperation.s.bulkResult)); + } + + const batch = bulkOperation.s.batches.shift(); + + function resultHandler(err, result) { + // Error is a driver related error not a bulk op error, terminate + if (((err && err.driver) || (err && err.message)) && !(err instanceof MongoWriteConcernError)) { + return handleCallback(callback, err); + } + + // If we have and error + if (err) err.ok = 0; + if (err instanceof MongoWriteConcernError) { + return handleMongoWriteConcernError(batch, bulkOperation.s.bulkResult, err, callback); + } + + // Merge the results together + const writeResult = new BulkWriteResult(bulkOperation.s.bulkResult); + const mergeResult = mergeBatchResults(batch, bulkOperation.s.bulkResult, err, result); + if (mergeResult != null) { + return handleCallback(callback, null, writeResult); + } + + if (bulkOperation.handleWriteError(callback, writeResult)) return; + + // Execute the next command in line + executeCommands(bulkOperation, options, callback); + } + + bulkOperation.finalOptionsHandler({ options, batch, resultHandler }, callback); +} + +/** + * handles write concern error + * + * @ignore + * @param {object} batch + * @param {object} bulkResult + * @param {boolean} ordered + * @param {WriteConcernError} err + * @param {function} callback + */ +function handleMongoWriteConcernError(batch, bulkResult, err, callback) { + mergeBatchResults(batch, bulkResult, null, err.result); + + const wrappedWriteConcernError = new WriteConcernError({ + errmsg: err.result.writeConcernError.errmsg, + code: err.result.writeConcernError.result + }); + return handleCallback( + callback, + new BulkWriteError(toError(wrappedWriteConcernError), new BulkWriteResult(bulkResult)), + null + ); +} + +/** + * @classdesc An error indicating an unsuccessful Bulk Write + */ +class BulkWriteError extends MongoError { + /** + * Creates a new BulkWriteError + * + * @param {Error|string|object} message The error message + * @param {BulkWriteResult} result The result of the bulk write operation + * @extends {MongoError} + */ + constructor(error, result) { + const message = error.err || error.errmsg || error.errMessage || error; + super(message); + + Object.assign(this, error); + + this.name = 'BulkWriteError'; + this.result = result; + } +} + +/** + * @classdesc A builder object that is returned from {@link BulkOperationBase#find}. + * Is used to build a write operation that involves a query filter. + */ +class FindOperators { + /** + * Creates a new FindOperators object. + * + * **NOTE:** Internal Type, do not instantiate directly + * @param {OrderedBulkOperation|UnorderedBulkOperation} bulkOperation + */ + constructor(bulkOperation) { + this.s = bulkOperation.s; + } + + /** + * Add a multiple update operation to the bulk operation + * + * @method + * @param {object} updateDocument An update field for an update operation. See {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-u u documentation} + * @throws {MongoError} If operation cannot be added to bulk write + * @return {OrderedBulkOperation|UnorderedBulkOperation} A reference to the parent BulkOperation + */ + update(updateDocument) { + // Perform upsert + const upsert = typeof this.s.currentOp.upsert === 'boolean' ? this.s.currentOp.upsert : false; + + // Establish the update command + const document = { + q: this.s.currentOp.selector, + u: updateDocument, + multi: true, + upsert: upsert + }; + + // Clear out current Op + this.s.currentOp = null; + return this.s.options.addToOperationsList(this, UPDATE, document); + } + + /** + * Add a single update operation to the bulk operation + * + * @method + * @param {object} updateDocument An update field for an update operation. See {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-u u documentation} + * @throws {MongoError} If operation cannot be added to bulk write + * @return {OrderedBulkOperation|UnorderedBulkOperation} A reference to the parent BulkOperation + */ + updateOne(updateDocument) { + // Perform upsert + const upsert = typeof this.s.currentOp.upsert === 'boolean' ? this.s.currentOp.upsert : false; + + // Establish the update command + const document = { + q: this.s.currentOp.selector, + u: updateDocument, + multi: false, + upsert: upsert + }; + + // Clear out current Op + this.s.currentOp = null; + return this.s.options.addToOperationsList(this, UPDATE, document); + } + + /** + * Add a replace one operation to the bulk operation + * + * @method + * @param {object} updateDocument the new document to replace the existing one with + * @throws {MongoError} If operation cannot be added to bulk write + * @return {OrderedBulkOperation|UnorderedBulkOperation} A reference to the parent BulkOperation + */ + replaceOne(updateDocument) { + this.updateOne(updateDocument); + } + + /** + * Upsert modifier for update bulk operation, noting that this operation is an upsert. + * + * @method + * @throws {MongoError} If operation cannot be added to bulk write + * @return {FindOperators} reference to self + */ + upsert() { + this.s.currentOp.upsert = true; + return this; + } + + /** + * Add a delete one operation to the bulk operation + * + * @method + * @throws {MongoError} If operation cannot be added to bulk write + * @return {OrderedBulkOperation|UnorderedBulkOperation} A reference to the parent BulkOperation + */ + deleteOne() { + // Establish the update command + const document = { + q: this.s.currentOp.selector, + limit: 1 + }; + + // Clear out current Op + this.s.currentOp = null; + return this.s.options.addToOperationsList(this, REMOVE, document); + } + + /** + * Add a delete many operation to the bulk operation + * + * @method + * @throws {MongoError} If operation cannot be added to bulk write + * @return {OrderedBulkOperation|UnorderedBulkOperation} A reference to the parent BulkOperation + */ + delete() { + // Establish the update command + const document = { + q: this.s.currentOp.selector, + limit: 0 + }; + + // Clear out current Op + this.s.currentOp = null; + return this.s.options.addToOperationsList(this, REMOVE, document); + } + + /** + * backwards compatability for deleteOne + */ + removeOne() { + return this.deleteOne(); + } + + /** + * backwards compatability for delete + */ + remove() { + return this.delete(); + } +} + +/** + * @classdesc Parent class to OrderedBulkOperation and UnorderedBulkOperation + * + * **NOTE:** Internal Type, do not instantiate directly + */ +class BulkOperationBase { + /** + * Create a new OrderedBulkOperation or UnorderedBulkOperation instance + * @property {number} length Get the number of operations in the bulk. + */ + constructor(topology, collection, options, isOrdered) { + // determine whether bulkOperation is ordered or unordered + this.isOrdered = isOrdered; + + options = options == null ? {} : options; + // TODO Bring from driver information in isMaster + // Get the namespace for the write operations + const namespace = collection.s.namespace; + // Used to mark operation as executed + const executed = false; + + // Current item + const currentOp = null; + + // Handle to the bson serializer, used to calculate running sizes + const bson = topology.bson; + + // Set max byte size + const isMaster = topology.lastIsMaster(); + const maxBatchSizeBytes = + isMaster && isMaster.maxBsonObjectSize ? isMaster.maxBsonObjectSize : 1024 * 1024 * 16; + const maxWriteBatchSize = + isMaster && isMaster.maxWriteBatchSize ? isMaster.maxWriteBatchSize : 1000; + + // Calculates the largest possible size of an Array key, represented as a BSON string + // element. This calculation: + // 1 byte for BSON type + // # of bytes = length of (string representation of (maxWriteBatchSize - 1)) + // + 1 bytes for null terminator + const maxKeySize = (maxWriteBatchSize - 1).toString(10).length + 2; + + // Final options for retryable writes and write concern + let finalOptions = Object.assign({}, options); + finalOptions = applyRetryableWrites(finalOptions, collection.s.db); + finalOptions = applyWriteConcern(finalOptions, { collection: collection }, options); + const writeConcern = finalOptions.writeConcern; + + // Get the promiseLibrary + const promiseLibrary = options.promiseLibrary || Promise; + + // Final results + const bulkResult = { + ok: 1, + writeErrors: [], + writeConcernErrors: [], + insertedIds: [], + nInserted: 0, + nUpserted: 0, + nMatched: 0, + nModified: 0, + nRemoved: 0, + upserted: [] + }; + + // Internal state + this.s = { + // Final result + bulkResult: bulkResult, + // Current batch state + currentBatch: null, + currentIndex: 0, + // ordered specific + currentBatchSize: 0, + currentBatchSizeBytes: 0, + // unordered specific + currentInsertBatch: null, + currentUpdateBatch: null, + currentRemoveBatch: null, + batches: [], + // Write concern + writeConcern: writeConcern, + // Max batch size options + maxBatchSizeBytes: maxBatchSizeBytes, + maxWriteBatchSize: maxWriteBatchSize, + maxKeySize, + // Namespace + namespace: namespace, + // BSON + bson: bson, + // Topology + topology: topology, + // Options + options: finalOptions, + // Current operation + currentOp: currentOp, + // Executed + executed: executed, + // Collection + collection: collection, + // Promise Library + promiseLibrary: promiseLibrary, + // Fundamental error + err: null, + // check keys + checkKeys: typeof options.checkKeys === 'boolean' ? options.checkKeys : true + }; + + // bypass Validation + if (options.bypassDocumentValidation === true) { + this.s.bypassDocumentValidation = true; + } + } + + /** + * Add a single insert document to the bulk operation + * + * @param {object} document the document to insert + * @throws {MongoError} + * @return {BulkOperationBase} A reference to self + * + * @example + * const bulkOp = collection.initializeOrderedBulkOp(); + * // Adds three inserts to the bulkOp. + * bulkOp + * .insert({ a: 1 }) + * .insert({ b: 2 }) + * .insert({ c: 3 }); + * await bulkOp.execute(); + */ + insert(document) { + if (this.s.collection.s.db.options.forceServerObjectId !== true && document._id == null) + document._id = new ObjectID(); + return this.s.options.addToOperationsList(this, INSERT, document); + } + + /** + * Builds a find operation for an update/updateOne/delete/deleteOne/replaceOne. + * Returns a builder object used to complete the definition of the operation. + * + * @method + * @param {object} selector The selector for the bulk operation. See {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-q q documentation} + * @throws {MongoError} if a selector is not specified + * @return {FindOperators} A helper object with which the write operation can be defined. + * + * @example + * const bulkOp = collection.initializeOrderedBulkOp(); + * + * // Add an updateOne to the bulkOp + * bulkOp.find({ a: 1 }).updateOne({ $set: { b: 2 } }); + * + * // Add an updateMany to the bulkOp + * bulkOp.find({ c: 3 }).update({ $set: { d: 4 } }); + * + * // Add an upsert + * bulkOp.find({ e: 5 }).upsert().updateOne({ $set: { f: 6 } }); + * + * // Add a deletion + * bulkOp.find({ g: 7 }).deleteOne(); + * + * // Add a multi deletion + * bulkOp.find({ h: 8 }).delete(); + * + * // Add a replaceOne + * bulkOp.find({ i: 9 }).replaceOne({ j: 10 }); + * + * // Update using a pipeline (requires Mongodb 4.2 or higher) + * bulk.find({ k: 11, y: { $exists: true }, z: { $exists: true } }).updateOne([ + * { $set: { total: { $sum: [ '$y', '$z' ] } } } + * ]); + * + * // All of the ops will now be executed + * await bulkOp.execute(); + */ + find(selector) { + if (!selector) { + throw toError('Bulk find operation must specify a selector'); + } + + // Save a current selector + this.s.currentOp = { + selector: selector + }; + + return new FindOperators(this); + } + + /** + * Specifies a raw operation to perform in the bulk write. + * + * @method + * @param {object} op The raw operation to perform. + * @return {BulkOperationBase} A reference to self + */ + raw(op) { + const key = Object.keys(op)[0]; + + // Set up the force server object id + const forceServerObjectId = + typeof this.s.options.forceServerObjectId === 'boolean' + ? this.s.options.forceServerObjectId + : this.s.collection.s.db.options.forceServerObjectId; + + // Update operations + if ( + (op.updateOne && op.updateOne.q) || + (op.updateMany && op.updateMany.q) || + (op.replaceOne && op.replaceOne.q) + ) { + op[key].multi = op.updateOne || op.replaceOne ? false : true; + return this.s.options.addToOperationsList(this, UPDATE, op[key]); + } + + // Crud spec update format + if (op.updateOne || op.updateMany || op.replaceOne) { + const multi = op.updateOne || op.replaceOne ? false : true; + const operation = { + q: op[key].filter, + u: op[key].update || op[key].replacement, + multi: multi + }; + if (this.isOrdered) { + operation.upsert = op[key].upsert ? true : false; + if (op.collation) operation.collation = op.collation; + } else { + if (op[key].upsert) operation.upsert = true; + } + if (op[key].arrayFilters) operation.arrayFilters = op[key].arrayFilters; + return this.s.options.addToOperationsList(this, UPDATE, operation); + } + + // Remove operations + if ( + op.removeOne || + op.removeMany || + (op.deleteOne && op.deleteOne.q) || + (op.deleteMany && op.deleteMany.q) + ) { + op[key].limit = op.removeOne ? 1 : 0; + return this.s.options.addToOperationsList(this, REMOVE, op[key]); + } + + // Crud spec delete operations, less efficient + if (op.deleteOne || op.deleteMany) { + const limit = op.deleteOne ? 1 : 0; + const operation = { q: op[key].filter, limit: limit }; + if (this.isOrdered) { + if (op.collation) operation.collation = op.collation; + } + return this.s.options.addToOperationsList(this, REMOVE, operation); + } + + // Insert operations + if (op.insertOne && op.insertOne.document == null) { + if (forceServerObjectId !== true && op.insertOne._id == null) + op.insertOne._id = new ObjectID(); + return this.s.options.addToOperationsList(this, INSERT, op.insertOne); + } else if (op.insertOne && op.insertOne.document) { + if (forceServerObjectId !== true && op.insertOne.document._id == null) + op.insertOne.document._id = new ObjectID(); + return this.s.options.addToOperationsList(this, INSERT, op.insertOne.document); + } + + if (op.insertMany) { + for (let i = 0; i < op.insertMany.length; i++) { + if (forceServerObjectId !== true && op.insertMany[i]._id == null) + op.insertMany[i]._id = new ObjectID(); + this.s.options.addToOperationsList(this, INSERT, op.insertMany[i]); + } + + return; + } + + // No valid type of operation + throw toError( + 'bulkWrite only supports insertOne, insertMany, updateOne, updateMany, removeOne, removeMany, deleteOne, deleteMany' + ); + } + + /** + * helper function to assist with promiseOrCallback behavior + * @ignore + * @param {*} err + * @param {*} callback + */ + _handleEarlyError(err, callback) { + if (typeof callback === 'function') { + callback(err, null); + return; + } + + return this.s.promiseLibrary.reject(err); + } + + /** + * An internal helper method. Do not invoke directly. Will be going away in the future + * + * @ignore + * @method + * @param {class} bulk either OrderedBulkOperation or UnorderdBulkOperation + * @param {object} writeConcern + * @param {object} options + * @param {function} callback + */ + bulkExecute(_writeConcern, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + if (typeof _writeConcern === 'function') { + callback = _writeConcern; + } else if (_writeConcern && typeof _writeConcern === 'object') { + this.s.writeConcern = _writeConcern; + } + + if (this.s.executed) { + const executedError = toError('batch cannot be re-executed'); + return this._handleEarlyError(executedError, callback); + } + + // If we have current batch + if (this.isOrdered) { + if (this.s.currentBatch) this.s.batches.push(this.s.currentBatch); + } else { + if (this.s.currentInsertBatch) this.s.batches.push(this.s.currentInsertBatch); + if (this.s.currentUpdateBatch) this.s.batches.push(this.s.currentUpdateBatch); + if (this.s.currentRemoveBatch) this.s.batches.push(this.s.currentRemoveBatch); + } + // If we have no operations in the bulk raise an error + if (this.s.batches.length === 0) { + const emptyBatchError = toError('Invalid Operation, no operations specified'); + return this._handleEarlyError(emptyBatchError, callback); + } + return { options, callback }; + } + + /** + * The callback format for results + * @callback BulkOperationBase~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {BulkWriteResult} result The bulk write result. + */ + + /** + * Execute the bulk operation + * + * @method + * @param {WriteConcern} [_writeConcern] Optional write concern. Can also be specified through options. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.fsync=false] Specify a file sync write concern. + * @param {BulkOperationBase~resultCallback} [callback] A callback that will be invoked when bulkWrite finishes/errors + * @throws {MongoError} Throws error if the bulk object has already been executed + * @throws {MongoError} Throws error if the bulk object does not have any operations + * @return {Promise|void} returns Promise if no callback passed + */ + execute(_writeConcern, options, callback) { + const ret = this.bulkExecute(_writeConcern, options, callback); + if (!ret || isPromiseLike(ret)) { + return ret; + } + + options = ret.options; + callback = ret.callback; + + return executeLegacyOperation(this.s.topology, executeCommands, [this, options, callback]); + } + + /** + * Handles final options before executing command + * + * An internal method. Do not invoke. Will not be accessible in the future + * + * @ignore + * @param {object} config + * @param {object} config.options + * @param {number} config.batch + * @param {function} config.resultHandler + * @param {function} callback + */ + finalOptionsHandler(config, callback) { + const finalOptions = Object.assign({ ordered: this.isOrdered }, config.options); + if (this.s.writeConcern != null) { + finalOptions.writeConcern = this.s.writeConcern; + } + + if (finalOptions.bypassDocumentValidation !== true) { + delete finalOptions.bypassDocumentValidation; + } + + // Set an operationIf if provided + if (this.operationId) { + config.resultHandler.operationId = this.operationId; + } + + // Serialize functions + if (this.s.options.serializeFunctions) { + finalOptions.serializeFunctions = true; + } + + // Ignore undefined + if (this.s.options.ignoreUndefined) { + finalOptions.ignoreUndefined = true; + } + + // Is the bypassDocumentValidation options specific + if (this.s.bypassDocumentValidation === true) { + finalOptions.bypassDocumentValidation = true; + } + + // Is the checkKeys option disabled + if (this.s.checkKeys === false) { + finalOptions.checkKeys = false; + } + + if (finalOptions.retryWrites) { + if (config.batch.batchType === UPDATE) { + finalOptions.retryWrites = + finalOptions.retryWrites && !config.batch.operations.some(op => op.multi); + } + + if (config.batch.batchType === REMOVE) { + finalOptions.retryWrites = + finalOptions.retryWrites && !config.batch.operations.some(op => op.limit === 0); + } + } + + try { + if (config.batch.batchType === INSERT) { + this.s.topology.insert( + this.s.namespace, + config.batch.operations, + finalOptions, + config.resultHandler + ); + } else if (config.batch.batchType === UPDATE) { + this.s.topology.update( + this.s.namespace, + config.batch.operations, + finalOptions, + config.resultHandler + ); + } else if (config.batch.batchType === REMOVE) { + this.s.topology.remove( + this.s.namespace, + config.batch.operations, + finalOptions, + config.resultHandler + ); + } + } catch (err) { + // Force top level error + err.ok = 0; + // Merge top level error and return + handleCallback(callback, null, mergeBatchResults(config.batch, this.s.bulkResult, err, null)); + } + } + + /** + * Handles the write error before executing commands + * + * An internal helper method. Do not invoke directly. Will be going away in the future + * + * @ignore + * @param {function} callback + * @param {BulkWriteResult} writeResult + * @param {class} self either OrderedBulkOperation or UnorderdBulkOperation + */ + handleWriteError(callback, writeResult) { + if (this.s.bulkResult.writeErrors.length > 0) { + if (this.s.bulkResult.writeErrors.length === 1) { + handleCallback( + callback, + new BulkWriteError(toError(this.s.bulkResult.writeErrors[0]), writeResult), + null + ); + return true; + } + + const msg = this.s.bulkResult.writeErrors[0].errmsg + ? this.s.bulkResult.writeErrors[0].errmsg + : 'write operation failed'; + + handleCallback( + callback, + new BulkWriteError( + toError({ + message: msg, + code: this.s.bulkResult.writeErrors[0].code, + writeErrors: this.s.bulkResult.writeErrors + }), + writeResult + ), + null + ); + return true; + } else if (writeResult.getWriteConcernError()) { + handleCallback( + callback, + new BulkWriteError(toError(writeResult.getWriteConcernError()), writeResult), + null + ); + return true; + } + } +} + +Object.defineProperty(BulkOperationBase.prototype, 'length', { + enumerable: true, + get: function() { + return this.s.currentIndex; + } +}); + +// Exports symbols +module.exports = { + Batch, + BulkOperationBase, + bson, + INSERT: INSERT, + UPDATE: UPDATE, + REMOVE: REMOVE, + BulkWriteError +}; diff --git a/scripts/node_modules/mongodb/lib/bulk/ordered.js b/scripts/node_modules/mongodb/lib/bulk/ordered.js new file mode 100644 index 00000000..e2507b86 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/bulk/ordered.js @@ -0,0 +1,105 @@ +'use strict'; + +const common = require('./common'); +const BulkOperationBase = common.BulkOperationBase; +const Batch = common.Batch; +const bson = common.bson; +const utils = require('../utils'); +const toError = utils.toError; + +/** + * Add to internal list of Operations + * + * @ignore + * @param {OrderedBulkOperation} bulkOperation + * @param {number} docType number indicating the document type + * @param {object} document + * @return {OrderedBulkOperation} + */ +function addToOperationsList(bulkOperation, docType, document) { + // Get the bsonSize + const bsonSize = bson.calculateObjectSize(document, { + checkKeys: false, + + // Since we don't know what the user selected for BSON options here, + // err on the safe side, and check the size with ignoreUndefined: false. + ignoreUndefined: false + }); + + // Throw error if the doc is bigger than the max BSON size + if (bsonSize >= bulkOperation.s.maxBatchSizeBytes) + throw toError('document is larger than the maximum size ' + bulkOperation.s.maxBatchSizeBytes); + + // Create a new batch object if we don't have a current one + if (bulkOperation.s.currentBatch == null) + bulkOperation.s.currentBatch = new Batch(docType, bulkOperation.s.currentIndex); + + const maxKeySize = bulkOperation.s.maxKeySize; + + // Check if we need to create a new batch + if ( + bulkOperation.s.currentBatchSize + 1 >= bulkOperation.s.maxWriteBatchSize || + bulkOperation.s.currentBatchSizeBytes + maxKeySize + bsonSize >= + bulkOperation.s.maxBatchSizeBytes || + bulkOperation.s.currentBatch.batchType !== docType + ) { + // Save the batch to the execution stack + bulkOperation.s.batches.push(bulkOperation.s.currentBatch); + + // Create a new batch + bulkOperation.s.currentBatch = new Batch(docType, bulkOperation.s.currentIndex); + + // Reset the current size trackers + bulkOperation.s.currentBatchSize = 0; + bulkOperation.s.currentBatchSizeBytes = 0; + } + + if (docType === common.INSERT) { + bulkOperation.s.bulkResult.insertedIds.push({ + index: bulkOperation.s.currentIndex, + _id: document._id + }); + } + + // We have an array of documents + if (Array.isArray(document)) { + throw toError('operation passed in cannot be an Array'); + } + + bulkOperation.s.currentBatch.originalIndexes.push(bulkOperation.s.currentIndex); + bulkOperation.s.currentBatch.operations.push(document); + bulkOperation.s.currentBatchSize += 1; + bulkOperation.s.currentBatchSizeBytes += maxKeySize + bsonSize; + bulkOperation.s.currentIndex += 1; + + // Return bulkOperation + return bulkOperation; +} + +/** + * Create a new OrderedBulkOperation instance (INTERNAL TYPE, do not instantiate directly) + * @class + * @extends BulkOperationBase + * @property {number} length Get the number of operations in the bulk. + * @return {OrderedBulkOperation} a OrderedBulkOperation instance. + */ +class OrderedBulkOperation extends BulkOperationBase { + constructor(topology, collection, options) { + options = options || {}; + options = Object.assign(options, { addToOperationsList }); + + super(topology, collection, options, true); + } +} + +/** + * Returns an unordered batch object + * @ignore + */ +function initializeOrderedBulkOp(topology, collection, options) { + return new OrderedBulkOperation(topology, collection, options); +} + +initializeOrderedBulkOp.OrderedBulkOperation = OrderedBulkOperation; +module.exports = initializeOrderedBulkOp; +module.exports.Bulk = OrderedBulkOperation; diff --git a/scripts/node_modules/mongodb/lib/bulk/unordered.js b/scripts/node_modules/mongodb/lib/bulk/unordered.js new file mode 100644 index 00000000..999de3c4 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/bulk/unordered.js @@ -0,0 +1,118 @@ +'use strict'; + +const common = require('./common'); +const BulkOperationBase = common.BulkOperationBase; +const Batch = common.Batch; +const bson = common.bson; +const utils = require('../utils'); +const toError = utils.toError; + +/** + * Add to internal list of Operations + * + * @ignore + * @param {UnorderedBulkOperation} bulkOperation + * @param {number} docType number indicating the document type + * @param {object} document + * @return {UnorderedBulkOperation} + */ +function addToOperationsList(bulkOperation, docType, document) { + // Get the bsonSize + const bsonSize = bson.calculateObjectSize(document, { + checkKeys: false, + + // Since we don't know what the user selected for BSON options here, + // err on the safe side, and check the size with ignoreUndefined: false. + ignoreUndefined: false + }); + // Throw error if the doc is bigger than the max BSON size + if (bsonSize >= bulkOperation.s.maxBatchSizeBytes) + throw toError('document is larger than the maximum size ' + bulkOperation.s.maxBatchSizeBytes); + // Holds the current batch + bulkOperation.s.currentBatch = null; + // Get the right type of batch + if (docType === common.INSERT) { + bulkOperation.s.currentBatch = bulkOperation.s.currentInsertBatch; + } else if (docType === common.UPDATE) { + bulkOperation.s.currentBatch = bulkOperation.s.currentUpdateBatch; + } else if (docType === common.REMOVE) { + bulkOperation.s.currentBatch = bulkOperation.s.currentRemoveBatch; + } + + const maxKeySize = bulkOperation.s.maxKeySize; + + // Create a new batch object if we don't have a current one + if (bulkOperation.s.currentBatch == null) + bulkOperation.s.currentBatch = new Batch(docType, bulkOperation.s.currentIndex); + + // Check if we need to create a new batch + if ( + bulkOperation.s.currentBatch.size + 1 >= bulkOperation.s.maxWriteBatchSize || + bulkOperation.s.currentBatch.sizeBytes + maxKeySize + bsonSize >= + bulkOperation.s.maxBatchSizeBytes || + bulkOperation.s.currentBatch.batchType !== docType + ) { + // Save the batch to the execution stack + bulkOperation.s.batches.push(bulkOperation.s.currentBatch); + + // Create a new batch + bulkOperation.s.currentBatch = new Batch(docType, bulkOperation.s.currentIndex); + } + + // We have an array of documents + if (Array.isArray(document)) { + throw toError('operation passed in cannot be an Array'); + } + + bulkOperation.s.currentBatch.operations.push(document); + bulkOperation.s.currentBatch.originalIndexes.push(bulkOperation.s.currentIndex); + bulkOperation.s.currentIndex = bulkOperation.s.currentIndex + 1; + + // Save back the current Batch to the right type + if (docType === common.INSERT) { + bulkOperation.s.currentInsertBatch = bulkOperation.s.currentBatch; + bulkOperation.s.bulkResult.insertedIds.push({ + index: bulkOperation.s.bulkResult.insertedIds.length, + _id: document._id + }); + } else if (docType === common.UPDATE) { + bulkOperation.s.currentUpdateBatch = bulkOperation.s.currentBatch; + } else if (docType === common.REMOVE) { + bulkOperation.s.currentRemoveBatch = bulkOperation.s.currentBatch; + } + + // Update current batch size + bulkOperation.s.currentBatch.size += 1; + bulkOperation.s.currentBatch.sizeBytes += maxKeySize + bsonSize; + + // Return bulkOperation + return bulkOperation; +} + +/** + * Create a new UnorderedBulkOperation instance (INTERNAL TYPE, do not instantiate directly) + * @class + * @extends BulkOperationBase + * @property {number} length Get the number of operations in the bulk. + * @return {UnorderedBulkOperation} a UnorderedBulkOperation instance. + */ +class UnorderedBulkOperation extends BulkOperationBase { + constructor(topology, collection, options) { + options = options || {}; + options = Object.assign(options, { addToOperationsList }); + + super(topology, collection, options, false); + } +} + +/** + * Returns an unordered batch object + * @ignore + */ +function initializeUnorderedBulkOp(topology, collection, options) { + return new UnorderedBulkOperation(topology, collection, options); +} + +initializeUnorderedBulkOp.UnorderedBulkOperation = UnorderedBulkOperation; +module.exports = initializeUnorderedBulkOp; +module.exports.Bulk = UnorderedBulkOperation; diff --git a/scripts/node_modules/mongodb/lib/change_stream.js b/scripts/node_modules/mongodb/lib/change_stream.js new file mode 100644 index 00000000..4cc779de --- /dev/null +++ b/scripts/node_modules/mongodb/lib/change_stream.js @@ -0,0 +1,576 @@ +'use strict'; + +const EventEmitter = require('events'); +const isResumableError = require('./error').isResumableError; +const MongoError = require('./core').MongoError; +const Cursor = require('./cursor'); +const relayEvents = require('./core/utils').relayEvents; +const maxWireVersion = require('./core/utils').maxWireVersion; +const AggregateOperation = require('./operations/aggregate'); + +const CHANGE_STREAM_OPTIONS = ['resumeAfter', 'startAfter', 'startAtOperationTime', 'fullDocument']; +const CURSOR_OPTIONS = ['batchSize', 'maxAwaitTimeMS', 'collation', 'readPreference'].concat( + CHANGE_STREAM_OPTIONS +); + +const CHANGE_DOMAIN_TYPES = { + COLLECTION: Symbol('Collection'), + DATABASE: Symbol('Database'), + CLUSTER: Symbol('Cluster') +}; + +/** + * @typedef ResumeToken + * @description Represents the logical starting point for a new or resuming {@link ChangeStream} on the server. + * @see https://docs.mongodb.com/master/changeStreams/#change-stream-resume-token + */ + +/** + * @typedef OperationTime + * @description Represents a specific point in time on a server. Can be retrieved by using {@link Db#command} + * @see https://docs.mongodb.com/manual/reference/method/db.runCommand/#response + */ + +/** + * @typedef ChangeStreamOptions + * @description Options that can be passed to a ChangeStream. Note that startAfter, resumeAfter, and startAtOperationTime are all mutually exclusive, and the server will error if more than one is specified. + * @property {string} [fullDocument='default'] Allowed values: ‘default’, ‘updateLookup’. When set to ‘updateLookup’, the change stream will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred. + * @property {number} [maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a change stream query. + * @property {ResumeToken} [resumeAfter] Allows you to start a changeStream after a specified event. See {@link https://docs.mongodb.com/master/changeStreams/#resumeafter-for-change-streams|ChangeStream documentation}. + * @property {ResumeToken} [startAfter] Similar to resumeAfter, but will allow you to start after an invalidated event. See {@link https://docs.mongodb.com/master/changeStreams/#startafter-for-change-streams|ChangeStream documentation}. + * @property {OperationTime} [startAtOperationTime] Will start the changeStream after the specified operationTime. + * @property {number} [batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. + * @property {object} [collation] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. + * @property {ReadPreference} [readPreference] The read preference. Defaults to the read preference of the database or collection. See {@link https://docs.mongodb.com/manual/reference/read-preference|read preference documentation}. + */ + +/** + * Creates a new Change Stream instance. Normally created using {@link Collection#watch|Collection.watch()}. + * @class ChangeStream + * @since 3.0.0 + * @param {(MongoClient|Db|Collection)} parent The parent object that created this change stream + * @param {Array} pipeline An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents + * @param {ChangeStreamOptions} [options] Optional settings + * @fires ChangeStream#close + * @fires ChangeStream#change + * @fires ChangeStream#end + * @fires ChangeStream#error + * @fires ChangeStream#resumeTokenChanged + * @return {ChangeStream} a ChangeStream instance. + */ +class ChangeStream extends EventEmitter { + constructor(parent, pipeline, options) { + super(); + const Collection = require('./collection'); + const Db = require('./db'); + const MongoClient = require('./mongo_client'); + + this.pipeline = pipeline || []; + this.options = options || {}; + + this.parent = parent; + this.namespace = parent.s.namespace; + if (parent instanceof Collection) { + this.type = CHANGE_DOMAIN_TYPES.COLLECTION; + this.topology = parent.s.db.serverConfig; + } else if (parent instanceof Db) { + this.type = CHANGE_DOMAIN_TYPES.DATABASE; + this.topology = parent.serverConfig; + } else if (parent instanceof MongoClient) { + this.type = CHANGE_DOMAIN_TYPES.CLUSTER; + this.topology = parent.topology; + } else { + throw new TypeError( + 'parent provided to ChangeStream constructor is not an instance of Collection, Db, or MongoClient' + ); + } + + this.promiseLibrary = parent.s.promiseLibrary; + if (!this.options.readPreference && parent.s.readPreference) { + this.options.readPreference = parent.s.readPreference; + } + + // Create contained Change Stream cursor + this.cursor = createChangeStreamCursor(this, options); + + // Listen for any `change` listeners being added to ChangeStream + this.on('newListener', eventName => { + if (eventName === 'change' && this.cursor && this.listenerCount('change') === 0) { + this.cursor.on('data', change => + processNewChange({ changeStream: this, change, eventEmitter: true }) + ); + } + }); + + // Listen for all `change` listeners being removed from ChangeStream + this.on('removeListener', eventName => { + if (eventName === 'change' && this.listenerCount('change') === 0 && this.cursor) { + this.cursor.removeAllListeners('data'); + } + }); + } + + /** + * @property {ResumeToken} resumeToken + * The cached resume token that will be used to resume + * after the most recently returned change. + */ + get resumeToken() { + return this.cursor.resumeToken; + } + + /** + * Check if there is any document still available in the Change Stream + * @function ChangeStream.prototype.hasNext + * @param {ChangeStream~resultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ + hasNext(callback) { + return this.cursor.hasNext(callback); + } + + /** + * Get the next available document from the Change Stream, returns null if no more documents are available. + * @function ChangeStream.prototype.next + * @param {ChangeStream~resultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ + next(callback) { + var self = this; + if (this.isClosed()) { + if (callback) return callback(new Error('Change Stream is not open.'), null); + return self.promiseLibrary.reject(new Error('Change Stream is not open.')); + } + + return this.cursor + .next() + .then(change => processNewChange({ changeStream: self, change, callback })) + .catch(error => processNewChange({ changeStream: self, error, callback })); + } + + /** + * Is the cursor closed + * @method ChangeStream.prototype.isClosed + * @return {boolean} + */ + isClosed() { + if (this.cursor) { + return this.cursor.isClosed(); + } + return true; + } + + /** + * Close the Change Stream + * @method ChangeStream.prototype.close + * @param {ChangeStream~resultCallback} [callback] The result callback. + * @return {Promise} returns Promise if no callback passed + */ + close(callback) { + if (!this.cursor) { + if (callback) return callback(); + return this.promiseLibrary.resolve(); + } + + // Tidy up the existing cursor + const cursor = this.cursor; + + if (callback) { + return cursor.close(err => { + ['data', 'close', 'end', 'error'].forEach(event => cursor.removeAllListeners(event)); + delete this.cursor; + + return callback(err); + }); + } + + const PromiseCtor = this.promiseLibrary || Promise; + return new PromiseCtor((resolve, reject) => { + cursor.close(err => { + ['data', 'close', 'end', 'error'].forEach(event => cursor.removeAllListeners(event)); + delete this.cursor; + + if (err) return reject(err); + resolve(); + }); + }); + } + + /** + * This method pulls all the data out of a readable stream, and writes it to the supplied destination, automatically managing the flow so that the destination is not overwhelmed by a fast readable stream. + * @method + * @param {Writable} destination The destination for writing data + * @param {object} [options] {@link https://nodejs.org/api/stream.html#stream_readable_pipe_destination_options|Pipe options} + * @return {null} + */ + pipe(destination, options) { + if (!this.pipeDestinations) { + this.pipeDestinations = []; + } + this.pipeDestinations.push(destination); + return this.cursor.pipe(destination, options); + } + + /** + * This method will remove the hooks set up for a previous pipe() call. + * @param {Writable} [destination] The destination for writing data + * @return {null} + */ + unpipe(destination) { + if (this.pipeDestinations && this.pipeDestinations.indexOf(destination) > -1) { + this.pipeDestinations.splice(this.pipeDestinations.indexOf(destination), 1); + } + return this.cursor.unpipe(destination); + } + + /** + * Return a modified Readable stream including a possible transform method. + * @method + * @param {object} [options] Optional settings. + * @param {function} [options.transform] A transformation method applied to each document emitted by the stream. + * @return {Cursor} + */ + stream(options) { + this.streamOptions = options; + return this.cursor.stream(options); + } + + /** + * This method will cause a stream in flowing mode to stop emitting data events. Any data that becomes available will remain in the internal buffer. + * @return {null} + */ + pause() { + return this.cursor.pause(); + } + + /** + * This method will cause the readable stream to resume emitting data events. + * @return {null} + */ + resume() { + return this.cursor.resume(); + } +} + +class ChangeStreamCursor extends Cursor { + constructor(topology, operation, options) { + super(topology, operation, options); + + options = options || {}; + this._resumeToken = null; + this.startAtOperationTime = options.startAtOperationTime; + + if (options.startAfter) { + this.resumeToken = options.startAfter; + } else if (options.resumeAfter) { + this.resumeToken = options.resumeAfter; + } + } + + set resumeToken(token) { + this._resumeToken = token; + this.emit('resumeTokenChanged', token); + } + + get resumeToken() { + return this._resumeToken; + } + + get resumeOptions() { + const result = {}; + for (const optionName of CURSOR_OPTIONS) { + if (this.options[optionName]) result[optionName] = this.options[optionName]; + } + + if (this.resumeToken || this.startAtOperationTime) { + ['resumeAfter', 'startAfter', 'startAtOperationTime'].forEach(key => delete result[key]); + + if (this.resumeToken) { + result.resumeAfter = this.resumeToken; + } else if (this.startAtOperationTime && maxWireVersion(this.server) >= 7) { + result.startAtOperationTime = this.startAtOperationTime; + } + } + + return result; + } + + _initializeCursor(callback) { + super._initializeCursor((err, result) => { + if (err) { + callback(err, null); + return; + } + + const response = result.documents[0]; + + if ( + this.startAtOperationTime == null && + this.resumeAfter == null && + this.startAfter == null && + maxWireVersion(this.server) >= 7 + ) { + this.startAtOperationTime = response.operationTime; + } + + const cursor = response.cursor; + if (cursor.postBatchResumeToken) { + this.cursorState.postBatchResumeToken = cursor.postBatchResumeToken; + + if (cursor.firstBatch.length === 0) { + this.resumeToken = cursor.postBatchResumeToken; + } + } + + this.emit('response'); + callback(err, result); + }); + } + + _getMore(callback) { + super._getMore((err, response) => { + if (err) { + callback(err, null); + return; + } + + const cursor = response.cursor; + if (cursor.postBatchResumeToken) { + this.cursorState.postBatchResumeToken = cursor.postBatchResumeToken; + + if (cursor.nextBatch.length === 0) { + this.resumeToken = cursor.postBatchResumeToken; + } + } + + this.emit('response'); + callback(err, response); + }); + } +} + +/** + * @event ChangeStreamCursor#response + * internal event DO NOT USE + * @ignore + */ + +// Create a new change stream cursor based on self's configuration +function createChangeStreamCursor(self, options) { + const changeStreamStageOptions = { fullDocument: options.fullDocument || 'default' }; + applyKnownOptions(changeStreamStageOptions, options, CHANGE_STREAM_OPTIONS); + if (self.type === CHANGE_DOMAIN_TYPES.CLUSTER) { + changeStreamStageOptions.allChangesForCluster = true; + } + + const pipeline = [{ $changeStream: changeStreamStageOptions }].concat(self.pipeline); + const cursorOptions = applyKnownOptions({}, options, CURSOR_OPTIONS); + const changeStreamCursor = new ChangeStreamCursor( + self.topology, + new AggregateOperation(self.parent, pipeline, options), + cursorOptions + ); + + relayEvents(changeStreamCursor, self, ['resumeTokenChanged', 'end', 'close']); + + /** + * Fired for each new matching change in the specified namespace. Attaching a `change` + * event listener to a Change Stream will switch the stream into flowing mode. Data will + * then be passed as soon as it is available. + * + * @event ChangeStream#change + * @type {object} + */ + if (self.listenerCount('change') > 0) { + changeStreamCursor.on('data', function(change) { + processNewChange({ changeStream: self, change, eventEmitter: true }); + }); + } + + /** + * Change stream close event + * + * @event ChangeStream#close + * @type {null} + */ + + /** + * Change stream end event + * + * @event ChangeStream#end + * @type {null} + */ + + /** + * Emitted each time the change stream stores a new resume token. + * + * @event ChangeStream#resumeTokenChanged + * @type {ResumeToken} + */ + + /** + * Fired when the stream encounters an error. + * + * @event ChangeStream#error + * @type {Error} + */ + changeStreamCursor.on('error', function(error) { + processNewChange({ changeStream: self, error, eventEmitter: true }); + }); + + if (self.pipeDestinations) { + const cursorStream = changeStreamCursor.stream(self.streamOptions); + for (let pipeDestination in self.pipeDestinations) { + cursorStream.pipe(pipeDestination); + } + } + + return changeStreamCursor; +} + +function applyKnownOptions(target, source, optionNames) { + optionNames.forEach(name => { + if (source[name]) { + target[name] = source[name]; + } + }); + + return target; +} + +// This method performs a basic server selection loop, satisfying the requirements of +// ChangeStream resumability until the new SDAM layer can be used. +const SELECTION_TIMEOUT = 30000; +function waitForTopologyConnected(topology, options, callback) { + setTimeout(() => { + if (options && options.start == null) options.start = process.hrtime(); + const start = options.start || process.hrtime(); + const timeout = options.timeout || SELECTION_TIMEOUT; + const readPreference = options.readPreference; + + if (topology.isConnected({ readPreference })) return callback(null, null); + const hrElapsed = process.hrtime(start); + const elapsed = (hrElapsed[0] * 1e9 + hrElapsed[1]) / 1e6; + if (elapsed > timeout) return callback(new MongoError('Timed out waiting for connection')); + waitForTopologyConnected(topology, options, callback); + }, 3000); // this is an arbitrary wait time to allow SDAM to transition +} + +// Handle new change events. This method brings together the routes from the callback, event emitter, and promise ways of using ChangeStream. +function processNewChange(args) { + const changeStream = args.changeStream; + const error = args.error; + const change = args.change; + const callback = args.callback; + const eventEmitter = args.eventEmitter || false; + + // If the changeStream is closed, then it should not process a change. + if (changeStream.isClosed()) { + // We do not error in the eventEmitter case. + if (eventEmitter) { + return; + } + + const error = new MongoError('ChangeStream is closed'); + return typeof callback === 'function' + ? callback(error, null) + : changeStream.promiseLibrary.reject(error); + } + + const cursor = changeStream.cursor; + const topology = changeStream.topology; + const options = changeStream.cursor.options; + + if (error) { + if (isResumableError(error) && !changeStream.attemptingResume) { + changeStream.attemptingResume = true; + + // stop listening to all events from old cursor + ['data', 'close', 'end', 'error'].forEach(event => + changeStream.cursor.removeAllListeners(event) + ); + + // close internal cursor, ignore errors + changeStream.cursor.close(); + + // attempt recreating the cursor + if (eventEmitter) { + waitForTopologyConnected(topology, { readPreference: options.readPreference }, err => { + if (err) { + changeStream.emit('error', err); + changeStream.emit('close'); + return; + } + changeStream.cursor = createChangeStreamCursor(changeStream, cursor.resumeOptions); + }); + + return; + } + + if (callback) { + waitForTopologyConnected(topology, { readPreference: options.readPreference }, err => { + if (err) return callback(err, null); + + changeStream.cursor = createChangeStreamCursor(changeStream, cursor.resumeOptions); + changeStream.next(callback); + }); + + return; + } + + return new Promise((resolve, reject) => { + waitForTopologyConnected(topology, { readPreference: options.readPreference }, err => { + if (err) return reject(err); + resolve(); + }); + }) + .then( + () => (changeStream.cursor = createChangeStreamCursor(changeStream, cursor.resumeOptions)) + ) + .then(() => changeStream.next()); + } + + if (eventEmitter) return changeStream.emit('error', error); + if (typeof callback === 'function') return callback(error, null); + return changeStream.promiseLibrary.reject(error); + } + + changeStream.attemptingResume = false; + + if (change && !change._id) { + const noResumeTokenError = new Error( + 'A change stream document has been received that lacks a resume token (_id).' + ); + + if (eventEmitter) return changeStream.emit('error', noResumeTokenError); + if (typeof callback === 'function') return callback(noResumeTokenError, null); + return changeStream.promiseLibrary.reject(noResumeTokenError); + } + + // cache the resume token + if (cursor.bufferedCount() === 0 && cursor.cursorState.postBatchResumeToken) { + cursor.resumeToken = cursor.cursorState.postBatchResumeToken; + } else { + cursor.resumeToken = change._id; + } + + // wipe the startAtOperationTime if there was one so that there won't be a conflict + // between resumeToken and startAtOperationTime if we need to reconnect the cursor + changeStream.options.startAtOperationTime = undefined; + + // Return the change + if (eventEmitter) return changeStream.emit('change', change); + if (typeof callback === 'function') return callback(error, change); + return changeStream.promiseLibrary.resolve(change); +} + +/** + * The callback format for results + * @callback ChangeStream~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {(object|null)} result The result object if the command was executed successfully. + */ + +module.exports = ChangeStream; diff --git a/scripts/node_modules/mongodb/lib/collection.js b/scripts/node_modules/mongodb/lib/collection.js new file mode 100644 index 00000000..49edbdbe --- /dev/null +++ b/scripts/node_modules/mongodb/lib/collection.js @@ -0,0 +1,2113 @@ +'use strict'; + +const deprecate = require('util').deprecate; +const deprecateOptions = require('./utils').deprecateOptions; +const checkCollectionName = require('./utils').checkCollectionName; +const ObjectID = require('./core').BSON.ObjectID; +const MongoError = require('./core').MongoError; +const toError = require('./utils').toError; +const normalizeHintField = require('./utils').normalizeHintField; +const decorateCommand = require('./utils').decorateCommand; +const decorateWithCollation = require('./utils').decorateWithCollation; +const decorateWithReadConcern = require('./utils').decorateWithReadConcern; +const formattedOrderClause = require('./utils').formattedOrderClause; +const ReadPreference = require('./core').ReadPreference; +const unordered = require('./bulk/unordered'); +const ordered = require('./bulk/ordered'); +const ChangeStream = require('./change_stream'); +const executeLegacyOperation = require('./utils').executeLegacyOperation; +const resolveReadPreference = require('./utils').resolveReadPreference; +const WriteConcern = require('./write_concern'); +const ReadConcern = require('./read_concern'); +const MongoDBNamespace = require('./utils').MongoDBNamespace; +const AggregationCursor = require('./aggregation_cursor'); +const CommandCursor = require('./command_cursor'); + +// Operations +const checkForAtomicOperators = require('./operations/collection_ops').checkForAtomicOperators; +const ensureIndex = require('./operations/collection_ops').ensureIndex; +const group = require('./operations/collection_ops').group; +const parallelCollectionScan = require('./operations/collection_ops').parallelCollectionScan; +const removeDocuments = require('./operations/common_functions').removeDocuments; +const save = require('./operations/collection_ops').save; +const updateDocuments = require('./operations/common_functions').updateDocuments; + +const AggregateOperation = require('./operations/aggregate'); +const BulkWriteOperation = require('./operations/bulk_write'); +const CountDocumentsOperation = require('./operations/count_documents'); +const CreateIndexOperation = require('./operations/create_index'); +const CreateIndexesOperation = require('./operations/create_indexes'); +const DeleteManyOperation = require('./operations/delete_many'); +const DeleteOneOperation = require('./operations/delete_one'); +const DistinctOperation = require('./operations/distinct'); +const DropCollectionOperation = require('./operations/drop').DropCollectionOperation; +const DropIndexOperation = require('./operations/drop_index'); +const DropIndexesOperation = require('./operations/drop_indexes'); +const EstimatedDocumentCountOperation = require('./operations/estimated_document_count'); +const FindOperation = require('./operations/find'); +const FindOneOperation = require('./operations/find_one'); +const FindAndModifyOperation = require('./operations/find_and_modify'); +const FindOneAndDeleteOperation = require('./operations/find_one_and_delete'); +const FindOneAndReplaceOperation = require('./operations/find_one_and_replace'); +const FindOneAndUpdateOperation = require('./operations/find_one_and_update'); +const GeoHaystackSearchOperation = require('./operations/geo_haystack_search'); +const IndexesOperation = require('./operations/indexes'); +const IndexExistsOperation = require('./operations/index_exists'); +const IndexInformationOperation = require('./operations/index_information'); +const InsertManyOperation = require('./operations/insert_many'); +const InsertOneOperation = require('./operations/insert_one'); +const IsCappedOperation = require('./operations/is_capped'); +const ListIndexesOperation = require('./operations/list_indexes'); +const MapReduceOperation = require('./operations/map_reduce'); +const OptionsOperation = require('./operations/options_operation'); +const RenameOperation = require('./operations/rename'); +const ReIndexOperation = require('./operations/re_index'); +const ReplaceOneOperation = require('./operations/replace_one'); +const StatsOperation = require('./operations/stats'); +const UpdateManyOperation = require('./operations/update_many'); +const UpdateOneOperation = require('./operations/update_one'); + +const executeOperation = require('./operations/execute_operation'); + +/** + * @fileOverview The **Collection** class is an internal class that embodies a MongoDB collection + * allowing for insert/update/remove/find and other command operation on that MongoDB collection. + * + * **COLLECTION Cannot directly be instantiated** + * @example + * const MongoClient = require('mongodb').MongoClient; + * const test = require('assert'); + * // Connection url + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, client) { + * // Create a collection we want to drop later + * const col = client.db(dbName).collection('createIndexExample1'); + * // Show that duplicate records got dropped + * col.find({}).toArray(function(err, items) { + * test.equal(null, err); + * test.equal(4, items.length); + * client.close(); + * }); + * }); + */ + +const mergeKeys = ['ignoreUndefined']; + +/** + * Create a new Collection instance (INTERNAL TYPE, do not instantiate directly) + * @class + * @property {string} collectionName Get the collection name. + * @property {string} namespace Get the full collection namespace. + * @property {object} writeConcern The current write concern values. + * @property {object} readConcern The current read concern values. + * @property {object} hint Get current index hint for collection. + * @return {Collection} a Collection instance. + */ +function Collection(db, topology, dbName, name, pkFactory, options) { + checkCollectionName(name); + + // Unpack variables + const internalHint = null; + const slaveOk = options == null || options.slaveOk == null ? db.slaveOk : options.slaveOk; + const serializeFunctions = + options == null || options.serializeFunctions == null + ? db.s.options.serializeFunctions + : options.serializeFunctions; + const raw = options == null || options.raw == null ? db.s.options.raw : options.raw; + const promoteLongs = + options == null || options.promoteLongs == null + ? db.s.options.promoteLongs + : options.promoteLongs; + const promoteValues = + options == null || options.promoteValues == null + ? db.s.options.promoteValues + : options.promoteValues; + const promoteBuffers = + options == null || options.promoteBuffers == null + ? db.s.options.promoteBuffers + : options.promoteBuffers; + const collectionHint = null; + + const namespace = new MongoDBNamespace(dbName, name); + + // Get the promiseLibrary + const promiseLibrary = options.promiseLibrary || Promise; + + // Set custom primary key factory if provided + pkFactory = pkFactory == null ? ObjectID : pkFactory; + + // Internal state + this.s = { + // Set custom primary key factory if provided + pkFactory: pkFactory, + // Db + db: db, + // Topology + topology: topology, + // Options + options: options, + // Namespace + namespace: namespace, + // Read preference + readPreference: ReadPreference.fromOptions(options), + // SlaveOK + slaveOk: slaveOk, + // Serialize functions + serializeFunctions: serializeFunctions, + // Raw + raw: raw, + // promoteLongs + promoteLongs: promoteLongs, + // promoteValues + promoteValues: promoteValues, + // promoteBuffers + promoteBuffers: promoteBuffers, + // internalHint + internalHint: internalHint, + // collectionHint + collectionHint: collectionHint, + // Promise library + promiseLibrary: promiseLibrary, + // Read Concern + readConcern: ReadConcern.fromOptions(options), + // Write Concern + writeConcern: WriteConcern.fromOptions(options) + }; +} + +Object.defineProperty(Collection.prototype, 'dbName', { + enumerable: true, + get: function() { + return this.s.namespace.db; + } +}); + +Object.defineProperty(Collection.prototype, 'collectionName', { + enumerable: true, + get: function() { + return this.s.namespace.collection; + } +}); + +Object.defineProperty(Collection.prototype, 'namespace', { + enumerable: true, + get: function() { + return this.s.namespace.toString(); + } +}); + +Object.defineProperty(Collection.prototype, 'readConcern', { + enumerable: true, + get: function() { + if (this.s.readConcern == null) { + return this.s.db.readConcern; + } + return this.s.readConcern; + } +}); + +Object.defineProperty(Collection.prototype, 'readPreference', { + enumerable: true, + get: function() { + if (this.s.readPreference == null) { + return this.s.db.readPreference; + } + + return this.s.readPreference; + } +}); + +Object.defineProperty(Collection.prototype, 'writeConcern', { + enumerable: true, + get: function() { + if (this.s.writeConcern == null) { + return this.s.db.writeConcern; + } + return this.s.writeConcern; + } +}); + +/** + * @ignore + */ +Object.defineProperty(Collection.prototype, 'hint', { + enumerable: true, + get: function() { + return this.s.collectionHint; + }, + set: function(v) { + this.s.collectionHint = normalizeHintField(v); + } +}); + +const DEPRECATED_FIND_OPTIONS = ['maxScan', 'fields', 'snapshot']; + +/** + * Creates a cursor for a query that can be used to iterate over results from MongoDB + * @method + * @param {object} [query={}] The cursor query object. + * @param {object} [options] Optional settings. + * @param {number} [options.limit=0] Sets the limit of documents returned in the query. + * @param {(array|object)} [options.sort] Set to sort the documents coming back from the query. Array of indexes, [['a', 1]] etc. + * @param {object} [options.projection] The fields to return in the query. Object of fields to include or exclude (not both), {'a':1} + * @param {object} [options.fields] **Deprecated** Use `options.projection` instead + * @param {number} [options.skip=0] Set to skip N documents ahead in your query (useful for pagination). + * @param {Object} [options.hint] Tell the query to use specific indexes in the query. Object of indexes to use, {'_id':1} + * @param {boolean} [options.explain=false] Explain the query instead of returning the data. + * @param {boolean} [options.snapshot=false] DEPRECATED: Snapshot query. + * @param {boolean} [options.timeout=false] Specify if the cursor can timeout. + * @param {boolean} [options.tailable=false] Specify if the cursor is tailable. + * @param {number} [options.batchSize=1000] Set the batchSize for the getMoreCommand when iterating over the query results. + * @param {boolean} [options.returnKey=false] Only return the index key. + * @param {number} [options.maxScan] DEPRECATED: Limit the number of items to scan. + * @param {number} [options.min] Set index bounds. + * @param {number} [options.max] Set index bounds. + * @param {boolean} [options.showDiskLoc=false] Show disk location of results. + * @param {string} [options.comment] You can put a $comment field on a query to make looking in the profiler logs simpler. + * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. + * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution. + * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. + * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {boolean} [options.partial=false] Specify if the cursor should return partial results when querying against a sharded system + * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query. + * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). + * @param {ClientSession} [options.session] optional session to use for this operation + * @throws {MongoError} + * @return {Cursor} + */ +Collection.prototype.find = deprecateOptions( + { + name: 'collection.find', + deprecatedOptions: DEPRECATED_FIND_OPTIONS, + optionsIndex: 1 + }, + function(query, options, callback) { + if (typeof callback === 'object') { + // TODO(MAJOR): throw in the future + console.warn('Third parameter to `find()` must be a callback or undefined'); + } + + let selector = query; + // figuring out arguments + if (typeof callback !== 'function') { + if (typeof options === 'function') { + callback = options; + options = undefined; + } else if (options == null) { + callback = typeof selector === 'function' ? selector : undefined; + selector = typeof selector === 'object' ? selector : undefined; + } + } + + // Ensure selector is not null + selector = selector == null ? {} : selector; + // Validate correctness off the selector + const object = selector; + if (Buffer.isBuffer(object)) { + const object_size = object[0] | (object[1] << 8) | (object[2] << 16) | (object[3] << 24); + if (object_size !== object.length) { + const error = new Error( + 'query selector raw message size does not match message header size [' + + object.length + + '] != [' + + object_size + + ']' + ); + error.name = 'MongoError'; + throw error; + } + } + + // Check special case where we are using an objectId + if (selector != null && selector._bsontype === 'ObjectID') { + selector = { _id: selector }; + } + + if (!options) options = {}; + + let projection = options.projection || options.fields; + + if (projection && !Buffer.isBuffer(projection) && Array.isArray(projection)) { + projection = projection.length + ? projection.reduce((result, field) => { + result[field] = 1; + return result; + }, {}) + : { _id: 1 }; + } + + // Make a shallow copy of options + let newOptions = Object.assign({}, options); + + // Make a shallow copy of the collection options + for (let key in this.s.options) { + if (mergeKeys.indexOf(key) !== -1) { + newOptions[key] = this.s.options[key]; + } + } + + // Unpack options + newOptions.skip = options.skip ? options.skip : 0; + newOptions.limit = options.limit ? options.limit : 0; + newOptions.raw = typeof options.raw === 'boolean' ? options.raw : this.s.raw; + newOptions.hint = + options.hint != null ? normalizeHintField(options.hint) : this.s.collectionHint; + newOptions.timeout = typeof options.timeout === 'undefined' ? undefined : options.timeout; + // // If we have overridden slaveOk otherwise use the default db setting + newOptions.slaveOk = options.slaveOk != null ? options.slaveOk : this.s.db.slaveOk; + + // Add read preference if needed + newOptions.readPreference = resolveReadPreference(this, newOptions); + + // Set slave ok to true if read preference different from primary + if ( + newOptions.readPreference != null && + (newOptions.readPreference !== 'primary' || newOptions.readPreference.mode !== 'primary') + ) { + newOptions.slaveOk = true; + } + + // Ensure the query is an object + if (selector != null && typeof selector !== 'object') { + throw MongoError.create({ message: 'query selector must be an object', driver: true }); + } + + // Build the find command + const findCommand = { + find: this.s.namespace.toString(), + limit: newOptions.limit, + skip: newOptions.skip, + query: selector + }; + + // Ensure we use the right await data option + if (typeof newOptions.awaitdata === 'boolean') { + newOptions.awaitData = newOptions.awaitdata; + } + + // Translate to new command option noCursorTimeout + if (typeof newOptions.timeout === 'boolean') newOptions.noCursorTimeout = newOptions.timeout; + + decorateCommand(findCommand, newOptions, ['session', 'collation']); + + if (projection) findCommand.fields = projection; + + // Add db object to the new options + newOptions.db = this.s.db; + + // Add the promise library + newOptions.promiseLibrary = this.s.promiseLibrary; + + // Set raw if available at collection level + if (newOptions.raw == null && typeof this.s.raw === 'boolean') newOptions.raw = this.s.raw; + // Set promoteLongs if available at collection level + if (newOptions.promoteLongs == null && typeof this.s.promoteLongs === 'boolean') + newOptions.promoteLongs = this.s.promoteLongs; + if (newOptions.promoteValues == null && typeof this.s.promoteValues === 'boolean') + newOptions.promoteValues = this.s.promoteValues; + if (newOptions.promoteBuffers == null && typeof this.s.promoteBuffers === 'boolean') + newOptions.promoteBuffers = this.s.promoteBuffers; + + // Sort options + if (findCommand.sort) { + findCommand.sort = formattedOrderClause(findCommand.sort); + } + + // Set the readConcern + decorateWithReadConcern(findCommand, this, options); + + // Decorate find command with collation options + try { + decorateWithCollation(findCommand, this, options); + } catch (err) { + if (typeof callback === 'function') return callback(err, null); + throw err; + } + + const cursor = this.s.topology.cursor( + new FindOperation(this, this.s.namespace, findCommand, newOptions), + newOptions + ); + + // TODO: remove this when NODE-2074 is resolved + if (typeof callback === 'function') { + callback(null, cursor); + return; + } + + return cursor; + } +); + +/** + * Inserts a single document into MongoDB. If documents passed in do not contain the **_id** field, + * one will be added to each of the documents missing it by the driver, mutating the document. This behavior + * can be overridden by setting the **forceServerObjectId** flag. + * + * @method + * @param {object} doc Document to insert. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~insertOneWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.insertOne = function(doc, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + // Add ignoreUndefined + if (this.s.options.ignoreUndefined) { + options = Object.assign({}, options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + const insertOneOperation = new InsertOneOperation(this, doc, options); + + return executeOperation(this.s.topology, insertOneOperation, callback); +}; + +/** + * Inserts an array of documents into MongoDB. If documents passed in do not contain the **_id** field, + * one will be added to each of the documents missing it by the driver, mutating the document. This behavior + * can be overridden by setting the **forceServerObjectId** flag. + * + * @method + * @param {object[]} docs Documents to insert. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {boolean} [options.ordered=true] If true, when an insert fails, don't execute the remaining writes. If false, continue with remaining inserts when one fails. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~insertWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.insertMany = function(docs, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options ? Object.assign({}, options) : { ordered: true }; + + const insertManyOperation = new InsertManyOperation(this, docs, options); + + return executeOperation(this.s.topology, insertManyOperation, callback); +}; + +/** + * @typedef {Object} Collection~BulkWriteOpResult + * @property {number} insertedCount Number of documents inserted. + * @property {number} matchedCount Number of documents matched for update. + * @property {number} modifiedCount Number of documents modified. + * @property {number} deletedCount Number of documents deleted. + * @property {number} upsertedCount Number of documents upserted. + * @property {object} insertedIds Inserted document generated Id's, hash key is the index of the originating operation + * @property {object} upsertedIds Upserted document generated Id's, hash key is the index of the originating operation + * @property {object} result The command result object. + */ + +/** + * The callback format for inserts + * @callback Collection~bulkWriteOpCallback + * @param {BulkWriteError} error An error instance representing the error during the execution. + * @param {Collection~BulkWriteOpResult} result The result object if the command was executed successfully. + */ + +/** + * Perform a bulkWrite operation without a fluent API + * + * Legal operation types are + * + * { insertOne: { document: { a: 1 } } } + * + * { updateOne: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } } + * + * { updateMany: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } } + * + * { updateMany: { filter: {}, update: {$set: {"a.$[i].x": 5}}, arrayFilters: [{ "i.x": 5 }]} } + * + * { deleteOne: { filter: {c:1} } } + * + * { deleteMany: { filter: {c:1} } } + * + * { replaceOne: { filter: {c:3}, replacement: {c:4}, upsert:true}} + * + * If documents passed in do not contain the **_id** field, + * one will be added to each of the documents missing it by the driver, mutating the document. This behavior + * can be overridden by setting the **forceServerObjectId** flag. + * + * @method + * @param {object[]} operations Bulk operations to perform. + * @param {object} [options] Optional settings. + * @param {object[]} [options.arrayFilters] Determines which array elements to modify for update operation in MongoDB 3.6 or higher. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {boolean} [options.ordered=true] Execute write operation in ordered or unordered fashion. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~bulkWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.bulkWrite = function(operations, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || { ordered: true }; + + if (!Array.isArray(operations)) { + throw MongoError.create({ message: 'operations must be an array of documents', driver: true }); + } + + const bulkWriteOperation = new BulkWriteOperation(this, operations, options); + + return executeOperation(this.s.topology, bulkWriteOperation, callback); +}; + +/** + * @typedef {Object} Collection~WriteOpResult + * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany + * @property {object} connection The connection object used for the operation. + * @property {object} result The command result object. + */ + +/** + * The callback format for inserts + * @callback Collection~writeOpCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection~WriteOpResult} result The result object if the command was executed successfully. + */ + +/** + * @typedef {Object} Collection~insertWriteOpResult + * @property {Number} insertedCount The total amount of documents inserted. + * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany + * @property {Object.} insertedIds Map of the index of the inserted document to the id of the inserted document. + * @property {object} connection The connection object used for the operation. + * @property {object} result The raw command result object returned from MongoDB (content might vary by server version). + * @property {Number} result.ok Is 1 if the command executed correctly. + * @property {Number} result.n The total count of documents inserted. + */ + +/** + * @typedef {Object} Collection~insertOneWriteOpResult + * @property {Number} insertedCount The total amount of documents inserted. + * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany + * @property {ObjectId} insertedId The driver generated ObjectId for the insert operation. + * @property {object} connection The connection object used for the operation. + * @property {object} result The raw command result object returned from MongoDB (content might vary by server version). + * @property {Number} result.ok Is 1 if the command executed correctly. + * @property {Number} result.n The total count of documents inserted. + */ + +/** + * The callback format for inserts + * @callback Collection~insertWriteOpCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection~insertWriteOpResult} result The result object if the command was executed successfully. + */ + +/** + * The callback format for inserts + * @callback Collection~insertOneWriteOpCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection~insertOneWriteOpResult} result The result object if the command was executed successfully. + */ + +/** + * Inserts a single document or a an array of documents into MongoDB. If documents passed in do not contain the **_id** field, + * one will be added to each of the documents missing it by the driver, mutating the document. This behavior + * can be overridden by setting the **forceServerObjectId** flag. + * + * @method + * @param {(object|object[])} docs Documents to insert. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~insertWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + * @deprecated Use insertOne, insertMany or bulkWrite + */ +Collection.prototype.insert = deprecate(function(docs, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || { ordered: false }; + docs = !Array.isArray(docs) ? [docs] : docs; + + if (options.keepGoing === true) { + options.ordered = false; + } + + return this.insertMany(docs, options, callback); +}, 'collection.insert is deprecated. Use insertOne, insertMany or bulkWrite instead.'); + +/** + * @typedef {Object} Collection~updateWriteOpResult + * @property {Object} result The raw result returned from MongoDB. Will vary depending on server version. + * @property {Number} result.ok Is 1 if the command executed correctly. + * @property {Number} result.n The total count of documents scanned. + * @property {Number} result.nModified The total count of documents modified. + * @property {Object} connection The connection object used for the operation. + * @property {Number} matchedCount The number of documents that matched the filter. + * @property {Number} modifiedCount The number of documents that were modified. + * @property {Number} upsertedCount The number of documents upserted. + * @property {Object} upsertedId The upserted id. + * @property {ObjectId} upsertedId._id The upserted _id returned from the server. + * @property {Object} message + * @property {object[]} [ops] In a response to {@link Collection#replaceOne replaceOne}, contains the new value of the document on the server. This is the same document that was originally passed in, and is only here for legacy purposes. + */ + +/** + * The callback format for inserts + * @callback Collection~updateWriteOpCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection~updateWriteOpResult} result The result object if the command was executed successfully. + */ + +/** + * Update a single document in a collection + * @method + * @param {object} filter The Filter used to select the document to update + * @param {object} update The update operations to be applied to the document + * @param {object} [options] Optional settings. + * @param {boolean} [options.upsert=false] Update operation is an upsert. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {Array} [options.arrayFilters] optional list of array filters referenced in filtered positional operators + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~updateWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.updateOne = function(filter, update, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const err = checkForAtomicOperators(update); + if (err) { + if (typeof callback === 'function') return callback(err); + return this.s.promiseLibrary.reject(err); + } + + options = Object.assign({}, options); + + // Add ignoreUndefined + if (this.s.options.ignoreUndefined) { + options = Object.assign({}, options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + const updateOneOperation = new UpdateOneOperation(this, filter, update, options); + + return executeOperation(this.s.topology, updateOneOperation, callback); +}; + +/** + * Replace a document in a collection with another document + * @method + * @param {object} filter The Filter used to select the document to replace + * @param {object} doc The Document that replaces the matching document + * @param {object} [options] Optional settings. + * @param {boolean} [options.upsert=false] Update operation is an upsert. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~updateWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.replaceOne = function(filter, doc, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = Object.assign({}, options); + + // Add ignoreUndefined + if (this.s.options.ignoreUndefined) { + options = Object.assign({}, options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + const replaceOneOperation = new ReplaceOneOperation(this, filter, doc, options); + + return executeOperation(this.s.topology, replaceOneOperation, callback); +}; + +/** + * Update multiple documents in a collection + * @method + * @param {object} filter The Filter used to select the documents to update + * @param {object} update The update operations to be applied to the documents + * @param {object} [options] Optional settings. + * @param {boolean} [options.upsert=false] Update operation is an upsert. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {Array} [options.arrayFilters] optional list of array filters referenced in filtered positional operators + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~updateWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.updateMany = function(filter, update, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const err = checkForAtomicOperators(update); + if (err) { + if (typeof callback === 'function') return callback(err); + return this.s.promiseLibrary.reject(err); + } + + options = Object.assign({}, options); + + // Add ignoreUndefined + if (this.s.options.ignoreUndefined) { + options = Object.assign({}, options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + const updateManyOperation = new UpdateManyOperation(this, filter, update, options); + + return executeOperation(this.s.topology, updateManyOperation, callback); +}; + +/** + * Updates documents. + * @method + * @param {object} selector The selector for the update operation. + * @param {object} update The update operations to be applied to the documents + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.upsert=false] Update operation is an upsert. + * @param {boolean} [options.multi=false] Update one/all documents with operation. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). + * @param {Array} [options.arrayFilters] optional list of array filters referenced in filtered positional operators + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~writeOpCallback} [callback] The command result callback + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + * @deprecated use updateOne, updateMany or bulkWrite + */ +Collection.prototype.update = deprecate(function(selector, update, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + // Add ignoreUndefined + if (this.s.options.ignoreUndefined) { + options = Object.assign({}, options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + return executeLegacyOperation(this.s.topology, updateDocuments, [ + this, + selector, + update, + options, + callback + ]); +}, 'collection.update is deprecated. Use updateOne, updateMany, or bulkWrite instead.'); + +/** + * @typedef {Object} Collection~deleteWriteOpResult + * @property {Object} result The raw result returned from MongoDB. Will vary depending on server version. + * @property {Number} result.ok Is 1 if the command executed correctly. + * @property {Number} result.n The total count of documents deleted. + * @property {Object} connection The connection object used for the operation. + * @property {Number} deletedCount The number of documents deleted. + */ + +/** + * The callback format for inserts + * @callback Collection~deleteWriteOpCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection~deleteWriteOpResult} result The result object if the command was executed successfully. + */ + +/** + * Delete a document from a collection + * @method + * @param {object} filter The Filter used to select the document to remove + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~deleteWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.deleteOne = function(filter, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = Object.assign({}, options); + + // Add ignoreUndefined + if (this.s.options.ignoreUndefined) { + options = Object.assign({}, options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + const deleteOneOperation = new DeleteOneOperation(this, filter, options); + + return executeOperation(this.s.topology, deleteOneOperation, callback); +}; + +Collection.prototype.removeOne = Collection.prototype.deleteOne; + +/** + * Delete multiple documents from a collection + * @method + * @param {object} filter The Filter used to select the documents to remove + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~deleteWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.deleteMany = function(filter, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = Object.assign({}, options); + + // Add ignoreUndefined + if (this.s.options.ignoreUndefined) { + options = Object.assign({}, options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + const deleteManyOperation = new DeleteManyOperation(this, filter, options); + + return executeOperation(this.s.topology, deleteManyOperation, callback); +}; + +Collection.prototype.removeMany = Collection.prototype.deleteMany; + +/** + * Remove documents. + * @method + * @param {object} selector The selector for the update operation. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.single=false] Removes the first document found. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~writeOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + * @deprecated use deleteOne, deleteMany or bulkWrite + */ +Collection.prototype.remove = deprecate(function(selector, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + // Add ignoreUndefined + if (this.s.options.ignoreUndefined) { + options = Object.assign({}, options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + return executeLegacyOperation(this.s.topology, removeDocuments, [ + this, + selector, + options, + callback + ]); +}, 'collection.remove is deprecated. Use deleteOne, deleteMany, or bulkWrite instead.'); + +/** + * Save a document. Simple full document replacement function. Not recommended for efficiency, use atomic + * operators and update instead for more efficient operations. + * @method + * @param {object} doc Document to save + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~writeOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + * @deprecated use insertOne, insertMany, updateOne or updateMany + */ +Collection.prototype.save = deprecate(function(doc, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + // Add ignoreUndefined + if (this.s.options.ignoreUndefined) { + options = Object.assign({}, options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + return executeLegacyOperation(this.s.topology, save, [this, doc, options, callback]); +}, 'collection.save is deprecated. Use insertOne, insertMany, updateOne, or updateMany instead.'); + +/** + * The callback format for results + * @callback Collection~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {object} result The result object if the command was executed successfully. + */ + +/** + * The callback format for an aggregation call + * @callback Collection~aggregationCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {AggregationCursor} cursor The cursor if the aggregation command was executed successfully. + */ + +/** + * Fetches the first document that matches the query + * @method + * @param {object} query Query for find Operation + * @param {object} [options] Optional settings. + * @param {number} [options.limit=0] Sets the limit of documents returned in the query. + * @param {(array|object)} [options.sort] Set to sort the documents coming back from the query. Array of indexes, [['a', 1]] etc. + * @param {object} [options.projection] The fields to return in the query. Object of fields to include or exclude (not both), {'a':1} + * @param {object} [options.fields] **Deprecated** Use `options.projection` instead + * @param {number} [options.skip=0] Set to skip N documents ahead in your query (useful for pagination). + * @param {Object} [options.hint] Tell the query to use specific indexes in the query. Object of indexes to use, {'_id':1} + * @param {boolean} [options.explain=false] Explain the query instead of returning the data. + * @param {boolean} [options.snapshot=false] DEPRECATED: Snapshot query. + * @param {boolean} [options.timeout=false] Specify if the cursor can timeout. + * @param {boolean} [options.tailable=false] Specify if the cursor is tailable. + * @param {number} [options.batchSize=1] Set the batchSize for the getMoreCommand when iterating over the query results. + * @param {boolean} [options.returnKey=false] Only return the index key. + * @param {number} [options.maxScan] DEPRECATED: Limit the number of items to scan. + * @param {number} [options.min] Set index bounds. + * @param {number} [options.max] Set index bounds. + * @param {boolean} [options.showDiskLoc=false] Show disk location of results. + * @param {string} [options.comment] You can put a $comment field on a query to make looking in the profiler logs simpler. + * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. + * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution. + * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. + * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {boolean} [options.partial=false] Specify if the cursor should return partial results when querying against a sharded system + * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query. + * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.findOne = deprecateOptions( + { + name: 'collection.find', + deprecatedOptions: DEPRECATED_FIND_OPTIONS, + optionsIndex: 1 + }, + function(query, options, callback) { + if (typeof callback === 'object') { + // TODO(MAJOR): throw in the future + console.warn('Third parameter to `findOne()` must be a callback or undefined'); + } + + if (typeof query === 'function') (callback = query), (query = {}), (options = {}); + if (typeof options === 'function') (callback = options), (options = {}); + query = query || {}; + options = options || {}; + + const findOneOperation = new FindOneOperation(this, query, options); + + return executeOperation(this.s.topology, findOneOperation, callback); + } +); + +/** + * The callback format for the collection method, must be used if strict is specified + * @callback Collection~collectionResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection} collection The collection instance. + */ + +/** + * Rename the collection. + * + * @method + * @param {string} newName New name of of the collection. + * @param {object} [options] Optional settings. + * @param {boolean} [options.dropTarget=false] Drop the target name collection if it previously exists. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~collectionResultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.rename = function(newName, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = Object.assign({}, options, { readPreference: ReadPreference.PRIMARY }); + + const renameOperation = new RenameOperation(this, newName, options); + + return executeOperation(this.s.topology, renameOperation, callback); +}; + +/** + * Drop the collection from the database, removing it permanently. New accesses will create a new collection. + * + * @method + * @param {object} [options] Optional settings. + * @param {WriteConcern} [options.writeConcern] A full WriteConcern object + * @param {(number|string)} [options.w] The write concern + * @param {number} [options.wtimeout] The write concern timeout + * @param {boolean} [options.j] The journal write concern + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.drop = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const dropCollectionOperation = new DropCollectionOperation( + this.s.db, + this.collectionName, + options + ); + + return executeOperation(this.s.topology, dropCollectionOperation, callback); +}; + +/** + * Returns the options of the collection. + * + * @method + * @param {Object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.options = function(opts, callback) { + if (typeof opts === 'function') (callback = opts), (opts = {}); + opts = opts || {}; + + const optionsOperation = new OptionsOperation(this, opts); + + return executeOperation(this.s.topology, optionsOperation, callback); +}; + +/** + * Returns if the collection is a capped collection + * + * @method + * @param {Object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.isCapped = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const isCappedOperation = new IsCappedOperation(this, options); + + return executeOperation(this.s.topology, isCappedOperation, callback); +}; + +/** + * Creates an index on the db and collection collection. + * @method + * @param {(string|array|object)} fieldOrSpec Defines the index. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.unique=false] Creates an unique index. + * @param {boolean} [options.sparse=false] Creates a sparse index. + * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. + * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value + * @param {number} [options.min] For geospatial indexes set the lower bound for the co-ordinates. + * @param {number} [options.max] For geospatial indexes set the high bound for the co-ordinates. + * @param {number} [options.v] Specify the format version of the indexes. + * @param {number} [options.expireAfterSeconds] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) + * @param {string} [options.name] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) + * @param {object} [options.partialFilterExpression] Creates a partial index based on the given filter object (MongoDB 3.2 or higher) + * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + * @example + * const collection = client.db('foo').collection('bar'); + * + * await collection.createIndex({ a: 1, b: -1 }); + * + * // Alternate syntax for { c: 1, d: -1 } that ensures order of indexes + * await collection.createIndex([ [c, 1], [d, -1] ]); + * + * // Equivalent to { e: 1 } + * await collection.createIndex('e'); + * + * // Equivalent to { f: 1, g: 1 } + * await collection.createIndex(['f', 'g']) + * + * // Equivalent to { h: 1, i: -1 } + * await collection.createIndex([ { h: 1 }, { i: -1 } ]); + * + * // Equivalent to { j: 1, k: -1, l: 2d } + * await collection.createIndex(['j', ['k', -1], { l: '2d' }]) + */ +Collection.prototype.createIndex = function(fieldOrSpec, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const createIndexOperation = new CreateIndexOperation( + this.s.db, + this.collectionName, + fieldOrSpec, + options + ); + + return executeOperation(this.s.topology, createIndexOperation, callback); +}; + +/** + * @typedef {object} Collection~IndexDefinition + * @description A definition for an index. Used by the createIndex command. + * @see https://docs.mongodb.com/manual/reference/command/createIndexes/ + */ + +/** + * Creates multiple indexes in the collection, this method is only supported for + * MongoDB 2.6 or higher. Earlier version of MongoDB will throw a command not supported + * error. + * + * **Note**: Unlike {@link Collection#createIndex createIndex}, this function takes in raw index specifications. + * Index specifications are defined {@link http://docs.mongodb.org/manual/reference/command/createIndexes/ here}. + * + * @method + * @param {Collection~IndexDefinition[]} indexSpecs An array of index specifications to be created + * @param {Object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + * @example + * const collection = client.db('foo').collection('bar'); + * await collection.createIndexes([ + * // Simple index on field fizz + * { + * key: { fizz: 1 }, + * } + * // wildcard index + * { + * key: { '$**': 1 } + * }, + * // named index on darmok and jalad + * { + * key: { darmok: 1, jalad: -1 } + * name: 'tanagra' + * } + * ]); + */ +Collection.prototype.createIndexes = function(indexSpecs, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + + options = options ? Object.assign({}, options) : {}; + if (typeof options.maxTimeMS !== 'number') delete options.maxTimeMS; + + const createIndexesOperation = new CreateIndexesOperation(this, indexSpecs, options); + + return executeOperation(this.s.topology, createIndexesOperation, callback); +}; + +/** + * Drops an index from this collection. + * @method + * @param {string} indexName Name of the index to drop. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query. + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.dropIndex = function(indexName, options, callback) { + const args = Array.prototype.slice.call(arguments, 1); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + + options = args.length ? args.shift() || {} : {}; + // Run only against primary + options.readPreference = ReadPreference.PRIMARY; + + const dropIndexOperation = new DropIndexOperation(this, indexName, options); + + return executeOperation(this.s.topology, dropIndexOperation, callback); +}; + +/** + * Drops all indexes from this collection. + * @method + * @param {Object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query. + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.dropIndexes = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options ? Object.assign({}, options) : {}; + + if (typeof options.maxTimeMS !== 'number') delete options.maxTimeMS; + + const dropIndexesOperation = new DropIndexesOperation(this, options); + + return executeOperation(this.s.topology, dropIndexesOperation, callback); +}; + +/** + * Drops all indexes from this collection. + * @method + * @deprecated use dropIndexes + * @param {Collection~resultCallback} callback The command result callback + * @return {Promise} returns Promise if no [callback] passed + */ +Collection.prototype.dropAllIndexes = deprecate( + Collection.prototype.dropIndexes, + 'collection.dropAllIndexes is deprecated. Use dropIndexes instead.' +); + +/** + * Reindex all indexes on the collection + * Warning: reIndex is a blocking operation (indexes are rebuilt in the foreground) and will be slow for large collections. + * @method + * @param {Object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.reIndex = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const reIndexOperation = new ReIndexOperation(this, options); + + return executeOperation(this.s.topology, reIndexOperation, callback); +}; + +/** + * Get the list of all indexes information for the collection. + * + * @method + * @param {object} [options] Optional settings. + * @param {number} [options.batchSize=1000] The batchSize for the returned command cursor or if pre 2.8 the systems batch collection + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {ClientSession} [options.session] optional session to use for this operation + * @return {CommandCursor} + */ +Collection.prototype.listIndexes = function(options) { + const cursor = new CommandCursor( + this.s.topology, + new ListIndexesOperation(this, options), + options + ); + + return cursor; +}; + +/** + * Ensures that an index exists, if it does not it creates it + * @method + * @deprecated use createIndexes instead + * @param {(string|object)} fieldOrSpec Defines the index. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.unique=false] Creates an unique index. + * @param {boolean} [options.sparse=false] Creates a sparse index. + * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. + * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value + * @param {number} [options.min] For geospatial indexes set the lower bound for the co-ordinates. + * @param {number} [options.max] For geospatial indexes set the high bound for the co-ordinates. + * @param {number} [options.v] Specify the format version of the indexes. + * @param {number} [options.expireAfterSeconds] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) + * @param {number} [options.name] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) + * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.ensureIndex = deprecate(function(fieldOrSpec, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeLegacyOperation(this.s.topology, ensureIndex, [ + this, + fieldOrSpec, + options, + callback + ]); +}, 'collection.ensureIndex is deprecated. Use createIndexes instead.'); + +/** + * Checks if one or more indexes exist on the collection, fails on first non-existing index + * @method + * @param {(string|array)} indexes One or more index names to check. + * @param {Object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.indexExists = function(indexes, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const indexExistsOperation = new IndexExistsOperation(this, indexes, options); + + return executeOperation(this.s.topology, indexExistsOperation, callback); +}; + +/** + * Retrieves this collections index info. + * @method + * @param {object} [options] Optional settings. + * @param {boolean} [options.full=false] Returns the full raw index information. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.indexInformation = function(options, callback) { + const args = Array.prototype.slice.call(arguments, 0); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + options = args.length ? args.shift() || {} : {}; + + const indexInformationOperation = new IndexInformationOperation( + this.s.db, + this.collectionName, + options + ); + + return executeOperation(this.s.topology, indexInformationOperation, callback); +}; + +/** + * The callback format for results + * @callback Collection~countCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {number} result The count of documents that matched the query. + */ + +/** + * An estimated count of matching documents in the db to a query. + * + * **NOTE:** This method has been deprecated, since it does not provide an accurate count of the documents + * in a collection. To obtain an accurate count of documents in the collection, use {@link Collection#countDocuments countDocuments}. + * To obtain an estimated count of all documents in the collection, use {@link Collection#estimatedDocumentCount estimatedDocumentCount}. + * + * @method + * @param {object} [query={}] The query for the count. + * @param {object} [options] Optional settings. + * @param {boolean} [options.limit] The limit of documents to count. + * @param {boolean} [options.skip] The number of documents to skip for the count. + * @param {string} [options.hint] An index name hint for the query. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~countCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + * @deprecated use {@link Collection#countDocuments countDocuments} or {@link Collection#estimatedDocumentCount estimatedDocumentCount} instead + */ +Collection.prototype.count = deprecate(function(query, options, callback) { + const args = Array.prototype.slice.call(arguments, 0); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + query = args.length ? args.shift() || {} : {}; + options = args.length ? args.shift() || {} : {}; + + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeOperation( + this.s.topology, + new EstimatedDocumentCountOperation(this, query, options), + callback + ); +}, 'collection.count is deprecated, and will be removed in a future version.' + + ' Use Collection.countDocuments or Collection.estimatedDocumentCount instead'); + +/** + * Gets an estimate of the count of documents in a collection using collection metadata. + * + * @method + * @param {object} [options] Optional settings. + * @param {number} [options.maxTimeMS] The maximum amount of time to allow the operation to run. + * @param {Collection~countCallback} [callback] The command result callback. + * @return {Promise} returns Promise if no callback passed. + */ +Collection.prototype.estimatedDocumentCount = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const estimatedDocumentCountOperation = new EstimatedDocumentCountOperation(this, options); + + return executeOperation(this.s.topology, estimatedDocumentCountOperation, callback); +}; + +/** + * Gets the number of documents matching the filter. + * For a fast count of the total documents in a collection see {@link Collection#estimatedDocumentCount estimatedDocumentCount}. + * **Note**: When migrating from {@link Collection#count count} to {@link Collection#countDocuments countDocuments} + * the following query operators must be replaced: + * + * | Operator | Replacement | + * | -------- | ----------- | + * | `$where` | [`$expr`][1] | + * | `$near` | [`$geoWithin`][2] with [`$center`][3] | + * | `$nearSphere` | [`$geoWithin`][2] with [`$centerSphere`][4] | + * + * [1]: https://docs.mongodb.com/manual/reference/operator/query/expr/ + * [2]: https://docs.mongodb.com/manual/reference/operator/query/geoWithin/ + * [3]: https://docs.mongodb.com/manual/reference/operator/query/center/#op._S_center + * [4]: https://docs.mongodb.com/manual/reference/operator/query/centerSphere/#op._S_centerSphere + * + * @param {object} [query] the query for the count + * @param {object} [options] Optional settings. + * @param {object} [options.collation] Specifies a collation. + * @param {string|object} [options.hint] The index to use. + * @param {number} [options.limit] The maximum number of document to count. + * @param {number} [options.maxTimeMS] The maximum amount of time to allow the operation to run. + * @param {number} [options.skip] The number of documents to skip before counting. + * @param {Collection~countCallback} [callback] The command result callback. + * @return {Promise} returns Promise if no callback passed. + * @see https://docs.mongodb.com/manual/reference/operator/query/expr/ + * @see https://docs.mongodb.com/manual/reference/operator/query/geoWithin/ + * @see https://docs.mongodb.com/manual/reference/operator/query/center/#op._S_center + * @see https://docs.mongodb.com/manual/reference/operator/query/centerSphere/#op._S_centerSphere + */ + +Collection.prototype.countDocuments = function(query, options, callback) { + const args = Array.prototype.slice.call(arguments, 0); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + query = args.length ? args.shift() || {} : {}; + options = args.length ? args.shift() || {} : {}; + + const countDocumentsOperation = new CountDocumentsOperation(this, query, options); + + return executeOperation(this.s.topology, countDocumentsOperation, callback); +}; + +/** + * The distinct command returns a list of distinct values for the given key across a collection. + * @method + * @param {string} key Field of the document to find distinct values for. + * @param {object} query The query for filtering the set of documents to which we apply the distinct filter. + * @param {object} [options] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.distinct = function(key, query, options, callback) { + const args = Array.prototype.slice.call(arguments, 1); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + const queryOption = args.length ? args.shift() || {} : {}; + const optionsOption = args.length ? args.shift() || {} : {}; + + const distinctOperation = new DistinctOperation(this, key, queryOption, optionsOption); + + return executeOperation(this.s.topology, distinctOperation, callback); +}; + +/** + * Retrieve all the indexes on the collection. + * @method + * @param {Object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.indexes = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const indexesOperation = new IndexesOperation(this, options); + + return executeOperation(this.s.topology, indexesOperation, callback); +}; + +/** + * Get all the collection statistics. + * + * @method + * @param {object} [options] Optional settings. + * @param {number} [options.scale] Divide the returned sizes by scale value. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The collection result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.stats = function(options, callback) { + const args = Array.prototype.slice.call(arguments, 0); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + options = args.length ? args.shift() || {} : {}; + + const statsOperation = new StatsOperation(this, options); + + return executeOperation(this.s.topology, statsOperation, callback); +}; + +/** + * @typedef {Object} Collection~findAndModifyWriteOpResult + * @property {object} value Document returned from the `findAndModify` command. If no documents were found, `value` will be `null` by default (`returnOriginal: true`), even if a document was upserted; if `returnOriginal` was false, the upserted document will be returned in that case. + * @property {object} lastErrorObject The raw lastErrorObject returned from the command. See {@link https://docs.mongodb.com/manual/reference/command/findAndModify/index.html#lasterrorobject|findAndModify command documentation}. + * @property {Number} ok Is 1 if the command executed correctly. + */ + +/** + * The callback format for inserts + * @callback Collection~findAndModifyCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection~findAndModifyWriteOpResult} result The result object if the command was executed successfully. + */ + +/** + * Find a document and delete it in one atomic operation. Requires a write lock for the duration of the operation. + * + * @method + * @param {object} filter The Filter used to select the document to remove + * @param {object} [options] Optional settings. + * @param {object} [options.projection] Limits the fields to return for all matching documents. + * @param {object} [options.sort] Determines which document the operation modifies if the query selects multiple documents. + * @param {number} [options.maxTimeMS] The maximum amount of time to allow the query to run. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~findAndModifyCallback} [callback] The collection result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.findOneAndDelete = function(filter, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + // Basic validation + if (filter == null || typeof filter !== 'object') + throw toError('filter parameter must be an object'); + + const findOneAndDeleteOperation = new FindOneAndDeleteOperation(this, filter, options); + + return executeOperation(this.s.topology, findOneAndDeleteOperation, callback); +}; + +/** + * Find a document and replace it in one atomic operation. Requires a write lock for the duration of the operation. + * + * @method + * @param {object} filter The Filter used to select the document to replace + * @param {object} replacement The Document that replaces the matching document + * @param {object} [options] Optional settings. + * @param {object} [options.projection] Limits the fields to return for all matching documents. + * @param {object} [options.sort] Determines which document the operation modifies if the query selects multiple documents. + * @param {number} [options.maxTimeMS] The maximum amount of time to allow the query to run. + * @param {boolean} [options.upsert=false] Upsert the document if it does not exist. + * @param {boolean} [options.returnOriginal=true] When false, returns the updated document rather than the original. The default is true. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~findAndModifyCallback} [callback] The collection result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.findOneAndReplace = function(filter, replacement, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + // Basic validation + if (filter == null || typeof filter !== 'object') + throw toError('filter parameter must be an object'); + if (replacement == null || typeof replacement !== 'object') + throw toError('replacement parameter must be an object'); + + // Check that there are no atomic operators + const keys = Object.keys(replacement); + + if (keys[0] && keys[0][0] === '$') { + throw toError('The replacement document must not contain atomic operators.'); + } + + const findOneAndReplaceOperation = new FindOneAndReplaceOperation( + this, + filter, + replacement, + options + ); + + return executeOperation(this.s.topology, findOneAndReplaceOperation, callback); +}; + +/** + * Find a document and update it in one atomic operation. Requires a write lock for the duration of the operation. + * + * @method + * @param {object} filter The Filter used to select the document to update + * @param {object} update Update operations to be performed on the document + * @param {object} [options] Optional settings. + * @param {object} [options.projection] Limits the fields to return for all matching documents. + * @param {object} [options.sort] Determines which document the operation modifies if the query selects multiple documents. + * @param {number} [options.maxTimeMS] The maximum amount of time to allow the query to run. + * @param {boolean} [options.upsert=false] Upsert the document if it does not exist. + * @param {boolean} [options.returnOriginal=true] When false, returns the updated document rather than the original. The default is true. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Array} [options.arrayFilters] optional list of array filters referenced in filtered positional operators + * @param {Collection~findAndModifyCallback} [callback] The collection result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.findOneAndUpdate = function(filter, update, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + // Basic validation + if (filter == null || typeof filter !== 'object') + throw toError('filter parameter must be an object'); + if (update == null || typeof update !== 'object') + throw toError('update parameter must be an object'); + + const err = checkForAtomicOperators(update); + if (err) { + if (typeof callback === 'function') return callback(err); + return this.s.promiseLibrary.reject(err); + } + + const findOneAndUpdateOperation = new FindOneAndUpdateOperation(this, filter, update, options); + + return executeOperation(this.s.topology, findOneAndUpdateOperation, callback); +}; + +/** + * Find and update a document. + * @method + * @param {object} query Query object to locate the object to modify. + * @param {array} sort If multiple docs match, choose the first one in the specified sort order as the object to manipulate. + * @param {object} doc The fields/vals to be updated. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.remove=false] Set to true to remove the object before returning. + * @param {boolean} [options.upsert=false] Perform an upsert operation. + * @param {boolean} [options.new=false] Set to true if you want to return the modified object rather than the original. Ignored for remove. + * @param {object} [options.projection] Object containing the field projection for the result returned from the operation. + * @param {object} [options.fields] **Deprecated** Use `options.projection` instead + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Array} [options.arrayFilters] optional list of array filters referenced in filtered positional operators + * @param {Collection~findAndModifyCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + * @deprecated use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead + */ +Collection.prototype.findAndModify = deprecate( + _findAndModify, + 'collection.findAndModify is deprecated. Use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead.' +); + +/** + * @ignore + */ + +Collection.prototype._findAndModify = _findAndModify; + +function _findAndModify(query, sort, doc, options, callback) { + const args = Array.prototype.slice.call(arguments, 1); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + sort = args.length ? args.shift() || [] : []; + doc = args.length ? args.shift() : null; + options = args.length ? args.shift() || {} : {}; + + // Clone options + options = Object.assign({}, options); + // Force read preference primary + options.readPreference = ReadPreference.PRIMARY; + + return executeOperation( + this.s.topology, + new FindAndModifyOperation(this, query, sort, doc, options), + callback + ); +} + +/** + * Find and remove a document. + * @method + * @param {object} query Query object to locate the object to modify. + * @param {array} sort If multiple docs match, choose the first one in the specified sort order as the object to manipulate. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + * @deprecated use findOneAndDelete instead + */ +Collection.prototype.findAndRemove = deprecate(function(query, sort, options, callback) { + const args = Array.prototype.slice.call(arguments, 1); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + sort = args.length ? args.shift() || [] : []; + options = args.length ? args.shift() || {} : {}; + + // Add the remove option + options.remove = true; + + return executeOperation( + this.s.topology, + new FindAndModifyOperation(this, query, sort, null, options), + callback + ); +}, 'collection.findAndRemove is deprecated. Use findOneAndDelete instead.'); + +/** + * Execute an aggregation framework pipeline against the collection, needs MongoDB >= 2.2 + * @method + * @param {object} [pipeline=[]] Array containing all the aggregation framework commands for the execution. + * @param {object} [options] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {object} [options.cursor] Return the query as cursor, on 2.6 > it returns as a real cursor on pre 2.6 it returns as an emulated cursor. + * @param {number} [options.cursor.batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. + * @param {boolean} [options.explain=false] Explain returns the aggregation execution plan (requires mongodb 2.6 >). + * @param {boolean} [options.allowDiskUse=false] allowDiskUse lets the server know if it can use disk to store temporary results for the aggregation (requires mongodb 2.6 >). + * @param {number} [options.maxTimeMS] maxTimeMS specifies a cumulative time limit in milliseconds for processing operations on the cursor. MongoDB interrupts the operation at the earliest following interrupt point. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. + * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution. + * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. + * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. + * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). + * @param {string} [options.comment] Add a comment to an aggregation command + * @param {string|object} [options.hint] Add an index selection hint to an aggregation command + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~aggregationCallback} callback The command result callback + * @return {(null|AggregationCursor)} + */ +Collection.prototype.aggregate = function(pipeline, options, callback) { + if (Array.isArray(pipeline)) { + // Set up callback if one is provided + if (typeof options === 'function') { + callback = options; + options = {}; + } + + // If we have no options or callback we are doing + // a cursor based aggregation + if (options == null && callback == null) { + options = {}; + } + } else { + // Aggregation pipeline passed as arguments on the method + const args = Array.prototype.slice.call(arguments, 0); + // Get the callback + callback = args.pop(); + // Get the possible options object + const opts = args[args.length - 1]; + // If it contains any of the admissible options pop it of the args + options = + opts && + (opts.readPreference || + opts.explain || + opts.cursor || + opts.out || + opts.maxTimeMS || + opts.hint || + opts.allowDiskUse) + ? args.pop() + : {}; + // Left over arguments is the pipeline + pipeline = args; + } + + const cursor = new AggregationCursor( + this.s.topology, + new AggregateOperation(this, pipeline, options), + options + ); + + // TODO: remove this when NODE-2074 is resolved + if (typeof callback === 'function') { + callback(null, cursor); + return; + } + + return cursor; +}; + +/** + * Create a new Change Stream, watching for new changes (insertions, updates, replacements, deletions, and invalidations) in this collection. + * @method + * @since 3.0.0 + * @param {Array} [pipeline] An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents. + * @param {object} [options] Optional settings + * @param {string} [options.fullDocument='default'] Allowed values: ‘default’, ‘updateLookup’. When set to ‘updateLookup’, the change stream will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred. + * @param {object} [options.resumeAfter] Specifies the logical starting point for the new change stream. This should be the _id field from a previously returned change stream document. + * @param {number} [options.maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a change stream query + * @param {number} [options.batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. + * @param {object} [options.collation] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. + * @param {ReadPreference} [options.readPreference] The read preference. Defaults to the read preference of the database or collection. See {@link https://docs.mongodb.com/manual/reference/read-preference|read preference documentation}. + * @param {Timestamp} [options.startAtOperationTime] receive change events that occur after the specified timestamp + * @param {ClientSession} [options.session] optional session to use for this operation + * @return {ChangeStream} a ChangeStream instance. + */ +Collection.prototype.watch = function(pipeline, options) { + pipeline = pipeline || []; + options = options || {}; + + // Allow optionally not specifying a pipeline + if (!Array.isArray(pipeline)) { + options = pipeline; + pipeline = []; + } + + return new ChangeStream(this, pipeline, options); +}; + +/** + * The callback format for results + * @callback Collection~parallelCollectionScanCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Cursor[]} cursors A list of cursors returned allowing for parallel reading of collection. + */ + +/** + * Return N number of parallel cursors for a collection allowing parallel reading of entire collection. There are + * no ordering guarantees for returned results. + * @method + * @param {object} [options] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {number} [options.batchSize=1000] Set the batchSize for the getMoreCommand when iterating over the query results. + * @param {number} [options.numCursors=1] The maximum number of parallel command cursors to return (the number of returned cursors will be in the range 1:numCursors) + * @param {boolean} [options.raw=false] Return all BSON documents as Raw Buffer documents. + * @param {Collection~parallelCollectionScanCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.parallelCollectionScan = deprecate(function(options, callback) { + if (typeof options === 'function') (callback = options), (options = { numCursors: 1 }); + // Set number of cursors to 1 + options.numCursors = options.numCursors || 1; + options.batchSize = options.batchSize || 1000; + + options = Object.assign({}, options); + // Ensure we have the right read preference inheritance + options.readPreference = resolveReadPreference(this, options); + + // Add a promiseLibrary + options.promiseLibrary = this.s.promiseLibrary; + + if (options.session) { + options.session = undefined; + } + + return executeLegacyOperation( + this.s.topology, + parallelCollectionScan, + [this, options, callback], + { skipSessions: true } + ); +}, 'parallelCollectionScan is deprecated in MongoDB v4.1'); + +/** + * Execute a geo search using a geo haystack index on a collection. + * + * @method + * @param {number} x Point to search on the x axis, ensure the indexes are ordered in the same order. + * @param {number} y Point to search on the y axis, ensure the indexes are ordered in the same order. + * @param {object} [options] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {number} [options.maxDistance] Include results up to maxDistance from the point. + * @param {object} [options.search] Filter the results by a query. + * @param {number} [options.limit=false] Max number of results to return. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.geoHaystackSearch = function(x, y, options, callback) { + const args = Array.prototype.slice.call(arguments, 2); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + options = args.length ? args.shift() || {} : {}; + + const geoHaystackSearchOperation = new GeoHaystackSearchOperation(this, x, y, options); + + return executeOperation(this.s.topology, geoHaystackSearchOperation, callback); +}; + +/** + * Run a group command across a collection + * + * @method + * @param {(object|array|function|code)} keys An object, array or function expressing the keys to group by. + * @param {object} condition An optional condition that must be true for a row to be considered. + * @param {object} initial Initial value of the aggregation counter object. + * @param {(function|Code)} reduce The reduce function aggregates (reduces) the objects iterated + * @param {(function|Code)} finalize An optional function to be run on each item in the result set just before the item is returned. + * @param {boolean} command Specify if you wish to run using the internal group command or using eval, default is true. + * @param {object} [options] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + * @deprecated MongoDB 3.6 or higher no longer supports the group command. We recommend rewriting using the aggregation framework. + */ +Collection.prototype.group = deprecate(function( + keys, + condition, + initial, + reduce, + finalize, + command, + options, + callback +) { + const args = Array.prototype.slice.call(arguments, 3); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + reduce = args.length ? args.shift() : null; + finalize = args.length ? args.shift() : null; + command = args.length ? args.shift() : null; + options = args.length ? args.shift() || {} : {}; + + // Make sure we are backward compatible + if (!(typeof finalize === 'function')) { + command = finalize; + finalize = null; + } + + if ( + !Array.isArray(keys) && + keys instanceof Object && + typeof keys !== 'function' && + !(keys._bsontype === 'Code') + ) { + keys = Object.keys(keys); + } + + if (typeof reduce === 'function') { + reduce = reduce.toString(); + } + + if (typeof finalize === 'function') { + finalize = finalize.toString(); + } + + // Set up the command as default + command = command == null ? true : command; + + return executeLegacyOperation(this.s.topology, group, [ + this, + keys, + condition, + initial, + reduce, + finalize, + command, + options, + callback + ]); +}, +'MongoDB 3.6 or higher no longer supports the group command. We recommend rewriting using the aggregation framework.'); + +/** + * Run Map Reduce across a collection. Be aware that the inline option for out will return an array of results not a collection. + * + * @method + * @param {(function|string)} map The mapping function. + * @param {(function|string)} reduce The reduce function. + * @param {object} [options] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {object} [options.out] Sets the output target for the map reduce job. *{inline:1} | {replace:'collectionName'} | {merge:'collectionName'} | {reduce:'collectionName'}* + * @param {object} [options.query] Query filter object. + * @param {object} [options.sort] Sorts the input objects using this key. Useful for optimization, like sorting by the emit key for fewer reduces. + * @param {number} [options.limit] Number of objects to return from collection. + * @param {boolean} [options.keeptemp=false] Keep temporary data. + * @param {(function|string)} [options.finalize] Finalize function. + * @param {object} [options.scope] Can pass in variables that can be access from map/reduce/finalize. + * @param {boolean} [options.jsMode=false] It is possible to make the execution stay in JS. Provided in MongoDB > 2.0.X. + * @param {boolean} [options.verbose=false] Provide statistics on job execution time. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Collection~resultCallback} [callback] The command result callback + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.mapReduce = function(map, reduce, options, callback) { + if ('function' === typeof options) (callback = options), (options = {}); + // Out must allways be defined (make sure we don't break weirdly on pre 1.8+ servers) + if (null == options.out) { + throw new Error( + 'the out option parameter must be defined, see mongodb docs for possible values' + ); + } + + if ('function' === typeof map) { + map = map.toString(); + } + + if ('function' === typeof reduce) { + reduce = reduce.toString(); + } + + if ('function' === typeof options.finalize) { + options.finalize = options.finalize.toString(); + } + const mapReduceOperation = new MapReduceOperation(this, map, reduce, options); + + return executeOperation(this.s.topology, mapReduceOperation, callback); +}; + +/** + * Initiate an Out of order batch write operation. All operations will be buffered into insert/update/remove commands executed out of order. + * + * @method + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session] optional session to use for this operation + * @return {UnorderedBulkOperation} + */ +Collection.prototype.initializeUnorderedBulkOp = function(options) { + options = options || {}; + // Give function's options precedence over session options. + if (options.ignoreUndefined == null) { + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + options.promiseLibrary = this.s.promiseLibrary; + return unordered(this.s.topology, this, options); +}; + +/** + * Initiate an In order bulk write operation. Operations will be serially executed in the order they are added, creating a new operation for each switch in types. + * + * @method + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {OrderedBulkOperation} callback The command result callback + * @return {null} + */ +Collection.prototype.initializeOrderedBulkOp = function(options) { + options = options || {}; + // Give function's options precedence over session's options. + if (options.ignoreUndefined == null) { + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + options.promiseLibrary = this.s.promiseLibrary; + return ordered(this.s.topology, this, options); +}; + +/** + * Return the db logger + * @method + * @return {Logger} return the db logger + * @ignore + */ +Collection.prototype.getLogger = function() { + return this.s.db.s.logger; +}; + +module.exports = Collection; diff --git a/scripts/node_modules/mongodb/lib/command_cursor.js b/scripts/node_modules/mongodb/lib/command_cursor.js new file mode 100644 index 00000000..cd0f9d7a --- /dev/null +++ b/scripts/node_modules/mongodb/lib/command_cursor.js @@ -0,0 +1,269 @@ +'use strict'; + +const ReadPreference = require('./core').ReadPreference; +const MongoError = require('./core').MongoError; +const Cursor = require('./cursor'); +const CursorState = require('./core/cursor').CursorState; + +/** + * @fileOverview The **CommandCursor** class is an internal class that embodies a + * generalized cursor based on a MongoDB command allowing for iteration over the + * results returned. It supports one by one document iteration, conversion to an + * array or can be iterated as a Node 0.10.X or higher stream + * + * **CommandCursor Cannot directly be instantiated** + * @example + * const MongoClient = require('mongodb').MongoClient; + * const test = require('assert'); + * // Connection url + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, client) { + * // Create a collection we want to drop later + * const col = client.db(dbName).collection('listCollectionsExample1'); + * // Insert a bunch of documents + * col.insert([{a:1, b:1} + * , {a:2, b:2}, {a:3, b:3} + * , {a:4, b:4}], {w:1}, function(err, result) { + * test.equal(null, err); + * // List the database collections available + * db.listCollections().toArray(function(err, items) { + * test.equal(null, err); + * client.close(); + * }); + * }); + * }); + */ + +/** + * Namespace provided by the browser. + * @external Readable + */ + +/** + * Creates a new Command Cursor instance (INTERNAL TYPE, do not instantiate directly) + * @class CommandCursor + * @extends external:Readable + * @fires CommandCursor#data + * @fires CommandCursor#end + * @fires CommandCursor#close + * @fires CommandCursor#readable + * @return {CommandCursor} an CommandCursor instance. + */ +class CommandCursor extends Cursor { + constructor(topology, ns, cmd, options) { + super(topology, ns, cmd, options); + } + + /** + * Set the ReadPreference for the cursor. + * @method + * @param {(string|ReadPreference)} readPreference The new read preference for the cursor. + * @throws {MongoError} + * @return {Cursor} + */ + setReadPreference(readPreference) { + if (this.s.state === CursorState.CLOSED || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + if (this.s.state !== CursorState.INIT) { + throw MongoError.create({ + message: 'cannot change cursor readPreference after cursor has been accessed', + driver: true + }); + } + + if (readPreference instanceof ReadPreference) { + this.options.readPreference = readPreference; + } else if (typeof readPreference === 'string') { + this.options.readPreference = new ReadPreference(readPreference); + } else { + throw new TypeError('Invalid read preference: ' + readPreference); + } + + return this; + } + + /** + * Set the batch size for the cursor. + * @method + * @param {number} value The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/find/|find command documentation}. + * @throws {MongoError} + * @return {CommandCursor} + */ + batchSize(value) { + if (this.s.state === CursorState.CLOSED || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + if (typeof value !== 'number') { + throw MongoError.create({ message: 'batchSize requires an integer', driver: true }); + } + + if (this.cmd.cursor) { + this.cmd.cursor.batchSize = value; + } + + this.setCursorBatchSize(value); + return this; + } + + /** + * Add a maxTimeMS stage to the aggregation pipeline + * @method + * @param {number} value The state maxTimeMS value. + * @return {CommandCursor} + */ + maxTimeMS(value) { + if (this.topology.lastIsMaster().minWireVersion > 2) { + this.cmd.maxTimeMS = value; + } + + return this; + } + + /** + * Return the cursor logger + * @method + * @return {Logger} return the cursor logger + * @ignore + */ + getLogger() { + return this.logger; + } +} + +// aliases +CommandCursor.prototype.get = CommandCursor.prototype.toArray; + +/** + * CommandCursor stream data event, fired for each document in the cursor. + * + * @event CommandCursor#data + * @type {object} + */ + +/** + * CommandCursor stream end event + * + * @event CommandCursor#end + * @type {null} + */ + +/** + * CommandCursor stream close event + * + * @event CommandCursor#close + * @type {null} + */ + +/** + * CommandCursor stream readable event + * + * @event CommandCursor#readable + * @type {null} + */ + +/** + * Get the next available document from the cursor, returns null if no more documents are available. + * @function CommandCursor.prototype.next + * @param {CommandCursor~resultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ + +/** + * Check if there is any document still available in the cursor + * @function CommandCursor.prototype.hasNext + * @param {CommandCursor~resultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ + +/** + * The callback format for results + * @callback CommandCursor~toArrayResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {object[]} documents All the documents the satisfy the cursor. + */ + +/** + * Returns an array of documents. The caller is responsible for making sure that there + * is enough memory to store the results. Note that the array only contain partial + * results when this cursor had been previously accessed. + * @method CommandCursor.prototype.toArray + * @param {CommandCursor~toArrayResultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ + +/** + * The callback format for results + * @callback CommandCursor~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {(object|null)} result The result object if the command was executed successfully. + */ + +/** + * Iterates over all the documents for this cursor. As with **{cursor.toArray}**, + * not all of the elements will be iterated if this cursor had been previously accessed. + * In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike + * **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements + * at any given time if batch size is specified. Otherwise, the caller is responsible + * for making sure that the entire result can fit the memory. + * @method CommandCursor.prototype.each + * @param {CommandCursor~resultCallback} callback The result callback. + * @throws {MongoError} + * @return {null} + */ + +/** + * Close the cursor, sending a KillCursor command and emitting close. + * @method CommandCursor.prototype.close + * @param {CommandCursor~resultCallback} [callback] The result callback. + * @return {Promise} returns Promise if no callback passed + */ + +/** + * Is the cursor closed + * @method CommandCursor.prototype.isClosed + * @return {boolean} + */ + +/** + * Clone the cursor + * @function CommandCursor.prototype.clone + * @return {CommandCursor} + */ + +/** + * Resets the cursor + * @function CommandCursor.prototype.rewind + * @return {CommandCursor} + */ + +/** + * The callback format for the forEach iterator method + * @callback CommandCursor~iteratorCallback + * @param {Object} doc An emitted document for the iterator + */ + +/** + * The callback error format for the forEach iterator method + * @callback CommandCursor~endCallback + * @param {MongoError} error An error instance representing the error during the execution. + */ + +/* + * Iterates over all the documents for this cursor using the iterator, callback pattern. + * @method CommandCursor.prototype.forEach + * @param {CommandCursor~iteratorCallback} iterator The iteration callback. + * @param {CommandCursor~endCallback} callback The end callback. + * @throws {MongoError} + * @return {null} + */ + +module.exports = CommandCursor; diff --git a/scripts/node_modules/mongodb/lib/constants.js b/scripts/node_modules/mongodb/lib/constants.js new file mode 100644 index 00000000..d6cc68ad --- /dev/null +++ b/scripts/node_modules/mongodb/lib/constants.js @@ -0,0 +1,10 @@ +'use strict'; + +module.exports = { + SYSTEM_NAMESPACE_COLLECTION: 'system.namespaces', + SYSTEM_INDEX_COLLECTION: 'system.indexes', + SYSTEM_PROFILE_COLLECTION: 'system.profile', + SYSTEM_USER_COLLECTION: 'system.users', + SYSTEM_COMMAND_COLLECTION: '$cmd', + SYSTEM_JS_COLLECTION: 'system.js' +}; diff --git a/scripts/node_modules/mongodb/lib/core/auth/auth_provider.js b/scripts/node_modules/mongodb/lib/core/auth/auth_provider.js new file mode 100644 index 00000000..7597b728 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/core/auth/auth_provider.js @@ -0,0 +1,158 @@ +'use strict'; + +const MongoError = require('../error').MongoError; + +/** + * Creates a new AuthProvider, which dictates how to authenticate for a given + * mechanism. + * @class + */ +class AuthProvider { + constructor(bson) { + this.bson = bson; + this.authStore = []; + } + + /** + * Authenticate + * @method + * @param {SendAuthCommand} sendAuthCommand Writes an auth command directly to a specific connection + * @param {Connection[]} connections Connections to authenticate using this authenticator + * @param {MongoCredentials} credentials Authentication credentials + * @param {authResultCallback} callback The callback to return the result from the authentication + */ + auth(sendAuthCommand, connections, credentials, callback) { + // Total connections + let count = connections.length; + + if (count === 0) { + callback(null, null); + return; + } + + // Valid connections + let numberOfValidConnections = 0; + let errorObject = null; + + const execute = connection => { + this._authenticateSingleConnection(sendAuthCommand, connection, credentials, (err, r) => { + // Adjust count + count = count - 1; + + // If we have an error + if (err) { + errorObject = new MongoError(err); + } else if (r && (r.$err || r.errmsg)) { + errorObject = new MongoError(r); + } else { + numberOfValidConnections = numberOfValidConnections + 1; + } + + // Still authenticating against other connections. + if (count !== 0) { + return; + } + + // We have authenticated all connections + if (numberOfValidConnections > 0) { + // Store the auth details + this.addCredentials(credentials); + // Return correct authentication + callback(null, true); + } else { + if (errorObject == null) { + errorObject = new MongoError(`failed to authenticate using ${credentials.mechanism}`); + } + callback(errorObject, false); + } + }); + }; + + const executeInNextTick = _connection => process.nextTick(() => execute(_connection)); + + // For each connection we need to authenticate + while (connections.length > 0) { + executeInNextTick(connections.shift()); + } + } + + /** + * Implementation of a single connection authenticating. Is meant to be overridden. + * Will error if called directly + * @ignore + */ + _authenticateSingleConnection(/*sendAuthCommand, connection, credentials, callback*/) { + throw new Error('_authenticateSingleConnection must be overridden'); + } + + /** + * Adds credentials to store only if it does not exist + * @param {MongoCredentials} credentials credentials to add to store + */ + addCredentials(credentials) { + const found = this.authStore.some(cred => cred.equals(credentials)); + + if (!found) { + this.authStore.push(credentials); + } + } + + /** + * Re authenticate pool + * @method + * @param {SendAuthCommand} sendAuthCommand Writes an auth command directly to a specific connection + * @param {Connection[]} connections Connections to authenticate using this authenticator + * @param {authResultCallback} callback The callback to return the result from the authentication + */ + reauthenticate(sendAuthCommand, connections, callback) { + const authStore = this.authStore.slice(0); + let count = authStore.length; + if (count === 0) { + return callback(null, null); + } + + for (let i = 0; i < authStore.length; i++) { + this.auth(sendAuthCommand, connections, authStore[i], function(err) { + count = count - 1; + if (count === 0) { + callback(err, null); + } + }); + } + } + + /** + * Remove credentials that have been previously stored in the auth provider + * @method + * @param {string} source Name of database we are removing authStore details about + * @return {object} + */ + logout(source) { + this.authStore = this.authStore.filter(credentials => credentials.source !== source); + } +} + +/** + * A function that writes authentication commands to a specific connection + * @callback SendAuthCommand + * @param {Connection} connection The connection to write to + * @param {Command} command A command with a toBin method that can be written to a connection + * @param {AuthWriteCallback} callback Callback called when command response is received + */ + +/** + * A callback for a specific auth command + * @callback AuthWriteCallback + * @param {Error} err If command failed, an error from the server + * @param {object} r The response from the server + */ + +/** + * This is a result from an authentication strategy + * + * @callback authResultCallback + * @param {error} error An error object. Set to null if no error present + * @param {boolean} result The result of the authentication process + */ + +module.exports = { AuthProvider }; diff --git a/scripts/node_modules/mongodb/lib/core/auth/defaultAuthProviders.js b/scripts/node_modules/mongodb/lib/core/auth/defaultAuthProviders.js new file mode 100644 index 00000000..fc5f4c28 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/core/auth/defaultAuthProviders.js @@ -0,0 +1,29 @@ +'use strict'; + +const MongoCR = require('./mongocr'); +const X509 = require('./x509'); +const Plain = require('./plain'); +const GSSAPI = require('./gssapi'); +const SSPI = require('./sspi'); +const ScramSHA1 = require('./scram').ScramSHA1; +const ScramSHA256 = require('./scram').ScramSHA256; + +/** + * Returns the default authentication providers. + * + * @param {BSON} bson Bson definition + * @returns {Object} a mapping of auth names to auth types + */ +function defaultAuthProviders(bson) { + return { + mongocr: new MongoCR(bson), + x509: new X509(bson), + plain: new Plain(bson), + gssapi: new GSSAPI(bson), + sspi: new SSPI(bson), + 'scram-sha-1': new ScramSHA1(bson), + 'scram-sha-256': new ScramSHA256(bson) + }; +} + +module.exports = { defaultAuthProviders }; diff --git a/scripts/node_modules/mongodb/lib/core/auth/gssapi.js b/scripts/node_modules/mongodb/lib/core/auth/gssapi.js new file mode 100644 index 00000000..936fb65a --- /dev/null +++ b/scripts/node_modules/mongodb/lib/core/auth/gssapi.js @@ -0,0 +1,241 @@ +'use strict'; + +const AuthProvider = require('./auth_provider').AuthProvider; +const retrieveKerberos = require('../utils').retrieveKerberos; +let kerberos; + +/** + * Creates a new GSSAPI authentication mechanism + * @class + * @extends AuthProvider + */ +class GSSAPI extends AuthProvider { + /** + * Implementation of authentication for a single connection + * @override + */ + _authenticateSingleConnection(sendAuthCommand, connection, credentials, callback) { + const source = credentials.source; + const username = credentials.username; + const password = credentials.password; + const mechanismProperties = credentials.mechanismProperties; + const gssapiServiceName = + mechanismProperties['gssapiservicename'] || + mechanismProperties['gssapiServiceName'] || + 'mongodb'; + + GSSAPIInitialize( + this, + kerberos.processes.MongoAuthProcess, + source, + username, + password, + source, + gssapiServiceName, + sendAuthCommand, + connection, + mechanismProperties, + callback + ); + } + + /** + * Authenticate + * @override + * @method + */ + auth(sendAuthCommand, connections, credentials, callback) { + if (kerberos == null) { + try { + kerberos = retrieveKerberos(); + } catch (e) { + return callback(e, null); + } + } + + super.auth(sendAuthCommand, connections, credentials, callback); + } +} + +// +// Initialize step +var GSSAPIInitialize = function( + self, + MongoAuthProcess, + db, + username, + password, + authdb, + gssapiServiceName, + sendAuthCommand, + connection, + options, + callback +) { + // Create authenticator + var mongo_auth_process = new MongoAuthProcess( + connection.host, + connection.port, + gssapiServiceName, + options + ); + + // Perform initialization + mongo_auth_process.init(username, password, function(err) { + if (err) return callback(err, false); + + // Perform the first step + mongo_auth_process.transition('', function(err, payload) { + if (err) return callback(err, false); + + // Call the next db step + MongoDBGSSAPIFirstStep( + self, + mongo_auth_process, + payload, + db, + username, + password, + authdb, + sendAuthCommand, + connection, + callback + ); + }); + }); +}; + +// +// Perform first step against mongodb +var MongoDBGSSAPIFirstStep = function( + self, + mongo_auth_process, + payload, + db, + username, + password, + authdb, + sendAuthCommand, + connection, + callback +) { + // Build the sasl start command + var command = { + saslStart: 1, + mechanism: 'GSSAPI', + payload: payload, + autoAuthorize: 1 + }; + + // Write the commmand on the connection + sendAuthCommand(connection, '$external.$cmd', command, (err, doc) => { + if (err) return callback(err, false); + // Execute mongodb transition + mongo_auth_process.transition(doc.payload, function(err, payload) { + if (err) return callback(err, false); + + // MongoDB API Second Step + MongoDBGSSAPISecondStep( + self, + mongo_auth_process, + payload, + doc, + db, + username, + password, + authdb, + sendAuthCommand, + connection, + callback + ); + }); + }); +}; + +// +// Perform first step against mongodb +var MongoDBGSSAPISecondStep = function( + self, + mongo_auth_process, + payload, + doc, + db, + username, + password, + authdb, + sendAuthCommand, + connection, + callback +) { + // Build Authentication command to send to MongoDB + var command = { + saslContinue: 1, + conversationId: doc.conversationId, + payload: payload + }; + + // Execute the command + // Write the commmand on the connection + sendAuthCommand(connection, '$external.$cmd', command, (err, doc) => { + if (err) return callback(err, false); + // Call next transition for kerberos + mongo_auth_process.transition(doc.payload, function(err, payload) { + if (err) return callback(err, false); + + // Call the last and third step + MongoDBGSSAPIThirdStep( + self, + mongo_auth_process, + payload, + doc, + db, + username, + password, + authdb, + sendAuthCommand, + connection, + callback + ); + }); + }); +}; + +var MongoDBGSSAPIThirdStep = function( + self, + mongo_auth_process, + payload, + doc, + db, + username, + password, + authdb, + sendAuthCommand, + connection, + callback +) { + // Build final command + var command = { + saslContinue: 1, + conversationId: doc.conversationId, + payload: payload + }; + + // Execute the command + sendAuthCommand(connection, '$external.$cmd', command, (err, r) => { + if (err) return callback(err, false); + mongo_auth_process.transition(null, function(err) { + if (err) return callback(err, null); + callback(null, r); + }); + }); +}; + +/** + * This is a result from a authentication strategy + * + * @callback authResultCallback + * @param {error} error An error object. Set to null if no error present + * @param {boolean} result The result of the authentication process + */ + +module.exports = GSSAPI; diff --git a/scripts/node_modules/mongodb/lib/core/auth/mongo_credentials.js b/scripts/node_modules/mongodb/lib/core/auth/mongo_credentials.js new file mode 100644 index 00000000..13c00b14 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/core/auth/mongo_credentials.js @@ -0,0 +1,81 @@ +'use strict'; + +// Resolves the default auth mechanism according to +// https://github.com/mongodb/specifications/blob/master/source/auth/auth.rst +function getDefaultAuthMechanism(ismaster) { + if (ismaster) { + // If ismaster contains saslSupportedMechs, use scram-sha-256 + // if it is available, else scram-sha-1 + if (Array.isArray(ismaster.saslSupportedMechs)) { + return ismaster.saslSupportedMechs.indexOf('SCRAM-SHA-256') >= 0 + ? 'scram-sha-256' + : 'scram-sha-1'; + } + + // Fallback to legacy selection method. If wire version >= 3, use scram-sha-1 + if (ismaster.maxWireVersion >= 3) { + return 'scram-sha-1'; + } + } + + // Default for wireprotocol < 3 + return 'mongocr'; +} + +/** + * A representation of the credentials used by MongoDB + * @class + * @property {string} mechanism The method used to authenticate + * @property {string} [username] The username used for authentication + * @property {string} [password] The password used for authentication + * @property {string} [source] The database that the user should authenticate against + * @property {object} [mechanismProperties] Special properties used by some types of auth mechanisms + */ +class MongoCredentials { + /** + * Creates a new MongoCredentials object + * @param {object} [options] + * @param {string} [options.username] The username used for authentication + * @param {string} [options.password] The password used for authentication + * @param {string} [options.source] The database that the user should authenticate against + * @param {string} [options.mechanism] The method used to authenticate + * @param {object} [options.mechanismProperties] Special properties used by some types of auth mechanisms + */ + constructor(options) { + options = options || {}; + this.username = options.username; + this.password = options.password; + this.source = options.source || options.db; + this.mechanism = options.mechanism || 'default'; + this.mechanismProperties = options.mechanismProperties; + } + + /** + * Determines if two MongoCredentials objects are equivalent + * @param {MongoCredentials} other another MongoCredentials object + * @returns {boolean} true if the two objects are equal. + */ + equals(other) { + return ( + this.mechanism === other.mechanism && + this.username === other.username && + this.password === other.password && + this.source === other.source + ); + } + + /** + * If the authentication mechanism is set to "default", resolves the authMechanism + * based on the server version and server supported sasl mechanisms. + * + * @param {Object} [ismaster] An ismaster response from the server + */ + resolveAuthMechanism(ismaster) { + // If the mechanism is not "default", then it does not need to be resolved + if (this.mechanism.toLowerCase() === 'default') { + this.mechanism = getDefaultAuthMechanism(ismaster); + } + } +} + +module.exports = { MongoCredentials }; diff --git a/scripts/node_modules/mongodb/lib/core/auth/mongocr.js b/scripts/node_modules/mongodb/lib/core/auth/mongocr.js new file mode 100644 index 00000000..be8fcb6b --- /dev/null +++ b/scripts/node_modules/mongodb/lib/core/auth/mongocr.js @@ -0,0 +1,51 @@ +'use strict'; + +const crypto = require('crypto'); +const AuthProvider = require('./auth_provider').AuthProvider; + +/** + * Creates a new MongoCR authentication mechanism + * + * @extends AuthProvider + */ +class MongoCR extends AuthProvider { + /** + * Implementation of authentication for a single connection + * @override + */ + _authenticateSingleConnection(sendAuthCommand, connection, credentials, callback) { + const username = credentials.username; + const password = credentials.password; + const source = credentials.source; + + sendAuthCommand(connection, `${source}.$cmd`, { getnonce: 1 }, (err, r) => { + let nonce = null; + let key = null; + + // Get nonce + if (err == null) { + nonce = r.nonce; + // Use node md5 generator + let md5 = crypto.createHash('md5'); + // Generate keys used for authentication + md5.update(username + ':mongo:' + password, 'utf8'); + const hash_password = md5.digest('hex'); + // Final key + md5 = crypto.createHash('md5'); + md5.update(nonce + username + hash_password, 'utf8'); + key = md5.digest('hex'); + } + + const authenticateCommand = { + authenticate: 1, + user: username, + nonce, + key + }; + + sendAuthCommand(connection, `${source}.$cmd`, authenticateCommand, callback); + }); + } +} + +module.exports = MongoCR; diff --git a/scripts/node_modules/mongodb/lib/core/auth/plain.js b/scripts/node_modules/mongodb/lib/core/auth/plain.js new file mode 100644 index 00000000..240de758 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/core/auth/plain.js @@ -0,0 +1,35 @@ +'use strict'; + +const retrieveBSON = require('../connection/utils').retrieveBSON; +const AuthProvider = require('./auth_provider').AuthProvider; + +// TODO: can we get the Binary type from this.bson instead? +const BSON = retrieveBSON(); +const Binary = BSON.Binary; + +/** + * Creates a new Plain authentication mechanism + * + * @extends AuthProvider + */ +class Plain extends AuthProvider { + /** + * Implementation of authentication for a single connection + * @override + */ + _authenticateSingleConnection(sendAuthCommand, connection, credentials, callback) { + const username = credentials.username; + const password = credentials.password; + const payload = new Binary(`\x00${username}\x00${password}`); + const command = { + saslStart: 1, + mechanism: 'PLAIN', + payload: payload, + autoAuthorize: 1 + }; + + sendAuthCommand(connection, '$external.$cmd', command, callback); + } +} + +module.exports = Plain; diff --git a/scripts/node_modules/mongodb/lib/core/auth/scram.js b/scripts/node_modules/mongodb/lib/core/auth/scram.js new file mode 100644 index 00000000..ac8853eb --- /dev/null +++ b/scripts/node_modules/mongodb/lib/core/auth/scram.js @@ -0,0 +1,293 @@ +'use strict'; + +const crypto = require('crypto'); +const Buffer = require('safe-buffer').Buffer; +const retrieveBSON = require('../connection/utils').retrieveBSON; +const MongoError = require('../error').MongoError; +const AuthProvider = require('./auth_provider').AuthProvider; + +const BSON = retrieveBSON(); +const Binary = BSON.Binary; + +let saslprep; +try { + saslprep = require('saslprep'); +} catch (e) { + // don't do anything; +} + +var parsePayload = function(payload) { + var dict = {}; + var parts = payload.split(','); + + for (var i = 0; i < parts.length; i++) { + var valueParts = parts[i].split('='); + dict[valueParts[0]] = valueParts[1]; + } + + return dict; +}; + +var passwordDigest = function(username, password) { + if (typeof username !== 'string') throw new MongoError('username must be a string'); + if (typeof password !== 'string') throw new MongoError('password must be a string'); + if (password.length === 0) throw new MongoError('password cannot be empty'); + // Use node md5 generator + var md5 = crypto.createHash('md5'); + // Generate keys used for authentication + md5.update(username + ':mongo:' + password, 'utf8'); + return md5.digest('hex'); +}; + +// XOR two buffers +function xor(a, b) { + if (!Buffer.isBuffer(a)) a = Buffer.from(a); + if (!Buffer.isBuffer(b)) b = Buffer.from(b); + const length = Math.max(a.length, b.length); + const res = []; + + for (let i = 0; i < length; i += 1) { + res.push(a[i] ^ b[i]); + } + + return Buffer.from(res).toString('base64'); +} + +function H(method, text) { + return crypto + .createHash(method) + .update(text) + .digest(); +} + +function HMAC(method, key, text) { + return crypto + .createHmac(method, key) + .update(text) + .digest(); +} + +var _hiCache = {}; +var _hiCacheCount = 0; +var _hiCachePurge = function() { + _hiCache = {}; + _hiCacheCount = 0; +}; + +const hiLengthMap = { + sha256: 32, + sha1: 20 +}; + +function HI(data, salt, iterations, cryptoMethod) { + // omit the work if already generated + const key = [data, salt.toString('base64'), iterations].join('_'); + if (_hiCache[key] !== undefined) { + return _hiCache[key]; + } + + // generate the salt + const saltedData = crypto.pbkdf2Sync( + data, + salt, + iterations, + hiLengthMap[cryptoMethod], + cryptoMethod + ); + + // cache a copy to speed up the next lookup, but prevent unbounded cache growth + if (_hiCacheCount >= 200) { + _hiCachePurge(); + } + + _hiCache[key] = saltedData; + _hiCacheCount += 1; + return saltedData; +} + +/** + * Creates a new ScramSHA authentication mechanism + * @class + * @extends AuthProvider + */ +class ScramSHA extends AuthProvider { + constructor(bson, cryptoMethod) { + super(bson); + this.cryptoMethod = cryptoMethod || 'sha1'; + } + + static _getError(err, r) { + if (err) { + return err; + } + + if (r.$err || r.errmsg) { + return new MongoError(r); + } + } + + /** + * @ignore + */ + _executeScram(sendAuthCommand, connection, credentials, nonce, callback) { + let username = credentials.username; + const password = credentials.password; + const db = credentials.source; + + const cryptoMethod = this.cryptoMethod; + let mechanism = 'SCRAM-SHA-1'; + let processedPassword; + + if (cryptoMethod === 'sha256') { + mechanism = 'SCRAM-SHA-256'; + + processedPassword = saslprep ? saslprep(password) : password; + } else { + try { + processedPassword = passwordDigest(username, password); + } catch (e) { + return callback(e); + } + } + + // Clean up the user + username = username.replace('=', '=3D').replace(',', '=2C'); + + // NOTE: This is done b/c Javascript uses UTF-16, but the server is hashing in UTF-8. + // Since the username is not sasl-prep-d, we need to do this here. + const firstBare = Buffer.concat([ + Buffer.from('n=', 'utf8'), + Buffer.from(username, 'utf8'), + Buffer.from(',r=', 'utf8'), + Buffer.from(nonce, 'utf8') + ]); + + // Build command structure + const saslStartCmd = { + saslStart: 1, + mechanism, + payload: new Binary(Buffer.concat([Buffer.from('n,,', 'utf8'), firstBare])), + autoAuthorize: 1 + }; + + // Write the commmand on the connection + sendAuthCommand(connection, `${db}.$cmd`, saslStartCmd, (err, r) => { + let tmpError = ScramSHA._getError(err, r); + if (tmpError) { + return callback(tmpError, null); + } + + const payload = Buffer.isBuffer(r.payload) ? new Binary(r.payload) : r.payload; + const dict = parsePayload(payload.value()); + const iterations = parseInt(dict.i, 10); + const salt = dict.s; + const rnonce = dict.r; + + // Set up start of proof + const withoutProof = `c=biws,r=${rnonce}`; + const saltedPassword = HI( + processedPassword, + Buffer.from(salt, 'base64'), + iterations, + cryptoMethod + ); + + if (iterations && iterations < 4096) { + const error = new MongoError(`Server returned an invalid iteration count ${iterations}`); + return callback(error, false); + } + + const clientKey = HMAC(cryptoMethod, saltedPassword, 'Client Key'); + const storedKey = H(cryptoMethod, clientKey); + const authMessage = [firstBare, payload.value().toString('base64'), withoutProof].join(','); + + const clientSignature = HMAC(cryptoMethod, storedKey, authMessage); + const clientProof = `p=${xor(clientKey, clientSignature)}`; + const clientFinal = [withoutProof, clientProof].join(','); + const saslContinueCmd = { + saslContinue: 1, + conversationId: r.conversationId, + payload: new Binary(Buffer.from(clientFinal)) + }; + + sendAuthCommand(connection, `${db}.$cmd`, saslContinueCmd, (err, r) => { + if (!r || r.done !== false) { + return callback(err, r); + } + + const retrySaslContinueCmd = { + saslContinue: 1, + conversationId: r.conversationId, + payload: Buffer.alloc(0) + }; + + sendAuthCommand(connection, `${db}.$cmd`, retrySaslContinueCmd, callback); + }); + }); + } + + /** + * Implementation of authentication for a single connection + * @override + */ + _authenticateSingleConnection(sendAuthCommand, connection, credentials, callback) { + // Create a random nonce + crypto.randomBytes(24, (err, buff) => { + if (err) { + return callback(err, null); + } + + return this._executeScram( + sendAuthCommand, + connection, + credentials, + buff.toString('base64'), + callback + ); + }); + } + + /** + * Authenticate + * @override + * @method + */ + auth(sendAuthCommand, connections, credentials, callback) { + this._checkSaslprep(); + super.auth(sendAuthCommand, connections, credentials, callback); + } + + _checkSaslprep() { + const cryptoMethod = this.cryptoMethod; + + if (cryptoMethod === 'sha256') { + if (!saslprep) { + console.warn('Warning: no saslprep library specified. Passwords will not be sanitized'); + } + } + } +} + +/** + * Creates a new ScramSHA1 authentication mechanism + * @class + * @extends ScramSHA + */ +class ScramSHA1 extends ScramSHA { + constructor(bson) { + super(bson, 'sha1'); + } +} + +/** + * Creates a new ScramSHA256 authentication mechanism + * @class + * @extends ScramSHA + */ +class ScramSHA256 extends ScramSHA { + constructor(bson) { + super(bson, 'sha256'); + } +} + +module.exports = { ScramSHA1, ScramSHA256 }; diff --git a/scripts/node_modules/mongodb/lib/core/auth/sspi.js b/scripts/node_modules/mongodb/lib/core/auth/sspi.js new file mode 100644 index 00000000..8a3f5448 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/core/auth/sspi.js @@ -0,0 +1,131 @@ +'use strict'; + +const AuthProvider = require('./auth_provider').AuthProvider; +const retrieveKerberos = require('../utils').retrieveKerberos; +let kerberos; + +/** + * Creates a new SSPI authentication mechanism + * @class + * @extends AuthProvider + */ +class SSPI extends AuthProvider { + /** + * Implementation of authentication for a single connection + * @override + */ + _authenticateSingleConnection(sendAuthCommand, connection, credentials, callback) { + // TODO: Destructure this + const username = credentials.username; + const password = credentials.password; + const mechanismProperties = credentials.mechanismProperties; + const gssapiServiceName = + mechanismProperties['gssapiservicename'] || + mechanismProperties['gssapiServiceName'] || + 'mongodb'; + + SSIPAuthenticate( + this, + kerberos.processes.MongoAuthProcess, + username, + password, + gssapiServiceName, + sendAuthCommand, + connection, + mechanismProperties, + callback + ); + } + + /** + * Authenticate + * @override + * @method + */ + auth(sendAuthCommand, connections, credentials, callback) { + if (kerberos == null) { + try { + kerberos = retrieveKerberos(); + } catch (e) { + return callback(e, null); + } + } + + super.auth(sendAuthCommand, connections, credentials, callback); + } +} + +function SSIPAuthenticate( + self, + MongoAuthProcess, + username, + password, + gssapiServiceName, + sendAuthCommand, + connection, + options, + callback +) { + const authProcess = new MongoAuthProcess( + connection.host, + connection.port, + gssapiServiceName, + options + ); + + function authCommand(command, authCb) { + sendAuthCommand(connection, '$external.$cmd', command, authCb); + } + + authProcess.init(username, password, err => { + if (err) return callback(err, false); + + authProcess.transition('', (err, payload) => { + if (err) return callback(err, false); + + const command = { + saslStart: 1, + mechanism: 'GSSAPI', + payload, + autoAuthorize: 1 + }; + + authCommand(command, (err, doc) => { + if (err) return callback(err, false); + + authProcess.transition(doc.payload, (err, payload) => { + if (err) return callback(err, false); + const command = { + saslContinue: 1, + conversationId: doc.conversationId, + payload + }; + + authCommand(command, (err, doc) => { + if (err) return callback(err, false); + + authProcess.transition(doc.payload, (err, payload) => { + if (err) return callback(err, false); + const command = { + saslContinue: 1, + conversationId: doc.conversationId, + payload + }; + + authCommand(command, (err, response) => { + if (err) return callback(err, false); + + authProcess.transition(null, err => { + if (err) return callback(err, null); + callback(null, response); + }); + }); + }); + }); + }); + }); + }); + }); +} + +module.exports = SSPI; diff --git a/scripts/node_modules/mongodb/lib/core/auth/x509.js b/scripts/node_modules/mongodb/lib/core/auth/x509.js new file mode 100644 index 00000000..10d5b588 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/core/auth/x509.js @@ -0,0 +1,26 @@ +'use strict'; + +const AuthProvider = require('./auth_provider').AuthProvider; + +/** + * Creates a new X509 authentication mechanism + * @class + * @extends AuthProvider + */ +class X509 extends AuthProvider { + /** + * Implementation of authentication for a single connection + * @override + */ + _authenticateSingleConnection(sendAuthCommand, connection, credentials, callback) { + const username = credentials.username; + const command = { authenticate: 1, mechanism: 'MONGODB-X509' }; + if (username) { + command.user = username; + } + + sendAuthCommand(connection, '$external.$cmd', command, callback); + } +} + +module.exports = X509; diff --git a/scripts/node_modules/mongodb/lib/core/connection/apm.js b/scripts/node_modules/mongodb/lib/core/connection/apm.js new file mode 100644 index 00000000..defc59a1 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/core/connection/apm.js @@ -0,0 +1,236 @@ +'use strict'; +const Msg = require('../connection/msg').Msg; +const KillCursor = require('../connection/commands').KillCursor; +const GetMore = require('../connection/commands').GetMore; +const calculateDurationInMs = require('../utils').calculateDurationInMs; + +/** Commands that we want to redact because of the sensitive nature of their contents */ +const SENSITIVE_COMMANDS = new Set([ + 'authenticate', + 'saslStart', + 'saslContinue', + 'getnonce', + 'createUser', + 'updateUser', + 'copydbgetnonce', + 'copydbsaslstart', + 'copydb' +]); + +// helper methods +const extractCommandName = commandDoc => Object.keys(commandDoc)[0]; +const namespace = command => command.ns; +const databaseName = command => command.ns.split('.')[0]; +const collectionName = command => command.ns.split('.')[1]; +const generateConnectionId = pool => `${pool.options.host}:${pool.options.port}`; +const maybeRedact = (commandName, result) => (SENSITIVE_COMMANDS.has(commandName) ? {} : result); + +const LEGACY_FIND_QUERY_MAP = { + $query: 'filter', + $orderby: 'sort', + $hint: 'hint', + $comment: 'comment', + $maxScan: 'maxScan', + $max: 'max', + $min: 'min', + $returnKey: 'returnKey', + $showDiskLoc: 'showRecordId', + $maxTimeMS: 'maxTimeMS', + $snapshot: 'snapshot' +}; + +const LEGACY_FIND_OPTIONS_MAP = { + numberToSkip: 'skip', + numberToReturn: 'batchSize', + returnFieldsSelector: 'projection' +}; + +const OP_QUERY_KEYS = [ + 'tailable', + 'oplogReplay', + 'noCursorTimeout', + 'awaitData', + 'partial', + 'exhaust' +]; + +/** + * Extract the actual command from the query, possibly upconverting if it's a legacy + * format + * + * @param {Object} command the command + */ +const extractCommand = command => { + if (command instanceof GetMore) { + return { + getMore: command.cursorId, + collection: collectionName(command), + batchSize: command.numberToReturn + }; + } + + if (command instanceof KillCursor) { + return { + killCursors: collectionName(command), + cursors: command.cursorIds + }; + } + + if (command instanceof Msg) { + return command.command; + } + + if (command.query && command.query.$query) { + let result; + if (command.ns === 'admin.$cmd') { + // upconvert legacy command + result = Object.assign({}, command.query.$query); + } else { + // upconvert legacy find command + result = { find: collectionName(command) }; + Object.keys(LEGACY_FIND_QUERY_MAP).forEach(key => { + if (typeof command.query[key] !== 'undefined') + result[LEGACY_FIND_QUERY_MAP[key]] = command.query[key]; + }); + } + + Object.keys(LEGACY_FIND_OPTIONS_MAP).forEach(key => { + if (typeof command[key] !== 'undefined') result[LEGACY_FIND_OPTIONS_MAP[key]] = command[key]; + }); + + OP_QUERY_KEYS.forEach(key => { + if (command[key]) result[key] = command[key]; + }); + + if (typeof command.pre32Limit !== 'undefined') { + result.limit = command.pre32Limit; + } + + if (command.query.$explain) { + return { explain: result }; + } + + return result; + } + + return command.query ? command.query : command; +}; + +const extractReply = (command, reply) => { + if (command instanceof GetMore) { + return { + ok: 1, + cursor: { + id: reply.message.cursorId, + ns: namespace(command), + nextBatch: reply.message.documents + } + }; + } + + if (command instanceof KillCursor) { + return { + ok: 1, + cursorsUnknown: command.cursorIds + }; + } + + // is this a legacy find command? + if (command.query && typeof command.query.$query !== 'undefined') { + return { + ok: 1, + cursor: { + id: reply.message.cursorId, + ns: namespace(command), + firstBatch: reply.message.documents + } + }; + } + + // in the event of a `noResponse` command, just return + if (reply === null) return reply; + + return reply.result; +}; + +/** An event indicating the start of a given command */ +class CommandStartedEvent { + /** + * Create a started event + * + * @param {Pool} pool the pool that originated the command + * @param {Object} command the command + */ + constructor(pool, command) { + const cmd = extractCommand(command); + const commandName = extractCommandName(cmd); + + // NOTE: remove in major revision, this is not spec behavior + if (SENSITIVE_COMMANDS.has(commandName)) { + this.commandObj = {}; + this.commandObj[commandName] = true; + } + + Object.assign(this, { + command: cmd, + databaseName: databaseName(command), + commandName, + requestId: command.requestId, + connectionId: generateConnectionId(pool) + }); + } +} + +/** An event indicating the success of a given command */ +class CommandSucceededEvent { + /** + * Create a succeeded event + * + * @param {Pool} pool the pool that originated the command + * @param {Object} command the command + * @param {Object} reply the reply for this command from the server + * @param {Array} started a high resolution tuple timestamp of when the command was first sent, to calculate duration + */ + constructor(pool, command, reply, started) { + const cmd = extractCommand(command); + const commandName = extractCommandName(cmd); + + Object.assign(this, { + duration: calculateDurationInMs(started), + commandName, + reply: maybeRedact(commandName, extractReply(command, reply)), + requestId: command.requestId, + connectionId: generateConnectionId(pool) + }); + } +} + +/** An event indicating the failure of a given command */ +class CommandFailedEvent { + /** + * Create a failure event + * + * @param {Pool} pool the pool that originated the command + * @param {Object} command the command + * @param {MongoError|Object} error the generated error or a server error response + * @param {Array} started a high resolution tuple timestamp of when the command was first sent, to calculate duration + */ + constructor(pool, command, error, started) { + const cmd = extractCommand(command); + const commandName = extractCommandName(cmd); + + Object.assign(this, { + duration: calculateDurationInMs(started), + commandName, + failure: maybeRedact(commandName, error), + requestId: command.requestId, + connectionId: generateConnectionId(pool) + }); + } +} + +module.exports = { + CommandStartedEvent, + CommandSucceededEvent, + CommandFailedEvent +}; diff --git a/scripts/node_modules/mongodb/lib/core/connection/command_result.js b/scripts/node_modules/mongodb/lib/core/connection/command_result.js new file mode 100644 index 00000000..762aa3f1 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/core/connection/command_result.js @@ -0,0 +1,36 @@ +'use strict'; + +/** + * Creates a new CommandResult instance + * @class + * @param {object} result CommandResult object + * @param {Connection} connection A connection instance associated with this result + * @return {CommandResult} A cursor instance + */ +var CommandResult = function(result, connection, message) { + this.result = result; + this.connection = connection; + this.message = message; +}; + +/** + * Convert CommandResult to JSON + * @method + * @return {object} + */ +CommandResult.prototype.toJSON = function() { + let result = Object.assign({}, this, this.result); + delete result.message; + return result; +}; + +/** + * Convert CommandResult to String representation + * @method + * @return {string} + */ +CommandResult.prototype.toString = function() { + return JSON.stringify(this.toJSON()); +}; + +module.exports = CommandResult; diff --git a/scripts/node_modules/mongodb/lib/core/connection/commands.js b/scripts/node_modules/mongodb/lib/core/connection/commands.js new file mode 100644 index 00000000..b24ff848 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/core/connection/commands.js @@ -0,0 +1,507 @@ +'use strict'; + +var retrieveBSON = require('./utils').retrieveBSON; +var BSON = retrieveBSON(); +var Long = BSON.Long; +const Buffer = require('safe-buffer').Buffer; + +// Incrementing request id +var _requestId = 0; + +// Wire command operation ids +var opcodes = require('../wireprotocol/shared').opcodes; + +// Query flags +var OPTS_TAILABLE_CURSOR = 2; +var OPTS_SLAVE = 4; +var OPTS_OPLOG_REPLAY = 8; +var OPTS_NO_CURSOR_TIMEOUT = 16; +var OPTS_AWAIT_DATA = 32; +var OPTS_EXHAUST = 64; +var OPTS_PARTIAL = 128; + +// Response flags +var CURSOR_NOT_FOUND = 1; +var QUERY_FAILURE = 2; +var SHARD_CONFIG_STALE = 4; +var AWAIT_CAPABLE = 8; + +/************************************************************** + * QUERY + **************************************************************/ +var Query = function(bson, ns, query, options) { + var self = this; + // Basic options needed to be passed in + if (ns == null) throw new Error('ns must be specified for query'); + if (query == null) throw new Error('query must be specified for query'); + + // Validate that we are not passing 0x00 in the collection name + if (ns.indexOf('\x00') !== -1) { + throw new Error('namespace cannot contain a null character'); + } + + // Basic options + this.bson = bson; + this.ns = ns; + this.query = query; + + // Additional options + this.numberToSkip = options.numberToSkip || 0; + this.numberToReturn = options.numberToReturn || 0; + this.returnFieldSelector = options.returnFieldSelector || null; + this.requestId = Query.getRequestId(); + + // special case for pre-3.2 find commands, delete ASAP + this.pre32Limit = options.pre32Limit; + + // Serialization option + this.serializeFunctions = + typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + this.ignoreUndefined = + typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : false; + this.maxBsonSize = options.maxBsonSize || 1024 * 1024 * 16; + this.checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : true; + this.batchSize = self.numberToReturn; + + // Flags + this.tailable = false; + this.slaveOk = typeof options.slaveOk === 'boolean' ? options.slaveOk : false; + this.oplogReplay = false; + this.noCursorTimeout = false; + this.awaitData = false; + this.exhaust = false; + this.partial = false; +}; + +// +// Assign a new request Id +Query.prototype.incRequestId = function() { + this.requestId = _requestId++; +}; + +// +// Assign a new request Id +Query.nextRequestId = function() { + return _requestId + 1; +}; + +// +// Uses a single allocated buffer for the process, avoiding multiple memory allocations +Query.prototype.toBin = function() { + var self = this; + var buffers = []; + var projection = null; + + // Set up the flags + var flags = 0; + if (this.tailable) { + flags |= OPTS_TAILABLE_CURSOR; + } + + if (this.slaveOk) { + flags |= OPTS_SLAVE; + } + + if (this.oplogReplay) { + flags |= OPTS_OPLOG_REPLAY; + } + + if (this.noCursorTimeout) { + flags |= OPTS_NO_CURSOR_TIMEOUT; + } + + if (this.awaitData) { + flags |= OPTS_AWAIT_DATA; + } + + if (this.exhaust) { + flags |= OPTS_EXHAUST; + } + + if (this.partial) { + flags |= OPTS_PARTIAL; + } + + // If batchSize is different to self.numberToReturn + if (self.batchSize !== self.numberToReturn) self.numberToReturn = self.batchSize; + + // Allocate write protocol header buffer + var header = Buffer.alloc( + 4 * 4 + // Header + 4 + // Flags + Buffer.byteLength(self.ns) + + 1 + // namespace + 4 + // numberToSkip + 4 // numberToReturn + ); + + // Add header to buffers + buffers.push(header); + + // Serialize the query + var query = self.bson.serialize(this.query, { + checkKeys: this.checkKeys, + serializeFunctions: this.serializeFunctions, + ignoreUndefined: this.ignoreUndefined + }); + + // Add query document + buffers.push(query); + + if (self.returnFieldSelector && Object.keys(self.returnFieldSelector).length > 0) { + // Serialize the projection document + projection = self.bson.serialize(this.returnFieldSelector, { + checkKeys: this.checkKeys, + serializeFunctions: this.serializeFunctions, + ignoreUndefined: this.ignoreUndefined + }); + // Add projection document + buffers.push(projection); + } + + // Total message size + var totalLength = header.length + query.length + (projection ? projection.length : 0); + + // Set up the index + var index = 4; + + // Write total document length + header[3] = (totalLength >> 24) & 0xff; + header[2] = (totalLength >> 16) & 0xff; + header[1] = (totalLength >> 8) & 0xff; + header[0] = totalLength & 0xff; + + // Write header information requestId + header[index + 3] = (this.requestId >> 24) & 0xff; + header[index + 2] = (this.requestId >> 16) & 0xff; + header[index + 1] = (this.requestId >> 8) & 0xff; + header[index] = this.requestId & 0xff; + index = index + 4; + + // Write header information responseTo + header[index + 3] = (0 >> 24) & 0xff; + header[index + 2] = (0 >> 16) & 0xff; + header[index + 1] = (0 >> 8) & 0xff; + header[index] = 0 & 0xff; + index = index + 4; + + // Write header information OP_QUERY + header[index + 3] = (opcodes.OP_QUERY >> 24) & 0xff; + header[index + 2] = (opcodes.OP_QUERY >> 16) & 0xff; + header[index + 1] = (opcodes.OP_QUERY >> 8) & 0xff; + header[index] = opcodes.OP_QUERY & 0xff; + index = index + 4; + + // Write header information flags + header[index + 3] = (flags >> 24) & 0xff; + header[index + 2] = (flags >> 16) & 0xff; + header[index + 1] = (flags >> 8) & 0xff; + header[index] = flags & 0xff; + index = index + 4; + + // Write collection name + index = index + header.write(this.ns, index, 'utf8') + 1; + header[index - 1] = 0; + + // Write header information flags numberToSkip + header[index + 3] = (this.numberToSkip >> 24) & 0xff; + header[index + 2] = (this.numberToSkip >> 16) & 0xff; + header[index + 1] = (this.numberToSkip >> 8) & 0xff; + header[index] = this.numberToSkip & 0xff; + index = index + 4; + + // Write header information flags numberToReturn + header[index + 3] = (this.numberToReturn >> 24) & 0xff; + header[index + 2] = (this.numberToReturn >> 16) & 0xff; + header[index + 1] = (this.numberToReturn >> 8) & 0xff; + header[index] = this.numberToReturn & 0xff; + index = index + 4; + + // Return the buffers + return buffers; +}; + +Query.getRequestId = function() { + return ++_requestId; +}; + +/************************************************************** + * GETMORE + **************************************************************/ +var GetMore = function(bson, ns, cursorId, opts) { + opts = opts || {}; + this.numberToReturn = opts.numberToReturn || 0; + this.requestId = _requestId++; + this.bson = bson; + this.ns = ns; + this.cursorId = cursorId; +}; + +// +// Uses a single allocated buffer for the process, avoiding multiple memory allocations +GetMore.prototype.toBin = function() { + var length = 4 + Buffer.byteLength(this.ns) + 1 + 4 + 8 + 4 * 4; + // Create command buffer + var index = 0; + // Allocate buffer + var _buffer = Buffer.alloc(length); + + // Write header information + // index = write32bit(index, _buffer, length); + _buffer[index + 3] = (length >> 24) & 0xff; + _buffer[index + 2] = (length >> 16) & 0xff; + _buffer[index + 1] = (length >> 8) & 0xff; + _buffer[index] = length & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, requestId); + _buffer[index + 3] = (this.requestId >> 24) & 0xff; + _buffer[index + 2] = (this.requestId >> 16) & 0xff; + _buffer[index + 1] = (this.requestId >> 8) & 0xff; + _buffer[index] = this.requestId & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, 0); + _buffer[index + 3] = (0 >> 24) & 0xff; + _buffer[index + 2] = (0 >> 16) & 0xff; + _buffer[index + 1] = (0 >> 8) & 0xff; + _buffer[index] = 0 & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, OP_GETMORE); + _buffer[index + 3] = (opcodes.OP_GETMORE >> 24) & 0xff; + _buffer[index + 2] = (opcodes.OP_GETMORE >> 16) & 0xff; + _buffer[index + 1] = (opcodes.OP_GETMORE >> 8) & 0xff; + _buffer[index] = opcodes.OP_GETMORE & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, 0); + _buffer[index + 3] = (0 >> 24) & 0xff; + _buffer[index + 2] = (0 >> 16) & 0xff; + _buffer[index + 1] = (0 >> 8) & 0xff; + _buffer[index] = 0 & 0xff; + index = index + 4; + + // Write collection name + index = index + _buffer.write(this.ns, index, 'utf8') + 1; + _buffer[index - 1] = 0; + + // Write batch size + // index = write32bit(index, _buffer, numberToReturn); + _buffer[index + 3] = (this.numberToReturn >> 24) & 0xff; + _buffer[index + 2] = (this.numberToReturn >> 16) & 0xff; + _buffer[index + 1] = (this.numberToReturn >> 8) & 0xff; + _buffer[index] = this.numberToReturn & 0xff; + index = index + 4; + + // Write cursor id + // index = write32bit(index, _buffer, cursorId.getLowBits()); + _buffer[index + 3] = (this.cursorId.getLowBits() >> 24) & 0xff; + _buffer[index + 2] = (this.cursorId.getLowBits() >> 16) & 0xff; + _buffer[index + 1] = (this.cursorId.getLowBits() >> 8) & 0xff; + _buffer[index] = this.cursorId.getLowBits() & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, cursorId.getHighBits()); + _buffer[index + 3] = (this.cursorId.getHighBits() >> 24) & 0xff; + _buffer[index + 2] = (this.cursorId.getHighBits() >> 16) & 0xff; + _buffer[index + 1] = (this.cursorId.getHighBits() >> 8) & 0xff; + _buffer[index] = this.cursorId.getHighBits() & 0xff; + index = index + 4; + + // Return buffer + return _buffer; +}; + +/************************************************************** + * KILLCURSOR + **************************************************************/ +var KillCursor = function(bson, ns, cursorIds) { + this.ns = ns; + this.requestId = _requestId++; + this.cursorIds = cursorIds; +}; + +// +// Uses a single allocated buffer for the process, avoiding multiple memory allocations +KillCursor.prototype.toBin = function() { + var length = 4 + 4 + 4 * 4 + this.cursorIds.length * 8; + + // Create command buffer + var index = 0; + var _buffer = Buffer.alloc(length); + + // Write header information + // index = write32bit(index, _buffer, length); + _buffer[index + 3] = (length >> 24) & 0xff; + _buffer[index + 2] = (length >> 16) & 0xff; + _buffer[index + 1] = (length >> 8) & 0xff; + _buffer[index] = length & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, requestId); + _buffer[index + 3] = (this.requestId >> 24) & 0xff; + _buffer[index + 2] = (this.requestId >> 16) & 0xff; + _buffer[index + 1] = (this.requestId >> 8) & 0xff; + _buffer[index] = this.requestId & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, 0); + _buffer[index + 3] = (0 >> 24) & 0xff; + _buffer[index + 2] = (0 >> 16) & 0xff; + _buffer[index + 1] = (0 >> 8) & 0xff; + _buffer[index] = 0 & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, OP_KILL_CURSORS); + _buffer[index + 3] = (opcodes.OP_KILL_CURSORS >> 24) & 0xff; + _buffer[index + 2] = (opcodes.OP_KILL_CURSORS >> 16) & 0xff; + _buffer[index + 1] = (opcodes.OP_KILL_CURSORS >> 8) & 0xff; + _buffer[index] = opcodes.OP_KILL_CURSORS & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, 0); + _buffer[index + 3] = (0 >> 24) & 0xff; + _buffer[index + 2] = (0 >> 16) & 0xff; + _buffer[index + 1] = (0 >> 8) & 0xff; + _buffer[index] = 0 & 0xff; + index = index + 4; + + // Write batch size + // index = write32bit(index, _buffer, this.cursorIds.length); + _buffer[index + 3] = (this.cursorIds.length >> 24) & 0xff; + _buffer[index + 2] = (this.cursorIds.length >> 16) & 0xff; + _buffer[index + 1] = (this.cursorIds.length >> 8) & 0xff; + _buffer[index] = this.cursorIds.length & 0xff; + index = index + 4; + + // Write all the cursor ids into the array + for (var i = 0; i < this.cursorIds.length; i++) { + // Write cursor id + // index = write32bit(index, _buffer, cursorIds[i].getLowBits()); + _buffer[index + 3] = (this.cursorIds[i].getLowBits() >> 24) & 0xff; + _buffer[index + 2] = (this.cursorIds[i].getLowBits() >> 16) & 0xff; + _buffer[index + 1] = (this.cursorIds[i].getLowBits() >> 8) & 0xff; + _buffer[index] = this.cursorIds[i].getLowBits() & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, cursorIds[i].getHighBits()); + _buffer[index + 3] = (this.cursorIds[i].getHighBits() >> 24) & 0xff; + _buffer[index + 2] = (this.cursorIds[i].getHighBits() >> 16) & 0xff; + _buffer[index + 1] = (this.cursorIds[i].getHighBits() >> 8) & 0xff; + _buffer[index] = this.cursorIds[i].getHighBits() & 0xff; + index = index + 4; + } + + // Return buffer + return _buffer; +}; + +var Response = function(bson, message, msgHeader, msgBody, opts) { + opts = opts || { promoteLongs: true, promoteValues: true, promoteBuffers: false }; + this.parsed = false; + this.raw = message; + this.data = msgBody; + this.bson = bson; + this.opts = opts; + + // Read the message header + this.length = msgHeader.length; + this.requestId = msgHeader.requestId; + this.responseTo = msgHeader.responseTo; + this.opCode = msgHeader.opCode; + this.fromCompressed = msgHeader.fromCompressed; + + // Read the message body + this.responseFlags = msgBody.readInt32LE(0); + this.cursorId = new Long(msgBody.readInt32LE(4), msgBody.readInt32LE(8)); + this.startingFrom = msgBody.readInt32LE(12); + this.numberReturned = msgBody.readInt32LE(16); + + // Preallocate document array + this.documents = new Array(this.numberReturned); + + // Flag values + this.cursorNotFound = (this.responseFlags & CURSOR_NOT_FOUND) !== 0; + this.queryFailure = (this.responseFlags & QUERY_FAILURE) !== 0; + this.shardConfigStale = (this.responseFlags & SHARD_CONFIG_STALE) !== 0; + this.awaitCapable = (this.responseFlags & AWAIT_CAPABLE) !== 0; + this.promoteLongs = typeof opts.promoteLongs === 'boolean' ? opts.promoteLongs : true; + this.promoteValues = typeof opts.promoteValues === 'boolean' ? opts.promoteValues : true; + this.promoteBuffers = typeof opts.promoteBuffers === 'boolean' ? opts.promoteBuffers : false; +}; + +Response.prototype.isParsed = function() { + return this.parsed; +}; + +Response.prototype.parse = function(options) { + // Don't parse again if not needed + if (this.parsed) return; + options = options || {}; + + // Allow the return of raw documents instead of parsing + var raw = options.raw || false; + var documentsReturnedIn = options.documentsReturnedIn || null; + var promoteLongs = + typeof options.promoteLongs === 'boolean' ? options.promoteLongs : this.opts.promoteLongs; + var promoteValues = + typeof options.promoteValues === 'boolean' ? options.promoteValues : this.opts.promoteValues; + var promoteBuffers = + typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : this.opts.promoteBuffers; + var bsonSize, _options; + + // Set up the options + _options = { + promoteLongs: promoteLongs, + promoteValues: promoteValues, + promoteBuffers: promoteBuffers + }; + + // Position within OP_REPLY at which documents start + // (See https://docs.mongodb.com/manual/reference/mongodb-wire-protocol/#wire-op-reply) + this.index = 20; + + // + // Parse Body + // + for (var i = 0; i < this.numberReturned; i++) { + bsonSize = + this.data[this.index] | + (this.data[this.index + 1] << 8) | + (this.data[this.index + 2] << 16) | + (this.data[this.index + 3] << 24); + + // If we have raw results specified slice the return document + if (raw) { + this.documents[i] = this.data.slice(this.index, this.index + bsonSize); + } else { + this.documents[i] = this.bson.deserialize( + this.data.slice(this.index, this.index + bsonSize), + _options + ); + } + + // Adjust the index + this.index = this.index + bsonSize; + } + + if (this.documents.length === 1 && documentsReturnedIn != null && raw) { + const fieldsAsRaw = {}; + fieldsAsRaw[documentsReturnedIn] = true; + _options.fieldsAsRaw = fieldsAsRaw; + + const doc = this.bson.deserialize(this.documents[0], _options); + this.documents = [doc]; + } + + // Set parsed + this.parsed = true; +}; + +module.exports = { + Query: Query, + GetMore: GetMore, + Response: Response, + KillCursor: KillCursor +}; diff --git a/scripts/node_modules/mongodb/lib/core/connection/connect.js b/scripts/node_modules/mongodb/lib/core/connection/connect.js new file mode 100644 index 00000000..e1a643e0 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/core/connection/connect.js @@ -0,0 +1,370 @@ +'use strict'; +const net = require('net'); +const tls = require('tls'); +const Connection = require('./connection'); +const Query = require('./commands').Query; +const createClientInfo = require('../topologies/shared').createClientInfo; +const MongoError = require('../error').MongoError; +const MongoNetworkError = require('../error').MongoNetworkError; +const defaultAuthProviders = require('../auth/defaultAuthProviders').defaultAuthProviders; +const WIRE_CONSTANTS = require('../wireprotocol/constants'); +const MAX_SUPPORTED_WIRE_VERSION = WIRE_CONSTANTS.MAX_SUPPORTED_WIRE_VERSION; +const MAX_SUPPORTED_SERVER_VERSION = WIRE_CONSTANTS.MAX_SUPPORTED_SERVER_VERSION; +const MIN_SUPPORTED_WIRE_VERSION = WIRE_CONSTANTS.MIN_SUPPORTED_WIRE_VERSION; +const MIN_SUPPORTED_SERVER_VERSION = WIRE_CONSTANTS.MIN_SUPPORTED_SERVER_VERSION; +let AUTH_PROVIDERS; + +function connect(options, callback) { + if (AUTH_PROVIDERS == null) { + AUTH_PROVIDERS = defaultAuthProviders(options.bson); + } + + if (options.family !== void 0) { + makeConnection(options.family, options, (err, socket) => { + if (err) { + callback(err, socket); // in the error case, `socket` is the originating error event name + return; + } + + performInitialHandshake(new Connection(socket, options), options, callback); + }); + + return; + } + + return makeConnection(6, options, (err, ipv6Socket) => { + if (err) { + makeConnection(4, options, (err, ipv4Socket) => { + if (err) { + callback(err, ipv4Socket); // in the error case, `ipv4Socket` is the originating error event name + return; + } + + performInitialHandshake(new Connection(ipv4Socket, options), options, callback); + }); + + return; + } + + performInitialHandshake(new Connection(ipv6Socket, options), options, callback); + }); +} + +function getSaslSupportedMechs(options) { + if (!(options && options.credentials)) { + return {}; + } + + const credentials = options.credentials; + + // TODO: revisit whether or not items like `options.user` and `options.dbName` should be checked here + const authMechanism = credentials.mechanism; + const authSource = credentials.source || options.dbName || 'admin'; + const user = credentials.username || options.user; + + if (typeof authMechanism === 'string' && authMechanism.toUpperCase() !== 'DEFAULT') { + return {}; + } + + if (!user) { + return {}; + } + + return { saslSupportedMechs: `${authSource}.${user}` }; +} + +function checkSupportedServer(ismaster, options) { + const serverVersionHighEnough = + ismaster && + typeof ismaster.maxWireVersion === 'number' && + ismaster.maxWireVersion >= MIN_SUPPORTED_WIRE_VERSION; + const serverVersionLowEnough = + ismaster && + typeof ismaster.minWireVersion === 'number' && + ismaster.minWireVersion <= MAX_SUPPORTED_WIRE_VERSION; + + if (serverVersionHighEnough) { + if (serverVersionLowEnough) { + return null; + } + + const message = `Server at ${options.host}:${options.port} reports minimum wire version ${ + ismaster.minWireVersion + }, but this version of the Node.js Driver requires at most ${MAX_SUPPORTED_WIRE_VERSION} (MongoDB ${MAX_SUPPORTED_SERVER_VERSION})`; + return new MongoError(message); + } + + const message = `Server at ${options.host}:${ + options.port + } reports maximum wire version ${ismaster.maxWireVersion || + 0}, but this version of the Node.js Driver requires at least ${MIN_SUPPORTED_WIRE_VERSION} (MongoDB ${MIN_SUPPORTED_SERVER_VERSION})`; + return new MongoError(message); +} + +function performInitialHandshake(conn, options, _callback) { + const callback = function(err, ret) { + if (err && conn) { + conn.destroy(); + } + _callback(err, ret); + }; + + let compressors = []; + if (options.compression && options.compression.compressors) { + compressors = options.compression.compressors; + } + + const handshakeDoc = Object.assign( + { + ismaster: true, + client: createClientInfo(options), + compression: compressors + }, + getSaslSupportedMechs(options) + ); + + const start = new Date().getTime(); + runCommand(conn, 'admin.$cmd', handshakeDoc, options, (err, ismaster) => { + if (err) { + callback(err, null); + return; + } + + if (ismaster.ok === 0) { + callback(new MongoError(ismaster), null); + return; + } + + const supportedServerErr = checkSupportedServer(ismaster, options); + if (supportedServerErr) { + callback(supportedServerErr, null); + return; + } + + // resolve compression + if (ismaster.compression) { + const agreedCompressors = compressors.filter( + compressor => ismaster.compression.indexOf(compressor) !== -1 + ); + + if (agreedCompressors.length) { + conn.agreedCompressor = agreedCompressors[0]; + } + + if (options.compression && options.compression.zlibCompressionLevel) { + conn.zlibCompressionLevel = options.compression.zlibCompressionLevel; + } + } + + // NOTE: This is metadata attached to the connection while porting away from + // handshake being done in the `Server` class. Likely, it should be + // relocated, or at very least restructured. + conn.ismaster = ismaster; + conn.lastIsMasterMS = new Date().getTime() - start; + + const credentials = options.credentials; + if (!ismaster.arbiterOnly && credentials) { + credentials.resolveAuthMechanism(ismaster); + authenticate(conn, credentials, callback); + return; + } + + callback(null, conn); + }); +} + +const LEGAL_SSL_SOCKET_OPTIONS = [ + 'pfx', + 'key', + 'passphrase', + 'cert', + 'ca', + 'ciphers', + 'NPNProtocols', + 'ALPNProtocols', + 'servername', + 'ecdhCurve', + 'secureProtocol', + 'secureContext', + 'session', + 'minDHSize', + 'crl', + 'rejectUnauthorized' +]; + +function parseConnectOptions(family, options) { + const host = typeof options.host === 'string' ? options.host : 'localhost'; + if (host.indexOf('/') !== -1) { + return { path: host }; + } + + const result = { + family, + host, + port: typeof options.port === 'number' ? options.port : 27017, + rejectUnauthorized: false + }; + + return result; +} + +function parseSslOptions(family, options) { + const result = parseConnectOptions(family, options); + + // Merge in valid SSL options + for (const name in options) { + if (options[name] != null && LEGAL_SSL_SOCKET_OPTIONS.indexOf(name) !== -1) { + result[name] = options[name]; + } + } + + // Override checkServerIdentity behavior + if (options.checkServerIdentity === false) { + // Skip the identiy check by retuning undefined as per node documents + // https://nodejs.org/api/tls.html#tls_tls_connect_options_callback + result.checkServerIdentity = function() { + return undefined; + }; + } else if (typeof options.checkServerIdentity === 'function') { + result.checkServerIdentity = options.checkServerIdentity; + } + + // Set default sni servername to be the same as host + if (result.servername == null) { + result.servername = result.host; + } + + return result; +} + +function makeConnection(family, options, _callback) { + const useSsl = typeof options.ssl === 'boolean' ? options.ssl : false; + const keepAlive = typeof options.keepAlive === 'boolean' ? options.keepAlive : true; + let keepAliveInitialDelay = + typeof options.keepAliveInitialDelay === 'number' ? options.keepAliveInitialDelay : 300000; + const noDelay = typeof options.noDelay === 'boolean' ? options.noDelay : true; + const connectionTimeout = + typeof options.connectionTimeout === 'number' ? options.connectionTimeout : 30000; + const socketTimeout = typeof options.socketTimeout === 'number' ? options.socketTimeout : 360000; + const rejectUnauthorized = + typeof options.rejectUnauthorized === 'boolean' ? options.rejectUnauthorized : true; + + if (keepAliveInitialDelay > socketTimeout) { + keepAliveInitialDelay = Math.round(socketTimeout / 2); + } + + let socket; + const callback = function(err, ret) { + if (err && socket) { + socket.destroy(); + } + _callback(err, ret); + }; + + try { + if (useSsl) { + socket = tls.connect(parseSslOptions(family, options)); + if (typeof socket.disableRenegotiation === 'function') { + socket.disableRenegotiation(); + } + } else { + socket = net.createConnection(parseConnectOptions(family, options)); + } + } catch (err) { + return callback(err); + } + + socket.setKeepAlive(keepAlive, keepAliveInitialDelay); + socket.setTimeout(connectionTimeout); + socket.setNoDelay(noDelay); + + const errorEvents = ['error', 'close', 'timeout', 'parseError']; + function errorHandler(eventName) { + return err => { + errorEvents.forEach(event => socket.removeAllListeners(event)); + socket.removeListener('connect', connectHandler); + callback(connectionFailureError(eventName, err), eventName); + }; + } + + function connectHandler() { + errorEvents.forEach(event => socket.removeAllListeners(event)); + if (socket.authorizationError && rejectUnauthorized) { + return callback(socket.authorizationError); + } + + socket.setTimeout(socketTimeout); + callback(null, socket); + } + + socket.once('error', errorHandler('error')); + socket.once('close', errorHandler('close')); + socket.once('timeout', errorHandler('timeout')); + socket.once('parseError', errorHandler('parseError')); + socket.once('connect', connectHandler); +} + +const CONNECTION_ERROR_EVENTS = ['error', 'close', 'timeout', 'parseError']; +function runCommand(conn, ns, command, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + const socketTimeout = typeof options.socketTimeout === 'number' ? options.socketTimeout : 360000; + const bson = conn.options.bson; + const query = new Query(bson, ns, command, { + numberToSkip: 0, + numberToReturn: 1 + }); + + function errorHandler(err) { + conn.resetSocketTimeout(); + CONNECTION_ERROR_EVENTS.forEach(eventName => conn.removeListener(eventName, errorHandler)); + conn.removeListener('message', messageHandler); + callback(err, null); + } + + function messageHandler(msg) { + if (msg.responseTo !== query.requestId) { + return; + } + + conn.resetSocketTimeout(); + CONNECTION_ERROR_EVENTS.forEach(eventName => conn.removeListener(eventName, errorHandler)); + conn.removeListener('message', messageHandler); + + msg.parse({ promoteValues: true }); + callback(null, msg.documents[0]); + } + + conn.setSocketTimeout(socketTimeout); + CONNECTION_ERROR_EVENTS.forEach(eventName => conn.once(eventName, errorHandler)); + conn.on('message', messageHandler); + conn.write(query.toBin()); +} + +function authenticate(conn, credentials, callback) { + const mechanism = credentials.mechanism; + if (!AUTH_PROVIDERS[mechanism]) { + callback(new MongoError(`authMechanism '${mechanism}' not supported`)); + return; + } + + const provider = AUTH_PROVIDERS[mechanism]; + provider.auth(runCommand, [conn], credentials, err => { + if (err) return callback(err); + callback(null, conn); + }); +} + +function connectionFailureError(type, err) { + switch (type) { + case 'error': + return new MongoNetworkError(err); + case 'timeout': + return new MongoNetworkError(`connection timed out`); + case 'close': + return new MongoNetworkError(`connection closed`); + default: + return new MongoNetworkError(`unknown network error`); + } +} + +module.exports = connect; diff --git a/scripts/node_modules/mongodb/lib/core/connection/connection.js b/scripts/node_modules/mongodb/lib/core/connection/connection.js new file mode 100644 index 00000000..6f6ca6ad --- /dev/null +++ b/scripts/node_modules/mongodb/lib/core/connection/connection.js @@ -0,0 +1,628 @@ +'use strict'; + +const EventEmitter = require('events').EventEmitter; +const crypto = require('crypto'); +const debugOptions = require('./utils').debugOptions; +const parseHeader = require('../wireprotocol/shared').parseHeader; +const decompress = require('../wireprotocol/compression').decompress; +const Response = require('./commands').Response; +const BinMsg = require('./msg').BinMsg; +const MongoNetworkError = require('../error').MongoNetworkError; +const MongoError = require('../error').MongoError; +const Logger = require('./logger'); +const OP_COMPRESSED = require('../wireprotocol/shared').opcodes.OP_COMPRESSED; +const OP_MSG = require('../wireprotocol/shared').opcodes.OP_MSG; +const MESSAGE_HEADER_SIZE = require('../wireprotocol/shared').MESSAGE_HEADER_SIZE; +const Buffer = require('safe-buffer').Buffer; + +let _id = 0; + +const DEFAULT_MAX_BSON_MESSAGE_SIZE = 1024 * 1024 * 16 * 4; +const DEBUG_FIELDS = [ + 'host', + 'port', + 'size', + 'keepAlive', + 'keepAliveInitialDelay', + 'noDelay', + 'connectionTimeout', + 'socketTimeout', + 'ssl', + 'ca', + 'crl', + 'cert', + 'rejectUnauthorized', + 'promoteLongs', + 'promoteValues', + 'promoteBuffers', + 'checkServerIdentity' +]; + +let connectionAccountingSpy = undefined; +let connectionAccounting = false; +let connections = {}; + +/** + * A class representing a single connection to a MongoDB server + * + * @fires Connection#connect + * @fires Connection#close + * @fires Connection#error + * @fires Connection#timeout + * @fires Connection#parseError + * @fires Connection#message + */ +class Connection extends EventEmitter { + /** + * Creates a new Connection instance + * + * **NOTE**: Internal class, do not instantiate directly + * + * @param {Socket} socket The socket this connection wraps + * @param {Object} options Various settings + * @param {object} options.bson An implementation of bson serialize and deserialize + * @param {string} [options.host='localhost'] The host the socket is connected to + * @param {number} [options.port=27017] The port used for the socket connection + * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled + * @param {number} [options.keepAliveInitialDelay=300000] Initial delay before TCP keep alive enabled + * @param {number} [options.connectionTimeout=30000] TCP Connection timeout setting + * @param {number} [options.socketTimeout=360000] TCP Socket timeout setting + * @param {boolean} [options.promoteLongs] Convert Long values from the db into Numbers if they fit into 53 bits + * @param {boolean} [options.promoteValues] Promotes BSON values to native types where possible, set to false to only receive wrapper types. + * @param {boolean} [options.promoteBuffers] Promotes Binary BSON values to native Node Buffers. + * @param {number} [options.maxBsonMessageSize=0x4000000] Largest possible size of a BSON message (for legacy purposes) + */ + constructor(socket, options) { + super(); + + options = options || {}; + if (!options.bson) { + throw new TypeError('must pass in valid bson parser'); + } + + this.id = _id++; + this.options = options; + this.logger = Logger('Connection', options); + this.bson = options.bson; + this.tag = options.tag; + this.maxBsonMessageSize = options.maxBsonMessageSize || DEFAULT_MAX_BSON_MESSAGE_SIZE; + + this.port = options.port || 27017; + this.host = options.host || 'localhost'; + this.socketTimeout = typeof options.socketTimeout === 'number' ? options.socketTimeout : 360000; + + // These values are inspected directly in tests, but maybe not necessary to keep around + this.keepAlive = typeof options.keepAlive === 'boolean' ? options.keepAlive : true; + this.keepAliveInitialDelay = + typeof options.keepAliveInitialDelay === 'number' ? options.keepAliveInitialDelay : 300000; + this.connectionTimeout = + typeof options.connectionTimeout === 'number' ? options.connectionTimeout : 30000; + if (this.keepAliveInitialDelay > this.socketTimeout) { + this.keepAliveInitialDelay = Math.round(this.socketTimeout / 2); + } + + // Debug information + if (this.logger.isDebug()) { + this.logger.debug( + `creating connection ${this.id} with options [${JSON.stringify( + debugOptions(DEBUG_FIELDS, options) + )}]` + ); + } + + // Response options + this.responseOptions = { + promoteLongs: typeof options.promoteLongs === 'boolean' ? options.promoteLongs : true, + promoteValues: typeof options.promoteValues === 'boolean' ? options.promoteValues : true, + promoteBuffers: typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : false + }; + + // Flushing + this.flushing = false; + this.queue = []; + + // Internal state + this.writeStream = null; + this.destroyed = false; + + // Create hash method + const hash = crypto.createHash('sha1'); + hash.update(this.address); + this.hashedName = hash.digest('hex'); + + // All operations in flight on the connection + this.workItems = []; + + // setup socket + this.socket = socket; + this.socket.once('error', errorHandler(this)); + this.socket.once('timeout', timeoutHandler(this)); + this.socket.once('close', closeHandler(this)); + this.socket.on('data', dataHandler(this)); + + if (connectionAccounting) { + addConnection(this.id, this); + } + } + + setSocketTimeout(value) { + if (this.socket) { + this.socket.setTimeout(value); + } + } + + resetSocketTimeout() { + if (this.socket) { + this.socket.setTimeout(this.socketTimeout); + } + } + + static enableConnectionAccounting(spy) { + if (spy) { + connectionAccountingSpy = spy; + } + + connectionAccounting = true; + connections = {}; + } + + static disableConnectionAccounting() { + connectionAccounting = false; + connectionAccountingSpy = undefined; + } + + static connections() { + return connections; + } + + get address() { + return `${this.host}:${this.port}`; + } + + /** + * Unref this connection + * @method + * @return {boolean} + */ + unref() { + if (this.socket == null) { + this.once('connect', () => this.socket.unref()); + return; + } + + this.socket.unref(); + } + + /** + * Destroy connection + * @method + */ + destroy(options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + + options = Object.assign({ force: false }, options); + + if (connectionAccounting) { + deleteConnection(this.id); + } + + if (this.socket == null) { + this.destroyed = true; + return; + } + + if (options.force) { + this.socket.destroy(); + this.destroyed = true; + if (typeof callback === 'function') callback(null, null); + return; + } + + this.socket.end(err => { + this.destroyed = true; + if (typeof callback === 'function') callback(err, null); + }); + } + + /** + * Write to connection + * @method + * @param {Command} command Command to write out need to implement toBin and toBinUnified + */ + write(buffer) { + // Debug Log + if (this.logger.isDebug()) { + if (!Array.isArray(buffer)) { + this.logger.debug(`writing buffer [${buffer.toString('hex')}] to ${this.address}`); + } else { + for (let i = 0; i < buffer.length; i++) + this.logger.debug(`writing buffer [${buffer[i].toString('hex')}] to ${this.address}`); + } + } + + // Double check that the connection is not destroyed + if (this.socket.destroyed === false) { + // Write out the command + if (!Array.isArray(buffer)) { + this.socket.write(buffer, 'binary'); + return true; + } + + // Iterate over all buffers and write them in order to the socket + for (let i = 0; i < buffer.length; i++) { + this.socket.write(buffer[i], 'binary'); + } + + return true; + } + + // Connection is destroyed return write failed + return false; + } + + /** + * Return id of connection as a string + * @method + * @return {string} + */ + toString() { + return '' + this.id; + } + + /** + * Return json object of connection + * @method + * @return {object} + */ + toJSON() { + return { id: this.id, host: this.host, port: this.port }; + } + + /** + * Is the connection connected + * @method + * @return {boolean} + */ + isConnected() { + if (this.destroyed) return false; + return !this.socket.destroyed && this.socket.writable; + } +} + +function deleteConnection(id) { + // console.log("=== deleted connection " + id + " :: " + (connections[id] ? connections[id].port : '')) + delete connections[id]; + + if (connectionAccountingSpy) { + connectionAccountingSpy.deleteConnection(id); + } +} + +function addConnection(id, connection) { + // console.log("=== added connection " + id + " :: " + connection.port) + connections[id] = connection; + + if (connectionAccountingSpy) { + connectionAccountingSpy.addConnection(id, connection); + } +} + +// +// Connection handlers +function errorHandler(conn) { + return function(err) { + if (connectionAccounting) deleteConnection(conn.id); + // Debug information + if (conn.logger.isDebug()) { + conn.logger.debug( + `connection ${conn.id} for [${conn.address}] errored out with [${JSON.stringify(err)}]` + ); + } + + conn.emit('error', new MongoNetworkError(err), conn); + }; +} + +function timeoutHandler(conn) { + return function() { + if (connectionAccounting) deleteConnection(conn.id); + + if (conn.logger.isDebug()) { + conn.logger.debug(`connection ${conn.id} for [${conn.address}] timed out`); + } + + conn.emit( + 'timeout', + new MongoNetworkError(`connection ${conn.id} to ${conn.address} timed out`), + conn + ); + }; +} + +function closeHandler(conn) { + return function(hadError) { + if (connectionAccounting) deleteConnection(conn.id); + + if (conn.logger.isDebug()) { + conn.logger.debug(`connection ${conn.id} with for [${conn.address}] closed`); + } + + if (!hadError) { + conn.emit( + 'close', + new MongoNetworkError(`connection ${conn.id} to ${conn.address} closed`), + conn + ); + } + }; +} + +// Handle a message once it is received +function processMessage(conn, message) { + const msgHeader = parseHeader(message); + if (msgHeader.opCode !== OP_COMPRESSED) { + const ResponseConstructor = msgHeader.opCode === OP_MSG ? BinMsg : Response; + conn.emit( + 'message', + new ResponseConstructor( + conn.bson, + message, + msgHeader, + message.slice(MESSAGE_HEADER_SIZE), + conn.responseOptions + ), + conn + ); + + return; + } + + msgHeader.fromCompressed = true; + let index = MESSAGE_HEADER_SIZE; + msgHeader.opCode = message.readInt32LE(index); + index += 4; + msgHeader.length = message.readInt32LE(index); + index += 4; + const compressorID = message[index]; + index++; + + decompress(compressorID, message.slice(index), (err, decompressedMsgBody) => { + if (err) { + conn.emit('error', err); + return; + } + + if (decompressedMsgBody.length !== msgHeader.length) { + conn.emit( + 'error', + new MongoError( + 'Decompressing a compressed message from the server failed. The message is corrupt.' + ) + ); + + return; + } + + const ResponseConstructor = msgHeader.opCode === OP_MSG ? BinMsg : Response; + conn.emit( + 'message', + new ResponseConstructor( + conn.bson, + message, + msgHeader, + decompressedMsgBody, + conn.responseOptions + ), + conn + ); + }); +} + +function dataHandler(conn) { + return function(data) { + // Parse until we are done with the data + while (data.length > 0) { + // If we still have bytes to read on the current message + if (conn.bytesRead > 0 && conn.sizeOfMessage > 0) { + // Calculate the amount of remaining bytes + const remainingBytesToRead = conn.sizeOfMessage - conn.bytesRead; + // Check if the current chunk contains the rest of the message + if (remainingBytesToRead > data.length) { + // Copy the new data into the exiting buffer (should have been allocated when we know the message size) + data.copy(conn.buffer, conn.bytesRead); + // Adjust the number of bytes read so it point to the correct index in the buffer + conn.bytesRead = conn.bytesRead + data.length; + + // Reset state of buffer + data = Buffer.alloc(0); + } else { + // Copy the missing part of the data into our current buffer + data.copy(conn.buffer, conn.bytesRead, 0, remainingBytesToRead); + // Slice the overflow into a new buffer that we will then re-parse + data = data.slice(remainingBytesToRead); + + // Emit current complete message + const emitBuffer = conn.buffer; + // Reset state of buffer + conn.buffer = null; + conn.sizeOfMessage = 0; + conn.bytesRead = 0; + conn.stubBuffer = null; + + processMessage(conn, emitBuffer); + } + } else { + // Stub buffer is kept in case we don't get enough bytes to determine the + // size of the message (< 4 bytes) + if (conn.stubBuffer != null && conn.stubBuffer.length > 0) { + // If we have enough bytes to determine the message size let's do it + if (conn.stubBuffer.length + data.length > 4) { + // Prepad the data + const newData = Buffer.alloc(conn.stubBuffer.length + data.length); + conn.stubBuffer.copy(newData, 0); + data.copy(newData, conn.stubBuffer.length); + // Reassign for parsing + data = newData; + + // Reset state of buffer + conn.buffer = null; + conn.sizeOfMessage = 0; + conn.bytesRead = 0; + conn.stubBuffer = null; + } else { + // Add the the bytes to the stub buffer + const newStubBuffer = Buffer.alloc(conn.stubBuffer.length + data.length); + // Copy existing stub buffer + conn.stubBuffer.copy(newStubBuffer, 0); + // Copy missing part of the data + data.copy(newStubBuffer, conn.stubBuffer.length); + // Exit parsing loop + data = Buffer.alloc(0); + } + } else { + if (data.length > 4) { + // Retrieve the message size + const sizeOfMessage = data[0] | (data[1] << 8) | (data[2] << 16) | (data[3] << 24); + // If we have a negative sizeOfMessage emit error and return + if (sizeOfMessage < 0 || sizeOfMessage > conn.maxBsonMessageSize) { + const errorObject = { + err: 'socketHandler', + trace: '', + bin: conn.buffer, + parseState: { + sizeOfMessage: sizeOfMessage, + bytesRead: conn.bytesRead, + stubBuffer: conn.stubBuffer + } + }; + // We got a parse Error fire it off then keep going + conn.emit('parseError', errorObject, conn); + return; + } + + // Ensure that the size of message is larger than 0 and less than the max allowed + if ( + sizeOfMessage > 4 && + sizeOfMessage < conn.maxBsonMessageSize && + sizeOfMessage > data.length + ) { + conn.buffer = Buffer.alloc(sizeOfMessage); + // Copy all the data into the buffer + data.copy(conn.buffer, 0); + // Update bytes read + conn.bytesRead = data.length; + // Update sizeOfMessage + conn.sizeOfMessage = sizeOfMessage; + // Ensure stub buffer is null + conn.stubBuffer = null; + // Exit parsing loop + data = Buffer.alloc(0); + } else if ( + sizeOfMessage > 4 && + sizeOfMessage < conn.maxBsonMessageSize && + sizeOfMessage === data.length + ) { + const emitBuffer = data; + // Reset state of buffer + conn.buffer = null; + conn.sizeOfMessage = 0; + conn.bytesRead = 0; + conn.stubBuffer = null; + // Exit parsing loop + data = Buffer.alloc(0); + // Emit the message + processMessage(conn, emitBuffer); + } else if (sizeOfMessage <= 4 || sizeOfMessage > conn.maxBsonMessageSize) { + const errorObject = { + err: 'socketHandler', + trace: null, + bin: data, + parseState: { + sizeOfMessage: sizeOfMessage, + bytesRead: 0, + buffer: null, + stubBuffer: null + } + }; + // We got a parse Error fire it off then keep going + conn.emit('parseError', errorObject, conn); + + // Clear out the state of the parser + conn.buffer = null; + conn.sizeOfMessage = 0; + conn.bytesRead = 0; + conn.stubBuffer = null; + // Exit parsing loop + data = Buffer.alloc(0); + } else { + const emitBuffer = data.slice(0, sizeOfMessage); + // Reset state of buffer + conn.buffer = null; + conn.sizeOfMessage = 0; + conn.bytesRead = 0; + conn.stubBuffer = null; + // Copy rest of message + data = data.slice(sizeOfMessage); + // Emit the message + processMessage(conn, emitBuffer); + } + } else { + // Create a buffer that contains the space for the non-complete message + conn.stubBuffer = Buffer.alloc(data.length); + // Copy the data to the stub buffer + data.copy(conn.stubBuffer, 0); + // Exit parsing loop + data = Buffer.alloc(0); + } + } + } + } + }; +} + +/** + * A server connect event, used to verify that the connection is up and running + * + * @event Connection#connect + * @type {Connection} + */ + +/** + * The server connection closed, all pool connections closed + * + * @event Connection#close + * @type {Connection} + */ + +/** + * The server connection caused an error, all pool connections closed + * + * @event Connection#error + * @type {Connection} + */ + +/** + * The server connection timed out, all pool connections closed + * + * @event Connection#timeout + * @type {Connection} + */ + +/** + * The driver experienced an invalid message, all pool connections closed + * + * @event Connection#parseError + * @type {Connection} + */ + +/** + * An event emitted each time the connection receives a parsed message from the wire + * + * @event Connection#message + * @type {Connection} + */ + +module.exports = Connection; diff --git a/scripts/node_modules/mongodb/lib/core/connection/logger.js b/scripts/node_modules/mongodb/lib/core/connection/logger.js new file mode 100644 index 00000000..eb11e43d --- /dev/null +++ b/scripts/node_modules/mongodb/lib/core/connection/logger.js @@ -0,0 +1,246 @@ +'use strict'; + +var f = require('util').format, + MongoError = require('../error').MongoError; + +// Filters for classes +var classFilters = {}; +var filteredClasses = {}; +var level = null; +// Save the process id +var pid = process.pid; +// current logger +var currentLogger = null; + +/** + * Creates a new Logger instance + * @class + * @param {string} className The Class name associated with the logging instance + * @param {object} [options=null] Optional settings. + * @param {Function} [options.logger=null] Custom logger function; + * @param {string} [options.loggerLevel=error] Override default global log level. + * @return {Logger} a Logger instance. + */ +var Logger = function(className, options) { + if (!(this instanceof Logger)) return new Logger(className, options); + options = options || {}; + + // Current reference + this.className = className; + + // Current logger + if (options.logger) { + currentLogger = options.logger; + } else if (currentLogger == null) { + currentLogger = console.log; + } + + // Set level of logging, default is error + if (options.loggerLevel) { + level = options.loggerLevel || 'error'; + } + + // Add all class names + if (filteredClasses[this.className] == null) classFilters[this.className] = true; +}; + +/** + * Log a message at the debug level + * @method + * @param {string} message The message to log + * @param {object} object additional meta data to log + * @return {null} + */ +Logger.prototype.debug = function(message, object) { + if ( + this.isDebug() && + ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) || + (Object.keys(filteredClasses).length === 0 && classFilters[this.className])) + ) { + var dateTime = new Date().getTime(); + var msg = f('[%s-%s:%s] %s %s', 'DEBUG', this.className, pid, dateTime, message); + var state = { + type: 'debug', + message: message, + className: this.className, + pid: pid, + date: dateTime + }; + if (object) state.meta = object; + currentLogger(msg, state); + } +}; + +/** + * Log a message at the warn level + * @method + * @param {string} message The message to log + * @param {object} object additional meta data to log + * @return {null} + */ +(Logger.prototype.warn = function(message, object) { + if ( + this.isWarn() && + ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) || + (Object.keys(filteredClasses).length === 0 && classFilters[this.className])) + ) { + var dateTime = new Date().getTime(); + var msg = f('[%s-%s:%s] %s %s', 'WARN', this.className, pid, dateTime, message); + var state = { + type: 'warn', + message: message, + className: this.className, + pid: pid, + date: dateTime + }; + if (object) state.meta = object; + currentLogger(msg, state); + } +}), + /** + * Log a message at the info level + * @method + * @param {string} message The message to log + * @param {object} object additional meta data to log + * @return {null} + */ + (Logger.prototype.info = function(message, object) { + if ( + this.isInfo() && + ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) || + (Object.keys(filteredClasses).length === 0 && classFilters[this.className])) + ) { + var dateTime = new Date().getTime(); + var msg = f('[%s-%s:%s] %s %s', 'INFO', this.className, pid, dateTime, message); + var state = { + type: 'info', + message: message, + className: this.className, + pid: pid, + date: dateTime + }; + if (object) state.meta = object; + currentLogger(msg, state); + } + }), + /** + * Log a message at the error level + * @method + * @param {string} message The message to log + * @param {object} object additional meta data to log + * @return {null} + */ + (Logger.prototype.error = function(message, object) { + if ( + this.isError() && + ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) || + (Object.keys(filteredClasses).length === 0 && classFilters[this.className])) + ) { + var dateTime = new Date().getTime(); + var msg = f('[%s-%s:%s] %s %s', 'ERROR', this.className, pid, dateTime, message); + var state = { + type: 'error', + message: message, + className: this.className, + pid: pid, + date: dateTime + }; + if (object) state.meta = object; + currentLogger(msg, state); + } + }), + /** + * Is the logger set at info level + * @method + * @return {boolean} + */ + (Logger.prototype.isInfo = function() { + return level === 'info' || level === 'debug'; + }), + /** + * Is the logger set at error level + * @method + * @return {boolean} + */ + (Logger.prototype.isError = function() { + return level === 'error' || level === 'info' || level === 'debug'; + }), + /** + * Is the logger set at error level + * @method + * @return {boolean} + */ + (Logger.prototype.isWarn = function() { + return level === 'error' || level === 'warn' || level === 'info' || level === 'debug'; + }), + /** + * Is the logger set at debug level + * @method + * @return {boolean} + */ + (Logger.prototype.isDebug = function() { + return level === 'debug'; + }); + +/** + * Resets the logger to default settings, error and no filtered classes + * @method + * @return {null} + */ +Logger.reset = function() { + level = 'error'; + filteredClasses = {}; +}; + +/** + * Get the current logger function + * @method + * @return {function} + */ +Logger.currentLogger = function() { + return currentLogger; +}; + +/** + * Set the current logger function + * @method + * @param {function} logger Logger function. + * @return {null} + */ +Logger.setCurrentLogger = function(logger) { + if (typeof logger !== 'function') throw new MongoError('current logger must be a function'); + currentLogger = logger; +}; + +/** + * Set what classes to log. + * @method + * @param {string} type The type of filter (currently only class) + * @param {string[]} values The filters to apply + * @return {null} + */ +Logger.filter = function(type, values) { + if (type === 'class' && Array.isArray(values)) { + filteredClasses = {}; + + values.forEach(function(x) { + filteredClasses[x] = true; + }); + } +}; + +/** + * Set the current log level + * @method + * @param {string} level Set current log level (debug, info, error) + * @return {null} + */ +Logger.setLevel = function(_level) { + if (_level !== 'info' && _level !== 'error' && _level !== 'debug' && _level !== 'warn') { + throw new Error(f('%s is an illegal logging level', _level)); + } + + level = _level; +}; + +module.exports = Logger; diff --git a/scripts/node_modules/mongodb/lib/core/connection/msg.js b/scripts/node_modules/mongodb/lib/core/connection/msg.js new file mode 100644 index 00000000..7bee3c5e --- /dev/null +++ b/scripts/node_modules/mongodb/lib/core/connection/msg.js @@ -0,0 +1,221 @@ +'use strict'; + +// Implementation of OP_MSG spec: +// https://github.com/mongodb/specifications/blob/master/source/message/OP_MSG.rst +// +// struct Section { +// uint8 payloadType; +// union payload { +// document document; // payloadType == 0 +// struct sequence { // payloadType == 1 +// int32 size; +// cstring identifier; +// document* documents; +// }; +// }; +// }; + +// struct OP_MSG { +// struct MsgHeader { +// int32 messageLength; +// int32 requestID; +// int32 responseTo; +// int32 opCode = 2013; +// }; +// uint32 flagBits; +// Section+ sections; +// [uint32 checksum;] +// }; + +const Buffer = require('safe-buffer').Buffer; +const opcodes = require('../wireprotocol/shared').opcodes; +const databaseNamespace = require('../wireprotocol/shared').databaseNamespace; +const ReadPreference = require('../topologies/read_preference'); + +// Incrementing request id +let _requestId = 0; + +// Msg Flags +const OPTS_CHECKSUM_PRESENT = 1; +const OPTS_MORE_TO_COME = 2; +const OPTS_EXHAUST_ALLOWED = 1 << 16; + +class Msg { + constructor(bson, ns, command, options) { + // Basic options needed to be passed in + if (command == null) throw new Error('query must be specified for query'); + + // Basic options + this.bson = bson; + this.ns = ns; + this.command = command; + this.command.$db = databaseNamespace(ns); + + if (options.readPreference && options.readPreference.mode !== ReadPreference.PRIMARY) { + this.command.$readPreference = options.readPreference.toJSON(); + } + + // Ensure empty options + this.options = options || {}; + + // Additional options + this.requestId = Msg.getRequestId(); + + // Serialization option + this.serializeFunctions = + typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + this.ignoreUndefined = + typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : false; + this.checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; + this.maxBsonSize = options.maxBsonSize || 1024 * 1024 * 16; + + // flags + this.checksumPresent = false; + this.moreToCome = options.moreToCome || false; + this.exhaustAllowed = false; + } + + toBin() { + const buffers = []; + let flags = 0; + + if (this.checksumPresent) { + flags |= OPTS_CHECKSUM_PRESENT; + } + + if (this.moreToCome) { + flags |= OPTS_MORE_TO_COME; + } + + if (this.exhaustAllowed) { + flags |= OPTS_EXHAUST_ALLOWED; + } + + const header = Buffer.alloc( + 4 * 4 + // Header + 4 // Flags + ); + + buffers.push(header); + + let totalLength = header.length; + const command = this.command; + totalLength += this.makeDocumentSegment(buffers, command); + + header.writeInt32LE(totalLength, 0); // messageLength + header.writeInt32LE(this.requestId, 4); // requestID + header.writeInt32LE(0, 8); // responseTo + header.writeInt32LE(opcodes.OP_MSG, 12); // opCode + header.writeUInt32LE(flags, 16); // flags + return buffers; + } + + makeDocumentSegment(buffers, document) { + const payloadTypeBuffer = Buffer.alloc(1); + payloadTypeBuffer[0] = 0; + + const documentBuffer = this.serializeBson(document); + buffers.push(payloadTypeBuffer); + buffers.push(documentBuffer); + + return payloadTypeBuffer.length + documentBuffer.length; + } + + serializeBson(document) { + return this.bson.serialize(document, { + checkKeys: this.checkKeys, + serializeFunctions: this.serializeFunctions, + ignoreUndefined: this.ignoreUndefined + }); + } +} + +Msg.getRequestId = function() { + _requestId = (_requestId + 1) & 0x7fffffff; + return _requestId; +}; + +class BinMsg { + constructor(bson, message, msgHeader, msgBody, opts) { + opts = opts || { promoteLongs: true, promoteValues: true, promoteBuffers: false }; + this.parsed = false; + this.raw = message; + this.data = msgBody; + this.bson = bson; + this.opts = opts; + + // Read the message header + this.length = msgHeader.length; + this.requestId = msgHeader.requestId; + this.responseTo = msgHeader.responseTo; + this.opCode = msgHeader.opCode; + this.fromCompressed = msgHeader.fromCompressed; + + // Read response flags + this.responseFlags = msgBody.readInt32LE(0); + this.checksumPresent = (this.responseFlags & OPTS_CHECKSUM_PRESENT) !== 0; + this.moreToCome = (this.responseFlags & OPTS_MORE_TO_COME) !== 0; + this.exhaustAllowed = (this.responseFlags & OPTS_EXHAUST_ALLOWED) !== 0; + this.promoteLongs = typeof opts.promoteLongs === 'boolean' ? opts.promoteLongs : true; + this.promoteValues = typeof opts.promoteValues === 'boolean' ? opts.promoteValues : true; + this.promoteBuffers = typeof opts.promoteBuffers === 'boolean' ? opts.promoteBuffers : false; + + this.documents = []; + } + + isParsed() { + return this.parsed; + } + + parse(options) { + // Don't parse again if not needed + if (this.parsed) return; + options = options || {}; + + this.index = 4; + // Allow the return of raw documents instead of parsing + const raw = options.raw || false; + const documentsReturnedIn = options.documentsReturnedIn || null; + const promoteLongs = + typeof options.promoteLongs === 'boolean' ? options.promoteLongs : this.opts.promoteLongs; + const promoteValues = + typeof options.promoteValues === 'boolean' ? options.promoteValues : this.opts.promoteValues; + const promoteBuffers = + typeof options.promoteBuffers === 'boolean' + ? options.promoteBuffers + : this.opts.promoteBuffers; + + // Set up the options + const _options = { + promoteLongs: promoteLongs, + promoteValues: promoteValues, + promoteBuffers: promoteBuffers + }; + + while (this.index < this.data.length) { + const payloadType = this.data.readUInt8(this.index++); + if (payloadType === 1) { + console.error('TYPE 1'); + } else if (payloadType === 0) { + const bsonSize = this.data.readUInt32LE(this.index); + const bin = this.data.slice(this.index, this.index + bsonSize); + this.documents.push(raw ? bin : this.bson.deserialize(bin, _options)); + + this.index += bsonSize; + } + } + + if (this.documents.length === 1 && documentsReturnedIn != null && raw) { + const fieldsAsRaw = {}; + fieldsAsRaw[documentsReturnedIn] = true; + _options.fieldsAsRaw = fieldsAsRaw; + + const doc = this.bson.deserialize(this.documents[0], _options); + this.documents = [doc]; + } + + this.parsed = true; + } +} + +module.exports = { Msg, BinMsg }; diff --git a/scripts/node_modules/mongodb/lib/core/connection/pool.js b/scripts/node_modules/mongodb/lib/core/connection/pool.js new file mode 100644 index 00000000..adc85900 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/core/connection/pool.js @@ -0,0 +1,1256 @@ +'use strict'; + +const inherits = require('util').inherits; +const EventEmitter = require('events').EventEmitter; +const MongoError = require('../error').MongoError; +const MongoTimeoutError = require('../error').MongoTimeoutError; +const MongoWriteConcernError = require('../error').MongoWriteConcernError; +const Logger = require('./logger'); +const f = require('util').format; +const Msg = require('./msg').Msg; +const CommandResult = require('./command_result'); +const MESSAGE_HEADER_SIZE = require('../wireprotocol/shared').MESSAGE_HEADER_SIZE; +const COMPRESSION_DETAILS_SIZE = require('../wireprotocol/shared').COMPRESSION_DETAILS_SIZE; +const opcodes = require('../wireprotocol/shared').opcodes; +const compress = require('../wireprotocol/compression').compress; +const compressorIDs = require('../wireprotocol/compression').compressorIDs; +const uncompressibleCommands = require('../wireprotocol/compression').uncompressibleCommands; +const apm = require('./apm'); +const Buffer = require('safe-buffer').Buffer; +const connect = require('./connect'); +const updateSessionFromResponse = require('../sessions').updateSessionFromResponse; +const eachAsync = require('../utils').eachAsync; + +var DISCONNECTED = 'disconnected'; +var CONNECTING = 'connecting'; +var CONNECTED = 'connected'; +var DESTROYING = 'destroying'; +var DESTROYED = 'destroyed'; + +const CONNECTION_EVENTS = new Set([ + 'error', + 'close', + 'timeout', + 'parseError', + 'connect', + 'message' +]); + +var _id = 0; + +/** + * Creates a new Pool instance + * @class + * @param {string} options.host The server host + * @param {number} options.port The server port + * @param {number} [options.size=5] Max server connection pool size + * @param {number} [options.minSize=0] Minimum server connection pool size + * @param {boolean} [options.reconnect=true] Server will attempt to reconnect on loss of connection + * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times + * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries + * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled + * @param {number} [options.keepAliveInitialDelay=300000] Initial delay before TCP keep alive enabled + * @param {boolean} [options.noDelay=true] TCP Connection no delay + * @param {number} [options.connectionTimeout=30000] TCP Connection timeout setting + * @param {number} [options.socketTimeout=360000] TCP Socket timeout setting + * @param {number} [options.monitoringSocketTimeout=30000] TCP Socket timeout setting for replicaset monitoring socket + * @param {boolean} [options.ssl=false] Use SSL for connection + * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. + * @param {Buffer} [options.ca] SSL Certificate store binary buffer + * @param {Buffer} [options.crl] SSL Certificate revocation store binary buffer + * @param {Buffer} [options.cert] SSL Certificate binary buffer + * @param {Buffer} [options.key] SSL Key file binary buffer + * @param {string} [options.passphrase] SSL Certificate pass phrase + * @param {boolean} [options.rejectUnauthorized=false] Reject unauthorized server certificates + * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits + * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. + * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. + * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. + * @fires Pool#connect + * @fires Pool#close + * @fires Pool#error + * @fires Pool#timeout + * @fires Pool#parseError + * @return {Pool} A cursor instance + */ +var Pool = function(topology, options) { + // Add event listener + EventEmitter.call(this); + + // Store topology for later use + this.topology = topology; + + // Add the options + this.options = Object.assign( + { + // Host and port settings + host: 'localhost', + port: 27017, + // Pool default max size + size: 5, + // Pool default min size + minSize: 0, + // socket settings + connectionTimeout: 30000, + socketTimeout: 360000, + keepAlive: true, + keepAliveInitialDelay: 300000, + noDelay: true, + // SSL Settings + ssl: false, + checkServerIdentity: true, + ca: null, + crl: null, + cert: null, + key: null, + passphrase: null, + rejectUnauthorized: false, + promoteLongs: true, + promoteValues: true, + promoteBuffers: false, + // Reconnection options + reconnect: true, + reconnectInterval: 1000, + reconnectTries: 30, + // Enable domains + domainsEnabled: false, + // feature flag for determining if we are running with the unified topology or not + legacyCompatMode: true + }, + options + ); + + // Identification information + this.id = _id++; + // Current reconnect retries + this.retriesLeft = this.options.reconnectTries; + this.reconnectId = null; + this.reconnectError = null; + // No bson parser passed in + if ( + !options.bson || + (options.bson && + (typeof options.bson.serialize !== 'function' || + typeof options.bson.deserialize !== 'function')) + ) { + throw new Error('must pass in valid bson parser'); + } + + // Logger instance + this.logger = Logger('Pool', options); + // Pool state + this.state = DISCONNECTED; + // Connections + this.availableConnections = []; + this.inUseConnections = []; + this.connectingConnections = 0; + // Currently executing + this.executing = false; + // Operation work queue + this.queue = []; + + // Number of consecutive timeouts caught + this.numberOfConsecutiveTimeouts = 0; + // Current pool Index + this.connectionIndex = 0; + + // event handlers + const pool = this; + this._messageHandler = messageHandler(this); + this._connectionCloseHandler = function(err) { + const connection = this; + connectionFailureHandler(pool, 'close', err, connection); + }; + + this._connectionErrorHandler = function(err) { + const connection = this; + connectionFailureHandler(pool, 'error', err, connection); + }; + + this._connectionTimeoutHandler = function(err) { + const connection = this; + connectionFailureHandler(pool, 'timeout', err, connection); + }; + + this._connectionParseErrorHandler = function(err) { + const connection = this; + connectionFailureHandler(pool, 'parseError', err, connection); + }; +}; + +inherits(Pool, EventEmitter); + +Object.defineProperty(Pool.prototype, 'size', { + enumerable: true, + get: function() { + return this.options.size; + } +}); + +Object.defineProperty(Pool.prototype, 'minSize', { + enumerable: true, + get: function() { + return this.options.minSize; + } +}); + +Object.defineProperty(Pool.prototype, 'connectionTimeout', { + enumerable: true, + get: function() { + return this.options.connectionTimeout; + } +}); + +Object.defineProperty(Pool.prototype, 'socketTimeout', { + enumerable: true, + get: function() { + return this.options.socketTimeout; + } +}); + +// clears all pool state +function resetPoolState(pool) { + pool.inUseConnections = []; + pool.availableConnections = []; + pool.connectingConnections = 0; + pool.executing = false; + pool.numberOfConsecutiveTimeouts = 0; + pool.connectionIndex = 0; + pool.retriesLeft = pool.options.reconnectTries; + pool.reconnectId = null; +} + +function stateTransition(self, newState) { + var legalTransitions = { + disconnected: [CONNECTING, DESTROYING, DISCONNECTED], + connecting: [CONNECTING, DESTROYING, CONNECTED, DISCONNECTED], + connected: [CONNECTED, DISCONNECTED, DESTROYING], + destroying: [DESTROYING, DESTROYED], + destroyed: [DESTROYED] + }; + + // Get current state + var legalStates = legalTransitions[self.state]; + if (legalStates && legalStates.indexOf(newState) !== -1) { + self.emit('stateChanged', self.state, newState); + self.state = newState; + } else { + self.logger.error( + f( + 'Pool with id [%s] failed attempted illegal state transition from [%s] to [%s] only following state allowed [%s]', + self.id, + self.state, + newState, + legalStates + ) + ); + } +} + +function connectionFailureHandler(pool, event, err, conn) { + if (conn) { + if (conn._connectionFailHandled) return; + conn._connectionFailHandled = true; + conn.destroy(); + + // Remove the connection + removeConnection(pool, conn); + + // Flush all work Items on this connection + while (conn.workItems.length > 0) { + const workItem = conn.workItems.shift(); + if (workItem.cb) workItem.cb(err); + } + } + + // Did we catch a timeout, increment the numberOfConsecutiveTimeouts + if (event === 'timeout') { + pool.numberOfConsecutiveTimeouts = pool.numberOfConsecutiveTimeouts + 1; + + // Have we timed out more than reconnectTries in a row ? + // Force close the pool as we are trying to connect to tcp sink hole + if (pool.numberOfConsecutiveTimeouts > pool.options.reconnectTries) { + pool.numberOfConsecutiveTimeouts = 0; + // Destroy all connections and pool + pool.destroy(true); + // Emit close event + return pool.emit('close', pool); + } + } + + // No more socket available propegate the event + if (pool.socketCount() === 0) { + if (pool.state !== DESTROYED && pool.state !== DESTROYING) { + stateTransition(pool, DISCONNECTED); + } + + // Do not emit error events, they are always close events + // do not trigger the low level error handler in node + event = event === 'error' ? 'close' : event; + pool.emit(event, err); + } + + // Start reconnection attempts + if (!pool.reconnectId && pool.options.reconnect) { + pool.reconnectError = err; + pool.reconnectId = setTimeout(attemptReconnect(pool), pool.options.reconnectInterval); + } + + // Do we need to do anything to maintain the minimum pool size + const totalConnections = totalConnectionCount(pool); + if (totalConnections < pool.minSize) { + createConnection(pool); + } +} + +function attemptReconnect(pool, callback) { + return function() { + pool.emit('attemptReconnect', pool); + + if (pool.state === DESTROYED || pool.state === DESTROYING) { + if (typeof callback === 'function') { + callback(new MongoError('Cannot create connection when pool is destroyed')); + } + + return; + } + + pool.retriesLeft = pool.retriesLeft - 1; + if (pool.retriesLeft <= 0) { + pool.destroy(); + + const error = new MongoTimeoutError( + `failed to reconnect after ${pool.options.reconnectTries} attempts with interval ${ + pool.options.reconnectInterval + } ms`, + pool.reconnectError + ); + + pool.emit('reconnectFailed', error); + if (typeof callback === 'function') { + callback(error); + } + + return; + } + + // clear the reconnect id on retry + pool.reconnectId = null; + + // now retry creating a connection + createConnection(pool, (err, conn) => { + if (err == null) { + pool.reconnectId = null; + pool.retriesLeft = pool.options.reconnectTries; + pool.emit('reconnect', pool); + } + + if (typeof callback === 'function') { + callback(err, conn); + } + }); + }; +} + +function moveConnectionBetween(connection, from, to) { + var index = from.indexOf(connection); + // Move the connection from connecting to available + if (index !== -1) { + from.splice(index, 1); + to.push(connection); + } +} + +function messageHandler(self) { + return function(message, connection) { + // workItem to execute + var workItem = null; + + // Locate the workItem + for (var i = 0; i < connection.workItems.length; i++) { + if (connection.workItems[i].requestId === message.responseTo) { + // Get the callback + workItem = connection.workItems[i]; + // Remove from list of workItems + connection.workItems.splice(i, 1); + } + } + + if (workItem && workItem.monitoring) { + moveConnectionBetween(connection, self.inUseConnections, self.availableConnections); + } + + // Reset timeout counter + self.numberOfConsecutiveTimeouts = 0; + + // Reset the connection timeout if we modified it for + // this operation + if (workItem && workItem.socketTimeout) { + connection.resetSocketTimeout(); + } + + // Log if debug enabled + if (self.logger.isDebug()) { + self.logger.debug( + f( + 'message [%s] received from %s:%s', + message.raw.toString('hex'), + self.options.host, + self.options.port + ) + ); + } + + function handleOperationCallback(self, cb, err, result) { + // No domain enabled + if (!self.options.domainsEnabled) { + return process.nextTick(function() { + return cb(err, result); + }); + } + + // Domain enabled just call the callback + cb(err, result); + } + + // Keep executing, ensure current message handler does not stop execution + if (!self.executing) { + process.nextTick(function() { + _execute(self)(); + }); + } + + // Time to dispatch the message if we have a callback + if (workItem && !workItem.immediateRelease) { + try { + // Parse the message according to the provided options + message.parse(workItem); + } catch (err) { + return handleOperationCallback(self, workItem.cb, new MongoError(err)); + } + + if (message.documents[0]) { + const document = message.documents[0]; + const session = workItem.session; + if (session) { + updateSessionFromResponse(session, document); + } + + if (document.$clusterTime) { + self.topology.clusterTime = document.$clusterTime; + } + } + + // Establish if we have an error + if (workItem.command && message.documents[0]) { + const responseDoc = message.documents[0]; + + if (responseDoc.writeConcernError) { + const err = new MongoWriteConcernError(responseDoc.writeConcernError, responseDoc); + return handleOperationCallback(self, workItem.cb, err); + } + + if (responseDoc.ok === 0 || responseDoc.$err || responseDoc.errmsg || responseDoc.code) { + return handleOperationCallback(self, workItem.cb, new MongoError(responseDoc)); + } + } + + // Add the connection details + message.hashedName = connection.hashedName; + + // Return the documents + handleOperationCallback( + self, + workItem.cb, + null, + new CommandResult(workItem.fullResult ? message : message.documents[0], connection, message) + ); + } + }; +} + +/** + * Return the total socket count in the pool. + * @method + * @return {Number} The number of socket available. + */ +Pool.prototype.socketCount = function() { + return this.availableConnections.length + this.inUseConnections.length; + // + this.connectingConnections.length; +}; + +function totalConnectionCount(pool) { + return ( + pool.availableConnections.length + pool.inUseConnections.length + pool.connectingConnections + ); +} + +/** + * Return all pool connections + * @method + * @return {Connection[]} The pool connections + */ +Pool.prototype.allConnections = function() { + return this.availableConnections.concat(this.inUseConnections); +}; + +/** + * Get a pool connection (round-robin) + * @method + * @return {Connection} + */ +Pool.prototype.get = function() { + return this.allConnections()[0]; +}; + +/** + * Is the pool connected + * @method + * @return {boolean} + */ +Pool.prototype.isConnected = function() { + // We are in a destroyed state + if (this.state === DESTROYED || this.state === DESTROYING) { + return false; + } + + // Get connections + var connections = this.availableConnections.concat(this.inUseConnections); + + // Check if we have any connected connections + for (var i = 0; i < connections.length; i++) { + if (connections[i].isConnected()) return true; + } + + // Not connected + return false; +}; + +/** + * Was the pool destroyed + * @method + * @return {boolean} + */ +Pool.prototype.isDestroyed = function() { + return this.state === DESTROYED || this.state === DESTROYING; +}; + +/** + * Is the pool in a disconnected state + * @method + * @return {boolean} + */ +Pool.prototype.isDisconnected = function() { + return this.state === DISCONNECTED; +}; + +/** + * Connect pool + */ +Pool.prototype.connect = function() { + if (this.state !== DISCONNECTED) { + throw new MongoError('connection in unlawful state ' + this.state); + } + + stateTransition(this, CONNECTING); + createConnection(this, (err, conn) => { + if (err) { + if (this.state === CONNECTING) { + this.emit('error', err); + } + + this.destroy(); + return; + } + + stateTransition(this, CONNECTED); + this.emit('connect', this, conn); + + // create min connections + if (this.minSize) { + for (let i = 0; i < this.minSize; i++) { + createConnection(this); + } + } + }); +}; + +/** + * Authenticate using a specified mechanism + * @param {authResultCallback} callback A callback function + */ +Pool.prototype.auth = function(credentials, callback) { + if (typeof callback === 'function') callback(null, null); +}; + +/** + * Logout all users against a database + * @param {authResultCallback} callback A callback function + */ +Pool.prototype.logout = function(dbName, callback) { + if (typeof callback === 'function') callback(null, null); +}; + +/** + * Unref the pool + * @method + */ +Pool.prototype.unref = function() { + // Get all the known connections + var connections = this.availableConnections.concat(this.inUseConnections); + + connections.forEach(function(c) { + c.unref(); + }); +}; + +// Destroy the connections +function destroy(self, connections, options, callback) { + eachAsync( + connections, + (conn, cb) => { + for (const eventName of CONNECTION_EVENTS) { + conn.removeAllListeners(eventName); + } + + conn.destroy(options, cb); + }, + err => { + if (err) { + if (typeof callback === 'function') callback(err, null); + return; + } + + resetPoolState(self); + self.queue = []; + + stateTransition(self, DESTROYED); + if (typeof callback === 'function') callback(null, null); + } + ); +} + +/** + * Destroy pool + * @method + */ +Pool.prototype.destroy = function(force, callback) { + var self = this; + // Do not try again if the pool is already dead + if (this.state === DESTROYED || self.state === DESTROYING) { + if (typeof callback === 'function') callback(null, null); + return; + } + + // Set state to destroyed + stateTransition(this, DESTROYING); + + // Are we force closing + if (force) { + // Get all the known connections + var connections = self.availableConnections.concat(self.inUseConnections); + + // Flush any remaining work items with + // an error + while (self.queue.length > 0) { + var workItem = self.queue.shift(); + if (typeof workItem.cb === 'function') { + workItem.cb(new MongoError('Pool was force destroyed')); + } + } + + // Destroy the topology + return destroy(self, connections, { force: true }, callback); + } + + // Clear out the reconnect if set + if (this.reconnectId) { + clearTimeout(this.reconnectId); + } + + // Wait for the operations to drain before we close the pool + function checkStatus() { + flushMonitoringOperations(self.queue); + + if (self.queue.length === 0) { + // Get all the known connections + var connections = self.availableConnections.concat(self.inUseConnections); + + // Check if we have any in flight operations + for (var i = 0; i < connections.length; i++) { + // There is an operation still in flight, reschedule a + // check waiting for it to drain + if (connections[i].workItems.length > 0) { + return setTimeout(checkStatus, 1); + } + } + + destroy(self, connections, { force: false }, callback); + // } else if (self.queue.length > 0 && !this.reconnectId) { + } else { + // Ensure we empty the queue + _execute(self)(); + // Set timeout + setTimeout(checkStatus, 1); + } + } + + // Initiate drain of operations + checkStatus(); +}; + +/** + * Reset all connections of this pool + * + * @param {function} [callback] + */ +Pool.prototype.reset = function(callback) { + const connections = this.availableConnections.concat(this.inUseConnections); + eachAsync( + connections, + (conn, cb) => { + for (const eventName of CONNECTION_EVENTS) { + conn.removeAllListeners(eventName); + } + + conn.destroy({ force: true }, cb); + }, + err => { + if (err) { + if (typeof callback === 'function') { + callback(err, null); + return; + } + } + + resetPoolState(this); + + // create an initial connection, and kick off execution again + createConnection(this); + + if (typeof callback === 'function') { + callback(null, null); + } + } + ); +}; + +// Prepare the buffer that Pool.prototype.write() uses to send to the server +function serializeCommand(self, command, callback) { + const originalCommandBuffer = command.toBin(); + + // Check whether we and the server have agreed to use a compressor + const shouldCompress = !!self.options.agreedCompressor; + if (!shouldCompress || !canCompress(command)) { + return callback(null, originalCommandBuffer); + } + + // Transform originalCommandBuffer into OP_COMPRESSED + const concatenatedOriginalCommandBuffer = Buffer.concat(originalCommandBuffer); + const messageToBeCompressed = concatenatedOriginalCommandBuffer.slice(MESSAGE_HEADER_SIZE); + + // Extract information needed for OP_COMPRESSED from the uncompressed message + const originalCommandOpCode = concatenatedOriginalCommandBuffer.readInt32LE(12); + + // Compress the message body + compress(self, messageToBeCompressed, function(err, compressedMessage) { + if (err) return callback(err, null); + + // Create the msgHeader of OP_COMPRESSED + const msgHeader = Buffer.alloc(MESSAGE_HEADER_SIZE); + msgHeader.writeInt32LE( + MESSAGE_HEADER_SIZE + COMPRESSION_DETAILS_SIZE + compressedMessage.length, + 0 + ); // messageLength + msgHeader.writeInt32LE(command.requestId, 4); // requestID + msgHeader.writeInt32LE(0, 8); // responseTo (zero) + msgHeader.writeInt32LE(opcodes.OP_COMPRESSED, 12); // opCode + + // Create the compression details of OP_COMPRESSED + const compressionDetails = Buffer.alloc(COMPRESSION_DETAILS_SIZE); + compressionDetails.writeInt32LE(originalCommandOpCode, 0); // originalOpcode + compressionDetails.writeInt32LE(messageToBeCompressed.length, 4); // Size of the uncompressed compressedMessage, excluding the MsgHeader + compressionDetails.writeUInt8(compressorIDs[self.options.agreedCompressor], 8); // compressorID + + return callback(null, [msgHeader, compressionDetails, compressedMessage]); + }); +} + +/** + * Write a message to MongoDB + * @method + * @return {Connection} + */ +Pool.prototype.write = function(command, options, cb) { + var self = this; + // Ensure we have a callback + if (typeof options === 'function') { + cb = options; + } + + // Always have options + options = options || {}; + + // We need to have a callback function unless the message returns no response + if (!(typeof cb === 'function') && !options.noResponse) { + throw new MongoError('write method must provide a callback'); + } + + // Pool was destroyed error out + if (this.state === DESTROYED || this.state === DESTROYING) { + // Callback with an error + if (cb) { + try { + cb(new MongoError('pool destroyed')); + } catch (err) { + process.nextTick(function() { + throw err; + }); + } + } + + return; + } + + if (this.options.domainsEnabled && process.domain && typeof cb === 'function') { + // if we have a domain bind to it + var oldCb = cb; + cb = process.domain.bind(function() { + // v8 - argumentsToArray one-liner + var args = new Array(arguments.length); + for (var i = 0; i < arguments.length; i++) { + args[i] = arguments[i]; + } + // bounce off event loop so domain switch takes place + process.nextTick(function() { + oldCb.apply(null, args); + }); + }); + } + + // Do we have an operation + var operation = { + cb: cb, + raw: false, + promoteLongs: true, + promoteValues: true, + promoteBuffers: false, + fullResult: false + }; + + // Set the options for the parsing + operation.promoteLongs = typeof options.promoteLongs === 'boolean' ? options.promoteLongs : true; + operation.promoteValues = + typeof options.promoteValues === 'boolean' ? options.promoteValues : true; + operation.promoteBuffers = + typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : false; + operation.raw = typeof options.raw === 'boolean' ? options.raw : false; + operation.immediateRelease = + typeof options.immediateRelease === 'boolean' ? options.immediateRelease : false; + operation.documentsReturnedIn = options.documentsReturnedIn; + operation.command = typeof options.command === 'boolean' ? options.command : false; + operation.fullResult = typeof options.fullResult === 'boolean' ? options.fullResult : false; + operation.noResponse = typeof options.noResponse === 'boolean' ? options.noResponse : false; + operation.session = options.session || null; + + // Optional per operation socketTimeout + operation.socketTimeout = options.socketTimeout; + operation.monitoring = options.monitoring; + // Custom socket Timeout + if (options.socketTimeout) { + operation.socketTimeout = options.socketTimeout; + } + + // Get the requestId + operation.requestId = command.requestId; + + // If command monitoring is enabled we need to modify the callback here + if (self.options.monitorCommands) { + this.emit('commandStarted', new apm.CommandStartedEvent(this, command)); + + operation.started = process.hrtime(); + operation.cb = (err, reply) => { + if (err) { + self.emit( + 'commandFailed', + new apm.CommandFailedEvent(this, command, err, operation.started) + ); + } else { + if (reply && reply.result && (reply.result.ok === 0 || reply.result.$err)) { + self.emit( + 'commandFailed', + new apm.CommandFailedEvent(this, command, reply.result, operation.started) + ); + } else { + self.emit( + 'commandSucceeded', + new apm.CommandSucceededEvent(this, command, reply, operation.started) + ); + } + } + + if (typeof cb === 'function') cb(err, reply); + }; + } + + // Prepare the operation buffer + serializeCommand(self, command, (err, serializedBuffers) => { + if (err) throw err; + + // Set the operation's buffer to the serialization of the commands + operation.buffer = serializedBuffers; + + // If we have a monitoring operation schedule as the very first operation + // Otherwise add to back of queue + if (options.monitoring) { + self.queue.unshift(operation); + } else { + self.queue.push(operation); + } + + // Attempt to execute the operation + if (!self.executing) { + process.nextTick(function() { + _execute(self)(); + }); + } + }); +}; + +// Return whether a command contains an uncompressible command term +// Will return true if command contains no uncompressible command terms +function canCompress(command) { + const commandDoc = command instanceof Msg ? command.command : command.query; + const commandName = Object.keys(commandDoc)[0]; + return uncompressibleCommands.indexOf(commandName) === -1; +} + +// Remove connection method +function remove(connection, connections) { + for (var i = 0; i < connections.length; i++) { + if (connections[i] === connection) { + connections.splice(i, 1); + return true; + } + } +} + +function removeConnection(self, connection) { + if (remove(connection, self.availableConnections)) return; + if (remove(connection, self.inUseConnections)) return; +} + +function createConnection(pool, callback) { + if (pool.state === DESTROYED || pool.state === DESTROYING) { + if (typeof callback === 'function') { + callback(new MongoError('Cannot create connection when pool is destroyed')); + } + + return; + } + + pool.connectingConnections++; + connect(pool.options, (err, connection) => { + pool.connectingConnections--; + + if (err) { + if (pool.logger.isDebug()) { + pool.logger.debug(`connection attempt failed with error [${JSON.stringify(err)}]`); + } + + if (pool.options.legacyCompatMode === false) { + // The unified topology uses the reported `error` from a pool to track what error + // reason is returned to the user during selection timeout. We only want to emit + // this if the pool is active because the listeners are removed on destruction. + if (pool.state !== DESTROYED && pool.state !== DESTROYING) { + pool.emit('error', err); + } + } + + // check if reconnect is enabled, and attempt retry if so + if (!pool.reconnectId && pool.options.reconnect) { + if (pool.state === CONNECTING && pool.options.legacyCompatMode) { + callback(err); + return; + } + + pool.reconnectError = err; + pool.reconnectId = setTimeout( + attemptReconnect(pool, callback), + pool.options.reconnectInterval + ); + + return; + } + + if (typeof callback === 'function') { + callback(err); + } + + return; + } + + // the pool might have been closed since we started creating the connection + if (pool.state === DESTROYED || pool.state === DESTROYING) { + if (typeof callback === 'function') { + callback(new MongoError('Pool was destroyed after connection creation')); + } + + connection.destroy(); + return; + } + + // otherwise, connect relevant event handlers and add it to our available connections + connection.on('error', pool._connectionErrorHandler); + connection.on('close', pool._connectionCloseHandler); + connection.on('timeout', pool._connectionTimeoutHandler); + connection.on('parseError', pool._connectionParseErrorHandler); + connection.on('message', pool._messageHandler); + + pool.availableConnections.push(connection); + + // if a callback was provided, return the connection + if (typeof callback === 'function') { + callback(null, connection); + } + + // immediately execute any waiting work + _execute(pool)(); + }); +} + +function flushMonitoringOperations(queue) { + for (var i = 0; i < queue.length; i++) { + if (queue[i].monitoring) { + var workItem = queue[i]; + queue.splice(i, 1); + workItem.cb( + new MongoError({ message: 'no connection available for monitoring', driver: true }) + ); + } + } +} + +function _execute(self) { + return function() { + if (self.state === DESTROYED) return; + // Already executing, skip + if (self.executing) return; + // Set pool as executing + self.executing = true; + + // New pool connections are in progress, wait them to finish + // before executing any more operation to ensure distribution of + // operations + if (self.connectingConnections > 0) { + self.executing = false; + return; + } + + // As long as we have available connections + // eslint-disable-next-line + while (true) { + // Total availble connections + const totalConnections = totalConnectionCount(self); + + // No available connections available, flush any monitoring ops + if (self.availableConnections.length === 0) { + // Flush any monitoring operations + flushMonitoringOperations(self.queue); + break; + } + + // No queue break + if (self.queue.length === 0) { + break; + } + + var connection = null; + const connections = self.availableConnections.filter(conn => conn.workItems.length === 0); + + // No connection found that has no work on it, just pick one for pipelining + if (connections.length === 0) { + connection = + self.availableConnections[self.connectionIndex++ % self.availableConnections.length]; + } else { + connection = connections[self.connectionIndex++ % connections.length]; + } + + // Is the connection connected + if (!connection.isConnected()) { + // Remove the disconnected connection + removeConnection(self, connection); + // Flush any monitoring operations in the queue, failing fast + flushMonitoringOperations(self.queue); + break; + } + + // Get the next work item + var workItem = self.queue.shift(); + + // If we are monitoring we need to use a connection that is not + // running another operation to avoid socket timeout changes + // affecting an existing operation + if (workItem.monitoring) { + var foundValidConnection = false; + + for (let i = 0; i < self.availableConnections.length; i++) { + // If the connection is connected + // And there are no pending workItems on it + // Then we can safely use it for monitoring. + if ( + self.availableConnections[i].isConnected() && + self.availableConnections[i].workItems.length === 0 + ) { + foundValidConnection = true; + connection = self.availableConnections[i]; + break; + } + } + + // No safe connection found, attempt to grow the connections + // if possible and break from the loop + if (!foundValidConnection) { + // Put workItem back on the queue + self.queue.unshift(workItem); + + // Attempt to grow the pool if it's not yet maxsize + if (totalConnections < self.options.size && self.queue.length > 0) { + // Create a new connection + createConnection(self); + } + + // Re-execute the operation + setTimeout(function() { + _execute(self)(); + }, 10); + + break; + } + } + + // Don't execute operation until we have a full pool + if (totalConnections < self.options.size) { + // Connection has work items, then put it back on the queue + // and create a new connection + if (connection.workItems.length > 0) { + // Lets put the workItem back on the list + self.queue.unshift(workItem); + // Create a new connection + createConnection(self); + // Break from the loop + break; + } + } + + // Get actual binary commands + var buffer = workItem.buffer; + + // If we are monitoring take the connection of the availableConnections + if (workItem.monitoring) { + moveConnectionBetween(connection, self.availableConnections, self.inUseConnections); + } + + // Track the executing commands on the mongo server + // as long as there is an expected response + if (!workItem.noResponse) { + connection.workItems.push(workItem); + } + + // We have a custom socketTimeout + if (!workItem.immediateRelease && typeof workItem.socketTimeout === 'number') { + connection.setSocketTimeout(workItem.socketTimeout); + } + + // Capture if write was successful + var writeSuccessful = true; + + // Put operation on the wire + if (Array.isArray(buffer)) { + for (let i = 0; i < buffer.length; i++) { + writeSuccessful = connection.write(buffer[i]); + } + } else { + writeSuccessful = connection.write(buffer); + } + + // if the command is designated noResponse, call the callback immeditely + if (workItem.noResponse && typeof workItem.cb === 'function') { + workItem.cb(null, null); + } + + if (writeSuccessful === false) { + // If write not successful put back on queue + self.queue.unshift(workItem); + // Remove the disconnected connection + removeConnection(self, connection); + // Flush any monitoring operations in the queue, failing fast + flushMonitoringOperations(self.queue); + break; + } + } + + self.executing = false; + }; +} + +// Make execution loop available for testing +Pool._execute = _execute; + +/** + * A server connect event, used to verify that the connection is up and running + * + * @event Pool#connect + * @type {Pool} + */ + +/** + * A server reconnect event, used to verify that pool reconnected. + * + * @event Pool#reconnect + * @type {Pool} + */ + +/** + * The server connection closed, all pool connections closed + * + * @event Pool#close + * @type {Pool} + */ + +/** + * The server connection caused an error, all pool connections closed + * + * @event Pool#error + * @type {Pool} + */ + +/** + * The server connection timed out, all pool connections closed + * + * @event Pool#timeout + * @type {Pool} + */ + +/** + * The driver experienced an invalid message, all pool connections closed + * + * @event Pool#parseError + * @type {Pool} + */ + +/** + * The driver attempted to reconnect + * + * @event Pool#attemptReconnect + * @type {Pool} + */ + +/** + * The driver exhausted all reconnect attempts + * + * @event Pool#reconnectFailed + * @type {Pool} + */ + +module.exports = Pool; diff --git a/scripts/node_modules/mongodb/lib/core/connection/utils.js b/scripts/node_modules/mongodb/lib/core/connection/utils.js new file mode 100644 index 00000000..2f3d889f --- /dev/null +++ b/scripts/node_modules/mongodb/lib/core/connection/utils.js @@ -0,0 +1,57 @@ +'use strict'; + +const require_optional = require('require_optional'); + +function debugOptions(debugFields, options) { + var finaloptions = {}; + debugFields.forEach(function(n) { + finaloptions[n] = options[n]; + }); + + return finaloptions; +} + +function retrieveBSON() { + var BSON = require('bson'); + BSON.native = false; + + try { + var optionalBSON = require_optional('bson-ext'); + if (optionalBSON) { + optionalBSON.native = true; + return optionalBSON; + } + } catch (err) {} // eslint-disable-line + + return BSON; +} + +// Throw an error if an attempt to use Snappy is made when Snappy is not installed +function noSnappyWarning() { + throw new Error( + 'Attempted to use Snappy compression, but Snappy is not installed. Install or disable Snappy compression and try again.' + ); +} + +// Facilitate loading Snappy optionally +function retrieveSnappy() { + var snappy = null; + try { + snappy = require_optional('snappy'); + } catch (error) {} // eslint-disable-line + if (!snappy) { + snappy = { + compress: noSnappyWarning, + uncompress: noSnappyWarning, + compressSync: noSnappyWarning, + uncompressSync: noSnappyWarning + }; + } + return snappy; +} + +module.exports = { + debugOptions, + retrieveBSON, + retrieveSnappy +}; diff --git a/scripts/node_modules/mongodb/lib/core/cursor.js b/scripts/node_modules/mongodb/lib/core/cursor.js new file mode 100644 index 00000000..f5272182 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/core/cursor.js @@ -0,0 +1,886 @@ +'use strict'; + +const Logger = require('./connection/logger'); +const retrieveBSON = require('./connection/utils').retrieveBSON; +const MongoError = require('./error').MongoError; +const MongoNetworkError = require('./error').MongoNetworkError; +const mongoErrorContextSymbol = require('./error').mongoErrorContextSymbol; +const collationNotSupported = require('./utils').collationNotSupported; +const ReadPreference = require('./topologies/read_preference'); +const isUnifiedTopology = require('./utils').isUnifiedTopology; +const executeOperation = require('../operations/execute_operation'); +const Readable = require('stream').Readable; +const SUPPORTS = require('../utils').SUPPORTS; +const MongoDBNamespace = require('../utils').MongoDBNamespace; +const OperationBase = require('../operations/operation').OperationBase; + +const BSON = retrieveBSON(); +const Long = BSON.Long; + +// Possible states for a cursor +const CursorState = { + INIT: 0, + OPEN: 1, + CLOSED: 2, + GET_MORE: 3 +}; + +// +// Handle callback (including any exceptions thrown) +function handleCallback(callback, err, result) { + try { + callback(err, result); + } catch (err) { + process.nextTick(function() { + throw err; + }); + } +} + +/** + * This is a cursor results callback + * + * @callback resultCallback + * @param {error} error An error object. Set to null if no error present + * @param {object} document + */ + +/** + * @fileOverview The **Cursor** class is an internal class that embodies a cursor on MongoDB + * allowing for iteration over the results returned from the underlying query. + * + * **CURSORS Cannot directly be instantiated** + */ + +/** + * The core cursor class. All cursors in the driver build off of this one. + * + * @property {number} cursorBatchSize The current cursorBatchSize for the cursor + * @property {number} cursorLimit The current cursorLimit for the cursor + * @property {number} cursorSkip The current cursorSkip for the cursor + */ +class CoreCursor extends Readable { + /** + * Create a new core `Cursor` instance. + * **NOTE** Not to be instantiated directly + * + * @param {object} topology The server topology instance. + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {{object}|Long} cmd The selector (can be a command or a cursorId) + * @param {object} [options=null] Optional settings. + * @param {object} [options.batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/find/| find command documentation} and {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. + * @param {array} [options.documents=[]] Initial documents list for cursor + * @param {object} [options.transforms=null] Transform methods for the cursor results + * @param {function} [options.transforms.query] Transform the value returned from the initial query + * @param {function} [options.transforms.doc] Transform each document returned from Cursor.prototype._next + */ + constructor(topology, ns, cmd, options) { + super({ objectMode: true }); + options = options || {}; + + if (ns instanceof OperationBase) { + this.operation = ns; + ns = this.operation.ns.toString(); + options = this.operation.options; + cmd = this.operation.cmd ? this.operation.cmd : {}; + } + + // Cursor pool + this.pool = null; + // Cursor server + this.server = null; + + // Do we have a not connected handler + this.disconnectHandler = options.disconnectHandler; + + // Set local values + this.bson = topology.s.bson; + this.ns = ns; + this.namespace = MongoDBNamespace.fromString(ns); + this.cmd = cmd; + this.options = options; + this.topology = topology; + + // All internal state + this.cursorState = { + cursorId: null, + cmd, + documents: options.documents || [], + cursorIndex: 0, + dead: false, + killed: false, + init: false, + notified: false, + limit: options.limit || cmd.limit || 0, + skip: options.skip || cmd.skip || 0, + batchSize: options.batchSize || cmd.batchSize || 1000, + currentLimit: 0, + // Result field name if not a cursor (contains the array of results) + transforms: options.transforms, + raw: options.raw || (cmd && cmd.raw) + }; + + if (typeof options.session === 'object') { + this.cursorState.session = options.session; + } + + // Add promoteLong to cursor state + const topologyOptions = topology.s.options; + if (typeof topologyOptions.promoteLongs === 'boolean') { + this.cursorState.promoteLongs = topologyOptions.promoteLongs; + } else if (typeof options.promoteLongs === 'boolean') { + this.cursorState.promoteLongs = options.promoteLongs; + } + + // Add promoteValues to cursor state + if (typeof topologyOptions.promoteValues === 'boolean') { + this.cursorState.promoteValues = topologyOptions.promoteValues; + } else if (typeof options.promoteValues === 'boolean') { + this.cursorState.promoteValues = options.promoteValues; + } + + // Add promoteBuffers to cursor state + if (typeof topologyOptions.promoteBuffers === 'boolean') { + this.cursorState.promoteBuffers = topologyOptions.promoteBuffers; + } else if (typeof options.promoteBuffers === 'boolean') { + this.cursorState.promoteBuffers = options.promoteBuffers; + } + + if (topologyOptions.reconnect) { + this.cursorState.reconnect = topologyOptions.reconnect; + } + + // Logger + this.logger = Logger('Cursor', topologyOptions); + + // + // Did we pass in a cursor id + if (typeof cmd === 'number') { + this.cursorState.cursorId = Long.fromNumber(cmd); + this.cursorState.lastCursorId = this.cursorState.cursorId; + } else if (cmd instanceof Long) { + this.cursorState.cursorId = cmd; + this.cursorState.lastCursorId = cmd; + } + + // TODO: remove as part of NODE-2104 + if (this.operation) { + this.operation.cursorState = this.cursorState; + } + } + + setCursorBatchSize(value) { + this.cursorState.batchSize = value; + } + + cursorBatchSize() { + return this.cursorState.batchSize; + } + + setCursorLimit(value) { + this.cursorState.limit = value; + } + + cursorLimit() { + return this.cursorState.limit; + } + + setCursorSkip(value) { + this.cursorState.skip = value; + } + + cursorSkip() { + return this.cursorState.skip; + } + + /** + * Retrieve the next document from the cursor + * @method + * @param {resultCallback} callback A callback function + */ + _next(callback) { + nextFunction(this, callback); + } + + /** + * Clone the cursor + * @method + * @return {Cursor} + */ + clone() { + return this.topology.cursor(this.ns, this.cmd, this.options); + } + + /** + * Checks if the cursor is dead + * @method + * @return {boolean} A boolean signifying if the cursor is dead or not + */ + isDead() { + return this.cursorState.dead === true; + } + + /** + * Checks if the cursor was killed by the application + * @method + * @return {boolean} A boolean signifying if the cursor was killed by the application + */ + isKilled() { + return this.cursorState.killed === true; + } + + /** + * Checks if the cursor notified it's caller about it's death + * @method + * @return {boolean} A boolean signifying if the cursor notified the callback + */ + isNotified() { + return this.cursorState.notified === true; + } + + /** + * Returns current buffered documents length + * @method + * @return {number} The number of items in the buffered documents + */ + bufferedCount() { + return this.cursorState.documents.length - this.cursorState.cursorIndex; + } + + /** + * Returns current buffered documents + * @method + * @return {Array} An array of buffered documents + */ + readBufferedDocuments(number) { + const unreadDocumentsLength = this.cursorState.documents.length - this.cursorState.cursorIndex; + const length = number < unreadDocumentsLength ? number : unreadDocumentsLength; + let elements = this.cursorState.documents.slice( + this.cursorState.cursorIndex, + this.cursorState.cursorIndex + length + ); + + // Transform the doc with passed in transformation method if provided + if (this.cursorState.transforms && typeof this.cursorState.transforms.doc === 'function') { + // Transform all the elements + for (let i = 0; i < elements.length; i++) { + elements[i] = this.cursorState.transforms.doc(elements[i]); + } + } + + // Ensure we do not return any more documents than the limit imposed + // Just return the number of elements up to the limit + if ( + this.cursorState.limit > 0 && + this.cursorState.currentLimit + elements.length > this.cursorState.limit + ) { + elements = elements.slice(0, this.cursorState.limit - this.cursorState.currentLimit); + this.kill(); + } + + // Adjust current limit + this.cursorState.currentLimit = this.cursorState.currentLimit + elements.length; + this.cursorState.cursorIndex = this.cursorState.cursorIndex + elements.length; + + // Return elements + return elements; + } + + /** + * Resets local state for this cursor instance, and issues a `killCursors` command to the server + * + * @param {resultCallback} callback A callback function + */ + kill(callback) { + // Set cursor to dead + this.cursorState.dead = true; + this.cursorState.killed = true; + // Remove documents + this.cursorState.documents = []; + + // If no cursor id just return + if ( + this.cursorState.cursorId == null || + this.cursorState.cursorId.isZero() || + this.cursorState.init === false + ) { + if (callback) callback(null, null); + return; + } + + this.server.killCursors(this.ns, this.cursorState, callback); + } + + /** + * Resets the cursor + */ + rewind() { + if (this.cursorState.init) { + if (!this.cursorState.dead) { + this.kill(); + } + + this.cursorState.currentLimit = 0; + this.cursorState.init = false; + this.cursorState.dead = false; + this.cursorState.killed = false; + this.cursorState.notified = false; + this.cursorState.documents = []; + this.cursorState.cursorId = null; + this.cursorState.cursorIndex = 0; + } + } + + // Internal methods + _read() { + if ((this.s && this.s.state === CursorState.CLOSED) || this.isDead()) { + return this.push(null); + } + + // Get the next item + this._next((err, result) => { + if (err) { + if (this.listeners('error') && this.listeners('error').length > 0) { + this.emit('error', err); + } + if (!this.isDead()) this.close(); + + // Emit end event + this.emit('end'); + return this.emit('finish'); + } + + // If we provided a transformation method + if ( + this.cursorState.streamOptions && + typeof this.cursorState.streamOptions.transform === 'function' && + result != null + ) { + return this.push(this.cursorState.streamOptions.transform(result)); + } + + // If we provided a map function + if ( + this.cursorState.transforms && + typeof this.cursorState.transforms.doc === 'function' && + result != null + ) { + return this.push(this.cursorState.transforms.doc(result)); + } + + // Return the result + this.push(result); + + if (result === null && this.isDead()) { + this.once('end', () => { + this.close(); + this.emit('finish'); + }); + } + }); + } + + _endSession(options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + options = options || {}; + + const session = this.cursorState.session; + + if (session && (options.force || session.owner === this)) { + this.cursorState.session = undefined; + + if (this.operation) { + this.operation.clearSession(); + } + + session.endSession(callback); + return true; + } + + if (callback) { + callback(); + } + + return false; + } + + _getMore(callback) { + if (this.logger.isDebug()) { + this.logger.debug(`schedule getMore call for query [${JSON.stringify(this.query)}]`); + } + + // Set the current batchSize + let batchSize = this.cursorState.batchSize; + if ( + this.cursorState.limit > 0 && + this.cursorState.currentLimit + batchSize > this.cursorState.limit + ) { + batchSize = this.cursorState.limit - this.cursorState.currentLimit; + } + + this.server.getMore(this.ns, this.cursorState, batchSize, this.options, callback); + } + + _initializeCursor(callback) { + const cursor = this; + + // NOTE: this goes away once cursors use `executeOperation` + if (isUnifiedTopology(cursor.topology) && cursor.topology.shouldCheckForSessionSupport()) { + cursor.topology.selectServer(ReadPreference.primaryPreferred, err => { + if (err) { + callback(err); + return; + } + + cursor._next(callback); + }); + + return; + } + + function done(err, result) { + if ( + cursor.cursorState.cursorId && + cursor.cursorState.cursorId.isZero() && + cursor._endSession + ) { + cursor._endSession(); + } + + if ( + cursor.cursorState.documents.length === 0 && + cursor.cursorState.cursorId && + cursor.cursorState.cursorId.isZero() && + !cursor.cmd.tailable && + !cursor.cmd.awaitData + ) { + return setCursorNotified(cursor, callback); + } + + callback(err, result); + } + + const queryCallback = (err, r) => { + if (err) { + return done(err); + } + + const result = r.message; + if (result.queryFailure) { + return done(new MongoError(result.documents[0]), null); + } + + // Check if we have a command cursor + if ( + Array.isArray(result.documents) && + result.documents.length === 1 && + (!cursor.cmd.find || (cursor.cmd.find && cursor.cmd.virtual === false)) && + (typeof result.documents[0].cursor !== 'string' || + result.documents[0]['$err'] || + result.documents[0]['errmsg'] || + Array.isArray(result.documents[0].result)) + ) { + // We have an error document, return the error + if (result.documents[0]['$err'] || result.documents[0]['errmsg']) { + return done(new MongoError(result.documents[0]), null); + } + + // We have a cursor document + if (result.documents[0].cursor != null && typeof result.documents[0].cursor !== 'string') { + const id = result.documents[0].cursor.id; + // If we have a namespace change set the new namespace for getmores + if (result.documents[0].cursor.ns) { + cursor.ns = result.documents[0].cursor.ns; + } + // Promote id to long if needed + cursor.cursorState.cursorId = typeof id === 'number' ? Long.fromNumber(id) : id; + cursor.cursorState.lastCursorId = cursor.cursorState.cursorId; + cursor.cursorState.operationTime = result.documents[0].operationTime; + + // If we have a firstBatch set it + if (Array.isArray(result.documents[0].cursor.firstBatch)) { + cursor.cursorState.documents = result.documents[0].cursor.firstBatch; //.reverse(); + } + + // Return after processing command cursor + return done(null, result); + } + + if (Array.isArray(result.documents[0].result)) { + cursor.cursorState.documents = result.documents[0].result; + cursor.cursorState.cursorId = Long.ZERO; + return done(null, result); + } + } + + // Otherwise fall back to regular find path + const cursorId = result.cursorId || 0; + cursor.cursorState.cursorId = cursorId instanceof Long ? cursorId : Long.fromNumber(cursorId); + cursor.cursorState.documents = result.documents; + cursor.cursorState.lastCursorId = result.cursorId; + + // Transform the results with passed in transformation method if provided + if ( + cursor.cursorState.transforms && + typeof cursor.cursorState.transforms.query === 'function' + ) { + cursor.cursorState.documents = cursor.cursorState.transforms.query(result); + } + + done(null, result); + }; + + if (cursor.operation) { + if (cursor.logger.isDebug()) { + cursor.logger.debug( + `issue initial query [${JSON.stringify(cursor.cmd)}] with flags [${JSON.stringify( + cursor.query + )}]` + ); + } + + executeOperation(cursor.topology, cursor.operation, (err, result) => { + if (err) { + done(err); + return; + } + + cursor.server = cursor.operation.server; + cursor.cursorState.init = true; + + // NOTE: this is a special internal method for cloning a cursor, consider removing + if (cursor.cursorState.cursorId != null) { + return done(); + } + + queryCallback(err, result); + }); + + return; + } + + // Very explicitly choose what is passed to selectServer + const serverSelectOptions = {}; + if (cursor.cursorState.session) { + serverSelectOptions.session = cursor.cursorState.session; + } + + if (cursor.operation) { + serverSelectOptions.readPreference = cursor.operation.readPreference; + } else if (cursor.options.readPreference) { + serverSelectOptions.readPreference = cursor.options.readPreference; + } + + return cursor.topology.selectServer(serverSelectOptions, (err, server) => { + if (err) { + const disconnectHandler = cursor.disconnectHandler; + if (disconnectHandler != null) { + return disconnectHandler.addObjectAndMethod( + 'cursor', + cursor, + 'next', + [callback], + callback + ); + } + + return callback(err); + } + + cursor.server = server; + cursor.cursorState.init = true; + if (collationNotSupported(cursor.server, cursor.cmd)) { + return callback(new MongoError(`server ${cursor.server.name} does not support collation`)); + } + + // NOTE: this is a special internal method for cloning a cursor, consider removing + if (cursor.cursorState.cursorId != null) { + return done(); + } + + if (cursor.logger.isDebug()) { + cursor.logger.debug( + `issue initial query [${JSON.stringify(cursor.cmd)}] with flags [${JSON.stringify( + cursor.query + )}]` + ); + } + + if (cursor.cmd.find != null) { + server.query(cursor.ns, cursor.cmd, cursor.cursorState, cursor.options, queryCallback); + return; + } + + const commandOptions = Object.assign({ session: cursor.cursorState.session }, cursor.options); + server.command(cursor.ns, cursor.cmd, commandOptions, queryCallback); + }); + } +} + +if (SUPPORTS.ASYNC_ITERATOR) { + CoreCursor.prototype[Symbol.asyncIterator] = require('../async/async_iterator').asyncIterator; +} + +/** + * Validate if the pool is dead and return error + */ +function isConnectionDead(self, callback) { + if (self.pool && self.pool.isDestroyed()) { + self.cursorState.killed = true; + const err = new MongoNetworkError( + `connection to host ${self.pool.host}:${self.pool.port} was destroyed` + ); + + _setCursorNotifiedImpl(self, () => callback(err)); + return true; + } + + return false; +} + +/** + * Validate if the cursor is dead but was not explicitly killed by user + */ +function isCursorDeadButNotkilled(self, callback) { + // Cursor is dead but not marked killed, return null + if (self.cursorState.dead && !self.cursorState.killed) { + self.cursorState.killed = true; + setCursorNotified(self, callback); + return true; + } + + return false; +} + +/** + * Validate if the cursor is dead and was killed by user + */ +function isCursorDeadAndKilled(self, callback) { + if (self.cursorState.dead && self.cursorState.killed) { + handleCallback(callback, new MongoError('cursor is dead')); + return true; + } + + return false; +} + +/** + * Validate if the cursor was killed by the user + */ +function isCursorKilled(self, callback) { + if (self.cursorState.killed) { + setCursorNotified(self, callback); + return true; + } + + return false; +} + +/** + * Mark cursor as being dead and notified + */ +function setCursorDeadAndNotified(self, callback) { + self.cursorState.dead = true; + setCursorNotified(self, callback); +} + +/** + * Mark cursor as being notified + */ +function setCursorNotified(self, callback) { + _setCursorNotifiedImpl(self, () => handleCallback(callback, null, null)); +} + +function _setCursorNotifiedImpl(self, callback) { + self.cursorState.notified = true; + self.cursorState.documents = []; + self.cursorState.cursorIndex = 0; + + if (self._endSession) { + self._endSession(undefined, () => callback()); + return; + } + + return callback(); +} + +function nextFunction(self, callback) { + // We have notified about it + if (self.cursorState.notified) { + return callback(new Error('cursor is exhausted')); + } + + // Cursor is killed return null + if (isCursorKilled(self, callback)) return; + + // Cursor is dead but not marked killed, return null + if (isCursorDeadButNotkilled(self, callback)) return; + + // We have a dead and killed cursor, attempting to call next should error + if (isCursorDeadAndKilled(self, callback)) return; + + // We have just started the cursor + if (!self.cursorState.init) { + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if (!self.topology.isConnected(self.options)) { + // Only need this for single server, because repl sets and mongos + // will always continue trying to reconnect + if (self.topology._type === 'server' && !self.topology.s.options.reconnect) { + // Reconnect is disabled, so we'll never reconnect + return callback(new MongoError('no connection available')); + } + + if (self.disconnectHandler != null) { + if (self.topology.isDestroyed()) { + // Topology was destroyed, so don't try to wait for it to reconnect + return callback(new MongoError('Topology was destroyed')); + } + + self.disconnectHandler.addObjectAndMethod('cursor', self, 'next', [callback], callback); + return; + } + } + + self._initializeCursor((err, result) => { + if (err || result === null) { + callback(err, result); + return; + } + + nextFunction(self, callback); + }); + + return; + } + + if (self.cursorState.limit > 0 && self.cursorState.currentLimit >= self.cursorState.limit) { + // Ensure we kill the cursor on the server + self.kill(); + // Set cursor in dead and notified state + return setCursorDeadAndNotified(self, callback); + } else if ( + self.cursorState.cursorIndex === self.cursorState.documents.length && + !Long.ZERO.equals(self.cursorState.cursorId) + ) { + // Ensure an empty cursor state + self.cursorState.documents = []; + self.cursorState.cursorIndex = 0; + + // Check if topology is destroyed + if (self.topology.isDestroyed()) + return callback( + new MongoNetworkError('connection destroyed, not possible to instantiate cursor') + ); + + // Check if connection is dead and return if not possible to + // execute a getMore on this connection + if (isConnectionDead(self, callback)) return; + + // Execute the next get more + self._getMore(function(err, doc, connection) { + if (err) { + if (err instanceof MongoError) { + err[mongoErrorContextSymbol].isGetMore = true; + } + + return handleCallback(callback, err); + } + + if (self.cursorState.cursorId && self.cursorState.cursorId.isZero() && self._endSession) { + self._endSession(); + } + + // Save the returned connection to ensure all getMore's fire over the same connection + self.connection = connection; + + // Tailable cursor getMore result, notify owner about it + // No attempt is made here to retry, this is left to the user of the + // core module to handle to keep core simple + if ( + self.cursorState.documents.length === 0 && + self.cmd.tailable && + Long.ZERO.equals(self.cursorState.cursorId) + ) { + // No more documents in the tailed cursor + return handleCallback( + callback, + new MongoError({ + message: 'No more documents in tailed cursor', + tailable: self.cmd.tailable, + awaitData: self.cmd.awaitData + }) + ); + } else if ( + self.cursorState.documents.length === 0 && + self.cmd.tailable && + !Long.ZERO.equals(self.cursorState.cursorId) + ) { + return nextFunction(self, callback); + } + + if (self.cursorState.limit > 0 && self.cursorState.currentLimit >= self.cursorState.limit) { + return setCursorDeadAndNotified(self, callback); + } + + nextFunction(self, callback); + }); + } else if ( + self.cursorState.documents.length === self.cursorState.cursorIndex && + self.cmd.tailable && + Long.ZERO.equals(self.cursorState.cursorId) + ) { + return handleCallback( + callback, + new MongoError({ + message: 'No more documents in tailed cursor', + tailable: self.cmd.tailable, + awaitData: self.cmd.awaitData + }) + ); + } else if ( + self.cursorState.documents.length === self.cursorState.cursorIndex && + Long.ZERO.equals(self.cursorState.cursorId) + ) { + setCursorDeadAndNotified(self, callback); + } else { + if (self.cursorState.limit > 0 && self.cursorState.currentLimit >= self.cursorState.limit) { + // Ensure we kill the cursor on the server + self.kill(); + // Set cursor in dead and notified state + return setCursorDeadAndNotified(self, callback); + } + + // Increment the current cursor limit + self.cursorState.currentLimit += 1; + + // Get the document + let doc = self.cursorState.documents[self.cursorState.cursorIndex++]; + + // Doc overflow + if (!doc || doc.$err) { + // Ensure we kill the cursor on the server + self.kill(); + // Set cursor in dead and notified state + return setCursorDeadAndNotified(self, function() { + handleCallback(callback, new MongoError(doc ? doc.$err : undefined)); + }); + } + + // Transform the doc with passed in transformation method if provided + if (self.cursorState.transforms && typeof self.cursorState.transforms.doc === 'function') { + doc = self.cursorState.transforms.doc(doc); + } + + // Return the document + handleCallback(callback, null, doc); + } +} + +module.exports = { + CursorState, + CoreCursor +}; diff --git a/scripts/node_modules/mongodb/lib/core/error.js b/scripts/node_modules/mongodb/lib/core/error.js new file mode 100644 index 00000000..d35fbbef --- /dev/null +++ b/scripts/node_modules/mongodb/lib/core/error.js @@ -0,0 +1,237 @@ +'use strict'; + +const mongoErrorContextSymbol = Symbol('mongoErrorContextSymbol'); +const maxWireVersion = require('./utils').maxWireVersion; + +/** + * Creates a new MongoError + * + * @augments Error + * @param {Error|string|object} message The error message + * @property {string} message The error message + * @property {string} stack The error call stack + */ +class MongoError extends Error { + constructor(message) { + if (message instanceof Error) { + super(message.message); + this.stack = message.stack; + } else { + if (typeof message === 'string') { + super(message); + } else { + super(message.message || message.errmsg || message.$err || 'n/a'); + for (var name in message) { + this[name] = message[name]; + } + } + + Error.captureStackTrace(this, this.constructor); + } + + this.name = 'MongoError'; + this[mongoErrorContextSymbol] = this[mongoErrorContextSymbol] || {}; + } + + /** + * Creates a new MongoError object + * + * @param {Error|string|object} options The options used to create the error. + * @return {MongoError} A MongoError instance + * @deprecated Use `new MongoError()` instead. + */ + static create(options) { + return new MongoError(options); + } + + hasErrorLabel(label) { + return this.errorLabels && this.errorLabels.indexOf(label) !== -1; + } +} + +/** + * Creates a new MongoNetworkError + * + * @param {Error|string|object} message The error message + * @property {string} message The error message + * @property {string} stack The error call stack + */ +class MongoNetworkError extends MongoError { + constructor(message) { + super(message); + this.name = 'MongoNetworkError'; + + // This is added as part of the transactions specification + this.errorLabels = ['TransientTransactionError']; + } +} + +/** + * An error used when attempting to parse a value (like a connection string) + * + * @param {Error|string|object} message The error message + * @property {string} message The error message + */ +class MongoParseError extends MongoError { + constructor(message) { + super(message); + this.name = 'MongoParseError'; + } +} + +/** + * An error signifying a timeout event + * + * @param {Error|string|object} message The error message + * @param {string|object} [reason] The reason the timeout occured + * @property {string} message The error message + * @property {string} [reason] An optional reason context for the timeout, generally an error saved during flow of monitoring and selecting servers + */ +class MongoTimeoutError extends MongoError { + constructor(message, reason) { + super(message); + this.name = 'MongoTimeoutError'; + if (reason != null) { + this.reason = reason; + } + } +} + +function makeWriteConcernResultObject(input) { + const output = Object.assign({}, input); + + if (output.ok === 0) { + output.ok = 1; + delete output.errmsg; + delete output.code; + delete output.codeName; + } + + return output; +} + +/** + * An error thrown when the server reports a writeConcernError + * + * @param {Error|string|object} message The error message + * @param {object} result The result document (provided if ok: 1) + * @property {string} message The error message + * @property {object} [result] The result document (provided if ok: 1) + */ +class MongoWriteConcernError extends MongoError { + constructor(message, result) { + super(message); + this.name = 'MongoWriteConcernError'; + + if (result != null) { + this.result = makeWriteConcernResultObject(result); + } + } +} + +// see: https://github.com/mongodb/specifications/blob/master/source/retryable-writes/retryable-writes.rst#terms +const RETRYABLE_ERROR_CODES = new Set([ + 6, // HostUnreachable + 7, // HostNotFound + 89, // NetworkTimeout + 91, // ShutdownInProgress + 189, // PrimarySteppedDown + 9001, // SocketException + 10107, // NotMaster + 11600, // InterruptedAtShutdown + 11602, // InterruptedDueToReplStateChange + 13435, // NotMasterNoSlaveOk + 13436 // NotMasterOrSecondary +]); + +/** + * Determines whether an error is something the driver should attempt to retry + * + * @param {MongoError|Error} error + */ +function isRetryableError(error) { + return ( + RETRYABLE_ERROR_CODES.has(error.code) || + error instanceof MongoNetworkError || + error.message.match(/not master/) || + error.message.match(/node is recovering/) + ); +} + +const SDAM_RECOVERING_CODES = new Set([ + 91, // ShutdownInProgress + 189, // PrimarySteppedDown + 11600, // InterruptedAtShutdown + 11602, // InterruptedDueToReplStateChange + 13436 // NotMasterOrSecondary +]); + +const SDAM_NOTMASTER_CODES = new Set([ + 10107, // NotMaster + 13435 // NotMasterNoSlaveOk +]); + +const SDAM_NODE_SHUTTING_DOWN_ERROR_CODES = new Set([ + 11600, // InterruptedAtShutdown + 91 // ShutdownInProgress +]); + +function isRecoveringError(err) { + if (err.code && SDAM_RECOVERING_CODES.has(err.code)) { + return true; + } + + return err.message.match(/not master or secondary/) || err.message.match(/node is recovering/); +} + +function isNotMasterError(err) { + if (err.code && SDAM_NOTMASTER_CODES.has(err.code)) { + return true; + } + + if (isRecoveringError(err)) { + return false; + } + + return err.message.match(/not master/); +} + +function isNodeShuttingDownError(err) { + return err.code && SDAM_NODE_SHUTTING_DOWN_ERROR_CODES.has(err.code); +} + +/** + * Determines whether SDAM can recover from a given error. If it cannot + * then the pool will be cleared, and server state will completely reset + * locally. + * + * @see https://github.com/mongodb/specifications/blob/master/source/server-discovery-and-monitoring/server-discovery-and-monitoring.rst#not-master-and-node-is-recovering + * @param {MongoError|Error} error + * @param {Server} server + */ +function isSDAMUnrecoverableError(error, server) { + if (error instanceof MongoParseError) { + return true; + } + + if (isRecoveringError(error) || isNotMasterError(error)) { + if (maxWireVersion(server) >= 8 && !isNodeShuttingDownError(error)) { + return false; + } + + return true; + } + + return false; +} + +module.exports = { + MongoError, + MongoNetworkError, + MongoParseError, + MongoTimeoutError, + MongoWriteConcernError, + mongoErrorContextSymbol, + isRetryableError, + isSDAMUnrecoverableError +}; diff --git a/scripts/node_modules/mongodb/lib/core/index.js b/scripts/node_modules/mongodb/lib/core/index.js new file mode 100644 index 00000000..8d1ca8f5 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/core/index.js @@ -0,0 +1,50 @@ +'use strict'; + +let BSON = require('bson'); +const require_optional = require('require_optional'); +const EJSON = require('./utils').retrieveEJSON(); + +try { + // Attempt to grab the native BSON parser + const BSONNative = require_optional('bson-ext'); + // If we got the native parser, use it instead of the + // Javascript one + if (BSONNative) { + BSON = BSONNative; + } +} catch (err) {} // eslint-disable-line + +module.exports = { + // Errors + MongoError: require('./error').MongoError, + MongoNetworkError: require('./error').MongoNetworkError, + MongoParseError: require('./error').MongoParseError, + MongoTimeoutError: require('./error').MongoTimeoutError, + MongoWriteConcernError: require('./error').MongoWriteConcernError, + mongoErrorContextSymbol: require('./error').mongoErrorContextSymbol, + // Core + Connection: require('./connection/connection'), + Server: require('./topologies/server'), + ReplSet: require('./topologies/replset'), + Mongos: require('./topologies/mongos'), + Logger: require('./connection/logger'), + Cursor: require('./cursor').CoreCursor, + ReadPreference: require('./topologies/read_preference'), + Sessions: require('./sessions'), + BSON: BSON, + EJSON: EJSON, + Topology: require('./sdam/topology'), + // Raw operations + Query: require('./connection/commands').Query, + // Auth mechanisms + MongoCredentials: require('./auth/mongo_credentials').MongoCredentials, + defaultAuthProviders: require('./auth/defaultAuthProviders').defaultAuthProviders, + MongoCR: require('./auth/mongocr'), + X509: require('./auth/x509'), + Plain: require('./auth/plain'), + GSSAPI: require('./auth/gssapi'), + ScramSHA1: require('./auth/scram').ScramSHA1, + ScramSHA256: require('./auth/scram').ScramSHA256, + // Utilities + parseConnectionString: require('./uri_parser') +}; diff --git a/scripts/node_modules/mongodb/lib/core/sdam/monitoring.js b/scripts/node_modules/mongodb/lib/core/sdam/monitoring.js new file mode 100644 index 00000000..15f081c8 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/core/sdam/monitoring.js @@ -0,0 +1,235 @@ +'use strict'; + +const ServerDescription = require('./server_description').ServerDescription; +const calculateDurationInMs = require('../utils').calculateDurationInMs; + +// pulled from `Server` implementation +const STATE_DISCONNECTED = 'disconnected'; +const STATE_DISCONNECTING = 'disconnecting'; + +/** + * Published when server description changes, but does NOT include changes to the RTT. + * + * @property {Object} topologyId A unique identifier for the topology + * @property {ServerAddress} address The address (host/port pair) of the server + * @property {ServerDescription} previousDescription The previous server description + * @property {ServerDescription} newDescription The new server description + */ +class ServerDescriptionChangedEvent { + constructor(topologyId, address, previousDescription, newDescription) { + Object.assign(this, { topologyId, address, previousDescription, newDescription }); + } +} + +/** + * Published when server is initialized. + * + * @property {Object} topologyId A unique identifier for the topology + * @property {ServerAddress} address The address (host/port pair) of the server + */ +class ServerOpeningEvent { + constructor(topologyId, address) { + Object.assign(this, { topologyId, address }); + } +} + +/** + * Published when server is closed. + * + * @property {ServerAddress} address The address (host/port pair) of the server + * @property {Object} topologyId A unique identifier for the topology + */ +class ServerClosedEvent { + constructor(topologyId, address) { + Object.assign(this, { topologyId, address }); + } +} + +/** + * Published when topology description changes. + * + * @property {Object} topologyId + * @property {TopologyDescription} previousDescription The old topology description + * @property {TopologyDescription} newDescription The new topology description + */ +class TopologyDescriptionChangedEvent { + constructor(topologyId, previousDescription, newDescription) { + Object.assign(this, { topologyId, previousDescription, newDescription }); + } +} + +/** + * Published when topology is initialized. + * + * @param {Object} topologyId A unique identifier for the topology + */ +class TopologyOpeningEvent { + constructor(topologyId) { + Object.assign(this, { topologyId }); + } +} + +/** + * Published when topology is closed. + * + * @param {Object} topologyId A unique identifier for the topology + */ +class TopologyClosedEvent { + constructor(topologyId) { + Object.assign(this, { topologyId }); + } +} + +/** + * Fired when the server monitor’s ismaster command is started - immediately before + * the ismaster command is serialized into raw BSON and written to the socket. + * + * @property {Object} connectionId The connection id for the command + */ +class ServerHeartbeatStartedEvent { + constructor(connectionId) { + Object.assign(this, { connectionId }); + } +} + +/** + * Fired when the server monitor’s ismaster succeeds. + * + * @param {Number} duration The execution time of the event in ms + * @param {Object} reply The command reply + * @param {Object} connectionId The connection id for the command + */ +class ServerHeartbeatSucceededEvent { + constructor(duration, reply, connectionId) { + Object.assign(this, { duration, reply, connectionId }); + } +} + +/** + * Fired when the server monitor’s ismaster fails, either with an “ok: 0” or a socket exception. + * + * @param {Number} duration The execution time of the event in ms + * @param {MongoError|Object} failure The command failure + * @param {Object} connectionId The connection id for the command + */ +class ServerHeartbeatFailedEvent { + constructor(duration, failure, connectionId) { + Object.assign(this, { duration, failure, connectionId }); + } +} + +/** + * Performs a server check as described by the SDAM spec. + * + * NOTE: This method automatically reschedules itself, so that there is always an active + * monitoring process + * + * @param {Server} server The server to monitor + */ +function monitorServer(server, options) { + options = options || {}; + const heartbeatFrequencyMS = options.heartbeatFrequencyMS || 10000; + + if (options.initial === true) { + server.s.monitorId = setTimeout(() => monitorServer(server), heartbeatFrequencyMS); + return; + } + + // executes a single check of a server + const checkServer = callback => { + let start = process.hrtime(); + + // emit a signal indicating we have started the heartbeat + server.emit('serverHeartbeatStarted', new ServerHeartbeatStartedEvent(server.name)); + + // NOTE: legacy monitoring event + process.nextTick(() => server.emit('monitoring', server)); + + server.command( + 'admin.$cmd', + { ismaster: true }, + { + monitoring: true, + socketTimeout: server.s.options.connectionTimeout || 2000 + }, + (err, result) => { + let duration = calculateDurationInMs(start); + + if (err) { + server.emit( + 'serverHeartbeatFailed', + new ServerHeartbeatFailedEvent(duration, err, server.name) + ); + + return callback(err, null); + } + + const isMaster = result.result; + server.emit( + 'serverHeartbeatSucceeded', + new ServerHeartbeatSucceededEvent(duration, isMaster, server.name) + ); + + return callback(null, isMaster); + } + ); + }; + + const successHandler = isMaster => { + server.s.monitoring = false; + + // emit an event indicating that our description has changed + server.emit('descriptionReceived', new ServerDescription(server.description.address, isMaster)); + if (server.s.state === STATE_DISCONNECTED || server.s.state === STATE_DISCONNECTING) { + return; + } + + // schedule the next monitoring process + server.s.monitorId = setTimeout(() => monitorServer(server), heartbeatFrequencyMS); + }; + + // run the actual monitoring loop + server.s.monitoring = true; + checkServer((err, isMaster) => { + if (!err) { + successHandler(isMaster); + return; + } + + // According to the SDAM specification's "Network error during server check" section, if + // an ismaster call fails we reset the server's pool. If a server was once connected, + // change its type to `Unknown` only after retrying once. + server.s.pool.reset(() => { + // otherwise re-attempt monitoring once + checkServer((error, isMaster) => { + if (error) { + server.s.monitoring = false; + + // we revert to an `Unknown` by emitting a default description with no isMaster + server.emit( + 'descriptionReceived', + new ServerDescription(server.description.address, null, { error }) + ); + + // we do not reschedule monitoring in this case + return; + } + + successHandler(isMaster); + }); + }); + }); +} + +module.exports = { + ServerDescriptionChangedEvent, + ServerOpeningEvent, + ServerClosedEvent, + TopologyDescriptionChangedEvent, + TopologyOpeningEvent, + TopologyClosedEvent, + ServerHeartbeatStartedEvent, + ServerHeartbeatSucceededEvent, + ServerHeartbeatFailedEvent, + monitorServer +}; diff --git a/scripts/node_modules/mongodb/lib/core/sdam/server.js b/scripts/node_modules/mongodb/lib/core/sdam/server.js new file mode 100644 index 00000000..abb1570a --- /dev/null +++ b/scripts/node_modules/mongodb/lib/core/sdam/server.js @@ -0,0 +1,511 @@ +'use strict'; +const EventEmitter = require('events'); +const MongoError = require('../error').MongoError; +const Pool = require('../connection/pool'); +const relayEvents = require('../utils').relayEvents; +const wireProtocol = require('../wireprotocol'); +const BSON = require('../connection/utils').retrieveBSON(); +const createClientInfo = require('../topologies/shared').createClientInfo; +const Logger = require('../connection/logger'); +const ServerDescription = require('./server_description').ServerDescription; +const ReadPreference = require('../topologies/read_preference'); +const monitorServer = require('./monitoring').monitorServer; +const MongoParseError = require('../error').MongoParseError; +const MongoNetworkError = require('../error').MongoNetworkError; +const collationNotSupported = require('../utils').collationNotSupported; +const debugOptions = require('../connection/utils').debugOptions; +const isSDAMUnrecoverableError = require('../error').isSDAMUnrecoverableError; + +// Used for filtering out fields for logging +const DEBUG_FIELDS = [ + 'reconnect', + 'reconnectTries', + 'reconnectInterval', + 'emitError', + 'cursorFactory', + 'host', + 'port', + 'size', + 'keepAlive', + 'keepAliveInitialDelay', + 'noDelay', + 'connectionTimeout', + 'checkServerIdentity', + 'socketTimeout', + 'ssl', + 'ca', + 'crl', + 'cert', + 'key', + 'rejectUnauthorized', + 'promoteLongs', + 'promoteValues', + 'promoteBuffers', + 'servername' +]; + +const STATE_DISCONNECTING = 'disconnecting'; +const STATE_DISCONNECTED = 'disconnected'; +const STATE_CONNECTING = 'connecting'; +const STATE_CONNECTED = 'connected'; + +/** + * + * @fires Server#serverHeartbeatStarted + * @fires Server#serverHeartbeatSucceeded + * @fires Server#serverHeartbeatFailed + */ +class Server extends EventEmitter { + /** + * Create a server + * + * @param {ServerDescription} description + * @param {Object} options + */ + constructor(description, options, topology) { + super(); + + this.s = { + // the server description + description, + // a saved copy of the incoming options + options, + // the server logger + logger: Logger('Server', options), + // the bson parser + bson: + options.bson || + new BSON([ + BSON.Binary, + BSON.Code, + BSON.DBRef, + BSON.Decimal128, + BSON.Double, + BSON.Int32, + BSON.Long, + BSON.Map, + BSON.MaxKey, + BSON.MinKey, + BSON.ObjectId, + BSON.BSONRegExp, + BSON.Symbol, + BSON.Timestamp + ]), + // client metadata for the initial handshake + clientInfo: createClientInfo(options), + // state variable to determine if there is an active server check in progress + monitoring: false, + // the implementation of the monitoring method + monitorFunction: options.monitorFunction || monitorServer, + // the connection pool + pool: null, + // the server state + state: STATE_DISCONNECTED, + credentials: options.credentials, + topology + }; + } + + get description() { + return this.s.description; + } + + get name() { + return this.s.description.address; + } + + get autoEncrypter() { + if (this.s.options && this.s.options.autoEncrypter) { + return this.s.options.autoEncrypter; + } + return null; + } + + /** + * Initiate server connect + */ + connect(options) { + options = options || {}; + + // do not allow connect to be called on anything that's not disconnected + if (this.s.pool && !this.s.pool.isDisconnected() && !this.s.pool.isDestroyed()) { + throw new MongoError(`Server instance in invalid state ${this.s.pool.state}`); + } + + // create a pool + const addressParts = this.description.address.split(':'); + const poolOptions = Object.assign( + { host: addressParts[0], port: parseInt(addressParts[1], 10) }, + this.s.options, + options, + { bson: this.s.bson } + ); + + // NOTE: this should only be the case if we are connecting to a single server + poolOptions.reconnect = true; + poolOptions.legacyCompatMode = false; + + this.s.pool = new Pool(this, poolOptions); + + // setup listeners + this.s.pool.on('connect', connectEventHandler(this)); + this.s.pool.on('close', errorEventHandler(this)); + this.s.pool.on('error', errorEventHandler(this)); + this.s.pool.on('parseError', parseErrorEventHandler(this)); + + // it is unclear whether consumers should even know about these events + // this.s.pool.on('timeout', timeoutEventHandler(this)); + // this.s.pool.on('reconnect', reconnectEventHandler(this)); + // this.s.pool.on('reconnectFailed', errorEventHandler(this)); + + // relay all command monitoring events + relayEvents(this.s.pool, this, ['commandStarted', 'commandSucceeded', 'commandFailed']); + + this.s.state = STATE_CONNECTING; + + // If auth settings have been provided, use them + if (options.auth) { + this.s.pool.connect.apply(this.s.pool, options.auth); + return; + } + + this.s.pool.connect(); + } + + /** + * Destroy the server connection + * + * @param {Boolean} [options.force=false] Force destroy the pool + */ + destroy(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = Object.assign({}, { force: false }, options); + + this.s.state = STATE_DISCONNECTING; + const done = err => { + this.emit('closed'); + this.s.state = STATE_DISCONNECTED; + if (typeof callback === 'function') { + callback(err, null); + } + }; + + if (!this.s.pool) { + return done(); + } + + ['close', 'error', 'timeout', 'parseError', 'connect'].forEach(event => { + this.s.pool.removeAllListeners(event); + }); + + if (this.s.monitorId) { + clearTimeout(this.s.monitorId); + } + + this.s.pool.destroy(options.force, done); + } + + /** + * Immediately schedule monitoring of this server. If there already an attempt being made + * this will be a no-op. + */ + monitor(options) { + options = options || {}; + if (this.s.state !== STATE_CONNECTED || this.s.monitoring) return; + if (this.s.monitorId) clearTimeout(this.s.monitorId); + this.s.monitorFunction(this, options); + } + + /** + * Execute a command + * + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object} cmd The command hash + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.checkKeys=false] Specify if the bson parser should validate keys. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {Boolean} [options.fullResult=false] Return the full envelope instead of just the result document. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {opResultCallback} callback A callback function + */ + command(ns, cmd, options, callback) { + if (typeof options === 'function') { + (callback = options), (options = {}), (options = options || {}); + } + + const error = basicReadValidations(this, options); + if (error) { + return callback(error, null); + } + + // Clone the options + options = Object.assign({}, options, { wireProtocolCommand: false }); + + // Debug log + if (this.s.logger.isDebug()) { + this.s.logger.debug( + `executing command [${JSON.stringify({ + ns, + cmd, + options: debugOptions(DEBUG_FIELDS, options) + })}] against ${this.name}` + ); + } + + // error if collation not supported + if (collationNotSupported(this, cmd)) { + callback(new MongoError(`server ${this.name} does not support collation`)); + return; + } + + wireProtocol.command(this, ns, cmd, options, (err, result) => { + if (err) { + if (options.session && err instanceof MongoNetworkError) { + options.session.serverSession.isDirty = true; + } + + if (isSDAMUnrecoverableError(err, this)) { + this.emit('error', err); + } + } + + callback(err, result); + }); + } + + /** + * Execute a query against the server + * + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object} cmd The command document for the query + * @param {object} options Optional settings + * @param {function} callback + */ + query(ns, cmd, cursorState, options, callback) { + wireProtocol.query(this, ns, cmd, cursorState, options, (err, result) => { + if (err) { + if (options.session && err instanceof MongoNetworkError) { + options.session.serverSession.isDirty = true; + } + + if (isSDAMUnrecoverableError(err, this)) { + this.emit('error', err); + } + } + + callback(err, result); + }); + } + + /** + * Execute a `getMore` against the server + * + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object} cursorState State data associated with the cursor calling this method + * @param {object} options Optional settings + * @param {function} callback + */ + getMore(ns, cursorState, batchSize, options, callback) { + wireProtocol.getMore(this, ns, cursorState, batchSize, options, (err, result) => { + if (err) { + if (options.session && err instanceof MongoNetworkError) { + options.session.serverSession.isDirty = true; + } + + if (isSDAMUnrecoverableError(err, this)) { + this.emit('error', err); + } + } + + callback(err, result); + }); + } + + /** + * Execute a `killCursors` command against the server + * + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object} cursorState State data associated with the cursor calling this method + * @param {function} callback + */ + killCursors(ns, cursorState, callback) { + wireProtocol.killCursors(this, ns, cursorState, (err, result) => { + if (err && isSDAMUnrecoverableError(err, this)) { + this.emit('error', err); + } + + if (typeof callback === 'function') { + callback(err, result); + } + }); + } + + /** + * Insert one or more documents + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of documents to insert + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {opResultCallback} callback A callback function + */ + insert(ns, ops, options, callback) { + executeWriteOperation({ server: this, op: 'insert', ns, ops }, options, callback); + } + + /** + * Perform one or more update operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of updates + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {opResultCallback} callback A callback function + */ + update(ns, ops, options, callback) { + executeWriteOperation({ server: this, op: 'update', ns, ops }, options, callback); + } + + /** + * Perform one or more remove operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of removes + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {opResultCallback} callback A callback function + */ + remove(ns, ops, options, callback) { + executeWriteOperation({ server: this, op: 'remove', ns, ops }, options, callback); + } +} + +Object.defineProperty(Server.prototype, 'clusterTime', { + get: function() { + return this.s.topology.clusterTime; + }, + set: function(clusterTime) { + this.s.topology.clusterTime = clusterTime; + } +}); + +function basicWriteValidations(server) { + if (!server.s.pool) { + return new MongoError('server instance is not connected'); + } + + if (server.s.pool.isDestroyed()) { + return new MongoError('server instance pool was destroyed'); + } + + return null; +} + +function basicReadValidations(server, options) { + const error = basicWriteValidations(server, options); + if (error) { + return error; + } + + if (options.readPreference && !(options.readPreference instanceof ReadPreference)) { + return new MongoError('readPreference must be an instance of ReadPreference'); + } +} + +function executeWriteOperation(args, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + // TODO: once we drop Node 4, use destructuring either here or in arguments. + const server = args.server; + const op = args.op; + const ns = args.ns; + const ops = Array.isArray(args.ops) ? args.ops : [args.ops]; + + const error = basicWriteValidations(server, options); + if (error) { + callback(error, null); + return; + } + + if (collationNotSupported(server, options)) { + callback(new MongoError(`server ${server.name} does not support collation`)); + return; + } + + return wireProtocol[op](server, ns, ops, options, (err, result) => { + if (err) { + if (options.session && err instanceof MongoNetworkError) { + options.session.serverSession.isDirty = true; + } + + if (isSDAMUnrecoverableError(err, server)) { + server.emit('error', err); + } + } + + callback(err, result); + }); +} + +function connectEventHandler(server) { + return function(pool, conn) { + const ismaster = conn.ismaster; + server.s.lastIsMasterMS = conn.lastIsMasterMS; + if (conn.agreedCompressor) { + server.s.pool.options.agreedCompressor = conn.agreedCompressor; + } + + if (conn.zlibCompressionLevel) { + server.s.pool.options.zlibCompressionLevel = conn.zlibCompressionLevel; + } + + if (conn.ismaster.$clusterTime) { + const $clusterTime = conn.ismaster.$clusterTime; + server.s.sclusterTime = $clusterTime; + } + + // log the connection event if requested + if (server.s.logger.isInfo()) { + server.s.logger.info( + `server ${server.name} connected with ismaster [${JSON.stringify(ismaster)}]` + ); + } + + // emit an event indicating that our description has changed + server.emit('descriptionReceived', new ServerDescription(server.description.address, ismaster)); + + // we are connected and handshaked (guaranteed by the pool) + server.s.state = STATE_CONNECTED; + server.emit('connect', server); + }; +} + +function errorEventHandler(server) { + return function(err) { + if (err) { + server.emit('error', new MongoNetworkError(err)); + } + + server.emit('close'); + }; +} + +function parseErrorEventHandler(server) { + return function(err) { + server.s.state = STATE_DISCONNECTED; + server.emit('error', new MongoParseError(err)); + }; +} + +module.exports = Server; diff --git a/scripts/node_modules/mongodb/lib/core/sdam/server_description.js b/scripts/node_modules/mongodb/lib/core/sdam/server_description.js new file mode 100644 index 00000000..41a5cf5b --- /dev/null +++ b/scripts/node_modules/mongodb/lib/core/sdam/server_description.js @@ -0,0 +1,163 @@ +'use strict'; + +// An enumeration of server types we know about +const ServerType = { + Standalone: 'Standalone', + Mongos: 'Mongos', + PossiblePrimary: 'PossiblePrimary', + RSPrimary: 'RSPrimary', + RSSecondary: 'RSSecondary', + RSArbiter: 'RSArbiter', + RSOther: 'RSOther', + RSGhost: 'RSGhost', + Unknown: 'Unknown' +}; + +const WRITABLE_SERVER_TYPES = new Set([ + ServerType.RSPrimary, + ServerType.Standalone, + ServerType.Mongos +]); + +const DATA_BEARING_SERVER_TYPES = new Set([ + ServerType.RSPrimary, + ServerType.RSSecondary, + ServerType.Mongos, + ServerType.Standalone +]); + +const ISMASTER_FIELDS = [ + 'minWireVersion', + 'maxWireVersion', + 'maxBsonObjectSize', + 'maxMessageSizeBytes', + 'maxWriteBatchSize', + 'compression', + 'me', + 'hosts', + 'passives', + 'arbiters', + 'tags', + 'setName', + 'setVersion', + 'electionId', + 'primary', + 'logicalSessionTimeoutMinutes', + 'saslSupportedMechs', + '__nodejs_mock_server__', + '$clusterTime' +]; + +/** + * The client's view of a single server, based on the most recent ismaster outcome. + * + * Internal type, not meant to be directly instantiated + */ +class ServerDescription { + /** + * Create a ServerDescription + * @param {String} address The address of the server + * @param {Object} [ismaster] An optional ismaster response for this server + * @param {Object} [options] Optional settings + * @param {Number} [options.roundTripTime] The round trip time to ping this server (in ms) + */ + constructor(address, ismaster, options) { + options = options || {}; + ismaster = Object.assign( + { + minWireVersion: 0, + maxWireVersion: 0, + hosts: [], + passives: [], + arbiters: [], + tags: [] + }, + ismaster + ); + + this.address = address; + this.error = options.error || null; + this.roundTripTime = options.roundTripTime || 0; + this.lastUpdateTime = Date.now(); + this.lastWriteDate = ismaster.lastWrite ? ismaster.lastWrite.lastWriteDate : null; + this.opTime = ismaster.lastWrite ? ismaster.lastWrite.opTime : null; + this.type = parseServerType(ismaster); + + // direct mappings + ISMASTER_FIELDS.forEach(field => { + if (typeof ismaster[field] !== 'undefined') this[field] = ismaster[field]; + }); + + // normalize case for hosts + if (this.me) this.me = this.me.toLowerCase(); + this.hosts = this.hosts.map(host => host.toLowerCase()); + this.passives = this.passives.map(host => host.toLowerCase()); + this.arbiters = this.arbiters.map(host => host.toLowerCase()); + } + + get allHosts() { + return this.hosts.concat(this.arbiters).concat(this.passives); + } + + /** + * @return {Boolean} Is this server available for reads + */ + get isReadable() { + return this.type === ServerType.RSSecondary || this.isWritable; + } + + /** + * @return {Boolean} Is this server data bearing + */ + get isDataBearing() { + return DATA_BEARING_SERVER_TYPES.has(this.type); + } + + /** + * @return {Boolean} Is this server available for writes + */ + get isWritable() { + return WRITABLE_SERVER_TYPES.has(this.type); + } +} + +/** + * Parses an `ismaster` message and determines the server type + * + * @param {Object} ismaster The `ismaster` message to parse + * @return {ServerType} + */ +function parseServerType(ismaster) { + if (!ismaster || !ismaster.ok) { + return ServerType.Unknown; + } + + if (ismaster.isreplicaset) { + return ServerType.RSGhost; + } + + if (ismaster.msg && ismaster.msg === 'isdbgrid') { + return ServerType.Mongos; + } + + if (ismaster.setName) { + if (ismaster.hidden) { + return ServerType.RSOther; + } else if (ismaster.ismaster) { + return ServerType.RSPrimary; + } else if (ismaster.secondary) { + return ServerType.RSSecondary; + } else if (ismaster.arbiterOnly) { + return ServerType.RSArbiter; + } else { + return ServerType.RSOther; + } + } + + return ServerType.Standalone; +} + +module.exports = { + ServerDescription, + ServerType +}; diff --git a/scripts/node_modules/mongodb/lib/core/sdam/server_selectors.js b/scripts/node_modules/mongodb/lib/core/sdam/server_selectors.js new file mode 100644 index 00000000..f26d419e --- /dev/null +++ b/scripts/node_modules/mongodb/lib/core/sdam/server_selectors.js @@ -0,0 +1,244 @@ +'use strict'; +const ServerType = require('./server_description').ServerType; +const TopologyType = require('./topology_description').TopologyType; +const ReadPreference = require('../topologies/read_preference'); +const MongoError = require('../error').MongoError; + +// max staleness constants +const IDLE_WRITE_PERIOD = 10000; +const SMALLEST_MAX_STALENESS_SECONDS = 90; + +/** + * Returns a server selector that selects for writable servers + */ +function writableServerSelector() { + return function(topologyDescription, servers) { + return latencyWindowReducer(topologyDescription, servers.filter(s => s.isWritable)); + }; +} + +/** + * Reduces the passed in array of servers by the rules of the "Max Staleness" specification + * found here: https://github.com/mongodb/specifications/blob/master/source/max-staleness/max-staleness.rst + * + * @param {ReadPreference} readPreference The read preference providing max staleness guidance + * @param {topologyDescription} topologyDescription The topology description + * @param {ServerDescription[]} servers The list of server descriptions to be reduced + * @return {ServerDescription[]} The list of servers that satisfy the requirements of max staleness + */ +function maxStalenessReducer(readPreference, topologyDescription, servers) { + if (readPreference.maxStalenessSeconds == null || readPreference.maxStalenessSeconds < 0) { + return servers; + } + + const maxStaleness = readPreference.maxStalenessSeconds; + const maxStalenessVariance = + (topologyDescription.heartbeatFrequencyMS + IDLE_WRITE_PERIOD) / 1000; + if (maxStaleness < maxStalenessVariance) { + throw new MongoError(`maxStalenessSeconds must be at least ${maxStalenessVariance} seconds`); + } + + if (maxStaleness < SMALLEST_MAX_STALENESS_SECONDS) { + throw new MongoError( + `maxStalenessSeconds must be at least ${SMALLEST_MAX_STALENESS_SECONDS} seconds` + ); + } + + if (topologyDescription.type === TopologyType.ReplicaSetWithPrimary) { + const primary = servers.filter(primaryFilter)[0]; + return servers.reduce((result, server) => { + const stalenessMS = + server.lastUpdateTime - + server.lastWriteDate - + (primary.lastUpdateTime - primary.lastWriteDate) + + topologyDescription.heartbeatFrequencyMS; + + const staleness = stalenessMS / 1000; + if (staleness <= readPreference.maxStalenessSeconds) result.push(server); + return result; + }, []); + } else if (topologyDescription.type === TopologyType.ReplicaSetNoPrimary) { + const sMax = servers.reduce((max, s) => (s.lastWriteDate > max.lastWriteDate ? s : max)); + return servers.reduce((result, server) => { + const stalenessMS = + sMax.lastWriteDate - server.lastWriteDate + topologyDescription.heartbeatFrequencyMS; + + const staleness = stalenessMS / 1000; + if (staleness <= readPreference.maxStalenessSeconds) result.push(server); + return result; + }, []); + } + + return servers; +} + +/** + * Determines whether a server's tags match a given set of tags + * + * @param {String[]} tagSet The requested tag set to match + * @param {String[]} serverTags The server's tags + */ +function tagSetMatch(tagSet, serverTags) { + const keys = Object.keys(tagSet); + const serverTagKeys = Object.keys(serverTags); + for (let i = 0; i < keys.length; ++i) { + const key = keys[i]; + if (serverTagKeys.indexOf(key) === -1 || serverTags[key] !== tagSet[key]) { + return false; + } + } + + return true; +} + +/** + * Reduces a set of server descriptions based on tags requested by the read preference + * + * @param {ReadPreference} readPreference The read preference providing the requested tags + * @param {ServerDescription[]} servers The list of server descriptions to reduce + * @return {ServerDescription[]} The list of servers matching the requested tags + */ +function tagSetReducer(readPreference, servers) { + if ( + readPreference.tags == null || + (Array.isArray(readPreference.tags) && readPreference.tags.length === 0) + ) { + return servers; + } + + for (let i = 0; i < readPreference.tags.length; ++i) { + const tagSet = readPreference.tags[i]; + const serversMatchingTagset = servers.reduce((matched, server) => { + if (tagSetMatch(tagSet, server.tags)) matched.push(server); + return matched; + }, []); + + if (serversMatchingTagset.length) { + return serversMatchingTagset; + } + } + + return []; +} + +/** + * Reduces a list of servers to ensure they fall within an acceptable latency window. This is + * further specified in the "Server Selection" specification, found here: + * https://github.com/mongodb/specifications/blob/master/source/server-selection/server-selection.rst + * + * @param {topologyDescription} topologyDescription The topology description + * @param {ServerDescription[]} servers The list of servers to reduce + * @returns {ServerDescription[]} The servers which fall within an acceptable latency window + */ +function latencyWindowReducer(topologyDescription, servers) { + const low = servers.reduce( + (min, server) => (min === -1 ? server.roundTripTime : Math.min(server.roundTripTime, min)), + -1 + ); + + const high = low + topologyDescription.localThresholdMS; + + return servers.reduce((result, server) => { + if (server.roundTripTime <= high && server.roundTripTime >= low) result.push(server); + return result; + }, []); +} + +// filters +function primaryFilter(server) { + return server.type === ServerType.RSPrimary; +} + +function secondaryFilter(server) { + return server.type === ServerType.RSSecondary; +} + +function nearestFilter(server) { + return server.type === ServerType.RSSecondary || server.type === ServerType.RSPrimary; +} + +function knownFilter(server) { + return server.type !== ServerType.Unknown; +} + +/** + * Returns a function which selects servers based on a provided read preference + * + * @param {ReadPreference} readPreference The read preference to select with + */ +function readPreferenceServerSelector(readPreference) { + if (!readPreference.isValid()) { + throw new TypeError('Invalid read preference specified'); + } + + return function(topologyDescription, servers) { + const commonWireVersion = topologyDescription.commonWireVersion; + if ( + commonWireVersion && + (readPreference.minWireVersion && readPreference.minWireVersion > commonWireVersion) + ) { + throw new MongoError( + `Minimum wire version '${ + readPreference.minWireVersion + }' required, but found '${commonWireVersion}'` + ); + } + + if ( + topologyDescription.type === TopologyType.Single || + topologyDescription.type === TopologyType.Sharded + ) { + return latencyWindowReducer(topologyDescription, servers.filter(knownFilter)); + } + + if (readPreference.mode === ReadPreference.PRIMARY) { + return servers.filter(primaryFilter); + } + + if (readPreference.mode === ReadPreference.SECONDARY) { + return latencyWindowReducer( + topologyDescription, + tagSetReducer( + readPreference, + maxStalenessReducer(readPreference, topologyDescription, servers) + ) + ).filter(secondaryFilter); + } else if (readPreference.mode === ReadPreference.NEAREST) { + return latencyWindowReducer( + topologyDescription, + tagSetReducer( + readPreference, + maxStalenessReducer(readPreference, topologyDescription, servers) + ) + ).filter(nearestFilter); + } else if (readPreference.mode === ReadPreference.SECONDARY_PREFERRED) { + const result = latencyWindowReducer( + topologyDescription, + tagSetReducer( + readPreference, + maxStalenessReducer(readPreference, topologyDescription, servers) + ) + ).filter(secondaryFilter); + + return result.length === 0 ? servers.filter(primaryFilter) : result; + } else if (readPreference.mode === ReadPreference.PRIMARY_PREFERRED) { + const result = servers.filter(primaryFilter); + if (result.length) { + return result; + } + + return latencyWindowReducer( + topologyDescription, + tagSetReducer( + readPreference, + maxStalenessReducer(readPreference, topologyDescription, servers) + ) + ).filter(secondaryFilter); + } + }; +} + +module.exports = { + writableServerSelector, + readPreferenceServerSelector +}; diff --git a/scripts/node_modules/mongodb/lib/core/sdam/srv_polling.js b/scripts/node_modules/mongodb/lib/core/sdam/srv_polling.js new file mode 100644 index 00000000..115ae45c --- /dev/null +++ b/scripts/node_modules/mongodb/lib/core/sdam/srv_polling.js @@ -0,0 +1,135 @@ +'use strict'; + +const Logger = require('../connection/logger'); +const EventEmitter = require('events').EventEmitter; +const dns = require('dns'); +/** + * Determines whether a provided address matches the provided parent domain in order + * to avoid certain attack vectors. + * + * @param {String} srvAddress The address to check against a domain + * @param {String} parentDomain The domain to check the provided address against + * @return {Boolean} Whether the provided address matches the parent domain + */ +function matchesParentDomain(srvAddress, parentDomain) { + const regex = /^.*?\./; + const srv = `.${srvAddress.replace(regex, '')}`; + const parent = `.${parentDomain.replace(regex, '')}`; + return srv.endsWith(parent); +} + +class SrvPollingEvent { + constructor(srvRecords) { + this.srvRecords = srvRecords; + } + + addresses() { + return new Set(this.srvRecords.map(record => `${record.name}:${record.port}`)); + } +} + +class SrvPoller extends EventEmitter { + /** + * @param {object} options + * @param {string} options.srvHost + * @param {number} [options.heartbeatFrequencyMS] + * @param {function} [options.logger] + * @param {string} [options.loggerLevel] + */ + constructor(options) { + super(); + + if (!options || !options.srvHost) { + throw new TypeError('options for SrvPoller must exist and include srvHost'); + } + + this.srvHost = options.srvHost; + this.rescanSrvIntervalMS = 60000; + this.heartbeatFrequencyMS = options.heartbeatFrequencyMS || 10000; + this.logger = Logger('srvPoller', options); + + this.haMode = false; + this.generation = 0; + + this._timeout = null; + } + + get srvAddress() { + return `_mongodb._tcp.${this.srvHost}`; + } + + get intervalMS() { + return this.haMode ? this.heartbeatFrequencyMS : this.rescanSrvIntervalMs; + } + + start() { + if (!this._timeout) { + this.schedule(); + } + } + + stop() { + if (this._timeout) { + clearTimeout(this._timeout); + this.generation += 1; + this._timeout = null; + } + } + + schedule() { + clearTimeout(this._timeout); + this._timeout = setTimeout(() => this._poll(), this.intervalMS); + } + + success(srvRecords) { + this.haMode = false; + this.schedule(); + this.emit('srvRecordDiscovery', new SrvPollingEvent(srvRecords)); + } + + failure(message, obj) { + this.logger.warn(message, obj); + this.haMode = true; + this.schedule(); + } + + parentDomainMismatch(srvRecord) { + this.logger.warn( + `parent domain mismatch on SRV record (${srvRecord.name}:${srvRecord.port})`, + srvRecord + ); + } + + _poll() { + const generation = this.generation; + dns.resolveSrv(this.srvAddress, (err, srvRecords) => { + if (generation !== this.generation) { + return; + } + + if (err) { + this.failure('DNS error', err); + return; + } + + const finalAddresses = []; + srvRecords.forEach(record => { + if (matchesParentDomain(record.name, this.srvHost)) { + finalAddresses.push(record); + } else { + this.parentDomainMismatch(record); + } + }); + + if (!finalAddresses.length) { + this.failure('No valid addresses found at host'); + return; + } + + this.success(finalAddresses); + }); + } +} + +module.exports.SrvPollingEvent = SrvPollingEvent; +module.exports.SrvPoller = SrvPoller; diff --git a/scripts/node_modules/mongodb/lib/core/sdam/topology.js b/scripts/node_modules/mongodb/lib/core/sdam/topology.js new file mode 100644 index 00000000..5dab4b36 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/core/sdam/topology.js @@ -0,0 +1,1186 @@ +'use strict'; +const EventEmitter = require('events'); +const ServerDescription = require('./server_description').ServerDescription; +const ServerType = require('./server_description').ServerType; +const TopologyDescription = require('./topology_description').TopologyDescription; +const TopologyType = require('./topology_description').TopologyType; +const monitoring = require('./monitoring'); +const calculateDurationInMs = require('../utils').calculateDurationInMs; +const MongoTimeoutError = require('../error').MongoTimeoutError; +const Server = require('./server'); +const relayEvents = require('../utils').relayEvents; +const ReadPreference = require('../topologies/read_preference'); +const readPreferenceServerSelector = require('./server_selectors').readPreferenceServerSelector; +const writableServerSelector = require('./server_selectors').writableServerSelector; +const isRetryableWritesSupported = require('../topologies/shared').isRetryableWritesSupported; +const CoreCursor = require('../cursor').CoreCursor; +const deprecate = require('util').deprecate; +const BSON = require('../connection/utils').retrieveBSON(); +const createCompressionInfo = require('../topologies/shared').createCompressionInfo; +const isRetryableError = require('../error').isRetryableError; +const isSDAMUnrecoverableError = require('../error').isSDAMUnrecoverableError; +const ClientSession = require('../sessions').ClientSession; +const createClientInfo = require('../topologies/shared').createClientInfo; +const MongoError = require('../error').MongoError; +const resolveClusterTime = require('../topologies/shared').resolveClusterTime; +const SrvPoller = require('./srv_polling').SrvPoller; +const getMMAPError = require('../topologies/shared').getMMAPError; + +// Global state +let globalTopologyCounter = 0; + +// Constants +const TOPOLOGY_DEFAULTS = { + localThresholdMS: 15, + serverSelectionTimeoutMS: 30000, + heartbeatFrequencyMS: 10000, + minHeartbeatFrequencyMS: 500 +}; + +// events that we relay to the `Topology` +const SERVER_RELAY_EVENTS = [ + 'serverHeartbeatStarted', + 'serverHeartbeatSucceeded', + 'serverHeartbeatFailed', + 'commandStarted', + 'commandSucceeded', + 'commandFailed', + + // NOTE: Legacy events + 'monitoring' +]; + +// all events we listen to from `Server` instances +const LOCAL_SERVER_EVENTS = SERVER_RELAY_EVENTS.concat([ + 'error', + 'connect', + 'descriptionReceived', + 'close', + 'ended' +]); + +/** + * A container of server instances representing a connection to a MongoDB topology. + * + * @fires Topology#serverOpening + * @fires Topology#serverClosed + * @fires Topology#serverDescriptionChanged + * @fires Topology#topologyOpening + * @fires Topology#topologyClosed + * @fires Topology#topologyDescriptionChanged + * @fires Topology#serverHeartbeatStarted + * @fires Topology#serverHeartbeatSucceeded + * @fires Topology#serverHeartbeatFailed + */ +class Topology extends EventEmitter { + /** + * Create a topology + * + * @param {Array|String} [seedlist] a string list, or array of Server instances to connect to + * @param {Object} [options] Optional settings + * @param {Number} [options.localThresholdMS=15] The size of the latency window for selecting among multiple suitable servers + * @param {Number} [options.serverSelectionTimeoutMS=30000] How long to block for server selection before throwing an error + * @param {Number} [options.heartbeatFrequencyMS=10000] The frequency with which topology updates are scheduled + */ + constructor(seedlist, options) { + super(); + if (typeof options === 'undefined' && typeof seedlist !== 'string') { + options = seedlist; + seedlist = []; + + // this is for legacy single server constructor support + if (options.host) { + seedlist.push({ host: options.host, port: options.port }); + } + } + + seedlist = seedlist || []; + if (typeof seedlist === 'string') { + seedlist = parseStringSeedlist(seedlist); + } + + options = Object.assign({}, TOPOLOGY_DEFAULTS, options); + + const topologyType = topologyTypeFromSeedlist(seedlist, options); + const topologyId = globalTopologyCounter++; + const serverDescriptions = seedlist.reduce((result, seed) => { + if (seed.domain_socket) seed.host = seed.domain_socket; + const address = seed.port ? `${seed.host}:${seed.port}` : `${seed.host}:27017`; + result.set(address, new ServerDescription(address)); + return result; + }, new Map()); + + this.s = { + // the id of this topology + id: topologyId, + // passed in options + options, + // initial seedlist of servers to connect to + seedlist: seedlist, + // the topology description + description: new TopologyDescription( + topologyType, + serverDescriptions, + options.replicaSet, + null, + null, + null, + options + ), + serverSelectionTimeoutMS: options.serverSelectionTimeoutMS, + heartbeatFrequencyMS: options.heartbeatFrequencyMS, + minHeartbeatIntervalMS: options.minHeartbeatIntervalMS, + // allow users to override the cursor factory + Cursor: options.cursorFactory || CoreCursor, + // the bson parser + bson: + options.bson || + new BSON([ + BSON.Binary, + BSON.Code, + BSON.DBRef, + BSON.Decimal128, + BSON.Double, + BSON.Int32, + BSON.Long, + BSON.Map, + BSON.MaxKey, + BSON.MinKey, + BSON.ObjectId, + BSON.BSONRegExp, + BSON.Symbol, + BSON.Timestamp + ]), + // a map of server instances to normalized addresses + servers: new Map(), + // Server Session Pool + sessionPool: null, + // Active client sessions + sessions: new Set(), + // Promise library + promiseLibrary: options.promiseLibrary || Promise, + credentials: options.credentials, + clusterTime: null, + + // timer management + monitorTimers: [], + iterationTimers: [] + }; + + // amend options for server instance creation + this.s.options.compression = { compressors: createCompressionInfo(options) }; + + // add client info + this.s.clientInfo = createClientInfo(options); + + if (options.srvHost) { + this.s.srvPoller = + options.srvPoller || + new SrvPoller({ + heartbeatFrequencyMS: this.s.heartbeatFrequencyMS, + srvHost: options.srvHost, // TODO: GET THIS + logger: options.logger, + loggerLevel: options.loggerLevel + }); + this.s.detectTopologyDescriptionChange = ev => { + const previousType = ev.previousDescription.type; + const newType = ev.newDescription.type; + + if (previousType !== TopologyType.Sharded && newType === TopologyType.Sharded) { + this.s.handleSrvPolling = srvPollingHandler(this); + this.s.srvPoller.on('srvRecordDiscovery', this.s.handleSrvPolling); + this.s.srvPoller.start(); + } + }; + + this.on('topologyDescriptionChanged', this.s.detectTopologyDescriptionChange); + } + } + + /** + * @return A `TopologyDescription` for this topology + */ + get description() { + return this.s.description; + } + + get parserType() { + return BSON.native ? 'c++' : 'js'; + } + + /** + * All raw connections + * @method + * @return {Connection[]} + */ + connections() { + return Array.from(this.s.servers.values()).reduce((result, server) => { + return result.concat(server.s.pool.allConnections()); + }, []); + } + + /** + * Initiate server connect + * + * @param {Object} [options] Optional settings + * @param {Array} [options.auth=null] Array of auth options to apply on connect + * @param {function} [callback] An optional callback called once on the first connected server + */ + connect(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + // emit SDAM monitoring events + this.emit('topologyOpening', new monitoring.TopologyOpeningEvent(this.s.id)); + + // emit an event for the topology change + this.emit( + 'topologyDescriptionChanged', + new monitoring.TopologyDescriptionChangedEvent( + this.s.id, + new TopologyDescription(TopologyType.Unknown), // initial is always Unknown + this.s.description + ) + ); + + connectServers(this, Array.from(this.s.description.servers.values())); + this.s.connected = true; + + // otherwise, wait for a server to properly connect based on user provided read preference, + // or primary. + + translateReadPreference(options); + const readPreference = options.readPreference || ReadPreference.primary; + + this.selectServer(readPreferenceServerSelector(readPreference), options, (err, server) => { + if (err) { + if (typeof callback === 'function') { + callback(err, null); + } else { + this.emit('error', err); + } + + return; + } + + const errorHandler = err => { + server.removeListener('connect', connectHandler); + if (typeof callback === 'function') callback(err, null); + }; + + const connectHandler = (_, err) => { + server.removeListener('error', errorHandler); + this.emit('open', err, this); + this.emit('connect', this); + + if (typeof callback === 'function') callback(err, this); + }; + + const STATE_CONNECTING = 1; + if (server.s.state === STATE_CONNECTING) { + server.once('error', errorHandler); + server.once('connect', connectHandler); + return; + } + + connectHandler(); + }); + } + + /** + * Close this topology + */ + close(options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + + if (typeof options === 'boolean') { + options = { force: options }; + } + + options = options || {}; + + // clear all existing monitor timers + this.s.monitorTimers.map(timer => clearTimeout(timer)); + this.s.monitorTimers = []; + + this.s.iterationTimers.map(timer => clearTimeout(timer)); + this.s.iterationTimers = []; + + if (this.s.sessionPool) { + this.s.sessions.forEach(session => session.endSession()); + this.s.sessionPool.endAllPooledSessions(); + } + + if (this.s.srvPoller) { + this.s.srvPoller.stop(); + if (this.s.handleSrvPolling) { + this.s.srvPoller.removeListener('srvRecordDiscovery', this.s.handleSrvPolling); + delete this.s.handleSrvPolling; + } + } + + if (this.s.detectTopologyDescriptionChange) { + this.removeListener('topologyDescriptionChanged', this.s.detectTopologyDescriptionChange); + delete this.s.detectTopologyDescriptionChange; + } + + const servers = this.s.servers; + if (servers.size === 0) { + this.s.connected = false; + if (typeof callback === 'function') { + callback(null, null); + } + + return; + } + + // destroy all child servers + let destroyed = 0; + servers.forEach(server => + destroyServer(server, this, options, () => { + destroyed++; + if (destroyed === servers.size) { + // emit an event for close + this.emit('topologyClosed', new monitoring.TopologyClosedEvent(this.s.id)); + + this.s.connected = false; + if (typeof callback === 'function') { + callback(null, null); + } + } + }) + ); + } + + /** + * Selects a server according to the selection predicate provided + * + * @param {function} [selector] An optional selector to select servers by, defaults to a random selection within a latency window + * @param {object} [options] Optional settings related to server selection + * @param {number} [options.serverSelectionTimeoutMS] How long to block for server selection before throwing an error + * @param {function} callback The callback used to indicate success or failure + * @return {Server} An instance of a `Server` meeting the criteria of the predicate provided + */ + selectServer(selector, options, callback) { + if (typeof options === 'function') { + callback = options; + if (typeof selector !== 'function') { + options = selector; + + let readPreference; + if (selector instanceof ReadPreference) { + readPreference = selector; + } else { + translateReadPreference(options); + readPreference = options.readPreference || ReadPreference.primary; + } + + selector = readPreferenceServerSelector(readPreference); + } else { + options = {}; + } + } + + options = Object.assign( + {}, + { serverSelectionTimeoutMS: this.s.serverSelectionTimeoutMS }, + options + ); + + const isSharded = this.description.type === TopologyType.Sharded; + const session = options.session; + const transaction = session && session.transaction; + + if (isSharded && transaction && transaction.server) { + callback(null, transaction.server); + return; + } + + // clear out any existing iteration timers + this.s.iterationTimers.map(timer => clearTimeout(timer)); + this.s.iterationTimers = []; + + selectServers( + this, + selector, + options.serverSelectionTimeoutMS, + process.hrtime(), + (err, servers) => { + if (err) return callback(err, null); + + const selectedServer = randomSelection(servers); + if (isSharded && transaction && transaction.isActive) { + transaction.pinServer(selectedServer); + } + + callback(null, selectedServer); + } + ); + } + + // Sessions related methods + + /** + * @return Whether the topology should initiate selection to determine session support + */ + shouldCheckForSessionSupport() { + return ( + (this.description.type === TopologyType.Single && !this.description.hasKnownServers) || + !this.description.hasDataBearingServers + ); + } + + /** + * @return Whether sessions are supported on the current topology + */ + hasSessionSupport() { + return this.description.logicalSessionTimeoutMinutes != null; + } + + /** + * Start a logical session + */ + startSession(options, clientOptions) { + const session = new ClientSession(this, this.s.sessionPool, options, clientOptions); + session.once('ended', () => { + this.s.sessions.delete(session); + }); + + this.s.sessions.add(session); + return session; + } + + /** + * Send endSessions command(s) with the given session ids + * + * @param {Array} sessions The sessions to end + * @param {function} [callback] + */ + endSessions(sessions, callback) { + if (!Array.isArray(sessions)) { + sessions = [sessions]; + } + + this.command( + 'admin.$cmd', + { endSessions: sessions }, + { readPreference: ReadPreference.primaryPreferred, noResponse: true }, + () => { + // intentionally ignored, per spec + if (typeof callback === 'function') callback(); + } + ); + } + + /** + * Update the internal TopologyDescription with a ServerDescription + * + * @param {object} serverDescription The server to update in the internal list of server descriptions + */ + serverUpdateHandler(serverDescription) { + if (!this.s.description.hasServer(serverDescription.address)) { + return; + } + + // these will be used for monitoring events later + const previousTopologyDescription = this.s.description; + const previousServerDescription = this.s.description.servers.get(serverDescription.address); + + // first update the TopologyDescription + this.s.description = this.s.description.update(serverDescription); + if (this.s.description.compatibilityError) { + this.emit('error', new MongoError(this.s.description.compatibilityError)); + return; + } + + // emit monitoring events for this change + this.emit( + 'serverDescriptionChanged', + new monitoring.ServerDescriptionChangedEvent( + this.s.id, + serverDescription.address, + previousServerDescription, + this.s.description.servers.get(serverDescription.address) + ) + ); + + // update server list from updated descriptions + updateServers(this, serverDescription); + + // Driver Sessions Spec: "Whenever a driver receives a cluster time from + // a server it MUST compare it to the current highest seen cluster time + // for the deployment. If the new cluster time is higher than the + // highest seen cluster time it MUST become the new highest seen cluster + // time. Two cluster times are compared using only the BsonTimestamp + // value of the clusterTime embedded field." + const clusterTime = serverDescription.$clusterTime; + if (clusterTime) { + resolveClusterTime(this, clusterTime); + } + + this.emit( + 'topologyDescriptionChanged', + new monitoring.TopologyDescriptionChangedEvent( + this.s.id, + previousTopologyDescription, + this.s.description + ) + ); + } + + auth(credentials, callback) { + if (typeof credentials === 'function') (callback = credentials), (credentials = null); + if (typeof callback === 'function') callback(null, true); + } + + logout(callback) { + if (typeof callback === 'function') callback(null, true); + } + + // Basic operation support. Eventually this should be moved into command construction + // during the command refactor. + + /** + * Insert one or more documents + * + * @param {String} ns The full qualified namespace for this operation + * @param {Array} ops An array of documents to insert + * @param {Boolean} [options.ordered=true] Execute in order or out of order + * @param {Object} [options.writeConcern] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields + * @param {ClientSession} [options.session] Session to use for the operation + * @param {boolean} [options.retryWrites] Enable retryable writes for this operation + * @param {opResultCallback} callback A callback function + */ + insert(ns, ops, options, callback) { + executeWriteOperation({ topology: this, op: 'insert', ns, ops }, options, callback); + } + + /** + * Perform one or more update operations + * + * @param {string} ns The fully qualified namespace for this operation + * @param {array} ops An array of updates + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields + * @param {ClientSession} [options.session] Session to use for the operation + * @param {boolean} [options.retryWrites] Enable retryable writes for this operation + * @param {opResultCallback} callback A callback function + */ + update(ns, ops, options, callback) { + executeWriteOperation({ topology: this, op: 'update', ns, ops }, options, callback); + } + + /** + * Perform one or more remove operations + * + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of removes + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {boolean} [options.retryWrites] Enable retryable writes for this operation + * @param {opResultCallback} callback A callback function + */ + remove(ns, ops, options, callback) { + executeWriteOperation({ topology: this, op: 'remove', ns, ops }, options, callback); + } + + /** + * Execute a command + * + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object} cmd The command hash + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Connection} [options.connection] Specify connection object to execute command against + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {opResultCallback} callback A callback function + */ + command(ns, cmd, options, callback) { + if (typeof options === 'function') { + (callback = options), (options = {}), (options = options || {}); + } + + translateReadPreference(options); + const readPreference = options.readPreference || ReadPreference.primary; + + this.selectServer(readPreferenceServerSelector(readPreference), options, (err, server) => { + if (err) { + callback(err, null); + return; + } + + const willRetryWrite = + !options.retrying && + !!options.retryWrites && + options.session && + isRetryableWritesSupported(this) && + !options.session.inTransaction() && + isWriteCommand(cmd); + + const cb = (err, result) => { + if (!err) return callback(null, result); + if (!isRetryableError(err)) { + return callback(err); + } + + if (willRetryWrite) { + const newOptions = Object.assign({}, options, { retrying: true }); + return this.command(ns, cmd, newOptions, callback); + } + + return callback(err); + }; + + // increment and assign txnNumber + if (willRetryWrite) { + options.session.incrementTransactionNumber(); + options.willRetryWrite = willRetryWrite; + } + + server.command(ns, cmd, options, cb); + }); + } + + /** + * Create a new cursor + * + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object|Long} cmd Can be either a command returning a cursor or a cursorId + * @param {object} [options] Options for the cursor + * @param {object} [options.batchSize=0] Batchsize for the operation + * @param {array} [options.documents=[]] Initial documents list for cursor + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {object} [options.topology] The internal topology of the created cursor + * @returns {Cursor} + */ + cursor(ns, cmd, options) { + options = options || {}; + const topology = options.topology || this; + const CursorClass = options.cursorFactory || this.s.Cursor; + translateReadPreference(options); + + return new CursorClass(topology, ns, cmd, options); + } + + get clientInfo() { + return this.s.clientInfo; + } + + // Legacy methods for compat with old topology types + isConnected() { + // console.log('not implemented: `isConnected`'); + return true; + } + + isDestroyed() { + // console.log('not implemented: `isDestroyed`'); + return false; + } + + unref() { + console.log('not implemented: `unref`'); + } + + // NOTE: There are many places in code where we explicitly check the last isMaster + // to do feature support detection. This should be done any other way, but for + // now we will just return the first isMaster seen, which should suffice. + lastIsMaster() { + const serverDescriptions = Array.from(this.description.servers.values()); + if (serverDescriptions.length === 0) return {}; + + const sd = serverDescriptions.filter(sd => sd.type !== ServerType.Unknown)[0]; + const result = sd || { maxWireVersion: this.description.commonWireVersion }; + return result; + } + + get logicalSessionTimeoutMinutes() { + return this.description.logicalSessionTimeoutMinutes; + } + + get bson() { + return this.s.bson; + } +} + +Object.defineProperty(Topology.prototype, 'clusterTime', { + enumerable: true, + get: function() { + return this.s.clusterTime; + }, + set: function(clusterTime) { + this.s.clusterTime = clusterTime; + } +}); + +// legacy aliases +Topology.prototype.destroy = deprecate( + Topology.prototype.close, + 'destroy() is deprecated, please use close() instead' +); + +const RETRYABLE_WRITE_OPERATIONS = ['findAndModify', 'insert', 'update', 'delete']; +function isWriteCommand(command) { + return RETRYABLE_WRITE_OPERATIONS.some(op => command[op]); +} + +/** + * Destroys a server, and removes all event listeners from the instance + * + * @param {Server} server + */ +function destroyServer(server, topology, options, callback) { + options = options || {}; + LOCAL_SERVER_EVENTS.forEach(event => server.removeAllListeners(event)); + + server.destroy(options, () => { + topology.emit( + 'serverClosed', + new monitoring.ServerClosedEvent(topology.s.id, server.description.address) + ); + + if (typeof callback === 'function') callback(null, null); + }); +} + +/** + * Parses a basic seedlist in string form + * + * @param {string} seedlist The seedlist to parse + */ +function parseStringSeedlist(seedlist) { + return seedlist.split(',').map(seed => ({ + host: seed.split(':')[0], + port: seed.split(':')[1] || 27017 + })); +} + +function topologyTypeFromSeedlist(seedlist, options) { + const replicaSet = options.replicaSet || options.setName || options.rs_name; + if (seedlist.length === 1 && !replicaSet) return TopologyType.Single; + if (replicaSet) return TopologyType.ReplicaSetNoPrimary; + return TopologyType.Unknown; +} + +function randomSelection(array) { + return array[Math.floor(Math.random() * array.length)]; +} + +/** + * Selects servers using the provided selector + * + * @private + * @param {Topology} topology The topology to select servers from + * @param {function} selector The actual predicate used for selecting servers + * @param {Number} timeout The max time we are willing wait for selection + * @param {Number} start A high precision timestamp for the start of the selection process + * @param {function} callback The callback used to convey errors or the resultant servers + */ +function selectServers(topology, selector, timeout, start, callback) { + const duration = calculateDurationInMs(start); + if (duration >= timeout) { + return callback( + new MongoTimeoutError(`Server selection timed out after ${timeout} ms`), + topology.description.error + ); + } + + // ensure we are connected + if (!topology.s.connected) { + topology.connect(); + + // we want to make sure we're still within the requested timeout window + const failToConnectTimer = setTimeout(() => { + topology.removeListener('connect', connectHandler); + callback( + new MongoTimeoutError('Server selection timed out waiting to connect'), + topology.description.error + ); + }, timeout - duration); + + const connectHandler = () => { + clearTimeout(failToConnectTimer); + selectServers(topology, selector, timeout, process.hrtime(), callback); + }; + + topology.once('connect', connectHandler); + return; + } + + // otherwise, attempt server selection + const serverDescriptions = Array.from(topology.description.servers.values()); + let descriptions; + + // support server selection by options with readPreference + if (typeof selector === 'object') { + const readPreference = selector.readPreference + ? selector.readPreference + : ReadPreference.primary; + + selector = readPreferenceServerSelector(readPreference); + } + + try { + descriptions = selector + ? selector(topology.description, serverDescriptions) + : serverDescriptions; + } catch (e) { + return callback(e, null); + } + + if (descriptions.length) { + const servers = descriptions.map(description => topology.s.servers.get(description.address)); + return callback(null, servers); + } + + const retrySelection = () => { + // clear all existing monitor timers + topology.s.monitorTimers.map(timer => clearTimeout(timer)); + topology.s.monitorTimers = []; + + // ensure all server monitors attempt monitoring soon + topology.s.servers.forEach(server => { + const timer = setTimeout( + () => server.monitor({ heartbeatFrequencyMS: topology.description.heartbeatFrequencyMS }), + TOPOLOGY_DEFAULTS.minHeartbeatFrequencyMS + ); + + topology.s.monitorTimers.push(timer); + }); + + const descriptionChangedHandler = () => { + // successful iteration, clear the check timer + clearTimeout(iterationTimer); + topology.s.iterationTimers.splice(timerIndex, 1); + + // topology description has changed due to monitoring, reattempt server selection + selectServers(topology, selector, timeout, start, callback); + }; + + const iterationTimer = setTimeout(() => { + topology.removeListener('topologyDescriptionChanged', descriptionChangedHandler); + callback( + new MongoTimeoutError( + `Server selection timed out after ${timeout} ms`, + topology.description.error + ) + ); + }, timeout - duration); + + // track this timer in case we need to clean it up outside this loop + const timerIndex = topology.s.iterationTimers.push(iterationTimer); + + topology.once('topologyDescriptionChanged', descriptionChangedHandler); + }; + + retrySelection(); +} + +function createAndConnectServer(topology, serverDescription) { + topology.emit( + 'serverOpening', + new monitoring.ServerOpeningEvent(topology.s.id, serverDescription.address) + ); + + const server = new Server(serverDescription, topology.s.options, topology); + relayEvents(server, topology, SERVER_RELAY_EVENTS); + + server.once('connect', serverConnectEventHandler(server, topology)); + server.on('descriptionReceived', topology.serverUpdateHandler.bind(topology)); + server.on('error', serverErrorEventHandler(server, topology)); + server.on('close', () => topology.emit('close', server)); + server.connect(); + return server; +} + +/** + * Create `Server` instances for all initially known servers, connect them, and assign + * them to the passed in `Topology`. + * + * @param {Topology} topology The topology responsible for the servers + * @param {ServerDescription[]} serverDescriptions A list of server descriptions to connect + */ +function connectServers(topology, serverDescriptions) { + topology.s.servers = serverDescriptions.reduce((servers, serverDescription) => { + const server = createAndConnectServer(topology, serverDescription); + servers.set(serverDescription.address, server); + return servers; + }, new Map()); +} + +function updateServers(topology, incomingServerDescription) { + // update the internal server's description + if (incomingServerDescription && topology.s.servers.has(incomingServerDescription.address)) { + const server = topology.s.servers.get(incomingServerDescription.address); + server.s.description = incomingServerDescription; + } + + // add new servers for all descriptions we currently don't know about locally + for (const serverDescription of topology.description.servers.values()) { + if (!topology.s.servers.has(serverDescription.address)) { + const server = createAndConnectServer(topology, serverDescription); + topology.s.servers.set(serverDescription.address, server); + } + } + + // for all servers no longer known, remove their descriptions and destroy their instances + for (const entry of topology.s.servers) { + const serverAddress = entry[0]; + if (topology.description.hasServer(serverAddress)) { + continue; + } + + const server = topology.s.servers.get(serverAddress); + topology.s.servers.delete(serverAddress); + + // prepare server for garbage collection + destroyServer(server, topology); + } +} + +function serverConnectEventHandler(server, topology) { + return function(/* isMaster, err */) { + server.monitor({ + initial: true, + heartbeatFrequencyMS: topology.description.heartbeatFrequencyMS + }); + }; +} + +function serverErrorEventHandler(server /*, topology */) { + return function(err) { + if (isSDAMUnrecoverableError(err, server)) { + resetServerState(server, err, { clearPool: true }); + return; + } + + resetServerState(server, err); + }; +} + +function executeWriteOperation(args, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + // TODO: once we drop Node 4, use destructuring either here or in arguments. + const topology = args.topology; + const op = args.op; + const ns = args.ns; + const ops = args.ops; + + const willRetryWrite = + !args.retrying && + !!options.retryWrites && + options.session && + isRetryableWritesSupported(topology) && + !options.session.inTransaction(); + + topology.selectServer(writableServerSelector(), options, (err, server) => { + if (err) { + callback(err, null); + return; + } + + const handler = (err, result) => { + if (!err) return callback(null, result); + if (!isRetryableError(err)) { + err = getMMAPError(err); + return callback(err); + } + + if (willRetryWrite) { + const newArgs = Object.assign({}, args, { retrying: true }); + return executeWriteOperation(newArgs, options, callback); + } + + return callback(err); + }; + + if (callback.operationId) { + handler.operationId = callback.operationId; + } + + // increment and assign txnNumber + if (willRetryWrite) { + options.session.incrementTransactionNumber(); + options.willRetryWrite = willRetryWrite; + } + + // execute the write operation + server[op](ns, ops, options, handler); + }); +} + +/** + * Resets the internal state of this server to `Unknown` by simulating an empty ismaster + * + * @private + * @param {Server} server + * @param {MongoError} error The error that caused the state reset + * @param {object} [options] Optional settings + * @param {boolean} [options.clearPool=false] Pool should be cleared out on state reset + */ +function resetServerState(server, error, options) { + options = Object.assign({}, { clearPool: false }, options); + + function resetState() { + server.emit( + 'descriptionReceived', + new ServerDescription(server.description.address, null, { error }) + ); + + process.nextTick(() => server.monitor()); + } + + if (options.clearPool && server.s.pool) { + server.s.pool.reset(() => resetState()); + return; + } + + resetState(); +} + +function translateReadPreference(options) { + if (options.readPreference == null) { + return; + } + + let r = options.readPreference; + if (typeof r === 'string') { + options.readPreference = new ReadPreference(r); + } else if (r && !(r instanceof ReadPreference) && typeof r === 'object') { + const mode = r.mode || r.preference; + if (mode && typeof mode === 'string') { + options.readPreference = new ReadPreference(mode, r.tags, { + maxStalenessSeconds: r.maxStalenessSeconds + }); + } + } else if (!(r instanceof ReadPreference)) { + throw new TypeError('Invalid read preference: ' + r); + } + + return options; +} + +function srvPollingHandler(topology) { + return function handleSrvPolling(ev) { + const previousTopologyDescription = topology.s.description; + topology.s.description = topology.s.description.updateFromSrvPollingEvent(ev); + if (topology.s.description === previousTopologyDescription) { + // Nothing changed, so return + return; + } + + updateServers(topology); + + topology.emit( + 'topologyDescriptionChanged', + new monitoring.TopologyDescriptionChangedEvent( + topology.s.id, + previousTopologyDescription, + topology.s.description + ) + ); + }; +} + +/** + * A server opening SDAM monitoring event + * + * @event Topology#serverOpening + * @type {ServerOpeningEvent} + */ + +/** + * A server closed SDAM monitoring event + * + * @event Topology#serverClosed + * @type {ServerClosedEvent} + */ + +/** + * A server description SDAM change monitoring event + * + * @event Topology#serverDescriptionChanged + * @type {ServerDescriptionChangedEvent} + */ + +/** + * A topology open SDAM event + * + * @event Topology#topologyOpening + * @type {TopologyOpeningEvent} + */ + +/** + * A topology closed SDAM event + * + * @event Topology#topologyClosed + * @type {TopologyClosedEvent} + */ + +/** + * A topology structure SDAM change event + * + * @event Topology#topologyDescriptionChanged + * @type {TopologyDescriptionChangedEvent} + */ + +/** + * A topology serverHeartbeatStarted SDAM event + * + * @event Topology#serverHeartbeatStarted + * @type {ServerHeartbeatStartedEvent} + */ + +/** + * A topology serverHeartbeatFailed SDAM event + * + * @event Topology#serverHeartbeatFailed + * @type {ServerHearbeatFailedEvent} + */ + +/** + * A topology serverHeartbeatSucceeded SDAM change event + * + * @event Topology#serverHeartbeatSucceeded + * @type {ServerHeartbeatSucceededEvent} + */ + +/** + * An event emitted indicating a command was started, if command monitoring is enabled + * + * @event Topology#commandStarted + * @type {object} + */ + +/** + * An event emitted indicating a command succeeded, if command monitoring is enabled + * + * @event Topology#commandSucceeded + * @type {object} + */ + +/** + * An event emitted indicating a command failed, if command monitoring is enabled + * + * @event Topology#commandFailed + * @type {object} + */ + +module.exports = Topology; diff --git a/scripts/node_modules/mongodb/lib/core/sdam/topology_description.js b/scripts/node_modules/mongodb/lib/core/sdam/topology_description.js new file mode 100644 index 00000000..a94fb678 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/core/sdam/topology_description.js @@ -0,0 +1,408 @@ +'use strict'; +const ServerType = require('./server_description').ServerType; +const ServerDescription = require('./server_description').ServerDescription; +const WIRE_CONSTANTS = require('../wireprotocol/constants'); + +// contstants related to compatability checks +const MIN_SUPPORTED_SERVER_VERSION = WIRE_CONSTANTS.MIN_SUPPORTED_SERVER_VERSION; +const MAX_SUPPORTED_SERVER_VERSION = WIRE_CONSTANTS.MAX_SUPPORTED_SERVER_VERSION; +const MIN_SUPPORTED_WIRE_VERSION = WIRE_CONSTANTS.MIN_SUPPORTED_WIRE_VERSION; +const MAX_SUPPORTED_WIRE_VERSION = WIRE_CONSTANTS.MAX_SUPPORTED_WIRE_VERSION; + +// An enumeration of topology types we know about +const TopologyType = { + Single: 'Single', + ReplicaSetNoPrimary: 'ReplicaSetNoPrimary', + ReplicaSetWithPrimary: 'ReplicaSetWithPrimary', + Sharded: 'Sharded', + Unknown: 'Unknown' +}; + +// Representation of a deployment of servers +class TopologyDescription { + /** + * Create a TopologyDescription + * + * @param {string} topologyType + * @param {Map} serverDescriptions the a map of address to ServerDescription + * @param {string} setName + * @param {number} maxSetVersion + * @param {ObjectId} maxElectionId + */ + constructor( + topologyType, + serverDescriptions, + setName, + maxSetVersion, + maxElectionId, + commonWireVersion, + options, + error + ) { + options = options || {}; + + // TODO: consider assigning all these values to a temporary value `s` which + // we use `Object.freeze` on, ensuring the internal state of this type + // is immutable. + this.type = topologyType || TopologyType.Unknown; + this.setName = setName || null; + this.maxSetVersion = maxSetVersion || null; + this.maxElectionId = maxElectionId || null; + this.servers = serverDescriptions || new Map(); + this.stale = false; + this.compatible = true; + this.compatibilityError = null; + this.logicalSessionTimeoutMinutes = null; + this.heartbeatFrequencyMS = options.heartbeatFrequencyMS || 0; + this.localThresholdMS = options.localThresholdMS || 0; + this.options = options; + this.error = error; + this.commonWireVersion = commonWireVersion || null; + + // determine server compatibility + for (const serverDescription of this.servers.values()) { + if (serverDescription.type === ServerType.Unknown) continue; + + if (serverDescription.minWireVersion > MAX_SUPPORTED_WIRE_VERSION) { + this.compatible = false; + this.compatibilityError = `Server at ${serverDescription.address} requires wire version ${ + serverDescription.minWireVersion + }, but this version of the driver only supports up to ${MAX_SUPPORTED_WIRE_VERSION} (MongoDB ${MAX_SUPPORTED_SERVER_VERSION})`; + } + + if (serverDescription.maxWireVersion < MIN_SUPPORTED_WIRE_VERSION) { + this.compatible = false; + this.compatibilityError = `Server at ${serverDescription.address} reports wire version ${ + serverDescription.maxWireVersion + }, but this version of the driver requires at least ${MIN_SUPPORTED_WIRE_VERSION} (MongoDB ${MIN_SUPPORTED_SERVER_VERSION}).`; + break; + } + } + + // Whenever a client updates the TopologyDescription from an ismaster response, it MUST set + // TopologyDescription.logicalSessionTimeoutMinutes to the smallest logicalSessionTimeoutMinutes + // value among ServerDescriptions of all data-bearing server types. If any have a null + // logicalSessionTimeoutMinutes, then TopologyDescription.logicalSessionTimeoutMinutes MUST be + // set to null. + const readableServers = Array.from(this.servers.values()).filter(s => s.isReadable); + this.logicalSessionTimeoutMinutes = readableServers.reduce((result, server) => { + if (server.logicalSessionTimeoutMinutes == null) return null; + if (result == null) return server.logicalSessionTimeoutMinutes; + return Math.min(result, server.logicalSessionTimeoutMinutes); + }, null); + } + + /** + * Returns a new TopologyDescription based on the SrvPollingEvent + * @param {SrvPollingEvent} ev The event + */ + updateFromSrvPollingEvent(ev) { + const newAddresses = ev.addresses(); + const serverDescriptions = new Map(this.servers); + for (const server of this.servers) { + if (newAddresses.has(server[0])) { + newAddresses.delete(server[0]); + } else { + serverDescriptions.delete(server[0]); + } + } + + if (serverDescriptions.size === this.servers.size && newAddresses.size === 0) { + return this; + } + + for (const address of newAddresses) { + serverDescriptions.set(address, new ServerDescription(address)); + } + + return new TopologyDescription( + this.type, + serverDescriptions, + this.setName, + this.maxSetVersion, + this.maxElectionId, + this.commonWireVersion, + this.options, + null + ); + } + + /** + * Returns a copy of this description updated with a given ServerDescription + * + * @param {ServerDescription} serverDescription + */ + update(serverDescription) { + const address = serverDescription.address; + // NOTE: there are a number of prime targets for refactoring here + // once we support destructuring assignments + + // potentially mutated values + let topologyType = this.type; + let setName = this.setName; + let maxSetVersion = this.maxSetVersion; + let maxElectionId = this.maxElectionId; + let commonWireVersion = this.commonWireVersion; + let error = serverDescription.error || this.error; + + const serverType = serverDescription.type; + let serverDescriptions = new Map(this.servers); + + // update common wire version + if (serverDescription.maxWireVersion !== 0) { + if (commonWireVersion == null) { + commonWireVersion = serverDescription.maxWireVersion; + } else { + commonWireVersion = Math.min(commonWireVersion, serverDescription.maxWireVersion); + } + } + + // update the actual server description + serverDescriptions.set(address, serverDescription); + + if (topologyType === TopologyType.Single) { + // once we are defined as single, that never changes + return new TopologyDescription( + TopologyType.Single, + serverDescriptions, + setName, + maxSetVersion, + maxElectionId, + commonWireVersion, + this.options, + error + ); + } + + if (topologyType === TopologyType.Unknown) { + if (serverType === ServerType.Standalone) { + serverDescriptions.delete(address); + } else { + topologyType = topologyTypeForServerType(serverType); + } + } + + if (topologyType === TopologyType.Sharded) { + if ([ServerType.Mongos, ServerType.Unknown].indexOf(serverType) === -1) { + serverDescriptions.delete(address); + } + } + + if (topologyType === TopologyType.ReplicaSetNoPrimary) { + if ([ServerType.Mongos, ServerType.Unknown].indexOf(serverType) >= 0) { + serverDescriptions.delete(address); + } + + if (serverType === ServerType.RSPrimary) { + const result = updateRsFromPrimary( + serverDescriptions, + setName, + serverDescription, + maxSetVersion, + maxElectionId + ); + + (topologyType = result[0]), + (setName = result[1]), + (maxSetVersion = result[2]), + (maxElectionId = result[3]); + } else if ( + [ServerType.RSSecondary, ServerType.RSArbiter, ServerType.RSOther].indexOf(serverType) >= 0 + ) { + const result = updateRsNoPrimaryFromMember(serverDescriptions, setName, serverDescription); + (topologyType = result[0]), (setName = result[1]); + } + } + + if (topologyType === TopologyType.ReplicaSetWithPrimary) { + if ([ServerType.Standalone, ServerType.Mongos].indexOf(serverType) >= 0) { + serverDescriptions.delete(address); + topologyType = checkHasPrimary(serverDescriptions); + } else if (serverType === ServerType.RSPrimary) { + const result = updateRsFromPrimary( + serverDescriptions, + setName, + serverDescription, + maxSetVersion, + maxElectionId + ); + + (topologyType = result[0]), + (setName = result[1]), + (maxSetVersion = result[2]), + (maxElectionId = result[3]); + } else if ( + [ServerType.RSSecondary, ServerType.RSArbiter, ServerType.RSOther].indexOf(serverType) >= 0 + ) { + topologyType = updateRsWithPrimaryFromMember( + serverDescriptions, + setName, + serverDescription + ); + } else { + topologyType = checkHasPrimary(serverDescriptions); + } + } + + return new TopologyDescription( + topologyType, + serverDescriptions, + setName, + maxSetVersion, + maxElectionId, + commonWireVersion, + this.options, + error + ); + } + + /** + * Determines if the topology description has any known servers + */ + get hasKnownServers() { + return Array.from(this.servers.values()).some(sd => sd.type !== ServerDescription.Unknown); + } + + /** + * Determines if this topology description has a data-bearing server available. + */ + get hasDataBearingServers() { + return Array.from(this.servers.values()).some(sd => sd.isDataBearing); + } + + /** + * Determines if the topology has a definition for the provided address + * + * @param {String} address + * @return {Boolean} Whether the topology knows about this server + */ + hasServer(address) { + return this.servers.has(address); + } +} + +function topologyTypeForServerType(serverType) { + if (serverType === ServerType.Mongos) return TopologyType.Sharded; + if (serverType === ServerType.RSPrimary) return TopologyType.ReplicaSetWithPrimary; + return TopologyType.ReplicaSetNoPrimary; +} + +function updateRsFromPrimary( + serverDescriptions, + setName, + serverDescription, + maxSetVersion, + maxElectionId +) { + setName = setName || serverDescription.setName; + if (setName !== serverDescription.setName) { + serverDescriptions.delete(serverDescription.address); + return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId]; + } + + const electionIdOID = serverDescription.electionId ? serverDescription.electionId.$oid : null; + const maxElectionIdOID = maxElectionId ? maxElectionId.$oid : null; + if (serverDescription.setVersion != null && electionIdOID != null) { + if (maxSetVersion != null && maxElectionIdOID != null) { + if (maxSetVersion > serverDescription.setVersion || maxElectionIdOID > electionIdOID) { + // this primary is stale, we must remove it + serverDescriptions.set( + serverDescription.address, + new ServerDescription(serverDescription.address) + ); + + return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId]; + } + } + + maxElectionId = serverDescription.electionId; + } + + if ( + serverDescription.setVersion != null && + (maxSetVersion == null || serverDescription.setVersion > maxSetVersion) + ) { + maxSetVersion = serverDescription.setVersion; + } + + // We've heard from the primary. Is it the same primary as before? + for (const address of serverDescriptions.keys()) { + const server = serverDescriptions.get(address); + + if (server.type === ServerType.RSPrimary && server.address !== serverDescription.address) { + // Reset old primary's type to Unknown. + serverDescriptions.set(address, new ServerDescription(server.address)); + + // There can only be one primary + break; + } + } + + // Discover new hosts from this primary's response. + serverDescription.allHosts.forEach(address => { + if (!serverDescriptions.has(address)) { + serverDescriptions.set(address, new ServerDescription(address)); + } + }); + + // Remove hosts not in the response. + const currentAddresses = Array.from(serverDescriptions.keys()); + const responseAddresses = serverDescription.allHosts; + currentAddresses.filter(addr => responseAddresses.indexOf(addr) === -1).forEach(address => { + serverDescriptions.delete(address); + }); + + return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId]; +} + +function updateRsWithPrimaryFromMember(serverDescriptions, setName, serverDescription) { + if (setName == null) { + throw new TypeError('setName is required'); + } + + if ( + setName !== serverDescription.setName || + (serverDescription.me && serverDescription.address !== serverDescription.me) + ) { + serverDescriptions.delete(serverDescription.address); + } + + return checkHasPrimary(serverDescriptions); +} + +function updateRsNoPrimaryFromMember(serverDescriptions, setName, serverDescription) { + let topologyType = TopologyType.ReplicaSetNoPrimary; + + setName = setName || serverDescription.setName; + if (setName !== serverDescription.setName) { + serverDescriptions.delete(serverDescription.address); + return [topologyType, setName]; + } + + serverDescription.allHosts.forEach(address => { + if (!serverDescriptions.has(address)) { + serverDescriptions.set(address, new ServerDescription(address)); + } + }); + + if (serverDescription.me && serverDescription.address !== serverDescription.me) { + serverDescriptions.delete(serverDescription.address); + } + + return [topologyType, setName]; +} + +function checkHasPrimary(serverDescriptions) { + for (const addr of serverDescriptions.keys()) { + if (serverDescriptions.get(addr).type === ServerType.RSPrimary) { + return TopologyType.ReplicaSetWithPrimary; + } + } + + return TopologyType.ReplicaSetNoPrimary; +} + +module.exports = { + TopologyType, + TopologyDescription +}; diff --git a/scripts/node_modules/mongodb/lib/core/sessions.js b/scripts/node_modules/mongodb/lib/core/sessions.js new file mode 100644 index 00000000..d15015c8 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/core/sessions.js @@ -0,0 +1,767 @@ +'use strict'; + +const retrieveBSON = require('./connection/utils').retrieveBSON; +const EventEmitter = require('events'); +const BSON = retrieveBSON(); +const Binary = BSON.Binary; +const uuidV4 = require('./utils').uuidV4; +const MongoError = require('./error').MongoError; +const isRetryableError = require('././error').isRetryableError; +const MongoNetworkError = require('./error').MongoNetworkError; +const MongoWriteConcernError = require('./error').MongoWriteConcernError; +const Transaction = require('./transactions').Transaction; +const TxnState = require('./transactions').TxnState; +const isPromiseLike = require('./utils').isPromiseLike; +const ReadPreference = require('./topologies/read_preference'); +const isTransactionCommand = require('./transactions').isTransactionCommand; +const resolveClusterTime = require('./topologies/shared').resolveClusterTime; +const isSharded = require('./wireprotocol/shared').isSharded; +const maxWireVersion = require('./utils').maxWireVersion; + +const minWireVersionForShardedTransactions = 8; + +function assertAlive(session, callback) { + if (session.serverSession == null) { + const error = new MongoError('Cannot use a session that has ended'); + if (typeof callback === 'function') { + callback(error, null); + return false; + } + + throw error; + } + + return true; +} + +/** + * Options to pass when creating a Client Session + * @typedef {Object} SessionOptions + * @property {boolean} [causalConsistency=true] Whether causal consistency should be enabled on this session + * @property {TransactionOptions} [defaultTransactionOptions] The default TransactionOptions to use for transactions started on this session. + */ + +/** + * A BSON document reflecting the lsid of a {@link ClientSession} + * @typedef {Object} SessionId + */ + +/** + * A class representing a client session on the server + * WARNING: not meant to be instantiated directly. + * @class + * @hideconstructor + */ +class ClientSession extends EventEmitter { + /** + * Create a client session. + * WARNING: not meant to be instantiated directly + * + * @param {Topology} topology The current client's topology (Internal Class) + * @param {ServerSessionPool} sessionPool The server session pool (Internal Class) + * @param {SessionOptions} [options] Optional settings + * @param {Object} [clientOptions] Optional settings provided when creating a client in the porcelain driver + */ + constructor(topology, sessionPool, options, clientOptions) { + super(); + + if (topology == null) { + throw new Error('ClientSession requires a topology'); + } + + if (sessionPool == null || !(sessionPool instanceof ServerSessionPool)) { + throw new Error('ClientSession requires a ServerSessionPool'); + } + + options = options || {}; + clientOptions = clientOptions || {}; + + this.topology = topology; + this.sessionPool = sessionPool; + this.hasEnded = false; + this.serverSession = sessionPool.acquire(); + this.clientOptions = clientOptions; + + this.supports = { + causalConsistency: + typeof options.causalConsistency !== 'undefined' ? options.causalConsistency : true + }; + + this.clusterTime = options.initialClusterTime; + + this.operationTime = null; + this.explicit = !!options.explicit; + this.owner = options.owner; + this.defaultTransactionOptions = Object.assign({}, options.defaultTransactionOptions); + this.transaction = new Transaction(); + } + + /** + * The server id associated with this session + * @type {SessionId} + */ + get id() { + return this.serverSession.id; + } + + /** + * Ends this session on the server + * + * @param {Object} [options] Optional settings. Currently reserved for future use + * @param {Function} [callback] Optional callback for completion of this operation + */ + endSession(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + if (this.hasEnded) { + if (typeof callback === 'function') callback(null, null); + return; + } + + if (this.serverSession && this.inTransaction()) { + this.abortTransaction(); // pass in callback? + } + + // mark the session as ended, and emit a signal + this.hasEnded = true; + this.emit('ended', this); + + // release the server session back to the pool + this.sessionPool.release(this.serverSession); + this.serverSession = null; + + // spec indicates that we should ignore all errors for `endSessions` + if (typeof callback === 'function') callback(null, null); + } + + /** + * Advances the operationTime for a ClientSession. + * + * @param {Timestamp} operationTime the `BSON.Timestamp` of the operation type it is desired to advance to + */ + advanceOperationTime(operationTime) { + if (this.operationTime == null) { + this.operationTime = operationTime; + return; + } + + if (operationTime.greaterThan(this.operationTime)) { + this.operationTime = operationTime; + } + } + + /** + * Used to determine if this session equals another + * @param {ClientSession} session + * @return {boolean} true if the sessions are equal + */ + equals(session) { + if (!(session instanceof ClientSession)) { + return false; + } + + return this.id.id.buffer.equals(session.id.id.buffer); + } + + /** + * Increment the transaction number on the internal ServerSession + */ + incrementTransactionNumber() { + this.serverSession.txnNumber++; + } + + /** + * @returns {boolean} whether this session is currently in a transaction or not + */ + inTransaction() { + return this.transaction.isActive; + } + + /** + * Starts a new transaction with the given options. + * + * @param {TransactionOptions} options Options for the transaction + */ + startTransaction(options) { + assertAlive(this); + if (this.inTransaction()) { + throw new MongoError('Transaction already in progress'); + } + + const topologyMaxWireVersion = maxWireVersion(this.topology); + if ( + isSharded(this.topology) && + topologyMaxWireVersion != null && + topologyMaxWireVersion < minWireVersionForShardedTransactions + ) { + throw new MongoError('Transactions are not supported on sharded clusters in MongoDB < 4.2.'); + } + + // increment txnNumber + this.incrementTransactionNumber(); + + // create transaction state + this.transaction = new Transaction( + Object.assign({}, this.clientOptions, options || this.defaultTransactionOptions) + ); + + this.transaction.transition(TxnState.STARTING_TRANSACTION); + } + + /** + * Commits the currently active transaction in this session. + * + * @param {Function} [callback] optional callback for completion of this operation + * @return {Promise} A promise is returned if no callback is provided + */ + commitTransaction(callback) { + if (typeof callback === 'function') { + endTransaction(this, 'commitTransaction', callback); + return; + } + + return new Promise((resolve, reject) => { + endTransaction( + this, + 'commitTransaction', + (err, reply) => (err ? reject(err) : resolve(reply)) + ); + }); + } + + /** + * Aborts the currently active transaction in this session. + * + * @param {Function} [callback] optional callback for completion of this operation + * @return {Promise} A promise is returned if no callback is provided + */ + abortTransaction(callback) { + if (typeof callback === 'function') { + endTransaction(this, 'abortTransaction', callback); + return; + } + + return new Promise((resolve, reject) => { + endTransaction( + this, + 'abortTransaction', + (err, reply) => (err ? reject(err) : resolve(reply)) + ); + }); + } + + /** + * This is here to ensure that ClientSession is never serialized to BSON. + * @ignore + */ + toBSON() { + throw new Error('ClientSession cannot be serialized to BSON.'); + } + + /** + * A user provided function to be run within a transaction + * + * @callback WithTransactionCallback + * @param {ClientSession} session The parent session of the transaction running the operation. This should be passed into each operation within the lambda. + * @returns {Promise} The resulting Promise of operations run within this transaction + */ + + /** + * Runs a provided lambda within a transaction, retrying either the commit operation + * or entire transaction as needed (and when the error permits) to better ensure that + * the transaction can complete successfully. + * + * IMPORTANT: This method requires the user to return a Promise, all lambdas that do not + * return a Promise will result in undefined behavior. + * + * @param {WithTransactionCallback} fn + * @param {TransactionOptions} [options] Optional settings for the transaction + */ + withTransaction(fn, options) { + const startTime = Date.now(); + return attemptTransaction(this, startTime, fn, options); + } +} + +const MAX_WITH_TRANSACTION_TIMEOUT = 120000; +const UNSATISFIABLE_WRITE_CONCERN_CODE = 100; +const UNKNOWN_REPL_WRITE_CONCERN_CODE = 79; +const MAX_TIME_MS_EXPIRED_CODE = 50; +const NON_DETERMINISTIC_WRITE_CONCERN_ERRORS = new Set([ + 'CannotSatisfyWriteConcern', + 'UnknownReplWriteConcern', + 'UnsatisfiableWriteConcern' +]); + +function hasNotTimedOut(startTime, max) { + return Date.now() - startTime < max; +} + +function isUnknownTransactionCommitResult(err) { + return ( + isMaxTimeMSExpiredError(err) || + (!NON_DETERMINISTIC_WRITE_CONCERN_ERRORS.has(err.codeName) && + err.code !== UNSATISFIABLE_WRITE_CONCERN_CODE && + err.code !== UNKNOWN_REPL_WRITE_CONCERN_CODE) + ); +} + +function isMaxTimeMSExpiredError(err) { + return ( + err.code === MAX_TIME_MS_EXPIRED_CODE || + (err.writeConcernError && err.writeConcernError.code === MAX_TIME_MS_EXPIRED_CODE) + ); +} + +function attemptTransactionCommit(session, startTime, fn, options) { + return session.commitTransaction().catch(err => { + if ( + err instanceof MongoError && + hasNotTimedOut(startTime, MAX_WITH_TRANSACTION_TIMEOUT) && + !isMaxTimeMSExpiredError(err) + ) { + if (err.hasErrorLabel('UnknownTransactionCommitResult')) { + return attemptTransactionCommit(session, startTime, fn, options); + } + + if (err.hasErrorLabel('TransientTransactionError')) { + return attemptTransaction(session, startTime, fn, options); + } + } + + throw err; + }); +} + +const USER_EXPLICIT_TXN_END_STATES = new Set([ + TxnState.NO_TRANSACTION, + TxnState.TRANSACTION_COMMITTED, + TxnState.TRANSACTION_ABORTED +]); + +function userExplicitlyEndedTransaction(session) { + return USER_EXPLICIT_TXN_END_STATES.has(session.transaction.state); +} + +function attemptTransaction(session, startTime, fn, options) { + session.startTransaction(options); + + let promise; + try { + promise = fn(session); + } catch (err) { + promise = Promise.reject(err); + } + + if (!isPromiseLike(promise)) { + session.abortTransaction(); + throw new TypeError('Function provided to `withTransaction` must return a Promise'); + } + + return promise + .then(() => { + if (userExplicitlyEndedTransaction(session)) { + return; + } + + return attemptTransactionCommit(session, startTime, fn, options); + }) + .catch(err => { + function maybeRetryOrThrow(err) { + if ( + err instanceof MongoError && + err.hasErrorLabel('TransientTransactionError') && + hasNotTimedOut(startTime, MAX_WITH_TRANSACTION_TIMEOUT) + ) { + return attemptTransaction(session, startTime, fn, options); + } + + if (isMaxTimeMSExpiredError(err)) { + if (err.errorLabels == null) { + err.errorLabels = []; + } + err.errorLabels.push('UnknownTransactionCommitResult'); + } + + throw err; + } + + if (session.transaction.isActive) { + return session.abortTransaction().then(() => maybeRetryOrThrow(err)); + } + + return maybeRetryOrThrow(err); + }); +} + +function endTransaction(session, commandName, callback) { + if (!assertAlive(session, callback)) { + // checking result in case callback was called + return; + } + + // handle any initial problematic cases + let txnState = session.transaction.state; + + if (txnState === TxnState.NO_TRANSACTION) { + callback(new MongoError('No transaction started')); + return; + } + + if (commandName === 'commitTransaction') { + if ( + txnState === TxnState.STARTING_TRANSACTION || + txnState === TxnState.TRANSACTION_COMMITTED_EMPTY + ) { + // the transaction was never started, we can safely exit here + session.transaction.transition(TxnState.TRANSACTION_COMMITTED_EMPTY); + callback(null, null); + return; + } + + if (txnState === TxnState.TRANSACTION_ABORTED) { + callback(new MongoError('Cannot call commitTransaction after calling abortTransaction')); + return; + } + } else { + if (txnState === TxnState.STARTING_TRANSACTION) { + // the transaction was never started, we can safely exit here + session.transaction.transition(TxnState.TRANSACTION_ABORTED); + callback(null, null); + return; + } + + if (txnState === TxnState.TRANSACTION_ABORTED) { + callback(new MongoError('Cannot call abortTransaction twice')); + return; + } + + if ( + txnState === TxnState.TRANSACTION_COMMITTED || + txnState === TxnState.TRANSACTION_COMMITTED_EMPTY + ) { + callback(new MongoError('Cannot call abortTransaction after calling commitTransaction')); + return; + } + } + + // construct and send the command + const command = { [commandName]: 1 }; + + // apply a writeConcern if specified + let writeConcern; + if (session.transaction.options.writeConcern) { + writeConcern = Object.assign({}, session.transaction.options.writeConcern); + } else if (session.clientOptions && session.clientOptions.w) { + writeConcern = { w: session.clientOptions.w }; + } + + if (txnState === TxnState.TRANSACTION_COMMITTED) { + writeConcern = Object.assign({ wtimeout: 10000 }, writeConcern, { w: 'majority' }); + } + + if (writeConcern) { + Object.assign(command, { writeConcern }); + } + + if (commandName === 'commitTransaction' && session.transaction.options.maxTimeMS) { + Object.assign(command, { maxTimeMS: session.transaction.options.maxTimeMS }); + } + + function commandHandler(e, r) { + if (commandName === 'commitTransaction') { + session.transaction.transition(TxnState.TRANSACTION_COMMITTED); + + if ( + e && + (e instanceof MongoNetworkError || + e instanceof MongoWriteConcernError || + isRetryableError(e) || + isMaxTimeMSExpiredError(e)) + ) { + if (e.errorLabels) { + const idx = e.errorLabels.indexOf('TransientTransactionError'); + if (idx !== -1) { + e.errorLabels.splice(idx, 1); + } + } else { + e.errorLabels = []; + } + + if (isUnknownTransactionCommitResult(e)) { + e.errorLabels.push('UnknownTransactionCommitResult'); + + // per txns spec, must unpin session in this case + session.transaction.unpinServer(); + } + } + } else { + session.transaction.transition(TxnState.TRANSACTION_ABORTED); + } + + callback(e, r); + } + + // The spec indicates that we should ignore all errors on `abortTransaction` + function transactionError(err) { + return commandName === 'commitTransaction' ? err : null; + } + + if ( + // Assumption here that commandName is "commitTransaction" or "abortTransaction" + session.transaction.recoveryToken && + supportsRecoveryToken(session) + ) { + command.recoveryToken = session.transaction.recoveryToken; + } + + // send the command + session.topology.command('admin.$cmd', command, { session }, (err, reply) => { + if (err && isRetryableError(err)) { + // SPEC-1185: apply majority write concern when retrying commitTransaction + if (command.commitTransaction) { + // per txns spec, must unpin session in this case + session.transaction.unpinServer(); + + command.writeConcern = Object.assign({ wtimeout: 10000 }, command.writeConcern, { + w: 'majority' + }); + } + + return session.topology.command('admin.$cmd', command, { session }, (_err, _reply) => + commandHandler(transactionError(_err), _reply) + ); + } + + commandHandler(transactionError(err), reply); + }); +} + +function supportsRecoveryToken(session) { + const topology = session.topology; + return !!topology.s.options.useRecoveryToken; +} + +/** + * Reflects the existence of a session on the server. Can be reused by the session pool. + * WARNING: not meant to be instantiated directly. For internal use only. + * @ignore + */ +class ServerSession { + constructor() { + this.id = { id: new Binary(uuidV4(), Binary.SUBTYPE_UUID) }; + this.lastUse = Date.now(); + this.txnNumber = 0; + this.isDirty = false; + } + + /** + * Determines if the server session has timed out. + * @ignore + * @param {Date} sessionTimeoutMinutes The server's "logicalSessionTimeoutMinutes" + * @return {boolean} true if the session has timed out. + */ + hasTimedOut(sessionTimeoutMinutes) { + // Take the difference of the lastUse timestamp and now, which will result in a value in + // milliseconds, and then convert milliseconds to minutes to compare to `sessionTimeoutMinutes` + const idleTimeMinutes = Math.round( + (((Date.now() - this.lastUse) % 86400000) % 3600000) / 60000 + ); + + return idleTimeMinutes > sessionTimeoutMinutes - 1; + } +} + +/** + * Maintains a pool of Server Sessions. + * For internal use only + * @ignore + */ +class ServerSessionPool { + constructor(topology) { + if (topology == null) { + throw new Error('ServerSessionPool requires a topology'); + } + + this.topology = topology; + this.sessions = []; + } + + /** + * Ends all sessions in the session pool. + * @ignore + */ + endAllPooledSessions() { + if (this.sessions.length) { + this.topology.endSessions(this.sessions.map(session => session.id)); + this.sessions = []; + } + } + + /** + * Acquire a Server Session from the pool. + * Iterates through each session in the pool, removing any stale sessions + * along the way. The first non-stale session found is removed from the + * pool and returned. If no non-stale session is found, a new ServerSession + * is created. + * @ignore + * @returns {ServerSession} + */ + acquire() { + const sessionTimeoutMinutes = this.topology.logicalSessionTimeoutMinutes; + while (this.sessions.length) { + const session = this.sessions.shift(); + if (!session.hasTimedOut(sessionTimeoutMinutes)) { + return session; + } + } + + return new ServerSession(); + } + + /** + * Release a session to the session pool + * Adds the session back to the session pool if the session has not timed out yet. + * This method also removes any stale sessions from the pool. + * @ignore + * @param {ServerSession} session The session to release to the pool + */ + release(session) { + const sessionTimeoutMinutes = this.topology.logicalSessionTimeoutMinutes; + while (this.sessions.length) { + const pooledSession = this.sessions[this.sessions.length - 1]; + if (pooledSession.hasTimedOut(sessionTimeoutMinutes)) { + this.sessions.pop(); + } else { + break; + } + } + + if (!session.hasTimedOut(sessionTimeoutMinutes)) { + if (session.isDirty) { + return; + } + + // otherwise, readd this session to the session pool + this.sessions.unshift(session); + } + } +} + +// TODO: this should be codified in command construction +// @see https://github.com/mongodb/specifications/blob/master/source/read-write-concern/read-write-concern.rst#read-concern +function commandSupportsReadConcern(command, options) { + if ( + command.aggregate || + command.count || + command.distinct || + command.find || + command.parallelCollectionScan || + command.geoNear || + command.geoSearch + ) { + return true; + } + + if (command.mapReduce && options.out && (options.out.inline === 1 || options.out === 'inline')) { + return true; + } + + return false; +} + +/** + * Optionally decorate a command with sessions specific keys + * + * @param {ClientSession} session the session tracking transaction state + * @param {Object} command the command to decorate + * @param {Object} topology the topology for tracking the cluster time + * @param {Object} [options] Optional settings passed to calling operation + * @return {MongoError|null} An error, if some error condition was met + */ +function applySession(session, command, options) { + const serverSession = session.serverSession; + if (serverSession == null) { + // TODO: merge this with `assertAlive`, did not want to throw a try/catch here + return new MongoError('Cannot use a session that has ended'); + } + + // mark the last use of this session, and apply the `lsid` + serverSession.lastUse = Date.now(); + command.lsid = serverSession.id; + + // first apply non-transaction-specific sessions data + const inTransaction = session.inTransaction() || isTransactionCommand(command); + const isRetryableWrite = options.willRetryWrite; + const shouldApplyReadConcern = commandSupportsReadConcern(command); + + if (serverSession.txnNumber && (isRetryableWrite || inTransaction)) { + command.txnNumber = BSON.Long.fromNumber(serverSession.txnNumber); + } + + // now attempt to apply transaction-specific sessions data + if (!inTransaction) { + if (session.transaction.state !== TxnState.NO_TRANSACTION) { + session.transaction.transition(TxnState.NO_TRANSACTION); + } + + // TODO: the following should only be applied to read operation per spec. + // for causal consistency + if (session.supports.causalConsistency && session.operationTime && shouldApplyReadConcern) { + command.readConcern = command.readConcern || {}; + Object.assign(command.readConcern, { afterClusterTime: session.operationTime }); + } + + return; + } + + if (options.readPreference && !options.readPreference.equals(ReadPreference.primary)) { + return new MongoError( + `Read preference in a transaction must be primary, not: ${options.readPreference.mode}` + ); + } + + // `autocommit` must always be false to differentiate from retryable writes + command.autocommit = false; + + if (session.transaction.state === TxnState.STARTING_TRANSACTION) { + session.transaction.transition(TxnState.TRANSACTION_IN_PROGRESS); + command.startTransaction = true; + + const readConcern = + session.transaction.options.readConcern || session.clientOptions.readConcern; + if (readConcern) { + command.readConcern = readConcern; + } + + if (session.supports.causalConsistency && session.operationTime) { + command.readConcern = command.readConcern || {}; + Object.assign(command.readConcern, { afterClusterTime: session.operationTime }); + } + } +} + +function updateSessionFromResponse(session, document) { + if (document.$clusterTime) { + resolveClusterTime(session, document.$clusterTime); + } + + if (document.operationTime && session && session.supports.causalConsistency) { + session.advanceOperationTime(document.operationTime); + } + + if (document.recoveryToken && session && session.inTransaction()) { + session.transaction._recoveryToken = document.recoveryToken; + } +} + +module.exports = { + ClientSession, + ServerSession, + ServerSessionPool, + TxnState, + applySession, + updateSessionFromResponse, + commandSupportsReadConcern +}; diff --git a/scripts/node_modules/mongodb/lib/core/tools/smoke_plugin.js b/scripts/node_modules/mongodb/lib/core/tools/smoke_plugin.js new file mode 100644 index 00000000..22d02986 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/core/tools/smoke_plugin.js @@ -0,0 +1,61 @@ +'use strict'; + +var fs = require('fs'); + +/* Note: because this plugin uses process.on('uncaughtException'), only one + * of these can exist at any given time. This plugin and anything else that + * uses process.on('uncaughtException') will conflict. */ +exports.attachToRunner = function(runner, outputFile) { + var smokeOutput = { results: [] }; + var runningTests = {}; + + var integraPlugin = { + beforeTest: function(test, callback) { + test.startTime = Date.now(); + runningTests[test.name] = test; + callback(); + }, + afterTest: function(test, callback) { + smokeOutput.results.push({ + status: test.status, + start: test.startTime, + end: Date.now(), + test_file: test.name, + exit_code: 0, + url: '' + }); + delete runningTests[test.name]; + callback(); + }, + beforeExit: function(obj, callback) { + fs.writeFile(outputFile, JSON.stringify(smokeOutput), function() { + callback(); + }); + } + }; + + // In case of exception, make sure we write file + process.on('uncaughtException', function(err) { + // Mark all currently running tests as failed + for (var testName in runningTests) { + smokeOutput.results.push({ + status: 'fail', + start: runningTests[testName].startTime, + end: Date.now(), + test_file: testName, + exit_code: 0, + url: '' + }); + } + + // write file + fs.writeFileSync(outputFile, JSON.stringify(smokeOutput)); + + // Standard NodeJS uncaught exception handler + console.error(err.stack); + process.exit(1); + }); + + runner.plugin(integraPlugin); + return integraPlugin; +}; diff --git a/scripts/node_modules/mongodb/lib/core/topologies/mongos.js b/scripts/node_modules/mongodb/lib/core/topologies/mongos.js new file mode 100644 index 00000000..681b01fd --- /dev/null +++ b/scripts/node_modules/mongodb/lib/core/topologies/mongos.js @@ -0,0 +1,1392 @@ +'use strict'; + +const inherits = require('util').inherits; +const f = require('util').format; +const EventEmitter = require('events').EventEmitter; +const CoreCursor = require('../cursor').CoreCursor; +const Logger = require('../connection/logger'); +const retrieveBSON = require('../connection/utils').retrieveBSON; +const MongoError = require('../error').MongoError; +const Server = require('./server'); +const clone = require('./shared').clone; +const diff = require('./shared').diff; +const cloneOptions = require('./shared').cloneOptions; +const createClientInfo = require('./shared').createClientInfo; +const SessionMixins = require('./shared').SessionMixins; +const isRetryableWritesSupported = require('./shared').isRetryableWritesSupported; +const relayEvents = require('../utils').relayEvents; +const isRetryableError = require('../error').isRetryableError; +const BSON = retrieveBSON(); +const getMMAPError = require('./shared').getMMAPError; + +/** + * @fileOverview The **Mongos** class is a class that represents a Mongos Proxy topology and is + * used to construct connections. + */ + +// +// States +var DISCONNECTED = 'disconnected'; +var CONNECTING = 'connecting'; +var CONNECTED = 'connected'; +var UNREFERENCED = 'unreferenced'; +var DESTROYING = 'destroying'; +var DESTROYED = 'destroyed'; + +function stateTransition(self, newState) { + var legalTransitions = { + disconnected: [CONNECTING, DESTROYING, DESTROYED, DISCONNECTED], + connecting: [CONNECTING, DESTROYING, DESTROYED, CONNECTED, DISCONNECTED], + connected: [CONNECTED, DISCONNECTED, DESTROYING, DESTROYED, UNREFERENCED], + unreferenced: [UNREFERENCED, DESTROYING, DESTROYED], + destroyed: [DESTROYED] + }; + + // Get current state + var legalStates = legalTransitions[self.state]; + if (legalStates && legalStates.indexOf(newState) !== -1) { + self.state = newState; + } else { + self.s.logger.error( + f( + 'Mongos with id [%s] failed attempted illegal state transition from [%s] to [%s] only following state allowed [%s]', + self.id, + self.state, + newState, + legalStates + ) + ); + } +} + +// +// ReplSet instance id +var id = 1; +var handlers = ['connect', 'close', 'error', 'timeout', 'parseError']; + +/** + * Creates a new Mongos instance + * @class + * @param {array} seedlist A list of seeds for the replicaset + * @param {number} [options.haInterval=5000] The High availability period for replicaset inquiry + * @param {Cursor} [options.cursorFactory=Cursor] The cursor factory class used for all query cursors + * @param {number} [options.size=5] Server connection pool size + * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled + * @param {number} [options.keepAliveInitialDelay=0] Initial delay before TCP keep alive enabled + * @param {number} [options.localThresholdMS=15] Cutoff latency point in MS for MongoS proxy selection + * @param {boolean} [options.noDelay=true] TCP Connection no delay + * @param {number} [options.connectionTimeout=1000] TCP Connection timeout setting + * @param {number} [options.socketTimeout=0] TCP Socket timeout setting + * @param {boolean} [options.ssl=false] Use SSL for connection + * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. + * @param {Buffer} [options.ca] SSL Certificate store binary buffer + * @param {Buffer} [options.crl] SSL Certificate revocation store binary buffer + * @param {Buffer} [options.cert] SSL Certificate binary buffer + * @param {Buffer} [options.key] SSL Key file binary buffer + * @param {string} [options.passphrase] SSL Certificate pass phrase + * @param {string} [options.servername=null] String containing the server name requested via TLS SNI. + * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates + * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits + * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. + * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. + * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. + * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology + * @return {Mongos} A cursor instance + * @fires Mongos#connect + * @fires Mongos#reconnect + * @fires Mongos#joined + * @fires Mongos#left + * @fires Mongos#failed + * @fires Mongos#fullsetup + * @fires Mongos#all + * @fires Mongos#serverHeartbeatStarted + * @fires Mongos#serverHeartbeatSucceeded + * @fires Mongos#serverHeartbeatFailed + * @fires Mongos#topologyOpening + * @fires Mongos#topologyClosed + * @fires Mongos#topologyDescriptionChanged + * @property {string} type the topology type. + * @property {string} parserType the parser type used (c++ or js). + */ +var Mongos = function(seedlist, options) { + options = options || {}; + + // Get replSet Id + this.id = id++; + + // Internal state + this.s = { + options: Object.assign({}, options), + // BSON instance + bson: + options.bson || + new BSON([ + BSON.Binary, + BSON.Code, + BSON.DBRef, + BSON.Decimal128, + BSON.Double, + BSON.Int32, + BSON.Long, + BSON.Map, + BSON.MaxKey, + BSON.MinKey, + BSON.ObjectId, + BSON.BSONRegExp, + BSON.Symbol, + BSON.Timestamp + ]), + // Factory overrides + Cursor: options.cursorFactory || CoreCursor, + // Logger instance + logger: Logger('Mongos', options), + // Seedlist + seedlist: seedlist, + // Ha interval + haInterval: options.haInterval ? options.haInterval : 10000, + // Disconnect handler + disconnectHandler: options.disconnectHandler, + // Server selection index + index: 0, + // Connect function options passed in + connectOptions: {}, + // Are we running in debug mode + debug: typeof options.debug === 'boolean' ? options.debug : false, + // localThresholdMS + localThresholdMS: options.localThresholdMS || 15, + // Client info + clientInfo: createClientInfo(options) + }; + + // Set the client info + this.s.options.clientInfo = createClientInfo(options); + + // Log info warning if the socketTimeout < haInterval as it will cause + // a lot of recycled connections to happen. + if ( + this.s.logger.isWarn() && + this.s.options.socketTimeout !== 0 && + this.s.options.socketTimeout < this.s.haInterval + ) { + this.s.logger.warn( + f( + 'warning socketTimeout %s is less than haInterval %s. This might cause unnecessary server reconnections due to socket timeouts', + this.s.options.socketTimeout, + this.s.haInterval + ) + ); + } + + // Disconnected state + this.state = DISCONNECTED; + + // Current proxies we are connecting to + this.connectingProxies = []; + // Currently connected proxies + this.connectedProxies = []; + // Disconnected proxies + this.disconnectedProxies = []; + // Index of proxy to run operations against + this.index = 0; + // High availability timeout id + this.haTimeoutId = null; + // Last ismaster + this.ismaster = null; + + // Description of the Replicaset + this.topologyDescription = { + topologyType: 'Unknown', + servers: [] + }; + + // Highest clusterTime seen in responses from the current deployment + this.clusterTime = null; + + // Add event listener + EventEmitter.call(this); +}; + +inherits(Mongos, EventEmitter); +Object.assign(Mongos.prototype, SessionMixins); + +Object.defineProperty(Mongos.prototype, 'type', { + enumerable: true, + get: function() { + return 'mongos'; + } +}); + +Object.defineProperty(Mongos.prototype, 'parserType', { + enumerable: true, + get: function() { + return BSON.native ? 'c++' : 'js'; + } +}); + +Object.defineProperty(Mongos.prototype, 'logicalSessionTimeoutMinutes', { + enumerable: true, + get: function() { + if (!this.ismaster) return null; + return this.ismaster.logicalSessionTimeoutMinutes || null; + } +}); + +/** + * Emit event if it exists + * @method + */ +function emitSDAMEvent(self, event, description) { + if (self.listeners(event).length > 0) { + self.emit(event, description); + } +} + +const SERVER_EVENTS = ['serverDescriptionChanged', 'error', 'close', 'timeout', 'parseError']; +function destroyServer(server, options, callback) { + options = options || {}; + SERVER_EVENTS.forEach(event => server.removeAllListeners(event)); + server.destroy(options, callback); +} + +/** + * Initiate server connect + */ +Mongos.prototype.connect = function(options) { + var self = this; + // Add any connect level options to the internal state + this.s.connectOptions = options || {}; + + // Set connecting state + stateTransition(this, CONNECTING); + + // Create server instances + var servers = this.s.seedlist.map(function(x) { + const server = new Server( + Object.assign({}, self.s.options, x, options, { + reconnect: false, + monitoring: false, + parent: self, + clientInfo: clone(self.s.clientInfo) + }) + ); + + relayEvents(server, self, ['serverDescriptionChanged']); + return server; + }); + + // Emit the topology opening event + emitSDAMEvent(this, 'topologyOpening', { topologyId: this.id }); + + // Start all server connections + connectProxies(self, servers); +}; + +/** + * Authenticate the topology. + * @method + * @param {MongoCredentials} credentials The credentials for authentication we are using + * @param {authResultCallback} callback A callback function + */ +Mongos.prototype.auth = function(credentials, callback) { + if (typeof callback === 'function') callback(null, null); +}; + +function handleEvent(self) { + return function() { + if (self.state === DESTROYED || self.state === DESTROYING) { + return; + } + + // Move to list of disconnectedProxies + moveServerFrom(self.connectedProxies, self.disconnectedProxies, this); + // Emit the initial topology + emitTopologyDescriptionChanged(self); + // Emit the left signal + self.emit('left', 'mongos', this); + // Emit the sdam event + self.emit('serverClosed', { + topologyId: self.id, + address: this.name + }); + }; +} + +function handleInitialConnectEvent(self, event) { + return function() { + var _this = this; + + // Destroy the instance + if (self.state === DESTROYED) { + // Emit the initial topology + emitTopologyDescriptionChanged(self); + // Move from connectingProxies + moveServerFrom(self.connectingProxies, self.disconnectedProxies, this); + return this.destroy(); + } + + // Check the type of server + if (event === 'connect') { + // Get last known ismaster + self.ismaster = _this.lastIsMaster(); + + // Is this not a proxy, remove t + if (self.ismaster.msg === 'isdbgrid') { + // Add to the connectd list + for (let i = 0; i < self.connectedProxies.length; i++) { + if (self.connectedProxies[i].name === _this.name) { + // Move from connectingProxies + moveServerFrom(self.connectingProxies, self.disconnectedProxies, _this); + // Emit the initial topology + emitTopologyDescriptionChanged(self); + _this.destroy(); + return self.emit('failed', _this); + } + } + + // Remove the handlers + for (let i = 0; i < handlers.length; i++) { + _this.removeAllListeners(handlers[i]); + } + + // Add stable state handlers + _this.on('error', handleEvent(self, 'error')); + _this.on('close', handleEvent(self, 'close')); + _this.on('timeout', handleEvent(self, 'timeout')); + _this.on('parseError', handleEvent(self, 'parseError')); + + // Move from connecting proxies connected + moveServerFrom(self.connectingProxies, self.connectedProxies, _this); + // Emit the joined event + self.emit('joined', 'mongos', _this); + } else { + // Print warning if we did not find a mongos proxy + if (self.s.logger.isWarn()) { + var message = 'expected mongos proxy, but found replicaset member mongod for server %s'; + // We have a standalone server + if (!self.ismaster.hosts) { + message = 'expected mongos proxy, but found standalone mongod for server %s'; + } + + self.s.logger.warn(f(message, _this.name)); + } + + // This is not a mongos proxy, destroy and remove it completely + _this.destroy(true); + removeProxyFrom(self.connectingProxies, _this); + // Emit the left event + self.emit('left', 'server', _this); + // Emit failed event + self.emit('failed', _this); + } + } else { + moveServerFrom(self.connectingProxies, self.disconnectedProxies, this); + // Emit the left event + self.emit('left', 'mongos', this); + // Emit failed event + self.emit('failed', this); + } + + // Emit the initial topology + emitTopologyDescriptionChanged(self); + + // Trigger topologyMonitor + if (self.connectingProxies.length === 0) { + // Emit connected if we are connected + if (self.connectedProxies.length > 0 && self.state === CONNECTING) { + // Set the state to connected + stateTransition(self, CONNECTED); + // Emit the connect event + self.emit('connect', self); + self.emit('fullsetup', self); + self.emit('all', self); + } else if (self.disconnectedProxies.length === 0) { + // Print warning if we did not find a mongos proxy + if (self.s.logger.isWarn()) { + self.s.logger.warn( + f('no mongos proxies found in seed list, did you mean to connect to a replicaset') + ); + } + + // Emit the error that no proxies were found + return self.emit('error', new MongoError('no mongos proxies found in seed list')); + } + + // Topology monitor + topologyMonitor(self, { firstConnect: true }); + } + }; +} + +function connectProxies(self, servers) { + // Update connectingProxies + self.connectingProxies = self.connectingProxies.concat(servers); + + // Index used to interleaf the server connects, avoiding + // runtime issues on io constrained vm's + var timeoutInterval = 0; + + function connect(server, timeoutInterval) { + setTimeout(function() { + // Emit opening server event + self.emit('serverOpening', { + topologyId: self.id, + address: server.name + }); + + // Emit the initial topology + emitTopologyDescriptionChanged(self); + + // Add event handlers + server.once('close', handleInitialConnectEvent(self, 'close')); + server.once('timeout', handleInitialConnectEvent(self, 'timeout')); + server.once('parseError', handleInitialConnectEvent(self, 'parseError')); + server.once('error', handleInitialConnectEvent(self, 'error')); + server.once('connect', handleInitialConnectEvent(self, 'connect')); + + // Command Monitoring events + relayEvents(server, self, ['commandStarted', 'commandSucceeded', 'commandFailed']); + + // Start connection + server.connect(self.s.connectOptions); + }, timeoutInterval); + } + + // Start all the servers + servers.forEach(server => connect(server, timeoutInterval++)); +} + +function pickProxy(self, session) { + // TODO: Destructure :) + const transaction = session && session.transaction; + + if (transaction && transaction.server) { + if (transaction.server.isConnected()) { + return transaction.server; + } else { + transaction.unpinServer(); + } + } + + // Get the currently connected Proxies + var connectedProxies = self.connectedProxies.slice(0); + + // Set lower bound + var lowerBoundLatency = Number.MAX_VALUE; + + // Determine the lower bound for the Proxies + for (var i = 0; i < connectedProxies.length; i++) { + if (connectedProxies[i].lastIsMasterMS < lowerBoundLatency) { + lowerBoundLatency = connectedProxies[i].lastIsMasterMS; + } + } + + // Filter out the possible servers + connectedProxies = connectedProxies.filter(function(server) { + if ( + server.lastIsMasterMS <= lowerBoundLatency + self.s.localThresholdMS && + server.isConnected() + ) { + return true; + } + }); + + let proxy; + + // We have no connectedProxies pick first of the connected ones + if (connectedProxies.length === 0) { + proxy = self.connectedProxies[0]; + } else { + // Get proxy + proxy = connectedProxies[self.index % connectedProxies.length]; + // Update the index + self.index = (self.index + 1) % connectedProxies.length; + } + + if (transaction && transaction.isActive && proxy && proxy.isConnected()) { + transaction.pinServer(proxy); + } + + // Return the proxy + return proxy; +} + +function moveServerFrom(from, to, proxy) { + for (var i = 0; i < from.length; i++) { + if (from[i].name === proxy.name) { + from.splice(i, 1); + } + } + + for (i = 0; i < to.length; i++) { + if (to[i].name === proxy.name) { + to.splice(i, 1); + } + } + + to.push(proxy); +} + +function removeProxyFrom(from, proxy) { + for (var i = 0; i < from.length; i++) { + if (from[i].name === proxy.name) { + from.splice(i, 1); + } + } +} + +function reconnectProxies(self, proxies, callback) { + // Count lefts + var count = proxies.length; + + // Handle events + var _handleEvent = function(self, event) { + return function() { + var _self = this; + count = count - 1; + + // Destroyed + if (self.state === DESTROYED || self.state === DESTROYING || self.state === UNREFERENCED) { + moveServerFrom(self.connectingProxies, self.disconnectedProxies, _self); + return this.destroy(); + } + + if (event === 'connect') { + // Destroyed + if (self.state === DESTROYED || self.state === DESTROYING || self.state === UNREFERENCED) { + moveServerFrom(self.connectingProxies, self.disconnectedProxies, _self); + return _self.destroy(); + } + + // Remove the handlers + for (var i = 0; i < handlers.length; i++) { + _self.removeAllListeners(handlers[i]); + } + + // Add stable state handlers + _self.on('error', handleEvent(self, 'error')); + _self.on('close', handleEvent(self, 'close')); + _self.on('timeout', handleEvent(self, 'timeout')); + _self.on('parseError', handleEvent(self, 'parseError')); + + // Move to the connected servers + moveServerFrom(self.connectingProxies, self.connectedProxies, _self); + // Emit topology Change + emitTopologyDescriptionChanged(self); + // Emit joined event + self.emit('joined', 'mongos', _self); + } else { + // Move from connectingProxies + moveServerFrom(self.connectingProxies, self.disconnectedProxies, _self); + this.destroy(); + } + + // Are we done finish up callback + if (count === 0) { + callback(); + } + }; + }; + + // No new servers + if (count === 0) { + return callback(); + } + + // Execute method + function execute(_server, i) { + setTimeout(function() { + // Destroyed + if (self.state === DESTROYED || self.state === DESTROYING || self.state === UNREFERENCED) { + return; + } + + // Create a new server instance + var server = new Server( + Object.assign({}, self.s.options, { + host: _server.name.split(':')[0], + port: parseInt(_server.name.split(':')[1], 10), + reconnect: false, + monitoring: false, + parent: self, + clientInfo: clone(self.s.clientInfo) + }) + ); + + destroyServer(_server, { force: true }); + removeProxyFrom(self.disconnectedProxies, _server); + + // Relay the server description change + relayEvents(server, self, ['serverDescriptionChanged']); + + // Emit opening server event + self.emit('serverOpening', { + topologyId: server.s.topologyId !== -1 ? server.s.topologyId : self.id, + address: server.name + }); + + // Add temp handlers + server.once('connect', _handleEvent(self, 'connect')); + server.once('close', _handleEvent(self, 'close')); + server.once('timeout', _handleEvent(self, 'timeout')); + server.once('error', _handleEvent(self, 'error')); + server.once('parseError', _handleEvent(self, 'parseError')); + + // Command Monitoring events + relayEvents(server, self, ['commandStarted', 'commandSucceeded', 'commandFailed']); + + // Connect to proxy + self.connectingProxies.push(server); + server.connect(self.s.connectOptions); + }, i); + } + + // Create new instances + for (var i = 0; i < proxies.length; i++) { + execute(proxies[i], i); + } +} + +function topologyMonitor(self, options) { + options = options || {}; + + // no need to set up the monitor if we're already closed + if (self.state === DESTROYED || self.state === DESTROYING || self.state === UNREFERENCED) { + return; + } + + // Set momitoring timeout + self.haTimeoutId = setTimeout(function() { + if (self.state === DESTROYED || self.state === DESTROYING || self.state === UNREFERENCED) { + return; + } + + // If we have a primary and a disconnect handler, execute + // buffered operations + if (self.isConnected() && self.s.disconnectHandler) { + self.s.disconnectHandler.execute(); + } + + // Get the connectingServers + var proxies = self.connectedProxies.slice(0); + // Get the count + var count = proxies.length; + + // If the count is zero schedule a new fast + function pingServer(_self, _server, cb) { + // Measure running time + var start = new Date().getTime(); + + // Emit the server heartbeat start + emitSDAMEvent(self, 'serverHeartbeatStarted', { connectionId: _server.name }); + + // Execute ismaster + _server.command( + 'admin.$cmd', + { + ismaster: true + }, + { + monitoring: true, + socketTimeout: self.s.options.connectionTimeout || 2000 + }, + function(err, r) { + if ( + self.state === DESTROYED || + self.state === DESTROYING || + self.state === UNREFERENCED + ) { + // Move from connectingProxies + moveServerFrom(self.connectedProxies, self.disconnectedProxies, _server); + _server.destroy(); + return cb(err, r); + } + + // Calculate latency + var latencyMS = new Date().getTime() - start; + + // We had an error, remove it from the state + if (err) { + // Emit the server heartbeat failure + emitSDAMEvent(self, 'serverHeartbeatFailed', { + durationMS: latencyMS, + failure: err, + connectionId: _server.name + }); + // Move from connected proxies to disconnected proxies + moveServerFrom(self.connectedProxies, self.disconnectedProxies, _server); + } else { + // Update the server ismaster + _server.ismaster = r.result; + _server.lastIsMasterMS = latencyMS; + + // Server heart beat event + emitSDAMEvent(self, 'serverHeartbeatSucceeded', { + durationMS: latencyMS, + reply: r.result, + connectionId: _server.name + }); + } + + cb(err, r); + } + ); + } + + // No proxies initiate monitor again + if (proxies.length === 0) { + // Emit close event if any listeners registered + if (self.listeners('close').length > 0 && self.state === CONNECTING) { + self.emit('error', new MongoError('no mongos proxy available')); + } else { + self.emit('close', self); + } + + // Attempt to connect to any unknown servers + return reconnectProxies(self, self.disconnectedProxies, function() { + if (self.state === DESTROYED || self.state === DESTROYING || self.state === UNREFERENCED) { + return; + } + + // Are we connected ? emit connect event + if (self.state === CONNECTING && options.firstConnect) { + self.emit('connect', self); + self.emit('fullsetup', self); + self.emit('all', self); + } else if (self.isConnected()) { + self.emit('reconnect', self); + } else if (!self.isConnected() && self.listeners('close').length > 0) { + self.emit('close', self); + } + + // Perform topology monitor + topologyMonitor(self); + }); + } + + // Ping all servers + for (var i = 0; i < proxies.length; i++) { + pingServer(self, proxies[i], function() { + count = count - 1; + + if (count === 0) { + if ( + self.state === DESTROYED || + self.state === DESTROYING || + self.state === UNREFERENCED + ) { + return; + } + + // Attempt to connect to any unknown servers + reconnectProxies(self, self.disconnectedProxies, function() { + if ( + self.state === DESTROYED || + self.state === DESTROYING || + self.state === UNREFERENCED + ) { + return; + } + + // Perform topology monitor + topologyMonitor(self); + }); + } + }); + } + }, self.s.haInterval); +} + +/** + * Returns the last known ismaster document for this server + * @method + * @return {object} + */ +Mongos.prototype.lastIsMaster = function() { + return this.ismaster; +}; + +/** + * Unref all connections belong to this server + * @method + */ +Mongos.prototype.unref = function() { + // Transition state + stateTransition(this, UNREFERENCED); + // Get all proxies + var proxies = this.connectedProxies.concat(this.connectingProxies); + proxies.forEach(function(x) { + x.unref(); + }); + + clearTimeout(this.haTimeoutId); +}; + +/** + * Destroy the server connection + * @param {boolean} [options.force=false] Force destroy the pool + * @method + */ +Mongos.prototype.destroy = function(options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + + options = options || {}; + + stateTransition(this, DESTROYING); + if (this.haTimeoutId) { + clearTimeout(this.haTimeoutId); + } + + const proxies = this.connectedProxies.concat(this.connectingProxies); + let serverCount = proxies.length; + const serverDestroyed = () => { + serverCount--; + if (serverCount > 0) { + return; + } + + emitTopologyDescriptionChanged(this); + emitSDAMEvent(this, 'topologyClosed', { topologyId: this.id }); + stateTransition(this, DESTROYED); + if (typeof callback === 'function') { + callback(null, null); + } + }; + + if (serverCount === 0) { + serverDestroyed(); + return; + } + + // Destroy all connecting servers + proxies.forEach(server => { + // Emit the sdam event + this.emit('serverClosed', { + topologyId: this.id, + address: server.name + }); + + destroyServer(server, options, serverDestroyed); + moveServerFrom(this.connectedProxies, this.disconnectedProxies, server); + }); +}; + +/** + * Figure out if the server is connected + * @method + * @return {boolean} + */ +Mongos.prototype.isConnected = function() { + return this.connectedProxies.length > 0; +}; + +/** + * Figure out if the server instance was destroyed by calling destroy + * @method + * @return {boolean} + */ +Mongos.prototype.isDestroyed = function() { + return this.state === DESTROYED; +}; + +// +// Operations +// + +function executeWriteOperation(args, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + // TODO: once we drop Node 4, use destructuring either here or in arguments. + const self = args.self; + const op = args.op; + const ns = args.ns; + const ops = args.ops; + + // Pick a server + let server = pickProxy(self, options.session); + // No server found error out + if (!server) return callback(new MongoError('no mongos proxy available')); + + const willRetryWrite = + !args.retrying && + !!options.retryWrites && + options.session && + isRetryableWritesSupported(self) && + !options.session.inTransaction(); + + const handler = (err, result) => { + if (!err) return callback(null, result); + if (!isRetryableError(err) || !willRetryWrite) { + err = getMMAPError(err); + return callback(err); + } + + // Pick another server + server = pickProxy(self, options.session); + + // No server found error out with original error + if (!server) { + return callback(err); + } + + const newArgs = Object.assign({}, args, { retrying: true }); + return executeWriteOperation(newArgs, options, callback); + }; + + if (callback.operationId) { + handler.operationId = callback.operationId; + } + + // increment and assign txnNumber + if (willRetryWrite) { + options.session.incrementTransactionNumber(); + options.willRetryWrite = willRetryWrite; + } + + // rerun the operation + server[op](ns, ops, options, handler); +} + +/** + * Insert one or more documents + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of documents to insert + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {boolean} [options.retryWrites] Enable retryable writes for this operation + * @param {opResultCallback} callback A callback function + */ +Mongos.prototype.insert = function(ns, ops, options, callback) { + if (typeof options === 'function') { + (callback = options), (options = {}), (options = options || {}); + } + + if (this.state === DESTROYED) { + return callback(new MongoError(f('topology was destroyed'))); + } + + // Not connected but we have a disconnecthandler + if (!this.isConnected() && this.s.disconnectHandler != null) { + return this.s.disconnectHandler.add('insert', ns, ops, options, callback); + } + + // No mongos proxy available + if (!this.isConnected()) { + return callback(new MongoError('no mongos proxy available')); + } + + // Execute write operation + executeWriteOperation({ self: this, op: 'insert', ns, ops }, options, callback); +}; + +/** + * Perform one or more update operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of updates + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {boolean} [options.retryWrites] Enable retryable writes for this operation + * @param {opResultCallback} callback A callback function + */ +Mongos.prototype.update = function(ns, ops, options, callback) { + if (typeof options === 'function') { + (callback = options), (options = {}), (options = options || {}); + } + + if (this.state === DESTROYED) { + return callback(new MongoError(f('topology was destroyed'))); + } + + // Not connected but we have a disconnecthandler + if (!this.isConnected() && this.s.disconnectHandler != null) { + return this.s.disconnectHandler.add('update', ns, ops, options, callback); + } + + // No mongos proxy available + if (!this.isConnected()) { + return callback(new MongoError('no mongos proxy available')); + } + + // Execute write operation + executeWriteOperation({ self: this, op: 'update', ns, ops }, options, callback); +}; + +/** + * Perform one or more remove operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of removes + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {boolean} [options.retryWrites] Enable retryable writes for this operation + * @param {opResultCallback} callback A callback function + */ +Mongos.prototype.remove = function(ns, ops, options, callback) { + if (typeof options === 'function') { + (callback = options), (options = {}), (options = options || {}); + } + + if (this.state === DESTROYED) { + return callback(new MongoError(f('topology was destroyed'))); + } + + // Not connected but we have a disconnecthandler + if (!this.isConnected() && this.s.disconnectHandler != null) { + return this.s.disconnectHandler.add('remove', ns, ops, options, callback); + } + + // No mongos proxy available + if (!this.isConnected()) { + return callback(new MongoError('no mongos proxy available')); + } + + // Execute write operation + executeWriteOperation({ self: this, op: 'remove', ns, ops }, options, callback); +}; + +const RETRYABLE_WRITE_OPERATIONS = ['findAndModify', 'insert', 'update', 'delete']; + +function isWriteCommand(command) { + return RETRYABLE_WRITE_OPERATIONS.some(op => command[op]); +} + +/** + * Execute a command + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object} cmd The command hash + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Connection} [options.connection] Specify connection object to execute command against + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {opResultCallback} callback A callback function + */ +Mongos.prototype.command = function(ns, cmd, options, callback) { + if (typeof options === 'function') { + (callback = options), (options = {}), (options = options || {}); + } + + if (this.state === DESTROYED) { + return callback(new MongoError(f('topology was destroyed'))); + } + + var self = this; + + // Pick a proxy + var server = pickProxy(self, options.session); + + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if ((server == null || !server.isConnected()) && this.s.disconnectHandler != null) { + return this.s.disconnectHandler.add('command', ns, cmd, options, callback); + } + + // No server returned we had an error + if (server == null) { + return callback(new MongoError('no mongos proxy available')); + } + + // Cloned options + var clonedOptions = cloneOptions(options); + clonedOptions.topology = self; + + const willRetryWrite = + !options.retrying && + options.retryWrites && + options.session && + isRetryableWritesSupported(self) && + !options.session.inTransaction() && + isWriteCommand(cmd); + + const cb = (err, result) => { + if (!err) return callback(null, result); + if (!isRetryableError(err)) { + return callback(err); + } + + if (willRetryWrite) { + const newOptions = Object.assign({}, clonedOptions, { retrying: true }); + return this.command(ns, cmd, newOptions, callback); + } + + return callback(err); + }; + + // increment and assign txnNumber + if (willRetryWrite) { + options.session.incrementTransactionNumber(); + options.willRetryWrite = willRetryWrite; + } + + // Execute the command + server.command(ns, cmd, clonedOptions, cb); +}; + +/** + * Get a new cursor + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object|Long} cmd Can be either a command returning a cursor or a cursorId + * @param {object} [options] Options for the cursor + * @param {object} [options.batchSize=0] Batchsize for the operation + * @param {array} [options.documents=[]] Initial documents list for cursor + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {object} [options.topology] The internal topology of the created cursor + * @returns {Cursor} + */ +Mongos.prototype.cursor = function(ns, cmd, options) { + options = options || {}; + const topology = options.topology || this; + + // Set up final cursor type + var FinalCursor = options.cursorFactory || this.s.Cursor; + + // Return the cursor + return new FinalCursor(topology, ns, cmd, options); +}; + +/** + * Selects a server + * + * @method + * @param {function} selector Unused + * @param {ReadPreference} [options.readPreference] Unused + * @param {ClientSession} [options.session] Specify a session if it is being used + * @param {function} callback + */ +Mongos.prototype.selectServer = function(selector, options, callback) { + if (typeof selector === 'function' && typeof callback === 'undefined') + (callback = selector), (selector = undefined), (options = {}); + if (typeof options === 'function') + (callback = options), (options = selector), (selector = undefined); + options = options || {}; + + const server = pickProxy(this, options.session); + if (server == null) { + callback(new MongoError('server selection failed')); + return; + } + + if (this.s.debug) this.emit('pickedServer', null, server); + callback(null, server); +}; + +/** + * All raw connections + * @method + * @return {Connection[]} + */ +Mongos.prototype.connections = function() { + var connections = []; + + for (var i = 0; i < this.connectedProxies.length; i++) { + connections = connections.concat(this.connectedProxies[i].connections()); + } + + return connections; +}; + +function emitTopologyDescriptionChanged(self) { + if (self.listeners('topologyDescriptionChanged').length > 0) { + var topology = 'Unknown'; + if (self.connectedProxies.length > 0) { + topology = 'Sharded'; + } + + // Generate description + var description = { + topologyType: topology, + servers: [] + }; + + // All proxies + var proxies = self.disconnectedProxies.concat(self.connectingProxies); + + // Add all the disconnected proxies + description.servers = description.servers.concat( + proxies.map(function(x) { + var description = x.getDescription(); + description.type = 'Unknown'; + return description; + }) + ); + + // Add all the connected proxies + description.servers = description.servers.concat( + self.connectedProxies.map(function(x) { + var description = x.getDescription(); + description.type = 'Mongos'; + return description; + }) + ); + + // Get the diff + var diffResult = diff(self.topologyDescription, description); + + // Create the result + var result = { + topologyId: self.id, + previousDescription: self.topologyDescription, + newDescription: description, + diff: diffResult + }; + + // Emit the topologyDescription change + if (diffResult.servers.length > 0) { + self.emit('topologyDescriptionChanged', result); + } + + // Set the new description + self.topologyDescription = description; + } +} + +/** + * A mongos connect event, used to verify that the connection is up and running + * + * @event Mongos#connect + * @type {Mongos} + */ + +/** + * A mongos reconnect event, used to verify that the mongos topology has reconnected + * + * @event Mongos#reconnect + * @type {Mongos} + */ + +/** + * A mongos fullsetup event, used to signal that all topology members have been contacted. + * + * @event Mongos#fullsetup + * @type {Mongos} + */ + +/** + * A mongos all event, used to signal that all topology members have been contacted. + * + * @event Mongos#all + * @type {Mongos} + */ + +/** + * A server member left the mongos list + * + * @event Mongos#left + * @type {Mongos} + * @param {string} type The type of member that left (mongos) + * @param {Server} server The server object that left + */ + +/** + * A server member joined the mongos list + * + * @event Mongos#joined + * @type {Mongos} + * @param {string} type The type of member that left (mongos) + * @param {Server} server The server object that joined + */ + +/** + * A server opening SDAM monitoring event + * + * @event Mongos#serverOpening + * @type {object} + */ + +/** + * A server closed SDAM monitoring event + * + * @event Mongos#serverClosed + * @type {object} + */ + +/** + * A server description SDAM change monitoring event + * + * @event Mongos#serverDescriptionChanged + * @type {object} + */ + +/** + * A topology open SDAM event + * + * @event Mongos#topologyOpening + * @type {object} + */ + +/** + * A topology closed SDAM event + * + * @event Mongos#topologyClosed + * @type {object} + */ + +/** + * A topology structure SDAM change event + * + * @event Mongos#topologyDescriptionChanged + * @type {object} + */ + +/** + * A topology serverHeartbeatStarted SDAM event + * + * @event Mongos#serverHeartbeatStarted + * @type {object} + */ + +/** + * A topology serverHeartbeatFailed SDAM event + * + * @event Mongos#serverHeartbeatFailed + * @type {object} + */ + +/** + * A topology serverHeartbeatSucceeded SDAM change event + * + * @event Mongos#serverHeartbeatSucceeded + * @type {object} + */ + +/** + * An event emitted indicating a command was started, if command monitoring is enabled + * + * @event Mongos#commandStarted + * @type {object} + */ + +/** + * An event emitted indicating a command succeeded, if command monitoring is enabled + * + * @event Mongos#commandSucceeded + * @type {object} + */ + +/** + * An event emitted indicating a command failed, if command monitoring is enabled + * + * @event Mongos#commandFailed + * @type {object} + */ + +module.exports = Mongos; diff --git a/scripts/node_modules/mongodb/lib/core/topologies/read_preference.js b/scripts/node_modules/mongodb/lib/core/topologies/read_preference.js new file mode 100644 index 00000000..a813ec4f --- /dev/null +++ b/scripts/node_modules/mongodb/lib/core/topologies/read_preference.js @@ -0,0 +1,202 @@ +'use strict'; + +/** + * The **ReadPreference** class is a class that represents a MongoDB ReadPreference and is + * used to construct connections. + * @class + * @param {string} mode A string describing the read preference mode (primary|primaryPreferred|secondary|secondaryPreferred|nearest) + * @param {array} tags The tags object + * @param {object} [options] Additional read preference options + * @param {number} [options.maxStalenessSeconds] Max secondary read staleness in seconds, Minimum value is 90 seconds. + * @see https://docs.mongodb.com/manual/core/read-preference/ + * @return {ReadPreference} + */ +const ReadPreference = function(mode, tags, options) { + if (!ReadPreference.isValid(mode)) { + throw new TypeError(`Invalid read preference mode ${mode}`); + } + + // TODO(major): tags MUST be an array of tagsets + if (tags && !Array.isArray(tags)) { + console.warn( + 'ReadPreference tags must be an array, this will change in the next major version' + ); + + if (typeof tags.maxStalenessSeconds !== 'undefined') { + // this is likely an options object + options = tags; + tags = undefined; + } else { + tags = [tags]; + } + } + + this.mode = mode; + this.tags = tags; + + options = options || {}; + if (options.maxStalenessSeconds != null) { + if (options.maxStalenessSeconds <= 0) { + throw new TypeError('maxStalenessSeconds must be a positive integer'); + } + + this.maxStalenessSeconds = options.maxStalenessSeconds; + + // NOTE: The minimum required wire version is 5 for this read preference. If the existing + // topology has a lower value then a MongoError will be thrown during server selection. + this.minWireVersion = 5; + } + + if (this.mode === ReadPreference.PRIMARY) { + if (this.tags && Array.isArray(this.tags) && this.tags.length > 0) { + throw new TypeError('Primary read preference cannot be combined with tags'); + } + + if (this.maxStalenessSeconds) { + throw new TypeError('Primary read preference cannot be combined with maxStalenessSeconds'); + } + } +}; + +// Support the deprecated `preference` property introduced in the porcelain layer +Object.defineProperty(ReadPreference.prototype, 'preference', { + enumerable: true, + get: function() { + return this.mode; + } +}); + +/* + * Read preference mode constants + */ +ReadPreference.PRIMARY = 'primary'; +ReadPreference.PRIMARY_PREFERRED = 'primaryPreferred'; +ReadPreference.SECONDARY = 'secondary'; +ReadPreference.SECONDARY_PREFERRED = 'secondaryPreferred'; +ReadPreference.NEAREST = 'nearest'; + +const VALID_MODES = [ + ReadPreference.PRIMARY, + ReadPreference.PRIMARY_PREFERRED, + ReadPreference.SECONDARY, + ReadPreference.SECONDARY_PREFERRED, + ReadPreference.NEAREST, + null +]; + +/** + * Construct a ReadPreference given an options object. + * + * @param {object} options The options object from which to extract the read preference. + * @return {ReadPreference} + */ +ReadPreference.fromOptions = function(options) { + const readPreference = options.readPreference; + const readPreferenceTags = options.readPreferenceTags; + + if (readPreference == null) { + return null; + } + + if (typeof readPreference === 'string') { + return new ReadPreference(readPreference, readPreferenceTags); + } else if (!(readPreference instanceof ReadPreference) && typeof readPreference === 'object') { + const mode = readPreference.mode || readPreference.preference; + if (mode && typeof mode === 'string') { + return new ReadPreference(mode, readPreference.tags, { + maxStalenessSeconds: readPreference.maxStalenessSeconds + }); + } + } + + return readPreference; +}; + +/** + * Validate if a mode is legal + * + * @method + * @param {string} mode The string representing the read preference mode. + * @return {boolean} True if a mode is valid + */ +ReadPreference.isValid = function(mode) { + return VALID_MODES.indexOf(mode) !== -1; +}; + +/** + * Validate if a mode is legal + * + * @method + * @param {string} mode The string representing the read preference mode. + * @return {boolean} True if a mode is valid + */ +ReadPreference.prototype.isValid = function(mode) { + return ReadPreference.isValid(typeof mode === 'string' ? mode : this.mode); +}; + +const needSlaveOk = ['primaryPreferred', 'secondary', 'secondaryPreferred', 'nearest']; + +/** + * Indicates that this readPreference needs the "slaveOk" bit when sent over the wire + * @method + * @return {boolean} + * @see https://docs.mongodb.com/manual/reference/mongodb-wire-protocol/#op-query + */ +ReadPreference.prototype.slaveOk = function() { + return needSlaveOk.indexOf(this.mode) !== -1; +}; + +/** + * Are the two read preference equal + * @method + * @param {ReadPreference} readPreference The read preference with which to check equality + * @return {boolean} True if the two ReadPreferences are equivalent + */ +ReadPreference.prototype.equals = function(readPreference) { + return readPreference.mode === this.mode; +}; + +/** + * Return JSON representation + * @method + * @return {Object} A JSON representation of the ReadPreference + */ +ReadPreference.prototype.toJSON = function() { + const readPreference = { mode: this.mode }; + if (Array.isArray(this.tags)) readPreference.tags = this.tags; + if (this.maxStalenessSeconds) readPreference.maxStalenessSeconds = this.maxStalenessSeconds; + return readPreference; +}; + +/** + * Primary read preference + * @member + * @type {ReadPreference} + */ +ReadPreference.primary = new ReadPreference('primary'); +/** + * Primary Preferred read preference + * @member + * @type {ReadPreference} + */ +ReadPreference.primaryPreferred = new ReadPreference('primaryPreferred'); +/** + * Secondary read preference + * @member + * @type {ReadPreference} + */ +ReadPreference.secondary = new ReadPreference('secondary'); +/** + * Secondary Preferred read preference + * @member + * @type {ReadPreference} + */ +ReadPreference.secondaryPreferred = new ReadPreference('secondaryPreferred'); +/** + * Nearest read preference + * @member + * @type {ReadPreference} + */ +ReadPreference.nearest = new ReadPreference('nearest'); + +module.exports = ReadPreference; diff --git a/scripts/node_modules/mongodb/lib/core/topologies/replset.js b/scripts/node_modules/mongodb/lib/core/topologies/replset.js new file mode 100644 index 00000000..89403ea4 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/core/topologies/replset.js @@ -0,0 +1,1553 @@ +'use strict'; + +const inherits = require('util').inherits; +const f = require('util').format; +const EventEmitter = require('events').EventEmitter; +const ReadPreference = require('./read_preference'); +const CoreCursor = require('../cursor').CoreCursor; +const retrieveBSON = require('../connection/utils').retrieveBSON; +const Logger = require('../connection/logger'); +const MongoError = require('../error').MongoError; +const Server = require('./server'); +const ReplSetState = require('./replset_state'); +const clone = require('./shared').clone; +const Timeout = require('./shared').Timeout; +const Interval = require('./shared').Interval; +const createClientInfo = require('./shared').createClientInfo; +const SessionMixins = require('./shared').SessionMixins; +const isRetryableWritesSupported = require('./shared').isRetryableWritesSupported; +const relayEvents = require('../utils').relayEvents; +const isRetryableError = require('../error').isRetryableError; +const BSON = retrieveBSON(); +const calculateDurationInMs = require('../utils').calculateDurationInMs; +const getMMAPError = require('./shared').getMMAPError; + +// +// States +var DISCONNECTED = 'disconnected'; +var CONNECTING = 'connecting'; +var CONNECTED = 'connected'; +var UNREFERENCED = 'unreferenced'; +var DESTROYED = 'destroyed'; + +function stateTransition(self, newState) { + var legalTransitions = { + disconnected: [CONNECTING, DESTROYED, DISCONNECTED], + connecting: [CONNECTING, DESTROYED, CONNECTED, DISCONNECTED], + connected: [CONNECTED, DISCONNECTED, DESTROYED, UNREFERENCED], + unreferenced: [UNREFERENCED, DESTROYED], + destroyed: [DESTROYED] + }; + + // Get current state + var legalStates = legalTransitions[self.state]; + if (legalStates && legalStates.indexOf(newState) !== -1) { + self.state = newState; + } else { + self.s.logger.error( + f( + 'Pool with id [%s] failed attempted illegal state transition from [%s] to [%s] only following state allowed [%s]', + self.id, + self.state, + newState, + legalStates + ) + ); + } +} + +// +// ReplSet instance id +var id = 1; +var handlers = ['connect', 'close', 'error', 'timeout', 'parseError']; + +/** + * Creates a new Replset instance + * @class + * @param {array} seedlist A list of seeds for the replicaset + * @param {boolean} options.setName The Replicaset set name + * @param {boolean} [options.secondaryOnlyConnectionAllowed=false] Allow connection to a secondary only replicaset + * @param {number} [options.haInterval=10000] The High availability period for replicaset inquiry + * @param {boolean} [options.emitError=false] Server will emit errors events + * @param {Cursor} [options.cursorFactory=Cursor] The cursor factory class used for all query cursors + * @param {number} [options.size=5] Server connection pool size + * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled + * @param {number} [options.keepAliveInitialDelay=0] Initial delay before TCP keep alive enabled + * @param {boolean} [options.noDelay=true] TCP Connection no delay + * @param {number} [options.connectionTimeout=10000] TCP Connection timeout setting + * @param {number} [options.socketTimeout=0] TCP Socket timeout setting + * @param {boolean} [options.ssl=false] Use SSL for connection + * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. + * @param {Buffer} [options.ca] SSL Certificate store binary buffer + * @param {Buffer} [options.crl] SSL Certificate revocation store binary buffer + * @param {Buffer} [options.cert] SSL Certificate binary buffer + * @param {Buffer} [options.key] SSL Key file binary buffer + * @param {string} [options.passphrase] SSL Certificate pass phrase + * @param {string} [options.servername=null] String containing the server name requested via TLS SNI. + * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates + * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits + * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. + * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. + * @param {number} [options.pingInterval=5000] Ping interval to check the response time to the different servers + * @param {number} [options.localThresholdMS=15] Cutoff latency point in MS for Replicaset member selection + * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. + * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology + * @return {ReplSet} A cursor instance + * @fires ReplSet#connect + * @fires ReplSet#ha + * @fires ReplSet#joined + * @fires ReplSet#left + * @fires ReplSet#failed + * @fires ReplSet#fullsetup + * @fires ReplSet#all + * @fires ReplSet#error + * @fires ReplSet#serverHeartbeatStarted + * @fires ReplSet#serverHeartbeatSucceeded + * @fires ReplSet#serverHeartbeatFailed + * @fires ReplSet#topologyOpening + * @fires ReplSet#topologyClosed + * @fires ReplSet#topologyDescriptionChanged + * @property {string} type the topology type. + * @property {string} parserType the parser type used (c++ or js). + */ +var ReplSet = function(seedlist, options) { + var self = this; + options = options || {}; + + // Validate seedlist + if (!Array.isArray(seedlist)) throw new MongoError('seedlist must be an array'); + // Validate list + if (seedlist.length === 0) throw new MongoError('seedlist must contain at least one entry'); + // Validate entries + seedlist.forEach(function(e) { + if (typeof e.host !== 'string' || typeof e.port !== 'number') + throw new MongoError('seedlist entry must contain a host and port'); + }); + + // Add event listener + EventEmitter.call(this); + + // Get replSet Id + this.id = id++; + + // Get the localThresholdMS + var localThresholdMS = options.localThresholdMS || 15; + // Backward compatibility + if (options.acceptableLatency) localThresholdMS = options.acceptableLatency; + + // Create a logger + var logger = Logger('ReplSet', options); + + // Internal state + this.s = { + options: Object.assign({}, options), + // BSON instance + bson: + options.bson || + new BSON([ + BSON.Binary, + BSON.Code, + BSON.DBRef, + BSON.Decimal128, + BSON.Double, + BSON.Int32, + BSON.Long, + BSON.Map, + BSON.MaxKey, + BSON.MinKey, + BSON.ObjectId, + BSON.BSONRegExp, + BSON.Symbol, + BSON.Timestamp + ]), + // Factory overrides + Cursor: options.cursorFactory || CoreCursor, + // Logger instance + logger: logger, + // Seedlist + seedlist: seedlist, + // Replicaset state + replicaSetState: new ReplSetState({ + id: this.id, + setName: options.setName, + acceptableLatency: localThresholdMS, + heartbeatFrequencyMS: options.haInterval ? options.haInterval : 10000, + logger: logger + }), + // Current servers we are connecting to + connectingServers: [], + // Ha interval + haInterval: options.haInterval ? options.haInterval : 10000, + // Minimum heartbeat frequency used if we detect a server close + minHeartbeatFrequencyMS: 500, + // Disconnect handler + disconnectHandler: options.disconnectHandler, + // Server selection index + index: 0, + // Connect function options passed in + connectOptions: {}, + // Are we running in debug mode + debug: typeof options.debug === 'boolean' ? options.debug : false, + // Client info + clientInfo: createClientInfo(options) + }; + + // Add handler for topology change + this.s.replicaSetState.on('topologyDescriptionChanged', function(r) { + self.emit('topologyDescriptionChanged', r); + }); + + // Log info warning if the socketTimeout < haInterval as it will cause + // a lot of recycled connections to happen. + if ( + this.s.logger.isWarn() && + this.s.options.socketTimeout !== 0 && + this.s.options.socketTimeout < this.s.haInterval + ) { + this.s.logger.warn( + f( + 'warning socketTimeout %s is less than haInterval %s. This might cause unnecessary server reconnections due to socket timeouts', + this.s.options.socketTimeout, + this.s.haInterval + ) + ); + } + + // Add forwarding of events from state handler + var types = ['joined', 'left']; + types.forEach(function(x) { + self.s.replicaSetState.on(x, function(t, s) { + self.emit(x, t, s); + }); + }); + + // Connect stat + this.initialConnectState = { + connect: false, + fullsetup: false, + all: false + }; + + // Disconnected state + this.state = DISCONNECTED; + this.haTimeoutId = null; + // Last ismaster + this.ismaster = null; + // Contains the intervalId + this.intervalIds = []; + + // Highest clusterTime seen in responses from the current deployment + this.clusterTime = null; +}; + +inherits(ReplSet, EventEmitter); +Object.assign(ReplSet.prototype, SessionMixins); + +Object.defineProperty(ReplSet.prototype, 'type', { + enumerable: true, + get: function() { + return 'replset'; + } +}); + +Object.defineProperty(ReplSet.prototype, 'parserType', { + enumerable: true, + get: function() { + return BSON.native ? 'c++' : 'js'; + } +}); + +Object.defineProperty(ReplSet.prototype, 'logicalSessionTimeoutMinutes', { + enumerable: true, + get: function() { + return this.s.replicaSetState.logicalSessionTimeoutMinutes || null; + } +}); + +function rexecuteOperations(self) { + // If we have a primary and a disconnect handler, execute + // buffered operations + if (self.s.replicaSetState.hasPrimaryAndSecondary() && self.s.disconnectHandler) { + self.s.disconnectHandler.execute(); + } else if (self.s.replicaSetState.hasPrimary() && self.s.disconnectHandler) { + self.s.disconnectHandler.execute({ executePrimary: true }); + } else if (self.s.replicaSetState.hasSecondary() && self.s.disconnectHandler) { + self.s.disconnectHandler.execute({ executeSecondary: true }); + } +} + +function connectNewServers(self, servers, callback) { + // Count lefts + var count = servers.length; + var error = null; + + // Handle events + var _handleEvent = function(self, event) { + return function(err) { + var _self = this; + count = count - 1; + + // Destroyed + if (self.state === DESTROYED || self.state === UNREFERENCED) { + return this.destroy({ force: true }); + } + + if (event === 'connect') { + // Destroyed + if (self.state === DESTROYED || self.state === UNREFERENCED) { + return _self.destroy({ force: true }); + } + + // Update the state + var result = self.s.replicaSetState.update(_self); + // Update the state with the new server + if (result) { + // Primary lastIsMaster store it + if (_self.lastIsMaster() && _self.lastIsMaster().ismaster) { + self.ismaster = _self.lastIsMaster(); + } + + // Remove the handlers + for (let i = 0; i < handlers.length; i++) { + _self.removeAllListeners(handlers[i]); + } + + // Add stable state handlers + _self.on('error', handleEvent(self, 'error')); + _self.on('close', handleEvent(self, 'close')); + _self.on('timeout', handleEvent(self, 'timeout')); + _self.on('parseError', handleEvent(self, 'parseError')); + + // Enalbe the monitoring of the new server + monitorServer(_self.lastIsMaster().me, self, {}); + + // Rexecute any stalled operation + rexecuteOperations(self); + } else { + _self.destroy({ force: true }); + } + } else if (event === 'error') { + error = err; + } + + // Rexecute any stalled operation + rexecuteOperations(self); + + // Are we done finish up callback + if (count === 0) { + callback(error); + } + }; + }; + + // No new servers + if (count === 0) return callback(); + + // Execute method + function execute(_server, i) { + setTimeout(function() { + // Destroyed + if (self.state === DESTROYED || self.state === UNREFERENCED) { + return; + } + + // Create a new server instance + var server = new Server( + Object.assign({}, self.s.options, { + host: _server.split(':')[0], + port: parseInt(_server.split(':')[1], 10), + reconnect: false, + monitoring: false, + parent: self, + clientInfo: clone(self.s.clientInfo) + }) + ); + + // Add temp handlers + server.once('connect', _handleEvent(self, 'connect')); + server.once('close', _handleEvent(self, 'close')); + server.once('timeout', _handleEvent(self, 'timeout')); + server.once('error', _handleEvent(self, 'error')); + server.once('parseError', _handleEvent(self, 'parseError')); + + // SDAM Monitoring events + server.on('serverOpening', e => self.emit('serverOpening', e)); + server.on('serverDescriptionChanged', e => self.emit('serverDescriptionChanged', e)); + server.on('serverClosed', e => self.emit('serverClosed', e)); + + // Command Monitoring events + relayEvents(server, self, ['commandStarted', 'commandSucceeded', 'commandFailed']); + + self.s.connectingServers.push(server); + server.connect(self.s.connectOptions); + }, i); + } + + // Create new instances + for (var i = 0; i < servers.length; i++) { + execute(servers[i], i); + } +} + +// Ping the server +var pingServer = function(self, server, cb) { + // Measure running time + var start = new Date().getTime(); + + // Emit the server heartbeat start + emitSDAMEvent(self, 'serverHeartbeatStarted', { connectionId: server.name }); + + // Execute ismaster + // Set the socketTimeout for a monitoring message to a low number + // Ensuring ismaster calls are timed out quickly + server.command( + 'admin.$cmd', + { + ismaster: true + }, + { + monitoring: true, + socketTimeout: self.s.options.connectionTimeout || 2000 + }, + function(err, r) { + if (self.state === DESTROYED || self.state === UNREFERENCED) { + server.destroy({ force: true }); + return cb(err, r); + } + + // Calculate latency + var latencyMS = new Date().getTime() - start; + + // Set the last updatedTime + var hrtime = process.hrtime(); + server.lastUpdateTime = (hrtime[0] * 1e9 + hrtime[1]) / 1e6; + + // We had an error, remove it from the state + if (err) { + // Emit the server heartbeat failure + emitSDAMEvent(self, 'serverHeartbeatFailed', { + durationMS: latencyMS, + failure: err, + connectionId: server.name + }); + + // Remove server from the state + self.s.replicaSetState.remove(server); + } else { + // Update the server ismaster + server.ismaster = r.result; + + // Check if we have a lastWriteDate convert it to MS + // and store on the server instance for later use + if (server.ismaster.lastWrite && server.ismaster.lastWrite.lastWriteDate) { + server.lastWriteDate = server.ismaster.lastWrite.lastWriteDate.getTime(); + } + + // Do we have a brand new server + if (server.lastIsMasterMS === -1) { + server.lastIsMasterMS = latencyMS; + } else if (server.lastIsMasterMS) { + // After the first measurement, average RTT MUST be computed using an + // exponentially-weighted moving average formula, with a weighting factor (alpha) of 0.2. + // If the prior average is denoted old_rtt, then the new average (new_rtt) is + // computed from a new RTT measurement (x) using the following formula: + // alpha = 0.2 + // new_rtt = alpha * x + (1 - alpha) * old_rtt + server.lastIsMasterMS = 0.2 * latencyMS + (1 - 0.2) * server.lastIsMasterMS; + } + + if (self.s.replicaSetState.update(server)) { + // Primary lastIsMaster store it + if (server.lastIsMaster() && server.lastIsMaster().ismaster) { + self.ismaster = server.lastIsMaster(); + } + } + + // Server heart beat event + emitSDAMEvent(self, 'serverHeartbeatSucceeded', { + durationMS: latencyMS, + reply: r.result, + connectionId: server.name + }); + } + + // Calculate the staleness for this server + self.s.replicaSetState.updateServerMaxStaleness(server, self.s.haInterval); + + // Callback + cb(err, r); + } + ); +}; + +// Each server is monitored in parallel in their own timeout loop +var monitorServer = function(host, self, options) { + // If this is not the initial scan + // Is this server already being monitoried, then skip monitoring + if (!options.haInterval) { + for (var i = 0; i < self.intervalIds.length; i++) { + if (self.intervalIds[i].__host === host) { + return; + } + } + } + + // Get the haInterval + var _process = options.haInterval ? Timeout : Interval; + var _haInterval = options.haInterval ? options.haInterval : self.s.haInterval; + + // Create the interval + var intervalId = new _process(function() { + if (self.state === DESTROYED || self.state === UNREFERENCED) { + // clearInterval(intervalId); + intervalId.stop(); + return; + } + + // Do we already have server connection available for this host + var _server = self.s.replicaSetState.get(host); + + // Check if we have a known server connection and reuse + if (_server) { + // Ping the server + return pingServer(self, _server, function(err) { + if (err) { + // NOTE: should something happen here? + return; + } + + if (self.state === DESTROYED || self.state === UNREFERENCED) { + intervalId.stop(); + return; + } + + // Filter out all called intervaliIds + self.intervalIds = self.intervalIds.filter(function(intervalId) { + return intervalId.isRunning(); + }); + + // Initial sweep + if (_process === Timeout) { + if ( + self.state === CONNECTING && + ((self.s.replicaSetState.hasSecondary() && + self.s.options.secondaryOnlyConnectionAllowed) || + self.s.replicaSetState.hasPrimary()) + ) { + self.state = CONNECTED; + + // Emit connected sign + process.nextTick(function() { + self.emit('connect', self); + }); + + // Start topology interval check + topologyMonitor(self, {}); + } + } else { + if ( + self.state === DISCONNECTED && + ((self.s.replicaSetState.hasSecondary() && + self.s.options.secondaryOnlyConnectionAllowed) || + self.s.replicaSetState.hasPrimary()) + ) { + self.state = CONNECTED; + + // Rexecute any stalled operation + rexecuteOperations(self); + + // Emit connected sign + process.nextTick(function() { + self.emit('reconnect', self); + }); + } + } + + if ( + self.initialConnectState.connect && + !self.initialConnectState.fullsetup && + self.s.replicaSetState.hasPrimaryAndSecondary() + ) { + // Set initial connect state + self.initialConnectState.fullsetup = true; + self.initialConnectState.all = true; + + process.nextTick(function() { + self.emit('fullsetup', self); + self.emit('all', self); + }); + } + }); + } + }, _haInterval); + + // Start the interval + intervalId.start(); + // Add the intervalId host name + intervalId.__host = host; + // Add the intervalId to our list of intervalIds + self.intervalIds.push(intervalId); +}; + +function topologyMonitor(self, options) { + if (self.state === DESTROYED || self.state === UNREFERENCED) return; + options = options || {}; + + // Get the servers + var servers = Object.keys(self.s.replicaSetState.set); + + // Get the haInterval + var _process = options.haInterval ? Timeout : Interval; + var _haInterval = options.haInterval ? options.haInterval : self.s.haInterval; + + if (_process === Timeout) { + return connectNewServers(self, self.s.replicaSetState.unknownServers, function(err) { + // Don't emit errors if the connection was already + if (self.state === DESTROYED || self.state === UNREFERENCED) { + return; + } + + if (!self.s.replicaSetState.hasPrimary() && !self.s.options.secondaryOnlyConnectionAllowed) { + if (err) { + return self.emit('error', err); + } + + self.emit( + 'error', + new MongoError('no primary found in replicaset or invalid replica set name') + ); + return self.destroy({ force: true }); + } else if ( + !self.s.replicaSetState.hasSecondary() && + self.s.options.secondaryOnlyConnectionAllowed + ) { + if (err) { + return self.emit('error', err); + } + + self.emit( + 'error', + new MongoError('no secondary found in replicaset or invalid replica set name') + ); + return self.destroy({ force: true }); + } + + for (var i = 0; i < servers.length; i++) { + monitorServer(servers[i], self, options); + } + }); + } else { + for (var i = 0; i < servers.length; i++) { + monitorServer(servers[i], self, options); + } + } + + // Run the reconnect process + function executeReconnect(self) { + return function() { + if (self.state === DESTROYED || self.state === UNREFERENCED) { + return; + } + + connectNewServers(self, self.s.replicaSetState.unknownServers, function() { + var monitoringFrequencey = self.s.replicaSetState.hasPrimary() + ? _haInterval + : self.s.minHeartbeatFrequencyMS; + + // Create a timeout + self.intervalIds.push(new Timeout(executeReconnect(self), monitoringFrequencey).start()); + }); + }; + } + + // Decide what kind of interval to use + var intervalTime = !self.s.replicaSetState.hasPrimary() + ? self.s.minHeartbeatFrequencyMS + : _haInterval; + + self.intervalIds.push(new Timeout(executeReconnect(self), intervalTime).start()); +} + +function addServerToList(list, server) { + for (var i = 0; i < list.length; i++) { + if (list[i].name.toLowerCase() === server.name.toLowerCase()) return true; + } + + list.push(server); +} + +function handleEvent(self, event) { + return function() { + if (self.state === DESTROYED || self.state === UNREFERENCED) return; + // Debug log + if (self.s.logger.isDebug()) { + self.s.logger.debug( + f('handleEvent %s from server %s in replset with id %s', event, this.name, self.id) + ); + } + + // Remove from the replicaset state + self.s.replicaSetState.remove(this); + + // Are we in a destroyed state return + if (self.state === DESTROYED || self.state === UNREFERENCED) return; + + // If no primary and secondary available + if ( + !self.s.replicaSetState.hasPrimary() && + !self.s.replicaSetState.hasSecondary() && + self.s.options.secondaryOnlyConnectionAllowed + ) { + stateTransition(self, DISCONNECTED); + } else if (!self.s.replicaSetState.hasPrimary()) { + stateTransition(self, DISCONNECTED); + } + + addServerToList(self.s.connectingServers, this); + }; +} + +function shouldTriggerConnect(self) { + const isConnecting = self.state === CONNECTING; + const hasPrimary = self.s.replicaSetState.hasPrimary(); + const hasSecondary = self.s.replicaSetState.hasSecondary(); + const secondaryOnlyConnectionAllowed = self.s.options.secondaryOnlyConnectionAllowed; + const readPreferenceSecondary = + self.s.connectOptions.readPreference && + self.s.connectOptions.readPreference.equals(ReadPreference.secondary); + + return ( + (isConnecting && + ((readPreferenceSecondary && hasSecondary) || (!readPreferenceSecondary && hasPrimary))) || + (hasSecondary && secondaryOnlyConnectionAllowed) + ); +} + +function handleInitialConnectEvent(self, event) { + return function() { + var _this = this; + // Debug log + if (self.s.logger.isDebug()) { + self.s.logger.debug( + f( + 'handleInitialConnectEvent %s from server %s in replset with id %s', + event, + this.name, + self.id + ) + ); + } + + // Destroy the instance + if (self.state === DESTROYED || self.state === UNREFERENCED) { + return this.destroy({ force: true }); + } + + // Check the type of server + if (event === 'connect') { + // Update the state + var result = self.s.replicaSetState.update(_this); + if (result === true) { + // Primary lastIsMaster store it + if (_this.lastIsMaster() && _this.lastIsMaster().ismaster) { + self.ismaster = _this.lastIsMaster(); + } + + // Debug log + if (self.s.logger.isDebug()) { + self.s.logger.debug( + f( + 'handleInitialConnectEvent %s from server %s in replset with id %s has state [%s]', + event, + _this.name, + self.id, + JSON.stringify(self.s.replicaSetState.set) + ) + ); + } + + // Remove the handlers + for (let i = 0; i < handlers.length; i++) { + _this.removeAllListeners(handlers[i]); + } + + // Add stable state handlers + _this.on('error', handleEvent(self, 'error')); + _this.on('close', handleEvent(self, 'close')); + _this.on('timeout', handleEvent(self, 'timeout')); + _this.on('parseError', handleEvent(self, 'parseError')); + + // Do we have a primary or primaryAndSecondary + if (shouldTriggerConnect(self)) { + // We are connected + self.state = CONNECTED; + + // Set initial connect state + self.initialConnectState.connect = true; + // Emit connect event + process.nextTick(function() { + self.emit('connect', self); + }); + + topologyMonitor(self, {}); + } + } else if (result instanceof MongoError) { + _this.destroy({ force: true }); + self.destroy({ force: true }); + return self.emit('error', result); + } else { + _this.destroy({ force: true }); + } + } else { + // Emit failure to connect + self.emit('failed', this); + + addServerToList(self.s.connectingServers, this); + // Remove from the state + self.s.replicaSetState.remove(this); + } + + if ( + self.initialConnectState.connect && + !self.initialConnectState.fullsetup && + self.s.replicaSetState.hasPrimaryAndSecondary() + ) { + // Set initial connect state + self.initialConnectState.fullsetup = true; + self.initialConnectState.all = true; + + process.nextTick(function() { + self.emit('fullsetup', self); + self.emit('all', self); + }); + } + + // Remove from the list from connectingServers + for (var i = 0; i < self.s.connectingServers.length; i++) { + if (self.s.connectingServers[i].equals(this)) { + self.s.connectingServers.splice(i, 1); + } + } + + // Trigger topologyMonitor + if (self.s.connectingServers.length === 0 && self.state === CONNECTING) { + topologyMonitor(self, { haInterval: 1 }); + } + }; +} + +function connectServers(self, servers) { + // Update connectingServers + self.s.connectingServers = self.s.connectingServers.concat(servers); + + // Index used to interleaf the server connects, avoiding + // runtime issues on io constrained vm's + var timeoutInterval = 0; + + function connect(server, timeoutInterval) { + setTimeout(function() { + // Add the server to the state + if (self.s.replicaSetState.update(server)) { + // Primary lastIsMaster store it + if (server.lastIsMaster() && server.lastIsMaster().ismaster) { + self.ismaster = server.lastIsMaster(); + } + } + + // Add event handlers + server.once('close', handleInitialConnectEvent(self, 'close')); + server.once('timeout', handleInitialConnectEvent(self, 'timeout')); + server.once('parseError', handleInitialConnectEvent(self, 'parseError')); + server.once('error', handleInitialConnectEvent(self, 'error')); + server.once('connect', handleInitialConnectEvent(self, 'connect')); + + // SDAM Monitoring events + server.on('serverOpening', e => self.emit('serverOpening', e)); + server.on('serverDescriptionChanged', e => self.emit('serverDescriptionChanged', e)); + server.on('serverClosed', e => self.emit('serverClosed', e)); + + // Command Monitoring events + relayEvents(server, self, ['commandStarted', 'commandSucceeded', 'commandFailed']); + + // Start connection + server.connect(self.s.connectOptions); + }, timeoutInterval); + } + + // Start all the servers + while (servers.length > 0) { + connect(servers.shift(), timeoutInterval++); + } +} + +/** + * Emit event if it exists + * @method + */ +function emitSDAMEvent(self, event, description) { + if (self.listeners(event).length > 0) { + self.emit(event, description); + } +} + +/** + * Initiate server connect + */ +ReplSet.prototype.connect = function(options) { + var self = this; + // Add any connect level options to the internal state + this.s.connectOptions = options || {}; + + // Set connecting state + stateTransition(this, CONNECTING); + + // Create server instances + var servers = this.s.seedlist.map(function(x) { + return new Server( + Object.assign({}, self.s.options, x, options, { + reconnect: false, + monitoring: false, + parent: self, + clientInfo: clone(self.s.clientInfo) + }) + ); + }); + + // Error out as high availbility interval must be < than socketTimeout + if ( + this.s.options.socketTimeout > 0 && + this.s.options.socketTimeout <= this.s.options.haInterval + ) { + return self.emit( + 'error', + new MongoError( + f( + 'haInterval [%s] MS must be set to less than socketTimeout [%s] MS', + this.s.options.haInterval, + this.s.options.socketTimeout + ) + ) + ); + } + + // Emit the topology opening event + emitSDAMEvent(this, 'topologyOpening', { topologyId: this.id }); + // Start all server connections + connectServers(self, servers); +}; + +/** + * Authenticate the topology. + * @method + * @param {MongoCredentials} credentials The credentials for authentication we are using + * @param {authResultCallback} callback A callback function + */ +ReplSet.prototype.auth = function(credentials, callback) { + if (typeof callback === 'function') callback(null, null); +}; + +/** + * Destroy the server connection + * @param {boolean} [options.force=false] Force destroy the pool + * @method + */ +ReplSet.prototype.destroy = function(options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + + options = options || {}; + + let destroyCount = this.s.connectingServers.length + 1; // +1 for the callback from `replicaSetState.destroy` + const serverDestroyed = () => { + destroyCount--; + if (destroyCount > 0) { + return; + } + + // Emit toplogy closing event + emitSDAMEvent(this, 'topologyClosed', { topologyId: this.id }); + + // Transition state + stateTransition(this, DESTROYED); + + if (typeof callback === 'function') { + callback(null, null); + } + }; + + // Clear out any monitoring process + if (this.haTimeoutId) clearTimeout(this.haTimeoutId); + + // Clear out all monitoring + for (var i = 0; i < this.intervalIds.length; i++) { + this.intervalIds[i].stop(); + } + + // Reset list of intervalIds + this.intervalIds = []; + + if (destroyCount === 0) { + serverDestroyed(); + return; + } + + // Destroy the replicaset + this.s.replicaSetState.destroy(options, serverDestroyed); + + // Destroy all connecting servers + this.s.connectingServers.forEach(function(x) { + x.destroy(options, serverDestroyed); + }); +}; + +/** + * Unref all connections belong to this server + * @method + */ +ReplSet.prototype.unref = function() { + // Transition state + stateTransition(this, UNREFERENCED); + + this.s.replicaSetState.allServers().forEach(function(x) { + x.unref(); + }); + + clearTimeout(this.haTimeoutId); +}; + +/** + * Returns the last known ismaster document for this server + * @method + * @return {object} + */ +ReplSet.prototype.lastIsMaster = function() { + // If secondaryOnlyConnectionAllowed and no primary but secondary + // return the secondaries ismaster result. + if ( + this.s.options.secondaryOnlyConnectionAllowed && + !this.s.replicaSetState.hasPrimary() && + this.s.replicaSetState.hasSecondary() + ) { + return this.s.replicaSetState.secondaries[0].lastIsMaster(); + } + + return this.s.replicaSetState.primary + ? this.s.replicaSetState.primary.lastIsMaster() + : this.ismaster; +}; + +/** + * All raw connections + * @method + * @return {Connection[]} + */ +ReplSet.prototype.connections = function() { + var servers = this.s.replicaSetState.allServers(); + var connections = []; + for (var i = 0; i < servers.length; i++) { + connections = connections.concat(servers[i].connections()); + } + + return connections; +}; + +/** + * Figure out if the server is connected + * @method + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @return {boolean} + */ +ReplSet.prototype.isConnected = function(options) { + options = options || {}; + + // If we specified a read preference check if we are connected to something + // than can satisfy this + if (options.readPreference && options.readPreference.equals(ReadPreference.secondary)) { + return this.s.replicaSetState.hasSecondary(); + } + + if (options.readPreference && options.readPreference.equals(ReadPreference.primary)) { + return this.s.replicaSetState.hasPrimary(); + } + + if (options.readPreference && options.readPreference.equals(ReadPreference.primaryPreferred)) { + return this.s.replicaSetState.hasSecondary() || this.s.replicaSetState.hasPrimary(); + } + + if (options.readPreference && options.readPreference.equals(ReadPreference.secondaryPreferred)) { + return this.s.replicaSetState.hasSecondary() || this.s.replicaSetState.hasPrimary(); + } + + if (this.s.options.secondaryOnlyConnectionAllowed && this.s.replicaSetState.hasSecondary()) { + return true; + } + + return this.s.replicaSetState.hasPrimary(); +}; + +/** + * Figure out if the replicaset instance was destroyed by calling destroy + * @method + * @return {boolean} + */ +ReplSet.prototype.isDestroyed = function() { + return this.state === DESTROYED; +}; + +const SERVER_SELECTION_TIMEOUT_MS = 10000; // hardcoded `serverSelectionTimeoutMS` for legacy topology +const SERVER_SELECTION_INTERVAL_MS = 1000; // time to wait between selection attempts +/** + * Selects a server + * + * @method + * @param {function} selector Unused + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {ClientSession} [options.session] Unused + * @param {function} callback + */ +ReplSet.prototype.selectServer = function(selector, options, callback) { + if (typeof selector === 'function' && typeof callback === 'undefined') + (callback = selector), (selector = undefined), (options = {}); + if (typeof options === 'function') (callback = options), (options = selector); + options = options || {}; + + let readPreference; + if (selector instanceof ReadPreference) { + readPreference = selector; + } else { + readPreference = options.readPreference || ReadPreference.primary; + } + + let lastError; + const start = process.hrtime(); + const _selectServer = () => { + if (calculateDurationInMs(start) >= SERVER_SELECTION_TIMEOUT_MS) { + if (lastError != null) { + callback(lastError, null); + } else { + callback(new MongoError('Server selection timed out')); + } + + return; + } + + const server = this.s.replicaSetState.pickServer(readPreference); + if (server == null) { + setTimeout(_selectServer, SERVER_SELECTION_INTERVAL_MS); + return; + } + + if (!(server instanceof Server)) { + lastError = server; + setTimeout(_selectServer, SERVER_SELECTION_INTERVAL_MS); + return; + } + + if (this.s.debug) this.emit('pickedServer', options.readPreference, server); + callback(null, server); + }; + + _selectServer(); +}; + +/** + * Get all connected servers + * @method + * @return {Server[]} + */ +ReplSet.prototype.getServers = function() { + return this.s.replicaSetState.allServers(); +}; + +// +// Execute write operation +function executeWriteOperation(args, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + // TODO: once we drop Node 4, use destructuring either here or in arguments. + const self = args.self; + const op = args.op; + const ns = args.ns; + const ops = args.ops; + + if (self.state === DESTROYED) { + return callback(new MongoError(f('topology was destroyed'))); + } + + const willRetryWrite = + !args.retrying && + !!options.retryWrites && + options.session && + isRetryableWritesSupported(self) && + !options.session.inTransaction(); + + if (!self.s.replicaSetState.hasPrimary()) { + if (self.s.disconnectHandler) { + // Not connected but we have a disconnecthandler + return self.s.disconnectHandler.add(op, ns, ops, options, callback); + } else if (!willRetryWrite) { + // No server returned we had an error + return callback(new MongoError('no primary server found')); + } + } + + const handler = (err, result) => { + if (!err) return callback(null, result); + if (!isRetryableError(err)) { + err = getMMAPError(err); + return callback(err); + } + + if (willRetryWrite) { + const newArgs = Object.assign({}, args, { retrying: true }); + return executeWriteOperation(newArgs, options, callback); + } + + // Per SDAM, remove primary from replicaset + if (self.s.replicaSetState.primary) { + self.s.replicaSetState.primary.destroy(); + self.s.replicaSetState.remove(self.s.replicaSetState.primary, { force: true }); + } + + return callback(err); + }; + + if (callback.operationId) { + handler.operationId = callback.operationId; + } + + // increment and assign txnNumber + if (willRetryWrite) { + options.session.incrementTransactionNumber(); + options.willRetryWrite = willRetryWrite; + } + + self.s.replicaSetState.primary[op](ns, ops, options, handler); +} + +/** + * Insert one or more documents + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of documents to insert + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {boolean} [options.retryWrites] Enable retryable writes for this operation + * @param {opResultCallback} callback A callback function + */ +ReplSet.prototype.insert = function(ns, ops, options, callback) { + // Execute write operation + executeWriteOperation({ self: this, op: 'insert', ns, ops }, options, callback); +}; + +/** + * Perform one or more update operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of updates + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {boolean} [options.retryWrites] Enable retryable writes for this operation + * @param {opResultCallback} callback A callback function + */ +ReplSet.prototype.update = function(ns, ops, options, callback) { + // Execute write operation + executeWriteOperation({ self: this, op: 'update', ns, ops }, options, callback); +}; + +/** + * Perform one or more remove operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of removes + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {boolean} [options.retryWrites] Enable retryable writes for this operation + * @param {opResultCallback} callback A callback function + */ +ReplSet.prototype.remove = function(ns, ops, options, callback) { + // Execute write operation + executeWriteOperation({ self: this, op: 'remove', ns, ops }, options, callback); +}; + +const RETRYABLE_WRITE_OPERATIONS = ['findAndModify', 'insert', 'update', 'delete']; + +function isWriteCommand(command) { + return RETRYABLE_WRITE_OPERATIONS.some(op => command[op]); +} + +/** + * Execute a command + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object} cmd The command hash + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Connection} [options.connection] Specify connection object to execute command against + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {opResultCallback} callback A callback function + */ +ReplSet.prototype.command = function(ns, cmd, options, callback) { + if (typeof options === 'function') { + (callback = options), (options = {}), (options = options || {}); + } + + if (this.state === DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + var self = this; + + // Establish readPreference + var readPreference = options.readPreference ? options.readPreference : ReadPreference.primary; + + // If the readPreference is primary and we have no primary, store it + if ( + readPreference.preference === 'primary' && + !this.s.replicaSetState.hasPrimary() && + this.s.disconnectHandler != null + ) { + return this.s.disconnectHandler.add('command', ns, cmd, options, callback); + } else if ( + readPreference.preference === 'secondary' && + !this.s.replicaSetState.hasSecondary() && + this.s.disconnectHandler != null + ) { + return this.s.disconnectHandler.add('command', ns, cmd, options, callback); + } else if ( + readPreference.preference !== 'primary' && + !this.s.replicaSetState.hasSecondary() && + !this.s.replicaSetState.hasPrimary() && + this.s.disconnectHandler != null + ) { + return this.s.disconnectHandler.add('command', ns, cmd, options, callback); + } + + // Pick a server + var server = this.s.replicaSetState.pickServer(readPreference); + // We received an error, return it + if (!(server instanceof Server)) return callback(server); + // Emit debug event + if (self.s.debug) self.emit('pickedServer', ReadPreference.primary, server); + + // No server returned we had an error + if (server == null) { + return callback( + new MongoError( + f('no server found that matches the provided readPreference %s', readPreference) + ) + ); + } + + const willRetryWrite = + !options.retrying && + !!options.retryWrites && + options.session && + isRetryableWritesSupported(self) && + !options.session.inTransaction() && + isWriteCommand(cmd); + + const cb = (err, result) => { + if (!err) return callback(null, result); + if (!isRetryableError(err)) { + return callback(err); + } + + if (willRetryWrite) { + const newOptions = Object.assign({}, options, { retrying: true }); + return this.command(ns, cmd, newOptions, callback); + } + + // Per SDAM, remove primary from replicaset + if (this.s.replicaSetState.primary) { + this.s.replicaSetState.primary.destroy(); + this.s.replicaSetState.remove(this.s.replicaSetState.primary, { force: true }); + } + + return callback(err); + }; + + // increment and assign txnNumber + if (willRetryWrite) { + options.session.incrementTransactionNumber(); + options.willRetryWrite = willRetryWrite; + } + + // Execute the command + server.command(ns, cmd, options, cb); +}; + +/** + * Get a new cursor + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object|Long} cmd Can be either a command returning a cursor or a cursorId + * @param {object} [options] Options for the cursor + * @param {object} [options.batchSize=0] Batchsize for the operation + * @param {array} [options.documents=[]] Initial documents list for cursor + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {object} [options.topology] The internal topology of the created cursor + * @returns {Cursor} + */ +ReplSet.prototype.cursor = function(ns, cmd, options) { + options = options || {}; + const topology = options.topology || this; + + // Set up final cursor type + var FinalCursor = options.cursorFactory || this.s.Cursor; + + // Return the cursor + return new FinalCursor(topology, ns, cmd, options); +}; + +/** + * A replset connect event, used to verify that the connection is up and running + * + * @event ReplSet#connect + * @type {ReplSet} + */ + +/** + * A replset reconnect event, used to verify that the topology reconnected + * + * @event ReplSet#reconnect + * @type {ReplSet} + */ + +/** + * A replset fullsetup event, used to signal that all topology members have been contacted. + * + * @event ReplSet#fullsetup + * @type {ReplSet} + */ + +/** + * A replset all event, used to signal that all topology members have been contacted. + * + * @event ReplSet#all + * @type {ReplSet} + */ + +/** + * A replset failed event, used to signal that initial replset connection failed. + * + * @event ReplSet#failed + * @type {ReplSet} + */ + +/** + * A server member left the replicaset + * + * @event ReplSet#left + * @type {function} + * @param {string} type The type of member that left (primary|secondary|arbiter) + * @param {Server} server The server object that left + */ + +/** + * A server member joined the replicaset + * + * @event ReplSet#joined + * @type {function} + * @param {string} type The type of member that joined (primary|secondary|arbiter) + * @param {Server} server The server object that joined + */ + +/** + * A server opening SDAM monitoring event + * + * @event ReplSet#serverOpening + * @type {object} + */ + +/** + * A server closed SDAM monitoring event + * + * @event ReplSet#serverClosed + * @type {object} + */ + +/** + * A server description SDAM change monitoring event + * + * @event ReplSet#serverDescriptionChanged + * @type {object} + */ + +/** + * A topology open SDAM event + * + * @event ReplSet#topologyOpening + * @type {object} + */ + +/** + * A topology closed SDAM event + * + * @event ReplSet#topologyClosed + * @type {object} + */ + +/** + * A topology structure SDAM change event + * + * @event ReplSet#topologyDescriptionChanged + * @type {object} + */ + +/** + * A topology serverHeartbeatStarted SDAM event + * + * @event ReplSet#serverHeartbeatStarted + * @type {object} + */ + +/** + * A topology serverHeartbeatFailed SDAM event + * + * @event ReplSet#serverHeartbeatFailed + * @type {object} + */ + +/** + * A topology serverHeartbeatSucceeded SDAM change event + * + * @event ReplSet#serverHeartbeatSucceeded + * @type {object} + */ + +/** + * An event emitted indicating a command was started, if command monitoring is enabled + * + * @event ReplSet#commandStarted + * @type {object} + */ + +/** + * An event emitted indicating a command succeeded, if command monitoring is enabled + * + * @event ReplSet#commandSucceeded + * @type {object} + */ + +/** + * An event emitted indicating a command failed, if command monitoring is enabled + * + * @event ReplSet#commandFailed + * @type {object} + */ + +module.exports = ReplSet; diff --git a/scripts/node_modules/mongodb/lib/core/topologies/replset_state.js b/scripts/node_modules/mongodb/lib/core/topologies/replset_state.js new file mode 100644 index 00000000..24c16d6d --- /dev/null +++ b/scripts/node_modules/mongodb/lib/core/topologies/replset_state.js @@ -0,0 +1,1121 @@ +'use strict'; + +var inherits = require('util').inherits, + f = require('util').format, + diff = require('./shared').diff, + EventEmitter = require('events').EventEmitter, + Logger = require('../connection/logger'), + ReadPreference = require('./read_preference'), + MongoError = require('../error').MongoError, + Buffer = require('safe-buffer').Buffer; + +var TopologyType = { + Single: 'Single', + ReplicaSetNoPrimary: 'ReplicaSetNoPrimary', + ReplicaSetWithPrimary: 'ReplicaSetWithPrimary', + Sharded: 'Sharded', + Unknown: 'Unknown' +}; + +var ServerType = { + Standalone: 'Standalone', + Mongos: 'Mongos', + PossiblePrimary: 'PossiblePrimary', + RSPrimary: 'RSPrimary', + RSSecondary: 'RSSecondary', + RSArbiter: 'RSArbiter', + RSOther: 'RSOther', + RSGhost: 'RSGhost', + Unknown: 'Unknown' +}; + +var ReplSetState = function(options) { + options = options || {}; + // Add event listener + EventEmitter.call(this); + // Topology state + this.topologyType = TopologyType.ReplicaSetNoPrimary; + this.setName = options.setName; + + // Server set + this.set = {}; + + // Unpacked options + this.id = options.id; + this.setName = options.setName; + + // Replicaset logger + this.logger = options.logger || Logger('ReplSet', options); + + // Server selection index + this.index = 0; + // Acceptable latency + this.acceptableLatency = options.acceptableLatency || 15; + + // heartbeatFrequencyMS + this.heartbeatFrequencyMS = options.heartbeatFrequencyMS || 10000; + + // Server side + this.primary = null; + this.secondaries = []; + this.arbiters = []; + this.passives = []; + this.ghosts = []; + // Current unknown hosts + this.unknownServers = []; + // In set status + this.set = {}; + // Status + this.maxElectionId = null; + this.maxSetVersion = 0; + // Description of the Replicaset + this.replicasetDescription = { + topologyType: 'Unknown', + servers: [] + }; + + this.logicalSessionTimeoutMinutes = undefined; +}; + +inherits(ReplSetState, EventEmitter); + +ReplSetState.prototype.hasPrimaryAndSecondary = function() { + return this.primary != null && this.secondaries.length > 0; +}; + +ReplSetState.prototype.hasPrimaryOrSecondary = function() { + return this.hasPrimary() || this.hasSecondary(); +}; + +ReplSetState.prototype.hasPrimary = function() { + return this.primary != null; +}; + +ReplSetState.prototype.hasSecondary = function() { + return this.secondaries.length > 0; +}; + +ReplSetState.prototype.get = function(host) { + var servers = this.allServers(); + + for (var i = 0; i < servers.length; i++) { + if (servers[i].name.toLowerCase() === host.toLowerCase()) { + return servers[i]; + } + } + + return null; +}; + +ReplSetState.prototype.allServers = function(options) { + options = options || {}; + var servers = this.primary ? [this.primary] : []; + servers = servers.concat(this.secondaries); + if (!options.ignoreArbiters) servers = servers.concat(this.arbiters); + servers = servers.concat(this.passives); + return servers; +}; + +ReplSetState.prototype.destroy = function(options, callback) { + const serversToDestroy = this.secondaries + .concat(this.arbiters) + .concat(this.passives) + .concat(this.ghosts); + if (this.primary) serversToDestroy.push(this.primary); + + let serverCount = serversToDestroy.length; + const serverDestroyed = () => { + serverCount--; + if (serverCount > 0) { + return; + } + + // Clear out the complete state + this.secondaries = []; + this.arbiters = []; + this.passives = []; + this.ghosts = []; + this.unknownServers = []; + this.set = {}; + this.primary = null; + + // Emit the topology changed + emitTopologyDescriptionChanged(this); + + if (typeof callback === 'function') { + callback(null, null); + } + }; + + if (serverCount === 0) { + serverDestroyed(); + return; + } + + serversToDestroy.forEach(server => server.destroy(options, serverDestroyed)); +}; + +ReplSetState.prototype.remove = function(server, options) { + options = options || {}; + + // Get the server name and lowerCase it + var serverName = server.name.toLowerCase(); + + // Only remove if the current server is not connected + var servers = this.primary ? [this.primary] : []; + servers = servers.concat(this.secondaries); + servers = servers.concat(this.arbiters); + servers = servers.concat(this.passives); + + // Check if it's active and this is just a failed connection attempt + for (var i = 0; i < servers.length; i++) { + if ( + !options.force && + servers[i].equals(server) && + servers[i].isConnected && + servers[i].isConnected() + ) { + return; + } + } + + // If we have it in the set remove it + if (this.set[serverName]) { + this.set[serverName].type = ServerType.Unknown; + this.set[serverName].electionId = null; + this.set[serverName].setName = null; + this.set[serverName].setVersion = null; + } + + // Remove type + var removeType = null; + + // Remove from any lists + if (this.primary && this.primary.equals(server)) { + this.primary = null; + this.topologyType = TopologyType.ReplicaSetNoPrimary; + removeType = 'primary'; + } + + // Remove from any other server lists + removeType = removeFrom(server, this.secondaries) ? 'secondary' : removeType; + removeType = removeFrom(server, this.arbiters) ? 'arbiter' : removeType; + removeType = removeFrom(server, this.passives) ? 'secondary' : removeType; + removeFrom(server, this.ghosts); + removeFrom(server, this.unknownServers); + + // Push to unknownServers + this.unknownServers.push(serverName); + + // Do we have a removeType + if (removeType) { + this.emit('left', removeType, server); + } +}; + +const isArbiter = ismaster => ismaster.arbiterOnly && ismaster.setName; + +ReplSetState.prototype.update = function(server) { + var self = this; + // Get the current ismaster + var ismaster = server.lastIsMaster(); + + // Get the server name and lowerCase it + var serverName = server.name.toLowerCase(); + + // + // Add any hosts + // + if (ismaster) { + // Join all the possible new hosts + var hosts = Array.isArray(ismaster.hosts) ? ismaster.hosts : []; + hosts = hosts.concat(Array.isArray(ismaster.arbiters) ? ismaster.arbiters : []); + hosts = hosts.concat(Array.isArray(ismaster.passives) ? ismaster.passives : []); + hosts = hosts.map(function(s) { + return s.toLowerCase(); + }); + + // Add all hosts as unknownServers + for (var i = 0; i < hosts.length; i++) { + // Add to the list of unknown server + if ( + this.unknownServers.indexOf(hosts[i]) === -1 && + (!this.set[hosts[i]] || this.set[hosts[i]].type === ServerType.Unknown) + ) { + this.unknownServers.push(hosts[i].toLowerCase()); + } + + if (!this.set[hosts[i]]) { + this.set[hosts[i]] = { + type: ServerType.Unknown, + electionId: null, + setName: null, + setVersion: null + }; + } + } + } + + // + // Unknown server + // + if (!ismaster && !inList(ismaster, server, this.unknownServers)) { + self.set[serverName] = { + type: ServerType.Unknown, + setVersion: null, + electionId: null, + setName: null + }; + // Update set information about the server instance + self.set[serverName].type = ServerType.Unknown; + self.set[serverName].electionId = ismaster ? ismaster.electionId : ismaster; + self.set[serverName].setName = ismaster ? ismaster.setName : ismaster; + self.set[serverName].setVersion = ismaster ? ismaster.setVersion : ismaster; + + if (self.unknownServers.indexOf(server.name) === -1) { + self.unknownServers.push(serverName); + } + + // Set the topology + return false; + } + + // Update logicalSessionTimeoutMinutes + if (ismaster.logicalSessionTimeoutMinutes !== undefined && !isArbiter(ismaster)) { + if ( + self.logicalSessionTimeoutMinutes === undefined || + ismaster.logicalSessionTimeoutMinutes === null + ) { + self.logicalSessionTimeoutMinutes = ismaster.logicalSessionTimeoutMinutes; + } else { + self.logicalSessionTimeoutMinutes = Math.min( + self.logicalSessionTimeoutMinutes, + ismaster.logicalSessionTimeoutMinutes + ); + } + } + + // + // Is this a mongos + // + if (ismaster && ismaster.msg === 'isdbgrid') { + if (this.primary && this.primary.name === serverName) { + this.primary = null; + this.topologyType = TopologyType.ReplicaSetNoPrimary; + } + + return false; + } + + // A RSGhost instance + if (ismaster.isreplicaset) { + self.set[serverName] = { + type: ServerType.RSGhost, + setVersion: null, + electionId: null, + setName: ismaster.setName + }; + + if (this.primary && this.primary.name === serverName) { + this.primary = null; + } + + // Set the topology + this.topologyType = this.primary + ? TopologyType.ReplicaSetWithPrimary + : TopologyType.ReplicaSetNoPrimary; + if (ismaster.setName) this.setName = ismaster.setName; + + // Set the topology + return false; + } + + // A RSOther instance + if ( + (ismaster.setName && ismaster.hidden) || + (ismaster.setName && + !ismaster.ismaster && + !ismaster.secondary && + !ismaster.arbiterOnly && + !ismaster.passive) + ) { + self.set[serverName] = { + type: ServerType.RSOther, + setVersion: null, + electionId: null, + setName: ismaster.setName + }; + + // Set the topology + this.topologyType = this.primary + ? TopologyType.ReplicaSetWithPrimary + : TopologyType.ReplicaSetNoPrimary; + if (ismaster.setName) this.setName = ismaster.setName; + return false; + } + + // + // Standalone server, destroy and return + // + if (ismaster && ismaster.ismaster && !ismaster.setName) { + this.topologyType = this.primary ? TopologyType.ReplicaSetWithPrimary : TopologyType.Unknown; + this.remove(server, { force: true }); + return false; + } + + // + // Server in maintanance mode + // + if (ismaster && !ismaster.ismaster && !ismaster.secondary && !ismaster.arbiterOnly) { + this.remove(server, { force: true }); + return false; + } + + // + // If the .me field does not match the passed in server + // + if (ismaster.me && ismaster.me.toLowerCase() !== serverName) { + if (this.logger.isWarn()) { + this.logger.warn( + f( + 'the seedlist server was removed due to its address %s not matching its ismaster.me address %s', + server.name, + ismaster.me + ) + ); + } + + // Delete from the set + delete this.set[serverName]; + // Delete unknown servers + removeFrom(server, self.unknownServers); + + // Destroy the instance + server.destroy({ force: true }); + + // Set the type of topology we have + if (this.primary && !this.primary.equals(server)) { + this.topologyType = TopologyType.ReplicaSetWithPrimary; + } else { + this.topologyType = TopologyType.ReplicaSetNoPrimary; + } + + // + // We have a potential primary + // + if (!this.primary && ismaster.primary) { + this.set[ismaster.primary.toLowerCase()] = { + type: ServerType.PossiblePrimary, + setName: null, + electionId: null, + setVersion: null + }; + } + + return false; + } + + // + // Primary handling + // + if (!this.primary && ismaster.ismaster && ismaster.setName) { + var ismasterElectionId = server.lastIsMaster().electionId; + if (this.setName && this.setName !== ismaster.setName) { + this.topologyType = TopologyType.ReplicaSetNoPrimary; + return new MongoError( + f( + 'setName from ismaster does not match provided connection setName [%s] != [%s]', + ismaster.setName, + this.setName + ) + ); + } + + if (!this.maxElectionId && ismasterElectionId) { + this.maxElectionId = ismasterElectionId; + } else if (this.maxElectionId && ismasterElectionId) { + var result = compareObjectIds(this.maxElectionId, ismasterElectionId); + // Get the electionIds + var ismasterSetVersion = server.lastIsMaster().setVersion; + + if (result === 1) { + this.topologyType = TopologyType.ReplicaSetNoPrimary; + return false; + } else if (result === 0 && ismasterSetVersion) { + if (ismasterSetVersion < this.maxSetVersion) { + this.topologyType = TopologyType.ReplicaSetNoPrimary; + return false; + } + } + + this.maxSetVersion = ismasterSetVersion; + this.maxElectionId = ismasterElectionId; + } + + // Hande normalization of server names + var normalizedHosts = ismaster.hosts.map(function(x) { + return x.toLowerCase(); + }); + var locationIndex = normalizedHosts.indexOf(serverName); + + // Validate that the server exists in the host list + if (locationIndex !== -1) { + self.primary = server; + self.set[serverName] = { + type: ServerType.RSPrimary, + setVersion: ismaster.setVersion, + electionId: ismaster.electionId, + setName: ismaster.setName + }; + + // Set the topology + this.topologyType = TopologyType.ReplicaSetWithPrimary; + if (ismaster.setName) this.setName = ismaster.setName; + removeFrom(server, self.unknownServers); + removeFrom(server, self.secondaries); + removeFrom(server, self.passives); + self.emit('joined', 'primary', server); + } else { + this.topologyType = TopologyType.ReplicaSetNoPrimary; + } + + emitTopologyDescriptionChanged(self); + return true; + } else if (ismaster.ismaster && ismaster.setName) { + // Get the electionIds + var currentElectionId = self.set[self.primary.name.toLowerCase()].electionId; + var currentSetVersion = self.set[self.primary.name.toLowerCase()].setVersion; + var currentSetName = self.set[self.primary.name.toLowerCase()].setName; + ismasterElectionId = server.lastIsMaster().electionId; + ismasterSetVersion = server.lastIsMaster().setVersion; + var ismasterSetName = server.lastIsMaster().setName; + + // Is it the same server instance + if (this.primary.equals(server) && currentSetName === ismasterSetName) { + return false; + } + + // If we do not have the same rs name + if (currentSetName && currentSetName !== ismasterSetName) { + if (!this.primary.equals(server)) { + this.topologyType = TopologyType.ReplicaSetWithPrimary; + } else { + this.topologyType = TopologyType.ReplicaSetNoPrimary; + } + + return false; + } + + // Check if we need to replace the server + if (currentElectionId && ismasterElectionId) { + result = compareObjectIds(currentElectionId, ismasterElectionId); + + if (result === 1) { + return false; + } else if (result === 0 && currentSetVersion > ismasterSetVersion) { + return false; + } + } else if (!currentElectionId && ismasterElectionId && ismasterSetVersion) { + if (ismasterSetVersion < this.maxSetVersion) { + return false; + } + } + + if (!this.maxElectionId && ismasterElectionId) { + this.maxElectionId = ismasterElectionId; + } else if (this.maxElectionId && ismasterElectionId) { + result = compareObjectIds(this.maxElectionId, ismasterElectionId); + + if (result === 1) { + return false; + } else if (result === 0 && currentSetVersion && ismasterSetVersion) { + if (ismasterSetVersion < this.maxSetVersion) { + return false; + } + } else { + if (ismasterSetVersion < this.maxSetVersion) { + return false; + } + } + + this.maxElectionId = ismasterElectionId; + this.maxSetVersion = ismasterSetVersion; + } else { + this.maxSetVersion = ismasterSetVersion; + } + + // Modify the entry to unknown + self.set[self.primary.name.toLowerCase()] = { + type: ServerType.Unknown, + setVersion: null, + electionId: null, + setName: null + }; + + // Signal primary left + self.emit('left', 'primary', this.primary); + // Destroy the instance + self.primary.destroy({ force: true }); + // Set the new instance + self.primary = server; + // Set the set information + self.set[serverName] = { + type: ServerType.RSPrimary, + setVersion: ismaster.setVersion, + electionId: ismaster.electionId, + setName: ismaster.setName + }; + + // Set the topology + this.topologyType = TopologyType.ReplicaSetWithPrimary; + if (ismaster.setName) this.setName = ismaster.setName; + removeFrom(server, self.unknownServers); + removeFrom(server, self.secondaries); + removeFrom(server, self.passives); + self.emit('joined', 'primary', server); + emitTopologyDescriptionChanged(self); + return true; + } + + // A possible instance + if (!this.primary && ismaster.primary) { + self.set[ismaster.primary.toLowerCase()] = { + type: ServerType.PossiblePrimary, + setVersion: null, + electionId: null, + setName: null + }; + } + + // + // Secondary handling + // + if ( + ismaster.secondary && + ismaster.setName && + !inList(ismaster, server, this.secondaries) && + this.setName && + this.setName === ismaster.setName + ) { + addToList(self, ServerType.RSSecondary, ismaster, server, this.secondaries); + // Set the topology + this.topologyType = this.primary + ? TopologyType.ReplicaSetWithPrimary + : TopologyType.ReplicaSetNoPrimary; + if (ismaster.setName) this.setName = ismaster.setName; + removeFrom(server, self.unknownServers); + + // Remove primary + if (this.primary && this.primary.name.toLowerCase() === serverName) { + server.destroy({ force: true }); + this.primary = null; + self.emit('left', 'primary', server); + } + + // Emit secondary joined replicaset + self.emit('joined', 'secondary', server); + emitTopologyDescriptionChanged(self); + return true; + } + + // + // Arbiter handling + // + if ( + isArbiter(ismaster) && + !inList(ismaster, server, this.arbiters) && + this.setName && + this.setName === ismaster.setName + ) { + addToList(self, ServerType.RSArbiter, ismaster, server, this.arbiters); + // Set the topology + this.topologyType = this.primary + ? TopologyType.ReplicaSetWithPrimary + : TopologyType.ReplicaSetNoPrimary; + if (ismaster.setName) this.setName = ismaster.setName; + removeFrom(server, self.unknownServers); + self.emit('joined', 'arbiter', server); + emitTopologyDescriptionChanged(self); + return true; + } + + // + // Passive handling + // + if ( + ismaster.passive && + ismaster.setName && + !inList(ismaster, server, this.passives) && + this.setName && + this.setName === ismaster.setName + ) { + addToList(self, ServerType.RSSecondary, ismaster, server, this.passives); + // Set the topology + this.topologyType = this.primary + ? TopologyType.ReplicaSetWithPrimary + : TopologyType.ReplicaSetNoPrimary; + if (ismaster.setName) this.setName = ismaster.setName; + removeFrom(server, self.unknownServers); + + // Remove primary + if (this.primary && this.primary.name.toLowerCase() === serverName) { + server.destroy({ force: true }); + this.primary = null; + self.emit('left', 'primary', server); + } + + self.emit('joined', 'secondary', server); + emitTopologyDescriptionChanged(self); + return true; + } + + // + // Remove the primary + // + if (this.set[serverName] && this.set[serverName].type === ServerType.RSPrimary) { + self.emit('left', 'primary', this.primary); + this.primary.destroy({ force: true }); + this.primary = null; + this.topologyType = TopologyType.ReplicaSetNoPrimary; + return false; + } + + this.topologyType = this.primary + ? TopologyType.ReplicaSetWithPrimary + : TopologyType.ReplicaSetNoPrimary; + return false; +}; + +/** + * Recalculate single server max staleness + * @method + */ +ReplSetState.prototype.updateServerMaxStaleness = function(server, haInterval) { + // Locate the max secondary lastwrite + var max = 0; + // Go over all secondaries + for (var i = 0; i < this.secondaries.length; i++) { + max = Math.max(max, this.secondaries[i].lastWriteDate); + } + + // Perform this servers staleness calculation + if (server.ismaster.maxWireVersion >= 5 && server.ismaster.secondary && this.hasPrimary()) { + server.staleness = + server.lastUpdateTime - + server.lastWriteDate - + (this.primary.lastUpdateTime - this.primary.lastWriteDate) + + haInterval; + } else if (server.ismaster.maxWireVersion >= 5 && server.ismaster.secondary) { + server.staleness = max - server.lastWriteDate + haInterval; + } +}; + +/** + * Recalculate all the staleness values for secodaries + * @method + */ +ReplSetState.prototype.updateSecondariesMaxStaleness = function(haInterval) { + for (var i = 0; i < this.secondaries.length; i++) { + this.updateServerMaxStaleness(this.secondaries[i], haInterval); + } +}; + +/** + * Pick a server by the passed in ReadPreference + * @method + * @param {ReadPreference} readPreference The ReadPreference instance to use + */ +ReplSetState.prototype.pickServer = function(readPreference) { + // If no read Preference set to primary by default + readPreference = readPreference || ReadPreference.primary; + + // maxStalenessSeconds is not allowed with a primary read + if (readPreference.preference === 'primary' && readPreference.maxStalenessSeconds != null) { + return new MongoError('primary readPreference incompatible with maxStalenessSeconds'); + } + + // Check if we have any non compatible servers for maxStalenessSeconds + var allservers = this.primary ? [this.primary] : []; + allservers = allservers.concat(this.secondaries); + + // Does any of the servers not support the right wire protocol version + // for maxStalenessSeconds when maxStalenessSeconds specified on readPreference. Then error out + if (readPreference.maxStalenessSeconds != null) { + for (var i = 0; i < allservers.length; i++) { + if (allservers[i].ismaster.maxWireVersion < 5) { + return new MongoError( + 'maxStalenessSeconds not supported by at least one of the replicaset members' + ); + } + } + } + + // Do we have the nearest readPreference + if (readPreference.preference === 'nearest' && readPreference.maxStalenessSeconds == null) { + return pickNearest(this, readPreference); + } else if ( + readPreference.preference === 'nearest' && + readPreference.maxStalenessSeconds != null + ) { + return pickNearestMaxStalenessSeconds(this, readPreference); + } + + // Get all the secondaries + var secondaries = this.secondaries; + + // Check if we can satisfy and of the basic read Preferences + if (readPreference.equals(ReadPreference.secondary) && secondaries.length === 0) { + return new MongoError('no secondary server available'); + } + + if ( + readPreference.equals(ReadPreference.secondaryPreferred) && + secondaries.length === 0 && + this.primary == null + ) { + return new MongoError('no secondary or primary server available'); + } + + if (readPreference.equals(ReadPreference.primary) && this.primary == null) { + return new MongoError('no primary server available'); + } + + // Secondary preferred or just secondaries + if ( + readPreference.equals(ReadPreference.secondaryPreferred) || + readPreference.equals(ReadPreference.secondary) + ) { + if (secondaries.length > 0 && readPreference.maxStalenessSeconds == null) { + // Pick nearest of any other servers available + var server = pickNearest(this, readPreference); + // No server in the window return primary + if (server) { + return server; + } + } else if (secondaries.length > 0 && readPreference.maxStalenessSeconds != null) { + // Pick nearest of any other servers available + server = pickNearestMaxStalenessSeconds(this, readPreference); + // No server in the window return primary + if (server) { + return server; + } + } + + if (readPreference.equals(ReadPreference.secondaryPreferred)) { + return this.primary; + } + + return null; + } + + // Primary preferred + if (readPreference.equals(ReadPreference.primaryPreferred)) { + server = null; + + // We prefer the primary if it's available + if (this.primary) { + return this.primary; + } + + // Pick a secondary + if (secondaries.length > 0 && readPreference.maxStalenessSeconds == null) { + server = pickNearest(this, readPreference); + } else if (secondaries.length > 0 && readPreference.maxStalenessSeconds != null) { + server = pickNearestMaxStalenessSeconds(this, readPreference); + } + + // Did we find a server + if (server) return server; + } + + // Return the primary + return this.primary; +}; + +// +// Filter serves by tags +var filterByTags = function(readPreference, servers) { + if (readPreference.tags == null) return servers; + var filteredServers = []; + var tagsArray = Array.isArray(readPreference.tags) ? readPreference.tags : [readPreference.tags]; + + // Iterate over the tags + for (var j = 0; j < tagsArray.length; j++) { + var tags = tagsArray[j]; + + // Iterate over all the servers + for (var i = 0; i < servers.length; i++) { + var serverTag = servers[i].lastIsMaster().tags || {}; + + // Did we find the a matching server + var found = true; + // Check if the server is valid + for (var name in tags) { + if (serverTag[name] !== tags[name]) { + found = false; + } + } + + // Add to candidate list + if (found) { + filteredServers.push(servers[i]); + } + } + } + + // Returned filtered servers + return filteredServers; +}; + +function pickNearestMaxStalenessSeconds(self, readPreference) { + // Only get primary and secondaries as seeds + var servers = []; + + // Get the maxStalenessMS + var maxStalenessMS = readPreference.maxStalenessSeconds * 1000; + + // Check if the maxStalenessMS > 90 seconds + if (maxStalenessMS < 90 * 1000) { + return new MongoError('maxStalenessSeconds must be set to at least 90 seconds'); + } + + // Add primary to list if not a secondary read preference + if ( + self.primary && + readPreference.preference !== 'secondary' && + readPreference.preference !== 'secondaryPreferred' + ) { + servers.push(self.primary); + } + + // Add all the secondaries + for (var i = 0; i < self.secondaries.length; i++) { + servers.push(self.secondaries[i]); + } + + // If we have a secondaryPreferred readPreference and no server add the primary + if (self.primary && servers.length === 0 && readPreference.preference !== 'secondaryPreferred') { + servers.push(self.primary); + } + + // Filter by tags + servers = filterByTags(readPreference, servers); + + // Filter by latency + servers = servers.filter(function(s) { + return s.staleness <= maxStalenessMS; + }); + + // Sort by time + servers.sort(function(a, b) { + return a.lastIsMasterMS - b.lastIsMasterMS; + }); + + // No servers, default to primary + if (servers.length === 0) { + return null; + } + + // Ensure index does not overflow the number of available servers + self.index = self.index % servers.length; + + // Get the server + var server = servers[self.index]; + // Add to the index + self.index = self.index + 1; + // Return the first server of the sorted and filtered list + return server; +} + +function pickNearest(self, readPreference) { + // Only get primary and secondaries as seeds + var servers = []; + + // Add primary to list if not a secondary read preference + if ( + self.primary && + readPreference.preference !== 'secondary' && + readPreference.preference !== 'secondaryPreferred' + ) { + servers.push(self.primary); + } + + // Add all the secondaries + for (var i = 0; i < self.secondaries.length; i++) { + servers.push(self.secondaries[i]); + } + + // If we have a secondaryPreferred readPreference and no server add the primary + if (servers.length === 0 && self.primary && readPreference.preference !== 'secondaryPreferred') { + servers.push(self.primary); + } + + // Filter by tags + servers = filterByTags(readPreference, servers); + + // Sort by time + servers.sort(function(a, b) { + return a.lastIsMasterMS - b.lastIsMasterMS; + }); + + // Locate lowest time (picked servers are lowest time + acceptable Latency margin) + var lowest = servers.length > 0 ? servers[0].lastIsMasterMS : 0; + + // Filter by latency + servers = servers.filter(function(s) { + return s.lastIsMasterMS <= lowest + self.acceptableLatency; + }); + + // No servers, default to primary + if (servers.length === 0) { + return null; + } + + // Ensure index does not overflow the number of available servers + self.index = self.index % servers.length; + // Get the server + var server = servers[self.index]; + // Add to the index + self.index = self.index + 1; + // Return the first server of the sorted and filtered list + return server; +} + +function inList(ismaster, server, list) { + for (var i = 0; i < list.length; i++) { + if (list[i] && list[i].name && list[i].name.toLowerCase() === server.name.toLowerCase()) + return true; + } + + return false; +} + +function addToList(self, type, ismaster, server, list) { + var serverName = server.name.toLowerCase(); + // Update set information about the server instance + self.set[serverName].type = type; + self.set[serverName].electionId = ismaster ? ismaster.electionId : ismaster; + self.set[serverName].setName = ismaster ? ismaster.setName : ismaster; + self.set[serverName].setVersion = ismaster ? ismaster.setVersion : ismaster; + // Add to the list + list.push(server); +} + +function compareObjectIds(id1, id2) { + var a = Buffer.from(id1.toHexString(), 'hex'); + var b = Buffer.from(id2.toHexString(), 'hex'); + + if (a === b) { + return 0; + } + + if (typeof Buffer.compare === 'function') { + return Buffer.compare(a, b); + } + + var x = a.length; + var y = b.length; + var len = Math.min(x, y); + + for (var i = 0; i < len; i++) { + if (a[i] !== b[i]) { + break; + } + } + + if (i !== len) { + x = a[i]; + y = b[i]; + } + + return x < y ? -1 : y < x ? 1 : 0; +} + +function removeFrom(server, list) { + for (var i = 0; i < list.length; i++) { + if (list[i].equals && list[i].equals(server)) { + list.splice(i, 1); + return true; + } else if (typeof list[i] === 'string' && list[i].toLowerCase() === server.name.toLowerCase()) { + list.splice(i, 1); + return true; + } + } + + return false; +} + +function emitTopologyDescriptionChanged(self) { + if (self.listeners('topologyDescriptionChanged').length > 0) { + var topology = 'Unknown'; + var setName = self.setName; + + if (self.hasPrimaryAndSecondary()) { + topology = 'ReplicaSetWithPrimary'; + } else if (!self.hasPrimary() && self.hasSecondary()) { + topology = 'ReplicaSetNoPrimary'; + } + + // Generate description + var description = { + topologyType: topology, + setName: setName, + servers: [] + }; + + // Add the primary to the list + if (self.hasPrimary()) { + var desc = self.primary.getDescription(); + desc.type = 'RSPrimary'; + description.servers.push(desc); + } + + // Add all the secondaries + description.servers = description.servers.concat( + self.secondaries.map(function(x) { + var description = x.getDescription(); + description.type = 'RSSecondary'; + return description; + }) + ); + + // Add all the arbiters + description.servers = description.servers.concat( + self.arbiters.map(function(x) { + var description = x.getDescription(); + description.type = 'RSArbiter'; + return description; + }) + ); + + // Add all the passives + description.servers = description.servers.concat( + self.passives.map(function(x) { + var description = x.getDescription(); + description.type = 'RSSecondary'; + return description; + }) + ); + + // Get the diff + var diffResult = diff(self.replicasetDescription, description); + + // Create the result + var result = { + topologyId: self.id, + previousDescription: self.replicasetDescription, + newDescription: description, + diff: diffResult + }; + + // Emit the topologyDescription change + // if(diffResult.servers.length > 0) { + self.emit('topologyDescriptionChanged', result); + // } + + // Set the new description + self.replicasetDescription = description; + } +} + +module.exports = ReplSetState; diff --git a/scripts/node_modules/mongodb/lib/core/topologies/server.js b/scripts/node_modules/mongodb/lib/core/topologies/server.js new file mode 100644 index 00000000..c2f86421 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/core/topologies/server.js @@ -0,0 +1,989 @@ +'use strict'; + +var inherits = require('util').inherits, + f = require('util').format, + EventEmitter = require('events').EventEmitter, + ReadPreference = require('./read_preference'), + Logger = require('../connection/logger'), + debugOptions = require('../connection/utils').debugOptions, + retrieveBSON = require('../connection/utils').retrieveBSON, + Pool = require('../connection/pool'), + MongoError = require('../error').MongoError, + MongoNetworkError = require('../error').MongoNetworkError, + wireProtocol = require('../wireprotocol'), + CoreCursor = require('../cursor').CoreCursor, + sdam = require('./shared'), + createClientInfo = require('./shared').createClientInfo, + createCompressionInfo = require('./shared').createCompressionInfo, + resolveClusterTime = require('./shared').resolveClusterTime, + SessionMixins = require('./shared').SessionMixins, + relayEvents = require('../utils').relayEvents; + +const collationNotSupported = require('../utils').collationNotSupported; + +// Used for filtering out fields for loggin +var debugFields = [ + 'reconnect', + 'reconnectTries', + 'reconnectInterval', + 'emitError', + 'cursorFactory', + 'host', + 'port', + 'size', + 'keepAlive', + 'keepAliveInitialDelay', + 'noDelay', + 'connectionTimeout', + 'checkServerIdentity', + 'socketTimeout', + 'ssl', + 'ca', + 'crl', + 'cert', + 'key', + 'rejectUnauthorized', + 'promoteLongs', + 'promoteValues', + 'promoteBuffers', + 'servername' +]; + +// Server instance id +var id = 0; +var serverAccounting = false; +var servers = {}; +var BSON = retrieveBSON(); + +/** + * Creates a new Server instance + * @class + * @param {boolean} [options.reconnect=true] Server will attempt to reconnect on loss of connection + * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times + * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries + * @param {number} [options.monitoring=true] Enable the server state monitoring (calling ismaster at monitoringInterval) + * @param {number} [options.monitoringInterval=5000] The interval of calling ismaster when monitoring is enabled. + * @param {Cursor} [options.cursorFactory=Cursor] The cursor factory class used for all query cursors + * @param {string} options.host The server host + * @param {number} options.port The server port + * @param {number} [options.size=5] Server connection pool size + * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled + * @param {number} [options.keepAliveInitialDelay=300000] Initial delay before TCP keep alive enabled + * @param {boolean} [options.noDelay=true] TCP Connection no delay + * @param {number} [options.connectionTimeout=30000] TCP Connection timeout setting + * @param {number} [options.socketTimeout=360000] TCP Socket timeout setting + * @param {boolean} [options.ssl=false] Use SSL for connection + * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. + * @param {Buffer} [options.ca] SSL Certificate store binary buffer + * @param {Buffer} [options.crl] SSL Certificate revocation store binary buffer + * @param {Buffer} [options.cert] SSL Certificate binary buffer + * @param {Buffer} [options.key] SSL Key file binary buffer + * @param {string} [options.passphrase] SSL Certificate pass phrase + * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates + * @param {string} [options.servername=null] String containing the server name requested via TLS SNI. + * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits + * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. + * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. + * @param {string} [options.appname=null] Application name, passed in on ismaster call and logged in mongod server logs. Maximum size 128 bytes. + * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. + * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology + * @return {Server} A cursor instance + * @fires Server#connect + * @fires Server#close + * @fires Server#error + * @fires Server#timeout + * @fires Server#parseError + * @fires Server#reconnect + * @fires Server#reconnectFailed + * @fires Server#serverHeartbeatStarted + * @fires Server#serverHeartbeatSucceeded + * @fires Server#serverHeartbeatFailed + * @fires Server#topologyOpening + * @fires Server#topologyClosed + * @fires Server#topologyDescriptionChanged + * @property {string} type the topology type. + * @property {string} parserType the parser type used (c++ or js). + */ +var Server = function(options) { + options = options || {}; + + // Add event listener + EventEmitter.call(this); + + // Server instance id + this.id = id++; + + // Internal state + this.s = { + // Options + options: options, + // Logger + logger: Logger('Server', options), + // Factory overrides + Cursor: options.cursorFactory || CoreCursor, + // BSON instance + bson: + options.bson || + new BSON([ + BSON.Binary, + BSON.Code, + BSON.DBRef, + BSON.Decimal128, + BSON.Double, + BSON.Int32, + BSON.Long, + BSON.Map, + BSON.MaxKey, + BSON.MinKey, + BSON.ObjectId, + BSON.BSONRegExp, + BSON.Symbol, + BSON.Timestamp + ]), + // Pool + pool: null, + // Disconnect handler + disconnectHandler: options.disconnectHandler, + // Monitor thread (keeps the connection alive) + monitoring: typeof options.monitoring === 'boolean' ? options.monitoring : true, + // Is the server in a topology + inTopology: !!options.parent, + // Monitoring timeout + monitoringInterval: + typeof options.monitoringInterval === 'number' ? options.monitoringInterval : 5000, + // Topology id + topologyId: -1, + compression: { compressors: createCompressionInfo(options) }, + // Optional parent topology + parent: options.parent + }; + + // If this is a single deployment we need to track the clusterTime here + if (!this.s.parent) { + this.s.clusterTime = null; + } + + // Curent ismaster + this.ismaster = null; + // Current ping time + this.lastIsMasterMS = -1; + // The monitoringProcessId + this.monitoringProcessId = null; + // Initial connection + this.initialConnect = true; + // Default type + this._type = 'server'; + // Set the client info + this.clientInfo = createClientInfo(options); + + // Max Stalleness values + // last time we updated the ismaster state + this.lastUpdateTime = 0; + // Last write time + this.lastWriteDate = 0; + // Stalleness + this.staleness = 0; +}; + +inherits(Server, EventEmitter); +Object.assign(Server.prototype, SessionMixins); + +Object.defineProperty(Server.prototype, 'type', { + enumerable: true, + get: function() { + return this._type; + } +}); + +Object.defineProperty(Server.prototype, 'parserType', { + enumerable: true, + get: function() { + return BSON.native ? 'c++' : 'js'; + } +}); + +Object.defineProperty(Server.prototype, 'logicalSessionTimeoutMinutes', { + enumerable: true, + get: function() { + if (!this.ismaster) return null; + return this.ismaster.logicalSessionTimeoutMinutes || null; + } +}); + +// In single server deployments we track the clusterTime directly on the topology, however +// in Mongos and ReplSet deployments we instead need to delegate the clusterTime up to the +// tracking objects so we can ensure we are gossiping the maximum time received from the +// server. +Object.defineProperty(Server.prototype, 'clusterTime', { + enumerable: true, + set: function(clusterTime) { + const settings = this.s.parent ? this.s.parent : this.s; + resolveClusterTime(settings, clusterTime); + }, + get: function() { + const settings = this.s.parent ? this.s.parent : this.s; + return settings.clusterTime || null; + } +}); + +Server.enableServerAccounting = function() { + serverAccounting = true; + servers = {}; +}; + +Server.disableServerAccounting = function() { + serverAccounting = false; +}; + +Server.servers = function() { + return servers; +}; + +Object.defineProperty(Server.prototype, 'name', { + enumerable: true, + get: function() { + return this.s.options.host + ':' + this.s.options.port; + } +}); + +function disconnectHandler(self, type, ns, cmd, options, callback) { + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if ( + !self.s.pool.isConnected() && + self.s.options.reconnect && + self.s.disconnectHandler != null && + !options.monitoring + ) { + self.s.disconnectHandler.add(type, ns, cmd, options, callback); + return true; + } + + // If we have no connection error + if (!self.s.pool.isConnected()) { + callback(new MongoError(f('no connection available to server %s', self.name))); + return true; + } +} + +function monitoringProcess(self) { + return function() { + // Pool was destroyed do not continue process + if (self.s.pool.isDestroyed()) return; + // Emit monitoring Process event + self.emit('monitoring', self); + // Perform ismaster call + // Get start time + var start = new Date().getTime(); + + // Execute the ismaster query + self.command( + 'admin.$cmd', + { ismaster: true }, + { + socketTimeout: + typeof self.s.options.connectionTimeout !== 'number' + ? 2000 + : self.s.options.connectionTimeout, + monitoring: true + }, + (err, result) => { + // Set initial lastIsMasterMS + self.lastIsMasterMS = new Date().getTime() - start; + if (self.s.pool.isDestroyed()) return; + // Update the ismaster view if we have a result + if (result) { + self.ismaster = result.result; + } + // Re-schedule the monitoring process + self.monitoringProcessId = setTimeout(monitoringProcess(self), self.s.monitoringInterval); + } + ); + }; +} + +var eventHandler = function(self, event) { + return function(err, conn) { + // Log information of received information if in info mode + if (self.s.logger.isInfo()) { + var object = err instanceof MongoError ? JSON.stringify(err) : {}; + self.s.logger.info( + f('server %s fired event %s out with message %s', self.name, event, object) + ); + } + + // Handle connect event + if (event === 'connect') { + self.initialConnect = false; + self.ismaster = conn.ismaster; + self.lastIsMasterMS = conn.lastIsMasterMS; + if (conn.agreedCompressor) { + self.s.pool.options.agreedCompressor = conn.agreedCompressor; + } + + if (conn.zlibCompressionLevel) { + self.s.pool.options.zlibCompressionLevel = conn.zlibCompressionLevel; + } + + if (conn.ismaster.$clusterTime) { + const $clusterTime = conn.ismaster.$clusterTime; + self.clusterTime = $clusterTime; + } + + // It's a proxy change the type so + // the wireprotocol will send $readPreference + if (self.ismaster.msg === 'isdbgrid') { + self._type = 'mongos'; + } + + // Have we defined self monitoring + if (self.s.monitoring) { + self.monitoringProcessId = setTimeout(monitoringProcess(self), self.s.monitoringInterval); + } + + // Emit server description changed if something listening + sdam.emitServerDescriptionChanged(self, { + address: self.name, + arbiters: [], + hosts: [], + passives: [], + type: sdam.getTopologyType(self) + }); + + if (!self.s.inTopology) { + // Emit topology description changed if something listening + sdam.emitTopologyDescriptionChanged(self, { + topologyType: 'Single', + servers: [ + { + address: self.name, + arbiters: [], + hosts: [], + passives: [], + type: sdam.getTopologyType(self) + } + ] + }); + } + + // Log the ismaster if available + if (self.s.logger.isInfo()) { + self.s.logger.info( + f('server %s connected with ismaster [%s]', self.name, JSON.stringify(self.ismaster)) + ); + } + + // Emit connect + self.emit('connect', self); + } else if ( + event === 'error' || + event === 'parseError' || + event === 'close' || + event === 'timeout' || + event === 'reconnect' || + event === 'attemptReconnect' || + 'reconnectFailed' + ) { + // Remove server instance from accounting + if ( + serverAccounting && + ['close', 'timeout', 'error', 'parseError', 'reconnectFailed'].indexOf(event) !== -1 + ) { + // Emit toplogy opening event if not in topology + if (!self.s.inTopology) { + self.emit('topologyOpening', { topologyId: self.id }); + } + + delete servers[self.id]; + } + + if (event === 'close') { + // Closing emits a server description changed event going to unknown. + sdam.emitServerDescriptionChanged(self, { + address: self.name, + arbiters: [], + hosts: [], + passives: [], + type: 'Unknown' + }); + } + + // Reconnect failed return error + if (event === 'reconnectFailed') { + self.emit('reconnectFailed', err); + // Emit error if any listeners + if (self.listeners('error').length > 0) { + self.emit('error', err); + } + // Terminate + return; + } + + // On first connect fail + if ( + ['disconnected', 'connecting'].indexOf(self.s.pool.state) !== -1 && + self.initialConnect && + ['close', 'timeout', 'error', 'parseError'].indexOf(event) !== -1 + ) { + self.initialConnect = false; + return self.emit( + 'error', + new MongoNetworkError( + f('failed to connect to server [%s] on first connect [%s]', self.name, err) + ) + ); + } + + // Reconnect event, emit the server + if (event === 'reconnect') { + // Reconnecting emits a server description changed event going from unknown to the + // current server type. + sdam.emitServerDescriptionChanged(self, { + address: self.name, + arbiters: [], + hosts: [], + passives: [], + type: sdam.getTopologyType(self) + }); + return self.emit(event, self); + } + + // Emit the event + self.emit(event, err); + } + }; +}; + +/** + * Initiate server connect + */ +Server.prototype.connect = function(options) { + var self = this; + options = options || {}; + + // Set the connections + if (serverAccounting) servers[this.id] = this; + + // Do not allow connect to be called on anything that's not disconnected + if (self.s.pool && !self.s.pool.isDisconnected() && !self.s.pool.isDestroyed()) { + throw new MongoError(f('server instance in invalid state %s', self.s.pool.state)); + } + + // Create a pool + self.s.pool = new Pool(this, Object.assign(self.s.options, options, { bson: this.s.bson })); + + // Set up listeners + self.s.pool.on('close', eventHandler(self, 'close')); + self.s.pool.on('error', eventHandler(self, 'error')); + self.s.pool.on('timeout', eventHandler(self, 'timeout')); + self.s.pool.on('parseError', eventHandler(self, 'parseError')); + self.s.pool.on('connect', eventHandler(self, 'connect')); + self.s.pool.on('reconnect', eventHandler(self, 'reconnect')); + self.s.pool.on('reconnectFailed', eventHandler(self, 'reconnectFailed')); + + // Set up listeners for command monitoring + relayEvents(self.s.pool, self, ['commandStarted', 'commandSucceeded', 'commandFailed']); + + // Emit toplogy opening event if not in topology + if (!self.s.inTopology) { + this.emit('topologyOpening', { topologyId: self.id }); + } + + // Emit opening server event + self.emit('serverOpening', { + topologyId: self.s.topologyId !== -1 ? self.s.topologyId : self.id, + address: self.name + }); + + self.s.pool.connect(); +}; + +/** + * Authenticate the topology. + * @method + * @param {MongoCredentials} credentials The credentials for authentication we are using + * @param {authResultCallback} callback A callback function + */ +Server.prototype.auth = function(credentials, callback) { + if (typeof callback === 'function') callback(null, null); +}; + +/** + * Get the server description + * @method + * @return {object} + */ +Server.prototype.getDescription = function() { + var ismaster = this.ismaster || {}; + var description = { + type: sdam.getTopologyType(this), + address: this.name + }; + + // Add fields if available + if (ismaster.hosts) description.hosts = ismaster.hosts; + if (ismaster.arbiters) description.arbiters = ismaster.arbiters; + if (ismaster.passives) description.passives = ismaster.passives; + if (ismaster.setName) description.setName = ismaster.setName; + return description; +}; + +/** + * Returns the last known ismaster document for this server + * @method + * @return {object} + */ +Server.prototype.lastIsMaster = function() { + return this.ismaster; +}; + +/** + * Unref all connections belong to this server + * @method + */ +Server.prototype.unref = function() { + this.s.pool.unref(); +}; + +/** + * Figure out if the server is connected + * @method + * @return {boolean} + */ +Server.prototype.isConnected = function() { + if (!this.s.pool) return false; + return this.s.pool.isConnected(); +}; + +/** + * Figure out if the server instance was destroyed by calling destroy + * @method + * @return {boolean} + */ +Server.prototype.isDestroyed = function() { + if (!this.s.pool) return false; + return this.s.pool.isDestroyed(); +}; + +function basicWriteValidations(self) { + if (!self.s.pool) return new MongoError('server instance is not connected'); + if (self.s.pool.isDestroyed()) return new MongoError('server instance pool was destroyed'); +} + +function basicReadValidations(self, options) { + basicWriteValidations(self, options); + + if (options.readPreference && !(options.readPreference instanceof ReadPreference)) { + throw new Error('readPreference must be an instance of ReadPreference'); + } +} + +/** + * Execute a command + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object} cmd The command hash + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.checkKeys=false] Specify if the bson parser should validate keys. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {Boolean} [options.fullResult=false] Return the full envelope instead of just the result document. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {opResultCallback} callback A callback function + */ +Server.prototype.command = function(ns, cmd, options, callback) { + var self = this; + if (typeof options === 'function') { + (callback = options), (options = {}), (options = options || {}); + } + + var result = basicReadValidations(self, options); + if (result) return callback(result); + + // Clone the options + options = Object.assign({}, options, { wireProtocolCommand: false }); + + // Debug log + if (self.s.logger.isDebug()) + self.s.logger.debug( + f( + 'executing command [%s] against %s', + JSON.stringify({ + ns: ns, + cmd: cmd, + options: debugOptions(debugFields, options) + }), + self.name + ) + ); + + // If we are not connected or have a disconnectHandler specified + if (disconnectHandler(self, 'command', ns, cmd, options, callback)) return; + + // error if collation not supported + if (collationNotSupported(this, cmd)) { + return callback(new MongoError(`server ${this.name} does not support collation`)); + } + + wireProtocol.command(self, ns, cmd, options, callback); +}; + +/** + * Execute a query against the server + * + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object} cmd The command document for the query + * @param {object} options Optional settings + * @param {function} callback + */ +Server.prototype.query = function(ns, cmd, cursorState, options, callback) { + wireProtocol.query(this, ns, cmd, cursorState, options, callback); +}; + +/** + * Execute a `getMore` against the server + * + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object} cursorState State data associated with the cursor calling this method + * @param {object} options Optional settings + * @param {function} callback + */ +Server.prototype.getMore = function(ns, cursorState, batchSize, options, callback) { + wireProtocol.getMore(this, ns, cursorState, batchSize, options, callback); +}; + +/** + * Execute a `killCursors` command against the server + * + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object} cursorState State data associated with the cursor calling this method + * @param {function} callback + */ +Server.prototype.killCursors = function(ns, cursorState, callback) { + wireProtocol.killCursors(this, ns, cursorState, callback); +}; + +/** + * Insert one or more documents + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of documents to insert + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {opResultCallback} callback A callback function + */ +Server.prototype.insert = function(ns, ops, options, callback) { + var self = this; + if (typeof options === 'function') { + (callback = options), (options = {}), (options = options || {}); + } + + var result = basicWriteValidations(self, options); + if (result) return callback(result); + + // If we are not connected or have a disconnectHandler specified + if (disconnectHandler(self, 'insert', ns, ops, options, callback)) return; + + // Setup the docs as an array + ops = Array.isArray(ops) ? ops : [ops]; + + // Execute write + return wireProtocol.insert(self, ns, ops, options, callback); +}; + +/** + * Perform one or more update operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of updates + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {opResultCallback} callback A callback function + */ +Server.prototype.update = function(ns, ops, options, callback) { + var self = this; + if (typeof options === 'function') { + (callback = options), (options = {}), (options = options || {}); + } + + var result = basicWriteValidations(self, options); + if (result) return callback(result); + + // If we are not connected or have a disconnectHandler specified + if (disconnectHandler(self, 'update', ns, ops, options, callback)) return; + + // error if collation not supported + if (collationNotSupported(this, options)) { + return callback(new MongoError(`server ${this.name} does not support collation`)); + } + + // Setup the docs as an array + ops = Array.isArray(ops) ? ops : [ops]; + // Execute write + return wireProtocol.update(self, ns, ops, options, callback); +}; + +/** + * Perform one or more remove operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of removes + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {opResultCallback} callback A callback function + */ +Server.prototype.remove = function(ns, ops, options, callback) { + var self = this; + if (typeof options === 'function') { + (callback = options), (options = {}), (options = options || {}); + } + + var result = basicWriteValidations(self, options); + if (result) return callback(result); + + // If we are not connected or have a disconnectHandler specified + if (disconnectHandler(self, 'remove', ns, ops, options, callback)) return; + + // error if collation not supported + if (collationNotSupported(this, options)) { + return callback(new MongoError(`server ${this.name} does not support collation`)); + } + + // Setup the docs as an array + ops = Array.isArray(ops) ? ops : [ops]; + // Execute write + return wireProtocol.remove(self, ns, ops, options, callback); +}; + +/** + * Get a new cursor + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object|Long} cmd Can be either a command returning a cursor or a cursorId + * @param {object} [options] Options for the cursor + * @param {object} [options.batchSize=0] Batchsize for the operation + * @param {array} [options.documents=[]] Initial documents list for cursor + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {ClientSession} [options.session=null] Session to use for the operation + * @param {object} [options.topology] The internal topology of the created cursor + * @returns {Cursor} + */ +Server.prototype.cursor = function(ns, cmd, options) { + options = options || {}; + const topology = options.topology || this; + + // Set up final cursor type + var FinalCursor = options.cursorFactory || this.s.Cursor; + + // Return the cursor + return new FinalCursor(topology, ns, cmd, options); +}; + +/** + * Compare two server instances + * @method + * @param {Server} server Server to compare equality against + * @return {boolean} + */ +Server.prototype.equals = function(server) { + if (typeof server === 'string') return this.name.toLowerCase() === server.toLowerCase(); + if (server.name) return this.name.toLowerCase() === server.name.toLowerCase(); + return false; +}; + +/** + * All raw connections + * @method + * @return {Connection[]} + */ +Server.prototype.connections = function() { + return this.s.pool.allConnections(); +}; + +/** + * Selects a server + * @method + * @param {function} selector Unused + * @param {ReadPreference} [options.readPreference] Unused + * @param {ClientSession} [options.session] Unused + * @return {Server} + */ +Server.prototype.selectServer = function(selector, options, callback) { + if (typeof selector === 'function' && typeof callback === 'undefined') + (callback = selector), (selector = undefined), (options = {}); + if (typeof options === 'function') + (callback = options), (options = selector), (selector = undefined); + + callback(null, this); +}; + +var listeners = ['close', 'error', 'timeout', 'parseError', 'connect']; + +/** + * Destroy the server connection + * @method + * @param {boolean} [options.emitClose=false] Emit close event on destroy + * @param {boolean} [options.emitDestroy=false] Emit destroy event on destroy + * @param {boolean} [options.force=false] Force destroy the pool + */ +Server.prototype.destroy = function(options, callback) { + if (this._destroyed) { + if (typeof callback === 'function') callback(null, null); + return; + } + + if (typeof options === 'function') { + callback = options; + options = {}; + } + + options = options || {}; + var self = this; + + // Set the connections + if (serverAccounting) delete servers[this.id]; + + // Destroy the monitoring process if any + if (this.monitoringProcessId) { + clearTimeout(this.monitoringProcessId); + } + + // No pool, return + if (!self.s.pool) { + this._destroyed = true; + if (typeof callback === 'function') callback(null, null); + return; + } + + // Emit close event + if (options.emitClose) { + self.emit('close', self); + } + + // Emit destroy event + if (options.emitDestroy) { + self.emit('destroy', self); + } + + // Remove all listeners + listeners.forEach(function(event) { + self.s.pool.removeAllListeners(event); + }); + + // Emit opening server event + if (self.listeners('serverClosed').length > 0) + self.emit('serverClosed', { + topologyId: self.s.topologyId !== -1 ? self.s.topologyId : self.id, + address: self.name + }); + + // Emit toplogy opening event if not in topology + if (self.listeners('topologyClosed').length > 0 && !self.s.inTopology) { + self.emit('topologyClosed', { topologyId: self.id }); + } + + if (self.s.logger.isDebug()) { + self.s.logger.debug(f('destroy called on server %s', self.name)); + } + + // Destroy the pool + this.s.pool.destroy(options.force, callback); + this._destroyed = true; +}; + +/** + * A server connect event, used to verify that the connection is up and running + * + * @event Server#connect + * @type {Server} + */ + +/** + * A server reconnect event, used to verify that the server topology has reconnected + * + * @event Server#reconnect + * @type {Server} + */ + +/** + * A server opening SDAM monitoring event + * + * @event Server#serverOpening + * @type {object} + */ + +/** + * A server closed SDAM monitoring event + * + * @event Server#serverClosed + * @type {object} + */ + +/** + * A server description SDAM change monitoring event + * + * @event Server#serverDescriptionChanged + * @type {object} + */ + +/** + * A topology open SDAM event + * + * @event Server#topologyOpening + * @type {object} + */ + +/** + * A topology closed SDAM event + * + * @event Server#topologyClosed + * @type {object} + */ + +/** + * A topology structure SDAM change event + * + * @event Server#topologyDescriptionChanged + * @type {object} + */ + +/** + * Server reconnect failed + * + * @event Server#reconnectFailed + * @type {Error} + */ + +/** + * Server connection pool closed + * + * @event Server#close + * @type {object} + */ + +/** + * Server connection pool caused an error + * + * @event Server#error + * @type {Error} + */ + +/** + * Server destroyed was called + * + * @event Server#destroy + * @type {Server} + */ + +module.exports = Server; diff --git a/scripts/node_modules/mongodb/lib/core/topologies/shared.js b/scripts/node_modules/mongodb/lib/core/topologies/shared.js new file mode 100644 index 00000000..8e227bad --- /dev/null +++ b/scripts/node_modules/mongodb/lib/core/topologies/shared.js @@ -0,0 +1,476 @@ +'use strict'; + +const os = require('os'); +const f = require('util').format; +const ReadPreference = require('./read_preference'); +const Buffer = require('safe-buffer').Buffer; +const TopologyType = require('../sdam/topology_description').TopologyType; +const MongoError = require('../error').MongoError; + +const MMAPv1_RETRY_WRITES_ERROR_CODE = 20; + +/** + * Emit event if it exists + * @method + */ +function emitSDAMEvent(self, event, description) { + if (self.listeners(event).length > 0) { + self.emit(event, description); + } +} + +// Get package.json variable +var driverVersion = require('../../../package.json').version; +var nodejsversion = f('Node.js %s, %s', process.version, os.endianness()); +var type = os.type(); +var name = process.platform; +var architecture = process.arch; +var release = os.release(); + +function createClientInfo(options) { + // Build default client information + var clientInfo = options.clientInfo + ? clone(options.clientInfo) + : { + driver: { + name: 'nodejs-core', + version: driverVersion + }, + os: { + type: type, + name: name, + architecture: architecture, + version: release + } + }; + + // Is platform specified + if (clientInfo.platform && clientInfo.platform.indexOf('mongodb-core') === -1) { + clientInfo.platform = f('%s, mongodb-core: %s', clientInfo.platform, driverVersion); + } else if (!clientInfo.platform) { + clientInfo.platform = nodejsversion; + } + + // Do we have an application specific string + if (options.appname) { + // Cut at 128 bytes + var buffer = Buffer.from(options.appname); + // Return the truncated appname + var appname = buffer.length > 128 ? buffer.slice(0, 128).toString('utf8') : options.appname; + // Add to the clientInfo + clientInfo.application = { name: appname }; + } + + return clientInfo; +} + +function createCompressionInfo(options) { + if (!options.compression || !options.compression.compressors) { + return []; + } + + // Check that all supplied compressors are valid + options.compression.compressors.forEach(function(compressor) { + if (compressor !== 'snappy' && compressor !== 'zlib') { + throw new Error('compressors must be at least one of snappy or zlib'); + } + }); + + return options.compression.compressors; +} + +function clone(object) { + return JSON.parse(JSON.stringify(object)); +} + +var getPreviousDescription = function(self) { + if (!self.s.serverDescription) { + self.s.serverDescription = { + address: self.name, + arbiters: [], + hosts: [], + passives: [], + type: 'Unknown' + }; + } + + return self.s.serverDescription; +}; + +var emitServerDescriptionChanged = function(self, description) { + if (self.listeners('serverDescriptionChanged').length > 0) { + // Emit the server description changed events + self.emit('serverDescriptionChanged', { + topologyId: self.s.topologyId !== -1 ? self.s.topologyId : self.id, + address: self.name, + previousDescription: getPreviousDescription(self), + newDescription: description + }); + + self.s.serverDescription = description; + } +}; + +var getPreviousTopologyDescription = function(self) { + if (!self.s.topologyDescription) { + self.s.topologyDescription = { + topologyType: 'Unknown', + servers: [ + { + address: self.name, + arbiters: [], + hosts: [], + passives: [], + type: 'Unknown' + } + ] + }; + } + + return self.s.topologyDescription; +}; + +var emitTopologyDescriptionChanged = function(self, description) { + if (self.listeners('topologyDescriptionChanged').length > 0) { + // Emit the server description changed events + self.emit('topologyDescriptionChanged', { + topologyId: self.s.topologyId !== -1 ? self.s.topologyId : self.id, + address: self.name, + previousDescription: getPreviousTopologyDescription(self), + newDescription: description + }); + + self.s.serverDescription = description; + } +}; + +var changedIsMaster = function(self, currentIsmaster, ismaster) { + var currentType = getTopologyType(self, currentIsmaster); + var newType = getTopologyType(self, ismaster); + if (newType !== currentType) return true; + return false; +}; + +var getTopologyType = function(self, ismaster) { + if (!ismaster) { + ismaster = self.ismaster; + } + + if (!ismaster) return 'Unknown'; + if (ismaster.ismaster && ismaster.msg === 'isdbgrid') return 'Mongos'; + if (ismaster.ismaster && !ismaster.hosts) return 'Standalone'; + if (ismaster.ismaster) return 'RSPrimary'; + if (ismaster.secondary) return 'RSSecondary'; + if (ismaster.arbiterOnly) return 'RSArbiter'; + return 'Unknown'; +}; + +var inquireServerState = function(self) { + return function(callback) { + if (self.s.state === 'destroyed') return; + // Record response time + var start = new Date().getTime(); + + // emitSDAMEvent + emitSDAMEvent(self, 'serverHeartbeatStarted', { connectionId: self.name }); + + // Attempt to execute ismaster command + self.command('admin.$cmd', { ismaster: true }, { monitoring: true }, function(err, r) { + if (!err) { + // Legacy event sender + self.emit('ismaster', r, self); + + // Calculate latencyMS + var latencyMS = new Date().getTime() - start; + + // Server heart beat event + emitSDAMEvent(self, 'serverHeartbeatSucceeded', { + durationMS: latencyMS, + reply: r.result, + connectionId: self.name + }); + + // Did the server change + if (changedIsMaster(self, self.s.ismaster, r.result)) { + // Emit server description changed if something listening + emitServerDescriptionChanged(self, { + address: self.name, + arbiters: [], + hosts: [], + passives: [], + type: !self.s.inTopology ? 'Standalone' : getTopologyType(self) + }); + } + + // Updat ismaster view + self.s.ismaster = r.result; + + // Set server response time + self.s.isMasterLatencyMS = latencyMS; + } else { + emitSDAMEvent(self, 'serverHeartbeatFailed', { + durationMS: latencyMS, + failure: err, + connectionId: self.name + }); + } + + // Peforming an ismaster monitoring callback operation + if (typeof callback === 'function') { + return callback(err, r); + } + + // Perform another sweep + self.s.inquireServerStateTimeout = setTimeout(inquireServerState(self), self.s.haInterval); + }); + }; +}; + +// +// Clone the options +var cloneOptions = function(options) { + var opts = {}; + for (var name in options) { + opts[name] = options[name]; + } + return opts; +}; + +function Interval(fn, time) { + var timer = false; + + this.start = function() { + if (!this.isRunning()) { + timer = setInterval(fn, time); + } + + return this; + }; + + this.stop = function() { + clearInterval(timer); + timer = false; + return this; + }; + + this.isRunning = function() { + return timer !== false; + }; +} + +function Timeout(fn, time) { + var timer = false; + + this.start = function() { + if (!this.isRunning()) { + timer = setTimeout(fn, time); + } + return this; + }; + + this.stop = function() { + clearTimeout(timer); + timer = false; + return this; + }; + + this.isRunning = function() { + if (timer && timer._called) return false; + return timer !== false; + }; +} + +function diff(previous, current) { + // Difference document + var diff = { + servers: [] + }; + + // Previous entry + if (!previous) { + previous = { servers: [] }; + } + + // Check if we have any previous servers missing in the current ones + for (var i = 0; i < previous.servers.length; i++) { + var found = false; + + for (var j = 0; j < current.servers.length; j++) { + if (current.servers[j].address.toLowerCase() === previous.servers[i].address.toLowerCase()) { + found = true; + break; + } + } + + if (!found) { + // Add to the diff + diff.servers.push({ + address: previous.servers[i].address, + from: previous.servers[i].type, + to: 'Unknown' + }); + } + } + + // Check if there are any severs that don't exist + for (j = 0; j < current.servers.length; j++) { + found = false; + + // Go over all the previous servers + for (i = 0; i < previous.servers.length; i++) { + if (previous.servers[i].address.toLowerCase() === current.servers[j].address.toLowerCase()) { + found = true; + break; + } + } + + // Add the server to the diff + if (!found) { + diff.servers.push({ + address: current.servers[j].address, + from: 'Unknown', + to: current.servers[j].type + }); + } + } + + // Got through all the servers + for (i = 0; i < previous.servers.length; i++) { + var prevServer = previous.servers[i]; + + // Go through all current servers + for (j = 0; j < current.servers.length; j++) { + var currServer = current.servers[j]; + + // Matching server + if (prevServer.address.toLowerCase() === currServer.address.toLowerCase()) { + // We had a change in state + if (prevServer.type !== currServer.type) { + diff.servers.push({ + address: prevServer.address, + from: prevServer.type, + to: currServer.type + }); + } + } + } + } + + // Return difference + return diff; +} + +/** + * Shared function to determine clusterTime for a given topology + * + * @param {*} topology + * @param {*} clusterTime + */ +function resolveClusterTime(topology, $clusterTime) { + if (topology.clusterTime == null) { + topology.clusterTime = $clusterTime; + } else { + if ($clusterTime.clusterTime.greaterThan(topology.clusterTime.clusterTime)) { + topology.clusterTime = $clusterTime; + } + } +} + +// NOTE: this is a temporary move until the topologies can be more formally refactored +// to share code. +const SessionMixins = { + endSessions: function(sessions, callback) { + if (!Array.isArray(sessions)) { + sessions = [sessions]; + } + + // TODO: + // When connected to a sharded cluster the endSessions command + // can be sent to any mongos. When connected to a replica set the + // endSessions command MUST be sent to the primary if the primary + // is available, otherwise it MUST be sent to any available secondary. + // Is it enough to use: ReadPreference.primaryPreferred ? + this.command( + 'admin.$cmd', + { endSessions: sessions }, + { readPreference: ReadPreference.primaryPreferred }, + () => { + // intentionally ignored, per spec + if (typeof callback === 'function') callback(); + } + ); + } +}; + +function topologyType(topology) { + if (topology.description) { + return topology.description.type; + } + + if (topology.type === 'mongos') { + return TopologyType.Sharded; + } else if (topology.type === 'replset') { + return TopologyType.ReplicaSetWithPrimary; + } + + return TopologyType.Single; +} + +const RETRYABLE_WIRE_VERSION = 6; + +/** + * Determines whether the provided topology supports retryable writes + * + * @param {Mongos|Replset} topology + */ +const isRetryableWritesSupported = function(topology) { + const maxWireVersion = topology.lastIsMaster().maxWireVersion; + if (maxWireVersion < RETRYABLE_WIRE_VERSION) { + return false; + } + + if (!topology.logicalSessionTimeoutMinutes) { + return false; + } + + if (topologyType(topology) === TopologyType.Single) { + return false; + } + + return true; +}; + +const MMAPv1_RETRY_WRITES_ERROR_MESSAGE = + 'This MongoDB deployment does not support retryable writes. Please add retryWrites=false to your connection string.'; + +function getMMAPError(err) { + if (err.code !== MMAPv1_RETRY_WRITES_ERROR_CODE || !err.errmsg.includes('Transaction numbers')) { + return err; + } + + // According to the retryable writes spec, we must replace the error message in this case. + // We need to replace err.message so the thrown message is correct and we need to replace err.errmsg to meet the spec requirement. + const newErr = new MongoError({ + message: MMAPv1_RETRY_WRITES_ERROR_MESSAGE, + errmsg: MMAPv1_RETRY_WRITES_ERROR_MESSAGE, + originalError: err + }); + return newErr; +} + +module.exports.SessionMixins = SessionMixins; +module.exports.resolveClusterTime = resolveClusterTime; +module.exports.inquireServerState = inquireServerState; +module.exports.getTopologyType = getTopologyType; +module.exports.emitServerDescriptionChanged = emitServerDescriptionChanged; +module.exports.emitTopologyDescriptionChanged = emitTopologyDescriptionChanged; +module.exports.cloneOptions = cloneOptions; +module.exports.createClientInfo = createClientInfo; +module.exports.createCompressionInfo = createCompressionInfo; +module.exports.clone = clone; +module.exports.diff = diff; +module.exports.Interval = Interval; +module.exports.Timeout = Timeout; +module.exports.isRetryableWritesSupported = isRetryableWritesSupported; +module.exports.getMMAPError = getMMAPError; +module.exports.topologyType = topologyType; diff --git a/scripts/node_modules/mongodb/lib/core/transactions.js b/scripts/node_modules/mongodb/lib/core/transactions.js new file mode 100644 index 00000000..891a8734 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/core/transactions.js @@ -0,0 +1,168 @@ +'use strict'; +const MongoError = require('./error').MongoError; + +let TxnState; +let stateMachine; + +(() => { + const NO_TRANSACTION = 'NO_TRANSACTION'; + const STARTING_TRANSACTION = 'STARTING_TRANSACTION'; + const TRANSACTION_IN_PROGRESS = 'TRANSACTION_IN_PROGRESS'; + const TRANSACTION_COMMITTED = 'TRANSACTION_COMMITTED'; + const TRANSACTION_COMMITTED_EMPTY = 'TRANSACTION_COMMITTED_EMPTY'; + const TRANSACTION_ABORTED = 'TRANSACTION_ABORTED'; + + TxnState = { + NO_TRANSACTION, + STARTING_TRANSACTION, + TRANSACTION_IN_PROGRESS, + TRANSACTION_COMMITTED, + TRANSACTION_COMMITTED_EMPTY, + TRANSACTION_ABORTED + }; + + stateMachine = { + [NO_TRANSACTION]: [NO_TRANSACTION, STARTING_TRANSACTION], + [STARTING_TRANSACTION]: [ + TRANSACTION_IN_PROGRESS, + TRANSACTION_COMMITTED, + TRANSACTION_COMMITTED_EMPTY, + TRANSACTION_ABORTED + ], + [TRANSACTION_IN_PROGRESS]: [ + TRANSACTION_IN_PROGRESS, + TRANSACTION_COMMITTED, + TRANSACTION_ABORTED + ], + [TRANSACTION_COMMITTED]: [ + TRANSACTION_COMMITTED, + TRANSACTION_COMMITTED_EMPTY, + STARTING_TRANSACTION, + NO_TRANSACTION + ], + [TRANSACTION_ABORTED]: [STARTING_TRANSACTION, NO_TRANSACTION], + [TRANSACTION_COMMITTED_EMPTY]: [TRANSACTION_COMMITTED_EMPTY, NO_TRANSACTION] + }; +})(); + +/** + * The MongoDB ReadConcern, which allows for control of the consistency and isolation properties + * of the data read from replica sets and replica set shards. + * @typedef {Object} ReadConcern + * @property {'local'|'available'|'majority'|'linearizable'|'snapshot'} level The readConcern Level + * @see https://docs.mongodb.com/manual/reference/read-concern/ + */ + +/** + * A MongoDB WriteConcern, which describes the level of acknowledgement + * requested from MongoDB for write operations. + * @typedef {Object} WriteConcern + * @property {number|'majority'|string} [w=1] requests acknowledgement that the write operation has + * propagated to a specified number of mongod hosts + * @property {boolean} [j=false] requests acknowledgement from MongoDB that the write operation has + * been written to the journal + * @property {number} [wtimeout] a time limit, in milliseconds, for the write concern + * @see https://docs.mongodb.com/manual/reference/write-concern/ + */ + +/** + * Configuration options for a transaction. + * @typedef {Object} TransactionOptions + * @property {ReadConcern} [readConcern] A default read concern for commands in this transaction + * @property {WriteConcern} [writeConcern] A default writeConcern for commands in this transaction + * @property {ReadPreference} [readPreference] A default read preference for commands in this transaction + */ + +/** + * A class maintaining state related to a server transaction. Internal Only + * @ignore + */ +class Transaction { + /** + * Create a transaction + * + * @ignore + * @param {TransactionOptions} [options] Optional settings + */ + constructor(options) { + options = options || {}; + + this.state = TxnState.NO_TRANSACTION; + this.options = {}; + + if (options.writeConcern || typeof options.w !== 'undefined') { + const w = options.writeConcern ? options.writeConcern.w : options.w; + if (w <= 0) { + throw new MongoError('Transactions do not support unacknowledged write concern'); + } + + this.options.writeConcern = options.writeConcern ? options.writeConcern : { w: options.w }; + } + + if (options.readConcern) this.options.readConcern = options.readConcern; + if (options.readPreference) this.options.readPreference = options.readPreference; + if (options.maxCommitTimeMS) this.options.maxTimeMS = options.maxCommitTimeMS; + + // TODO: This isn't technically necessary + this._pinnedServer = undefined; + this._recoveryToken = undefined; + } + + get server() { + return this._pinnedServer; + } + + get recoveryToken() { + return this._recoveryToken; + } + + get isPinned() { + return !!this.server; + } + + /** + * @ignore + * @return Whether this session is presently in a transaction + */ + get isActive() { + return ( + [TxnState.STARTING_TRANSACTION, TxnState.TRANSACTION_IN_PROGRESS].indexOf(this.state) !== -1 + ); + } + + /** + * Transition the transaction in the state machine + * @ignore + * @param {TxnState} state The new state to transition to + */ + transition(nextState) { + const nextStates = stateMachine[this.state]; + if (nextStates && nextStates.indexOf(nextState) !== -1) { + this.state = nextState; + if (this.state === TxnState.NO_TRANSACTION || this.state === TxnState.STARTING_TRANSACTION) { + this.unpinServer(); + } + return; + } + + throw new MongoError( + `Attempted illegal state transition from [${this.state}] to [${nextState}]` + ); + } + + pinServer(server) { + if (this.isActive) { + this._pinnedServer = server; + } + } + + unpinServer() { + this._pinnedServer = undefined; + } +} + +function isTransactionCommand(command) { + return !!(command.commitTransaction || command.abortTransaction); +} + +module.exports = { TxnState, Transaction, isTransactionCommand }; diff --git a/scripts/node_modules/mongodb/lib/core/uri_parser.js b/scripts/node_modules/mongodb/lib/core/uri_parser.js new file mode 100644 index 00000000..1530d88d --- /dev/null +++ b/scripts/node_modules/mongodb/lib/core/uri_parser.js @@ -0,0 +1,637 @@ +'use strict'; +const URL = require('url'); +const qs = require('querystring'); +const dns = require('dns'); +const MongoParseError = require('./error').MongoParseError; +const ReadPreference = require('./topologies/read_preference'); + +/** + * The following regular expression validates a connection string and breaks the + * provide string into the following capture groups: [protocol, username, password, hosts] + */ +const HOSTS_RX = /(mongodb(?:\+srv|)):\/\/(?: (?:[^:]*) (?: : ([^@]*) )? @ )?([^/?]*)(?:\/|)(.*)/; + +/** + * Determines whether a provided address matches the provided parent domain in order + * to avoid certain attack vectors. + * + * @param {String} srvAddress The address to check against a domain + * @param {String} parentDomain The domain to check the provided address against + * @return {Boolean} Whether the provided address matches the parent domain + */ +function matchesParentDomain(srvAddress, parentDomain) { + const regex = /^.*?\./; + const srv = `.${srvAddress.replace(regex, '')}`; + const parent = `.${parentDomain.replace(regex, '')}`; + return srv.endsWith(parent); +} + +/** + * Lookup a `mongodb+srv` connection string, combine the parts and reparse it as a normal + * connection string. + * + * @param {string} uri The connection string to parse + * @param {object} options Optional user provided connection string options + * @param {function} callback + */ +function parseSrvConnectionString(uri, options, callback) { + const result = URL.parse(uri, true); + + if (result.hostname.split('.').length < 3) { + return callback(new MongoParseError('URI does not have hostname, domain name and tld')); + } + + result.domainLength = result.hostname.split('.').length; + if (result.pathname && result.pathname.match(',')) { + return callback(new MongoParseError('Invalid URI, cannot contain multiple hostnames')); + } + + if (result.port) { + return callback(new MongoParseError(`Ports not accepted with '${PROTOCOL_MONGODB_SRV}' URIs`)); + } + + // Resolve the SRV record and use the result as the list of hosts to connect to. + const lookupAddress = result.host; + dns.resolveSrv(`_mongodb._tcp.${lookupAddress}`, (err, addresses) => { + if (err) return callback(err); + + if (addresses.length === 0) { + return callback(new MongoParseError('No addresses found at host')); + } + + for (let i = 0; i < addresses.length; i++) { + if (!matchesParentDomain(addresses[i].name, result.hostname, result.domainLength)) { + return callback( + new MongoParseError('Server record does not share hostname with parent URI') + ); + } + } + + // Convert the original URL to a non-SRV URL. + result.protocol = 'mongodb'; + result.host = addresses.map(address => `${address.name}:${address.port}`).join(','); + + // Default to SSL true if it's not specified. + if ( + !('ssl' in options) && + (!result.search || !('ssl' in result.query) || result.query.ssl === null) + ) { + result.query.ssl = true; + } + + // Resolve TXT record and add options from there if they exist. + dns.resolveTxt(lookupAddress, (err, record) => { + if (err) { + if (err.code !== 'ENODATA') { + return callback(err); + } + record = null; + } + + if (record) { + if (record.length > 1) { + return callback(new MongoParseError('Multiple text records not allowed')); + } + + record = qs.parse(record[0].join('')); + if (Object.keys(record).some(key => key !== 'authSource' && key !== 'replicaSet')) { + return callback( + new MongoParseError('Text record must only set `authSource` or `replicaSet`') + ); + } + + Object.assign(result.query, record); + } + + // Set completed options back into the URL object. + result.search = qs.stringify(result.query); + + const finalString = URL.format(result); + parseConnectionString(finalString, options, (err, ret) => { + if (err) { + callback(err); + return; + } + + callback(null, Object.assign({}, ret, { srvHost: lookupAddress })); + }); + }); + }); +} + +/** + * Parses a query string item according to the connection string spec + * + * @param {string} key The key for the parsed value + * @param {Array|String} value The value to parse + * @return {Array|Object|String} The parsed value + */ +function parseQueryStringItemValue(key, value) { + if (Array.isArray(value)) { + // deduplicate and simplify arrays + value = value.filter((v, idx) => value.indexOf(v) === idx); + if (value.length === 1) value = value[0]; + } else if (value.indexOf(':') > 0) { + value = value.split(',').reduce((result, pair) => { + const parts = pair.split(':'); + result[parts[0]] = parseQueryStringItemValue(key, parts[1]); + return result; + }, {}); + } else if (value.indexOf(',') > 0) { + value = value.split(',').map(v => { + return parseQueryStringItemValue(key, v); + }); + } else if (value.toLowerCase() === 'true' || value.toLowerCase() === 'false') { + value = value.toLowerCase() === 'true'; + } else if (!Number.isNaN(value) && !STRING_OPTIONS.has(key)) { + const numericValue = parseFloat(value); + if (!Number.isNaN(numericValue)) { + value = parseFloat(value); + } + } + + return value; +} + +// Options that are known boolean types +const BOOLEAN_OPTIONS = new Set([ + 'slaveok', + 'slave_ok', + 'sslvalidate', + 'fsync', + 'safe', + 'retrywrites', + 'j' +]); + +// Known string options, only used to bypass Number coercion in `parseQueryStringItemValue` +const STRING_OPTIONS = new Set(['authsource', 'replicaset']); + +// Supported text representations of auth mechanisms +// NOTE: this list exists in native already, if it is merged here we should deduplicate +const AUTH_MECHANISMS = new Set([ + 'GSSAPI', + 'MONGODB-X509', + 'MONGODB-CR', + 'DEFAULT', + 'SCRAM-SHA-1', + 'SCRAM-SHA-256', + 'PLAIN' +]); + +// Lookup table used to translate normalized (lower-cased) forms of connection string +// options to their expected camelCase version +const CASE_TRANSLATION = { + replicaset: 'replicaSet', + connecttimeoutms: 'connectTimeoutMS', + sockettimeoutms: 'socketTimeoutMS', + maxpoolsize: 'maxPoolSize', + minpoolsize: 'minPoolSize', + maxidletimems: 'maxIdleTimeMS', + waitqueuemultiple: 'waitQueueMultiple', + waitqueuetimeoutms: 'waitQueueTimeoutMS', + wtimeoutms: 'wtimeoutMS', + readconcern: 'readConcern', + readconcernlevel: 'readConcernLevel', + readpreference: 'readPreference', + maxstalenessseconds: 'maxStalenessSeconds', + readpreferencetags: 'readPreferenceTags', + authsource: 'authSource', + authmechanism: 'authMechanism', + authmechanismproperties: 'authMechanismProperties', + gssapiservicename: 'gssapiServiceName', + localthresholdms: 'localThresholdMS', + serverselectiontimeoutms: 'serverSelectionTimeoutMS', + serverselectiontryonce: 'serverSelectionTryOnce', + heartbeatfrequencyms: 'heartbeatFrequencyMS', + retrywrites: 'retryWrites', + uuidrepresentation: 'uuidRepresentation', + zlibcompressionlevel: 'zlibCompressionLevel', + tlsallowinvalidcertificates: 'tlsAllowInvalidCertificates', + tlsallowinvalidhostnames: 'tlsAllowInvalidHostnames', + tlsinsecure: 'tlsInsecure', + tlscafile: 'tlsCAFile', + tlscertificatekeyfile: 'tlsCertificateKeyFile', + tlscertificatekeyfilepassword: 'tlsCertificateKeyFilePassword', + wtimeout: 'wTimeoutMS', + j: 'journal' +}; + +/** + * Sets the value for `key`, allowing for any required translation + * + * @param {object} obj The object to set the key on + * @param {string} key The key to set the value for + * @param {*} value The value to set + * @param {object} options The options used for option parsing + */ +function applyConnectionStringOption(obj, key, value, options) { + // simple key translation + if (key === 'journal') { + key = 'j'; + } else if (key === 'wtimeoutms') { + key = 'wtimeout'; + } + + // more complicated translation + if (BOOLEAN_OPTIONS.has(key)) { + value = value === 'true' || value === true; + } else if (key === 'appname') { + value = decodeURIComponent(value); + } else if (key === 'readconcernlevel') { + obj['readConcernLevel'] = value; + key = 'readconcern'; + value = { level: value }; + } + + // simple validation + if (key === 'compressors') { + value = Array.isArray(value) ? value : [value]; + + if (!value.every(c => c === 'snappy' || c === 'zlib')) { + throw new MongoParseError( + 'Value for `compressors` must be at least one of: `snappy`, `zlib`' + ); + } + } + + if (key === 'authmechanism' && !AUTH_MECHANISMS.has(value)) { + throw new MongoParseError( + 'Value for `authMechanism` must be one of: `DEFAULT`, `GSSAPI`, `PLAIN`, `MONGODB-X509`, `SCRAM-SHA-1`, `SCRAM-SHA-256`' + ); + } + + if (key === 'readpreference' && !ReadPreference.isValid(value)) { + throw new MongoParseError( + 'Value for `readPreference` must be one of: `primary`, `primaryPreferred`, `secondary`, `secondaryPreferred`, `nearest`' + ); + } + + if (key === 'zlibcompressionlevel' && (value < -1 || value > 9)) { + throw new MongoParseError('zlibCompressionLevel must be an integer between -1 and 9'); + } + + // special cases + if (key === 'compressors' || key === 'zlibcompressionlevel') { + obj.compression = obj.compression || {}; + obj = obj.compression; + } + + if (key === 'authmechanismproperties') { + if (typeof value.SERVICE_NAME === 'string') obj.gssapiServiceName = value.SERVICE_NAME; + if (typeof value.SERVICE_REALM === 'string') obj.gssapiServiceRealm = value.SERVICE_REALM; + if (typeof value.CANONICALIZE_HOST_NAME !== 'undefined') { + obj.gssapiCanonicalizeHostName = value.CANONICALIZE_HOST_NAME; + } + } + + if (key === 'readpreferencetags' && Array.isArray(value)) { + value = splitArrayOfMultipleReadPreferenceTags(value); + } + + // set the actual value + if (options.caseTranslate && CASE_TRANSLATION[key]) { + obj[CASE_TRANSLATION[key]] = value; + return; + } + + obj[key] = value; +} + +const USERNAME_REQUIRED_MECHANISMS = new Set([ + 'GSSAPI', + 'MONGODB-CR', + 'PLAIN', + 'SCRAM-SHA-1', + 'SCRAM-SHA-256' +]); + +function splitArrayOfMultipleReadPreferenceTags(value) { + const parsedTags = []; + + for (let i = 0; i < value.length; i++) { + parsedTags[i] = {}; + value[i].split(',').forEach(individualTag => { + const splitTag = individualTag.split(':'); + parsedTags[i][splitTag[0]] = splitTag[1]; + }); + } + + return parsedTags; +} + +/** + * Modifies the parsed connection string object taking into account expectations we + * have for authentication-related options. + * + * @param {object} parsed The parsed connection string result + * @return The parsed connection string result possibly modified for auth expectations + */ +function applyAuthExpectations(parsed) { + if (parsed.options == null) { + return; + } + + const options = parsed.options; + const authSource = options.authsource || options.authSource; + if (authSource != null) { + parsed.auth = Object.assign({}, parsed.auth, { db: authSource }); + } + + const authMechanism = options.authmechanism || options.authMechanism; + if (authMechanism != null) { + if ( + USERNAME_REQUIRED_MECHANISMS.has(authMechanism) && + (!parsed.auth || parsed.auth.username == null) + ) { + throw new MongoParseError(`Username required for mechanism \`${authMechanism}\``); + } + + if (authMechanism === 'GSSAPI') { + if (authSource != null && authSource !== '$external') { + throw new MongoParseError( + `Invalid source \`${authSource}\` for mechanism \`${authMechanism}\` specified.` + ); + } + + parsed.auth = Object.assign({}, parsed.auth, { db: '$external' }); + } + + if (authMechanism === 'MONGODB-X509') { + if (parsed.auth && parsed.auth.password != null) { + throw new MongoParseError(`Password not allowed for mechanism \`${authMechanism}\``); + } + + if (authSource != null && authSource !== '$external') { + throw new MongoParseError( + `Invalid source \`${authSource}\` for mechanism \`${authMechanism}\` specified.` + ); + } + + parsed.auth = Object.assign({}, parsed.auth, { db: '$external' }); + } + + if (authMechanism === 'PLAIN') { + if (parsed.auth && parsed.auth.db == null) { + parsed.auth = Object.assign({}, parsed.auth, { db: '$external' }); + } + } + } + + // default to `admin` if nothing else was resolved + if (parsed.auth && parsed.auth.db == null) { + parsed.auth = Object.assign({}, parsed.auth, { db: 'admin' }); + } + + return parsed; +} + +/** + * Parses a query string according the connection string spec. + * + * @param {String} query The query string to parse + * @param {object} [options] The options used for options parsing + * @return {Object|Error} The parsed query string as an object, or an error if one was encountered + */ +function parseQueryString(query, options) { + const result = {}; + let parsedQueryString = qs.parse(query); + + checkTLSOptions(parsedQueryString); + + for (const key in parsedQueryString) { + const value = parsedQueryString[key]; + if (value === '' || value == null) { + throw new MongoParseError('Incomplete key value pair for option'); + } + + const normalizedKey = key.toLowerCase(); + const parsedValue = parseQueryStringItemValue(normalizedKey, value); + applyConnectionStringOption(result, normalizedKey, parsedValue, options); + } + + // special cases for known deprecated options + if (result.wtimeout && result.wtimeoutms) { + delete result.wtimeout; + console.warn('Unsupported option `wtimeout` specified'); + } + + return Object.keys(result).length ? result : null; +} + +/** + * Checks a query string for invalid tls options according to the URI options spec. + * + * @param {string} queryString The query string to check + * @throws {MongoParseError} + */ +function checkTLSOptions(queryString) { + const queryStringKeys = Object.keys(queryString); + if ( + queryStringKeys.indexOf('tlsInsecure') !== -1 && + (queryStringKeys.indexOf('tlsAllowInvalidCertificates') !== -1 || + queryStringKeys.indexOf('tlsAllowInvalidHostnames') !== -1) + ) { + throw new MongoParseError( + 'The `tlsInsecure` option cannot be used with `tlsAllowInvalidCertificates` or `tlsAllowInvalidHostnames`.' + ); + } + + const tlsValue = assertTlsOptionsAreEqual('tls', queryString, queryStringKeys); + const sslValue = assertTlsOptionsAreEqual('ssl', queryString, queryStringKeys); + + if (tlsValue != null && sslValue != null) { + if (tlsValue !== sslValue) { + throw new MongoParseError('All values of `tls` and `ssl` must be the same.'); + } + } +} + +/** + * Checks a query string to ensure all tls/ssl options are the same. + * + * @param {string} key The key (tls or ssl) to check + * @param {string} queryString The query string to check + * @throws {MongoParseError} + * @return The value of the tls/ssl option + */ +function assertTlsOptionsAreEqual(optionName, queryString, queryStringKeys) { + const queryStringHasTLSOption = queryStringKeys.indexOf(optionName) !== -1; + + let optionValue; + if (Array.isArray(queryString[optionName])) { + optionValue = queryString[optionName][0]; + } else { + optionValue = queryString[optionName]; + } + + if (queryStringHasTLSOption) { + if (Array.isArray(queryString[optionName])) { + const firstValue = queryString[optionName][0]; + queryString[optionName].forEach(tlsValue => { + if (tlsValue !== firstValue) { + throw new MongoParseError('All values of ${optionName} must be the same.'); + } + }); + } + } + + return optionValue; +} + +const PROTOCOL_MONGODB = 'mongodb'; +const PROTOCOL_MONGODB_SRV = 'mongodb+srv'; +const SUPPORTED_PROTOCOLS = [PROTOCOL_MONGODB, PROTOCOL_MONGODB_SRV]; + +/** + * Parses a MongoDB connection string + * + * @param {*} uri the MongoDB connection string to parse + * @param {object} [options] Optional settings. + * @param {boolean} [options.caseTranslate] Whether the parser should translate options back into camelCase after normalization + * @param {parseCallback} callback + */ +function parseConnectionString(uri, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = Object.assign({}, { caseTranslate: true }, options); + + // Check for bad uris before we parse + try { + URL.parse(uri); + } catch (e) { + return callback(new MongoParseError('URI malformed, cannot be parsed')); + } + + const cap = uri.match(HOSTS_RX); + if (!cap) { + return callback(new MongoParseError('Invalid connection string')); + } + + const protocol = cap[1]; + if (SUPPORTED_PROTOCOLS.indexOf(protocol) === -1) { + return callback(new MongoParseError('Invalid protocol provided')); + } + + if (protocol === PROTOCOL_MONGODB_SRV) { + return parseSrvConnectionString(uri, options, callback); + } + + const dbAndQuery = cap[4].split('?'); + const db = dbAndQuery.length > 0 ? dbAndQuery[0] : null; + const query = dbAndQuery.length > 1 ? dbAndQuery[1] : null; + + let parsedOptions; + try { + parsedOptions = parseQueryString(query, options); + } catch (parseError) { + return callback(parseError); + } + + parsedOptions = Object.assign({}, parsedOptions, options); + const auth = { username: null, password: null, db: db && db !== '' ? qs.unescape(db) : null }; + if (parsedOptions.auth) { + // maintain support for legacy options passed into `MongoClient` + if (parsedOptions.auth.username) auth.username = parsedOptions.auth.username; + if (parsedOptions.auth.user) auth.username = parsedOptions.auth.user; + if (parsedOptions.auth.password) auth.password = parsedOptions.auth.password; + } else { + if (parsedOptions.username) auth.username = parsedOptions.username; + if (parsedOptions.user) auth.username = parsedOptions.user; + if (parsedOptions.password) auth.password = parsedOptions.password; + } + + if (cap[4].split('?')[0].indexOf('@') !== -1) { + return callback(new MongoParseError('Unescaped slash in userinfo section')); + } + + const authorityParts = cap[3].split('@'); + if (authorityParts.length > 2) { + return callback(new MongoParseError('Unescaped at-sign in authority section')); + } + + if (authorityParts.length > 1) { + const authParts = authorityParts.shift().split(':'); + if (authParts.length > 2) { + return callback(new MongoParseError('Unescaped colon in authority section')); + } + + if (!auth.username) auth.username = qs.unescape(authParts[0]); + if (!auth.password) auth.password = authParts[1] ? qs.unescape(authParts[1]) : null; + } + + let hostParsingError = null; + const hosts = authorityParts + .shift() + .split(',') + .map(host => { + let parsedHost = URL.parse(`mongodb://${host}`); + if (parsedHost.path === '/:') { + hostParsingError = new MongoParseError('Double colon in host identifier'); + return null; + } + + // heuristically determine if we're working with a domain socket + if (host.match(/\.sock/)) { + parsedHost.hostname = qs.unescape(host); + parsedHost.port = null; + } + + if (Number.isNaN(parsedHost.port)) { + hostParsingError = new MongoParseError('Invalid port (non-numeric string)'); + return; + } + + const result = { + host: parsedHost.hostname, + port: parsedHost.port ? parseInt(parsedHost.port) : 27017 + }; + + if (result.port === 0) { + hostParsingError = new MongoParseError('Invalid port (zero) with hostname'); + return; + } + + if (result.port > 65535) { + hostParsingError = new MongoParseError('Invalid port (larger than 65535) with hostname'); + return; + } + + if (result.port < 0) { + hostParsingError = new MongoParseError('Invalid port (negative number)'); + return; + } + + return result; + }) + .filter(host => !!host); + + if (hostParsingError) { + return callback(hostParsingError); + } + + if (hosts.length === 0 || hosts[0].host === '' || hosts[0].host === null) { + return callback(new MongoParseError('No hostname or hostnames provided in connection string')); + } + + const result = { + hosts: hosts, + auth: auth.db || auth.username ? auth : null, + options: Object.keys(parsedOptions).length ? parsedOptions : null + }; + + if (result.auth && result.auth.db) { + result.defaultDatabase = result.auth.db; + } else { + result.defaultDatabase = 'test'; + } + + try { + applyAuthExpectations(result); + } catch (authError) { + return callback(authError); + } + + callback(null, result); +} + +module.exports = parseConnectionString; diff --git a/scripts/node_modules/mongodb/lib/core/utils.js b/scripts/node_modules/mongodb/lib/core/utils.js new file mode 100644 index 00000000..7581bf25 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/core/utils.js @@ -0,0 +1,177 @@ +'use strict'; + +const crypto = require('crypto'); +const requireOptional = require('require_optional'); + +/** + * Generate a UUIDv4 + */ +const uuidV4 = () => { + const result = crypto.randomBytes(16); + result[6] = (result[6] & 0x0f) | 0x40; + result[8] = (result[8] & 0x3f) | 0x80; + return result; +}; + +/** + * Returns the duration calculated from two high resolution timers in milliseconds + * + * @param {Object} started A high resolution timestamp created from `process.hrtime()` + * @returns {Number} The duration in milliseconds + */ +const calculateDurationInMs = started => { + const hrtime = process.hrtime(started); + return (hrtime[0] * 1e9 + hrtime[1]) / 1e6; +}; + +/** + * Relays events for a given listener and emitter + * + * @param {EventEmitter} listener the EventEmitter to listen to the events from + * @param {EventEmitter} emitter the EventEmitter to relay the events to + */ +function relayEvents(listener, emitter, events) { + events.forEach(eventName => listener.on(eventName, event => emitter.emit(eventName, event))); +} + +function retrieveKerberos() { + let kerberos; + + try { + kerberos = requireOptional('kerberos'); + } catch (err) { + if (err.code === 'MODULE_NOT_FOUND') { + throw new Error('The `kerberos` module was not found. Please install it and try again.'); + } + + throw err; + } + + return kerberos; +} + +// Throw an error if an attempt to use EJSON is made when it is not installed +const noEJSONError = function() { + throw new Error('The `mongodb-extjson` module was not found. Please install it and try again.'); +}; + +// Facilitate loading EJSON optionally +function retrieveEJSON() { + let EJSON = null; + try { + EJSON = requireOptional('mongodb-extjson'); + } catch (error) {} // eslint-disable-line + if (!EJSON) { + EJSON = { + parse: noEJSONError, + deserialize: noEJSONError, + serialize: noEJSONError, + stringify: noEJSONError, + setBSONModule: noEJSONError, + BSON: noEJSONError + }; + } + + return EJSON; +} + +/** + * A helper function for determining `maxWireVersion` between legacy and new topology + * instances + * + * @private + * @param {(Topology|Server)} topologyOrServer + */ +function maxWireVersion(topologyOrServer) { + if (topologyOrServer.ismaster) { + return topologyOrServer.ismaster.maxWireVersion; + } + + if (typeof topologyOrServer.lastIsMaster === 'function') { + const lastIsMaster = topologyOrServer.lastIsMaster(); + if (lastIsMaster) { + return lastIsMaster.maxWireVersion; + } + } + + if (topologyOrServer.description) { + return topologyOrServer.description.maxWireVersion; + } + + return null; +} + +/* + * Checks that collation is supported by server. + * + * @param {Server} [server] to check against + * @param {object} [cmd] object where collation may be specified + * @param {function} [callback] callback function + * @return true if server does not support collation + */ +function collationNotSupported(server, cmd) { + return cmd && cmd.collation && maxWireVersion(server) < 5; +} + +/** + * Checks if a given value is a Promise + * + * @param {*} maybePromise + * @return true if the provided value is a Promise + */ +function isPromiseLike(maybePromise) { + return maybePromise && typeof maybePromise.then === 'function'; +} + +/** + * Applies the function `eachFn` to each item in `arr`, in parallel. + * + * @param {array} arr an array of items to asynchronusly iterate over + * @param {function} eachFn A function to call on each item of the array. The callback signature is `(item, callback)`, where the callback indicates iteration is complete. + * @param {function} callback The callback called after every item has been iterated + */ +function eachAsync(arr, eachFn, callback) { + if (arr.length === 0) { + callback(null); + return; + } + + const length = arr.length; + let completed = 0; + function eachCallback(err) { + if (err) { + callback(err, null); + return; + } + + if (++completed === length) { + callback(null); + } + } + + for (let idx = 0; idx < length; ++idx) { + try { + eachFn(arr[idx], eachCallback); + } catch (err) { + callback(err); + return; + } + } +} + +function isUnifiedTopology(topology) { + return topology.description != null; +} + +module.exports = { + uuidV4, + calculateDurationInMs, + relayEvents, + collationNotSupported, + retrieveEJSON, + retrieveKerberos, + maxWireVersion, + isPromiseLike, + eachAsync, + isUnifiedTopology +}; diff --git a/scripts/node_modules/mongodb/lib/core/wireprotocol/command.js b/scripts/node_modules/mongodb/lib/core/wireprotocol/command.js new file mode 100644 index 00000000..47107c62 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/core/wireprotocol/command.js @@ -0,0 +1,170 @@ +'use strict'; + +const Query = require('../connection/commands').Query; +const Msg = require('../connection/msg').Msg; +const MongoError = require('../error').MongoError; +const getReadPreference = require('./shared').getReadPreference; +const isSharded = require('./shared').isSharded; +const databaseNamespace = require('./shared').databaseNamespace; +const isTransactionCommand = require('../transactions').isTransactionCommand; +const applySession = require('../sessions').applySession; + +function isClientEncryptionEnabled(server) { + return server.autoEncrypter; +} + +function command(server, ns, cmd, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + if (cmd == null) { + return callback(new MongoError(`command ${JSON.stringify(cmd)} does not return a cursor`)); + } + + if (!isClientEncryptionEnabled(server)) { + _command(server, ns, cmd, options, callback); + return; + } + + _cryptCommand(server, ns, cmd, options, callback); +} + +function _command(server, ns, cmd, options, callback) { + const bson = server.s.bson; + const pool = server.s.pool; + const readPreference = getReadPreference(cmd, options); + const shouldUseOpMsg = supportsOpMsg(server); + const session = options.session; + + let clusterTime = server.clusterTime; + let finalCmd = Object.assign({}, cmd); + if (hasSessionSupport(server) && session) { + if ( + session.clusterTime && + session.clusterTime.clusterTime.greaterThan(clusterTime.clusterTime) + ) { + clusterTime = session.clusterTime; + } + + const err = applySession(session, finalCmd, options); + if (err) { + return callback(err); + } + } + + // if we have a known cluster time, gossip it + if (clusterTime) { + finalCmd.$clusterTime = clusterTime; + } + + if ( + isSharded(server) && + !shouldUseOpMsg && + readPreference && + readPreference.preference !== 'primary' + ) { + finalCmd = { + $query: finalCmd, + $readPreference: readPreference.toJSON() + }; + } + + const commandOptions = Object.assign( + { + command: true, + numberToSkip: 0, + numberToReturn: -1, + checkKeys: false + }, + options + ); + + // This value is not overridable + commandOptions.slaveOk = readPreference.slaveOk(); + + const cmdNs = `${databaseNamespace(ns)}.$cmd`; + const message = shouldUseOpMsg + ? new Msg(bson, cmdNs, finalCmd, commandOptions) + : new Query(bson, cmdNs, finalCmd, commandOptions); + + const inTransaction = session && (session.inTransaction() || isTransactionCommand(finalCmd)); + const commandResponseHandler = inTransaction + ? function(err) { + if ( + !cmd.commitTransaction && + err && + err instanceof MongoError && + err.hasErrorLabel('TransientTransactionError') + ) { + session.transaction.unpinServer(); + } + + return callback.apply(null, arguments); + } + : callback; + + try { + pool.write(message, commandOptions, commandResponseHandler); + } catch (err) { + commandResponseHandler(err); + } +} + +function hasSessionSupport(topology) { + if (topology == null) return false; + if (topology.description) { + return topology.description.maxWireVersion >= 6; + } + + return topology.ismaster == null ? false : topology.ismaster.maxWireVersion >= 6; +} + +function supportsOpMsg(topologyOrServer) { + const description = topologyOrServer.ismaster + ? topologyOrServer.ismaster + : topologyOrServer.description; + + if (description == null) { + return false; + } + + return description.maxWireVersion >= 6 && description.__nodejs_mock_server__ == null; +} + +function _cryptCommand(server, ns, cmd, options, callback) { + const shouldBypassAutoEncryption = !!server.s.options.bypassAutoEncryption; + const autoEncrypter = server.autoEncrypter; + function commandResponseHandler(err, response) { + if (err || response == null) { + callback(err, response); + return; + } + + autoEncrypter.decrypt(response.result, (err, decrypted) => { + if (err) { + callback(err, null); + return; + } + + response.result = decrypted; + response.message.documents = [decrypted]; + callback(null, response); + }); + } + + if (shouldBypassAutoEncryption) { + _command(server, ns, cmd, options, commandResponseHandler); + return; + } + + autoEncrypter.encrypt(ns, cmd, (err, encrypted) => { + if (err) { + callback(err, null); + return; + } + + _command(server, ns, encrypted, options, commandResponseHandler); + }); +} + +module.exports = command; diff --git a/scripts/node_modules/mongodb/lib/core/wireprotocol/compression.js b/scripts/node_modules/mongodb/lib/core/wireprotocol/compression.js new file mode 100644 index 00000000..4b908e63 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/core/wireprotocol/compression.js @@ -0,0 +1,73 @@ +'use strict'; + +var Snappy = require('../connection/utils').retrieveSnappy(), + zlib = require('zlib'); + +var compressorIDs = { + snappy: 1, + zlib: 2 +}; + +var uncompressibleCommands = [ + 'ismaster', + 'saslStart', + 'saslContinue', + 'getnonce', + 'authenticate', + 'createUser', + 'updateUser', + 'copydbSaslStart', + 'copydbgetnonce', + 'copydb' +]; + +// Facilitate compressing a message using an agreed compressor +var compress = function(self, dataToBeCompressed, callback) { + switch (self.options.agreedCompressor) { + case 'snappy': + Snappy.compress(dataToBeCompressed, callback); + break; + case 'zlib': + // Determine zlibCompressionLevel + var zlibOptions = {}; + if (self.options.zlibCompressionLevel) { + zlibOptions.level = self.options.zlibCompressionLevel; + } + zlib.deflate(dataToBeCompressed, zlibOptions, callback); + break; + default: + throw new Error( + 'Attempt to compress message using unknown compressor "' + + self.options.agreedCompressor + + '".' + ); + } +}; + +// Decompress a message using the given compressor +var decompress = function(compressorID, compressedData, callback) { + if (compressorID < 0 || compressorID > compressorIDs.length) { + throw new Error( + 'Server sent message compressed using an unsupported compressor. (Received compressor ID ' + + compressorID + + ')' + ); + } + switch (compressorID) { + case compressorIDs.snappy: + Snappy.uncompress(compressedData, callback); + break; + case compressorIDs.zlib: + zlib.inflate(compressedData, callback); + break; + default: + callback(null, compressedData); + } +}; + +module.exports = { + compressorIDs: compressorIDs, + uncompressibleCommands: uncompressibleCommands, + compress: compress, + decompress: decompress +}; diff --git a/scripts/node_modules/mongodb/lib/core/wireprotocol/constants.js b/scripts/node_modules/mongodb/lib/core/wireprotocol/constants.js new file mode 100644 index 00000000..df2293b5 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/core/wireprotocol/constants.js @@ -0,0 +1,13 @@ +'use strict'; + +const MIN_SUPPORTED_SERVER_VERSION = '2.6'; +const MAX_SUPPORTED_SERVER_VERSION = '4.2'; +const MIN_SUPPORTED_WIRE_VERSION = 2; +const MAX_SUPPORTED_WIRE_VERSION = 8; + +module.exports = { + MIN_SUPPORTED_SERVER_VERSION, + MAX_SUPPORTED_SERVER_VERSION, + MIN_SUPPORTED_WIRE_VERSION, + MAX_SUPPORTED_WIRE_VERSION +}; diff --git a/scripts/node_modules/mongodb/lib/core/wireprotocol/get_more.js b/scripts/node_modules/mongodb/lib/core/wireprotocol/get_more.js new file mode 100644 index 00000000..b2db3202 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/core/wireprotocol/get_more.js @@ -0,0 +1,90 @@ +'use strict'; + +const GetMore = require('../connection/commands').GetMore; +const retrieveBSON = require('../connection/utils').retrieveBSON; +const MongoError = require('../error').MongoError; +const MongoNetworkError = require('../error').MongoNetworkError; +const BSON = retrieveBSON(); +const Long = BSON.Long; +const collectionNamespace = require('./shared').collectionNamespace; +const maxWireVersion = require('../utils').maxWireVersion; +const applyCommonQueryOptions = require('./shared').applyCommonQueryOptions; +const command = require('./command'); + +function getMore(server, ns, cursorState, batchSize, options, callback) { + options = options || {}; + + const wireVersion = maxWireVersion(server); + function queryCallback(err, result) { + if (err) return callback(err); + const response = result.message; + + // If we have a timed out query or a cursor that was killed + if (response.cursorNotFound) { + return callback(new MongoNetworkError('cursor killed or timed out'), null); + } + + if (wireVersion < 4) { + const cursorId = + typeof response.cursorId === 'number' + ? Long.fromNumber(response.cursorId) + : response.cursorId; + + cursorState.documents = response.documents; + cursorState.cursorId = cursorId; + + callback(null, null, response.connection); + return; + } + + // We have an error detected + if (response.documents[0].ok === 0) { + return callback(new MongoError(response.documents[0])); + } + + // Ensure we have a Long valid cursor id + const cursorId = + typeof response.documents[0].cursor.id === 'number' + ? Long.fromNumber(response.documents[0].cursor.id) + : response.documents[0].cursor.id; + + cursorState.documents = response.documents[0].cursor.nextBatch; + cursorState.cursorId = cursorId; + + callback(null, response.documents[0], response.connection); + } + + if (wireVersion < 4) { + const bson = server.s.bson; + const getMoreOp = new GetMore(bson, ns, cursorState.cursorId, { numberToReturn: batchSize }); + const queryOptions = applyCommonQueryOptions({}, cursorState); + server.s.pool.write(getMoreOp, queryOptions, queryCallback); + return; + } + + const getMoreCmd = { + getMore: cursorState.cursorId, + collection: collectionNamespace(ns), + batchSize: Math.abs(batchSize) + }; + + if (cursorState.cmd.tailable && typeof cursorState.cmd.maxAwaitTimeMS === 'number') { + getMoreCmd.maxTimeMS = cursorState.cmd.maxAwaitTimeMS; + } + + const commandOptions = Object.assign( + { + returnFieldSelector: null, + documentsReturnedIn: 'nextBatch' + }, + options + ); + + if (cursorState.session) { + commandOptions.session = cursorState.session; + } + + command(server, ns, getMoreCmd, commandOptions, queryCallback); +} + +module.exports = getMore; diff --git a/scripts/node_modules/mongodb/lib/core/wireprotocol/index.js b/scripts/node_modules/mongodb/lib/core/wireprotocol/index.js new file mode 100644 index 00000000..b6ffda7c --- /dev/null +++ b/scripts/node_modules/mongodb/lib/core/wireprotocol/index.js @@ -0,0 +1,18 @@ +'use strict'; +const writeCommand = require('./write_command'); + +module.exports = { + insert: function insert(server, ns, ops, options, callback) { + writeCommand(server, 'insert', 'documents', ns, ops, options, callback); + }, + update: function update(server, ns, ops, options, callback) { + writeCommand(server, 'update', 'updates', ns, ops, options, callback); + }, + remove: function remove(server, ns, ops, options, callback) { + writeCommand(server, 'delete', 'deletes', ns, ops, options, callback); + }, + killCursors: require('./kill_cursors'), + getMore: require('./get_more'), + query: require('./query'), + command: require('./command') +}; diff --git a/scripts/node_modules/mongodb/lib/core/wireprotocol/kill_cursors.js b/scripts/node_modules/mongodb/lib/core/wireprotocol/kill_cursors.js new file mode 100644 index 00000000..bb134773 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/core/wireprotocol/kill_cursors.js @@ -0,0 +1,70 @@ +'use strict'; + +const KillCursor = require('../connection/commands').KillCursor; +const MongoError = require('../error').MongoError; +const MongoNetworkError = require('../error').MongoNetworkError; +const collectionNamespace = require('./shared').collectionNamespace; +const maxWireVersion = require('../utils').maxWireVersion; +const command = require('./command'); + +function killCursors(server, ns, cursorState, callback) { + callback = typeof callback === 'function' ? callback : () => {}; + const cursorId = cursorState.cursorId; + + if (maxWireVersion(server) < 4) { + const bson = server.s.bson; + const pool = server.s.pool; + const killCursor = new KillCursor(bson, ns, [cursorId]); + const options = { + immediateRelease: true, + noResponse: true + }; + + if (typeof cursorState.session === 'object') { + options.session = cursorState.session; + } + + if (pool && pool.isConnected()) { + try { + pool.write(killCursor, options, callback); + } catch (err) { + if (typeof callback === 'function') { + callback(err, null); + } else { + console.warn(err); + } + } + } + + return; + } + + const killCursorCmd = { + killCursors: collectionNamespace(ns), + cursors: [cursorId] + }; + + const options = {}; + if (typeof cursorState.session === 'object') options.session = cursorState.session; + + command(server, ns, killCursorCmd, options, (err, result) => { + if (err) { + return callback(err); + } + + const response = result.message; + if (response.cursorNotFound) { + return callback(new MongoNetworkError('cursor killed or timed out'), null); + } + + if (!Array.isArray(response.documents) || response.documents.length === 0) { + return callback( + new MongoError(`invalid killCursors result returned for cursor id ${cursorId}`) + ); + } + + callback(null, response.documents[0]); + }); +} + +module.exports = killCursors; diff --git a/scripts/node_modules/mongodb/lib/core/wireprotocol/query.js b/scripts/node_modules/mongodb/lib/core/wireprotocol/query.js new file mode 100644 index 00000000..c501b506 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/core/wireprotocol/query.js @@ -0,0 +1,231 @@ +'use strict'; + +const Query = require('../connection/commands').Query; +const MongoError = require('../error').MongoError; +const getReadPreference = require('./shared').getReadPreference; +const collectionNamespace = require('./shared').collectionNamespace; +const isSharded = require('./shared').isSharded; +const maxWireVersion = require('../utils').maxWireVersion; +const applyCommonQueryOptions = require('./shared').applyCommonQueryOptions; +const command = require('./command'); + +function query(server, ns, cmd, cursorState, options, callback) { + options = options || {}; + if (cursorState.cursorId != null) { + return callback(); + } + + if (cmd == null) { + return callback(new MongoError(`command ${JSON.stringify(cmd)} does not return a cursor`)); + } + + if (maxWireVersion(server) < 4) { + const query = prepareLegacyFindQuery(server, ns, cmd, cursorState, options); + const queryOptions = applyCommonQueryOptions({}, cursorState); + if (typeof query.documentsReturnedIn === 'string') { + queryOptions.documentsReturnedIn = query.documentsReturnedIn; + } + + server.s.pool.write(query, queryOptions, callback); + return; + } + + const readPreference = getReadPreference(cmd, options); + const findCmd = prepareFindCommand(server, ns, cmd, cursorState, options); + + // NOTE: This actually modifies the passed in cmd, and our code _depends_ on this + // side-effect. Change this ASAP + cmd.virtual = false; + + const commandOptions = Object.assign( + { + documentsReturnedIn: 'firstBatch', + numberToReturn: 1, + slaveOk: readPreference.slaveOk() + }, + options + ); + + if (cmd.readPreference) { + commandOptions.readPreference = readPreference; + } + + if (cursorState.session) { + commandOptions.session = cursorState.session; + } + + command(server, ns, findCmd, commandOptions, callback); +} + +function prepareFindCommand(server, ns, cmd, cursorState) { + cursorState.batchSize = cmd.batchSize || cursorState.batchSize; + let findCmd = { + find: collectionNamespace(ns) + }; + + if (cmd.query) { + if (cmd.query['$query']) { + findCmd.filter = cmd.query['$query']; + } else { + findCmd.filter = cmd.query; + } + } + + let sortValue = cmd.sort; + if (Array.isArray(sortValue)) { + const sortObject = {}; + + if (sortValue.length > 0 && !Array.isArray(sortValue[0])) { + let sortDirection = sortValue[1]; + if (sortDirection === 'asc') { + sortDirection = 1; + } else if (sortDirection === 'desc') { + sortDirection = -1; + } + + sortObject[sortValue[0]] = sortDirection; + } else { + for (let i = 0; i < sortValue.length; i++) { + let sortDirection = sortValue[i][1]; + if (sortDirection === 'asc') { + sortDirection = 1; + } else if (sortDirection === 'desc') { + sortDirection = -1; + } + + sortObject[sortValue[i][0]] = sortDirection; + } + } + + sortValue = sortObject; + } + + if (cmd.sort) findCmd.sort = sortValue; + if (cmd.fields) findCmd.projection = cmd.fields; + if (cmd.hint) findCmd.hint = cmd.hint; + if (cmd.skip) findCmd.skip = cmd.skip; + if (cmd.limit) findCmd.limit = cmd.limit; + if (cmd.limit < 0) { + findCmd.limit = Math.abs(cmd.limit); + findCmd.singleBatch = true; + } + + if (typeof cmd.batchSize === 'number') { + if (cmd.batchSize < 0) { + if (cmd.limit !== 0 && Math.abs(cmd.batchSize) < Math.abs(cmd.limit)) { + findCmd.limit = Math.abs(cmd.batchSize); + } + + findCmd.singleBatch = true; + } + + findCmd.batchSize = Math.abs(cmd.batchSize); + } + + if (cmd.comment) findCmd.comment = cmd.comment; + if (cmd.maxScan) findCmd.maxScan = cmd.maxScan; + if (cmd.maxTimeMS) findCmd.maxTimeMS = cmd.maxTimeMS; + if (cmd.min) findCmd.min = cmd.min; + if (cmd.max) findCmd.max = cmd.max; + findCmd.returnKey = cmd.returnKey ? cmd.returnKey : false; + findCmd.showRecordId = cmd.showDiskLoc ? cmd.showDiskLoc : false; + if (cmd.snapshot) findCmd.snapshot = cmd.snapshot; + if (cmd.tailable) findCmd.tailable = cmd.tailable; + if (cmd.oplogReplay) findCmd.oplogReplay = cmd.oplogReplay; + if (cmd.noCursorTimeout) findCmd.noCursorTimeout = cmd.noCursorTimeout; + if (cmd.awaitData) findCmd.awaitData = cmd.awaitData; + if (cmd.awaitdata) findCmd.awaitData = cmd.awaitdata; + if (cmd.partial) findCmd.partial = cmd.partial; + if (cmd.collation) findCmd.collation = cmd.collation; + if (cmd.readConcern) findCmd.readConcern = cmd.readConcern; + + // If we have explain, we need to rewrite the find command + // to wrap it in the explain command + if (cmd.explain) { + findCmd = { + explain: findCmd + }; + } + + return findCmd; +} + +function prepareLegacyFindQuery(server, ns, cmd, cursorState, options) { + options = options || {}; + const bson = server.s.bson; + const readPreference = getReadPreference(cmd, options); + cursorState.batchSize = cmd.batchSize || cursorState.batchSize; + + let numberToReturn = 0; + if ( + cursorState.limit < 0 || + (cursorState.limit !== 0 && cursorState.limit < cursorState.batchSize) || + (cursorState.limit > 0 && cursorState.batchSize === 0) + ) { + numberToReturn = cursorState.limit; + } else { + numberToReturn = cursorState.batchSize; + } + + const numberToSkip = cursorState.skip || 0; + + const findCmd = {}; + if (isSharded(server) && readPreference) { + findCmd['$readPreference'] = readPreference.toJSON(); + } + + if (cmd.sort) findCmd['$orderby'] = cmd.sort; + if (cmd.hint) findCmd['$hint'] = cmd.hint; + if (cmd.snapshot) findCmd['$snapshot'] = cmd.snapshot; + if (typeof cmd.returnKey !== 'undefined') findCmd['$returnKey'] = cmd.returnKey; + if (cmd.maxScan) findCmd['$maxScan'] = cmd.maxScan; + if (cmd.min) findCmd['$min'] = cmd.min; + if (cmd.max) findCmd['$max'] = cmd.max; + if (typeof cmd.showDiskLoc !== 'undefined') findCmd['$showDiskLoc'] = cmd.showDiskLoc; + if (cmd.comment) findCmd['$comment'] = cmd.comment; + if (cmd.maxTimeMS) findCmd['$maxTimeMS'] = cmd.maxTimeMS; + if (cmd.explain) { + // nToReturn must be 0 (match all) or negative (match N and close cursor) + // nToReturn > 0 will give explain results equivalent to limit(0) + numberToReturn = -Math.abs(cmd.limit || 0); + findCmd['$explain'] = true; + } + + findCmd['$query'] = cmd.query; + if (cmd.readConcern && cmd.readConcern.level !== 'local') { + throw new MongoError( + `server find command does not support a readConcern level of ${cmd.readConcern.level}` + ); + } + + if (cmd.readConcern) { + cmd = Object.assign({}, cmd); + delete cmd['readConcern']; + } + + const serializeFunctions = + typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; + const ignoreUndefined = + typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : false; + + const query = new Query(bson, ns, findCmd, { + numberToSkip: numberToSkip, + numberToReturn: numberToReturn, + pre32Limit: typeof cmd.limit !== 'undefined' ? cmd.limit : undefined, + checkKeys: false, + returnFieldSelector: cmd.fields, + serializeFunctions: serializeFunctions, + ignoreUndefined: ignoreUndefined + }); + + if (typeof cmd.tailable === 'boolean') query.tailable = cmd.tailable; + if (typeof cmd.oplogReplay === 'boolean') query.oplogReplay = cmd.oplogReplay; + if (typeof cmd.noCursorTimeout === 'boolean') query.noCursorTimeout = cmd.noCursorTimeout; + if (typeof cmd.awaitData === 'boolean') query.awaitData = cmd.awaitData; + if (typeof cmd.partial === 'boolean') query.partial = cmd.partial; + + query.slaveOk = readPreference.slaveOk(); + return query; +} + +module.exports = query; diff --git a/scripts/node_modules/mongodb/lib/core/wireprotocol/shared.js b/scripts/node_modules/mongodb/lib/core/wireprotocol/shared.js new file mode 100644 index 00000000..2574aade --- /dev/null +++ b/scripts/node_modules/mongodb/lib/core/wireprotocol/shared.js @@ -0,0 +1,115 @@ +'use strict'; + +const ReadPreference = require('../topologies/read_preference'); +const MongoError = require('../error').MongoError; +const ServerType = require('../sdam/server_description').ServerType; +const TopologyDescription = require('../sdam/topology_description').TopologyDescription; + +const MESSAGE_HEADER_SIZE = 16; +const COMPRESSION_DETAILS_SIZE = 9; // originalOpcode + uncompressedSize, compressorID + +// OPCODE Numbers +// Defined at https://docs.mongodb.com/manual/reference/mongodb-wire-protocol/#request-opcodes +var opcodes = { + OP_REPLY: 1, + OP_UPDATE: 2001, + OP_INSERT: 2002, + OP_QUERY: 2004, + OP_GETMORE: 2005, + OP_DELETE: 2006, + OP_KILL_CURSORS: 2007, + OP_COMPRESSED: 2012, + OP_MSG: 2013 +}; + +var getReadPreference = function(cmd, options) { + // Default to command version of the readPreference + var readPreference = cmd.readPreference || new ReadPreference('primary'); + // If we have an option readPreference override the command one + if (options.readPreference) { + readPreference = options.readPreference; + } + + if (typeof readPreference === 'string') { + readPreference = new ReadPreference(readPreference); + } + + if (!(readPreference instanceof ReadPreference)) { + throw new MongoError('read preference must be a ReadPreference instance'); + } + + return readPreference; +}; + +// Parses the header of a wire protocol message +var parseHeader = function(message) { + return { + length: message.readInt32LE(0), + requestId: message.readInt32LE(4), + responseTo: message.readInt32LE(8), + opCode: message.readInt32LE(12) + }; +}; + +function applyCommonQueryOptions(queryOptions, options) { + Object.assign(queryOptions, { + raw: typeof options.raw === 'boolean' ? options.raw : false, + promoteLongs: typeof options.promoteLongs === 'boolean' ? options.promoteLongs : true, + promoteValues: typeof options.promoteValues === 'boolean' ? options.promoteValues : true, + promoteBuffers: typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : false, + monitoring: typeof options.monitoring === 'boolean' ? options.monitoring : false, + fullResult: typeof options.fullResult === 'boolean' ? options.fullResult : false + }); + + if (typeof options.socketTimeout === 'number') { + queryOptions.socketTimeout = options.socketTimeout; + } + + if (options.session) { + queryOptions.session = options.session; + } + + if (typeof options.documentsReturnedIn === 'string') { + queryOptions.documentsReturnedIn = options.documentsReturnedIn; + } + + return queryOptions; +} + +function isSharded(topologyOrServer) { + if (topologyOrServer.type === 'mongos') return true; + if (topologyOrServer.description && topologyOrServer.description.type === ServerType.Mongos) { + return true; + } + + // NOTE: This is incredibly inefficient, and should be removed once command construction + // happens based on `Server` not `Topology`. + if (topologyOrServer.description && topologyOrServer.description instanceof TopologyDescription) { + const servers = Array.from(topologyOrServer.description.servers.values()); + return servers.some(server => server.type === ServerType.Mongos); + } + + return false; +} + +function databaseNamespace(ns) { + return ns.split('.')[0]; +} +function collectionNamespace(ns) { + return ns + .split('.') + .slice(1) + .join('.'); +} + +module.exports = { + getReadPreference, + MESSAGE_HEADER_SIZE, + COMPRESSION_DETAILS_SIZE, + opcodes, + parseHeader, + applyCommonQueryOptions, + isSharded, + databaseNamespace, + collectionNamespace +}; diff --git a/scripts/node_modules/mongodb/lib/core/wireprotocol/write_command.js b/scripts/node_modules/mongodb/lib/core/wireprotocol/write_command.js new file mode 100644 index 00000000..e334d518 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/core/wireprotocol/write_command.js @@ -0,0 +1,50 @@ +'use strict'; + +const MongoError = require('../error').MongoError; +const collectionNamespace = require('./shared').collectionNamespace; +const command = require('./command'); + +function writeCommand(server, type, opsField, ns, ops, options, callback) { + if (ops.length === 0) throw new MongoError(`${type} must contain at least one document`); + if (typeof options === 'function') { + callback = options; + options = {}; + } + + options = options || {}; + const ordered = typeof options.ordered === 'boolean' ? options.ordered : true; + const writeConcern = options.writeConcern; + + const writeCommand = {}; + writeCommand[type] = collectionNamespace(ns); + writeCommand[opsField] = ops; + writeCommand.ordered = ordered; + + if (writeConcern && Object.keys(writeConcern).length > 0) { + writeCommand.writeConcern = writeConcern; + } + + if (options.collation) { + for (let i = 0; i < writeCommand[opsField].length; i++) { + if (!writeCommand[opsField][i].collation) { + writeCommand[opsField][i].collation = options.collation; + } + } + } + + if (options.bypassDocumentValidation === true) { + writeCommand.bypassDocumentValidation = options.bypassDocumentValidation; + } + + const commandOptions = Object.assign( + { + checkKeys: type === 'insert', + numberToReturn: 1 + }, + options + ); + + command(server, ns, writeCommand, commandOptions, callback); +} + +module.exports = writeCommand; diff --git a/scripts/node_modules/mongodb/lib/cursor.js b/scripts/node_modules/mongodb/lib/cursor.js new file mode 100644 index 00000000..bed709be --- /dev/null +++ b/scripts/node_modules/mongodb/lib/cursor.js @@ -0,0 +1,1089 @@ +'use strict'; + +const Transform = require('stream').Transform; +const PassThrough = require('stream').PassThrough; +const deprecate = require('util').deprecate; +const handleCallback = require('./utils').handleCallback; +const ReadPreference = require('./core').ReadPreference; +const MongoError = require('./core').MongoError; +const CoreCursor = require('./core/cursor').CoreCursor; +const CursorState = require('./core/cursor').CursorState; +const Map = require('./core').BSON.Map; + +const each = require('./operations/cursor_ops').each; + +const CountOperation = require('./operations/count'); +const ExplainOperation = require('./operations/explain'); +const HasNextOperation = require('./operations/has_next'); +const NextOperation = require('./operations/next'); +const ToArrayOperation = require('./operations/to_array'); + +const executeOperation = require('./operations/execute_operation'); + +/** + * @fileOverview The **Cursor** class is an internal class that embodies a cursor on MongoDB + * allowing for iteration over the results returned from the underlying query. It supports + * one by one document iteration, conversion to an array or can be iterated as a Node 4.X + * or higher stream + * + * **CURSORS Cannot directly be instantiated** + * @example + * const MongoClient = require('mongodb').MongoClient; + * const test = require('assert'); + * // Connection url + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, client) { + * // Create a collection we want to drop later + * const col = client.db(dbName).collection('createIndexExample1'); + * // Insert a bunch of documents + * col.insert([{a:1, b:1} + * , {a:2, b:2}, {a:3, b:3} + * , {a:4, b:4}], {w:1}, function(err, result) { + * test.equal(null, err); + * // Show that duplicate records got dropped + * col.find({}).toArray(function(err, items) { + * test.equal(null, err); + * test.equal(4, items.length); + * client.close(); + * }); + * }); + * }); + */ + +/** + * Namespace provided by the code module + * @external CoreCursor + * @external Readable + */ + +// Flags allowed for cursor +const flags = ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'exhaust', 'partial']; +const fields = ['numberOfRetries', 'tailableRetryInterval']; + +/** + * Creates a new Cursor instance (INTERNAL TYPE, do not instantiate directly) + * @class Cursor + * @extends external:CoreCursor + * @extends external:Readable + * @property {string} sortValue Cursor query sort setting. + * @property {boolean} timeout Is Cursor able to time out. + * @property {ReadPreference} readPreference Get cursor ReadPreference. + * @fires Cursor#data + * @fires Cursor#end + * @fires Cursor#close + * @fires Cursor#readable + * @return {Cursor} a Cursor instance. + * @example + * Cursor cursor options. + * + * collection.find({}).project({a:1}) // Create a projection of field a + * collection.find({}).skip(1).limit(10) // Skip 1 and limit 10 + * collection.find({}).batchSize(5) // Set batchSize on cursor to 5 + * collection.find({}).filter({a:1}) // Set query on the cursor + * collection.find({}).comment('add a comment') // Add a comment to the query, allowing to correlate queries + * collection.find({}).addCursorFlag('tailable', true) // Set cursor as tailable + * collection.find({}).addCursorFlag('oplogReplay', true) // Set cursor as oplogReplay + * collection.find({}).addCursorFlag('noCursorTimeout', true) // Set cursor as noCursorTimeout + * collection.find({}).addCursorFlag('awaitData', true) // Set cursor as awaitData + * collection.find({}).addCursorFlag('partial', true) // Set cursor as partial + * collection.find({}).addQueryModifier('$orderby', {a:1}) // Set $orderby {a:1} + * collection.find({}).max(10) // Set the cursor max + * collection.find({}).maxTimeMS(1000) // Set the cursor maxTimeMS + * collection.find({}).min(100) // Set the cursor min + * collection.find({}).returnKey(true) // Set the cursor returnKey + * collection.find({}).setReadPreference(ReadPreference.PRIMARY) // Set the cursor readPreference + * collection.find({}).showRecordId(true) // Set the cursor showRecordId + * collection.find({}).sort([['a', 1]]) // Sets the sort order of the cursor query + * collection.find({}).hint('a_1') // Set the cursor hint + * + * All options are chainable, so one can do the following. + * + * collection.find({}).maxTimeMS(1000).maxScan(100).skip(1).toArray(..) + */ +class Cursor extends CoreCursor { + constructor(topology, ns, cmd, options) { + super(topology, ns, cmd, options); + if (this.operation) { + options = this.operation.options; + } + + // Tailable cursor options + const numberOfRetries = options.numberOfRetries || 5; + const tailableRetryInterval = options.tailableRetryInterval || 500; + const currentNumberOfRetries = numberOfRetries; + + // Get the promiseLibrary + const promiseLibrary = options.promiseLibrary || Promise; + + // Internal cursor state + this.s = { + // Tailable cursor options + numberOfRetries: numberOfRetries, + tailableRetryInterval: tailableRetryInterval, + currentNumberOfRetries: currentNumberOfRetries, + // State + state: CursorState.INIT, + // Promise library + promiseLibrary, + // Current doc + currentDoc: null, + // explicitlyIgnoreSession + explicitlyIgnoreSession: !!options.explicitlyIgnoreSession + }; + + // Optional ClientSession + if (!options.explicitlyIgnoreSession && options.session) { + this.cursorState.session = options.session; + } + + // Translate correctly + if (this.options.noCursorTimeout === true) { + this.addCursorFlag('noCursorTimeout', true); + } + + // Get the batchSize + let batchSize = 1000; + if (this.cmd.cursor && this.cmd.cursor.batchSize) { + batchSize = this.cmd.cursor.batchSize; + } else if (options.cursor && options.cursor.batchSize) { + batchSize = options.cursor.batchSize; + } else if (typeof options.batchSize === 'number') { + batchSize = options.batchSize; + } + + // Set the batchSize + this.setCursorBatchSize(batchSize); + } + + get readPreference() { + if (this.operation) { + return this.operation.readPreference; + } + + return this.options.readPreference; + } + + get sortValue() { + return this.cmd.sort; + } + + _initializeCursor(callback) { + if (this.operation && this.operation.session != null) { + this.cursorState.session = this.operation.session; + } else { + // implicitly create a session if one has not been provided + if ( + !this.s.explicitlyIgnoreSession && + !this.cursorState.session && + this.topology.hasSessionSupport() + ) { + this.cursorState.session = this.topology.startSession({ owner: this }); + + if (this.operation) { + this.operation.session = this.cursorState.session; + } + } + } + + super._initializeCursor(callback); + } + + /** + * Check if there is any document still available in the cursor + * @method + * @param {Cursor~resultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ + hasNext(callback) { + const hasNextOperation = new HasNextOperation(this); + + return executeOperation(this.topology, hasNextOperation, callback); + } + + /** + * Get the next available document from the cursor, returns null if no more documents are available. + * @method + * @param {Cursor~resultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ + next(callback) { + const nextOperation = new NextOperation(this); + + return executeOperation(this.topology, nextOperation, callback); + } + + /** + * Set the cursor query + * @method + * @param {object} filter The filter object used for the cursor. + * @return {Cursor} + */ + filter(filter) { + if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + this.cmd.query = filter; + return this; + } + + /** + * Set the cursor maxScan + * @method + * @param {object} maxScan Constrains the query to only scan the specified number of documents when fulfilling the query + * @deprecated as of MongoDB 4.0 + * @return {Cursor} + */ + maxScan(maxScan) { + if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + this.cmd.maxScan = maxScan; + return this; + } + + /** + * Set the cursor hint + * @method + * @param {object} hint If specified, then the query system will only consider plans using the hinted index. + * @return {Cursor} + */ + hint(hint) { + if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + this.cmd.hint = hint; + return this; + } + + /** + * Set the cursor min + * @method + * @param {object} min Specify a $min value to specify the inclusive lower bound for a specific index in order to constrain the results of find(). The $min specifies the lower bound for all keys of a specific index in order. + * @return {Cursor} + */ + min(min) { + if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + this.cmd.min = min; + return this; + } + + /** + * Set the cursor max + * @method + * @param {object} max Specify a $max value to specify the exclusive upper bound for a specific index in order to constrain the results of find(). The $max specifies the upper bound for all keys of a specific index in order. + * @return {Cursor} + */ + max(max) { + if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + this.cmd.max = max; + return this; + } + + /** + * Set the cursor returnKey. If set to true, modifies the cursor to only return the index field or fields for the results of the query, rather than documents. If set to true and the query does not use an index to perform the read operation, the returned documents will not contain any fields. + * @method + * @param {bool} returnKey the returnKey value. + * @return {Cursor} + */ + returnKey(value) { + if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + this.cmd.returnKey = value; + return this; + } + + /** + * Set the cursor showRecordId + * @method + * @param {object} showRecordId The $showDiskLoc option has now been deprecated and replaced with the showRecordId field. $showDiskLoc will still be accepted for OP_QUERY stye find. + * @return {Cursor} + */ + showRecordId(value) { + if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + this.cmd.showDiskLoc = value; + return this; + } + + /** + * Set the cursor snapshot + * @method + * @param {object} snapshot The $snapshot operator prevents the cursor from returning a document more than once because an intervening write operation results in a move of the document. + * @deprecated as of MongoDB 4.0 + * @return {Cursor} + */ + snapshot(value) { + if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + this.cmd.snapshot = value; + return this; + } + + /** + * Set a node.js specific cursor option + * @method + * @param {string} field The cursor option to set ['numberOfRetries', 'tailableRetryInterval']. + * @param {object} value The field value. + * @throws {MongoError} + * @return {Cursor} + */ + setCursorOption(field, value) { + if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + if (fields.indexOf(field) === -1) { + throw MongoError.create({ + message: `option ${field} is not a supported option ${fields}`, + driver: true + }); + } + + this.s[field] = value; + if (field === 'numberOfRetries') this.s.currentNumberOfRetries = value; + return this; + } + + /** + * Add a cursor flag to the cursor + * @method + * @param {string} flag The flag to set, must be one of following ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'partial']. + * @param {boolean} value The flag boolean value. + * @throws {MongoError} + * @return {Cursor} + */ + addCursorFlag(flag, value) { + if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + if (flags.indexOf(flag) === -1) { + throw MongoError.create({ + message: `flag ${flag} is not a supported flag ${flags}`, + driver: true + }); + } + + if (typeof value !== 'boolean') { + throw MongoError.create({ message: `flag ${flag} must be a boolean value`, driver: true }); + } + + this.cmd[flag] = value; + return this; + } + + /** + * Add a query modifier to the cursor query + * @method + * @param {string} name The query modifier (must start with $, such as $orderby etc) + * @param {string|boolean|number} value The modifier value. + * @throws {MongoError} + * @return {Cursor} + */ + addQueryModifier(name, value) { + if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + if (name[0] !== '$') { + throw MongoError.create({ message: `${name} is not a valid query modifier`, driver: true }); + } + + // Strip of the $ + const field = name.substr(1); + // Set on the command + this.cmd[field] = value; + // Deal with the special case for sort + if (field === 'orderby') this.cmd.sort = this.cmd[field]; + return this; + } + + /** + * Add a comment to the cursor query allowing for tracking the comment in the log. + * @method + * @param {string} value The comment attached to this query. + * @throws {MongoError} + * @return {Cursor} + */ + comment(value) { + if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + this.cmd.comment = value; + return this; + } + + /** + * Set a maxAwaitTimeMS on a tailing cursor query to allow to customize the timeout value for the option awaitData (Only supported on MongoDB 3.2 or higher, ignored otherwise) + * @method + * @param {number} value Number of milliseconds to wait before aborting the tailed query. + * @throws {MongoError} + * @return {Cursor} + */ + maxAwaitTimeMS(value) { + if (typeof value !== 'number') { + throw MongoError.create({ message: 'maxAwaitTimeMS must be a number', driver: true }); + } + + if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + this.cmd.maxAwaitTimeMS = value; + return this; + } + + /** + * Set a maxTimeMS on the cursor query, allowing for hard timeout limits on queries (Only supported on MongoDB 2.6 or higher) + * @method + * @param {number} value Number of milliseconds to wait before aborting the query. + * @throws {MongoError} + * @return {Cursor} + */ + maxTimeMS(value) { + if (typeof value !== 'number') { + throw MongoError.create({ message: 'maxTimeMS must be a number', driver: true }); + } + + if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + this.cmd.maxTimeMS = value; + return this; + } + + /** + * Sets a field projection for the query. + * @method + * @param {object} value The field projection object. + * @throws {MongoError} + * @return {Cursor} + */ + project(value) { + if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + this.cmd.fields = value; + return this; + } + + /** + * Sets the sort order of the cursor query. + * @method + * @param {(string|array|object)} keyOrList The key or keys set for the sort. + * @param {number} [direction] The direction of the sorting (1 or -1). + * @throws {MongoError} + * @return {Cursor} + */ + sort(keyOrList, direction) { + if (this.options.tailable) { + throw MongoError.create({ message: "Tailable cursor doesn't support sorting", driver: true }); + } + + if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + let order = keyOrList; + + // We have an array of arrays, we need to preserve the order of the sort + // so we will us a Map + if (Array.isArray(order) && Array.isArray(order[0])) { + order = new Map( + order.map(x => { + const value = [x[0], null]; + if (x[1] === 'asc') { + value[1] = 1; + } else if (x[1] === 'desc') { + value[1] = -1; + } else if (x[1] === 1 || x[1] === -1 || x[1].$meta) { + value[1] = x[1]; + } else { + throw new MongoError( + "Illegal sort clause, must be of the form [['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]" + ); + } + + return value; + }) + ); + } + + if (direction != null) { + order = [[keyOrList, direction]]; + } + + this.cmd.sort = order; + return this; + } + + /** + * Set the batch size for the cursor. + * @method + * @param {number} value The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/find/|find command documentation}. + * @throws {MongoError} + * @return {Cursor} + */ + batchSize(value) { + if (this.options.tailable) { + throw MongoError.create({ + message: "Tailable cursor doesn't support batchSize", + driver: true + }); + } + + if (this.s.state === CursorState.CLOSED || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + if (typeof value !== 'number') { + throw MongoError.create({ message: 'batchSize requires an integer', driver: true }); + } + + this.cmd.batchSize = value; + this.setCursorBatchSize(value); + return this; + } + + /** + * Set the collation options for the cursor. + * @method + * @param {object} value The cursor collation options (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). + * @throws {MongoError} + * @return {Cursor} + */ + collation(value) { + this.cmd.collation = value; + return this; + } + + /** + * Set the limit for the cursor. + * @method + * @param {number} value The limit for the cursor query. + * @throws {MongoError} + * @return {Cursor} + */ + limit(value) { + if (this.options.tailable) { + throw MongoError.create({ message: "Tailable cursor doesn't support limit", driver: true }); + } + + if (this.s.state === CursorState.OPEN || this.s.state === CursorState.CLOSED || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + if (typeof value !== 'number') { + throw MongoError.create({ message: 'limit requires an integer', driver: true }); + } + + this.cmd.limit = value; + this.setCursorLimit(value); + return this; + } + + /** + * Set the skip for the cursor. + * @method + * @param {number} value The skip for the cursor query. + * @throws {MongoError} + * @return {Cursor} + */ + skip(value) { + if (this.options.tailable) { + throw MongoError.create({ message: "Tailable cursor doesn't support skip", driver: true }); + } + + if (this.s.state === CursorState.OPEN || this.s.state === CursorState.CLOSED || this.isDead()) { + throw MongoError.create({ message: 'Cursor is closed', driver: true }); + } + + if (typeof value !== 'number') { + throw MongoError.create({ message: 'skip requires an integer', driver: true }); + } + + this.cmd.skip = value; + this.setCursorSkip(value); + return this; + } + + /** + * The callback format for results + * @callback Cursor~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {(object|null|boolean)} result The result object if the command was executed successfully. + */ + + /** + * Clone the cursor + * @function external:CoreCursor#clone + * @return {Cursor} + */ + + /** + * Resets the cursor + * @function external:CoreCursor#rewind + * @return {null} + */ + + /** + * Iterates over all the documents for this cursor. As with **{cursor.toArray}**, + * not all of the elements will be iterated if this cursor had been previously accessed. + * In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike + * **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements + * at any given time if batch size is specified. Otherwise, the caller is responsible + * for making sure that the entire result can fit the memory. + * @method + * @deprecated + * @param {Cursor~resultCallback} callback The result callback. + * @throws {MongoError} + * @return {null} + */ + each(callback) { + // Rewind cursor state + this.rewind(); + // Set current cursor to INIT + this.s.state = CursorState.INIT; + // Run the query + each(this, callback); + } + + /** + * The callback format for the forEach iterator method + * @callback Cursor~iteratorCallback + * @param {Object} doc An emitted document for the iterator + */ + + /** + * The callback error format for the forEach iterator method + * @callback Cursor~endCallback + * @param {MongoError} error An error instance representing the error during the execution. + */ + + /** + * Iterates over all the documents for this cursor using the iterator, callback pattern. + * @method + * @param {Cursor~iteratorCallback} iterator The iteration callback. + * @param {Cursor~endCallback} callback The end callback. + * @throws {MongoError} + * @return {Promise} if no callback supplied + */ + forEach(iterator, callback) { + // Rewind cursor state + this.rewind(); + + // Set current cursor to INIT + this.s.state = CursorState.INIT; + + if (typeof callback === 'function') { + each(this, (err, doc) => { + if (err) { + callback(err); + return false; + } + if (doc != null) { + iterator(doc); + return true; + } + if (doc == null && callback) { + const internalCallback = callback; + callback = null; + internalCallback(null); + return false; + } + }); + } else { + return new this.s.promiseLibrary((fulfill, reject) => { + each(this, (err, doc) => { + if (err) { + reject(err); + return false; + } else if (doc == null) { + fulfill(null); + return false; + } else { + iterator(doc); + return true; + } + }); + }); + } + } + + /** + * Set the ReadPreference for the cursor. + * @method + * @param {(string|ReadPreference)} readPreference The new read preference for the cursor. + * @throws {MongoError} + * @return {Cursor} + */ + setReadPreference(readPreference) { + if (this.s.state !== CursorState.INIT) { + throw MongoError.create({ + message: 'cannot change cursor readPreference after cursor has been accessed', + driver: true + }); + } + + if (readPreference instanceof ReadPreference) { + this.options.readPreference = readPreference; + } else if (typeof readPreference === 'string') { + this.options.readPreference = new ReadPreference(readPreference); + } else { + throw new TypeError('Invalid read preference: ' + readPreference); + } + + return this; + } + + /** + * The callback format for results + * @callback Cursor~toArrayResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {object[]} documents All the documents the satisfy the cursor. + */ + + /** + * Returns an array of documents. The caller is responsible for making sure that there + * is enough memory to store the results. Note that the array only contains partial + * results when this cursor had been previously accessed. In that case, + * cursor.rewind() can be used to reset the cursor. + * @method + * @param {Cursor~toArrayResultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ + toArray(callback) { + if (this.options.tailable) { + throw MongoError.create({ + message: 'Tailable cursor cannot be converted to array', + driver: true + }); + } + + const toArrayOperation = new ToArrayOperation(this); + + return executeOperation(this.topology, toArrayOperation, callback); + } + + /** + * The callback format for results + * @callback Cursor~countResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {number} count The count of documents. + */ + + /** + * Get the count of documents for this cursor + * @method + * @param {boolean} [applySkipLimit=true] Should the count command apply limit and skip settings on the cursor or in the passed in options. + * @param {object} [options] Optional settings. + * @param {number} [options.skip] The number of documents to skip. + * @param {number} [options.limit] The maximum amounts to count before aborting. + * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query. + * @param {string} [options.hint] An index name hint for the query. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {Cursor~countResultCallback} [callback] The result callback. + * @return {Promise} returns Promise if no callback passed + */ + count(applySkipLimit, opts, callback) { + if (this.cmd.query == null) + throw MongoError.create({ + message: 'count can only be used with find command', + driver: true + }); + if (typeof opts === 'function') (callback = opts), (opts = {}); + opts = opts || {}; + + if (typeof applySkipLimit === 'function') { + callback = applySkipLimit; + applySkipLimit = true; + } + + if (this.cursorState.session) { + opts = Object.assign({}, opts, { session: this.cursorState.session }); + } + + const countOperation = new CountOperation(this, applySkipLimit, opts); + + return executeOperation(this.topology, countOperation, callback); + } + + /** + * Close the cursor, sending a KillCursor command and emitting close. + * @method + * @param {object} [options] Optional settings. + * @param {boolean} [options.skipKillCursors] Bypass calling killCursors when closing the cursor. + * @param {Cursor~resultCallback} [callback] The result callback. + * @return {Promise} returns Promise if no callback passed + */ + close(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = Object.assign({}, { skipKillCursors: false }, options); + + this.s.state = CursorState.CLOSED; + if (!options.skipKillCursors) { + // Kill the cursor + this.kill(); + } + + const completeClose = () => { + // Emit the close event for the cursor + this.emit('close'); + + // Callback if provided + if (typeof callback === 'function') { + return handleCallback(callback, null, this); + } + + // Return a Promise + return new this.s.promiseLibrary(resolve => { + resolve(); + }); + }; + + if (this.cursorState.session) { + if (typeof callback === 'function') { + return this._endSession(() => completeClose()); + } + + return new this.s.promiseLibrary(resolve => { + this._endSession(() => completeClose().then(resolve)); + }); + } + + return completeClose(); + } + + /** + * Map all documents using the provided function + * @method + * @param {function} [transform] The mapping transformation method. + * @return {Cursor} + */ + map(transform) { + if (this.cursorState.transforms && this.cursorState.transforms.doc) { + const oldTransform = this.cursorState.transforms.doc; + this.cursorState.transforms.doc = doc => { + return transform(oldTransform(doc)); + }; + } else { + this.cursorState.transforms = { doc: transform }; + } + + return this; + } + + /** + * Is the cursor closed + * @method + * @return {boolean} + */ + isClosed() { + return this.isDead(); + } + + destroy(err) { + if (err) this.emit('error', err); + this.pause(); + this.close(); + } + + /** + * Return a modified Readable stream including a possible transform method. + * @method + * @param {object} [options] Optional settings. + * @param {function} [options.transform] A transformation method applied to each document emitted by the stream. + * @return {Cursor} + * TODO: replace this method with transformStream in next major release + */ + stream(options) { + this.cursorState.streamOptions = options || {}; + return this; + } + + /** + * Return a modified Readable stream that applies a given transform function, if supplied. If none supplied, + * returns a stream of unmodified docs. + * @method + * @param {object} [options] Optional settings. + * @param {function} [options.transform] A transformation method applied to each document emitted by the stream. + * @return {stream} + */ + transformStream(options) { + const streamOptions = options || {}; + if (typeof streamOptions.transform === 'function') { + const stream = new Transform({ + objectMode: true, + transform: function(chunk, encoding, callback) { + this.push(streamOptions.transform(chunk)); + callback(); + } + }); + + return this.pipe(stream); + } + + return this.pipe(new PassThrough({ objectMode: true })); + } + + /** + * Execute the explain for the cursor + * @method + * @param {Cursor~resultCallback} [callback] The result callback. + * @return {Promise} returns Promise if no callback passed + */ + explain(callback) { + // NOTE: the next line includes a special case for operations which do not + // subclass `CommandOperationV2`. To be removed asap. + if (this.operation && this.operation.cmd == null) { + this.operation.options.explain = true; + this.operation.fullResponse = false; + return executeOperation(this.topology, this.operation, callback); + } + + this.cmd.explain = true; + + // Do we have a readConcern + if (this.cmd.readConcern) { + delete this.cmd['readConcern']; + } + + const explainOperation = new ExplainOperation(this); + + return executeOperation(this.topology, explainOperation, callback); + } + + /** + * Return the cursor logger + * @method + * @return {Logger} return the cursor logger + * @ignore + */ + getLogger() { + return this.logger; + } +} + +/** + * Cursor stream data event, fired for each document in the cursor. + * + * @event Cursor#data + * @type {object} + */ + +/** + * Cursor stream end event + * + * @event Cursor#end + * @type {null} + */ + +/** + * Cursor stream close event + * + * @event Cursor#close + * @type {null} + */ + +/** + * Cursor stream readable event + * + * @event Cursor#readable + * @type {null} + */ + +// aliases +Cursor.prototype.maxTimeMs = Cursor.prototype.maxTimeMS; + +// deprecated methods +deprecate(Cursor.prototype.each, 'Cursor.each is deprecated. Use Cursor.forEach instead.'); +deprecate( + Cursor.prototype.maxScan, + 'Cursor.maxScan is deprecated, and will be removed in a later version' +); + +deprecate( + Cursor.prototype.snapshot, + 'Cursor Snapshot is deprecated, and will be removed in a later version' +); + +/** + * The read() method pulls some data out of the internal buffer and returns it. If there is no data available, then it will return null. + * @function external:Readable#read + * @param {number} size Optional argument to specify how much data to read. + * @return {(String | Buffer | null)} + */ + +/** + * Call this function to cause the stream to return strings of the specified encoding instead of Buffer objects. + * @function external:Readable#setEncoding + * @param {string} encoding The encoding to use. + * @return {null} + */ + +/** + * This method will cause the readable stream to resume emitting data events. + * @function external:Readable#resume + * @return {null} + */ + +/** + * This method will cause a stream in flowing-mode to stop emitting data events. Any data that becomes available will remain in the internal buffer. + * @function external:Readable#pause + * @return {null} + */ + +/** + * This method pulls all the data out of a readable stream, and writes it to the supplied destination, automatically managing the flow so that the destination is not overwhelmed by a fast readable stream. + * @function external:Readable#pipe + * @param {Writable} destination The destination for writing data + * @param {object} [options] Pipe options + * @return {null} + */ + +/** + * This method will remove the hooks set up for a previous pipe() call. + * @function external:Readable#unpipe + * @param {Writable} [destination] The destination for writing data + * @return {null} + */ + +/** + * This is useful in certain cases where a stream is being consumed by a parser, which needs to "un-consume" some data that it has optimistically pulled out of the source, so that the stream can be passed on to some other party. + * @function external:Readable#unshift + * @param {(Buffer|string)} chunk Chunk of data to unshift onto the read queue. + * @return {null} + */ + +/** + * Versions of Node prior to v0.10 had streams that did not implement the entire Streams API as it is today. (See "Compatibility" below for more information.) + * @function external:Readable#wrap + * @param {Stream} stream An "old style" readable stream. + * @return {null} + */ + +module.exports = Cursor; diff --git a/scripts/node_modules/mongodb/lib/db.js b/scripts/node_modules/mongodb/lib/db.js new file mode 100644 index 00000000..5e68734a --- /dev/null +++ b/scripts/node_modules/mongodb/lib/db.js @@ -0,0 +1,1029 @@ +'use strict'; + +const EventEmitter = require('events').EventEmitter; +const inherits = require('util').inherits; +const getSingleProperty = require('./utils').getSingleProperty; +const CommandCursor = require('./command_cursor'); +const handleCallback = require('./utils').handleCallback; +const filterOptions = require('./utils').filterOptions; +const toError = require('./utils').toError; +const ReadPreference = require('./core').ReadPreference; +const MongoError = require('./core').MongoError; +const ObjectID = require('./core').ObjectID; +const Logger = require('./core').Logger; +const Collection = require('./collection'); +const mergeOptionsAndWriteConcern = require('./utils').mergeOptionsAndWriteConcern; +const executeLegacyOperation = require('./utils').executeLegacyOperation; +const resolveReadPreference = require('./utils').resolveReadPreference; +const ChangeStream = require('./change_stream'); +const deprecate = require('util').deprecate; +const deprecateOptions = require('./utils').deprecateOptions; +const MongoDBNamespace = require('./utils').MongoDBNamespace; +const CONSTANTS = require('./constants'); +const WriteConcern = require('./write_concern'); +const ReadConcern = require('./read_concern'); +const AggregationCursor = require('./aggregation_cursor'); + +// Operations +const createListener = require('./operations/db_ops').createListener; +const ensureIndex = require('./operations/db_ops').ensureIndex; +const evaluate = require('./operations/db_ops').evaluate; +const profilingInfo = require('./operations/db_ops').profilingInfo; +const validateDatabaseName = require('./operations/db_ops').validateDatabaseName; + +const AggregateOperation = require('./operations/aggregate'); +const AddUserOperation = require('./operations/add_user'); +const CollectionsOperation = require('./operations/collections'); +const CommandOperation = require('./operations/command'); +const CreateCollectionOperation = require('./operations/create_collection'); +const CreateIndexOperation = require('./operations/create_index'); +const DropCollectionOperation = require('./operations/drop').DropCollectionOperation; +const DropDatabaseOperation = require('./operations/drop').DropDatabaseOperation; +const ExecuteDbAdminCommandOperation = require('./operations/execute_db_admin_command'); +const IndexInformationOperation = require('./operations/index_information'); +const ListCollectionsOperation = require('./operations/list_collections'); +const ProfilingLevelOperation = require('./operations/profiling_level'); +const RemoveUserOperation = require('./operations/remove_user'); +const RenameOperation = require('./operations/rename'); +const SetProfilingLevelOperation = require('./operations/set_profiling_level'); + +const executeOperation = require('./operations/execute_operation'); + +/** + * @fileOverview The **Db** class is a class that represents a MongoDB Database. + * + * @example + * const MongoClient = require('mongodb').MongoClient; + * // Connection url + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, client) { + * // Select the database by name + * const testDb = client.db(dbName); + * client.close(); + * }); + */ + +// Allowed parameters +const legalOptionNames = [ + 'w', + 'wtimeout', + 'fsync', + 'j', + 'readPreference', + 'readPreferenceTags', + 'native_parser', + 'forceServerObjectId', + 'pkFactory', + 'serializeFunctions', + 'raw', + 'bufferMaxEntries', + 'authSource', + 'ignoreUndefined', + 'promoteLongs', + 'promiseLibrary', + 'readConcern', + 'retryMiliSeconds', + 'numberOfRetries', + 'parentDb', + 'noListener', + 'loggerLevel', + 'logger', + 'promoteBuffers', + 'promoteLongs', + 'promoteValues', + 'compression', + 'retryWrites' +]; + +/** + * Creates a new Db instance + * @class + * @param {string} databaseName The name of the database this instance represents. + * @param {(Server|ReplSet|Mongos)} topology The server topology for the database. + * @param {object} [options] Optional settings. + * @param {string} [options.authSource] If the database authentication is dependent on another databaseName. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. + * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution. + * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. + * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. + * @param {number} [options.bufferMaxEntries=-1] Sets a cap on how many operations the driver will buffer up before giving up on getting a working connection, default is -1 which is unlimited. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {object} [options.pkFactory] A primary key factory object for generation of custom _id keys. + * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {object} [options.readConcern] Specify a read concern for the collection. (only MongoDB 3.2 or higher supported) + * @param {ReadConcernLevel} [options.readConcern.level='local'] Specify a read concern level for the collection operations (only MongoDB 3.2 or higher supported) + * @property {(Server|ReplSet|Mongos)} serverConfig Get the current db topology. + * @property {number} bufferMaxEntries Current bufferMaxEntries value for the database + * @property {string} databaseName The name of the database this instance represents. + * @property {object} options The options associated with the db instance. + * @property {boolean} native_parser The current value of the parameter native_parser. + * @property {boolean} slaveOk The current slaveOk value for the db instance. + * @property {object} writeConcern The current write concern values. + * @property {object} topology Access the topology object (single server, replicaset or mongos). + * @fires Db#close + * @fires Db#reconnect + * @fires Db#error + * @fires Db#timeout + * @fires Db#parseError + * @fires Db#fullsetup + * @return {Db} a Db instance. + */ +function Db(databaseName, topology, options) { + options = options || {}; + if (!(this instanceof Db)) return new Db(databaseName, topology, options); + EventEmitter.call(this); + + // Get the promiseLibrary + const promiseLibrary = options.promiseLibrary || Promise; + + // Filter the options + options = filterOptions(options, legalOptionNames); + + // Ensure we put the promiseLib in the options + options.promiseLibrary = promiseLibrary; + + // Internal state of the db object + this.s = { + // DbCache + dbCache: {}, + // Children db's + children: [], + // Topology + topology: topology, + // Options + options: options, + // Logger instance + logger: Logger('Db', options), + // Get the bson parser + bson: topology ? topology.bson : null, + // Unpack read preference + readPreference: ReadPreference.fromOptions(options), + // Set buffermaxEntries + bufferMaxEntries: typeof options.bufferMaxEntries === 'number' ? options.bufferMaxEntries : -1, + // Parent db (if chained) + parentDb: options.parentDb || null, + // Set up the primary key factory or fallback to ObjectID + pkFactory: options.pkFactory || ObjectID, + // Get native parser + nativeParser: options.nativeParser || options.native_parser, + // Promise library + promiseLibrary: promiseLibrary, + // No listener + noListener: typeof options.noListener === 'boolean' ? options.noListener : false, + // ReadConcern + readConcern: ReadConcern.fromOptions(options), + writeConcern: WriteConcern.fromOptions(options), + // Namespace + namespace: new MongoDBNamespace(databaseName) + }; + + // Ensure we have a valid db name + validateDatabaseName(databaseName); + + // Add a read Only property + getSingleProperty(this, 'serverConfig', this.s.topology); + getSingleProperty(this, 'bufferMaxEntries', this.s.bufferMaxEntries); + getSingleProperty(this, 'databaseName', this.s.namespace.db); + + // This is a child db, do not register any listeners + if (options.parentDb) return; + if (this.s.noListener) return; + + // Add listeners + topology.on('error', createListener(this, 'error', this)); + topology.on('timeout', createListener(this, 'timeout', this)); + topology.on('close', createListener(this, 'close', this)); + topology.on('parseError', createListener(this, 'parseError', this)); + topology.once('open', createListener(this, 'open', this)); + topology.once('fullsetup', createListener(this, 'fullsetup', this)); + topology.once('all', createListener(this, 'all', this)); + topology.on('reconnect', createListener(this, 'reconnect', this)); +} + +inherits(Db, EventEmitter); + +// Topology +Object.defineProperty(Db.prototype, 'topology', { + enumerable: true, + get: function() { + return this.s.topology; + } +}); + +// Options +Object.defineProperty(Db.prototype, 'options', { + enumerable: true, + get: function() { + return this.s.options; + } +}); + +// slaveOk specified +Object.defineProperty(Db.prototype, 'slaveOk', { + enumerable: true, + get: function() { + if ( + this.s.options.readPreference != null && + (this.s.options.readPreference !== 'primary' || + this.s.options.readPreference.mode !== 'primary') + ) { + return true; + } + return false; + } +}); + +Object.defineProperty(Db.prototype, 'readConcern', { + enumerable: true, + get: function() { + return this.s.readConcern; + } +}); + +Object.defineProperty(Db.prototype, 'readPreference', { + enumerable: true, + get: function() { + if (this.s.readPreference == null) { + // TODO: check client + return ReadPreference.primary; + } + + return this.s.readPreference; + } +}); + +// get the write Concern +Object.defineProperty(Db.prototype, 'writeConcern', { + enumerable: true, + get: function() { + return this.s.writeConcern; + } +}); + +Object.defineProperty(Db.prototype, 'namespace', { + enumerable: true, + get: function() { + return this.s.namespace.toString(); + } +}); + +/** + * Execute a command + * @method + * @param {object} command The command hash + * @param {object} [options] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.command = function(command, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = Object.assign({}, options); + + const commandOperation = new CommandOperation(this, options, null, command); + + return executeOperation(this.s.topology, commandOperation, callback); +}; + +/** + * Execute an aggregation framework pipeline against the database, needs MongoDB >= 3.6 + * @method + * @param {object} [pipeline=[]] Array containing all the aggregation framework commands for the execution. + * @param {object} [options] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {object} [options.cursor] Return the query as cursor, on 2.6 > it returns as a real cursor on pre 2.6 it returns as an emulated cursor. + * @param {number} [options.cursor.batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. + * @param {boolean} [options.explain=false] Explain returns the aggregation execution plan (requires mongodb 2.6 >). + * @param {boolean} [options.allowDiskUse=false] allowDiskUse lets the server know if it can use disk to store temporary results for the aggregation (requires mongodb 2.6 >). + * @param {number} [options.maxTimeMS] maxTimeMS specifies a cumulative time limit in milliseconds for processing operations on the cursor. MongoDB interrupts the operation at the earliest following interrupt point. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. + * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution. + * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. + * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. + * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). + * @param {string} [options.comment] Add a comment to an aggregation command + * @param {string|object} [options.hint] Add an index selection hint to an aggregation command + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Database~aggregationCallback} callback The command result callback + * @return {(null|AggregationCursor)} + */ +Db.prototype.aggregate = function(pipeline, options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + + // If we have no options or callback we are doing + // a cursor based aggregation + if (options == null && callback == null) { + options = {}; + } + + const cursor = new AggregationCursor( + this.s.topology, + new AggregateOperation(this, pipeline, options), + options + ); + + // TODO: remove this when NODE-2074 is resolved + if (typeof callback === 'function') { + callback(null, cursor); + return; + } + + return cursor; +}; + +/** + * Return the Admin db instance + * @method + * @return {Admin} return the new Admin db instance + */ +Db.prototype.admin = function() { + const Admin = require('./admin'); + + return new Admin(this, this.s.topology, this.s.promiseLibrary); +}; + +/** + * The callback format for the collection method, must be used if strict is specified + * @callback Db~collectionResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection} collection The collection instance. + */ + +/** + * The callback format for an aggregation call + * @callback Database~aggregationCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {AggregationCursor} cursor The cursor if the aggregation command was executed successfully. + */ + +const collectionKeys = [ + 'pkFactory', + 'readPreference', + 'serializeFunctions', + 'strict', + 'readConcern', + 'ignoreUndefined', + 'promoteValues', + 'promoteBuffers', + 'promoteLongs' +]; + +/** + * Fetch a specific collection (containing the actual collection information). If the application does not use strict mode you + * can use it without a callback in the following way: `const collection = db.collection('mycollection');` + * + * @method + * @param {string} name the collection name we wish to access. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. + * @param {object} [options.pkFactory] A primary key factory object for generation of custom _id keys. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {boolean} [options.strict=false] Returns an error if the collection does not exist + * @param {object} [options.readConcern] Specify a read concern for the collection. (only MongoDB 3.2 or higher supported) + * @param {ReadConcernLevel} [options.readConcern.level='local'] Specify a read concern level for the collection operations (only MongoDB 3.2 or higher supported) + * @param {Db~collectionResultCallback} [callback] The collection result callback + * @return {Collection} return the new Collection instance if not in strict mode + */ +Db.prototype.collection = function(name, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + options = Object.assign({}, options); + + // Set the promise library + options.promiseLibrary = this.s.promiseLibrary; + + // If we have not set a collection level readConcern set the db level one + options.readConcern = options.readConcern + ? new ReadConcern(options.readConcern.level) + : this.readConcern; + + // Do we have ignoreUndefined set + if (this.s.options.ignoreUndefined) { + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + // Merge in all needed options and ensure correct writeConcern merging from db level + options = mergeOptionsAndWriteConcern(options, this.s.options, collectionKeys, true); + + // Execute + if (options == null || !options.strict) { + try { + const collection = new Collection( + this, + this.s.topology, + this.databaseName, + name, + this.s.pkFactory, + options + ); + if (callback) callback(null, collection); + return collection; + } catch (err) { + if (err instanceof MongoError && callback) return callback(err); + throw err; + } + } + + // Strict mode + if (typeof callback !== 'function') { + throw toError(`A callback is required in strict mode. While getting collection ${name}`); + } + + // Did the user destroy the topology + if (this.serverConfig && this.serverConfig.isDestroyed()) { + return callback(new MongoError('topology was destroyed')); + } + + const listCollectionOptions = Object.assign({}, options, { nameOnly: true }); + + // Strict mode + this.listCollections({ name: name }, listCollectionOptions).toArray((err, collections) => { + if (err != null) return handleCallback(callback, err, null); + if (collections.length === 0) + return handleCallback( + callback, + toError(`Collection ${name} does not exist. Currently in strict mode.`), + null + ); + + try { + return handleCallback( + callback, + null, + new Collection(this, this.s.topology, this.databaseName, name, this.s.pkFactory, options) + ); + } catch (err) { + return handleCallback(callback, err, null); + } + }); +}; + +/** + * Create a new collection on a server with the specified options. Use this to create capped collections. + * More information about command options available at https://docs.mongodb.com/manual/reference/command/create/ + * + * @method + * @param {string} name the collection name we wish to access. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. + * @param {object} [options.pkFactory] A primary key factory object for generation of custom _id keys. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {boolean} [options.strict=false] Returns an error if the collection does not exist + * @param {boolean} [options.capped=false] Create a capped collection. + * @param {boolean} [options.autoIndexId=true] DEPRECATED: Create an index on the _id field of the document, True by default on MongoDB 2.6 - 3.0 + * @param {number} [options.size] The size of the capped collection in bytes. + * @param {number} [options.max] The maximum number of documents in the capped collection. + * @param {number} [options.flags] Optional. Available for the MMAPv1 storage engine only to set the usePowerOf2Sizes and the noPadding flag. + * @param {object} [options.storageEngine] Allows users to specify configuration to the storage engine on a per-collection basis when creating a collection on MongoDB 3.0 or higher. + * @param {object} [options.validator] Allows users to specify validation rules or expressions for the collection. For more information, see Document Validation on MongoDB 3.2 or higher. + * @param {string} [options.validationLevel] Determines how strictly MongoDB applies the validation rules to existing documents during an update on MongoDB 3.2 or higher. + * @param {string} [options.validationAction] Determines whether to error on invalid documents or just warn about the violations but allow invalid documents to be inserted on MongoDB 3.2 or higher. + * @param {object} [options.indexOptionDefaults] Allows users to specify a default configuration for indexes when creating a collection on MongoDB 3.2 or higher. + * @param {string} [options.viewOn] The name of the source collection or view from which to create the view. The name is not the full namespace of the collection or view; i.e. does not include the database name and implies the same database as the view to create on MongoDB 3.4 or higher. + * @param {array} [options.pipeline] An array that consists of the aggregation pipeline stage. Creates the view by applying the specified pipeline to the viewOn collection or view on MongoDB 3.4 or higher. + * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~collectionResultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.createCollection = deprecateOptions( + { + name: 'Db.createCollection', + deprecatedOptions: ['autoIndexId'], + optionsIndex: 1 + }, + function(name, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + options.promiseLibrary = options.promiseLibrary || this.s.promiseLibrary; + options.readConcern = options.readConcern + ? new ReadConcern(options.readConcern.level) + : this.readConcern; + const createCollectionOperation = new CreateCollectionOperation(this, name, options); + + return executeOperation(this.s.topology, createCollectionOperation, callback); + } +); + +/** + * Get all the db statistics. + * + * @method + * @param {object} [options] Optional settings. + * @param {number} [options.scale] Divide the returned sizes by scale value. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~resultCallback} [callback] The collection result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.stats = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + // Build command object + const commandObject = { dbStats: true }; + // Check if we have the scale value + if (options['scale'] != null) commandObject['scale'] = options['scale']; + + // If we have a readPreference set + if (options.readPreference == null && this.s.readPreference) { + options.readPreference = this.s.readPreference; + } + + const statsOperation = new CommandOperation(this, options, null, commandObject); + + // Execute the command + return executeOperation(this.s.topology, statsOperation, callback); +}; + +/** + * Get the list of all collection information for the specified db. + * + * @method + * @param {object} [filter={}] Query to filter collections by + * @param {object} [options] Optional settings. + * @param {boolean} [options.nameOnly=false] Since 4.0: If true, will only return the collection name in the response, and will omit additional info + * @param {number} [options.batchSize=1000] The batchSize for the returned command cursor or if pre 2.8 the systems batch collection + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {ClientSession} [options.session] optional session to use for this operation + * @return {CommandCursor} + */ +Db.prototype.listCollections = function(filter, options) { + filter = filter || {}; + options = options || {}; + + return new CommandCursor( + this.s.topology, + new ListCollectionsOperation(this, filter, options), + options + ); +}; + +/** + * Evaluate JavaScript on the server + * + * @method + * @param {Code} code JavaScript to execute on server. + * @param {(object|array)} parameters The parameters for the call. + * @param {object} [options] Optional settings. + * @param {boolean} [options.nolock=false] Tell MongoDB not to block on the evaluation of the javascript. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~resultCallback} [callback] The results callback + * @deprecated Eval is deprecated on MongoDB 3.2 and forward + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.eval = deprecate(function(code, parameters, options, callback) { + const args = Array.prototype.slice.call(arguments, 1); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + parameters = args.length ? args.shift() : parameters; + options = args.length ? args.shift() || {} : {}; + + return executeLegacyOperation(this.s.topology, evaluate, [ + this, + code, + parameters, + options, + callback + ]); +}, 'Db.eval is deprecated as of MongoDB version 3.2'); + +/** + * Rename a collection. + * + * @method + * @param {string} fromCollection Name of current collection to rename. + * @param {string} toCollection New name of of the collection. + * @param {object} [options] Optional settings. + * @param {boolean} [options.dropTarget=false] Drop the target name collection if it previously exists. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~collectionResultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.renameCollection = function(fromCollection, toCollection, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = Object.assign({}, options, { readPreference: ReadPreference.PRIMARY }); + + // Add return new collection + options.new_collection = true; + + const renameOperation = new RenameOperation( + this.collection(fromCollection), + toCollection, + options + ); + + return executeOperation(this.s.topology, renameOperation, callback); +}; + +/** + * Drop a collection from the database, removing it permanently. New accesses will create a new collection. + * + * @method + * @param {string} name Name of collection to drop + * @param {Object} [options] Optional settings + * @param {WriteConcern} [options.writeConcern] A full WriteConcern object + * @param {(number|string)} [options.w] The write concern + * @param {number} [options.wtimeout] The write concern timeout + * @param {boolean} [options.j] The journal write concern + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~resultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.dropCollection = function(name, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const dropCollectionOperation = new DropCollectionOperation(this, name, options); + + return executeOperation(this.s.topology, dropCollectionOperation, callback); +}; + +/** + * Drop a database, removing it permanently from the server. + * + * @method + * @param {Object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~resultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.dropDatabase = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const dropDatabaseOperation = new DropDatabaseOperation(this, options); + + return executeOperation(this.s.topology, dropDatabaseOperation, callback); +}; + +/** + * Fetch all collections for the current db. + * + * @method + * @param {Object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~collectionsResultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.collections = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const collectionsOperation = new CollectionsOperation(this, options); + + return executeOperation(this.s.topology, collectionsOperation, callback); +}; + +/** + * Runs a command on the database as admin. + * @method + * @param {object} command The command hash + * @param {object} [options] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.executeDbAdminCommand = function(selector, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + options.readPreference = resolveReadPreference(this, options); + + const executeDbAdminCommandOperation = new ExecuteDbAdminCommandOperation( + this, + selector, + options + ); + + return executeOperation(this.s.topology, executeDbAdminCommandOperation, callback); +}; + +/** + * Creates an index on the db and collection. + * @method + * @param {string} name Name of the collection to create the index on. + * @param {(string|object)} fieldOrSpec Defines the index. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.unique=false] Creates an unique index. + * @param {boolean} [options.sparse=false] Creates a sparse index. + * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. + * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value + * @param {number} [options.min] For geospatial indexes set the lower bound for the co-ordinates. + * @param {number} [options.max] For geospatial indexes set the high bound for the co-ordinates. + * @param {number} [options.v] Specify the format version of the indexes. + * @param {number} [options.expireAfterSeconds] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) + * @param {string} [options.name] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) + * @param {object} [options.partialFilterExpression] Creates a partial index based on the given filter object (MongoDB 3.2 or higher) + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.createIndex = function(name, fieldOrSpec, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options ? Object.assign({}, options) : {}; + + const createIndexOperation = new CreateIndexOperation(this, name, fieldOrSpec, options); + + return executeOperation(this.s.topology, createIndexOperation, callback); +}; + +/** + * Ensures that an index exists, if it does not it creates it + * @method + * @deprecated since version 2.0 + * @param {string} name The index name + * @param {(string|object)} fieldOrSpec Defines the index. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.unique=false] Creates an unique index. + * @param {boolean} [options.sparse=false] Creates a sparse index. + * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. + * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value + * @param {number} [options.min] For geospatial indexes set the lower bound for the co-ordinates. + * @param {number} [options.max] For geospatial indexes set the high bound for the co-ordinates. + * @param {number} [options.v] Specify the format version of the indexes. + * @param {number} [options.expireAfterSeconds] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) + * @param {number} [options.name] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.ensureIndex = deprecate(function(name, fieldOrSpec, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeLegacyOperation(this.s.topology, ensureIndex, [ + this, + name, + fieldOrSpec, + options, + callback + ]); +}, 'Db.ensureIndex is deprecated as of MongoDB version 3.0 / driver version 2.0'); + +Db.prototype.addChild = function(db) { + if (this.s.parentDb) return this.s.parentDb.addChild(db); + this.s.children.push(db); +}; + +/** + * Add a user to the database. + * @method + * @param {string} username The username. + * @param {string} password The password. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {object} [options.customData] Custom data associated with the user (only Mongodb 2.6 or higher) + * @param {object[]} [options.roles] Roles associated with the created user (only Mongodb 2.6 or higher) + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.addUser = function(username, password, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + // Special case where there is no password ($external users) + if (typeof username === 'string' && password != null && typeof password === 'object') { + options = password; + password = null; + } + + const addUserOperation = new AddUserOperation(this, username, password, options); + + return executeOperation(this.s.topology, addUserOperation, callback); +}; + +/** + * Remove a user from a database + * @method + * @param {string} username The username. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.removeUser = function(username, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const removeUserOperation = new RemoveUserOperation(this, username, options); + + return executeOperation(this.s.topology, removeUserOperation, callback); +}; + +/** + * Set the current profiling level of MongoDB + * + * @param {string} level The new profiling level (off, slow_only, all). + * @param {Object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~resultCallback} [callback] The command result callback. + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.setProfilingLevel = function(level, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const setProfilingLevelOperation = new SetProfilingLevelOperation(this, level, options); + + return executeOperation(this.s.topology, setProfilingLevelOperation, callback); +}; + +/** + * Retrieve the current profiling information for MongoDB + * + * @param {Object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~resultCallback} [callback] The command result callback. + * @return {Promise} returns Promise if no callback passed + * @deprecated Query the system.profile collection directly. + */ +Db.prototype.profilingInfo = deprecate(function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeLegacyOperation(this.s.topology, profilingInfo, [this, options, callback]); +}, 'Db.profilingInfo is deprecated. Query the system.profile collection directly.'); + +/** + * Retrieve the current profiling Level for MongoDB + * + * @param {Object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.profilingLevel = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const profilingLevelOperation = new ProfilingLevelOperation(this, options); + + return executeOperation(this.s.topology, profilingLevelOperation, callback); +}; + +/** + * Retrieves this collections index info. + * @method + * @param {string} name The name of the collection. + * @param {object} [options] Optional settings. + * @param {boolean} [options.full=false] Returns the full raw index information. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.indexInformation = function(name, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + const indexInformationOperation = new IndexInformationOperation(this, name, options); + + return executeOperation(this.s.topology, indexInformationOperation, callback); +}; + +/** + * Unref all sockets + * @method + */ +Db.prototype.unref = function() { + this.s.topology.unref(); +}; + +/** + * Create a new Change Stream, watching for new changes (insertions, updates, replacements, deletions, and invalidations) in this database. Will ignore all changes to system collections. + * @method + * @since 3.1.0 + * @param {Array} [pipeline] An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents. + * @param {object} [options] Optional settings + * @param {string} [options.fullDocument='default'] Allowed values: ‘default’, ‘updateLookup’. When set to ‘updateLookup’, the change stream will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred. + * @param {object} [options.resumeAfter] Specifies the logical starting point for the new change stream. This should be the _id field from a previously returned change stream document. + * @param {number} [options.maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a change stream query + * @param {number} [options.batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. + * @param {object} [options.collation] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. + * @param {ReadPreference} [options.readPreference] The read preference. Defaults to the read preference of the database. See {@link https://docs.mongodb.com/manual/reference/read-preference|read preference documentation}. + * @param {Timestamp} [options.startAtOperationTime] receive change events that occur after the specified timestamp + * @param {ClientSession} [options.session] optional session to use for this operation + * @return {ChangeStream} a ChangeStream instance. + */ +Db.prototype.watch = function(pipeline, options) { + pipeline = pipeline || []; + options = options || {}; + + // Allow optionally not specifying a pipeline + if (!Array.isArray(pipeline)) { + options = pipeline; + pipeline = []; + } + + return new ChangeStream(this, pipeline, options); +}; + +/** + * Return the db logger + * @method + * @return {Logger} return the db logger + * @ignore + */ +Db.prototype.getLogger = function() { + return this.s.logger; +}; + +/** + * Db close event + * + * Emitted after a socket closed against a single server or mongos proxy. + * + * @event Db#close + * @type {MongoError} + */ + +/** + * Db reconnect event + * + * * Server: Emitted when the driver has reconnected and re-authenticated. + * * ReplicaSet: N/A + * * Mongos: Emitted when the driver reconnects and re-authenticates successfully against a Mongos. + * + * @event Db#reconnect + * @type {object} + */ + +/** + * Db error event + * + * Emitted after an error occurred against a single server or mongos proxy. + * + * @event Db#error + * @type {MongoError} + */ + +/** + * Db timeout event + * + * Emitted after a socket timeout occurred against a single server or mongos proxy. + * + * @event Db#timeout + * @type {MongoError} + */ + +/** + * Db parseError event + * + * The parseError event is emitted if the driver detects illegal or corrupt BSON being received from the server. + * + * @event Db#parseError + * @type {MongoError} + */ + +/** + * Db fullsetup event, emitted when all servers in the topology have been connected to at start up time. + * + * * Server: Emitted when the driver has connected to the single server and has authenticated. + * * ReplSet: Emitted after the driver has attempted to connect to all replicaset members. + * * Mongos: Emitted after the driver has attempted to connect to all mongos proxies. + * + * @event Db#fullsetup + * @type {Db} + */ + +// Constants +Db.SYSTEM_NAMESPACE_COLLECTION = CONSTANTS.SYSTEM_NAMESPACE_COLLECTION; +Db.SYSTEM_INDEX_COLLECTION = CONSTANTS.SYSTEM_INDEX_COLLECTION; +Db.SYSTEM_PROFILE_COLLECTION = CONSTANTS.SYSTEM_PROFILE_COLLECTION; +Db.SYSTEM_USER_COLLECTION = CONSTANTS.SYSTEM_USER_COLLECTION; +Db.SYSTEM_COMMAND_COLLECTION = CONSTANTS.SYSTEM_COMMAND_COLLECTION; +Db.SYSTEM_JS_COLLECTION = CONSTANTS.SYSTEM_JS_COLLECTION; + +module.exports = Db; diff --git a/scripts/node_modules/mongodb/lib/dynamic_loaders.js b/scripts/node_modules/mongodb/lib/dynamic_loaders.js new file mode 100644 index 00000000..c4610023 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/dynamic_loaders.js @@ -0,0 +1,32 @@ +'use strict'; + +let collection; +let cursor; +let db; + +function loadCollection() { + if (!collection) { + collection = require('./collection'); + } + return collection; +} + +function loadCursor() { + if (!cursor) { + cursor = require('./cursor'); + } + return cursor; +} + +function loadDb() { + if (!db) { + db = require('./db'); + } + return db; +} + +module.exports = { + loadCollection, + loadCursor, + loadDb +}; diff --git a/scripts/node_modules/mongodb/lib/error.js b/scripts/node_modules/mongodb/lib/error.js new file mode 100644 index 00000000..4d104e9b --- /dev/null +++ b/scripts/node_modules/mongodb/lib/error.js @@ -0,0 +1,45 @@ +'use strict'; + +const MongoNetworkError = require('./core').MongoNetworkError; +const mongoErrorContextSymbol = require('./core').mongoErrorContextSymbol; + +const GET_MORE_NON_RESUMABLE_CODES = new Set([ + 136, // CappedPositionLost + 237, // CursorKilled + 11601 // Interrupted +]); + +// From spec@https://github.com/mongodb/specifications/blob/7a2e93d85935ee4b1046a8d2ad3514c657dc74fa/source/change-streams/change-streams.rst#resumable-error: +// +// An error is considered resumable if it meets any of the following criteria: +// - any error encountered which is not a server error (e.g. a timeout error or network error) +// - any server error response from a getMore command excluding those containing the error label +// NonRetryableChangeStreamError and those containing the following error codes: +// - Interrupted: 11601 +// - CappedPositionLost: 136 +// - CursorKilled: 237 +// +// An error on an aggregate command is not a resumable error. Only errors on a getMore command may be considered resumable errors. + +function isGetMoreError(error) { + if (error[mongoErrorContextSymbol]) { + return error[mongoErrorContextSymbol].isGetMore; + } +} + +function isResumableError(error) { + if (!isGetMoreError(error)) { + return false; + } + + if (error instanceof MongoNetworkError) { + return true; + } + + return !( + GET_MORE_NON_RESUMABLE_CODES.has(error.code) || + error.hasErrorLabel('NonRetryableChangeStreamError') + ); +} + +module.exports = { GET_MORE_NON_RESUMABLE_CODES, isResumableError }; diff --git a/scripts/node_modules/mongodb/lib/gridfs-stream/download.js b/scripts/node_modules/mongodb/lib/gridfs-stream/download.js new file mode 100644 index 00000000..dfb1de57 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/gridfs-stream/download.js @@ -0,0 +1,421 @@ +'use strict'; + +var stream = require('stream'), + util = require('util'); + +module.exports = GridFSBucketReadStream; + +/** + * A readable stream that enables you to read buffers from GridFS. + * + * Do not instantiate this class directly. Use `openDownloadStream()` instead. + * + * @class + * @param {Collection} chunks Handle for chunks collection + * @param {Collection} files Handle for files collection + * @param {Object} readPreference The read preference to use + * @param {Object} filter The query to use to find the file document + * @param {Object} [options] Optional settings. + * @param {Number} [options.sort] Optional sort for the file find query + * @param {Number} [options.skip] Optional skip for the file find query + * @param {Number} [options.start] Optional 0-based offset in bytes to start streaming from + * @param {Number} [options.end] Optional 0-based offset in bytes to stop streaming before + * @fires GridFSBucketReadStream#error + * @fires GridFSBucketReadStream#file + * @return {GridFSBucketReadStream} a GridFSBucketReadStream instance. + */ + +function GridFSBucketReadStream(chunks, files, readPreference, filter, options) { + this.s = { + bytesRead: 0, + chunks: chunks, + cursor: null, + expected: 0, + files: files, + filter: filter, + init: false, + expectedEnd: 0, + file: null, + options: options, + readPreference: readPreference + }; + + stream.Readable.call(this); +} + +util.inherits(GridFSBucketReadStream, stream.Readable); + +/** + * An error occurred + * + * @event GridFSBucketReadStream#error + * @type {Error} + */ + +/** + * Fires when the stream loaded the file document corresponding to the + * provided id. + * + * @event GridFSBucketReadStream#file + * @type {object} + */ + +/** + * Emitted when a chunk of data is available to be consumed. + * + * @event GridFSBucketReadStream#data + * @type {object} + */ + +/** + * Fired when the stream is exhausted (no more data events). + * + * @event GridFSBucketReadStream#end + * @type {object} + */ + +/** + * Fired when the stream is exhausted and the underlying cursor is killed + * + * @event GridFSBucketReadStream#close + * @type {object} + */ + +/** + * Reads from the cursor and pushes to the stream. + * @method + */ + +GridFSBucketReadStream.prototype._read = function() { + var _this = this; + if (this.destroyed) { + return; + } + + waitForFile(_this, function() { + doRead(_this); + }); +}; + +/** + * Sets the 0-based offset in bytes to start streaming from. Throws + * an error if this stream has entered flowing mode + * (e.g. if you've already called `on('data')`) + * @method + * @param {Number} start Offset in bytes to start reading at + * @return {GridFSBucketReadStream} + */ + +GridFSBucketReadStream.prototype.start = function(start) { + throwIfInitialized(this); + this.s.options.start = start; + return this; +}; + +/** + * Sets the 0-based offset in bytes to start streaming from. Throws + * an error if this stream has entered flowing mode + * (e.g. if you've already called `on('data')`) + * @method + * @param {Number} end Offset in bytes to stop reading at + * @return {GridFSBucketReadStream} + */ + +GridFSBucketReadStream.prototype.end = function(end) { + throwIfInitialized(this); + this.s.options.end = end; + return this; +}; + +/** + * Marks this stream as aborted (will never push another `data` event) + * and kills the underlying cursor. Will emit the 'end' event, and then + * the 'close' event once the cursor is successfully killed. + * + * @method + * @param {GridFSBucket~errorCallback} [callback] called when the cursor is successfully closed or an error occurred. + * @fires GridFSBucketWriteStream#close + * @fires GridFSBucketWriteStream#end + */ + +GridFSBucketReadStream.prototype.abort = function(callback) { + var _this = this; + this.push(null); + this.destroyed = true; + if (this.s.cursor) { + this.s.cursor.close(function(error) { + _this.emit('close'); + callback && callback(error); + }); + } else { + if (!this.s.init) { + // If not initialized, fire close event because we will never + // get a cursor + _this.emit('close'); + } + callback && callback(); + } +}; + +/** + * @ignore + */ + +function throwIfInitialized(self) { + if (self.s.init) { + throw new Error('You cannot change options after the stream has entered' + 'flowing mode!'); + } +} + +/** + * @ignore + */ + +function doRead(_this) { + if (_this.destroyed) { + return; + } + + _this.s.cursor.next(function(error, doc) { + if (_this.destroyed) { + return; + } + if (error) { + return __handleError(_this, error); + } + if (!doc) { + _this.push(null); + + process.nextTick(() => { + _this.s.cursor.close(function(error) { + if (error) { + __handleError(_this, error); + return; + } + + _this.emit('close'); + }); + }); + + return; + } + + var bytesRemaining = _this.s.file.length - _this.s.bytesRead; + var expectedN = _this.s.expected++; + var expectedLength = Math.min(_this.s.file.chunkSize, bytesRemaining); + + if (doc.n > expectedN) { + var errmsg = 'ChunkIsMissing: Got unexpected n: ' + doc.n + ', expected: ' + expectedN; + return __handleError(_this, new Error(errmsg)); + } + + if (doc.n < expectedN) { + errmsg = 'ExtraChunk: Got unexpected n: ' + doc.n + ', expected: ' + expectedN; + return __handleError(_this, new Error(errmsg)); + } + + var buf = Buffer.isBuffer(doc.data) ? doc.data : doc.data.buffer; + + if (buf.length !== expectedLength) { + if (bytesRemaining <= 0) { + errmsg = 'ExtraChunk: Got unexpected n: ' + doc.n; + return __handleError(_this, new Error(errmsg)); + } + + errmsg = + 'ChunkIsWrongSize: Got unexpected length: ' + buf.length + ', expected: ' + expectedLength; + return __handleError(_this, new Error(errmsg)); + } + + _this.s.bytesRead += buf.length; + + if (buf.length === 0) { + return _this.push(null); + } + + var sliceStart = null; + var sliceEnd = null; + + if (_this.s.bytesToSkip != null) { + sliceStart = _this.s.bytesToSkip; + _this.s.bytesToSkip = 0; + } + + const atEndOfStream = expectedN === _this.s.expectedEnd - 1; + const bytesLeftToRead = _this.s.options.end - _this.s.bytesToSkip; + if (atEndOfStream && _this.s.bytesToTrim != null) { + sliceEnd = _this.s.file.chunkSize - _this.s.bytesToTrim; + } else if (_this.s.options.end && bytesLeftToRead < doc.data.length()) { + sliceEnd = bytesLeftToRead; + } + + if (sliceStart != null || sliceEnd != null) { + buf = buf.slice(sliceStart || 0, sliceEnd || buf.length); + } + + _this.push(buf); + }); +} + +/** + * @ignore + */ + +function init(self) { + var findOneOptions = {}; + if (self.s.readPreference) { + findOneOptions.readPreference = self.s.readPreference; + } + if (self.s.options && self.s.options.sort) { + findOneOptions.sort = self.s.options.sort; + } + if (self.s.options && self.s.options.skip) { + findOneOptions.skip = self.s.options.skip; + } + + self.s.files.findOne(self.s.filter, findOneOptions, function(error, doc) { + if (error) { + return __handleError(self, error); + } + if (!doc) { + var identifier = self.s.filter._id ? self.s.filter._id.toString() : self.s.filter.filename; + var errmsg = 'FileNotFound: file ' + identifier + ' was not found'; + var err = new Error(errmsg); + err.code = 'ENOENT'; + return __handleError(self, err); + } + + // If document is empty, kill the stream immediately and don't + // execute any reads + if (doc.length <= 0) { + self.push(null); + return; + } + + if (self.destroyed) { + // If user destroys the stream before we have a cursor, wait + // until the query is done to say we're 'closed' because we can't + // cancel a query. + self.emit('close'); + return; + } + + self.s.bytesToSkip = handleStartOption(self, doc, self.s.options); + + var filter = { files_id: doc._id }; + + // Currently (MongoDB 3.4.4) skip function does not support the index, + // it needs to retrieve all the documents first and then skip them. (CS-25811) + // As work around we use $gte on the "n" field. + if (self.s.options && self.s.options.start != null) { + var skip = Math.floor(self.s.options.start / doc.chunkSize); + if (skip > 0) { + filter['n'] = { $gte: skip }; + } + } + self.s.cursor = self.s.chunks.find(filter).sort({ n: 1 }); + + if (self.s.readPreference) { + self.s.cursor.setReadPreference(self.s.readPreference); + } + + self.s.expectedEnd = Math.ceil(doc.length / doc.chunkSize); + self.s.file = doc; + self.s.bytesToTrim = handleEndOption(self, doc, self.s.cursor, self.s.options); + self.emit('file', doc); + }); +} + +/** + * @ignore + */ + +function waitForFile(_this, callback) { + if (_this.s.file) { + return callback(); + } + + if (!_this.s.init) { + init(_this); + _this.s.init = true; + } + + _this.once('file', function() { + callback(); + }); +} + +/** + * @ignore + */ + +function handleStartOption(stream, doc, options) { + if (options && options.start != null) { + if (options.start > doc.length) { + throw new Error( + 'Stream start (' + + options.start + + ') must not be ' + + 'more than the length of the file (' + + doc.length + + ')' + ); + } + if (options.start < 0) { + throw new Error('Stream start (' + options.start + ') must not be ' + 'negative'); + } + if (options.end != null && options.end < options.start) { + throw new Error( + 'Stream start (' + + options.start + + ') must not be ' + + 'greater than stream end (' + + options.end + + ')' + ); + } + + stream.s.bytesRead = Math.floor(options.start / doc.chunkSize) * doc.chunkSize; + stream.s.expected = Math.floor(options.start / doc.chunkSize); + + return options.start - stream.s.bytesRead; + } +} + +/** + * @ignore + */ + +function handleEndOption(stream, doc, cursor, options) { + if (options && options.end != null) { + if (options.end > doc.length) { + throw new Error( + 'Stream end (' + + options.end + + ') must not be ' + + 'more than the length of the file (' + + doc.length + + ')' + ); + } + if (options.start < 0) { + throw new Error('Stream end (' + options.end + ') must not be ' + 'negative'); + } + + var start = options.start != null ? Math.floor(options.start / doc.chunkSize) : 0; + + cursor.limit(Math.ceil(options.end / doc.chunkSize) - start); + + stream.s.expectedEnd = Math.ceil(options.end / doc.chunkSize); + + return Math.ceil(options.end / doc.chunkSize) * doc.chunkSize - options.end; + } +} + +/** + * @ignore + */ + +function __handleError(_this, error) { + _this.emit('error', error); +} diff --git a/scripts/node_modules/mongodb/lib/gridfs-stream/index.js b/scripts/node_modules/mongodb/lib/gridfs-stream/index.js new file mode 100644 index 00000000..93b45ebf --- /dev/null +++ b/scripts/node_modules/mongodb/lib/gridfs-stream/index.js @@ -0,0 +1,358 @@ +'use strict'; + +var Emitter = require('events').EventEmitter; +var GridFSBucketReadStream = require('./download'); +var GridFSBucketWriteStream = require('./upload'); +var shallowClone = require('../utils').shallowClone; +var toError = require('../utils').toError; +var util = require('util'); +var executeLegacyOperation = require('../utils').executeLegacyOperation; + +var DEFAULT_GRIDFS_BUCKET_OPTIONS = { + bucketName: 'fs', + chunkSizeBytes: 255 * 1024 +}; + +module.exports = GridFSBucket; + +/** + * Constructor for a streaming GridFS interface + * @class + * @param {Db} db A db handle + * @param {object} [options] Optional settings. + * @param {string} [options.bucketName="fs"] The 'files' and 'chunks' collections will be prefixed with the bucket name followed by a dot. + * @param {number} [options.chunkSizeBytes=255 * 1024] Number of bytes stored in each chunk. Defaults to 255KB + * @param {object} [options.writeConcern] Optional write concern to be passed to write operations, for instance `{ w: 1 }` + * @param {object} [options.readPreference] Optional read preference to be passed to read operations + * @fires GridFSBucketWriteStream#index + * @return {GridFSBucket} + */ + +function GridFSBucket(db, options) { + Emitter.apply(this); + this.setMaxListeners(0); + + if (options && typeof options === 'object') { + options = shallowClone(options); + var keys = Object.keys(DEFAULT_GRIDFS_BUCKET_OPTIONS); + for (var i = 0; i < keys.length; ++i) { + if (!options[keys[i]]) { + options[keys[i]] = DEFAULT_GRIDFS_BUCKET_OPTIONS[keys[i]]; + } + } + } else { + options = DEFAULT_GRIDFS_BUCKET_OPTIONS; + } + + this.s = { + db: db, + options: options, + _chunksCollection: db.collection(options.bucketName + '.chunks'), + _filesCollection: db.collection(options.bucketName + '.files'), + checkedIndexes: false, + calledOpenUploadStream: false, + promiseLibrary: db.s.promiseLibrary || Promise + }; +} + +util.inherits(GridFSBucket, Emitter); + +/** + * When the first call to openUploadStream is made, the upload stream will + * check to see if it needs to create the proper indexes on the chunks and + * files collections. This event is fired either when 1) it determines that + * no index creation is necessary, 2) when it successfully creates the + * necessary indexes. + * + * @event GridFSBucket#index + * @type {Error} + */ + +/** + * Returns a writable stream (GridFSBucketWriteStream) for writing + * buffers to GridFS. The stream's 'id' property contains the resulting + * file's id. + * @method + * @param {string} filename The value of the 'filename' key in the files doc + * @param {object} [options] Optional settings. + * @param {number} [options.chunkSizeBytes] Optional overwrite this bucket's chunkSizeBytes for this file + * @param {object} [options.metadata] Optional object to store in the file document's `metadata` field + * @param {string} [options.contentType] Optional string to store in the file document's `contentType` field + * @param {array} [options.aliases] Optional array of strings to store in the file document's `aliases` field + * @param {boolean} [options.disableMD5=false] If true, disables adding an md5 field to file data + * @return {GridFSBucketWriteStream} + */ + +GridFSBucket.prototype.openUploadStream = function(filename, options) { + if (options) { + options = shallowClone(options); + } else { + options = {}; + } + if (!options.chunkSizeBytes) { + options.chunkSizeBytes = this.s.options.chunkSizeBytes; + } + return new GridFSBucketWriteStream(this, filename, options); +}; + +/** + * Returns a writable stream (GridFSBucketWriteStream) for writing + * buffers to GridFS for a custom file id. The stream's 'id' property contains the resulting + * file's id. + * @method + * @param {string|number|object} id A custom id used to identify the file + * @param {string} filename The value of the 'filename' key in the files doc + * @param {object} [options] Optional settings. + * @param {number} [options.chunkSizeBytes] Optional overwrite this bucket's chunkSizeBytes for this file + * @param {object} [options.metadata] Optional object to store in the file document's `metadata` field + * @param {string} [options.contentType] Optional string to store in the file document's `contentType` field + * @param {array} [options.aliases] Optional array of strings to store in the file document's `aliases` field + * @param {boolean} [options.disableMD5=false] If true, disables adding an md5 field to file data + * @return {GridFSBucketWriteStream} + */ + +GridFSBucket.prototype.openUploadStreamWithId = function(id, filename, options) { + if (options) { + options = shallowClone(options); + } else { + options = {}; + } + + if (!options.chunkSizeBytes) { + options.chunkSizeBytes = this.s.options.chunkSizeBytes; + } + + options.id = id; + + return new GridFSBucketWriteStream(this, filename, options); +}; + +/** + * Returns a readable stream (GridFSBucketReadStream) for streaming file + * data from GridFS. + * @method + * @param {ObjectId} id The id of the file doc + * @param {Object} [options] Optional settings. + * @param {Number} [options.start] Optional 0-based offset in bytes to start streaming from + * @param {Number} [options.end] Optional 0-based offset in bytes to stop streaming before + * @return {GridFSBucketReadStream} + */ + +GridFSBucket.prototype.openDownloadStream = function(id, options) { + var filter = { _id: id }; + options = { + start: options && options.start, + end: options && options.end + }; + + return new GridFSBucketReadStream( + this.s._chunksCollection, + this.s._filesCollection, + this.s.options.readPreference, + filter, + options + ); +}; + +/** + * Deletes a file with the given id + * @method + * @param {ObjectId} id The id of the file doc + * @param {GridFSBucket~errorCallback} [callback] + */ + +GridFSBucket.prototype.delete = function(id, callback) { + return executeLegacyOperation(this.s.db.s.topology, _delete, [this, id, callback], { + skipSessions: true + }); +}; + +/** + * @ignore + */ + +function _delete(_this, id, callback) { + _this.s._filesCollection.deleteOne({ _id: id }, function(error, res) { + if (error) { + return callback(error); + } + + _this.s._chunksCollection.deleteMany({ files_id: id }, function(error) { + if (error) { + return callback(error); + } + + // Delete orphaned chunks before returning FileNotFound + if (!res.result.n) { + var errmsg = 'FileNotFound: no file with id ' + id + ' found'; + return callback(new Error(errmsg)); + } + + callback(); + }); + }); +} + +/** + * Convenience wrapper around find on the files collection + * @method + * @param {Object} filter + * @param {Object} [options] Optional settings for cursor + * @param {number} [options.batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/find|find command documentation}. + * @param {number} [options.limit] Optional limit for cursor + * @param {number} [options.maxTimeMS] Optional maxTimeMS for cursor + * @param {boolean} [options.noCursorTimeout] Optionally set cursor's `noCursorTimeout` flag + * @param {number} [options.skip] Optional skip for cursor + * @param {object} [options.sort] Optional sort for cursor + * @return {Cursor} + */ + +GridFSBucket.prototype.find = function(filter, options) { + filter = filter || {}; + options = options || {}; + + var cursor = this.s._filesCollection.find(filter); + + if (options.batchSize != null) { + cursor.batchSize(options.batchSize); + } + if (options.limit != null) { + cursor.limit(options.limit); + } + if (options.maxTimeMS != null) { + cursor.maxTimeMS(options.maxTimeMS); + } + if (options.noCursorTimeout != null) { + cursor.addCursorFlag('noCursorTimeout', options.noCursorTimeout); + } + if (options.skip != null) { + cursor.skip(options.skip); + } + if (options.sort != null) { + cursor.sort(options.sort); + } + + return cursor; +}; + +/** + * Returns a readable stream (GridFSBucketReadStream) for streaming the + * file with the given name from GridFS. If there are multiple files with + * the same name, this will stream the most recent file with the given name + * (as determined by the `uploadDate` field). You can set the `revision` + * option to change this behavior. + * @method + * @param {String} filename The name of the file to stream + * @param {Object} [options] Optional settings + * @param {number} [options.revision=-1] The revision number relative to the oldest file with the given filename. 0 gets you the oldest file, 1 gets you the 2nd oldest, -1 gets you the newest. + * @param {Number} [options.start] Optional 0-based offset in bytes to start streaming from + * @param {Number} [options.end] Optional 0-based offset in bytes to stop streaming before + * @return {GridFSBucketReadStream} + */ + +GridFSBucket.prototype.openDownloadStreamByName = function(filename, options) { + var sort = { uploadDate: -1 }; + var skip = null; + if (options && options.revision != null) { + if (options.revision >= 0) { + sort = { uploadDate: 1 }; + skip = options.revision; + } else { + skip = -options.revision - 1; + } + } + + var filter = { filename: filename }; + options = { + sort: sort, + skip: skip, + start: options && options.start, + end: options && options.end + }; + return new GridFSBucketReadStream( + this.s._chunksCollection, + this.s._filesCollection, + this.s.options.readPreference, + filter, + options + ); +}; + +/** + * Renames the file with the given _id to the given string + * @method + * @param {ObjectId} id the id of the file to rename + * @param {String} filename new name for the file + * @param {GridFSBucket~errorCallback} [callback] + */ + +GridFSBucket.prototype.rename = function(id, filename, callback) { + return executeLegacyOperation(this.s.db.s.topology, _rename, [this, id, filename, callback], { + skipSessions: true + }); +}; + +/** + * @ignore + */ + +function _rename(_this, id, filename, callback) { + var filter = { _id: id }; + var update = { $set: { filename: filename } }; + _this.s._filesCollection.updateOne(filter, update, function(error, res) { + if (error) { + return callback(error); + } + if (!res.result.n) { + return callback(toError('File with id ' + id + ' not found')); + } + callback(); + }); +} + +/** + * Removes this bucket's files collection, followed by its chunks collection. + * @method + * @param {GridFSBucket~errorCallback} [callback] + */ + +GridFSBucket.prototype.drop = function(callback) { + return executeLegacyOperation(this.s.db.s.topology, _drop, [this, callback], { + skipSessions: true + }); +}; + +/** + * Return the db logger + * @method + * @return {Logger} return the db logger + * @ignore + */ +GridFSBucket.prototype.getLogger = function() { + return this.s.db.s.logger; +}; + +/** + * @ignore + */ + +function _drop(_this, callback) { + _this.s._filesCollection.drop(function(error) { + if (error) { + return callback(error); + } + _this.s._chunksCollection.drop(function(error) { + if (error) { + return callback(error); + } + + return callback(); + }); + }); +} + +/** + * Callback format for all GridFSBucket methods that can accept a callback. + * @callback GridFSBucket~errorCallback + * @param {MongoError} error An error instance representing any errors that occurred + */ diff --git a/scripts/node_modules/mongodb/lib/gridfs-stream/upload.js b/scripts/node_modules/mongodb/lib/gridfs-stream/upload.js new file mode 100644 index 00000000..3733f2cb --- /dev/null +++ b/scripts/node_modules/mongodb/lib/gridfs-stream/upload.js @@ -0,0 +1,538 @@ +'use strict'; + +var core = require('../core'); +var crypto = require('crypto'); +var stream = require('stream'); +var util = require('util'); +var Buffer = require('safe-buffer').Buffer; + +var ERROR_NAMESPACE_NOT_FOUND = 26; + +module.exports = GridFSBucketWriteStream; + +/** + * A writable stream that enables you to write buffers to GridFS. + * + * Do not instantiate this class directly. Use `openUploadStream()` instead. + * + * @class + * @param {GridFSBucket} bucket Handle for this stream's corresponding bucket + * @param {string} filename The value of the 'filename' key in the files doc + * @param {object} [options] Optional settings. + * @param {string|number|object} [options.id] Custom file id for the GridFS file. + * @param {number} [options.chunkSizeBytes] The chunk size to use, in bytes + * @param {number} [options.w] The write concern + * @param {number} [options.wtimeout] The write concern timeout + * @param {number} [options.j] The journal write concern + * @param {boolean} [options.disableMD5=false] If true, disables adding an md5 field to file data + * @fires GridFSBucketWriteStream#error + * @fires GridFSBucketWriteStream#finish + * @return {GridFSBucketWriteStream} a GridFSBucketWriteStream instance. + */ + +function GridFSBucketWriteStream(bucket, filename, options) { + options = options || {}; + this.bucket = bucket; + this.chunks = bucket.s._chunksCollection; + this.filename = filename; + this.files = bucket.s._filesCollection; + this.options = options; + // Signals the write is all done + this.done = false; + + this.id = options.id ? options.id : core.BSON.ObjectId(); + this.chunkSizeBytes = this.options.chunkSizeBytes; + this.bufToStore = Buffer.alloc(this.chunkSizeBytes); + this.length = 0; + this.md5 = !options.disableMD5 && crypto.createHash('md5'); + this.n = 0; + this.pos = 0; + this.state = { + streamEnd: false, + outstandingRequests: 0, + errored: false, + aborted: false, + promiseLibrary: this.bucket.s.promiseLibrary + }; + + if (!this.bucket.s.calledOpenUploadStream) { + this.bucket.s.calledOpenUploadStream = true; + + var _this = this; + checkIndexes(this, function() { + _this.bucket.s.checkedIndexes = true; + _this.bucket.emit('index'); + }); + } +} + +util.inherits(GridFSBucketWriteStream, stream.Writable); + +/** + * An error occurred + * + * @event GridFSBucketWriteStream#error + * @type {Error} + */ + +/** + * `end()` was called and the write stream successfully wrote the file + * metadata and all the chunks to MongoDB. + * + * @event GridFSBucketWriteStream#finish + * @type {object} + */ + +/** + * Write a buffer to the stream. + * + * @method + * @param {Buffer} chunk Buffer to write + * @param {String} encoding Optional encoding for the buffer + * @param {Function} callback Function to call when the chunk was added to the buffer, or if the entire chunk was persisted to MongoDB if this chunk caused a flush. + * @return {Boolean} False if this write required flushing a chunk to MongoDB. True otherwise. + */ + +GridFSBucketWriteStream.prototype.write = function(chunk, encoding, callback) { + var _this = this; + return waitForIndexes(this, function() { + return doWrite(_this, chunk, encoding, callback); + }); +}; + +/** + * Places this write stream into an aborted state (all future writes fail) + * and deletes all chunks that have already been written. + * + * @method + * @param {GridFSBucket~errorCallback} callback called when chunks are successfully removed or error occurred + * @return {Promise} if no callback specified + */ + +GridFSBucketWriteStream.prototype.abort = function(callback) { + if (this.state.streamEnd) { + var error = new Error('Cannot abort a stream that has already completed'); + if (typeof callback === 'function') { + return callback(error); + } + return this.state.promiseLibrary.reject(error); + } + if (this.state.aborted) { + error = new Error('Cannot call abort() on a stream twice'); + if (typeof callback === 'function') { + return callback(error); + } + return this.state.promiseLibrary.reject(error); + } + this.state.aborted = true; + this.chunks.deleteMany({ files_id: this.id }, function(error) { + if (typeof callback === 'function') callback(error); + }); +}; + +/** + * Tells the stream that no more data will be coming in. The stream will + * persist the remaining data to MongoDB, write the files document, and + * then emit a 'finish' event. + * + * @method + * @param {Buffer} chunk Buffer to write + * @param {String} encoding Optional encoding for the buffer + * @param {Function} callback Function to call when all files and chunks have been persisted to MongoDB + */ + +GridFSBucketWriteStream.prototype.end = function(chunk, encoding, callback) { + var _this = this; + if (typeof chunk === 'function') { + (callback = chunk), (chunk = null), (encoding = null); + } else if (typeof encoding === 'function') { + (callback = encoding), (encoding = null); + } + + if (checkAborted(this, callback)) { + return; + } + this.state.streamEnd = true; + + if (callback) { + this.once('finish', function(result) { + callback(null, result); + }); + } + + if (!chunk) { + waitForIndexes(this, function() { + writeRemnant(_this); + }); + return; + } + + this.write(chunk, encoding, function() { + writeRemnant(_this); + }); +}; + +/** + * @ignore + */ + +function __handleError(_this, error, callback) { + if (_this.state.errored) { + return; + } + _this.state.errored = true; + if (callback) { + return callback(error); + } + _this.emit('error', error); +} + +/** + * @ignore + */ + +function createChunkDoc(filesId, n, data) { + return { + _id: core.BSON.ObjectId(), + files_id: filesId, + n: n, + data: data + }; +} + +/** + * @ignore + */ + +function checkChunksIndex(_this, callback) { + _this.chunks.listIndexes().toArray(function(error, indexes) { + if (error) { + // Collection doesn't exist so create index + if (error.code === ERROR_NAMESPACE_NOT_FOUND) { + var index = { files_id: 1, n: 1 }; + _this.chunks.createIndex(index, { background: false, unique: true }, function(error) { + if (error) { + return callback(error); + } + + callback(); + }); + return; + } + return callback(error); + } + + var hasChunksIndex = false; + indexes.forEach(function(index) { + if (index.key) { + var keys = Object.keys(index.key); + if (keys.length === 2 && index.key.files_id === 1 && index.key.n === 1) { + hasChunksIndex = true; + } + } + }); + + if (hasChunksIndex) { + callback(); + } else { + index = { files_id: 1, n: 1 }; + var indexOptions = getWriteOptions(_this); + + indexOptions.background = false; + indexOptions.unique = true; + + _this.chunks.createIndex(index, indexOptions, function(error) { + if (error) { + return callback(error); + } + + callback(); + }); + } + }); +} + +/** + * @ignore + */ + +function checkDone(_this, callback) { + if (_this.done) return true; + if (_this.state.streamEnd && _this.state.outstandingRequests === 0 && !_this.state.errored) { + // Set done so we dont' trigger duplicate createFilesDoc + _this.done = true; + // Create a new files doc + var filesDoc = createFilesDoc( + _this.id, + _this.length, + _this.chunkSizeBytes, + _this.md5 && _this.md5.digest('hex'), + _this.filename, + _this.options.contentType, + _this.options.aliases, + _this.options.metadata + ); + + if (checkAborted(_this, callback)) { + return false; + } + + _this.files.insertOne(filesDoc, getWriteOptions(_this), function(error) { + if (error) { + return __handleError(_this, error, callback); + } + _this.emit('finish', filesDoc); + }); + + return true; + } + + return false; +} + +/** + * @ignore + */ + +function checkIndexes(_this, callback) { + _this.files.findOne({}, { _id: 1 }, function(error, doc) { + if (error) { + return callback(error); + } + if (doc) { + return callback(); + } + + _this.files.listIndexes().toArray(function(error, indexes) { + if (error) { + // Collection doesn't exist so create index + if (error.code === ERROR_NAMESPACE_NOT_FOUND) { + var index = { filename: 1, uploadDate: 1 }; + _this.files.createIndex(index, { background: false }, function(error) { + if (error) { + return callback(error); + } + + checkChunksIndex(_this, callback); + }); + return; + } + return callback(error); + } + + var hasFileIndex = false; + indexes.forEach(function(index) { + var keys = Object.keys(index.key); + if (keys.length === 2 && index.key.filename === 1 && index.key.uploadDate === 1) { + hasFileIndex = true; + } + }); + + if (hasFileIndex) { + checkChunksIndex(_this, callback); + } else { + index = { filename: 1, uploadDate: 1 }; + + var indexOptions = getWriteOptions(_this); + + indexOptions.background = false; + + _this.files.createIndex(index, indexOptions, function(error) { + if (error) { + return callback(error); + } + + checkChunksIndex(_this, callback); + }); + } + }); + }); +} + +/** + * @ignore + */ + +function createFilesDoc(_id, length, chunkSize, md5, filename, contentType, aliases, metadata) { + var ret = { + _id: _id, + length: length, + chunkSize: chunkSize, + uploadDate: new Date(), + filename: filename + }; + + if (md5) { + ret.md5 = md5; + } + + if (contentType) { + ret.contentType = contentType; + } + + if (aliases) { + ret.aliases = aliases; + } + + if (metadata) { + ret.metadata = metadata; + } + + return ret; +} + +/** + * @ignore + */ + +function doWrite(_this, chunk, encoding, callback) { + if (checkAborted(_this, callback)) { + return false; + } + + var inputBuf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding); + + _this.length += inputBuf.length; + + // Input is small enough to fit in our buffer + if (_this.pos + inputBuf.length < _this.chunkSizeBytes) { + inputBuf.copy(_this.bufToStore, _this.pos); + _this.pos += inputBuf.length; + + callback && callback(); + + // Note that we reverse the typical semantics of write's return value + // to be compatible with node's `.pipe()` function. + // True means client can keep writing. + return true; + } + + // Otherwise, buffer is too big for current chunk, so we need to flush + // to MongoDB. + var inputBufRemaining = inputBuf.length; + var spaceRemaining = _this.chunkSizeBytes - _this.pos; + var numToCopy = Math.min(spaceRemaining, inputBuf.length); + var outstandingRequests = 0; + while (inputBufRemaining > 0) { + var inputBufPos = inputBuf.length - inputBufRemaining; + inputBuf.copy(_this.bufToStore, _this.pos, inputBufPos, inputBufPos + numToCopy); + _this.pos += numToCopy; + spaceRemaining -= numToCopy; + if (spaceRemaining === 0) { + if (_this.md5) { + _this.md5.update(_this.bufToStore); + } + var doc = createChunkDoc(_this.id, _this.n, _this.bufToStore); + ++_this.state.outstandingRequests; + ++outstandingRequests; + + if (checkAborted(_this, callback)) { + return false; + } + + _this.chunks.insertOne(doc, getWriteOptions(_this), function(error) { + if (error) { + return __handleError(_this, error); + } + --_this.state.outstandingRequests; + --outstandingRequests; + + if (!outstandingRequests) { + _this.emit('drain', doc); + callback && callback(); + checkDone(_this); + } + }); + + spaceRemaining = _this.chunkSizeBytes; + _this.pos = 0; + ++_this.n; + } + inputBufRemaining -= numToCopy; + numToCopy = Math.min(spaceRemaining, inputBufRemaining); + } + + // Note that we reverse the typical semantics of write's return value + // to be compatible with node's `.pipe()` function. + // False means the client should wait for the 'drain' event. + return false; +} + +/** + * @ignore + */ + +function getWriteOptions(_this) { + var obj = {}; + if (_this.options.writeConcern) { + obj.w = _this.options.writeConcern.w; + obj.wtimeout = _this.options.writeConcern.wtimeout; + obj.j = _this.options.writeConcern.j; + } + return obj; +} + +/** + * @ignore + */ + +function waitForIndexes(_this, callback) { + if (_this.bucket.s.checkedIndexes) { + return callback(false); + } + + _this.bucket.once('index', function() { + callback(true); + }); + + return true; +} + +/** + * @ignore + */ + +function writeRemnant(_this, callback) { + // Buffer is empty, so don't bother to insert + if (_this.pos === 0) { + return checkDone(_this, callback); + } + + ++_this.state.outstandingRequests; + + // Create a new buffer to make sure the buffer isn't bigger than it needs + // to be. + var remnant = Buffer.alloc(_this.pos); + _this.bufToStore.copy(remnant, 0, 0, _this.pos); + if (_this.md5) { + _this.md5.update(remnant); + } + var doc = createChunkDoc(_this.id, _this.n, remnant); + + // If the stream was aborted, do not write remnant + if (checkAborted(_this, callback)) { + return false; + } + + _this.chunks.insertOne(doc, getWriteOptions(_this), function(error) { + if (error) { + return __handleError(_this, error); + } + --_this.state.outstandingRequests; + checkDone(_this); + }); +} + +/** + * @ignore + */ + +function checkAborted(_this, callback) { + if (_this.state.aborted) { + if (typeof callback === 'function') { + callback(new Error('this stream has been aborted')); + } + return true; + } + return false; +} diff --git a/scripts/node_modules/mongodb/lib/gridfs/chunk.js b/scripts/node_modules/mongodb/lib/gridfs/chunk.js new file mode 100644 index 00000000..d276d720 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/gridfs/chunk.js @@ -0,0 +1,236 @@ +'use strict'; + +var Binary = require('../core').BSON.Binary, + ObjectID = require('../core').BSON.ObjectID; + +var Buffer = require('safe-buffer').Buffer; + +/** + * Class for representing a single chunk in GridFS. + * + * @class + * + * @param file {GridStore} The {@link GridStore} object holding this chunk. + * @param mongoObject {object} The mongo object representation of this chunk. + * + * @throws Error when the type of data field for {@link mongoObject} is not + * supported. Currently supported types for data field are instances of + * {@link String}, {@link Array}, {@link Binary} and {@link Binary} + * from the bson module + * + * @see Chunk#buildMongoObject + */ +var Chunk = function(file, mongoObject, writeConcern) { + if (!(this instanceof Chunk)) return new Chunk(file, mongoObject); + + this.file = file; + var mongoObjectFinal = mongoObject == null ? {} : mongoObject; + this.writeConcern = writeConcern || { w: 1 }; + this.objectId = mongoObjectFinal._id == null ? new ObjectID() : mongoObjectFinal._id; + this.chunkNumber = mongoObjectFinal.n == null ? 0 : mongoObjectFinal.n; + this.data = new Binary(); + + if (typeof mongoObjectFinal.data === 'string') { + var buffer = Buffer.alloc(mongoObjectFinal.data.length); + buffer.write(mongoObjectFinal.data, 0, mongoObjectFinal.data.length, 'binary'); + this.data = new Binary(buffer); + } else if (Array.isArray(mongoObjectFinal.data)) { + buffer = Buffer.alloc(mongoObjectFinal.data.length); + var data = mongoObjectFinal.data.join(''); + buffer.write(data, 0, data.length, 'binary'); + this.data = new Binary(buffer); + } else if (mongoObjectFinal.data && mongoObjectFinal.data._bsontype === 'Binary') { + this.data = mongoObjectFinal.data; + } else if (!Buffer.isBuffer(mongoObjectFinal.data) && !(mongoObjectFinal.data == null)) { + throw Error('Illegal chunk format'); + } + + // Update position + this.internalPosition = 0; +}; + +/** + * Writes a data to this object and advance the read/write head. + * + * @param data {string} the data to write + * @param callback {function(*, GridStore)} This will be called after executing + * this method. The first parameter will contain null and the second one + * will contain a reference to this object. + */ +Chunk.prototype.write = function(data, callback) { + this.data.write(data, this.internalPosition, data.length, 'binary'); + this.internalPosition = this.data.length(); + if (callback != null) return callback(null, this); + return this; +}; + +/** + * Reads data and advances the read/write head. + * + * @param length {number} The length of data to read. + * + * @return {string} The data read if the given length will not exceed the end of + * the chunk. Returns an empty String otherwise. + */ +Chunk.prototype.read = function(length) { + // Default to full read if no index defined + length = length == null || length === 0 ? this.length() : length; + + if (this.length() - this.internalPosition + 1 >= length) { + var data = this.data.read(this.internalPosition, length); + this.internalPosition = this.internalPosition + length; + return data; + } else { + return ''; + } +}; + +Chunk.prototype.readSlice = function(length) { + if (this.length() - this.internalPosition >= length) { + var data = null; + if (this.data.buffer != null) { + //Pure BSON + data = this.data.buffer.slice(this.internalPosition, this.internalPosition + length); + } else { + //Native BSON + data = Buffer.alloc(length); + length = this.data.readInto(data, this.internalPosition); + } + this.internalPosition = this.internalPosition + length; + return data; + } else { + return null; + } +}; + +/** + * Checks if the read/write head is at the end. + * + * @return {boolean} Whether the read/write head has reached the end of this + * chunk. + */ +Chunk.prototype.eof = function() { + return this.internalPosition === this.length() ? true : false; +}; + +/** + * Reads one character from the data of this chunk and advances the read/write + * head. + * + * @return {string} a single character data read if the the read/write head is + * not at the end of the chunk. Returns an empty String otherwise. + */ +Chunk.prototype.getc = function() { + return this.read(1); +}; + +/** + * Clears the contents of the data in this chunk and resets the read/write head + * to the initial position. + */ +Chunk.prototype.rewind = function() { + this.internalPosition = 0; + this.data = new Binary(); +}; + +/** + * Saves this chunk to the database. Also overwrites existing entries having the + * same id as this chunk. + * + * @param callback {function(*, GridStore)} This will be called after executing + * this method. The first parameter will contain null and the second one + * will contain a reference to this object. + */ +Chunk.prototype.save = function(options, callback) { + var self = this; + if (typeof options === 'function') { + callback = options; + options = {}; + } + + self.file.chunkCollection(function(err, collection) { + if (err) return callback(err); + + // Merge the options + var writeOptions = { upsert: true }; + for (var name in options) writeOptions[name] = options[name]; + for (name in self.writeConcern) writeOptions[name] = self.writeConcern[name]; + + if (self.data.length() > 0) { + self.buildMongoObject(function(mongoObject) { + var options = { forceServerObjectId: true }; + for (var name in self.writeConcern) { + options[name] = self.writeConcern[name]; + } + + collection.replaceOne({ _id: self.objectId }, mongoObject, writeOptions, function(err) { + callback(err, self); + }); + }); + } else { + callback(null, self); + } + // }); + }); +}; + +/** + * Creates a mongoDB object representation of this chunk. + * + * @param callback {function(Object)} This will be called after executing this + * method. The object will be passed to the first parameter and will have + * the structure: + * + *

+ *        {
+ *          '_id' : , // {number} id for this chunk
+ *          'files_id' : , // {number} foreign key to the file collection
+ *          'n' : , // {number} chunk number
+ *          'data' : , // {bson#Binary} the chunk data itself
+ *        }
+ *        
+ * + * @see MongoDB GridFS Chunk Object Structure + */ +Chunk.prototype.buildMongoObject = function(callback) { + var mongoObject = { + files_id: this.file.fileId, + n: this.chunkNumber, + data: this.data + }; + // If we are saving using a specific ObjectId + if (this.objectId != null) mongoObject._id = this.objectId; + + callback(mongoObject); +}; + +/** + * @return {number} the length of the data + */ +Chunk.prototype.length = function() { + return this.data.length(); +}; + +/** + * The position of the read/write head + * @name position + * @lends Chunk# + * @field + */ +Object.defineProperty(Chunk.prototype, 'position', { + enumerable: true, + get: function() { + return this.internalPosition; + }, + set: function(value) { + this.internalPosition = value; + } +}); + +/** + * The default chunk size + * @constant + */ +Chunk.DEFAULT_CHUNK_SIZE = 1024 * 255; + +module.exports = Chunk; diff --git a/scripts/node_modules/mongodb/lib/gridfs/grid_store.js b/scripts/node_modules/mongodb/lib/gridfs/grid_store.js new file mode 100644 index 00000000..c8ccb850 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/gridfs/grid_store.js @@ -0,0 +1,1913 @@ +'use strict'; + +/** + * @fileOverview GridFS is a tool for MongoDB to store files to the database. + * Because of the restrictions of the object size the database can hold, a + * facility to split a file into several chunks is needed. The {@link GridStore} + * class offers a simplified api to interact with files while managing the + * chunks of split files behind the scenes. More information about GridFS can be + * found here. + * + * @example + * const MongoClient = require('mongodb').MongoClient; + * const GridStore = require('mongodb').GridStore; + * const ObjectID = require('mongodb').ObjectID; + * const test = require('assert'); + * // Connection url + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, client) { + * const db = client.db(dbName); + * const gridStore = new GridStore(db, null, "w"); + * gridStore.open(function(err, gridStore) { + * gridStore.write("hello world!", function(err, gridStore) { + * gridStore.close(function(err, result) { + * // Let's read the file using object Id + * GridStore.read(db, result._id, function(err, data) { + * test.equal('hello world!', data); + * client.close(); + * test.done(); + * }); + * }); + * }); + * }); + * }); + */ +const Chunk = require('./chunk'); +const ObjectID = require('../core').BSON.ObjectID; +const ReadPreference = require('../core').ReadPreference; +const Buffer = require('safe-buffer').Buffer; +const fs = require('fs'); +const f = require('util').format; +const util = require('util'); +const MongoError = require('../core').MongoError; +const inherits = util.inherits; +const Duplex = require('stream').Duplex; +const shallowClone = require('../utils').shallowClone; +const executeLegacyOperation = require('../utils').executeLegacyOperation; +const deprecate = require('util').deprecate; + +var REFERENCE_BY_FILENAME = 0, + REFERENCE_BY_ID = 1; + +const deprecationFn = deprecate(() => {}, +'GridStore is deprecated, and will be removed in a future version. Please use GridFSBucket instead'); + +/** + * Namespace provided by the core module + * @external Duplex + */ + +/** + * Create a new GridStore instance + * + * Modes + * - **"r"** - read only. This is the default mode. + * - **"w"** - write in truncate mode. Existing data will be overwritten. + * + * @class + * @param {Db} db A database instance to interact with. + * @param {object} [id] optional unique id for this file + * @param {string} [filename] optional filename for this file, no unique constrain on the field + * @param {string} mode set the mode for this file. + * @param {object} [options] Optional settings. + * @param {(number|string)} [options.w] The write concern. + * @param {number} [options.wtimeout] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.fsync=false] Specify a file sync write concern. + * @param {string} [options.root] Root collection to use. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**. + * @param {string} [options.content_type] MIME type of the file. Defaults to **{GridStore.DEFAULT_CONTENT_TYPE}**. + * @param {number} [options.chunk_size=261120] Size for the chunk. Defaults to **{Chunk.DEFAULT_CHUNK_SIZE}**. + * @param {object} [options.metadata] Arbitrary data the user wants to store. + * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @property {number} chunkSize Get the gridstore chunk size. + * @property {number} md5 The md5 checksum for this file. + * @property {number} chunkNumber The current chunk number the gridstore has materialized into memory + * @return {GridStore} a GridStore instance. + * @deprecated Use GridFSBucket API instead + */ +var GridStore = function GridStore(db, id, filename, mode, options) { + deprecationFn(); + if (!(this instanceof GridStore)) return new GridStore(db, id, filename, mode, options); + this.db = db; + + // Handle options + if (typeof options === 'undefined') options = {}; + // Handle mode + if (typeof mode === 'undefined') { + mode = filename; + filename = undefined; + } else if (typeof mode === 'object') { + options = mode; + mode = filename; + filename = undefined; + } + + if (id && id._bsontype === 'ObjectID') { + this.referenceBy = REFERENCE_BY_ID; + this.fileId = id; + this.filename = filename; + } else if (typeof filename === 'undefined') { + this.referenceBy = REFERENCE_BY_FILENAME; + this.filename = id; + if (mode.indexOf('w') != null) { + this.fileId = new ObjectID(); + } + } else { + this.referenceBy = REFERENCE_BY_ID; + this.fileId = id; + this.filename = filename; + } + + // Set up the rest + this.mode = mode == null ? 'r' : mode; + this.options = options || {}; + + // Opened + this.isOpen = false; + + // Set the root if overridden + this.root = + this.options['root'] == null ? GridStore.DEFAULT_ROOT_COLLECTION : this.options['root']; + this.position = 0; + this.readPreference = + this.options.readPreference || db.options.readPreference || ReadPreference.primary; + this.writeConcern = _getWriteConcern(db, this.options); + // Set default chunk size + this.internalChunkSize = + this.options['chunkSize'] == null ? Chunk.DEFAULT_CHUNK_SIZE : this.options['chunkSize']; + + // Get the promiseLibrary + var promiseLibrary = this.options.promiseLibrary || Promise; + + // Set the promiseLibrary + this.promiseLibrary = promiseLibrary; + + Object.defineProperty(this, 'chunkSize', { + enumerable: true, + get: function() { + return this.internalChunkSize; + }, + set: function(value) { + if (!(this.mode[0] === 'w' && this.position === 0 && this.uploadDate == null)) { + this.internalChunkSize = this.internalChunkSize; + } else { + this.internalChunkSize = value; + } + } + }); + + Object.defineProperty(this, 'md5', { + enumerable: true, + get: function() { + return this.internalMd5; + } + }); + + Object.defineProperty(this, 'chunkNumber', { + enumerable: true, + get: function() { + return this.currentChunk && this.currentChunk.chunkNumber + ? this.currentChunk.chunkNumber + : null; + } + }); +}; + +/** + * The callback format for the Gridstore.open method + * @callback GridStore~openCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {GridStore} gridStore The GridStore instance if the open method was successful. + */ + +/** + * Opens the file from the database and initialize this object. Also creates a + * new one if file does not exist. + * + * @method + * @param {object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~openCallback} [callback] this will be called after executing this method + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.open = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + if (this.mode !== 'w' && this.mode !== 'w+' && this.mode !== 'r') { + throw MongoError.create({ message: 'Illegal mode ' + this.mode, driver: true }); + } + + return executeLegacyOperation(this.db.s.topology, open, [this, options, callback], { + skipSessions: true + }); +}; + +var open = function(self, options, callback) { + // Get the write concern + var writeConcern = _getWriteConcern(self.db, self.options); + + // If we are writing we need to ensure we have the right indexes for md5's + if (self.mode === 'w' || self.mode === 'w+') { + // Get files collection + var collection = self.collection(); + // Put index on filename + collection.ensureIndex([['filename', 1]], writeConcern, function() { + // Get chunk collection + var chunkCollection = self.chunkCollection(); + // Make an unique index for compatibility with mongo-cxx-driver:legacy + var chunkIndexOptions = shallowClone(writeConcern); + chunkIndexOptions.unique = true; + // Ensure index on chunk collection + chunkCollection.ensureIndex([['files_id', 1], ['n', 1]], chunkIndexOptions, function() { + // Open the connection + _open(self, writeConcern, function(err, r) { + if (err) return callback(err); + self.isOpen = true; + callback(err, r); + }); + }); + }); + } else { + // Open the gridstore + _open(self, writeConcern, function(err, r) { + if (err) return callback(err); + self.isOpen = true; + callback(err, r); + }); + } +}; + +/** + * Verify if the file is at EOF. + * + * @method + * @return {boolean} true if the read/write head is at the end of this file. + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.eof = function() { + return this.position === this.length ? true : false; +}; + +/** + * The callback result format. + * @callback GridStore~resultCallback + * @param {object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {MongoError} error An error instance representing the error during the execution. + * @param {object} result The result from the callback. + */ + +/** + * Retrieves a single character from this file. + * + * @method + * @param {GridStore~resultCallback} [callback] this gets called after this method is executed. Passes null to the first parameter and the character read to the second or null to the second if the read/write head is at the end of the file. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.getc = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeLegacyOperation(this.db.s.topology, getc, [this, options, callback], { + skipSessions: true + }); +}; + +var getc = function(self, options, callback) { + if (self.eof()) { + callback(null, null); + } else if (self.currentChunk.eof()) { + nthChunk(self, self.currentChunk.chunkNumber + 1, function(err, chunk) { + self.currentChunk = chunk; + self.position = self.position + 1; + callback(err, self.currentChunk.getc()); + }); + } else { + self.position = self.position + 1; + callback(null, self.currentChunk.getc()); + } +}; + +/** + * Writes a string to the file with a newline character appended at the end if + * the given string does not have one. + * + * @method + * @param {string} string the string to write. + * @param {object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.puts = function(string, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + var finalString = string.match(/\n$/) == null ? string + '\n' : string; + return executeLegacyOperation( + this.db.s.topology, + this.write.bind(this), + [finalString, options, callback], + { skipSessions: true } + ); +}; + +/** + * Return a modified Readable stream including a possible transform method. + * + * @method + * @return {GridStoreStream} + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.stream = function() { + return new GridStoreStream(this); +}; + +/** + * Writes some data. This method will work properly only if initialized with mode "w" or "w+". + * + * @method + * @param {(string|Buffer)} data the data to write. + * @param {boolean} [close] closes this file after writing if set to true. + * @param {object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.write = function write(data, close, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeLegacyOperation( + this.db.s.topology, + _writeNormal, + [this, data, close, options, callback], + { skipSessions: true } + ); +}; + +/** + * Handles the destroy part of a stream + * + * @method + * @result {null} + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.destroy = function destroy() { + // close and do not emit any more events. queued data is not sent. + if (!this.writable) return; + this.readable = false; + if (this.writable) { + this.writable = false; + this._q.length = 0; + this.emit('close'); + } +}; + +/** + * Stores a file from the file system to the GridFS database. + * + * @method + * @param {(string|Buffer|FileHandle)} file the file to store. + * @param {object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.writeFile = function(file, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeLegacyOperation(this.db.s.topology, writeFile, [this, file, options, callback], { + skipSessions: true + }); +}; + +var writeFile = function(self, file, options, callback) { + if (typeof file === 'string') { + fs.open(file, 'r', function(err, fd) { + if (err) return callback(err); + self.writeFile(fd, callback); + }); + return; + } + + self.open(function(err, self) { + if (err) return callback(err, self); + + fs.fstat(file, function(err, stats) { + if (err) return callback(err, self); + + var offset = 0; + var index = 0; + + // Write a chunk + var writeChunk = function() { + // Allocate the buffer + var _buffer = Buffer.alloc(self.chunkSize); + // Read the file + fs.read(file, _buffer, 0, _buffer.length, offset, function(err, bytesRead, data) { + if (err) return callback(err, self); + + offset = offset + bytesRead; + + // Create a new chunk for the data + var chunk = new Chunk(self, { n: index++ }, self.writeConcern); + chunk.write(data.slice(0, bytesRead), function(err, chunk) { + if (err) return callback(err, self); + + chunk.save({}, function(err) { + if (err) return callback(err, self); + + self.position = self.position + bytesRead; + + // Point to current chunk + self.currentChunk = chunk; + + if (offset >= stats.size) { + fs.close(file, function(err) { + if (err) return callback(err); + + self.close(function(err) { + if (err) return callback(err, self); + return callback(null, self); + }); + }); + } else { + return process.nextTick(writeChunk); + } + }); + }); + }); + }; + + // Process the first write + process.nextTick(writeChunk); + }); + }); +}; + +/** + * Saves this file to the database. This will overwrite the old entry if it + * already exists. This will work properly only if mode was initialized to + * "w" or "w+". + * + * @method + * @param {object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.close = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeLegacyOperation(this.db.s.topology, close, [this, options, callback], { + skipSessions: true + }); +}; + +var close = function(self, options, callback) { + if (self.mode[0] === 'w') { + // Set up options + options = Object.assign({}, self.writeConcern, options); + + if (self.currentChunk != null && self.currentChunk.position > 0) { + self.currentChunk.save({}, function(err) { + if (err && typeof callback === 'function') return callback(err); + + self.collection(function(err, files) { + if (err && typeof callback === 'function') return callback(err); + + // Build the mongo object + if (self.uploadDate != null) { + buildMongoObject(self, function(err, mongoObject) { + if (err) { + if (typeof callback === 'function') return callback(err); + else throw err; + } + + files.save(mongoObject, options, function(err) { + if (typeof callback === 'function') callback(err, mongoObject); + }); + }); + } else { + self.uploadDate = new Date(); + buildMongoObject(self, function(err, mongoObject) { + if (err) { + if (typeof callback === 'function') return callback(err); + else throw err; + } + + files.save(mongoObject, options, function(err) { + if (typeof callback === 'function') callback(err, mongoObject); + }); + }); + } + }); + }); + } else { + self.collection(function(err, files) { + if (err && typeof callback === 'function') return callback(err); + + self.uploadDate = new Date(); + buildMongoObject(self, function(err, mongoObject) { + if (err) { + if (typeof callback === 'function') return callback(err); + else throw err; + } + + files.save(mongoObject, options, function(err) { + if (typeof callback === 'function') callback(err, mongoObject); + }); + }); + }); + } + } else if (self.mode[0] === 'r') { + if (typeof callback === 'function') callback(null, null); + } else { + if (typeof callback === 'function') + callback(MongoError.create({ message: f('Illegal mode %s', self.mode), driver: true })); + } +}; + +/** + * The collection callback format. + * @callback GridStore~collectionCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection} collection The collection from the command execution. + */ + +/** + * Retrieve this file's chunks collection. + * + * @method + * @param {GridStore~collectionCallback} callback the command callback. + * @return {Collection} + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.chunkCollection = function(callback) { + if (typeof callback === 'function') return this.db.collection(this.root + '.chunks', callback); + return this.db.collection(this.root + '.chunks'); +}; + +/** + * Deletes all the chunks of this file in the database. + * + * @method + * @param {object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~resultCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.unlink = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeLegacyOperation(this.db.s.topology, unlink, [this, options, callback], { + skipSessions: true + }); +}; + +var unlink = function(self, options, callback) { + deleteChunks(self, function(err) { + if (err !== null) { + err.message = 'at deleteChunks: ' + err.message; + return callback(err); + } + + self.collection(function(err, collection) { + if (err !== null) { + err.message = 'at collection: ' + err.message; + return callback(err); + } + + collection.remove({ _id: self.fileId }, self.writeConcern, function(err) { + callback(err, self); + }); + }); + }); +}; + +/** + * Retrieves the file collection associated with this object. + * + * @method + * @param {GridStore~collectionCallback} callback the command callback. + * @return {Collection} + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.collection = function(callback) { + if (typeof callback === 'function') this.db.collection(this.root + '.files', callback); + return this.db.collection(this.root + '.files'); +}; + +/** + * The readlines callback format. + * @callback GridStore~readlinesCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {string[]} strings The array of strings returned. + */ + +/** + * Read the entire file as a list of strings splitting by the provided separator. + * + * @method + * @param {string} [separator] The character to be recognized as the newline separator. + * @param {object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~readlinesCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.readlines = function(separator, options, callback) { + var args = Array.prototype.slice.call(arguments, 0); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + separator = args.length ? args.shift() : '\n'; + separator = separator || '\n'; + options = args.length ? args.shift() : {}; + + return executeLegacyOperation( + this.db.s.topology, + readlines, + [this, separator, options, callback], + { skipSessions: true } + ); +}; + +var readlines = function(self, separator, options, callback) { + self.read(function(err, data) { + if (err) return callback(err); + + var items = data.toString().split(separator); + items = items.length > 0 ? items.splice(0, items.length - 1) : []; + for (var i = 0; i < items.length; i++) { + items[i] = items[i] + separator; + } + + callback(null, items); + }); +}; + +/** + * Deletes all the chunks of this file in the database if mode was set to "w" or + * "w+" and resets the read/write head to the initial position. + * + * @method + * @param {object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.rewind = function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + return executeLegacyOperation(this.db.s.topology, rewind, [this, options, callback], { + skipSessions: true + }); +}; + +var rewind = function(self, options, callback) { + if (self.currentChunk.chunkNumber !== 0) { + if (self.mode[0] === 'w') { + deleteChunks(self, function(err) { + if (err) return callback(err); + self.currentChunk = new Chunk(self, { n: 0 }, self.writeConcern); + self.position = 0; + callback(null, self); + }); + } else { + self.currentChunk(0, function(err, chunk) { + if (err) return callback(err); + self.currentChunk = chunk; + self.currentChunk.rewind(); + self.position = 0; + callback(null, self); + }); + } + } else { + self.currentChunk.rewind(); + self.position = 0; + callback(null, self); + } +}; + +/** + * The read callback format. + * @callback GridStore~readCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Buffer} data The data read from the GridStore object + */ + +/** + * Retrieves the contents of this file and advances the read/write head. Works with Buffers only. + * + * There are 3 signatures for this method: + * + * (callback) + * (length, callback) + * (length, buffer, callback) + * + * @method + * @param {number} [length] the number of characters to read. Reads all the characters from the read/write head to the EOF if not specified. + * @param {(string|Buffer)} [buffer] a string to hold temporary data. This is used for storing the string data read so far when recursively calling this method. + * @param {object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~readCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.read = function(length, buffer, options, callback) { + var args = Array.prototype.slice.call(arguments, 0); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + length = args.length ? args.shift() : null; + buffer = args.length ? args.shift() : null; + options = args.length ? args.shift() : {}; + + return executeLegacyOperation( + this.db.s.topology, + read, + [this, length, buffer, options, callback], + { skipSessions: true } + ); +}; + +var read = function(self, length, buffer, options, callback) { + // The data is a c-terminated string and thus the length - 1 + var finalLength = length == null ? self.length - self.position : length; + var finalBuffer = buffer == null ? Buffer.alloc(finalLength) : buffer; + // Add a index to buffer to keep track of writing position or apply current index + finalBuffer._index = buffer != null && buffer._index != null ? buffer._index : 0; + + if (self.currentChunk.length() - self.currentChunk.position + finalBuffer._index >= finalLength) { + var slice = self.currentChunk.readSlice(finalLength - finalBuffer._index); + // Copy content to final buffer + slice.copy(finalBuffer, finalBuffer._index); + // Update internal position + self.position = self.position + finalBuffer.length; + // Check if we don't have a file at all + if (finalLength === 0 && finalBuffer.length === 0) + return callback(MongoError.create({ message: 'File does not exist', driver: true }), null); + // Else return data + return callback(null, finalBuffer); + } + + // Read the next chunk + slice = self.currentChunk.readSlice(self.currentChunk.length() - self.currentChunk.position); + // Copy content to final buffer + slice.copy(finalBuffer, finalBuffer._index); + // Update index position + finalBuffer._index += slice.length; + + // Load next chunk and read more + nthChunk(self, self.currentChunk.chunkNumber + 1, function(err, chunk) { + if (err) return callback(err); + + if (chunk.length() > 0) { + self.currentChunk = chunk; + self.read(length, finalBuffer, callback); + } else { + if (finalBuffer._index > 0) { + callback(null, finalBuffer); + } else { + callback( + MongoError.create({ + message: 'no chunks found for file, possibly corrupt', + driver: true + }), + null + ); + } + } + }); +}; + +/** + * The tell callback format. + * @callback GridStore~tellCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {number} position The current read position in the GridStore. + */ + +/** + * Retrieves the position of the read/write head of this file. + * + * @method + * @param {number} [length] the number of characters to read. Reads all the characters from the read/write head to the EOF if not specified. + * @param {(string|Buffer)} [buffer] a string to hold temporary data. This is used for storing the string data read so far when recursively calling this method. + * @param {object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~tellCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.tell = function(callback) { + var self = this; + // We provided a callback leg + if (typeof callback === 'function') return callback(null, this.position); + // Return promise + return new self.promiseLibrary(function(resolve) { + resolve(self.position); + }); +}; + +/** + * The tell callback format. + * @callback GridStore~gridStoreCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {GridStore} gridStore The gridStore. + */ + +/** + * Moves the read/write head to a new location. + * + * There are 3 signatures for this method + * + * Seek Location Modes + * - **GridStore.IO_SEEK_SET**, **(default)** set the position from the start of the file. + * - **GridStore.IO_SEEK_CUR**, set the position from the current position in the file. + * - **GridStore.IO_SEEK_END**, set the position from the end of the file. + * + * @method + * @param {number} [position] the position to seek to + * @param {number} [seekLocation] seek mode. Use one of the Seek Location modes. + * @param {object} [options] Optional settings + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~gridStoreCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.prototype.seek = function(position, seekLocation, options, callback) { + var args = Array.prototype.slice.call(arguments, 1); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + seekLocation = args.length ? args.shift() : null; + options = args.length ? args.shift() : {}; + + return executeLegacyOperation( + this.db.s.topology, + seek, + [this, position, seekLocation, options, callback], + { skipSessions: true } + ); +}; + +var seek = function(self, position, seekLocation, options, callback) { + // Seek only supports read mode + if (self.mode !== 'r') { + return callback( + MongoError.create({ message: 'seek is only supported for mode r', driver: true }) + ); + } + + var seekLocationFinal = seekLocation == null ? GridStore.IO_SEEK_SET : seekLocation; + var finalPosition = position; + var targetPosition = 0; + + // Calculate the position + if (seekLocationFinal === GridStore.IO_SEEK_CUR) { + targetPosition = self.position + finalPosition; + } else if (seekLocationFinal === GridStore.IO_SEEK_END) { + targetPosition = self.length + finalPosition; + } else { + targetPosition = finalPosition; + } + + // Get the chunk + var newChunkNumber = Math.floor(targetPosition / self.chunkSize); + var seekChunk = function() { + nthChunk(self, newChunkNumber, function(err, chunk) { + if (err) return callback(err, null); + if (chunk == null) return callback(new Error('no chunk found')); + + // Set the current chunk + self.currentChunk = chunk; + self.position = targetPosition; + self.currentChunk.position = self.position % self.chunkSize; + callback(err, self); + }); + }; + + seekChunk(); +}; + +/** + * @ignore + */ +var _open = function(self, options, callback) { + var collection = self.collection(); + // Create the query + var query = + self.referenceBy === REFERENCE_BY_ID ? { _id: self.fileId } : { filename: self.filename }; + query = null == self.fileId && self.filename == null ? null : query; + options.readPreference = self.readPreference; + + // Fetch the chunks + if (query != null) { + collection.findOne(query, options, function(err, doc) { + if (err) { + return error(err); + } + + // Check if the collection for the files exists otherwise prepare the new one + if (doc != null) { + self.fileId = doc._id; + // Prefer a new filename over the existing one if this is a write + self.filename = + self.mode === 'r' || self.filename === undefined ? doc.filename : self.filename; + self.contentType = doc.contentType; + self.internalChunkSize = doc.chunkSize; + self.uploadDate = doc.uploadDate; + self.aliases = doc.aliases; + self.length = doc.length; + self.metadata = doc.metadata; + self.internalMd5 = doc.md5; + } else if (self.mode !== 'r') { + self.fileId = self.fileId == null ? new ObjectID() : self.fileId; + self.contentType = GridStore.DEFAULT_CONTENT_TYPE; + self.internalChunkSize = + self.internalChunkSize == null ? Chunk.DEFAULT_CHUNK_SIZE : self.internalChunkSize; + self.length = 0; + } else { + self.length = 0; + var txtId = self.fileId._bsontype === 'ObjectID' ? self.fileId.toHexString() : self.fileId; + return error( + MongoError.create({ + message: f( + 'file with id %s not opened for writing', + self.referenceBy === REFERENCE_BY_ID ? txtId : self.filename + ), + driver: true + }), + self + ); + } + + // Process the mode of the object + if (self.mode === 'r') { + nthChunk(self, 0, options, function(err, chunk) { + if (err) return error(err); + self.currentChunk = chunk; + self.position = 0; + callback(null, self); + }); + } else if (self.mode === 'w' && doc) { + // Delete any existing chunks + deleteChunks(self, options, function(err) { + if (err) return error(err); + self.currentChunk = new Chunk(self, { n: 0 }, self.writeConcern); + self.contentType = + self.options['content_type'] == null ? self.contentType : self.options['content_type']; + self.internalChunkSize = + self.options['chunk_size'] == null + ? self.internalChunkSize + : self.options['chunk_size']; + self.metadata = + self.options['metadata'] == null ? self.metadata : self.options['metadata']; + self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; + self.position = 0; + callback(null, self); + }); + } else if (self.mode === 'w') { + self.currentChunk = new Chunk(self, { n: 0 }, self.writeConcern); + self.contentType = + self.options['content_type'] == null ? self.contentType : self.options['content_type']; + self.internalChunkSize = + self.options['chunk_size'] == null ? self.internalChunkSize : self.options['chunk_size']; + self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata']; + self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; + self.position = 0; + callback(null, self); + } else if (self.mode === 'w+') { + nthChunk(self, lastChunkNumber(self), options, function(err, chunk) { + if (err) return error(err); + // Set the current chunk + self.currentChunk = chunk == null ? new Chunk(self, { n: 0 }, self.writeConcern) : chunk; + self.currentChunk.position = self.currentChunk.data.length(); + self.metadata = + self.options['metadata'] == null ? self.metadata : self.options['metadata']; + self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; + self.position = self.length; + callback(null, self); + }); + } + }); + } else { + // Write only mode + self.fileId = null == self.fileId ? new ObjectID() : self.fileId; + self.contentType = GridStore.DEFAULT_CONTENT_TYPE; + self.internalChunkSize = + self.internalChunkSize == null ? Chunk.DEFAULT_CHUNK_SIZE : self.internalChunkSize; + self.length = 0; + + // No file exists set up write mode + if (self.mode === 'w') { + // Delete any existing chunks + deleteChunks(self, options, function(err) { + if (err) return error(err); + self.currentChunk = new Chunk(self, { n: 0 }, self.writeConcern); + self.contentType = + self.options['content_type'] == null ? self.contentType : self.options['content_type']; + self.internalChunkSize = + self.options['chunk_size'] == null ? self.internalChunkSize : self.options['chunk_size']; + self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata']; + self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; + self.position = 0; + callback(null, self); + }); + } else if (self.mode === 'w+') { + nthChunk(self, lastChunkNumber(self), options, function(err, chunk) { + if (err) return error(err); + // Set the current chunk + self.currentChunk = chunk == null ? new Chunk(self, { n: 0 }, self.writeConcern) : chunk; + self.currentChunk.position = self.currentChunk.data.length(); + self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata']; + self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; + self.position = self.length; + callback(null, self); + }); + } + } + + // only pass error to callback once + function error(err) { + if (error.err) return; + callback((error.err = err)); + } +}; + +/** + * @ignore + */ +var writeBuffer = function(self, buffer, close, callback) { + if (typeof close === 'function') { + callback = close; + close = null; + } + var finalClose = typeof close === 'boolean' ? close : false; + + if (self.mode !== 'w') { + callback( + MongoError.create({ + message: f( + 'file with id %s not opened for writing', + self.referenceBy === REFERENCE_BY_ID ? self.referenceBy : self.filename + ), + driver: true + }), + null + ); + } else { + if (self.currentChunk.position + buffer.length >= self.chunkSize) { + // Write out the current Chunk and then keep writing until we have less data left than a chunkSize left + // to a new chunk (recursively) + var previousChunkNumber = self.currentChunk.chunkNumber; + var leftOverDataSize = self.chunkSize - self.currentChunk.position; + var firstChunkData = buffer.slice(0, leftOverDataSize); + var leftOverData = buffer.slice(leftOverDataSize); + // A list of chunks to write out + var chunksToWrite = [self.currentChunk.write(firstChunkData)]; + // If we have more data left than the chunk size let's keep writing new chunks + while (leftOverData.length >= self.chunkSize) { + // Create a new chunk and write to it + var newChunk = new Chunk(self, { n: previousChunkNumber + 1 }, self.writeConcern); + firstChunkData = leftOverData.slice(0, self.chunkSize); + leftOverData = leftOverData.slice(self.chunkSize); + // Update chunk number + previousChunkNumber = previousChunkNumber + 1; + // Write data + newChunk.write(firstChunkData); + // Push chunk to save list + chunksToWrite.push(newChunk); + } + + // Set current chunk with remaining data + self.currentChunk = new Chunk(self, { n: previousChunkNumber + 1 }, self.writeConcern); + // If we have left over data write it + if (leftOverData.length > 0) self.currentChunk.write(leftOverData); + + // Update the position for the gridstore + self.position = self.position + buffer.length; + // Total number of chunks to write + var numberOfChunksToWrite = chunksToWrite.length; + + for (var i = 0; i < chunksToWrite.length; i++) { + chunksToWrite[i].save({}, function(err) { + if (err) return callback(err); + + numberOfChunksToWrite = numberOfChunksToWrite - 1; + + if (numberOfChunksToWrite <= 0) { + // We care closing the file before returning + if (finalClose) { + return self.close(function(err) { + callback(err, self); + }); + } + + // Return normally + return callback(null, self); + } + }); + } + } else { + // Update the position for the gridstore + self.position = self.position + buffer.length; + // We have less data than the chunk size just write it and callback + self.currentChunk.write(buffer); + // We care closing the file before returning + if (finalClose) { + return self.close(function(err) { + callback(err, self); + }); + } + // Return normally + return callback(null, self); + } + } +}; + +/** + * Creates a mongoDB object representation of this object. + * + *

+ *        {
+ *          '_id' : , // {number} id for this file
+ *          'filename' : , // {string} name for this file
+ *          'contentType' : , // {string} mime type for this file
+ *          'length' : , // {number} size of this file?
+ *          'chunksize' : , // {number} chunk size used by this file
+ *          'uploadDate' : , // {Date}
+ *          'aliases' : , // {array of string}
+ *          'metadata' : , // {string}
+ *        }
+ *        
+ * + * @ignore + */ +var buildMongoObject = function(self, callback) { + // Calcuate the length + var mongoObject = { + _id: self.fileId, + filename: self.filename, + contentType: self.contentType, + length: self.position ? self.position : 0, + chunkSize: self.chunkSize, + uploadDate: self.uploadDate, + aliases: self.aliases, + metadata: self.metadata + }; + + var md5Command = { filemd5: self.fileId, root: self.root }; + self.db.command(md5Command, function(err, results) { + if (err) return callback(err); + + mongoObject.md5 = results.md5; + callback(null, mongoObject); + }); +}; + +/** + * Gets the nth chunk of this file. + * @ignore + */ +var nthChunk = function(self, chunkNumber, options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + + options = options || self.writeConcern; + options.readPreference = self.readPreference; + // Get the nth chunk + self + .chunkCollection() + .findOne({ files_id: self.fileId, n: chunkNumber }, options, function(err, chunk) { + if (err) return callback(err); + + var finalChunk = chunk == null ? {} : chunk; + callback(null, new Chunk(self, finalChunk, self.writeConcern)); + }); +}; + +/** + * @ignore + */ +var lastChunkNumber = function(self) { + return Math.floor((self.length ? self.length - 1 : 0) / self.chunkSize); +}; + +/** + * Deletes all the chunks of this file in the database. + * + * @ignore + */ +var deleteChunks = function(self, options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + + options = options || self.writeConcern; + + if (self.fileId != null) { + self.chunkCollection().remove({ files_id: self.fileId }, options, function(err) { + if (err) return callback(err, false); + callback(null, true); + }); + } else { + callback(null, true); + } +}; + +/** + * The collection to be used for holding the files and chunks collection. + * + * @classconstant DEFAULT_ROOT_COLLECTION + */ +GridStore.DEFAULT_ROOT_COLLECTION = 'fs'; + +/** + * Default file mime type + * + * @classconstant DEFAULT_CONTENT_TYPE + */ +GridStore.DEFAULT_CONTENT_TYPE = 'binary/octet-stream'; + +/** + * Seek mode where the given length is absolute. + * + * @classconstant IO_SEEK_SET + */ +GridStore.IO_SEEK_SET = 0; + +/** + * Seek mode where the given length is an offset to the current read/write head. + * + * @classconstant IO_SEEK_CUR + */ +GridStore.IO_SEEK_CUR = 1; + +/** + * Seek mode where the given length is an offset to the end of the file. + * + * @classconstant IO_SEEK_END + */ +GridStore.IO_SEEK_END = 2; + +/** + * Checks if a file exists in the database. + * + * @method + * @static + * @param {Db} db the database to query. + * @param {string} name The name of the file to look for. + * @param {string} [rootCollection] The root collection that holds the files and chunks collection. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**. + * @param {object} [options] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~resultCallback} [callback] result from exists. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.exist = function(db, fileIdObject, rootCollection, options, callback) { + var args = Array.prototype.slice.call(arguments, 2); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + rootCollection = args.length ? args.shift() : null; + options = args.length ? args.shift() : {}; + options = options || {}; + + return executeLegacyOperation( + db.s.topology, + exists, + [db, fileIdObject, rootCollection, options, callback], + { skipSessions: true } + ); +}; + +var exists = function(db, fileIdObject, rootCollection, options, callback) { + // Establish read preference + var readPreference = options.readPreference || ReadPreference.PRIMARY; + // Fetch collection + var rootCollectionFinal = + rootCollection != null ? rootCollection : GridStore.DEFAULT_ROOT_COLLECTION; + db.collection(rootCollectionFinal + '.files', function(err, collection) { + if (err) return callback(err); + + // Build query + var query = + typeof fileIdObject === 'string' || + Object.prototype.toString.call(fileIdObject) === '[object RegExp]' + ? { filename: fileIdObject } + : { _id: fileIdObject }; // Attempt to locate file + + // We have a specific query + if ( + fileIdObject != null && + typeof fileIdObject === 'object' && + Object.prototype.toString.call(fileIdObject) !== '[object RegExp]' + ) { + query = fileIdObject; + } + + // Check if the entry exists + collection.findOne(query, { readPreference: readPreference }, function(err, item) { + if (err) return callback(err); + callback(null, item == null ? false : true); + }); + }); +}; + +/** + * Gets the list of files stored in the GridFS. + * + * @method + * @static + * @param {Db} db the database to query. + * @param {string} [rootCollection] The root collection that holds the files and chunks collection. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**. + * @param {object} [options] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~resultCallback} [callback] result from exists. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.list = function(db, rootCollection, options, callback) { + var args = Array.prototype.slice.call(arguments, 1); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + rootCollection = args.length ? args.shift() : null; + options = args.length ? args.shift() : {}; + options = options || {}; + + return executeLegacyOperation(db.s.topology, list, [db, rootCollection, options, callback], { + skipSessions: true + }); +}; + +var list = function(db, rootCollection, options, callback) { + // Ensure we have correct values + if (rootCollection != null && typeof rootCollection === 'object') { + options = rootCollection; + rootCollection = null; + } + + // Establish read preference + var readPreference = options.readPreference || ReadPreference.primary; + // Check if we are returning by id not filename + var byId = options['id'] != null ? options['id'] : false; + // Fetch item + var rootCollectionFinal = + rootCollection != null ? rootCollection : GridStore.DEFAULT_ROOT_COLLECTION; + var items = []; + db.collection(rootCollectionFinal + '.files', function(err, collection) { + if (err) return callback(err); + + collection.find({}, { readPreference: readPreference }, function(err, cursor) { + if (err) return callback(err); + + cursor.each(function(err, item) { + if (item != null) { + items.push(byId ? item._id : item.filename); + } else { + callback(err, items); + } + }); + }); + }); +}; + +/** + * Reads the contents of a file. + * + * This method has the following signatures + * + * (db, name, callback) + * (db, name, length, callback) + * (db, name, length, offset, callback) + * (db, name, length, offset, options, callback) + * + * @method + * @static + * @param {Db} db the database to query. + * @param {string} name The name of the file. + * @param {number} [length] The size of data to read. + * @param {number} [offset] The offset from the head of the file of which to start reading from. + * @param {object} [options] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~readCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.read = function(db, name, length, offset, options, callback) { + var args = Array.prototype.slice.call(arguments, 2); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + length = args.length ? args.shift() : null; + offset = args.length ? args.shift() : null; + options = args.length ? args.shift() : null; + options = options || {}; + + return executeLegacyOperation( + db.s.topology, + readStatic, + [db, name, length, offset, options, callback], + { skipSessions: true } + ); +}; + +var readStatic = function(db, name, length, offset, options, callback) { + new GridStore(db, name, 'r', options).open(function(err, gridStore) { + if (err) return callback(err); + // Make sure we are not reading out of bounds + if (offset && offset >= gridStore.length) + return callback('offset larger than size of file', null); + if (length && length > gridStore.length) + return callback('length is larger than the size of the file', null); + if (offset && length && offset + length > gridStore.length) + return callback('offset and length is larger than the size of the file', null); + + if (offset != null) { + gridStore.seek(offset, function(err, gridStore) { + if (err) return callback(err); + gridStore.read(length, callback); + }); + } else { + gridStore.read(length, callback); + } + }); +}; + +/** + * Read the entire file as a list of strings splitting by the provided separator. + * + * @method + * @static + * @param {Db} db the database to query. + * @param {(String|object)} name the name of the file. + * @param {string} [separator] The character to be recognized as the newline separator. + * @param {object} [options] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~readlinesCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.readlines = function(db, name, separator, options, callback) { + var args = Array.prototype.slice.call(arguments, 2); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + separator = args.length ? args.shift() : null; + options = args.length ? args.shift() : null; + options = options || {}; + + return executeLegacyOperation( + db.s.topology, + readlinesStatic, + [db, name, separator, options, callback], + { skipSessions: true } + ); +}; + +var readlinesStatic = function(db, name, separator, options, callback) { + var finalSeperator = separator == null ? '\n' : separator; + new GridStore(db, name, 'r', options).open(function(err, gridStore) { + if (err) return callback(err); + gridStore.readlines(finalSeperator, callback); + }); +}; + +/** + * Deletes the chunks and metadata information of a file from GridFS. + * + * @method + * @static + * @param {Db} db The database to query. + * @param {(string|array)} names The name/names of the files to delete. + * @param {object} [options] Optional settings. + * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {ClientSession} [options.session] optional session to use for this operation + * @param {GridStore~resultCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + * @deprecated Use GridFSBucket API instead + */ +GridStore.unlink = function(db, names, options, callback) { + var args = Array.prototype.slice.call(arguments, 2); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + options = args.length ? args.shift() : {}; + options = options || {}; + + return executeLegacyOperation(db.s.topology, unlinkStatic, [this, db, names, options, callback], { + skipSessions: true + }); +}; + +var unlinkStatic = function(self, db, names, options, callback) { + // Get the write concern + var writeConcern = _getWriteConcern(db, options); + + // List of names + if (names.constructor === Array) { + var tc = 0; + for (var i = 0; i < names.length; i++) { + ++tc; + GridStore.unlink(db, names[i], options, function() { + if (--tc === 0) { + callback(null, self); + } + }); + } + } else { + new GridStore(db, names, 'w', options).open(function(err, gridStore) { + if (err) return callback(err); + deleteChunks(gridStore, function(err) { + if (err) return callback(err); + gridStore.collection(function(err, collection) { + if (err) return callback(err); + collection.remove({ _id: gridStore.fileId }, writeConcern, function(err) { + callback(err, self); + }); + }); + }); + }); + } +}; + +/** + * @ignore + */ +var _writeNormal = function(self, data, close, options, callback) { + // If we have a buffer write it using the writeBuffer method + if (Buffer.isBuffer(data)) { + return writeBuffer(self, data, close, callback); + } else { + return writeBuffer(self, Buffer.from(data, 'binary'), close, callback); + } +}; + +/** + * @ignore + */ +var _setWriteConcernHash = function(options) { + var finalOptions = {}; + if (options.w != null) finalOptions.w = options.w; + if (options.journal === true) finalOptions.j = options.journal; + if (options.j === true) finalOptions.j = options.j; + if (options.fsync === true) finalOptions.fsync = options.fsync; + if (options.wtimeout != null) finalOptions.wtimeout = options.wtimeout; + return finalOptions; +}; + +/** + * @ignore + */ +var _getWriteConcern = function(self, options) { + // Final options + var finalOptions = { w: 1 }; + options = options || {}; + + // Local options verification + if ( + options.w != null || + typeof options.j === 'boolean' || + typeof options.journal === 'boolean' || + typeof options.fsync === 'boolean' + ) { + finalOptions = _setWriteConcernHash(options); + } else if (options.safe != null && typeof options.safe === 'object') { + finalOptions = _setWriteConcernHash(options.safe); + } else if (typeof options.safe === 'boolean') { + finalOptions = { w: options.safe ? 1 : 0 }; + } else if ( + self.options.w != null || + typeof self.options.j === 'boolean' || + typeof self.options.journal === 'boolean' || + typeof self.options.fsync === 'boolean' + ) { + finalOptions = _setWriteConcernHash(self.options); + } else if ( + self.safe && + (self.safe.w != null || + typeof self.safe.j === 'boolean' || + typeof self.safe.journal === 'boolean' || + typeof self.safe.fsync === 'boolean') + ) { + finalOptions = _setWriteConcernHash(self.safe); + } else if (typeof self.safe === 'boolean') { + finalOptions = { w: self.safe ? 1 : 0 }; + } + + // Ensure we don't have an invalid combination of write concerns + if ( + finalOptions.w < 1 && + (finalOptions.journal === true || finalOptions.j === true || finalOptions.fsync === true) + ) + throw MongoError.create({ + message: 'No acknowledgement using w < 1 cannot be combined with journal:true or fsync:true', + driver: true + }); + + // Return the options + return finalOptions; +}; + +/** + * Create a new GridStoreStream instance (INTERNAL TYPE, do not instantiate directly) + * + * @class + * @extends external:Duplex + * @return {GridStoreStream} a GridStoreStream instance. + * @deprecated Use GridFSBucket API instead + */ +var GridStoreStream = function(gs) { + // Initialize the duplex stream + Duplex.call(this); + + // Get the gridstore + this.gs = gs; + + // End called + this.endCalled = false; + + // If we have a seek + this.totalBytesToRead = this.gs.length - this.gs.position; + this.seekPosition = this.gs.position; +}; + +// +// Inherit duplex +inherits(GridStoreStream, Duplex); + +GridStoreStream.prototype._pipe = GridStoreStream.prototype.pipe; + +// Set up override +GridStoreStream.prototype.pipe = function(destination) { + var self = this; + + // Only open gridstore if not already open + if (!self.gs.isOpen) { + self.gs.open(function(err) { + if (err) return self.emit('error', err); + self.totalBytesToRead = self.gs.length - self.gs.position; + self._pipe.apply(self, [destination]); + }); + } else { + self.totalBytesToRead = self.gs.length - self.gs.position; + self._pipe.apply(self, [destination]); + } + + return destination; +}; + +// Called by stream +GridStoreStream.prototype._read = function() { + var self = this; + + var read = function() { + // Read data + self.gs.read(length, function(err, buffer) { + if (err && !self.endCalled) return self.emit('error', err); + + // Stream is closed + if (self.endCalled || buffer == null) return self.push(null); + // Remove bytes read + if (buffer.length <= self.totalBytesToRead) { + self.totalBytesToRead = self.totalBytesToRead - buffer.length; + self.push(buffer); + } else if (buffer.length > self.totalBytesToRead) { + self.totalBytesToRead = self.totalBytesToRead - buffer._index; + self.push(buffer.slice(0, buffer._index)); + } + + // Finished reading + if (self.totalBytesToRead <= 0) { + self.endCalled = true; + } + }); + }; + + // Set read length + var length = + self.gs.length < self.gs.chunkSize ? self.gs.length - self.seekPosition : self.gs.chunkSize; + if (!self.gs.isOpen) { + self.gs.open(function(err) { + self.totalBytesToRead = self.gs.length - self.gs.position; + if (err) return self.emit('error', err); + read(); + }); + } else { + read(); + } +}; + +GridStoreStream.prototype.destroy = function() { + this.pause(); + this.endCalled = true; + this.gs.close(); + this.emit('end'); +}; + +GridStoreStream.prototype.write = function(chunk) { + var self = this; + if (self.endCalled) + return self.emit( + 'error', + MongoError.create({ message: 'attempting to write to stream after end called', driver: true }) + ); + // Do we have to open the gridstore + if (!self.gs.isOpen) { + self.gs.open(function() { + self.gs.isOpen = true; + self.gs.write(chunk, function() { + process.nextTick(function() { + self.emit('drain'); + }); + }); + }); + return false; + } else { + self.gs.write(chunk, function() { + self.emit('drain'); + }); + return true; + } +}; + +GridStoreStream.prototype.end = function(chunk, encoding, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 0); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + chunk = args.length ? args.shift() : null; + encoding = args.length ? args.shift() : null; + self.endCalled = true; + + if (chunk) { + self.gs.write(chunk, function() { + self.gs.close(function() { + if (typeof callback === 'function') callback(); + self.emit('end'); + }); + }); + } + + self.gs.close(function() { + if (typeof callback === 'function') callback(); + self.emit('end'); + }); +}; + +/** + * The read() method pulls some data out of the internal buffer and returns it. If there is no data available, then it will return null. + * @function external:Duplex#read + * @param {number} size Optional argument to specify how much data to read. + * @return {(String | Buffer | null)} + */ + +/** + * Call this function to cause the stream to return strings of the specified encoding instead of Buffer objects. + * @function external:Duplex#setEncoding + * @param {string} encoding The encoding to use. + * @return {null} + */ + +/** + * This method will cause the readable stream to resume emitting data events. + * @function external:Duplex#resume + * @return {null} + */ + +/** + * This method will cause a stream in flowing-mode to stop emitting data events. Any data that becomes available will remain in the internal buffer. + * @function external:Duplex#pause + * @return {null} + */ + +/** + * This method pulls all the data out of a readable stream, and writes it to the supplied destination, automatically managing the flow so that the destination is not overwhelmed by a fast readable stream. + * @function external:Duplex#pipe + * @param {Writable} destination The destination for writing data + * @param {object} [options] Pipe options + * @return {null} + */ + +/** + * This method will remove the hooks set up for a previous pipe() call. + * @function external:Duplex#unpipe + * @param {Writable} [destination] The destination for writing data + * @return {null} + */ + +/** + * This is useful in certain cases where a stream is being consumed by a parser, which needs to "un-consume" some data that it has optimistically pulled out of the source, so that the stream can be passed on to some other party. + * @function external:Duplex#unshift + * @param {(Buffer|string)} chunk Chunk of data to unshift onto the read queue. + * @return {null} + */ + +/** + * Versions of Node prior to v0.10 had streams that did not implement the entire Streams API as it is today. (See "Compatibility" below for more information.) + * @function external:Duplex#wrap + * @param {Stream} stream An "old style" readable stream. + * @return {null} + */ + +/** + * This method writes some data to the underlying system, and calls the supplied callback once the data has been fully handled. + * @function external:Duplex#write + * @param {(string|Buffer)} chunk The data to write + * @param {string} encoding The encoding, if chunk is a String + * @param {function} callback Callback for when this chunk of data is flushed + * @return {boolean} + */ + +/** + * Call this method when no more data will be written to the stream. If supplied, the callback is attached as a listener on the finish event. + * @function external:Duplex#end + * @param {(string|Buffer)} chunk The data to write + * @param {string} encoding The encoding, if chunk is a String + * @param {function} callback Callback for when this chunk of data is flushed + * @return {null} + */ + +/** + * GridStoreStream stream data event, fired for each document in the cursor. + * + * @event GridStoreStream#data + * @type {object} + */ + +/** + * GridStoreStream stream end event + * + * @event GridStoreStream#end + * @type {null} + */ + +/** + * GridStoreStream stream close event + * + * @event GridStoreStream#close + * @type {null} + */ + +/** + * GridStoreStream stream readable event + * + * @event GridStoreStream#readable + * @type {null} + */ + +/** + * GridStoreStream stream drain event + * + * @event GridStoreStream#drain + * @type {null} + */ + +/** + * GridStoreStream stream finish event + * + * @event GridStoreStream#finish + * @type {null} + */ + +/** + * GridStoreStream stream pipe event + * + * @event GridStoreStream#pipe + * @type {null} + */ + +/** + * GridStoreStream stream unpipe event + * + * @event GridStoreStream#unpipe + * @type {null} + */ + +/** + * GridStoreStream stream error event + * + * @event GridStoreStream#error + * @type {null} + */ + +/** + * @ignore + */ +module.exports = GridStore; diff --git a/scripts/node_modules/mongodb/lib/mongo_client.js b/scripts/node_modules/mongodb/lib/mongo_client.js new file mode 100644 index 00000000..703eda64 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/mongo_client.js @@ -0,0 +1,479 @@ +'use strict'; + +const ChangeStream = require('./change_stream'); +const Db = require('./db'); +const EventEmitter = require('events').EventEmitter; +const executeOperation = require('./operations/execute_operation'); +const inherits = require('util').inherits; +const MongoError = require('./core').MongoError; +const deprecate = require('util').deprecate; +const WriteConcern = require('./write_concern'); +const MongoDBNamespace = require('./utils').MongoDBNamespace; +const ReadPreference = require('./core/topologies/read_preference'); + +// Operations +const ConnectOperation = require('./operations/connect'); +const CloseOperation = require('./operations/close'); + +/** + * @fileOverview The **MongoClient** class is a class that allows for making Connections to MongoDB. + * + * @example + * // Connect using a MongoClient instance + * const MongoClient = require('mongodb').MongoClient; + * const test = require('assert'); + * // Connection url + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * // Connect using MongoClient + * const mongoClient = new MongoClient(url); + * mongoClient.connect(function(err, client) { + * const db = client.db(dbName); + * client.close(); + * }); + * + * @example + * // Connect using the MongoClient.connect static method + * const MongoClient = require('mongodb').MongoClient; + * const test = require('assert'); + * // Connection url + * const url = 'mongodb://localhost:27017'; + * // Database Name + * const dbName = 'test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, client) { + * const db = client.db(dbName); + * client.close(); + * }); + */ + +/** + * A string specifying the level of a ReadConcern + * @typedef {'local'|'available'|'majority'|'linearizable'|'snapshot'} ReadConcernLevel + * @see https://docs.mongodb.com/manual/reference/read-concern/index.html#read-concern-levels + */ + +/** + * Configuration options for a automatic client encryption. + * + * **NOTE**: Support for client side encryption is in beta. Backwards-breaking changes may be made before the final release. + * + * @typedef {Object} AutoEncryptionOptions + * @property {MongoClient} [keyVaultClient] A `MongoClient` used to fetch keys from a key vault + * @property {string} [keyVaultNamespace] The namespace where keys are stored in the key vault + * @property {object} [kmsProviders] Provider details for the desired Key Management Service to use for encryption + * @property {object} [kmsProviders.aws] Optional settings for the AWS KMS provider + * @property {string} [kmsProviders.aws.accessKeyId] The access key used for the AWS KMS provider + * @property {string} [kmsProviders.aws.secretAccessKey] The secret access key used for the AWS KMS provider + * @property {object} [kmsProviders.local] Optional settings for the local KMS provider + * @property {string} [kmsProviders.local.key] The master key used to encrypt/decrypt data keys + * @property {object} [schemaMap] A map of namespaces to a local JSON schema for encryption + * @property {boolean} [bypassAutoEncryption] Allows the user to bypass auto encryption, maintaining implicit decryption + * @property {object} [extraOptions] Extra options related to the mongocryptd process + * @property {string} [extraOptions.mongocryptURI] A local process the driver communicates with to determine how to encrypt values in a command. Defaults to "mongodb://%2Fvar%2Fmongocryptd.sock" if domain sockets are available or "mongodb://localhost:27020" otherwise + * @property {boolean} [extraOptions.mongocryptdBypassSpawn=false] If true, autoEncryption will not attempt to spawn a mongocryptd before connecting + * @property {string} [extraOptions.mongocryptdSpawnPath] The path to the mongocryptd executable on the system + * @property {string[]} [extraOptions.mongocryptdSpawnArgs] Command line arguments to use when auto-spawning a mongocryptd + */ + +/** + * Creates a new MongoClient instance + * @class + * @param {string} url The connection URI string + * @param {object} [options] Optional settings + * @param {number} [options.poolSize=5] The maximum size of the individual server pool + * @param {boolean} [options.ssl=false] Enable SSL connection. + * @param {boolean} [options.sslValidate=false] Validate mongod server certificate against Certificate Authority + * @param {buffer} [options.sslCA=undefined] SSL Certificate store binary buffer + * @param {buffer} [options.sslCert=undefined] SSL Certificate binary buffer + * @param {buffer} [options.sslKey=undefined] SSL Key file binary buffer + * @param {string} [options.sslPass=undefined] SSL Certificate pass phrase + * @param {buffer} [options.sslCRL=undefined] SSL Certificate revocation list binary buffer + * @param {boolean} [options.autoReconnect=true] Enable autoReconnect for single server instances + * @param {boolean} [options.noDelay=true] TCP Connection no delay + * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled + * @param {number} [options.keepAliveInitialDelay=30000] The number of milliseconds to wait before initiating keepAlive on the TCP socket + * @param {number} [options.connectTimeoutMS=30000] TCP Connection timeout setting + * @param {number} [options.family] Version of IP stack. Can be 4, 6 or null (default). + * If null, will attempt to connect with IPv6, and will fall back to IPv4 on failure + * @param {number} [options.socketTimeoutMS=360000] TCP Socket timeout setting + * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times + * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries + * @param {boolean} [options.ha=true] Control if high availability monitoring runs for Replicaset or Mongos proxies + * @param {number} [options.haInterval=10000] The High availability period for replicaset inquiry + * @param {string} [options.replicaSet=undefined] The Replicaset set name + * @param {number} [options.secondaryAcceptableLatencyMS=15] Cutoff latency point in MS for Replicaset member selection + * @param {number} [options.acceptableLatencyMS=15] Cutoff latency point in MS for Mongos proxies selection + * @param {boolean} [options.connectWithNoPrimary=false] Sets if the driver should connect even if no primary is available + * @param {string} [options.authSource=undefined] Define the database to authenticate against + * @param {(number|string)} [options.w] The write concern + * @param {number} [options.wtimeout] The write concern timeout + * @param {boolean} [options.j=false] Specify a journal write concern + * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields + * @param {boolean} [options.raw=false] Return document results as raw BSON buffers + * @param {number} [options.bufferMaxEntries=-1] Sets a cap on how many operations the driver will buffer up before giving up on getting a working connection, default is -1 which is unlimited + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST) + * @param {object} [options.pkFactory] A primary key factory object for generation of custom _id keys + * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {object} [options.readConcern] Specify a read concern for the collection (only MongoDB 3.2 or higher supported) + * @param {ReadConcernLevel} [options.readConcern.level='local'] Specify a read concern level for the collection operations (only MongoDB 3.2 or higher supported) + * @param {number} [options.maxStalenessSeconds=undefined] The max staleness to secondary reads (values under 10 seconds cannot be guaranteed) + * @param {string} [options.loggerLevel=undefined] The logging level (error/warn/info/debug) + * @param {object} [options.logger=undefined] Custom logger object + * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types + * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers + * @param {boolean} [options.promoteLongs=true] Promotes long values to number if they fit inside the 53 bits resolution + * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit + * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function + * @param {object} [options.validateOptions=false] Validate MongoClient passed in options for correctness + * @param {string} [options.appname=undefined] The name of the application that created this MongoClient instance. MongoDB 3.4 and newer will print this value in the server log upon establishing each connection. It is also recorded in the slow query log and profile collections + * @param {string} [options.auth.user=undefined] The username for auth + * @param {string} [options.auth.password=undefined] The password for auth + * @param {string} [options.authMechanism=undefined] Mechanism for authentication: MDEFAULT, GSSAPI, PLAIN, MONGODB-X509, or SCRAM-SHA-1 + * @param {object} [options.compression] Type of compression to use: snappy or zlib + * @param {boolean} [options.fsync=false] Specify a file sync write concern + * @param {array} [options.readPreferenceTags] Read preference tags + * @param {number} [options.numberOfRetries=5] The number of retries for a tailable cursor + * @param {boolean} [options.auto_reconnect=true] Enable auto reconnecting for single server instances + * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this client + * @param {number} [options.minSize] If present, the connection pool will be initialized with minSize connections, and will never dip below minSize connections + * @param {boolean} [options.useNewUrlParser=true] Determines whether or not to use the new url parser. Enables the new, spec-compliant, url parser shipped in the core driver. This url parser fixes a number of problems with the original parser, and aims to outright replace that parser in the near future. Defaults to true, and must be explicitly set to false to use the legacy url parser. + * @param {boolean} [options.useUnifiedTopology] Enables the new unified topology layer + * @param {AutoEncryptionOptions} [options.autoEncryption] Optionally enable client side auto encryption + * @param {MongoClient~connectCallback} [callback] The command result callback + * @return {MongoClient} a MongoClient instance + */ +function MongoClient(url, options) { + if (!(this instanceof MongoClient)) return new MongoClient(url, options); + // Set up event emitter + EventEmitter.call(this); + + // The internal state + this.s = { + url: url, + options: options || {}, + promiseLibrary: null, + dbCache: new Map(), + sessions: new Set(), + writeConcern: WriteConcern.fromOptions(options), + namespace: new MongoDBNamespace('admin') + }; + + // Get the promiseLibrary + const promiseLibrary = this.s.options.promiseLibrary || Promise; + + // Add the promise to the internal state + this.s.promiseLibrary = promiseLibrary; +} + +/** + * @ignore + */ +inherits(MongoClient, EventEmitter); + +Object.defineProperty(MongoClient.prototype, 'writeConcern', { + enumerable: true, + get: function() { + return this.s.writeConcern; + } +}); + +Object.defineProperty(MongoClient.prototype, 'readPreference', { + enumerable: true, + get: function() { + return ReadPreference.primary; + } +}); + +/** + * The callback format for results + * @callback MongoClient~connectCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {MongoClient} client The connected client. + */ + +/** + * Connect to MongoDB using a url as documented at + * + * docs.mongodb.org/manual/reference/connection-string/ + * + * Note that for replicasets the replicaSet query parameter is required in the 2.0 driver + * + * @method + * @param {MongoClient~connectCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +MongoClient.prototype.connect = function(callback) { + if (typeof callback === 'string') { + throw new TypeError('`connect` only accepts a callback'); + } + + const operation = new ConnectOperation(this); + + return executeOperation(this, operation, callback); +}; + +MongoClient.prototype.logout = deprecate(function(options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + if (typeof callback === 'function') callback(null, true); +}, 'Multiple authentication is prohibited on a connected client, please only authenticate once per MongoClient'); + +/** + * Close the db and its underlying connections + * @method + * @param {boolean} [force=false] Force close, emitting no events + * @param {Db~noResultCallback} [callback] The result callback + * @return {Promise} returns Promise if no callback passed + */ +MongoClient.prototype.close = function(force, callback) { + if (typeof force === 'function') (callback = force), (force = false); + const operation = new CloseOperation(this, force); + return executeOperation(this, operation, callback); +}; + +/** + * Create a new Db instance sharing the current socket connections. Be aware that the new db instances are + * related in a parent-child relationship to the original instance so that events are correctly emitted on child + * db instances. Child db instances are cached so performing db('db1') twice will return the same instance. + * You can control these behaviors with the options noListener and returnNonCachedInstance. + * + * @method + * @param {string} [dbName] The name of the database we want to use. If not provided, use database name from connection string. + * @param {object} [options] Optional settings. + * @param {boolean} [options.noListener=false] Do not make the db an event listener to the original connection. + * @param {boolean} [options.returnNonCachedInstance=false] Control if you want to return a cached instance or have a new one created + * @return {Db} + */ +MongoClient.prototype.db = function(dbName, options) { + options = options || {}; + + // Default to db from connection string if not provided + if (!dbName) { + dbName = this.s.options.dbName; + } + + // Copy the options and add out internal override of the not shared flag + const finalOptions = Object.assign({}, this.s.options, options); + + // Do we have the db in the cache already + if (this.s.dbCache.has(dbName) && finalOptions.returnNonCachedInstance !== true) { + return this.s.dbCache.get(dbName); + } + + // Add promiseLibrary + finalOptions.promiseLibrary = this.s.promiseLibrary; + + // If no topology throw an error message + if (!this.topology) { + throw new MongoError('MongoClient must be connected before calling MongoClient.prototype.db'); + } + + // Return the db object + const db = new Db(dbName, this.topology, finalOptions); + + // Add the db to the cache + this.s.dbCache.set(dbName, db); + // Return the database + return db; +}; + +/** + * Check if MongoClient is connected + * + * @method + * @param {object} [options] Optional settings. + * @param {boolean} [options.noListener=false] Do not make the db an event listener to the original connection. + * @param {boolean} [options.returnNonCachedInstance=false] Control if you want to return a cached instance or have a new one created + * @return {boolean} + */ +MongoClient.prototype.isConnected = function(options) { + options = options || {}; + + if (!this.topology) return false; + return this.topology.isConnected(options); +}; + +/** + * Connect to MongoDB using a url as documented at + * + * docs.mongodb.org/manual/reference/connection-string/ + * + * Note that for replicasets the replicaSet query parameter is required in the 2.0 driver + * + * @method + * @static + * @param {string} url The connection URI string + * @param {object} [options] Optional settings + * @param {number} [options.poolSize=5] The maximum size of the individual server pool + * @param {boolean} [options.ssl=false] Enable SSL connection. + * @param {boolean} [options.sslValidate=false] Validate mongod server certificate against Certificate Authority + * @param {buffer} [options.sslCA=undefined] SSL Certificate store binary buffer + * @param {buffer} [options.sslCert=undefined] SSL Certificate binary buffer + * @param {buffer} [options.sslKey=undefined] SSL Key file binary buffer + * @param {string} [options.sslPass=undefined] SSL Certificate pass phrase + * @param {buffer} [options.sslCRL=undefined] SSL Certificate revocation list binary buffer + * @param {boolean} [options.autoReconnect=true] Enable autoReconnect for single server instances + * @param {boolean} [options.noDelay=true] TCP Connection no delay + * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled + * @param {boolean} [options.keepAliveInitialDelay=30000] The number of milliseconds to wait before initiating keepAlive on the TCP socket + * @param {number} [options.connectTimeoutMS=30000] TCP Connection timeout setting + * @param {number} [options.family] Version of IP stack. Can be 4, 6 or null (default). + * If null, will attempt to connect with IPv6, and will fall back to IPv4 on failure + * @param {number} [options.socketTimeoutMS=360000] TCP Socket timeout setting + * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times + * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries + * @param {boolean} [options.ha=true] Control if high availability monitoring runs for Replicaset or Mongos proxies + * @param {number} [options.haInterval=10000] The High availability period for replicaset inquiry + * @param {string} [options.replicaSet=undefined] The Replicaset set name + * @param {number} [options.secondaryAcceptableLatencyMS=15] Cutoff latency point in MS for Replicaset member selection + * @param {number} [options.acceptableLatencyMS=15] Cutoff latency point in MS for Mongos proxies selection + * @param {boolean} [options.connectWithNoPrimary=false] Sets if the driver should connect even if no primary is available + * @param {string} [options.authSource=undefined] Define the database to authenticate against + * @param {(number|string)} [options.w] The write concern + * @param {number} [options.wtimeout] The write concern timeout + * @param {boolean} [options.j=false] Specify a journal write concern + * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields + * @param {boolean} [options.raw=false] Return document results as raw BSON buffers + * @param {number} [options.bufferMaxEntries=-1] Sets a cap on how many operations the driver will buffer up before giving up on getting a working connection, default is -1 which is unlimited + * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST) + * @param {object} [options.pkFactory] A primary key factory object for generation of custom _id keys + * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {object} [options.readConcern] Specify a read concern for the collection (only MongoDB 3.2 or higher supported) + * @param {ReadConcernLevel} [options.readConcern.level='local'] Specify a read concern level for the collection operations (only MongoDB 3.2 or higher supported) + * @param {number} [options.maxStalenessSeconds=undefined] The max staleness to secondary reads (values under 10 seconds cannot be guaranteed) + * @param {string} [options.loggerLevel=undefined] The logging level (error/warn/info/debug) + * @param {object} [options.logger=undefined] Custom logger object + * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types + * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers + * @param {boolean} [options.promoteLongs=true] Promotes long values to number if they fit inside the 53 bits resolution + * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit + * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function + * @param {object} [options.validateOptions=false] Validate MongoClient passed in options for correctness + * @param {string} [options.appname=undefined] The name of the application that created this MongoClient instance. MongoDB 3.4 and newer will print this value in the server log upon establishing each connection. It is also recorded in the slow query log and profile collections + * @param {string} [options.auth.user=undefined] The username for auth + * @param {string} [options.auth.password=undefined] The password for auth + * @param {string} [options.authMechanism=undefined] Mechanism for authentication: MDEFAULT, GSSAPI, PLAIN, MONGODB-X509, or SCRAM-SHA-1 + * @param {object} [options.compression] Type of compression to use: snappy or zlib + * @param {boolean} [options.fsync=false] Specify a file sync write concern + * @param {array} [options.readPreferenceTags] Read preference tags + * @param {number} [options.numberOfRetries=5] The number of retries for a tailable cursor + * @param {boolean} [options.auto_reconnect=true] Enable auto reconnecting for single server instances + * @param {number} [options.minSize] If present, the connection pool will be initialized with minSize connections, and will never dip below minSize connections + * @param {MongoClient~connectCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +MongoClient.connect = function(url, options, callback) { + const args = Array.prototype.slice.call(arguments, 1); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; + options = args.length ? args.shift() : null; + options = options || {}; + + // Create client + const mongoClient = new MongoClient(url, options); + // Execute the connect method + return mongoClient.connect(callback); +}; + +/** + * Starts a new session on the server + * + * @param {SessionOptions} [options] optional settings for a driver session + * @return {ClientSession} the newly established session + */ +MongoClient.prototype.startSession = function(options) { + options = Object.assign({ explicit: true }, options); + if (!this.topology) { + throw new MongoError('Must connect to a server before calling this method'); + } + + if (!this.topology.hasSessionSupport()) { + throw new MongoError('Current topology does not support sessions'); + } + + return this.topology.startSession(options, this.s.options); +}; + +/** + * Runs a given operation with an implicitly created session. The lifetime of the session + * will be handled without the need for user interaction. + * + * NOTE: presently the operation MUST return a Promise (either explicit or implicity as an async function) + * + * @param {Object} [options] Optional settings to be appled to implicitly created session + * @param {Function} operation An operation to execute with an implicitly created session. The signature of this MUST be `(session) => {}` + * @return {Promise} + */ +MongoClient.prototype.withSession = function(options, operation) { + if (typeof options === 'function') (operation = options), (options = undefined); + const session = this.startSession(options); + + let cleanupHandler = (err, result, opts) => { + // prevent multiple calls to cleanupHandler + cleanupHandler = () => { + throw new ReferenceError('cleanupHandler was called too many times'); + }; + + opts = Object.assign({ throw: true }, opts); + session.endSession(); + + if (err) { + if (opts.throw) throw err; + return Promise.reject(err); + } + }; + + try { + const result = operation(session); + return Promise.resolve(result) + .then(result => cleanupHandler(null, result)) + .catch(err => cleanupHandler(err, null, { throw: true })); + } catch (err) { + return cleanupHandler(err, null, { throw: false }); + } +}; +/** + * Create a new Change Stream, watching for new changes (insertions, updates, replacements, deletions, and invalidations) in this cluster. Will ignore all changes to system collections, as well as the local, admin, + * and config databases. + * @method + * @since 3.1.0 + * @param {Array} [pipeline] An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents. + * @param {object} [options] Optional settings + * @param {string} [options.fullDocument='default'] Allowed values: ‘default’, ‘updateLookup’. When set to ‘updateLookup’, the change stream will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred. + * @param {object} [options.resumeAfter] Specifies the logical starting point for the new change stream. This should be the _id field from a previously returned change stream document. + * @param {number} [options.maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a change stream query + * @param {number} [options.batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. + * @param {object} [options.collation] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. + * @param {ReadPreference} [options.readPreference] The read preference. See {@link https://docs.mongodb.com/manual/reference/read-preference|read preference documentation}. + * @param {Timestamp} [options.startAtOperationTime] receive change events that occur after the specified timestamp + * @param {ClientSession} [options.session] optional session to use for this operation + * @return {ChangeStream} a ChangeStream instance. + */ +MongoClient.prototype.watch = function(pipeline, options) { + pipeline = pipeline || []; + options = options || {}; + + // Allow optionally not specifying a pipeline + if (!Array.isArray(pipeline)) { + options = pipeline; + pipeline = []; + } + + return new ChangeStream(this, pipeline, options); +}; + +/** + * Return the mongo client logger + * @method + * @return {Logger} return the mongo client logger + * @ignore + */ +MongoClient.prototype.getLogger = function() { + return this.s.options.logger; +}; + +module.exports = MongoClient; diff --git a/scripts/node_modules/mongodb/lib/operations/add_user.js b/scripts/node_modules/mongodb/lib/operations/add_user.js new file mode 100644 index 00000000..1f3f3a6f --- /dev/null +++ b/scripts/node_modules/mongodb/lib/operations/add_user.js @@ -0,0 +1,96 @@ +'use strict'; + +const Aspect = require('./operation').Aspect; +const CommandOperation = require('./command'); +const defineAspects = require('./operation').defineAspects; +const crypto = require('crypto'); +const handleCallback = require('../utils').handleCallback; +const toError = require('../utils').toError; + +class AddUserOperation extends CommandOperation { + constructor(db, username, password, options) { + super(db, options); + + this.username = username; + this.password = password; + } + + _buildCommand() { + const db = this.db; + const username = this.username; + const password = this.password; + const options = this.options; + + // Get additional values + let roles = Array.isArray(options.roles) ? options.roles : []; + + // If not roles defined print deprecated message + // TODO: handle deprecation properly + if (roles.length === 0) { + console.log('Creating a user without roles is deprecated in MongoDB >= 2.6'); + } + + // Check the db name and add roles if needed + if ( + (db.databaseName.toLowerCase() === 'admin' || options.dbName === 'admin') && + !Array.isArray(options.roles) + ) { + roles = ['root']; + } else if (!Array.isArray(options.roles)) { + roles = ['dbOwner']; + } + + const digestPassword = db.s.topology.lastIsMaster().maxWireVersion >= 7; + + let userPassword = password; + + if (!digestPassword) { + // Use node md5 generator + const md5 = crypto.createHash('md5'); + // Generate keys used for authentication + md5.update(username + ':mongo:' + password); + userPassword = md5.digest('hex'); + } + + // Build the command to execute + const command = { + createUser: username, + customData: options.customData || {}, + roles: roles, + digestPassword + }; + + // No password + if (typeof password === 'string') { + command.pwd = userPassword; + } + + return command; + } + + execute(callback) { + const options = this.options; + + // Error out if digestPassword set + if (options.digestPassword != null) { + return callback( + toError( + "The digestPassword option is not supported via add_user. Please use db.command('createUser', ...) instead for this option." + ) + ); + } + + // Attempt to execute auth command + super.execute((err, r) => { + if (!err) { + return handleCallback(callback, err, r); + } + + return handleCallback(callback, err, null); + }); + } +} + +defineAspects(AddUserOperation, Aspect.WRITE_OPERATION); + +module.exports = AddUserOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/admin_ops.js b/scripts/node_modules/mongodb/lib/operations/admin_ops.js new file mode 100644 index 00000000..b08071c3 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/operations/admin_ops.js @@ -0,0 +1,62 @@ +'use strict'; + +const executeCommand = require('./db_ops').executeCommand; +const executeDbAdminCommand = require('./db_ops').executeDbAdminCommand; + +/** + * Get ReplicaSet status + * + * @param {Admin} a collection instance. + * @param {Object} [options] Optional settings. See Admin.prototype.replSetGetStatus for a list of options. + * @param {Admin~resultCallback} [callback] The command result callback. + */ +function replSetGetStatus(admin, options, callback) { + executeDbAdminCommand(admin.s.db, { replSetGetStatus: 1 }, options, callback); +} + +/** + * Retrieve this db's server status. + * + * @param {Admin} a collection instance. + * @param {Object} [options] Optional settings. See Admin.prototype.serverStatus for a list of options. + * @param {Admin~resultCallback} [callback] The command result callback + */ +function serverStatus(admin, options, callback) { + executeDbAdminCommand(admin.s.db, { serverStatus: 1 }, options, callback); +} + +/** + * Validate an existing collection + * + * @param {Admin} a collection instance. + * @param {string} collectionName The name of the collection to validate. + * @param {Object} [options] Optional settings. See Admin.prototype.validateCollection for a list of options. + * @param {Admin~resultCallback} [callback] The command result callback. + */ +function validateCollection(admin, collectionName, options, callback) { + const command = { validate: collectionName }; + const keys = Object.keys(options); + + // Decorate command with extra options + for (let i = 0; i < keys.length; i++) { + if (options.hasOwnProperty(keys[i]) && keys[i] !== 'session') { + command[keys[i]] = options[keys[i]]; + } + } + + executeCommand(admin.s.db, command, options, (err, doc) => { + if (err != null) return callback(err, null); + + if (doc.ok === 0) return callback(new Error('Error with validate command'), null); + if (doc.result != null && doc.result.constructor !== String) + return callback(new Error('Error with validation data'), null); + if (doc.result != null && doc.result.match(/exception|corrupt/) != null) + return callback(new Error('Error: invalid collection ' + collectionName), null); + if (doc.valid != null && !doc.valid) + return callback(new Error('Error: invalid collection ' + collectionName), null); + + return callback(null, doc); + }); +} + +module.exports = { replSetGetStatus, serverStatus, validateCollection }; diff --git a/scripts/node_modules/mongodb/lib/operations/aggregate.js b/scripts/node_modules/mongodb/lib/operations/aggregate.js new file mode 100644 index 00000000..e0f2da84 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/operations/aggregate.js @@ -0,0 +1,106 @@ +'use strict'; + +const CommandOperationV2 = require('./command_v2'); +const MongoError = require('../core').MongoError; +const maxWireVersion = require('../core/utils').maxWireVersion; +const ReadPreference = require('../core').ReadPreference; +const Aspect = require('./operation').Aspect; +const defineAspects = require('./operation').defineAspects; + +const DB_AGGREGATE_COLLECTION = 1; +const MIN_WIRE_VERSION_$OUT_READ_CONCERN_SUPPORT = 8; + +class AggregateOperation extends CommandOperationV2 { + constructor(parent, pipeline, options) { + super(parent, options, { fullResponse: true }); + + this.target = + parent.s.namespace && parent.s.namespace.collection + ? parent.s.namespace.collection + : DB_AGGREGATE_COLLECTION; + + this.pipeline = pipeline; + + // determine if we have a write stage, override read preference if so + this.hasWriteStage = false; + if (typeof options.out === 'string') { + this.pipeline = this.pipeline.concat({ $out: options.out }); + this.hasWriteStage = true; + } else if (pipeline.length > 0) { + const finalStage = pipeline[pipeline.length - 1]; + if (finalStage.$out || finalStage.$merge) { + this.hasWriteStage = true; + } + } + + if (this.hasWriteStage) { + this.readPreference = ReadPreference.primary; + } + + if (options.explain && (this.readConcern || this.writeConcern)) { + throw new MongoError( + '"explain" cannot be used on an aggregate call with readConcern/writeConcern' + ); + } + + if (options.cursor != null && typeof options.cursor !== 'object') { + throw new MongoError('cursor options must be an object'); + } + } + + get canRetryRead() { + return !this.hasWriteStage; + } + + addToPipeline(stage) { + this.pipeline.push(stage); + } + + execute(server, callback) { + const options = this.options; + const serverWireVersion = maxWireVersion(server); + const command = { aggregate: this.target, pipeline: this.pipeline }; + + if (this.hasWriteStage && serverWireVersion < MIN_WIRE_VERSION_$OUT_READ_CONCERN_SUPPORT) { + this.readConcern = null; + } + + if (serverWireVersion >= 5) { + if (this.hasWriteStage && this.writeConcern) { + Object.assign(command, { writeConcern: this.writeConcern }); + } + } + + if (options.bypassDocumentValidation === true) { + command.bypassDocumentValidation = options.bypassDocumentValidation; + } + + if (typeof options.allowDiskUse === 'boolean') { + command.allowDiskUse = options.allowDiskUse; + } + + if (options.hint) { + command.hint = options.hint; + } + + if (options.explain) { + options.full = false; + command.explain = options.explain; + } + + command.cursor = options.cursor || {}; + if (options.batchSize && !this.hasWriteStage) { + command.cursor.batchSize = options.batchSize; + } + + super.executeCommand(server, command, callback); + } +} + +defineAspects(AggregateOperation, [ + Aspect.READ_OPERATION, + Aspect.RETRYABLE, + Aspect.EXECUTE_WITH_SELECTION +]); + +module.exports = AggregateOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/bulk_write.js b/scripts/node_modules/mongodb/lib/operations/bulk_write.js new file mode 100644 index 00000000..8f14f021 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/operations/bulk_write.js @@ -0,0 +1,104 @@ +'use strict'; + +const applyRetryableWrites = require('../utils').applyRetryableWrites; +const applyWriteConcern = require('../utils').applyWriteConcern; +const MongoError = require('../core').MongoError; +const OperationBase = require('./operation').OperationBase; + +class BulkWriteOperation extends OperationBase { + constructor(collection, operations, options) { + super(options); + + this.collection = collection; + this.operations = operations; + } + + execute(callback) { + const coll = this.collection; + const operations = this.operations; + let options = this.options; + + // Add ignoreUndfined + if (coll.s.options.ignoreUndefined) { + options = Object.assign({}, options); + options.ignoreUndefined = coll.s.options.ignoreUndefined; + } + + // Create the bulk operation + const bulk = + options.ordered === true || options.ordered == null + ? coll.initializeOrderedBulkOp(options) + : coll.initializeUnorderedBulkOp(options); + + // Do we have a collation + let collation = false; + + // for each op go through and add to the bulk + try { + for (let i = 0; i < operations.length; i++) { + // Get the operation type + const key = Object.keys(operations[i])[0]; + // Check if we have a collation + if (operations[i][key].collation) { + collation = true; + } + + // Pass to the raw bulk + bulk.raw(operations[i]); + } + } catch (err) { + return callback(err, null); + } + + // Final options for retryable writes and write concern + let finalOptions = Object.assign({}, options); + finalOptions = applyRetryableWrites(finalOptions, coll.s.db); + finalOptions = applyWriteConcern(finalOptions, { db: coll.s.db, collection: coll }, options); + + const writeCon = finalOptions.writeConcern ? finalOptions.writeConcern : {}; + const capabilities = coll.s.topology.capabilities(); + + // Did the user pass in a collation, check if our write server supports it + if (collation && capabilities && !capabilities.commandsTakeCollation) { + return callback(new MongoError('server/primary/mongos does not support collation')); + } + + // Execute the bulk + bulk.execute(writeCon, finalOptions, (err, r) => { + // We have connection level error + if (!r && err) { + return callback(err, null); + } + + r.insertedCount = r.nInserted; + r.matchedCount = r.nMatched; + r.modifiedCount = r.nModified || 0; + r.deletedCount = r.nRemoved; + r.upsertedCount = r.getUpsertedIds().length; + r.upsertedIds = {}; + r.insertedIds = {}; + + // Update the n + r.n = r.insertedCount; + + // Inserted documents + const inserted = r.getInsertedIds(); + // Map inserted ids + for (let i = 0; i < inserted.length; i++) { + r.insertedIds[inserted[i].index] = inserted[i]._id; + } + + // Upserted documents + const upserted = r.getUpsertedIds(); + // Map upserted ids + for (let i = 0; i < upserted.length; i++) { + r.upsertedIds[upserted[i].index] = upserted[i]._id; + } + + // Return the results + callback(null, r); + }); + } +} + +module.exports = BulkWriteOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/close.js b/scripts/node_modules/mongodb/lib/operations/close.js new file mode 100644 index 00000000..57fdef6f --- /dev/null +++ b/scripts/node_modules/mongodb/lib/operations/close.js @@ -0,0 +1,46 @@ +'use strict'; + +const Aspect = require('./operation').Aspect; +const defineAspects = require('./operation').defineAspects; +const OperationBase = require('./operation').OperationBase; + +class CloseOperation extends OperationBase { + constructor(client, force) { + super(); + this.client = client; + this.force = force; + } + + execute(callback) { + const client = this.client; + const force = this.force; + const completeClose = err => { + client.emit('close', client); + for (const item of client.s.dbCache) { + item[1].emit('close', client); + } + + client.removeAllListeners('close'); + callback(err, null); + }; + + if (client.topology == null) { + completeClose(); + return; + } + + client.topology.close(force, err => { + const autoEncrypter = client.topology.s.options.autoEncrypter; + if (!autoEncrypter) { + completeClose(err); + return; + } + + autoEncrypter.teardown(force, err2 => completeClose(err || err2)); + }); + } +} + +defineAspects(CloseOperation, [Aspect.SKIP_SESSION]); + +module.exports = CloseOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/collection_ops.js b/scripts/node_modules/mongodb/lib/operations/collection_ops.js new file mode 100644 index 00000000..df5995d7 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/operations/collection_ops.js @@ -0,0 +1,374 @@ +'use strict'; + +const applyWriteConcern = require('../utils').applyWriteConcern; +const Code = require('../core').BSON.Code; +const createIndexDb = require('./db_ops').createIndex; +const decorateWithCollation = require('../utils').decorateWithCollation; +const decorateWithReadConcern = require('../utils').decorateWithReadConcern; +const ensureIndexDb = require('./db_ops').ensureIndex; +const evaluate = require('./db_ops').evaluate; +const executeCommand = require('./db_ops').executeCommand; +const resolveReadPreference = require('../utils').resolveReadPreference; +const handleCallback = require('../utils').handleCallback; +const indexInformationDb = require('./db_ops').indexInformation; +const Long = require('../core').BSON.Long; +const MongoError = require('../core').MongoError; +const ReadPreference = require('../core').ReadPreference; +const toError = require('../utils').toError; +const insertDocuments = require('./common_functions').insertDocuments; +const updateDocuments = require('./common_functions').updateDocuments; + +/** + * Group function helper + * @ignore + */ +// var groupFunction = function () { +// var c = db[ns].find(condition); +// var map = new Map(); +// var reduce_function = reduce; +// +// while (c.hasNext()) { +// var obj = c.next(); +// var key = {}; +// +// for (var i = 0, len = keys.length; i < len; ++i) { +// var k = keys[i]; +// key[k] = obj[k]; +// } +// +// var aggObj = map.get(key); +// +// if (aggObj == null) { +// var newObj = Object.extend({}, key); +// aggObj = Object.extend(newObj, initial); +// map.put(key, aggObj); +// } +// +// reduce_function(obj, aggObj); +// } +// +// return { "result": map.values() }; +// }.toString(); +const groupFunction = + 'function () {\nvar c = db[ns].find(condition);\nvar map = new Map();\nvar reduce_function = reduce;\n\nwhile (c.hasNext()) {\nvar obj = c.next();\nvar key = {};\n\nfor (var i = 0, len = keys.length; i < len; ++i) {\nvar k = keys[i];\nkey[k] = obj[k];\n}\n\nvar aggObj = map.get(key);\n\nif (aggObj == null) {\nvar newObj = Object.extend({}, key);\naggObj = Object.extend(newObj, initial);\nmap.put(key, aggObj);\n}\n\nreduce_function(obj, aggObj);\n}\n\nreturn { "result": map.values() };\n}'; + +// Check the update operation to ensure it has atomic operators. +function checkForAtomicOperators(update) { + if (Array.isArray(update)) { + return update.reduce((err, u) => err || checkForAtomicOperators(u), null); + } + + const keys = Object.keys(update); + + // same errors as the server would give for update doc lacking atomic operators + if (keys.length === 0) { + return toError('The update operation document must contain at least one atomic operator.'); + } + + if (keys[0][0] !== '$') { + return toError('the update operation document must contain atomic operators.'); + } +} + +/** + * Create an index on the db and collection. + * + * @method + * @param {Collection} a Collection instance. + * @param {(string|object)} fieldOrSpec Defines the index. + * @param {object} [options] Optional settings. See Collection.prototype.createIndex for a list of options. + * @param {Collection~resultCallback} [callback] The command result callback + */ +function createIndex(coll, fieldOrSpec, options, callback) { + createIndexDb(coll.s.db, coll.collectionName, fieldOrSpec, options, callback); +} + +/** + * Create multiple indexes in the collection. This method is only supported for + * MongoDB 2.6 or higher. Earlier version of MongoDB will throw a command not supported + * error. Index specifications are defined at http://docs.mongodb.org/manual/reference/command/createIndexes/. + * + * @method + * @param {Collection} a Collection instance. + * @param {array} indexSpecs An array of index specifications to be created + * @param {Object} [options] Optional settings. See Collection.prototype.createIndexes for a list of options. + * @param {Collection~resultCallback} [callback] The command result callback + */ +function createIndexes(coll, indexSpecs, options, callback) { + const capabilities = coll.s.topology.capabilities(); + + // Ensure we generate the correct name if the parameter is not set + for (let i = 0; i < indexSpecs.length; i++) { + if (indexSpecs[i].name == null) { + const keys = []; + + // Did the user pass in a collation, check if our write server supports it + if (indexSpecs[i].collation && capabilities && !capabilities.commandsTakeCollation) { + return callback(new MongoError('server/primary/mongos does not support collation')); + } + + for (let name in indexSpecs[i].key) { + keys.push(`${name}_${indexSpecs[i].key[name]}`); + } + + // Set the name + indexSpecs[i].name = keys.join('_'); + } + } + + options = Object.assign({}, options, { readPreference: ReadPreference.PRIMARY }); + + // Execute the index + executeCommand( + coll.s.db, + { + createIndexes: coll.collectionName, + indexes: indexSpecs + }, + options, + callback + ); +} + +/** + * Ensure that an index exists. If the index does not exist, this function creates it. + * + * @method + * @param {Collection} a Collection instance. + * @param {(string|object)} fieldOrSpec Defines the index. + * @param {object} [options] Optional settings. See Collection.prototype.ensureIndex for a list of options. + * @param {Collection~resultCallback} [callback] The command result callback + */ +function ensureIndex(coll, fieldOrSpec, options, callback) { + ensureIndexDb(coll.s.db, coll.collectionName, fieldOrSpec, options, callback); +} + +/** + * Run a group command across a collection. + * + * @method + * @param {Collection} a Collection instance. + * @param {(object|array|function|code)} keys An object, array or function expressing the keys to group by. + * @param {object} condition An optional condition that must be true for a row to be considered. + * @param {object} initial Initial value of the aggregation counter object. + * @param {(function|Code)} reduce The reduce function aggregates (reduces) the objects iterated + * @param {(function|Code)} finalize An optional function to be run on each item in the result set just before the item is returned. + * @param {boolean} command Specify if you wish to run using the internal group command or using eval, default is true. + * @param {object} [options] Optional settings. See Collection.prototype.group for a list of options. + * @param {Collection~resultCallback} [callback] The command result callback + * @deprecated MongoDB 3.6 or higher will no longer support the group command. We recommend rewriting using the aggregation framework. + */ +function group(coll, keys, condition, initial, reduce, finalize, command, options, callback) { + // Execute using the command + if (command) { + const reduceFunction = reduce && reduce._bsontype === 'Code' ? reduce : new Code(reduce); + + const selector = { + group: { + ns: coll.collectionName, + $reduce: reduceFunction, + cond: condition, + initial: initial, + out: 'inline' + } + }; + + // if finalize is defined + if (finalize != null) selector.group['finalize'] = finalize; + // Set up group selector + if ('function' === typeof keys || (keys && keys._bsontype === 'Code')) { + selector.group.$keyf = keys && keys._bsontype === 'Code' ? keys : new Code(keys); + } else { + const hash = {}; + keys.forEach(key => { + hash[key] = 1; + }); + selector.group.key = hash; + } + + options = Object.assign({}, options); + // Ensure we have the right read preference inheritance + options.readPreference = resolveReadPreference(coll, options); + + // Do we have a readConcern specified + decorateWithReadConcern(selector, coll, options); + + // Have we specified collation + try { + decorateWithCollation(selector, coll, options); + } catch (err) { + return callback(err, null); + } + + // Execute command + executeCommand(coll.s.db, selector, options, (err, result) => { + if (err) return handleCallback(callback, err, null); + handleCallback(callback, null, result.retval); + }); + } else { + // Create execution scope + const scope = reduce != null && reduce._bsontype === 'Code' ? reduce.scope : {}; + + scope.ns = coll.collectionName; + scope.keys = keys; + scope.condition = condition; + scope.initial = initial; + + // Pass in the function text to execute within mongodb. + const groupfn = groupFunction.replace(/ reduce;/, reduce.toString() + ';'); + + evaluate(coll.s.db, new Code(groupfn, scope), null, options, (err, results) => { + if (err) return handleCallback(callback, err, null); + handleCallback(callback, null, results.result || results); + }); + } +} + +/** + * Retrieve all the indexes on the collection. + * + * @method + * @param {Collection} a Collection instance. + * @param {Object} [options] Optional settings. See Collection.prototype.indexes for a list of options. + * @param {Collection~resultCallback} [callback] The command result callback + */ +function indexes(coll, options, callback) { + options = Object.assign({}, { full: true }, options); + indexInformationDb(coll.s.db, coll.collectionName, options, callback); +} + +/** + * Check if one or more indexes exist on the collection. This fails on the first index that doesn't exist. + * + * @method + * @param {Collection} a Collection instance. + * @param {(string|array)} indexes One or more index names to check. + * @param {Object} [options] Optional settings. See Collection.prototype.indexExists for a list of options. + * @param {Collection~resultCallback} [callback] The command result callback + */ +function indexExists(coll, indexes, options, callback) { + indexInformation(coll, options, (err, indexInformation) => { + // If we have an error return + if (err != null) return handleCallback(callback, err, null); + // Let's check for the index names + if (!Array.isArray(indexes)) + return handleCallback(callback, null, indexInformation[indexes] != null); + // Check in list of indexes + for (let i = 0; i < indexes.length; i++) { + if (indexInformation[indexes[i]] == null) { + return handleCallback(callback, null, false); + } + } + + // All keys found return true + return handleCallback(callback, null, true); + }); +} + +/** + * Retrieve this collection's index info. + * + * @method + * @param {Collection} a Collection instance. + * @param {object} [options] Optional settings. See Collection.prototype.indexInformation for a list of options. + * @param {Collection~resultCallback} [callback] The command result callback + */ +function indexInformation(coll, options, callback) { + indexInformationDb(coll.s.db, coll.collectionName, options, callback); +} + +/** + * Return N parallel cursors for a collection to allow parallel reading of the entire collection. There are + * no ordering guarantees for returned results. + * + * @method + * @param {Collection} a Collection instance. + * @param {object} [options] Optional settings. See Collection.prototype.parallelCollectionScan for a list of options. + * @param {Collection~parallelCollectionScanCallback} [callback] The command result callback + */ +function parallelCollectionScan(coll, options, callback) { + // Create command object + const commandObject = { + parallelCollectionScan: coll.collectionName, + numCursors: options.numCursors + }; + + // Do we have a readConcern specified + decorateWithReadConcern(commandObject, coll, options); + + // Store the raw value + const raw = options.raw; + delete options['raw']; + + // Execute the command + executeCommand(coll.s.db, commandObject, options, (err, result) => { + if (err) return handleCallback(callback, err, null); + if (result == null) + return handleCallback( + callback, + new Error('no result returned for parallelCollectionScan'), + null + ); + + options = Object.assign({ explicitlyIgnoreSession: true }, options); + + const cursors = []; + // Add the raw back to the option + if (raw) options.raw = raw; + // Create command cursors for each item + for (let i = 0; i < result.cursors.length; i++) { + const rawId = result.cursors[i].cursor.id; + // Convert cursorId to Long if needed + const cursorId = typeof rawId === 'number' ? Long.fromNumber(rawId) : rawId; + // Add a command cursor + cursors.push(coll.s.topology.cursor(coll.namespace, cursorId, options)); + } + + handleCallback(callback, null, cursors); + }); +} + +/** + * Save a document. + * + * @method + * @param {Collection} a Collection instance. + * @param {object} doc Document to save + * @param {object} [options] Optional settings. See Collection.prototype.save for a list of options. + * @param {Collection~writeOpCallback} [callback] The command result callback + * @deprecated use insertOne, insertMany, updateOne or updateMany + */ +function save(coll, doc, options, callback) { + // Get the write concern options + const finalOptions = applyWriteConcern( + Object.assign({}, options), + { db: coll.s.db, collection: coll }, + options + ); + // Establish if we need to perform an insert or update + if (doc._id != null) { + finalOptions.upsert = true; + return updateDocuments(coll, { _id: doc._id }, doc, finalOptions, callback); + } + + // Insert the document + insertDocuments(coll, [doc], finalOptions, (err, result) => { + if (callback == null) return; + if (doc == null) return handleCallback(callback, null, null); + if (err) return handleCallback(callback, err, null); + handleCallback(callback, null, result); + }); +} + +module.exports = { + checkForAtomicOperators, + createIndex, + createIndexes, + ensureIndex, + group, + indexes, + indexExists, + indexInformation, + parallelCollectionScan, + save +}; diff --git a/scripts/node_modules/mongodb/lib/operations/collections.js b/scripts/node_modules/mongodb/lib/operations/collections.js new file mode 100644 index 00000000..eac690a2 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/operations/collections.js @@ -0,0 +1,55 @@ +'use strict'; + +const OperationBase = require('./operation').OperationBase; +const handleCallback = require('../utils').handleCallback; + +let collection; +function loadCollection() { + if (!collection) { + collection = require('../collection'); + } + return collection; +} + +class CollectionsOperation extends OperationBase { + constructor(db, options) { + super(options); + + this.db = db; + } + + execute(callback) { + const db = this.db; + let options = this.options; + + let Collection = loadCollection(); + + options = Object.assign({}, options, { nameOnly: true }); + // Let's get the collection names + db.listCollections({}, options).toArray((err, documents) => { + if (err != null) return handleCallback(callback, err, null); + // Filter collections removing any illegal ones + documents = documents.filter(doc => { + return doc.name.indexOf('$') === -1; + }); + + // Return the collection objects + handleCallback( + callback, + null, + documents.map(d => { + return new Collection( + db, + db.s.topology, + db.databaseName, + d.name, + db.s.pkFactory, + db.s.options + ); + }) + ); + }); + } +} + +module.exports = CollectionsOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/command.js b/scripts/node_modules/mongodb/lib/operations/command.js new file mode 100644 index 00000000..3c795bef --- /dev/null +++ b/scripts/node_modules/mongodb/lib/operations/command.js @@ -0,0 +1,120 @@ +'use strict'; + +const Aspect = require('./operation').Aspect; +const OperationBase = require('./operation').OperationBase; +const applyWriteConcern = require('../utils').applyWriteConcern; +const debugOptions = require('../utils').debugOptions; +const handleCallback = require('../utils').handleCallback; +const MongoError = require('../core').MongoError; +const ReadPreference = require('../core').ReadPreference; +const resolveReadPreference = require('../utils').resolveReadPreference; +const MongoDBNamespace = require('../utils').MongoDBNamespace; + +const debugFields = [ + 'authSource', + 'w', + 'wtimeout', + 'j', + 'native_parser', + 'forceServerObjectId', + 'serializeFunctions', + 'raw', + 'promoteLongs', + 'promoteValues', + 'promoteBuffers', + 'bufferMaxEntries', + 'numberOfRetries', + 'retryMiliSeconds', + 'readPreference', + 'pkFactory', + 'parentDb', + 'promiseLibrary', + 'noListener' +]; + +class CommandOperation extends OperationBase { + constructor(db, options, collection, command) { + super(options); + + if (!this.hasAspect(Aspect.WRITE_OPERATION)) { + if (collection != null) { + this.options.readPreference = resolveReadPreference(collection, options); + } else { + this.options.readPreference = resolveReadPreference(db, options); + } + } else { + if (collection != null) { + applyWriteConcern(this.options, { db, coll: collection }, this.options); + } else { + applyWriteConcern(this.options, { db }, this.options); + } + this.options.readPreference = ReadPreference.primary; + } + + this.db = db; + + if (command != null) { + this.command = command; + } + + if (collection != null) { + this.collection = collection; + } + } + + _buildCommand() { + if (this.command != null) { + return this.command; + } + } + + execute(callback) { + const db = this.db; + const options = Object.assign({}, this.options); + + // Did the user destroy the topology + if (db.serverConfig && db.serverConfig.isDestroyed()) { + return callback(new MongoError('topology was destroyed')); + } + + let command; + try { + command = this._buildCommand(); + } catch (e) { + return callback(e); + } + + // Get the db name we are executing against + const dbName = options.dbName || options.authdb || db.databaseName; + + // Convert the readPreference if its not a write + if (this.hasAspect(Aspect.WRITE_OPERATION)) { + if (options.writeConcern && (!options.session || !options.session.inTransaction())) { + command.writeConcern = options.writeConcern; + } + } + + // Debug information + if (db.s.logger.isDebug()) { + db.s.logger.debug( + `executing command ${JSON.stringify( + command + )} against ${dbName}.$cmd with options [${JSON.stringify( + debugOptions(debugFields, options) + )}]` + ); + } + + const namespace = + this.namespace != null ? this.namespace : new MongoDBNamespace(dbName, '$cmd'); + + // Execute command + db.s.topology.command(namespace, command, options, (err, result) => { + if (err) return handleCallback(callback, err); + if (options.full) return handleCallback(callback, null, result); + handleCallback(callback, null, result.result); + }); + } +} + +module.exports = CommandOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/command_v2.js b/scripts/node_modules/mongodb/lib/operations/command_v2.js new file mode 100644 index 00000000..8df703fd --- /dev/null +++ b/scripts/node_modules/mongodb/lib/operations/command_v2.js @@ -0,0 +1,109 @@ +'use strict'; + +const Aspect = require('./operation').Aspect; +const OperationBase = require('./operation').OperationBase; +const resolveReadPreference = require('../utils').resolveReadPreference; +const ReadConcern = require('../read_concern'); +const WriteConcern = require('../write_concern'); +const maxWireVersion = require('../core/utils').maxWireVersion; +const commandSupportsReadConcern = require('../core/sessions').commandSupportsReadConcern; +const MongoError = require('../error').MongoError; + +const SUPPORTS_WRITE_CONCERN_AND_COLLATION = 5; + +class CommandOperationV2 extends OperationBase { + constructor(parent, options, operationOptions) { + super(options); + + this.ns = parent.s.namespace.withCollection('$cmd'); + this.readPreference = resolveReadPreference(parent, this.options); + this.readConcern = resolveReadConcern(parent, this.options); + this.writeConcern = resolveWriteConcern(parent, this.options); + this.explain = false; + + if (operationOptions && typeof operationOptions.fullResponse === 'boolean') { + this.fullResponse = true; + } + + // TODO: A lot of our code depends on having the read preference in the options. This should + // go away, but also requires massive test rewrites. + this.options.readPreference = this.readPreference; + + // TODO(NODE-2056): make logger another "inheritable" property + if (parent.s.logger) { + this.logger = parent.s.logger; + } else if (parent.s.db && parent.s.db.logger) { + this.logger = parent.s.db.logger; + } + } + + executeCommand(server, cmd, callback) { + // TODO: consider making this a non-enumerable property + this.server = server; + + const options = this.options; + const serverWireVersion = maxWireVersion(server); + const inTransaction = this.session && this.session.inTransaction(); + + if (this.readConcern && commandSupportsReadConcern(cmd) && !inTransaction) { + Object.assign(cmd, { readConcern: this.readConcern }); + } + + if (options.collation && serverWireVersion < SUPPORTS_WRITE_CONCERN_AND_COLLATION) { + callback( + new MongoError( + `Server ${ + server.name + }, which reports wire version ${serverWireVersion}, does not support collation` + ) + ); + return; + } + + if (serverWireVersion >= SUPPORTS_WRITE_CONCERN_AND_COLLATION) { + if (this.writeConcern && this.hasAspect(Aspect.WRITE_OPERATION)) { + Object.assign(cmd, { writeConcern: this.writeConcern }); + } + + if (options.collation && typeof options.collation === 'object') { + Object.assign(cmd, { collation: options.collation }); + } + } + + if (typeof options.maxTimeMS === 'number') { + cmd.maxTimeMS = options.maxTimeMS; + } + + if (typeof options.comment === 'string') { + cmd.comment = options.comment; + } + + if (this.logger && this.logger.isDebug()) { + this.logger.debug(`executing command ${JSON.stringify(cmd)} against ${this.ns}`); + } + + server.command(this.ns.toString(), cmd, this.options, (err, result) => { + if (err) { + callback(err, null); + return; + } + + if (this.fullResponse) { + callback(null, result); + return; + } + + callback(null, result.result); + }); + } +} + +function resolveWriteConcern(parent, options) { + return WriteConcern.fromOptions(options) || parent.writeConcern; +} + +function resolveReadConcern(parent, options) { + return ReadConcern.fromOptions(options) || parent.readConcern; +} + +module.exports = CommandOperationV2; diff --git a/scripts/node_modules/mongodb/lib/operations/common_functions.js b/scripts/node_modules/mongodb/lib/operations/common_functions.js new file mode 100644 index 00000000..20c2bc9a --- /dev/null +++ b/scripts/node_modules/mongodb/lib/operations/common_functions.js @@ -0,0 +1,406 @@ +'use strict'; + +const applyRetryableWrites = require('../utils').applyRetryableWrites; +const applyWriteConcern = require('../utils').applyWriteConcern; +const decorateWithCollation = require('../utils').decorateWithCollation; +const decorateWithReadConcern = require('../utils').decorateWithReadConcern; +const executeCommand = require('./db_ops').executeCommand; +const formattedOrderClause = require('../utils').formattedOrderClause; +const handleCallback = require('../utils').handleCallback; +const MongoError = require('../core').MongoError; +const ReadPreference = require('../core').ReadPreference; +const toError = require('../utils').toError; +const CursorState = require('../core/cursor').CursorState; + +/** + * Build the count command. + * + * @method + * @param {collectionOrCursor} an instance of a collection or cursor + * @param {object} query The query for the count. + * @param {object} [options] Optional settings. See Collection.prototype.count and Cursor.prototype.count for a list of options. + */ +function buildCountCommand(collectionOrCursor, query, options) { + const skip = options.skip; + const limit = options.limit; + let hint = options.hint; + const maxTimeMS = options.maxTimeMS; + query = query || {}; + + // Final query + const cmd = { + count: options.collectionName, + query: query + }; + + if (collectionOrCursor.s.numberOfRetries) { + // collectionOrCursor is a cursor + if (collectionOrCursor.options.hint) { + hint = collectionOrCursor.options.hint; + } else if (collectionOrCursor.cmd.hint) { + hint = collectionOrCursor.cmd.hint; + } + decorateWithCollation(cmd, collectionOrCursor, collectionOrCursor.cmd); + } else { + decorateWithCollation(cmd, collectionOrCursor, options); + } + + // Add limit, skip and maxTimeMS if defined + if (typeof skip === 'number') cmd.skip = skip; + if (typeof limit === 'number') cmd.limit = limit; + if (typeof maxTimeMS === 'number') cmd.maxTimeMS = maxTimeMS; + if (hint) cmd.hint = hint; + + // Do we have a readConcern specified + decorateWithReadConcern(cmd, collectionOrCursor); + + return cmd; +} + +function deleteCallback(err, r, callback) { + if (callback == null) return; + if (err && callback) return callback(err); + if (r == null) return callback(null, { result: { ok: 1 } }); + r.deletedCount = r.result.n; + if (callback) callback(null, r); +} + +/** + * Find and update a document. + * + * @method + * @param {Collection} a Collection instance. + * @param {object} query Query object to locate the object to modify. + * @param {array} sort If multiple docs match, choose the first one in the specified sort order as the object to manipulate. + * @param {object} doc The fields/vals to be updated. + * @param {object} [options] Optional settings. See Collection.prototype.findAndModify for a list of options. + * @param {Collection~findAndModifyCallback} [callback] The command result callback + * @deprecated use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead + */ +function findAndModify(coll, query, sort, doc, options, callback) { + // Create findAndModify command object + const queryObject = { + findAndModify: coll.collectionName, + query: query + }; + + sort = formattedOrderClause(sort); + if (sort) { + queryObject.sort = sort; + } + + queryObject.new = options.new ? true : false; + queryObject.remove = options.remove ? true : false; + queryObject.upsert = options.upsert ? true : false; + + const projection = options.projection || options.fields; + + if (projection) { + queryObject.fields = projection; + } + + if (options.arrayFilters) { + queryObject.arrayFilters = options.arrayFilters; + delete options.arrayFilters; + } + + if (doc && !options.remove) { + queryObject.update = doc; + } + + if (options.maxTimeMS) queryObject.maxTimeMS = options.maxTimeMS; + + // Either use override on the function, or go back to default on either the collection + // level or db + options.serializeFunctions = options.serializeFunctions || coll.s.serializeFunctions; + + // No check on the documents + options.checkKeys = false; + + // Final options for retryable writes and write concern + let finalOptions = Object.assign({}, options); + finalOptions = applyRetryableWrites(finalOptions, coll.s.db); + finalOptions = applyWriteConcern(finalOptions, { db: coll.s.db, collection: coll }, options); + + // Decorate the findAndModify command with the write Concern + if (finalOptions.writeConcern) { + queryObject.writeConcern = finalOptions.writeConcern; + } + + // Have we specified bypassDocumentValidation + if (finalOptions.bypassDocumentValidation === true) { + queryObject.bypassDocumentValidation = finalOptions.bypassDocumentValidation; + } + + finalOptions.readPreference = ReadPreference.primary; + + // Have we specified collation + try { + decorateWithCollation(queryObject, coll, finalOptions); + } catch (err) { + return callback(err, null); + } + + // Execute the command + executeCommand(coll.s.db, queryObject, finalOptions, (err, result) => { + if (err) return handleCallback(callback, err, null); + + return handleCallback(callback, null, result); + }); +} + +/** + * Retrieves this collections index info. + * + * @method + * @param {Db} db The Db instance on which to retrieve the index info. + * @param {string} name The name of the collection. + * @param {object} [options] Optional settings. See Db.prototype.indexInformation for a list of options. + * @param {Db~resultCallback} [callback] The command result callback + */ +function indexInformation(db, name, options, callback) { + // If we specified full information + const full = options['full'] == null ? false : options['full']; + + // Did the user destroy the topology + if (db.serverConfig && db.serverConfig.isDestroyed()) + return callback(new MongoError('topology was destroyed')); + // Process all the results from the index command and collection + function processResults(indexes) { + // Contains all the information + let info = {}; + // Process all the indexes + for (let i = 0; i < indexes.length; i++) { + const index = indexes[i]; + // Let's unpack the object + info[index.name] = []; + for (let name in index.key) { + info[index.name].push([name, index.key[name]]); + } + } + + return info; + } + + // Get the list of indexes of the specified collection + db + .collection(name) + .listIndexes(options) + .toArray((err, indexes) => { + if (err) return callback(toError(err)); + if (!Array.isArray(indexes)) return handleCallback(callback, null, []); + if (full) return handleCallback(callback, null, indexes); + handleCallback(callback, null, processResults(indexes)); + }); +} + +function prepareDocs(coll, docs, options) { + const forceServerObjectId = + typeof options.forceServerObjectId === 'boolean' + ? options.forceServerObjectId + : coll.s.db.options.forceServerObjectId; + + // no need to modify the docs if server sets the ObjectId + if (forceServerObjectId === true) { + return docs; + } + + return docs.map(doc => { + if (forceServerObjectId !== true && doc._id == null) { + doc._id = coll.s.pkFactory.createPk(); + } + + return doc; + }); +} + +// Get the next available document from the cursor, returns null if no more documents are available. +function nextObject(cursor, callback) { + if (cursor.s.state === CursorState.CLOSED || (cursor.isDead && cursor.isDead())) { + return handleCallback( + callback, + MongoError.create({ message: 'Cursor is closed', driver: true }) + ); + } + + if (cursor.s.state === CursorState.INIT && cursor.cmd && cursor.cmd.sort) { + try { + cursor.cmd.sort = formattedOrderClause(cursor.cmd.sort); + } catch (err) { + return handleCallback(callback, err); + } + } + + // Get the next object + cursor._next((err, doc) => { + cursor.s.state = CursorState.OPEN; + if (err) return handleCallback(callback, err); + handleCallback(callback, null, doc); + }); +} + +function insertDocuments(coll, docs, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + // Ensure we are operating on an array op docs + docs = Array.isArray(docs) ? docs : [docs]; + + // Final options for retryable writes and write concern + let finalOptions = Object.assign({}, options); + finalOptions = applyRetryableWrites(finalOptions, coll.s.db); + finalOptions = applyWriteConcern(finalOptions, { db: coll.s.db, collection: coll }, options); + + // If keep going set unordered + if (finalOptions.keepGoing === true) finalOptions.ordered = false; + finalOptions.serializeFunctions = options.serializeFunctions || coll.s.serializeFunctions; + + docs = prepareDocs(coll, docs, options); + + // File inserts + coll.s.topology.insert(coll.s.namespace, docs, finalOptions, (err, result) => { + if (callback == null) return; + if (err) return handleCallback(callback, err); + if (result == null) return handleCallback(callback, null, null); + if (result.result.code) return handleCallback(callback, toError(result.result)); + if (result.result.writeErrors) + return handleCallback(callback, toError(result.result.writeErrors[0])); + // Add docs to the list + result.ops = docs; + // Return the results + handleCallback(callback, null, result); + }); +} + +function removeDocuments(coll, selector, options, callback) { + if (typeof options === 'function') { + (callback = options), (options = {}); + } else if (typeof selector === 'function') { + callback = selector; + options = {}; + selector = {}; + } + + // Create an empty options object if the provided one is null + options = options || {}; + + // Final options for retryable writes and write concern + let finalOptions = Object.assign({}, options); + finalOptions = applyRetryableWrites(finalOptions, coll.s.db); + finalOptions = applyWriteConcern(finalOptions, { db: coll.s.db, collection: coll }, options); + + // If selector is null set empty + if (selector == null) selector = {}; + + // Build the op + const op = { q: selector, limit: 0 }; + if (options.single) { + op.limit = 1; + } else if (finalOptions.retryWrites) { + finalOptions.retryWrites = false; + } + + // Have we specified collation + try { + decorateWithCollation(finalOptions, coll, options); + } catch (err) { + return callback(err, null); + } + + // Execute the remove + coll.s.topology.remove(coll.s.namespace, [op], finalOptions, (err, result) => { + if (callback == null) return; + if (err) return handleCallback(callback, err, null); + if (result == null) return handleCallback(callback, null, null); + if (result.result.code) return handleCallback(callback, toError(result.result)); + if (result.result.writeErrors) { + return handleCallback(callback, toError(result.result.writeErrors[0])); + } + + // Return the results + handleCallback(callback, null, result); + }); +} + +function updateDocuments(coll, selector, document, options, callback) { + if ('function' === typeof options) (callback = options), (options = null); + if (options == null) options = {}; + if (!('function' === typeof callback)) callback = null; + + // If we are not providing a selector or document throw + if (selector == null || typeof selector !== 'object') + return callback(toError('selector must be a valid JavaScript object')); + if (document == null || typeof document !== 'object') + return callback(toError('document must be a valid JavaScript object')); + + // Final options for retryable writes and write concern + let finalOptions = Object.assign({}, options); + finalOptions = applyRetryableWrites(finalOptions, coll.s.db); + finalOptions = applyWriteConcern(finalOptions, { db: coll.s.db, collection: coll }, options); + + // Do we return the actual result document + // Either use override on the function, or go back to default on either the collection + // level or db + finalOptions.serializeFunctions = options.serializeFunctions || coll.s.serializeFunctions; + + // Execute the operation + const op = { q: selector, u: document }; + op.upsert = options.upsert !== void 0 ? !!options.upsert : false; + op.multi = options.multi !== void 0 ? !!options.multi : false; + + if (finalOptions.arrayFilters) { + op.arrayFilters = finalOptions.arrayFilters; + delete finalOptions.arrayFilters; + } + + if (finalOptions.retryWrites && op.multi) { + finalOptions.retryWrites = false; + } + + // Have we specified collation + try { + decorateWithCollation(finalOptions, coll, options); + } catch (err) { + return callback(err, null); + } + + // Update options + coll.s.topology.update(coll.s.namespace, [op], finalOptions, (err, result) => { + if (callback == null) return; + if (err) return handleCallback(callback, err, null); + if (result == null) return handleCallback(callback, null, null); + if (result.result.code) return handleCallback(callback, toError(result.result)); + if (result.result.writeErrors) + return handleCallback(callback, toError(result.result.writeErrors[0])); + // Return the results + handleCallback(callback, null, result); + }); +} + +function updateCallback(err, r, callback) { + if (callback == null) return; + if (err) return callback(err); + if (r == null) return callback(null, { result: { ok: 1 } }); + r.modifiedCount = r.result.nModified != null ? r.result.nModified : r.result.n; + r.upsertedId = + Array.isArray(r.result.upserted) && r.result.upserted.length > 0 + ? r.result.upserted[0] // FIXME(major): should be `r.result.upserted[0]._id` + : null; + r.upsertedCount = + Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0; + r.matchedCount = + Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? 0 : r.result.n; + callback(null, r); +} + +module.exports = { + buildCountCommand, + deleteCallback, + findAndModify, + indexInformation, + nextObject, + prepareDocs, + insertDocuments, + removeDocuments, + updateDocuments, + updateCallback +}; diff --git a/scripts/node_modules/mongodb/lib/operations/connect.js b/scripts/node_modules/mongodb/lib/operations/connect.js new file mode 100644 index 00000000..e8f25187 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/operations/connect.js @@ -0,0 +1,709 @@ +'use strict'; + +const OperationBase = require('./operation').OperationBase; +const defineAspects = require('./operation').defineAspects; +const Aspect = require('./operation').Aspect; +const deprecate = require('util').deprecate; +const Logger = require('../core').Logger; +const MongoCredentials = require('../core').MongoCredentials; +const MongoError = require('../core').MongoError; +const Mongos = require('../topologies/mongos'); +const NativeTopology = require('../topologies/native_topology'); +const parse = require('../core').parseConnectionString; +const ReadConcern = require('../read_concern'); +const ReadPreference = require('../core').ReadPreference; +const ReplSet = require('../topologies/replset'); +const Server = require('../topologies/server'); +const ServerSessionPool = require('../core').Sessions.ServerSessionPool; + +let client; +function loadClient() { + if (!client) { + client = require('../mongo_client'); + } + return client; +} + +const legacyParse = deprecate( + require('../url_parser'), + 'current URL string parser is deprecated, and will be removed in a future version. ' + + 'To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.' +); + +const AUTH_MECHANISM_INTERNAL_MAP = { + DEFAULT: 'default', + 'MONGODB-CR': 'mongocr', + PLAIN: 'plain', + 'MONGODB-X509': 'x509', + 'SCRAM-SHA-1': 'scram-sha-1', + 'SCRAM-SHA-256': 'scram-sha-256' +}; + +const monitoringEvents = [ + 'timeout', + 'close', + 'serverOpening', + 'serverDescriptionChanged', + 'serverHeartbeatStarted', + 'serverHeartbeatSucceeded', + 'serverHeartbeatFailed', + 'serverClosed', + 'topologyOpening', + 'topologyClosed', + 'topologyDescriptionChanged', + 'commandStarted', + 'commandSucceeded', + 'commandFailed', + 'joined', + 'left', + 'ping', + 'ha', + 'all', + 'fullsetup', + 'open' +]; + +const VALID_AUTH_MECHANISMS = new Set([ + 'DEFAULT', + 'MONGODB-CR', + 'PLAIN', + 'MONGODB-X509', + 'SCRAM-SHA-1', + 'SCRAM-SHA-256', + 'GSSAPI' +]); + +const validOptionNames = [ + 'poolSize', + 'ssl', + 'sslValidate', + 'sslCA', + 'sslCert', + 'sslKey', + 'sslPass', + 'sslCRL', + 'autoReconnect', + 'noDelay', + 'keepAlive', + 'keepAliveInitialDelay', + 'connectTimeoutMS', + 'family', + 'socketTimeoutMS', + 'reconnectTries', + 'reconnectInterval', + 'ha', + 'haInterval', + 'replicaSet', + 'secondaryAcceptableLatencyMS', + 'acceptableLatencyMS', + 'connectWithNoPrimary', + 'authSource', + 'w', + 'wtimeout', + 'j', + 'forceServerObjectId', + 'serializeFunctions', + 'ignoreUndefined', + 'raw', + 'bufferMaxEntries', + 'readPreference', + 'pkFactory', + 'promiseLibrary', + 'readConcern', + 'maxStalenessSeconds', + 'loggerLevel', + 'logger', + 'promoteValues', + 'promoteBuffers', + 'promoteLongs', + 'domainsEnabled', + 'checkServerIdentity', + 'validateOptions', + 'appname', + 'auth', + 'user', + 'password', + 'authMechanism', + 'compression', + 'fsync', + 'readPreferenceTags', + 'numberOfRetries', + 'auto_reconnect', + 'minSize', + 'monitorCommands', + 'retryWrites', + 'retryReads', + 'useNewUrlParser', + 'useUnifiedTopology', + 'serverSelectionTimeoutMS', + 'useRecoveryToken', + 'autoEncryption' +]; + +const ignoreOptionNames = ['native_parser']; +const legacyOptionNames = ['server', 'replset', 'replSet', 'mongos', 'db']; + +// Validate options object +function validOptions(options) { + const _validOptions = validOptionNames.concat(legacyOptionNames); + + for (const name in options) { + if (ignoreOptionNames.indexOf(name) !== -1) { + continue; + } + + if (_validOptions.indexOf(name) === -1) { + if (options.validateOptions) { + return new MongoError(`option ${name} is not supported`); + } else { + console.warn(`the options [${name}] is not supported`); + } + } + + if (legacyOptionNames.indexOf(name) !== -1) { + console.warn( + `the server/replset/mongos/db options are deprecated, ` + + `all their options are supported at the top level of the options object [${validOptionNames}]` + ); + } + } +} + +const LEGACY_OPTIONS_MAP = validOptionNames.reduce((obj, name) => { + obj[name.toLowerCase()] = name; + return obj; +}, {}); + +class ConnectOperation extends OperationBase { + constructor(mongoClient) { + super(); + + this.mongoClient = mongoClient; + } + + execute(callback) { + const mongoClient = this.mongoClient; + const err = validOptions(mongoClient.s.options); + + // Did we have a validation error + if (err) return callback(err); + // Fallback to callback based connect + connect(mongoClient, mongoClient.s.url, mongoClient.s.options, err => { + if (err) return callback(err); + callback(null, mongoClient); + }); + } +} +defineAspects(ConnectOperation, [Aspect.SKIP_SESSION]); + +function addListeners(mongoClient, topology) { + topology.on('authenticated', createListener(mongoClient, 'authenticated')); + topology.on('error', createListener(mongoClient, 'error')); + topology.on('timeout', createListener(mongoClient, 'timeout')); + topology.on('close', createListener(mongoClient, 'close')); + topology.on('parseError', createListener(mongoClient, 'parseError')); + topology.once('open', createListener(mongoClient, 'open')); + topology.once('fullsetup', createListener(mongoClient, 'fullsetup')); + topology.once('all', createListener(mongoClient, 'all')); + topology.on('reconnect', createListener(mongoClient, 'reconnect')); +} + +function assignTopology(client, topology) { + client.topology = topology; + topology.s.sessionPool = + topology instanceof NativeTopology + ? new ServerSessionPool(topology) + : new ServerSessionPool(topology.s.coreTopology); +} + +// Clear out all events +function clearAllEvents(topology) { + monitoringEvents.forEach(event => topology.removeAllListeners(event)); +} + +// Collect all events in order from SDAM +function collectEvents(mongoClient, topology) { + let MongoClient = loadClient(); + const collectedEvents = []; + + if (mongoClient instanceof MongoClient) { + monitoringEvents.forEach(event => { + topology.on(event, (object1, object2) => { + if (event === 'open') { + collectedEvents.push({ event: event, object1: mongoClient }); + } else { + collectedEvents.push({ event: event, object1: object1, object2: object2 }); + } + }); + }); + } + + return collectedEvents; +} + +const emitDeprecationForNonUnifiedTopology = deprecate(() => {}, +'current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. ' + 'To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.'); + +function connect(mongoClient, url, options, callback) { + options = Object.assign({}, options); + + // If callback is null throw an exception + if (callback == null) { + throw new Error('no callback function provided'); + } + + let didRequestAuthentication = false; + const logger = Logger('MongoClient', options); + + // Did we pass in a Server/ReplSet/Mongos + if (url instanceof Server || url instanceof ReplSet || url instanceof Mongos) { + return connectWithUrl(mongoClient, url, options, connectCallback); + } + + const useNewUrlParser = options.useNewUrlParser !== false; + + const parseFn = useNewUrlParser ? parse : legacyParse; + const transform = useNewUrlParser ? transformUrlOptions : legacyTransformUrlOptions; + + parseFn(url, options, (err, _object) => { + // Do not attempt to connect if parsing error + if (err) return callback(err); + + // Flatten + const object = transform(_object); + + // Parse the string + const _finalOptions = createUnifiedOptions(object, options); + + // Check if we have connection and socket timeout set + if (_finalOptions.socketTimeoutMS == null) _finalOptions.socketTimeoutMS = 360000; + if (_finalOptions.connectTimeoutMS == null) _finalOptions.connectTimeoutMS = 30000; + if (_finalOptions.retryWrites == null) _finalOptions.retryWrites = true; + if (_finalOptions.useRecoveryToken == null) _finalOptions.useRecoveryToken = true; + if (_finalOptions.readPreference == null) _finalOptions.readPreference = 'primary'; + + if (_finalOptions.db_options && _finalOptions.db_options.auth) { + delete _finalOptions.db_options.auth; + } + + // Store the merged options object + mongoClient.s.options = _finalOptions; + + // Failure modes + if (object.servers.length === 0) { + return callback(new Error('connection string must contain at least one seed host')); + } + + if (_finalOptions.auth && !_finalOptions.credentials) { + try { + didRequestAuthentication = true; + _finalOptions.credentials = generateCredentials( + mongoClient, + _finalOptions.auth.user, + _finalOptions.auth.password, + _finalOptions + ); + } catch (err) { + return callback(err); + } + } + + if (_finalOptions.useUnifiedTopology) { + return createTopology(mongoClient, 'unified', _finalOptions, connectCallback); + } + + emitDeprecationForNonUnifiedTopology(); + + // Do we have a replicaset then skip discovery and go straight to connectivity + if (_finalOptions.replicaSet || _finalOptions.rs_name) { + return createTopology(mongoClient, 'replicaset', _finalOptions, connectCallback); + } else if (object.servers.length > 1) { + return createTopology(mongoClient, 'mongos', _finalOptions, connectCallback); + } else { + return createServer(mongoClient, _finalOptions, connectCallback); + } + }); + + function connectCallback(err, topology) { + const warningMessage = `seed list contains no mongos proxies, replicaset connections requires the parameter replicaSet to be supplied in the URI or options object, mongodb://server:port/db?replicaSet=name`; + if (err && err.message === 'no mongos proxies found in seed list') { + if (logger.isWarn()) { + logger.warn(warningMessage); + } + + // Return a more specific error message for MongoClient.connect + return callback(new MongoError(warningMessage)); + } + + if (didRequestAuthentication) { + mongoClient.emit('authenticated', null, true); + } + + // Return the error and db instance + callback(err, topology); + } +} + +function connectWithUrl(mongoClient, url, options, connectCallback) { + // Set the topology + assignTopology(mongoClient, url); + + // Add listeners + addListeners(mongoClient, url); + + // Propagate the events to the client + relayEvents(mongoClient, url); + + let finalOptions = Object.assign({}, options); + + // If we have a readPreference passed in by the db options, convert it from a string + if (typeof options.readPreference === 'string' || typeof options.read_preference === 'string') { + finalOptions.readPreference = new ReadPreference( + options.readPreference || options.read_preference + ); + } + + const isDoingAuth = finalOptions.user || finalOptions.password || finalOptions.authMechanism; + if (isDoingAuth && !finalOptions.credentials) { + try { + finalOptions.credentials = generateCredentials( + mongoClient, + finalOptions.user, + finalOptions.password, + finalOptions + ); + } catch (err) { + return connectCallback(err, url); + } + } + + return url.connect(finalOptions, connectCallback); +} + +function createListener(mongoClient, event) { + const eventSet = new Set(['all', 'fullsetup', 'open', 'reconnect']); + return (v1, v2) => { + if (eventSet.has(event)) { + return mongoClient.emit(event, mongoClient); + } + + mongoClient.emit(event, v1, v2); + }; +} + +function createServer(mongoClient, options, callback) { + // Pass in the promise library + options.promiseLibrary = mongoClient.s.promiseLibrary; + + // Set default options + const servers = translateOptions(options); + + const server = servers[0]; + + // Propagate the events to the client + const collectedEvents = collectEvents(mongoClient, server); + + // Connect to topology + server.connect(options, (err, topology) => { + if (err) { + server.close(true); + return callback(err); + } + // Clear out all the collected event listeners + clearAllEvents(server); + + // Relay all the events + relayEvents(mongoClient, server); + // Add listeners + addListeners(mongoClient, server); + // Check if we are really speaking to a mongos + const ismaster = topology.lastIsMaster(); + + // Set the topology + assignTopology(mongoClient, topology); + + // Do we actually have a mongos + if (ismaster && ismaster.msg === 'isdbgrid') { + // Destroy the current connection + topology.close(); + // Create mongos connection instead + return createTopology(mongoClient, 'mongos', options, callback); + } + + // Fire all the events + replayEvents(mongoClient, collectedEvents); + // Otherwise callback + callback(err, topology); + }); +} + +function createTopology(mongoClient, topologyType, options, callback) { + // Pass in the promise library + options.promiseLibrary = mongoClient.s.promiseLibrary; + + const translationOptions = {}; + if (topologyType === 'unified') translationOptions.createServers = false; + + // Set default options + const servers = translateOptions(options, translationOptions); + + // Create the topology + let topology; + if (topologyType === 'mongos') { + topology = new Mongos(servers, options); + } else if (topologyType === 'replicaset') { + topology = new ReplSet(servers, options); + } else if (topologyType === 'unified') { + topology = new NativeTopology(options.servers, options); + } + + // Add listeners + addListeners(mongoClient, topology); + + // Propagate the events to the client + relayEvents(mongoClient, topology); + + // Open the connection + assignTopology(mongoClient, topology); + topology.connect(options, err => { + if (err) { + topology.close(true); + return callback(err); + } + + if (options.autoEncryption == null) { + callback(null, topology); + return; + } + + // setup for client side encryption + let AutoEncrypter; + try { + require.resolve('mongodb-client-encryption'); + } catch (err) { + callback( + new MongoError( + 'Auto-encryption requested, but the module is not installed. Please add `mongodb-client-encryption` as a dependency of your project' + ) + ); + return; + } + try { + AutoEncrypter = require('mongodb-client-encryption')(require('../../index')).AutoEncrypter; + } catch (err) { + callback(err); + return; + } + + const mongoCryptOptions = Object.assign({}, options.autoEncryption); + topology.s.options.autoEncrypter = new AutoEncrypter(mongoClient, mongoCryptOptions); + topology.s.options.autoEncrypter.init(err => { + if (err) return callback(err, null); + callback(null, topology); + }); + }); +} + +function createUnifiedOptions(finalOptions, options) { + const childOptions = [ + 'mongos', + 'server', + 'db', + 'replset', + 'db_options', + 'server_options', + 'rs_options', + 'mongos_options' + ]; + const noMerge = ['readconcern', 'compression']; + + for (const name in options) { + if (noMerge.indexOf(name.toLowerCase()) !== -1) { + finalOptions[name] = options[name]; + } else if (childOptions.indexOf(name.toLowerCase()) !== -1) { + finalOptions = mergeOptions(finalOptions, options[name], false); + } else { + if ( + options[name] && + typeof options[name] === 'object' && + !Buffer.isBuffer(options[name]) && + !Array.isArray(options[name]) + ) { + finalOptions = mergeOptions(finalOptions, options[name], true); + } else { + finalOptions[name] = options[name]; + } + } + } + + return finalOptions; +} + +function generateCredentials(client, username, password, options) { + options = Object.assign({}, options); + + // the default db to authenticate against is 'self' + // if authententicate is called from a retry context, it may be another one, like admin + const source = options.authSource || options.authdb || options.dbName; + + // authMechanism + const authMechanismRaw = options.authMechanism || 'DEFAULT'; + const authMechanism = authMechanismRaw.toUpperCase(); + + if (!VALID_AUTH_MECHANISMS.has(authMechanism)) { + throw MongoError.create({ + message: `authentication mechanism ${authMechanismRaw} not supported', options.authMechanism`, + driver: true + }); + } + + if (authMechanism === 'GSSAPI') { + return new MongoCredentials({ + mechanism: process.platform === 'win32' ? 'sspi' : 'gssapi', + mechanismProperties: options, + source, + username, + password + }); + } + + return new MongoCredentials({ + mechanism: AUTH_MECHANISM_INTERNAL_MAP[authMechanism], + source, + username, + password + }); +} + +function legacyTransformUrlOptions(object) { + return mergeOptions(createUnifiedOptions({}, object), object, false); +} + +function mergeOptions(target, source, flatten) { + for (const name in source) { + if (source[name] && typeof source[name] === 'object' && flatten) { + target = mergeOptions(target, source[name], flatten); + } else { + target[name] = source[name]; + } + } + + return target; +} + +function relayEvents(mongoClient, topology) { + const serverOrCommandEvents = [ + 'serverOpening', + 'serverDescriptionChanged', + 'serverHeartbeatStarted', + 'serverHeartbeatSucceeded', + 'serverHeartbeatFailed', + 'serverClosed', + 'topologyOpening', + 'topologyClosed', + 'topologyDescriptionChanged', + 'commandStarted', + 'commandSucceeded', + 'commandFailed', + 'joined', + 'left', + 'ping', + 'ha' + ]; + + serverOrCommandEvents.forEach(event => { + topology.on(event, (object1, object2) => { + mongoClient.emit(event, object1, object2); + }); + }); +} + +// +// Replay any events due to single server connection switching to Mongos +// +function replayEvents(mongoClient, events) { + for (let i = 0; i < events.length; i++) { + mongoClient.emit(events[i].event, events[i].object1, events[i].object2); + } +} + +function transformUrlOptions(_object) { + let object = Object.assign({ servers: _object.hosts }, _object.options); + for (let name in object) { + const camelCaseName = LEGACY_OPTIONS_MAP[name]; + if (camelCaseName) { + object[camelCaseName] = object[name]; + } + } + + const hasUsername = _object.auth && _object.auth.username; + const hasAuthMechanism = _object.options && _object.options.authMechanism; + if (hasUsername || hasAuthMechanism) { + object.auth = Object.assign({}, _object.auth); + if (object.auth.db) { + object.authSource = object.authSource || object.auth.db; + } + + if (object.auth.username) { + object.auth.user = object.auth.username; + } + } + + if (_object.defaultDatabase) { + object.dbName = _object.defaultDatabase; + } + + if (object.maxPoolSize) { + object.poolSize = object.maxPoolSize; + } + + if (object.readConcernLevel) { + object.readConcern = new ReadConcern(object.readConcernLevel); + } + + if (object.wTimeoutMS) { + object.wtimeout = object.wTimeoutMS; + } + + if (_object.srvHost) { + object.srvHost = _object.srvHost; + } + + return object; +} + +function translateOptions(options, translationOptions) { + translationOptions = Object.assign({}, { createServers: true }, translationOptions); + + // If we have a readPreference passed in by the db options + if (typeof options.readPreference === 'string' || typeof options.read_preference === 'string') { + options.readPreference = new ReadPreference(options.readPreference || options.read_preference); + } + + // Do we have readPreference tags, add them + if (options.readPreference && (options.readPreferenceTags || options.read_preference_tags)) { + options.readPreference.tags = options.readPreferenceTags || options.read_preference_tags; + } + + // Do we have maxStalenessSeconds + if (options.maxStalenessSeconds) { + options.readPreference.maxStalenessSeconds = options.maxStalenessSeconds; + } + + // Set the socket and connection timeouts + if (options.socketTimeoutMS == null) options.socketTimeoutMS = 360000; + if (options.connectTimeoutMS == null) options.connectTimeoutMS = 30000; + + if (!translationOptions.createServers) { + return; + } + + // Create server instances + return options.servers.map(serverObj => { + return serverObj.domain_socket + ? new Server(serverObj.domain_socket, 27017, options) + : new Server(serverObj.host, serverObj.port, options); + }); +} + +module.exports = ConnectOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/count.js b/scripts/node_modules/mongodb/lib/operations/count.js new file mode 100644 index 00000000..5bf03f08 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/operations/count.js @@ -0,0 +1,72 @@ +'use strict'; + +const Aspect = require('./operation').Aspect; +const buildCountCommand = require('./common_functions').buildCountCommand; +const defineAspects = require('./operation').defineAspects; +const OperationBase = require('./operation').OperationBase; + +class CountOperation extends OperationBase { + constructor(cursor, applySkipLimit, options) { + super(options); + + this.cursor = cursor; + this.applySkipLimit = applySkipLimit; + } + + execute(callback) { + const cursor = this.cursor; + const applySkipLimit = this.applySkipLimit; + const options = this.options; + + if (applySkipLimit) { + if (typeof cursor.cursorSkip() === 'number') options.skip = cursor.cursorSkip(); + if (typeof cursor.cursorLimit() === 'number') options.limit = cursor.cursorLimit(); + } + + // Ensure we have the right read preference inheritance + if (options.readPreference) { + cursor.setReadPreference(options.readPreference); + } + + if ( + typeof options.maxTimeMS !== 'number' && + cursor.cmd && + typeof cursor.cmd.maxTimeMS === 'number' + ) { + options.maxTimeMS = cursor.cmd.maxTimeMS; + } + + let finalOptions = {}; + finalOptions.skip = options.skip; + finalOptions.limit = options.limit; + finalOptions.hint = options.hint; + finalOptions.maxTimeMS = options.maxTimeMS; + + // Command + finalOptions.collectionName = cursor.namespace.collection; + + let command; + try { + command = buildCountCommand(cursor, cursor.cmd.query, finalOptions); + } catch (err) { + return callback(err); + } + + // Set cursor server to the same as the topology + cursor.server = cursor.topology.s.coreTopology; + + // Execute the command + cursor.topology.command( + cursor.namespace.withCollection('$cmd'), + command, + cursor.options, + (err, result) => { + callback(err, result ? result.result.n : null); + } + ); + } +} + +defineAspects(CountOperation, Aspect.SKIP_SESSION); + +module.exports = CountOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/count_documents.js b/scripts/node_modules/mongodb/lib/operations/count_documents.js new file mode 100644 index 00000000..d043abfa --- /dev/null +++ b/scripts/node_modules/mongodb/lib/operations/count_documents.js @@ -0,0 +1,41 @@ +'use strict'; + +const AggregateOperation = require('./aggregate'); + +class CountDocumentsOperation extends AggregateOperation { + constructor(collection, query, options) { + const pipeline = [{ $match: query }]; + if (typeof options.skip === 'number') { + pipeline.push({ $skip: options.skip }); + } + + if (typeof options.limit === 'number') { + pipeline.push({ $limit: options.limit }); + } + + pipeline.push({ $group: { _id: 1, n: { $sum: 1 } } }); + + super(collection, pipeline, options); + } + + execute(server, callback) { + super.execute(server, (err, result) => { + if (err) { + callback(err, null); + return; + } + + // NOTE: We're avoiding creating a cursor here to reduce the callstack. + const response = result.result; + if (response.cursor == null || response.cursor.firstBatch == null) { + callback(null, 0); + return; + } + + const docs = response.cursor.firstBatch; + callback(null, docs.length ? docs[0].n : 0); + }); + } +} + +module.exports = CountDocumentsOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/create_collection.js b/scripts/node_modules/mongodb/lib/operations/create_collection.js new file mode 100644 index 00000000..35c3a6f0 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/operations/create_collection.js @@ -0,0 +1,118 @@ +'use strict'; + +const Aspect = require('./operation').Aspect; +const defineAspects = require('./operation').defineAspects; +const CommandOperation = require('./command'); +const applyWriteConcern = require('../utils').applyWriteConcern; +const handleCallback = require('../utils').handleCallback; +const loadCollection = require('../dynamic_loaders').loadCollection; +const MongoError = require('../core').MongoError; +const ReadPreference = require('../core').ReadPreference; + +// Filter out any write concern options +const illegalCommandFields = [ + 'w', + 'wtimeout', + 'j', + 'fsync', + 'autoIndexId', + 'strict', + 'serializeFunctions', + 'pkFactory', + 'raw', + 'readPreference', + 'session', + 'readConcern', + 'writeConcern' +]; + +class CreateCollectionOperation extends CommandOperation { + constructor(db, name, options) { + super(db, options); + + this.name = name; + } + + _buildCommand() { + const name = this.name; + const options = this.options; + + // Create collection command + const cmd = { create: name }; + // Add all optional parameters + for (let n in options) { + if ( + options[n] != null && + typeof options[n] !== 'function' && + illegalCommandFields.indexOf(n) === -1 + ) { + cmd[n] = options[n]; + } + } + + return cmd; + } + + execute(callback) { + const db = this.db; + const name = this.name; + const options = this.options; + + let Collection = loadCollection(); + + // Did the user destroy the topology + if (db.serverConfig && db.serverConfig.isDestroyed()) { + return callback(new MongoError('topology was destroyed')); + } + + let listCollectionOptions = Object.assign({}, options, { nameOnly: true }); + listCollectionOptions = applyWriteConcern(listCollectionOptions, { db }, listCollectionOptions); + + // Check if we have the name + db + .listCollections({ name }, listCollectionOptions) + .setReadPreference(ReadPreference.PRIMARY) + .toArray((err, collections) => { + if (err != null) return handleCallback(callback, err, null); + if (collections.length > 0 && listCollectionOptions.strict) { + return handleCallback( + callback, + MongoError.create({ + message: `Collection ${name} already exists. Currently in strict mode.`, + driver: true + }), + null + ); + } else if (collections.length > 0) { + try { + return handleCallback( + callback, + null, + new Collection(db, db.s.topology, db.databaseName, name, db.s.pkFactory, options) + ); + } catch (err) { + return handleCallback(callback, err); + } + } + + // Execute command + super.execute(err => { + if (err) return handleCallback(callback, err); + + try { + return handleCallback( + callback, + null, + new Collection(db, db.s.topology, db.databaseName, name, db.s.pkFactory, options) + ); + } catch (err) { + return handleCallback(callback, err); + } + }); + }); + } +} + +defineAspects(CreateCollectionOperation, Aspect.WRITE_OPERATION); + +module.exports = CreateCollectionOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/create_index.js b/scripts/node_modules/mongodb/lib/operations/create_index.js new file mode 100644 index 00000000..98bba71e --- /dev/null +++ b/scripts/node_modules/mongodb/lib/operations/create_index.js @@ -0,0 +1,92 @@ +'use strict'; + +const Aspect = require('./operation').Aspect; +const CommandOperation = require('./command'); +const defineAspects = require('./operation').defineAspects; +const handleCallback = require('../utils').handleCallback; +const MongoError = require('../core').MongoError; +const parseIndexOptions = require('../utils').parseIndexOptions; + +const keysToOmit = new Set([ + 'name', + 'key', + 'writeConcern', + 'w', + 'wtimeout', + 'j', + 'fsync', + 'readPreference', + 'session' +]); + +class CreateIndexOperation extends CommandOperation { + constructor(db, name, fieldOrSpec, options) { + super(db, options); + + // Build the index + const indexParameters = parseIndexOptions(fieldOrSpec); + // Generate the index name + const indexName = typeof options.name === 'string' ? options.name : indexParameters.name; + // Set up the index + const indexesObject = { name: indexName, key: indexParameters.fieldHash }; + + this.name = name; + this.fieldOrSpec = fieldOrSpec; + this.indexes = indexesObject; + } + + _buildCommand() { + const options = this.options; + const name = this.name; + const indexes = this.indexes; + + // merge all the options + for (let optionName in options) { + if (!keysToOmit.has(optionName)) { + indexes[optionName] = options[optionName]; + } + } + + // Create command, apply write concern to command + const cmd = { createIndexes: name, indexes: [indexes] }; + + return cmd; + } + + execute(callback) { + const db = this.db; + const options = this.options; + const indexes = this.indexes; + + // Get capabilities + const capabilities = db.s.topology.capabilities(); + + // Did the user pass in a collation, check if our write server supports it + if (options.collation && capabilities && !capabilities.commandsTakeCollation) { + // Create a new error + const error = new MongoError('server/primary/mongos does not support collation'); + error.code = 67; + // Return the error + return callback(error); + } + + // Ensure we have a callback + if (options.writeConcern && typeof callback !== 'function') { + throw MongoError.create({ + message: 'Cannot use a writeConcern without a provided callback', + driver: true + }); + } + + // Attempt to run using createIndexes command + super.execute((err, result) => { + if (err == null) return handleCallback(callback, err, indexes.name); + + return handleCallback(callback, err, result); + }); + } +} + +defineAspects(CreateIndexOperation, Aspect.WRITE_OPERATION); + +module.exports = CreateIndexOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/create_indexes.js b/scripts/node_modules/mongodb/lib/operations/create_indexes.js new file mode 100644 index 00000000..46228e8c --- /dev/null +++ b/scripts/node_modules/mongodb/lib/operations/create_indexes.js @@ -0,0 +1,61 @@ +'use strict'; + +const Aspect = require('./operation').Aspect; +const defineAspects = require('./operation').defineAspects; +const OperationBase = require('./operation').OperationBase; +const executeCommand = require('./db_ops').executeCommand; +const MongoError = require('../core').MongoError; +const ReadPreference = require('../core').ReadPreference; + +class CreateIndexesOperation extends OperationBase { + constructor(collection, indexSpecs, options) { + super(options); + + this.collection = collection; + this.indexSpecs = indexSpecs; + } + + execute(callback) { + const coll = this.collection; + const indexSpecs = this.indexSpecs; + let options = this.options; + + const capabilities = coll.s.topology.capabilities(); + + // Ensure we generate the correct name if the parameter is not set + for (let i = 0; i < indexSpecs.length; i++) { + if (indexSpecs[i].name == null) { + const keys = []; + + // Did the user pass in a collation, check if our write server supports it + if (indexSpecs[i].collation && capabilities && !capabilities.commandsTakeCollation) { + return callback(new MongoError('server/primary/mongos does not support collation')); + } + + for (let name in indexSpecs[i].key) { + keys.push(`${name}_${indexSpecs[i].key[name]}`); + } + + // Set the name + indexSpecs[i].name = keys.join('_'); + } + } + + options = Object.assign({}, options, { readPreference: ReadPreference.PRIMARY }); + + // Execute the index + executeCommand( + coll.s.db, + { + createIndexes: coll.collectionName, + indexes: indexSpecs + }, + options, + callback + ); + } +} + +defineAspects(CreateIndexesOperation, Aspect.WRITE_OPERATION); + +module.exports = CreateIndexesOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/cursor_ops.js b/scripts/node_modules/mongodb/lib/operations/cursor_ops.js new file mode 100644 index 00000000..513624ff --- /dev/null +++ b/scripts/node_modules/mongodb/lib/operations/cursor_ops.js @@ -0,0 +1,239 @@ +'use strict'; + +const buildCountCommand = require('./collection_ops').buildCountCommand; +const formattedOrderClause = require('../utils').formattedOrderClause; +const handleCallback = require('../utils').handleCallback; +const MongoError = require('../core').MongoError; +const push = Array.prototype.push; +const CursorState = require('../core/cursor').CursorState; + +/** + * Get the count of documents for this cursor. + * + * @method + * @param {Cursor} cursor The Cursor instance on which to count. + * @param {boolean} [applySkipLimit=true] Specifies whether the count command apply limit and skip settings should be applied on the cursor or in the provided options. + * @param {object} [options] Optional settings. See Cursor.prototype.count for a list of options. + * @param {Cursor~countResultCallback} [callback] The result callback. + */ +function count(cursor, applySkipLimit, opts, callback) { + if (applySkipLimit) { + if (typeof cursor.cursorSkip() === 'number') opts.skip = cursor.cursorSkip(); + if (typeof cursor.cursorLimit() === 'number') opts.limit = cursor.cursorLimit(); + } + + // Ensure we have the right read preference inheritance + if (opts.readPreference) { + cursor.setReadPreference(opts.readPreference); + } + + if ( + typeof opts.maxTimeMS !== 'number' && + cursor.cmd && + typeof cursor.cmd.maxTimeMS === 'number' + ) { + opts.maxTimeMS = cursor.cmd.maxTimeMS; + } + + let options = {}; + options.skip = opts.skip; + options.limit = opts.limit; + options.hint = opts.hint; + options.maxTimeMS = opts.maxTimeMS; + + // Command + options.collectionName = cursor.namespace.collection; + + let command; + try { + command = buildCountCommand(cursor, cursor.cmd.query, options); + } catch (err) { + return callback(err); + } + + // Set cursor server to the same as the topology + cursor.server = cursor.topology.s.coreTopology; + + // Execute the command + cursor.topology.command( + cursor.namespace.withCollection('$cmd'), + command, + cursor.options, + (err, result) => { + callback(err, result ? result.result.n : null); + } + ); +} + +/** + * Iterates over all the documents for this cursor. See Cursor.prototype.each for more information. + * + * @method + * @deprecated + * @param {Cursor} cursor The Cursor instance on which to run. + * @param {Cursor~resultCallback} callback The result callback. + */ +function each(cursor, callback) { + if (!callback) throw MongoError.create({ message: 'callback is mandatory', driver: true }); + if (cursor.isNotified()) return; + if (cursor.s.state === CursorState.CLOSED || cursor.isDead()) { + return handleCallback( + callback, + MongoError.create({ message: 'Cursor is closed', driver: true }) + ); + } + + if (cursor.s.state === CursorState.INIT) { + cursor.s.state = CursorState.OPEN; + } + + // Define function to avoid global scope escape + let fn = null; + // Trampoline all the entries + if (cursor.bufferedCount() > 0) { + while ((fn = loop(cursor, callback))) fn(cursor, callback); + each(cursor, callback); + } else { + cursor.next((err, item) => { + if (err) return handleCallback(callback, err); + if (item == null) { + return cursor.close({ skipKillCursors: true }, () => handleCallback(callback, null, null)); + } + + if (handleCallback(callback, null, item) === false) return; + each(cursor, callback); + }); + } +} + +/** + * Check if there is any document still available in the cursor. + * + * @method + * @param {Cursor} cursor The Cursor instance on which to run. + * @param {Cursor~resultCallback} [callback] The result callback. + */ +function hasNext(cursor, callback) { + if (cursor.s.currentDoc) { + return callback(null, true); + } + + if (cursor.isNotified()) { + return callback(null, false); + } + + nextObject(cursor, (err, doc) => { + if (err) return callback(err, null); + if (cursor.s.state === CursorState.CLOSED || cursor.isDead()) { + return callback(null, false); + } + + if (!doc) return callback(null, false); + cursor.s.currentDoc = doc; + callback(null, true); + }); +} + +// Trampoline emptying the number of retrieved items +// without incurring a nextTick operation +function loop(cursor, callback) { + // No more items we are done + if (cursor.bufferedCount() === 0) return; + // Get the next document + cursor._next(callback); + // Loop + return loop; +} + +/** + * Get the next available document from the cursor. Returns null if no more documents are available. + * + * @method + * @param {Cursor} cursor The Cursor instance from which to get the next document. + * @param {Cursor~resultCallback} [callback] The result callback. + */ +function next(cursor, callback) { + // Return the currentDoc if someone called hasNext first + if (cursor.s.currentDoc) { + const doc = cursor.s.currentDoc; + cursor.s.currentDoc = null; + return callback(null, doc); + } + + // Return the next object + nextObject(cursor, callback); +} + +// Get the next available document from the cursor, returns null if no more documents are available. +function nextObject(cursor, callback) { + if (cursor.s.state === CursorState.CLOSED || (cursor.isDead && cursor.isDead())) + return handleCallback( + callback, + MongoError.create({ message: 'Cursor is closed', driver: true }) + ); + if (cursor.s.state === CursorState.INIT && cursor.cmd.sort) { + try { + cursor.cmd.sort = formattedOrderClause(cursor.cmd.sort); + } catch (err) { + return handleCallback(callback, err); + } + } + + // Get the next object + cursor._next((err, doc) => { + cursor.s.state = CursorState.OPEN; + if (err) return handleCallback(callback, err); + handleCallback(callback, null, doc); + }); +} + +/** + * Returns an array of documents. See Cursor.prototype.toArray for more information. + * + * @method + * @param {Cursor} cursor The Cursor instance from which to get the next document. + * @param {Cursor~toArrayResultCallback} [callback] The result callback. + */ +function toArray(cursor, callback) { + const items = []; + + // Reset cursor + cursor.rewind(); + cursor.s.state = CursorState.INIT; + + // Fetch all the documents + const fetchDocs = () => { + cursor._next((err, doc) => { + if (err) { + return cursor._endSession + ? cursor._endSession(() => handleCallback(callback, err)) + : handleCallback(callback, err); + } + if (doc == null) { + return cursor.close({ skipKillCursors: true }, () => handleCallback(callback, null, items)); + } + + // Add doc to items + items.push(doc); + + // Get all buffered objects + if (cursor.bufferedCount() > 0) { + let docs = cursor.readBufferedDocuments(cursor.bufferedCount()); + + // Transform the doc if transform method added + if (cursor.s.transforms && typeof cursor.s.transforms.doc === 'function') { + docs = docs.map(cursor.s.transforms.doc); + } + + push.apply(items, docs); + } + + // Attempt a fetch + fetchDocs(); + }); + }; + + fetchDocs(); +} + +module.exports = { count, each, hasNext, next, toArray }; diff --git a/scripts/node_modules/mongodb/lib/operations/db_ops.js b/scripts/node_modules/mongodb/lib/operations/db_ops.js new file mode 100644 index 00000000..08037620 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/operations/db_ops.js @@ -0,0 +1,831 @@ +'use strict'; + +const applyWriteConcern = require('../utils').applyWriteConcern; +const Code = require('../core').BSON.Code; +const resolveReadPreference = require('../utils').resolveReadPreference; +const crypto = require('crypto'); +const debugOptions = require('../utils').debugOptions; +const handleCallback = require('../utils').handleCallback; +const MongoError = require('../core').MongoError; +const parseIndexOptions = require('../utils').parseIndexOptions; +const ReadPreference = require('../core').ReadPreference; +const toError = require('../utils').toError; +const CONSTANTS = require('../constants'); +const MongoDBNamespace = require('../utils').MongoDBNamespace; + +const count = require('./collection_ops').count; +const findOne = require('./collection_ops').findOne; +const remove = require('./collection_ops').remove; +const updateOne = require('./collection_ops').updateOne; + +let collection; +function loadCollection() { + if (!collection) { + collection = require('../collection'); + } + return collection; +} +let db; +function loadDb() { + if (!db) { + db = require('../db'); + } + return db; +} + +const debugFields = [ + 'authSource', + 'w', + 'wtimeout', + 'j', + 'native_parser', + 'forceServerObjectId', + 'serializeFunctions', + 'raw', + 'promoteLongs', + 'promoteValues', + 'promoteBuffers', + 'bufferMaxEntries', + 'numberOfRetries', + 'retryMiliSeconds', + 'readPreference', + 'pkFactory', + 'parentDb', + 'promiseLibrary', + 'noListener' +]; + +/** + * Add a user to the database. + * @method + * @param {Db} db The Db instance on which to add a user. + * @param {string} username The username. + * @param {string} password The password. + * @param {object} [options] Optional settings. See Db.prototype.addUser for a list of options. + * @param {Db~resultCallback} [callback] The command result callback + */ +function addUser(db, username, password, options, callback) { + let Db = loadDb(); + + // Did the user destroy the topology + if (db.serverConfig && db.serverConfig.isDestroyed()) + return callback(new MongoError('topology was destroyed')); + // Attempt to execute auth command + executeAuthCreateUserCommand(db, username, password, options, (err, r) => { + // We need to perform the backward compatible insert operation + if (err && err.code === -5000) { + const finalOptions = applyWriteConcern(Object.assign({}, options), { db }, options); + + // Use node md5 generator + const md5 = crypto.createHash('md5'); + // Generate keys used for authentication + md5.update(username + ':mongo:' + password); + const userPassword = md5.digest('hex'); + + // If we have another db set + const dbToUse = options.dbName ? new Db(options.dbName, db.s.topology, db.s.options) : db; + + // Fetch a user collection + const collection = dbToUse.collection(CONSTANTS.SYSTEM_USER_COLLECTION); + + // Check if we are inserting the first user + count(collection, {}, finalOptions, (err, count) => { + // We got an error (f.ex not authorized) + if (err != null) return handleCallback(callback, err, null); + // Check if the user exists and update i + const findOptions = Object.assign({ projection: { dbName: 1 } }, finalOptions); + collection.find({ user: username }, findOptions).toArray(err => { + // We got an error (f.ex not authorized) + if (err != null) return handleCallback(callback, err, null); + // Add command keys + finalOptions.upsert = true; + + // We have a user, let's update the password or upsert if not + updateOne( + collection, + { user: username }, + { $set: { user: username, pwd: userPassword } }, + finalOptions, + err => { + if (count === 0 && err) + return handleCallback(callback, null, [{ user: username, pwd: userPassword }]); + if (err) return handleCallback(callback, err, null); + handleCallback(callback, null, [{ user: username, pwd: userPassword }]); + } + ); + }); + }); + + return; + } + + if (err) return handleCallback(callback, err); + handleCallback(callback, err, r); + }); +} + +/** + * Fetch all collections for the current db. + * + * @method + * @param {Db} db The Db instance on which to fetch collections. + * @param {object} [options] Optional settings. See Db.prototype.collections for a list of options. + * @param {Db~collectionsResultCallback} [callback] The results callback + */ +function collections(db, options, callback) { + let Collection = loadCollection(); + + options = Object.assign({}, options, { nameOnly: true }); + // Let's get the collection names + db.listCollections({}, options).toArray((err, documents) => { + if (err != null) return handleCallback(callback, err, null); + // Filter collections removing any illegal ones + documents = documents.filter(doc => { + return doc.name.indexOf('$') === -1; + }); + + // Return the collection objects + handleCallback( + callback, + null, + documents.map(d => { + return new Collection( + db, + db.s.topology, + db.databaseName, + d.name, + db.s.pkFactory, + db.s.options + ); + }) + ); + }); +} + +/** + * Creates an index on the db and collection. + * @method + * @param {Db} db The Db instance on which to create an index. + * @param {string} name Name of the collection to create the index on. + * @param {(string|object)} fieldOrSpec Defines the index. + * @param {object} [options] Optional settings. See Db.prototype.createIndex for a list of options. + * @param {Db~resultCallback} [callback] The command result callback + */ +function createIndex(db, name, fieldOrSpec, options, callback) { + // Get the write concern options + let finalOptions = Object.assign({}, { readPreference: ReadPreference.PRIMARY }, options); + finalOptions = applyWriteConcern(finalOptions, { db }, options); + + // Ensure we have a callback + if (finalOptions.writeConcern && typeof callback !== 'function') { + throw MongoError.create({ + message: 'Cannot use a writeConcern without a provided callback', + driver: true + }); + } + + // Did the user destroy the topology + if (db.serverConfig && db.serverConfig.isDestroyed()) + return callback(new MongoError('topology was destroyed')); + + // Attempt to run using createIndexes command + createIndexUsingCreateIndexes(db, name, fieldOrSpec, finalOptions, (err, result) => { + if (err == null) return handleCallback(callback, err, result); + + /** + * The following errors mean that the server recognized `createIndex` as a command so we don't need to fallback to an insert: + * 67 = 'CannotCreateIndex' (malformed index options) + * 85 = 'IndexOptionsConflict' (index already exists with different options) + * 86 = 'IndexKeySpecsConflict' (index already exists with the same name) + * 11000 = 'DuplicateKey' (couldn't build unique index because of dupes) + * 11600 = 'InterruptedAtShutdown' (interrupted at shutdown) + * 197 = 'InvalidIndexSpecificationOption' (`_id` with `background: true`) + */ + if ( + err.code === 67 || + err.code === 11000 || + err.code === 85 || + err.code === 86 || + err.code === 11600 || + err.code === 197 + ) { + return handleCallback(callback, err, result); + } + + // Create command + const doc = createCreateIndexCommand(db, name, fieldOrSpec, options); + // Set no key checking + finalOptions.checkKeys = false; + // Insert document + db.s.topology.insert( + db.s.namespace.withCollection(CONSTANTS.SYSTEM_INDEX_COLLECTION), + doc, + finalOptions, + (err, result) => { + if (callback == null) return; + if (err) return handleCallback(callback, err); + if (result == null) return handleCallback(callback, null, null); + if (result.result.writeErrors) + return handleCallback(callback, MongoError.create(result.result.writeErrors[0]), null); + handleCallback(callback, null, doc.name); + } + ); + }); +} + +// Add listeners to topology +function createListener(db, e, object) { + function listener(err) { + if (object.listeners(e).length > 0) { + object.emit(e, err, db); + + // Emit on all associated db's if available + for (let i = 0; i < db.s.children.length; i++) { + db.s.children[i].emit(e, err, db.s.children[i]); + } + } + } + return listener; +} + +/** + * Drop a collection from the database, removing it permanently. New accesses will create a new collection. + * + * @method + * @param {Db} db The Db instance on which to drop the collection. + * @param {string} name Name of collection to drop + * @param {Object} [options] Optional settings. See Db.prototype.dropCollection for a list of options. + * @param {Db~resultCallback} [callback] The results callback + */ +function dropCollection(db, name, options, callback) { + executeCommand(db, name, options, (err, result) => { + // Did the user destroy the topology + if (db.serverConfig && db.serverConfig.isDestroyed()) { + return callback(new MongoError('topology was destroyed')); + } + + if (err) return handleCallback(callback, err); + if (result.ok) return handleCallback(callback, null, true); + handleCallback(callback, null, false); + }); +} + +/** + * Drop a database, removing it permanently from the server. + * + * @method + * @param {Db} db The Db instance to drop. + * @param {Object} cmd The command document. + * @param {Object} [options] Optional settings. See Db.prototype.dropDatabase for a list of options. + * @param {Db~resultCallback} [callback] The results callback + */ +function dropDatabase(db, cmd, options, callback) { + executeCommand(db, cmd, options, (err, result) => { + // Did the user destroy the topology + if (db.serverConfig && db.serverConfig.isDestroyed()) { + return callback(new MongoError('topology was destroyed')); + } + + if (callback == null) return; + if (err) return handleCallback(callback, err, null); + handleCallback(callback, null, result.ok ? true : false); + }); +} + +/** + * Ensures that an index exists. If it does not, creates it. + * + * @method + * @param {Db} db The Db instance on which to ensure the index. + * @param {string} name The index name + * @param {(string|object)} fieldOrSpec Defines the index. + * @param {object} [options] Optional settings. See Db.prototype.ensureIndex for a list of options. + * @param {Db~resultCallback} [callback] The command result callback + */ +function ensureIndex(db, name, fieldOrSpec, options, callback) { + // Get the write concern options + const finalOptions = applyWriteConcern({}, { db }, options); + // Create command + const selector = createCreateIndexCommand(db, name, fieldOrSpec, options); + const index_name = selector.name; + + // Did the user destroy the topology + if (db.serverConfig && db.serverConfig.isDestroyed()) + return callback(new MongoError('topology was destroyed')); + + // Merge primary readPreference + finalOptions.readPreference = ReadPreference.PRIMARY; + + // Check if the index already exists + indexInformation(db, name, finalOptions, (err, indexInformation) => { + if (err != null && err.code !== 26) return handleCallback(callback, err, null); + // If the index does not exist, create it + if (indexInformation == null || !indexInformation[index_name]) { + createIndex(db, name, fieldOrSpec, options, callback); + } else { + if (typeof callback === 'function') return handleCallback(callback, null, index_name); + } + }); +} + +/** + * Evaluate JavaScript on the server + * + * @method + * @param {Db} db The Db instance. + * @param {Code} code JavaScript to execute on server. + * @param {(object|array)} parameters The parameters for the call. + * @param {object} [options] Optional settings. See Db.prototype.eval for a list of options. + * @param {Db~resultCallback} [callback] The results callback + * @deprecated Eval is deprecated on MongoDB 3.2 and forward + */ +function evaluate(db, code, parameters, options, callback) { + let finalCode = code; + let finalParameters = []; + + // Did the user destroy the topology + if (db.serverConfig && db.serverConfig.isDestroyed()) + return callback(new MongoError('topology was destroyed')); + + // If not a code object translate to one + if (!(finalCode && finalCode._bsontype === 'Code')) finalCode = new Code(finalCode); + // Ensure the parameters are correct + if (parameters != null && !Array.isArray(parameters) && typeof parameters !== 'function') { + finalParameters = [parameters]; + } else if (parameters != null && Array.isArray(parameters) && typeof parameters !== 'function') { + finalParameters = parameters; + } + + // Create execution selector + let cmd = { $eval: finalCode, args: finalParameters }; + // Check if the nolock parameter is passed in + if (options['nolock']) { + cmd['nolock'] = options['nolock']; + } + + // Set primary read preference + options.readPreference = new ReadPreference(ReadPreference.PRIMARY); + + // Execute the command + executeCommand(db, cmd, options, (err, result) => { + if (err) return handleCallback(callback, err, null); + if (result && result.ok === 1) return handleCallback(callback, null, result.retval); + if (result) + return handleCallback( + callback, + MongoError.create({ message: `eval failed: ${result.errmsg}`, driver: true }), + null + ); + handleCallback(callback, err, result); + }); +} + +/** + * Execute a command + * + * @method + * @param {Db} db The Db instance on which to execute the command. + * @param {object} command The command hash + * @param {object} [options] Optional settings. See Db.prototype.command for a list of options. + * @param {Db~resultCallback} [callback] The command result callback + */ +function executeCommand(db, command, options, callback) { + // Did the user destroy the topology + if (db.serverConfig && db.serverConfig.isDestroyed()) + return callback(new MongoError('topology was destroyed')); + // Get the db name we are executing against + const dbName = options.dbName || options.authdb || db.databaseName; + + // Convert the readPreference if its not a write + options.readPreference = resolveReadPreference(db, options); + + // Debug information + if (db.s.logger.isDebug()) + db.s.logger.debug( + `executing command ${JSON.stringify( + command + )} against ${dbName}.$cmd with options [${JSON.stringify( + debugOptions(debugFields, options) + )}]` + ); + + // Execute command + db.s.topology.command(db.s.namespace.withCollection('$cmd'), command, options, (err, result) => { + if (err) return handleCallback(callback, err); + if (options.full) return handleCallback(callback, null, result); + handleCallback(callback, null, result.result); + }); +} + +/** + * Runs a command on the database as admin. + * + * @method + * @param {Db} db The Db instance on which to execute the command. + * @param {object} command The command hash + * @param {object} [options] Optional settings. See Db.prototype.executeDbAdminCommand for a list of options. + * @param {Db~resultCallback} [callback] The command result callback + */ +function executeDbAdminCommand(db, command, options, callback) { + const namespace = new MongoDBNamespace('admin', '$cmd'); + + db.s.topology.command(namespace, command, options, (err, result) => { + // Did the user destroy the topology + if (db.serverConfig && db.serverConfig.isDestroyed()) { + return callback(new MongoError('topology was destroyed')); + } + + if (err) return handleCallback(callback, err); + handleCallback(callback, null, result.result); + }); +} + +/** + * Retrieves this collections index info. + * + * @method + * @param {Db} db The Db instance on which to retrieve the index info. + * @param {string} name The name of the collection. + * @param {object} [options] Optional settings. See Db.prototype.indexInformation for a list of options. + * @param {Db~resultCallback} [callback] The command result callback + */ +function indexInformation(db, name, options, callback) { + // If we specified full information + const full = options['full'] == null ? false : options['full']; + + // Did the user destroy the topology + if (db.serverConfig && db.serverConfig.isDestroyed()) + return callback(new MongoError('topology was destroyed')); + // Process all the results from the index command and collection + function processResults(indexes) { + // Contains all the information + let info = {}; + // Process all the indexes + for (let i = 0; i < indexes.length; i++) { + const index = indexes[i]; + // Let's unpack the object + info[index.name] = []; + for (let name in index.key) { + info[index.name].push([name, index.key[name]]); + } + } + + return info; + } + + // Get the list of indexes of the specified collection + db + .collection(name) + .listIndexes(options) + .toArray((err, indexes) => { + if (err) return callback(toError(err)); + if (!Array.isArray(indexes)) return handleCallback(callback, null, []); + if (full) return handleCallback(callback, null, indexes); + handleCallback(callback, null, processResults(indexes)); + }); +} + +/** + * Retrieve the current profiling information for MongoDB + * + * @method + * @param {Db} db The Db instance on which to retrieve the profiling info. + * @param {Object} [options] Optional settings. See Db.protoype.profilingInfo for a list of options. + * @param {Db~resultCallback} [callback] The command result callback. + * @deprecated Query the system.profile collection directly. + */ +function profilingInfo(db, options, callback) { + try { + db + .collection('system.profile') + .find({}, options) + .toArray(callback); + } catch (err) { + return callback(err, null); + } +} + +/** + * Remove a user from a database + * + * @method + * @param {Db} db The Db instance on which to remove the user. + * @param {string} username The username. + * @param {object} [options] Optional settings. See Db.prototype.removeUser for a list of options. + * @param {Db~resultCallback} [callback] The command result callback + */ +function removeUser(db, username, options, callback) { + let Db = loadDb(); + + // Attempt to execute command + executeAuthRemoveUserCommand(db, username, options, (err, result) => { + if (err && err.code === -5000) { + const finalOptions = applyWriteConcern(Object.assign({}, options), { db }, options); + // If we have another db set + const db = options.dbName ? new Db(options.dbName, db.s.topology, db.s.options) : db; + + // Fetch a user collection + const collection = db.collection(CONSTANTS.SYSTEM_USER_COLLECTION); + + // Locate the user + findOne(collection, { user: username }, finalOptions, (err, user) => { + if (user == null) return handleCallback(callback, err, false); + remove(collection, { user: username }, finalOptions, err => { + handleCallback(callback, err, true); + }); + }); + + return; + } + + if (err) return handleCallback(callback, err); + handleCallback(callback, err, result); + }); +} + +// Validate the database name +function validateDatabaseName(databaseName) { + if (typeof databaseName !== 'string') + throw MongoError.create({ message: 'database name must be a string', driver: true }); + if (databaseName.length === 0) + throw MongoError.create({ message: 'database name cannot be the empty string', driver: true }); + if (databaseName === '$external') return; + + const invalidChars = [' ', '.', '$', '/', '\\']; + for (let i = 0; i < invalidChars.length; i++) { + if (databaseName.indexOf(invalidChars[i]) !== -1) + throw MongoError.create({ + message: "database names cannot contain the character '" + invalidChars[i] + "'", + driver: true + }); + } +} + +/** + * Create the command object for Db.prototype.createIndex. + * + * @param {Db} db The Db instance on which to create the command. + * @param {string} name Name of the collection to create the index on. + * @param {(string|object)} fieldOrSpec Defines the index. + * @param {Object} [options] Optional settings. See Db.prototype.createIndex for a list of options. + * @return {Object} The insert command object. + */ +function createCreateIndexCommand(db, name, fieldOrSpec, options) { + const indexParameters = parseIndexOptions(fieldOrSpec); + const fieldHash = indexParameters.fieldHash; + + // Generate the index name + const indexName = typeof options.name === 'string' ? options.name : indexParameters.name; + const selector = { + ns: db.s.namespace.withCollection(name).toString(), + key: fieldHash, + name: indexName + }; + + // Ensure we have a correct finalUnique + const finalUnique = options == null || 'object' === typeof options ? false : options; + // Set up options + options = options == null || typeof options === 'boolean' ? {} : options; + + // Add all the options + const keysToOmit = Object.keys(selector); + for (let optionName in options) { + if (keysToOmit.indexOf(optionName) === -1) { + selector[optionName] = options[optionName]; + } + } + + if (selector['unique'] == null) selector['unique'] = finalUnique; + + // Remove any write concern operations + const removeKeys = ['w', 'wtimeout', 'j', 'fsync', 'readPreference', 'session']; + for (let i = 0; i < removeKeys.length; i++) { + delete selector[removeKeys[i]]; + } + + // Return the command creation selector + return selector; +} + +/** + * Create index using the createIndexes command. + * + * @param {Db} db The Db instance on which to execute the command. + * @param {string} name Name of the collection to create the index on. + * @param {(string|object)} fieldOrSpec Defines the index. + * @param {Object} [options] Optional settings. See Db.prototype.createIndex for a list of options. + * @param {Db~resultCallback} [callback] The command result callback. + */ +function createIndexUsingCreateIndexes(db, name, fieldOrSpec, options, callback) { + // Build the index + const indexParameters = parseIndexOptions(fieldOrSpec); + // Generate the index name + const indexName = typeof options.name === 'string' ? options.name : indexParameters.name; + // Set up the index + const indexes = [{ name: indexName, key: indexParameters.fieldHash }]; + // merge all the options + const keysToOmit = Object.keys(indexes[0]).concat([ + 'writeConcern', + 'w', + 'wtimeout', + 'j', + 'fsync', + 'readPreference', + 'session' + ]); + + for (let optionName in options) { + if (keysToOmit.indexOf(optionName) === -1) { + indexes[0][optionName] = options[optionName]; + } + } + + // Get capabilities + const capabilities = db.s.topology.capabilities(); + + // Did the user pass in a collation, check if our write server supports it + if (indexes[0].collation && capabilities && !capabilities.commandsTakeCollation) { + // Create a new error + const error = new MongoError('server/primary/mongos does not support collation'); + error.code = 67; + // Return the error + return callback(error); + } + + // Create command, apply write concern to command + const cmd = applyWriteConcern({ createIndexes: name, indexes }, { db }, options); + + // ReadPreference primary + options.readPreference = ReadPreference.PRIMARY; + + // Build the command + executeCommand(db, cmd, options, (err, result) => { + if (err) return handleCallback(callback, err, null); + if (result.ok === 0) return handleCallback(callback, toError(result), null); + // Return the indexName for backward compatibility + handleCallback(callback, null, indexName); + }); +} + +/** + * Run the createUser command. + * + * @param {Db} db The Db instance on which to execute the command. + * @param {string} username The username of the user to add. + * @param {string} password The password of the user to add. + * @param {object} [options] Optional settings. See Db.prototype.addUser for a list of options. + * @param {Db~resultCallback} [callback] The command result callback + */ +function executeAuthCreateUserCommand(db, username, password, options, callback) { + // Special case where there is no password ($external users) + if (typeof username === 'string' && password != null && typeof password === 'object') { + options = password; + password = null; + } + + // Unpack all options + if (typeof options === 'function') { + callback = options; + options = {}; + } + + // Error out if we digestPassword set + if (options.digestPassword != null) { + return callback( + toError( + "The digestPassword option is not supported via add_user. Please use db.command('createUser', ...) instead for this option." + ) + ); + } + + // Get additional values + const customData = options.customData != null ? options.customData : {}; + let roles = Array.isArray(options.roles) ? options.roles : []; + const maxTimeMS = typeof options.maxTimeMS === 'number' ? options.maxTimeMS : null; + + // If not roles defined print deprecated message + if (roles.length === 0) { + console.log('Creating a user without roles is deprecated in MongoDB >= 2.6'); + } + + // Get the error options + const commandOptions = { writeCommand: true }; + if (options['dbName']) commandOptions.dbName = options['dbName']; + + // Add maxTimeMS to options if set + if (maxTimeMS != null) commandOptions.maxTimeMS = maxTimeMS; + + // Check the db name and add roles if needed + if ( + (db.databaseName.toLowerCase() === 'admin' || options.dbName === 'admin') && + !Array.isArray(options.roles) + ) { + roles = ['root']; + } else if (!Array.isArray(options.roles)) { + roles = ['dbOwner']; + } + + const digestPassword = db.s.topology.lastIsMaster().maxWireVersion >= 7; + + // Build the command to execute + let command = { + createUser: username, + customData: customData, + roles: roles, + digestPassword + }; + + // Apply write concern to command + command = applyWriteConcern(command, { db }, options); + + let userPassword = password; + + if (!digestPassword) { + // Use node md5 generator + const md5 = crypto.createHash('md5'); + // Generate keys used for authentication + md5.update(username + ':mongo:' + password); + userPassword = md5.digest('hex'); + } + + // No password + if (typeof password === 'string') { + command.pwd = userPassword; + } + + // Force write using primary + commandOptions.readPreference = ReadPreference.primary; + + // Execute the command + executeCommand(db, command, commandOptions, (err, result) => { + if (err && err.ok === 0 && err.code === undefined) + return handleCallback(callback, { code: -5000 }, null); + if (err) return handleCallback(callback, err, null); + handleCallback( + callback, + !result.ok ? toError(result) : null, + result.ok ? [{ user: username, pwd: '' }] : null + ); + }); +} + +/** + * Run the dropUser command. + * + * @param {Db} db The Db instance on which to execute the command. + * @param {string} username The username of the user to remove. + * @param {object} [options] Optional settings. See Db.prototype.removeUser for a list of options. + * @param {Db~resultCallback} [callback] The command result callback + */ +function executeAuthRemoveUserCommand(db, username, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + // Did the user destroy the topology + if (db.serverConfig && db.serverConfig.isDestroyed()) + return callback(new MongoError('topology was destroyed')); + // Get the error options + const commandOptions = { writeCommand: true }; + if (options['dbName']) commandOptions.dbName = options['dbName']; + + // Get additional values + const maxTimeMS = typeof options.maxTimeMS === 'number' ? options.maxTimeMS : null; + + // Add maxTimeMS to options if set + if (maxTimeMS != null) commandOptions.maxTimeMS = maxTimeMS; + + // Build the command to execute + let command = { + dropUser: username + }; + + // Apply write concern to command + command = applyWriteConcern(command, { db }, options); + + // Force write using primary + commandOptions.readPreference = ReadPreference.primary; + + // Execute the command + executeCommand(db, command, commandOptions, (err, result) => { + if (err && !err.ok && err.code === undefined) return handleCallback(callback, { code: -5000 }); + if (err) return handleCallback(callback, err, null); + handleCallback(callback, null, result.ok ? true : false); + }); +} + +module.exports = { + addUser, + collections, + createListener, + createIndex, + dropCollection, + dropDatabase, + ensureIndex, + evaluate, + executeCommand, + executeDbAdminCommand, + indexInformation, + profilingInfo, + removeUser, + validateDatabaseName +}; diff --git a/scripts/node_modules/mongodb/lib/operations/delete_many.js b/scripts/node_modules/mongodb/lib/operations/delete_many.js new file mode 100644 index 00000000..d881f67d --- /dev/null +++ b/scripts/node_modules/mongodb/lib/operations/delete_many.js @@ -0,0 +1,25 @@ +'use strict'; + +const OperationBase = require('./operation').OperationBase; +const deleteCallback = require('./common_functions').deleteCallback; +const removeDocuments = require('./common_functions').removeDocuments; + +class DeleteManyOperation extends OperationBase { + constructor(collection, filter, options) { + super(options); + + this.collection = collection; + this.filter = filter; + } + + execute(callback) { + const coll = this.collection; + const filter = this.filter; + const options = this.options; + + options.single = false; + removeDocuments(coll, filter, options, (err, r) => deleteCallback(err, r, callback)); + } +} + +module.exports = DeleteManyOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/delete_one.js b/scripts/node_modules/mongodb/lib/operations/delete_one.js new file mode 100644 index 00000000..b05597fd --- /dev/null +++ b/scripts/node_modules/mongodb/lib/operations/delete_one.js @@ -0,0 +1,25 @@ +'use strict'; + +const OperationBase = require('./operation').OperationBase; +const deleteCallback = require('./common_functions').deleteCallback; +const removeDocuments = require('./common_functions').removeDocuments; + +class DeleteOneOperation extends OperationBase { + constructor(collection, filter, options) { + super(options); + + this.collection = collection; + this.filter = filter; + } + + execute(callback) { + const coll = this.collection; + const filter = this.filter; + const options = this.options; + + options.single = true; + removeDocuments(coll, filter, options, (err, r) => deleteCallback(err, r, callback)); + } +} + +module.exports = DeleteOneOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/distinct.js b/scripts/node_modules/mongodb/lib/operations/distinct.js new file mode 100644 index 00000000..dcf4f7e2 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/operations/distinct.js @@ -0,0 +1,85 @@ +'use strict'; + +const Aspect = require('./operation').Aspect; +const defineAspects = require('./operation').defineAspects; +const CommandOperationV2 = require('./command_v2'); +const decorateWithCollation = require('../utils').decorateWithCollation; +const decorateWithReadConcern = require('../utils').decorateWithReadConcern; + +/** + * Return a list of distinct values for the given key across a collection. + * + * @class + * @property {Collection} a Collection instance. + * @property {string} key Field of the document to find distinct values for. + * @property {object} query The query for filtering the set of documents to which we apply the distinct filter. + * @property {object} [options] Optional settings. See Collection.prototype.distinct for a list of options. + */ +class DistinctOperation extends CommandOperationV2 { + /** + * Construct a Distinct operation. + * + * @param {Collection} a Collection instance. + * @param {string} key Field of the document to find distinct values for. + * @param {object} query The query for filtering the set of documents to which we apply the distinct filter. + * @param {object} [options] Optional settings. See Collection.prototype.distinct for a list of options. + */ + constructor(collection, key, query, options) { + super(collection, options); + + this.collection = collection; + this.key = key; + this.query = query; + } + + /** + * Execute the operation. + * + * @param {Collection~resultCallback} [callback] The command result callback + */ + execute(server, callback) { + const coll = this.collection; + const key = this.key; + const query = this.query; + const options = this.options; + + // Distinct command + const cmd = { + distinct: coll.collectionName, + key: key, + query: query + }; + + // Add maxTimeMS if defined + if (typeof options.maxTimeMS === 'number') { + cmd.maxTimeMS = options.maxTimeMS; + } + + // Do we have a readConcern specified + decorateWithReadConcern(cmd, coll, options); + + // Have we specified collation + try { + decorateWithCollation(cmd, coll, options); + } catch (err) { + return callback(err, null); + } + + super.executeCommand(server, cmd, (err, result) => { + if (err) { + callback(err); + return; + } + + callback(null, this.options.full ? result : result.values); + }); + } +} + +defineAspects(DistinctOperation, [ + Aspect.READ_OPERATION, + Aspect.RETRYABLE, + Aspect.EXECUTE_WITH_SELECTION +]); + +module.exports = DistinctOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/drop.js b/scripts/node_modules/mongodb/lib/operations/drop.js new file mode 100644 index 00000000..be03716f --- /dev/null +++ b/scripts/node_modules/mongodb/lib/operations/drop.js @@ -0,0 +1,53 @@ +'use strict'; + +const Aspect = require('./operation').Aspect; +const CommandOperation = require('./command'); +const defineAspects = require('./operation').defineAspects; +const handleCallback = require('../utils').handleCallback; + +class DropOperation extends CommandOperation { + constructor(db, options) { + const finalOptions = Object.assign({}, options, db.s.options); + + if (options.session) { + finalOptions.session = options.session; + } + + super(db, finalOptions); + } + + execute(callback) { + super.execute((err, result) => { + if (err) return handleCallback(callback, err); + if (result.ok) return handleCallback(callback, null, true); + handleCallback(callback, null, false); + }); + } +} + +defineAspects(DropOperation, Aspect.WRITE_OPERATION); + +class DropCollectionOperation extends DropOperation { + constructor(db, name, options) { + super(db, options); + + this.name = name; + this.namespace = `${db.namespace}.${name}`; + } + + _buildCommand() { + return { drop: this.name }; + } +} + +class DropDatabaseOperation extends DropOperation { + _buildCommand() { + return { dropDatabase: 1 }; + } +} + +module.exports = { + DropOperation, + DropCollectionOperation, + DropDatabaseOperation +}; diff --git a/scripts/node_modules/mongodb/lib/operations/drop_index.js b/scripts/node_modules/mongodb/lib/operations/drop_index.js new file mode 100644 index 00000000..a6ca783d --- /dev/null +++ b/scripts/node_modules/mongodb/lib/operations/drop_index.js @@ -0,0 +1,42 @@ +'use strict'; + +const Aspect = require('./operation').Aspect; +const defineAspects = require('./operation').defineAspects; +const CommandOperation = require('./command'); +const applyWriteConcern = require('../utils').applyWriteConcern; +const handleCallback = require('../utils').handleCallback; + +class DropIndexOperation extends CommandOperation { + constructor(collection, indexName, options) { + super(collection.s.db, options, collection); + + this.collection = collection; + this.indexName = indexName; + } + + _buildCommand() { + const collection = this.collection; + const indexName = this.indexName; + const options = this.options; + + let cmd = { dropIndexes: collection.collectionName, index: indexName }; + + // Decorate command with writeConcern if supported + cmd = applyWriteConcern(cmd, { db: collection.s.db, collection }, options); + + return cmd; + } + + execute(callback) { + // Execute command + super.execute((err, result) => { + if (typeof callback !== 'function') return; + if (err) return handleCallback(callback, err, null); + handleCallback(callback, null, result); + }); + } +} + +defineAspects(DropIndexOperation, Aspect.WRITE_OPERATION); + +module.exports = DropIndexOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/drop_indexes.js b/scripts/node_modules/mongodb/lib/operations/drop_indexes.js new file mode 100644 index 00000000..ed404ee9 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/operations/drop_indexes.js @@ -0,0 +1,23 @@ +'use strict'; + +const Aspect = require('./operation').Aspect; +const defineAspects = require('./operation').defineAspects; +const DropIndexOperation = require('./drop_index'); +const handleCallback = require('../utils').handleCallback; + +class DropIndexesOperation extends DropIndexOperation { + constructor(collection, options) { + super(collection, '*', options); + } + + execute(callback) { + super.execute(err => { + if (err) return handleCallback(callback, err, false); + handleCallback(callback, null, true); + }); + } +} + +defineAspects(DropIndexesOperation, Aspect.WRITE_OPERATION); + +module.exports = DropIndexesOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/estimated_document_count.js b/scripts/node_modules/mongodb/lib/operations/estimated_document_count.js new file mode 100644 index 00000000..e2d65563 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/operations/estimated_document_count.js @@ -0,0 +1,58 @@ +'use strict'; + +const Aspect = require('./operation').Aspect; +const defineAspects = require('./operation').defineAspects; +const CommandOperationV2 = require('./command_v2'); + +class EstimatedDocumentCountOperation extends CommandOperationV2 { + constructor(collection, query, options) { + if (typeof options === 'undefined') { + options = query; + query = undefined; + } + + super(collection, options); + this.collectionName = collection.s.namespace.collection; + if (query) { + this.query = query; + } + } + + execute(server, callback) { + const options = this.options; + const cmd = { count: this.collectionName }; + + if (this.query) { + cmd.query = this.query; + } + + if (typeof options.skip === 'number') { + cmd.skip = options.skip; + } + + if (typeof options.limit === 'number') { + cmd.limit = options.limit; + } + + if (options.hint) { + cmd.hint = options.hint; + } + + super.executeCommand(server, cmd, (err, response) => { + if (err) { + callback(err); + return; + } + + callback(null, response.n); + }); + } +} + +defineAspects(EstimatedDocumentCountOperation, [ + Aspect.READ_OPERATION, + Aspect.RETRYABLE, + Aspect.EXECUTE_WITH_SELECTION +]); + +module.exports = EstimatedDocumentCountOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/execute_db_admin_command.js b/scripts/node_modules/mongodb/lib/operations/execute_db_admin_command.js new file mode 100644 index 00000000..d15fc8e6 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/operations/execute_db_admin_command.js @@ -0,0 +1,34 @@ +'use strict'; + +const OperationBase = require('./operation').OperationBase; +const handleCallback = require('../utils').handleCallback; +const MongoError = require('../core').MongoError; +const MongoDBNamespace = require('../utils').MongoDBNamespace; + +class ExecuteDbAdminCommandOperation extends OperationBase { + constructor(db, selector, options) { + super(options); + + this.db = db; + this.selector = selector; + } + + execute(callback) { + const db = this.db; + const selector = this.selector; + const options = this.options; + + const namespace = new MongoDBNamespace('admin', '$cmd'); + db.s.topology.command(namespace, selector, options, (err, result) => { + // Did the user destroy the topology + if (db.serverConfig && db.serverConfig.isDestroyed()) { + return callback(new MongoError('topology was destroyed')); + } + + if (err) return handleCallback(callback, err); + handleCallback(callback, null, result.result); + }); + } +} + +module.exports = ExecuteDbAdminCommandOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/execute_operation.js b/scripts/node_modules/mongodb/lib/operations/execute_operation.js new file mode 100644 index 00000000..e23a80c0 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/operations/execute_operation.js @@ -0,0 +1,198 @@ +'use strict'; + +const MongoError = require('../core/error').MongoError; +const Aspect = require('./operation').Aspect; +const OperationBase = require('./operation').OperationBase; +const ReadPreference = require('../core/topologies/read_preference'); +const isRetryableError = require('../core/error').isRetryableError; +const maxWireVersion = require('../core/utils').maxWireVersion; +const isUnifiedTopology = require('../core/utils').isUnifiedTopology; + +/** + * Executes the given operation with provided arguments. + * + * This method reduces large amounts of duplication in the entire codebase by providing + * a single point for determining whether callbacks or promises should be used. Additionally + * it allows for a single point of entry to provide features such as implicit sessions, which + * are required by the Driver Sessions specification in the event that a ClientSession is + * not provided + * + * @param {object} topology The topology to execute this operation on + * @param {Operation} operation The operation to execute + * @param {function} callback The command result callback + */ +function executeOperation(topology, operation, callback) { + if (topology == null) { + throw new TypeError('This method requires a valid topology instance'); + } + + if (!(operation instanceof OperationBase)) { + throw new TypeError('This method requires a valid operation instance'); + } + + if ( + isUnifiedTopology(topology) && + !operation.hasAspect(Aspect.SKIP_SESSION) && + topology.shouldCheckForSessionSupport() + ) { + return selectServerForSessionSupport(topology, operation, callback); + } + + const Promise = topology.s.promiseLibrary; + + // The driver sessions spec mandates that we implicitly create sessions for operations + // that are not explicitly provided with a session. + let session, owner; + if (!operation.hasAspect(Aspect.SKIP_SESSION) && topology.hasSessionSupport()) { + if (operation.session == null) { + owner = Symbol(); + session = topology.startSession({ owner }); + operation.session = session; + } else if (operation.session.hasEnded) { + throw new MongoError('Use of expired sessions is not permitted'); + } + } + + const makeExecuteCallback = (resolve, reject) => + function executeCallback(err, result) { + if (session && session.owner === owner) { + session.endSession(() => { + if (operation.session === session) { + operation.clearSession(); + } + if (err) return reject(err); + resolve(result); + }); + } else { + if (err) return reject(err); + resolve(result); + } + }; + + // Execute using callback + if (typeof callback === 'function') { + const handler = makeExecuteCallback( + result => callback(null, result), + err => callback(err, null) + ); + + try { + if (operation.hasAspect(Aspect.EXECUTE_WITH_SELECTION)) { + return executeWithServerSelection(topology, operation, handler); + } else { + return operation.execute(handler); + } + } catch (e) { + handler(e); + throw e; + } + } + + return new Promise(function(resolve, reject) { + const handler = makeExecuteCallback(resolve, reject); + + try { + if (operation.hasAspect(Aspect.EXECUTE_WITH_SELECTION)) { + return executeWithServerSelection(topology, operation, handler); + } else { + return operation.execute(handler); + } + } catch (e) { + handler(e); + } + }); +} + +function supportsRetryableReads(server) { + return maxWireVersion(server) >= 6; +} + +function executeWithServerSelection(topology, operation, callback) { + const readPreference = operation.readPreference || ReadPreference.primary; + const inTransaction = operation.session && operation.session.inTransaction(); + + if (inTransaction && !readPreference.equals(ReadPreference.primary)) { + callback( + new MongoError( + `Read preference in a transaction must be primary, not: ${readPreference.mode}` + ) + ); + + return; + } + + const serverSelectionOptions = { + readPreference, + session: operation.session + }; + + function callbackWithRetry(err, result) { + if (err == null) { + return callback(null, result); + } + + if (!isRetryableError(err)) { + return callback(err); + } + + // select a new server, and attempt to retry the operation + topology.selectServer(serverSelectionOptions, (err, server) => { + if (err || !supportsRetryableReads(server)) { + callback(err, null); + return; + } + + operation.execute(server, callback); + }); + } + + // select a server, and execute the operation against it + topology.selectServer(serverSelectionOptions, (err, server) => { + if (err) { + callback(err, null); + return; + } + + const shouldRetryReads = + topology.s.options.retryReads !== false && + (operation.session && !inTransaction) && + supportsRetryableReads(server) && + operation.canRetryRead; + + if (operation.hasAspect(Aspect.RETRYABLE) && shouldRetryReads) { + operation.execute(server, callbackWithRetry); + return; + } + + operation.execute(server, callback); + }); +} + +// TODO: This is only supported for unified topology, it should go away once +// we remove support for legacy topology types. +function selectServerForSessionSupport(topology, operation, callback) { + const Promise = topology.s.promiseLibrary; + + let result; + if (typeof callback !== 'function') { + result = new Promise((resolve, reject) => { + callback = (err, result) => { + if (err) return reject(err); + resolve(result); + }; + }); + } + + topology.selectServer(ReadPreference.primaryPreferred, err => { + if (err) { + callback(err); + return; + } + + executeOperation(topology, operation, callback); + }); + + return result; +} + +module.exports = executeOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/explain.js b/scripts/node_modules/mongodb/lib/operations/explain.js new file mode 100644 index 00000000..44f3b483 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/operations/explain.js @@ -0,0 +1,23 @@ +'use strict'; + +const Aspect = require('./operation').Aspect; +const CoreCursor = require('../core/cursor').CoreCursor; +const defineAspects = require('./operation').defineAspects; +const OperationBase = require('./operation').OperationBase; + +class ExplainOperation extends OperationBase { + constructor(cursor) { + super(); + + this.cursor = cursor; + } + + execute() { + const cursor = this.cursor; + return CoreCursor.prototype._next.apply(cursor, arguments); + } +} + +defineAspects(ExplainOperation, Aspect.SKIP_SESSION); + +module.exports = ExplainOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/find.js b/scripts/node_modules/mongodb/lib/operations/find.js new file mode 100644 index 00000000..6838213c --- /dev/null +++ b/scripts/node_modules/mongodb/lib/operations/find.js @@ -0,0 +1,35 @@ +'use strict'; + +const OperationBase = require('./operation').OperationBase; +const Aspect = require('./operation').Aspect; +const defineAspects = require('./operation').defineAspects; +const resolveReadPreference = require('../utils').resolveReadPreference; + +class FindOperation extends OperationBase { + constructor(collection, ns, command, options) { + super(options); + + this.ns = ns; + this.cmd = command; + this.readPreference = resolveReadPreference(collection, this.options); + } + + execute(server, callback) { + // copied from `CommandOperationV2`, to be subclassed in the future + this.server = server; + + const cursorState = this.cursorState || {}; + + // TOOD: use `MongoDBNamespace` through and through + server.query(this.ns.toString(), this.cmd, cursorState, this.options, callback); + } +} + +defineAspects(FindOperation, [ + Aspect.READ_OPERATION, + Aspect.RETRYABLE, + Aspect.EXECUTE_WITH_SELECTION, + Aspect.SKIP_SESSION +]); + +module.exports = FindOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/find_and_modify.js b/scripts/node_modules/mongodb/lib/operations/find_and_modify.js new file mode 100644 index 00000000..8965eb48 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/operations/find_and_modify.js @@ -0,0 +1,98 @@ +'use strict'; + +const OperationBase = require('./operation').OperationBase; +const applyRetryableWrites = require('../utils').applyRetryableWrites; +const applyWriteConcern = require('../utils').applyWriteConcern; +const decorateWithCollation = require('../utils').decorateWithCollation; +const executeCommand = require('./db_ops').executeCommand; +const formattedOrderClause = require('../utils').formattedOrderClause; +const handleCallback = require('../utils').handleCallback; +const ReadPreference = require('../core').ReadPreference; + +class FindAndModifyOperation extends OperationBase { + constructor(collection, query, sort, doc, options) { + super(options); + + this.collection = collection; + this.query = query; + this.sort = sort; + this.doc = doc; + } + + execute(callback) { + const coll = this.collection; + const query = this.query; + const sort = formattedOrderClause(this.sort); + const doc = this.doc; + let options = this.options; + + // Create findAndModify command object + const queryObject = { + findAndModify: coll.collectionName, + query: query + }; + + if (sort) { + queryObject.sort = sort; + } + + queryObject.new = options.new ? true : false; + queryObject.remove = options.remove ? true : false; + queryObject.upsert = options.upsert ? true : false; + + const projection = options.projection || options.fields; + + if (projection) { + queryObject.fields = projection; + } + + if (options.arrayFilters) { + queryObject.arrayFilters = options.arrayFilters; + } + + if (doc && !options.remove) { + queryObject.update = doc; + } + + if (options.maxTimeMS) queryObject.maxTimeMS = options.maxTimeMS; + + // Either use override on the function, or go back to default on either the collection + // level or db + options.serializeFunctions = options.serializeFunctions || coll.s.serializeFunctions; + + // No check on the documents + options.checkKeys = false; + + // Final options for retryable writes and write concern + options = applyRetryableWrites(options, coll.s.db); + options = applyWriteConcern(options, { db: coll.s.db, collection: coll }, options); + + // Decorate the findAndModify command with the write Concern + if (options.writeConcern) { + queryObject.writeConcern = options.writeConcern; + } + + // Have we specified bypassDocumentValidation + if (options.bypassDocumentValidation === true) { + queryObject.bypassDocumentValidation = options.bypassDocumentValidation; + } + + options.readPreference = ReadPreference.primary; + + // Have we specified collation + try { + decorateWithCollation(queryObject, coll, options); + } catch (err) { + return callback(err, null); + } + + // Execute the command + executeCommand(coll.s.db, queryObject, options, (err, result) => { + if (err) return handleCallback(callback, err, null); + + return handleCallback(callback, null, result); + }); + } +} + +module.exports = FindAndModifyOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/find_one.js b/scripts/node_modules/mongodb/lib/operations/find_one.js new file mode 100644 index 00000000..d3037a6d --- /dev/null +++ b/scripts/node_modules/mongodb/lib/operations/find_one.js @@ -0,0 +1,33 @@ +'use strict'; + +const handleCallback = require('../utils').handleCallback; +const OperationBase = require('./operation').OperationBase; +const toError = require('../utils').toError; + +class FindOneOperation extends OperationBase { + constructor(collection, query, options) { + super(options); + + this.collection = collection; + this.query = query; + } + + execute(callback) { + const coll = this.collection; + const query = this.query; + const options = this.options; + + const cursor = coll + .find(query, options) + .limit(-1) + .batchSize(1); + + // Return the item + cursor.next((err, item) => { + if (err != null) return handleCallback(callback, toError(err), null); + handleCallback(callback, null, item); + }); + } +} + +module.exports = FindOneOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/find_one_and_delete.js b/scripts/node_modules/mongodb/lib/operations/find_one_and_delete.js new file mode 100644 index 00000000..1c7527dd --- /dev/null +++ b/scripts/node_modules/mongodb/lib/operations/find_one_and_delete.js @@ -0,0 +1,16 @@ +'use strict'; + +const FindAndModifyOperation = require('./find_and_modify'); + +class FindOneAndDeleteOperation extends FindAndModifyOperation { + constructor(collection, filter, options) { + // Final options + const finalOptions = Object.assign({}, options); + finalOptions.fields = options.projection; + finalOptions.remove = true; + + super(collection, filter, finalOptions.sort, null, finalOptions); + } +} + +module.exports = FindOneAndDeleteOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/find_one_and_replace.js b/scripts/node_modules/mongodb/lib/operations/find_one_and_replace.js new file mode 100644 index 00000000..ae37df5d --- /dev/null +++ b/scripts/node_modules/mongodb/lib/operations/find_one_and_replace.js @@ -0,0 +1,18 @@ +'use strict'; + +const FindAndModifyOperation = require('./find_and_modify'); + +class FindOneAndReplaceOperation extends FindAndModifyOperation { + constructor(collection, filter, replacement, options) { + // Final options + const finalOptions = Object.assign({}, options); + finalOptions.fields = options.projection; + finalOptions.update = true; + finalOptions.new = options.returnOriginal !== void 0 ? !options.returnOriginal : false; + finalOptions.upsert = options.upsert !== void 0 ? !!options.upsert : false; + + super(collection, filter, finalOptions.sort, replacement, finalOptions); + } +} + +module.exports = FindOneAndReplaceOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/find_one_and_update.js b/scripts/node_modules/mongodb/lib/operations/find_one_and_update.js new file mode 100644 index 00000000..6a199652 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/operations/find_one_and_update.js @@ -0,0 +1,19 @@ +'use strict'; + +const FindAndModifyOperation = require('./find_and_modify'); + +class FindOneAndUpdateOperation extends FindAndModifyOperation { + constructor(collection, filter, update, options) { + // Final options + const finalOptions = Object.assign({}, options); + finalOptions.fields = options.projection; + finalOptions.update = true; + finalOptions.new = + typeof options.returnOriginal === 'boolean' ? !options.returnOriginal : false; + finalOptions.upsert = typeof options.upsert === 'boolean' ? options.upsert : false; + + super(collection, filter, finalOptions.sort, update, finalOptions); + } +} + +module.exports = FindOneAndUpdateOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/geo_haystack_search.js b/scripts/node_modules/mongodb/lib/operations/geo_haystack_search.js new file mode 100644 index 00000000..edd1fb17 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/operations/geo_haystack_search.js @@ -0,0 +1,79 @@ +'use strict'; + +const Aspect = require('./operation').Aspect; +const defineAspects = require('./operation').defineAspects; +const OperationBase = require('./operation').OperationBase; +const decorateCommand = require('../utils').decorateCommand; +const decorateWithReadConcern = require('../utils').decorateWithReadConcern; +const executeCommand = require('./db_ops').executeCommand; +const handleCallback = require('../utils').handleCallback; +const resolveReadPreference = require('../utils').resolveReadPreference; +const toError = require('../utils').toError; + +/** + * Execute a geo search using a geo haystack index on a collection. + * + * @class + * @property {Collection} a Collection instance. + * @property {number} x Point to search on the x axis, ensure the indexes are ordered in the same order. + * @property {number} y Point to search on the y axis, ensure the indexes are ordered in the same order. + * @property {object} [options] Optional settings. See Collection.prototype.geoHaystackSearch for a list of options. + */ +class GeoHaystackSearchOperation extends OperationBase { + /** + * Construct a GeoHaystackSearch operation. + * + * @param {Collection} a Collection instance. + * @param {number} x Point to search on the x axis, ensure the indexes are ordered in the same order. + * @param {number} y Point to search on the y axis, ensure the indexes are ordered in the same order. + * @param {object} [options] Optional settings. See Collection.prototype.geoHaystackSearch for a list of options. + */ + constructor(collection, x, y, options) { + super(options); + + this.collection = collection; + this.x = x; + this.y = y; + } + + /** + * Execute the operation. + * + * @param {Collection~resultCallback} [callback] The command result callback + */ + execute(callback) { + const coll = this.collection; + const x = this.x; + const y = this.y; + let options = this.options; + + // Build command object + let commandObject = { + geoSearch: coll.collectionName, + near: [x, y] + }; + + // Remove read preference from hash if it exists + commandObject = decorateCommand(commandObject, options, ['readPreference', 'session']); + + options = Object.assign({}, options); + // Ensure we have the right read preference inheritance + options.readPreference = resolveReadPreference(coll, options); + + // Do we have a readConcern specified + decorateWithReadConcern(commandObject, coll, options); + + // Execute the command + executeCommand(coll.s.db, commandObject, options, (err, res) => { + if (err) return handleCallback(callback, err); + if (res.err || res.errmsg) handleCallback(callback, toError(res)); + // should we only be returning res.results here? Not sure if the user + // should see the other return information + handleCallback(callback, null, res); + }); + } +} + +defineAspects(GeoHaystackSearchOperation, Aspect.READ_OPERATION); + +module.exports = GeoHaystackSearchOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/has_next.js b/scripts/node_modules/mongodb/lib/operations/has_next.js new file mode 100644 index 00000000..b2e4b861 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/operations/has_next.js @@ -0,0 +1,40 @@ +'use strict'; + +const Aspect = require('./operation').Aspect; +const defineAspects = require('./operation').defineAspects; +const loadCursor = require('../dynamic_loaders').loadCursor; +const OperationBase = require('./operation').OperationBase; +const nextObject = require('./common_functions').nextObject; + +class HasNextOperation extends OperationBase { + constructor(cursor) { + super(); + + this.cursor = cursor; + } + + execute(callback) { + const cursor = this.cursor; + let Cursor = loadCursor(); + + if (cursor.s.currentDoc) { + return callback(null, true); + } + + if (cursor.isNotified()) { + return callback(null, false); + } + + nextObject(cursor, (err, doc) => { + if (err) return callback(err, null); + if (cursor.s.state === Cursor.CLOSED || cursor.isDead()) return callback(null, false); + if (!doc) return callback(null, false); + cursor.s.currentDoc = doc; + callback(null, true); + }); + } +} + +defineAspects(HasNextOperation, Aspect.SKIP_SESSION); + +module.exports = HasNextOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/index_exists.js b/scripts/node_modules/mongodb/lib/operations/index_exists.js new file mode 100644 index 00000000..bd9dc0e9 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/operations/index_exists.js @@ -0,0 +1,39 @@ +'use strict'; + +const OperationBase = require('./operation').OperationBase; +const handleCallback = require('../utils').handleCallback; +const indexInformationDb = require('./db_ops').indexInformation; + +class IndexExistsOperation extends OperationBase { + constructor(collection, indexes, options) { + super(options); + + this.collection = collection; + this.indexes = indexes; + } + + execute(callback) { + const coll = this.collection; + const indexes = this.indexes; + const options = this.options; + + indexInformationDb(coll.s.db, coll.collectionName, options, (err, indexInformation) => { + // If we have an error return + if (err != null) return handleCallback(callback, err, null); + // Let's check for the index names + if (!Array.isArray(indexes)) + return handleCallback(callback, null, indexInformation[indexes] != null); + // Check in list of indexes + for (let i = 0; i < indexes.length; i++) { + if (indexInformation[indexes[i]] == null) { + return handleCallback(callback, null, false); + } + } + + // All keys found return true + return handleCallback(callback, null, true); + }); + } +} + +module.exports = IndexExistsOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/index_information.js b/scripts/node_modules/mongodb/lib/operations/index_information.js new file mode 100644 index 00000000..b18a603f --- /dev/null +++ b/scripts/node_modules/mongodb/lib/operations/index_information.js @@ -0,0 +1,23 @@ +'use strict'; + +const OperationBase = require('./operation').OperationBase; +const indexInformation = require('./common_functions').indexInformation; + +class IndexInformationOperation extends OperationBase { + constructor(db, name, options) { + super(options); + + this.db = db; + this.name = name; + } + + execute(callback) { + const db = this.db; + const name = this.name; + const options = this.options; + + indexInformation(db, name, options, callback); + } +} + +module.exports = IndexInformationOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/indexes.js b/scripts/node_modules/mongodb/lib/operations/indexes.js new file mode 100644 index 00000000..e29a88aa --- /dev/null +++ b/scripts/node_modules/mongodb/lib/operations/indexes.js @@ -0,0 +1,22 @@ +'use strict'; + +const OperationBase = require('./operation').OperationBase; +const indexInformation = require('./common_functions').indexInformation; + +class IndexesOperation extends OperationBase { + constructor(collection, options) { + super(options); + + this.collection = collection; + } + + execute(callback) { + const coll = this.collection; + let options = this.options; + + options = Object.assign({}, { full: true }, options); + indexInformation(coll.s.db, coll.collectionName, options, callback); + } +} + +module.exports = IndexesOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/insert_many.js b/scripts/node_modules/mongodb/lib/operations/insert_many.js new file mode 100644 index 00000000..460a535d --- /dev/null +++ b/scripts/node_modules/mongodb/lib/operations/insert_many.js @@ -0,0 +1,63 @@ +'use strict'; + +const OperationBase = require('./operation').OperationBase; +const BulkWriteOperation = require('./bulk_write'); +const MongoError = require('../core').MongoError; +const prepareDocs = require('./common_functions').prepareDocs; + +class InsertManyOperation extends OperationBase { + constructor(collection, docs, options) { + super(options); + + this.collection = collection; + this.docs = docs; + } + + execute(callback) { + const coll = this.collection; + let docs = this.docs; + const options = this.options; + + if (!Array.isArray(docs)) { + return callback( + MongoError.create({ message: 'docs parameter must be an array of documents', driver: true }) + ); + } + + // If keep going set unordered + options['serializeFunctions'] = options['serializeFunctions'] || coll.s.serializeFunctions; + + docs = prepareDocs(coll, docs, options); + + // Generate the bulk write operations + const operations = [ + { + insertMany: docs + } + ]; + + const bulkWriteOperation = new BulkWriteOperation(coll, operations, options); + + bulkWriteOperation.execute((err, result) => { + if (err) return callback(err, null); + callback(null, mapInsertManyResults(docs, result)); + }); + } +} + +function mapInsertManyResults(docs, r) { + const finalResult = { + result: { ok: 1, n: r.insertedCount }, + ops: docs, + insertedCount: r.insertedCount, + insertedIds: r.insertedIds + }; + + if (r.getLastOp()) { + finalResult.result.opTime = r.getLastOp(); + } + + return finalResult; +} + +module.exports = InsertManyOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/insert_one.js b/scripts/node_modules/mongodb/lib/operations/insert_one.js new file mode 100644 index 00000000..5e708801 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/operations/insert_one.js @@ -0,0 +1,39 @@ +'use strict'; + +const MongoError = require('../core').MongoError; +const OperationBase = require('./operation').OperationBase; +const insertDocuments = require('./common_functions').insertDocuments; + +class InsertOneOperation extends OperationBase { + constructor(collection, doc, options) { + super(options); + + this.collection = collection; + this.doc = doc; + } + + execute(callback) { + const coll = this.collection; + const doc = this.doc; + const options = this.options; + + if (Array.isArray(doc)) { + return callback( + MongoError.create({ message: 'doc parameter must be an object', driver: true }) + ); + } + + insertDocuments(coll, [doc], options, (err, r) => { + if (callback == null) return; + if (err && callback) return callback(err); + // Workaround for pre 2.6 servers + if (r == null) return callback(null, { result: { ok: 1 } }); + // Add values to top level to ensure crud spec compatibility + r.insertedCount = r.result.n; + r.insertedId = doc._id; + if (callback) callback(null, r); + }); + } +} + +module.exports = InsertOneOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/is_capped.js b/scripts/node_modules/mongodb/lib/operations/is_capped.js new file mode 100644 index 00000000..3bfd9ffa --- /dev/null +++ b/scripts/node_modules/mongodb/lib/operations/is_capped.js @@ -0,0 +1,19 @@ +'use strict'; + +const OptionsOperation = require('./options_operation'); +const handleCallback = require('../utils').handleCallback; + +class IsCappedOperation extends OptionsOperation { + constructor(collection, options) { + super(collection, options); + } + + execute(callback) { + super.execute((err, document) => { + if (err) return handleCallback(callback, err); + handleCallback(callback, null, !!(document && document.capped)); + }); + } +} + +module.exports = IsCappedOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/list_collections.js b/scripts/node_modules/mongodb/lib/operations/list_collections.js new file mode 100644 index 00000000..ee01d31e --- /dev/null +++ b/scripts/node_modules/mongodb/lib/operations/list_collections.js @@ -0,0 +1,106 @@ +'use strict'; + +const CommandOperationV2 = require('./command_v2'); +const Aspect = require('./operation').Aspect; +const defineAspects = require('./operation').defineAspects; +const maxWireVersion = require('../core/utils').maxWireVersion; +const CONSTANTS = require('../constants'); + +const LIST_COLLECTIONS_WIRE_VERSION = 3; + +function listCollectionsTransforms(databaseName) { + const matching = `${databaseName}.`; + + return { + doc: doc => { + const index = doc.name.indexOf(matching); + // Remove database name if available + if (doc.name && index === 0) { + doc.name = doc.name.substr(index + matching.length); + } + + return doc; + } + }; +} + +class ListCollectionsOperation extends CommandOperationV2 { + constructor(db, filter, options) { + super(db, options, { fullResponse: true }); + + this.db = db; + this.filter = filter; + this.nameOnly = !!this.options.nameOnly; + + if (typeof this.options.batchSize === 'number') { + this.batchSize = this.options.batchSize; + } + } + + execute(server, callback) { + if (maxWireVersion(server) < LIST_COLLECTIONS_WIRE_VERSION) { + let filter = this.filter; + const databaseName = this.db.s.namespace.db; + + // If we have legacy mode and have not provided a full db name filter it + if ( + typeof filter.name === 'string' && + !new RegExp('^' + databaseName + '\\.').test(filter.name) + ) { + filter = Object.assign({}, filter); + filter.name = this.db.s.namespace.withCollection(filter.name).toString(); + } + + // No filter, filter by current database + if (filter == null) { + filter.name = `/${databaseName}/`; + } + + // Rewrite the filter to use $and to filter out indexes + if (filter.name) { + filter = { $and: [{ name: filter.name }, { name: /^((?!\$).)*$/ }] }; + } else { + filter = { name: /^((?!\$).)*$/ }; + } + + const transforms = listCollectionsTransforms(databaseName); + server.query( + `${databaseName}.${CONSTANTS.SYSTEM_NAMESPACE_COLLECTION}`, + { query: filter }, + { batchSize: this.batchSize || 1000 }, + {}, + (err, result) => { + if ( + result && + result.message && + result.message.documents && + Array.isArray(result.message.documents) + ) { + result.message.documents = result.message.documents.map(transforms.doc); + } + + callback(err, result); + } + ); + + return; + } + + const command = { + listCollections: 1, + filter: this.filter, + cursor: this.batchSize ? { batchSize: this.batchSize } : {}, + nameOnly: this.nameOnly + }; + + return super.executeCommand(server, command, callback); + } +} + +defineAspects(ListCollectionsOperation, [ + Aspect.READ_OPERATION, + Aspect.RETRYABLE, + Aspect.EXECUTE_WITH_SELECTION +]); + +module.exports = ListCollectionsOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/list_databases.js b/scripts/node_modules/mongodb/lib/operations/list_databases.js new file mode 100644 index 00000000..62b2606f --- /dev/null +++ b/scripts/node_modules/mongodb/lib/operations/list_databases.js @@ -0,0 +1,38 @@ +'use strict'; + +const CommandOperationV2 = require('./command_v2'); +const Aspect = require('./operation').Aspect; +const defineAspects = require('./operation').defineAspects; +const MongoDBNamespace = require('../utils').MongoDBNamespace; + +class ListDatabasesOperation extends CommandOperationV2 { + constructor(db, options) { + super(db, options); + this.ns = new MongoDBNamespace('admin', '$cmd'); + } + + execute(server, callback) { + const cmd = { listDatabases: 1 }; + if (this.options.nameOnly) { + cmd.nameOnly = Number(cmd.nameOnly); + } + + if (this.options.filter) { + cmd.filter = this.options.filter; + } + + if (typeof this.options.authorizedDatabases === 'boolean') { + cmd.authorizedDatabases = this.options.authorizedDatabases; + } + + super.executeCommand(server, cmd, callback); + } +} + +defineAspects(ListDatabasesOperation, [ + Aspect.READ_OPERATION, + Aspect.RETRYABLE, + Aspect.EXECUTE_WITH_SELECTION +]); + +module.exports = ListDatabasesOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/list_indexes.js b/scripts/node_modules/mongodb/lib/operations/list_indexes.js new file mode 100644 index 00000000..302a31b7 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/operations/list_indexes.js @@ -0,0 +1,42 @@ +'use strict'; + +const CommandOperationV2 = require('./command_v2'); +const Aspect = require('./operation').Aspect; +const defineAspects = require('./operation').defineAspects; +const maxWireVersion = require('../core/utils').maxWireVersion; + +const LIST_INDEXES_WIRE_VERSION = 3; + +class ListIndexesOperation extends CommandOperationV2 { + constructor(collection, options) { + super(collection, options, { fullResponse: true }); + + this.collectionNamespace = collection.s.namespace; + } + + execute(server, callback) { + const serverWireVersion = maxWireVersion(server); + if (serverWireVersion < LIST_INDEXES_WIRE_VERSION) { + const systemIndexesNS = this.collectionNamespace.withCollection('system.indexes').toString(); + const collectionNS = this.collectionNamespace.toString(); + + server.query(systemIndexesNS, { query: { ns: collectionNS } }, {}, this.options, callback); + return; + } + + const cursor = this.options.batchSize ? { batchSize: this.options.batchSize } : {}; + super.executeCommand( + server, + { listIndexes: this.collectionNamespace.collection, cursor }, + callback + ); + } +} + +defineAspects(ListIndexesOperation, [ + Aspect.READ_OPERATION, + Aspect.RETRYABLE, + Aspect.EXECUTE_WITH_SELECTION +]); + +module.exports = ListIndexesOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/map_reduce.js b/scripts/node_modules/mongodb/lib/operations/map_reduce.js new file mode 100644 index 00000000..613f3f73 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/operations/map_reduce.js @@ -0,0 +1,189 @@ +'use strict'; + +const applyWriteConcern = require('../utils').applyWriteConcern; +const Code = require('../core').BSON.Code; +const decorateWithCollation = require('../utils').decorateWithCollation; +const decorateWithReadConcern = require('../utils').decorateWithReadConcern; +const executeCommand = require('./db_ops').executeCommand; +const handleCallback = require('../utils').handleCallback; +const isObject = require('../utils').isObject; +const loadDb = require('../dynamic_loaders').loadDb; +const OperationBase = require('./operation').OperationBase; +const resolveReadPreference = require('../utils').resolveReadPreference; +const toError = require('../utils').toError; + +const exclusionList = [ + 'readPreference', + 'session', + 'bypassDocumentValidation', + 'w', + 'wtimeout', + 'j', + 'writeConcern' +]; + +/** + * Run Map Reduce across a collection. Be aware that the inline option for out will return an array of results not a collection. + * + * @class + * @property {Collection} a Collection instance. + * @property {(function|string)} map The mapping function. + * @property {(function|string)} reduce The reduce function. + * @property {object} [options] Optional settings. See Collection.prototype.mapReduce for a list of options. + */ +class MapReduceOperation extends OperationBase { + /** + * Constructs a MapReduce operation. + * + * @param {Collection} a Collection instance. + * @param {(function|string)} map The mapping function. + * @param {(function|string)} reduce The reduce function. + * @param {object} [options] Optional settings. See Collection.prototype.mapReduce for a list of options. + */ + constructor(collection, map, reduce, options) { + super(options); + + this.collection = collection; + this.map = map; + this.reduce = reduce; + } + + /** + * Execute the operation. + * + * @param {Collection~resultCallback} [callback] The command result callback + */ + execute(callback) { + const coll = this.collection; + const map = this.map; + const reduce = this.reduce; + let options = this.options; + + const mapCommandHash = { + mapreduce: coll.collectionName, + map: map, + reduce: reduce + }; + + // Add any other options passed in + for (let n in options) { + if ('scope' === n) { + mapCommandHash[n] = processScope(options[n]); + } else { + // Only include if not in exclusion list + if (exclusionList.indexOf(n) === -1) { + mapCommandHash[n] = options[n]; + } + } + } + + options = Object.assign({}, options); + + // Ensure we have the right read preference inheritance + options.readPreference = resolveReadPreference(coll, options); + + // If we have a read preference and inline is not set as output fail hard + if ( + options.readPreference !== false && + options.readPreference !== 'primary' && + options['out'] && + (options['out'].inline !== 1 && options['out'] !== 'inline') + ) { + // Force readPreference to primary + options.readPreference = 'primary'; + // Decorate command with writeConcern if supported + applyWriteConcern(mapCommandHash, { db: coll.s.db, collection: coll }, options); + } else { + decorateWithReadConcern(mapCommandHash, coll, options); + } + + // Is bypassDocumentValidation specified + if (options.bypassDocumentValidation === true) { + mapCommandHash.bypassDocumentValidation = options.bypassDocumentValidation; + } + + // Have we specified collation + try { + decorateWithCollation(mapCommandHash, coll, options); + } catch (err) { + return callback(err, null); + } + + // Execute command + executeCommand(coll.s.db, mapCommandHash, options, (err, result) => { + if (err) return handleCallback(callback, err); + // Check if we have an error + if (1 !== result.ok || result.err || result.errmsg) { + return handleCallback(callback, toError(result)); + } + + // Create statistics value + const stats = {}; + if (result.timeMillis) stats['processtime'] = result.timeMillis; + if (result.counts) stats['counts'] = result.counts; + if (result.timing) stats['timing'] = result.timing; + + // invoked with inline? + if (result.results) { + // If we wish for no verbosity + if (options['verbose'] == null || !options['verbose']) { + return handleCallback(callback, null, result.results); + } + + return handleCallback(callback, null, { results: result.results, stats: stats }); + } + + // The returned collection + let collection = null; + + // If we have an object it's a different db + if (result.result != null && typeof result.result === 'object') { + const doc = result.result; + // Return a collection from another db + let Db = loadDb(); + collection = new Db(doc.db, coll.s.db.s.topology, coll.s.db.s.options).collection( + doc.collection + ); + } else { + // Create a collection object that wraps the result collection + collection = coll.s.db.collection(result.result); + } + + // If we wish for no verbosity + if (options['verbose'] == null || !options['verbose']) { + return handleCallback(callback, err, collection); + } + + // Return stats as third set of values + handleCallback(callback, err, { collection: collection, stats: stats }); + }); + } +} + +/** + * Functions that are passed as scope args must + * be converted to Code instances. + * @ignore + */ +function processScope(scope) { + if (!isObject(scope) || scope._bsontype === 'ObjectID') { + return scope; + } + + const keys = Object.keys(scope); + let key; + const new_scope = {}; + + for (let i = keys.length - 1; i >= 0; i--) { + key = keys[i]; + if ('function' === typeof scope[key]) { + new_scope[key] = new Code(String(scope[key])); + } else { + new_scope[key] = processScope(scope[key]); + } + } + + return new_scope; +} + +module.exports = MapReduceOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/next.js b/scripts/node_modules/mongodb/lib/operations/next.js new file mode 100644 index 00000000..72bc4eb9 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/operations/next.js @@ -0,0 +1,32 @@ +'use strict'; + +const Aspect = require('./operation').Aspect; +const defineAspects = require('./operation').defineAspects; +const OperationBase = require('./operation').OperationBase; +const nextObject = require('./common_functions').nextObject; + +class NextOperation extends OperationBase { + constructor(cursor) { + super(); + + this.cursor = cursor; + } + + execute(callback) { + const cursor = this.cursor; + + // Return the currentDoc if someone called hasNext first + if (cursor.s.currentDoc) { + const doc = cursor.s.currentDoc; + cursor.s.currentDoc = null; + return callback(null, doc); + } + + // Return the next object + nextObject(cursor, callback); + } +} + +defineAspects(NextOperation, Aspect.SKIP_SESSION); + +module.exports = NextOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/operation.js b/scripts/node_modules/mongodb/lib/operations/operation.js new file mode 100644 index 00000000..471627ad --- /dev/null +++ b/scripts/node_modules/mongodb/lib/operations/operation.js @@ -0,0 +1,67 @@ +'use strict'; + +const Aspect = { + READ_OPERATION: Symbol('READ_OPERATION'), + SKIP_SESSION: Symbol('SKIP_SESSION'), + WRITE_OPERATION: Symbol('WRITE_OPERATION'), + RETRYABLE: Symbol('RETRYABLE'), + EXECUTE_WITH_SELECTION: Symbol('EXECUTE_WITH_SELECTION') +}; + +/** + * This class acts as a parent class for any operation and is responsible for setting this.options, + * as well as setting and getting a session. + * Additionally, this class implements `hasAspect`, which determines whether an operation has + * a specific aspect, including `SKIP_SESSION` and other aspects to encode retryability + * and other functionality. + */ +class OperationBase { + constructor(options) { + this.options = Object.assign({}, options); + } + + hasAspect(aspect) { + if (this.constructor.aspects == null) { + return false; + } + return this.constructor.aspects.has(aspect); + } + + set session(session) { + Object.assign(this.options, { session }); + } + + get session() { + return this.options.session; + } + + clearSession() { + delete this.options.session; + } + + get canRetryRead() { + return true; + } + + execute() { + throw new TypeError('`execute` must be implemented for OperationBase subclasses'); + } +} + +function defineAspects(operation, aspects) { + if (!Array.isArray(aspects) && !(aspects instanceof Set)) { + aspects = [aspects]; + } + aspects = new Set(aspects); + Object.defineProperty(operation, 'aspects', { + value: aspects, + writable: false + }); + return aspects; +} + +module.exports = { + Aspect, + defineAspects, + OperationBase +}; diff --git a/scripts/node_modules/mongodb/lib/operations/options_operation.js b/scripts/node_modules/mongodb/lib/operations/options_operation.js new file mode 100644 index 00000000..9a739a51 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/operations/options_operation.js @@ -0,0 +1,32 @@ +'use strict'; + +const OperationBase = require('./operation').OperationBase; +const handleCallback = require('../utils').handleCallback; +const MongoError = require('../core').MongoError; + +class OptionsOperation extends OperationBase { + constructor(collection, options) { + super(options); + + this.collection = collection; + } + + execute(callback) { + const coll = this.collection; + const opts = this.options; + + coll.s.db.listCollections({ name: coll.collectionName }, opts).toArray((err, collections) => { + if (err) return handleCallback(callback, err); + if (collections.length === 0) { + return handleCallback( + callback, + MongoError.create({ message: `collection ${coll.namespace} not found`, driver: true }) + ); + } + + handleCallback(callback, err, collections[0].options || null); + }); + } +} + +module.exports = OptionsOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/profiling_level.js b/scripts/node_modules/mongodb/lib/operations/profiling_level.js new file mode 100644 index 00000000..3f7639b4 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/operations/profiling_level.js @@ -0,0 +1,31 @@ +'use strict'; + +const CommandOperation = require('./command'); + +class ProfilingLevelOperation extends CommandOperation { + constructor(db, command, options) { + super(db, options); + } + + _buildCommand() { + const command = { profile: -1 }; + + return command; + } + + execute(callback) { + super.execute((err, doc) => { + if (err == null && doc.ok === 1) { + const was = doc.was; + if (was === 0) return callback(null, 'off'); + if (was === 1) return callback(null, 'slow_only'); + if (was === 2) return callback(null, 'all'); + return callback(new Error('Error: illegal profiling level value ' + was), null); + } else { + err != null ? callback(err, null) : callback(new Error('Error with profile command'), null); + } + }); + } +} + +module.exports = ProfilingLevelOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/re_index.js b/scripts/node_modules/mongodb/lib/operations/re_index.js new file mode 100644 index 00000000..89437fe3 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/operations/re_index.js @@ -0,0 +1,28 @@ +'use strict'; + +const CommandOperation = require('./command'); +const handleCallback = require('../utils').handleCallback; + +class ReIndexOperation extends CommandOperation { + constructor(collection, options) { + super(collection.s.db, options, collection); + } + + _buildCommand() { + const collection = this.collection; + + const cmd = { reIndex: collection.collectionName }; + + return cmd; + } + + execute(callback) { + super.execute((err, result) => { + if (callback == null) return; + if (err) return handleCallback(callback, err, null); + handleCallback(callback, null, result.ok ? true : false); + }); + } +} + +module.exports = ReIndexOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/remove_user.js b/scripts/node_modules/mongodb/lib/operations/remove_user.js new file mode 100644 index 00000000..9a59744d --- /dev/null +++ b/scripts/node_modules/mongodb/lib/operations/remove_user.js @@ -0,0 +1,52 @@ +'use strict'; + +const Aspect = require('./operation').Aspect; +const CommandOperation = require('./command'); +const defineAspects = require('./operation').defineAspects; +const handleCallback = require('../utils').handleCallback; +const WriteConcern = require('../write_concern'); + +class RemoveUserOperation extends CommandOperation { + constructor(db, username, options) { + const commandOptions = {}; + + const writeConcern = WriteConcern.fromOptions(options); + if (writeConcern != null) { + commandOptions.writeConcern = writeConcern; + } + + if (options.dbName) { + commandOptions.dbName = options.dbName; + } + + // Add maxTimeMS to options if set + if (typeof options.maxTimeMS === 'number') { + commandOptions.maxTimeMS = options.maxTimeMS; + } + + super(db, commandOptions); + + this.username = username; + } + + _buildCommand() { + const username = this.username; + + // Build the command to execute + const command = { dropUser: username }; + + return command; + } + + execute(callback) { + // Attempt to execute command + super.execute((err, result) => { + if (err) return handleCallback(callback, err, null); + handleCallback(callback, err, result.ok ? true : false); + }); + } +} + +defineAspects(RemoveUserOperation, [Aspect.WRITE_OPERATION, Aspect.SKIP_SESSIONS]); + +module.exports = RemoveUserOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/rename.js b/scripts/node_modules/mongodb/lib/operations/rename.js new file mode 100644 index 00000000..8098fe6b --- /dev/null +++ b/scripts/node_modules/mongodb/lib/operations/rename.js @@ -0,0 +1,61 @@ +'use strict'; + +const OperationBase = require('./operation').OperationBase; +const applyWriteConcern = require('../utils').applyWriteConcern; +const checkCollectionName = require('../utils').checkCollectionName; +const executeDbAdminCommand = require('./db_ops').executeDbAdminCommand; +const handleCallback = require('../utils').handleCallback; +const loadCollection = require('../dynamic_loaders').loadCollection; +const toError = require('../utils').toError; + +class RenameOperation extends OperationBase { + constructor(collection, newName, options) { + super(options); + + this.collection = collection; + this.newName = newName; + } + + execute(callback) { + const coll = this.collection; + const newName = this.newName; + const options = this.options; + + let Collection = loadCollection(); + // Check the collection name + checkCollectionName(newName); + // Build the command + const renameCollection = coll.namespace; + const toCollection = coll.s.namespace.withCollection(newName).toString(); + const dropTarget = typeof options.dropTarget === 'boolean' ? options.dropTarget : false; + const cmd = { renameCollection: renameCollection, to: toCollection, dropTarget: dropTarget }; + + // Decorate command with writeConcern if supported + applyWriteConcern(cmd, { db: coll.s.db, collection: coll }, options); + + // Execute against admin + executeDbAdminCommand(coll.s.db.admin().s.db, cmd, options, (err, doc) => { + if (err) return handleCallback(callback, err, null); + // We have an error + if (doc.errmsg) return handleCallback(callback, toError(doc), null); + try { + return handleCallback( + callback, + null, + new Collection( + coll.s.db, + coll.s.topology, + coll.s.namespace.db, + newName, + coll.s.pkFactory, + coll.s.options + ) + ); + } catch (err) { + return handleCallback(callback, toError(err), null); + } + }); + } +} + +module.exports = RenameOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/replace_one.js b/scripts/node_modules/mongodb/lib/operations/replace_one.js new file mode 100644 index 00000000..a5aa7608 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/operations/replace_one.js @@ -0,0 +1,47 @@ +'use strict'; + +const OperationBase = require('./operation').OperationBase; +const updateDocuments = require('./common_functions').updateDocuments; + +class ReplaceOneOperation extends OperationBase { + constructor(collection, filter, doc, options) { + super(options); + + this.collection = collection; + this.filter = filter; + this.doc = doc; + } + + execute(callback) { + const coll = this.collection; + const filter = this.filter; + const doc = this.doc; + const options = this.options; + + // Set single document update + options.multi = false; + + // Execute update + updateDocuments(coll, filter, doc, options, (err, r) => replaceCallback(err, r, doc, callback)); + } +} + +function replaceCallback(err, r, doc, callback) { + if (callback == null) return; + if (err && callback) return callback(err); + if (r == null) return callback(null, { result: { ok: 1 } }); + + r.modifiedCount = r.result.nModified != null ? r.result.nModified : r.result.n; + r.upsertedId = + Array.isArray(r.result.upserted) && r.result.upserted.length > 0 + ? r.result.upserted[0] // FIXME(major): should be `r.result.upserted[0]._id` + : null; + r.upsertedCount = + Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0; + r.matchedCount = + Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? 0 : r.result.n; + r.ops = [doc]; // TODO: Should we still have this? + if (callback) callback(null, r); +} + +module.exports = ReplaceOneOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/set_profiling_level.js b/scripts/node_modules/mongodb/lib/operations/set_profiling_level.js new file mode 100644 index 00000000..b31cc130 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/operations/set_profiling_level.js @@ -0,0 +1,48 @@ +'use strict'; + +const CommandOperation = require('./command'); +const levelValues = new Set(['off', 'slow_only', 'all']); + +class SetProfilingLevelOperation extends CommandOperation { + constructor(db, level, options) { + let profile = 0; + + if (level === 'off') { + profile = 0; + } else if (level === 'slow_only') { + profile = 1; + } else if (level === 'all') { + profile = 2; + } + + super(db, options); + this.level = level; + this.profile = profile; + } + + _buildCommand() { + const profile = this.profile; + + // Set up the profile number + const command = { profile }; + + return command; + } + + execute(callback) { + const level = this.level; + + if (!levelValues.has(level)) { + return callback(new Error('Error: illegal profiling level value ' + level)); + } + + super.execute((err, doc) => { + if (err == null && doc.ok === 1) return callback(null, level); + return err != null + ? callback(err, null) + : callback(new Error('Error with profile command'), null); + }); + } +} + +module.exports = SetProfilingLevelOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/stats.js b/scripts/node_modules/mongodb/lib/operations/stats.js new file mode 100644 index 00000000..ff79126e --- /dev/null +++ b/scripts/node_modules/mongodb/lib/operations/stats.js @@ -0,0 +1,45 @@ +'use strict'; + +const Aspect = require('./operation').Aspect; +const CommandOperation = require('./command'); +const defineAspects = require('./operation').defineAspects; + +/** + * Get all the collection statistics. + * + * @class + * @property {Collection} a Collection instance. + * @property {object} [options] Optional settings. See Collection.prototype.stats for a list of options. + */ +class StatsOperation extends CommandOperation { + /** + * Construct a Stats operation. + * + * @param {Collection} a Collection instance. + * @param {object} [options] Optional settings. See Collection.prototype.stats for a list of options. + */ + constructor(collection, options) { + super(collection.s.db, options, collection); + } + + _buildCommand() { + const collection = this.collection; + const options = this.options; + + // Build command object + const command = { + collStats: collection.collectionName + }; + + // Check if we have the scale value + if (options['scale'] != null) { + command['scale'] = options['scale']; + } + + return command; + } +} + +defineAspects(StatsOperation, Aspect.READ_OPERATION); + +module.exports = StatsOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/to_array.js b/scripts/node_modules/mongodb/lib/operations/to_array.js new file mode 100644 index 00000000..db6d1a07 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/operations/to_array.js @@ -0,0 +1,66 @@ +'use strict'; + +const Aspect = require('./operation').Aspect; +const defineAspects = require('./operation').defineAspects; +const handleCallback = require('../utils').handleCallback; +const CursorState = require('../core/cursor').CursorState; +const OperationBase = require('./operation').OperationBase; +const push = Array.prototype.push; + +class ToArrayOperation extends OperationBase { + constructor(cursor) { + super(); + + this.cursor = cursor; + } + + execute(callback) { + const cursor = this.cursor; + const items = []; + + // Reset cursor + cursor.rewind(); + cursor.s.state = CursorState.INIT; + + // Fetch all the documents + const fetchDocs = () => { + cursor._next((err, doc) => { + if (err) { + return cursor._endSession + ? cursor._endSession(() => handleCallback(callback, err)) + : handleCallback(callback, err); + } + + if (doc == null) { + return cursor.close({ skipKillCursors: true }, () => + handleCallback(callback, null, items) + ); + } + + // Add doc to items + items.push(doc); + + // Get all buffered objects + if (cursor.bufferedCount() > 0) { + let docs = cursor.readBufferedDocuments(cursor.bufferedCount()); + + // Transform the doc if transform method added + if (cursor.s.transforms && typeof cursor.s.transforms.doc === 'function') { + docs = docs.map(cursor.s.transforms.doc); + } + + push.apply(items, docs); + } + + // Attempt a fetch + fetchDocs(); + }); + }; + + fetchDocs(); + } +} + +defineAspects(ToArrayOperation, Aspect.SKIP_SESSION); + +module.exports = ToArrayOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/update_many.js b/scripts/node_modules/mongodb/lib/operations/update_many.js new file mode 100644 index 00000000..9a18d253 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/operations/update_many.js @@ -0,0 +1,29 @@ +'use strict'; + +const OperationBase = require('./operation').OperationBase; +const updateCallback = require('./common_functions').updateCallback; +const updateDocuments = require('./common_functions').updateDocuments; + +class UpdateManyOperation extends OperationBase { + constructor(collection, filter, update, options) { + super(options); + + this.collection = collection; + this.filter = filter; + this.update = update; + } + + execute(callback) { + const coll = this.collection; + const filter = this.filter; + const update = this.update; + const options = this.options; + + // Set single document update + options.multi = true; + // Execute update + updateDocuments(coll, filter, update, options, (err, r) => updateCallback(err, r, callback)); + } +} + +module.exports = UpdateManyOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/update_one.js b/scripts/node_modules/mongodb/lib/operations/update_one.js new file mode 100644 index 00000000..b1c1bc16 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/operations/update_one.js @@ -0,0 +1,44 @@ +'use strict'; + +const OperationBase = require('./operation').OperationBase; +const updateDocuments = require('./common_functions').updateDocuments; + +class UpdateOneOperation extends OperationBase { + constructor(collection, filter, update, options) { + super(options); + + this.collection = collection; + this.filter = filter; + this.update = update; + } + + execute(callback) { + const coll = this.collection; + const filter = this.filter; + const update = this.update; + const options = this.options; + + // Set single document update + options.multi = false; + // Execute update + updateDocuments(coll, filter, update, options, (err, r) => updateCallback(err, r, callback)); + } +} + +function updateCallback(err, r, callback) { + if (callback == null) return; + if (err) return callback(err); + if (r == null) return callback(null, { result: { ok: 1 } }); + r.modifiedCount = r.result.nModified != null ? r.result.nModified : r.result.n; + r.upsertedId = + Array.isArray(r.result.upserted) && r.result.upserted.length > 0 + ? r.result.upserted[0] // FIXME(major): should be `r.result.upserted[0]._id` + : null; + r.upsertedCount = + Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0; + r.matchedCount = + Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? 0 : r.result.n; + callback(null, r); +} + +module.exports = UpdateOneOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/validate_collection.js b/scripts/node_modules/mongodb/lib/operations/validate_collection.js new file mode 100644 index 00000000..133c6c4b --- /dev/null +++ b/scripts/node_modules/mongodb/lib/operations/validate_collection.js @@ -0,0 +1,40 @@ +'use strict'; + +const CommandOperation = require('./command'); + +class ValidateCollectionOperation extends CommandOperation { + constructor(admin, collectionName, options) { + // Decorate command with extra options + let command = { validate: collectionName }; + const keys = Object.keys(options); + for (let i = 0; i < keys.length; i++) { + if (options.hasOwnProperty(keys[i]) && keys[i] !== 'session') { + command[keys[i]] = options[keys[i]]; + } + } + + super(admin.s.db, options, null, command); + + this.collectionName; + } + + execute(callback) { + const collectionName = this.collectionName; + + super.execute((err, doc) => { + if (err != null) return callback(err, null); + + if (doc.ok === 0) return callback(new Error('Error with validate command'), null); + if (doc.result != null && doc.result.constructor !== String) + return callback(new Error('Error with validation data'), null); + if (doc.result != null && doc.result.match(/exception|corrupt/) != null) + return callback(new Error('Error: invalid collection ' + collectionName), null); + if (doc.valid != null && !doc.valid) + return callback(new Error('Error: invalid collection ' + collectionName), null); + + return callback(null, doc); + }); + } +} + +module.exports = ValidateCollectionOperation; diff --git a/scripts/node_modules/mongodb/lib/read_concern.js b/scripts/node_modules/mongodb/lib/read_concern.js new file mode 100644 index 00000000..b48b8e0e --- /dev/null +++ b/scripts/node_modules/mongodb/lib/read_concern.js @@ -0,0 +1,61 @@ +'use strict'; + +/** + * The **ReadConcern** class is a class that represents a MongoDB ReadConcern. + * @class + * @property {string} level The read concern level + * @see https://docs.mongodb.com/manual/reference/read-concern/index.html + */ +class ReadConcern { + /** + * Constructs a ReadConcern from the read concern properties. + * @param {string} [level] The read concern level ({'local'|'available'|'majority'|'linearizable'|'snapshot'}) + */ + constructor(level) { + if (level != null) { + this.level = level; + } + } + + /** + * Construct a ReadConcern given an options object. + * + * @param {object} options The options object from which to extract the write concern. + * @return {ReadConcern} + */ + static fromOptions(options) { + if (options == null) { + return; + } + + if (options.readConcern) { + if (options.readConcern instanceof ReadConcern) { + return options.readConcern; + } + + return new ReadConcern(options.readConcern.level); + } + + if (options.level) { + return new ReadConcern(options.level); + } + } + + static get MAJORITY() { + return 'majority'; + } + + static get AVAILABLE() { + return 'available'; + } + + static get LINEARIZABLE() { + return 'linearizable'; + } + + static get SNAPSHOT() { + return 'snapshot'; + } +} + +module.exports = ReadConcern; diff --git a/scripts/node_modules/mongodb/lib/topologies/mongos.js b/scripts/node_modules/mongodb/lib/topologies/mongos.js new file mode 100644 index 00000000..ec14f485 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/topologies/mongos.js @@ -0,0 +1,452 @@ +'use strict'; + +const TopologyBase = require('./topology_base').TopologyBase; +const MongoError = require('../core').MongoError; +const CMongos = require('../core').Mongos; +const Cursor = require('../cursor'); +const Server = require('./server'); +const Store = require('./topology_base').Store; +const MAX_JS_INT = require('../utils').MAX_JS_INT; +const translateOptions = require('../utils').translateOptions; +const filterOptions = require('../utils').filterOptions; +const mergeOptions = require('../utils').mergeOptions; + +/** + * @fileOverview The **Mongos** class is a class that represents a Mongos Proxy topology and is + * used to construct connections. + * + * **Mongos Should not be used, use MongoClient.connect** + */ + +// Allowed parameters +var legalOptionNames = [ + 'ha', + 'haInterval', + 'acceptableLatencyMS', + 'poolSize', + 'ssl', + 'checkServerIdentity', + 'sslValidate', + 'sslCA', + 'sslCRL', + 'sslCert', + 'ciphers', + 'ecdhCurve', + 'sslKey', + 'sslPass', + 'socketOptions', + 'bufferMaxEntries', + 'store', + 'auto_reconnect', + 'autoReconnect', + 'emitError', + 'keepAlive', + 'keepAliveInitialDelay', + 'noDelay', + 'connectTimeoutMS', + 'socketTimeoutMS', + 'loggerLevel', + 'logger', + 'reconnectTries', + 'appname', + 'domainsEnabled', + 'servername', + 'promoteLongs', + 'promoteValues', + 'promoteBuffers', + 'promiseLibrary', + 'monitorCommands' +]; + +/** + * Creates a new Mongos instance + * @class + * @deprecated + * @param {Server[]} servers A seedlist of servers participating in the replicaset. + * @param {object} [options] Optional settings. + * @param {booelan} [options.ha=true] Turn on high availability monitoring. + * @param {number} [options.haInterval=5000] Time between each replicaset status check. + * @param {number} [options.poolSize=5] Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons. + * @param {number} [options.acceptableLatencyMS=15] Cutoff latency point in MS for MongoS proxy selection + * @param {boolean} [options.ssl=false] Use ssl connection (needs to have a mongod server with ssl support) + * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. + * @param {boolean} [options.sslValidate=false] Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {array} [options.sslCA] Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {array} [options.sslCRL] Array of revocation certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {string} [options.ciphers] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. + * @param {string} [options.ecdhCurve] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. + * @param {(Buffer|string)} [options.sslCert] String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {(Buffer|string)} [options.sslKey] String or buffer containing the certificate private key we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {(Buffer|string)} [options.sslPass] String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {string} [options.servername] String containing the server name requested via TLS SNI. + * @param {object} [options.socketOptions] Socket options + * @param {boolean} [options.socketOptions.noDelay=true] TCP Socket NoDelay option. + * @param {boolean} [options.socketOptions.keepAlive=true] TCP Connection keep alive enabled + * @param {number} [options.socketOptions.keepAliveInitialDelay=30000] The number of milliseconds to wait before initiating keepAlive on the TCP socket + * @param {number} [options.socketOptions.connectTimeoutMS=0] TCP Connection timeout setting + * @param {number} [options.socketOptions.socketTimeoutMS=0] TCP Socket timeout setting + * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. + * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology + * @fires Mongos#connect + * @fires Mongos#ha + * @fires Mongos#joined + * @fires Mongos#left + * @fires Mongos#fullsetup + * @fires Mongos#open + * @fires Mongos#close + * @fires Mongos#error + * @fires Mongos#timeout + * @fires Mongos#parseError + * @fires Mongos#commandStarted + * @fires Mongos#commandSucceeded + * @fires Mongos#commandFailed + * @property {string} parserType the parser type used (c++ or js). + * @return {Mongos} a Mongos instance. + */ +class Mongos extends TopologyBase { + constructor(servers, options) { + super(); + + options = options || {}; + var self = this; + + // Filter the options + options = filterOptions(options, legalOptionNames); + + // Ensure all the instances are Server + for (var i = 0; i < servers.length; i++) { + if (!(servers[i] instanceof Server)) { + throw MongoError.create({ + message: 'all seed list instances must be of the Server type', + driver: true + }); + } + } + + // Stored options + var storeOptions = { + force: false, + bufferMaxEntries: + typeof options.bufferMaxEntries === 'number' ? options.bufferMaxEntries : MAX_JS_INT + }; + + // Shared global store + var store = options.store || new Store(self, storeOptions); + + // Build seed list + var seedlist = servers.map(function(x) { + return { host: x.host, port: x.port }; + }); + + // Get the reconnect option + var reconnect = typeof options.auto_reconnect === 'boolean' ? options.auto_reconnect : true; + reconnect = typeof options.autoReconnect === 'boolean' ? options.autoReconnect : reconnect; + + // Clone options + var clonedOptions = mergeOptions( + {}, + { + disconnectHandler: store, + cursorFactory: Cursor, + reconnect: reconnect, + emitError: typeof options.emitError === 'boolean' ? options.emitError : true, + size: typeof options.poolSize === 'number' ? options.poolSize : 5, + monitorCommands: + typeof options.monitorCommands === 'boolean' ? options.monitorCommands : false + } + ); + + // Translate any SSL options and other connectivity options + clonedOptions = translateOptions(clonedOptions, options); + + // Socket options + var socketOptions = + options.socketOptions && Object.keys(options.socketOptions).length > 0 + ? options.socketOptions + : options; + + // Translate all the options to the core types + clonedOptions = translateOptions(clonedOptions, socketOptions); + + // Build default client information + clonedOptions.clientInfo = this.clientInfo; + // Do we have an application specific string + if (options.appname) { + clonedOptions.clientInfo.application = { name: options.appname }; + } + + // Internal state + this.s = { + // Create the Mongos + coreTopology: new CMongos(seedlist, clonedOptions), + // Server capabilities + sCapabilities: null, + // Debug turned on + debug: clonedOptions.debug, + // Store option defaults + storeOptions: storeOptions, + // Cloned options + clonedOptions: clonedOptions, + // Actual store of callbacks + store: store, + // Options + options: options, + // Server Session Pool + sessionPool: null, + // Active client sessions + sessions: new Set(), + // Promise library + promiseLibrary: options.promiseLibrary || Promise + }; + } + + // Connect + connect(_options, callback) { + var self = this; + if ('function' === typeof _options) (callback = _options), (_options = {}); + if (_options == null) _options = {}; + if (!('function' === typeof callback)) callback = null; + _options = Object.assign({}, this.s.clonedOptions, _options); + self.s.options = _options; + + // Update bufferMaxEntries + self.s.storeOptions.bufferMaxEntries = + typeof _options.bufferMaxEntries === 'number' ? _options.bufferMaxEntries : -1; + + // Error handler + var connectErrorHandler = function() { + return function(err) { + // Remove all event handlers + var events = ['timeout', 'error', 'close']; + events.forEach(function(e) { + self.removeListener(e, connectErrorHandler); + }); + + self.s.coreTopology.removeListener('connect', connectErrorHandler); + // Force close the topology + self.close(true); + + // Try to callback + try { + callback(err); + } catch (err) { + process.nextTick(function() { + throw err; + }); + } + }; + }; + + // Actual handler + var errorHandler = function(event) { + return function(err) { + if (event !== 'error') { + self.emit(event, err); + } + }; + }; + + // Error handler + var reconnectHandler = function() { + self.emit('reconnect'); + self.s.store.execute(); + }; + + // relay the event + var relay = function(event) { + return function(t, server) { + self.emit(event, t, server); + }; + }; + + // Connect handler + var connectHandler = function() { + // Clear out all the current handlers left over + var events = ['timeout', 'error', 'close', 'fullsetup']; + events.forEach(function(e) { + self.s.coreTopology.removeAllListeners(e); + }); + + // Set up listeners + self.s.coreTopology.on('timeout', errorHandler('timeout')); + self.s.coreTopology.on('error', errorHandler('error')); + self.s.coreTopology.on('close', errorHandler('close')); + + // Set up serverConfig listeners + self.s.coreTopology.on('fullsetup', function() { + self.emit('fullsetup', self); + }); + + // Emit open event + self.emit('open', null, self); + + // Return correctly + try { + callback(null, self); + } catch (err) { + process.nextTick(function() { + throw err; + }); + } + }; + + // Clear out all the current handlers left over + var events = [ + 'timeout', + 'error', + 'close', + 'serverOpening', + 'serverDescriptionChanged', + 'serverHeartbeatStarted', + 'serverHeartbeatSucceeded', + 'serverHeartbeatFailed', + 'serverClosed', + 'topologyOpening', + 'topologyClosed', + 'topologyDescriptionChanged', + 'commandStarted', + 'commandSucceeded', + 'commandFailed' + ]; + events.forEach(function(e) { + self.s.coreTopology.removeAllListeners(e); + }); + + // Set up SDAM listeners + self.s.coreTopology.on('serverDescriptionChanged', relay('serverDescriptionChanged')); + self.s.coreTopology.on('serverHeartbeatStarted', relay('serverHeartbeatStarted')); + self.s.coreTopology.on('serverHeartbeatSucceeded', relay('serverHeartbeatSucceeded')); + self.s.coreTopology.on('serverHeartbeatFailed', relay('serverHeartbeatFailed')); + self.s.coreTopology.on('serverOpening', relay('serverOpening')); + self.s.coreTopology.on('serverClosed', relay('serverClosed')); + self.s.coreTopology.on('topologyOpening', relay('topologyOpening')); + self.s.coreTopology.on('topologyClosed', relay('topologyClosed')); + self.s.coreTopology.on('topologyDescriptionChanged', relay('topologyDescriptionChanged')); + self.s.coreTopology.on('commandStarted', relay('commandStarted')); + self.s.coreTopology.on('commandSucceeded', relay('commandSucceeded')); + self.s.coreTopology.on('commandFailed', relay('commandFailed')); + + // Set up listeners + self.s.coreTopology.once('timeout', connectErrorHandler('timeout')); + self.s.coreTopology.once('error', connectErrorHandler('error')); + self.s.coreTopology.once('close', connectErrorHandler('close')); + self.s.coreTopology.once('connect', connectHandler); + // Join and leave events + self.s.coreTopology.on('joined', relay('joined')); + self.s.coreTopology.on('left', relay('left')); + + // Reconnect server + self.s.coreTopology.on('reconnect', reconnectHandler); + + // Start connection + self.s.coreTopology.connect(_options); + } +} + +Object.defineProperty(Mongos.prototype, 'haInterval', { + enumerable: true, + get: function() { + return this.s.coreTopology.s.haInterval; + } +}); + +/** + * A mongos connect event, used to verify that the connection is up and running + * + * @event Mongos#connect + * @type {Mongos} + */ + +/** + * The mongos high availability event + * + * @event Mongos#ha + * @type {function} + * @param {string} type The stage in the high availability event (start|end) + * @param {boolean} data.norepeat This is a repeating high availability process or a single execution only + * @param {number} data.id The id for this high availability request + * @param {object} data.state An object containing the information about the current replicaset + */ + +/** + * A server member left the mongos set + * + * @event Mongos#left + * @type {function} + * @param {string} type The type of member that left (primary|secondary|arbiter) + * @param {Server} server The server object that left + */ + +/** + * A server member joined the mongos set + * + * @event Mongos#joined + * @type {function} + * @param {string} type The type of member that joined (primary|secondary|arbiter) + * @param {Server} server The server object that joined + */ + +/** + * Mongos fullsetup event, emitted when all proxies in the topology have been connected to. + * + * @event Mongos#fullsetup + * @type {Mongos} + */ + +/** + * Mongos open event, emitted when mongos can start processing commands. + * + * @event Mongos#open + * @type {Mongos} + */ + +/** + * Mongos close event + * + * @event Mongos#close + * @type {object} + */ + +/** + * Mongos error event, emitted if there is an error listener. + * + * @event Mongos#error + * @type {MongoError} + */ + +/** + * Mongos timeout event + * + * @event Mongos#timeout + * @type {object} + */ + +/** + * Mongos parseError event + * + * @event Mongos#parseError + * @type {object} + */ + +/** + * An event emitted indicating a command was started, if command monitoring is enabled + * + * @event Mongos#commandStarted + * @type {object} + */ + +/** + * An event emitted indicating a command succeeded, if command monitoring is enabled + * + * @event Mongos#commandSucceeded + * @type {object} + */ + +/** + * An event emitted indicating a command failed, if command monitoring is enabled + * + * @event Mongos#commandFailed + * @type {object} + */ + +module.exports = Mongos; diff --git a/scripts/node_modules/mongodb/lib/topologies/native_topology.js b/scripts/node_modules/mongodb/lib/topologies/native_topology.js new file mode 100644 index 00000000..51574878 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/topologies/native_topology.js @@ -0,0 +1,72 @@ +'use strict'; + +const Topology = require('../core').Topology; +const ServerCapabilities = require('./topology_base').ServerCapabilities; +const Cursor = require('../cursor'); +const translateOptions = require('../utils').translateOptions; + +class NativeTopology extends Topology { + constructor(servers, options) { + options = options || {}; + + let clonedOptions = Object.assign( + {}, + { + cursorFactory: Cursor, + reconnect: false, + emitError: typeof options.emitError === 'boolean' ? options.emitError : true, + size: typeof options.poolSize === 'number' ? options.poolSize : 5, + monitorCommands: + typeof options.monitorCommands === 'boolean' ? options.monitorCommands : false + } + ); + + // Translate any SSL options and other connectivity options + clonedOptions = translateOptions(clonedOptions, options); + + // Socket options + var socketOptions = + options.socketOptions && Object.keys(options.socketOptions).length > 0 + ? options.socketOptions + : options; + + // Translate all the options to the core types + clonedOptions = translateOptions(clonedOptions, socketOptions); + + super(servers, clonedOptions); + + // Do we have an application specific string + if (options.appname) { + this.s.clientInfo.application = { name: options.appname }; + } + } + + capabilities() { + if (this.s.sCapabilities) return this.s.sCapabilities; + if (this.lastIsMaster() == null) return null; + this.s.sCapabilities = new ServerCapabilities(this.lastIsMaster()); + return this.s.sCapabilities; + } + + // Command + command(ns, cmd, options, callback) { + super.command(ns.toString(), cmd, options, callback); + } + + // Insert + insert(ns, ops, options, callback) { + super.insert(ns.toString(), ops, options, callback); + } + + // Update + update(ns, ops, options, callback) { + super.update(ns.toString(), ops, options, callback); + } + + // Remove + remove(ns, ops, options, callback) { + super.remove(ns.toString(), ops, options, callback); + } +} + +module.exports = NativeTopology; diff --git a/scripts/node_modules/mongodb/lib/topologies/replset.js b/scripts/node_modules/mongodb/lib/topologies/replset.js new file mode 100644 index 00000000..44e83d11 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/topologies/replset.js @@ -0,0 +1,496 @@ +'use strict'; + +const Server = require('./server'); +const Cursor = require('../cursor'); +const MongoError = require('../core').MongoError; +const TopologyBase = require('./topology_base').TopologyBase; +const Store = require('./topology_base').Store; +const CReplSet = require('../core').ReplSet; +const MAX_JS_INT = require('../utils').MAX_JS_INT; +const translateOptions = require('../utils').translateOptions; +const filterOptions = require('../utils').filterOptions; +const mergeOptions = require('../utils').mergeOptions; + +/** + * @fileOverview The **ReplSet** class is a class that represents a Replicaset topology and is + * used to construct connections. + * + * **ReplSet Should not be used, use MongoClient.connect** + */ + +// Allowed parameters +var legalOptionNames = [ + 'ha', + 'haInterval', + 'replicaSet', + 'rs_name', + 'secondaryAcceptableLatencyMS', + 'connectWithNoPrimary', + 'poolSize', + 'ssl', + 'checkServerIdentity', + 'sslValidate', + 'sslCA', + 'sslCert', + 'ciphers', + 'ecdhCurve', + 'sslCRL', + 'sslKey', + 'sslPass', + 'socketOptions', + 'bufferMaxEntries', + 'store', + 'auto_reconnect', + 'autoReconnect', + 'emitError', + 'keepAlive', + 'keepAliveInitialDelay', + 'noDelay', + 'connectTimeoutMS', + 'socketTimeoutMS', + 'strategy', + 'debug', + 'family', + 'loggerLevel', + 'logger', + 'reconnectTries', + 'appname', + 'domainsEnabled', + 'servername', + 'promoteLongs', + 'promoteValues', + 'promoteBuffers', + 'maxStalenessSeconds', + 'promiseLibrary', + 'minSize', + 'monitorCommands' +]; + +/** + * Creates a new ReplSet instance + * @class + * @deprecated + * @param {Server[]} servers A seedlist of servers participating in the replicaset. + * @param {object} [options] Optional settings. + * @param {boolean} [options.ha=true] Turn on high availability monitoring. + * @param {number} [options.haInterval=10000] Time between each replicaset status check. + * @param {string} [options.replicaSet] The name of the replicaset to connect to. + * @param {number} [options.secondaryAcceptableLatencyMS=15] Sets the range of servers to pick when using NEAREST (lowest ping ms + the latency fence, ex: range of 1 to (1 + 15) ms) + * @param {boolean} [options.connectWithNoPrimary=false] Sets if the driver should connect even if no primary is available + * @param {number} [options.poolSize=5] Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons. + * @param {boolean} [options.ssl=false] Use ssl connection (needs to have a mongod server with ssl support) + * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. + * @param {boolean} [options.sslValidate=false] Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {array} [options.sslCA] Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {array} [options.sslCRL] Array of revocation certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {(Buffer|string)} [options.sslCert] String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher. + * @param {string} [options.ciphers] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. + * @param {string} [options.ecdhCurve] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. + * @param {(Buffer|string)} [options.sslKey] String or buffer containing the certificate private key we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {(Buffer|string)} [options.sslPass] String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {string} [options.servername] String containing the server name requested via TLS SNI. + * @param {object} [options.socketOptions] Socket options + * @param {boolean} [options.socketOptions.noDelay=true] TCP Socket NoDelay option. + * @param {boolean} [options.socketOptions.keepAlive=true] TCP Connection keep alive enabled + * @param {number} [options.socketOptions.keepAliveInitialDelay=30000] The number of milliseconds to wait before initiating keepAlive on the TCP socket + * @param {number} [options.socketOptions.connectTimeoutMS=10000] TCP Connection timeout setting + * @param {number} [options.socketOptions.socketTimeoutMS=0] TCP Socket timeout setting + * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. + * @param {number} [options.maxStalenessSeconds=undefined] The max staleness to secondary reads (values under 10 seconds cannot be guaranteed); + * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology + * @fires ReplSet#connect + * @fires ReplSet#ha + * @fires ReplSet#joined + * @fires ReplSet#left + * @fires ReplSet#fullsetup + * @fires ReplSet#open + * @fires ReplSet#close + * @fires ReplSet#error + * @fires ReplSet#timeout + * @fires ReplSet#parseError + * @fires ReplSet#commandStarted + * @fires ReplSet#commandSucceeded + * @fires ReplSet#commandFailed + * @property {string} parserType the parser type used (c++ or js). + * @return {ReplSet} a ReplSet instance. + */ +class ReplSet extends TopologyBase { + constructor(servers, options) { + super(); + + options = options || {}; + var self = this; + + // Filter the options + options = filterOptions(options, legalOptionNames); + + // Ensure all the instances are Server + for (var i = 0; i < servers.length; i++) { + if (!(servers[i] instanceof Server)) { + throw MongoError.create({ + message: 'all seed list instances must be of the Server type', + driver: true + }); + } + } + + // Stored options + var storeOptions = { + force: false, + bufferMaxEntries: + typeof options.bufferMaxEntries === 'number' ? options.bufferMaxEntries : MAX_JS_INT + }; + + // Shared global store + var store = options.store || new Store(self, storeOptions); + + // Build seed list + var seedlist = servers.map(function(x) { + return { host: x.host, port: x.port }; + }); + + // Clone options + var clonedOptions = mergeOptions( + {}, + { + disconnectHandler: store, + cursorFactory: Cursor, + reconnect: false, + emitError: typeof options.emitError === 'boolean' ? options.emitError : true, + size: typeof options.poolSize === 'number' ? options.poolSize : 5, + monitorCommands: + typeof options.monitorCommands === 'boolean' ? options.monitorCommands : false + } + ); + + // Translate any SSL options and other connectivity options + clonedOptions = translateOptions(clonedOptions, options); + + // Socket options + var socketOptions = + options.socketOptions && Object.keys(options.socketOptions).length > 0 + ? options.socketOptions + : options; + + // Translate all the options to the core types + clonedOptions = translateOptions(clonedOptions, socketOptions); + + // Build default client information + clonedOptions.clientInfo = this.clientInfo; + // Do we have an application specific string + if (options.appname) { + clonedOptions.clientInfo.application = { name: options.appname }; + } + + // Create the ReplSet + var coreTopology = new CReplSet(seedlist, clonedOptions); + + // Listen to reconnect event + coreTopology.on('reconnect', function() { + self.emit('reconnect'); + store.execute(); + }); + + // Internal state + this.s = { + // Replicaset + coreTopology: coreTopology, + // Server capabilities + sCapabilities: null, + // Debug tag + tag: options.tag, + // Store options + storeOptions: storeOptions, + // Cloned options + clonedOptions: clonedOptions, + // Store + store: store, + // Options + options: options, + // Server Session Pool + sessionPool: null, + // Active client sessions + sessions: new Set(), + // Promise library + promiseLibrary: options.promiseLibrary || Promise + }; + + // Debug + if (clonedOptions.debug) { + // Last ismaster + Object.defineProperty(this, 'replset', { + enumerable: true, + get: function() { + return coreTopology; + } + }); + } + } + + // Connect method + connect(_options, callback) { + var self = this; + if ('function' === typeof _options) (callback = _options), (_options = {}); + if (_options == null) _options = {}; + if (!('function' === typeof callback)) callback = null; + _options = Object.assign({}, this.s.clonedOptions, _options); + self.s.options = _options; + + // Update bufferMaxEntries + self.s.storeOptions.bufferMaxEntries = + typeof _options.bufferMaxEntries === 'number' ? _options.bufferMaxEntries : -1; + + // Actual handler + var errorHandler = function(event) { + return function(err) { + if (event !== 'error') { + self.emit(event, err); + } + }; + }; + + // Clear out all the current handlers left over + var events = [ + 'timeout', + 'error', + 'close', + 'serverOpening', + 'serverDescriptionChanged', + 'serverHeartbeatStarted', + 'serverHeartbeatSucceeded', + 'serverHeartbeatFailed', + 'serverClosed', + 'topologyOpening', + 'topologyClosed', + 'topologyDescriptionChanged', + 'commandStarted', + 'commandSucceeded', + 'commandFailed', + 'joined', + 'left', + 'ping', + 'ha' + ]; + events.forEach(function(e) { + self.s.coreTopology.removeAllListeners(e); + }); + + // relay the event + var relay = function(event) { + return function(t, server) { + self.emit(event, t, server); + }; + }; + + // Replset events relay + var replsetRelay = function(event) { + return function(t, server) { + self.emit(event, t, server.lastIsMaster(), server); + }; + }; + + // Relay ha + var relayHa = function(t, state) { + self.emit('ha', t, state); + + if (t === 'start') { + self.emit('ha_connect', t, state); + } else if (t === 'end') { + self.emit('ha_ismaster', t, state); + } + }; + + // Set up serverConfig listeners + self.s.coreTopology.on('joined', replsetRelay('joined')); + self.s.coreTopology.on('left', relay('left')); + self.s.coreTopology.on('ping', relay('ping')); + self.s.coreTopology.on('ha', relayHa); + + // Set up SDAM listeners + self.s.coreTopology.on('serverDescriptionChanged', relay('serverDescriptionChanged')); + self.s.coreTopology.on('serverHeartbeatStarted', relay('serverHeartbeatStarted')); + self.s.coreTopology.on('serverHeartbeatSucceeded', relay('serverHeartbeatSucceeded')); + self.s.coreTopology.on('serverHeartbeatFailed', relay('serverHeartbeatFailed')); + self.s.coreTopology.on('serverOpening', relay('serverOpening')); + self.s.coreTopology.on('serverClosed', relay('serverClosed')); + self.s.coreTopology.on('topologyOpening', relay('topologyOpening')); + self.s.coreTopology.on('topologyClosed', relay('topologyClosed')); + self.s.coreTopology.on('topologyDescriptionChanged', relay('topologyDescriptionChanged')); + self.s.coreTopology.on('commandStarted', relay('commandStarted')); + self.s.coreTopology.on('commandSucceeded', relay('commandSucceeded')); + self.s.coreTopology.on('commandFailed', relay('commandFailed')); + + self.s.coreTopology.on('fullsetup', function() { + self.emit('fullsetup', self, self); + }); + + self.s.coreTopology.on('all', function() { + self.emit('all', null, self); + }); + + // Connect handler + var connectHandler = function() { + // Set up listeners + self.s.coreTopology.once('timeout', errorHandler('timeout')); + self.s.coreTopology.once('error', errorHandler('error')); + self.s.coreTopology.once('close', errorHandler('close')); + + // Emit open event + self.emit('open', null, self); + + // Return correctly + try { + callback(null, self); + } catch (err) { + process.nextTick(function() { + throw err; + }); + } + }; + + // Error handler + var connectErrorHandler = function() { + return function(err) { + ['timeout', 'error', 'close'].forEach(function(e) { + self.s.coreTopology.removeListener(e, connectErrorHandler); + }); + + self.s.coreTopology.removeListener('connect', connectErrorHandler); + // Destroy the replset + self.s.coreTopology.destroy(); + + // Try to callback + try { + callback(err); + } catch (err) { + if (!self.s.coreTopology.isConnected()) + process.nextTick(function() { + throw err; + }); + } + }; + }; + + // Set up listeners + self.s.coreTopology.once('timeout', connectErrorHandler('timeout')); + self.s.coreTopology.once('error', connectErrorHandler('error')); + self.s.coreTopology.once('close', connectErrorHandler('close')); + self.s.coreTopology.once('connect', connectHandler); + + // Start connection + self.s.coreTopology.connect(_options); + } + + close(forceClosed, callback) { + ['timeout', 'error', 'close', 'joined', 'left'].forEach(e => this.removeAllListeners(e)); + super.close(forceClosed, callback); + } +} + +Object.defineProperty(ReplSet.prototype, 'haInterval', { + enumerable: true, + get: function() { + return this.s.coreTopology.s.haInterval; + } +}); + +/** + * A replset connect event, used to verify that the connection is up and running + * + * @event ReplSet#connect + * @type {ReplSet} + */ + +/** + * The replset high availability event + * + * @event ReplSet#ha + * @type {function} + * @param {string} type The stage in the high availability event (start|end) + * @param {boolean} data.norepeat This is a repeating high availability process or a single execution only + * @param {number} data.id The id for this high availability request + * @param {object} data.state An object containing the information about the current replicaset + */ + +/** + * A server member left the replicaset + * + * @event ReplSet#left + * @type {function} + * @param {string} type The type of member that left (primary|secondary|arbiter) + * @param {Server} server The server object that left + */ + +/** + * A server member joined the replicaset + * + * @event ReplSet#joined + * @type {function} + * @param {string} type The type of member that joined (primary|secondary|arbiter) + * @param {Server} server The server object that joined + */ + +/** + * ReplSet open event, emitted when replicaset can start processing commands. + * + * @event ReplSet#open + * @type {Replset} + */ + +/** + * ReplSet fullsetup event, emitted when all servers in the topology have been connected to. + * + * @event ReplSet#fullsetup + * @type {Replset} + */ + +/** + * ReplSet close event + * + * @event ReplSet#close + * @type {object} + */ + +/** + * ReplSet error event, emitted if there is an error listener. + * + * @event ReplSet#error + * @type {MongoError} + */ + +/** + * ReplSet timeout event + * + * @event ReplSet#timeout + * @type {object} + */ + +/** + * ReplSet parseError event + * + * @event ReplSet#parseError + * @type {object} + */ + +/** + * An event emitted indicating a command was started, if command monitoring is enabled + * + * @event ReplSet#commandStarted + * @type {object} + */ + +/** + * An event emitted indicating a command succeeded, if command monitoring is enabled + * + * @event ReplSet#commandSucceeded + * @type {object} + */ + +/** + * An event emitted indicating a command failed, if command monitoring is enabled + * + * @event ReplSet#commandFailed + * @type {object} + */ + +module.exports = ReplSet; diff --git a/scripts/node_modules/mongodb/lib/topologies/server.js b/scripts/node_modules/mongodb/lib/topologies/server.js new file mode 100644 index 00000000..9bbe4350 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/topologies/server.js @@ -0,0 +1,455 @@ +'use strict'; + +const CServer = require('../core').Server; +const Cursor = require('../cursor'); +const TopologyBase = require('./topology_base').TopologyBase; +const Store = require('./topology_base').Store; +const MongoError = require('../core').MongoError; +const MAX_JS_INT = require('../utils').MAX_JS_INT; +const translateOptions = require('../utils').translateOptions; +const filterOptions = require('../utils').filterOptions; +const mergeOptions = require('../utils').mergeOptions; + +/** + * @fileOverview The **Server** class is a class that represents a single server topology and is + * used to construct connections. + * + * **Server Should not be used, use MongoClient.connect** + */ + +// Allowed parameters +var legalOptionNames = [ + 'ha', + 'haInterval', + 'acceptableLatencyMS', + 'poolSize', + 'ssl', + 'checkServerIdentity', + 'sslValidate', + 'sslCA', + 'sslCRL', + 'sslCert', + 'ciphers', + 'ecdhCurve', + 'sslKey', + 'sslPass', + 'socketOptions', + 'bufferMaxEntries', + 'store', + 'auto_reconnect', + 'autoReconnect', + 'emitError', + 'keepAlive', + 'keepAliveInitialDelay', + 'noDelay', + 'connectTimeoutMS', + 'socketTimeoutMS', + 'family', + 'loggerLevel', + 'logger', + 'reconnectTries', + 'reconnectInterval', + 'monitoring', + 'appname', + 'domainsEnabled', + 'servername', + 'promoteLongs', + 'promoteValues', + 'promoteBuffers', + 'compression', + 'promiseLibrary', + 'monitorCommands' +]; + +/** + * Creates a new Server instance + * @class + * @deprecated + * @param {string} host The host for the server, can be either an IP4, IP6 or domain socket style host. + * @param {number} [port] The server port if IP4. + * @param {object} [options] Optional settings. + * @param {number} [options.poolSize=5] Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons. + * @param {boolean} [options.ssl=false] Use ssl connection (needs to have a mongod server with ssl support) + * @param {boolean} [options.sslValidate=false] Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. + * @param {array} [options.sslCA] Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {array} [options.sslCRL] Array of revocation certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {(Buffer|string)} [options.sslCert] String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {string} [options.ciphers] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. + * @param {string} [options.ecdhCurve] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. + * @param {(Buffer|string)} [options.sslKey] String or buffer containing the certificate private key we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {(Buffer|string)} [options.sslPass] String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {string} [options.servername] String containing the server name requested via TLS SNI. + * @param {object} [options.socketOptions] Socket options + * @param {boolean} [options.socketOptions.autoReconnect=true] Reconnect on error. + * @param {boolean} [options.socketOptions.noDelay=true] TCP Socket NoDelay option. + * @param {boolean} [options.socketOptions.keepAlive=true] TCP Connection keep alive enabled + * @param {number} [options.socketOptions.keepAliveInitialDelay=30000] The number of milliseconds to wait before initiating keepAlive on the TCP socket + * @param {number} [options.socketOptions.connectTimeoutMS=0] TCP Connection timeout setting + * @param {number} [options.socketOptions.socketTimeoutMS=0] TCP Socket timeout setting + * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times + * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries + * @param {boolean} [options.monitoring=true] Triggers the server instance to call ismaster + * @param {number} [options.haInterval=10000] The interval of calling ismaster when monitoring is enabled. + * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. + * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology + * @fires Server#connect + * @fires Server#close + * @fires Server#error + * @fires Server#timeout + * @fires Server#parseError + * @fires Server#reconnect + * @fires Server#commandStarted + * @fires Server#commandSucceeded + * @fires Server#commandFailed + * @property {string} parserType the parser type used (c++ or js). + * @return {Server} a Server instance. + */ +class Server extends TopologyBase { + constructor(host, port, options) { + super(); + var self = this; + + // Filter the options + options = filterOptions(options, legalOptionNames); + + // Promise library + const promiseLibrary = options.promiseLibrary; + + // Stored options + var storeOptions = { + force: false, + bufferMaxEntries: + typeof options.bufferMaxEntries === 'number' ? options.bufferMaxEntries : MAX_JS_INT + }; + + // Shared global store + var store = options.store || new Store(self, storeOptions); + + // Detect if we have a socket connection + if (host.indexOf('/') !== -1) { + if (port != null && typeof port === 'object') { + options = port; + port = null; + } + } else if (port == null) { + throw MongoError.create({ message: 'port must be specified', driver: true }); + } + + // Get the reconnect option + var reconnect = typeof options.auto_reconnect === 'boolean' ? options.auto_reconnect : true; + reconnect = typeof options.autoReconnect === 'boolean' ? options.autoReconnect : reconnect; + + // Clone options + var clonedOptions = mergeOptions( + {}, + { + host: host, + port: port, + disconnectHandler: store, + cursorFactory: Cursor, + reconnect: reconnect, + emitError: typeof options.emitError === 'boolean' ? options.emitError : true, + size: typeof options.poolSize === 'number' ? options.poolSize : 5, + monitorCommands: + typeof options.monitorCommands === 'boolean' ? options.monitorCommands : false + } + ); + + // Translate any SSL options and other connectivity options + clonedOptions = translateOptions(clonedOptions, options); + + // Socket options + var socketOptions = + options.socketOptions && Object.keys(options.socketOptions).length > 0 + ? options.socketOptions + : options; + + // Translate all the options to the core types + clonedOptions = translateOptions(clonedOptions, socketOptions); + + // Build default client information + clonedOptions.clientInfo = this.clientInfo; + // Do we have an application specific string + if (options.appname) { + clonedOptions.clientInfo.application = { name: options.appname }; + } + + // Define the internal properties + this.s = { + // Create an instance of a server instance from core module + coreTopology: new CServer(clonedOptions), + // Server capabilities + sCapabilities: null, + // Cloned options + clonedOptions: clonedOptions, + // Reconnect + reconnect: clonedOptions.reconnect, + // Emit error + emitError: clonedOptions.emitError, + // Pool size + poolSize: clonedOptions.size, + // Store Options + storeOptions: storeOptions, + // Store + store: store, + // Host + host: host, + // Port + port: port, + // Options + options: options, + // Server Session Pool + sessionPool: null, + // Active client sessions + sessions: new Set(), + // Promise library + promiseLibrary: promiseLibrary || Promise + }; + } + + // Connect + connect(_options, callback) { + var self = this; + if ('function' === typeof _options) (callback = _options), (_options = {}); + if (_options == null) _options = this.s.clonedOptions; + if (!('function' === typeof callback)) callback = null; + _options = Object.assign({}, this.s.clonedOptions, _options); + self.s.options = _options; + + // Update bufferMaxEntries + self.s.storeOptions.bufferMaxEntries = + typeof _options.bufferMaxEntries === 'number' ? _options.bufferMaxEntries : -1; + + // Error handler + var connectErrorHandler = function() { + return function(err) { + // Remove all event handlers + var events = ['timeout', 'error', 'close']; + events.forEach(function(e) { + self.s.coreTopology.removeListener(e, connectHandlers[e]); + }); + + self.s.coreTopology.removeListener('connect', connectErrorHandler); + + // Try to callback + try { + callback(err); + } catch (err) { + process.nextTick(function() { + throw err; + }); + } + }; + }; + + // Actual handler + var errorHandler = function(event) { + return function(err) { + if (event !== 'error') { + self.emit(event, err); + } + }; + }; + + // Error handler + var reconnectHandler = function() { + self.emit('reconnect', self); + self.s.store.execute(); + }; + + // Reconnect failed + var reconnectFailedHandler = function(err) { + self.emit('reconnectFailed', err); + self.s.store.flush(err); + }; + + // Destroy called on topology, perform cleanup + var destroyHandler = function() { + self.s.store.flush(); + }; + + // relay the event + var relay = function(event) { + return function(t, server) { + self.emit(event, t, server); + }; + }; + + // Connect handler + var connectHandler = function() { + // Clear out all the current handlers left over + ['timeout', 'error', 'close', 'destroy'].forEach(function(e) { + self.s.coreTopology.removeAllListeners(e); + }); + + // Set up listeners + self.s.coreTopology.on('timeout', errorHandler('timeout')); + self.s.coreTopology.once('error', errorHandler('error')); + self.s.coreTopology.on('close', errorHandler('close')); + // Only called on destroy + self.s.coreTopology.on('destroy', destroyHandler); + + // Emit open event + self.emit('open', null, self); + + // Return correctly + try { + callback(null, self); + } catch (err) { + process.nextTick(function() { + throw err; + }); + } + }; + + // Set up listeners + var connectHandlers = { + timeout: connectErrorHandler('timeout'), + error: connectErrorHandler('error'), + close: connectErrorHandler('close') + }; + + // Clear out all the current handlers left over + [ + 'timeout', + 'error', + 'close', + 'serverOpening', + 'serverDescriptionChanged', + 'serverHeartbeatStarted', + 'serverHeartbeatSucceeded', + 'serverHeartbeatFailed', + 'serverClosed', + 'topologyOpening', + 'topologyClosed', + 'topologyDescriptionChanged', + 'commandStarted', + 'commandSucceeded', + 'commandFailed' + ].forEach(function(e) { + self.s.coreTopology.removeAllListeners(e); + }); + + // Add the event handlers + self.s.coreTopology.once('timeout', connectHandlers.timeout); + self.s.coreTopology.once('error', connectHandlers.error); + self.s.coreTopology.once('close', connectHandlers.close); + self.s.coreTopology.once('connect', connectHandler); + // Reconnect server + self.s.coreTopology.on('reconnect', reconnectHandler); + self.s.coreTopology.on('reconnectFailed', reconnectFailedHandler); + + // Set up SDAM listeners + self.s.coreTopology.on('serverDescriptionChanged', relay('serverDescriptionChanged')); + self.s.coreTopology.on('serverHeartbeatStarted', relay('serverHeartbeatStarted')); + self.s.coreTopology.on('serverHeartbeatSucceeded', relay('serverHeartbeatSucceeded')); + self.s.coreTopology.on('serverHeartbeatFailed', relay('serverHeartbeatFailed')); + self.s.coreTopology.on('serverOpening', relay('serverOpening')); + self.s.coreTopology.on('serverClosed', relay('serverClosed')); + self.s.coreTopology.on('topologyOpening', relay('topologyOpening')); + self.s.coreTopology.on('topologyClosed', relay('topologyClosed')); + self.s.coreTopology.on('topologyDescriptionChanged', relay('topologyDescriptionChanged')); + self.s.coreTopology.on('commandStarted', relay('commandStarted')); + self.s.coreTopology.on('commandSucceeded', relay('commandSucceeded')); + self.s.coreTopology.on('commandFailed', relay('commandFailed')); + self.s.coreTopology.on('attemptReconnect', relay('attemptReconnect')); + self.s.coreTopology.on('monitoring', relay('monitoring')); + + // Start connection + self.s.coreTopology.connect(_options); + } +} + +Object.defineProperty(Server.prototype, 'poolSize', { + enumerable: true, + get: function() { + return this.s.coreTopology.connections().length; + } +}); + +Object.defineProperty(Server.prototype, 'autoReconnect', { + enumerable: true, + get: function() { + return this.s.reconnect; + } +}); + +Object.defineProperty(Server.prototype, 'host', { + enumerable: true, + get: function() { + return this.s.host; + } +}); + +Object.defineProperty(Server.prototype, 'port', { + enumerable: true, + get: function() { + return this.s.port; + } +}); + +/** + * Server connect event + * + * @event Server#connect + * @type {object} + */ + +/** + * Server close event + * + * @event Server#close + * @type {object} + */ + +/** + * Server reconnect event + * + * @event Server#reconnect + * @type {object} + */ + +/** + * Server error event + * + * @event Server#error + * @type {MongoError} + */ + +/** + * Server timeout event + * + * @event Server#timeout + * @type {object} + */ + +/** + * Server parseError event + * + * @event Server#parseError + * @type {object} + */ + +/** + * An event emitted indicating a command was started, if command monitoring is enabled + * + * @event Server#commandStarted + * @type {object} + */ + +/** + * An event emitted indicating a command succeeded, if command monitoring is enabled + * + * @event Server#commandSucceeded + * @type {object} + */ + +/** + * An event emitted indicating a command failed, if command monitoring is enabled + * + * @event Server#commandFailed + * @type {object} + */ + +module.exports = Server; diff --git a/scripts/node_modules/mongodb/lib/topologies/topology_base.js b/scripts/node_modules/mongodb/lib/topologies/topology_base.js new file mode 100644 index 00000000..e74cb9ff --- /dev/null +++ b/scripts/node_modules/mongodb/lib/topologies/topology_base.js @@ -0,0 +1,438 @@ +'use strict'; + +const EventEmitter = require('events'), + MongoError = require('../core').MongoError, + f = require('util').format, + os = require('os'), + translateReadPreference = require('../utils').translateReadPreference, + ClientSession = require('../core').Sessions.ClientSession; + +// The store of ops +var Store = function(topology, storeOptions) { + var self = this; + var storedOps = []; + storeOptions = storeOptions || { force: false, bufferMaxEntries: -1 }; + + // Internal state + this.s = { + storedOps: storedOps, + storeOptions: storeOptions, + topology: topology + }; + + Object.defineProperty(this, 'length', { + enumerable: true, + get: function() { + return self.s.storedOps.length; + } + }); +}; + +Store.prototype.add = function(opType, ns, ops, options, callback) { + if (this.s.storeOptions.force) { + return callback(MongoError.create({ message: 'db closed by application', driver: true })); + } + + if (this.s.storeOptions.bufferMaxEntries === 0) { + return callback( + MongoError.create({ + message: f( + 'no connection available for operation and number of stored operation > %s', + this.s.storeOptions.bufferMaxEntries + ), + driver: true + }) + ); + } + + if ( + this.s.storeOptions.bufferMaxEntries > 0 && + this.s.storedOps.length > this.s.storeOptions.bufferMaxEntries + ) { + while (this.s.storedOps.length > 0) { + var op = this.s.storedOps.shift(); + op.c( + MongoError.create({ + message: f( + 'no connection available for operation and number of stored operation > %s', + this.s.storeOptions.bufferMaxEntries + ), + driver: true + }) + ); + } + + return; + } + + this.s.storedOps.push({ t: opType, n: ns, o: ops, op: options, c: callback }); +}; + +Store.prototype.addObjectAndMethod = function(opType, object, method, params, callback) { + if (this.s.storeOptions.force) { + return callback(MongoError.create({ message: 'db closed by application', driver: true })); + } + + if (this.s.storeOptions.bufferMaxEntries === 0) { + return callback( + MongoError.create({ + message: f( + 'no connection available for operation and number of stored operation > %s', + this.s.storeOptions.bufferMaxEntries + ), + driver: true + }) + ); + } + + if ( + this.s.storeOptions.bufferMaxEntries > 0 && + this.s.storedOps.length > this.s.storeOptions.bufferMaxEntries + ) { + while (this.s.storedOps.length > 0) { + var op = this.s.storedOps.shift(); + op.c( + MongoError.create({ + message: f( + 'no connection available for operation and number of stored operation > %s', + this.s.storeOptions.bufferMaxEntries + ), + driver: true + }) + ); + } + + return; + } + + this.s.storedOps.push({ t: opType, m: method, o: object, p: params, c: callback }); +}; + +Store.prototype.flush = function(err) { + while (this.s.storedOps.length > 0) { + this.s.storedOps + .shift() + .c( + err || + MongoError.create({ message: f('no connection available for operation'), driver: true }) + ); + } +}; + +var primaryOptions = ['primary', 'primaryPreferred', 'nearest', 'secondaryPreferred']; +var secondaryOptions = ['secondary', 'secondaryPreferred']; + +Store.prototype.execute = function(options) { + options = options || {}; + // Get current ops + var ops = this.s.storedOps; + // Reset the ops + this.s.storedOps = []; + + // Unpack options + var executePrimary = typeof options.executePrimary === 'boolean' ? options.executePrimary : true; + var executeSecondary = + typeof options.executeSecondary === 'boolean' ? options.executeSecondary : true; + + // Execute all the stored ops + while (ops.length > 0) { + var op = ops.shift(); + + if (op.t === 'cursor') { + if (executePrimary && executeSecondary) { + op.o[op.m].apply(op.o, op.p); + } else if ( + executePrimary && + op.o.options && + op.o.options.readPreference && + primaryOptions.indexOf(op.o.options.readPreference.mode) !== -1 + ) { + op.o[op.m].apply(op.o, op.p); + } else if ( + !executePrimary && + executeSecondary && + op.o.options && + op.o.options.readPreference && + secondaryOptions.indexOf(op.o.options.readPreference.mode) !== -1 + ) { + op.o[op.m].apply(op.o, op.p); + } + } else if (op.t === 'auth') { + this.s.topology[op.t].apply(this.s.topology, op.o); + } else { + if (executePrimary && executeSecondary) { + this.s.topology[op.t](op.n, op.o, op.op, op.c); + } else if ( + executePrimary && + op.op && + op.op.readPreference && + primaryOptions.indexOf(op.op.readPreference.mode) !== -1 + ) { + this.s.topology[op.t](op.n, op.o, op.op, op.c); + } else if ( + !executePrimary && + executeSecondary && + op.op && + op.op.readPreference && + secondaryOptions.indexOf(op.op.readPreference.mode) !== -1 + ) { + this.s.topology[op.t](op.n, op.o, op.op, op.c); + } + } + } +}; + +Store.prototype.all = function() { + return this.s.storedOps; +}; + +// Server capabilities +var ServerCapabilities = function(ismaster) { + var setup_get_property = function(object, name, value) { + Object.defineProperty(object, name, { + enumerable: true, + get: function() { + return value; + } + }); + }; + + // Capabilities + var aggregationCursor = false; + var writeCommands = false; + var textSearch = false; + var authCommands = false; + var listCollections = false; + var listIndexes = false; + var maxNumberOfDocsInBatch = ismaster.maxWriteBatchSize || 1000; + var commandsTakeWriteConcern = false; + var commandsTakeCollation = false; + + if (ismaster.minWireVersion >= 0) { + textSearch = true; + } + + if (ismaster.maxWireVersion >= 1) { + aggregationCursor = true; + authCommands = true; + } + + if (ismaster.maxWireVersion >= 2) { + writeCommands = true; + } + + if (ismaster.maxWireVersion >= 3) { + listCollections = true; + listIndexes = true; + } + + if (ismaster.maxWireVersion >= 5) { + commandsTakeWriteConcern = true; + commandsTakeCollation = true; + } + + // If no min or max wire version set to 0 + if (ismaster.minWireVersion == null) { + ismaster.minWireVersion = 0; + } + + if (ismaster.maxWireVersion == null) { + ismaster.maxWireVersion = 0; + } + + // Map up read only parameters + setup_get_property(this, 'hasAggregationCursor', aggregationCursor); + setup_get_property(this, 'hasWriteCommands', writeCommands); + setup_get_property(this, 'hasTextSearch', textSearch); + setup_get_property(this, 'hasAuthCommands', authCommands); + setup_get_property(this, 'hasListCollectionsCommand', listCollections); + setup_get_property(this, 'hasListIndexesCommand', listIndexes); + setup_get_property(this, 'minWireVersion', ismaster.minWireVersion); + setup_get_property(this, 'maxWireVersion', ismaster.maxWireVersion); + setup_get_property(this, 'maxNumberOfDocsInBatch', maxNumberOfDocsInBatch); + setup_get_property(this, 'commandsTakeWriteConcern', commandsTakeWriteConcern); + setup_get_property(this, 'commandsTakeCollation', commandsTakeCollation); +}; + +// Get package.json variable +const driverVersion = require('../../package.json').version, + nodejsversion = f('Node.js %s, %s', process.version, os.endianness()), + type = os.type(), + name = process.platform, + architecture = process.arch, + release = os.release(); + +class TopologyBase extends EventEmitter { + constructor() { + super(); + + // Build default client information + this.clientInfo = { + driver: { + name: 'nodejs', + version: driverVersion + }, + os: { + type: type, + name: name, + architecture: architecture, + version: release + }, + platform: nodejsversion + }; + + this.setMaxListeners(Infinity); + } + + // Sessions related methods + hasSessionSupport() { + return this.logicalSessionTimeoutMinutes != null; + } + + startSession(options, clientOptions) { + const session = new ClientSession(this, this.s.sessionPool, options, clientOptions); + + session.once('ended', () => { + this.s.sessions.delete(session); + }); + + this.s.sessions.add(session); + return session; + } + + endSessions(sessions, callback) { + return this.s.coreTopology.endSessions(sessions, callback); + } + + // Server capabilities + capabilities() { + if (this.s.sCapabilities) return this.s.sCapabilities; + if (this.s.coreTopology.lastIsMaster() == null) return null; + this.s.sCapabilities = new ServerCapabilities(this.s.coreTopology.lastIsMaster()); + return this.s.sCapabilities; + } + + // Command + command(ns, cmd, options, callback) { + this.s.coreTopology.command(ns.toString(), cmd, translateReadPreference(options), callback); + } + + // Insert + insert(ns, ops, options, callback) { + this.s.coreTopology.insert(ns.toString(), ops, options, callback); + } + + // Update + update(ns, ops, options, callback) { + this.s.coreTopology.update(ns.toString(), ops, options, callback); + } + + // Remove + remove(ns, ops, options, callback) { + this.s.coreTopology.remove(ns.toString(), ops, options, callback); + } + + // IsConnected + isConnected(options) { + options = options || {}; + options = translateReadPreference(options); + + return this.s.coreTopology.isConnected(options); + } + + // IsDestroyed + isDestroyed() { + return this.s.coreTopology.isDestroyed(); + } + + // Cursor + cursor(ns, cmd, options) { + options = options || {}; + options = translateReadPreference(options); + options.disconnectHandler = this.s.store; + options.topology = this; + + return this.s.coreTopology.cursor(ns, cmd, options); + } + + lastIsMaster() { + return this.s.coreTopology.lastIsMaster(); + } + + selectServer(selector, options, callback) { + return this.s.coreTopology.selectServer(selector, options, callback); + } + + /** + * Unref all sockets + * @method + */ + unref() { + return this.s.coreTopology.unref(); + } + + /** + * All raw connections + * @method + * @return {array} + */ + connections() { + return this.s.coreTopology.connections(); + } + + close(forceClosed, callback) { + // If we have sessions, we want to individually move them to the session pool, + // and then send a single endSessions call. + this.s.sessions.forEach(session => session.endSession()); + + if (this.s.sessionPool) { + this.s.sessionPool.endAllPooledSessions(); + } + + // We need to wash out all stored processes + if (forceClosed === true) { + this.s.storeOptions.force = forceClosed; + this.s.store.flush(); + } + + this.s.coreTopology.destroy( + { + force: typeof forceClosed === 'boolean' ? forceClosed : false + }, + callback + ); + } +} + +// Properties +Object.defineProperty(TopologyBase.prototype, 'bson', { + enumerable: true, + get: function() { + return this.s.coreTopology.s.bson; + } +}); + +Object.defineProperty(TopologyBase.prototype, 'parserType', { + enumerable: true, + get: function() { + return this.s.coreTopology.parserType; + } +}); + +Object.defineProperty(TopologyBase.prototype, 'logicalSessionTimeoutMinutes', { + enumerable: true, + get: function() { + return this.s.coreTopology.logicalSessionTimeoutMinutes; + } +}); + +Object.defineProperty(TopologyBase.prototype, 'type', { + enumerable: true, + get: function() { + return this.s.coreTopology.type; + } +}); + +exports.Store = Store; +exports.ServerCapabilities = ServerCapabilities; +exports.TopologyBase = TopologyBase; diff --git a/scripts/node_modules/mongodb/lib/url_parser.js b/scripts/node_modules/mongodb/lib/url_parser.js new file mode 100644 index 00000000..c0f10b46 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/url_parser.js @@ -0,0 +1,623 @@ +'use strict'; + +const ReadPreference = require('./core').ReadPreference, + parser = require('url'), + f = require('util').format, + Logger = require('./core').Logger, + dns = require('dns'); +const ReadConcern = require('./read_concern'); + +module.exports = function(url, options, callback) { + if (typeof options === 'function') (callback = options), (options = {}); + options = options || {}; + + let result; + try { + result = parser.parse(url, true); + } catch (e) { + return callback(new Error('URL malformed, cannot be parsed')); + } + + if (result.protocol !== 'mongodb:' && result.protocol !== 'mongodb+srv:') { + return callback(new Error('Invalid schema, expected `mongodb` or `mongodb+srv`')); + } + + if (result.protocol === 'mongodb:') { + return parseHandler(url, options, callback); + } + + // Otherwise parse this as an SRV record + if (result.hostname.split('.').length < 3) { + return callback(new Error('URI does not have hostname, domain name and tld')); + } + + result.domainLength = result.hostname.split('.').length; + + if (result.pathname && result.pathname.match(',')) { + return callback(new Error('Invalid URI, cannot contain multiple hostnames')); + } + + if (result.port) { + return callback(new Error('Ports not accepted with `mongodb+srv` URIs')); + } + + let srvAddress = `_mongodb._tcp.${result.host}`; + dns.resolveSrv(srvAddress, function(err, addresses) { + if (err) return callback(err); + + if (addresses.length === 0) { + return callback(new Error('No addresses found at host')); + } + + for (let i = 0; i < addresses.length; i++) { + if (!matchesParentDomain(addresses[i].name, result.hostname, result.domainLength)) { + return callback(new Error('Server record does not share hostname with parent URI')); + } + } + + let base = result.auth ? `mongodb://${result.auth}@` : `mongodb://`; + let connectionStrings = addresses.map(function(address, i) { + if (i === 0) return `${base}${address.name}:${address.port}`; + else return `${address.name}:${address.port}`; + }); + + let connectionString = connectionStrings.join(',') + '/'; + let connectionStringOptions = []; + + // Add the default database if needed + if (result.path) { + let defaultDb = result.path.slice(1); + if (defaultDb.indexOf('?') !== -1) { + defaultDb = defaultDb.slice(0, defaultDb.indexOf('?')); + } + + connectionString += defaultDb; + } + + // Default to SSL true + if (!options.ssl && !result.search) { + connectionStringOptions.push('ssl=true'); + } else if (!options.ssl && result.search && !result.search.match('ssl')) { + connectionStringOptions.push('ssl=true'); + } + + // Keep original uri options + if (result.search) { + connectionStringOptions.push(result.search.replace('?', '')); + } + + dns.resolveTxt(result.host, function(err, record) { + if (err && err.code !== 'ENODATA') return callback(err); + if (err && err.code === 'ENODATA') record = null; + + if (record) { + if (record.length > 1) { + return callback(new Error('Multiple text records not allowed')); + } + + record = record[0]; + if (record.length > 1) record = record.join(''); + else record = record[0]; + + if (!record.includes('authSource') && !record.includes('replicaSet')) { + return callback(new Error('Text record must only set `authSource` or `replicaSet`')); + } + + connectionStringOptions.push(record); + } + + // Add any options to the connection string + if (connectionStringOptions.length) { + connectionString += `?${connectionStringOptions.join('&')}`; + } + + parseHandler(connectionString, options, callback); + }); + }); +}; + +function matchesParentDomain(srvAddress, parentDomain) { + let regex = /^.*?\./; + let srv = `.${srvAddress.replace(regex, '')}`; + let parent = `.${parentDomain.replace(regex, '')}`; + if (srv.endsWith(parent)) return true; + else return false; +} + +function parseHandler(address, options, callback) { + let result, err; + try { + result = parseConnectionString(address, options); + } catch (e) { + err = e; + } + + return err ? callback(err, null) : callback(null, result); +} + +function parseConnectionString(url, options) { + // Variables + let connection_part = ''; + let auth_part = ''; + let query_string_part = ''; + let dbName = 'admin'; + + // Url parser result + let result = parser.parse(url, true); + if ((result.hostname == null || result.hostname === '') && url.indexOf('.sock') === -1) { + throw new Error('No hostname or hostnames provided in connection string'); + } + + if (result.port === '0') { + throw new Error('Invalid port (zero) with hostname'); + } + + if (!isNaN(parseInt(result.port, 10)) && parseInt(result.port, 10) > 65535) { + throw new Error('Invalid port (larger than 65535) with hostname'); + } + + if ( + result.path && + result.path.length > 0 && + result.path[0] !== '/' && + url.indexOf('.sock') === -1 + ) { + throw new Error('Missing delimiting slash between hosts and options'); + } + + if (result.query) { + for (let name in result.query) { + if (name.indexOf('::') !== -1) { + throw new Error('Double colon in host identifier'); + } + + if (result.query[name] === '') { + throw new Error('Query parameter ' + name + ' is an incomplete value pair'); + } + } + } + + if (result.auth) { + let parts = result.auth.split(':'); + if (url.indexOf(result.auth) !== -1 && parts.length > 2) { + throw new Error('Username with password containing an unescaped colon'); + } + + if (url.indexOf(result.auth) !== -1 && result.auth.indexOf('@') !== -1) { + throw new Error('Username containing an unescaped at-sign'); + } + } + + // Remove query + let clean = url.split('?').shift(); + + // Extract the list of hosts + let strings = clean.split(','); + let hosts = []; + + for (let i = 0; i < strings.length; i++) { + let hostString = strings[i]; + + if (hostString.indexOf('mongodb') !== -1) { + if (hostString.indexOf('@') !== -1) { + hosts.push(hostString.split('@').pop()); + } else { + hosts.push(hostString.substr('mongodb://'.length)); + } + } else if (hostString.indexOf('/') !== -1) { + hosts.push(hostString.split('/').shift()); + } else if (hostString.indexOf('/') === -1) { + hosts.push(hostString.trim()); + } + } + + for (let i = 0; i < hosts.length; i++) { + let r = parser.parse(f('mongodb://%s', hosts[i].trim())); + if (r.path && r.path.indexOf('.sock') !== -1) continue; + if (r.path && r.path.indexOf(':') !== -1) { + // Not connecting to a socket so check for an extra slash in the hostname. + // Using String#split as perf is better than match. + if (r.path.split('/').length > 1 && r.path.indexOf('::') === -1) { + throw new Error('Slash in host identifier'); + } else { + throw new Error('Double colon in host identifier'); + } + } + } + + // If we have a ? mark cut the query elements off + if (url.indexOf('?') !== -1) { + query_string_part = url.substr(url.indexOf('?') + 1); + connection_part = url.substring('mongodb://'.length, url.indexOf('?')); + } else { + connection_part = url.substring('mongodb://'.length); + } + + // Check if we have auth params + if (connection_part.indexOf('@') !== -1) { + auth_part = connection_part.split('@')[0]; + connection_part = connection_part.split('@')[1]; + } + + // Check there is not more than one unescaped slash + if (connection_part.split('/').length > 2) { + throw new Error( + "Unsupported host '" + + connection_part.split('?')[0] + + "', hosts must be URL encoded and contain at most one unencoded slash" + ); + } + + // Check if the connection string has a db + if (connection_part.indexOf('.sock') !== -1) { + if (connection_part.indexOf('.sock/') !== -1) { + dbName = connection_part.split('.sock/')[1]; + // Check if multiple database names provided, or just an illegal trailing backslash + if (dbName.indexOf('/') !== -1) { + if (dbName.split('/').length === 2 && dbName.split('/')[1].length === 0) { + throw new Error('Illegal trailing backslash after database name'); + } + throw new Error('More than 1 database name in URL'); + } + connection_part = connection_part.split( + '/', + connection_part.indexOf('.sock') + '.sock'.length + ); + } + } else if (connection_part.indexOf('/') !== -1) { + // Check if multiple database names provided, or just an illegal trailing backslash + if (connection_part.split('/').length > 2) { + if (connection_part.split('/')[2].length === 0) { + throw new Error('Illegal trailing backslash after database name'); + } + throw new Error('More than 1 database name in URL'); + } + dbName = connection_part.split('/')[1]; + connection_part = connection_part.split('/')[0]; + } + + // URI decode the host information + connection_part = decodeURIComponent(connection_part); + + // Result object + let object = {}; + + // Pick apart the authentication part of the string + let authPart = auth_part || ''; + let auth = authPart.split(':', 2); + + // Decode the authentication URI components and verify integrity + let user = decodeURIComponent(auth[0]); + if (auth[0] !== encodeURIComponent(user)) { + throw new Error('Username contains an illegal unescaped character'); + } + auth[0] = user; + + if (auth[1]) { + let pass = decodeURIComponent(auth[1]); + if (auth[1] !== encodeURIComponent(pass)) { + throw new Error('Password contains an illegal unescaped character'); + } + auth[1] = pass; + } + + // Add auth to final object if we have 2 elements + if (auth.length === 2) object.auth = { user: auth[0], password: auth[1] }; + // if user provided auth options, use that + if (options && options.auth != null) object.auth = options.auth; + + // Variables used for temporary storage + let hostPart; + let urlOptions; + let servers; + let compression; + let serverOptions = { socketOptions: {} }; + let dbOptions = { read_preference_tags: [] }; + let replSetServersOptions = { socketOptions: {} }; + let mongosOptions = { socketOptions: {} }; + // Add server options to final object + object.server_options = serverOptions; + object.db_options = dbOptions; + object.rs_options = replSetServersOptions; + object.mongos_options = mongosOptions; + + // Let's check if we are using a domain socket + if (url.match(/\.sock/)) { + // Split out the socket part + let domainSocket = url.substring( + url.indexOf('mongodb://') + 'mongodb://'.length, + url.lastIndexOf('.sock') + '.sock'.length + ); + // Clean out any auth stuff if any + if (domainSocket.indexOf('@') !== -1) domainSocket = domainSocket.split('@')[1]; + domainSocket = decodeURIComponent(domainSocket); + servers = [{ domain_socket: domainSocket }]; + } else { + // Split up the db + hostPart = connection_part; + // Deduplicate servers + let deduplicatedServers = {}; + + // Parse all server results + servers = hostPart + .split(',') + .map(function(h) { + let _host, _port, ipv6match; + //check if it matches [IPv6]:port, where the port number is optional + if ((ipv6match = /\[([^\]]+)\](?::(.+))?/.exec(h))) { + _host = ipv6match[1]; + _port = parseInt(ipv6match[2], 10) || 27017; + } else { + //otherwise assume it's IPv4, or plain hostname + let hostPort = h.split(':', 2); + _host = hostPort[0] || 'localhost'; + _port = hostPort[1] != null ? parseInt(hostPort[1], 10) : 27017; + // Check for localhost?safe=true style case + if (_host.indexOf('?') !== -1) _host = _host.split(/\?/)[0]; + } + + // No entry returned for duplicate server + if (deduplicatedServers[_host + '_' + _port]) return null; + deduplicatedServers[_host + '_' + _port] = 1; + + // Return the mapped object + return { host: _host, port: _port }; + }) + .filter(function(x) { + return x != null; + }); + } + + // Get the db name + object.dbName = dbName || 'admin'; + // Split up all the options + urlOptions = (query_string_part || '').split(/[&;]/); + // Ugh, we have to figure out which options go to which constructor manually. + urlOptions.forEach(function(opt) { + if (!opt) return; + var splitOpt = opt.split('='), + name = splitOpt[0], + value = splitOpt[1]; + + // Options implementations + switch (name) { + case 'slaveOk': + case 'slave_ok': + serverOptions.slave_ok = value === 'true'; + dbOptions.slaveOk = value === 'true'; + break; + case 'maxPoolSize': + case 'poolSize': + serverOptions.poolSize = parseInt(value, 10); + replSetServersOptions.poolSize = parseInt(value, 10); + break; + case 'appname': + object.appname = decodeURIComponent(value); + break; + case 'autoReconnect': + case 'auto_reconnect': + serverOptions.auto_reconnect = value === 'true'; + break; + case 'ssl': + if (value === 'prefer') { + serverOptions.ssl = value; + replSetServersOptions.ssl = value; + mongosOptions.ssl = value; + break; + } + serverOptions.ssl = value === 'true'; + replSetServersOptions.ssl = value === 'true'; + mongosOptions.ssl = value === 'true'; + break; + case 'sslValidate': + serverOptions.sslValidate = value === 'true'; + replSetServersOptions.sslValidate = value === 'true'; + mongosOptions.sslValidate = value === 'true'; + break; + case 'replicaSet': + case 'rs_name': + replSetServersOptions.rs_name = value; + break; + case 'reconnectWait': + replSetServersOptions.reconnectWait = parseInt(value, 10); + break; + case 'retries': + replSetServersOptions.retries = parseInt(value, 10); + break; + case 'readSecondary': + case 'read_secondary': + replSetServersOptions.read_secondary = value === 'true'; + break; + case 'fsync': + dbOptions.fsync = value === 'true'; + break; + case 'journal': + dbOptions.j = value === 'true'; + break; + case 'safe': + dbOptions.safe = value === 'true'; + break; + case 'nativeParser': + case 'native_parser': + dbOptions.native_parser = value === 'true'; + break; + case 'readConcernLevel': + dbOptions.readConcern = new ReadConcern(value); + break; + case 'connectTimeoutMS': + serverOptions.socketOptions.connectTimeoutMS = parseInt(value, 10); + replSetServersOptions.socketOptions.connectTimeoutMS = parseInt(value, 10); + mongosOptions.socketOptions.connectTimeoutMS = parseInt(value, 10); + break; + case 'socketTimeoutMS': + serverOptions.socketOptions.socketTimeoutMS = parseInt(value, 10); + replSetServersOptions.socketOptions.socketTimeoutMS = parseInt(value, 10); + mongosOptions.socketOptions.socketTimeoutMS = parseInt(value, 10); + break; + case 'w': + dbOptions.w = parseInt(value, 10); + if (isNaN(dbOptions.w)) dbOptions.w = value; + break; + case 'authSource': + dbOptions.authSource = value; + break; + case 'gssapiServiceName': + dbOptions.gssapiServiceName = value; + break; + case 'authMechanism': + if (value === 'GSSAPI') { + // If no password provided decode only the principal + if (object.auth == null) { + let urlDecodeAuthPart = decodeURIComponent(authPart); + if (urlDecodeAuthPart.indexOf('@') === -1) + throw new Error('GSSAPI requires a provided principal'); + object.auth = { user: urlDecodeAuthPart, password: null }; + } else { + object.auth.user = decodeURIComponent(object.auth.user); + } + } else if (value === 'MONGODB-X509') { + object.auth = { user: decodeURIComponent(authPart) }; + } + + // Only support GSSAPI or MONGODB-CR for now + if ( + value !== 'GSSAPI' && + value !== 'MONGODB-X509' && + value !== 'MONGODB-CR' && + value !== 'DEFAULT' && + value !== 'SCRAM-SHA-1' && + value !== 'SCRAM-SHA-256' && + value !== 'PLAIN' + ) + throw new Error( + 'Only DEFAULT, GSSAPI, PLAIN, MONGODB-X509, or SCRAM-SHA-1 is supported by authMechanism' + ); + + // Authentication mechanism + dbOptions.authMechanism = value; + break; + case 'authMechanismProperties': + { + // Split up into key, value pairs + let values = value.split(','); + let o = {}; + // For each value split into key, value + values.forEach(function(x) { + let v = x.split(':'); + o[v[0]] = v[1]; + }); + + // Set all authMechanismProperties + dbOptions.authMechanismProperties = o; + // Set the service name value + if (typeof o.SERVICE_NAME === 'string') dbOptions.gssapiServiceName = o.SERVICE_NAME; + if (typeof o.SERVICE_REALM === 'string') dbOptions.gssapiServiceRealm = o.SERVICE_REALM; + if (typeof o.CANONICALIZE_HOST_NAME === 'string') + dbOptions.gssapiCanonicalizeHostName = + o.CANONICALIZE_HOST_NAME === 'true' ? true : false; + } + break; + case 'wtimeoutMS': + dbOptions.wtimeout = parseInt(value, 10); + break; + case 'readPreference': + if (!ReadPreference.isValid(value)) + throw new Error( + 'readPreference must be either primary/primaryPreferred/secondary/secondaryPreferred/nearest' + ); + dbOptions.readPreference = value; + break; + case 'maxStalenessSeconds': + dbOptions.maxStalenessSeconds = parseInt(value, 10); + break; + case 'readPreferenceTags': + { + // Decode the value + value = decodeURIComponent(value); + // Contains the tag object + let tagObject = {}; + if (value == null || value === '') { + dbOptions.read_preference_tags.push(tagObject); + break; + } + + // Split up the tags + let tags = value.split(/,/); + for (let i = 0; i < tags.length; i++) { + let parts = tags[i].trim().split(/:/); + tagObject[parts[0]] = parts[1]; + } + + // Set the preferences tags + dbOptions.read_preference_tags.push(tagObject); + } + break; + case 'compressors': + { + compression = serverOptions.compression || {}; + let compressors = value.split(','); + if ( + !compressors.every(function(compressor) { + return compressor === 'snappy' || compressor === 'zlib'; + }) + ) { + throw new Error('Compressors must be at least one of snappy or zlib'); + } + + compression.compressors = compressors; + serverOptions.compression = compression; + } + break; + case 'zlibCompressionLevel': + { + compression = serverOptions.compression || {}; + let zlibCompressionLevel = parseInt(value, 10); + if (zlibCompressionLevel < -1 || zlibCompressionLevel > 9) { + throw new Error('zlibCompressionLevel must be an integer between -1 and 9'); + } + + compression.zlibCompressionLevel = zlibCompressionLevel; + serverOptions.compression = compression; + } + break; + case 'retryWrites': + dbOptions.retryWrites = value === 'true'; + break; + case 'minSize': + dbOptions.minSize = parseInt(value, 10); + break; + default: + { + let logger = Logger('URL Parser'); + logger.warn(`${name} is not supported as a connection string option`); + } + break; + } + }); + + // No tags: should be null (not []) + if (dbOptions.read_preference_tags.length === 0) { + dbOptions.read_preference_tags = null; + } + + // Validate if there are an invalid write concern combinations + if ( + (dbOptions.w === -1 || dbOptions.w === 0) && + (dbOptions.journal === true || dbOptions.fsync === true || dbOptions.safe === true) + ) + throw new Error('w set to -1 or 0 cannot be combined with safe/w/journal/fsync'); + + // If no read preference set it to primary + if (!dbOptions.readPreference) { + dbOptions.readPreference = 'primary'; + } + + // make sure that user-provided options are applied with priority + dbOptions = Object.assign(dbOptions, options); + + // Add servers to result + object.servers = servers; + + // Returned parsed object + return object; +} diff --git a/scripts/node_modules/mongodb/lib/utils.js b/scripts/node_modules/mongodb/lib/utils.js new file mode 100644 index 00000000..98dee668 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/utils.js @@ -0,0 +1,716 @@ +'use strict'; + +const MongoError = require('./core/error').MongoError; +const ReadPreference = require('./core/topologies/read_preference'); +const WriteConcern = require('./write_concern'); + +var shallowClone = function(obj) { + var copy = {}; + for (var name in obj) copy[name] = obj[name]; + return copy; +}; + +// Figure out the read preference +var translateReadPreference = function(options) { + var r = null; + if (options.readPreference) { + r = options.readPreference; + } else { + return options; + } + + if (typeof r === 'string') { + options.readPreference = new ReadPreference(r); + } else if (r && !(r instanceof ReadPreference) && typeof r === 'object') { + const mode = r.mode || r.preference; + if (mode && typeof mode === 'string') { + options.readPreference = new ReadPreference(mode, r.tags, { + maxStalenessSeconds: r.maxStalenessSeconds + }); + } + } else if (!(r instanceof ReadPreference)) { + throw new TypeError('Invalid read preference: ' + r); + } + + return options; +}; + +// Set simple property +var getSingleProperty = function(obj, name, value) { + Object.defineProperty(obj, name, { + enumerable: true, + get: function() { + return value; + } + }); +}; + +var formatSortValue = (exports.formatSortValue = function(sortDirection) { + var value = ('' + sortDirection).toLowerCase(); + + switch (value) { + case 'ascending': + case 'asc': + case '1': + return 1; + case 'descending': + case 'desc': + case '-1': + return -1; + default: + throw new Error( + 'Illegal sort clause, must be of the form ' + + "[['field1', '(ascending|descending)'], " + + "['field2', '(ascending|descending)']]" + ); + } +}); + +var formattedOrderClause = (exports.formattedOrderClause = function(sortValue) { + var orderBy = {}; + if (sortValue == null) return null; + if (Array.isArray(sortValue)) { + if (sortValue.length === 0) { + return null; + } + + for (var i = 0; i < sortValue.length; i++) { + if (sortValue[i].constructor === String) { + orderBy[sortValue[i]] = 1; + } else { + orderBy[sortValue[i][0]] = formatSortValue(sortValue[i][1]); + } + } + } else if (sortValue != null && typeof sortValue === 'object') { + orderBy = sortValue; + } else if (typeof sortValue === 'string') { + orderBy[sortValue] = 1; + } else { + throw new Error( + 'Illegal sort clause, must be of the form ' + + "[['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]" + ); + } + + return orderBy; +}); + +var checkCollectionName = function checkCollectionName(collectionName) { + if ('string' !== typeof collectionName) { + throw new MongoError('collection name must be a String'); + } + + if (!collectionName || collectionName.indexOf('..') !== -1) { + throw new MongoError('collection names cannot be empty'); + } + + if ( + collectionName.indexOf('$') !== -1 && + collectionName.match(/((^\$cmd)|(oplog\.\$main))/) == null + ) { + throw new MongoError("collection names must not contain '$'"); + } + + if (collectionName.match(/^\.|\.$/) != null) { + throw new MongoError("collection names must not start or end with '.'"); + } + + // Validate that we are not passing 0x00 in the collection name + if (collectionName.indexOf('\x00') !== -1) { + throw new MongoError('collection names cannot contain a null character'); + } +}; + +var handleCallback = function(callback, err, value1, value2) { + try { + if (callback == null) return; + + if (callback) { + return value2 ? callback(err, value1, value2) : callback(err, value1); + } + } catch (err) { + process.nextTick(function() { + throw err; + }); + return false; + } + + return true; +}; + +/** + * Wrap a Mongo error document in an Error instance + * @ignore + * @api private + */ +var toError = function(error) { + if (error instanceof Error) return error; + + var msg = error.err || error.errmsg || error.errMessage || error; + var e = MongoError.create({ message: msg, driver: true }); + + // Get all object keys + var keys = typeof error === 'object' ? Object.keys(error) : []; + + for (var i = 0; i < keys.length; i++) { + try { + e[keys[i]] = error[keys[i]]; + } catch (err) { + // continue + } + } + + return e; +}; + +/** + * @ignore + */ +var normalizeHintField = function normalizeHintField(hint) { + var finalHint = null; + + if (typeof hint === 'string') { + finalHint = hint; + } else if (Array.isArray(hint)) { + finalHint = {}; + + hint.forEach(function(param) { + finalHint[param] = 1; + }); + } else if (hint != null && typeof hint === 'object') { + finalHint = {}; + for (var name in hint) { + finalHint[name] = hint[name]; + } + } + + return finalHint; +}; + +/** + * Create index name based on field spec + * + * @ignore + * @api private + */ +var parseIndexOptions = function(fieldOrSpec) { + var fieldHash = {}; + var indexes = []; + var keys; + + // Get all the fields accordingly + if ('string' === typeof fieldOrSpec) { + // 'type' + indexes.push(fieldOrSpec + '_' + 1); + fieldHash[fieldOrSpec] = 1; + } else if (Array.isArray(fieldOrSpec)) { + fieldOrSpec.forEach(function(f) { + if ('string' === typeof f) { + // [{location:'2d'}, 'type'] + indexes.push(f + '_' + 1); + fieldHash[f] = 1; + } else if (Array.isArray(f)) { + // [['location', '2d'],['type', 1]] + indexes.push(f[0] + '_' + (f[1] || 1)); + fieldHash[f[0]] = f[1] || 1; + } else if (isObject(f)) { + // [{location:'2d'}, {type:1}] + keys = Object.keys(f); + keys.forEach(function(k) { + indexes.push(k + '_' + f[k]); + fieldHash[k] = f[k]; + }); + } else { + // undefined (ignore) + } + }); + } else if (isObject(fieldOrSpec)) { + // {location:'2d', type:1} + keys = Object.keys(fieldOrSpec); + keys.forEach(function(key) { + indexes.push(key + '_' + fieldOrSpec[key]); + fieldHash[key] = fieldOrSpec[key]; + }); + } + + return { + name: indexes.join('_'), + keys: keys, + fieldHash: fieldHash + }; +}; + +var isObject = (exports.isObject = function(arg) { + return '[object Object]' === Object.prototype.toString.call(arg); +}); + +var debugOptions = function(debugFields, options) { + var finaloptions = {}; + debugFields.forEach(function(n) { + finaloptions[n] = options[n]; + }); + + return finaloptions; +}; + +var decorateCommand = function(command, options, exclude) { + for (var name in options) { + if (exclude.indexOf(name) === -1) command[name] = options[name]; + } + + return command; +}; + +var mergeOptions = function(target, source) { + for (var name in source) { + target[name] = source[name]; + } + + return target; +}; + +// Merge options with translation +var translateOptions = function(target, source) { + var translations = { + // SSL translation options + sslCA: 'ca', + sslCRL: 'crl', + sslValidate: 'rejectUnauthorized', + sslKey: 'key', + sslCert: 'cert', + sslPass: 'passphrase', + // SocketTimeout translation options + socketTimeoutMS: 'socketTimeout', + connectTimeoutMS: 'connectionTimeout', + // Replicaset options + replicaSet: 'setName', + rs_name: 'setName', + secondaryAcceptableLatencyMS: 'acceptableLatency', + connectWithNoPrimary: 'secondaryOnlyConnectionAllowed', + // Mongos options + acceptableLatencyMS: 'localThresholdMS' + }; + + for (var name in source) { + if (translations[name]) { + target[translations[name]] = source[name]; + } else { + target[name] = source[name]; + } + } + + return target; +}; + +var filterOptions = function(options, names) { + var filterOptions = {}; + + for (var name in options) { + if (names.indexOf(name) !== -1) filterOptions[name] = options[name]; + } + + // Filtered options + return filterOptions; +}; + +// Write concern keys +var writeConcernKeys = ['w', 'j', 'wtimeout', 'fsync']; + +// Merge the write concern options +var mergeOptionsAndWriteConcern = function(targetOptions, sourceOptions, keys, mergeWriteConcern) { + // Mix in any allowed options + for (var i = 0; i < keys.length; i++) { + if (!targetOptions[keys[i]] && sourceOptions[keys[i]] !== undefined) { + targetOptions[keys[i]] = sourceOptions[keys[i]]; + } + } + + // No merging of write concern + if (!mergeWriteConcern) return targetOptions; + + // Found no write Concern options + var found = false; + for (i = 0; i < writeConcernKeys.length; i++) { + if (targetOptions[writeConcernKeys[i]]) { + found = true; + break; + } + } + + if (!found) { + for (i = 0; i < writeConcernKeys.length; i++) { + if (sourceOptions[writeConcernKeys[i]]) { + targetOptions[writeConcernKeys[i]] = sourceOptions[writeConcernKeys[i]]; + } + } + } + + return targetOptions; +}; + +/** + * Executes the given operation with provided arguments. + * + * This method reduces large amounts of duplication in the entire codebase by providing + * a single point for determining whether callbacks or promises should be used. Additionally + * it allows for a single point of entry to provide features such as implicit sessions, which + * are required by the Driver Sessions specification in the event that a ClientSession is + * not provided + * + * @param {object} topology The topology to execute this operation on + * @param {function} operation The operation to execute + * @param {array} args Arguments to apply the provided operation + * @param {object} [options] Options that modify the behavior of the method + */ +const executeLegacyOperation = (topology, operation, args, options) => { + if (topology == null) { + throw new TypeError('This method requires a valid topology instance'); + } + + if (!Array.isArray(args)) { + throw new TypeError('This method requires an array of arguments to apply'); + } + + options = options || {}; + const Promise = topology.s.promiseLibrary; + let callback = args[args.length - 1]; + + // The driver sessions spec mandates that we implicitly create sessions for operations + // that are not explicitly provided with a session. + let session, opOptions, owner; + if (!options.skipSessions && topology.hasSessionSupport()) { + opOptions = args[args.length - 2]; + if (opOptions == null || opOptions.session == null) { + owner = Symbol(); + session = topology.startSession({ owner }); + const optionsIndex = args.length - 2; + args[optionsIndex] = Object.assign({}, args[optionsIndex], { session: session }); + } else if (opOptions.session && opOptions.session.hasEnded) { + throw new MongoError('Use of expired sessions is not permitted'); + } + } + + const makeExecuteCallback = (resolve, reject) => + function executeCallback(err, result) { + if (session && session.owner === owner && !options.returnsCursor) { + session.endSession(() => { + delete opOptions.session; + if (err) return reject(err); + resolve(result); + }); + } else { + if (err) return reject(err); + resolve(result); + } + }; + + // Execute using callback + if (typeof callback === 'function') { + callback = args.pop(); + const handler = makeExecuteCallback( + result => callback(null, result), + err => callback(err, null) + ); + args.push(handler); + + try { + return operation.apply(null, args); + } catch (e) { + handler(e); + throw e; + } + } + + // Return a Promise + if (args[args.length - 1] != null) { + throw new TypeError('final argument to `executeLegacyOperation` must be a callback'); + } + + return new Promise(function(resolve, reject) { + const handler = makeExecuteCallback(resolve, reject); + args[args.length - 1] = handler; + + try { + return operation.apply(null, args); + } catch (e) { + handler(e); + } + }); +}; + +/** + * Applies retryWrites: true to a command if retryWrites is set on the command's database. + * + * @param {object} target The target command to which we will apply retryWrites. + * @param {object} db The database from which we can inherit a retryWrites value. + */ +function applyRetryableWrites(target, db) { + if (db && db.s.options.retryWrites) { + target.retryWrites = true; + } + + return target; +} + +/** + * Applies a write concern to a command based on well defined inheritance rules, optionally + * detecting support for the write concern in the first place. + * + * @param {Object} target the target command we will be applying the write concern to + * @param {Object} sources sources where we can inherit default write concerns from + * @param {Object} [options] optional settings passed into a command for write concern overrides + * @returns {Object} the (now) decorated target + */ +function applyWriteConcern(target, sources, options) { + options = options || {}; + const db = sources.db; + const coll = sources.collection; + + if (options.session && options.session.inTransaction()) { + // writeConcern is not allowed within a multi-statement transaction + if (target.writeConcern) { + delete target.writeConcern; + } + + return target; + } + + const writeConcern = WriteConcern.fromOptions(options); + if (writeConcern) { + return Object.assign(target, { writeConcern }); + } + + if (coll && coll.writeConcern) { + return Object.assign(target, { writeConcern: Object.assign({}, coll.writeConcern) }); + } + + if (db && db.writeConcern) { + return Object.assign(target, { writeConcern: Object.assign({}, db.writeConcern) }); + } + + return target; +} + +/** + * Resolves a read preference based on well-defined inheritance rules. This method will not only + * determine the read preference (if there is one), but will also ensure the returned value is a + * properly constructed instance of `ReadPreference`. + * + * @param {Collection|Db|MongoClient} parent The parent of the operation on which to determine the read + * preference, used for determining the inherited read preference. + * @param {Object} options The options passed into the method, potentially containing a read preference + * @returns {(ReadPreference|null)} The resolved read preference + */ +function resolveReadPreference(parent, options) { + options = options || {}; + const session = options.session; + + const inheritedReadPreference = parent.readPreference; + + let readPreference; + if (options.readPreference) { + readPreference = ReadPreference.fromOptions(options); + } else if (session && session.inTransaction() && session.transaction.options.readPreference) { + // The transaction’s read preference MUST override all other user configurable read preferences. + readPreference = session.transaction.options.readPreference; + } else if (inheritedReadPreference != null) { + readPreference = inheritedReadPreference; + } else { + throw new Error('No readPreference was provided or inherited.'); + } + + return typeof readPreference === 'string' ? new ReadPreference(readPreference) : readPreference; +} + +/** + * Checks if a given value is a Promise + * + * @param {*} maybePromise + * @return true if the provided value is a Promise + */ +function isPromiseLike(maybePromise) { + return maybePromise && typeof maybePromise.then === 'function'; +} + +/** + * Applies collation to a given command. + * + * @param {object} [command] the command on which to apply collation + * @param {(Cursor|Collection)} [target] target of command + * @param {object} [options] options containing collation settings + */ +function decorateWithCollation(command, target, options) { + const topology = (target.s && target.s.topology) || target.topology; + + if (!topology) { + throw new TypeError('parameter "target" is missing a topology'); + } + + const capabilities = topology.capabilities(); + if (options.collation && typeof options.collation === 'object') { + if (capabilities && capabilities.commandsTakeCollation) { + command.collation = options.collation; + } else { + throw new MongoError(`Current topology does not support collation`); + } + } +} + +/** + * Applies a read concern to a given command. + * + * @param {object} command the command on which to apply the read concern + * @param {Collection} coll the parent collection of the operation calling this method + */ +function decorateWithReadConcern(command, coll, options) { + if (options && options.session && options.session.inTransaction()) { + return; + } + let readConcern = Object.assign({}, command.readConcern || {}); + if (coll.s.readConcern) { + Object.assign(readConcern, coll.s.readConcern); + } + + if (Object.keys(readConcern).length > 0) { + Object.assign(command, { readConcern: readConcern }); + } +} + +const emitProcessWarning = msg => process.emitWarning(msg, 'DeprecationWarning'); +const emitConsoleWarning = msg => console.error(msg); +const emitDeprecationWarning = process.emitWarning ? emitProcessWarning : emitConsoleWarning; + +/** + * Default message handler for generating deprecation warnings. + * + * @param {string} name function name + * @param {string} option option name + * @return {string} warning message + * @ignore + * @api private + */ +function defaultMsgHandler(name, option) { + return `${name} option [${option}] is deprecated and will be removed in a later version.`; +} + +/** + * Deprecates a given function's options. + * + * @param {object} config configuration for deprecation + * @param {string} config.name function name + * @param {Array} config.deprecatedOptions options to deprecate + * @param {number} config.optionsIndex index of options object in function arguments array + * @param {function} [config.msgHandler] optional custom message handler to generate warnings + * @param {function} fn the target function of deprecation + * @return {function} modified function that warns once per deprecated option, and executes original function + * @ignore + * @api private + */ +function deprecateOptions(config, fn) { + if (process.noDeprecation === true) { + return fn; + } + + const msgHandler = config.msgHandler ? config.msgHandler : defaultMsgHandler; + + const optionsWarned = new Set(); + function deprecated() { + const options = arguments[config.optionsIndex]; + + // ensure options is a valid, non-empty object, otherwise short-circuit + if (!isObject(options) || Object.keys(options).length === 0) { + return fn.apply(this, arguments); + } + + config.deprecatedOptions.forEach(deprecatedOption => { + if (options.hasOwnProperty(deprecatedOption) && !optionsWarned.has(deprecatedOption)) { + optionsWarned.add(deprecatedOption); + const msg = msgHandler(config.name, deprecatedOption); + emitDeprecationWarning(msg); + if (this && this.getLogger) { + const logger = this.getLogger(); + if (logger) { + logger.warn(msg); + } + } + } + }); + + return fn.apply(this, arguments); + } + + // These lines copied from https://github.com/nodejs/node/blob/25e5ae41688676a5fd29b2e2e7602168eee4ceb5/lib/internal/util.js#L73-L80 + // The wrapper will keep the same prototype as fn to maintain prototype chain + Object.setPrototypeOf(deprecated, fn); + if (fn.prototype) { + // Setting this (rather than using Object.setPrototype, as above) ensures + // that calling the unwrapped constructor gives an instanceof the wrapped + // constructor. + deprecated.prototype = fn.prototype; + } + + return deprecated; +} + +const SUPPORTS = {}; +// Test asyncIterator support +try { + require('./async/async_iterator'); + SUPPORTS.ASYNC_ITERATOR = true; +} catch (e) { + SUPPORTS.ASYNC_ITERATOR = false; +} + +class MongoDBNamespace { + constructor(db, collection) { + this.db = db; + this.collection = collection; + } + + toString() { + return this.collection ? `${this.db}.${this.collection}` : this.db; + } + + withCollection(collection) { + return new MongoDBNamespace(this.db, collection); + } + + static fromString(namespace) { + if (!namespace) { + throw new Error(`Cannot parse namespace from "${namespace}"`); + } + + const index = namespace.indexOf('.'); + return new MongoDBNamespace(namespace.substring(0, index), namespace.substring(index + 1)); + } +} + +module.exports = { + filterOptions, + mergeOptions, + translateOptions, + shallowClone, + getSingleProperty, + checkCollectionName, + toError, + formattedOrderClause, + parseIndexOptions, + normalizeHintField, + handleCallback, + decorateCommand, + isObject, + debugOptions, + MAX_JS_INT: Number.MAX_SAFE_INTEGER + 1, + mergeOptionsAndWriteConcern, + translateReadPreference, + executeLegacyOperation, + applyRetryableWrites, + applyWriteConcern, + isPromiseLike, + decorateWithCollation, + decorateWithReadConcern, + deprecateOptions, + SUPPORTS, + MongoDBNamespace, + resolveReadPreference +}; diff --git a/scripts/node_modules/mongodb/lib/write_concern.js b/scripts/node_modules/mongodb/lib/write_concern.js new file mode 100644 index 00000000..79b0f092 --- /dev/null +++ b/scripts/node_modules/mongodb/lib/write_concern.js @@ -0,0 +1,66 @@ +'use strict'; + +/** + * The **WriteConcern** class is a class that represents a MongoDB WriteConcern. + * @class + * @property {(number|string)} w The write concern + * @property {number} wtimeout The write concern timeout + * @property {boolean} j The journal write concern + * @property {boolean} fsync The file sync write concern + * @see https://docs.mongodb.com/manual/reference/write-concern/index.html + */ +class WriteConcern { + /** + * Constructs a WriteConcern from the write concern properties. + * @param {(number|string)} [w] The write concern + * @param {number} [wtimeout] The write concern timeout + * @param {boolean} [j] The journal write concern + * @param {boolean} [fsync] The file sync write concern + */ + constructor(w, wtimeout, j, fsync) { + if (w != null) { + this.w = w; + } + if (wtimeout != null) { + this.wtimeout = wtimeout; + } + if (j != null) { + this.j = j; + } + if (fsync != null) { + this.fsync = fsync; + } + } + + /** + * Construct a WriteConcern given an options object. + * + * @param {object} options The options object from which to extract the write concern. + * @return {WriteConcern} + */ + static fromOptions(options) { + if ( + options == null || + (options.writeConcern == null && + options.w == null && + options.wtimeout == null && + options.j == null && + options.fsync == null) + ) { + return; + } + + if (options.writeConcern) { + return new WriteConcern( + options.writeConcern.w, + options.writeConcern.wtimeout, + options.writeConcern.j, + options.writeConcern.fsync + ); + } + + return new WriteConcern(options.w, options.wtimeout, options.j, options.fsync); + } +} + +module.exports = WriteConcern; diff --git a/scripts/node_modules/mongodb/package.json b/scripts/node_modules/mongodb/package.json new file mode 100644 index 00000000..ad87330b --- /dev/null +++ b/scripts/node_modules/mongodb/package.json @@ -0,0 +1,104 @@ +{ + "_from": "mongodb", + "_id": "mongodb@3.3.3", + "_inBundle": false, + "_integrity": "sha512-MdRnoOjstmnrKJsK8PY0PjP6fyF/SBS4R8coxmhsfEU7tQ46/J6j+aSHF2n4c2/H8B+Hc/Klbfp8vggZfI0mmA==", + "_location": "/mongodb", + "_phantomChildren": {}, + "_requested": { + "type": "tag", + "registry": true, + "raw": "mongodb", + "name": "mongodb", + "escapedName": "mongodb", + "rawSpec": "", + "saveSpec": null, + "fetchSpec": "latest" + }, + "_requiredBy": [ + "#USER", + "/" + ], + "_resolved": "https://registry.npmjs.org/mongodb/-/mongodb-3.3.3.tgz", + "_shasum": "509cad2225a1c56c65a331ed73a0d5d4ed5cbe67", + "_spec": "mongodb", + "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/2.5", + "bugs": { + "url": "https://github.com/mongodb/node-mongodb-native/issues" + }, + "bundleDependencies": false, + "dependencies": { + "bson": "^1.1.1", + "require_optional": "^1.0.1", + "safe-buffer": "^5.1.2", + "saslprep": "^1.0.0" + }, + "deprecated": false, + "description": "The official MongoDB driver for Node.js", + "devDependencies": { + "bluebird": "3.5.0", + "chai": "^4.1.1", + "chai-subset": "^1.6.0", + "chalk": "^2.4.2", + "co": "4.6.0", + "coveralls": "^2.11.6", + "eslint": "^4.5.0", + "eslint-plugin-prettier": "^2.2.0", + "istanbul": "^0.4.5", + "jsdoc": "3.5.5", + "lodash.camelcase": "^4.3.0", + "mocha": "5.2.0", + "mocha-sinon": "^2.1.0", + "mongodb-extjson": "^2.1.1", + "mongodb-mock-server": "^1.0.1", + "prettier": "~1.12.0", + "semver": "^5.5.0", + "sinon": "^4.3.0", + "sinon-chai": "^3.2.0", + "snappy": "^6.1.2", + "standard-version": "^4.4.0", + "worker-farm": "^1.5.0", + "wtfnode": "^0.8.0" + }, + "engines": { + "node": ">=4" + }, + "files": [ + "index.js", + "lib" + ], + "homepage": "https://github.com/mongodb/node-mongodb-native", + "keywords": [ + "mongodb", + "driver", + "official" + ], + "license": "Apache-2.0", + "main": "index.js", + "name": "mongodb", + "optionalDependencies": { + "saslprep": "^1.0.0" + }, + "peerOptionalDependencies": { + "kerberos": "^1.1.0", + "mongodb-client-encryption": "^1.0.0", + "mongodb-extjson": "^2.1.2", + "snappy": "^6.1.1", + "bson-ext": "^2.0.0" + }, + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/mongodb/node-mongodb-native.git" + }, + "scripts": { + "atlas": "node ./test/atlas_connectivity_tests.js", + "bench": "node test/driverBench/", + "coverage": "istanbul cover mongodb-test-runner -- -t 60000 test/core test/unit test/functional", + "format": "prettier --print-width 100 --tab-width 2 --single-quote --write 'test/**/*.js' 'lib/**/*.js'", + "generate-evergreen": "node .evergreen/generate_evergreen_tasks.js", + "lint": "eslint lib test", + "release": "standard-version -i HISTORY.md", + "test": "npm run lint && mocha --recursive test/functional test/unit test/core" + }, + "version": "3.3.3" +} diff --git a/scripts/node_modules/require_optional/.npmignore b/scripts/node_modules/require_optional/.npmignore new file mode 100644 index 00000000..e920c167 --- /dev/null +++ b/scripts/node_modules/require_optional/.npmignore @@ -0,0 +1,33 @@ +# Logs +logs +*.log +npm-debug.log* + +# Runtime data +pids +*.pid +*.seed + +# Directory for instrumented libs generated by jscoverage/JSCover +lib-cov + +# Coverage directory used by tools like istanbul +coverage + +# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) +.grunt + +# node-waf configuration +.lock-wscript + +# Compiled binary addons (http://nodejs.org/api/addons.html) +build/Release + +# Dependency directory +node_modules + +# Optional npm cache directory +.npm + +# Optional REPL history +.node_repl_history diff --git a/scripts/node_modules/require_optional/.travis.yml b/scripts/node_modules/require_optional/.travis.yml new file mode 100644 index 00000000..72903c34 --- /dev/null +++ b/scripts/node_modules/require_optional/.travis.yml @@ -0,0 +1,9 @@ +language: node_js +node_js: + - "0.10" + - "0.12" + - "4" + - "6" + - "7" + - "8" +sudo: false diff --git a/scripts/node_modules/require_optional/HISTORY.md b/scripts/node_modules/require_optional/HISTORY.md new file mode 100644 index 00000000..7bee02fc --- /dev/null +++ b/scripts/node_modules/require_optional/HISTORY.md @@ -0,0 +1,7 @@ +1.0.1 03-02-2016 +================ +* Fix dependency resolution issue when a component in peerOptionalDependencies is installed at the level of the module declaring in peerOptionalDependencies. + +1.0.0 03-02-2016 +================ +* Initial release allowing us to optionally resolve dependencies in the package.json file under the peerOptionalDependencies tag. \ No newline at end of file diff --git a/scripts/node_modules/require_optional/LICENSE b/scripts/node_modules/require_optional/LICENSE new file mode 100644 index 00000000..8dada3ed --- /dev/null +++ b/scripts/node_modules/require_optional/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/scripts/node_modules/require_optional/README.md b/scripts/node_modules/require_optional/README.md new file mode 100644 index 00000000..c0323f06 --- /dev/null +++ b/scripts/node_modules/require_optional/README.md @@ -0,0 +1,2 @@ +# require_optional +Work around the problem that we do not have a optionalPeerDependencies concept in node.js making it a hassle to optionally include native modules diff --git a/scripts/node_modules/require_optional/index.js b/scripts/node_modules/require_optional/index.js new file mode 100644 index 00000000..3710319f --- /dev/null +++ b/scripts/node_modules/require_optional/index.js @@ -0,0 +1,128 @@ +var path = require('path'), + fs = require('fs'), + f = require('util').format, + resolveFrom = require('resolve-from'), + semver = require('semver'); + +var exists = fs.existsSync || path.existsSync; + +// Find the location of a package.json file near or above the given location +var find_package_json = function(location) { + var found = false; + + while(!found) { + if (exists(location + '/package.json')) { + found = location; + } else if (location !== '/') { + location = path.dirname(location); + } else { + return false; + } + } + + return location; +} + +// Find the package.json object of the module closest up the module call tree that contains name in that module's peerOptionalDependencies +var find_package_json_with_name = function(name) { + // Walk up the module call tree until we find a module containing name in its peerOptionalDependencies + var currentModule = module; + var found = false; + while (currentModule) { + // Check currentModule has a package.json + location = currentModule.filename; + var location = find_package_json(location) + if (!location) { + currentModule = currentModule.parent; + continue; + } + + // Read the package.json file + var object = JSON.parse(fs.readFileSync(f('%s/package.json', location))); + // Is the name defined by interal file references + var parts = name.split(/\//); + + // Check whether this package.json contains peerOptionalDependencies containing the name we're searching for + if (!object.peerOptionalDependencies || (object.peerOptionalDependencies && !object.peerOptionalDependencies[parts[0]])) { + currentModule = currentModule.parent; + continue; + } + found = true; + break; + } + + // Check whether name has been found in currentModule's peerOptionalDependencies + if (!found) { + throw new Error(f('no optional dependency [%s] defined in peerOptionalDependencies in any package.json', parts[0])); + } + + return { + object: object, + parts: parts + } +} + +var require_optional = function(name, options) { + options = options || {}; + options.strict = typeof options.strict == 'boolean' ? options.strict : true; + + var res = find_package_json_with_name(name) + var object = res.object; + var parts = res.parts; + + // Unpack the expected version + var expectedVersions = object.peerOptionalDependencies[parts[0]]; + // The resolved package + var moduleEntry = undefined; + // Module file + var moduleEntryFile = name; + + try { + // Validate if it's possible to read the module + moduleEntry = require(moduleEntryFile); + } catch(err) { + // Attempt to resolve in top level package + try { + // Get the module entry file + moduleEntryFile = resolveFrom(process.cwd(), name); + if(moduleEntryFile == null) return undefined; + // Attempt to resolve the module + moduleEntry = require(moduleEntryFile); + } catch(err) { + if(err.code === 'MODULE_NOT_FOUND') return undefined; + } + } + + // Resolve the location of the module's package.json file + var location = find_package_json(require.resolve(moduleEntryFile)); + if(!location) { + throw new Error('package.json can not be located'); + } + + // Read the module file + var dependentOnModule = JSON.parse(fs.readFileSync(f('%s/package.json', location))); + // Get the version + var version = dependentOnModule.version; + // Validate if the found module satisfies the version id + if(semver.satisfies(version, expectedVersions) == false + && options.strict) { + var error = new Error(f('optional dependency [%s] found but version [%s] did not satisfy constraint [%s]', parts[0], version, expectedVersions)); + error.code = 'OPTIONAL_MODULE_NOT_FOUND'; + throw error; + } + + // Satifies the module requirement + return moduleEntry; +} + +require_optional.exists = function(name) { + try { + var m = require_optional(name); + if(m === undefined) return false; + return true; + } catch(err) { + return false; + } +} + +module.exports = require_optional; diff --git a/scripts/node_modules/require_optional/package.json b/scripts/node_modules/require_optional/package.json new file mode 100644 index 00000000..138364fe --- /dev/null +++ b/scripts/node_modules/require_optional/package.json @@ -0,0 +1,67 @@ +{ + "_from": "require_optional@^1.0.1", + "_id": "require_optional@1.0.1", + "_inBundle": false, + "_integrity": "sha512-qhM/y57enGWHAe3v/NcwML6a3/vfESLe/sGM2dII+gEO0BpKRUkWZow/tyloNqJyN6kXSl3RyyM8Ll5D/sJP8g==", + "_location": "/require_optional", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "require_optional@^1.0.1", + "name": "require_optional", + "escapedName": "require_optional", + "rawSpec": "^1.0.1", + "saveSpec": null, + "fetchSpec": "^1.0.1" + }, + "_requiredBy": [ + "/mongodb" + ], + "_resolved": "https://registry.npmjs.org/require_optional/-/require_optional-1.0.1.tgz", + "_shasum": "4cf35a4247f64ca3df8c2ef208cc494b1ca8fc2e", + "_spec": "require_optional@^1.0.1", + "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/node_modules/mongodb", + "author": { + "name": "Christian Kvalheim Amor" + }, + "bugs": { + "url": "https://github.com/christkv/require_optional/issues" + }, + "bundleDependencies": false, + "dependencies": { + "resolve-from": "^2.0.0", + "semver": "^5.1.0" + }, + "deprecated": false, + "description": "Allows you declare optionalPeerDependencies that can be satisfied by the top level module but ignored if they are not.", + "devDependencies": { + "bson": "0.4.21", + "co": "4.6.0", + "es6-promise": "^3.0.2", + "mocha": "^2.4.5" + }, + "homepage": "https://github.com/christkv/require_optional", + "keywords": [ + "optional", + "require", + "optionalPeerDependencies" + ], + "license": "Apache-2.0", + "main": "index.js", + "name": "require_optional", + "peerOptionalDependencies": { + "co": ">=5.6.0", + "es6-promise": "^3.0.2", + "es6-promise2": "^4.0.2", + "bson": "0.4.21" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/christkv/require_optional.git" + }, + "scripts": { + "test": "mocha" + }, + "version": "1.0.1" +} diff --git a/scripts/node_modules/require_optional/test/nestedTest/index.js b/scripts/node_modules/require_optional/test/nestedTest/index.js new file mode 100644 index 00000000..76de2ab4 --- /dev/null +++ b/scripts/node_modules/require_optional/test/nestedTest/index.js @@ -0,0 +1,8 @@ +var require_optional = require('../../') + +function findPackage(packageName) { + var pkg = require_optional(packageName); + return pkg; +} + +module.exports.findPackage = findPackage diff --git a/scripts/node_modules/require_optional/test/nestedTest/package.json b/scripts/node_modules/require_optional/test/nestedTest/package.json new file mode 100644 index 00000000..4c456a6b --- /dev/null +++ b/scripts/node_modules/require_optional/test/nestedTest/package.json @@ -0,0 +1,11 @@ +{ + "name": "nestedtest", + "version": "1.0.0", + "description": "A dummy package that facilitates testing that require_optional correctly walks up the module call stack", + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "author": "Sebastian Hallum Clarke", + "license": "ISC" +} diff --git a/scripts/node_modules/require_optional/test/require_optional_tests.js b/scripts/node_modules/require_optional/test/require_optional_tests.js new file mode 100644 index 00000000..c9cc2a36 --- /dev/null +++ b/scripts/node_modules/require_optional/test/require_optional_tests.js @@ -0,0 +1,59 @@ +var assert = require('assert'), + require_optional = require('../'), + nestedTest = require('./nestedTest'); + +describe('Require Optional', function() { + describe('top level require', function() { + it('should correctly require co library', function() { + var promise = require_optional('es6-promise'); + assert.ok(promise); + }); + + it('should fail to require es6-promise library', function() { + try { + require_optional('co'); + } catch(e) { + assert.equal('OPTIONAL_MODULE_NOT_FOUND', e.code); + return; + } + + assert.ok(false); + }); + + it('should ignore optional library not defined', function() { + assert.equal(undefined, require_optional('es6-promise2')); + }); + }); + + describe('internal module file require', function() { + it('should correctly require co library', function() { + var Long = require_optional('bson/lib/bson/long.js'); + assert.ok(Long); + }); + }); + + describe('top level resolve', function() { + it('should correctly use exists method', function() { + assert.equal(false, require_optional.exists('co')); + assert.equal(true, require_optional.exists('es6-promise')); + assert.equal(true, require_optional.exists('bson/lib/bson/long.js')); + assert.equal(false, require_optional.exists('es6-promise2')); + }); + }); + + describe('require_optional inside dependencies', function() { + it('should correctly walk up module call stack searching for peerOptionalDependencies', function() { + assert.ok(nestedTest.findPackage('bson')) + }); + it('should return null when a package is defined in top-level package.json but not installed', function() { + assert.equal(null, nestedTest.findPackage('es6-promise2')) + }); + it('should error when searching for an optional dependency that is not defined in any ancestor package.json', function() { + try { + nestedTest.findPackage('bison') + } catch (err) { + assert.equal(err.message, 'no optional dependency [bison] defined in peerOptionalDependencies in any package.json') + } + }) + }); +}); diff --git a/scripts/node_modules/resolve-from/index.js b/scripts/node_modules/resolve-from/index.js new file mode 100644 index 00000000..434159f1 --- /dev/null +++ b/scripts/node_modules/resolve-from/index.js @@ -0,0 +1,23 @@ +'use strict'; +var path = require('path'); +var Module = require('module'); + +module.exports = function (fromDir, moduleId) { + if (typeof fromDir !== 'string' || typeof moduleId !== 'string') { + throw new TypeError('Expected `fromDir` and `moduleId` to be a string'); + } + + fromDir = path.resolve(fromDir); + + var fromFile = path.join(fromDir, 'noop.js'); + + try { + return Module._resolveFilename(moduleId, { + id: fromFile, + filename: fromFile, + paths: Module._nodeModulePaths(fromDir) + }); + } catch (err) { + return null; + } +}; diff --git a/scripts/node_modules/resolve-from/license b/scripts/node_modules/resolve-from/license new file mode 100644 index 00000000..654d0bfe --- /dev/null +++ b/scripts/node_modules/resolve-from/license @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/scripts/node_modules/resolve-from/package.json b/scripts/node_modules/resolve-from/package.json new file mode 100644 index 00000000..4484dd56 --- /dev/null +++ b/scripts/node_modules/resolve-from/package.json @@ -0,0 +1,66 @@ +{ + "_from": "resolve-from@^2.0.0", + "_id": "resolve-from@2.0.0", + "_inBundle": false, + "_integrity": "sha1-lICrIOlP+h2egKgEx+oUdhGWa1c=", + "_location": "/resolve-from", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "resolve-from@^2.0.0", + "name": "resolve-from", + "escapedName": "resolve-from", + "rawSpec": "^2.0.0", + "saveSpec": null, + "fetchSpec": "^2.0.0" + }, + "_requiredBy": [ + "/require_optional" + ], + "_resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-2.0.0.tgz", + "_shasum": "9480ab20e94ffa1d9e80a804c7ea147611966b57", + "_spec": "resolve-from@^2.0.0", + "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/node_modules/require_optional", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "bugs": { + "url": "https://github.com/sindresorhus/resolve-from/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "Resolve the path of a module like require.resolve() but from a given path", + "devDependencies": { + "ava": "*", + "xo": "*" + }, + "engines": { + "node": ">=0.10.0" + }, + "files": [ + "index.js" + ], + "homepage": "https://github.com/sindresorhus/resolve-from#readme", + "keywords": [ + "require", + "resolve", + "path", + "module", + "from", + "like", + "path" + ], + "license": "MIT", + "name": "resolve-from", + "repository": { + "type": "git", + "url": "git+https://github.com/sindresorhus/resolve-from.git" + }, + "scripts": { + "test": "xo && ava" + }, + "version": "2.0.0" +} diff --git a/scripts/node_modules/resolve-from/readme.md b/scripts/node_modules/resolve-from/readme.md new file mode 100644 index 00000000..bb4ca91e --- /dev/null +++ b/scripts/node_modules/resolve-from/readme.md @@ -0,0 +1,58 @@ +# resolve-from [![Build Status](https://travis-ci.org/sindresorhus/resolve-from.svg?branch=master)](https://travis-ci.org/sindresorhus/resolve-from) + +> Resolve the path of a module like [`require.resolve()`](http://nodejs.org/api/globals.html#globals_require_resolve) but from a given path + +Unlike `require.resolve()` it returns `null` instead of throwing when the module can't be found. + + +## Install + +``` +$ npm install --save resolve-from +``` + + +## Usage + +```js +const resolveFrom = require('resolve-from'); + +// there's a file at `./foo/bar.js` + +resolveFrom('foo', './bar'); +//=> '/Users/sindresorhus/dev/test/foo/bar.js' +``` + + +## API + +### resolveFrom(fromDir, moduleId) + +#### fromDir + +Type: `string` + +Directory to resolve from. + +#### moduleId + +Type: `string` + +What you would use in `require()`. + + +## Tip + +Create a partial using a bound function if you want to require from the same `fromDir` multiple times: + +```js +const resolveFromFoo = resolveFrom.bind(null, 'foo'); + +resolveFromFoo('./bar'); +resolveFromFoo('./baz'); +``` + + +## License + +MIT © [Sindre Sorhus](http://sindresorhus.com) diff --git a/scripts/node_modules/safe-buffer/LICENSE b/scripts/node_modules/safe-buffer/LICENSE new file mode 100644 index 00000000..0c068cee --- /dev/null +++ b/scripts/node_modules/safe-buffer/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Feross Aboukhadijeh + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/scripts/node_modules/safe-buffer/README.md b/scripts/node_modules/safe-buffer/README.md new file mode 100644 index 00000000..356e3519 --- /dev/null +++ b/scripts/node_modules/safe-buffer/README.md @@ -0,0 +1,586 @@ +# safe-buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] + +[travis-image]: https://img.shields.io/travis/feross/safe-buffer/master.svg +[travis-url]: https://travis-ci.org/feross/safe-buffer +[npm-image]: https://img.shields.io/npm/v/safe-buffer.svg +[npm-url]: https://npmjs.org/package/safe-buffer +[downloads-image]: https://img.shields.io/npm/dm/safe-buffer.svg +[downloads-url]: https://npmjs.org/package/safe-buffer +[standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg +[standard-url]: https://standardjs.com + +#### Safer Node.js Buffer API + +**Use the new Node.js Buffer APIs (`Buffer.from`, `Buffer.alloc`, +`Buffer.allocUnsafe`, `Buffer.allocUnsafeSlow`) in all versions of Node.js.** + +**Uses the built-in implementation when available.** + +## install + +``` +npm install safe-buffer +``` + +[Get supported safe-buffer with the Tidelift Subscription](https://tidelift.com/subscription/pkg/npm-safe-buffer?utm_source=npm-safe-buffer&utm_medium=referral&utm_campaign=readme) + +## usage + +The goal of this package is to provide a safe replacement for the node.js `Buffer`. + +It's a drop-in replacement for `Buffer`. You can use it by adding one `require` line to +the top of your node.js modules: + +```js +var Buffer = require('safe-buffer').Buffer + +// Existing buffer code will continue to work without issues: + +new Buffer('hey', 'utf8') +new Buffer([1, 2, 3], 'utf8') +new Buffer(obj) +new Buffer(16) // create an uninitialized buffer (potentially unsafe) + +// But you can use these new explicit APIs to make clear what you want: + +Buffer.from('hey', 'utf8') // convert from many types to a Buffer +Buffer.alloc(16) // create a zero-filled buffer (safe) +Buffer.allocUnsafe(16) // create an uninitialized buffer (potentially unsafe) +``` + +## api + +### Class Method: Buffer.from(array) + + +* `array` {Array} + +Allocates a new `Buffer` using an `array` of octets. + +```js +const buf = Buffer.from([0x62,0x75,0x66,0x66,0x65,0x72]); + // creates a new Buffer containing ASCII bytes + // ['b','u','f','f','e','r'] +``` + +A `TypeError` will be thrown if `array` is not an `Array`. + +### Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]]) + + +* `arrayBuffer` {ArrayBuffer} The `.buffer` property of a `TypedArray` or + a `new ArrayBuffer()` +* `byteOffset` {Number} Default: `0` +* `length` {Number} Default: `arrayBuffer.length - byteOffset` + +When passed a reference to the `.buffer` property of a `TypedArray` instance, +the newly created `Buffer` will share the same allocated memory as the +TypedArray. + +```js +const arr = new Uint16Array(2); +arr[0] = 5000; +arr[1] = 4000; + +const buf = Buffer.from(arr.buffer); // shares the memory with arr; + +console.log(buf); + // Prints: + +// changing the TypedArray changes the Buffer also +arr[1] = 6000; + +console.log(buf); + // Prints: +``` + +The optional `byteOffset` and `length` arguments specify a memory range within +the `arrayBuffer` that will be shared by the `Buffer`. + +```js +const ab = new ArrayBuffer(10); +const buf = Buffer.from(ab, 0, 2); +console.log(buf.length); + // Prints: 2 +``` + +A `TypeError` will be thrown if `arrayBuffer` is not an `ArrayBuffer`. + +### Class Method: Buffer.from(buffer) + + +* `buffer` {Buffer} + +Copies the passed `buffer` data onto a new `Buffer` instance. + +```js +const buf1 = Buffer.from('buffer'); +const buf2 = Buffer.from(buf1); + +buf1[0] = 0x61; +console.log(buf1.toString()); + // 'auffer' +console.log(buf2.toString()); + // 'buffer' (copy is not changed) +``` + +A `TypeError` will be thrown if `buffer` is not a `Buffer`. + +### Class Method: Buffer.from(str[, encoding]) + + +* `str` {String} String to encode. +* `encoding` {String} Encoding to use, Default: `'utf8'` + +Creates a new `Buffer` containing the given JavaScript string `str`. If +provided, the `encoding` parameter identifies the character encoding. +If not provided, `encoding` defaults to `'utf8'`. + +```js +const buf1 = Buffer.from('this is a tést'); +console.log(buf1.toString()); + // prints: this is a tést +console.log(buf1.toString('ascii')); + // prints: this is a tC)st + +const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex'); +console.log(buf2.toString()); + // prints: this is a tést +``` + +A `TypeError` will be thrown if `str` is not a string. + +### Class Method: Buffer.alloc(size[, fill[, encoding]]) + + +* `size` {Number} +* `fill` {Value} Default: `undefined` +* `encoding` {String} Default: `utf8` + +Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the +`Buffer` will be *zero-filled*. + +```js +const buf = Buffer.alloc(5); +console.log(buf); + // +``` + +The `size` must be less than or equal to the value of +`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is +`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will +be created if a `size` less than or equal to 0 is specified. + +If `fill` is specified, the allocated `Buffer` will be initialized by calling +`buf.fill(fill)`. See [`buf.fill()`][] for more information. + +```js +const buf = Buffer.alloc(5, 'a'); +console.log(buf); + // +``` + +If both `fill` and `encoding` are specified, the allocated `Buffer` will be +initialized by calling `buf.fill(fill, encoding)`. For example: + +```js +const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); +console.log(buf); + // +``` + +Calling `Buffer.alloc(size)` can be significantly slower than the alternative +`Buffer.allocUnsafe(size)` but ensures that the newly created `Buffer` instance +contents will *never contain sensitive data*. + +A `TypeError` will be thrown if `size` is not a number. + +### Class Method: Buffer.allocUnsafe(size) + + +* `size` {Number} + +Allocates a new *non-zero-filled* `Buffer` of `size` bytes. The `size` must +be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit +architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is +thrown. A zero-length Buffer will be created if a `size` less than or equal to +0 is specified. + +The underlying memory for `Buffer` instances created in this way is *not +initialized*. The contents of the newly created `Buffer` are unknown and +*may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such +`Buffer` instances to zeroes. + +```js +const buf = Buffer.allocUnsafe(5); +console.log(buf); + // + // (octets will be different, every time) +buf.fill(0); +console.log(buf); + // +``` + +A `TypeError` will be thrown if `size` is not a number. + +Note that the `Buffer` module pre-allocates an internal `Buffer` instance of +size `Buffer.poolSize` that is used as a pool for the fast allocation of new +`Buffer` instances created using `Buffer.allocUnsafe(size)` (and the deprecated +`new Buffer(size)` constructor) only when `size` is less than or equal to +`Buffer.poolSize >> 1` (floor of `Buffer.poolSize` divided by two). The default +value of `Buffer.poolSize` is `8192` but can be modified. + +Use of this pre-allocated internal memory pool is a key difference between +calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`. +Specifically, `Buffer.alloc(size, fill)` will *never* use the internal Buffer +pool, while `Buffer.allocUnsafe(size).fill(fill)` *will* use the internal +Buffer pool if `size` is less than or equal to half `Buffer.poolSize`. The +difference is subtle but can be important when an application requires the +additional performance that `Buffer.allocUnsafe(size)` provides. + +### Class Method: Buffer.allocUnsafeSlow(size) + + +* `size` {Number} + +Allocates a new *non-zero-filled* and non-pooled `Buffer` of `size` bytes. The +`size` must be less than or equal to the value of +`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is +`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will +be created if a `size` less than or equal to 0 is specified. + +The underlying memory for `Buffer` instances created in this way is *not +initialized*. The contents of the newly created `Buffer` are unknown and +*may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such +`Buffer` instances to zeroes. + +When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances, +allocations under 4KB are, by default, sliced from a single pre-allocated +`Buffer`. This allows applications to avoid the garbage collection overhead of +creating many individually allocated Buffers. This approach improves both +performance and memory usage by eliminating the need to track and cleanup as +many `Persistent` objects. + +However, in the case where a developer may need to retain a small chunk of +memory from a pool for an indeterminate amount of time, it may be appropriate +to create an un-pooled Buffer instance using `Buffer.allocUnsafeSlow()` then +copy out the relevant bits. + +```js +// need to keep around a few small chunks of memory +const store = []; + +socket.on('readable', () => { + const data = socket.read(); + // allocate for retained data + const sb = Buffer.allocUnsafeSlow(10); + // copy the data into the new allocation + data.copy(sb, 0, 0, 10); + store.push(sb); +}); +``` + +Use of `Buffer.allocUnsafeSlow()` should be used only as a last resort *after* +a developer has observed undue memory retention in their applications. + +A `TypeError` will be thrown if `size` is not a number. + +### All the Rest + +The rest of the `Buffer` API is exactly the same as in node.js. +[See the docs](https://nodejs.org/api/buffer.html). + + +## Related links + +- [Node.js issue: Buffer(number) is unsafe](https://github.com/nodejs/node/issues/4660) +- [Node.js Enhancement Proposal: Buffer.from/Buffer.alloc/Buffer.zalloc/Buffer() soft-deprecate](https://github.com/nodejs/node-eps/pull/4) + +## Why is `Buffer` unsafe? + +Today, the node.js `Buffer` constructor is overloaded to handle many different argument +types like `String`, `Array`, `Object`, `TypedArrayView` (`Uint8Array`, etc.), +`ArrayBuffer`, and also `Number`. + +The API is optimized for convenience: you can throw any type at it, and it will try to do +what you want. + +Because the Buffer constructor is so powerful, you often see code like this: + +```js +// Convert UTF-8 strings to hex +function toHex (str) { + return new Buffer(str).toString('hex') +} +``` + +***But what happens if `toHex` is called with a `Number` argument?*** + +### Remote Memory Disclosure + +If an attacker can make your program call the `Buffer` constructor with a `Number` +argument, then they can make it allocate uninitialized memory from the node.js process. +This could potentially disclose TLS private keys, user data, or database passwords. + +When the `Buffer` constructor is passed a `Number` argument, it returns an +**UNINITIALIZED** block of memory of the specified `size`. When you create a `Buffer` like +this, you **MUST** overwrite the contents before returning it to the user. + +From the [node.js docs](https://nodejs.org/api/buffer.html#buffer_new_buffer_size): + +> `new Buffer(size)` +> +> - `size` Number +> +> The underlying memory for `Buffer` instances created in this way is not initialized. +> **The contents of a newly created `Buffer` are unknown and could contain sensitive +> data.** Use `buf.fill(0)` to initialize a Buffer to zeroes. + +(Emphasis our own.) + +Whenever the programmer intended to create an uninitialized `Buffer` you often see code +like this: + +```js +var buf = new Buffer(16) + +// Immediately overwrite the uninitialized buffer with data from another buffer +for (var i = 0; i < buf.length; i++) { + buf[i] = otherBuf[i] +} +``` + + +### Would this ever be a problem in real code? + +Yes. It's surprisingly common to forget to check the type of your variables in a +dynamically-typed language like JavaScript. + +Usually the consequences of assuming the wrong type is that your program crashes with an +uncaught exception. But the failure mode for forgetting to check the type of arguments to +the `Buffer` constructor is more catastrophic. + +Here's an example of a vulnerable service that takes a JSON payload and converts it to +hex: + +```js +// Take a JSON payload {str: "some string"} and convert it to hex +var server = http.createServer(function (req, res) { + var data = '' + req.setEncoding('utf8') + req.on('data', function (chunk) { + data += chunk + }) + req.on('end', function () { + var body = JSON.parse(data) + res.end(new Buffer(body.str).toString('hex')) + }) +}) + +server.listen(8080) +``` + +In this example, an http client just has to send: + +```json +{ + "str": 1000 +} +``` + +and it will get back 1,000 bytes of uninitialized memory from the server. + +This is a very serious bug. It's similar in severity to the +[the Heartbleed bug](http://heartbleed.com/) that allowed disclosure of OpenSSL process +memory by remote attackers. + + +### Which real-world packages were vulnerable? + +#### [`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht) + +[Mathias Buus](https://github.com/mafintosh) and I +([Feross Aboukhadijeh](http://feross.org/)) found this issue in one of our own packages, +[`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht). The bug would allow +anyone on the internet to send a series of messages to a user of `bittorrent-dht` and get +them to reveal 20 bytes at a time of uninitialized memory from the node.js process. + +Here's +[the commit](https://github.com/feross/bittorrent-dht/commit/6c7da04025d5633699800a99ec3fbadf70ad35b8) +that fixed it. We released a new fixed version, created a +[Node Security Project disclosure](https://nodesecurity.io/advisories/68), and deprecated all +vulnerable versions on npm so users will get a warning to upgrade to a newer version. + +#### [`ws`](https://www.npmjs.com/package/ws) + +That got us wondering if there were other vulnerable packages. Sure enough, within a short +period of time, we found the same issue in [`ws`](https://www.npmjs.com/package/ws), the +most popular WebSocket implementation in node.js. + +If certain APIs were called with `Number` parameters instead of `String` or `Buffer` as +expected, then uninitialized server memory would be disclosed to the remote peer. + +These were the vulnerable methods: + +```js +socket.send(number) +socket.ping(number) +socket.pong(number) +``` + +Here's a vulnerable socket server with some echo functionality: + +```js +server.on('connection', function (socket) { + socket.on('message', function (message) { + message = JSON.parse(message) + if (message.type === 'echo') { + socket.send(message.data) // send back the user's message + } + }) +}) +``` + +`socket.send(number)` called on the server, will disclose server memory. + +Here's [the release](https://github.com/websockets/ws/releases/tag/1.0.1) where the issue +was fixed, with a more detailed explanation. Props to +[Arnout Kazemier](https://github.com/3rd-Eden) for the quick fix. Here's the +[Node Security Project disclosure](https://nodesecurity.io/advisories/67). + + +### What's the solution? + +It's important that node.js offers a fast way to get memory otherwise performance-critical +applications would needlessly get a lot slower. + +But we need a better way to *signal our intent* as programmers. **When we want +uninitialized memory, we should request it explicitly.** + +Sensitive functionality should not be packed into a developer-friendly API that loosely +accepts many different types. This type of API encourages the lazy practice of passing +variables in without checking the type very carefully. + +#### A new API: `Buffer.allocUnsafe(number)` + +The functionality of creating buffers with uninitialized memory should be part of another +API. We propose `Buffer.allocUnsafe(number)`. This way, it's not part of an API that +frequently gets user input of all sorts of different types passed into it. + +```js +var buf = Buffer.allocUnsafe(16) // careful, uninitialized memory! + +// Immediately overwrite the uninitialized buffer with data from another buffer +for (var i = 0; i < buf.length; i++) { + buf[i] = otherBuf[i] +} +``` + + +### How do we fix node.js core? + +We sent [a PR to node.js core](https://github.com/nodejs/node/pull/4514) (merged as +`semver-major`) which defends against one case: + +```js +var str = 16 +new Buffer(str, 'utf8') +``` + +In this situation, it's implied that the programmer intended the first argument to be a +string, since they passed an encoding as a second argument. Today, node.js will allocate +uninitialized memory in the case of `new Buffer(number, encoding)`, which is probably not +what the programmer intended. + +But this is only a partial solution, since if the programmer does `new Buffer(variable)` +(without an `encoding` parameter) there's no way to know what they intended. If `variable` +is sometimes a number, then uninitialized memory will sometimes be returned. + +### What's the real long-term fix? + +We could deprecate and remove `new Buffer(number)` and use `Buffer.allocUnsafe(number)` when +we need uninitialized memory. But that would break 1000s of packages. + +~~We believe the best solution is to:~~ + +~~1. Change `new Buffer(number)` to return safe, zeroed-out memory~~ + +~~2. Create a new API for creating uninitialized Buffers. We propose: `Buffer.allocUnsafe(number)`~~ + +#### Update + +We now support adding three new APIs: + +- `Buffer.from(value)` - convert from any type to a buffer +- `Buffer.alloc(size)` - create a zero-filled buffer +- `Buffer.allocUnsafe(size)` - create an uninitialized buffer with given size + +This solves the core problem that affected `ws` and `bittorrent-dht` which is +`Buffer(variable)` getting tricked into taking a number argument. + +This way, existing code continues working and the impact on the npm ecosystem will be +minimal. Over time, npm maintainers can migrate performance-critical code to use +`Buffer.allocUnsafe(number)` instead of `new Buffer(number)`. + + +### Conclusion + +We think there's a serious design issue with the `Buffer` API as it exists today. It +promotes insecure software by putting high-risk functionality into a convenient API +with friendly "developer ergonomics". + +This wasn't merely a theoretical exercise because we found the issue in some of the +most popular npm packages. + +Fortunately, there's an easy fix that can be applied today. Use `safe-buffer` in place of +`buffer`. + +```js +var Buffer = require('safe-buffer').Buffer +``` + +Eventually, we hope that node.js core can switch to this new, safer behavior. We believe +the impact on the ecosystem would be minimal since it's not a breaking change. +Well-maintained, popular packages would be updated to use `Buffer.alloc` quickly, while +older, insecure packages would magically become safe from this attack vector. + + +## links + +- [Node.js PR: buffer: throw if both length and enc are passed](https://github.com/nodejs/node/pull/4514) +- [Node Security Project disclosure for `ws`](https://nodesecurity.io/advisories/67) +- [Node Security Project disclosure for`bittorrent-dht`](https://nodesecurity.io/advisories/68) + + +## credit + +The original issues in `bittorrent-dht` +([disclosure](https://nodesecurity.io/advisories/68)) and +`ws` ([disclosure](https://nodesecurity.io/advisories/67)) were discovered by +[Mathias Buus](https://github.com/mafintosh) and +[Feross Aboukhadijeh](http://feross.org/). + +Thanks to [Adam Baldwin](https://github.com/evilpacket) for helping disclose these issues +and for his work running the [Node Security Project](https://nodesecurity.io/). + +Thanks to [John Hiesey](https://github.com/jhiesey) for proofreading this README and +auditing the code. + + +## license + +MIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org) diff --git a/scripts/node_modules/safe-buffer/index.d.ts b/scripts/node_modules/safe-buffer/index.d.ts new file mode 100644 index 00000000..e9fed809 --- /dev/null +++ b/scripts/node_modules/safe-buffer/index.d.ts @@ -0,0 +1,187 @@ +declare module "safe-buffer" { + export class Buffer { + length: number + write(string: string, offset?: number, length?: number, encoding?: string): number; + toString(encoding?: string, start?: number, end?: number): string; + toJSON(): { type: 'Buffer', data: any[] }; + equals(otherBuffer: Buffer): boolean; + compare(otherBuffer: Buffer, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number; + copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; + slice(start?: number, end?: number): Buffer; + writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readUInt8(offset: number, noAssert?: boolean): number; + readUInt16LE(offset: number, noAssert?: boolean): number; + readUInt16BE(offset: number, noAssert?: boolean): number; + readUInt32LE(offset: number, noAssert?: boolean): number; + readUInt32BE(offset: number, noAssert?: boolean): number; + readInt8(offset: number, noAssert?: boolean): number; + readInt16LE(offset: number, noAssert?: boolean): number; + readInt16BE(offset: number, noAssert?: boolean): number; + readInt32LE(offset: number, noAssert?: boolean): number; + readInt32BE(offset: number, noAssert?: boolean): number; + readFloatLE(offset: number, noAssert?: boolean): number; + readFloatBE(offset: number, noAssert?: boolean): number; + readDoubleLE(offset: number, noAssert?: boolean): number; + readDoubleBE(offset: number, noAssert?: boolean): number; + swap16(): Buffer; + swap32(): Buffer; + swap64(): Buffer; + writeUInt8(value: number, offset: number, noAssert?: boolean): number; + writeUInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeInt8(value: number, offset: number, noAssert?: boolean): number; + writeInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeFloatLE(value: number, offset: number, noAssert?: boolean): number; + writeFloatBE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleLE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleBE(value: number, offset: number, noAssert?: boolean): number; + fill(value: any, offset?: number, end?: number): this; + indexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + lastIndexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean; + + /** + * Allocates a new buffer containing the given {str}. + * + * @param str String to store in buffer. + * @param encoding encoding to use, optional. Default is 'utf8' + */ + constructor (str: string, encoding?: string); + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + */ + constructor (size: number); + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + */ + constructor (array: Uint8Array); + /** + * Produces a Buffer backed by the same allocated memory as + * the given {ArrayBuffer}. + * + * + * @param arrayBuffer The ArrayBuffer with which to share memory. + */ + constructor (arrayBuffer: ArrayBuffer); + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + */ + constructor (array: any[]); + /** + * Copies the passed {buffer} data onto a new {Buffer} instance. + * + * @param buffer The buffer to copy. + */ + constructor (buffer: Buffer); + prototype: Buffer; + /** + * Allocates a new Buffer using an {array} of octets. + * + * @param array + */ + static from(array: any[]): Buffer; + /** + * When passed a reference to the .buffer property of a TypedArray instance, + * the newly created Buffer will share the same allocated memory as the TypedArray. + * The optional {byteOffset} and {length} arguments specify a memory range + * within the {arrayBuffer} that will be shared by the Buffer. + * + * @param arrayBuffer The .buffer property of a TypedArray or a new ArrayBuffer() + * @param byteOffset + * @param length + */ + static from(arrayBuffer: ArrayBuffer, byteOffset?: number, length?: number): Buffer; + /** + * Copies the passed {buffer} data onto a new Buffer instance. + * + * @param buffer + */ + static from(buffer: Buffer): Buffer; + /** + * Creates a new Buffer containing the given JavaScript string {str}. + * If provided, the {encoding} parameter identifies the character encoding. + * If not provided, {encoding} defaults to 'utf8'. + * + * @param str + */ + static from(str: string, encoding?: string): Buffer; + /** + * Returns true if {obj} is a Buffer + * + * @param obj object to test. + */ + static isBuffer(obj: any): obj is Buffer; + /** + * Returns true if {encoding} is a valid encoding argument. + * Valid string encodings in Node 0.12: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' + * + * @param encoding string to test. + */ + static isEncoding(encoding: string): boolean; + /** + * Gives the actual byte length of a string. encoding defaults to 'utf8'. + * This is not the same as String.prototype.length since that returns the number of characters in a string. + * + * @param string string to test. + * @param encoding encoding used to evaluate (defaults to 'utf8') + */ + static byteLength(string: string, encoding?: string): number; + /** + * Returns a buffer which is the result of concatenating all the buffers in the list together. + * + * If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer. + * If the list has exactly one item, then the first item of the list is returned. + * If the list has more than one item, then a new Buffer is created. + * + * @param list An array of Buffer objects to concatenate + * @param totalLength Total length of the buffers when concatenated. + * If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly. + */ + static concat(list: Buffer[], totalLength?: number): Buffer; + /** + * The same as buf1.compare(buf2). + */ + static compare(buf1: Buffer, buf2: Buffer): number; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @param fill if specified, buffer will be initialized by calling buf.fill(fill). + * If parameter is omitted, buffer will be filled with zeros. + * @param encoding encoding used for call to buf.fill while initalizing + */ + static alloc(size: number, fill?: string | Buffer | number, encoding?: string): Buffer; + /** + * Allocates a new buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + static allocUnsafe(size: number): Buffer; + /** + * Allocates a new non-pooled buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + static allocUnsafeSlow(size: number): Buffer; + } +} \ No newline at end of file diff --git a/scripts/node_modules/safe-buffer/index.js b/scripts/node_modules/safe-buffer/index.js new file mode 100644 index 00000000..054c8d30 --- /dev/null +++ b/scripts/node_modules/safe-buffer/index.js @@ -0,0 +1,64 @@ +/* eslint-disable node/no-deprecated-api */ +var buffer = require('buffer') +var Buffer = buffer.Buffer + +// alternative to using Object.keys for old browsers +function copyProps (src, dst) { + for (var key in src) { + dst[key] = src[key] + } +} +if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { + module.exports = buffer +} else { + // Copy properties from require('buffer') + copyProps(buffer, exports) + exports.Buffer = SafeBuffer +} + +function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) +} + +SafeBuffer.prototype = Object.create(Buffer.prototype) + +// Copy static methods from Buffer +copyProps(Buffer, SafeBuffer) + +SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') + } + return Buffer(arg, encodingOrOffset, length) +} + +SafeBuffer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + var buf = Buffer(size) + if (fill !== undefined) { + if (typeof encoding === 'string') { + buf.fill(fill, encoding) + } else { + buf.fill(fill) + } + } else { + buf.fill(0) + } + return buf +} + +SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return Buffer(size) +} + +SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return buffer.SlowBuffer(size) +} diff --git a/scripts/node_modules/safe-buffer/package.json b/scripts/node_modules/safe-buffer/package.json new file mode 100644 index 00000000..ee699fac --- /dev/null +++ b/scripts/node_modules/safe-buffer/package.json @@ -0,0 +1,62 @@ +{ + "_from": "safe-buffer@^5.1.2", + "_id": "safe-buffer@5.2.0", + "_inBundle": false, + "_integrity": "sha512-fZEwUGbVl7kouZs1jCdMLdt95hdIv0ZeHg6L7qPeciMZhZ+/gdesW4wgTARkrFWEpspjEATAzUGPG8N2jJiwbg==", + "_location": "/safe-buffer", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "safe-buffer@^5.1.2", + "name": "safe-buffer", + "escapedName": "safe-buffer", + "rawSpec": "^5.1.2", + "saveSpec": null, + "fetchSpec": "^5.1.2" + }, + "_requiredBy": [ + "/mongodb" + ], + "_resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.0.tgz", + "_shasum": "b74daec49b1148f88c64b68d49b1e815c1f2f519", + "_spec": "safe-buffer@^5.1.2", + "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/node_modules/mongodb", + "author": { + "name": "Feross Aboukhadijeh", + "email": "feross@feross.org", + "url": "http://feross.org" + }, + "bugs": { + "url": "https://github.com/feross/safe-buffer/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "Safer Node.js Buffer API", + "devDependencies": { + "standard": "*", + "tape": "^4.0.0" + }, + "homepage": "https://github.com/feross/safe-buffer", + "keywords": [ + "buffer", + "buffer allocate", + "node security", + "safe", + "safe-buffer", + "security", + "uninitialized" + ], + "license": "MIT", + "main": "index.js", + "name": "safe-buffer", + "repository": { + "type": "git", + "url": "git://github.com/feross/safe-buffer.git" + }, + "scripts": { + "test": "standard && tape test/*.js" + }, + "types": "index.d.ts", + "version": "5.2.0" +} diff --git a/scripts/node_modules/saslprep/.editorconfig b/scripts/node_modules/saslprep/.editorconfig new file mode 100644 index 00000000..d1d8a417 --- /dev/null +++ b/scripts/node_modules/saslprep/.editorconfig @@ -0,0 +1,10 @@ +# http://editorconfig.org +root = true + +[*] +indent_style = space +indent_size = 2 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true diff --git a/scripts/node_modules/saslprep/.gitattributes b/scripts/node_modules/saslprep/.gitattributes new file mode 100644 index 00000000..3ba45360 --- /dev/null +++ b/scripts/node_modules/saslprep/.gitattributes @@ -0,0 +1 @@ +*.mem binary diff --git a/scripts/node_modules/saslprep/.travis.yml b/scripts/node_modules/saslprep/.travis.yml new file mode 100644 index 00000000..0bca8265 --- /dev/null +++ b/scripts/node_modules/saslprep/.travis.yml @@ -0,0 +1,10 @@ +sudo: false +language: node_js +node_js: + - "6" + - "8" + - "10" + - "12" + +before_install: +- npm install -g npm@6 diff --git a/scripts/node_modules/saslprep/CHANGELOG.md b/scripts/node_modules/saslprep/CHANGELOG.md new file mode 100644 index 00000000..77980787 --- /dev/null +++ b/scripts/node_modules/saslprep/CHANGELOG.md @@ -0,0 +1,19 @@ +# Change Log +All notable changes to the "saslprep" package will be documented in this file. + +## [1.0.3] - 2019-05-01 + +- Correctly get code points >U+FFFF ([#5](https://github.com/reklatsmasters/saslprep/pull/5)) +- Fix perfomance downgrades from [#5](https://github.com/reklatsmasters/saslprep/pull/5). + +## [1.0.2] - 2018-09-13 + +- Reduced initialization time ([#3](https://github.com/reklatsmasters/saslprep/issues/3)) + +## [1.0.1] - 2018-06-20 + +- Reduced stack overhead of range creation ([#2](https://github.com/reklatsmasters/saslprep/pull/2)) + +## [1.0.0] - 2017-06-21 + +- First release diff --git a/scripts/node_modules/saslprep/LICENSE b/scripts/node_modules/saslprep/LICENSE new file mode 100644 index 00000000..481c7a50 --- /dev/null +++ b/scripts/node_modules/saslprep/LICENSE @@ -0,0 +1,22 @@ +Copyright (c) 2014 Dmitry Tsvettsikh + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/scripts/node_modules/saslprep/code-points.mem b/scripts/node_modules/saslprep/code-points.mem new file mode 100644 index 0000000000000000000000000000000000000000..4781b066802688bdf954d2e89bcfac967db29c09 GIT binary patch literal 419864 zcmeI*O^9Si9RTop)4e+(t{DX(dsufSM8xBQfdsOo2lf&{@FWO&5cZ;Y@FWHe%nKV~ z@sxvzw;c53DIgdRk!c;t<{;##B4%51h#=^gL^8Y6+hx^z-92x{*9;3Umv`GA&vUy%enler!HTQKkA3&c=OSJMn7j|JGjl-d;Iey^#7>ZH0(RWYm^YJNA>kJ59aOu`p6X{MHRe9bu8cD2oYvN=9*ybv z%TyjdGTZ46aN&^<{xI6U)O2~U(!G+Yl0gPYRjbu8Wx~a<(#z+pIGvPkC#O7E&NgnV zIeue)&FW_ULfI&__U^^i@bTrer0O33=x2+%W4?Qo^)pjbsxinkv-K<<-Z9O6ZEyaQ zcB_@u#{%W}q9N0;ypzw%<*<}a^^Ob|R8?1xx0U*l{Mfi-J@SG5+xHJnzAqkVA73p) zfWWZ=`LSE4W4mY|K!5-N0t5&UATSizd-XW}{r>FO4Bx#OzCAE{nLD@VvjcA?1PBnA ze}O7c;{B8P-)Ji&@Gu01QMDYyI+%*sOCglv+~@Yqqm#Pz_SKwJ*n6ekt-IE7xb$i{ z#vJ7-%1?!2rG0Ri^X0*sx?FU--CIQw%Y*Zsb~)W#QAMFvj~+Qsr{Zh=QgU=xwFC$d zAV7cs0RjXF5FkK+009C72oNAZfB*pkrx2*aLB}2IZvhtFBipAEvDq7W9J^}&<>l~& z=Z6hT7u&hviF4icy{;$Z#$Rfh)bDEDcnTt22oNAJj{^NkPm$UP5FkK+009C72oNAZ zfB*pk1PBlya5e=N=WpRu-1tFH?r+Uep=aLS_2t}!1M%`E=_N&nH;IH{&FT4 zVA2E#5FkK+009C72oNAZfB*pk1PBlyK!5-N0tDtqVE;Gx53TDIQTIm zIQs(S*`MN>nqk~d)2W{+PVszkrlxK(QxGVpFoq#!SYT-_Rh1zb5B|v}x z0RjXF5FkK+009C72oNAZfB*pk1PBlyK!5;&ITaB9pVN)CECK`w5FkK+009C72oNAZ zfB*pk1PBlyK!5-N0t5&USSSJU|ApFaizPsS009C72oNAZfB*pk1PBlyK!5-N0t5&U zAV7csfjJcr|DV&1wJZVz2oNAZfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF5LhUI)_PiQ zY@~%+y~PqBK!5-N0t5&UAV7cs0RjXF5FkK+009C72oNAZfB=E{5NI_*|FQ%K5FkK+ z009C72oNAZfB*pk1PBlyK!5-N0t5&UAV7e?Yzp*ebJ}K2fB*pk1PBlyK!5-N0t5&U zAV7cs0RjXF5FkK+009C72s8ykSewfEzdsXvos!llv!K)XN+!bACMEW{kJW7s~i{EW^`xUX5|{=UXrRtoY&_gwz< zRvE$%TJf3i_%h&Xxb|Z>^W9wXR6Vl#j!mc_rtE>35?{Z6IbwcGK;>nSRoF zHt&;$O2P80zs-^hqp)?4qhw2`7#YP=_?Tw>wDeltgbe?$_^GM=@ z?HoDm9erzgM=HMNFC|BJRZD;X0RjXF5FkK+009C72oNAZfB*pk1PBlya0-DOe>pzY z-vZ3vILv9#>4l5=+gV#xaVim;YNYBg{{HIj=YJUg^!l*j-g~>b;hnpk&0)>Sr{)*n zj_ut&1&%HR2oRWKfn%Q^H4q>`fB*pk1PBlyK!5-N0t5&UAVA>E3Jm7>U0X{dK!5-N z0t5&U__zX7c= character.codePointAt(0); +const first = x => x[0]; +const last = x => x[x.length - 1]; + +/** + * Convert provided string into an array of Unicode Code Points. + * Based on https://stackoverflow.com/a/21409165/1556249 + * and https://www.npmjs.com/package/code-point-at. + * @param {string} input + * @returns {number[]} + */ +function toCodePoints(input) { + const codepoints = []; + const size = input.length; + + for (let i = 0; i < size; i += 1) { + const before = input.charCodeAt(i); + + if (before >= 0xd800 && before <= 0xdbff && size > i + 1) { + const next = input.charCodeAt(i + 1); + + if (next >= 0xdc00 && next <= 0xdfff) { + codepoints.push((before - 0xd800) * 0x400 + next - 0xdc00 + 0x10000); + i += 1; + continue; + } + } + + codepoints.push(before); + } + + return codepoints; +} + +/** + * SASLprep. + * @param {string} input + * @param {Object} opts + * @param {boolean} opts.allowUnassigned + * @returns {string} + */ +function saslprep(input, opts = {}) { + if (typeof input !== 'string') { + throw new TypeError('Expected string.'); + } + + if (input.length === 0) { + return ''; + } + + // 1. Map + const mapped_input = toCodePoints(input) + // 1.1 mapping to space + .map(character => (mapping2space.get(character) ? 0x20 : character)) + // 1.2 mapping to nothing + .filter(character => !mapping2nothing.get(character)); + + // 2. Normalize + const normalized_input = String.fromCodePoint + .apply(null, mapped_input) + .normalize('NFKC'); + + const normalized_map = toCodePoints(normalized_input); + + // 3. Prohibit + const hasProhibited = normalized_map.some(character => + prohibited_characters.get(character) + ); + + if (hasProhibited) { + throw new Error( + 'Prohibited character, see https://tools.ietf.org/html/rfc4013#section-2.3' + ); + } + + // Unassigned Code Points + if (opts.allowUnassigned !== true) { + const hasUnassigned = normalized_map.some(character => + unassigned_code_points.get(character) + ); + + if (hasUnassigned) { + throw new Error( + 'Unassigned code point, see https://tools.ietf.org/html/rfc4013#section-2.5' + ); + } + } + + // 4. check bidi + + const hasBidiRAL = normalized_map.some(character => + bidirectional_r_al.get(character) + ); + + const hasBidiL = normalized_map.some(character => + bidirectional_l.get(character) + ); + + // 4.1 If a string contains any RandALCat character, the string MUST NOT + // contain any LCat character. + if (hasBidiRAL && hasBidiL) { + throw new Error( + 'String must not contain RandALCat and LCat at the same time,' + + ' see https://tools.ietf.org/html/rfc3454#section-6' + ); + } + + /** + * 4.2 If a string contains any RandALCat character, a RandALCat + * character MUST be the first character of the string, and a + * RandALCat character MUST be the last character of the string. + */ + + const isFirstBidiRAL = bidirectional_r_al.get( + getCodePoint(first(normalized_input)) + ); + const isLastBidiRAL = bidirectional_r_al.get( + getCodePoint(last(normalized_input)) + ); + + if (hasBidiRAL && !(isFirstBidiRAL && isLastBidiRAL)) { + throw new Error( + 'Bidirectional RandALCat character must be the first and the last' + + ' character of the string, see https://tools.ietf.org/html/rfc3454#section-6' + ); + } + + return normalized_input; +} diff --git a/scripts/node_modules/saslprep/lib/code-points.js b/scripts/node_modules/saslprep/lib/code-points.js new file mode 100644 index 00000000..222182c8 --- /dev/null +++ b/scripts/node_modules/saslprep/lib/code-points.js @@ -0,0 +1,996 @@ +'use strict'; + +const { range } = require('./util'); + +/** + * A.1 Unassigned code points in Unicode 3.2 + * @link https://tools.ietf.org/html/rfc3454#appendix-A.1 + */ +const unassigned_code_points = new Set([ + 0x0221, + ...range(0x0234, 0x024f), + ...range(0x02ae, 0x02af), + ...range(0x02ef, 0x02ff), + ...range(0x0350, 0x035f), + ...range(0x0370, 0x0373), + ...range(0x0376, 0x0379), + ...range(0x037b, 0x037d), + ...range(0x037f, 0x0383), + 0x038b, + 0x038d, + 0x03a2, + 0x03cf, + ...range(0x03f7, 0x03ff), + 0x0487, + 0x04cf, + ...range(0x04f6, 0x04f7), + ...range(0x04fa, 0x04ff), + ...range(0x0510, 0x0530), + ...range(0x0557, 0x0558), + 0x0560, + 0x0588, + ...range(0x058b, 0x0590), + 0x05a2, + 0x05ba, + ...range(0x05c5, 0x05cf), + ...range(0x05eb, 0x05ef), + ...range(0x05f5, 0x060b), + ...range(0x060d, 0x061a), + ...range(0x061c, 0x061e), + 0x0620, + ...range(0x063b, 0x063f), + ...range(0x0656, 0x065f), + ...range(0x06ee, 0x06ef), + 0x06ff, + 0x070e, + ...range(0x072d, 0x072f), + ...range(0x074b, 0x077f), + ...range(0x07b2, 0x0900), + 0x0904, + ...range(0x093a, 0x093b), + ...range(0x094e, 0x094f), + ...range(0x0955, 0x0957), + ...range(0x0971, 0x0980), + 0x0984, + ...range(0x098d, 0x098e), + ...range(0x0991, 0x0992), + 0x09a9, + 0x09b1, + ...range(0x09b3, 0x09b5), + ...range(0x09ba, 0x09bb), + 0x09bd, + ...range(0x09c5, 0x09c6), + ...range(0x09c9, 0x09ca), + ...range(0x09ce, 0x09d6), + ...range(0x09d8, 0x09db), + 0x09de, + ...range(0x09e4, 0x09e5), + ...range(0x09fb, 0x0a01), + ...range(0x0a03, 0x0a04), + ...range(0x0a0b, 0x0a0e), + ...range(0x0a11, 0x0a12), + 0x0a29, + 0x0a31, + 0x0a34, + 0x0a37, + ...range(0x0a3a, 0x0a3b), + 0x0a3d, + ...range(0x0a43, 0x0a46), + ...range(0x0a49, 0x0a4a), + ...range(0x0a4e, 0x0a58), + 0x0a5d, + ...range(0x0a5f, 0x0a65), + ...range(0x0a75, 0x0a80), + 0x0a84, + 0x0a8c, + 0x0a8e, + 0x0a92, + 0x0aa9, + 0x0ab1, + 0x0ab4, + ...range(0x0aba, 0x0abb), + 0x0ac6, + 0x0aca, + ...range(0x0ace, 0x0acf), + ...range(0x0ad1, 0x0adf), + ...range(0x0ae1, 0x0ae5), + ...range(0x0af0, 0x0b00), + 0x0b04, + ...range(0x0b0d, 0x0b0e), + ...range(0x0b11, 0x0b12), + 0x0b29, + 0x0b31, + ...range(0x0b34, 0x0b35), + ...range(0x0b3a, 0x0b3b), + ...range(0x0b44, 0x0b46), + ...range(0x0b49, 0x0b4a), + ...range(0x0b4e, 0x0b55), + ...range(0x0b58, 0x0b5b), + 0x0b5e, + ...range(0x0b62, 0x0b65), + ...range(0x0b71, 0x0b81), + 0x0b84, + ...range(0x0b8b, 0x0b8d), + 0x0b91, + ...range(0x0b96, 0x0b98), + 0x0b9b, + 0x0b9d, + ...range(0x0ba0, 0x0ba2), + ...range(0x0ba5, 0x0ba7), + ...range(0x0bab, 0x0bad), + 0x0bb6, + ...range(0x0bba, 0x0bbd), + ...range(0x0bc3, 0x0bc5), + 0x0bc9, + ...range(0x0bce, 0x0bd6), + ...range(0x0bd8, 0x0be6), + ...range(0x0bf3, 0x0c00), + 0x0c04, + 0x0c0d, + 0x0c11, + 0x0c29, + 0x0c34, + ...range(0x0c3a, 0x0c3d), + 0x0c45, + 0x0c49, + ...range(0x0c4e, 0x0c54), + ...range(0x0c57, 0x0c5f), + ...range(0x0c62, 0x0c65), + ...range(0x0c70, 0x0c81), + 0x0c84, + 0x0c8d, + 0x0c91, + 0x0ca9, + 0x0cb4, + ...range(0x0cba, 0x0cbd), + 0x0cc5, + 0x0cc9, + ...range(0x0cce, 0x0cd4), + ...range(0x0cd7, 0x0cdd), + 0x0cdf, + ...range(0x0ce2, 0x0ce5), + ...range(0x0cf0, 0x0d01), + 0x0d04, + 0x0d0d, + 0x0d11, + 0x0d29, + ...range(0x0d3a, 0x0d3d), + ...range(0x0d44, 0x0d45), + 0x0d49, + ...range(0x0d4e, 0x0d56), + ...range(0x0d58, 0x0d5f), + ...range(0x0d62, 0x0d65), + ...range(0x0d70, 0x0d81), + 0x0d84, + ...range(0x0d97, 0x0d99), + 0x0db2, + 0x0dbc, + ...range(0x0dbe, 0x0dbf), + ...range(0x0dc7, 0x0dc9), + ...range(0x0dcb, 0x0dce), + 0x0dd5, + 0x0dd7, + ...range(0x0de0, 0x0df1), + ...range(0x0df5, 0x0e00), + ...range(0x0e3b, 0x0e3e), + ...range(0x0e5c, 0x0e80), + 0x0e83, + ...range(0x0e85, 0x0e86), + 0x0e89, + ...range(0x0e8b, 0x0e8c), + ...range(0x0e8e, 0x0e93), + 0x0e98, + 0x0ea0, + 0x0ea4, + 0x0ea6, + ...range(0x0ea8, 0x0ea9), + 0x0eac, + 0x0eba, + ...range(0x0ebe, 0x0ebf), + 0x0ec5, + 0x0ec7, + ...range(0x0ece, 0x0ecf), + ...range(0x0eda, 0x0edb), + ...range(0x0ede, 0x0eff), + 0x0f48, + ...range(0x0f6b, 0x0f70), + ...range(0x0f8c, 0x0f8f), + 0x0f98, + 0x0fbd, + ...range(0x0fcd, 0x0fce), + ...range(0x0fd0, 0x0fff), + 0x1022, + 0x1028, + 0x102b, + ...range(0x1033, 0x1035), + ...range(0x103a, 0x103f), + ...range(0x105a, 0x109f), + ...range(0x10c6, 0x10cf), + ...range(0x10f9, 0x10fa), + ...range(0x10fc, 0x10ff), + ...range(0x115a, 0x115e), + ...range(0x11a3, 0x11a7), + ...range(0x11fa, 0x11ff), + 0x1207, + 0x1247, + 0x1249, + ...range(0x124e, 0x124f), + 0x1257, + 0x1259, + ...range(0x125e, 0x125f), + 0x1287, + 0x1289, + ...range(0x128e, 0x128f), + 0x12af, + 0x12b1, + ...range(0x12b6, 0x12b7), + 0x12bf, + 0x12c1, + ...range(0x12c6, 0x12c7), + 0x12cf, + 0x12d7, + 0x12ef, + 0x130f, + 0x1311, + ...range(0x1316, 0x1317), + 0x131f, + 0x1347, + ...range(0x135b, 0x1360), + ...range(0x137d, 0x139f), + ...range(0x13f5, 0x1400), + ...range(0x1677, 0x167f), + ...range(0x169d, 0x169f), + ...range(0x16f1, 0x16ff), + 0x170d, + ...range(0x1715, 0x171f), + ...range(0x1737, 0x173f), + ...range(0x1754, 0x175f), + 0x176d, + 0x1771, + ...range(0x1774, 0x177f), + ...range(0x17dd, 0x17df), + ...range(0x17ea, 0x17ff), + 0x180f, + ...range(0x181a, 0x181f), + ...range(0x1878, 0x187f), + ...range(0x18aa, 0x1dff), + ...range(0x1e9c, 0x1e9f), + ...range(0x1efa, 0x1eff), + ...range(0x1f16, 0x1f17), + ...range(0x1f1e, 0x1f1f), + ...range(0x1f46, 0x1f47), + ...range(0x1f4e, 0x1f4f), + 0x1f58, + 0x1f5a, + 0x1f5c, + 0x1f5e, + ...range(0x1f7e, 0x1f7f), + 0x1fb5, + 0x1fc5, + ...range(0x1fd4, 0x1fd5), + 0x1fdc, + ...range(0x1ff0, 0x1ff1), + 0x1ff5, + 0x1fff, + ...range(0x2053, 0x2056), + ...range(0x2058, 0x205e), + ...range(0x2064, 0x2069), + ...range(0x2072, 0x2073), + ...range(0x208f, 0x209f), + ...range(0x20b2, 0x20cf), + ...range(0x20eb, 0x20ff), + ...range(0x213b, 0x213c), + ...range(0x214c, 0x2152), + ...range(0x2184, 0x218f), + ...range(0x23cf, 0x23ff), + ...range(0x2427, 0x243f), + ...range(0x244b, 0x245f), + 0x24ff, + ...range(0x2614, 0x2615), + 0x2618, + ...range(0x267e, 0x267f), + ...range(0x268a, 0x2700), + 0x2705, + ...range(0x270a, 0x270b), + 0x2728, + 0x274c, + 0x274e, + ...range(0x2753, 0x2755), + 0x2757, + ...range(0x275f, 0x2760), + ...range(0x2795, 0x2797), + 0x27b0, + ...range(0x27bf, 0x27cf), + ...range(0x27ec, 0x27ef), + ...range(0x2b00, 0x2e7f), + 0x2e9a, + ...range(0x2ef4, 0x2eff), + ...range(0x2fd6, 0x2fef), + ...range(0x2ffc, 0x2fff), + 0x3040, + ...range(0x3097, 0x3098), + ...range(0x3100, 0x3104), + ...range(0x312d, 0x3130), + 0x318f, + ...range(0x31b8, 0x31ef), + ...range(0x321d, 0x321f), + ...range(0x3244, 0x3250), + ...range(0x327c, 0x327e), + ...range(0x32cc, 0x32cf), + 0x32ff, + ...range(0x3377, 0x337a), + ...range(0x33de, 0x33df), + 0x33ff, + ...range(0x4db6, 0x4dff), + ...range(0x9fa6, 0x9fff), + ...range(0xa48d, 0xa48f), + ...range(0xa4c7, 0xabff), + ...range(0xd7a4, 0xd7ff), + ...range(0xfa2e, 0xfa2f), + ...range(0xfa6b, 0xfaff), + ...range(0xfb07, 0xfb12), + ...range(0xfb18, 0xfb1c), + 0xfb37, + 0xfb3d, + 0xfb3f, + 0xfb42, + 0xfb45, + ...range(0xfbb2, 0xfbd2), + ...range(0xfd40, 0xfd4f), + ...range(0xfd90, 0xfd91), + ...range(0xfdc8, 0xfdcf), + ...range(0xfdfd, 0xfdff), + ...range(0xfe10, 0xfe1f), + ...range(0xfe24, 0xfe2f), + ...range(0xfe47, 0xfe48), + 0xfe53, + 0xfe67, + ...range(0xfe6c, 0xfe6f), + 0xfe75, + ...range(0xfefd, 0xfefe), + 0xff00, + ...range(0xffbf, 0xffc1), + ...range(0xffc8, 0xffc9), + ...range(0xffd0, 0xffd1), + ...range(0xffd8, 0xffd9), + ...range(0xffdd, 0xffdf), + 0xffe7, + ...range(0xffef, 0xfff8), + ...range(0x10000, 0x102ff), + 0x1031f, + ...range(0x10324, 0x1032f), + ...range(0x1034b, 0x103ff), + ...range(0x10426, 0x10427), + ...range(0x1044e, 0x1cfff), + ...range(0x1d0f6, 0x1d0ff), + ...range(0x1d127, 0x1d129), + ...range(0x1d1de, 0x1d3ff), + 0x1d455, + 0x1d49d, + ...range(0x1d4a0, 0x1d4a1), + ...range(0x1d4a3, 0x1d4a4), + ...range(0x1d4a7, 0x1d4a8), + 0x1d4ad, + 0x1d4ba, + 0x1d4bc, + 0x1d4c1, + 0x1d4c4, + 0x1d506, + ...range(0x1d50b, 0x1d50c), + 0x1d515, + 0x1d51d, + 0x1d53a, + 0x1d53f, + 0x1d545, + ...range(0x1d547, 0x1d549), + 0x1d551, + ...range(0x1d6a4, 0x1d6a7), + ...range(0x1d7ca, 0x1d7cd), + ...range(0x1d800, 0x1fffd), + ...range(0x2a6d7, 0x2f7ff), + ...range(0x2fa1e, 0x2fffd), + ...range(0x30000, 0x3fffd), + ...range(0x40000, 0x4fffd), + ...range(0x50000, 0x5fffd), + ...range(0x60000, 0x6fffd), + ...range(0x70000, 0x7fffd), + ...range(0x80000, 0x8fffd), + ...range(0x90000, 0x9fffd), + ...range(0xa0000, 0xafffd), + ...range(0xb0000, 0xbfffd), + ...range(0xc0000, 0xcfffd), + ...range(0xd0000, 0xdfffd), + 0xe0000, + ...range(0xe0002, 0xe001f), + ...range(0xe0080, 0xefffd), +]); + +/** + * B.1 Commonly mapped to nothing + * @link https://tools.ietf.org/html/rfc3454#appendix-B.1 + */ +const commonly_mapped_to_nothing = new Set([ + 0x00ad, + 0x034f, + 0x1806, + 0x180b, + 0x180c, + 0x180d, + 0x200b, + 0x200c, + 0x200d, + 0x2060, + 0xfe00, + 0xfe01, + 0xfe02, + 0xfe03, + 0xfe04, + 0xfe05, + 0xfe06, + 0xfe07, + 0xfe08, + 0xfe09, + 0xfe0a, + 0xfe0b, + 0xfe0c, + 0xfe0d, + 0xfe0e, + 0xfe0f, + 0xfeff, +]); + +/** + * C.1.2 Non-ASCII space characters + * @link https://tools.ietf.org/html/rfc3454#appendix-C.1.2 + */ +const non_ASCII_space_characters = new Set([ + 0x00a0 /* NO-BREAK SPACE */, + 0x1680 /* OGHAM SPACE MARK */, + 0x2000 /* EN QUAD */, + 0x2001 /* EM QUAD */, + 0x2002 /* EN SPACE */, + 0x2003 /* EM SPACE */, + 0x2004 /* THREE-PER-EM SPACE */, + 0x2005 /* FOUR-PER-EM SPACE */, + 0x2006 /* SIX-PER-EM SPACE */, + 0x2007 /* FIGURE SPACE */, + 0x2008 /* PUNCTUATION SPACE */, + 0x2009 /* THIN SPACE */, + 0x200a /* HAIR SPACE */, + 0x200b /* ZERO WIDTH SPACE */, + 0x202f /* NARROW NO-BREAK SPACE */, + 0x205f /* MEDIUM MATHEMATICAL SPACE */, + 0x3000 /* IDEOGRAPHIC SPACE */, +]); + +/** + * 2.3. Prohibited Output + * @type {Set} + */ +const prohibited_characters = new Set([ + ...non_ASCII_space_characters, + + /** + * C.2.1 ASCII control characters + * @link https://tools.ietf.org/html/rfc3454#appendix-C.2.1 + */ + ...range(0, 0x001f) /* [CONTROL CHARACTERS] */, + 0x007f /* DELETE */, + + /** + * C.2.2 Non-ASCII control characters + * @link https://tools.ietf.org/html/rfc3454#appendix-C.2.2 + */ + ...range(0x0080, 0x009f) /* [CONTROL CHARACTERS] */, + 0x06dd /* ARABIC END OF AYAH */, + 0x070f /* SYRIAC ABBREVIATION MARK */, + 0x180e /* MONGOLIAN VOWEL SEPARATOR */, + 0x200c /* ZERO WIDTH NON-JOINER */, + 0x200d /* ZERO WIDTH JOINER */, + 0x2028 /* LINE SEPARATOR */, + 0x2029 /* PARAGRAPH SEPARATOR */, + 0x2060 /* WORD JOINER */, + 0x2061 /* FUNCTION APPLICATION */, + 0x2062 /* INVISIBLE TIMES */, + 0x2063 /* INVISIBLE SEPARATOR */, + ...range(0x206a, 0x206f) /* [CONTROL CHARACTERS] */, + 0xfeff /* ZERO WIDTH NO-BREAK SPACE */, + ...range(0xfff9, 0xfffc) /* [CONTROL CHARACTERS] */, + ...range(0x1d173, 0x1d17a) /* [MUSICAL CONTROL CHARACTERS] */, + + /** + * C.3 Private use + * @link https://tools.ietf.org/html/rfc3454#appendix-C.3 + */ + ...range(0xe000, 0xf8ff) /* [PRIVATE USE, PLANE 0] */, + ...range(0xf0000, 0xffffd) /* [PRIVATE USE, PLANE 15] */, + ...range(0x100000, 0x10fffd) /* [PRIVATE USE, PLANE 16] */, + + /** + * C.4 Non-character code points + * @link https://tools.ietf.org/html/rfc3454#appendix-C.4 + */ + ...range(0xfdd0, 0xfdef) /* [NONCHARACTER CODE POINTS] */, + ...range(0xfffe, 0xffff) /* [NONCHARACTER CODE POINTS] */, + ...range(0x1fffe, 0x1ffff) /* [NONCHARACTER CODE POINTS] */, + ...range(0x2fffe, 0x2ffff) /* [NONCHARACTER CODE POINTS] */, + ...range(0x3fffe, 0x3ffff) /* [NONCHARACTER CODE POINTS] */, + ...range(0x4fffe, 0x4ffff) /* [NONCHARACTER CODE POINTS] */, + ...range(0x5fffe, 0x5ffff) /* [NONCHARACTER CODE POINTS] */, + ...range(0x6fffe, 0x6ffff) /* [NONCHARACTER CODE POINTS] */, + ...range(0x7fffe, 0x7ffff) /* [NONCHARACTER CODE POINTS] */, + ...range(0x8fffe, 0x8ffff) /* [NONCHARACTER CODE POINTS] */, + ...range(0x9fffe, 0x9ffff) /* [NONCHARACTER CODE POINTS] */, + ...range(0xafffe, 0xaffff) /* [NONCHARACTER CODE POINTS] */, + ...range(0xbfffe, 0xbffff) /* [NONCHARACTER CODE POINTS] */, + ...range(0xcfffe, 0xcffff) /* [NONCHARACTER CODE POINTS] */, + ...range(0xdfffe, 0xdffff) /* [NONCHARACTER CODE POINTS] */, + ...range(0xefffe, 0xeffff) /* [NONCHARACTER CODE POINTS] */, + ...range(0x10fffe, 0x10ffff) /* [NONCHARACTER CODE POINTS] */, + + /** + * C.5 Surrogate codes + * @link https://tools.ietf.org/html/rfc3454#appendix-C.5 + */ + ...range(0xd800, 0xdfff), + + /** + * C.6 Inappropriate for plain text + * @link https://tools.ietf.org/html/rfc3454#appendix-C.6 + */ + 0xfff9 /* INTERLINEAR ANNOTATION ANCHOR */, + 0xfffa /* INTERLINEAR ANNOTATION SEPARATOR */, + 0xfffb /* INTERLINEAR ANNOTATION TERMINATOR */, + 0xfffc /* OBJECT REPLACEMENT CHARACTER */, + 0xfffd /* REPLACEMENT CHARACTER */, + + /** + * C.7 Inappropriate for canonical representation + * @link https://tools.ietf.org/html/rfc3454#appendix-C.7 + */ + ...range(0x2ff0, 0x2ffb) /* [IDEOGRAPHIC DESCRIPTION CHARACTERS] */, + + /** + * C.8 Change display properties or are deprecated + * @link https://tools.ietf.org/html/rfc3454#appendix-C.8 + */ + 0x0340 /* COMBINING GRAVE TONE MARK */, + 0x0341 /* COMBINING ACUTE TONE MARK */, + 0x200e /* LEFT-TO-RIGHT MARK */, + 0x200f /* RIGHT-TO-LEFT MARK */, + 0x202a /* LEFT-TO-RIGHT EMBEDDING */, + 0x202b /* RIGHT-TO-LEFT EMBEDDING */, + 0x202c /* POP DIRECTIONAL FORMATTING */, + 0x202d /* LEFT-TO-RIGHT OVERRIDE */, + 0x202e /* RIGHT-TO-LEFT OVERRIDE */, + 0x206a /* INHIBIT SYMMETRIC SWAPPING */, + 0x206b /* ACTIVATE SYMMETRIC SWAPPING */, + 0x206c /* INHIBIT ARABIC FORM SHAPING */, + 0x206d /* ACTIVATE ARABIC FORM SHAPING */, + 0x206e /* NATIONAL DIGIT SHAPES */, + 0x206f /* NOMINAL DIGIT SHAPES */, + + /** + * C.9 Tagging characters + * @link https://tools.ietf.org/html/rfc3454#appendix-C.9 + */ + 0xe0001 /* LANGUAGE TAG */, + ...range(0xe0020, 0xe007f) /* [TAGGING CHARACTERS] */, +]); + +/** + * D.1 Characters with bidirectional property "R" or "AL" + * @link https://tools.ietf.org/html/rfc3454#appendix-D.1 + */ +const bidirectional_r_al = new Set([ + 0x05be, + 0x05c0, + 0x05c3, + ...range(0x05d0, 0x05ea), + ...range(0x05f0, 0x05f4), + 0x061b, + 0x061f, + ...range(0x0621, 0x063a), + ...range(0x0640, 0x064a), + ...range(0x066d, 0x066f), + ...range(0x0671, 0x06d5), + 0x06dd, + ...range(0x06e5, 0x06e6), + ...range(0x06fa, 0x06fe), + ...range(0x0700, 0x070d), + 0x0710, + ...range(0x0712, 0x072c), + ...range(0x0780, 0x07a5), + 0x07b1, + 0x200f, + 0xfb1d, + ...range(0xfb1f, 0xfb28), + ...range(0xfb2a, 0xfb36), + ...range(0xfb38, 0xfb3c), + 0xfb3e, + ...range(0xfb40, 0xfb41), + ...range(0xfb43, 0xfb44), + ...range(0xfb46, 0xfbb1), + ...range(0xfbd3, 0xfd3d), + ...range(0xfd50, 0xfd8f), + ...range(0xfd92, 0xfdc7), + ...range(0xfdf0, 0xfdfc), + ...range(0xfe70, 0xfe74), + ...range(0xfe76, 0xfefc), +]); + +/** + * D.2 Characters with bidirectional property "L" + * @link https://tools.ietf.org/html/rfc3454#appendix-D.2 + */ +const bidirectional_l = new Set([ + ...range(0x0041, 0x005a), + ...range(0x0061, 0x007a), + 0x00aa, + 0x00b5, + 0x00ba, + ...range(0x00c0, 0x00d6), + ...range(0x00d8, 0x00f6), + ...range(0x00f8, 0x0220), + ...range(0x0222, 0x0233), + ...range(0x0250, 0x02ad), + ...range(0x02b0, 0x02b8), + ...range(0x02bb, 0x02c1), + ...range(0x02d0, 0x02d1), + ...range(0x02e0, 0x02e4), + 0x02ee, + 0x037a, + 0x0386, + ...range(0x0388, 0x038a), + 0x038c, + ...range(0x038e, 0x03a1), + ...range(0x03a3, 0x03ce), + ...range(0x03d0, 0x03f5), + ...range(0x0400, 0x0482), + ...range(0x048a, 0x04ce), + ...range(0x04d0, 0x04f5), + ...range(0x04f8, 0x04f9), + ...range(0x0500, 0x050f), + ...range(0x0531, 0x0556), + ...range(0x0559, 0x055f), + ...range(0x0561, 0x0587), + 0x0589, + 0x0903, + ...range(0x0905, 0x0939), + ...range(0x093d, 0x0940), + ...range(0x0949, 0x094c), + 0x0950, + ...range(0x0958, 0x0961), + ...range(0x0964, 0x0970), + ...range(0x0982, 0x0983), + ...range(0x0985, 0x098c), + ...range(0x098f, 0x0990), + ...range(0x0993, 0x09a8), + ...range(0x09aa, 0x09b0), + 0x09b2, + ...range(0x09b6, 0x09b9), + ...range(0x09be, 0x09c0), + ...range(0x09c7, 0x09c8), + ...range(0x09cb, 0x09cc), + 0x09d7, + ...range(0x09dc, 0x09dd), + ...range(0x09df, 0x09e1), + ...range(0x09e6, 0x09f1), + ...range(0x09f4, 0x09fa), + ...range(0x0a05, 0x0a0a), + ...range(0x0a0f, 0x0a10), + ...range(0x0a13, 0x0a28), + ...range(0x0a2a, 0x0a30), + ...range(0x0a32, 0x0a33), + ...range(0x0a35, 0x0a36), + ...range(0x0a38, 0x0a39), + ...range(0x0a3e, 0x0a40), + ...range(0x0a59, 0x0a5c), + 0x0a5e, + ...range(0x0a66, 0x0a6f), + ...range(0x0a72, 0x0a74), + 0x0a83, + ...range(0x0a85, 0x0a8b), + 0x0a8d, + ...range(0x0a8f, 0x0a91), + ...range(0x0a93, 0x0aa8), + ...range(0x0aaa, 0x0ab0), + ...range(0x0ab2, 0x0ab3), + ...range(0x0ab5, 0x0ab9), + ...range(0x0abd, 0x0ac0), + 0x0ac9, + ...range(0x0acb, 0x0acc), + 0x0ad0, + 0x0ae0, + ...range(0x0ae6, 0x0aef), + ...range(0x0b02, 0x0b03), + ...range(0x0b05, 0x0b0c), + ...range(0x0b0f, 0x0b10), + ...range(0x0b13, 0x0b28), + ...range(0x0b2a, 0x0b30), + ...range(0x0b32, 0x0b33), + ...range(0x0b36, 0x0b39), + ...range(0x0b3d, 0x0b3e), + 0x0b40, + ...range(0x0b47, 0x0b48), + ...range(0x0b4b, 0x0b4c), + 0x0b57, + ...range(0x0b5c, 0x0b5d), + ...range(0x0b5f, 0x0b61), + ...range(0x0b66, 0x0b70), + 0x0b83, + ...range(0x0b85, 0x0b8a), + ...range(0x0b8e, 0x0b90), + ...range(0x0b92, 0x0b95), + ...range(0x0b99, 0x0b9a), + 0x0b9c, + ...range(0x0b9e, 0x0b9f), + ...range(0x0ba3, 0x0ba4), + ...range(0x0ba8, 0x0baa), + ...range(0x0bae, 0x0bb5), + ...range(0x0bb7, 0x0bb9), + ...range(0x0bbe, 0x0bbf), + ...range(0x0bc1, 0x0bc2), + ...range(0x0bc6, 0x0bc8), + ...range(0x0bca, 0x0bcc), + 0x0bd7, + ...range(0x0be7, 0x0bf2), + ...range(0x0c01, 0x0c03), + ...range(0x0c05, 0x0c0c), + ...range(0x0c0e, 0x0c10), + ...range(0x0c12, 0x0c28), + ...range(0x0c2a, 0x0c33), + ...range(0x0c35, 0x0c39), + ...range(0x0c41, 0x0c44), + ...range(0x0c60, 0x0c61), + ...range(0x0c66, 0x0c6f), + ...range(0x0c82, 0x0c83), + ...range(0x0c85, 0x0c8c), + ...range(0x0c8e, 0x0c90), + ...range(0x0c92, 0x0ca8), + ...range(0x0caa, 0x0cb3), + ...range(0x0cb5, 0x0cb9), + 0x0cbe, + ...range(0x0cc0, 0x0cc4), + ...range(0x0cc7, 0x0cc8), + ...range(0x0cca, 0x0ccb), + ...range(0x0cd5, 0x0cd6), + 0x0cde, + ...range(0x0ce0, 0x0ce1), + ...range(0x0ce6, 0x0cef), + ...range(0x0d02, 0x0d03), + ...range(0x0d05, 0x0d0c), + ...range(0x0d0e, 0x0d10), + ...range(0x0d12, 0x0d28), + ...range(0x0d2a, 0x0d39), + ...range(0x0d3e, 0x0d40), + ...range(0x0d46, 0x0d48), + ...range(0x0d4a, 0x0d4c), + 0x0d57, + ...range(0x0d60, 0x0d61), + ...range(0x0d66, 0x0d6f), + ...range(0x0d82, 0x0d83), + ...range(0x0d85, 0x0d96), + ...range(0x0d9a, 0x0db1), + ...range(0x0db3, 0x0dbb), + 0x0dbd, + ...range(0x0dc0, 0x0dc6), + ...range(0x0dcf, 0x0dd1), + ...range(0x0dd8, 0x0ddf), + ...range(0x0df2, 0x0df4), + ...range(0x0e01, 0x0e30), + ...range(0x0e32, 0x0e33), + ...range(0x0e40, 0x0e46), + ...range(0x0e4f, 0x0e5b), + ...range(0x0e81, 0x0e82), + 0x0e84, + ...range(0x0e87, 0x0e88), + 0x0e8a, + 0x0e8d, + ...range(0x0e94, 0x0e97), + ...range(0x0e99, 0x0e9f), + ...range(0x0ea1, 0x0ea3), + 0x0ea5, + 0x0ea7, + ...range(0x0eaa, 0x0eab), + ...range(0x0ead, 0x0eb0), + ...range(0x0eb2, 0x0eb3), + 0x0ebd, + ...range(0x0ec0, 0x0ec4), + 0x0ec6, + ...range(0x0ed0, 0x0ed9), + ...range(0x0edc, 0x0edd), + ...range(0x0f00, 0x0f17), + ...range(0x0f1a, 0x0f34), + 0x0f36, + 0x0f38, + ...range(0x0f3e, 0x0f47), + ...range(0x0f49, 0x0f6a), + 0x0f7f, + 0x0f85, + ...range(0x0f88, 0x0f8b), + ...range(0x0fbe, 0x0fc5), + ...range(0x0fc7, 0x0fcc), + 0x0fcf, + ...range(0x1000, 0x1021), + ...range(0x1023, 0x1027), + ...range(0x1029, 0x102a), + 0x102c, + 0x1031, + 0x1038, + ...range(0x1040, 0x1057), + ...range(0x10a0, 0x10c5), + ...range(0x10d0, 0x10f8), + 0x10fb, + ...range(0x1100, 0x1159), + ...range(0x115f, 0x11a2), + ...range(0x11a8, 0x11f9), + ...range(0x1200, 0x1206), + ...range(0x1208, 0x1246), + 0x1248, + ...range(0x124a, 0x124d), + ...range(0x1250, 0x1256), + 0x1258, + ...range(0x125a, 0x125d), + ...range(0x1260, 0x1286), + 0x1288, + ...range(0x128a, 0x128d), + ...range(0x1290, 0x12ae), + 0x12b0, + ...range(0x12b2, 0x12b5), + ...range(0x12b8, 0x12be), + 0x12c0, + ...range(0x12c2, 0x12c5), + ...range(0x12c8, 0x12ce), + ...range(0x12d0, 0x12d6), + ...range(0x12d8, 0x12ee), + ...range(0x12f0, 0x130e), + 0x1310, + ...range(0x1312, 0x1315), + ...range(0x1318, 0x131e), + ...range(0x1320, 0x1346), + ...range(0x1348, 0x135a), + ...range(0x1361, 0x137c), + ...range(0x13a0, 0x13f4), + ...range(0x1401, 0x1676), + ...range(0x1681, 0x169a), + ...range(0x16a0, 0x16f0), + ...range(0x1700, 0x170c), + ...range(0x170e, 0x1711), + ...range(0x1720, 0x1731), + ...range(0x1735, 0x1736), + ...range(0x1740, 0x1751), + ...range(0x1760, 0x176c), + ...range(0x176e, 0x1770), + ...range(0x1780, 0x17b6), + ...range(0x17be, 0x17c5), + ...range(0x17c7, 0x17c8), + ...range(0x17d4, 0x17da), + 0x17dc, + ...range(0x17e0, 0x17e9), + ...range(0x1810, 0x1819), + ...range(0x1820, 0x1877), + ...range(0x1880, 0x18a8), + ...range(0x1e00, 0x1e9b), + ...range(0x1ea0, 0x1ef9), + ...range(0x1f00, 0x1f15), + ...range(0x1f18, 0x1f1d), + ...range(0x1f20, 0x1f45), + ...range(0x1f48, 0x1f4d), + ...range(0x1f50, 0x1f57), + 0x1f59, + 0x1f5b, + 0x1f5d, + ...range(0x1f5f, 0x1f7d), + ...range(0x1f80, 0x1fb4), + ...range(0x1fb6, 0x1fbc), + 0x1fbe, + ...range(0x1fc2, 0x1fc4), + ...range(0x1fc6, 0x1fcc), + ...range(0x1fd0, 0x1fd3), + ...range(0x1fd6, 0x1fdb), + ...range(0x1fe0, 0x1fec), + ...range(0x1ff2, 0x1ff4), + ...range(0x1ff6, 0x1ffc), + 0x200e, + 0x2071, + 0x207f, + 0x2102, + 0x2107, + ...range(0x210a, 0x2113), + 0x2115, + ...range(0x2119, 0x211d), + 0x2124, + 0x2126, + 0x2128, + ...range(0x212a, 0x212d), + ...range(0x212f, 0x2131), + ...range(0x2133, 0x2139), + ...range(0x213d, 0x213f), + ...range(0x2145, 0x2149), + ...range(0x2160, 0x2183), + ...range(0x2336, 0x237a), + 0x2395, + ...range(0x249c, 0x24e9), + ...range(0x3005, 0x3007), + ...range(0x3021, 0x3029), + ...range(0x3031, 0x3035), + ...range(0x3038, 0x303c), + ...range(0x3041, 0x3096), + ...range(0x309d, 0x309f), + ...range(0x30a1, 0x30fa), + ...range(0x30fc, 0x30ff), + ...range(0x3105, 0x312c), + ...range(0x3131, 0x318e), + ...range(0x3190, 0x31b7), + ...range(0x31f0, 0x321c), + ...range(0x3220, 0x3243), + ...range(0x3260, 0x327b), + ...range(0x327f, 0x32b0), + ...range(0x32c0, 0x32cb), + ...range(0x32d0, 0x32fe), + ...range(0x3300, 0x3376), + ...range(0x337b, 0x33dd), + ...range(0x33e0, 0x33fe), + ...range(0x3400, 0x4db5), + ...range(0x4e00, 0x9fa5), + ...range(0xa000, 0xa48c), + ...range(0xac00, 0xd7a3), + ...range(0xd800, 0xfa2d), + ...range(0xfa30, 0xfa6a), + ...range(0xfb00, 0xfb06), + ...range(0xfb13, 0xfb17), + ...range(0xff21, 0xff3a), + ...range(0xff41, 0xff5a), + ...range(0xff66, 0xffbe), + ...range(0xffc2, 0xffc7), + ...range(0xffca, 0xffcf), + ...range(0xffd2, 0xffd7), + ...range(0xffda, 0xffdc), + ...range(0x10300, 0x1031e), + ...range(0x10320, 0x10323), + ...range(0x10330, 0x1034a), + ...range(0x10400, 0x10425), + ...range(0x10428, 0x1044d), + ...range(0x1d000, 0x1d0f5), + ...range(0x1d100, 0x1d126), + ...range(0x1d12a, 0x1d166), + ...range(0x1d16a, 0x1d172), + ...range(0x1d183, 0x1d184), + ...range(0x1d18c, 0x1d1a9), + ...range(0x1d1ae, 0x1d1dd), + ...range(0x1d400, 0x1d454), + ...range(0x1d456, 0x1d49c), + ...range(0x1d49e, 0x1d49f), + 0x1d4a2, + ...range(0x1d4a5, 0x1d4a6), + ...range(0x1d4a9, 0x1d4ac), + ...range(0x1d4ae, 0x1d4b9), + 0x1d4bb, + ...range(0x1d4bd, 0x1d4c0), + ...range(0x1d4c2, 0x1d4c3), + ...range(0x1d4c5, 0x1d505), + ...range(0x1d507, 0x1d50a), + ...range(0x1d50d, 0x1d514), + ...range(0x1d516, 0x1d51c), + ...range(0x1d51e, 0x1d539), + ...range(0x1d53b, 0x1d53e), + ...range(0x1d540, 0x1d544), + 0x1d546, + ...range(0x1d54a, 0x1d550), + ...range(0x1d552, 0x1d6a3), + ...range(0x1d6a8, 0x1d7c9), + ...range(0x20000, 0x2a6d6), + ...range(0x2f800, 0x2fa1d), + ...range(0xf0000, 0xffffd), + ...range(0x100000, 0x10fffd), +]); + +module.exports = { + unassigned_code_points, + commonly_mapped_to_nothing, + non_ASCII_space_characters, + prohibited_characters, + bidirectional_r_al, + bidirectional_l, +}; diff --git a/scripts/node_modules/saslprep/lib/memory-code-points.js b/scripts/node_modules/saslprep/lib/memory-code-points.js new file mode 100644 index 00000000..cb0289c8 --- /dev/null +++ b/scripts/node_modules/saslprep/lib/memory-code-points.js @@ -0,0 +1,39 @@ +'use strict'; + +const fs = require('fs'); +const path = require('path'); +const bitfield = require('sparse-bitfield'); + +/* eslint-disable-next-line security/detect-non-literal-fs-filename */ +const memory = fs.readFileSync(path.resolve(__dirname, '../code-points.mem')); +let offset = 0; + +/** + * Loads each code points sequence from buffer. + * @returns {bitfield} + */ +function read() { + const size = memory.readUInt32BE(offset); + offset += 4; + + const codepoints = memory.slice(offset, offset + size); + offset += size; + + return bitfield({ buffer: codepoints }); +} + +const unassigned_code_points = read(); +const commonly_mapped_to_nothing = read(); +const non_ASCII_space_characters = read(); +const prohibited_characters = read(); +const bidirectional_r_al = read(); +const bidirectional_l = read(); + +module.exports = { + unassigned_code_points, + commonly_mapped_to_nothing, + non_ASCII_space_characters, + prohibited_characters, + bidirectional_r_al, + bidirectional_l, +}; diff --git a/scripts/node_modules/saslprep/lib/util.js b/scripts/node_modules/saslprep/lib/util.js new file mode 100644 index 00000000..506bdc99 --- /dev/null +++ b/scripts/node_modules/saslprep/lib/util.js @@ -0,0 +1,21 @@ +'use strict'; + +/** + * Create an array of numbers. + * @param {number} from + * @param {number} to + * @returns {number[]} + */ +function range(from, to) { + // TODO: make this inlined. + const list = new Array(to - from + 1); + + for (let i = 0; i < list.length; i += 1) { + list[i] = from + i; + } + return list; +} + +module.exports = { + range, +}; diff --git a/scripts/node_modules/saslprep/package.json b/scripts/node_modules/saslprep/package.json new file mode 100644 index 00000000..8d894e04 --- /dev/null +++ b/scripts/node_modules/saslprep/package.json @@ -0,0 +1,100 @@ +{ + "_from": "saslprep@^1.0.0", + "_id": "saslprep@1.0.3", + "_inBundle": false, + "_integrity": "sha512-/MY/PEMbk2SuY5sScONwhUDsV2p77Znkb/q3nSVstq/yQzYJOH/Azh29p9oJLsl3LnQwSvZDKagDGBsBwSooag==", + "_location": "/saslprep", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "saslprep@^1.0.0", + "name": "saslprep", + "escapedName": "saslprep", + "rawSpec": "^1.0.0", + "saveSpec": null, + "fetchSpec": "^1.0.0" + }, + "_requiredBy": [ + "/mongodb" + ], + "_resolved": "https://registry.npmjs.org/saslprep/-/saslprep-1.0.3.tgz", + "_shasum": "4c02f946b56cf54297e347ba1093e7acac4cf226", + "_spec": "saslprep@^1.0.0", + "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/node_modules/mongodb", + "author": { + "name": "Dmitry Tsvettsikh", + "email": "me@reklatsmasters.com" + }, + "bugs": { + "url": "https://github.com/reklatsmasters/saslprep/issues" + }, + "bundleDependencies": false, + "dependencies": { + "sparse-bitfield": "^3.0.3" + }, + "deprecated": false, + "description": "SASLprep: Stringprep Profile for User Names and Passwords, rfc4013.", + "devDependencies": { + "@nodertc/eslint-config": "^0.2.1", + "eslint": "^5.16.0", + "jest": "^23.6.0", + "prettier": "^1.14.3" + }, + "engines": { + "node": ">=6" + }, + "eslintConfig": { + "extends": "@nodertc", + "rules": { + "camelcase": "off", + "no-continue": "off" + }, + "overrides": [ + { + "files": [ + "test/*.js" + ], + "env": { + "jest": true + }, + "rules": { + "require-jsdoc": "off" + } + } + ] + }, + "homepage": "https://github.com/reklatsmasters/saslprep#readme", + "jest": { + "modulePaths": [ + "" + ], + "testMatch": [ + "**/test/*.js" + ], + "testPathIgnorePatterns": [ + "/node_modules/" + ] + }, + "keywords": [ + "sasl", + "saslprep", + "stringprep", + "rfc4013", + "4013" + ], + "license": "MIT", + "main": "index.js", + "name": "saslprep", + "repository": { + "type": "git", + "url": "git+https://github.com/reklatsmasters/saslprep.git" + }, + "scripts": { + "gen-code-points": "node generate-code-points.js > code-points.mem", + "lint": "npx eslint --quiet .", + "test": "npm run lint && npm run unit-test", + "unit-test": "npx jest" + }, + "version": "1.0.3" +} diff --git a/scripts/node_modules/saslprep/readme.md b/scripts/node_modules/saslprep/readme.md new file mode 100644 index 00000000..8ff3d70d --- /dev/null +++ b/scripts/node_modules/saslprep/readme.md @@ -0,0 +1,31 @@ +# saslprep +[![Build Status](https://travis-ci.org/reklatsmasters/saslprep.svg?branch=master)](https://travis-ci.org/reklatsmasters/saslprep) +[![npm](https://img.shields.io/npm/v/saslprep.svg)](https://npmjs.org/package/saslprep) +[![node](https://img.shields.io/node/v/saslprep.svg)](https://npmjs.org/package/saslprep) +[![license](https://img.shields.io/npm/l/saslprep.svg)](https://npmjs.org/package/saslprep) +[![downloads](https://img.shields.io/npm/dm/saslprep.svg)](https://npmjs.org/package/saslprep) + +Stringprep Profile for User Names and Passwords, [rfc4013](https://tools.ietf.org/html/rfc4013) + +### Usage + +```js +const saslprep = require('saslprep') + +saslprep('password\u00AD') // password +saslprep('password\u0007') // Error: prohibited character +``` + +### API + +##### `saslprep(input: String, opts: Options): String` + +Normalize user name or password. + +##### `Options.allowUnassigned: bool` + +A special behavior for unassigned code points, see https://tools.ietf.org/html/rfc4013#section-2.5. Disabled by default. + +## License + +MIT, 2017-2019 (c) Dmitriy Tsvettsikh diff --git a/scripts/node_modules/saslprep/test/index.js b/scripts/node_modules/saslprep/test/index.js new file mode 100644 index 00000000..80c71af5 --- /dev/null +++ b/scripts/node_modules/saslprep/test/index.js @@ -0,0 +1,76 @@ +'use strict'; + +const saslprep = require('..'); + +const chr = String.fromCodePoint; + +test('should work with liatin letters', () => { + const str = 'user'; + expect(saslprep(str)).toEqual(str); +}); + +test('should work be case preserved', () => { + const str = 'USER'; + expect(saslprep(str)).toEqual(str); +}); + +test('should work with high code points (> U+FFFF)', () => { + const str = '\uD83D\uDE00'; + expect(saslprep(str, { allowUnassigned: true })).toEqual(str); +}); + +test('should remove `mapped to nothing` characters', () => { + expect(saslprep('I\u00ADX')).toEqual('IX'); +}); + +test('should replace `Non-ASCII space characters` with space', () => { + expect(saslprep('a\u00A0b')).toEqual('a\u0020b'); +}); + +test('should normalize as NFKC', () => { + expect(saslprep('\u00AA')).toEqual('a'); + expect(saslprep('\u2168')).toEqual('IX'); +}); + +test('should throws when prohibited characters', () => { + // C.2.1 ASCII control characters + expect(() => saslprep('a\u007Fb')).toThrow(); + + // C.2.2 Non-ASCII control characters + expect(() => saslprep('a\u06DDb')).toThrow(); + + // C.3 Private use + expect(() => saslprep('a\uE000b')).toThrow(); + + // C.4 Non-character code points + expect(() => saslprep(`a${chr(0x1fffe)}b`)).toThrow(); + + // C.5 Surrogate codes + expect(() => saslprep('a\uD800b')).toThrow(); + + // C.6 Inappropriate for plain text + expect(() => saslprep('a\uFFF9b')).toThrow(); + + // C.7 Inappropriate for canonical representation + expect(() => saslprep('a\u2FF0b')).toThrow(); + + // C.8 Change display properties or are deprecated + expect(() => saslprep('a\u200Eb')).toThrow(); + + // C.9 Tagging characters + expect(() => saslprep(`a${chr(0xe0001)}b`)).toThrow(); +}); + +test('should not containt RandALCat and LCat bidi', () => { + expect(() => saslprep('a\u06DD\u00AAb')).toThrow(); +}); + +test('RandALCat should be first and last', () => { + expect(() => saslprep('\u0627\u0031\u0628')).not.toThrow(); + expect(() => saslprep('\u0627\u0031')).toThrow(); +}); + +test('should handle unassigned code points', () => { + expect(() => saslprep('a\u0487')).toThrow(); + expect(() => saslprep('a\u0487', { allowUnassigned: true })).not.toThrow(); +}); diff --git a/scripts/node_modules/saslprep/test/util.js b/scripts/node_modules/saslprep/test/util.js new file mode 100644 index 00000000..355db3f8 --- /dev/null +++ b/scripts/node_modules/saslprep/test/util.js @@ -0,0 +1,16 @@ +'use strict'; + +const { setFlagsFromString } = require('v8'); +const { range } = require('../lib/util'); + +// 984 by default. +setFlagsFromString('--stack_size=500'); + +test('should work', () => { + const list = range(1, 3); + expect(list).toEqual([1, 2, 3]); +}); + +test('should work for large ranges', () => { + expect(() => range(1, 1e6)).not.toThrow(); +}); diff --git a/scripts/node_modules/semver/CHANGELOG.md b/scripts/node_modules/semver/CHANGELOG.md new file mode 100644 index 00000000..66304fdd --- /dev/null +++ b/scripts/node_modules/semver/CHANGELOG.md @@ -0,0 +1,39 @@ +# changes log + +## 5.7 + +* Add `minVersion` method + +## 5.6 + +* Move boolean `loose` param to an options object, with + backwards-compatibility protection. +* Add ability to opt out of special prerelease version handling with + the `includePrerelease` option flag. + +## 5.5 + +* Add version coercion capabilities + +## 5.4 + +* Add intersection checking + +## 5.3 + +* Add `minSatisfying` method + +## 5.2 + +* Add `prerelease(v)` that returns prerelease components + +## 5.1 + +* Add Backus-Naur for ranges +* Remove excessively cute inspection methods + +## 5.0 + +* Remove AMD/Browserified build artifacts +* Fix ltr and gtr when using the `*` range +* Fix for range `*` with a prerelease identifier diff --git a/scripts/node_modules/semver/LICENSE b/scripts/node_modules/semver/LICENSE new file mode 100644 index 00000000..19129e31 --- /dev/null +++ b/scripts/node_modules/semver/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/scripts/node_modules/semver/README.md b/scripts/node_modules/semver/README.md new file mode 100644 index 00000000..f8dfa5a0 --- /dev/null +++ b/scripts/node_modules/semver/README.md @@ -0,0 +1,412 @@ +semver(1) -- The semantic versioner for npm +=========================================== + +## Install + +```bash +npm install --save semver +```` + +## Usage + +As a node module: + +```js +const semver = require('semver') + +semver.valid('1.2.3') // '1.2.3' +semver.valid('a.b.c') // null +semver.clean(' =v1.2.3 ') // '1.2.3' +semver.satisfies('1.2.3', '1.x || >=2.5.0 || 5.0.0 - 7.2.3') // true +semver.gt('1.2.3', '9.8.7') // false +semver.lt('1.2.3', '9.8.7') // true +semver.minVersion('>=1.0.0') // '1.0.0' +semver.valid(semver.coerce('v2')) // '2.0.0' +semver.valid(semver.coerce('42.6.7.9.3-alpha')) // '42.6.7' +``` + +As a command-line utility: + +``` +$ semver -h + +A JavaScript implementation of the https://semver.org/ specification +Copyright Isaac Z. Schlueter + +Usage: semver [options] [ [...]] +Prints valid versions sorted by SemVer precedence + +Options: +-r --range + Print versions that match the specified range. + +-i --increment [] + Increment a version by the specified level. Level can + be one of: major, minor, patch, premajor, preminor, + prepatch, or prerelease. Default level is 'patch'. + Only one version may be specified. + +--preid + Identifier to be used to prefix premajor, preminor, + prepatch or prerelease version increments. + +-l --loose + Interpret versions and ranges loosely + +-p --include-prerelease + Always include prerelease versions in range matching + +-c --coerce + Coerce a string into SemVer if possible + (does not imply --loose) + +Program exits successfully if any valid version satisfies +all supplied ranges, and prints all satisfying versions. + +If no satisfying versions are found, then exits failure. + +Versions are printed in ascending order, so supplying +multiple versions to the utility will just sort them. +``` + +## Versions + +A "version" is described by the `v2.0.0` specification found at +. + +A leading `"="` or `"v"` character is stripped off and ignored. + +## Ranges + +A `version range` is a set of `comparators` which specify versions +that satisfy the range. + +A `comparator` is composed of an `operator` and a `version`. The set +of primitive `operators` is: + +* `<` Less than +* `<=` Less than or equal to +* `>` Greater than +* `>=` Greater than or equal to +* `=` Equal. If no operator is specified, then equality is assumed, + so this operator is optional, but MAY be included. + +For example, the comparator `>=1.2.7` would match the versions +`1.2.7`, `1.2.8`, `2.5.3`, and `1.3.9`, but not the versions `1.2.6` +or `1.1.0`. + +Comparators can be joined by whitespace to form a `comparator set`, +which is satisfied by the **intersection** of all of the comparators +it includes. + +A range is composed of one or more comparator sets, joined by `||`. A +version matches a range if and only if every comparator in at least +one of the `||`-separated comparator sets is satisfied by the version. + +For example, the range `>=1.2.7 <1.3.0` would match the versions +`1.2.7`, `1.2.8`, and `1.2.99`, but not the versions `1.2.6`, `1.3.0`, +or `1.1.0`. + +The range `1.2.7 || >=1.2.9 <2.0.0` would match the versions `1.2.7`, +`1.2.9`, and `1.4.6`, but not the versions `1.2.8` or `2.0.0`. + +### Prerelease Tags + +If a version has a prerelease tag (for example, `1.2.3-alpha.3`) then +it will only be allowed to satisfy comparator sets if at least one +comparator with the same `[major, minor, patch]` tuple also has a +prerelease tag. + +For example, the range `>1.2.3-alpha.3` would be allowed to match the +version `1.2.3-alpha.7`, but it would *not* be satisfied by +`3.4.5-alpha.9`, even though `3.4.5-alpha.9` is technically "greater +than" `1.2.3-alpha.3` according to the SemVer sort rules. The version +range only accepts prerelease tags on the `1.2.3` version. The +version `3.4.5` *would* satisfy the range, because it does not have a +prerelease flag, and `3.4.5` is greater than `1.2.3-alpha.7`. + +The purpose for this behavior is twofold. First, prerelease versions +frequently are updated very quickly, and contain many breaking changes +that are (by the author's design) not yet fit for public consumption. +Therefore, by default, they are excluded from range matching +semantics. + +Second, a user who has opted into using a prerelease version has +clearly indicated the intent to use *that specific* set of +alpha/beta/rc versions. By including a prerelease tag in the range, +the user is indicating that they are aware of the risk. However, it +is still not appropriate to assume that they have opted into taking a +similar risk on the *next* set of prerelease versions. + +Note that this behavior can be suppressed (treating all prerelease +versions as if they were normal versions, for the purpose of range +matching) by setting the `includePrerelease` flag on the options +object to any +[functions](https://github.com/npm/node-semver#functions) that do +range matching. + +#### Prerelease Identifiers + +The method `.inc` takes an additional `identifier` string argument that +will append the value of the string as a prerelease identifier: + +```javascript +semver.inc('1.2.3', 'prerelease', 'beta') +// '1.2.4-beta.0' +``` + +command-line example: + +```bash +$ semver 1.2.3 -i prerelease --preid beta +1.2.4-beta.0 +``` + +Which then can be used to increment further: + +```bash +$ semver 1.2.4-beta.0 -i prerelease +1.2.4-beta.1 +``` + +### Advanced Range Syntax + +Advanced range syntax desugars to primitive comparators in +deterministic ways. + +Advanced ranges may be combined in the same way as primitive +comparators using white space or `||`. + +#### Hyphen Ranges `X.Y.Z - A.B.C` + +Specifies an inclusive set. + +* `1.2.3 - 2.3.4` := `>=1.2.3 <=2.3.4` + +If a partial version is provided as the first version in the inclusive +range, then the missing pieces are replaced with zeroes. + +* `1.2 - 2.3.4` := `>=1.2.0 <=2.3.4` + +If a partial version is provided as the second version in the +inclusive range, then all versions that start with the supplied parts +of the tuple are accepted, but nothing that would be greater than the +provided tuple parts. + +* `1.2.3 - 2.3` := `>=1.2.3 <2.4.0` +* `1.2.3 - 2` := `>=1.2.3 <3.0.0` + +#### X-Ranges `1.2.x` `1.X` `1.2.*` `*` + +Any of `X`, `x`, or `*` may be used to "stand in" for one of the +numeric values in the `[major, minor, patch]` tuple. + +* `*` := `>=0.0.0` (Any version satisfies) +* `1.x` := `>=1.0.0 <2.0.0` (Matching major version) +* `1.2.x` := `>=1.2.0 <1.3.0` (Matching major and minor versions) + +A partial version range is treated as an X-Range, so the special +character is in fact optional. + +* `""` (empty string) := `*` := `>=0.0.0` +* `1` := `1.x.x` := `>=1.0.0 <2.0.0` +* `1.2` := `1.2.x` := `>=1.2.0 <1.3.0` + +#### Tilde Ranges `~1.2.3` `~1.2` `~1` + +Allows patch-level changes if a minor version is specified on the +comparator. Allows minor-level changes if not. + +* `~1.2.3` := `>=1.2.3 <1.(2+1).0` := `>=1.2.3 <1.3.0` +* `~1.2` := `>=1.2.0 <1.(2+1).0` := `>=1.2.0 <1.3.0` (Same as `1.2.x`) +* `~1` := `>=1.0.0 <(1+1).0.0` := `>=1.0.0 <2.0.0` (Same as `1.x`) +* `~0.2.3` := `>=0.2.3 <0.(2+1).0` := `>=0.2.3 <0.3.0` +* `~0.2` := `>=0.2.0 <0.(2+1).0` := `>=0.2.0 <0.3.0` (Same as `0.2.x`) +* `~0` := `>=0.0.0 <(0+1).0.0` := `>=0.0.0 <1.0.0` (Same as `0.x`) +* `~1.2.3-beta.2` := `>=1.2.3-beta.2 <1.3.0` Note that prereleases in + the `1.2.3` version will be allowed, if they are greater than or + equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but + `1.2.4-beta.2` would not, because it is a prerelease of a + different `[major, minor, patch]` tuple. + +#### Caret Ranges `^1.2.3` `^0.2.5` `^0.0.4` + +Allows changes that do not modify the left-most non-zero digit in the +`[major, minor, patch]` tuple. In other words, this allows patch and +minor updates for versions `1.0.0` and above, patch updates for +versions `0.X >=0.1.0`, and *no* updates for versions `0.0.X`. + +Many authors treat a `0.x` version as if the `x` were the major +"breaking-change" indicator. + +Caret ranges are ideal when an author may make breaking changes +between `0.2.4` and `0.3.0` releases, which is a common practice. +However, it presumes that there will *not* be breaking changes between +`0.2.4` and `0.2.5`. It allows for changes that are presumed to be +additive (but non-breaking), according to commonly observed practices. + +* `^1.2.3` := `>=1.2.3 <2.0.0` +* `^0.2.3` := `>=0.2.3 <0.3.0` +* `^0.0.3` := `>=0.0.3 <0.0.4` +* `^1.2.3-beta.2` := `>=1.2.3-beta.2 <2.0.0` Note that prereleases in + the `1.2.3` version will be allowed, if they are greater than or + equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but + `1.2.4-beta.2` would not, because it is a prerelease of a + different `[major, minor, patch]` tuple. +* `^0.0.3-beta` := `>=0.0.3-beta <0.0.4` Note that prereleases in the + `0.0.3` version *only* will be allowed, if they are greater than or + equal to `beta`. So, `0.0.3-pr.2` would be allowed. + +When parsing caret ranges, a missing `patch` value desugars to the +number `0`, but will allow flexibility within that value, even if the +major and minor versions are both `0`. + +* `^1.2.x` := `>=1.2.0 <2.0.0` +* `^0.0.x` := `>=0.0.0 <0.1.0` +* `^0.0` := `>=0.0.0 <0.1.0` + +A missing `minor` and `patch` values will desugar to zero, but also +allow flexibility within those values, even if the major version is +zero. + +* `^1.x` := `>=1.0.0 <2.0.0` +* `^0.x` := `>=0.0.0 <1.0.0` + +### Range Grammar + +Putting all this together, here is a Backus-Naur grammar for ranges, +for the benefit of parser authors: + +```bnf +range-set ::= range ( logical-or range ) * +logical-or ::= ( ' ' ) * '||' ( ' ' ) * +range ::= hyphen | simple ( ' ' simple ) * | '' +hyphen ::= partial ' - ' partial +simple ::= primitive | partial | tilde | caret +primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial +partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? +xr ::= 'x' | 'X' | '*' | nr +nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * +tilde ::= '~' partial +caret ::= '^' partial +qualifier ::= ( '-' pre )? ( '+' build )? +pre ::= parts +build ::= parts +parts ::= part ( '.' part ) * +part ::= nr | [-0-9A-Za-z]+ +``` + +## Functions + +All methods and classes take a final `options` object argument. All +options in this object are `false` by default. The options supported +are: + +- `loose` Be more forgiving about not-quite-valid semver strings. + (Any resulting output will always be 100% strict compliant, of + course.) For backwards compatibility reasons, if the `options` + argument is a boolean value instead of an object, it is interpreted + to be the `loose` param. +- `includePrerelease` Set to suppress the [default + behavior](https://github.com/npm/node-semver#prerelease-tags) of + excluding prerelease tagged versions from ranges unless they are + explicitly opted into. + +Strict-mode Comparators and Ranges will be strict about the SemVer +strings that they parse. + +* `valid(v)`: Return the parsed version, or null if it's not valid. +* `inc(v, release)`: Return the version incremented by the release + type (`major`, `premajor`, `minor`, `preminor`, `patch`, + `prepatch`, or `prerelease`), or null if it's not valid + * `premajor` in one call will bump the version up to the next major + version and down to a prerelease of that major version. + `preminor`, and `prepatch` work the same way. + * If called from a non-prerelease version, the `prerelease` will work the + same as `prepatch`. It increments the patch version, then makes a + prerelease. If the input version is already a prerelease it simply + increments it. +* `prerelease(v)`: Returns an array of prerelease components, or null + if none exist. Example: `prerelease('1.2.3-alpha.1') -> ['alpha', 1]` +* `major(v)`: Return the major version number. +* `minor(v)`: Return the minor version number. +* `patch(v)`: Return the patch version number. +* `intersects(r1, r2, loose)`: Return true if the two supplied ranges + or comparators intersect. +* `parse(v)`: Attempt to parse a string as a semantic version, returning either + a `SemVer` object or `null`. + +### Comparison + +* `gt(v1, v2)`: `v1 > v2` +* `gte(v1, v2)`: `v1 >= v2` +* `lt(v1, v2)`: `v1 < v2` +* `lte(v1, v2)`: `v1 <= v2` +* `eq(v1, v2)`: `v1 == v2` This is true if they're logically equivalent, + even if they're not the exact same string. You already know how to + compare strings. +* `neq(v1, v2)`: `v1 != v2` The opposite of `eq`. +* `cmp(v1, comparator, v2)`: Pass in a comparison string, and it'll call + the corresponding function above. `"==="` and `"!=="` do simple + string comparison, but are included for completeness. Throws if an + invalid comparison string is provided. +* `compare(v1, v2)`: Return `0` if `v1 == v2`, or `1` if `v1` is greater, or `-1` if + `v2` is greater. Sorts in ascending order if passed to `Array.sort()`. +* `rcompare(v1, v2)`: The reverse of compare. Sorts an array of versions + in descending order when passed to `Array.sort()`. +* `diff(v1, v2)`: Returns difference between two versions by the release type + (`major`, `premajor`, `minor`, `preminor`, `patch`, `prepatch`, or `prerelease`), + or null if the versions are the same. + +### Comparators + +* `intersects(comparator)`: Return true if the comparators intersect + +### Ranges + +* `validRange(range)`: Return the valid range or null if it's not valid +* `satisfies(version, range)`: Return true if the version satisfies the + range. +* `maxSatisfying(versions, range)`: Return the highest version in the list + that satisfies the range, or `null` if none of them do. +* `minSatisfying(versions, range)`: Return the lowest version in the list + that satisfies the range, or `null` if none of them do. +* `minVersion(range)`: Return the lowest version that can possibly match + the given range. +* `gtr(version, range)`: Return `true` if version is greater than all the + versions possible in the range. +* `ltr(version, range)`: Return `true` if version is less than all the + versions possible in the range. +* `outside(version, range, hilo)`: Return true if the version is outside + the bounds of the range in either the high or low direction. The + `hilo` argument must be either the string `'>'` or `'<'`. (This is + the function called by `gtr` and `ltr`.) +* `intersects(range)`: Return true if any of the ranges comparators intersect + +Note that, since ranges may be non-contiguous, a version might not be +greater than a range, less than a range, *or* satisfy a range! For +example, the range `1.2 <1.2.9 || >2.0.0` would have a hole from `1.2.9` +until `2.0.0`, so the version `1.2.10` would not be greater than the +range (because `2.0.1` satisfies, which is higher), nor less than the +range (since `1.2.8` satisfies, which is lower), and it also does not +satisfy the range. + +If you want to know if a version satisfies or does not satisfy a +range, use the `satisfies(version, range)` function. + +### Coercion + +* `coerce(version)`: Coerces a string to semver if possible + +This aims to provide a very forgiving translation of a non-semver string to +semver. It looks for the first digit in a string, and consumes all +remaining characters which satisfy at least a partial semver (e.g., `1`, +`1.2`, `1.2.3`) up to the max permitted length (256 characters). Longer +versions are simply truncated (`4.6.3.9.2-alpha2` becomes `4.6.3`). All +surrounding text is simply ignored (`v3.4 replaces v3.3.1` becomes +`3.4.0`). Only text which lacks digits will fail coercion (`version one` +is not valid). The maximum length for any semver component considered for +coercion is 16 characters; longer components will be ignored +(`10000000000000000.4.7.4` becomes `4.7.4`). The maximum value for any +semver component is `Number.MAX_SAFE_INTEGER || (2**53 - 1)`; higher value +components are invalid (`9999999999999999.4.7.4` is likely invalid). diff --git a/scripts/node_modules/semver/bin/semver b/scripts/node_modules/semver/bin/semver new file mode 100755 index 00000000..801e77f1 --- /dev/null +++ b/scripts/node_modules/semver/bin/semver @@ -0,0 +1,160 @@ +#!/usr/bin/env node +// Standalone semver comparison program. +// Exits successfully and prints matching version(s) if +// any supplied version is valid and passes all tests. + +var argv = process.argv.slice(2) + +var versions = [] + +var range = [] + +var inc = null + +var version = require('../package.json').version + +var loose = false + +var includePrerelease = false + +var coerce = false + +var identifier + +var semver = require('../semver') + +var reverse = false + +var options = {} + +main() + +function main () { + if (!argv.length) return help() + while (argv.length) { + var a = argv.shift() + var indexOfEqualSign = a.indexOf('=') + if (indexOfEqualSign !== -1) { + a = a.slice(0, indexOfEqualSign) + argv.unshift(a.slice(indexOfEqualSign + 1)) + } + switch (a) { + case '-rv': case '-rev': case '--rev': case '--reverse': + reverse = true + break + case '-l': case '--loose': + loose = true + break + case '-p': case '--include-prerelease': + includePrerelease = true + break + case '-v': case '--version': + versions.push(argv.shift()) + break + case '-i': case '--inc': case '--increment': + switch (argv[0]) { + case 'major': case 'minor': case 'patch': case 'prerelease': + case 'premajor': case 'preminor': case 'prepatch': + inc = argv.shift() + break + default: + inc = 'patch' + break + } + break + case '--preid': + identifier = argv.shift() + break + case '-r': case '--range': + range.push(argv.shift()) + break + case '-c': case '--coerce': + coerce = true + break + case '-h': case '--help': case '-?': + return help() + default: + versions.push(a) + break + } + } + + var options = { loose: loose, includePrerelease: includePrerelease } + + versions = versions.map(function (v) { + return coerce ? (semver.coerce(v) || { version: v }).version : v + }).filter(function (v) { + return semver.valid(v) + }) + if (!versions.length) return fail() + if (inc && (versions.length !== 1 || range.length)) { return failInc() } + + for (var i = 0, l = range.length; i < l; i++) { + versions = versions.filter(function (v) { + return semver.satisfies(v, range[i], options) + }) + if (!versions.length) return fail() + } + return success(versions) +} + +function failInc () { + console.error('--inc can only be used on a single version with no range') + fail() +} + +function fail () { process.exit(1) } + +function success () { + var compare = reverse ? 'rcompare' : 'compare' + versions.sort(function (a, b) { + return semver[compare](a, b, options) + }).map(function (v) { + return semver.clean(v, options) + }).map(function (v) { + return inc ? semver.inc(v, inc, options, identifier) : v + }).forEach(function (v, i, _) { console.log(v) }) +} + +function help () { + console.log(['SemVer ' + version, + '', + 'A JavaScript implementation of the https://semver.org/ specification', + 'Copyright Isaac Z. Schlueter', + '', + 'Usage: semver [options] [ [...]]', + 'Prints valid versions sorted by SemVer precedence', + '', + 'Options:', + '-r --range ', + ' Print versions that match the specified range.', + '', + '-i --increment []', + ' Increment a version by the specified level. Level can', + ' be one of: major, minor, patch, premajor, preminor,', + " prepatch, or prerelease. Default level is 'patch'.", + ' Only one version may be specified.', + '', + '--preid ', + ' Identifier to be used to prefix premajor, preminor,', + ' prepatch or prerelease version increments.', + '', + '-l --loose', + ' Interpret versions and ranges loosely', + '', + '-p --include-prerelease', + ' Always include prerelease versions in range matching', + '', + '-c --coerce', + ' Coerce a string into SemVer if possible', + ' (does not imply --loose)', + '', + 'Program exits successfully if any valid version satisfies', + 'all supplied ranges, and prints all satisfying versions.', + '', + 'If no satisfying versions are found, then exits failure.', + '', + 'Versions are printed in ascending order, so supplying', + 'multiple versions to the utility will just sort them.' + ].join('\n')) +} diff --git a/scripts/node_modules/semver/package.json b/scripts/node_modules/semver/package.json new file mode 100644 index 00000000..dc3f686a --- /dev/null +++ b/scripts/node_modules/semver/package.json @@ -0,0 +1,60 @@ +{ + "_from": "semver@^5.1.0", + "_id": "semver@5.7.1", + "_inBundle": false, + "_integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==", + "_location": "/semver", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "semver@^5.1.0", + "name": "semver", + "escapedName": "semver", + "rawSpec": "^5.1.0", + "saveSpec": null, + "fetchSpec": "^5.1.0" + }, + "_requiredBy": [ + "/require_optional" + ], + "_resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz", + "_shasum": "a954f931aeba508d307bbf069eff0c01c96116f7", + "_spec": "semver@^5.1.0", + "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/node_modules/require_optional", + "bin": { + "semver": "./bin/semver" + }, + "bugs": { + "url": "https://github.com/npm/node-semver/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "The semantic version parser used by npm.", + "devDependencies": { + "tap": "^13.0.0-rc.18" + }, + "files": [ + "bin", + "range.bnf", + "semver.js" + ], + "homepage": "https://github.com/npm/node-semver#readme", + "license": "ISC", + "main": "semver.js", + "name": "semver", + "repository": { + "type": "git", + "url": "git+https://github.com/npm/node-semver.git" + }, + "scripts": { + "postpublish": "git push origin --all; git push origin --tags", + "postversion": "npm publish", + "preversion": "npm test", + "test": "tap" + }, + "tap": { + "check-coverage": true + }, + "version": "5.7.1" +} diff --git a/scripts/node_modules/semver/range.bnf b/scripts/node_modules/semver/range.bnf new file mode 100644 index 00000000..d4c6ae0d --- /dev/null +++ b/scripts/node_modules/semver/range.bnf @@ -0,0 +1,16 @@ +range-set ::= range ( logical-or range ) * +logical-or ::= ( ' ' ) * '||' ( ' ' ) * +range ::= hyphen | simple ( ' ' simple ) * | '' +hyphen ::= partial ' - ' partial +simple ::= primitive | partial | tilde | caret +primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial +partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? +xr ::= 'x' | 'X' | '*' | nr +nr ::= '0' | [1-9] ( [0-9] ) * +tilde ::= '~' partial +caret ::= '^' partial +qualifier ::= ( '-' pre )? ( '+' build )? +pre ::= parts +build ::= parts +parts ::= part ( '.' part ) * +part ::= nr | [-0-9A-Za-z]+ diff --git a/scripts/node_modules/semver/semver.js b/scripts/node_modules/semver/semver.js new file mode 100644 index 00000000..d315d5d6 --- /dev/null +++ b/scripts/node_modules/semver/semver.js @@ -0,0 +1,1483 @@ +exports = module.exports = SemVer + +var debug +/* istanbul ignore next */ +if (typeof process === 'object' && + process.env && + process.env.NODE_DEBUG && + /\bsemver\b/i.test(process.env.NODE_DEBUG)) { + debug = function () { + var args = Array.prototype.slice.call(arguments, 0) + args.unshift('SEMVER') + console.log.apply(console, args) + } +} else { + debug = function () {} +} + +// Note: this is the semver.org version of the spec that it implements +// Not necessarily the package version of this code. +exports.SEMVER_SPEC_VERSION = '2.0.0' + +var MAX_LENGTH = 256 +var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || + /* istanbul ignore next */ 9007199254740991 + +// Max safe segment length for coercion. +var MAX_SAFE_COMPONENT_LENGTH = 16 + +// The actual regexps go on exports.re +var re = exports.re = [] +var src = exports.src = [] +var R = 0 + +// The following Regular Expressions can be used for tokenizing, +// validating, and parsing SemVer version strings. + +// ## Numeric Identifier +// A single `0`, or a non-zero digit followed by zero or more digits. + +var NUMERICIDENTIFIER = R++ +src[NUMERICIDENTIFIER] = '0|[1-9]\\d*' +var NUMERICIDENTIFIERLOOSE = R++ +src[NUMERICIDENTIFIERLOOSE] = '[0-9]+' + +// ## Non-numeric Identifier +// Zero or more digits, followed by a letter or hyphen, and then zero or +// more letters, digits, or hyphens. + +var NONNUMERICIDENTIFIER = R++ +src[NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*' + +// ## Main Version +// Three dot-separated numeric identifiers. + +var MAINVERSION = R++ +src[MAINVERSION] = '(' + src[NUMERICIDENTIFIER] + ')\\.' + + '(' + src[NUMERICIDENTIFIER] + ')\\.' + + '(' + src[NUMERICIDENTIFIER] + ')' + +var MAINVERSIONLOOSE = R++ +src[MAINVERSIONLOOSE] = '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + + '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + + '(' + src[NUMERICIDENTIFIERLOOSE] + ')' + +// ## Pre-release Version Identifier +// A numeric identifier, or a non-numeric identifier. + +var PRERELEASEIDENTIFIER = R++ +src[PRERELEASEIDENTIFIER] = '(?:' + src[NUMERICIDENTIFIER] + + '|' + src[NONNUMERICIDENTIFIER] + ')' + +var PRERELEASEIDENTIFIERLOOSE = R++ +src[PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[NUMERICIDENTIFIERLOOSE] + + '|' + src[NONNUMERICIDENTIFIER] + ')' + +// ## Pre-release Version +// Hyphen, followed by one or more dot-separated pre-release version +// identifiers. + +var PRERELEASE = R++ +src[PRERELEASE] = '(?:-(' + src[PRERELEASEIDENTIFIER] + + '(?:\\.' + src[PRERELEASEIDENTIFIER] + ')*))' + +var PRERELEASELOOSE = R++ +src[PRERELEASELOOSE] = '(?:-?(' + src[PRERELEASEIDENTIFIERLOOSE] + + '(?:\\.' + src[PRERELEASEIDENTIFIERLOOSE] + ')*))' + +// ## Build Metadata Identifier +// Any combination of digits, letters, or hyphens. + +var BUILDIDENTIFIER = R++ +src[BUILDIDENTIFIER] = '[0-9A-Za-z-]+' + +// ## Build Metadata +// Plus sign, followed by one or more period-separated build metadata +// identifiers. + +var BUILD = R++ +src[BUILD] = '(?:\\+(' + src[BUILDIDENTIFIER] + + '(?:\\.' + src[BUILDIDENTIFIER] + ')*))' + +// ## Full Version String +// A main version, followed optionally by a pre-release version and +// build metadata. + +// Note that the only major, minor, patch, and pre-release sections of +// the version string are capturing groups. The build metadata is not a +// capturing group, because it should not ever be used in version +// comparison. + +var FULL = R++ +var FULLPLAIN = 'v?' + src[MAINVERSION] + + src[PRERELEASE] + '?' + + src[BUILD] + '?' + +src[FULL] = '^' + FULLPLAIN + '$' + +// like full, but allows v1.2.3 and =1.2.3, which people do sometimes. +// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty +// common in the npm registry. +var LOOSEPLAIN = '[v=\\s]*' + src[MAINVERSIONLOOSE] + + src[PRERELEASELOOSE] + '?' + + src[BUILD] + '?' + +var LOOSE = R++ +src[LOOSE] = '^' + LOOSEPLAIN + '$' + +var GTLT = R++ +src[GTLT] = '((?:<|>)?=?)' + +// Something like "2.*" or "1.2.x". +// Note that "x.x" is a valid xRange identifer, meaning "any version" +// Only the first item is strictly required. +var XRANGEIDENTIFIERLOOSE = R++ +src[XRANGEIDENTIFIERLOOSE] = src[NUMERICIDENTIFIERLOOSE] + '|x|X|\\*' +var XRANGEIDENTIFIER = R++ +src[XRANGEIDENTIFIER] = src[NUMERICIDENTIFIER] + '|x|X|\\*' + +var XRANGEPLAIN = R++ +src[XRANGEPLAIN] = '[v=\\s]*(' + src[XRANGEIDENTIFIER] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + + '(?:' + src[PRERELEASE] + ')?' + + src[BUILD] + '?' + + ')?)?' + +var XRANGEPLAINLOOSE = R++ +src[XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[XRANGEIDENTIFIERLOOSE] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + + '(?:' + src[PRERELEASELOOSE] + ')?' + + src[BUILD] + '?' + + ')?)?' + +var XRANGE = R++ +src[XRANGE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAIN] + '$' +var XRANGELOOSE = R++ +src[XRANGELOOSE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAINLOOSE] + '$' + +// Coercion. +// Extract anything that could conceivably be a part of a valid semver +var COERCE = R++ +src[COERCE] = '(?:^|[^\\d])' + + '(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' + + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + + '(?:$|[^\\d])' + +// Tilde ranges. +// Meaning is "reasonably at or greater than" +var LONETILDE = R++ +src[LONETILDE] = '(?:~>?)' + +var TILDETRIM = R++ +src[TILDETRIM] = '(\\s*)' + src[LONETILDE] + '\\s+' +re[TILDETRIM] = new RegExp(src[TILDETRIM], 'g') +var tildeTrimReplace = '$1~' + +var TILDE = R++ +src[TILDE] = '^' + src[LONETILDE] + src[XRANGEPLAIN] + '$' +var TILDELOOSE = R++ +src[TILDELOOSE] = '^' + src[LONETILDE] + src[XRANGEPLAINLOOSE] + '$' + +// Caret ranges. +// Meaning is "at least and backwards compatible with" +var LONECARET = R++ +src[LONECARET] = '(?:\\^)' + +var CARETTRIM = R++ +src[CARETTRIM] = '(\\s*)' + src[LONECARET] + '\\s+' +re[CARETTRIM] = new RegExp(src[CARETTRIM], 'g') +var caretTrimReplace = '$1^' + +var CARET = R++ +src[CARET] = '^' + src[LONECARET] + src[XRANGEPLAIN] + '$' +var CARETLOOSE = R++ +src[CARETLOOSE] = '^' + src[LONECARET] + src[XRANGEPLAINLOOSE] + '$' + +// A simple gt/lt/eq thing, or just "" to indicate "any version" +var COMPARATORLOOSE = R++ +src[COMPARATORLOOSE] = '^' + src[GTLT] + '\\s*(' + LOOSEPLAIN + ')$|^$' +var COMPARATOR = R++ +src[COMPARATOR] = '^' + src[GTLT] + '\\s*(' + FULLPLAIN + ')$|^$' + +// An expression to strip any whitespace between the gtlt and the thing +// it modifies, so that `> 1.2.3` ==> `>1.2.3` +var COMPARATORTRIM = R++ +src[COMPARATORTRIM] = '(\\s*)' + src[GTLT] + + '\\s*(' + LOOSEPLAIN + '|' + src[XRANGEPLAIN] + ')' + +// this one has to use the /g flag +re[COMPARATORTRIM] = new RegExp(src[COMPARATORTRIM], 'g') +var comparatorTrimReplace = '$1$2$3' + +// Something like `1.2.3 - 1.2.4` +// Note that these all use the loose form, because they'll be +// checked against either the strict or loose comparator form +// later. +var HYPHENRANGE = R++ +src[HYPHENRANGE] = '^\\s*(' + src[XRANGEPLAIN] + ')' + + '\\s+-\\s+' + + '(' + src[XRANGEPLAIN] + ')' + + '\\s*$' + +var HYPHENRANGELOOSE = R++ +src[HYPHENRANGELOOSE] = '^\\s*(' + src[XRANGEPLAINLOOSE] + ')' + + '\\s+-\\s+' + + '(' + src[XRANGEPLAINLOOSE] + ')' + + '\\s*$' + +// Star ranges basically just allow anything at all. +var STAR = R++ +src[STAR] = '(<|>)?=?\\s*\\*' + +// Compile to actual regexp objects. +// All are flag-free, unless they were created above with a flag. +for (var i = 0; i < R; i++) { + debug(i, src[i]) + if (!re[i]) { + re[i] = new RegExp(src[i]) + } +} + +exports.parse = parse +function parse (version, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } + + if (version instanceof SemVer) { + return version + } + + if (typeof version !== 'string') { + return null + } + + if (version.length > MAX_LENGTH) { + return null + } + + var r = options.loose ? re[LOOSE] : re[FULL] + if (!r.test(version)) { + return null + } + + try { + return new SemVer(version, options) + } catch (er) { + return null + } +} + +exports.valid = valid +function valid (version, options) { + var v = parse(version, options) + return v ? v.version : null +} + +exports.clean = clean +function clean (version, options) { + var s = parse(version.trim().replace(/^[=v]+/, ''), options) + return s ? s.version : null +} + +exports.SemVer = SemVer + +function SemVer (version, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } + if (version instanceof SemVer) { + if (version.loose === options.loose) { + return version + } else { + version = version.version + } + } else if (typeof version !== 'string') { + throw new TypeError('Invalid Version: ' + version) + } + + if (version.length > MAX_LENGTH) { + throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters') + } + + if (!(this instanceof SemVer)) { + return new SemVer(version, options) + } + + debug('SemVer', version, options) + this.options = options + this.loose = !!options.loose + + var m = version.trim().match(options.loose ? re[LOOSE] : re[FULL]) + + if (!m) { + throw new TypeError('Invalid Version: ' + version) + } + + this.raw = version + + // these are actually numbers + this.major = +m[1] + this.minor = +m[2] + this.patch = +m[3] + + if (this.major > MAX_SAFE_INTEGER || this.major < 0) { + throw new TypeError('Invalid major version') + } + + if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { + throw new TypeError('Invalid minor version') + } + + if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { + throw new TypeError('Invalid patch version') + } + + // numberify any prerelease numeric ids + if (!m[4]) { + this.prerelease = [] + } else { + this.prerelease = m[4].split('.').map(function (id) { + if (/^[0-9]+$/.test(id)) { + var num = +id + if (num >= 0 && num < MAX_SAFE_INTEGER) { + return num + } + } + return id + }) + } + + this.build = m[5] ? m[5].split('.') : [] + this.format() +} + +SemVer.prototype.format = function () { + this.version = this.major + '.' + this.minor + '.' + this.patch + if (this.prerelease.length) { + this.version += '-' + this.prerelease.join('.') + } + return this.version +} + +SemVer.prototype.toString = function () { + return this.version +} + +SemVer.prototype.compare = function (other) { + debug('SemVer.compare', this.version, this.options, other) + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + return this.compareMain(other) || this.comparePre(other) +} + +SemVer.prototype.compareMain = function (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + return compareIdentifiers(this.major, other.major) || + compareIdentifiers(this.minor, other.minor) || + compareIdentifiers(this.patch, other.patch) +} + +SemVer.prototype.comparePre = function (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + // NOT having a prerelease is > having one + if (this.prerelease.length && !other.prerelease.length) { + return -1 + } else if (!this.prerelease.length && other.prerelease.length) { + return 1 + } else if (!this.prerelease.length && !other.prerelease.length) { + return 0 + } + + var i = 0 + do { + var a = this.prerelease[i] + var b = other.prerelease[i] + debug('prerelease compare', i, a, b) + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) +} + +// preminor will bump the version up to the next minor release, and immediately +// down to pre-release. premajor and prepatch work the same way. +SemVer.prototype.inc = function (release, identifier) { + switch (release) { + case 'premajor': + this.prerelease.length = 0 + this.patch = 0 + this.minor = 0 + this.major++ + this.inc('pre', identifier) + break + case 'preminor': + this.prerelease.length = 0 + this.patch = 0 + this.minor++ + this.inc('pre', identifier) + break + case 'prepatch': + // If this is already a prerelease, it will bump to the next version + // drop any prereleases that might already exist, since they are not + // relevant at this point. + this.prerelease.length = 0 + this.inc('patch', identifier) + this.inc('pre', identifier) + break + // If the input is a non-prerelease version, this acts the same as + // prepatch. + case 'prerelease': + if (this.prerelease.length === 0) { + this.inc('patch', identifier) + } + this.inc('pre', identifier) + break + + case 'major': + // If this is a pre-major version, bump up to the same major version. + // Otherwise increment major. + // 1.0.0-5 bumps to 1.0.0 + // 1.1.0 bumps to 2.0.0 + if (this.minor !== 0 || + this.patch !== 0 || + this.prerelease.length === 0) { + this.major++ + } + this.minor = 0 + this.patch = 0 + this.prerelease = [] + break + case 'minor': + // If this is a pre-minor version, bump up to the same minor version. + // Otherwise increment minor. + // 1.2.0-5 bumps to 1.2.0 + // 1.2.1 bumps to 1.3.0 + if (this.patch !== 0 || this.prerelease.length === 0) { + this.minor++ + } + this.patch = 0 + this.prerelease = [] + break + case 'patch': + // If this is not a pre-release version, it will increment the patch. + // If it is a pre-release it will bump up to the same patch version. + // 1.2.0-5 patches to 1.2.0 + // 1.2.0 patches to 1.2.1 + if (this.prerelease.length === 0) { + this.patch++ + } + this.prerelease = [] + break + // This probably shouldn't be used publicly. + // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction. + case 'pre': + if (this.prerelease.length === 0) { + this.prerelease = [0] + } else { + var i = this.prerelease.length + while (--i >= 0) { + if (typeof this.prerelease[i] === 'number') { + this.prerelease[i]++ + i = -2 + } + } + if (i === -1) { + // didn't increment anything + this.prerelease.push(0) + } + } + if (identifier) { + // 1.2.0-beta.1 bumps to 1.2.0-beta.2, + // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 + if (this.prerelease[0] === identifier) { + if (isNaN(this.prerelease[1])) { + this.prerelease = [identifier, 0] + } + } else { + this.prerelease = [identifier, 0] + } + } + break + + default: + throw new Error('invalid increment argument: ' + release) + } + this.format() + this.raw = this.version + return this +} + +exports.inc = inc +function inc (version, release, loose, identifier) { + if (typeof (loose) === 'string') { + identifier = loose + loose = undefined + } + + try { + return new SemVer(version, loose).inc(release, identifier).version + } catch (er) { + return null + } +} + +exports.diff = diff +function diff (version1, version2) { + if (eq(version1, version2)) { + return null + } else { + var v1 = parse(version1) + var v2 = parse(version2) + var prefix = '' + if (v1.prerelease.length || v2.prerelease.length) { + prefix = 'pre' + var defaultResult = 'prerelease' + } + for (var key in v1) { + if (key === 'major' || key === 'minor' || key === 'patch') { + if (v1[key] !== v2[key]) { + return prefix + key + } + } + } + return defaultResult // may be undefined + } +} + +exports.compareIdentifiers = compareIdentifiers + +var numeric = /^[0-9]+$/ +function compareIdentifiers (a, b) { + var anum = numeric.test(a) + var bnum = numeric.test(b) + + if (anum && bnum) { + a = +a + b = +b + } + + return a === b ? 0 + : (anum && !bnum) ? -1 + : (bnum && !anum) ? 1 + : a < b ? -1 + : 1 +} + +exports.rcompareIdentifiers = rcompareIdentifiers +function rcompareIdentifiers (a, b) { + return compareIdentifiers(b, a) +} + +exports.major = major +function major (a, loose) { + return new SemVer(a, loose).major +} + +exports.minor = minor +function minor (a, loose) { + return new SemVer(a, loose).minor +} + +exports.patch = patch +function patch (a, loose) { + return new SemVer(a, loose).patch +} + +exports.compare = compare +function compare (a, b, loose) { + return new SemVer(a, loose).compare(new SemVer(b, loose)) +} + +exports.compareLoose = compareLoose +function compareLoose (a, b) { + return compare(a, b, true) +} + +exports.rcompare = rcompare +function rcompare (a, b, loose) { + return compare(b, a, loose) +} + +exports.sort = sort +function sort (list, loose) { + return list.sort(function (a, b) { + return exports.compare(a, b, loose) + }) +} + +exports.rsort = rsort +function rsort (list, loose) { + return list.sort(function (a, b) { + return exports.rcompare(a, b, loose) + }) +} + +exports.gt = gt +function gt (a, b, loose) { + return compare(a, b, loose) > 0 +} + +exports.lt = lt +function lt (a, b, loose) { + return compare(a, b, loose) < 0 +} + +exports.eq = eq +function eq (a, b, loose) { + return compare(a, b, loose) === 0 +} + +exports.neq = neq +function neq (a, b, loose) { + return compare(a, b, loose) !== 0 +} + +exports.gte = gte +function gte (a, b, loose) { + return compare(a, b, loose) >= 0 +} + +exports.lte = lte +function lte (a, b, loose) { + return compare(a, b, loose) <= 0 +} + +exports.cmp = cmp +function cmp (a, op, b, loose) { + switch (op) { + case '===': + if (typeof a === 'object') + a = a.version + if (typeof b === 'object') + b = b.version + return a === b + + case '!==': + if (typeof a === 'object') + a = a.version + if (typeof b === 'object') + b = b.version + return a !== b + + case '': + case '=': + case '==': + return eq(a, b, loose) + + case '!=': + return neq(a, b, loose) + + case '>': + return gt(a, b, loose) + + case '>=': + return gte(a, b, loose) + + case '<': + return lt(a, b, loose) + + case '<=': + return lte(a, b, loose) + + default: + throw new TypeError('Invalid operator: ' + op) + } +} + +exports.Comparator = Comparator +function Comparator (comp, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } + + if (comp instanceof Comparator) { + if (comp.loose === !!options.loose) { + return comp + } else { + comp = comp.value + } + } + + if (!(this instanceof Comparator)) { + return new Comparator(comp, options) + } + + debug('comparator', comp, options) + this.options = options + this.loose = !!options.loose + this.parse(comp) + + if (this.semver === ANY) { + this.value = '' + } else { + this.value = this.operator + this.semver.version + } + + debug('comp', this) +} + +var ANY = {} +Comparator.prototype.parse = function (comp) { + var r = this.options.loose ? re[COMPARATORLOOSE] : re[COMPARATOR] + var m = comp.match(r) + + if (!m) { + throw new TypeError('Invalid comparator: ' + comp) + } + + this.operator = m[1] + if (this.operator === '=') { + this.operator = '' + } + + // if it literally is just '>' or '' then allow anything. + if (!m[2]) { + this.semver = ANY + } else { + this.semver = new SemVer(m[2], this.options.loose) + } +} + +Comparator.prototype.toString = function () { + return this.value +} + +Comparator.prototype.test = function (version) { + debug('Comparator.test', version, this.options.loose) + + if (this.semver === ANY) { + return true + } + + if (typeof version === 'string') { + version = new SemVer(version, this.options) + } + + return cmp(version, this.operator, this.semver, this.options) +} + +Comparator.prototype.intersects = function (comp, options) { + if (!(comp instanceof Comparator)) { + throw new TypeError('a Comparator is required') + } + + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } + + var rangeTmp + + if (this.operator === '') { + rangeTmp = new Range(comp.value, options) + return satisfies(this.value, rangeTmp, options) + } else if (comp.operator === '') { + rangeTmp = new Range(this.value, options) + return satisfies(comp.semver, rangeTmp, options) + } + + var sameDirectionIncreasing = + (this.operator === '>=' || this.operator === '>') && + (comp.operator === '>=' || comp.operator === '>') + var sameDirectionDecreasing = + (this.operator === '<=' || this.operator === '<') && + (comp.operator === '<=' || comp.operator === '<') + var sameSemVer = this.semver.version === comp.semver.version + var differentDirectionsInclusive = + (this.operator === '>=' || this.operator === '<=') && + (comp.operator === '>=' || comp.operator === '<=') + var oppositeDirectionsLessThan = + cmp(this.semver, '<', comp.semver, options) && + ((this.operator === '>=' || this.operator === '>') && + (comp.operator === '<=' || comp.operator === '<')) + var oppositeDirectionsGreaterThan = + cmp(this.semver, '>', comp.semver, options) && + ((this.operator === '<=' || this.operator === '<') && + (comp.operator === '>=' || comp.operator === '>')) + + return sameDirectionIncreasing || sameDirectionDecreasing || + (sameSemVer && differentDirectionsInclusive) || + oppositeDirectionsLessThan || oppositeDirectionsGreaterThan +} + +exports.Range = Range +function Range (range, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } + + if (range instanceof Range) { + if (range.loose === !!options.loose && + range.includePrerelease === !!options.includePrerelease) { + return range + } else { + return new Range(range.raw, options) + } + } + + if (range instanceof Comparator) { + return new Range(range.value, options) + } + + if (!(this instanceof Range)) { + return new Range(range, options) + } + + this.options = options + this.loose = !!options.loose + this.includePrerelease = !!options.includePrerelease + + // First, split based on boolean or || + this.raw = range + this.set = range.split(/\s*\|\|\s*/).map(function (range) { + return this.parseRange(range.trim()) + }, this).filter(function (c) { + // throw out any that are not relevant for whatever reason + return c.length + }) + + if (!this.set.length) { + throw new TypeError('Invalid SemVer Range: ' + range) + } + + this.format() +} + +Range.prototype.format = function () { + this.range = this.set.map(function (comps) { + return comps.join(' ').trim() + }).join('||').trim() + return this.range +} + +Range.prototype.toString = function () { + return this.range +} + +Range.prototype.parseRange = function (range) { + var loose = this.options.loose + range = range.trim() + // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` + var hr = loose ? re[HYPHENRANGELOOSE] : re[HYPHENRANGE] + range = range.replace(hr, hyphenReplace) + debug('hyphen replace', range) + // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` + range = range.replace(re[COMPARATORTRIM], comparatorTrimReplace) + debug('comparator trim', range, re[COMPARATORTRIM]) + + // `~ 1.2.3` => `~1.2.3` + range = range.replace(re[TILDETRIM], tildeTrimReplace) + + // `^ 1.2.3` => `^1.2.3` + range = range.replace(re[CARETTRIM], caretTrimReplace) + + // normalize spaces + range = range.split(/\s+/).join(' ') + + // At this point, the range is completely trimmed and + // ready to be split into comparators. + + var compRe = loose ? re[COMPARATORLOOSE] : re[COMPARATOR] + var set = range.split(' ').map(function (comp) { + return parseComparator(comp, this.options) + }, this).join(' ').split(/\s+/) + if (this.options.loose) { + // in loose mode, throw out any that are not valid comparators + set = set.filter(function (comp) { + return !!comp.match(compRe) + }) + } + set = set.map(function (comp) { + return new Comparator(comp, this.options) + }, this) + + return set +} + +Range.prototype.intersects = function (range, options) { + if (!(range instanceof Range)) { + throw new TypeError('a Range is required') + } + + return this.set.some(function (thisComparators) { + return thisComparators.every(function (thisComparator) { + return range.set.some(function (rangeComparators) { + return rangeComparators.every(function (rangeComparator) { + return thisComparator.intersects(rangeComparator, options) + }) + }) + }) + }) +} + +// Mostly just for testing and legacy API reasons +exports.toComparators = toComparators +function toComparators (range, options) { + return new Range(range, options).set.map(function (comp) { + return comp.map(function (c) { + return c.value + }).join(' ').trim().split(' ') + }) +} + +// comprised of xranges, tildes, stars, and gtlt's at this point. +// already replaced the hyphen ranges +// turn into a set of JUST comparators. +function parseComparator (comp, options) { + debug('comp', comp, options) + comp = replaceCarets(comp, options) + debug('caret', comp) + comp = replaceTildes(comp, options) + debug('tildes', comp) + comp = replaceXRanges(comp, options) + debug('xrange', comp) + comp = replaceStars(comp, options) + debug('stars', comp) + return comp +} + +function isX (id) { + return !id || id.toLowerCase() === 'x' || id === '*' +} + +// ~, ~> --> * (any, kinda silly) +// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0 +// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0 +// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0 +// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0 +// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0 +function replaceTildes (comp, options) { + return comp.trim().split(/\s+/).map(function (comp) { + return replaceTilde(comp, options) + }).join(' ') +} + +function replaceTilde (comp, options) { + var r = options.loose ? re[TILDELOOSE] : re[TILDE] + return comp.replace(r, function (_, M, m, p, pr) { + debug('tilde', comp, _, M, m, p, pr) + var ret + + if (isX(M)) { + ret = '' + } else if (isX(m)) { + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' + } else if (isX(p)) { + // ~1.2 == >=1.2.0 <1.3.0 + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' + } else if (pr) { + debug('replaceTilde pr', pr) + ret = '>=' + M + '.' + m + '.' + p + '-' + pr + + ' <' + M + '.' + (+m + 1) + '.0' + } else { + // ~1.2.3 == >=1.2.3 <1.3.0 + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + (+m + 1) + '.0' + } + + debug('tilde return', ret) + return ret + }) +} + +// ^ --> * (any, kinda silly) +// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0 +// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0 +// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0 +// ^1.2.3 --> >=1.2.3 <2.0.0 +// ^1.2.0 --> >=1.2.0 <2.0.0 +function replaceCarets (comp, options) { + return comp.trim().split(/\s+/).map(function (comp) { + return replaceCaret(comp, options) + }).join(' ') +} + +function replaceCaret (comp, options) { + debug('caret', comp, options) + var r = options.loose ? re[CARETLOOSE] : re[CARET] + return comp.replace(r, function (_, M, m, p, pr) { + debug('caret', comp, _, M, m, p, pr) + var ret + + if (isX(M)) { + ret = '' + } else if (isX(m)) { + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' + } else if (isX(p)) { + if (M === '0') { + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' + } else { + ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0' + } + } else if (pr) { + debug('replaceCaret pr', pr) + if (M === '0') { + if (m === '0') { + ret = '>=' + M + '.' + m + '.' + p + '-' + pr + + ' <' + M + '.' + m + '.' + (+p + 1) + } else { + ret = '>=' + M + '.' + m + '.' + p + '-' + pr + + ' <' + M + '.' + (+m + 1) + '.0' + } + } else { + ret = '>=' + M + '.' + m + '.' + p + '-' + pr + + ' <' + (+M + 1) + '.0.0' + } + } else { + debug('no pr') + if (M === '0') { + if (m === '0') { + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + m + '.' + (+p + 1) + } else { + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + (+m + 1) + '.0' + } + } else { + ret = '>=' + M + '.' + m + '.' + p + + ' <' + (+M + 1) + '.0.0' + } + } + + debug('caret return', ret) + return ret + }) +} + +function replaceXRanges (comp, options) { + debug('replaceXRanges', comp, options) + return comp.split(/\s+/).map(function (comp) { + return replaceXRange(comp, options) + }).join(' ') +} + +function replaceXRange (comp, options) { + comp = comp.trim() + var r = options.loose ? re[XRANGELOOSE] : re[XRANGE] + return comp.replace(r, function (ret, gtlt, M, m, p, pr) { + debug('xRange', comp, ret, gtlt, M, m, p, pr) + var xM = isX(M) + var xm = xM || isX(m) + var xp = xm || isX(p) + var anyX = xp + + if (gtlt === '=' && anyX) { + gtlt = '' + } + + if (xM) { + if (gtlt === '>' || gtlt === '<') { + // nothing is allowed + ret = '<0.0.0' + } else { + // nothing is forbidden + ret = '*' + } + } else if (gtlt && anyX) { + // we know patch is an x, because we have any x at all. + // replace X with 0 + if (xm) { + m = 0 + } + p = 0 + + if (gtlt === '>') { + // >1 => >=2.0.0 + // >1.2 => >=1.3.0 + // >1.2.3 => >= 1.2.4 + gtlt = '>=' + if (xm) { + M = +M + 1 + m = 0 + p = 0 + } else { + m = +m + 1 + p = 0 + } + } else if (gtlt === '<=') { + // <=0.7.x is actually <0.8.0, since any 0.7.x should + // pass. Similarly, <=7.x is actually <8.0.0, etc. + gtlt = '<' + if (xm) { + M = +M + 1 + } else { + m = +m + 1 + } + } + + ret = gtlt + M + '.' + m + '.' + p + } else if (xm) { + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' + } else if (xp) { + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' + } + + debug('xRange return', ret) + + return ret + }) +} + +// Because * is AND-ed with everything else in the comparator, +// and '' means "any version", just remove the *s entirely. +function replaceStars (comp, options) { + debug('replaceStars', comp, options) + // Looseness is ignored here. star is always as loose as it gets! + return comp.trim().replace(re[STAR], '') +} + +// This function is passed to string.replace(re[HYPHENRANGE]) +// M, m, patch, prerelease, build +// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 +// 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do +// 1.2 - 3.4 => >=1.2.0 <3.5.0 +function hyphenReplace ($0, + from, fM, fm, fp, fpr, fb, + to, tM, tm, tp, tpr, tb) { + if (isX(fM)) { + from = '' + } else if (isX(fm)) { + from = '>=' + fM + '.0.0' + } else if (isX(fp)) { + from = '>=' + fM + '.' + fm + '.0' + } else { + from = '>=' + from + } + + if (isX(tM)) { + to = '' + } else if (isX(tm)) { + to = '<' + (+tM + 1) + '.0.0' + } else if (isX(tp)) { + to = '<' + tM + '.' + (+tm + 1) + '.0' + } else if (tpr) { + to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr + } else { + to = '<=' + to + } + + return (from + ' ' + to).trim() +} + +// if ANY of the sets match ALL of its comparators, then pass +Range.prototype.test = function (version) { + if (!version) { + return false + } + + if (typeof version === 'string') { + version = new SemVer(version, this.options) + } + + for (var i = 0; i < this.set.length; i++) { + if (testSet(this.set[i], version, this.options)) { + return true + } + } + return false +} + +function testSet (set, version, options) { + for (var i = 0; i < set.length; i++) { + if (!set[i].test(version)) { + return false + } + } + + if (version.prerelease.length && !options.includePrerelease) { + // Find the set of versions that are allowed to have prereleases + // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 + // That should allow `1.2.3-pr.2` to pass. + // However, `1.2.4-alpha.notready` should NOT be allowed, + // even though it's within the range set by the comparators. + for (i = 0; i < set.length; i++) { + debug(set[i].semver) + if (set[i].semver === ANY) { + continue + } + + if (set[i].semver.prerelease.length > 0) { + var allowed = set[i].semver + if (allowed.major === version.major && + allowed.minor === version.minor && + allowed.patch === version.patch) { + return true + } + } + } + + // Version has a -pre, but it's not one of the ones we like. + return false + } + + return true +} + +exports.satisfies = satisfies +function satisfies (version, range, options) { + try { + range = new Range(range, options) + } catch (er) { + return false + } + return range.test(version) +} + +exports.maxSatisfying = maxSatisfying +function maxSatisfying (versions, range, options) { + var max = null + var maxSV = null + try { + var rangeObj = new Range(range, options) + } catch (er) { + return null + } + versions.forEach(function (v) { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!max || maxSV.compare(v) === -1) { + // compare(max, v, true) + max = v + maxSV = new SemVer(max, options) + } + } + }) + return max +} + +exports.minSatisfying = minSatisfying +function minSatisfying (versions, range, options) { + var min = null + var minSV = null + try { + var rangeObj = new Range(range, options) + } catch (er) { + return null + } + versions.forEach(function (v) { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!min || minSV.compare(v) === 1) { + // compare(min, v, true) + min = v + minSV = new SemVer(min, options) + } + } + }) + return min +} + +exports.minVersion = minVersion +function minVersion (range, loose) { + range = new Range(range, loose) + + var minver = new SemVer('0.0.0') + if (range.test(minver)) { + return minver + } + + minver = new SemVer('0.0.0-0') + if (range.test(minver)) { + return minver + } + + minver = null + for (var i = 0; i < range.set.length; ++i) { + var comparators = range.set[i] + + comparators.forEach(function (comparator) { + // Clone to avoid manipulating the comparator's semver object. + var compver = new SemVer(comparator.semver.version) + switch (comparator.operator) { + case '>': + if (compver.prerelease.length === 0) { + compver.patch++ + } else { + compver.prerelease.push(0) + } + compver.raw = compver.format() + /* fallthrough */ + case '': + case '>=': + if (!minver || gt(minver, compver)) { + minver = compver + } + break + case '<': + case '<=': + /* Ignore maximum versions */ + break + /* istanbul ignore next */ + default: + throw new Error('Unexpected operation: ' + comparator.operator) + } + }) + } + + if (minver && range.test(minver)) { + return minver + } + + return null +} + +exports.validRange = validRange +function validRange (range, options) { + try { + // Return '*' instead of '' so that truthiness works. + // This will throw if it's invalid anyway + return new Range(range, options).range || '*' + } catch (er) { + return null + } +} + +// Determine if version is less than all the versions possible in the range +exports.ltr = ltr +function ltr (version, range, options) { + return outside(version, range, '<', options) +} + +// Determine if version is greater than all the versions possible in the range. +exports.gtr = gtr +function gtr (version, range, options) { + return outside(version, range, '>', options) +} + +exports.outside = outside +function outside (version, range, hilo, options) { + version = new SemVer(version, options) + range = new Range(range, options) + + var gtfn, ltefn, ltfn, comp, ecomp + switch (hilo) { + case '>': + gtfn = gt + ltefn = lte + ltfn = lt + comp = '>' + ecomp = '>=' + break + case '<': + gtfn = lt + ltefn = gte + ltfn = gt + comp = '<' + ecomp = '<=' + break + default: + throw new TypeError('Must provide a hilo val of "<" or ">"') + } + + // If it satisifes the range it is not outside + if (satisfies(version, range, options)) { + return false + } + + // From now on, variable terms are as if we're in "gtr" mode. + // but note that everything is flipped for the "ltr" function. + + for (var i = 0; i < range.set.length; ++i) { + var comparators = range.set[i] + + var high = null + var low = null + + comparators.forEach(function (comparator) { + if (comparator.semver === ANY) { + comparator = new Comparator('>=0.0.0') + } + high = high || comparator + low = low || comparator + if (gtfn(comparator.semver, high.semver, options)) { + high = comparator + } else if (ltfn(comparator.semver, low.semver, options)) { + low = comparator + } + }) + + // If the edge version comparator has a operator then our version + // isn't outside it + if (high.operator === comp || high.operator === ecomp) { + return false + } + + // If the lowest version comparator has an operator and our version + // is less than it then it isn't higher than the range + if ((!low.operator || low.operator === comp) && + ltefn(version, low.semver)) { + return false + } else if (low.operator === ecomp && ltfn(version, low.semver)) { + return false + } + } + return true +} + +exports.prerelease = prerelease +function prerelease (version, options) { + var parsed = parse(version, options) + return (parsed && parsed.prerelease.length) ? parsed.prerelease : null +} + +exports.intersects = intersects +function intersects (r1, r2, options) { + r1 = new Range(r1, options) + r2 = new Range(r2, options) + return r1.intersects(r2) +} + +exports.coerce = coerce +function coerce (version) { + if (version instanceof SemVer) { + return version + } + + if (typeof version !== 'string') { + return null + } + + var match = version.match(re[COERCE]) + + if (match == null) { + return null + } + + return parse(match[1] + + '.' + (match[2] || '0') + + '.' + (match[3] || '0')) +} diff --git a/scripts/node_modules/sparse-bitfield/.npmignore b/scripts/node_modules/sparse-bitfield/.npmignore new file mode 100644 index 00000000..3c3629e6 --- /dev/null +++ b/scripts/node_modules/sparse-bitfield/.npmignore @@ -0,0 +1 @@ +node_modules diff --git a/scripts/node_modules/sparse-bitfield/.travis.yml b/scripts/node_modules/sparse-bitfield/.travis.yml new file mode 100644 index 00000000..c0428217 --- /dev/null +++ b/scripts/node_modules/sparse-bitfield/.travis.yml @@ -0,0 +1,6 @@ +language: node_js +node_js: + - '0.10' + - '0.12' + - '4.0' + - '5.0' diff --git a/scripts/node_modules/sparse-bitfield/LICENSE b/scripts/node_modules/sparse-bitfield/LICENSE new file mode 100644 index 00000000..bae9da7b --- /dev/null +++ b/scripts/node_modules/sparse-bitfield/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2016 Mathias Buus + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/scripts/node_modules/sparse-bitfield/README.md b/scripts/node_modules/sparse-bitfield/README.md new file mode 100644 index 00000000..7b6b8f9e --- /dev/null +++ b/scripts/node_modules/sparse-bitfield/README.md @@ -0,0 +1,62 @@ +# sparse-bitfield + +Bitfield implementation that allocates a series of 1kb buffers to support sparse bitfields +without allocating a massive buffer. If you want to simple implementation of a flat bitfield +see the [bitfield](https://github.com/fb55/bitfield) module. + +This module is mostly useful if you need a big bitfield where you won't nessecarily set every bit. + +``` +npm install sparse-bitfield +``` + +[![build status](http://img.shields.io/travis/mafintosh/sparse-bitfield.svg?style=flat)](http://travis-ci.org/mafintosh/sparse-bitfield) + +## Usage + +``` js +var bitfield = require('sparse-bitfield') +var bits = bitfield() + +bits.set(0, true) // set first bit +bits.set(1, true) // set second bit +bits.set(1000000000000, true) // set the 1.000.000.000.000th bit +``` + +Running the above example will allocate two 1kb buffers internally. +Each 1kb buffer can hold information about 8192 bits so the first one will be used to store information about the first two bits and the second will be used to store the 1.000.000.000.000th bit. + +## API + +#### `var bits = bitfield([options])` + +Create a new bitfield. Options include + +``` js +{ + pageSize: 1024, // how big should the partial buffers be + buffer: anExistingBitfield, + trackUpdates: false // track when pages are being updated in the pager +} +``` + +#### `bits.set(index, value)` + +Set a bit to true or false. + +#### `bits.get(index)` + +Get the value of a bit. + +#### `bits.pages` + +A [memory-pager](https://github.com/mafintosh/memory-pager) instance that is managing the underlying memory. +If you set `trackUpdates` to true in the constructor you can use `.lastUpdate()` on this instance to get the last updated memory page. + +#### `var buffer = bits.toBuffer()` + +Get a single buffer representing the entire bitfield. + +## License + +MIT diff --git a/scripts/node_modules/sparse-bitfield/index.js b/scripts/node_modules/sparse-bitfield/index.js new file mode 100644 index 00000000..ff458c97 --- /dev/null +++ b/scripts/node_modules/sparse-bitfield/index.js @@ -0,0 +1,95 @@ +var pager = require('memory-pager') + +module.exports = Bitfield + +function Bitfield (opts) { + if (!(this instanceof Bitfield)) return new Bitfield(opts) + if (!opts) opts = {} + if (Buffer.isBuffer(opts)) opts = {buffer: opts} + + this.pageOffset = opts.pageOffset || 0 + this.pageSize = opts.pageSize || 1024 + this.pages = opts.pages || pager(this.pageSize) + + this.byteLength = this.pages.length * this.pageSize + this.length = 8 * this.byteLength + + if (!powerOfTwo(this.pageSize)) throw new Error('The page size should be a power of two') + + this._trackUpdates = !!opts.trackUpdates + this._pageMask = this.pageSize - 1 + + if (opts.buffer) { + for (var i = 0; i < opts.buffer.length; i += this.pageSize) { + this.pages.set(i / this.pageSize, opts.buffer.slice(i, i + this.pageSize)) + } + this.byteLength = opts.buffer.length + this.length = 8 * this.byteLength + } +} + +Bitfield.prototype.get = function (i) { + var o = i & 7 + var j = (i - o) / 8 + + return !!(this.getByte(j) & (128 >> o)) +} + +Bitfield.prototype.getByte = function (i) { + var o = i & this._pageMask + var j = (i - o) / this.pageSize + var page = this.pages.get(j, true) + + return page ? page.buffer[o + this.pageOffset] : 0 +} + +Bitfield.prototype.set = function (i, v) { + var o = i & 7 + var j = (i - o) / 8 + var b = this.getByte(j) + + return this.setByte(j, v ? b | (128 >> o) : b & (255 ^ (128 >> o))) +} + +Bitfield.prototype.toBuffer = function () { + var all = alloc(this.pages.length * this.pageSize) + + for (var i = 0; i < this.pages.length; i++) { + var next = this.pages.get(i, true) + var allOffset = i * this.pageSize + if (next) next.buffer.copy(all, allOffset, this.pageOffset, this.pageOffset + this.pageSize) + } + + return all +} + +Bitfield.prototype.setByte = function (i, b) { + var o = i & this._pageMask + var j = (i - o) / this.pageSize + var page = this.pages.get(j, false) + + o += this.pageOffset + + if (page.buffer[o] === b) return false + page.buffer[o] = b + + if (i >= this.byteLength) { + this.byteLength = i + 1 + this.length = this.byteLength * 8 + } + + if (this._trackUpdates) this.pages.updated(page) + + return true +} + +function alloc (n) { + if (Buffer.alloc) return Buffer.alloc(n) + var b = new Buffer(n) + b.fill(0) + return b +} + +function powerOfTwo (x) { + return !(x & (x - 1)) +} diff --git a/scripts/node_modules/sparse-bitfield/package.json b/scripts/node_modules/sparse-bitfield/package.json new file mode 100644 index 00000000..b1cf7878 --- /dev/null +++ b/scripts/node_modules/sparse-bitfield/package.json @@ -0,0 +1,55 @@ +{ + "_from": "sparse-bitfield@^3.0.3", + "_id": "sparse-bitfield@3.0.3", + "_inBundle": false, + "_integrity": "sha1-/0rm5oZWBWuks+eSqzM004JzyhE=", + "_location": "/sparse-bitfield", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "sparse-bitfield@^3.0.3", + "name": "sparse-bitfield", + "escapedName": "sparse-bitfield", + "rawSpec": "^3.0.3", + "saveSpec": null, + "fetchSpec": "^3.0.3" + }, + "_requiredBy": [ + "/saslprep" + ], + "_resolved": "https://registry.npmjs.org/sparse-bitfield/-/sparse-bitfield-3.0.3.tgz", + "_shasum": "ff4ae6e68656056ba4b3e792ab3334d38273ca11", + "_spec": "sparse-bitfield@^3.0.3", + "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/node_modules/saslprep", + "author": { + "name": "Mathias Buus", + "url": "@mafintosh" + }, + "bugs": { + "url": "https://github.com/mafintosh/sparse-bitfield/issues" + }, + "bundleDependencies": false, + "dependencies": { + "memory-pager": "^1.0.2" + }, + "deprecated": false, + "description": "Bitfield that allocates a series of small buffers to support sparse bits without allocating a massive buffer", + "devDependencies": { + "buffer-alloc": "^1.1.0", + "standard": "^9.0.0", + "tape": "^4.6.3" + }, + "homepage": "https://github.com/mafintosh/sparse-bitfield", + "license": "MIT", + "main": "index.js", + "name": "sparse-bitfield", + "repository": { + "type": "git", + "url": "git+https://github.com/mafintosh/sparse-bitfield.git" + }, + "scripts": { + "test": "standard && tape test.js" + }, + "version": "3.0.3" +} diff --git a/scripts/node_modules/sparse-bitfield/test.js b/scripts/node_modules/sparse-bitfield/test.js new file mode 100644 index 00000000..ae42ef46 --- /dev/null +++ b/scripts/node_modules/sparse-bitfield/test.js @@ -0,0 +1,79 @@ +var alloc = require('buffer-alloc') +var tape = require('tape') +var bitfield = require('./') + +tape('set and get', function (t) { + var bits = bitfield() + + t.same(bits.get(0), false, 'first bit is false') + bits.set(0, true) + t.same(bits.get(0), true, 'first bit is true') + t.same(bits.get(1), false, 'second bit is false') + bits.set(0, false) + t.same(bits.get(0), false, 'first bit is reset') + t.end() +}) + +tape('set large and get', function (t) { + var bits = bitfield() + + t.same(bits.get(9999999999999), false, 'large bit is false') + bits.set(9999999999999, true) + t.same(bits.get(9999999999999), true, 'large bit is true') + t.same(bits.get(9999999999999 + 1), false, 'large bit + 1 is false') + bits.set(9999999999999, false) + t.same(bits.get(9999999999999), false, 'large bit is reset') + t.end() +}) + +tape('get and set buffer', function (t) { + var bits = bitfield({trackUpdates: true}) + + t.same(bits.pages.get(0, true), undefined) + t.same(bits.pages.get(Math.floor(9999999999999 / 8 / 1024), true), undefined) + bits.set(9999999999999, true) + + var bits2 = bitfield() + var upd = bits.pages.lastUpdate() + bits2.pages.set(Math.floor(upd.offset / 1024), upd.buffer) + t.same(bits2.get(9999999999999), true, 'bit is set') + t.end() +}) + +tape('toBuffer', function (t) { + var bits = bitfield() + + t.same(bits.toBuffer(), alloc(0)) + + bits.set(0, true) + + t.same(bits.toBuffer(), bits.pages.get(0).buffer) + + bits.set(9000, true) + + t.same(bits.toBuffer(), Buffer.concat([bits.pages.get(0).buffer, bits.pages.get(1).buffer])) + t.end() +}) + +tape('pass in buffer', function (t) { + var bits = bitfield() + + bits.set(0, true) + bits.set(9000, true) + + var clone = bitfield(bits.toBuffer()) + + t.same(clone.get(0), true) + t.same(clone.get(9000), true) + t.end() +}) + +tape('set small buffer', function (t) { + var buf = alloc(1) + buf[0] = 255 + var bits = bitfield(buf) + + t.same(bits.get(0), true) + t.same(bits.pages.get(0).buffer.length, bits.pageSize) + t.end() +}) diff --git a/src/main/java/org/kpmp/packages/state/PackageNotificationInfo.java b/src/main/java/org/kpmp/packages/PackageNotificationInfo.java similarity index 95% rename from src/main/java/org/kpmp/packages/state/PackageNotificationInfo.java rename to src/main/java/org/kpmp/packages/PackageNotificationInfo.java index 43f4bd0d..cd329de6 100644 --- a/src/main/java/org/kpmp/packages/state/PackageNotificationInfo.java +++ b/src/main/java/org/kpmp/packages/PackageNotificationInfo.java @@ -1,8 +1,8 @@ -package org.kpmp.packages.state; +package org.kpmp.packages; import java.util.Date; -public class PackageNotificationInfo { +class PackageNotificationInfo { private String packageId; private String packageType; diff --git a/src/main/java/org/kpmp/packages/PackageService.java b/src/main/java/org/kpmp/packages/PackageService.java index 3e571616..b7566e38 100755 --- a/src/main/java/org/kpmp/packages/PackageService.java +++ b/src/main/java/org/kpmp/packages/PackageService.java @@ -21,8 +21,6 @@ import org.kpmp.externalProcess.CommandBuilder; import org.kpmp.externalProcess.ProcessExecutor; import org.kpmp.logging.LoggingService; -import org.kpmp.packages.state.State; -import org.kpmp.packages.state.StateHandlerService; import org.kpmp.users.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; diff --git a/src/main/java/org/kpmp/packages/PackageView.java b/src/main/java/org/kpmp/packages/PackageView.java index aab664eb..31c9344e 100644 --- a/src/main/java/org/kpmp/packages/PackageView.java +++ b/src/main/java/org/kpmp/packages/PackageView.java @@ -3,7 +3,6 @@ import java.io.IOException; import org.json.JSONObject; -import org.kpmp.packages.state.State; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; diff --git a/src/main/java/org/kpmp/packages/state/State.java b/src/main/java/org/kpmp/packages/State.java similarity index 96% rename from src/main/java/org/kpmp/packages/state/State.java rename to src/main/java/org/kpmp/packages/State.java index 412d2027..d7fc7200 100644 --- a/src/main/java/org/kpmp/packages/state/State.java +++ b/src/main/java/org/kpmp/packages/State.java @@ -1,4 +1,4 @@ -package org.kpmp.packages.state; +package org.kpmp.packages; import java.util.Date; diff --git a/src/main/java/org/kpmp/packages/state/StateHandlerService.java b/src/main/java/org/kpmp/packages/StateHandlerService.java similarity index 98% rename from src/main/java/org/kpmp/packages/state/StateHandlerService.java rename to src/main/java/org/kpmp/packages/StateHandlerService.java index 3643eb0a..67531cbb 100644 --- a/src/main/java/org/kpmp/packages/state/StateHandlerService.java +++ b/src/main/java/org/kpmp/packages/StateHandlerService.java @@ -1,4 +1,4 @@ -package org.kpmp.packages.state; +package org.kpmp.packages; import java.util.Date; import java.util.HashMap; diff --git a/src/test/java/org/kpmp/packages/state/PackageNotificationInfoTest.java b/src/test/java/org/kpmp/packages/PackageNotificationInfoTest.java similarity index 96% rename from src/test/java/org/kpmp/packages/state/PackageNotificationInfoTest.java rename to src/test/java/org/kpmp/packages/PackageNotificationInfoTest.java index eafb455d..1d14cf62 100644 --- a/src/test/java/org/kpmp/packages/state/PackageNotificationInfoTest.java +++ b/src/test/java/org/kpmp/packages/PackageNotificationInfoTest.java @@ -1,4 +1,4 @@ -package org.kpmp.packages.state; +package org.kpmp.packages; import static org.junit.Assert.assertEquals; @@ -7,6 +7,7 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; +import org.kpmp.packages.PackageNotificationInfo; public class PackageNotificationInfoTest { diff --git a/src/test/java/org/kpmp/packages/PackageServiceTest.java b/src/test/java/org/kpmp/packages/PackageServiceTest.java index e95476cc..9481e953 100755 --- a/src/test/java/org/kpmp/packages/PackageServiceTest.java +++ b/src/test/java/org/kpmp/packages/PackageServiceTest.java @@ -27,8 +27,6 @@ import org.kpmp.externalProcess.CommandBuilder; import org.kpmp.externalProcess.ProcessExecutor; import org.kpmp.logging.LoggingService; -import org.kpmp.packages.state.State; -import org.kpmp.packages.state.StateHandlerService; import org.kpmp.users.User; import org.mockito.Mock; import org.mockito.MockitoAnnotations; diff --git a/src/test/java/org/kpmp/packages/PackageViewTest.java b/src/test/java/org/kpmp/packages/PackageViewTest.java index b4b3fd2a..de4f7d46 100644 --- a/src/test/java/org/kpmp/packages/PackageViewTest.java +++ b/src/test/java/org/kpmp/packages/PackageViewTest.java @@ -9,7 +9,6 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; -import org.kpmp.packages.state.State; import com.fasterxml.jackson.databind.ObjectMapper; diff --git a/src/test/java/org/kpmp/packages/state/StateHandlerServiceTest.java b/src/test/java/org/kpmp/packages/StateHandlerServiceTest.java similarity index 97% rename from src/test/java/org/kpmp/packages/state/StateHandlerServiceTest.java rename to src/test/java/org/kpmp/packages/StateHandlerServiceTest.java index cc42a5b6..257ae9e8 100644 --- a/src/test/java/org/kpmp/packages/state/StateHandlerServiceTest.java +++ b/src/test/java/org/kpmp/packages/StateHandlerServiceTest.java @@ -1,4 +1,4 @@ -package org.kpmp.packages.state; +package org.kpmp.packages; import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.any; @@ -16,6 +16,9 @@ import org.junit.Before; import org.junit.Test; import org.kpmp.logging.LoggingService; +import org.kpmp.packages.PackageNotificationInfo; +import org.kpmp.packages.State; +import org.kpmp.packages.StateHandlerService; import org.kpmp.users.User; import org.mockito.ArgumentCaptor; import org.mockito.Mock; diff --git a/src/test/java/org/kpmp/packages/state/StateTest.java b/src/test/java/org/kpmp/packages/StateTest.java similarity index 95% rename from src/test/java/org/kpmp/packages/state/StateTest.java rename to src/test/java/org/kpmp/packages/StateTest.java index 119ee597..9a32bb40 100644 --- a/src/test/java/org/kpmp/packages/state/StateTest.java +++ b/src/test/java/org/kpmp/packages/StateTest.java @@ -1,4 +1,4 @@ -package org.kpmp.packages.state; +package org.kpmp.packages; import static org.junit.Assert.assertEquals; @@ -7,6 +7,7 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; +import org.kpmp.packages.State; public class StateTest { From e7d1b6d7053194009095bc861e0e77d2ac41ba2e Mon Sep 17 00:00:00 2001 From: Becky Reamy Date: Mon, 28 Oct 2019 15:44:46 -0400 Subject: [PATCH 21/26] KPMP-1270: Starting to add in the error handling and tests around it --- .../org/kpmp/packages/PackageController.java | 42 +++++++++----- src/main/resources/application.properties | 3 +- .../kpmp/packages/PackageControllerTest.java | 56 ++++++++++++++++++- 3 files changed, 83 insertions(+), 18 deletions(-) diff --git a/src/main/java/org/kpmp/packages/PackageController.java b/src/main/java/org/kpmp/packages/PackageController.java index 50982e12..60ce6201 100755 --- a/src/main/java/org/kpmp/packages/PackageController.java +++ b/src/main/java/org/kpmp/packages/PackageController.java @@ -39,6 +39,8 @@ public class PackageController { private String uploadStartedState; @Value("${package.state.metadata.received}") private String metadataReceivedState; + @Value("${package.state.upload.failed}") + private String uploadFailedState; private static final MessageFormat finish = new MessageFormat("{0} {1}"); private static final MessageFormat fileUploadRequest = new MessageFormat( @@ -54,7 +56,8 @@ public class PackageController { @Autowired public PackageController(PackageService packageService, LoggingService logger, - ShibbolethUserService shibUserService, UniversalIdGenerator universalIdGenerator, GoogleDriveService driveService) { + ShibbolethUserService shibUserService, UniversalIdGenerator universalIdGenerator, + GoogleDriveService driveService) { this.packageService = packageService; this.logger = logger; this.shibUserService = shibUserService; @@ -71,20 +74,26 @@ public PackageController(PackageService packageService, LoggingService logger, @RequestMapping(value = "/v1/packages", method = RequestMethod.POST) public @ResponseBody PackageResponse postPackageInformation(@RequestBody String packageInfoString, - HttpServletRequest request) throws JSONException, IOException { - PackageResponse packageResponse = new PackageResponse(); + HttpServletRequest request) { + PackageResponse packageResponse = new PackageResponse(); String packageId = universalIdGenerator.generateUniversalId(); packageResponse.setPackageId(packageId); packageService.sendStateChangeEvent(packageId, uploadStartedState, null); - JSONObject packageInfo = new JSONObject(packageInfoString); - logger.logInfoMessage(this.getClass(), packageId, "Posting package info: " + packageInfo, request); - User user = shibUserService.getUser(request); - packageService.savePackageInformation(packageInfo, user, packageId); - Boolean largeFilesChecked = (Boolean) packageInfo.optBoolean("largeFilesChecked"); - if (largeFilesChecked) { - packageResponse.setGdriveId(driveService.createFolder(packageId)); + JSONObject packageInfo; + try { + packageInfo = new JSONObject(packageInfoString); + logger.logInfoMessage(this.getClass(), packageId, "Posting package info: " + packageInfo, request); + User user = shibUserService.getUser(request); + packageService.savePackageInformation(packageInfo, user, packageId); + Boolean largeFilesChecked = (Boolean) packageInfo.optBoolean("largeFilesChecked"); + if (largeFilesChecked) { + packageResponse.setGdriveId(driveService.createFolder(packageId)); + } + packageService.sendStateChangeEvent(packageId, metadataReceivedState, packageResponse.getGdriveId()); + } catch (JSONException | IOException e) { + logger.logErrorMessage(this.getClass(), packageId, e.getMessage(), request); + packageService.sendStateChangeEvent(packageId, uploadFailedState, e.getMessage()); } - packageService.sendStateChangeEvent(packageId, metadataReceivedState, packageResponse.getGdriveId()); return packageResponse; } @@ -94,13 +103,18 @@ public PackageController(PackageService packageService, LoggingService logger, @RequestParam("qqfile") MultipartFile file, @RequestParam("qqfilename") String filename, @RequestParam("qqtotalfilesize") long fileSize, @RequestParam(name = "qqtotalparts", defaultValue = "1") int chunks, - @RequestParam(name = "qqpartindex", defaultValue = "0") int chunk, HttpServletRequest request) - throws Exception { + @RequestParam(name = "qqpartindex", defaultValue = "0") int chunk, HttpServletRequest request) { String message = fileUploadRequest.format(new Object[] { filename, packageId, fileSize, chunk, chunks }); logger.logInfoMessage(this.getClass(), packageId, message, request); - packageService.saveFile(file, packageId, filename, shouldAppend(chunk)); + try { + packageService.saveFile(file, packageId, filename, shouldAppend(chunk)); + } catch (Exception e) { + logger.logErrorMessage(this.getClass(), packageId, e.getMessage(), request); + packageService.sendStateChangeEvent(packageId, uploadFailedState, e.getMessage()); + return new FileUploadResponse(false); + } return new FileUploadResponse(true); } diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index b9c6f844..0fcd67c7 100755 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -29,4 +29,5 @@ logging.file=orion-data.log package.state.metadata.received=METADATA_RECEIVED package.state.upload.succeeded=UPLOAD_SUCCEEDED package.state.upload.started=UPLOAD_STARTED -package.state.files.received=FILES_RECEIVED \ No newline at end of file +package.state.files.received=FILES_RECEIVED +package.state.upload.failed=UPLOAD_FAILED \ No newline at end of file diff --git a/src/test/java/org/kpmp/packages/PackageControllerTest.java b/src/test/java/org/kpmp/packages/PackageControllerTest.java index 81df7104..5327fa19 100755 --- a/src/test/java/org/kpmp/packages/PackageControllerTest.java +++ b/src/test/java/org/kpmp/packages/PackageControllerTest.java @@ -3,6 +3,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; @@ -10,6 +11,7 @@ import static org.mockito.Mockito.when; import java.io.IOException; +import java.io.UnsupportedEncodingException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; @@ -54,10 +56,12 @@ public class PackageControllerTest { @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); - controller = new PackageController(packageService, logger, shibUserService, universalIdGenerator, googleDriveService); + controller = new PackageController(packageService, logger, shibUserService, universalIdGenerator, + googleDriveService); ReflectionTestUtils.setField(controller, "filesReceivedState", "FILES_RECEIVED"); ReflectionTestUtils.setField(controller, "uploadStartedState", "UPLOAD_STARTED"); ReflectionTestUtils.setField(controller, "metadataReceivedState", "METADATA_RECEIVED"); + ReflectionTestUtils.setField(controller, "uploadFailedState", "UPLOAD_FAILED"); } @@ -80,10 +84,56 @@ public void testGetAllPackages() throws JSONException, IOException { } @Test - public void testPostPackageInfo() throws Exception { + public void testPostPackageInformation_whenSaveThrowsException() throws Exception { String packageInfoString = "{\"packageType\":\"blah\"}"; when(universalIdGenerator.generateUniversalId()).thenReturn("universalId"); + when(packageService.savePackageInformation(any(JSONObject.class), any(User.class), any(String.class))) + .thenThrow(new JSONException("FAIL")); + HttpServletRequest request = mock(HttpServletRequest.class); + User user = mock(User.class); + when(shibUserService.getUser(request)).thenReturn(user); + + PackageResponse response = controller.postPackageInformation(packageInfoString, request); + assertEquals(null, response.getGdriveId()); + verify(logger).logErrorMessage(PackageController.class, "universalId", "FAIL", request); + verify(packageService).sendStateChangeEvent("universalId", "UPLOAD_FAILED", "FAIL"); + } + + @Test + public void testPostPackageInformation_whenShibUserServiceThrowsException() throws Exception { + String packageInfoString = "{\"packageType\":\"blah\"}"; + when(universalIdGenerator.generateUniversalId()).thenReturn("universalId"); + HttpServletRequest request = mock(HttpServletRequest.class); + when(shibUserService.getUser(request)).thenThrow(new UnsupportedEncodingException("WHAT?")); + + PackageResponse response = controller.postPackageInformation(packageInfoString, request); + + assertEquals(null, response.getGdriveId()); + verify(logger).logErrorMessage(PackageController.class, "universalId", "WHAT?", request); + verify(packageService).sendStateChangeEvent("universalId", "UPLOAD_FAILED", "WHAT?"); + } + + @Test + public void testPostPackageInformation_whenGoogleDriveServiceThrowsException() throws Exception { + String packageInfoString = "{\"packageType\":\"blah\",\"largeFilesChecked\":true}"; + when(universalIdGenerator.generateUniversalId()).thenReturn("universalId"); + HttpServletRequest request = mock(HttpServletRequest.class); + User user = mock(User.class); + when(shibUserService.getUser(request)).thenReturn(user); + when(googleDriveService.createFolder("universalId")).thenThrow(new IOException("NO DICE")); + + PackageResponse response = controller.postPackageInformation(packageInfoString, request); + + assertEquals(null, response.getGdriveId()); + verify(logger).logErrorMessage(PackageController.class, "universalId", "NO DICE", request); + verify(packageService).sendStateChangeEvent("universalId", "UPLOAD_FAILED", "NO DICE"); + } + + @Test + public void testPostPackageInformation() throws Exception { + String packageInfoString = "{\"packageType\":\"blah\"}"; + when(universalIdGenerator.generateUniversalId()).thenReturn("universalId"); HttpServletRequest request = mock(HttpServletRequest.class); User user = mock(User.class); when(shibUserService.getUser(request)).thenReturn(user); @@ -107,7 +157,7 @@ public void testPostPackageInfo() throws Exception { } @Test - public void testPostPackageInfoLargeFile() throws Exception { + public void testPostPackageInformationLargeFile() throws Exception { String packageInfoString = "{\"packageType\":\"blah\",\"largeFilesChecked\":true}"; when(universalIdGenerator.generateUniversalId()).thenReturn("universalId"); From 9e9c346ee329e7e7c6d301a4ce5aae80cc3502f5 Mon Sep 17 00:00:00 2001 From: Becky Reamy Date: Mon, 28 Oct 2019 16:32:11 -0400 Subject: [PATCH 22/26] KPMP-1270: Finished adding error states captured in controller --- .../java/org/kpmp/logging/LoggingService.java | 47 ++++++------------- .../org/kpmp/packages/PackageController.java | 15 +++--- .../shibboleth/ShibbolethUserService.java | 4 +- .../java/org/kpmp/shibboleth/UTF8Encoder.java | 3 +- .../kpmp/packages/PackageControllerTest.java | 35 +++++++------- 5 files changed, 44 insertions(+), 60 deletions(-) diff --git a/src/main/java/org/kpmp/logging/LoggingService.java b/src/main/java/org/kpmp/logging/LoggingService.java index ea938c12..cf83ca01 100644 --- a/src/main/java/org/kpmp/logging/LoggingService.java +++ b/src/main/java/org/kpmp/logging/LoggingService.java @@ -1,7 +1,5 @@ package org.kpmp.logging; -import java.io.UnsupportedEncodingException; - import javax.servlet.http.HttpServletRequest; import org.kpmp.shibboleth.ShibbolethUserService; @@ -25,16 +23,11 @@ public LoggingService(ShibbolethUserService shibUserService) { @SuppressWarnings("rawtypes") public void logInfoMessage(Class clazz, String packageId, String message, HttpServletRequest request) { Logger log = LoggerFactory.getLogger(clazz); - try { - User user = shibUserService.getUser(request); - if (user == null) { - log.info(LOG_MESSAGE_FORMAT, "Unknown user", packageId, request.getRequestURI(), message); - } else { - log.info(LOG_MESSAGE_FORMAT, user.toString(), packageId, request.getRequestURI(), message); - } - } catch (UnsupportedEncodingException e) { - log.error(LOG_MESSAGE_FORMAT, "unknown", packageId, request.getRequestURI(), - "ERROR: Unable to get user information from request: " + e.getMessage()); + User user = shibUserService.getUser(request); + if (user == null) { + log.info(LOG_MESSAGE_FORMAT, "Unknown user", packageId, request.getRequestURI(), message); + } else { + log.info(LOG_MESSAGE_FORMAT, user.toString(), packageId, request.getRequestURI(), message); } } @@ -51,16 +44,11 @@ public void logInfoMessage(Class clazz, User user, String packageId, String uri, @SuppressWarnings("rawtypes") public void logErrorMessage(Class clazz, String packageId, String message, HttpServletRequest request) { Logger log = LoggerFactory.getLogger(clazz); - try { - User user = shibUserService.getUser(request); - if (user == null) { - log.error(LOG_MESSAGE_FORMAT, "Unknown user", packageId, request.getRequestURI(), message); - } else { - log.error(LOG_MESSAGE_FORMAT, user.toString(), packageId, request.getRequestURI(), message); - } - } catch (UnsupportedEncodingException e) { - log.error(LOG_MESSAGE_FORMAT, "unknown", packageId, request.getRequestURI(), - "ERROR: Unable to get user information from request: " + e.getMessage()); + User user = shibUserService.getUser(request); + if (user == null) { + log.error(LOG_MESSAGE_FORMAT, "Unknown user", packageId, request.getRequestURI(), message); + } else { + log.error(LOG_MESSAGE_FORMAT, user.toString(), packageId, request.getRequestURI(), message); } } @@ -77,16 +65,11 @@ public void logErrorMessage(Class clazz, User user, String packageId, String uri @SuppressWarnings("rawtypes") public void logWarnMessage(Class clazz, String packageId, String message, HttpServletRequest request) { Logger log = LoggerFactory.getLogger(clazz); - try { - User user = shibUserService.getUser(request); - if (user == null) { - log.warn(LOG_MESSAGE_FORMAT, "Unknown user", packageId, request.getRequestURI(), message); - } else { - log.warn(LOG_MESSAGE_FORMAT, user.toString(), packageId, request.getRequestURI(), message); - } - } catch (UnsupportedEncodingException e) { - log.error(LOG_MESSAGE_FORMAT, "unknown", packageId, request.getRequestURI(), - "ERROR: Unable to get user information from request: " + e.getMessage()); + User user = shibUserService.getUser(request); + if (user == null) { + log.warn(LOG_MESSAGE_FORMAT, "Unknown user", packageId, request.getRequestURI(), message); + } else { + log.warn(LOG_MESSAGE_FORMAT, user.toString(), packageId, request.getRequestURI(), message); } } diff --git a/src/main/java/org/kpmp/packages/PackageController.java b/src/main/java/org/kpmp/packages/PackageController.java index 60ce6201..8b40c913 100755 --- a/src/main/java/org/kpmp/packages/PackageController.java +++ b/src/main/java/org/kpmp/packages/PackageController.java @@ -1,7 +1,6 @@ package org.kpmp.packages; import java.io.IOException; -import java.io.UnsupportedEncodingException; import java.text.MessageFormat; import java.util.List; @@ -140,7 +139,7 @@ public PackageController(PackageService packageService, LoggingService logger, @RequestMapping(value = "/v1/packages/{packageId}/files/finish", method = RequestMethod.POST) public @ResponseBody FileUploadResponse finishUpload(@PathVariable("packageId") String packageId, - @RequestBody String hostname, HttpServletRequest request) throws UnsupportedEncodingException { + @RequestBody String hostname, HttpServletRequest request) { packageService.sendStateChangeEvent(packageId, filesReceivedState, null); FileUploadResponse fileUploadResponse; @@ -150,17 +149,19 @@ public PackageController(PackageService packageService, LoggingService logger, try { String removeErrantEqualSign = hostname.replace("=", ""); packageService.createZipFile(packageId, removeErrantEqualSign, shibUserService.getUser(request)); - fileUploadResponse = new FileUploadResponse(true); } catch (Exception e) { - logger.logErrorMessage(this.getClass(), packageId, - finish.format(new Object[] { "error getting metadata for package id: ", packageId }), request); + String errorMessage = finish + .format(new Object[] { "error getting metadata for package id: ", packageId }); + logger.logErrorMessage(this.getClass(), packageId, errorMessage, request); fileUploadResponse = new FileUploadResponse(false); + packageService.sendStateChangeEvent(packageId, uploadFailedState, errorMessage); } } else { - logger.logErrorMessage(this.getClass(), packageId, - finish.format(new Object[] { "Unable to zip package with package id: ", packageId }), request); + String errorMessage = finish.format(new Object[] { "Unable to zip package with package id: ", packageId }); + logger.logErrorMessage(this.getClass(), packageId, errorMessage, request); fileUploadResponse = new FileUploadResponse(false); + packageService.sendStateChangeEvent(packageId, uploadFailedState, errorMessage); } return fileUploadResponse; } diff --git a/src/main/java/org/kpmp/shibboleth/ShibbolethUserService.java b/src/main/java/org/kpmp/shibboleth/ShibbolethUserService.java index b82caa41..dd575696 100644 --- a/src/main/java/org/kpmp/shibboleth/ShibbolethUserService.java +++ b/src/main/java/org/kpmp/shibboleth/ShibbolethUserService.java @@ -1,7 +1,5 @@ package org.kpmp.shibboleth; -import java.io.UnsupportedEncodingException; - import javax.servlet.http.HttpServletRequest; import org.kpmp.users.User; @@ -18,7 +16,7 @@ public ShibbolethUserService(UTF8Encoder encoder) { this.encoder = encoder; } - public User getUser(HttpServletRequest request) throws UnsupportedEncodingException { + public User getUser(HttpServletRequest request) { String value = handleNull(request.getHeader("mail")); String email = encoder.convertFromLatin1(value); diff --git a/src/main/java/org/kpmp/shibboleth/UTF8Encoder.java b/src/main/java/org/kpmp/shibboleth/UTF8Encoder.java index e6a6d190..122e50f6 100644 --- a/src/main/java/org/kpmp/shibboleth/UTF8Encoder.java +++ b/src/main/java/org/kpmp/shibboleth/UTF8Encoder.java @@ -1,6 +1,5 @@ package org.kpmp.shibboleth; -import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets; import org.springframework.stereotype.Component; @@ -8,7 +7,7 @@ @Component class UTF8Encoder { - public String convertFromLatin1(String value) throws UnsupportedEncodingException { + public String convertFromLatin1(String value) { return new String(value.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8); } diff --git a/src/test/java/org/kpmp/packages/PackageControllerTest.java b/src/test/java/org/kpmp/packages/PackageControllerTest.java index 5327fa19..1a7a5c39 100755 --- a/src/test/java/org/kpmp/packages/PackageControllerTest.java +++ b/src/test/java/org/kpmp/packages/PackageControllerTest.java @@ -11,7 +11,6 @@ import static org.mockito.Mockito.when; import java.io.IOException; -import java.io.UnsupportedEncodingException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; @@ -100,20 +99,6 @@ public void testPostPackageInformation_whenSaveThrowsException() throws Exceptio verify(packageService).sendStateChangeEvent("universalId", "UPLOAD_FAILED", "FAIL"); } - @Test - public void testPostPackageInformation_whenShibUserServiceThrowsException() throws Exception { - String packageInfoString = "{\"packageType\":\"blah\"}"; - when(universalIdGenerator.generateUniversalId()).thenReturn("universalId"); - HttpServletRequest request = mock(HttpServletRequest.class); - when(shibUserService.getUser(request)).thenThrow(new UnsupportedEncodingException("WHAT?")); - - PackageResponse response = controller.postPackageInformation(packageInfoString, request); - - assertEquals(null, response.getGdriveId()); - verify(logger).logErrorMessage(PackageController.class, "universalId", "WHAT?", request); - verify(packageService).sendStateChangeEvent("universalId", "UPLOAD_FAILED", "WHAT?"); - } - @Test public void testPostPackageInformation_whenGoogleDriveServiceThrowsException() throws Exception { String packageInfoString = "{\"packageType\":\"blah\",\"largeFilesChecked\":true}"; @@ -204,14 +189,28 @@ public void testPostFilesToPackage_whenInitialChunk() throws Exception { MultipartFile file = mock(MultipartFile.class); HttpServletRequest request = mock(HttpServletRequest.class); - controller.postFilesToPackage("packageId", file, "filename", 1234, 3, 0, request); + FileUploadResponse response = controller.postFilesToPackage("packageId", file, "filename", 1234, 3, 0, request); + assertEquals(true, response.isSuccess()); verify(packageService).saveFile(file, "packageId", "filename", false); verify(logger).logInfoMessage(PackageController.class, "packageId", "Posting file: filename to package with id: packageId, filesize: 1,234, chunk: 0 out of 3 chunks", request); } + @Test + public void testPostFilesToPackage_whenSaveThrowsException() throws Exception { + MultipartFile file = mock(MultipartFile.class); + HttpServletRequest request = mock(HttpServletRequest.class); + doThrow(new Exception("NOPE")).when(packageService).saveFile(file, "packageId", "filename", false); + + FileUploadResponse response = controller.postFilesToPackage("packageId", file, "filename", 1234, 3, 0, request); + + assertEquals(false, response.isSuccess()); + verify(logger).logErrorMessage(PackageController.class, "packageId", "NOPE", request); + verify(packageService).sendStateChangeEvent("packageId", "UPLOAD_FAILED", "NOPE"); + } + @Test public void testFinishUpload() throws Exception { User user = mock(User.class); @@ -245,6 +244,8 @@ public void testFinishUpload_whenCreateZipThrows() throws Exception { verify(logger).logErrorMessage(PackageController.class, "3545", "error getting metadata for package id: 3545", request); verify(packageService).sendStateChangeEvent("3545", "FILES_RECEIVED", null); + verify(packageService).sendStateChangeEvent("3545", "UPLOAD_FAILED", + "error getting metadata for package id: 3545"); } @Test @@ -262,6 +263,8 @@ public void testFinishUpload_whenMismatchedFiles() throws Exception { verify(logger).logErrorMessage(PackageController.class, "3545", "Unable to zip package with package id: 3545", request); verify(packageService).sendStateChangeEvent("3545", "FILES_RECEIVED", null); + verify(packageService).sendStateChangeEvent("3545", "UPLOAD_FAILED", + "Unable to zip package with package id: 3545"); } @Test From f95bff8c460c96245cdef7c1690301e11defae96 Mon Sep 17 00:00:00 2001 From: Becky Reamy Date: Mon, 28 Oct 2019 16:53:58 -0400 Subject: [PATCH 23/26] KPMP-1270: Hit other places where a package upload might fail --- src/main/java/org/kpmp/packages/PackageController.java | 2 +- src/main/java/org/kpmp/packages/PackageService.java | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/kpmp/packages/PackageController.java b/src/main/java/org/kpmp/packages/PackageController.java index 8b40c913..f80c9411 100755 --- a/src/main/java/org/kpmp/packages/PackageController.java +++ b/src/main/java/org/kpmp/packages/PackageController.java @@ -89,7 +89,7 @@ public PackageController(PackageService packageService, LoggingService logger, packageResponse.setGdriveId(driveService.createFolder(packageId)); } packageService.sendStateChangeEvent(packageId, metadataReceivedState, packageResponse.getGdriveId()); - } catch (JSONException | IOException e) { + } catch (Exception e) { logger.logErrorMessage(this.getClass(), packageId, e.getMessage(), request); packageService.sendStateChangeEvent(packageId, uploadFailedState, e.getMessage()); } diff --git a/src/main/java/org/kpmp/packages/PackageService.java b/src/main/java/org/kpmp/packages/PackageService.java index b7566e38..ac68cad4 100755 --- a/src/main/java/org/kpmp/packages/PackageService.java +++ b/src/main/java/org/kpmp/packages/PackageService.java @@ -32,6 +32,8 @@ public class PackageService { @Value("${package.state.upload.succeeded}") private String uploadSucceededState; + @Value("${package.state.upload.failed}") + private String uploadFailedState; private static final MessageFormat zipPackage = new MessageFormat("{0} {1}"); private static final MessageFormat fileUploadFinishTiming = new MessageFormat( @@ -149,10 +151,12 @@ public void run() { } else { logger.logErrorMessage(PackageService.class, user, packageId, PackageService.class.getSimpleName(), "Unable to zip package"); + sendStateChangeEvent(packageId, uploadFailedState, "Unable to zip package"); } } catch (Exception e) { logger.logErrorMessage(PackageService.class, user, packageId, PackageService.class.getSimpleName(), e.getMessage()); + sendStateChangeEvent(packageId, uploadFailedState, e.getMessage()); } } From 7033e16e110e8fe710a9eeaebfe8bd1417a452dc Mon Sep 17 00:00:00 2001 From: Becky Reamy Date: Tue, 29 Oct 2019 10:54:19 -0400 Subject: [PATCH 24/26] KPMP-1270: Removing node_modules --- scripts/2.5/node_modules/.bin/semver | 1 - scripts/2.5/node_modules/assert/CHANGELOG.md | 14 - scripts/2.5/node_modules/assert/LICENSE | 18 - scripts/2.5/node_modules/assert/README.md | 73 - scripts/2.5/node_modules/assert/package.json | 77 - scripts/2.5/node_modules/bson/HISTORY.md | 268 - scripts/2.5/node_modules/bson/LICENSE.md | 201 - scripts/2.5/node_modules/bson/README.md | 170 - scripts/2.5/node_modules/bson/bower.json | 25 - .../node_modules/bson/browser_build/bson.js | 17769 ---------------- .../bson/browser_build/package.json | 8 - scripts/2.5/node_modules/bson/index.js | 46 - .../2.5/node_modules/bson/lib/bson/binary.js | 384 - .../2.5/node_modules/bson/lib/bson/bson.js | 386 - .../2.5/node_modules/bson/lib/bson/code.js | 24 - .../2.5/node_modules/bson/lib/bson/db_ref.js | 32 - .../node_modules/bson/lib/bson/decimal128.js | 820 - .../2.5/node_modules/bson/lib/bson/double.js | 33 - .../bson/lib/bson/float_parser.js | 124 - .../2.5/node_modules/bson/lib/bson/int_32.js | 33 - .../2.5/node_modules/bson/lib/bson/long.js | 851 - scripts/2.5/node_modules/bson/lib/bson/map.js | 128 - .../2.5/node_modules/bson/lib/bson/max_key.js | 14 - .../2.5/node_modules/bson/lib/bson/min_key.js | 14 - .../node_modules/bson/lib/bson/objectid.js | 389 - .../bson/lib/bson/parser/calculate_size.js | 255 - .../bson/lib/bson/parser/deserializer.js | 782 - .../bson/lib/bson/parser/serializer.js | 1182 - .../bson/lib/bson/parser/utils.js | 28 - .../2.5/node_modules/bson/lib/bson/regexp.js | 33 - .../2.5/node_modules/bson/lib/bson/symbol.js | 50 - .../node_modules/bson/lib/bson/timestamp.js | 854 - scripts/2.5/node_modules/bson/package.json | 87 - .../define-properties/.editorconfig | 13 - .../node_modules/define-properties/.eslintrc | 12 - .../node_modules/define-properties/.jscs.json | 175 - .../define-properties/.travis.yml | 233 - .../define-properties/CHANGELOG.md | 44 - .../node_modules/define-properties/LICENSE | 21 - .../node_modules/define-properties/README.md | 86 - .../node_modules/define-properties/index.js | 58 - .../define-properties/package.json | 99 - .../define-properties/test/index.js | 125 - .../node_modules/es-abstract/.editorconfig | 13 - .../2.5/node_modules/es-abstract/.eslintrc | 70 - .../es-abstract/.github/FUNDING.yml | 12 - scripts/2.5/node_modules/es-abstract/.nycrc | 14 - .../2.5/node_modules/es-abstract/.travis.yml | 333 - .../2.5/node_modules/es-abstract/CHANGELOG.md | 264 - .../node_modules/es-abstract/GetIntrinsic.js | 189 - scripts/2.5/node_modules/es-abstract/LICENSE | 21 - scripts/2.5/node_modules/es-abstract/Makefile | 61 - .../2.5/node_modules/es-abstract/README.md | 48 - .../2.5/node_modules/es-abstract/es2015.js | 1464 -- .../2.5/node_modules/es-abstract/es2016.js | 98 - .../2.5/node_modules/es-abstract/es2017.js | 71 - .../2.5/node_modules/es-abstract/es2018.js | 289 - .../2.5/node_modules/es-abstract/es2019.js | 111 - scripts/2.5/node_modules/es-abstract/es5.js | 544 - scripts/2.5/node_modules/es-abstract/es6.js | 3 - scripts/2.5/node_modules/es-abstract/es7.js | 3 - .../es-abstract/helpers/assertRecord.js | 48 - .../es-abstract/helpers/assign.js | 21 - .../es-abstract/helpers/callBind.js | 17 - .../es-abstract/helpers/callBound.js | 15 - .../node_modules/es-abstract/helpers/every.js | 10 - .../es-abstract/helpers/forEach.js | 7 - .../es-abstract/helpers/getInferredName.js | 10 - .../es-abstract/helpers/getIteratorMethod.js | 46 - .../es-abstract/helpers/getProto.js | 15 - .../helpers/getSymbolDescription.js | 30 - .../es-abstract/helpers/isFinite.js | 5 - .../node_modules/es-abstract/helpers/isNaN.js | 5 - .../es-abstract/helpers/isPrefixOf.js | 13 - .../es-abstract/helpers/isPrimitive.js | 5 - .../helpers/isPropertyDescriptor.js | 31 - .../helpers/isSamePropertyDescriptor.js | 20 - .../es-abstract/helpers/maxSafeInteger.js | 8 - .../node_modules/es-abstract/helpers/mod.js | 6 - .../es-abstract/helpers/regexTester.js | 11 - .../es-abstract/helpers/setProto.js | 16 - .../node_modules/es-abstract/helpers/sign.js | 5 - scripts/2.5/node_modules/es-abstract/index.js | 26 - .../es-abstract/operations/.eslintrc | 5 - .../2.5/node_modules/es-abstract/package.json | 130 - .../node_modules/es-abstract/test/.eslintrc | 13 - .../es-abstract/test/GetIntrinsic.js | 48 - .../node_modules/es-abstract/test/diffOps.js | 26 - .../node_modules/es-abstract/test/es2015.js | 9 - .../node_modules/es-abstract/test/es2016.js | 9 - .../node_modules/es-abstract/test/es2017.js | 9 - .../node_modules/es-abstract/test/es2018.js | 9 - .../node_modules/es-abstract/test/es2019.js | 9 - .../2.5/node_modules/es-abstract/test/es5.js | 782 - .../2.5/node_modules/es-abstract/test/es6.js | 18 - .../2.5/node_modules/es-abstract/test/es7.js | 18 - .../es-abstract/test/helpers/assertRecord.js | 60 - .../test/helpers/getSymbolDescription.js | 50 - .../es-abstract/test/helpers/values.js | 121 - .../node_modules/es-abstract/test/index.js | 30 - .../node_modules/es-abstract/test/tests.js | 4075 ---- .../es-to-primitive/.editorconfig | 20 - .../node_modules/es-to-primitive/.eslintrc | 14 - .../node_modules/es-to-primitive/.jscs.json | 176 - .../node_modules/es-to-primitive/.travis.yml | 243 - .../node_modules/es-to-primitive/CHANGELOG.md | 38 - .../2.5/node_modules/es-to-primitive/LICENSE | 22 - .../2.5/node_modules/es-to-primitive/Makefile | 61 - .../node_modules/es-to-primitive/README.md | 51 - .../node_modules/es-to-primitive/es2015.js | 75 - .../2.5/node_modules/es-to-primitive/es5.js | 45 - .../2.5/node_modules/es-to-primitive/es6.js | 3 - .../es-to-primitive/helpers/isPrimitive.js | 3 - .../2.5/node_modules/es-to-primitive/index.js | 17 - .../node_modules/es-to-primitive/package.json | 113 - .../es-to-primitive/test/.eslintrc | 9 - .../es-to-primitive/test/es2015.js | 151 - .../node_modules/es-to-primitive/test/es5.js | 94 - .../node_modules/es-to-primitive/test/es6.js | 151 - .../es-to-primitive/test/index.js | 20 - .../node_modules/es6-object-assign/LICENSE | 22 - .../node_modules/es6-object-assign/README.md | 96 - .../node_modules/es6-object-assign/auto.js | 3 - .../dist/object-assign-auto.js | 54 - .../dist/object-assign-auto.min.js | 1 - .../es6-object-assign/dist/object-assign.js | 50 - .../dist/object-assign.min.js | 1 - .../node_modules/es6-object-assign/index.js | 46 - .../es6-object-assign/package.json | 72 - .../node_modules/function-bind/.editorconfig | 20 - .../2.5/node_modules/function-bind/.eslintrc | 15 - .../2.5/node_modules/function-bind/.jscs.json | 176 - .../2.5/node_modules/function-bind/.npmignore | 22 - .../node_modules/function-bind/.travis.yml | 168 - .../2.5/node_modules/function-bind/LICENSE | 20 - .../2.5/node_modules/function-bind/README.md | 48 - .../function-bind/implementation.js | 52 - .../2.5/node_modules/function-bind/index.js | 5 - .../node_modules/function-bind/package.json | 98 - .../node_modules/function-bind/test/.eslintrc | 9 - .../node_modules/function-bind/test/index.js | 252 - .../2.5/node_modules/has-symbols/.eslintrc | 10 - .../2.5/node_modules/has-symbols/.npmignore | 37 - .../2.5/node_modules/has-symbols/.travis.yml | 113 - .../2.5/node_modules/has-symbols/CHANGELOG.md | 3 - scripts/2.5/node_modules/has-symbols/LICENSE | 21 - .../2.5/node_modules/has-symbols/README.md | 45 - scripts/2.5/node_modules/has-symbols/index.js | 13 - .../2.5/node_modules/has-symbols/package.json | 108 - scripts/2.5/node_modules/has-symbols/shams.js | 42 - .../node_modules/has-symbols/test/index.js | 22 - .../has-symbols/test/shams/core-js.js | 28 - .../test/shams/get-own-property-symbols.js | 28 - .../node_modules/has-symbols/test/tests.js | 54 - scripts/2.5/node_modules/has/LICENSE-MIT | 22 - scripts/2.5/node_modules/has/README.md | 18 - scripts/2.5/node_modules/has/package.json | 75 - scripts/2.5/node_modules/has/src/index.js | 5 - scripts/2.5/node_modules/has/test/index.js | 10 - scripts/2.5/node_modules/inherits/LICENSE | 16 - scripts/2.5/node_modules/inherits/README.md | 42 - scripts/2.5/node_modules/inherits/inherits.js | 9 - .../node_modules/inherits/inherits_browser.js | 27 - .../2.5/node_modules/inherits/package.json | 61 - .../node_modules/is-arguments/.editorconfig | 20 - .../2.5/node_modules/is-arguments/.eslintrc | 10 - .../2.5/node_modules/is-arguments/.jscs.json | 176 - .../2.5/node_modules/is-arguments/.travis.yml | 248 - .../node_modules/is-arguments/CHANGELOG.md | 32 - scripts/2.5/node_modules/is-arguments/LICENSE | 20 - .../2.5/node_modules/is-arguments/README.md | 49 - .../2.5/node_modules/is-arguments/index.js | 31 - .../node_modules/is-arguments/package.json | 101 - scripts/2.5/node_modules/is-arguments/test.js | 44 - .../node_modules/is-callable/.editorconfig | 20 - .../2.5/node_modules/is-callable/.eslintrc | 11 - .../node_modules/is-callable/.istanbul.yml | 47 - .../2.5/node_modules/is-callable/.jscs.json | 176 - .../2.5/node_modules/is-callable/.travis.yml | 225 - .../2.5/node_modules/is-callable/CHANGELOG.md | 56 - scripts/2.5/node_modules/is-callable/LICENSE | 22 - scripts/2.5/node_modules/is-callable/Makefile | 61 - .../2.5/node_modules/is-callable/README.md | 59 - scripts/2.5/node_modules/is-callable/index.js | 37 - .../2.5/node_modules/is-callable/package.json | 124 - scripts/2.5/node_modules/is-callable/test.js | 158 - .../2.5/node_modules/is-date-object/.eslintrc | 9 - .../node_modules/is-date-object/.jscs.json | 122 - .../node_modules/is-date-object/.npmignore | 28 - .../node_modules/is-date-object/.travis.yml | 58 - .../node_modules/is-date-object/CHANGELOG.md | 10 - .../2.5/node_modules/is-date-object/LICENSE | 22 - .../2.5/node_modules/is-date-object/Makefile | 61 - .../2.5/node_modules/is-date-object/README.md | 53 - .../2.5/node_modules/is-date-object/index.js | 20 - .../node_modules/is-date-object/package.json | 93 - .../2.5/node_modules/is-date-object/test.js | 33 - .../is-generator-function/.editorconfig | 20 - .../is-generator-function/.eslintrc | 9 - .../is-generator-function/.jscs.json | 176 - .../node_modules/is-generator-function/.nvmrc | 1 - .../is-generator-function/.travis.yml | 191 - .../is-generator-function/CHANGELOG.md | 44 - .../is-generator-function/LICENSE | 20 - .../is-generator-function/Makefile | 61 - .../is-generator-function/README.md | 42 - .../is-generator-function/index.js | 32 - .../is-generator-function/package.json | 101 - .../is-generator-function/test/.eslintrc | 5 - .../is-generator-function/test/corejs.js | 5 - .../is-generator-function/test/index.js | 94 - .../is-generator-function/test/uglified.js | 8 - scripts/2.5/node_modules/is-nan/.eslintrc | 9 - scripts/2.5/node_modules/is-nan/.jscs.json | 124 - scripts/2.5/node_modules/is-nan/.npmignore | 15 - scripts/2.5/node_modules/is-nan/.travis.yml | 49 - scripts/2.5/node_modules/is-nan/CHANGELOG.md | 27 - scripts/2.5/node_modules/is-nan/LICENSE | 20 - scripts/2.5/node_modules/is-nan/README.md | 56 - .../2.5/node_modules/is-nan/implementation.js | 7 - scripts/2.5/node_modules/is-nan/index.js | 17 - scripts/2.5/node_modules/is-nan/package.json | 101 - scripts/2.5/node_modules/is-nan/polyfill.js | 10 - scripts/2.5/node_modules/is-nan/shim.js | 12 - scripts/2.5/node_modules/is-nan/test/index.js | 10 - .../2.5/node_modules/is-nan/test/shimmed.js | 28 - scripts/2.5/node_modules/is-nan/test/tests.js | 36 - scripts/2.5/node_modules/is-regex/.eslintrc | 9 - scripts/2.5/node_modules/is-regex/.jscs.json | 176 - scripts/2.5/node_modules/is-regex/.npmignore | 15 - scripts/2.5/node_modules/is-regex/.travis.yml | 165 - .../2.5/node_modules/is-regex/CHANGELOG.md | 27 - scripts/2.5/node_modules/is-regex/LICENSE | 20 - scripts/2.5/node_modules/is-regex/Makefile | 61 - scripts/2.5/node_modules/is-regex/README.md | 54 - scripts/2.5/node_modules/is-regex/index.js | 39 - .../2.5/node_modules/is-regex/package.json | 100 - scripts/2.5/node_modules/is-regex/test.js | 58 - .../2.5/node_modules/is-symbol/.editorconfig | 13 - scripts/2.5/node_modules/is-symbol/.eslintrc | 9 - scripts/2.5/node_modules/is-symbol/.jscs.json | 176 - scripts/2.5/node_modules/is-symbol/.nvmrc | 1 - .../2.5/node_modules/is-symbol/.travis.yml | 241 - .../2.5/node_modules/is-symbol/CHANGELOG.md | 12 - scripts/2.5/node_modules/is-symbol/LICENSE | 22 - scripts/2.5/node_modules/is-symbol/Makefile | 61 - scripts/2.5/node_modules/is-symbol/README.md | 46 - scripts/2.5/node_modules/is-symbol/index.js | 35 - .../2.5/node_modules/is-symbol/package.json | 96 - .../2.5/node_modules/is-symbol/test/.eslintrc | 7 - .../2.5/node_modules/is-symbol/test/index.js | 92 - .../2.5/node_modules/memory-pager/.travis.yml | 4 - scripts/2.5/node_modules/memory-pager/LICENSE | 21 - .../2.5/node_modules/memory-pager/README.md | 65 - .../2.5/node_modules/memory-pager/index.js | 160 - .../node_modules/memory-pager/package.json | 52 - scripts/2.5/node_modules/memory-pager/test.js | 80 - scripts/2.5/node_modules/mongodb/HISTORY.md | 2485 --- scripts/2.5/node_modules/mongodb/LICENSE.md | 201 - scripts/2.5/node_modules/mongodb/README.md | 499 - scripts/2.5/node_modules/mongodb/index.js | 68 - scripts/2.5/node_modules/mongodb/lib/admin.js | 293 - .../mongodb/lib/aggregation_cursor.js | 370 - scripts/2.5/node_modules/mongodb/lib/apm.js | 31 - .../node_modules/mongodb/lib/async/.eslintrc | 5 - .../mongodb/lib/async/async_iterator.js | 33 - .../node_modules/mongodb/lib/bulk/common.js | 1239 -- .../node_modules/mongodb/lib/bulk/ordered.js | 105 - .../mongodb/lib/bulk/unordered.js | 118 - .../node_modules/mongodb/lib/change_stream.js | 576 - .../node_modules/mongodb/lib/collection.js | 2113 -- .../mongodb/lib/command_cursor.js | 269 - .../2.5/node_modules/mongodb/lib/constants.js | 10 - .../mongodb/lib/core/auth/auth_provider.js | 158 - .../lib/core/auth/defaultAuthProviders.js | 29 - .../mongodb/lib/core/auth/gssapi.js | 241 - .../lib/core/auth/mongo_credentials.js | 81 - .../mongodb/lib/core/auth/mongocr.js | 51 - .../mongodb/lib/core/auth/plain.js | 35 - .../mongodb/lib/core/auth/scram.js | 293 - .../mongodb/lib/core/auth/sspi.js | 131 - .../mongodb/lib/core/auth/x509.js | 26 - .../mongodb/lib/core/connection/apm.js | 236 - .../lib/core/connection/command_result.js | 36 - .../mongodb/lib/core/connection/commands.js | 507 - .../mongodb/lib/core/connection/connect.js | 370 - .../mongodb/lib/core/connection/connection.js | 628 - .../mongodb/lib/core/connection/logger.js | 246 - .../mongodb/lib/core/connection/msg.js | 221 - .../mongodb/lib/core/connection/pool.js | 1256 -- .../mongodb/lib/core/connection/utils.js | 57 - .../node_modules/mongodb/lib/core/cursor.js | 886 - .../node_modules/mongodb/lib/core/error.js | 237 - .../node_modules/mongodb/lib/core/index.js | 50 - .../mongodb/lib/core/sdam/monitoring.js | 235 - .../mongodb/lib/core/sdam/server.js | 511 - .../lib/core/sdam/server_description.js | 163 - .../mongodb/lib/core/sdam/server_selectors.js | 244 - .../mongodb/lib/core/sdam/srv_polling.js | 135 - .../mongodb/lib/core/sdam/topology.js | 1186 -- .../lib/core/sdam/topology_description.js | 408 - .../node_modules/mongodb/lib/core/sessions.js | 767 - .../mongodb/lib/core/tools/smoke_plugin.js | 61 - .../mongodb/lib/core/topologies/mongos.js | 1392 -- .../lib/core/topologies/read_preference.js | 202 - .../mongodb/lib/core/topologies/replset.js | 1553 -- .../lib/core/topologies/replset_state.js | 1121 - .../mongodb/lib/core/topologies/server.js | 989 - .../mongodb/lib/core/topologies/shared.js | 476 - .../mongodb/lib/core/transactions.js | 168 - .../mongodb/lib/core/uri_parser.js | 637 - .../node_modules/mongodb/lib/core/utils.js | 177 - .../mongodb/lib/core/wireprotocol/command.js | 170 - .../lib/core/wireprotocol/compression.js | 73 - .../lib/core/wireprotocol/constants.js | 13 - .../mongodb/lib/core/wireprotocol/get_more.js | 90 - .../mongodb/lib/core/wireprotocol/index.js | 18 - .../lib/core/wireprotocol/kill_cursors.js | 70 - .../mongodb/lib/core/wireprotocol/query.js | 231 - .../mongodb/lib/core/wireprotocol/shared.js | 115 - .../lib/core/wireprotocol/write_command.js | 50 - .../2.5/node_modules/mongodb/lib/cursor.js | 1089 - scripts/2.5/node_modules/mongodb/lib/db.js | 1029 - .../mongodb/lib/dynamic_loaders.js | 32 - scripts/2.5/node_modules/mongodb/lib/error.js | 45 - .../mongodb/lib/gridfs-stream/download.js | 421 - .../mongodb/lib/gridfs-stream/index.js | 358 - .../mongodb/lib/gridfs-stream/upload.js | 538 - .../node_modules/mongodb/lib/gridfs/chunk.js | 236 - .../mongodb/lib/gridfs/grid_store.js | 1913 -- .../node_modules/mongodb/lib/mongo_client.js | 479 - .../mongodb/lib/operations/add_user.js | 96 - .../mongodb/lib/operations/admin_ops.js | 62 - .../mongodb/lib/operations/aggregate.js | 106 - .../mongodb/lib/operations/bulk_write.js | 104 - .../mongodb/lib/operations/close.js | 46 - .../mongodb/lib/operations/collection_ops.js | 374 - .../mongodb/lib/operations/collections.js | 55 - .../mongodb/lib/operations/command.js | 120 - .../mongodb/lib/operations/command_v2.js | 109 - .../lib/operations/common_functions.js | 406 - .../mongodb/lib/operations/connect.js | 709 - .../mongodb/lib/operations/count.js | 72 - .../mongodb/lib/operations/count_documents.js | 41 - .../lib/operations/create_collection.js | 118 - .../mongodb/lib/operations/create_index.js | 92 - .../mongodb/lib/operations/create_indexes.js | 61 - .../mongodb/lib/operations/cursor_ops.js | 239 - .../mongodb/lib/operations/db_ops.js | 831 - .../mongodb/lib/operations/delete_many.js | 25 - .../mongodb/lib/operations/delete_one.js | 25 - .../mongodb/lib/operations/distinct.js | 85 - .../mongodb/lib/operations/drop.js | 53 - .../mongodb/lib/operations/drop_index.js | 42 - .../mongodb/lib/operations/drop_indexes.js | 23 - .../operations/estimated_document_count.js | 58 - .../operations/execute_db_admin_command.js | 34 - .../lib/operations/execute_operation.js | 198 - .../mongodb/lib/operations/explain.js | 23 - .../mongodb/lib/operations/find.js | 35 - .../mongodb/lib/operations/find_and_modify.js | 98 - .../mongodb/lib/operations/find_one.js | 33 - .../lib/operations/find_one_and_delete.js | 16 - .../lib/operations/find_one_and_replace.js | 18 - .../lib/operations/find_one_and_update.js | 19 - .../lib/operations/geo_haystack_search.js | 79 - .../mongodb/lib/operations/has_next.js | 40 - .../mongodb/lib/operations/index_exists.js | 39 - .../lib/operations/index_information.js | 23 - .../mongodb/lib/operations/indexes.js | 22 - .../mongodb/lib/operations/insert_many.js | 63 - .../mongodb/lib/operations/insert_one.js | 39 - .../mongodb/lib/operations/is_capped.js | 19 - .../lib/operations/list_collections.js | 106 - .../mongodb/lib/operations/list_databases.js | 38 - .../mongodb/lib/operations/list_indexes.js | 42 - .../mongodb/lib/operations/map_reduce.js | 189 - .../mongodb/lib/operations/next.js | 32 - .../mongodb/lib/operations/operation.js | 67 - .../lib/operations/options_operation.js | 32 - .../mongodb/lib/operations/profiling_level.js | 31 - .../mongodb/lib/operations/re_index.js | 28 - .../mongodb/lib/operations/remove_user.js | 52 - .../mongodb/lib/operations/rename.js | 61 - .../mongodb/lib/operations/replace_one.js | 47 - .../lib/operations/set_profiling_level.js | 48 - .../mongodb/lib/operations/stats.js | 45 - .../mongodb/lib/operations/to_array.js | 66 - .../mongodb/lib/operations/update_many.js | 29 - .../mongodb/lib/operations/update_one.js | 44 - .../lib/operations/validate_collection.js | 40 - .../node_modules/mongodb/lib/read_concern.js | 61 - .../mongodb/lib/topologies/mongos.js | 452 - .../mongodb/lib/topologies/native_topology.js | 72 - .../mongodb/lib/topologies/replset.js | 496 - .../mongodb/lib/topologies/server.js | 455 - .../mongodb/lib/topologies/topology_base.js | 438 - .../node_modules/mongodb/lib/url_parser.js | 623 - scripts/2.5/node_modules/mongodb/lib/utils.js | 716 - .../node_modules/mongodb/lib/write_concern.js | 66 - scripts/2.5/node_modules/mongodb/package.json | 104 - .../2.5/node_modules/object-inspect/.nycrc | 17 - .../node_modules/object-inspect/.travis.yml | 216 - .../2.5/node_modules/object-inspect/LICENSE | 18 - .../object-inspect/example/all.js | 19 - .../object-inspect/example/circular.js | 4 - .../node_modules/object-inspect/example/fn.js | 3 - .../object-inspect/example/inspect.js | 7 - .../2.5/node_modules/object-inspect/index.js | 257 - .../node_modules/object-inspect/package.json | 84 - .../object-inspect/readme.markdown | 61 - .../object-inspect/test-core-js.js | 16 - .../object-inspect/test/bigint.js | 30 - .../object-inspect/test/browser/dom.js | 15 - .../object-inspect/test/circular.js | 9 - .../node_modules/object-inspect/test/deep.js | 9 - .../object-inspect/test/element.js | 53 - .../node_modules/object-inspect/test/err.js | 29 - .../node_modules/object-inspect/test/fn.js | 28 - .../node_modules/object-inspect/test/has.js | 31 - .../node_modules/object-inspect/test/holes.js | 15 - .../object-inspect/test/inspect.js | 8 - .../object-inspect/test/lowbyte.js | 12 - .../object-inspect/test/number.js | 12 - .../object-inspect/test/quoteStyle.js | 17 - .../node_modules/object-inspect/test/undef.js | 12 - .../object-inspect/test/values.js | 136 - .../object-inspect/util.inspect.js | 1 - scripts/2.5/node_modules/object-is/.jscs.json | 55 - scripts/2.5/node_modules/object-is/.npmignore | 15 - .../2.5/node_modules/object-is/.travis.yml | 18 - scripts/2.5/node_modules/object-is/LICENSE | 20 - scripts/2.5/node_modules/object-is/README.md | 54 - scripts/2.5/node_modules/object-is/index.js | 19 - .../2.5/node_modules/object-is/package.json | 86 - scripts/2.5/node_modules/object-is/test.js | 50 - .../node_modules/object-keys/.editorconfig | 13 - .../2.5/node_modules/object-keys/.eslintrc | 17 - .../2.5/node_modules/object-keys/.travis.yml | 277 - .../2.5/node_modules/object-keys/CHANGELOG.md | 232 - scripts/2.5/node_modules/object-keys/LICENSE | 21 - .../2.5/node_modules/object-keys/README.md | 76 - .../object-keys/implementation.js | 122 - scripts/2.5/node_modules/object-keys/index.js | 32 - .../node_modules/object-keys/isArguments.js | 17 - .../2.5/node_modules/object-keys/package.json | 118 - .../node_modules/object-keys/test/index.js | 5 - .../node_modules/object.entries/.editorconfig | 20 - .../2.5/node_modules/object.entries/.eslintrc | 11 - .../node_modules/object.entries/.travis.yml | 269 - .../node_modules/object.entries/CHANGELOG.md | 33 - .../2.5/node_modules/object.entries/LICENSE | 22 - .../2.5/node_modules/object.entries/README.md | 59 - .../2.5/node_modules/object.entries/auto.js | 3 - .../object.entries/implementation.js | 17 - .../2.5/node_modules/object.entries/index.js | 17 - .../node_modules/object.entries/package.json | 107 - .../node_modules/object.entries/polyfill.js | 7 - .../2.5/node_modules/object.entries/shim.js | 14 - .../object.entries/test/.eslintrc | 11 - .../node_modules/object.entries/test/index.js | 17 - .../object.entries/test/shimmed.js | 36 - .../node_modules/object.entries/test/tests.js | 84 - .../node_modules/require_optional/.npmignore | 33 - .../node_modules/require_optional/.travis.yml | 9 - .../node_modules/require_optional/HISTORY.md | 7 - .../2.5/node_modules/require_optional/LICENSE | 201 - .../node_modules/require_optional/README.md | 2 - .../node_modules/require_optional/index.js | 128 - .../require_optional/package.json | 67 - .../require_optional/test/nestedTest/index.js | 8 - .../test/nestedTest/package.json | 11 - .../test/require_optional_tests.js | 59 - .../2.5/node_modules/resolve-from/index.js | 23 - scripts/2.5/node_modules/resolve-from/license | 21 - .../node_modules/resolve-from/package.json | 66 - .../2.5/node_modules/resolve-from/readme.md | 58 - scripts/2.5/node_modules/safe-buffer/LICENSE | 21 - .../2.5/node_modules/safe-buffer/README.md | 586 - .../2.5/node_modules/safe-buffer/index.d.ts | 187 - scripts/2.5/node_modules/safe-buffer/index.js | 64 - .../2.5/node_modules/safe-buffer/package.json | 62 - .../2.5/node_modules/saslprep/.editorconfig | 10 - .../2.5/node_modules/saslprep/.gitattributes | 1 - scripts/2.5/node_modules/saslprep/.travis.yml | 10 - .../2.5/node_modules/saslprep/CHANGELOG.md | 19 - scripts/2.5/node_modules/saslprep/LICENSE | 22 - .../2.5/node_modules/saslprep/code-points.mem | Bin 419864 -> 0 bytes .../saslprep/generate-code-points.js | 51 - scripts/2.5/node_modules/saslprep/index.js | 157 - .../node_modules/saslprep/lib/code-points.js | 996 - .../saslprep/lib/memory-code-points.js | 39 - scripts/2.5/node_modules/saslprep/lib/util.js | 21 - .../2.5/node_modules/saslprep/package.json | 100 - scripts/2.5/node_modules/saslprep/readme.md | 31 - .../2.5/node_modules/saslprep/test/index.js | 76 - .../2.5/node_modules/saslprep/test/util.js | 16 - scripts/2.5/node_modules/semver/CHANGELOG.md | 39 - scripts/2.5/node_modules/semver/LICENSE | 15 - scripts/2.5/node_modules/semver/README.md | 412 - scripts/2.5/node_modules/semver/bin/semver | 160 - scripts/2.5/node_modules/semver/package.json | 60 - scripts/2.5/node_modules/semver/range.bnf | 16 - scripts/2.5/node_modules/semver/semver.js | 1483 -- .../node_modules/sparse-bitfield/.npmignore | 1 - .../node_modules/sparse-bitfield/.travis.yml | 6 - .../2.5/node_modules/sparse-bitfield/LICENSE | 21 - .../node_modules/sparse-bitfield/README.md | 62 - .../2.5/node_modules/sparse-bitfield/index.js | 95 - .../node_modules/sparse-bitfield/package.json | 55 - .../2.5/node_modules/sparse-bitfield/test.js | 79 - .../string.prototype.trimleft/.editorconfig | 20 - .../string.prototype.trimleft/.eslintrc | 15 - .../string.prototype.trimleft/.travis.yml | 317 - .../string.prototype.trimleft/CHANGELOG.md | 30 - .../string.prototype.trimleft/LICENSE | 22 - .../string.prototype.trimleft/README.md | 47 - .../string.prototype.trimleft/auto.js | 3 - .../implementation.js | 12 - .../string.prototype.trimleft/index.js | 18 - .../string.prototype.trimleft/package.json | 97 - .../string.prototype.trimleft/polyfill.js | 14 - .../string.prototype.trimleft/shim.js | 14 - .../string.prototype.trimleft/test/index.js | 18 - .../string.prototype.trimleft/test/shimmed.js | 37 - .../string.prototype.trimleft/test/tests.js | 26 - .../string.prototype.trimright/.editorconfig | 20 - .../string.prototype.trimright/.eslintrc | 15 - .../string.prototype.trimright/.travis.yml | 317 - .../string.prototype.trimright/CHANGELOG.md | 30 - .../string.prototype.trimright/LICENSE | 22 - .../string.prototype.trimright/README.md | 47 - .../string.prototype.trimright/auto.js | 3 - .../implementation.js | 12 - .../string.prototype.trimright/index.js | 18 - .../string.prototype.trimright/package.json | 97 - .../string.prototype.trimright/polyfill.js | 14 - .../string.prototype.trimright/shim.js | 14 - .../string.prototype.trimright/test/index.js | 17 - .../test/shimmed.js | 37 - .../string.prototype.trimright/test/tests.js | 26 - scripts/2.5/node_modules/util/CHANGELOG.md | 22 - scripts/2.5/node_modules/util/LICENSE | 18 - scripts/2.5/node_modules/util/README.md | 48 - scripts/2.5/node_modules/util/package.json | 73 - .../2.5/node_modules/util/support/isBuffer.js | 3 - .../util/support/isBufferBrowser.js | 6 - .../2.5/node_modules/util/support/types.js | 422 - scripts/2.5/node_modules/util/util.js | 715 - 549 files changed, 96526 deletions(-) delete mode 120000 scripts/2.5/node_modules/.bin/semver delete mode 100644 scripts/2.5/node_modules/assert/CHANGELOG.md delete mode 100644 scripts/2.5/node_modules/assert/LICENSE delete mode 100644 scripts/2.5/node_modules/assert/README.md delete mode 100644 scripts/2.5/node_modules/assert/package.json delete mode 100644 scripts/2.5/node_modules/bson/HISTORY.md delete mode 100644 scripts/2.5/node_modules/bson/LICENSE.md delete mode 100644 scripts/2.5/node_modules/bson/README.md delete mode 100644 scripts/2.5/node_modules/bson/bower.json delete mode 100644 scripts/2.5/node_modules/bson/browser_build/bson.js delete mode 100644 scripts/2.5/node_modules/bson/browser_build/package.json delete mode 100644 scripts/2.5/node_modules/bson/index.js delete mode 100644 scripts/2.5/node_modules/bson/lib/bson/binary.js delete mode 100644 scripts/2.5/node_modules/bson/lib/bson/bson.js delete mode 100644 scripts/2.5/node_modules/bson/lib/bson/code.js delete mode 100644 scripts/2.5/node_modules/bson/lib/bson/db_ref.js delete mode 100644 scripts/2.5/node_modules/bson/lib/bson/decimal128.js delete mode 100644 scripts/2.5/node_modules/bson/lib/bson/double.js delete mode 100644 scripts/2.5/node_modules/bson/lib/bson/float_parser.js delete mode 100644 scripts/2.5/node_modules/bson/lib/bson/int_32.js delete mode 100644 scripts/2.5/node_modules/bson/lib/bson/long.js delete mode 100644 scripts/2.5/node_modules/bson/lib/bson/map.js delete mode 100644 scripts/2.5/node_modules/bson/lib/bson/max_key.js delete mode 100644 scripts/2.5/node_modules/bson/lib/bson/min_key.js delete mode 100644 scripts/2.5/node_modules/bson/lib/bson/objectid.js delete mode 100644 scripts/2.5/node_modules/bson/lib/bson/parser/calculate_size.js delete mode 100644 scripts/2.5/node_modules/bson/lib/bson/parser/deserializer.js delete mode 100644 scripts/2.5/node_modules/bson/lib/bson/parser/serializer.js delete mode 100644 scripts/2.5/node_modules/bson/lib/bson/parser/utils.js delete mode 100644 scripts/2.5/node_modules/bson/lib/bson/regexp.js delete mode 100644 scripts/2.5/node_modules/bson/lib/bson/symbol.js delete mode 100644 scripts/2.5/node_modules/bson/lib/bson/timestamp.js delete mode 100644 scripts/2.5/node_modules/bson/package.json delete mode 100644 scripts/2.5/node_modules/define-properties/.editorconfig delete mode 100644 scripts/2.5/node_modules/define-properties/.eslintrc delete mode 100644 scripts/2.5/node_modules/define-properties/.jscs.json delete mode 100644 scripts/2.5/node_modules/define-properties/.travis.yml delete mode 100644 scripts/2.5/node_modules/define-properties/CHANGELOG.md delete mode 100644 scripts/2.5/node_modules/define-properties/LICENSE delete mode 100644 scripts/2.5/node_modules/define-properties/README.md delete mode 100644 scripts/2.5/node_modules/define-properties/index.js delete mode 100644 scripts/2.5/node_modules/define-properties/package.json delete mode 100644 scripts/2.5/node_modules/define-properties/test/index.js delete mode 100644 scripts/2.5/node_modules/es-abstract/.editorconfig delete mode 100644 scripts/2.5/node_modules/es-abstract/.eslintrc delete mode 100644 scripts/2.5/node_modules/es-abstract/.github/FUNDING.yml delete mode 100644 scripts/2.5/node_modules/es-abstract/.nycrc delete mode 100644 scripts/2.5/node_modules/es-abstract/.travis.yml delete mode 100644 scripts/2.5/node_modules/es-abstract/CHANGELOG.md delete mode 100644 scripts/2.5/node_modules/es-abstract/GetIntrinsic.js delete mode 100644 scripts/2.5/node_modules/es-abstract/LICENSE delete mode 100644 scripts/2.5/node_modules/es-abstract/Makefile delete mode 100644 scripts/2.5/node_modules/es-abstract/README.md delete mode 100644 scripts/2.5/node_modules/es-abstract/es2015.js delete mode 100644 scripts/2.5/node_modules/es-abstract/es2016.js delete mode 100644 scripts/2.5/node_modules/es-abstract/es2017.js delete mode 100644 scripts/2.5/node_modules/es-abstract/es2018.js delete mode 100644 scripts/2.5/node_modules/es-abstract/es2019.js delete mode 100644 scripts/2.5/node_modules/es-abstract/es5.js delete mode 100644 scripts/2.5/node_modules/es-abstract/es6.js delete mode 100644 scripts/2.5/node_modules/es-abstract/es7.js delete mode 100644 scripts/2.5/node_modules/es-abstract/helpers/assertRecord.js delete mode 100644 scripts/2.5/node_modules/es-abstract/helpers/assign.js delete mode 100644 scripts/2.5/node_modules/es-abstract/helpers/callBind.js delete mode 100644 scripts/2.5/node_modules/es-abstract/helpers/callBound.js delete mode 100644 scripts/2.5/node_modules/es-abstract/helpers/every.js delete mode 100644 scripts/2.5/node_modules/es-abstract/helpers/forEach.js delete mode 100644 scripts/2.5/node_modules/es-abstract/helpers/getInferredName.js delete mode 100644 scripts/2.5/node_modules/es-abstract/helpers/getIteratorMethod.js delete mode 100644 scripts/2.5/node_modules/es-abstract/helpers/getProto.js delete mode 100644 scripts/2.5/node_modules/es-abstract/helpers/getSymbolDescription.js delete mode 100644 scripts/2.5/node_modules/es-abstract/helpers/isFinite.js delete mode 100644 scripts/2.5/node_modules/es-abstract/helpers/isNaN.js delete mode 100644 scripts/2.5/node_modules/es-abstract/helpers/isPrefixOf.js delete mode 100644 scripts/2.5/node_modules/es-abstract/helpers/isPrimitive.js delete mode 100644 scripts/2.5/node_modules/es-abstract/helpers/isPropertyDescriptor.js delete mode 100644 scripts/2.5/node_modules/es-abstract/helpers/isSamePropertyDescriptor.js delete mode 100644 scripts/2.5/node_modules/es-abstract/helpers/maxSafeInteger.js delete mode 100644 scripts/2.5/node_modules/es-abstract/helpers/mod.js delete mode 100644 scripts/2.5/node_modules/es-abstract/helpers/regexTester.js delete mode 100644 scripts/2.5/node_modules/es-abstract/helpers/setProto.js delete mode 100644 scripts/2.5/node_modules/es-abstract/helpers/sign.js delete mode 100644 scripts/2.5/node_modules/es-abstract/index.js delete mode 100644 scripts/2.5/node_modules/es-abstract/operations/.eslintrc delete mode 100644 scripts/2.5/node_modules/es-abstract/package.json delete mode 100644 scripts/2.5/node_modules/es-abstract/test/.eslintrc delete mode 100644 scripts/2.5/node_modules/es-abstract/test/GetIntrinsic.js delete mode 100644 scripts/2.5/node_modules/es-abstract/test/diffOps.js delete mode 100644 scripts/2.5/node_modules/es-abstract/test/es2015.js delete mode 100644 scripts/2.5/node_modules/es-abstract/test/es2016.js delete mode 100644 scripts/2.5/node_modules/es-abstract/test/es2017.js delete mode 100644 scripts/2.5/node_modules/es-abstract/test/es2018.js delete mode 100644 scripts/2.5/node_modules/es-abstract/test/es2019.js delete mode 100644 scripts/2.5/node_modules/es-abstract/test/es5.js delete mode 100644 scripts/2.5/node_modules/es-abstract/test/es6.js delete mode 100644 scripts/2.5/node_modules/es-abstract/test/es7.js delete mode 100644 scripts/2.5/node_modules/es-abstract/test/helpers/assertRecord.js delete mode 100644 scripts/2.5/node_modules/es-abstract/test/helpers/getSymbolDescription.js delete mode 100644 scripts/2.5/node_modules/es-abstract/test/helpers/values.js delete mode 100644 scripts/2.5/node_modules/es-abstract/test/index.js delete mode 100644 scripts/2.5/node_modules/es-abstract/test/tests.js delete mode 100644 scripts/2.5/node_modules/es-to-primitive/.editorconfig delete mode 100644 scripts/2.5/node_modules/es-to-primitive/.eslintrc delete mode 100644 scripts/2.5/node_modules/es-to-primitive/.jscs.json delete mode 100644 scripts/2.5/node_modules/es-to-primitive/.travis.yml delete mode 100644 scripts/2.5/node_modules/es-to-primitive/CHANGELOG.md delete mode 100644 scripts/2.5/node_modules/es-to-primitive/LICENSE delete mode 100644 scripts/2.5/node_modules/es-to-primitive/Makefile delete mode 100644 scripts/2.5/node_modules/es-to-primitive/README.md delete mode 100644 scripts/2.5/node_modules/es-to-primitive/es2015.js delete mode 100644 scripts/2.5/node_modules/es-to-primitive/es5.js delete mode 100644 scripts/2.5/node_modules/es-to-primitive/es6.js delete mode 100644 scripts/2.5/node_modules/es-to-primitive/helpers/isPrimitive.js delete mode 100644 scripts/2.5/node_modules/es-to-primitive/index.js delete mode 100644 scripts/2.5/node_modules/es-to-primitive/package.json delete mode 100644 scripts/2.5/node_modules/es-to-primitive/test/.eslintrc delete mode 100644 scripts/2.5/node_modules/es-to-primitive/test/es2015.js delete mode 100644 scripts/2.5/node_modules/es-to-primitive/test/es5.js delete mode 100644 scripts/2.5/node_modules/es-to-primitive/test/es6.js delete mode 100644 scripts/2.5/node_modules/es-to-primitive/test/index.js delete mode 100644 scripts/2.5/node_modules/es6-object-assign/LICENSE delete mode 100644 scripts/2.5/node_modules/es6-object-assign/README.md delete mode 100644 scripts/2.5/node_modules/es6-object-assign/auto.js delete mode 100644 scripts/2.5/node_modules/es6-object-assign/dist/object-assign-auto.js delete mode 100644 scripts/2.5/node_modules/es6-object-assign/dist/object-assign-auto.min.js delete mode 100644 scripts/2.5/node_modules/es6-object-assign/dist/object-assign.js delete mode 100644 scripts/2.5/node_modules/es6-object-assign/dist/object-assign.min.js delete mode 100644 scripts/2.5/node_modules/es6-object-assign/index.js delete mode 100644 scripts/2.5/node_modules/es6-object-assign/package.json delete mode 100644 scripts/2.5/node_modules/function-bind/.editorconfig delete mode 100644 scripts/2.5/node_modules/function-bind/.eslintrc delete mode 100644 scripts/2.5/node_modules/function-bind/.jscs.json delete mode 100644 scripts/2.5/node_modules/function-bind/.npmignore delete mode 100644 scripts/2.5/node_modules/function-bind/.travis.yml delete mode 100644 scripts/2.5/node_modules/function-bind/LICENSE delete mode 100644 scripts/2.5/node_modules/function-bind/README.md delete mode 100644 scripts/2.5/node_modules/function-bind/implementation.js delete mode 100644 scripts/2.5/node_modules/function-bind/index.js delete mode 100644 scripts/2.5/node_modules/function-bind/package.json delete mode 100644 scripts/2.5/node_modules/function-bind/test/.eslintrc delete mode 100644 scripts/2.5/node_modules/function-bind/test/index.js delete mode 100644 scripts/2.5/node_modules/has-symbols/.eslintrc delete mode 100644 scripts/2.5/node_modules/has-symbols/.npmignore delete mode 100644 scripts/2.5/node_modules/has-symbols/.travis.yml delete mode 100644 scripts/2.5/node_modules/has-symbols/CHANGELOG.md delete mode 100644 scripts/2.5/node_modules/has-symbols/LICENSE delete mode 100644 scripts/2.5/node_modules/has-symbols/README.md delete mode 100644 scripts/2.5/node_modules/has-symbols/index.js delete mode 100644 scripts/2.5/node_modules/has-symbols/package.json delete mode 100644 scripts/2.5/node_modules/has-symbols/shams.js delete mode 100644 scripts/2.5/node_modules/has-symbols/test/index.js delete mode 100644 scripts/2.5/node_modules/has-symbols/test/shams/core-js.js delete mode 100644 scripts/2.5/node_modules/has-symbols/test/shams/get-own-property-symbols.js delete mode 100644 scripts/2.5/node_modules/has-symbols/test/tests.js delete mode 100644 scripts/2.5/node_modules/has/LICENSE-MIT delete mode 100644 scripts/2.5/node_modules/has/README.md delete mode 100644 scripts/2.5/node_modules/has/package.json delete mode 100644 scripts/2.5/node_modules/has/src/index.js delete mode 100644 scripts/2.5/node_modules/has/test/index.js delete mode 100644 scripts/2.5/node_modules/inherits/LICENSE delete mode 100644 scripts/2.5/node_modules/inherits/README.md delete mode 100644 scripts/2.5/node_modules/inherits/inherits.js delete mode 100644 scripts/2.5/node_modules/inherits/inherits_browser.js delete mode 100644 scripts/2.5/node_modules/inherits/package.json delete mode 100644 scripts/2.5/node_modules/is-arguments/.editorconfig delete mode 100644 scripts/2.5/node_modules/is-arguments/.eslintrc delete mode 100644 scripts/2.5/node_modules/is-arguments/.jscs.json delete mode 100644 scripts/2.5/node_modules/is-arguments/.travis.yml delete mode 100644 scripts/2.5/node_modules/is-arguments/CHANGELOG.md delete mode 100644 scripts/2.5/node_modules/is-arguments/LICENSE delete mode 100644 scripts/2.5/node_modules/is-arguments/README.md delete mode 100644 scripts/2.5/node_modules/is-arguments/index.js delete mode 100644 scripts/2.5/node_modules/is-arguments/package.json delete mode 100644 scripts/2.5/node_modules/is-arguments/test.js delete mode 100644 scripts/2.5/node_modules/is-callable/.editorconfig delete mode 100644 scripts/2.5/node_modules/is-callable/.eslintrc delete mode 100644 scripts/2.5/node_modules/is-callable/.istanbul.yml delete mode 100644 scripts/2.5/node_modules/is-callable/.jscs.json delete mode 100644 scripts/2.5/node_modules/is-callable/.travis.yml delete mode 100644 scripts/2.5/node_modules/is-callable/CHANGELOG.md delete mode 100644 scripts/2.5/node_modules/is-callable/LICENSE delete mode 100644 scripts/2.5/node_modules/is-callable/Makefile delete mode 100644 scripts/2.5/node_modules/is-callable/README.md delete mode 100644 scripts/2.5/node_modules/is-callable/index.js delete mode 100644 scripts/2.5/node_modules/is-callable/package.json delete mode 100644 scripts/2.5/node_modules/is-callable/test.js delete mode 100644 scripts/2.5/node_modules/is-date-object/.eslintrc delete mode 100644 scripts/2.5/node_modules/is-date-object/.jscs.json delete mode 100644 scripts/2.5/node_modules/is-date-object/.npmignore delete mode 100644 scripts/2.5/node_modules/is-date-object/.travis.yml delete mode 100644 scripts/2.5/node_modules/is-date-object/CHANGELOG.md delete mode 100644 scripts/2.5/node_modules/is-date-object/LICENSE delete mode 100644 scripts/2.5/node_modules/is-date-object/Makefile delete mode 100644 scripts/2.5/node_modules/is-date-object/README.md delete mode 100644 scripts/2.5/node_modules/is-date-object/index.js delete mode 100644 scripts/2.5/node_modules/is-date-object/package.json delete mode 100644 scripts/2.5/node_modules/is-date-object/test.js delete mode 100644 scripts/2.5/node_modules/is-generator-function/.editorconfig delete mode 100644 scripts/2.5/node_modules/is-generator-function/.eslintrc delete mode 100644 scripts/2.5/node_modules/is-generator-function/.jscs.json delete mode 100644 scripts/2.5/node_modules/is-generator-function/.nvmrc delete mode 100644 scripts/2.5/node_modules/is-generator-function/.travis.yml delete mode 100644 scripts/2.5/node_modules/is-generator-function/CHANGELOG.md delete mode 100644 scripts/2.5/node_modules/is-generator-function/LICENSE delete mode 100644 scripts/2.5/node_modules/is-generator-function/Makefile delete mode 100644 scripts/2.5/node_modules/is-generator-function/README.md delete mode 100644 scripts/2.5/node_modules/is-generator-function/index.js delete mode 100644 scripts/2.5/node_modules/is-generator-function/package.json delete mode 100644 scripts/2.5/node_modules/is-generator-function/test/.eslintrc delete mode 100644 scripts/2.5/node_modules/is-generator-function/test/corejs.js delete mode 100644 scripts/2.5/node_modules/is-generator-function/test/index.js delete mode 100644 scripts/2.5/node_modules/is-generator-function/test/uglified.js delete mode 100644 scripts/2.5/node_modules/is-nan/.eslintrc delete mode 100644 scripts/2.5/node_modules/is-nan/.jscs.json delete mode 100644 scripts/2.5/node_modules/is-nan/.npmignore delete mode 100644 scripts/2.5/node_modules/is-nan/.travis.yml delete mode 100644 scripts/2.5/node_modules/is-nan/CHANGELOG.md delete mode 100644 scripts/2.5/node_modules/is-nan/LICENSE delete mode 100644 scripts/2.5/node_modules/is-nan/README.md delete mode 100644 scripts/2.5/node_modules/is-nan/implementation.js delete mode 100644 scripts/2.5/node_modules/is-nan/index.js delete mode 100644 scripts/2.5/node_modules/is-nan/package.json delete mode 100644 scripts/2.5/node_modules/is-nan/polyfill.js delete mode 100644 scripts/2.5/node_modules/is-nan/shim.js delete mode 100644 scripts/2.5/node_modules/is-nan/test/index.js delete mode 100644 scripts/2.5/node_modules/is-nan/test/shimmed.js delete mode 100644 scripts/2.5/node_modules/is-nan/test/tests.js delete mode 100644 scripts/2.5/node_modules/is-regex/.eslintrc delete mode 100644 scripts/2.5/node_modules/is-regex/.jscs.json delete mode 100644 scripts/2.5/node_modules/is-regex/.npmignore delete mode 100644 scripts/2.5/node_modules/is-regex/.travis.yml delete mode 100644 scripts/2.5/node_modules/is-regex/CHANGELOG.md delete mode 100644 scripts/2.5/node_modules/is-regex/LICENSE delete mode 100644 scripts/2.5/node_modules/is-regex/Makefile delete mode 100644 scripts/2.5/node_modules/is-regex/README.md delete mode 100644 scripts/2.5/node_modules/is-regex/index.js delete mode 100644 scripts/2.5/node_modules/is-regex/package.json delete mode 100644 scripts/2.5/node_modules/is-regex/test.js delete mode 100644 scripts/2.5/node_modules/is-symbol/.editorconfig delete mode 100644 scripts/2.5/node_modules/is-symbol/.eslintrc delete mode 100644 scripts/2.5/node_modules/is-symbol/.jscs.json delete mode 100644 scripts/2.5/node_modules/is-symbol/.nvmrc delete mode 100644 scripts/2.5/node_modules/is-symbol/.travis.yml delete mode 100644 scripts/2.5/node_modules/is-symbol/CHANGELOG.md delete mode 100644 scripts/2.5/node_modules/is-symbol/LICENSE delete mode 100644 scripts/2.5/node_modules/is-symbol/Makefile delete mode 100644 scripts/2.5/node_modules/is-symbol/README.md delete mode 100644 scripts/2.5/node_modules/is-symbol/index.js delete mode 100644 scripts/2.5/node_modules/is-symbol/package.json delete mode 100644 scripts/2.5/node_modules/is-symbol/test/.eslintrc delete mode 100644 scripts/2.5/node_modules/is-symbol/test/index.js delete mode 100644 scripts/2.5/node_modules/memory-pager/.travis.yml delete mode 100644 scripts/2.5/node_modules/memory-pager/LICENSE delete mode 100644 scripts/2.5/node_modules/memory-pager/README.md delete mode 100644 scripts/2.5/node_modules/memory-pager/index.js delete mode 100644 scripts/2.5/node_modules/memory-pager/package.json delete mode 100644 scripts/2.5/node_modules/memory-pager/test.js delete mode 100644 scripts/2.5/node_modules/mongodb/HISTORY.md delete mode 100644 scripts/2.5/node_modules/mongodb/LICENSE.md delete mode 100644 scripts/2.5/node_modules/mongodb/README.md delete mode 100644 scripts/2.5/node_modules/mongodb/index.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/admin.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/aggregation_cursor.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/apm.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/async/.eslintrc delete mode 100644 scripts/2.5/node_modules/mongodb/lib/async/async_iterator.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/bulk/common.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/bulk/ordered.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/bulk/unordered.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/change_stream.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/collection.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/command_cursor.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/constants.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/core/auth/auth_provider.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/core/auth/defaultAuthProviders.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/core/auth/gssapi.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/core/auth/mongo_credentials.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/core/auth/mongocr.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/core/auth/plain.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/core/auth/scram.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/core/auth/sspi.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/core/auth/x509.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/core/connection/apm.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/core/connection/command_result.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/core/connection/commands.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/core/connection/connect.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/core/connection/connection.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/core/connection/logger.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/core/connection/msg.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/core/connection/pool.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/core/connection/utils.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/core/cursor.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/core/error.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/core/index.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/core/sdam/monitoring.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/core/sdam/server.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/core/sdam/server_description.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/core/sdam/server_selectors.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/core/sdam/srv_polling.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/core/sdam/topology.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/core/sdam/topology_description.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/core/sessions.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/core/tools/smoke_plugin.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/core/topologies/mongos.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/core/topologies/read_preference.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/core/topologies/replset.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/core/topologies/replset_state.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/core/topologies/server.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/core/topologies/shared.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/core/transactions.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/core/uri_parser.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/core/utils.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/core/wireprotocol/command.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/core/wireprotocol/compression.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/core/wireprotocol/constants.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/core/wireprotocol/get_more.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/core/wireprotocol/index.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/core/wireprotocol/kill_cursors.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/core/wireprotocol/query.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/core/wireprotocol/shared.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/core/wireprotocol/write_command.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/cursor.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/db.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/dynamic_loaders.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/error.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/gridfs-stream/download.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/gridfs-stream/index.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/gridfs-stream/upload.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/gridfs/chunk.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/gridfs/grid_store.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/mongo_client.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/add_user.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/admin_ops.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/aggregate.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/bulk_write.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/close.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/collection_ops.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/collections.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/command.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/command_v2.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/common_functions.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/connect.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/count.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/count_documents.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/create_collection.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/create_index.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/create_indexes.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/cursor_ops.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/db_ops.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/delete_many.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/delete_one.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/distinct.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/drop.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/drop_index.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/drop_indexes.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/estimated_document_count.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/execute_db_admin_command.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/execute_operation.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/explain.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/find.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/find_and_modify.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/find_one.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/find_one_and_delete.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/find_one_and_replace.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/find_one_and_update.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/geo_haystack_search.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/has_next.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/index_exists.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/index_information.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/indexes.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/insert_many.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/insert_one.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/is_capped.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/list_collections.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/list_databases.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/list_indexes.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/map_reduce.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/next.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/operation.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/options_operation.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/profiling_level.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/re_index.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/remove_user.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/rename.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/replace_one.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/set_profiling_level.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/stats.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/to_array.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/update_many.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/update_one.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/operations/validate_collection.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/read_concern.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/topologies/mongos.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/topologies/native_topology.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/topologies/replset.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/topologies/server.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/topologies/topology_base.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/url_parser.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/utils.js delete mode 100644 scripts/2.5/node_modules/mongodb/lib/write_concern.js delete mode 100644 scripts/2.5/node_modules/mongodb/package.json delete mode 100644 scripts/2.5/node_modules/object-inspect/.nycrc delete mode 100644 scripts/2.5/node_modules/object-inspect/.travis.yml delete mode 100644 scripts/2.5/node_modules/object-inspect/LICENSE delete mode 100644 scripts/2.5/node_modules/object-inspect/example/all.js delete mode 100644 scripts/2.5/node_modules/object-inspect/example/circular.js delete mode 100644 scripts/2.5/node_modules/object-inspect/example/fn.js delete mode 100644 scripts/2.5/node_modules/object-inspect/example/inspect.js delete mode 100644 scripts/2.5/node_modules/object-inspect/index.js delete mode 100644 scripts/2.5/node_modules/object-inspect/package.json delete mode 100644 scripts/2.5/node_modules/object-inspect/readme.markdown delete mode 100644 scripts/2.5/node_modules/object-inspect/test-core-js.js delete mode 100644 scripts/2.5/node_modules/object-inspect/test/bigint.js delete mode 100644 scripts/2.5/node_modules/object-inspect/test/browser/dom.js delete mode 100644 scripts/2.5/node_modules/object-inspect/test/circular.js delete mode 100644 scripts/2.5/node_modules/object-inspect/test/deep.js delete mode 100644 scripts/2.5/node_modules/object-inspect/test/element.js delete mode 100644 scripts/2.5/node_modules/object-inspect/test/err.js delete mode 100644 scripts/2.5/node_modules/object-inspect/test/fn.js delete mode 100644 scripts/2.5/node_modules/object-inspect/test/has.js delete mode 100644 scripts/2.5/node_modules/object-inspect/test/holes.js delete mode 100644 scripts/2.5/node_modules/object-inspect/test/inspect.js delete mode 100644 scripts/2.5/node_modules/object-inspect/test/lowbyte.js delete mode 100644 scripts/2.5/node_modules/object-inspect/test/number.js delete mode 100644 scripts/2.5/node_modules/object-inspect/test/quoteStyle.js delete mode 100644 scripts/2.5/node_modules/object-inspect/test/undef.js delete mode 100644 scripts/2.5/node_modules/object-inspect/test/values.js delete mode 100644 scripts/2.5/node_modules/object-inspect/util.inspect.js delete mode 100644 scripts/2.5/node_modules/object-is/.jscs.json delete mode 100644 scripts/2.5/node_modules/object-is/.npmignore delete mode 100644 scripts/2.5/node_modules/object-is/.travis.yml delete mode 100644 scripts/2.5/node_modules/object-is/LICENSE delete mode 100644 scripts/2.5/node_modules/object-is/README.md delete mode 100644 scripts/2.5/node_modules/object-is/index.js delete mode 100644 scripts/2.5/node_modules/object-is/package.json delete mode 100644 scripts/2.5/node_modules/object-is/test.js delete mode 100644 scripts/2.5/node_modules/object-keys/.editorconfig delete mode 100644 scripts/2.5/node_modules/object-keys/.eslintrc delete mode 100644 scripts/2.5/node_modules/object-keys/.travis.yml delete mode 100644 scripts/2.5/node_modules/object-keys/CHANGELOG.md delete mode 100644 scripts/2.5/node_modules/object-keys/LICENSE delete mode 100644 scripts/2.5/node_modules/object-keys/README.md delete mode 100644 scripts/2.5/node_modules/object-keys/implementation.js delete mode 100644 scripts/2.5/node_modules/object-keys/index.js delete mode 100644 scripts/2.5/node_modules/object-keys/isArguments.js delete mode 100644 scripts/2.5/node_modules/object-keys/package.json delete mode 100644 scripts/2.5/node_modules/object-keys/test/index.js delete mode 100644 scripts/2.5/node_modules/object.entries/.editorconfig delete mode 100644 scripts/2.5/node_modules/object.entries/.eslintrc delete mode 100644 scripts/2.5/node_modules/object.entries/.travis.yml delete mode 100644 scripts/2.5/node_modules/object.entries/CHANGELOG.md delete mode 100644 scripts/2.5/node_modules/object.entries/LICENSE delete mode 100644 scripts/2.5/node_modules/object.entries/README.md delete mode 100644 scripts/2.5/node_modules/object.entries/auto.js delete mode 100644 scripts/2.5/node_modules/object.entries/implementation.js delete mode 100644 scripts/2.5/node_modules/object.entries/index.js delete mode 100644 scripts/2.5/node_modules/object.entries/package.json delete mode 100644 scripts/2.5/node_modules/object.entries/polyfill.js delete mode 100644 scripts/2.5/node_modules/object.entries/shim.js delete mode 100644 scripts/2.5/node_modules/object.entries/test/.eslintrc delete mode 100644 scripts/2.5/node_modules/object.entries/test/index.js delete mode 100644 scripts/2.5/node_modules/object.entries/test/shimmed.js delete mode 100644 scripts/2.5/node_modules/object.entries/test/tests.js delete mode 100644 scripts/2.5/node_modules/require_optional/.npmignore delete mode 100644 scripts/2.5/node_modules/require_optional/.travis.yml delete mode 100644 scripts/2.5/node_modules/require_optional/HISTORY.md delete mode 100644 scripts/2.5/node_modules/require_optional/LICENSE delete mode 100644 scripts/2.5/node_modules/require_optional/README.md delete mode 100644 scripts/2.5/node_modules/require_optional/index.js delete mode 100644 scripts/2.5/node_modules/require_optional/package.json delete mode 100644 scripts/2.5/node_modules/require_optional/test/nestedTest/index.js delete mode 100644 scripts/2.5/node_modules/require_optional/test/nestedTest/package.json delete mode 100644 scripts/2.5/node_modules/require_optional/test/require_optional_tests.js delete mode 100644 scripts/2.5/node_modules/resolve-from/index.js delete mode 100644 scripts/2.5/node_modules/resolve-from/license delete mode 100644 scripts/2.5/node_modules/resolve-from/package.json delete mode 100644 scripts/2.5/node_modules/resolve-from/readme.md delete mode 100644 scripts/2.5/node_modules/safe-buffer/LICENSE delete mode 100644 scripts/2.5/node_modules/safe-buffer/README.md delete mode 100644 scripts/2.5/node_modules/safe-buffer/index.d.ts delete mode 100644 scripts/2.5/node_modules/safe-buffer/index.js delete mode 100644 scripts/2.5/node_modules/safe-buffer/package.json delete mode 100644 scripts/2.5/node_modules/saslprep/.editorconfig delete mode 100644 scripts/2.5/node_modules/saslprep/.gitattributes delete mode 100644 scripts/2.5/node_modules/saslprep/.travis.yml delete mode 100644 scripts/2.5/node_modules/saslprep/CHANGELOG.md delete mode 100644 scripts/2.5/node_modules/saslprep/LICENSE delete mode 100644 scripts/2.5/node_modules/saslprep/code-points.mem delete mode 100644 scripts/2.5/node_modules/saslprep/generate-code-points.js delete mode 100644 scripts/2.5/node_modules/saslprep/index.js delete mode 100644 scripts/2.5/node_modules/saslprep/lib/code-points.js delete mode 100644 scripts/2.5/node_modules/saslprep/lib/memory-code-points.js delete mode 100644 scripts/2.5/node_modules/saslprep/lib/util.js delete mode 100644 scripts/2.5/node_modules/saslprep/package.json delete mode 100644 scripts/2.5/node_modules/saslprep/readme.md delete mode 100644 scripts/2.5/node_modules/saslprep/test/index.js delete mode 100644 scripts/2.5/node_modules/saslprep/test/util.js delete mode 100644 scripts/2.5/node_modules/semver/CHANGELOG.md delete mode 100644 scripts/2.5/node_modules/semver/LICENSE delete mode 100644 scripts/2.5/node_modules/semver/README.md delete mode 100755 scripts/2.5/node_modules/semver/bin/semver delete mode 100644 scripts/2.5/node_modules/semver/package.json delete mode 100644 scripts/2.5/node_modules/semver/range.bnf delete mode 100644 scripts/2.5/node_modules/semver/semver.js delete mode 100644 scripts/2.5/node_modules/sparse-bitfield/.npmignore delete mode 100644 scripts/2.5/node_modules/sparse-bitfield/.travis.yml delete mode 100644 scripts/2.5/node_modules/sparse-bitfield/LICENSE delete mode 100644 scripts/2.5/node_modules/sparse-bitfield/README.md delete mode 100644 scripts/2.5/node_modules/sparse-bitfield/index.js delete mode 100644 scripts/2.5/node_modules/sparse-bitfield/package.json delete mode 100644 scripts/2.5/node_modules/sparse-bitfield/test.js delete mode 100644 scripts/2.5/node_modules/string.prototype.trimleft/.editorconfig delete mode 100644 scripts/2.5/node_modules/string.prototype.trimleft/.eslintrc delete mode 100644 scripts/2.5/node_modules/string.prototype.trimleft/.travis.yml delete mode 100644 scripts/2.5/node_modules/string.prototype.trimleft/CHANGELOG.md delete mode 100644 scripts/2.5/node_modules/string.prototype.trimleft/LICENSE delete mode 100644 scripts/2.5/node_modules/string.prototype.trimleft/README.md delete mode 100644 scripts/2.5/node_modules/string.prototype.trimleft/auto.js delete mode 100644 scripts/2.5/node_modules/string.prototype.trimleft/implementation.js delete mode 100644 scripts/2.5/node_modules/string.prototype.trimleft/index.js delete mode 100644 scripts/2.5/node_modules/string.prototype.trimleft/package.json delete mode 100644 scripts/2.5/node_modules/string.prototype.trimleft/polyfill.js delete mode 100644 scripts/2.5/node_modules/string.prototype.trimleft/shim.js delete mode 100644 scripts/2.5/node_modules/string.prototype.trimleft/test/index.js delete mode 100644 scripts/2.5/node_modules/string.prototype.trimleft/test/shimmed.js delete mode 100644 scripts/2.5/node_modules/string.prototype.trimleft/test/tests.js delete mode 100644 scripts/2.5/node_modules/string.prototype.trimright/.editorconfig delete mode 100644 scripts/2.5/node_modules/string.prototype.trimright/.eslintrc delete mode 100644 scripts/2.5/node_modules/string.prototype.trimright/.travis.yml delete mode 100644 scripts/2.5/node_modules/string.prototype.trimright/CHANGELOG.md delete mode 100644 scripts/2.5/node_modules/string.prototype.trimright/LICENSE delete mode 100644 scripts/2.5/node_modules/string.prototype.trimright/README.md delete mode 100644 scripts/2.5/node_modules/string.prototype.trimright/auto.js delete mode 100644 scripts/2.5/node_modules/string.prototype.trimright/implementation.js delete mode 100644 scripts/2.5/node_modules/string.prototype.trimright/index.js delete mode 100644 scripts/2.5/node_modules/string.prototype.trimright/package.json delete mode 100644 scripts/2.5/node_modules/string.prototype.trimright/polyfill.js delete mode 100644 scripts/2.5/node_modules/string.prototype.trimright/shim.js delete mode 100644 scripts/2.5/node_modules/string.prototype.trimright/test/index.js delete mode 100644 scripts/2.5/node_modules/string.prototype.trimright/test/shimmed.js delete mode 100644 scripts/2.5/node_modules/string.prototype.trimright/test/tests.js delete mode 100644 scripts/2.5/node_modules/util/CHANGELOG.md delete mode 100644 scripts/2.5/node_modules/util/LICENSE delete mode 100644 scripts/2.5/node_modules/util/README.md delete mode 100644 scripts/2.5/node_modules/util/package.json delete mode 100644 scripts/2.5/node_modules/util/support/isBuffer.js delete mode 100644 scripts/2.5/node_modules/util/support/isBufferBrowser.js delete mode 100644 scripts/2.5/node_modules/util/support/types.js delete mode 100644 scripts/2.5/node_modules/util/util.js diff --git a/scripts/2.5/node_modules/.bin/semver b/scripts/2.5/node_modules/.bin/semver deleted file mode 120000 index 317eb293..00000000 --- a/scripts/2.5/node_modules/.bin/semver +++ /dev/null @@ -1 +0,0 @@ -../semver/bin/semver \ No newline at end of file diff --git a/scripts/2.5/node_modules/assert/CHANGELOG.md b/scripts/2.5/node_modules/assert/CHANGELOG.md deleted file mode 100644 index 807626d6..00000000 --- a/scripts/2.5/node_modules/assert/CHANGELOG.md +++ /dev/null @@ -1,14 +0,0 @@ -# assert change log - -All notable changes to this project will be documented in this file. - -This project adheres to [Semantic Versioning](http://semver.org/). - -## 2.0.0 - -* Sync with Node.js master. ([@lukechilds](https://github.com/lukechilds) in [#44](https://github.com/browserify/commonjs-assert/pull/44)) - -**Note:** Support for IE9 and IE10 has been dropped. IE11 is still supported. - -## 1.5.0 -* Add strict mode APIs. ([@lukechilds](https://github.com/lukechilds) in [#41](https://github.com/browserify/commonjs-assert/pull/41)) diff --git a/scripts/2.5/node_modules/assert/LICENSE b/scripts/2.5/node_modules/assert/LICENSE deleted file mode 100644 index e3d4e695..00000000 --- a/scripts/2.5/node_modules/assert/LICENSE +++ /dev/null @@ -1,18 +0,0 @@ -Copyright Joyent, Inc. and other Node contributors. All rights reserved. -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to -deal in the Software without restriction, including without limitation the -rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -sell copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -IN THE SOFTWARE. diff --git a/scripts/2.5/node_modules/assert/README.md b/scripts/2.5/node_modules/assert/README.md deleted file mode 100644 index e2cc9e15..00000000 --- a/scripts/2.5/node_modules/assert/README.md +++ /dev/null @@ -1,73 +0,0 @@ -# assert - -> The [`assert`](https://nodejs.org/api/assert.html) module from Node.js, for the browser. - -[![Build Status](https://travis-ci.org/browserify/commonjs-assert.svg?branch=master)](https://travis-ci.org/browserify/commonjs-assert) -[![npm](https://img.shields.io/npm/dm/assert.svg)](https://www.npmjs.com/package/assert) -[![npm](https://img.shields.io/npm/v/assert.svg)](https://www.npmjs.com/package/assert) - -With browserify, simply `require('assert')` or use the `assert` global and you will get this module. - -The goal is to provide an API that is as functionally identical to the [Node.js `assert` API](https://nodejs.org/api/assert.html) as possible. Read the [official docs](https://nodejs.org/api/assert.html) for API documentation. - -## Install - -To use this module directly (without browserify), install it as a dependency: - -``` -npm install assert -``` - -## Usage - -The goal is to provide an API that is as functionally identical to the [Node.js `assert` API](https://nodejs.org/api/assert.html) as possible. Read the [official docs](https://nodejs.org/api/assert.html) for API documentation. - -### Inconsistencies with Node.js `assert` - -Due to differences between browsers, some error properties such as `message` and `stack` will be inconsistent. However the assertion behaviour is as close as possible to Node.js and the same error `code` will always be used. - -## Contributing - -To contribute, work on the source files. Then build and run the tests against the built files. Be careful to not introduce syntax that will be transpiled down to unsupported syntax. For example, `for...of` loops will be transpiled to use `Symbol.iterator` which is unavailable in IE. - -### Build scripts - -#### `npm run build` - -Builds the project into the `build` dir. - -#### `npm run dev` - -Watches source files for changes and rebuilds them into the `build` dir. - -#### `npm run test` - -Builds the source files into the `build` dir and then runs the tests against the built project. - -#### `npm run test:nobuild` - -Runs the tests against the built project without rebuilding first. - -This is useful if you're debugging in the transpiled code and want to re-run the tests without overwriting any changes you may have made. - -#### `npm run test:source` - -Runs the tests against the unbuilt source files. - -This will only work on modern Node.js versions. - -#### `npm run test:browsers` - -Run browser tests against the all targets in the cloud. - -Requires airtap credentials to be configured on your machine. - -#### `npm run test:browsers:local` - -Run a local browser test server. No airtap configuration required. - -When paired with `npm run dev` any changes you make to the source files will be automatically transpiled and served on the next request to the test server. - -## License - -MIT © Joyent, Inc. and other Node contributors diff --git a/scripts/2.5/node_modules/assert/package.json b/scripts/2.5/node_modules/assert/package.json deleted file mode 100644 index f6d36c2a..00000000 --- a/scripts/2.5/node_modules/assert/package.json +++ /dev/null @@ -1,77 +0,0 @@ -{ - "_from": "assert", - "_id": "assert@2.0.0", - "_inBundle": false, - "_integrity": "sha512-se5Cd+js9dXJnu6Ag2JFc00t+HmHOen+8Q+L7O9zI0PqQXr20uk2J0XQqMxZEeo5U50o8Nvmmx7dZrl+Ufr35A==", - "_location": "/assert", - "_phantomChildren": {}, - "_requested": { - "type": "tag", - "registry": true, - "raw": "assert", - "name": "assert", - "escapedName": "assert", - "rawSpec": "", - "saveSpec": null, - "fetchSpec": "latest" - }, - "_requiredBy": [ - "#USER", - "/" - ], - "_resolved": "https://registry.npmjs.org/assert/-/assert-2.0.0.tgz", - "_shasum": "95fc1c616d48713510680f2eaf2d10dd22e02d32", - "_spec": "assert", - "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/2.5", - "bugs": { - "url": "https://github.com/browserify/commonjs-assert/issues" - }, - "bundleDependencies": false, - "dependencies": { - "es6-object-assign": "^1.1.0", - "is-nan": "^1.2.1", - "object-is": "^1.0.1", - "util": "^0.12.0" - }, - "deprecated": false, - "description": "The assert module from Node.js, for the browser.", - "devDependencies": { - "@babel/cli": "^7.4.4", - "@babel/core": "^7.4.4", - "@babel/preset-env": "^7.4.4", - "airtap": "^2.0.2", - "array-fill": "^1.2.0", - "core-js": "^3.0.1", - "cross-env": "^5.2.0", - "object.entries": "^1.1.0", - "object.getownpropertydescriptors": "^2.0.3", - "tape": "^4.10.1" - }, - "files": [ - "build/assert.js", - "build/internal" - ], - "homepage": "https://github.com/browserify/commonjs-assert", - "keywords": [ - "assert", - "browser" - ], - "license": "MIT", - "main": "build/assert.js", - "name": "assert", - "repository": { - "type": "git", - "url": "git+https://github.com/browserify/commonjs-assert.git" - }, - "scripts": { - "build": "babel assert.js test.js --out-dir build && babel internal --out-dir build/internal && babel test --out-dir build/test", - "dev": "babel assert.js test.js --watch --out-dir build & babel internal --watch --out-dir build/internal & babel test --watch --out-dir build/test", - "prepare": "npm run build", - "test": "npm run build && npm run test:nobuild", - "test:browsers": "airtap build/test.js", - "test:browsers:local": "npm run test:browsers -- --local", - "test:nobuild": "node build/test.js", - "test:source": "node test.js" - }, - "version": "2.0.0" -} diff --git a/scripts/2.5/node_modules/bson/HISTORY.md b/scripts/2.5/node_modules/bson/HISTORY.md deleted file mode 100644 index 0da8acef..00000000 --- a/scripts/2.5/node_modules/bson/HISTORY.md +++ /dev/null @@ -1,268 +0,0 @@ - -## [1.1.1](https://github.com/mongodb/js-bson/compare/v1.1.0...v1.1.1) (2019-03-08) - - -### Bug Fixes - -* **object-id:** support 4.x->1.x interop for MinKey and ObjectId ([53419a5](https://github.com/mongodb/js-bson/commit/53419a5)) - - -### Features - -* replace new Buffer with modern versions ([24aefba](https://github.com/mongodb/js-bson/commit/24aefba)) - - - - -# [1.1.0](https://github.com/mongodb/js-bson/compare/v1.0.9...v1.1.0) (2018-08-13) - - -### Bug Fixes - -* **serializer:** do not use checkKeys for $clusterTime ([573e141](https://github.com/mongodb/js-bson/commit/573e141)) - - - - -## [1.0.9](https://github.com/mongodb/js-bson/compare/v1.0.8...v1.0.9) (2018-06-07) - - -### Bug Fixes - -* **serializer:** remove use of `const` ([5feb12f](https://github.com/mongodb/js-bson/commit/5feb12f)) - - - - -## [1.0.7](https://github.com/mongodb/js-bson/compare/v1.0.6...v1.0.7) (2018-06-06) - - -### Bug Fixes - -* **binary:** add type checking for buffer ([26b05b5](https://github.com/mongodb/js-bson/commit/26b05b5)) -* **bson:** fix custom inspect property ([080323b](https://github.com/mongodb/js-bson/commit/080323b)) -* **readme:** clarify documentation about deserialize methods ([20f764c](https://github.com/mongodb/js-bson/commit/20f764c)) -* **serialization:** normalize function stringification ([1320c10](https://github.com/mongodb/js-bson/commit/1320c10)) - - - - -## [1.0.6](https://github.com/mongodb/js-bson/compare/v1.0.5...v1.0.6) (2018-03-12) - - -### Features - -* **serialization:** support arbitrary sizes for the internal serialization buffer ([abe97bc](https://github.com/mongodb/js-bson/commit/abe97bc)) - - - - -## 1.0.5 (2018-02-26) - - -### Bug Fixes - -* **decimal128:** add basic guard against REDOS attacks ([bd61c45](https://github.com/mongodb/js-bson/commit/bd61c45)) -* **objectid:** if pid is 1, use random value ([e188ae6](https://github.com/mongodb/js-bson/commit/e188ae6)) - - - -1.0.4 2016-01-11 ----------------- -- #204 remove Buffer.from as it's partially broken in early 4.x.x. series of node releases. - -1.0.3 2016-01-03 ----------------- -- Fixed toString for ObjectId so it will work with inspect. - -1.0.2 2016-01-02 ----------------- -- Minor optimizations for ObjectID to use Buffer.from where available. - -1.0.1 2016-12-06 ----------------- -- Reverse behavior for undefined to be serialized as NULL. MongoDB 3.4 does not allow for undefined comparisons. - -1.0.0 2016-12-06 ----------------- -- Introduced new BSON API and documentation. - -0.5.7 2016-11-18 ------------------ -- NODE-848 BSON Regex flags must be alphabetically ordered. - -0.5.6 2016-10-19 ------------------ -- NODE-833, Detects cyclic dependencies in documents and throws error if one is found. -- Fix(deserializer): corrected the check for (size + index) comparison… (Issue #195, https://github.com/JoelParke). - -0.5.5 2016-09-15 ------------------ -- Added DBPointer up conversion to DBRef - -0.5.4 2016-08-23 ------------------ -- Added promoteValues flag (default to true) allowing user to specify if deserialization should be into wrapper classes only. - -0.5.3 2016-07-11 ------------------ -- Throw error if ObjectId is not a string or a buffer. - -0.5.2 2016-07-11 ------------------ -- All values encoded big-endian style for ObjectId. - -0.5.1 2016-07-11 ------------------ -- Fixed encoding/decoding issue in ObjectId timestamp generation. -- Removed BinaryParser dependency from the serializer/deserializer. - -0.5.0 2016-07-05 ------------------ -- Added Decimal128 type and extended test suite to include entire bson corpus. - -0.4.23 2016-04-08 ------------------ -- Allow for proper detection of ObjectId or objects that look like ObjectId, improving compatibility across third party libraries. -- Remove one package from dependency due to having been pulled from NPM. - -0.4.22 2016-03-04 ------------------ -- Fix "TypeError: data.copy is not a function" in Electron (Issue #170, https://github.com/kangas). -- Fixed issue with undefined type on deserializing. - -0.4.21 2016-01-12 ------------------ -- Minor optimizations to avoid non needed object creation. - -0.4.20 2015-10-15 ------------------ -- Added bower file to repository. -- Fixed browser pid sometimes set greater than 0xFFFF on browsers (Issue #155, https://github.com/rahatarmanahmed) - -0.4.19 2015-10-15 ------------------ -- Remove all support for bson-ext. - -0.4.18 2015-10-15 ------------------ -- ObjectID equality check should return boolean instead of throwing exception for invalid oid string #139 -- add option for deserializing binary into Buffer object #116 - -0.4.17 2015-10-15 ------------------ -- Validate regexp string for null bytes and throw if there is one. - -0.4.16 2015-10-07 ------------------ -- Fixed issue with return statement in Map.js. - -0.4.15 2015-10-06 ------------------ -- Exposed Map correctly via index.js file. - -0.4.14 2015-10-06 ------------------ -- Exposed Map correctly via bson.js file. - -0.4.13 2015-10-06 ------------------ -- Added ES6 Map type serialization as well as a polyfill for ES5. - -0.4.12 2015-09-18 ------------------ -- Made ignore undefined an optional parameter. - -0.4.11 2015-08-06 ------------------ -- Minor fix for invalid key checking. - -0.4.10 2015-08-06 ------------------ -- NODE-38 Added new BSONRegExp type to allow direct serialization to MongoDB type. -- Some performance improvements by in lining code. - -0.4.9 2015-08-06 ----------------- -- Undefined fields are omitted from serialization in objects. - -0.4.8 2015-07-14 ----------------- -- Fixed size validation to ensure we can deserialize from dumped files. - -0.4.7 2015-06-26 ----------------- -- Added ability to instruct deserializer to return raw BSON buffers for named array fields. -- Minor deserialization optimization by moving inlined function out. - -0.4.6 2015-06-17 ----------------- -- Fixed serializeWithBufferAndIndex bug. - -0.4.5 2015-06-17 ----------------- -- Removed any references to the shared buffer to avoid non GC collectible bson instances. - -0.4.4 2015-06-17 ----------------- -- Fixed rethrowing of error when not RangeError. - -0.4.3 2015-06-17 ----------------- -- Start buffer at 64K and double as needed, meaning we keep a low memory profile until needed. - -0.4.2 2015-06-16 ----------------- -- More fixes for corrupt Bson - -0.4.1 2015-06-16 ----------------- -- More fixes for corrupt Bson - -0.4.0 2015-06-16 ----------------- -- New JS serializer serializing into a single buffer then copying out the new buffer. Performance is similar to current C++ parser. -- Removed bson-ext extension dependency for now. - -0.3.2 2015-03-27 ----------------- -- Removed node-gyp from install script in package.json. - -0.3.1 2015-03-27 ----------------- -- Return pure js version on native() call if failed to initialize. - -0.3.0 2015-03-26 ----------------- -- Pulled out all C++ code into bson-ext and made it an optional dependency. - -0.2.21 2015-03-21 ------------------ -- Updated Nan to 1.7.0 to support io.js and node 0.12.0 - -0.2.19 2015-02-16 ------------------ -- Updated Nan to 1.6.2 to support io.js and node 0.12.0 - -0.2.18 2015-01-20 ------------------ -- Updated Nan to 1.5.1 to support io.js - -0.2.16 2014-12-17 ------------------ -- Made pid cycle on 0xffff to avoid weird overflows on creation of ObjectID's - -0.2.12 2014-08-24 ------------------ -- Fixes for fortify review of c++ extension -- toBSON correctly allows returns of non objects - -0.2.3 2013-10-01 ----------------- -- Drying of ObjectId code for generation of id (Issue #54, https://github.com/moredip) -- Fixed issue where corrupt CString's could cause endless loop -- Support for Node 0.11.X > (Issue #49, https://github.com/kkoopa) - -0.1.4 2012-09-25 ----------------- -- Added precompiled c++ native extensions for win32 ia32 and x64 diff --git a/scripts/2.5/node_modules/bson/LICENSE.md b/scripts/2.5/node_modules/bson/LICENSE.md deleted file mode 100644 index 261eeb9e..00000000 --- a/scripts/2.5/node_modules/bson/LICENSE.md +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/scripts/2.5/node_modules/bson/README.md b/scripts/2.5/node_modules/bson/README.md deleted file mode 100644 index 06883410..00000000 --- a/scripts/2.5/node_modules/bson/README.md +++ /dev/null @@ -1,170 +0,0 @@ -# BSON parser - -BSON is short for Bin­ary JSON and is the bin­ary-en­coded seri­al­iz­a­tion of JSON-like doc­u­ments. You can learn more about it in [the specification](http://bsonspec.org). - -This browser version of the BSON parser is compiled using [webpack](https://webpack.js.org/) and the current version is pre-compiled in the `browser_build` directory. - -This is the default BSON parser, however, there is a C++ Node.js addon version as well that does not support the browser. It can be found at [mongod-js/bson-ext](https://github.com/mongodb-js/bson-ext). - -## Usage - -To build a new version perform the following operations: - -``` -npm install -npm run build -``` - -A simple example of how to use BSON in the browser: - -```html - - - -``` - -A simple example of how to use BSON in `Node.js`: - -```js -// Get BSON parser class -var BSON = require('bson') -// Get the Long type -var Long = BSON.Long; -// Create a bson parser instance -var bson = new BSON(); - -// Serialize document -var doc = { long: Long.fromNumber(100) } - -// Serialize a document -var data = bson.serialize(doc) -console.log('data:', data) - -// Deserialize the resulting Buffer -var doc_2 = bson.deserialize(data) -console.log('doc_2:', doc_2) -``` - -## Installation - -`npm install bson` - -## API - -### BSON types - -For all BSON types documentation, please refer to the following sources: - * [MongoDB BSON Type Reference](https://docs.mongodb.com/manual/reference/bson-types/) - * [BSON Spec](https://bsonspec.org/) - -### BSON serialization and deserialiation - -**`new BSON()`** - Creates a new BSON serializer/deserializer you can use to serialize and deserialize BSON. - -#### BSON.serialize - -The BSON `serialize` method takes a JavaScript object and an optional options object and returns a Node.js Buffer. - - * `BSON.serialize(object, options)` - * @param {Object} object the JavaScript object to serialize. - * @param {Boolean} [options.checkKeys=false] the serializer will check if keys are valid. - * @param {Boolean} [options.serializeFunctions=false] serialize the JavaScript functions. - * @param {Boolean} [options.ignoreUndefined=true] - * @return {Buffer} returns a Buffer instance. - -#### BSON.serializeWithBufferAndIndex - -The BSON `serializeWithBufferAndIndex` method takes an object, a target buffer instance and an optional options object and returns the end serialization index in the final buffer. - - * `BSON.serializeWithBufferAndIndex(object, buffer, options)` - * @param {Object} object the JavaScript object to serialize. - * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. - * @param {Boolean} [options.checkKeys=false] the serializer will check if keys are valid. - * @param {Boolean} [options.serializeFunctions=false] serialize the JavaScript functions. - * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields. - * @param {Number} [options.index=0] the index in the buffer where we wish to start serializing into. - * @return {Number} returns the index pointing to the last written byte in the buffer. - -#### BSON.calculateObjectSize - -The BSON `calculateObjectSize` method takes a JavaScript object and an optional options object and returns the size of the BSON object. - - * `BSON.calculateObjectSize(object, options)` - * @param {Object} object the JavaScript object to serialize. - * @param {Boolean} [options.serializeFunctions=false] serialize the JavaScript functions. - * @param {Boolean} [options.ignoreUndefined=true] - * @return {Buffer} returns a Buffer instance. - -#### BSON.deserialize - -The BSON `deserialize` method takes a Node.js Buffer and an optional options object and returns a deserialized JavaScript object. - - * `BSON.deserialize(buffer, options)` - * @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized. - * @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse. - * @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function. - * @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits - * @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a Node.js Buffer instance. - * @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types. - * @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer. - * @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances. - * @return {Object} returns the deserialized Javascript Object. - -#### BSON.deserializeStream - -The BSON `deserializeStream` method takes a Node.js Buffer, `startIndex` and allow more control over deserialization of a Buffer containing concatenated BSON documents. - - * `BSON.deserializeStream(buffer, startIndex, numberOfDocuments, documents, docStartIndex, options)` - * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. - * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. - * @param {Number} numberOfDocuments number of documents to deserialize. - * @param {Array} documents an array where to store the deserialized documents. - * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. - * @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized. - * @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse. - * @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function. - * @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits - * @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a Node.js Buffer instance. - * @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types. - * @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer. - * @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances. - * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. - -## FAQ - -#### Why does `undefined` get converted to `null`? - -The `undefined` BSON type has been [deprecated for many years](http://bsonspec.org/spec.html), so this library has dropped support for it. Use the `ignoreUndefined` option (for example, from the [driver](http://mongodb.github.io/node-mongodb-native/2.2/api/MongoClient.html#connect) ) to instead remove `undefined` keys. - -#### How do I add custom serialization logic? - -This library looks for `toBSON()` functions on every path, and calls the `toBSON()` function to get the value to serialize. - -```javascript -var bson = new BSON(); - -class CustomSerialize { - toBSON() { - return 42; - } -} - -const obj = { answer: new CustomSerialize() }; -// "{ answer: 42 }" -console.log(bson.deserialize(bson.serialize(obj))); -``` diff --git a/scripts/2.5/node_modules/bson/bower.json b/scripts/2.5/node_modules/bson/bower.json deleted file mode 100644 index b32140ea..00000000 --- a/scripts/2.5/node_modules/bson/bower.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "name": "bson", - "description": "A bson parser for node.js and the browser", - "keywords": [ - "mongodb", - "bson", - "parser" - ], - "author": "Christian Amor Kvalheim ", - "main": "./browser_build/bson.js", - "license": "Apache-2.0", - "moduleType": [ - "globals", - "node" - ], - "ignore": [ - "**/.*", - "alternate_parsers", - "benchmarks", - "bower_components", - "node_modules", - "test", - "tools" - ] -} diff --git a/scripts/2.5/node_modules/bson/browser_build/bson.js b/scripts/2.5/node_modules/bson/browser_build/bson.js deleted file mode 100644 index e601c992..00000000 --- a/scripts/2.5/node_modules/bson/browser_build/bson.js +++ /dev/null @@ -1,17769 +0,0 @@ -(function webpackUniversalModuleDefinition(root, factory) { - if(typeof exports === 'object' && typeof module === 'object') - module.exports = factory(); - else if(typeof define === 'function' && define.amd) - define([], factory); - else { - var a = factory(); - for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i]; - } -})(this, function() { -return /******/ (function(modules) { // webpackBootstrap -/******/ // The module cache -/******/ var installedModules = {}; - -/******/ // The require function -/******/ function __webpack_require__(moduleId) { - -/******/ // Check if module is in cache -/******/ if(installedModules[moduleId]) -/******/ return installedModules[moduleId].exports; - -/******/ // Create a new module (and put it into the cache) -/******/ var module = installedModules[moduleId] = { -/******/ exports: {}, -/******/ id: moduleId, -/******/ loaded: false -/******/ }; - -/******/ // Execute the module function -/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); - -/******/ // Flag the module as loaded -/******/ module.loaded = true; - -/******/ // Return the exports of the module -/******/ return module.exports; -/******/ } - - -/******/ // expose the modules object (__webpack_modules__) -/******/ __webpack_require__.m = modules; - -/******/ // expose the module cache -/******/ __webpack_require__.c = installedModules; - -/******/ // __webpack_public_path__ -/******/ __webpack_require__.p = "/"; - -/******/ // Load entry module and return exports -/******/ return __webpack_require__(0); -/******/ }) -/************************************************************************/ -/******/ ([ -/* 0 */ -/***/ (function(module, exports, __webpack_require__) { - - __webpack_require__(1); - module.exports = __webpack_require__(327); - - -/***/ }), -/* 1 */ -/***/ (function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(global) {"use strict"; - - __webpack_require__(2); - - __webpack_require__(323); - - __webpack_require__(324); - - if (global._babelPolyfill) { - throw new Error("only one instance of babel-polyfill is allowed"); - } - global._babelPolyfill = true; - - var DEFINE_PROPERTY = "defineProperty"; - function define(O, key, value) { - O[key] || Object[DEFINE_PROPERTY](O, key, { - writable: true, - configurable: true, - value: value - }); - } - - define(String.prototype, "padLeft", "".padStart); - define(String.prototype, "padRight", "".padEnd); - - "pop,reverse,shift,keys,values,entries,indexOf,every,some,forEach,map,filter,find,findIndex,includes,join,slice,concat,push,splice,unshift,sort,lastIndexOf,reduce,reduceRight,copyWithin,fill".split(",").forEach(function (key) { - [][key] && define(Array, key, Function.call.bind([][key])); - }); - /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) - -/***/ }), -/* 2 */ -/***/ (function(module, exports, __webpack_require__) { - - __webpack_require__(3); - __webpack_require__(51); - __webpack_require__(52); - __webpack_require__(53); - __webpack_require__(54); - __webpack_require__(56); - __webpack_require__(59); - __webpack_require__(60); - __webpack_require__(61); - __webpack_require__(62); - __webpack_require__(63); - __webpack_require__(64); - __webpack_require__(65); - __webpack_require__(66); - __webpack_require__(67); - __webpack_require__(69); - __webpack_require__(71); - __webpack_require__(73); - __webpack_require__(75); - __webpack_require__(78); - __webpack_require__(79); - __webpack_require__(80); - __webpack_require__(84); - __webpack_require__(86); - __webpack_require__(88); - __webpack_require__(91); - __webpack_require__(92); - __webpack_require__(93); - __webpack_require__(94); - __webpack_require__(96); - __webpack_require__(97); - __webpack_require__(98); - __webpack_require__(99); - __webpack_require__(100); - __webpack_require__(101); - __webpack_require__(102); - __webpack_require__(104); - __webpack_require__(105); - __webpack_require__(106); - __webpack_require__(108); - __webpack_require__(109); - __webpack_require__(110); - __webpack_require__(112); - __webpack_require__(114); - __webpack_require__(115); - __webpack_require__(116); - __webpack_require__(117); - __webpack_require__(118); - __webpack_require__(119); - __webpack_require__(120); - __webpack_require__(121); - __webpack_require__(122); - __webpack_require__(123); - __webpack_require__(124); - __webpack_require__(125); - __webpack_require__(126); - __webpack_require__(131); - __webpack_require__(132); - __webpack_require__(136); - __webpack_require__(137); - __webpack_require__(138); - __webpack_require__(139); - __webpack_require__(141); - __webpack_require__(142); - __webpack_require__(143); - __webpack_require__(144); - __webpack_require__(145); - __webpack_require__(146); - __webpack_require__(147); - __webpack_require__(148); - __webpack_require__(149); - __webpack_require__(150); - __webpack_require__(151); - __webpack_require__(152); - __webpack_require__(153); - __webpack_require__(154); - __webpack_require__(155); - __webpack_require__(157); - __webpack_require__(158); - __webpack_require__(160); - __webpack_require__(161); - __webpack_require__(167); - __webpack_require__(168); - __webpack_require__(170); - __webpack_require__(171); - __webpack_require__(172); - __webpack_require__(176); - __webpack_require__(177); - __webpack_require__(178); - __webpack_require__(179); - __webpack_require__(180); - __webpack_require__(182); - __webpack_require__(183); - __webpack_require__(184); - __webpack_require__(185); - __webpack_require__(188); - __webpack_require__(190); - __webpack_require__(191); - __webpack_require__(192); - __webpack_require__(194); - __webpack_require__(196); - __webpack_require__(198); - __webpack_require__(199); - __webpack_require__(200); - __webpack_require__(202); - __webpack_require__(203); - __webpack_require__(204); - __webpack_require__(205); - __webpack_require__(216); - __webpack_require__(220); - __webpack_require__(221); - __webpack_require__(223); - __webpack_require__(224); - __webpack_require__(228); - __webpack_require__(229); - __webpack_require__(231); - __webpack_require__(232); - __webpack_require__(233); - __webpack_require__(234); - __webpack_require__(235); - __webpack_require__(236); - __webpack_require__(237); - __webpack_require__(238); - __webpack_require__(239); - __webpack_require__(240); - __webpack_require__(241); - __webpack_require__(242); - __webpack_require__(243); - __webpack_require__(244); - __webpack_require__(245); - __webpack_require__(246); - __webpack_require__(247); - __webpack_require__(248); - __webpack_require__(249); - __webpack_require__(251); - __webpack_require__(252); - __webpack_require__(253); - __webpack_require__(254); - __webpack_require__(255); - __webpack_require__(257); - __webpack_require__(258); - __webpack_require__(259); - __webpack_require__(261); - __webpack_require__(262); - __webpack_require__(263); - __webpack_require__(264); - __webpack_require__(265); - __webpack_require__(266); - __webpack_require__(267); - __webpack_require__(268); - __webpack_require__(270); - __webpack_require__(271); - __webpack_require__(273); - __webpack_require__(274); - __webpack_require__(275); - __webpack_require__(276); - __webpack_require__(279); - __webpack_require__(280); - __webpack_require__(282); - __webpack_require__(283); - __webpack_require__(284); - __webpack_require__(285); - __webpack_require__(287); - __webpack_require__(288); - __webpack_require__(289); - __webpack_require__(290); - __webpack_require__(291); - __webpack_require__(292); - __webpack_require__(293); - __webpack_require__(294); - __webpack_require__(295); - __webpack_require__(296); - __webpack_require__(298); - __webpack_require__(299); - __webpack_require__(300); - __webpack_require__(301); - __webpack_require__(302); - __webpack_require__(303); - __webpack_require__(304); - __webpack_require__(305); - __webpack_require__(306); - __webpack_require__(307); - __webpack_require__(308); - __webpack_require__(310); - __webpack_require__(311); - __webpack_require__(312); - __webpack_require__(313); - __webpack_require__(314); - __webpack_require__(315); - __webpack_require__(316); - __webpack_require__(317); - __webpack_require__(318); - __webpack_require__(319); - __webpack_require__(320); - __webpack_require__(321); - __webpack_require__(322); - module.exports = __webpack_require__(9); - - -/***/ }), -/* 3 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // ECMAScript 6 symbols shim - var global = __webpack_require__(4); - var has = __webpack_require__(5); - var DESCRIPTORS = __webpack_require__(6); - var $export = __webpack_require__(8); - var redefine = __webpack_require__(18); - var META = __webpack_require__(22).KEY; - var $fails = __webpack_require__(7); - var shared = __webpack_require__(23); - var setToStringTag = __webpack_require__(25); - var uid = __webpack_require__(19); - var wks = __webpack_require__(26); - var wksExt = __webpack_require__(27); - var wksDefine = __webpack_require__(28); - var enumKeys = __webpack_require__(29); - var isArray = __webpack_require__(44); - var anObject = __webpack_require__(12); - var isObject = __webpack_require__(13); - var toIObject = __webpack_require__(32); - var toPrimitive = __webpack_require__(16); - var createDesc = __webpack_require__(17); - var _create = __webpack_require__(45); - var gOPNExt = __webpack_require__(48); - var $GOPD = __webpack_require__(50); - var $DP = __webpack_require__(11); - var $keys = __webpack_require__(30); - var gOPD = $GOPD.f; - var dP = $DP.f; - var gOPN = gOPNExt.f; - var $Symbol = global.Symbol; - var $JSON = global.JSON; - var _stringify = $JSON && $JSON.stringify; - var PROTOTYPE = 'prototype'; - var HIDDEN = wks('_hidden'); - var TO_PRIMITIVE = wks('toPrimitive'); - var isEnum = {}.propertyIsEnumerable; - var SymbolRegistry = shared('symbol-registry'); - var AllSymbols = shared('symbols'); - var OPSymbols = shared('op-symbols'); - var ObjectProto = Object[PROTOTYPE]; - var USE_NATIVE = typeof $Symbol == 'function'; - var QObject = global.QObject; - // Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173 - var setter = !QObject || !QObject[PROTOTYPE] || !QObject[PROTOTYPE].findChild; - - // fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687 - var setSymbolDesc = DESCRIPTORS && $fails(function () { - return _create(dP({}, 'a', { - get: function () { return dP(this, 'a', { value: 7 }).a; } - })).a != 7; - }) ? function (it, key, D) { - var protoDesc = gOPD(ObjectProto, key); - if (protoDesc) delete ObjectProto[key]; - dP(it, key, D); - if (protoDesc && it !== ObjectProto) dP(ObjectProto, key, protoDesc); - } : dP; - - var wrap = function (tag) { - var sym = AllSymbols[tag] = _create($Symbol[PROTOTYPE]); - sym._k = tag; - return sym; - }; - - var isSymbol = USE_NATIVE && typeof $Symbol.iterator == 'symbol' ? function (it) { - return typeof it == 'symbol'; - } : function (it) { - return it instanceof $Symbol; - }; - - var $defineProperty = function defineProperty(it, key, D) { - if (it === ObjectProto) $defineProperty(OPSymbols, key, D); - anObject(it); - key = toPrimitive(key, true); - anObject(D); - if (has(AllSymbols, key)) { - if (!D.enumerable) { - if (!has(it, HIDDEN)) dP(it, HIDDEN, createDesc(1, {})); - it[HIDDEN][key] = true; - } else { - if (has(it, HIDDEN) && it[HIDDEN][key]) it[HIDDEN][key] = false; - D = _create(D, { enumerable: createDesc(0, false) }); - } return setSymbolDesc(it, key, D); - } return dP(it, key, D); - }; - var $defineProperties = function defineProperties(it, P) { - anObject(it); - var keys = enumKeys(P = toIObject(P)); - var i = 0; - var l = keys.length; - var key; - while (l > i) $defineProperty(it, key = keys[i++], P[key]); - return it; - }; - var $create = function create(it, P) { - return P === undefined ? _create(it) : $defineProperties(_create(it), P); - }; - var $propertyIsEnumerable = function propertyIsEnumerable(key) { - var E = isEnum.call(this, key = toPrimitive(key, true)); - if (this === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key)) return false; - return E || !has(this, key) || !has(AllSymbols, key) || has(this, HIDDEN) && this[HIDDEN][key] ? E : true; - }; - var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(it, key) { - it = toIObject(it); - key = toPrimitive(key, true); - if (it === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key)) return; - var D = gOPD(it, key); - if (D && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key])) D.enumerable = true; - return D; - }; - var $getOwnPropertyNames = function getOwnPropertyNames(it) { - var names = gOPN(toIObject(it)); - var result = []; - var i = 0; - var key; - while (names.length > i) { - if (!has(AllSymbols, key = names[i++]) && key != HIDDEN && key != META) result.push(key); - } return result; - }; - var $getOwnPropertySymbols = function getOwnPropertySymbols(it) { - var IS_OP = it === ObjectProto; - var names = gOPN(IS_OP ? OPSymbols : toIObject(it)); - var result = []; - var i = 0; - var key; - while (names.length > i) { - if (has(AllSymbols, key = names[i++]) && (IS_OP ? has(ObjectProto, key) : true)) result.push(AllSymbols[key]); - } return result; - }; - - // 19.4.1.1 Symbol([description]) - if (!USE_NATIVE) { - $Symbol = function Symbol() { - if (this instanceof $Symbol) throw TypeError('Symbol is not a constructor!'); - var tag = uid(arguments.length > 0 ? arguments[0] : undefined); - var $set = function (value) { - if (this === ObjectProto) $set.call(OPSymbols, value); - if (has(this, HIDDEN) && has(this[HIDDEN], tag)) this[HIDDEN][tag] = false; - setSymbolDesc(this, tag, createDesc(1, value)); - }; - if (DESCRIPTORS && setter) setSymbolDesc(ObjectProto, tag, { configurable: true, set: $set }); - return wrap(tag); - }; - redefine($Symbol[PROTOTYPE], 'toString', function toString() { - return this._k; - }); - - $GOPD.f = $getOwnPropertyDescriptor; - $DP.f = $defineProperty; - __webpack_require__(49).f = gOPNExt.f = $getOwnPropertyNames; - __webpack_require__(43).f = $propertyIsEnumerable; - __webpack_require__(42).f = $getOwnPropertySymbols; - - if (DESCRIPTORS && !__webpack_require__(24)) { - redefine(ObjectProto, 'propertyIsEnumerable', $propertyIsEnumerable, true); - } - - wksExt.f = function (name) { - return wrap(wks(name)); - }; - } - - $export($export.G + $export.W + $export.F * !USE_NATIVE, { Symbol: $Symbol }); - - for (var es6Symbols = ( - // 19.4.2.2, 19.4.2.3, 19.4.2.4, 19.4.2.6, 19.4.2.8, 19.4.2.9, 19.4.2.10, 19.4.2.11, 19.4.2.12, 19.4.2.13, 19.4.2.14 - 'hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables' - ).split(','), j = 0; es6Symbols.length > j;)wks(es6Symbols[j++]); - - for (var wellKnownSymbols = $keys(wks.store), k = 0; wellKnownSymbols.length > k;) wksDefine(wellKnownSymbols[k++]); - - $export($export.S + $export.F * !USE_NATIVE, 'Symbol', { - // 19.4.2.1 Symbol.for(key) - 'for': function (key) { - return has(SymbolRegistry, key += '') - ? SymbolRegistry[key] - : SymbolRegistry[key] = $Symbol(key); - }, - // 19.4.2.5 Symbol.keyFor(sym) - keyFor: function keyFor(sym) { - if (!isSymbol(sym)) throw TypeError(sym + ' is not a symbol!'); - for (var key in SymbolRegistry) if (SymbolRegistry[key] === sym) return key; - }, - useSetter: function () { setter = true; }, - useSimple: function () { setter = false; } - }); - - $export($export.S + $export.F * !USE_NATIVE, 'Object', { - // 19.1.2.2 Object.create(O [, Properties]) - create: $create, - // 19.1.2.4 Object.defineProperty(O, P, Attributes) - defineProperty: $defineProperty, - // 19.1.2.3 Object.defineProperties(O, Properties) - defineProperties: $defineProperties, - // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P) - getOwnPropertyDescriptor: $getOwnPropertyDescriptor, - // 19.1.2.7 Object.getOwnPropertyNames(O) - getOwnPropertyNames: $getOwnPropertyNames, - // 19.1.2.8 Object.getOwnPropertySymbols(O) - getOwnPropertySymbols: $getOwnPropertySymbols - }); - - // 24.3.2 JSON.stringify(value [, replacer [, space]]) - $JSON && $export($export.S + $export.F * (!USE_NATIVE || $fails(function () { - var S = $Symbol(); - // MS Edge converts symbol values to JSON as {} - // WebKit converts symbol values to JSON as null - // V8 throws on boxed symbols - return _stringify([S]) != '[null]' || _stringify({ a: S }) != '{}' || _stringify(Object(S)) != '{}'; - })), 'JSON', { - stringify: function stringify(it) { - var args = [it]; - var i = 1; - var replacer, $replacer; - while (arguments.length > i) args.push(arguments[i++]); - $replacer = replacer = args[1]; - if (!isObject(replacer) && it === undefined || isSymbol(it)) return; // IE8 returns string on undefined - if (!isArray(replacer)) replacer = function (key, value) { - if (typeof $replacer == 'function') value = $replacer.call(this, key, value); - if (!isSymbol(value)) return value; - }; - args[1] = replacer; - return _stringify.apply($JSON, args); - } - }); - - // 19.4.3.4 Symbol.prototype[@@toPrimitive](hint) - $Symbol[PROTOTYPE][TO_PRIMITIVE] || __webpack_require__(10)($Symbol[PROTOTYPE], TO_PRIMITIVE, $Symbol[PROTOTYPE].valueOf); - // 19.4.3.5 Symbol.prototype[@@toStringTag] - setToStringTag($Symbol, 'Symbol'); - // 20.2.1.9 Math[@@toStringTag] - setToStringTag(Math, 'Math', true); - // 24.3.3 JSON[@@toStringTag] - setToStringTag(global.JSON, 'JSON', true); - - -/***/ }), -/* 4 */ -/***/ (function(module, exports) { - - // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 - var global = module.exports = typeof window != 'undefined' && window.Math == Math - ? window : typeof self != 'undefined' && self.Math == Math ? self - // eslint-disable-next-line no-new-func - : Function('return this')(); - if (typeof __g == 'number') __g = global; // eslint-disable-line no-undef - - -/***/ }), -/* 5 */ -/***/ (function(module, exports) { - - var hasOwnProperty = {}.hasOwnProperty; - module.exports = function (it, key) { - return hasOwnProperty.call(it, key); - }; - - -/***/ }), -/* 6 */ -/***/ (function(module, exports, __webpack_require__) { - - // Thank's IE8 for his funny defineProperty - module.exports = !__webpack_require__(7)(function () { - return Object.defineProperty({}, 'a', { get: function () { return 7; } }).a != 7; - }); - - -/***/ }), -/* 7 */ -/***/ (function(module, exports) { - - module.exports = function (exec) { - try { - return !!exec(); - } catch (e) { - return true; - } - }; - - -/***/ }), -/* 8 */ -/***/ (function(module, exports, __webpack_require__) { - - var global = __webpack_require__(4); - var core = __webpack_require__(9); - var hide = __webpack_require__(10); - var redefine = __webpack_require__(18); - var ctx = __webpack_require__(20); - var PROTOTYPE = 'prototype'; - - var $export = function (type, name, source) { - var IS_FORCED = type & $export.F; - var IS_GLOBAL = type & $export.G; - var IS_STATIC = type & $export.S; - var IS_PROTO = type & $export.P; - var IS_BIND = type & $export.B; - var target = IS_GLOBAL ? global : IS_STATIC ? global[name] || (global[name] = {}) : (global[name] || {})[PROTOTYPE]; - var exports = IS_GLOBAL ? core : core[name] || (core[name] = {}); - var expProto = exports[PROTOTYPE] || (exports[PROTOTYPE] = {}); - var key, own, out, exp; - if (IS_GLOBAL) source = name; - for (key in source) { - // contains in native - own = !IS_FORCED && target && target[key] !== undefined; - // export native or passed - out = (own ? target : source)[key]; - // bind timers to global for call from export context - exp = IS_BIND && own ? ctx(out, global) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out; - // extend global - if (target) redefine(target, key, out, type & $export.U); - // export - if (exports[key] != out) hide(exports, key, exp); - if (IS_PROTO && expProto[key] != out) expProto[key] = out; - } - }; - global.core = core; - // type bitmap - $export.F = 1; // forced - $export.G = 2; // global - $export.S = 4; // static - $export.P = 8; // proto - $export.B = 16; // bind - $export.W = 32; // wrap - $export.U = 64; // safe - $export.R = 128; // real proto method for `library` - module.exports = $export; - - -/***/ }), -/* 9 */ -/***/ (function(module, exports) { - - var core = module.exports = { version: '2.5.7' }; - if (typeof __e == 'number') __e = core; // eslint-disable-line no-undef - - -/***/ }), -/* 10 */ -/***/ (function(module, exports, __webpack_require__) { - - var dP = __webpack_require__(11); - var createDesc = __webpack_require__(17); - module.exports = __webpack_require__(6) ? function (object, key, value) { - return dP.f(object, key, createDesc(1, value)); - } : function (object, key, value) { - object[key] = value; - return object; - }; - - -/***/ }), -/* 11 */ -/***/ (function(module, exports, __webpack_require__) { - - var anObject = __webpack_require__(12); - var IE8_DOM_DEFINE = __webpack_require__(14); - var toPrimitive = __webpack_require__(16); - var dP = Object.defineProperty; - - exports.f = __webpack_require__(6) ? Object.defineProperty : function defineProperty(O, P, Attributes) { - anObject(O); - P = toPrimitive(P, true); - anObject(Attributes); - if (IE8_DOM_DEFINE) try { - return dP(O, P, Attributes); - } catch (e) { /* empty */ } - if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported!'); - if ('value' in Attributes) O[P] = Attributes.value; - return O; - }; - - -/***/ }), -/* 12 */ -/***/ (function(module, exports, __webpack_require__) { - - var isObject = __webpack_require__(13); - module.exports = function (it) { - if (!isObject(it)) throw TypeError(it + ' is not an object!'); - return it; - }; - - -/***/ }), -/* 13 */ -/***/ (function(module, exports) { - - module.exports = function (it) { - return typeof it === 'object' ? it !== null : typeof it === 'function'; - }; - - -/***/ }), -/* 14 */ -/***/ (function(module, exports, __webpack_require__) { - - module.exports = !__webpack_require__(6) && !__webpack_require__(7)(function () { - return Object.defineProperty(__webpack_require__(15)('div'), 'a', { get: function () { return 7; } }).a != 7; - }); - - -/***/ }), -/* 15 */ -/***/ (function(module, exports, __webpack_require__) { - - var isObject = __webpack_require__(13); - var document = __webpack_require__(4).document; - // typeof document.createElement is 'object' in old IE - var is = isObject(document) && isObject(document.createElement); - module.exports = function (it) { - return is ? document.createElement(it) : {}; - }; - - -/***/ }), -/* 16 */ -/***/ (function(module, exports, __webpack_require__) { - - // 7.1.1 ToPrimitive(input [, PreferredType]) - var isObject = __webpack_require__(13); - // instead of the ES6 spec version, we didn't implement @@toPrimitive case - // and the second argument - flag - preferred type is a string - module.exports = function (it, S) { - if (!isObject(it)) return it; - var fn, val; - if (S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val; - if (typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it))) return val; - if (!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val; - throw TypeError("Can't convert object to primitive value"); - }; - - -/***/ }), -/* 17 */ -/***/ (function(module, exports) { - - module.exports = function (bitmap, value) { - return { - enumerable: !(bitmap & 1), - configurable: !(bitmap & 2), - writable: !(bitmap & 4), - value: value - }; - }; - - -/***/ }), -/* 18 */ -/***/ (function(module, exports, __webpack_require__) { - - var global = __webpack_require__(4); - var hide = __webpack_require__(10); - var has = __webpack_require__(5); - var SRC = __webpack_require__(19)('src'); - var TO_STRING = 'toString'; - var $toString = Function[TO_STRING]; - var TPL = ('' + $toString).split(TO_STRING); - - __webpack_require__(9).inspectSource = function (it) { - return $toString.call(it); - }; - - (module.exports = function (O, key, val, safe) { - var isFunction = typeof val == 'function'; - if (isFunction) has(val, 'name') || hide(val, 'name', key); - if (O[key] === val) return; - if (isFunction) has(val, SRC) || hide(val, SRC, O[key] ? '' + O[key] : TPL.join(String(key))); - if (O === global) { - O[key] = val; - } else if (!safe) { - delete O[key]; - hide(O, key, val); - } else if (O[key]) { - O[key] = val; - } else { - hide(O, key, val); - } - // add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative - })(Function.prototype, TO_STRING, function toString() { - return typeof this == 'function' && this[SRC] || $toString.call(this); - }); - - -/***/ }), -/* 19 */ -/***/ (function(module, exports) { - - var id = 0; - var px = Math.random(); - module.exports = function (key) { - return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36)); - }; - - -/***/ }), -/* 20 */ -/***/ (function(module, exports, __webpack_require__) { - - // optional / simple context binding - var aFunction = __webpack_require__(21); - module.exports = function (fn, that, length) { - aFunction(fn); - if (that === undefined) return fn; - switch (length) { - case 1: return function (a) { - return fn.call(that, a); - }; - case 2: return function (a, b) { - return fn.call(that, a, b); - }; - case 3: return function (a, b, c) { - return fn.call(that, a, b, c); - }; - } - return function (/* ...args */) { - return fn.apply(that, arguments); - }; - }; - - -/***/ }), -/* 21 */ -/***/ (function(module, exports) { - - module.exports = function (it) { - if (typeof it != 'function') throw TypeError(it + ' is not a function!'); - return it; - }; - - -/***/ }), -/* 22 */ -/***/ (function(module, exports, __webpack_require__) { - - var META = __webpack_require__(19)('meta'); - var isObject = __webpack_require__(13); - var has = __webpack_require__(5); - var setDesc = __webpack_require__(11).f; - var id = 0; - var isExtensible = Object.isExtensible || function () { - return true; - }; - var FREEZE = !__webpack_require__(7)(function () { - return isExtensible(Object.preventExtensions({})); - }); - var setMeta = function (it) { - setDesc(it, META, { value: { - i: 'O' + ++id, // object ID - w: {} // weak collections IDs - } }); - }; - var fastKey = function (it, create) { - // return primitive with prefix - if (!isObject(it)) return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it; - if (!has(it, META)) { - // can't set metadata to uncaught frozen object - if (!isExtensible(it)) return 'F'; - // not necessary to add metadata - if (!create) return 'E'; - // add missing metadata - setMeta(it); - // return object ID - } return it[META].i; - }; - var getWeak = function (it, create) { - if (!has(it, META)) { - // can't set metadata to uncaught frozen object - if (!isExtensible(it)) return true; - // not necessary to add metadata - if (!create) return false; - // add missing metadata - setMeta(it); - // return hash weak collections IDs - } return it[META].w; - }; - // add metadata on freeze-family methods calling - var onFreeze = function (it) { - if (FREEZE && meta.NEED && isExtensible(it) && !has(it, META)) setMeta(it); - return it; - }; - var meta = module.exports = { - KEY: META, - NEED: false, - fastKey: fastKey, - getWeak: getWeak, - onFreeze: onFreeze - }; - - -/***/ }), -/* 23 */ -/***/ (function(module, exports, __webpack_require__) { - - var core = __webpack_require__(9); - var global = __webpack_require__(4); - var SHARED = '__core-js_shared__'; - var store = global[SHARED] || (global[SHARED] = {}); - - (module.exports = function (key, value) { - return store[key] || (store[key] = value !== undefined ? value : {}); - })('versions', []).push({ - version: core.version, - mode: __webpack_require__(24) ? 'pure' : 'global', - copyright: '© 2018 Denis Pushkarev (zloirock.ru)' - }); - - -/***/ }), -/* 24 */ -/***/ (function(module, exports) { - - module.exports = false; - - -/***/ }), -/* 25 */ -/***/ (function(module, exports, __webpack_require__) { - - var def = __webpack_require__(11).f; - var has = __webpack_require__(5); - var TAG = __webpack_require__(26)('toStringTag'); - - module.exports = function (it, tag, stat) { - if (it && !has(it = stat ? it : it.prototype, TAG)) def(it, TAG, { configurable: true, value: tag }); - }; - - -/***/ }), -/* 26 */ -/***/ (function(module, exports, __webpack_require__) { - - var store = __webpack_require__(23)('wks'); - var uid = __webpack_require__(19); - var Symbol = __webpack_require__(4).Symbol; - var USE_SYMBOL = typeof Symbol == 'function'; - - var $exports = module.exports = function (name) { - return store[name] || (store[name] = - USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)('Symbol.' + name)); - }; - - $exports.store = store; - - -/***/ }), -/* 27 */ -/***/ (function(module, exports, __webpack_require__) { - - exports.f = __webpack_require__(26); - - -/***/ }), -/* 28 */ -/***/ (function(module, exports, __webpack_require__) { - - var global = __webpack_require__(4); - var core = __webpack_require__(9); - var LIBRARY = __webpack_require__(24); - var wksExt = __webpack_require__(27); - var defineProperty = __webpack_require__(11).f; - module.exports = function (name) { - var $Symbol = core.Symbol || (core.Symbol = LIBRARY ? {} : global.Symbol || {}); - if (name.charAt(0) != '_' && !(name in $Symbol)) defineProperty($Symbol, name, { value: wksExt.f(name) }); - }; - - -/***/ }), -/* 29 */ -/***/ (function(module, exports, __webpack_require__) { - - // all enumerable object keys, includes symbols - var getKeys = __webpack_require__(30); - var gOPS = __webpack_require__(42); - var pIE = __webpack_require__(43); - module.exports = function (it) { - var result = getKeys(it); - var getSymbols = gOPS.f; - if (getSymbols) { - var symbols = getSymbols(it); - var isEnum = pIE.f; - var i = 0; - var key; - while (symbols.length > i) if (isEnum.call(it, key = symbols[i++])) result.push(key); - } return result; - }; - - -/***/ }), -/* 30 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.2.14 / 15.2.3.14 Object.keys(O) - var $keys = __webpack_require__(31); - var enumBugKeys = __webpack_require__(41); - - module.exports = Object.keys || function keys(O) { - return $keys(O, enumBugKeys); - }; - - -/***/ }), -/* 31 */ -/***/ (function(module, exports, __webpack_require__) { - - var has = __webpack_require__(5); - var toIObject = __webpack_require__(32); - var arrayIndexOf = __webpack_require__(36)(false); - var IE_PROTO = __webpack_require__(40)('IE_PROTO'); - - module.exports = function (object, names) { - var O = toIObject(object); - var i = 0; - var result = []; - var key; - for (key in O) if (key != IE_PROTO) has(O, key) && result.push(key); - // Don't enum bug & hidden keys - while (names.length > i) if (has(O, key = names[i++])) { - ~arrayIndexOf(result, key) || result.push(key); - } - return result; - }; - - -/***/ }), -/* 32 */ -/***/ (function(module, exports, __webpack_require__) { - - // to indexed object, toObject with fallback for non-array-like ES3 strings - var IObject = __webpack_require__(33); - var defined = __webpack_require__(35); - module.exports = function (it) { - return IObject(defined(it)); - }; - - -/***/ }), -/* 33 */ -/***/ (function(module, exports, __webpack_require__) { - - // fallback for non-array-like ES3 and non-enumerable old V8 strings - var cof = __webpack_require__(34); - // eslint-disable-next-line no-prototype-builtins - module.exports = Object('z').propertyIsEnumerable(0) ? Object : function (it) { - return cof(it) == 'String' ? it.split('') : Object(it); - }; - - -/***/ }), -/* 34 */ -/***/ (function(module, exports) { - - var toString = {}.toString; - - module.exports = function (it) { - return toString.call(it).slice(8, -1); - }; - - -/***/ }), -/* 35 */ -/***/ (function(module, exports) { - - // 7.2.1 RequireObjectCoercible(argument) - module.exports = function (it) { - if (it == undefined) throw TypeError("Can't call method on " + it); - return it; - }; - - -/***/ }), -/* 36 */ -/***/ (function(module, exports, __webpack_require__) { - - // false -> Array#indexOf - // true -> Array#includes - var toIObject = __webpack_require__(32); - var toLength = __webpack_require__(37); - var toAbsoluteIndex = __webpack_require__(39); - module.exports = function (IS_INCLUDES) { - return function ($this, el, fromIndex) { - var O = toIObject($this); - var length = toLength(O.length); - var index = toAbsoluteIndex(fromIndex, length); - var value; - // Array#includes uses SameValueZero equality algorithm - // eslint-disable-next-line no-self-compare - if (IS_INCLUDES && el != el) while (length > index) { - value = O[index++]; - // eslint-disable-next-line no-self-compare - if (value != value) return true; - // Array#indexOf ignores holes, Array#includes - not - } else for (;length > index; index++) if (IS_INCLUDES || index in O) { - if (O[index] === el) return IS_INCLUDES || index || 0; - } return !IS_INCLUDES && -1; - }; - }; - - -/***/ }), -/* 37 */ -/***/ (function(module, exports, __webpack_require__) { - - // 7.1.15 ToLength - var toInteger = __webpack_require__(38); - var min = Math.min; - module.exports = function (it) { - return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991 - }; - - -/***/ }), -/* 38 */ -/***/ (function(module, exports) { - - // 7.1.4 ToInteger - var ceil = Math.ceil; - var floor = Math.floor; - module.exports = function (it) { - return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it); - }; - - -/***/ }), -/* 39 */ -/***/ (function(module, exports, __webpack_require__) { - - var toInteger = __webpack_require__(38); - var max = Math.max; - var min = Math.min; - module.exports = function (index, length) { - index = toInteger(index); - return index < 0 ? max(index + length, 0) : min(index, length); - }; - - -/***/ }), -/* 40 */ -/***/ (function(module, exports, __webpack_require__) { - - var shared = __webpack_require__(23)('keys'); - var uid = __webpack_require__(19); - module.exports = function (key) { - return shared[key] || (shared[key] = uid(key)); - }; - - -/***/ }), -/* 41 */ -/***/ (function(module, exports) { - - // IE 8- don't enum bug keys - module.exports = ( - 'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf' - ).split(','); - - -/***/ }), -/* 42 */ -/***/ (function(module, exports) { - - exports.f = Object.getOwnPropertySymbols; - - -/***/ }), -/* 43 */ -/***/ (function(module, exports) { - - exports.f = {}.propertyIsEnumerable; - - -/***/ }), -/* 44 */ -/***/ (function(module, exports, __webpack_require__) { - - // 7.2.2 IsArray(argument) - var cof = __webpack_require__(34); - module.exports = Array.isArray || function isArray(arg) { - return cof(arg) == 'Array'; - }; - - -/***/ }), -/* 45 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) - var anObject = __webpack_require__(12); - var dPs = __webpack_require__(46); - var enumBugKeys = __webpack_require__(41); - var IE_PROTO = __webpack_require__(40)('IE_PROTO'); - var Empty = function () { /* empty */ }; - var PROTOTYPE = 'prototype'; - - // Create object with fake `null` prototype: use iframe Object with cleared prototype - var createDict = function () { - // Thrash, waste and sodomy: IE GC bug - var iframe = __webpack_require__(15)('iframe'); - var i = enumBugKeys.length; - var lt = '<'; - var gt = '>'; - var iframeDocument; - iframe.style.display = 'none'; - __webpack_require__(47).appendChild(iframe); - iframe.src = 'javascript:'; // eslint-disable-line no-script-url - // createDict = iframe.contentWindow.Object; - // html.removeChild(iframe); - iframeDocument = iframe.contentWindow.document; - iframeDocument.open(); - iframeDocument.write(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt); - iframeDocument.close(); - createDict = iframeDocument.F; - while (i--) delete createDict[PROTOTYPE][enumBugKeys[i]]; - return createDict(); - }; - - module.exports = Object.create || function create(O, Properties) { - var result; - if (O !== null) { - Empty[PROTOTYPE] = anObject(O); - result = new Empty(); - Empty[PROTOTYPE] = null; - // add "__proto__" for Object.getPrototypeOf polyfill - result[IE_PROTO] = O; - } else result = createDict(); - return Properties === undefined ? result : dPs(result, Properties); - }; - - -/***/ }), -/* 46 */ -/***/ (function(module, exports, __webpack_require__) { - - var dP = __webpack_require__(11); - var anObject = __webpack_require__(12); - var getKeys = __webpack_require__(30); - - module.exports = __webpack_require__(6) ? Object.defineProperties : function defineProperties(O, Properties) { - anObject(O); - var keys = getKeys(Properties); - var length = keys.length; - var i = 0; - var P; - while (length > i) dP.f(O, P = keys[i++], Properties[P]); - return O; - }; - - -/***/ }), -/* 47 */ -/***/ (function(module, exports, __webpack_require__) { - - var document = __webpack_require__(4).document; - module.exports = document && document.documentElement; - - -/***/ }), -/* 48 */ -/***/ (function(module, exports, __webpack_require__) { - - // fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window - var toIObject = __webpack_require__(32); - var gOPN = __webpack_require__(49).f; - var toString = {}.toString; - - var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames - ? Object.getOwnPropertyNames(window) : []; - - var getWindowNames = function (it) { - try { - return gOPN(it); - } catch (e) { - return windowNames.slice(); - } - }; - - module.exports.f = function getOwnPropertyNames(it) { - return windowNames && toString.call(it) == '[object Window]' ? getWindowNames(it) : gOPN(toIObject(it)); - }; - - -/***/ }), -/* 49 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O) - var $keys = __webpack_require__(31); - var hiddenKeys = __webpack_require__(41).concat('length', 'prototype'); - - exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) { - return $keys(O, hiddenKeys); - }; - - -/***/ }), -/* 50 */ -/***/ (function(module, exports, __webpack_require__) { - - var pIE = __webpack_require__(43); - var createDesc = __webpack_require__(17); - var toIObject = __webpack_require__(32); - var toPrimitive = __webpack_require__(16); - var has = __webpack_require__(5); - var IE8_DOM_DEFINE = __webpack_require__(14); - var gOPD = Object.getOwnPropertyDescriptor; - - exports.f = __webpack_require__(6) ? gOPD : function getOwnPropertyDescriptor(O, P) { - O = toIObject(O); - P = toPrimitive(P, true); - if (IE8_DOM_DEFINE) try { - return gOPD(O, P); - } catch (e) { /* empty */ } - if (has(O, P)) return createDesc(!pIE.f.call(O, P), O[P]); - }; - - -/***/ }), -/* 51 */ -/***/ (function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8); - // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) - $export($export.S, 'Object', { create: __webpack_require__(45) }); - - -/***/ }), -/* 52 */ -/***/ (function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8); - // 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes) - $export($export.S + $export.F * !__webpack_require__(6), 'Object', { defineProperty: __webpack_require__(11).f }); - - -/***/ }), -/* 53 */ -/***/ (function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8); - // 19.1.2.3 / 15.2.3.7 Object.defineProperties(O, Properties) - $export($export.S + $export.F * !__webpack_require__(6), 'Object', { defineProperties: __webpack_require__(46) }); - - -/***/ }), -/* 54 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P) - var toIObject = __webpack_require__(32); - var $getOwnPropertyDescriptor = __webpack_require__(50).f; - - __webpack_require__(55)('getOwnPropertyDescriptor', function () { - return function getOwnPropertyDescriptor(it, key) { - return $getOwnPropertyDescriptor(toIObject(it), key); - }; - }); - - -/***/ }), -/* 55 */ -/***/ (function(module, exports, __webpack_require__) { - - // most Object methods by ES6 should accept primitives - var $export = __webpack_require__(8); - var core = __webpack_require__(9); - var fails = __webpack_require__(7); - module.exports = function (KEY, exec) { - var fn = (core.Object || {})[KEY] || Object[KEY]; - var exp = {}; - exp[KEY] = exec(fn); - $export($export.S + $export.F * fails(function () { fn(1); }), 'Object', exp); - }; - - -/***/ }), -/* 56 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.2.9 Object.getPrototypeOf(O) - var toObject = __webpack_require__(57); - var $getPrototypeOf = __webpack_require__(58); - - __webpack_require__(55)('getPrototypeOf', function () { - return function getPrototypeOf(it) { - return $getPrototypeOf(toObject(it)); - }; - }); - - -/***/ }), -/* 57 */ -/***/ (function(module, exports, __webpack_require__) { - - // 7.1.13 ToObject(argument) - var defined = __webpack_require__(35); - module.exports = function (it) { - return Object(defined(it)); - }; - - -/***/ }), -/* 58 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O) - var has = __webpack_require__(5); - var toObject = __webpack_require__(57); - var IE_PROTO = __webpack_require__(40)('IE_PROTO'); - var ObjectProto = Object.prototype; - - module.exports = Object.getPrototypeOf || function (O) { - O = toObject(O); - if (has(O, IE_PROTO)) return O[IE_PROTO]; - if (typeof O.constructor == 'function' && O instanceof O.constructor) { - return O.constructor.prototype; - } return O instanceof Object ? ObjectProto : null; - }; - - -/***/ }), -/* 59 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.2.14 Object.keys(O) - var toObject = __webpack_require__(57); - var $keys = __webpack_require__(30); - - __webpack_require__(55)('keys', function () { - return function keys(it) { - return $keys(toObject(it)); - }; - }); - - -/***/ }), -/* 60 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.2.7 Object.getOwnPropertyNames(O) - __webpack_require__(55)('getOwnPropertyNames', function () { - return __webpack_require__(48).f; - }); - - -/***/ }), -/* 61 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.2.5 Object.freeze(O) - var isObject = __webpack_require__(13); - var meta = __webpack_require__(22).onFreeze; - - __webpack_require__(55)('freeze', function ($freeze) { - return function freeze(it) { - return $freeze && isObject(it) ? $freeze(meta(it)) : it; - }; - }); - - -/***/ }), -/* 62 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.2.17 Object.seal(O) - var isObject = __webpack_require__(13); - var meta = __webpack_require__(22).onFreeze; - - __webpack_require__(55)('seal', function ($seal) { - return function seal(it) { - return $seal && isObject(it) ? $seal(meta(it)) : it; - }; - }); - - -/***/ }), -/* 63 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.2.15 Object.preventExtensions(O) - var isObject = __webpack_require__(13); - var meta = __webpack_require__(22).onFreeze; - - __webpack_require__(55)('preventExtensions', function ($preventExtensions) { - return function preventExtensions(it) { - return $preventExtensions && isObject(it) ? $preventExtensions(meta(it)) : it; - }; - }); - - -/***/ }), -/* 64 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.2.12 Object.isFrozen(O) - var isObject = __webpack_require__(13); - - __webpack_require__(55)('isFrozen', function ($isFrozen) { - return function isFrozen(it) { - return isObject(it) ? $isFrozen ? $isFrozen(it) : false : true; - }; - }); - - -/***/ }), -/* 65 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.2.13 Object.isSealed(O) - var isObject = __webpack_require__(13); - - __webpack_require__(55)('isSealed', function ($isSealed) { - return function isSealed(it) { - return isObject(it) ? $isSealed ? $isSealed(it) : false : true; - }; - }); - - -/***/ }), -/* 66 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.2.11 Object.isExtensible(O) - var isObject = __webpack_require__(13); - - __webpack_require__(55)('isExtensible', function ($isExtensible) { - return function isExtensible(it) { - return isObject(it) ? $isExtensible ? $isExtensible(it) : true : false; - }; - }); - - -/***/ }), -/* 67 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.3.1 Object.assign(target, source) - var $export = __webpack_require__(8); - - $export($export.S + $export.F, 'Object', { assign: __webpack_require__(68) }); - - -/***/ }), -/* 68 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // 19.1.2.1 Object.assign(target, source, ...) - var getKeys = __webpack_require__(30); - var gOPS = __webpack_require__(42); - var pIE = __webpack_require__(43); - var toObject = __webpack_require__(57); - var IObject = __webpack_require__(33); - var $assign = Object.assign; - - // should work with symbols and should have deterministic property order (V8 bug) - module.exports = !$assign || __webpack_require__(7)(function () { - var A = {}; - var B = {}; - // eslint-disable-next-line no-undef - var S = Symbol(); - var K = 'abcdefghijklmnopqrst'; - A[S] = 7; - K.split('').forEach(function (k) { B[k] = k; }); - return $assign({}, A)[S] != 7 || Object.keys($assign({}, B)).join('') != K; - }) ? function assign(target, source) { // eslint-disable-line no-unused-vars - var T = toObject(target); - var aLen = arguments.length; - var index = 1; - var getSymbols = gOPS.f; - var isEnum = pIE.f; - while (aLen > index) { - var S = IObject(arguments[index++]); - var keys = getSymbols ? getKeys(S).concat(getSymbols(S)) : getKeys(S); - var length = keys.length; - var j = 0; - var key; - while (length > j) if (isEnum.call(S, key = keys[j++])) T[key] = S[key]; - } return T; - } : $assign; - - -/***/ }), -/* 69 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.3.10 Object.is(value1, value2) - var $export = __webpack_require__(8); - $export($export.S, 'Object', { is: __webpack_require__(70) }); - - -/***/ }), -/* 70 */ -/***/ (function(module, exports) { - - // 7.2.9 SameValue(x, y) - module.exports = Object.is || function is(x, y) { - // eslint-disable-next-line no-self-compare - return x === y ? x !== 0 || 1 / x === 1 / y : x != x && y != y; - }; - - -/***/ }), -/* 71 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.3.19 Object.setPrototypeOf(O, proto) - var $export = __webpack_require__(8); - $export($export.S, 'Object', { setPrototypeOf: __webpack_require__(72).set }); - - -/***/ }), -/* 72 */ -/***/ (function(module, exports, __webpack_require__) { - - // Works with __proto__ only. Old v8 can't work with null proto objects. - /* eslint-disable no-proto */ - var isObject = __webpack_require__(13); - var anObject = __webpack_require__(12); - var check = function (O, proto) { - anObject(O); - if (!isObject(proto) && proto !== null) throw TypeError(proto + ": can't set as prototype!"); - }; - module.exports = { - set: Object.setPrototypeOf || ('__proto__' in {} ? // eslint-disable-line - function (test, buggy, set) { - try { - set = __webpack_require__(20)(Function.call, __webpack_require__(50).f(Object.prototype, '__proto__').set, 2); - set(test, []); - buggy = !(test instanceof Array); - } catch (e) { buggy = true; } - return function setPrototypeOf(O, proto) { - check(O, proto); - if (buggy) O.__proto__ = proto; - else set(O, proto); - return O; - }; - }({}, false) : undefined), - check: check - }; - - -/***/ }), -/* 73 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // 19.1.3.6 Object.prototype.toString() - var classof = __webpack_require__(74); - var test = {}; - test[__webpack_require__(26)('toStringTag')] = 'z'; - if (test + '' != '[object z]') { - __webpack_require__(18)(Object.prototype, 'toString', function toString() { - return '[object ' + classof(this) + ']'; - }, true); - } - - -/***/ }), -/* 74 */ -/***/ (function(module, exports, __webpack_require__) { - - // getting tag from 19.1.3.6 Object.prototype.toString() - var cof = __webpack_require__(34); - var TAG = __webpack_require__(26)('toStringTag'); - // ES3 wrong here - var ARG = cof(function () { return arguments; }()) == 'Arguments'; - - // fallback for IE11 Script Access Denied error - var tryGet = function (it, key) { - try { - return it[key]; - } catch (e) { /* empty */ } - }; - - module.exports = function (it) { - var O, T, B; - return it === undefined ? 'Undefined' : it === null ? 'Null' - // @@toStringTag case - : typeof (T = tryGet(O = Object(it), TAG)) == 'string' ? T - // builtinTag case - : ARG ? cof(O) - // ES3 arguments fallback - : (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B; - }; - - -/***/ }), -/* 75 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.2.3.2 / 15.3.4.5 Function.prototype.bind(thisArg, args...) - var $export = __webpack_require__(8); - - $export($export.P, 'Function', { bind: __webpack_require__(76) }); - - -/***/ }), -/* 76 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var aFunction = __webpack_require__(21); - var isObject = __webpack_require__(13); - var invoke = __webpack_require__(77); - var arraySlice = [].slice; - var factories = {}; - - var construct = function (F, len, args) { - if (!(len in factories)) { - for (var n = [], i = 0; i < len; i++) n[i] = 'a[' + i + ']'; - // eslint-disable-next-line no-new-func - factories[len] = Function('F,a', 'return new F(' + n.join(',') + ')'); - } return factories[len](F, args); - }; - - module.exports = Function.bind || function bind(that /* , ...args */) { - var fn = aFunction(this); - var partArgs = arraySlice.call(arguments, 1); - var bound = function (/* args... */) { - var args = partArgs.concat(arraySlice.call(arguments)); - return this instanceof bound ? construct(fn, args.length, args) : invoke(fn, args, that); - }; - if (isObject(fn.prototype)) bound.prototype = fn.prototype; - return bound; - }; - - -/***/ }), -/* 77 */ -/***/ (function(module, exports) { - - // fast apply, http://jsperf.lnkit.com/fast-apply/5 - module.exports = function (fn, args, that) { - var un = that === undefined; - switch (args.length) { - case 0: return un ? fn() - : fn.call(that); - case 1: return un ? fn(args[0]) - : fn.call(that, args[0]); - case 2: return un ? fn(args[0], args[1]) - : fn.call(that, args[0], args[1]); - case 3: return un ? fn(args[0], args[1], args[2]) - : fn.call(that, args[0], args[1], args[2]); - case 4: return un ? fn(args[0], args[1], args[2], args[3]) - : fn.call(that, args[0], args[1], args[2], args[3]); - } return fn.apply(that, args); - }; - - -/***/ }), -/* 78 */ -/***/ (function(module, exports, __webpack_require__) { - - var dP = __webpack_require__(11).f; - var FProto = Function.prototype; - var nameRE = /^\s*function ([^ (]*)/; - var NAME = 'name'; - - // 19.2.4.2 name - NAME in FProto || __webpack_require__(6) && dP(FProto, NAME, { - configurable: true, - get: function () { - try { - return ('' + this).match(nameRE)[1]; - } catch (e) { - return ''; - } - } - }); - - -/***/ }), -/* 79 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var isObject = __webpack_require__(13); - var getPrototypeOf = __webpack_require__(58); - var HAS_INSTANCE = __webpack_require__(26)('hasInstance'); - var FunctionProto = Function.prototype; - // 19.2.3.6 Function.prototype[@@hasInstance](V) - if (!(HAS_INSTANCE in FunctionProto)) __webpack_require__(11).f(FunctionProto, HAS_INSTANCE, { value: function (O) { - if (typeof this != 'function' || !isObject(O)) return false; - if (!isObject(this.prototype)) return O instanceof this; - // for environment w/o native `@@hasInstance` logic enough `instanceof`, but add this: - while (O = getPrototypeOf(O)) if (this.prototype === O) return true; - return false; - } }); - - -/***/ }), -/* 80 */ -/***/ (function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8); - var $parseInt = __webpack_require__(81); - // 18.2.5 parseInt(string, radix) - $export($export.G + $export.F * (parseInt != $parseInt), { parseInt: $parseInt }); - - -/***/ }), -/* 81 */ -/***/ (function(module, exports, __webpack_require__) { - - var $parseInt = __webpack_require__(4).parseInt; - var $trim = __webpack_require__(82).trim; - var ws = __webpack_require__(83); - var hex = /^[-+]?0[xX]/; - - module.exports = $parseInt(ws + '08') !== 8 || $parseInt(ws + '0x16') !== 22 ? function parseInt(str, radix) { - var string = $trim(String(str), 3); - return $parseInt(string, (radix >>> 0) || (hex.test(string) ? 16 : 10)); - } : $parseInt; - - -/***/ }), -/* 82 */ -/***/ (function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8); - var defined = __webpack_require__(35); - var fails = __webpack_require__(7); - var spaces = __webpack_require__(83); - var space = '[' + spaces + ']'; - var non = '\u200b\u0085'; - var ltrim = RegExp('^' + space + space + '*'); - var rtrim = RegExp(space + space + '*$'); - - var exporter = function (KEY, exec, ALIAS) { - var exp = {}; - var FORCE = fails(function () { - return !!spaces[KEY]() || non[KEY]() != non; - }); - var fn = exp[KEY] = FORCE ? exec(trim) : spaces[KEY]; - if (ALIAS) exp[ALIAS] = fn; - $export($export.P + $export.F * FORCE, 'String', exp); - }; - - // 1 -> String#trimLeft - // 2 -> String#trimRight - // 3 -> String#trim - var trim = exporter.trim = function (string, TYPE) { - string = String(defined(string)); - if (TYPE & 1) string = string.replace(ltrim, ''); - if (TYPE & 2) string = string.replace(rtrim, ''); - return string; - }; - - module.exports = exporter; - - -/***/ }), -/* 83 */ -/***/ (function(module, exports) { - - module.exports = '\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003' + - '\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF'; - - -/***/ }), -/* 84 */ -/***/ (function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8); - var $parseFloat = __webpack_require__(85); - // 18.2.4 parseFloat(string) - $export($export.G + $export.F * (parseFloat != $parseFloat), { parseFloat: $parseFloat }); - - -/***/ }), -/* 85 */ -/***/ (function(module, exports, __webpack_require__) { - - var $parseFloat = __webpack_require__(4).parseFloat; - var $trim = __webpack_require__(82).trim; - - module.exports = 1 / $parseFloat(__webpack_require__(83) + '-0') !== -Infinity ? function parseFloat(str) { - var string = $trim(String(str), 3); - var result = $parseFloat(string); - return result === 0 && string.charAt(0) == '-' ? -0 : result; - } : $parseFloat; - - -/***/ }), -/* 86 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var global = __webpack_require__(4); - var has = __webpack_require__(5); - var cof = __webpack_require__(34); - var inheritIfRequired = __webpack_require__(87); - var toPrimitive = __webpack_require__(16); - var fails = __webpack_require__(7); - var gOPN = __webpack_require__(49).f; - var gOPD = __webpack_require__(50).f; - var dP = __webpack_require__(11).f; - var $trim = __webpack_require__(82).trim; - var NUMBER = 'Number'; - var $Number = global[NUMBER]; - var Base = $Number; - var proto = $Number.prototype; - // Opera ~12 has broken Object#toString - var BROKEN_COF = cof(__webpack_require__(45)(proto)) == NUMBER; - var TRIM = 'trim' in String.prototype; - - // 7.1.3 ToNumber(argument) - var toNumber = function (argument) { - var it = toPrimitive(argument, false); - if (typeof it == 'string' && it.length > 2) { - it = TRIM ? it.trim() : $trim(it, 3); - var first = it.charCodeAt(0); - var third, radix, maxCode; - if (first === 43 || first === 45) { - third = it.charCodeAt(2); - if (third === 88 || third === 120) return NaN; // Number('+0x1') should be NaN, old V8 fix - } else if (first === 48) { - switch (it.charCodeAt(1)) { - case 66: case 98: radix = 2; maxCode = 49; break; // fast equal /^0b[01]+$/i - case 79: case 111: radix = 8; maxCode = 55; break; // fast equal /^0o[0-7]+$/i - default: return +it; - } - for (var digits = it.slice(2), i = 0, l = digits.length, code; i < l; i++) { - code = digits.charCodeAt(i); - // parseInt parses a string to a first unavailable symbol - // but ToNumber should return NaN if a string contains unavailable symbols - if (code < 48 || code > maxCode) return NaN; - } return parseInt(digits, radix); - } - } return +it; - }; - - if (!$Number(' 0o1') || !$Number('0b1') || $Number('+0x1')) { - $Number = function Number(value) { - var it = arguments.length < 1 ? 0 : value; - var that = this; - return that instanceof $Number - // check on 1..constructor(foo) case - && (BROKEN_COF ? fails(function () { proto.valueOf.call(that); }) : cof(that) != NUMBER) - ? inheritIfRequired(new Base(toNumber(it)), that, $Number) : toNumber(it); - }; - for (var keys = __webpack_require__(6) ? gOPN(Base) : ( - // ES3: - 'MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,' + - // ES6 (in case, if modules with ES6 Number statics required before): - 'EPSILON,isFinite,isInteger,isNaN,isSafeInteger,MAX_SAFE_INTEGER,' + - 'MIN_SAFE_INTEGER,parseFloat,parseInt,isInteger' - ).split(','), j = 0, key; keys.length > j; j++) { - if (has(Base, key = keys[j]) && !has($Number, key)) { - dP($Number, key, gOPD(Base, key)); - } - } - $Number.prototype = proto; - proto.constructor = $Number; - __webpack_require__(18)(global, NUMBER, $Number); - } - - -/***/ }), -/* 87 */ -/***/ (function(module, exports, __webpack_require__) { - - var isObject = __webpack_require__(13); - var setPrototypeOf = __webpack_require__(72).set; - module.exports = function (that, target, C) { - var S = target.constructor; - var P; - if (S !== C && typeof S == 'function' && (P = S.prototype) !== C.prototype && isObject(P) && setPrototypeOf) { - setPrototypeOf(that, P); - } return that; - }; - - -/***/ }), -/* 88 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var toInteger = __webpack_require__(38); - var aNumberValue = __webpack_require__(89); - var repeat = __webpack_require__(90); - var $toFixed = 1.0.toFixed; - var floor = Math.floor; - var data = [0, 0, 0, 0, 0, 0]; - var ERROR = 'Number.toFixed: incorrect invocation!'; - var ZERO = '0'; - - var multiply = function (n, c) { - var i = -1; - var c2 = c; - while (++i < 6) { - c2 += n * data[i]; - data[i] = c2 % 1e7; - c2 = floor(c2 / 1e7); - } - }; - var divide = function (n) { - var i = 6; - var c = 0; - while (--i >= 0) { - c += data[i]; - data[i] = floor(c / n); - c = (c % n) * 1e7; - } - }; - var numToString = function () { - var i = 6; - var s = ''; - while (--i >= 0) { - if (s !== '' || i === 0 || data[i] !== 0) { - var t = String(data[i]); - s = s === '' ? t : s + repeat.call(ZERO, 7 - t.length) + t; - } - } return s; - }; - var pow = function (x, n, acc) { - return n === 0 ? acc : n % 2 === 1 ? pow(x, n - 1, acc * x) : pow(x * x, n / 2, acc); - }; - var log = function (x) { - var n = 0; - var x2 = x; - while (x2 >= 4096) { - n += 12; - x2 /= 4096; - } - while (x2 >= 2) { - n += 1; - x2 /= 2; - } return n; - }; - - $export($export.P + $export.F * (!!$toFixed && ( - 0.00008.toFixed(3) !== '0.000' || - 0.9.toFixed(0) !== '1' || - 1.255.toFixed(2) !== '1.25' || - 1000000000000000128.0.toFixed(0) !== '1000000000000000128' - ) || !__webpack_require__(7)(function () { - // V8 ~ Android 4.3- - $toFixed.call({}); - })), 'Number', { - toFixed: function toFixed(fractionDigits) { - var x = aNumberValue(this, ERROR); - var f = toInteger(fractionDigits); - var s = ''; - var m = ZERO; - var e, z, j, k; - if (f < 0 || f > 20) throw RangeError(ERROR); - // eslint-disable-next-line no-self-compare - if (x != x) return 'NaN'; - if (x <= -1e21 || x >= 1e21) return String(x); - if (x < 0) { - s = '-'; - x = -x; - } - if (x > 1e-21) { - e = log(x * pow(2, 69, 1)) - 69; - z = e < 0 ? x * pow(2, -e, 1) : x / pow(2, e, 1); - z *= 0x10000000000000; - e = 52 - e; - if (e > 0) { - multiply(0, z); - j = f; - while (j >= 7) { - multiply(1e7, 0); - j -= 7; - } - multiply(pow(10, j, 1), 0); - j = e - 1; - while (j >= 23) { - divide(1 << 23); - j -= 23; - } - divide(1 << j); - multiply(1, 1); - divide(2); - m = numToString(); - } else { - multiply(0, z); - multiply(1 << -e, 0); - m = numToString() + repeat.call(ZERO, f); - } - } - if (f > 0) { - k = m.length; - m = s + (k <= f ? '0.' + repeat.call(ZERO, f - k) + m : m.slice(0, k - f) + '.' + m.slice(k - f)); - } else { - m = s + m; - } return m; - } - }); - - -/***/ }), -/* 89 */ -/***/ (function(module, exports, __webpack_require__) { - - var cof = __webpack_require__(34); - module.exports = function (it, msg) { - if (typeof it != 'number' && cof(it) != 'Number') throw TypeError(msg); - return +it; - }; - - -/***/ }), -/* 90 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var toInteger = __webpack_require__(38); - var defined = __webpack_require__(35); - - module.exports = function repeat(count) { - var str = String(defined(this)); - var res = ''; - var n = toInteger(count); - if (n < 0 || n == Infinity) throw RangeError("Count can't be negative"); - for (;n > 0; (n >>>= 1) && (str += str)) if (n & 1) res += str; - return res; - }; - - -/***/ }), -/* 91 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var $fails = __webpack_require__(7); - var aNumberValue = __webpack_require__(89); - var $toPrecision = 1.0.toPrecision; - - $export($export.P + $export.F * ($fails(function () { - // IE7- - return $toPrecision.call(1, undefined) !== '1'; - }) || !$fails(function () { - // V8 ~ Android 4.3- - $toPrecision.call({}); - })), 'Number', { - toPrecision: function toPrecision(precision) { - var that = aNumberValue(this, 'Number#toPrecision: incorrect invocation!'); - return precision === undefined ? $toPrecision.call(that) : $toPrecision.call(that, precision); - } - }); - - -/***/ }), -/* 92 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.1.2.1 Number.EPSILON - var $export = __webpack_require__(8); - - $export($export.S, 'Number', { EPSILON: Math.pow(2, -52) }); - - -/***/ }), -/* 93 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.1.2.2 Number.isFinite(number) - var $export = __webpack_require__(8); - var _isFinite = __webpack_require__(4).isFinite; - - $export($export.S, 'Number', { - isFinite: function isFinite(it) { - return typeof it == 'number' && _isFinite(it); - } - }); - - -/***/ }), -/* 94 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.1.2.3 Number.isInteger(number) - var $export = __webpack_require__(8); - - $export($export.S, 'Number', { isInteger: __webpack_require__(95) }); - - -/***/ }), -/* 95 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.1.2.3 Number.isInteger(number) - var isObject = __webpack_require__(13); - var floor = Math.floor; - module.exports = function isInteger(it) { - return !isObject(it) && isFinite(it) && floor(it) === it; - }; - - -/***/ }), -/* 96 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.1.2.4 Number.isNaN(number) - var $export = __webpack_require__(8); - - $export($export.S, 'Number', { - isNaN: function isNaN(number) { - // eslint-disable-next-line no-self-compare - return number != number; - } - }); - - -/***/ }), -/* 97 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.1.2.5 Number.isSafeInteger(number) - var $export = __webpack_require__(8); - var isInteger = __webpack_require__(95); - var abs = Math.abs; - - $export($export.S, 'Number', { - isSafeInteger: function isSafeInteger(number) { - return isInteger(number) && abs(number) <= 0x1fffffffffffff; - } - }); - - -/***/ }), -/* 98 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.1.2.6 Number.MAX_SAFE_INTEGER - var $export = __webpack_require__(8); - - $export($export.S, 'Number', { MAX_SAFE_INTEGER: 0x1fffffffffffff }); - - -/***/ }), -/* 99 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.1.2.10 Number.MIN_SAFE_INTEGER - var $export = __webpack_require__(8); - - $export($export.S, 'Number', { MIN_SAFE_INTEGER: -0x1fffffffffffff }); - - -/***/ }), -/* 100 */ -/***/ (function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8); - var $parseFloat = __webpack_require__(85); - // 20.1.2.12 Number.parseFloat(string) - $export($export.S + $export.F * (Number.parseFloat != $parseFloat), 'Number', { parseFloat: $parseFloat }); - - -/***/ }), -/* 101 */ -/***/ (function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8); - var $parseInt = __webpack_require__(81); - // 20.1.2.13 Number.parseInt(string, radix) - $export($export.S + $export.F * (Number.parseInt != $parseInt), 'Number', { parseInt: $parseInt }); - - -/***/ }), -/* 102 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.3 Math.acosh(x) - var $export = __webpack_require__(8); - var log1p = __webpack_require__(103); - var sqrt = Math.sqrt; - var $acosh = Math.acosh; - - $export($export.S + $export.F * !($acosh - // V8 bug: https://code.google.com/p/v8/issues/detail?id=3509 - && Math.floor($acosh(Number.MAX_VALUE)) == 710 - // Tor Browser bug: Math.acosh(Infinity) -> NaN - && $acosh(Infinity) == Infinity - ), 'Math', { - acosh: function acosh(x) { - return (x = +x) < 1 ? NaN : x > 94906265.62425156 - ? Math.log(x) + Math.LN2 - : log1p(x - 1 + sqrt(x - 1) * sqrt(x + 1)); - } - }); - - -/***/ }), -/* 103 */ -/***/ (function(module, exports) { - - // 20.2.2.20 Math.log1p(x) - module.exports = Math.log1p || function log1p(x) { - return (x = +x) > -1e-8 && x < 1e-8 ? x - x * x / 2 : Math.log(1 + x); - }; - - -/***/ }), -/* 104 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.5 Math.asinh(x) - var $export = __webpack_require__(8); - var $asinh = Math.asinh; - - function asinh(x) { - return !isFinite(x = +x) || x == 0 ? x : x < 0 ? -asinh(-x) : Math.log(x + Math.sqrt(x * x + 1)); - } - - // Tor Browser bug: Math.asinh(0) -> -0 - $export($export.S + $export.F * !($asinh && 1 / $asinh(0) > 0), 'Math', { asinh: asinh }); - - -/***/ }), -/* 105 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.7 Math.atanh(x) - var $export = __webpack_require__(8); - var $atanh = Math.atanh; - - // Tor Browser bug: Math.atanh(-0) -> 0 - $export($export.S + $export.F * !($atanh && 1 / $atanh(-0) < 0), 'Math', { - atanh: function atanh(x) { - return (x = +x) == 0 ? x : Math.log((1 + x) / (1 - x)) / 2; - } - }); - - -/***/ }), -/* 106 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.9 Math.cbrt(x) - var $export = __webpack_require__(8); - var sign = __webpack_require__(107); - - $export($export.S, 'Math', { - cbrt: function cbrt(x) { - return sign(x = +x) * Math.pow(Math.abs(x), 1 / 3); - } - }); - - -/***/ }), -/* 107 */ -/***/ (function(module, exports) { - - // 20.2.2.28 Math.sign(x) - module.exports = Math.sign || function sign(x) { - // eslint-disable-next-line no-self-compare - return (x = +x) == 0 || x != x ? x : x < 0 ? -1 : 1; - }; - - -/***/ }), -/* 108 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.11 Math.clz32(x) - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { - clz32: function clz32(x) { - return (x >>>= 0) ? 31 - Math.floor(Math.log(x + 0.5) * Math.LOG2E) : 32; - } - }); - - -/***/ }), -/* 109 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.12 Math.cosh(x) - var $export = __webpack_require__(8); - var exp = Math.exp; - - $export($export.S, 'Math', { - cosh: function cosh(x) { - return (exp(x = +x) + exp(-x)) / 2; - } - }); - - -/***/ }), -/* 110 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.14 Math.expm1(x) - var $export = __webpack_require__(8); - var $expm1 = __webpack_require__(111); - - $export($export.S + $export.F * ($expm1 != Math.expm1), 'Math', { expm1: $expm1 }); - - -/***/ }), -/* 111 */ -/***/ (function(module, exports) { - - // 20.2.2.14 Math.expm1(x) - var $expm1 = Math.expm1; - module.exports = (!$expm1 - // Old FF bug - || $expm1(10) > 22025.465794806719 || $expm1(10) < 22025.4657948067165168 - // Tor Browser bug - || $expm1(-2e-17) != -2e-17 - ) ? function expm1(x) { - return (x = +x) == 0 ? x : x > -1e-6 && x < 1e-6 ? x + x * x / 2 : Math.exp(x) - 1; - } : $expm1; - - -/***/ }), -/* 112 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.16 Math.fround(x) - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { fround: __webpack_require__(113) }); - - -/***/ }), -/* 113 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.16 Math.fround(x) - var sign = __webpack_require__(107); - var pow = Math.pow; - var EPSILON = pow(2, -52); - var EPSILON32 = pow(2, -23); - var MAX32 = pow(2, 127) * (2 - EPSILON32); - var MIN32 = pow(2, -126); - - var roundTiesToEven = function (n) { - return n + 1 / EPSILON - 1 / EPSILON; - }; - - module.exports = Math.fround || function fround(x) { - var $abs = Math.abs(x); - var $sign = sign(x); - var a, result; - if ($abs < MIN32) return $sign * roundTiesToEven($abs / MIN32 / EPSILON32) * MIN32 * EPSILON32; - a = (1 + EPSILON32 / EPSILON) * $abs; - result = a - (a - $abs); - // eslint-disable-next-line no-self-compare - if (result > MAX32 || result != result) return $sign * Infinity; - return $sign * result; - }; - - -/***/ }), -/* 114 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.17 Math.hypot([value1[, value2[, … ]]]) - var $export = __webpack_require__(8); - var abs = Math.abs; - - $export($export.S, 'Math', { - hypot: function hypot(value1, value2) { // eslint-disable-line no-unused-vars - var sum = 0; - var i = 0; - var aLen = arguments.length; - var larg = 0; - var arg, div; - while (i < aLen) { - arg = abs(arguments[i++]); - if (larg < arg) { - div = larg / arg; - sum = sum * div * div + 1; - larg = arg; - } else if (arg > 0) { - div = arg / larg; - sum += div * div; - } else sum += arg; - } - return larg === Infinity ? Infinity : larg * Math.sqrt(sum); - } - }); - - -/***/ }), -/* 115 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.18 Math.imul(x, y) - var $export = __webpack_require__(8); - var $imul = Math.imul; - - // some WebKit versions fails with big numbers, some has wrong arity - $export($export.S + $export.F * __webpack_require__(7)(function () { - return $imul(0xffffffff, 5) != -5 || $imul.length != 2; - }), 'Math', { - imul: function imul(x, y) { - var UINT16 = 0xffff; - var xn = +x; - var yn = +y; - var xl = UINT16 & xn; - var yl = UINT16 & yn; - return 0 | xl * yl + ((UINT16 & xn >>> 16) * yl + xl * (UINT16 & yn >>> 16) << 16 >>> 0); - } - }); - - -/***/ }), -/* 116 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.21 Math.log10(x) - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { - log10: function log10(x) { - return Math.log(x) * Math.LOG10E; - } - }); - - -/***/ }), -/* 117 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.20 Math.log1p(x) - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { log1p: __webpack_require__(103) }); - - -/***/ }), -/* 118 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.22 Math.log2(x) - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { - log2: function log2(x) { - return Math.log(x) / Math.LN2; - } - }); - - -/***/ }), -/* 119 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.28 Math.sign(x) - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { sign: __webpack_require__(107) }); - - -/***/ }), -/* 120 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.30 Math.sinh(x) - var $export = __webpack_require__(8); - var expm1 = __webpack_require__(111); - var exp = Math.exp; - - // V8 near Chromium 38 has a problem with very small numbers - $export($export.S + $export.F * __webpack_require__(7)(function () { - return !Math.sinh(-2e-17) != -2e-17; - }), 'Math', { - sinh: function sinh(x) { - return Math.abs(x = +x) < 1 - ? (expm1(x) - expm1(-x)) / 2 - : (exp(x - 1) - exp(-x - 1)) * (Math.E / 2); - } - }); - - -/***/ }), -/* 121 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.33 Math.tanh(x) - var $export = __webpack_require__(8); - var expm1 = __webpack_require__(111); - var exp = Math.exp; - - $export($export.S, 'Math', { - tanh: function tanh(x) { - var a = expm1(x = +x); - var b = expm1(-x); - return a == Infinity ? 1 : b == Infinity ? -1 : (a - b) / (exp(x) + exp(-x)); - } - }); - - -/***/ }), -/* 122 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.34 Math.trunc(x) - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { - trunc: function trunc(it) { - return (it > 0 ? Math.floor : Math.ceil)(it); - } - }); - - -/***/ }), -/* 123 */ -/***/ (function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8); - var toAbsoluteIndex = __webpack_require__(39); - var fromCharCode = String.fromCharCode; - var $fromCodePoint = String.fromCodePoint; - - // length should be 1, old FF problem - $export($export.S + $export.F * (!!$fromCodePoint && $fromCodePoint.length != 1), 'String', { - // 21.1.2.2 String.fromCodePoint(...codePoints) - fromCodePoint: function fromCodePoint(x) { // eslint-disable-line no-unused-vars - var res = []; - var aLen = arguments.length; - var i = 0; - var code; - while (aLen > i) { - code = +arguments[i++]; - if (toAbsoluteIndex(code, 0x10ffff) !== code) throw RangeError(code + ' is not a valid code point'); - res.push(code < 0x10000 - ? fromCharCode(code) - : fromCharCode(((code -= 0x10000) >> 10) + 0xd800, code % 0x400 + 0xdc00) - ); - } return res.join(''); - } - }); - - -/***/ }), -/* 124 */ -/***/ (function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8); - var toIObject = __webpack_require__(32); - var toLength = __webpack_require__(37); - - $export($export.S, 'String', { - // 21.1.2.4 String.raw(callSite, ...substitutions) - raw: function raw(callSite) { - var tpl = toIObject(callSite.raw); - var len = toLength(tpl.length); - var aLen = arguments.length; - var res = []; - var i = 0; - while (len > i) { - res.push(String(tpl[i++])); - if (i < aLen) res.push(String(arguments[i])); - } return res.join(''); - } - }); - - -/***/ }), -/* 125 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // 21.1.3.25 String.prototype.trim() - __webpack_require__(82)('trim', function ($trim) { - return function trim() { - return $trim(this, 3); - }; - }); - - -/***/ }), -/* 126 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $at = __webpack_require__(127)(true); - - // 21.1.3.27 String.prototype[@@iterator]() - __webpack_require__(128)(String, 'String', function (iterated) { - this._t = String(iterated); // target - this._i = 0; // next index - // 21.1.5.2.1 %StringIteratorPrototype%.next() - }, function () { - var O = this._t; - var index = this._i; - var point; - if (index >= O.length) return { value: undefined, done: true }; - point = $at(O, index); - this._i += point.length; - return { value: point, done: false }; - }); - - -/***/ }), -/* 127 */ -/***/ (function(module, exports, __webpack_require__) { - - var toInteger = __webpack_require__(38); - var defined = __webpack_require__(35); - // true -> String#at - // false -> String#codePointAt - module.exports = function (TO_STRING) { - return function (that, pos) { - var s = String(defined(that)); - var i = toInteger(pos); - var l = s.length; - var a, b; - if (i < 0 || i >= l) return TO_STRING ? '' : undefined; - a = s.charCodeAt(i); - return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff - ? TO_STRING ? s.charAt(i) : a - : TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000; - }; - }; - - -/***/ }), -/* 128 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var LIBRARY = __webpack_require__(24); - var $export = __webpack_require__(8); - var redefine = __webpack_require__(18); - var hide = __webpack_require__(10); - var Iterators = __webpack_require__(129); - var $iterCreate = __webpack_require__(130); - var setToStringTag = __webpack_require__(25); - var getPrototypeOf = __webpack_require__(58); - var ITERATOR = __webpack_require__(26)('iterator'); - var BUGGY = !([].keys && 'next' in [].keys()); // Safari has buggy iterators w/o `next` - var FF_ITERATOR = '@@iterator'; - var KEYS = 'keys'; - var VALUES = 'values'; - - var returnThis = function () { return this; }; - - module.exports = function (Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED) { - $iterCreate(Constructor, NAME, next); - var getMethod = function (kind) { - if (!BUGGY && kind in proto) return proto[kind]; - switch (kind) { - case KEYS: return function keys() { return new Constructor(this, kind); }; - case VALUES: return function values() { return new Constructor(this, kind); }; - } return function entries() { return new Constructor(this, kind); }; - }; - var TAG = NAME + ' Iterator'; - var DEF_VALUES = DEFAULT == VALUES; - var VALUES_BUG = false; - var proto = Base.prototype; - var $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT]; - var $default = $native || getMethod(DEFAULT); - var $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined; - var $anyNative = NAME == 'Array' ? proto.entries || $native : $native; - var methods, key, IteratorPrototype; - // Fix native - if ($anyNative) { - IteratorPrototype = getPrototypeOf($anyNative.call(new Base())); - if (IteratorPrototype !== Object.prototype && IteratorPrototype.next) { - // Set @@toStringTag to native iterators - setToStringTag(IteratorPrototype, TAG, true); - // fix for some old engines - if (!LIBRARY && typeof IteratorPrototype[ITERATOR] != 'function') hide(IteratorPrototype, ITERATOR, returnThis); - } - } - // fix Array#{values, @@iterator}.name in V8 / FF - if (DEF_VALUES && $native && $native.name !== VALUES) { - VALUES_BUG = true; - $default = function values() { return $native.call(this); }; - } - // Define iterator - if ((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])) { - hide(proto, ITERATOR, $default); - } - // Plug for library - Iterators[NAME] = $default; - Iterators[TAG] = returnThis; - if (DEFAULT) { - methods = { - values: DEF_VALUES ? $default : getMethod(VALUES), - keys: IS_SET ? $default : getMethod(KEYS), - entries: $entries - }; - if (FORCED) for (key in methods) { - if (!(key in proto)) redefine(proto, key, methods[key]); - } else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods); - } - return methods; - }; - - -/***/ }), -/* 129 */ -/***/ (function(module, exports) { - - module.exports = {}; - - -/***/ }), -/* 130 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var create = __webpack_require__(45); - var descriptor = __webpack_require__(17); - var setToStringTag = __webpack_require__(25); - var IteratorPrototype = {}; - - // 25.1.2.1.1 %IteratorPrototype%[@@iterator]() - __webpack_require__(10)(IteratorPrototype, __webpack_require__(26)('iterator'), function () { return this; }); - - module.exports = function (Constructor, NAME, next) { - Constructor.prototype = create(IteratorPrototype, { next: descriptor(1, next) }); - setToStringTag(Constructor, NAME + ' Iterator'); - }; - - -/***/ }), -/* 131 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var $at = __webpack_require__(127)(false); - $export($export.P, 'String', { - // 21.1.3.3 String.prototype.codePointAt(pos) - codePointAt: function codePointAt(pos) { - return $at(this, pos); - } - }); - - -/***/ }), -/* 132 */ -/***/ (function(module, exports, __webpack_require__) { - - // 21.1.3.6 String.prototype.endsWith(searchString [, endPosition]) - 'use strict'; - var $export = __webpack_require__(8); - var toLength = __webpack_require__(37); - var context = __webpack_require__(133); - var ENDS_WITH = 'endsWith'; - var $endsWith = ''[ENDS_WITH]; - - $export($export.P + $export.F * __webpack_require__(135)(ENDS_WITH), 'String', { - endsWith: function endsWith(searchString /* , endPosition = @length */) { - var that = context(this, searchString, ENDS_WITH); - var endPosition = arguments.length > 1 ? arguments[1] : undefined; - var len = toLength(that.length); - var end = endPosition === undefined ? len : Math.min(toLength(endPosition), len); - var search = String(searchString); - return $endsWith - ? $endsWith.call(that, search, end) - : that.slice(end - search.length, end) === search; - } - }); - - -/***/ }), -/* 133 */ -/***/ (function(module, exports, __webpack_require__) { - - // helper for String#{startsWith, endsWith, includes} - var isRegExp = __webpack_require__(134); - var defined = __webpack_require__(35); - - module.exports = function (that, searchString, NAME) { - if (isRegExp(searchString)) throw TypeError('String#' + NAME + " doesn't accept regex!"); - return String(defined(that)); - }; - - -/***/ }), -/* 134 */ -/***/ (function(module, exports, __webpack_require__) { - - // 7.2.8 IsRegExp(argument) - var isObject = __webpack_require__(13); - var cof = __webpack_require__(34); - var MATCH = __webpack_require__(26)('match'); - module.exports = function (it) { - var isRegExp; - return isObject(it) && ((isRegExp = it[MATCH]) !== undefined ? !!isRegExp : cof(it) == 'RegExp'); - }; - - -/***/ }), -/* 135 */ -/***/ (function(module, exports, __webpack_require__) { - - var MATCH = __webpack_require__(26)('match'); - module.exports = function (KEY) { - var re = /./; - try { - '/./'[KEY](re); - } catch (e) { - try { - re[MATCH] = false; - return !'/./'[KEY](re); - } catch (f) { /* empty */ } - } return true; - }; - - -/***/ }), -/* 136 */ -/***/ (function(module, exports, __webpack_require__) { - - // 21.1.3.7 String.prototype.includes(searchString, position = 0) - 'use strict'; - var $export = __webpack_require__(8); - var context = __webpack_require__(133); - var INCLUDES = 'includes'; - - $export($export.P + $export.F * __webpack_require__(135)(INCLUDES), 'String', { - includes: function includes(searchString /* , position = 0 */) { - return !!~context(this, searchString, INCLUDES) - .indexOf(searchString, arguments.length > 1 ? arguments[1] : undefined); - } - }); - - -/***/ }), -/* 137 */ -/***/ (function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8); - - $export($export.P, 'String', { - // 21.1.3.13 String.prototype.repeat(count) - repeat: __webpack_require__(90) - }); - - -/***/ }), -/* 138 */ -/***/ (function(module, exports, __webpack_require__) { - - // 21.1.3.18 String.prototype.startsWith(searchString [, position ]) - 'use strict'; - var $export = __webpack_require__(8); - var toLength = __webpack_require__(37); - var context = __webpack_require__(133); - var STARTS_WITH = 'startsWith'; - var $startsWith = ''[STARTS_WITH]; - - $export($export.P + $export.F * __webpack_require__(135)(STARTS_WITH), 'String', { - startsWith: function startsWith(searchString /* , position = 0 */) { - var that = context(this, searchString, STARTS_WITH); - var index = toLength(Math.min(arguments.length > 1 ? arguments[1] : undefined, that.length)); - var search = String(searchString); - return $startsWith - ? $startsWith.call(that, search, index) - : that.slice(index, index + search.length) === search; - } - }); - - -/***/ }), -/* 139 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.2 String.prototype.anchor(name) - __webpack_require__(140)('anchor', function (createHTML) { - return function anchor(name) { - return createHTML(this, 'a', 'name', name); - }; - }); - - -/***/ }), -/* 140 */ -/***/ (function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8); - var fails = __webpack_require__(7); - var defined = __webpack_require__(35); - var quot = /"/g; - // B.2.3.2.1 CreateHTML(string, tag, attribute, value) - var createHTML = function (string, tag, attribute, value) { - var S = String(defined(string)); - var p1 = '<' + tag; - if (attribute !== '') p1 += ' ' + attribute + '="' + String(value).replace(quot, '"') + '"'; - return p1 + '>' + S + ''; - }; - module.exports = function (NAME, exec) { - var O = {}; - O[NAME] = exec(createHTML); - $export($export.P + $export.F * fails(function () { - var test = ''[NAME]('"'); - return test !== test.toLowerCase() || test.split('"').length > 3; - }), 'String', O); - }; - - -/***/ }), -/* 141 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.3 String.prototype.big() - __webpack_require__(140)('big', function (createHTML) { - return function big() { - return createHTML(this, 'big', '', ''); - }; - }); - - -/***/ }), -/* 142 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.4 String.prototype.blink() - __webpack_require__(140)('blink', function (createHTML) { - return function blink() { - return createHTML(this, 'blink', '', ''); - }; - }); - - -/***/ }), -/* 143 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.5 String.prototype.bold() - __webpack_require__(140)('bold', function (createHTML) { - return function bold() { - return createHTML(this, 'b', '', ''); - }; - }); - - -/***/ }), -/* 144 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.6 String.prototype.fixed() - __webpack_require__(140)('fixed', function (createHTML) { - return function fixed() { - return createHTML(this, 'tt', '', ''); - }; - }); - - -/***/ }), -/* 145 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.7 String.prototype.fontcolor(color) - __webpack_require__(140)('fontcolor', function (createHTML) { - return function fontcolor(color) { - return createHTML(this, 'font', 'color', color); - }; - }); - - -/***/ }), -/* 146 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.8 String.prototype.fontsize(size) - __webpack_require__(140)('fontsize', function (createHTML) { - return function fontsize(size) { - return createHTML(this, 'font', 'size', size); - }; - }); - - -/***/ }), -/* 147 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.9 String.prototype.italics() - __webpack_require__(140)('italics', function (createHTML) { - return function italics() { - return createHTML(this, 'i', '', ''); - }; - }); - - -/***/ }), -/* 148 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.10 String.prototype.link(url) - __webpack_require__(140)('link', function (createHTML) { - return function link(url) { - return createHTML(this, 'a', 'href', url); - }; - }); - - -/***/ }), -/* 149 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.11 String.prototype.small() - __webpack_require__(140)('small', function (createHTML) { - return function small() { - return createHTML(this, 'small', '', ''); - }; - }); - - -/***/ }), -/* 150 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.12 String.prototype.strike() - __webpack_require__(140)('strike', function (createHTML) { - return function strike() { - return createHTML(this, 'strike', '', ''); - }; - }); - - -/***/ }), -/* 151 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.13 String.prototype.sub() - __webpack_require__(140)('sub', function (createHTML) { - return function sub() { - return createHTML(this, 'sub', '', ''); - }; - }); - - -/***/ }), -/* 152 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.14 String.prototype.sup() - __webpack_require__(140)('sup', function (createHTML) { - return function sup() { - return createHTML(this, 'sup', '', ''); - }; - }); - - -/***/ }), -/* 153 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.3.3.1 / 15.9.4.4 Date.now() - var $export = __webpack_require__(8); - - $export($export.S, 'Date', { now: function () { return new Date().getTime(); } }); - - -/***/ }), -/* 154 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var toObject = __webpack_require__(57); - var toPrimitive = __webpack_require__(16); - - $export($export.P + $export.F * __webpack_require__(7)(function () { - return new Date(NaN).toJSON() !== null - || Date.prototype.toJSON.call({ toISOString: function () { return 1; } }) !== 1; - }), 'Date', { - // eslint-disable-next-line no-unused-vars - toJSON: function toJSON(key) { - var O = toObject(this); - var pv = toPrimitive(O); - return typeof pv == 'number' && !isFinite(pv) ? null : O.toISOString(); - } - }); - - -/***/ }), -/* 155 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.3.4.36 / 15.9.5.43 Date.prototype.toISOString() - var $export = __webpack_require__(8); - var toISOString = __webpack_require__(156); - - // PhantomJS / old WebKit has a broken implementations - $export($export.P + $export.F * (Date.prototype.toISOString !== toISOString), 'Date', { - toISOString: toISOString - }); - - -/***/ }), -/* 156 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // 20.3.4.36 / 15.9.5.43 Date.prototype.toISOString() - var fails = __webpack_require__(7); - var getTime = Date.prototype.getTime; - var $toISOString = Date.prototype.toISOString; - - var lz = function (num) { - return num > 9 ? num : '0' + num; - }; - - // PhantomJS / old WebKit has a broken implementations - module.exports = (fails(function () { - return $toISOString.call(new Date(-5e13 - 1)) != '0385-07-25T07:06:39.999Z'; - }) || !fails(function () { - $toISOString.call(new Date(NaN)); - })) ? function toISOString() { - if (!isFinite(getTime.call(this))) throw RangeError('Invalid time value'); - var d = this; - var y = d.getUTCFullYear(); - var m = d.getUTCMilliseconds(); - var s = y < 0 ? '-' : y > 9999 ? '+' : ''; - return s + ('00000' + Math.abs(y)).slice(s ? -6 : -4) + - '-' + lz(d.getUTCMonth() + 1) + '-' + lz(d.getUTCDate()) + - 'T' + lz(d.getUTCHours()) + ':' + lz(d.getUTCMinutes()) + - ':' + lz(d.getUTCSeconds()) + '.' + (m > 99 ? m : '0' + lz(m)) + 'Z'; - } : $toISOString; - - -/***/ }), -/* 157 */ -/***/ (function(module, exports, __webpack_require__) { - - var DateProto = Date.prototype; - var INVALID_DATE = 'Invalid Date'; - var TO_STRING = 'toString'; - var $toString = DateProto[TO_STRING]; - var getTime = DateProto.getTime; - if (new Date(NaN) + '' != INVALID_DATE) { - __webpack_require__(18)(DateProto, TO_STRING, function toString() { - var value = getTime.call(this); - // eslint-disable-next-line no-self-compare - return value === value ? $toString.call(this) : INVALID_DATE; - }); - } - - -/***/ }), -/* 158 */ -/***/ (function(module, exports, __webpack_require__) { - - var TO_PRIMITIVE = __webpack_require__(26)('toPrimitive'); - var proto = Date.prototype; - - if (!(TO_PRIMITIVE in proto)) __webpack_require__(10)(proto, TO_PRIMITIVE, __webpack_require__(159)); - - -/***/ }), -/* 159 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var anObject = __webpack_require__(12); - var toPrimitive = __webpack_require__(16); - var NUMBER = 'number'; - - module.exports = function (hint) { - if (hint !== 'string' && hint !== NUMBER && hint !== 'default') throw TypeError('Incorrect hint'); - return toPrimitive(anObject(this), hint != NUMBER); - }; - - -/***/ }), -/* 160 */ -/***/ (function(module, exports, __webpack_require__) { - - // 22.1.2.2 / 15.4.3.2 Array.isArray(arg) - var $export = __webpack_require__(8); - - $export($export.S, 'Array', { isArray: __webpack_require__(44) }); - - -/***/ }), -/* 161 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var ctx = __webpack_require__(20); - var $export = __webpack_require__(8); - var toObject = __webpack_require__(57); - var call = __webpack_require__(162); - var isArrayIter = __webpack_require__(163); - var toLength = __webpack_require__(37); - var createProperty = __webpack_require__(164); - var getIterFn = __webpack_require__(165); - - $export($export.S + $export.F * !__webpack_require__(166)(function (iter) { Array.from(iter); }), 'Array', { - // 22.1.2.1 Array.from(arrayLike, mapfn = undefined, thisArg = undefined) - from: function from(arrayLike /* , mapfn = undefined, thisArg = undefined */) { - var O = toObject(arrayLike); - var C = typeof this == 'function' ? this : Array; - var aLen = arguments.length; - var mapfn = aLen > 1 ? arguments[1] : undefined; - var mapping = mapfn !== undefined; - var index = 0; - var iterFn = getIterFn(O); - var length, result, step, iterator; - if (mapping) mapfn = ctx(mapfn, aLen > 2 ? arguments[2] : undefined, 2); - // if object isn't iterable or it's array with default iterator - use simple case - if (iterFn != undefined && !(C == Array && isArrayIter(iterFn))) { - for (iterator = iterFn.call(O), result = new C(); !(step = iterator.next()).done; index++) { - createProperty(result, index, mapping ? call(iterator, mapfn, [step.value, index], true) : step.value); - } - } else { - length = toLength(O.length); - for (result = new C(length); length > index; index++) { - createProperty(result, index, mapping ? mapfn(O[index], index) : O[index]); - } - } - result.length = index; - return result; - } - }); - - -/***/ }), -/* 162 */ -/***/ (function(module, exports, __webpack_require__) { - - // call something on iterator step with safe closing on error - var anObject = __webpack_require__(12); - module.exports = function (iterator, fn, value, entries) { - try { - return entries ? fn(anObject(value)[0], value[1]) : fn(value); - // 7.4.6 IteratorClose(iterator, completion) - } catch (e) { - var ret = iterator['return']; - if (ret !== undefined) anObject(ret.call(iterator)); - throw e; - } - }; - - -/***/ }), -/* 163 */ -/***/ (function(module, exports, __webpack_require__) { - - // check on default Array iterator - var Iterators = __webpack_require__(129); - var ITERATOR = __webpack_require__(26)('iterator'); - var ArrayProto = Array.prototype; - - module.exports = function (it) { - return it !== undefined && (Iterators.Array === it || ArrayProto[ITERATOR] === it); - }; - - -/***/ }), -/* 164 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $defineProperty = __webpack_require__(11); - var createDesc = __webpack_require__(17); - - module.exports = function (object, index, value) { - if (index in object) $defineProperty.f(object, index, createDesc(0, value)); - else object[index] = value; - }; - - -/***/ }), -/* 165 */ -/***/ (function(module, exports, __webpack_require__) { - - var classof = __webpack_require__(74); - var ITERATOR = __webpack_require__(26)('iterator'); - var Iterators = __webpack_require__(129); - module.exports = __webpack_require__(9).getIteratorMethod = function (it) { - if (it != undefined) return it[ITERATOR] - || it['@@iterator'] - || Iterators[classof(it)]; - }; - - -/***/ }), -/* 166 */ -/***/ (function(module, exports, __webpack_require__) { - - var ITERATOR = __webpack_require__(26)('iterator'); - var SAFE_CLOSING = false; - - try { - var riter = [7][ITERATOR](); - riter['return'] = function () { SAFE_CLOSING = true; }; - // eslint-disable-next-line no-throw-literal - Array.from(riter, function () { throw 2; }); - } catch (e) { /* empty */ } - - module.exports = function (exec, skipClosing) { - if (!skipClosing && !SAFE_CLOSING) return false; - var safe = false; - try { - var arr = [7]; - var iter = arr[ITERATOR](); - iter.next = function () { return { done: safe = true }; }; - arr[ITERATOR] = function () { return iter; }; - exec(arr); - } catch (e) { /* empty */ } - return safe; - }; - - -/***/ }), -/* 167 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var createProperty = __webpack_require__(164); - - // WebKit Array.of isn't generic - $export($export.S + $export.F * __webpack_require__(7)(function () { - function F() { /* empty */ } - return !(Array.of.call(F) instanceof F); - }), 'Array', { - // 22.1.2.3 Array.of( ...items) - of: function of(/* ...args */) { - var index = 0; - var aLen = arguments.length; - var result = new (typeof this == 'function' ? this : Array)(aLen); - while (aLen > index) createProperty(result, index, arguments[index++]); - result.length = aLen; - return result; - } - }); - - -/***/ }), -/* 168 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // 22.1.3.13 Array.prototype.join(separator) - var $export = __webpack_require__(8); - var toIObject = __webpack_require__(32); - var arrayJoin = [].join; - - // fallback for not array-like strings - $export($export.P + $export.F * (__webpack_require__(33) != Object || !__webpack_require__(169)(arrayJoin)), 'Array', { - join: function join(separator) { - return arrayJoin.call(toIObject(this), separator === undefined ? ',' : separator); - } - }); - - -/***/ }), -/* 169 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var fails = __webpack_require__(7); - - module.exports = function (method, arg) { - return !!method && fails(function () { - // eslint-disable-next-line no-useless-call - arg ? method.call(null, function () { /* empty */ }, 1) : method.call(null); - }); - }; - - -/***/ }), -/* 170 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var html = __webpack_require__(47); - var cof = __webpack_require__(34); - var toAbsoluteIndex = __webpack_require__(39); - var toLength = __webpack_require__(37); - var arraySlice = [].slice; - - // fallback for not array-like ES3 strings and DOM objects - $export($export.P + $export.F * __webpack_require__(7)(function () { - if (html) arraySlice.call(html); - }), 'Array', { - slice: function slice(begin, end) { - var len = toLength(this.length); - var klass = cof(this); - end = end === undefined ? len : end; - if (klass == 'Array') return arraySlice.call(this, begin, end); - var start = toAbsoluteIndex(begin, len); - var upTo = toAbsoluteIndex(end, len); - var size = toLength(upTo - start); - var cloned = new Array(size); - var i = 0; - for (; i < size; i++) cloned[i] = klass == 'String' - ? this.charAt(start + i) - : this[start + i]; - return cloned; - } - }); - - -/***/ }), -/* 171 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var aFunction = __webpack_require__(21); - var toObject = __webpack_require__(57); - var fails = __webpack_require__(7); - var $sort = [].sort; - var test = [1, 2, 3]; - - $export($export.P + $export.F * (fails(function () { - // IE8- - test.sort(undefined); - }) || !fails(function () { - // V8 bug - test.sort(null); - // Old WebKit - }) || !__webpack_require__(169)($sort)), 'Array', { - // 22.1.3.25 Array.prototype.sort(comparefn) - sort: function sort(comparefn) { - return comparefn === undefined - ? $sort.call(toObject(this)) - : $sort.call(toObject(this), aFunction(comparefn)); - } - }); - - -/***/ }), -/* 172 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var $forEach = __webpack_require__(173)(0); - var STRICT = __webpack_require__(169)([].forEach, true); - - $export($export.P + $export.F * !STRICT, 'Array', { - // 22.1.3.10 / 15.4.4.18 Array.prototype.forEach(callbackfn [, thisArg]) - forEach: function forEach(callbackfn /* , thisArg */) { - return $forEach(this, callbackfn, arguments[1]); - } - }); - - -/***/ }), -/* 173 */ -/***/ (function(module, exports, __webpack_require__) { - - // 0 -> Array#forEach - // 1 -> Array#map - // 2 -> Array#filter - // 3 -> Array#some - // 4 -> Array#every - // 5 -> Array#find - // 6 -> Array#findIndex - var ctx = __webpack_require__(20); - var IObject = __webpack_require__(33); - var toObject = __webpack_require__(57); - var toLength = __webpack_require__(37); - var asc = __webpack_require__(174); - module.exports = function (TYPE, $create) { - var IS_MAP = TYPE == 1; - var IS_FILTER = TYPE == 2; - var IS_SOME = TYPE == 3; - var IS_EVERY = TYPE == 4; - var IS_FIND_INDEX = TYPE == 6; - var NO_HOLES = TYPE == 5 || IS_FIND_INDEX; - var create = $create || asc; - return function ($this, callbackfn, that) { - var O = toObject($this); - var self = IObject(O); - var f = ctx(callbackfn, that, 3); - var length = toLength(self.length); - var index = 0; - var result = IS_MAP ? create($this, length) : IS_FILTER ? create($this, 0) : undefined; - var val, res; - for (;length > index; index++) if (NO_HOLES || index in self) { - val = self[index]; - res = f(val, index, O); - if (TYPE) { - if (IS_MAP) result[index] = res; // map - else if (res) switch (TYPE) { - case 3: return true; // some - case 5: return val; // find - case 6: return index; // findIndex - case 2: result.push(val); // filter - } else if (IS_EVERY) return false; // every - } - } - return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : result; - }; - }; - - -/***/ }), -/* 174 */ -/***/ (function(module, exports, __webpack_require__) { - - // 9.4.2.3 ArraySpeciesCreate(originalArray, length) - var speciesConstructor = __webpack_require__(175); - - module.exports = function (original, length) { - return new (speciesConstructor(original))(length); - }; - - -/***/ }), -/* 175 */ -/***/ (function(module, exports, __webpack_require__) { - - var isObject = __webpack_require__(13); - var isArray = __webpack_require__(44); - var SPECIES = __webpack_require__(26)('species'); - - module.exports = function (original) { - var C; - if (isArray(original)) { - C = original.constructor; - // cross-realm fallback - if (typeof C == 'function' && (C === Array || isArray(C.prototype))) C = undefined; - if (isObject(C)) { - C = C[SPECIES]; - if (C === null) C = undefined; - } - } return C === undefined ? Array : C; - }; - - -/***/ }), -/* 176 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var $map = __webpack_require__(173)(1); - - $export($export.P + $export.F * !__webpack_require__(169)([].map, true), 'Array', { - // 22.1.3.15 / 15.4.4.19 Array.prototype.map(callbackfn [, thisArg]) - map: function map(callbackfn /* , thisArg */) { - return $map(this, callbackfn, arguments[1]); - } - }); - - -/***/ }), -/* 177 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var $filter = __webpack_require__(173)(2); - - $export($export.P + $export.F * !__webpack_require__(169)([].filter, true), 'Array', { - // 22.1.3.7 / 15.4.4.20 Array.prototype.filter(callbackfn [, thisArg]) - filter: function filter(callbackfn /* , thisArg */) { - return $filter(this, callbackfn, arguments[1]); - } - }); - - -/***/ }), -/* 178 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var $some = __webpack_require__(173)(3); - - $export($export.P + $export.F * !__webpack_require__(169)([].some, true), 'Array', { - // 22.1.3.23 / 15.4.4.17 Array.prototype.some(callbackfn [, thisArg]) - some: function some(callbackfn /* , thisArg */) { - return $some(this, callbackfn, arguments[1]); - } - }); - - -/***/ }), -/* 179 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var $every = __webpack_require__(173)(4); - - $export($export.P + $export.F * !__webpack_require__(169)([].every, true), 'Array', { - // 22.1.3.5 / 15.4.4.16 Array.prototype.every(callbackfn [, thisArg]) - every: function every(callbackfn /* , thisArg */) { - return $every(this, callbackfn, arguments[1]); - } - }); - - -/***/ }), -/* 180 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var $reduce = __webpack_require__(181); - - $export($export.P + $export.F * !__webpack_require__(169)([].reduce, true), 'Array', { - // 22.1.3.18 / 15.4.4.21 Array.prototype.reduce(callbackfn [, initialValue]) - reduce: function reduce(callbackfn /* , initialValue */) { - return $reduce(this, callbackfn, arguments.length, arguments[1], false); - } - }); - - -/***/ }), -/* 181 */ -/***/ (function(module, exports, __webpack_require__) { - - var aFunction = __webpack_require__(21); - var toObject = __webpack_require__(57); - var IObject = __webpack_require__(33); - var toLength = __webpack_require__(37); - - module.exports = function (that, callbackfn, aLen, memo, isRight) { - aFunction(callbackfn); - var O = toObject(that); - var self = IObject(O); - var length = toLength(O.length); - var index = isRight ? length - 1 : 0; - var i = isRight ? -1 : 1; - if (aLen < 2) for (;;) { - if (index in self) { - memo = self[index]; - index += i; - break; - } - index += i; - if (isRight ? index < 0 : length <= index) { - throw TypeError('Reduce of empty array with no initial value'); - } - } - for (;isRight ? index >= 0 : length > index; index += i) if (index in self) { - memo = callbackfn(memo, self[index], index, O); - } - return memo; - }; - - -/***/ }), -/* 182 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var $reduce = __webpack_require__(181); - - $export($export.P + $export.F * !__webpack_require__(169)([].reduceRight, true), 'Array', { - // 22.1.3.19 / 15.4.4.22 Array.prototype.reduceRight(callbackfn [, initialValue]) - reduceRight: function reduceRight(callbackfn /* , initialValue */) { - return $reduce(this, callbackfn, arguments.length, arguments[1], true); - } - }); - - -/***/ }), -/* 183 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var $indexOf = __webpack_require__(36)(false); - var $native = [].indexOf; - var NEGATIVE_ZERO = !!$native && 1 / [1].indexOf(1, -0) < 0; - - $export($export.P + $export.F * (NEGATIVE_ZERO || !__webpack_require__(169)($native)), 'Array', { - // 22.1.3.11 / 15.4.4.14 Array.prototype.indexOf(searchElement [, fromIndex]) - indexOf: function indexOf(searchElement /* , fromIndex = 0 */) { - return NEGATIVE_ZERO - // convert -0 to +0 - ? $native.apply(this, arguments) || 0 - : $indexOf(this, searchElement, arguments[1]); - } - }); - - -/***/ }), -/* 184 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var toIObject = __webpack_require__(32); - var toInteger = __webpack_require__(38); - var toLength = __webpack_require__(37); - var $native = [].lastIndexOf; - var NEGATIVE_ZERO = !!$native && 1 / [1].lastIndexOf(1, -0) < 0; - - $export($export.P + $export.F * (NEGATIVE_ZERO || !__webpack_require__(169)($native)), 'Array', { - // 22.1.3.14 / 15.4.4.15 Array.prototype.lastIndexOf(searchElement [, fromIndex]) - lastIndexOf: function lastIndexOf(searchElement /* , fromIndex = @[*-1] */) { - // convert -0 to +0 - if (NEGATIVE_ZERO) return $native.apply(this, arguments) || 0; - var O = toIObject(this); - var length = toLength(O.length); - var index = length - 1; - if (arguments.length > 1) index = Math.min(index, toInteger(arguments[1])); - if (index < 0) index = length + index; - for (;index >= 0; index--) if (index in O) if (O[index] === searchElement) return index || 0; - return -1; - } - }); - - -/***/ }), -/* 185 */ -/***/ (function(module, exports, __webpack_require__) { - - // 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length) - var $export = __webpack_require__(8); - - $export($export.P, 'Array', { copyWithin: __webpack_require__(186) }); - - __webpack_require__(187)('copyWithin'); - - -/***/ }), -/* 186 */ -/***/ (function(module, exports, __webpack_require__) { - - // 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length) - 'use strict'; - var toObject = __webpack_require__(57); - var toAbsoluteIndex = __webpack_require__(39); - var toLength = __webpack_require__(37); - - module.exports = [].copyWithin || function copyWithin(target /* = 0 */, start /* = 0, end = @length */) { - var O = toObject(this); - var len = toLength(O.length); - var to = toAbsoluteIndex(target, len); - var from = toAbsoluteIndex(start, len); - var end = arguments.length > 2 ? arguments[2] : undefined; - var count = Math.min((end === undefined ? len : toAbsoluteIndex(end, len)) - from, len - to); - var inc = 1; - if (from < to && to < from + count) { - inc = -1; - from += count - 1; - to += count - 1; - } - while (count-- > 0) { - if (from in O) O[to] = O[from]; - else delete O[to]; - to += inc; - from += inc; - } return O; - }; - - -/***/ }), -/* 187 */ -/***/ (function(module, exports, __webpack_require__) { - - // 22.1.3.31 Array.prototype[@@unscopables] - var UNSCOPABLES = __webpack_require__(26)('unscopables'); - var ArrayProto = Array.prototype; - if (ArrayProto[UNSCOPABLES] == undefined) __webpack_require__(10)(ArrayProto, UNSCOPABLES, {}); - module.exports = function (key) { - ArrayProto[UNSCOPABLES][key] = true; - }; - - -/***/ }), -/* 188 */ -/***/ (function(module, exports, __webpack_require__) { - - // 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length) - var $export = __webpack_require__(8); - - $export($export.P, 'Array', { fill: __webpack_require__(189) }); - - __webpack_require__(187)('fill'); - - -/***/ }), -/* 189 */ -/***/ (function(module, exports, __webpack_require__) { - - // 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length) - 'use strict'; - var toObject = __webpack_require__(57); - var toAbsoluteIndex = __webpack_require__(39); - var toLength = __webpack_require__(37); - module.exports = function fill(value /* , start = 0, end = @length */) { - var O = toObject(this); - var length = toLength(O.length); - var aLen = arguments.length; - var index = toAbsoluteIndex(aLen > 1 ? arguments[1] : undefined, length); - var end = aLen > 2 ? arguments[2] : undefined; - var endPos = end === undefined ? length : toAbsoluteIndex(end, length); - while (endPos > index) O[index++] = value; - return O; - }; - - -/***/ }), -/* 190 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // 22.1.3.8 Array.prototype.find(predicate, thisArg = undefined) - var $export = __webpack_require__(8); - var $find = __webpack_require__(173)(5); - var KEY = 'find'; - var forced = true; - // Shouldn't skip holes - if (KEY in []) Array(1)[KEY](function () { forced = false; }); - $export($export.P + $export.F * forced, 'Array', { - find: function find(callbackfn /* , that = undefined */) { - return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); - } - }); - __webpack_require__(187)(KEY); - - -/***/ }), -/* 191 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // 22.1.3.9 Array.prototype.findIndex(predicate, thisArg = undefined) - var $export = __webpack_require__(8); - var $find = __webpack_require__(173)(6); - var KEY = 'findIndex'; - var forced = true; - // Shouldn't skip holes - if (KEY in []) Array(1)[KEY](function () { forced = false; }); - $export($export.P + $export.F * forced, 'Array', { - findIndex: function findIndex(callbackfn /* , that = undefined */) { - return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); - } - }); - __webpack_require__(187)(KEY); - - -/***/ }), -/* 192 */ -/***/ (function(module, exports, __webpack_require__) { - - __webpack_require__(193)('Array'); - - -/***/ }), -/* 193 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var global = __webpack_require__(4); - var dP = __webpack_require__(11); - var DESCRIPTORS = __webpack_require__(6); - var SPECIES = __webpack_require__(26)('species'); - - module.exports = function (KEY) { - var C = global[KEY]; - if (DESCRIPTORS && C && !C[SPECIES]) dP.f(C, SPECIES, { - configurable: true, - get: function () { return this; } - }); - }; - - -/***/ }), -/* 194 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var addToUnscopables = __webpack_require__(187); - var step = __webpack_require__(195); - var Iterators = __webpack_require__(129); - var toIObject = __webpack_require__(32); - - // 22.1.3.4 Array.prototype.entries() - // 22.1.3.13 Array.prototype.keys() - // 22.1.3.29 Array.prototype.values() - // 22.1.3.30 Array.prototype[@@iterator]() - module.exports = __webpack_require__(128)(Array, 'Array', function (iterated, kind) { - this._t = toIObject(iterated); // target - this._i = 0; // next index - this._k = kind; // kind - // 22.1.5.2.1 %ArrayIteratorPrototype%.next() - }, function () { - var O = this._t; - var kind = this._k; - var index = this._i++; - if (!O || index >= O.length) { - this._t = undefined; - return step(1); - } - if (kind == 'keys') return step(0, index); - if (kind == 'values') return step(0, O[index]); - return step(0, [index, O[index]]); - }, 'values'); - - // argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7) - Iterators.Arguments = Iterators.Array; - - addToUnscopables('keys'); - addToUnscopables('values'); - addToUnscopables('entries'); - - -/***/ }), -/* 195 */ -/***/ (function(module, exports) { - - module.exports = function (done, value) { - return { value: value, done: !!done }; - }; - - -/***/ }), -/* 196 */ -/***/ (function(module, exports, __webpack_require__) { - - var global = __webpack_require__(4); - var inheritIfRequired = __webpack_require__(87); - var dP = __webpack_require__(11).f; - var gOPN = __webpack_require__(49).f; - var isRegExp = __webpack_require__(134); - var $flags = __webpack_require__(197); - var $RegExp = global.RegExp; - var Base = $RegExp; - var proto = $RegExp.prototype; - var re1 = /a/g; - var re2 = /a/g; - // "new" creates a new object, old webkit buggy here - var CORRECT_NEW = new $RegExp(re1) !== re1; - - if (__webpack_require__(6) && (!CORRECT_NEW || __webpack_require__(7)(function () { - re2[__webpack_require__(26)('match')] = false; - // RegExp constructor can alter flags and IsRegExp works correct with @@match - return $RegExp(re1) != re1 || $RegExp(re2) == re2 || $RegExp(re1, 'i') != '/a/i'; - }))) { - $RegExp = function RegExp(p, f) { - var tiRE = this instanceof $RegExp; - var piRE = isRegExp(p); - var fiU = f === undefined; - return !tiRE && piRE && p.constructor === $RegExp && fiU ? p - : inheritIfRequired(CORRECT_NEW - ? new Base(piRE && !fiU ? p.source : p, f) - : Base((piRE = p instanceof $RegExp) ? p.source : p, piRE && fiU ? $flags.call(p) : f) - , tiRE ? this : proto, $RegExp); - }; - var proxy = function (key) { - key in $RegExp || dP($RegExp, key, { - configurable: true, - get: function () { return Base[key]; }, - set: function (it) { Base[key] = it; } - }); - }; - for (var keys = gOPN(Base), i = 0; keys.length > i;) proxy(keys[i++]); - proto.constructor = $RegExp; - $RegExp.prototype = proto; - __webpack_require__(18)(global, 'RegExp', $RegExp); - } - - __webpack_require__(193)('RegExp'); - - -/***/ }), -/* 197 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // 21.2.5.3 get RegExp.prototype.flags - var anObject = __webpack_require__(12); - module.exports = function () { - var that = anObject(this); - var result = ''; - if (that.global) result += 'g'; - if (that.ignoreCase) result += 'i'; - if (that.multiline) result += 'm'; - if (that.unicode) result += 'u'; - if (that.sticky) result += 'y'; - return result; - }; - - -/***/ }), -/* 198 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - __webpack_require__(199); - var anObject = __webpack_require__(12); - var $flags = __webpack_require__(197); - var DESCRIPTORS = __webpack_require__(6); - var TO_STRING = 'toString'; - var $toString = /./[TO_STRING]; - - var define = function (fn) { - __webpack_require__(18)(RegExp.prototype, TO_STRING, fn, true); - }; - - // 21.2.5.14 RegExp.prototype.toString() - if (__webpack_require__(7)(function () { return $toString.call({ source: 'a', flags: 'b' }) != '/a/b'; })) { - define(function toString() { - var R = anObject(this); - return '/'.concat(R.source, '/', - 'flags' in R ? R.flags : !DESCRIPTORS && R instanceof RegExp ? $flags.call(R) : undefined); - }); - // FF44- RegExp#toString has a wrong name - } else if ($toString.name != TO_STRING) { - define(function toString() { - return $toString.call(this); - }); - } - - -/***/ }), -/* 199 */ -/***/ (function(module, exports, __webpack_require__) { - - // 21.2.5.3 get RegExp.prototype.flags() - if (__webpack_require__(6) && /./g.flags != 'g') __webpack_require__(11).f(RegExp.prototype, 'flags', { - configurable: true, - get: __webpack_require__(197) - }); - - -/***/ }), -/* 200 */ -/***/ (function(module, exports, __webpack_require__) { - - // @@match logic - __webpack_require__(201)('match', 1, function (defined, MATCH, $match) { - // 21.1.3.11 String.prototype.match(regexp) - return [function match(regexp) { - 'use strict'; - var O = defined(this); - var fn = regexp == undefined ? undefined : regexp[MATCH]; - return fn !== undefined ? fn.call(regexp, O) : new RegExp(regexp)[MATCH](String(O)); - }, $match]; - }); - - -/***/ }), -/* 201 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var hide = __webpack_require__(10); - var redefine = __webpack_require__(18); - var fails = __webpack_require__(7); - var defined = __webpack_require__(35); - var wks = __webpack_require__(26); - - module.exports = function (KEY, length, exec) { - var SYMBOL = wks(KEY); - var fns = exec(defined, SYMBOL, ''[KEY]); - var strfn = fns[0]; - var rxfn = fns[1]; - if (fails(function () { - var O = {}; - O[SYMBOL] = function () { return 7; }; - return ''[KEY](O) != 7; - })) { - redefine(String.prototype, KEY, strfn); - hide(RegExp.prototype, SYMBOL, length == 2 - // 21.2.5.8 RegExp.prototype[@@replace](string, replaceValue) - // 21.2.5.11 RegExp.prototype[@@split](string, limit) - ? function (string, arg) { return rxfn.call(string, this, arg); } - // 21.2.5.6 RegExp.prototype[@@match](string) - // 21.2.5.9 RegExp.prototype[@@search](string) - : function (string) { return rxfn.call(string, this); } - ); - } - }; - - -/***/ }), -/* 202 */ -/***/ (function(module, exports, __webpack_require__) { - - // @@replace logic - __webpack_require__(201)('replace', 2, function (defined, REPLACE, $replace) { - // 21.1.3.14 String.prototype.replace(searchValue, replaceValue) - return [function replace(searchValue, replaceValue) { - 'use strict'; - var O = defined(this); - var fn = searchValue == undefined ? undefined : searchValue[REPLACE]; - return fn !== undefined - ? fn.call(searchValue, O, replaceValue) - : $replace.call(String(O), searchValue, replaceValue); - }, $replace]; - }); - - -/***/ }), -/* 203 */ -/***/ (function(module, exports, __webpack_require__) { - - // @@search logic - __webpack_require__(201)('search', 1, function (defined, SEARCH, $search) { - // 21.1.3.15 String.prototype.search(regexp) - return [function search(regexp) { - 'use strict'; - var O = defined(this); - var fn = regexp == undefined ? undefined : regexp[SEARCH]; - return fn !== undefined ? fn.call(regexp, O) : new RegExp(regexp)[SEARCH](String(O)); - }, $search]; - }); - - -/***/ }), -/* 204 */ -/***/ (function(module, exports, __webpack_require__) { - - // @@split logic - __webpack_require__(201)('split', 2, function (defined, SPLIT, $split) { - 'use strict'; - var isRegExp = __webpack_require__(134); - var _split = $split; - var $push = [].push; - var $SPLIT = 'split'; - var LENGTH = 'length'; - var LAST_INDEX = 'lastIndex'; - if ( - 'abbc'[$SPLIT](/(b)*/)[1] == 'c' || - 'test'[$SPLIT](/(?:)/, -1)[LENGTH] != 4 || - 'ab'[$SPLIT](/(?:ab)*/)[LENGTH] != 2 || - '.'[$SPLIT](/(.?)(.?)/)[LENGTH] != 4 || - '.'[$SPLIT](/()()/)[LENGTH] > 1 || - ''[$SPLIT](/.?/)[LENGTH] - ) { - var NPCG = /()??/.exec('')[1] === undefined; // nonparticipating capturing group - // based on es5-shim implementation, need to rework it - $split = function (separator, limit) { - var string = String(this); - if (separator === undefined && limit === 0) return []; - // If `separator` is not a regex, use native split - if (!isRegExp(separator)) return _split.call(string, separator, limit); - var output = []; - var flags = (separator.ignoreCase ? 'i' : '') + - (separator.multiline ? 'm' : '') + - (separator.unicode ? 'u' : '') + - (separator.sticky ? 'y' : ''); - var lastLastIndex = 0; - var splitLimit = limit === undefined ? 4294967295 : limit >>> 0; - // Make `global` and avoid `lastIndex` issues by working with a copy - var separatorCopy = new RegExp(separator.source, flags + 'g'); - var separator2, match, lastIndex, lastLength, i; - // Doesn't need flags gy, but they don't hurt - if (!NPCG) separator2 = new RegExp('^' + separatorCopy.source + '$(?!\\s)', flags); - while (match = separatorCopy.exec(string)) { - // `separatorCopy.lastIndex` is not reliable cross-browser - lastIndex = match.index + match[0][LENGTH]; - if (lastIndex > lastLastIndex) { - output.push(string.slice(lastLastIndex, match.index)); - // Fix browsers whose `exec` methods don't consistently return `undefined` for NPCG - // eslint-disable-next-line no-loop-func - if (!NPCG && match[LENGTH] > 1) match[0].replace(separator2, function () { - for (i = 1; i < arguments[LENGTH] - 2; i++) if (arguments[i] === undefined) match[i] = undefined; - }); - if (match[LENGTH] > 1 && match.index < string[LENGTH]) $push.apply(output, match.slice(1)); - lastLength = match[0][LENGTH]; - lastLastIndex = lastIndex; - if (output[LENGTH] >= splitLimit) break; - } - if (separatorCopy[LAST_INDEX] === match.index) separatorCopy[LAST_INDEX]++; // Avoid an infinite loop - } - if (lastLastIndex === string[LENGTH]) { - if (lastLength || !separatorCopy.test('')) output.push(''); - } else output.push(string.slice(lastLastIndex)); - return output[LENGTH] > splitLimit ? output.slice(0, splitLimit) : output; - }; - // Chakra, V8 - } else if ('0'[$SPLIT](undefined, 0)[LENGTH]) { - $split = function (separator, limit) { - return separator === undefined && limit === 0 ? [] : _split.call(this, separator, limit); - }; - } - // 21.1.3.17 String.prototype.split(separator, limit) - return [function split(separator, limit) { - var O = defined(this); - var fn = separator == undefined ? undefined : separator[SPLIT]; - return fn !== undefined ? fn.call(separator, O, limit) : $split.call(String(O), separator, limit); - }, $split]; - }); - - -/***/ }), -/* 205 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var LIBRARY = __webpack_require__(24); - var global = __webpack_require__(4); - var ctx = __webpack_require__(20); - var classof = __webpack_require__(74); - var $export = __webpack_require__(8); - var isObject = __webpack_require__(13); - var aFunction = __webpack_require__(21); - var anInstance = __webpack_require__(206); - var forOf = __webpack_require__(207); - var speciesConstructor = __webpack_require__(208); - var task = __webpack_require__(209).set; - var microtask = __webpack_require__(210)(); - var newPromiseCapabilityModule = __webpack_require__(211); - var perform = __webpack_require__(212); - var userAgent = __webpack_require__(213); - var promiseResolve = __webpack_require__(214); - var PROMISE = 'Promise'; - var TypeError = global.TypeError; - var process = global.process; - var versions = process && process.versions; - var v8 = versions && versions.v8 || ''; - var $Promise = global[PROMISE]; - var isNode = classof(process) == 'process'; - var empty = function () { /* empty */ }; - var Internal, newGenericPromiseCapability, OwnPromiseCapability, Wrapper; - var newPromiseCapability = newGenericPromiseCapability = newPromiseCapabilityModule.f; - - var USE_NATIVE = !!function () { - try { - // correct subclassing with @@species support - var promise = $Promise.resolve(1); - var FakePromise = (promise.constructor = {})[__webpack_require__(26)('species')] = function (exec) { - exec(empty, empty); - }; - // unhandled rejections tracking support, NodeJS Promise without it fails @@species test - return (isNode || typeof PromiseRejectionEvent == 'function') - && promise.then(empty) instanceof FakePromise - // v8 6.6 (Node 10 and Chrome 66) have a bug with resolving custom thenables - // https://bugs.chromium.org/p/chromium/issues/detail?id=830565 - // we can't detect it synchronously, so just check versions - && v8.indexOf('6.6') !== 0 - && userAgent.indexOf('Chrome/66') === -1; - } catch (e) { /* empty */ } - }(); - - // helpers - var isThenable = function (it) { - var then; - return isObject(it) && typeof (then = it.then) == 'function' ? then : false; - }; - var notify = function (promise, isReject) { - if (promise._n) return; - promise._n = true; - var chain = promise._c; - microtask(function () { - var value = promise._v; - var ok = promise._s == 1; - var i = 0; - var run = function (reaction) { - var handler = ok ? reaction.ok : reaction.fail; - var resolve = reaction.resolve; - var reject = reaction.reject; - var domain = reaction.domain; - var result, then, exited; - try { - if (handler) { - if (!ok) { - if (promise._h == 2) onHandleUnhandled(promise); - promise._h = 1; - } - if (handler === true) result = value; - else { - if (domain) domain.enter(); - result = handler(value); // may throw - if (domain) { - domain.exit(); - exited = true; - } - } - if (result === reaction.promise) { - reject(TypeError('Promise-chain cycle')); - } else if (then = isThenable(result)) { - then.call(result, resolve, reject); - } else resolve(result); - } else reject(value); - } catch (e) { - if (domain && !exited) domain.exit(); - reject(e); - } - }; - while (chain.length > i) run(chain[i++]); // variable length - can't use forEach - promise._c = []; - promise._n = false; - if (isReject && !promise._h) onUnhandled(promise); - }); - }; - var onUnhandled = function (promise) { - task.call(global, function () { - var value = promise._v; - var unhandled = isUnhandled(promise); - var result, handler, console; - if (unhandled) { - result = perform(function () { - if (isNode) { - process.emit('unhandledRejection', value, promise); - } else if (handler = global.onunhandledrejection) { - handler({ promise: promise, reason: value }); - } else if ((console = global.console) && console.error) { - console.error('Unhandled promise rejection', value); - } - }); - // Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should - promise._h = isNode || isUnhandled(promise) ? 2 : 1; - } promise._a = undefined; - if (unhandled && result.e) throw result.v; - }); - }; - var isUnhandled = function (promise) { - return promise._h !== 1 && (promise._a || promise._c).length === 0; - }; - var onHandleUnhandled = function (promise) { - task.call(global, function () { - var handler; - if (isNode) { - process.emit('rejectionHandled', promise); - } else if (handler = global.onrejectionhandled) { - handler({ promise: promise, reason: promise._v }); - } - }); - }; - var $reject = function (value) { - var promise = this; - if (promise._d) return; - promise._d = true; - promise = promise._w || promise; // unwrap - promise._v = value; - promise._s = 2; - if (!promise._a) promise._a = promise._c.slice(); - notify(promise, true); - }; - var $resolve = function (value) { - var promise = this; - var then; - if (promise._d) return; - promise._d = true; - promise = promise._w || promise; // unwrap - try { - if (promise === value) throw TypeError("Promise can't be resolved itself"); - if (then = isThenable(value)) { - microtask(function () { - var wrapper = { _w: promise, _d: false }; // wrap - try { - then.call(value, ctx($resolve, wrapper, 1), ctx($reject, wrapper, 1)); - } catch (e) { - $reject.call(wrapper, e); - } - }); - } else { - promise._v = value; - promise._s = 1; - notify(promise, false); - } - } catch (e) { - $reject.call({ _w: promise, _d: false }, e); // wrap - } - }; - - // constructor polyfill - if (!USE_NATIVE) { - // 25.4.3.1 Promise(executor) - $Promise = function Promise(executor) { - anInstance(this, $Promise, PROMISE, '_h'); - aFunction(executor); - Internal.call(this); - try { - executor(ctx($resolve, this, 1), ctx($reject, this, 1)); - } catch (err) { - $reject.call(this, err); - } - }; - // eslint-disable-next-line no-unused-vars - Internal = function Promise(executor) { - this._c = []; // <- awaiting reactions - this._a = undefined; // <- checked in isUnhandled reactions - this._s = 0; // <- state - this._d = false; // <- done - this._v = undefined; // <- value - this._h = 0; // <- rejection state, 0 - default, 1 - handled, 2 - unhandled - this._n = false; // <- notify - }; - Internal.prototype = __webpack_require__(215)($Promise.prototype, { - // 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected) - then: function then(onFulfilled, onRejected) { - var reaction = newPromiseCapability(speciesConstructor(this, $Promise)); - reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true; - reaction.fail = typeof onRejected == 'function' && onRejected; - reaction.domain = isNode ? process.domain : undefined; - this._c.push(reaction); - if (this._a) this._a.push(reaction); - if (this._s) notify(this, false); - return reaction.promise; - }, - // 25.4.5.1 Promise.prototype.catch(onRejected) - 'catch': function (onRejected) { - return this.then(undefined, onRejected); - } - }); - OwnPromiseCapability = function () { - var promise = new Internal(); - this.promise = promise; - this.resolve = ctx($resolve, promise, 1); - this.reject = ctx($reject, promise, 1); - }; - newPromiseCapabilityModule.f = newPromiseCapability = function (C) { - return C === $Promise || C === Wrapper - ? new OwnPromiseCapability(C) - : newGenericPromiseCapability(C); - }; - } - - $export($export.G + $export.W + $export.F * !USE_NATIVE, { Promise: $Promise }); - __webpack_require__(25)($Promise, PROMISE); - __webpack_require__(193)(PROMISE); - Wrapper = __webpack_require__(9)[PROMISE]; - - // statics - $export($export.S + $export.F * !USE_NATIVE, PROMISE, { - // 25.4.4.5 Promise.reject(r) - reject: function reject(r) { - var capability = newPromiseCapability(this); - var $$reject = capability.reject; - $$reject(r); - return capability.promise; - } - }); - $export($export.S + $export.F * (LIBRARY || !USE_NATIVE), PROMISE, { - // 25.4.4.6 Promise.resolve(x) - resolve: function resolve(x) { - return promiseResolve(LIBRARY && this === Wrapper ? $Promise : this, x); - } - }); - $export($export.S + $export.F * !(USE_NATIVE && __webpack_require__(166)(function (iter) { - $Promise.all(iter)['catch'](empty); - })), PROMISE, { - // 25.4.4.1 Promise.all(iterable) - all: function all(iterable) { - var C = this; - var capability = newPromiseCapability(C); - var resolve = capability.resolve; - var reject = capability.reject; - var result = perform(function () { - var values = []; - var index = 0; - var remaining = 1; - forOf(iterable, false, function (promise) { - var $index = index++; - var alreadyCalled = false; - values.push(undefined); - remaining++; - C.resolve(promise).then(function (value) { - if (alreadyCalled) return; - alreadyCalled = true; - values[$index] = value; - --remaining || resolve(values); - }, reject); - }); - --remaining || resolve(values); - }); - if (result.e) reject(result.v); - return capability.promise; - }, - // 25.4.4.4 Promise.race(iterable) - race: function race(iterable) { - var C = this; - var capability = newPromiseCapability(C); - var reject = capability.reject; - var result = perform(function () { - forOf(iterable, false, function (promise) { - C.resolve(promise).then(capability.resolve, reject); - }); - }); - if (result.e) reject(result.v); - return capability.promise; - } - }); - - -/***/ }), -/* 206 */ -/***/ (function(module, exports) { - - module.exports = function (it, Constructor, name, forbiddenField) { - if (!(it instanceof Constructor) || (forbiddenField !== undefined && forbiddenField in it)) { - throw TypeError(name + ': incorrect invocation!'); - } return it; - }; - - -/***/ }), -/* 207 */ -/***/ (function(module, exports, __webpack_require__) { - - var ctx = __webpack_require__(20); - var call = __webpack_require__(162); - var isArrayIter = __webpack_require__(163); - var anObject = __webpack_require__(12); - var toLength = __webpack_require__(37); - var getIterFn = __webpack_require__(165); - var BREAK = {}; - var RETURN = {}; - var exports = module.exports = function (iterable, entries, fn, that, ITERATOR) { - var iterFn = ITERATOR ? function () { return iterable; } : getIterFn(iterable); - var f = ctx(fn, that, entries ? 2 : 1); - var index = 0; - var length, step, iterator, result; - if (typeof iterFn != 'function') throw TypeError(iterable + ' is not iterable!'); - // fast case for arrays with default iterator - if (isArrayIter(iterFn)) for (length = toLength(iterable.length); length > index; index++) { - result = entries ? f(anObject(step = iterable[index])[0], step[1]) : f(iterable[index]); - if (result === BREAK || result === RETURN) return result; - } else for (iterator = iterFn.call(iterable); !(step = iterator.next()).done;) { - result = call(iterator, f, step.value, entries); - if (result === BREAK || result === RETURN) return result; - } - }; - exports.BREAK = BREAK; - exports.RETURN = RETURN; - - -/***/ }), -/* 208 */ -/***/ (function(module, exports, __webpack_require__) { - - // 7.3.20 SpeciesConstructor(O, defaultConstructor) - var anObject = __webpack_require__(12); - var aFunction = __webpack_require__(21); - var SPECIES = __webpack_require__(26)('species'); - module.exports = function (O, D) { - var C = anObject(O).constructor; - var S; - return C === undefined || (S = anObject(C)[SPECIES]) == undefined ? D : aFunction(S); - }; - - -/***/ }), -/* 209 */ -/***/ (function(module, exports, __webpack_require__) { - - var ctx = __webpack_require__(20); - var invoke = __webpack_require__(77); - var html = __webpack_require__(47); - var cel = __webpack_require__(15); - var global = __webpack_require__(4); - var process = global.process; - var setTask = global.setImmediate; - var clearTask = global.clearImmediate; - var MessageChannel = global.MessageChannel; - var Dispatch = global.Dispatch; - var counter = 0; - var queue = {}; - var ONREADYSTATECHANGE = 'onreadystatechange'; - var defer, channel, port; - var run = function () { - var id = +this; - // eslint-disable-next-line no-prototype-builtins - if (queue.hasOwnProperty(id)) { - var fn = queue[id]; - delete queue[id]; - fn(); - } - }; - var listener = function (event) { - run.call(event.data); - }; - // Node.js 0.9+ & IE10+ has setImmediate, otherwise: - if (!setTask || !clearTask) { - setTask = function setImmediate(fn) { - var args = []; - var i = 1; - while (arguments.length > i) args.push(arguments[i++]); - queue[++counter] = function () { - // eslint-disable-next-line no-new-func - invoke(typeof fn == 'function' ? fn : Function(fn), args); - }; - defer(counter); - return counter; - }; - clearTask = function clearImmediate(id) { - delete queue[id]; - }; - // Node.js 0.8- - if (__webpack_require__(34)(process) == 'process') { - defer = function (id) { - process.nextTick(ctx(run, id, 1)); - }; - // Sphere (JS game engine) Dispatch API - } else if (Dispatch && Dispatch.now) { - defer = function (id) { - Dispatch.now(ctx(run, id, 1)); - }; - // Browsers with MessageChannel, includes WebWorkers - } else if (MessageChannel) { - channel = new MessageChannel(); - port = channel.port2; - channel.port1.onmessage = listener; - defer = ctx(port.postMessage, port, 1); - // Browsers with postMessage, skip WebWorkers - // IE8 has postMessage, but it's sync & typeof its postMessage is 'object' - } else if (global.addEventListener && typeof postMessage == 'function' && !global.importScripts) { - defer = function (id) { - global.postMessage(id + '', '*'); - }; - global.addEventListener('message', listener, false); - // IE8- - } else if (ONREADYSTATECHANGE in cel('script')) { - defer = function (id) { - html.appendChild(cel('script'))[ONREADYSTATECHANGE] = function () { - html.removeChild(this); - run.call(id); - }; - }; - // Rest old browsers - } else { - defer = function (id) { - setTimeout(ctx(run, id, 1), 0); - }; - } - } - module.exports = { - set: setTask, - clear: clearTask - }; - - -/***/ }), -/* 210 */ -/***/ (function(module, exports, __webpack_require__) { - - var global = __webpack_require__(4); - var macrotask = __webpack_require__(209).set; - var Observer = global.MutationObserver || global.WebKitMutationObserver; - var process = global.process; - var Promise = global.Promise; - var isNode = __webpack_require__(34)(process) == 'process'; - - module.exports = function () { - var head, last, notify; - - var flush = function () { - var parent, fn; - if (isNode && (parent = process.domain)) parent.exit(); - while (head) { - fn = head.fn; - head = head.next; - try { - fn(); - } catch (e) { - if (head) notify(); - else last = undefined; - throw e; - } - } last = undefined; - if (parent) parent.enter(); - }; - - // Node.js - if (isNode) { - notify = function () { - process.nextTick(flush); - }; - // browsers with MutationObserver, except iOS Safari - https://github.com/zloirock/core-js/issues/339 - } else if (Observer && !(global.navigator && global.navigator.standalone)) { - var toggle = true; - var node = document.createTextNode(''); - new Observer(flush).observe(node, { characterData: true }); // eslint-disable-line no-new - notify = function () { - node.data = toggle = !toggle; - }; - // environments with maybe non-completely correct, but existent Promise - } else if (Promise && Promise.resolve) { - // Promise.resolve without an argument throws an error in LG WebOS 2 - var promise = Promise.resolve(undefined); - notify = function () { - promise.then(flush); - }; - // for other environments - macrotask based on: - // - setImmediate - // - MessageChannel - // - window.postMessag - // - onreadystatechange - // - setTimeout - } else { - notify = function () { - // strange IE + webpack dev server bug - use .call(global) - macrotask.call(global, flush); - }; - } - - return function (fn) { - var task = { fn: fn, next: undefined }; - if (last) last.next = task; - if (!head) { - head = task; - notify(); - } last = task; - }; - }; - - -/***/ }), -/* 211 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // 25.4.1.5 NewPromiseCapability(C) - var aFunction = __webpack_require__(21); - - function PromiseCapability(C) { - var resolve, reject; - this.promise = new C(function ($$resolve, $$reject) { - if (resolve !== undefined || reject !== undefined) throw TypeError('Bad Promise constructor'); - resolve = $$resolve; - reject = $$reject; - }); - this.resolve = aFunction(resolve); - this.reject = aFunction(reject); - } - - module.exports.f = function (C) { - return new PromiseCapability(C); - }; - - -/***/ }), -/* 212 */ -/***/ (function(module, exports) { - - module.exports = function (exec) { - try { - return { e: false, v: exec() }; - } catch (e) { - return { e: true, v: e }; - } - }; - - -/***/ }), -/* 213 */ -/***/ (function(module, exports, __webpack_require__) { - - var global = __webpack_require__(4); - var navigator = global.navigator; - - module.exports = navigator && navigator.userAgent || ''; - - -/***/ }), -/* 214 */ -/***/ (function(module, exports, __webpack_require__) { - - var anObject = __webpack_require__(12); - var isObject = __webpack_require__(13); - var newPromiseCapability = __webpack_require__(211); - - module.exports = function (C, x) { - anObject(C); - if (isObject(x) && x.constructor === C) return x; - var promiseCapability = newPromiseCapability.f(C); - var resolve = promiseCapability.resolve; - resolve(x); - return promiseCapability.promise; - }; - - -/***/ }), -/* 215 */ -/***/ (function(module, exports, __webpack_require__) { - - var redefine = __webpack_require__(18); - module.exports = function (target, src, safe) { - for (var key in src) redefine(target, key, src[key], safe); - return target; - }; - - -/***/ }), -/* 216 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var strong = __webpack_require__(217); - var validate = __webpack_require__(218); - var MAP = 'Map'; - - // 23.1 Map Objects - module.exports = __webpack_require__(219)(MAP, function (get) { - return function Map() { return get(this, arguments.length > 0 ? arguments[0] : undefined); }; - }, { - // 23.1.3.6 Map.prototype.get(key) - get: function get(key) { - var entry = strong.getEntry(validate(this, MAP), key); - return entry && entry.v; - }, - // 23.1.3.9 Map.prototype.set(key, value) - set: function set(key, value) { - return strong.def(validate(this, MAP), key === 0 ? 0 : key, value); - } - }, strong, true); - - -/***/ }), -/* 217 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var dP = __webpack_require__(11).f; - var create = __webpack_require__(45); - var redefineAll = __webpack_require__(215); - var ctx = __webpack_require__(20); - var anInstance = __webpack_require__(206); - var forOf = __webpack_require__(207); - var $iterDefine = __webpack_require__(128); - var step = __webpack_require__(195); - var setSpecies = __webpack_require__(193); - var DESCRIPTORS = __webpack_require__(6); - var fastKey = __webpack_require__(22).fastKey; - var validate = __webpack_require__(218); - var SIZE = DESCRIPTORS ? '_s' : 'size'; - - var getEntry = function (that, key) { - // fast case - var index = fastKey(key); - var entry; - if (index !== 'F') return that._i[index]; - // frozen object case - for (entry = that._f; entry; entry = entry.n) { - if (entry.k == key) return entry; - } - }; - - module.exports = { - getConstructor: function (wrapper, NAME, IS_MAP, ADDER) { - var C = wrapper(function (that, iterable) { - anInstance(that, C, NAME, '_i'); - that._t = NAME; // collection type - that._i = create(null); // index - that._f = undefined; // first entry - that._l = undefined; // last entry - that[SIZE] = 0; // size - if (iterable != undefined) forOf(iterable, IS_MAP, that[ADDER], that); - }); - redefineAll(C.prototype, { - // 23.1.3.1 Map.prototype.clear() - // 23.2.3.2 Set.prototype.clear() - clear: function clear() { - for (var that = validate(this, NAME), data = that._i, entry = that._f; entry; entry = entry.n) { - entry.r = true; - if (entry.p) entry.p = entry.p.n = undefined; - delete data[entry.i]; - } - that._f = that._l = undefined; - that[SIZE] = 0; - }, - // 23.1.3.3 Map.prototype.delete(key) - // 23.2.3.4 Set.prototype.delete(value) - 'delete': function (key) { - var that = validate(this, NAME); - var entry = getEntry(that, key); - if (entry) { - var next = entry.n; - var prev = entry.p; - delete that._i[entry.i]; - entry.r = true; - if (prev) prev.n = next; - if (next) next.p = prev; - if (that._f == entry) that._f = next; - if (that._l == entry) that._l = prev; - that[SIZE]--; - } return !!entry; - }, - // 23.2.3.6 Set.prototype.forEach(callbackfn, thisArg = undefined) - // 23.1.3.5 Map.prototype.forEach(callbackfn, thisArg = undefined) - forEach: function forEach(callbackfn /* , that = undefined */) { - validate(this, NAME); - var f = ctx(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3); - var entry; - while (entry = entry ? entry.n : this._f) { - f(entry.v, entry.k, this); - // revert to the last existing entry - while (entry && entry.r) entry = entry.p; - } - }, - // 23.1.3.7 Map.prototype.has(key) - // 23.2.3.7 Set.prototype.has(value) - has: function has(key) { - return !!getEntry(validate(this, NAME), key); - } - }); - if (DESCRIPTORS) dP(C.prototype, 'size', { - get: function () { - return validate(this, NAME)[SIZE]; - } - }); - return C; - }, - def: function (that, key, value) { - var entry = getEntry(that, key); - var prev, index; - // change existing entry - if (entry) { - entry.v = value; - // create new entry - } else { - that._l = entry = { - i: index = fastKey(key, true), // <- index - k: key, // <- key - v: value, // <- value - p: prev = that._l, // <- previous entry - n: undefined, // <- next entry - r: false // <- removed - }; - if (!that._f) that._f = entry; - if (prev) prev.n = entry; - that[SIZE]++; - // add to index - if (index !== 'F') that._i[index] = entry; - } return that; - }, - getEntry: getEntry, - setStrong: function (C, NAME, IS_MAP) { - // add .keys, .values, .entries, [@@iterator] - // 23.1.3.4, 23.1.3.8, 23.1.3.11, 23.1.3.12, 23.2.3.5, 23.2.3.8, 23.2.3.10, 23.2.3.11 - $iterDefine(C, NAME, function (iterated, kind) { - this._t = validate(iterated, NAME); // target - this._k = kind; // kind - this._l = undefined; // previous - }, function () { - var that = this; - var kind = that._k; - var entry = that._l; - // revert to the last existing entry - while (entry && entry.r) entry = entry.p; - // get next entry - if (!that._t || !(that._l = entry = entry ? entry.n : that._t._f)) { - // or finish the iteration - that._t = undefined; - return step(1); - } - // return step by kind - if (kind == 'keys') return step(0, entry.k); - if (kind == 'values') return step(0, entry.v); - return step(0, [entry.k, entry.v]); - }, IS_MAP ? 'entries' : 'values', !IS_MAP, true); - - // add [@@species], 23.1.2.2, 23.2.2.2 - setSpecies(NAME); - } - }; - - -/***/ }), -/* 218 */ -/***/ (function(module, exports, __webpack_require__) { - - var isObject = __webpack_require__(13); - module.exports = function (it, TYPE) { - if (!isObject(it) || it._t !== TYPE) throw TypeError('Incompatible receiver, ' + TYPE + ' required!'); - return it; - }; - - -/***/ }), -/* 219 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var global = __webpack_require__(4); - var $export = __webpack_require__(8); - var redefine = __webpack_require__(18); - var redefineAll = __webpack_require__(215); - var meta = __webpack_require__(22); - var forOf = __webpack_require__(207); - var anInstance = __webpack_require__(206); - var isObject = __webpack_require__(13); - var fails = __webpack_require__(7); - var $iterDetect = __webpack_require__(166); - var setToStringTag = __webpack_require__(25); - var inheritIfRequired = __webpack_require__(87); - - module.exports = function (NAME, wrapper, methods, common, IS_MAP, IS_WEAK) { - var Base = global[NAME]; - var C = Base; - var ADDER = IS_MAP ? 'set' : 'add'; - var proto = C && C.prototype; - var O = {}; - var fixMethod = function (KEY) { - var fn = proto[KEY]; - redefine(proto, KEY, - KEY == 'delete' ? function (a) { - return IS_WEAK && !isObject(a) ? false : fn.call(this, a === 0 ? 0 : a); - } : KEY == 'has' ? function has(a) { - return IS_WEAK && !isObject(a) ? false : fn.call(this, a === 0 ? 0 : a); - } : KEY == 'get' ? function get(a) { - return IS_WEAK && !isObject(a) ? undefined : fn.call(this, a === 0 ? 0 : a); - } : KEY == 'add' ? function add(a) { fn.call(this, a === 0 ? 0 : a); return this; } - : function set(a, b) { fn.call(this, a === 0 ? 0 : a, b); return this; } - ); - }; - if (typeof C != 'function' || !(IS_WEAK || proto.forEach && !fails(function () { - new C().entries().next(); - }))) { - // create collection constructor - C = common.getConstructor(wrapper, NAME, IS_MAP, ADDER); - redefineAll(C.prototype, methods); - meta.NEED = true; - } else { - var instance = new C(); - // early implementations not supports chaining - var HASNT_CHAINING = instance[ADDER](IS_WEAK ? {} : -0, 1) != instance; - // V8 ~ Chromium 40- weak-collections throws on primitives, but should return false - var THROWS_ON_PRIMITIVES = fails(function () { instance.has(1); }); - // most early implementations doesn't supports iterables, most modern - not close it correctly - var ACCEPT_ITERABLES = $iterDetect(function (iter) { new C(iter); }); // eslint-disable-line no-new - // for early implementations -0 and +0 not the same - var BUGGY_ZERO = !IS_WEAK && fails(function () { - // V8 ~ Chromium 42- fails only with 5+ elements - var $instance = new C(); - var index = 5; - while (index--) $instance[ADDER](index, index); - return !$instance.has(-0); - }); - if (!ACCEPT_ITERABLES) { - C = wrapper(function (target, iterable) { - anInstance(target, C, NAME); - var that = inheritIfRequired(new Base(), target, C); - if (iterable != undefined) forOf(iterable, IS_MAP, that[ADDER], that); - return that; - }); - C.prototype = proto; - proto.constructor = C; - } - if (THROWS_ON_PRIMITIVES || BUGGY_ZERO) { - fixMethod('delete'); - fixMethod('has'); - IS_MAP && fixMethod('get'); - } - if (BUGGY_ZERO || HASNT_CHAINING) fixMethod(ADDER); - // weak collections should not contains .clear method - if (IS_WEAK && proto.clear) delete proto.clear; - } - - setToStringTag(C, NAME); - - O[NAME] = C; - $export($export.G + $export.W + $export.F * (C != Base), O); - - if (!IS_WEAK) common.setStrong(C, NAME, IS_MAP); - - return C; - }; - - -/***/ }), -/* 220 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var strong = __webpack_require__(217); - var validate = __webpack_require__(218); - var SET = 'Set'; - - // 23.2 Set Objects - module.exports = __webpack_require__(219)(SET, function (get) { - return function Set() { return get(this, arguments.length > 0 ? arguments[0] : undefined); }; - }, { - // 23.2.3.1 Set.prototype.add(value) - add: function add(value) { - return strong.def(validate(this, SET), value = value === 0 ? 0 : value, value); - } - }, strong); - - -/***/ }), -/* 221 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var each = __webpack_require__(173)(0); - var redefine = __webpack_require__(18); - var meta = __webpack_require__(22); - var assign = __webpack_require__(68); - var weak = __webpack_require__(222); - var isObject = __webpack_require__(13); - var fails = __webpack_require__(7); - var validate = __webpack_require__(218); - var WEAK_MAP = 'WeakMap'; - var getWeak = meta.getWeak; - var isExtensible = Object.isExtensible; - var uncaughtFrozenStore = weak.ufstore; - var tmp = {}; - var InternalMap; - - var wrapper = function (get) { - return function WeakMap() { - return get(this, arguments.length > 0 ? arguments[0] : undefined); - }; - }; - - var methods = { - // 23.3.3.3 WeakMap.prototype.get(key) - get: function get(key) { - if (isObject(key)) { - var data = getWeak(key); - if (data === true) return uncaughtFrozenStore(validate(this, WEAK_MAP)).get(key); - return data ? data[this._i] : undefined; - } - }, - // 23.3.3.5 WeakMap.prototype.set(key, value) - set: function set(key, value) { - return weak.def(validate(this, WEAK_MAP), key, value); - } - }; - - // 23.3 WeakMap Objects - var $WeakMap = module.exports = __webpack_require__(219)(WEAK_MAP, wrapper, methods, weak, true, true); - - // IE11 WeakMap frozen keys fix - if (fails(function () { return new $WeakMap().set((Object.freeze || Object)(tmp), 7).get(tmp) != 7; })) { - InternalMap = weak.getConstructor(wrapper, WEAK_MAP); - assign(InternalMap.prototype, methods); - meta.NEED = true; - each(['delete', 'has', 'get', 'set'], function (key) { - var proto = $WeakMap.prototype; - var method = proto[key]; - redefine(proto, key, function (a, b) { - // store frozen objects on internal weakmap shim - if (isObject(a) && !isExtensible(a)) { - if (!this._f) this._f = new InternalMap(); - var result = this._f[key](a, b); - return key == 'set' ? this : result; - // store all the rest on native weakmap - } return method.call(this, a, b); - }); - }); - } - - -/***/ }), -/* 222 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var redefineAll = __webpack_require__(215); - var getWeak = __webpack_require__(22).getWeak; - var anObject = __webpack_require__(12); - var isObject = __webpack_require__(13); - var anInstance = __webpack_require__(206); - var forOf = __webpack_require__(207); - var createArrayMethod = __webpack_require__(173); - var $has = __webpack_require__(5); - var validate = __webpack_require__(218); - var arrayFind = createArrayMethod(5); - var arrayFindIndex = createArrayMethod(6); - var id = 0; - - // fallback for uncaught frozen keys - var uncaughtFrozenStore = function (that) { - return that._l || (that._l = new UncaughtFrozenStore()); - }; - var UncaughtFrozenStore = function () { - this.a = []; - }; - var findUncaughtFrozen = function (store, key) { - return arrayFind(store.a, function (it) { - return it[0] === key; - }); - }; - UncaughtFrozenStore.prototype = { - get: function (key) { - var entry = findUncaughtFrozen(this, key); - if (entry) return entry[1]; - }, - has: function (key) { - return !!findUncaughtFrozen(this, key); - }, - set: function (key, value) { - var entry = findUncaughtFrozen(this, key); - if (entry) entry[1] = value; - else this.a.push([key, value]); - }, - 'delete': function (key) { - var index = arrayFindIndex(this.a, function (it) { - return it[0] === key; - }); - if (~index) this.a.splice(index, 1); - return !!~index; - } - }; - - module.exports = { - getConstructor: function (wrapper, NAME, IS_MAP, ADDER) { - var C = wrapper(function (that, iterable) { - anInstance(that, C, NAME, '_i'); - that._t = NAME; // collection type - that._i = id++; // collection id - that._l = undefined; // leak store for uncaught frozen objects - if (iterable != undefined) forOf(iterable, IS_MAP, that[ADDER], that); - }); - redefineAll(C.prototype, { - // 23.3.3.2 WeakMap.prototype.delete(key) - // 23.4.3.3 WeakSet.prototype.delete(value) - 'delete': function (key) { - if (!isObject(key)) return false; - var data = getWeak(key); - if (data === true) return uncaughtFrozenStore(validate(this, NAME))['delete'](key); - return data && $has(data, this._i) && delete data[this._i]; - }, - // 23.3.3.4 WeakMap.prototype.has(key) - // 23.4.3.4 WeakSet.prototype.has(value) - has: function has(key) { - if (!isObject(key)) return false; - var data = getWeak(key); - if (data === true) return uncaughtFrozenStore(validate(this, NAME)).has(key); - return data && $has(data, this._i); - } - }); - return C; - }, - def: function (that, key, value) { - var data = getWeak(anObject(key), true); - if (data === true) uncaughtFrozenStore(that).set(key, value); - else data[that._i] = value; - return that; - }, - ufstore: uncaughtFrozenStore - }; - - -/***/ }), -/* 223 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var weak = __webpack_require__(222); - var validate = __webpack_require__(218); - var WEAK_SET = 'WeakSet'; - - // 23.4 WeakSet Objects - __webpack_require__(219)(WEAK_SET, function (get) { - return function WeakSet() { return get(this, arguments.length > 0 ? arguments[0] : undefined); }; - }, { - // 23.4.3.1 WeakSet.prototype.add(value) - add: function add(value) { - return weak.def(validate(this, WEAK_SET), value, true); - } - }, weak, false, true); - - -/***/ }), -/* 224 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var $typed = __webpack_require__(225); - var buffer = __webpack_require__(226); - var anObject = __webpack_require__(12); - var toAbsoluteIndex = __webpack_require__(39); - var toLength = __webpack_require__(37); - var isObject = __webpack_require__(13); - var ArrayBuffer = __webpack_require__(4).ArrayBuffer; - var speciesConstructor = __webpack_require__(208); - var $ArrayBuffer = buffer.ArrayBuffer; - var $DataView = buffer.DataView; - var $isView = $typed.ABV && ArrayBuffer.isView; - var $slice = $ArrayBuffer.prototype.slice; - var VIEW = $typed.VIEW; - var ARRAY_BUFFER = 'ArrayBuffer'; - - $export($export.G + $export.W + $export.F * (ArrayBuffer !== $ArrayBuffer), { ArrayBuffer: $ArrayBuffer }); - - $export($export.S + $export.F * !$typed.CONSTR, ARRAY_BUFFER, { - // 24.1.3.1 ArrayBuffer.isView(arg) - isView: function isView(it) { - return $isView && $isView(it) || isObject(it) && VIEW in it; - } - }); - - $export($export.P + $export.U + $export.F * __webpack_require__(7)(function () { - return !new $ArrayBuffer(2).slice(1, undefined).byteLength; - }), ARRAY_BUFFER, { - // 24.1.4.3 ArrayBuffer.prototype.slice(start, end) - slice: function slice(start, end) { - if ($slice !== undefined && end === undefined) return $slice.call(anObject(this), start); // FF fix - var len = anObject(this).byteLength; - var first = toAbsoluteIndex(start, len); - var fin = toAbsoluteIndex(end === undefined ? len : end, len); - var result = new (speciesConstructor(this, $ArrayBuffer))(toLength(fin - first)); - var viewS = new $DataView(this); - var viewT = new $DataView(result); - var index = 0; - while (first < fin) { - viewT.setUint8(index++, viewS.getUint8(first++)); - } return result; - } - }); - - __webpack_require__(193)(ARRAY_BUFFER); - - -/***/ }), -/* 225 */ -/***/ (function(module, exports, __webpack_require__) { - - var global = __webpack_require__(4); - var hide = __webpack_require__(10); - var uid = __webpack_require__(19); - var TYPED = uid('typed_array'); - var VIEW = uid('view'); - var ABV = !!(global.ArrayBuffer && global.DataView); - var CONSTR = ABV; - var i = 0; - var l = 9; - var Typed; - - var TypedArrayConstructors = ( - 'Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array' - ).split(','); - - while (i < l) { - if (Typed = global[TypedArrayConstructors[i++]]) { - hide(Typed.prototype, TYPED, true); - hide(Typed.prototype, VIEW, true); - } else CONSTR = false; - } - - module.exports = { - ABV: ABV, - CONSTR: CONSTR, - TYPED: TYPED, - VIEW: VIEW - }; - - -/***/ }), -/* 226 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var global = __webpack_require__(4); - var DESCRIPTORS = __webpack_require__(6); - var LIBRARY = __webpack_require__(24); - var $typed = __webpack_require__(225); - var hide = __webpack_require__(10); - var redefineAll = __webpack_require__(215); - var fails = __webpack_require__(7); - var anInstance = __webpack_require__(206); - var toInteger = __webpack_require__(38); - var toLength = __webpack_require__(37); - var toIndex = __webpack_require__(227); - var gOPN = __webpack_require__(49).f; - var dP = __webpack_require__(11).f; - var arrayFill = __webpack_require__(189); - var setToStringTag = __webpack_require__(25); - var ARRAY_BUFFER = 'ArrayBuffer'; - var DATA_VIEW = 'DataView'; - var PROTOTYPE = 'prototype'; - var WRONG_LENGTH = 'Wrong length!'; - var WRONG_INDEX = 'Wrong index!'; - var $ArrayBuffer = global[ARRAY_BUFFER]; - var $DataView = global[DATA_VIEW]; - var Math = global.Math; - var RangeError = global.RangeError; - // eslint-disable-next-line no-shadow-restricted-names - var Infinity = global.Infinity; - var BaseBuffer = $ArrayBuffer; - var abs = Math.abs; - var pow = Math.pow; - var floor = Math.floor; - var log = Math.log; - var LN2 = Math.LN2; - var BUFFER = 'buffer'; - var BYTE_LENGTH = 'byteLength'; - var BYTE_OFFSET = 'byteOffset'; - var $BUFFER = DESCRIPTORS ? '_b' : BUFFER; - var $LENGTH = DESCRIPTORS ? '_l' : BYTE_LENGTH; - var $OFFSET = DESCRIPTORS ? '_o' : BYTE_OFFSET; - - // IEEE754 conversions based on https://github.com/feross/ieee754 - function packIEEE754(value, mLen, nBytes) { - var buffer = new Array(nBytes); - var eLen = nBytes * 8 - mLen - 1; - var eMax = (1 << eLen) - 1; - var eBias = eMax >> 1; - var rt = mLen === 23 ? pow(2, -24) - pow(2, -77) : 0; - var i = 0; - var s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0; - var e, m, c; - value = abs(value); - // eslint-disable-next-line no-self-compare - if (value != value || value === Infinity) { - // eslint-disable-next-line no-self-compare - m = value != value ? 1 : 0; - e = eMax; - } else { - e = floor(log(value) / LN2); - if (value * (c = pow(2, -e)) < 1) { - e--; - c *= 2; - } - if (e + eBias >= 1) { - value += rt / c; - } else { - value += rt * pow(2, 1 - eBias); - } - if (value * c >= 2) { - e++; - c /= 2; - } - if (e + eBias >= eMax) { - m = 0; - e = eMax; - } else if (e + eBias >= 1) { - m = (value * c - 1) * pow(2, mLen); - e = e + eBias; - } else { - m = value * pow(2, eBias - 1) * pow(2, mLen); - e = 0; - } - } - for (; mLen >= 8; buffer[i++] = m & 255, m /= 256, mLen -= 8); - e = e << mLen | m; - eLen += mLen; - for (; eLen > 0; buffer[i++] = e & 255, e /= 256, eLen -= 8); - buffer[--i] |= s * 128; - return buffer; - } - function unpackIEEE754(buffer, mLen, nBytes) { - var eLen = nBytes * 8 - mLen - 1; - var eMax = (1 << eLen) - 1; - var eBias = eMax >> 1; - var nBits = eLen - 7; - var i = nBytes - 1; - var s = buffer[i--]; - var e = s & 127; - var m; - s >>= 7; - for (; nBits > 0; e = e * 256 + buffer[i], i--, nBits -= 8); - m = e & (1 << -nBits) - 1; - e >>= -nBits; - nBits += mLen; - for (; nBits > 0; m = m * 256 + buffer[i], i--, nBits -= 8); - if (e === 0) { - e = 1 - eBias; - } else if (e === eMax) { - return m ? NaN : s ? -Infinity : Infinity; - } else { - m = m + pow(2, mLen); - e = e - eBias; - } return (s ? -1 : 1) * m * pow(2, e - mLen); - } - - function unpackI32(bytes) { - return bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0]; - } - function packI8(it) { - return [it & 0xff]; - } - function packI16(it) { - return [it & 0xff, it >> 8 & 0xff]; - } - function packI32(it) { - return [it & 0xff, it >> 8 & 0xff, it >> 16 & 0xff, it >> 24 & 0xff]; - } - function packF64(it) { - return packIEEE754(it, 52, 8); - } - function packF32(it) { - return packIEEE754(it, 23, 4); - } - - function addGetter(C, key, internal) { - dP(C[PROTOTYPE], key, { get: function () { return this[internal]; } }); - } - - function get(view, bytes, index, isLittleEndian) { - var numIndex = +index; - var intIndex = toIndex(numIndex); - if (intIndex + bytes > view[$LENGTH]) throw RangeError(WRONG_INDEX); - var store = view[$BUFFER]._b; - var start = intIndex + view[$OFFSET]; - var pack = store.slice(start, start + bytes); - return isLittleEndian ? pack : pack.reverse(); - } - function set(view, bytes, index, conversion, value, isLittleEndian) { - var numIndex = +index; - var intIndex = toIndex(numIndex); - if (intIndex + bytes > view[$LENGTH]) throw RangeError(WRONG_INDEX); - var store = view[$BUFFER]._b; - var start = intIndex + view[$OFFSET]; - var pack = conversion(+value); - for (var i = 0; i < bytes; i++) store[start + i] = pack[isLittleEndian ? i : bytes - i - 1]; - } - - if (!$typed.ABV) { - $ArrayBuffer = function ArrayBuffer(length) { - anInstance(this, $ArrayBuffer, ARRAY_BUFFER); - var byteLength = toIndex(length); - this._b = arrayFill.call(new Array(byteLength), 0); - this[$LENGTH] = byteLength; - }; - - $DataView = function DataView(buffer, byteOffset, byteLength) { - anInstance(this, $DataView, DATA_VIEW); - anInstance(buffer, $ArrayBuffer, DATA_VIEW); - var bufferLength = buffer[$LENGTH]; - var offset = toInteger(byteOffset); - if (offset < 0 || offset > bufferLength) throw RangeError('Wrong offset!'); - byteLength = byteLength === undefined ? bufferLength - offset : toLength(byteLength); - if (offset + byteLength > bufferLength) throw RangeError(WRONG_LENGTH); - this[$BUFFER] = buffer; - this[$OFFSET] = offset; - this[$LENGTH] = byteLength; - }; - - if (DESCRIPTORS) { - addGetter($ArrayBuffer, BYTE_LENGTH, '_l'); - addGetter($DataView, BUFFER, '_b'); - addGetter($DataView, BYTE_LENGTH, '_l'); - addGetter($DataView, BYTE_OFFSET, '_o'); - } - - redefineAll($DataView[PROTOTYPE], { - getInt8: function getInt8(byteOffset) { - return get(this, 1, byteOffset)[0] << 24 >> 24; - }, - getUint8: function getUint8(byteOffset) { - return get(this, 1, byteOffset)[0]; - }, - getInt16: function getInt16(byteOffset /* , littleEndian */) { - var bytes = get(this, 2, byteOffset, arguments[1]); - return (bytes[1] << 8 | bytes[0]) << 16 >> 16; - }, - getUint16: function getUint16(byteOffset /* , littleEndian */) { - var bytes = get(this, 2, byteOffset, arguments[1]); - return bytes[1] << 8 | bytes[0]; - }, - getInt32: function getInt32(byteOffset /* , littleEndian */) { - return unpackI32(get(this, 4, byteOffset, arguments[1])); - }, - getUint32: function getUint32(byteOffset /* , littleEndian */) { - return unpackI32(get(this, 4, byteOffset, arguments[1])) >>> 0; - }, - getFloat32: function getFloat32(byteOffset /* , littleEndian */) { - return unpackIEEE754(get(this, 4, byteOffset, arguments[1]), 23, 4); - }, - getFloat64: function getFloat64(byteOffset /* , littleEndian */) { - return unpackIEEE754(get(this, 8, byteOffset, arguments[1]), 52, 8); - }, - setInt8: function setInt8(byteOffset, value) { - set(this, 1, byteOffset, packI8, value); - }, - setUint8: function setUint8(byteOffset, value) { - set(this, 1, byteOffset, packI8, value); - }, - setInt16: function setInt16(byteOffset, value /* , littleEndian */) { - set(this, 2, byteOffset, packI16, value, arguments[2]); - }, - setUint16: function setUint16(byteOffset, value /* , littleEndian */) { - set(this, 2, byteOffset, packI16, value, arguments[2]); - }, - setInt32: function setInt32(byteOffset, value /* , littleEndian */) { - set(this, 4, byteOffset, packI32, value, arguments[2]); - }, - setUint32: function setUint32(byteOffset, value /* , littleEndian */) { - set(this, 4, byteOffset, packI32, value, arguments[2]); - }, - setFloat32: function setFloat32(byteOffset, value /* , littleEndian */) { - set(this, 4, byteOffset, packF32, value, arguments[2]); - }, - setFloat64: function setFloat64(byteOffset, value /* , littleEndian */) { - set(this, 8, byteOffset, packF64, value, arguments[2]); - } - }); - } else { - if (!fails(function () { - $ArrayBuffer(1); - }) || !fails(function () { - new $ArrayBuffer(-1); // eslint-disable-line no-new - }) || fails(function () { - new $ArrayBuffer(); // eslint-disable-line no-new - new $ArrayBuffer(1.5); // eslint-disable-line no-new - new $ArrayBuffer(NaN); // eslint-disable-line no-new - return $ArrayBuffer.name != ARRAY_BUFFER; - })) { - $ArrayBuffer = function ArrayBuffer(length) { - anInstance(this, $ArrayBuffer); - return new BaseBuffer(toIndex(length)); - }; - var ArrayBufferProto = $ArrayBuffer[PROTOTYPE] = BaseBuffer[PROTOTYPE]; - for (var keys = gOPN(BaseBuffer), j = 0, key; keys.length > j;) { - if (!((key = keys[j++]) in $ArrayBuffer)) hide($ArrayBuffer, key, BaseBuffer[key]); - } - if (!LIBRARY) ArrayBufferProto.constructor = $ArrayBuffer; - } - // iOS Safari 7.x bug - var view = new $DataView(new $ArrayBuffer(2)); - var $setInt8 = $DataView[PROTOTYPE].setInt8; - view.setInt8(0, 2147483648); - view.setInt8(1, 2147483649); - if (view.getInt8(0) || !view.getInt8(1)) redefineAll($DataView[PROTOTYPE], { - setInt8: function setInt8(byteOffset, value) { - $setInt8.call(this, byteOffset, value << 24 >> 24); - }, - setUint8: function setUint8(byteOffset, value) { - $setInt8.call(this, byteOffset, value << 24 >> 24); - } - }, true); - } - setToStringTag($ArrayBuffer, ARRAY_BUFFER); - setToStringTag($DataView, DATA_VIEW); - hide($DataView[PROTOTYPE], $typed.VIEW, true); - exports[ARRAY_BUFFER] = $ArrayBuffer; - exports[DATA_VIEW] = $DataView; - - -/***/ }), -/* 227 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://tc39.github.io/ecma262/#sec-toindex - var toInteger = __webpack_require__(38); - var toLength = __webpack_require__(37); - module.exports = function (it) { - if (it === undefined) return 0; - var number = toInteger(it); - var length = toLength(number); - if (number !== length) throw RangeError('Wrong length!'); - return length; - }; - - -/***/ }), -/* 228 */ -/***/ (function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8); - $export($export.G + $export.W + $export.F * !__webpack_require__(225).ABV, { - DataView: __webpack_require__(226).DataView - }); - - -/***/ }), -/* 229 */ -/***/ (function(module, exports, __webpack_require__) { - - __webpack_require__(230)('Int8', 1, function (init) { - return function Int8Array(data, byteOffset, length) { - return init(this, data, byteOffset, length); - }; - }); - - -/***/ }), -/* 230 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - if (__webpack_require__(6)) { - var LIBRARY = __webpack_require__(24); - var global = __webpack_require__(4); - var fails = __webpack_require__(7); - var $export = __webpack_require__(8); - var $typed = __webpack_require__(225); - var $buffer = __webpack_require__(226); - var ctx = __webpack_require__(20); - var anInstance = __webpack_require__(206); - var propertyDesc = __webpack_require__(17); - var hide = __webpack_require__(10); - var redefineAll = __webpack_require__(215); - var toInteger = __webpack_require__(38); - var toLength = __webpack_require__(37); - var toIndex = __webpack_require__(227); - var toAbsoluteIndex = __webpack_require__(39); - var toPrimitive = __webpack_require__(16); - var has = __webpack_require__(5); - var classof = __webpack_require__(74); - var isObject = __webpack_require__(13); - var toObject = __webpack_require__(57); - var isArrayIter = __webpack_require__(163); - var create = __webpack_require__(45); - var getPrototypeOf = __webpack_require__(58); - var gOPN = __webpack_require__(49).f; - var getIterFn = __webpack_require__(165); - var uid = __webpack_require__(19); - var wks = __webpack_require__(26); - var createArrayMethod = __webpack_require__(173); - var createArrayIncludes = __webpack_require__(36); - var speciesConstructor = __webpack_require__(208); - var ArrayIterators = __webpack_require__(194); - var Iterators = __webpack_require__(129); - var $iterDetect = __webpack_require__(166); - var setSpecies = __webpack_require__(193); - var arrayFill = __webpack_require__(189); - var arrayCopyWithin = __webpack_require__(186); - var $DP = __webpack_require__(11); - var $GOPD = __webpack_require__(50); - var dP = $DP.f; - var gOPD = $GOPD.f; - var RangeError = global.RangeError; - var TypeError = global.TypeError; - var Uint8Array = global.Uint8Array; - var ARRAY_BUFFER = 'ArrayBuffer'; - var SHARED_BUFFER = 'Shared' + ARRAY_BUFFER; - var BYTES_PER_ELEMENT = 'BYTES_PER_ELEMENT'; - var PROTOTYPE = 'prototype'; - var ArrayProto = Array[PROTOTYPE]; - var $ArrayBuffer = $buffer.ArrayBuffer; - var $DataView = $buffer.DataView; - var arrayForEach = createArrayMethod(0); - var arrayFilter = createArrayMethod(2); - var arraySome = createArrayMethod(3); - var arrayEvery = createArrayMethod(4); - var arrayFind = createArrayMethod(5); - var arrayFindIndex = createArrayMethod(6); - var arrayIncludes = createArrayIncludes(true); - var arrayIndexOf = createArrayIncludes(false); - var arrayValues = ArrayIterators.values; - var arrayKeys = ArrayIterators.keys; - var arrayEntries = ArrayIterators.entries; - var arrayLastIndexOf = ArrayProto.lastIndexOf; - var arrayReduce = ArrayProto.reduce; - var arrayReduceRight = ArrayProto.reduceRight; - var arrayJoin = ArrayProto.join; - var arraySort = ArrayProto.sort; - var arraySlice = ArrayProto.slice; - var arrayToString = ArrayProto.toString; - var arrayToLocaleString = ArrayProto.toLocaleString; - var ITERATOR = wks('iterator'); - var TAG = wks('toStringTag'); - var TYPED_CONSTRUCTOR = uid('typed_constructor'); - var DEF_CONSTRUCTOR = uid('def_constructor'); - var ALL_CONSTRUCTORS = $typed.CONSTR; - var TYPED_ARRAY = $typed.TYPED; - var VIEW = $typed.VIEW; - var WRONG_LENGTH = 'Wrong length!'; - - var $map = createArrayMethod(1, function (O, length) { - return allocate(speciesConstructor(O, O[DEF_CONSTRUCTOR]), length); - }); - - var LITTLE_ENDIAN = fails(function () { - // eslint-disable-next-line no-undef - return new Uint8Array(new Uint16Array([1]).buffer)[0] === 1; - }); - - var FORCED_SET = !!Uint8Array && !!Uint8Array[PROTOTYPE].set && fails(function () { - new Uint8Array(1).set({}); - }); - - var toOffset = function (it, BYTES) { - var offset = toInteger(it); - if (offset < 0 || offset % BYTES) throw RangeError('Wrong offset!'); - return offset; - }; - - var validate = function (it) { - if (isObject(it) && TYPED_ARRAY in it) return it; - throw TypeError(it + ' is not a typed array!'); - }; - - var allocate = function (C, length) { - if (!(isObject(C) && TYPED_CONSTRUCTOR in C)) { - throw TypeError('It is not a typed array constructor!'); - } return new C(length); - }; - - var speciesFromList = function (O, list) { - return fromList(speciesConstructor(O, O[DEF_CONSTRUCTOR]), list); - }; - - var fromList = function (C, list) { - var index = 0; - var length = list.length; - var result = allocate(C, length); - while (length > index) result[index] = list[index++]; - return result; - }; - - var addGetter = function (it, key, internal) { - dP(it, key, { get: function () { return this._d[internal]; } }); - }; - - var $from = function from(source /* , mapfn, thisArg */) { - var O = toObject(source); - var aLen = arguments.length; - var mapfn = aLen > 1 ? arguments[1] : undefined; - var mapping = mapfn !== undefined; - var iterFn = getIterFn(O); - var i, length, values, result, step, iterator; - if (iterFn != undefined && !isArrayIter(iterFn)) { - for (iterator = iterFn.call(O), values = [], i = 0; !(step = iterator.next()).done; i++) { - values.push(step.value); - } O = values; - } - if (mapping && aLen > 2) mapfn = ctx(mapfn, arguments[2], 2); - for (i = 0, length = toLength(O.length), result = allocate(this, length); length > i; i++) { - result[i] = mapping ? mapfn(O[i], i) : O[i]; - } - return result; - }; - - var $of = function of(/* ...items */) { - var index = 0; - var length = arguments.length; - var result = allocate(this, length); - while (length > index) result[index] = arguments[index++]; - return result; - }; - - // iOS Safari 6.x fails here - var TO_LOCALE_BUG = !!Uint8Array && fails(function () { arrayToLocaleString.call(new Uint8Array(1)); }); - - var $toLocaleString = function toLocaleString() { - return arrayToLocaleString.apply(TO_LOCALE_BUG ? arraySlice.call(validate(this)) : validate(this), arguments); - }; - - var proto = { - copyWithin: function copyWithin(target, start /* , end */) { - return arrayCopyWithin.call(validate(this), target, start, arguments.length > 2 ? arguments[2] : undefined); - }, - every: function every(callbackfn /* , thisArg */) { - return arrayEvery(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined); - }, - fill: function fill(value /* , start, end */) { // eslint-disable-line no-unused-vars - return arrayFill.apply(validate(this), arguments); - }, - filter: function filter(callbackfn /* , thisArg */) { - return speciesFromList(this, arrayFilter(validate(this), callbackfn, - arguments.length > 1 ? arguments[1] : undefined)); - }, - find: function find(predicate /* , thisArg */) { - return arrayFind(validate(this), predicate, arguments.length > 1 ? arguments[1] : undefined); - }, - findIndex: function findIndex(predicate /* , thisArg */) { - return arrayFindIndex(validate(this), predicate, arguments.length > 1 ? arguments[1] : undefined); - }, - forEach: function forEach(callbackfn /* , thisArg */) { - arrayForEach(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined); - }, - indexOf: function indexOf(searchElement /* , fromIndex */) { - return arrayIndexOf(validate(this), searchElement, arguments.length > 1 ? arguments[1] : undefined); - }, - includes: function includes(searchElement /* , fromIndex */) { - return arrayIncludes(validate(this), searchElement, arguments.length > 1 ? arguments[1] : undefined); - }, - join: function join(separator) { // eslint-disable-line no-unused-vars - return arrayJoin.apply(validate(this), arguments); - }, - lastIndexOf: function lastIndexOf(searchElement /* , fromIndex */) { // eslint-disable-line no-unused-vars - return arrayLastIndexOf.apply(validate(this), arguments); - }, - map: function map(mapfn /* , thisArg */) { - return $map(validate(this), mapfn, arguments.length > 1 ? arguments[1] : undefined); - }, - reduce: function reduce(callbackfn /* , initialValue */) { // eslint-disable-line no-unused-vars - return arrayReduce.apply(validate(this), arguments); - }, - reduceRight: function reduceRight(callbackfn /* , initialValue */) { // eslint-disable-line no-unused-vars - return arrayReduceRight.apply(validate(this), arguments); - }, - reverse: function reverse() { - var that = this; - var length = validate(that).length; - var middle = Math.floor(length / 2); - var index = 0; - var value; - while (index < middle) { - value = that[index]; - that[index++] = that[--length]; - that[length] = value; - } return that; - }, - some: function some(callbackfn /* , thisArg */) { - return arraySome(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined); - }, - sort: function sort(comparefn) { - return arraySort.call(validate(this), comparefn); - }, - subarray: function subarray(begin, end) { - var O = validate(this); - var length = O.length; - var $begin = toAbsoluteIndex(begin, length); - return new (speciesConstructor(O, O[DEF_CONSTRUCTOR]))( - O.buffer, - O.byteOffset + $begin * O.BYTES_PER_ELEMENT, - toLength((end === undefined ? length : toAbsoluteIndex(end, length)) - $begin) - ); - } - }; - - var $slice = function slice(start, end) { - return speciesFromList(this, arraySlice.call(validate(this), start, end)); - }; - - var $set = function set(arrayLike /* , offset */) { - validate(this); - var offset = toOffset(arguments[1], 1); - var length = this.length; - var src = toObject(arrayLike); - var len = toLength(src.length); - var index = 0; - if (len + offset > length) throw RangeError(WRONG_LENGTH); - while (index < len) this[offset + index] = src[index++]; - }; - - var $iterators = { - entries: function entries() { - return arrayEntries.call(validate(this)); - }, - keys: function keys() { - return arrayKeys.call(validate(this)); - }, - values: function values() { - return arrayValues.call(validate(this)); - } - }; - - var isTAIndex = function (target, key) { - return isObject(target) - && target[TYPED_ARRAY] - && typeof key != 'symbol' - && key in target - && String(+key) == String(key); - }; - var $getDesc = function getOwnPropertyDescriptor(target, key) { - return isTAIndex(target, key = toPrimitive(key, true)) - ? propertyDesc(2, target[key]) - : gOPD(target, key); - }; - var $setDesc = function defineProperty(target, key, desc) { - if (isTAIndex(target, key = toPrimitive(key, true)) - && isObject(desc) - && has(desc, 'value') - && !has(desc, 'get') - && !has(desc, 'set') - // TODO: add validation descriptor w/o calling accessors - && !desc.configurable - && (!has(desc, 'writable') || desc.writable) - && (!has(desc, 'enumerable') || desc.enumerable) - ) { - target[key] = desc.value; - return target; - } return dP(target, key, desc); - }; - - if (!ALL_CONSTRUCTORS) { - $GOPD.f = $getDesc; - $DP.f = $setDesc; - } - - $export($export.S + $export.F * !ALL_CONSTRUCTORS, 'Object', { - getOwnPropertyDescriptor: $getDesc, - defineProperty: $setDesc - }); - - if (fails(function () { arrayToString.call({}); })) { - arrayToString = arrayToLocaleString = function toString() { - return arrayJoin.call(this); - }; - } - - var $TypedArrayPrototype$ = redefineAll({}, proto); - redefineAll($TypedArrayPrototype$, $iterators); - hide($TypedArrayPrototype$, ITERATOR, $iterators.values); - redefineAll($TypedArrayPrototype$, { - slice: $slice, - set: $set, - constructor: function () { /* noop */ }, - toString: arrayToString, - toLocaleString: $toLocaleString - }); - addGetter($TypedArrayPrototype$, 'buffer', 'b'); - addGetter($TypedArrayPrototype$, 'byteOffset', 'o'); - addGetter($TypedArrayPrototype$, 'byteLength', 'l'); - addGetter($TypedArrayPrototype$, 'length', 'e'); - dP($TypedArrayPrototype$, TAG, { - get: function () { return this[TYPED_ARRAY]; } - }); - - // eslint-disable-next-line max-statements - module.exports = function (KEY, BYTES, wrapper, CLAMPED) { - CLAMPED = !!CLAMPED; - var NAME = KEY + (CLAMPED ? 'Clamped' : '') + 'Array'; - var GETTER = 'get' + KEY; - var SETTER = 'set' + KEY; - var TypedArray = global[NAME]; - var Base = TypedArray || {}; - var TAC = TypedArray && getPrototypeOf(TypedArray); - var FORCED = !TypedArray || !$typed.ABV; - var O = {}; - var TypedArrayPrototype = TypedArray && TypedArray[PROTOTYPE]; - var getter = function (that, index) { - var data = that._d; - return data.v[GETTER](index * BYTES + data.o, LITTLE_ENDIAN); - }; - var setter = function (that, index, value) { - var data = that._d; - if (CLAMPED) value = (value = Math.round(value)) < 0 ? 0 : value > 0xff ? 0xff : value & 0xff; - data.v[SETTER](index * BYTES + data.o, value, LITTLE_ENDIAN); - }; - var addElement = function (that, index) { - dP(that, index, { - get: function () { - return getter(this, index); - }, - set: function (value) { - return setter(this, index, value); - }, - enumerable: true - }); - }; - if (FORCED) { - TypedArray = wrapper(function (that, data, $offset, $length) { - anInstance(that, TypedArray, NAME, '_d'); - var index = 0; - var offset = 0; - var buffer, byteLength, length, klass; - if (!isObject(data)) { - length = toIndex(data); - byteLength = length * BYTES; - buffer = new $ArrayBuffer(byteLength); - } else if (data instanceof $ArrayBuffer || (klass = classof(data)) == ARRAY_BUFFER || klass == SHARED_BUFFER) { - buffer = data; - offset = toOffset($offset, BYTES); - var $len = data.byteLength; - if ($length === undefined) { - if ($len % BYTES) throw RangeError(WRONG_LENGTH); - byteLength = $len - offset; - if (byteLength < 0) throw RangeError(WRONG_LENGTH); - } else { - byteLength = toLength($length) * BYTES; - if (byteLength + offset > $len) throw RangeError(WRONG_LENGTH); - } - length = byteLength / BYTES; - } else if (TYPED_ARRAY in data) { - return fromList(TypedArray, data); - } else { - return $from.call(TypedArray, data); - } - hide(that, '_d', { - b: buffer, - o: offset, - l: byteLength, - e: length, - v: new $DataView(buffer) - }); - while (index < length) addElement(that, index++); - }); - TypedArrayPrototype = TypedArray[PROTOTYPE] = create($TypedArrayPrototype$); - hide(TypedArrayPrototype, 'constructor', TypedArray); - } else if (!fails(function () { - TypedArray(1); - }) || !fails(function () { - new TypedArray(-1); // eslint-disable-line no-new - }) || !$iterDetect(function (iter) { - new TypedArray(); // eslint-disable-line no-new - new TypedArray(null); // eslint-disable-line no-new - new TypedArray(1.5); // eslint-disable-line no-new - new TypedArray(iter); // eslint-disable-line no-new - }, true)) { - TypedArray = wrapper(function (that, data, $offset, $length) { - anInstance(that, TypedArray, NAME); - var klass; - // `ws` module bug, temporarily remove validation length for Uint8Array - // https://github.com/websockets/ws/pull/645 - if (!isObject(data)) return new Base(toIndex(data)); - if (data instanceof $ArrayBuffer || (klass = classof(data)) == ARRAY_BUFFER || klass == SHARED_BUFFER) { - return $length !== undefined - ? new Base(data, toOffset($offset, BYTES), $length) - : $offset !== undefined - ? new Base(data, toOffset($offset, BYTES)) - : new Base(data); - } - if (TYPED_ARRAY in data) return fromList(TypedArray, data); - return $from.call(TypedArray, data); - }); - arrayForEach(TAC !== Function.prototype ? gOPN(Base).concat(gOPN(TAC)) : gOPN(Base), function (key) { - if (!(key in TypedArray)) hide(TypedArray, key, Base[key]); - }); - TypedArray[PROTOTYPE] = TypedArrayPrototype; - if (!LIBRARY) TypedArrayPrototype.constructor = TypedArray; - } - var $nativeIterator = TypedArrayPrototype[ITERATOR]; - var CORRECT_ITER_NAME = !!$nativeIterator - && ($nativeIterator.name == 'values' || $nativeIterator.name == undefined); - var $iterator = $iterators.values; - hide(TypedArray, TYPED_CONSTRUCTOR, true); - hide(TypedArrayPrototype, TYPED_ARRAY, NAME); - hide(TypedArrayPrototype, VIEW, true); - hide(TypedArrayPrototype, DEF_CONSTRUCTOR, TypedArray); - - if (CLAMPED ? new TypedArray(1)[TAG] != NAME : !(TAG in TypedArrayPrototype)) { - dP(TypedArrayPrototype, TAG, { - get: function () { return NAME; } - }); - } - - O[NAME] = TypedArray; - - $export($export.G + $export.W + $export.F * (TypedArray != Base), O); - - $export($export.S, NAME, { - BYTES_PER_ELEMENT: BYTES - }); - - $export($export.S + $export.F * fails(function () { Base.of.call(TypedArray, 1); }), NAME, { - from: $from, - of: $of - }); - - if (!(BYTES_PER_ELEMENT in TypedArrayPrototype)) hide(TypedArrayPrototype, BYTES_PER_ELEMENT, BYTES); - - $export($export.P, NAME, proto); - - setSpecies(NAME); - - $export($export.P + $export.F * FORCED_SET, NAME, { set: $set }); - - $export($export.P + $export.F * !CORRECT_ITER_NAME, NAME, $iterators); - - if (!LIBRARY && TypedArrayPrototype.toString != arrayToString) TypedArrayPrototype.toString = arrayToString; - - $export($export.P + $export.F * fails(function () { - new TypedArray(1).slice(); - }), NAME, { slice: $slice }); - - $export($export.P + $export.F * (fails(function () { - return [1, 2].toLocaleString() != new TypedArray([1, 2]).toLocaleString(); - }) || !fails(function () { - TypedArrayPrototype.toLocaleString.call([1, 2]); - })), NAME, { toLocaleString: $toLocaleString }); - - Iterators[NAME] = CORRECT_ITER_NAME ? $nativeIterator : $iterator; - if (!LIBRARY && !CORRECT_ITER_NAME) hide(TypedArrayPrototype, ITERATOR, $iterator); - }; - } else module.exports = function () { /* empty */ }; - - -/***/ }), -/* 231 */ -/***/ (function(module, exports, __webpack_require__) { - - __webpack_require__(230)('Uint8', 1, function (init) { - return function Uint8Array(data, byteOffset, length) { - return init(this, data, byteOffset, length); - }; - }); - - -/***/ }), -/* 232 */ -/***/ (function(module, exports, __webpack_require__) { - - __webpack_require__(230)('Uint8', 1, function (init) { - return function Uint8ClampedArray(data, byteOffset, length) { - return init(this, data, byteOffset, length); - }; - }, true); - - -/***/ }), -/* 233 */ -/***/ (function(module, exports, __webpack_require__) { - - __webpack_require__(230)('Int16', 2, function (init) { - return function Int16Array(data, byteOffset, length) { - return init(this, data, byteOffset, length); - }; - }); - - -/***/ }), -/* 234 */ -/***/ (function(module, exports, __webpack_require__) { - - __webpack_require__(230)('Uint16', 2, function (init) { - return function Uint16Array(data, byteOffset, length) { - return init(this, data, byteOffset, length); - }; - }); - - -/***/ }), -/* 235 */ -/***/ (function(module, exports, __webpack_require__) { - - __webpack_require__(230)('Int32', 4, function (init) { - return function Int32Array(data, byteOffset, length) { - return init(this, data, byteOffset, length); - }; - }); - - -/***/ }), -/* 236 */ -/***/ (function(module, exports, __webpack_require__) { - - __webpack_require__(230)('Uint32', 4, function (init) { - return function Uint32Array(data, byteOffset, length) { - return init(this, data, byteOffset, length); - }; - }); - - -/***/ }), -/* 237 */ -/***/ (function(module, exports, __webpack_require__) { - - __webpack_require__(230)('Float32', 4, function (init) { - return function Float32Array(data, byteOffset, length) { - return init(this, data, byteOffset, length); - }; - }); - - -/***/ }), -/* 238 */ -/***/ (function(module, exports, __webpack_require__) { - - __webpack_require__(230)('Float64', 8, function (init) { - return function Float64Array(data, byteOffset, length) { - return init(this, data, byteOffset, length); - }; - }); - - -/***/ }), -/* 239 */ -/***/ (function(module, exports, __webpack_require__) { - - // 26.1.1 Reflect.apply(target, thisArgument, argumentsList) - var $export = __webpack_require__(8); - var aFunction = __webpack_require__(21); - var anObject = __webpack_require__(12); - var rApply = (__webpack_require__(4).Reflect || {}).apply; - var fApply = Function.apply; - // MS Edge argumentsList argument is optional - $export($export.S + $export.F * !__webpack_require__(7)(function () { - rApply(function () { /* empty */ }); - }), 'Reflect', { - apply: function apply(target, thisArgument, argumentsList) { - var T = aFunction(target); - var L = anObject(argumentsList); - return rApply ? rApply(T, thisArgument, L) : fApply.call(T, thisArgument, L); - } - }); - - -/***/ }), -/* 240 */ -/***/ (function(module, exports, __webpack_require__) { - - // 26.1.2 Reflect.construct(target, argumentsList [, newTarget]) - var $export = __webpack_require__(8); - var create = __webpack_require__(45); - var aFunction = __webpack_require__(21); - var anObject = __webpack_require__(12); - var isObject = __webpack_require__(13); - var fails = __webpack_require__(7); - var bind = __webpack_require__(76); - var rConstruct = (__webpack_require__(4).Reflect || {}).construct; - - // MS Edge supports only 2 arguments and argumentsList argument is optional - // FF Nightly sets third argument as `new.target`, but does not create `this` from it - var NEW_TARGET_BUG = fails(function () { - function F() { /* empty */ } - return !(rConstruct(function () { /* empty */ }, [], F) instanceof F); - }); - var ARGS_BUG = !fails(function () { - rConstruct(function () { /* empty */ }); - }); - - $export($export.S + $export.F * (NEW_TARGET_BUG || ARGS_BUG), 'Reflect', { - construct: function construct(Target, args /* , newTarget */) { - aFunction(Target); - anObject(args); - var newTarget = arguments.length < 3 ? Target : aFunction(arguments[2]); - if (ARGS_BUG && !NEW_TARGET_BUG) return rConstruct(Target, args, newTarget); - if (Target == newTarget) { - // w/o altered newTarget, optimization for 0-4 arguments - switch (args.length) { - case 0: return new Target(); - case 1: return new Target(args[0]); - case 2: return new Target(args[0], args[1]); - case 3: return new Target(args[0], args[1], args[2]); - case 4: return new Target(args[0], args[1], args[2], args[3]); - } - // w/o altered newTarget, lot of arguments case - var $args = [null]; - $args.push.apply($args, args); - return new (bind.apply(Target, $args))(); - } - // with altered newTarget, not support built-in constructors - var proto = newTarget.prototype; - var instance = create(isObject(proto) ? proto : Object.prototype); - var result = Function.apply.call(Target, instance, args); - return isObject(result) ? result : instance; - } - }); - - -/***/ }), -/* 241 */ -/***/ (function(module, exports, __webpack_require__) { - - // 26.1.3 Reflect.defineProperty(target, propertyKey, attributes) - var dP = __webpack_require__(11); - var $export = __webpack_require__(8); - var anObject = __webpack_require__(12); - var toPrimitive = __webpack_require__(16); - - // MS Edge has broken Reflect.defineProperty - throwing instead of returning false - $export($export.S + $export.F * __webpack_require__(7)(function () { - // eslint-disable-next-line no-undef - Reflect.defineProperty(dP.f({}, 1, { value: 1 }), 1, { value: 2 }); - }), 'Reflect', { - defineProperty: function defineProperty(target, propertyKey, attributes) { - anObject(target); - propertyKey = toPrimitive(propertyKey, true); - anObject(attributes); - try { - dP.f(target, propertyKey, attributes); - return true; - } catch (e) { - return false; - } - } - }); - - -/***/ }), -/* 242 */ -/***/ (function(module, exports, __webpack_require__) { - - // 26.1.4 Reflect.deleteProperty(target, propertyKey) - var $export = __webpack_require__(8); - var gOPD = __webpack_require__(50).f; - var anObject = __webpack_require__(12); - - $export($export.S, 'Reflect', { - deleteProperty: function deleteProperty(target, propertyKey) { - var desc = gOPD(anObject(target), propertyKey); - return desc && !desc.configurable ? false : delete target[propertyKey]; - } - }); - - -/***/ }), -/* 243 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // 26.1.5 Reflect.enumerate(target) - var $export = __webpack_require__(8); - var anObject = __webpack_require__(12); - var Enumerate = function (iterated) { - this._t = anObject(iterated); // target - this._i = 0; // next index - var keys = this._k = []; // keys - var key; - for (key in iterated) keys.push(key); - }; - __webpack_require__(130)(Enumerate, 'Object', function () { - var that = this; - var keys = that._k; - var key; - do { - if (that._i >= keys.length) return { value: undefined, done: true }; - } while (!((key = keys[that._i++]) in that._t)); - return { value: key, done: false }; - }); - - $export($export.S, 'Reflect', { - enumerate: function enumerate(target) { - return new Enumerate(target); - } - }); - - -/***/ }), -/* 244 */ -/***/ (function(module, exports, __webpack_require__) { - - // 26.1.6 Reflect.get(target, propertyKey [, receiver]) - var gOPD = __webpack_require__(50); - var getPrototypeOf = __webpack_require__(58); - var has = __webpack_require__(5); - var $export = __webpack_require__(8); - var isObject = __webpack_require__(13); - var anObject = __webpack_require__(12); - - function get(target, propertyKey /* , receiver */) { - var receiver = arguments.length < 3 ? target : arguments[2]; - var desc, proto; - if (anObject(target) === receiver) return target[propertyKey]; - if (desc = gOPD.f(target, propertyKey)) return has(desc, 'value') - ? desc.value - : desc.get !== undefined - ? desc.get.call(receiver) - : undefined; - if (isObject(proto = getPrototypeOf(target))) return get(proto, propertyKey, receiver); - } - - $export($export.S, 'Reflect', { get: get }); - - -/***/ }), -/* 245 */ -/***/ (function(module, exports, __webpack_require__) { - - // 26.1.7 Reflect.getOwnPropertyDescriptor(target, propertyKey) - var gOPD = __webpack_require__(50); - var $export = __webpack_require__(8); - var anObject = __webpack_require__(12); - - $export($export.S, 'Reflect', { - getOwnPropertyDescriptor: function getOwnPropertyDescriptor(target, propertyKey) { - return gOPD.f(anObject(target), propertyKey); - } - }); - - -/***/ }), -/* 246 */ -/***/ (function(module, exports, __webpack_require__) { - - // 26.1.8 Reflect.getPrototypeOf(target) - var $export = __webpack_require__(8); - var getProto = __webpack_require__(58); - var anObject = __webpack_require__(12); - - $export($export.S, 'Reflect', { - getPrototypeOf: function getPrototypeOf(target) { - return getProto(anObject(target)); - } - }); - - -/***/ }), -/* 247 */ -/***/ (function(module, exports, __webpack_require__) { - - // 26.1.9 Reflect.has(target, propertyKey) - var $export = __webpack_require__(8); - - $export($export.S, 'Reflect', { - has: function has(target, propertyKey) { - return propertyKey in target; - } - }); - - -/***/ }), -/* 248 */ -/***/ (function(module, exports, __webpack_require__) { - - // 26.1.10 Reflect.isExtensible(target) - var $export = __webpack_require__(8); - var anObject = __webpack_require__(12); - var $isExtensible = Object.isExtensible; - - $export($export.S, 'Reflect', { - isExtensible: function isExtensible(target) { - anObject(target); - return $isExtensible ? $isExtensible(target) : true; - } - }); - - -/***/ }), -/* 249 */ -/***/ (function(module, exports, __webpack_require__) { - - // 26.1.11 Reflect.ownKeys(target) - var $export = __webpack_require__(8); - - $export($export.S, 'Reflect', { ownKeys: __webpack_require__(250) }); - - -/***/ }), -/* 250 */ -/***/ (function(module, exports, __webpack_require__) { - - // all object keys, includes non-enumerable and symbols - var gOPN = __webpack_require__(49); - var gOPS = __webpack_require__(42); - var anObject = __webpack_require__(12); - var Reflect = __webpack_require__(4).Reflect; - module.exports = Reflect && Reflect.ownKeys || function ownKeys(it) { - var keys = gOPN.f(anObject(it)); - var getSymbols = gOPS.f; - return getSymbols ? keys.concat(getSymbols(it)) : keys; - }; - - -/***/ }), -/* 251 */ -/***/ (function(module, exports, __webpack_require__) { - - // 26.1.12 Reflect.preventExtensions(target) - var $export = __webpack_require__(8); - var anObject = __webpack_require__(12); - var $preventExtensions = Object.preventExtensions; - - $export($export.S, 'Reflect', { - preventExtensions: function preventExtensions(target) { - anObject(target); - try { - if ($preventExtensions) $preventExtensions(target); - return true; - } catch (e) { - return false; - } - } - }); - - -/***/ }), -/* 252 */ -/***/ (function(module, exports, __webpack_require__) { - - // 26.1.13 Reflect.set(target, propertyKey, V [, receiver]) - var dP = __webpack_require__(11); - var gOPD = __webpack_require__(50); - var getPrototypeOf = __webpack_require__(58); - var has = __webpack_require__(5); - var $export = __webpack_require__(8); - var createDesc = __webpack_require__(17); - var anObject = __webpack_require__(12); - var isObject = __webpack_require__(13); - - function set(target, propertyKey, V /* , receiver */) { - var receiver = arguments.length < 4 ? target : arguments[3]; - var ownDesc = gOPD.f(anObject(target), propertyKey); - var existingDescriptor, proto; - if (!ownDesc) { - if (isObject(proto = getPrototypeOf(target))) { - return set(proto, propertyKey, V, receiver); - } - ownDesc = createDesc(0); - } - if (has(ownDesc, 'value')) { - if (ownDesc.writable === false || !isObject(receiver)) return false; - if (existingDescriptor = gOPD.f(receiver, propertyKey)) { - if (existingDescriptor.get || existingDescriptor.set || existingDescriptor.writable === false) return false; - existingDescriptor.value = V; - dP.f(receiver, propertyKey, existingDescriptor); - } else dP.f(receiver, propertyKey, createDesc(0, V)); - return true; - } - return ownDesc.set === undefined ? false : (ownDesc.set.call(receiver, V), true); - } - - $export($export.S, 'Reflect', { set: set }); - - -/***/ }), -/* 253 */ -/***/ (function(module, exports, __webpack_require__) { - - // 26.1.14 Reflect.setPrototypeOf(target, proto) - var $export = __webpack_require__(8); - var setProto = __webpack_require__(72); - - if (setProto) $export($export.S, 'Reflect', { - setPrototypeOf: function setPrototypeOf(target, proto) { - setProto.check(target, proto); - try { - setProto.set(target, proto); - return true; - } catch (e) { - return false; - } - } - }); - - -/***/ }), -/* 254 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // https://github.com/tc39/Array.prototype.includes - var $export = __webpack_require__(8); - var $includes = __webpack_require__(36)(true); - - $export($export.P, 'Array', { - includes: function includes(el /* , fromIndex = 0 */) { - return $includes(this, el, arguments.length > 1 ? arguments[1] : undefined); - } - }); - - __webpack_require__(187)('includes'); - - -/***/ }), -/* 255 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // https://tc39.github.io/proposal-flatMap/#sec-Array.prototype.flatMap - var $export = __webpack_require__(8); - var flattenIntoArray = __webpack_require__(256); - var toObject = __webpack_require__(57); - var toLength = __webpack_require__(37); - var aFunction = __webpack_require__(21); - var arraySpeciesCreate = __webpack_require__(174); - - $export($export.P, 'Array', { - flatMap: function flatMap(callbackfn /* , thisArg */) { - var O = toObject(this); - var sourceLen, A; - aFunction(callbackfn); - sourceLen = toLength(O.length); - A = arraySpeciesCreate(O, 0); - flattenIntoArray(A, O, O, sourceLen, 0, 1, callbackfn, arguments[1]); - return A; - } - }); - - __webpack_require__(187)('flatMap'); - - -/***/ }), -/* 256 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // https://tc39.github.io/proposal-flatMap/#sec-FlattenIntoArray - var isArray = __webpack_require__(44); - var isObject = __webpack_require__(13); - var toLength = __webpack_require__(37); - var ctx = __webpack_require__(20); - var IS_CONCAT_SPREADABLE = __webpack_require__(26)('isConcatSpreadable'); - - function flattenIntoArray(target, original, source, sourceLen, start, depth, mapper, thisArg) { - var targetIndex = start; - var sourceIndex = 0; - var mapFn = mapper ? ctx(mapper, thisArg, 3) : false; - var element, spreadable; - - while (sourceIndex < sourceLen) { - if (sourceIndex in source) { - element = mapFn ? mapFn(source[sourceIndex], sourceIndex, original) : source[sourceIndex]; - - spreadable = false; - if (isObject(element)) { - spreadable = element[IS_CONCAT_SPREADABLE]; - spreadable = spreadable !== undefined ? !!spreadable : isArray(element); - } - - if (spreadable && depth > 0) { - targetIndex = flattenIntoArray(target, original, element, toLength(element.length), targetIndex, depth - 1) - 1; - } else { - if (targetIndex >= 0x1fffffffffffff) throw TypeError(); - target[targetIndex] = element; - } - - targetIndex++; - } - sourceIndex++; - } - return targetIndex; - } - - module.exports = flattenIntoArray; - - -/***/ }), -/* 257 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // https://tc39.github.io/proposal-flatMap/#sec-Array.prototype.flatten - var $export = __webpack_require__(8); - var flattenIntoArray = __webpack_require__(256); - var toObject = __webpack_require__(57); - var toLength = __webpack_require__(37); - var toInteger = __webpack_require__(38); - var arraySpeciesCreate = __webpack_require__(174); - - $export($export.P, 'Array', { - flatten: function flatten(/* depthArg = 1 */) { - var depthArg = arguments[0]; - var O = toObject(this); - var sourceLen = toLength(O.length); - var A = arraySpeciesCreate(O, 0); - flattenIntoArray(A, O, O, sourceLen, 0, depthArg === undefined ? 1 : toInteger(depthArg)); - return A; - } - }); - - __webpack_require__(187)('flatten'); - - -/***/ }), -/* 258 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // https://github.com/mathiasbynens/String.prototype.at - var $export = __webpack_require__(8); - var $at = __webpack_require__(127)(true); - - $export($export.P, 'String', { - at: function at(pos) { - return $at(this, pos); - } - }); - - -/***/ }), -/* 259 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // https://github.com/tc39/proposal-string-pad-start-end - var $export = __webpack_require__(8); - var $pad = __webpack_require__(260); - var userAgent = __webpack_require__(213); - - // https://github.com/zloirock/core-js/issues/280 - $export($export.P + $export.F * /Version\/10\.\d+(\.\d+)? Safari\//.test(userAgent), 'String', { - padStart: function padStart(maxLength /* , fillString = ' ' */) { - return $pad(this, maxLength, arguments.length > 1 ? arguments[1] : undefined, true); - } - }); - - -/***/ }), -/* 260 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://github.com/tc39/proposal-string-pad-start-end - var toLength = __webpack_require__(37); - var repeat = __webpack_require__(90); - var defined = __webpack_require__(35); - - module.exports = function (that, maxLength, fillString, left) { - var S = String(defined(that)); - var stringLength = S.length; - var fillStr = fillString === undefined ? ' ' : String(fillString); - var intMaxLength = toLength(maxLength); - if (intMaxLength <= stringLength || fillStr == '') return S; - var fillLen = intMaxLength - stringLength; - var stringFiller = repeat.call(fillStr, Math.ceil(fillLen / fillStr.length)); - if (stringFiller.length > fillLen) stringFiller = stringFiller.slice(0, fillLen); - return left ? stringFiller + S : S + stringFiller; - }; - - -/***/ }), -/* 261 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // https://github.com/tc39/proposal-string-pad-start-end - var $export = __webpack_require__(8); - var $pad = __webpack_require__(260); - var userAgent = __webpack_require__(213); - - // https://github.com/zloirock/core-js/issues/280 - $export($export.P + $export.F * /Version\/10\.\d+(\.\d+)? Safari\//.test(userAgent), 'String', { - padEnd: function padEnd(maxLength /* , fillString = ' ' */) { - return $pad(this, maxLength, arguments.length > 1 ? arguments[1] : undefined, false); - } - }); - - -/***/ }), -/* 262 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // https://github.com/sebmarkbage/ecmascript-string-left-right-trim - __webpack_require__(82)('trimLeft', function ($trim) { - return function trimLeft() { - return $trim(this, 1); - }; - }, 'trimStart'); - - -/***/ }), -/* 263 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // https://github.com/sebmarkbage/ecmascript-string-left-right-trim - __webpack_require__(82)('trimRight', function ($trim) { - return function trimRight() { - return $trim(this, 2); - }; - }, 'trimEnd'); - - -/***/ }), -/* 264 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // https://tc39.github.io/String.prototype.matchAll/ - var $export = __webpack_require__(8); - var defined = __webpack_require__(35); - var toLength = __webpack_require__(37); - var isRegExp = __webpack_require__(134); - var getFlags = __webpack_require__(197); - var RegExpProto = RegExp.prototype; - - var $RegExpStringIterator = function (regexp, string) { - this._r = regexp; - this._s = string; - }; - - __webpack_require__(130)($RegExpStringIterator, 'RegExp String', function next() { - var match = this._r.exec(this._s); - return { value: match, done: match === null }; - }); - - $export($export.P, 'String', { - matchAll: function matchAll(regexp) { - defined(this); - if (!isRegExp(regexp)) throw TypeError(regexp + ' is not a regexp!'); - var S = String(this); - var flags = 'flags' in RegExpProto ? String(regexp.flags) : getFlags.call(regexp); - var rx = new RegExp(regexp.source, ~flags.indexOf('g') ? flags : 'g' + flags); - rx.lastIndex = toLength(regexp.lastIndex); - return new $RegExpStringIterator(rx, S); - } - }); - - -/***/ }), -/* 265 */ -/***/ (function(module, exports, __webpack_require__) { - - __webpack_require__(28)('asyncIterator'); - - -/***/ }), -/* 266 */ -/***/ (function(module, exports, __webpack_require__) { - - __webpack_require__(28)('observable'); - - -/***/ }), -/* 267 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://github.com/tc39/proposal-object-getownpropertydescriptors - var $export = __webpack_require__(8); - var ownKeys = __webpack_require__(250); - var toIObject = __webpack_require__(32); - var gOPD = __webpack_require__(50); - var createProperty = __webpack_require__(164); - - $export($export.S, 'Object', { - getOwnPropertyDescriptors: function getOwnPropertyDescriptors(object) { - var O = toIObject(object); - var getDesc = gOPD.f; - var keys = ownKeys(O); - var result = {}; - var i = 0; - var key, desc; - while (keys.length > i) { - desc = getDesc(O, key = keys[i++]); - if (desc !== undefined) createProperty(result, key, desc); - } - return result; - } - }); - - -/***/ }), -/* 268 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://github.com/tc39/proposal-object-values-entries - var $export = __webpack_require__(8); - var $values = __webpack_require__(269)(false); - - $export($export.S, 'Object', { - values: function values(it) { - return $values(it); - } - }); - - -/***/ }), -/* 269 */ -/***/ (function(module, exports, __webpack_require__) { - - var getKeys = __webpack_require__(30); - var toIObject = __webpack_require__(32); - var isEnum = __webpack_require__(43).f; - module.exports = function (isEntries) { - return function (it) { - var O = toIObject(it); - var keys = getKeys(O); - var length = keys.length; - var i = 0; - var result = []; - var key; - while (length > i) if (isEnum.call(O, key = keys[i++])) { - result.push(isEntries ? [key, O[key]] : O[key]); - } return result; - }; - }; - - -/***/ }), -/* 270 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://github.com/tc39/proposal-object-values-entries - var $export = __webpack_require__(8); - var $entries = __webpack_require__(269)(true); - - $export($export.S, 'Object', { - entries: function entries(it) { - return $entries(it); - } - }); - - -/***/ }), -/* 271 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var toObject = __webpack_require__(57); - var aFunction = __webpack_require__(21); - var $defineProperty = __webpack_require__(11); - - // B.2.2.2 Object.prototype.__defineGetter__(P, getter) - __webpack_require__(6) && $export($export.P + __webpack_require__(272), 'Object', { - __defineGetter__: function __defineGetter__(P, getter) { - $defineProperty.f(toObject(this), P, { get: aFunction(getter), enumerable: true, configurable: true }); - } - }); - - -/***/ }), -/* 272 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // Forced replacement prototype accessors methods - module.exports = __webpack_require__(24) || !__webpack_require__(7)(function () { - var K = Math.random(); - // In FF throws only define methods - // eslint-disable-next-line no-undef, no-useless-call - __defineSetter__.call(null, K, function () { /* empty */ }); - delete __webpack_require__(4)[K]; - }); - - -/***/ }), -/* 273 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var toObject = __webpack_require__(57); - var aFunction = __webpack_require__(21); - var $defineProperty = __webpack_require__(11); - - // B.2.2.3 Object.prototype.__defineSetter__(P, setter) - __webpack_require__(6) && $export($export.P + __webpack_require__(272), 'Object', { - __defineSetter__: function __defineSetter__(P, setter) { - $defineProperty.f(toObject(this), P, { set: aFunction(setter), enumerable: true, configurable: true }); - } - }); - - -/***/ }), -/* 274 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var toObject = __webpack_require__(57); - var toPrimitive = __webpack_require__(16); - var getPrototypeOf = __webpack_require__(58); - var getOwnPropertyDescriptor = __webpack_require__(50).f; - - // B.2.2.4 Object.prototype.__lookupGetter__(P) - __webpack_require__(6) && $export($export.P + __webpack_require__(272), 'Object', { - __lookupGetter__: function __lookupGetter__(P) { - var O = toObject(this); - var K = toPrimitive(P, true); - var D; - do { - if (D = getOwnPropertyDescriptor(O, K)) return D.get; - } while (O = getPrototypeOf(O)); - } - }); - - -/***/ }), -/* 275 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var toObject = __webpack_require__(57); - var toPrimitive = __webpack_require__(16); - var getPrototypeOf = __webpack_require__(58); - var getOwnPropertyDescriptor = __webpack_require__(50).f; - - // B.2.2.5 Object.prototype.__lookupSetter__(P) - __webpack_require__(6) && $export($export.P + __webpack_require__(272), 'Object', { - __lookupSetter__: function __lookupSetter__(P) { - var O = toObject(this); - var K = toPrimitive(P, true); - var D; - do { - if (D = getOwnPropertyDescriptor(O, K)) return D.set; - } while (O = getPrototypeOf(O)); - } - }); - - -/***/ }), -/* 276 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://github.com/DavidBruant/Map-Set.prototype.toJSON - var $export = __webpack_require__(8); - - $export($export.P + $export.R, 'Map', { toJSON: __webpack_require__(277)('Map') }); - - -/***/ }), -/* 277 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://github.com/DavidBruant/Map-Set.prototype.toJSON - var classof = __webpack_require__(74); - var from = __webpack_require__(278); - module.exports = function (NAME) { - return function toJSON() { - if (classof(this) != NAME) throw TypeError(NAME + "#toJSON isn't generic"); - return from(this); - }; - }; - - -/***/ }), -/* 278 */ -/***/ (function(module, exports, __webpack_require__) { - - var forOf = __webpack_require__(207); - - module.exports = function (iter, ITERATOR) { - var result = []; - forOf(iter, false, result.push, result, ITERATOR); - return result; - }; - - -/***/ }), -/* 279 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://github.com/DavidBruant/Map-Set.prototype.toJSON - var $export = __webpack_require__(8); - - $export($export.P + $export.R, 'Set', { toJSON: __webpack_require__(277)('Set') }); - - -/***/ }), -/* 280 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://tc39.github.io/proposal-setmap-offrom/#sec-map.of - __webpack_require__(281)('Map'); - - -/***/ }), -/* 281 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // https://tc39.github.io/proposal-setmap-offrom/ - var $export = __webpack_require__(8); - - module.exports = function (COLLECTION) { - $export($export.S, COLLECTION, { of: function of() { - var length = arguments.length; - var A = new Array(length); - while (length--) A[length] = arguments[length]; - return new this(A); - } }); - }; - - -/***/ }), -/* 282 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://tc39.github.io/proposal-setmap-offrom/#sec-set.of - __webpack_require__(281)('Set'); - - -/***/ }), -/* 283 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://tc39.github.io/proposal-setmap-offrom/#sec-weakmap.of - __webpack_require__(281)('WeakMap'); - - -/***/ }), -/* 284 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://tc39.github.io/proposal-setmap-offrom/#sec-weakset.of - __webpack_require__(281)('WeakSet'); - - -/***/ }), -/* 285 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://tc39.github.io/proposal-setmap-offrom/#sec-map.from - __webpack_require__(286)('Map'); - - -/***/ }), -/* 286 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // https://tc39.github.io/proposal-setmap-offrom/ - var $export = __webpack_require__(8); - var aFunction = __webpack_require__(21); - var ctx = __webpack_require__(20); - var forOf = __webpack_require__(207); - - module.exports = function (COLLECTION) { - $export($export.S, COLLECTION, { from: function from(source /* , mapFn, thisArg */) { - var mapFn = arguments[1]; - var mapping, A, n, cb; - aFunction(this); - mapping = mapFn !== undefined; - if (mapping) aFunction(mapFn); - if (source == undefined) return new this(); - A = []; - if (mapping) { - n = 0; - cb = ctx(mapFn, arguments[2], 2); - forOf(source, false, function (nextItem) { - A.push(cb(nextItem, n++)); - }); - } else { - forOf(source, false, A.push, A); - } - return new this(A); - } }); - }; - - -/***/ }), -/* 287 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://tc39.github.io/proposal-setmap-offrom/#sec-set.from - __webpack_require__(286)('Set'); - - -/***/ }), -/* 288 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://tc39.github.io/proposal-setmap-offrom/#sec-weakmap.from - __webpack_require__(286)('WeakMap'); - - -/***/ }), -/* 289 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://tc39.github.io/proposal-setmap-offrom/#sec-weakset.from - __webpack_require__(286)('WeakSet'); - - -/***/ }), -/* 290 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://github.com/tc39/proposal-global - var $export = __webpack_require__(8); - - $export($export.G, { global: __webpack_require__(4) }); - - -/***/ }), -/* 291 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://github.com/tc39/proposal-global - var $export = __webpack_require__(8); - - $export($export.S, 'System', { global: __webpack_require__(4) }); - - -/***/ }), -/* 292 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://github.com/ljharb/proposal-is-error - var $export = __webpack_require__(8); - var cof = __webpack_require__(34); - - $export($export.S, 'Error', { - isError: function isError(it) { - return cof(it) === 'Error'; - } - }); - - -/***/ }), -/* 293 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://rwaldron.github.io/proposal-math-extensions/ - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { - clamp: function clamp(x, lower, upper) { - return Math.min(upper, Math.max(lower, x)); - } - }); - - -/***/ }), -/* 294 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://rwaldron.github.io/proposal-math-extensions/ - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { DEG_PER_RAD: Math.PI / 180 }); - - -/***/ }), -/* 295 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://rwaldron.github.io/proposal-math-extensions/ - var $export = __webpack_require__(8); - var RAD_PER_DEG = 180 / Math.PI; - - $export($export.S, 'Math', { - degrees: function degrees(radians) { - return radians * RAD_PER_DEG; - } - }); - - -/***/ }), -/* 296 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://rwaldron.github.io/proposal-math-extensions/ - var $export = __webpack_require__(8); - var scale = __webpack_require__(297); - var fround = __webpack_require__(113); - - $export($export.S, 'Math', { - fscale: function fscale(x, inLow, inHigh, outLow, outHigh) { - return fround(scale(x, inLow, inHigh, outLow, outHigh)); - } - }); - - -/***/ }), -/* 297 */ -/***/ (function(module, exports) { - - // https://rwaldron.github.io/proposal-math-extensions/ - module.exports = Math.scale || function scale(x, inLow, inHigh, outLow, outHigh) { - if ( - arguments.length === 0 - // eslint-disable-next-line no-self-compare - || x != x - // eslint-disable-next-line no-self-compare - || inLow != inLow - // eslint-disable-next-line no-self-compare - || inHigh != inHigh - // eslint-disable-next-line no-self-compare - || outLow != outLow - // eslint-disable-next-line no-self-compare - || outHigh != outHigh - ) return NaN; - if (x === Infinity || x === -Infinity) return x; - return (x - inLow) * (outHigh - outLow) / (inHigh - inLow) + outLow; - }; - - -/***/ }), -/* 298 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://gist.github.com/BrendanEich/4294d5c212a6d2254703 - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { - iaddh: function iaddh(x0, x1, y0, y1) { - var $x0 = x0 >>> 0; - var $x1 = x1 >>> 0; - var $y0 = y0 >>> 0; - return $x1 + (y1 >>> 0) + (($x0 & $y0 | ($x0 | $y0) & ~($x0 + $y0 >>> 0)) >>> 31) | 0; - } - }); - - -/***/ }), -/* 299 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://gist.github.com/BrendanEich/4294d5c212a6d2254703 - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { - isubh: function isubh(x0, x1, y0, y1) { - var $x0 = x0 >>> 0; - var $x1 = x1 >>> 0; - var $y0 = y0 >>> 0; - return $x1 - (y1 >>> 0) - ((~$x0 & $y0 | ~($x0 ^ $y0) & $x0 - $y0 >>> 0) >>> 31) | 0; - } - }); - - -/***/ }), -/* 300 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://gist.github.com/BrendanEich/4294d5c212a6d2254703 - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { - imulh: function imulh(u, v) { - var UINT16 = 0xffff; - var $u = +u; - var $v = +v; - var u0 = $u & UINT16; - var v0 = $v & UINT16; - var u1 = $u >> 16; - var v1 = $v >> 16; - var t = (u1 * v0 >>> 0) + (u0 * v0 >>> 16); - return u1 * v1 + (t >> 16) + ((u0 * v1 >>> 0) + (t & UINT16) >> 16); - } - }); - - -/***/ }), -/* 301 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://rwaldron.github.io/proposal-math-extensions/ - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { RAD_PER_DEG: 180 / Math.PI }); - - -/***/ }), -/* 302 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://rwaldron.github.io/proposal-math-extensions/ - var $export = __webpack_require__(8); - var DEG_PER_RAD = Math.PI / 180; - - $export($export.S, 'Math', { - radians: function radians(degrees) { - return degrees * DEG_PER_RAD; - } - }); - - -/***/ }), -/* 303 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://rwaldron.github.io/proposal-math-extensions/ - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { scale: __webpack_require__(297) }); - - -/***/ }), -/* 304 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://gist.github.com/BrendanEich/4294d5c212a6d2254703 - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { - umulh: function umulh(u, v) { - var UINT16 = 0xffff; - var $u = +u; - var $v = +v; - var u0 = $u & UINT16; - var v0 = $v & UINT16; - var u1 = $u >>> 16; - var v1 = $v >>> 16; - var t = (u1 * v0 >>> 0) + (u0 * v0 >>> 16); - return u1 * v1 + (t >>> 16) + ((u0 * v1 >>> 0) + (t & UINT16) >>> 16); - } - }); - - -/***/ }), -/* 305 */ -/***/ (function(module, exports, __webpack_require__) { - - // http://jfbastien.github.io/papers/Math.signbit.html - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { signbit: function signbit(x) { - // eslint-disable-next-line no-self-compare - return (x = +x) != x ? x : x == 0 ? 1 / x == Infinity : x > 0; - } }); - - -/***/ }), -/* 306 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://github.com/tc39/proposal-promise-finally - 'use strict'; - var $export = __webpack_require__(8); - var core = __webpack_require__(9); - var global = __webpack_require__(4); - var speciesConstructor = __webpack_require__(208); - var promiseResolve = __webpack_require__(214); - - $export($export.P + $export.R, 'Promise', { 'finally': function (onFinally) { - var C = speciesConstructor(this, core.Promise || global.Promise); - var isFunction = typeof onFinally == 'function'; - return this.then( - isFunction ? function (x) { - return promiseResolve(C, onFinally()).then(function () { return x; }); - } : onFinally, - isFunction ? function (e) { - return promiseResolve(C, onFinally()).then(function () { throw e; }); - } : onFinally - ); - } }); - - -/***/ }), -/* 307 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // https://github.com/tc39/proposal-promise-try - var $export = __webpack_require__(8); - var newPromiseCapability = __webpack_require__(211); - var perform = __webpack_require__(212); - - $export($export.S, 'Promise', { 'try': function (callbackfn) { - var promiseCapability = newPromiseCapability.f(this); - var result = perform(callbackfn); - (result.e ? promiseCapability.reject : promiseCapability.resolve)(result.v); - return promiseCapability.promise; - } }); - - -/***/ }), -/* 308 */ -/***/ (function(module, exports, __webpack_require__) { - - var metadata = __webpack_require__(309); - var anObject = __webpack_require__(12); - var toMetaKey = metadata.key; - var ordinaryDefineOwnMetadata = metadata.set; - - metadata.exp({ defineMetadata: function defineMetadata(metadataKey, metadataValue, target, targetKey) { - ordinaryDefineOwnMetadata(metadataKey, metadataValue, anObject(target), toMetaKey(targetKey)); - } }); - - -/***/ }), -/* 309 */ -/***/ (function(module, exports, __webpack_require__) { - - var Map = __webpack_require__(216); - var $export = __webpack_require__(8); - var shared = __webpack_require__(23)('metadata'); - var store = shared.store || (shared.store = new (__webpack_require__(221))()); - - var getOrCreateMetadataMap = function (target, targetKey, create) { - var targetMetadata = store.get(target); - if (!targetMetadata) { - if (!create) return undefined; - store.set(target, targetMetadata = new Map()); - } - var keyMetadata = targetMetadata.get(targetKey); - if (!keyMetadata) { - if (!create) return undefined; - targetMetadata.set(targetKey, keyMetadata = new Map()); - } return keyMetadata; - }; - var ordinaryHasOwnMetadata = function (MetadataKey, O, P) { - var metadataMap = getOrCreateMetadataMap(O, P, false); - return metadataMap === undefined ? false : metadataMap.has(MetadataKey); - }; - var ordinaryGetOwnMetadata = function (MetadataKey, O, P) { - var metadataMap = getOrCreateMetadataMap(O, P, false); - return metadataMap === undefined ? undefined : metadataMap.get(MetadataKey); - }; - var ordinaryDefineOwnMetadata = function (MetadataKey, MetadataValue, O, P) { - getOrCreateMetadataMap(O, P, true).set(MetadataKey, MetadataValue); - }; - var ordinaryOwnMetadataKeys = function (target, targetKey) { - var metadataMap = getOrCreateMetadataMap(target, targetKey, false); - var keys = []; - if (metadataMap) metadataMap.forEach(function (_, key) { keys.push(key); }); - return keys; - }; - var toMetaKey = function (it) { - return it === undefined || typeof it == 'symbol' ? it : String(it); - }; - var exp = function (O) { - $export($export.S, 'Reflect', O); - }; - - module.exports = { - store: store, - map: getOrCreateMetadataMap, - has: ordinaryHasOwnMetadata, - get: ordinaryGetOwnMetadata, - set: ordinaryDefineOwnMetadata, - keys: ordinaryOwnMetadataKeys, - key: toMetaKey, - exp: exp - }; - - -/***/ }), -/* 310 */ -/***/ (function(module, exports, __webpack_require__) { - - var metadata = __webpack_require__(309); - var anObject = __webpack_require__(12); - var toMetaKey = metadata.key; - var getOrCreateMetadataMap = metadata.map; - var store = metadata.store; - - metadata.exp({ deleteMetadata: function deleteMetadata(metadataKey, target /* , targetKey */) { - var targetKey = arguments.length < 3 ? undefined : toMetaKey(arguments[2]); - var metadataMap = getOrCreateMetadataMap(anObject(target), targetKey, false); - if (metadataMap === undefined || !metadataMap['delete'](metadataKey)) return false; - if (metadataMap.size) return true; - var targetMetadata = store.get(target); - targetMetadata['delete'](targetKey); - return !!targetMetadata.size || store['delete'](target); - } }); - - -/***/ }), -/* 311 */ -/***/ (function(module, exports, __webpack_require__) { - - var metadata = __webpack_require__(309); - var anObject = __webpack_require__(12); - var getPrototypeOf = __webpack_require__(58); - var ordinaryHasOwnMetadata = metadata.has; - var ordinaryGetOwnMetadata = metadata.get; - var toMetaKey = metadata.key; - - var ordinaryGetMetadata = function (MetadataKey, O, P) { - var hasOwn = ordinaryHasOwnMetadata(MetadataKey, O, P); - if (hasOwn) return ordinaryGetOwnMetadata(MetadataKey, O, P); - var parent = getPrototypeOf(O); - return parent !== null ? ordinaryGetMetadata(MetadataKey, parent, P) : undefined; - }; - - metadata.exp({ getMetadata: function getMetadata(metadataKey, target /* , targetKey */) { - return ordinaryGetMetadata(metadataKey, anObject(target), arguments.length < 3 ? undefined : toMetaKey(arguments[2])); - } }); - - -/***/ }), -/* 312 */ -/***/ (function(module, exports, __webpack_require__) { - - var Set = __webpack_require__(220); - var from = __webpack_require__(278); - var metadata = __webpack_require__(309); - var anObject = __webpack_require__(12); - var getPrototypeOf = __webpack_require__(58); - var ordinaryOwnMetadataKeys = metadata.keys; - var toMetaKey = metadata.key; - - var ordinaryMetadataKeys = function (O, P) { - var oKeys = ordinaryOwnMetadataKeys(O, P); - var parent = getPrototypeOf(O); - if (parent === null) return oKeys; - var pKeys = ordinaryMetadataKeys(parent, P); - return pKeys.length ? oKeys.length ? from(new Set(oKeys.concat(pKeys))) : pKeys : oKeys; - }; - - metadata.exp({ getMetadataKeys: function getMetadataKeys(target /* , targetKey */) { - return ordinaryMetadataKeys(anObject(target), arguments.length < 2 ? undefined : toMetaKey(arguments[1])); - } }); - - -/***/ }), -/* 313 */ -/***/ (function(module, exports, __webpack_require__) { - - var metadata = __webpack_require__(309); - var anObject = __webpack_require__(12); - var ordinaryGetOwnMetadata = metadata.get; - var toMetaKey = metadata.key; - - metadata.exp({ getOwnMetadata: function getOwnMetadata(metadataKey, target /* , targetKey */) { - return ordinaryGetOwnMetadata(metadataKey, anObject(target) - , arguments.length < 3 ? undefined : toMetaKey(arguments[2])); - } }); - - -/***/ }), -/* 314 */ -/***/ (function(module, exports, __webpack_require__) { - - var metadata = __webpack_require__(309); - var anObject = __webpack_require__(12); - var ordinaryOwnMetadataKeys = metadata.keys; - var toMetaKey = metadata.key; - - metadata.exp({ getOwnMetadataKeys: function getOwnMetadataKeys(target /* , targetKey */) { - return ordinaryOwnMetadataKeys(anObject(target), arguments.length < 2 ? undefined : toMetaKey(arguments[1])); - } }); - - -/***/ }), -/* 315 */ -/***/ (function(module, exports, __webpack_require__) { - - var metadata = __webpack_require__(309); - var anObject = __webpack_require__(12); - var getPrototypeOf = __webpack_require__(58); - var ordinaryHasOwnMetadata = metadata.has; - var toMetaKey = metadata.key; - - var ordinaryHasMetadata = function (MetadataKey, O, P) { - var hasOwn = ordinaryHasOwnMetadata(MetadataKey, O, P); - if (hasOwn) return true; - var parent = getPrototypeOf(O); - return parent !== null ? ordinaryHasMetadata(MetadataKey, parent, P) : false; - }; - - metadata.exp({ hasMetadata: function hasMetadata(metadataKey, target /* , targetKey */) { - return ordinaryHasMetadata(metadataKey, anObject(target), arguments.length < 3 ? undefined : toMetaKey(arguments[2])); - } }); - - -/***/ }), -/* 316 */ -/***/ (function(module, exports, __webpack_require__) { - - var metadata = __webpack_require__(309); - var anObject = __webpack_require__(12); - var ordinaryHasOwnMetadata = metadata.has; - var toMetaKey = metadata.key; - - metadata.exp({ hasOwnMetadata: function hasOwnMetadata(metadataKey, target /* , targetKey */) { - return ordinaryHasOwnMetadata(metadataKey, anObject(target) - , arguments.length < 3 ? undefined : toMetaKey(arguments[2])); - } }); - - -/***/ }), -/* 317 */ -/***/ (function(module, exports, __webpack_require__) { - - var $metadata = __webpack_require__(309); - var anObject = __webpack_require__(12); - var aFunction = __webpack_require__(21); - var toMetaKey = $metadata.key; - var ordinaryDefineOwnMetadata = $metadata.set; - - $metadata.exp({ metadata: function metadata(metadataKey, metadataValue) { - return function decorator(target, targetKey) { - ordinaryDefineOwnMetadata( - metadataKey, metadataValue, - (targetKey !== undefined ? anObject : aFunction)(target), - toMetaKey(targetKey) - ); - }; - } }); - - -/***/ }), -/* 318 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://github.com/rwaldron/tc39-notes/blob/master/es6/2014-09/sept-25.md#510-globalasap-for-enqueuing-a-microtask - var $export = __webpack_require__(8); - var microtask = __webpack_require__(210)(); - var process = __webpack_require__(4).process; - var isNode = __webpack_require__(34)(process) == 'process'; - - $export($export.G, { - asap: function asap(fn) { - var domain = isNode && process.domain; - microtask(domain ? domain.bind(fn) : fn); - } - }); - - -/***/ }), -/* 319 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // https://github.com/zenparsing/es-observable - var $export = __webpack_require__(8); - var global = __webpack_require__(4); - var core = __webpack_require__(9); - var microtask = __webpack_require__(210)(); - var OBSERVABLE = __webpack_require__(26)('observable'); - var aFunction = __webpack_require__(21); - var anObject = __webpack_require__(12); - var anInstance = __webpack_require__(206); - var redefineAll = __webpack_require__(215); - var hide = __webpack_require__(10); - var forOf = __webpack_require__(207); - var RETURN = forOf.RETURN; - - var getMethod = function (fn) { - return fn == null ? undefined : aFunction(fn); - }; - - var cleanupSubscription = function (subscription) { - var cleanup = subscription._c; - if (cleanup) { - subscription._c = undefined; - cleanup(); - } - }; - - var subscriptionClosed = function (subscription) { - return subscription._o === undefined; - }; - - var closeSubscription = function (subscription) { - if (!subscriptionClosed(subscription)) { - subscription._o = undefined; - cleanupSubscription(subscription); - } - }; - - var Subscription = function (observer, subscriber) { - anObject(observer); - this._c = undefined; - this._o = observer; - observer = new SubscriptionObserver(this); - try { - var cleanup = subscriber(observer); - var subscription = cleanup; - if (cleanup != null) { - if (typeof cleanup.unsubscribe === 'function') cleanup = function () { subscription.unsubscribe(); }; - else aFunction(cleanup); - this._c = cleanup; - } - } catch (e) { - observer.error(e); - return; - } if (subscriptionClosed(this)) cleanupSubscription(this); - }; - - Subscription.prototype = redefineAll({}, { - unsubscribe: function unsubscribe() { closeSubscription(this); } - }); - - var SubscriptionObserver = function (subscription) { - this._s = subscription; - }; - - SubscriptionObserver.prototype = redefineAll({}, { - next: function next(value) { - var subscription = this._s; - if (!subscriptionClosed(subscription)) { - var observer = subscription._o; - try { - var m = getMethod(observer.next); - if (m) return m.call(observer, value); - } catch (e) { - try { - closeSubscription(subscription); - } finally { - throw e; - } - } - } - }, - error: function error(value) { - var subscription = this._s; - if (subscriptionClosed(subscription)) throw value; - var observer = subscription._o; - subscription._o = undefined; - try { - var m = getMethod(observer.error); - if (!m) throw value; - value = m.call(observer, value); - } catch (e) { - try { - cleanupSubscription(subscription); - } finally { - throw e; - } - } cleanupSubscription(subscription); - return value; - }, - complete: function complete(value) { - var subscription = this._s; - if (!subscriptionClosed(subscription)) { - var observer = subscription._o; - subscription._o = undefined; - try { - var m = getMethod(observer.complete); - value = m ? m.call(observer, value) : undefined; - } catch (e) { - try { - cleanupSubscription(subscription); - } finally { - throw e; - } - } cleanupSubscription(subscription); - return value; - } - } - }); - - var $Observable = function Observable(subscriber) { - anInstance(this, $Observable, 'Observable', '_f')._f = aFunction(subscriber); - }; - - redefineAll($Observable.prototype, { - subscribe: function subscribe(observer) { - return new Subscription(observer, this._f); - }, - forEach: function forEach(fn) { - var that = this; - return new (core.Promise || global.Promise)(function (resolve, reject) { - aFunction(fn); - var subscription = that.subscribe({ - next: function (value) { - try { - return fn(value); - } catch (e) { - reject(e); - subscription.unsubscribe(); - } - }, - error: reject, - complete: resolve - }); - }); - } - }); - - redefineAll($Observable, { - from: function from(x) { - var C = typeof this === 'function' ? this : $Observable; - var method = getMethod(anObject(x)[OBSERVABLE]); - if (method) { - var observable = anObject(method.call(x)); - return observable.constructor === C ? observable : new C(function (observer) { - return observable.subscribe(observer); - }); - } - return new C(function (observer) { - var done = false; - microtask(function () { - if (!done) { - try { - if (forOf(x, false, function (it) { - observer.next(it); - if (done) return RETURN; - }) === RETURN) return; - } catch (e) { - if (done) throw e; - observer.error(e); - return; - } observer.complete(); - } - }); - return function () { done = true; }; - }); - }, - of: function of() { - for (var i = 0, l = arguments.length, items = new Array(l); i < l;) items[i] = arguments[i++]; - return new (typeof this === 'function' ? this : $Observable)(function (observer) { - var done = false; - microtask(function () { - if (!done) { - for (var j = 0; j < items.length; ++j) { - observer.next(items[j]); - if (done) return; - } observer.complete(); - } - }); - return function () { done = true; }; - }); - } - }); - - hide($Observable.prototype, OBSERVABLE, function () { return this; }); - - $export($export.G, { Observable: $Observable }); - - __webpack_require__(193)('Observable'); - - -/***/ }), -/* 320 */ -/***/ (function(module, exports, __webpack_require__) { - - // ie9- setTimeout & setInterval additional parameters fix - var global = __webpack_require__(4); - var $export = __webpack_require__(8); - var userAgent = __webpack_require__(213); - var slice = [].slice; - var MSIE = /MSIE .\./.test(userAgent); // <- dirty ie9- check - var wrap = function (set) { - return function (fn, time /* , ...args */) { - var boundArgs = arguments.length > 2; - var args = boundArgs ? slice.call(arguments, 2) : false; - return set(boundArgs ? function () { - // eslint-disable-next-line no-new-func - (typeof fn == 'function' ? fn : Function(fn)).apply(this, args); - } : fn, time); - }; - }; - $export($export.G + $export.B + $export.F * MSIE, { - setTimeout: wrap(global.setTimeout), - setInterval: wrap(global.setInterval) - }); - - -/***/ }), -/* 321 */ -/***/ (function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8); - var $task = __webpack_require__(209); - $export($export.G + $export.B, { - setImmediate: $task.set, - clearImmediate: $task.clear - }); - - -/***/ }), -/* 322 */ -/***/ (function(module, exports, __webpack_require__) { - - var $iterators = __webpack_require__(194); - var getKeys = __webpack_require__(30); - var redefine = __webpack_require__(18); - var global = __webpack_require__(4); - var hide = __webpack_require__(10); - var Iterators = __webpack_require__(129); - var wks = __webpack_require__(26); - var ITERATOR = wks('iterator'); - var TO_STRING_TAG = wks('toStringTag'); - var ArrayValues = Iterators.Array; - - var DOMIterables = { - CSSRuleList: true, // TODO: Not spec compliant, should be false. - CSSStyleDeclaration: false, - CSSValueList: false, - ClientRectList: false, - DOMRectList: false, - DOMStringList: false, - DOMTokenList: true, - DataTransferItemList: false, - FileList: false, - HTMLAllCollection: false, - HTMLCollection: false, - HTMLFormElement: false, - HTMLSelectElement: false, - MediaList: true, // TODO: Not spec compliant, should be false. - MimeTypeArray: false, - NamedNodeMap: false, - NodeList: true, - PaintRequestList: false, - Plugin: false, - PluginArray: false, - SVGLengthList: false, - SVGNumberList: false, - SVGPathSegList: false, - SVGPointList: false, - SVGStringList: false, - SVGTransformList: false, - SourceBufferList: false, - StyleSheetList: true, // TODO: Not spec compliant, should be false. - TextTrackCueList: false, - TextTrackList: false, - TouchList: false - }; - - for (var collections = getKeys(DOMIterables), i = 0; i < collections.length; i++) { - var NAME = collections[i]; - var explicit = DOMIterables[NAME]; - var Collection = global[NAME]; - var proto = Collection && Collection.prototype; - var key; - if (proto) { - if (!proto[ITERATOR]) hide(proto, ITERATOR, ArrayValues); - if (!proto[TO_STRING_TAG]) hide(proto, TO_STRING_TAG, NAME); - Iterators[NAME] = ArrayValues; - if (explicit) for (key in $iterators) if (!proto[key]) redefine(proto, key, $iterators[key], true); - } - } - - -/***/ }), -/* 323 */ -/***/ (function(module, exports) { - - /* WEBPACK VAR INJECTION */(function(global) {/** - * Copyright (c) 2014, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * https://raw.github.com/facebook/regenerator/master/LICENSE file. An - * additional grant of patent rights can be found in the PATENTS file in - * the same directory. - */ - - !(function(global) { - "use strict"; - - var Op = Object.prototype; - var hasOwn = Op.hasOwnProperty; - var undefined; // More compressible than void 0. - var $Symbol = typeof Symbol === "function" ? Symbol : {}; - var iteratorSymbol = $Symbol.iterator || "@@iterator"; - var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator"; - var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; - - var inModule = typeof module === "object"; - var runtime = global.regeneratorRuntime; - if (runtime) { - if (inModule) { - // If regeneratorRuntime is defined globally and we're in a module, - // make the exports object identical to regeneratorRuntime. - module.exports = runtime; - } - // Don't bother evaluating the rest of this file if the runtime was - // already defined globally. - return; - } - - // Define the runtime globally (as expected by generated code) as either - // module.exports (if we're in a module) or a new, empty object. - runtime = global.regeneratorRuntime = inModule ? module.exports : {}; - - function wrap(innerFn, outerFn, self, tryLocsList) { - // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator. - var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator; - var generator = Object.create(protoGenerator.prototype); - var context = new Context(tryLocsList || []); - - // The ._invoke method unifies the implementations of the .next, - // .throw, and .return methods. - generator._invoke = makeInvokeMethod(innerFn, self, context); - - return generator; - } - runtime.wrap = wrap; - - // Try/catch helper to minimize deoptimizations. Returns a completion - // record like context.tryEntries[i].completion. This interface could - // have been (and was previously) designed to take a closure to be - // invoked without arguments, but in all the cases we care about we - // already have an existing method we want to call, so there's no need - // to create a new function object. We can even get away with assuming - // the method takes exactly one argument, since that happens to be true - // in every case, so we don't have to touch the arguments object. The - // only additional allocation required is the completion record, which - // has a stable shape and so hopefully should be cheap to allocate. - function tryCatch(fn, obj, arg) { - try { - return { type: "normal", arg: fn.call(obj, arg) }; - } catch (err) { - return { type: "throw", arg: err }; - } - } - - var GenStateSuspendedStart = "suspendedStart"; - var GenStateSuspendedYield = "suspendedYield"; - var GenStateExecuting = "executing"; - var GenStateCompleted = "completed"; - - // Returning this object from the innerFn has the same effect as - // breaking out of the dispatch switch statement. - var ContinueSentinel = {}; - - // Dummy constructor functions that we use as the .constructor and - // .constructor.prototype properties for functions that return Generator - // objects. For full spec compliance, you may wish to configure your - // minifier not to mangle the names of these two functions. - function Generator() {} - function GeneratorFunction() {} - function GeneratorFunctionPrototype() {} - - // This is a polyfill for %IteratorPrototype% for environments that - // don't natively support it. - var IteratorPrototype = {}; - IteratorPrototype[iteratorSymbol] = function () { - return this; - }; - - var getProto = Object.getPrototypeOf; - var NativeIteratorPrototype = getProto && getProto(getProto(values([]))); - if (NativeIteratorPrototype && - NativeIteratorPrototype !== Op && - hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) { - // This environment has a native %IteratorPrototype%; use it instead - // of the polyfill. - IteratorPrototype = NativeIteratorPrototype; - } - - var Gp = GeneratorFunctionPrototype.prototype = - Generator.prototype = Object.create(IteratorPrototype); - GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype; - GeneratorFunctionPrototype.constructor = GeneratorFunction; - GeneratorFunctionPrototype[toStringTagSymbol] = - GeneratorFunction.displayName = "GeneratorFunction"; - - // Helper for defining the .next, .throw, and .return methods of the - // Iterator interface in terms of a single ._invoke method. - function defineIteratorMethods(prototype) { - ["next", "throw", "return"].forEach(function(method) { - prototype[method] = function(arg) { - return this._invoke(method, arg); - }; - }); - } - - runtime.isGeneratorFunction = function(genFun) { - var ctor = typeof genFun === "function" && genFun.constructor; - return ctor - ? ctor === GeneratorFunction || - // For the native GeneratorFunction constructor, the best we can - // do is to check its .name property. - (ctor.displayName || ctor.name) === "GeneratorFunction" - : false; - }; - - runtime.mark = function(genFun) { - if (Object.setPrototypeOf) { - Object.setPrototypeOf(genFun, GeneratorFunctionPrototype); - } else { - genFun.__proto__ = GeneratorFunctionPrototype; - if (!(toStringTagSymbol in genFun)) { - genFun[toStringTagSymbol] = "GeneratorFunction"; - } - } - genFun.prototype = Object.create(Gp); - return genFun; - }; - - // Within the body of any async function, `await x` is transformed to - // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test - // `hasOwn.call(value, "__await")` to determine if the yielded value is - // meant to be awaited. - runtime.awrap = function(arg) { - return { __await: arg }; - }; - - function AsyncIterator(generator) { - function invoke(method, arg, resolve, reject) { - var record = tryCatch(generator[method], generator, arg); - if (record.type === "throw") { - reject(record.arg); - } else { - var result = record.arg; - var value = result.value; - if (value && - typeof value === "object" && - hasOwn.call(value, "__await")) { - return Promise.resolve(value.__await).then(function(value) { - invoke("next", value, resolve, reject); - }, function(err) { - invoke("throw", err, resolve, reject); - }); - } - - return Promise.resolve(value).then(function(unwrapped) { - // When a yielded Promise is resolved, its final value becomes - // the .value of the Promise<{value,done}> result for the - // current iteration. If the Promise is rejected, however, the - // result for this iteration will be rejected with the same - // reason. Note that rejections of yielded Promises are not - // thrown back into the generator function, as is the case - // when an awaited Promise is rejected. This difference in - // behavior between yield and await is important, because it - // allows the consumer to decide what to do with the yielded - // rejection (swallow it and continue, manually .throw it back - // into the generator, abandon iteration, whatever). With - // await, by contrast, there is no opportunity to examine the - // rejection reason outside the generator function, so the - // only option is to throw it from the await expression, and - // let the generator function handle the exception. - result.value = unwrapped; - resolve(result); - }, reject); - } - } - - if (typeof global.process === "object" && global.process.domain) { - invoke = global.process.domain.bind(invoke); - } - - var previousPromise; - - function enqueue(method, arg) { - function callInvokeWithMethodAndArg() { - return new Promise(function(resolve, reject) { - invoke(method, arg, resolve, reject); - }); - } - - return previousPromise = - // If enqueue has been called before, then we want to wait until - // all previous Promises have been resolved before calling invoke, - // so that results are always delivered in the correct order. If - // enqueue has not been called before, then it is important to - // call invoke immediately, without waiting on a callback to fire, - // so that the async generator function has the opportunity to do - // any necessary setup in a predictable way. This predictability - // is why the Promise constructor synchronously invokes its - // executor callback, and why async functions synchronously - // execute code before the first await. Since we implement simple - // async functions in terms of async generators, it is especially - // important to get this right, even though it requires care. - previousPromise ? previousPromise.then( - callInvokeWithMethodAndArg, - // Avoid propagating failures to Promises returned by later - // invocations of the iterator. - callInvokeWithMethodAndArg - ) : callInvokeWithMethodAndArg(); - } - - // Define the unified helper method that is used to implement .next, - // .throw, and .return (see defineIteratorMethods). - this._invoke = enqueue; - } - - defineIteratorMethods(AsyncIterator.prototype); - AsyncIterator.prototype[asyncIteratorSymbol] = function () { - return this; - }; - runtime.AsyncIterator = AsyncIterator; - - // Note that simple async functions are implemented on top of - // AsyncIterator objects; they just return a Promise for the value of - // the final result produced by the iterator. - runtime.async = function(innerFn, outerFn, self, tryLocsList) { - var iter = new AsyncIterator( - wrap(innerFn, outerFn, self, tryLocsList) - ); - - return runtime.isGeneratorFunction(outerFn) - ? iter // If outerFn is a generator, return the full iterator. - : iter.next().then(function(result) { - return result.done ? result.value : iter.next(); - }); - }; - - function makeInvokeMethod(innerFn, self, context) { - var state = GenStateSuspendedStart; - - return function invoke(method, arg) { - if (state === GenStateExecuting) { - throw new Error("Generator is already running"); - } - - if (state === GenStateCompleted) { - if (method === "throw") { - throw arg; - } - - // Be forgiving, per 25.3.3.3.3 of the spec: - // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume - return doneResult(); - } - - context.method = method; - context.arg = arg; - - while (true) { - var delegate = context.delegate; - if (delegate) { - var delegateResult = maybeInvokeDelegate(delegate, context); - if (delegateResult) { - if (delegateResult === ContinueSentinel) continue; - return delegateResult; - } - } - - if (context.method === "next") { - // Setting context._sent for legacy support of Babel's - // function.sent implementation. - context.sent = context._sent = context.arg; - - } else if (context.method === "throw") { - if (state === GenStateSuspendedStart) { - state = GenStateCompleted; - throw context.arg; - } - - context.dispatchException(context.arg); - - } else if (context.method === "return") { - context.abrupt("return", context.arg); - } - - state = GenStateExecuting; - - var record = tryCatch(innerFn, self, context); - if (record.type === "normal") { - // If an exception is thrown from innerFn, we leave state === - // GenStateExecuting and loop back for another invocation. - state = context.done - ? GenStateCompleted - : GenStateSuspendedYield; - - if (record.arg === ContinueSentinel) { - continue; - } - - return { - value: record.arg, - done: context.done - }; - - } else if (record.type === "throw") { - state = GenStateCompleted; - // Dispatch the exception by looping back around to the - // context.dispatchException(context.arg) call above. - context.method = "throw"; - context.arg = record.arg; - } - } - }; - } - - // Call delegate.iterator[context.method](context.arg) and handle the - // result, either by returning a { value, done } result from the - // delegate iterator, or by modifying context.method and context.arg, - // setting context.delegate to null, and returning the ContinueSentinel. - function maybeInvokeDelegate(delegate, context) { - var method = delegate.iterator[context.method]; - if (method === undefined) { - // A .throw or .return when the delegate iterator has no .throw - // method always terminates the yield* loop. - context.delegate = null; - - if (context.method === "throw") { - if (delegate.iterator.return) { - // If the delegate iterator has a return method, give it a - // chance to clean up. - context.method = "return"; - context.arg = undefined; - maybeInvokeDelegate(delegate, context); - - if (context.method === "throw") { - // If maybeInvokeDelegate(context) changed context.method from - // "return" to "throw", let that override the TypeError below. - return ContinueSentinel; - } - } - - context.method = "throw"; - context.arg = new TypeError( - "The iterator does not provide a 'throw' method"); - } - - return ContinueSentinel; - } - - var record = tryCatch(method, delegate.iterator, context.arg); - - if (record.type === "throw") { - context.method = "throw"; - context.arg = record.arg; - context.delegate = null; - return ContinueSentinel; - } - - var info = record.arg; - - if (! info) { - context.method = "throw"; - context.arg = new TypeError("iterator result is not an object"); - context.delegate = null; - return ContinueSentinel; - } - - if (info.done) { - // Assign the result of the finished delegate to the temporary - // variable specified by delegate.resultName (see delegateYield). - context[delegate.resultName] = info.value; - - // Resume execution at the desired location (see delegateYield). - context.next = delegate.nextLoc; - - // If context.method was "throw" but the delegate handled the - // exception, let the outer generator proceed normally. If - // context.method was "next", forget context.arg since it has been - // "consumed" by the delegate iterator. If context.method was - // "return", allow the original .return call to continue in the - // outer generator. - if (context.method !== "return") { - context.method = "next"; - context.arg = undefined; - } - - } else { - // Re-yield the result returned by the delegate method. - return info; - } - - // The delegate iterator is finished, so forget it and continue with - // the outer generator. - context.delegate = null; - return ContinueSentinel; - } - - // Define Generator.prototype.{next,throw,return} in terms of the - // unified ._invoke helper method. - defineIteratorMethods(Gp); - - Gp[toStringTagSymbol] = "Generator"; - - // A Generator should always return itself as the iterator object when the - // @@iterator function is called on it. Some browsers' implementations of the - // iterator prototype chain incorrectly implement this, causing the Generator - // object to not be returned from this call. This ensures that doesn't happen. - // See https://github.com/facebook/regenerator/issues/274 for more details. - Gp[iteratorSymbol] = function() { - return this; - }; - - Gp.toString = function() { - return "[object Generator]"; - }; - - function pushTryEntry(locs) { - var entry = { tryLoc: locs[0] }; - - if (1 in locs) { - entry.catchLoc = locs[1]; - } - - if (2 in locs) { - entry.finallyLoc = locs[2]; - entry.afterLoc = locs[3]; - } - - this.tryEntries.push(entry); - } - - function resetTryEntry(entry) { - var record = entry.completion || {}; - record.type = "normal"; - delete record.arg; - entry.completion = record; - } - - function Context(tryLocsList) { - // The root entry object (effectively a try statement without a catch - // or a finally block) gives us a place to store values thrown from - // locations where there is no enclosing try statement. - this.tryEntries = [{ tryLoc: "root" }]; - tryLocsList.forEach(pushTryEntry, this); - this.reset(true); - } - - runtime.keys = function(object) { - var keys = []; - for (var key in object) { - keys.push(key); - } - keys.reverse(); - - // Rather than returning an object with a next method, we keep - // things simple and return the next function itself. - return function next() { - while (keys.length) { - var key = keys.pop(); - if (key in object) { - next.value = key; - next.done = false; - return next; - } - } - - // To avoid creating an additional object, we just hang the .value - // and .done properties off the next function object itself. This - // also ensures that the minifier will not anonymize the function. - next.done = true; - return next; - }; - }; - - function values(iterable) { - if (iterable) { - var iteratorMethod = iterable[iteratorSymbol]; - if (iteratorMethod) { - return iteratorMethod.call(iterable); - } - - if (typeof iterable.next === "function") { - return iterable; - } - - if (!isNaN(iterable.length)) { - var i = -1, next = function next() { - while (++i < iterable.length) { - if (hasOwn.call(iterable, i)) { - next.value = iterable[i]; - next.done = false; - return next; - } - } - - next.value = undefined; - next.done = true; - - return next; - }; - - return next.next = next; - } - } - - // Return an iterator with no values. - return { next: doneResult }; - } - runtime.values = values; - - function doneResult() { - return { value: undefined, done: true }; - } - - Context.prototype = { - constructor: Context, - - reset: function(skipTempReset) { - this.prev = 0; - this.next = 0; - // Resetting context._sent for legacy support of Babel's - // function.sent implementation. - this.sent = this._sent = undefined; - this.done = false; - this.delegate = null; - - this.method = "next"; - this.arg = undefined; - - this.tryEntries.forEach(resetTryEntry); - - if (!skipTempReset) { - for (var name in this) { - // Not sure about the optimal order of these conditions: - if (name.charAt(0) === "t" && - hasOwn.call(this, name) && - !isNaN(+name.slice(1))) { - this[name] = undefined; - } - } - } - }, - - stop: function() { - this.done = true; - - var rootEntry = this.tryEntries[0]; - var rootRecord = rootEntry.completion; - if (rootRecord.type === "throw") { - throw rootRecord.arg; - } - - return this.rval; - }, - - dispatchException: function(exception) { - if (this.done) { - throw exception; - } - - var context = this; - function handle(loc, caught) { - record.type = "throw"; - record.arg = exception; - context.next = loc; - - if (caught) { - // If the dispatched exception was caught by a catch block, - // then let that catch block handle the exception normally. - context.method = "next"; - context.arg = undefined; - } - - return !! caught; - } - - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - var record = entry.completion; - - if (entry.tryLoc === "root") { - // Exception thrown outside of any try block that could handle - // it, so set the completion value of the entire function to - // throw the exception. - return handle("end"); - } - - if (entry.tryLoc <= this.prev) { - var hasCatch = hasOwn.call(entry, "catchLoc"); - var hasFinally = hasOwn.call(entry, "finallyLoc"); - - if (hasCatch && hasFinally) { - if (this.prev < entry.catchLoc) { - return handle(entry.catchLoc, true); - } else if (this.prev < entry.finallyLoc) { - return handle(entry.finallyLoc); - } - - } else if (hasCatch) { - if (this.prev < entry.catchLoc) { - return handle(entry.catchLoc, true); - } - - } else if (hasFinally) { - if (this.prev < entry.finallyLoc) { - return handle(entry.finallyLoc); - } - - } else { - throw new Error("try statement without catch or finally"); - } - } - } - }, - - abrupt: function(type, arg) { - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - if (entry.tryLoc <= this.prev && - hasOwn.call(entry, "finallyLoc") && - this.prev < entry.finallyLoc) { - var finallyEntry = entry; - break; - } - } - - if (finallyEntry && - (type === "break" || - type === "continue") && - finallyEntry.tryLoc <= arg && - arg <= finallyEntry.finallyLoc) { - // Ignore the finally entry if control is not jumping to a - // location outside the try/catch block. - finallyEntry = null; - } - - var record = finallyEntry ? finallyEntry.completion : {}; - record.type = type; - record.arg = arg; - - if (finallyEntry) { - this.method = "next"; - this.next = finallyEntry.finallyLoc; - return ContinueSentinel; - } - - return this.complete(record); - }, - - complete: function(record, afterLoc) { - if (record.type === "throw") { - throw record.arg; - } - - if (record.type === "break" || - record.type === "continue") { - this.next = record.arg; - } else if (record.type === "return") { - this.rval = this.arg = record.arg; - this.method = "return"; - this.next = "end"; - } else if (record.type === "normal" && afterLoc) { - this.next = afterLoc; - } - - return ContinueSentinel; - }, - - finish: function(finallyLoc) { - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - if (entry.finallyLoc === finallyLoc) { - this.complete(entry.completion, entry.afterLoc); - resetTryEntry(entry); - return ContinueSentinel; - } - } - }, - - "catch": function(tryLoc) { - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - if (entry.tryLoc === tryLoc) { - var record = entry.completion; - if (record.type === "throw") { - var thrown = record.arg; - resetTryEntry(entry); - } - return thrown; - } - } - - // The context.catch method must only be called with a location - // argument that corresponds to a known catch block. - throw new Error("illegal catch attempt"); - }, - - delegateYield: function(iterable, resultName, nextLoc) { - this.delegate = { - iterator: values(iterable), - resultName: resultName, - nextLoc: nextLoc - }; - - if (this.method === "next") { - // Deliberately forget the last sent value so that we don't - // accidentally pass it on to the delegate. - this.arg = undefined; - } - - return ContinueSentinel; - } - }; - })( - // Among the various tricks for obtaining a reference to the global - // object, this seems to be the most reliable technique that does not - // use indirect eval (which violates Content Security Policy). - typeof global === "object" ? global : - typeof window === "object" ? window : - typeof self === "object" ? self : this - ); - - /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) - -/***/ }), -/* 324 */ -/***/ (function(module, exports, __webpack_require__) { - - __webpack_require__(325); - module.exports = __webpack_require__(9).RegExp.escape; - - -/***/ }), -/* 325 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://github.com/benjamingr/RexExp.escape - var $export = __webpack_require__(8); - var $re = __webpack_require__(326)(/[\\^$*+?.()|[\]{}]/g, '\\$&'); - - $export($export.S, 'RegExp', { escape: function escape(it) { return $re(it); } }); - - -/***/ }), -/* 326 */ -/***/ (function(module, exports) { - - module.exports = function (regExp, replace) { - var replacer = replace === Object(replace) ? function (part) { - return replace[part]; - } : replace; - return function (it) { - return String(it).replace(regExp, replacer); - }; - }; - - -/***/ }), -/* 327 */ -/***/ (function(module, exports, __webpack_require__) { - - var BSON = __webpack_require__(328), - Binary = __webpack_require__(351), - Code = __webpack_require__(346), - DBRef = __webpack_require__(350), - Decimal128 = __webpack_require__(347), - Double = __webpack_require__(331), - Int32 = __webpack_require__(345), - Long = __webpack_require__(330), - Map = __webpack_require__(329), - MaxKey = __webpack_require__(349), - MinKey = __webpack_require__(348), - ObjectId = __webpack_require__(333), - BSONRegExp = __webpack_require__(343), - Symbol = __webpack_require__(344), - Timestamp = __webpack_require__(332); - - // BSON MAX VALUES - BSON.BSON_INT32_MAX = 0x7fffffff; - BSON.BSON_INT32_MIN = -0x80000000; - - BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; - BSON.BSON_INT64_MIN = -Math.pow(2, 63); - - // JS MAX PRECISE VALUES - BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. - BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. - - // Add BSON types to function creation - BSON.Binary = Binary; - BSON.Code = Code; - BSON.DBRef = DBRef; - BSON.Decimal128 = Decimal128; - BSON.Double = Double; - BSON.Int32 = Int32; - BSON.Long = Long; - BSON.Map = Map; - BSON.MaxKey = MaxKey; - BSON.MinKey = MinKey; - BSON.ObjectId = ObjectId; - BSON.ObjectID = ObjectId; - BSON.BSONRegExp = BSONRegExp; - BSON.Symbol = Symbol; - BSON.Timestamp = Timestamp; - - // Return the BSON - module.exports = BSON; - -/***/ }), -/* 328 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - - var Map = __webpack_require__(329), - Long = __webpack_require__(330), - Double = __webpack_require__(331), - Timestamp = __webpack_require__(332), - ObjectID = __webpack_require__(333), - BSONRegExp = __webpack_require__(343), - Symbol = __webpack_require__(344), - Int32 = __webpack_require__(345), - Code = __webpack_require__(346), - Decimal128 = __webpack_require__(347), - MinKey = __webpack_require__(348), - MaxKey = __webpack_require__(349), - DBRef = __webpack_require__(350), - Binary = __webpack_require__(351); - - // Parts of the parser - var deserialize = __webpack_require__(352), - serializer = __webpack_require__(353), - calculateObjectSize = __webpack_require__(355), - utils = __webpack_require__(339); - - /** - * @ignore - * @api private - */ - // Default Max Size - var MAXSIZE = 1024 * 1024 * 17; - - // Current Internal Temporary Serialization Buffer - var buffer = utils.allocBuffer(MAXSIZE); - - var BSON = function () {}; - - /** - * Serialize a Javascript object. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} [options.checkKeys] the serializer will check if keys are valid. - * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. - * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. - * @param {Number} [options.minInternalBufferSize=1024*1024*17] minimum size of the internal temporary serialization buffer **(default:1024*1024*17)**. - * @return {Buffer} returns the Buffer object containing the serialized object. - * @api public - */ - BSON.prototype.serialize = function serialize(object, options) { - options = options || {}; - // Unpack the options - var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; - var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; - var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; - var minInternalBufferSize = typeof options.minInternalBufferSize === 'number' ? options.minInternalBufferSize : MAXSIZE; - - // Resize the internal serialization buffer if needed - if (buffer.length < minInternalBufferSize) { - buffer = utils.allocBuffer(minInternalBufferSize); - } - - // Attempt to serialize - var serializationIndex = serializer(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, []); - // Create the final buffer - var finishedBuffer = utils.allocBuffer(serializationIndex); - // Copy into the finished buffer - buffer.copy(finishedBuffer, 0, 0, finishedBuffer.length); - // Return the buffer - return finishedBuffer; - }; - - /** - * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. - * - * @param {Object} object the Javascript object to serialize. - * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. - * @param {Boolean} [options.checkKeys] the serializer will check if keys are valid. - * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. - * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. - * @param {Number} [options.index] the index in the buffer where we wish to start serializing into. - * @return {Number} returns the index pointing to the last written byte in the buffer. - * @api public - */ - BSON.prototype.serializeWithBufferAndIndex = function (object, finalBuffer, options) { - options = options || {}; - // Unpack the options - var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; - var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; - var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; - var startIndex = typeof options.index === 'number' ? options.index : 0; - - // Attempt to serialize - var serializationIndex = serializer(finalBuffer, object, checkKeys, startIndex || 0, 0, serializeFunctions, ignoreUndefined); - - // Return the index - return serializationIndex - 1; - }; - - /** - * Deserialize data as BSON. - * - * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. - * @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized. - * @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse. - * @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function. - * @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits - * @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a node.js Buffer instance. - * @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types. - * @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer. - * @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances. - * @return {Object} returns the deserialized Javascript Object. - * @api public - */ - BSON.prototype.deserialize = function (buffer, options) { - return deserialize(buffer, options); - }; - - /** - * Calculate the bson size for a passed in Javascript object. - * - * @param {Object} object the Javascript object to calculate the BSON byte size for. - * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. - * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. - * @return {Number} returns the number of bytes the BSON object will take up. - * @api public - */ - BSON.prototype.calculateObjectSize = function (object, options) { - options = options || {}; - - var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; - var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; - - return calculateObjectSize(object, serializeFunctions, ignoreUndefined); - }; - - /** - * Deserialize stream data as BSON documents. - * - * @param {Buffer} data the buffer containing the serialized set of BSON documents. - * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. - * @param {Number} numberOfDocuments number of documents to deserialize. - * @param {Array} documents an array where to store the deserialized documents. - * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. - * @param {Object} [options] additional options used for the deserialization. - * @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized. - * @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse. - * @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function. - * @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits - * @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a node.js Buffer instance. - * @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types. - * @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer. - * @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances. - * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. - * @api public - */ - BSON.prototype.deserializeStream = function (data, startIndex, numberOfDocuments, documents, docStartIndex, options) { - options = options != null ? options : {}; - var index = startIndex; - // Loop over all documents - for (var i = 0; i < numberOfDocuments; i++) { - // Find size of the document - var size = data[index] | data[index + 1] << 8 | data[index + 2] << 16 | data[index + 3] << 24; - // Update options with index - options['index'] = index; - // Parse the document at this point - documents[docStartIndex + i] = this.deserialize(data, options); - // Adjust index by the document size - index = index + size; - } - - // Return object containing end index of parsing and list of documents - return index; - }; - - /** - * @ignore - * @api private - */ - // BSON MAX VALUES - BSON.BSON_INT32_MAX = 0x7fffffff; - BSON.BSON_INT32_MIN = -0x80000000; - - BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; - BSON.BSON_INT64_MIN = -Math.pow(2, 63); - - // JS MAX PRECISE VALUES - BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. - BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. - - // Internal long versions - // var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. - // var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. - - /** - * Number BSON Type - * - * @classconstant BSON_DATA_NUMBER - **/ - BSON.BSON_DATA_NUMBER = 1; - /** - * String BSON Type - * - * @classconstant BSON_DATA_STRING - **/ - BSON.BSON_DATA_STRING = 2; - /** - * Object BSON Type - * - * @classconstant BSON_DATA_OBJECT - **/ - BSON.BSON_DATA_OBJECT = 3; - /** - * Array BSON Type - * - * @classconstant BSON_DATA_ARRAY - **/ - BSON.BSON_DATA_ARRAY = 4; - /** - * Binary BSON Type - * - * @classconstant BSON_DATA_BINARY - **/ - BSON.BSON_DATA_BINARY = 5; - /** - * ObjectID BSON Type - * - * @classconstant BSON_DATA_OID - **/ - BSON.BSON_DATA_OID = 7; - /** - * Boolean BSON Type - * - * @classconstant BSON_DATA_BOOLEAN - **/ - BSON.BSON_DATA_BOOLEAN = 8; - /** - * Date BSON Type - * - * @classconstant BSON_DATA_DATE - **/ - BSON.BSON_DATA_DATE = 9; - /** - * null BSON Type - * - * @classconstant BSON_DATA_NULL - **/ - BSON.BSON_DATA_NULL = 10; - /** - * RegExp BSON Type - * - * @classconstant BSON_DATA_REGEXP - **/ - BSON.BSON_DATA_REGEXP = 11; - /** - * Code BSON Type - * - * @classconstant BSON_DATA_CODE - **/ - BSON.BSON_DATA_CODE = 13; - /** - * Symbol BSON Type - * - * @classconstant BSON_DATA_SYMBOL - **/ - BSON.BSON_DATA_SYMBOL = 14; - /** - * Code with Scope BSON Type - * - * @classconstant BSON_DATA_CODE_W_SCOPE - **/ - BSON.BSON_DATA_CODE_W_SCOPE = 15; - /** - * 32 bit Integer BSON Type - * - * @classconstant BSON_DATA_INT - **/ - BSON.BSON_DATA_INT = 16; - /** - * Timestamp BSON Type - * - * @classconstant BSON_DATA_TIMESTAMP - **/ - BSON.BSON_DATA_TIMESTAMP = 17; - /** - * Long BSON Type - * - * @classconstant BSON_DATA_LONG - **/ - BSON.BSON_DATA_LONG = 18; - /** - * MinKey BSON Type - * - * @classconstant BSON_DATA_MIN_KEY - **/ - BSON.BSON_DATA_MIN_KEY = 0xff; - /** - * MaxKey BSON Type - * - * @classconstant BSON_DATA_MAX_KEY - **/ - BSON.BSON_DATA_MAX_KEY = 0x7f; - - /** - * Binary Default Type - * - * @classconstant BSON_BINARY_SUBTYPE_DEFAULT - **/ - BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; - /** - * Binary Function Type - * - * @classconstant BSON_BINARY_SUBTYPE_FUNCTION - **/ - BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; - /** - * Binary Byte Array Type - * - * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY - **/ - BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; - /** - * Binary UUID Type - * - * @classconstant BSON_BINARY_SUBTYPE_UUID - **/ - BSON.BSON_BINARY_SUBTYPE_UUID = 3; - /** - * Binary MD5 Type - * - * @classconstant BSON_BINARY_SUBTYPE_MD5 - **/ - BSON.BSON_BINARY_SUBTYPE_MD5 = 4; - /** - * Binary User Defined Type - * - * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED - **/ - BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; - - // Return BSON - module.exports = BSON; - module.exports.Code = Code; - module.exports.Map = Map; - module.exports.Symbol = Symbol; - module.exports.BSON = BSON; - module.exports.DBRef = DBRef; - module.exports.Binary = Binary; - module.exports.ObjectID = ObjectID; - module.exports.Long = Long; - module.exports.Timestamp = Timestamp; - module.exports.Double = Double; - module.exports.Int32 = Int32; - module.exports.MinKey = MinKey; - module.exports.MaxKey = MaxKey; - module.exports.BSONRegExp = BSONRegExp; - module.exports.Decimal128 = Decimal128; - -/***/ }), -/* 329 */ -/***/ (function(module, exports) { - - /* WEBPACK VAR INJECTION */(function(global) {'use strict'; - - // We have an ES6 Map available, return the native instance - - if (typeof global.Map !== 'undefined') { - module.exports = global.Map; - module.exports.Map = global.Map; - } else { - // We will return a polyfill - var Map = function (array) { - this._keys = []; - this._values = {}; - - for (var i = 0; i < array.length; i++) { - if (array[i] == null) continue; // skip null and undefined - var entry = array[i]; - var key = entry[0]; - var value = entry[1]; - // Add the key to the list of keys in order - this._keys.push(key); - // Add the key and value to the values dictionary with a point - // to the location in the ordered keys list - this._values[key] = { v: value, i: this._keys.length - 1 }; - } - }; - - Map.prototype.clear = function () { - this._keys = []; - this._values = {}; - }; - - Map.prototype.delete = function (key) { - var value = this._values[key]; - if (value == null) return false; - // Delete entry - delete this._values[key]; - // Remove the key from the ordered keys list - this._keys.splice(value.i, 1); - return true; - }; - - Map.prototype.entries = function () { - var self = this; - var index = 0; - - return { - next: function () { - var key = self._keys[index++]; - return { - value: key !== undefined ? [key, self._values[key].v] : undefined, - done: key !== undefined ? false : true - }; - } - }; - }; - - Map.prototype.forEach = function (callback, self) { - self = self || this; - - for (var i = 0; i < this._keys.length; i++) { - var key = this._keys[i]; - // Call the forEach callback - callback.call(self, this._values[key].v, key, self); - } - }; - - Map.prototype.get = function (key) { - return this._values[key] ? this._values[key].v : undefined; - }; - - Map.prototype.has = function (key) { - return this._values[key] != null; - }; - - Map.prototype.keys = function () { - var self = this; - var index = 0; - - return { - next: function () { - var key = self._keys[index++]; - return { - value: key !== undefined ? key : undefined, - done: key !== undefined ? false : true - }; - } - }; - }; - - Map.prototype.set = function (key, value) { - if (this._values[key]) { - this._values[key].v = value; - return this; - } - - // Add the key to the list of keys in order - this._keys.push(key); - // Add the key and value to the values dictionary with a point - // to the location in the ordered keys list - this._values[key] = { v: value, i: this._keys.length - 1 }; - return this; - }; - - Map.prototype.values = function () { - var self = this; - var index = 0; - - return { - next: function () { - var key = self._keys[index++]; - return { - value: key !== undefined ? self._values[key].v : undefined, - done: key !== undefined ? false : true - }; - } - }; - }; - - // Last ismaster - Object.defineProperty(Map.prototype, 'size', { - enumerable: true, - get: function () { - return this._keys.length; - } - }); - - module.exports = Map; - module.exports.Map = Map; - } - /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) - -/***/ }), -/* 330 */ -/***/ (function(module, exports) { - - // Licensed under the Apache License, Version 2.0 (the "License"); - // you may not use this file except in compliance with the License. - // You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - // Copyright 2009 Google Inc. All Rights Reserved - - /** - * Defines a Long class for representing a 64-bit two's-complement - * integer value, which faithfully simulates the behavior of a Java "Long". This - * implementation is derived from LongLib in GWT. - * - * Constructs a 64-bit two's-complement integer, given its low and high 32-bit - * values as *signed* integers. See the from* functions below for more - * convenient ways of constructing Longs. - * - * The internal representation of a Long is the two given signed, 32-bit values. - * We use 32-bit pieces because these are the size of integers on which - * Javascript performs bit-operations. For operations like addition and - * multiplication, we split each number into 16-bit pieces, which can easily be - * multiplied within Javascript's floating-point representation without overflow - * or change in sign. - * - * In the algorithms below, we frequently reduce the negative case to the - * positive case by negating the input(s) and then post-processing the result. - * Note that we must ALWAYS check specially whether those values are MIN_VALUE - * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as - * a positive number, it overflows back into a negative). Not handling this - * case would often result in infinite recursion. - * - * @class - * @param {number} low the low (signed) 32 bits of the Long. - * @param {number} high the high (signed) 32 bits of the Long. - * @return {Long} - */ - function Long(low, high) { - if (!(this instanceof Long)) return new Long(low, high); - - this._bsontype = 'Long'; - /** - * @type {number} - * @ignore - */ - this.low_ = low | 0; // force into 32 signed bits. - - /** - * @type {number} - * @ignore - */ - this.high_ = high | 0; // force into 32 signed bits. - } - - /** - * Return the int value. - * - * @method - * @return {number} the value, assuming it is a 32-bit integer. - */ - Long.prototype.toInt = function () { - return this.low_; - }; - - /** - * Return the Number value. - * - * @method - * @return {number} the closest floating-point representation to this value. - */ - Long.prototype.toNumber = function () { - return this.high_ * Long.TWO_PWR_32_DBL_ + this.getLowBitsUnsigned(); - }; - - /** - * Return the JSON value. - * - * @method - * @return {string} the JSON representation. - */ - Long.prototype.toJSON = function () { - return this.toString(); - }; - - /** - * Return the String value. - * - * @method - * @param {number} [opt_radix] the radix in which the text should be written. - * @return {string} the textual representation of this value. - */ - Long.prototype.toString = function (opt_radix) { - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (this.isZero()) { - return '0'; - } - - if (this.isNegative()) { - if (this.equals(Long.MIN_VALUE)) { - // We need to change the Long value before it can be negated, so we remove - // the bottom-most digit in this base and then recurse to do the rest. - var radixLong = Long.fromNumber(radix); - var div = this.div(radixLong); - var rem = div.multiply(radixLong).subtract(this); - return div.toString(radix) + rem.toInt().toString(radix); - } else { - return '-' + this.negate().toString(radix); - } - } - - // Do several (6) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Long.fromNumber(Math.pow(radix, 6)); - - rem = this; - var result = ''; - - while (!rem.isZero()) { - var remDiv = rem.div(radixToPower); - var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); - var digits = intval.toString(radix); - - rem = remDiv; - if (rem.isZero()) { - return digits + result; - } else { - while (digits.length < 6) { - digits = '0' + digits; - } - result = '' + digits + result; - } - } - }; - - /** - * Return the high 32-bits value. - * - * @method - * @return {number} the high 32-bits as a signed value. - */ - Long.prototype.getHighBits = function () { - return this.high_; - }; - - /** - * Return the low 32-bits value. - * - * @method - * @return {number} the low 32-bits as a signed value. - */ - Long.prototype.getLowBits = function () { - return this.low_; - }; - - /** - * Return the low unsigned 32-bits value. - * - * @method - * @return {number} the low 32-bits as an unsigned value. - */ - Long.prototype.getLowBitsUnsigned = function () { - return this.low_ >= 0 ? this.low_ : Long.TWO_PWR_32_DBL_ + this.low_; - }; - - /** - * Returns the number of bits needed to represent the absolute value of this Long. - * - * @method - * @return {number} Returns the number of bits needed to represent the absolute value of this Long. - */ - Long.prototype.getNumBitsAbs = function () { - if (this.isNegative()) { - if (this.equals(Long.MIN_VALUE)) { - return 64; - } else { - return this.negate().getNumBitsAbs(); - } - } else { - var val = this.high_ !== 0 ? this.high_ : this.low_; - for (var bit = 31; bit > 0; bit--) { - if ((val & 1 << bit) !== 0) { - break; - } - } - return this.high_ !== 0 ? bit + 33 : bit + 1; - } - }; - - /** - * Return whether this value is zero. - * - * @method - * @return {boolean} whether this value is zero. - */ - Long.prototype.isZero = function () { - return this.high_ === 0 && this.low_ === 0; - }; - - /** - * Return whether this value is negative. - * - * @method - * @return {boolean} whether this value is negative. - */ - Long.prototype.isNegative = function () { - return this.high_ < 0; - }; - - /** - * Return whether this value is odd. - * - * @method - * @return {boolean} whether this value is odd. - */ - Long.prototype.isOdd = function () { - return (this.low_ & 1) === 1; - }; - - /** - * Return whether this Long equals the other - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long equals the other - */ - Long.prototype.equals = function (other) { - return this.high_ === other.high_ && this.low_ === other.low_; - }; - - /** - * Return whether this Long does not equal the other. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long does not equal the other. - */ - Long.prototype.notEquals = function (other) { - return this.high_ !== other.high_ || this.low_ !== other.low_; - }; - - /** - * Return whether this Long is less than the other. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long is less than the other. - */ - Long.prototype.lessThan = function (other) { - return this.compare(other) < 0; - }; - - /** - * Return whether this Long is less than or equal to the other. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long is less than or equal to the other. - */ - Long.prototype.lessThanOrEqual = function (other) { - return this.compare(other) <= 0; - }; - - /** - * Return whether this Long is greater than the other. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long is greater than the other. - */ - Long.prototype.greaterThan = function (other) { - return this.compare(other) > 0; - }; - - /** - * Return whether this Long is greater than or equal to the other. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long is greater than or equal to the other. - */ - Long.prototype.greaterThanOrEqual = function (other) { - return this.compare(other) >= 0; - }; - - /** - * Compares this Long with the given one. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. - */ - Long.prototype.compare = function (other) { - if (this.equals(other)) { - return 0; - } - - var thisNeg = this.isNegative(); - var otherNeg = other.isNegative(); - if (thisNeg && !otherNeg) { - return -1; - } - if (!thisNeg && otherNeg) { - return 1; - } - - // at this point, the signs are the same, so subtraction will not overflow - if (this.subtract(other).isNegative()) { - return -1; - } else { - return 1; - } - }; - - /** - * The negation of this value. - * - * @method - * @return {Long} the negation of this value. - */ - Long.prototype.negate = function () { - if (this.equals(Long.MIN_VALUE)) { - return Long.MIN_VALUE; - } else { - return this.not().add(Long.ONE); - } - }; - - /** - * Returns the sum of this and the given Long. - * - * @method - * @param {Long} other Long to add to this one. - * @return {Long} the sum of this and the given Long. - */ - Long.prototype.add = function (other) { - // Divide each number into 4 chunks of 16 bits, and then sum the chunks. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xffff; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xffff; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xffff; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xffff; - - var c48 = 0, - c32 = 0, - c16 = 0, - c00 = 0; - c00 += a00 + b00; - c16 += c00 >>> 16; - c00 &= 0xffff; - c16 += a16 + b16; - c32 += c16 >>> 16; - c16 &= 0xffff; - c32 += a32 + b32; - c48 += c32 >>> 16; - c32 &= 0xffff; - c48 += a48 + b48; - c48 &= 0xffff; - return Long.fromBits(c16 << 16 | c00, c48 << 16 | c32); - }; - - /** - * Returns the difference of this and the given Long. - * - * @method - * @param {Long} other Long to subtract from this. - * @return {Long} the difference of this and the given Long. - */ - Long.prototype.subtract = function (other) { - return this.add(other.negate()); - }; - - /** - * Returns the product of this and the given Long. - * - * @method - * @param {Long} other Long to multiply with this. - * @return {Long} the product of this and the other. - */ - Long.prototype.multiply = function (other) { - if (this.isZero()) { - return Long.ZERO; - } else if (other.isZero()) { - return Long.ZERO; - } - - if (this.equals(Long.MIN_VALUE)) { - return other.isOdd() ? Long.MIN_VALUE : Long.ZERO; - } else if (other.equals(Long.MIN_VALUE)) { - return this.isOdd() ? Long.MIN_VALUE : Long.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().multiply(other.negate()); - } else { - return this.negate().multiply(other).negate(); - } - } else if (other.isNegative()) { - return this.multiply(other.negate()).negate(); - } - - // If both Longs are small, use float multiplication - if (this.lessThan(Long.TWO_PWR_24_) && other.lessThan(Long.TWO_PWR_24_)) { - return Long.fromNumber(this.toNumber() * other.toNumber()); - } - - // Divide each Long into 4 chunks of 16 bits, and then add up 4x4 products. - // We can skip products that would overflow. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xffff; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xffff; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xffff; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xffff; - - var c48 = 0, - c32 = 0, - c16 = 0, - c00 = 0; - c00 += a00 * b00; - c16 += c00 >>> 16; - c00 &= 0xffff; - c16 += a16 * b00; - c32 += c16 >>> 16; - c16 &= 0xffff; - c16 += a00 * b16; - c32 += c16 >>> 16; - c16 &= 0xffff; - c32 += a32 * b00; - c48 += c32 >>> 16; - c32 &= 0xffff; - c32 += a16 * b16; - c48 += c32 >>> 16; - c32 &= 0xffff; - c32 += a00 * b32; - c48 += c32 >>> 16; - c32 &= 0xffff; - c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; - c48 &= 0xffff; - return Long.fromBits(c16 << 16 | c00, c48 << 16 | c32); - }; - - /** - * Returns this Long divided by the given one. - * - * @method - * @param {Long} other Long by which to divide. - * @return {Long} this Long divided by the given one. - */ - Long.prototype.div = function (other) { - if (other.isZero()) { - throw Error('division by zero'); - } else if (this.isZero()) { - return Long.ZERO; - } - - if (this.equals(Long.MIN_VALUE)) { - if (other.equals(Long.ONE) || other.equals(Long.NEG_ONE)) { - return Long.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE - } else if (other.equals(Long.MIN_VALUE)) { - return Long.ONE; - } else { - // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. - var halfThis = this.shiftRight(1); - var approx = halfThis.div(other).shiftLeft(1); - if (approx.equals(Long.ZERO)) { - return other.isNegative() ? Long.ONE : Long.NEG_ONE; - } else { - var rem = this.subtract(other.multiply(approx)); - var result = approx.add(rem.div(other)); - return result; - } - } - } else if (other.equals(Long.MIN_VALUE)) { - return Long.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().div(other.negate()); - } else { - return this.negate().div(other).negate(); - } - } else if (other.isNegative()) { - return this.div(other.negate()).negate(); - } - - // Repeat the following until the remainder is less than other: find a - // floating-point that approximates remainder / other *from below*, add this - // into the result, and subtract it from the remainder. It is critical that - // the approximate value is less than or equal to the real value so that the - // remainder never becomes negative. - var res = Long.ZERO; - rem = this; - while (rem.greaterThanOrEqual(other)) { - // Approximate the result of division. This may be a little greater or - // smaller than the actual value. - approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); - - // We will tweak the approximate result by changing it in the 48-th digit or - // the smallest non-fractional digit, whichever is larger. - var log2 = Math.ceil(Math.log(approx) / Math.LN2); - var delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48); - - // Decrease the approximation until it is smaller than the remainder. Note - // that if it is too large, the product overflows and is negative. - var approxRes = Long.fromNumber(approx); - var approxRem = approxRes.multiply(other); - while (approxRem.isNegative() || approxRem.greaterThan(rem)) { - approx -= delta; - approxRes = Long.fromNumber(approx); - approxRem = approxRes.multiply(other); - } - - // We know the answer can't be zero... and actually, zero would cause - // infinite recursion since we would make no progress. - if (approxRes.isZero()) { - approxRes = Long.ONE; - } - - res = res.add(approxRes); - rem = rem.subtract(approxRem); - } - return res; - }; - - /** - * Returns this Long modulo the given one. - * - * @method - * @param {Long} other Long by which to mod. - * @return {Long} this Long modulo the given one. - */ - Long.prototype.modulo = function (other) { - return this.subtract(this.div(other).multiply(other)); - }; - - /** - * The bitwise-NOT of this value. - * - * @method - * @return {Long} the bitwise-NOT of this value. - */ - Long.prototype.not = function () { - return Long.fromBits(~this.low_, ~this.high_); - }; - - /** - * Returns the bitwise-AND of this Long and the given one. - * - * @method - * @param {Long} other the Long with which to AND. - * @return {Long} the bitwise-AND of this and the other. - */ - Long.prototype.and = function (other) { - return Long.fromBits(this.low_ & other.low_, this.high_ & other.high_); - }; - - /** - * Returns the bitwise-OR of this Long and the given one. - * - * @method - * @param {Long} other the Long with which to OR. - * @return {Long} the bitwise-OR of this and the other. - */ - Long.prototype.or = function (other) { - return Long.fromBits(this.low_ | other.low_, this.high_ | other.high_); - }; - - /** - * Returns the bitwise-XOR of this Long and the given one. - * - * @method - * @param {Long} other the Long with which to XOR. - * @return {Long} the bitwise-XOR of this and the other. - */ - Long.prototype.xor = function (other) { - return Long.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); - }; - - /** - * Returns this Long with bits shifted to the left by the given amount. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Long} this shifted to the left by the given amount. - */ - Long.prototype.shiftLeft = function (numBits) { - numBits &= 63; - if (numBits === 0) { - return this; - } else { - var low = this.low_; - if (numBits < 32) { - var high = this.high_; - return Long.fromBits(low << numBits, high << numBits | low >>> 32 - numBits); - } else { - return Long.fromBits(0, low << numBits - 32); - } - } - }; - - /** - * Returns this Long with bits shifted to the right by the given amount. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Long} this shifted to the right by the given amount. - */ - Long.prototype.shiftRight = function (numBits) { - numBits &= 63; - if (numBits === 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Long.fromBits(low >>> numBits | high << 32 - numBits, high >> numBits); - } else { - return Long.fromBits(high >> numBits - 32, high >= 0 ? 0 : -1); - } - } - }; - - /** - * Returns this Long with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Long} this shifted to the right by the given amount, with zeros placed into the new leading bits. - */ - Long.prototype.shiftRightUnsigned = function (numBits) { - numBits &= 63; - if (numBits === 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Long.fromBits(low >>> numBits | high << 32 - numBits, high >>> numBits); - } else if (numBits === 32) { - return Long.fromBits(high, 0); - } else { - return Long.fromBits(high >>> numBits - 32, 0); - } - } - }; - - /** - * Returns a Long representing the given (32-bit) integer value. - * - * @method - * @param {number} value the 32-bit integer in question. - * @return {Long} the corresponding Long value. - */ - Long.fromInt = function (value) { - if (-128 <= value && value < 128) { - var cachedObj = Long.INT_CACHE_[value]; - if (cachedObj) { - return cachedObj; - } - } - - var obj = new Long(value | 0, value < 0 ? -1 : 0); - if (-128 <= value && value < 128) { - Long.INT_CACHE_[value] = obj; - } - return obj; - }; - - /** - * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. - * - * @method - * @param {number} value the number in question. - * @return {Long} the corresponding Long value. - */ - Long.fromNumber = function (value) { - if (isNaN(value) || !isFinite(value)) { - return Long.ZERO; - } else if (value <= -Long.TWO_PWR_63_DBL_) { - return Long.MIN_VALUE; - } else if (value + 1 >= Long.TWO_PWR_63_DBL_) { - return Long.MAX_VALUE; - } else if (value < 0) { - return Long.fromNumber(-value).negate(); - } else { - return new Long(value % Long.TWO_PWR_32_DBL_ | 0, value / Long.TWO_PWR_32_DBL_ | 0); - } - }; - - /** - * Returns a Long representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. - * - * @method - * @param {number} lowBits the low 32-bits. - * @param {number} highBits the high 32-bits. - * @return {Long} the corresponding Long value. - */ - Long.fromBits = function (lowBits, highBits) { - return new Long(lowBits, highBits); - }; - - /** - * Returns a Long representation of the given string, written using the given radix. - * - * @method - * @param {string} str the textual representation of the Long. - * @param {number} opt_radix the radix in which the text is written. - * @return {Long} the corresponding Long value. - */ - Long.fromString = function (str, opt_radix) { - if (str.length === 0) { - throw Error('number format error: empty string'); - } - - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (str.charAt(0) === '-') { - return Long.fromString(str.substring(1), radix).negate(); - } else if (str.indexOf('-') >= 0) { - throw Error('number format error: interior "-" character: ' + str); - } - - // Do several (8) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Long.fromNumber(Math.pow(radix, 8)); - - var result = Long.ZERO; - for (var i = 0; i < str.length; i += 8) { - var size = Math.min(8, str.length - i); - var value = parseInt(str.substring(i, i + size), radix); - if (size < 8) { - var power = Long.fromNumber(Math.pow(radix, size)); - result = result.multiply(power).add(Long.fromNumber(value)); - } else { - result = result.multiply(radixToPower); - result = result.add(Long.fromNumber(value)); - } - } - return result; - }; - - // NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the - // from* methods on which they depend. - - /** - * A cache of the Long representations of small integer values. - * @type {Object} - * @ignore - */ - Long.INT_CACHE_ = {}; - - // NOTE: the compiler should inline these constant values below and then remove - // these variables, so there should be no runtime penalty for these. - - /** - * Number used repeated below in calculations. This must appear before the - * first call to any from* function below. - * @type {number} - * @ignore - */ - Long.TWO_PWR_16_DBL_ = 1 << 16; - - /** - * @type {number} - * @ignore - */ - Long.TWO_PWR_24_DBL_ = 1 << 24; - - /** - * @type {number} - * @ignore - */ - Long.TWO_PWR_32_DBL_ = Long.TWO_PWR_16_DBL_ * Long.TWO_PWR_16_DBL_; - - /** - * @type {number} - * @ignore - */ - Long.TWO_PWR_31_DBL_ = Long.TWO_PWR_32_DBL_ / 2; - - /** - * @type {number} - * @ignore - */ - Long.TWO_PWR_48_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_16_DBL_; - - /** - * @type {number} - * @ignore - */ - Long.TWO_PWR_64_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_32_DBL_; - - /** - * @type {number} - * @ignore - */ - Long.TWO_PWR_63_DBL_ = Long.TWO_PWR_64_DBL_ / 2; - - /** @type {Long} */ - Long.ZERO = Long.fromInt(0); - - /** @type {Long} */ - Long.ONE = Long.fromInt(1); - - /** @type {Long} */ - Long.NEG_ONE = Long.fromInt(-1); - - /** @type {Long} */ - Long.MAX_VALUE = Long.fromBits(0xffffffff | 0, 0x7fffffff | 0); - - /** @type {Long} */ - Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0); - - /** - * @type {Long} - * @ignore - */ - Long.TWO_PWR_24_ = Long.fromInt(1 << 24); - - /** - * Expose. - */ - module.exports = Long; - module.exports.Long = Long; - -/***/ }), -/* 331 */ -/***/ (function(module, exports) { - - /** - * A class representation of the BSON Double type. - * - * @class - * @param {number} value the number we want to represent as a double. - * @return {Double} - */ - function Double(value) { - if (!(this instanceof Double)) return new Double(value); - - this._bsontype = 'Double'; - this.value = value; - } - - /** - * Access the number value. - * - * @method - * @return {number} returns the wrapped double number. - */ - Double.prototype.valueOf = function () { - return this.value; - }; - - /** - * @ignore - */ - Double.prototype.toJSON = function () { - return this.value; - }; - - module.exports = Double; - module.exports.Double = Double; - -/***/ }), -/* 332 */ -/***/ (function(module, exports) { - - // Licensed under the Apache License, Version 2.0 (the "License"); - // you may not use this file except in compliance with the License. - // You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - // Copyright 2009 Google Inc. All Rights Reserved - - /** - * This type is for INTERNAL use in MongoDB only and should not be used in applications. - * The appropriate corresponding type is the JavaScript Date type. - * - * Defines a Timestamp class for representing a 64-bit two's-complement - * integer value, which faithfully simulates the behavior of a Java "Timestamp". This - * implementation is derived from TimestampLib in GWT. - * - * Constructs a 64-bit two's-complement integer, given its low and high 32-bit - * values as *signed* integers. See the from* functions below for more - * convenient ways of constructing Timestamps. - * - * The internal representation of a Timestamp is the two given signed, 32-bit values. - * We use 32-bit pieces because these are the size of integers on which - * Javascript performs bit-operations. For operations like addition and - * multiplication, we split each number into 16-bit pieces, which can easily be - * multiplied within Javascript's floating-point representation without overflow - * or change in sign. - * - * In the algorithms below, we frequently reduce the negative case to the - * positive case by negating the input(s) and then post-processing the result. - * Note that we must ALWAYS check specially whether those values are MIN_VALUE - * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as - * a positive number, it overflows back into a negative). Not handling this - * case would often result in infinite recursion. - * - * @class - * @param {number} low the low (signed) 32 bits of the Timestamp. - * @param {number} high the high (signed) 32 bits of the Timestamp. - */ - function Timestamp(low, high) { - if (!(this instanceof Timestamp)) return new Timestamp(low, high); - this._bsontype = 'Timestamp'; - /** - * @type {number} - * @ignore - */ - this.low_ = low | 0; // force into 32 signed bits. - - /** - * @type {number} - * @ignore - */ - this.high_ = high | 0; // force into 32 signed bits. - } - - /** - * Return the int value. - * - * @return {number} the value, assuming it is a 32-bit integer. - */ - Timestamp.prototype.toInt = function () { - return this.low_; - }; - - /** - * Return the Number value. - * - * @method - * @return {number} the closest floating-point representation to this value. - */ - Timestamp.prototype.toNumber = function () { - return this.high_ * Timestamp.TWO_PWR_32_DBL_ + this.getLowBitsUnsigned(); - }; - - /** - * Return the JSON value. - * - * @method - * @return {string} the JSON representation. - */ - Timestamp.prototype.toJSON = function () { - return this.toString(); - }; - - /** - * Return the String value. - * - * @method - * @param {number} [opt_radix] the radix in which the text should be written. - * @return {string} the textual representation of this value. - */ - Timestamp.prototype.toString = function (opt_radix) { - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (this.isZero()) { - return '0'; - } - - if (this.isNegative()) { - if (this.equals(Timestamp.MIN_VALUE)) { - // We need to change the Timestamp value before it can be negated, so we remove - // the bottom-most digit in this base and then recurse to do the rest. - var radixTimestamp = Timestamp.fromNumber(radix); - var div = this.div(radixTimestamp); - var rem = div.multiply(radixTimestamp).subtract(this); - return div.toString(radix) + rem.toInt().toString(radix); - } else { - return '-' + this.negate().toString(radix); - } - } - - // Do several (6) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Timestamp.fromNumber(Math.pow(radix, 6)); - - rem = this; - var result = ''; - - while (!rem.isZero()) { - var remDiv = rem.div(radixToPower); - var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); - var digits = intval.toString(radix); - - rem = remDiv; - if (rem.isZero()) { - return digits + result; - } else { - while (digits.length < 6) { - digits = '0' + digits; - } - result = '' + digits + result; - } - } - }; - - /** - * Return the high 32-bits value. - * - * @method - * @return {number} the high 32-bits as a signed value. - */ - Timestamp.prototype.getHighBits = function () { - return this.high_; - }; - - /** - * Return the low 32-bits value. - * - * @method - * @return {number} the low 32-bits as a signed value. - */ - Timestamp.prototype.getLowBits = function () { - return this.low_; - }; - - /** - * Return the low unsigned 32-bits value. - * - * @method - * @return {number} the low 32-bits as an unsigned value. - */ - Timestamp.prototype.getLowBitsUnsigned = function () { - return this.low_ >= 0 ? this.low_ : Timestamp.TWO_PWR_32_DBL_ + this.low_; - }; - - /** - * Returns the number of bits needed to represent the absolute value of this Timestamp. - * - * @method - * @return {number} Returns the number of bits needed to represent the absolute value of this Timestamp. - */ - Timestamp.prototype.getNumBitsAbs = function () { - if (this.isNegative()) { - if (this.equals(Timestamp.MIN_VALUE)) { - return 64; - } else { - return this.negate().getNumBitsAbs(); - } - } else { - var val = this.high_ !== 0 ? this.high_ : this.low_; - for (var bit = 31; bit > 0; bit--) { - if ((val & 1 << bit) !== 0) { - break; - } - } - return this.high_ !== 0 ? bit + 33 : bit + 1; - } - }; - - /** - * Return whether this value is zero. - * - * @method - * @return {boolean} whether this value is zero. - */ - Timestamp.prototype.isZero = function () { - return this.high_ === 0 && this.low_ === 0; - }; - - /** - * Return whether this value is negative. - * - * @method - * @return {boolean} whether this value is negative. - */ - Timestamp.prototype.isNegative = function () { - return this.high_ < 0; - }; - - /** - * Return whether this value is odd. - * - * @method - * @return {boolean} whether this value is odd. - */ - Timestamp.prototype.isOdd = function () { - return (this.low_ & 1) === 1; - }; - - /** - * Return whether this Timestamp equals the other - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp equals the other - */ - Timestamp.prototype.equals = function (other) { - return this.high_ === other.high_ && this.low_ === other.low_; - }; - - /** - * Return whether this Timestamp does not equal the other. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp does not equal the other. - */ - Timestamp.prototype.notEquals = function (other) { - return this.high_ !== other.high_ || this.low_ !== other.low_; - }; - - /** - * Return whether this Timestamp is less than the other. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp is less than the other. - */ - Timestamp.prototype.lessThan = function (other) { - return this.compare(other) < 0; - }; - - /** - * Return whether this Timestamp is less than or equal to the other. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp is less than or equal to the other. - */ - Timestamp.prototype.lessThanOrEqual = function (other) { - return this.compare(other) <= 0; - }; - - /** - * Return whether this Timestamp is greater than the other. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp is greater than the other. - */ - Timestamp.prototype.greaterThan = function (other) { - return this.compare(other) > 0; - }; - - /** - * Return whether this Timestamp is greater than or equal to the other. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp is greater than or equal to the other. - */ - Timestamp.prototype.greaterThanOrEqual = function (other) { - return this.compare(other) >= 0; - }; - - /** - * Compares this Timestamp with the given one. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. - */ - Timestamp.prototype.compare = function (other) { - if (this.equals(other)) { - return 0; - } - - var thisNeg = this.isNegative(); - var otherNeg = other.isNegative(); - if (thisNeg && !otherNeg) { - return -1; - } - if (!thisNeg && otherNeg) { - return 1; - } - - // at this point, the signs are the same, so subtraction will not overflow - if (this.subtract(other).isNegative()) { - return -1; - } else { - return 1; - } - }; - - /** - * The negation of this value. - * - * @method - * @return {Timestamp} the negation of this value. - */ - Timestamp.prototype.negate = function () { - if (this.equals(Timestamp.MIN_VALUE)) { - return Timestamp.MIN_VALUE; - } else { - return this.not().add(Timestamp.ONE); - } - }; - - /** - * Returns the sum of this and the given Timestamp. - * - * @method - * @param {Timestamp} other Timestamp to add to this one. - * @return {Timestamp} the sum of this and the given Timestamp. - */ - Timestamp.prototype.add = function (other) { - // Divide each number into 4 chunks of 16 bits, and then sum the chunks. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xffff; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xffff; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xffff; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xffff; - - var c48 = 0, - c32 = 0, - c16 = 0, - c00 = 0; - c00 += a00 + b00; - c16 += c00 >>> 16; - c00 &= 0xffff; - c16 += a16 + b16; - c32 += c16 >>> 16; - c16 &= 0xffff; - c32 += a32 + b32; - c48 += c32 >>> 16; - c32 &= 0xffff; - c48 += a48 + b48; - c48 &= 0xffff; - return Timestamp.fromBits(c16 << 16 | c00, c48 << 16 | c32); - }; - - /** - * Returns the difference of this and the given Timestamp. - * - * @method - * @param {Timestamp} other Timestamp to subtract from this. - * @return {Timestamp} the difference of this and the given Timestamp. - */ - Timestamp.prototype.subtract = function (other) { - return this.add(other.negate()); - }; - - /** - * Returns the product of this and the given Timestamp. - * - * @method - * @param {Timestamp} other Timestamp to multiply with this. - * @return {Timestamp} the product of this and the other. - */ - Timestamp.prototype.multiply = function (other) { - if (this.isZero()) { - return Timestamp.ZERO; - } else if (other.isZero()) { - return Timestamp.ZERO; - } - - if (this.equals(Timestamp.MIN_VALUE)) { - return other.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; - } else if (other.equals(Timestamp.MIN_VALUE)) { - return this.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().multiply(other.negate()); - } else { - return this.negate().multiply(other).negate(); - } - } else if (other.isNegative()) { - return this.multiply(other.negate()).negate(); - } - - // If both Timestamps are small, use float multiplication - if (this.lessThan(Timestamp.TWO_PWR_24_) && other.lessThan(Timestamp.TWO_PWR_24_)) { - return Timestamp.fromNumber(this.toNumber() * other.toNumber()); - } - - // Divide each Timestamp into 4 chunks of 16 bits, and then add up 4x4 products. - // We can skip products that would overflow. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xffff; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xffff; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xffff; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xffff; - - var c48 = 0, - c32 = 0, - c16 = 0, - c00 = 0; - c00 += a00 * b00; - c16 += c00 >>> 16; - c00 &= 0xffff; - c16 += a16 * b00; - c32 += c16 >>> 16; - c16 &= 0xffff; - c16 += a00 * b16; - c32 += c16 >>> 16; - c16 &= 0xffff; - c32 += a32 * b00; - c48 += c32 >>> 16; - c32 &= 0xffff; - c32 += a16 * b16; - c48 += c32 >>> 16; - c32 &= 0xffff; - c32 += a00 * b32; - c48 += c32 >>> 16; - c32 &= 0xffff; - c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; - c48 &= 0xffff; - return Timestamp.fromBits(c16 << 16 | c00, c48 << 16 | c32); - }; - - /** - * Returns this Timestamp divided by the given one. - * - * @method - * @param {Timestamp} other Timestamp by which to divide. - * @return {Timestamp} this Timestamp divided by the given one. - */ - Timestamp.prototype.div = function (other) { - if (other.isZero()) { - throw Error('division by zero'); - } else if (this.isZero()) { - return Timestamp.ZERO; - } - - if (this.equals(Timestamp.MIN_VALUE)) { - if (other.equals(Timestamp.ONE) || other.equals(Timestamp.NEG_ONE)) { - return Timestamp.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE - } else if (other.equals(Timestamp.MIN_VALUE)) { - return Timestamp.ONE; - } else { - // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. - var halfThis = this.shiftRight(1); - var approx = halfThis.div(other).shiftLeft(1); - if (approx.equals(Timestamp.ZERO)) { - return other.isNegative() ? Timestamp.ONE : Timestamp.NEG_ONE; - } else { - var rem = this.subtract(other.multiply(approx)); - var result = approx.add(rem.div(other)); - return result; - } - } - } else if (other.equals(Timestamp.MIN_VALUE)) { - return Timestamp.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().div(other.negate()); - } else { - return this.negate().div(other).negate(); - } - } else if (other.isNegative()) { - return this.div(other.negate()).negate(); - } - - // Repeat the following until the remainder is less than other: find a - // floating-point that approximates remainder / other *from below*, add this - // into the result, and subtract it from the remainder. It is critical that - // the approximate value is less than or equal to the real value so that the - // remainder never becomes negative. - var res = Timestamp.ZERO; - rem = this; - while (rem.greaterThanOrEqual(other)) { - // Approximate the result of division. This may be a little greater or - // smaller than the actual value. - approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); - - // We will tweak the approximate result by changing it in the 48-th digit or - // the smallest non-fractional digit, whichever is larger. - var log2 = Math.ceil(Math.log(approx) / Math.LN2); - var delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48); - - // Decrease the approximation until it is smaller than the remainder. Note - // that if it is too large, the product overflows and is negative. - var approxRes = Timestamp.fromNumber(approx); - var approxRem = approxRes.multiply(other); - while (approxRem.isNegative() || approxRem.greaterThan(rem)) { - approx -= delta; - approxRes = Timestamp.fromNumber(approx); - approxRem = approxRes.multiply(other); - } - - // We know the answer can't be zero... and actually, zero would cause - // infinite recursion since we would make no progress. - if (approxRes.isZero()) { - approxRes = Timestamp.ONE; - } - - res = res.add(approxRes); - rem = rem.subtract(approxRem); - } - return res; - }; - - /** - * Returns this Timestamp modulo the given one. - * - * @method - * @param {Timestamp} other Timestamp by which to mod. - * @return {Timestamp} this Timestamp modulo the given one. - */ - Timestamp.prototype.modulo = function (other) { - return this.subtract(this.div(other).multiply(other)); - }; - - /** - * The bitwise-NOT of this value. - * - * @method - * @return {Timestamp} the bitwise-NOT of this value. - */ - Timestamp.prototype.not = function () { - return Timestamp.fromBits(~this.low_, ~this.high_); - }; - - /** - * Returns the bitwise-AND of this Timestamp and the given one. - * - * @method - * @param {Timestamp} other the Timestamp with which to AND. - * @return {Timestamp} the bitwise-AND of this and the other. - */ - Timestamp.prototype.and = function (other) { - return Timestamp.fromBits(this.low_ & other.low_, this.high_ & other.high_); - }; - - /** - * Returns the bitwise-OR of this Timestamp and the given one. - * - * @method - * @param {Timestamp} other the Timestamp with which to OR. - * @return {Timestamp} the bitwise-OR of this and the other. - */ - Timestamp.prototype.or = function (other) { - return Timestamp.fromBits(this.low_ | other.low_, this.high_ | other.high_); - }; - - /** - * Returns the bitwise-XOR of this Timestamp and the given one. - * - * @method - * @param {Timestamp} other the Timestamp with which to XOR. - * @return {Timestamp} the bitwise-XOR of this and the other. - */ - Timestamp.prototype.xor = function (other) { - return Timestamp.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); - }; - - /** - * Returns this Timestamp with bits shifted to the left by the given amount. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Timestamp} this shifted to the left by the given amount. - */ - Timestamp.prototype.shiftLeft = function (numBits) { - numBits &= 63; - if (numBits === 0) { - return this; - } else { - var low = this.low_; - if (numBits < 32) { - var high = this.high_; - return Timestamp.fromBits(low << numBits, high << numBits | low >>> 32 - numBits); - } else { - return Timestamp.fromBits(0, low << numBits - 32); - } - } - }; - - /** - * Returns this Timestamp with bits shifted to the right by the given amount. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Timestamp} this shifted to the right by the given amount. - */ - Timestamp.prototype.shiftRight = function (numBits) { - numBits &= 63; - if (numBits === 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Timestamp.fromBits(low >>> numBits | high << 32 - numBits, high >> numBits); - } else { - return Timestamp.fromBits(high >> numBits - 32, high >= 0 ? 0 : -1); - } - } - }; - - /** - * Returns this Timestamp with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Timestamp} this shifted to the right by the given amount, with zeros placed into the new leading bits. - */ - Timestamp.prototype.shiftRightUnsigned = function (numBits) { - numBits &= 63; - if (numBits === 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Timestamp.fromBits(low >>> numBits | high << 32 - numBits, high >>> numBits); - } else if (numBits === 32) { - return Timestamp.fromBits(high, 0); - } else { - return Timestamp.fromBits(high >>> numBits - 32, 0); - } - } - }; - - /** - * Returns a Timestamp representing the given (32-bit) integer value. - * - * @method - * @param {number} value the 32-bit integer in question. - * @return {Timestamp} the corresponding Timestamp value. - */ - Timestamp.fromInt = function (value) { - if (-128 <= value && value < 128) { - var cachedObj = Timestamp.INT_CACHE_[value]; - if (cachedObj) { - return cachedObj; - } - } - - var obj = new Timestamp(value | 0, value < 0 ? -1 : 0); - if (-128 <= value && value < 128) { - Timestamp.INT_CACHE_[value] = obj; - } - return obj; - }; - - /** - * Returns a Timestamp representing the given value, provided that it is a finite number. Otherwise, zero is returned. - * - * @method - * @param {number} value the number in question. - * @return {Timestamp} the corresponding Timestamp value. - */ - Timestamp.fromNumber = function (value) { - if (isNaN(value) || !isFinite(value)) { - return Timestamp.ZERO; - } else if (value <= -Timestamp.TWO_PWR_63_DBL_) { - return Timestamp.MIN_VALUE; - } else if (value + 1 >= Timestamp.TWO_PWR_63_DBL_) { - return Timestamp.MAX_VALUE; - } else if (value < 0) { - return Timestamp.fromNumber(-value).negate(); - } else { - return new Timestamp(value % Timestamp.TWO_PWR_32_DBL_ | 0, value / Timestamp.TWO_PWR_32_DBL_ | 0); - } - }; - - /** - * Returns a Timestamp representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. - * - * @method - * @param {number} lowBits the low 32-bits. - * @param {number} highBits the high 32-bits. - * @return {Timestamp} the corresponding Timestamp value. - */ - Timestamp.fromBits = function (lowBits, highBits) { - return new Timestamp(lowBits, highBits); - }; - - /** - * Returns a Timestamp representation of the given string, written using the given radix. - * - * @method - * @param {string} str the textual representation of the Timestamp. - * @param {number} opt_radix the radix in which the text is written. - * @return {Timestamp} the corresponding Timestamp value. - */ - Timestamp.fromString = function (str, opt_radix) { - if (str.length === 0) { - throw Error('number format error: empty string'); - } - - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (str.charAt(0) === '-') { - return Timestamp.fromString(str.substring(1), radix).negate(); - } else if (str.indexOf('-') >= 0) { - throw Error('number format error: interior "-" character: ' + str); - } - - // Do several (8) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Timestamp.fromNumber(Math.pow(radix, 8)); - - var result = Timestamp.ZERO; - for (var i = 0; i < str.length; i += 8) { - var size = Math.min(8, str.length - i); - var value = parseInt(str.substring(i, i + size), radix); - if (size < 8) { - var power = Timestamp.fromNumber(Math.pow(radix, size)); - result = result.multiply(power).add(Timestamp.fromNumber(value)); - } else { - result = result.multiply(radixToPower); - result = result.add(Timestamp.fromNumber(value)); - } - } - return result; - }; - - // NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the - // from* methods on which they depend. - - /** - * A cache of the Timestamp representations of small integer values. - * @type {Object} - * @ignore - */ - Timestamp.INT_CACHE_ = {}; - - // NOTE: the compiler should inline these constant values below and then remove - // these variables, so there should be no runtime penalty for these. - - /** - * Number used repeated below in calculations. This must appear before the - * first call to any from* function below. - * @type {number} - * @ignore - */ - Timestamp.TWO_PWR_16_DBL_ = 1 << 16; - - /** - * @type {number} - * @ignore - */ - Timestamp.TWO_PWR_24_DBL_ = 1 << 24; - - /** - * @type {number} - * @ignore - */ - Timestamp.TWO_PWR_32_DBL_ = Timestamp.TWO_PWR_16_DBL_ * Timestamp.TWO_PWR_16_DBL_; - - /** - * @type {number} - * @ignore - */ - Timestamp.TWO_PWR_31_DBL_ = Timestamp.TWO_PWR_32_DBL_ / 2; - - /** - * @type {number} - * @ignore - */ - Timestamp.TWO_PWR_48_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_16_DBL_; - - /** - * @type {number} - * @ignore - */ - Timestamp.TWO_PWR_64_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_32_DBL_; - - /** - * @type {number} - * @ignore - */ - Timestamp.TWO_PWR_63_DBL_ = Timestamp.TWO_PWR_64_DBL_ / 2; - - /** @type {Timestamp} */ - Timestamp.ZERO = Timestamp.fromInt(0); - - /** @type {Timestamp} */ - Timestamp.ONE = Timestamp.fromInt(1); - - /** @type {Timestamp} */ - Timestamp.NEG_ONE = Timestamp.fromInt(-1); - - /** @type {Timestamp} */ - Timestamp.MAX_VALUE = Timestamp.fromBits(0xffffffff | 0, 0x7fffffff | 0); - - /** @type {Timestamp} */ - Timestamp.MIN_VALUE = Timestamp.fromBits(0, 0x80000000 | 0); - - /** - * @type {Timestamp} - * @ignore - */ - Timestamp.TWO_PWR_24_ = Timestamp.fromInt(1 << 24); - - /** - * Expose. - */ - module.exports = Timestamp; - module.exports.Timestamp = Timestamp; - -/***/ }), -/* 333 */ -/***/ (function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(Buffer, process) {// Custom inspect property name / symbol. - var inspect = 'inspect'; - - var utils = __webpack_require__(339); - - /** - * Machine id. - * - * Create a random 3-byte value (i.e. unique for this - * process). Other drivers use a md5 of the machine id here, but - * that would mean an asyc call to gethostname, so we don't bother. - * @ignore - */ - var MACHINE_ID = parseInt(Math.random() * 0xffffff, 10); - - // Regular expression that checks for hex value - var checkForHexRegExp = new RegExp('^[0-9a-fA-F]{24}$'); - - // Check if buffer exists - try { - if (Buffer && Buffer.from) { - var hasBufferType = true; - inspect = __webpack_require__(340).inspect.custom || 'inspect'; - } - } catch (err) { - hasBufferType = false; - } - - /** - * Create a new ObjectID instance - * - * @class - * @param {(string|number)} id Can be a 24 byte hex string, 12 byte binary string or a Number. - * @property {number} generationTime The generation time of this ObjectId instance - * @return {ObjectID} instance of ObjectID. - */ - var ObjectID = function ObjectID(id) { - // Duck-typing to support ObjectId from different npm packages - if (id instanceof ObjectID) return id; - if (!(this instanceof ObjectID)) return new ObjectID(id); - - this._bsontype = 'ObjectID'; - - // The most common usecase (blank id, new objectId instance) - if (id == null || typeof id === 'number') { - // Generate a new id - this.id = this.generate(id); - // If we are caching the hex string - if (ObjectID.cacheHexString) this.__id = this.toString('hex'); - // Return the object - return; - } - - // Check if the passed in id is valid - var valid = ObjectID.isValid(id); - - // Throw an error if it's not a valid setup - if (!valid && id != null) { - throw new Error('Argument passed in must be a single String of 12 bytes or a string of 24 hex characters'); - } else if (valid && typeof id === 'string' && id.length === 24 && hasBufferType) { - return new ObjectID(utils.toBuffer(id, 'hex')); - } else if (valid && typeof id === 'string' && id.length === 24) { - return ObjectID.createFromHexString(id); - } else if (id != null && id.length === 12) { - // assume 12 byte string - this.id = id; - } else if (id != null && id.toHexString) { - // Duck-typing to support ObjectId from different npm packages - return id; - } else { - throw new Error('Argument passed in must be a single String of 12 bytes or a string of 24 hex characters'); - } - - if (ObjectID.cacheHexString) this.__id = this.toString('hex'); - }; - - // Allow usage of ObjectId as well as ObjectID - // var ObjectId = ObjectID; - - // Precomputed hex table enables speedy hex string conversion - var hexTable = []; - for (var i = 0; i < 256; i++) { - hexTable[i] = (i <= 15 ? '0' : '') + i.toString(16); - } - - /** - * Return the ObjectID id as a 24 byte hex string representation - * - * @method - * @return {string} return the 24 byte hex string representation. - */ - ObjectID.prototype.toHexString = function () { - if (ObjectID.cacheHexString && this.__id) return this.__id; - - var hexString = ''; - if (!this.id || !this.id.length) { - throw new Error('invalid ObjectId, ObjectId.id must be either a string or a Buffer, but is [' + JSON.stringify(this.id) + ']'); - } - - if (this.id instanceof _Buffer) { - hexString = convertToHex(this.id); - if (ObjectID.cacheHexString) this.__id = hexString; - return hexString; - } - - for (var i = 0; i < this.id.length; i++) { - hexString += hexTable[this.id.charCodeAt(i)]; - } - - if (ObjectID.cacheHexString) this.__id = hexString; - return hexString; - }; - - /** - * Update the ObjectID index used in generating new ObjectID's on the driver - * - * @method - * @return {number} returns next index value. - * @ignore - */ - ObjectID.prototype.get_inc = function () { - return ObjectID.index = (ObjectID.index + 1) % 0xffffff; - }; - - /** - * Update the ObjectID index used in generating new ObjectID's on the driver - * - * @method - * @return {number} returns next index value. - * @ignore - */ - ObjectID.prototype.getInc = function () { - return this.get_inc(); - }; - - /** - * Generate a 12 byte id buffer used in ObjectID's - * - * @method - * @param {number} [time] optional parameter allowing to pass in a second based timestamp. - * @return {Buffer} return the 12 byte id buffer string. - */ - ObjectID.prototype.generate = function (time) { - if ('number' !== typeof time) { - time = ~~(Date.now() / 1000); - } - - // Use pid - var pid = (typeof process === 'undefined' || process.pid === 1 ? Math.floor(Math.random() * 100000) : process.pid) % 0xffff; - var inc = this.get_inc(); - // Buffer used - var buffer = utils.allocBuffer(12); - // Encode time - buffer[3] = time & 0xff; - buffer[2] = time >> 8 & 0xff; - buffer[1] = time >> 16 & 0xff; - buffer[0] = time >> 24 & 0xff; - // Encode machine - buffer[6] = MACHINE_ID & 0xff; - buffer[5] = MACHINE_ID >> 8 & 0xff; - buffer[4] = MACHINE_ID >> 16 & 0xff; - // Encode pid - buffer[8] = pid & 0xff; - buffer[7] = pid >> 8 & 0xff; - // Encode index - buffer[11] = inc & 0xff; - buffer[10] = inc >> 8 & 0xff; - buffer[9] = inc >> 16 & 0xff; - // Return the buffer - return buffer; - }; - - /** - * Converts the id into a 24 byte hex string for printing - * - * @param {String} format The Buffer toString format parameter. - * @return {String} return the 24 byte hex string representation. - * @ignore - */ - ObjectID.prototype.toString = function (format) { - // Is the id a buffer then use the buffer toString method to return the format - if (this.id && this.id.copy) { - return this.id.toString(typeof format === 'string' ? format : 'hex'); - } - - // if(this.buffer ) - return this.toHexString(); - }; - - /** - * Converts to a string representation of this Id. - * - * @return {String} return the 24 byte hex string representation. - * @ignore - */ - ObjectID.prototype[inspect] = ObjectID.prototype.toString; - - /** - * Converts to its JSON representation. - * - * @return {String} return the 24 byte hex string representation. - * @ignore - */ - ObjectID.prototype.toJSON = function () { - return this.toHexString(); - }; - - /** - * Compares the equality of this ObjectID with `otherID`. - * - * @method - * @param {object} otherID ObjectID instance to compare against. - * @return {boolean} the result of comparing two ObjectID's - */ - ObjectID.prototype.equals = function equals(otherId) { - // var id; - - if (otherId instanceof ObjectID) { - return this.toString() === otherId.toString(); - } else if (typeof otherId === 'string' && ObjectID.isValid(otherId) && otherId.length === 12 && this.id instanceof _Buffer) { - return otherId === this.id.toString('binary'); - } else if (typeof otherId === 'string' && ObjectID.isValid(otherId) && otherId.length === 24) { - return otherId.toLowerCase() === this.toHexString(); - } else if (typeof otherId === 'string' && ObjectID.isValid(otherId) && otherId.length === 12) { - return otherId === this.id; - } else if (otherId != null && (otherId instanceof ObjectID || otherId.toHexString)) { - return otherId.toHexString() === this.toHexString(); - } else { - return false; - } - }; - - /** - * Returns the generation date (accurate up to the second) that this ID was generated. - * - * @method - * @return {date} the generation date - */ - ObjectID.prototype.getTimestamp = function () { - var timestamp = new Date(); - var time = this.id[3] | this.id[2] << 8 | this.id[1] << 16 | this.id[0] << 24; - timestamp.setTime(Math.floor(time) * 1000); - return timestamp; - }; - - /** - * @ignore - */ - ObjectID.index = ~~(Math.random() * 0xffffff); - - /** - * @ignore - */ - ObjectID.createPk = function createPk() { - return new ObjectID(); - }; - - /** - * Creates an ObjectID from a second based number, with the rest of the ObjectID zeroed out. Used for comparisons or sorting the ObjectID. - * - * @method - * @param {number} time an integer number representing a number of seconds. - * @return {ObjectID} return the created ObjectID - */ - ObjectID.createFromTime = function createFromTime(time) { - var buffer = utils.toBuffer([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); - // Encode time into first 4 bytes - buffer[3] = time & 0xff; - buffer[2] = time >> 8 & 0xff; - buffer[1] = time >> 16 & 0xff; - buffer[0] = time >> 24 & 0xff; - // Return the new objectId - return new ObjectID(buffer); - }; - - // Lookup tables - //var encodeLookup = '0123456789abcdef'.split(''); - var decodeLookup = []; - i = 0; - while (i < 10) decodeLookup[0x30 + i] = i++; - while (i < 16) decodeLookup[0x41 - 10 + i] = decodeLookup[0x61 - 10 + i] = i++; - - var _Buffer = Buffer; - var convertToHex = function (bytes) { - return bytes.toString('hex'); - }; - - /** - * Creates an ObjectID from a hex string representation of an ObjectID. - * - * @method - * @param {string} hexString create a ObjectID from a passed in 24 byte hexstring. - * @return {ObjectID} return the created ObjectID - */ - ObjectID.createFromHexString = function createFromHexString(string) { - // Throw an error if it's not a valid setup - if (typeof string === 'undefined' || string != null && string.length !== 24) { - throw new Error('Argument passed in must be a single String of 12 bytes or a string of 24 hex characters'); - } - - // Use Buffer.from method if available - if (hasBufferType) return new ObjectID(utils.toBuffer(string, 'hex')); - - // Calculate lengths - var array = new _Buffer(12); - var n = 0; - var i = 0; - - while (i < 24) { - array[n++] = decodeLookup[string.charCodeAt(i++)] << 4 | decodeLookup[string.charCodeAt(i++)]; - } - - return new ObjectID(array); - }; - - /** - * Checks if a value is a valid bson ObjectId - * - * @method - * @return {boolean} return true if the value is a valid bson ObjectId, return false otherwise. - */ - ObjectID.isValid = function isValid(id) { - if (id == null) return false; - - if (typeof id === 'number') { - return true; - } - - if (typeof id === 'string') { - return id.length === 12 || id.length === 24 && checkForHexRegExp.test(id); - } - - if (id instanceof ObjectID) { - return true; - } - - if (id instanceof _Buffer) { - return true; - } - - // Duck-Typing detection of ObjectId like objects - if (id.toHexString) { - return id.id.length === 12 || id.id.length === 24 && checkForHexRegExp.test(id.id); - } - - return false; - }; - - /** - * @ignore - */ - Object.defineProperty(ObjectID.prototype, 'generationTime', { - enumerable: true, - get: function () { - return this.id[3] | this.id[2] << 8 | this.id[1] << 16 | this.id[0] << 24; - }, - set: function (value) { - // Encode time into first 4 bytes - this.id[3] = value & 0xff; - this.id[2] = value >> 8 & 0xff; - this.id[1] = value >> 16 & 0xff; - this.id[0] = value >> 24 & 0xff; - } - }); - - /** - * Expose. - */ - module.exports = ObjectID; - module.exports.ObjectID = ObjectID; - module.exports.ObjectId = ObjectID; - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(334).Buffer, __webpack_require__(338))) - -/***/ }), -/* 334 */ -/***/ (function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(global) {/*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - */ - /* eslint-disable no-proto */ - - 'use strict' - - var base64 = __webpack_require__(335) - var ieee754 = __webpack_require__(336) - var isArray = __webpack_require__(337) - - exports.Buffer = Buffer - exports.SlowBuffer = SlowBuffer - exports.INSPECT_MAX_BYTES = 50 - - /** - * If `Buffer.TYPED_ARRAY_SUPPORT`: - * === true Use Uint8Array implementation (fastest) - * === false Use Object implementation (most compatible, even IE6) - * - * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, - * Opera 11.6+, iOS 4.2+. - * - * Due to various browser bugs, sometimes the Object implementation will be used even - * when the browser supports typed arrays. - * - * Note: - * - * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, - * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. - * - * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. - * - * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of - * incorrect length in some situations. - - * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they - * get the Object implementation, which is slower but behaves correctly. - */ - Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined - ? global.TYPED_ARRAY_SUPPORT - : typedArraySupport() - - /* - * Export kMaxLength after typed array support is determined. - */ - exports.kMaxLength = kMaxLength() - - function typedArraySupport () { - try { - var arr = new Uint8Array(1) - arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }} - return arr.foo() === 42 && // typed array instances can be augmented - typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray` - arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray` - } catch (e) { - return false - } - } - - function kMaxLength () { - return Buffer.TYPED_ARRAY_SUPPORT - ? 0x7fffffff - : 0x3fffffff - } - - function createBuffer (that, length) { - if (kMaxLength() < length) { - throw new RangeError('Invalid typed array length') - } - if (Buffer.TYPED_ARRAY_SUPPORT) { - // Return an augmented `Uint8Array` instance, for best performance - that = new Uint8Array(length) - that.__proto__ = Buffer.prototype - } else { - // Fallback: Return an object instance of the Buffer class - if (that === null) { - that = new Buffer(length) - } - that.length = length - } - - return that - } - - /** - * The Buffer constructor returns instances of `Uint8Array` that have their - * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of - * `Uint8Array`, so the returned instances will have all the node `Buffer` methods - * and the `Uint8Array` methods. Square bracket notation works as expected -- it - * returns a single octet. - * - * The `Uint8Array` prototype remains unmodified. - */ - - function Buffer (arg, encodingOrOffset, length) { - if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { - return new Buffer(arg, encodingOrOffset, length) - } - - // Common case. - if (typeof arg === 'number') { - if (typeof encodingOrOffset === 'string') { - throw new Error( - 'If encoding is specified then the first argument must be a string' - ) - } - return allocUnsafe(this, arg) - } - return from(this, arg, encodingOrOffset, length) - } - - Buffer.poolSize = 8192 // not used by this implementation - - // TODO: Legacy, not needed anymore. Remove in next major version. - Buffer._augment = function (arr) { - arr.__proto__ = Buffer.prototype - return arr - } - - function from (that, value, encodingOrOffset, length) { - if (typeof value === 'number') { - throw new TypeError('"value" argument must not be a number') - } - - if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { - return fromArrayBuffer(that, value, encodingOrOffset, length) - } - - if (typeof value === 'string') { - return fromString(that, value, encodingOrOffset) - } - - return fromObject(that, value) - } - - /** - * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError - * if value is a number. - * Buffer.from(str[, encoding]) - * Buffer.from(array) - * Buffer.from(buffer) - * Buffer.from(arrayBuffer[, byteOffset[, length]]) - **/ - Buffer.from = function (value, encodingOrOffset, length) { - return from(null, value, encodingOrOffset, length) - } - - if (Buffer.TYPED_ARRAY_SUPPORT) { - Buffer.prototype.__proto__ = Uint8Array.prototype - Buffer.__proto__ = Uint8Array - if (typeof Symbol !== 'undefined' && Symbol.species && - Buffer[Symbol.species] === Buffer) { - // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 - Object.defineProperty(Buffer, Symbol.species, { - value: null, - configurable: true - }) - } - } - - function assertSize (size) { - if (typeof size !== 'number') { - throw new TypeError('"size" argument must be a number') - } else if (size < 0) { - throw new RangeError('"size" argument must not be negative') - } - } - - function alloc (that, size, fill, encoding) { - assertSize(size) - if (size <= 0) { - return createBuffer(that, size) - } - if (fill !== undefined) { - // Only pay attention to encoding if it's a string. This - // prevents accidentally sending in a number that would - // be interpretted as a start offset. - return typeof encoding === 'string' - ? createBuffer(that, size).fill(fill, encoding) - : createBuffer(that, size).fill(fill) - } - return createBuffer(that, size) - } - - /** - * Creates a new filled Buffer instance. - * alloc(size[, fill[, encoding]]) - **/ - Buffer.alloc = function (size, fill, encoding) { - return alloc(null, size, fill, encoding) - } - - function allocUnsafe (that, size) { - assertSize(size) - that = createBuffer(that, size < 0 ? 0 : checked(size) | 0) - if (!Buffer.TYPED_ARRAY_SUPPORT) { - for (var i = 0; i < size; ++i) { - that[i] = 0 - } - } - return that - } - - /** - * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. - * */ - Buffer.allocUnsafe = function (size) { - return allocUnsafe(null, size) - } - /** - * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. - */ - Buffer.allocUnsafeSlow = function (size) { - return allocUnsafe(null, size) - } - - function fromString (that, string, encoding) { - if (typeof encoding !== 'string' || encoding === '') { - encoding = 'utf8' - } - - if (!Buffer.isEncoding(encoding)) { - throw new TypeError('"encoding" must be a valid string encoding') - } - - var length = byteLength(string, encoding) | 0 - that = createBuffer(that, length) - - var actual = that.write(string, encoding) - - if (actual !== length) { - // Writing a hex string, for example, that contains invalid characters will - // cause everything after the first invalid character to be ignored. (e.g. - // 'abxxcd' will be treated as 'ab') - that = that.slice(0, actual) - } - - return that - } - - function fromArrayLike (that, array) { - var length = array.length < 0 ? 0 : checked(array.length) | 0 - that = createBuffer(that, length) - for (var i = 0; i < length; i += 1) { - that[i] = array[i] & 255 - } - return that - } - - function fromArrayBuffer (that, array, byteOffset, length) { - array.byteLength // this throws if `array` is not a valid ArrayBuffer - - if (byteOffset < 0 || array.byteLength < byteOffset) { - throw new RangeError('\'offset\' is out of bounds') - } - - if (array.byteLength < byteOffset + (length || 0)) { - throw new RangeError('\'length\' is out of bounds') - } - - if (byteOffset === undefined && length === undefined) { - array = new Uint8Array(array) - } else if (length === undefined) { - array = new Uint8Array(array, byteOffset) - } else { - array = new Uint8Array(array, byteOffset, length) - } - - if (Buffer.TYPED_ARRAY_SUPPORT) { - // Return an augmented `Uint8Array` instance, for best performance - that = array - that.__proto__ = Buffer.prototype - } else { - // Fallback: Return an object instance of the Buffer class - that = fromArrayLike(that, array) - } - return that - } - - function fromObject (that, obj) { - if (Buffer.isBuffer(obj)) { - var len = checked(obj.length) | 0 - that = createBuffer(that, len) - - if (that.length === 0) { - return that - } - - obj.copy(that, 0, 0, len) - return that - } - - if (obj) { - if ((typeof ArrayBuffer !== 'undefined' && - obj.buffer instanceof ArrayBuffer) || 'length' in obj) { - if (typeof obj.length !== 'number' || isnan(obj.length)) { - return createBuffer(that, 0) - } - return fromArrayLike(that, obj) - } - - if (obj.type === 'Buffer' && isArray(obj.data)) { - return fromArrayLike(that, obj.data) - } - } - - throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') - } - - function checked (length) { - // Note: cannot use `length < kMaxLength()` here because that fails when - // length is NaN (which is otherwise coerced to zero.) - if (length >= kMaxLength()) { - throw new RangeError('Attempt to allocate Buffer larger than maximum ' + - 'size: 0x' + kMaxLength().toString(16) + ' bytes') - } - return length | 0 - } - - function SlowBuffer (length) { - if (+length != length) { // eslint-disable-line eqeqeq - length = 0 - } - return Buffer.alloc(+length) - } - - Buffer.isBuffer = function isBuffer (b) { - return !!(b != null && b._isBuffer) - } - - Buffer.compare = function compare (a, b) { - if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { - throw new TypeError('Arguments must be Buffers') - } - - if (a === b) return 0 - - var x = a.length - var y = b.length - - for (var i = 0, len = Math.min(x, y); i < len; ++i) { - if (a[i] !== b[i]) { - x = a[i] - y = b[i] - break - } - } - - if (x < y) return -1 - if (y < x) return 1 - return 0 - } - - Buffer.isEncoding = function isEncoding (encoding) { - switch (String(encoding).toLowerCase()) { - case 'hex': - case 'utf8': - case 'utf-8': - case 'ascii': - case 'latin1': - case 'binary': - case 'base64': - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return true - default: - return false - } - } - - Buffer.concat = function concat (list, length) { - if (!isArray(list)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - - if (list.length === 0) { - return Buffer.alloc(0) - } - - var i - if (length === undefined) { - length = 0 - for (i = 0; i < list.length; ++i) { - length += list[i].length - } - } - - var buffer = Buffer.allocUnsafe(length) - var pos = 0 - for (i = 0; i < list.length; ++i) { - var buf = list[i] - if (!Buffer.isBuffer(buf)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - buf.copy(buffer, pos) - pos += buf.length - } - return buffer - } - - function byteLength (string, encoding) { - if (Buffer.isBuffer(string)) { - return string.length - } - if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && - (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { - return string.byteLength - } - if (typeof string !== 'string') { - string = '' + string - } - - var len = string.length - if (len === 0) return 0 - - // Use a for loop to avoid recursion - var loweredCase = false - for (;;) { - switch (encoding) { - case 'ascii': - case 'latin1': - case 'binary': - return len - case 'utf8': - case 'utf-8': - case undefined: - return utf8ToBytes(string).length - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return len * 2 - case 'hex': - return len >>> 1 - case 'base64': - return base64ToBytes(string).length - default: - if (loweredCase) return utf8ToBytes(string).length // assume utf8 - encoding = ('' + encoding).toLowerCase() - loweredCase = true - } - } - } - Buffer.byteLength = byteLength - - function slowToString (encoding, start, end) { - var loweredCase = false - - // No need to verify that "this.length <= MAX_UINT32" since it's a read-only - // property of a typed array. - - // This behaves neither like String nor Uint8Array in that we set start/end - // to their upper/lower bounds if the value passed is out of range. - // undefined is handled specially as per ECMA-262 6th Edition, - // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. - if (start === undefined || start < 0) { - start = 0 - } - // Return early if start > this.length. Done here to prevent potential uint32 - // coercion fail below. - if (start > this.length) { - return '' - } - - if (end === undefined || end > this.length) { - end = this.length - } - - if (end <= 0) { - return '' - } - - // Force coersion to uint32. This will also coerce falsey/NaN values to 0. - end >>>= 0 - start >>>= 0 - - if (end <= start) { - return '' - } - - if (!encoding) encoding = 'utf8' - - while (true) { - switch (encoding) { - case 'hex': - return hexSlice(this, start, end) - - case 'utf8': - case 'utf-8': - return utf8Slice(this, start, end) - - case 'ascii': - return asciiSlice(this, start, end) - - case 'latin1': - case 'binary': - return latin1Slice(this, start, end) - - case 'base64': - return base64Slice(this, start, end) - - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return utf16leSlice(this, start, end) - - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = (encoding + '').toLowerCase() - loweredCase = true - } - } - } - - // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect - // Buffer instances. - Buffer.prototype._isBuffer = true - - function swap (b, n, m) { - var i = b[n] - b[n] = b[m] - b[m] = i - } - - Buffer.prototype.swap16 = function swap16 () { - var len = this.length - if (len % 2 !== 0) { - throw new RangeError('Buffer size must be a multiple of 16-bits') - } - for (var i = 0; i < len; i += 2) { - swap(this, i, i + 1) - } - return this - } - - Buffer.prototype.swap32 = function swap32 () { - var len = this.length - if (len % 4 !== 0) { - throw new RangeError('Buffer size must be a multiple of 32-bits') - } - for (var i = 0; i < len; i += 4) { - swap(this, i, i + 3) - swap(this, i + 1, i + 2) - } - return this - } - - Buffer.prototype.swap64 = function swap64 () { - var len = this.length - if (len % 8 !== 0) { - throw new RangeError('Buffer size must be a multiple of 64-bits') - } - for (var i = 0; i < len; i += 8) { - swap(this, i, i + 7) - swap(this, i + 1, i + 6) - swap(this, i + 2, i + 5) - swap(this, i + 3, i + 4) - } - return this - } - - Buffer.prototype.toString = function toString () { - var length = this.length | 0 - if (length === 0) return '' - if (arguments.length === 0) return utf8Slice(this, 0, length) - return slowToString.apply(this, arguments) - } - - Buffer.prototype.equals = function equals (b) { - if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') - if (this === b) return true - return Buffer.compare(this, b) === 0 - } - - Buffer.prototype.inspect = function inspect () { - var str = '' - var max = exports.INSPECT_MAX_BYTES - if (this.length > 0) { - str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') - if (this.length > max) str += ' ... ' - } - return '' - } - - Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { - if (!Buffer.isBuffer(target)) { - throw new TypeError('Argument must be a Buffer') - } - - if (start === undefined) { - start = 0 - } - if (end === undefined) { - end = target ? target.length : 0 - } - if (thisStart === undefined) { - thisStart = 0 - } - if (thisEnd === undefined) { - thisEnd = this.length - } - - if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { - throw new RangeError('out of range index') - } - - if (thisStart >= thisEnd && start >= end) { - return 0 - } - if (thisStart >= thisEnd) { - return -1 - } - if (start >= end) { - return 1 - } - - start >>>= 0 - end >>>= 0 - thisStart >>>= 0 - thisEnd >>>= 0 - - if (this === target) return 0 - - var x = thisEnd - thisStart - var y = end - start - var len = Math.min(x, y) - - var thisCopy = this.slice(thisStart, thisEnd) - var targetCopy = target.slice(start, end) - - for (var i = 0; i < len; ++i) { - if (thisCopy[i] !== targetCopy[i]) { - x = thisCopy[i] - y = targetCopy[i] - break - } - } - - if (x < y) return -1 - if (y < x) return 1 - return 0 - } - - // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, - // OR the last index of `val` in `buffer` at offset <= `byteOffset`. - // - // Arguments: - // - buffer - a Buffer to search - // - val - a string, Buffer, or number - // - byteOffset - an index into `buffer`; will be clamped to an int32 - // - encoding - an optional encoding, relevant is val is a string - // - dir - true for indexOf, false for lastIndexOf - function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { - // Empty buffer means no match - if (buffer.length === 0) return -1 - - // Normalize byteOffset - if (typeof byteOffset === 'string') { - encoding = byteOffset - byteOffset = 0 - } else if (byteOffset > 0x7fffffff) { - byteOffset = 0x7fffffff - } else if (byteOffset < -0x80000000) { - byteOffset = -0x80000000 - } - byteOffset = +byteOffset // Coerce to Number. - if (isNaN(byteOffset)) { - // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer - byteOffset = dir ? 0 : (buffer.length - 1) - } - - // Normalize byteOffset: negative offsets start from the end of the buffer - if (byteOffset < 0) byteOffset = buffer.length + byteOffset - if (byteOffset >= buffer.length) { - if (dir) return -1 - else byteOffset = buffer.length - 1 - } else if (byteOffset < 0) { - if (dir) byteOffset = 0 - else return -1 - } - - // Normalize val - if (typeof val === 'string') { - val = Buffer.from(val, encoding) - } - - // Finally, search either indexOf (if dir is true) or lastIndexOf - if (Buffer.isBuffer(val)) { - // Special case: looking for empty string/buffer always fails - if (val.length === 0) { - return -1 - } - return arrayIndexOf(buffer, val, byteOffset, encoding, dir) - } else if (typeof val === 'number') { - val = val & 0xFF // Search for a byte value [0-255] - if (Buffer.TYPED_ARRAY_SUPPORT && - typeof Uint8Array.prototype.indexOf === 'function') { - if (dir) { - return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) - } else { - return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) - } - } - return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) - } - - throw new TypeError('val must be string, number or Buffer') - } - - function arrayIndexOf (arr, val, byteOffset, encoding, dir) { - var indexSize = 1 - var arrLength = arr.length - var valLength = val.length - - if (encoding !== undefined) { - encoding = String(encoding).toLowerCase() - if (encoding === 'ucs2' || encoding === 'ucs-2' || - encoding === 'utf16le' || encoding === 'utf-16le') { - if (arr.length < 2 || val.length < 2) { - return -1 - } - indexSize = 2 - arrLength /= 2 - valLength /= 2 - byteOffset /= 2 - } - } - - function read (buf, i) { - if (indexSize === 1) { - return buf[i] - } else { - return buf.readUInt16BE(i * indexSize) - } - } - - var i - if (dir) { - var foundIndex = -1 - for (i = byteOffset; i < arrLength; i++) { - if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { - if (foundIndex === -1) foundIndex = i - if (i - foundIndex + 1 === valLength) return foundIndex * indexSize - } else { - if (foundIndex !== -1) i -= i - foundIndex - foundIndex = -1 - } - } - } else { - if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength - for (i = byteOffset; i >= 0; i--) { - var found = true - for (var j = 0; j < valLength; j++) { - if (read(arr, i + j) !== read(val, j)) { - found = false - break - } - } - if (found) return i - } - } - - return -1 - } - - Buffer.prototype.includes = function includes (val, byteOffset, encoding) { - return this.indexOf(val, byteOffset, encoding) !== -1 - } - - Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, true) - } - - Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, false) - } - - function hexWrite (buf, string, offset, length) { - offset = Number(offset) || 0 - var remaining = buf.length - offset - if (!length) { - length = remaining - } else { - length = Number(length) - if (length > remaining) { - length = remaining - } - } - - // must be an even number of digits - var strLen = string.length - if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') - - if (length > strLen / 2) { - length = strLen / 2 - } - for (var i = 0; i < length; ++i) { - var parsed = parseInt(string.substr(i * 2, 2), 16) - if (isNaN(parsed)) return i - buf[offset + i] = parsed - } - return i - } - - function utf8Write (buf, string, offset, length) { - return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) - } - - function asciiWrite (buf, string, offset, length) { - return blitBuffer(asciiToBytes(string), buf, offset, length) - } - - function latin1Write (buf, string, offset, length) { - return asciiWrite(buf, string, offset, length) - } - - function base64Write (buf, string, offset, length) { - return blitBuffer(base64ToBytes(string), buf, offset, length) - } - - function ucs2Write (buf, string, offset, length) { - return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) - } - - Buffer.prototype.write = function write (string, offset, length, encoding) { - // Buffer#write(string) - if (offset === undefined) { - encoding = 'utf8' - length = this.length - offset = 0 - // Buffer#write(string, encoding) - } else if (length === undefined && typeof offset === 'string') { - encoding = offset - length = this.length - offset = 0 - // Buffer#write(string, offset[, length][, encoding]) - } else if (isFinite(offset)) { - offset = offset | 0 - if (isFinite(length)) { - length = length | 0 - if (encoding === undefined) encoding = 'utf8' - } else { - encoding = length - length = undefined - } - // legacy write(string, encoding, offset, length) - remove in v0.13 - } else { - throw new Error( - 'Buffer.write(string, encoding, offset[, length]) is no longer supported' - ) - } - - var remaining = this.length - offset - if (length === undefined || length > remaining) length = remaining - - if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { - throw new RangeError('Attempt to write outside buffer bounds') - } - - if (!encoding) encoding = 'utf8' - - var loweredCase = false - for (;;) { - switch (encoding) { - case 'hex': - return hexWrite(this, string, offset, length) - - case 'utf8': - case 'utf-8': - return utf8Write(this, string, offset, length) - - case 'ascii': - return asciiWrite(this, string, offset, length) - - case 'latin1': - case 'binary': - return latin1Write(this, string, offset, length) - - case 'base64': - // Warning: maxLength not taken into account in base64Write - return base64Write(this, string, offset, length) - - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return ucs2Write(this, string, offset, length) - - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = ('' + encoding).toLowerCase() - loweredCase = true - } - } - } - - Buffer.prototype.toJSON = function toJSON () { - return { - type: 'Buffer', - data: Array.prototype.slice.call(this._arr || this, 0) - } - } - - function base64Slice (buf, start, end) { - if (start === 0 && end === buf.length) { - return base64.fromByteArray(buf) - } else { - return base64.fromByteArray(buf.slice(start, end)) - } - } - - function utf8Slice (buf, start, end) { - end = Math.min(buf.length, end) - var res = [] - - var i = start - while (i < end) { - var firstByte = buf[i] - var codePoint = null - var bytesPerSequence = (firstByte > 0xEF) ? 4 - : (firstByte > 0xDF) ? 3 - : (firstByte > 0xBF) ? 2 - : 1 - - if (i + bytesPerSequence <= end) { - var secondByte, thirdByte, fourthByte, tempCodePoint - - switch (bytesPerSequence) { - case 1: - if (firstByte < 0x80) { - codePoint = firstByte - } - break - case 2: - secondByte = buf[i + 1] - if ((secondByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) - if (tempCodePoint > 0x7F) { - codePoint = tempCodePoint - } - } - break - case 3: - secondByte = buf[i + 1] - thirdByte = buf[i + 2] - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) - if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { - codePoint = tempCodePoint - } - } - break - case 4: - secondByte = buf[i + 1] - thirdByte = buf[i + 2] - fourthByte = buf[i + 3] - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) - if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { - codePoint = tempCodePoint - } - } - } - } - - if (codePoint === null) { - // we did not generate a valid codePoint so insert a - // replacement char (U+FFFD) and advance only 1 byte - codePoint = 0xFFFD - bytesPerSequence = 1 - } else if (codePoint > 0xFFFF) { - // encode to utf16 (surrogate pair dance) - codePoint -= 0x10000 - res.push(codePoint >>> 10 & 0x3FF | 0xD800) - codePoint = 0xDC00 | codePoint & 0x3FF - } - - res.push(codePoint) - i += bytesPerSequence - } - - return decodeCodePointsArray(res) - } - - // Based on http://stackoverflow.com/a/22747272/680742, the browser with - // the lowest limit is Chrome, with 0x10000 args. - // We go 1 magnitude less, for safety - var MAX_ARGUMENTS_LENGTH = 0x1000 - - function decodeCodePointsArray (codePoints) { - var len = codePoints.length - if (len <= MAX_ARGUMENTS_LENGTH) { - return String.fromCharCode.apply(String, codePoints) // avoid extra slice() - } - - // Decode in chunks to avoid "call stack size exceeded". - var res = '' - var i = 0 - while (i < len) { - res += String.fromCharCode.apply( - String, - codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) - ) - } - return res - } - - function asciiSlice (buf, start, end) { - var ret = '' - end = Math.min(buf.length, end) - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i] & 0x7F) - } - return ret - } - - function latin1Slice (buf, start, end) { - var ret = '' - end = Math.min(buf.length, end) - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i]) - } - return ret - } - - function hexSlice (buf, start, end) { - var len = buf.length - - if (!start || start < 0) start = 0 - if (!end || end < 0 || end > len) end = len - - var out = '' - for (var i = start; i < end; ++i) { - out += toHex(buf[i]) - } - return out - } - - function utf16leSlice (buf, start, end) { - var bytes = buf.slice(start, end) - var res = '' - for (var i = 0; i < bytes.length; i += 2) { - res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256) - } - return res - } - - Buffer.prototype.slice = function slice (start, end) { - var len = this.length - start = ~~start - end = end === undefined ? len : ~~end - - if (start < 0) { - start += len - if (start < 0) start = 0 - } else if (start > len) { - start = len - } - - if (end < 0) { - end += len - if (end < 0) end = 0 - } else if (end > len) { - end = len - } - - if (end < start) end = start - - var newBuf - if (Buffer.TYPED_ARRAY_SUPPORT) { - newBuf = this.subarray(start, end) - newBuf.__proto__ = Buffer.prototype - } else { - var sliceLen = end - start - newBuf = new Buffer(sliceLen, undefined) - for (var i = 0; i < sliceLen; ++i) { - newBuf[i] = this[i + start] - } - } - - return newBuf - } - - /* - * Need to make sure that buffer isn't trying to write out of bounds. - */ - function checkOffset (offset, ext, length) { - if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') - if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') - } - - Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var val = this[offset] - var mul = 1 - var i = 0 - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul - } - - return val - } - - Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) { - checkOffset(offset, byteLength, this.length) - } - - var val = this[offset + --byteLength] - var mul = 1 - while (byteLength > 0 && (mul *= 0x100)) { - val += this[offset + --byteLength] * mul - } - - return val - } - - Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { - if (!noAssert) checkOffset(offset, 1, this.length) - return this[offset] - } - - Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - return this[offset] | (this[offset + 1] << 8) - } - - Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - return (this[offset] << 8) | this[offset + 1] - } - - Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - - return ((this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16)) + - (this[offset + 3] * 0x1000000) - } - - Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset] * 0x1000000) + - ((this[offset + 1] << 16) | - (this[offset + 2] << 8) | - this[offset + 3]) - } - - Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var val = this[offset] - var mul = 1 - var i = 0 - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul - } - mul *= 0x80 - - if (val >= mul) val -= Math.pow(2, 8 * byteLength) - - return val - } - - Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var i = byteLength - var mul = 1 - var val = this[offset + --i] - while (i > 0 && (mul *= 0x100)) { - val += this[offset + --i] * mul - } - mul *= 0x80 - - if (val >= mul) val -= Math.pow(2, 8 * byteLength) - - return val - } - - Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { - if (!noAssert) checkOffset(offset, 1, this.length) - if (!(this[offset] & 0x80)) return (this[offset]) - return ((0xff - this[offset] + 1) * -1) - } - - Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - var val = this[offset] | (this[offset + 1] << 8) - return (val & 0x8000) ? val | 0xFFFF0000 : val - } - - Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - var val = this[offset + 1] | (this[offset] << 8) - return (val & 0x8000) ? val | 0xFFFF0000 : val - } - - Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16) | - (this[offset + 3] << 24) - } - - Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset] << 24) | - (this[offset + 1] << 16) | - (this[offset + 2] << 8) | - (this[offset + 3]) - } - - Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - return ieee754.read(this, offset, true, 23, 4) - } - - Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - return ieee754.read(this, offset, false, 23, 4) - } - - Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 8, this.length) - return ieee754.read(this, offset, true, 52, 8) - } - - Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 8, this.length) - return ieee754.read(this, offset, false, 52, 8) - } - - function checkInt (buf, value, offset, ext, max, min) { - if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') - if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') - if (offset + ext > buf.length) throw new RangeError('Index out of range') - } - - Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { - value = +value - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1 - checkInt(this, value, offset, byteLength, maxBytes, 0) - } - - var mul = 1 - var i = 0 - this[offset] = value & 0xFF - while (++i < byteLength && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF - } - - return offset + byteLength - } - - Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { - value = +value - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1 - checkInt(this, value, offset, byteLength, maxBytes, 0) - } - - var i = byteLength - 1 - var mul = 1 - this[offset + i] = value & 0xFF - while (--i >= 0 && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF - } - - return offset + byteLength - } - - Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) - if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) - this[offset] = (value & 0xff) - return offset + 1 - } - - function objectWriteUInt16 (buf, value, offset, littleEndian) { - if (value < 0) value = 0xffff + value + 1 - for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { - buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> - (littleEndian ? i : 1 - i) * 8 - } - } - - Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - } else { - objectWriteUInt16(this, value, offset, true) - } - return offset + 2 - } - - Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 8) - this[offset + 1] = (value & 0xff) - } else { - objectWriteUInt16(this, value, offset, false) - } - return offset + 2 - } - - function objectWriteUInt32 (buf, value, offset, littleEndian) { - if (value < 0) value = 0xffffffff + value + 1 - for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { - buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff - } - } - - Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset + 3] = (value >>> 24) - this[offset + 2] = (value >>> 16) - this[offset + 1] = (value >>> 8) - this[offset] = (value & 0xff) - } else { - objectWriteUInt32(this, value, offset, true) - } - return offset + 4 - } - - Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = (value & 0xff) - } else { - objectWriteUInt32(this, value, offset, false) - } - return offset + 4 - } - - Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength - 1) - - checkInt(this, value, offset, byteLength, limit - 1, -limit) - } - - var i = 0 - var mul = 1 - var sub = 0 - this[offset] = value & 0xFF - while (++i < byteLength && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { - sub = 1 - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF - } - - return offset + byteLength - } - - Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength - 1) - - checkInt(this, value, offset, byteLength, limit - 1, -limit) - } - - var i = byteLength - 1 - var mul = 1 - var sub = 0 - this[offset + i] = value & 0xFF - while (--i >= 0 && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { - sub = 1 - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF - } - - return offset + byteLength - } - - Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) - if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) - if (value < 0) value = 0xff + value + 1 - this[offset] = (value & 0xff) - return offset + 1 - } - - Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - } else { - objectWriteUInt16(this, value, offset, true) - } - return offset + 2 - } - - Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 8) - this[offset + 1] = (value & 0xff) - } else { - objectWriteUInt16(this, value, offset, false) - } - return offset + 2 - } - - Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - this[offset + 2] = (value >>> 16) - this[offset + 3] = (value >>> 24) - } else { - objectWriteUInt32(this, value, offset, true) - } - return offset + 4 - } - - Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - if (value < 0) value = 0xffffffff + value + 1 - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = (value & 0xff) - } else { - objectWriteUInt32(this, value, offset, false) - } - return offset + 4 - } - - function checkIEEE754 (buf, value, offset, ext, max, min) { - if (offset + ext > buf.length) throw new RangeError('Index out of range') - if (offset < 0) throw new RangeError('Index out of range') - } - - function writeFloat (buf, value, offset, littleEndian, noAssert) { - if (!noAssert) { - checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) - } - ieee754.write(buf, value, offset, littleEndian, 23, 4) - return offset + 4 - } - - Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { - return writeFloat(this, value, offset, true, noAssert) - } - - Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { - return writeFloat(this, value, offset, false, noAssert) - } - - function writeDouble (buf, value, offset, littleEndian, noAssert) { - if (!noAssert) { - checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) - } - ieee754.write(buf, value, offset, littleEndian, 52, 8) - return offset + 8 - } - - Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { - return writeDouble(this, value, offset, true, noAssert) - } - - Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { - return writeDouble(this, value, offset, false, noAssert) - } - - // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) - Buffer.prototype.copy = function copy (target, targetStart, start, end) { - if (!start) start = 0 - if (!end && end !== 0) end = this.length - if (targetStart >= target.length) targetStart = target.length - if (!targetStart) targetStart = 0 - if (end > 0 && end < start) end = start - - // Copy 0 bytes; we're done - if (end === start) return 0 - if (target.length === 0 || this.length === 0) return 0 - - // Fatal error conditions - if (targetStart < 0) { - throw new RangeError('targetStart out of bounds') - } - if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') - if (end < 0) throw new RangeError('sourceEnd out of bounds') - - // Are we oob? - if (end > this.length) end = this.length - if (target.length - targetStart < end - start) { - end = target.length - targetStart + start - } - - var len = end - start - var i - - if (this === target && start < targetStart && targetStart < end) { - // descending copy from end - for (i = len - 1; i >= 0; --i) { - target[i + targetStart] = this[i + start] - } - } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { - // ascending copy from start - for (i = 0; i < len; ++i) { - target[i + targetStart] = this[i + start] - } - } else { - Uint8Array.prototype.set.call( - target, - this.subarray(start, start + len), - targetStart - ) - } - - return len - } - - // Usage: - // buffer.fill(number[, offset[, end]]) - // buffer.fill(buffer[, offset[, end]]) - // buffer.fill(string[, offset[, end]][, encoding]) - Buffer.prototype.fill = function fill (val, start, end, encoding) { - // Handle string cases: - if (typeof val === 'string') { - if (typeof start === 'string') { - encoding = start - start = 0 - end = this.length - } else if (typeof end === 'string') { - encoding = end - end = this.length - } - if (val.length === 1) { - var code = val.charCodeAt(0) - if (code < 256) { - val = code - } - } - if (encoding !== undefined && typeof encoding !== 'string') { - throw new TypeError('encoding must be a string') - } - if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { - throw new TypeError('Unknown encoding: ' + encoding) - } - } else if (typeof val === 'number') { - val = val & 255 - } - - // Invalid ranges are not set to a default, so can range check early. - if (start < 0 || this.length < start || this.length < end) { - throw new RangeError('Out of range index') - } - - if (end <= start) { - return this - } - - start = start >>> 0 - end = end === undefined ? this.length : end >>> 0 - - if (!val) val = 0 - - var i - if (typeof val === 'number') { - for (i = start; i < end; ++i) { - this[i] = val - } - } else { - var bytes = Buffer.isBuffer(val) - ? val - : utf8ToBytes(new Buffer(val, encoding).toString()) - var len = bytes.length - for (i = 0; i < end - start; ++i) { - this[i + start] = bytes[i % len] - } - } - - return this - } - - // HELPER FUNCTIONS - // ================ - - var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g - - function base64clean (str) { - // Node strips out invalid characters like \n and \t from the string, base64-js does not - str = stringtrim(str).replace(INVALID_BASE64_RE, '') - // Node converts strings with length < 2 to '' - if (str.length < 2) return '' - // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not - while (str.length % 4 !== 0) { - str = str + '=' - } - return str - } - - function stringtrim (str) { - if (str.trim) return str.trim() - return str.replace(/^\s+|\s+$/g, '') - } - - function toHex (n) { - if (n < 16) return '0' + n.toString(16) - return n.toString(16) - } - - function utf8ToBytes (string, units) { - units = units || Infinity - var codePoint - var length = string.length - var leadSurrogate = null - var bytes = [] - - for (var i = 0; i < length; ++i) { - codePoint = string.charCodeAt(i) - - // is surrogate component - if (codePoint > 0xD7FF && codePoint < 0xE000) { - // last char was a lead - if (!leadSurrogate) { - // no lead yet - if (codePoint > 0xDBFF) { - // unexpected trail - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } else if (i + 1 === length) { - // unpaired lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } - - // valid lead - leadSurrogate = codePoint - - continue - } - - // 2 leads in a row - if (codePoint < 0xDC00) { - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - leadSurrogate = codePoint - continue - } - - // valid surrogate pair - codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 - } else if (leadSurrogate) { - // valid bmp char, but last char was a lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - } - - leadSurrogate = null - - // encode utf8 - if (codePoint < 0x80) { - if ((units -= 1) < 0) break - bytes.push(codePoint) - } else if (codePoint < 0x800) { - if ((units -= 2) < 0) break - bytes.push( - codePoint >> 0x6 | 0xC0, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x10000) { - if ((units -= 3) < 0) break - bytes.push( - codePoint >> 0xC | 0xE0, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x110000) { - if ((units -= 4) < 0) break - bytes.push( - codePoint >> 0x12 | 0xF0, - codePoint >> 0xC & 0x3F | 0x80, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else { - throw new Error('Invalid code point') - } - } - - return bytes - } - - function asciiToBytes (str) { - var byteArray = [] - for (var i = 0; i < str.length; ++i) { - // Node's code seems to be doing this and not & 0x7F.. - byteArray.push(str.charCodeAt(i) & 0xFF) - } - return byteArray - } - - function utf16leToBytes (str, units) { - var c, hi, lo - var byteArray = [] - for (var i = 0; i < str.length; ++i) { - if ((units -= 2) < 0) break - - c = str.charCodeAt(i) - hi = c >> 8 - lo = c % 256 - byteArray.push(lo) - byteArray.push(hi) - } - - return byteArray - } - - function base64ToBytes (str) { - return base64.toByteArray(base64clean(str)) - } - - function blitBuffer (src, dst, offset, length) { - for (var i = 0; i < length; ++i) { - if ((i + offset >= dst.length) || (i >= src.length)) break - dst[i + offset] = src[i] - } - return i - } - - function isnan (val) { - return val !== val // eslint-disable-line no-self-compare - } - - /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) - -/***/ }), -/* 335 */ -/***/ (function(module, exports) { - - 'use strict' - - exports.byteLength = byteLength - exports.toByteArray = toByteArray - exports.fromByteArray = fromByteArray - - var lookup = [] - var revLookup = [] - var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array - - var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' - for (var i = 0, len = code.length; i < len; ++i) { - lookup[i] = code[i] - revLookup[code.charCodeAt(i)] = i - } - - // Support decoding URL-safe base64 strings, as Node.js does. - // See: https://en.wikipedia.org/wiki/Base64#URL_applications - revLookup['-'.charCodeAt(0)] = 62 - revLookup['_'.charCodeAt(0)] = 63 - - function getLens (b64) { - var len = b64.length - - if (len % 4 > 0) { - throw new Error('Invalid string. Length must be a multiple of 4') - } - - // Trim off extra bytes after placeholder bytes are found - // See: https://github.com/beatgammit/base64-js/issues/42 - var validLen = b64.indexOf('=') - if (validLen === -1) validLen = len - - var placeHoldersLen = validLen === len - ? 0 - : 4 - (validLen % 4) - - return [validLen, placeHoldersLen] - } - - // base64 is 4/3 + up to two characters of the original data - function byteLength (b64) { - var lens = getLens(b64) - var validLen = lens[0] - var placeHoldersLen = lens[1] - return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen - } - - function _byteLength (b64, validLen, placeHoldersLen) { - return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen - } - - function toByteArray (b64) { - var tmp - var lens = getLens(b64) - var validLen = lens[0] - var placeHoldersLen = lens[1] - - var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)) - - var curByte = 0 - - // if there are placeholders, only get up to the last complete 4 chars - var len = placeHoldersLen > 0 - ? validLen - 4 - : validLen - - for (var i = 0; i < len; i += 4) { - tmp = - (revLookup[b64.charCodeAt(i)] << 18) | - (revLookup[b64.charCodeAt(i + 1)] << 12) | - (revLookup[b64.charCodeAt(i + 2)] << 6) | - revLookup[b64.charCodeAt(i + 3)] - arr[curByte++] = (tmp >> 16) & 0xFF - arr[curByte++] = (tmp >> 8) & 0xFF - arr[curByte++] = tmp & 0xFF - } - - if (placeHoldersLen === 2) { - tmp = - (revLookup[b64.charCodeAt(i)] << 2) | - (revLookup[b64.charCodeAt(i + 1)] >> 4) - arr[curByte++] = tmp & 0xFF - } - - if (placeHoldersLen === 1) { - tmp = - (revLookup[b64.charCodeAt(i)] << 10) | - (revLookup[b64.charCodeAt(i + 1)] << 4) | - (revLookup[b64.charCodeAt(i + 2)] >> 2) - arr[curByte++] = (tmp >> 8) & 0xFF - arr[curByte++] = tmp & 0xFF - } - - return arr - } - - function tripletToBase64 (num) { - return lookup[num >> 18 & 0x3F] + - lookup[num >> 12 & 0x3F] + - lookup[num >> 6 & 0x3F] + - lookup[num & 0x3F] - } - - function encodeChunk (uint8, start, end) { - var tmp - var output = [] - for (var i = start; i < end; i += 3) { - tmp = - ((uint8[i] << 16) & 0xFF0000) + - ((uint8[i + 1] << 8) & 0xFF00) + - (uint8[i + 2] & 0xFF) - output.push(tripletToBase64(tmp)) - } - return output.join('') - } - - function fromByteArray (uint8) { - var tmp - var len = uint8.length - var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes - var parts = [] - var maxChunkLength = 16383 // must be multiple of 3 - - // go through the array every three bytes, we'll deal with trailing stuff later - for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { - parts.push(encodeChunk( - uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength) - )) - } - - // pad the end with zeros, but make sure to not forget the extra bytes - if (extraBytes === 1) { - tmp = uint8[len - 1] - parts.push( - lookup[tmp >> 2] + - lookup[(tmp << 4) & 0x3F] + - '==' - ) - } else if (extraBytes === 2) { - tmp = (uint8[len - 2] << 8) + uint8[len - 1] - parts.push( - lookup[tmp >> 10] + - lookup[(tmp >> 4) & 0x3F] + - lookup[(tmp << 2) & 0x3F] + - '=' - ) - } - - return parts.join('') - } - - -/***/ }), -/* 336 */ -/***/ (function(module, exports) { - - exports.read = function (buffer, offset, isLE, mLen, nBytes) { - var e, m - var eLen = (nBytes * 8) - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 1 - var nBits = -7 - var i = isLE ? (nBytes - 1) : 0 - var d = isLE ? -1 : 1 - var s = buffer[offset + i] - - i += d - - e = s & ((1 << (-nBits)) - 1) - s >>= (-nBits) - nBits += eLen - for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {} - - m = e & ((1 << (-nBits)) - 1) - e >>= (-nBits) - nBits += mLen - for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} - - if (e === 0) { - e = 1 - eBias - } else if (e === eMax) { - return m ? NaN : ((s ? -1 : 1) * Infinity) - } else { - m = m + Math.pow(2, mLen) - e = e - eBias - } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen) - } - - exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { - var e, m, c - var eLen = (nBytes * 8) - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 1 - var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) - var i = isLE ? 0 : (nBytes - 1) - var d = isLE ? 1 : -1 - var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 - - value = Math.abs(value) - - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0 - e = eMax - } else { - e = Math.floor(Math.log(value) / Math.LN2) - if (value * (c = Math.pow(2, -e)) < 1) { - e-- - c *= 2 - } - if (e + eBias >= 1) { - value += rt / c - } else { - value += rt * Math.pow(2, 1 - eBias) - } - if (value * c >= 2) { - e++ - c /= 2 - } - - if (e + eBias >= eMax) { - m = 0 - e = eMax - } else if (e + eBias >= 1) { - m = ((value * c) - 1) * Math.pow(2, mLen) - e = e + eBias - } else { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) - e = 0 - } - } - - for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} - - e = (e << mLen) | m - eLen += mLen - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} - - buffer[offset + i - d] |= s * 128 - } - - -/***/ }), -/* 337 */ -/***/ (function(module, exports) { - - var toString = {}.toString; - - module.exports = Array.isArray || function (arr) { - return toString.call(arr) == '[object Array]'; - }; - - -/***/ }), -/* 338 */ -/***/ (function(module, exports) { - - // shim for using process in browser - var process = module.exports = {}; - - // cached from whatever global is present so that test runners that stub it - // don't break things. But we need to wrap it in a try catch in case it is - // wrapped in strict mode code which doesn't define any globals. It's inside a - // function because try/catches deoptimize in certain engines. - - var cachedSetTimeout; - var cachedClearTimeout; - - function defaultSetTimout() { - throw new Error('setTimeout has not been defined'); - } - function defaultClearTimeout () { - throw new Error('clearTimeout has not been defined'); - } - (function () { - try { - if (typeof setTimeout === 'function') { - cachedSetTimeout = setTimeout; - } else { - cachedSetTimeout = defaultSetTimout; - } - } catch (e) { - cachedSetTimeout = defaultSetTimout; - } - try { - if (typeof clearTimeout === 'function') { - cachedClearTimeout = clearTimeout; - } else { - cachedClearTimeout = defaultClearTimeout; - } - } catch (e) { - cachedClearTimeout = defaultClearTimeout; - } - } ()) - function runTimeout(fun) { - if (cachedSetTimeout === setTimeout) { - //normal enviroments in sane situations - return setTimeout(fun, 0); - } - // if setTimeout wasn't available but was latter defined - if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { - cachedSetTimeout = setTimeout; - return setTimeout(fun, 0); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedSetTimeout(fun, 0); - } catch(e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedSetTimeout.call(null, fun, 0); - } catch(e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error - return cachedSetTimeout.call(this, fun, 0); - } - } - - - } - function runClearTimeout(marker) { - if (cachedClearTimeout === clearTimeout) { - //normal enviroments in sane situations - return clearTimeout(marker); - } - // if clearTimeout wasn't available but was latter defined - if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { - cachedClearTimeout = clearTimeout; - return clearTimeout(marker); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedClearTimeout(marker); - } catch (e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedClearTimeout.call(null, marker); - } catch (e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. - // Some versions of I.E. have different rules for clearTimeout vs setTimeout - return cachedClearTimeout.call(this, marker); - } - } - - - - } - var queue = []; - var draining = false; - var currentQueue; - var queueIndex = -1; - - function cleanUpNextTick() { - if (!draining || !currentQueue) { - return; - } - draining = false; - if (currentQueue.length) { - queue = currentQueue.concat(queue); - } else { - queueIndex = -1; - } - if (queue.length) { - drainQueue(); - } - } - - function drainQueue() { - if (draining) { - return; - } - var timeout = runTimeout(cleanUpNextTick); - draining = true; - - var len = queue.length; - while(len) { - currentQueue = queue; - queue = []; - while (++queueIndex < len) { - if (currentQueue) { - currentQueue[queueIndex].run(); - } - } - queueIndex = -1; - len = queue.length; - } - currentQueue = null; - draining = false; - runClearTimeout(timeout); - } - - process.nextTick = function (fun) { - var args = new Array(arguments.length - 1); - if (arguments.length > 1) { - for (var i = 1; i < arguments.length; i++) { - args[i - 1] = arguments[i]; - } - } - queue.push(new Item(fun, args)); - if (queue.length === 1 && !draining) { - runTimeout(drainQueue); - } - }; - - // v8 likes predictible objects - function Item(fun, array) { - this.fun = fun; - this.array = array; - } - Item.prototype.run = function () { - this.fun.apply(null, this.array); - }; - process.title = 'browser'; - process.browser = true; - process.env = {}; - process.argv = []; - process.version = ''; // empty string to avoid regexp issues - process.versions = {}; - - function noop() {} - - process.on = noop; - process.addListener = noop; - process.once = noop; - process.off = noop; - process.removeListener = noop; - process.removeAllListeners = noop; - process.emit = noop; - process.prependListener = noop; - process.prependOnceListener = noop; - - process.listeners = function (name) { return [] } - - process.binding = function (name) { - throw new Error('process.binding is not supported'); - }; - - process.cwd = function () { return '/' }; - process.chdir = function (dir) { - throw new Error('process.chdir is not supported'); - }; - process.umask = function() { return 0; }; - - -/***/ }), -/* 339 */ -/***/ (function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(Buffer) {'use strict'; - - /** - * Normalizes our expected stringified form of a function across versions of node - * @param {Function} fn The function to stringify - */ - - function normalizedFunctionString(fn) { - return fn.toString().replace(/function *\(/, 'function ('); - } - - function newBuffer(item, encoding) { - return new Buffer(item, encoding); - } - - function allocBuffer() { - return Buffer.alloc.apply(Buffer, arguments); - } - - function toBuffer() { - return Buffer.from.apply(Buffer, arguments); - } - - module.exports = { - normalizedFunctionString: normalizedFunctionString, - allocBuffer: typeof Buffer.alloc === 'function' ? allocBuffer : newBuffer, - toBuffer: typeof Buffer.from === 'function' ? toBuffer : newBuffer - }; - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(334).Buffer)) - -/***/ }), -/* 340 */ -/***/ (function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(global, process) {// Copyright Joyent, Inc. and other Node contributors. - // - // Permission is hereby granted, free of charge, to any person obtaining a - // copy of this software and associated documentation files (the - // "Software"), to deal in the Software without restriction, including - // without limitation the rights to use, copy, modify, merge, publish, - // distribute, sublicense, and/or sell copies of the Software, and to permit - // persons to whom the Software is furnished to do so, subject to the - // following conditions: - // - // The above copyright notice and this permission notice shall be included - // in all copies or substantial portions of the Software. - // - // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS - // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN - // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR - // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE - // USE OR OTHER DEALINGS IN THE SOFTWARE. - - var formatRegExp = /%[sdj%]/g; - exports.format = function(f) { - if (!isString(f)) { - var objects = []; - for (var i = 0; i < arguments.length; i++) { - objects.push(inspect(arguments[i])); - } - return objects.join(' '); - } - - var i = 1; - var args = arguments; - var len = args.length; - var str = String(f).replace(formatRegExp, function(x) { - if (x === '%%') return '%'; - if (i >= len) return x; - switch (x) { - case '%s': return String(args[i++]); - case '%d': return Number(args[i++]); - case '%j': - try { - return JSON.stringify(args[i++]); - } catch (_) { - return '[Circular]'; - } - default: - return x; - } - }); - for (var x = args[i]; i < len; x = args[++i]) { - if (isNull(x) || !isObject(x)) { - str += ' ' + x; - } else { - str += ' ' + inspect(x); - } - } - return str; - }; - - - // Mark that a method should not be used. - // Returns a modified function which warns once by default. - // If --no-deprecation is set, then it is a no-op. - exports.deprecate = function(fn, msg) { - // Allow for deprecating things in the process of starting up. - if (isUndefined(global.process)) { - return function() { - return exports.deprecate(fn, msg).apply(this, arguments); - }; - } - - if (process.noDeprecation === true) { - return fn; - } - - var warned = false; - function deprecated() { - if (!warned) { - if (process.throwDeprecation) { - throw new Error(msg); - } else if (process.traceDeprecation) { - console.trace(msg); - } else { - console.error(msg); - } - warned = true; - } - return fn.apply(this, arguments); - } - - return deprecated; - }; - - - var debugs = {}; - var debugEnviron; - exports.debuglog = function(set) { - if (isUndefined(debugEnviron)) - debugEnviron = process.env.NODE_DEBUG || ''; - set = set.toUpperCase(); - if (!debugs[set]) { - if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { - var pid = process.pid; - debugs[set] = function() { - var msg = exports.format.apply(exports, arguments); - console.error('%s %d: %s', set, pid, msg); - }; - } else { - debugs[set] = function() {}; - } - } - return debugs[set]; - }; - - - /** - * Echos the value of a value. Trys to print the value out - * in the best way possible given the different types. - * - * @param {Object} obj The object to print out. - * @param {Object} opts Optional options object that alters the output. - */ - /* legacy: obj, showHidden, depth, colors*/ - function inspect(obj, opts) { - // default options - var ctx = { - seen: [], - stylize: stylizeNoColor - }; - // legacy... - if (arguments.length >= 3) ctx.depth = arguments[2]; - if (arguments.length >= 4) ctx.colors = arguments[3]; - if (isBoolean(opts)) { - // legacy... - ctx.showHidden = opts; - } else if (opts) { - // got an "options" object - exports._extend(ctx, opts); - } - // set default options - if (isUndefined(ctx.showHidden)) ctx.showHidden = false; - if (isUndefined(ctx.depth)) ctx.depth = 2; - if (isUndefined(ctx.colors)) ctx.colors = false; - if (isUndefined(ctx.customInspect)) ctx.customInspect = true; - if (ctx.colors) ctx.stylize = stylizeWithColor; - return formatValue(ctx, obj, ctx.depth); - } - exports.inspect = inspect; - - - // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics - inspect.colors = { - 'bold' : [1, 22], - 'italic' : [3, 23], - 'underline' : [4, 24], - 'inverse' : [7, 27], - 'white' : [37, 39], - 'grey' : [90, 39], - 'black' : [30, 39], - 'blue' : [34, 39], - 'cyan' : [36, 39], - 'green' : [32, 39], - 'magenta' : [35, 39], - 'red' : [31, 39], - 'yellow' : [33, 39] - }; - - // Don't use 'blue' not visible on cmd.exe - inspect.styles = { - 'special': 'cyan', - 'number': 'yellow', - 'boolean': 'yellow', - 'undefined': 'grey', - 'null': 'bold', - 'string': 'green', - 'date': 'magenta', - // "name": intentionally not styling - 'regexp': 'red' - }; - - - function stylizeWithColor(str, styleType) { - var style = inspect.styles[styleType]; - - if (style) { - return '\u001b[' + inspect.colors[style][0] + 'm' + str + - '\u001b[' + inspect.colors[style][1] + 'm'; - } else { - return str; - } - } - - - function stylizeNoColor(str, styleType) { - return str; - } - - - function arrayToHash(array) { - var hash = {}; - - array.forEach(function(val, idx) { - hash[val] = true; - }); - - return hash; - } - - - function formatValue(ctx, value, recurseTimes) { - // Provide a hook for user-specified inspect functions. - // Check that value is an object with an inspect function on it - if (ctx.customInspect && - value && - isFunction(value.inspect) && - // Filter out the util module, it's inspect function is special - value.inspect !== exports.inspect && - // Also filter out any prototype objects using the circular check. - !(value.constructor && value.constructor.prototype === value)) { - var ret = value.inspect(recurseTimes, ctx); - if (!isString(ret)) { - ret = formatValue(ctx, ret, recurseTimes); - } - return ret; - } - - // Primitive types cannot have properties - var primitive = formatPrimitive(ctx, value); - if (primitive) { - return primitive; - } - - // Look up the keys of the object. - var keys = Object.keys(value); - var visibleKeys = arrayToHash(keys); - - if (ctx.showHidden) { - keys = Object.getOwnPropertyNames(value); - } - - // IE doesn't make error fields non-enumerable - // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx - if (isError(value) - && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { - return formatError(value); - } - - // Some type of object without properties can be shortcutted. - if (keys.length === 0) { - if (isFunction(value)) { - var name = value.name ? ': ' + value.name : ''; - return ctx.stylize('[Function' + name + ']', 'special'); - } - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } - if (isDate(value)) { - return ctx.stylize(Date.prototype.toString.call(value), 'date'); - } - if (isError(value)) { - return formatError(value); - } - } - - var base = '', array = false, braces = ['{', '}']; - - // Make Array say that they are Array - if (isArray(value)) { - array = true; - braces = ['[', ']']; - } - - // Make functions say that they are functions - if (isFunction(value)) { - var n = value.name ? ': ' + value.name : ''; - base = ' [Function' + n + ']'; - } - - // Make RegExps say that they are RegExps - if (isRegExp(value)) { - base = ' ' + RegExp.prototype.toString.call(value); - } - - // Make dates with properties first say the date - if (isDate(value)) { - base = ' ' + Date.prototype.toUTCString.call(value); - } - - // Make error with message first say the error - if (isError(value)) { - base = ' ' + formatError(value); - } - - if (keys.length === 0 && (!array || value.length == 0)) { - return braces[0] + base + braces[1]; - } - - if (recurseTimes < 0) { - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } else { - return ctx.stylize('[Object]', 'special'); - } - } - - ctx.seen.push(value); - - var output; - if (array) { - output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); - } else { - output = keys.map(function(key) { - return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); - }); - } - - ctx.seen.pop(); - - return reduceToSingleString(output, base, braces); - } - - - function formatPrimitive(ctx, value) { - if (isUndefined(value)) - return ctx.stylize('undefined', 'undefined'); - if (isString(value)) { - var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') - .replace(/'/g, "\\'") - .replace(/\\"/g, '"') + '\''; - return ctx.stylize(simple, 'string'); - } - if (isNumber(value)) - return ctx.stylize('' + value, 'number'); - if (isBoolean(value)) - return ctx.stylize('' + value, 'boolean'); - // For some reason typeof null is "object", so special case here. - if (isNull(value)) - return ctx.stylize('null', 'null'); - } - - - function formatError(value) { - return '[' + Error.prototype.toString.call(value) + ']'; - } - - - function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { - var output = []; - for (var i = 0, l = value.length; i < l; ++i) { - if (hasOwnProperty(value, String(i))) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - String(i), true)); - } else { - output.push(''); - } - } - keys.forEach(function(key) { - if (!key.match(/^\d+$/)) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - key, true)); - } - }); - return output; - } - - - function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { - var name, str, desc; - desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; - if (desc.get) { - if (desc.set) { - str = ctx.stylize('[Getter/Setter]', 'special'); - } else { - str = ctx.stylize('[Getter]', 'special'); - } - } else { - if (desc.set) { - str = ctx.stylize('[Setter]', 'special'); - } - } - if (!hasOwnProperty(visibleKeys, key)) { - name = '[' + key + ']'; - } - if (!str) { - if (ctx.seen.indexOf(desc.value) < 0) { - if (isNull(recurseTimes)) { - str = formatValue(ctx, desc.value, null); - } else { - str = formatValue(ctx, desc.value, recurseTimes - 1); - } - if (str.indexOf('\n') > -1) { - if (array) { - str = str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n').substr(2); - } else { - str = '\n' + str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n'); - } - } - } else { - str = ctx.stylize('[Circular]', 'special'); - } - } - if (isUndefined(name)) { - if (array && key.match(/^\d+$/)) { - return str; - } - name = JSON.stringify('' + key); - if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { - name = name.substr(1, name.length - 2); - name = ctx.stylize(name, 'name'); - } else { - name = name.replace(/'/g, "\\'") - .replace(/\\"/g, '"') - .replace(/(^"|"$)/g, "'"); - name = ctx.stylize(name, 'string'); - } - } - - return name + ': ' + str; - } - - - function reduceToSingleString(output, base, braces) { - var numLinesEst = 0; - var length = output.reduce(function(prev, cur) { - numLinesEst++; - if (cur.indexOf('\n') >= 0) numLinesEst++; - return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; - }, 0); - - if (length > 60) { - return braces[0] + - (base === '' ? '' : base + '\n ') + - ' ' + - output.join(',\n ') + - ' ' + - braces[1]; - } - - return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; - } - - - // NOTE: These type checking functions intentionally don't use `instanceof` - // because it is fragile and can be easily faked with `Object.create()`. - function isArray(ar) { - return Array.isArray(ar); - } - exports.isArray = isArray; - - function isBoolean(arg) { - return typeof arg === 'boolean'; - } - exports.isBoolean = isBoolean; - - function isNull(arg) { - return arg === null; - } - exports.isNull = isNull; - - function isNullOrUndefined(arg) { - return arg == null; - } - exports.isNullOrUndefined = isNullOrUndefined; - - function isNumber(arg) { - return typeof arg === 'number'; - } - exports.isNumber = isNumber; - - function isString(arg) { - return typeof arg === 'string'; - } - exports.isString = isString; - - function isSymbol(arg) { - return typeof arg === 'symbol'; - } - exports.isSymbol = isSymbol; - - function isUndefined(arg) { - return arg === void 0; - } - exports.isUndefined = isUndefined; - - function isRegExp(re) { - return isObject(re) && objectToString(re) === '[object RegExp]'; - } - exports.isRegExp = isRegExp; - - function isObject(arg) { - return typeof arg === 'object' && arg !== null; - } - exports.isObject = isObject; - - function isDate(d) { - return isObject(d) && objectToString(d) === '[object Date]'; - } - exports.isDate = isDate; - - function isError(e) { - return isObject(e) && - (objectToString(e) === '[object Error]' || e instanceof Error); - } - exports.isError = isError; - - function isFunction(arg) { - return typeof arg === 'function'; - } - exports.isFunction = isFunction; - - function isPrimitive(arg) { - return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; - } - exports.isPrimitive = isPrimitive; - - exports.isBuffer = __webpack_require__(341); - - function objectToString(o) { - return Object.prototype.toString.call(o); - } - - - function pad(n) { - return n < 10 ? '0' + n.toString(10) : n.toString(10); - } - - - var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', - 'Oct', 'Nov', 'Dec']; - - // 26 Feb 16:19:34 - function timestamp() { - var d = new Date(); - var time = [pad(d.getHours()), - pad(d.getMinutes()), - pad(d.getSeconds())].join(':'); - return [d.getDate(), months[d.getMonth()], time].join(' '); - } - - - // log is just a thin wrapper to console.log that prepends a timestamp - exports.log = function() { - console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); - }; - - - /** - * Inherit the prototype methods from one constructor into another. - * - * The Function.prototype.inherits from lang.js rewritten as a standalone - * function (not on Function.prototype). NOTE: If this file is to be loaded - * during bootstrapping this function needs to be rewritten using some native - * functions as prototype setup using normal JavaScript does not work as - * expected during bootstrapping (see mirror.js in r114903). - * - * @param {function} ctor Constructor function which needs to inherit the - * prototype. - * @param {function} superCtor Constructor function to inherit prototype from. - */ - exports.inherits = __webpack_require__(342); - - exports._extend = function(origin, add) { - // Don't do anything if add isn't an object - if (!add || !isObject(add)) return origin; - - var keys = Object.keys(add); - var i = keys.length; - while (i--) { - origin[keys[i]] = add[keys[i]]; - } - return origin; - }; - - function hasOwnProperty(obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop); - } - - /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()), __webpack_require__(338))) - -/***/ }), -/* 341 */ -/***/ (function(module, exports) { - - module.exports = function isBuffer(arg) { - return arg && typeof arg === 'object' - && typeof arg.copy === 'function' - && typeof arg.fill === 'function' - && typeof arg.readUInt8 === 'function'; - } - -/***/ }), -/* 342 */ -/***/ (function(module, exports) { - - if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }); - }; - } else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - var TempCtor = function () {} - TempCtor.prototype = superCtor.prototype - ctor.prototype = new TempCtor() - ctor.prototype.constructor = ctor - } - } - - -/***/ }), -/* 343 */ -/***/ (function(module, exports) { - - /** - * A class representation of the BSON RegExp type. - * - * @class - * @return {BSONRegExp} A MinKey instance - */ - function BSONRegExp(pattern, options) { - if (!(this instanceof BSONRegExp)) return new BSONRegExp(); - - // Execute - this._bsontype = 'BSONRegExp'; - this.pattern = pattern || ''; - this.options = options || ''; - - // Validate options - for (var i = 0; i < this.options.length; i++) { - if (!(this.options[i] === 'i' || this.options[i] === 'm' || this.options[i] === 'x' || this.options[i] === 'l' || this.options[i] === 's' || this.options[i] === 'u')) { - throw new Error('the regular expression options [' + this.options[i] + '] is not supported'); - } - } - } - - module.exports = BSONRegExp; - module.exports.BSONRegExp = BSONRegExp; - -/***/ }), -/* 344 */ -/***/ (function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(Buffer) {// Custom inspect property name / symbol. - var inspect = Buffer ? __webpack_require__(340).inspect.custom || 'inspect' : 'inspect'; - - /** - * A class representation of the BSON Symbol type. - * - * @class - * @deprecated - * @param {string} value the string representing the symbol. - * @return {Symbol} - */ - function Symbol(value) { - if (!(this instanceof Symbol)) return new Symbol(value); - this._bsontype = 'Symbol'; - this.value = value; - } - - /** - * Access the wrapped string value. - * - * @method - * @return {String} returns the wrapped string. - */ - Symbol.prototype.valueOf = function () { - return this.value; - }; - - /** - * @ignore - */ - Symbol.prototype.toString = function () { - return this.value; - }; - - /** - * @ignore - */ - Symbol.prototype[inspect] = function () { - return this.value; - }; - - /** - * @ignore - */ - Symbol.prototype.toJSON = function () { - return this.value; - }; - - module.exports = Symbol; - module.exports.Symbol = Symbol; - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(334).Buffer)) - -/***/ }), -/* 345 */ -/***/ (function(module, exports) { - - /** - * A class representation of a BSON Int32 type. - * - * @class - * @param {number} value the number we want to represent as an int32. - * @return {Int32} - */ - var Int32 = function (value) { - if (!(this instanceof Int32)) return new Int32(value); - - this._bsontype = 'Int32'; - this.value = value; - }; - - /** - * Access the number value. - * - * @method - * @return {number} returns the wrapped int32 number. - */ - Int32.prototype.valueOf = function () { - return this.value; - }; - - /** - * @ignore - */ - Int32.prototype.toJSON = function () { - return this.value; - }; - - module.exports = Int32; - module.exports.Int32 = Int32; - -/***/ }), -/* 346 */ -/***/ (function(module, exports) { - - /** - * A class representation of the BSON Code type. - * - * @class - * @param {(string|function)} code a string or function. - * @param {Object} [scope] an optional scope for the function. - * @return {Code} - */ - var Code = function Code(code, scope) { - if (!(this instanceof Code)) return new Code(code, scope); - this._bsontype = 'Code'; - this.code = code; - this.scope = scope; - }; - - /** - * @ignore - */ - Code.prototype.toJSON = function () { - return { scope: this.scope, code: this.code }; - }; - - module.exports = Code; - module.exports.Code = Code; - -/***/ }), -/* 347 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - - var Long = __webpack_require__(330); - - var PARSE_STRING_REGEXP = /^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/; - var PARSE_INF_REGEXP = /^(\+|-)?(Infinity|inf)$/i; - var PARSE_NAN_REGEXP = /^(\+|-)?NaN$/i; - - var EXPONENT_MAX = 6111; - var EXPONENT_MIN = -6176; - var EXPONENT_BIAS = 6176; - var MAX_DIGITS = 34; - - // Nan value bits as 32 bit values (due to lack of longs) - var NAN_BUFFER = [0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00].reverse(); - // Infinity value bits 32 bit values (due to lack of longs) - var INF_NEGATIVE_BUFFER = [0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00].reverse(); - var INF_POSITIVE_BUFFER = [0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00].reverse(); - - var EXPONENT_REGEX = /^([-+])?(\d+)?$/; - - var utils = __webpack_require__(339); - - // Detect if the value is a digit - var isDigit = function (value) { - return !isNaN(parseInt(value, 10)); - }; - - // Divide two uint128 values - var divideu128 = function (value) { - var DIVISOR = Long.fromNumber(1000 * 1000 * 1000); - var _rem = Long.fromNumber(0); - var i = 0; - - if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) { - return { quotient: value, rem: _rem }; - } - - for (i = 0; i <= 3; i++) { - // Adjust remainder to match value of next dividend - _rem = _rem.shiftLeft(32); - // Add the divided to _rem - _rem = _rem.add(new Long(value.parts[i], 0)); - value.parts[i] = _rem.div(DIVISOR).low_; - _rem = _rem.modulo(DIVISOR); - } - - return { quotient: value, rem: _rem }; - }; - - // Multiply two Long values and return the 128 bit value - var multiply64x2 = function (left, right) { - if (!left && !right) { - return { high: Long.fromNumber(0), low: Long.fromNumber(0) }; - } - - var leftHigh = left.shiftRightUnsigned(32); - var leftLow = new Long(left.getLowBits(), 0); - var rightHigh = right.shiftRightUnsigned(32); - var rightLow = new Long(right.getLowBits(), 0); - - var productHigh = leftHigh.multiply(rightHigh); - var productMid = leftHigh.multiply(rightLow); - var productMid2 = leftLow.multiply(rightHigh); - var productLow = leftLow.multiply(rightLow); - - productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); - productMid = new Long(productMid.getLowBits(), 0).add(productMid2).add(productLow.shiftRightUnsigned(32)); - - productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); - productLow = productMid.shiftLeft(32).add(new Long(productLow.getLowBits(), 0)); - - // Return the 128 bit result - return { high: productHigh, low: productLow }; - }; - - var lessThan = function (left, right) { - // Make values unsigned - var uhleft = left.high_ >>> 0; - var uhright = right.high_ >>> 0; - - // Compare high bits first - if (uhleft < uhright) { - return true; - } else if (uhleft === uhright) { - var ulleft = left.low_ >>> 0; - var ulright = right.low_ >>> 0; - if (ulleft < ulright) return true; - } - - return false; - }; - - // var longtoHex = function(value) { - // var buffer = utils.allocBuffer(8); - // var index = 0; - // // Encode the low 64 bits of the decimal - // // Encode low bits - // buffer[index++] = value.low_ & 0xff; - // buffer[index++] = (value.low_ >> 8) & 0xff; - // buffer[index++] = (value.low_ >> 16) & 0xff; - // buffer[index++] = (value.low_ >> 24) & 0xff; - // // Encode high bits - // buffer[index++] = value.high_ & 0xff; - // buffer[index++] = (value.high_ >> 8) & 0xff; - // buffer[index++] = (value.high_ >> 16) & 0xff; - // buffer[index++] = (value.high_ >> 24) & 0xff; - // return buffer.reverse().toString('hex'); - // }; - - // var int32toHex = function(value) { - // var buffer = utils.allocBuffer(4); - // var index = 0; - // // Encode the low 64 bits of the decimal - // // Encode low bits - // buffer[index++] = value & 0xff; - // buffer[index++] = (value >> 8) & 0xff; - // buffer[index++] = (value >> 16) & 0xff; - // buffer[index++] = (value >> 24) & 0xff; - // return buffer.reverse().toString('hex'); - // }; - - /** - * A class representation of the BSON Decimal128 type. - * - * @class - * @param {Buffer} bytes a buffer containing the raw Decimal128 bytes. - * @return {Double} - */ - var Decimal128 = function (bytes) { - this._bsontype = 'Decimal128'; - this.bytes = bytes; - }; - - /** - * Create a Decimal128 instance from a string representation - * - * @method - * @param {string} string a numeric string representation. - * @return {Decimal128} returns a Decimal128 instance. - */ - Decimal128.fromString = function (string) { - // Parse state tracking - var isNegative = false; - var sawRadix = false; - var foundNonZero = false; - - // Total number of significant digits (no leading or trailing zero) - var significantDigits = 0; - // Total number of significand digits read - var nDigitsRead = 0; - // Total number of digits (no leading zeros) - var nDigits = 0; - // The number of the digits after radix - var radixPosition = 0; - // The index of the first non-zero in *str* - var firstNonZero = 0; - - // Digits Array - var digits = [0]; - // The number of digits in digits - var nDigitsStored = 0; - // Insertion pointer for digits - var digitsInsert = 0; - // The index of the first non-zero digit - var firstDigit = 0; - // The index of the last digit - var lastDigit = 0; - - // Exponent - var exponent = 0; - // loop index over array - var i = 0; - // The high 17 digits of the significand - var significandHigh = [0, 0]; - // The low 17 digits of the significand - var significandLow = [0, 0]; - // The biased exponent - var biasedExponent = 0; - - // Read index - var index = 0; - - // Trim the string - string = string.trim(); - - // Naively prevent against REDOS attacks. - // TODO: implementing a custom parsing for this, or refactoring the regex would yield - // further gains. - if (string.length >= 7000) { - throw new Error('' + string + ' not a valid Decimal128 string'); - } - - // Results - var stringMatch = string.match(PARSE_STRING_REGEXP); - var infMatch = string.match(PARSE_INF_REGEXP); - var nanMatch = string.match(PARSE_NAN_REGEXP); - - // Validate the string - if (!stringMatch && !infMatch && !nanMatch || string.length === 0) { - throw new Error('' + string + ' not a valid Decimal128 string'); - } - - // Check if we have an illegal exponent format - if (stringMatch && stringMatch[4] && stringMatch[2] === undefined) { - throw new Error('' + string + ' not a valid Decimal128 string'); - } - - // Get the negative or positive sign - if (string[index] === '+' || string[index] === '-') { - isNegative = string[index++] === '-'; - } - - // Check if user passed Infinity or NaN - if (!isDigit(string[index]) && string[index] !== '.') { - if (string[index] === 'i' || string[index] === 'I') { - return new Decimal128(utils.toBuffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); - } else if (string[index] === 'N') { - return new Decimal128(utils.toBuffer(NAN_BUFFER)); - } - } - - // Read all the digits - while (isDigit(string[index]) || string[index] === '.') { - if (string[index] === '.') { - if (sawRadix) { - return new Decimal128(utils.toBuffer(NAN_BUFFER)); - } - - sawRadix = true; - index = index + 1; - continue; - } - - if (nDigitsStored < 34) { - if (string[index] !== '0' || foundNonZero) { - if (!foundNonZero) { - firstNonZero = nDigitsRead; - } - - foundNonZero = true; - - // Only store 34 digits - digits[digitsInsert++] = parseInt(string[index], 10); - nDigitsStored = nDigitsStored + 1; - } - } - - if (foundNonZero) { - nDigits = nDigits + 1; - } - - if (sawRadix) { - radixPosition = radixPosition + 1; - } - - nDigitsRead = nDigitsRead + 1; - index = index + 1; - } - - if (sawRadix && !nDigitsRead) { - throw new Error('' + string + ' not a valid Decimal128 string'); - } - - // Read exponent if exists - if (string[index] === 'e' || string[index] === 'E') { - // Read exponent digits - var match = string.substr(++index).match(EXPONENT_REGEX); - - // No digits read - if (!match || !match[2]) { - return new Decimal128(utils.toBuffer(NAN_BUFFER)); - } - - // Get exponent - exponent = parseInt(match[0], 10); - - // Adjust the index - index = index + match[0].length; - } - - // Return not a number - if (string[index]) { - return new Decimal128(utils.toBuffer(NAN_BUFFER)); - } - - // Done reading input - // Find first non-zero digit in digits - firstDigit = 0; - - if (!nDigitsStored) { - firstDigit = 0; - lastDigit = 0; - digits[0] = 0; - nDigits = 1; - nDigitsStored = 1; - significantDigits = 0; - } else { - lastDigit = nDigitsStored - 1; - significantDigits = nDigits; - - if (exponent !== 0 && significantDigits !== 1) { - while (string[firstNonZero + significantDigits - 1] === '0') { - significantDigits = significantDigits - 1; - } - } - } - - // Normalization of exponent - // Correct exponent based on radix position, and shift significand as needed - // to represent user input - - // Overflow prevention - if (exponent <= radixPosition && radixPosition - exponent > 1 << 14) { - exponent = EXPONENT_MIN; - } else { - exponent = exponent - radixPosition; - } - - // Attempt to normalize the exponent - while (exponent > EXPONENT_MAX) { - // Shift exponent to significand and decrease - lastDigit = lastDigit + 1; - - if (lastDigit - firstDigit > MAX_DIGITS) { - // Check if we have a zero then just hard clamp, otherwise fail - var digitsString = digits.join(''); - if (digitsString.match(/^0+$/)) { - exponent = EXPONENT_MAX; - break; - } else { - return new Decimal128(utils.toBuffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); - } - } - - exponent = exponent - 1; - } - - while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) { - // Shift last digit - if (lastDigit === 0) { - exponent = EXPONENT_MIN; - significantDigits = 0; - break; - } - - if (nDigitsStored < nDigits) { - // adjust to match digits not stored - nDigits = nDigits - 1; - } else { - // adjust to round - lastDigit = lastDigit - 1; - } - - if (exponent < EXPONENT_MAX) { - exponent = exponent + 1; - } else { - // Check if we have a zero then just hard clamp, otherwise fail - digitsString = digits.join(''); - if (digitsString.match(/^0+$/)) { - exponent = EXPONENT_MAX; - break; - } else { - return new Decimal128(utils.toBuffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); - } - } - } - - // Round - // We've normalized the exponent, but might still need to round. - if (lastDigit - firstDigit + 1 < significantDigits && string[significantDigits] !== '0') { - var endOfString = nDigitsRead; - - // If we have seen a radix point, 'string' is 1 longer than we have - // documented with ndigits_read, so inc the position of the first nonzero - // digit and the position that digits are read to. - if (sawRadix && exponent === EXPONENT_MIN) { - firstNonZero = firstNonZero + 1; - endOfString = endOfString + 1; - } - - var roundDigit = parseInt(string[firstNonZero + lastDigit + 1], 10); - var roundBit = 0; - - if (roundDigit >= 5) { - roundBit = 1; - - if (roundDigit === 5) { - roundBit = digits[lastDigit] % 2 === 1; - - for (i = firstNonZero + lastDigit + 2; i < endOfString; i++) { - if (parseInt(string[i], 10)) { - roundBit = 1; - break; - } - } - } - } - - if (roundBit) { - var dIdx = lastDigit; - - for (; dIdx >= 0; dIdx--) { - if (++digits[dIdx] > 9) { - digits[dIdx] = 0; - - // overflowed most significant digit - if (dIdx === 0) { - if (exponent < EXPONENT_MAX) { - exponent = exponent + 1; - digits[dIdx] = 1; - } else { - return new Decimal128(utils.toBuffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); - } - } - } else { - break; - } - } - } - } - - // Encode significand - // The high 17 digits of the significand - significandHigh = Long.fromNumber(0); - // The low 17 digits of the significand - significandLow = Long.fromNumber(0); - - // read a zero - if (significantDigits === 0) { - significandHigh = Long.fromNumber(0); - significandLow = Long.fromNumber(0); - } else if (lastDigit - firstDigit < 17) { - dIdx = firstDigit; - significandLow = Long.fromNumber(digits[dIdx++]); - significandHigh = new Long(0, 0); - - for (; dIdx <= lastDigit; dIdx++) { - significandLow = significandLow.multiply(Long.fromNumber(10)); - significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); - } - } else { - dIdx = firstDigit; - significandHigh = Long.fromNumber(digits[dIdx++]); - - for (; dIdx <= lastDigit - 17; dIdx++) { - significandHigh = significandHigh.multiply(Long.fromNumber(10)); - significandHigh = significandHigh.add(Long.fromNumber(digits[dIdx])); - } - - significandLow = Long.fromNumber(digits[dIdx++]); - - for (; dIdx <= lastDigit; dIdx++) { - significandLow = significandLow.multiply(Long.fromNumber(10)); - significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); - } - } - - var significand = multiply64x2(significandHigh, Long.fromString('100000000000000000')); - - significand.low = significand.low.add(significandLow); - - if (lessThan(significand.low, significandLow)) { - significand.high = significand.high.add(Long.fromNumber(1)); - } - - // Biased exponent - biasedExponent = exponent + EXPONENT_BIAS; - var dec = { low: Long.fromNumber(0), high: Long.fromNumber(0) }; - - // Encode combination, exponent, and significand. - if (significand.high.shiftRightUnsigned(49).and(Long.fromNumber(1)).equals(Long.fromNumber)) { - // Encode '11' into bits 1 to 3 - dec.high = dec.high.or(Long.fromNumber(0x3).shiftLeft(61)); - dec.high = dec.high.or(Long.fromNumber(biasedExponent).and(Long.fromNumber(0x3fff).shiftLeft(47))); - dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x7fffffffffff))); - } else { - dec.high = dec.high.or(Long.fromNumber(biasedExponent & 0x3fff).shiftLeft(49)); - dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x1ffffffffffff))); - } - - dec.low = significand.low; - - // Encode sign - if (isNegative) { - dec.high = dec.high.or(Long.fromString('9223372036854775808')); - } - - // Encode into a buffer - var buffer = utils.allocBuffer(16); - index = 0; - - // Encode the low 64 bits of the decimal - // Encode low bits - buffer[index++] = dec.low.low_ & 0xff; - buffer[index++] = dec.low.low_ >> 8 & 0xff; - buffer[index++] = dec.low.low_ >> 16 & 0xff; - buffer[index++] = dec.low.low_ >> 24 & 0xff; - // Encode high bits - buffer[index++] = dec.low.high_ & 0xff; - buffer[index++] = dec.low.high_ >> 8 & 0xff; - buffer[index++] = dec.low.high_ >> 16 & 0xff; - buffer[index++] = dec.low.high_ >> 24 & 0xff; - - // Encode the high 64 bits of the decimal - // Encode low bits - buffer[index++] = dec.high.low_ & 0xff; - buffer[index++] = dec.high.low_ >> 8 & 0xff; - buffer[index++] = dec.high.low_ >> 16 & 0xff; - buffer[index++] = dec.high.low_ >> 24 & 0xff; - // Encode high bits - buffer[index++] = dec.high.high_ & 0xff; - buffer[index++] = dec.high.high_ >> 8 & 0xff; - buffer[index++] = dec.high.high_ >> 16 & 0xff; - buffer[index++] = dec.high.high_ >> 24 & 0xff; - - // Return the new Decimal128 - return new Decimal128(buffer); - }; - - // Extract least significant 5 bits - var COMBINATION_MASK = 0x1f; - // Extract least significant 14 bits - var EXPONENT_MASK = 0x3fff; - // Value of combination field for Inf - var COMBINATION_INFINITY = 30; - // Value of combination field for NaN - var COMBINATION_NAN = 31; - // Value of combination field for NaN - // var COMBINATION_SNAN = 32; - // decimal128 exponent bias - EXPONENT_BIAS = 6176; - - /** - * Create a string representation of the raw Decimal128 value - * - * @method - * @return {string} returns a Decimal128 string representation. - */ - Decimal128.prototype.toString = function () { - // Note: bits in this routine are referred to starting at 0, - // from the sign bit, towards the coefficient. - - // bits 0 - 31 - var high; - // bits 32 - 63 - var midh; - // bits 64 - 95 - var midl; - // bits 96 - 127 - var low; - // bits 1 - 5 - var combination; - // decoded biased exponent (14 bits) - var biased_exponent; - // the number of significand digits - var significand_digits = 0; - // the base-10 digits in the significand - var significand = new Array(36); - for (var i = 0; i < significand.length; i++) significand[i] = 0; - // read pointer into significand - var index = 0; - - // unbiased exponent - var exponent; - // the exponent if scientific notation is used - var scientific_exponent; - - // true if the number is zero - var is_zero = false; - - // the most signifcant significand bits (50-46) - var significand_msb; - // temporary storage for significand decoding - var significand128 = { parts: new Array(4) }; - // indexing variables - i; - var j, k; - - // Output string - var string = []; - - // Unpack index - index = 0; - - // Buffer reference - var buffer = this.bytes; - - // Unpack the low 64bits into a long - low = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - midl = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - - // Unpack the high 64bits into a long - midh = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - high = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - - // Unpack index - index = 0; - - // Create the state of the decimal - var dec = { - low: new Long(low, midl), - high: new Long(midh, high) - }; - - if (dec.high.lessThan(Long.ZERO)) { - string.push('-'); - } - - // Decode combination field and exponent - combination = high >> 26 & COMBINATION_MASK; - - if (combination >> 3 === 3) { - // Check for 'special' values - if (combination === COMBINATION_INFINITY) { - return string.join('') + 'Infinity'; - } else if (combination === COMBINATION_NAN) { - return 'NaN'; - } else { - biased_exponent = high >> 15 & EXPONENT_MASK; - significand_msb = 0x08 + (high >> 14 & 0x01); - } - } else { - significand_msb = high >> 14 & 0x07; - biased_exponent = high >> 17 & EXPONENT_MASK; - } - - exponent = biased_exponent - EXPONENT_BIAS; - - // Create string of significand digits - - // Convert the 114-bit binary number represented by - // (significand_high, significand_low) to at most 34 decimal - // digits through modulo and division. - significand128.parts[0] = (high & 0x3fff) + ((significand_msb & 0xf) << 14); - significand128.parts[1] = midh; - significand128.parts[2] = midl; - significand128.parts[3] = low; - - if (significand128.parts[0] === 0 && significand128.parts[1] === 0 && significand128.parts[2] === 0 && significand128.parts[3] === 0) { - is_zero = true; - } else { - for (k = 3; k >= 0; k--) { - var least_digits = 0; - // Peform the divide - var result = divideu128(significand128); - significand128 = result.quotient; - least_digits = result.rem.low_; - - // We now have the 9 least significant digits (in base 2). - // Convert and output to string. - if (!least_digits) continue; - - for (j = 8; j >= 0; j--) { - // significand[k * 9 + j] = Math.round(least_digits % 10); - significand[k * 9 + j] = least_digits % 10; - // least_digits = Math.round(least_digits / 10); - least_digits = Math.floor(least_digits / 10); - } - } - } - - // Output format options: - // Scientific - [-]d.dddE(+/-)dd or [-]dE(+/-)dd - // Regular - ddd.ddd - - if (is_zero) { - significand_digits = 1; - significand[index] = 0; - } else { - significand_digits = 36; - i = 0; - - while (!significand[index]) { - i++; - significand_digits = significand_digits - 1; - index = index + 1; - } - } - - scientific_exponent = significand_digits - 1 + exponent; - - // The scientific exponent checks are dictated by the string conversion - // specification and are somewhat arbitrary cutoffs. - // - // We must check exponent > 0, because if this is the case, the number - // has trailing zeros. However, we *cannot* output these trailing zeros, - // because doing so would change the precision of the value, and would - // change stored data if the string converted number is round tripped. - - if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) { - // Scientific format - string.push(significand[index++]); - significand_digits = significand_digits - 1; - - if (significand_digits) { - string.push('.'); - } - - for (i = 0; i < significand_digits; i++) { - string.push(significand[index++]); - } - - // Exponent - string.push('E'); - if (scientific_exponent > 0) { - string.push('+' + scientific_exponent); - } else { - string.push(scientific_exponent); - } - } else { - // Regular format with no decimal place - if (exponent >= 0) { - for (i = 0; i < significand_digits; i++) { - string.push(significand[index++]); - } - } else { - var radix_position = significand_digits + exponent; - - // non-zero digits before radix - if (radix_position > 0) { - for (i = 0; i < radix_position; i++) { - string.push(significand[index++]); - } - } else { - string.push('0'); - } - - string.push('.'); - // add leading zeros after radix - while (radix_position++ < 0) { - string.push('0'); - } - - for (i = 0; i < significand_digits - Math.max(radix_position - 1, 0); i++) { - string.push(significand[index++]); - } - } - } - - return string.join(''); - }; - - Decimal128.prototype.toJSON = function () { - return { $numberDecimal: this.toString() }; - }; - - module.exports = Decimal128; - module.exports.Decimal128 = Decimal128; - -/***/ }), -/* 348 */ -/***/ (function(module, exports) { - - /** - * A class representation of the BSON MinKey type. - * - * @class - * @return {MinKey} A MinKey instance - */ - function MinKey() { - if (!(this instanceof MinKey)) return new MinKey(); - - this._bsontype = 'MinKey'; - } - - module.exports = MinKey; - module.exports.MinKey = MinKey; - -/***/ }), -/* 349 */ -/***/ (function(module, exports) { - - /** - * A class representation of the BSON MaxKey type. - * - * @class - * @return {MaxKey} A MaxKey instance - */ - function MaxKey() { - if (!(this instanceof MaxKey)) return new MaxKey(); - - this._bsontype = 'MaxKey'; - } - - module.exports = MaxKey; - module.exports.MaxKey = MaxKey; - -/***/ }), -/* 350 */ -/***/ (function(module, exports) { - - /** - * A class representation of the BSON DBRef type. - * - * @class - * @param {string} namespace the collection name. - * @param {ObjectID} oid the reference ObjectID. - * @param {string} [db] optional db name, if omitted the reference is local to the current db. - * @return {DBRef} - */ - function DBRef(namespace, oid, db) { - if (!(this instanceof DBRef)) return new DBRef(namespace, oid, db); - - this._bsontype = 'DBRef'; - this.namespace = namespace; - this.oid = oid; - this.db = db; - } - - /** - * @ignore - * @api private - */ - DBRef.prototype.toJSON = function () { - return { - $ref: this.namespace, - $id: this.oid, - $db: this.db == null ? '' : this.db - }; - }; - - module.exports = DBRef; - module.exports.DBRef = DBRef; - -/***/ }), -/* 351 */ -/***/ (function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(global) {/** - * Module dependencies. - * @ignore - */ - - // Test if we're in Node via presence of "global" not absence of "window" - // to support hybrid environments like Electron - if (typeof global !== 'undefined') { - var Buffer = __webpack_require__(334).Buffer; // TODO just use global Buffer - } - - var utils = __webpack_require__(339); - - /** - * A class representation of the BSON Binary type. - * - * Sub types - * - **BSON.BSON_BINARY_SUBTYPE_DEFAULT**, default BSON type. - * - **BSON.BSON_BINARY_SUBTYPE_FUNCTION**, BSON function type. - * - **BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY**, BSON byte array type. - * - **BSON.BSON_BINARY_SUBTYPE_UUID**, BSON uuid type. - * - **BSON.BSON_BINARY_SUBTYPE_MD5**, BSON md5 type. - * - **BSON.BSON_BINARY_SUBTYPE_USER_DEFINED**, BSON user defined type. - * - * @class - * @param {Buffer} buffer a buffer object containing the binary data. - * @param {Number} [subType] the option binary type. - * @return {Binary} - */ - function Binary(buffer, subType) { - if (!(this instanceof Binary)) return new Binary(buffer, subType); - - if (buffer != null && !(typeof buffer === 'string') && !Buffer.isBuffer(buffer) && !(buffer instanceof Uint8Array) && !Array.isArray(buffer)) { - throw new Error('only String, Buffer, Uint8Array or Array accepted'); - } - - this._bsontype = 'Binary'; - - if (buffer instanceof Number) { - this.sub_type = buffer; - this.position = 0; - } else { - this.sub_type = subType == null ? BSON_BINARY_SUBTYPE_DEFAULT : subType; - this.position = 0; - } - - if (buffer != null && !(buffer instanceof Number)) { - // Only accept Buffer, Uint8Array or Arrays - if (typeof buffer === 'string') { - // Different ways of writing the length of the string for the different types - if (typeof Buffer !== 'undefined') { - this.buffer = utils.toBuffer(buffer); - } else if (typeof Uint8Array !== 'undefined' || Object.prototype.toString.call(buffer) === '[object Array]') { - this.buffer = writeStringToArray(buffer); - } else { - throw new Error('only String, Buffer, Uint8Array or Array accepted'); - } - } else { - this.buffer = buffer; - } - this.position = buffer.length; - } else { - if (typeof Buffer !== 'undefined') { - this.buffer = utils.allocBuffer(Binary.BUFFER_SIZE); - } else if (typeof Uint8Array !== 'undefined') { - this.buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE)); - } else { - this.buffer = new Array(Binary.BUFFER_SIZE); - } - // Set position to start of buffer - this.position = 0; - } - } - - /** - * Updates this binary with byte_value. - * - * @method - * @param {string} byte_value a single byte we wish to write. - */ - Binary.prototype.put = function put(byte_value) { - // If it's a string and a has more than one character throw an error - if (byte_value['length'] != null && typeof byte_value !== 'number' && byte_value.length !== 1) throw new Error('only accepts single character String, Uint8Array or Array'); - if (typeof byte_value !== 'number' && byte_value < 0 || byte_value > 255) throw new Error('only accepts number in a valid unsigned byte range 0-255'); - - // Decode the byte value once - var decoded_byte = null; - if (typeof byte_value === 'string') { - decoded_byte = byte_value.charCodeAt(0); - } else if (byte_value['length'] != null) { - decoded_byte = byte_value[0]; - } else { - decoded_byte = byte_value; - } - - if (this.buffer.length > this.position) { - this.buffer[this.position++] = decoded_byte; - } else { - if (typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer)) { - // Create additional overflow buffer - var buffer = utils.allocBuffer(Binary.BUFFER_SIZE + this.buffer.length); - // Combine the two buffers together - this.buffer.copy(buffer, 0, 0, this.buffer.length); - this.buffer = buffer; - this.buffer[this.position++] = decoded_byte; - } else { - buffer = null; - // Create a new buffer (typed or normal array) - if (Object.prototype.toString.call(this.buffer) === '[object Uint8Array]') { - buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE + this.buffer.length)); - } else { - buffer = new Array(Binary.BUFFER_SIZE + this.buffer.length); - } - - // We need to copy all the content to the new array - for (var i = 0; i < this.buffer.length; i++) { - buffer[i] = this.buffer[i]; - } - - // Reassign the buffer - this.buffer = buffer; - // Write the byte - this.buffer[this.position++] = decoded_byte; - } - } - }; - - /** - * Writes a buffer or string to the binary. - * - * @method - * @param {(Buffer|string)} string a string or buffer to be written to the Binary BSON object. - * @param {number} offset specify the binary of where to write the content. - * @return {null} - */ - Binary.prototype.write = function write(string, offset) { - offset = typeof offset === 'number' ? offset : this.position; - - // If the buffer is to small let's extend the buffer - if (this.buffer.length < offset + string.length) { - var buffer = null; - // If we are in node.js - if (typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer)) { - buffer = utils.allocBuffer(this.buffer.length + string.length); - this.buffer.copy(buffer, 0, 0, this.buffer.length); - } else if (Object.prototype.toString.call(this.buffer) === '[object Uint8Array]') { - // Create a new buffer - buffer = new Uint8Array(new ArrayBuffer(this.buffer.length + string.length)); - // Copy the content - for (var i = 0; i < this.position; i++) { - buffer[i] = this.buffer[i]; - } - } - - // Assign the new buffer - this.buffer = buffer; - } - - if (typeof Buffer !== 'undefined' && Buffer.isBuffer(string) && Buffer.isBuffer(this.buffer)) { - string.copy(this.buffer, offset, 0, string.length); - this.position = offset + string.length > this.position ? offset + string.length : this.position; - // offset = string.length - } else if (typeof Buffer !== 'undefined' && typeof string === 'string' && Buffer.isBuffer(this.buffer)) { - this.buffer.write(string, offset, 'binary'); - this.position = offset + string.length > this.position ? offset + string.length : this.position; - // offset = string.length; - } else if (Object.prototype.toString.call(string) === '[object Uint8Array]' || Object.prototype.toString.call(string) === '[object Array]' && typeof string !== 'string') { - for (i = 0; i < string.length; i++) { - this.buffer[offset++] = string[i]; - } - - this.position = offset > this.position ? offset : this.position; - } else if (typeof string === 'string') { - for (i = 0; i < string.length; i++) { - this.buffer[offset++] = string.charCodeAt(i); - } - - this.position = offset > this.position ? offset : this.position; - } - }; - - /** - * Reads **length** bytes starting at **position**. - * - * @method - * @param {number} position read from the given position in the Binary. - * @param {number} length the number of bytes to read. - * @return {Buffer} - */ - Binary.prototype.read = function read(position, length) { - length = length && length > 0 ? length : this.position; - - // Let's return the data based on the type we have - if (this.buffer['slice']) { - return this.buffer.slice(position, position + length); - } else { - // Create a buffer to keep the result - var buffer = typeof Uint8Array !== 'undefined' ? new Uint8Array(new ArrayBuffer(length)) : new Array(length); - for (var i = 0; i < length; i++) { - buffer[i] = this.buffer[position++]; - } - } - // Return the buffer - return buffer; - }; - - /** - * Returns the value of this binary as a string. - * - * @method - * @return {string} - */ - Binary.prototype.value = function value(asRaw) { - asRaw = asRaw == null ? false : asRaw; - - // Optimize to serialize for the situation where the data == size of buffer - if (asRaw && typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer) && this.buffer.length === this.position) return this.buffer; - - // If it's a node.js buffer object - if (typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer)) { - return asRaw ? this.buffer.slice(0, this.position) : this.buffer.toString('binary', 0, this.position); - } else { - if (asRaw) { - // we support the slice command use it - if (this.buffer['slice'] != null) { - return this.buffer.slice(0, this.position); - } else { - // Create a new buffer to copy content to - var newBuffer = Object.prototype.toString.call(this.buffer) === '[object Uint8Array]' ? new Uint8Array(new ArrayBuffer(this.position)) : new Array(this.position); - // Copy content - for (var i = 0; i < this.position; i++) { - newBuffer[i] = this.buffer[i]; - } - // Return the buffer - return newBuffer; - } - } else { - return convertArraytoUtf8BinaryString(this.buffer, 0, this.position); - } - } - }; - - /** - * Length. - * - * @method - * @return {number} the length of the binary. - */ - Binary.prototype.length = function length() { - return this.position; - }; - - /** - * @ignore - */ - Binary.prototype.toJSON = function () { - return this.buffer != null ? this.buffer.toString('base64') : ''; - }; - - /** - * @ignore - */ - Binary.prototype.toString = function (format) { - return this.buffer != null ? this.buffer.slice(0, this.position).toString(format) : ''; - }; - - /** - * Binary default subtype - * @ignore - */ - var BSON_BINARY_SUBTYPE_DEFAULT = 0; - - /** - * @ignore - */ - var writeStringToArray = function (data) { - // Create a buffer - var buffer = typeof Uint8Array !== 'undefined' ? new Uint8Array(new ArrayBuffer(data.length)) : new Array(data.length); - // Write the content to the buffer - for (var i = 0; i < data.length; i++) { - buffer[i] = data.charCodeAt(i); - } - // Write the string to the buffer - return buffer; - }; - - /** - * Convert Array ot Uint8Array to Binary String - * - * @ignore - */ - var convertArraytoUtf8BinaryString = function (byteArray, startIndex, endIndex) { - var result = ''; - for (var i = startIndex; i < endIndex; i++) { - result = result + String.fromCharCode(byteArray[i]); - } - return result; - }; - - Binary.BUFFER_SIZE = 256; - - /** - * Default BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ - Binary.SUBTYPE_DEFAULT = 0; - /** - * Function BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ - Binary.SUBTYPE_FUNCTION = 1; - /** - * Byte Array BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ - Binary.SUBTYPE_BYTE_ARRAY = 2; - /** - * OLD UUID BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ - Binary.SUBTYPE_UUID_OLD = 3; - /** - * UUID BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ - Binary.SUBTYPE_UUID = 4; - /** - * MD5 BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ - Binary.SUBTYPE_MD5 = 5; - /** - * User BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ - Binary.SUBTYPE_USER_DEFINED = 128; - - /** - * Expose. - */ - module.exports = Binary; - module.exports.Binary = Binary; - /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) - -/***/ }), -/* 352 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - - var Long = __webpack_require__(330).Long, - Double = __webpack_require__(331).Double, - Timestamp = __webpack_require__(332).Timestamp, - ObjectID = __webpack_require__(333).ObjectID, - Symbol = __webpack_require__(344).Symbol, - Code = __webpack_require__(346).Code, - MinKey = __webpack_require__(348).MinKey, - MaxKey = __webpack_require__(349).MaxKey, - Decimal128 = __webpack_require__(347), - Int32 = __webpack_require__(345), - DBRef = __webpack_require__(350).DBRef, - BSONRegExp = __webpack_require__(343).BSONRegExp, - Binary = __webpack_require__(351).Binary; - - var utils = __webpack_require__(339); - - var deserialize = function (buffer, options, isArray) { - options = options == null ? {} : options; - var index = options && options.index ? options.index : 0; - // Read the document size - var size = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - - // Ensure buffer is valid size - if (size < 5 || buffer.length < size || size + index > buffer.length) { - throw new Error('corrupt bson message'); - } - - // Illegal end value - if (buffer[index + size - 1] !== 0) { - throw new Error("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00"); - } - - // Start deserializtion - return deserializeObject(buffer, index, options, isArray); - }; - - var deserializeObject = function (buffer, index, options, isArray) { - var evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions']; - var cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions']; - var cacheFunctionsCrc32 = options['cacheFunctionsCrc32'] == null ? false : options['cacheFunctionsCrc32']; - - if (!cacheFunctionsCrc32) var crc32 = null; - - var fieldsAsRaw = options['fieldsAsRaw'] == null ? null : options['fieldsAsRaw']; - - // Return raw bson buffer instead of parsing it - var raw = options['raw'] == null ? false : options['raw']; - - // Return BSONRegExp objects instead of native regular expressions - var bsonRegExp = typeof options['bsonRegExp'] === 'boolean' ? options['bsonRegExp'] : false; - - // Controls the promotion of values vs wrapper classes - var promoteBuffers = options['promoteBuffers'] == null ? false : options['promoteBuffers']; - var promoteLongs = options['promoteLongs'] == null ? true : options['promoteLongs']; - var promoteValues = options['promoteValues'] == null ? true : options['promoteValues']; - - // Set the start index - var startIndex = index; - - // Validate that we have at least 4 bytes of buffer - if (buffer.length < 5) throw new Error('corrupt bson message < 5 bytes long'); - - // Read the document size - var size = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - - // Ensure buffer is valid size - if (size < 5 || size > buffer.length) throw new Error('corrupt bson message'); - - // Create holding object - var object = isArray ? [] : {}; - // Used for arrays to skip having to perform utf8 decoding - var arrayIndex = 0; - - var done = false; - - // While we have more left data left keep parsing - // while (buffer[index + 1] !== 0) { - while (!done) { - // Read the type - var elementType = buffer[index++]; - // If we get a zero it's the last byte, exit - if (elementType === 0) break; - - // Get the start search index - var i = index; - // Locate the end of the c string - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - - // If are at the end of the buffer there is a problem with the document - if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); - var name = isArray ? arrayIndex++ : buffer.toString('utf8', index, i); - - index = i + 1; - - if (elementType === BSON.BSON_DATA_STRING) { - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - if (stringSize <= 0 || stringSize > buffer.length - index || buffer[index + stringSize - 1] !== 0) throw new Error('bad string length in bson'); - object[name] = buffer.toString('utf8', index, index + stringSize - 1); - index = index + stringSize; - } else if (elementType === BSON.BSON_DATA_OID) { - var oid = utils.allocBuffer(12); - buffer.copy(oid, 0, index, index + 12); - object[name] = new ObjectID(oid); - index = index + 12; - } else if (elementType === BSON.BSON_DATA_INT && promoteValues === false) { - object[name] = new Int32(buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24); - } else if (elementType === BSON.BSON_DATA_INT) { - object[name] = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - } else if (elementType === BSON.BSON_DATA_NUMBER && promoteValues === false) { - object[name] = new Double(buffer.readDoubleLE(index)); - index = index + 8; - } else if (elementType === BSON.BSON_DATA_NUMBER) { - object[name] = buffer.readDoubleLE(index); - index = index + 8; - } else if (elementType === BSON.BSON_DATA_DATE) { - var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - object[name] = new Date(new Long(lowBits, highBits).toNumber()); - } else if (elementType === BSON.BSON_DATA_BOOLEAN) { - if (buffer[index] !== 0 && buffer[index] !== 1) throw new Error('illegal boolean type value'); - object[name] = buffer[index++] === 1; - } else if (elementType === BSON.BSON_DATA_OBJECT) { - var _index = index; - var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - if (objectSize <= 0 || objectSize > buffer.length - index) throw new Error('bad embedded document length in bson'); - - // We have a raw value - if (raw) { - object[name] = buffer.slice(index, index + objectSize); - } else { - object[name] = deserializeObject(buffer, _index, options, false); - } - - index = index + objectSize; - } else if (elementType === BSON.BSON_DATA_ARRAY) { - _index = index; - objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - var arrayOptions = options; - - // Stop index - var stopIndex = index + objectSize; - - // All elements of array to be returned as raw bson - if (fieldsAsRaw && fieldsAsRaw[name]) { - arrayOptions = {}; - for (var n in options) arrayOptions[n] = options[n]; - arrayOptions['raw'] = true; - } - - object[name] = deserializeObject(buffer, _index, arrayOptions, true); - index = index + objectSize; - - if (buffer[index - 1] !== 0) throw new Error('invalid array terminator byte'); - if (index !== stopIndex) throw new Error('corrupted array bson'); - } else if (elementType === BSON.BSON_DATA_UNDEFINED) { - object[name] = undefined; - } else if (elementType === BSON.BSON_DATA_NULL) { - object[name] = null; - } else if (elementType === BSON.BSON_DATA_LONG) { - // Unpack the low and high bits - lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var long = new Long(lowBits, highBits); - // Promote the long if possible - if (promoteLongs && promoteValues === true) { - object[name] = long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) ? long.toNumber() : long; - } else { - object[name] = long; - } - } else if (elementType === BSON.BSON_DATA_DECIMAL128) { - // Buffer to contain the decimal bytes - var bytes = utils.allocBuffer(16); - // Copy the next 16 bytes into the bytes buffer - buffer.copy(bytes, 0, index, index + 16); - // Update index - index = index + 16; - // Assign the new Decimal128 value - var decimal128 = new Decimal128(bytes); - // If we have an alternative mapper use that - object[name] = decimal128.toObject ? decimal128.toObject() : decimal128; - } else if (elementType === BSON.BSON_DATA_BINARY) { - var binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var totalBinarySize = binarySize; - var subType = buffer[index++]; - - // Did we have a negative binary size, throw - if (binarySize < 0) throw new Error('Negative binary type element size found'); - - // Is the length longer than the document - if (binarySize > buffer.length) throw new Error('Binary type size larger than document size'); - - // Decode as raw Buffer object if options specifies it - if (buffer['slice'] != null) { - // If we have subtype 2 skip the 4 bytes for the size - if (subType === Binary.SUBTYPE_BYTE_ARRAY) { - binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - if (binarySize < 0) throw new Error('Negative binary type element size found for subtype 0x02'); - if (binarySize > totalBinarySize - 4) throw new Error('Binary type with subtype 0x02 contains to long binary size'); - if (binarySize < totalBinarySize - 4) throw new Error('Binary type with subtype 0x02 contains to short binary size'); - } - - if (promoteBuffers && promoteValues) { - object[name] = buffer.slice(index, index + binarySize); - } else { - object[name] = new Binary(buffer.slice(index, index + binarySize), subType); - } - } else { - var _buffer = typeof Uint8Array !== 'undefined' ? new Uint8Array(new ArrayBuffer(binarySize)) : new Array(binarySize); - // If we have subtype 2 skip the 4 bytes for the size - if (subType === Binary.SUBTYPE_BYTE_ARRAY) { - binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - if (binarySize < 0) throw new Error('Negative binary type element size found for subtype 0x02'); - if (binarySize > totalBinarySize - 4) throw new Error('Binary type with subtype 0x02 contains to long binary size'); - if (binarySize < totalBinarySize - 4) throw new Error('Binary type with subtype 0x02 contains to short binary size'); - } - - // Copy the data - for (i = 0; i < binarySize; i++) { - _buffer[i] = buffer[index + i]; - } - - if (promoteBuffers && promoteValues) { - object[name] = _buffer; - } else { - object[name] = new Binary(_buffer, subType); - } - } - - // Update the index - index = index + binarySize; - } else if (elementType === BSON.BSON_DATA_REGEXP && bsonRegExp === false) { - // Get the start search index - i = index; - // Locate the end of the c string - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - // If are at the end of the buffer there is a problem with the document - if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); - // Return the C string - var source = buffer.toString('utf8', index, i); - // Create the regexp - index = i + 1; - - // Get the start search index - i = index; - // Locate the end of the c string - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - // If are at the end of the buffer there is a problem with the document - if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); - // Return the C string - var regExpOptions = buffer.toString('utf8', index, i); - index = i + 1; - - // For each option add the corresponding one for javascript - var optionsArray = new Array(regExpOptions.length); - - // Parse options - for (i = 0; i < regExpOptions.length; i++) { - switch (regExpOptions[i]) { - case 'm': - optionsArray[i] = 'm'; - break; - case 's': - optionsArray[i] = 'g'; - break; - case 'i': - optionsArray[i] = 'i'; - break; - } - } - - object[name] = new RegExp(source, optionsArray.join('')); - } else if (elementType === BSON.BSON_DATA_REGEXP && bsonRegExp === true) { - // Get the start search index - i = index; - // Locate the end of the c string - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - // If are at the end of the buffer there is a problem with the document - if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); - // Return the C string - source = buffer.toString('utf8', index, i); - index = i + 1; - - // Get the start search index - i = index; - // Locate the end of the c string - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - // If are at the end of the buffer there is a problem with the document - if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); - // Return the C string - regExpOptions = buffer.toString('utf8', index, i); - index = i + 1; - - // Set the object - object[name] = new BSONRegExp(source, regExpOptions); - } else if (elementType === BSON.BSON_DATA_SYMBOL) { - stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - if (stringSize <= 0 || stringSize > buffer.length - index || buffer[index + stringSize - 1] !== 0) throw new Error('bad string length in bson'); - object[name] = new Symbol(buffer.toString('utf8', index, index + stringSize - 1)); - index = index + stringSize; - } else if (elementType === BSON.BSON_DATA_TIMESTAMP) { - lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - object[name] = new Timestamp(lowBits, highBits); - } else if (elementType === BSON.BSON_DATA_MIN_KEY) { - object[name] = new MinKey(); - } else if (elementType === BSON.BSON_DATA_MAX_KEY) { - object[name] = new MaxKey(); - } else if (elementType === BSON.BSON_DATA_CODE) { - stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - if (stringSize <= 0 || stringSize > buffer.length - index || buffer[index + stringSize - 1] !== 0) throw new Error('bad string length in bson'); - var functionString = buffer.toString('utf8', index, index + stringSize - 1); - - // If we are evaluating the functions - if (evalFunctions) { - // If we have cache enabled let's look for the md5 of the function in the cache - if (cacheFunctions) { - var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; - // Got to do this to avoid V8 deoptimizing the call due to finding eval - object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); - } else { - object[name] = isolateEval(functionString); - } - } else { - object[name] = new Code(functionString); - } - - // Update parse index position - index = index + stringSize; - } else if (elementType === BSON.BSON_DATA_CODE_W_SCOPE) { - var totalSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - - // Element cannot be shorter than totalSize + stringSize + documentSize + terminator - if (totalSize < 4 + 4 + 4 + 1) { - throw new Error('code_w_scope total size shorter minimum expected length'); - } - - // Get the code string size - stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Check if we have a valid string - if (stringSize <= 0 || stringSize > buffer.length - index || buffer[index + stringSize - 1] !== 0) throw new Error('bad string length in bson'); - - // Javascript function - functionString = buffer.toString('utf8', index, index + stringSize - 1); - // Update parse index position - index = index + stringSize; - // Parse the element - _index = index; - // Decode the size of the object document - objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - // Decode the scope object - var scopeObject = deserializeObject(buffer, _index, options, false); - // Adjust the index - index = index + objectSize; - - // Check if field length is to short - if (totalSize < 4 + 4 + objectSize + stringSize) { - throw new Error('code_w_scope total size is to short, truncating scope'); - } - - // Check if totalSize field is to long - if (totalSize > 4 + 4 + objectSize + stringSize) { - throw new Error('code_w_scope total size is to long, clips outer document'); - } - - // If we are evaluating the functions - if (evalFunctions) { - // If we have cache enabled let's look for the md5 of the function in the cache - if (cacheFunctions) { - hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; - // Got to do this to avoid V8 deoptimizing the call due to finding eval - object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); - } else { - object[name] = isolateEval(functionString); - } - - object[name].scope = scopeObject; - } else { - object[name] = new Code(functionString, scopeObject); - } - } else if (elementType === BSON.BSON_DATA_DBPOINTER) { - // Get the code string size - stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Check if we have a valid string - if (stringSize <= 0 || stringSize > buffer.length - index || buffer[index + stringSize - 1] !== 0) throw new Error('bad string length in bson'); - // Namespace - var namespace = buffer.toString('utf8', index, index + stringSize - 1); - // Update parse index position - index = index + stringSize; - - // Read the oid - var oidBuffer = utils.allocBuffer(12); - buffer.copy(oidBuffer, 0, index, index + 12); - oid = new ObjectID(oidBuffer); - - // Update the index - index = index + 12; - - // Split the namespace - var parts = namespace.split('.'); - var db = parts.shift(); - var collection = parts.join('.'); - // Upgrade to DBRef type - object[name] = new DBRef(collection, oid, db); - } else { - throw new Error('Detected unknown BSON type ' + elementType.toString(16) + ' for fieldname "' + name + '", are you using the latest BSON parser'); - } - } - - // Check if the deserialization was against a valid array/object - if (size !== index - startIndex) { - if (isArray) throw new Error('corrupt array bson'); - throw new Error('corrupt object bson'); - } - - // Check if we have a db ref object - if (object['$id'] != null) object = new DBRef(object['$ref'], object['$id'], object['$db']); - return object; - }; - - /** - * Ensure eval is isolated. - * - * @ignore - * @api private - */ - var isolateEvalWithHash = function (functionCache, hash, functionString, object) { - // Contains the value we are going to set - var value = null; - - // Check for cache hit, eval if missing and return cached function - if (functionCache[hash] == null) { - eval('value = ' + functionString); - functionCache[hash] = value; - } - // Set the object - return functionCache[hash].bind(object); - }; - - /** - * Ensure eval is isolated. - * - * @ignore - * @api private - */ - var isolateEval = function (functionString) { - // Contains the value we are going to set - var value = null; - // Eval the function - eval('value = ' + functionString); - return value; - }; - - var BSON = {}; - - /** - * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 - * - * @ignore - * @api private - */ - var functionCache = BSON.functionCache = {}; - - /** - * Number BSON Type - * - * @classconstant BSON_DATA_NUMBER - **/ - BSON.BSON_DATA_NUMBER = 1; - /** - * String BSON Type - * - * @classconstant BSON_DATA_STRING - **/ - BSON.BSON_DATA_STRING = 2; - /** - * Object BSON Type - * - * @classconstant BSON_DATA_OBJECT - **/ - BSON.BSON_DATA_OBJECT = 3; - /** - * Array BSON Type - * - * @classconstant BSON_DATA_ARRAY - **/ - BSON.BSON_DATA_ARRAY = 4; - /** - * Binary BSON Type - * - * @classconstant BSON_DATA_BINARY - **/ - BSON.BSON_DATA_BINARY = 5; - /** - * Binary BSON Type - * - * @classconstant BSON_DATA_UNDEFINED - **/ - BSON.BSON_DATA_UNDEFINED = 6; - /** - * ObjectID BSON Type - * - * @classconstant BSON_DATA_OID - **/ - BSON.BSON_DATA_OID = 7; - /** - * Boolean BSON Type - * - * @classconstant BSON_DATA_BOOLEAN - **/ - BSON.BSON_DATA_BOOLEAN = 8; - /** - * Date BSON Type - * - * @classconstant BSON_DATA_DATE - **/ - BSON.BSON_DATA_DATE = 9; - /** - * null BSON Type - * - * @classconstant BSON_DATA_NULL - **/ - BSON.BSON_DATA_NULL = 10; - /** - * RegExp BSON Type - * - * @classconstant BSON_DATA_REGEXP - **/ - BSON.BSON_DATA_REGEXP = 11; - /** - * Code BSON Type - * - * @classconstant BSON_DATA_DBPOINTER - **/ - BSON.BSON_DATA_DBPOINTER = 12; - /** - * Code BSON Type - * - * @classconstant BSON_DATA_CODE - **/ - BSON.BSON_DATA_CODE = 13; - /** - * Symbol BSON Type - * - * @classconstant BSON_DATA_SYMBOL - **/ - BSON.BSON_DATA_SYMBOL = 14; - /** - * Code with Scope BSON Type - * - * @classconstant BSON_DATA_CODE_W_SCOPE - **/ - BSON.BSON_DATA_CODE_W_SCOPE = 15; - /** - * 32 bit Integer BSON Type - * - * @classconstant BSON_DATA_INT - **/ - BSON.BSON_DATA_INT = 16; - /** - * Timestamp BSON Type - * - * @classconstant BSON_DATA_TIMESTAMP - **/ - BSON.BSON_DATA_TIMESTAMP = 17; - /** - * Long BSON Type - * - * @classconstant BSON_DATA_LONG - **/ - BSON.BSON_DATA_LONG = 18; - /** - * Long BSON Type - * - * @classconstant BSON_DATA_DECIMAL128 - **/ - BSON.BSON_DATA_DECIMAL128 = 19; - /** - * MinKey BSON Type - * - * @classconstant BSON_DATA_MIN_KEY - **/ - BSON.BSON_DATA_MIN_KEY = 0xff; - /** - * MaxKey BSON Type - * - * @classconstant BSON_DATA_MAX_KEY - **/ - BSON.BSON_DATA_MAX_KEY = 0x7f; - - /** - * Binary Default Type - * - * @classconstant BSON_BINARY_SUBTYPE_DEFAULT - **/ - BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; - /** - * Binary Function Type - * - * @classconstant BSON_BINARY_SUBTYPE_FUNCTION - **/ - BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; - /** - * Binary Byte Array Type - * - * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY - **/ - BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; - /** - * Binary UUID Type - * - * @classconstant BSON_BINARY_SUBTYPE_UUID - **/ - BSON.BSON_BINARY_SUBTYPE_UUID = 3; - /** - * Binary MD5 Type - * - * @classconstant BSON_BINARY_SUBTYPE_MD5 - **/ - BSON.BSON_BINARY_SUBTYPE_MD5 = 4; - /** - * Binary User Defined Type - * - * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED - **/ - BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; - - // BSON MAX VALUES - BSON.BSON_INT32_MAX = 0x7fffffff; - BSON.BSON_INT32_MIN = -0x80000000; - - BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; - BSON.BSON_INT64_MIN = -Math.pow(2, 63); - - // JS MAX PRECISE VALUES - BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. - BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. - - // Internal long versions - var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. - var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. - - module.exports = deserialize; - -/***/ }), -/* 353 */ -/***/ (function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(Buffer) {'use strict'; - - var writeIEEE754 = __webpack_require__(354).writeIEEE754, - Long = __webpack_require__(330).Long, - Map = __webpack_require__(329), - Binary = __webpack_require__(351).Binary; - - var normalizedFunctionString = __webpack_require__(339).normalizedFunctionString; - - // try { - // var _Buffer = Uint8Array; - // } catch (e) { - // _Buffer = Buffer; - // } - - var regexp = /\x00/; // eslint-disable-line no-control-regex - var ignoreKeys = ['$db', '$ref', '$id', '$clusterTime']; - - // To ensure that 0.4 of node works correctly - var isDate = function isDate(d) { - return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; - }; - - var isRegExp = function isRegExp(d) { - return Object.prototype.toString.call(d) === '[object RegExp]'; - }; - - var serializeString = function (buffer, key, value, index, isArray) { - // Encode String type - buffer[index++] = BSON.BSON_DATA_STRING; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write the string - var size = buffer.write(value, index + 4, 'utf8'); - // Write the size of the string to buffer - buffer[index + 3] = size + 1 >> 24 & 0xff; - buffer[index + 2] = size + 1 >> 16 & 0xff; - buffer[index + 1] = size + 1 >> 8 & 0xff; - buffer[index] = size + 1 & 0xff; - // Update index - index = index + 4 + size; - // Write zero - buffer[index++] = 0; - return index; - }; - - var serializeNumber = function (buffer, key, value, index, isArray) { - // We have an integer value - if (Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - // If the value fits in 32 bits encode as int, if it fits in a double - // encode it as a double, otherwise long - if (value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { - // Set int type 32 bits or less - buffer[index++] = BSON.BSON_DATA_INT; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the int value - buffer[index++] = value & 0xff; - buffer[index++] = value >> 8 & 0xff; - buffer[index++] = value >> 16 & 0xff; - buffer[index++] = value >> 24 & 0xff; - } else if (value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - } else { - // Set long type - buffer[index++] = BSON.BSON_DATA_LONG; - // Number of written bytes - numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - var longVal = Long.fromNumber(value); - var lowBits = longVal.getLowBits(); - var highBits = longVal.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = lowBits >> 8 & 0xff; - buffer[index++] = lowBits >> 16 & 0xff; - buffer[index++] = lowBits >> 24 & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = highBits >> 8 & 0xff; - buffer[index++] = highBits >> 16 & 0xff; - buffer[index++] = highBits >> 24 & 0xff; - } - } else { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - } - - return index; - }; - - var serializeNull = function (buffer, key, value, index, isArray) { - // Set long type - buffer[index++] = BSON.BSON_DATA_NULL; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - return index; - }; - - var serializeBoolean = function (buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_BOOLEAN; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Encode the boolean value - buffer[index++] = value ? 1 : 0; - return index; - }; - - var serializeDate = function (buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_DATE; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - - // Write the date - var dateInMilis = Long.fromNumber(value.getTime()); - var lowBits = dateInMilis.getLowBits(); - var highBits = dateInMilis.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = lowBits >> 8 & 0xff; - buffer[index++] = lowBits >> 16 & 0xff; - buffer[index++] = lowBits >> 24 & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = highBits >> 8 & 0xff; - buffer[index++] = highBits >> 16 & 0xff; - buffer[index++] = highBits >> 24 & 0xff; - return index; - }; - - var serializeRegExp = function (buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_REGEXP; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - if (value.source && value.source.match(regexp) != null) { - throw Error('value ' + value.source + ' must not contain null bytes'); - } - // Adjust the index - index = index + buffer.write(value.source, index, 'utf8'); - // Write zero - buffer[index++] = 0x00; - // Write the parameters - if (value.global) buffer[index++] = 0x73; // s - if (value.ignoreCase) buffer[index++] = 0x69; // i - if (value.multiline) buffer[index++] = 0x6d; // m - // Add ending zero - buffer[index++] = 0x00; - return index; - }; - - var serializeBSONRegExp = function (buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_REGEXP; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - - // Check the pattern for 0 bytes - if (value.pattern.match(regexp) != null) { - // The BSON spec doesn't allow keys with null bytes because keys are - // null-terminated. - throw Error('pattern ' + value.pattern + ' must not contain null bytes'); - } - - // Adjust the index - index = index + buffer.write(value.pattern, index, 'utf8'); - // Write zero - buffer[index++] = 0x00; - // Write the options - index = index + buffer.write(value.options.split('').sort().join(''), index, 'utf8'); - // Add ending zero - buffer[index++] = 0x00; - return index; - }; - - var serializeMinMax = function (buffer, key, value, index, isArray) { - // Write the type of either min or max key - if (value === null) { - buffer[index++] = BSON.BSON_DATA_NULL; - } else if (value._bsontype === 'MinKey') { - buffer[index++] = BSON.BSON_DATA_MIN_KEY; - } else { - buffer[index++] = BSON.BSON_DATA_MAX_KEY; - } - - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - return index; - }; - - var serializeObjectId = function (buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_OID; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - - // Write the objectId into the shared buffer - if (typeof value.id === 'string') { - buffer.write(value.id, index, 'binary'); - } else if (value.id && value.id.copy) { - value.id.copy(buffer, index, 0, 12); - } else { - throw new Error('object [' + JSON.stringify(value) + '] is not a valid ObjectId'); - } - - // Ajust index - return index + 12; - }; - - var serializeBuffer = function (buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_BINARY; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Get size of the buffer (current write point) - var size = value.length; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = size >> 8 & 0xff; - buffer[index++] = size >> 16 & 0xff; - buffer[index++] = size >> 24 & 0xff; - // Write the default subtype - buffer[index++] = BSON.BSON_BINARY_SUBTYPE_DEFAULT; - // Copy the content form the binary field to the buffer - value.copy(buffer, index, 0, size); - // Adjust the index - index = index + size; - return index; - }; - - var serializeObject = function (buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, isArray, path) { - for (var i = 0; i < path.length; i++) { - if (path[i] === value) throw new Error('cyclic dependency detected'); - } - - // Push value to stack - path.push(value); - // Write the type - buffer[index++] = Array.isArray(value) ? BSON.BSON_DATA_ARRAY : BSON.BSON_DATA_OBJECT; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - var endIndex = serializeInto(buffer, value, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path); - // Pop stack - path.pop(); - // Write size - return endIndex; - }; - - var serializeDecimal128 = function (buffer, key, value, index, isArray) { - buffer[index++] = BSON.BSON_DATA_DECIMAL128; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the data from the value - value.bytes.copy(buffer, index, 0, 16); - return index + 16; - }; - - var serializeLong = function (buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = value._bsontype === 'Long' ? BSON.BSON_DATA_LONG : BSON.BSON_DATA_TIMESTAMP; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the date - var lowBits = value.getLowBits(); - var highBits = value.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = lowBits >> 8 & 0xff; - buffer[index++] = lowBits >> 16 & 0xff; - buffer[index++] = lowBits >> 24 & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = highBits >> 8 & 0xff; - buffer[index++] = highBits >> 16 & 0xff; - buffer[index++] = highBits >> 24 & 0xff; - return index; - }; - - var serializeInt32 = function (buffer, key, value, index, isArray) { - // Set int type 32 bits or less - buffer[index++] = BSON.BSON_DATA_INT; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the int value - buffer[index++] = value & 0xff; - buffer[index++] = value >> 8 & 0xff; - buffer[index++] = value >> 16 & 0xff; - buffer[index++] = value >> 24 & 0xff; - return index; - }; - - var serializeDouble = function (buffer, key, value, index, isArray) { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - return index; - }; - - var serializeFunction = function (buffer, key, value, index, checkKeys, depth, isArray) { - buffer[index++] = BSON.BSON_DATA_CODE; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Function string - var functionString = normalizedFunctionString(value); - - // Write the string - var size = buffer.write(functionString, index + 4, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = size & 0xff; - buffer[index + 1] = size >> 8 & 0xff; - buffer[index + 2] = size >> 16 & 0xff; - buffer[index + 3] = size >> 24 & 0xff; - // Update index - index = index + 4 + size - 1; - // Write zero - buffer[index++] = 0; - return index; - }; - - var serializeCode = function (buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, isArray) { - if (value.scope && typeof value.scope === 'object') { - // Write the type - buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - - // Starting index - var startIndex = index; - - // Serialize the function - // Get the function string - var functionString = typeof value.code === 'string' ? value.code : value.code.toString(); - // Index adjustment - index = index + 4; - // Write string into buffer - var codeSize = buffer.write(functionString, index + 4, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = codeSize & 0xff; - buffer[index + 1] = codeSize >> 8 & 0xff; - buffer[index + 2] = codeSize >> 16 & 0xff; - buffer[index + 3] = codeSize >> 24 & 0xff; - // Write end 0 - buffer[index + 4 + codeSize - 1] = 0; - // Write the - index = index + codeSize + 4; - - // - // Serialize the scope value - var endIndex = serializeInto(buffer, value.scope, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined); - index = endIndex - 1; - - // Writ the total - var totalSize = endIndex - startIndex; - - // Write the total size of the object - buffer[startIndex++] = totalSize & 0xff; - buffer[startIndex++] = totalSize >> 8 & 0xff; - buffer[startIndex++] = totalSize >> 16 & 0xff; - buffer[startIndex++] = totalSize >> 24 & 0xff; - // Write trailing zero - buffer[index++] = 0; - } else { - buffer[index++] = BSON.BSON_DATA_CODE; - // Number of written bytes - numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Function string - functionString = value.code.toString(); - // Write the string - var size = buffer.write(functionString, index + 4, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = size & 0xff; - buffer[index + 1] = size >> 8 & 0xff; - buffer[index + 2] = size >> 16 & 0xff; - buffer[index + 3] = size >> 24 & 0xff; - // Update index - index = index + 4 + size - 1; - // Write zero - buffer[index++] = 0; - } - - return index; - }; - - var serializeBinary = function (buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_BINARY; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Extract the buffer - var data = value.value(true); - // Calculate size - var size = value.position; - // Add the deprecated 02 type 4 bytes of size to total - if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) size = size + 4; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = size >> 8 & 0xff; - buffer[index++] = size >> 16 & 0xff; - buffer[index++] = size >> 24 & 0xff; - // Write the subtype to the buffer - buffer[index++] = value.sub_type; - - // If we have binary type 2 the 4 first bytes are the size - if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { - size = size - 4; - buffer[index++] = size & 0xff; - buffer[index++] = size >> 8 & 0xff; - buffer[index++] = size >> 16 & 0xff; - buffer[index++] = size >> 24 & 0xff; - } - - // Write the data to the object - data.copy(buffer, index, 0, value.position); - // Adjust the index - index = index + value.position; - return index; - }; - - var serializeSymbol = function (buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_SYMBOL; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the string - var size = buffer.write(value.value, index + 4, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = size & 0xff; - buffer[index + 1] = size >> 8 & 0xff; - buffer[index + 2] = size >> 16 & 0xff; - buffer[index + 3] = size >> 24 & 0xff; - // Update index - index = index + 4 + size - 1; - // Write zero - buffer[index++] = 0x00; - return index; - }; - - var serializeDBRef = function (buffer, key, value, index, depth, serializeFunctions, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_OBJECT; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - - var startIndex = index; - var endIndex; - - // Serialize object - if (null != value.db) { - endIndex = serializeInto(buffer, { - $ref: value.namespace, - $id: value.oid, - $db: value.db - }, false, index, depth + 1, serializeFunctions); - } else { - endIndex = serializeInto(buffer, { - $ref: value.namespace, - $id: value.oid - }, false, index, depth + 1, serializeFunctions); - } - - // Calculate object size - var size = endIndex - startIndex; - // Write the size - buffer[startIndex++] = size & 0xff; - buffer[startIndex++] = size >> 8 & 0xff; - buffer[startIndex++] = size >> 16 & 0xff; - buffer[startIndex++] = size >> 24 & 0xff; - // Set index - return endIndex; - }; - - var serializeInto = function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializeFunctions, ignoreUndefined, path) { - startingIndex = startingIndex || 0; - path = path || []; - - // Push the object to the path - path.push(object); - - // Start place to serialize into - var index = startingIndex + 4; - // var self = this; - - // Special case isArray - if (Array.isArray(object)) { - // Get object keys - for (var i = 0; i < object.length; i++) { - var key = '' + i; - var value = object[i]; - - // Is there an override value - if (value && value.toBSON) { - if (typeof value.toBSON !== 'function') throw new Error('toBSON is not a function'); - value = value.toBSON(); - } - - var type = typeof value; - if (type === 'string') { - index = serializeString(buffer, key, value, index, true); - } else if (type === 'number') { - index = serializeNumber(buffer, key, value, index, true); - } else if (type === 'boolean') { - index = serializeBoolean(buffer, key, value, index, true); - } else if (value instanceof Date || isDate(value)) { - index = serializeDate(buffer, key, value, index, true); - } else if (value === undefined) { - index = serializeNull(buffer, key, value, index, true); - } else if (value === null) { - index = serializeNull(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'ObjectID' || value['_bsontype'] === 'ObjectId') { - index = serializeObjectId(buffer, key, value, index, true); - } else if (Buffer.isBuffer(value)) { - index = serializeBuffer(buffer, key, value, index, true); - } else if (value instanceof RegExp || isRegExp(value)) { - index = serializeRegExp(buffer, key, value, index, true); - } else if (type === 'object' && value['_bsontype'] == null) { - index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, true, path); - } else if (type === 'object' && value['_bsontype'] === 'Decimal128') { - index = serializeDecimal128(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { - index = serializeLong(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'Double') { - index = serializeDouble(buffer, key, value, index, true); - } else if (typeof value === 'function' && serializeFunctions) { - index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions, true); - } else if (value['_bsontype'] === 'Code') { - index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, true); - } else if (value['_bsontype'] === 'Binary') { - index = serializeBinary(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'Symbol') { - index = serializeSymbol(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'DBRef') { - index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, true); - } else if (value['_bsontype'] === 'BSONRegExp') { - index = serializeBSONRegExp(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'Int32') { - index = serializeInt32(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { - index = serializeMinMax(buffer, key, value, index, true); - } - } - } else if (object instanceof Map) { - var iterator = object.entries(); - var done = false; - - while (!done) { - // Unpack the next entry - var entry = iterator.next(); - done = entry.done; - // Are we done, then skip and terminate - if (done) continue; - - // Get the entry values - key = entry.value[0]; - value = entry.value[1]; - - // Check the type of the value - type = typeof value; - - // Check the key and throw error if it's illegal - if (typeof key === 'string' && ignoreKeys.indexOf(key) === -1) { - if (key.match(regexp) != null) { - // The BSON spec doesn't allow keys with null bytes because keys are - // null-terminated. - throw Error('key ' + key + ' must not contain null bytes'); - } - - if (checkKeys) { - if ('$' === key[0]) { - throw Error('key ' + key + " must not start with '$'"); - } else if (~key.indexOf('.')) { - throw Error('key ' + key + " must not contain '.'"); - } - } - } - - if (type === 'string') { - index = serializeString(buffer, key, value, index); - } else if (type === 'number') { - index = serializeNumber(buffer, key, value, index); - } else if (type === 'boolean') { - index = serializeBoolean(buffer, key, value, index); - } else if (value instanceof Date || isDate(value)) { - index = serializeDate(buffer, key, value, index); - // } else if (value === undefined && ignoreUndefined === true) { - } else if (value === null || value === undefined && ignoreUndefined === false) { - index = serializeNull(buffer, key, value, index); - } else if (value['_bsontype'] === 'ObjectID' || value['_bsontype'] === 'ObjectId') { - index = serializeObjectId(buffer, key, value, index); - } else if (Buffer.isBuffer(value)) { - index = serializeBuffer(buffer, key, value, index); - } else if (value instanceof RegExp || isRegExp(value)) { - index = serializeRegExp(buffer, key, value, index); - } else if (type === 'object' && value['_bsontype'] == null) { - index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, false, path); - } else if (type === 'object' && value['_bsontype'] === 'Decimal128') { - index = serializeDecimal128(buffer, key, value, index); - } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { - index = serializeLong(buffer, key, value, index); - } else if (value['_bsontype'] === 'Double') { - index = serializeDouble(buffer, key, value, index); - } else if (value['_bsontype'] === 'Code') { - index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); - } else if (typeof value === 'function' && serializeFunctions) { - index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); - } else if (value['_bsontype'] === 'Binary') { - index = serializeBinary(buffer, key, value, index); - } else if (value['_bsontype'] === 'Symbol') { - index = serializeSymbol(buffer, key, value, index); - } else if (value['_bsontype'] === 'DBRef') { - index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); - } else if (value['_bsontype'] === 'BSONRegExp') { - index = serializeBSONRegExp(buffer, key, value, index); - } else if (value['_bsontype'] === 'Int32') { - index = serializeInt32(buffer, key, value, index); - } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { - index = serializeMinMax(buffer, key, value, index); - } - } - } else { - // Did we provide a custom serialization method - if (object.toBSON) { - if (typeof object.toBSON !== 'function') throw new Error('toBSON is not a function'); - object = object.toBSON(); - if (object != null && typeof object !== 'object') throw new Error('toBSON function did not return an object'); - } - - // Iterate over all the keys - for (key in object) { - value = object[key]; - // Is there an override value - if (value && value.toBSON) { - if (typeof value.toBSON !== 'function') throw new Error('toBSON is not a function'); - value = value.toBSON(); - } - - // Check the type of the value - type = typeof value; - - // Check the key and throw error if it's illegal - if (typeof key === 'string' && ignoreKeys.indexOf(key) === -1) { - if (key.match(regexp) != null) { - // The BSON spec doesn't allow keys with null bytes because keys are - // null-terminated. - throw Error('key ' + key + ' must not contain null bytes'); - } - - if (checkKeys) { - if ('$' === key[0]) { - throw Error('key ' + key + " must not start with '$'"); - } else if (~key.indexOf('.')) { - throw Error('key ' + key + " must not contain '.'"); - } - } - } - - if (type === 'string') { - index = serializeString(buffer, key, value, index); - } else if (type === 'number') { - index = serializeNumber(buffer, key, value, index); - } else if (type === 'boolean') { - index = serializeBoolean(buffer, key, value, index); - } else if (value instanceof Date || isDate(value)) { - index = serializeDate(buffer, key, value, index); - } else if (value === undefined) { - if (ignoreUndefined === false) index = serializeNull(buffer, key, value, index); - } else if (value === null) { - index = serializeNull(buffer, key, value, index); - } else if (value['_bsontype'] === 'ObjectID' || value['_bsontype'] === 'ObjectId') { - index = serializeObjectId(buffer, key, value, index); - } else if (Buffer.isBuffer(value)) { - index = serializeBuffer(buffer, key, value, index); - } else if (value instanceof RegExp || isRegExp(value)) { - index = serializeRegExp(buffer, key, value, index); - } else if (type === 'object' && value['_bsontype'] == null) { - index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, false, path); - } else if (type === 'object' && value['_bsontype'] === 'Decimal128') { - index = serializeDecimal128(buffer, key, value, index); - } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { - index = serializeLong(buffer, key, value, index); - } else if (value['_bsontype'] === 'Double') { - index = serializeDouble(buffer, key, value, index); - } else if (value['_bsontype'] === 'Code') { - index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); - } else if (typeof value === 'function' && serializeFunctions) { - index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); - } else if (value['_bsontype'] === 'Binary') { - index = serializeBinary(buffer, key, value, index); - } else if (value['_bsontype'] === 'Symbol') { - index = serializeSymbol(buffer, key, value, index); - } else if (value['_bsontype'] === 'DBRef') { - index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); - } else if (value['_bsontype'] === 'BSONRegExp') { - index = serializeBSONRegExp(buffer, key, value, index); - } else if (value['_bsontype'] === 'Int32') { - index = serializeInt32(buffer, key, value, index); - } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { - index = serializeMinMax(buffer, key, value, index); - } - } - } - - // Remove the path - path.pop(); - - // Final padding byte for object - buffer[index++] = 0x00; - - // Final size - var size = index - startingIndex; - // Write the size of the object - buffer[startingIndex++] = size & 0xff; - buffer[startingIndex++] = size >> 8 & 0xff; - buffer[startingIndex++] = size >> 16 & 0xff; - buffer[startingIndex++] = size >> 24 & 0xff; - return index; - }; - - var BSON = {}; - - /** - * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 - * - * @ignore - * @api private - */ - // var functionCache = (BSON.functionCache = {}); - - /** - * Number BSON Type - * - * @classconstant BSON_DATA_NUMBER - **/ - BSON.BSON_DATA_NUMBER = 1; - /** - * String BSON Type - * - * @classconstant BSON_DATA_STRING - **/ - BSON.BSON_DATA_STRING = 2; - /** - * Object BSON Type - * - * @classconstant BSON_DATA_OBJECT - **/ - BSON.BSON_DATA_OBJECT = 3; - /** - * Array BSON Type - * - * @classconstant BSON_DATA_ARRAY - **/ - BSON.BSON_DATA_ARRAY = 4; - /** - * Binary BSON Type - * - * @classconstant BSON_DATA_BINARY - **/ - BSON.BSON_DATA_BINARY = 5; - /** - * ObjectID BSON Type, deprecated - * - * @classconstant BSON_DATA_UNDEFINED - **/ - BSON.BSON_DATA_UNDEFINED = 6; - /** - * ObjectID BSON Type - * - * @classconstant BSON_DATA_OID - **/ - BSON.BSON_DATA_OID = 7; - /** - * Boolean BSON Type - * - * @classconstant BSON_DATA_BOOLEAN - **/ - BSON.BSON_DATA_BOOLEAN = 8; - /** - * Date BSON Type - * - * @classconstant BSON_DATA_DATE - **/ - BSON.BSON_DATA_DATE = 9; - /** - * null BSON Type - * - * @classconstant BSON_DATA_NULL - **/ - BSON.BSON_DATA_NULL = 10; - /** - * RegExp BSON Type - * - * @classconstant BSON_DATA_REGEXP - **/ - BSON.BSON_DATA_REGEXP = 11; - /** - * Code BSON Type - * - * @classconstant BSON_DATA_CODE - **/ - BSON.BSON_DATA_CODE = 13; - /** - * Symbol BSON Type - * - * @classconstant BSON_DATA_SYMBOL - **/ - BSON.BSON_DATA_SYMBOL = 14; - /** - * Code with Scope BSON Type - * - * @classconstant BSON_DATA_CODE_W_SCOPE - **/ - BSON.BSON_DATA_CODE_W_SCOPE = 15; - /** - * 32 bit Integer BSON Type - * - * @classconstant BSON_DATA_INT - **/ - BSON.BSON_DATA_INT = 16; - /** - * Timestamp BSON Type - * - * @classconstant BSON_DATA_TIMESTAMP - **/ - BSON.BSON_DATA_TIMESTAMP = 17; - /** - * Long BSON Type - * - * @classconstant BSON_DATA_LONG - **/ - BSON.BSON_DATA_LONG = 18; - /** - * Long BSON Type - * - * @classconstant BSON_DATA_DECIMAL128 - **/ - BSON.BSON_DATA_DECIMAL128 = 19; - /** - * MinKey BSON Type - * - * @classconstant BSON_DATA_MIN_KEY - **/ - BSON.BSON_DATA_MIN_KEY = 0xff; - /** - * MaxKey BSON Type - * - * @classconstant BSON_DATA_MAX_KEY - **/ - BSON.BSON_DATA_MAX_KEY = 0x7f; - /** - * Binary Default Type - * - * @classconstant BSON_BINARY_SUBTYPE_DEFAULT - **/ - BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; - /** - * Binary Function Type - * - * @classconstant BSON_BINARY_SUBTYPE_FUNCTION - **/ - BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; - /** - * Binary Byte Array Type - * - * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY - **/ - BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; - /** - * Binary UUID Type - * - * @classconstant BSON_BINARY_SUBTYPE_UUID - **/ - BSON.BSON_BINARY_SUBTYPE_UUID = 3; - /** - * Binary MD5 Type - * - * @classconstant BSON_BINARY_SUBTYPE_MD5 - **/ - BSON.BSON_BINARY_SUBTYPE_MD5 = 4; - /** - * Binary User Defined Type - * - * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED - **/ - BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; - - // BSON MAX VALUES - BSON.BSON_INT32_MAX = 0x7fffffff; - BSON.BSON_INT32_MIN = -0x80000000; - - BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; - BSON.BSON_INT64_MIN = -Math.pow(2, 63); - - // JS MAX PRECISE VALUES - BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. - BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. - - // Internal long versions - // var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. - // var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. - - module.exports = serializeInto; - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(334).Buffer)) - -/***/ }), -/* 354 */ -/***/ (function(module, exports) { - - // Copyright (c) 2008, Fair Oaks Labs, Inc. - // All rights reserved. - // - // Redistribution and use in source and binary forms, with or without - // modification, are permitted provided that the following conditions are met: - // - // * Redistributions of source code must retain the above copyright notice, - // this list of conditions and the following disclaimer. - // - // * Redistributions in binary form must reproduce the above copyright notice, - // this list of conditions and the following disclaimer in the documentation - // and/or other materials provided with the distribution. - // - // * Neither the name of Fair Oaks Labs, Inc. nor the names of its contributors - // may be used to endorse or promote products derived from this software - // without specific prior written permission. - // - // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - // POSSIBILITY OF SUCH DAMAGE. - // - // - // Modifications to writeIEEE754 to support negative zeroes made by Brian White - - var readIEEE754 = function (buffer, offset, endian, mLen, nBytes) { - var e, - m, - bBE = endian === 'big', - eLen = nBytes * 8 - mLen - 1, - eMax = (1 << eLen) - 1, - eBias = eMax >> 1, - nBits = -7, - i = bBE ? 0 : nBytes - 1, - d = bBE ? 1 : -1, - s = buffer[offset + i]; - - i += d; - - e = s & (1 << -nBits) - 1; - s >>= -nBits; - nBits += eLen; - for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8); - - m = e & (1 << -nBits) - 1; - e >>= -nBits; - nBits += mLen; - for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8); - - if (e === 0) { - e = 1 - eBias; - } else if (e === eMax) { - return m ? NaN : (s ? -1 : 1) * Infinity; - } else { - m = m + Math.pow(2, mLen); - e = e - eBias; - } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen); - }; - - var writeIEEE754 = function (buffer, value, offset, endian, mLen, nBytes) { - var e, - m, - c, - bBE = endian === 'big', - eLen = nBytes * 8 - mLen - 1, - eMax = (1 << eLen) - 1, - eBias = eMax >> 1, - rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0, - i = bBE ? nBytes - 1 : 0, - d = bBE ? -1 : 1, - s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0; - - value = Math.abs(value); - - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0; - e = eMax; - } else { - e = Math.floor(Math.log(value) / Math.LN2); - if (value * (c = Math.pow(2, -e)) < 1) { - e--; - c *= 2; - } - if (e + eBias >= 1) { - value += rt / c; - } else { - value += rt * Math.pow(2, 1 - eBias); - } - if (value * c >= 2) { - e++; - c /= 2; - } - - if (e + eBias >= eMax) { - m = 0; - e = eMax; - } else if (e + eBias >= 1) { - m = (value * c - 1) * Math.pow(2, mLen); - e = e + eBias; - } else { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); - e = 0; - } - } - - for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8); - - e = e << mLen | m; - eLen += mLen; - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8); - - buffer[offset + i - d] |= s * 128; - }; - - exports.readIEEE754 = readIEEE754; - exports.writeIEEE754 = writeIEEE754; - -/***/ }), -/* 355 */ -/***/ (function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(Buffer) {'use strict'; - - var Long = __webpack_require__(330).Long, - Double = __webpack_require__(331).Double, - Timestamp = __webpack_require__(332).Timestamp, - ObjectID = __webpack_require__(333).ObjectID, - Symbol = __webpack_require__(344).Symbol, - BSONRegExp = __webpack_require__(343).BSONRegExp, - Code = __webpack_require__(346).Code, - Decimal128 = __webpack_require__(347), - MinKey = __webpack_require__(348).MinKey, - MaxKey = __webpack_require__(349).MaxKey, - DBRef = __webpack_require__(350).DBRef, - Binary = __webpack_require__(351).Binary; - - var normalizedFunctionString = __webpack_require__(339).normalizedFunctionString; - - // To ensure that 0.4 of node works correctly - var isDate = function isDate(d) { - return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; - }; - - var calculateObjectSize = function calculateObjectSize(object, serializeFunctions, ignoreUndefined) { - var totalLength = 4 + 1; - - if (Array.isArray(object)) { - for (var i = 0; i < object.length; i++) { - totalLength += calculateElement(i.toString(), object[i], serializeFunctions, true, ignoreUndefined); - } - } else { - // If we have toBSON defined, override the current object - if (object.toBSON) { - object = object.toBSON(); - } - - // Calculate size - for (var key in object) { - totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined); - } - } - - return totalLength; - }; - - /** - * @ignore - * @api private - */ - function calculateElement(name, value, serializeFunctions, isArray, ignoreUndefined) { - // If we have toBSON defined, override the current object - if (value && value.toBSON) { - value = value.toBSON(); - } - - switch (typeof value) { - case 'string': - return 1 + Buffer.byteLength(name, 'utf8') + 1 + 4 + Buffer.byteLength(value, 'utf8') + 1; - case 'number': - if (Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - if (value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { - // 32 bit - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (4 + 1); - } else { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); - } - } else { - // 64 bit - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); - } - case 'undefined': - if (isArray || !ignoreUndefined) return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1; - return 0; - case 'boolean': - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (1 + 1); - case 'object': - if (value == null || value instanceof MinKey || value instanceof MaxKey || value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1; - } else if (value instanceof ObjectID || value['_bsontype'] === 'ObjectID' || value['_bsontype'] === 'ObjectId') { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (12 + 1); - } else if (value instanceof Date || isDate(value)) { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); - } else if (typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (1 + 4 + 1) + value.length; - } else if (value instanceof Long || value instanceof Double || value instanceof Timestamp || value['_bsontype'] === 'Long' || value['_bsontype'] === 'Double' || value['_bsontype'] === 'Timestamp') { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); - } else if (value instanceof Decimal128 || value['_bsontype'] === 'Decimal128') { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (16 + 1); - } else if (value instanceof Code || value['_bsontype'] === 'Code') { - // Calculate size depending on the availability of a scope - if (value.scope != null && Object.keys(value.scope).length > 0) { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + 4 + 4 + Buffer.byteLength(value.code.toString(), 'utf8') + 1 + calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined); - } else { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + 4 + Buffer.byteLength(value.code.toString(), 'utf8') + 1; - } - } else if (value instanceof Binary || value['_bsontype'] === 'Binary') { - // Check what kind of subtype we have - if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (value.position + 1 + 4 + 1 + 4); - } else { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (value.position + 1 + 4 + 1); - } - } else if (value instanceof Symbol || value['_bsontype'] === 'Symbol') { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + Buffer.byteLength(value.value, 'utf8') + 4 + 1 + 1; - } else if (value instanceof DBRef || value['_bsontype'] === 'DBRef') { - // Set up correct object for serialization - var ordered_values = { - $ref: value.namespace, - $id: value.oid - }; - - // Add db reference if it exists - if (null != value.db) { - ordered_values['$db'] = value.db; - } - - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + calculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined); - } else if (value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]') { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + Buffer.byteLength(value.source, 'utf8') + 1 + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1; - } else if (value instanceof BSONRegExp || value['_bsontype'] === 'BSONRegExp') { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + Buffer.byteLength(value.pattern, 'utf8') + 1 + Buffer.byteLength(value.options, 'utf8') + 1; - } else { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + calculateObjectSize(value, serializeFunctions, ignoreUndefined) + 1; - } - case 'function': - // WTF for 0.4.X where typeof /someregexp/ === 'function' - if (value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]' || String.call(value) === '[object RegExp]') { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + Buffer.byteLength(value.source, 'utf8') + 1 + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1; - } else { - if (serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + 4 + 4 + Buffer.byteLength(normalizedFunctionString(value), 'utf8') + 1 + calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined); - } else if (serializeFunctions) { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + 4 + Buffer.byteLength(normalizedFunctionString(value), 'utf8') + 1; - } - } - } - - return 0; - } - - var BSON = {}; - - // BSON MAX VALUES - BSON.BSON_INT32_MAX = 0x7fffffff; - BSON.BSON_INT32_MIN = -0x80000000; - - // JS MAX PRECISE VALUES - BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. - BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. - - module.exports = calculateObjectSize; - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(334).Buffer)) - -/***/ }) -/******/ ]) -}); -; \ No newline at end of file diff --git a/scripts/2.5/node_modules/bson/browser_build/package.json b/scripts/2.5/node_modules/bson/browser_build/package.json deleted file mode 100644 index 980db7f9..00000000 --- a/scripts/2.5/node_modules/bson/browser_build/package.json +++ /dev/null @@ -1,8 +0,0 @@ -{ "name" : "bson" -, "description" : "A bson parser for node.js and the browser" -, "main": "../" -, "directories" : { "lib" : "../lib/bson" } -, "engines" : { "node" : ">=0.6.0" } -, "licenses" : [ { "type" : "Apache License, Version 2.0" - , "url" : "http://www.apache.org/licenses/LICENSE-2.0" } ] -} diff --git a/scripts/2.5/node_modules/bson/index.js b/scripts/2.5/node_modules/bson/index.js deleted file mode 100644 index 6502552d..00000000 --- a/scripts/2.5/node_modules/bson/index.js +++ /dev/null @@ -1,46 +0,0 @@ -var BSON = require('./lib/bson/bson'), - Binary = require('./lib/bson/binary'), - Code = require('./lib/bson/code'), - DBRef = require('./lib/bson/db_ref'), - Decimal128 = require('./lib/bson/decimal128'), - Double = require('./lib/bson/double'), - Int32 = require('./lib/bson/int_32'), - Long = require('./lib/bson/long'), - Map = require('./lib/bson/map'), - MaxKey = require('./lib/bson/max_key'), - MinKey = require('./lib/bson/min_key'), - ObjectId = require('./lib/bson/objectid'), - BSONRegExp = require('./lib/bson/regexp'), - Symbol = require('./lib/bson/symbol'), - Timestamp = require('./lib/bson/timestamp'); - -// BSON MAX VALUES -BSON.BSON_INT32_MAX = 0x7fffffff; -BSON.BSON_INT32_MIN = -0x80000000; - -BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; -BSON.BSON_INT64_MIN = -Math.pow(2, 63); - -// JS MAX PRECISE VALUES -BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. -BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. - -// Add BSON types to function creation -BSON.Binary = Binary; -BSON.Code = Code; -BSON.DBRef = DBRef; -BSON.Decimal128 = Decimal128; -BSON.Double = Double; -BSON.Int32 = Int32; -BSON.Long = Long; -BSON.Map = Map; -BSON.MaxKey = MaxKey; -BSON.MinKey = MinKey; -BSON.ObjectId = ObjectId; -BSON.ObjectID = ObjectId; -BSON.BSONRegExp = BSONRegExp; -BSON.Symbol = Symbol; -BSON.Timestamp = Timestamp; - -// Return the BSON -module.exports = BSON; diff --git a/scripts/2.5/node_modules/bson/lib/bson/binary.js b/scripts/2.5/node_modules/bson/lib/bson/binary.js deleted file mode 100644 index 6d190bca..00000000 --- a/scripts/2.5/node_modules/bson/lib/bson/binary.js +++ /dev/null @@ -1,384 +0,0 @@ -/** - * Module dependencies. - * @ignore - */ - -// Test if we're in Node via presence of "global" not absence of "window" -// to support hybrid environments like Electron -if (typeof global !== 'undefined') { - var Buffer = require('buffer').Buffer; // TODO just use global Buffer -} - -var utils = require('./parser/utils'); - -/** - * A class representation of the BSON Binary type. - * - * Sub types - * - **BSON.BSON_BINARY_SUBTYPE_DEFAULT**, default BSON type. - * - **BSON.BSON_BINARY_SUBTYPE_FUNCTION**, BSON function type. - * - **BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY**, BSON byte array type. - * - **BSON.BSON_BINARY_SUBTYPE_UUID**, BSON uuid type. - * - **BSON.BSON_BINARY_SUBTYPE_MD5**, BSON md5 type. - * - **BSON.BSON_BINARY_SUBTYPE_USER_DEFINED**, BSON user defined type. - * - * @class - * @param {Buffer} buffer a buffer object containing the binary data. - * @param {Number} [subType] the option binary type. - * @return {Binary} - */ -function Binary(buffer, subType) { - if (!(this instanceof Binary)) return new Binary(buffer, subType); - - if ( - buffer != null && - !(typeof buffer === 'string') && - !Buffer.isBuffer(buffer) && - !(buffer instanceof Uint8Array) && - !Array.isArray(buffer) - ) { - throw new Error('only String, Buffer, Uint8Array or Array accepted'); - } - - this._bsontype = 'Binary'; - - if (buffer instanceof Number) { - this.sub_type = buffer; - this.position = 0; - } else { - this.sub_type = subType == null ? BSON_BINARY_SUBTYPE_DEFAULT : subType; - this.position = 0; - } - - if (buffer != null && !(buffer instanceof Number)) { - // Only accept Buffer, Uint8Array or Arrays - if (typeof buffer === 'string') { - // Different ways of writing the length of the string for the different types - if (typeof Buffer !== 'undefined') { - this.buffer = utils.toBuffer(buffer); - } else if ( - typeof Uint8Array !== 'undefined' || - Object.prototype.toString.call(buffer) === '[object Array]' - ) { - this.buffer = writeStringToArray(buffer); - } else { - throw new Error('only String, Buffer, Uint8Array or Array accepted'); - } - } else { - this.buffer = buffer; - } - this.position = buffer.length; - } else { - if (typeof Buffer !== 'undefined') { - this.buffer = utils.allocBuffer(Binary.BUFFER_SIZE); - } else if (typeof Uint8Array !== 'undefined') { - this.buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE)); - } else { - this.buffer = new Array(Binary.BUFFER_SIZE); - } - // Set position to start of buffer - this.position = 0; - } -} - -/** - * Updates this binary with byte_value. - * - * @method - * @param {string} byte_value a single byte we wish to write. - */ -Binary.prototype.put = function put(byte_value) { - // If it's a string and a has more than one character throw an error - if (byte_value['length'] != null && typeof byte_value !== 'number' && byte_value.length !== 1) - throw new Error('only accepts single character String, Uint8Array or Array'); - if ((typeof byte_value !== 'number' && byte_value < 0) || byte_value > 255) - throw new Error('only accepts number in a valid unsigned byte range 0-255'); - - // Decode the byte value once - var decoded_byte = null; - if (typeof byte_value === 'string') { - decoded_byte = byte_value.charCodeAt(0); - } else if (byte_value['length'] != null) { - decoded_byte = byte_value[0]; - } else { - decoded_byte = byte_value; - } - - if (this.buffer.length > this.position) { - this.buffer[this.position++] = decoded_byte; - } else { - if (typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer)) { - // Create additional overflow buffer - var buffer = utils.allocBuffer(Binary.BUFFER_SIZE + this.buffer.length); - // Combine the two buffers together - this.buffer.copy(buffer, 0, 0, this.buffer.length); - this.buffer = buffer; - this.buffer[this.position++] = decoded_byte; - } else { - buffer = null; - // Create a new buffer (typed or normal array) - if (Object.prototype.toString.call(this.buffer) === '[object Uint8Array]') { - buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE + this.buffer.length)); - } else { - buffer = new Array(Binary.BUFFER_SIZE + this.buffer.length); - } - - // We need to copy all the content to the new array - for (var i = 0; i < this.buffer.length; i++) { - buffer[i] = this.buffer[i]; - } - - // Reassign the buffer - this.buffer = buffer; - // Write the byte - this.buffer[this.position++] = decoded_byte; - } - } -}; - -/** - * Writes a buffer or string to the binary. - * - * @method - * @param {(Buffer|string)} string a string or buffer to be written to the Binary BSON object. - * @param {number} offset specify the binary of where to write the content. - * @return {null} - */ -Binary.prototype.write = function write(string, offset) { - offset = typeof offset === 'number' ? offset : this.position; - - // If the buffer is to small let's extend the buffer - if (this.buffer.length < offset + string.length) { - var buffer = null; - // If we are in node.js - if (typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer)) { - buffer = utils.allocBuffer(this.buffer.length + string.length); - this.buffer.copy(buffer, 0, 0, this.buffer.length); - } else if (Object.prototype.toString.call(this.buffer) === '[object Uint8Array]') { - // Create a new buffer - buffer = new Uint8Array(new ArrayBuffer(this.buffer.length + string.length)); - // Copy the content - for (var i = 0; i < this.position; i++) { - buffer[i] = this.buffer[i]; - } - } - - // Assign the new buffer - this.buffer = buffer; - } - - if (typeof Buffer !== 'undefined' && Buffer.isBuffer(string) && Buffer.isBuffer(this.buffer)) { - string.copy(this.buffer, offset, 0, string.length); - this.position = offset + string.length > this.position ? offset + string.length : this.position; - // offset = string.length - } else if ( - typeof Buffer !== 'undefined' && - typeof string === 'string' && - Buffer.isBuffer(this.buffer) - ) { - this.buffer.write(string, offset, 'binary'); - this.position = offset + string.length > this.position ? offset + string.length : this.position; - // offset = string.length; - } else if ( - Object.prototype.toString.call(string) === '[object Uint8Array]' || - (Object.prototype.toString.call(string) === '[object Array]' && typeof string !== 'string') - ) { - for (i = 0; i < string.length; i++) { - this.buffer[offset++] = string[i]; - } - - this.position = offset > this.position ? offset : this.position; - } else if (typeof string === 'string') { - for (i = 0; i < string.length; i++) { - this.buffer[offset++] = string.charCodeAt(i); - } - - this.position = offset > this.position ? offset : this.position; - } -}; - -/** - * Reads **length** bytes starting at **position**. - * - * @method - * @param {number} position read from the given position in the Binary. - * @param {number} length the number of bytes to read. - * @return {Buffer} - */ -Binary.prototype.read = function read(position, length) { - length = length && length > 0 ? length : this.position; - - // Let's return the data based on the type we have - if (this.buffer['slice']) { - return this.buffer.slice(position, position + length); - } else { - // Create a buffer to keep the result - var buffer = - typeof Uint8Array !== 'undefined' - ? new Uint8Array(new ArrayBuffer(length)) - : new Array(length); - for (var i = 0; i < length; i++) { - buffer[i] = this.buffer[position++]; - } - } - // Return the buffer - return buffer; -}; - -/** - * Returns the value of this binary as a string. - * - * @method - * @return {string} - */ -Binary.prototype.value = function value(asRaw) { - asRaw = asRaw == null ? false : asRaw; - - // Optimize to serialize for the situation where the data == size of buffer - if ( - asRaw && - typeof Buffer !== 'undefined' && - Buffer.isBuffer(this.buffer) && - this.buffer.length === this.position - ) - return this.buffer; - - // If it's a node.js buffer object - if (typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer)) { - return asRaw - ? this.buffer.slice(0, this.position) - : this.buffer.toString('binary', 0, this.position); - } else { - if (asRaw) { - // we support the slice command use it - if (this.buffer['slice'] != null) { - return this.buffer.slice(0, this.position); - } else { - // Create a new buffer to copy content to - var newBuffer = - Object.prototype.toString.call(this.buffer) === '[object Uint8Array]' - ? new Uint8Array(new ArrayBuffer(this.position)) - : new Array(this.position); - // Copy content - for (var i = 0; i < this.position; i++) { - newBuffer[i] = this.buffer[i]; - } - // Return the buffer - return newBuffer; - } - } else { - return convertArraytoUtf8BinaryString(this.buffer, 0, this.position); - } - } -}; - -/** - * Length. - * - * @method - * @return {number} the length of the binary. - */ -Binary.prototype.length = function length() { - return this.position; -}; - -/** - * @ignore - */ -Binary.prototype.toJSON = function() { - return this.buffer != null ? this.buffer.toString('base64') : ''; -}; - -/** - * @ignore - */ -Binary.prototype.toString = function(format) { - return this.buffer != null ? this.buffer.slice(0, this.position).toString(format) : ''; -}; - -/** - * Binary default subtype - * @ignore - */ -var BSON_BINARY_SUBTYPE_DEFAULT = 0; - -/** - * @ignore - */ -var writeStringToArray = function(data) { - // Create a buffer - var buffer = - typeof Uint8Array !== 'undefined' - ? new Uint8Array(new ArrayBuffer(data.length)) - : new Array(data.length); - // Write the content to the buffer - for (var i = 0; i < data.length; i++) { - buffer[i] = data.charCodeAt(i); - } - // Write the string to the buffer - return buffer; -}; - -/** - * Convert Array ot Uint8Array to Binary String - * - * @ignore - */ -var convertArraytoUtf8BinaryString = function(byteArray, startIndex, endIndex) { - var result = ''; - for (var i = startIndex; i < endIndex; i++) { - result = result + String.fromCharCode(byteArray[i]); - } - return result; -}; - -Binary.BUFFER_SIZE = 256; - -/** - * Default BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_DEFAULT = 0; -/** - * Function BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_FUNCTION = 1; -/** - * Byte Array BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_BYTE_ARRAY = 2; -/** - * OLD UUID BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_UUID_OLD = 3; -/** - * UUID BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_UUID = 4; -/** - * MD5 BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_MD5 = 5; -/** - * User BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_USER_DEFINED = 128; - -/** - * Expose. - */ -module.exports = Binary; -module.exports.Binary = Binary; diff --git a/scripts/2.5/node_modules/bson/lib/bson/bson.js b/scripts/2.5/node_modules/bson/lib/bson/bson.js deleted file mode 100644 index 912c5b92..00000000 --- a/scripts/2.5/node_modules/bson/lib/bson/bson.js +++ /dev/null @@ -1,386 +0,0 @@ -'use strict'; - -var Map = require('./map'), - Long = require('./long'), - Double = require('./double'), - Timestamp = require('./timestamp'), - ObjectID = require('./objectid'), - BSONRegExp = require('./regexp'), - Symbol = require('./symbol'), - Int32 = require('./int_32'), - Code = require('./code'), - Decimal128 = require('./decimal128'), - MinKey = require('./min_key'), - MaxKey = require('./max_key'), - DBRef = require('./db_ref'), - Binary = require('./binary'); - -// Parts of the parser -var deserialize = require('./parser/deserializer'), - serializer = require('./parser/serializer'), - calculateObjectSize = require('./parser/calculate_size'), - utils = require('./parser/utils'); - -/** - * @ignore - * @api private - */ -// Default Max Size -var MAXSIZE = 1024 * 1024 * 17; - -// Current Internal Temporary Serialization Buffer -var buffer = utils.allocBuffer(MAXSIZE); - -var BSON = function() {}; - -/** - * Serialize a Javascript object. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} [options.checkKeys] the serializer will check if keys are valid. - * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. - * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. - * @param {Number} [options.minInternalBufferSize=1024*1024*17] minimum size of the internal temporary serialization buffer **(default:1024*1024*17)**. - * @return {Buffer} returns the Buffer object containing the serialized object. - * @api public - */ -BSON.prototype.serialize = function serialize(object, options) { - options = options || {}; - // Unpack the options - var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; - var serializeFunctions = - typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; - var ignoreUndefined = - typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; - var minInternalBufferSize = - typeof options.minInternalBufferSize === 'number' ? options.minInternalBufferSize : MAXSIZE; - - // Resize the internal serialization buffer if needed - if (buffer.length < minInternalBufferSize) { - buffer = utils.allocBuffer(minInternalBufferSize); - } - - // Attempt to serialize - var serializationIndex = serializer( - buffer, - object, - checkKeys, - 0, - 0, - serializeFunctions, - ignoreUndefined, - [] - ); - // Create the final buffer - var finishedBuffer = utils.allocBuffer(serializationIndex); - // Copy into the finished buffer - buffer.copy(finishedBuffer, 0, 0, finishedBuffer.length); - // Return the buffer - return finishedBuffer; -}; - -/** - * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. - * - * @param {Object} object the Javascript object to serialize. - * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. - * @param {Boolean} [options.checkKeys] the serializer will check if keys are valid. - * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. - * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. - * @param {Number} [options.index] the index in the buffer where we wish to start serializing into. - * @return {Number} returns the index pointing to the last written byte in the buffer. - * @api public - */ -BSON.prototype.serializeWithBufferAndIndex = function(object, finalBuffer, options) { - options = options || {}; - // Unpack the options - var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; - var serializeFunctions = - typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; - var ignoreUndefined = - typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; - var startIndex = typeof options.index === 'number' ? options.index : 0; - - // Attempt to serialize - var serializationIndex = serializer( - finalBuffer, - object, - checkKeys, - startIndex || 0, - 0, - serializeFunctions, - ignoreUndefined - ); - - // Return the index - return serializationIndex - 1; -}; - -/** - * Deserialize data as BSON. - * - * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. - * @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized. - * @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse. - * @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function. - * @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits - * @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a node.js Buffer instance. - * @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types. - * @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer. - * @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances. - * @return {Object} returns the deserialized Javascript Object. - * @api public - */ -BSON.prototype.deserialize = function(buffer, options) { - return deserialize(buffer, options); -}; - -/** - * Calculate the bson size for a passed in Javascript object. - * - * @param {Object} object the Javascript object to calculate the BSON byte size for. - * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. - * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. - * @return {Number} returns the number of bytes the BSON object will take up. - * @api public - */ -BSON.prototype.calculateObjectSize = function(object, options) { - options = options || {}; - - var serializeFunctions = - typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; - var ignoreUndefined = - typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; - - return calculateObjectSize(object, serializeFunctions, ignoreUndefined); -}; - -/** - * Deserialize stream data as BSON documents. - * - * @param {Buffer} data the buffer containing the serialized set of BSON documents. - * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. - * @param {Number} numberOfDocuments number of documents to deserialize. - * @param {Array} documents an array where to store the deserialized documents. - * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. - * @param {Object} [options] additional options used for the deserialization. - * @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized. - * @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse. - * @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function. - * @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits - * @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a node.js Buffer instance. - * @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types. - * @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer. - * @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances. - * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. - * @api public - */ -BSON.prototype.deserializeStream = function( - data, - startIndex, - numberOfDocuments, - documents, - docStartIndex, - options -) { - options = options != null ? options : {}; - var index = startIndex; - // Loop over all documents - for (var i = 0; i < numberOfDocuments; i++) { - // Find size of the document - var size = - data[index] | (data[index + 1] << 8) | (data[index + 2] << 16) | (data[index + 3] << 24); - // Update options with index - options['index'] = index; - // Parse the document at this point - documents[docStartIndex + i] = this.deserialize(data, options); - // Adjust index by the document size - index = index + size; - } - - // Return object containing end index of parsing and list of documents - return index; -}; - -/** - * @ignore - * @api private - */ -// BSON MAX VALUES -BSON.BSON_INT32_MAX = 0x7fffffff; -BSON.BSON_INT32_MIN = -0x80000000; - -BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; -BSON.BSON_INT64_MIN = -Math.pow(2, 63); - -// JS MAX PRECISE VALUES -BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. -BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. - -// Internal long versions -// var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. -// var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. - -/** - * Number BSON Type - * - * @classconstant BSON_DATA_NUMBER - **/ -BSON.BSON_DATA_NUMBER = 1; -/** - * String BSON Type - * - * @classconstant BSON_DATA_STRING - **/ -BSON.BSON_DATA_STRING = 2; -/** - * Object BSON Type - * - * @classconstant BSON_DATA_OBJECT - **/ -BSON.BSON_DATA_OBJECT = 3; -/** - * Array BSON Type - * - * @classconstant BSON_DATA_ARRAY - **/ -BSON.BSON_DATA_ARRAY = 4; -/** - * Binary BSON Type - * - * @classconstant BSON_DATA_BINARY - **/ -BSON.BSON_DATA_BINARY = 5; -/** - * ObjectID BSON Type - * - * @classconstant BSON_DATA_OID - **/ -BSON.BSON_DATA_OID = 7; -/** - * Boolean BSON Type - * - * @classconstant BSON_DATA_BOOLEAN - **/ -BSON.BSON_DATA_BOOLEAN = 8; -/** - * Date BSON Type - * - * @classconstant BSON_DATA_DATE - **/ -BSON.BSON_DATA_DATE = 9; -/** - * null BSON Type - * - * @classconstant BSON_DATA_NULL - **/ -BSON.BSON_DATA_NULL = 10; -/** - * RegExp BSON Type - * - * @classconstant BSON_DATA_REGEXP - **/ -BSON.BSON_DATA_REGEXP = 11; -/** - * Code BSON Type - * - * @classconstant BSON_DATA_CODE - **/ -BSON.BSON_DATA_CODE = 13; -/** - * Symbol BSON Type - * - * @classconstant BSON_DATA_SYMBOL - **/ -BSON.BSON_DATA_SYMBOL = 14; -/** - * Code with Scope BSON Type - * - * @classconstant BSON_DATA_CODE_W_SCOPE - **/ -BSON.BSON_DATA_CODE_W_SCOPE = 15; -/** - * 32 bit Integer BSON Type - * - * @classconstant BSON_DATA_INT - **/ -BSON.BSON_DATA_INT = 16; -/** - * Timestamp BSON Type - * - * @classconstant BSON_DATA_TIMESTAMP - **/ -BSON.BSON_DATA_TIMESTAMP = 17; -/** - * Long BSON Type - * - * @classconstant BSON_DATA_LONG - **/ -BSON.BSON_DATA_LONG = 18; -/** - * MinKey BSON Type - * - * @classconstant BSON_DATA_MIN_KEY - **/ -BSON.BSON_DATA_MIN_KEY = 0xff; -/** - * MaxKey BSON Type - * - * @classconstant BSON_DATA_MAX_KEY - **/ -BSON.BSON_DATA_MAX_KEY = 0x7f; - -/** - * Binary Default Type - * - * @classconstant BSON_BINARY_SUBTYPE_DEFAULT - **/ -BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; -/** - * Binary Function Type - * - * @classconstant BSON_BINARY_SUBTYPE_FUNCTION - **/ -BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; -/** - * Binary Byte Array Type - * - * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY - **/ -BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; -/** - * Binary UUID Type - * - * @classconstant BSON_BINARY_SUBTYPE_UUID - **/ -BSON.BSON_BINARY_SUBTYPE_UUID = 3; -/** - * Binary MD5 Type - * - * @classconstant BSON_BINARY_SUBTYPE_MD5 - **/ -BSON.BSON_BINARY_SUBTYPE_MD5 = 4; -/** - * Binary User Defined Type - * - * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED - **/ -BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; - -// Return BSON -module.exports = BSON; -module.exports.Code = Code; -module.exports.Map = Map; -module.exports.Symbol = Symbol; -module.exports.BSON = BSON; -module.exports.DBRef = DBRef; -module.exports.Binary = Binary; -module.exports.ObjectID = ObjectID; -module.exports.Long = Long; -module.exports.Timestamp = Timestamp; -module.exports.Double = Double; -module.exports.Int32 = Int32; -module.exports.MinKey = MinKey; -module.exports.MaxKey = MaxKey; -module.exports.BSONRegExp = BSONRegExp; -module.exports.Decimal128 = Decimal128; diff --git a/scripts/2.5/node_modules/bson/lib/bson/code.js b/scripts/2.5/node_modules/bson/lib/bson/code.js deleted file mode 100644 index c2984cd5..00000000 --- a/scripts/2.5/node_modules/bson/lib/bson/code.js +++ /dev/null @@ -1,24 +0,0 @@ -/** - * A class representation of the BSON Code type. - * - * @class - * @param {(string|function)} code a string or function. - * @param {Object} [scope] an optional scope for the function. - * @return {Code} - */ -var Code = function Code(code, scope) { - if (!(this instanceof Code)) return new Code(code, scope); - this._bsontype = 'Code'; - this.code = code; - this.scope = scope; -}; - -/** - * @ignore - */ -Code.prototype.toJSON = function() { - return { scope: this.scope, code: this.code }; -}; - -module.exports = Code; -module.exports.Code = Code; diff --git a/scripts/2.5/node_modules/bson/lib/bson/db_ref.js b/scripts/2.5/node_modules/bson/lib/bson/db_ref.js deleted file mode 100644 index f95795b1..00000000 --- a/scripts/2.5/node_modules/bson/lib/bson/db_ref.js +++ /dev/null @@ -1,32 +0,0 @@ -/** - * A class representation of the BSON DBRef type. - * - * @class - * @param {string} namespace the collection name. - * @param {ObjectID} oid the reference ObjectID. - * @param {string} [db] optional db name, if omitted the reference is local to the current db. - * @return {DBRef} - */ -function DBRef(namespace, oid, db) { - if (!(this instanceof DBRef)) return new DBRef(namespace, oid, db); - - this._bsontype = 'DBRef'; - this.namespace = namespace; - this.oid = oid; - this.db = db; -} - -/** - * @ignore - * @api private - */ -DBRef.prototype.toJSON = function() { - return { - $ref: this.namespace, - $id: this.oid, - $db: this.db == null ? '' : this.db - }; -}; - -module.exports = DBRef; -module.exports.DBRef = DBRef; diff --git a/scripts/2.5/node_modules/bson/lib/bson/decimal128.js b/scripts/2.5/node_modules/bson/lib/bson/decimal128.js deleted file mode 100644 index 924513f4..00000000 --- a/scripts/2.5/node_modules/bson/lib/bson/decimal128.js +++ /dev/null @@ -1,820 +0,0 @@ -'use strict'; - -var Long = require('./long'); - -var PARSE_STRING_REGEXP = /^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/; -var PARSE_INF_REGEXP = /^(\+|-)?(Infinity|inf)$/i; -var PARSE_NAN_REGEXP = /^(\+|-)?NaN$/i; - -var EXPONENT_MAX = 6111; -var EXPONENT_MIN = -6176; -var EXPONENT_BIAS = 6176; -var MAX_DIGITS = 34; - -// Nan value bits as 32 bit values (due to lack of longs) -var NAN_BUFFER = [ - 0x7c, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00 -].reverse(); -// Infinity value bits 32 bit values (due to lack of longs) -var INF_NEGATIVE_BUFFER = [ - 0xf8, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00 -].reverse(); -var INF_POSITIVE_BUFFER = [ - 0x78, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00 -].reverse(); - -var EXPONENT_REGEX = /^([-+])?(\d+)?$/; - -var utils = require('./parser/utils'); - -// Detect if the value is a digit -var isDigit = function(value) { - return !isNaN(parseInt(value, 10)); -}; - -// Divide two uint128 values -var divideu128 = function(value) { - var DIVISOR = Long.fromNumber(1000 * 1000 * 1000); - var _rem = Long.fromNumber(0); - var i = 0; - - if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) { - return { quotient: value, rem: _rem }; - } - - for (i = 0; i <= 3; i++) { - // Adjust remainder to match value of next dividend - _rem = _rem.shiftLeft(32); - // Add the divided to _rem - _rem = _rem.add(new Long(value.parts[i], 0)); - value.parts[i] = _rem.div(DIVISOR).low_; - _rem = _rem.modulo(DIVISOR); - } - - return { quotient: value, rem: _rem }; -}; - -// Multiply two Long values and return the 128 bit value -var multiply64x2 = function(left, right) { - if (!left && !right) { - return { high: Long.fromNumber(0), low: Long.fromNumber(0) }; - } - - var leftHigh = left.shiftRightUnsigned(32); - var leftLow = new Long(left.getLowBits(), 0); - var rightHigh = right.shiftRightUnsigned(32); - var rightLow = new Long(right.getLowBits(), 0); - - var productHigh = leftHigh.multiply(rightHigh); - var productMid = leftHigh.multiply(rightLow); - var productMid2 = leftLow.multiply(rightHigh); - var productLow = leftLow.multiply(rightLow); - - productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); - productMid = new Long(productMid.getLowBits(), 0) - .add(productMid2) - .add(productLow.shiftRightUnsigned(32)); - - productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); - productLow = productMid.shiftLeft(32).add(new Long(productLow.getLowBits(), 0)); - - // Return the 128 bit result - return { high: productHigh, low: productLow }; -}; - -var lessThan = function(left, right) { - // Make values unsigned - var uhleft = left.high_ >>> 0; - var uhright = right.high_ >>> 0; - - // Compare high bits first - if (uhleft < uhright) { - return true; - } else if (uhleft === uhright) { - var ulleft = left.low_ >>> 0; - var ulright = right.low_ >>> 0; - if (ulleft < ulright) return true; - } - - return false; -}; - -// var longtoHex = function(value) { -// var buffer = utils.allocBuffer(8); -// var index = 0; -// // Encode the low 64 bits of the decimal -// // Encode low bits -// buffer[index++] = value.low_ & 0xff; -// buffer[index++] = (value.low_ >> 8) & 0xff; -// buffer[index++] = (value.low_ >> 16) & 0xff; -// buffer[index++] = (value.low_ >> 24) & 0xff; -// // Encode high bits -// buffer[index++] = value.high_ & 0xff; -// buffer[index++] = (value.high_ >> 8) & 0xff; -// buffer[index++] = (value.high_ >> 16) & 0xff; -// buffer[index++] = (value.high_ >> 24) & 0xff; -// return buffer.reverse().toString('hex'); -// }; - -// var int32toHex = function(value) { -// var buffer = utils.allocBuffer(4); -// var index = 0; -// // Encode the low 64 bits of the decimal -// // Encode low bits -// buffer[index++] = value & 0xff; -// buffer[index++] = (value >> 8) & 0xff; -// buffer[index++] = (value >> 16) & 0xff; -// buffer[index++] = (value >> 24) & 0xff; -// return buffer.reverse().toString('hex'); -// }; - -/** - * A class representation of the BSON Decimal128 type. - * - * @class - * @param {Buffer} bytes a buffer containing the raw Decimal128 bytes. - * @return {Double} - */ -var Decimal128 = function(bytes) { - this._bsontype = 'Decimal128'; - this.bytes = bytes; -}; - -/** - * Create a Decimal128 instance from a string representation - * - * @method - * @param {string} string a numeric string representation. - * @return {Decimal128} returns a Decimal128 instance. - */ -Decimal128.fromString = function(string) { - // Parse state tracking - var isNegative = false; - var sawRadix = false; - var foundNonZero = false; - - // Total number of significant digits (no leading or trailing zero) - var significantDigits = 0; - // Total number of significand digits read - var nDigitsRead = 0; - // Total number of digits (no leading zeros) - var nDigits = 0; - // The number of the digits after radix - var radixPosition = 0; - // The index of the first non-zero in *str* - var firstNonZero = 0; - - // Digits Array - var digits = [0]; - // The number of digits in digits - var nDigitsStored = 0; - // Insertion pointer for digits - var digitsInsert = 0; - // The index of the first non-zero digit - var firstDigit = 0; - // The index of the last digit - var lastDigit = 0; - - // Exponent - var exponent = 0; - // loop index over array - var i = 0; - // The high 17 digits of the significand - var significandHigh = [0, 0]; - // The low 17 digits of the significand - var significandLow = [0, 0]; - // The biased exponent - var biasedExponent = 0; - - // Read index - var index = 0; - - // Trim the string - string = string.trim(); - - // Naively prevent against REDOS attacks. - // TODO: implementing a custom parsing for this, or refactoring the regex would yield - // further gains. - if (string.length >= 7000) { - throw new Error('' + string + ' not a valid Decimal128 string'); - } - - // Results - var stringMatch = string.match(PARSE_STRING_REGEXP); - var infMatch = string.match(PARSE_INF_REGEXP); - var nanMatch = string.match(PARSE_NAN_REGEXP); - - // Validate the string - if ((!stringMatch && !infMatch && !nanMatch) || string.length === 0) { - throw new Error('' + string + ' not a valid Decimal128 string'); - } - - // Check if we have an illegal exponent format - if (stringMatch && stringMatch[4] && stringMatch[2] === undefined) { - throw new Error('' + string + ' not a valid Decimal128 string'); - } - - // Get the negative or positive sign - if (string[index] === '+' || string[index] === '-') { - isNegative = string[index++] === '-'; - } - - // Check if user passed Infinity or NaN - if (!isDigit(string[index]) && string[index] !== '.') { - if (string[index] === 'i' || string[index] === 'I') { - return new Decimal128(utils.toBuffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); - } else if (string[index] === 'N') { - return new Decimal128(utils.toBuffer(NAN_BUFFER)); - } - } - - // Read all the digits - while (isDigit(string[index]) || string[index] === '.') { - if (string[index] === '.') { - if (sawRadix) { - return new Decimal128(utils.toBuffer(NAN_BUFFER)); - } - - sawRadix = true; - index = index + 1; - continue; - } - - if (nDigitsStored < 34) { - if (string[index] !== '0' || foundNonZero) { - if (!foundNonZero) { - firstNonZero = nDigitsRead; - } - - foundNonZero = true; - - // Only store 34 digits - digits[digitsInsert++] = parseInt(string[index], 10); - nDigitsStored = nDigitsStored + 1; - } - } - - if (foundNonZero) { - nDigits = nDigits + 1; - } - - if (sawRadix) { - radixPosition = radixPosition + 1; - } - - nDigitsRead = nDigitsRead + 1; - index = index + 1; - } - - if (sawRadix && !nDigitsRead) { - throw new Error('' + string + ' not a valid Decimal128 string'); - } - - // Read exponent if exists - if (string[index] === 'e' || string[index] === 'E') { - // Read exponent digits - var match = string.substr(++index).match(EXPONENT_REGEX); - - // No digits read - if (!match || !match[2]) { - return new Decimal128(utils.toBuffer(NAN_BUFFER)); - } - - // Get exponent - exponent = parseInt(match[0], 10); - - // Adjust the index - index = index + match[0].length; - } - - // Return not a number - if (string[index]) { - return new Decimal128(utils.toBuffer(NAN_BUFFER)); - } - - // Done reading input - // Find first non-zero digit in digits - firstDigit = 0; - - if (!nDigitsStored) { - firstDigit = 0; - lastDigit = 0; - digits[0] = 0; - nDigits = 1; - nDigitsStored = 1; - significantDigits = 0; - } else { - lastDigit = nDigitsStored - 1; - significantDigits = nDigits; - - if (exponent !== 0 && significantDigits !== 1) { - while (string[firstNonZero + significantDigits - 1] === '0') { - significantDigits = significantDigits - 1; - } - } - } - - // Normalization of exponent - // Correct exponent based on radix position, and shift significand as needed - // to represent user input - - // Overflow prevention - if (exponent <= radixPosition && radixPosition - exponent > 1 << 14) { - exponent = EXPONENT_MIN; - } else { - exponent = exponent - radixPosition; - } - - // Attempt to normalize the exponent - while (exponent > EXPONENT_MAX) { - // Shift exponent to significand and decrease - lastDigit = lastDigit + 1; - - if (lastDigit - firstDigit > MAX_DIGITS) { - // Check if we have a zero then just hard clamp, otherwise fail - var digitsString = digits.join(''); - if (digitsString.match(/^0+$/)) { - exponent = EXPONENT_MAX; - break; - } else { - return new Decimal128(utils.toBuffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); - } - } - - exponent = exponent - 1; - } - - while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) { - // Shift last digit - if (lastDigit === 0) { - exponent = EXPONENT_MIN; - significantDigits = 0; - break; - } - - if (nDigitsStored < nDigits) { - // adjust to match digits not stored - nDigits = nDigits - 1; - } else { - // adjust to round - lastDigit = lastDigit - 1; - } - - if (exponent < EXPONENT_MAX) { - exponent = exponent + 1; - } else { - // Check if we have a zero then just hard clamp, otherwise fail - digitsString = digits.join(''); - if (digitsString.match(/^0+$/)) { - exponent = EXPONENT_MAX; - break; - } else { - return new Decimal128(utils.toBuffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); - } - } - } - - // Round - // We've normalized the exponent, but might still need to round. - if (lastDigit - firstDigit + 1 < significantDigits && string[significantDigits] !== '0') { - var endOfString = nDigitsRead; - - // If we have seen a radix point, 'string' is 1 longer than we have - // documented with ndigits_read, so inc the position of the first nonzero - // digit and the position that digits are read to. - if (sawRadix && exponent === EXPONENT_MIN) { - firstNonZero = firstNonZero + 1; - endOfString = endOfString + 1; - } - - var roundDigit = parseInt(string[firstNonZero + lastDigit + 1], 10); - var roundBit = 0; - - if (roundDigit >= 5) { - roundBit = 1; - - if (roundDigit === 5) { - roundBit = digits[lastDigit] % 2 === 1; - - for (i = firstNonZero + lastDigit + 2; i < endOfString; i++) { - if (parseInt(string[i], 10)) { - roundBit = 1; - break; - } - } - } - } - - if (roundBit) { - var dIdx = lastDigit; - - for (; dIdx >= 0; dIdx--) { - if (++digits[dIdx] > 9) { - digits[dIdx] = 0; - - // overflowed most significant digit - if (dIdx === 0) { - if (exponent < EXPONENT_MAX) { - exponent = exponent + 1; - digits[dIdx] = 1; - } else { - return new Decimal128( - utils.toBuffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER) - ); - } - } - } else { - break; - } - } - } - } - - // Encode significand - // The high 17 digits of the significand - significandHigh = Long.fromNumber(0); - // The low 17 digits of the significand - significandLow = Long.fromNumber(0); - - // read a zero - if (significantDigits === 0) { - significandHigh = Long.fromNumber(0); - significandLow = Long.fromNumber(0); - } else if (lastDigit - firstDigit < 17) { - dIdx = firstDigit; - significandLow = Long.fromNumber(digits[dIdx++]); - significandHigh = new Long(0, 0); - - for (; dIdx <= lastDigit; dIdx++) { - significandLow = significandLow.multiply(Long.fromNumber(10)); - significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); - } - } else { - dIdx = firstDigit; - significandHigh = Long.fromNumber(digits[dIdx++]); - - for (; dIdx <= lastDigit - 17; dIdx++) { - significandHigh = significandHigh.multiply(Long.fromNumber(10)); - significandHigh = significandHigh.add(Long.fromNumber(digits[dIdx])); - } - - significandLow = Long.fromNumber(digits[dIdx++]); - - for (; dIdx <= lastDigit; dIdx++) { - significandLow = significandLow.multiply(Long.fromNumber(10)); - significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); - } - } - - var significand = multiply64x2(significandHigh, Long.fromString('100000000000000000')); - - significand.low = significand.low.add(significandLow); - - if (lessThan(significand.low, significandLow)) { - significand.high = significand.high.add(Long.fromNumber(1)); - } - - // Biased exponent - biasedExponent = exponent + EXPONENT_BIAS; - var dec = { low: Long.fromNumber(0), high: Long.fromNumber(0) }; - - // Encode combination, exponent, and significand. - if ( - significand.high - .shiftRightUnsigned(49) - .and(Long.fromNumber(1)) - .equals(Long.fromNumber) - ) { - // Encode '11' into bits 1 to 3 - dec.high = dec.high.or(Long.fromNumber(0x3).shiftLeft(61)); - dec.high = dec.high.or( - Long.fromNumber(biasedExponent).and(Long.fromNumber(0x3fff).shiftLeft(47)) - ); - dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x7fffffffffff))); - } else { - dec.high = dec.high.or(Long.fromNumber(biasedExponent & 0x3fff).shiftLeft(49)); - dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x1ffffffffffff))); - } - - dec.low = significand.low; - - // Encode sign - if (isNegative) { - dec.high = dec.high.or(Long.fromString('9223372036854775808')); - } - - // Encode into a buffer - var buffer = utils.allocBuffer(16); - index = 0; - - // Encode the low 64 bits of the decimal - // Encode low bits - buffer[index++] = dec.low.low_ & 0xff; - buffer[index++] = (dec.low.low_ >> 8) & 0xff; - buffer[index++] = (dec.low.low_ >> 16) & 0xff; - buffer[index++] = (dec.low.low_ >> 24) & 0xff; - // Encode high bits - buffer[index++] = dec.low.high_ & 0xff; - buffer[index++] = (dec.low.high_ >> 8) & 0xff; - buffer[index++] = (dec.low.high_ >> 16) & 0xff; - buffer[index++] = (dec.low.high_ >> 24) & 0xff; - - // Encode the high 64 bits of the decimal - // Encode low bits - buffer[index++] = dec.high.low_ & 0xff; - buffer[index++] = (dec.high.low_ >> 8) & 0xff; - buffer[index++] = (dec.high.low_ >> 16) & 0xff; - buffer[index++] = (dec.high.low_ >> 24) & 0xff; - // Encode high bits - buffer[index++] = dec.high.high_ & 0xff; - buffer[index++] = (dec.high.high_ >> 8) & 0xff; - buffer[index++] = (dec.high.high_ >> 16) & 0xff; - buffer[index++] = (dec.high.high_ >> 24) & 0xff; - - // Return the new Decimal128 - return new Decimal128(buffer); -}; - -// Extract least significant 5 bits -var COMBINATION_MASK = 0x1f; -// Extract least significant 14 bits -var EXPONENT_MASK = 0x3fff; -// Value of combination field for Inf -var COMBINATION_INFINITY = 30; -// Value of combination field for NaN -var COMBINATION_NAN = 31; -// Value of combination field for NaN -// var COMBINATION_SNAN = 32; -// decimal128 exponent bias -EXPONENT_BIAS = 6176; - -/** - * Create a string representation of the raw Decimal128 value - * - * @method - * @return {string} returns a Decimal128 string representation. - */ -Decimal128.prototype.toString = function() { - // Note: bits in this routine are referred to starting at 0, - // from the sign bit, towards the coefficient. - - // bits 0 - 31 - var high; - // bits 32 - 63 - var midh; - // bits 64 - 95 - var midl; - // bits 96 - 127 - var low; - // bits 1 - 5 - var combination; - // decoded biased exponent (14 bits) - var biased_exponent; - // the number of significand digits - var significand_digits = 0; - // the base-10 digits in the significand - var significand = new Array(36); - for (var i = 0; i < significand.length; i++) significand[i] = 0; - // read pointer into significand - var index = 0; - - // unbiased exponent - var exponent; - // the exponent if scientific notation is used - var scientific_exponent; - - // true if the number is zero - var is_zero = false; - - // the most signifcant significand bits (50-46) - var significand_msb; - // temporary storage for significand decoding - var significand128 = { parts: new Array(4) }; - // indexing variables - i; - var j, k; - - // Output string - var string = []; - - // Unpack index - index = 0; - - // Buffer reference - var buffer = this.bytes; - - // Unpack the low 64bits into a long - low = - buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); - midl = - buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); - - // Unpack the high 64bits into a long - midh = - buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); - high = - buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); - - // Unpack index - index = 0; - - // Create the state of the decimal - var dec = { - low: new Long(low, midl), - high: new Long(midh, high) - }; - - if (dec.high.lessThan(Long.ZERO)) { - string.push('-'); - } - - // Decode combination field and exponent - combination = (high >> 26) & COMBINATION_MASK; - - if (combination >> 3 === 3) { - // Check for 'special' values - if (combination === COMBINATION_INFINITY) { - return string.join('') + 'Infinity'; - } else if (combination === COMBINATION_NAN) { - return 'NaN'; - } else { - biased_exponent = (high >> 15) & EXPONENT_MASK; - significand_msb = 0x08 + ((high >> 14) & 0x01); - } - } else { - significand_msb = (high >> 14) & 0x07; - biased_exponent = (high >> 17) & EXPONENT_MASK; - } - - exponent = biased_exponent - EXPONENT_BIAS; - - // Create string of significand digits - - // Convert the 114-bit binary number represented by - // (significand_high, significand_low) to at most 34 decimal - // digits through modulo and division. - significand128.parts[0] = (high & 0x3fff) + ((significand_msb & 0xf) << 14); - significand128.parts[1] = midh; - significand128.parts[2] = midl; - significand128.parts[3] = low; - - if ( - significand128.parts[0] === 0 && - significand128.parts[1] === 0 && - significand128.parts[2] === 0 && - significand128.parts[3] === 0 - ) { - is_zero = true; - } else { - for (k = 3; k >= 0; k--) { - var least_digits = 0; - // Peform the divide - var result = divideu128(significand128); - significand128 = result.quotient; - least_digits = result.rem.low_; - - // We now have the 9 least significant digits (in base 2). - // Convert and output to string. - if (!least_digits) continue; - - for (j = 8; j >= 0; j--) { - // significand[k * 9 + j] = Math.round(least_digits % 10); - significand[k * 9 + j] = least_digits % 10; - // least_digits = Math.round(least_digits / 10); - least_digits = Math.floor(least_digits / 10); - } - } - } - - // Output format options: - // Scientific - [-]d.dddE(+/-)dd or [-]dE(+/-)dd - // Regular - ddd.ddd - - if (is_zero) { - significand_digits = 1; - significand[index] = 0; - } else { - significand_digits = 36; - i = 0; - - while (!significand[index]) { - i++; - significand_digits = significand_digits - 1; - index = index + 1; - } - } - - scientific_exponent = significand_digits - 1 + exponent; - - // The scientific exponent checks are dictated by the string conversion - // specification and are somewhat arbitrary cutoffs. - // - // We must check exponent > 0, because if this is the case, the number - // has trailing zeros. However, we *cannot* output these trailing zeros, - // because doing so would change the precision of the value, and would - // change stored data if the string converted number is round tripped. - - if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) { - // Scientific format - string.push(significand[index++]); - significand_digits = significand_digits - 1; - - if (significand_digits) { - string.push('.'); - } - - for (i = 0; i < significand_digits; i++) { - string.push(significand[index++]); - } - - // Exponent - string.push('E'); - if (scientific_exponent > 0) { - string.push('+' + scientific_exponent); - } else { - string.push(scientific_exponent); - } - } else { - // Regular format with no decimal place - if (exponent >= 0) { - for (i = 0; i < significand_digits; i++) { - string.push(significand[index++]); - } - } else { - var radix_position = significand_digits + exponent; - - // non-zero digits before radix - if (radix_position > 0) { - for (i = 0; i < radix_position; i++) { - string.push(significand[index++]); - } - } else { - string.push('0'); - } - - string.push('.'); - // add leading zeros after radix - while (radix_position++ < 0) { - string.push('0'); - } - - for (i = 0; i < significand_digits - Math.max(radix_position - 1, 0); i++) { - string.push(significand[index++]); - } - } - } - - return string.join(''); -}; - -Decimal128.prototype.toJSON = function() { - return { $numberDecimal: this.toString() }; -}; - -module.exports = Decimal128; -module.exports.Decimal128 = Decimal128; diff --git a/scripts/2.5/node_modules/bson/lib/bson/double.js b/scripts/2.5/node_modules/bson/lib/bson/double.js deleted file mode 100644 index 523c21f8..00000000 --- a/scripts/2.5/node_modules/bson/lib/bson/double.js +++ /dev/null @@ -1,33 +0,0 @@ -/** - * A class representation of the BSON Double type. - * - * @class - * @param {number} value the number we want to represent as a double. - * @return {Double} - */ -function Double(value) { - if (!(this instanceof Double)) return new Double(value); - - this._bsontype = 'Double'; - this.value = value; -} - -/** - * Access the number value. - * - * @method - * @return {number} returns the wrapped double number. - */ -Double.prototype.valueOf = function() { - return this.value; -}; - -/** - * @ignore - */ -Double.prototype.toJSON = function() { - return this.value; -}; - -module.exports = Double; -module.exports.Double = Double; diff --git a/scripts/2.5/node_modules/bson/lib/bson/float_parser.js b/scripts/2.5/node_modules/bson/lib/bson/float_parser.js deleted file mode 100644 index 0054a2f6..00000000 --- a/scripts/2.5/node_modules/bson/lib/bson/float_parser.js +++ /dev/null @@ -1,124 +0,0 @@ -// Copyright (c) 2008, Fair Oaks Labs, Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * Neither the name of Fair Oaks Labs, Inc. nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. -// -// -// Modifications to writeIEEE754 to support negative zeroes made by Brian White - -var readIEEE754 = function(buffer, offset, endian, mLen, nBytes) { - var e, - m, - bBE = endian === 'big', - eLen = nBytes * 8 - mLen - 1, - eMax = (1 << eLen) - 1, - eBias = eMax >> 1, - nBits = -7, - i = bBE ? 0 : nBytes - 1, - d = bBE ? 1 : -1, - s = buffer[offset + i]; - - i += d; - - e = s & ((1 << -nBits) - 1); - s >>= -nBits; - nBits += eLen; - for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8); - - m = e & ((1 << -nBits) - 1); - e >>= -nBits; - nBits += mLen; - for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8); - - if (e === 0) { - e = 1 - eBias; - } else if (e === eMax) { - return m ? NaN : (s ? -1 : 1) * Infinity; - } else { - m = m + Math.pow(2, mLen); - e = e - eBias; - } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen); -}; - -var writeIEEE754 = function(buffer, value, offset, endian, mLen, nBytes) { - var e, - m, - c, - bBE = endian === 'big', - eLen = nBytes * 8 - mLen - 1, - eMax = (1 << eLen) - 1, - eBias = eMax >> 1, - rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0, - i = bBE ? nBytes - 1 : 0, - d = bBE ? -1 : 1, - s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; - - value = Math.abs(value); - - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0; - e = eMax; - } else { - e = Math.floor(Math.log(value) / Math.LN2); - if (value * (c = Math.pow(2, -e)) < 1) { - e--; - c *= 2; - } - if (e + eBias >= 1) { - value += rt / c; - } else { - value += rt * Math.pow(2, 1 - eBias); - } - if (value * c >= 2) { - e++; - c /= 2; - } - - if (e + eBias >= eMax) { - m = 0; - e = eMax; - } else if (e + eBias >= 1) { - m = (value * c - 1) * Math.pow(2, mLen); - e = e + eBias; - } else { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); - e = 0; - } - } - - for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8); - - e = (e << mLen) | m; - eLen += mLen; - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8); - - buffer[offset + i - d] |= s * 128; -}; - -exports.readIEEE754 = readIEEE754; -exports.writeIEEE754 = writeIEEE754; diff --git a/scripts/2.5/node_modules/bson/lib/bson/int_32.js b/scripts/2.5/node_modules/bson/lib/bson/int_32.js deleted file mode 100644 index 85dbdec6..00000000 --- a/scripts/2.5/node_modules/bson/lib/bson/int_32.js +++ /dev/null @@ -1,33 +0,0 @@ -/** - * A class representation of a BSON Int32 type. - * - * @class - * @param {number} value the number we want to represent as an int32. - * @return {Int32} - */ -var Int32 = function(value) { - if (!(this instanceof Int32)) return new Int32(value); - - this._bsontype = 'Int32'; - this.value = value; -}; - -/** - * Access the number value. - * - * @method - * @return {number} returns the wrapped int32 number. - */ -Int32.prototype.valueOf = function() { - return this.value; -}; - -/** - * @ignore - */ -Int32.prototype.toJSON = function() { - return this.value; -}; - -module.exports = Int32; -module.exports.Int32 = Int32; diff --git a/scripts/2.5/node_modules/bson/lib/bson/long.js b/scripts/2.5/node_modules/bson/lib/bson/long.js deleted file mode 100644 index 78215aa3..00000000 --- a/scripts/2.5/node_modules/bson/lib/bson/long.js +++ /dev/null @@ -1,851 +0,0 @@ -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// Copyright 2009 Google Inc. All Rights Reserved - -/** - * Defines a Long class for representing a 64-bit two's-complement - * integer value, which faithfully simulates the behavior of a Java "Long". This - * implementation is derived from LongLib in GWT. - * - * Constructs a 64-bit two's-complement integer, given its low and high 32-bit - * values as *signed* integers. See the from* functions below for more - * convenient ways of constructing Longs. - * - * The internal representation of a Long is the two given signed, 32-bit values. - * We use 32-bit pieces because these are the size of integers on which - * Javascript performs bit-operations. For operations like addition and - * multiplication, we split each number into 16-bit pieces, which can easily be - * multiplied within Javascript's floating-point representation without overflow - * or change in sign. - * - * In the algorithms below, we frequently reduce the negative case to the - * positive case by negating the input(s) and then post-processing the result. - * Note that we must ALWAYS check specially whether those values are MIN_VALUE - * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as - * a positive number, it overflows back into a negative). Not handling this - * case would often result in infinite recursion. - * - * @class - * @param {number} low the low (signed) 32 bits of the Long. - * @param {number} high the high (signed) 32 bits of the Long. - * @return {Long} - */ -function Long(low, high) { - if (!(this instanceof Long)) return new Long(low, high); - - this._bsontype = 'Long'; - /** - * @type {number} - * @ignore - */ - this.low_ = low | 0; // force into 32 signed bits. - - /** - * @type {number} - * @ignore - */ - this.high_ = high | 0; // force into 32 signed bits. -} - -/** - * Return the int value. - * - * @method - * @return {number} the value, assuming it is a 32-bit integer. - */ -Long.prototype.toInt = function() { - return this.low_; -}; - -/** - * Return the Number value. - * - * @method - * @return {number} the closest floating-point representation to this value. - */ -Long.prototype.toNumber = function() { - return this.high_ * Long.TWO_PWR_32_DBL_ + this.getLowBitsUnsigned(); -}; - -/** - * Return the JSON value. - * - * @method - * @return {string} the JSON representation. - */ -Long.prototype.toJSON = function() { - return this.toString(); -}; - -/** - * Return the String value. - * - * @method - * @param {number} [opt_radix] the radix in which the text should be written. - * @return {string} the textual representation of this value. - */ -Long.prototype.toString = function(opt_radix) { - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (this.isZero()) { - return '0'; - } - - if (this.isNegative()) { - if (this.equals(Long.MIN_VALUE)) { - // We need to change the Long value before it can be negated, so we remove - // the bottom-most digit in this base and then recurse to do the rest. - var radixLong = Long.fromNumber(radix); - var div = this.div(radixLong); - var rem = div.multiply(radixLong).subtract(this); - return div.toString(radix) + rem.toInt().toString(radix); - } else { - return '-' + this.negate().toString(radix); - } - } - - // Do several (6) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Long.fromNumber(Math.pow(radix, 6)); - - rem = this; - var result = ''; - - while (!rem.isZero()) { - var remDiv = rem.div(radixToPower); - var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); - var digits = intval.toString(radix); - - rem = remDiv; - if (rem.isZero()) { - return digits + result; - } else { - while (digits.length < 6) { - digits = '0' + digits; - } - result = '' + digits + result; - } - } -}; - -/** - * Return the high 32-bits value. - * - * @method - * @return {number} the high 32-bits as a signed value. - */ -Long.prototype.getHighBits = function() { - return this.high_; -}; - -/** - * Return the low 32-bits value. - * - * @method - * @return {number} the low 32-bits as a signed value. - */ -Long.prototype.getLowBits = function() { - return this.low_; -}; - -/** - * Return the low unsigned 32-bits value. - * - * @method - * @return {number} the low 32-bits as an unsigned value. - */ -Long.prototype.getLowBitsUnsigned = function() { - return this.low_ >= 0 ? this.low_ : Long.TWO_PWR_32_DBL_ + this.low_; -}; - -/** - * Returns the number of bits needed to represent the absolute value of this Long. - * - * @method - * @return {number} Returns the number of bits needed to represent the absolute value of this Long. - */ -Long.prototype.getNumBitsAbs = function() { - if (this.isNegative()) { - if (this.equals(Long.MIN_VALUE)) { - return 64; - } else { - return this.negate().getNumBitsAbs(); - } - } else { - var val = this.high_ !== 0 ? this.high_ : this.low_; - for (var bit = 31; bit > 0; bit--) { - if ((val & (1 << bit)) !== 0) { - break; - } - } - return this.high_ !== 0 ? bit + 33 : bit + 1; - } -}; - -/** - * Return whether this value is zero. - * - * @method - * @return {boolean} whether this value is zero. - */ -Long.prototype.isZero = function() { - return this.high_ === 0 && this.low_ === 0; -}; - -/** - * Return whether this value is negative. - * - * @method - * @return {boolean} whether this value is negative. - */ -Long.prototype.isNegative = function() { - return this.high_ < 0; -}; - -/** - * Return whether this value is odd. - * - * @method - * @return {boolean} whether this value is odd. - */ -Long.prototype.isOdd = function() { - return (this.low_ & 1) === 1; -}; - -/** - * Return whether this Long equals the other - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long equals the other - */ -Long.prototype.equals = function(other) { - return this.high_ === other.high_ && this.low_ === other.low_; -}; - -/** - * Return whether this Long does not equal the other. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long does not equal the other. - */ -Long.prototype.notEquals = function(other) { - return this.high_ !== other.high_ || this.low_ !== other.low_; -}; - -/** - * Return whether this Long is less than the other. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long is less than the other. - */ -Long.prototype.lessThan = function(other) { - return this.compare(other) < 0; -}; - -/** - * Return whether this Long is less than or equal to the other. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long is less than or equal to the other. - */ -Long.prototype.lessThanOrEqual = function(other) { - return this.compare(other) <= 0; -}; - -/** - * Return whether this Long is greater than the other. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long is greater than the other. - */ -Long.prototype.greaterThan = function(other) { - return this.compare(other) > 0; -}; - -/** - * Return whether this Long is greater than or equal to the other. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long is greater than or equal to the other. - */ -Long.prototype.greaterThanOrEqual = function(other) { - return this.compare(other) >= 0; -}; - -/** - * Compares this Long with the given one. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. - */ -Long.prototype.compare = function(other) { - if (this.equals(other)) { - return 0; - } - - var thisNeg = this.isNegative(); - var otherNeg = other.isNegative(); - if (thisNeg && !otherNeg) { - return -1; - } - if (!thisNeg && otherNeg) { - return 1; - } - - // at this point, the signs are the same, so subtraction will not overflow - if (this.subtract(other).isNegative()) { - return -1; - } else { - return 1; - } -}; - -/** - * The negation of this value. - * - * @method - * @return {Long} the negation of this value. - */ -Long.prototype.negate = function() { - if (this.equals(Long.MIN_VALUE)) { - return Long.MIN_VALUE; - } else { - return this.not().add(Long.ONE); - } -}; - -/** - * Returns the sum of this and the given Long. - * - * @method - * @param {Long} other Long to add to this one. - * @return {Long} the sum of this and the given Long. - */ -Long.prototype.add = function(other) { - // Divide each number into 4 chunks of 16 bits, and then sum the chunks. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xffff; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xffff; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xffff; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xffff; - - var c48 = 0, - c32 = 0, - c16 = 0, - c00 = 0; - c00 += a00 + b00; - c16 += c00 >>> 16; - c00 &= 0xffff; - c16 += a16 + b16; - c32 += c16 >>> 16; - c16 &= 0xffff; - c32 += a32 + b32; - c48 += c32 >>> 16; - c32 &= 0xffff; - c48 += a48 + b48; - c48 &= 0xffff; - return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32); -}; - -/** - * Returns the difference of this and the given Long. - * - * @method - * @param {Long} other Long to subtract from this. - * @return {Long} the difference of this and the given Long. - */ -Long.prototype.subtract = function(other) { - return this.add(other.negate()); -}; - -/** - * Returns the product of this and the given Long. - * - * @method - * @param {Long} other Long to multiply with this. - * @return {Long} the product of this and the other. - */ -Long.prototype.multiply = function(other) { - if (this.isZero()) { - return Long.ZERO; - } else if (other.isZero()) { - return Long.ZERO; - } - - if (this.equals(Long.MIN_VALUE)) { - return other.isOdd() ? Long.MIN_VALUE : Long.ZERO; - } else if (other.equals(Long.MIN_VALUE)) { - return this.isOdd() ? Long.MIN_VALUE : Long.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().multiply(other.negate()); - } else { - return this.negate() - .multiply(other) - .negate(); - } - } else if (other.isNegative()) { - return this.multiply(other.negate()).negate(); - } - - // If both Longs are small, use float multiplication - if (this.lessThan(Long.TWO_PWR_24_) && other.lessThan(Long.TWO_PWR_24_)) { - return Long.fromNumber(this.toNumber() * other.toNumber()); - } - - // Divide each Long into 4 chunks of 16 bits, and then add up 4x4 products. - // We can skip products that would overflow. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xffff; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xffff; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xffff; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xffff; - - var c48 = 0, - c32 = 0, - c16 = 0, - c00 = 0; - c00 += a00 * b00; - c16 += c00 >>> 16; - c00 &= 0xffff; - c16 += a16 * b00; - c32 += c16 >>> 16; - c16 &= 0xffff; - c16 += a00 * b16; - c32 += c16 >>> 16; - c16 &= 0xffff; - c32 += a32 * b00; - c48 += c32 >>> 16; - c32 &= 0xffff; - c32 += a16 * b16; - c48 += c32 >>> 16; - c32 &= 0xffff; - c32 += a00 * b32; - c48 += c32 >>> 16; - c32 &= 0xffff; - c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; - c48 &= 0xffff; - return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32); -}; - -/** - * Returns this Long divided by the given one. - * - * @method - * @param {Long} other Long by which to divide. - * @return {Long} this Long divided by the given one. - */ -Long.prototype.div = function(other) { - if (other.isZero()) { - throw Error('division by zero'); - } else if (this.isZero()) { - return Long.ZERO; - } - - if (this.equals(Long.MIN_VALUE)) { - if (other.equals(Long.ONE) || other.equals(Long.NEG_ONE)) { - return Long.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE - } else if (other.equals(Long.MIN_VALUE)) { - return Long.ONE; - } else { - // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. - var halfThis = this.shiftRight(1); - var approx = halfThis.div(other).shiftLeft(1); - if (approx.equals(Long.ZERO)) { - return other.isNegative() ? Long.ONE : Long.NEG_ONE; - } else { - var rem = this.subtract(other.multiply(approx)); - var result = approx.add(rem.div(other)); - return result; - } - } - } else if (other.equals(Long.MIN_VALUE)) { - return Long.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().div(other.negate()); - } else { - return this.negate() - .div(other) - .negate(); - } - } else if (other.isNegative()) { - return this.div(other.negate()).negate(); - } - - // Repeat the following until the remainder is less than other: find a - // floating-point that approximates remainder / other *from below*, add this - // into the result, and subtract it from the remainder. It is critical that - // the approximate value is less than or equal to the real value so that the - // remainder never becomes negative. - var res = Long.ZERO; - rem = this; - while (rem.greaterThanOrEqual(other)) { - // Approximate the result of division. This may be a little greater or - // smaller than the actual value. - approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); - - // We will tweak the approximate result by changing it in the 48-th digit or - // the smallest non-fractional digit, whichever is larger. - var log2 = Math.ceil(Math.log(approx) / Math.LN2); - var delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48); - - // Decrease the approximation until it is smaller than the remainder. Note - // that if it is too large, the product overflows and is negative. - var approxRes = Long.fromNumber(approx); - var approxRem = approxRes.multiply(other); - while (approxRem.isNegative() || approxRem.greaterThan(rem)) { - approx -= delta; - approxRes = Long.fromNumber(approx); - approxRem = approxRes.multiply(other); - } - - // We know the answer can't be zero... and actually, zero would cause - // infinite recursion since we would make no progress. - if (approxRes.isZero()) { - approxRes = Long.ONE; - } - - res = res.add(approxRes); - rem = rem.subtract(approxRem); - } - return res; -}; - -/** - * Returns this Long modulo the given one. - * - * @method - * @param {Long} other Long by which to mod. - * @return {Long} this Long modulo the given one. - */ -Long.prototype.modulo = function(other) { - return this.subtract(this.div(other).multiply(other)); -}; - -/** - * The bitwise-NOT of this value. - * - * @method - * @return {Long} the bitwise-NOT of this value. - */ -Long.prototype.not = function() { - return Long.fromBits(~this.low_, ~this.high_); -}; - -/** - * Returns the bitwise-AND of this Long and the given one. - * - * @method - * @param {Long} other the Long with which to AND. - * @return {Long} the bitwise-AND of this and the other. - */ -Long.prototype.and = function(other) { - return Long.fromBits(this.low_ & other.low_, this.high_ & other.high_); -}; - -/** - * Returns the bitwise-OR of this Long and the given one. - * - * @method - * @param {Long} other the Long with which to OR. - * @return {Long} the bitwise-OR of this and the other. - */ -Long.prototype.or = function(other) { - return Long.fromBits(this.low_ | other.low_, this.high_ | other.high_); -}; - -/** - * Returns the bitwise-XOR of this Long and the given one. - * - * @method - * @param {Long} other the Long with which to XOR. - * @return {Long} the bitwise-XOR of this and the other. - */ -Long.prototype.xor = function(other) { - return Long.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); -}; - -/** - * Returns this Long with bits shifted to the left by the given amount. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Long} this shifted to the left by the given amount. - */ -Long.prototype.shiftLeft = function(numBits) { - numBits &= 63; - if (numBits === 0) { - return this; - } else { - var low = this.low_; - if (numBits < 32) { - var high = this.high_; - return Long.fromBits(low << numBits, (high << numBits) | (low >>> (32 - numBits))); - } else { - return Long.fromBits(0, low << (numBits - 32)); - } - } -}; - -/** - * Returns this Long with bits shifted to the right by the given amount. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Long} this shifted to the right by the given amount. - */ -Long.prototype.shiftRight = function(numBits) { - numBits &= 63; - if (numBits === 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Long.fromBits((low >>> numBits) | (high << (32 - numBits)), high >> numBits); - } else { - return Long.fromBits(high >> (numBits - 32), high >= 0 ? 0 : -1); - } - } -}; - -/** - * Returns this Long with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Long} this shifted to the right by the given amount, with zeros placed into the new leading bits. - */ -Long.prototype.shiftRightUnsigned = function(numBits) { - numBits &= 63; - if (numBits === 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Long.fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits); - } else if (numBits === 32) { - return Long.fromBits(high, 0); - } else { - return Long.fromBits(high >>> (numBits - 32), 0); - } - } -}; - -/** - * Returns a Long representing the given (32-bit) integer value. - * - * @method - * @param {number} value the 32-bit integer in question. - * @return {Long} the corresponding Long value. - */ -Long.fromInt = function(value) { - if (-128 <= value && value < 128) { - var cachedObj = Long.INT_CACHE_[value]; - if (cachedObj) { - return cachedObj; - } - } - - var obj = new Long(value | 0, value < 0 ? -1 : 0); - if (-128 <= value && value < 128) { - Long.INT_CACHE_[value] = obj; - } - return obj; -}; - -/** - * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. - * - * @method - * @param {number} value the number in question. - * @return {Long} the corresponding Long value. - */ -Long.fromNumber = function(value) { - if (isNaN(value) || !isFinite(value)) { - return Long.ZERO; - } else if (value <= -Long.TWO_PWR_63_DBL_) { - return Long.MIN_VALUE; - } else if (value + 1 >= Long.TWO_PWR_63_DBL_) { - return Long.MAX_VALUE; - } else if (value < 0) { - return Long.fromNumber(-value).negate(); - } else { - return new Long((value % Long.TWO_PWR_32_DBL_) | 0, (value / Long.TWO_PWR_32_DBL_) | 0); - } -}; - -/** - * Returns a Long representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. - * - * @method - * @param {number} lowBits the low 32-bits. - * @param {number} highBits the high 32-bits. - * @return {Long} the corresponding Long value. - */ -Long.fromBits = function(lowBits, highBits) { - return new Long(lowBits, highBits); -}; - -/** - * Returns a Long representation of the given string, written using the given radix. - * - * @method - * @param {string} str the textual representation of the Long. - * @param {number} opt_radix the radix in which the text is written. - * @return {Long} the corresponding Long value. - */ -Long.fromString = function(str, opt_radix) { - if (str.length === 0) { - throw Error('number format error: empty string'); - } - - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (str.charAt(0) === '-') { - return Long.fromString(str.substring(1), radix).negate(); - } else if (str.indexOf('-') >= 0) { - throw Error('number format error: interior "-" character: ' + str); - } - - // Do several (8) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Long.fromNumber(Math.pow(radix, 8)); - - var result = Long.ZERO; - for (var i = 0; i < str.length; i += 8) { - var size = Math.min(8, str.length - i); - var value = parseInt(str.substring(i, i + size), radix); - if (size < 8) { - var power = Long.fromNumber(Math.pow(radix, size)); - result = result.multiply(power).add(Long.fromNumber(value)); - } else { - result = result.multiply(radixToPower); - result = result.add(Long.fromNumber(value)); - } - } - return result; -}; - -// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the -// from* methods on which they depend. - -/** - * A cache of the Long representations of small integer values. - * @type {Object} - * @ignore - */ -Long.INT_CACHE_ = {}; - -// NOTE: the compiler should inline these constant values below and then remove -// these variables, so there should be no runtime penalty for these. - -/** - * Number used repeated below in calculations. This must appear before the - * first call to any from* function below. - * @type {number} - * @ignore - */ -Long.TWO_PWR_16_DBL_ = 1 << 16; - -/** - * @type {number} - * @ignore - */ -Long.TWO_PWR_24_DBL_ = 1 << 24; - -/** - * @type {number} - * @ignore - */ -Long.TWO_PWR_32_DBL_ = Long.TWO_PWR_16_DBL_ * Long.TWO_PWR_16_DBL_; - -/** - * @type {number} - * @ignore - */ -Long.TWO_PWR_31_DBL_ = Long.TWO_PWR_32_DBL_ / 2; - -/** - * @type {number} - * @ignore - */ -Long.TWO_PWR_48_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_16_DBL_; - -/** - * @type {number} - * @ignore - */ -Long.TWO_PWR_64_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_32_DBL_; - -/** - * @type {number} - * @ignore - */ -Long.TWO_PWR_63_DBL_ = Long.TWO_PWR_64_DBL_ / 2; - -/** @type {Long} */ -Long.ZERO = Long.fromInt(0); - -/** @type {Long} */ -Long.ONE = Long.fromInt(1); - -/** @type {Long} */ -Long.NEG_ONE = Long.fromInt(-1); - -/** @type {Long} */ -Long.MAX_VALUE = Long.fromBits(0xffffffff | 0, 0x7fffffff | 0); - -/** @type {Long} */ -Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0); - -/** - * @type {Long} - * @ignore - */ -Long.TWO_PWR_24_ = Long.fromInt(1 << 24); - -/** - * Expose. - */ -module.exports = Long; -module.exports.Long = Long; diff --git a/scripts/2.5/node_modules/bson/lib/bson/map.js b/scripts/2.5/node_modules/bson/lib/bson/map.js deleted file mode 100644 index 7edb4f2a..00000000 --- a/scripts/2.5/node_modules/bson/lib/bson/map.js +++ /dev/null @@ -1,128 +0,0 @@ -'use strict'; - -// We have an ES6 Map available, return the native instance -if (typeof global.Map !== 'undefined') { - module.exports = global.Map; - module.exports.Map = global.Map; -} else { - // We will return a polyfill - var Map = function(array) { - this._keys = []; - this._values = {}; - - for (var i = 0; i < array.length; i++) { - if (array[i] == null) continue; // skip null and undefined - var entry = array[i]; - var key = entry[0]; - var value = entry[1]; - // Add the key to the list of keys in order - this._keys.push(key); - // Add the key and value to the values dictionary with a point - // to the location in the ordered keys list - this._values[key] = { v: value, i: this._keys.length - 1 }; - } - }; - - Map.prototype.clear = function() { - this._keys = []; - this._values = {}; - }; - - Map.prototype.delete = function(key) { - var value = this._values[key]; - if (value == null) return false; - // Delete entry - delete this._values[key]; - // Remove the key from the ordered keys list - this._keys.splice(value.i, 1); - return true; - }; - - Map.prototype.entries = function() { - var self = this; - var index = 0; - - return { - next: function() { - var key = self._keys[index++]; - return { - value: key !== undefined ? [key, self._values[key].v] : undefined, - done: key !== undefined ? false : true - }; - } - }; - }; - - Map.prototype.forEach = function(callback, self) { - self = self || this; - - for (var i = 0; i < this._keys.length; i++) { - var key = this._keys[i]; - // Call the forEach callback - callback.call(self, this._values[key].v, key, self); - } - }; - - Map.prototype.get = function(key) { - return this._values[key] ? this._values[key].v : undefined; - }; - - Map.prototype.has = function(key) { - return this._values[key] != null; - }; - - Map.prototype.keys = function() { - var self = this; - var index = 0; - - return { - next: function() { - var key = self._keys[index++]; - return { - value: key !== undefined ? key : undefined, - done: key !== undefined ? false : true - }; - } - }; - }; - - Map.prototype.set = function(key, value) { - if (this._values[key]) { - this._values[key].v = value; - return this; - } - - // Add the key to the list of keys in order - this._keys.push(key); - // Add the key and value to the values dictionary with a point - // to the location in the ordered keys list - this._values[key] = { v: value, i: this._keys.length - 1 }; - return this; - }; - - Map.prototype.values = function() { - var self = this; - var index = 0; - - return { - next: function() { - var key = self._keys[index++]; - return { - value: key !== undefined ? self._values[key].v : undefined, - done: key !== undefined ? false : true - }; - } - }; - }; - - // Last ismaster - Object.defineProperty(Map.prototype, 'size', { - enumerable: true, - get: function() { - return this._keys.length; - } - }); - - module.exports = Map; - module.exports.Map = Map; -} diff --git a/scripts/2.5/node_modules/bson/lib/bson/max_key.js b/scripts/2.5/node_modules/bson/lib/bson/max_key.js deleted file mode 100644 index eebca7bc..00000000 --- a/scripts/2.5/node_modules/bson/lib/bson/max_key.js +++ /dev/null @@ -1,14 +0,0 @@ -/** - * A class representation of the BSON MaxKey type. - * - * @class - * @return {MaxKey} A MaxKey instance - */ -function MaxKey() { - if (!(this instanceof MaxKey)) return new MaxKey(); - - this._bsontype = 'MaxKey'; -} - -module.exports = MaxKey; -module.exports.MaxKey = MaxKey; diff --git a/scripts/2.5/node_modules/bson/lib/bson/min_key.js b/scripts/2.5/node_modules/bson/lib/bson/min_key.js deleted file mode 100644 index 15f45228..00000000 --- a/scripts/2.5/node_modules/bson/lib/bson/min_key.js +++ /dev/null @@ -1,14 +0,0 @@ -/** - * A class representation of the BSON MinKey type. - * - * @class - * @return {MinKey} A MinKey instance - */ -function MinKey() { - if (!(this instanceof MinKey)) return new MinKey(); - - this._bsontype = 'MinKey'; -} - -module.exports = MinKey; -module.exports.MinKey = MinKey; diff --git a/scripts/2.5/node_modules/bson/lib/bson/objectid.js b/scripts/2.5/node_modules/bson/lib/bson/objectid.js deleted file mode 100644 index 79de40d2..00000000 --- a/scripts/2.5/node_modules/bson/lib/bson/objectid.js +++ /dev/null @@ -1,389 +0,0 @@ -// Custom inspect property name / symbol. -var inspect = 'inspect'; - -var utils = require('./parser/utils'); - -/** - * Machine id. - * - * Create a random 3-byte value (i.e. unique for this - * process). Other drivers use a md5 of the machine id here, but - * that would mean an asyc call to gethostname, so we don't bother. - * @ignore - */ -var MACHINE_ID = parseInt(Math.random() * 0xffffff, 10); - -// Regular expression that checks for hex value -var checkForHexRegExp = new RegExp('^[0-9a-fA-F]{24}$'); - -// Check if buffer exists -try { - if (Buffer && Buffer.from) { - var hasBufferType = true; - inspect = require('util').inspect.custom || 'inspect'; - } -} catch (err) { - hasBufferType = false; -} - -/** -* Create a new ObjectID instance -* -* @class -* @param {(string|number)} id Can be a 24 byte hex string, 12 byte binary string or a Number. -* @property {number} generationTime The generation time of this ObjectId instance -* @return {ObjectID} instance of ObjectID. -*/ -var ObjectID = function ObjectID(id) { - // Duck-typing to support ObjectId from different npm packages - if (id instanceof ObjectID) return id; - if (!(this instanceof ObjectID)) return new ObjectID(id); - - this._bsontype = 'ObjectID'; - - // The most common usecase (blank id, new objectId instance) - if (id == null || typeof id === 'number') { - // Generate a new id - this.id = this.generate(id); - // If we are caching the hex string - if (ObjectID.cacheHexString) this.__id = this.toString('hex'); - // Return the object - return; - } - - // Check if the passed in id is valid - var valid = ObjectID.isValid(id); - - // Throw an error if it's not a valid setup - if (!valid && id != null) { - throw new Error( - 'Argument passed in must be a single String of 12 bytes or a string of 24 hex characters' - ); - } else if (valid && typeof id === 'string' && id.length === 24 && hasBufferType) { - return new ObjectID(utils.toBuffer(id, 'hex')); - } else if (valid && typeof id === 'string' && id.length === 24) { - return ObjectID.createFromHexString(id); - } else if (id != null && id.length === 12) { - // assume 12 byte string - this.id = id; - } else if (id != null && id.toHexString) { - // Duck-typing to support ObjectId from different npm packages - return id; - } else { - throw new Error( - 'Argument passed in must be a single String of 12 bytes or a string of 24 hex characters' - ); - } - - if (ObjectID.cacheHexString) this.__id = this.toString('hex'); -}; - -// Allow usage of ObjectId as well as ObjectID -// var ObjectId = ObjectID; - -// Precomputed hex table enables speedy hex string conversion -var hexTable = []; -for (var i = 0; i < 256; i++) { - hexTable[i] = (i <= 15 ? '0' : '') + i.toString(16); -} - -/** -* Return the ObjectID id as a 24 byte hex string representation -* -* @method -* @return {string} return the 24 byte hex string representation. -*/ -ObjectID.prototype.toHexString = function() { - if (ObjectID.cacheHexString && this.__id) return this.__id; - - var hexString = ''; - if (!this.id || !this.id.length) { - throw new Error( - 'invalid ObjectId, ObjectId.id must be either a string or a Buffer, but is [' + - JSON.stringify(this.id) + - ']' - ); - } - - if (this.id instanceof _Buffer) { - hexString = convertToHex(this.id); - if (ObjectID.cacheHexString) this.__id = hexString; - return hexString; - } - - for (var i = 0; i < this.id.length; i++) { - hexString += hexTable[this.id.charCodeAt(i)]; - } - - if (ObjectID.cacheHexString) this.__id = hexString; - return hexString; -}; - -/** -* Update the ObjectID index used in generating new ObjectID's on the driver -* -* @method -* @return {number} returns next index value. -* @ignore -*/ -ObjectID.prototype.get_inc = function() { - return (ObjectID.index = (ObjectID.index + 1) % 0xffffff); -}; - -/** -* Update the ObjectID index used in generating new ObjectID's on the driver -* -* @method -* @return {number} returns next index value. -* @ignore -*/ -ObjectID.prototype.getInc = function() { - return this.get_inc(); -}; - -/** -* Generate a 12 byte id buffer used in ObjectID's -* -* @method -* @param {number} [time] optional parameter allowing to pass in a second based timestamp. -* @return {Buffer} return the 12 byte id buffer string. -*/ -ObjectID.prototype.generate = function(time) { - if ('number' !== typeof time) { - time = ~~(Date.now() / 1000); - } - - // Use pid - var pid = - (typeof process === 'undefined' || process.pid === 1 - ? Math.floor(Math.random() * 100000) - : process.pid) % 0xffff; - var inc = this.get_inc(); - // Buffer used - var buffer = utils.allocBuffer(12); - // Encode time - buffer[3] = time & 0xff; - buffer[2] = (time >> 8) & 0xff; - buffer[1] = (time >> 16) & 0xff; - buffer[0] = (time >> 24) & 0xff; - // Encode machine - buffer[6] = MACHINE_ID & 0xff; - buffer[5] = (MACHINE_ID >> 8) & 0xff; - buffer[4] = (MACHINE_ID >> 16) & 0xff; - // Encode pid - buffer[8] = pid & 0xff; - buffer[7] = (pid >> 8) & 0xff; - // Encode index - buffer[11] = inc & 0xff; - buffer[10] = (inc >> 8) & 0xff; - buffer[9] = (inc >> 16) & 0xff; - // Return the buffer - return buffer; -}; - -/** -* Converts the id into a 24 byte hex string for printing -* -* @param {String} format The Buffer toString format parameter. -* @return {String} return the 24 byte hex string representation. -* @ignore -*/ -ObjectID.prototype.toString = function(format) { - // Is the id a buffer then use the buffer toString method to return the format - if (this.id && this.id.copy) { - return this.id.toString(typeof format === 'string' ? format : 'hex'); - } - - // if(this.buffer ) - return this.toHexString(); -}; - -/** -* Converts to a string representation of this Id. -* -* @return {String} return the 24 byte hex string representation. -* @ignore -*/ -ObjectID.prototype[inspect] = ObjectID.prototype.toString; - -/** -* Converts to its JSON representation. -* -* @return {String} return the 24 byte hex string representation. -* @ignore -*/ -ObjectID.prototype.toJSON = function() { - return this.toHexString(); -}; - -/** -* Compares the equality of this ObjectID with `otherID`. -* -* @method -* @param {object} otherID ObjectID instance to compare against. -* @return {boolean} the result of comparing two ObjectID's -*/ -ObjectID.prototype.equals = function equals(otherId) { - // var id; - - if (otherId instanceof ObjectID) { - return this.toString() === otherId.toString(); - } else if ( - typeof otherId === 'string' && - ObjectID.isValid(otherId) && - otherId.length === 12 && - this.id instanceof _Buffer - ) { - return otherId === this.id.toString('binary'); - } else if (typeof otherId === 'string' && ObjectID.isValid(otherId) && otherId.length === 24) { - return otherId.toLowerCase() === this.toHexString(); - } else if (typeof otherId === 'string' && ObjectID.isValid(otherId) && otherId.length === 12) { - return otherId === this.id; - } else if (otherId != null && (otherId instanceof ObjectID || otherId.toHexString)) { - return otherId.toHexString() === this.toHexString(); - } else { - return false; - } -}; - -/** -* Returns the generation date (accurate up to the second) that this ID was generated. -* -* @method -* @return {date} the generation date -*/ -ObjectID.prototype.getTimestamp = function() { - var timestamp = new Date(); - var time = this.id[3] | (this.id[2] << 8) | (this.id[1] << 16) | (this.id[0] << 24); - timestamp.setTime(Math.floor(time) * 1000); - return timestamp; -}; - -/** -* @ignore -*/ -ObjectID.index = ~~(Math.random() * 0xffffff); - -/** -* @ignore -*/ -ObjectID.createPk = function createPk() { - return new ObjectID(); -}; - -/** -* Creates an ObjectID from a second based number, with the rest of the ObjectID zeroed out. Used for comparisons or sorting the ObjectID. -* -* @method -* @param {number} time an integer number representing a number of seconds. -* @return {ObjectID} return the created ObjectID -*/ -ObjectID.createFromTime = function createFromTime(time) { - var buffer = utils.toBuffer([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); - // Encode time into first 4 bytes - buffer[3] = time & 0xff; - buffer[2] = (time >> 8) & 0xff; - buffer[1] = (time >> 16) & 0xff; - buffer[0] = (time >> 24) & 0xff; - // Return the new objectId - return new ObjectID(buffer); -}; - -// Lookup tables -//var encodeLookup = '0123456789abcdef'.split(''); -var decodeLookup = []; -i = 0; -while (i < 10) decodeLookup[0x30 + i] = i++; -while (i < 16) decodeLookup[0x41 - 10 + i] = decodeLookup[0x61 - 10 + i] = i++; - -var _Buffer = Buffer; -var convertToHex = function(bytes) { - return bytes.toString('hex'); -}; - -/** -* Creates an ObjectID from a hex string representation of an ObjectID. -* -* @method -* @param {string} hexString create a ObjectID from a passed in 24 byte hexstring. -* @return {ObjectID} return the created ObjectID -*/ -ObjectID.createFromHexString = function createFromHexString(string) { - // Throw an error if it's not a valid setup - if (typeof string === 'undefined' || (string != null && string.length !== 24)) { - throw new Error( - 'Argument passed in must be a single String of 12 bytes or a string of 24 hex characters' - ); - } - - // Use Buffer.from method if available - if (hasBufferType) return new ObjectID(utils.toBuffer(string, 'hex')); - - // Calculate lengths - var array = new _Buffer(12); - var n = 0; - var i = 0; - - while (i < 24) { - array[n++] = (decodeLookup[string.charCodeAt(i++)] << 4) | decodeLookup[string.charCodeAt(i++)]; - } - - return new ObjectID(array); -}; - -/** -* Checks if a value is a valid bson ObjectId -* -* @method -* @return {boolean} return true if the value is a valid bson ObjectId, return false otherwise. -*/ -ObjectID.isValid = function isValid(id) { - if (id == null) return false; - - if (typeof id === 'number') { - return true; - } - - if (typeof id === 'string') { - return id.length === 12 || (id.length === 24 && checkForHexRegExp.test(id)); - } - - if (id instanceof ObjectID) { - return true; - } - - if (id instanceof _Buffer) { - return true; - } - - // Duck-Typing detection of ObjectId like objects - if (id.toHexString) { - return id.id.length === 12 || (id.id.length === 24 && checkForHexRegExp.test(id.id)); - } - - return false; -}; - -/** -* @ignore -*/ -Object.defineProperty(ObjectID.prototype, 'generationTime', { - enumerable: true, - get: function() { - return this.id[3] | (this.id[2] << 8) | (this.id[1] << 16) | (this.id[0] << 24); - }, - set: function(value) { - // Encode time into first 4 bytes - this.id[3] = value & 0xff; - this.id[2] = (value >> 8) & 0xff; - this.id[1] = (value >> 16) & 0xff; - this.id[0] = (value >> 24) & 0xff; - } -}); - -/** - * Expose. - */ -module.exports = ObjectID; -module.exports.ObjectID = ObjectID; -module.exports.ObjectId = ObjectID; diff --git a/scripts/2.5/node_modules/bson/lib/bson/parser/calculate_size.js b/scripts/2.5/node_modules/bson/lib/bson/parser/calculate_size.js deleted file mode 100644 index 7e0026ca..00000000 --- a/scripts/2.5/node_modules/bson/lib/bson/parser/calculate_size.js +++ /dev/null @@ -1,255 +0,0 @@ -'use strict'; - -var Long = require('../long').Long, - Double = require('../double').Double, - Timestamp = require('../timestamp').Timestamp, - ObjectID = require('../objectid').ObjectID, - Symbol = require('../symbol').Symbol, - BSONRegExp = require('../regexp').BSONRegExp, - Code = require('../code').Code, - Decimal128 = require('../decimal128'), - MinKey = require('../min_key').MinKey, - MaxKey = require('../max_key').MaxKey, - DBRef = require('../db_ref').DBRef, - Binary = require('../binary').Binary; - -var normalizedFunctionString = require('./utils').normalizedFunctionString; - -// To ensure that 0.4 of node works correctly -var isDate = function isDate(d) { - return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; -}; - -var calculateObjectSize = function calculateObjectSize( - object, - serializeFunctions, - ignoreUndefined -) { - var totalLength = 4 + 1; - - if (Array.isArray(object)) { - for (var i = 0; i < object.length; i++) { - totalLength += calculateElement( - i.toString(), - object[i], - serializeFunctions, - true, - ignoreUndefined - ); - } - } else { - // If we have toBSON defined, override the current object - if (object.toBSON) { - object = object.toBSON(); - } - - // Calculate size - for (var key in object) { - totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined); - } - } - - return totalLength; -}; - -/** - * @ignore - * @api private - */ -function calculateElement(name, value, serializeFunctions, isArray, ignoreUndefined) { - // If we have toBSON defined, override the current object - if (value && value.toBSON) { - value = value.toBSON(); - } - - switch (typeof value) { - case 'string': - return 1 + Buffer.byteLength(name, 'utf8') + 1 + 4 + Buffer.byteLength(value, 'utf8') + 1; - case 'number': - if (Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - if (value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { - // 32 bit - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (4 + 1); - } else { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); - } - } else { - // 64 bit - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); - } - case 'undefined': - if (isArray || !ignoreUndefined) - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1; - return 0; - case 'boolean': - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (1 + 1); - case 'object': - if ( - value == null || - value instanceof MinKey || - value instanceof MaxKey || - value['_bsontype'] === 'MinKey' || - value['_bsontype'] === 'MaxKey' - ) { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1; - } else if (value instanceof ObjectID || value['_bsontype'] === 'ObjectID' || value['_bsontype'] === 'ObjectId') { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (12 + 1); - } else if (value instanceof Date || isDate(value)) { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); - } else if (typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { - return ( - (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (1 + 4 + 1) + value.length - ); - } else if ( - value instanceof Long || - value instanceof Double || - value instanceof Timestamp || - value['_bsontype'] === 'Long' || - value['_bsontype'] === 'Double' || - value['_bsontype'] === 'Timestamp' - ) { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); - } else if (value instanceof Decimal128 || value['_bsontype'] === 'Decimal128') { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (16 + 1); - } else if (value instanceof Code || value['_bsontype'] === 'Code') { - // Calculate size depending on the availability of a scope - if (value.scope != null && Object.keys(value.scope).length > 0) { - return ( - (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - 1 + - 4 + - 4 + - Buffer.byteLength(value.code.toString(), 'utf8') + - 1 + - calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined) - ); - } else { - return ( - (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - 1 + - 4 + - Buffer.byteLength(value.code.toString(), 'utf8') + - 1 - ); - } - } else if (value instanceof Binary || value['_bsontype'] === 'Binary') { - // Check what kind of subtype we have - if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { - return ( - (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - (value.position + 1 + 4 + 1 + 4) - ); - } else { - return ( - (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (value.position + 1 + 4 + 1) - ); - } - } else if (value instanceof Symbol || value['_bsontype'] === 'Symbol') { - return ( - (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - Buffer.byteLength(value.value, 'utf8') + - 4 + - 1 + - 1 - ); - } else if (value instanceof DBRef || value['_bsontype'] === 'DBRef') { - // Set up correct object for serialization - var ordered_values = { - $ref: value.namespace, - $id: value.oid - }; - - // Add db reference if it exists - if (null != value.db) { - ordered_values['$db'] = value.db; - } - - return ( - (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - 1 + - calculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined) - ); - } else if ( - value instanceof RegExp || - Object.prototype.toString.call(value) === '[object RegExp]' - ) { - return ( - (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - 1 + - Buffer.byteLength(value.source, 'utf8') + - 1 + - (value.global ? 1 : 0) + - (value.ignoreCase ? 1 : 0) + - (value.multiline ? 1 : 0) + - 1 - ); - } else if (value instanceof BSONRegExp || value['_bsontype'] === 'BSONRegExp') { - return ( - (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - 1 + - Buffer.byteLength(value.pattern, 'utf8') + - 1 + - Buffer.byteLength(value.options, 'utf8') + - 1 - ); - } else { - return ( - (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - calculateObjectSize(value, serializeFunctions, ignoreUndefined) + - 1 - ); - } - case 'function': - // WTF for 0.4.X where typeof /someregexp/ === 'function' - if ( - value instanceof RegExp || - Object.prototype.toString.call(value) === '[object RegExp]' || - String.call(value) === '[object RegExp]' - ) { - return ( - (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - 1 + - Buffer.byteLength(value.source, 'utf8') + - 1 + - (value.global ? 1 : 0) + - (value.ignoreCase ? 1 : 0) + - (value.multiline ? 1 : 0) + - 1 - ); - } else { - if (serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { - return ( - (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - 1 + - 4 + - 4 + - Buffer.byteLength(normalizedFunctionString(value), 'utf8') + - 1 + - calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined) - ); - } else if (serializeFunctions) { - return ( - (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - 1 + - 4 + - Buffer.byteLength(normalizedFunctionString(value), 'utf8') + - 1 - ); - } - } - } - - return 0; -} - -var BSON = {}; - -// BSON MAX VALUES -BSON.BSON_INT32_MAX = 0x7fffffff; -BSON.BSON_INT32_MIN = -0x80000000; - -// JS MAX PRECISE VALUES -BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. -BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. - -module.exports = calculateObjectSize; diff --git a/scripts/2.5/node_modules/bson/lib/bson/parser/deserializer.js b/scripts/2.5/node_modules/bson/lib/bson/parser/deserializer.js deleted file mode 100644 index be3c8654..00000000 --- a/scripts/2.5/node_modules/bson/lib/bson/parser/deserializer.js +++ /dev/null @@ -1,782 +0,0 @@ -'use strict'; - -var Long = require('../long').Long, - Double = require('../double').Double, - Timestamp = require('../timestamp').Timestamp, - ObjectID = require('../objectid').ObjectID, - Symbol = require('../symbol').Symbol, - Code = require('../code').Code, - MinKey = require('../min_key').MinKey, - MaxKey = require('../max_key').MaxKey, - Decimal128 = require('../decimal128'), - Int32 = require('../int_32'), - DBRef = require('../db_ref').DBRef, - BSONRegExp = require('../regexp').BSONRegExp, - Binary = require('../binary').Binary; - -var utils = require('./utils'); - -var deserialize = function(buffer, options, isArray) { - options = options == null ? {} : options; - var index = options && options.index ? options.index : 0; - // Read the document size - var size = - buffer[index] | - (buffer[index + 1] << 8) | - (buffer[index + 2] << 16) | - (buffer[index + 3] << 24); - - // Ensure buffer is valid size - if (size < 5 || buffer.length < size || size + index > buffer.length) { - throw new Error('corrupt bson message'); - } - - // Illegal end value - if (buffer[index + size - 1] !== 0) { - throw new Error("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00"); - } - - // Start deserializtion - return deserializeObject(buffer, index, options, isArray); -}; - -var deserializeObject = function(buffer, index, options, isArray) { - var evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions']; - var cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions']; - var cacheFunctionsCrc32 = - options['cacheFunctionsCrc32'] == null ? false : options['cacheFunctionsCrc32']; - - if (!cacheFunctionsCrc32) var crc32 = null; - - var fieldsAsRaw = options['fieldsAsRaw'] == null ? null : options['fieldsAsRaw']; - - // Return raw bson buffer instead of parsing it - var raw = options['raw'] == null ? false : options['raw']; - - // Return BSONRegExp objects instead of native regular expressions - var bsonRegExp = typeof options['bsonRegExp'] === 'boolean' ? options['bsonRegExp'] : false; - - // Controls the promotion of values vs wrapper classes - var promoteBuffers = options['promoteBuffers'] == null ? false : options['promoteBuffers']; - var promoteLongs = options['promoteLongs'] == null ? true : options['promoteLongs']; - var promoteValues = options['promoteValues'] == null ? true : options['promoteValues']; - - // Set the start index - var startIndex = index; - - // Validate that we have at least 4 bytes of buffer - if (buffer.length < 5) throw new Error('corrupt bson message < 5 bytes long'); - - // Read the document size - var size = - buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); - - // Ensure buffer is valid size - if (size < 5 || size > buffer.length) throw new Error('corrupt bson message'); - - // Create holding object - var object = isArray ? [] : {}; - // Used for arrays to skip having to perform utf8 decoding - var arrayIndex = 0; - - var done = false; - - // While we have more left data left keep parsing - // while (buffer[index + 1] !== 0) { - while (!done) { - // Read the type - var elementType = buffer[index++]; - // If we get a zero it's the last byte, exit - if (elementType === 0) break; - - // Get the start search index - var i = index; - // Locate the end of the c string - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - - // If are at the end of the buffer there is a problem with the document - if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); - var name = isArray ? arrayIndex++ : buffer.toString('utf8', index, i); - - index = i + 1; - - if (elementType === BSON.BSON_DATA_STRING) { - var stringSize = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - if ( - stringSize <= 0 || - stringSize > buffer.length - index || - buffer[index + stringSize - 1] !== 0 - ) - throw new Error('bad string length in bson'); - object[name] = buffer.toString('utf8', index, index + stringSize - 1); - index = index + stringSize; - } else if (elementType === BSON.BSON_DATA_OID) { - var oid = utils.allocBuffer(12); - buffer.copy(oid, 0, index, index + 12); - object[name] = new ObjectID(oid); - index = index + 12; - } else if (elementType === BSON.BSON_DATA_INT && promoteValues === false) { - object[name] = new Int32( - buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24) - ); - } else if (elementType === BSON.BSON_DATA_INT) { - object[name] = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - } else if (elementType === BSON.BSON_DATA_NUMBER && promoteValues === false) { - object[name] = new Double(buffer.readDoubleLE(index)); - index = index + 8; - } else if (elementType === BSON.BSON_DATA_NUMBER) { - object[name] = buffer.readDoubleLE(index); - index = index + 8; - } else if (elementType === BSON.BSON_DATA_DATE) { - var lowBits = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - var highBits = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - object[name] = new Date(new Long(lowBits, highBits).toNumber()); - } else if (elementType === BSON.BSON_DATA_BOOLEAN) { - if (buffer[index] !== 0 && buffer[index] !== 1) throw new Error('illegal boolean type value'); - object[name] = buffer[index++] === 1; - } else if (elementType === BSON.BSON_DATA_OBJECT) { - var _index = index; - var objectSize = - buffer[index] | - (buffer[index + 1] << 8) | - (buffer[index + 2] << 16) | - (buffer[index + 3] << 24); - if (objectSize <= 0 || objectSize > buffer.length - index) - throw new Error('bad embedded document length in bson'); - - // We have a raw value - if (raw) { - object[name] = buffer.slice(index, index + objectSize); - } else { - object[name] = deserializeObject(buffer, _index, options, false); - } - - index = index + objectSize; - } else if (elementType === BSON.BSON_DATA_ARRAY) { - _index = index; - objectSize = - buffer[index] | - (buffer[index + 1] << 8) | - (buffer[index + 2] << 16) | - (buffer[index + 3] << 24); - var arrayOptions = options; - - // Stop index - var stopIndex = index + objectSize; - - // All elements of array to be returned as raw bson - if (fieldsAsRaw && fieldsAsRaw[name]) { - arrayOptions = {}; - for (var n in options) arrayOptions[n] = options[n]; - arrayOptions['raw'] = true; - } - - object[name] = deserializeObject(buffer, _index, arrayOptions, true); - index = index + objectSize; - - if (buffer[index - 1] !== 0) throw new Error('invalid array terminator byte'); - if (index !== stopIndex) throw new Error('corrupted array bson'); - } else if (elementType === BSON.BSON_DATA_UNDEFINED) { - object[name] = undefined; - } else if (elementType === BSON.BSON_DATA_NULL) { - object[name] = null; - } else if (elementType === BSON.BSON_DATA_LONG) { - // Unpack the low and high bits - lowBits = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - highBits = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - var long = new Long(lowBits, highBits); - // Promote the long if possible - if (promoteLongs && promoteValues === true) { - object[name] = - long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) - ? long.toNumber() - : long; - } else { - object[name] = long; - } - } else if (elementType === BSON.BSON_DATA_DECIMAL128) { - // Buffer to contain the decimal bytes - var bytes = utils.allocBuffer(16); - // Copy the next 16 bytes into the bytes buffer - buffer.copy(bytes, 0, index, index + 16); - // Update index - index = index + 16; - // Assign the new Decimal128 value - var decimal128 = new Decimal128(bytes); - // If we have an alternative mapper use that - object[name] = decimal128.toObject ? decimal128.toObject() : decimal128; - } else if (elementType === BSON.BSON_DATA_BINARY) { - var binarySize = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - var totalBinarySize = binarySize; - var subType = buffer[index++]; - - // Did we have a negative binary size, throw - if (binarySize < 0) throw new Error('Negative binary type element size found'); - - // Is the length longer than the document - if (binarySize > buffer.length) throw new Error('Binary type size larger than document size'); - - // Decode as raw Buffer object if options specifies it - if (buffer['slice'] != null) { - // If we have subtype 2 skip the 4 bytes for the size - if (subType === Binary.SUBTYPE_BYTE_ARRAY) { - binarySize = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - if (binarySize < 0) - throw new Error('Negative binary type element size found for subtype 0x02'); - if (binarySize > totalBinarySize - 4) - throw new Error('Binary type with subtype 0x02 contains to long binary size'); - if (binarySize < totalBinarySize - 4) - throw new Error('Binary type with subtype 0x02 contains to short binary size'); - } - - if (promoteBuffers && promoteValues) { - object[name] = buffer.slice(index, index + binarySize); - } else { - object[name] = new Binary(buffer.slice(index, index + binarySize), subType); - } - } else { - var _buffer = - typeof Uint8Array !== 'undefined' - ? new Uint8Array(new ArrayBuffer(binarySize)) - : new Array(binarySize); - // If we have subtype 2 skip the 4 bytes for the size - if (subType === Binary.SUBTYPE_BYTE_ARRAY) { - binarySize = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - if (binarySize < 0) - throw new Error('Negative binary type element size found for subtype 0x02'); - if (binarySize > totalBinarySize - 4) - throw new Error('Binary type with subtype 0x02 contains to long binary size'); - if (binarySize < totalBinarySize - 4) - throw new Error('Binary type with subtype 0x02 contains to short binary size'); - } - - // Copy the data - for (i = 0; i < binarySize; i++) { - _buffer[i] = buffer[index + i]; - } - - if (promoteBuffers && promoteValues) { - object[name] = _buffer; - } else { - object[name] = new Binary(_buffer, subType); - } - } - - // Update the index - index = index + binarySize; - } else if (elementType === BSON.BSON_DATA_REGEXP && bsonRegExp === false) { - // Get the start search index - i = index; - // Locate the end of the c string - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - // If are at the end of the buffer there is a problem with the document - if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); - // Return the C string - var source = buffer.toString('utf8', index, i); - // Create the regexp - index = i + 1; - - // Get the start search index - i = index; - // Locate the end of the c string - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - // If are at the end of the buffer there is a problem with the document - if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); - // Return the C string - var regExpOptions = buffer.toString('utf8', index, i); - index = i + 1; - - // For each option add the corresponding one for javascript - var optionsArray = new Array(regExpOptions.length); - - // Parse options - for (i = 0; i < regExpOptions.length; i++) { - switch (regExpOptions[i]) { - case 'm': - optionsArray[i] = 'm'; - break; - case 's': - optionsArray[i] = 'g'; - break; - case 'i': - optionsArray[i] = 'i'; - break; - } - } - - object[name] = new RegExp(source, optionsArray.join('')); - } else if (elementType === BSON.BSON_DATA_REGEXP && bsonRegExp === true) { - // Get the start search index - i = index; - // Locate the end of the c string - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - // If are at the end of the buffer there is a problem with the document - if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); - // Return the C string - source = buffer.toString('utf8', index, i); - index = i + 1; - - // Get the start search index - i = index; - // Locate the end of the c string - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - // If are at the end of the buffer there is a problem with the document - if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); - // Return the C string - regExpOptions = buffer.toString('utf8', index, i); - index = i + 1; - - // Set the object - object[name] = new BSONRegExp(source, regExpOptions); - } else if (elementType === BSON.BSON_DATA_SYMBOL) { - stringSize = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - if ( - stringSize <= 0 || - stringSize > buffer.length - index || - buffer[index + stringSize - 1] !== 0 - ) - throw new Error('bad string length in bson'); - object[name] = new Symbol(buffer.toString('utf8', index, index + stringSize - 1)); - index = index + stringSize; - } else if (elementType === BSON.BSON_DATA_TIMESTAMP) { - lowBits = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - highBits = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - object[name] = new Timestamp(lowBits, highBits); - } else if (elementType === BSON.BSON_DATA_MIN_KEY) { - object[name] = new MinKey(); - } else if (elementType === BSON.BSON_DATA_MAX_KEY) { - object[name] = new MaxKey(); - } else if (elementType === BSON.BSON_DATA_CODE) { - stringSize = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - if ( - stringSize <= 0 || - stringSize > buffer.length - index || - buffer[index + stringSize - 1] !== 0 - ) - throw new Error('bad string length in bson'); - var functionString = buffer.toString('utf8', index, index + stringSize - 1); - - // If we are evaluating the functions - if (evalFunctions) { - // If we have cache enabled let's look for the md5 of the function in the cache - if (cacheFunctions) { - var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; - // Got to do this to avoid V8 deoptimizing the call due to finding eval - object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); - } else { - object[name] = isolateEval(functionString); - } - } else { - object[name] = new Code(functionString); - } - - // Update parse index position - index = index + stringSize; - } else if (elementType === BSON.BSON_DATA_CODE_W_SCOPE) { - var totalSize = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - - // Element cannot be shorter than totalSize + stringSize + documentSize + terminator - if (totalSize < 4 + 4 + 4 + 1) { - throw new Error('code_w_scope total size shorter minimum expected length'); - } - - // Get the code string size - stringSize = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - // Check if we have a valid string - if ( - stringSize <= 0 || - stringSize > buffer.length - index || - buffer[index + stringSize - 1] !== 0 - ) - throw new Error('bad string length in bson'); - - // Javascript function - functionString = buffer.toString('utf8', index, index + stringSize - 1); - // Update parse index position - index = index + stringSize; - // Parse the element - _index = index; - // Decode the size of the object document - objectSize = - buffer[index] | - (buffer[index + 1] << 8) | - (buffer[index + 2] << 16) | - (buffer[index + 3] << 24); - // Decode the scope object - var scopeObject = deserializeObject(buffer, _index, options, false); - // Adjust the index - index = index + objectSize; - - // Check if field length is to short - if (totalSize < 4 + 4 + objectSize + stringSize) { - throw new Error('code_w_scope total size is to short, truncating scope'); - } - - // Check if totalSize field is to long - if (totalSize > 4 + 4 + objectSize + stringSize) { - throw new Error('code_w_scope total size is to long, clips outer document'); - } - - // If we are evaluating the functions - if (evalFunctions) { - // If we have cache enabled let's look for the md5 of the function in the cache - if (cacheFunctions) { - hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; - // Got to do this to avoid V8 deoptimizing the call due to finding eval - object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); - } else { - object[name] = isolateEval(functionString); - } - - object[name].scope = scopeObject; - } else { - object[name] = new Code(functionString, scopeObject); - } - } else if (elementType === BSON.BSON_DATA_DBPOINTER) { - // Get the code string size - stringSize = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - // Check if we have a valid string - if ( - stringSize <= 0 || - stringSize > buffer.length - index || - buffer[index + stringSize - 1] !== 0 - ) - throw new Error('bad string length in bson'); - // Namespace - var namespace = buffer.toString('utf8', index, index + stringSize - 1); - // Update parse index position - index = index + stringSize; - - // Read the oid - var oidBuffer = utils.allocBuffer(12); - buffer.copy(oidBuffer, 0, index, index + 12); - oid = new ObjectID(oidBuffer); - - // Update the index - index = index + 12; - - // Split the namespace - var parts = namespace.split('.'); - var db = parts.shift(); - var collection = parts.join('.'); - // Upgrade to DBRef type - object[name] = new DBRef(collection, oid, db); - } else { - throw new Error( - 'Detected unknown BSON type ' + - elementType.toString(16) + - ' for fieldname "' + - name + - '", are you using the latest BSON parser' - ); - } - } - - // Check if the deserialization was against a valid array/object - if (size !== index - startIndex) { - if (isArray) throw new Error('corrupt array bson'); - throw new Error('corrupt object bson'); - } - - // Check if we have a db ref object - if (object['$id'] != null) object = new DBRef(object['$ref'], object['$id'], object['$db']); - return object; -}; - -/** - * Ensure eval is isolated. - * - * @ignore - * @api private - */ -var isolateEvalWithHash = function(functionCache, hash, functionString, object) { - // Contains the value we are going to set - var value = null; - - // Check for cache hit, eval if missing and return cached function - if (functionCache[hash] == null) { - eval('value = ' + functionString); - functionCache[hash] = value; - } - // Set the object - return functionCache[hash].bind(object); -}; - -/** - * Ensure eval is isolated. - * - * @ignore - * @api private - */ -var isolateEval = function(functionString) { - // Contains the value we are going to set - var value = null; - // Eval the function - eval('value = ' + functionString); - return value; -}; - -var BSON = {}; - -/** - * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 - * - * @ignore - * @api private - */ -var functionCache = (BSON.functionCache = {}); - -/** - * Number BSON Type - * - * @classconstant BSON_DATA_NUMBER - **/ -BSON.BSON_DATA_NUMBER = 1; -/** - * String BSON Type - * - * @classconstant BSON_DATA_STRING - **/ -BSON.BSON_DATA_STRING = 2; -/** - * Object BSON Type - * - * @classconstant BSON_DATA_OBJECT - **/ -BSON.BSON_DATA_OBJECT = 3; -/** - * Array BSON Type - * - * @classconstant BSON_DATA_ARRAY - **/ -BSON.BSON_DATA_ARRAY = 4; -/** - * Binary BSON Type - * - * @classconstant BSON_DATA_BINARY - **/ -BSON.BSON_DATA_BINARY = 5; -/** - * Binary BSON Type - * - * @classconstant BSON_DATA_UNDEFINED - **/ -BSON.BSON_DATA_UNDEFINED = 6; -/** - * ObjectID BSON Type - * - * @classconstant BSON_DATA_OID - **/ -BSON.BSON_DATA_OID = 7; -/** - * Boolean BSON Type - * - * @classconstant BSON_DATA_BOOLEAN - **/ -BSON.BSON_DATA_BOOLEAN = 8; -/** - * Date BSON Type - * - * @classconstant BSON_DATA_DATE - **/ -BSON.BSON_DATA_DATE = 9; -/** - * null BSON Type - * - * @classconstant BSON_DATA_NULL - **/ -BSON.BSON_DATA_NULL = 10; -/** - * RegExp BSON Type - * - * @classconstant BSON_DATA_REGEXP - **/ -BSON.BSON_DATA_REGEXP = 11; -/** - * Code BSON Type - * - * @classconstant BSON_DATA_DBPOINTER - **/ -BSON.BSON_DATA_DBPOINTER = 12; -/** - * Code BSON Type - * - * @classconstant BSON_DATA_CODE - **/ -BSON.BSON_DATA_CODE = 13; -/** - * Symbol BSON Type - * - * @classconstant BSON_DATA_SYMBOL - **/ -BSON.BSON_DATA_SYMBOL = 14; -/** - * Code with Scope BSON Type - * - * @classconstant BSON_DATA_CODE_W_SCOPE - **/ -BSON.BSON_DATA_CODE_W_SCOPE = 15; -/** - * 32 bit Integer BSON Type - * - * @classconstant BSON_DATA_INT - **/ -BSON.BSON_DATA_INT = 16; -/** - * Timestamp BSON Type - * - * @classconstant BSON_DATA_TIMESTAMP - **/ -BSON.BSON_DATA_TIMESTAMP = 17; -/** - * Long BSON Type - * - * @classconstant BSON_DATA_LONG - **/ -BSON.BSON_DATA_LONG = 18; -/** - * Long BSON Type - * - * @classconstant BSON_DATA_DECIMAL128 - **/ -BSON.BSON_DATA_DECIMAL128 = 19; -/** - * MinKey BSON Type - * - * @classconstant BSON_DATA_MIN_KEY - **/ -BSON.BSON_DATA_MIN_KEY = 0xff; -/** - * MaxKey BSON Type - * - * @classconstant BSON_DATA_MAX_KEY - **/ -BSON.BSON_DATA_MAX_KEY = 0x7f; - -/** - * Binary Default Type - * - * @classconstant BSON_BINARY_SUBTYPE_DEFAULT - **/ -BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; -/** - * Binary Function Type - * - * @classconstant BSON_BINARY_SUBTYPE_FUNCTION - **/ -BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; -/** - * Binary Byte Array Type - * - * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY - **/ -BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; -/** - * Binary UUID Type - * - * @classconstant BSON_BINARY_SUBTYPE_UUID - **/ -BSON.BSON_BINARY_SUBTYPE_UUID = 3; -/** - * Binary MD5 Type - * - * @classconstant BSON_BINARY_SUBTYPE_MD5 - **/ -BSON.BSON_BINARY_SUBTYPE_MD5 = 4; -/** - * Binary User Defined Type - * - * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED - **/ -BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; - -// BSON MAX VALUES -BSON.BSON_INT32_MAX = 0x7fffffff; -BSON.BSON_INT32_MIN = -0x80000000; - -BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; -BSON.BSON_INT64_MIN = -Math.pow(2, 63); - -// JS MAX PRECISE VALUES -BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. -BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. - -// Internal long versions -var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. -var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. - -module.exports = deserialize; diff --git a/scripts/2.5/node_modules/bson/lib/bson/parser/serializer.js b/scripts/2.5/node_modules/bson/lib/bson/parser/serializer.js deleted file mode 100644 index e4ff2bd9..00000000 --- a/scripts/2.5/node_modules/bson/lib/bson/parser/serializer.js +++ /dev/null @@ -1,1182 +0,0 @@ -'use strict'; - -var writeIEEE754 = require('../float_parser').writeIEEE754, - Long = require('../long').Long, - Map = require('../map'), - Binary = require('../binary').Binary; - -var normalizedFunctionString = require('./utils').normalizedFunctionString; - -// try { -// var _Buffer = Uint8Array; -// } catch (e) { -// _Buffer = Buffer; -// } - -var regexp = /\x00/; // eslint-disable-line no-control-regex -var ignoreKeys = ['$db', '$ref', '$id', '$clusterTime']; - -// To ensure that 0.4 of node works correctly -var isDate = function isDate(d) { - return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; -}; - -var isRegExp = function isRegExp(d) { - return Object.prototype.toString.call(d) === '[object RegExp]'; -}; - -var serializeString = function(buffer, key, value, index, isArray) { - // Encode String type - buffer[index++] = BSON.BSON_DATA_STRING; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write the string - var size = buffer.write(value, index + 4, 'utf8'); - // Write the size of the string to buffer - buffer[index + 3] = ((size + 1) >> 24) & 0xff; - buffer[index + 2] = ((size + 1) >> 16) & 0xff; - buffer[index + 1] = ((size + 1) >> 8) & 0xff; - buffer[index] = (size + 1) & 0xff; - // Update index - index = index + 4 + size; - // Write zero - buffer[index++] = 0; - return index; -}; - -var serializeNumber = function(buffer, key, value, index, isArray) { - // We have an integer value - if (Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - // If the value fits in 32 bits encode as int, if it fits in a double - // encode it as a double, otherwise long - if (value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { - // Set int type 32 bits or less - buffer[index++] = BSON.BSON_DATA_INT; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the int value - buffer[index++] = value & 0xff; - buffer[index++] = (value >> 8) & 0xff; - buffer[index++] = (value >> 16) & 0xff; - buffer[index++] = (value >> 24) & 0xff; - } else if (value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - } else { - // Set long type - buffer[index++] = BSON.BSON_DATA_LONG; - // Number of written bytes - numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - var longVal = Long.fromNumber(value); - var lowBits = longVal.getLowBits(); - var highBits = longVal.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - } - } else { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - } - - return index; -}; - -var serializeNull = function(buffer, key, value, index, isArray) { - // Set long type - buffer[index++] = BSON.BSON_DATA_NULL; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - return index; -}; - -var serializeBoolean = function(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_BOOLEAN; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Encode the boolean value - buffer[index++] = value ? 1 : 0; - return index; -}; - -var serializeDate = function(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_DATE; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - - // Write the date - var dateInMilis = Long.fromNumber(value.getTime()); - var lowBits = dateInMilis.getLowBits(); - var highBits = dateInMilis.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - return index; -}; - -var serializeRegExp = function(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_REGEXP; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - if (value.source && value.source.match(regexp) != null) { - throw Error('value ' + value.source + ' must not contain null bytes'); - } - // Adjust the index - index = index + buffer.write(value.source, index, 'utf8'); - // Write zero - buffer[index++] = 0x00; - // Write the parameters - if (value.global) buffer[index++] = 0x73; // s - if (value.ignoreCase) buffer[index++] = 0x69; // i - if (value.multiline) buffer[index++] = 0x6d; // m - // Add ending zero - buffer[index++] = 0x00; - return index; -}; - -var serializeBSONRegExp = function(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_REGEXP; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - - // Check the pattern for 0 bytes - if (value.pattern.match(regexp) != null) { - // The BSON spec doesn't allow keys with null bytes because keys are - // null-terminated. - throw Error('pattern ' + value.pattern + ' must not contain null bytes'); - } - - // Adjust the index - index = index + buffer.write(value.pattern, index, 'utf8'); - // Write zero - buffer[index++] = 0x00; - // Write the options - index = - index + - buffer.write( - value.options - .split('') - .sort() - .join(''), - index, - 'utf8' - ); - // Add ending zero - buffer[index++] = 0x00; - return index; -}; - -var serializeMinMax = function(buffer, key, value, index, isArray) { - // Write the type of either min or max key - if (value === null) { - buffer[index++] = BSON.BSON_DATA_NULL; - } else if (value._bsontype === 'MinKey') { - buffer[index++] = BSON.BSON_DATA_MIN_KEY; - } else { - buffer[index++] = BSON.BSON_DATA_MAX_KEY; - } - - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - return index; -}; - -var serializeObjectId = function(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_OID; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - - // Write the objectId into the shared buffer - if (typeof value.id === 'string') { - buffer.write(value.id, index, 'binary'); - } else if (value.id && value.id.copy) { - value.id.copy(buffer, index, 0, 12); - } else { - throw new Error('object [' + JSON.stringify(value) + '] is not a valid ObjectId'); - } - - // Ajust index - return index + 12; -}; - -var serializeBuffer = function(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_BINARY; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Get size of the buffer (current write point) - var size = value.length; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the default subtype - buffer[index++] = BSON.BSON_BINARY_SUBTYPE_DEFAULT; - // Copy the content form the binary field to the buffer - value.copy(buffer, index, 0, size); - // Adjust the index - index = index + size; - return index; -}; - -var serializeObject = function( - buffer, - key, - value, - index, - checkKeys, - depth, - serializeFunctions, - ignoreUndefined, - isArray, - path -) { - for (var i = 0; i < path.length; i++) { - if (path[i] === value) throw new Error('cyclic dependency detected'); - } - - // Push value to stack - path.push(value); - // Write the type - buffer[index++] = Array.isArray(value) ? BSON.BSON_DATA_ARRAY : BSON.BSON_DATA_OBJECT; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - var endIndex = serializeInto( - buffer, - value, - checkKeys, - index, - depth + 1, - serializeFunctions, - ignoreUndefined, - path - ); - // Pop stack - path.pop(); - // Write size - return endIndex; -}; - -var serializeDecimal128 = function(buffer, key, value, index, isArray) { - buffer[index++] = BSON.BSON_DATA_DECIMAL128; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the data from the value - value.bytes.copy(buffer, index, 0, 16); - return index + 16; -}; - -var serializeLong = function(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = value._bsontype === 'Long' ? BSON.BSON_DATA_LONG : BSON.BSON_DATA_TIMESTAMP; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the date - var lowBits = value.getLowBits(); - var highBits = value.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - return index; -}; - -var serializeInt32 = function(buffer, key, value, index, isArray) { - // Set int type 32 bits or less - buffer[index++] = BSON.BSON_DATA_INT; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the int value - buffer[index++] = value & 0xff; - buffer[index++] = (value >> 8) & 0xff; - buffer[index++] = (value >> 16) & 0xff; - buffer[index++] = (value >> 24) & 0xff; - return index; -}; - -var serializeDouble = function(buffer, key, value, index, isArray) { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - return index; -}; - -var serializeFunction = function(buffer, key, value, index, checkKeys, depth, isArray) { - buffer[index++] = BSON.BSON_DATA_CODE; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Function string - var functionString = normalizedFunctionString(value); - - // Write the string - var size = buffer.write(functionString, index + 4, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = size & 0xff; - buffer[index + 1] = (size >> 8) & 0xff; - buffer[index + 2] = (size >> 16) & 0xff; - buffer[index + 3] = (size >> 24) & 0xff; - // Update index - index = index + 4 + size - 1; - // Write zero - buffer[index++] = 0; - return index; -}; - -var serializeCode = function( - buffer, - key, - value, - index, - checkKeys, - depth, - serializeFunctions, - ignoreUndefined, - isArray -) { - if (value.scope && typeof value.scope === 'object') { - // Write the type - buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - - // Starting index - var startIndex = index; - - // Serialize the function - // Get the function string - var functionString = typeof value.code === 'string' ? value.code : value.code.toString(); - // Index adjustment - index = index + 4; - // Write string into buffer - var codeSize = buffer.write(functionString, index + 4, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = codeSize & 0xff; - buffer[index + 1] = (codeSize >> 8) & 0xff; - buffer[index + 2] = (codeSize >> 16) & 0xff; - buffer[index + 3] = (codeSize >> 24) & 0xff; - // Write end 0 - buffer[index + 4 + codeSize - 1] = 0; - // Write the - index = index + codeSize + 4; - - // - // Serialize the scope value - var endIndex = serializeInto( - buffer, - value.scope, - checkKeys, - index, - depth + 1, - serializeFunctions, - ignoreUndefined - ); - index = endIndex - 1; - - // Writ the total - var totalSize = endIndex - startIndex; - - // Write the total size of the object - buffer[startIndex++] = totalSize & 0xff; - buffer[startIndex++] = (totalSize >> 8) & 0xff; - buffer[startIndex++] = (totalSize >> 16) & 0xff; - buffer[startIndex++] = (totalSize >> 24) & 0xff; - // Write trailing zero - buffer[index++] = 0; - } else { - buffer[index++] = BSON.BSON_DATA_CODE; - // Number of written bytes - numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Function string - functionString = value.code.toString(); - // Write the string - var size = buffer.write(functionString, index + 4, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = size & 0xff; - buffer[index + 1] = (size >> 8) & 0xff; - buffer[index + 2] = (size >> 16) & 0xff; - buffer[index + 3] = (size >> 24) & 0xff; - // Update index - index = index + 4 + size - 1; - // Write zero - buffer[index++] = 0; - } - - return index; -}; - -var serializeBinary = function(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_BINARY; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Extract the buffer - var data = value.value(true); - // Calculate size - var size = value.position; - // Add the deprecated 02 type 4 bytes of size to total - if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) size = size + 4; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the subtype to the buffer - buffer[index++] = value.sub_type; - - // If we have binary type 2 the 4 first bytes are the size - if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { - size = size - 4; - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - } - - // Write the data to the object - data.copy(buffer, index, 0, value.position); - // Adjust the index - index = index + value.position; - return index; -}; - -var serializeSymbol = function(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_SYMBOL; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the string - var size = buffer.write(value.value, index + 4, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = size & 0xff; - buffer[index + 1] = (size >> 8) & 0xff; - buffer[index + 2] = (size >> 16) & 0xff; - buffer[index + 3] = (size >> 24) & 0xff; - // Update index - index = index + 4 + size - 1; - // Write zero - buffer[index++] = 0x00; - return index; -}; - -var serializeDBRef = function(buffer, key, value, index, depth, serializeFunctions, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_OBJECT; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - - var startIndex = index; - var endIndex; - - // Serialize object - if (null != value.db) { - endIndex = serializeInto( - buffer, - { - $ref: value.namespace, - $id: value.oid, - $db: value.db - }, - false, - index, - depth + 1, - serializeFunctions - ); - } else { - endIndex = serializeInto( - buffer, - { - $ref: value.namespace, - $id: value.oid - }, - false, - index, - depth + 1, - serializeFunctions - ); - } - - // Calculate object size - var size = endIndex - startIndex; - // Write the size - buffer[startIndex++] = size & 0xff; - buffer[startIndex++] = (size >> 8) & 0xff; - buffer[startIndex++] = (size >> 16) & 0xff; - buffer[startIndex++] = (size >> 24) & 0xff; - // Set index - return endIndex; -}; - -var serializeInto = function serializeInto( - buffer, - object, - checkKeys, - startingIndex, - depth, - serializeFunctions, - ignoreUndefined, - path -) { - startingIndex = startingIndex || 0; - path = path || []; - - // Push the object to the path - path.push(object); - - // Start place to serialize into - var index = startingIndex + 4; - // var self = this; - - // Special case isArray - if (Array.isArray(object)) { - // Get object keys - for (var i = 0; i < object.length; i++) { - var key = '' + i; - var value = object[i]; - - // Is there an override value - if (value && value.toBSON) { - if (typeof value.toBSON !== 'function') throw new Error('toBSON is not a function'); - value = value.toBSON(); - } - - var type = typeof value; - if (type === 'string') { - index = serializeString(buffer, key, value, index, true); - } else if (type === 'number') { - index = serializeNumber(buffer, key, value, index, true); - } else if (type === 'boolean') { - index = serializeBoolean(buffer, key, value, index, true); - } else if (value instanceof Date || isDate(value)) { - index = serializeDate(buffer, key, value, index, true); - } else if (value === undefined) { - index = serializeNull(buffer, key, value, index, true); - } else if (value === null) { - index = serializeNull(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'ObjectID' || value['_bsontype'] === 'ObjectId') { - index = serializeObjectId(buffer, key, value, index, true); - } else if (Buffer.isBuffer(value)) { - index = serializeBuffer(buffer, key, value, index, true); - } else if (value instanceof RegExp || isRegExp(value)) { - index = serializeRegExp(buffer, key, value, index, true); - } else if (type === 'object' && value['_bsontype'] == null) { - index = serializeObject( - buffer, - key, - value, - index, - checkKeys, - depth, - serializeFunctions, - ignoreUndefined, - true, - path - ); - } else if (type === 'object' && value['_bsontype'] === 'Decimal128') { - index = serializeDecimal128(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { - index = serializeLong(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'Double') { - index = serializeDouble(buffer, key, value, index, true); - } else if (typeof value === 'function' && serializeFunctions) { - index = serializeFunction( - buffer, - key, - value, - index, - checkKeys, - depth, - serializeFunctions, - true - ); - } else if (value['_bsontype'] === 'Code') { - index = serializeCode( - buffer, - key, - value, - index, - checkKeys, - depth, - serializeFunctions, - ignoreUndefined, - true - ); - } else if (value['_bsontype'] === 'Binary') { - index = serializeBinary(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'Symbol') { - index = serializeSymbol(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'DBRef') { - index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, true); - } else if (value['_bsontype'] === 'BSONRegExp') { - index = serializeBSONRegExp(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'Int32') { - index = serializeInt32(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { - index = serializeMinMax(buffer, key, value, index, true); - } - } - } else if (object instanceof Map) { - var iterator = object.entries(); - var done = false; - - while (!done) { - // Unpack the next entry - var entry = iterator.next(); - done = entry.done; - // Are we done, then skip and terminate - if (done) continue; - - // Get the entry values - key = entry.value[0]; - value = entry.value[1]; - - // Check the type of the value - type = typeof value; - - // Check the key and throw error if it's illegal - if (typeof key === 'string' && ignoreKeys.indexOf(key) === -1) { - if (key.match(regexp) != null) { - // The BSON spec doesn't allow keys with null bytes because keys are - // null-terminated. - throw Error('key ' + key + ' must not contain null bytes'); - } - - if (checkKeys) { - if ('$' === key[0]) { - throw Error('key ' + key + " must not start with '$'"); - } else if (~key.indexOf('.')) { - throw Error('key ' + key + " must not contain '.'"); - } - } - } - - if (type === 'string') { - index = serializeString(buffer, key, value, index); - } else if (type === 'number') { - index = serializeNumber(buffer, key, value, index); - } else if (type === 'boolean') { - index = serializeBoolean(buffer, key, value, index); - } else if (value instanceof Date || isDate(value)) { - index = serializeDate(buffer, key, value, index); - // } else if (value === undefined && ignoreUndefined === true) { - } else if (value === null || (value === undefined && ignoreUndefined === false)) { - index = serializeNull(buffer, key, value, index); - } else if (value['_bsontype'] === 'ObjectID' || value['_bsontype'] === 'ObjectId') { - index = serializeObjectId(buffer, key, value, index); - } else if (Buffer.isBuffer(value)) { - index = serializeBuffer(buffer, key, value, index); - } else if (value instanceof RegExp || isRegExp(value)) { - index = serializeRegExp(buffer, key, value, index); - } else if (type === 'object' && value['_bsontype'] == null) { - index = serializeObject( - buffer, - key, - value, - index, - checkKeys, - depth, - serializeFunctions, - ignoreUndefined, - false, - path - ); - } else if (type === 'object' && value['_bsontype'] === 'Decimal128') { - index = serializeDecimal128(buffer, key, value, index); - } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { - index = serializeLong(buffer, key, value, index); - } else if (value['_bsontype'] === 'Double') { - index = serializeDouble(buffer, key, value, index); - } else if (value['_bsontype'] === 'Code') { - index = serializeCode( - buffer, - key, - value, - index, - checkKeys, - depth, - serializeFunctions, - ignoreUndefined - ); - } else if (typeof value === 'function' && serializeFunctions) { - index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); - } else if (value['_bsontype'] === 'Binary') { - index = serializeBinary(buffer, key, value, index); - } else if (value['_bsontype'] === 'Symbol') { - index = serializeSymbol(buffer, key, value, index); - } else if (value['_bsontype'] === 'DBRef') { - index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); - } else if (value['_bsontype'] === 'BSONRegExp') { - index = serializeBSONRegExp(buffer, key, value, index); - } else if (value['_bsontype'] === 'Int32') { - index = serializeInt32(buffer, key, value, index); - } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { - index = serializeMinMax(buffer, key, value, index); - } - } - } else { - // Did we provide a custom serialization method - if (object.toBSON) { - if (typeof object.toBSON !== 'function') throw new Error('toBSON is not a function'); - object = object.toBSON(); - if (object != null && typeof object !== 'object') - throw new Error('toBSON function did not return an object'); - } - - // Iterate over all the keys - for (key in object) { - value = object[key]; - // Is there an override value - if (value && value.toBSON) { - if (typeof value.toBSON !== 'function') throw new Error('toBSON is not a function'); - value = value.toBSON(); - } - - // Check the type of the value - type = typeof value; - - // Check the key and throw error if it's illegal - if (typeof key === 'string' && ignoreKeys.indexOf(key) === -1) { - if (key.match(regexp) != null) { - // The BSON spec doesn't allow keys with null bytes because keys are - // null-terminated. - throw Error('key ' + key + ' must not contain null bytes'); - } - - if (checkKeys) { - if ('$' === key[0]) { - throw Error('key ' + key + " must not start with '$'"); - } else if (~key.indexOf('.')) { - throw Error('key ' + key + " must not contain '.'"); - } - } - } - - if (type === 'string') { - index = serializeString(buffer, key, value, index); - } else if (type === 'number') { - index = serializeNumber(buffer, key, value, index); - } else if (type === 'boolean') { - index = serializeBoolean(buffer, key, value, index); - } else if (value instanceof Date || isDate(value)) { - index = serializeDate(buffer, key, value, index); - } else if (value === undefined) { - if (ignoreUndefined === false) index = serializeNull(buffer, key, value, index); - } else if (value === null) { - index = serializeNull(buffer, key, value, index); - } else if (value['_bsontype'] === 'ObjectID' || value['_bsontype'] === 'ObjectId') { - index = serializeObjectId(buffer, key, value, index); - } else if (Buffer.isBuffer(value)) { - index = serializeBuffer(buffer, key, value, index); - } else if (value instanceof RegExp || isRegExp(value)) { - index = serializeRegExp(buffer, key, value, index); - } else if (type === 'object' && value['_bsontype'] == null) { - index = serializeObject( - buffer, - key, - value, - index, - checkKeys, - depth, - serializeFunctions, - ignoreUndefined, - false, - path - ); - } else if (type === 'object' && value['_bsontype'] === 'Decimal128') { - index = serializeDecimal128(buffer, key, value, index); - } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { - index = serializeLong(buffer, key, value, index); - } else if (value['_bsontype'] === 'Double') { - index = serializeDouble(buffer, key, value, index); - } else if (value['_bsontype'] === 'Code') { - index = serializeCode( - buffer, - key, - value, - index, - checkKeys, - depth, - serializeFunctions, - ignoreUndefined - ); - } else if (typeof value === 'function' && serializeFunctions) { - index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); - } else if (value['_bsontype'] === 'Binary') { - index = serializeBinary(buffer, key, value, index); - } else if (value['_bsontype'] === 'Symbol') { - index = serializeSymbol(buffer, key, value, index); - } else if (value['_bsontype'] === 'DBRef') { - index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); - } else if (value['_bsontype'] === 'BSONRegExp') { - index = serializeBSONRegExp(buffer, key, value, index); - } else if (value['_bsontype'] === 'Int32') { - index = serializeInt32(buffer, key, value, index); - } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { - index = serializeMinMax(buffer, key, value, index); - } - } - } - - // Remove the path - path.pop(); - - // Final padding byte for object - buffer[index++] = 0x00; - - // Final size - var size = index - startingIndex; - // Write the size of the object - buffer[startingIndex++] = size & 0xff; - buffer[startingIndex++] = (size >> 8) & 0xff; - buffer[startingIndex++] = (size >> 16) & 0xff; - buffer[startingIndex++] = (size >> 24) & 0xff; - return index; -}; - -var BSON = {}; - -/** - * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 - * - * @ignore - * @api private - */ -// var functionCache = (BSON.functionCache = {}); - -/** - * Number BSON Type - * - * @classconstant BSON_DATA_NUMBER - **/ -BSON.BSON_DATA_NUMBER = 1; -/** - * String BSON Type - * - * @classconstant BSON_DATA_STRING - **/ -BSON.BSON_DATA_STRING = 2; -/** - * Object BSON Type - * - * @classconstant BSON_DATA_OBJECT - **/ -BSON.BSON_DATA_OBJECT = 3; -/** - * Array BSON Type - * - * @classconstant BSON_DATA_ARRAY - **/ -BSON.BSON_DATA_ARRAY = 4; -/** - * Binary BSON Type - * - * @classconstant BSON_DATA_BINARY - **/ -BSON.BSON_DATA_BINARY = 5; -/** - * ObjectID BSON Type, deprecated - * - * @classconstant BSON_DATA_UNDEFINED - **/ -BSON.BSON_DATA_UNDEFINED = 6; -/** - * ObjectID BSON Type - * - * @classconstant BSON_DATA_OID - **/ -BSON.BSON_DATA_OID = 7; -/** - * Boolean BSON Type - * - * @classconstant BSON_DATA_BOOLEAN - **/ -BSON.BSON_DATA_BOOLEAN = 8; -/** - * Date BSON Type - * - * @classconstant BSON_DATA_DATE - **/ -BSON.BSON_DATA_DATE = 9; -/** - * null BSON Type - * - * @classconstant BSON_DATA_NULL - **/ -BSON.BSON_DATA_NULL = 10; -/** - * RegExp BSON Type - * - * @classconstant BSON_DATA_REGEXP - **/ -BSON.BSON_DATA_REGEXP = 11; -/** - * Code BSON Type - * - * @classconstant BSON_DATA_CODE - **/ -BSON.BSON_DATA_CODE = 13; -/** - * Symbol BSON Type - * - * @classconstant BSON_DATA_SYMBOL - **/ -BSON.BSON_DATA_SYMBOL = 14; -/** - * Code with Scope BSON Type - * - * @classconstant BSON_DATA_CODE_W_SCOPE - **/ -BSON.BSON_DATA_CODE_W_SCOPE = 15; -/** - * 32 bit Integer BSON Type - * - * @classconstant BSON_DATA_INT - **/ -BSON.BSON_DATA_INT = 16; -/** - * Timestamp BSON Type - * - * @classconstant BSON_DATA_TIMESTAMP - **/ -BSON.BSON_DATA_TIMESTAMP = 17; -/** - * Long BSON Type - * - * @classconstant BSON_DATA_LONG - **/ -BSON.BSON_DATA_LONG = 18; -/** - * Long BSON Type - * - * @classconstant BSON_DATA_DECIMAL128 - **/ -BSON.BSON_DATA_DECIMAL128 = 19; -/** - * MinKey BSON Type - * - * @classconstant BSON_DATA_MIN_KEY - **/ -BSON.BSON_DATA_MIN_KEY = 0xff; -/** - * MaxKey BSON Type - * - * @classconstant BSON_DATA_MAX_KEY - **/ -BSON.BSON_DATA_MAX_KEY = 0x7f; -/** - * Binary Default Type - * - * @classconstant BSON_BINARY_SUBTYPE_DEFAULT - **/ -BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; -/** - * Binary Function Type - * - * @classconstant BSON_BINARY_SUBTYPE_FUNCTION - **/ -BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; -/** - * Binary Byte Array Type - * - * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY - **/ -BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; -/** - * Binary UUID Type - * - * @classconstant BSON_BINARY_SUBTYPE_UUID - **/ -BSON.BSON_BINARY_SUBTYPE_UUID = 3; -/** - * Binary MD5 Type - * - * @classconstant BSON_BINARY_SUBTYPE_MD5 - **/ -BSON.BSON_BINARY_SUBTYPE_MD5 = 4; -/** - * Binary User Defined Type - * - * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED - **/ -BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; - -// BSON MAX VALUES -BSON.BSON_INT32_MAX = 0x7fffffff; -BSON.BSON_INT32_MIN = -0x80000000; - -BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; -BSON.BSON_INT64_MIN = -Math.pow(2, 63); - -// JS MAX PRECISE VALUES -BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. -BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. - -// Internal long versions -// var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. -// var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. - -module.exports = serializeInto; diff --git a/scripts/2.5/node_modules/bson/lib/bson/parser/utils.js b/scripts/2.5/node_modules/bson/lib/bson/parser/utils.js deleted file mode 100644 index 6faa4396..00000000 --- a/scripts/2.5/node_modules/bson/lib/bson/parser/utils.js +++ /dev/null @@ -1,28 +0,0 @@ -'use strict'; - -/** - * Normalizes our expected stringified form of a function across versions of node - * @param {Function} fn The function to stringify - */ -function normalizedFunctionString(fn) { - return fn.toString().replace(/function *\(/, 'function ('); -} - -function newBuffer(item, encoding) { - return new Buffer(item, encoding); -} - -function allocBuffer() { - return Buffer.alloc.apply(Buffer, arguments); -} - -function toBuffer() { - return Buffer.from.apply(Buffer, arguments); -} - -module.exports = { - normalizedFunctionString: normalizedFunctionString, - allocBuffer: typeof Buffer.alloc === 'function' ? allocBuffer : newBuffer, - toBuffer: typeof Buffer.from === 'function' ? toBuffer : newBuffer -}; - diff --git a/scripts/2.5/node_modules/bson/lib/bson/regexp.js b/scripts/2.5/node_modules/bson/lib/bson/regexp.js deleted file mode 100644 index 108f0166..00000000 --- a/scripts/2.5/node_modules/bson/lib/bson/regexp.js +++ /dev/null @@ -1,33 +0,0 @@ -/** - * A class representation of the BSON RegExp type. - * - * @class - * @return {BSONRegExp} A MinKey instance - */ -function BSONRegExp(pattern, options) { - if (!(this instanceof BSONRegExp)) return new BSONRegExp(); - - // Execute - this._bsontype = 'BSONRegExp'; - this.pattern = pattern || ''; - this.options = options || ''; - - // Validate options - for (var i = 0; i < this.options.length; i++) { - if ( - !( - this.options[i] === 'i' || - this.options[i] === 'm' || - this.options[i] === 'x' || - this.options[i] === 'l' || - this.options[i] === 's' || - this.options[i] === 'u' - ) - ) { - throw new Error('the regular expression options [' + this.options[i] + '] is not supported'); - } - } -} - -module.exports = BSONRegExp; -module.exports.BSONRegExp = BSONRegExp; diff --git a/scripts/2.5/node_modules/bson/lib/bson/symbol.js b/scripts/2.5/node_modules/bson/lib/bson/symbol.js deleted file mode 100644 index ba20cabe..00000000 --- a/scripts/2.5/node_modules/bson/lib/bson/symbol.js +++ /dev/null @@ -1,50 +0,0 @@ -// Custom inspect property name / symbol. -var inspect = Buffer ? require('util').inspect.custom || 'inspect' : 'inspect'; - -/** - * A class representation of the BSON Symbol type. - * - * @class - * @deprecated - * @param {string} value the string representing the symbol. - * @return {Symbol} - */ -function Symbol(value) { - if (!(this instanceof Symbol)) return new Symbol(value); - this._bsontype = 'Symbol'; - this.value = value; -} - -/** - * Access the wrapped string value. - * - * @method - * @return {String} returns the wrapped string. - */ -Symbol.prototype.valueOf = function() { - return this.value; -}; - -/** - * @ignore - */ -Symbol.prototype.toString = function() { - return this.value; -}; - -/** - * @ignore - */ -Symbol.prototype[inspect] = function() { - return this.value; -}; - -/** - * @ignore - */ -Symbol.prototype.toJSON = function() { - return this.value; -}; - -module.exports = Symbol; -module.exports.Symbol = Symbol; diff --git a/scripts/2.5/node_modules/bson/lib/bson/timestamp.js b/scripts/2.5/node_modules/bson/lib/bson/timestamp.js deleted file mode 100644 index dc61a6cc..00000000 --- a/scripts/2.5/node_modules/bson/lib/bson/timestamp.js +++ /dev/null @@ -1,854 +0,0 @@ -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// Copyright 2009 Google Inc. All Rights Reserved - -/** - * This type is for INTERNAL use in MongoDB only and should not be used in applications. - * The appropriate corresponding type is the JavaScript Date type. - * - * Defines a Timestamp class for representing a 64-bit two's-complement - * integer value, which faithfully simulates the behavior of a Java "Timestamp". This - * implementation is derived from TimestampLib in GWT. - * - * Constructs a 64-bit two's-complement integer, given its low and high 32-bit - * values as *signed* integers. See the from* functions below for more - * convenient ways of constructing Timestamps. - * - * The internal representation of a Timestamp is the two given signed, 32-bit values. - * We use 32-bit pieces because these are the size of integers on which - * Javascript performs bit-operations. For operations like addition and - * multiplication, we split each number into 16-bit pieces, which can easily be - * multiplied within Javascript's floating-point representation without overflow - * or change in sign. - * - * In the algorithms below, we frequently reduce the negative case to the - * positive case by negating the input(s) and then post-processing the result. - * Note that we must ALWAYS check specially whether those values are MIN_VALUE - * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as - * a positive number, it overflows back into a negative). Not handling this - * case would often result in infinite recursion. - * - * @class - * @param {number} low the low (signed) 32 bits of the Timestamp. - * @param {number} high the high (signed) 32 bits of the Timestamp. - */ -function Timestamp(low, high) { - if (!(this instanceof Timestamp)) return new Timestamp(low, high); - this._bsontype = 'Timestamp'; - /** - * @type {number} - * @ignore - */ - this.low_ = low | 0; // force into 32 signed bits. - - /** - * @type {number} - * @ignore - */ - this.high_ = high | 0; // force into 32 signed bits. -} - -/** - * Return the int value. - * - * @return {number} the value, assuming it is a 32-bit integer. - */ -Timestamp.prototype.toInt = function() { - return this.low_; -}; - -/** - * Return the Number value. - * - * @method - * @return {number} the closest floating-point representation to this value. - */ -Timestamp.prototype.toNumber = function() { - return this.high_ * Timestamp.TWO_PWR_32_DBL_ + this.getLowBitsUnsigned(); -}; - -/** - * Return the JSON value. - * - * @method - * @return {string} the JSON representation. - */ -Timestamp.prototype.toJSON = function() { - return this.toString(); -}; - -/** - * Return the String value. - * - * @method - * @param {number} [opt_radix] the radix in which the text should be written. - * @return {string} the textual representation of this value. - */ -Timestamp.prototype.toString = function(opt_radix) { - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (this.isZero()) { - return '0'; - } - - if (this.isNegative()) { - if (this.equals(Timestamp.MIN_VALUE)) { - // We need to change the Timestamp value before it can be negated, so we remove - // the bottom-most digit in this base and then recurse to do the rest. - var radixTimestamp = Timestamp.fromNumber(radix); - var div = this.div(radixTimestamp); - var rem = div.multiply(radixTimestamp).subtract(this); - return div.toString(radix) + rem.toInt().toString(radix); - } else { - return '-' + this.negate().toString(radix); - } - } - - // Do several (6) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Timestamp.fromNumber(Math.pow(radix, 6)); - - rem = this; - var result = ''; - - while (!rem.isZero()) { - var remDiv = rem.div(radixToPower); - var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); - var digits = intval.toString(radix); - - rem = remDiv; - if (rem.isZero()) { - return digits + result; - } else { - while (digits.length < 6) { - digits = '0' + digits; - } - result = '' + digits + result; - } - } -}; - -/** - * Return the high 32-bits value. - * - * @method - * @return {number} the high 32-bits as a signed value. - */ -Timestamp.prototype.getHighBits = function() { - return this.high_; -}; - -/** - * Return the low 32-bits value. - * - * @method - * @return {number} the low 32-bits as a signed value. - */ -Timestamp.prototype.getLowBits = function() { - return this.low_; -}; - -/** - * Return the low unsigned 32-bits value. - * - * @method - * @return {number} the low 32-bits as an unsigned value. - */ -Timestamp.prototype.getLowBitsUnsigned = function() { - return this.low_ >= 0 ? this.low_ : Timestamp.TWO_PWR_32_DBL_ + this.low_; -}; - -/** - * Returns the number of bits needed to represent the absolute value of this Timestamp. - * - * @method - * @return {number} Returns the number of bits needed to represent the absolute value of this Timestamp. - */ -Timestamp.prototype.getNumBitsAbs = function() { - if (this.isNegative()) { - if (this.equals(Timestamp.MIN_VALUE)) { - return 64; - } else { - return this.negate().getNumBitsAbs(); - } - } else { - var val = this.high_ !== 0 ? this.high_ : this.low_; - for (var bit = 31; bit > 0; bit--) { - if ((val & (1 << bit)) !== 0) { - break; - } - } - return this.high_ !== 0 ? bit + 33 : bit + 1; - } -}; - -/** - * Return whether this value is zero. - * - * @method - * @return {boolean} whether this value is zero. - */ -Timestamp.prototype.isZero = function() { - return this.high_ === 0 && this.low_ === 0; -}; - -/** - * Return whether this value is negative. - * - * @method - * @return {boolean} whether this value is negative. - */ -Timestamp.prototype.isNegative = function() { - return this.high_ < 0; -}; - -/** - * Return whether this value is odd. - * - * @method - * @return {boolean} whether this value is odd. - */ -Timestamp.prototype.isOdd = function() { - return (this.low_ & 1) === 1; -}; - -/** - * Return whether this Timestamp equals the other - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp equals the other - */ -Timestamp.prototype.equals = function(other) { - return this.high_ === other.high_ && this.low_ === other.low_; -}; - -/** - * Return whether this Timestamp does not equal the other. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp does not equal the other. - */ -Timestamp.prototype.notEquals = function(other) { - return this.high_ !== other.high_ || this.low_ !== other.low_; -}; - -/** - * Return whether this Timestamp is less than the other. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp is less than the other. - */ -Timestamp.prototype.lessThan = function(other) { - return this.compare(other) < 0; -}; - -/** - * Return whether this Timestamp is less than or equal to the other. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp is less than or equal to the other. - */ -Timestamp.prototype.lessThanOrEqual = function(other) { - return this.compare(other) <= 0; -}; - -/** - * Return whether this Timestamp is greater than the other. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp is greater than the other. - */ -Timestamp.prototype.greaterThan = function(other) { - return this.compare(other) > 0; -}; - -/** - * Return whether this Timestamp is greater than or equal to the other. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp is greater than or equal to the other. - */ -Timestamp.prototype.greaterThanOrEqual = function(other) { - return this.compare(other) >= 0; -}; - -/** - * Compares this Timestamp with the given one. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. - */ -Timestamp.prototype.compare = function(other) { - if (this.equals(other)) { - return 0; - } - - var thisNeg = this.isNegative(); - var otherNeg = other.isNegative(); - if (thisNeg && !otherNeg) { - return -1; - } - if (!thisNeg && otherNeg) { - return 1; - } - - // at this point, the signs are the same, so subtraction will not overflow - if (this.subtract(other).isNegative()) { - return -1; - } else { - return 1; - } -}; - -/** - * The negation of this value. - * - * @method - * @return {Timestamp} the negation of this value. - */ -Timestamp.prototype.negate = function() { - if (this.equals(Timestamp.MIN_VALUE)) { - return Timestamp.MIN_VALUE; - } else { - return this.not().add(Timestamp.ONE); - } -}; - -/** - * Returns the sum of this and the given Timestamp. - * - * @method - * @param {Timestamp} other Timestamp to add to this one. - * @return {Timestamp} the sum of this and the given Timestamp. - */ -Timestamp.prototype.add = function(other) { - // Divide each number into 4 chunks of 16 bits, and then sum the chunks. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xffff; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xffff; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xffff; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xffff; - - var c48 = 0, - c32 = 0, - c16 = 0, - c00 = 0; - c00 += a00 + b00; - c16 += c00 >>> 16; - c00 &= 0xffff; - c16 += a16 + b16; - c32 += c16 >>> 16; - c16 &= 0xffff; - c32 += a32 + b32; - c48 += c32 >>> 16; - c32 &= 0xffff; - c48 += a48 + b48; - c48 &= 0xffff; - return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32); -}; - -/** - * Returns the difference of this and the given Timestamp. - * - * @method - * @param {Timestamp} other Timestamp to subtract from this. - * @return {Timestamp} the difference of this and the given Timestamp. - */ -Timestamp.prototype.subtract = function(other) { - return this.add(other.negate()); -}; - -/** - * Returns the product of this and the given Timestamp. - * - * @method - * @param {Timestamp} other Timestamp to multiply with this. - * @return {Timestamp} the product of this and the other. - */ -Timestamp.prototype.multiply = function(other) { - if (this.isZero()) { - return Timestamp.ZERO; - } else if (other.isZero()) { - return Timestamp.ZERO; - } - - if (this.equals(Timestamp.MIN_VALUE)) { - return other.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; - } else if (other.equals(Timestamp.MIN_VALUE)) { - return this.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().multiply(other.negate()); - } else { - return this.negate() - .multiply(other) - .negate(); - } - } else if (other.isNegative()) { - return this.multiply(other.negate()).negate(); - } - - // If both Timestamps are small, use float multiplication - if (this.lessThan(Timestamp.TWO_PWR_24_) && other.lessThan(Timestamp.TWO_PWR_24_)) { - return Timestamp.fromNumber(this.toNumber() * other.toNumber()); - } - - // Divide each Timestamp into 4 chunks of 16 bits, and then add up 4x4 products. - // We can skip products that would overflow. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xffff; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xffff; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xffff; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xffff; - - var c48 = 0, - c32 = 0, - c16 = 0, - c00 = 0; - c00 += a00 * b00; - c16 += c00 >>> 16; - c00 &= 0xffff; - c16 += a16 * b00; - c32 += c16 >>> 16; - c16 &= 0xffff; - c16 += a00 * b16; - c32 += c16 >>> 16; - c16 &= 0xffff; - c32 += a32 * b00; - c48 += c32 >>> 16; - c32 &= 0xffff; - c32 += a16 * b16; - c48 += c32 >>> 16; - c32 &= 0xffff; - c32 += a00 * b32; - c48 += c32 >>> 16; - c32 &= 0xffff; - c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; - c48 &= 0xffff; - return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32); -}; - -/** - * Returns this Timestamp divided by the given one. - * - * @method - * @param {Timestamp} other Timestamp by which to divide. - * @return {Timestamp} this Timestamp divided by the given one. - */ -Timestamp.prototype.div = function(other) { - if (other.isZero()) { - throw Error('division by zero'); - } else if (this.isZero()) { - return Timestamp.ZERO; - } - - if (this.equals(Timestamp.MIN_VALUE)) { - if (other.equals(Timestamp.ONE) || other.equals(Timestamp.NEG_ONE)) { - return Timestamp.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE - } else if (other.equals(Timestamp.MIN_VALUE)) { - return Timestamp.ONE; - } else { - // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. - var halfThis = this.shiftRight(1); - var approx = halfThis.div(other).shiftLeft(1); - if (approx.equals(Timestamp.ZERO)) { - return other.isNegative() ? Timestamp.ONE : Timestamp.NEG_ONE; - } else { - var rem = this.subtract(other.multiply(approx)); - var result = approx.add(rem.div(other)); - return result; - } - } - } else if (other.equals(Timestamp.MIN_VALUE)) { - return Timestamp.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().div(other.negate()); - } else { - return this.negate() - .div(other) - .negate(); - } - } else if (other.isNegative()) { - return this.div(other.negate()).negate(); - } - - // Repeat the following until the remainder is less than other: find a - // floating-point that approximates remainder / other *from below*, add this - // into the result, and subtract it from the remainder. It is critical that - // the approximate value is less than or equal to the real value so that the - // remainder never becomes negative. - var res = Timestamp.ZERO; - rem = this; - while (rem.greaterThanOrEqual(other)) { - // Approximate the result of division. This may be a little greater or - // smaller than the actual value. - approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); - - // We will tweak the approximate result by changing it in the 48-th digit or - // the smallest non-fractional digit, whichever is larger. - var log2 = Math.ceil(Math.log(approx) / Math.LN2); - var delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48); - - // Decrease the approximation until it is smaller than the remainder. Note - // that if it is too large, the product overflows and is negative. - var approxRes = Timestamp.fromNumber(approx); - var approxRem = approxRes.multiply(other); - while (approxRem.isNegative() || approxRem.greaterThan(rem)) { - approx -= delta; - approxRes = Timestamp.fromNumber(approx); - approxRem = approxRes.multiply(other); - } - - // We know the answer can't be zero... and actually, zero would cause - // infinite recursion since we would make no progress. - if (approxRes.isZero()) { - approxRes = Timestamp.ONE; - } - - res = res.add(approxRes); - rem = rem.subtract(approxRem); - } - return res; -}; - -/** - * Returns this Timestamp modulo the given one. - * - * @method - * @param {Timestamp} other Timestamp by which to mod. - * @return {Timestamp} this Timestamp modulo the given one. - */ -Timestamp.prototype.modulo = function(other) { - return this.subtract(this.div(other).multiply(other)); -}; - -/** - * The bitwise-NOT of this value. - * - * @method - * @return {Timestamp} the bitwise-NOT of this value. - */ -Timestamp.prototype.not = function() { - return Timestamp.fromBits(~this.low_, ~this.high_); -}; - -/** - * Returns the bitwise-AND of this Timestamp and the given one. - * - * @method - * @param {Timestamp} other the Timestamp with which to AND. - * @return {Timestamp} the bitwise-AND of this and the other. - */ -Timestamp.prototype.and = function(other) { - return Timestamp.fromBits(this.low_ & other.low_, this.high_ & other.high_); -}; - -/** - * Returns the bitwise-OR of this Timestamp and the given one. - * - * @method - * @param {Timestamp} other the Timestamp with which to OR. - * @return {Timestamp} the bitwise-OR of this and the other. - */ -Timestamp.prototype.or = function(other) { - return Timestamp.fromBits(this.low_ | other.low_, this.high_ | other.high_); -}; - -/** - * Returns the bitwise-XOR of this Timestamp and the given one. - * - * @method - * @param {Timestamp} other the Timestamp with which to XOR. - * @return {Timestamp} the bitwise-XOR of this and the other. - */ -Timestamp.prototype.xor = function(other) { - return Timestamp.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); -}; - -/** - * Returns this Timestamp with bits shifted to the left by the given amount. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Timestamp} this shifted to the left by the given amount. - */ -Timestamp.prototype.shiftLeft = function(numBits) { - numBits &= 63; - if (numBits === 0) { - return this; - } else { - var low = this.low_; - if (numBits < 32) { - var high = this.high_; - return Timestamp.fromBits(low << numBits, (high << numBits) | (low >>> (32 - numBits))); - } else { - return Timestamp.fromBits(0, low << (numBits - 32)); - } - } -}; - -/** - * Returns this Timestamp with bits shifted to the right by the given amount. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Timestamp} this shifted to the right by the given amount. - */ -Timestamp.prototype.shiftRight = function(numBits) { - numBits &= 63; - if (numBits === 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Timestamp.fromBits((low >>> numBits) | (high << (32 - numBits)), high >> numBits); - } else { - return Timestamp.fromBits(high >> (numBits - 32), high >= 0 ? 0 : -1); - } - } -}; - -/** - * Returns this Timestamp with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Timestamp} this shifted to the right by the given amount, with zeros placed into the new leading bits. - */ -Timestamp.prototype.shiftRightUnsigned = function(numBits) { - numBits &= 63; - if (numBits === 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Timestamp.fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits); - } else if (numBits === 32) { - return Timestamp.fromBits(high, 0); - } else { - return Timestamp.fromBits(high >>> (numBits - 32), 0); - } - } -}; - -/** - * Returns a Timestamp representing the given (32-bit) integer value. - * - * @method - * @param {number} value the 32-bit integer in question. - * @return {Timestamp} the corresponding Timestamp value. - */ -Timestamp.fromInt = function(value) { - if (-128 <= value && value < 128) { - var cachedObj = Timestamp.INT_CACHE_[value]; - if (cachedObj) { - return cachedObj; - } - } - - var obj = new Timestamp(value | 0, value < 0 ? -1 : 0); - if (-128 <= value && value < 128) { - Timestamp.INT_CACHE_[value] = obj; - } - return obj; -}; - -/** - * Returns a Timestamp representing the given value, provided that it is a finite number. Otherwise, zero is returned. - * - * @method - * @param {number} value the number in question. - * @return {Timestamp} the corresponding Timestamp value. - */ -Timestamp.fromNumber = function(value) { - if (isNaN(value) || !isFinite(value)) { - return Timestamp.ZERO; - } else if (value <= -Timestamp.TWO_PWR_63_DBL_) { - return Timestamp.MIN_VALUE; - } else if (value + 1 >= Timestamp.TWO_PWR_63_DBL_) { - return Timestamp.MAX_VALUE; - } else if (value < 0) { - return Timestamp.fromNumber(-value).negate(); - } else { - return new Timestamp( - (value % Timestamp.TWO_PWR_32_DBL_) | 0, - (value / Timestamp.TWO_PWR_32_DBL_) | 0 - ); - } -}; - -/** - * Returns a Timestamp representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. - * - * @method - * @param {number} lowBits the low 32-bits. - * @param {number} highBits the high 32-bits. - * @return {Timestamp} the corresponding Timestamp value. - */ -Timestamp.fromBits = function(lowBits, highBits) { - return new Timestamp(lowBits, highBits); -}; - -/** - * Returns a Timestamp representation of the given string, written using the given radix. - * - * @method - * @param {string} str the textual representation of the Timestamp. - * @param {number} opt_radix the radix in which the text is written. - * @return {Timestamp} the corresponding Timestamp value. - */ -Timestamp.fromString = function(str, opt_radix) { - if (str.length === 0) { - throw Error('number format error: empty string'); - } - - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (str.charAt(0) === '-') { - return Timestamp.fromString(str.substring(1), radix).negate(); - } else if (str.indexOf('-') >= 0) { - throw Error('number format error: interior "-" character: ' + str); - } - - // Do several (8) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Timestamp.fromNumber(Math.pow(radix, 8)); - - var result = Timestamp.ZERO; - for (var i = 0; i < str.length; i += 8) { - var size = Math.min(8, str.length - i); - var value = parseInt(str.substring(i, i + size), radix); - if (size < 8) { - var power = Timestamp.fromNumber(Math.pow(radix, size)); - result = result.multiply(power).add(Timestamp.fromNumber(value)); - } else { - result = result.multiply(radixToPower); - result = result.add(Timestamp.fromNumber(value)); - } - } - return result; -}; - -// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the -// from* methods on which they depend. - -/** - * A cache of the Timestamp representations of small integer values. - * @type {Object} - * @ignore - */ -Timestamp.INT_CACHE_ = {}; - -// NOTE: the compiler should inline these constant values below and then remove -// these variables, so there should be no runtime penalty for these. - -/** - * Number used repeated below in calculations. This must appear before the - * first call to any from* function below. - * @type {number} - * @ignore - */ -Timestamp.TWO_PWR_16_DBL_ = 1 << 16; - -/** - * @type {number} - * @ignore - */ -Timestamp.TWO_PWR_24_DBL_ = 1 << 24; - -/** - * @type {number} - * @ignore - */ -Timestamp.TWO_PWR_32_DBL_ = Timestamp.TWO_PWR_16_DBL_ * Timestamp.TWO_PWR_16_DBL_; - -/** - * @type {number} - * @ignore - */ -Timestamp.TWO_PWR_31_DBL_ = Timestamp.TWO_PWR_32_DBL_ / 2; - -/** - * @type {number} - * @ignore - */ -Timestamp.TWO_PWR_48_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_16_DBL_; - -/** - * @type {number} - * @ignore - */ -Timestamp.TWO_PWR_64_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_32_DBL_; - -/** - * @type {number} - * @ignore - */ -Timestamp.TWO_PWR_63_DBL_ = Timestamp.TWO_PWR_64_DBL_ / 2; - -/** @type {Timestamp} */ -Timestamp.ZERO = Timestamp.fromInt(0); - -/** @type {Timestamp} */ -Timestamp.ONE = Timestamp.fromInt(1); - -/** @type {Timestamp} */ -Timestamp.NEG_ONE = Timestamp.fromInt(-1); - -/** @type {Timestamp} */ -Timestamp.MAX_VALUE = Timestamp.fromBits(0xffffffff | 0, 0x7fffffff | 0); - -/** @type {Timestamp} */ -Timestamp.MIN_VALUE = Timestamp.fromBits(0, 0x80000000 | 0); - -/** - * @type {Timestamp} - * @ignore - */ -Timestamp.TWO_PWR_24_ = Timestamp.fromInt(1 << 24); - -/** - * Expose. - */ -module.exports = Timestamp; -module.exports.Timestamp = Timestamp; diff --git a/scripts/2.5/node_modules/bson/package.json b/scripts/2.5/node_modules/bson/package.json deleted file mode 100644 index fe065124..00000000 --- a/scripts/2.5/node_modules/bson/package.json +++ /dev/null @@ -1,87 +0,0 @@ -{ - "_from": "bson@^1.1.1", - "_id": "bson@1.1.1", - "_inBundle": false, - "_integrity": "sha512-jCGVYLoYMHDkOsbwJZBCqwMHyH4c+wzgI9hG7Z6SZJRXWr+x58pdIbm2i9a/jFGCkRJqRUr8eoI7lDWa0hTkxg==", - "_location": "/bson", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "bson@^1.1.1", - "name": "bson", - "escapedName": "bson", - "rawSpec": "^1.1.1", - "saveSpec": null, - "fetchSpec": "^1.1.1" - }, - "_requiredBy": [ - "/mongodb" - ], - "_resolved": "https://registry.npmjs.org/bson/-/bson-1.1.1.tgz", - "_shasum": "4330f5e99104c4e751e7351859e2d408279f2f13", - "_spec": "bson@^1.1.1", - "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/2.5/node_modules/mongodb", - "author": { - "name": "Christian Amor Kvalheim", - "email": "christkv@gmail.com" - }, - "browser": "lib/bson/bson.js", - "bugs": { - "url": "https://github.com/mongodb/js-bson/issues" - }, - "bundleDependencies": false, - "config": { - "native": false - }, - "contributors": [], - "deprecated": false, - "description": "A bson parser for node.js and the browser", - "devDependencies": { - "babel-core": "^6.14.0", - "babel-loader": "^6.2.5", - "babel-polyfill": "^6.13.0", - "babel-preset-es2015": "^6.14.0", - "babel-preset-stage-0": "^6.5.0", - "babel-register": "^6.14.0", - "benchmark": "1.0.0", - "colors": "1.1.0", - "conventional-changelog-cli": "^1.3.5", - "nodeunit": "0.9.0", - "webpack": "^1.13.2", - "webpack-polyfills-plugin": "0.0.9" - }, - "directories": { - "lib": "./lib/bson" - }, - "engines": { - "node": ">=0.6.19" - }, - "files": [ - "lib", - "index.js", - "browser_build", - "bower.json" - ], - "homepage": "https://github.com/mongodb/js-bson#readme", - "keywords": [ - "mongodb", - "bson", - "parser" - ], - "license": "Apache-2.0", - "main": "./index", - "name": "bson", - "repository": { - "type": "git", - "url": "git+https://github.com/mongodb/js-bson.git" - }, - "scripts": { - "build": "webpack --config ./webpack.dist.config.js", - "changelog": "conventional-changelog -p angular -i HISTORY.md -s", - "format": "prettier --print-width 100 --tab-width 2 --single-quote --write 'test/**/*.js' 'lib/**/*.js'", - "lint": "eslint lib test", - "test": "nodeunit ./test/node" - }, - "version": "1.1.1" -} diff --git a/scripts/2.5/node_modules/define-properties/.editorconfig b/scripts/2.5/node_modules/define-properties/.editorconfig deleted file mode 100644 index eaa21416..00000000 --- a/scripts/2.5/node_modules/define-properties/.editorconfig +++ /dev/null @@ -1,13 +0,0 @@ -root = true - -[*] -indent_style = tab; -insert_final_newline = true; -quote_type = auto; -space_after_anonymous_functions = true; -space_after_control_statements = true; -spaces_around_operators = true; -trim_trailing_whitespace = true; -spaces_in_brackets = false; -end_of_line = lf; - diff --git a/scripts/2.5/node_modules/define-properties/.eslintrc b/scripts/2.5/node_modules/define-properties/.eslintrc deleted file mode 100644 index db992d7a..00000000 --- a/scripts/2.5/node_modules/define-properties/.eslintrc +++ /dev/null @@ -1,12 +0,0 @@ -{ - "root": true, - - "extends": "@ljharb", - - "rules": { - "id-length": [2, { "min": 1, "max": 35 }], - "max-lines-per-function": [2, 100], - "max-params": [2, 4], - "max-statements": [2, 13] - } -} diff --git a/scripts/2.5/node_modules/define-properties/.jscs.json b/scripts/2.5/node_modules/define-properties/.jscs.json deleted file mode 100644 index 6f2d7f9f..00000000 --- a/scripts/2.5/node_modules/define-properties/.jscs.json +++ /dev/null @@ -1,175 +0,0 @@ -{ - "es3": true, - - "additionalRules": [], - - "requireSemicolons": true, - - "disallowMultipleSpaces": true, - - "disallowIdentifierNames": [], - - "requireCurlyBraces": { - "allExcept": [], - "keywords": ["if", "else", "for", "while", "do", "try", "catch"] - }, - - "requireSpaceAfterKeywords": ["if", "else", "for", "while", "do", "switch", "return", "try", "catch", "function"], - - "disallowSpaceAfterKeywords": [], - - "disallowSpaceBeforeComma": true, - "disallowSpaceAfterComma": false, - "disallowSpaceBeforeSemicolon": true, - - "disallowNodeTypes": [ - "DebuggerStatement", - "LabeledStatement", - "SwitchCase", - "SwitchStatement", - "WithStatement" - ], - - "requireObjectKeysOnNewLine": { "allExcept": ["sameLine"] }, - - "requireSpacesInAnonymousFunctionExpression": { "beforeOpeningRoundBrace": true, "beforeOpeningCurlyBrace": true }, - "requireSpacesInNamedFunctionExpression": { "beforeOpeningCurlyBrace": true }, - "disallowSpacesInNamedFunctionExpression": { "beforeOpeningRoundBrace": true }, - "requireSpacesInFunctionDeclaration": { "beforeOpeningCurlyBrace": true }, - "disallowSpacesInFunctionDeclaration": { "beforeOpeningRoundBrace": true }, - - "requireSpaceBetweenArguments": true, - - "disallowSpacesInsideParentheses": true, - - "disallowSpacesInsideArrayBrackets": true, - - "disallowQuotedKeysInObjects": { "allExcept": ["reserved"] }, - - "disallowSpaceAfterObjectKeys": true, - - "requireCommaBeforeLineBreak": true, - - "disallowSpaceAfterPrefixUnaryOperators": ["++", "--", "+", "-", "~", "!"], - "requireSpaceAfterPrefixUnaryOperators": [], - - "disallowSpaceBeforePostfixUnaryOperators": ["++", "--"], - "requireSpaceBeforePostfixUnaryOperators": [], - - "disallowSpaceBeforeBinaryOperators": [], - "requireSpaceBeforeBinaryOperators": ["+", "-", "/", "*", "=", "==", "===", "!=", "!=="], - - "requireSpaceAfterBinaryOperators": ["+", "-", "/", "*", "=", "==", "===", "!=", "!=="], - "disallowSpaceAfterBinaryOperators": [], - - "disallowImplicitTypeConversion": ["binary", "string"], - - "disallowKeywords": ["with", "eval"], - - "requireKeywordsOnNewLine": [], - "disallowKeywordsOnNewLine": ["else"], - - "requireLineFeedAtFileEnd": true, - - "disallowTrailingWhitespace": true, - - "disallowTrailingComma": true, - - "excludeFiles": ["node_modules/**", "vendor/**"], - - "disallowMultipleLineStrings": true, - - "requireDotNotation": { "allExcept": ["keywords"] }, - - "requireParenthesesAroundIIFE": true, - - "validateLineBreaks": "LF", - - "validateQuoteMarks": { - "escape": true, - "mark": "'" - }, - - "disallowOperatorBeforeLineBreak": [], - - "requireSpaceBeforeKeywords": [ - "do", - "for", - "if", - "else", - "switch", - "case", - "try", - "catch", - "finally", - "while", - "with", - "return" - ], - - "validateAlignedFunctionParameters": { - "lineBreakAfterOpeningBraces": true, - "lineBreakBeforeClosingBraces": true - }, - - "requirePaddingNewLinesBeforeExport": true, - - "validateNewlineAfterArrayElements": { - "maximum": 3 - }, - - "requirePaddingNewLinesAfterUseStrict": true, - - "disallowArrowFunctions": true, - - "disallowMultiLineTernary": true, - - "validateOrderInObjectKeys": "asc-insensitive", - - "disallowIdenticalDestructuringNames": true, - - "disallowNestedTernaries": { "maxLevel": 1 }, - - "requireSpaceAfterComma": { "allExcept": ["trailing"] }, - "requireAlignedMultilineParams": false, - - "requireSpacesInGenerator": { - "afterStar": true - }, - - "disallowSpacesInGenerator": { - "beforeStar": true - }, - - "disallowVar": false, - - "requireArrayDestructuring": false, - - "requireEnhancedObjectLiterals": false, - - "requireObjectDestructuring": false, - - "requireEarlyReturn": false, - - "requireCapitalizedConstructorsNew": { - "allExcept": ["Function", "String", "Object", "Symbol", "Number", "Date", "RegExp", "Error", "Boolean", "Array"] - }, - - "requireImportAlphabetized": false, - - "requireSpaceBeforeObjectValues": true, - "requireSpaceBeforeDestructuredValues": true, - - "disallowSpacesInsideTemplateStringPlaceholders": true, - - "disallowArrayDestructuringReturn": false, - - "requireNewlineBeforeSingleStatementsInIf": false, - - "disallowUnusedVariables": true, - - "requireSpacesInsideImportedObjectBraces": true, - - "requireUseStrict": true -} - diff --git a/scripts/2.5/node_modules/define-properties/.travis.yml b/scripts/2.5/node_modules/define-properties/.travis.yml deleted file mode 100644 index ec72d5f3..00000000 --- a/scripts/2.5/node_modules/define-properties/.travis.yml +++ /dev/null @@ -1,233 +0,0 @@ -language: node_js -os: - - linux -node_js: - - "10.8" - - "9.11" - - "8.11" - - "7.10" - - "6.14" - - "5.12" - - "4.9" - - "iojs-v3.3" - - "iojs-v2.5" - - "iojs-v1.8" - - "0.12" - - "0.10" - - "0.8" -before_install: - - 'case "${TRAVIS_NODE_VERSION}" in 0.*) export NPM_CONFIG_STRICT_SSL=false ;; esac' - - 'nvm install-latest-npm' -install: - - 'if [ "${TRAVIS_NODE_VERSION}" = "0.6" ] || [ "${TRAVIS_NODE_VERSION}" = "0.9" ]; then nvm install --latest-npm 0.8 && npm install && nvm use "${TRAVIS_NODE_VERSION}"; else npm install; fi;' -script: - - 'if [ -n "${PRETEST-}" ]; then npm run pretest ; fi' - - 'if [ -n "${POSTTEST-}" ]; then npm run posttest ; fi' - - 'if [ -n "${COVERAGE-}" ]; then npm run coverage ; fi' - - 'if [ -n "${TEST-}" ]; then npm run tests-only ; fi' -sudo: false -env: - - TEST=true -matrix: - fast_finish: true - include: - - node_js: "lts/*" - env: PRETEST=true - - node_js: "lts/*" - env: POSTTEST=true - - node_js: "4" - env: COVERAGE=true - - node_js: "10.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.10" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.10" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.13" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.12" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.11" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.10" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.11" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.10" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v3.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v3.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v3.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "0.11" - env: TEST=true ALLOW_FAILURE=true - - node_js: "0.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "0.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "0.4" - env: TEST=true ALLOW_FAILURE=true - allow_failures: - - os: osx - - env: TEST=true ALLOW_FAILURE=true - - env: COVERAGE=true diff --git a/scripts/2.5/node_modules/define-properties/CHANGELOG.md b/scripts/2.5/node_modules/define-properties/CHANGELOG.md deleted file mode 100644 index 5cad1e26..00000000 --- a/scripts/2.5/node_modules/define-properties/CHANGELOG.md +++ /dev/null @@ -1,44 +0,0 @@ -1.1.3 / 2018-08-14 -================= - * [Refactor] use a for loop instead of `foreach` to make for smaller bundle sizes - * [Robustness] cache `Array.prototype.concat` and `Object.defineProperty` - * [Deps] update `object-keys` - * [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `nsp`, `tape`, `jscs`; remove unused eccheck script + dep - * [Tests] use pretest/posttest for linting/security - * [Tests] fix npm upgrades on older nodes - -1.1.2 / 2015-10-14 -================= - * [Docs] Switch from vb.teelaun.ch to versionbadg.es for the npm version badge SVG - * [Deps] Update `object-keys` - * [Dev Deps] update `jscs`, `tape`, `eslint`, `@ljharb/eslint-config`, `nsp` - * [Tests] up to `io.js` `v3.3`, `node` `v4.2` - -1.1.1 / 2015-07-21 -================= - * [Deps] Update `object-keys` - * [Dev Deps] Update `tape`, `eslint` - * [Tests] Test on `io.js` `v2.4` - -1.1.0 / 2015-07-01 -================= - * [New] Add support for symbol-valued properties. - * [Dev Deps] Update `nsp`, `eslint` - * [Tests] Test up to `io.js` `v2.3` - -1.0.3 / 2015-05-30 -================= - * Using a more reliable check for supported property descriptors. - -1.0.2 / 2015-05-23 -================= - * Test up to `io.js` `v2.0` - * Update `tape`, `jscs`, `nsp`, `eslint`, `object-keys`, `editorconfig-tools`, `covert` - -1.0.1 / 2015-01-06 -================= - * Update `object-keys` to fix ES3 support - -1.0.0 / 2015-01-04 -================= - * v1.0.0 diff --git a/scripts/2.5/node_modules/define-properties/LICENSE b/scripts/2.5/node_modules/define-properties/LICENSE deleted file mode 100644 index 8c271c14..00000000 --- a/scripts/2.5/node_modules/define-properties/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (C) 2015 Jordan Harband - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. \ No newline at end of file diff --git a/scripts/2.5/node_modules/define-properties/README.md b/scripts/2.5/node_modules/define-properties/README.md deleted file mode 100644 index 33b6111f..00000000 --- a/scripts/2.5/node_modules/define-properties/README.md +++ /dev/null @@ -1,86 +0,0 @@ -#define-properties [![Version Badge][npm-version-svg]][package-url] - -[![Build Status][travis-svg]][travis-url] -[![dependency status][deps-svg]][deps-url] -[![dev dependency status][dev-deps-svg]][dev-deps-url] -[![License][license-image]][license-url] -[![Downloads][downloads-image]][downloads-url] - -[![npm badge][npm-badge-png]][package-url] - -[![browser support][testling-svg]][testling-url] - -Define multiple non-enumerable properties at once. Uses `Object.defineProperty` when available; falls back to standard assignment in older engines. -Existing properties are not overridden. Accepts a map of property names to a predicate that, when true, force-overrides. - -## Example - -```js -var define = require('define-properties'); -var assert = require('assert'); - -var obj = define({ a: 1, b: 2 }, { - a: 10, - b: 20, - c: 30 -}); -assert(obj.a === 1); -assert(obj.b === 2); -assert(obj.c === 30); -if (define.supportsDescriptors) { - assert.deepEqual(Object.keys(obj), ['a', 'b']); - assert.deepEqual(Object.getOwnPropertyDescriptor(obj, 'c'), { - configurable: true, - enumerable: false, - value: 30, - writable: false - }); -} -``` - -Then, with predicates: -```js -var define = require('define-properties'); -var assert = require('assert'); - -var obj = define({ a: 1, b: 2, c: 3 }, { - a: 10, - b: 20, - c: 30 -}, { - a: function () { return false; }, - b: function () { return true; } -}); -assert(obj.a === 1); -assert(obj.b === 20); -assert(obj.c === 3); -if (define.supportsDescriptors) { - assert.deepEqual(Object.keys(obj), ['a', 'c']); - assert.deepEqual(Object.getOwnPropertyDescriptor(obj, 'b'), { - configurable: true, - enumerable: false, - value: 20, - writable: false - }); -} -``` - -## Tests -Simply clone the repo, `npm install`, and run `npm test` - -[package-url]: https://npmjs.org/package/define-properties -[npm-version-svg]: http://versionbadg.es/ljharb/define-properties.svg -[travis-svg]: https://travis-ci.org/ljharb/define-properties.svg -[travis-url]: https://travis-ci.org/ljharb/define-properties -[deps-svg]: https://david-dm.org/ljharb/define-properties.svg -[deps-url]: https://david-dm.org/ljharb/define-properties -[dev-deps-svg]: https://david-dm.org/ljharb/define-properties/dev-status.svg -[dev-deps-url]: https://david-dm.org/ljharb/define-properties#info=devDependencies -[testling-svg]: https://ci.testling.com/ljharb/define-properties.png -[testling-url]: https://ci.testling.com/ljharb/define-properties -[npm-badge-png]: https://nodei.co/npm/define-properties.png?downloads=true&stars=true -[license-image]: http://img.shields.io/npm/l/define-properties.svg -[license-url]: LICENSE -[downloads-image]: http://img.shields.io/npm/dm/define-properties.svg -[downloads-url]: http://npm-stat.com/charts.html?package=define-properties - diff --git a/scripts/2.5/node_modules/define-properties/index.js b/scripts/2.5/node_modules/define-properties/index.js deleted file mode 100644 index cb3ae1c7..00000000 --- a/scripts/2.5/node_modules/define-properties/index.js +++ /dev/null @@ -1,58 +0,0 @@ -'use strict'; - -var keys = require('object-keys'); -var hasSymbols = typeof Symbol === 'function' && typeof Symbol('foo') === 'symbol'; - -var toStr = Object.prototype.toString; -var concat = Array.prototype.concat; -var origDefineProperty = Object.defineProperty; - -var isFunction = function (fn) { - return typeof fn === 'function' && toStr.call(fn) === '[object Function]'; -}; - -var arePropertyDescriptorsSupported = function () { - var obj = {}; - try { - origDefineProperty(obj, 'x', { enumerable: false, value: obj }); - // eslint-disable-next-line no-unused-vars, no-restricted-syntax - for (var _ in obj) { // jscs:ignore disallowUnusedVariables - return false; - } - return obj.x === obj; - } catch (e) { /* this is IE 8. */ - return false; - } -}; -var supportsDescriptors = origDefineProperty && arePropertyDescriptorsSupported(); - -var defineProperty = function (object, name, value, predicate) { - if (name in object && (!isFunction(predicate) || !predicate())) { - return; - } - if (supportsDescriptors) { - origDefineProperty(object, name, { - configurable: true, - enumerable: false, - value: value, - writable: true - }); - } else { - object[name] = value; - } -}; - -var defineProperties = function (object, map) { - var predicates = arguments.length > 2 ? arguments[2] : {}; - var props = keys(map); - if (hasSymbols) { - props = concat.call(props, Object.getOwnPropertySymbols(map)); - } - for (var i = 0; i < props.length; i += 1) { - defineProperty(object, props[i], map[props[i]], predicates[props[i]]); - } -}; - -defineProperties.supportsDescriptors = !!supportsDescriptors; - -module.exports = defineProperties; diff --git a/scripts/2.5/node_modules/define-properties/package.json b/scripts/2.5/node_modules/define-properties/package.json deleted file mode 100644 index 8ca60c09..00000000 --- a/scripts/2.5/node_modules/define-properties/package.json +++ /dev/null @@ -1,99 +0,0 @@ -{ - "_from": "define-properties@^1.1.1", - "_id": "define-properties@1.1.3", - "_inBundle": false, - "_integrity": "sha512-3MqfYKj2lLzdMSf8ZIZE/V+Zuy+BgD6f164e8K2w7dgnpKArBDerGYpM46IYYcjnkdPNMjPk9A6VFB8+3SKlXQ==", - "_location": "/define-properties", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "define-properties@^1.1.1", - "name": "define-properties", - "escapedName": "define-properties", - "rawSpec": "^1.1.1", - "saveSpec": null, - "fetchSpec": "^1.1.1" - }, - "_requiredBy": [ - "/is-nan", - "/object.entries", - "/string.prototype.trimleft", - "/string.prototype.trimright" - ], - "_resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.1.3.tgz", - "_shasum": "cf88da6cbee26fe6db7094f61d870cbd84cee9f1", - "_spec": "define-properties@^1.1.1", - "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/2.5/node_modules/is-nan", - "author": { - "name": "Jordan Harband" - }, - "bugs": { - "url": "https://github.com/ljharb/define-properties/issues" - }, - "bundleDependencies": false, - "dependencies": { - "object-keys": "^1.0.12" - }, - "deprecated": false, - "description": "Define multiple non-enumerable properties at once. Uses `Object.defineProperty` when available; falls back to standard assignment in older engines.", - "devDependencies": { - "@ljharb/eslint-config": "^13.0.0", - "covert": "^1.1.0", - "eslint": "^5.3.0", - "jscs": "^3.0.7", - "nsp": "^3.2.1", - "tape": "^4.9.0" - }, - "engines": { - "node": ">= 0.4" - }, - "homepage": "https://github.com/ljharb/define-properties#readme", - "keywords": [ - "Object.defineProperty", - "Object.defineProperties", - "object", - "property descriptor", - "descriptor", - "define", - "ES5" - ], - "license": "MIT", - "main": "index.js", - "name": "define-properties", - "repository": { - "type": "git", - "url": "git://github.com/ljharb/define-properties.git" - }, - "scripts": { - "coverage": "covert test/*.js", - "coverage-quiet": "covert test/*.js --quiet", - "eslint": "eslint test/*.js *.js", - "jscs": "jscs test/*.js *.js", - "lint": "npm run --silent jscs && npm run --silent eslint", - "posttest": "npm run --silent security", - "pretest": "npm run --silent lint", - "security": "nsp check", - "test": "npm run --silent tests-only", - "tests-only": "node test/index.js" - }, - "testling": { - "files": "test/index.js", - "browsers": [ - "iexplore/6.0..latest", - "firefox/3.0..6.0", - "firefox/15.0..latest", - "firefox/nightly", - "chrome/4.0..10.0", - "chrome/20.0..latest", - "chrome/canary", - "opera/10.0..latest", - "opera/next", - "safari/4.0..latest", - "ipad/6.0..latest", - "iphone/6.0..latest", - "android-browser/4.2" - ] - }, - "version": "1.1.3" -} diff --git a/scripts/2.5/node_modules/define-properties/test/index.js b/scripts/2.5/node_modules/define-properties/test/index.js deleted file mode 100644 index 3387f6bc..00000000 --- a/scripts/2.5/node_modules/define-properties/test/index.js +++ /dev/null @@ -1,125 +0,0 @@ -'use strict'; - -var define = require('../'); -var test = require('tape'); -var keys = require('object-keys'); - -var arePropertyDescriptorsSupported = function () { - var obj = { a: 1 }; - try { - Object.defineProperty(obj, 'x', { value: obj }); - return obj.x === obj; - } catch (e) { /* this is IE 8. */ - return false; - } -}; -var descriptorsSupported = !!Object.defineProperty && arePropertyDescriptorsSupported(); - -var hasSymbols = typeof Symbol === 'function' && typeof Symbol('foo') === 'symbol'; - -test('defineProperties', function (dt) { - dt.test('with descriptor support', { skip: !descriptorsSupported }, function (t) { - var getDescriptor = function (value) { - return { - configurable: true, - enumerable: false, - value: value, - writable: true - }; - }; - - var obj = { - a: 1, - b: 2, - c: 3 - }; - t.deepEqual(keys(obj), ['a', 'b', 'c'], 'all literal-set keys start enumerable'); - define(obj, { - b: 3, - c: 4, - d: 5 - }); - t.deepEqual(obj, { - a: 1, - b: 2, - c: 3 - }, 'existing properties were not overridden'); - t.deepEqual(Object.getOwnPropertyDescriptor(obj, 'd'), getDescriptor(5), 'new property "d" was added and is not enumerable'); - t.deepEqual(['a', 'b', 'c'], keys(obj), 'new keys are not enumerable'); - - define(obj, { - a: 2, - b: 3, - c: 4 - }, { - a: function () { return true; }, - b: function () { return false; } - }); - t.deepEqual(obj, { - b: 2, - c: 3 - }, 'properties only overriden when predicate exists and returns true'); - t.deepEqual(Object.getOwnPropertyDescriptor(obj, 'd'), getDescriptor(5), 'existing property "d" remained and is not enumerable'); - t.deepEqual(Object.getOwnPropertyDescriptor(obj, 'a'), getDescriptor(2), 'existing property "a" was overridden and is not enumerable'); - t.deepEqual(['b', 'c'], keys(obj), 'overridden keys are not enumerable'); - - t.end(); - }); - - dt.test('without descriptor support', { skip: descriptorsSupported }, function (t) { - var obj = { - a: 1, - b: 2, - c: 3 - }; - define(obj, { - b: 3, - c: 4, - d: 5 - }); - t.deepEqual(obj, { - a: 1, - b: 2, - c: 3, - d: 5 - }, 'existing properties were not overridden, new properties were added'); - - define(obj, { - a: 2, - b: 3, - c: 4 - }, { - a: function () { return true; }, - b: function () { return false; } - }); - t.deepEqual(obj, { - a: 2, - b: 2, - c: 3, - d: 5 - }, 'properties only overriden when predicate exists and returns true'); - - t.end(); - }); - - dt.end(); -}); - -test('symbols', { skip: !hasSymbols }, function (t) { - var sym = Symbol('foo'); - var obj = {}; - var aValue = {}; - var bValue = {}; - var properties = { a: aValue }; - properties[sym] = bValue; - - define(obj, properties); - - t.deepEqual(Object.keys(obj), [], 'object has no enumerable keys'); - t.deepEqual(Object.getOwnPropertyNames(obj), ['a'], 'object has non-enumerable "a" key'); - t.deepEqual(Object.getOwnPropertySymbols(obj), [sym], 'object has non-enumerable symbol key'); - t.equal(obj.a, aValue, 'string keyed value is defined'); - t.equal(obj[sym], bValue, 'symbol keyed value is defined'); - - t.end(); -}); diff --git a/scripts/2.5/node_modules/es-abstract/.editorconfig b/scripts/2.5/node_modules/es-abstract/.editorconfig deleted file mode 100644 index eaa21416..00000000 --- a/scripts/2.5/node_modules/es-abstract/.editorconfig +++ /dev/null @@ -1,13 +0,0 @@ -root = true - -[*] -indent_style = tab; -insert_final_newline = true; -quote_type = auto; -space_after_anonymous_functions = true; -space_after_control_statements = true; -spaces_around_operators = true; -trim_trailing_whitespace = true; -spaces_in_brackets = false; -end_of_line = lf; - diff --git a/scripts/2.5/node_modules/es-abstract/.eslintrc b/scripts/2.5/node_modules/es-abstract/.eslintrc deleted file mode 100644 index fedc4628..00000000 --- a/scripts/2.5/node_modules/es-abstract/.eslintrc +++ /dev/null @@ -1,70 +0,0 @@ -{ - "root": true, - - "extends": "@ljharb", - - "env": { - "es6": true, - }, - - "rules": { - "arrow-parens": [2, "always"], - "array-bracket-newline": 0, - "array-element-newline": 0, - "complexity": 0, - "eqeqeq": [2, "allow-null"], - "func-name-matching": 0, - "id-length": [2, { "min": 1, "max": 30 }], - "max-params": [2, 4], - "max-statements": [2, 24], - "max-statements-per-line": [2, { "max": 2 }], - "multiline-comment-style": 1, - "no-magic-numbers": 0, - "new-cap": 0, - "no-extra-parens": 1, - "operator-linebreak": [2, "before"], - "sort-keys": 0, - }, - - "overrides": [ - { - "files": "./es5.js", - "rules": { - "max-lines": [2, 600], - "max-statements": [2, 30], - }, - }, - { - "files": "./es2015.js", - "rules": { - "max-lines": [2, 1500], - }, - }, - { - "files": "operations/*", - "rules": { - "max-lines": 0, - }, - }, - { - "files": "operations/*.js", - "parserOptions": { - "ecmaVersion": "2018", - }, - "rules": { -//camelcase -//array-callback-return -//consistent-return - "no-console": 0, - "no-multi-str": 0, - }, - }, - { - "files": "operations/getOps.js", - "rules": { - "no-console": 0, - "no-process-exit": 0, - }, - }, - ], -} diff --git a/scripts/2.5/node_modules/es-abstract/.github/FUNDING.yml b/scripts/2.5/node_modules/es-abstract/.github/FUNDING.yml deleted file mode 100644 index beeb7a28..00000000 --- a/scripts/2.5/node_modules/es-abstract/.github/FUNDING.yml +++ /dev/null @@ -1,12 +0,0 @@ -# These are supported funding model platforms - -github: [ljharb] -patreon: # Replace with a single Patreon username -open_collective: # Replace with a single Open Collective username -ko_fi: # Replace with a single Ko-fi username -tidelift: npm/es-abstract -community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry -liberapay: # Replace with a single Liberapay username -issuehunt: # Replace with a single IssueHunt username -otechie: # Replace with a single Otechie username -custom: # Replace with a single custom sponsorship URL diff --git a/scripts/2.5/node_modules/es-abstract/.nycrc b/scripts/2.5/node_modules/es-abstract/.nycrc deleted file mode 100644 index 3421adaa..00000000 --- a/scripts/2.5/node_modules/es-abstract/.nycrc +++ /dev/null @@ -1,14 +0,0 @@ -{ - "all": true, - "check-coverage": true, - "reporter": ["text-summary", "text", "html", "json"], - "lines": 86, - "statements": 85.93, - "functions": 82.43, - "branches": 76.06, - "exclude": [ - "coverage", - "operations", - "test" - ] -} diff --git a/scripts/2.5/node_modules/es-abstract/.travis.yml b/scripts/2.5/node_modules/es-abstract/.travis.yml deleted file mode 100644 index a0a9356e..00000000 --- a/scripts/2.5/node_modules/es-abstract/.travis.yml +++ /dev/null @@ -1,333 +0,0 @@ -language: node_js -os: - - linux -node_js: - - "12.12" - - "11.15" - - "10.16" - - "9.11" - - "8.16" - - "7.10" - - "6.17" - - "5.12" - - "4.9" - - "iojs-v3.3" - - "iojs-v2.5" - - "iojs-v1.8" - - "0.12" - - "0.10" - - "0.8" - - "0.6" -cache: - directories: - - "$HOME/.npm" - - "$(nvm cache dir)" - - "$(nvm_version_path $(nvm_version_remote 0.4))" - - "$(nvm_version_path $(nvm_version_remote 0.6))" - - "$(nvm_version_path $(nvm_version_remote 0.10))" -before_install: - - 'case "${TRAVIS_NODE_VERSION}" in 0.*) export NPM_CONFIG_STRICT_SSL=false ;; esac' - - 'nvm install-latest-npm' -install: - - 'if [ "${TRAVIS_NODE_VERSION}" = "0.6" ] || [ "${TRAVIS_NODE_VERSION}" = "0.9" ]; then nvm install --latest-npm 0.8 && npm install && nvm use "${TRAVIS_NODE_VERSION}"; else npm install; fi;' -script: - - 'if [ -n "${PRETEST-}" ]; then npm run pretest ; fi' - - 'if [ -n "${POSTTEST-}" ]; then npm run posttest ; fi' - - 'if [ -n "${COVERAGE-}" ]; then npm run coverage && bash <(curl -s https://codecov.io/bash) -f coverage/*.json; fi' - - 'if [ -n "${TEST-}" ]; then npm run tests-only ; fi' -sudo: false -env: - - TEST=true -matrix: - fast_finish: true - include: - - node_js: "lts/*" - env: PRETEST=true - - node_js: "lts/*" - env: POSTTEST=true - - node_js: "0.8" - env: COVERAGE=true - - node_js: "0.12" - env: COVERAGE=true - - node_js: "4" - env: COVERAGE=true - - node_js: "8" - env: COVERAGE=true - - node_js: "12.11" - env: TEST=true ALLOW_FAILURE=true - - node_js: "12.10" - env: TEST=true ALLOW_FAILURE=true - - node_js: "12.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "12.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "12.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "12.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "12.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "12.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "12.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "12.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "12.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "12.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "11.14" - env: TEST=true ALLOW_FAILURE=true - - node_js: "11.13" - env: TEST=true ALLOW_FAILURE=true - - node_js: "11.12" - env: TEST=true ALLOW_FAILURE=true - - node_js: "11.11" - env: TEST=true ALLOW_FAILURE=true - - node_js: "11.10" - env: TEST=true ALLOW_FAILURE=true - - node_js: "11.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "11.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "11.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "11.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "11.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "11.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "11.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "11.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "11.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "11.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.15" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.14" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.13" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.12" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.11" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.10" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.10" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.15" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.14" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.13" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.12" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.11" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.10" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.16" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.15" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.14" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.13" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.12" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.11" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.10" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.11" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.10" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v3.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v3.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v3.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "0.11" - env: TEST=true ALLOW_FAILURE=true - - node_js: "0.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "0.4" - env: TEST=true ALLOW_FAILURE=true - allow_failures: - - os: osx - - env: TEST=true ALLOW_FAILURE=true - - node_js: "0.6" diff --git a/scripts/2.5/node_modules/es-abstract/CHANGELOG.md b/scripts/2.5/node_modules/es-abstract/CHANGELOG.md deleted file mode 100644 index 048d2057..00000000 --- a/scripts/2.5/node_modules/es-abstract/CHANGELOG.md +++ /dev/null @@ -1,264 +0,0 @@ -1.16.0 / 2019-10-18 -================= - * [New] `ES2015+`: add `SetFunctionName` - * [New] `ES2015+`: add `GetPrototypeFromConstructor`, with caveats - * [New] `ES2015+`: add `CreateListFromArrayLike` - * [New] `ES2016+`: add `OrdinarySetPrototypeOf` - * [New] `ES2016+`: add `OrdinaryGetPrototypeOf` - * [New] add `getSymbolDescription` and `getInferredName` helpers - * [Fix] `GetIterator`: add fallback for pre-Symbol environments, tests - * [Dev Deps] update `object.fromentries` - * [Tests] add `node` `v12.2` - - -1.15.0 / 2019-10-02 -================= - * [New] `ES2018`+: add `DateString`, `TimeString` - * [New] `ES2015`+: add `ToDateString` - * [New] `ES5`+: add `msFromTime`, `SecFromTime`, `MinFromTime`, `HourFromTime`, `TimeWithinDay`, `Day`, `DayFromYear`, `TimeFromYear`, `YearFromTime`, `WeekDay`, `DaysInYear`, `InLeapYear`, `DayWithinYear`, `MonthFromTime`, `DateFromTime`, `MakeDay`, `MakeDate`, `MakeTime`, `TimeClip`, `modulo` - * [New] add `regexTester` helper - * [New] add `callBound` helper - * [New] add ES2020’s intrinsic dot notation - * [New] add `isPrefixOf` helper - * [New] add `maxSafeInteger` helper - * [Deps] update `string.prototype.trimleft`, `string.prototype.trimright` - * [Dev Deps] update `eslint` - * [Tests] on `node` `v12.11` - * [meta] npmignore operations scripts; add "deltas" - -1.14.2 / 2019-09-08 -================= - * [Fix] `ES2016`: `IterableToArrayLike`: add proper fallback for strings, pre-Symbols - * [Tests] on `node` `v12.10` - -1.14.1 / 2019-09-03 -================= - * [meta] republish with some extra files removed - -1.14.0 / 2019-09-02 -================= - * [New] add ES2019 - * [New] `ES2017+`: add `IterableToList` - * [New] `ES2016`: add `IterableToArrayLike` - * [New] `ES2015+`: add `ArrayCreate`, `ArraySetLength`, `OrdinaryDefineOwnProperty`, `OrdinaryGetOwnProperty`, `OrdinaryHasProperty`, `CreateHTML`, `GetOwnPropertyKeys`, `InstanceofOperator`, `SymbolDescriptiveString`, `GetSubstitution`, `ValidateAndApplyPropertyDescriptor`, `IsPromise`, `OrdinaryHasInstance`, `TestIntegrityLevel`, `SetIntegrityLevel` - * [New] add `callBind` helper, and use it - * [New] add helpers: `isPropertyDescriptor`, `every` - * [New] ES5+: add `Abstract Relational Comparison` - * [New] ES5+: add `Abstract Equality Comparison`, `Strict Equality Comparison` - * [Fix] `ES2015+`: `GetIterator`: only require native Symbols when `method` is omitted - * [Fix] `ES2015`: `Call`: error message now properly displays Symbols using `object-inspect` - * [Fix] `ES2015+`: `ValidateAndApplyPropertyDescriptor`: use ES2017 logic to bypass spec bugs - * [Fix] `ES2015+`: `CreateDataProperty`, `DefinePropertyOrThrow`, `ValidateAndApplyPropertyDescriptor`: add fallbacks for ES3 - * [Fix] `ES2015+`: `FromPropertyDescriptor`: no longer requires a fully complete Property Descriptor - * [Fix] `ES5`: `IsPropertyDescriptor`: call into `IsDataDescriptor` and `IsAccessorDescriptor` - * [Refactor] use `has-symbols` for Symbol detection - * [Fix] `helpers/assertRecord`: remove `console.log` - * [Deps] update `object-keys` - * [readme] add security note - * [meta] change http URLs to https - * [meta] linter cleanup - * [meta] fix getOps script - * [meta] add FUNDING.yml - * [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `safe-publish-latest`, `semver`, `replace`, `cheerio`, `tape` - * [Tests] up to `node` `v12.9`, `v11.15`, `v10.16`, `v8.16`, `v6.17` - * [Tests] temporarily allow node 0.6 to fail; segfaulting in travis - * [Tests] use the values helper more in es5 tests - * [Tests] fix linting to apply to all files - * [Tests] run `npx aud` only on prod deps - * [Tests] add v.descriptors helpers - * [Tests] use `npx aud` instead of `npm audit` with hoops - * [Tests] use `eclint` instead of `editorconfig-tools` - * [Tests] some intrinsic cleanup - * [Tests] migrate es5 tests to use values helper - * [Tests] add some missing ES2015 ops - -1.13.0 / 2019-01-02 -================= - * [New] add ES2018 - * [New] add ES2015/ES2016: EnumerableOwnNames; ES2017: EnumerableOwnProperties - * [New] `ES2015+`: add `thisBooleanValue`, `thisNumberValue`, `thisStringValue`, `thisTimeValue` - * [New] `ES2015+`: add `DefinePropertyOrThrow`, `DeletePropertyOrThrow`, `CreateMethodProperty` - * [New] add `assertRecord` helper - * [Deps] update `is-callable`, `has`, `object-keys`, `es-to-primitive` - * [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape`, `semver`, `safe-publish-latest`, `replace` - * [Tests] use `npm audit` instead of `nsp` - * [Tests] remove `jscs` - * [Tests] up to `node` `v11.6`, `v10.15`, `v8.15`, `v6.16` - * [Tests] move descriptor factories to `values` helper - * [Tests] add `getOps` to programmatically fetch abstract operation names - -1.12.0 / 2018-05-31 -================= - * [New] add `GetIntrinsic` entry point - * [New] `ES2015`+: add `ObjectCreate` - * [Robustness]: `ES2015+`: ensure `Math.{abs,floor}` and `Function.call` are cached - -1.11.0 / 2018-03-21 -================= - * [New] `ES2015+`: add iterator abstract ops - * [Dev Deps] update `eslint`, `nsp`, `object.assign`, `semver`, `tape` - * [Tests] up to `node` `v9.8`, `v8.10`, `v6.13` - -1.10.0 / 2017-11-24 -================= - * [New] ES2015+: `AdvanceStringIndex` - * [Dev Deps] update `eslint`, `nsp` - * [Tests] require node 0.6 to pass again - * [Tests] up to `node` `v9.2`, `v8.9`, `v6.12`; use `nvm install-latest-npm`; pin included builds to LTS - -1.9.0 / 2017-09-30 -================= - * [New] `es2015+`: add `ArraySpeciesCreate` - * [New] ES2015+: add `CreateDataProperty` and `CreateDataPropertyOrThrow` - * [Tests] consolidate duplicated tests - * [Tests] increase coverage - * [Dev Deps] update `nsp`, `eslint` - -1.8.2 / 2017-09-03 -================= - * [Fix] `es2015`+: `ToNumber`: provide the proper hint for Date objects (#27) - * [Dev Deps] update `eslint` - -1.8.1 / 2017-08-30 -================= - * [Fix] ES2015+: `ToPropertyKey`: should return a symbol for Symbols (#26) - * [Deps] update `function-bind` - * [Dev Deps] update `eslint`, `@ljharb/eslint-config` - * [Docs] github broke markdown parsing - -1.8.0 / 2017-08-04 -================= - * [New] add ES2017 - * [New] move es6+ to es2015+; leave es6/es7 as aliases - * [New] ES5+: add `IsPropertyDescriptor`, `IsAccessorDescriptor`, `IsDataDescriptor`, `IsGenericDescriptor`, `FromPropertyDescriptor`, `ToPropertyDescriptor` - * [New] ES2015+: add `CompletePropertyDescriptor`, `Set`, `HasOwnProperty`, `HasProperty`, `IsConcatSpreadable`, `Invoke`, `CreateIterResultObject`, `RegExpExec` - * [Fix] es7/es2016: do not mutate ES6 - * [Fix] assign helper only supports one source - * [Deps] update `is-regex` - * [Dev Deps] update `nsp`, `eslint`, `@ljharb/eslint-config` - * [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `nsp`, `semver`, `tape` - * [Tests] add tests for missing and excess operations - * [Tests] add codecov for coverage - * [Tests] up to `node` `v8.2`, `v7.10`, `v6.11`, `v4.8`; newer npm breaks on older node - * [Tests] use same lists of value types across tests; ensure tests are the same when ops are the same - * [Tests] ES2015: add ToNumber symbol tests - * [Tests] switch to `nyc` for code coverage - * [Tests] make IsRegExp tests consistent across editions - -1.7.0 / 2017-01-22 -================= - * [New] ES6: Add `GetMethod` (#16) - * [New] ES6: Add `GetV` (#16) - * [New] ES6: Add `Get` (#17) - * [Tests] up to `node` `v7.4`, `v6.9`, `v4.6`; improve test matrix - * [Dev Deps] update `tape`, `nsp`, `eslint`, `@ljharb/eslint-config`, `safe-publish-latest` - -1.6.1 / 2016-08-21 -================= - * [Fix] ES6: IsConstructor should return true for `class` constructors. - -1.6.0 / 2016-08-20 -================= - * [New] ES5 / ES6: add `Type` - * [New] ES6: `SpeciesConstructor` - * [Dev Deps] update `jscs`, `nsp`, `eslint`, `@ljharb/eslint-config`, `semver`; add `safe-publish-latest` - * [Tests] up to `node` `v6.4`, `v5.12`, `v4.5` - -1.5.1 / 2016-05-30 -================= - * [Fix] `ES.IsRegExp`: actually look up `Symbol.match` on the argument - * [Refactor] create `isNaN` helper - * [Deps] update `is-callable`, `function-bind` - * [Deps] update `es-to-primitive`, fix ES5 tests - * [Dev Deps] update `jscs`, `eslint`, `@ljharb/eslint-config`, `tape`, `nsp` - * [Tests] up to `node` `v6.2`, `v5.11`, `v4.4` - * [Tests] use pretest/posttest for linting/security - -1.5.0 / 2015-12-27 -================= - * [New] adds `Symbol.toPrimitive` support via `es-to-primitive` - * [Deps] update `is-callable`, `es-to-primitive` - * [Dev Deps] update `jscs`, `nsp`, `eslint`, `@ljharb/eslint-config`, `semver`, `tape` - * [Tests] up to `node` `v5.3` - -1.4.3 / 2015-11-04 -================= - * [Fix] `ES6.ToNumber`: should give `NaN` for explicitly signed hex strings (#4) - * [Refactor] `ES6.ToNumber`: No need to double-trim - * [Refactor] group tests better - * [Tests] should still pass on `node` `v0.8` - -1.4.2 / 2015-11-02 -================= - * [Fix] ensure `ES.ToNumber` trims whitespace, and does not trim non-whitespace (#3) - -1.4.1 / 2015-10-31 -================= - * [Fix] ensure only 0-1 are valid binary and 0-7 are valid octal digits (#2) - * [Dev Deps] update `tape`, `jscs`, `nsp`, `eslint`, `@ljharb/eslint-config` - * [Tests] on `node` `v5.0` - * [Tests] fix npm upgrades for older node versions - * package.json: use object form of "authors", add "contributors" - -1.4.0 / 2015-09-26 -================= - * [Deps] update `is-callable` - * [Dev Deps] update `tape`, `jscs`, `eslint`, `@ljharb/eslint-config` - * [Tests] on `node` `v4.2` - * [New] Add `SameValueNonNumber` to ES7 - -1.3.2 / 2015-09-26 -================= - * [Fix] Fix `ES6.IsRegExp` to properly handle `Symbol.match`, per spec. - * [Tests] up to `io.js` `v3.3`, `node` `v4.1` - * [Dev Deps] update `tape`, `jscs`, `nsp`, `eslint`, `@ljharb/eslint-config`, `semver` - -1.3.1 / 2015-08-15 -================= - * [Fix] Ensure that objects that `toString` to a binary or octal literal also convert properly - -1.3.0 / 2015-08-15 -================= - * [New] ES6’s ToNumber now supports binary and octal literals. - * [Dev Deps] update `jscs`, `eslint`, `@ljharb/eslint-config`, `tape` - * [Docs] Switch from vb.teelaun.ch to versionbadg.es for the npm version badge SVG - * [Tests] up to `io.js` `v3.0` - -1.2.2 / 2015-07-28 -================= - * [Fix] Both `ES5.CheckObjectCoercible` and `ES6.RequireObjectCoercible` return the value if they don't throw. - * [Tests] Test on latest `io.js` versions. - * [Dev Deps] Update `eslint`, `jscs`, `tape`, `semver`, `covert`, `nsp` - -1.2.1 / 2015-03-20 -================= - * Fix `isFinite` helper. - -1.2.0 / 2015-03-19 -================= - * Use `es-to-primitive` for ToPrimitive methods. - * Test on latest `io.js` versions; allow failures on all but 2 latest `node`/`io.js` versions. - -1.1.2 / 2015-03-20 -================= - * Fix isFinite helper. - -1.1.1 / 2015-03-19 -================= - * Fix isPrimitive check for functions - * Update `eslint`, `editorconfig-tools`, `semver`, `nsp` - -1.1.0 / 2015-02-17 -================= - * Add ES7 export (non-default). - * All grade A-supported `node`/`iojs` versions now ship with an `npm` that understands `^`. - * Test on `iojs-v1.2`. - -1.0.1 / 2015-01-30 -================= - * Use `is-callable` instead of an internal function. - * Update `tape`, `jscs`, `nsp`, `eslint` - -1.0.0 / 2015-01-10 -================= - * v1.0.0 diff --git a/scripts/2.5/node_modules/es-abstract/GetIntrinsic.js b/scripts/2.5/node_modules/es-abstract/GetIntrinsic.js deleted file mode 100644 index 6c43b0db..00000000 --- a/scripts/2.5/node_modules/es-abstract/GetIntrinsic.js +++ /dev/null @@ -1,189 +0,0 @@ -'use strict'; - -/* globals - Atomics, - SharedArrayBuffer, -*/ - -var undefined; // eslint-disable-line no-shadow-restricted-names - -var $TypeError = TypeError; - -var ThrowTypeError = Object.getOwnPropertyDescriptor - ? (function () { return Object.getOwnPropertyDescriptor(arguments, 'callee').get; }()) - : function () { throw new $TypeError(); }; - -var hasSymbols = require('has-symbols')(); - -var getProto = Object.getPrototypeOf || function (x) { return x.__proto__; }; // eslint-disable-line no-proto - -var generator; // = function * () {}; -var generatorFunction = generator ? getProto(generator) : undefined; -var asyncFn; // async function() {}; -var asyncFunction = asyncFn ? asyncFn.constructor : undefined; -var asyncGen; // async function * () {}; -var asyncGenFunction = asyncGen ? getProto(asyncGen) : undefined; -var asyncGenIterator = asyncGen ? asyncGen() : undefined; - -var TypedArray = typeof Uint8Array === 'undefined' ? undefined : getProto(Uint8Array); - -var INTRINSICS = { - '$ %Array%': Array, - '$ %ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer, - '$ %ArrayBufferPrototype%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer.prototype, - '$ %ArrayIteratorPrototype%': hasSymbols ? getProto([][Symbol.iterator]()) : undefined, - '$ %ArrayPrototype%': Array.prototype, - '$ %ArrayProto_entries%': Array.prototype.entries, - '$ %ArrayProto_forEach%': Array.prototype.forEach, - '$ %ArrayProto_keys%': Array.prototype.keys, - '$ %ArrayProto_values%': Array.prototype.values, - '$ %AsyncFromSyncIteratorPrototype%': undefined, - '$ %AsyncFunction%': asyncFunction, - '$ %AsyncFunctionPrototype%': asyncFunction ? asyncFunction.prototype : undefined, - '$ %AsyncGenerator%': asyncGen ? getProto(asyncGenIterator) : undefined, - '$ %AsyncGeneratorFunction%': asyncGenFunction, - '$ %AsyncGeneratorPrototype%': asyncGenFunction ? asyncGenFunction.prototype : undefined, - '$ %AsyncIteratorPrototype%': asyncGenIterator && hasSymbols && Symbol.asyncIterator ? asyncGenIterator[Symbol.asyncIterator]() : undefined, - '$ %Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics, - '$ %Boolean%': Boolean, - '$ %BooleanPrototype%': Boolean.prototype, - '$ %DataView%': typeof DataView === 'undefined' ? undefined : DataView, - '$ %DataViewPrototype%': typeof DataView === 'undefined' ? undefined : DataView.prototype, - '$ %Date%': Date, - '$ %DatePrototype%': Date.prototype, - '$ %decodeURI%': decodeURI, - '$ %decodeURIComponent%': decodeURIComponent, - '$ %encodeURI%': encodeURI, - '$ %encodeURIComponent%': encodeURIComponent, - '$ %Error%': Error, - '$ %ErrorPrototype%': Error.prototype, - '$ %eval%': eval, // eslint-disable-line no-eval - '$ %EvalError%': EvalError, - '$ %EvalErrorPrototype%': EvalError.prototype, - '$ %Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array, - '$ %Float32ArrayPrototype%': typeof Float32Array === 'undefined' ? undefined : Float32Array.prototype, - '$ %Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array, - '$ %Float64ArrayPrototype%': typeof Float64Array === 'undefined' ? undefined : Float64Array.prototype, - '$ %Function%': Function, - '$ %FunctionPrototype%': Function.prototype, - '$ %Generator%': generator ? getProto(generator()) : undefined, - '$ %GeneratorFunction%': generatorFunction, - '$ %GeneratorPrototype%': generatorFunction ? generatorFunction.prototype : undefined, - '$ %Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array, - '$ %Int8ArrayPrototype%': typeof Int8Array === 'undefined' ? undefined : Int8Array.prototype, - '$ %Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array, - '$ %Int16ArrayPrototype%': typeof Int16Array === 'undefined' ? undefined : Int8Array.prototype, - '$ %Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array, - '$ %Int32ArrayPrototype%': typeof Int32Array === 'undefined' ? undefined : Int32Array.prototype, - '$ %isFinite%': isFinite, - '$ %isNaN%': isNaN, - '$ %IteratorPrototype%': hasSymbols ? getProto(getProto([][Symbol.iterator]())) : undefined, - '$ %JSON%': JSON, - '$ %JSONParse%': JSON.parse, - '$ %Map%': typeof Map === 'undefined' ? undefined : Map, - '$ %MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols ? undefined : getProto(new Map()[Symbol.iterator]()), - '$ %MapPrototype%': typeof Map === 'undefined' ? undefined : Map.prototype, - '$ %Math%': Math, - '$ %Number%': Number, - '$ %NumberPrototype%': Number.prototype, - '$ %Object%': Object, - '$ %ObjectPrototype%': Object.prototype, - '$ %ObjProto_toString%': Object.prototype.toString, - '$ %ObjProto_valueOf%': Object.prototype.valueOf, - '$ %parseFloat%': parseFloat, - '$ %parseInt%': parseInt, - '$ %Promise%': typeof Promise === 'undefined' ? undefined : Promise, - '$ %PromisePrototype%': typeof Promise === 'undefined' ? undefined : Promise.prototype, - '$ %PromiseProto_then%': typeof Promise === 'undefined' ? undefined : Promise.prototype.then, - '$ %Promise_all%': typeof Promise === 'undefined' ? undefined : Promise.all, - '$ %Promise_reject%': typeof Promise === 'undefined' ? undefined : Promise.reject, - '$ %Promise_resolve%': typeof Promise === 'undefined' ? undefined : Promise.resolve, - '$ %Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy, - '$ %RangeError%': RangeError, - '$ %RangeErrorPrototype%': RangeError.prototype, - '$ %ReferenceError%': ReferenceError, - '$ %ReferenceErrorPrototype%': ReferenceError.prototype, - '$ %Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect, - '$ %RegExp%': RegExp, - '$ %RegExpPrototype%': RegExp.prototype, - '$ %Set%': typeof Set === 'undefined' ? undefined : Set, - '$ %SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols ? undefined : getProto(new Set()[Symbol.iterator]()), - '$ %SetPrototype%': typeof Set === 'undefined' ? undefined : Set.prototype, - '$ %SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer, - '$ %SharedArrayBufferPrototype%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer.prototype, - '$ %String%': String, - '$ %StringIteratorPrototype%': hasSymbols ? getProto(''[Symbol.iterator]()) : undefined, - '$ %StringPrototype%': String.prototype, - '$ %Symbol%': hasSymbols ? Symbol : undefined, - '$ %SymbolPrototype%': hasSymbols ? Symbol.prototype : undefined, - '$ %SyntaxError%': SyntaxError, - '$ %SyntaxErrorPrototype%': SyntaxError.prototype, - '$ %ThrowTypeError%': ThrowTypeError, - '$ %TypedArray%': TypedArray, - '$ %TypedArrayPrototype%': TypedArray ? TypedArray.prototype : undefined, - '$ %TypeError%': $TypeError, - '$ %TypeErrorPrototype%': $TypeError.prototype, - '$ %Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array, - '$ %Uint8ArrayPrototype%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array.prototype, - '$ %Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray, - '$ %Uint8ClampedArrayPrototype%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray.prototype, - '$ %Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array, - '$ %Uint16ArrayPrototype%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array.prototype, - '$ %Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array, - '$ %Uint32ArrayPrototype%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array.prototype, - '$ %URIError%': URIError, - '$ %URIErrorPrototype%': URIError.prototype, - '$ %WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap, - '$ %WeakMapPrototype%': typeof WeakMap === 'undefined' ? undefined : WeakMap.prototype, - '$ %WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet, - '$ %WeakSetPrototype%': typeof WeakSet === 'undefined' ? undefined : WeakSet.prototype -}; - -var bind = require('function-bind'); -var $replace = bind.call(Function.call, String.prototype.replace); - -/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */ -var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g; -var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */ -var stringToPath = function stringToPath(string) { - var result = []; - $replace(string, rePropName, function (match, number, quote, subString) { - result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : (number || match); - }); - return result; -}; -/* end adaptation */ - -var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) { - var key = '$ ' + name; - if (!(key in INTRINSICS)) { - throw new SyntaxError('intrinsic ' + name + ' does not exist!'); - } - - // istanbul ignore if // hopefully this is impossible to test :-) - if (typeof INTRINSICS[key] === 'undefined' && !allowMissing) { - throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!'); - } - - return INTRINSICS[key]; -}; - -module.exports = function GetIntrinsic(name, allowMissing) { - if (arguments.length > 1 && typeof allowMissing !== 'boolean') { - throw new TypeError('"allowMissing" argument must be a boolean'); - } - - var parts = stringToPath(name); - - if (parts.length === 0) { - return getBaseIntrinsic(name, allowMissing); - } - - var value = getBaseIntrinsic('%' + parts[0] + '%', allowMissing); - for (var i = 1; i < parts.length; i += 1) { - if (value != null) { - value = value[parts[i]]; - } - } - return value; -}; diff --git a/scripts/2.5/node_modules/es-abstract/LICENSE b/scripts/2.5/node_modules/es-abstract/LICENSE deleted file mode 100644 index 8c271c14..00000000 --- a/scripts/2.5/node_modules/es-abstract/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (C) 2015 Jordan Harband - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. \ No newline at end of file diff --git a/scripts/2.5/node_modules/es-abstract/Makefile b/scripts/2.5/node_modules/es-abstract/Makefile deleted file mode 100644 index 959bbd49..00000000 --- a/scripts/2.5/node_modules/es-abstract/Makefile +++ /dev/null @@ -1,61 +0,0 @@ -# Since we rely on paths relative to the makefile location, abort if make isn't being run from there. -$(if $(findstring /,$(MAKEFILE_LIST)),$(error Please only invoke this makefile from the directory it resides in)) - - # The files that need updating when incrementing the version number. -VERSIONED_FILES := *.js */*.js *.json README* - - -# Add the local npm packages' bin folder to the PATH, so that `make` can find them, when invoked directly. -# Note that rather than using `$(npm bin)` the 'node_modules/.bin' path component is hard-coded, so that invocation works even from an environment -# where npm is (temporarily) unavailable due to having deactivated an nvm instance loaded into the calling shell in order to avoid interference with tests. -export PATH := $(shell printf '%s' "$$PWD/node_modules/.bin:$$PATH") -UTILS := semver -# Make sure that all required utilities can be located. -UTIL_CHECK := $(or $(shell PATH="$(PATH)" which $(UTILS) >/dev/null && echo 'ok'),$(error Did you forget to run `npm install` after cloning the repo? At least one of the required supporting utilities not found: $(UTILS))) - -# Default target (by virtue of being the first non '.'-prefixed in the file). -.PHONY: _no-target-specified -_no-target-specified: - $(error Please specify the target to make - `make list` shows targets. Alternatively, use `npm test` to run the default tests; `npm run` shows all tests) - -# Lists all targets defined in this makefile. -.PHONY: list -list: - @$(MAKE) -pRrn : -f $(MAKEFILE_LIST) 2>/dev/null | awk -v RS= -F: '/^# File/,/^# Finished Make data base/ {if ($$1 !~ "^[#.]") {print $$1}}' | command grep -v -e '^[^[:alnum:]]' -e '^$@$$command ' | sort - -# All-tests target: invokes the specified test suites for ALL shells defined in $(SHELLS). -.PHONY: test -test: - @npm test - -.PHONY: _ensure-tag -_ensure-tag: -ifndef TAG - $(error Please invoke with `make TAG= release`, where is either an increment specifier (patch, minor, major, prepatch, preminor, premajor, prerelease), or an explicit major.minor.patch version number) -endif - -CHANGELOG_ERROR = $(error No CHANGELOG specified) -.PHONY: _ensure-changelog -_ensure-changelog: - @ (git status -sb --porcelain | command grep -E '^( M|[MA] ) CHANGELOG.md' > /dev/null) || (echo no CHANGELOG.md specified && exit 2) - -# Ensures that the git workspace is clean. -.PHONY: _ensure-clean -_ensure-clean: - @[ -z "$$((git status --porcelain --untracked-files=no || echo err) | command grep -v 'CHANGELOG.md')" ] || { echo "Workspace is not clean; please commit changes first." >&2; exit 2; } - -# Makes a release; invoke with `make TAG= release`. -.PHONY: release -release: _ensure-tag _ensure-changelog _ensure-clean - @old_ver=`git describe --abbrev=0 --tags --match 'v[0-9]*.[0-9]*.[0-9]*'` || { echo "Failed to determine current version." >&2; exit 1; }; old_ver=$${old_ver#v}; \ - new_ver=`echo "$(TAG)" | sed 's/^v//'`; new_ver=$${new_ver:-patch}; \ - if printf "$$new_ver" | command grep -q '^[0-9]'; then \ - semver "$$new_ver" >/dev/null || { echo 'Invalid version number specified: $(TAG) - must be major.minor.patch' >&2; exit 2; }; \ - semver -r "> $$old_ver" "$$new_ver" >/dev/null || { echo 'Invalid version number specified: $(TAG) - must be HIGHER than current one.' >&2; exit 2; } \ - else \ - new_ver=`semver -i "$$new_ver" "$$old_ver"` || { echo 'Invalid version-increment specifier: $(TAG)' >&2; exit 2; } \ - fi; \ - printf "=== Bumping version **$$old_ver** to **$$new_ver** before committing and tagging:\n=== TYPE 'proceed' TO PROCEED, anything else to abort: " && read response && [ "$$response" = 'proceed' ] || { echo 'Aborted.' >&2; exit 2; }; \ - replace "$$old_ver" "$$new_ver" -- $(VERSIONED_FILES) && \ - git commit -m "v$$new_ver" $(VERSIONED_FILES) CHANGELOG.md && \ - git tag -a -m "v$$new_ver" "v$$new_ver" diff --git a/scripts/2.5/node_modules/es-abstract/README.md b/scripts/2.5/node_modules/es-abstract/README.md deleted file mode 100644 index 20342d11..00000000 --- a/scripts/2.5/node_modules/es-abstract/README.md +++ /dev/null @@ -1,48 +0,0 @@ -# es-abstract [![Version Badge][npm-version-svg]][package-url] - -[![Build Status][travis-svg]][travis-url] -[![dependency status][deps-svg]][deps-url] -[![dev dependency status][dev-deps-svg]][dev-deps-url] -[![License][license-image]][license-url] -[![Downloads][downloads-image]][downloads-url] - -[![npm badge][npm-badge-png]][package-url] - -[![browser support][testling-svg]][testling-url] - -ECMAScript spec abstract operations. -When different versions of the spec conflict, the default export will be the latest version of the abstract operation. -All abstract operations will also be available under an `es5`/`es2015`/`es2016`/`es2017`/`es2018`/`es2019` entry point, and exported property, if you require a specific version. - -## Example - -```js -var ES = require('es-abstract'); -var assert = require('assert'); - -assert(ES.isCallable(function () {})); -assert(!ES.isCallable(/a/g)); -``` - -## Tests -Simply clone the repo, `npm install`, and run `npm test` - -## Security - -Please email [@ljharb](https://github.com/ljharb) or see https://tidelift.com/security if you have a potential security vulnerability to report. - -[package-url]: https://npmjs.org/package/es-abstract -[npm-version-svg]: http://versionbadg.es/ljharb/es-abstract.svg -[travis-svg]: https://travis-ci.org/ljharb/es-abstract.svg -[travis-url]: https://travis-ci.org/ljharb/es-abstract -[deps-svg]: https://david-dm.org/ljharb/es-abstract.svg -[deps-url]: https://david-dm.org/ljharb/es-abstract -[dev-deps-svg]: https://david-dm.org/ljharb/es-abstract/dev-status.svg -[dev-deps-url]: https://david-dm.org/ljharb/es-abstract#info=devDependencies -[testling-svg]: https://ci.testling.com/ljharb/es-abstract.png -[testling-url]: https://ci.testling.com/ljharb/es-abstract -[npm-badge-png]: https://nodei.co/npm/es-abstract.png?downloads=true&stars=true -[license-image]: https://img.shields.io/npm/l/es-abstract.svg -[license-url]: LICENSE -[downloads-image]: https://img.shields.io/npm/dm/es-abstract.svg -[downloads-url]: https://npm-stat.com/charts.html?package=es-abstract diff --git a/scripts/2.5/node_modules/es-abstract/es2015.js b/scripts/2.5/node_modules/es-abstract/es2015.js deleted file mode 100644 index 6a1f045e..00000000 --- a/scripts/2.5/node_modules/es-abstract/es2015.js +++ /dev/null @@ -1,1464 +0,0 @@ -'use strict'; - -var has = require('has'); -var toPrimitive = require('es-to-primitive/es6'); -var keys = require('object-keys'); -var inspect = require('object-inspect'); - -var GetIntrinsic = require('./GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); -var $RangeError = GetIntrinsic('%RangeError%'); -var $SyntaxError = GetIntrinsic('%SyntaxError%'); -var $Array = GetIntrinsic('%Array%'); -var $ArrayPrototype = $Array.prototype; -var $String = GetIntrinsic('%String%'); -var $Object = GetIntrinsic('%Object%'); -var $Number = GetIntrinsic('%Number%'); -var $Symbol = GetIntrinsic('%Symbol%', true); -var $RegExp = GetIntrinsic('%RegExp%'); -var $Date = GetIntrinsic('%Date%'); -var $Function = GetIntrinsic('%Function%'); -var $preventExtensions = $Object.preventExtensions; - -var hasSymbols = require('has-symbols')(); - -var assertRecord = require('./helpers/assertRecord'); -var $isNaN = require('./helpers/isNaN'); -var $isFinite = require('./helpers/isFinite'); -var MAX_ARRAY_LENGTH = Math.pow(2, 32) - 1; -var MAX_SAFE_INTEGER = require('./helpers/maxSafeInteger'); - -var assign = require('./helpers/assign'); -var sign = require('./helpers/sign'); -var mod = require('./helpers/mod'); -var isPrimitive = require('./helpers/isPrimitive'); -var forEach = require('./helpers/forEach'); -var every = require('./helpers/every'); -var isSamePropertyDescriptor = require('./helpers/isSamePropertyDescriptor'); -var isPropertyDescriptor = require('./helpers/isPropertyDescriptor'); -var parseInteger = parseInt; -var callBound = require('./helpers/callBound'); -var regexTester = require('./helpers/regexTester'); -var getIteratorMethod = require('./helpers/getIteratorMethod'); -var getSymbolDescription = require('./helpers/getSymbolDescription'); - -var $PromiseThen = callBound('Promise.prototype.then', true); -var arraySlice = callBound('Array.prototype.slice'); -var strSlice = callBound('String.prototype.slice'); -var $indexOf = callBound('Array.prototype.indexOf'); -var $push = callBound('Array.prototype.push'); - -var isBinary = regexTester(/^0b[01]+$/i); -var isOctal = regexTester(/^0o[0-7]+$/i); -var isDigit = regexTester(/^[0-9]$/); -var regexExec = callBound('RegExp.prototype.exec'); -var nonWS = ['\u0085', '\u200b', '\ufffe'].join(''); -var nonWSregex = new $RegExp('[' + nonWS + ']', 'g'); -var hasNonWS = regexTester(nonWSregex); -var isInvalidHexLiteral = regexTester(/^[-+]0x[0-9a-f]+$/i); -var $charCodeAt = callBound('String.prototype.charCodeAt'); -var $isEnumerable = callBound('Object.prototype.propertyIsEnumerable'); - -var toStr = callBound('Object.prototype.toString'); - -var $NumberValueOf = callBound('Number.prototype.valueOf'); -var $BooleanValueOf = callBound('Boolean.prototype.valueOf'); -var $StringValueOf = callBound('String.prototype.valueOf'); -var $DateValueOf = callBound('Date.prototype.valueOf'); -var $SymbolToString = callBound('Symbol.prototype.toString', true); - -var $floor = Math.floor; -var $abs = Math.abs; - -var $ObjectCreate = $Object.create; -var $gOPD = $Object.getOwnPropertyDescriptor; -var $gOPN = $Object.getOwnPropertyNames; -var $gOPS = $Object.getOwnPropertySymbols; -var $isExtensible = $Object.isExtensible; -var $defineProperty = $Object.defineProperty; -var $setProto = require('./helpers/setProto'); - -var DefineOwnProperty = function DefineOwnProperty(ES, O, P, desc) { - if (!$defineProperty) { - if (!ES.IsDataDescriptor(desc)) { - // ES3 does not support getters/setters - return false; - } - if (!desc['[[Configurable]]'] || !desc['[[Writable]]']) { - return false; - } - - // fallback for ES3 - if (P in O && $isEnumerable(O, P) !== !!desc['[[Enumerable]]']) { - // a non-enumerable existing property - return false; - } - - // property does not exist at all, or exists but is enumerable - var V = desc['[[Value]]']; - O[P] = V; // will use [[Define]] - return ES.SameValue(O[P], V); - } - $defineProperty(O, P, ES.FromPropertyDescriptor(desc)); - return true; -}; - -// whitespace from: https://es5.github.io/#x15.5.4.20 -// implementation from https://github.com/es-shims/es5-shim/blob/v3.4.0/es5-shim.js#L1304-L1324 -var ws = [ - '\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003', - '\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028', - '\u2029\uFEFF' -].join(''); -var trimRegex = new RegExp('(^[' + ws + ']+)|([' + ws + ']+$)', 'g'); -var $replace = callBound('String.prototype.replace'); -var trim = function (value) { - return $replace(value, trimRegex, ''); -}; - -var ES5 = require('./es5'); - -var hasRegExpMatcher = require('is-regex'); - -// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-abstract-operations -var ES6 = assign(assign({}, ES5), { - - // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-call-f-v-args - Call: function Call(F, V) { - var args = arguments.length > 2 ? arguments[2] : []; - if (!this.IsCallable(F)) { - throw new $TypeError(inspect(F) + ' is not a function'); - } - return F.apply(V, args); - }, - - // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-toprimitive - ToPrimitive: toPrimitive, - - // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-toboolean - // ToBoolean: ES5.ToBoolean, - - // https://ecma-international.org/ecma-262/6.0/#sec-tonumber - ToNumber: function ToNumber(argument) { - var value = isPrimitive(argument) ? argument : toPrimitive(argument, $Number); - if (typeof value === 'symbol') { - throw new $TypeError('Cannot convert a Symbol value to a number'); - } - if (typeof value === 'string') { - if (isBinary(value)) { - return this.ToNumber(parseInteger(strSlice(value, 2), 2)); - } else if (isOctal(value)) { - return this.ToNumber(parseInteger(strSlice(value, 2), 8)); - } else if (hasNonWS(value) || isInvalidHexLiteral(value)) { - return NaN; - } else { - var trimmed = trim(value); - if (trimmed !== value) { - return this.ToNumber(trimmed); - } - } - } - return $Number(value); - }, - - // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tointeger - // ToInteger: ES5.ToNumber, - - // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-toint32 - // ToInt32: ES5.ToInt32, - - // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-touint32 - // ToUint32: ES5.ToUint32, - - // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-toint16 - ToInt16: function ToInt16(argument) { - var int16bit = this.ToUint16(argument); - return int16bit >= 0x8000 ? int16bit - 0x10000 : int16bit; - }, - - // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-touint16 - // ToUint16: ES5.ToUint16, - - // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-toint8 - ToInt8: function ToInt8(argument) { - var int8bit = this.ToUint8(argument); - return int8bit >= 0x80 ? int8bit - 0x100 : int8bit; - }, - - // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-touint8 - ToUint8: function ToUint8(argument) { - var number = this.ToNumber(argument); - if ($isNaN(number) || number === 0 || !$isFinite(number)) { return 0; } - var posInt = sign(number) * $floor($abs(number)); - return mod(posInt, 0x100); - }, - - // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-touint8clamp - ToUint8Clamp: function ToUint8Clamp(argument) { - var number = this.ToNumber(argument); - if ($isNaN(number) || number <= 0) { return 0; } - if (number >= 0xFF) { return 0xFF; } - var f = $floor(argument); - if (f + 0.5 < number) { return f + 1; } - if (number < f + 0.5) { return f; } - if (f % 2 !== 0) { return f + 1; } - return f; - }, - - // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tostring - ToString: function ToString(argument) { - if (typeof argument === 'symbol') { - throw new $TypeError('Cannot convert a Symbol value to a string'); - } - return $String(argument); - }, - - // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-toobject - ToObject: function ToObject(value) { - this.RequireObjectCoercible(value); - return $Object(value); - }, - - // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-topropertykey - ToPropertyKey: function ToPropertyKey(argument) { - var key = this.ToPrimitive(argument, $String); - return typeof key === 'symbol' ? key : this.ToString(key); - }, - - // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength - ToLength: function ToLength(argument) { - var len = this.ToInteger(argument); - if (len <= 0) { return 0; } // includes converting -0 to +0 - if (len > MAX_SAFE_INTEGER) { return MAX_SAFE_INTEGER; } - return len; - }, - - // https://ecma-international.org/ecma-262/6.0/#sec-canonicalnumericindexstring - CanonicalNumericIndexString: function CanonicalNumericIndexString(argument) { - if (toStr(argument) !== '[object String]') { - throw new $TypeError('must be a string'); - } - if (argument === '-0') { return -0; } - var n = this.ToNumber(argument); - if (this.SameValue(this.ToString(n), argument)) { return n; } - return void 0; - }, - - // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-requireobjectcoercible - RequireObjectCoercible: ES5.CheckObjectCoercible, - - // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-isarray - IsArray: $Array.isArray || function IsArray(argument) { - return toStr(argument) === '[object Array]'; - }, - - // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-iscallable - // IsCallable: ES5.IsCallable, - - // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-isconstructor - IsConstructor: function IsConstructor(argument) { - return typeof argument === 'function' && !!argument.prototype; // unfortunately there's no way to truly check this without try/catch `new argument` or Proxy - }, - - // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-isextensible-o - IsExtensible: $preventExtensions - ? function IsExtensible(obj) { - if (isPrimitive(obj)) { - return false; - } - return $isExtensible(obj); - } - : function isExtensible(obj) { return true; }, // eslint-disable-line no-unused-vars - - // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-isinteger - IsInteger: function IsInteger(argument) { - if (typeof argument !== 'number' || $isNaN(argument) || !$isFinite(argument)) { - return false; - } - var abs = $abs(argument); - return $floor(abs) === abs; - }, - - // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-ispropertykey - IsPropertyKey: function IsPropertyKey(argument) { - return typeof argument === 'string' || typeof argument === 'symbol'; - }, - - // https://ecma-international.org/ecma-262/6.0/#sec-isregexp - IsRegExp: function IsRegExp(argument) { - if (!argument || typeof argument !== 'object') { - return false; - } - if (hasSymbols) { - var isRegExp = argument[$Symbol.match]; - if (typeof isRegExp !== 'undefined') { - return ES5.ToBoolean(isRegExp); - } - } - return hasRegExpMatcher(argument); - }, - - // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevalue - // SameValue: ES5.SameValue, - - // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero - SameValueZero: function SameValueZero(x, y) { - return (x === y) || ($isNaN(x) && $isNaN(y)); - }, - - /** - * 7.3.2 GetV (V, P) - * 1. Assert: IsPropertyKey(P) is true. - * 2. Let O be ToObject(V). - * 3. ReturnIfAbrupt(O). - * 4. Return O.[[Get]](P, V). - */ - GetV: function GetV(V, P) { - // 7.3.2.1 - if (!this.IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true'); - } - - // 7.3.2.2-3 - var O = this.ToObject(V); - - // 7.3.2.4 - return O[P]; - }, - - /** - * 7.3.9 - https://ecma-international.org/ecma-262/6.0/#sec-getmethod - * 1. Assert: IsPropertyKey(P) is true. - * 2. Let func be GetV(O, P). - * 3. ReturnIfAbrupt(func). - * 4. If func is either undefined or null, return undefined. - * 5. If IsCallable(func) is false, throw a TypeError exception. - * 6. Return func. - */ - GetMethod: function GetMethod(O, P) { - // 7.3.9.1 - if (!this.IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true'); - } - - // 7.3.9.2 - var func = this.GetV(O, P); - - // 7.3.9.4 - if (func == null) { - return void 0; - } - - // 7.3.9.5 - if (!this.IsCallable(func)) { - throw new $TypeError(P + 'is not a function'); - } - - // 7.3.9.6 - return func; - }, - - /** - * 7.3.1 Get (O, P) - https://ecma-international.org/ecma-262/6.0/#sec-get-o-p - * 1. Assert: Type(O) is Object. - * 2. Assert: IsPropertyKey(P) is true. - * 3. Return O.[[Get]](P, O). - */ - Get: function Get(O, P) { - // 7.3.1.1 - if (this.Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - // 7.3.1.2 - if (!this.IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true, got ' + inspect(P)); - } - // 7.3.1.3 - return O[P]; - }, - - Type: function Type(x) { - if (typeof x === 'symbol') { - return 'Symbol'; - } - return ES5.Type(x); - }, - - // https://ecma-international.org/ecma-262/6.0/#sec-speciesconstructor - SpeciesConstructor: function SpeciesConstructor(O, defaultConstructor) { - if (this.Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - var C = O.constructor; - if (typeof C === 'undefined') { - return defaultConstructor; - } - if (this.Type(C) !== 'Object') { - throw new $TypeError('O.constructor is not an Object'); - } - var S = hasSymbols && $Symbol.species ? C[$Symbol.species] : void 0; - if (S == null) { - return defaultConstructor; - } - if (this.IsConstructor(S)) { - return S; - } - throw new $TypeError('no constructor found'); - }, - - // https://www.ecma-international.org/ecma-262/6.0/#sec-frompropertydescriptor - FromPropertyDescriptor: function FromPropertyDescriptor(Desc) { - if (typeof Desc === 'undefined') { - return Desc; - } - - assertRecord(this, 'Property Descriptor', 'Desc', Desc); - - var obj = {}; - if ('[[Value]]' in Desc) { - obj.value = Desc['[[Value]]']; - } - if ('[[Writable]]' in Desc) { - obj.writable = Desc['[[Writable]]']; - } - if ('[[Get]]' in Desc) { - obj.get = Desc['[[Get]]']; - } - if ('[[Set]]' in Desc) { - obj.set = Desc['[[Set]]']; - } - if ('[[Enumerable]]' in Desc) { - obj.enumerable = Desc['[[Enumerable]]']; - } - if ('[[Configurable]]' in Desc) { - obj.configurable = Desc['[[Configurable]]']; - } - return obj; - }, - - // https://ecma-international.org/ecma-262/6.0/#sec-completepropertydescriptor - CompletePropertyDescriptor: function CompletePropertyDescriptor(Desc) { - assertRecord(this, 'Property Descriptor', 'Desc', Desc); - - if (this.IsGenericDescriptor(Desc) || this.IsDataDescriptor(Desc)) { - if (!has(Desc, '[[Value]]')) { - Desc['[[Value]]'] = void 0; - } - if (!has(Desc, '[[Writable]]')) { - Desc['[[Writable]]'] = false; - } - } else { - if (!has(Desc, '[[Get]]')) { - Desc['[[Get]]'] = void 0; - } - if (!has(Desc, '[[Set]]')) { - Desc['[[Set]]'] = void 0; - } - } - if (!has(Desc, '[[Enumerable]]')) { - Desc['[[Enumerable]]'] = false; - } - if (!has(Desc, '[[Configurable]]')) { - Desc['[[Configurable]]'] = false; - } - return Desc; - }, - - // https://ecma-international.org/ecma-262/6.0/#sec-set-o-p-v-throw - Set: function Set(O, P, V, Throw) { - if (this.Type(O) !== 'Object') { - throw new $TypeError('O must be an Object'); - } - if (!this.IsPropertyKey(P)) { - throw new $TypeError('P must be a Property Key'); - } - if (this.Type(Throw) !== 'Boolean') { - throw new $TypeError('Throw must be a Boolean'); - } - if (Throw) { - O[P] = V; - return true; - } else { - try { - O[P] = V; - } catch (e) { - return false; - } - } - }, - - // https://ecma-international.org/ecma-262/6.0/#sec-hasownproperty - HasOwnProperty: function HasOwnProperty(O, P) { - if (this.Type(O) !== 'Object') { - throw new $TypeError('O must be an Object'); - } - if (!this.IsPropertyKey(P)) { - throw new $TypeError('P must be a Property Key'); - } - return has(O, P); - }, - - // https://ecma-international.org/ecma-262/6.0/#sec-hasproperty - HasProperty: function HasProperty(O, P) { - if (this.Type(O) !== 'Object') { - throw new $TypeError('O must be an Object'); - } - if (!this.IsPropertyKey(P)) { - throw new $TypeError('P must be a Property Key'); - } - return P in O; - }, - - // https://ecma-international.org/ecma-262/6.0/#sec-isconcatspreadable - IsConcatSpreadable: function IsConcatSpreadable(O) { - if (this.Type(O) !== 'Object') { - return false; - } - if (hasSymbols && typeof $Symbol.isConcatSpreadable === 'symbol') { - var spreadable = this.Get(O, Symbol.isConcatSpreadable); - if (typeof spreadable !== 'undefined') { - return this.ToBoolean(spreadable); - } - } - return this.IsArray(O); - }, - - // https://ecma-international.org/ecma-262/6.0/#sec-invoke - Invoke: function Invoke(O, P) { - if (!this.IsPropertyKey(P)) { - throw new $TypeError('P must be a Property Key'); - } - var argumentsList = arraySlice(arguments, 2); - var func = this.GetV(O, P); - return this.Call(func, O, argumentsList); - }, - - // https://ecma-international.org/ecma-262/6.0/#sec-getiterator - GetIterator: function GetIterator(obj, method) { - var actualMethod = method; - if (arguments.length < 2) { - actualMethod = getIteratorMethod(this, obj); - } - var iterator = this.Call(actualMethod, obj); - if (this.Type(iterator) !== 'Object') { - throw new $TypeError('iterator must return an object'); - } - - return iterator; - }, - - // https://ecma-international.org/ecma-262/6.0/#sec-iteratornext - IteratorNext: function IteratorNext(iterator, value) { - var result = this.Invoke(iterator, 'next', arguments.length < 2 ? [] : [value]); - if (this.Type(result) !== 'Object') { - throw new $TypeError('iterator next must return an object'); - } - return result; - }, - - // https://ecma-international.org/ecma-262/6.0/#sec-iteratorcomplete - IteratorComplete: function IteratorComplete(iterResult) { - if (this.Type(iterResult) !== 'Object') { - throw new $TypeError('Assertion failed: Type(iterResult) is not Object'); - } - return this.ToBoolean(this.Get(iterResult, 'done')); - }, - - // https://ecma-international.org/ecma-262/6.0/#sec-iteratorvalue - IteratorValue: function IteratorValue(iterResult) { - if (this.Type(iterResult) !== 'Object') { - throw new $TypeError('Assertion failed: Type(iterResult) is not Object'); - } - return this.Get(iterResult, 'value'); - }, - - // https://ecma-international.org/ecma-262/6.0/#sec-iteratorstep - IteratorStep: function IteratorStep(iterator) { - var result = this.IteratorNext(iterator); - var done = this.IteratorComplete(result); - return done === true ? false : result; - }, - - // https://ecma-international.org/ecma-262/6.0/#sec-iteratorclose - IteratorClose: function IteratorClose(iterator, completion) { - if (this.Type(iterator) !== 'Object') { - throw new $TypeError('Assertion failed: Type(iterator) is not Object'); - } - if (!this.IsCallable(completion)) { - throw new $TypeError('Assertion failed: completion is not a thunk for a Completion Record'); - } - var completionThunk = completion; - - var iteratorReturn = this.GetMethod(iterator, 'return'); - - if (typeof iteratorReturn === 'undefined') { - return completionThunk(); - } - - var completionRecord; - try { - var innerResult = this.Call(iteratorReturn, iterator, []); - } catch (e) { - // if we hit here, then "e" is the innerResult completion that needs re-throwing - - // if the completion is of type "throw", this will throw. - completionRecord = completionThunk(); - completionThunk = null; // ensure it's not called twice. - - // if not, then return the innerResult completion - throw e; - } - completionRecord = completionThunk(); // if innerResult worked, then throw if the completion does - completionThunk = null; // ensure it's not called twice. - - if (this.Type(innerResult) !== 'Object') { - throw new $TypeError('iterator .return must return an object'); - } - - return completionRecord; - }, - - // https://ecma-international.org/ecma-262/6.0/#sec-createiterresultobject - CreateIterResultObject: function CreateIterResultObject(value, done) { - if (this.Type(done) !== 'Boolean') { - throw new $TypeError('Assertion failed: Type(done) is not Boolean'); - } - return { - value: value, - done: done - }; - }, - - // https://ecma-international.org/ecma-262/6.0/#sec-regexpexec - RegExpExec: function RegExpExec(R, S) { - if (this.Type(R) !== 'Object') { - throw new $TypeError('R must be an Object'); - } - if (this.Type(S) !== 'String') { - throw new $TypeError('S must be a String'); - } - var exec = this.Get(R, 'exec'); - if (this.IsCallable(exec)) { - var result = this.Call(exec, R, [S]); - if (result === null || this.Type(result) === 'Object') { - return result; - } - throw new $TypeError('"exec" method must return `null` or an Object'); - } - return regexExec(R, S); - }, - - // https://ecma-international.org/ecma-262/6.0/#sec-arrayspeciescreate - ArraySpeciesCreate: function ArraySpeciesCreate(originalArray, length) { - if (!this.IsInteger(length) || length < 0) { - throw new $TypeError('Assertion failed: length must be an integer >= 0'); - } - var len = length === 0 ? 0 : length; - var C; - var isArray = this.IsArray(originalArray); - if (isArray) { - C = this.Get(originalArray, 'constructor'); - // TODO: figure out how to make a cross-realm normal Array, a same-realm Array - // if (this.IsConstructor(C)) { - // if C is another realm's Array, C = undefined - // Object.getPrototypeOf(Object.getPrototypeOf(Object.getPrototypeOf(Array))) === null ? - // } - if (this.Type(C) === 'Object' && hasSymbols && $Symbol.species) { - C = this.Get(C, $Symbol.species); - if (C === null) { - C = void 0; - } - } - } - if (typeof C === 'undefined') { - return $Array(len); - } - if (!this.IsConstructor(C)) { - throw new $TypeError('C must be a constructor'); - } - return new C(len); // this.Construct(C, len); - }, - - CreateDataProperty: function CreateDataProperty(O, P, V) { - if (this.Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - if (!this.IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true'); - } - var oldDesc = $gOPD(O, P); - var extensible = oldDesc || this.IsExtensible(O); - var immutable = oldDesc && (!oldDesc.writable || !oldDesc.configurable); - if (immutable || !extensible) { - return false; - } - return DefineOwnProperty(this, O, P, { - '[[Configurable]]': true, - '[[Enumerable]]': true, - '[[Value]]': V, - '[[Writable]]': true - }); - }, - - // https://ecma-international.org/ecma-262/6.0/#sec-createdatapropertyorthrow - CreateDataPropertyOrThrow: function CreateDataPropertyOrThrow(O, P, V) { - if (this.Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - if (!this.IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true'); - } - var success = this.CreateDataProperty(O, P, V); - if (!success) { - throw new $TypeError('unable to create data property'); - } - return success; - }, - - // https://www.ecma-international.org/ecma-262/6.0/#sec-objectcreate - ObjectCreate: function ObjectCreate(proto, internalSlotsList) { - if (proto !== null && this.Type(proto) !== 'Object') { - throw new $TypeError('Assertion failed: proto must be null or an object'); - } - var slots = arguments.length < 2 ? [] : internalSlotsList; - if (slots.length > 0) { - throw new $SyntaxError('es-abstract does not yet support internal slots'); - } - - if (proto === null && !$ObjectCreate) { - throw new $SyntaxError('native Object.create support is required to create null objects'); - } - - return $ObjectCreate(proto); - }, - - // https://ecma-international.org/ecma-262/6.0/#sec-advancestringindex - AdvanceStringIndex: function AdvanceStringIndex(S, index, unicode) { - if (this.Type(S) !== 'String') { - throw new $TypeError('S must be a String'); - } - if (!this.IsInteger(index) || index < 0 || index > MAX_SAFE_INTEGER) { - throw new $TypeError('Assertion failed: length must be an integer >= 0 and <= 2**53'); - } - if (this.Type(unicode) !== 'Boolean') { - throw new $TypeError('Assertion failed: unicode must be a Boolean'); - } - if (!unicode) { - return index + 1; - } - var length = S.length; - if ((index + 1) >= length) { - return index + 1; - } - - var first = $charCodeAt(S, index); - if (first < 0xD800 || first > 0xDBFF) { - return index + 1; - } - - var second = $charCodeAt(S, index + 1); - if (second < 0xDC00 || second > 0xDFFF) { - return index + 1; - } - - return index + 2; - }, - - // https://www.ecma-international.org/ecma-262/6.0/#sec-createmethodproperty - CreateMethodProperty: function CreateMethodProperty(O, P, V) { - if (this.Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - - if (!this.IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true'); - } - - var newDesc = { - '[[Configurable]]': true, - '[[Enumerable]]': false, - '[[Value]]': V, - '[[Writable]]': true - }; - return DefineOwnProperty(this, O, P, newDesc); - }, - - // https://www.ecma-international.org/ecma-262/6.0/#sec-definepropertyorthrow - DefinePropertyOrThrow: function DefinePropertyOrThrow(O, P, desc) { - if (this.Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - - if (!this.IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true'); - } - - var Desc = isPropertyDescriptor(this, desc) ? desc : this.ToPropertyDescriptor(desc); - if (!isPropertyDescriptor(this, Desc)) { - throw new $TypeError('Assertion failed: Desc is not a valid Property Descriptor'); - } - - return DefineOwnProperty(this, O, P, Desc); - }, - - // https://www.ecma-international.org/ecma-262/6.0/#sec-deletepropertyorthrow - DeletePropertyOrThrow: function DeletePropertyOrThrow(O, P) { - if (this.Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - - if (!this.IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: IsPropertyKey(P) is not true'); - } - - var success = delete O[P]; - if (!success) { - throw new TypeError('Attempt to delete property failed.'); - } - return success; - }, - - // https://www.ecma-international.org/ecma-262/6.0/#sec-enumerableownnames - EnumerableOwnNames: function EnumerableOwnNames(O) { - if (this.Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - - return keys(O); - }, - - // https://ecma-international.org/ecma-262/6.0/#sec-properties-of-the-number-prototype-object - thisNumberValue: function thisNumberValue(value) { - if (this.Type(value) === 'Number') { - return value; - } - - return $NumberValueOf(value); - }, - - // https://ecma-international.org/ecma-262/6.0/#sec-properties-of-the-boolean-prototype-object - thisBooleanValue: function thisBooleanValue(value) { - if (this.Type(value) === 'Boolean') { - return value; - } - - return $BooleanValueOf(value); - }, - - // https://ecma-international.org/ecma-262/6.0/#sec-properties-of-the-string-prototype-object - thisStringValue: function thisStringValue(value) { - if (this.Type(value) === 'String') { - return value; - } - - return $StringValueOf(value); - }, - - // https://ecma-international.org/ecma-262/6.0/#sec-properties-of-the-date-prototype-object - thisTimeValue: function thisTimeValue(value) { - return $DateValueOf(value); - }, - - // https://www.ecma-international.org/ecma-262/6.0/#sec-setintegritylevel - SetIntegrityLevel: function SetIntegrityLevel(O, level) { - if (this.Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - if (level !== 'sealed' && level !== 'frozen') { - throw new $TypeError('Assertion failed: `level` must be `"sealed"` or `"frozen"`'); - } - if (!$preventExtensions) { - throw new $SyntaxError('SetIntegrityLevel requires native `Object.preventExtensions` support'); - } - var status = $preventExtensions(O); - if (!status) { - return false; - } - if (!$gOPN) { - throw new $SyntaxError('SetIntegrityLevel requires native `Object.getOwnPropertyNames` support'); - } - var theKeys = $gOPN(O); - var ES = this; - if (level === 'sealed') { - forEach(theKeys, function (k) { - ES.DefinePropertyOrThrow(O, k, { configurable: false }); - }); - } else if (level === 'frozen') { - forEach(theKeys, function (k) { - var currentDesc = $gOPD(O, k); - if (typeof currentDesc !== 'undefined') { - var desc; - if (ES.IsAccessorDescriptor(ES.ToPropertyDescriptor(currentDesc))) { - desc = { configurable: false }; - } else { - desc = { configurable: false, writable: false }; - } - ES.DefinePropertyOrThrow(O, k, desc); - } - }); - } - return true; - }, - - // https://www.ecma-international.org/ecma-262/6.0/#sec-testintegritylevel - TestIntegrityLevel: function TestIntegrityLevel(O, level) { - if (this.Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - if (level !== 'sealed' && level !== 'frozen') { - throw new $TypeError('Assertion failed: `level` must be `"sealed"` or `"frozen"`'); - } - var status = this.IsExtensible(O); - if (status) { - return false; - } - var theKeys = $gOPN(O); - var ES = this; - return theKeys.length === 0 || every(theKeys, function (k) { - var currentDesc = $gOPD(O, k); - if (typeof currentDesc !== 'undefined') { - if (currentDesc.configurable) { - return false; - } - if (level === 'frozen' && ES.IsDataDescriptor(ES.ToPropertyDescriptor(currentDesc)) && currentDesc.writable) { - return false; - } - } - return true; - }); - }, - - // https://www.ecma-international.org/ecma-262/6.0/#sec-ordinaryhasinstance - OrdinaryHasInstance: function OrdinaryHasInstance(C, O) { - if (this.IsCallable(C) === false) { - return false; - } - if (this.Type(O) !== 'Object') { - return false; - } - var P = this.Get(C, 'prototype'); - if (this.Type(P) !== 'Object') { - throw new $TypeError('OrdinaryHasInstance called on an object with an invalid prototype property.'); - } - return O instanceof C; - }, - - // https://www.ecma-international.org/ecma-262/6.0/#sec-ordinaryhasproperty - OrdinaryHasProperty: function OrdinaryHasProperty(O, P) { - if (this.Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - if (!this.IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: P must be a Property Key'); - } - return P in O; - }, - - // https://www.ecma-international.org/ecma-262/6.0/#sec-instanceofoperator - InstanceofOperator: function InstanceofOperator(O, C) { - if (this.Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - var instOfHandler = hasSymbols && $Symbol.hasInstance ? this.GetMethod(C, $Symbol.hasInstance) : void 0; - if (typeof instOfHandler !== 'undefined') { - return this.ToBoolean(this.Call(instOfHandler, C, [O])); - } - if (!this.IsCallable(C)) { - throw new $TypeError('`C` is not Callable'); - } - return this.OrdinaryHasInstance(C, O); - }, - - // https://www.ecma-international.org/ecma-262/6.0/#sec-ispromise - IsPromise: function IsPromise(x) { - if (this.Type(x) !== 'Object') { - return false; - } - if (!$PromiseThen) { // Promises are not supported - return false; - } - try { - $PromiseThen(x); // throws if not a promise - } catch (e) { - return false; - } - return true; - }, - - // https://www.ecma-international.org/ecma-262/6.0/#sec-abstract-equality-comparison - 'Abstract Equality Comparison': function AbstractEqualityComparison(x, y) { - var xType = this.Type(x); - var yType = this.Type(y); - if (xType === yType) { - return x === y; // ES6+ specified this shortcut anyways. - } - if (x == null && y == null) { - return true; - } - if (xType === 'Number' && yType === 'String') { - return this['Abstract Equality Comparison'](x, this.ToNumber(y)); - } - if (xType === 'String' && yType === 'Number') { - return this['Abstract Equality Comparison'](this.ToNumber(x), y); - } - if (xType === 'Boolean') { - return this['Abstract Equality Comparison'](this.ToNumber(x), y); - } - if (yType === 'Boolean') { - return this['Abstract Equality Comparison'](x, this.ToNumber(y)); - } - if ((xType === 'String' || xType === 'Number' || xType === 'Symbol') && yType === 'Object') { - return this['Abstract Equality Comparison'](x, this.ToPrimitive(y)); - } - if (xType === 'Object' && (yType === 'String' || yType === 'Number' || yType === 'Symbol')) { - return this['Abstract Equality Comparison'](this.ToPrimitive(x), y); - } - return false; - }, - - // eslint-disable-next-line max-lines-per-function, max-statements, id-length, max-params - ValidateAndApplyPropertyDescriptor: function ValidateAndApplyPropertyDescriptor(O, P, extensible, Desc, current) { - // this uses the ES2017+ logic, since it fixes a number of bugs in the ES2015 logic. - var oType = this.Type(O); - if (oType !== 'Undefined' && oType !== 'Object') { - throw new $TypeError('Assertion failed: O must be undefined or an Object'); - } - if (this.Type(extensible) !== 'Boolean') { - throw new $TypeError('Assertion failed: extensible must be a Boolean'); - } - if (!isPropertyDescriptor(this, Desc)) { - throw new $TypeError('Assertion failed: Desc must be a Property Descriptor'); - } - if (this.Type(current) !== 'Undefined' && !isPropertyDescriptor(this, current)) { - throw new $TypeError('Assertion failed: current must be a Property Descriptor, or undefined'); - } - if (oType !== 'Undefined' && !this.IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: if O is not undefined, P must be a Property Key'); - } - if (this.Type(current) === 'Undefined') { - if (!extensible) { - return false; - } - if (this.IsGenericDescriptor(Desc) || this.IsDataDescriptor(Desc)) { - if (oType !== 'Undefined') { - DefineOwnProperty(this, O, P, { - '[[Configurable]]': Desc['[[Configurable]]'], - '[[Enumerable]]': Desc['[[Enumerable]]'], - '[[Value]]': Desc['[[Value]]'], - '[[Writable]]': Desc['[[Writable]]'] - }); - } - } else { - if (!this.IsAccessorDescriptor(Desc)) { - throw new $TypeError('Assertion failed: Desc is not an accessor descriptor'); - } - if (oType !== 'Undefined') { - return DefineOwnProperty(this, O, P, Desc); - } - } - return true; - } - if (this.IsGenericDescriptor(Desc) && !('[[Configurable]]' in Desc) && !('[[Enumerable]]' in Desc)) { - return true; - } - if (isSamePropertyDescriptor(this, Desc, current)) { - return true; // removed by ES2017, but should still be correct - } - // "if every field in Desc is absent, return true" can't really match the assertion that it's a Property Descriptor - if (!current['[[Configurable]]']) { - if (Desc['[[Configurable]]']) { - return false; - } - if ('[[Enumerable]]' in Desc && !Desc['[[Enumerable]]'] === !!current['[[Enumerable]]']) { - return false; - } - } - if (this.IsGenericDescriptor(Desc)) { - // no further validation is required. - } else if (this.IsDataDescriptor(current) !== this.IsDataDescriptor(Desc)) { - if (!current['[[Configurable]]']) { - return false; - } - if (this.IsDataDescriptor(current)) { - if (oType !== 'Undefined') { - DefineOwnProperty(this, O, P, { - '[[Configurable]]': current['[[Configurable]]'], - '[[Enumerable]]': current['[[Enumerable]]'], - '[[Get]]': undefined - }); - } - } else if (oType !== 'Undefined') { - DefineOwnProperty(this, O, P, { - '[[Configurable]]': current['[[Configurable]]'], - '[[Enumerable]]': current['[[Enumerable]]'], - '[[Value]]': undefined - }); - } - } else if (this.IsDataDescriptor(current) && this.IsDataDescriptor(Desc)) { - if (!current['[[Configurable]]'] && !current['[[Writable]]']) { - if ('[[Writable]]' in Desc && Desc['[[Writable]]']) { - return false; - } - if ('[[Value]]' in Desc && !this.SameValue(Desc['[[Value]]'], current['[[Value]]'])) { - return false; - } - return true; - } - } else if (this.IsAccessorDescriptor(current) && this.IsAccessorDescriptor(Desc)) { - if (!current['[[Configurable]]']) { - if ('[[Set]]' in Desc && !this.SameValue(Desc['[[Set]]'], current['[[Set]]'])) { - return false; - } - if ('[[Get]]' in Desc && !this.SameValue(Desc['[[Get]]'], current['[[Get]]'])) { - return false; - } - return true; - } - } else { - throw new $TypeError('Assertion failed: current and Desc are not both data, both accessors, or one accessor and one data.'); - } - if (oType !== 'Undefined') { - return DefineOwnProperty(this, O, P, Desc); - } - return true; - }, - - // https://www.ecma-international.org/ecma-262/6.0/#sec-ordinarydefineownproperty - OrdinaryDefineOwnProperty: function OrdinaryDefineOwnProperty(O, P, Desc) { - if (this.Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: O must be an Object'); - } - if (!this.IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: P must be a Property Key'); - } - if (!isPropertyDescriptor(this, Desc)) { - throw new $TypeError('Assertion failed: Desc must be a Property Descriptor'); - } - var desc = $gOPD(O, P); - var current = desc && this.ToPropertyDescriptor(desc); - var extensible = this.IsExtensible(O); - return this.ValidateAndApplyPropertyDescriptor(O, P, extensible, Desc, current); - }, - - // https://www.ecma-international.org/ecma-262/6.0/#sec-ordinarygetownproperty - OrdinaryGetOwnProperty: function OrdinaryGetOwnProperty(O, P) { - if (this.Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: O must be an Object'); - } - if (!this.IsPropertyKey(P)) { - throw new $TypeError('Assertion failed: P must be a Property Key'); - } - if (!has(O, P)) { - return void 0; - } - if (!$gOPD) { - // ES3 fallback - var arrayLength = this.IsArray(O) && P === 'length'; - var regexLastIndex = this.IsRegExp(O) && P === 'lastIndex'; - return { - '[[Configurable]]': !(arrayLength || regexLastIndex), - '[[Enumerable]]': $isEnumerable(O, P), - '[[Value]]': O[P], - '[[Writable]]': true - }; - } - return this.ToPropertyDescriptor($gOPD(O, P)); - }, - - // https://www.ecma-international.org/ecma-262/6.0/#sec-arraycreate - ArrayCreate: function ArrayCreate(length) { - if (!this.IsInteger(length) || length < 0) { - throw new $TypeError('Assertion failed: `length` must be an integer Number >= 0'); - } - if (length > MAX_ARRAY_LENGTH) { - throw new $RangeError('length is greater than (2**32 - 1)'); - } - var proto = arguments.length > 1 ? arguments[1] : $ArrayPrototype; - var A = []; // steps 5 - 7, and 9 - if (proto !== $ArrayPrototype) { // step 8 - if (!$setProto) { - throw new $SyntaxError('ArrayCreate: a `proto` argument that is not `Array.prototype` is not supported in an environment that does not support setting the [[Prototype]]'); - } - $setProto(A, proto); - } - if (length !== 0) { // bypasses the need for step 2 - A.length = length; - } - /* step 10, the above as a shortcut for the below - this.OrdinaryDefineOwnProperty(A, 'length', { - '[[Configurable]]': false, - '[[Enumerable]]': false, - '[[Value]]': length, - '[[Writable]]': true - }); - */ - return A; - }, - - // eslint-disable-next-line max-statements, max-lines-per-function - ArraySetLength: function ArraySetLength(A, Desc) { - if (!this.IsArray(A)) { - throw new $TypeError('Assertion failed: A must be an Array'); - } - if (!isPropertyDescriptor(this, Desc)) { - throw new $TypeError('Assertion failed: Desc must be a Property Descriptor'); - } - if (!('[[Value]]' in Desc)) { - return this.OrdinaryDefineOwnProperty(A, 'length', Desc); - } - var newLenDesc = assign({}, Desc); - var newLen = this.ToUint32(Desc['[[Value]]']); - var numberLen = this.ToNumber(Desc['[[Value]]']); - if (newLen !== numberLen) { - throw new $RangeError('Invalid array length'); - } - newLenDesc['[[Value]]'] = newLen; - var oldLenDesc = this.OrdinaryGetOwnProperty(A, 'length'); - if (!this.IsDataDescriptor(oldLenDesc)) { - throw new $TypeError('Assertion failed: an array had a non-data descriptor on `length`'); - } - var oldLen = oldLenDesc['[[Value]]']; - if (newLen >= oldLen) { - return this.OrdinaryDefineOwnProperty(A, 'length', newLenDesc); - } - if (!oldLenDesc['[[Writable]]']) { - return false; - } - var newWritable; - if (!('[[Writable]]' in newLenDesc) || newLenDesc['[[Writable]]']) { - newWritable = true; - } else { - newWritable = false; - newLenDesc['[[Writable]]'] = true; - } - var succeeded = this.OrdinaryDefineOwnProperty(A, 'length', newLenDesc); - if (!succeeded) { - return false; - } - while (newLen < oldLen) { - oldLen -= 1; - var deleteSucceeded = delete A[this.ToString(oldLen)]; - if (!deleteSucceeded) { - newLenDesc['[[Value]]'] = oldLen + 1; - if (!newWritable) { - newLenDesc['[[Writable]]'] = false; - this.OrdinaryDefineOwnProperty(A, 'length', newLenDesc); - return false; - } - } - } - if (!newWritable) { - return this.OrdinaryDefineOwnProperty(A, 'length', { '[[Writable]]': false }); - } - return true; - }, - - // https://www.ecma-international.org/ecma-262/6.0/#sec-createhtml - CreateHTML: function CreateHTML(string, tag, attribute, value) { - if (this.Type(tag) !== 'String' || this.Type(attribute) !== 'String') { - throw new $TypeError('Assertion failed: `tag` and `attribute` must be strings'); - } - var str = this.RequireObjectCoercible(string); - var S = this.ToString(str); - var p1 = '<' + tag; - if (attribute !== '') { - var V = this.ToString(value); - var escapedV = $replace(V, /\x22/g, '"'); - p1 += '\x20' + attribute + '\x3D\x22' + escapedV + '\x22'; - } - return p1 + '>' + S + ''; - }, - - // https://www.ecma-international.org/ecma-262/6.0/#sec-getownpropertykeys - GetOwnPropertyKeys: function GetOwnPropertyKeys(O, Type) { - if (this.Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: Type(O) is not Object'); - } - if (Type === 'Symbol') { - return hasSymbols && $gOPS ? $gOPS(O) : []; - } - if (Type === 'String') { - if (!$gOPN) { - return keys(O); - } - return $gOPN(O); - } - throw new $TypeError('Assertion failed: `Type` must be `"String"` or `"Symbol"`'); - }, - - // https://www.ecma-international.org/ecma-262/6.0/#sec-symboldescriptivestring - SymbolDescriptiveString: function SymbolDescriptiveString(sym) { - if (this.Type(sym) !== 'Symbol') { - throw new $TypeError('Assertion failed: `sym` must be a Symbol'); - } - return $SymbolToString(sym); - }, - - // https://www.ecma-international.org/ecma-262/6.0/#sec-getsubstitution - // eslint-disable-next-line max-statements, max-params, max-lines-per-function - GetSubstitution: function GetSubstitution(matched, str, position, captures, replacement) { - if (this.Type(matched) !== 'String') { - throw new $TypeError('Assertion failed: `matched` must be a String'); - } - var matchLength = matched.length; - - if (this.Type(str) !== 'String') { - throw new $TypeError('Assertion failed: `str` must be a String'); - } - var stringLength = str.length; - - if (!this.IsInteger(position) || position < 0 || position > stringLength) { - throw new $TypeError('Assertion failed: `position` must be a nonnegative integer, and less than or equal to the length of `string`, got ' + inspect(position)); - } - - var ES = this; - var isStringOrHole = function (capture, index, arr) { return ES.Type(capture) === 'String' || !(index in arr); }; - if (!this.IsArray(captures) || !every(captures, isStringOrHole)) { - throw new $TypeError('Assertion failed: `captures` must be a List of Strings, got ' + inspect(captures)); - } - - if (this.Type(replacement) !== 'String') { - throw new $TypeError('Assertion failed: `replacement` must be a String'); - } - - var tailPos = position + matchLength; - var m = captures.length; - - var result = ''; - for (var i = 0; i < replacement.length; i += 1) { - // if this is a $, and it's not the end of the replacement - var current = replacement[i]; - var isLast = (i + 1) >= replacement.length; - var nextIsLast = (i + 2) >= replacement.length; - if (current === '$' && !isLast) { - var next = replacement[i + 1]; - if (next === '$') { - result += '$'; - i += 1; - } else if (next === '&') { - result += matched; - i += 1; - } else if (next === '`') { - result += position === 0 ? '' : strSlice(str, 0, position - 1); - i += 1; - } else if (next === "'") { - result += tailPos >= stringLength ? '' : strSlice(str, tailPos); - i += 1; - } else { - var nextNext = nextIsLast ? null : replacement[i + 2]; - if (isDigit(next) && next !== '0' && (nextIsLast || !isDigit(nextNext))) { - // $1 through $9, and not followed by a digit - var n = parseInteger(next, 10); - // if (n > m, impl-defined) - result += (n <= m && this.Type(captures[n - 1]) === 'Undefined') ? '' : captures[n - 1]; - i += 1; - } else if (isDigit(next) && (nextIsLast || isDigit(nextNext))) { - // $00 through $99 - var nn = next + nextNext; - var nnI = parseInteger(nn, 10) - 1; - // if nn === '00' or nn > m, impl-defined - result += (nn <= m && this.Type(captures[nnI]) === 'Undefined') ? '' : captures[nnI]; - i += 2; - } else { - result += '$'; - } - } - } else { - // the final $, or else not a $ - result += replacement[i]; - } - } - return result; - }, - - // https://ecma-international.org/ecma-262/6.0/#sec-todatestring - ToDateString: function ToDateString(tv) { - if (this.Type(tv) !== 'Number') { - throw new $TypeError('Assertion failed: `tv` must be a Number'); - } - if ($isNaN(tv)) { - return 'Invalid Date'; - } - return $Date(tv); - }, - - // https://ecma-international.org/ecma-262/6.0/#sec-createlistfromarraylike - CreateListFromArrayLike: function CreateListFromArrayLike(obj) { - var elementTypes = arguments.length > 1 - ? arguments[1] - : ['Undefined', 'Null', 'Boolean', 'String', 'Symbol', 'Number', 'Object']; - - if (this.Type(obj) !== 'Object') { - throw new $TypeError('Assertion failed: `obj` must be an Object'); - } - if (!this.IsArray(elementTypes)) { - throw new $TypeError('Assertion failed: `elementTypes`, if provided, must be an array'); - } - var len = this.ToLength(this.Get(obj, 'length')); - var list = []; - var index = 0; - while (index < len) { - var indexName = this.ToString(index); - var next = this.Get(obj, indexName); - var nextType = this.Type(next); - if ($indexOf(elementTypes, nextType) < 0) { - throw new $TypeError('item type ' + nextType + ' is not a valid elementType'); - } - $push(list, next); - index += 1; - } - return list; - }, - - // https://ecma-international.org/ecma-262/6.0/#sec-getprototypefromconstructor - GetPrototypeFromConstructor: function GetPrototypeFromConstructor(constructor, intrinsicDefaultProto) { - var intrinsic = GetIntrinsic(intrinsicDefaultProto); // throws if not a valid intrinsic - if (!this.IsConstructor(constructor)) { - throw new $TypeError('Assertion failed: `constructor` must be a constructor'); - } - var proto = this.Get(constructor, 'prototype'); - if (this.Type(proto) !== 'Object') { - if (!(constructor instanceof $Function)) { - // ignore other realms, for now - throw new $TypeError('cross-realm constructors not currently supported'); - } - proto = intrinsic; - } - return proto; - }, - - // https://ecma-international.org/ecma-262/6.0/#sec-setfunctionname - SetFunctionName: function SetFunctionName(F, name) { - if (typeof F !== 'function') { - throw new $TypeError('Assertion failed: `F` must be a function'); - } - if (!this.IsExtensible(F) || has(F, 'name')) { - throw new $TypeError('Assertion failed: `F` must be extensible, and must not have a `name` own property'); - } - var nameType = this.Type(name); - if (nameType !== 'Symbol' && nameType !== 'String') { - throw new $TypeError('Assertion failed: `name` must be a Symbol or a String'); - } - if (nameType === 'Symbol') { - var description = getSymbolDescription(name); - // eslint-disable-next-line no-param-reassign - name = typeof description === 'undefined' ? '' : '[' + description + ']'; - } - if (arguments.length > 2) { - var prefix = arguments[2]; - // eslint-disable-next-line no-param-reassign - name = prefix + ' ' + name; - } - return this.DefinePropertyOrThrow(F, 'name', { - '[[Value]]': name, - '[[Writable]]': false, - '[[Enumerable]]': false, - '[[Configurable]]': true - }); - } -}); - -delete ES6.CheckObjectCoercible; // renamed in ES6 to RequireObjectCoercible - -module.exports = ES6; diff --git a/scripts/2.5/node_modules/es-abstract/es2016.js b/scripts/2.5/node_modules/es-abstract/es2016.js deleted file mode 100644 index 9b5f9d4d..00000000 --- a/scripts/2.5/node_modules/es-abstract/es2016.js +++ /dev/null @@ -1,98 +0,0 @@ -'use strict'; - -var ES2015 = require('./es2015'); -var GetIntrinsic = require('./GetIntrinsic'); -var assign = require('./helpers/assign'); -var $setProto = require('./helpers/setProto'); - -var callBound = require('./helpers/callBound'); -var getIteratorMethod = require('./helpers/getIteratorMethod'); - -var $TypeError = GetIntrinsic('%TypeError%'); -var $arrayPush = callBound('Array.prototype.push'); -var $getProto = require('./helpers/getProto'); - -var ES2016 = assign(assign({}, ES2015), { - // https://www.ecma-international.org/ecma-262/7.0/#sec-samevaluenonnumber - SameValueNonNumber: function SameValueNonNumber(x, y) { - if (typeof x === 'number' || typeof x !== typeof y) { - throw new TypeError('SameValueNonNumber requires two non-number values of the same type.'); - } - return this.SameValue(x, y); - }, - - // https://www.ecma-international.org/ecma-262/7.0/#sec-iterabletoarraylike - IterableToArrayLike: function IterableToArrayLike(items) { - var usingIterator = getIteratorMethod(this, items); - if (typeof usingIterator !== 'undefined') { - var iterator = this.GetIterator(items, usingIterator); - var values = []; - var next = true; - while (next) { - next = this.IteratorStep(iterator); - if (next) { - var nextValue = this.IteratorValue(next); - $arrayPush(values, nextValue); - } - } - return values; - } - - return this.ToObject(items); - }, - - // https://ecma-international.org/ecma-262/7.0/#sec-ordinarygetprototypeof - OrdinaryGetPrototypeOf: function (O) { - if (this.Type(O) !== 'Object') { - throw new $TypeError('Assertion failed: O must be an Object'); - } - if (!$getProto) { - throw new $TypeError('This environment does not support fetching prototypes.'); - } - return $getProto(O); - }, - - // https://ecma-international.org/ecma-262/7.0/#sec-ordinarysetprototypeof - OrdinarySetPrototypeOf: function (O, V) { - if (this.Type(V) !== 'Object' && this.Type(V) !== 'Null') { - throw new $TypeError('Assertion failed: V must be Object or Null'); - } - /* - var extensible = this.IsExtensible(O); - var current = this.OrdinaryGetPrototypeOf(O); - if (this.SameValue(V, current)) { - return true; - } - if (!extensible) { - return false; - } - */ - try { - $setProto(O, V); - } catch (e) { - return false; - } - return this.OrdinaryGetPrototypeOf(O) === V; - /* - var p = V; - var done = false; - while (!done) { - if (p === null) { - done = true; - } else if (this.SameValue(p, O)) { - return false; - } else { - if (wat) { - done = true; - } else { - p = p.[[Prototype]]; - } - } - } - O.[[Prototype]] = V; - return true; - */ - } -}); - -module.exports = ES2016; diff --git a/scripts/2.5/node_modules/es-abstract/es2017.js b/scripts/2.5/node_modules/es-abstract/es2017.js deleted file mode 100644 index 98039903..00000000 --- a/scripts/2.5/node_modules/es-abstract/es2017.js +++ /dev/null @@ -1,71 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('./GetIntrinsic'); - -var ES2016 = require('./es2016'); -var assign = require('./helpers/assign'); -var forEach = require('./helpers/forEach'); -var callBind = require('./helpers/callBind'); - -var $TypeError = GetIntrinsic('%TypeError%'); -var callBound = require('./helpers/callBound'); -var $isEnumerable = callBound('Object.prototype.propertyIsEnumerable'); -var $pushApply = callBind.apply(GetIntrinsic('%Array.prototype.push%')); -var $arrayPush = callBound('Array.prototype.push'); - -var ES2017 = assign(assign({}, ES2016), { - ToIndex: function ToIndex(value) { - if (typeof value === 'undefined') { - return 0; - } - var integerIndex = this.ToInteger(value); - if (integerIndex < 0) { - throw new RangeError('index must be >= 0'); - } - var index = this.ToLength(integerIndex); - if (!this.SameValueZero(integerIndex, index)) { - throw new RangeError('index must be >= 0 and < 2 ** 53 - 1'); - } - return index; - }, - - // https://www.ecma-international.org/ecma-262/8.0/#sec-enumerableownproperties - EnumerableOwnProperties: function EnumerableOwnProperties(O, kind) { - var keys = ES2016.EnumerableOwnNames(O); - if (kind === 'key') { - return keys; - } - if (kind === 'value' || kind === 'key+value') { - var results = []; - forEach(keys, function (key) { - if ($isEnumerable(O, key)) { - $pushApply(results, [ - kind === 'value' ? O[key] : [key, O[key]] - ]); - } - }); - return results; - } - throw new $TypeError('Assertion failed: "kind" is not "key", "value", or "key+value": ' + kind); - }, - - // https://www.ecma-international.org/ecma-262/8.0/#sec-iterabletolist - IterableToList: function IterableToList(items, method) { - var iterator = this.GetIterator(items, method); - var values = []; - var next = true; - while (next) { - next = this.IteratorStep(iterator); - if (next) { - var nextValue = this.IteratorValue(next); - $arrayPush(values, nextValue); - } - } - return values; - } -}); - -delete ES2017.EnumerableOwnNames; // replaced with EnumerableOwnProperties -delete ES2017.IterableToArrayLike; // replaced with IterableToList - -module.exports = ES2017; diff --git a/scripts/2.5/node_modules/es-abstract/es2018.js b/scripts/2.5/node_modules/es-abstract/es2018.js deleted file mode 100644 index 2de7fa7a..00000000 --- a/scripts/2.5/node_modules/es-abstract/es2018.js +++ /dev/null @@ -1,289 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('./GetIntrinsic'); - -var keys = require('object-keys'); -var inspect = require('object-inspect'); - -var ES2017 = require('./es2017'); -var assign = require('./helpers/assign'); -var forEach = require('./helpers/forEach'); -var callBind = require('./helpers/callBind'); -var every = require('./helpers/every'); -var isPrefixOf = require('./helpers/isPrefixOf'); - -var $String = GetIntrinsic('%String%'); -var $TypeError = GetIntrinsic('%TypeError%'); - -var callBound = require('./helpers/callBound'); -var regexTester = require('./helpers/regexTester'); -var $isNaN = require('./helpers/isNaN'); - -var $SymbolValueOf = callBound('Symbol.prototype.valueOf', true); -// var $charAt = callBound('String.prototype.charAt'); -var $strSlice = callBound('String.prototype.slice'); -var $indexOf = callBound('String.prototype.indexOf'); -var $parseInt = parseInt; - -var isDigit = regexTester(/^[0-9]$/); - -var $PromiseResolve = callBound('Promise.resolve', true); - -var $isEnumerable = callBound('Object.prototype.propertyIsEnumerable'); -var $pushApply = callBind.apply(GetIntrinsic('%Array.prototype.push%')); -var $gOPS = $SymbolValueOf ? GetIntrinsic('%Object.getOwnPropertySymbols%') : null; - -var padTimeComponent = function padTimeComponent(c, count) { - return $strSlice('00' + c, -(count || 2)); -}; - -var weekdays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; -var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; - -var OwnPropertyKeys = function OwnPropertyKeys(ES, source) { - var ownKeys = keys(source); - if ($gOPS) { - $pushApply(ownKeys, $gOPS(source)); - } - return ownKeys; -}; - -var ES2018 = assign(assign({}, ES2017), { - EnumerableOwnPropertyNames: ES2017.EnumerableOwnProperties, - - // https://ecma-international.org/ecma-262/9.0/#sec-thissymbolvalue - thisSymbolValue: function thisSymbolValue(value) { - if (!$SymbolValueOf) { - throw new SyntaxError('Symbols are not supported; thisSymbolValue requires that `value` be a Symbol or a Symbol object'); - } - if (this.Type(value) === 'Symbol') { - return value; - } - return $SymbolValueOf(value); - }, - - // https://www.ecma-international.org/ecma-262/9.0/#sec-isstringprefix - IsStringPrefix: function IsStringPrefix(p, q) { - if (this.Type(p) !== 'String') { - throw new TypeError('Assertion failed: "p" must be a String'); - } - - if (this.Type(q) !== 'String') { - throw new TypeError('Assertion failed: "q" must be a String'); - } - - return isPrefixOf(p, q); - /* - if (p === q || p === '') { - return true; - } - - var pLength = p.length; - var qLength = q.length; - if (pLength >= qLength) { - return false; - } - - // assert: pLength < qLength - - for (var i = 0; i < pLength; i += 1) { - if ($charAt(p, i) !== $charAt(q, i)) { - return false; - } - } - return true; - */ - }, - - // https://www.ecma-international.org/ecma-262/9.0/#sec-tostring-applied-to-the-number-type - NumberToString: function NumberToString(m) { - if (this.Type(m) !== 'Number') { - throw new TypeError('Assertion failed: "m" must be a String'); - } - - return $String(m); - }, - - // https://www.ecma-international.org/ecma-262/9.0/#sec-copydataproperties - CopyDataProperties: function CopyDataProperties(target, source, excludedItems) { - if (this.Type(target) !== 'Object') { - throw new TypeError('Assertion failed: "target" must be an Object'); - } - - if (!this.IsArray(excludedItems)) { - throw new TypeError('Assertion failed: "excludedItems" must be a List of Property Keys'); - } - for (var i = 0; i < excludedItems.length; i += 1) { - if (!this.IsPropertyKey(excludedItems[i])) { - throw new TypeError('Assertion failed: "excludedItems" must be a List of Property Keys'); - } - } - - if (typeof source === 'undefined' || source === null) { - return target; - } - - var ES = this; - - var fromObj = ES.ToObject(source); - - var sourceKeys = OwnPropertyKeys(ES, fromObj); - forEach(sourceKeys, function (nextKey) { - var excluded = false; - - forEach(excludedItems, function (e) { - if (ES.SameValue(e, nextKey) === true) { - excluded = true; - } - }); - - var enumerable = $isEnumerable(fromObj, nextKey) || ( - // this is to handle string keys being non-enumerable in older engines - typeof source === 'string' - && nextKey >= 0 - && ES.IsInteger(ES.ToNumber(nextKey)) - ); - if (excluded === false && enumerable) { - var propValue = ES.Get(fromObj, nextKey); - ES.CreateDataProperty(target, nextKey, propValue); - } - }); - - return target; - }, - - // https://ecma-international.org/ecma-262/9.0/#sec-promise-resolve - PromiseResolve: function PromiseResolve(C, x) { - if (!$PromiseResolve) { - throw new SyntaxError('This environment does not support Promises.'); - } - return $PromiseResolve(C, x); - }, - - // http://www.ecma-international.org/ecma-262/9.0/#sec-getsubstitution - // eslint-disable-next-line max-statements, max-params, max-lines-per-function - GetSubstitution: function GetSubstitution(matched, str, position, captures, namedCaptures, replacement) { - if (this.Type(matched) !== 'String') { - throw new $TypeError('Assertion failed: `matched` must be a String'); - } - var matchLength = matched.length; - - if (this.Type(str) !== 'String') { - throw new $TypeError('Assertion failed: `str` must be a String'); - } - var stringLength = str.length; - - if (!this.IsInteger(position) || position < 0 || position > stringLength) { - throw new $TypeError('Assertion failed: `position` must be a nonnegative integer, and less than or equal to the length of `string`, got ' + inspect(position)); - } - - var ES = this; - var isStringOrHole = function (capture, index, arr) { return ES.Type(capture) === 'String' || !(index in arr); }; - if (!this.IsArray(captures) || !every(captures, isStringOrHole)) { - throw new $TypeError('Assertion failed: `captures` must be a List of Strings, got ' + inspect(captures)); - } - - if (this.Type(replacement) !== 'String') { - throw new $TypeError('Assertion failed: `replacement` must be a String'); - } - - var tailPos = position + matchLength; - var m = captures.length; - if (this.Type(namedCaptures) !== 'Undefined') { - namedCaptures = this.ToObject(namedCaptures); // eslint-disable-line no-param-reassign - } - - var result = ''; - for (var i = 0; i < replacement.length; i += 1) { - // if this is a $, and it's not the end of the replacement - var current = replacement[i]; - var isLast = (i + 1) >= replacement.length; - var nextIsLast = (i + 2) >= replacement.length; - if (current === '$' && !isLast) { - var next = replacement[i + 1]; - if (next === '$') { - result += '$'; - i += 1; - } else if (next === '&') { - result += matched; - i += 1; - } else if (next === '`') { - result += position === 0 ? '' : $strSlice(str, 0, position - 1); - i += 1; - } else if (next === "'") { - result += tailPos >= stringLength ? '' : $strSlice(str, tailPos); - i += 1; - } else { - var nextNext = nextIsLast ? null : replacement[i + 2]; - if (isDigit(next) && next !== '0' && (nextIsLast || !isDigit(nextNext))) { - // $1 through $9, and not followed by a digit - var n = $parseInt(next, 10); - // if (n > m, impl-defined) - result += (n <= m && this.Type(captures[n - 1]) === 'Undefined') ? '' : captures[n - 1]; - i += 1; - } else if (isDigit(next) && (nextIsLast || isDigit(nextNext))) { - // $00 through $99 - var nn = next + nextNext; - var nnI = $parseInt(nn, 10) - 1; - // if nn === '00' or nn > m, impl-defined - result += (nn <= m && this.Type(captures[nnI]) === 'Undefined') ? '' : captures[nnI]; - i += 2; - } else if (next === '<') { - // eslint-disable-next-line max-depth - if (this.Type(namedCaptures) === 'Undefined') { - result += '$<'; - i += 2; - } else { - var endIndex = $indexOf(replacement, '>', i); - // eslint-disable-next-line max-depth - if (endIndex > -1) { - var groupName = $strSlice(replacement, i, endIndex); - var capture = this.Get(namedCaptures, groupName); - // eslint-disable-next-line max-depth - if (this.Type(capture) !== 'Undefined') { - result += this.ToString(capture); - } - i += '$<' + groupName + '>'.length; - } - } - } else { - result += '$'; - } - } - } else { - // the final $, or else not a $ - result += replacement[i]; - } - } - return result; - }, - - // https://www.ecma-international.org/ecma-262/9.0/#sec-datestring - DateString: function DateString(tv) { - if (this.Type(tv) !== 'Number' || $isNaN(tv)) { - throw new $TypeError('Assertion failed: `tv` must be a non-NaN Number'); - } - var weekday = weekdays[this.WeekDay(tv)]; - var month = months[this.MonthFromTime(tv)]; - var day = padTimeComponent(this.DateFromTime(tv)); - var year = padTimeComponent(this.YearFromTime(tv), 4); - return weekday + '\x20' + month + '\x20' + day + '\x20' + year; - }, - - // https://www.ecma-international.org/ecma-262/9.0/#sec-timestring - TimeString: function TimeString(tv) { - if (this.Type(tv) !== 'Number' || $isNaN(tv)) { - throw new $TypeError('Assertion failed: `tv` must be a non-NaN Number'); - } - var hour = this.HourFromTime(tv); - var minute = this.MinFromTime(tv); - var second = this.SecFromTime(tv); - return padTimeComponent(hour) + ':' + padTimeComponent(minute) + ':' + padTimeComponent(second) + '\x20GMT'; - } -}); - -delete ES2018.EnumerableOwnProperties; // replaced with EnumerableOwnPropertyNames - -delete ES2018.IsPropertyDescriptor; // not an actual abstract operation - -module.exports = ES2018; diff --git a/scripts/2.5/node_modules/es-abstract/es2019.js b/scripts/2.5/node_modules/es-abstract/es2019.js deleted file mode 100644 index 937c06c2..00000000 --- a/scripts/2.5/node_modules/es-abstract/es2019.js +++ /dev/null @@ -1,111 +0,0 @@ -'use strict'; - -var trimStart = require('string.prototype.trimleft'); -var trimEnd = require('string.prototype.trimright'); -var inspect = require('object-inspect'); - -var ES2018 = require('./es2018'); -var assign = require('./helpers/assign'); -var MAX_SAFE_INTEGER = require('./helpers/maxSafeInteger'); - -var GetIntrinsic = require('./GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); - -var ES2019 = assign(assign({}, ES2018), { - // https://tc39.es/ecma262/#sec-add-entries-from-iterable - AddEntriesFromIterable: function AddEntriesFromIterable(target, iterable, adder) { - if (!this.IsCallable(adder)) { - throw new $TypeError('Assertion failed: `adder` is not callable'); - } - if (iterable == null) { - throw new $TypeError('Assertion failed: `iterable` is present, and not nullish'); - } - var iteratorRecord = this.GetIterator(iterable); - while (true) { // eslint-disable-line no-constant-condition - var next = this.IteratorStep(iteratorRecord); - if (!next) { - return target; - } - var nextItem = this.IteratorValue(next); - if (this.Type(nextItem) !== 'Object') { - var error = new $TypeError('iterator next must return an Object, got ' + inspect(nextItem)); - return this.IteratorClose( - iteratorRecord, - function () { throw error; } // eslint-disable-line no-loop-func - ); - } - try { - var k = this.Get(nextItem, '0'); - var v = this.Get(nextItem, '1'); - this.Call(adder, target, [k, v]); - } catch (e) { - return this.IteratorClose( - iteratorRecord, - function () { throw e; } // eslint-disable-line no-loop-func - ); - } - } - }, - - // https://ecma-international.org/ecma-262/10.0/#sec-flattenintoarray - // eslint-disable-next-line max-params, max-statements - FlattenIntoArray: function FlattenIntoArray(target, source, sourceLen, start, depth) { - var mapperFunction; - if (arguments.length > 5) { - mapperFunction = arguments[5]; - } - - var targetIndex = start; - var sourceIndex = 0; - while (sourceIndex < sourceLen) { - var P = this.ToString(sourceIndex); - var exists = this.HasProperty(source, P); - if (exists === true) { - var element = this.Get(source, P); - if (typeof mapperFunction !== 'undefined') { - if (arguments.length <= 6) { - throw new $TypeError('Assertion failed: thisArg is required when mapperFunction is provided'); - } - element = this.Call(mapperFunction, arguments[6], [element, sourceIndex, source]); - } - var shouldFlatten = false; - if (depth > 0) { - shouldFlatten = this.IsArray(element); - } - if (shouldFlatten) { - var elementLen = this.ToLength(this.Get(element, 'length')); - targetIndex = this.FlattenIntoArray(target, element, elementLen, targetIndex, depth - 1); - } else { - if (targetIndex >= MAX_SAFE_INTEGER) { - throw new $TypeError('index too large'); - } - this.CreateDataPropertyOrThrow(target, this.ToString(targetIndex), element); - targetIndex += 1; - } - } - sourceIndex += 1; - } - - return targetIndex; - }, - - // https://ecma-international.org/ecma-262/10.0/#sec-trimstring - TrimString: function TrimString(string, where) { - var str = this.RequireObjectCoercible(string); - var S = this.ToString(str); - var T; - if (where === 'start') { - T = trimStart(S); - } else if (where === 'end') { - T = trimEnd(S); - } else if (where === 'start+end') { - T = trimStart(trimEnd(S)); - } else { - throw new $TypeError('Assertion failed: invalid `where` value; must be "start", "end", or "start+end"'); - } - return T; - } -}); - -module.exports = ES2019; diff --git a/scripts/2.5/node_modules/es-abstract/es5.js b/scripts/2.5/node_modules/es-abstract/es5.js deleted file mode 100644 index 9a97ba39..00000000 --- a/scripts/2.5/node_modules/es-abstract/es5.js +++ /dev/null @@ -1,544 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('./GetIntrinsic'); - -var $Object = GetIntrinsic('%Object%'); -var $EvalError = GetIntrinsic('%EvalError%'); -var $TypeError = GetIntrinsic('%TypeError%'); -var $String = GetIntrinsic('%String%'); -var $Date = GetIntrinsic('%Date%'); -var $Number = GetIntrinsic('%Number%'); -var $floor = GetIntrinsic('%Math.floor%'); -var $DateUTC = GetIntrinsic('%Date.UTC%'); -var $abs = GetIntrinsic('%Math.abs%'); - -var assertRecord = require('./helpers/assertRecord'); -var isPropertyDescriptor = require('./helpers/isPropertyDescriptor'); -var $isNaN = require('./helpers/isNaN'); -var $isFinite = require('./helpers/isFinite'); -var sign = require('./helpers/sign'); -var mod = require('./helpers/mod'); -var isPrefixOf = require('./helpers/isPrefixOf'); -var callBound = require('./helpers/callBound'); - -var IsCallable = require('is-callable'); -var toPrimitive = require('es-to-primitive/es5'); - -var has = require('has'); - -var $getUTCFullYear = callBound('Date.prototype.getUTCFullYear'); - -var HoursPerDay = 24; -var MinutesPerHour = 60; -var SecondsPerMinute = 60; -var msPerSecond = 1e3; -var msPerMinute = msPerSecond * SecondsPerMinute; -var msPerHour = msPerMinute * MinutesPerHour; -var msPerDay = 86400000; - -// https://es5.github.io/#x9 -var ES5 = { - ToPrimitive: toPrimitive, - - ToBoolean: function ToBoolean(value) { - return !!value; - }, - ToNumber: function ToNumber(value) { - return +value; // eslint-disable-line no-implicit-coercion - }, - ToInteger: function ToInteger(value) { - var number = this.ToNumber(value); - if ($isNaN(number)) { return 0; } - if (number === 0 || !$isFinite(number)) { return number; } - return sign(number) * Math.floor(Math.abs(number)); - }, - ToInt32: function ToInt32(x) { - return this.ToNumber(x) >> 0; - }, - ToUint32: function ToUint32(x) { - return this.ToNumber(x) >>> 0; - }, - ToUint16: function ToUint16(value) { - var number = this.ToNumber(value); - if ($isNaN(number) || number === 0 || !$isFinite(number)) { return 0; } - var posInt = sign(number) * Math.floor(Math.abs(number)); - return mod(posInt, 0x10000); - }, - ToString: function ToString(value) { - return $String(value); - }, - ToObject: function ToObject(value) { - this.CheckObjectCoercible(value); - return $Object(value); - }, - CheckObjectCoercible: function CheckObjectCoercible(value, optMessage) { - /* jshint eqnull:true */ - if (value == null) { - throw new $TypeError(optMessage || 'Cannot call method on ' + value); - } - return value; - }, - IsCallable: IsCallable, - SameValue: function SameValue(x, y) { - if (x === y) { // 0 === -0, but they are not identical. - if (x === 0) { return 1 / x === 1 / y; } - return true; - } - return $isNaN(x) && $isNaN(y); - }, - - // https://ecma-international.org/ecma-262/5.1/#sec-8 - Type: function Type(x) { - if (x === null) { - return 'Null'; - } - if (typeof x === 'undefined') { - return 'Undefined'; - } - if (typeof x === 'function' || typeof x === 'object') { - return 'Object'; - } - if (typeof x === 'number') { - return 'Number'; - } - if (typeof x === 'boolean') { - return 'Boolean'; - } - if (typeof x === 'string') { - return 'String'; - } - }, - - // https://ecma-international.org/ecma-262/6.0/#sec-property-descriptor-specification-type - IsPropertyDescriptor: function IsPropertyDescriptor(Desc) { - return isPropertyDescriptor(this, Desc); - }, - - // https://ecma-international.org/ecma-262/5.1/#sec-8.10.1 - IsAccessorDescriptor: function IsAccessorDescriptor(Desc) { - if (typeof Desc === 'undefined') { - return false; - } - - assertRecord(this, 'Property Descriptor', 'Desc', Desc); - - if (!has(Desc, '[[Get]]') && !has(Desc, '[[Set]]')) { - return false; - } - - return true; - }, - - // https://ecma-international.org/ecma-262/5.1/#sec-8.10.2 - IsDataDescriptor: function IsDataDescriptor(Desc) { - if (typeof Desc === 'undefined') { - return false; - } - - assertRecord(this, 'Property Descriptor', 'Desc', Desc); - - if (!has(Desc, '[[Value]]') && !has(Desc, '[[Writable]]')) { - return false; - } - - return true; - }, - - // https://ecma-international.org/ecma-262/5.1/#sec-8.10.3 - IsGenericDescriptor: function IsGenericDescriptor(Desc) { - if (typeof Desc === 'undefined') { - return false; - } - - assertRecord(this, 'Property Descriptor', 'Desc', Desc); - - if (!this.IsAccessorDescriptor(Desc) && !this.IsDataDescriptor(Desc)) { - return true; - } - - return false; - }, - - // https://ecma-international.org/ecma-262/5.1/#sec-8.10.4 - FromPropertyDescriptor: function FromPropertyDescriptor(Desc) { - if (typeof Desc === 'undefined') { - return Desc; - } - - assertRecord(this, 'Property Descriptor', 'Desc', Desc); - - if (this.IsDataDescriptor(Desc)) { - return { - value: Desc['[[Value]]'], - writable: !!Desc['[[Writable]]'], - enumerable: !!Desc['[[Enumerable]]'], - configurable: !!Desc['[[Configurable]]'] - }; - } else if (this.IsAccessorDescriptor(Desc)) { - return { - get: Desc['[[Get]]'], - set: Desc['[[Set]]'], - enumerable: !!Desc['[[Enumerable]]'], - configurable: !!Desc['[[Configurable]]'] - }; - } else { - throw new $TypeError('FromPropertyDescriptor must be called with a fully populated Property Descriptor'); - } - }, - - // https://ecma-international.org/ecma-262/5.1/#sec-8.10.5 - ToPropertyDescriptor: function ToPropertyDescriptor(Obj) { - if (this.Type(Obj) !== 'Object') { - throw new $TypeError('ToPropertyDescriptor requires an object'); - } - - var desc = {}; - if (has(Obj, 'enumerable')) { - desc['[[Enumerable]]'] = this.ToBoolean(Obj.enumerable); - } - if (has(Obj, 'configurable')) { - desc['[[Configurable]]'] = this.ToBoolean(Obj.configurable); - } - if (has(Obj, 'value')) { - desc['[[Value]]'] = Obj.value; - } - if (has(Obj, 'writable')) { - desc['[[Writable]]'] = this.ToBoolean(Obj.writable); - } - if (has(Obj, 'get')) { - var getter = Obj.get; - if (typeof getter !== 'undefined' && !this.IsCallable(getter)) { - throw new TypeError('getter must be a function'); - } - desc['[[Get]]'] = getter; - } - if (has(Obj, 'set')) { - var setter = Obj.set; - if (typeof setter !== 'undefined' && !this.IsCallable(setter)) { - throw new $TypeError('setter must be a function'); - } - desc['[[Set]]'] = setter; - } - - if ((has(desc, '[[Get]]') || has(desc, '[[Set]]')) && (has(desc, '[[Value]]') || has(desc, '[[Writable]]'))) { - throw new $TypeError('Invalid property descriptor. Cannot both specify accessors and a value or writable attribute'); - } - return desc; - }, - - // https://ecma-international.org/ecma-262/5.1/#sec-11.9.3 - 'Abstract Equality Comparison': function AbstractEqualityComparison(x, y) { - var xType = this.Type(x); - var yType = this.Type(y); - if (xType === yType) { - return x === y; // ES6+ specified this shortcut anyways. - } - if (x == null && y == null) { - return true; - } - if (xType === 'Number' && yType === 'String') { - return this['Abstract Equality Comparison'](x, this.ToNumber(y)); - } - if (xType === 'String' && yType === 'Number') { - return this['Abstract Equality Comparison'](this.ToNumber(x), y); - } - if (xType === 'Boolean') { - return this['Abstract Equality Comparison'](this.ToNumber(x), y); - } - if (yType === 'Boolean') { - return this['Abstract Equality Comparison'](x, this.ToNumber(y)); - } - if ((xType === 'String' || xType === 'Number') && yType === 'Object') { - return this['Abstract Equality Comparison'](x, this.ToPrimitive(y)); - } - if (xType === 'Object' && (yType === 'String' || yType === 'Number')) { - return this['Abstract Equality Comparison'](this.ToPrimitive(x), y); - } - return false; - }, - - // https://ecma-international.org/ecma-262/5.1/#sec-11.9.6 - 'Strict Equality Comparison': function StrictEqualityComparison(x, y) { - var xType = this.Type(x); - var yType = this.Type(y); - if (xType !== yType) { - return false; - } - if (xType === 'Undefined' || xType === 'Null') { - return true; - } - return x === y; // shortcut for steps 4-7 - }, - - // https://ecma-international.org/ecma-262/5.1/#sec-11.8.5 - // eslint-disable-next-line max-statements - 'Abstract Relational Comparison': function AbstractRelationalComparison(x, y, LeftFirst) { - if (this.Type(LeftFirst) !== 'Boolean') { - throw new $TypeError('Assertion failed: LeftFirst argument must be a Boolean'); - } - var px; - var py; - if (LeftFirst) { - px = this.ToPrimitive(x, $Number); - py = this.ToPrimitive(y, $Number); - } else { - py = this.ToPrimitive(y, $Number); - px = this.ToPrimitive(x, $Number); - } - var bothStrings = this.Type(px) === 'String' && this.Type(py) === 'String'; - if (!bothStrings) { - var nx = this.ToNumber(px); - var ny = this.ToNumber(py); - if ($isNaN(nx) || $isNaN(ny)) { - return undefined; - } - if ($isFinite(nx) && $isFinite(ny) && nx === ny) { - return false; - } - if (nx === 0 && ny === 0) { - return false; - } - if (nx === Infinity) { - return false; - } - if (ny === Infinity) { - return true; - } - if (ny === -Infinity) { - return false; - } - if (nx === -Infinity) { - return true; - } - return nx < ny; // by now, these are both nonzero, finite, and not equal - } - if (isPrefixOf(py, px)) { - return false; - } - if (isPrefixOf(px, py)) { - return true; - } - return px < py; // both strings, neither a prefix of the other. shortcut for steps c-f - }, - - // https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.10 - msFromTime: function msFromTime(t) { - return mod(t, msPerSecond); - }, - - // https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.10 - SecFromTime: function SecFromTime(t) { - return mod($floor(t / msPerSecond), SecondsPerMinute); - }, - - // https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.10 - MinFromTime: function MinFromTime(t) { - return mod($floor(t / msPerMinute), MinutesPerHour); - }, - - // https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.10 - HourFromTime: function HourFromTime(t) { - return mod($floor(t / msPerHour), HoursPerDay); - }, - - // https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.2 - Day: function Day(t) { - return $floor(t / msPerDay); - }, - - // https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.2 - TimeWithinDay: function TimeWithinDay(t) { - return mod(t, msPerDay); - }, - - // https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.3 - DayFromYear: function DayFromYear(y) { - return (365 * (y - 1970)) + $floor((y - 1969) / 4) - $floor((y - 1901) / 100) + $floor((y - 1601) / 400); - }, - - // https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.3 - TimeFromYear: function TimeFromYear(y) { - return msPerDay * this.DayFromYear(y); - }, - - // https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.3 - YearFromTime: function YearFromTime(t) { - // largest y such that this.TimeFromYear(y) <= t - return $getUTCFullYear(new $Date(t)); - }, - - // https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.6 - WeekDay: function WeekDay(t) { - return mod(this.Day(t) + 4, 7); - }, - - // https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.3 - DaysInYear: function DaysInYear(y) { - if (mod(y, 4) !== 0) { - return 365; - } - if (mod(y, 100) !== 0) { - return 366; - } - if (mod(y, 400) !== 0) { - return 365; - } - return 366; - }, - - // https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.3 - InLeapYear: function InLeapYear(t) { - var days = this.DaysInYear(this.YearFromTime(t)); - if (days === 365) { - return 0; - } - if (days === 366) { - return 1; - } - throw new $EvalError('Assertion failed: there are not 365 or 366 days in a year, got: ' + days); - }, - - // https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.4 - DayWithinYear: function DayWithinYear(t) { - return this.Day(t) - this.DayFromYear(this.YearFromTime(t)); - }, - - // https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.4 - MonthFromTime: function MonthFromTime(t) { - var day = this.DayWithinYear(t); - if (0 <= day && day < 31) { - return 0; - } - var leap = this.InLeapYear(t); - if (31 <= day && day < (59 + leap)) { - return 1; - } - if ((59 + leap) <= day && day < (90 + leap)) { - return 2; - } - if ((90 + leap) <= day && day < (120 + leap)) { - return 3; - } - if ((120 + leap) <= day && day < (151 + leap)) { - return 4; - } - if ((151 + leap) <= day && day < (181 + leap)) { - return 5; - } - if ((181 + leap) <= day && day < (212 + leap)) { - return 6; - } - if ((212 + leap) <= day && day < (243 + leap)) { - return 7; - } - if ((243 + leap) <= day && day < (273 + leap)) { - return 8; - } - if ((273 + leap) <= day && day < (304 + leap)) { - return 9; - } - if ((304 + leap) <= day && day < (334 + leap)) { - return 10; - } - if ((334 + leap) <= day && day < (365 + leap)) { - return 11; - } - }, - - // https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.5 - DateFromTime: function DateFromTime(t) { - var m = this.MonthFromTime(t); - var d = this.DayWithinYear(t); - if (m === 0) { - return d + 1; - } - if (m === 1) { - return d - 30; - } - var leap = this.InLeapYear(t); - if (m === 2) { - return d - 58 - leap; - } - if (m === 3) { - return d - 89 - leap; - } - if (m === 4) { - return d - 119 - leap; - } - if (m === 5) { - return d - 150 - leap; - } - if (m === 6) { - return d - 180 - leap; - } - if (m === 7) { - return d - 211 - leap; - } - if (m === 8) { - return d - 242 - leap; - } - if (m === 9) { - return d - 272 - leap; - } - if (m === 10) { - return d - 303 - leap; - } - if (m === 11) { - return d - 333 - leap; - } - throw new $EvalError('Assertion failed: MonthFromTime returned an impossible value: ' + m); - }, - - // https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.12 - MakeDay: function MakeDay(year, month, date) { - if (!$isFinite(year) || !$isFinite(month) || !$isFinite(date)) { - return NaN; - } - var y = this.ToInteger(year); - var m = this.ToInteger(month); - var dt = this.ToInteger(date); - var ym = y + $floor(m / 12); - var mn = mod(m, 12); - var t = $DateUTC(ym, mn, 1); - if (this.YearFromTime(t) !== ym || this.MonthFromTime(t) !== mn || this.DateFromTime(t) !== 1) { - return NaN; - } - return this.Day(t) + dt - 1; - }, - - // https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.13 - MakeDate: function MakeDate(day, time) { - if (!$isFinite(day) || !$isFinite(time)) { - return NaN; - } - return (day * msPerDay) + time; - }, - - // https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.11 - MakeTime: function MakeTime(hour, min, sec, ms) { - if (!$isFinite(hour) || !$isFinite(min) || !$isFinite(sec) || !$isFinite(ms)) { - return NaN; - } - var h = this.ToInteger(hour); - var m = this.ToInteger(min); - var s = this.ToInteger(sec); - var milli = this.ToInteger(ms); - var t = (h * msPerHour) + (m * msPerMinute) + (s * msPerSecond) + milli; - return t; - }, - - // https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.14 - TimeClip: function TimeClip(time) { - if (!$isFinite(time) || $abs(time) > 8.64e15) { - return NaN; - } - return $Number(new $Date(this.ToNumber(time))); - }, - - // https://ecma-international.org/ecma-262/5.1/#sec-5.2 - modulo: function modulo(x, y) { - return mod(x, y); - } -}; - -module.exports = ES5; diff --git a/scripts/2.5/node_modules/es-abstract/es6.js b/scripts/2.5/node_modules/es-abstract/es6.js deleted file mode 100644 index 2d1f4dc9..00000000 --- a/scripts/2.5/node_modules/es-abstract/es6.js +++ /dev/null @@ -1,3 +0,0 @@ -'use strict'; - -module.exports = require('./es2015'); diff --git a/scripts/2.5/node_modules/es-abstract/es7.js b/scripts/2.5/node_modules/es-abstract/es7.js deleted file mode 100644 index f2f15c0a..00000000 --- a/scripts/2.5/node_modules/es-abstract/es7.js +++ /dev/null @@ -1,3 +0,0 @@ -'use strict'; - -module.exports = require('./es2016'); diff --git a/scripts/2.5/node_modules/es-abstract/helpers/assertRecord.js b/scripts/2.5/node_modules/es-abstract/helpers/assertRecord.js deleted file mode 100644 index 72df7716..00000000 --- a/scripts/2.5/node_modules/es-abstract/helpers/assertRecord.js +++ /dev/null @@ -1,48 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $TypeError = GetIntrinsic('%TypeError%'); -var $SyntaxError = GetIntrinsic('%SyntaxError%'); - -var has = require('has'); - -var predicates = { - // https://ecma-international.org/ecma-262/6.0/#sec-property-descriptor-specification-type - 'Property Descriptor': function isPropertyDescriptor(ES, Desc) { - if (ES.Type(Desc) !== 'Object') { - return false; - } - var allowed = { - '[[Configurable]]': true, - '[[Enumerable]]': true, - '[[Get]]': true, - '[[Set]]': true, - '[[Value]]': true, - '[[Writable]]': true - }; - - for (var key in Desc) { // eslint-disable-line - if (has(Desc, key) && !allowed[key]) { - return false; - } - } - - var isData = has(Desc, '[[Value]]'); - var IsAccessor = has(Desc, '[[Get]]') || has(Desc, '[[Set]]'); - if (isData && IsAccessor) { - throw new $TypeError('Property Descriptors may not be both accessor and data descriptors'); - } - return true; - } -}; - -module.exports = function assertRecord(ES, recordType, argumentName, value) { - var predicate = predicates[recordType]; - if (typeof predicate !== 'function') { - throw new $SyntaxError('unknown record type: ' + recordType); - } - if (!predicate(ES, value)) { - throw new $TypeError(argumentName + ' must be a ' + recordType); - } -}; diff --git a/scripts/2.5/node_modules/es-abstract/helpers/assign.js b/scripts/2.5/node_modules/es-abstract/helpers/assign.js deleted file mode 100644 index 420bebb8..00000000 --- a/scripts/2.5/node_modules/es-abstract/helpers/assign.js +++ /dev/null @@ -1,21 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var has = require('has'); - -var $assign = GetIntrinsic('%Object%').assign; - -module.exports = function assign(target, source) { - if ($assign) { - return $assign(target, source); - } - - // eslint-disable-next-line no-restricted-syntax - for (var key in source) { - if (has(source, key)) { - target[key] = source[key]; - } - } - return target; -}; diff --git a/scripts/2.5/node_modules/es-abstract/helpers/callBind.js b/scripts/2.5/node_modules/es-abstract/helpers/callBind.js deleted file mode 100644 index dd206abe..00000000 --- a/scripts/2.5/node_modules/es-abstract/helpers/callBind.js +++ /dev/null @@ -1,17 +0,0 @@ -'use strict'; - -var bind = require('function-bind'); - -var GetIntrinsic = require('../GetIntrinsic'); - -var $Function = GetIntrinsic('%Function%'); -var $apply = $Function.apply; -var $call = $Function.call; - -module.exports = function callBind() { - return bind.apply($call, arguments); -}; - -module.exports.apply = function applyBind() { - return bind.apply($apply, arguments); -}; diff --git a/scripts/2.5/node_modules/es-abstract/helpers/callBound.js b/scripts/2.5/node_modules/es-abstract/helpers/callBound.js deleted file mode 100644 index 9dc8fc51..00000000 --- a/scripts/2.5/node_modules/es-abstract/helpers/callBound.js +++ /dev/null @@ -1,15 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var callBind = require('./callBind'); - -var $indexOf = callBind(GetIntrinsic('String.prototype.indexOf')); - -module.exports = function callBoundIntrinsic(name, allowMissing) { - var intrinsic = GetIntrinsic(name, !!allowMissing); - if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.')) { - return callBind(intrinsic); - } - return intrinsic; -}; diff --git a/scripts/2.5/node_modules/es-abstract/helpers/every.js b/scripts/2.5/node_modules/es-abstract/helpers/every.js deleted file mode 100644 index 42a45821..00000000 --- a/scripts/2.5/node_modules/es-abstract/helpers/every.js +++ /dev/null @@ -1,10 +0,0 @@ -'use strict'; - -module.exports = function every(array, predicate) { - for (var i = 0; i < array.length; i += 1) { - if (!predicate(array[i], i, array)) { - return false; - } - } - return true; -}; diff --git a/scripts/2.5/node_modules/es-abstract/helpers/forEach.js b/scripts/2.5/node_modules/es-abstract/helpers/forEach.js deleted file mode 100644 index 35915a65..00000000 --- a/scripts/2.5/node_modules/es-abstract/helpers/forEach.js +++ /dev/null @@ -1,7 +0,0 @@ -'use strict'; - -module.exports = function forEach(array, callback) { - for (var i = 0; i < array.length; i += 1) { - callback(array[i], i, array); // eslint-disable-line callback-return - } -}; diff --git a/scripts/2.5/node_modules/es-abstract/helpers/getInferredName.js b/scripts/2.5/node_modules/es-abstract/helpers/getInferredName.js deleted file mode 100644 index 2dab6e77..00000000 --- a/scripts/2.5/node_modules/es-abstract/helpers/getInferredName.js +++ /dev/null @@ -1,10 +0,0 @@ -'use strict'; - -var getInferredName; -try { - // eslint-disable-next-line no-new-func - getInferredName = Function('s', 'return { [s]() {} }[s].name;'); -} catch (e) {} - -var inferred = function () {}; -module.exports = getInferredName && inferred.name === 'inferred' ? getInferredName : null; diff --git a/scripts/2.5/node_modules/es-abstract/helpers/getIteratorMethod.js b/scripts/2.5/node_modules/es-abstract/helpers/getIteratorMethod.js deleted file mode 100644 index d1f8596e..00000000 --- a/scripts/2.5/node_modules/es-abstract/helpers/getIteratorMethod.js +++ /dev/null @@ -1,46 +0,0 @@ -'use strict'; - -var hasSymbols = require('has-symbols')(); -var GetIntrinsic = require('../GetIntrinsic'); -var callBound = require('./callBound'); - -var $iterator = GetIntrinsic('%Symbol.iterator%', true); -var $arraySlice = callBound('Array.prototype.slice'); -var $arrayJoin = callBound('Array.prototype.join'); - -module.exports = function getIteratorMethod(ES, iterable) { - var usingIterator; - if (hasSymbols) { - usingIterator = ES.GetMethod(iterable, $iterator); - } else if (ES.IsArray(iterable)) { - usingIterator = function () { - var i = -1; - var arr = this; // eslint-disable-line no-invalid-this - return { - next: function () { - i += 1; - return { - done: i >= arr.length, - value: arr[i] - }; - } - }; - }; - } else if (ES.Type(iterable) === 'String') { - usingIterator = function () { - var i = 0; - return { - next: function () { - var nextIndex = ES.AdvanceStringIndex(iterable, i, true); - var value = $arrayJoin($arraySlice(iterable, i, nextIndex), ''); - i = nextIndex; - return { - done: nextIndex > iterable.length, - value: value - }; - } - }; - }; - } - return usingIterator; -}; diff --git a/scripts/2.5/node_modules/es-abstract/helpers/getProto.js b/scripts/2.5/node_modules/es-abstract/helpers/getProto.js deleted file mode 100644 index af10fd8a..00000000 --- a/scripts/2.5/node_modules/es-abstract/helpers/getProto.js +++ /dev/null @@ -1,15 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var originalGetProto = GetIntrinsic('%Object.getPrototypeOf%', true); -var $ArrayProto = GetIntrinsic('%Array.prototype%'); - -module.exports = originalGetProto || ( - // eslint-disable-next-line no-proto - [].__proto__ === $ArrayProto - ? function (O) { - return O.__proto__; // eslint-disable-line no-proto - } - : null -); diff --git a/scripts/2.5/node_modules/es-abstract/helpers/getSymbolDescription.js b/scripts/2.5/node_modules/es-abstract/helpers/getSymbolDescription.js deleted file mode 100644 index dff8fccb..00000000 --- a/scripts/2.5/node_modules/es-abstract/helpers/getSymbolDescription.js +++ /dev/null @@ -1,30 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var callBound = require('./callBound'); - -var $SyntaxError = GetIntrinsic('%SyntaxError%'); -var symToStr = callBound('Symbol.prototype.toString', true); - -var getInferredName = require('./getInferredName'); - -module.exports = function getSymbolDescription(symbol) { - if (!symToStr) { - throw new $SyntaxError('Symbols are not supported in this environment'); - } - var str = symToStr(symbol); // will throw if not a symbol - - if (getInferredName) { - var name = getInferredName(symbol); - if (name === '') { return; } - // eslint-disable-next-line consistent-return - return name.slice(1, -1); // name.slice('['.length, -']'.length); - } - - var desc = str.slice(7, -1); // str.slice('Symbol('.length, -')'.length); - if (desc) { - // eslint-disable-next-line consistent-return - return desc; - } -}; diff --git a/scripts/2.5/node_modules/es-abstract/helpers/isFinite.js b/scripts/2.5/node_modules/es-abstract/helpers/isFinite.js deleted file mode 100644 index 9e7cd4f8..00000000 --- a/scripts/2.5/node_modules/es-abstract/helpers/isFinite.js +++ /dev/null @@ -1,5 +0,0 @@ -'use strict'; - -var $isNaN = Number.isNaN || function (a) { return a !== a; }; - -module.exports = Number.isFinite || function (x) { return typeof x === 'number' && !$isNaN(x) && x !== Infinity && x !== -Infinity; }; diff --git a/scripts/2.5/node_modules/es-abstract/helpers/isNaN.js b/scripts/2.5/node_modules/es-abstract/helpers/isNaN.js deleted file mode 100644 index cb8631dc..00000000 --- a/scripts/2.5/node_modules/es-abstract/helpers/isNaN.js +++ /dev/null @@ -1,5 +0,0 @@ -'use strict'; - -module.exports = Number.isNaN || function isNaN(a) { - return a !== a; -}; diff --git a/scripts/2.5/node_modules/es-abstract/helpers/isPrefixOf.js b/scripts/2.5/node_modules/es-abstract/helpers/isPrefixOf.js deleted file mode 100644 index b67d6405..00000000 --- a/scripts/2.5/node_modules/es-abstract/helpers/isPrefixOf.js +++ /dev/null @@ -1,13 +0,0 @@ -'use strict'; - -var $strSlice = require('../helpers/callBound')('String.prototype.slice'); - -module.exports = function isPrefixOf(prefix, string) { - if (prefix === string) { - return true; - } - if (prefix.length > string.length) { - return false; - } - return $strSlice(string, 0, prefix.length) === prefix; -}; diff --git a/scripts/2.5/node_modules/es-abstract/helpers/isPrimitive.js b/scripts/2.5/node_modules/es-abstract/helpers/isPrimitive.js deleted file mode 100644 index 06f0bf04..00000000 --- a/scripts/2.5/node_modules/es-abstract/helpers/isPrimitive.js +++ /dev/null @@ -1,5 +0,0 @@ -'use strict'; - -module.exports = function isPrimitive(value) { - return value === null || (typeof value !== 'function' && typeof value !== 'object'); -}; diff --git a/scripts/2.5/node_modules/es-abstract/helpers/isPropertyDescriptor.js b/scripts/2.5/node_modules/es-abstract/helpers/isPropertyDescriptor.js deleted file mode 100644 index 23e89952..00000000 --- a/scripts/2.5/node_modules/es-abstract/helpers/isPropertyDescriptor.js +++ /dev/null @@ -1,31 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var has = require('has'); -var $TypeError = GetIntrinsic('%TypeError%'); - -module.exports = function IsPropertyDescriptor(ES, Desc) { - if (ES.Type(Desc) !== 'Object') { - return false; - } - var allowed = { - '[[Configurable]]': true, - '[[Enumerable]]': true, - '[[Get]]': true, - '[[Set]]': true, - '[[Value]]': true, - '[[Writable]]': true - }; - - for (var key in Desc) { // eslint-disable-line - if (has(Desc, key) && !allowed[key]) { - return false; - } - } - - if (ES.IsDataDescriptor(Desc) && ES.IsAccessorDescriptor(Desc)) { - throw new $TypeError('Property Descriptors may not be both accessor and data descriptors'); - } - return true; -}; diff --git a/scripts/2.5/node_modules/es-abstract/helpers/isSamePropertyDescriptor.js b/scripts/2.5/node_modules/es-abstract/helpers/isSamePropertyDescriptor.js deleted file mode 100644 index a6162a1d..00000000 --- a/scripts/2.5/node_modules/es-abstract/helpers/isSamePropertyDescriptor.js +++ /dev/null @@ -1,20 +0,0 @@ -'use strict'; - -var every = require('./every'); - -module.exports = function isSamePropertyDescriptor(ES, D1, D2) { - var fields = [ - '[[Configurable]]', - '[[Enumerable]]', - '[[Get]]', - '[[Set]]', - '[[Value]]', - '[[Writable]]' - ]; - return every(fields, function (field) { - if ((field in D1) !== (field in D2)) { - return false; - } - return ES.SameValue(D1[field], D2[field]); - }); -}; diff --git a/scripts/2.5/node_modules/es-abstract/helpers/maxSafeInteger.js b/scripts/2.5/node_modules/es-abstract/helpers/maxSafeInteger.js deleted file mode 100644 index 2fe8f38e..00000000 --- a/scripts/2.5/node_modules/es-abstract/helpers/maxSafeInteger.js +++ /dev/null @@ -1,8 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $Math = GetIntrinsic('%Math%'); -var $Number = GetIntrinsic('%Number%'); - -module.exports = $Number.MAX_SAFE_INTEGER || $Math.pow(2, 53) - 1; diff --git a/scripts/2.5/node_modules/es-abstract/helpers/mod.js b/scripts/2.5/node_modules/es-abstract/helpers/mod.js deleted file mode 100644 index 70f0eead..00000000 --- a/scripts/2.5/node_modules/es-abstract/helpers/mod.js +++ /dev/null @@ -1,6 +0,0 @@ -'use strict'; - -module.exports = function mod(number, modulo) { - var remain = number % modulo; - return Math.floor(remain >= 0 ? remain : remain + modulo); -}; diff --git a/scripts/2.5/node_modules/es-abstract/helpers/regexTester.js b/scripts/2.5/node_modules/es-abstract/helpers/regexTester.js deleted file mode 100644 index 982cc9f7..00000000 --- a/scripts/2.5/node_modules/es-abstract/helpers/regexTester.js +++ /dev/null @@ -1,11 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var $test = GetIntrinsic('RegExp.prototype.test'); - -var callBind = require('./callBind'); - -module.exports = function regexTester(regex) { - return callBind($test, regex); -}; diff --git a/scripts/2.5/node_modules/es-abstract/helpers/setProto.js b/scripts/2.5/node_modules/es-abstract/helpers/setProto.js deleted file mode 100644 index 4c234746..00000000 --- a/scripts/2.5/node_modules/es-abstract/helpers/setProto.js +++ /dev/null @@ -1,16 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var originalSetProto = GetIntrinsic('%Object.setPrototypeOf%', true); -var $ArrayProto = GetIntrinsic('%Array.prototype%'); - -module.exports = originalSetProto || ( - // eslint-disable-next-line no-proto, no-negated-condition - [].__proto__ !== $ArrayProto - ? null - : function (O, proto) { - O.__proto__ = proto; // eslint-disable-line no-proto - return O; - } -); diff --git a/scripts/2.5/node_modules/es-abstract/helpers/sign.js b/scripts/2.5/node_modules/es-abstract/helpers/sign.js deleted file mode 100644 index 598ea7d8..00000000 --- a/scripts/2.5/node_modules/es-abstract/helpers/sign.js +++ /dev/null @@ -1,5 +0,0 @@ -'use strict'; - -module.exports = function sign(number) { - return number >= 0 ? 1 : -1; -}; diff --git a/scripts/2.5/node_modules/es-abstract/index.js b/scripts/2.5/node_modules/es-abstract/index.js deleted file mode 100644 index 7cef0395..00000000 --- a/scripts/2.5/node_modules/es-abstract/index.js +++ /dev/null @@ -1,26 +0,0 @@ -'use strict'; - -var assign = require('./helpers/assign'); - -var ES5 = require('./es5'); -var ES2015 = require('./es2015'); -var ES2016 = require('./es2016'); -var ES2017 = require('./es2017'); -var ES2018 = require('./es2018'); -var ES2019 = require('./es2019'); - -var ES = { - ES5: ES5, - ES6: ES2015, - ES2015: ES2015, - ES7: ES2016, - ES2016: ES2016, - ES2017: ES2017, - ES2018: ES2018, - ES2019: ES2019 -}; -assign(ES, ES5); -delete ES.CheckObjectCoercible; // renamed in ES6 to RequireObjectCoercible -assign(ES, ES2015); - -module.exports = ES; diff --git a/scripts/2.5/node_modules/es-abstract/operations/.eslintrc b/scripts/2.5/node_modules/es-abstract/operations/.eslintrc deleted file mode 100644 index bcd76f76..00000000 --- a/scripts/2.5/node_modules/es-abstract/operations/.eslintrc +++ /dev/null @@ -1,5 +0,0 @@ -{ - "rules": { - "id-length": 0, - }, -} diff --git a/scripts/2.5/node_modules/es-abstract/package.json b/scripts/2.5/node_modules/es-abstract/package.json deleted file mode 100644 index 3c668e4e..00000000 --- a/scripts/2.5/node_modules/es-abstract/package.json +++ /dev/null @@ -1,130 +0,0 @@ -{ - "_from": "es-abstract@^1.12.0", - "_id": "es-abstract@1.16.0", - "_inBundle": false, - "_integrity": "sha512-xdQnfykZ9JMEiasTAJZJdMWCQ1Vm00NBw79/AWi7ELfZuuPCSOMDZbT9mkOfSctVtfhb+sAAzrm+j//GjjLHLg==", - "_location": "/es-abstract", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "es-abstract@^1.12.0", - "name": "es-abstract", - "escapedName": "es-abstract", - "rawSpec": "^1.12.0", - "saveSpec": null, - "fetchSpec": "^1.12.0" - }, - "_requiredBy": [ - "/object.entries" - ], - "_resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.16.0.tgz", - "_shasum": "d3a26dc9c3283ac9750dca569586e976d9dcc06d", - "_spec": "es-abstract@^1.12.0", - "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/2.5/node_modules/object.entries", - "author": { - "name": "Jordan Harband", - "email": "ljharb@gmail.com", - "url": "http://ljharb.codes" - }, - "bugs": { - "url": "https://github.com/ljharb/es-abstract/issues" - }, - "bundleDependencies": false, - "contributors": [ - { - "name": "Jordan Harband", - "email": "ljharb@gmail.com", - "url": "http://ljharb.codes" - } - ], - "dependencies": { - "es-to-primitive": "^1.2.0", - "function-bind": "^1.1.1", - "has": "^1.0.3", - "has-symbols": "^1.0.0", - "is-callable": "^1.1.4", - "is-regex": "^1.0.4", - "object-inspect": "^1.6.0", - "object-keys": "^1.1.1", - "string.prototype.trimleft": "^2.1.0", - "string.prototype.trimright": "^2.1.0" - }, - "deprecated": false, - "description": "ECMAScript spec abstract operations.", - "devDependencies": { - "@ljharb/eslint-config": "^14.1.0", - "cheerio": "^1.0.0-rc.3", - "diff": "^4.0.1", - "eclint": "^2.8.1", - "eslint": "^6.5.1", - "foreach": "^2.0.5", - "make-arrow-function": "^1.1.0", - "nyc": "^10.3.2", - "object-is": "^1.0.1", - "object.assign": "^4.1.0", - "object.fromentries": "^2.0.1", - "replace": "^1.1.1", - "safe-publish-latest": "^1.1.3", - "semver": "^6.3.0", - "tape": "^4.11.0" - }, - "engines": { - "node": ">= 0.4" - }, - "greenkeeper": { - "//": "nyc is ignored because it requires node 4+, and we support older than that", - "ignore": [ - "nyc" - ] - }, - "homepage": "https://github.com/ljharb/es-abstract#readme", - "keywords": [ - "ECMAScript", - "ES", - "abstract", - "operation", - "abstract operation", - "JavaScript", - "ES5", - "ES6", - "ES7" - ], - "license": "MIT", - "main": "index.js", - "name": "es-abstract", - "repository": { - "type": "git", - "url": "git://github.com/ljharb/es-abstract.git" - }, - "scripts": { - "coverage": "nyc npm run --silent tests-only >/dev/null", - "eccheck": "eclint check *.js **/*.js > /dev/null", - "lint": "eslint .", - "postcoverage": "nyc report", - "posttest": "npx aud --production", - "prepublish": "safe-publish-latest", - "pretest": "npm run --silent lint", - "test": "npm run tests-only", - "tests-only": "node test" - }, - "testling": { - "files": "test/index.js", - "browsers": [ - "iexplore/6.0..latest", - "firefox/3.0..6.0", - "firefox/15.0..latest", - "firefox/nightly", - "chrome/4.0..10.0", - "chrome/20.0..latest", - "chrome/canary", - "opera/10.0..latest", - "opera/next", - "safari/4.0..latest", - "ipad/6.0..latest", - "iphone/6.0..latest", - "android-browser/4.2" - ] - }, - "version": "1.16.0" -} diff --git a/scripts/2.5/node_modules/es-abstract/test/.eslintrc b/scripts/2.5/node_modules/es-abstract/test/.eslintrc deleted file mode 100644 index f33c7476..00000000 --- a/scripts/2.5/node_modules/es-abstract/test/.eslintrc +++ /dev/null @@ -1,13 +0,0 @@ -{ - "rules": { - "id-length": 0, - "max-lines": 0, - "max-lines-per-function": 0, - "max-statements-per-line": [2, { "max": 3 }], - "max-nested-callbacks": [2, 4], - "max-statements": 0, - "no-implicit-coercion": 1, - "no-invalid-this": 1, - "object-curly-newline": 0, - } -} diff --git a/scripts/2.5/node_modules/es-abstract/test/GetIntrinsic.js b/scripts/2.5/node_modules/es-abstract/test/GetIntrinsic.js deleted file mode 100644 index 2ec9ff8d..00000000 --- a/scripts/2.5/node_modules/es-abstract/test/GetIntrinsic.js +++ /dev/null @@ -1,48 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('../GetIntrinsic'); - -var test = require('tape'); -var forEach = require('foreach'); -var debug = require('object-inspect'); - -var v = require('./helpers/values'); - -test('export', function (t) { - t.equal(typeof GetIntrinsic, 'function', 'it is a function'); - t.equal(GetIntrinsic.length, 2, 'function has length of 2'); - - t.end(); -}); - -test('throws', function (t) { - t['throws']( - function () { GetIntrinsic('not an intrinsic'); }, - SyntaxError, - 'nonexistent intrinsic throws a syntax error' - ); - - forEach(v.nonBooleans, function (nonBoolean) { - t['throws']( - function () { GetIntrinsic('%', nonBoolean); }, - TypeError, - debug(nonBoolean) + ' is not a Boolean' - ); - }); - - t.end(); -}); - -test('base intrinsics', function (t) { - t.equal(GetIntrinsic('%Object%'), Object, '%Object% yields Object'); - t.equal(GetIntrinsic('%Array%'), Array, '%Array% yields Array'); - - t.end(); -}); - -test('dotted paths', function (t) { - t.equal(GetIntrinsic('%Object.prototype.toString%'), Object.prototype.toString, '%Object.prototype.toString% yields Object.prototype.toString'); - t.equal(GetIntrinsic('%Array.prototype.push%'), Array.prototype.push, '%Array.prototype.push% yields Array.prototype.push'); - - t.end(); -}); diff --git a/scripts/2.5/node_modules/es-abstract/test/diffOps.js b/scripts/2.5/node_modules/es-abstract/test/diffOps.js deleted file mode 100644 index 0fb2fc40..00000000 --- a/scripts/2.5/node_modules/es-abstract/test/diffOps.js +++ /dev/null @@ -1,26 +0,0 @@ -'use strict'; - -var keys = require('object-keys'); -var forEach = require('foreach'); - -module.exports = function diffOperations(actual, expected, expectedMissing) { - var actualKeys = keys(actual); - var expectedKeys = keys(expected); - - var extra = []; - var missing = []; - forEach(actualKeys, function (op) { - if (!(op in expected)) { - extra.push(op); - } else if (expectedMissing.indexOf(op) !== -1) { - extra.push(op); - } - }); - forEach(expectedKeys, function (op) { - if (typeof actual[op] !== 'function' && expectedMissing.indexOf(op) === -1) { - missing.push(op); - } - }); - - return { missing: missing, extra: extra }; -}; diff --git a/scripts/2.5/node_modules/es-abstract/test/es2015.js b/scripts/2.5/node_modules/es-abstract/test/es2015.js deleted file mode 100644 index 7922d9cc..00000000 --- a/scripts/2.5/node_modules/es-abstract/test/es2015.js +++ /dev/null @@ -1,9 +0,0 @@ -'use strict'; - -var ES = require('../').ES2015; - -var ops = require('../operations/2015'); - -var expectedMissing = ['Construct', 'CreateArrayFromList', 'CreateListIterator', 'NormalCompletion', 'RegExpBuiltinExec']; - -require('./tests').es2015(ES, ops, expectedMissing); diff --git a/scripts/2.5/node_modules/es-abstract/test/es2016.js b/scripts/2.5/node_modules/es-abstract/test/es2016.js deleted file mode 100644 index 016d35f7..00000000 --- a/scripts/2.5/node_modules/es-abstract/test/es2016.js +++ /dev/null @@ -1,9 +0,0 @@ -'use strict'; - -var ES = require('../').ES2016; - -var ops = require('../operations/2016'); - -var expectedMissing = ['AddRestrictedFunctionProperties', 'AllocateArrayBuffer', 'AllocateTypedArray', 'AllocateTypedArrayBuffer', 'BlockDeclarationInstantiation', 'BoundFunctionCreate', 'Canonicalize', 'CharacterRange', 'CharacterRangeOrUnion', 'CharacterSetMatcher', 'CloneArrayBuffer', 'Completion', 'Construct', 'CopyDataBlockBytes', 'CreateArrayFromList', 'CreateArrayIterator', 'CreateBuiltinFunction', 'CreateByteDataBlock', 'CreateDynamicFunction', 'CreateIntrinsics', 'CreateListIterator', 'CreateMapIterator', 'CreateMappedArgumentsObject', 'CreatePerIterationEnvironment', 'CreateRealm', 'CreateResolvingFunctions', 'CreateSetIterator', 'CreateStringIterator', 'CreateUnmappedArgumentsObject', 'Decode', 'DetachArrayBuffer', 'Encode', 'EnqueueJob', 'EnumerateObjectProperties', 'EscapeRegExpPattern', 'EvalDeclarationInstantiation', 'EvaluateCall', 'EvaluateDirectCall', 'EvaluateNew', 'ForBodyEvaluation', 'ForIn/OfBodyEvaluation', 'ForIn/OfHeadEvaluation', 'FulfillPromise', 'FunctionAllocate', 'FunctionCreate', 'FunctionDeclarationInstantiation', 'FunctionInitialize', 'GeneratorFunctionCreate', 'GeneratorResume', 'GeneratorResumeAbrupt', 'GeneratorStart', 'GeneratorValidate', 'GeneratorYield', 'GetActiveScriptOrModule', 'GetFunctionRealm', 'GetGlobalObject', 'GetIdentifierReference', 'GetModuleNamespace', 'GetNewTarget', 'GetSuperConstructor', 'GetTemplateObject', 'GetThisEnvironment', 'GetThisValue', 'GetValue', 'GetValueFromBuffer', 'GetViewValue', 'GlobalDeclarationInstantiation', 'HostPromiseRejectionTracker', 'HostReportErrors', 'HostResolveImportedModule', 'IfAbruptRejectPromise', 'ImportedLocalNames', 'InitializeBoundName', 'InitializeHostDefinedRealm', 'InitializeReferencedBinding', 'IntegerIndexedElementGet', 'IntegerIndexedElementSet', 'IntegerIndexedObjectCreate', 'InternalizeJSONProperty', 'IsAnonymousFunctionDefinition', 'IsCompatiblePropertyDescriptor', 'IsDetachedBuffer', 'IsInTailPosition', 'IsLabelledFunction', 'IsWordChar', 'LocalTime', 'LoopContinues', 'MakeArgGetter', 'MakeArgSetter', 'MakeClassConstructor', 'MakeConstructor', 'MakeMethod', 'MakeSuperPropertyReference', 'ModuleNamespaceCreate', 'NewDeclarativeEnvironment', 'NewFunctionEnvironment', 'NewGlobalEnvironment', 'NewModuleEnvironment', 'NewObjectEnvironment', 'NewPromiseCapability', 'NextJob', 'NormalCompletion', 'ObjectDefineProperties', 'OrdinaryCallBindThis', 'OrdinaryCallEvaluateBody', 'OrdinaryCreateFromConstructor', 'OrdinaryDelete', 'OrdinaryGet', 'OrdinaryIsExtensible', 'OrdinaryOwnPropertyKeys', 'OrdinaryPreventExtensions', 'OrdinarySet', 'ParseModule', 'ParseScript', 'PerformEval', 'PerformPromiseAll', 'PerformPromiseRace', 'PerformPromiseThen', 'PrepareForOrdinaryCall', 'PrepareForTailCall', 'PromiseReactionJob', 'PromiseResolveThenableJob', 'ProxyCreate', 'PutValue', 'QuoteJSONString', 'RegExpAlloc', 'RegExpBuiltinExec', 'RegExpCreate', 'RegExpInitialize', 'RejectPromise', 'RepeatMatcher', 'ResolveBinding', 'ResolveThisBinding', 'ReturnIfAbrupt', 'ScriptEvaluation', 'ScriptEvaluationJob', 'SerializeJSONArray', 'SerializeJSONObject', 'SerializeJSONProperty', 'SetDefaultGlobalBindings', 'SetRealmGlobalObject', 'SetValueInBuffer', 'SetViewValue', 'SortCompare', 'SplitMatch', 'StringCreate', 'ToString Applied to the Number Type', 'TopLevelModuleEvaluationJob', 'TriggerPromiseReactions', 'TypedArrayCreate', 'TypedArraySpeciesCreate', 'UTC', 'UTF16Decode', 'UTF16Encoding', 'UpdateEmpty', 'ValidateTypedArray', 'abs', 'floor', 'max', 'min']; - -require('./tests').es2016(ES, ops, expectedMissing); diff --git a/scripts/2.5/node_modules/es-abstract/test/es2017.js b/scripts/2.5/node_modules/es-abstract/test/es2017.js deleted file mode 100644 index c497679c..00000000 --- a/scripts/2.5/node_modules/es-abstract/test/es2017.js +++ /dev/null @@ -1,9 +0,0 @@ -'use strict'; - -var ES = require('../').ES2017; - -var ops = require('../operations/2017'); - -var expectedMissing = ['AddRestrictedFunctionProperties', 'AddWaiter', 'AgentCanSuspend', 'AgentSignifier', 'AllocateArrayBuffer', 'AllocateSharedArrayBuffer', 'AllocateTypedArray', 'AllocateTypedArrayBuffer', 'AsyncFunctionAwait', 'AsyncFunctionCreate', 'AsyncFunctionStart', 'AtomicLoad', 'AtomicReadModifyWrite', 'BlockDeclarationInstantiation', 'BoundFunctionCreate', 'Canonicalize', 'CharacterRange', 'CharacterRangeOrUnion', 'CharacterSetMatcher', 'CloneArrayBuffer', 'Completion', 'ComposeWriteEventBytes', 'Construct', 'CopyDataBlockBytes', 'CreateArrayFromList', 'CreateArrayIterator', 'CreateBuiltinFunction', 'CreateByteDataBlock', 'CreateDynamicFunction', 'CreateIntrinsics', 'CreateListIterator', 'CreateMapIterator', 'CreateMappedArgumentsObject', 'CreatePerIterationEnvironment', 'CreateRealm', 'CreateResolvingFunctions', 'CreateSetIterator', 'CreateSharedByteDataBlock', 'CreateStringIterator', 'CreateUnmappedArgumentsObject', 'Decode', 'DetachArrayBuffer', 'Encode', 'EnqueueJob', 'EnterCriticalSection', 'EnumerateObjectProperties', 'EscapeRegExpPattern', 'EvalDeclarationInstantiation', 'EvaluateCall', 'EvaluateDirectCall', 'EvaluateNew', 'EventSet', 'ForBodyEvaluation', 'ForIn/OfBodyEvaluation', 'ForIn/OfHeadEvaluation', 'FulfillPromise', 'FunctionAllocate', 'FunctionCreate', 'FunctionDeclarationInstantiation', 'FunctionInitialize', 'GeneratorFunctionCreate', 'GeneratorResume', 'GeneratorResumeAbrupt', 'GeneratorStart', 'GeneratorValidate', 'GeneratorYield', 'GetActiveScriptOrModule', 'GetBase', 'GetFunctionRealm', 'GetGlobalObject', 'GetIdentifierReference', 'GetModifySetValueInBuffer', 'GetModuleNamespace', 'GetNewTarget', 'GetReferencedName', 'GetSuperConstructor', 'GetTemplateObject', 'GetThisEnvironment', 'GetThisValue', 'GetValue', 'GetValueFromBuffer', 'GetViewValue', 'GetWaiterList', 'GlobalDeclarationInstantiation', 'HasPrimitiveBase', 'HostEnsureCanCompileStrings', 'HostEventSet', 'HostPromiseRejectionTracker', 'HostReportErrors', 'HostResolveImportedModule', 'IfAbruptRejectPromise', 'ImportedLocalNames', 'InitializeBoundName', 'InitializeHostDefinedRealm', 'InitializeReferencedBinding', 'IntegerIndexedElementGet', 'IntegerIndexedElementSet', 'IntegerIndexedObjectCreate', 'InternalizeJSONProperty', 'IsAnonymousFunctionDefinition', 'IsCompatiblePropertyDescriptor', 'IsDetachedBuffer', 'IsInTailPosition', 'IsLabelledFunction', 'IsPropertyReference', 'IsSharedArrayBuffer', 'IsStrictReference', 'IsSuperReference', 'IsUnresolvableReference', 'IsWordChar', 'LeaveCriticalSection', 'LocalTime', 'LoopContinues', 'MakeArgGetter', 'MakeArgSetter', 'MakeClassConstructor', 'MakeConstructor', 'MakeMethod', 'MakeSuperPropertyReference', 'ModuleNamespaceCreate', 'NewDeclarativeEnvironment', 'NewFunctionEnvironment', 'NewGlobalEnvironment', 'NewModuleEnvironment', 'NewObjectEnvironment', 'NewPromiseCapability', 'NormalCompletion', 'NumberToRawBytes', 'ObjectDefineProperties', 'OrdinaryCallBindThis', 'OrdinaryCallEvaluateBody', 'OrdinaryCreateFromConstructor', 'OrdinaryDelete', 'OrdinaryGet', 'OrdinaryIsExtensible', 'OrdinaryOwnPropertyKeys', 'OrdinaryPreventExtensions', 'OrdinarySet', 'OrdinaryToPrimitive', 'ParseModule', 'ParseScript', 'PerformEval', 'PerformPromiseAll', 'PerformPromiseRace', 'PerformPromiseThen', 'PrepareForOrdinaryCall', 'PrepareForTailCall', 'PromiseReactionJob', 'PromiseResolveThenableJob', 'ProxyCreate', 'PutValue', 'QuoteJSONString', 'RawBytesToNumber', 'RegExpAlloc', 'RegExpBuiltinExec', 'RegExpCreate', 'RegExpInitialize', 'RejectPromise', 'RemoveWaiter', 'RemoveWaiters', 'RepeatMatcher', 'ResolveBinding', 'ResolveThisBinding', 'ReturnIfAbrupt', 'RunJobs', 'ScriptEvaluation', 'ScriptEvaluationJob', 'SerializeJSONArray', 'SerializeJSONObject', 'SerializeJSONProperty', 'SetDefaultGlobalBindings', 'SetImmutablePrototype', 'SetRealmGlobalObject', 'SetValueInBuffer', 'SetViewValue', 'SharedDataBlockEventSet', 'SortCompare', 'SplitMatch', 'StringCreate', 'StringGetOwnProperty', 'Suspend', 'ToString Applied to the Number Type', 'TopLevelModuleEvaluationJob', 'TriggerPromiseReactions', 'TypedArrayCreate', 'TypedArraySpeciesCreate', 'UTC', 'UTF16Decode', 'UTF16Encoding', 'UpdateEmpty', 'ValidateAtomicAccess', 'ValidateSharedIntegerTypedArray', 'ValidateTypedArray', 'ValueOfReadEvent', 'WakeWaiter', 'WordCharacters', 'abs', 'agent-order', 'floor', 'happens-before', 'host-synchronizes-with', 'max', 'memory-order', 'min', 'reads-bytes-from', 'reads-from', 'synchronizes-with']; - -require('./tests').es2017(ES, ops, expectedMissing); diff --git a/scripts/2.5/node_modules/es-abstract/test/es2018.js b/scripts/2.5/node_modules/es-abstract/test/es2018.js deleted file mode 100644 index 37c029a3..00000000 --- a/scripts/2.5/node_modules/es-abstract/test/es2018.js +++ /dev/null @@ -1,9 +0,0 @@ -'use strict'; - -var ES = require('../').ES2018; - -var ops = require('../operations/2018'); - -var expectedMissing = ['abs', 'AddRestrictedFunctionProperties', 'AddWaiter', 'agent-order', 'AgentCanSuspend', 'AgentSignifier', 'AllocateArrayBuffer', 'AllocateSharedArrayBuffer', 'AllocateTypedArray', 'AllocateTypedArrayBuffer', 'AsyncFunctionStart', 'AsyncGeneratorEnqueue', 'AsyncGeneratorReject', 'AsyncGeneratorResolve', 'AsyncGeneratorResumeNext', 'AsyncGeneratorStart', 'AsyncGeneratorYield', 'AtomicLoad', 'AtomicReadModifyWrite', 'Await', 'BlockDeclarationInstantiation', 'BoundFunctionCreate', 'Canonicalize', 'CaseClauseIsSelected', 'CharacterRange', 'CharacterRangeOrUnion', 'CharacterSetMatcher', 'CloneArrayBuffer', 'Completion', 'ComposeWriteEventBytes', 'CopyDataBlockBytes', 'CreateArrayIterator', 'CreateAsyncFromSyncIterator', 'CreateBuiltinFunction', 'CreateByteDataBlock', 'CreateDynamicFunction', 'CreateIntrinsics', 'CreateMapIterator', 'CreateMappedArgumentsObject', 'CreatePerIterationEnvironment', 'CreateRealm', 'CreateResolvingFunctions', 'CreateSetIterator', 'CreateSharedByteDataBlock', 'CreateStringIterator', 'CreateUnmappedArgumentsObject', 'Decode', 'DetachArrayBuffer', 'Encode', 'EnqueueJob', 'EnterCriticalSection', 'EnumerateObjectProperties', 'EscapeRegExpPattern', 'EvalDeclarationInstantiation', 'EvaluateCall', 'EvaluateNew', 'EventSet', 'floor', 'ForBodyEvaluation', 'ForIn/OfBodyEvaluation', 'ForIn/OfHeadEvaluation', 'FulfillPromise', 'FunctionAllocate', 'FunctionCreate', 'FunctionDeclarationInstantiation', 'FunctionInitialize', 'GeneratorFunctionCreate', 'GeneratorResume', 'GeneratorResumeAbrupt', 'GeneratorStart', 'GeneratorValidate', 'GeneratorYield', 'GetActiveScriptOrModule', 'GetBase', 'GetFunctionRealm', 'GetGeneratorKind', 'GetGlobalObject', 'GetIdentifierReference', 'GetModifySetValueInBuffer', 'GetModuleNamespace', 'GetNewTarget', 'GetReferencedName', 'GetSuperConstructor', 'GetTemplateObject', 'GetThisEnvironment', 'GetThisValue', 'GetValue', 'GetValueFromBuffer', 'GetViewValue', 'GetWaiterList', 'GlobalDeclarationInstantiation', 'happens-before', 'HasPrimitiveBase', 'host-synchronizes-with', 'HostEnsureCanCompileStrings', 'HostEventSet', 'HostPromiseRejectionTracker', 'HostReportErrors', 'HostResolveImportedModule', 'IfAbruptRejectPromise', 'ImportedLocalNames', 'InitializeBoundName', 'InitializeHostDefinedRealm', 'InitializeReferencedBinding', 'InnerModuleEvaluation', 'InnerModuleInstantiation', 'IntegerIndexedElementGet', 'IntegerIndexedElementSet', 'IntegerIndexedObjectCreate', 'InternalizeJSONProperty', 'IsAnonymousFunctionDefinition', 'IsCompatiblePropertyDescriptor', 'IsDetachedBuffer', 'IsInTailPosition', 'IsLabelledFunction', 'IsPropertyReference', 'IsSharedArrayBuffer', 'IsStrictReference', 'IsSuperReference', 'IsUnresolvableReference', 'IsWordChar', 'LeaveCriticalSection', 'LocalTime', 'LoopContinues', 'MakeArgGetter', 'MakeArgSetter', 'MakeClassConstructor', 'MakeConstructor', 'MakeMethod', 'MakeSuperPropertyReference', 'max', 'memory-order', 'min', 'ModuleDeclarationEnvironmentSetup', 'ModuleExecution', 'ModuleNamespaceCreate', 'NewDeclarativeEnvironment', 'NewFunctionEnvironment', 'NewGlobalEnvironment', 'NewModuleEnvironment', 'NewObjectEnvironment', 'NewPromiseCapability', 'NumberToRawBytes', 'ObjectDefineProperties', 'OrdinaryCallBindThis', 'OrdinaryCallEvaluateBody', 'OrdinaryCreateFromConstructor', 'OrdinaryDelete', 'OrdinaryGet', 'OrdinaryIsExtensible', 'OrdinaryOwnPropertyKeys', 'OrdinaryPreventExtensions', 'OrdinaryToPrimitive', 'ParseModule', 'ParseScript', 'PerformEval', 'PerformPromiseAll', 'PerformPromiseRace', 'PerformPromiseThen', 'PrepareForOrdinaryCall', 'PrepareForTailCall', 'PromiseReactionJob', 'PromiseResolveThenableJob', 'ProxyCreate', 'PutValue', 'QuoteJSONString', 'RawBytesToNumber', 'reads-bytes-from', 'reads-from', 'RegExpAlloc', 'RegExpCreate', 'RegExpInitialize', 'RejectPromise', 'RemoveWaiter', 'RemoveWaiters', 'RepeatMatcher', 'ResolveBinding', 'ResolveThisBinding', 'ReturnIfAbrupt', 'RunJobs', 'ScriptEvaluation', 'ScriptEvaluationJob', 'SerializeJSONArray', 'SerializeJSONObject', 'SerializeJSONProperty', 'SetDefaultGlobalBindings', 'SetImmutablePrototype', 'SetRealmGlobalObject', 'SetValueInBuffer', 'SetViewValue', 'SharedDataBlockEventSet', 'SortCompare', 'SplitMatch', 'StringCreate', 'StringGetOwnProperty', 'Suspend', 'synchronizes-with', 'TimeZoneString', 'TopLevelModuleEvaluationJob', 'TriggerPromiseReactions', 'TypedArrayCreate', 'TypedArraySpeciesCreate', 'UnicodeEscape', 'UpdateEmpty', 'UTC', 'UTF16Decode', 'UTF16Encoding', 'ValidateAtomicAccess', 'ValidateSharedIntegerTypedArray', 'ValidateTypedArray', 'ValueOfReadEvent', 'WakeWaiter', 'WordCharacters', 'AsyncFunctionCreate', 'AsyncGeneratorFunctionCreate', 'AsyncIteratorClose', 'BackreferenceMatcher', 'Construct', 'CreateArrayFromList', 'CreateListIteratorRecord', 'NormalCompletion', 'OrdinarySet', 'OrdinarySetWithOwnDescriptor', 'RegExpBuiltinExec', 'SetFunctionLength', 'ThrowCompletion', 'UnicodeMatchProperty', 'UnicodeMatchPropertyValue']; - -require('./tests').es2018(ES, ops, expectedMissing); diff --git a/scripts/2.5/node_modules/es-abstract/test/es2019.js b/scripts/2.5/node_modules/es-abstract/test/es2019.js deleted file mode 100644 index 94e00a39..00000000 --- a/scripts/2.5/node_modules/es-abstract/test/es2019.js +++ /dev/null @@ -1,9 +0,0 @@ -'use strict'; - -var ES = require('../').ES2019; - -var ops = require('../operations/2019'); - -var expectedMissing = ['abs', 'AddRestrictedFunctionProperties', 'AddWaiter', 'agent-order', 'AgentCanSuspend', 'AgentSignifier', 'AllocateArrayBuffer', 'AllocateSharedArrayBuffer', 'AllocateTypedArray', 'AllocateTypedArrayBuffer', 'AsyncFunctionStart', 'AsyncGeneratorEnqueue', 'AsyncGeneratorReject', 'AsyncGeneratorResolve', 'AsyncGeneratorResumeNext', 'AsyncGeneratorStart', 'AsyncGeneratorYield', 'AtomicLoad', 'AtomicReadModifyWrite', 'Await', 'BlockDeclarationInstantiation', 'BoundFunctionCreate', 'Canonicalize', 'CaseClauseIsSelected', 'CharacterRange', 'CharacterRangeOrUnion', 'CharacterSetMatcher', 'CloneArrayBuffer', 'Completion', 'ComposeWriteEventBytes', 'CopyDataBlockBytes', 'CreateArrayIterator', 'CreateAsyncFromSyncIterator', 'CreateBuiltinFunction', 'CreateByteDataBlock', 'CreateDynamicFunction', 'CreateIntrinsics', 'CreateMapIterator', 'CreateMappedArgumentsObject', 'CreatePerIterationEnvironment', 'CreateRealm', 'CreateResolvingFunctions', 'CreateSetIterator', 'CreateSharedByteDataBlock', 'CreateStringIterator', 'CreateUnmappedArgumentsObject', 'Decode', 'DetachArrayBuffer', 'Encode', 'EnqueueJob', 'EnterCriticalSection', 'EnumerateObjectProperties', 'EscapeRegExpPattern', 'EvalDeclarationInstantiation', 'EvaluateCall', 'EvaluateNew', 'EventSet', 'floor', 'ForBodyEvaluation', 'ForIn/OfBodyEvaluation', 'ForIn/OfHeadEvaluation', 'FulfillPromise', 'FunctionAllocate', 'FunctionCreate', 'FunctionDeclarationInstantiation', 'FunctionInitialize', 'GeneratorFunctionCreate', 'GeneratorResume', 'GeneratorResumeAbrupt', 'GeneratorStart', 'GeneratorValidate', 'GeneratorYield', 'GetActiveScriptOrModule', 'GetBase', 'GetFunctionRealm', 'GetGeneratorKind', 'GetGlobalObject', 'GetIdentifierReference', 'GetModifySetValueInBuffer', 'GetModuleNamespace', 'GetNewTarget', 'GetReferencedName', 'GetSuperConstructor', 'GetTemplateObject', 'GetThisEnvironment', 'GetThisValue', 'GetValue', 'GetValueFromBuffer', 'GetViewValue', 'GetWaiterList', 'GlobalDeclarationInstantiation', 'happens-before', 'HasPrimitiveBase', 'host-synchronizes-with', 'HostEnsureCanCompileStrings', 'HostEventSet', 'HostPromiseRejectionTracker', 'HostReportErrors', 'HostResolveImportedModule', 'IfAbruptRejectPromise', 'ImportedLocalNames', 'InitializeBoundName', 'InitializeHostDefinedRealm', 'InitializeReferencedBinding', 'InnerModuleEvaluation', 'InnerModuleInstantiation', 'IntegerIndexedElementGet', 'IntegerIndexedElementSet', 'IntegerIndexedObjectCreate', 'InternalizeJSONProperty', 'IsAnonymousFunctionDefinition', 'IsCompatiblePropertyDescriptor', 'IsDetachedBuffer', 'IsInTailPosition', 'IsLabelledFunction', 'IsPropertyReference', 'IsSharedArrayBuffer', 'IsStrictReference', 'IsSuperReference', 'IsUnresolvableReference', 'IsWordChar', 'LeaveCriticalSection', 'LocalTime', 'LoopContinues', 'MakeArgGetter', 'MakeArgSetter', 'MakeClassConstructor', 'MakeConstructor', 'MakeMethod', 'MakeSuperPropertyReference', 'max', 'memory-order', 'min', 'ModuleDeclarationEnvironmentSetup', 'ModuleExecution', 'ModuleNamespaceCreate', 'NewDeclarativeEnvironment', 'NewFunctionEnvironment', 'NewGlobalEnvironment', 'NewModuleEnvironment', 'NewObjectEnvironment', 'NewPromiseCapability', 'NumberToRawBytes', 'ObjectDefineProperties', 'OrdinaryCallBindThis', 'OrdinaryCallEvaluateBody', 'OrdinaryCreateFromConstructor', 'OrdinaryDelete', 'OrdinaryGet', 'OrdinaryIsExtensible', 'OrdinaryOwnPropertyKeys', 'OrdinaryPreventExtensions', 'OrdinaryToPrimitive', 'ParseModule', 'ParseScript', 'PerformEval', 'PerformPromiseAll', 'PerformPromiseRace', 'PerformPromiseThen', 'PrepareForOrdinaryCall', 'PrepareForTailCall', 'PromiseReactionJob', 'PromiseResolveThenableJob', 'ProxyCreate', 'PutValue', 'QuoteJSONString', 'RawBytesToNumber', 'reads-bytes-from', 'reads-from', 'RegExpAlloc', 'RegExpCreate', 'RegExpInitialize', 'RejectPromise', 'RemoveWaiter', 'RemoveWaiters', 'RepeatMatcher', 'ResolveBinding', 'ResolveThisBinding', 'ReturnIfAbrupt', 'RunJobs', 'ScriptEvaluation', 'ScriptEvaluationJob', 'SerializeJSONArray', 'SerializeJSONObject', 'SerializeJSONProperty', 'SetDefaultGlobalBindings', 'SetImmutablePrototype', 'SetRealmGlobalObject', 'SetValueInBuffer', 'SetViewValue', 'SharedDataBlockEventSet', 'SortCompare', 'SplitMatch', 'StringCreate', 'StringGetOwnProperty', 'Suspend', 'synchronizes-with', 'TimeZoneString', 'TopLevelModuleEvaluationJob', 'TriggerPromiseReactions', 'TypedArrayCreate', 'TypedArraySpeciesCreate', 'UnicodeEscape', 'UpdateEmpty', 'UTC', 'UTF16Decode', 'UTF16Encoding', 'ValidateAtomicAccess', 'ValidateSharedIntegerTypedArray', 'ValidateTypedArray', 'ValueOfReadEvent', 'WakeWaiter', 'WordCharacters', 'AsyncFunctionCreate', 'AsyncGeneratorFunctionCreate', 'AsyncIteratorClose', 'BackreferenceMatcher', 'Construct', 'CreateArrayFromList', 'CreateListIteratorRecord', 'NormalCompletion', 'OrdinarySet', 'OrdinarySetWithOwnDescriptor', 'RegExpBuiltinExec', 'SetFunctionLength', 'ThrowCompletion', 'UnicodeMatchProperty', 'UnicodeMatchPropertyValue', 'AsyncFromSyncIteratorContinuation', 'ExecuteModule', 'InitializeEnvironment', 'NotifyWaiter', 'SynchronizeEventSet']; - -require('./tests').es2019(ES, ops, expectedMissing); diff --git a/scripts/2.5/node_modules/es-abstract/test/es5.js b/scripts/2.5/node_modules/es-abstract/test/es5.js deleted file mode 100644 index efd9042b..00000000 --- a/scripts/2.5/node_modules/es-abstract/test/es5.js +++ /dev/null @@ -1,782 +0,0 @@ -'use strict'; - -var ES = require('../').ES5; -var test = require('tape'); - -var forEach = require('foreach'); -var is = require('object-is'); -var debug = require('object-inspect'); - -var v = require('./helpers/values'); - -test('ToPrimitive', function (t) { - t.test('primitives', function (st) { - var testPrimitive = function (primitive) { - st.ok(is(ES.ToPrimitive(primitive), primitive), debug(primitive) + ' is returned correctly'); - }; - forEach(v.primitives, testPrimitive); - st.end(); - }); - - t.test('objects', function (st) { - st.equal(ES.ToPrimitive(v.coercibleObject), v.coercibleObject.valueOf(), 'coercibleObject coerces to valueOf'); - st.equal(ES.ToPrimitive(v.coercibleObject, Number), v.coercibleObject.valueOf(), 'coercibleObject with hint Number coerces to valueOf'); - st.equal(ES.ToPrimitive(v.coercibleObject, String), v.coercibleObject.toString(), 'coercibleObject with hint String coerces to toString'); - st.equal(ES.ToPrimitive(v.coercibleFnObject), v.coercibleFnObject.toString(), 'coercibleFnObject coerces to toString'); - st.equal(ES.ToPrimitive(v.toStringOnlyObject), v.toStringOnlyObject.toString(), 'toStringOnlyObject returns toString'); - st.equal(ES.ToPrimitive(v.valueOfOnlyObject), v.valueOfOnlyObject.valueOf(), 'valueOfOnlyObject returns valueOf'); - st.equal(ES.ToPrimitive({}), '[object Object]', '{} with no hint coerces to Object#toString'); - st.equal(ES.ToPrimitive({}, String), '[object Object]', '{} with hint String coerces to Object#toString'); - st.equal(ES.ToPrimitive({}, Number), '[object Object]', '{} with hint Number coerces to Object#toString'); - st['throws'](function () { return ES.ToPrimitive(v.uncoercibleObject); }, TypeError, 'uncoercibleObject throws a TypeError'); - st['throws'](function () { return ES.ToPrimitive(v.uncoercibleFnObject); }, TypeError, 'uncoercibleFnObject throws a TypeError'); - st.end(); - }); - - t.end(); -}); - -test('ToBoolean', function (t) { - t.equal(false, ES.ToBoolean(undefined), 'undefined coerces to false'); - t.equal(false, ES.ToBoolean(null), 'null coerces to false'); - t.equal(false, ES.ToBoolean(false), 'false returns false'); - t.equal(true, ES.ToBoolean(true), 'true returns true'); - forEach([0, -0, NaN], function (falsyNumber) { - t.equal(false, ES.ToBoolean(falsyNumber), 'falsy number ' + falsyNumber + ' coerces to false'); - }); - forEach([Infinity, 42, 1, -Infinity], function (truthyNumber) { - t.equal(true, ES.ToBoolean(truthyNumber), 'truthy number ' + truthyNumber + ' coerces to true'); - }); - t.equal(false, ES.ToBoolean(''), 'empty string coerces to false'); - t.equal(true, ES.ToBoolean('foo'), 'nonempty string coerces to true'); - forEach(v.objects, function (obj) { - t.equal(true, ES.ToBoolean(obj), 'object coerces to true'); - }); - t.equal(true, ES.ToBoolean(v.uncoercibleObject), 'uncoercibleObject coerces to true'); - t.end(); -}); - -test('ToNumber', function (t) { - t.ok(is(NaN, ES.ToNumber(undefined)), 'undefined coerces to NaN'); - t.ok(is(ES.ToNumber(null), 0), 'null coerces to +0'); - t.ok(is(ES.ToNumber(false), 0), 'false coerces to +0'); - t.equal(1, ES.ToNumber(true), 'true coerces to 1'); - t.ok(is(NaN, ES.ToNumber(NaN)), 'NaN returns itself'); - forEach([0, -0, 42, Infinity, -Infinity], function (num) { - t.equal(num, ES.ToNumber(num), num + ' returns itself'); - }); - forEach(['foo', '0', '4a', '2.0', 'Infinity', '-Infinity'], function (numString) { - t.ok(is(+numString, ES.ToNumber(numString)), '"' + numString + '" coerces to ' + Number(numString)); - }); - forEach(v.objects, function (object) { - t.ok(is(ES.ToNumber(object), ES.ToNumber(ES.ToPrimitive(object))), 'object ' + object + ' coerces to same as ToPrimitive of object does'); - }); - t['throws'](function () { return ES.ToNumber(v.uncoercibleObject); }, TypeError, 'uncoercibleObject throws'); - t.end(); -}); - -test('ToInteger', function (t) { - t.ok(is(0, ES.ToInteger(NaN)), 'NaN coerces to +0'); - forEach([0, Infinity, 42], function (num) { - t.ok(is(num, ES.ToInteger(num)), num + ' returns itself'); - t.ok(is(-num, ES.ToInteger(-num)), '-' + num + ' returns itself'); - }); - t.equal(3, ES.ToInteger(Math.PI), 'pi returns 3'); - t['throws'](function () { return ES.ToInteger(v.uncoercibleObject); }, TypeError, 'uncoercibleObject throws'); - t.end(); -}); - -test('ToInt32', function (t) { - t.ok(is(0, ES.ToInt32(NaN)), 'NaN coerces to +0'); - forEach([0, Infinity], function (num) { - t.ok(is(0, ES.ToInt32(num)), num + ' returns +0'); - t.ok(is(0, ES.ToInt32(-num)), '-' + num + ' returns +0'); - }); - t['throws'](function () { return ES.ToInt32(v.uncoercibleObject); }, TypeError, 'uncoercibleObject throws'); - t.ok(is(ES.ToInt32(0x100000000), 0), '2^32 returns +0'); - t.ok(is(ES.ToInt32(0x100000000 - 1), -1), '2^32 - 1 returns -1'); - t.ok(is(ES.ToInt32(0x80000000), -0x80000000), '2^31 returns -2^31'); - t.ok(is(ES.ToInt32(0x80000000 - 1), 0x80000000 - 1), '2^31 - 1 returns 2^31 - 1'); - forEach([0, Infinity, NaN, 0x100000000, 0x80000000, 0x10000, 0x42], function (num) { - t.ok(is(ES.ToInt32(num), ES.ToInt32(ES.ToUint32(num))), 'ToInt32(x) === ToInt32(ToUint32(x)) for 0x' + num.toString(16)); - t.ok(is(ES.ToInt32(-num), ES.ToInt32(ES.ToUint32(-num))), 'ToInt32(x) === ToInt32(ToUint32(x)) for -0x' + num.toString(16)); - }); - t.end(); -}); - -test('ToUint32', function (t) { - t.ok(is(0, ES.ToUint32(NaN)), 'NaN coerces to +0'); - forEach([0, Infinity], function (num) { - t.ok(is(0, ES.ToUint32(num)), num + ' returns +0'); - t.ok(is(0, ES.ToUint32(-num)), '-' + num + ' returns +0'); - }); - t['throws'](function () { return ES.ToUint32(v.uncoercibleObject); }, TypeError, 'uncoercibleObject throws'); - t.ok(is(ES.ToUint32(0x100000000), 0), '2^32 returns +0'); - t.ok(is(ES.ToUint32(0x100000000 - 1), 0x100000000 - 1), '2^32 - 1 returns 2^32 - 1'); - t.ok(is(ES.ToUint32(0x80000000), 0x80000000), '2^31 returns 2^31'); - t.ok(is(ES.ToUint32(0x80000000 - 1), 0x80000000 - 1), '2^31 - 1 returns 2^31 - 1'); - forEach([0, Infinity, NaN, 0x100000000, 0x80000000, 0x10000, 0x42], function (num) { - t.ok(is(ES.ToUint32(num), ES.ToUint32(ES.ToInt32(num))), 'ToUint32(x) === ToUint32(ToInt32(x)) for 0x' + num.toString(16)); - t.ok(is(ES.ToUint32(-num), ES.ToUint32(ES.ToInt32(-num))), 'ToUint32(x) === ToUint32(ToInt32(x)) for -0x' + num.toString(16)); - }); - t.end(); -}); - -test('ToUint16', function (t) { - t.ok(is(0, ES.ToUint16(NaN)), 'NaN coerces to +0'); - forEach([0, Infinity], function (num) { - t.ok(is(0, ES.ToUint16(num)), num + ' returns +0'); - t.ok(is(0, ES.ToUint16(-num)), '-' + num + ' returns +0'); - }); - t['throws'](function () { return ES.ToUint16(v.uncoercibleObject); }, TypeError, 'uncoercibleObject throws'); - t.ok(is(ES.ToUint16(0x100000000), 0), '2^32 returns +0'); - t.ok(is(ES.ToUint16(0x100000000 - 1), 0x10000 - 1), '2^32 - 1 returns 2^16 - 1'); - t.ok(is(ES.ToUint16(0x80000000), 0), '2^31 returns +0'); - t.ok(is(ES.ToUint16(0x80000000 - 1), 0x10000 - 1), '2^31 - 1 returns 2^16 - 1'); - t.ok(is(ES.ToUint16(0x10000), 0), '2^16 returns +0'); - t.ok(is(ES.ToUint16(0x10000 - 1), 0x10000 - 1), '2^16 - 1 returns 2^16 - 1'); - t.end(); -}); - -test('ToString', function (t) { - t['throws'](function () { return ES.ToString(v.uncoercibleObject); }, TypeError, 'uncoercibleObject throws'); - t.end(); -}); - -test('ToObject', function (t) { - t['throws'](function () { return ES.ToObject(undefined); }, TypeError, 'undefined throws'); - t['throws'](function () { return ES.ToObject(null); }, TypeError, 'null throws'); - forEach(v.numbers, function (number) { - var obj = ES.ToObject(number); - t.equal(typeof obj, 'object', 'number ' + number + ' coerces to object'); - t.equal(true, obj instanceof Number, 'object of ' + number + ' is Number object'); - t.ok(is(obj.valueOf(), number), 'object of ' + number + ' coerces to ' + number); - }); - t.end(); -}); - -test('CheckObjectCoercible', function (t) { - t['throws'](function () { return ES.CheckObjectCoercible(undefined); }, TypeError, 'undefined throws'); - t['throws'](function () { return ES.CheckObjectCoercible(null); }, TypeError, 'null throws'); - var checkCoercible = function (value) { - t.doesNotThrow(function () { return ES.CheckObjectCoercible(value); }, debug(value) + ' does not throw'); - }; - forEach(v.objects.concat(v.nonNullPrimitives), checkCoercible); - t.end(); -}); - -test('IsCallable', function (t) { - t.equal(true, ES.IsCallable(function () {}), 'function is callable'); - var nonCallables = [/a/g, {}, Object.prototype, NaN].concat(v.primitives); - forEach(nonCallables, function (nonCallable) { - t.equal(false, ES.IsCallable(nonCallable), debug(nonCallable) + ' is not callable'); - }); - t.end(); -}); - -test('SameValue', function (t) { - t.equal(true, ES.SameValue(NaN, NaN), 'NaN is SameValue as NaN'); - t.equal(false, ES.SameValue(0, -0), '+0 is not SameValue as -0'); - forEach(v.objects.concat(v.primitives), function (val) { - t.equal(val === val, ES.SameValue(val, val), debug(val) + ' is SameValue to itself'); - }); - t.end(); -}); - -test('Type', function (t) { - t.equal(ES.Type(), 'Undefined', 'Type() is Undefined'); - t.equal(ES.Type(undefined), 'Undefined', 'Type(undefined) is Undefined'); - t.equal(ES.Type(null), 'Null', 'Type(null) is Null'); - t.equal(ES.Type(true), 'Boolean', 'Type(true) is Boolean'); - t.equal(ES.Type(false), 'Boolean', 'Type(false) is Boolean'); - t.equal(ES.Type(0), 'Number', 'Type(0) is Number'); - t.equal(ES.Type(NaN), 'Number', 'Type(NaN) is Number'); - t.equal(ES.Type('abc'), 'String', 'Type("abc") is String'); - t.equal(ES.Type(function () {}), 'Object', 'Type(function () {}) is Object'); - t.equal(ES.Type({}), 'Object', 'Type({}) is Object'); - t.end(); -}); - -test('IsPropertyDescriptor', function (t) { - forEach(v.primitives, function (primitive) { - t.equal(ES.IsPropertyDescriptor(primitive), false, debug(primitive) + ' is not a Property Descriptor'); - }); - - t.equal(ES.IsPropertyDescriptor({ invalid: true }), false, 'invalid keys not allowed on a Property Descriptor'); - - t.equal(ES.IsPropertyDescriptor({}), true, 'empty object is an incomplete Property Descriptor'); - - t.equal(ES.IsPropertyDescriptor(v.accessorDescriptor()), true, 'accessor descriptor is a Property Descriptor'); - t.equal(ES.IsPropertyDescriptor(v.mutatorDescriptor()), true, 'mutator descriptor is a Property Descriptor'); - t.equal(ES.IsPropertyDescriptor(v.dataDescriptor()), true, 'data descriptor is a Property Descriptor'); - t.equal(ES.IsPropertyDescriptor(v.genericDescriptor()), true, 'generic descriptor is a Property Descriptor'); - - t['throws']( - function () { ES.IsPropertyDescriptor(v.bothDescriptor()); }, - TypeError, - 'a Property Descriptor can not be both a Data and an Accessor Descriptor' - ); - - t['throws']( - function () { ES.IsPropertyDescriptor(v.bothDescriptorWritable()); }, - TypeError, - 'a Property Descriptor can not be both a Data and an Accessor Descriptor' - ); - - t.end(); -}); - -test('IsAccessorDescriptor', function (t) { - forEach(v.nonNullPrimitives.concat(null), function (primitive) { - t['throws'](function () { ES.IsAccessorDescriptor(primitive); }, TypeError, debug(primitive) + ' is not a Property Descriptor'); - }); - - t.equal(ES.IsAccessorDescriptor(), false, 'no value is not an Accessor Descriptor'); - t.equal(ES.IsAccessorDescriptor(undefined), false, 'undefined value is not an Accessor Descriptor'); - - t.equal(ES.IsAccessorDescriptor(v.accessorDescriptor()), true, 'accessor descriptor is an Accessor Descriptor'); - t.equal(ES.IsAccessorDescriptor(v.mutatorDescriptor()), true, 'mutator descriptor is an Accessor Descriptor'); - t.equal(ES.IsAccessorDescriptor(v.dataDescriptor()), false, 'data descriptor is not an Accessor Descriptor'); - t.equal(ES.IsAccessorDescriptor(v.genericDescriptor()), false, 'generic descriptor is not an Accessor Descriptor'); - - t.end(); -}); - -test('IsDataDescriptor', function (t) { - forEach(v.nonNullPrimitives.concat(null), function (primitive) { - t['throws'](function () { ES.IsDataDescriptor(primitive); }, TypeError, debug(primitive) + ' is not a Property Descriptor'); - }); - - t.equal(ES.IsDataDescriptor(), false, 'no value is not a Data Descriptor'); - t.equal(ES.IsDataDescriptor(undefined), false, 'undefined value is not a Data Descriptor'); - - t.equal(ES.IsDataDescriptor(v.accessorDescriptor()), false, 'accessor descriptor is not a Data Descriptor'); - t.equal(ES.IsDataDescriptor(v.mutatorDescriptor()), false, 'mutator descriptor is not a Data Descriptor'); - t.equal(ES.IsDataDescriptor(v.dataDescriptor()), true, 'data descriptor is a Data Descriptor'); - t.equal(ES.IsDataDescriptor(v.genericDescriptor()), false, 'generic descriptor is not a Data Descriptor'); - - t.end(); -}); - -test('IsGenericDescriptor', function (t) { - forEach(v.nonNullPrimitives.concat(null), function (primitive) { - t['throws']( - function () { ES.IsGenericDescriptor(primitive); }, - TypeError, - debug(primitive) + ' is not a Property Descriptor' - ); - }); - - t.equal(ES.IsGenericDescriptor(), false, 'no value is not a Data Descriptor'); - t.equal(ES.IsGenericDescriptor(undefined), false, 'undefined value is not a Data Descriptor'); - - t.equal(ES.IsGenericDescriptor(v.accessorDescriptor()), false, 'accessor descriptor is not a generic Descriptor'); - t.equal(ES.IsGenericDescriptor(v.mutatorDescriptor()), false, 'mutator descriptor is not a generic Descriptor'); - t.equal(ES.IsGenericDescriptor(v.dataDescriptor()), false, 'data descriptor is not a generic Descriptor'); - - t.equal(ES.IsGenericDescriptor(v.genericDescriptor()), true, 'generic descriptor is a generic Descriptor'); - - t.end(); -}); - -test('FromPropertyDescriptor', function (t) { - t.equal(ES.FromPropertyDescriptor(), undefined, 'no value begets undefined'); - t.equal(ES.FromPropertyDescriptor(undefined), undefined, 'undefined value begets undefined'); - - forEach(v.nonNullPrimitives.concat(null), function (primitive) { - t['throws']( - function () { ES.FromPropertyDescriptor(primitive); }, - TypeError, - debug(primitive) + ' is not a Property Descriptor' - ); - }); - - var accessor = v.accessorDescriptor(); - t.deepEqual(ES.FromPropertyDescriptor(accessor), { - get: accessor['[[Get]]'], - set: accessor['[[Set]]'], - enumerable: !!accessor['[[Enumerable]]'], - configurable: !!accessor['[[Configurable]]'] - }); - - var mutator = v.mutatorDescriptor(); - t.deepEqual(ES.FromPropertyDescriptor(mutator), { - get: mutator['[[Get]]'], - set: mutator['[[Set]]'], - enumerable: !!mutator['[[Enumerable]]'], - configurable: !!mutator['[[Configurable]]'] - }); - var data = v.dataDescriptor(); - t.deepEqual(ES.FromPropertyDescriptor(data), { - value: data['[[Value]]'], - writable: data['[[Writable]]'], - enumerable: !!data['[[Enumerable]]'], - configurable: !!data['[[Configurable]]'] - }); - - t['throws']( - function () { ES.FromPropertyDescriptor(v.genericDescriptor()); }, - TypeError, - 'a complete Property Descriptor is required' - ); - - t.end(); -}); - -test('ToPropertyDescriptor', function (t) { - forEach(v.nonNullPrimitives.concat(null), function (primitive) { - t['throws']( - function () { ES.ToPropertyDescriptor(primitive); }, - TypeError, - debug(primitive) + ' is not an Object' - ); - }); - - var accessor = v.accessorDescriptor(); - t.deepEqual(ES.ToPropertyDescriptor({ - get: accessor['[[Get]]'], - enumerable: !!accessor['[[Enumerable]]'], - configurable: !!accessor['[[Configurable]]'] - }), accessor); - - var mutator = v.mutatorDescriptor(); - t.deepEqual(ES.ToPropertyDescriptor({ - set: mutator['[[Set]]'], - enumerable: !!mutator['[[Enumerable]]'], - configurable: !!mutator['[[Configurable]]'] - }), mutator); - - var data = v.descriptors.nonConfigurable(v.dataDescriptor()); - t.deepEqual(ES.ToPropertyDescriptor({ - value: data['[[Value]]'], - writable: data['[[Writable]]'], - configurable: !!data['[[Configurable]]'] - }), data); - - var both = v.bothDescriptor(); - t['throws']( - function () { - ES.ToPropertyDescriptor({ get: both['[[Get]]'], value: both['[[Value]]'] }); - }, - TypeError, - 'data and accessor descriptors are mutually exclusive' - ); - - t['throws']( - function () { ES.ToPropertyDescriptor({ get: 'not callable' }); }, - TypeError, - '"get" must be undefined or callable' - ); - - t['throws']( - function () { ES.ToPropertyDescriptor({ set: 'not callable' }); }, - TypeError, - '"set" must be undefined or callable' - ); - - t.end(); -}); - -test('Abstract Equality Comparison', function (t) { - t.test('same types use ===', function (st) { - forEach(v.primitives.concat(v.objects), function (value) { - st.equal(ES['Abstract Equality Comparison'](value, value), value === value, debug(value) + ' is abstractly equal to itself'); - }); - st.end(); - }); - - t.test('different types coerce', function (st) { - var pairs = [ - [null, undefined], - [3, '3'], - [true, '3'], - [true, 3], - [false, 0], - [false, '0'], - [3, [3]], - ['3', [3]], - [true, [1]], - [false, [0]], - [String(v.coercibleObject), v.coercibleObject], - [Number(String(v.coercibleObject)), v.coercibleObject], - [Number(v.coercibleObject), v.coercibleObject], - [String(Number(v.coercibleObject)), v.coercibleObject] - ]; - forEach(pairs, function (pair) { - var a = pair[0]; - var b = pair[1]; - // eslint-disable-next-line eqeqeq - st.equal(ES['Abstract Equality Comparison'](a, b), a == b, debug(a) + ' == ' + debug(b)); - // eslint-disable-next-line eqeqeq - st.equal(ES['Abstract Equality Comparison'](b, a), b == a, debug(b) + ' == ' + debug(a)); - }); - st.end(); - }); - - t.end(); -}); - -test('Strict Equality Comparison', function (t) { - t.test('same types use ===', function (st) { - forEach(v.primitives.concat(v.objects), function (value) { - st.equal(ES['Strict Equality Comparison'](value, value), value === value, debug(value) + ' is strictly equal to itself'); - }); - st.end(); - }); - - t.test('different types are not ===', function (st) { - var pairs = [ - [null, undefined], - [3, '3'], - [true, '3'], - [true, 3], - [false, 0], - [false, '0'], - [3, [3]], - ['3', [3]], - [true, [1]], - [false, [0]], - [String(v.coercibleObject), v.coercibleObject], - [Number(String(v.coercibleObject)), v.coercibleObject], - [Number(v.coercibleObject), v.coercibleObject], - [String(Number(v.coercibleObject)), v.coercibleObject] - ]; - forEach(pairs, function (pair) { - var a = pair[0]; - var b = pair[1]; - st.equal(ES['Strict Equality Comparison'](a, b), a === b, debug(a) + ' === ' + debug(b)); - st.equal(ES['Strict Equality Comparison'](b, a), b === a, debug(b) + ' === ' + debug(a)); - }); - st.end(); - }); - - t.end(); -}); - -test('Abstract Relational Comparison', function (t) { - t.test('at least one operand is NaN', function (st) { - st.equal(ES['Abstract Relational Comparison'](NaN, {}, true), undefined, 'LeftFirst: first is NaN, returns undefined'); - st.equal(ES['Abstract Relational Comparison']({}, NaN, true), undefined, 'LeftFirst: second is NaN, returns undefined'); - st.equal(ES['Abstract Relational Comparison'](NaN, {}, false), undefined, '!LeftFirst: first is NaN, returns undefined'); - st.equal(ES['Abstract Relational Comparison']({}, NaN, false), undefined, '!LeftFirst: second is NaN, returns undefined'); - st.end(); - }); - - t.equal(ES['Abstract Relational Comparison'](3, 4, true), true, 'LeftFirst: 3 is less than 4'); - t.equal(ES['Abstract Relational Comparison'](4, 3, true), false, 'LeftFirst: 3 is not less than 4'); - t.equal(ES['Abstract Relational Comparison'](3, 4, false), true, '!LeftFirst: 3 is less than 4'); - t.equal(ES['Abstract Relational Comparison'](4, 3, false), false, '!LeftFirst: 3 is not less than 4'); - - t.equal(ES['Abstract Relational Comparison']('3', '4', true), true, 'LeftFirst: "3" is less than "4"'); - t.equal(ES['Abstract Relational Comparison']('4', '3', true), false, 'LeftFirst: "3" is not less than "4"'); - t.equal(ES['Abstract Relational Comparison']('3', '4', false), true, '!LeftFirst: "3" is less than "4"'); - t.equal(ES['Abstract Relational Comparison']('4', '3', false), false, '!LeftFirst: "3" is not less than "4"'); - - t.equal(ES['Abstract Relational Comparison'](v.coercibleObject, 42, true), true, 'LeftFirst: coercible object is less than 42'); - t.equal(ES['Abstract Relational Comparison'](42, v.coercibleObject, true), false, 'LeftFirst: 42 is not less than coercible object'); - t.equal(ES['Abstract Relational Comparison'](v.coercibleObject, 42, false), true, '!LeftFirst: coercible object is less than 42'); - t.equal(ES['Abstract Relational Comparison'](42, v.coercibleObject, false), false, '!LeftFirst: 42 is not less than coercible object'); - - t.equal(ES['Abstract Relational Comparison'](v.coercibleObject, '3', true), false, 'LeftFirst: coercible object is not less than "3"'); - t.equal(ES['Abstract Relational Comparison']('3', v.coercibleObject, true), false, 'LeftFirst: "3" is not less than coercible object'); - t.equal(ES['Abstract Relational Comparison'](v.coercibleObject, '3', false), false, '!LeftFirst: coercible object is not less than "3"'); - t.equal(ES['Abstract Relational Comparison']('3', v.coercibleObject, false), false, '!LeftFirst: "3" is not less than coercible object'); - - t.end(); -}); - -test('FromPropertyDescriptor', function (t) { - t.equal(ES.FromPropertyDescriptor(), undefined, 'no value begets undefined'); - t.equal(ES.FromPropertyDescriptor(undefined), undefined, 'undefined value begets undefined'); - - forEach(v.nonUndefinedPrimitives, function (primitive) { - t['throws']( - function () { ES.FromPropertyDescriptor(primitive); }, - TypeError, - debug(primitive) + ' is not a Property Descriptor' - ); - }); - - var accessor = v.accessorDescriptor(); - t.deepEqual(ES.FromPropertyDescriptor(accessor), { - get: accessor['[[Get]]'], - set: accessor['[[Set]]'], - enumerable: !!accessor['[[Enumerable]]'], - configurable: !!accessor['[[Configurable]]'] - }); - - var mutator = v.mutatorDescriptor(); - t.deepEqual(ES.FromPropertyDescriptor(mutator), { - get: mutator['[[Get]]'], - set: mutator['[[Set]]'], - enumerable: !!mutator['[[Enumerable]]'], - configurable: !!mutator['[[Configurable]]'] - }); - var data = v.dataDescriptor(); - t.deepEqual(ES.FromPropertyDescriptor(data), { - value: data['[[Value]]'], - writable: data['[[Writable]]'], - enumerable: !!data['[[Enumerable]]'], - configurable: !!data['[[Configurable]]'] - }); - - t['throws']( - function () { ES.FromPropertyDescriptor(v.genericDescriptor()); }, - TypeError, - 'a complete Property Descriptor is required' - ); - - t.end(); -}); - -test('SecFromTime', function (t) { - var now = new Date(); - t.equal(ES.SecFromTime(now.getTime()), now.getUTCSeconds(), 'second from Date timestamp matches getUTCSeconds'); - t.end(); -}); - -test('MinFromTime', function (t) { - var now = new Date(); - t.equal(ES.MinFromTime(now.getTime()), now.getUTCMinutes(), 'minute from Date timestamp matches getUTCMinutes'); - t.end(); -}); - -test('HourFromTime', function (t) { - var now = new Date(); - t.equal(ES.HourFromTime(now.getTime()), now.getUTCHours(), 'hour from Date timestamp matches getUTCHours'); - t.end(); -}); - -test('msFromTime', function (t) { - var now = new Date(); - t.equal(ES.msFromTime(now.getTime()), now.getUTCMilliseconds(), 'ms from Date timestamp matches getUTCMilliseconds'); - t.end(); -}); - -var msPerSecond = 1e3; -var msPerMinute = 60 * msPerSecond; -var msPerHour = 60 * msPerMinute; -var msPerDay = 24 * msPerHour; - -test('Day', function (t) { - var time = Date.UTC(2019, 8, 10, 2, 3, 4, 5); - var add = 2.5; - var later = new Date(time + (add * msPerDay)); - - t.equal(ES.Day(later.getTime()), ES.Day(time) + Math.floor(add), 'adding 2.5 days worth of ms, gives a Day delta of 2'); - t.end(); -}); - -test('TimeWithinDay', function (t) { - var time = Date.UTC(2019, 8, 10, 2, 3, 4, 5); - var add = 2.5; - var later = new Date(time + (add * msPerDay)); - - t.equal(ES.TimeWithinDay(later.getTime()), ES.TimeWithinDay(time) + (0.5 * msPerDay), 'adding 2.5 days worth of ms, gives a TimeWithinDay delta of +0.5'); - t.end(); -}); - -test('DayFromYear', function (t) { - t.equal(ES.DayFromYear(2021) - ES.DayFromYear(2020), 366, '2021 is a leap year, has 366 days'); - t.equal(ES.DayFromYear(2020) - ES.DayFromYear(2019), 365, '2020 is not a leap year, has 365 days'); - t.equal(ES.DayFromYear(2019) - ES.DayFromYear(2018), 365, '2019 is not a leap year, has 365 days'); - t.equal(ES.DayFromYear(2018) - ES.DayFromYear(2017), 365, '2018 is not a leap year, has 365 days'); - t.equal(ES.DayFromYear(2017) - ES.DayFromYear(2016), 366, '2017 is a leap year, has 366 days'); - - t.end(); -}); - -test('TimeFromYear', function (t) { - for (var i = 1900; i < 2100; i += 1) { - t.equal(ES.TimeFromYear(i), Date.UTC(i, 0, 1), 'TimeFromYear matches a Date object’s year: ' + i); - } - t.end(); -}); - -test('YearFromTime', function (t) { - for (var i = 1900; i < 2100; i += 1) { - t.equal(ES.YearFromTime(Date.UTC(i, 0, 1)), i, 'YearFromTime matches a Date object’s year on 1/1: ' + i); - t.equal(ES.YearFromTime(Date.UTC(i, 10, 1)), i, 'YearFromTime matches a Date object’s year on 10/1: ' + i); - } - t.end(); -}); - -test('WeekDay', function (t) { - var now = new Date(); - var today = now.getUTCDay(); - for (var i = 0; i < 7; i += 1) { - var weekDay = ES.WeekDay(now.getTime() + (i * msPerDay)); - t.equal(weekDay, (today + i) % 7, i + ' days after today (' + today + '), WeekDay is ' + weekDay); - } - t.end(); -}); - -test('DaysInYear', function (t) { - t.equal(ES.DaysInYear(2021), 365, '2021 is not a leap year'); - t.equal(ES.DaysInYear(2020), 366, '2020 is a leap year'); - t.equal(ES.DaysInYear(2019), 365, '2019 is not a leap year'); - t.equal(ES.DaysInYear(2018), 365, '2018 is not a leap year'); - t.equal(ES.DaysInYear(2017), 365, '2017 is not a leap year'); - t.equal(ES.DaysInYear(2016), 366, '2016 is a leap year'); - - t.end(); -}); - -test('InLeapYear', function (t) { - t.equal(ES.InLeapYear(Date.UTC(2021, 0, 1)), 0, '2021 is not a leap year'); - t.equal(ES.InLeapYear(Date.UTC(2020, 0, 1)), 1, '2020 is a leap year'); - t.equal(ES.InLeapYear(Date.UTC(2019, 0, 1)), 0, '2019 is not a leap year'); - t.equal(ES.InLeapYear(Date.UTC(2018, 0, 1)), 0, '2018 is not a leap year'); - t.equal(ES.InLeapYear(Date.UTC(2017, 0, 1)), 0, '2017 is not a leap year'); - t.equal(ES.InLeapYear(Date.UTC(2016, 0, 1)), 1, '2016 is a leap year'); - - t.end(); -}); - -test('DayWithinYear', function (t) { - t.equal(ES.DayWithinYear(Date.UTC(2019, 0, 1)), 0, '1/1 is the 1st day'); - t.equal(ES.DayWithinYear(Date.UTC(2019, 11, 31)), 364, '12/31 is the 365th day in a non leap year'); - t.equal(ES.DayWithinYear(Date.UTC(2016, 11, 31)), 365, '12/31 is the 366th day in a leap year'); - - t.end(); -}); - -test('MonthFromTime', function (t) { - t.equal(ES.MonthFromTime(Date.UTC(2019, 0, 1)), 0, 'non-leap: 1/1 gives January'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 0, 31)), 0, 'non-leap: 1/31 gives January'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 1, 1)), 1, 'non-leap: 2/1 gives February'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 1, 28)), 1, 'non-leap: 2/28 gives February'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 1, 29)), 2, 'non-leap: 2/29 gives March'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 2, 1)), 2, 'non-leap: 3/1 gives March'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 2, 31)), 2, 'non-leap: 3/31 gives March'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 3, 1)), 3, 'non-leap: 4/1 gives April'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 3, 30)), 3, 'non-leap: 4/30 gives April'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 4, 1)), 4, 'non-leap: 5/1 gives May'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 4, 31)), 4, 'non-leap: 5/31 gives May'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 5, 1)), 5, 'non-leap: 6/1 gives June'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 5, 30)), 5, 'non-leap: 6/30 gives June'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 6, 1)), 6, 'non-leap: 7/1 gives July'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 6, 31)), 6, 'non-leap: 7/31 gives July'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 7, 1)), 7, 'non-leap: 8/1 gives August'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 7, 30)), 7, 'non-leap: 8/30 gives August'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 8, 1)), 8, 'non-leap: 9/1 gives September'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 8, 30)), 8, 'non-leap: 9/30 gives September'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 9, 1)), 9, 'non-leap: 10/1 gives October'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 9, 31)), 9, 'non-leap: 10/31 gives October'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 10, 1)), 10, 'non-leap: 11/1 gives November'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 10, 30)), 10, 'non-leap: 11/30 gives November'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 11, 1)), 11, 'non-leap: 12/1 gives December'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 11, 31)), 11, 'non-leap: 12/31 gives December'); - - t.equal(ES.MonthFromTime(Date.UTC(2016, 0, 1)), 0, 'leap: 1/1 gives January'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 0, 31)), 0, 'leap: 1/31 gives January'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 1, 1)), 1, 'leap: 2/1 gives February'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 1, 28)), 1, 'leap: 2/28 gives February'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 1, 29)), 1, 'leap: 2/29 gives February'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 2, 1)), 2, 'leap: 3/1 gives March'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 2, 31)), 2, 'leap: 3/31 gives March'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 3, 1)), 3, 'leap: 4/1 gives April'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 3, 30)), 3, 'leap: 4/30 gives April'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 4, 1)), 4, 'leap: 5/1 gives May'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 4, 31)), 4, 'leap: 5/31 gives May'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 5, 1)), 5, 'leap: 6/1 gives June'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 5, 30)), 5, 'leap: 6/30 gives June'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 6, 1)), 6, 'leap: 7/1 gives July'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 6, 31)), 6, 'leap: 7/31 gives July'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 7, 1)), 7, 'leap: 8/1 gives August'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 7, 30)), 7, 'leap: 8/30 gives August'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 8, 1)), 8, 'leap: 9/1 gives September'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 8, 30)), 8, 'leap: 9/30 gives September'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 9, 1)), 9, 'leap: 10/1 gives October'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 9, 31)), 9, 'leap: 10/31 gives October'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 10, 1)), 10, 'leap: 11/1 gives November'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 10, 30)), 10, 'leap: 11/30 gives November'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 11, 1)), 11, 'leap: 12/1 gives December'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 11, 31)), 11, 'leap: 12/31 gives December'); - t.end(); -}); - -test('DateFromTime', function (t) { - var i; - for (i = 1; i <= 28; i += 1) { - t.equal(ES.DateFromTime(Date.UTC(2019, 1, i)), i, '2019.02.' + i + ' is date ' + i); - } - for (i = 1; i <= 29; i += 1) { - t.equal(ES.DateFromTime(Date.UTC(2016, 1, i)), i, '2016.02.' + i + ' is date ' + i); - } - for (i = 1; i <= 30; i += 1) { - t.equal(ES.DateFromTime(Date.UTC(2019, 8, i)), i, '2019.09.' + i + ' is date ' + i); - } - for (i = 1; i <= 31; i += 1) { - t.equal(ES.DateFromTime(Date.UTC(2019, 9, i)), i, '2019.10.' + i + ' is date ' + i); - } - t.end(); -}); - -test('MakeDay', function (t) { - var day2015 = 16687; - t.equal(ES.MakeDay(2015, 8, 9), day2015, '2015.09.09 is day 16687'); - var day2016 = day2015 + 366; // 2016 is a leap year - t.equal(ES.MakeDay(2016, 8, 9), day2016, '2015.09.09 is day 17053'); - var day2017 = day2016 + 365; - t.equal(ES.MakeDay(2017, 8, 9), day2017, '2017.09.09 is day 17418'); - var day2018 = day2017 + 365; - t.equal(ES.MakeDay(2018, 8, 9), day2018, '2018.09.09 is day 17783'); - var day2019 = day2018 + 365; - t.equal(ES.MakeDay(2019, 8, 9), day2019, '2019.09.09 is day 18148'); - t.end(); -}); - -test('MakeDate', function (t) { - forEach(v.infinities.concat(NaN), function (nonFiniteNumber) { - t.ok(is(ES.MakeDate(nonFiniteNumber, 0), NaN), debug(nonFiniteNumber) + ' is not a finite `day`'); - t.ok(is(ES.MakeDate(0, nonFiniteNumber), NaN), debug(nonFiniteNumber) + ' is not a finite `time`'); - }); - t.equal(ES.MakeDate(0, 0), 0, 'zero day and zero time is zero date'); - t.equal(ES.MakeDate(0, 123), 123, 'zero day and nonzero time is a date of the "time"'); - t.equal(ES.MakeDate(1, 0), msPerDay, 'day of 1 and zero time is a date of "ms per day"'); - t.equal(ES.MakeDate(3, 0), 3 * msPerDay, 'day of 3 and zero time is a date of thrice "ms per day"'); - t.equal(ES.MakeDate(1, 123), msPerDay + 123, 'day of 1 and nonzero time is a date of "ms per day" plus the "time"'); - t.equal(ES.MakeDate(3, 123), (3 * msPerDay) + 123, 'day of 3 and nonzero time is a date of thrice "ms per day" plus the "time"'); - - t.end(); -}); - -test('MakeTime', function (t) { - forEach(v.infinities.concat(NaN), function (nonFiniteNumber) { - t.ok(is(ES.MakeTime(nonFiniteNumber, 0, 0, 0), NaN), debug(nonFiniteNumber) + ' is not a finite `hour`'); - t.ok(is(ES.MakeTime(0, nonFiniteNumber, 0, 0), NaN), debug(nonFiniteNumber) + ' is not a finite `min`'); - t.ok(is(ES.MakeTime(0, 0, nonFiniteNumber, 0), NaN), debug(nonFiniteNumber) + ' is not a finite `sec`'); - t.ok(is(ES.MakeTime(0, 0, 0, nonFiniteNumber), NaN), debug(nonFiniteNumber) + ' is not a finite `ms`'); - }); - - t.equal( - ES.MakeTime(1.2, 2.3, 3.4, 4.5), - (1 * msPerHour) + (2 * msPerMinute) + (3 * msPerSecond) + 4, - 'all numbers are converted to integer, multiplied by the right number of ms, and summed' - ); - t.end(); -}); - -test('TimeClip', function (t) { - forEach(v.infinities.concat(NaN), function (nonFiniteNumber) { - t.ok(is(ES.TimeClip(nonFiniteNumber), NaN), debug(nonFiniteNumber) + ' is not a finite `time`'); - }); - t.ok(is(ES.TimeClip(8.64e15 + 1), NaN), '8.64e15 is the largest magnitude considered "finite"'); - t.ok(is(ES.TimeClip(-8.64e15 - 1), NaN), '-8.64e15 is the largest magnitude considered "finite"'); - - forEach(v.zeroes.concat([-10, 10, Date.now()]), function (time) { - t.equal(ES.TimeClip(time), time, debug(time) + ' is a time of ' + debug(time)); - }); - - t.end(); -}); - -test('modulo', function (t) { - t.equal(3 % 2, 1, '+3 % 2 is +1'); - t.equal(ES.modulo(3, 2), 1, '+3 mod 2 is +1'); - - t.equal(-3 % 2, -1, '-3 % 2 is -1'); - t.equal(ES.modulo(-3, 2), 1, '-3 mod 2 is +1'); - t.end(); -}); diff --git a/scripts/2.5/node_modules/es-abstract/test/es6.js b/scripts/2.5/node_modules/es-abstract/test/es6.js deleted file mode 100644 index e7c9d98a..00000000 --- a/scripts/2.5/node_modules/es-abstract/test/es6.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; - -var test = require('tape'); - -var ES = require('../'); -var ES6 = ES.ES6; -var ES2015 = ES.ES2015; -var ES6entry = require('../es6'); - -test('legacy es6 export', function (t) { - t.equal(ES6, ES2015, 'main ES6 === main ES2015'); - t.end(); -}); - -test('legacy es6 entry point', function (t) { - t.equal(ES6, ES6entry, 'main ES6 === ES6 entry point'); - t.end(); -}); diff --git a/scripts/2.5/node_modules/es-abstract/test/es7.js b/scripts/2.5/node_modules/es-abstract/test/es7.js deleted file mode 100644 index ee57e153..00000000 --- a/scripts/2.5/node_modules/es-abstract/test/es7.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; - -var test = require('tape'); - -var ES = require('../'); -var ES7 = ES.ES7; -var ES2016 = ES.ES2016; -var ES7entry = require('../es7'); - -test('legacy es7 export', function (t) { - t.equal(ES7, ES2016, 'main ES7 === main ES2016'); - t.end(); -}); - -test('legacy es7 entry point', function (t) { - t.equal(ES7, ES7entry, 'main ES7 === ES7 entry point'); - t.end(); -}); diff --git a/scripts/2.5/node_modules/es-abstract/test/helpers/assertRecord.js b/scripts/2.5/node_modules/es-abstract/test/helpers/assertRecord.js deleted file mode 100644 index 22e1aea4..00000000 --- a/scripts/2.5/node_modules/es-abstract/test/helpers/assertRecord.js +++ /dev/null @@ -1,60 +0,0 @@ -'use strict'; - -var forEach = require('foreach'); -var debug = require('object-inspect'); - -var assertRecord = require('../../helpers/assertRecord'); -var v = require('./values'); - -module.exports = function assertRecordTests(ES, test) { - test('Property Descriptor', function (t) { - var record = 'Property Descriptor'; - - forEach(v.nonUndefinedPrimitives, function (primitive) { - t['throws']( - function () { assertRecord(ES, record, 'arg', primitive); }, - TypeError, - debug(primitive) + ' is not a Property Descriptor' - ); - }); - - t['throws']( - function () { assertRecord(ES, record, 'arg', { invalid: true }); }, - TypeError, - 'invalid keys not allowed on a Property Descriptor' - ); - - t.doesNotThrow( - function () { assertRecord(ES, record, 'arg', {}); }, - 'empty object is an incomplete Property Descriptor' - ); - - t.doesNotThrow( - function () { assertRecord(ES, record, 'arg', v.accessorDescriptor()); }, - 'accessor descriptor is a Property Descriptor' - ); - - t.doesNotThrow( - function () { assertRecord(ES, record, 'arg', v.mutatorDescriptor()); }, - 'mutator descriptor is a Property Descriptor' - ); - - t.doesNotThrow( - function () { assertRecord(ES, record, 'arg', v.dataDescriptor()); }, - 'data descriptor is a Property Descriptor' - ); - - t.doesNotThrow( - function () { assertRecord(ES, record, 'arg', v.genericDescriptor()); }, - 'generic descriptor is a Property Descriptor' - ); - - t['throws']( - function () { assertRecord(ES, record, 'arg', v.bothDescriptor()); }, - TypeError, - 'a Property Descriptor can not be both a Data and an Accessor Descriptor' - ); - - t.end(); - }); -}; diff --git a/scripts/2.5/node_modules/es-abstract/test/helpers/getSymbolDescription.js b/scripts/2.5/node_modules/es-abstract/test/helpers/getSymbolDescription.js deleted file mode 100644 index 49af899f..00000000 --- a/scripts/2.5/node_modules/es-abstract/test/helpers/getSymbolDescription.js +++ /dev/null @@ -1,50 +0,0 @@ -'use strict'; - -var test = require('tape'); -var debug = require('object-inspect'); -var forEach = require('foreach'); - -var v = require('./values'); -var getSymbolDescription = require('../../helpers/getSymbolDescription'); - -test('getSymbolDescription', function (t) { - t.test('no symbols', { skip: v.hasSymbols }, function (st) { - st['throws']( - getSymbolDescription, - SyntaxError, - 'requires Symbol support' - ); - - st.end(); - }); - - forEach(v.nonSymbolPrimitives.concat(v.objects), function (nonSymbol) { - t['throws']( - function () { getSymbolDescription(nonSymbol); }, - TypeError, - debug(nonSymbol) + ' is not a Symbol' - ); - }); - - t.test('with symbols', { skip: !v.hasSymbols }, function (st) { - forEach( - [ - [Symbol(), undefined], - [Symbol(undefined), undefined], - [Symbol(null), 'null'], - [Symbol(''), ''], - [Symbol.iterator, 'Symbol.iterator'], - [Symbol('foo'), 'foo'] - ], - function (pair) { - var sym = pair[0]; - var desc = pair[1]; - st.equal(getSymbolDescription(sym), desc, debug(sym) + ' yields ' + debug(desc)); - } - ); - - st.end(); - }); - - t.end(); -}); diff --git a/scripts/2.5/node_modules/es-abstract/test/helpers/values.js b/scripts/2.5/node_modules/es-abstract/test/helpers/values.js deleted file mode 100644 index ccef743a..00000000 --- a/scripts/2.5/node_modules/es-abstract/test/helpers/values.js +++ /dev/null @@ -1,121 +0,0 @@ -'use strict'; - -var assign = require('../../helpers/assign'); - -var hasSymbols = require('has-symbols')(); - -var coercibleObject = { valueOf: function () { return 3; }, toString: function () { return 42; } }; -var coercibleFnObject = { - valueOf: function () { return function valueOfFn() {}; }, - toString: function () { return 42; } -}; -var valueOfOnlyObject = { valueOf: function () { return 4; }, toString: function () { return {}; } }; -var toStringOnlyObject = { valueOf: function () { return {}; }, toString: function () { return 7; } }; -var uncoercibleObject = { valueOf: function () { return {}; }, toString: function () { return {}; } }; -var uncoercibleFnObject = { - valueOf: function () { return function valueOfFn() {}; }, - toString: function () { return function toStrFn() {}; } -}; -var objects = [{}, coercibleObject, coercibleFnObject, toStringOnlyObject, valueOfOnlyObject]; -var nullPrimitives = [undefined, null]; -var nonIntegerNumbers = [-1.3, 0.2, 1.8, 1 / 3]; -var zeroes = [0, -0]; -var infinities = [Infinity, -Infinity]; -var numbers = zeroes.concat([42], infinities, nonIntegerNumbers); -var strings = ['', 'foo', 'a\uD83D\uDCA9c']; -var booleans = [true, false]; -var symbols = hasSymbols ? [Symbol.iterator, Symbol('foo')] : []; -var nonSymbolPrimitives = [].concat(nullPrimitives, booleans, strings, numbers); -var nonNumberPrimitives = [].concat(nullPrimitives, booleans, strings, symbols); -var nonNullPrimitives = [].concat(booleans, strings, numbers, symbols); -var nonUndefinedPrimitives = [].concat(null, nonNullPrimitives); -var nonStrings = [].concat(nullPrimitives, booleans, numbers, symbols, objects); -var primitives = [].concat(nullPrimitives, nonNullPrimitives); -var nonPropertyKeys = [].concat(nullPrimitives, booleans, numbers, objects); -var propertyKeys = [].concat(strings, symbols); -var nonBooleans = [].concat(nullPrimitives, strings, symbols, numbers, objects); -var falsies = [].concat(nullPrimitives, false, '', 0, -0, NaN); -var truthies = [].concat(true, 'foo', 42, symbols, objects); -var timestamps = [].concat(0, 946713600000, 1546329600000); -var nonFunctions = [].concat(primitives, objects, [42]); -var nonArrays = [].concat(nonFunctions); - -var descriptors = { - configurable: function (descriptor) { - return assign(assign({}, descriptor), { '[[Configurable]]': true }); - }, - nonConfigurable: function (descriptor) { - return assign(assign({}, descriptor), { '[[Configurable]]': false }); - }, - enumerable: function (descriptor) { - return assign(assign({}, descriptor), { '[[Enumerable]]': true }); - }, - nonEnumerable: function (descriptor) { - return assign(assign({}, descriptor), { '[[Enumerable]]': false }); - }, - writable: function (descriptor) { - return assign(assign({}, descriptor), { '[[Writable]]': true }); - }, - nonWritable: function (descriptor) { - return assign(assign({}, descriptor), { '[[Writable]]': false }); - } -}; - -module.exports = { - coercibleObject: coercibleObject, - coercibleFnObject: coercibleFnObject, - valueOfOnlyObject: valueOfOnlyObject, - toStringOnlyObject: toStringOnlyObject, - uncoercibleObject: uncoercibleObject, - uncoercibleFnObject: uncoercibleFnObject, - objects: objects, - nonFunctions: nonFunctions, - nonArrays: nonArrays, - nullPrimitives: nullPrimitives, - numbers: numbers, - zeroes: zeroes, - infinities: infinities, - strings: strings, - booleans: booleans, - symbols: symbols, - hasSymbols: hasSymbols, - nonSymbolPrimitives: nonSymbolPrimitives, - nonNumberPrimitives: nonNumberPrimitives, - nonNullPrimitives: nonNullPrimitives, - nonUndefinedPrimitives: nonUndefinedPrimitives, - nonStrings: nonStrings, - nonNumbers: nonNumberPrimitives.concat(objects), - nonIntegerNumbers: nonIntegerNumbers, - primitives: primitives, - nonPropertyKeys: nonPropertyKeys, - propertyKeys: propertyKeys, - nonBooleans: nonBooleans, - falsies: falsies, - truthies: truthies, - timestamps: timestamps, - bothDescriptor: function () { - return { '[[Get]]': function () {}, '[[Value]]': true }; - }, - bothDescriptorWritable: function () { - return descriptors.writable({ '[[Get]]': function () {} }); - }, - accessorDescriptor: function (value) { - return descriptors.enumerable(descriptors.configurable({ - '[[Get]]': function get() { return value; } - })); - }, - mutatorDescriptor: function () { - return descriptors.enumerable(descriptors.configurable({ - '[[Set]]': function () {} - })); - }, - dataDescriptor: function (value) { - return descriptors.nonWritable({ - '[[Value]]': arguments.length > 0 ? value : 42 - }); - }, - genericDescriptor: function () { - return descriptors.configurable(descriptors.nonEnumerable()); - }, - descriptors: descriptors -}; diff --git a/scripts/2.5/node_modules/es-abstract/test/index.js b/scripts/2.5/node_modules/es-abstract/test/index.js deleted file mode 100644 index a435044b..00000000 --- a/scripts/2.5/node_modules/es-abstract/test/index.js +++ /dev/null @@ -1,30 +0,0 @@ -'use strict'; - -var ES = require('../'); -var test = require('tape'); - -var ESkeys = Object.keys(ES).sort(); -var ES6keys = Object.keys(ES.ES6).sort(); - -test('exposed properties', function (t) { - t.deepEqual(ESkeys, ES6keys.concat(['ES2019', 'ES2018', 'ES2017', 'ES7', 'ES2016', 'ES6', 'ES2015', 'ES5']).sort(), 'main ES object keys match ES6 keys'); - t.end(); -}); - -test('methods match', function (t) { - ES6keys.forEach(function (key) { - t.equal(ES.ES6[key], ES[key], 'method ' + key + ' on main ES object is ES6 method'); - }); - t.end(); -}); - -require('./GetIntrinsic'); - -require('./es5'); -require('./es6'); -require('./es2015'); -require('./es7'); -require('./es2016'); -require('./es2017'); -require('./es2018'); -require('./es2019'); diff --git a/scripts/2.5/node_modules/es-abstract/test/tests.js b/scripts/2.5/node_modules/es-abstract/test/tests.js deleted file mode 100644 index eb8f91df..00000000 --- a/scripts/2.5/node_modules/es-abstract/test/tests.js +++ /dev/null @@ -1,4075 +0,0 @@ -'use strict'; - -var test = require('tape'); - -var forEach = require('foreach'); -var is = require('object-is'); -var debug = require('object-inspect'); -var assign = require('object.assign'); -var keys = require('object-keys'); -var has = require('has'); -var arrowFns = require('make-arrow-function').list(); - -var getInferredName = require('../helpers/getInferredName'); -var assertRecordTests = require('./helpers/assertRecord'); -var v = require('./helpers/values'); -var diffOps = require('./diffOps'); - -var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || Math.pow(2, 53) - 1; - -var getArraySubclassWithSpeciesConstructor = function getArraySubclass(speciesConstructor) { - var Bar = function Bar() { - var inst = []; - Object.setPrototypeOf(inst, Bar.prototype); - Object.defineProperty(inst, 'constructor', { value: Bar }); - return inst; - }; - Bar.prototype = Object.create(Array.prototype); - Object.setPrototypeOf(Bar, Array); - Object.defineProperty(Bar, Symbol.species, { value: speciesConstructor }); - - return Bar; -}; - -var testIterator = function (t, iterator, expected) { - var resultCount = 0; - var result; - while (result = iterator.next(), !result.done) { // eslint-disable-line no-sequences - t.deepEqual(result, { done: false, value: expected[resultCount] }, 'result ' + resultCount); - resultCount += 1; - } - t.equal(resultCount, expected.length, 'expected ' + expected.length + ', got ' + resultCount); -}; - -var hasSpecies = v.hasSymbols && Symbol.species; - -var hasGroups = 'groups' in (/a/).exec('a'); -var groups = function groups(matchObject) { - return hasGroups ? assign(matchObject, { groups: matchObject.groups }) : matchObject; -}; - -var testEnumerableOwnNames = function (t, enumerableOwnNames) { - forEach(v.primitives, function (nonObject) { - t['throws']( - function () { enumerableOwnNames(nonObject); }, - debug(nonObject) + ' is not an Object' - ); - }); - - var Child = function Child() { - this.own = {}; - }; - Child.prototype = { - inherited: {} - }; - - var obj = new Child(); - - t.equal('own' in obj, true, 'has "own"'); - t.equal(has(obj, 'own'), true, 'has own "own"'); - t.equal(Object.prototype.propertyIsEnumerable.call(obj, 'own'), true, 'has enumerable "own"'); - - t.equal('inherited' in obj, true, 'has "inherited"'); - t.equal(has(obj, 'inherited'), false, 'has non-own "inherited"'); - t.equal(has(Child.prototype, 'inherited'), true, 'Child.prototype has own "inherited"'); - t.equal(Child.prototype.inherited, obj.inherited, 'Child.prototype.inherited === obj.inherited'); - t.equal(Object.prototype.propertyIsEnumerable.call(Child.prototype, 'inherited'), true, 'has enumerable "inherited"'); - - t.equal('toString' in obj, true, 'has "toString"'); - t.equal(has(obj, 'toString'), false, 'has non-own "toString"'); - t.equal(has(Object.prototype, 'toString'), true, 'Object.prototype has own "toString"'); - t.equal(Object.prototype.toString, obj.toString, 'Object.prototype.toString === obj.toString'); - // eslint-disable-next-line no-useless-call - t.equal(Object.prototype.propertyIsEnumerable.call(Object.prototype, 'toString'), false, 'has non-enumerable "toString"'); - - return obj; -}; - -var es2015 = function ES2015(ES, ops, expectedMissing, skips) { - test('has expected operations', function (t) { - var diff = diffOps(ES, ops, expectedMissing); - - t.deepEqual(diff.extra, [], 'no extra ops'); - - t.deepEqual(diff.missing, [], 'no unexpected missing ops'); - - t.end(); - }); - - test('ToPrimitive', function (t) { - t.test('primitives', function (st) { - var testPrimitive = function (primitive) { - st.ok(is(ES.ToPrimitive(primitive), primitive), debug(primitive) + ' is returned correctly'); - }; - forEach(v.primitives, testPrimitive); - st.end(); - }); - - t.test('objects', function (st) { - st.equal(ES.ToPrimitive(v.coercibleObject), 3, 'coercibleObject with no hint coerces to valueOf'); - st.ok(is(ES.ToPrimitive({}), '[object Object]'), '{} with no hint coerces to Object#toString'); - st.equal(ES.ToPrimitive(v.coercibleObject, Number), 3, 'coercibleObject with hint Number coerces to valueOf'); - st.ok(is(ES.ToPrimitive({}, Number), '[object Object]'), '{} with hint Number coerces to NaN'); - st.equal(ES.ToPrimitive(v.coercibleObject, String), 42, 'coercibleObject with hint String coerces to nonstringified toString'); - st.equal(ES.ToPrimitive({}, String), '[object Object]', '{} with hint String coerces to Object#toString'); - st.equal(ES.ToPrimitive(v.toStringOnlyObject), 7, 'toStringOnlyObject returns non-stringified toString'); - st.equal(ES.ToPrimitive(v.valueOfOnlyObject), 4, 'valueOfOnlyObject returns valueOf'); - st['throws'](function () { return ES.ToPrimitive(v.uncoercibleObject); }, TypeError, 'uncoercibleObject throws a TypeError'); - st.end(); - }); - - t.test('dates', function (st) { - var invalid = new Date(NaN); - st.equal(ES.ToPrimitive(invalid), Date.prototype.toString.call(invalid), 'invalid Date coerces to Date#toString'); - var now = new Date(); - st.equal(ES.ToPrimitive(now), Date.prototype.toString.call(now), 'Date coerces to Date#toString'); - st.end(); - }); - - t.end(); - }); - - test('ToBoolean', function (t) { - t.equal(false, ES.ToBoolean(undefined), 'undefined coerces to false'); - t.equal(false, ES.ToBoolean(null), 'null coerces to false'); - t.equal(false, ES.ToBoolean(false), 'false returns false'); - t.equal(true, ES.ToBoolean(true), 'true returns true'); - - t.test('numbers', function (st) { - forEach(v.zeroes.concat(NaN), function (falsyNumber) { - st.equal(false, ES.ToBoolean(falsyNumber), 'falsy number ' + falsyNumber + ' coerces to false'); - }); - forEach(v.infinities.concat([42, 1]), function (truthyNumber) { - st.equal(true, ES.ToBoolean(truthyNumber), 'truthy number ' + truthyNumber + ' coerces to true'); - }); - - st.end(); - }); - - t.equal(false, ES.ToBoolean(''), 'empty string coerces to false'); - t.equal(true, ES.ToBoolean('foo'), 'nonempty string coerces to true'); - - t.test('objects', function (st) { - forEach(v.objects, function (obj) { - st.equal(true, ES.ToBoolean(obj), 'object coerces to true'); - }); - st.equal(true, ES.ToBoolean(v.uncoercibleObject), 'uncoercibleObject coerces to true'); - - st.end(); - }); - - t.end(); - }); - - test('ToNumber', function (t) { - t.ok(is(NaN, ES.ToNumber(undefined)), 'undefined coerces to NaN'); - t.ok(is(ES.ToNumber(null), 0), 'null coerces to +0'); - t.ok(is(ES.ToNumber(false), 0), 'false coerces to +0'); - t.equal(1, ES.ToNumber(true), 'true coerces to 1'); - - t.test('numbers', function (st) { - st.ok(is(NaN, ES.ToNumber(NaN)), 'NaN returns itself'); - forEach(v.zeroes.concat(v.infinities, 42), function (num) { - st.equal(num, ES.ToNumber(num), num + ' returns itself'); - }); - forEach(['foo', '0', '4a', '2.0', 'Infinity', '-Infinity'], function (numString) { - st.ok(is(+numString, ES.ToNumber(numString)), '"' + numString + '" coerces to ' + Number(numString)); - }); - st.end(); - }); - - t.test('objects', function (st) { - forEach(v.objects, function (object) { - st.ok(is(ES.ToNumber(object), ES.ToNumber(ES.ToPrimitive(object))), 'object ' + object + ' coerces to same as ToPrimitive of object does'); - }); - st['throws'](function () { return ES.ToNumber(v.uncoercibleObject); }, TypeError, 'uncoercibleObject throws'); - st.end(); - }); - - t.test('binary literals', function (st) { - st.equal(ES.ToNumber('0b10'), 2, '0b10 is 2'); - st.equal(ES.ToNumber({ toString: function () { return '0b11'; } }), 3, 'Object that toStrings to 0b11 is 3'); - - st.equal(true, is(ES.ToNumber('0b12'), NaN), '0b12 is NaN'); - st.equal(true, is(ES.ToNumber({ toString: function () { return '0b112'; } }), NaN), 'Object that toStrings to 0b112 is NaN'); - st.end(); - }); - - t.test('octal literals', function (st) { - st.equal(ES.ToNumber('0o10'), 8, '0o10 is 8'); - st.equal(ES.ToNumber({ toString: function () { return '0o11'; } }), 9, 'Object that toStrings to 0o11 is 9'); - - st.equal(true, is(ES.ToNumber('0o18'), NaN), '0o18 is NaN'); - st.equal(true, is(ES.ToNumber({ toString: function () { return '0o118'; } }), NaN), 'Object that toStrings to 0o118 is NaN'); - st.end(); - }); - - t.test('signed hex numbers', function (st) { - st.equal(true, is(ES.ToNumber('-0xF'), NaN), '-0xF is NaN'); - st.equal(true, is(ES.ToNumber(' -0xF '), NaN), 'space-padded -0xF is NaN'); - st.equal(true, is(ES.ToNumber('+0xF'), NaN), '+0xF is NaN'); - st.equal(true, is(ES.ToNumber(' +0xF '), NaN), 'space-padded +0xF is NaN'); - - st.end(); - }); - - t.test('trimming of whitespace and non-whitespace characters', function (st) { - var whitespace = ' \t\x0b\f\xa0\ufeff\n\r\u2028\u2029\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000'; - st.equal(0, ES.ToNumber(whitespace + 0 + whitespace), 'whitespace is trimmed'); - - // Zero-width space (zws), next line character (nel), and non-character (bom) are not whitespace. - var nonWhitespaces = { - '\\u0085': '\u0085', - '\\u200b': '\u200b', - '\\ufffe': '\ufffe' - }; - - forEach(nonWhitespaces, function (desc, nonWS) { - st.equal(true, is(ES.ToNumber(nonWS + 0 + nonWS), NaN), 'non-whitespace ' + desc + ' not trimmed'); - }); - - st.end(); - }); - - forEach(v.symbols, function (symbol) { - t['throws']( - function () { ES.ToNumber(symbol); }, - TypeError, - 'Symbols can’t be converted to a Number: ' + debug(symbol) - ); - }); - - t.test('dates', function (st) { - var invalid = new Date(NaN); - st.ok(is(ES.ToNumber(invalid), NaN), 'invalid Date coerces to NaN'); - var now = Date.now(); - st.equal(ES.ToNumber(new Date(now)), now, 'Date coerces to timestamp'); - st.end(); - }); - - t.end(); - }); - - test('ToInteger', function (t) { - t.ok(is(0, ES.ToInteger(NaN)), 'NaN coerces to +0'); - forEach([0, Infinity, 42], function (num) { - t.ok(is(num, ES.ToInteger(num)), num + ' returns itself'); - t.ok(is(-num, ES.ToInteger(-num)), '-' + num + ' returns itself'); - }); - t.equal(3, ES.ToInteger(Math.PI), 'pi returns 3'); - t['throws'](function () { return ES.ToInteger(v.uncoercibleObject); }, TypeError, 'uncoercibleObject throws'); - t.end(); - }); - - test('ToInt32', function (t) { - t.ok(is(0, ES.ToInt32(NaN)), 'NaN coerces to +0'); - forEach([0, Infinity], function (num) { - t.ok(is(0, ES.ToInt32(num)), num + ' returns +0'); - t.ok(is(0, ES.ToInt32(-num)), '-' + num + ' returns +0'); - }); - t['throws'](function () { return ES.ToInt32(v.uncoercibleObject); }, TypeError, 'uncoercibleObject throws'); - t.ok(is(ES.ToInt32(0x100000000), 0), '2^32 returns +0'); - t.ok(is(ES.ToInt32(0x100000000 - 1), -1), '2^32 - 1 returns -1'); - t.ok(is(ES.ToInt32(0x80000000), -0x80000000), '2^31 returns -2^31'); - t.ok(is(ES.ToInt32(0x80000000 - 1), 0x80000000 - 1), '2^31 - 1 returns 2^31 - 1'); - forEach([0, Infinity, NaN, 0x100000000, 0x80000000, 0x10000, 0x42], function (num) { - t.ok(is(ES.ToInt32(num), ES.ToInt32(ES.ToUint32(num))), 'ToInt32(x) === ToInt32(ToUint32(x)) for 0x' + num.toString(16)); - t.ok(is(ES.ToInt32(-num), ES.ToInt32(ES.ToUint32(-num))), 'ToInt32(x) === ToInt32(ToUint32(x)) for -0x' + num.toString(16)); - }); - t.end(); - }); - - test('ToUint32', function (t) { - t.ok(is(0, ES.ToUint32(NaN)), 'NaN coerces to +0'); - forEach([0, Infinity], function (num) { - t.ok(is(0, ES.ToUint32(num)), num + ' returns +0'); - t.ok(is(0, ES.ToUint32(-num)), '-' + num + ' returns +0'); - }); - t['throws'](function () { return ES.ToUint32(v.uncoercibleObject); }, TypeError, 'uncoercibleObject throws'); - t.ok(is(ES.ToUint32(0x100000000), 0), '2^32 returns +0'); - t.ok(is(ES.ToUint32(0x100000000 - 1), 0x100000000 - 1), '2^32 - 1 returns 2^32 - 1'); - t.ok(is(ES.ToUint32(0x80000000), 0x80000000), '2^31 returns 2^31'); - t.ok(is(ES.ToUint32(0x80000000 - 1), 0x80000000 - 1), '2^31 - 1 returns 2^31 - 1'); - forEach([0, Infinity, NaN, 0x100000000, 0x80000000, 0x10000, 0x42], function (num) { - t.ok(is(ES.ToUint32(num), ES.ToUint32(ES.ToInt32(num))), 'ToUint32(x) === ToUint32(ToInt32(x)) for 0x' + num.toString(16)); - t.ok(is(ES.ToUint32(-num), ES.ToUint32(ES.ToInt32(-num))), 'ToUint32(x) === ToUint32(ToInt32(x)) for -0x' + num.toString(16)); - }); - t.end(); - }); - - test('ToInt16', function (t) { - t.ok(is(0, ES.ToInt16(NaN)), 'NaN coerces to +0'); - forEach([0, Infinity], function (num) { - t.ok(is(0, ES.ToInt16(num)), num + ' returns +0'); - t.ok(is(0, ES.ToInt16(-num)), '-' + num + ' returns +0'); - }); - t['throws'](function () { return ES.ToInt16(v.uncoercibleObject); }, TypeError, 'uncoercibleObject throws'); - t.ok(is(ES.ToInt16(0x100000000), 0), '2^32 returns +0'); - t.ok(is(ES.ToInt16(0x100000000 - 1), -1), '2^32 - 1 returns -1'); - t.ok(is(ES.ToInt16(0x80000000), 0), '2^31 returns +0'); - t.ok(is(ES.ToInt16(0x80000000 - 1), -1), '2^31 - 1 returns -1'); - t.ok(is(ES.ToInt16(0x10000), 0), '2^16 returns +0'); - t.ok(is(ES.ToInt16(0x10000 - 1), -1), '2^16 - 1 returns -1'); - t.end(); - }); - - test('ToUint16', function (t) { - t.ok(is(0, ES.ToUint16(NaN)), 'NaN coerces to +0'); - forEach([0, Infinity], function (num) { - t.ok(is(0, ES.ToUint16(num)), num + ' returns +0'); - t.ok(is(0, ES.ToUint16(-num)), '-' + num + ' returns +0'); - }); - t['throws'](function () { return ES.ToUint16(v.uncoercibleObject); }, TypeError, 'uncoercibleObject throws'); - t.ok(is(ES.ToUint16(0x100000000), 0), '2^32 returns +0'); - t.ok(is(ES.ToUint16(0x100000000 - 1), 0x10000 - 1), '2^32 - 1 returns 2^16 - 1'); - t.ok(is(ES.ToUint16(0x80000000), 0), '2^31 returns +0'); - t.ok(is(ES.ToUint16(0x80000000 - 1), 0x10000 - 1), '2^31 - 1 returns 2^16 - 1'); - t.ok(is(ES.ToUint16(0x10000), 0), '2^16 returns +0'); - t.ok(is(ES.ToUint16(0x10000 - 1), 0x10000 - 1), '2^16 - 1 returns 2^16 - 1'); - t.end(); - }); - - test('ToInt8', function (t) { - t.ok(is(0, ES.ToInt8(NaN)), 'NaN coerces to +0'); - forEach([0, Infinity], function (num) { - t.ok(is(0, ES.ToInt8(num)), num + ' returns +0'); - t.ok(is(0, ES.ToInt8(-num)), '-' + num + ' returns +0'); - }); - t['throws'](function () { return ES.ToInt8(v.uncoercibleObject); }, TypeError, 'uncoercibleObject throws'); - t.ok(is(ES.ToInt8(0x100000000), 0), '2^32 returns +0'); - t.ok(is(ES.ToInt8(0x100000000 - 1), -1), '2^32 - 1 returns -1'); - t.ok(is(ES.ToInt8(0x80000000), 0), '2^31 returns +0'); - t.ok(is(ES.ToInt8(0x80000000 - 1), -1), '2^31 - 1 returns -1'); - t.ok(is(ES.ToInt8(0x10000), 0), '2^16 returns +0'); - t.ok(is(ES.ToInt8(0x10000 - 1), -1), '2^16 - 1 returns -1'); - t.ok(is(ES.ToInt8(0x100), 0), '2^8 returns +0'); - t.ok(is(ES.ToInt8(0x100 - 1), -1), '2^8 - 1 returns -1'); - t.ok(is(ES.ToInt8(0x10), 0x10), '2^4 returns 2^4'); - t.end(); - }); - - test('ToUint8', function (t) { - t.ok(is(0, ES.ToUint8(NaN)), 'NaN coerces to +0'); - forEach([0, Infinity], function (num) { - t.ok(is(0, ES.ToUint8(num)), num + ' returns +0'); - t.ok(is(0, ES.ToUint8(-num)), '-' + num + ' returns +0'); - }); - t['throws'](function () { return ES.ToUint8(v.uncoercibleObject); }, TypeError, 'uncoercibleObject throws'); - t.ok(is(ES.ToUint8(0x100000000), 0), '2^32 returns +0'); - t.ok(is(ES.ToUint8(0x100000000 - 1), 0x100 - 1), '2^32 - 1 returns 2^8 - 1'); - t.ok(is(ES.ToUint8(0x80000000), 0), '2^31 returns +0'); - t.ok(is(ES.ToUint8(0x80000000 - 1), 0x100 - 1), '2^31 - 1 returns 2^8 - 1'); - t.ok(is(ES.ToUint8(0x10000), 0), '2^16 returns +0'); - t.ok(is(ES.ToUint8(0x10000 - 1), 0x100 - 1), '2^16 - 1 returns 2^8 - 1'); - t.ok(is(ES.ToUint8(0x100), 0), '2^8 returns +0'); - t.ok(is(ES.ToUint8(0x100 - 1), 0x100 - 1), '2^8 - 1 returns 2^16 - 1'); - t.ok(is(ES.ToUint8(0x10), 0x10), '2^4 returns 2^4'); - t.ok(is(ES.ToUint8(0x10 - 1), 0x10 - 1), '2^4 - 1 returns 2^4 - 1'); - t.end(); - }); - - test('ToUint8Clamp', function (t) { - t.ok(is(0, ES.ToUint8Clamp(NaN)), 'NaN coerces to +0'); - t.ok(is(0, ES.ToUint8Clamp(0)), '+0 returns +0'); - t.ok(is(0, ES.ToUint8Clamp(-0)), '-0 returns +0'); - t.ok(is(0, ES.ToUint8Clamp(-Infinity)), '-Infinity returns +0'); - t['throws'](function () { return ES.ToUint8Clamp(v.uncoercibleObject); }, TypeError, 'uncoercibleObject throws'); - forEach([255, 256, 0x100000, Infinity], function (number) { - t.ok(is(255, ES.ToUint8Clamp(number)), number + ' coerces to 255'); - }); - t.equal(1, ES.ToUint8Clamp(1.49), '1.49 coerces to 1'); - t.equal(2, ES.ToUint8Clamp(1.5), '1.5 coerces to 2, because 2 is even'); - t.equal(2, ES.ToUint8Clamp(1.51), '1.51 coerces to 2'); - - t.equal(2, ES.ToUint8Clamp(2.49), '2.49 coerces to 2'); - t.equal(2, ES.ToUint8Clamp(2.5), '2.5 coerces to 2, because 2 is even'); - t.equal(3, ES.ToUint8Clamp(2.51), '2.51 coerces to 3'); - t.end(); - }); - - test('ToString', function (t) { - forEach(v.objects.concat(v.nonSymbolPrimitives), function (item) { - t.equal(ES.ToString(item), String(item), 'ES.ToString(' + debug(item) + ') ToStrings to String(' + debug(item) + ')'); - }); - - t['throws'](function () { return ES.ToString(v.uncoercibleObject); }, TypeError, 'uncoercibleObject throws'); - - forEach(v.symbols, function (symbol) { - t['throws'](function () { return ES.ToString(symbol); }, TypeError, debug(symbol) + ' throws'); - }); - t.end(); - }); - - test('ToObject', function (t) { - t['throws'](function () { return ES.ToObject(undefined); }, TypeError, 'undefined throws'); - t['throws'](function () { return ES.ToObject(null); }, TypeError, 'null throws'); - forEach(v.numbers, function (number) { - var obj = ES.ToObject(number); - t.equal(typeof obj, 'object', 'number ' + number + ' coerces to object'); - t.equal(true, obj instanceof Number, 'object of ' + number + ' is Number object'); - t.ok(is(obj.valueOf(), number), 'object of ' + number + ' coerces to ' + number); - }); - t.end(); - }); - - test('RequireObjectCoercible', function (t) { - t.equal(false, 'CheckObjectCoercible' in ES, 'CheckObjectCoercible -> RequireObjectCoercible in ES6'); - t['throws'](function () { return ES.RequireObjectCoercible(undefined); }, TypeError, 'undefined throws'); - t['throws'](function () { return ES.RequireObjectCoercible(null); }, TypeError, 'null throws'); - var isCoercible = function (value) { - t.doesNotThrow(function () { return ES.RequireObjectCoercible(value); }, debug(value) + ' does not throw'); - }; - forEach(v.objects.concat(v.nonNullPrimitives), isCoercible); - t.end(); - }); - - test('IsCallable', function (t) { - t.equal(true, ES.IsCallable(function () {}), 'function is callable'); - var nonCallables = [/a/g, {}, Object.prototype, NaN].concat(v.nonFunctions); - forEach(nonCallables, function (nonCallable) { - t.equal(false, ES.IsCallable(nonCallable), debug(nonCallable) + ' is not callable'); - }); - t.end(); - }); - - test('SameValue', function (t) { - t.equal(true, ES.SameValue(NaN, NaN), 'NaN is SameValue as NaN'); - t.equal(false, ES.SameValue(0, -0), '+0 is not SameValue as -0'); - forEach(v.objects.concat(v.primitives), function (val) { - t.equal(val === val, ES.SameValue(val, val), debug(val) + ' is SameValue to itself'); - }); - t.end(); - }); - - test('SameValueZero', function (t) { - t.equal(true, ES.SameValueZero(NaN, NaN), 'NaN is SameValueZero as NaN'); - t.equal(true, ES.SameValueZero(0, -0), '+0 is SameValueZero as -0'); - forEach(v.objects.concat(v.primitives), function (val) { - t.equal(val === val, ES.SameValueZero(val, val), debug(val) + ' is SameValueZero to itself'); - }); - t.end(); - }); - - test('ToPropertyKey', function (t) { - forEach(v.objects.concat(v.nonSymbolPrimitives), function (value) { - t.equal(ES.ToPropertyKey(value), String(value), 'ToPropertyKey(value) === String(value) for non-Symbols'); - }); - - forEach(v.symbols, function (symbol) { - t.equal( - ES.ToPropertyKey(symbol), - symbol, - 'ToPropertyKey(' + debug(symbol) + ') === ' + debug(symbol) - ); - t.equal( - ES.ToPropertyKey(Object(symbol)), - symbol, - 'ToPropertyKey(' + debug(Object(symbol)) + ') === ' + debug(symbol) - ); - }); - - t.end(); - }); - - test('ToLength', function (t) { - t['throws'](function () { return ES.ToLength(v.uncoercibleObject); }, TypeError, 'uncoercibleObject throws a TypeError'); - t.equal(3, ES.ToLength(v.coercibleObject), 'coercibleObject coerces to 3'); - t.equal(42, ES.ToLength('42.5'), '"42.5" coerces to 42'); - t.equal(7, ES.ToLength(7.3), '7.3 coerces to 7'); - forEach([-0, -1, -42, -Infinity], function (negative) { - t.ok(is(0, ES.ToLength(negative)), negative + ' coerces to +0'); - }); - t.equal(MAX_SAFE_INTEGER, ES.ToLength(MAX_SAFE_INTEGER + 1), '2^53 coerces to 2^53 - 1'); - t.equal(MAX_SAFE_INTEGER, ES.ToLength(MAX_SAFE_INTEGER + 3), '2^53 + 2 coerces to 2^53 - 1'); - t.end(); - }); - - test('IsArray', function (t) { - t.equal(true, ES.IsArray([]), '[] is array'); - t.equal(false, ES.IsArray({}), '{} is not array'); - t.equal(false, ES.IsArray({ length: 1, 0: true }), 'arraylike object is not array'); - forEach(v.objects.concat(v.primitives), function (value) { - t.equal(false, ES.IsArray(value), debug(value) + ' is not array'); - }); - t.end(); - }); - - test('IsRegExp', function (t) { - forEach([/a/g, new RegExp('a', 'g')], function (regex) { - t.equal(true, ES.IsRegExp(regex), regex + ' is regex'); - }); - - forEach(v.objects.concat(v.primitives), function (nonRegex) { - t.equal(false, ES.IsRegExp(nonRegex), debug(nonRegex) + ' is not regex'); - }); - - t.test('Symbol.match', { skip: !v.hasSymbols || !Symbol.match }, function (st) { - var obj = {}; - obj[Symbol.match] = true; - st.equal(true, ES.IsRegExp(obj), 'object with truthy Symbol.match is regex'); - - var regex = /a/; - regex[Symbol.match] = false; - st.equal(false, ES.IsRegExp(regex), 'regex with falsy Symbol.match is not regex'); - - st.end(); - }); - - t.end(); - }); - - test('IsPropertyKey', function (t) { - forEach(v.numbers.concat(v.objects), function (notKey) { - t.equal(false, ES.IsPropertyKey(notKey), debug(notKey) + ' is not property key'); - }); - - t.equal(true, ES.IsPropertyKey('foo'), 'string is property key'); - - forEach(v.symbols, function (symbol) { - t.equal(true, ES.IsPropertyKey(symbol), debug(symbol) + ' is property key'); - }); - t.end(); - }); - - test('IsInteger', function (t) { - for (var i = -100; i < 100; i += 10) { - t.equal(true, ES.IsInteger(i), i + ' is integer'); - t.equal(false, ES.IsInteger(i + 0.2), (i + 0.2) + ' is not integer'); - } - t.equal(true, ES.IsInteger(-0), '-0 is integer'); - var notInts = v.nonNumbers.concat(v.nonIntegerNumbers, v.infinities, [NaN, [], new Date()]); - forEach(notInts, function (notInt) { - t.equal(false, ES.IsInteger(notInt), debug(notInt) + ' is not integer'); - }); - t.equal(false, ES.IsInteger(v.uncoercibleObject), 'uncoercibleObject is not integer'); - t.end(); - }); - - test('IsExtensible', function (t) { - forEach(v.objects, function (object) { - t.equal(true, ES.IsExtensible(object), debug(object) + ' object is extensible'); - }); - forEach(v.primitives, function (primitive) { - t.equal(false, ES.IsExtensible(primitive), debug(primitive) + ' is not extensible'); - }); - if (Object.preventExtensions) { - t.equal(false, ES.IsExtensible(Object.preventExtensions({})), 'object with extensions prevented is not extensible'); - } - t.end(); - }); - - test('CanonicalNumericIndexString', function (t) { - var throwsOnNonString = function (notString) { - t['throws']( - function () { return ES.CanonicalNumericIndexString(notString); }, - TypeError, - debug(notString) + ' is not a string' - ); - }; - forEach(v.objects.concat(v.numbers), throwsOnNonString); - t.ok(is(-0, ES.CanonicalNumericIndexString('-0')), '"-0" returns -0'); - for (var i = -50; i < 50; i += 10) { - t.equal(i, ES.CanonicalNumericIndexString(String(i)), '"' + i + '" returns ' + i); - t.equal(undefined, ES.CanonicalNumericIndexString(String(i) + 'a'), '"' + i + 'a" returns undefined'); - } - t.end(); - }); - - test('IsConstructor', function (t) { - t.equal(true, ES.IsConstructor(function () {}), 'function is constructor'); - t.equal(false, ES.IsConstructor(/a/g), 'regex is not constructor'); - forEach(v.objects, function (object) { - t.equal(false, ES.IsConstructor(object), object + ' object is not constructor'); - }); - - try { - var foo = Function('return class Foo {}')(); // eslint-disable-line no-new-func - t.equal(ES.IsConstructor(foo), true, 'class is constructor'); - } catch (e) { - t.comment('SKIP: class syntax not supported.'); - } - t.end(); - }); - - test('Call', function (t) { - var receiver = {}; - var notFuncs = v.nonFunctions.concat([/a/g, new RegExp('a', 'g')]); - t.plan(notFuncs.length + 4); - var throwsIfNotCallable = function (notFunc) { - t['throws']( - function () { return ES.Call(notFunc, receiver); }, - TypeError, - debug(notFunc) + ' (' + typeof notFunc + ') is not callable' - ); - }; - forEach(notFuncs, throwsIfNotCallable); - ES.Call( - function (a, b) { - t.equal(this, receiver, 'context matches expected'); - t.deepEqual([a, b], [1, 2], 'named args are correct'); - t.equal(arguments.length, 3, 'extra argument was passed'); - t.equal(arguments[2], 3, 'extra argument was correct'); - }, - receiver, - [1, 2, 3] - ); - t.end(); - }); - - test('GetV', function (t) { - t['throws'](function () { return ES.GetV({ 7: 7 }, 7); }, TypeError, 'Throws a TypeError if `P` is not a property key'); - var obj = { a: function () {} }; - t.equal(ES.GetV(obj, 'a'), obj.a, 'returns property if it exists'); - t.equal(ES.GetV(obj, 'b'), undefined, 'returns undefiend if property does not exist'); - t.end(); - }); - - test('GetMethod', function (t) { - t['throws'](function () { return ES.GetMethod({ 7: 7 }, 7); }, TypeError, 'Throws a TypeError if `P` is not a property key'); - t.equal(ES.GetMethod({}, 'a'), undefined, 'returns undefined in property is undefined'); - t.equal(ES.GetMethod({ a: null }, 'a'), undefined, 'returns undefined if property is null'); - t.equal(ES.GetMethod({ a: undefined }, 'a'), undefined, 'returns undefined if property is undefined'); - var obj = { a: function () {} }; - t['throws'](function () { ES.GetMethod({ a: 'b' }, 'a'); }, TypeError, 'throws TypeError if property exists and is not callable'); - t.equal(ES.GetMethod(obj, 'a'), obj.a, 'returns property if it is callable'); - t.end(); - }); - - test('Get', function (t) { - t['throws'](function () { return ES.Get('a', 'a'); }, TypeError, 'Throws a TypeError if `O` is not an Object'); - t['throws'](function () { return ES.Get({ 7: 7 }, 7); }, TypeError, 'Throws a TypeError if `P` is not a property key'); - - var value = {}; - t.test('Symbols', { skip: !v.hasSymbols }, function (st) { - var sym = Symbol('sym'); - var obj = {}; - obj[sym] = value; - st.equal(ES.Get(obj, sym), value, 'returns property `P` if it exists on object `O`'); - st.end(); - }); - t.equal(ES.Get({ a: value }, 'a'), value, 'returns property `P` if it exists on object `O`'); - t.end(); - }); - - test('Type', { skip: !v.hasSymbols }, function (t) { - t.equal(ES.Type(Symbol.iterator), 'Symbol', 'Type(Symbol.iterator) is Symbol'); - t.end(); - }); - - test('SpeciesConstructor', function (t) { - t['throws'](function () { ES.SpeciesConstructor(null); }, TypeError); - t['throws'](function () { ES.SpeciesConstructor(undefined); }, TypeError); - - var defaultConstructor = function Foo() {}; - - t.equal( - ES.SpeciesConstructor({ constructor: undefined }, defaultConstructor), - defaultConstructor, - 'undefined constructor returns defaultConstructor' - ); - - t['throws']( - function () { return ES.SpeciesConstructor({ constructor: null }, defaultConstructor); }, - TypeError, - 'non-undefined non-object constructor throws' - ); - - t.test('with Symbol.species', { skip: !hasSpecies }, function (st) { - var Bar = function Bar() {}; - Bar[Symbol.species] = null; - - st.equal( - ES.SpeciesConstructor(new Bar(), defaultConstructor), - defaultConstructor, - 'undefined/null Symbol.species returns default constructor' - ); - - var Baz = function Baz() {}; - Baz[Symbol.species] = Bar; - st.equal( - ES.SpeciesConstructor(new Baz(), defaultConstructor), - Bar, - 'returns Symbol.species constructor value' - ); - - Baz[Symbol.species] = {}; - st['throws']( - function () { ES.SpeciesConstructor(new Baz(), defaultConstructor); }, - TypeError, - 'throws when non-constructor non-null non-undefined species value found' - ); - - st.end(); - }); - - t.end(); - }); - - test('IsPropertyDescriptor', { skip: skips && skips.IsPropertyDescriptor }, function (t) { - forEach(v.nonUndefinedPrimitives, function (primitive) { - t.equal( - ES.IsPropertyDescriptor(primitive), - false, - debug(primitive) + ' is not a Property Descriptor' - ); - }); - - t.equal(ES.IsPropertyDescriptor({ invalid: true }), false, 'invalid keys not allowed on a Property Descriptor'); - - t.equal(ES.IsPropertyDescriptor({}), true, 'empty object is an incomplete Property Descriptor'); - - t.equal(ES.IsPropertyDescriptor(v.accessorDescriptor()), true, 'accessor descriptor is a Property Descriptor'); - t.equal(ES.IsPropertyDescriptor(v.mutatorDescriptor()), true, 'mutator descriptor is a Property Descriptor'); - t.equal(ES.IsPropertyDescriptor(v.dataDescriptor()), true, 'data descriptor is a Property Descriptor'); - t.equal(ES.IsPropertyDescriptor(v.genericDescriptor()), true, 'generic descriptor is a Property Descriptor'); - - t['throws']( - function () { - ES.IsPropertyDescriptor(v.bothDescriptor()); - }, TypeError, - 'a Property Descriptor can not be both a Data and an Accessor Descriptor' - ); - - t.end(); - }); - - assertRecordTests(ES, test); - - test('IsAccessorDescriptor', function (t) { - forEach(v.nonUndefinedPrimitives, function (primitive) { - t['throws']( - function () { ES.IsAccessorDescriptor(primitive); }, - TypeError, - debug(primitive) + ' is not a Property Descriptor' - ); - }); - - t.equal(ES.IsAccessorDescriptor(), false, 'no value is not an Accessor Descriptor'); - t.equal(ES.IsAccessorDescriptor(undefined), false, 'undefined value is not an Accessor Descriptor'); - - t.equal(ES.IsAccessorDescriptor(v.accessorDescriptor()), true, 'accessor descriptor is an Accessor Descriptor'); - t.equal(ES.IsAccessorDescriptor(v.mutatorDescriptor()), true, 'mutator descriptor is an Accessor Descriptor'); - t.equal(ES.IsAccessorDescriptor(v.dataDescriptor()), false, 'data descriptor is not an Accessor Descriptor'); - t.equal(ES.IsAccessorDescriptor(v.genericDescriptor()), false, 'generic descriptor is not an Accessor Descriptor'); - - t.end(); - }); - - test('IsDataDescriptor', function (t) { - forEach(v.nonUndefinedPrimitives, function (primitive) { - t['throws']( - function () { ES.IsDataDescriptor(primitive); }, - TypeError, - debug(primitive) + ' is not a Property Descriptor' - ); - }); - - t.equal(ES.IsDataDescriptor(), false, 'no value is not a Data Descriptor'); - t.equal(ES.IsDataDescriptor(undefined), false, 'undefined value is not a Data Descriptor'); - - t.equal(ES.IsDataDescriptor(v.accessorDescriptor()), false, 'accessor descriptor is not a Data Descriptor'); - t.equal(ES.IsDataDescriptor(v.mutatorDescriptor()), false, 'mutator descriptor is not a Data Descriptor'); - t.equal(ES.IsDataDescriptor(v.dataDescriptor()), true, 'data descriptor is a Data Descriptor'); - t.equal(ES.IsDataDescriptor(v.genericDescriptor()), false, 'generic descriptor is not a Data Descriptor'); - - t.end(); - }); - - test('IsGenericDescriptor', function (t) { - forEach(v.nonUndefinedPrimitives, function (primitive) { - t['throws']( - function () { ES.IsGenericDescriptor(primitive); }, - TypeError, - debug(primitive) + ' is not a Property Descriptor' - ); - }); - - t.equal(ES.IsGenericDescriptor(), false, 'no value is not a Data Descriptor'); - t.equal(ES.IsGenericDescriptor(undefined), false, 'undefined value is not a Data Descriptor'); - - t.equal(ES.IsGenericDescriptor(v.accessorDescriptor()), false, 'accessor descriptor is not a generic Descriptor'); - t.equal(ES.IsGenericDescriptor(v.mutatorDescriptor()), false, 'mutator descriptor is not a generic Descriptor'); - t.equal(ES.IsGenericDescriptor(v.dataDescriptor()), false, 'data descriptor is not a generic Descriptor'); - - t.equal(ES.IsGenericDescriptor(v.genericDescriptor()), true, 'generic descriptor is a generic Descriptor'); - - t.end(); - }); - - test('FromPropertyDescriptor', function (t) { - t.equal(ES.FromPropertyDescriptor(), undefined, 'no value begets undefined'); - t.equal(ES.FromPropertyDescriptor(undefined), undefined, 'undefined value begets undefined'); - - forEach(v.nonUndefinedPrimitives, function (primitive) { - t['throws']( - function () { ES.FromPropertyDescriptor(primitive); }, - TypeError, - debug(primitive) + ' is not a Property Descriptor' - ); - }); - - var accessor = v.accessorDescriptor(); - t.deepEqual(ES.FromPropertyDescriptor(accessor), { - get: accessor['[[Get]]'], - enumerable: !!accessor['[[Enumerable]]'], - configurable: !!accessor['[[Configurable]]'] - }); - - var mutator = v.mutatorDescriptor(); - t.deepEqual(ES.FromPropertyDescriptor(mutator), { - set: mutator['[[Set]]'], - enumerable: !!mutator['[[Enumerable]]'], - configurable: !!mutator['[[Configurable]]'] - }); - var data = v.dataDescriptor(); - t.deepEqual(ES.FromPropertyDescriptor(data), { - value: data['[[Value]]'], - writable: data['[[Writable]]'] - }); - - t.deepEqual(ES.FromPropertyDescriptor(v.genericDescriptor()), { - enumerable: false, - configurable: true - }); - - t.end(); - }); - - test('ToPropertyDescriptor', function (t) { - forEach(v.nonUndefinedPrimitives, function (primitive) { - t['throws']( - function () { ES.ToPropertyDescriptor(primitive); }, - TypeError, - debug(primitive) + ' is not an Object' - ); - }); - - var accessor = v.accessorDescriptor(); - t.deepEqual(ES.ToPropertyDescriptor({ - get: accessor['[[Get]]'], - enumerable: !!accessor['[[Enumerable]]'], - configurable: !!accessor['[[Configurable]]'] - }), accessor); - - var mutator = v.mutatorDescriptor(); - t.deepEqual(ES.ToPropertyDescriptor({ - set: mutator['[[Set]]'], - enumerable: !!mutator['[[Enumerable]]'], - configurable: !!mutator['[[Configurable]]'] - }), mutator); - - var data = v.dataDescriptor(); - t.deepEqual(ES.ToPropertyDescriptor({ - value: data['[[Value]]'], - writable: data['[[Writable]]'], - configurable: !!data['[[Configurable]]'] - }), assign(data, { '[[Configurable]]': false })); - - var both = v.bothDescriptor(); - t['throws']( - function () { - ES.FromPropertyDescriptor({ get: both['[[Get]]'], value: both['[[Value]]'] }); - }, - TypeError, - 'data and accessor descriptors are mutually exclusive' - ); - - t.end(); - }); - - test('CompletePropertyDescriptor', function (t) { - forEach(v.nonUndefinedPrimitives, function (primitive) { - t['throws']( - function () { ES.CompletePropertyDescriptor(primitive); }, - TypeError, - debug(primitive) + ' is not a Property Descriptor' - ); - }); - - var generic = v.genericDescriptor(); - t.deepEqual( - ES.CompletePropertyDescriptor(generic), - { - '[[Configurable]]': !!generic['[[Configurable]]'], - '[[Enumerable]]': !!generic['[[Enumerable]]'], - '[[Value]]': undefined, - '[[Writable]]': false - }, - 'completes a Generic Descriptor' - ); - - var data = v.dataDescriptor(); - t.deepEqual( - ES.CompletePropertyDescriptor(data), - { - '[[Configurable]]': !!data['[[Configurable]]'], - '[[Enumerable]]': false, - '[[Value]]': data['[[Value]]'], - '[[Writable]]': !!data['[[Writable]]'] - }, - 'completes a Data Descriptor' - ); - - var accessor = v.accessorDescriptor(); - t.deepEqual( - ES.CompletePropertyDescriptor(accessor), - { - '[[Get]]': accessor['[[Get]]'], - '[[Enumerable]]': !!accessor['[[Enumerable]]'], - '[[Configurable]]': !!accessor['[[Configurable]]'], - '[[Set]]': undefined - }, - 'completes an Accessor Descriptor' - ); - - var mutator = v.mutatorDescriptor(); - t.deepEqual( - ES.CompletePropertyDescriptor(mutator), - { - '[[Set]]': mutator['[[Set]]'], - '[[Enumerable]]': !!mutator['[[Enumerable]]'], - '[[Configurable]]': !!mutator['[[Configurable]]'], - '[[Get]]': undefined - }, - 'completes a mutator Descriptor' - ); - - t['throws']( - function () { ES.CompletePropertyDescriptor(v.bothDescriptor()); }, - TypeError, - 'data and accessor descriptors are mutually exclusive' - ); - - t.end(); - }); - - test('Set', function (t) { - forEach(v.primitives, function (primitive) { - t['throws']( - function () { ES.Set(primitive, '', null, false); }, - TypeError, - debug(primitive) + ' is not an Object' - ); - }); - - forEach(v.nonPropertyKeys, function (nonKey) { - t['throws']( - function () { ES.Set({}, nonKey, null, false); }, - TypeError, - debug(nonKey) + ' is not a Property Key' - ); - }); - - forEach(v.nonBooleans, function (nonBoolean) { - t['throws']( - function () { ES.Set({}, '', null, nonBoolean); }, - TypeError, - debug(nonBoolean) + ' is not a Boolean' - ); - }); - - var o = {}; - var value = {}; - ES.Set(o, 'key', value, true); - t.deepEqual(o, { key: value }, 'key is set'); - - t.test('nonwritable', { skip: !Object.defineProperty }, function (st) { - var obj = { a: value }; - Object.defineProperty(obj, 'a', { writable: false }); - - st['throws']( - function () { ES.Set(obj, 'a', value, true); }, - TypeError, - 'can not Set nonwritable property' - ); - - st.doesNotThrow( - function () { ES.Set(obj, 'a', value, false); }, - 'setting Throw to false prevents an exception' - ); - - st.end(); - }); - - t.test('nonconfigurable', { skip: !Object.defineProperty }, function (st) { - var obj = { a: value }; - Object.defineProperty(obj, 'a', { configurable: false }); - - ES.Set(obj, 'a', value, true); - st.deepEqual(obj, { a: value }, 'key is set'); - - st.end(); - }); - - t.end(); - }); - - test('HasOwnProperty', function (t) { - forEach(v.primitives, function (primitive) { - t['throws']( - function () { ES.HasOwnProperty(primitive, 'key'); }, - TypeError, - debug(primitive) + ' is not an Object' - ); - }); - - forEach(v.nonPropertyKeys, function (nonKey) { - t['throws']( - function () { ES.HasOwnProperty({}, nonKey); }, - TypeError, - debug(nonKey) + ' is not a Property Key' - ); - }); - - t.equal(ES.HasOwnProperty({}, 'toString'), false, 'inherited properties are not own'); - t.equal( - ES.HasOwnProperty({ toString: 1 }, 'toString'), - true, - 'shadowed inherited own properties are own' - ); - t.equal(ES.HasOwnProperty({ a: 1 }, 'a'), true, 'own properties are own'); - - t.end(); - }); - - test('HasProperty', function (t) { - forEach(v.primitives, function (primitive) { - t['throws']( - function () { ES.HasProperty(primitive, 'key'); }, - TypeError, - debug(primitive) + ' is not an Object' - ); - }); - - forEach(v.nonPropertyKeys, function (nonKey) { - t['throws']( - function () { ES.HasProperty({}, nonKey); }, - TypeError, - debug(nonKey) + ' is not a Property Key' - ); - }); - - t.equal(ES.HasProperty({}, 'nope'), false, 'object does not have nonexistent properties'); - t.equal(ES.HasProperty({}, 'toString'), true, 'object has inherited properties'); - t.equal( - ES.HasProperty({ toString: 1 }, 'toString'), - true, - 'object has shadowed inherited own properties' - ); - t.equal(ES.HasProperty({ a: 1 }, 'a'), true, 'object has own properties'); - - t.end(); - }); - - test('IsConcatSpreadable', function (t) { - forEach(v.primitives, function (primitive) { - t.equal(ES.IsConcatSpreadable(primitive), false, debug(primitive) + ' is not an Object'); - }); - - var hasSymbolConcatSpreadable = v.hasSymbols && Symbol.isConcatSpreadable; - t.test('Symbol.isConcatSpreadable', { skip: !hasSymbolConcatSpreadable }, function (st) { - forEach(v.falsies, function (falsy) { - var obj = {}; - obj[Symbol.isConcatSpreadable] = falsy; - st.equal( - ES.IsConcatSpreadable(obj), - false, - 'an object with ' + debug(falsy) + ' as Symbol.isConcatSpreadable is not concat spreadable' - ); - }); - - forEach(v.truthies, function (truthy) { - var obj = {}; - obj[Symbol.isConcatSpreadable] = truthy; - st.equal( - ES.IsConcatSpreadable(obj), - true, - 'an object with ' + debug(truthy) + ' as Symbol.isConcatSpreadable is concat spreadable' - ); - }); - - st.end(); - }); - - forEach(v.objects, function (object) { - t.equal( - ES.IsConcatSpreadable(object), - false, - 'non-array without Symbol.isConcatSpreadable is not concat spreadable' - ); - }); - - t.equal(ES.IsConcatSpreadable([]), true, 'arrays are concat spreadable'); - - t.end(); - }); - - test('Invoke', function (t) { - forEach(v.nonPropertyKeys, function (nonKey) { - t['throws']( - function () { ES.Invoke({}, nonKey); }, - TypeError, - debug(nonKey) + ' is not a Property Key' - ); - }); - - t['throws'](function () { ES.Invoke({ o: false }, 'o'); }, TypeError, 'fails on a non-function'); - - t.test('invoked callback', function (st) { - var aValue = {}; - var bValue = {}; - var obj = { - f: function (a) { - st.equal(arguments.length, 2, '2 args passed'); - st.equal(a, aValue, 'first arg is correct'); - st.equal(arguments[1], bValue, 'second arg is correct'); - } - }; - st.plan(3); - ES.Invoke(obj, 'f', aValue, bValue); - }); - - t.end(); - }); - - test('GetIterator', function (t) { - var arr = [1, 2]; - testIterator(t, ES.GetIterator(arr), arr); - - testIterator(t, ES.GetIterator('abc'), 'abc'.split('')); - - t.test('Symbol.iterator', { skip: !v.hasSymbols }, function (st) { - var m = new Map(); - m.set(1, 'a'); - m.set(2, 'b'); - - testIterator(st, ES.GetIterator(m), [[1, 'a'], [2, 'b']]); - - st.end(); - }); - - t.end(); - }); - - test('IteratorNext', { skip: true }); - - test('IteratorComplete', { skip: true }); - - test('IteratorValue', { skip: true }); - - test('IteratorStep', { skip: true }); - - test('IteratorClose', { skip: true }); - - test('CreateIterResultObject', function (t) { - forEach(v.nonBooleans, function (nonBoolean) { - t['throws']( - function () { ES.CreateIterResultObject({}, nonBoolean); }, - TypeError, - '"done" argument must be a boolean; ' + debug(nonBoolean) + ' is not' - ); - }); - - var value = {}; - t.deepEqual( - ES.CreateIterResultObject(value, true), - { value: value, done: true }, - 'creates a "done" iteration result' - ); - t.deepEqual( - ES.CreateIterResultObject(value, false), - { value: value, done: false }, - 'creates a "not done" iteration result' - ); - - t.end(); - }); - - test('RegExpExec', function (t) { - forEach(v.primitives, function (primitive) { - t['throws']( - function () { ES.RegExpExec(primitive); }, - TypeError, - '"R" argument must be an object; ' + debug(primitive) + ' is not' - ); - }); - - forEach(v.nonStrings, function (nonString) { - t['throws']( - function () { ES.RegExpExec({}, nonString); }, - TypeError, - '"S" argument must be a String; ' + debug(nonString) + ' is not' - ); - }); - - t.test('gets and calls a callable "exec"', function (st) { - var str = '123'; - var o = { - exec: function (S) { - st.equal(this, o, '"exec" receiver is R'); - st.equal(S, str, '"exec" argument is S'); - - return null; - } - }; - st.plan(2); - ES.RegExpExec(o, str); - st.end(); - }); - - t.test('throws if a callable "exec" returns a non-null non-object', function (st) { - var str = '123'; - st.plan(v.nonNullPrimitives.length); - forEach(v.nonNullPrimitives, function (nonNullPrimitive) { - st['throws']( - function () { ES.RegExpExec({ exec: function () { return nonNullPrimitive; } }, str); }, - TypeError, - '"exec" method must return `null` or an Object; ' + debug(nonNullPrimitive) + ' is not' - ); - }); - st.end(); - }); - - t.test('actual regex that should match against a string', function (st) { - var S = 'aabc'; - var R = /a/g; - var match1 = ES.RegExpExec(R, S); - var match2 = ES.RegExpExec(R, S); - var match3 = ES.RegExpExec(R, S); - st.deepEqual(match1, assign(['a'], groups({ index: 0, input: S })), 'match object 1 is as expected'); - st.deepEqual(match2, assign(['a'], groups({ index: 1, input: S })), 'match object 2 is as expected'); - st.equal(match3, null, 'match 3 is null as expected'); - st.end(); - }); - - t.test('actual regex that should match against a string, with shadowed "exec"', function (st) { - var S = 'aabc'; - var R = /a/g; - R.exec = undefined; - var match1 = ES.RegExpExec(R, S); - var match2 = ES.RegExpExec(R, S); - var match3 = ES.RegExpExec(R, S); - st.deepEqual(match1, assign(['a'], groups({ index: 0, input: S })), 'match object 1 is as expected'); - st.deepEqual(match2, assign(['a'], groups({ index: 1, input: S })), 'match object 2 is as expected'); - st.equal(match3, null, 'match 3 is null as expected'); - st.end(); - }); - t.end(); - }); - - test('ArraySpeciesCreate', function (t) { - t.test('errors', function (st) { - var testNonNumber = function (nonNumber) { - st['throws']( - function () { ES.ArraySpeciesCreate([], nonNumber); }, - TypeError, - debug(nonNumber) + ' is not a number' - ); - }; - forEach(v.nonNumbers, testNonNumber); - - st['throws']( - function () { ES.ArraySpeciesCreate([], -1); }, - TypeError, - '-1 is not >= 0' - ); - st['throws']( - function () { ES.ArraySpeciesCreate([], -Infinity); }, - TypeError, - '-Infinity is not >= 0' - ); - - var testNonIntegers = function (nonInteger) { - st['throws']( - function () { ES.ArraySpeciesCreate([], nonInteger); }, - TypeError, - debug(nonInteger) + ' is not an integer' - ); - }; - forEach(v.nonIntegerNumbers, testNonIntegers); - - st.end(); - }); - - t.test('works with a non-array', function (st) { - forEach(v.objects.concat(v.primitives), function (nonArray) { - var arr = ES.ArraySpeciesCreate(nonArray, 0); - st.ok(ES.IsArray(arr), 'is an array'); - st.equal(arr.length, 0, 'length is correct'); - st.equal(arr.constructor, Array, 'constructor is correct'); - }); - - st.end(); - }); - - t.test('works with a normal array', function (st) { - var len = 2; - var orig = [1, 2, 3]; - var arr = ES.ArraySpeciesCreate(orig, len); - - st.ok(ES.IsArray(arr), 'is an array'); - st.equal(arr.length, len, 'length is correct'); - st.equal(arr.constructor, orig.constructor, 'constructor is correct'); - - st.end(); - }); - - t.test('-0 length produces +0 length', function (st) { - var len = -0; - st.ok(is(len, -0), '-0 is negative zero'); - st.notOk(is(len, 0), '-0 is not positive zero'); - - var orig = [1, 2, 3]; - var arr = ES.ArraySpeciesCreate(orig, len); - - st.equal(ES.IsArray(arr), true); - st.ok(is(arr.length, 0)); - st.equal(arr.constructor, orig.constructor); - - st.end(); - }); - - t.test('works with species construtor', { skip: !hasSpecies }, function (st) { - var sentinel = {}; - var Foo = function Foo(len) { - this.length = len; - this.sentinel = sentinel; - }; - var Bar = getArraySubclassWithSpeciesConstructor(Foo); - var bar = new Bar(); - - t.equal(ES.IsArray(bar), true, 'Bar instance is an array'); - - var arr = ES.ArraySpeciesCreate(bar, 3); - st.equal(arr.constructor, Foo, 'result used species constructor'); - st.equal(arr.length, 3, 'length property is correct'); - st.equal(arr.sentinel, sentinel, 'Foo constructor was exercised'); - - st.end(); - }); - - t.test('works with null species constructor', { skip: !hasSpecies }, function (st) { - var Bar = getArraySubclassWithSpeciesConstructor(null); - var bar = new Bar(); - - t.equal(ES.IsArray(bar), true, 'Bar instance is an array'); - - var arr = ES.ArraySpeciesCreate(bar, 3); - st.equal(arr.constructor, Array, 'result used default constructor'); - st.equal(arr.length, 3, 'length property is correct'); - - st.end(); - }); - - t.test('works with undefined species constructor', { skip: !hasSpecies }, function (st) { - var Bar = getArraySubclassWithSpeciesConstructor(); - var bar = new Bar(); - - t.equal(ES.IsArray(bar), true, 'Bar instance is an array'); - - var arr = ES.ArraySpeciesCreate(bar, 3); - st.equal(arr.constructor, Array, 'result used default constructor'); - st.equal(arr.length, 3, 'length property is correct'); - - st.end(); - }); - - t.test('throws with object non-construtor species constructor', { skip: !hasSpecies }, function (st) { - forEach(v.objects, function (obj) { - var Bar = getArraySubclassWithSpeciesConstructor(obj); - var bar = new Bar(); - - st.equal(ES.IsArray(bar), true, 'Bar instance is an array'); - - st['throws']( - function () { ES.ArraySpeciesCreate(bar, 3); }, - TypeError, - debug(obj) + ' is not a constructor' - ); - }); - - st.end(); - }); - - t.end(); - }); - - test('CreateDataProperty', function (t) { - forEach(v.primitives, function (primitive) { - t['throws']( - function () { ES.CreateDataProperty(primitive); }, - TypeError, - debug(primitive) + ' is not an object' - ); - }); - - forEach(v.nonPropertyKeys, function (nonPropertyKey) { - t['throws']( - function () { ES.CreateDataProperty({}, nonPropertyKey); }, - TypeError, - debug(nonPropertyKey) + ' is not a property key' - ); - }); - - var sentinel = {}; - forEach(v.propertyKeys, function (propertyKey) { - var obj = {}; - var status = ES.CreateDataProperty(obj, propertyKey, sentinel); - t.equal(status, true, 'status is true'); - t.equal( - obj[propertyKey], - sentinel, - debug(sentinel) + ' is installed on "' + debug(propertyKey) + '" on the object' - ); - - if (typeof Object.defineProperty === 'function') { - var nonWritable = Object.defineProperty({}, propertyKey, { configurable: true, writable: false }); - - var nonWritableStatus = ES.CreateDataProperty(nonWritable, propertyKey, sentinel); - t.equal(nonWritableStatus, false, 'create data property failed'); - t.notEqual( - nonWritable[propertyKey], - sentinel, - debug(sentinel) + ' is not installed on "' + debug(propertyKey) + '" on the object when key is nonwritable' - ); - - var nonConfigurable = Object.defineProperty({}, propertyKey, { configurable: false, writable: true }); - - var nonConfigurableStatus = ES.CreateDataProperty(nonConfigurable, propertyKey, sentinel); - t.equal(nonConfigurableStatus, false, 'create data property failed'); - t.notEqual( - nonConfigurable[propertyKey], - sentinel, - debug(sentinel) + ' is not installed on "' + debug(propertyKey) + '" on the object when key is nonconfigurable' - ); - } - }); - - t.end(); - }); - - test('CreateDataPropertyOrThrow', function (t) { - forEach(v.primitives, function (primitive) { - t['throws']( - function () { ES.CreateDataPropertyOrThrow(primitive); }, - TypeError, - debug(primitive) + ' is not an object' - ); - }); - - forEach(v.nonPropertyKeys, function (nonPropertyKey) { - t['throws']( - function () { ES.CreateDataPropertyOrThrow({}, nonPropertyKey); }, - TypeError, - debug(nonPropertyKey) + ' is not a property key' - ); - }); - - var sentinel = {}; - forEach(v.propertyKeys, function (propertyKey) { - var obj = {}; - var status = ES.CreateDataPropertyOrThrow(obj, propertyKey, sentinel); - t.equal(status, true, 'status is true'); - t.equal( - obj[propertyKey], - sentinel, - debug(sentinel) + ' is installed on "' + debug(propertyKey) + '" on the object' - ); - - if (typeof Object.preventExtensions === 'function') { - var notExtensible = {}; - Object.preventExtensions(notExtensible); - - t['throws']( - function () { ES.CreateDataPropertyOrThrow(notExtensible, propertyKey, sentinel); }, - TypeError, - 'can not install ' + debug(propertyKey) + ' on non-extensible object' - ); - t.notEqual( - notExtensible[propertyKey], - sentinel, - debug(sentinel) + ' is not installed on "' + debug(propertyKey) + '" on the object' - ); - } - }); - - t.end(); - }); - - test('ObjectCreate', function (t) { - forEach(v.nonNullPrimitives, function (value) { - t['throws']( - function () { ES.ObjectCreate(value); }, - TypeError, - debug(value) + ' is not null, or an object' - ); - }); - - t.test('proto arg', function (st) { - var Parent = function Parent() {}; - Parent.prototype.foo = {}; - var child = ES.ObjectCreate(Parent.prototype); - st.equal(child instanceof Parent, true, 'child is instanceof Parent'); - st.equal(child.foo, Parent.prototype.foo, 'child inherits properties from Parent.prototype'); - - st.end(); - }); - - t.test('internal slots arg', function (st) { - st.doesNotThrow(function () { ES.ObjectCreate(null, []); }, 'an empty slot list is valid'); - - st['throws']( - function () { ES.ObjectCreate(null, ['a']); }, - SyntaxError, - 'internal slots are not supported' - ); - - st.end(); - }); - - t.test('null proto', { skip: !Object.create }, function (st) { - st.equal('toString' in {}, true, 'normal objects have toString'); - st.equal('toString' in ES.ObjectCreate(null), false, 'makes a null object'); - - st.end(); - }); - - t.test('null proto when no native Object.create', { skip: Object.create }, function (st) { - st['throws']( - function () { ES.ObjectCreate(null); }, - SyntaxError, - 'without a native Object.create, can not create null objects' - ); - - st.end(); - }); - - t.end(); - }); - - test('AdvanceStringIndex', function (t) { - forEach(v.nonStrings, function (nonString) { - t['throws']( - function () { ES.AdvanceStringIndex(nonString); }, - TypeError, - '"S" argument must be a String; ' + debug(nonString) + ' is not' - ); - }); - - var notInts = v.nonNumbers.concat( - v.nonIntegerNumbers, - v.infinities, - [NaN, [], new Date(), Math.pow(2, 53), -1] - ); - forEach(notInts, function (nonInt) { - t['throws']( - function () { ES.AdvanceStringIndex('abc', nonInt); }, - TypeError, - '"index" argument must be an integer, ' + debug(nonInt) + ' is not.' - ); - }); - - forEach(v.nonBooleans, function (nonBoolean) { - t['throws']( - function () { ES.AdvanceStringIndex('abc', 0, nonBoolean); }, - TypeError, - debug(nonBoolean) + ' is not a Boolean' - ); - }); - - var str = 'a\uD83D\uDCA9c'; - - t.test('non-unicode mode', function (st) { - for (var i = 0; i < str.length + 2; i += 1) { - st.equal(ES.AdvanceStringIndex(str, i, false), i + 1, i + ' advances to ' + (i + 1)); - } - - st.end(); - }); - - t.test('unicode mode', function (st) { - st.equal(ES.AdvanceStringIndex(str, 0, true), 1, '0 advances to 1'); - st.equal(ES.AdvanceStringIndex(str, 1, true), 3, '1 advances to 3'); - st.equal(ES.AdvanceStringIndex(str, 2, true), 3, '2 advances to 3'); - st.equal(ES.AdvanceStringIndex(str, 3, true), 4, '3 advances to 4'); - st.equal(ES.AdvanceStringIndex(str, 4, true), 5, '4 advances to 5'); - - st.end(); - }); - - t.test('lone surrogates', function (st) { - var halfPoo = 'a\uD83Dc'; - - st.equal(ES.AdvanceStringIndex(halfPoo, 0, true), 1, '0 advances to 1'); - st.equal(ES.AdvanceStringIndex(halfPoo, 1, true), 2, '1 advances to 2'); - st.equal(ES.AdvanceStringIndex(halfPoo, 2, true), 3, '2 advances to 3'); - st.equal(ES.AdvanceStringIndex(halfPoo, 3, true), 4, '3 advances to 4'); - - st.end(); - }); - - t.test('surrogate pairs', function (st) { - var lowestPair = String.fromCharCode('0xD800') + String.fromCharCode('0xDC00'); - var highestPair = String.fromCharCode('0xDBFF') + String.fromCharCode('0xDFFF'); - var poop = String.fromCharCode('0xD83D') + String.fromCharCode('0xDCA9'); - - st.equal(ES.AdvanceStringIndex(lowestPair, 0, true), 2, 'lowest surrogate pair, 0 -> 2'); - st.equal(ES.AdvanceStringIndex(highestPair, 0, true), 2, 'highest surrogate pair, 0 -> 2'); - st.equal(ES.AdvanceStringIndex(poop, 0, true), 2, 'poop, 0 -> 2'); - - st.end(); - }); - - t.end(); - }); - - test('CreateMethodProperty', function (t) { - forEach(v.primitives, function (primitive) { - t['throws']( - function () { ES.CreateMethodProperty(primitive, 'key'); }, - TypeError, - 'O must be an Object' - ); - }); - - forEach(v.nonPropertyKeys, function (nonPropertyKey) { - t['throws']( - function () { ES.CreateMethodProperty({}, nonPropertyKey); }, - TypeError, - debug(nonPropertyKey) + ' is not a Property Key' - ); - }); - - t.test('defines correctly', function (st) { - var obj = {}; - var key = 'the key'; - var value = { foo: 'bar' }; - - st.equal(ES.CreateMethodProperty(obj, key, value), true, 'defines property successfully'); - st.test('property descriptor', { skip: !Object.getOwnPropertyDescriptor }, function (s2t) { - s2t.deepEqual( - Object.getOwnPropertyDescriptor(obj, key), - { - configurable: true, - enumerable: false, - value: value, - writable: true - }, - 'sets the correct property descriptor' - ); - - s2t.end(); - }); - st.equal(obj[key], value, 'sets the correct value'); - - st.end(); - }); - - t.test('fails as expected on a frozen object', { skip: !Object.freeze }, function (st) { - var obj = Object.freeze({ foo: 'bar' }); - st['throws']( - function () { ES.CreateMethodProperty(obj, 'foo', { value: 'baz' }); }, - TypeError, - 'nonconfigurable key can not be defined' - ); - - st.end(); - }); - - var hasNonConfigurableFunctionName = !Object.getOwnPropertyDescriptor - || !Object.getOwnPropertyDescriptor(function () {}, 'name').configurable; - t.test('fails as expected on a function with a nonconfigurable name', { skip: !hasNonConfigurableFunctionName }, function (st) { - st['throws']( - function () { ES.CreateMethodProperty(function () {}, 'name', { value: 'baz' }); }, - TypeError, - 'nonconfigurable function name can not be defined' - ); - st.end(); - }); - - t.end(); - }); - - test('DefinePropertyOrThrow', function (t) { - forEach(v.primitives, function (primitive) { - t['throws']( - function () { ES.DefinePropertyOrThrow(primitive, 'key', {}); }, - TypeError, - 'O must be an Object' - ); - }); - - forEach(v.nonPropertyKeys, function (nonPropertyKey) { - t['throws']( - function () { ES.DefinePropertyOrThrow({}, nonPropertyKey, {}); }, - TypeError, - debug(nonPropertyKey) + ' is not a Property Key' - ); - }); - - t.test('defines correctly', function (st) { - var obj = {}; - var key = 'the key'; - var descriptor = { - configurable: true, - enumerable: false, - value: { foo: 'bar' }, - writable: true - }; - - st.equal(ES.DefinePropertyOrThrow(obj, key, descriptor), true, 'defines property successfully'); - st.test('property descriptor', { skip: !Object.getOwnPropertyDescriptor }, function (s2t) { - s2t.deepEqual( - Object.getOwnPropertyDescriptor(obj, key), - descriptor, - 'sets the correct property descriptor' - ); - - s2t.end(); - }); - st.deepEqual(obj[key], descriptor.value, 'sets the correct value'); - - st.end(); - }); - - t.test('fails as expected on a frozen object', { skip: !Object.freeze }, function (st) { - var obj = Object.freeze({ foo: 'bar' }); - st['throws']( - function () { - ES.DefinePropertyOrThrow(obj, 'foo', { configurable: true, value: 'baz' }); - }, - TypeError, - 'nonconfigurable key can not be defined' - ); - - st.end(); - }); - - var hasNonConfigurableFunctionName = !Object.getOwnPropertyDescriptor - || !Object.getOwnPropertyDescriptor(function () {}, 'name').configurable; - t.test('fails as expected on a function with a nonconfigurable name', { skip: !hasNonConfigurableFunctionName }, function (st) { - st['throws']( - function () { - ES.DefinePropertyOrThrow(function () {}, 'name', { configurable: true, value: 'baz' }); - }, - TypeError, - 'nonconfigurable function name can not be defined' - ); - st.end(); - }); - - t.end(); - }); - - test('DeletePropertyOrThrow', function (t) { - forEach(v.primitives, function (primitive) { - t['throws']( - function () { ES.DeletePropertyOrThrow(primitive, 'key', {}); }, - TypeError, - 'O must be an Object' - ); - }); - - forEach(v.nonPropertyKeys, function (nonPropertyKey) { - t['throws']( - function () { ES.DeletePropertyOrThrow({}, nonPropertyKey, {}); }, - TypeError, - debug(nonPropertyKey) + ' is not a Property Key' - ); - }); - - t.test('defines correctly', function (st) { - var obj = { 'the key': 42 }; - var key = 'the key'; - - st.equal(ES.DeletePropertyOrThrow(obj, key), true, 'deletes property successfully'); - st.equal(key in obj, false, 'key is no longer in the object'); - - st.end(); - }); - - t.test('fails as expected on a frozen object', { skip: !Object.freeze }, function (st) { - var obj = Object.freeze({ foo: 'bar' }); - st['throws']( - function () { ES.DeletePropertyOrThrow(obj, 'foo'); }, - TypeError, - 'nonconfigurable key can not be deleted' - ); - - st.end(); - }); - - var hasNonConfigurableFunctionName = !Object.getOwnPropertyDescriptor - || !Object.getOwnPropertyDescriptor(function () {}, 'name').configurable; - t.test('fails as expected on a function with a nonconfigurable name', { skip: !hasNonConfigurableFunctionName }, function (st) { - st['throws']( - function () { ES.DeletePropertyOrThrow(function () {}, 'name'); }, - TypeError, - 'nonconfigurable function name can not be deleted' - ); - st.end(); - }); - - t.end(); - }); - - test('EnumerableOwnNames', { skip: skips && skips.EnumerableOwnNames }, function (t) { - var obj = testEnumerableOwnNames(t, function (O) { return ES.EnumerableOwnNames(O); }); - - t.deepEqual( - ES.EnumerableOwnNames(obj), - ['own'], - 'returns enumerable own names' - ); - - t.end(); - }); - - test('thisNumberValue', function (t) { - forEach(v.nonNumbers, function (nonNumber) { - t['throws']( - function () { ES.thisNumberValue(nonNumber); }, - TypeError, - debug(nonNumber) + ' is not a Number' - ); - }); - - forEach(v.numbers, function (number) { - t.equal(ES.thisNumberValue(number), number, debug(number) + ' is its own thisNumberValue'); - var obj = Object(number); - t.equal(ES.thisNumberValue(obj), number, debug(obj) + ' is the boxed thisNumberValue'); - }); - - t.end(); - }); - - test('thisBooleanValue', function (t) { - forEach(v.nonBooleans, function (nonBoolean) { - t['throws']( - function () { ES.thisBooleanValue(nonBoolean); }, - TypeError, - debug(nonBoolean) + ' is not a Boolean' - ); - }); - - forEach(v.booleans, function (boolean) { - t.equal(ES.thisBooleanValue(boolean), boolean, debug(boolean) + ' is its own thisBooleanValue'); - var obj = Object(boolean); - t.equal(ES.thisBooleanValue(obj), boolean, debug(obj) + ' is the boxed thisBooleanValue'); - }); - - t.end(); - }); - - test('thisStringValue', function (t) { - forEach(v.nonStrings, function (nonString) { - t['throws']( - function () { ES.thisStringValue(nonString); }, - TypeError, - debug(nonString) + ' is not a String' - ); - }); - - forEach(v.strings, function (string) { - t.equal(ES.thisStringValue(string), string, debug(string) + ' is its own thisStringValue'); - var obj = Object(string); - t.equal(ES.thisStringValue(obj), string, debug(obj) + ' is the boxed thisStringValue'); - }); - - t.end(); - }); - - test('thisTimeValue', function (t) { - forEach(v.primitives.concat(v.objects), function (nonDate) { - t['throws']( - function () { ES.thisTimeValue(nonDate); }, - TypeError, - debug(nonDate) + ' is not a Date' - ); - }); - - forEach(v.timestamps, function (timestamp) { - var date = new Date(timestamp); - - t.equal(ES.thisTimeValue(date), timestamp, debug(date) + ' is its own thisTimeValue'); - }); - - t.end(); - }); - - test('SetIntegrityLevel', function (t) { - forEach(v.primitives, function (primitive) { - t['throws']( - function () { ES.SetIntegrityLevel(primitive); }, - TypeError, - debug(primitive) + ' is not an Object' - ); - }); - - t['throws']( - function () { ES.SetIntegrityLevel({}); }, - /^TypeError: Assertion failed: `level` must be `"sealed"` or `"frozen"`$/, - '`level` must be `"sealed"` or `"frozen"`' - ); - - var O = { a: 1 }; - t.equal(ES.SetIntegrityLevel(O, 'sealed'), true); - t['throws']( - function () { O.b = 2; }, - /^TypeError: (Cannot|Can't) add property b, object is not extensible$/, - 'sealing prevent new properties from being added' - ); - O.a = 2; - t.equal(O.a, 2, 'pre-frozen, existing properties are mutable'); - - t.equal(ES.SetIntegrityLevel(O, 'frozen'), true); - t['throws']( - function () { O.a = 3; }, - /^TypeError: Cannot assign to read only property 'a' of /, - 'freezing prevents existing properties from being mutated' - ); - - t.end(); - }); - - test('TestIntegrityLevel', function (t) { - forEach(v.primitives, function (primitive) { - t['throws']( - function () { ES.TestIntegrityLevel(primitive); }, - TypeError, - debug(primitive) + ' is not an Object' - ); - }); - - t['throws']( - function () { ES.TestIntegrityLevel({ a: 1 }); }, - /^TypeError: Assertion failed: `level` must be `"sealed"` or `"frozen"`$/, - '`level` must be `"sealed"` or `"frozen"`' - ); - - t.equal(ES.TestIntegrityLevel({ a: 1 }, 'sealed'), false, 'basic object is not sealed'); - t.equal(ES.TestIntegrityLevel({ a: 1 }, 'frozen'), false, 'basic object is not frozen'); - - t.test('preventExtensions', { skip: !Object.preventExtensions }, function (st) { - var o = Object.preventExtensions({ a: 1 }); - st.equal(ES.TestIntegrityLevel(o, 'sealed'), false, 'nonextensible object is not sealed'); - st.equal(ES.TestIntegrityLevel(o, 'frozen'), false, 'nonextensible object is not frozen'); - - var empty = Object.preventExtensions({}); - st.equal(ES.TestIntegrityLevel(empty, 'sealed'), true, 'empty nonextensible object is sealed'); - st.equal(ES.TestIntegrityLevel(empty, 'frozen'), true, 'empty nonextensible object is frozen'); - st.end(); - }); - - t.test('seal', { skip: !Object.seal }, function (st) { - var o = Object.seal({ a: 1 }); - st.equal(ES.TestIntegrityLevel(o, 'sealed'), true, 'sealed object is sealed'); - st.equal(ES.TestIntegrityLevel(o, 'frozen'), false, 'sealed object is not frozen'); - - var empty = Object.seal({}); - st.equal(ES.TestIntegrityLevel(empty, 'sealed'), true, 'empty sealed object is sealed'); - st.equal(ES.TestIntegrityLevel(empty, 'frozen'), true, 'empty sealed object is frozen'); - - st.end(); - }); - - t.test('freeze', { skip: !Object.freeze }, function (st) { - var o = Object.freeze({ a: 1 }); - st.equal(ES.TestIntegrityLevel(o, 'sealed'), true, 'frozen object is sealed'); - st.equal(ES.TestIntegrityLevel(o, 'frozen'), true, 'frozen object is frozen'); - - var empty = Object.freeze({}); - st.equal(ES.TestIntegrityLevel(empty, 'sealed'), true, 'empty frozen object is sealed'); - st.equal(ES.TestIntegrityLevel(empty, 'frozen'), true, 'empty frozen object is frozen'); - - st.end(); - }); - - t.end(); - }); - - test('OrdinaryHasInstance', function (t) { - forEach(v.nonFunctions, function (nonFunction) { - t.equal(ES.OrdinaryHasInstance(nonFunction, {}), false, debug(nonFunction) + ' is not callable'); - }); - - forEach(v.primitives, function (primitive) { - t.equal(ES.OrdinaryHasInstance(function () {}, primitive), false, debug(primitive) + ' is not an object'); - }); - - var C = function C() {}; - var D = function D() {}; - t.equal(ES.OrdinaryHasInstance(C, new C()), true, 'constructor function has an instance of itself'); - t.equal(ES.OrdinaryHasInstance(C, new D()), false, 'constructor/instance mismatch is false'); - t.equal(ES.OrdinaryHasInstance(D, new C()), false, 'instance/constructor mismatch is false'); - t.equal(ES.OrdinaryHasInstance(C, {}), false, 'plain object is not an instance of a constructor'); - t.equal(ES.OrdinaryHasInstance(Object, {}), true, 'plain object is an instance of Object'); - - t.end(); - }); - - test('OrdinaryHasProperty', function (t) { - forEach(v.primitives, function (primitive) { - t['throws']( - function () { ES.OrdinaryHasProperty(primitive, ''); }, - TypeError, - debug(primitive) + ' is not an object' - ); - }); - forEach(v.nonPropertyKeys, function (nonPropertyKey) { - t['throws']( - function () { ES.OrdinaryHasProperty({}, nonPropertyKey); }, - TypeError, - 'P: ' + debug(nonPropertyKey) + ' is not a Property Key' - ); - }); - - t.equal(ES.OrdinaryHasProperty({ a: 1 }, 'a'), true, 'own property is true'); - t.equal(ES.OrdinaryHasProperty({}, 'toString'), true, 'inherited property is true'); - t.equal(ES.OrdinaryHasProperty({}, 'nope'), false, 'absent property is false'); - - t.end(); - }); - - test('InstanceofOperator', function (t) { - forEach(v.primitives, function (primitive) { - t['throws']( - function () { ES.InstanceofOperator(primitive, function () {}); }, - TypeError, - debug(primitive) + ' is not an object' - ); - }); - - forEach(v.nonFunctions, function (nonFunction) { - t['throws']( - function () { ES.InstanceofOperator({}, nonFunction); }, - TypeError, - debug(nonFunction) + ' is not callable' - ); - }); - - var C = function C() {}; - var D = function D() {}; - - t.equal(ES.InstanceofOperator(new C(), C), true, 'constructor function has an instance of itself'); - t.equal(ES.InstanceofOperator(new D(), C), false, 'constructor/instance mismatch is false'); - t.equal(ES.InstanceofOperator(new C(), D), false, 'instance/constructor mismatch is false'); - t.equal(ES.InstanceofOperator({}, C), false, 'plain object is not an instance of a constructor'); - t.equal(ES.InstanceofOperator({}, Object), true, 'plain object is an instance of Object'); - - t.test('Symbol.hasInstance', { skip: !v.hasSymbols || !Symbol.hasInstance }, function (st) { - st.plan(4); - - var O = {}; - var C2 = function () {}; - st.equal(ES.InstanceofOperator(O, C2), false, 'O is not an instance of C2'); - - Object.defineProperty(C2, Symbol.hasInstance, { - value: function (obj) { - st.equal(this, C2, 'hasInstance receiver is C2'); - st.equal(obj, O, 'hasInstance argument is O'); - - return {}; // testing coercion to boolean - } - }); - - st.equal(ES.InstanceofOperator(O, C2), true, 'O is now an instance of C2'); - - st.end(); - }); - - t.end(); - }); - - test('Abstract Equality Comparison', function (t) { - t.test('same types use ===', function (st) { - forEach(v.primitives.concat(v.objects), function (value) { - st.equal(ES['Abstract Equality Comparison'](value, value), value === value, debug(value) + ' is abstractly equal to itself'); - }); - st.end(); - }); - - t.test('different types coerce', function (st) { - var pairs = [ - [null, undefined], - [3, '3'], - [true, '3'], - [true, 3], - [false, 0], - [false, '0'], - [3, [3]], - ['3', [3]], - [true, [1]], - [false, [0]], - [String(v.coercibleObject), v.coercibleObject], - [Number(String(v.coercibleObject)), v.coercibleObject], - [Number(v.coercibleObject), v.coercibleObject], - [String(Number(v.coercibleObject)), v.coercibleObject] - ]; - forEach(pairs, function (pair) { - var a = pair[0]; - var b = pair[1]; - // eslint-disable-next-line eqeqeq - st.equal(ES['Abstract Equality Comparison'](a, b), a == b, debug(a) + ' == ' + debug(b)); - // eslint-disable-next-line eqeqeq - st.equal(ES['Abstract Equality Comparison'](b, a), b == a, debug(b) + ' == ' + debug(a)); - }); - st.end(); - }); - - t.end(); - }); - - test('Strict Equality Comparison', function (t) { - t.test('same types use ===', function (st) { - forEach(v.primitives.concat(v.objects), function (value) { - st.equal(ES['Strict Equality Comparison'](value, value), value === value, debug(value) + ' is strictly equal to itself'); - }); - st.end(); - }); - - t.test('different types are not ===', function (st) { - var pairs = [ - [null, undefined], - [3, '3'], - [true, '3'], - [true, 3], - [false, 0], - [false, '0'], - [3, [3]], - ['3', [3]], - [true, [1]], - [false, [0]], - [String(v.coercibleObject), v.coercibleObject], - [Number(String(v.coercibleObject)), v.coercibleObject], - [Number(v.coercibleObject), v.coercibleObject], - [String(Number(v.coercibleObject)), v.coercibleObject] - ]; - forEach(pairs, function (pair) { - var a = pair[0]; - var b = pair[1]; - st.equal(ES['Strict Equality Comparison'](a, b), a === b, debug(a) + ' === ' + debug(b)); - st.equal(ES['Strict Equality Comparison'](b, a), b === a, debug(b) + ' === ' + debug(a)); - }); - st.end(); - }); - - t.end(); - }); - - test('Abstract Relational Comparison', function (t) { - t.test('at least one operand is NaN', function (st) { - st.equal(ES['Abstract Relational Comparison'](NaN, {}, true), undefined, 'LeftFirst: first is NaN, returns undefined'); - st.equal(ES['Abstract Relational Comparison']({}, NaN, true), undefined, 'LeftFirst: second is NaN, returns undefined'); - st.equal(ES['Abstract Relational Comparison'](NaN, {}, false), undefined, '!LeftFirst: first is NaN, returns undefined'); - st.equal(ES['Abstract Relational Comparison']({}, NaN, false), undefined, '!LeftFirst: second is NaN, returns undefined'); - st.end(); - }); - - t.equal(ES['Abstract Relational Comparison'](3, 4, true), true, 'LeftFirst: 3 is less than 4'); - t.equal(ES['Abstract Relational Comparison'](4, 3, true), false, 'LeftFirst: 3 is not less than 4'); - t.equal(ES['Abstract Relational Comparison'](3, 4, false), true, '!LeftFirst: 3 is less than 4'); - t.equal(ES['Abstract Relational Comparison'](4, 3, false), false, '!LeftFirst: 3 is not less than 4'); - - t.equal(ES['Abstract Relational Comparison']('3', '4', true), true, 'LeftFirst: "3" is less than "4"'); - t.equal(ES['Abstract Relational Comparison']('4', '3', true), false, 'LeftFirst: "3" is not less than "4"'); - t.equal(ES['Abstract Relational Comparison']('3', '4', false), true, '!LeftFirst: "3" is less than "4"'); - t.equal(ES['Abstract Relational Comparison']('4', '3', false), false, '!LeftFirst: "3" is not less than "4"'); - - t.equal(ES['Abstract Relational Comparison'](v.coercibleObject, 42, true), true, 'LeftFirst: coercible object is less than 42'); - t.equal(ES['Abstract Relational Comparison'](42, v.coercibleObject, true), false, 'LeftFirst: 42 is not less than coercible object'); - t.equal(ES['Abstract Relational Comparison'](v.coercibleObject, 42, false), true, '!LeftFirst: coercible object is less than 42'); - t.equal(ES['Abstract Relational Comparison'](42, v.coercibleObject, false), false, '!LeftFirst: 42 is not less than coercible object'); - - t.equal(ES['Abstract Relational Comparison'](v.coercibleObject, '3', true), false, 'LeftFirst: coercible object is not less than "3"'); - t.equal(ES['Abstract Relational Comparison']('3', v.coercibleObject, true), false, 'LeftFirst: "3" is not less than coercible object'); - t.equal(ES['Abstract Relational Comparison'](v.coercibleObject, '3', false), false, '!LeftFirst: coercible object is not less than "3"'); - t.equal(ES['Abstract Relational Comparison']('3', v.coercibleObject, false), false, '!LeftFirst: "3" is not less than coercible object'); - - t.end(); - }); - - test('ValidateAndApplyPropertyDescriptor', function (t) { - forEach(v.nonUndefinedPrimitives, function (nonUndefinedPrimitive) { - t['throws']( - function () { ES.ValidateAndApplyPropertyDescriptor(nonUndefinedPrimitive, '', false, v.genericDescriptor(), v.genericDescriptor()); }, - TypeError, - 'O: ' + debug(nonUndefinedPrimitive) + ' is not undefined or an Object' - ); - }); - - forEach(v.nonBooleans, function (nonBoolean) { - t['throws']( - function () { - return ES.ValidateAndApplyPropertyDescriptor( - undefined, - null, - nonBoolean, - v.genericDescriptor(), - v.genericDescriptor() - ); - }, - TypeError, - 'extensible: ' + debug(nonBoolean) + ' is not a Boolean' - ); - }); - - forEach(v.primitives, function (primitive) { - // Desc must be a Property Descriptor - t['throws']( - function () { - return ES.ValidateAndApplyPropertyDescriptor( - undefined, - null, - false, - primitive, - v.genericDescriptor() - ); - }, - TypeError, - 'Desc: ' + debug(primitive) + ' is not a Property Descriptor' - ); - }); - - forEach(v.nonUndefinedPrimitives, function (primitive) { - // current must be undefined or a Property Descriptor - t['throws']( - function () { - return ES.ValidateAndApplyPropertyDescriptor( - undefined, - null, - false, - v.genericDescriptor(), - primitive - ); - }, - TypeError, - 'current: ' + debug(primitive) + ' is not a Property Descriptor or undefined' - ); - }); - - forEach(v.nonPropertyKeys, function (nonPropertyKey) { - // if O is an object, P must be a property key - t['throws']( - function () { - return ES.ValidateAndApplyPropertyDescriptor( - {}, - nonPropertyKey, - false, - v.genericDescriptor(), - v.genericDescriptor() - ); - }, - TypeError, - 'P: ' + debug(nonPropertyKey) + ' is not a Property Key' - ); - }); - - t.test('current is undefined', function (st) { - var propertyKey = 'howdy'; - - st.test('generic descriptor', function (s2t) { - var generic = v.genericDescriptor(); - generic['[[Enumerable]]'] = true; - var O = {}; - ES.ValidateAndApplyPropertyDescriptor(undefined, propertyKey, true, generic); - s2t.equal( - ES.ValidateAndApplyPropertyDescriptor(O, propertyKey, false, generic), - false, - 'when extensible is false, nothing happens' - ); - s2t.deepEqual(O, {}, 'no changes applied when O is undefined or extensible is false'); - s2t.equal( - ES.ValidateAndApplyPropertyDescriptor(O, propertyKey, true, generic), - true, - 'operation is successful' - ); - var expected = {}; - expected[propertyKey] = undefined; - s2t.deepEqual(O, expected, 'generic descriptor has been defined as an own data property'); - s2t.end(); - }); - - st.test('data descriptor', function (s2t) { - var data = v.dataDescriptor(); - data['[[Enumerable]]'] = true; - - var O = {}; - ES.ValidateAndApplyPropertyDescriptor(undefined, propertyKey, true, data); - s2t.equal( - ES.ValidateAndApplyPropertyDescriptor(O, propertyKey, false, data), - false, - 'when extensible is false, nothing happens' - ); - s2t.deepEqual(O, {}, 'no changes applied when O is undefined or extensible is false'); - s2t.equal( - ES.ValidateAndApplyPropertyDescriptor(O, propertyKey, true, data), - true, - 'operation is successful' - ); - var expected = {}; - expected[propertyKey] = data['[[Value]]']; - s2t.deepEqual(O, expected, 'data descriptor has been defined as an own data property'); - s2t.end(); - }); - - st.test('accessor descriptor', function (s2t) { - var count = 0; - var accessor = v.accessorDescriptor(); - accessor['[[Enumerable]]'] = true; - accessor['[[Get]]'] = function () { - count += 1; - return count; - }; - - var O = {}; - ES.ValidateAndApplyPropertyDescriptor(undefined, propertyKey, true, accessor); - s2t.equal( - ES.ValidateAndApplyPropertyDescriptor(O, propertyKey, false, accessor), - false, - 'when extensible is false, nothing happens' - ); - s2t.deepEqual(O, {}, 'no changes applied when O is undefined or extensible is false'); - s2t.equal( - ES.ValidateAndApplyPropertyDescriptor(O, propertyKey, true, accessor), - true, - 'operation is successful' - ); - var expected = {}; - expected[propertyKey] = accessor['[[Get]]']() + 1; - s2t.deepEqual(O, expected, 'accessor descriptor has been defined as an own accessor property'); - s2t.end(); - }); - - st.end(); - }); - - t.test('every field in Desc is absent', { skip: 'it is unclear if having no fields qualifies Desc to be a Property Descriptor' }); - - forEach([v.dataDescriptor, v.accessorDescriptor, v.mutatorDescriptor], function (getDescriptor) { - t.equal( - ES.ValidateAndApplyPropertyDescriptor(undefined, 'property key', true, getDescriptor(), getDescriptor()), - true, - 'when Desc and current are the same, early return true' - ); - }); - - t.test('current is nonconfigurable', function (st) { - // note: these must not be generic descriptors, or else the algorithm returns an early true - st.equal( - ES.ValidateAndApplyPropertyDescriptor( - undefined, - 'property key', - true, - v.descriptors.configurable(v.dataDescriptor()), - v.descriptors.nonConfigurable(v.dataDescriptor()) - ), - false, - 'false if Desc is configurable' - ); - - st.equal( - ES.ValidateAndApplyPropertyDescriptor( - undefined, - 'property key', - true, - v.descriptors.enumerable(v.dataDescriptor()), - v.descriptors.nonEnumerable(v.dataDescriptor()) - ), - false, - 'false if Desc is Enumerable and current is not' - ); - - st.equal( - ES.ValidateAndApplyPropertyDescriptor( - undefined, - 'property key', - true, - v.descriptors.nonEnumerable(v.dataDescriptor()), - v.descriptors.enumerable(v.dataDescriptor()) - ), - false, - 'false if Desc is not Enumerable and current is' - ); - - var descLackingEnumerable = v.accessorDescriptor(); - delete descLackingEnumerable['[[Enumerable]]']; - st.equal( - ES.ValidateAndApplyPropertyDescriptor( - undefined, - 'property key', - true, - descLackingEnumerable, - v.descriptors.enumerable(v.accessorDescriptor()) - ), - true, - 'not false if Desc lacks Enumerable' - ); - - st.end(); - }); - - t.test('Desc and current: one is a data descriptor, one is not', { skip: !Object.defineProperty }, function (st) { - // note: Desc must be configurable if current is nonconfigurable, to hit this branch - st.equal( - ES.ValidateAndApplyPropertyDescriptor( - undefined, - 'property key', - true, - v.descriptors.configurable(v.accessorDescriptor()), - v.descriptors.nonConfigurable(v.dataDescriptor()) - ), - false, - 'false if current (data) is nonconfigurable' - ); - - st.equal( - ES.ValidateAndApplyPropertyDescriptor( - undefined, - 'property key', - true, - v.descriptors.configurable(v.dataDescriptor()), - v.descriptors.nonConfigurable(v.accessorDescriptor()) - ), - false, - 'false if current (not data) is nonconfigurable' - ); - - // one is data and one is not, - // // if current is data, convert to accessor - // // else convert to data - - var startsWithData = { - 'property key': 42 - }; - st.equal( - ES.ValidateAndApplyPropertyDescriptor( - startsWithData, - 'property key', - true, - v.descriptors.enumerable(v.descriptors.configurable(v.accessorDescriptor())), - v.descriptors.enumerable(v.descriptors.configurable(v.dataDescriptor())) - ), - true, - 'operation is successful: current is data, Desc is accessor' - ); - var shouldBeAccessor = Object.getOwnPropertyDescriptor(startsWithData, 'property key'); - st.equal(typeof shouldBeAccessor.get, 'function', 'has a getter'); - - var key = 'property key'; - var startsWithAccessor = {}; - Object.defineProperty(startsWithAccessor, key, { - configurable: true, - enumerable: true, - get: function get() { return 42; } - }); - st.equal( - ES.ValidateAndApplyPropertyDescriptor( - startsWithAccessor, - key, - true, - v.descriptors.enumerable(v.descriptors.configurable(v.dataDescriptor())), - v.descriptors.enumerable(v.descriptors.configurable(v.accessorDescriptor(42))) - ), - true, - 'operation is successful: current is accessor, Desc is data' - ); - var shouldBeData = Object.getOwnPropertyDescriptor(startsWithAccessor, 'property key'); - st.deepEqual(shouldBeData, { configurable: true, enumerable: true, value: 42, writable: false }, 'is a data property'); - - st.end(); - }); - - t.test('Desc and current are both data descriptors', function (st) { - st.equal( - ES.ValidateAndApplyPropertyDescriptor( - undefined, - 'property key', - true, - v.descriptors.writable(v.dataDescriptor()), - v.descriptors.nonWritable(v.descriptors.nonConfigurable(v.dataDescriptor())) - ), - false, - 'false if frozen current and writable Desc' - ); - - st.equal( - ES.ValidateAndApplyPropertyDescriptor( - undefined, - 'property key', - true, - v.descriptors.configurable({ '[[Value]]': 42 }), - v.descriptors.nonWritable({ '[[Value]]': 7 }) - ), - false, - 'false if nonwritable current has a different value than Desc' - ); - - st.end(); - }); - - t.test('current is nonconfigurable; Desc and current are both accessor descriptors', function (st) { - st.equal( - ES.ValidateAndApplyPropertyDescriptor( - undefined, - 'property key', - true, - v.mutatorDescriptor(), - v.descriptors.nonConfigurable(v.mutatorDescriptor()) - ), - false, - 'false if both Sets are not equal' - ); - - st.equal( - ES.ValidateAndApplyPropertyDescriptor( - undefined, - 'property key', - true, - v.accessorDescriptor(), - v.descriptors.nonConfigurable(v.accessorDescriptor()) - ), - false, - 'false if both Gets are not equal' - ); - - st.end(); - }); - - t.end(); - }); - - test('OrdinaryGetOwnProperty', function (t) { - forEach(v.primitives, function (primitive) { - t['throws']( - function () { ES.OrdinaryGetOwnProperty(primitive, ''); }, - TypeError, - 'O: ' + debug(primitive) + ' is not an Object' - ); - }); - forEach(v.nonPropertyKeys, function (nonPropertyKey) { - t['throws']( - function () { ES.OrdinaryGetOwnProperty({}, nonPropertyKey); }, - TypeError, - 'P: ' + debug(nonPropertyKey) + ' is not a Property Key' - ); - }); - - t.equal(ES.OrdinaryGetOwnProperty({}, 'not in the object'), undefined, 'missing property yields undefined'); - t.equal(ES.OrdinaryGetOwnProperty({}, 'toString'), undefined, 'inherited non-own property yields undefined'); - - t.deepEqual( - ES.OrdinaryGetOwnProperty({ a: 1 }, 'a'), - ES.ToPropertyDescriptor({ - configurable: true, - enumerable: true, - value: 1, - writable: true - }), - 'own assigned data property yields expected descriptor' - ); - - t.deepEqual( - ES.OrdinaryGetOwnProperty(/a/, 'lastIndex'), - ES.ToPropertyDescriptor({ - configurable: false, - enumerable: false, - value: 0, - writable: true - }), - 'regex lastIndex yields expected descriptor' - ); - - t.deepEqual( - ES.OrdinaryGetOwnProperty([], 'length'), - ES.ToPropertyDescriptor({ - configurable: false, - enumerable: false, - value: 0, - writable: true - }), - 'array length yields expected descriptor' - ); - - t.deepEqual( - ES.OrdinaryGetOwnProperty(Object.prototype, 'toString'), - ES.ToPropertyDescriptor({ - configurable: true, - enumerable: false, - value: Object.prototype.toString, - writable: true - }), - 'own non-enumerable data property yields expected descriptor' - ); - - t.test('ES5+', { skip: !Object.defineProperty }, function (st) { - var O = {}; - Object.defineProperty(O, 'foo', { - configurable: false, - enumerable: false, - value: O, - writable: true - }); - - t.deepEqual( - ES.OrdinaryGetOwnProperty(O, 'foo'), - ES.ToPropertyDescriptor({ - configurable: false, - enumerable: false, - value: O, - writable: true - }), - 'defined own property yields expected descriptor' - ); - - st.end(); - }); - - t.end(); - }); - - test('OrdinaryDefineOwnProperty', { skip: !Object.defineProperty }, function (t) { - forEach(v.primitives, function (primitive) { - t['throws']( - function () { ES.CopyDataProperties(primitive, {}, []); }, - TypeError, - 'O: ' + debug(primitive) + ' is not an Object' - ); - }); - forEach(v.nonPropertyKeys, function (nonPropertyKey) { - t['throws']( - function () { ES.OrdinaryDefineOwnProperty({}, nonPropertyKey, v.genericDescriptor()); }, - TypeError, - 'P: ' + debug(nonPropertyKey) + ' is not a Property Key' - ); - }); - forEach(v.primitives, function (primitive) { - t['throws']( - function () { ES.OrdinaryDefineOwnProperty(primitive, '', v.genericDescriptor()); }, - TypeError, - 'Desc: ' + debug(primitive) + ' is not a Property Descriptor' - ); - }); - - var O = {}; - var P = 'property key'; - var Desc = v.accessorDescriptor(); - t.equal( - ES.OrdinaryDefineOwnProperty(O, P, Desc), - true, - 'operation is successful' - ); - t.deepEqual( - Object.getOwnPropertyDescriptor(O, P), - ES.FromPropertyDescriptor(ES.CompletePropertyDescriptor(Desc)), - 'expected property descriptor is defined' - ); - - t.end(); - }); - - test('ArrayCreate', function (t) { - forEach(v.nonIntegerNumbers.concat([-1]), function (nonIntegerNumber) { - t['throws']( - function () { ES.ArrayCreate(nonIntegerNumber); }, - TypeError, - 'length must be an integer number >= 0' - ); - }); - - t['throws']( - function () { ES.ArrayCreate(Math.pow(2, 32)); }, - RangeError, - 'length must be < 2**32' - ); - - t.deepEqual(ES.ArrayCreate(-0), [], 'length of -0 creates an empty array'); - t.deepEqual(ES.ArrayCreate(0), [], 'length of +0 creates an empty array'); - // eslint-disable-next-line no-sparse-arrays, comma-spacing - t.deepEqual(ES.ArrayCreate(1), [,], 'length of 1 creates a sparse array of length 1'); - // eslint-disable-next-line no-sparse-arrays, comma-spacing - t.deepEqual(ES.ArrayCreate(2), [,,], 'length of 2 creates a sparse array of length 2'); - - // eslint-disable-next-line no-proto - t.test('proto argument', { skip: [].__proto__ !== Array.prototype }, function (st) { - var fakeProto = { - push: { toString: function () { return 'not array push'; } } - }; - st.equal(ES.ArrayCreate(0, fakeProto).push, fakeProto.push, 'passing the proto argument works'); - st.end(); - }); - - t.end(); - }); - - test('ArraySetLength', function (t) { - forEach(v.primitives.concat(v.objects), function (nonArray) { - t['throws']( - function () { ES.ArraySetLength(nonArray, 0); }, - TypeError, - 'A: ' + debug(nonArray) + ' is not an Array' - ); - }); - - forEach(v.nonUndefinedPrimitives, function (primitive) { - t['throws']( - function () { ES.ArraySetLength([], primitive); }, - TypeError, - 'Desc: ' + debug(primitive) + ' is not a Property Descriptor' - ); - }); - - t.test('making length nonwritable', { skip: !Object.defineProperty }, function (st) { - var a = []; - ES.ArraySetLength(a, { '[[Writable]]': false }); - st.deepEqual( - Object.getOwnPropertyDescriptor(a, 'length'), - { - configurable: false, - enumerable: false, - value: 0, - writable: false - }, - 'without a value, length becomes nonwritable' - ); - st.end(); - }); - - var arr = []; - ES.ArraySetLength(arr, { '[[Value]]': 7 }); - t.equal(arr.length, 7, 'array now has a length of 7'); - - t.end(); - }); - - test('CreateHTML', function (t) { - forEach(v.nonStrings, function (nonString) { - t['throws']( - function () { ES.CreateHTML('', nonString, '', ''); }, - TypeError, - 'tag: ' + debug(nonString) + ' is not a String' - ); - t['throws']( - function () { ES.CreateHTML('', '', nonString, ''); }, - TypeError, - 'attribute: ' + debug(nonString) + ' is not a String' - ); - }); - - t.equal( - ES.CreateHTML( - { toString: function () { return 'the string'; } }, - 'some HTML tag!', - '' - ), - 'the string', - 'works with an empty string attribute value' - ); - - t.equal( - ES.CreateHTML( - { toString: function () { return 'the string'; } }, - 'some HTML tag!', - 'attr', - 'value "with quotes"' - ), - 'the string', - 'works with an attribute, and a value with quotes' - ); - - t.end(); - }); - - test('GetOwnPropertyKeys', function (t) { - forEach(v.primitives, function (primitive) { - t['throws']( - function () { ES.GetOwnPropertyKeys(primitive, 'String'); }, - TypeError, - 'O: ' + debug(primitive) + ' is not an Object' - ); - }); - - t['throws']( - function () { ES.GetOwnPropertyKeys({}, 'not string or symbol'); }, - TypeError, - 'Type: must be "String" or "Symbol"' - ); - - t.test('Symbols', { skip: !v.hasSymbols }, function (st) { - var O = { a: 1 }; - O[Symbol.iterator] = true; - var s = Symbol('test'); - Object.defineProperty(O, s, { enumerable: false, value: true }); - - st.deepEqual( - ES.GetOwnPropertyKeys(O, 'Symbol'), - [Symbol.iterator, s], - 'works with Symbols, enumerable or not' - ); - - st.end(); - }); - - t.test('non-enumerable names', { skip: !Object.defineProperty }, function (st) { - var O = { a: 1 }; - Object.defineProperty(O, 'b', { enumerable: false, value: 2 }); - if (v.hasSymbols) { - O[Symbol.iterator] = true; - } - - st.deepEqual( - ES.GetOwnPropertyKeys(O, 'String').sort(), - ['a', 'b'].sort(), - 'works with Strings, enumerable or not' - ); - - st.end(); - }); - - t.deepEqual( - ES.GetOwnPropertyKeys({ a: 1, b: 2 }, 'String').sort(), - ['a', 'b'].sort(), - 'works with enumerable keys' - ); - - t.end(); - }); - - test('SymbolDescriptiveString', function (t) { - forEach(v.nonSymbolPrimitives.concat(v.objects), function (nonSymbol) { - t['throws']( - function () { ES.SymbolDescriptiveString(nonSymbol); }, - TypeError, - debug(nonSymbol) + ' is not a Symbol' - ); - }); - - t.test('Symbols', { skip: !v.hasSymbols }, function (st) { - st.equal(ES.SymbolDescriptiveString(Symbol()), 'Symbol()', 'undefined description'); - st.equal(ES.SymbolDescriptiveString(Symbol('')), 'Symbol()', 'empty string description'); - st.equal(ES.SymbolDescriptiveString(Symbol.iterator), 'Symbol(Symbol.iterator)', 'well-known symbol'); - st.equal(ES.SymbolDescriptiveString(Symbol('foo')), 'Symbol(foo)', 'string description'); - - st.end(); - }); - - t.end(); - }); - - test('GetSubstitution', { skip: skips && skips.GetSubstitution }, function (t) { - forEach(v.nonStrings, function (nonString) { - t['throws']( - function () { ES.GetSubstitution(nonString, '', 0, [], ''); }, - TypeError, - '`matched`: ' + debug(nonString) + ' is not a String' - ); - - t['throws']( - function () { ES.GetSubstitution('', nonString, 0, [], ''); }, - TypeError, - '`str`: ' + debug(nonString) + ' is not a String' - ); - - t['throws']( - function () { ES.GetSubstitution('', '', 0, [], nonString); }, - TypeError, - '`replacement`: ' + debug(nonString) + ' is not a String' - ); - - t['throws']( - function () { ES.GetSubstitution('', '', 0, [nonString], ''); }, - TypeError, - '`captures`: ' + debug([nonString]) + ' is not an Array of strings' - ); - }); - - forEach(v.nonIntegerNumbers.concat([-1, -42, -Infinity]), function (nonNonNegativeInteger) { - t['throws']( - function () { ES.GetSubstitution('', '', nonNonNegativeInteger, [], ''); }, - TypeError, - '`position`: ' + debug(nonNonNegativeInteger) + ' is not a non-negative integer' - ); - }); - - forEach(v.nonArrays, function (nonArray) { - t['throws']( - function () { ES.GetSubstitution('', '', 0, nonArray, ''); }, - TypeError, - '`captures`: ' + debug(nonArray) + ' is not an Array' - ); - }); - - t.equal( - ES.GetSubstitution('def', 'abcdefghi', 3, [], '123'), - '123', - 'returns the substitution' - ); - t.equal( - ES.GetSubstitution('abcdef', 'abcdefghi', 0, [], '$$2$'), - '$2$', - 'supports $$, and trailing $' - ); - - t.equal( - ES.GetSubstitution('abcdef', 'abcdefghi', 0, [], '>$&<'), - '>abcdef<', - 'supports $&' - ); - - t.equal( - ES.GetSubstitution('abcdef', 'abcdefghi', 0, [], '>$`<'), - '><', - 'supports $` at position 0' - ); - t.equal( - ES.GetSubstitution('def', 'abcdefghi', 3, [], '>$`<'), - '>ab<', - 'supports $` at position > 0' - ); - - t.equal( - ES.GetSubstitution('def', 'abcdefghi', 7, [], ">$'<"), - '><', - "supports $' at a position where there's less than `matched.length` chars left" - ); - t.equal( - ES.GetSubstitution('def', 'abcdefghi', 3, [], ">$'<"), - '>ghi<', - "supports $' at a position where there's more than `matched.length` chars left" - ); - - for (var i = 0; i < 100; i += 1) { - var captures = []; - captures[i] = 'test'; - if (i > 0) { - t.equal( - ES.GetSubstitution('abcdef', 'abcdefghi', 0, [], '>$' + i + '<'), - '>undefined<', - 'supports $' + i + ' with no captures' - ); - t.equal( - ES.GetSubstitution('abcdef', 'abcdefghi', 0, [], '>$' + i), - '>undefined', - 'supports $' + i + ' at the end of the replacement, with no captures' - ); - t.equal( - ES.GetSubstitution('abcdef', 'abcdefghi', 0, captures, '>$' + i + '<'), - '><', - 'supports $' + i + ' with a capture at that index' - ); - t.equal( - ES.GetSubstitution('abcdef', 'abcdefghi', 0, captures, '>$' + i), - '>', - 'supports $' + i + ' at the end of the replacement, with a capture at that index' - ); - } - if (i < 10) { - t.equal( - ES.GetSubstitution('abcdef', 'abcdefghi', 0, [], '>$0' + i + '<'), - i === 0 ? '><' : '>undefined<', - 'supports $0' + i + ' with no captures' - ); - t.equal( - ES.GetSubstitution('abcdef', 'abcdefghi', 0, [], '>$0' + i), - i === 0 ? '>' : '>undefined', - 'supports $0' + i + ' at the end of the replacement, with no captures' - ); - t.equal( - ES.GetSubstitution('abcdef', 'abcdefghi', 0, captures, '>$0' + i + '<'), - '><', - 'supports $0' + i + ' with a capture at that index' - ); - t.equal( - ES.GetSubstitution('abcdef', 'abcdefghi', 0, captures, '>$0' + i), - '>', - 'supports $0' + i + ' at the end of the replacement, with a capture at that index' - ); - } - } - - t.end(); - }); - - test('SecFromTime', function (t) { - var now = new Date(); - t.equal(ES.SecFromTime(now.getTime()), now.getUTCSeconds(), 'second from Date timestamp matches getUTCSeconds'); - t.end(); - }); - - test('MinFromTime', function (t) { - var now = new Date(); - t.equal(ES.MinFromTime(now.getTime()), now.getUTCMinutes(), 'minute from Date timestamp matches getUTCMinutes'); - t.end(); - }); - - test('HourFromTime', function (t) { - var now = new Date(); - t.equal(ES.HourFromTime(now.getTime()), now.getUTCHours(), 'hour from Date timestamp matches getUTCHours'); - t.end(); - }); - - test('msFromTime', function (t) { - var now = new Date(); - t.equal(ES.msFromTime(now.getTime()), now.getUTCMilliseconds(), 'ms from Date timestamp matches getUTCMilliseconds'); - t.end(); - }); - - var msPerSecond = 1e3; - var msPerMinute = 60 * msPerSecond; - var msPerHour = 60 * msPerMinute; - var msPerDay = 24 * msPerHour; - - test('Day', function (t) { - var time = Date.UTC(2019, 8, 10, 2, 3, 4, 5); - var add = 2.5; - var later = new Date(time + (add * msPerDay)); - - t.equal(ES.Day(later.getTime()), ES.Day(time) + Math.floor(add), 'adding 2.5 days worth of ms, gives a Day delta of 2'); - t.end(); - }); - - test('TimeWithinDay', function (t) { - var time = Date.UTC(2019, 8, 10, 2, 3, 4, 5); - var add = 2.5; - var later = new Date(time + (add * msPerDay)); - - t.equal(ES.TimeWithinDay(later.getTime()), ES.TimeWithinDay(time) + (0.5 * msPerDay), 'adding 2.5 days worth of ms, gives a TimeWithinDay delta of +0.5'); - t.end(); - }); - - test('DayFromYear', function (t) { - t.equal(ES.DayFromYear(2021) - ES.DayFromYear(2020), 366, '2021 is a leap year, has 366 days'); - t.equal(ES.DayFromYear(2020) - ES.DayFromYear(2019), 365, '2020 is not a leap year, has 365 days'); - t.equal(ES.DayFromYear(2019) - ES.DayFromYear(2018), 365, '2019 is not a leap year, has 365 days'); - t.equal(ES.DayFromYear(2018) - ES.DayFromYear(2017), 365, '2018 is not a leap year, has 365 days'); - t.equal(ES.DayFromYear(2017) - ES.DayFromYear(2016), 366, '2017 is a leap year, has 366 days'); - - t.end(); - }); - - test('TimeFromYear', function (t) { - for (var i = 1900; i < 2100; i += 1) { - t.equal(ES.TimeFromYear(i), Date.UTC(i, 0, 1), 'TimeFromYear matches a Date object’s year: ' + i); - } - t.end(); - }); - - test('YearFromTime', function (t) { - for (var i = 1900; i < 2100; i += 1) { - t.equal(ES.YearFromTime(Date.UTC(i, 0, 1)), i, 'YearFromTime matches a Date object’s year on 1/1: ' + i); - t.equal(ES.YearFromTime(Date.UTC(i, 10, 1)), i, 'YearFromTime matches a Date object’s year on 10/1: ' + i); - } - t.end(); - }); - - test('WeekDay', function (t) { - var now = new Date(); - var today = now.getUTCDay(); - for (var i = 0; i < 7; i += 1) { - var weekDay = ES.WeekDay(now.getTime() + (i * msPerDay)); - t.equal(weekDay, (today + i) % 7, i + ' days after today (' + today + '), WeekDay is ' + weekDay); - } - t.end(); - }); - - test('DaysInYear', function (t) { - t.equal(ES.DaysInYear(2021), 365, '2021 is not a leap year'); - t.equal(ES.DaysInYear(2020), 366, '2020 is a leap year'); - t.equal(ES.DaysInYear(2019), 365, '2019 is not a leap year'); - t.equal(ES.DaysInYear(2018), 365, '2018 is not a leap year'); - t.equal(ES.DaysInYear(2017), 365, '2017 is not a leap year'); - t.equal(ES.DaysInYear(2016), 366, '2016 is a leap year'); - - t.end(); - }); - - test('InLeapYear', function (t) { - t.equal(ES.InLeapYear(Date.UTC(2021, 0, 1)), 0, '2021 is not a leap year'); - t.equal(ES.InLeapYear(Date.UTC(2020, 0, 1)), 1, '2020 is a leap year'); - t.equal(ES.InLeapYear(Date.UTC(2019, 0, 1)), 0, '2019 is not a leap year'); - t.equal(ES.InLeapYear(Date.UTC(2018, 0, 1)), 0, '2018 is not a leap year'); - t.equal(ES.InLeapYear(Date.UTC(2017, 0, 1)), 0, '2017 is not a leap year'); - t.equal(ES.InLeapYear(Date.UTC(2016, 0, 1)), 1, '2016 is a leap year'); - - t.end(); - }); - - test('DayWithinYear', function (t) { - t.equal(ES.DayWithinYear(Date.UTC(2019, 0, 1)), 0, '1/1 is the 1st day'); - t.equal(ES.DayWithinYear(Date.UTC(2019, 11, 31)), 364, '12/31 is the 365th day in a non leap year'); - t.equal(ES.DayWithinYear(Date.UTC(2016, 11, 31)), 365, '12/31 is the 366th day in a leap year'); - - t.end(); - }); - - test('MonthFromTime', function (t) { - t.equal(ES.MonthFromTime(Date.UTC(2019, 0, 1)), 0, 'non-leap: 1/1 gives January'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 0, 31)), 0, 'non-leap: 1/31 gives January'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 1, 1)), 1, 'non-leap: 2/1 gives February'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 1, 28)), 1, 'non-leap: 2/28 gives February'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 1, 29)), 2, 'non-leap: 2/29 gives March'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 2, 1)), 2, 'non-leap: 3/1 gives March'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 2, 31)), 2, 'non-leap: 3/31 gives March'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 3, 1)), 3, 'non-leap: 4/1 gives April'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 3, 30)), 3, 'non-leap: 4/30 gives April'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 4, 1)), 4, 'non-leap: 5/1 gives May'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 4, 31)), 4, 'non-leap: 5/31 gives May'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 5, 1)), 5, 'non-leap: 6/1 gives June'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 5, 30)), 5, 'non-leap: 6/30 gives June'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 6, 1)), 6, 'non-leap: 7/1 gives July'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 6, 31)), 6, 'non-leap: 7/31 gives July'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 7, 1)), 7, 'non-leap: 8/1 gives August'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 7, 30)), 7, 'non-leap: 8/30 gives August'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 8, 1)), 8, 'non-leap: 9/1 gives September'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 8, 30)), 8, 'non-leap: 9/30 gives September'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 9, 1)), 9, 'non-leap: 10/1 gives October'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 9, 31)), 9, 'non-leap: 10/31 gives October'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 10, 1)), 10, 'non-leap: 11/1 gives November'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 10, 30)), 10, 'non-leap: 11/30 gives November'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 11, 1)), 11, 'non-leap: 12/1 gives December'); - t.equal(ES.MonthFromTime(Date.UTC(2019, 11, 31)), 11, 'non-leap: 12/31 gives December'); - - t.equal(ES.MonthFromTime(Date.UTC(2016, 0, 1)), 0, 'leap: 1/1 gives January'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 0, 31)), 0, 'leap: 1/31 gives January'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 1, 1)), 1, 'leap: 2/1 gives February'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 1, 28)), 1, 'leap: 2/28 gives February'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 1, 29)), 1, 'leap: 2/29 gives February'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 2, 1)), 2, 'leap: 3/1 gives March'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 2, 31)), 2, 'leap: 3/31 gives March'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 3, 1)), 3, 'leap: 4/1 gives April'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 3, 30)), 3, 'leap: 4/30 gives April'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 4, 1)), 4, 'leap: 5/1 gives May'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 4, 31)), 4, 'leap: 5/31 gives May'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 5, 1)), 5, 'leap: 6/1 gives June'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 5, 30)), 5, 'leap: 6/30 gives June'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 6, 1)), 6, 'leap: 7/1 gives July'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 6, 31)), 6, 'leap: 7/31 gives July'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 7, 1)), 7, 'leap: 8/1 gives August'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 7, 30)), 7, 'leap: 8/30 gives August'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 8, 1)), 8, 'leap: 9/1 gives September'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 8, 30)), 8, 'leap: 9/30 gives September'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 9, 1)), 9, 'leap: 10/1 gives October'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 9, 31)), 9, 'leap: 10/31 gives October'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 10, 1)), 10, 'leap: 11/1 gives November'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 10, 30)), 10, 'leap: 11/30 gives November'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 11, 1)), 11, 'leap: 12/1 gives December'); - t.equal(ES.MonthFromTime(Date.UTC(2016, 11, 31)), 11, 'leap: 12/31 gives December'); - t.end(); - }); - - test('DateFromTime', function (t) { - var i; - for (i = 1; i <= 28; i += 1) { - t.equal(ES.DateFromTime(Date.UTC(2019, 1, i)), i, '2019.02.' + i + ' is date ' + i); - } - for (i = 1; i <= 29; i += 1) { - t.equal(ES.DateFromTime(Date.UTC(2016, 1, i)), i, '2016.02.' + i + ' is date ' + i); - } - for (i = 1; i <= 30; i += 1) { - t.equal(ES.DateFromTime(Date.UTC(2019, 8, i)), i, '2019.09.' + i + ' is date ' + i); - } - for (i = 1; i <= 31; i += 1) { - t.equal(ES.DateFromTime(Date.UTC(2019, 9, i)), i, '2019.10.' + i + ' is date ' + i); - } - t.end(); - }); - - test('MakeDay', function (t) { - var day2015 = 16687; - t.equal(ES.MakeDay(2015, 8, 9), day2015, '2015.09.09 is day 16687'); - var day2016 = day2015 + 366; // 2016 is a leap year - t.equal(ES.MakeDay(2016, 8, 9), day2016, '2015.09.09 is day 17053'); - var day2017 = day2016 + 365; - t.equal(ES.MakeDay(2017, 8, 9), day2017, '2017.09.09 is day 17418'); - var day2018 = day2017 + 365; - t.equal(ES.MakeDay(2018, 8, 9), day2018, '2018.09.09 is day 17783'); - var day2019 = day2018 + 365; - t.equal(ES.MakeDay(2019, 8, 9), day2019, '2019.09.09 is day 18148'); - t.end(); - }); - - test('MakeDate', function (t) { - forEach(v.infinities.concat(NaN), function (nonFiniteNumber) { - t.ok(is(ES.MakeDate(nonFiniteNumber, 0), NaN), debug(nonFiniteNumber) + ' is not a finite `day`'); - t.ok(is(ES.MakeDate(0, nonFiniteNumber), NaN), debug(nonFiniteNumber) + ' is not a finite `time`'); - }); - t.equal(ES.MakeDate(0, 0), 0, 'zero day and zero time is zero date'); - t.equal(ES.MakeDate(0, 123), 123, 'zero day and nonzero time is a date of the "time"'); - t.equal(ES.MakeDate(1, 0), msPerDay, 'day of 1 and zero time is a date of "ms per day"'); - t.equal(ES.MakeDate(3, 0), 3 * msPerDay, 'day of 3 and zero time is a date of thrice "ms per day"'); - t.equal(ES.MakeDate(1, 123), msPerDay + 123, 'day of 1 and nonzero time is a date of "ms per day" plus the "time"'); - t.equal(ES.MakeDate(3, 123), (3 * msPerDay) + 123, 'day of 3 and nonzero time is a date of thrice "ms per day" plus the "time"'); - - t.end(); - }); - - test('MakeTime', function (t) { - forEach(v.infinities.concat(NaN), function (nonFiniteNumber) { - t.ok(is(ES.MakeTime(nonFiniteNumber, 0, 0, 0), NaN), debug(nonFiniteNumber) + ' is not a finite `hour`'); - t.ok(is(ES.MakeTime(0, nonFiniteNumber, 0, 0), NaN), debug(nonFiniteNumber) + ' is not a finite `min`'); - t.ok(is(ES.MakeTime(0, 0, nonFiniteNumber, 0), NaN), debug(nonFiniteNumber) + ' is not a finite `sec`'); - t.ok(is(ES.MakeTime(0, 0, 0, nonFiniteNumber), NaN), debug(nonFiniteNumber) + ' is not a finite `ms`'); - }); - - t.equal( - ES.MakeTime(1.2, 2.3, 3.4, 4.5), - (1 * msPerHour) + (2 * msPerMinute) + (3 * msPerSecond) + 4, - 'all numbers are converted to integer, multiplied by the right number of ms, and summed' - ); - - t.end(); - }); - - test('TimeClip', function (t) { - forEach(v.infinities.concat(NaN), function (nonFiniteNumber) { - t.ok(is(ES.TimeClip(nonFiniteNumber), NaN), debug(nonFiniteNumber) + ' is not a finite `time`'); - }); - t.ok(is(ES.TimeClip(8.64e15 + 1), NaN), '8.64e15 is the largest magnitude considered "finite"'); - t.ok(is(ES.TimeClip(-8.64e15 - 1), NaN), '-8.64e15 is the largest magnitude considered "finite"'); - - forEach(v.zeroes.concat([-10, 10, Date.now()]), function (time) { - t.equal(ES.TimeClip(time), time, debug(time) + ' is a time of ' + debug(time)); - }); - - t.end(); - }); - - test('modulo', function (t) { - t.equal(3 % 2, 1, '+3 % 2 is +1'); - t.equal(ES.modulo(3, 2), 1, '+3 mod 2 is +1'); - - t.equal(-3 % 2, -1, '-3 % 2 is -1'); - t.equal(ES.modulo(-3, 2), 1, '-3 mod 2 is +1'); - t.end(); - }); - - test('ToDateString', function (t) { - forEach(v.nonNumbers, function (nonNumber) { - t['throws']( - function () { ES.ToDateString(nonNumber); }, - TypeError, - debug(nonNumber) + ' is not a Number' - ); - }); - - t.equal(ES.ToDateString(NaN), 'Invalid Date', 'NaN becomes "Invalid Date"'); - var now = Date.now(); - t.equal(ES.ToDateString(now), Date(now), 'any timestamp becomes `Date(timestamp)`'); - t.end(); - }); - - test('CreateListFromArrayLike', function (t) { - forEach(v.primitives, function (nonObject) { - t['throws']( - function () { ES.CreateListFromArrayLike(nonObject); }, - TypeError, - debug(nonObject) + ' is not an Object' - ); - }); - forEach(v.nonArrays, function (nonArray) { - t['throws']( - function () { ES.CreateListFromArrayLike({}, nonArray); }, - TypeError, - debug(nonArray) + ' is not an Array' - ); - }); - - t.deepEqual( - ES.CreateListFromArrayLike({ length: 2, 0: 'a', 1: 'b', 2: 'c' }), - ['a', 'b'], - 'arraylike stops at the length' - ); - - t.end(); - }); - - test('GetPrototypeFromConstructor', function (t) { - forEach(v.nonFunctions, function (nonFunction) { - t['throws']( - function () { ES.GetPrototypeFromConstructor(nonFunction, '%Array%'); }, - TypeError, - debug(nonFunction) + ' is not a constructor' - ); - }); - - forEach(arrowFns, function (arrowFn) { - t['throws']( - function () { ES.GetPrototypeFromConstructor(arrowFn, '%Array%'); }, - TypeError, - debug(arrowFn) + ' is not a constructor' - ); - }); - - var f = function () {}; - t.equal( - ES.GetPrototypeFromConstructor(f, '%Array.prototype%'), - f.prototype, - 'function with normal `prototype` property returns it' - ); - forEach([true, 'foo', 42], function (truthyPrimitive) { - f.prototype = truthyPrimitive; - t.equal( - ES.GetPrototypeFromConstructor(f, '%Array.prototype%'), - Array.prototype, - 'function with non-object `prototype` property (' + debug(truthyPrimitive) + ') returns default intrinsic' - ); - }); - - t.end(); - }); - - var getNamelessFunction = function () { - var f = Object(function () {}); - try { - delete f.name; - } catch (e) { /**/ } - return f; - }; - - test('SetFunctionName', function (t) { - t.test('non-extensible function', { skip: !Object.preventExtensions }, function (st) { - var f = getNamelessFunction(); - Object.preventExtensions(f); - st['throws']( - function () { ES.SetFunctionName(f, ''); }, - TypeError, - 'throws on a non-extensible function' - ); - st.end(); - }); - - t['throws']( - function () { ES.SetFunctionName(function g() {}, ''); }, - TypeError, - 'throws if function has an own `name` property' - ); - - forEach(v.nonPropertyKeys, function (nonPropertyKey) { - t['throws']( - function () { ES.SetFunctionName(getNamelessFunction(), nonPropertyKey); }, - TypeError, - debug(nonPropertyKey) + ' is not a Symbol or String' - ); - }); - - t.test('symbols', { skip: !v.hasSymbols || has(getNamelessFunction(), 'name') }, function (st) { - var pairs = [ - [Symbol(), ''], - [Symbol(undefined), ''], - [Symbol(null), '[null]'], - [Symbol(''), getInferredName ? '[]' : ''], - [Symbol.iterator, '[Symbol.iterator]'], - [Symbol('foo'), '[foo]'] - ]; - forEach(pairs, function (pair) { - var sym = pair[0]; - var desc = pair[1]; - var f = getNamelessFunction(); - ES.SetFunctionName(f, sym); - st.equal(f.name, desc, debug(sym) + ' yields a name of ' + debug(desc)); - }); - - st.end(); - }); - - var f = getNamelessFunction(); - t.test('when names are configurable', { skip: has(f, 'name') }, function (st) { - // without prefix - st.notEqual(f.name, 'foo', 'precondition'); - ES.SetFunctionName(f, 'foo'); - st.equal(f.name, 'foo', 'function name is set without a prefix'); - - // with prefix - var g = getNamelessFunction(); - st.notEqual(g.name, 'pre- foo', 'precondition'); - ES.SetFunctionName(g, 'foo', 'pre-'); - st.equal(g.name, 'pre- foo', 'function name is set with a prefix'); - - st.end(); - }); - - t.end(); - }); -}; - -var es2016 = function ES2016(ES, ops, expectedMissing, skips) { - es2015(ES, ops, expectedMissing, skips); - - test('SameValueNonNumber', function (t) { - var willThrow = [ - [3, 4], - [NaN, 4], - [4, ''], - ['abc', true], - [{}, false] - ]; - forEach(willThrow, function (nums) { - t['throws'](function () { return ES.SameValueNonNumber.apply(ES, nums); }, TypeError, 'value must be same type and non-number'); - }); - - forEach(v.objects.concat(v.nonNumberPrimitives), function (val) { - t.equal(val === val, ES.SameValueNonNumber(val, val), debug(val) + ' is SameValueNonNumber to itself'); - }); - - t.end(); - }); - - test('IterableToArrayLike', { skip: skips && skips.IterableToArrayLike }, function (t) { - t.test('custom iterables', { skip: !v.hasSymbols }, function (st) { - var O = {}; - O[Symbol.iterator] = function () { - var i = -1; - return { - next: function () { - i += 1; - return { - done: i >= 5, - value: i - }; - } - }; - }; - st.deepEqual( - ES.IterableToArrayLike(O), - [0, 1, 2, 3, 4], - 'Symbol.iterator method is called and values collected' - ); - - st.end(); - }); - - t.deepEqual(ES.IterableToArrayLike('abc'), ['a', 'b', 'c'], 'a string of code units spreads'); - t.deepEqual(ES.IterableToArrayLike('💩'), ['💩'], 'a string of code points spreads'); - t.deepEqual(ES.IterableToArrayLike('a💩c'), ['a', '💩', 'c'], 'a string of code points and units spreads'); - - var arr = [1, 2, 3]; - t.deepEqual(ES.IterableToArrayLike(arr), arr, 'an array becomes a similar array'); - t.notEqual(ES.IterableToArrayLike(arr), arr, 'an array becomes a different, but similar, array'); - - var O = {}; - t.equal(ES.IterableToArrayLike(O), O, 'a non-iterable non-array non-string object is returned directly'); - - t.end(); - }); - - test('OrdinaryGetPrototypeOf', function (t) { - t.equal(ES.OrdinaryGetPrototypeOf([]), Array.prototype, 'array [[Prototype]] is Array.prototype'); - t.equal(ES.OrdinaryGetPrototypeOf({}), Object.prototype, 'object [[Prototype]] is Object.prototype'); - t.equal(ES.OrdinaryGetPrototypeOf(/a/g), RegExp.prototype, 'regex [[Prototype]] is RegExp.prototype'); - t.equal(ES.OrdinaryGetPrototypeOf(Object('')), String.prototype, 'boxed string [[Prototype]] is String.prototype'); - t.equal(ES.OrdinaryGetPrototypeOf(Object(42)), Number.prototype, 'boxed number [[Prototype]] is Number.prototype'); - t.equal(ES.OrdinaryGetPrototypeOf(Object(true)), Boolean.prototype, 'boxed boolean [[Prototype]] is Boolean.prototype'); - if (v.hasSymbols) { - t.equal(ES.OrdinaryGetPrototypeOf(Object(Symbol.iterator)), Symbol.prototype, 'boxed symbol [[Prototype]] is Symbol.prototype'); - } - - forEach(v.primitives, function (primitive) { - t['throws']( - function () { ES.OrdinaryGetPrototypeOf(primitive); }, - TypeError, - debug(primitive) + ' is not an Object' - ); - }); - t.end(); - }); - - test('OrdinarySetPrototypeOf', function (t) { - var a = []; - var proto = {}; - - t.equal(ES.OrdinaryGetPrototypeOf(a), Array.prototype, 'precondition'); - t.equal(ES.OrdinarySetPrototypeOf(a, proto), true, 'setting prototype is successful'); - t.equal(ES.OrdinaryGetPrototypeOf(a), proto, 'postcondition'); - - t.end(); - }); -}; - -var es2017 = function ES2017(ES, ops, expectedMissing, skips) { - es2016(ES, ops, expectedMissing, assign({}, skips, { - EnumerableOwnNames: true, - IterableToArrayLike: true - })); - - test('ToIndex', function (t) { - t.ok(is(ES.ToIndex(), 0), 'no value gives 0'); - t.ok(is(ES.ToIndex(undefined), 0), 'undefined value gives 0'); - - t['throws'](function () { ES.ToIndex(-1); }, RangeError, 'negative numbers throw'); - - t['throws'](function () { ES.ToIndex(MAX_SAFE_INTEGER + 1); }, RangeError, 'too large numbers throw'); - - t.equal(ES.ToIndex(3), 3, 'numbers work'); - t.equal(ES.ToIndex(v.valueOfOnlyObject), 4, 'coercible objects are coerced'); - - t.end(); - }); - - test('EnumerableOwnProperties', { skip: skips && skips.EnumerableOwnProperties }, function (t) { - var obj = testEnumerableOwnNames(t, function (O) { - return ES.EnumerableOwnProperties(O, 'key'); - }); - - t.deepEqual( - ES.EnumerableOwnProperties(obj, 'value'), - [obj.own], - 'returns enumerable own values' - ); - - t.deepEqual( - ES.EnumerableOwnProperties(obj, 'key+value'), - [['own', obj.own]], - 'returns enumerable own entries' - ); - - t.end(); - }); - - test('IterableToList', function (t) { - var customIterator = function () { - var i = -1; - return { - next: function () { - i += 1; - return { - done: i >= 5, - value: i - }; - } - }; - }; - - t.deepEqual( - ES.IterableToList({}, customIterator), - [0, 1, 2, 3, 4], - 'iterator method is called and values collected' - ); - - t.test('Symbol support', { skip: !v.hasSymbols }, function (st) { - st.deepEqual(ES.IterableToList('abc', String.prototype[Symbol.iterator]), ['a', 'b', 'c'], 'a string of code units spreads'); - st.deepEqual(ES.IterableToList('☃', String.prototype[Symbol.iterator]), ['☃'], 'a string of code points spreads'); - - var arr = [1, 2, 3]; - st.deepEqual(ES.IterableToList(arr, arr[Symbol.iterator]), arr, 'an array becomes a similar array'); - st.notEqual(ES.IterableToList(arr, arr[Symbol.iterator]), arr, 'an array becomes a different, but similar, array'); - - st.end(); - }); - - t['throws']( - function () { ES.IterableToList({}, void 0); }, - TypeError, - 'non-function iterator method' - ); - - t.end(); - }); -}; - -var es2018 = function ES2018(ES, ops, expectedMissing, skips) { - es2017(ES, ops, expectedMissing, assign({}, skips, { - EnumerableOwnProperties: true, - GetSubstitution: true, - IsPropertyDescriptor: true - })); - - test('thisSymbolValue', function (t) { - forEach(v.nonSymbolPrimitives.concat(v.objects), function (nonSymbol) { - t['throws']( - function () { ES.thisSymbolValue(nonSymbol); }, - v.hasSymbols ? TypeError : SyntaxError, - debug(nonSymbol) + ' is not a Symbol' - ); - }); - - t.test('no native Symbols', { skip: v.hasSymbols }, function (st) { - forEach(v.objects.concat(v.primitives), function (value) { - st['throws']( - function () { ES.thisSymbolValue(value); }, - SyntaxError, - 'Symbols are not supported' - ); - }); - st.end(); - }); - - t.test('symbol values', { skip: !v.hasSymbols }, function (st) { - forEach(v.symbols, function (symbol) { - st.equal(ES.thisSymbolValue(symbol), symbol, 'Symbol value of ' + debug(symbol) + ' is same symbol'); - - st.equal( - ES.thisSymbolValue(Object(symbol)), - symbol, - 'Symbol value of ' + debug(Object(symbol)) + ' is ' + debug(symbol) - ); - }); - - st.end(); - }); - - t.end(); - }); - - test('IsStringPrefix', function (t) { - forEach(v.nonStrings, function (nonString) { - t['throws']( - function () { ES.IsStringPrefix(nonString, 'a'); }, - TypeError, - 'first arg: ' + debug(nonString) + ' is not a string' - ); - t['throws']( - function () { ES.IsStringPrefix('a', nonString); }, - TypeError, - 'second arg: ' + debug(nonString) + ' is not a string' - ); - }); - - forEach(v.strings, function (string) { - t.equal(ES.IsStringPrefix(string, string), true, debug(string) + ' is a prefix of itself'); - - t.equal(ES.IsStringPrefix('', string), true, 'the empty string is a prefix of everything'); - }); - - t.equal(ES.IsStringPrefix('abc', 'abcd'), true, '"abc" is a prefix of "abcd"'); - t.equal(ES.IsStringPrefix('abcd', 'abc'), false, '"abcd" is not a prefix of "abc"'); - - t.equal(ES.IsStringPrefix('a', 'bc'), false, '"a" is not a prefix of "bc"'); - - t.end(); - }); - - test('NumberToString', function (t) { - forEach(v.nonNumbers, function (nonNumber) { - t['throws']( - function () { ES.NumberToString(nonNumber); }, - TypeError, - debug(nonNumber) + ' is not a Number' - ); - }); - - forEach(v.numbers, function (number) { - t.equal(ES.NumberToString(number), String(number), debug(number) + ' stringifies to ' + number); - }); - - t.end(); - }); - - test('CopyDataProperties', function (t) { - t.test('first argument: target', function (st) { - forEach(v.primitives, function (primitive) { - st['throws']( - function () { ES.CopyDataProperties(primitive, {}, []); }, - TypeError, - debug(primitive) + ' is not an Object' - ); - }); - st.end(); - }); - - t.test('second argument: source', function (st) { - var frozenTarget = Object.freeze ? Object.freeze({}) : {}; - forEach(v.nullPrimitives, function (nullish) { - st.equal( - ES.CopyDataProperties(frozenTarget, nullish, []), - frozenTarget, - debug(nullish) + ' "source" yields identical, unmodified target' - ); - }); - - forEach(v.nonNullPrimitives, function (objectCoercible) { - var target = {}; - var result = ES.CopyDataProperties(target, objectCoercible, []); - st.equal(result, target, 'result === target'); - st.deepEqual(keys(result), keys(Object(objectCoercible)), 'target ends up with keys of ' + debug(objectCoercible)); - }); - - st.end(); - }); - - t.test('third argument: excludedItems', function (st) { - forEach(v.objects.concat(v.primitives), function (nonArray) { - st['throws']( - function () { ES.CopyDataProperties({}, {}, nonArray); }, - TypeError, - debug(nonArray) + ' is not an Array' - ); - }); - - forEach(v.nonPropertyKeys, function (nonPropertyKey) { - st['throws']( - function () { ES.CopyDataProperties({}, {}, [nonPropertyKey]); }, - TypeError, - debug(nonPropertyKey) + ' is not a Property Key' - ); - }); - - var result = ES.CopyDataProperties({}, { a: 1, b: 2, c: 3 }, ['b']); - st.deepEqual(keys(result), ['a', 'c'], 'excluded string keys are excluded'); - - st.test('excluding symbols', { skip: !v.hasSymbols }, function (s2t) { - var source = {}; - forEach(v.symbols, function (symbol) { - source[symbol] = true; - }); - - var includedSymbols = v.symbols.slice(1); - var excludedSymbols = v.symbols.slice(0, 1); - var target = ES.CopyDataProperties({}, source, excludedSymbols); - - forEach(includedSymbols, function (symbol) { - s2t.equal(has(target, symbol), true, debug(symbol) + ' is included'); - }); - - forEach(excludedSymbols, function (symbol) { - s2t.equal(has(target, symbol), false, debug(symbol) + ' is excluded'); - }); - - s2t.end(); - }); - - st.end(); - }); - - t.end(); - }); - - test('PromiseResolve', function (t) { - t.test('Promises unsupported', { skip: typeof Promise === 'function' }, function (st) { - st['throws']( - function () { ES.PromiseResolve(); }, - SyntaxError, - 'Promises are not supported' - ); - st.end(); - }); - - t.test('Promises supported', { skip: typeof Promise !== 'function' }, function (st) { - st.plan(2); - - var a = {}; - var b = {}; - var fulfilled = Promise.resolve(a); - var rejected = Promise.reject(b); - - ES.PromiseResolve(Promise, fulfilled).then(function (x) { - st.equal(x, a, 'fulfilled promise resolves to fulfilled'); - }); - - ES.PromiseResolve(Promise, rejected)['catch'](function (e) { - st.equal(e, b, 'rejected promise resolves to rejected'); - }); - }); - - t.end(); - }); - - test('EnumerableOwnPropertyNames', { skip: skips && skips.EnumerableOwnPropertyNames }, function (t) { - var obj = testEnumerableOwnNames(t, function (O) { - return ES.EnumerableOwnPropertyNames(O, 'key'); - }); - - t.deepEqual( - ES.EnumerableOwnPropertyNames(obj, 'value'), - [obj.own], - 'returns enumerable own values' - ); - - t.deepEqual( - ES.EnumerableOwnPropertyNames(obj, 'key+value'), - [['own', obj.own]], - 'returns enumerable own entries' - ); - - t.end(); - }); - - test('IsPromise', { skip: typeof Promise !== 'function' }, function (t) { - forEach(v.objects.concat(v.primitives), function (nonPromise) { - t.equal(ES.IsPromise(nonPromise), false, debug(nonPromise) + ' is not a Promise'); - }); - - var thenable = { then: Promise.prototype.then }; - t.equal(ES.IsPromise(thenable), false, 'generic thenable is not a Promise'); - - t.equal(ES.IsPromise(Promise.resolve()), true, 'Promise is a Promise'); - - t.end(); - }); - - test('GetSubstitution (ES2018+)', function (t) { - forEach(v.nonStrings, function (nonString) { - t['throws']( - function () { ES.GetSubstitution(nonString, '', 0, [], undefined, ''); }, - TypeError, - '`matched`: ' + debug(nonString) + ' is not a String' - ); - - t['throws']( - function () { ES.GetSubstitution('', nonString, 0, [], undefined, ''); }, - TypeError, - '`str`: ' + debug(nonString) + ' is not a String' - ); - - t['throws']( - function () { ES.GetSubstitution('', '', 0, [], undefined, nonString); }, - TypeError, - '`replacement`: ' + debug(nonString) + ' is not a String' - ); - - t['throws']( - function () { ES.GetSubstitution('', '', 0, [nonString], undefined, ''); }, - TypeError, - '`captures`: ' + debug([nonString]) + ' is not an Array of strings' - ); - }); - - forEach(v.nonIntegerNumbers.concat([-1, -42, -Infinity]), function (nonNonNegativeInteger) { - t['throws']( - function () { ES.GetSubstitution('', '', nonNonNegativeInteger, [], undefined, ''); }, - TypeError, - '`position`: ' + debug(nonNonNegativeInteger) + ' is not a non-negative integer' - ); - }); - - forEach(v.nonArrays, function (nonArray) { - t['throws']( - function () { ES.GetSubstitution('', '', 0, nonArray, undefined, ''); }, - TypeError, - '`captures`: ' + debug(nonArray) + ' is not an Array' - ); - }); - - t.equal( - ES.GetSubstitution('def', 'abcdefghi', 3, [], undefined, '123'), - '123', - 'returns the substitution' - ); - t.equal( - ES.GetSubstitution('abcdef', 'abcdefghi', 0, [], undefined, '$$2$'), - '$2$', - 'supports $$, and trailing $' - ); - - t.equal( - ES.GetSubstitution('abcdef', 'abcdefghi', 0, [], undefined, '>$&<'), - '>abcdef<', - 'supports $&' - ); - - t.equal( - ES.GetSubstitution('abcdef', 'abcdefghi', 0, [], undefined, '>$`<'), - '><', - 'supports $` at position 0' - ); - t.equal( - ES.GetSubstitution('def', 'abcdefghi', 3, [], undefined, '>$`<'), - '>ab<', - 'supports $` at position > 0' - ); - - t.equal( - ES.GetSubstitution('def', 'abcdefghi', 7, [], undefined, ">$'<"), - '><', - "supports $' at a position where there's less than `matched.length` chars left" - ); - t.equal( - ES.GetSubstitution('def', 'abcdefghi', 3, [], undefined, ">$'<"), - '>ghi<', - "supports $' at a position where there's more than `matched.length` chars left" - ); - - for (var i = 0; i < 100; i += 1) { - var captures = []; - captures[i] = 'test'; - if (i > 0) { - t.equal( - ES.GetSubstitution('abcdef', 'abcdefghi', 0, [], undefined, '>$' + i + '<'), - '>undefined<', - 'supports $' + i + ' with no captures' - ); - t.equal( - ES.GetSubstitution('abcdef', 'abcdefghi', 0, [], undefined, '>$' + i), - '>undefined', - 'supports $' + i + ' at the end of the replacement, with no captures' - ); - t.equal( - ES.GetSubstitution('abcdef', 'abcdefghi', 0, captures, undefined, '>$' + i + '<'), - '><', - 'supports $' + i + ' with a capture at that index' - ); - t.equal( - ES.GetSubstitution('abcdef', 'abcdefghi', 0, captures, undefined, '>$' + i), - '>', - 'supports $' + i + ' at the end of the replacement, with a capture at that index' - ); - } - if (i < 10) { - t.equal( - ES.GetSubstitution('abcdef', 'abcdefghi', 0, [], undefined, '>$0' + i + '<'), - i === 0 ? '><' : '>undefined<', - 'supports $0' + i + ' with no captures' - ); - t.equal( - ES.GetSubstitution('abcdef', 'abcdefghi', 0, [], undefined, '>$0' + i), - i === 0 ? '>' : '>undefined', - 'supports $0' + i + ' at the end of the replacement, with no captures' - ); - t.equal( - ES.GetSubstitution('abcdef', 'abcdefghi', 0, captures, undefined, '>$0' + i + '<'), - '><', - 'supports $0' + i + ' with a capture at that index' - ); - t.equal( - ES.GetSubstitution('abcdef', 'abcdefghi', 0, captures, undefined, '>$0' + i), - '>', - 'supports $0' + i + ' at the end of the replacement, with a capture at that index' - ); - } - } - - t.end(); - }); - - test('DateString', function (t) { - forEach(v.nonNumbers.concat(NaN), function (nonNumberOrNaN) { - t['throws']( - function () { ES.DateString(nonNumberOrNaN); }, - TypeError, - debug(nonNumberOrNaN) + ' is not a non-NaN Number' - ); - }); - - t.equal(ES.DateString(Date.UTC(2019, 8, 10, 7, 8, 9)), 'Tue Sep 10 2019'); - t.equal(ES.DateString(Date.UTC(2016, 1, 29, 7, 8, 9)), 'Mon Feb 29 2016'); // leap day - t.end(); - }); - - test('TimeString', function (t) { - forEach(v.nonNumbers.concat(NaN), function (nonNumberOrNaN) { - t['throws']( - function () { ES.TimeString(nonNumberOrNaN); }, - TypeError, - debug(nonNumberOrNaN) + ' is not a non-NaN Number' - ); - }); - - var tv = Date.UTC(2019, 8, 10, 7, 8, 9); - t.equal(ES.TimeString(tv), '07:08:09 GMT'); - t.end(); - }); -}; - -var es2019 = function ES2018(ES, ops, expectedMissing, skips) { - es2018(ES, ops, expectedMissing, assign({}, skips, { - })); - - test('AddEntriesFromIterable', function (t) { - t['throws']( - function () { ES.AddEntriesFromIterable({}, undefined, function () {}); }, - TypeError, - 'iterable must not be undefined' - ); - t['throws']( - function () { ES.AddEntriesFromIterable({}, null, function () {}); }, - TypeError, - 'iterable must not be null' - ); - forEach(v.nonFunctions, function (nonFunction) { - t['throws']( - function () { ES.AddEntriesFromIterable({}, {}, nonFunction); }, - TypeError, - debug(nonFunction) + ' is not a function' - ); - }); - - t.test('Symbol support', { skip: !v.hasSymbols }, function (st) { - st.plan(4); - - var O = {}; - st.equal(ES.AddEntriesFromIterable(O, [], function () {}), O, 'returns the target'); - - var adder = function (key, value) { - st.equal(this, O, 'adder gets proper receiver'); - st.equal(key, 0, 'k is key'); - st.equal(value, 'a', 'v is value'); - }; - ES.AddEntriesFromIterable(O, ['a'].entries(), adder); - - st.end(); - }); - - t.end(); - }); - - test('FlattenIntoArray', function (t) { - t.test('no mapper function', function (st) { - var testDepth = function testDepth(tt, depth, expected) { - var a = []; - var o = [[1], 2, , [[3]], [], 4, [[[[5]]]]]; // eslint-disable-line no-sparse-arrays - ES.FlattenIntoArray(a, o, o.length, 0, depth); - tt.deepEqual(a, expected, 'depth: ' + depth); - }; - - testDepth(st, 1, [1, 2, [3], 4, [[[5]]]]); - testDepth(st, 2, [1, 2, 3, 4, [[5]]]); - testDepth(st, 3, [1, 2, 3, 4, [5]]); - testDepth(st, 4, [1, 2, 3, 4, 5]); - testDepth(st, Infinity, [1, 2, 3, 4, 5]); - st.end(); - }); - - t.test('mapper function', function (st) { - var testMapper = function testMapper(tt, mapper, expected, thisArg) { - var a = []; - var o = [[1], 2, , [[3]], [], 4, [[[[5]]]]]; // eslint-disable-line no-sparse-arrays - ES.FlattenIntoArray(a, o, o.length, 0, 1, mapper, thisArg); - tt.deepEqual(a, expected); - }; - - var double = function double(x) { - return typeof x === 'number' ? 2 * x : x; - }; - testMapper( - st, - double, - [1, 4, [3], 8, [[[5]]]] - ); - testMapper( - st, - function (x) { return [this, double(x)]; }, - [42, [1], 42, 4, 42, [[3]], 42, [], 42, 8, 42, [[[[5]]]]], - 42 - ); - st.end(); - }); - - t.end(); - }); - - test('TrimString', function (t) { - t.test('non-object string', function (st) { - forEach(v.nullPrimitives, function (nullish) { - st['throws']( - function () { ES.TrimString(nullish); }, - debug(nullish) + ' is not an Object' - ); - }); - st.end(); - }); - - var string = ' \n abc \n '; - t.equal(ES.TrimString(string, 'start'), string.slice(string.indexOf('a'))); - t.equal(ES.TrimString(string, 'end'), string.slice(0, string.lastIndexOf('c') + 1)); - t.equal(ES.TrimString(string, 'start+end'), string.slice(string.indexOf('a'), string.lastIndexOf('c') + 1)); - - t.end(); - }); -}; - -module.exports = { - es2015: es2015, - es2016: es2016, - es2017: es2017, - es2018: es2018, - es2019: es2019 -}; diff --git a/scripts/2.5/node_modules/es-to-primitive/.editorconfig b/scripts/2.5/node_modules/es-to-primitive/.editorconfig deleted file mode 100644 index bc228f82..00000000 --- a/scripts/2.5/node_modules/es-to-primitive/.editorconfig +++ /dev/null @@ -1,20 +0,0 @@ -root = true - -[*] -indent_style = tab -indent_size = 4 -end_of_line = lf -charset = utf-8 -trim_trailing_whitespace = true -insert_final_newline = true -max_line_length = 150 - -[CHANGELOG.md] -indent_style = space -indent_size = 2 - -[*.json] -max_line_length = off - -[Makefile] -max_line_length = off diff --git a/scripts/2.5/node_modules/es-to-primitive/.eslintrc b/scripts/2.5/node_modules/es-to-primitive/.eslintrc deleted file mode 100644 index 09e0c6c2..00000000 --- a/scripts/2.5/node_modules/es-to-primitive/.eslintrc +++ /dev/null @@ -1,14 +0,0 @@ -{ - "root": true, - - "extends": "@ljharb", - - "rules": { - "complexity": [2, 14], - "func-name-matching": 0, - "id-length": [2, { "min": 1, "max": 24, "properties": "never" }], - "max-lines-per-function": [2, { "max": 68 }], - "max-statements": [2, 20], - "new-cap": [2, { "capIsNewExceptions": ["GetMethod"] }] - } -} diff --git a/scripts/2.5/node_modules/es-to-primitive/.jscs.json b/scripts/2.5/node_modules/es-to-primitive/.jscs.json deleted file mode 100644 index 8666c750..00000000 --- a/scripts/2.5/node_modules/es-to-primitive/.jscs.json +++ /dev/null @@ -1,176 +0,0 @@ -{ - "es3": true, - - "additionalRules": [], - - "requireSemicolons": true, - - "disallowMultipleSpaces": true, - - "disallowIdentifierNames": [], - - "requireCurlyBraces": { - "allExcept": [], - "keywords": ["if", "else", "for", "while", "do", "try", "catch"] - }, - - "requireSpaceAfterKeywords": ["if", "else", "for", "while", "do", "switch", "return", "try", "catch", "function"], - - "disallowSpaceAfterKeywords": [], - - "disallowSpaceBeforeComma": true, - "disallowSpaceAfterComma": false, - "disallowSpaceBeforeSemicolon": true, - - "disallowNodeTypes": [ - "DebuggerStatement", - "ForInStatement", - "LabeledStatement", - "SwitchCase", - "SwitchStatement", - "WithStatement" - ], - - "requireObjectKeysOnNewLine": { "allExcept": ["sameLine"] }, - - "requireSpacesInAnonymousFunctionExpression": { "beforeOpeningRoundBrace": true, "beforeOpeningCurlyBrace": true }, - "requireSpacesInNamedFunctionExpression": { "beforeOpeningCurlyBrace": true }, - "disallowSpacesInNamedFunctionExpression": { "beforeOpeningRoundBrace": true }, - "requireSpacesInFunctionDeclaration": { "beforeOpeningCurlyBrace": true }, - "disallowSpacesInFunctionDeclaration": { "beforeOpeningRoundBrace": true }, - - "requireSpaceBetweenArguments": true, - - "disallowSpacesInsideParentheses": true, - - "disallowSpacesInsideArrayBrackets": true, - - "disallowQuotedKeysInObjects": { "allExcept": ["reserved"] }, - - "disallowSpaceAfterObjectKeys": true, - - "requireCommaBeforeLineBreak": true, - - "disallowSpaceAfterPrefixUnaryOperators": ["++", "--", "+", "-", "~", "!"], - "requireSpaceAfterPrefixUnaryOperators": [], - - "disallowSpaceBeforePostfixUnaryOperators": ["++", "--"], - "requireSpaceBeforePostfixUnaryOperators": [], - - "disallowSpaceBeforeBinaryOperators": [], - "requireSpaceBeforeBinaryOperators": ["+", "-", "/", "*", "=", "==", "===", "!=", "!=="], - - "requireSpaceAfterBinaryOperators": ["+", "-", "/", "*", "=", "==", "===", "!=", "!=="], - "disallowSpaceAfterBinaryOperators": [], - - "disallowImplicitTypeConversion": ["binary", "string"], - - "disallowKeywords": ["with", "eval"], - - "requireKeywordsOnNewLine": [], - "disallowKeywordsOnNewLine": ["else"], - - "requireLineFeedAtFileEnd": true, - - "disallowTrailingWhitespace": true, - - "disallowTrailingComma": true, - - "excludeFiles": ["node_modules/**", "vendor/**"], - - "disallowMultipleLineStrings": true, - - "requireDotNotation": { "allExcept": ["keywords"] }, - - "requireParenthesesAroundIIFE": true, - - "validateLineBreaks": "LF", - - "validateQuoteMarks": { - "escape": true, - "mark": "'" - }, - - "disallowOperatorBeforeLineBreak": [], - - "requireSpaceBeforeKeywords": [ - "do", - "for", - "if", - "else", - "switch", - "case", - "try", - "catch", - "finally", - "while", - "with", - "return" - ], - - "validateAlignedFunctionParameters": { - "lineBreakAfterOpeningBraces": true, - "lineBreakBeforeClosingBraces": true - }, - - "requirePaddingNewLinesBeforeExport": true, - - "validateNewlineAfterArrayElements": { - "maximum": 12 - }, - - "requirePaddingNewLinesAfterUseStrict": true, - - "disallowArrowFunctions": true, - - "disallowMultiLineTernary": true, - - "validateOrderInObjectKeys": false, - - "disallowIdenticalDestructuringNames": true, - - "disallowNestedTernaries": { "maxLevel": 1 }, - - "requireSpaceAfterComma": { "allExcept": ["trailing"] }, - "requireAlignedMultilineParams": false, - - "requireSpacesInGenerator": { - "afterStar": true - }, - - "disallowSpacesInGenerator": { - "beforeStar": true - }, - - "disallowVar": false, - - "requireArrayDestructuring": false, - - "requireEnhancedObjectLiterals": false, - - "requireObjectDestructuring": false, - - "requireEarlyReturn": false, - - "requireCapitalizedConstructorsNew": { - "allExcept": ["Function", "String", "Object", "Symbol", "Number", "Date", "RegExp", "Error", "Boolean", "Array", "GetMethod"] - }, - - "requireImportAlphabetized": false, - - "requireSpaceBeforeObjectValues": true, - "requireSpaceBeforeDestructuredValues": true, - - "disallowSpacesInsideTemplateStringPlaceholders": true, - - "disallowArrayDestructuringReturn": false, - - "requireNewlineBeforeSingleStatementsInIf": false, - - "disallowUnusedVariables": true, - - "requireSpacesInsideImportedObjectBraces": true, - - "requireUseStrict": true -} - diff --git a/scripts/2.5/node_modules/es-to-primitive/.travis.yml b/scripts/2.5/node_modules/es-to-primitive/.travis.yml deleted file mode 100644 index c9ee1ece..00000000 --- a/scripts/2.5/node_modules/es-to-primitive/.travis.yml +++ /dev/null @@ -1,243 +0,0 @@ -language: node_js -cache: - directories: - - "$(nvm cache dir)" -os: - - linux -node_js: - - "10.11" - - "9.11" - - "8.12" - - "7.10" - - "6.14" - - "5.12" - - "4.9" - - "iojs-v3.3" - - "iojs-v2.5" - - "iojs-v1.8" - - "0.12" - - "0.11" - - "0.10" - - "0.8" - - "0.6" -before_install: - - 'case "${TRAVIS_NODE_VERSION}" in 0.*) export NPM_CONFIG_STRICT_SSL=false ;; esac' - - 'nvm install-latest-npm' -install: - - 'if [ "${TRAVIS_NODE_VERSION}" = "0.6" ] || [ "${TRAVIS_NODE_VERSION}" = "0.9" ]; then nvm install --latest-npm 0.8 && npm install && nvm use "${TRAVIS_NODE_VERSION}"; else npm install; fi;' -script: - - 'if [ -n "${PRETEST-}" ]; then npm run pretest ; fi' - - 'if [ -n "${POSTTEST-}" ]; then npm run posttest ; fi' - - 'if [ -n "${COVERAGE-}" ]; then npm run coverage ; fi' - - 'if [ -n "${TEST-}" ]; then npm run tests-only ; fi' -sudo: false -env: - - TEST=true -matrix: - fast_finish: true - include: - - node_js: "lts/*" - env: PRETEST=true - - node_js: "lts/*" - env: POSTTEST=true - - node_js: "4" - env: COVERAGE=true - - node_js: "10.10" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.10" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.11" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.10" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.13" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.12" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.11" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.10" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.11" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.10" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v3.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v3.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v3.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "0.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "0.4" - env: TEST=true ALLOW_FAILURE=true - allow_failures: - - os: osx - - env: TEST=true ALLOW_FAILURE=true - - env: COVERAGE=true - - node_js: "0.6" diff --git a/scripts/2.5/node_modules/es-to-primitive/CHANGELOG.md b/scripts/2.5/node_modules/es-to-primitive/CHANGELOG.md deleted file mode 100644 index 96298696..00000000 --- a/scripts/2.5/node_modules/es-to-primitive/CHANGELOG.md +++ /dev/null @@ -1,38 +0,0 @@ -1.2.0 / 2018-09-27 -================= - * [New] create ES2015 entry point/property, to replace ES6 - * [Fix] Ensure optional arguments are not part of the length (#29) - * [Deps] update `is-callable` - * [Dev Deps] update `tape`, `jscs`, `nsp`, `eslint`, `@ljharb/eslint-config`, `semver`, `object-inspect`, `replace` - * [Tests] avoid util.inspect bug with `new Date(NaN)` on node v6.0 and v6.1. - * [Tests] up to `node` `v10.11`, `v9.11`, `v8.12`, `v6.14`, `v4.9` - -1.1.1 / 2016-01-03 -================= - * [Fix: ES5] fix coercion logic: ES5’s ToPrimitive does not coerce any primitive value, regardless of hint (#2) - -1.1.0 / 2015-12-27 -================= - * [New] add `Symbol.toPrimitive` support - * [Deps] update `is-callable`, `is-date-object` - * [Dev Deps] update `eslint`, `tape`, `semver`, `jscs`, `covert`, `nsp`, `@ljharb/eslint-config` - * [Dev Deps] remove unused deps - * [Tests] up to `node` `v5.3` - * [Tests] fix npm upgrades on older node versions - * [Tests] fix testling - * [Docs] Switch from vb.teelaun.ch to versionbadg.es for the npm version badge SVG - -1.0.1 / 2016-01-03 -================= - * [Fix: ES5] fix coercion logic: ES5’s ToPrimitive does not coerce any primitive value, regardless of hint (#2) - * [Deps] update `is-callable`, `is-date-object` - * [Dev Deps] update `eslint`, `tape`, `semver`, `jscs`, `covert`, `nsp`, `@ljharb/eslint-config` - * [Dev Deps] remove unused deps - * [Tests] up to `node` `v5.3` - * [Tests] fix npm upgrades on older node versions - * [Tests] fix testling - * [Docs] Switch from vb.teelaun.ch to versionbadg.es for the npm version badge SVG - -1.0.0 / 2015-03-19 -================= - * Initial release. diff --git a/scripts/2.5/node_modules/es-to-primitive/LICENSE b/scripts/2.5/node_modules/es-to-primitive/LICENSE deleted file mode 100644 index b43df444..00000000 --- a/scripts/2.5/node_modules/es-to-primitive/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015 Jordan Harband - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - diff --git a/scripts/2.5/node_modules/es-to-primitive/Makefile b/scripts/2.5/node_modules/es-to-primitive/Makefile deleted file mode 100644 index b9e4fe1a..00000000 --- a/scripts/2.5/node_modules/es-to-primitive/Makefile +++ /dev/null @@ -1,61 +0,0 @@ -# Since we rely on paths relative to the makefile location, abort if make isn't being run from there. -$(if $(findstring /,$(MAKEFILE_LIST)),$(error Please only invoke this makefile from the directory it resides in)) - - # The files that need updating when incrementing the version number. -VERSIONED_FILES := *.js *.json README* - - -# Add the local npm packages' bin folder to the PATH, so that `make` can find them, when invoked directly. -# Note that rather than using `$(npm bin)` the 'node_modules/.bin' path component is hard-coded, so that invocation works even from an environment -# where npm is (temporarily) unavailable due to having deactivated an nvm instance loaded into the calling shell in order to avoid interference with tests. -export PATH := $(shell printf '%s' "$$PWD/node_modules/.bin:$$PATH") -UTILS := semver -# Make sure that all required utilities can be located. -UTIL_CHECK := $(or $(shell PATH="$(PATH)" which $(UTILS) >/dev/null && echo 'ok'),$(error Did you forget to run `npm install` after cloning the repo? At least one of the required supporting utilities not found: $(UTILS))) - -# Default target (by virtue of being the first non '.'-prefixed in the file). -.PHONY: _no-target-specified -_no-target-specified: - $(error Please specify the target to make - `make list` shows targets. Alternatively, use `npm test` to run the default tests; `npm run` shows all tests) - -# Lists all targets defined in this makefile. -.PHONY: list -list: - @$(MAKE) -pRrn : -f $(MAKEFILE_LIST) 2>/dev/null | awk -v RS= -F: '/^# File/,/^# Finished Make data base/ {if ($$1 !~ "^[#.]") {print $$1}}' | command grep -v -e '^[^[:alnum:]]' -e '^$@$$command ' | sort - -# All-tests target: invokes the specified test suites for ALL shells defined in $(SHELLS). -.PHONY: test -test: - @npm test - -.PHONY: _ensure-tag -_ensure-tag: -ifndef TAG - $(error Please invoke with `make TAG= release`, where is either an increment specifier (patch, minor, major, prepatch, preminor, premajor, prerelease), or an explicit major.minor.patch version number) -endif - -CHANGELOG_ERROR = $(error No CHANGELOG specified) -.PHONY: _ensure-changelog -_ensure-changelog: - @ (git status -sb --porcelain | command grep -E '^( M|[MA] ) CHANGELOG.md' > /dev/null) || (echo no CHANGELOG.md specified && exit 2) - -# Ensures that the git workspace is clean. -.PHONY: _ensure-clean -_ensure-clean: - @[ -z "$$((git status --porcelain --untracked-files=no || echo err) | command grep -v 'CHANGELOG.md')" ] || { echo "Workspace is not clean; please commit changes first." >&2; exit 2; } - -# Makes a release; invoke with `make TAG= release`. -.PHONY: release -release: _ensure-tag _ensure-changelog _ensure-clean - @old_ver=`git describe --abbrev=0 --tags --match 'v[0-9]*.[0-9]*.[0-9]*'` || { echo "Failed to determine current version." >&2; exit 1; }; old_ver=$${old_ver#v}; \ - new_ver=`echo "$(TAG)" | sed 's/^v//'`; new_ver=$${new_ver:-patch}; \ - if printf "$$new_ver" | command grep -q '^[0-9]'; then \ - semver "$$new_ver" >/dev/null || { echo 'Invalid version number specified: $(TAG) - must be major.minor.patch' >&2; exit 2; }; \ - semver -r "> $$old_ver" "$$new_ver" >/dev/null || { echo 'Invalid version number specified: $(TAG) - must be HIGHER than current one.' >&2; exit 2; } \ - else \ - new_ver=`semver -i "$$new_ver" "$$old_ver"` || { echo 'Invalid version-increment specifier: $(TAG)' >&2; exit 2; } \ - fi; \ - printf "=== Bumping version **$$old_ver** to **$$new_ver** before committing and tagging:\n=== TYPE 'proceed' TO PROCEED, anything else to abort: " && read response && [ "$$response" = 'proceed' ] || { echo 'Aborted.' >&2; exit 2; }; \ - replace "$$old_ver" "$$new_ver" -- $(VERSIONED_FILES) && \ - git commit -m "v$$new_ver" $(VERSIONED_FILES) CHANGELOG.md && \ - git tag -a -m "v$$new_ver" "v$$new_ver" diff --git a/scripts/2.5/node_modules/es-to-primitive/README.md b/scripts/2.5/node_modules/es-to-primitive/README.md deleted file mode 100644 index 1831ecf3..00000000 --- a/scripts/2.5/node_modules/es-to-primitive/README.md +++ /dev/null @@ -1,51 +0,0 @@ -# es-to-primitive [![Version Badge][npm-version-svg]][package-url] - -[![Build Status][travis-svg]][travis-url] -[![dependency status][deps-svg]][deps-url] -[![dev dependency status][dev-deps-svg]][dev-deps-url] -[![License][license-image]][license-url] -[![Downloads][downloads-image]][downloads-url] - -[![npm badge][npm-badge-png]][package-url] - -ECMAScript “ToPrimitive” algorithm. Provides ES5 and ES2015 versions. -When different versions of the spec conflict, the default export will be the latest version of the abstract operation. -Alternative versions will also be available under an `es5`/`es2015` exported property if you require a specific version. - -## Example - -```js -var toPrimitive = require('es-to-primitive'); -var assert = require('assert'); - -assert(toPrimitive(function () {}) === String(function () {})); - -var date = new Date(); -assert(toPrimitive(date) === String(date)); - -assert(toPrimitive({ valueOf: function () { return 3; } }) === 3); - -assert(toPrimitive(['a', 'b', 3]) === String(['a', 'b', 3])); - -var sym = Symbol(); -assert(toPrimitive(Object(sym)) === sym); -``` - -## Tests -Simply clone the repo, `npm install`, and run `npm test` - -[package-url]: https://npmjs.org/package/es-to-primitive -[npm-version-svg]: http://versionbadg.es/ljharb/es-to-primitive.svg -[travis-svg]: https://travis-ci.org/ljharb/es-to-primitive.svg -[travis-url]: https://travis-ci.org/ljharb/es-to-primitive -[deps-svg]: https://david-dm.org/ljharb/es-to-primitive.svg -[deps-url]: https://david-dm.org/ljharb/es-to-primitive -[dev-deps-svg]: https://david-dm.org/ljharb/es-to-primitive/dev-status.svg -[dev-deps-url]: https://david-dm.org/ljharb/es-to-primitive#info=devDependencies -[testling-svg]: https://ci.testling.com/ljharb/es-to-primitive.png -[testling-url]: https://ci.testling.com/ljharb/es-to-primitive -[npm-badge-png]: https://nodei.co/npm/es-to-primitive.png?downloads=true&stars=true -[license-image]: http://img.shields.io/npm/l/es-to-primitive.svg -[license-url]: LICENSE -[downloads-image]: http://img.shields.io/npm/dm/es-to-primitive.svg -[downloads-url]: http://npm-stat.com/charts.html?package=es-to-primitive diff --git a/scripts/2.5/node_modules/es-to-primitive/es2015.js b/scripts/2.5/node_modules/es-to-primitive/es2015.js deleted file mode 100644 index 4a11a346..00000000 --- a/scripts/2.5/node_modules/es-to-primitive/es2015.js +++ /dev/null @@ -1,75 +0,0 @@ -'use strict'; - -var hasSymbols = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol'; - -var isPrimitive = require('./helpers/isPrimitive'); -var isCallable = require('is-callable'); -var isDate = require('is-date-object'); -var isSymbol = require('is-symbol'); - -var ordinaryToPrimitive = function OrdinaryToPrimitive(O, hint) { - if (typeof O === 'undefined' || O === null) { - throw new TypeError('Cannot call method on ' + O); - } - if (typeof hint !== 'string' || (hint !== 'number' && hint !== 'string')) { - throw new TypeError('hint must be "string" or "number"'); - } - var methodNames = hint === 'string' ? ['toString', 'valueOf'] : ['valueOf', 'toString']; - var method, result, i; - for (i = 0; i < methodNames.length; ++i) { - method = O[methodNames[i]]; - if (isCallable(method)) { - result = method.call(O); - if (isPrimitive(result)) { - return result; - } - } - } - throw new TypeError('No default value'); -}; - -var GetMethod = function GetMethod(O, P) { - var func = O[P]; - if (func !== null && typeof func !== 'undefined') { - if (!isCallable(func)) { - throw new TypeError(func + ' returned for property ' + P + ' of object ' + O + ' is not a function'); - } - return func; - } - return void 0; -}; - -// http://www.ecma-international.org/ecma-262/6.0/#sec-toprimitive -module.exports = function ToPrimitive(input) { - if (isPrimitive(input)) { - return input; - } - var hint = 'default'; - if (arguments.length > 1) { - if (arguments[1] === String) { - hint = 'string'; - } else if (arguments[1] === Number) { - hint = 'number'; - } - } - - var exoticToPrim; - if (hasSymbols) { - if (Symbol.toPrimitive) { - exoticToPrim = GetMethod(input, Symbol.toPrimitive); - } else if (isSymbol(input)) { - exoticToPrim = Symbol.prototype.valueOf; - } - } - if (typeof exoticToPrim !== 'undefined') { - var result = exoticToPrim.call(input, hint); - if (isPrimitive(result)) { - return result; - } - throw new TypeError('unable to convert exotic object to primitive'); - } - if (hint === 'default' && (isDate(input) || isSymbol(input))) { - hint = 'string'; - } - return ordinaryToPrimitive(input, hint === 'default' ? 'number' : hint); -}; diff --git a/scripts/2.5/node_modules/es-to-primitive/es5.js b/scripts/2.5/node_modules/es-to-primitive/es5.js deleted file mode 100644 index 602aa362..00000000 --- a/scripts/2.5/node_modules/es-to-primitive/es5.js +++ /dev/null @@ -1,45 +0,0 @@ -'use strict'; - -var toStr = Object.prototype.toString; - -var isPrimitive = require('./helpers/isPrimitive'); - -var isCallable = require('is-callable'); - -// http://ecma-international.org/ecma-262/5.1/#sec-8.12.8 -var ES5internalSlots = { - '[[DefaultValue]]': function (O) { - var actualHint; - if (arguments.length > 1) { - actualHint = arguments[1]; - } else { - actualHint = toStr.call(O) === '[object Date]' ? String : Number; - } - - if (actualHint === String || actualHint === Number) { - var methods = actualHint === String ? ['toString', 'valueOf'] : ['valueOf', 'toString']; - var value, i; - for (i = 0; i < methods.length; ++i) { - if (isCallable(O[methods[i]])) { - value = O[methods[i]](); - if (isPrimitive(value)) { - return value; - } - } - } - throw new TypeError('No default value'); - } - throw new TypeError('invalid [[DefaultValue]] hint supplied'); - } -}; - -// http://ecma-international.org/ecma-262/5.1/#sec-9.1 -module.exports = function ToPrimitive(input) { - if (isPrimitive(input)) { - return input; - } - if (arguments.length > 1) { - return ES5internalSlots['[[DefaultValue]]'](input, arguments[1]); - } - return ES5internalSlots['[[DefaultValue]]'](input); -}; diff --git a/scripts/2.5/node_modules/es-to-primitive/es6.js b/scripts/2.5/node_modules/es-to-primitive/es6.js deleted file mode 100644 index 2d1f4dc9..00000000 --- a/scripts/2.5/node_modules/es-to-primitive/es6.js +++ /dev/null @@ -1,3 +0,0 @@ -'use strict'; - -module.exports = require('./es2015'); diff --git a/scripts/2.5/node_modules/es-to-primitive/helpers/isPrimitive.js b/scripts/2.5/node_modules/es-to-primitive/helpers/isPrimitive.js deleted file mode 100644 index 36691564..00000000 --- a/scripts/2.5/node_modules/es-to-primitive/helpers/isPrimitive.js +++ /dev/null @@ -1,3 +0,0 @@ -module.exports = function isPrimitive(value) { - return value === null || (typeof value !== 'function' && typeof value !== 'object'); -}; diff --git a/scripts/2.5/node_modules/es-to-primitive/index.js b/scripts/2.5/node_modules/es-to-primitive/index.js deleted file mode 100644 index e60d912e..00000000 --- a/scripts/2.5/node_modules/es-to-primitive/index.js +++ /dev/null @@ -1,17 +0,0 @@ -'use strict'; - -var ES5 = require('./es5'); -var ES6 = require('./es6'); -var ES2015 = require('./es2015'); - -if (Object.defineProperty) { - Object.defineProperty(ES2015, 'ES5', { enumerable: false, value: ES5 }); - Object.defineProperty(ES2015, 'ES6', { enumerable: false, value: ES6 }); - Object.defineProperty(ES2015, 'ES2015', { enumerable: false, value: ES2015 }); -} else { - ES6.ES5 = ES5; - ES6.ES6 = ES6; - ES6.ES2015 = ES2015; -} - -module.exports = ES2015; diff --git a/scripts/2.5/node_modules/es-to-primitive/package.json b/scripts/2.5/node_modules/es-to-primitive/package.json deleted file mode 100644 index 73ded945..00000000 --- a/scripts/2.5/node_modules/es-to-primitive/package.json +++ /dev/null @@ -1,113 +0,0 @@ -{ - "_from": "es-to-primitive@^1.2.0", - "_id": "es-to-primitive@1.2.0", - "_inBundle": false, - "_integrity": "sha512-qZryBOJjV//LaxLTV6UC//WewneB3LcXOL9NP++ozKVXsIIIpm/2c13UDiD9Jp2eThsecw9m3jPqDwTyobcdbg==", - "_location": "/es-to-primitive", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "es-to-primitive@^1.2.0", - "name": "es-to-primitive", - "escapedName": "es-to-primitive", - "rawSpec": "^1.2.0", - "saveSpec": null, - "fetchSpec": "^1.2.0" - }, - "_requiredBy": [ - "/es-abstract" - ], - "_resolved": "https://registry.npmjs.org/es-to-primitive/-/es-to-primitive-1.2.0.tgz", - "_shasum": "edf72478033456e8dda8ef09e00ad9650707f377", - "_spec": "es-to-primitive@^1.2.0", - "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/2.5/node_modules/es-abstract", - "author": { - "name": "Jordan Harband" - }, - "bugs": { - "url": "https://github.com/ljharb/es-to-primitive/issues" - }, - "bundleDependencies": false, - "dependencies": { - "is-callable": "^1.1.4", - "is-date-object": "^1.0.1", - "is-symbol": "^1.0.2" - }, - "deprecated": false, - "description": "ECMAScript “ToPrimitive” algorithm. Provides ES5 and ES2015 versions.", - "devDependencies": { - "@ljharb/eslint-config": "^13.0.0", - "covert": "^1.1.0", - "eslint": "^5.6.0", - "foreach": "^2.0.5", - "function.prototype.name": "^1.1.0", - "jscs": "^3.0.7", - "nsp": "^3.2.1", - "object-inspect": "^1.6.0", - "object-is": "^1.0.1", - "replace": "^1.0.0", - "semver": "^5.5.1", - "tape": "^4.9.1" - }, - "engines": { - "node": ">= 0.4" - }, - "homepage": "https://github.com/ljharb/es-to-primitive#readme", - "keywords": [ - "primitive", - "abstract", - "ecmascript", - "es5", - "es6", - "es2015", - "toPrimitive", - "coerce", - "type", - "object", - "string", - "number", - "boolean", - "symbol", - "null", - "undefined" - ], - "license": "MIT", - "main": "index.js", - "name": "es-to-primitive", - "repository": { - "type": "git", - "url": "git://github.com/ljharb/es-to-primitive.git" - }, - "scripts": { - "coverage": "covert test/*.js", - "coverage-quiet": "covert test/*.js --quiet", - "eslint": "eslint test/*.js *.js", - "jscs": "jscs test/*.js *.js", - "lint": "npm run --silent jscs && npm run --silent eslint", - "posttest": "npm run --silent security", - "pretest": "npm run --silent lint", - "security": "nsp check", - "test": "npm run --silent tests-only", - "tests-only": "node --es-staging test" - }, - "testling": { - "files": "test", - "browsers": [ - "iexplore/6.0..latest", - "firefox/3.0..6.0", - "firefox/15.0..latest", - "firefox/nightly", - "chrome/4.0..10.0", - "chrome/20.0..latest", - "chrome/canary", - "opera/10.0..latest", - "opera/next", - "safari/4.0..latest", - "ipad/6.0..latest", - "iphone/6.0..latest", - "android-browser/4.2" - ] - }, - "version": "1.2.0" -} diff --git a/scripts/2.5/node_modules/es-to-primitive/test/.eslintrc b/scripts/2.5/node_modules/es-to-primitive/test/.eslintrc deleted file mode 100644 index 9beb88c7..00000000 --- a/scripts/2.5/node_modules/es-to-primitive/test/.eslintrc +++ /dev/null @@ -1,9 +0,0 @@ -{ - "rules": { - "array-bracket-newline": 0, - "array-element-newline": 0, - "max-statements-per-line": [2, { "max": 3 }], - "no-magic-numbers": [0], - "sort-keys": [0] - } -} diff --git a/scripts/2.5/node_modules/es-to-primitive/test/es2015.js b/scripts/2.5/node_modules/es-to-primitive/test/es2015.js deleted file mode 100644 index 80f4083d..00000000 --- a/scripts/2.5/node_modules/es-to-primitive/test/es2015.js +++ /dev/null @@ -1,151 +0,0 @@ -'use strict'; - -var test = require('tape'); -var toPrimitive = require('../es2015'); -var is = require('object-is'); -var forEach = require('foreach'); -var functionName = require('function.prototype.name'); -var debug = require('object-inspect'); - -var hasSymbols = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol'; -var hasSymbolToPrimitive = hasSymbols && typeof Symbol.toPrimitive === 'symbol'; - -test('function properties', function (t) { - t.equal(toPrimitive.length, 1, 'length is 1'); - t.equal(functionName(toPrimitive), 'ToPrimitive', 'name is ToPrimitive'); - - t.end(); -}); - -var primitives = [null, undefined, true, false, 0, -0, 42, NaN, Infinity, -Infinity, '', 'abc']; - -test('primitives', function (t) { - forEach(primitives, function (i) { - t.ok(is(toPrimitive(i), i), 'toPrimitive(' + debug(i) + ') returns the same value'); - t.ok(is(toPrimitive(i, String), i), 'toPrimitive(' + debug(i) + ', String) returns the same value'); - t.ok(is(toPrimitive(i, Number), i), 'toPrimitive(' + debug(i) + ', Number) returns the same value'); - }); - t.end(); -}); - -test('Symbols', { skip: !hasSymbols }, function (t) { - var symbols = [ - Symbol('foo'), - Symbol.iterator, - Symbol['for']('foo') // eslint-disable-line no-restricted-properties - ]; - forEach(symbols, function (sym) { - t.equal(toPrimitive(sym), sym, 'toPrimitive(' + debug(sym) + ') returns the same value'); - t.equal(toPrimitive(sym, String), sym, 'toPrimitive(' + debug(sym) + ', String) returns the same value'); - t.equal(toPrimitive(sym, Number), sym, 'toPrimitive(' + debug(sym) + ', Number) returns the same value'); - }); - - var primitiveSym = Symbol('primitiveSym'); - var objectSym = Object(primitiveSym); - t.equal(toPrimitive(objectSym), primitiveSym, 'toPrimitive(' + debug(objectSym) + ') returns ' + debug(primitiveSym)); - t.equal(toPrimitive(objectSym, String), primitiveSym, 'toPrimitive(' + debug(objectSym) + ', String) returns ' + debug(primitiveSym)); - t.equal(toPrimitive(objectSym, Number), primitiveSym, 'toPrimitive(' + debug(objectSym) + ', Number) returns ' + debug(primitiveSym)); - t.end(); -}); - -test('Arrays', function (t) { - var arrays = [[], ['a', 'b'], [1, 2]]; - forEach(arrays, function (arr) { - t.equal(toPrimitive(arr), String(arr), 'toPrimitive(' + debug(arr) + ') returns the string version of the array'); - t.equal(toPrimitive(arr, String), String(arr), 'toPrimitive(' + debug(arr) + ') returns the string version of the array'); - t.equal(toPrimitive(arr, Number), String(arr), 'toPrimitive(' + debug(arr) + ') returns the string version of the array'); - }); - t.end(); -}); - -test('Dates', function (t) { - var dates = [new Date(), new Date(0), new Date(NaN)]; - forEach(dates, function (date) { - t.equal(toPrimitive(date), String(date), 'toPrimitive(' + debug(date) + ') returns the string version of the date'); - t.equal(toPrimitive(date, String), String(date), 'toPrimitive(' + debug(date) + ') returns the string version of the date'); - t.ok(is(toPrimitive(date, Number), Number(date)), 'toPrimitive(' + debug(date) + ') returns the number version of the date'); - }); - t.end(); -}); - -var coercibleObject = { valueOf: function () { return 3; }, toString: function () { return 42; } }; -var valueOfOnlyObject = { valueOf: function () { return 4; }, toString: function () { return {}; } }; -var toStringOnlyObject = { valueOf: function () { return {}; }, toString: function () { return 7; } }; -var coercibleFnObject = { - valueOf: function () { return function valueOfFn() {}; }, - toString: function () { return 42; } -}; -var uncoercibleObject = { valueOf: function () { return {}; }, toString: function () { return {}; } }; -var uncoercibleFnObject = { - valueOf: function () { return function valueOfFn() {}; }, - toString: function () { return function toStrFn() {}; } -}; - -test('Objects', function (t) { - t.equal(toPrimitive(coercibleObject), coercibleObject.valueOf(), 'coercibleObject with no hint coerces to valueOf'); - t.equal(toPrimitive(coercibleObject, Number), coercibleObject.valueOf(), 'coercibleObject with hint Number coerces to valueOf'); - t.equal(toPrimitive(coercibleObject, String), coercibleObject.toString(), 'coercibleObject with hint String coerces to non-stringified toString'); - - t.equal(toPrimitive(coercibleFnObject), coercibleFnObject.toString(), 'coercibleFnObject coerces to non-stringified toString'); - t.equal(toPrimitive(coercibleFnObject, Number), coercibleFnObject.toString(), 'coercibleFnObject with hint Number coerces to non-stringified toString'); - t.equal(toPrimitive(coercibleFnObject, String), coercibleFnObject.toString(), 'coercibleFnObject with hint String coerces to non-stringified toString'); - - t.equal(toPrimitive({}), '[object Object]', '{} with no hint coerces to Object#toString'); - t.equal(toPrimitive({}, Number), '[object Object]', '{} with hint Number coerces to Object#toString'); - t.equal(toPrimitive({}, String), '[object Object]', '{} with hint String coerces to Object#toString'); - - t.equal(toPrimitive(toStringOnlyObject), toStringOnlyObject.toString(), 'toStringOnlyObject returns non-stringified toString'); - t.equal(toPrimitive(toStringOnlyObject, Number), toStringOnlyObject.toString(), 'toStringOnlyObject with hint Number returns non-stringified toString'); - t.equal(toPrimitive(toStringOnlyObject, String), toStringOnlyObject.toString(), 'toStringOnlyObject with hint String returns non-stringified toString'); - - t.equal(toPrimitive(valueOfOnlyObject), valueOfOnlyObject.valueOf(), 'valueOfOnlyObject returns valueOf'); - t.equal(toPrimitive(valueOfOnlyObject, Number), valueOfOnlyObject.valueOf(), 'valueOfOnlyObject with hint Number returns valueOf'); - t.equal(toPrimitive(valueOfOnlyObject, String), valueOfOnlyObject.valueOf(), 'valueOfOnlyObject with hint String returns non-stringified valueOf'); - - t.test('Symbol.toPrimitive', { skip: !hasSymbolToPrimitive }, function (st) { - var overriddenObject = { toString: st.fail, valueOf: st.fail }; - overriddenObject[Symbol.toPrimitive] = function (hint) { return String(hint); }; - - st.equal(toPrimitive(overriddenObject), 'default', 'object with Symbol.toPrimitive + no hint invokes that'); - st.equal(toPrimitive(overriddenObject, Number), 'number', 'object with Symbol.toPrimitive + hint Number invokes that'); - st.equal(toPrimitive(overriddenObject, String), 'string', 'object with Symbol.toPrimitive + hint String invokes that'); - - var nullToPrimitive = { toString: coercibleObject.toString, valueOf: coercibleObject.valueOf }; - nullToPrimitive[Symbol.toPrimitive] = null; - st.equal(toPrimitive(nullToPrimitive), toPrimitive(coercibleObject), 'object with no hint + null Symbol.toPrimitive ignores it'); - st.equal(toPrimitive(nullToPrimitive, Number), toPrimitive(coercibleObject, Number), 'object with hint Number + null Symbol.toPrimitive ignores it'); - st.equal(toPrimitive(nullToPrimitive, String), toPrimitive(coercibleObject, String), 'object with hint String + null Symbol.toPrimitive ignores it'); - - st.test('exceptions', function (sst) { - var nonFunctionToPrimitive = { toString: sst.fail, valueOf: sst.fail }; - nonFunctionToPrimitive[Symbol.toPrimitive] = {}; - sst['throws'](toPrimitive.bind(null, nonFunctionToPrimitive), TypeError, 'Symbol.toPrimitive returning a non-function throws'); - - var uncoercibleToPrimitive = { toString: sst.fail, valueOf: sst.fail }; - uncoercibleToPrimitive[Symbol.toPrimitive] = function (hint) { - return { toString: function () { return hint; } }; - }; - sst['throws'](toPrimitive.bind(null, uncoercibleToPrimitive), TypeError, 'Symbol.toPrimitive returning an object throws'); - - var throwingToPrimitive = { toString: sst.fail, valueOf: sst.fail }; - throwingToPrimitive[Symbol.toPrimitive] = function (hint) { throw new RangeError(hint); }; - sst['throws'](toPrimitive.bind(null, throwingToPrimitive), RangeError, 'Symbol.toPrimitive throwing throws'); - - sst.end(); - }); - - st.end(); - }); - - t.test('exceptions', function (st) { - st['throws'](toPrimitive.bind(null, uncoercibleObject), TypeError, 'uncoercibleObject throws a TypeError'); - st['throws'](toPrimitive.bind(null, uncoercibleObject, Number), TypeError, 'uncoercibleObject with hint Number throws a TypeError'); - st['throws'](toPrimitive.bind(null, uncoercibleObject, String), TypeError, 'uncoercibleObject with hint String throws a TypeError'); - - st['throws'](toPrimitive.bind(null, uncoercibleFnObject), TypeError, 'uncoercibleFnObject throws a TypeError'); - st['throws'](toPrimitive.bind(null, uncoercibleFnObject, Number), TypeError, 'uncoercibleFnObject with hint Number throws a TypeError'); - st['throws'](toPrimitive.bind(null, uncoercibleFnObject, String), TypeError, 'uncoercibleFnObject with hint String throws a TypeError'); - st.end(); - }); - t.end(); -}); diff --git a/scripts/2.5/node_modules/es-to-primitive/test/es5.js b/scripts/2.5/node_modules/es-to-primitive/test/es5.js deleted file mode 100644 index 8b80ff5b..00000000 --- a/scripts/2.5/node_modules/es-to-primitive/test/es5.js +++ /dev/null @@ -1,94 +0,0 @@ -'use strict'; - -var test = require('tape'); -var toPrimitive = require('../es5'); -var is = require('object-is'); -var forEach = require('foreach'); -var functionName = require('function.prototype.name'); -var debug = require('object-inspect'); - -test('function properties', function (t) { - t.equal(toPrimitive.length, 1, 'length is 1'); - t.equal(functionName(toPrimitive), 'ToPrimitive', 'name is ToPrimitive'); - - t.end(); -}); - -var primitives = [null, undefined, true, false, 0, -0, 42, NaN, Infinity, -Infinity, '', 'abc']; - -test('primitives', function (t) { - forEach(primitives, function (i) { - t.ok(is(toPrimitive(i), i), 'toPrimitive(' + debug(i) + ') returns the same value'); - t.ok(is(toPrimitive(i, String), i), 'toPrimitive(' + debug(i) + ', String) returns the same value'); - t.ok(is(toPrimitive(i, Number), i), 'toPrimitive(' + debug(i) + ', Number) returns the same value'); - }); - t.end(); -}); - -test('Arrays', function (t) { - var arrays = [[], ['a', 'b'], [1, 2]]; - forEach(arrays, function (arr) { - t.ok(is(toPrimitive(arr), arr.toString()), 'toPrimitive(' + debug(arr) + ') returns toString of the array'); - t.equal(toPrimitive(arr, String), arr.toString(), 'toPrimitive(' + debug(arr) + ') returns toString of the array'); - t.ok(is(toPrimitive(arr, Number), arr.toString()), 'toPrimitive(' + debug(arr) + ') returns toString of the array'); - }); - t.end(); -}); - -test('Dates', function (t) { - var dates = [new Date(), new Date(0), new Date(NaN)]; - forEach(dates, function (date) { - t.equal(toPrimitive(date), date.toString(), 'toPrimitive(' + debug(date) + ') returns toString of the date'); - t.equal(toPrimitive(date, String), date.toString(), 'toPrimitive(' + debug(date) + ') returns toString of the date'); - t.ok(is(toPrimitive(date, Number), date.valueOf()), 'toPrimitive(' + debug(date) + ') returns valueOf of the date'); - }); - t.end(); -}); - -var coercibleObject = { valueOf: function () { return 3; }, toString: function () { return 42; } }; -var valueOfOnlyObject = { valueOf: function () { return 4; }, toString: function () { return {}; } }; -var toStringOnlyObject = { valueOf: function () { return {}; }, toString: function () { return 7; } }; -var coercibleFnObject = { - valueOf: function () { return function valueOfFn() {}; }, - toString: function () { return 42; } -}; -var uncoercibleObject = { valueOf: function () { return {}; }, toString: function () { return {}; } }; -var uncoercibleFnObject = { - valueOf: function () { return function valueOfFn() {}; }, - toString: function () { return function toStrFn() {}; } -}; - -test('Objects', function (t) { - t.equal(toPrimitive(coercibleObject), coercibleObject.valueOf(), 'coercibleObject with no hint coerces to valueOf'); - t.equal(toPrimitive(coercibleObject, String), coercibleObject.toString(), 'coercibleObject with hint String coerces to toString'); - t.equal(toPrimitive(coercibleObject, Number), coercibleObject.valueOf(), 'coercibleObject with hint Number coerces to valueOf'); - - t.equal(toPrimitive(coercibleFnObject), coercibleFnObject.toString(), 'coercibleFnObject coerces to toString'); - t.equal(toPrimitive(coercibleFnObject, String), coercibleFnObject.toString(), 'coercibleFnObject with hint String coerces to toString'); - t.equal(toPrimitive(coercibleFnObject, Number), coercibleFnObject.toString(), 'coercibleFnObject with hint Number coerces to toString'); - - t.ok(is(toPrimitive({}), '[object Object]'), '{} with no hint coerces to Object#toString'); - t.equal(toPrimitive({}, String), '[object Object]', '{} with hint String coerces to Object#toString'); - t.ok(is(toPrimitive({}, Number), '[object Object]'), '{} with hint Number coerces to Object#toString'); - - t.equal(toPrimitive(toStringOnlyObject), toStringOnlyObject.toString(), 'toStringOnlyObject returns toString'); - t.equal(toPrimitive(toStringOnlyObject, String), toStringOnlyObject.toString(), 'toStringOnlyObject with hint String returns toString'); - t.equal(toPrimitive(toStringOnlyObject, Number), toStringOnlyObject.toString(), 'toStringOnlyObject with hint Number returns toString'); - - t.equal(toPrimitive(valueOfOnlyObject), valueOfOnlyObject.valueOf(), 'valueOfOnlyObject returns valueOf'); - t.equal(toPrimitive(valueOfOnlyObject, String), valueOfOnlyObject.valueOf(), 'valueOfOnlyObject with hint String returns valueOf'); - t.equal(toPrimitive(valueOfOnlyObject, Number), valueOfOnlyObject.valueOf(), 'valueOfOnlyObject with hint Number returns valueOf'); - - t.test('exceptions', function (st) { - st['throws'](toPrimitive.bind(null, uncoercibleObject), TypeError, 'uncoercibleObject throws a TypeError'); - st['throws'](toPrimitive.bind(null, uncoercibleObject, String), TypeError, 'uncoercibleObject with hint String throws a TypeError'); - st['throws'](toPrimitive.bind(null, uncoercibleObject, Number), TypeError, 'uncoercibleObject with hint Number throws a TypeError'); - - st['throws'](toPrimitive.bind(null, uncoercibleFnObject), TypeError, 'uncoercibleFnObject throws a TypeError'); - st['throws'](toPrimitive.bind(null, uncoercibleFnObject, String), TypeError, 'uncoercibleFnObject with hint String throws a TypeError'); - st['throws'](toPrimitive.bind(null, uncoercibleFnObject, Number), TypeError, 'uncoercibleFnObject with hint Number throws a TypeError'); - st.end(); - }); - - t.end(); -}); diff --git a/scripts/2.5/node_modules/es-to-primitive/test/es6.js b/scripts/2.5/node_modules/es-to-primitive/test/es6.js deleted file mode 100644 index c6df63fb..00000000 --- a/scripts/2.5/node_modules/es-to-primitive/test/es6.js +++ /dev/null @@ -1,151 +0,0 @@ -'use strict'; - -var test = require('tape'); -var toPrimitive = require('../es6'); -var is = require('object-is'); -var forEach = require('foreach'); -var functionName = require('function.prototype.name'); -var debug = require('object-inspect'); - -var hasSymbols = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol'; -var hasSymbolToPrimitive = hasSymbols && typeof Symbol.toPrimitive === 'symbol'; - -test('function properties', function (t) { - t.equal(toPrimitive.length, 1, 'length is 1'); - t.equal(functionName(toPrimitive), 'ToPrimitive', 'name is ToPrimitive'); - - t.end(); -}); - -var primitives = [null, undefined, true, false, 0, -0, 42, NaN, Infinity, -Infinity, '', 'abc']; - -test('primitives', function (t) { - forEach(primitives, function (i) { - t.ok(is(toPrimitive(i), i), 'toPrimitive(' + debug(i) + ') returns the same value'); - t.ok(is(toPrimitive(i, String), i), 'toPrimitive(' + debug(i) + ', String) returns the same value'); - t.ok(is(toPrimitive(i, Number), i), 'toPrimitive(' + debug(i) + ', Number) returns the same value'); - }); - t.end(); -}); - -test('Symbols', { skip: !hasSymbols }, function (t) { - var symbols = [ - Symbol('foo'), - Symbol.iterator, - Symbol['for']('foo') // eslint-disable-line no-restricted-properties - ]; - forEach(symbols, function (sym) { - t.equal(toPrimitive(sym), sym, 'toPrimitive(' + debug(sym) + ') returns the same value'); - t.equal(toPrimitive(sym, String), sym, 'toPrimitive(' + debug(sym) + ', String) returns the same value'); - t.equal(toPrimitive(sym, Number), sym, 'toPrimitive(' + debug(sym) + ', Number) returns the same value'); - }); - - var primitiveSym = Symbol('primitiveSym'); - var objectSym = Object(primitiveSym); - t.equal(toPrimitive(objectSym), primitiveSym, 'toPrimitive(' + debug(objectSym) + ') returns ' + debug(primitiveSym)); - t.equal(toPrimitive(objectSym, String), primitiveSym, 'toPrimitive(' + debug(objectSym) + ', String) returns ' + debug(primitiveSym)); - t.equal(toPrimitive(objectSym, Number), primitiveSym, 'toPrimitive(' + debug(objectSym) + ', Number) returns ' + debug(primitiveSym)); - t.end(); -}); - -test('Arrays', function (t) { - var arrays = [[], ['a', 'b'], [1, 2]]; - forEach(arrays, function (arr) { - t.equal(toPrimitive(arr), String(arr), 'toPrimitive(' + debug(arr) + ') returns the string version of the array'); - t.equal(toPrimitive(arr, String), String(arr), 'toPrimitive(' + debug(arr) + ') returns the string version of the array'); - t.equal(toPrimitive(arr, Number), String(arr), 'toPrimitive(' + debug(arr) + ') returns the string version of the array'); - }); - t.end(); -}); - -test('Dates', function (t) { - var dates = [new Date(), new Date(0), new Date(NaN)]; - forEach(dates, function (date) { - t.equal(toPrimitive(date), String(date), 'toPrimitive(' + debug(date) + ') returns the string version of the date'); - t.equal(toPrimitive(date, String), String(date), 'toPrimitive(' + debug(date) + ') returns the string version of the date'); - t.ok(is(toPrimitive(date, Number), Number(date)), 'toPrimitive(' + debug(date) + ') returns the number version of the date'); - }); - t.end(); -}); - -var coercibleObject = { valueOf: function () { return 3; }, toString: function () { return 42; } }; -var valueOfOnlyObject = { valueOf: function () { return 4; }, toString: function () { return {}; } }; -var toStringOnlyObject = { valueOf: function () { return {}; }, toString: function () { return 7; } }; -var coercibleFnObject = { - valueOf: function () { return function valueOfFn() {}; }, - toString: function () { return 42; } -}; -var uncoercibleObject = { valueOf: function () { return {}; }, toString: function () { return {}; } }; -var uncoercibleFnObject = { - valueOf: function () { return function valueOfFn() {}; }, - toString: function () { return function toStrFn() {}; } -}; - -test('Objects', function (t) { - t.equal(toPrimitive(coercibleObject), coercibleObject.valueOf(), 'coercibleObject with no hint coerces to valueOf'); - t.equal(toPrimitive(coercibleObject, Number), coercibleObject.valueOf(), 'coercibleObject with hint Number coerces to valueOf'); - t.equal(toPrimitive(coercibleObject, String), coercibleObject.toString(), 'coercibleObject with hint String coerces to non-stringified toString'); - - t.equal(toPrimitive(coercibleFnObject), coercibleFnObject.toString(), 'coercibleFnObject coerces to non-stringified toString'); - t.equal(toPrimitive(coercibleFnObject, Number), coercibleFnObject.toString(), 'coercibleFnObject with hint Number coerces to non-stringified toString'); - t.equal(toPrimitive(coercibleFnObject, String), coercibleFnObject.toString(), 'coercibleFnObject with hint String coerces to non-stringified toString'); - - t.equal(toPrimitive({}), '[object Object]', '{} with no hint coerces to Object#toString'); - t.equal(toPrimitive({}, Number), '[object Object]', '{} with hint Number coerces to Object#toString'); - t.equal(toPrimitive({}, String), '[object Object]', '{} with hint String coerces to Object#toString'); - - t.equal(toPrimitive(toStringOnlyObject), toStringOnlyObject.toString(), 'toStringOnlyObject returns non-stringified toString'); - t.equal(toPrimitive(toStringOnlyObject, Number), toStringOnlyObject.toString(), 'toStringOnlyObject with hint Number returns non-stringified toString'); - t.equal(toPrimitive(toStringOnlyObject, String), toStringOnlyObject.toString(), 'toStringOnlyObject with hint String returns non-stringified toString'); - - t.equal(toPrimitive(valueOfOnlyObject), valueOfOnlyObject.valueOf(), 'valueOfOnlyObject returns valueOf'); - t.equal(toPrimitive(valueOfOnlyObject, Number), valueOfOnlyObject.valueOf(), 'valueOfOnlyObject with hint Number returns valueOf'); - t.equal(toPrimitive(valueOfOnlyObject, String), valueOfOnlyObject.valueOf(), 'valueOfOnlyObject with hint String returns non-stringified valueOf'); - - t.test('Symbol.toPrimitive', { skip: !hasSymbolToPrimitive }, function (st) { - var overriddenObject = { toString: st.fail, valueOf: st.fail }; - overriddenObject[Symbol.toPrimitive] = function (hint) { return String(hint); }; - - st.equal(toPrimitive(overriddenObject), 'default', 'object with Symbol.toPrimitive + no hint invokes that'); - st.equal(toPrimitive(overriddenObject, Number), 'number', 'object with Symbol.toPrimitive + hint Number invokes that'); - st.equal(toPrimitive(overriddenObject, String), 'string', 'object with Symbol.toPrimitive + hint String invokes that'); - - var nullToPrimitive = { toString: coercibleObject.toString, valueOf: coercibleObject.valueOf }; - nullToPrimitive[Symbol.toPrimitive] = null; - st.equal(toPrimitive(nullToPrimitive), toPrimitive(coercibleObject), 'object with no hint + null Symbol.toPrimitive ignores it'); - st.equal(toPrimitive(nullToPrimitive, Number), toPrimitive(coercibleObject, Number), 'object with hint Number + null Symbol.toPrimitive ignores it'); - st.equal(toPrimitive(nullToPrimitive, String), toPrimitive(coercibleObject, String), 'object with hint String + null Symbol.toPrimitive ignores it'); - - st.test('exceptions', function (sst) { - var nonFunctionToPrimitive = { toString: sst.fail, valueOf: sst.fail }; - nonFunctionToPrimitive[Symbol.toPrimitive] = {}; - sst['throws'](toPrimitive.bind(null, nonFunctionToPrimitive), TypeError, 'Symbol.toPrimitive returning a non-function throws'); - - var uncoercibleToPrimitive = { toString: sst.fail, valueOf: sst.fail }; - uncoercibleToPrimitive[Symbol.toPrimitive] = function (hint) { - return { toString: function () { return hint; } }; - }; - sst['throws'](toPrimitive.bind(null, uncoercibleToPrimitive), TypeError, 'Symbol.toPrimitive returning an object throws'); - - var throwingToPrimitive = { toString: sst.fail, valueOf: sst.fail }; - throwingToPrimitive[Symbol.toPrimitive] = function (hint) { throw new RangeError(hint); }; - sst['throws'](toPrimitive.bind(null, throwingToPrimitive), RangeError, 'Symbol.toPrimitive throwing throws'); - - sst.end(); - }); - - st.end(); - }); - - t.test('exceptions', function (st) { - st['throws'](toPrimitive.bind(null, uncoercibleObject), TypeError, 'uncoercibleObject throws a TypeError'); - st['throws'](toPrimitive.bind(null, uncoercibleObject, Number), TypeError, 'uncoercibleObject with hint Number throws a TypeError'); - st['throws'](toPrimitive.bind(null, uncoercibleObject, String), TypeError, 'uncoercibleObject with hint String throws a TypeError'); - - st['throws'](toPrimitive.bind(null, uncoercibleFnObject), TypeError, 'uncoercibleFnObject throws a TypeError'); - st['throws'](toPrimitive.bind(null, uncoercibleFnObject, Number), TypeError, 'uncoercibleFnObject with hint Number throws a TypeError'); - st['throws'](toPrimitive.bind(null, uncoercibleFnObject, String), TypeError, 'uncoercibleFnObject with hint String throws a TypeError'); - st.end(); - }); - t.end(); -}); diff --git a/scripts/2.5/node_modules/es-to-primitive/test/index.js b/scripts/2.5/node_modules/es-to-primitive/test/index.js deleted file mode 100644 index ad71f39e..00000000 --- a/scripts/2.5/node_modules/es-to-primitive/test/index.js +++ /dev/null @@ -1,20 +0,0 @@ -'use strict'; - -var toPrimitive = require('../'); -var ES5 = require('../es5'); -var ES6 = require('../es6'); -var ES2015 = require('../es2015'); - -var test = require('tape'); - -test('default export', function (t) { - t.equal(toPrimitive, ES2015, 'default export is ES2015'); - t.equal(toPrimitive.ES5, ES5, 'ES5 property has ES5 method'); - t.equal(toPrimitive.ES6, ES6, 'ES6 property has ES6 method'); - t.equal(toPrimitive.ES2015, ES2015, 'ES2015 property has ES2015 method'); - t.end(); -}); - -require('./es5'); -require('./es6'); -require('./es2015'); diff --git a/scripts/2.5/node_modules/es6-object-assign/LICENSE b/scripts/2.5/node_modules/es6-object-assign/LICENSE deleted file mode 100644 index 3fef2a24..00000000 --- a/scripts/2.5/node_modules/es6-object-assign/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -Copyright (c) 2015-2017 Rubén Norte - -MIT License - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/scripts/2.5/node_modules/es6-object-assign/README.md b/scripts/2.5/node_modules/es6-object-assign/README.md deleted file mode 100644 index 39172998..00000000 --- a/scripts/2.5/node_modules/es6-object-assign/README.md +++ /dev/null @@ -1,96 +0,0 @@ -[![npm](https://img.shields.io/npm/l/es6-object-assign.svg)](https://www.npmjs.org/package/es6-object-assign) -[![npm](https://img.shields.io/npm/v/es6-object-assign.svg)](https://www.npmjs.org/package/es6-object-assign) - -# ES6 Object.assign() - -ECMAScript 2015 (ES2015/ES6) [Object.assign()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) polyfill and [ponyfill](https://ponyfill.com) for ECMAScript 5 environments. - -The main definition of this package has been copied from the polyfill defined in the [Mozilla Developer Network](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign). - -## Installation - -### NPM - -```bash -npm install es6-object-assign -``` - -### Manual download and import - -The package is also available as a UMD module (compatible with AMD, CommonJS and exposing a global variable `ObjectAssign`) in `dist/object-assign.js` and `dist/object-assign.min.js` (833 bytes minified and gzipped). - -The versions with automatic polyfilling are `dist/object-assign-auto.js` and `dist/object-assign-auto.min.js`. - -## Usage - -**CommonJS**: - -```javascript -// Polyfill, modifying the global Object -require('es6-object-assign').polyfill(); -var obj = Object.assign({}, { foo: 'bar' }); - -// Same version with automatic polyfilling -require('es6-object-assign/auto'); -var obj = Object.assign({}, { foo: 'bar' }); - -// Or ponyfill, using a reference to the function without modifying globals -var assign = require('es6-object-assign').assign; -var obj = assign({}, { foo: 'bar' }); -``` - -**Globals**: - -Manual polyfill: - -```html - - -``` - -Automatic polyfill: - -```html - - -``` - -Ponyfill, without modifying globals: - -```html - - -``` - -## License - -The MIT License (MIT) - -Copyright (c) 2017 Rubén Norte - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/scripts/2.5/node_modules/es6-object-assign/auto.js b/scripts/2.5/node_modules/es6-object-assign/auto.js deleted file mode 100644 index 43b68da0..00000000 --- a/scripts/2.5/node_modules/es6-object-assign/auto.js +++ /dev/null @@ -1,3 +0,0 @@ -'use strict'; - -require('./index').polyfill(); diff --git a/scripts/2.5/node_modules/es6-object-assign/dist/object-assign-auto.js b/scripts/2.5/node_modules/es6-object-assign/dist/object-assign-auto.js deleted file mode 100644 index 12d22b6d..00000000 --- a/scripts/2.5/node_modules/es6-object-assign/dist/object-assign-auto.js +++ /dev/null @@ -1,54 +0,0 @@ -(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o dist/object-assign-auto.min.js", - "compress:manual": "uglifyjs dist/object-assign.js --compress --mangle > dist/object-assign.min.js" - }, - "version": "1.1.0" -} diff --git a/scripts/2.5/node_modules/function-bind/.editorconfig b/scripts/2.5/node_modules/function-bind/.editorconfig deleted file mode 100644 index ac29adef..00000000 --- a/scripts/2.5/node_modules/function-bind/.editorconfig +++ /dev/null @@ -1,20 +0,0 @@ -root = true - -[*] -indent_style = tab -indent_size = 4 -end_of_line = lf -charset = utf-8 -trim_trailing_whitespace = true -insert_final_newline = true -max_line_length = 120 - -[CHANGELOG.md] -indent_style = space -indent_size = 2 - -[*.json] -max_line_length = off - -[Makefile] -max_line_length = off diff --git a/scripts/2.5/node_modules/function-bind/.eslintrc b/scripts/2.5/node_modules/function-bind/.eslintrc deleted file mode 100644 index 9b33d8ed..00000000 --- a/scripts/2.5/node_modules/function-bind/.eslintrc +++ /dev/null @@ -1,15 +0,0 @@ -{ - "root": true, - - "extends": "@ljharb", - - "rules": { - "func-name-matching": 0, - "indent": [2, 4], - "max-nested-callbacks": [2, 3], - "max-params": [2, 3], - "max-statements": [2, 20], - "no-new-func": [1], - "strict": [0] - } -} diff --git a/scripts/2.5/node_modules/function-bind/.jscs.json b/scripts/2.5/node_modules/function-bind/.jscs.json deleted file mode 100644 index 8c447948..00000000 --- a/scripts/2.5/node_modules/function-bind/.jscs.json +++ /dev/null @@ -1,176 +0,0 @@ -{ - "es3": true, - - "additionalRules": [], - - "requireSemicolons": true, - - "disallowMultipleSpaces": true, - - "disallowIdentifierNames": [], - - "requireCurlyBraces": { - "allExcept": [], - "keywords": ["if", "else", "for", "while", "do", "try", "catch"] - }, - - "requireSpaceAfterKeywords": ["if", "else", "for", "while", "do", "switch", "return", "try", "catch", "function"], - - "disallowSpaceAfterKeywords": [], - - "disallowSpaceBeforeComma": true, - "disallowSpaceAfterComma": false, - "disallowSpaceBeforeSemicolon": true, - - "disallowNodeTypes": [ - "DebuggerStatement", - "ForInStatement", - "LabeledStatement", - "SwitchCase", - "SwitchStatement", - "WithStatement" - ], - - "requireObjectKeysOnNewLine": { "allExcept": ["sameLine"] }, - - "requireSpacesInAnonymousFunctionExpression": { "beforeOpeningRoundBrace": true, "beforeOpeningCurlyBrace": true }, - "requireSpacesInNamedFunctionExpression": { "beforeOpeningCurlyBrace": true }, - "disallowSpacesInNamedFunctionExpression": { "beforeOpeningRoundBrace": true }, - "requireSpacesInFunctionDeclaration": { "beforeOpeningCurlyBrace": true }, - "disallowSpacesInFunctionDeclaration": { "beforeOpeningRoundBrace": true }, - - "requireSpaceBetweenArguments": true, - - "disallowSpacesInsideParentheses": true, - - "disallowSpacesInsideArrayBrackets": true, - - "disallowQuotedKeysInObjects": { "allExcept": ["reserved"] }, - - "disallowSpaceAfterObjectKeys": true, - - "requireCommaBeforeLineBreak": true, - - "disallowSpaceAfterPrefixUnaryOperators": ["++", "--", "+", "-", "~", "!"], - "requireSpaceAfterPrefixUnaryOperators": [], - - "disallowSpaceBeforePostfixUnaryOperators": ["++", "--"], - "requireSpaceBeforePostfixUnaryOperators": [], - - "disallowSpaceBeforeBinaryOperators": [], - "requireSpaceBeforeBinaryOperators": ["+", "-", "/", "*", "=", "==", "===", "!=", "!=="], - - "requireSpaceAfterBinaryOperators": ["+", "-", "/", "*", "=", "==", "===", "!=", "!=="], - "disallowSpaceAfterBinaryOperators": [], - - "disallowImplicitTypeConversion": ["binary", "string"], - - "disallowKeywords": ["with", "eval"], - - "requireKeywordsOnNewLine": [], - "disallowKeywordsOnNewLine": ["else"], - - "requireLineFeedAtFileEnd": true, - - "disallowTrailingWhitespace": true, - - "disallowTrailingComma": true, - - "excludeFiles": ["node_modules/**", "vendor/**"], - - "disallowMultipleLineStrings": true, - - "requireDotNotation": { "allExcept": ["keywords"] }, - - "requireParenthesesAroundIIFE": true, - - "validateLineBreaks": "LF", - - "validateQuoteMarks": { - "escape": true, - "mark": "'" - }, - - "disallowOperatorBeforeLineBreak": [], - - "requireSpaceBeforeKeywords": [ - "do", - "for", - "if", - "else", - "switch", - "case", - "try", - "catch", - "finally", - "while", - "with", - "return" - ], - - "validateAlignedFunctionParameters": { - "lineBreakAfterOpeningBraces": true, - "lineBreakBeforeClosingBraces": true - }, - - "requirePaddingNewLinesBeforeExport": true, - - "validateNewlineAfterArrayElements": { - "maximum": 8 - }, - - "requirePaddingNewLinesAfterUseStrict": true, - - "disallowArrowFunctions": true, - - "disallowMultiLineTernary": true, - - "validateOrderInObjectKeys": "asc-insensitive", - - "disallowIdenticalDestructuringNames": true, - - "disallowNestedTernaries": { "maxLevel": 1 }, - - "requireSpaceAfterComma": { "allExcept": ["trailing"] }, - "requireAlignedMultilineParams": false, - - "requireSpacesInGenerator": { - "afterStar": true - }, - - "disallowSpacesInGenerator": { - "beforeStar": true - }, - - "disallowVar": false, - - "requireArrayDestructuring": false, - - "requireEnhancedObjectLiterals": false, - - "requireObjectDestructuring": false, - - "requireEarlyReturn": false, - - "requireCapitalizedConstructorsNew": { - "allExcept": ["Function", "String", "Object", "Symbol", "Number", "Date", "RegExp", "Error", "Boolean", "Array"] - }, - - "requireImportAlphabetized": false, - - "requireSpaceBeforeObjectValues": true, - "requireSpaceBeforeDestructuredValues": true, - - "disallowSpacesInsideTemplateStringPlaceholders": true, - - "disallowArrayDestructuringReturn": false, - - "requireNewlineBeforeSingleStatementsInIf": false, - - "disallowUnusedVariables": true, - - "requireSpacesInsideImportedObjectBraces": true, - - "requireUseStrict": true -} - diff --git a/scripts/2.5/node_modules/function-bind/.npmignore b/scripts/2.5/node_modules/function-bind/.npmignore deleted file mode 100644 index dbb555fd..00000000 --- a/scripts/2.5/node_modules/function-bind/.npmignore +++ /dev/null @@ -1,22 +0,0 @@ -# gitignore -.DS_Store -.monitor -.*.swp -.nodemonignore -releases -*.log -*.err -fleet.json -public/browserify -bin/*.json -.bin -build -compile -.lock-wscript -coverage -node_modules - -# Only apps should have lockfiles -npm-shrinkwrap.json -package-lock.json -yarn.lock diff --git a/scripts/2.5/node_modules/function-bind/.travis.yml b/scripts/2.5/node_modules/function-bind/.travis.yml deleted file mode 100644 index 85f70d24..00000000 --- a/scripts/2.5/node_modules/function-bind/.travis.yml +++ /dev/null @@ -1,168 +0,0 @@ -language: node_js -os: - - linux -node_js: - - "8.4" - - "7.10" - - "6.11" - - "5.12" - - "4.8" - - "iojs-v3.3" - - "iojs-v2.5" - - "iojs-v1.8" - - "0.12" - - "0.10" - - "0.8" -before_install: - - 'if [ "${TRAVIS_NODE_VERSION}" = "0.6" ]; then npm install -g npm@1.3 ; elif [ "${TRAVIS_NODE_VERSION}" != "0.9" ]; then case "$(npm --version)" in 1.*) npm install -g npm@1.4.28 ;; 2.*) npm install -g npm@2 ;; esac ; fi' - - 'if [ "${TRAVIS_NODE_VERSION}" != "0.6" ] && [ "${TRAVIS_NODE_VERSION}" != "0.9" ]; then if [ "${TRAVIS_NODE_VERSION%${TRAVIS_NODE_VERSION#[0-9]}}" = "0" ] || [ "${TRAVIS_NODE_VERSION:0:4}" = "iojs" ]; then npm install -g npm@4.5 ; else npm install -g npm; fi; fi' -install: - - 'if [ "${TRAVIS_NODE_VERSION}" = "0.6" ]; then nvm install 0.8 && npm install -g npm@1.3 && npm install -g npm@1.4.28 && npm install -g npm@2 && npm install && nvm use "${TRAVIS_NODE_VERSION}"; else npm install; fi;' -script: - - 'if [ -n "${PRETEST-}" ]; then npm run pretest ; fi' - - 'if [ -n "${POSTTEST-}" ]; then npm run posttest ; fi' - - 'if [ -n "${COVERAGE-}" ]; then npm run coverage ; fi' - - 'if [ -n "${TEST-}" ]; then npm run tests-only ; fi' -sudo: false -env: - - TEST=true -matrix: - fast_finish: true - include: - - node_js: "node" - env: PRETEST=true - - node_js: "4" - env: COVERAGE=true - - node_js: "8.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.10" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.11" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.10" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v3.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v3.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v3.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "0.11" - env: TEST=true ALLOW_FAILURE=true - - node_js: "0.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "0.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "0.4" - env: TEST=true ALLOW_FAILURE=true - allow_failures: - - os: osx - - env: TEST=true ALLOW_FAILURE=true diff --git a/scripts/2.5/node_modules/function-bind/LICENSE b/scripts/2.5/node_modules/function-bind/LICENSE deleted file mode 100644 index 62d6d237..00000000 --- a/scripts/2.5/node_modules/function-bind/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -Copyright (c) 2013 Raynos. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. - diff --git a/scripts/2.5/node_modules/function-bind/README.md b/scripts/2.5/node_modules/function-bind/README.md deleted file mode 100644 index 81862a02..00000000 --- a/scripts/2.5/node_modules/function-bind/README.md +++ /dev/null @@ -1,48 +0,0 @@ -# function-bind - - - - - -Implementation of function.prototype.bind - -## Example - -I mainly do this for unit tests I run on phantomjs. -PhantomJS does not have Function.prototype.bind :( - -```js -Function.prototype.bind = require("function-bind") -``` - -## Installation - -`npm install function-bind` - -## Contributors - - - Raynos - -## MIT Licenced - - [travis-svg]: https://travis-ci.org/Raynos/function-bind.svg - [travis-url]: https://travis-ci.org/Raynos/function-bind - [npm-badge-svg]: https://badge.fury.io/js/function-bind.svg - [npm-url]: https://npmjs.org/package/function-bind - [5]: https://coveralls.io/repos/Raynos/function-bind/badge.png - [6]: https://coveralls.io/r/Raynos/function-bind - [7]: https://gemnasium.com/Raynos/function-bind.png - [8]: https://gemnasium.com/Raynos/function-bind - [deps-svg]: https://david-dm.org/Raynos/function-bind.svg - [deps-url]: https://david-dm.org/Raynos/function-bind - [dev-deps-svg]: https://david-dm.org/Raynos/function-bind/dev-status.svg - [dev-deps-url]: https://david-dm.org/Raynos/function-bind#info=devDependencies - [11]: https://ci.testling.com/Raynos/function-bind.png - [12]: https://ci.testling.com/Raynos/function-bind diff --git a/scripts/2.5/node_modules/function-bind/implementation.js b/scripts/2.5/node_modules/function-bind/implementation.js deleted file mode 100644 index cc4daec1..00000000 --- a/scripts/2.5/node_modules/function-bind/implementation.js +++ /dev/null @@ -1,52 +0,0 @@ -'use strict'; - -/* eslint no-invalid-this: 1 */ - -var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; -var slice = Array.prototype.slice; -var toStr = Object.prototype.toString; -var funcType = '[object Function]'; - -module.exports = function bind(that) { - var target = this; - if (typeof target !== 'function' || toStr.call(target) !== funcType) { - throw new TypeError(ERROR_MESSAGE + target); - } - var args = slice.call(arguments, 1); - - var bound; - var binder = function () { - if (this instanceof bound) { - var result = target.apply( - this, - args.concat(slice.call(arguments)) - ); - if (Object(result) === result) { - return result; - } - return this; - } else { - return target.apply( - that, - args.concat(slice.call(arguments)) - ); - } - }; - - var boundLength = Math.max(0, target.length - args.length); - var boundArgs = []; - for (var i = 0; i < boundLength; i++) { - boundArgs.push('$' + i); - } - - bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder); - - if (target.prototype) { - var Empty = function Empty() {}; - Empty.prototype = target.prototype; - bound.prototype = new Empty(); - Empty.prototype = null; - } - - return bound; -}; diff --git a/scripts/2.5/node_modules/function-bind/index.js b/scripts/2.5/node_modules/function-bind/index.js deleted file mode 100644 index 3bb6b960..00000000 --- a/scripts/2.5/node_modules/function-bind/index.js +++ /dev/null @@ -1,5 +0,0 @@ -'use strict'; - -var implementation = require('./implementation'); - -module.exports = Function.prototype.bind || implementation; diff --git a/scripts/2.5/node_modules/function-bind/package.json b/scripts/2.5/node_modules/function-bind/package.json deleted file mode 100644 index ea8e7b63..00000000 --- a/scripts/2.5/node_modules/function-bind/package.json +++ /dev/null @@ -1,98 +0,0 @@ -{ - "_from": "function-bind@^1.1.1", - "_id": "function-bind@1.1.1", - "_inBundle": false, - "_integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==", - "_location": "/function-bind", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "function-bind@^1.1.1", - "name": "function-bind", - "escapedName": "function-bind", - "rawSpec": "^1.1.1", - "saveSpec": null, - "fetchSpec": "^1.1.1" - }, - "_requiredBy": [ - "/es-abstract", - "/has", - "/object.entries", - "/string.prototype.trimleft", - "/string.prototype.trimright" - ], - "_resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz", - "_shasum": "a56899d3ea3c9bab874bb9773b7c5ede92f4895d", - "_spec": "function-bind@^1.1.1", - "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/2.5/node_modules/object.entries", - "author": { - "name": "Raynos", - "email": "raynos2@gmail.com" - }, - "bugs": { - "url": "https://github.com/Raynos/function-bind/issues", - "email": "raynos2@gmail.com" - }, - "bundleDependencies": false, - "contributors": [ - { - "name": "Raynos" - }, - { - "name": "Jordan Harband", - "url": "https://github.com/ljharb" - } - ], - "dependencies": {}, - "deprecated": false, - "description": "Implementation of Function.prototype.bind", - "devDependencies": { - "@ljharb/eslint-config": "^12.2.1", - "covert": "^1.1.0", - "eslint": "^4.5.0", - "jscs": "^3.0.7", - "tape": "^4.8.0" - }, - "homepage": "https://github.com/Raynos/function-bind", - "keywords": [ - "function", - "bind", - "shim", - "es5" - ], - "license": "MIT", - "main": "index", - "name": "function-bind", - "repository": { - "type": "git", - "url": "git://github.com/Raynos/function-bind.git" - }, - "scripts": { - "coverage": "covert test/*.js", - "eslint": "eslint *.js */*.js", - "jscs": "jscs *.js */*.js", - "lint": "npm run jscs && npm run eslint", - "posttest": "npm run coverage -- --quiet", - "pretest": "npm run lint", - "test": "npm run tests-only", - "tests-only": "node test" - }, - "testling": { - "files": "test/index.js", - "browsers": [ - "ie/8..latest", - "firefox/16..latest", - "firefox/nightly", - "chrome/22..latest", - "chrome/canary", - "opera/12..latest", - "opera/next", - "safari/5.1..latest", - "ipad/6.0..latest", - "iphone/6.0..latest", - "android-browser/4.2..latest" - ] - }, - "version": "1.1.1" -} diff --git a/scripts/2.5/node_modules/function-bind/test/.eslintrc b/scripts/2.5/node_modules/function-bind/test/.eslintrc deleted file mode 100644 index 8a56d5b7..00000000 --- a/scripts/2.5/node_modules/function-bind/test/.eslintrc +++ /dev/null @@ -1,9 +0,0 @@ -{ - "rules": { - "array-bracket-newline": 0, - "array-element-newline": 0, - "max-statements-per-line": [2, { "max": 2 }], - "no-invalid-this": 0, - "no-magic-numbers": 0, - } -} diff --git a/scripts/2.5/node_modules/function-bind/test/index.js b/scripts/2.5/node_modules/function-bind/test/index.js deleted file mode 100644 index 2edecce2..00000000 --- a/scripts/2.5/node_modules/function-bind/test/index.js +++ /dev/null @@ -1,252 +0,0 @@ -// jscs:disable requireUseStrict - -var test = require('tape'); - -var functionBind = require('../implementation'); -var getCurrentContext = function () { return this; }; - -test('functionBind is a function', function (t) { - t.equal(typeof functionBind, 'function'); - t.end(); -}); - -test('non-functions', function (t) { - var nonFunctions = [true, false, [], {}, 42, 'foo', NaN, /a/g]; - t.plan(nonFunctions.length); - for (var i = 0; i < nonFunctions.length; ++i) { - try { functionBind.call(nonFunctions[i]); } catch (ex) { - t.ok(ex instanceof TypeError, 'throws when given ' + String(nonFunctions[i])); - } - } - t.end(); -}); - -test('without a context', function (t) { - t.test('binds properly', function (st) { - var args, context; - var namespace = { - func: functionBind.call(function () { - args = Array.prototype.slice.call(arguments); - context = this; - }) - }; - namespace.func(1, 2, 3); - st.deepEqual(args, [1, 2, 3]); - st.equal(context, getCurrentContext.call()); - st.end(); - }); - - t.test('binds properly, and still supplies bound arguments', function (st) { - var args, context; - var namespace = { - func: functionBind.call(function () { - args = Array.prototype.slice.call(arguments); - context = this; - }, undefined, 1, 2, 3) - }; - namespace.func(4, 5, 6); - st.deepEqual(args, [1, 2, 3, 4, 5, 6]); - st.equal(context, getCurrentContext.call()); - st.end(); - }); - - t.test('returns properly', function (st) { - var args; - var namespace = { - func: functionBind.call(function () { - args = Array.prototype.slice.call(arguments); - return this; - }, null) - }; - var context = namespace.func(1, 2, 3); - st.equal(context, getCurrentContext.call(), 'returned context is namespaced context'); - st.deepEqual(args, [1, 2, 3], 'passed arguments are correct'); - st.end(); - }); - - t.test('returns properly with bound arguments', function (st) { - var args; - var namespace = { - func: functionBind.call(function () { - args = Array.prototype.slice.call(arguments); - return this; - }, null, 1, 2, 3) - }; - var context = namespace.func(4, 5, 6); - st.equal(context, getCurrentContext.call(), 'returned context is namespaced context'); - st.deepEqual(args, [1, 2, 3, 4, 5, 6], 'passed arguments are correct'); - st.end(); - }); - - t.test('called as a constructor', function (st) { - var thunkify = function (value) { - return function () { return value; }; - }; - st.test('returns object value', function (sst) { - var expectedReturnValue = [1, 2, 3]; - var Constructor = functionBind.call(thunkify(expectedReturnValue), null); - var result = new Constructor(); - sst.equal(result, expectedReturnValue); - sst.end(); - }); - - st.test('does not return primitive value', function (sst) { - var Constructor = functionBind.call(thunkify(42), null); - var result = new Constructor(); - sst.notEqual(result, 42); - sst.end(); - }); - - st.test('object from bound constructor is instance of original and bound constructor', function (sst) { - var A = function (x) { - this.name = x || 'A'; - }; - var B = functionBind.call(A, null, 'B'); - - var result = new B(); - sst.ok(result instanceof B, 'result is instance of bound constructor'); - sst.ok(result instanceof A, 'result is instance of original constructor'); - sst.end(); - }); - - st.end(); - }); - - t.end(); -}); - -test('with a context', function (t) { - t.test('with no bound arguments', function (st) { - var args, context; - var boundContext = {}; - var namespace = { - func: functionBind.call(function () { - args = Array.prototype.slice.call(arguments); - context = this; - }, boundContext) - }; - namespace.func(1, 2, 3); - st.equal(context, boundContext, 'binds a context properly'); - st.deepEqual(args, [1, 2, 3], 'supplies passed arguments'); - st.end(); - }); - - t.test('with bound arguments', function (st) { - var args, context; - var boundContext = {}; - var namespace = { - func: functionBind.call(function () { - args = Array.prototype.slice.call(arguments); - context = this; - }, boundContext, 1, 2, 3) - }; - namespace.func(4, 5, 6); - st.equal(context, boundContext, 'binds a context properly'); - st.deepEqual(args, [1, 2, 3, 4, 5, 6], 'supplies bound and passed arguments'); - st.end(); - }); - - t.test('returns properly', function (st) { - var boundContext = {}; - var args; - var namespace = { - func: functionBind.call(function () { - args = Array.prototype.slice.call(arguments); - return this; - }, boundContext) - }; - var context = namespace.func(1, 2, 3); - st.equal(context, boundContext, 'returned context is bound context'); - st.notEqual(context, getCurrentContext.call(), 'returned context is not lexical context'); - st.deepEqual(args, [1, 2, 3], 'passed arguments are correct'); - st.end(); - }); - - t.test('returns properly with bound arguments', function (st) { - var boundContext = {}; - var args; - var namespace = { - func: functionBind.call(function () { - args = Array.prototype.slice.call(arguments); - return this; - }, boundContext, 1, 2, 3) - }; - var context = namespace.func(4, 5, 6); - st.equal(context, boundContext, 'returned context is bound context'); - st.notEqual(context, getCurrentContext.call(), 'returned context is not lexical context'); - st.deepEqual(args, [1, 2, 3, 4, 5, 6], 'passed arguments are correct'); - st.end(); - }); - - t.test('passes the correct arguments when called as a constructor', function (st) { - var expected = { name: 'Correct' }; - var namespace = { - Func: functionBind.call(function (arg) { - return arg; - }, { name: 'Incorrect' }) - }; - var returned = new namespace.Func(expected); - st.equal(returned, expected, 'returns the right arg when called as a constructor'); - st.end(); - }); - - t.test('has the new instance\'s context when called as a constructor', function (st) { - var actualContext; - var expectedContext = { foo: 'bar' }; - var namespace = { - Func: functionBind.call(function () { - actualContext = this; - }, expectedContext) - }; - var result = new namespace.Func(); - st.equal(result instanceof namespace.Func, true); - st.notEqual(actualContext, expectedContext); - st.end(); - }); - - t.end(); -}); - -test('bound function length', function (t) { - t.test('sets a correct length without thisArg', function (st) { - var subject = functionBind.call(function (a, b, c) { return a + b + c; }); - st.equal(subject.length, 3); - st.equal(subject(1, 2, 3), 6); - st.end(); - }); - - t.test('sets a correct length with thisArg', function (st) { - var subject = functionBind.call(function (a, b, c) { return a + b + c; }, {}); - st.equal(subject.length, 3); - st.equal(subject(1, 2, 3), 6); - st.end(); - }); - - t.test('sets a correct length without thisArg and first argument', function (st) { - var subject = functionBind.call(function (a, b, c) { return a + b + c; }, undefined, 1); - st.equal(subject.length, 2); - st.equal(subject(2, 3), 6); - st.end(); - }); - - t.test('sets a correct length with thisArg and first argument', function (st) { - var subject = functionBind.call(function (a, b, c) { return a + b + c; }, {}, 1); - st.equal(subject.length, 2); - st.equal(subject(2, 3), 6); - st.end(); - }); - - t.test('sets a correct length without thisArg and too many arguments', function (st) { - var subject = functionBind.call(function (a, b, c) { return a + b + c; }, undefined, 1, 2, 3, 4); - st.equal(subject.length, 0); - st.equal(subject(), 6); - st.end(); - }); - - t.test('sets a correct length with thisArg and too many arguments', function (st) { - var subject = functionBind.call(function (a, b, c) { return a + b + c; }, {}, 1, 2, 3, 4); - st.equal(subject.length, 0); - st.equal(subject(), 6); - st.end(); - }); -}); diff --git a/scripts/2.5/node_modules/has-symbols/.eslintrc b/scripts/2.5/node_modules/has-symbols/.eslintrc deleted file mode 100644 index f78f6f18..00000000 --- a/scripts/2.5/node_modules/has-symbols/.eslintrc +++ /dev/null @@ -1,10 +0,0 @@ -{ - "root": true, - - "extends": "@ljharb", - - "rules": { - "max-statements-per-line": [2, { "max": 2 }], - "no-magic-numbers": 0 - } -} diff --git a/scripts/2.5/node_modules/has-symbols/.npmignore b/scripts/2.5/node_modules/has-symbols/.npmignore deleted file mode 100644 index 5148e527..00000000 --- a/scripts/2.5/node_modules/has-symbols/.npmignore +++ /dev/null @@ -1,37 +0,0 @@ -# Logs -logs -*.log -npm-debug.log* - -# Runtime data -pids -*.pid -*.seed - -# Directory for instrumented libs generated by jscoverage/JSCover -lib-cov - -# Coverage directory used by tools like istanbul -coverage - -# nyc test coverage -.nyc_output - -# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) -.grunt - -# node-waf configuration -.lock-wscript - -# Compiled binary addons (http://nodejs.org/api/addons.html) -build/Release - -# Dependency directories -node_modules -jspm_packages - -# Optional npm cache directory -.npm - -# Optional REPL history -.node_repl_history diff --git a/scripts/2.5/node_modules/has-symbols/.travis.yml b/scripts/2.5/node_modules/has-symbols/.travis.yml deleted file mode 100644 index 3b3331a3..00000000 --- a/scripts/2.5/node_modules/has-symbols/.travis.yml +++ /dev/null @@ -1,113 +0,0 @@ -language: node_js -node_js: - - "6.6" - - "6.5" - - "6.4" - - "6.3" - - "6.2" - - "6.1" - - "6.0" - - "5.12" - - "5.11" - - "5.10" - - "5.9" - - "5.8" - - "5.7" - - "5.6" - - "5.5" - - "5.4" - - "5.3" - - "5.2" - - "5.1" - - "5.0" - - "4.5" - - "4.4" - - "4.3" - - "4.2" - - "4.1" - - "4.0" - - "iojs-v3.3" - - "iojs-v3.2" - - "iojs-v3.1" - - "iojs-v3.0" - - "iojs-v2.5" - - "iojs-v2.4" - - "iojs-v2.3" - - "iojs-v2.2" - - "iojs-v2.1" - - "iojs-v2.0" - - "iojs-v1.8" - - "iojs-v1.7" - - "iojs-v1.6" - - "iojs-v1.5" - - "iojs-v1.4" - - "iojs-v1.3" - - "iojs-v1.2" - - "iojs-v1.1" - - "iojs-v1.0" - - "0.12" - - "0.11" - - "0.10" - - "0.9" - - "0.8" - - "0.6" - - "0.4" -before_install: - - 'if [ "${TRAVIS_NODE_VERSION}" != "0.9" ]; then case "$(npm --version)" in 1.*) npm install -g npm@1.4.28 ;; 2.*) npm install -g npm@2 ;; esac ; fi' - - 'if [ "${TRAVIS_NODE_VERSION}" != "0.6" ] && [ "${TRAVIS_NODE_VERSION}" != "0.9" ]; then npm install -g npm; fi' -script: - - 'if [ -n "${LINT-}" ]; then npm run lint ; fi' - - 'if [ -n "${COVERAGE-}" ]; then npm run coverage ; fi' - - 'if [ -n "${TEST-}" ]; then npm run tests-only ; fi' -sudo: false -env: - - TEST=true -matrix: - fast_finish: true - include: - - node_js: "node" - env: LINT=true - allow_failures: - - node_js: "6.5" - - node_js: "6.4" - - node_js: "6.3" - - node_js: "6.2" - - node_js: "6.1" - - node_js: "6.0" - - node_js: "5.11" - - node_js: "5.10" - - node_js: "5.9" - - node_js: "5.8" - - node_js: "5.7" - - node_js: "5.6" - - node_js: "5.5" - - node_js: "5.4" - - node_js: "5.3" - - node_js: "5.2" - - node_js: "5.1" - - node_js: "5.0" - - node_js: "4.4" - - node_js: "4.3" - - node_js: "4.2" - - node_js: "4.1" - - node_js: "4.0" - - node_js: "iojs-v3.2" - - node_js: "iojs-v3.1" - - node_js: "iojs-v3.0" - - node_js: "iojs-v2.4" - - node_js: "iojs-v2.3" - - node_js: "iojs-v2.2" - - node_js: "iojs-v2.1" - - node_js: "iojs-v2.0" - - node_js: "iojs-v1.7" - - node_js: "iojs-v1.6" - - node_js: "iojs-v1.5" - - node_js: "iojs-v1.4" - - node_js: "iojs-v1.3" - - node_js: "iojs-v1.2" - - node_js: "iojs-v1.1" - - node_js: "iojs-v1.0" - - node_js: "0.11" - - node_js: "0.9" - - node_js: "0.6" - - node_js: "0.4" diff --git a/scripts/2.5/node_modules/has-symbols/CHANGELOG.md b/scripts/2.5/node_modules/has-symbols/CHANGELOG.md deleted file mode 100644 index da7f9da7..00000000 --- a/scripts/2.5/node_modules/has-symbols/CHANGELOG.md +++ /dev/null @@ -1,3 +0,0 @@ -1.0.0 / 2016-09-19 -================= - * Initial release. diff --git a/scripts/2.5/node_modules/has-symbols/LICENSE b/scripts/2.5/node_modules/has-symbols/LICENSE deleted file mode 100644 index df31cbf3..00000000 --- a/scripts/2.5/node_modules/has-symbols/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2016 Jordan Harband - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/scripts/2.5/node_modules/has-symbols/README.md b/scripts/2.5/node_modules/has-symbols/README.md deleted file mode 100644 index b27b31ac..00000000 --- a/scripts/2.5/node_modules/has-symbols/README.md +++ /dev/null @@ -1,45 +0,0 @@ -# has-symbols [![Version Badge][2]][1] - -[![Build Status][3]][4] -[![dependency status][5]][6] -[![dev dependency status][7]][8] -[![License][license-image]][license-url] -[![Downloads][downloads-image]][downloads-url] - -[![npm badge][11]][1] - -Determine if the JS environment has Symbol support. Supports spec, or shams. - -## Example - -```js -var hasSymbols = require('has-symbols'); - -hasSymbols() === true; // if the environment has native Symbol support. Not polyfillable, not forgeable. - -var hasSymbolsKinda = require('has-symbols/shams'); -hasSymbolsKinda() === true; // if the environment has a Symbol sham that mostly follows the spec. -``` - -## Supported Symbol shams - - get-own-property-symbols [npm](https://www.npmjs.com/package/get-own-property-symbols) | [github](https://github.com/WebReflection/get-own-property-symbols) - - core-js [npm](https://www.npmjs.com/package/core-js) | [github](https://github.com/zloirock/core-js) - -## Tests -Simply clone the repo, `npm install`, and run `npm test` - -[1]: https://npmjs.org/package/has-symbols -[2]: http://versionbadg.es/ljharb/has-symbols.svg -[3]: https://travis-ci.org/ljharb/has-symbols.svg -[4]: https://travis-ci.org/ljharb/has-symbols -[5]: https://david-dm.org/ljharb/has-symbols.svg -[6]: https://david-dm.org/ljharb/has-symbols -[7]: https://david-dm.org/ljharb/has-symbols/dev-status.svg -[8]: https://david-dm.org/ljharb/has-symbols#info=devDependencies -[9]: https://ci.testling.com/ljharb/has-symbols.png -[10]: https://ci.testling.com/ljharb/has-symbols -[11]: https://nodei.co/npm/has-symbols.png?downloads=true&stars=true -[license-image]: http://img.shields.io/npm/l/has-symbols.svg -[license-url]: LICENSE -[downloads-image]: http://img.shields.io/npm/dm/has-symbols.svg -[downloads-url]: http://npm-stat.com/charts.html?package=has-symbols diff --git a/scripts/2.5/node_modules/has-symbols/index.js b/scripts/2.5/node_modules/has-symbols/index.js deleted file mode 100644 index f72159e0..00000000 --- a/scripts/2.5/node_modules/has-symbols/index.js +++ /dev/null @@ -1,13 +0,0 @@ -'use strict'; - -var origSymbol = global.Symbol; -var hasSymbolSham = require('./shams'); - -module.exports = function hasNativeSymbols() { - if (typeof origSymbol !== 'function') { return false; } - if (typeof Symbol !== 'function') { return false; } - if (typeof origSymbol('foo') !== 'symbol') { return false; } - if (typeof Symbol('bar') !== 'symbol') { return false; } - - return hasSymbolSham(); -}; diff --git a/scripts/2.5/node_modules/has-symbols/package.json b/scripts/2.5/node_modules/has-symbols/package.json deleted file mode 100644 index f4aae2b1..00000000 --- a/scripts/2.5/node_modules/has-symbols/package.json +++ /dev/null @@ -1,108 +0,0 @@ -{ - "_from": "has-symbols@^1.0.0", - "_id": "has-symbols@1.0.0", - "_inBundle": false, - "_integrity": "sha1-uhqPGvKg/DllD1yFA2dwQSIGO0Q=", - "_location": "/has-symbols", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "has-symbols@^1.0.0", - "name": "has-symbols", - "escapedName": "has-symbols", - "rawSpec": "^1.0.0", - "saveSpec": null, - "fetchSpec": "^1.0.0" - }, - "_requiredBy": [ - "/es-abstract", - "/is-symbol" - ], - "_resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.0.tgz", - "_shasum": "ba1a8f1af2a0fc39650f5c850367704122063b44", - "_spec": "has-symbols@^1.0.0", - "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/2.5/node_modules/es-abstract", - "author": { - "name": "Jordan Harband", - "email": "ljharb@gmail.com", - "url": "http://ljharb.codes" - }, - "bugs": { - "url": "https://github.com/ljharb/has-symbols/issues" - }, - "bundleDependencies": false, - "contributors": [ - { - "name": "Jordan Harband", - "email": "ljharb@gmail.com", - "url": "http://ljharb.codes" - } - ], - "dependencies": {}, - "deprecated": false, - "description": "Determine if the JS environment has Symbol support. Supports spec, or shams.", - "devDependencies": { - "@ljharb/eslint-config": "^8.0.0", - "core-js": "^2.4.1", - "eslint": "^3.5.0", - "get-own-property-symbols": "^0.9.2", - "nsp": "^2.6.1", - "safe-publish-latest": "^1.0.1", - "tape": "^4.6.0" - }, - "engines": { - "node": ">= 0.4" - }, - "homepage": "https://github.com/ljharb/has-symbols#readme", - "keywords": [ - "Symbol", - "symbols", - "typeof", - "sham", - "polyfill", - "native", - "core-js", - "ES6" - ], - "license": "MIT", - "main": "index.js", - "name": "has-symbols", - "repository": { - "type": "git", - "url": "git://github.com/ljharb/has-symbols.git" - }, - "scripts": { - "lint": "eslint *.js", - "posttest": "npm run --silent security", - "prepublish": "safe-publish-latest", - "pretest": "npm run --silent lint", - "security": "nsp check", - "test": "npm run --silent tests-only", - "test:shams": "npm run --silent test:shams:getownpropertysymbols && npm run --silent test:shams:corejs", - "test:shams:corejs": "node test/shams/core-js.js", - "test:shams:getownpropertysymbols": "node test/shams/get-own-property-symbols.js", - "test:staging": "node --harmony --es-staging test", - "test:stock": "node test", - "tests-only": "npm run --silent test:stock && npm run --silent test:staging && npm run --silent test:shams" - }, - "testling": { - "files": "test/index.js", - "browsers": [ - "iexplore/6.0..latest", - "firefox/3.0..6.0", - "firefox/15.0..latest", - "firefox/nightly", - "chrome/4.0..10.0", - "chrome/20.0..latest", - "chrome/canary", - "opera/10.0..latest", - "opera/next", - "safari/4.0..latest", - "ipad/6.0..latest", - "iphone/6.0..latest", - "android-browser/4.2" - ] - }, - "version": "1.0.0" -} diff --git a/scripts/2.5/node_modules/has-symbols/shams.js b/scripts/2.5/node_modules/has-symbols/shams.js deleted file mode 100644 index f6c1ff4a..00000000 --- a/scripts/2.5/node_modules/has-symbols/shams.js +++ /dev/null @@ -1,42 +0,0 @@ -'use strict'; - -/* eslint complexity: [2, 17], max-statements: [2, 33] */ -module.exports = function hasSymbols() { - if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; } - if (typeof Symbol.iterator === 'symbol') { return true; } - - var obj = {}; - var sym = Symbol('test'); - var symObj = Object(sym); - if (typeof sym === 'string') { return false; } - - if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; } - if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; } - - // temp disabled per https://github.com/ljharb/object.assign/issues/17 - // if (sym instanceof Symbol) { return false; } - // temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4 - // if (!(symObj instanceof Symbol)) { return false; } - - // if (typeof Symbol.prototype.toString !== 'function') { return false; } - // if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; } - - var symVal = 42; - obj[sym] = symVal; - for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax - if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; } - - if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; } - - var syms = Object.getOwnPropertySymbols(obj); - if (syms.length !== 1 || syms[0] !== sym) { return false; } - - if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; } - - if (typeof Object.getOwnPropertyDescriptor === 'function') { - var descriptor = Object.getOwnPropertyDescriptor(obj, sym); - if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; } - } - - return true; -}; diff --git a/scripts/2.5/node_modules/has-symbols/test/index.js b/scripts/2.5/node_modules/has-symbols/test/index.js deleted file mode 100644 index fc32aff9..00000000 --- a/scripts/2.5/node_modules/has-symbols/test/index.js +++ /dev/null @@ -1,22 +0,0 @@ -'use strict'; - -var test = require('tape'); -var hasSymbols = require('../'); -var runSymbolTests = require('./tests'); - -test('interface', function (t) { - t.equal(typeof hasSymbols, 'function', 'is a function'); - t.equal(typeof hasSymbols(), 'boolean', 'returns a boolean'); - t.end(); -}); - -test('Symbols are supported', { skip: !hasSymbols() }, function (t) { - runSymbolTests(t); - t.end(); -}); - -test('Symbols are not supported', { skip: hasSymbols() }, function (t) { - t.equal(typeof Symbol, 'undefined', 'global Symbol is undefined'); - t.equal(typeof Object.getOwnPropertySymbols, 'undefined', 'Object.getOwnPropertySymbols does not exist'); - t.end(); -}); diff --git a/scripts/2.5/node_modules/has-symbols/test/shams/core-js.js b/scripts/2.5/node_modules/has-symbols/test/shams/core-js.js deleted file mode 100644 index df5365c2..00000000 --- a/scripts/2.5/node_modules/has-symbols/test/shams/core-js.js +++ /dev/null @@ -1,28 +0,0 @@ -'use strict'; - -var test = require('tape'); - -if (typeof Symbol === 'function' && typeof Symbol() === 'symbol') { - test('has native Symbol support', function (t) { - t.equal(typeof Symbol, 'function'); - t.equal(typeof Symbol(), 'symbol'); - t.end(); - }); - return; -} - -var hasSymbols = require('../../shams'); - -test('polyfilled Symbols', function (t) { - /* eslint-disable global-require */ - t.equal(hasSymbols(), false, 'hasSymbols is false before polyfilling'); - require('core-js/fn/symbol'); - require('core-js/fn/symbol/to-string-tag'); - - require('../tests')(t); - - var hasSymbolsAfter = hasSymbols(); - t.equal(hasSymbolsAfter, true, 'hasSymbols is true after polyfilling'); - /* eslint-enable global-require */ - t.end(); -}); diff --git a/scripts/2.5/node_modules/has-symbols/test/shams/get-own-property-symbols.js b/scripts/2.5/node_modules/has-symbols/test/shams/get-own-property-symbols.js deleted file mode 100644 index 9191b248..00000000 --- a/scripts/2.5/node_modules/has-symbols/test/shams/get-own-property-symbols.js +++ /dev/null @@ -1,28 +0,0 @@ -'use strict'; - -var test = require('tape'); - -if (typeof Symbol === 'function' && typeof Symbol() === 'symbol') { - test('has native Symbol support', function (t) { - t.equal(typeof Symbol, 'function'); - t.equal(typeof Symbol(), 'symbol'); - t.end(); - }); - return; -} - -var hasSymbols = require('../../shams'); - -test('polyfilled Symbols', function (t) { - /* eslint-disable global-require */ - t.equal(hasSymbols(), false, 'hasSymbols is false before polyfilling'); - - require('get-own-property-symbols'); - - require('../tests')(t); - - var hasSymbolsAfter = hasSymbols(); - t.equal(hasSymbolsAfter, true, 'hasSymbols is true after polyfilling'); - /* eslint-enable global-require */ - t.end(); -}); diff --git a/scripts/2.5/node_modules/has-symbols/test/tests.js b/scripts/2.5/node_modules/has-symbols/test/tests.js deleted file mode 100644 index 93ff0eae..00000000 --- a/scripts/2.5/node_modules/has-symbols/test/tests.js +++ /dev/null @@ -1,54 +0,0 @@ -'use strict'; - -module.exports = function runSymbolTests(t) { - t.equal(typeof Symbol, 'function', 'global Symbol is a function'); - - if (typeof Symbol !== 'function') { return false }; - - t.notEqual(Symbol(), Symbol(), 'two symbols are not equal'); - - /* - t.equal( - Symbol.prototype.toString.call(Symbol('foo')), - Symbol.prototype.toString.call(Symbol('foo')), - 'two symbols with the same description stringify the same' - ); - */ - - var foo = Symbol('foo'); - - /* - t.notEqual( - String(foo), - String(Symbol('bar')), - 'two symbols with different descriptions do not stringify the same' - ); - */ - - t.equal(typeof Symbol.prototype.toString, 'function', 'Symbol#toString is a function'); - // t.equal(String(foo), Symbol.prototype.toString.call(foo), 'Symbol#toString equals String of the same symbol'); - - t.equal(typeof Object.getOwnPropertySymbols, 'function', 'Object.getOwnPropertySymbols is a function'); - - var obj = {}; - var sym = Symbol('test'); - var symObj = Object(sym); - t.notEqual(typeof sym, 'string', 'Symbol is not a string'); - t.equal(Object.prototype.toString.call(sym), '[object Symbol]', 'symbol primitive Object#toStrings properly'); - t.equal(Object.prototype.toString.call(symObj), '[object Symbol]', 'symbol primitive Object#toStrings properly'); - - var symVal = 42; - obj[sym] = symVal; - for (sym in obj) { t.fail('symbol property key was found in for..in of object'); } - - t.deepEqual(Object.keys(obj), [], 'no enumerable own keys on symbol-valued object'); - t.deepEqual(Object.getOwnPropertyNames(obj), [], 'no own names on symbol-valued object'); - t.deepEqual(Object.getOwnPropertySymbols(obj), [sym], 'one own symbol on symbol-valued object'); - t.equal(Object.prototype.propertyIsEnumerable.call(obj, sym), true, 'symbol is enumerable'); - t.deepEqual(Object.getOwnPropertyDescriptor(obj, sym), { - configurable: true, - enumerable: true, - value: 42, - writable: true - }, 'property descriptor is correct'); -}; diff --git a/scripts/2.5/node_modules/has/LICENSE-MIT b/scripts/2.5/node_modules/has/LICENSE-MIT deleted file mode 100644 index ae7014d3..00000000 --- a/scripts/2.5/node_modules/has/LICENSE-MIT +++ /dev/null @@ -1,22 +0,0 @@ -Copyright (c) 2013 Thiago de Arruda - -Permission is hereby granted, free of charge, to any person -obtaining a copy of this software and associated documentation -files (the "Software"), to deal in the Software without -restriction, including without limitation the rights to use, -copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the -Software is furnished to do so, subject to the following -conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -OTHER DEALINGS IN THE SOFTWARE. diff --git a/scripts/2.5/node_modules/has/README.md b/scripts/2.5/node_modules/has/README.md deleted file mode 100644 index 635e3a4b..00000000 --- a/scripts/2.5/node_modules/has/README.md +++ /dev/null @@ -1,18 +0,0 @@ -# has - -> Object.prototype.hasOwnProperty.call shortcut - -## Installation - -```sh -npm install --save has -``` - -## Usage - -```js -var has = require('has'); - -has({}, 'hasOwnProperty'); // false -has(Object.prototype, 'hasOwnProperty'); // true -``` diff --git a/scripts/2.5/node_modules/has/package.json b/scripts/2.5/node_modules/has/package.json deleted file mode 100644 index 264e52f9..00000000 --- a/scripts/2.5/node_modules/has/package.json +++ /dev/null @@ -1,75 +0,0 @@ -{ - "_from": "has@^1.0.3", - "_id": "has@1.0.3", - "_inBundle": false, - "_integrity": "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==", - "_location": "/has", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "has@^1.0.3", - "name": "has", - "escapedName": "has", - "rawSpec": "^1.0.3", - "saveSpec": null, - "fetchSpec": "^1.0.3" - }, - "_requiredBy": [ - "/es-abstract", - "/is-regex", - "/object.entries" - ], - "_resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz", - "_shasum": "722d7cbfc1f6aa8241f16dd814e011e1f41e8796", - "_spec": "has@^1.0.3", - "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/2.5/node_modules/object.entries", - "author": { - "name": "Thiago de Arruda", - "email": "tpadilha84@gmail.com" - }, - "bugs": { - "url": "https://github.com/tarruda/has/issues" - }, - "bundleDependencies": false, - "contributors": [ - { - "name": "Jordan Harband", - "email": "ljharb@gmail.com", - "url": "http://ljharb.codes" - } - ], - "dependencies": { - "function-bind": "^1.1.1" - }, - "deprecated": false, - "description": "Object.prototype.hasOwnProperty.call shortcut", - "devDependencies": { - "@ljharb/eslint-config": "^12.2.1", - "eslint": "^4.19.1", - "tape": "^4.9.0" - }, - "engines": { - "node": ">= 0.4.0" - }, - "homepage": "https://github.com/tarruda/has", - "license": "MIT", - "licenses": [ - { - "type": "MIT", - "url": "https://github.com/tarruda/has/blob/master/LICENSE-MIT" - } - ], - "main": "./src", - "name": "has", - "repository": { - "type": "git", - "url": "git://github.com/tarruda/has.git" - }, - "scripts": { - "lint": "eslint .", - "pretest": "npm run lint", - "test": "tape test" - }, - "version": "1.0.3" -} diff --git a/scripts/2.5/node_modules/has/src/index.js b/scripts/2.5/node_modules/has/src/index.js deleted file mode 100644 index dd92dd90..00000000 --- a/scripts/2.5/node_modules/has/src/index.js +++ /dev/null @@ -1,5 +0,0 @@ -'use strict'; - -var bind = require('function-bind'); - -module.exports = bind.call(Function.call, Object.prototype.hasOwnProperty); diff --git a/scripts/2.5/node_modules/has/test/index.js b/scripts/2.5/node_modules/has/test/index.js deleted file mode 100644 index 43d480b2..00000000 --- a/scripts/2.5/node_modules/has/test/index.js +++ /dev/null @@ -1,10 +0,0 @@ -'use strict'; - -var test = require('tape'); -var has = require('../'); - -test('has', function (t) { - t.equal(has({}, 'hasOwnProperty'), false, 'object literal does not have own property "hasOwnProperty"'); - t.equal(has(Object.prototype, 'hasOwnProperty'), true, 'Object.prototype has own property "hasOwnProperty"'); - t.end(); -}); diff --git a/scripts/2.5/node_modules/inherits/LICENSE b/scripts/2.5/node_modules/inherits/LICENSE deleted file mode 100644 index dea3013d..00000000 --- a/scripts/2.5/node_modules/inherits/LICENSE +++ /dev/null @@ -1,16 +0,0 @@ -The ISC License - -Copyright (c) Isaac Z. Schlueter - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted, provided that the above -copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR -OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -PERFORMANCE OF THIS SOFTWARE. - diff --git a/scripts/2.5/node_modules/inherits/README.md b/scripts/2.5/node_modules/inherits/README.md deleted file mode 100644 index b1c56658..00000000 --- a/scripts/2.5/node_modules/inherits/README.md +++ /dev/null @@ -1,42 +0,0 @@ -Browser-friendly inheritance fully compatible with standard node.js -[inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor). - -This package exports standard `inherits` from node.js `util` module in -node environment, but also provides alternative browser-friendly -implementation through [browser -field](https://gist.github.com/shtylman/4339901). Alternative -implementation is a literal copy of standard one located in standalone -module to avoid requiring of `util`. It also has a shim for old -browsers with no `Object.create` support. - -While keeping you sure you are using standard `inherits` -implementation in node.js environment, it allows bundlers such as -[browserify](https://github.com/substack/node-browserify) to not -include full `util` package to your client code if all you need is -just `inherits` function. It worth, because browser shim for `util` -package is large and `inherits` is often the single function you need -from it. - -It's recommended to use this package instead of -`require('util').inherits` for any code that has chances to be used -not only in node.js but in browser too. - -## usage - -```js -var inherits = require('inherits'); -// then use exactly as the standard one -``` - -## note on version ~1.0 - -Version ~1.0 had completely different motivation and is not compatible -neither with 2.0 nor with standard node.js `inherits`. - -If you are using version ~1.0 and planning to switch to ~2.0, be -careful: - -* new version uses `super_` instead of `super` for referencing - superclass -* new version overwrites current prototype while old one preserves any - existing fields on it diff --git a/scripts/2.5/node_modules/inherits/inherits.js b/scripts/2.5/node_modules/inherits/inherits.js deleted file mode 100644 index f71f2d93..00000000 --- a/scripts/2.5/node_modules/inherits/inherits.js +++ /dev/null @@ -1,9 +0,0 @@ -try { - var util = require('util'); - /* istanbul ignore next */ - if (typeof util.inherits !== 'function') throw ''; - module.exports = util.inherits; -} catch (e) { - /* istanbul ignore next */ - module.exports = require('./inherits_browser.js'); -} diff --git a/scripts/2.5/node_modules/inherits/inherits_browser.js b/scripts/2.5/node_modules/inherits/inherits_browser.js deleted file mode 100644 index 86bbb3dc..00000000 --- a/scripts/2.5/node_modules/inherits/inherits_browser.js +++ /dev/null @@ -1,27 +0,0 @@ -if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - if (superCtor) { - ctor.super_ = superCtor - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }) - } - }; -} else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - if (superCtor) { - ctor.super_ = superCtor - var TempCtor = function () {} - TempCtor.prototype = superCtor.prototype - ctor.prototype = new TempCtor() - ctor.prototype.constructor = ctor - } - } -} diff --git a/scripts/2.5/node_modules/inherits/package.json b/scripts/2.5/node_modules/inherits/package.json deleted file mode 100644 index 1b984ce0..00000000 --- a/scripts/2.5/node_modules/inherits/package.json +++ /dev/null @@ -1,61 +0,0 @@ -{ - "_from": "inherits@^2.0.3", - "_id": "inherits@2.0.4", - "_inBundle": false, - "_integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", - "_location": "/inherits", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "inherits@^2.0.3", - "name": "inherits", - "escapedName": "inherits", - "rawSpec": "^2.0.3", - "saveSpec": null, - "fetchSpec": "^2.0.3" - }, - "_requiredBy": [ - "/util" - ], - "_resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", - "_shasum": "0fa2c64f932917c3433a0ded55363aae37416b7c", - "_spec": "inherits@^2.0.3", - "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/2.5/node_modules/util", - "browser": "./inherits_browser.js", - "bugs": { - "url": "https://github.com/isaacs/inherits/issues" - }, - "bundleDependencies": false, - "deprecated": false, - "description": "Browser-friendly inheritance fully compatible with standard node.js inherits()", - "devDependencies": { - "tap": "^14.2.4" - }, - "files": [ - "inherits.js", - "inherits_browser.js" - ], - "homepage": "https://github.com/isaacs/inherits#readme", - "keywords": [ - "inheritance", - "class", - "klass", - "oop", - "object-oriented", - "inherits", - "browser", - "browserify" - ], - "license": "ISC", - "main": "./inherits.js", - "name": "inherits", - "repository": { - "type": "git", - "url": "git://github.com/isaacs/inherits.git" - }, - "scripts": { - "test": "tap" - }, - "version": "2.0.4" -} diff --git a/scripts/2.5/node_modules/is-arguments/.editorconfig b/scripts/2.5/node_modules/is-arguments/.editorconfig deleted file mode 100644 index bc228f82..00000000 --- a/scripts/2.5/node_modules/is-arguments/.editorconfig +++ /dev/null @@ -1,20 +0,0 @@ -root = true - -[*] -indent_style = tab -indent_size = 4 -end_of_line = lf -charset = utf-8 -trim_trailing_whitespace = true -insert_final_newline = true -max_line_length = 150 - -[CHANGELOG.md] -indent_style = space -indent_size = 2 - -[*.json] -max_line_length = off - -[Makefile] -max_line_length = off diff --git a/scripts/2.5/node_modules/is-arguments/.eslintrc b/scripts/2.5/node_modules/is-arguments/.eslintrc deleted file mode 100644 index 6d42c6ed..00000000 --- a/scripts/2.5/node_modules/is-arguments/.eslintrc +++ /dev/null @@ -1,10 +0,0 @@ -{ - "root": true, - - "extends": "@ljharb", - - "rules": { - "id-length": [2, { "min": 1, "max": 25 }], - "operator-linebreak": [2, "after"] - } -} diff --git a/scripts/2.5/node_modules/is-arguments/.jscs.json b/scripts/2.5/node_modules/is-arguments/.jscs.json deleted file mode 100644 index b4d9b8b4..00000000 --- a/scripts/2.5/node_modules/is-arguments/.jscs.json +++ /dev/null @@ -1,176 +0,0 @@ -{ - "es3": true, - - "additionalRules": [], - - "requireSemicolons": true, - - "disallowMultipleSpaces": true, - - "disallowIdentifierNames": [], - - "requireCurlyBraces": { - "allExcept": [], - "keywords": ["if", "else", "for", "while", "do", "try", "catch"] - }, - - "requireSpaceAfterKeywords": ["if", "else", "for", "while", "do", "switch", "return", "try", "catch", "function"], - - "disallowSpaceAfterKeywords": [], - - "disallowSpaceBeforeComma": true, - "disallowSpaceAfterComma": false, - "disallowSpaceBeforeSemicolon": true, - - "disallowNodeTypes": [ - "DebuggerStatement", - "ForInStatement", - "LabeledStatement", - "SwitchCase", - "SwitchStatement", - "WithStatement" - ], - - "requireObjectKeysOnNewLine": { "allExcept": ["sameLine"] }, - - "requireSpacesInAnonymousFunctionExpression": { "beforeOpeningRoundBrace": true, "beforeOpeningCurlyBrace": true }, - "requireSpacesInNamedFunctionExpression": { "beforeOpeningCurlyBrace": true }, - "disallowSpacesInNamedFunctionExpression": { "beforeOpeningRoundBrace": true }, - "requireSpacesInFunctionDeclaration": { "beforeOpeningCurlyBrace": true }, - "disallowSpacesInFunctionDeclaration": { "beforeOpeningRoundBrace": true }, - - "requireSpaceBetweenArguments": true, - - "disallowSpacesInsideParentheses": true, - - "disallowSpacesInsideArrayBrackets": true, - - "disallowQuotedKeysInObjects": { "allExcept": ["reserved"] }, - - "disallowSpaceAfterObjectKeys": true, - - "requireCommaBeforeLineBreak": true, - - "disallowSpaceAfterPrefixUnaryOperators": ["++", "--", "+", "-", "~", "!"], - "requireSpaceAfterPrefixUnaryOperators": [], - - "disallowSpaceBeforePostfixUnaryOperators": ["++", "--"], - "requireSpaceBeforePostfixUnaryOperators": [], - - "disallowSpaceBeforeBinaryOperators": [], - "requireSpaceBeforeBinaryOperators": ["+", "-", "/", "*", "=", "==", "===", "!=", "!=="], - - "requireSpaceAfterBinaryOperators": ["+", "-", "/", "*", "=", "==", "===", "!=", "!=="], - "disallowSpaceAfterBinaryOperators": [], - - "disallowImplicitTypeConversion": ["binary", "string"], - - "disallowKeywords": ["with", "eval"], - - "requireKeywordsOnNewLine": [], - "disallowKeywordsOnNewLine": ["else"], - - "requireLineFeedAtFileEnd": true, - - "disallowTrailingWhitespace": true, - - "disallowTrailingComma": true, - - "excludeFiles": ["node_modules/**", "vendor/**"], - - "disallowMultipleLineStrings": true, - - "requireDotNotation": { "allExcept": ["keywords"] }, - - "requireParenthesesAroundIIFE": true, - - "validateLineBreaks": "LF", - - "validateQuoteMarks": { - "escape": true, - "mark": "'" - }, - - "disallowOperatorBeforeLineBreak": [], - - "requireSpaceBeforeKeywords": [ - "do", - "for", - "if", - "else", - "switch", - "case", - "try", - "catch", - "finally", - "while", - "with", - "return" - ], - - "validateAlignedFunctionParameters": { - "lineBreakAfterOpeningBraces": true, - "lineBreakBeforeClosingBraces": true - }, - - "requirePaddingNewLinesBeforeExport": true, - - "validateNewlineAfterArrayElements": { - "maximum": 1 - }, - - "requirePaddingNewLinesAfterUseStrict": true, - - "disallowArrowFunctions": true, - - "disallowMultiLineTernary": true, - - "validateOrderInObjectKeys": "asc-insensitive", - - "disallowIdenticalDestructuringNames": true, - - "disallowNestedTernaries": { "maxLevel": 1 }, - - "requireSpaceAfterComma": { "allExcept": ["trailing"] }, - "requireAlignedMultilineParams": false, - - "requireSpacesInGenerator": { - "afterStar": true - }, - - "disallowSpacesInGenerator": { - "beforeStar": true - }, - - "disallowVar": false, - - "requireArrayDestructuring": false, - - "requireEnhancedObjectLiterals": false, - - "requireObjectDestructuring": false, - - "requireEarlyReturn": false, - - "requireCapitalizedConstructorsNew": { - "allExcept": ["Function", "String", "Object", "Symbol", "Number", "Date", "RegExp", "Error", "Boolean", "Array"] - }, - - "requireImportAlphabetized": false, - - "requireSpaceBeforeObjectValues": true, - "requireSpaceBeforeDestructuredValues": true, - - "disallowSpacesInsideTemplateStringPlaceholders": true, - - "disallowArrayDestructuringReturn": false, - - "requireNewlineBeforeSingleStatementsInIf": false, - - "disallowUnusedVariables": true, - - "requireSpacesInsideImportedObjectBraces": true, - - "requireUseStrict": true -} - diff --git a/scripts/2.5/node_modules/is-arguments/.travis.yml b/scripts/2.5/node_modules/is-arguments/.travis.yml deleted file mode 100644 index db517853..00000000 --- a/scripts/2.5/node_modules/is-arguments/.travis.yml +++ /dev/null @@ -1,248 +0,0 @@ -language: node_js -os: - - linux -node_js: - - "11.1" - - "10.13" - - "9.11" - - "8.12" - - "7.10" - - "6.14" - - "5.12" - - "4.9" - - "iojs-v3.3" - - "iojs-v2.5" - - "iojs-v1.8" - - "0.12" - - "0.10" - - "0.8" -before_install: - - 'case "${TRAVIS_NODE_VERSION}" in 0.*) export NPM_CONFIG_STRICT_SSL=false ;; esac' - - 'nvm install-latest-npm' -install: - - 'if [ "${TRAVIS_NODE_VERSION}" = "0.6" ] || [ "${TRAVIS_NODE_VERSION}" = "0.9" ]; then nvm install --latest-npm 0.8 && npm install && nvm use "${TRAVIS_NODE_VERSION}"; else npm install; fi;' -script: - - 'if [ -n "${PRETEST-}" ]; then npm run pretest ; fi' - - 'if [ -n "${POSTTEST-}" ]; then npm run posttest ; fi' - - 'if [ -n "${COVERAGE-}" ]; then npm run coverage ; fi' - - 'if [ -n "${TEST-}" ]; then npm run tests-only ; fi' -sudo: false -env: - - TEST=true -matrix: - fast_finish: true - include: - - node_js: "lts/*" - env: PRETEST=true - - node_js: "lts/*" - env: POSTTEST=true - - node_js: "4" - env: COVERAGE=true - - node_js: "11.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.12" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.11" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.10" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.10" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.11" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.10" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.13" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.12" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.11" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.10" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.11" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.10" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v3.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v3.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v3.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "0.11" - env: TEST=true ALLOW_FAILURE=true - - node_js: "0.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "0.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "0.4" - env: TEST=true ALLOW_FAILURE=true - allow_failures: - - os: osx - - env: TEST=true ALLOW_FAILURE=true - - env: COVERAGE=true diff --git a/scripts/2.5/node_modules/is-arguments/CHANGELOG.md b/scripts/2.5/node_modules/is-arguments/CHANGELOG.md deleted file mode 100644 index 8e2a361a..00000000 --- a/scripts/2.5/node_modules/is-arguments/CHANGELOG.md +++ /dev/null @@ -1,32 +0,0 @@ -1.0.4 / 2018-11-05 -================== - * [Fix] Fix errors about `in` operator (#22) - -1.0.3 / 2018-11-02 -================== - * [Fix] add awareness of Symbol.toStringTag (#20) - * [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape`, `jscs`, `nsp` - * [Tests] up to `node` `v11.1`, `v10.13`, `v9.11`, `v8.12`, `v7.10`, `v6.14`, `v5.11`, `v4.8`; use `nvm install-latest-npm`; pin included builds to LTS. - -1.0.2 / 2015-09-21 -================== - * [Docs] Switch from vb.teelaun.ch to versionbadg.es for the npm version badge SVG. - * [Enhancement] In modern engines, only export the "is standard arguments" check. - * [Fix] `toString` as a variable name breaks in some older browsers. - * [Dev Deps] update `covert`, `jscs`, `eslint` - * [Tests] up to `io.js` `v3.3`, `node` `v4.1` - -1.0.1 / 2015-04-29 -================== - * [Docs] clean up README; add badges - * [Dev Deps] update `tape`, `covert` - * [Tests] add `npm run lint` - -1.0.0 / 2014-01-14 -================== - * Bump to v1.0 - -0.1.0 / 2014-01-14 -================== - * Initial release. - diff --git a/scripts/2.5/node_modules/is-arguments/LICENSE b/scripts/2.5/node_modules/is-arguments/LICENSE deleted file mode 100644 index 47b7b507..00000000 --- a/scripts/2.5/node_modules/is-arguments/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014 Jordan Harband - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software is furnished to do so, -subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS -FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR -COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/scripts/2.5/node_modules/is-arguments/README.md b/scripts/2.5/node_modules/is-arguments/README.md deleted file mode 100644 index b5353bc3..00000000 --- a/scripts/2.5/node_modules/is-arguments/README.md +++ /dev/null @@ -1,49 +0,0 @@ -#is-arguments [![Version Badge][2]][1] - -[![Build Status][3]][4] -[![dependency status][5]][6] -[![dev dependency status][7]][8] -[![License][license-image]][license-url] -[![Downloads][downloads-image]][downloads-url] - -[![npm badge][11]][1] - -[![browser support][9]][10] - -Is this an arguments object? It's a harder question than you think. - -## Example - -```js -var isArguments = require('is-arguments'); -var assert = require('assert'); - -assert.equal(isArguments({}), false); -assert.equal(isArguments([]), false); -(function () { - assert.equal(isArguments(arguments), true); -}()) -``` - -## Caveats -If you have modified an actual `arguments` object by giving it a `Symbol.toStringTag` property, then this package will return `false`. - -## Tests -Simply clone the repo, `npm install`, and run `npm test` - -[1]: https://npmjs.org/package/is-arguments -[2]: http://versionbadg.es/ljharb/is-arguments.svg -[3]: https://travis-ci.org/ljharb/is-arguments.svg -[4]: https://travis-ci.org/ljharb/is-arguments -[5]: https://david-dm.org/ljharb/is-arguments.svg -[6]: https://david-dm.org/ljharb/is-arguments -[7]: https://david-dm.org/ljharb/is-arguments/dev-status.svg -[8]: https://david-dm.org/ljharb/is-arguments#info=devDependencies -[9]: https://ci.testling.com/ljharb/is-arguments.png -[10]: https://ci.testling.com/ljharb/is-arguments -[11]: https://nodei.co/npm/is-arguments.png?downloads=true&stars=true -[license-image]: http://img.shields.io/npm/l/is-arguments.svg -[license-url]: LICENSE -[downloads-image]: http://img.shields.io/npm/dm/is-arguments.svg -[downloads-url]: http://npm-stat.com/charts.html?package=is-arguments - diff --git a/scripts/2.5/node_modules/is-arguments/index.js b/scripts/2.5/node_modules/is-arguments/index.js deleted file mode 100644 index 84cc200f..00000000 --- a/scripts/2.5/node_modules/is-arguments/index.js +++ /dev/null @@ -1,31 +0,0 @@ -'use strict'; - -var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol'; -var toStr = Object.prototype.toString; - -var isStandardArguments = function isArguments(value) { - if (hasToStringTag && value && typeof value === 'object' && Symbol.toStringTag in value) { - return false; - } - return toStr.call(value) === '[object Arguments]'; -}; - -var isLegacyArguments = function isArguments(value) { - if (isStandardArguments(value)) { - return true; - } - return value !== null && - typeof value === 'object' && - typeof value.length === 'number' && - value.length >= 0 && - toStr.call(value) !== '[object Array]' && - toStr.call(value.callee) === '[object Function]'; -}; - -var supportsStandardArguments = (function () { - return isStandardArguments(arguments); -}()); - -isStandardArguments.isLegacyArguments = isLegacyArguments; // for tests - -module.exports = supportsStandardArguments ? isStandardArguments : isLegacyArguments; diff --git a/scripts/2.5/node_modules/is-arguments/package.json b/scripts/2.5/node_modules/is-arguments/package.json deleted file mode 100644 index e754d7d3..00000000 --- a/scripts/2.5/node_modules/is-arguments/package.json +++ /dev/null @@ -1,101 +0,0 @@ -{ - "_from": "is-arguments@^1.0.4", - "_id": "is-arguments@1.0.4", - "_inBundle": false, - "_integrity": "sha512-xPh0Rmt8NE65sNzvyUmWgI1tz3mKq74lGA0mL8LYZcoIzKOzDh6HmrYm3d18k60nHerC8A9Km8kYu87zfSFnLA==", - "_location": "/is-arguments", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "is-arguments@^1.0.4", - "name": "is-arguments", - "escapedName": "is-arguments", - "rawSpec": "^1.0.4", - "saveSpec": null, - "fetchSpec": "^1.0.4" - }, - "_requiredBy": [ - "/util" - ], - "_resolved": "https://registry.npmjs.org/is-arguments/-/is-arguments-1.0.4.tgz", - "_shasum": "3faf966c7cba0ff437fb31f6250082fcf0448cf3", - "_spec": "is-arguments@^1.0.4", - "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/2.5/node_modules/util", - "author": { - "name": "Jordan Harband", - "email": "ljharb@gmail.com", - "url": "http://ljharb.codes" - }, - "bugs": { - "url": "https://github.com/ljharb/is-arguments/issues" - }, - "bundleDependencies": false, - "contributors": [ - { - "name": "Jordan Harband", - "email": "ljharb@gmail.com", - "url": "http://ljharb.codes" - } - ], - "dependencies": {}, - "deprecated": false, - "description": "Is this an arguments object? It's a harder question than you think.", - "devDependencies": { - "@ljharb/eslint-config": "^13.0.0", - "covert": "^1.1.0", - "eslint": "^5.8.0", - "jscs": "^3.0.7", - "nsp": "^3.2.1", - "tape": "^4.9.1" - }, - "engines": { - "node": ">= 0.4" - }, - "homepage": "https://github.com/ljharb/is-arguments", - "keywords": [ - "arguments", - "js", - "javascript", - "is-arguments", - "is", - "object" - ], - "license": "MIT", - "main": "index.js", - "name": "is-arguments", - "repository": { - "type": "git", - "url": "git://github.com/ljharb/is-arguments.git" - }, - "scripts": { - "coverage": "covert test.js", - "eslint": "eslint *.js", - "jscs": "jscs *.js", - "lint": "npm run --silent jscs && npm run --silent eslint", - "posttest": "npm run --silent security", - "pretest": "npm run --silent lint", - "security": "nsp check", - "test": "npm run --silent tests-only", - "tests-only": "node test.js" - }, - "testling": { - "files": "test.js", - "browsers": [ - "iexplore/6.0..latest", - "firefox/3.0..6.0", - "firefox/15.0..latest", - "firefox/nightly", - "chrome/4.0..10.0", - "chrome/20.0..latest", - "chrome/canary", - "opera/10.0..latest", - "opera/next", - "safari/4.0..latest", - "ipad/6.0..latest", - "iphone/6.0..latest", - "android-browser/4.2" - ] - }, - "version": "1.0.4" -} diff --git a/scripts/2.5/node_modules/is-arguments/test.js b/scripts/2.5/node_modules/is-arguments/test.js deleted file mode 100644 index fca78d83..00000000 --- a/scripts/2.5/node_modules/is-arguments/test.js +++ /dev/null @@ -1,44 +0,0 @@ -'use strict'; - -var test = require('tape'); -var isArguments = require('./'); -var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol'; - -test('primitives', function (t) { - t.notOk(isArguments([]), 'array is not arguments'); - t.notOk(isArguments({}), 'object is not arguments'); - t.notOk(isArguments(''), 'empty string is not arguments'); - t.notOk(isArguments('foo'), 'string is not arguments'); - t.notOk(isArguments({ length: 2 }), 'naive array-like is not arguments'); - t.end(); -}); - -test('arguments object', function (t) { - t.ok(isArguments(arguments), 'arguments is arguments'); - t.notOk(isArguments(Array.prototype.slice.call(arguments)), 'sliced arguments is not arguments'); - t.end(); -}); - -test('old-style arguments object', function (t) { - var isLegacyArguments = isArguments.isLegacyArguments || isArguments; - var fakeOldArguments = { - callee: function () {}, - length: 3 - }; - t.ok(isLegacyArguments(fakeOldArguments), 'old-style arguments is arguments'); - t.end(); -}); - -test('Symbol.toStringTag', { skip: !hasToStringTag }, function (t) { - var obj = {}; - obj[Symbol.toStringTag] = 'Arguments'; - t.notOk(isArguments(obj), 'object with faked toStringTag is not arguments'); - - var args = (function () { - return arguments; - }()); - args[Symbol.toStringTag] = 'Arguments'; - t.notOk(isArguments(obj), 'real arguments with faked toStringTag is not arguments'); - - t.end(); -}); diff --git a/scripts/2.5/node_modules/is-callable/.editorconfig b/scripts/2.5/node_modules/is-callable/.editorconfig deleted file mode 100644 index bc228f82..00000000 --- a/scripts/2.5/node_modules/is-callable/.editorconfig +++ /dev/null @@ -1,20 +0,0 @@ -root = true - -[*] -indent_style = tab -indent_size = 4 -end_of_line = lf -charset = utf-8 -trim_trailing_whitespace = true -insert_final_newline = true -max_line_length = 150 - -[CHANGELOG.md] -indent_style = space -indent_size = 2 - -[*.json] -max_line_length = off - -[Makefile] -max_line_length = off diff --git a/scripts/2.5/node_modules/is-callable/.eslintrc b/scripts/2.5/node_modules/is-callable/.eslintrc deleted file mode 100644 index db619b50..00000000 --- a/scripts/2.5/node_modules/is-callable/.eslintrc +++ /dev/null @@ -1,11 +0,0 @@ -{ - "root": true, - - "extends": "@ljharb", - - "rules": { - "id-length": 0, - "max-statements": [2, 12], - "max-statements-per-line": [2, { "max": 2 }] - } -} diff --git a/scripts/2.5/node_modules/is-callable/.istanbul.yml b/scripts/2.5/node_modules/is-callable/.istanbul.yml deleted file mode 100644 index 9affe0bc..00000000 --- a/scripts/2.5/node_modules/is-callable/.istanbul.yml +++ /dev/null @@ -1,47 +0,0 @@ -verbose: false -instrumentation: - root: . - extensions: - - .js - - .jsx - default-excludes: true - excludes: [] - variable: __coverage__ - compact: true - preserve-comments: false - complete-copy: false - save-baseline: false - baseline-file: ./coverage/coverage-baseline.raw.json - include-all-sources: false - include-pid: false - es-modules: false - auto-wrap: false -reporting: - print: summary - reports: - - html - dir: ./coverage - summarizer: pkg - report-config: {} - watermarks: - statements: [50, 80] - functions: [50, 80] - branches: [50, 80] - lines: [50, 80] -hooks: - hook-run-in-context: false - post-require-hook: null - handle-sigint: false -check: - global: - statements: 100 - lines: 100 - branches: 100 - functions: 100 - excludes: [] - each: - statements: 100 - lines: 100 - branches: 100 - functions: 100 - excludes: [] diff --git a/scripts/2.5/node_modules/is-callable/.jscs.json b/scripts/2.5/node_modules/is-callable/.jscs.json deleted file mode 100644 index b4d9b8b4..00000000 --- a/scripts/2.5/node_modules/is-callable/.jscs.json +++ /dev/null @@ -1,176 +0,0 @@ -{ - "es3": true, - - "additionalRules": [], - - "requireSemicolons": true, - - "disallowMultipleSpaces": true, - - "disallowIdentifierNames": [], - - "requireCurlyBraces": { - "allExcept": [], - "keywords": ["if", "else", "for", "while", "do", "try", "catch"] - }, - - "requireSpaceAfterKeywords": ["if", "else", "for", "while", "do", "switch", "return", "try", "catch", "function"], - - "disallowSpaceAfterKeywords": [], - - "disallowSpaceBeforeComma": true, - "disallowSpaceAfterComma": false, - "disallowSpaceBeforeSemicolon": true, - - "disallowNodeTypes": [ - "DebuggerStatement", - "ForInStatement", - "LabeledStatement", - "SwitchCase", - "SwitchStatement", - "WithStatement" - ], - - "requireObjectKeysOnNewLine": { "allExcept": ["sameLine"] }, - - "requireSpacesInAnonymousFunctionExpression": { "beforeOpeningRoundBrace": true, "beforeOpeningCurlyBrace": true }, - "requireSpacesInNamedFunctionExpression": { "beforeOpeningCurlyBrace": true }, - "disallowSpacesInNamedFunctionExpression": { "beforeOpeningRoundBrace": true }, - "requireSpacesInFunctionDeclaration": { "beforeOpeningCurlyBrace": true }, - "disallowSpacesInFunctionDeclaration": { "beforeOpeningRoundBrace": true }, - - "requireSpaceBetweenArguments": true, - - "disallowSpacesInsideParentheses": true, - - "disallowSpacesInsideArrayBrackets": true, - - "disallowQuotedKeysInObjects": { "allExcept": ["reserved"] }, - - "disallowSpaceAfterObjectKeys": true, - - "requireCommaBeforeLineBreak": true, - - "disallowSpaceAfterPrefixUnaryOperators": ["++", "--", "+", "-", "~", "!"], - "requireSpaceAfterPrefixUnaryOperators": [], - - "disallowSpaceBeforePostfixUnaryOperators": ["++", "--"], - "requireSpaceBeforePostfixUnaryOperators": [], - - "disallowSpaceBeforeBinaryOperators": [], - "requireSpaceBeforeBinaryOperators": ["+", "-", "/", "*", "=", "==", "===", "!=", "!=="], - - "requireSpaceAfterBinaryOperators": ["+", "-", "/", "*", "=", "==", "===", "!=", "!=="], - "disallowSpaceAfterBinaryOperators": [], - - "disallowImplicitTypeConversion": ["binary", "string"], - - "disallowKeywords": ["with", "eval"], - - "requireKeywordsOnNewLine": [], - "disallowKeywordsOnNewLine": ["else"], - - "requireLineFeedAtFileEnd": true, - - "disallowTrailingWhitespace": true, - - "disallowTrailingComma": true, - - "excludeFiles": ["node_modules/**", "vendor/**"], - - "disallowMultipleLineStrings": true, - - "requireDotNotation": { "allExcept": ["keywords"] }, - - "requireParenthesesAroundIIFE": true, - - "validateLineBreaks": "LF", - - "validateQuoteMarks": { - "escape": true, - "mark": "'" - }, - - "disallowOperatorBeforeLineBreak": [], - - "requireSpaceBeforeKeywords": [ - "do", - "for", - "if", - "else", - "switch", - "case", - "try", - "catch", - "finally", - "while", - "with", - "return" - ], - - "validateAlignedFunctionParameters": { - "lineBreakAfterOpeningBraces": true, - "lineBreakBeforeClosingBraces": true - }, - - "requirePaddingNewLinesBeforeExport": true, - - "validateNewlineAfterArrayElements": { - "maximum": 1 - }, - - "requirePaddingNewLinesAfterUseStrict": true, - - "disallowArrowFunctions": true, - - "disallowMultiLineTernary": true, - - "validateOrderInObjectKeys": "asc-insensitive", - - "disallowIdenticalDestructuringNames": true, - - "disallowNestedTernaries": { "maxLevel": 1 }, - - "requireSpaceAfterComma": { "allExcept": ["trailing"] }, - "requireAlignedMultilineParams": false, - - "requireSpacesInGenerator": { - "afterStar": true - }, - - "disallowSpacesInGenerator": { - "beforeStar": true - }, - - "disallowVar": false, - - "requireArrayDestructuring": false, - - "requireEnhancedObjectLiterals": false, - - "requireObjectDestructuring": false, - - "requireEarlyReturn": false, - - "requireCapitalizedConstructorsNew": { - "allExcept": ["Function", "String", "Object", "Symbol", "Number", "Date", "RegExp", "Error", "Boolean", "Array"] - }, - - "requireImportAlphabetized": false, - - "requireSpaceBeforeObjectValues": true, - "requireSpaceBeforeDestructuredValues": true, - - "disallowSpacesInsideTemplateStringPlaceholders": true, - - "disallowArrayDestructuringReturn": false, - - "requireNewlineBeforeSingleStatementsInIf": false, - - "disallowUnusedVariables": true, - - "requireSpacesInsideImportedObjectBraces": true, - - "requireUseStrict": true -} - diff --git a/scripts/2.5/node_modules/is-callable/.travis.yml b/scripts/2.5/node_modules/is-callable/.travis.yml deleted file mode 100644 index 767256c8..00000000 --- a/scripts/2.5/node_modules/is-callable/.travis.yml +++ /dev/null @@ -1,225 +0,0 @@ -language: node_js -os: - - linux -node_js: - - "10.4" - - "9.11" - - "8.11" - - "7.10" - - "6.14" - - "5.12" - - "4.9" - - "iojs-v3.3" - - "iojs-v2.5" - - "iojs-v1.8" - - "0.12" - - "0.10" - - "0.8" -before_install: - - 'case "${TRAVIS_NODE_VERSION}" in 0.*) export NPM_CONFIG_STRICT_SSL=false ;; esac' - - 'nvm install-latest-npm' -install: - - 'if [ "${TRAVIS_NODE_VERSION}" = "0.6" ] || [ "${TRAVIS_NODE_VERSION}" = "0.9" ]; then nvm install --latest-npm 0.8 && npm install && nvm use "${TRAVIS_NODE_VERSION}"; else npm install; fi;' -script: - - 'if [ -n "${PRETEST-}" ]; then npm run pretest ; fi' - - 'if [ -n "${POSTTEST-}" ]; then npm run posttest ; fi' - - 'if [ -n "${COVERAGE-}" ]; then npm run coverage ; fi' - - 'if [ -n "${TEST-}" ]; then npm run tests-only ; fi' -sudo: false -env: - - TEST=true -matrix: - fast_finish: true - include: - - node_js: "lts/*" - env: PRETEST=true - - node_js: "lts/*" - env: POSTTEST=true - - node_js: "4" - env: COVERAGE=true - - node_js: "10.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.10" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.10" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.13" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.12" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.11" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.10" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.11" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.10" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v3.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v3.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v3.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "0.11" - env: TEST=true ALLOW_FAILURE=true - - node_js: "0.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "0.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "0.4" - env: TEST=true ALLOW_FAILURE=true - allow_failures: - - os: osx - - env: TEST=true ALLOW_FAILURE=true - - env: COVERAGE=true diff --git a/scripts/2.5/node_modules/is-callable/CHANGELOG.md b/scripts/2.5/node_modules/is-callable/CHANGELOG.md deleted file mode 100644 index 58286a05..00000000 --- a/scripts/2.5/node_modules/is-callable/CHANGELOG.md +++ /dev/null @@ -1,56 +0,0 @@ -1.1.4 / 2018-07-02 -================= - * [Fix] improve `class` and arrow function detection (#30, #31) - * [Tests] on all latest node minors; improve matrix - * [Dev Deps] update all dev deps - -1.1.3 / 2016-02-27 -================= - * [Fix] ensure “class “ doesn’t screw up “class” detection - * [Tests] up to `node` `v5.7`, `v4.3` - * [Dev Deps] update to `eslint` v2, `@ljharb/eslint-config`, `jscs` - -1.1.2 / 2016-01-15 -================= - * [Fix] Make sure comments don’t screw up “class” detection (#4) - * [Tests] up to `node` `v5.3` - * [Tests] Add `parallelshell`, run both `--es-staging` and stock tests at once - * [Dev Deps] update `tape`, `jscs`, `nsp`, `eslint`, `@ljharb/eslint-config` - * [Refactor] convert `isNonES6ClassFn` into `isES6ClassFn` - -1.1.1 / 2015-11-30 -================= - * [Fix] do not throw when a non-function has a function in its [[Prototype]] (#2) - * [Dev Deps] update `tape`, `eslint`, `@ljharb/eslint-config`, `jscs`, `nsp`, `semver` - * [Tests] up to `node` `v5.1` - * [Tests] no longer allow node 0.8 to fail. - * [Tests] fix npm upgrades in older nodes - -1.1.0 / 2015-10-02 -================= - * [Fix] Some browsers report TypedArray constructors as `typeof object` - * [New] return false for "class" constructors, when possible. - * [Tests] up to `io.js` `v3.3`, `node` `v4.1` - * [Dev Deps] update `eslint`, `editorconfig-tools`, `nsp`, `tape`, `semver`, `jscs`, `covert`, `make-arrow-function` - * [Docs] Switch from vb.teelaun.ch to versionbadg.es for the npm version badge SVG - -1.0.4 / 2015-01-30 -================= - * If @@toStringTag is not present, use the old-school Object#toString test. - -1.0.3 / 2015-01-29 -================= - * Add tests to ensure arrow functions are callable. - * Refactor to aid optimization of non-try/catch code. - -1.0.2 / 2015-01-29 -================= - * Fix broken package.json - -1.0.1 / 2015-01-29 -================= - * Add early exit for typeof not "function" - -1.0.0 / 2015-01-29 -================= - * Initial release. diff --git a/scripts/2.5/node_modules/is-callable/LICENSE b/scripts/2.5/node_modules/is-callable/LICENSE deleted file mode 100644 index b43df444..00000000 --- a/scripts/2.5/node_modules/is-callable/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015 Jordan Harband - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - diff --git a/scripts/2.5/node_modules/is-callable/Makefile b/scripts/2.5/node_modules/is-callable/Makefile deleted file mode 100644 index b9e4fe1a..00000000 --- a/scripts/2.5/node_modules/is-callable/Makefile +++ /dev/null @@ -1,61 +0,0 @@ -# Since we rely on paths relative to the makefile location, abort if make isn't being run from there. -$(if $(findstring /,$(MAKEFILE_LIST)),$(error Please only invoke this makefile from the directory it resides in)) - - # The files that need updating when incrementing the version number. -VERSIONED_FILES := *.js *.json README* - - -# Add the local npm packages' bin folder to the PATH, so that `make` can find them, when invoked directly. -# Note that rather than using `$(npm bin)` the 'node_modules/.bin' path component is hard-coded, so that invocation works even from an environment -# where npm is (temporarily) unavailable due to having deactivated an nvm instance loaded into the calling shell in order to avoid interference with tests. -export PATH := $(shell printf '%s' "$$PWD/node_modules/.bin:$$PATH") -UTILS := semver -# Make sure that all required utilities can be located. -UTIL_CHECK := $(or $(shell PATH="$(PATH)" which $(UTILS) >/dev/null && echo 'ok'),$(error Did you forget to run `npm install` after cloning the repo? At least one of the required supporting utilities not found: $(UTILS))) - -# Default target (by virtue of being the first non '.'-prefixed in the file). -.PHONY: _no-target-specified -_no-target-specified: - $(error Please specify the target to make - `make list` shows targets. Alternatively, use `npm test` to run the default tests; `npm run` shows all tests) - -# Lists all targets defined in this makefile. -.PHONY: list -list: - @$(MAKE) -pRrn : -f $(MAKEFILE_LIST) 2>/dev/null | awk -v RS= -F: '/^# File/,/^# Finished Make data base/ {if ($$1 !~ "^[#.]") {print $$1}}' | command grep -v -e '^[^[:alnum:]]' -e '^$@$$command ' | sort - -# All-tests target: invokes the specified test suites for ALL shells defined in $(SHELLS). -.PHONY: test -test: - @npm test - -.PHONY: _ensure-tag -_ensure-tag: -ifndef TAG - $(error Please invoke with `make TAG= release`, where is either an increment specifier (patch, minor, major, prepatch, preminor, premajor, prerelease), or an explicit major.minor.patch version number) -endif - -CHANGELOG_ERROR = $(error No CHANGELOG specified) -.PHONY: _ensure-changelog -_ensure-changelog: - @ (git status -sb --porcelain | command grep -E '^( M|[MA] ) CHANGELOG.md' > /dev/null) || (echo no CHANGELOG.md specified && exit 2) - -# Ensures that the git workspace is clean. -.PHONY: _ensure-clean -_ensure-clean: - @[ -z "$$((git status --porcelain --untracked-files=no || echo err) | command grep -v 'CHANGELOG.md')" ] || { echo "Workspace is not clean; please commit changes first." >&2; exit 2; } - -# Makes a release; invoke with `make TAG= release`. -.PHONY: release -release: _ensure-tag _ensure-changelog _ensure-clean - @old_ver=`git describe --abbrev=0 --tags --match 'v[0-9]*.[0-9]*.[0-9]*'` || { echo "Failed to determine current version." >&2; exit 1; }; old_ver=$${old_ver#v}; \ - new_ver=`echo "$(TAG)" | sed 's/^v//'`; new_ver=$${new_ver:-patch}; \ - if printf "$$new_ver" | command grep -q '^[0-9]'; then \ - semver "$$new_ver" >/dev/null || { echo 'Invalid version number specified: $(TAG) - must be major.minor.patch' >&2; exit 2; }; \ - semver -r "> $$old_ver" "$$new_ver" >/dev/null || { echo 'Invalid version number specified: $(TAG) - must be HIGHER than current one.' >&2; exit 2; } \ - else \ - new_ver=`semver -i "$$new_ver" "$$old_ver"` || { echo 'Invalid version-increment specifier: $(TAG)' >&2; exit 2; } \ - fi; \ - printf "=== Bumping version **$$old_ver** to **$$new_ver** before committing and tagging:\n=== TYPE 'proceed' TO PROCEED, anything else to abort: " && read response && [ "$$response" = 'proceed' ] || { echo 'Aborted.' >&2; exit 2; }; \ - replace "$$old_ver" "$$new_ver" -- $(VERSIONED_FILES) && \ - git commit -m "v$$new_ver" $(VERSIONED_FILES) CHANGELOG.md && \ - git tag -a -m "v$$new_ver" "v$$new_ver" diff --git a/scripts/2.5/node_modules/is-callable/README.md b/scripts/2.5/node_modules/is-callable/README.md deleted file mode 100644 index 0cb65879..00000000 --- a/scripts/2.5/node_modules/is-callable/README.md +++ /dev/null @@ -1,59 +0,0 @@ -# is-callable [![Version Badge][2]][1] - -[![Build Status][3]][4] -[![dependency status][5]][6] -[![dev dependency status][7]][8] -[![License][license-image]][license-url] -[![Downloads][downloads-image]][downloads-url] - -[![npm badge][11]][1] - -[![browser support][9]][10] - -Is this JS value callable? Works with Functions and GeneratorFunctions, despite ES6 @@toStringTag. - -## Example - -```js -var isCallable = require('is-callable'); -var assert = require('assert'); - -assert.notOk(isCallable(undefined)); -assert.notOk(isCallable(null)); -assert.notOk(isCallable(false)); -assert.notOk(isCallable(true)); -assert.notOk(isCallable([])); -assert.notOk(isCallable({})); -assert.notOk(isCallable(/a/g)); -assert.notOk(isCallable(new RegExp('a', 'g'))); -assert.notOk(isCallable(new Date())); -assert.notOk(isCallable(42)); -assert.notOk(isCallable(NaN)); -assert.notOk(isCallable(Infinity)); -assert.notOk(isCallable(new Number(42))); -assert.notOk(isCallable('foo')); -assert.notOk(isCallable(Object('foo'))); - -assert.ok(isCallable(function () {})); -assert.ok(isCallable(function* () {})); -assert.ok(isCallable(x => x * x)); -``` - -## Tests -Simply clone the repo, `npm install`, and run `npm test` - -[1]: https://npmjs.org/package/is-callable -[2]: http://versionbadg.es/ljharb/is-callable.svg -[3]: https://travis-ci.org/ljharb/is-callable.svg -[4]: https://travis-ci.org/ljharb/is-callable -[5]: https://david-dm.org/ljharb/is-callable.svg -[6]: https://david-dm.org/ljharb/is-callable -[7]: https://david-dm.org/ljharb/is-callable/dev-status.svg -[8]: https://david-dm.org/ljharb/is-callable#info=devDependencies -[9]: https://ci.testling.com/ljharb/is-callable.png -[10]: https://ci.testling.com/ljharb/is-callable -[11]: https://nodei.co/npm/is-callable.png?downloads=true&stars=true -[license-image]: http://img.shields.io/npm/l/is-callable.svg -[license-url]: LICENSE -[downloads-image]: http://img.shields.io/npm/dm/is-callable.svg -[downloads-url]: http://npm-stat.com/charts.html?package=is-callable diff --git a/scripts/2.5/node_modules/is-callable/index.js b/scripts/2.5/node_modules/is-callable/index.js deleted file mode 100644 index d9820b51..00000000 --- a/scripts/2.5/node_modules/is-callable/index.js +++ /dev/null @@ -1,37 +0,0 @@ -'use strict'; - -var fnToStr = Function.prototype.toString; - -var constructorRegex = /^\s*class\b/; -var isES6ClassFn = function isES6ClassFunction(value) { - try { - var fnStr = fnToStr.call(value); - return constructorRegex.test(fnStr); - } catch (e) { - return false; // not a function - } -}; - -var tryFunctionObject = function tryFunctionToStr(value) { - try { - if (isES6ClassFn(value)) { return false; } - fnToStr.call(value); - return true; - } catch (e) { - return false; - } -}; -var toStr = Object.prototype.toString; -var fnClass = '[object Function]'; -var genClass = '[object GeneratorFunction]'; -var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol'; - -module.exports = function isCallable(value) { - if (!value) { return false; } - if (typeof value !== 'function' && typeof value !== 'object') { return false; } - if (typeof value === 'function' && !value.prototype) { return true; } - if (hasToStringTag) { return tryFunctionObject(value); } - if (isES6ClassFn(value)) { return false; } - var strClass = toStr.call(value); - return strClass === fnClass || strClass === genClass; -}; diff --git a/scripts/2.5/node_modules/is-callable/package.json b/scripts/2.5/node_modules/is-callable/package.json deleted file mode 100644 index 3ef5dc5d..00000000 --- a/scripts/2.5/node_modules/is-callable/package.json +++ /dev/null @@ -1,124 +0,0 @@ -{ - "_from": "is-callable@^1.1.4", - "_id": "is-callable@1.1.4", - "_inBundle": false, - "_integrity": "sha512-r5p9sxJjYnArLjObpjA4xu5EKI3CuKHkJXMhT7kwbpUyIFD1n5PMAsoPvWnvtZiNz7LjkYDRZhd7FlI0eMijEA==", - "_location": "/is-callable", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "is-callable@^1.1.4", - "name": "is-callable", - "escapedName": "is-callable", - "rawSpec": "^1.1.4", - "saveSpec": null, - "fetchSpec": "^1.1.4" - }, - "_requiredBy": [ - "/es-abstract", - "/es-to-primitive" - ], - "_resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.1.4.tgz", - "_shasum": "1e1adf219e1eeb684d691f9d6a05ff0d30a24d75", - "_spec": "is-callable@^1.1.4", - "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/2.5/node_modules/es-abstract", - "author": { - "name": "Jordan Harband", - "email": "ljharb@gmail.com", - "url": "http://ljharb.codes" - }, - "bugs": { - "url": "https://github.com/ljharb/is-callable/issues" - }, - "bundleDependencies": false, - "contributors": [ - { - "name": "Jordan Harband", - "email": "ljharb@gmail.com", - "url": "http://ljharb.codes" - } - ], - "dependencies": {}, - "deprecated": false, - "description": "Is this JS value callable? Works with Functions and GeneratorFunctions, despite ES6 @@toStringTag.", - "devDependencies": { - "@ljharb/eslint-config": "^12.2.1", - "covert": "^1.1.0", - "editorconfig-tools": "^0.1.1", - "eslint": "^4.19.1", - "foreach": "^2.0.5", - "istanbul": "1.1.0-alpha.1", - "istanbul-merge": "^1.1.1", - "jscs": "^3.0.7", - "make-arrow-function": "^1.1.0", - "make-generator-function": "^1.1.0", - "nsp": "^3.2.1", - "rimraf": "^2.6.2", - "semver": "^5.5.0", - "tape": "^4.9.1" - }, - "engines": { - "node": ">= 0.4" - }, - "homepage": "https://github.com/ljharb/is-callable#readme", - "keywords": [ - "Function", - "function", - "callable", - "generator", - "generator function", - "arrow", - "arrow function", - "ES6", - "toStringTag", - "@@toStringTag" - ], - "license": "MIT", - "main": "index.js", - "name": "is-callable", - "repository": { - "type": "git", - "url": "git://github.com/ljharb/is-callable.git" - }, - "scripts": { - "coverage": "npm run --silent istanbul", - "covert": "covert test.js", - "covert:quiet": "covert test.js --quiet", - "eslint": "eslint *.js", - "istanbul": "npm run --silent istanbul:clean && npm run --silent istanbul:std && npm run --silent istanbul:harmony && npm run --silent istanbul:merge && istanbul check", - "istanbul:clean": "rimraf coverage coverage-std coverage-harmony", - "istanbul:harmony": "node --harmony ./node_modules/istanbul/lib/cli.js cover test.js --dir coverage-harmony", - "istanbul:merge": "istanbul-merge --out coverage/coverage.raw.json coverage-harmony/coverage.raw.json coverage-std/coverage.raw.json && istanbul report html", - "istanbul:std": "istanbul cover test.js --report html --dir coverage-std", - "jscs": "jscs *.js", - "lint": "npm run jscs && npm run eslint", - "posttest": "npm run --silent security", - "prelint": "editorconfig-tools check *", - "pretest": "npm run --silent lint", - "security": "nsp check", - "test": "npm run --silent tests-only", - "test:staging": "node --es-staging test.js", - "test:stock": "node test.js", - "tests-only": "npm run --silent test:stock && npm run --silent test:staging" - }, - "testling": { - "files": "test.js", - "browsers": [ - "iexplore/6.0..latest", - "firefox/3.0..6.0", - "firefox/15.0..latest", - "firefox/nightly", - "chrome/4.0..10.0", - "chrome/20.0..latest", - "chrome/canary", - "opera/10.0..latest", - "opera/next", - "safari/4.0..latest", - "ipad/6.0..latest", - "iphone/6.0..latest", - "android-browser/4.2" - ] - }, - "version": "1.1.4" -} diff --git a/scripts/2.5/node_modules/is-callable/test.js b/scripts/2.5/node_modules/is-callable/test.js deleted file mode 100644 index f5be51d8..00000000 --- a/scripts/2.5/node_modules/is-callable/test.js +++ /dev/null @@ -1,158 +0,0 @@ -'use strict'; - -/* eslint no-magic-numbers: 1 */ - -var test = require('tape'); -var isCallable = require('./'); -var hasSymbols = typeof Symbol === 'function' && typeof Symbol('foo') === 'symbol'; -var genFn = require('make-generator-function'); -var arrowFn = require('make-arrow-function')(); -var weirdlyCommentedArrowFn; -var asyncFn; -var asyncArrowFn; -try { - /* eslint no-new-func: 0 */ - weirdlyCommentedArrowFn = Function('return cl/*/**/=>/**/ass - 1;')(); - asyncFn = Function('return async function foo() {};')(); - asyncArrowFn = Function('return async () => {};')(); -} catch (e) { /**/ } -var forEach = require('foreach'); - -var noop = function () {}; -var classFake = function classFake() { }; // eslint-disable-line func-name-matching -var returnClass = function () { return ' class '; }; -var return3 = function () { return 3; }; -/* for coverage */ -noop(); -classFake(); -returnClass(); -return3(); -/* end for coverage */ - -var invokeFunction = function invokeFunctionString(str) { - var result; - try { - /* eslint-disable no-new-func */ - var fn = Function(str); - /* eslint-enable no-new-func */ - result = fn(); - } catch (e) {} - return result; -}; - -var classConstructor = invokeFunction('"use strict"; return class Foo {}'); - -var commentedClass = invokeFunction('"use strict"; return class/*kkk*/\n//blah\n Bar\n//blah\n {}'); -var commentedClassOneLine = invokeFunction('"use strict"; return class/**/A{}'); -var classAnonymous = invokeFunction('"use strict"; return class{}'); -var classAnonymousCommentedOneLine = invokeFunction('"use strict"; return class/*/*/{}'); - -test('not callables', function (t) { - t.test('non-number/string primitives', function (st) { - st.notOk(isCallable(), 'undefined is not callable'); - st.notOk(isCallable(null), 'null is not callable'); - st.notOk(isCallable(false), 'false is not callable'); - st.notOk(isCallable(true), 'true is not callable'); - st.end(); - }); - - t.notOk(isCallable([]), 'array is not callable'); - t.notOk(isCallable({}), 'object is not callable'); - t.notOk(isCallable(/a/g), 'regex literal is not callable'); - t.notOk(isCallable(new RegExp('a', 'g')), 'regex object is not callable'); - t.notOk(isCallable(new Date()), 'new Date() is not callable'); - - t.test('numbers', function (st) { - st.notOk(isCallable(42), 'number is not callable'); - st.notOk(isCallable(Object(42)), 'number object is not callable'); - st.notOk(isCallable(NaN), 'NaN is not callable'); - st.notOk(isCallable(Infinity), 'Infinity is not callable'); - st.end(); - }); - - t.test('strings', function (st) { - st.notOk(isCallable('foo'), 'string primitive is not callable'); - st.notOk(isCallable(Object('foo')), 'string object is not callable'); - st.end(); - }); - - t.test('non-function with function in its [[Prototype]] chain', function (st) { - var Foo = function Bar() {}; - Foo.prototype = noop; - st.equal(true, isCallable(Foo), 'sanity check: Foo is callable'); - st.equal(false, isCallable(new Foo()), 'instance of Foo is not callable'); - st.end(); - }); - - t.end(); -}); - -test('@@toStringTag', { skip: !hasSymbols || !Symbol.toStringTag }, function (t) { - var fakeFunction = { - toString: function () { return String(return3); }, - valueOf: return3 - }; - fakeFunction[Symbol.toStringTag] = 'Function'; - t.equal(String(fakeFunction), String(return3)); - t.equal(Number(fakeFunction), return3()); - t.notOk(isCallable(fakeFunction), 'fake Function with @@toStringTag "Function" is not callable'); - t.end(); -}); - -var typedArrayNames = [ - 'Int8Array', - 'Uint8Array', - 'Uint8ClampedArray', - 'Int16Array', - 'Uint16Array', - 'Int32Array', - 'Uint32Array', - 'Float32Array', - 'Float64Array' -]; - -test('Functions', function (t) { - t.ok(isCallable(noop), 'function is callable'); - t.ok(isCallable(classFake), 'function with name containing "class" is callable'); - t.ok(isCallable(returnClass), 'function with string " class " is callable'); - t.ok(isCallable(isCallable), 'isCallable is callable'); - t.end(); -}); - -test('Typed Arrays', function (st) { - forEach(typedArrayNames, function (typedArray) { - /* istanbul ignore if : covered in node 0.6 */ - if (typeof global[typedArray] === 'undefined') { - st.comment('# SKIP typed array "' + typedArray + '" not supported'); - } else { - st.ok(isCallable(global[typedArray]), typedArray + ' is callable'); - } - }); - st.end(); -}); - -test('Generators', { skip: !genFn }, function (t) { - t.ok(isCallable(genFn), 'generator function is callable'); - t.end(); -}); - -test('Arrow functions', { skip: !arrowFn }, function (t) { - t.ok(isCallable(arrowFn), 'arrow function is callable'); - t.ok(isCallable(weirdlyCommentedArrowFn), 'weirdly commented arrow functions are callable'); - t.end(); -}); - -test('"Class" constructors', { skip: !classConstructor || !commentedClass || !commentedClassOneLine || !classAnonymous }, function (t) { - t.notOk(isCallable(classConstructor), 'class constructors are not callable'); - t.notOk(isCallable(commentedClass), 'class constructors with comments in the signature are not callable'); - t.notOk(isCallable(commentedClassOneLine), 'one-line class constructors with comments in the signature are not callable'); - t.notOk(isCallable(classAnonymous), 'anonymous class constructors are not callable'); - t.notOk(isCallable(classAnonymousCommentedOneLine), 'anonymous one-line class constructors with comments in the signature are not callable'); - t.end(); -}); - -test('`async function`s', { skip: !asyncFn }, function (t) { - t.ok(isCallable(asyncFn), '`async function`s are callable'); - t.ok(isCallable(asyncArrowFn), '`async` arrow functions are callable'); - t.end(); -}); diff --git a/scripts/2.5/node_modules/is-date-object/.eslintrc b/scripts/2.5/node_modules/is-date-object/.eslintrc deleted file mode 100644 index 1228f975..00000000 --- a/scripts/2.5/node_modules/is-date-object/.eslintrc +++ /dev/null @@ -1,9 +0,0 @@ -{ - "root": true, - - "extends": "@ljharb", - - "rules": { - "max-statements": [2, 12] - } -} diff --git a/scripts/2.5/node_modules/is-date-object/.jscs.json b/scripts/2.5/node_modules/is-date-object/.jscs.json deleted file mode 100644 index 040bb680..00000000 --- a/scripts/2.5/node_modules/is-date-object/.jscs.json +++ /dev/null @@ -1,122 +0,0 @@ -{ - "es3": true, - - "additionalRules": [], - - "requireSemicolons": true, - - "disallowMultipleSpaces": true, - - "disallowIdentifierNames": [], - - "requireCurlyBraces": ["if", "else", "for", "while", "do", "try", "catch"], - - "requireSpaceAfterKeywords": ["if", "else", "for", "while", "do", "switch", "return", "try", "catch", "function"], - - "disallowSpaceAfterKeywords": [], - - "disallowSpaceBeforeComma": true, - "disallowSpaceBeforeSemicolon": true, - - "disallowNodeTypes": [ - "DebuggerStatement", - "ForInStatement", - "LabeledStatement", - "SwitchCase", - "SwitchStatement", - "WithStatement" - ], - - "requireSpacesInAnonymousFunctionExpression": { "beforeOpeningRoundBrace": true, "beforeOpeningCurlyBrace": true }, - "requireSpacesInNamedFunctionExpression": { "beforeOpeningCurlyBrace": true }, - "disallowSpacesInNamedFunctionExpression": { "beforeOpeningRoundBrace": true }, - "requireSpacesInFunctionDeclaration": { "beforeOpeningCurlyBrace": true }, - "disallowSpacesInFunctionDeclaration": { "beforeOpeningRoundBrace": true }, - - "requireSpaceBetweenArguments": true, - - "disallowSpacesInsideParentheses": true, - - "disallowSpacesInsideArrayBrackets": true, - - "disallowQuotedKeysInObjects": "allButReserved", - - "disallowSpaceAfterObjectKeys": true, - - "requireCommaBeforeLineBreak": true, - - "disallowSpaceAfterPrefixUnaryOperators": ["++", "--", "+", "-", "~", "!"], - "requireSpaceAfterPrefixUnaryOperators": [], - - "disallowSpaceBeforePostfixUnaryOperators": ["++", "--"], - "requireSpaceBeforePostfixUnaryOperators": [], - - "disallowSpaceBeforeBinaryOperators": [], - "requireSpaceBeforeBinaryOperators": ["+", "-", "/", "*", "=", "==", "===", "!=", "!=="], - - "requireSpaceAfterBinaryOperators": ["+", "-", "/", "*", "=", "==", "===", "!=", "!=="], - "disallowSpaceAfterBinaryOperators": [], - - "disallowImplicitTypeConversion": ["binary", "string"], - - "disallowKeywords": ["with", "eval"], - - "requireKeywordsOnNewLine": [], - "disallowKeywordsOnNewLine": ["else"], - - "requireLineFeedAtFileEnd": true, - - "disallowTrailingWhitespace": true, - - "disallowTrailingComma": true, - - "excludeFiles": ["node_modules/**", "vendor/**"], - - "disallowMultipleLineStrings": true, - - "requireDotNotation": true, - - "requireParenthesesAroundIIFE": true, - - "validateLineBreaks": "LF", - - "validateQuoteMarks": { - "escape": true, - "mark": "'" - }, - - "disallowOperatorBeforeLineBreak": [], - - "requireSpaceBeforeKeywords": [ - "do", - "for", - "if", - "else", - "switch", - "case", - "try", - "catch", - "finally", - "while", - "with", - "return" - ], - - "validateAlignedFunctionParameters": { - "lineBreakAfterOpeningBraces": true, - "lineBreakBeforeClosingBraces": true - }, - - "requirePaddingNewLinesBeforeExport": true, - - "validateNewlineAfterArrayElements": { - "maximum": 1 - }, - - "requirePaddingNewLinesAfterUseStrict": true, - - "disallowArrowFunctions": true, - - "validateOrderInObjectKeys": "asc-insensitive" -} - diff --git a/scripts/2.5/node_modules/is-date-object/.npmignore b/scripts/2.5/node_modules/is-date-object/.npmignore deleted file mode 100644 index 59d842ba..00000000 --- a/scripts/2.5/node_modules/is-date-object/.npmignore +++ /dev/null @@ -1,28 +0,0 @@ -# Logs -logs -*.log - -# Runtime data -pids -*.pid -*.seed - -# Directory for instrumented libs generated by jscoverage/JSCover -lib-cov - -# Coverage directory used by tools like istanbul -coverage - -# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) -.grunt - -# Compiled binary addons (http://nodejs.org/api/addons.html) -build/Release - -# Dependency directory -# Commenting this out is preferred by some people, see -# https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git- -node_modules - -# Users Environment Variables -.lock-wscript diff --git a/scripts/2.5/node_modules/is-date-object/.travis.yml b/scripts/2.5/node_modules/is-date-object/.travis.yml deleted file mode 100644 index 4c29ed58..00000000 --- a/scripts/2.5/node_modules/is-date-object/.travis.yml +++ /dev/null @@ -1,58 +0,0 @@ -language: node_js -node_js: - - "4.1" - - "4.0" - - "iojs-v3.3" - - "iojs-v3.2" - - "iojs-v3.1" - - "iojs-v3.0" - - "iojs-v2.5" - - "iojs-v2.4" - - "iojs-v2.3" - - "iojs-v2.2" - - "iojs-v2.1" - - "iojs-v2.0" - - "iojs-v1.8" - - "iojs-v1.7" - - "iojs-v1.6" - - "iojs-v1.5" - - "iojs-v1.4" - - "iojs-v1.3" - - "iojs-v1.2" - - "iojs-v1.1" - - "iojs-v1.0" - - "0.12" - - "0.11" - - "0.10" - - "0.9" - - "0.8" - - "0.6" - - "0.4" -before_install: - - '[ "${TRAVIS_NODE_VERSION}" = "0.6" ] || npm install -g npm@1.4.28 && npm install -g npm' -sudo: false -matrix: - fast_finish: true - allow_failures: - - node_js: "4.0" - - node_js: "iojs-v3.2" - - node_js: "iojs-v3.1" - - node_js: "iojs-v3.0" - - node_js: "iojs-v2.4" - - node_js: "iojs-v2.3" - - node_js: "iojs-v2.2" - - node_js: "iojs-v2.1" - - node_js: "iojs-v2.0" - - node_js: "iojs-v1.7" - - node_js: "iojs-v1.6" - - node_js: "iojs-v1.5" - - node_js: "iojs-v1.4" - - node_js: "iojs-v1.3" - - node_js: "iojs-v1.2" - - node_js: "iojs-v1.1" - - node_js: "iojs-v1.0" - - node_js: "0.11" - - node_js: "0.9" - - node_js: "0.8" - - node_js: "0.6" - - node_js: "0.4" diff --git a/scripts/2.5/node_modules/is-date-object/CHANGELOG.md b/scripts/2.5/node_modules/is-date-object/CHANGELOG.md deleted file mode 100644 index 4a7eab61..00000000 --- a/scripts/2.5/node_modules/is-date-object/CHANGELOG.md +++ /dev/null @@ -1,10 +0,0 @@ -1.0.1 / 2015-09-27 -================= - * [Fix] If `@@toStringTag` is not present, use the old-school `Object#toString` test - * [Docs] Switch from vb.teelaun.ch to versionbadg.es for the npm version badge SVG - * [Dev Deps] update `is`, `eslint`, `@ljharb/eslint-config`, `semver`, `tape`, `jscs`, `nsp`, `covert` - * [Tests] up to `io.js` `v3.3`, `node` `v4.1` - -1.0.0 / 2015-01-28 -================= - * Initial release. diff --git a/scripts/2.5/node_modules/is-date-object/LICENSE b/scripts/2.5/node_modules/is-date-object/LICENSE deleted file mode 100644 index b43df444..00000000 --- a/scripts/2.5/node_modules/is-date-object/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015 Jordan Harband - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - diff --git a/scripts/2.5/node_modules/is-date-object/Makefile b/scripts/2.5/node_modules/is-date-object/Makefile deleted file mode 100644 index b9e4fe1a..00000000 --- a/scripts/2.5/node_modules/is-date-object/Makefile +++ /dev/null @@ -1,61 +0,0 @@ -# Since we rely on paths relative to the makefile location, abort if make isn't being run from there. -$(if $(findstring /,$(MAKEFILE_LIST)),$(error Please only invoke this makefile from the directory it resides in)) - - # The files that need updating when incrementing the version number. -VERSIONED_FILES := *.js *.json README* - - -# Add the local npm packages' bin folder to the PATH, so that `make` can find them, when invoked directly. -# Note that rather than using `$(npm bin)` the 'node_modules/.bin' path component is hard-coded, so that invocation works even from an environment -# where npm is (temporarily) unavailable due to having deactivated an nvm instance loaded into the calling shell in order to avoid interference with tests. -export PATH := $(shell printf '%s' "$$PWD/node_modules/.bin:$$PATH") -UTILS := semver -# Make sure that all required utilities can be located. -UTIL_CHECK := $(or $(shell PATH="$(PATH)" which $(UTILS) >/dev/null && echo 'ok'),$(error Did you forget to run `npm install` after cloning the repo? At least one of the required supporting utilities not found: $(UTILS))) - -# Default target (by virtue of being the first non '.'-prefixed in the file). -.PHONY: _no-target-specified -_no-target-specified: - $(error Please specify the target to make - `make list` shows targets. Alternatively, use `npm test` to run the default tests; `npm run` shows all tests) - -# Lists all targets defined in this makefile. -.PHONY: list -list: - @$(MAKE) -pRrn : -f $(MAKEFILE_LIST) 2>/dev/null | awk -v RS= -F: '/^# File/,/^# Finished Make data base/ {if ($$1 !~ "^[#.]") {print $$1}}' | command grep -v -e '^[^[:alnum:]]' -e '^$@$$command ' | sort - -# All-tests target: invokes the specified test suites for ALL shells defined in $(SHELLS). -.PHONY: test -test: - @npm test - -.PHONY: _ensure-tag -_ensure-tag: -ifndef TAG - $(error Please invoke with `make TAG= release`, where is either an increment specifier (patch, minor, major, prepatch, preminor, premajor, prerelease), or an explicit major.minor.patch version number) -endif - -CHANGELOG_ERROR = $(error No CHANGELOG specified) -.PHONY: _ensure-changelog -_ensure-changelog: - @ (git status -sb --porcelain | command grep -E '^( M|[MA] ) CHANGELOG.md' > /dev/null) || (echo no CHANGELOG.md specified && exit 2) - -# Ensures that the git workspace is clean. -.PHONY: _ensure-clean -_ensure-clean: - @[ -z "$$((git status --porcelain --untracked-files=no || echo err) | command grep -v 'CHANGELOG.md')" ] || { echo "Workspace is not clean; please commit changes first." >&2; exit 2; } - -# Makes a release; invoke with `make TAG= release`. -.PHONY: release -release: _ensure-tag _ensure-changelog _ensure-clean - @old_ver=`git describe --abbrev=0 --tags --match 'v[0-9]*.[0-9]*.[0-9]*'` || { echo "Failed to determine current version." >&2; exit 1; }; old_ver=$${old_ver#v}; \ - new_ver=`echo "$(TAG)" | sed 's/^v//'`; new_ver=$${new_ver:-patch}; \ - if printf "$$new_ver" | command grep -q '^[0-9]'; then \ - semver "$$new_ver" >/dev/null || { echo 'Invalid version number specified: $(TAG) - must be major.minor.patch' >&2; exit 2; }; \ - semver -r "> $$old_ver" "$$new_ver" >/dev/null || { echo 'Invalid version number specified: $(TAG) - must be HIGHER than current one.' >&2; exit 2; } \ - else \ - new_ver=`semver -i "$$new_ver" "$$old_ver"` || { echo 'Invalid version-increment specifier: $(TAG)' >&2; exit 2; } \ - fi; \ - printf "=== Bumping version **$$old_ver** to **$$new_ver** before committing and tagging:\n=== TYPE 'proceed' TO PROCEED, anything else to abort: " && read response && [ "$$response" = 'proceed' ] || { echo 'Aborted.' >&2; exit 2; }; \ - replace "$$old_ver" "$$new_ver" -- $(VERSIONED_FILES) && \ - git commit -m "v$$new_ver" $(VERSIONED_FILES) CHANGELOG.md && \ - git tag -a -m "v$$new_ver" "v$$new_ver" diff --git a/scripts/2.5/node_modules/is-date-object/README.md b/scripts/2.5/node_modules/is-date-object/README.md deleted file mode 100644 index 55b0c596..00000000 --- a/scripts/2.5/node_modules/is-date-object/README.md +++ /dev/null @@ -1,53 +0,0 @@ -# is-date-object [![Version Badge][2]][1] - -[![Build Status][3]][4] -[![dependency status][5]][6] -[![dev dependency status][7]][8] -[![License][license-image]][license-url] -[![Downloads][downloads-image]][downloads-url] - -[![npm badge][11]][1] - -[![browser support][9]][10] - -Is this value a JS Date object? This module works cross-realm/iframe, and despite ES6 @@toStringTag. - -## Example - -```js -var isDate = require('is-date-object'); -var assert = require('assert'); - -assert.notOk(isDate(undefined)); -assert.notOk(isDate(null)); -assert.notOk(isDate(false)); -assert.notOk(isDate(true)); -assert.notOk(isDate(42)); -assert.notOk(isDate('foo')); -assert.notOk(isDate(function () {})); -assert.notOk(isDate([])); -assert.notOk(isDate({})); -assert.notOk(isDate(/a/g)); -assert.notOk(isDate(new RegExp('a', 'g'))); - -assert.ok(isDate(new Date())); -``` - -## Tests -Simply clone the repo, `npm install`, and run `npm test` - -[1]: https://npmjs.org/package/is-date-object -[2]: http://versionbadg.es/ljharb/is-date-object.svg -[3]: https://travis-ci.org/ljharb/is-date-object.svg -[4]: https://travis-ci.org/ljharb/is-date-object -[5]: https://david-dm.org/ljharb/is-date-object.svg -[6]: https://david-dm.org/ljharb/is-date-object -[7]: https://david-dm.org/ljharb/is-date-object/dev-status.svg -[8]: https://david-dm.org/ljharb/is-date-object#info=devDependencies -[9]: https://ci.testling.com/ljharb/is-date-object.png -[10]: https://ci.testling.com/ljharb/is-date-object -[11]: https://nodei.co/npm/is-date-object.png?downloads=true&stars=true -[license-image]: http://img.shields.io/npm/l/is-date-object.svg -[license-url]: LICENSE -[downloads-image]: http://img.shields.io/npm/dm/is-date-object.svg -[downloads-url]: http://npm-stat.com/charts.html?package=is-date-object diff --git a/scripts/2.5/node_modules/is-date-object/index.js b/scripts/2.5/node_modules/is-date-object/index.js deleted file mode 100644 index fe0d7ecd..00000000 --- a/scripts/2.5/node_modules/is-date-object/index.js +++ /dev/null @@ -1,20 +0,0 @@ -'use strict'; - -var getDay = Date.prototype.getDay; -var tryDateObject = function tryDateObject(value) { - try { - getDay.call(value); - return true; - } catch (e) { - return false; - } -}; - -var toStr = Object.prototype.toString; -var dateClass = '[object Date]'; -var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol'; - -module.exports = function isDateObject(value) { - if (typeof value !== 'object' || value === null) { return false; } - return hasToStringTag ? tryDateObject(value) : toStr.call(value) === dateClass; -}; diff --git a/scripts/2.5/node_modules/is-date-object/package.json b/scripts/2.5/node_modules/is-date-object/package.json deleted file mode 100644 index f4e8b3cc..00000000 --- a/scripts/2.5/node_modules/is-date-object/package.json +++ /dev/null @@ -1,93 +0,0 @@ -{ - "_from": "is-date-object@^1.0.1", - "_id": "is-date-object@1.0.1", - "_inBundle": false, - "_integrity": "sha1-mqIOtq7rv/d/vTPnTKAbM1gdOhY=", - "_location": "/is-date-object", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "is-date-object@^1.0.1", - "name": "is-date-object", - "escapedName": "is-date-object", - "rawSpec": "^1.0.1", - "saveSpec": null, - "fetchSpec": "^1.0.1" - }, - "_requiredBy": [ - "/es-to-primitive" - ], - "_resolved": "https://registry.npmjs.org/is-date-object/-/is-date-object-1.0.1.tgz", - "_shasum": "9aa20eb6aeebbff77fbd33e74ca01b33581d3a16", - "_spec": "is-date-object@^1.0.1", - "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/2.5/node_modules/es-to-primitive", - "author": { - "name": "Jordan Harband" - }, - "bugs": { - "url": "https://github.com/ljharb/is-date-object/issues" - }, - "bundleDependencies": false, - "dependencies": {}, - "deprecated": false, - "description": "Is this value a JS Date object? This module works cross-realm/iframe, and despite ES6 @@toStringTag.", - "devDependencies": { - "@ljharb/eslint-config": "^1.2.0", - "covert": "^1.1.0", - "eslint": "^1.5.1", - "foreach": "^2.0.5", - "indexof": "^0.0.1", - "is": "^3.1.0", - "jscs": "^2.1.1", - "nsp": "^1.1.0", - "semver": "^5.0.3", - "tape": "^4.2.0" - }, - "engines": { - "node": ">= 0.4" - }, - "homepage": "https://github.com/ljharb/is-date-object#readme", - "keywords": [ - "Date", - "ES6", - "toStringTag", - "@@toStringTag", - "Date object" - ], - "license": "MIT", - "main": "index.js", - "name": "is-date-object", - "repository": { - "type": "git", - "url": "git://github.com/ljharb/is-date-object.git" - }, - "scripts": { - "coverage": "covert test.js", - "coverage-quiet": "covert test.js --quiet", - "eslint": "eslint test.js *.js", - "jscs": "jscs test.js *.js", - "lint": "npm run jscs && npm run eslint", - "security": "nsp package", - "test": "npm run lint && node --harmony --es-staging test.js && npm run security" - }, - "testling": { - "files": "test.js", - "browsers": [ - "iexplore/6.0..latest", - "firefox/3.0..6.0", - "firefox/15.0..latest", - "firefox/nightly", - "chrome/4.0..10.0", - "chrome/20.0..latest", - "chrome/canary", - "opera/10.0..latest", - "opera/next", - "safari/4.0..latest", - "ipad/6.0..latest", - "iphone/6.0..latest", - "android-browser/4.2" - ] - }, - "version": "1.0.1" -} diff --git a/scripts/2.5/node_modules/is-date-object/test.js b/scripts/2.5/node_modules/is-date-object/test.js deleted file mode 100644 index 29f0917b..00000000 --- a/scripts/2.5/node_modules/is-date-object/test.js +++ /dev/null @@ -1,33 +0,0 @@ -'use strict'; - -var test = require('tape'); -var isDate = require('./'); -var hasSymbols = typeof Symbol === 'function' && typeof Symbol() === 'symbol'; - -test('not Dates', function (t) { - t.notOk(isDate(), 'undefined is not Date'); - t.notOk(isDate(null), 'null is not Date'); - t.notOk(isDate(false), 'false is not Date'); - t.notOk(isDate(true), 'true is not Date'); - t.notOk(isDate(42), 'number is not Date'); - t.notOk(isDate('foo'), 'string is not Date'); - t.notOk(isDate([]), 'array is not Date'); - t.notOk(isDate({}), 'object is not Date'); - t.notOk(isDate(function () {}), 'function is not Date'); - t.notOk(isDate(/a/g), 'regex literal is not Date'); - t.notOk(isDate(new RegExp('a', 'g')), 'regex object is not Date'); - t.end(); -}); - -test('@@toStringTag', { skip: !hasSymbols || !Symbol.toStringTag }, function (t) { - var realDate = new Date(); - var fakeDate = { toString: function () { return String(realDate); }, valueOf: function () { return realDate.getTime(); } }; - fakeDate[Symbol.toStringTag] = 'Date'; - t.notOk(isDate(fakeDate), 'fake Date with @@toStringTag "Date" is not Date'); - t.end(); -}); - -test('Dates', function (t) { - t.ok(isDate(new Date()), 'new Date() is Date'); - t.end(); -}); diff --git a/scripts/2.5/node_modules/is-generator-function/.editorconfig b/scripts/2.5/node_modules/is-generator-function/.editorconfig deleted file mode 100644 index ac29adef..00000000 --- a/scripts/2.5/node_modules/is-generator-function/.editorconfig +++ /dev/null @@ -1,20 +0,0 @@ -root = true - -[*] -indent_style = tab -indent_size = 4 -end_of_line = lf -charset = utf-8 -trim_trailing_whitespace = true -insert_final_newline = true -max_line_length = 120 - -[CHANGELOG.md] -indent_style = space -indent_size = 2 - -[*.json] -max_line_length = off - -[Makefile] -max_line_length = off diff --git a/scripts/2.5/node_modules/is-generator-function/.eslintrc b/scripts/2.5/node_modules/is-generator-function/.eslintrc deleted file mode 100644 index 484e4d71..00000000 --- a/scripts/2.5/node_modules/is-generator-function/.eslintrc +++ /dev/null @@ -1,9 +0,0 @@ -{ - "root": true, - - "extends": "@ljharb", - - "rules": { - "no-new-func": [1] - } -} diff --git a/scripts/2.5/node_modules/is-generator-function/.jscs.json b/scripts/2.5/node_modules/is-generator-function/.jscs.json deleted file mode 100644 index c62f2c19..00000000 --- a/scripts/2.5/node_modules/is-generator-function/.jscs.json +++ /dev/null @@ -1,176 +0,0 @@ -{ - "es3": true, - - "additionalRules": [], - - "requireSemicolons": true, - - "disallowMultipleSpaces": true, - - "disallowIdentifierNames": [], - - "requireCurlyBraces": { - "allExcept": [], - "keywords": ["if", "else", "for", "while", "do", "try", "catch"] - }, - - "requireSpaceAfterKeywords": ["if", "else", "for", "while", "do", "switch", "return", "try", "catch", "function"], - - "disallowSpaceAfterKeywords": [], - - "disallowSpaceBeforeComma": true, - "disallowSpaceAfterComma": false, - "disallowSpaceBeforeSemicolon": true, - - "disallowNodeTypes": [ - "DebuggerStatement", - "ForInStatement", - "LabeledStatement", - "SwitchCase", - "SwitchStatement", - "WithStatement" - ], - - "requireObjectKeysOnNewLine": { "allExcept": ["sameLine"] }, - - "requireSpacesInAnonymousFunctionExpression": { "beforeOpeningRoundBrace": true, "beforeOpeningCurlyBrace": true }, - "requireSpacesInNamedFunctionExpression": { "beforeOpeningCurlyBrace": true }, - "disallowSpacesInNamedFunctionExpression": { "beforeOpeningRoundBrace": true }, - "requireSpacesInFunctionDeclaration": { "beforeOpeningCurlyBrace": true }, - "disallowSpacesInFunctionDeclaration": { "beforeOpeningRoundBrace": true }, - - "requireSpaceBetweenArguments": true, - - "disallowSpacesInsideParentheses": true, - - "disallowSpacesInsideArrayBrackets": true, - - "disallowQuotedKeysInObjects": { "allExcept": ["reserved"] }, - - "disallowSpaceAfterObjectKeys": true, - - "requireCommaBeforeLineBreak": true, - - "disallowSpaceAfterPrefixUnaryOperators": ["++", "--", "+", "-", "~", "!"], - "requireSpaceAfterPrefixUnaryOperators": [], - - "disallowSpaceBeforePostfixUnaryOperators": ["++", "--"], - "requireSpaceBeforePostfixUnaryOperators": [], - - "disallowSpaceBeforeBinaryOperators": [], - "requireSpaceBeforeBinaryOperators": ["+", "-", "/", "*", "=", "==", "===", "!=", "!=="], - - "requireSpaceAfterBinaryOperators": ["+", "-", "/", "*", "=", "==", "===", "!=", "!=="], - "disallowSpaceAfterBinaryOperators": [], - - "disallowImplicitTypeConversion": ["binary", "string"], - - "disallowKeywords": ["with", "eval"], - - "requireKeywordsOnNewLine": [], - "disallowKeywordsOnNewLine": ["else"], - - "requireLineFeedAtFileEnd": true, - - "disallowTrailingWhitespace": true, - - "disallowTrailingComma": true, - - "excludeFiles": ["node_modules/**", "vendor/**"], - - "disallowMultipleLineStrings": true, - - "requireDotNotation": { "allExcept": ["keywords"] }, - - "requireParenthesesAroundIIFE": true, - - "validateLineBreaks": "LF", - - "validateQuoteMarks": { - "escape": true, - "mark": "'" - }, - - "disallowOperatorBeforeLineBreak": [], - - "requireSpaceBeforeKeywords": [ - "do", - "for", - "if", - "else", - "switch", - "case", - "try", - "catch", - "finally", - "while", - "with", - "return" - ], - - "validateAlignedFunctionParameters": { - "lineBreakAfterOpeningBraces": true, - "lineBreakBeforeClosingBraces": true - }, - - "requirePaddingNewLinesBeforeExport": true, - - "validateNewlineAfterArrayElements": { - "maximum": 2 - }, - - "requirePaddingNewLinesAfterUseStrict": true, - - "disallowArrowFunctions": true, - - "disallowMultiLineTernary": true, - - "validateOrderInObjectKeys": "asc-insensitive", - - "disallowIdenticalDestructuringNames": true, - - "disallowNestedTernaries": { "maxLevel": 1 }, - - "requireSpaceAfterComma": { "allExcept": ["trailing"] }, - "requireAlignedMultilineParams": false, - - "requireSpacesInGenerator": { - "afterStar": true - }, - - "disallowSpacesInGenerator": { - "beforeStar": true - }, - - "disallowVar": false, - - "requireArrayDestructuring": false, - - "requireEnhancedObjectLiterals": false, - - "requireObjectDestructuring": false, - - "requireEarlyReturn": false, - - "requireCapitalizedConstructorsNew": { - "allExcept": ["Function", "String", "Object", "Symbol", "Number", "Date", "RegExp", "Error", "Boolean", "Array"] - }, - - "requireImportAlphabetized": false, - - "requireSpaceBeforeObjectValues": true, - "requireSpaceBeforeDestructuredValues": true, - - "disallowSpacesInsideTemplateStringPlaceholders": true, - - "disallowArrayDestructuringReturn": false, - - "requireNewlineBeforeSingleStatementsInIf": false, - - "disallowUnusedVariables": true, - - "requireSpacesInsideImportedObjectBraces": true, - - "requireUseStrict": true -} - diff --git a/scripts/2.5/node_modules/is-generator-function/.nvmrc b/scripts/2.5/node_modules/is-generator-function/.nvmrc deleted file mode 100644 index 64f5a0a6..00000000 --- a/scripts/2.5/node_modules/is-generator-function/.nvmrc +++ /dev/null @@ -1 +0,0 @@ -node diff --git a/scripts/2.5/node_modules/is-generator-function/.travis.yml b/scripts/2.5/node_modules/is-generator-function/.travis.yml deleted file mode 100644 index 7ead9e94..00000000 --- a/scripts/2.5/node_modules/is-generator-function/.travis.yml +++ /dev/null @@ -1,191 +0,0 @@ -language: node_js -os: - - linux -node_js: - - "9.3" - - "8.9" - - "7.10" - - "6.12" - - "5.12" - - "4.8" - - "iojs-v3.3" - - "iojs-v2.5" - - "iojs-v1.8" - - "0.12" - - "0.10" - - "0.8" -before_install: - - 'nvm install-latest-npm' -install: - - 'if [ "${TRAVIS_NODE_VERSION}" = "0.6" ] || [ "${TRAVIS_NODE_VERSION}" = "0.9" ]; then nvm install --latest-npm 0.8 && npm install && nvm use "${TRAVIS_NODE_VERSION}"; else npm install; fi;' -script: - - 'if [ -n "${PRETEST-}" ]; then npm run pretest ; fi' - - 'if [ -n "${POSTTEST-}" ]; then npm run posttest ; fi' - - 'if [ -n "${COVERAGE-}" ]; then npm run coverage ; fi' - - 'if [ -n "${TEST-}" ]; then npm run tests-only ; fi' -sudo: false -env: - - TEST=true -matrix: - fast_finish: true - include: - - node_js: "lts/*" - env: PRETEST=true - - node_js: "lts/*" - env: POSTTEST=true - - node_js: "8" - env: COVERAGE=true - - node_js: "4" - env: COVERAGE=true - - node_js: "9.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.11" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.10" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.11" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.10" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v3.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v3.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v3.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "0.11" - env: TEST=true ALLOW_FAILURE=true - - node_js: "0.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "0.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "0.4" - env: TEST=true ALLOW_FAILURE=true - allow_failures: - - os: osx - - env: TEST=true ALLOW_FAILURE=true - - env: COVERAGE=true diff --git a/scripts/2.5/node_modules/is-generator-function/CHANGELOG.md b/scripts/2.5/node_modules/is-generator-function/CHANGELOG.md deleted file mode 100644 index 983f5181..00000000 --- a/scripts/2.5/node_modules/is-generator-function/CHANGELOG.md +++ /dev/null @@ -1,44 +0,0 @@ -1.0.7 / 2017-12-27 -================= - * [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `core-js`, `nsp`, `semver`, `tape` - * [Tests] up to `node` `v9.3`, `v8.9`, `v6.12`; pin included builds to LTS; use `nvm install-latest-npm` - * [Tests] run tests with uglify-register - -1.0.6 / 2016-12-20 -================= - * [Fix] fix `is-generator-function` in an env without native generators, with core-js (https://github.com/ljharb/is-equal/issues/33) - -1.0.5 / 2016-12-19 -================= - * [Fix] account for Safari 10 which reports the wrong toString on generator functions - * [Refactor] remove useless `Object#toString` check - * [Dev Deps] update everything; add linting - * [Tests] use pretest/posttest for linting/security - * [Tests] on all minors of node and io.js - -1.0.4 / 2015-03-03 -================= - * Add support for concise generator methods (#2) This is a patch change since concise methods are not in any actual released engines yet. - * Test on latest `io.js` - * Update `semver` - -1.0.3 / 2015-01-31 -================= - * Speed up travis-ci tests - * Run tests against a faked @@toStringTag - * Bail out early when typeof is not "function" - -1.0.2 / 2015-01-20 -================= - * Update `jscs`, `tape` - * Fix tests in newer v8 (and io.js) where Object#toString.call of a generator is GeneratorFunction, not Function - -1.0.1 / 2014-12-14 -================= - * Update `jscs`, `tape` - * Tweaks to README - * Use `make-generator-function` in tests - -1.0.0 / 2014-08-09 -================= - * Initial release. diff --git a/scripts/2.5/node_modules/is-generator-function/LICENSE b/scripts/2.5/node_modules/is-generator-function/LICENSE deleted file mode 100644 index 47b7b507..00000000 --- a/scripts/2.5/node_modules/is-generator-function/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014 Jordan Harband - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software is furnished to do so, -subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS -FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR -COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/scripts/2.5/node_modules/is-generator-function/Makefile b/scripts/2.5/node_modules/is-generator-function/Makefile deleted file mode 100644 index ccca6f1c..00000000 --- a/scripts/2.5/node_modules/is-generator-function/Makefile +++ /dev/null @@ -1,61 +0,0 @@ -# Since we rely on paths relative to the makefile location, abort if make isn't being run from there. -$(if $(findstring /,$(MAKEFILE_LIST)),$(error Please only invoke this makefile from the directory it resides in)) - - # The files that need updating when incrementing the version number. -VERSIONED_FILES := *.js */*.js *.json README* - - -# Add the local npm packages' bin folder to the PATH, so that `make` can find them, when invoked directly. -# Note that rather than using `$(npm bin)` the 'node_modules/.bin' path component is hard-coded, so that invocation works even from an environment -# where npm is (temporarily) unavailable due to having deactivated an nvm instance loaded into the calling shell in order to avoid interference with tests. -export PATH := $(shell printf '%s' "$$PWD/node_modules/.bin:$$PATH") -UTILS := semver replace -# Make sure that all required utilities can be located. -UTIL_CHECK := $(or $(shell PATH="$(PATH)" which $(UTILS) >/dev/null && echo 'ok'),$(error Did you forget to run `npm install` after cloning the repo? At least one of the required supporting utilities not found: $(UTILS))) - -# Default target (by virtue of being the first non '.'-prefixed in the file). -.PHONY: _no-target-specified -_no-target-specified: - $(error Please specify the target to make - `make list` shows targets. Alternatively, use `npm test` to run the default tests; `npm run` shows all tests) - -# Lists all targets defined in this makefile. -.PHONY: list -list: - @$(MAKE) -pRrn : -f $(MAKEFILE_LIST) 2>/dev/null | awk -v RS= -F: '/^# File/,/^# Finished Make data base/ {if ($$1 !~ "^[#.]") {print $$1}}' | command grep -v -e '^[^[:alnum:]]' -e '^$@$$command ' | sort - -# All-tests target: invokes the specified test suites for ALL shells defined in $(SHELLS). -.PHONY: test -test: - @npm test - -.PHONY: _ensure-tag -_ensure-tag: -ifndef TAG - $(error Please invoke with `make TAG= release`, where is either an increment specifier (patch, minor, major, prepatch, preminor, premajor, prerelease), or an explicit major.minor.patch version number) -endif - -CHANGELOG_ERROR = $(error No CHANGELOG specified) -.PHONY: _ensure-changelog -_ensure-changelog: - @ (git status -sb --porcelain | command grep -E '^( M|[MA] ) CHANGELOG.md' > /dev/null) || (echo no CHANGELOG.md specified && exit 2) - -# Ensures that the git workspace is clean. -.PHONY: _ensure-clean -_ensure-clean: - @[ -z "$$((git status --porcelain --untracked-files=no || echo err) | command grep -v 'CHANGELOG.md')" ] || { echo "Workspace is not clean; please commit changes first." >&2; exit 2; } - -# Makes a release; invoke with `make TAG= release`. -.PHONY: release -release: _ensure-tag _ensure-changelog _ensure-clean - @old_ver=`git describe --abbrev=0 --tags --match 'v[0-9]*.[0-9]*.[0-9]*'` || { echo "Failed to determine current version." >&2; exit 1; }; old_ver=$${old_ver#v}; \ - new_ver=`echo "$(TAG)" | sed 's/^v//'`; new_ver=$${new_ver:-patch}; \ - if printf "$$new_ver" | command grep -q '^[0-9]'; then \ - semver "$$new_ver" >/dev/null || { echo 'Invalid version number specified: $(TAG) - must be major.minor.patch' >&2; exit 2; }; \ - semver -r "> $$old_ver" "$$new_ver" >/dev/null || { echo 'Invalid version number specified: $(TAG) - must be HIGHER than current one.' >&2; exit 2; } \ - else \ - new_ver=`semver -i "$$new_ver" "$$old_ver"` || { echo 'Invalid version-increment specifier: $(TAG)' >&2; exit 2; } \ - fi; \ - printf "=== Bumping version **$$old_ver** to **$$new_ver** before committing and tagging:\n=== TYPE 'proceed' TO PROCEED, anything else to abort: " && read response && [ "$$response" = 'proceed' ] || { echo 'Aborted.' >&2; exit 2; }; \ - replace "$$old_ver" "$$new_ver" -- $(VERSIONED_FILES) && \ - git commit -m "v$$new_ver" $(VERSIONED_FILES) CHANGELOG.md && \ - git tag -a -m "v$$new_ver" "v$$new_ver" diff --git a/scripts/2.5/node_modules/is-generator-function/README.md b/scripts/2.5/node_modules/is-generator-function/README.md deleted file mode 100644 index 027facf4..00000000 --- a/scripts/2.5/node_modules/is-generator-function/README.md +++ /dev/null @@ -1,42 +0,0 @@ -# is-generator-function [![Version Badge][2]][1] - -[![Build Status][3]][4] -[![dependency status][5]][6] -[![dev dependency status][7]][8] -[![License][license-image]][license-url] -[![Downloads][downloads-image]][downloads-url] - -[![npm badge][11]][1] - -[![browser support][9]][10] - -Is this a native generator function? - -## Example - -```js -var isGeneratorFunction = require('is-generator-function'); -assert(!isGeneratorFunction(function () {})); -assert(!isGeneratorFunction(null)); -assert(isGeneratorFunction(function* () { yield 42; return Infinity; })); -``` - -## Tests -Simply clone the repo, `npm install`, and run `npm test` - -[1]: https://npmjs.org/package/is-generator-function -[2]: http://versionbadg.es/ljharb/is-generator-function.svg -[3]: https://travis-ci.org/ljharb/is-generator-function.svg -[4]: https://travis-ci.org/ljharb/is-generator-function -[5]: https://david-dm.org/ljharb/is-generator-function.svg -[6]: https://david-dm.org/ljharb/is-generator-function -[7]: https://david-dm.org/ljharb/is-generator-function/dev-status.svg -[8]: https://david-dm.org/ljharb/is-generator-function#info=devDependencies -[9]: https://ci.testling.com/ljharb/is-generator-function.png -[10]: https://ci.testling.com/ljharb/is-generator-function -[11]: https://nodei.co/npm/is-generator-function.png?downloads=true&stars=true -[license-image]: http://img.shields.io/npm/l/is-generator-function.svg -[license-url]: LICENSE -[downloads-image]: http://img.shields.io/npm/dm/is-generator-function.svg -[downloads-url]: http://npm-stat.com/charts.html?package=is-generator-function - diff --git a/scripts/2.5/node_modules/is-generator-function/index.js b/scripts/2.5/node_modules/is-generator-function/index.js deleted file mode 100644 index 306a299c..00000000 --- a/scripts/2.5/node_modules/is-generator-function/index.js +++ /dev/null @@ -1,32 +0,0 @@ -'use strict'; - -var toStr = Object.prototype.toString; -var fnToStr = Function.prototype.toString; -var isFnRegex = /^\s*(?:function)?\*/; -var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol'; -var getProto = Object.getPrototypeOf; -var getGeneratorFunc = function () { // eslint-disable-line consistent-return - if (!hasToStringTag) { - return false; - } - try { - return Function('return function*() {}')(); - } catch (e) { - } -}; -var generatorFunc = getGeneratorFunc(); -var GeneratorFunction = generatorFunc ? getProto(generatorFunc) : {}; - -module.exports = function isGeneratorFunction(fn) { - if (typeof fn !== 'function') { - return false; - } - if (isFnRegex.test(fnToStr.call(fn))) { - return true; - } - if (!hasToStringTag) { - var str = toStr.call(fn); - return str === '[object GeneratorFunction]'; - } - return getProto(fn) === GeneratorFunction; -}; diff --git a/scripts/2.5/node_modules/is-generator-function/package.json b/scripts/2.5/node_modules/is-generator-function/package.json deleted file mode 100644 index f10bbbff..00000000 --- a/scripts/2.5/node_modules/is-generator-function/package.json +++ /dev/null @@ -1,101 +0,0 @@ -{ - "_from": "is-generator-function@^1.0.7", - "_id": "is-generator-function@1.0.7", - "_inBundle": false, - "_integrity": "sha512-YZc5EwyO4f2kWCax7oegfuSr9mFz1ZvieNYBEjmukLxgXfBUbxAWGVF7GZf0zidYtoBl3WvC07YK0wT76a+Rtw==", - "_location": "/is-generator-function", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "is-generator-function@^1.0.7", - "name": "is-generator-function", - "escapedName": "is-generator-function", - "rawSpec": "^1.0.7", - "saveSpec": null, - "fetchSpec": "^1.0.7" - }, - "_requiredBy": [ - "/util" - ], - "_resolved": "https://registry.npmjs.org/is-generator-function/-/is-generator-function-1.0.7.tgz", - "_shasum": "d2132e529bb0000a7f80794d4bdf5cd5e5813522", - "_spec": "is-generator-function@^1.0.7", - "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/2.5/node_modules/util", - "author": { - "name": "Jordan Harband" - }, - "bugs": { - "url": "https://github.com/ljharb/is-generator-function/issues" - }, - "bundleDependencies": false, - "dependencies": {}, - "deprecated": false, - "description": "Determine if a function is a native generator function.", - "devDependencies": { - "@ljharb/eslint-config": "^12.2.1", - "core-js": "^2.5.3", - "covert": "^1.1.0", - "eslint": "^4.14.0", - "jscs": "^3.0.7", - "make-generator-function": "^1.1.0", - "nsp": "^3.1.0", - "replace": "^0.3.0", - "semver": "^5.4.1", - "tape": "^4.8.0", - "uglify-register": "^1.0.1" - }, - "engines": { - "node": ">= 0.4" - }, - "homepage": "https://github.com/ljharb/is-generator-function#readme", - "keywords": [ - "generator", - "generator function", - "es6", - "es2015", - "yield", - "function", - "function*" - ], - "license": "MIT", - "main": "index.js", - "name": "is-generator-function", - "repository": { - "type": "git", - "url": "git://github.com/ljharb/is-generator-function.git" - }, - "scripts": { - "coverage": "covert test", - "eslint": "eslint *.js */*.js", - "jscs": "jscs *.js */*.js", - "lint": "npm run jscs && npm run eslint", - "posttest": "npm run security", - "posttests-only": "npm run test:corejs && npm run test:uglified", - "pretest": "npm run lint", - "security": "nsp check", - "test": "npm run tests-only", - "test:corejs": "node test/corejs", - "test:uglified": "node test/uglified", - "tests-only": "node --es-staging --harmony test" - }, - "testling": { - "files": "test/index.js", - "browsers": [ - "iexplore/6.0..latest", - "firefox/3.0..6.0", - "firefox/15.0..latest", - "firefox/nightly", - "chrome/4.0..10.0", - "chrome/20.0..latest", - "chrome/canary", - "opera/10.0..latest", - "opera/next", - "safari/4.0..latest", - "ipad/6.0..latest", - "iphone/6.0..latest", - "android-browser/4.2" - ] - }, - "version": "1.0.7" -} diff --git a/scripts/2.5/node_modules/is-generator-function/test/.eslintrc b/scripts/2.5/node_modules/is-generator-function/test/.eslintrc deleted file mode 100644 index 168cdf85..00000000 --- a/scripts/2.5/node_modules/is-generator-function/test/.eslintrc +++ /dev/null @@ -1,5 +0,0 @@ -{ - "rules": { - "max-statements-per-line": [2, { "max": 2 }] - } -} diff --git a/scripts/2.5/node_modules/is-generator-function/test/corejs.js b/scripts/2.5/node_modules/is-generator-function/test/corejs.js deleted file mode 100644 index 73f0c89c..00000000 --- a/scripts/2.5/node_modules/is-generator-function/test/corejs.js +++ /dev/null @@ -1,5 +0,0 @@ -'use strict'; - -require('core-js'); - -require('./'); diff --git a/scripts/2.5/node_modules/is-generator-function/test/index.js b/scripts/2.5/node_modules/is-generator-function/test/index.js deleted file mode 100644 index a33cc2b7..00000000 --- a/scripts/2.5/node_modules/is-generator-function/test/index.js +++ /dev/null @@ -1,94 +0,0 @@ -'use strict'; - -/* globals window */ - -var test = require('tape'); -var isGeneratorFunction = require('../index'); -var generatorFunc = require('make-generator-function'); -var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol'; - -var forEach = function (arr, func) { - var i; - for (i = 0; i < arr.length; ++i) { - func(arr[i], i, arr); - } -}; - -test('returns false for non-functions', function (t) { - var nonFuncs = [ - true, - false, - null, - undefined, - {}, - [], - /a/g, - 'string', - 42, - new Date() - ]; - t.plan(nonFuncs.length); - forEach(nonFuncs, function (nonFunc) { - t.notOk(isGeneratorFunction(nonFunc), nonFunc + ' is not a function'); - }); - t.end(); -}); - -test('returns false for non-generator functions', function (t) { - var func = function () {}; - t.notOk(isGeneratorFunction(func), 'anonymous function is not an generator function'); - - var namedFunc = function foo() {}; - t.notOk(isGeneratorFunction(namedFunc), 'named function is not an generator function'); - - if (typeof window === 'undefined') { - t.skip('window.alert is not an generator function'); - } else { - t.notOk(isGeneratorFunction(window.alert), 'window.alert is not an generator function'); - } - t.end(); -}); - -test('returns false for non-generator function with faked toString', function (t) { - var func = function () {}; - func.toString = function () { return 'function* () { return "TOTALLY REAL I SWEAR!"; }'; }; - - t.notEqual(String(func), Function.prototype.toString.apply(func), 'faked toString is not real toString'); - t.notOk(isGeneratorFunction(func), 'anonymous function with faked toString is not a generator function'); - t.end(); -}); - -test('returns false for non-generator function with faked @@toStringTag', { skip: !hasToStringTag }, function (t) { - var fakeGenFunction = { - toString: function () { return String(generatorFunc); }, - valueOf: function () { return generatorFunc; } - }; - fakeGenFunction[Symbol.toStringTag] = 'GeneratorFunction'; - t.notOk(isGeneratorFunction(fakeGenFunction), 'fake GeneratorFunction with @@toStringTag "GeneratorFunction" is not a generator function'); - t.end(); -}); - -test('returns true for generator functions', function (t) { - if (generatorFunc) { - t.ok(isGeneratorFunction(generatorFunc), 'generator function is generator function'); - } else { - t.skip('generator function is generator function - this environment does not support ES6 generator functions. Please run `node --harmony`, or use a supporting browser.'); - } - t.end(); -}); - -test('concise methods', { skip: !generatorFunc || !generatorFunc.concise }, function (t) { - t.test('returns true for concise generator methods', function (st) { - st.ok(isGeneratorFunction(generatorFunc.concise), 'concise generator method is generator function'); - st.end(); - }); - - t.test('returns false for concise non-generator methods', function (st) { - var conciseMethod = Function('return { concise() {} }.concise;')(); - st.equal(typeof conciseMethod, 'function', 'assert: concise method exists'); - st.notOk(isGeneratorFunction(conciseMethod), 'concise non-generator method is not generator function'); - st.end(); - }); - - t.end(); -}); diff --git a/scripts/2.5/node_modules/is-generator-function/test/uglified.js b/scripts/2.5/node_modules/is-generator-function/test/uglified.js deleted file mode 100644 index fd82b553..00000000 --- a/scripts/2.5/node_modules/is-generator-function/test/uglified.js +++ /dev/null @@ -1,8 +0,0 @@ -'use strict'; - -require('uglify-register/api').register({ - exclude: [/\/node_modules\//, /\/test\//], - uglify: { mangle: true } -}); - -require('./'); diff --git a/scripts/2.5/node_modules/is-nan/.eslintrc b/scripts/2.5/node_modules/is-nan/.eslintrc deleted file mode 100644 index ad448ec6..00000000 --- a/scripts/2.5/node_modules/is-nan/.eslintrc +++ /dev/null @@ -1,9 +0,0 @@ -{ - "root": true, - - "extends": "@ljharb", - - "rules": { - "no-extra-parens": [2] - } -} diff --git a/scripts/2.5/node_modules/is-nan/.jscs.json b/scripts/2.5/node_modules/is-nan/.jscs.json deleted file mode 100644 index 854b398f..00000000 --- a/scripts/2.5/node_modules/is-nan/.jscs.json +++ /dev/null @@ -1,124 +0,0 @@ -{ - "es3": true, - - "additionalRules": [], - - "requireSemicolons": true, - - "disallowMultipleSpaces": true, - - "disallowIdentifierNames": [], - - "requireCurlyBraces": ["if", "else", "for", "while", "do", "try", "catch"], - - "requireSpaceAfterKeywords": ["if", "else", "for", "while", "do", "switch", "return", "try", "catch", "function"], - - "disallowSpaceAfterKeywords": [], - - "disallowSpaceBeforeComma": true, - "disallowSpaceBeforeSemicolon": true, - - "disallowNodeTypes": [ - "DebuggerStatement", - "ForInStatement", - "LabeledStatement", - "SwitchCase", - "SwitchStatement", - "WithStatement" - ], - - "requireObjectKeysOnNewLine": true, - - "requireSpacesInAnonymousFunctionExpression": { "beforeOpeningRoundBrace": true, "beforeOpeningCurlyBrace": true }, - "requireSpacesInNamedFunctionExpression": { "beforeOpeningCurlyBrace": true }, - "disallowSpacesInNamedFunctionExpression": { "beforeOpeningRoundBrace": true }, - "requireSpacesInFunctionDeclaration": { "beforeOpeningCurlyBrace": true }, - "disallowSpacesInFunctionDeclaration": { "beforeOpeningRoundBrace": true }, - - "requireSpaceBetweenArguments": true, - - "disallowSpacesInsideParentheses": true, - - "disallowSpacesInsideArrayBrackets": true, - - "disallowQuotedKeysInObjects": "allButReserved", - - "disallowSpaceAfterObjectKeys": true, - - "requireCommaBeforeLineBreak": true, - - "disallowSpaceAfterPrefixUnaryOperators": ["++", "--", "+", "-", "~", "!"], - "requireSpaceAfterPrefixUnaryOperators": [], - - "disallowSpaceBeforePostfixUnaryOperators": ["++", "--"], - "requireSpaceBeforePostfixUnaryOperators": [], - - "disallowSpaceBeforeBinaryOperators": [], - "requireSpaceBeforeBinaryOperators": ["+", "-", "/", "*", "=", "==", "===", "!=", "!=="], - - "requireSpaceAfterBinaryOperators": ["+", "-", "/", "*", "=", "==", "===", "!=", "!=="], - "disallowSpaceAfterBinaryOperators": [], - - "disallowImplicitTypeConversion": ["binary", "string"], - - "disallowKeywords": ["with", "eval"], - - "requireKeywordsOnNewLine": [], - "disallowKeywordsOnNewLine": ["else"], - - "requireLineFeedAtFileEnd": true, - - "disallowTrailingWhitespace": true, - - "disallowTrailingComma": true, - - "excludeFiles": ["node_modules/**", "vendor/**"], - - "disallowMultipleLineStrings": true, - - "requireDotNotation": true, - - "requireParenthesesAroundIIFE": true, - - "validateLineBreaks": "LF", - - "validateQuoteMarks": { - "escape": true, - "mark": "'" - }, - - "disallowOperatorBeforeLineBreak": [], - - "requireSpaceBeforeKeywords": [ - "do", - "for", - "if", - "else", - "switch", - "case", - "try", - "catch", - "finally", - "while", - "with", - "return" - ], - - "validateAlignedFunctionParameters": { - "lineBreakAfterOpeningBraces": true, - "lineBreakBeforeClosingBraces": true - }, - - "requirePaddingNewLinesBeforeExport": true, - - "validateNewlineAfterArrayElements": { - "maximum": 1 - }, - - "requirePaddingNewLinesAfterUseStrict": true, - - "disallowArrowFunctions": true, - - "validateOrderInObjectKeys": "asc-insensitive" -} - diff --git a/scripts/2.5/node_modules/is-nan/.npmignore b/scripts/2.5/node_modules/is-nan/.npmignore deleted file mode 100644 index a72b52eb..00000000 --- a/scripts/2.5/node_modules/is-nan/.npmignore +++ /dev/null @@ -1,15 +0,0 @@ -lib-cov -*.seed -*.log -*.csv -*.dat -*.out -*.pid -*.gz - -pids -logs -results - -npm-debug.log -node_modules diff --git a/scripts/2.5/node_modules/is-nan/.travis.yml b/scripts/2.5/node_modules/is-nan/.travis.yml deleted file mode 100644 index feec7eef..00000000 --- a/scripts/2.5/node_modules/is-nan/.travis.yml +++ /dev/null @@ -1,49 +0,0 @@ -language: node_js -node_js: - - "iojs-v3.0" - - "iojs-v2.5" - - "iojs-v2.4" - - "iojs-v2.3" - - "iojs-v2.2" - - "iojs-v2.1" - - "iojs-v2.0" - - "iojs-v1.8" - - "iojs-v1.7" - - "iojs-v1.6" - - "iojs-v1.5" - - "iojs-v1.4" - - "iojs-v1.3" - - "iojs-v1.2" - - "iojs-v1.1" - - "iojs-v1.0" - - "0.12" - - "0.11" - - "0.10" - - "0.9" - - "0.8" - - "0.6" - - "0.4" -before_install: - - '[ "${TRAVIS_NODE_VERSION}" = "0.6" ] || npm install -g npm@1.4.28 && npm install -g npm' -sudo: false -matrix: - fast_finish: true - allow_failures: - - node_js: "iojs-v2.4" - - node_js: "iojs-v2.3" - - node_js: "iojs-v2.2" - - node_js: "iojs-v2.1" - - node_js: "iojs-v2.0" - - node_js: "iojs-v1.7" - - node_js: "iojs-v1.6" - - node_js: "iojs-v1.5" - - node_js: "iojs-v1.4" - - node_js: "iojs-v1.3" - - node_js: "iojs-v1.2" - - node_js: "iojs-v1.1" - - node_js: "iojs-v1.0" - - node_js: "0.11" - - node_js: "0.9" - - node_js: "0.8" - - node_js: "0.6" - - node_js: "0.4" diff --git a/scripts/2.5/node_modules/is-nan/CHANGELOG.md b/scripts/2.5/node_modules/is-nan/CHANGELOG.md deleted file mode 100644 index a10639ef..00000000 --- a/scripts/2.5/node_modules/is-nan/CHANGELOG.md +++ /dev/null @@ -1,27 +0,0 @@ -1.2.1 / 2015-08-16 -================= - * [Docs] Update readme - -1.2.0 / 2015-08-16 -================= - * [New] Implement the [es-shim API](es-shims/api) interface - * [Dev Deps] update `eslint`, `tape`, `es5-shim`, `@ljharb/eslint-config` - * [Tests] up to `io.js` `v3.0` - * [Docs] Switch from vb.teelaun.ch to versionbadg.es for the npm version badge SVG - * [Security] Add `npm run security` - -1.1.0 / 2015-06-24 -================= - * Add a "shim" method - * Add `npm run eslint` - * Test latest `node` and `io.js` on `travis-ci` - * Add license and download badges to README - * Update `tape`, `covert`, `jscs` - -1.0.1 / 2014-07-05 -================= - * Oops, jscs should be a devDependency - -1.0.0 / 2014-07-05 -================= - * Initial release. diff --git a/scripts/2.5/node_modules/is-nan/LICENSE b/scripts/2.5/node_modules/is-nan/LICENSE deleted file mode 100644 index 47b7b507..00000000 --- a/scripts/2.5/node_modules/is-nan/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014 Jordan Harband - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software is furnished to do so, -subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS -FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR -COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/scripts/2.5/node_modules/is-nan/README.md b/scripts/2.5/node_modules/is-nan/README.md deleted file mode 100644 index 5beebc95..00000000 --- a/scripts/2.5/node_modules/is-nan/README.md +++ /dev/null @@ -1,56 +0,0 @@ -#is-nan [![Version Badge][2]][1] - -[![Build Status][3]][4] -[![dependency status][5]][6] -[![dev dependency status][7]][8] -[![License][license-image]][license-url] -[![Downloads][downloads-image]][downloads-url] - -[![npm badge][11]][1] - -[![browser support][9]][10] - -ES6-compliant shim for Number.isNaN - the global isNaN returns false positives. - -This package implements the [es-shim API](https://github.com/es-shims/api) interface. It works in an ES3-supported environment and complies with the [spec](http://www.ecma-international.org/ecma-262/6.0/#sec-number.isnan). - -## Example - -```js -Number.isNaN = require('is-nan'); -var assert = require('assert'); - -assert.notOk(Number.isNaN(undefined)); -assert.notOk(Number.isNaN(null)); -assert.notOk(Number.isNaN(false)); -assert.notOk(Number.isNaN(true)); -assert.notOk(Number.isNaN(0)); -assert.notOk(Number.isNaN(42)); -assert.notOk(Number.isNaN(Infinity)); -assert.notOk(Number.isNaN(-Infinity)); -assert.notOk(Number.isNaN('foo')); -assert.notOk(Number.isNaN(function () {})); -assert.notOk(Number.isNaN([])); -assert.notOk(Number.isNaN({})); - -assert.ok(Number.isNaN(NaN)); -``` - -## Tests -Simply clone the repo, `npm install`, and run `npm test` - -[1]: https://npmjs.org/package/is-nan -[2]: http://versionbadg.es/ljharb/is-nan.svg -[3]: https://travis-ci.org/ljharb/is-nan.svg -[4]: https://travis-ci.org/ljharb/is-nan -[5]: https://david-dm.org/ljharb/is-nan.svg -[6]: https://david-dm.org/ljharb/is-nan -[7]: https://david-dm.org/ljharb/is-nan/dev-status.svg -[8]: https://david-dm.org/ljharb/is-nan#info=devDependencies -[9]: https://ci.testling.com/ljharb/is-nan.png -[10]: https://ci.testling.com/ljharb/is-nan -[11]: https://nodei.co/npm/is-nan.png?downloads=true&stars=true -[license-image]: http://img.shields.io/npm/l/is-nan.svg -[license-url]: LICENSE -[downloads-image]: http://img.shields.io/npm/dm/is-nan.svg -[downloads-url]: http://npm-stat.com/charts.html?package=is-nan diff --git a/scripts/2.5/node_modules/is-nan/implementation.js b/scripts/2.5/node_modules/is-nan/implementation.js deleted file mode 100644 index 6200b6b7..00000000 --- a/scripts/2.5/node_modules/is-nan/implementation.js +++ /dev/null @@ -1,7 +0,0 @@ -'use strict'; - -/* http://www.ecma-international.org/ecma-262/6.0/#sec-number.isnan */ - -module.exports = function isNaN(value) { - return value !== value; -}; diff --git a/scripts/2.5/node_modules/is-nan/index.js b/scripts/2.5/node_modules/is-nan/index.js deleted file mode 100644 index 5b327213..00000000 --- a/scripts/2.5/node_modules/is-nan/index.js +++ /dev/null @@ -1,17 +0,0 @@ -'use strict'; - -var define = require('define-properties'); - -var implementation = require('./implementation'); -var getPolyfill = require('./polyfill'); -var shim = require('./shim'); - -/* http://www.ecma-international.org/ecma-262/6.0/#sec-number.isnan */ - -define(implementation, { - getPolyfill: getPolyfill, - implementation: implementation, - shim: shim -}); - -module.exports = implementation; diff --git a/scripts/2.5/node_modules/is-nan/package.json b/scripts/2.5/node_modules/is-nan/package.json deleted file mode 100644 index 213ed48e..00000000 --- a/scripts/2.5/node_modules/is-nan/package.json +++ /dev/null @@ -1,101 +0,0 @@ -{ - "_from": "is-nan@^1.2.1", - "_id": "is-nan@1.2.1", - "_inBundle": false, - "_integrity": "sha1-n69ltvttskt/XAYoR16nH5iEAeI=", - "_location": "/is-nan", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "is-nan@^1.2.1", - "name": "is-nan", - "escapedName": "is-nan", - "rawSpec": "^1.2.1", - "saveSpec": null, - "fetchSpec": "^1.2.1" - }, - "_requiredBy": [ - "/assert" - ], - "_resolved": "https://registry.npmjs.org/is-nan/-/is-nan-1.2.1.tgz", - "_shasum": "9faf65b6fb6db24b7f5c0628475ea71f988401e2", - "_spec": "is-nan@^1.2.1", - "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/2.5/node_modules/assert", - "author": { - "name": "Jordan Harband" - }, - "bugs": { - "url": "https://github.com/ljharb/is-nan/issues" - }, - "bundleDependencies": false, - "dependencies": { - "define-properties": "^1.1.1" - }, - "deprecated": false, - "description": "ES6-compliant shim for Number.isNaN - the global isNaN returns false positives.", - "devDependencies": { - "@es-shims/api": "^1.0.0", - "@ljharb/eslint-config": "^1.0.4", - "covert": "^1.1.0", - "es5-shim": "^4.1.10", - "eslint": "^1.1.0", - "jscs": "^2.1.0", - "nsp": "^1.0.3", - "tape": "^4.2.0" - }, - "engines": { - "node": ">= 0.4" - }, - "homepage": "https://github.com/ljharb/is-nan", - "keywords": [ - "is", - "NaN", - "not a number", - "number", - "isNaN", - "ES6", - "shim", - "polyfill", - "es-shim API" - ], - "license": "MIT", - "main": "index.js", - "name": "is-nan", - "repository": { - "type": "git", - "url": "git://github.com/ljharb/is-nan.git" - }, - "scripts": { - "coverage": "covert test/*.js", - "coverage-quiet": "covert test/*.js --quiet", - "eslint": "eslint *.js test/*.js", - "jscs": "jscs *.js test/*.js", - "lint": "npm run jscs && npm run eslint", - "security": "nsp package", - "test": "npm run lint && es-shim-api && npm run tests-only && npm run security", - "test:function": "node test/index.js", - "test:shimmed": "node test/shimmed.js", - "tests-only": "npm run test:function && npm run test:shimmed" - }, - "testling": { - "files": "test.js", - "browsers": [ - "iexplore/6.0..latest", - "firefox/3.0..6.0", - "firefox/15.0..latest", - "firefox/nightly", - "chrome/4.0..10.0", - "chrome/20.0..latest", - "chrome/canary", - "opera/10.0..12.0", - "opera/15.0..latest", - "opera/next", - "safari/4.0..latest", - "ipad/6.0..latest", - "iphone/6.0..latest", - "android-browser/4.2" - ] - }, - "version": "1.2.1" -} diff --git a/scripts/2.5/node_modules/is-nan/polyfill.js b/scripts/2.5/node_modules/is-nan/polyfill.js deleted file mode 100644 index 2fa5886a..00000000 --- a/scripts/2.5/node_modules/is-nan/polyfill.js +++ /dev/null @@ -1,10 +0,0 @@ -'use strict'; - -var implementation = require('./implementation'); - -module.exports = function getPolyfill() { - if (Number.isNaN && Number.isNaN(NaN) && !Number.isNaN('a')) { - return Number.isNaN; - } - return implementation; -}; diff --git a/scripts/2.5/node_modules/is-nan/shim.js b/scripts/2.5/node_modules/is-nan/shim.js deleted file mode 100644 index abaa4954..00000000 --- a/scripts/2.5/node_modules/is-nan/shim.js +++ /dev/null @@ -1,12 +0,0 @@ -'use strict'; - -var define = require('define-properties'); -var getPolyfill = require('./polyfill'); - -/* http://www.ecma-international.org/ecma-262/6.0/#sec-number.isnan */ - -module.exports = function shimNumberIsNaN() { - var polyfill = getPolyfill(); - define(Number, { isNaN: polyfill }, { isNaN: function () { return Number.isNaN !== polyfill; } }); - return polyfill; -}; diff --git a/scripts/2.5/node_modules/is-nan/test/index.js b/scripts/2.5/node_modules/is-nan/test/index.js deleted file mode 100644 index 0711154c..00000000 --- a/scripts/2.5/node_modules/is-nan/test/index.js +++ /dev/null @@ -1,10 +0,0 @@ -'use strict'; - -var numberIsNaN = require('../'); -var test = require('tape'); - -test('as a function', function (t) { - require('./tests')(numberIsNaN, t); - - t.end(); -}); diff --git a/scripts/2.5/node_modules/is-nan/test/shimmed.js b/scripts/2.5/node_modules/is-nan/test/shimmed.js deleted file mode 100644 index ab1353cb..00000000 --- a/scripts/2.5/node_modules/is-nan/test/shimmed.js +++ /dev/null @@ -1,28 +0,0 @@ -'use strict'; - -require('es5-shim'); - -var numberIsNaN = require('../'); -numberIsNaN.shim(); - -var test = require('tape'); -var defineProperties = require('define-properties'); -var isEnumerable = Object.prototype.propertyIsEnumerable; -var functionsHaveNames = function f() {}.name === 'f'; - -test('shimmed', function (t) { - t.equal(Number.isNaN.length, 1, 'Number.isNaN has a length of 1'); - t.test('Function name', { skip: !functionsHaveNames }, function (st) { - st.equal(Number.isNaN.name, 'isNaN', 'Number.isNaN has name "isNaN"'); - st.end(); - }); - - t.test('enumerability', { skip: !defineProperties.supportsDescriptors }, function (et) { - et.equal(false, isEnumerable.call(Number, 'isNaN'), 'Number.isNaN is not enumerable'); - et.end(); - }); - - require('./tests')(Number.isNaN, t); - - t.end(); -}); diff --git a/scripts/2.5/node_modules/is-nan/test/tests.js b/scripts/2.5/node_modules/is-nan/test/tests.js deleted file mode 100644 index 33d2dc37..00000000 --- a/scripts/2.5/node_modules/is-nan/test/tests.js +++ /dev/null @@ -1,36 +0,0 @@ -'use strict'; - -module.exports = function (numberIsNaN, t) { - t.test('not NaN', function (st) { - st.test('primitives', function (sst) { - sst.notOk(numberIsNaN(), 'undefined is not NaN'); - sst.notOk(numberIsNaN(null), 'null is not NaN'); - sst.notOk(numberIsNaN(false), 'false is not NaN'); - sst.notOk(numberIsNaN(true), 'true is not NaN'); - sst.notOk(numberIsNaN(0), 'positive zero is not NaN'); - sst.notOk(numberIsNaN(Infinity), 'Infinity is not NaN'); - sst.notOk(numberIsNaN(-Infinity), '-Infinity is not NaN'); - sst.notOk(numberIsNaN('foo'), 'string is not NaN'); - sst.notOk(numberIsNaN('NaN'), 'string NaN is not NaN'); - sst.end(); - }); - - st.notOk(numberIsNaN([]), 'array is not NaN'); - st.notOk(numberIsNaN({}), 'object is not NaN'); - st.notOk(numberIsNaN(function () {}), 'function is not NaN'); - - st.test('valueOf', function (vt) { - var obj = { valueOf: function () { return NaN; } }; - vt.ok(numberIsNaN(Number(obj)), 'object with valueOf of NaN, converted to Number, is NaN'); - vt.notOk(numberIsNaN(obj), 'object with valueOf of NaN is not NaN'); - vt.end(); - }); - - st.end(); - }); - - t.test('NaN literal', function (st) { - st.ok(numberIsNaN(NaN), 'NaN is NaN'); - st.end(); - }); -}; diff --git a/scripts/2.5/node_modules/is-regex/.eslintrc b/scripts/2.5/node_modules/is-regex/.eslintrc deleted file mode 100644 index fbb8e9de..00000000 --- a/scripts/2.5/node_modules/is-regex/.eslintrc +++ /dev/null @@ -1,9 +0,0 @@ -{ - "root": true, - - "extends": "@ljharb", - - "rules": { - "id-length": [1] - } -} diff --git a/scripts/2.5/node_modules/is-regex/.jscs.json b/scripts/2.5/node_modules/is-regex/.jscs.json deleted file mode 100644 index 3d099c4b..00000000 --- a/scripts/2.5/node_modules/is-regex/.jscs.json +++ /dev/null @@ -1,176 +0,0 @@ -{ - "es3": true, - - "additionalRules": [], - - "requireSemicolons": true, - - "disallowMultipleSpaces": true, - - "disallowIdentifierNames": [], - - "requireCurlyBraces": { - "allExcept": [], - "keywords": ["if", "else", "for", "while", "do", "try", "catch"] - }, - - "requireSpaceAfterKeywords": ["if", "else", "for", "while", "do", "switch", "return", "try", "catch", "function"], - - "disallowSpaceAfterKeywords": [], - - "disallowSpaceBeforeComma": true, - "disallowSpaceAfterComma": false, - "disallowSpaceBeforeSemicolon": true, - - "disallowNodeTypes": [ - "DebuggerStatement", - "ForInStatement", - "LabeledStatement", - "SwitchCase", - "SwitchStatement", - "WithStatement" - ], - - "requireObjectKeysOnNewLine": { "allExcept": ["sameLine"] }, - - "requireSpacesInAnonymousFunctionExpression": { "beforeOpeningRoundBrace": true, "beforeOpeningCurlyBrace": true }, - "requireSpacesInNamedFunctionExpression": { "beforeOpeningCurlyBrace": true }, - "disallowSpacesInNamedFunctionExpression": { "beforeOpeningRoundBrace": true }, - "requireSpacesInFunctionDeclaration": { "beforeOpeningCurlyBrace": true }, - "disallowSpacesInFunctionDeclaration": { "beforeOpeningRoundBrace": true }, - - "requireSpaceBetweenArguments": true, - - "disallowSpacesInsideParentheses": true, - - "disallowSpacesInsideArrayBrackets": true, - - "disallowQuotedKeysInObjects": { "allExcept": ["reserved"] }, - - "disallowSpaceAfterObjectKeys": true, - - "requireCommaBeforeLineBreak": true, - - "disallowSpaceAfterPrefixUnaryOperators": ["++", "--", "+", "-", "~", "!"], - "requireSpaceAfterPrefixUnaryOperators": [], - - "disallowSpaceBeforePostfixUnaryOperators": ["++", "--"], - "requireSpaceBeforePostfixUnaryOperators": [], - - "disallowSpaceBeforeBinaryOperators": [], - "requireSpaceBeforeBinaryOperators": ["+", "-", "/", "*", "=", "==", "===", "!=", "!=="], - - "requireSpaceAfterBinaryOperators": ["+", "-", "/", "*", "=", "==", "===", "!=", "!=="], - "disallowSpaceAfterBinaryOperators": [], - - "disallowImplicitTypeConversion": ["binary", "string"], - - "disallowKeywords": ["with", "eval"], - - "requireKeywordsOnNewLine": [], - "disallowKeywordsOnNewLine": ["else"], - - "requireLineFeedAtFileEnd": true, - - "disallowTrailingWhitespace": true, - - "disallowTrailingComma": true, - - "excludeFiles": ["node_modules/**", "vendor/**"], - - "disallowMultipleLineStrings": true, - - "requireDotNotation": { "allExcept": ["keywords"] }, - - "requireParenthesesAroundIIFE": true, - - "validateLineBreaks": "LF", - - "validateQuoteMarks": { - "escape": true, - "mark": "'" - }, - - "disallowOperatorBeforeLineBreak": [], - - "requireSpaceBeforeKeywords": [ - "do", - "for", - "if", - "else", - "switch", - "case", - "try", - "catch", - "finally", - "while", - "with", - "return" - ], - - "validateAlignedFunctionParameters": { - "lineBreakAfterOpeningBraces": true, - "lineBreakBeforeClosingBraces": true - }, - - "requirePaddingNewLinesBeforeExport": true, - - "validateNewlineAfterArrayElements": { - "maximum": 1 - }, - - "requirePaddingNewLinesAfterUseStrict": true, - - "disallowArrowFunctions": true, - - "disallowMultiLineTernary": true, - - "validateOrderInObjectKeys": "asc-insensitive", - - "disallowIdenticalDestructuringNames": true, - - "disallowNestedTernaries": { "maxLevel": 1 }, - - "requireSpaceAfterComma": { "allExcept": ["trailing"] }, - "requireAlignedMultilineParams": false, - - "requireSpacesInGenerator": { - "afterStar": true - }, - - "disallowSpacesInGenerator": { - "beforeStar": true - }, - - "disallowVar": false, - - "requireArrayDestructuring": false, - - "requireEnhancedObjectLiterals": false, - - "requireObjectDestructuring": false, - - "requireEarlyReturn": false, - - "requireCapitalizedConstructorsNew": { - "allExcept": ["Function", "String", "Object", "Symbol", "Number", "Date", "RegExp", "Error", "Boolean", "Array"] - }, - - "requireImportAlphabetized": false, - - "requireSpaceBeforeObjectValues": true, - "requireSpaceBeforeDestructuredValues": true, - - "disallowSpacesInsideTemplateStringPlaceholders": true, - - "disallowArrayDestructuringReturn": false, - - "requireNewlineBeforeSingleStatementsInIf": false, - - "disallowUnusedVariables": true, - - "requireSpacesInsideImportedObjectBraces": true, - - "requireUseStrict": true -} - diff --git a/scripts/2.5/node_modules/is-regex/.npmignore b/scripts/2.5/node_modules/is-regex/.npmignore deleted file mode 100644 index a72b52eb..00000000 --- a/scripts/2.5/node_modules/is-regex/.npmignore +++ /dev/null @@ -1,15 +0,0 @@ -lib-cov -*.seed -*.log -*.csv -*.dat -*.out -*.pid -*.gz - -pids -logs -results - -npm-debug.log -node_modules diff --git a/scripts/2.5/node_modules/is-regex/.travis.yml b/scripts/2.5/node_modules/is-regex/.travis.yml deleted file mode 100644 index 41137a89..00000000 --- a/scripts/2.5/node_modules/is-regex/.travis.yml +++ /dev/null @@ -1,165 +0,0 @@ -language: node_js -os: - - linux -node_js: - - "7.5" - - "6.9" - - "5.12" - - "4.7" - - "iojs-v3.3" - - "iojs-v2.5" - - "iojs-v1.8" - - "0.12" - - "0.10" - - "0.8" -before_install: - - 'if [ "${TRAVIS_NODE_VERSION}" = "0.6" ]; then npm install -g npm@1.3 ; elif [ "${TRAVIS_NODE_VERSION}" != "0.9" ]; then case "$(npm --version)" in 1.*) npm install -g npm@1.4.28 ;; 2.*) npm install -g npm@2 ;; esac ; fi' - - 'if [ "${TRAVIS_NODE_VERSION}" != "0.6" ] && [ "${TRAVIS_NODE_VERSION}" != "0.9" ]; then npm install -g npm; fi' -script: - - 'if [ -n "${PRETEST-}" ]; then npm run pretest ; fi' - - 'if [ -n "${POSTTEST-}" ]; then npm run posttest ; fi' - - 'if [ -n "${COVERAGE-}" ]; then npm run coverage ; fi' - - 'if [ -n "${TEST-}" ]; then npm run tests-only ; fi' -sudo: false -env: - - TEST=true -matrix: - fast_finish: true - include: - - node_js: "node" - env: PRETEST=true - - node_js: "node" - env: POSTTEST=true - - node_js: "7.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.11" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.10" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v3.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v3.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v3.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "0.11" - env: TEST=true ALLOW_FAILURE=true - - node_js: "0.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "0.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "0.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7" - env: TEST=true - os: osx - - node_js: "6" - env: TEST=true - os: osx - - node_js: "5" - env: TEST=true - os: osx - - node_js: "4" - env: TEST=true - os: osx - - node_js: "iojs" - env: TEST=true - os: osx - - node_js: "0.12" - env: TEST=true - os: osx - - node_js: "0.10" - env: TEST=true - os: osx - - node_js: "0.8" - env: TEST=true - os: osx - allow_failures: - - os: osx - - env: TEST=true ALLOW_FAILURE=true diff --git a/scripts/2.5/node_modules/is-regex/CHANGELOG.md b/scripts/2.5/node_modules/is-regex/CHANGELOG.md deleted file mode 100644 index 6d738000..00000000 --- a/scripts/2.5/node_modules/is-regex/CHANGELOG.md +++ /dev/null @@ -1,27 +0,0 @@ -1.0.4 / 2016-02-18 -================= - * [Fix] ensure that `lastIndex` is not mutated (#3) - * [Refactor] when try/catch is needed, bail early if the value lacks an own `lastIndex` data property - * [Refactor] use an early return instead of a ternary - * [Refactor] bail earlier when the value is falsy - * Switch from vb.teelaun.ch to versionbadg.es for the npm version badge SVG - * [Dev Deps] update `tape`, `jscs`, `editorconfig-tools`, `eslint`, `semver`, `replace`, `nsp`, `covert`, `@ljharb/eslint-config` - * [Tests] on all the node and io.js versions; improve test matri - * [Tests] Fix tests for faked @@toStringTag - -1.0.3 / 2015-01-29 -================= - * If @@toStringTag is not present, use the old-school Object#toString test. - -1.0.2 / 2015-01-29 -================= - * Improve optimization by separating the try/catch, and bailing out early when not typeof "object". - -1.0.1 / 2015-01-28 -================= - * Update `jscs`, `tape`, `covert` - * Use RegExp#exec to test if something is a regex, which works even with ES6 @@toStringTag. - -1.0.0 / 2014-05-19 -================= - * Initial release. diff --git a/scripts/2.5/node_modules/is-regex/LICENSE b/scripts/2.5/node_modules/is-regex/LICENSE deleted file mode 100644 index 47b7b507..00000000 --- a/scripts/2.5/node_modules/is-regex/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014 Jordan Harband - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software is furnished to do so, -subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS -FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR -COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/scripts/2.5/node_modules/is-regex/Makefile b/scripts/2.5/node_modules/is-regex/Makefile deleted file mode 100644 index b9e4fe1a..00000000 --- a/scripts/2.5/node_modules/is-regex/Makefile +++ /dev/null @@ -1,61 +0,0 @@ -# Since we rely on paths relative to the makefile location, abort if make isn't being run from there. -$(if $(findstring /,$(MAKEFILE_LIST)),$(error Please only invoke this makefile from the directory it resides in)) - - # The files that need updating when incrementing the version number. -VERSIONED_FILES := *.js *.json README* - - -# Add the local npm packages' bin folder to the PATH, so that `make` can find them, when invoked directly. -# Note that rather than using `$(npm bin)` the 'node_modules/.bin' path component is hard-coded, so that invocation works even from an environment -# where npm is (temporarily) unavailable due to having deactivated an nvm instance loaded into the calling shell in order to avoid interference with tests. -export PATH := $(shell printf '%s' "$$PWD/node_modules/.bin:$$PATH") -UTILS := semver -# Make sure that all required utilities can be located. -UTIL_CHECK := $(or $(shell PATH="$(PATH)" which $(UTILS) >/dev/null && echo 'ok'),$(error Did you forget to run `npm install` after cloning the repo? At least one of the required supporting utilities not found: $(UTILS))) - -# Default target (by virtue of being the first non '.'-prefixed in the file). -.PHONY: _no-target-specified -_no-target-specified: - $(error Please specify the target to make - `make list` shows targets. Alternatively, use `npm test` to run the default tests; `npm run` shows all tests) - -# Lists all targets defined in this makefile. -.PHONY: list -list: - @$(MAKE) -pRrn : -f $(MAKEFILE_LIST) 2>/dev/null | awk -v RS= -F: '/^# File/,/^# Finished Make data base/ {if ($$1 !~ "^[#.]") {print $$1}}' | command grep -v -e '^[^[:alnum:]]' -e '^$@$$command ' | sort - -# All-tests target: invokes the specified test suites for ALL shells defined in $(SHELLS). -.PHONY: test -test: - @npm test - -.PHONY: _ensure-tag -_ensure-tag: -ifndef TAG - $(error Please invoke with `make TAG= release`, where is either an increment specifier (patch, minor, major, prepatch, preminor, premajor, prerelease), or an explicit major.minor.patch version number) -endif - -CHANGELOG_ERROR = $(error No CHANGELOG specified) -.PHONY: _ensure-changelog -_ensure-changelog: - @ (git status -sb --porcelain | command grep -E '^( M|[MA] ) CHANGELOG.md' > /dev/null) || (echo no CHANGELOG.md specified && exit 2) - -# Ensures that the git workspace is clean. -.PHONY: _ensure-clean -_ensure-clean: - @[ -z "$$((git status --porcelain --untracked-files=no || echo err) | command grep -v 'CHANGELOG.md')" ] || { echo "Workspace is not clean; please commit changes first." >&2; exit 2; } - -# Makes a release; invoke with `make TAG= release`. -.PHONY: release -release: _ensure-tag _ensure-changelog _ensure-clean - @old_ver=`git describe --abbrev=0 --tags --match 'v[0-9]*.[0-9]*.[0-9]*'` || { echo "Failed to determine current version." >&2; exit 1; }; old_ver=$${old_ver#v}; \ - new_ver=`echo "$(TAG)" | sed 's/^v//'`; new_ver=$${new_ver:-patch}; \ - if printf "$$new_ver" | command grep -q '^[0-9]'; then \ - semver "$$new_ver" >/dev/null || { echo 'Invalid version number specified: $(TAG) - must be major.minor.patch' >&2; exit 2; }; \ - semver -r "> $$old_ver" "$$new_ver" >/dev/null || { echo 'Invalid version number specified: $(TAG) - must be HIGHER than current one.' >&2; exit 2; } \ - else \ - new_ver=`semver -i "$$new_ver" "$$old_ver"` || { echo 'Invalid version-increment specifier: $(TAG)' >&2; exit 2; } \ - fi; \ - printf "=== Bumping version **$$old_ver** to **$$new_ver** before committing and tagging:\n=== TYPE 'proceed' TO PROCEED, anything else to abort: " && read response && [ "$$response" = 'proceed' ] || { echo 'Aborted.' >&2; exit 2; }; \ - replace "$$old_ver" "$$new_ver" -- $(VERSIONED_FILES) && \ - git commit -m "v$$new_ver" $(VERSIONED_FILES) CHANGELOG.md && \ - git tag -a -m "v$$new_ver" "v$$new_ver" diff --git a/scripts/2.5/node_modules/is-regex/README.md b/scripts/2.5/node_modules/is-regex/README.md deleted file mode 100644 index 05baa0eb..00000000 --- a/scripts/2.5/node_modules/is-regex/README.md +++ /dev/null @@ -1,54 +0,0 @@ -#is-regex [![Version Badge][2]][1] - -[![Build Status][3]][4] -[![dependency status][5]][6] -[![dev dependency status][7]][8] -[![License][license-image]][license-url] -[![Downloads][downloads-image]][downloads-url] - -[![npm badge][11]][1] - -[![browser support][9]][10] - -Is this value a JS regex? -This module works cross-realm/iframe, and despite ES6 @@toStringTag. - -## Example - -```js -var isRegex = require('is-regex'); -var assert = require('assert'); - -assert.notOk(isRegex(undefined)); -assert.notOk(isRegex(null)); -assert.notOk(isRegex(false)); -assert.notOk(isRegex(true)); -assert.notOk(isRegex(42)); -assert.notOk(isRegex('foo')); -assert.notOk(isRegex(function () {})); -assert.notOk(isRegex([])); -assert.notOk(isRegex({})); - -assert.ok(isRegex(/a/g)); -assert.ok(isRegex(new RegExp('a', 'g'))); -``` - -## Tests -Simply clone the repo, `npm install`, and run `npm test` - -[1]: https://npmjs.org/package/is-regex -[2]: http://versionbadg.es/ljharb/is-regex.svg -[3]: https://travis-ci.org/ljharb/is-regex.svg -[4]: https://travis-ci.org/ljharb/is-regex -[5]: https://david-dm.org/ljharb/is-regex.svg -[6]: https://david-dm.org/ljharb/is-regex -[7]: https://david-dm.org/ljharb/is-regex/dev-status.svg -[8]: https://david-dm.org/ljharb/is-regex#info=devDependencies -[9]: https://ci.testling.com/ljharb/is-regex.png -[10]: https://ci.testling.com/ljharb/is-regex -[11]: https://nodei.co/npm/is-regex.png?downloads=true&stars=true -[license-image]: http://img.shields.io/npm/l/is-regex.svg -[license-url]: LICENSE -[downloads-image]: http://img.shields.io/npm/dm/is-regex.svg -[downloads-url]: http://npm-stat.com/charts.html?package=is-regex - diff --git a/scripts/2.5/node_modules/is-regex/index.js b/scripts/2.5/node_modules/is-regex/index.js deleted file mode 100644 index be651339..00000000 --- a/scripts/2.5/node_modules/is-regex/index.js +++ /dev/null @@ -1,39 +0,0 @@ -'use strict'; - -var has = require('has'); -var regexExec = RegExp.prototype.exec; -var gOPD = Object.getOwnPropertyDescriptor; - -var tryRegexExecCall = function tryRegexExec(value) { - try { - var lastIndex = value.lastIndex; - value.lastIndex = 0; - - regexExec.call(value); - return true; - } catch (e) { - return false; - } finally { - value.lastIndex = lastIndex; - } -}; -var toStr = Object.prototype.toString; -var regexClass = '[object RegExp]'; -var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol'; - -module.exports = function isRegex(value) { - if (!value || typeof value !== 'object') { - return false; - } - if (!hasToStringTag) { - return toStr.call(value) === regexClass; - } - - var descriptor = gOPD(value, 'lastIndex'); - var hasLastIndexDataProperty = descriptor && has(descriptor, 'value'); - if (!hasLastIndexDataProperty) { - return false; - } - - return tryRegexExecCall(value); -}; diff --git a/scripts/2.5/node_modules/is-regex/package.json b/scripts/2.5/node_modules/is-regex/package.json deleted file mode 100644 index 8e3bd384..00000000 --- a/scripts/2.5/node_modules/is-regex/package.json +++ /dev/null @@ -1,100 +0,0 @@ -{ - "_from": "is-regex@^1.0.4", - "_id": "is-regex@1.0.4", - "_inBundle": false, - "_integrity": "sha1-VRdIm1RwkbCTDglWVM7SXul+lJE=", - "_location": "/is-regex", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "is-regex@^1.0.4", - "name": "is-regex", - "escapedName": "is-regex", - "rawSpec": "^1.0.4", - "saveSpec": null, - "fetchSpec": "^1.0.4" - }, - "_requiredBy": [ - "/es-abstract" - ], - "_resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.0.4.tgz", - "_shasum": "5517489b547091b0930e095654ced25ee97e9491", - "_spec": "is-regex@^1.0.4", - "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/2.5/node_modules/es-abstract", - "author": { - "name": "Jordan Harband" - }, - "bugs": { - "url": "https://github.com/ljharb/is-regex/issues" - }, - "bundleDependencies": false, - "dependencies": { - "has": "^1.0.1" - }, - "deprecated": false, - "description": "Is this value a JS regex? Works cross-realm/iframe, and despite ES6 @@toStringTag", - "devDependencies": { - "@ljharb/eslint-config": "^11.0.0", - "covert": "^1.1.0", - "editorconfig-tools": "^0.1.1", - "eslint": "^3.15.0", - "jscs": "^3.0.7", - "nsp": "^2.6.2", - "replace": "^0.3.0", - "semver": "^5.3.0", - "tape": "^4.6.3" - }, - "engines": { - "node": ">= 0.4" - }, - "homepage": "https://github.com/ljharb/is-regex", - "keywords": [ - "regex", - "regexp", - "is", - "regular expression", - "regular", - "expression" - ], - "license": "MIT", - "main": "index.js", - "name": "is-regex", - "repository": { - "type": "git", - "url": "git://github.com/ljharb/is-regex.git" - }, - "scripts": { - "coverage": "covert test.js", - "coverage-quiet": "covert test.js --quiet", - "eccheck": "editorconfig-tools check *.js **/*.js > /dev/null", - "eslint": "eslint test.js *.js", - "jscs": "jscs *.js", - "lint": "npm run jscs && npm run eslint", - "posttest": "npm run security", - "pretest": "npm run lint", - "security": "nsp check", - "test": "npm run tests-only", - "tests-only": "node --harmony --es-staging test.js" - }, - "testling": { - "files": "test.js", - "browsers": [ - "iexplore/6.0..latest", - "firefox/3.0..6.0", - "firefox/15.0..latest", - "firefox/nightly", - "chrome/4.0..10.0", - "chrome/20.0..latest", - "chrome/canary", - "opera/10.0..12.0", - "opera/15.0..latest", - "opera/next", - "safari/4.0..latest", - "ipad/6.0..latest", - "iphone/6.0..latest", - "android-browser/4.2" - ] - }, - "version": "1.0.4" -} diff --git a/scripts/2.5/node_modules/is-regex/test.js b/scripts/2.5/node_modules/is-regex/test.js deleted file mode 100644 index 8d390038..00000000 --- a/scripts/2.5/node_modules/is-regex/test.js +++ /dev/null @@ -1,58 +0,0 @@ -'use strict'; - -var test = require('tape'); -var isRegex = require('./'); -var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol'; - -test('not regexes', function (t) { - t.notOk(isRegex(), 'undefined is not regex'); - t.notOk(isRegex(null), 'null is not regex'); - t.notOk(isRegex(false), 'false is not regex'); - t.notOk(isRegex(true), 'true is not regex'); - t.notOk(isRegex(42), 'number is not regex'); - t.notOk(isRegex('foo'), 'string is not regex'); - t.notOk(isRegex([]), 'array is not regex'); - t.notOk(isRegex({}), 'object is not regex'); - t.notOk(isRegex(function () {}), 'function is not regex'); - t.end(); -}); - -test('@@toStringTag', { skip: !hasToStringTag }, function (t) { - var regex = /a/g; - var fakeRegex = { - toString: function () { return String(regex); }, - valueOf: function () { return regex; } - }; - fakeRegex[Symbol.toStringTag] = 'RegExp'; - t.notOk(isRegex(fakeRegex), 'fake RegExp with @@toStringTag "RegExp" is not regex'); - t.end(); -}); - -test('regexes', function (t) { - t.ok(isRegex(/a/g), 'regex literal is regex'); - t.ok(isRegex(new RegExp('a', 'g')), 'regex object is regex'); - t.end(); -}); - -test('does not mutate regexes', function (t) { - t.test('lastIndex is a marker object', function (st) { - var regex = /a/; - var marker = {}; - regex.lastIndex = marker; - st.equal(regex.lastIndex, marker, 'lastIndex is the marker object'); - st.ok(isRegex(regex), 'is regex'); - st.equal(regex.lastIndex, marker, 'lastIndex is the marker object after isRegex'); - st.end(); - }); - - t.test('lastIndex is nonzero', function (st) { - var regex = /a/; - regex.lastIndex = 3; - st.equal(regex.lastIndex, 3, 'lastIndex is 3'); - st.ok(isRegex(regex), 'is regex'); - st.equal(regex.lastIndex, 3, 'lastIndex is 3 after isRegex'); - st.end(); - }); - - t.end(); -}); diff --git a/scripts/2.5/node_modules/is-symbol/.editorconfig b/scripts/2.5/node_modules/is-symbol/.editorconfig deleted file mode 100644 index eaa21416..00000000 --- a/scripts/2.5/node_modules/is-symbol/.editorconfig +++ /dev/null @@ -1,13 +0,0 @@ -root = true - -[*] -indent_style = tab; -insert_final_newline = true; -quote_type = auto; -space_after_anonymous_functions = true; -space_after_control_statements = true; -spaces_around_operators = true; -trim_trailing_whitespace = true; -spaces_in_brackets = false; -end_of_line = lf; - diff --git a/scripts/2.5/node_modules/is-symbol/.eslintrc b/scripts/2.5/node_modules/is-symbol/.eslintrc deleted file mode 100644 index 5f511fd0..00000000 --- a/scripts/2.5/node_modules/is-symbol/.eslintrc +++ /dev/null @@ -1,9 +0,0 @@ -{ - "root": true, - - "extends": "@ljharb", - - "rules": { - "max-statements": [2, 14] - } -} diff --git a/scripts/2.5/node_modules/is-symbol/.jscs.json b/scripts/2.5/node_modules/is-symbol/.jscs.json deleted file mode 100644 index b4d9b8b4..00000000 --- a/scripts/2.5/node_modules/is-symbol/.jscs.json +++ /dev/null @@ -1,176 +0,0 @@ -{ - "es3": true, - - "additionalRules": [], - - "requireSemicolons": true, - - "disallowMultipleSpaces": true, - - "disallowIdentifierNames": [], - - "requireCurlyBraces": { - "allExcept": [], - "keywords": ["if", "else", "for", "while", "do", "try", "catch"] - }, - - "requireSpaceAfterKeywords": ["if", "else", "for", "while", "do", "switch", "return", "try", "catch", "function"], - - "disallowSpaceAfterKeywords": [], - - "disallowSpaceBeforeComma": true, - "disallowSpaceAfterComma": false, - "disallowSpaceBeforeSemicolon": true, - - "disallowNodeTypes": [ - "DebuggerStatement", - "ForInStatement", - "LabeledStatement", - "SwitchCase", - "SwitchStatement", - "WithStatement" - ], - - "requireObjectKeysOnNewLine": { "allExcept": ["sameLine"] }, - - "requireSpacesInAnonymousFunctionExpression": { "beforeOpeningRoundBrace": true, "beforeOpeningCurlyBrace": true }, - "requireSpacesInNamedFunctionExpression": { "beforeOpeningCurlyBrace": true }, - "disallowSpacesInNamedFunctionExpression": { "beforeOpeningRoundBrace": true }, - "requireSpacesInFunctionDeclaration": { "beforeOpeningCurlyBrace": true }, - "disallowSpacesInFunctionDeclaration": { "beforeOpeningRoundBrace": true }, - - "requireSpaceBetweenArguments": true, - - "disallowSpacesInsideParentheses": true, - - "disallowSpacesInsideArrayBrackets": true, - - "disallowQuotedKeysInObjects": { "allExcept": ["reserved"] }, - - "disallowSpaceAfterObjectKeys": true, - - "requireCommaBeforeLineBreak": true, - - "disallowSpaceAfterPrefixUnaryOperators": ["++", "--", "+", "-", "~", "!"], - "requireSpaceAfterPrefixUnaryOperators": [], - - "disallowSpaceBeforePostfixUnaryOperators": ["++", "--"], - "requireSpaceBeforePostfixUnaryOperators": [], - - "disallowSpaceBeforeBinaryOperators": [], - "requireSpaceBeforeBinaryOperators": ["+", "-", "/", "*", "=", "==", "===", "!=", "!=="], - - "requireSpaceAfterBinaryOperators": ["+", "-", "/", "*", "=", "==", "===", "!=", "!=="], - "disallowSpaceAfterBinaryOperators": [], - - "disallowImplicitTypeConversion": ["binary", "string"], - - "disallowKeywords": ["with", "eval"], - - "requireKeywordsOnNewLine": [], - "disallowKeywordsOnNewLine": ["else"], - - "requireLineFeedAtFileEnd": true, - - "disallowTrailingWhitespace": true, - - "disallowTrailingComma": true, - - "excludeFiles": ["node_modules/**", "vendor/**"], - - "disallowMultipleLineStrings": true, - - "requireDotNotation": { "allExcept": ["keywords"] }, - - "requireParenthesesAroundIIFE": true, - - "validateLineBreaks": "LF", - - "validateQuoteMarks": { - "escape": true, - "mark": "'" - }, - - "disallowOperatorBeforeLineBreak": [], - - "requireSpaceBeforeKeywords": [ - "do", - "for", - "if", - "else", - "switch", - "case", - "try", - "catch", - "finally", - "while", - "with", - "return" - ], - - "validateAlignedFunctionParameters": { - "lineBreakAfterOpeningBraces": true, - "lineBreakBeforeClosingBraces": true - }, - - "requirePaddingNewLinesBeforeExport": true, - - "validateNewlineAfterArrayElements": { - "maximum": 1 - }, - - "requirePaddingNewLinesAfterUseStrict": true, - - "disallowArrowFunctions": true, - - "disallowMultiLineTernary": true, - - "validateOrderInObjectKeys": "asc-insensitive", - - "disallowIdenticalDestructuringNames": true, - - "disallowNestedTernaries": { "maxLevel": 1 }, - - "requireSpaceAfterComma": { "allExcept": ["trailing"] }, - "requireAlignedMultilineParams": false, - - "requireSpacesInGenerator": { - "afterStar": true - }, - - "disallowSpacesInGenerator": { - "beforeStar": true - }, - - "disallowVar": false, - - "requireArrayDestructuring": false, - - "requireEnhancedObjectLiterals": false, - - "requireObjectDestructuring": false, - - "requireEarlyReturn": false, - - "requireCapitalizedConstructorsNew": { - "allExcept": ["Function", "String", "Object", "Symbol", "Number", "Date", "RegExp", "Error", "Boolean", "Array"] - }, - - "requireImportAlphabetized": false, - - "requireSpaceBeforeObjectValues": true, - "requireSpaceBeforeDestructuredValues": true, - - "disallowSpacesInsideTemplateStringPlaceholders": true, - - "disallowArrayDestructuringReturn": false, - - "requireNewlineBeforeSingleStatementsInIf": false, - - "disallowUnusedVariables": true, - - "requireSpacesInsideImportedObjectBraces": true, - - "requireUseStrict": true -} - diff --git a/scripts/2.5/node_modules/is-symbol/.nvmrc b/scripts/2.5/node_modules/is-symbol/.nvmrc deleted file mode 100644 index 64f5a0a6..00000000 --- a/scripts/2.5/node_modules/is-symbol/.nvmrc +++ /dev/null @@ -1 +0,0 @@ -node diff --git a/scripts/2.5/node_modules/is-symbol/.travis.yml b/scripts/2.5/node_modules/is-symbol/.travis.yml deleted file mode 100644 index c671d5ea..00000000 --- a/scripts/2.5/node_modules/is-symbol/.travis.yml +++ /dev/null @@ -1,241 +0,0 @@ -language: node_js -os: - - linux -node_js: - - "10.11" - - "9.11" - - "8.12" - - "7.10" - - "6.14" - - "5.12" - - "4.9" - - "iojs-v3.3" - - "iojs-v2.5" - - "iojs-v1.8" - - "0.12" - - "0.10" - - "0.8" -before_install: - - 'case "${TRAVIS_NODE_VERSION}" in 0.*) export NPM_CONFIG_STRICT_SSL=false ;; esac' - - 'nvm install-latest-npm' -install: - - 'if [ "${TRAVIS_NODE_VERSION}" = "0.6" ] || [ "${TRAVIS_NODE_VERSION}" = "0.9" ]; then nvm install --latest-npm 0.8 && npm install && nvm use "${TRAVIS_NODE_VERSION}"; else npm install; fi;' -script: - - 'if [ -n "${PRETEST-}" ]; then npm run pretest ; fi' - - 'if [ -n "${POSTTEST-}" ]; then npm run posttest ; fi' - - 'if [ -n "${COVERAGE-}" ]; then npm run coverage ; fi' - - 'if [ -n "${TEST-}" ]; then npm run tests-only ; fi' -sudo: false -env: - - TEST=true -matrix: - fast_finish: true - include: - - node_js: "lts/*" - env: PRETEST=true - - node_js: "lts/*" - env: POSTTEST=true - - node_js: "4" - env: COVERAGE=true - - node_js: "10.10" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.10" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.11" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.10" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.13" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.12" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.11" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.10" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.11" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.10" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v3.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v3.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v3.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "0.11" - env: TEST=true ALLOW_FAILURE=true - - node_js: "0.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "0.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "0.4" - env: TEST=true ALLOW_FAILURE=true - allow_failures: - - os: osx - - env: TEST=true ALLOW_FAILURE=true - - env: COVERAGE=true diff --git a/scripts/2.5/node_modules/is-symbol/CHANGELOG.md b/scripts/2.5/node_modules/is-symbol/CHANGELOG.md deleted file mode 100644 index a7b8baf8..00000000 --- a/scripts/2.5/node_modules/is-symbol/CHANGELOG.md +++ /dev/null @@ -1,12 +0,0 @@ -1.0.2 / 2018-09-20 -================= - * [Refactor] use `has-symbols` and `object-inspect` - * [Tests] test on all the node minor versions - -1.0.1 / 2015-01-26 -================= - * Corrected description - -1.0.0 / 2015-01-24 -================= - * Initial release diff --git a/scripts/2.5/node_modules/is-symbol/LICENSE b/scripts/2.5/node_modules/is-symbol/LICENSE deleted file mode 100644 index b43df444..00000000 --- a/scripts/2.5/node_modules/is-symbol/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015 Jordan Harband - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - diff --git a/scripts/2.5/node_modules/is-symbol/Makefile b/scripts/2.5/node_modules/is-symbol/Makefile deleted file mode 100644 index b9e4fe1a..00000000 --- a/scripts/2.5/node_modules/is-symbol/Makefile +++ /dev/null @@ -1,61 +0,0 @@ -# Since we rely on paths relative to the makefile location, abort if make isn't being run from there. -$(if $(findstring /,$(MAKEFILE_LIST)),$(error Please only invoke this makefile from the directory it resides in)) - - # The files that need updating when incrementing the version number. -VERSIONED_FILES := *.js *.json README* - - -# Add the local npm packages' bin folder to the PATH, so that `make` can find them, when invoked directly. -# Note that rather than using `$(npm bin)` the 'node_modules/.bin' path component is hard-coded, so that invocation works even from an environment -# where npm is (temporarily) unavailable due to having deactivated an nvm instance loaded into the calling shell in order to avoid interference with tests. -export PATH := $(shell printf '%s' "$$PWD/node_modules/.bin:$$PATH") -UTILS := semver -# Make sure that all required utilities can be located. -UTIL_CHECK := $(or $(shell PATH="$(PATH)" which $(UTILS) >/dev/null && echo 'ok'),$(error Did you forget to run `npm install` after cloning the repo? At least one of the required supporting utilities not found: $(UTILS))) - -# Default target (by virtue of being the first non '.'-prefixed in the file). -.PHONY: _no-target-specified -_no-target-specified: - $(error Please specify the target to make - `make list` shows targets. Alternatively, use `npm test` to run the default tests; `npm run` shows all tests) - -# Lists all targets defined in this makefile. -.PHONY: list -list: - @$(MAKE) -pRrn : -f $(MAKEFILE_LIST) 2>/dev/null | awk -v RS= -F: '/^# File/,/^# Finished Make data base/ {if ($$1 !~ "^[#.]") {print $$1}}' | command grep -v -e '^[^[:alnum:]]' -e '^$@$$command ' | sort - -# All-tests target: invokes the specified test suites for ALL shells defined in $(SHELLS). -.PHONY: test -test: - @npm test - -.PHONY: _ensure-tag -_ensure-tag: -ifndef TAG - $(error Please invoke with `make TAG= release`, where is either an increment specifier (patch, minor, major, prepatch, preminor, premajor, prerelease), or an explicit major.minor.patch version number) -endif - -CHANGELOG_ERROR = $(error No CHANGELOG specified) -.PHONY: _ensure-changelog -_ensure-changelog: - @ (git status -sb --porcelain | command grep -E '^( M|[MA] ) CHANGELOG.md' > /dev/null) || (echo no CHANGELOG.md specified && exit 2) - -# Ensures that the git workspace is clean. -.PHONY: _ensure-clean -_ensure-clean: - @[ -z "$$((git status --porcelain --untracked-files=no || echo err) | command grep -v 'CHANGELOG.md')" ] || { echo "Workspace is not clean; please commit changes first." >&2; exit 2; } - -# Makes a release; invoke with `make TAG= release`. -.PHONY: release -release: _ensure-tag _ensure-changelog _ensure-clean - @old_ver=`git describe --abbrev=0 --tags --match 'v[0-9]*.[0-9]*.[0-9]*'` || { echo "Failed to determine current version." >&2; exit 1; }; old_ver=$${old_ver#v}; \ - new_ver=`echo "$(TAG)" | sed 's/^v//'`; new_ver=$${new_ver:-patch}; \ - if printf "$$new_ver" | command grep -q '^[0-9]'; then \ - semver "$$new_ver" >/dev/null || { echo 'Invalid version number specified: $(TAG) - must be major.minor.patch' >&2; exit 2; }; \ - semver -r "> $$old_ver" "$$new_ver" >/dev/null || { echo 'Invalid version number specified: $(TAG) - must be HIGHER than current one.' >&2; exit 2; } \ - else \ - new_ver=`semver -i "$$new_ver" "$$old_ver"` || { echo 'Invalid version-increment specifier: $(TAG)' >&2; exit 2; } \ - fi; \ - printf "=== Bumping version **$$old_ver** to **$$new_ver** before committing and tagging:\n=== TYPE 'proceed' TO PROCEED, anything else to abort: " && read response && [ "$$response" = 'proceed' ] || { echo 'Aborted.' >&2; exit 2; }; \ - replace "$$old_ver" "$$new_ver" -- $(VERSIONED_FILES) && \ - git commit -m "v$$new_ver" $(VERSIONED_FILES) CHANGELOG.md && \ - git tag -a -m "v$$new_ver" "v$$new_ver" diff --git a/scripts/2.5/node_modules/is-symbol/README.md b/scripts/2.5/node_modules/is-symbol/README.md deleted file mode 100644 index 8544c8c0..00000000 --- a/scripts/2.5/node_modules/is-symbol/README.md +++ /dev/null @@ -1,46 +0,0 @@ -#is-symbol [![Version Badge][2]][1] - -[![Build Status][3]][4] -[![dependency status][5]][6] -[![dev dependency status][7]][8] -[![License][license-image]][license-url] -[![Downloads][downloads-image]][downloads-url] - -[![npm badge][11]][1] - -[![browser support][9]][10] - -Is this an ES6 Symbol value? - -## Example - -```js -var isSymbol = require('is-symbol'); -assert(!isSymbol(function () {})); -assert(!isSymbol(null)); -assert(!isSymbol(function* () { yield 42; return Infinity; }); - -assert(isSymbol(Symbol.iterator)); -assert(isSymbol(Symbol('foo'))); -assert(isSymbol(Symbol.for('foo'))); -assert(isSymbol(Object(Symbol('foo')))); -``` - -## Tests -Simply clone the repo, `npm install`, and run `npm test` - -[1]: https://npmjs.org/package/is-symbol -[2]: http://versionbadg.es/ljharb/is-symbol.svg -[3]: https://travis-ci.org/ljharb/is-symbol.svg -[4]: https://travis-ci.org/ljharb/is-symbol -[5]: https://david-dm.org/ljharb/is-symbol.svg -[6]: https://david-dm.org/ljharb/is-symbol -[7]: https://david-dm.org/ljharb/is-symbol/dev-status.svg -[8]: https://david-dm.org/ljharb/is-symbol#info=devDependencies -[9]: https://ci.testling.com/ljharb/is-symbol.png -[10]: https://ci.testling.com/ljharb/is-symbol -[11]: https://nodei.co/npm/is-symbol.png?downloads=true&stars=true -[license-image]: http://img.shields.io/npm/l/is-symbol.svg -[license-url]: LICENSE -[downloads-image]: http://img.shields.io/npm/dm/is-symbol.svg -[downloads-url]: http://npm-stat.com/charts.html?package=is-symbol diff --git a/scripts/2.5/node_modules/is-symbol/index.js b/scripts/2.5/node_modules/is-symbol/index.js deleted file mode 100644 index 3d653e27..00000000 --- a/scripts/2.5/node_modules/is-symbol/index.js +++ /dev/null @@ -1,35 +0,0 @@ -'use strict'; - -var toStr = Object.prototype.toString; -var hasSymbols = require('has-symbols')(); - -if (hasSymbols) { - var symToStr = Symbol.prototype.toString; - var symStringRegex = /^Symbol\(.*\)$/; - var isSymbolObject = function isRealSymbolObject(value) { - if (typeof value.valueOf() !== 'symbol') { - return false; - } - return symStringRegex.test(symToStr.call(value)); - }; - - module.exports = function isSymbol(value) { - if (typeof value === 'symbol') { - return true; - } - if (toStr.call(value) !== '[object Symbol]') { - return false; - } - try { - return isSymbolObject(value); - } catch (e) { - return false; - } - }; -} else { - - module.exports = function isSymbol(value) { - // this environment does not support Symbols. - return false && value; - }; -} diff --git a/scripts/2.5/node_modules/is-symbol/package.json b/scripts/2.5/node_modules/is-symbol/package.json deleted file mode 100644 index ccab591a..00000000 --- a/scripts/2.5/node_modules/is-symbol/package.json +++ /dev/null @@ -1,96 +0,0 @@ -{ - "_from": "is-symbol@^1.0.2", - "_id": "is-symbol@1.0.2", - "_inBundle": false, - "_integrity": "sha512-HS8bZ9ox60yCJLH9snBpIwv9pYUAkcuLhSA1oero1UB5y9aiQpRA8y2ex945AOtCZL1lJDeIk3G5LthswI46Lw==", - "_location": "/is-symbol", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "is-symbol@^1.0.2", - "name": "is-symbol", - "escapedName": "is-symbol", - "rawSpec": "^1.0.2", - "saveSpec": null, - "fetchSpec": "^1.0.2" - }, - "_requiredBy": [ - "/es-to-primitive" - ], - "_resolved": "https://registry.npmjs.org/is-symbol/-/is-symbol-1.0.2.tgz", - "_shasum": "a055f6ae57192caee329e7a860118b497a950f38", - "_spec": "is-symbol@^1.0.2", - "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/2.5/node_modules/es-to-primitive", - "author": { - "name": "Jordan Harband" - }, - "bugs": { - "url": "https://github.com/ljharb/is-symbol/issues" - }, - "bundleDependencies": false, - "dependencies": { - "has-symbols": "^1.0.0" - }, - "deprecated": false, - "description": "Determine if a value is an ES6 Symbol or not.", - "devDependencies": { - "@ljharb/eslint-config": "^12.2.1", - "covert": "^1.1.0", - "eslint": "^4.19.1", - "jscs": "^3.0.7", - "nsp": "^3.2.1", - "object-inspect": "^1.6.0", - "safe-publish-latest": "^1.1.2", - "semver": "^5.5.0", - "tape": "^4.9.0" - }, - "engines": { - "node": ">= 0.4" - }, - "homepage": "https://github.com/ljharb/is-symbol#readme", - "keywords": [ - "symbol", - "es6", - "is", - "Symbol" - ], - "license": "MIT", - "main": "index.js", - "name": "is-symbol", - "repository": { - "type": "git", - "url": "git://github.com/ljharb/is-symbol.git" - }, - "scripts": { - "coverage": "covert test", - "eslint": "eslint *.js */*.js", - "jscs": "jscs *.js */*.js", - "lint": "npm run jscs && npm run eslint", - "posttest": "npm run security", - "prepublish": "safe-publish-latest", - "pretest": "npm run lint", - "security": "nsp check", - "test": "npm run tests-only", - "tests-only": "node --es-staging --harmony test" - }, - "testling": { - "files": "test/index.js", - "browsers": [ - "iexplore/6.0..latest", - "firefox/3.0..6.0", - "firefox/15.0..latest", - "firefox/nightly", - "chrome/4.0..10.0", - "chrome/20.0..latest", - "chrome/canary", - "opera/10.0..latest", - "opera/next", - "safari/4.0..latest", - "ipad/6.0..latest", - "iphone/6.0..latest", - "android-browser/4.2" - ] - }, - "version": "1.0.2" -} diff --git a/scripts/2.5/node_modules/is-symbol/test/.eslintrc b/scripts/2.5/node_modules/is-symbol/test/.eslintrc deleted file mode 100644 index 1ac0d47b..00000000 --- a/scripts/2.5/node_modules/is-symbol/test/.eslintrc +++ /dev/null @@ -1,7 +0,0 @@ -{ - "rules": { - "max-statements-per-line": [2, { "max": 2 }], - "no-restricted-properties": 0, - "symbol-description": 0, - } -} diff --git a/scripts/2.5/node_modules/is-symbol/test/index.js b/scripts/2.5/node_modules/is-symbol/test/index.js deleted file mode 100644 index e01f035c..00000000 --- a/scripts/2.5/node_modules/is-symbol/test/index.js +++ /dev/null @@ -1,92 +0,0 @@ -'use strict'; - -var test = require('tape'); -var isSymbol = require('../index'); - -var forEach = function (arr, func) { - var i; - for (i = 0; i < arr.length; ++i) { - func(arr[i], i, arr); - } -}; - -var hasSymbols = require('has-symbols')(); -var inspect = require('object-inspect'); -var debug = function (v, m) { return inspect(v) + ' ' + m; }; - -test('non-symbol values', function (t) { - var nonSymbols = [ - true, - false, - Object(true), - Object(false), - null, - undefined, - {}, - [], - /a/g, - 'string', - 42, - new Date(), - function () {}, - NaN - ]; - t.plan(nonSymbols.length); - forEach(nonSymbols, function (nonSymbol) { - t.equal(false, isSymbol(nonSymbol), debug(nonSymbol, 'is not a symbol')); - }); - t.end(); -}); - -test('faked symbol values', function (t) { - t.test('real symbol valueOf', { skip: !hasSymbols }, function (st) { - var fakeSymbol = { valueOf: function () { return Symbol('foo'); } }; - st.equal(false, isSymbol(fakeSymbol), 'object with valueOf returning a symbol is not a symbol'); - st.end(); - }); - - t.test('faked @@toStringTag', { skip: !hasSymbols || !Symbol.toStringTag }, function (st) { - var fakeSymbol = { valueOf: function () { return Symbol('foo'); } }; - fakeSymbol[Symbol.toStringTag] = 'Symbol'; - st.equal(false, isSymbol(fakeSymbol), 'object with fake Symbol @@toStringTag and valueOf returning a symbol is not a symbol'); - var notSoFakeSymbol = { valueOf: function () { return 42; } }; - notSoFakeSymbol[Symbol.toStringTag] = 'Symbol'; - st.equal(false, isSymbol(notSoFakeSymbol), 'object with fake Symbol @@toStringTag and valueOf not returning a symbol is not a symbol'); - st.end(); - }); - - var fakeSymbolString = { toString: function () { return 'Symbol(foo)'; } }; - t.equal(false, isSymbol(fakeSymbolString), 'object with toString returning Symbol(foo) is not a symbol'); - - t.end(); -}); - -test('Symbol support', { skip: !hasSymbols }, function (t) { - t.test('well-known Symbols', function (st) { - var isWellKnown = function filterer(name) { - return name !== 'for' && name !== 'keyFor' && !(name in filterer); - }; - var wellKnownSymbols = Object.getOwnPropertyNames(Symbol).filter(isWellKnown); - wellKnownSymbols.forEach(function (name) { - var sym = Symbol[name]; - st.equal(true, isSymbol(sym), debug(sym, ' is a symbol')); - }); - st.end(); - }); - - t.test('user-created symbols', function (st) { - var symbols = [ - Symbol(), - Symbol('foo'), - Symbol['for']('foo'), - Object(Symbol('object')) - ]; - symbols.forEach(function (sym) { - st.equal(true, isSymbol(sym), debug(sym, ' is a symbol')); - }); - st.end(); - }); - - t.end(); -}); - diff --git a/scripts/2.5/node_modules/memory-pager/.travis.yml b/scripts/2.5/node_modules/memory-pager/.travis.yml deleted file mode 100644 index 1c4ab31e..00000000 --- a/scripts/2.5/node_modules/memory-pager/.travis.yml +++ /dev/null @@ -1,4 +0,0 @@ -language: node_js -node_js: - - '4' - - '6' diff --git a/scripts/2.5/node_modules/memory-pager/LICENSE b/scripts/2.5/node_modules/memory-pager/LICENSE deleted file mode 100644 index 56fce089..00000000 --- a/scripts/2.5/node_modules/memory-pager/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2017 Mathias Buus - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/scripts/2.5/node_modules/memory-pager/README.md b/scripts/2.5/node_modules/memory-pager/README.md deleted file mode 100644 index aed17614..00000000 --- a/scripts/2.5/node_modules/memory-pager/README.md +++ /dev/null @@ -1,65 +0,0 @@ -# memory-pager - -Access memory using small fixed sized buffers instead of allocating a huge buffer. -Useful if you are implementing sparse data structures (such as large bitfield). - -![travis](https://travis-ci.org/mafintosh/memory-pager.svg?branch=master) - -``` -npm install memory-pager -``` - -## Usage - -``` js -var pager = require('paged-memory') - -var pages = pager(1024) // use 1kb per page - -var page = pages.get(10) // get page #10 - -console.log(page.offset) // 10240 -console.log(page.buffer) // a blank 1kb buffer -``` - -## API - -#### `var pages = pager(pageSize)` - -Create a new pager. `pageSize` defaults to `1024`. - -#### `var page = pages.get(pageNumber, [noAllocate])` - -Get a page. The page will be allocated at first access. - -Optionally you can set the `noAllocate` flag which will make the -method return undefined if no page has been allocated already - -A page looks like this - -``` js -{ - offset: byteOffset, - buffer: bufferWithPageSize -} -``` - -#### `pages.set(pageNumber, buffer)` - -Explicitly set the buffer for a page. - -#### `pages.updated(page)` - -Mark a page as updated. - -#### `pages.lastUpdate()` - -Get the last page that was updated. - -#### `var buf = pages.toBuffer()` - -Concat all pages allocated pages into a single buffer - -## License - -MIT diff --git a/scripts/2.5/node_modules/memory-pager/index.js b/scripts/2.5/node_modules/memory-pager/index.js deleted file mode 100644 index 687f346f..00000000 --- a/scripts/2.5/node_modules/memory-pager/index.js +++ /dev/null @@ -1,160 +0,0 @@ -module.exports = Pager - -function Pager (pageSize, opts) { - if (!(this instanceof Pager)) return new Pager(pageSize, opts) - - this.length = 0 - this.updates = [] - this.path = new Uint16Array(4) - this.pages = new Array(32768) - this.maxPages = this.pages.length - this.level = 0 - this.pageSize = pageSize || 1024 - this.deduplicate = opts ? opts.deduplicate : null - this.zeros = this.deduplicate ? alloc(this.deduplicate.length) : null -} - -Pager.prototype.updated = function (page) { - while (this.deduplicate && page.buffer[page.deduplicate] === this.deduplicate[page.deduplicate]) { - page.deduplicate++ - if (page.deduplicate === this.deduplicate.length) { - page.deduplicate = 0 - if (page.buffer.equals && page.buffer.equals(this.deduplicate)) page.buffer = this.deduplicate - break - } - } - if (page.updated || !this.updates) return - page.updated = true - this.updates.push(page) -} - -Pager.prototype.lastUpdate = function () { - if (!this.updates || !this.updates.length) return null - var page = this.updates.pop() - page.updated = false - return page -} - -Pager.prototype._array = function (i, noAllocate) { - if (i >= this.maxPages) { - if (noAllocate) return - grow(this, i) - } - - factor(i, this.path) - - var arr = this.pages - - for (var j = this.level; j > 0; j--) { - var p = this.path[j] - var next = arr[p] - - if (!next) { - if (noAllocate) return - next = arr[p] = new Array(32768) - } - - arr = next - } - - return arr -} - -Pager.prototype.get = function (i, noAllocate) { - var arr = this._array(i, noAllocate) - var first = this.path[0] - var page = arr && arr[first] - - if (!page && !noAllocate) { - page = arr[first] = new Page(i, alloc(this.pageSize)) - if (i >= this.length) this.length = i + 1 - } - - if (page && page.buffer === this.deduplicate && this.deduplicate && !noAllocate) { - page.buffer = copy(page.buffer) - page.deduplicate = 0 - } - - return page -} - -Pager.prototype.set = function (i, buf) { - var arr = this._array(i, false) - var first = this.path[0] - - if (i >= this.length) this.length = i + 1 - - if (!buf || (this.zeros && buf.equals && buf.equals(this.zeros))) { - arr[first] = undefined - return - } - - if (this.deduplicate && buf.equals && buf.equals(this.deduplicate)) { - buf = this.deduplicate - } - - var page = arr[first] - var b = truncate(buf, this.pageSize) - - if (page) page.buffer = b - else arr[first] = new Page(i, b) -} - -Pager.prototype.toBuffer = function () { - var list = new Array(this.length) - var empty = alloc(this.pageSize) - var ptr = 0 - - while (ptr < list.length) { - var arr = this._array(ptr, true) - for (var i = 0; i < 32768 && ptr < list.length; i++) { - list[ptr++] = (arr && arr[i]) ? arr[i].buffer : empty - } - } - - return Buffer.concat(list) -} - -function grow (pager, index) { - while (pager.maxPages < index) { - var old = pager.pages - pager.pages = new Array(32768) - pager.pages[0] = old - pager.level++ - pager.maxPages *= 32768 - } -} - -function truncate (buf, len) { - if (buf.length === len) return buf - if (buf.length > len) return buf.slice(0, len) - var cpy = alloc(len) - buf.copy(cpy) - return cpy -} - -function alloc (size) { - if (Buffer.alloc) return Buffer.alloc(size) - var buf = new Buffer(size) - buf.fill(0) - return buf -} - -function copy (buf) { - var cpy = Buffer.allocUnsafe ? Buffer.allocUnsafe(buf.length) : new Buffer(buf.length) - buf.copy(cpy) - return cpy -} - -function Page (i, buf) { - this.offset = i * buf.length - this.buffer = buf - this.updated = false - this.deduplicate = 0 -} - -function factor (n, out) { - n = (n - (out[0] = (n & 32767))) / 32768 - n = (n - (out[1] = (n & 32767))) / 32768 - out[3] = ((n - (out[2] = (n & 32767))) / 32768) & 32767 -} diff --git a/scripts/2.5/node_modules/memory-pager/package.json b/scripts/2.5/node_modules/memory-pager/package.json deleted file mode 100644 index 4b40665a..00000000 --- a/scripts/2.5/node_modules/memory-pager/package.json +++ /dev/null @@ -1,52 +0,0 @@ -{ - "_from": "memory-pager@^1.0.2", - "_id": "memory-pager@1.5.0", - "_inBundle": false, - "_integrity": "sha512-ZS4Bp4r/Zoeq6+NLJpP+0Zzm0pR8whtGPf1XExKLJBAczGMnSi3It14OiNCStjQjM6NU1okjQGSxgEZN8eBYKg==", - "_location": "/memory-pager", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "memory-pager@^1.0.2", - "name": "memory-pager", - "escapedName": "memory-pager", - "rawSpec": "^1.0.2", - "saveSpec": null, - "fetchSpec": "^1.0.2" - }, - "_requiredBy": [ - "/sparse-bitfield" - ], - "_resolved": "https://registry.npmjs.org/memory-pager/-/memory-pager-1.5.0.tgz", - "_shasum": "d8751655d22d384682741c972f2c3d6dfa3e66b5", - "_spec": "memory-pager@^1.0.2", - "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/2.5/node_modules/sparse-bitfield", - "author": { - "name": "Mathias Buus", - "url": "@mafintosh" - }, - "bugs": { - "url": "https://github.com/mafintosh/memory-pager/issues" - }, - "bundleDependencies": false, - "dependencies": {}, - "deprecated": false, - "description": "Access memory using small fixed sized buffers", - "devDependencies": { - "standard": "^9.0.0", - "tape": "^4.6.3" - }, - "homepage": "https://github.com/mafintosh/memory-pager", - "license": "MIT", - "main": "index.js", - "name": "memory-pager", - "repository": { - "type": "git", - "url": "git+https://github.com/mafintosh/memory-pager.git" - }, - "scripts": { - "test": "standard && tape test.js" - }, - "version": "1.5.0" -} diff --git a/scripts/2.5/node_modules/memory-pager/test.js b/scripts/2.5/node_modules/memory-pager/test.js deleted file mode 100644 index 16382100..00000000 --- a/scripts/2.5/node_modules/memory-pager/test.js +++ /dev/null @@ -1,80 +0,0 @@ -var tape = require('tape') -var pager = require('./') - -tape('get page', function (t) { - var pages = pager(1024) - - var page = pages.get(0) - - t.same(page.offset, 0) - t.same(page.buffer, Buffer.alloc(1024)) - t.end() -}) - -tape('get page twice', function (t) { - var pages = pager(1024) - t.same(pages.length, 0) - - var page = pages.get(0) - - t.same(page.offset, 0) - t.same(page.buffer, Buffer.alloc(1024)) - t.same(pages.length, 1) - - var other = pages.get(0) - - t.same(other, page) - t.end() -}) - -tape('get no mutable page', function (t) { - var pages = pager(1024) - - t.ok(!pages.get(141, true)) - t.ok(pages.get(141)) - t.ok(pages.get(141, true)) - - t.end() -}) - -tape('get far out page', function (t) { - var pages = pager(1024) - - var page = pages.get(1000000) - - t.same(page.offset, 1000000 * 1024) - t.same(page.buffer, Buffer.alloc(1024)) - t.same(pages.length, 1000000 + 1) - - var other = pages.get(1) - - t.same(other.offset, 1024) - t.same(other.buffer, Buffer.alloc(1024)) - t.same(pages.length, 1000000 + 1) - t.ok(other !== page) - - t.end() -}) - -tape('updates', function (t) { - var pages = pager(1024) - - t.same(pages.lastUpdate(), null) - - var page = pages.get(10) - - page.buffer[42] = 1 - pages.updated(page) - - t.same(pages.lastUpdate(), page) - t.same(pages.lastUpdate(), null) - - page.buffer[42] = 2 - pages.updated(page) - pages.updated(page) - - t.same(pages.lastUpdate(), page) - t.same(pages.lastUpdate(), null) - - t.end() -}) diff --git a/scripts/2.5/node_modules/mongodb/HISTORY.md b/scripts/2.5/node_modules/mongodb/HISTORY.md deleted file mode 100644 index 73cbab99..00000000 --- a/scripts/2.5/node_modules/mongodb/HISTORY.md +++ /dev/null @@ -1,2485 +0,0 @@ -# Change Log - -All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. - - -## [3.3.3](https://github.com/mongodb/node-mongodb-native/compare/v3.3.2...v3.3.3) (2019-10-16) - - -### Bug Fixes - -* **change_stream:** emit 'close' event if reconnecting failed ([f24c084](https://github.com/mongodb/node-mongodb-native/commit/f24c084)) -* **ChangeStream:** remove startAtOperationTime once we have resumeToken ([362afd8](https://github.com/mongodb/node-mongodb-native/commit/362afd8)) -* **connect:** Switch new Buffer(size) -> Buffer.alloc(size) ([da90c3a](https://github.com/mongodb/node-mongodb-native/commit/da90c3a)) -* **MongoClient:** only check own properties for valid options ([9cde4b9](https://github.com/mongodb/node-mongodb-native/commit/9cde4b9)) -* **mongos:** disconnect proxies which are not mongos instances ([ee53983](https://github.com/mongodb/node-mongodb-native/commit/ee53983)) -* **mongos:** force close servers during reconnect flow ([186263f](https://github.com/mongodb/node-mongodb-native/commit/186263f)) -* **monitoring:** correct spelling mistake for heartbeat event ([21aa117](https://github.com/mongodb/node-mongodb-native/commit/21aa117)) -* **replset:** correct server leak on initial connect ([da39d1e](https://github.com/mongodb/node-mongodb-native/commit/da39d1e)) -* **replset:** destroy primary before removing from replsetstate ([45ac09a](https://github.com/mongodb/node-mongodb-native/commit/45ac09a)) -* **replset:** destroy servers that are removed during SDAM flow ([9ea0190](https://github.com/mongodb/node-mongodb-native/commit/9ea0190)) -* **saslprep:** add in missing saslprep dependency ([41f1165](https://github.com/mongodb/node-mongodb-native/commit/41f1165)) -* **topology:** don't early abort server selection on network errors ([2b6a359](https://github.com/mongodb/node-mongodb-native/commit/2b6a359)) -* **topology:** don't emit server closed event on network error ([194dcf0](https://github.com/mongodb/node-mongodb-native/commit/194dcf0)) -* **topology:** include all BSON types in ctor for bson-ext support ([aa4c832](https://github.com/mongodb/node-mongodb-native/commit/aa4c832)) -* **topology:** respect the `force` parameter for topology close ([d6e8936](https://github.com/mongodb/node-mongodb-native/commit/d6e8936)) - -### Features - -* **Update:** add the ability to specify a pipeline to an update command ([#2017](https://github.com/mongodb/node-mongodb-native/issues/2017)) ([44a4110](https://github.com/mongodb/node-mongodb-native/commit/44a4110)) -* **urlParser:** default useNewUrlParser to true ([52d76e3](https://github.com/mongodb/node-mongodb-native/commit/52d76e3)) - - -## [3.2.7](https://github.com/mongodb/node-mongodb-native/compare/v3.2.6...v3.2.7) (2019-06-04) - - -### Bug Fixes - -* **core:** updating core to version 3.2.7 ([2f91466](https://github.com/mongodb/node-mongodb-native/commit/2f91466)) -* **findOneAndReplace:** throw error if atomic operators provided for findOneAndReplace ([6a860a3](https://github.com/mongodb/node-mongodb-native/commit/6a860a3)) - - - - -## [3.3.2](https://github.com/mongodb/node-mongodb-native/compare/v3.3.1...v3.3.2) (2019-08-28) - - -### Bug Fixes - -* **change-stream:** default to server default batch size ([b3ae4c5](https://github.com/mongodb/node-mongodb-native/commit/b3ae4c5)) -* **execute-operation:** return promise on session support check ([a976c14](https://github.com/mongodb/node-mongodb-native/commit/a976c14)) -* **gridfs-stream:** ensure `close` is emitted after last chunk ([ae94cb9](https://github.com/mongodb/node-mongodb-native/commit/ae94cb9)) - - - - -## [3.3.1](https://github.com/mongodb/node-mongodb-native/compare/v3.3.0...v3.3.1) (2019-08-23) - - -### Bug Fixes - -* **find:** respect client-level provided read preference ([fec4f15](https://github.com/mongodb/node-mongodb-native/commit/fec4f15)) -* correct inverted defaults for unified topology ([cf598e1](https://github.com/mongodb/node-mongodb-native/commit/cf598e1)) - - - - -# [3.3.0](https://github.com/mongodb/node-mongodb-native/compare/v3.3.0-alpha1...v3.3.0) (2019-08-13) - - -### Bug Fixes - -* **aggregate-operation:** move type assertions to constructor ([25b27ff](https://github.com/mongodb/node-mongodb-native/commit/25b27ff)) -* **autoEncryption:** tear down mongocryptd client when main client closes ([fe2f57e](https://github.com/mongodb/node-mongodb-native/commit/fe2f57e)) -* **autoEncryption:** use new url parser for autoEncryption client ([d3670c2](https://github.com/mongodb/node-mongodb-native/commit/d3670c2)) -* **Bulk:** change BulkWriteError message to first item from writeErrors ([#2013](https://github.com/mongodb/node-mongodb-native/issues/2013)) ([6bcf1e4](https://github.com/mongodb/node-mongodb-native/commit/6bcf1e4)) -* **change_stream:** emit 'close' event if reconnecting failed ([41aba90](https://github.com/mongodb/node-mongodb-native/commit/41aba90)) -* **change_stream:** emit close event after cursor is closed during error ([c2d80b2](https://github.com/mongodb/node-mongodb-native/commit/c2d80b2)) -* **change-streams:** don't copy irrelevant resume options ([f190072](https://github.com/mongodb/node-mongodb-native/commit/f190072)) -* **changestream:** removes all event listeners on close ([30eeeb5](https://github.com/mongodb/node-mongodb-native/commit/30eeeb5)) -* **ChangeStream:** remove startAtOperationTime once we have resumeToken ([8d27e6e](https://github.com/mongodb/node-mongodb-native/commit/8d27e6e)) -* **ClientSessions:** initialize clientOptions and cluster time ([b95d64e](https://github.com/mongodb/node-mongodb-native/commit/b95d64e)) -* **connect:** don't treat 'connect' as an error event ([170a011](https://github.com/mongodb/node-mongodb-native/commit/170a011)) -* **connect:** fixed syntax issue in connect error handler ([ff7166d](https://github.com/mongodb/node-mongodb-native/commit/ff7166d)) -* **connections_stepdown_tests:** use correct version of mongo for tests ([ce2c9af](https://github.com/mongodb/node-mongodb-native/commit/ce2c9af)) -* **createCollection:** Db.createCollection should pass readConcern to new collection ([#2026](https://github.com/mongodb/node-mongodb-native/issues/2026)) ([6145d4b](https://github.com/mongodb/node-mongodb-native/commit/6145d4b)) -* **cursor:** do not truncate an existing Long ([317055b](https://github.com/mongodb/node-mongodb-native/commit/317055b)), closes [mongodb-js/mongodb-core#441](https://github.com/mongodb-js/mongodb-core/issues/441) -* **distinct:** return full response if `full` option was specified ([95a7d05](https://github.com/mongodb/node-mongodb-native/commit/95a7d05)) -* **MongoClient:** allow Object.prototype items as db names ([dc6fc37](https://github.com/mongodb/node-mongodb-native/commit/dc6fc37)) -* **MongoClient:** only check own properties for valid options ([c9dc717](https://github.com/mongodb/node-mongodb-native/commit/c9dc717)) -* **OpMsg:** cap requestIds at 0x7fffffff ([c0e87d5](https://github.com/mongodb/node-mongodb-native/commit/c0e87d5)) -* **read-operations:** send sessions on all read operations ([4d45c8a](https://github.com/mongodb/node-mongodb-native/commit/4d45c8a)) -* **ReadPreference:** improve ReadPreference error message and remove irrelevant sharding test ([dd34ce4](https://github.com/mongodb/node-mongodb-native/commit/dd34ce4)) -* **ReadPreference:** only allow valid ReadPreference modes ([06bbef2](https://github.com/mongodb/node-mongodb-native/commit/06bbef2)) -* **replset:** correct legacy max staleness calculation ([2eab8aa](https://github.com/mongodb/node-mongodb-native/commit/2eab8aa)) -* **replset:** introduce a fixed-time server selection loop ([cf53299](https://github.com/mongodb/node-mongodb-native/commit/cf53299)) -* **server:** emit "first connect" error if initial connect fails due to ECONNREFUSED ([#2016](https://github.com/mongodb/node-mongodb-native/issues/2016)) ([5a7b15b](https://github.com/mongodb/node-mongodb-native/commit/5a7b15b)) -* **serverSelection:** make sure to pass session to serverSelection ([eb5cc6b](https://github.com/mongodb/node-mongodb-native/commit/eb5cc6b)) -* **sessions:** ensure an error is thrown when attempting sharded transactions ([3a1fdc1](https://github.com/mongodb/node-mongodb-native/commit/3a1fdc1)) -* **topology:** add new error for retryWrites on MMAPv1 ([392f5a6](https://github.com/mongodb/node-mongodb-native/commit/392f5a6)) -* don't check non-unified topologies for session support check ([2bccd3f](https://github.com/mongodb/node-mongodb-native/commit/2bccd3f)) -* maintain internal database name on collection rename ([884d46f](https://github.com/mongodb/node-mongodb-native/commit/884d46f)) -* only check for transaction state if session exists ([360975a](https://github.com/mongodb/node-mongodb-native/commit/360975a)) -* preserve aggregate explain support for legacy servers ([032b204](https://github.com/mongodb/node-mongodb-native/commit/032b204)) -* read concern only supported for `mapReduce` without inline ([51a36f3](https://github.com/mongodb/node-mongodb-native/commit/51a36f3)) -* reintroduce support for 2.6 listIndexes ([c3bfc05](https://github.com/mongodb/node-mongodb-native/commit/c3bfc05)) -* return `executeOperation` for explain, if promise is desired ([b4a7ad7](https://github.com/mongodb/node-mongodb-native/commit/b4a7ad7)) -* validate atomic operations in all update methods ([88bb77e](https://github.com/mongodb/node-mongodb-native/commit/88bb77e)) -* **transactions:** fix error message for attempting sharded ([eb5dfc9](https://github.com/mongodb/node-mongodb-native/commit/eb5dfc9)) -* **transactions:** fix sharded transaction error logic ([083e18a](https://github.com/mongodb/node-mongodb-native/commit/083e18a)) - - -### Features - -* **Aggregate:** support ReadConcern in aggregates with $out ([21cdcf0](https://github.com/mongodb/node-mongodb-native/commit/21cdcf0)) -* **AutoEncryption:** improve error message for missing mongodb-client-encryption ([583f29f](https://github.com/mongodb/node-mongodb-native/commit/583f29f)) -* **ChangeStream:** adds new resume functionality to ChangeStreams ([9ec9b8f](https://github.com/mongodb/node-mongodb-native/commit/9ec9b8f)) -* **ChangeStreamCursor:** introduce new cursor type for change streams ([8813eb0](https://github.com/mongodb/node-mongodb-native/commit/8813eb0)) -* **cryptdConnectionString:** makes mongocryptd uri configurable ([#2049](https://github.com/mongodb/node-mongodb-native/issues/2049)) ([a487be4](https://github.com/mongodb/node-mongodb-native/commit/a487be4)) -* **eachAsync:** dedupe async iteration with a common helper ([c296f3a](https://github.com/mongodb/node-mongodb-native/commit/c296f3a)) -* **execute-operation:** allow execution with server selection ([36bc1fd](https://github.com/mongodb/node-mongodb-native/commit/36bc1fd)) -* **pool:** add support for resetting the connection pool ([2d1ff40](https://github.com/mongodb/node-mongodb-native/commit/2d1ff40)) -* **sessions:** track dirty state of sessions, drop after use ([f61df16](https://github.com/mongodb/node-mongodb-native/commit/f61df16)) -* add concept of `data-bearing` type to `ServerDescription` ([852e14f](https://github.com/mongodb/node-mongodb-native/commit/852e14f)) -* **transaction:** allow applications to set maxTimeMS for commitTransaction ([b3948aa](https://github.com/mongodb/node-mongodb-native/commit/b3948aa)) -* **Update:** add the ability to specify a pipeline to an update command ([#2017](https://github.com/mongodb/node-mongodb-native/issues/2017)) ([dc1387e](https://github.com/mongodb/node-mongodb-native/commit/dc1387e)) -* add `known`, `data-bearing` filters to `TopologyDescription` ([d0ccb56](https://github.com/mongodb/node-mongodb-native/commit/d0ccb56)) -* perform selection before cursor operation execution if needed ([808cf37](https://github.com/mongodb/node-mongodb-native/commit/808cf37)) -* perform selection before operation execution if needed ([1a25876](https://github.com/mongodb/node-mongodb-native/commit/1a25876)) -* support explain operations in `CommandOperationV2` ([86f5ba5](https://github.com/mongodb/node-mongodb-native/commit/86f5ba5)) -* support operations passed to a `Cursor` or subclass ([b78bb89](https://github.com/mongodb/node-mongodb-native/commit/b78bb89)) - - - - -## [3.2.7](https://github.com/mongodb/node-mongodb-native/compare/v3.2.6...v3.2.7) (2019-06-04) - - -### Bug Fixes - -* **core:** updating core to version 3.2.7 ([2f91466](https://github.com/mongodb/node-mongodb-native/commit/2f91466)) -* **findOneAndReplace:** throw error if atomic operators provided for findOneAndReplace ([6a860a3](https://github.com/mongodb/node-mongodb-native/commit/6a860a3)) - - - - -## [3.2.6](https://github.com/mongodb/node-mongodb-native/compare/v3.2.5...v3.2.6) (2019-05-24) - - - - -## [3.2.5](https://github.com/mongodb/node-mongodb-native/compare/v3.2.4...v3.2.5) (2019-05-17) - - -### Bug Fixes - -* **core:** updating core to 3.2.5 ([a2766c1](https://github.com/mongodb/node-mongodb-native/commit/a2766c1)) - - - - -## [3.2.4](https://github.com/mongodb/node-mongodb-native/compare/v3.2.2...v3.2.4) (2019-05-08) - - -### Bug Fixes - -* **aggregation:** fix field name typo ([4235d04](https://github.com/mongodb/node-mongodb-native/commit/4235d04)) -* **async:** rewrote asyncGenerator in node < 10 syntax ([49c8cef](https://github.com/mongodb/node-mongodb-native/commit/49c8cef)) -* **BulkOp:** run unordered bulk ops in serial ([f548bd7](https://github.com/mongodb/node-mongodb-native/commit/f548bd7)) -* **bulkWrite:** fix issue with bulkWrite continuing w/ callback ([2a4a42c](https://github.com/mongodb/node-mongodb-native/commit/2a4a42c)) -* **docs:** correctly document that default for `sslValidate` is false ([1f8e7fa](https://github.com/mongodb/node-mongodb-native/commit/1f8e7fa)) -* **gridfs-stream:** honor chunk size ([9eeb114](https://github.com/mongodb/node-mongodb-native/commit/9eeb114)) -* **unified-topology:** only clone pool size if provided ([8dc2416](https://github.com/mongodb/node-mongodb-native/commit/8dc2416)) - - -### Features - -* update to mongodb-core v3.2.3 ([1c5357a](https://github.com/mongodb/node-mongodb-native/commit/1c5357a)) -* **core:** update to mongodb-core v3.2.4 ([2059260](https://github.com/mongodb/node-mongodb-native/commit/2059260)) -* **lib:** implement executeOperationV2 ([67d4edf](https://github.com/mongodb/node-mongodb-native/commit/67d4edf)) - - - - -## [3.2.3](https://github.com/mongodb/node-mongodb-native/compare/v3.2.2...v3.2.3) (2019-04-05) - - -### Bug Fixes - -* **aggregation:** fix field name typo ([4235d04](https://github.com/mongodb/node-mongodb-native/commit/4235d04)) -* **async:** rewrote asyncGenerator in node < 10 syntax ([49c8cef](https://github.com/mongodb/node-mongodb-native/commit/49c8cef)) -* **bulkWrite:** fix issue with bulkWrite continuing w/ callback ([2a4a42c](https://github.com/mongodb/node-mongodb-native/commit/2a4a42c)) -* **docs:** correctly document that default for `sslValidate` is false ([1f8e7fa](https://github.com/mongodb/node-mongodb-native/commit/1f8e7fa)) - - -### Features - -* update to mongodb-core v3.2.3 ([1c5357a](https://github.com/mongodb/node-mongodb-native/commit/1c5357a)) - - - - -## [3.2.2](https://github.com/mongodb/node-mongodb-native/compare/v3.2.1...v3.2.2) (2019-03-22) - - -### Bug Fixes - -* **asyncIterator:** stronger guard against importing async generator ([e0826fb](https://github.com/mongodb/node-mongodb-native/commit/e0826fb)) - - -### Features - -* update to mongodb-core v3.2.2 ([868cfc3](https://github.com/mongodb/node-mongodb-native/commit/868cfc3)) - - - - -## [3.2.1](https://github.com/mongodb/node-mongodb-native/compare/v3.2.0...v3.2.1) (2019-03-21) - - -### Features - -* **core:** update to mongodb-core v3.2.1 ([30b0100](https://github.com/mongodb/node-mongodb-native/commit/30b0100)) - - - - -# [3.2.0](https://github.com/mongodb/node-mongodb-native/compare/v3.1.13...v3.2.0) (2019-03-21) - - -### Bug Fixes - -* **aggregate:** do not send batchSize for aggregation with $out ([ddb8d90](https://github.com/mongodb/node-mongodb-native/commit/ddb8d90)) -* **bulkWrite:** always count undefined values in bson size for bulk ([436d340](https://github.com/mongodb/node-mongodb-native/commit/436d340)) -* **db_ops:** rename db to add user on ([79931af](https://github.com/mongodb/node-mongodb-native/commit/79931af)) -* **mongo_client_ops:** only skip authentication if no authMechanism is specified ([3b6957d](https://github.com/mongodb/node-mongodb-native/commit/3b6957d)) -* **mongo-client:** ensure close callback is called with client ([f39e881](https://github.com/mongodb/node-mongodb-native/commit/f39e881)) - - -### Features - -* **core:** pin to mongodb-core v3.2.0 ([22af15a](https://github.com/mongodb/node-mongodb-native/commit/22af15a)) -* **Cursor:** adds support for AsyncIterator in cursors ([b972c1e](https://github.com/mongodb/node-mongodb-native/commit/b972c1e)) -* **db:** add database-level aggregation ([b629b21](https://github.com/mongodb/node-mongodb-native/commit/b629b21)) -* **mongo-client:** remove deprecated `logout` and print warning ([542859d](https://github.com/mongodb/node-mongodb-native/commit/542859d)) -* **topology-base:** support passing callbacks to `close` method ([7c111e0](https://github.com/mongodb/node-mongodb-native/commit/7c111e0)) -* **transactions:** support pinning mongos for sharded txns ([3886127](https://github.com/mongodb/node-mongodb-native/commit/3886127)) -* **unified-sdam:** backport unified SDAM to master for v3.2.0 ([79f33ca](https://github.com/mongodb/node-mongodb-native/commit/79f33ca)) - - - - -## [3.1.13](https://github.com/mongodb/node-mongodb-native/compare/v3.1.12...v3.1.13) (2019-01-23) - - -### Bug Fixes - -* restore ability to webpack by removing `makeLazyLoader` ([050267d](https://github.com/mongodb/node-mongodb-native/commit/050267d)) -* **bulk:** honor ignoreUndefined in initializeUnorderedBulkOp ([e806be4](https://github.com/mongodb/node-mongodb-native/commit/e806be4)) -* **changeStream:** properly handle changeStream event mid-close ([#1902](https://github.com/mongodb/node-mongodb-native/issues/1902)) ([5ad9fa9](https://github.com/mongodb/node-mongodb-native/commit/5ad9fa9)) -* **db_ops:** ensure we async resolve errors in createCollection ([210c71d](https://github.com/mongodb/node-mongodb-native/commit/210c71d)) - - - - -## [3.1.12](https://github.com/mongodb/node-mongodb-native/compare/v3.1.11...v3.1.12) (2019-01-16) - - -### Features - -* **core:** update to mongodb-core v3.1.11 ([9bef6e7](https://github.com/mongodb/node-mongodb-native/commit/9bef6e7)) - - - - -## [3.1.11](https://github.com/mongodb/node-mongodb-native/compare/v3.1.10...v3.1.11) (2019-01-15) - - -### Bug Fixes - -* **bulk:** fix error propagation in empty bulk.execute ([a3adb3f](https://github.com/mongodb/node-mongodb-native/commit/a3adb3f)) -* **bulk:** make sure that any error in bulk write is propagated ([bedc2d2](https://github.com/mongodb/node-mongodb-native/commit/bedc2d2)) -* **bulk:** properly calculate batch size for bulk writes ([aafe71b](https://github.com/mongodb/node-mongodb-native/commit/aafe71b)) -* **operations:** do not call require in a hot path ([ff82ff4](https://github.com/mongodb/node-mongodb-native/commit/ff82ff4)) - - - - -## [3.1.10](https://github.com/mongodb/node-mongodb-native/compare/v3.1.9...v3.1.10) (2018-11-16) - - -### Bug Fixes - -* **auth:** remember to default to admin database ([c7dec28](https://github.com/mongodb/node-mongodb-native/commit/c7dec28)) - - -### Features - -* **core:** update to mongodb-core v3.1.9 ([bd3355b](https://github.com/mongodb/node-mongodb-native/commit/bd3355b)) - - - - -## [3.1.9](https://github.com/mongodb/node-mongodb-native/compare/v3.1.8...v3.1.9) (2018-11-06) - - -### Bug Fixes - -* **db:** move db constants to other file to avoid circular ref ([#1858](https://github.com/mongodb/node-mongodb-native/issues/1858)) ([239036f](https://github.com/mongodb/node-mongodb-native/commit/239036f)) -* **estimated-document-count:** support options other than maxTimeMs ([36c3c7d](https://github.com/mongodb/node-mongodb-native/commit/36c3c7d)) - - -### Features - -* **core:** update to mongodb-core v3.1.8 ([80d7c79](https://github.com/mongodb/node-mongodb-native/commit/80d7c79)) - - - - -## [3.1.8](https://github.com/mongodb/node-mongodb-native/compare/v3.1.7...v3.1.8) (2018-10-10) - - -### Bug Fixes - -* **connect:** use reported default databse from new uri parser ([811f8f8](https://github.com/mongodb/node-mongodb-native/commit/811f8f8)) - - -### Features - -* **core:** update to mongodb-core v3.1.7 ([dbfc905](https://github.com/mongodb/node-mongodb-native/commit/dbfc905)) - - - - -## [3.1.7](https://github.com/mongodb/node-mongodb-native/compare/v3.1.6...v3.1.7) (2018-10-09) - - -### Features - -* **core:** update mongodb-core to v3.1.6 ([61b054e](https://github.com/mongodb/node-mongodb-native/commit/61b054e)) - - - - -## [3.1.6](https://github.com/mongodb/node-mongodb-native/compare/v3.1.5...v3.1.6) (2018-09-15) - - -### Features - -* **core:** update to core v3.1.5 ([c5f823d](https://github.com/mongodb/node-mongodb-native/commit/c5f823d)) - - - - -## [3.1.5](https://github.com/mongodb/node-mongodb-native/compare/v3.1.4...v3.1.5) (2018-09-14) - - -### Bug Fixes - -* **cursor:** allow `$meta` based sort when passing an array to `sort()` ([f93a8c3](https://github.com/mongodb/node-mongodb-native/commit/f93a8c3)) -* **utils:** only set retryWrites to true for valid operations ([3b725ef](https://github.com/mongodb/node-mongodb-native/commit/3b725ef)) - - -### Features - -* **core:** bump core to v3.1.4 ([805d58a](https://github.com/mongodb/node-mongodb-native/commit/805d58a)) - - - - -## [3.1.4](https://github.com/mongodb/node-mongodb-native/compare/v3.1.3...v3.1.4) (2018-08-25) - - -### Bug Fixes - -* **buffer:** use safe-buffer polyfill to maintain compatibility ([327da95](https://github.com/mongodb/node-mongodb-native/commit/327da95)) -* **change-stream:** properly support resumablity in stream mode ([c43a34b](https://github.com/mongodb/node-mongodb-native/commit/c43a34b)) -* **connect:** correct replacement of topology on connect callback ([918a1e0](https://github.com/mongodb/node-mongodb-native/commit/918a1e0)) -* **cursor:** remove deprecated notice on forEach ([a474158](https://github.com/mongodb/node-mongodb-native/commit/a474158)) -* **url-parser:** bail early on validation when using domain socket ([3cb3da3](https://github.com/mongodb/node-mongodb-native/commit/3cb3da3)) - - -### Features - -* **client-ops:** allow bypassing creation of topologies on connect ([fe39b93](https://github.com/mongodb/node-mongodb-native/commit/fe39b93)) -* **core:** update mongodb-core to 3.1.3 ([a029047](https://github.com/mongodb/node-mongodb-native/commit/a029047)) -* **test:** use connection strings for all calls to `newClient` ([1dac18f](https://github.com/mongodb/node-mongodb-native/commit/1dac18f)) - - - - -## [3.1.3](https://github.com/mongodb/node-mongodb-native/compare/v3.1.2...v3.1.3) (2018-08-13) - - -### Features - -* **core:** update to mongodb-core 3.1.2 ([337cb79](https://github.com/mongodb/node-mongodb-native/commit/337cb79)) - - - - -## [3.1.2](https://github.com/mongodb/node-mongodb-native/compare/v3.0.6...v3.1.2) (2018-08-13) - - -### Bug Fixes - -* **aggregate:** support user-provided `batchSize` ([ad10dee](https://github.com/mongodb/node-mongodb-native/commit/ad10dee)) -* **buffer:** replace deprecated Buffer constructor ([759dd85](https://github.com/mongodb/node-mongodb-native/commit/759dd85)) -* **bulk:** fixing retryable writes for mass-change ops ([0604036](https://github.com/mongodb/node-mongodb-native/commit/0604036)) -* **bulk:** handle MongoWriteConcernErrors ([12ff392](https://github.com/mongodb/node-mongodb-native/commit/12ff392)) -* **change_stream:** do not check isGetMore if error[mongoErrorContextSymbol] is undefined ([#1720](https://github.com/mongodb/node-mongodb-native/issues/1720)) ([844c2c8](https://github.com/mongodb/node-mongodb-native/commit/844c2c8)) -* **change-stream:** fix change stream resuming with promises ([3063f00](https://github.com/mongodb/node-mongodb-native/commit/3063f00)) -* **client-ops:** return transform map to map rather than function ([cfb7d83](https://github.com/mongodb/node-mongodb-native/commit/cfb7d83)) -* **collection:** correctly shallow clone passed in options ([7727700](https://github.com/mongodb/node-mongodb-native/commit/7727700)) -* **collection:** countDocuments throws error when query doesn't match docs ([09c7d8e](https://github.com/mongodb/node-mongodb-native/commit/09c7d8e)) -* **collection:** depend on `resolveReadPreference` for inheritance ([a649e35](https://github.com/mongodb/node-mongodb-native/commit/a649e35)) -* **collection:** ensure findAndModify always use readPreference primary ([86344f4](https://github.com/mongodb/node-mongodb-native/commit/86344f4)) -* **collection:** isCapped returns false instead of undefined ([b8471f1](https://github.com/mongodb/node-mongodb-native/commit/b8471f1)) -* **collection:** only send bypassDocumentValidation if true ([fdb828b](https://github.com/mongodb/node-mongodb-native/commit/fdb828b)) -* **count-documents:** return callback on error case ([fca1185](https://github.com/mongodb/node-mongodb-native/commit/fca1185)) -* **cursor:** cursor count with collation fix ([71879c3](https://github.com/mongodb/node-mongodb-native/commit/71879c3)) -* **cursor:** cursor hasNext returns false when exhausted ([184b817](https://github.com/mongodb/node-mongodb-native/commit/184b817)) -* **cursor:** cursor.count not respecting parent readPreference ([5a9fdf0](https://github.com/mongodb/node-mongodb-native/commit/5a9fdf0)) -* **cursor:** set readPreference for cursor.count ([13d776f](https://github.com/mongodb/node-mongodb-native/commit/13d776f)) -* **db:** don't send session down to createIndex command ([559c195](https://github.com/mongodb/node-mongodb-native/commit/559c195)) -* **db:** throw readable error when creating `_id` with background: true ([b3ff3ed](https://github.com/mongodb/node-mongodb-native/commit/b3ff3ed)) -* **db_ops:** call collection.find() with correct parameters ([#1795](https://github.com/mongodb/node-mongodb-native/issues/1795)) ([36e92f1](https://github.com/mongodb/node-mongodb-native/commit/36e92f1)) -* **db_ops:** fix two incorrectly named variables ([15dc808](https://github.com/mongodb/node-mongodb-native/commit/15dc808)) -* **findOneAndUpdate:** ensure that update documents contain atomic operators ([eb68074](https://github.com/mongodb/node-mongodb-native/commit/eb68074)) -* **index:** export MongoNetworkError ([98ab29e](https://github.com/mongodb/node-mongodb-native/commit/98ab29e)) -* **mongo_client:** translate options for connectWithUrl ([78f6977](https://github.com/mongodb/node-mongodb-native/commit/78f6977)) -* **mongo-client:** pass arguments to ctor when new keyword is used ([d6c3417](https://github.com/mongodb/node-mongodb-native/commit/d6c3417)) -* **mongos:** bubble up close events after the first one ([#1713](https://github.com/mongodb/node-mongodb-native/issues/1713)) ([3e91d77](https://github.com/mongodb/node-mongodb-native/commit/3e91d77)), closes [Automattic/mongoose#6249](https://github.com/Automattic/mongoose/issues/6249) [#1685](https://github.com/mongodb/node-mongodb-native/issues/1685) -* **parallelCollectionScan:** do not use implicit sessions on cursors ([2de470a](https://github.com/mongodb/node-mongodb-native/commit/2de470a)) -* **retryWrites:** fixes more bulk ops to not use retryWrites ([69e5254](https://github.com/mongodb/node-mongodb-native/commit/69e5254)) -* **server:** remove unnecessary print statement ([2bcbc12](https://github.com/mongodb/node-mongodb-native/commit/2bcbc12)) -* **teardown:** properly destroy a topology when initial connect fails ([b8d2f1d](https://github.com/mongodb/node-mongodb-native/commit/b8d2f1d)) -* **topology-base:** sending `endSessions` is always skipped now ([a276cbe](https://github.com/mongodb/node-mongodb-native/commit/a276cbe)) -* **txns:** omit writeConcern when in a transaction ([b88c938](https://github.com/mongodb/node-mongodb-native/commit/b88c938)) -* **utils:** restructure inheritance rules for read preferences ([6a7dac1](https://github.com/mongodb/node-mongodb-native/commit/6a7dac1)) - - -### Features - -* **auth:** add support for SCRAM-SHA-256 ([f53195d](https://github.com/mongodb/node-mongodb-native/commit/f53195d)) -* **changeStream:** Adding new 4.0 ChangeStream features ([2cb4894](https://github.com/mongodb/node-mongodb-native/commit/2cb4894)) -* **changeStream:** allow resuming on getMore errors ([4ba5adc](https://github.com/mongodb/node-mongodb-native/commit/4ba5adc)) -* **changeStream:** expanding changeStream resumable errors ([49fbafd](https://github.com/mongodb/node-mongodb-native/commit/49fbafd)) -* **ChangeStream:** update default startAtOperationTime ([50a9f65](https://github.com/mongodb/node-mongodb-native/commit/50a9f65)) -* **collection:** add colleciton level document mapping/unmapping ([d03335e](https://github.com/mongodb/node-mongodb-native/commit/d03335e)) -* **collection:** Implement new count API ([a5240ae](https://github.com/mongodb/node-mongodb-native/commit/a5240ae)) -* **Collection:** warn if callback is not function in find and findOne ([cddaba0](https://github.com/mongodb/node-mongodb-native/commit/cddaba0)) -* **core:** bump core dependency to v3.1.0 ([4937240](https://github.com/mongodb/node-mongodb-native/commit/4937240)) -* **cursor:** new cursor.transformStream method ([397fcd2](https://github.com/mongodb/node-mongodb-native/commit/397fcd2)) -* **deprecation:** create deprecation function ([4f907a0](https://github.com/mongodb/node-mongodb-native/commit/4f907a0)) -* **deprecation:** wrap deprecated functions ([a5d0f1d](https://github.com/mongodb/node-mongodb-native/commit/a5d0f1d)) -* **GridFS:** add option to disable md5 in file upload ([704a88e](https://github.com/mongodb/node-mongodb-native/commit/704a88e)) -* **listCollections:** add support for nameOnly option ([d2d0367](https://github.com/mongodb/node-mongodb-native/commit/d2d0367)) -* **parallelCollectionScan:** does not allow user to pass a session ([4da9e03](https://github.com/mongodb/node-mongodb-native/commit/4da9e03)) -* **read-preference:** add transaction to inheritance rules ([18ca41d](https://github.com/mongodb/node-mongodb-native/commit/18ca41d)) -* **read-preference:** unify means of read preference resolution ([#1738](https://github.com/mongodb/node-mongodb-native/issues/1738)) ([2995e11](https://github.com/mongodb/node-mongodb-native/commit/2995e11)) -* **urlParser:** use core URL parser ([c1c5d8d](https://github.com/mongodb/node-mongodb-native/commit/c1c5d8d)) -* **withSession:** add top level helper for session lifetime ([9976b86](https://github.com/mongodb/node-mongodb-native/commit/9976b86)) - - -### Reverts - -* **collection:** reverting collection-mapping features ([7298c76](https://github.com/mongodb/node-mongodb-native/commit/7298c76)), closes [#1698](https://github.com/mongodb/node-mongodb-native/issues/1698) [mongodb/js-bson#253](https://github.com/mongodb/js-bson/issues/253) - - - - -## [3.1.1](https://github.com/mongodb/node-mongodb-native/compare/v3.1.0...v3.1.1) (2018-07-05) - - -### Bug Fixes - -* **client-ops:** return transform map to map rather than function ([b8b4bfa](https://github.com/mongodb/node-mongodb-native/commit/b8b4bfa)) -* **collection:** correctly shallow clone passed in options ([2e6c4fa](https://github.com/mongodb/node-mongodb-native/commit/2e6c4fa)) -* **collection:** countDocuments throws error when query doesn't match docs ([4e83556](https://github.com/mongodb/node-mongodb-native/commit/4e83556)) -* **server:** remove unnecessary print statement ([20e11b3](https://github.com/mongodb/node-mongodb-native/commit/20e11b3)) - - - - -# [3.1.0](https://github.com/mongodb/node-mongodb-native/compare/v3.0.6...v3.1.0) (2018-06-27) - - -### Bug Fixes - -* **aggregate:** support user-provided `batchSize` ([ad10dee](https://github.com/mongodb/node-mongodb-native/commit/ad10dee)) -* **bulk:** fixing retryable writes for mass-change ops ([0604036](https://github.com/mongodb/node-mongodb-native/commit/0604036)) -* **bulk:** handle MongoWriteConcernErrors ([12ff392](https://github.com/mongodb/node-mongodb-native/commit/12ff392)) -* **change_stream:** do not check isGetMore if error[mongoErrorContextSymbol] is undefined ([#1720](https://github.com/mongodb/node-mongodb-native/issues/1720)) ([844c2c8](https://github.com/mongodb/node-mongodb-native/commit/844c2c8)) -* **change-stream:** fix change stream resuming with promises ([3063f00](https://github.com/mongodb/node-mongodb-native/commit/3063f00)) -* **collection:** depend on `resolveReadPreference` for inheritance ([a649e35](https://github.com/mongodb/node-mongodb-native/commit/a649e35)) -* **collection:** only send bypassDocumentValidation if true ([fdb828b](https://github.com/mongodb/node-mongodb-native/commit/fdb828b)) -* **cursor:** cursor count with collation fix ([71879c3](https://github.com/mongodb/node-mongodb-native/commit/71879c3)) -* **cursor:** cursor hasNext returns false when exhausted ([184b817](https://github.com/mongodb/node-mongodb-native/commit/184b817)) -* **cursor:** cursor.count not respecting parent readPreference ([5a9fdf0](https://github.com/mongodb/node-mongodb-native/commit/5a9fdf0)) -* **db:** don't send session down to createIndex command ([559c195](https://github.com/mongodb/node-mongodb-native/commit/559c195)) -* **db:** throw readable error when creating `_id` with background: true ([b3ff3ed](https://github.com/mongodb/node-mongodb-native/commit/b3ff3ed)) -* **findOneAndUpdate:** ensure that update documents contain atomic operators ([eb68074](https://github.com/mongodb/node-mongodb-native/commit/eb68074)) -* **index:** export MongoNetworkError ([98ab29e](https://github.com/mongodb/node-mongodb-native/commit/98ab29e)) -* **mongo-client:** pass arguments to ctor when new keyword is used ([d6c3417](https://github.com/mongodb/node-mongodb-native/commit/d6c3417)) -* **mongos:** bubble up close events after the first one ([#1713](https://github.com/mongodb/node-mongodb-native/issues/1713)) ([3e91d77](https://github.com/mongodb/node-mongodb-native/commit/3e91d77)), closes [Automattic/mongoose#6249](https://github.com/Automattic/mongoose/issues/6249) [#1685](https://github.com/mongodb/node-mongodb-native/issues/1685) -* **parallelCollectionScan:** do not use implicit sessions on cursors ([2de470a](https://github.com/mongodb/node-mongodb-native/commit/2de470a)) -* **retryWrites:** fixes more bulk ops to not use retryWrites ([69e5254](https://github.com/mongodb/node-mongodb-native/commit/69e5254)) -* **topology-base:** sending `endSessions` is always skipped now ([a276cbe](https://github.com/mongodb/node-mongodb-native/commit/a276cbe)) -* **txns:** omit writeConcern when in a transaction ([b88c938](https://github.com/mongodb/node-mongodb-native/commit/b88c938)) -* **utils:** restructure inheritance rules for read preferences ([6a7dac1](https://github.com/mongodb/node-mongodb-native/commit/6a7dac1)) - - -### Features - -* **auth:** add support for SCRAM-SHA-256 ([f53195d](https://github.com/mongodb/node-mongodb-native/commit/f53195d)) -* **changeStream:** Adding new 4.0 ChangeStream features ([2cb4894](https://github.com/mongodb/node-mongodb-native/commit/2cb4894)) -* **changeStream:** allow resuming on getMore errors ([4ba5adc](https://github.com/mongodb/node-mongodb-native/commit/4ba5adc)) -* **changeStream:** expanding changeStream resumable errors ([49fbafd](https://github.com/mongodb/node-mongodb-native/commit/49fbafd)) -* **ChangeStream:** update default startAtOperationTime ([50a9f65](https://github.com/mongodb/node-mongodb-native/commit/50a9f65)) -* **collection:** add colleciton level document mapping/unmapping ([d03335e](https://github.com/mongodb/node-mongodb-native/commit/d03335e)) -* **collection:** Implement new count API ([a5240ae](https://github.com/mongodb/node-mongodb-native/commit/a5240ae)) -* **Collection:** warn if callback is not function in find and findOne ([cddaba0](https://github.com/mongodb/node-mongodb-native/commit/cddaba0)) -* **core:** bump core dependency to v3.1.0 ([855bfdb](https://github.com/mongodb/node-mongodb-native/commit/855bfdb)) -* **cursor:** new cursor.transformStream method ([397fcd2](https://github.com/mongodb/node-mongodb-native/commit/397fcd2)) -* **GridFS:** add option to disable md5 in file upload ([704a88e](https://github.com/mongodb/node-mongodb-native/commit/704a88e)) -* **listCollections:** add support for nameOnly option ([d2d0367](https://github.com/mongodb/node-mongodb-native/commit/d2d0367)) -* **parallelCollectionScan:** does not allow user to pass a session ([4da9e03](https://github.com/mongodb/node-mongodb-native/commit/4da9e03)) -* **read-preference:** add transaction to inheritance rules ([18ca41d](https://github.com/mongodb/node-mongodb-native/commit/18ca41d)) -* **read-preference:** unify means of read preference resolution ([#1738](https://github.com/mongodb/node-mongodb-native/issues/1738)) ([2995e11](https://github.com/mongodb/node-mongodb-native/commit/2995e11)) -* **urlParser:** use core URL parser ([c1c5d8d](https://github.com/mongodb/node-mongodb-native/commit/c1c5d8d)) -* **withSession:** add top level helper for session lifetime ([9976b86](https://github.com/mongodb/node-mongodb-native/commit/9976b86)) - - -### Reverts - -* **collection:** reverting collection-mapping features ([7298c76](https://github.com/mongodb/node-mongodb-native/commit/7298c76)), closes [#1698](https://github.com/mongodb/node-mongodb-native/issues/1698) [mongodb/js-bson#253](https://github.com/mongodb/js-bson/issues/253) - - - - -## [3.0.6](https://github.com/mongodb/node-mongodb-native/compare/v3.0.5...v3.0.6) (2018-04-09) - - -### Bug Fixes - -* **db:** ensure `dropDatabase` always uses primary read preference ([e62e5c9](https://github.com/mongodb/node-mongodb-native/commit/e62e5c9)) -* **driverBench:** driverBench has default options object now ([c557817](https://github.com/mongodb/node-mongodb-native/commit/c557817)) - - -### Features - -* **command-monitoring:** support enabling command monitoring ([5903680](https://github.com/mongodb/node-mongodb-native/commit/5903680)) -* **core:** update to mongodb-core v3.0.6 ([cfdd0ae](https://github.com/mongodb/node-mongodb-native/commit/cfdd0ae)) -* **driverBench:** Implementing DriverBench ([d10fbad](https://github.com/mongodb/node-mongodb-native/commit/d10fbad)) - - - - -## [3.0.5](https://github.com/mongodb/node-mongodb-native/compare/v3.0.4...v3.0.5) (2018-03-23) - - -### Bug Fixes - -* **AggregationCursor:** adding session tracking to AggregationCursor ([baca5b7](https://github.com/mongodb/node-mongodb-native/commit/baca5b7)) -* **Collection:** fix session leak in parallelCollectonScan ([3331ec9](https://github.com/mongodb/node-mongodb-native/commit/3331ec9)) -* **comments:** adding fixes for PR comments ([ee110ac](https://github.com/mongodb/node-mongodb-native/commit/ee110ac)) -* **url_parser:** support a default database on mongodb+srv uris ([6d39b2a](https://github.com/mongodb/node-mongodb-native/commit/6d39b2a)) - - -### Features - -* **sessions:** adding implicit cursor session support ([a81245b](https://github.com/mongodb/node-mongodb-native/commit/a81245b)) - - - - -## [3.0.4](https://github.com/mongodb/node-mongodb-native/compare/v3.0.2...v3.0.4) (2018-03-05) - - -### Bug Fixes - -* **collection:** fix error when calling remove with no args ([#1657](https://github.com/mongodb/node-mongodb-native/issues/1657)) ([4c9b0f8](https://github.com/mongodb/node-mongodb-native/commit/4c9b0f8)) -* **executeOperation:** don't mutate options passed to commands ([934a43a](https://github.com/mongodb/node-mongodb-native/commit/934a43a)) -* **jsdoc:** mark db.collection callback as optional + typo fix ([#1658](https://github.com/mongodb/node-mongodb-native/issues/1658)) ([c519b9b](https://github.com/mongodb/node-mongodb-native/commit/c519b9b)) -* **sessions:** move active session tracking to topology base ([#1665](https://github.com/mongodb/node-mongodb-native/issues/1665)) ([b1f296f](https://github.com/mongodb/node-mongodb-native/commit/b1f296f)) -* **utils:** fixes executeOperation to clean up sessions ([04e6ef6](https://github.com/mongodb/node-mongodb-native/commit/04e6ef6)) - - -### Features - -* **default-db:** use dbName from uri if none provided ([23b1938](https://github.com/mongodb/node-mongodb-native/commit/23b1938)) -* **mongodb-core:** update to mongodb-core 3.0.4 ([1fdbaa5](https://github.com/mongodb/node-mongodb-native/commit/1fdbaa5)) - - - - -## [3.0.3](https://github.com/mongodb/node-mongodb-native/compare/v3.0.2...v3.0.3) (2018-02-23) - - -### Bug Fixes - -* **collection:** fix error when calling remove with no args ([#1657](https://github.com/mongodb/node-mongodb-native/issues/1657)) ([4c9b0f8](https://github.com/mongodb/node-mongodb-native/commit/4c9b0f8)) -* **executeOperation:** don't mutate options passed to commands ([934a43a](https://github.com/mongodb/node-mongodb-native/commit/934a43a)) -* **jsdoc:** mark db.collection callback as optional + typo fix ([#1658](https://github.com/mongodb/node-mongodb-native/issues/1658)) ([c519b9b](https://github.com/mongodb/node-mongodb-native/commit/c519b9b)) -* **sessions:** move active session tracking to topology base ([#1665](https://github.com/mongodb/node-mongodb-native/issues/1665)) ([b1f296f](https://github.com/mongodb/node-mongodb-native/commit/b1f296f)) - - - - -## [3.0.2](https://github.com/mongodb/node-mongodb-native/compare/v3.0.1...v3.0.2) (2018-01-29) - - -### Bug Fixes - -* **collection:** ensure dynamic require of `db` is wrapped in parentheses ([efa78f0](https://github.com/mongodb/node-mongodb-native/commit/efa78f0)) -* **db:** only callback with MongoError NODE-1293 ([#1652](https://github.com/mongodb/node-mongodb-native/issues/1652)) ([45bc722](https://github.com/mongodb/node-mongodb-native/commit/45bc722)) -* **topology base:** allow more than 10 event listeners ([#1630](https://github.com/mongodb/node-mongodb-native/issues/1630)) ([d9fb750](https://github.com/mongodb/node-mongodb-native/commit/d9fb750)) -* **url parser:** preserve auth creds when composing conn string ([#1640](https://github.com/mongodb/node-mongodb-native/issues/1640)) ([eddca5e](https://github.com/mongodb/node-mongodb-native/commit/eddca5e)) - - -### Features - -* **bulk:** forward 'checkKeys' option for ordered and unordered bulk operations ([421a6b2](https://github.com/mongodb/node-mongodb-native/commit/421a6b2)) -* **collection:** expose `dbName` property of collection ([6fd05c1](https://github.com/mongodb/node-mongodb-native/commit/6fd05c1)) - - - - -## [3.0.1](https://github.com/mongodb/node-mongodb-native/compare/v3.0.0...v3.0.1) (2017-12-24) - -* update mongodb-core to 3.0.1 - - -# [3.0.0](https://github.com/mongodb/node-mongodb-native/compare/v3.0.0-rc0...v3.0.0) (2017-12-24) - - -### Bug Fixes - -* **aggregate:** remove support for inline results for aggregate ([#1620](https://github.com/mongodb/node-mongodb-native/issues/1620)) ([84457ec](https://github.com/mongodb/node-mongodb-native/commit/84457ec)) -* **topologies:** unify topologies connect API ([#1615](https://github.com/mongodb/node-mongodb-native/issues/1615)) ([0fb4658](https://github.com/mongodb/node-mongodb-native/commit/0fb4658)) - - -### Features - -* **keepAlive:** make keepAlive options consistent ([#1612](https://github.com/mongodb/node-mongodb-native/issues/1612)) ([f608f44](https://github.com/mongodb/node-mongodb-native/commit/f608f44)) - - -### BREAKING CHANGES - -* **topologies:** Function signature for `.connect` method on replset and mongos has changed. You shouldn't have been using this anyway, but if you were, you only should pass `options` and `callback`. - -Part of NODE-1089 -* **keepAlive:** option `keepAlive` is now split into boolean `keepAlive` and -number `keepAliveInitialDelay` - -Fixes NODE-998 - - - - -# [3.0.0-rc0](https://github.com/mongodb/node-mongodb-native/compare/v2.2.31...v3.0.0-rc0) (2017-12-05) - - -### Bug Fixes - -* **aggregation:** ensure that the `cursor` key is always present ([f16f314](https://github.com/mongodb/node-mongodb-native/commit/f16f314)) -* **apm:** give users access to raw server responses ([88b206b](https://github.com/mongodb/node-mongodb-native/commit/88b206b)) -* **apm:** only rebuilt cursor if reply is non-null ([96052c8](https://github.com/mongodb/node-mongodb-native/commit/96052c8)) -* **apm:** rebuild lost `cursor` info on pre-OP_QUERY responses ([4242d49](https://github.com/mongodb/node-mongodb-native/commit/4242d49)) -* **bulk-unordered:** add check for ignoreUndefined ([f38641a](https://github.com/mongodb/node-mongodb-native/commit/f38641a)) -* **change stream examples:** use timeouts, cleanup ([c5fec5f](https://github.com/mongodb/node-mongodb-native/commit/c5fec5f)) -* **change-streams:** ensure a majority read concern on initial agg ([23011e9](https://github.com/mongodb/node-mongodb-native/commit/23011e9)) -* **changeStreams:** fixing node4 issue with util.inherits ([#1587](https://github.com/mongodb/node-mongodb-native/issues/1587)) ([168bb3d](https://github.com/mongodb/node-mongodb-native/commit/168bb3d)) -* **collection:** allow { upsert: 1 } for findOneAndUpdate() and update() ([5bcedd6](https://github.com/mongodb/node-mongodb-native/commit/5bcedd6)) -* **collection:** allow passing `noCursorTimeout` as an option to `find()` ([e9c4ffc](https://github.com/mongodb/node-mongodb-native/commit/e9c4ffc)) -* **collection:** make the parameters of findOne very explicit ([3054f1a](https://github.com/mongodb/node-mongodb-native/commit/3054f1a)) -* **cursor:** `hasNext` should propagate errors when using callback ([6339625](https://github.com/mongodb/node-mongodb-native/commit/6339625)) -* **cursor:** close readable on `null` response for dead cursor ([6aca2c5](https://github.com/mongodb/node-mongodb-native/commit/6aca2c5)) -* **dns txt records:** check options are set ([e5caf4f](https://github.com/mongodb/node-mongodb-native/commit/e5caf4f)) -* **docs:** Represent each valid option in docs in both places ([fde6e5d](https://github.com/mongodb/node-mongodb-native/commit/fde6e5d)) -* **grid-store:** add missing callback ([66a9a05](https://github.com/mongodb/node-mongodb-native/commit/66a9a05)) -* **grid-store:** move into callback scope ([b53f65f](https://github.com/mongodb/node-mongodb-native/commit/b53f65f)) -* **GridFS:** fix TypeError: doc.data.length is not a function ([#1570](https://github.com/mongodb/node-mongodb-native/issues/1570)) ([22a4628](https://github.com/mongodb/node-mongodb-native/commit/22a4628)) -* **list-collections:** ensure default of primary ReadPreference ([4a0cfeb](https://github.com/mongodb/node-mongodb-native/commit/4a0cfeb)) -* **mongo client:** close client before calling done ([c828aab](https://github.com/mongodb/node-mongodb-native/commit/c828aab)) -* **mongo client:** do not connect if url parse error ([cd10084](https://github.com/mongodb/node-mongodb-native/commit/cd10084)) -* **mongo client:** send error to cb ([eafc9e2](https://github.com/mongodb/node-mongodb-native/commit/eafc9e2)) -* **mongo-client:** move to inside of callback ([68b0fca](https://github.com/mongodb/node-mongodb-native/commit/68b0fca)) -* **mongo-client:** options should not be passed to `connect` ([474ac65](https://github.com/mongodb/node-mongodb-native/commit/474ac65)) -* **tests:** migrate 2.x tests to 3.x ([3a5232a](https://github.com/mongodb/node-mongodb-native/commit/3a5232a)) -* **updateOne/updateMany:** ensure that update documents contain atomic operators ([8b4255a](https://github.com/mongodb/node-mongodb-native/commit/8b4255a)) -* **url parser:** add check for options as cb ([52b6039](https://github.com/mongodb/node-mongodb-native/commit/52b6039)) -* **url parser:** compare srv address and parent domains ([daa186d](https://github.com/mongodb/node-mongodb-native/commit/daa186d)) -* **url parser:** compare string from first period on ([9e5d77e](https://github.com/mongodb/node-mongodb-native/commit/9e5d77e)) -* **url parser:** default to ssl true for mongodb+srv ([0fbca4b](https://github.com/mongodb/node-mongodb-native/commit/0fbca4b)) -* **url parser:** error when multiple hostnames used ([c1aa681](https://github.com/mongodb/node-mongodb-native/commit/c1aa681)) -* **url parser:** keep original uri options and default to ssl true ([e876a72](https://github.com/mongodb/node-mongodb-native/commit/e876a72)) -* **url parser:** log instead of throw error for unsupported url options ([155de2d](https://github.com/mongodb/node-mongodb-native/commit/155de2d)) -* **url parser:** make sure uri has 3 parts ([aa9871b](https://github.com/mongodb/node-mongodb-native/commit/aa9871b)) -* **url parser:** only 1 txt record allowed with 2 possible options ([d9f4218](https://github.com/mongodb/node-mongodb-native/commit/d9f4218)) -* **url parser:** only check for multiple hostnames with srv protocol ([5542bcc](https://github.com/mongodb/node-mongodb-native/commit/5542bcc)) -* **url parser:** remove .only from test ([642e39e](https://github.com/mongodb/node-mongodb-native/commit/642e39e)) -* **url parser:** return callback ([6096afc](https://github.com/mongodb/node-mongodb-native/commit/6096afc)) -* **url parser:** support single text record with multiple strings ([356fa57](https://github.com/mongodb/node-mongodb-native/commit/356fa57)) -* **url parser:** try catch bug, not actually returning from try loop ([758892b](https://github.com/mongodb/node-mongodb-native/commit/758892b)) -* **url parser:** use warn instead of info ([40ed27d](https://github.com/mongodb/node-mongodb-native/commit/40ed27d)) -* **url-parser:** remove comment, send error to cb ([d44420b](https://github.com/mongodb/node-mongodb-native/commit/d44420b)) - - -### Features - -* **aggregate:** support hit field for aggregate command ([aa7da15](https://github.com/mongodb/node-mongodb-native/commit/aa7da15)) -* **aggregation:** adds support for comment in aggregation command ([#1571](https://github.com/mongodb/node-mongodb-native/issues/1571)) ([4ac475c](https://github.com/mongodb/node-mongodb-native/commit/4ac475c)) -* **aggregation:** fail aggregation on explain + readConcern/writeConcern ([e0ca1b4](https://github.com/mongodb/node-mongodb-native/commit/e0ca1b4)) -* **causal-consistency:** support `afterClusterTime` in readConcern ([a9097f7](https://github.com/mongodb/node-mongodb-native/commit/a9097f7)) -* **change-streams:** add support for change streams ([c02d25c](https://github.com/mongodb/node-mongodb-native/commit/c02d25c)) -* **collection:** updating find API ([f26362d](https://github.com/mongodb/node-mongodb-native/commit/f26362d)) -* **execute-operation:** implementation for common op execution ([67c344f](https://github.com/mongodb/node-mongodb-native/commit/67c344f)) -* **listDatabases:** add support for nameOnly option to listDatabases ([eb79b5a](https://github.com/mongodb/node-mongodb-native/commit/eb79b5a)) -* **maxTimeMS:** adding maxTimeMS option to createIndexes and dropIndexes ([90d4a63](https://github.com/mongodb/node-mongodb-native/commit/90d4a63)) -* **mongo-client:** implement `MongoClient.prototype.startSession` ([bce5adf](https://github.com/mongodb/node-mongodb-native/commit/bce5adf)) -* **retryable-writes:** add support for `retryWrites` cs option ([2321870](https://github.com/mongodb/node-mongodb-native/commit/2321870)) -* **sessions:** MongoClient will now track sessions and release ([6829f47](https://github.com/mongodb/node-mongodb-native/commit/6829f47)) -* **sessions:** support passing sessions via objects in all methods ([a531f05](https://github.com/mongodb/node-mongodb-native/commit/a531f05)) -* **shared:** add helper utilities for assertion and suite setup ([b6cc34e](https://github.com/mongodb/node-mongodb-native/commit/b6cc34e)) -* **ssl:** adds missing ssl options ssl options for `ciphers` and `ecdhCurve` ([441b7b1](https://github.com/mongodb/node-mongodb-native/commit/441b7b1)) -* **test-shared:** add `notEqual` assertion ([41d93fd](https://github.com/mongodb/node-mongodb-native/commit/41d93fd)) -* **test-shared:** add `strictEqual` assertion method ([cad8e19](https://github.com/mongodb/node-mongodb-native/commit/cad8e19)) -* **topologies:** expose underlaying `logicalSessionTimeoutMinutes' ([1609a37](https://github.com/mongodb/node-mongodb-native/commit/1609a37)) -* **url parser:** better error message for slash in hostname ([457bc29](https://github.com/mongodb/node-mongodb-native/commit/457bc29)) - - -### BREAKING CHANGES - -* **aggregation:** If you use aggregation, and try to use the explain flag while you -have a readConcern or writeConcern, your query will fail -* **collection:** `find` and `findOne` no longer support the `fields` parameter. -You can achieve the same results as the `fields` parameter by -either using `Cursor.prototype.project`, or by passing the `projection` -property in on the `options` object. Additionally, `find` does not -support individual options like `skip` and `limit` as positional -parameters. You must pass in these parameters in the `options` object - - - -3.0.0 2017-??-?? ----------------- -* NODE-1043 URI-escaping authentication and hostname details in connection string - -2.2.31 2017-08-08 ------------------ -* update mongodb-core to 2.2.15 -* allow auth option in MongoClient.connect -* remove duplicate option `promoteLongs` from MongoClient's `connect` -* bulk operations should not throw an error on empty batch - -2.2.30 2017-07-07 ------------------ -* Update mongodb-core to 2.2.14 -* MongoClient - * add `appname` to list of valid option names - * added test for passing appname as option -* NODE-1052 ensure user options are applied while parsing connection string uris - -2.2.29 2017-06-19 ------------------ -* Update mongodb-core to 2.1.13 - * NODE-1039 ensure we force destroy server instances, forcing queue to be flushed. - * Use actual server type in standalone SDAM events. -* Allow multiple map calls (Issue #1521, https://github.com/Robbilie). -* Clone insertMany options before mutating (Issue #1522, https://github.com/vkarpov15). -* NODE-1034 Fix GridStore issue caused by Node 8.0.0 breaking backward compatible fs.read API. -* NODE-1026, use operator instead of skip function in order to avoid useless fetch stage. - -2.2.28 2017-06-02 ------------------ -* Update mongodb-core to 2.1.12 - * NODE-1019 Set keepAlive to 300 seconds or 1/2 of socketTimeout if socketTimeout < keepAlive. - * Minor fix to report the correct state on error. - * NODE-1020 'family' was added to options to provide high priority for ipv6 addresses (Issue #1518, https://github.com/firej). - * Fix require_optional loading of bson-ext. - * Ensure no errors are thrown by replset if topology is destroyed before it finished connecting. - * NODE-999 SDAM fixes for Mongos and single Server event emitting. - * NODE-1014 Set socketTimeout to default to 360 seconds. - * NODE-1019 Set keepAlive to 300 seconds or 1/2 of socketTimeout if socketTimeout < keepAlive. -* Just handle Collection name errors distinctly from general callback errors avoiding double callbacks in Db.collection. -* NODE-999 SDAM fixes for Mongos and single Server event emitting. -* NODE-1000 Added guard condition for upload.js checkDone function in case of race condition caused by late arriving chunk write. - -2.2.27 2017-05-22 ------------------ -* Updated mongodb-core to 2.1.11 - * NODE-987 Clear out old intervalIds on when calling topologyMonitor. - * NODE-987 Moved filtering to pingServer method and added test case. - * Check for connection destroyed just before writing out and flush out operations correctly if it is (Issue #179, https://github.com/jmholzinger). - * NODE-989 Refactored Replicaset monitoring to correcly monitor newly added servers, Also extracted setTimeout and setInterval to use custom wrappers Timeout and Interval. -* NODE-985 Deprecated Db.authenticate and Admin.authenticate and moved auth methods into authenticate.js to ensure MongoClient.connect does not print deprecation warnings. -* NODE-988 Merged readConcern and hint correctly on collection(...).find(...).count() -* Fix passing the readConcern option to MongoClient.connect (Issue #1514, https://github.com/bausmeier). -* NODE-996 Propegate all events up to a MongoClient instance. -* Allow saving doc with null `_id` (Issue #1517, https://github.com/vkarpov15). -* NODE-993 Expose hasNext for command cursor and add docs for both CommandCursor and Aggregation Cursor. - -2.2.26 2017-04-18 ------------------ -* Updated mongodb-core to 2.1.10 - * NODE-981 delegate auth to replset/mongos if inTopology is set. - * NODE-978 Wrap connection.end in try/catch for node 0.10.x issue causing exceptions to be thrown, Also surfaced getConnection for mongos and replset. - * Remove dynamic require (Issue #175, https://github.com/tellnes). - * NODE-696 Handle interrupted error for createIndexes. - * Fixed isse when user is executing find command using Server.command and it get interpreted as a wire protcol message, #172. - * NODE-966 promoteValues not being promoted correctly to getMore. - * Merged in fix for flushing out monitoring operations. -* NODE-983 Add cursorId to aggregate and listCollections commands (Issue, #1510). -* Mark group and profilingInfo as deprecated methods -* NODE-956 DOCS Examples. -* Update readable-stream to version 2.2.7. -* NODE-978 Added test case to uncover connection.end issue for node 0.10.x. -* NODE-972 Fix(db): don't remove database name if collectionName == dbName (Issue, #1502) -* Fixed merging of writeConcerns on db.collection method. -* NODE-970 mix in readPreference for strict mode listCollections callback. -* NODE-966 added testcase for promoteValues being applied to getMore commands. -* NODE-962 Merge in ignoreUndefined from collection level for find/findOne. -* Remove multi option from updateMany tests/docs (Issue #1499, https://github.com/spratt). -* NODE-963 Correctly handle cursor.count when using APM. - -2.2.25 2017-03-17 ------------------ -* Don't rely on global toString() for checking if object (Issue #1494, https://github.com/vkarpov15). -* Remove obsolete option uri_decode_auth (Issue #1488, https://github.com/kamagatos). -* NODE-936 Correctly translate ReadPreference to CoreReadPreference for mongos queries. -* Exposed BSONRegExp type. -* NODE-950 push correct index for INSERT ops (https://github.com/mbroadst). -* NODE-951 Added support for sslCRL option and added a test case for it. -* NODE-953 Made batchSize issue general at cursor level. -* NODE-954 Remove write concern from reindex helper as it will not be supported in 3.6. -* Updated mongodb-core to 2.1.9. - * Return lastIsMaster correctly when connecting with secondaryOnlyConnectionAllowed is set to true and only a secondary is available in replica state. - * Clone options when passed to wireProtocol handler to avoid intermittent modifications causing errors. - * Ensure SSL error propegates better for Replset connections when there is a SSL validation error. - * NODE-957 Fixed issue where < batchSize not causing cursor to be closed on execution of first batch. - * NODE-958 Store reconnectConnection on pool object to allow destroy to close immediately. - -2.2.24 2017-02-14 ------------------ -* NODE-935, NODE-931 Make MongoClient strict options validation optional and instead print annoying console.warn entries. - -2.2.23 2017-02-13 ------------------ -* Updated mongodb-core to 2.1.8. - * NODE-925 ensure we reschedule operations while pool is < poolSize while pool is growing and there are no connections with not currently performing work. - * NODE-927 fixes issue where authentication was performed against arbiter instances. - * NODE-915 Normalize all host names to avoid comparison issues. - * Fixed issue where pool.destroy would never finish due to a single operation not being executed and keeping it open. -* NODE-931 Validates all the options for MongoClient.connect and fixes missing connection settings. -* NODE-929 Update SSL tutorial to correctly reflect the non-need for server/mongos/replset subobjects -* Fix sensitive command check (Issue #1473, https://github.com/Annoraaq) - -2.2.22 2017-01-24 ------------------ -* Updated mongodb-core to 2.1.7. - * NODE-919 ReplicaSet connection does not close immediately (Issue #156). - * NODE-901 Fixed bug when normalizing host names. - * NODE-909 Fixed readPreference issue caused by direct connection to primary. - * NODE-910 Fixed issue when bufferMaxEntries == 0 and read preference set to nearest. -* Add missing unref implementations for replset, mongos (Issue #1455, https://github.com/zbjornson) - -2.2.21 2017-01-13 ------------------ -* Updated mongodb-core to 2.1.6. - * NODE-908 Keep auth contexts in replset and mongos topology to ensure correct application of authentication credentials when primary is first server to be detected causing an immediate connect event to happen. - -2.2.20 2017-01-11 ------------------ -* Updated mongodb-core to 2.1.5 to include bson 1.0.4 and bson-ext 1.0.4 due to Buffer.from being broken in early node 4.x versions. - -2.2.19 2017-01-03 ------------------ -* Corrupted Npm release fix. - -2.2.18 2017-01-03 ------------------ -* Updated mongodb-core to 2.1.4 to fix bson ObjectId toString issue with utils.inspect messing with toString parameters in node 6. - -2.2.17 2017-01-02 ------------------ -* updated createCollection doc options and linked to create command. -* Updated mongodb-core to 2.1.3. - * Monitoring operations are re-scheduled in pool if it cannot find a connection that does not already have scheduled work on it, this is to avoid the monitoring socket timeout being applied to any existing operations on the socket due to pipelining - * Moved replicaset monitoring away from serial mode and to parallel mode. - * updated bson and bson-ext dependencies to 1.0.2. - -2.2.16 2016-12-13 ------------------ -* NODE-899 reversed upsertedId change to bring back old behavior. - -2.2.15 2016-12-10 ------------------ -* Updated mongodb-core to 2.1.2. - * Delay topologyMonitoring on successful attemptReconnect as no need to run a full scan immediately. - * Emit reconnect event in primary joining when in connected status for a replicaset (Fixes mongoose reconnect issue). - -2.2.14 2016-12-08 ------------------ -* Updated mongodb-core to 2.1.1. -* NODE-892 Passthrough options.readPreference to mongodb-core ReplSet instance. - -2.2.13 2016-12-05 ------------------ -* Updated mongodb-core to 2.1.0. -* NODE-889 Fixed issue where legacy killcursor wire protocol messages would not be sent when APM is enabled. -* Expose parserType as property on topology objects. - -2.2.12 2016-11-29 ------------------ -* Updated mongodb-core to 2.0.14. - * Updated bson library to 0.5.7. - * Dont leak connection.workItems elments when killCursor is called (Issue #150, https://github.com/mdlavin). - * Remove unnecessary errors formatting (Issue #149, https://github.com/akryvomaz). - * Only check isConnected against availableConnections (Issue #142). - * NODE-838 Provide better error message on failed to connect on first retry for Mongos topology. - * Set default servername to host is not passed through for sni. - * Made monitoring happen on exclusive connection and using connectionTimeout to handle the wait time before failure (Issue #148). - * NODE-859 Make minimum value of maxStalenessSeconds 90 seconds. - * NODE-852 Fix Kerberos module deprecations on linux and windows and release new kerberos version. - * NODE-850 Update Max Staleness implementation. - * NODE-849 username no longer required for MONGODB-X509 auth. - * NODE-848 BSON Regex flags must be alphabetically ordered. - * NODE-846 Create notice for all third party libraries. - * NODE-843 Executing bulk operations overwrites write concern parameter. - * NODE-842 Re-sync SDAM and SDAM Monitoring tests from Specs repo. - * NODE-840 Resync CRUD spec tests. - * Unescapable while(true) loop (Issue #152). -* NODE-864 close event not emits during network issues using single server topology. -* Introduced maxStalenessSeconds. -* NODE-840 Added CRUD specification test cases and fix minor issues with upserts reporting matchedCount > 0. -* Don't ignore Db-level authSource when using auth method. (https://github.com/donaldguy). - -2.2.11 2016-10-21 ------------------ -* Updated mongodb-core to 2.0.13. - - Fire callback when topology was destroyed (Issue #147, https://github.com/vkarpov15). - - Refactoring to support pipelining ala 1.4.x branch will retaining the benefits of the growing/shrinking pool (Issue #146). - - Fix typo in serverHeartbeatFailed event name (Issue #143, https://github.com/jakesjews). - - NODE-798 Driver hangs on count command in replica set with one member (Issue #141, https://github.com/isayme). -* Updated bson library to 0.5.6. - - Included cyclic dependency detection -* Fix typo in serverHeartbeatFailed event name (Issue #1418, https://github.com/jakesjews). -* NODE-824, readPreference "nearest" does not work when specified at collection level. -* NODE-822, GridFSBucketWriteStream end method does not handle optional parameters. -* NODE-823, GridFSBucketWriteStream end: callback is invoked with invalid parameters. -* NODE-829, Using Start/End offset option in GridFSBucketReadStream doesn't return the right sized buffer. - -2.2.10 2016-09-15 ------------------ -* Updated mongodb-core to 2.0.12. -* fix debug logging message not printing server name. -* fixed application metadata being sent by wrong ismaster. -* NODE-812 Fixed mongos stall due to proxy monitoring ismaster failure causing reconnect. -* NODE-818 Replicaset timeouts in initial connect sequence can "no primary found". -* Updated bson library to 0.5.5. -* Added DBPointer up conversion to DBRef. -* MongoDB 3.4-RC Pass **appname** through MongoClient.connect uri or options to allow metadata to be passed. -* MongoDB 3.4-RC Pass collation options on update, findOne, find, createIndex, aggregate. -* MongoDB 3.4-RC Allow write concerns to be passed to all supporting server commands. -* MongoDB 3.4-RC Allow passing of **servername** as SSL options to support SNI. - -2.2.9 2016-08-29 ----------------- -* Updated mongodb-core to 2.0.11. -* NODE-803, Fixed issue in how the latency window is calculated for Mongos topology causing issues for single proxy connections. -* Avoid timeout in attemptReconnect causing multiple attemptReconnect attempts to happen (Issue #134, https://github.com/dead-horse). -* Ensure promoteBuffers is propegated in same fashion as promoteValues and promoteLongs. -* Don't treat ObjectId as object for mapReduce scope (Issue #1397, https://github.com/vkarpov15). - -2.2.8 2016-08-23 ----------------- -* Updated mongodb-core to 2.0.10. -* Added promoteValues flag (default to true) to allow user to specify they only want wrapped BSON values back instead of promotion to native types. -* Do not close mongos proxy connection on failed ismaster check in ha process (Issue #130). - -2.2.7 2016-08-19 ----------------- -* If only a single mongos is provided in the seedlist, fix issue where it would be assigned as single standalone server instead of mongos topology (Issue #130). -* Updated mongodb-core to 2.0.9. -* Allow promoteLongs to be passed in through Response.parse method and overrides default set on the connection. -* NODE-798 Driver hangs on count command in replica set with one member. -* Allow promoteLongs to be passed in through Response.parse method and overrides default set on the connection. -* Allow passing in servername for TLS connections for SNI support. - -2.2.6 2016-08-16 ----------------- -* Updated mongodb-core to 2.0.8. -* Allow execution of store operations independent of having both a primary and secondary available (Issue #123). -* Fixed command execution issue for mongos to ensure buffering of commands when no mongos available. -* Allow passing in an array of tags to ReadPreference constructor (Issue #1382, https://github.com/vkarpov15) -* Added hashed connection names and fullResult. -* Updated bson library to 0.5.3. -* Enable maxTimeMS in count, distinct, findAndModify. - -2.2.5 2016-07-28 ----------------- -* Updated mongodb-core to 2.0.7. -* Allow primary to be returned when secondaryPreferred is passed (Issue #117, https://github.com/dhendo). -* Added better warnings when passing in illegal seed list members to a Mongos topology. -* Minor attemptReconnect bug that would cause multiple attemptReconnect to run in parallel. -* Fix wrong opType passed to disconnectHandler.add (Issue #121, https://github.com/adrian-gierakowski) -* Implemented domain backward comp support enabled via domainsEnabled options on Server/ReplSet/Mongos and MongoClient.connect. - -2.2.4 2016-07-19 ----------------- -* NPM corrupted upload fix. - -2.2.3 2016-07-19 ----------------- -* Updated mongodb-core to 2.0.6. -* Destroy connection on socket timeout due to newer node versions not closing the socket. - -2.2.2 2016-07-15 ----------------- -* Updated mongodb-core to 2.0.5. -* Minor fixes to handle faster MongoClient connectivity from the driver, allowing single server instances to detect if they are a proxy. -* Added numberOfConsecutiveTimeouts to pool that will destroy the pool if the number of consecutive timeouts > reconnectTries. -* Print warning if seedlist servers host name does not match the one provided in it's ismaster.me field for Replicaset members. -* Fix issue where Replicaset connection would not succeeed if there the replicaset was a single primary server setup. - -2.2.1 2016-07-11 ----------------- -* Updated mongodb-core to 2.0.4. -* handle situation where user is providing seedlist names that do not match host list. fix allows for a single full discovery connection sweep before erroring out. -* NODE-747 Polyfill for Object.assign for 0.12.x or 0.10.x. -* NODE-746 Improves replicaset errors for wrong setName. - -2.2.0 2016-07-05 ----------------- -* Updated mongodb-core to 2.0.3. -* Moved all authentication and handling of growing/shrinking of pool connections into actual pool. -* All authentication methods now handle both auth/reauthenticate and logout events. -* Introduced logout method to get rid of onAll option for logout command. -* Updated bson to 0.5.0 that includes Decimal128 support. -* Fixed logger error serialization issue. -* Documentation fixes. -* Implemented Server Selection Specification test suite. -* Added warning level to logger. -* Added warning message when sockeTimeout < haInterval for Replset/Mongos. -* Mongos emits close event on no proxies available or when reconnect attempt fails. -* Replset emits close event when no servers available or when attemptReconnect fails to reconnect. -* Don't throw in auth methods but return error in callback. - -2.1.21 2016-05-30 ------------------ -* Updated mongodb-core to 1.3.21. -* Pool gets stuck if a connection marked for immediateRelease times out (Issue #99, https://github.com/nbrachet). -* Make authentication process retry up to authenticationRetries at authenticationRetryIntervalMS interval. -* Made ismaster replicaset calls operate with connectTimeout or monitorSocketTimeout to lower impact of big socketTimeouts on monitoring performance. -* Make sure connections mark as "immediateRelease" don't linger the inUserConnections list. Otherwise, after that connection times out, getAll() incorrectly returns more connections than are effectively present, causing the pool to not get restarted by reconnectServer. (Issue #99, https://github.com/nbrachet). -* Make cursor getMore or killCursor correctly trigger pool reconnect to single server if pool has not been destroyed. -* Make ismaster monitoring for single server connection default to avoid user confusion due to change in behavior. - -2.1.20 2016-05-25 ------------------ -* Refactored MongoClient options handling to simplify the logic, unifying it. -* NODE-707 Implemented openUploadStreamWithId on GridFS to allow for custom fileIds so users are able to customize shard key and shard distribution. -* NODE-710 Allow setting driver loggerLevel and logger function from MongoClient options. -* Updated mongodb-core to 1.3.20. -* Minor fix for SSL errors on connection attempts, minor fix to reconnect handler for the server. -* Don't write to socket before having registered the callback for commands, work around for windows issuing error events twice on node.js when socket gets destroyed by firewall. -* Fix minor issue where connectingServers would not be removed correctly causing single server connections to not auto-reconnect. - -2.1.19 2016-05-17 ----------------- -* Handle situation where a server connection in a replicaset sometimes fails to be destroyed properly due to being in the middle of authentication when the destroy method is called on the replicaset causing it to be orphaned and never collected. -* Ensure replicaset topology destroy is never called by SDAM. -* Ensure all paths are correctly returned on inspectServer in replset. -* Updated mongodb-core to 1.3.19 to fix minor connectivity issue on quick open/close of MongoClient connections on auth enabled mongodb Replicasets. - -2.1.18 2016-04-27 ------------------ -* Updated mongodb-core to 1.3.18 to fix Node 6.0 issues. - -2.1.17 2016-04-26 ------------------ -* Updated mongodb-core to 1.3.16 to work around issue with early versions of node 0.10.x due to missing unref method on ClearText streams. -* INT-1308: Allow listIndexes to inherit readPreference from Collection or DB. -* Fix timeout issue using new flags #1361. -* Updated mongodb-core to 1.3.17. -* Better handling of unique createIndex error. -* Emit error only if db instance has an error listener. -* DEFAULT authMechanism; don't throw error if explicitly set by user. - -2.1.16 2016-04-06 ------------------ -* Updated mongodb-core to 1.3.16. - -2.1.15 2016-04-06 ------------------ -* Updated mongodb-core to 1.3.15. -* Set ssl, sslValidate etc to mongosOptions on url_parser (Issue #1352, https://github.com/rubenstolk). -- NODE-687 Fixed issue where a server object failed to be destroyed if the replicaset state did not update successfully. This could leave active connections accumulating over time. -- Fixed some situations where all connections are flushed due to a single connection in the connection pool closing. - -2.1.14 2016-03-29 ------------------ -* Updated mongodb-core to 1.3.13. -* Handle missing cursor on getMore when going through a mongos proxy by pinning to socket connection and not server. - -2.1.13 2016-03-29 ------------------ -* Updated mongodb-core to 1.3.12. - -2.1.12 2016-03-29 ------------------ -* Updated mongodb-core to 1.3.11. -* Mongos setting acceptableLatencyMS exposed to control the latency women for mongos selection. -* Mongos pickProxies fall back to closest mongos if no proxies meet latency window specified. -* isConnected method for mongos uses same selection code as getServer. -* Exceptions in cursor getServer trapped and correctly delegated to high level handler. - -2.1.11 2016-03-23 ------------------ -* Updated mongodb-core to 1.3.10. -* Introducing simplified connections settings. - -2.1.10 2016-03-21 ------------------ -* Updated mongodb-core to 1.3.9. -* Fixing issue that prevented mapReduce stats from being resolved (Issue #1351, https://github.com/davidgtonge) -* Forwards SDAM monitoring events from mongodb-core. - -2.1.9 2016-03-16 ----------------- -* Updated mongodb-core to 1.3.7 to fix intermittent race condition that causes some users to experience big amounts of socket connections. -* Makde bson parser in ordered/unordered bulk be directly from mongodb-core to avoid intermittent null error on mongoose. - -2.1.8 2016-03-14 ----------------- -* Updated mongodb-core to 1.3.5. -* NODE-660 TypeError: Cannot read property 'noRelease' of undefined. -* Harden MessageHandler in server.js to avoid issues where we cannot find a callback for an operation. -* Ensure RequestId can never be larger than Max Number integer size. -* NODE-661 typo in url_parser.js resulting in replSetServerOptions is not defined when connecting over ssl. -* Confusing error with invalid partial index filter (Issue #1341, https://github.com/vkarpov15). -* NODE-669 Should only error out promise for bulkWrite when error is a driver level error not a write error or write concern error. -* NODE-662 shallow copy options on methods that are not currently doing it to avoid passed in options mutiation. -* NODE-663 added lookup helper on aggregation cursor. -* NODE-585 Result object specified incorrectly for findAndModify?. -* NODE-666 harden validation for findAndModify CRUD methods. - -2.1.7 2016-02-09 ----------------- -* NODE-656 fixed corner case where cursor count command could be left without a connection available. -* NODE-658 Work around issue that bufferMaxEntries:-1 for js gets interpreted wrongly due to double nature of Javascript numbers. -* Fix: GridFS always returns the oldest version due to incorrect field name (Issue #1338, https://github.com/mdebruijne). -* NODE-655 GridFS stream support for cancelling upload streams and download streams (Issue #1339, https://github.com/vkarpov15). -* NODE-657 insertOne don`t return promise in some cases. -* Added destroy alias for abort function on GridFSBucketWriteStream. - -2.1.6 2016-02-05 ----------------- -* Updated mongodb-core to 1.3.1. - -2.1.5 2016-02-04 ----------------- -* Updated mongodb-core to 1.3.0. -* Added raw support for the command function on topologies. -* Fixed issue where raw results that fell on batchSize boundaries failed (Issue #72) -* Copy over all the properties to the callback returned from bindToDomain, (Issue #72) -* Added connection hash id to be able to reference connection host/name without leaking it outside of driver. -* NODE-638, Cannot authenticate database user with utf-8 password. -* Refactored pool to be worker queue based, minimizing the impact a slow query have on throughput as long as # slow queries < # connections in the pool. -* Pool now grows and shrinks correctly depending on demand not causing a full pool reconnect. -* Improvements in monitoring of a Replicaset where in certain situations the inquiry process could get exited. -* Switched to using Array.push instead of concat for use cases of a lot of documents. -* Fixed issue where re-authentication could loose the credentials if whole Replicaset disconnected at once. -* Added peer optional dependencies support using require_optional module. -* Bug is listCollections for collection names that start with db name (Issue #1333, https://github.com/flyingfisher) -* Emit error before closing stream (Issue #1335, https://github.com/eagleeye) - -2.1.4 2016-01-12 ----------------- -* Restricted node engine to >0.10.3 (https://jira.mongodb.org/browse/NODE-635). -* Multiple database names ignored without a warning (https://jira.mongodb.org/browse/NODE-636, Issue #1324, https://github.com/yousefhamza). -* Convert custom readPreference objects in collection.js (Issue #1326, https://github.com/Machyne). - -2.1.3 2016-01-04 ----------------- -* Updated mongodb-core to 1.2.31. -* Allow connection to secondary if primaryPreferred or secondaryPreferred (Issue #70, https://github.com/leichter) - -2.1.2 2015-12-23 ----------------- -* Updated mongodb-core to 1.2.30. -* Pool allocates size + 1 connections when using replicasets, reserving additional pool connection for monitoring exclusively. -* Fixes bug when all replicaset members are down, that would cause it to fail to reconnect using the originally provided seedlist. - -2.1.1 2015-12-13 ----------------- -* Surfaced checkServerIdentity options for MongoClient, Server, ReplSet and Mongos to allow for control of the checkServerIdentity method available in Node.s 0.12.x or higher. -* Added readPreference support to listCollections and listIndexes helpers. -* Updated mongodb-core to 1.2.28. - -2.1.0 2015-12-06 ----------------- -* Implements the connection string specification, https://github.com/mongodb/specifications/blob/master/source/connection-string/connection-string-spec.rst. -* Implements the new GridFS specification, https://github.com/mongodb/specifications/blob/master/source/gridfs/gridfs-spec.rst. -* Full MongoDB 3.2 support. -* NODE-601 Added maxAwaitTimeMS support for 3.2 getMore to allow for custom timeouts on tailable cursors. -* Updated mongodb-core to 1.2.26. -* Return destination in GridStore pipe function. -* NODE-606 better error handling on destroyed topology for db.js methods. -* Added isDestroyed method to server, replset and mongos topologies. -* Upgraded test suite to run using mongodb-topology-manager. - -2.0.53 2015-12-23 ------------------ -* Updated mongodb-core to 1.2.30. -* Pool allocates size + 1 connections when using replicasets, reserving additional pool connection for monitoring exclusively. -* Fixes bug when all replicaset members are down, that would cause it to fail to reconnect using the originally provided seedlist. - -2.0.52 2015-12-14 ------------------ -* removed remove from Gridstore.close. - -2.0.51 2015-12-13 ------------------ -* Surfaced checkServerIdentity options for MongoClient, Server, ReplSet and Mongos to allow for control of the checkServerIdentity method available in Node.s 0.12.x or higher. -* Added readPreference support to listCollections and listIndexes helpers. -* Updated mongodb-core to 1.2.28. - -2.0.50 2015-12-06 ------------------ -* Updated mongodb-core to 1.2.26. - -2.0.49 2015-11-20 ------------------ -* Updated mongodb-core to 1.2.24 with several fixes. - * Fix Automattic/mongoose#3481; flush callbacks on error, (Issue #57, https://github.com/vkarpov15). - * $explain query for wire protocol 2.6 and 2.4 does not set number of returned documents to -1 but to 0. - * ismaster runs against admin.$cmd instead of system.$cmd. - * Fixes to handle getMore command errors for MongoDB 3.2 - * Allows the process to properly close upon a Db.close() call on the replica set by shutting down the haTimer and closing arbiter connections. - -2.0.48 2015-11-07 ------------------ -* GridFS no longer performs any deletes when writing a brand new file that does not have any previous .fs.chunks or .fs.files documents. -* Updated mongodb-core to 1.2.21. -* Hardened the checking for replicaset equality checks. -* OpReplay flag correctly set on Wire protocol query. -* Mongos load balancing added, introduced localThresholdMS to control the feature. -* Kerberos now a peerDependency, making it not install it by default in Node 5.0 or higher. - -2.0.47 2015-10-28 ------------------ -* Updated mongodb-core to 1.2.20. -* Fixed bug in arbiter connection capping code. -* NODE-599 correctly handle arrays of server tags in order of priority. -* Fix for 2.6 wire protocol handler related to readPreference handling. -* Added maxAwaitTimeMS support for 3.2 getMore to allow for custom timeouts on tailable cursors. -* Make CoreCursor check for $err before saying that 'next' succeeded (Issue #53, https://github.com/vkarpov15). - -2.0.46 2015-10-15 ------------------ -* Updated mongodb-core to 1.2.19. -* NODE-578 Order of sort fields is lost for numeric field names. -* Expose BSON Map (ES6 Map or polyfill). -* Minor fixes for APM support to pass extended APM test suite. - -2.0.45 2015-09-30 ------------------ -* NODE-566 Fix issue with rewind on capped collections causing cursor state to be reset on connection loss. - -2.0.44 2015-09-28 ------------------ -* Bug fixes for APM upconverting of legacy INSERT/UPDATE/REMOVE wire protocol messages. -* NODE-562, fixed issue where a Replicaset MongoDB URI with a single seed and replSet name set would cause a single direct connection instead of topology discovery. -* Updated mongodb-core to 1.2.14. -* NODE-563 Introduced options.ignoreUndefined for db class and MongoClient db options, made serialize undefined to null default again but allowing for overrides on insert/update/delete operations. -* Use handleCallback if result is an error for count queries. (Issue #1298, https://github.com/agclever) -* Rewind cursor to correctly force reconnect on capped collections when first query comes back empty. -* NODE-571 added code 59 to legacy server errors when SCRAM-SHA-1 mechanism fails. -* NODE-572 Remove examples that use the second parameter to `find()`. - -2.0.43 2015-09-14 ------------------ -* Propagate timeout event correctly to db instances. -* Application Monitoring API (APM) implemented. -* NOT providing replSet name in MongoClient connection URI will force single server connection. Fixes issue where it was impossible to directly connect to a replicaset member server. -* Updated mongodb-core to 1.2.12. -* NODE-541 Initial Support "read committed" isolation level where "committed" means confimed by the voting majority of a replica set. -* GridStore doesn't share readPreference setting from connection string. (Issue #1295, https://github.com/zhangyaoxing) -* fixed forceServerObjectId calls (Issue #1292, https://github.com/d-mon-) -* Pass promise library through to DB function (Issue #1294, https://github.com/RovingCodeMonkey) - -2.0.42 2015-08-18 ------------------ -* Added test case to exercise all non-crud methods on mongos topologies, fixed numberOfConnectedServers on mongos topology instance. - -2.0.41 2015-08-14 ------------------ -* Added missing Mongos.prototype.parserType function. -* Updated mongodb-core to 1.2.10. - -2.0.40 2015-07-14 ------------------ -* Updated mongodb-core to 1.2.9 for 2.4 wire protocol error handler fix. -* NODE-525 Reset connectionTimeout after it's overwritten by tls.connect. -* NODE-518 connectTimeoutMS is doubled in 2.0.39. -* NODE-506 Ensures that errors from bulk unordered and ordered are instanceof Error (Issue #1282, https://github.com/owenallenaz). -* NODE-526 Unique index not throwing duplicate key error. -* NODE-528 Ignore undefined fields in Collection.find(). -* NODE-527 The API example for collection.createIndex shows Db.createIndex functionality. - -2.0.39 2015-07-14 ------------------ -* Updated mongodb-core to 1.2.6 for NODE-505. - -2.0.38 2015-07-14 ------------------ -* NODE-505 Query fails to find records that have a 'result' property with an array value. - -2.0.37 2015-07-14 ------------------ -* NODE-504 Collection * Default options when using promiseLibrary. -* NODE-500 Accidental repeat of hostname in seed list multiplies total connections persistently. -* Updated mongodb-core to 1.2.5 to fix NODE-492. - -2.0.36 2015-07-07 ------------------ -* Fully promisified allowing the use of ES6 generators and libraries like co. Also allows for BYOP (Bring your own promises). -* NODE-493 updated mongodb-core to 1.2.4 to ensure we cannot DDOS the mongod or mongos process on large connection pool sizes. - -2.0.35 2015-06-17 ------------------ -* Upgraded to mongodb-core 1.2.2 including removing warnings when C++ bson parser is not available and a fix for SCRAM authentication. - -2.0.34 2015-06-17 ------------------ -* Upgraded to mongodb-core 1.2.1 speeding up serialization and removing the need for the c++ bson extension. -* NODE-486 fixed issue related to limit and skip when calling toArray in 2.0 driver. -* NODE-483 throw error if capabilities of topology is queries before topology has performed connection setup. -* NODE-482 fixed issue where MongoClient.connect would incorrectly identify a replset seed list server as a non replicaset member. -* NODE-487 fixed issue where killcursor command was not being sent correctly on limit and skip queries. - -2.0.33 2015-05-20 ------------------ -* Bumped mongodb-core to 1.1.32. - -2.0.32 2015-05-19 ------------------ -* NODE-463 db.close immediately executes its callback. -* Don't only emit server close event once (Issue #1276, https://github.com/vkarpov15). -* NODE-464 Updated mongodb-core to 1.1.31 that uses a single socket connection to arbiters and hidden servers as well as emitting all event correctly. - -2.0.31 2015-05-08 ------------------ -* NODE-461 Tripping on error "no chunks found for file, possibly corrupt" when there is no error. - -2.0.30 2015-05-07 ------------------ -* NODE-460 fix; don't set authMechanism for user in db.authenticate() to avoid mongoose authentication issue. - -2.0.29 2015-05-07 ------------------ -* NODE-444 Possible memory leak, too many listeners added. -* NODE-459 Auth failure using Node 0.8.28, MongoDB 3.0.2 & mongodb-node-native 1.4.35. -* Bumped mongodb-core to 1.1.26. - -2.0.28 2015-04-24 ------------------ -* Bumped mongodb-core to 1.1.25 -* Added Cursor.prototype.setCursorOption to allow for setting node specific cursor options for tailable cursors. -* NODE-430 Cursor.count() opts argument masked by var opts = {} -* NODE-406 Implemented Cursor.prototype.map function tapping into MongoClient cursor transforms. -* NODE-438 replaceOne is not returning the result.ops property as described in the docs. -* NODE-433 _read, pipe and write all open gridstore automatically if not open. -* NODE-426 ensure drain event is emitted after write function returns, fixes intermittent issues in writing files to gridstore. -* NODE-440 GridStoreStream._read() doesn't check GridStore.read() error. -* Always use readPreference = primary for findAndModify command (ignore passed in read preferences) (Issue #1274, https://github.com/vkarpov15). -* Minor fix in GridStore.exists for dealing with regular expressions searches. - -2.0.27 2015-04-07 ------------------ -* NODE-410 Correctly handle issue with pause/resume in Node 0.10.x that causes exceptions when using the Node 0.12.0 style streams. - -2.0.26 2015-04-07 ------------------ -* Implements the Common Index specification Standard API at https://github.com/mongodb/specifications/blob/master/source/index-management.rst. -* NODE-408 Expose GridStore.currentChunk.chunkNumber. - -2.0.25 2015-03-26 ------------------ -* Upgraded mongodb-core to 1.1.21, making the C++ bson code an optional dependency to the bson module. - -2.0.24 2015-03-24 ------------------ -* NODE-395 Socket Not Closing, db.close called before full set finished initalizing leading to server connections in progress not being closed properly. -* Upgraded mongodb-core to 1.1.20. - -2.0.23 2015-03-21 ------------------ -* NODE-380 Correctly return MongoError from toError method. -* Fixed issue where addCursorFlag was not correctly setting the flag on the command for mongodb-core. -* NODE-388 Changed length from method to property on order.js/unordered.js bulk operations. -* Upgraded mongodb-core to 1.1.19. - -2.0.22 2015-03-16 ------------------ -* NODE-377, fixed issue where tags would correctly be checked on secondary and nearest to filter out eligible server candidates. -* Upgraded mongodb-core to 1.1.17. - -2.0.21 2015-03-06 ------------------ -* Upgraded mongodb-core to 1.1.16 making sslValidate default to true to force validation on connection unless overriden by the user. - -2.0.20 2015-03-04 ------------------ -* Updated mongodb-core 1.1.15 to relax pickserver method. - -2.0.19 2015-03-03 ------------------ -* NODE-376 Fixes issue * Unordered batch incorrectly tracks batch size when switching batch types (Issue #1261, https://github.com/meirgottlieb) -* NODE-379 Fixes bug in cursor.count() that causes the result to always be zero for dotted collection names (Issue #1262, https://github.com/vsivsi) -* Expose MongoError from mongodb-core (Issue #1260, https://github.com/tjconcept) - -2.0.18 2015-02-27 ------------------ -* Bumped mongodb-core 1.1.14 to ensure passives are correctly added as secondaries. - -2.0.17 2015-02-27 ------------------ -* NODE-336 Added length function to ordered and unordered bulk operations to be able know the amount of current operations in bulk. -* Bumped mongodb-core 1.1.13 to ensure passives are correctly added as secondaries. - -2.0.16 2015-02-16 ------------------ -* listCollection now returns filtered result correctly removing db name for 2.6 or earlier servers. -* Bumped mongodb-core 1.1.12 to correctly work for node 0.12.0 and io.js. -* Add ability to get collection name from cursor (Issue #1253, https://github.com/vkarpov15) - -2.0.15 2015-02-02 ------------------ -* Unified behavior of listCollections results so 3.0 and pre 3.0 return same type of results. -* Bumped mongodb-core to 1.1.11 to support per document tranforms in cursors as well as relaxing the setName requirement. -* NODE-360 Aggregation cursor and command correctly passing down the maxTimeMS property. -* Added ~1.0 mongodb-tools module for test running. -* Remove the required setName for replicaset connections, if not set it will pick the first setName returned. - -2.0.14 2015-01-21 ------------------ -* Fixed some MongoClient.connect options pass through issues and added test coverage. -* Bumped mongodb-core to 1.1.9 including fixes for io.js - -2.0.13 2015-01-09 ------------------ -* Bumped mongodb-core to 1.1.8. -* Optimized query path for performance, moving Object.defineProperty outside of constructors. - -2.0.12 2014-12-22 ------------------ -* Minor fixes to listCollections to ensure correct querying of a collection when using a string. - -2.0.11 2014-12-19 ------------------ -* listCollections filters out index namespaces on < 2.8 correctly -* Bumped mongo-client to 1.1.7 - -2.0.10 2014-12-18 ------------------ -* NODE-328 fixed db.open return when no callback available issue and added test. -* NODE-327 Refactored listCollections to return cursor to support 2.8. -* NODE-327 Added listIndexes method and refactored internal methods to use the new command helper. -* NODE-335 Cannot create index for nested objects fixed by relaxing key checking for createIndex helper. -* Enable setting of connectTimeoutMS (Issue #1235, https://github.com/vkarpov15) -* Bumped mongo-client to 1.1.6 - -2.0.9 2014-12-01 ----------------- -* Bumped mongodb-core to 1.1.3 fixing global leaked variables and introducing strict across all classes. -* All classes are now strict (Issue #1233) -* NODE-324 Refactored insert/update/remove and all other crud opts to rely on internal methods to avoid any recursion. -* Fixed recursion issues in debug logging due to JSON.stringify() -* Documentation fixes (Issue #1232, https://github.com/wsmoak) -* Fix writeConcern in Db.prototype.ensureIndex (Issue #1231, https://github.com/Qard) - -2.0.8 2014-11-28 ----------------- -* NODE-322 Finished up prototype refactoring of Db class. -* NODE-322 Exposed Cursor in index.js for New Relic. - -2.0.7 2014-11-20 ----------------- -* Bumped mongodb-core to 1.1.2 fixing a UTF8 encoding issue for collection names. -* NODE-318 collection.update error while setting a function with serializeFunctions option. -* Documentation fixes. - -2.0.6 2014-11-14 ----------------- -* Refactored code to be prototype based instead of privileged methods. -* Bumped mongodb-core to 1.1.1 to take advantage of the prototype based refactorings. -* Implemented missing aspects of the CRUD specification. -* Fixed documentation issues. -* Fixed global leak REFERENCE_BY_ID in gridfs grid_store (Issue #1225, https://github.com/j) -* Fix LearnBoost/mongoose#2313: don't let user accidentally clobber geoNear params (Issue #1223, https://github.com/vkarpov15) - -2.0.5 2014-10-29 ----------------- -* Minor fixes to documentation and generation of documentation. -* NODE-306 (No results in aggregation cursor when collection name contains a dot), Merged code for cursor and aggregation cursor. - -2.0.4 2014-10-23 ----------------- -* Allow for single replicaset seed list with no setName specified (Issue #1220, https://github.com/imaman) -* Made each rewind on each call allowing for re-using the cursor. -* Fixed issue where incorrect iterations would happen on each for extensive batchSizes. -* NODE-301 specifying maxTimeMS on find causes all fields to be omitted from result. - -2.0.3 2014-10-14 ----------------- -* NODE-297 Aggregate Broken for case of pipeline with no options. - -2.0.2 2014-10-08 ----------------- -* Bumped mongodb-core to 1.0.2. -* Fixed bson module dependency issue by relying on the mongodb-core one. -* Use findOne instead of find followed by nextObject (Issue #1216, https://github.com/sergeyksv) - -2.0.1 2014-10-07 ----------------- -* Dependency fix - -2.0.0 2014-10-07 ----------------- -* First release of 2.0 driver - -2.0.0-alpha2 2014-10-02 ------------------------ -* CRUD API (insertOne, insertMany, updateOne, updateMany, removeOne, removeMany, bulkWrite, findOneAndDelete, findOneAndUpdate, findOneAndReplace) -* Cluster Management Spec compatible. - -2.0.0-alpha1 2014-09-08 ------------------------ -* Insert method allows only up 1000 pr batch for legacy as well as 2.6 mode -* Streaming behavior is 0.10.x or higher with backwards compatibility using readable-stream npm package -* Gridfs stream only available through .stream() method due to overlapping names on Gridstore object and streams in 0.10.x and higher of node -* remove third result on update and remove and return the whole result document instead (getting rid of the weird 3 result parameters) - * Might break some application -* Returns the actual mongodb-core result instead of just the number of records changed for insert/update/remove -* MongoClient only has the connect method (no ability instantiate with Server, ReplSet or similar) -* Removed Grid class -* GridStore only supports w+ for metadata updates, no appending to file as it's not thread safe and can cause corruption of the data - + seek will fail if attempt to use with w or w+ - + write will fail if attempted with w+ or r - + w+ only works for updating metadata on a file -* Cursor toArray and each resets and re-runs the cursor -* FindAndModify returns whole result document instead of just value -* Extend cursor to allow for setting all the options via methods instead of dealing with the current messed up find -* Removed db.dereference method -* Removed db.cursorInfo method -* Removed db.stats method -* Removed db.collectionNames not needed anymore as it's just a specialized case of listCollections -* Removed db.collectionInfo removed due to not being compatible with new storage engines in 2.8 as they need to use the listCollections command due to system collections not working for namespaces. -* Added db.listCollections to replace several methods above - -1.4.10 2014-09-04 ------------------ -* Fixed BSON and Kerberos compilation issues -* Bumped BSON to ~0.2 always installing latest BSON 0.2.x series -* Fixed Kerberos and bumped to 0.0.4 - -1.4.9 2014-08-26 ----------------- -* Check _bsonType for Binary (Issue #1202, https://github.com/mchapman) -* Remove duplicate Cursor constructor (Issue #1201, https://github.com/KenPowers) -* Added missing parameter in the documentation (Issue #1199, https://github.com/wpjunior) -* Documented third parameter on the update callback(Issue #1196, https://github.com/gabmontes) -* NODE-240 Operations on SSL connection hang on node 0.11.x -* NODE-235 writeResult is not being passed on when error occurs in insert -* NODE-229 Allow count to work with query hints -* NODE-233 collection.save() does not support fullResult -* NODE-244 Should parseError also emit a `disconnected` event? -* NODE-246 Cursors are inefficiently constructed and consequently cannot be promisified. -* NODE-248 Crash with X509 auth -* NODE-252 Uncaught Exception in Base.__executeAllServerSpecificErrorCallbacks -* Bumped BSON parser to 0.2.12 - - -1.4.8 2014-08-01 ----------------- -* NODE-205 correctly emit authenticate event -* NODE-210 ensure no undefined connection error when checking server state -* NODE-212 correctly inherit socketTimeoutMS from replicaset when HA process adds new servers or reconnects to existing ones -* NODE-220 don't throw error if ensureIndex errors out in Gridstore -* Updated bson to 0.2.11 to ensure correct toBSON behavior when returning non object in nested classes -* Fixed test running filters -* Wrap debug log in a call to format (Issue #1187, https://github.com/andyroyle) -* False option values should not trigger w:1 (Issue #1186, https://github.com/jsdevel) -* Fix aggregatestream.close(Issue #1194, https://github.com/jonathanong) -* Fixed parsing issue for w:0 in url parser when in connection string -* Modified collection.geoNear to support a geoJSON point or legacy coordinate pair (Issue #1198, https://github.com/mmacmillan) - -1.4.7 2014-06-18 ----------------- -* Make callbacks to be executed in right domain when server comes back up (Issue #1184, https://github.com/anton-kotenko) -* Fix issue where currentOp query against mongos would fail due to mongos passing through $readPreference field to mongod (CS-X) - -1.4.6 2014-06-12 ----------------- -* Added better support for MongoClient IP6 parsing (Issue #1181, https://github.com/micovery) -* Remove options check on index creation (Issue #1179, Issue #1183, https://github.com/jdesboeufs, https://github.com/rubenvereecken) -* Added missing type check before calling optional callback function (Issue #1180) - -1.4.5 2014-05-21 ----------------- -* Added fullResult flag to insert/update/remove which will pass raw result document back. Document contents will vary depending on the server version the driver is talking to. No attempt is made to coerce a joint response. -* Fix to avoid MongoClient.connect hanging during auth when secondaries building indexes pre 2.6. -* return the destination stream in GridStore.pipe (Issue #1176, https://github.com/iamdoron) - -1.4.4 2014-05-13 ----------------- -* Bumped BSON version to use the NaN 1.0 package, fixed strict comparison issue for ObjectID -* Removed leaking global variable (Issue #1174, https://github.com/dainis) -* MongoClient respects connectTimeoutMS for initial discovery process (NODE-185) -* Fix bug with return messages larger than 16MB but smaller than max BSON Message Size (NODE-184) - -1.4.3 2014-05-01 ----------------- -* Clone options for commands to avoid polluting original options passed from Mongoose (Issue #1171, https://github.com/vkarpov15) -* Made geoNear and geoHaystackSearch only clean out allowed options from command generation (Issue #1167) -* Fixed typo for allowDiskUse (Issue #1168, https://github.com/joaofranca) -* A 'mapReduce' function changed 'function' to instance '\' of 'Code' class (Issue #1165, https://github.com/exabugs) -* Made findAndModify set sort only when explicitly set (Issue #1163, https://github.com/sars) -* Rewriting a gridStore file by id should use a new filename if provided (Issue #1169, https://github.com/vsivsi) - -1.4.2 2014-04-15 ----------------- -* Fix for inheritance of readPreferences from MongoClient NODE-168/NODE-169 -* Merged in fix for ping strategy to avoid hitting non-pinged servers (Issue #1161, https://github.com/vaseker) -* Merged in fix for correct debug output for connection messages (Issue #1158, https://github.com/vaseker) -* Fixed global variable leak (Issue #1160, https://github.com/vaseker) - -1.4.1 2014-04-09 ----------------- -* Correctly emit joined event when primary change -* Add _id to documents correctly when using bulk operations - -1.4.0 2014-04-03 ----------------- -* All node exceptions will no longer be caught if on('error') is defined -* Added X509 auth support -* Fix for MongoClient connection timeout issue (NODE-97) -* Pass through error messages from parseError instead of just text (Issue #1125) -* Close db connection on error (Issue #1128, https://github.com/benighted) -* Fixed documentation generation -* Added aggregation cursor for 2.6 and emulated cursor for pre 2.6 (uses stream2) -* New Bulk API implementation using write commands for 2.6 and down converts for pre 2.6 -* Insert/Update/Remove using new write commands when available -* Added support for new roles based API's in 2.6 for addUser/removeUser -* Added bufferMaxEntries to start failing if the buffer hits the specified number of entries -* Upgraded BSON parser to version 0.2.7 to work with < 0.11.10 C++ API changes -* Support for OP_LOG_REPLAY flag (NODE-94) -* Fixes for SSL HA ping and discovery. -* Uses createIndexes if available for ensureIndex/createIndex -* Added parallelCollectionScan method to collection returning CommandCursor instances for cursors -* Made CommandCursor behave as Readable stream. -* Only Db honors readPreference settings, removed Server.js legacy readPreference settings due to user confusion. -* Reconnect event emitted by ReplSet/Mongos/Server after reconnect and before replaying of buffered operations. -* GridFS buildMongoObject returns error on illegal md5 (NODE-157, https://github.com/iantocristian) -* Default GridFS chunk size changed to (255 * 1024) bytes to optimize for collections defaulting to power of 2 sizes on 2.6. -* Refactored commands to all go through command function ensuring consistent command execution. -* Fixed issues where readPreferences where not correctly passed to mongos. -* Catch error == null and make err detection more prominent (NODE-130) -* Allow reads from arbiter for single server connection (NODE-117) -* Handle error coming back with no documents (NODE-130) -* Correctly use close parameter in Gridstore.write() (NODE-125) -* Throw an error on a bulk find with no selector (NODE-129, https://github.com/vkarpov15) -* Use a shallow copy of options in find() (NODE-124, https://github.com/vkarpov15) -* Fix statistical strategy (NODE-158, https://github.com/vkarpov15) -* GridFS off-by-one bug in lastChunkNumber() causes uncaught throw and data loss (Issue #1154, https://github.com/vsivsi) -* GridStore drops passed `aliases` option, always results in `null` value in GridFS files (Issue #1152, https://github.com/vsivsi) -* Remove superfluous connect object copying in index.js (Issue #1145, https://github.com/thomseddon) -* Do not return false when the connection buffer is still empty (Issue #1143, https://github.com/eknkc) -* Check ReadPreference object on ReplSet.canRead (Issue #1142, https://github.com/eknkc) -* Fix unpack error on _executeQueryCommand (Issue #1141, https://github.com/eknkc) -* Close db on failed connect so node can exit (Issue #1128, https://github.com/benighted) -* Fix global leak with _write_concern (Issue #1126, https://github.com/shanejonas) - -1.3.19 2013-08-21 ------------------ -* Correctly rethrowing errors after change from event emission to callbacks, compatibility with 0.10.X domains without breaking 0.8.X support. -* Small fix to return the entire findAndModify result as the third parameter (Issue #1068) -* No removal of "close" event handlers on server reconnect, emits "reconnect" event when reconnection happens. Reconnect Only applies for single server connections as of now as semantics for ReplSet and Mongos is not clear (Issue #1056) - -1.3.18 2013-08-10 ------------------ -* Fixed issue when throwing exceptions in MongoClient.connect/Db.open (Issue #1057) -* Fixed an issue where _events is not cleaned up correctly causing a slow steady memory leak. - -1.3.17 2013-08-07 ------------------ -* Ignore return commands that have no registered callback -* Made collection.count not use the db.command function -* Fix throw exception on ping command (Issue #1055) - -1.3.16 2013-08-02 ------------------ -* Fixes connection issue where lots of connections would happen if a server is in recovery mode during connection (Issue #1050, NODE-50, NODE-51) -* Bug in unlink mulit filename (Issue #1054) - -1.3.15 2013-08-01 ------------------ -* Memory leak issue due to node Issue #4390 where _events[id] is set to undefined instead of deleted leading to leaks in the Event Emitter over time - -1.3.14 2013-08-01 ------------------ -* Fixed issue with checkKeys where it would error on X.X - -1.3.13 2013-07-31 ------------------ -* Added override for checkKeys on insert/update (Warning will expose you to injection attacks) (Issue #1046) -* BSON size checking now done pre serialization (Issue #1037) -* Added isConnected returns false when no connection Pool exists (Issue #1043) -* Unified command handling to ensure same handling (Issue #1041, #1042) -* Correctly emit "open" and "fullsetup" across all Db's associated with Mongos, ReplSet or Server (Issue #1040) -* Correctly handles bug in authentication when attempting to connect to a recovering node in a replicaset. -* Correctly remove recovering servers from available servers in replicaset. Piggybacks on the ping command. -* Removed findAndModify chaining to be compliant with behavior in other official drivers and to fix a known mongos issue. -* Fixed issue with Kerberos authentication on Windows for re-authentication. -* Fixed Mongos failover behavior to correctly throw out old servers. -* Ensure stored queries/write ops are executed correctly after connection timeout -* Added promoteLongs option for to allow for overriding the promotion of Longs to Numbers and return the actual Long. - -1.3.12 2013-07-19 ------------------ -* Fixed issue where timeouts sometimes would behave wrongly (Issue #1032) -* Fixed bug with callback third parameter on some commands (Issue #1033) -* Fixed possible issue where killcursor command might leave hanging functions -* Fixed issue where Mongos was not correctly removing dead servers from the pool of eligable servers -* Throw error if dbName or collection name contains null character (at command level and at collection level) -* Updated bson parser to 0.2.1 with security fix and non-promotion of Long values to javascript Numbers (once a long always a long) - -1.3.11 2013-07-04 ------------------ -* Fixed errors on geoNear and geoSearch (Issue #1024, https://github.com/ebensing) -* Add driver version to export (Issue #1021, https://github.com/aheckmann) -* Add text to readpreference obedient commands (Issue #1019) -* Drivers should check the query failure bit even on getmore response (Issue #1018) -* Map reduce has incorrect expectations of 'inline' value for 'out' option (Issue #1016, https://github.com/rcotter) -* Support SASL PLAIN authentication (Issue #1009) -* Ability to use different Service Name on the driver for Kerberos Authentication (Issue #1008) -* Remove unnecessary octal literal to allow the code to run in strict mode (Issue #1005, https://github.com/jamesallardice) -* Proper handling of recovering nodes (when they go into recovery and when they return from recovery, Issue #1027) - -1.3.10 2013-06-17 ------------------ -* Guard against possible undefined in server::canCheckoutWriter (Issue #992, https://github.com/willyaranda) -* Fixed some duplicate test names (Issue #993, https://github.com/kawanet) -* Introduced write and read concerns for GridFS (Issue #996) -* Fixed commands not correctly respecting Collection level read preference (Issue #995, #999) -* Fixed issue with pool size on replicaset connections (Issue #1000) -* Execute all query commands on master switch (Issue #1002, https://github.com/fogaztuc) - -1.3.9 2013-06-05 ----------------- -* Fixed memory leak when findAndModify errors out on w>1 and chained callbacks not properly cleaned up. - -1.3.8 2013-05-31 ----------------- -* Fixed issue with socket death on windows where it emits error event instead of close event (Issue #987) -* Emit authenticate event on db after authenticate method has finished on db instance (Issue #984) -* Allows creation of MongoClient and do new MongoClient().connect(..). Emits open event when connection correct allowing for apps to react on event. - -1.3.7 2013-05-29 ----------------- -* After reconnect, tailable getMores go on inconsistent connections (Issue #981, #982, https://github.com/glasser) -* Updated Bson to 0.1.9 to fix ARM support (Issue #985) - -1.3.6 2013-05-21 ----------------- -* Fixed issue where single server reconnect attempt would throw due to missing options variable (Issue #979) -* Fixed issue where difference in ismaster server name and seed list caused connections issues, (Issue #976) - -1.3.5 2013-05-14 ----------------- -* Fixed issue where HA for replicaset would pick the same broken connection when attempting to ping the replicaset causing the replicaset to never recover. - -1.3.4 2013-05-14 ----------------- -* Fixed bug where options not correctly passed in for uri parser (Issue #973, https://github.com/supershabam) -* Fixed bug when passing a named index hint (Issue #974) - -1.3.3 2013-05-09 ----------------- -* Fixed auto-reconnect issue with single server instance. - -1.3.2 2013-05-08 ----------------- -* Fixes for an issue where replicaset would be pronounced dead when high priority primary caused double elections. - -1.3.1 2013-05-06 ----------------- -* Fix for replicaset consisting of primary/secondary/arbiter with priority applied failing to reconnect properly -* Applied auth before server instance is set as connected when single server connection -* Throw error if array of documents passed to save method - -1.3.0 2013-04-25 ----------------- -* Whole High availability handling for Replicaset, Server and Mongos connections refactored to ensure better handling of failover cases. -* Fixed issue where findAndModify would not correctly skip issuing of chained getLastError (Issue #941) -* Fixed throw error issue on errors with findAndModify during write out operation (Issue #939, https://github.com/autopulated) -* Gridstore.prototype.writeFile now returns gridstore object correctly (Issue #938) -* Kerberos support is now an optional module that allows for use of GSSAPI authentication using MongoDB Subscriber edition -* Fixed issue where cursor.toArray could blow the stack on node 0.10.X (#950) - -1.2.14 2013-03-14 ------------------ -* Refactored test suite to speed up running of replicaset tests -* Fix of async error handling when error happens in callback (Issue #909, https://github.com/medikoo) -* Corrected a slaveOk setting issue (Issue #906, #905) -* Fixed HA issue where ping's would not go to correct server on HA server connection failure. -* Uses setImmediate if on 0.10 otherwise nextTick for cursor stream -* Fixed race condition in Cursor stream (NODE-31) -* Fixed issues related to node 0.10 and process.nextTick now correctly using setImmediate where needed on node 0.10 -* Added support for maxMessageSizeBytes if available (DRIVERS-1) -* Added support for authSource (2.4) to MongoClient URL and db.authenticate method (DRIVER-69/NODE-34) -* Fixed issue in GridStore seek and GridStore read to correctly work on multiple seeks (Issue #895) - -1.2.13 2013-02-22 ------------------ -* Allow strategy 'none' for repliaset if no strategy wanted (will default to round robin selection of servers on a set readPreference) -* Fixed missing MongoErrors on some cursor methods (Issue #882) -* Correctly returning a null for the db instance on MongoClient.connect when auth fails (Issue #890) -* Added dropTarget option support for renameCollection/rename (Issue #891, help from https://github.com/jbottigliero) -* Fixed issue where connection using MongoClient.connect would fail if first server did not exist (Issue #885) - -1.2.12 2013-02-13 ------------------ -* Added limit/skip options to Collection.count (Issue #870) -* Added applySkipLimit option to Cursor.count (Issue #870) -* Enabled ping strategy as default for Replicaset if none specified (Issue #876) -* Should correctly pick nearest server for SECONDARY/SECONDARY_PREFERRED/NEAREST (Issue #878) - -1.2.11 2013-01-29 ------------------ -* Added fixes for handling type 2 binary due to PHP driver (Issue #864) -* Moved callBackStore to Base class to have single unified store (Issue #866) -* Ping strategy now reuses sockets unless they are closed by the server to avoid overhead - -1.2.10 2013-01-25 ------------------ -* Merged in SSL support for 2.4 supporting certificate validation and presenting certificates to the server. -* Only open a new HA socket when previous one dead (Issue #859, #857) -* Minor fixes - -1.2.9 2013-01-15 ----------------- -* Fixed bug in SSL support for MongoClient/Db.connect when discovering servers (Issue #849) -* Connection string with no db specified should default to admin db (Issue #848) -* Support port passed as string to Server class (Issue #844) -* Removed noOpen support for MongoClient/Db.connect as auto discovery of servers for Mongod/Mongos makes it not possible (Issue #842) -* Included toError wrapper code moved to utils.js file (Issue #839, #840) -* Rewrote cursor handling to avoid process.nextTick using trampoline instead to avoid stack overflow, speedup about 40% - -1.2.8 2013-01-07 ----------------- -* Accept function in a Map Reduce scope object not only a function string (Issue #826, https://github.com/aheckmann) -* Typo in db.authenticate caused a check (for provided connection) to return false, causing a connection AND onAll=true to be passed into __executeQueryCommand downstream (Issue #831, https://github.com/m4tty) -* Allow gridfs objects to use non ObjectID ids (Issue #825, https://github.com/nailgun) -* Removed the double wrap, by not passing an Error object to the wrap function (Issue #832, https://github.com/m4tty) -* Fix connection leak (gh-827) for HA replicaset health checks (Issue #833, https://github.com/aheckmann) -* Modified findOne to use nextObject instead of toArray avoiding a nextTick operation (Issue #836) -* Fixes for cursor stream to avoid multiple getmore issues when one in progress (Issue #818) -* Fixes .open replaying all backed up commands correctly if called after operations performed, (Issue #829 and #823) - -1.2.7 2012-12-23 ----------------- -* Rolled back batches as they hang in certain situations -* Fixes for NODE-25, keep reading from secondaries when primary goes down - -1.2.6 2012-12-21 ----------------- -* domain sockets shouldn't require a port arg (Issue #815, https://github.com/aheckmann) -* Cannot read property 'info' of null (Issue #809, https://github.com/thesmart) -* Cursor.each should work in batches (Issue #804, https://github.com/Swatinem) -* Cursor readPreference bug for non-supported read preferences (Issue #817) - -1.2.5 2012-12-12 ----------------- -* Fixed ssl regression, added more test coverage (Issue #800) -* Added better error reporting to the Db.connect if no valid serverConfig setup found (Issue #798) - -1.2.4 2012-12-11 ----------------- -* Fix to ensure authentication is correctly applied across all secondaries when using MongoClient. - -1.2.3 2012-12-10 ----------------- -* Fix for new replicaset members correctly authenticating when being added (Issue #791, https://github.com/m4tty) -* Fixed seek issue in gridstore when using stream (Issue #790) - -1.2.2 2012-12-03 ----------------- -* Fix for journal write concern not correctly being passed under some circumstances. -* Fixed correct behavior and re-auth for servers that get stepped down (Issue #779). - -1.2.1 2012-11-30 ----------------- -* Fix for double callback on insert with w:0 specified (Issue #783) -* Small cleanup of urlparser. - -1.2.0 2012-11-27 ----------------- -* Honor connectTimeoutMS option for replicasets (Issue #750, https://github.com/aheckmann) -* Fix ping strategy regression (Issue #738, https://github.com/aheckmann) -* Small cleanup of code (Issue #753, https://github.com/sokra/node-mongodb-native) -* Fixed index declaration using objects/arrays from other contexts (Issue #755, https://github.com/sokra/node-mongodb-native) -* Intermittent (and rare) null callback exception when using ReplicaSets (Issue #752) -* Force correct setting of read_secondary based on the read preference (Issue #741) -* If using read preferences with secondaries queries will not fail if primary is down (Issue #744) -* noOpen connection for Db.connect removed as not compatible with autodetection of Mongo type -* Mongos connection with auth not working (Issue #737) -* Use the connect method directly from the require. require('mongodb')("mongodb://localhost:27017/db") -* new MongoClient introduced as the point of connecting to MongoDB's instead of the Db - * open/close/db/connect methods implemented -* Implemented common URL connection format using MongoClient.connect allowing for simialar interface across all drivers. -* Fixed a bug with aggregation helper not properly accepting readPreference - -1.1.11 2012-10-10 ------------------ -* Removed strict mode and introduced normal handling of safe at DB level. - -1.1.10 2012-10-08 ------------------ -* fix Admin.serverStatus (Issue #723, https://github.com/Contra) -* logging on connection open/close(Issue #721, https://github.com/asiletto) -* more fixes for windows bson install (Issue #724) - -1.1.9 2012-10-05 ----------------- -* Updated bson to 0.1.5 to fix build problem on sunos/windows. - -1.1.8 2012-10-01 ----------------- -* Fixed db.eval to correctly handle system.js global javascript functions (Issue #709) -* Cleanup of non-closing connections (Issue #706) -* More cleanup of connections under replicaset (Issue #707, https://github.com/elbert3) -* Set keepalive on as default, override if not needed -* Cleanup of jsbon install to correctly build without install.js script (https://github.com/shtylman) -* Added domain socket support new Server("/tmp/mongodb.sock") style - -1.1.7 2012-09-10 ----------------- -* Protect against starting PingStrategy being called more than once (Issue #694, https://github.com/aheckmann) -* Make PingStrategy interval configurable (was 1 second, relaxed to 5) (Issue #693, https://github.com/aheckmann) -* Made PingStrategy api more consistant, callback to start/stop methods are optional (Issue #693, https://github.com/aheckmann) -* Proper stopping of strategy on replicaset stop -* Throw error when gridstore file is not found in read mode (Issue #702, https://github.com/jbrumwell) -* Cursor stream resume now using nextTick to avoid duplicated records (Issue #696) - -1.1.6 2012-09-01 ----------------- -* Fix for readPreference NEAREST for replicasets (Issue #693, https://github.com/aheckmann) -* Emit end correctly on stream cursor (Issue #692, https://github.com/Raynos) - -1.1.5 2012-08-29 ----------------- -* Fix for eval on replicaset Issue #684 -* Use helpful error msg when native parser not compiled (Issue #685, https://github.com/aheckmann) -* Arbiter connect hotfix (Issue #681, https://github.com/fengmk2) -* Upgraded bson parser to 0.1.2 using gyp, deprecated support for node 0.4.X -* Added name parameter to createIndex/ensureIndex to be able to override index names larger than 128 bytes -* Added exhaust option for find for feature completion (not recommended for normal use) -* Added tailableRetryInterval to find for tailable cursors to allow to control getMore retry time interval -* Fixes for read preferences when using MongoS to correctly handle no read preference set when iterating over a cursor (Issue #686) - -1.1.4 2012-08-12 ----------------- -* Added Mongos connection type with a fallback list for mongos proxies, supports ha (on by default) and will attempt to reconnect to failed proxies. -* Documents can now have a toBSON method that lets the user control the serialization behavior for documents being saved. -* Gridstore instance object now works as a readstream or writestream (thanks to code from Aaron heckmann (https://github.com/aheckmann/gridfs-stream)). -* Fix gridfs readstream (Issue #607, https://github.com/tedeh). -* Added disableDriverBSONSizeCheck property to Server.js for people who wish to push the inserts to the limit (Issue #609). -* Fixed bug where collection.group keyf given as Code is processed as a regular object (Issue #608, https://github.com/rrusso2007). -* Case mismatch between driver's ObjectID and mongo's ObjectId, allow both (Issue #618). -* Cleanup map reduce (Issue #614, https://github.com/aheckmann). -* Add proper error handling to gridfs (Issue #615, https://github.com/aheckmann). -* Ensure cursor is using same connection for all operations to avoid potential jump of servers when using replicasets. -* Date identification handled correctly in bson js parser when running in vm context. -* Documentation updates -* GridStore filename not set on read (Issue #621) -* Optimizations on the C++ bson parser to fix a potential memory leak and avoid non-needed calls -* Added support for awaitdata for tailable cursors (Issue #624) -* Implementing read preference setting at collection and cursor level - * collection.find().setReadPreference(Server.SECONDARY_PREFERRED) - * db.collection("some", {readPreference:Server.SECONDARY}) -* Replicaset now returns when the master is discovered on db.open and lets the rest of the connections happen asynchronous. - * ReplSet/ReplSetServers emits "fullsetup" when all servers have been connected to -* Prevent callback from executing more than once in getMore function (Issue #631, https://github.com/shankar0306) -* Corrupt bson messages now errors out to all callbacks and closes up connections correctly, Issue #634 -* Replica set member status update when primary changes bug (Issue #635, https://github.com/alinsilvian) -* Fixed auth to work better when multiple connections are involved. -* Default connection pool size increased to 5 connections. -* Fixes for the ReadStream class to work properly with 0.8 of Node.js -* Added explain function support to aggregation helper -* Added socketTimeoutMS and connectTimeoutMS to socket options for repl_set.js and server.js -* Fixed addUser to correctly handle changes in 2.2 for getLastError authentication required -* Added index to gridstore chunks on file_id (Issue #649, https://github.com/jacobbubu) -* Fixed Always emit db events (Issue #657) -* Close event not correctly resets DB openCalled variable to allow reconnect -* Added open event on connection established for replicaset, mongos and server -* Much faster BSON C++ parser thanks to Lucasfilm Singapore. -* Refactoring of replicaset connection logic to simplify the code. -* Add `options.connectArbiter` to decide connect arbiters or not (Issue #675) -* Minor optimization for findAndModify when not using j,w or fsync for safe - -1.0.2 2012-05-15 ----------------- -* Reconnect functionality for replicaset fix for mongodb 2.0.5 - -1.0.1 2012-05-12 ----------------- -* Passing back getLastError object as 3rd parameter on findAndModify command. -* Fixed a bunch of performance regressions in objectId and cursor. -* Fixed issue #600 allowing for single document delete to be passed in remove command. - -1.0.0 2012-04-25 ----------------- -* Fixes to handling of failover on server error -* Only emits error messages if there are error listeners to avoid uncaught events -* Server.isConnected using the server state variable not the connection pool state - -0.9.9.8 2012-04-12 ------------------- -* _id=0 is being turned into an ObjectID (Issue #551) -* fix for error in GridStore write method (Issue #559) -* Fix for reading a GridStore from arbitrary, non-chunk aligned offsets, added test (Issue #563, https://github.com/subroutine) -* Modified limitRequest to allow negative limits to pass through to Mongo, added test (Issue #561) -* Corrupt GridFS files when chunkSize < fileSize, fixed concurrency issue (Issue #555) -* Handle dead tailable cursors (Issue #568, https://github.com/aheckmann) -* Connection pools handles closing themselves down and clearing the state -* Check bson size of documents against maxBsonSize and throw client error instead of server error, (Issue #553) -* Returning update status document at the end of the callback for updates, (Issue #569) -* Refactor use of Arguments object to gain performance (Issue #574, https://github.com/AaronAsAChimp) - -0.9.9.7 2012-03-16 ------------------- -* Stats not returned from map reduce with inline results (Issue #542) -* Re-enable testing of whether or not the callback is called in the multi-chunk seek, fix small GridStore bug (Issue #543, https://github.com/pgebheim) -* Streaming large files from GridFS causes truncation (Issue #540) -* Make callback type checks agnostic to V8 context boundaries (Issue #545) -* Correctly throw error if an attempt is made to execute an insert/update/remove/createIndex/ensureIndex with safe enabled and no callback -* Db.open throws if the application attemps to call open again without calling close first - -0.9.9.6 2012-03-12 ------------------- -* BSON parser is externalized in it's own repository, currently using git master -* Fixes for Replicaset connectivity issue (Issue #537) -* Fixed issues with node 0.4.X vs 0.6.X (Issue #534) -* Removed SimpleEmitter and replaced with standard EventEmitter -* GridStore.seek fails to change chunks and call callback when in read mode (Issue #532) - -0.9.9.5 2012-03-07 ------------------- -* Merged in replSetGetStatus helper to admin class (Issue #515, https://github.com/mojodna) -* Merged in serverStatus helper to admin class (Issue #516, https://github.com/mojodna) -* Fixed memory leak in C++ bson parser (Issue #526) -* Fix empty MongoError "message" property (Issue #530, https://github.com/aheckmann) -* Cannot save files with the same file name to GridFS (Issue #531) - -0.9.9.4 2012-02-26 ------------------- -* bugfix for findAndModify: Error: corrupt bson message < 5 bytes long (Issue #519) - -0.9.9.3 2012-02-23 ------------------- -* document: save callback arguments are both undefined, (Issue #518) -* Native BSON parser install error with npm, (Issue #517) - -0.9.9.2 2012-02-17 ------------------- -* Improved detection of Buffers using Buffer.isBuffer instead of instanceof. -* Added wrap error around db.dropDatabase to catch all errors (Issue #512) -* Added aggregate helper to collection, only for MongoDB >= 2.1 - -0.9.9.1 2012-02-15 ------------------- -* Better handling of safe when using some commands such as createIndex, ensureIndex, addUser, removeUser, createCollection. -* Mapreduce now throws error if out parameter is not specified. - -0.9.9 2012-02-13 ----------------- -* Added createFromTime method on ObjectID to allow for queries against _id more easily using the timestamp. -* Db.close(true) now makes connection unusable as it's been force closed by app. -* Fixed mapReduce and group functions to correctly send slaveOk on queries. -* Fixes for find method to correctly work with find(query, fields, callback) (Issue #506). -* A fix for connection error handling when using the SSL on MongoDB. - -0.9.8-7 2012-02-06 ------------------- -* Simplified findOne to use the find command instead of the custom code (Issue #498). -* BSON JS parser not also checks for _bsonType variable in case BSON object is in weird scope (Issue #495). - -0.9.8-6 2012-02-04 ------------------- -* Removed the check for replicaset change code as it will never work with node.js. - -0.9.8-5 2012-02-02 ------------------- -* Added geoNear command to Collection. -* Added geoHaystackSearch command to Collection. -* Added indexes command to collection to retrieve the indexes on a Collection. -* Added stats command to collection to retrieve the statistics on a Collection. -* Added listDatabases command to admin object to allow retrieval of all available dbs. -* Changed createCreateIndexCommand to work better with options. -* Fixed dereference method on Db class to correctly dereference Db reference objects. -* Moved connect object onto Db class(Db.connect) as well as keeping backward compatibility. -* Removed writeBuffer method from gridstore, write handles switching automatically now. -* Changed readBuffer to read on Gridstore, Gridstore now only supports Binary Buffers no Strings anymore. -* Moved Long class to bson directory. - -0.9.8-4 2012-01-28 ------------------- -* Added reIndex command to collection and db level. -* Added support for $returnKey, $maxScan, $min, $max, $showDiskLoc, $comment to cursor and find/findOne methods. -* Added dropDups and v option to createIndex and ensureIndex. -* Added isCapped method to Collection. -* Added indexExists method to Collection. -* Added findAndRemove method to Collection. -* Fixed bug for replicaset connection when no active servers in the set. -* Fixed bug for replicaset connections when errors occur during connection. -* Merged in patch for BSON Number handling from Lee Salzman, did some small fixes and added test coverage. - -0.9.8-3 2012-01-21 ------------------- -* Workaround for issue with Object.defineProperty (Issue #484) -* ObjectID generation with date does not set rest of fields to zero (Issue #482) - -0.9.8-2 2012-01-20 ------------------- -* Fixed a missing this in the ReplSetServers constructor. - -0.9.8-1 2012-01-17 ------------------- -* FindAndModify bug fix for duplicate errors (Issue #481) - -0.9.8 2012-01-17 ----------------- -* Replicasets now correctly adjusts to live changes in the replicaset configuration on the servers, reconnecting correctly. - * Set the interval for checking for changes setting the replicaSetCheckInterval property when creating the ReplSetServers instance or on db.serverConfig.replicaSetCheckInterval. (default 1000 miliseconds) -* Fixes formattedOrderClause in collection.js to accept a plain hash as a parameter (Issue #469) https://github.com/tedeh -* Removed duplicate code for formattedOrderClause and moved to utils module -* Pass in poolSize for ReplSetServers to set default poolSize for new replicaset members -* Bug fix for BSON JS deserializer. Isolating the eval functions in separate functions to avoid V8 deoptimizations -* Correct handling of illegal BSON messages during deserialization -* Fixed Infinite loop when reading GridFs file with no chunks (Issue #471) -* Correctly update existing user password when using addUser (Issue #470) - -0.9.7.3-5 2012-01-04 --------------------- -* Fix for RegExp serialization for 0.4.X where typeof /regexp/ == 'function' vs in 0.6.X typeof /regexp/ == 'object' -* Don't allow keepAlive and setNoDelay for 0.4.X as it throws errors - -0.9.7.3-4 2012-01-04 --------------------- -* Chased down potential memory leak on findAndModify, Issue #467 (node.js removeAllListeners leaves the key in the _events object, node.js bug on eventlistener?, leads to extremely slow memory leak on listener object) -* Sanity checks for GridFS performance with benchmark added - -0.9.7.3-3 2012-01-04 --------------------- -* Bug fixes for performance issues going form 0.9.6.X to 0.9.7.X on linux -* BSON bug fixes for performance - -0.9.7.3-2 2012-01-02 --------------------- -* Fixed up documentation to reflect the preferred way of instantiating bson types -* GC bug fix for JS bson parser to avoid stop-and-go GC collection - -0.9.7.3-1 2012-01-02 --------------------- -* Fix to make db.bson_serializer and db.bson_deserializer work as it did previously - -0.9.7.3 2011-12-30 --------------------- -* Moved BSON_BINARY_SUBTYPE_DEFAULT from BSON object to Binary object and removed the BSON_BINARY_ prefixes -* Removed Native BSON types, C++ parser uses JS types (faster due to cost of crossing the JS-C++ barrier for each call) -* Added build fix for 0.4.X branch of Node.js where GetOwnPropertyNames is not defined in v8 -* Fix for wire protocol parser for corner situation where the message is larger than the maximum socket buffer in node.js (Issue #464, #461, #447) -* Connection pool status set to connected on poolReady, isConnected returns false on anything but connected status (Issue #455) - -0.9.7.2-5 2011-12-22 --------------------- -* Brand spanking new Streaming Cursor support Issue #458 (https://github.com/christkv/node-mongodb-native/pull/458) thanks to Mr Aaron Heckmann - -0.9.7.2-4 2011-12-21 --------------------- -* Refactoring of callback code to work around performance regression on linux -* Fixed group function to correctly use the command mode as default - -0.9.7.2-3 2011-12-18 --------------------- -* Fixed error handling for findAndModify while still working for mongodb 1.8.6 (Issue #450). -* Allow for force send query to primary, pass option (read:'primary') on find command. - * ``find({a:1}, {read:'primary'}).toArray(function(err, items) {});`` - -0.9.7.2-2 2011-12-16 --------------------- -* Fixes infinite streamRecords QueryFailure fix when using Mongos (Issue #442) - -0.9.7.2-1 2011-12-16 --------------------- -* ~10% perf improvement for ObjectId#toHexString (Issue #448, https://github.com/aheckmann) -* Only using process.nextTick on errors emitted on callbacks not on all parsing, reduces number of ticks in the driver -* Changed parsing off bson messages to use process.nextTick to do bson parsing in batches if the message is over 10K as to yield more time to the event look increasing concurrency on big mongoreply messages with multiple documents - -0.9.7.2 2011-12-15 ------------------- -* Added SSL support for future version of mongodb (VERY VERY EXPERIMENTAL) - * pass in the ssl:true option to the server or replicaset server config to enable - * a bug either in mongodb or node.js does not allow for more than 1 connection pr db instance (poolSize:1). -* Added getTimestamp() method to objectID that returns a date object -* Added finalize function to collection.group - * function group (keys, condition, initial, reduce, finalize, command, callback) -* Reaper no longer using setTimeout to handle reaping. Triggering is done in the general flow leading to predictable behavior. - * reaperInterval, set interval for reaper (default 10000 miliseconds) - * reaperTimeout, set timeout for calls (default 30000 miliseconds) - * reaper, enable/disable reaper (default false) -* Work around for issues with findAndModify during high concurrency load, insure that the behavior is the same across the 1.8.X branch and 2.X branch of MongoDb -* Reworked multiple db's sharing same connection pool to behave correctly on error, timeout and close -* EnsureIndex command can be executed without a callback (Issue #438) -* Eval function no accepts options including nolock (Issue #432) - * eval(code, parameters, options, callback) (where options = {nolock:true}) - -0.9.7.1-4 2011-11-27 --------------------- -* Replaced install.sh with install.js to install correctly on all supported os's - -0.9.7.1-3 2011-11-27 --------------------- -* Fixes incorrect scope for ensureIndex error wrapping (Issue #419) https://github.com/ritch - -0.9.7.1-2 2011-11-27 --------------------- -* Set statistical selection strategy as default for secondary choice. - -0.9.7.1-1 2011-11-27 --------------------- -* Better handling of single server reconnect (fixes some bugs) -* Better test coverage of single server failure -* Correct handling of callbacks on replicaset servers when firewall dropping packets, correct reconnect - -0.9.7.1 2011-11-24 ------------------- -* Better handling of dead server for single server instances -* FindOne and find treats selector == null as {}, Issue #403 -* Possible to pass in a strategy for the replicaset to pick secondary reader node - * parameter strategy - * ping (default), pings the servers and picks the one with the lowest ping time - * statistical, measures each request and pick the one with the lowest mean and std deviation -* Set replicaset read preference replicaset.setReadPreference() - * Server.READ_PRIMARY (use primary server for reads) - * Server.READ_SECONDARY (from a secondary server (uses the strategy set)) - * tags, {object of tags} -* Added replay of commands issued to a closed connection when the connection is re-established -* Fix isConnected and close on unopened connections. Issue #409, fix by (https://github.com/sethml) -* Moved reaper to db.open instead of constructor (Issue #406) -* Allows passing through of socket connection settings to Server or ReplSetServer under the option socketOptions - * timeout = set seconds before connection times out (default 0) - * noDelay = Disables the Nagle algorithm (default true) - * keepAlive = Set if keepAlive is used (default 0, which means no keepAlive, set higher than 0 for keepAlive) - * encoding = ['ascii', 'utf8', or 'base64'] (default null) -* Fixes for handling of errors during shutdown off a socket connection -* Correctly applies socket options including timeout -* Cleanup of test management code to close connections correctly -* Handle parser errors better, closing down the connection and emitting an error -* Correctly emit errors from server.js only wrapping errors that are strings - -0.9.7 2011-11-10 ----------------- -* Added priority setting to replicaset manager -* Added correct handling of passive servers in replicaset -* Reworked socket code for simpler clearer handling -* Correct handling of connections in test helpers -* Added control of retries on failure - * control with parameters retryMiliSeconds and numberOfRetries when creating a db instance -* Added reaper that will timeout and cleanup queries that never return - * control with parameters reaperInterval and reaperTimeout when creating a db instance -* Refactored test helper classes for replicaset tests -* Allows raw (no bson parser mode for insert, update, remove, find and findOne) - * control raw mode passing in option raw:true on the commands - * will return buffers with the binary bson objects -* Fixed memory leak in cursor.toArray -* Fixed bug in command creation for mongodb server with wrong scope of call -* Added db(dbName) method to db.js to allow for reuse of connections against other databases -* Serialization of functions in an object is off by default, override with parameter - * serializeFunctions [true/false] on db level, collection level or individual insert/update/findAndModify -* Added Long.fromString to c++ class and fixed minor bug in the code (Test case for $gt operator on 64-bit integers, Issue #394) -* FindOne and find now share same code execution and will work in the same manner, Issue #399 -* Fix for tailable cursors, Issue #384 -* Fix for Cursor rewind broken, Issue #389 -* Allow Gridstore.exist to query using regexp, Issue #387, fix by (https://github.com/kaij) -* Updated documentation on https://github.com/christkv/node-mongodb-native -* Fixed toJSON methods across all objects for BSON, Binary return Base64 Encoded data - -0.9.6-22 2011-10-15 -------------------- -* Fixed bug in js bson parser that could cause wrong object size on serialization, Issue #370 -* Fixed bug in findAndModify that did not throw error on replicaset timeout, Issue #373 - -0.9.6-21 2011-10-05 -------------------- -* Reworked reconnect code to work correctly -* Handling errors in different parts of the code to ensure that it does not lock the connection -* Consistent error handling for Object.createFromHexString for JS and C++ - -0.9.6-20 2011-10-04 -------------------- -* Reworked bson.js parser to get rid off Array.shift() due to it allocating new memory for each call. Speedup varies between 5-15% depending on doc -* Reworked bson.cc to throw error when trying to serialize js bson types -* Added MinKey, MaxKey and Double support for JS and C++ parser -* Reworked socket handling code to emit errors on unparsable messages -* Added logger option for Db class, lets you pass in a function in the shape - { - log : function(message, object) {}, - error : function(errorMessage, errorObject) {}, - debug : function(debugMessage, object) {}, - } - - Usage is new Db(new Server(..), {logger: loggerInstance}) - -0.9.6-19 2011-09-29 -------------------- -* Fixing compatibility issues between C++ bson parser and js parser -* Added Symbol support to C++ parser -* Fixed socket handling bug for seldom misaligned message from mongodb -* Correctly handles serialization of functions using the C++ bson parser - -0.9.6-18 2011-09-22 -------------------- -* Fixed bug in waitForConnection that would lead to 100% cpu usage, Issue #352 - -0.9.6-17 2011-09-21 -------------------- -* Fixed broken exception test causing bamboo to hang -* Handling correctly command+lastError when both return results as in findAndModify, Issue #351 - -0.9.6-16 2011-09-14 -------------------- -* Fixing a bunch of issues with compatibility with MongoDB 2.0.X branch. Some fairly big changes in behavior from 1.8.X to 2.0.X on the server. -* Error Connection MongoDB V2.0.0 with Auth=true, Issue #348 - -0.9.6-15 2011-09-09 -------------------- -* Fixed issue where pools would not be correctly cleaned up after an error, Issue #345 -* Fixed authentication issue with secondary servers in Replicaset, Issue #334 -* Duplicate replica-set servers when omitting port, Issue #341 -* Fixing findAndModify to correctly work with Replicasets ensuring proper error handling, Issue #336 -* Merged in code from (https://github.com/aheckmann) that checks for global variable leaks - -0.9.6-14 2011-09-05 -------------------- -* Minor fixes for error handling in cursor streaming (https://github.com/sethml), Issue #332 -* Minor doc fixes -* Some more cursor sort tests added, Issue #333 -* Fixes to work with 0.5.X branch -* Fix Db not removing reconnect listener from serverConfig, (https://github.com/sbrekken), Issue #337 -* Removed node_events.h includes (https://github.com/jannehietamaki), Issue #339 -* Implement correct safe/strict mode for findAndModify. - -0.9.6-13 2011-08-24 -------------------- -* Db names correctly error checked for illegal characters - -0.9.6-12 2011-08-24 -------------------- -* Nasty bug in GridFS if you changed the default chunk size -* Fixed error handling bug in findOne - -0.9.6-11 2011-08-23 -------------------- -* Timeout option not correctly making it to the cursor, Issue #320, Fix from (https://github.com/year2013) -* Fixes for memory leaks when using buffers and C++ parser -* Fixes to make tests pass on 0.5.X -* Cleanup of bson.js to remove duplicated code paths -* Fix for errors occurring in ensureIndex, Issue #326 -* Removing require.paths to make tests work with the 0.5.X branch - -0.9.6-10 2011-08-11 -------------------- -* Specific type Double for capped collections (https://github.com/mbostock), Issue #312 -* Decorating Errors with all all object info from Mongo (https://github.com/laurie71), Issue #308 -* Implementing fixes for mongodb 1.9.1 and higher to make tests pass -* Admin validateCollection now takes an options argument for you to pass in full option -* Implemented keepGoing parameter for mongodb 1.9.1 or higher, Issue #310 -* Added test for read_secondary count issue, merged in fix from (https://github.com/year2013), Issue #317 - -0.9.6-9 -------- -* Bug fix for bson parsing the key '':'' correctly without crashing - -0.9.6-8 -------- -* Changed to using node.js crypto library MD5 digest -* Connect method support documented mongodb: syntax by (https://github.com/sethml) -* Support Symbol type for BSON, serializes to it's own type Symbol, Issue #302, #288 -* Code object without scope serializing to correct BSON type -* Lot's of fixes to avoid double callbacks (https://github.com/aheckmann) Issue #304 -* Long deserializes as Number for values in the range -2^53 to 2^53, Issue #305 (https://github.com/sethml) -* Fixed C++ parser to reflect JS parser handling of long deserialization -* Bson small optimizations - -0.9.6-7 2011-07-13 ------------------- -* JS Bson deserialization bug #287 - -0.9.6-6 2011-07-12 ------------------- -* FindAndModify not returning error message as other methods Issue #277 -* Added test coverage for $push, $pushAll and $inc atomic operations -* Correct Error handling for non 12/24 bit ids on Pure JS ObjectID class Issue #276 -* Fixed terrible deserialization bug in js bson code #285 -* Fix by andrewjstone to avoid throwing errors when this.primary not defined - -0.9.6-5 2011-07-06 ------------------- -* Rewritten BSON js parser now faster than the C parser on my core2duo laptop -* Added option full to indexInformation to get all index info Issue #265 -* Passing in ObjectID for new Gridstore works correctly Issue #272 - -0.9.6-4 2011-07-01 ------------------- -* Added test and bug fix for insert/update/remove without callback supplied - -0.9.6-3 2011-07-01 ------------------- -* Added simple grid class called Grid with put, get, delete methods -* Fixed writeBuffer/readBuffer methods on GridStore so they work correctly -* Automatic handling of buffers when using write method on GridStore -* GridStore now accepts a ObjectID instead of file name for write and read methods -* GridStore.list accepts id option to return of file ids instead of filenames -* GridStore close method returns document for the file allowing user to reference _id field - -0.9.6-2 2011-06-30 ------------------- -* Fixes for reconnect logic for server object (replays auth correctly) -* More testcases for auth -* Fixes in error handling for replicaset -* Fixed bug with safe parameter that would fail to execute safe when passing w or wtimeout -* Fixed slaveOk bug for findOne method -* Implemented auth support for replicaset and test cases -* Fixed error when not passing in rs_name - -0.9.6-1 2011-06-25 ------------------- -* Fixes for test to run properly using c++ bson parser -* Fixes for dbref in native parser (correctly handles ref without db component) -* Connection fixes for replicasets to avoid runtime conditions in cygwin (https://github.com/vincentcr) -* Fixes for timestamp in js bson parser (distinct timestamp type now) - -0.9.6 2011-06-21 ----------------- -* Worked around npm version handling bug -* Race condition fix for cygwin (https://github.com/vincentcr) - -0.9.5-1 2011-06-21 ------------------- -* Extracted Timestamp as separate class for bson js parser to avoid instanceof problems -* Fixed driver strict mode issue - -0.9.5 2011-06-20 ----------------- -* Replicaset support (failover and reading from secondary servers) -* Removed ServerPair and ServerCluster -* Added connection pool functionality -* Fixed serious bug in C++ bson parser where bytes > 127 would generate 2 byte sequences -* Allows for forcing the server to assign ObjectID's using the option {forceServerObjectId: true} - -0.6.8 ------ -* Removed multiple message concept from bson -* Changed db.open(db) to be db.open(err, db) - -0.1 2010-01-30 --------------- -* Initial release support of driver using native node.js interface -* Supports gridfs specification -* Supports admin functionality diff --git a/scripts/2.5/node_modules/mongodb/LICENSE.md b/scripts/2.5/node_modules/mongodb/LICENSE.md deleted file mode 100644 index ad410e11..00000000 --- a/scripts/2.5/node_modules/mongodb/LICENSE.md +++ /dev/null @@ -1,201 +0,0 @@ -Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "{}" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright {yyyy} {name of copyright owner} - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. \ No newline at end of file diff --git a/scripts/2.5/node_modules/mongodb/README.md b/scripts/2.5/node_modules/mongodb/README.md deleted file mode 100644 index 672ccf39..00000000 --- a/scripts/2.5/node_modules/mongodb/README.md +++ /dev/null @@ -1,499 +0,0 @@ -[![npm](https://nodei.co/npm/mongodb.png?downloads=true&downloadRank=true)](https://nodei.co/npm/mongodb/) [![npm](https://nodei.co/npm-dl/mongodb.png?months=6&height=3)](https://nodei.co/npm/mongodb/) - -[![Build Status](https://secure.travis-ci.org/mongodb/node-mongodb-native.svg?branch=2.1)](http://travis-ci.org/mongodb/node-mongodb-native) -[![Coverage Status](https://coveralls.io/repos/github/mongodb/node-mongodb-native/badge.svg?branch=2.1)](https://coveralls.io/github/mongodb/node-mongodb-native?branch=2.1) -[![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/mongodb/node-mongodb-native?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) - -# Description - -The official [MongoDB](https://www.mongodb.com/) driver for Node.js. Provides a high-level API on top of [mongodb-core](https://www.npmjs.com/package/mongodb-core) that is meant for end users. - -**NOTE: v3.x was recently released with breaking API changes. You can find a list of changes [here](CHANGES_3.0.0.md).** - -## MongoDB Node.JS Driver - -| what | where | -|---------------|------------------------------------------------| -| documentation | http://mongodb.github.io/node-mongodb-native | -| api-doc | http://mongodb.github.io/node-mongodb-native/3.1/api | -| source | https://github.com/mongodb/node-mongodb-native | -| mongodb | http://www.mongodb.org | - -### Bugs / Feature Requests - -Think you’ve found a bug? Want to see a new feature in `node-mongodb-native`? Please open a -case in our issue management tool, JIRA: - -- Create an account and login [jira.mongodb.org](https://jira.mongodb.org). -- Navigate to the NODE project [jira.mongodb.org/browse/NODE](https://jira.mongodb.org/browse/NODE). -- Click **Create Issue** - Please provide as much information as possible about the issue type and how to reproduce it. - -Bug reports in JIRA for all driver projects (i.e. NODE, PYTHON, CSHARP, JAVA) and the -Core Server (i.e. SERVER) project are **public**. - -### Support / Feedback - -For issues with, questions about, or feedback for the Node.js driver, please look into our [support channels](http://www.mongodb.org/about/support). Please do not email any of the driver developers directly with issues or questions - you're more likely to get an answer on the [mongodb-user](http://groups.google.com/group/mongodb-user>) list on Google Groups. - -### Change Log - -Change history can be found in [`HISTORY.md`](HISTORY.md). - -### Compatibility - -For version compatibility matrices, please refer to the following links: - - * [MongoDB](https://docs.mongodb.com/ecosystem/drivers/driver-compatibility-reference/#reference-compatibility-mongodb-node) - * [NodeJS](https://docs.mongodb.com/ecosystem/drivers/driver-compatibility-reference/#reference-compatibility-language-node) - -# Installation - -The recommended way to get started using the Node.js 3.0 driver is by using the `npm` (Node Package Manager) to install the dependency in your project. - -## MongoDB Driver - -Given that you have created your own project using `npm init` we install the MongoDB driver and its dependencies by executing the following `npm` command. - -```bash -npm install mongodb --save -``` - -This will download the MongoDB driver and add a dependency entry in your `package.json` file. - -You can also use the [Yarn](https://yarnpkg.com/en) package manager. - -## Troubleshooting - -The MongoDB driver depends on several other packages. These are: - -* [mongodb-core](https://github.com/mongodb-js/mongodb-core) -* [bson](https://github.com/mongodb/js-bson) -* [kerberos](https://github.com/mongodb-js/kerberos) -* [node-gyp](https://github.com/nodejs/node-gyp) - -The `kerberos` package is a C++ extension that requires a build environment to be installed on your system. You must be able to build Node.js itself in order to compile and install the `kerberos` module. Furthermore, the `kerberos` module requires the MIT Kerberos package to correctly compile on UNIX operating systems. Consult your UNIX operation system package manager for what libraries to install. - -**Windows already contains the SSPI API used for Kerberos authentication. However, you will need to install a full compiler tool chain using Visual Studio C++ to correctly install the Kerberos extension.** - -### Diagnosing on UNIX - -If you don’t have the build-essentials, this module won’t build. In the case of Linux, you will need gcc, g++, Node.js with all the headers and Python. The easiest way to figure out what’s missing is by trying to build the Kerberos project. You can do this by performing the following steps. - -```bash -git clone https://github.com/mongodb-js/kerberos -cd kerberos -npm install -``` - -If all the steps complete, you have the right toolchain installed. If you get the error "node-gyp not found," you need to install `node-gyp` globally: - -```bash -npm install -g node-gyp -``` - -If it correctly compiles and runs the tests you are golden. We can now try to install the `mongod` driver by performing the following command. - -```bash -cd yourproject -npm install mongodb --save -``` - -If it still fails the next step is to examine the npm log. Rerun the command but in this case in verbose mode. - -```bash -npm --loglevel verbose install mongodb -``` - -This will print out all the steps npm is performing while trying to install the module. - -### Diagnosing on Windows - -A compiler tool chain known to work for compiling `kerberos` on Windows is the following. - -* Visual Studio C++ 2010 (do not use higher versions) -* Windows 7 64bit SDK -* Python 2.7 or higher - -Open the Visual Studio command prompt. Ensure `node.exe` is in your path and install `node-gyp`. - -```bash -npm install -g node-gyp -``` - -Next, you will have to build the project manually to test it. Clone the repo, install dependencies and rebuild: - -```bash -git clone https://github.com/christkv/kerberos.git -cd kerberos -npm install -node-gyp rebuild -``` - -This should rebuild the driver successfully if you have everything set up correctly. - -### Other possible issues - -Your Python installation might be hosed making gyp break. Test your deployment environment first by trying to build Node.js itself on the server in question, as this should unearth any issues with broken packages (and there are a lot of broken packages out there). - -Another tip is to ensure your user has write permission to wherever the Node.js modules are being installed. - -## Quick Start - -This guide will show you how to set up a simple application using Node.js and MongoDB. Its scope is only how to set up the driver and perform the simple CRUD operations. For more in-depth coverage, see the [tutorials](docs/reference/content/tutorials/main.md). - -### Create the `package.json` file - -First, create a directory where your application will live. - -```bash -mkdir myproject -cd myproject -``` - -Enter the following command and answer the questions to create the initial structure for your new project: - -```bash -npm init -``` - -Next, install the driver dependency. - -```bash -npm install mongodb --save -``` - -You should see **NPM** download a lot of files. Once it's done you'll find all the downloaded packages under the **node_modules** directory. - -### Start a MongoDB Server - -For complete MongoDB installation instructions, see [the manual](https://docs.mongodb.org/manual/installation/). - -1. Download the right MongoDB version from [MongoDB](https://www.mongodb.org/downloads) -2. Create a database directory (in this case under **/data**). -3. Install and start a ``mongod`` process. - -```bash -mongod --dbpath=/data -``` - -You should see the **mongod** process start up and print some status information. - -### Connect to MongoDB - -Create a new **app.js** file and add the following code to try out some basic CRUD -operations using the MongoDB driver. - -Add code to connect to the server and the database **myproject**: - -```js -const MongoClient = require('mongodb').MongoClient; -const assert = require('assert'); - -// Connection URL -const url = 'mongodb://localhost:27017'; - -// Database Name -const dbName = 'myproject'; - -// Use connect method to connect to the server -MongoClient.connect(url, function(err, client) { - assert.equal(null, err); - console.log("Connected successfully to server"); - - const db = client.db(dbName); - - client.close(); -}); -``` - -Run your app from the command line with: - -```bash -node app.js -``` - -The application should print **Connected successfully to server** to the console. - -### Insert a Document - -Add to **app.js** the following function which uses the **insertMany** -method to add three documents to the **documents** collection. - -```js -const insertDocuments = function(db, callback) { - // Get the documents collection - const collection = db.collection('documents'); - // Insert some documents - collection.insertMany([ - {a : 1}, {a : 2}, {a : 3} - ], function(err, result) { - assert.equal(err, null); - assert.equal(3, result.result.n); - assert.equal(3, result.ops.length); - console.log("Inserted 3 documents into the collection"); - callback(result); - }); -} -``` - -The **insert** command returns an object with the following fields: - -* **result** Contains the result document from MongoDB -* **ops** Contains the documents inserted with added **_id** fields -* **connection** Contains the connection used to perform the insert - -Add the following code to call the **insertDocuments** function: - -```js -const MongoClient = require('mongodb').MongoClient; -const assert = require('assert'); - -// Connection URL -const url = 'mongodb://localhost:27017'; - -// Database Name -const dbName = 'myproject'; - -// Use connect method to connect to the server -MongoClient.connect(url, function(err, client) { - assert.equal(null, err); - console.log("Connected successfully to server"); - - const db = client.db(dbName); - - insertDocuments(db, function() { - client.close(); - }); -}); -``` - -Run the updated **app.js** file: - -```bash -node app.js -``` - -The operation returns the following output: - -```bash -Connected successfully to server -Inserted 3 documents into the collection -``` - -### Find All Documents - -Add a query that returns all the documents. - -```js -const findDocuments = function(db, callback) { - // Get the documents collection - const collection = db.collection('documents'); - // Find some documents - collection.find({}).toArray(function(err, docs) { - assert.equal(err, null); - console.log("Found the following records"); - console.log(docs) - callback(docs); - }); -} -``` - -This query returns all the documents in the **documents** collection. Add the **findDocument** method to the **MongoClient.connect** callback: - -```js -const MongoClient = require('mongodb').MongoClient; -const assert = require('assert'); - -// Connection URL -const url = 'mongodb://localhost:27017'; - -// Database Name -const dbName = 'myproject'; - -// Use connect method to connect to the server -MongoClient.connect(url, function(err, client) { - assert.equal(null, err); - console.log("Connected correctly to server"); - - const db = client.db(dbName); - - insertDocuments(db, function() { - findDocuments(db, function() { - client.close(); - }); - }); -}); -``` - -### Find Documents with a Query Filter - -Add a query filter to find only documents which meet the query criteria. - -```js -const findDocuments = function(db, callback) { - // Get the documents collection - const collection = db.collection('documents'); - // Find some documents - collection.find({'a': 3}).toArray(function(err, docs) { - assert.equal(err, null); - console.log("Found the following records"); - console.log(docs); - callback(docs); - }); -} -``` - -Only the documents which match ``'a' : 3`` should be returned. - -### Update a document - -The following operation updates a document in the **documents** collection. - -```js -const updateDocument = function(db, callback) { - // Get the documents collection - const collection = db.collection('documents'); - // Update document where a is 2, set b equal to 1 - collection.updateOne({ a : 2 } - , { $set: { b : 1 } }, function(err, result) { - assert.equal(err, null); - assert.equal(1, result.result.n); - console.log("Updated the document with the field a equal to 2"); - callback(result); - }); -} -``` - -The method updates the first document where the field **a** is equal to **2** by adding a new field **b** to the document set to **1**. Next, update the callback function from **MongoClient.connect** to include the update method. - -```js -const MongoClient = require('mongodb').MongoClient; -const assert = require('assert'); - -// Connection URL -const url = 'mongodb://localhost:27017'; - -// Database Name -const dbName = 'myproject'; - -// Use connect method to connect to the server -MongoClient.connect(url, function(err, client) { - assert.equal(null, err); - console.log("Connected successfully to server"); - - const db = client.db(dbName); - - insertDocuments(db, function() { - updateDocument(db, function() { - client.close(); - }); - }); -}); -``` - -### Remove a document - -Remove the document where the field **a** is equal to **3**. - -```js -const removeDocument = function(db, callback) { - // Get the documents collection - const collection = db.collection('documents'); - // Delete document where a is 3 - collection.deleteOne({ a : 3 }, function(err, result) { - assert.equal(err, null); - assert.equal(1, result.result.n); - console.log("Removed the document with the field a equal to 3"); - callback(result); - }); -} -``` - -Add the new method to the **MongoClient.connect** callback function. - -```js -const MongoClient = require('mongodb').MongoClient; -const assert = require('assert'); - -// Connection URL -const url = 'mongodb://localhost:27017'; - -// Database Name -const dbName = 'myproject'; - -// Use connect method to connect to the server -MongoClient.connect(url, function(err, client) { - assert.equal(null, err); - console.log("Connected successfully to server"); - - const db = client.db(dbName); - - insertDocuments(db, function() { - updateDocument(db, function() { - removeDocument(db, function() { - client.close(); - }); - }); - }); -}); -``` - -### Index a Collection - -[Indexes](https://docs.mongodb.org/manual/indexes/) can improve your application's -performance. The following function creates an index on the **a** field in the -**documents** collection. - -```js -const indexCollection = function(db, callback) { - db.collection('documents').createIndex( - { "a": 1 }, - null, - function(err, results) { - console.log(results); - callback(); - } - ); -}; -``` - -Add the ``indexCollection`` method to your app: - -```js -const MongoClient = require('mongodb').MongoClient; -const assert = require('assert'); - -// Connection URL -const url = 'mongodb://localhost:27017'; - -const dbName = 'myproject'; - -// Use connect method to connect to the server -MongoClient.connect(url, function(err, client) { - assert.equal(null, err); - console.log("Connected successfully to server"); - - const db = client.db(dbName); - - insertDocuments(db, function() { - indexCollection(db, function() { - client.close(); - }); - }); -}); -``` - -For more detailed information, see the [tutorials](docs/reference/content/tutorials/main.md). - -## Next Steps - - * [MongoDB Documentation](http://mongodb.org) - * [Read about Schemas](http://learnmongodbthehardway.com) - * [Star us on GitHub](https://github.com/mongodb/node-mongodb-native) - -## License - -[Apache 2.0](LICENSE.md) - -© 2009-2012 Christian Amor Kvalheim -© 2012-present MongoDB [Contributors](CONTRIBUTORS.md) diff --git a/scripts/2.5/node_modules/mongodb/index.js b/scripts/2.5/node_modules/mongodb/index.js deleted file mode 100644 index 3ce36f59..00000000 --- a/scripts/2.5/node_modules/mongodb/index.js +++ /dev/null @@ -1,68 +0,0 @@ -'use strict'; - -// Core module -const core = require('./lib/core'); -const Instrumentation = require('./lib/apm'); - -// Set up the connect function -const connect = require('./lib/mongo_client').connect; - -// Expose error class -connect.MongoError = core.MongoError; -connect.MongoNetworkError = core.MongoNetworkError; -connect.MongoTimeoutError = core.MongoTimeoutError; - -// Actual driver classes exported -connect.Admin = require('./lib/admin'); -connect.MongoClient = require('./lib/mongo_client'); -connect.Db = require('./lib/db'); -connect.Collection = require('./lib/collection'); -connect.Server = require('./lib/topologies/server'); -connect.ReplSet = require('./lib/topologies/replset'); -connect.Mongos = require('./lib/topologies/mongos'); -connect.ReadPreference = core.ReadPreference; -connect.GridStore = require('./lib/gridfs/grid_store'); -connect.Chunk = require('./lib/gridfs/chunk'); -connect.Logger = core.Logger; -connect.AggregationCursor = require('./lib/aggregation_cursor'); -connect.CommandCursor = require('./lib/command_cursor'); -connect.Cursor = require('./lib/cursor'); -connect.GridFSBucket = require('./lib/gridfs-stream'); -// Exported to be used in tests not to be used anywhere else -connect.CoreServer = core.Server; -connect.CoreConnection = core.Connection; - -// BSON types exported -connect.Binary = core.BSON.Binary; -connect.Code = core.BSON.Code; -connect.Map = core.BSON.Map; -connect.DBRef = core.BSON.DBRef; -connect.Double = core.BSON.Double; -connect.Int32 = core.BSON.Int32; -connect.Long = core.BSON.Long; -connect.MinKey = core.BSON.MinKey; -connect.MaxKey = core.BSON.MaxKey; -connect.ObjectID = core.BSON.ObjectID; -connect.ObjectId = core.BSON.ObjectID; -connect.Symbol = core.BSON.Symbol; -connect.Timestamp = core.BSON.Timestamp; -connect.BSONRegExp = core.BSON.BSONRegExp; -connect.Decimal128 = core.BSON.Decimal128; - -// Add connect method -connect.connect = connect; - -// Set up the instrumentation method -connect.instrument = function(options, callback) { - if (typeof options === 'function') { - callback = options; - options = {}; - } - - const instrumentation = new Instrumentation(); - instrumentation.instrument(connect.MongoClient, callback); - return instrumentation; -}; - -// Set our exports to be the connect function -module.exports = connect; diff --git a/scripts/2.5/node_modules/mongodb/lib/admin.js b/scripts/2.5/node_modules/mongodb/lib/admin.js deleted file mode 100644 index 716844bb..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/admin.js +++ /dev/null @@ -1,293 +0,0 @@ -'use strict'; - -const applyWriteConcern = require('./utils').applyWriteConcern; - -const AddUserOperation = require('./operations/add_user'); -const ExecuteDbAdminCommandOperation = require('./operations/execute_db_admin_command'); -const RemoveUserOperation = require('./operations/remove_user'); -const ValidateCollectionOperation = require('./operations/validate_collection'); -const ListDatabasesOperation = require('./operations/list_databases'); - -const executeOperation = require('./operations/execute_operation'); - -/** - * @fileOverview The **Admin** class is an internal class that allows convenient access to - * the admin functionality and commands for MongoDB. - * - * **ADMIN Cannot directly be instantiated** - * @example - * const MongoClient = require('mongodb').MongoClient; - * const test = require('assert'); - * // Connection url - * const url = 'mongodb://localhost:27017'; - * // Database Name - * const dbName = 'test'; - * - * // Connect using MongoClient - * MongoClient.connect(url, function(err, client) { - * // Use the admin database for the operation - * const adminDb = client.db(dbName).admin(); - * - * // List all the available databases - * adminDb.listDatabases(function(err, dbs) { - * test.equal(null, err); - * test.ok(dbs.databases.length > 0); - * client.close(); - * }); - * }); - */ - -/** - * Create a new Admin instance (INTERNAL TYPE, do not instantiate directly) - * @class - * @return {Admin} a collection instance. - */ -function Admin(db, topology, promiseLibrary) { - if (!(this instanceof Admin)) return new Admin(db, topology); - - // Internal state - this.s = { - db: db, - topology: topology, - promiseLibrary: promiseLibrary - }; -} - -/** - * The callback format for results - * @callback Admin~resultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {object} result The result object if the command was executed successfully. - */ - -/** - * Execute a command - * @method - * @param {object} command The command hash - * @param {object} [options] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query. - * @param {Admin~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.command = function(command, options, callback) { - const args = Array.prototype.slice.call(arguments, 1); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - options = args.length ? args.shift() : {}; - - const commandOperation = new ExecuteDbAdminCommandOperation(this.s.db, command, options); - - return executeOperation(this.s.db.s.topology, commandOperation, callback); -}; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @param {Object} [options] optional parameters for this operation - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Admin~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.buildInfo = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const cmd = { buildinfo: 1 }; - - const buildInfoOperation = new ExecuteDbAdminCommandOperation(this.s.db, cmd, options); - - return executeOperation(this.s.db.s.topology, buildInfoOperation, callback); -}; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @param {Object} [options] optional parameters for this operation - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Admin~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.serverInfo = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const cmd = { buildinfo: 1 }; - - const serverInfoOperation = new ExecuteDbAdminCommandOperation(this.s.db, cmd, options); - - return executeOperation(this.s.db.s.topology, serverInfoOperation, callback); -}; - -/** - * Retrieve this db's server status. - * - * @param {Object} [options] optional parameters for this operation - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Admin~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.serverStatus = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const serverStatusOperation = new ExecuteDbAdminCommandOperation( - this.s.db, - { serverStatus: 1 }, - options - ); - - return executeOperation(this.s.db.s.topology, serverStatusOperation, callback); -}; - -/** - * Ping the MongoDB server and retrieve results - * - * @param {Object} [options] optional parameters for this operation - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Admin~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.ping = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const cmd = { ping: 1 }; - - const pingOperation = new ExecuteDbAdminCommandOperation(this.s.db, cmd, options); - - return executeOperation(this.s.db.s.topology, pingOperation, callback); -}; - -/** - * Add a user to the database. - * @method - * @param {string} username The username. - * @param {string} password The password. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.fsync=false] Specify a file sync write concern. - * @param {object} [options.customData] Custom data associated with the user (only Mongodb 2.6 or higher) - * @param {object[]} [options.roles] Roles associated with the created user (only Mongodb 2.6 or higher) - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Admin~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.addUser = function(username, password, options, callback) { - const args = Array.prototype.slice.call(arguments, 2); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - - // Special case where there is no password ($external users) - if (typeof username === 'string' && password != null && typeof password === 'object') { - options = password; - password = null; - } - - options = args.length ? args.shift() : {}; - options = Object.assign({}, options); - // Get the options - options = applyWriteConcern(options, { db: this.s.db }); - // Set the db name to admin - options.dbName = 'admin'; - - const addUserOperation = new AddUserOperation(this.s.db, username, password, options); - - return executeOperation(this.s.db.s.topology, addUserOperation, callback); -}; - -/** - * Remove a user from a database - * @method - * @param {string} username The username. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.fsync=false] Specify a file sync write concern. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Admin~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.removeUser = function(username, options, callback) { - const args = Array.prototype.slice.call(arguments, 1); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - - options = args.length ? args.shift() : {}; - options = Object.assign({}, options); - // Get the options - options = applyWriteConcern(options, { db: this.s.db }); - // Set the db name - options.dbName = 'admin'; - - const removeUserOperation = new RemoveUserOperation(this.s.db, username, options); - - return executeOperation(this.s.db.s.topology, removeUserOperation, callback); -}; - -/** - * Validate an existing collection - * - * @param {string} collectionName The name of the collection to validate. - * @param {object} [options] Optional settings. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Admin~resultCallback} [callback] The command result callback. - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.validateCollection = function(collectionName, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const validateCollectionOperation = new ValidateCollectionOperation( - this, - collectionName, - options - ); - - return executeOperation(this.s.db.s.topology, validateCollectionOperation, callback); -}; - -/** - * List the available databases - * - * @param {object} [options] Optional settings. - * @param {boolean} [options.nameOnly=false] Whether the command should return only db names, or names and size info. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Admin~resultCallback} [callback] The command result callback. - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.listDatabases = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - return executeOperation( - this.s.db.s.topology, - new ListDatabasesOperation(this.s.db, options), - callback - ); -}; - -/** - * Get ReplicaSet status - * - * @param {Object} [options] optional parameters for this operation - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Admin~resultCallback} [callback] The command result callback. - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.replSetGetStatus = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const replSetGetStatusOperation = new ExecuteDbAdminCommandOperation( - this.s.db, - { replSetGetStatus: 1 }, - options - ); - - return executeOperation(this.s.db.s.topology, replSetGetStatusOperation, callback); -}; - -module.exports = Admin; diff --git a/scripts/2.5/node_modules/mongodb/lib/aggregation_cursor.js b/scripts/2.5/node_modules/mongodb/lib/aggregation_cursor.js deleted file mode 100644 index b0977c69..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/aggregation_cursor.js +++ /dev/null @@ -1,370 +0,0 @@ -'use strict'; - -const MongoError = require('./core').MongoError; -const Cursor = require('./cursor'); -const CursorState = require('./core/cursor').CursorState; -const deprecate = require('util').deprecate; - -/** - * @fileOverview The **AggregationCursor** class is an internal class that embodies an aggregation cursor on MongoDB - * allowing for iteration over the results returned from the underlying query. It supports - * one by one document iteration, conversion to an array or can be iterated as a Node 4.X - * or higher stream - * - * **AGGREGATIONCURSOR Cannot directly be instantiated** - * @example - * const MongoClient = require('mongodb').MongoClient; - * const test = require('assert'); - * // Connection url - * const url = 'mongodb://localhost:27017'; - * // Database Name - * const dbName = 'test'; - * // Connect using MongoClient - * MongoClient.connect(url, function(err, client) { - * // Create a collection we want to drop later - * const col = client.db(dbName).collection('createIndexExample1'); - * // Insert a bunch of documents - * col.insert([{a:1, b:1} - * , {a:2, b:2}, {a:3, b:3} - * , {a:4, b:4}], {w:1}, function(err, result) { - * test.equal(null, err); - * // Show that duplicate records got dropped - * col.aggregation({}, {cursor: {}}).toArray(function(err, items) { - * test.equal(null, err); - * test.equal(4, items.length); - * client.close(); - * }); - * }); - * }); - */ - -/** - * Namespace provided by the browser. - * @external Readable - */ - -/** - * Creates a new Aggregation Cursor instance (INTERNAL TYPE, do not instantiate directly) - * @class AggregationCursor - * @extends external:Readable - * @fires AggregationCursor#data - * @fires AggregationCursor#end - * @fires AggregationCursor#close - * @fires AggregationCursor#readable - * @return {AggregationCursor} an AggregationCursor instance. - */ -class AggregationCursor extends Cursor { - constructor(topology, operation, options) { - super(topology, operation, options); - } - - /** - * Set the batch size for the cursor. - * @method - * @param {number} value The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. - * @throws {MongoError} - * @return {AggregationCursor} - */ - batchSize(value) { - if (this.s.state === CursorState.CLOSED || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - if (typeof value !== 'number') { - throw MongoError.create({ message: 'batchSize requires an integer', driver: true }); - } - - this.operation.options.batchSize = value; - this.setCursorBatchSize(value); - return this; - } - - /** - * Add a geoNear stage to the aggregation pipeline - * @method - * @param {object} document The geoNear stage document. - * @return {AggregationCursor} - */ - geoNear(document) { - this.operation.addToPipeline({ $geoNear: document }); - return this; - } - - /** - * Add a group stage to the aggregation pipeline - * @method - * @param {object} document The group stage document. - * @return {AggregationCursor} - */ - group(document) { - this.operation.addToPipeline({ $group: document }); - return this; - } - - /** - * Add a limit stage to the aggregation pipeline - * @method - * @param {number} value The state limit value. - * @return {AggregationCursor} - */ - limit(value) { - this.operation.addToPipeline({ $limit: value }); - return this; - } - - /** - * Add a match stage to the aggregation pipeline - * @method - * @param {object} document The match stage document. - * @return {AggregationCursor} - */ - match(document) { - this.operation.addToPipeline({ $match: document }); - return this; - } - - /** - * Add a maxTimeMS stage to the aggregation pipeline - * @method - * @param {number} value The state maxTimeMS value. - * @return {AggregationCursor} - */ - maxTimeMS(value) { - this.operation.options.maxTimeMS = value; - return this; - } - - /** - * Add a out stage to the aggregation pipeline - * @method - * @param {number} destination The destination name. - * @return {AggregationCursor} - */ - out(destination) { - this.operation.addToPipeline({ $out: destination }); - return this; - } - - /** - * Add a project stage to the aggregation pipeline - * @method - * @param {object} document The project stage document. - * @return {AggregationCursor} - */ - project(document) { - this.operation.addToPipeline({ $project: document }); - return this; - } - - /** - * Add a lookup stage to the aggregation pipeline - * @method - * @param {object} document The lookup stage document. - * @return {AggregationCursor} - */ - lookup(document) { - this.operation.addToPipeline({ $lookup: document }); - return this; - } - - /** - * Add a redact stage to the aggregation pipeline - * @method - * @param {object} document The redact stage document. - * @return {AggregationCursor} - */ - redact(document) { - this.operation.addToPipeline({ $redact: document }); - return this; - } - - /** - * Add a skip stage to the aggregation pipeline - * @method - * @param {number} value The state skip value. - * @return {AggregationCursor} - */ - skip(value) { - this.operation.addToPipeline({ $skip: value }); - return this; - } - - /** - * Add a sort stage to the aggregation pipeline - * @method - * @param {object} document The sort stage document. - * @return {AggregationCursor} - */ - sort(document) { - this.operation.addToPipeline({ $sort: document }); - return this; - } - - /** - * Add a unwind stage to the aggregation pipeline - * @method - * @param {number} field The unwind field name. - * @return {AggregationCursor} - */ - unwind(field) { - this.operation.addToPipeline({ $unwind: field }); - return this; - } - - /** - * Return the cursor logger - * @method - * @return {Logger} return the cursor logger - * @ignore - */ - getLogger() { - return this.logger; - } -} - -// aliases -AggregationCursor.prototype.get = AggregationCursor.prototype.toArray; - -// deprecated methods -deprecate( - AggregationCursor.prototype.geoNear, - 'The `$geoNear` stage is deprecated in MongoDB 4.0, and removed in version 4.2.' -); - -/** - * AggregationCursor stream data event, fired for each document in the cursor. - * - * @event AggregationCursor#data - * @type {object} - */ - -/** - * AggregationCursor stream end event - * - * @event AggregationCursor#end - * @type {null} - */ - -/** - * AggregationCursor stream close event - * - * @event AggregationCursor#close - * @type {null} - */ - -/** - * AggregationCursor stream readable event - * - * @event AggregationCursor#readable - * @type {null} - */ - -/** - * Get the next available document from the cursor, returns null if no more documents are available. - * @function AggregationCursor.prototype.next - * @param {AggregationCursor~resultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ - -/** - * Check if there is any document still available in the cursor - * @function AggregationCursor.prototype.hasNext - * @param {AggregationCursor~resultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ - -/** - * The callback format for results - * @callback AggregationCursor~toArrayResultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {object[]} documents All the documents the satisfy the cursor. - */ - -/** - * Returns an array of documents. The caller is responsible for making sure that there - * is enough memory to store the results. Note that the array only contain partial - * results when this cursor had been previously accessed. In that case, - * cursor.rewind() can be used to reset the cursor. - * @method AggregationCursor.prototype.toArray - * @param {AggregationCursor~toArrayResultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ - -/** - * The callback format for results - * @callback AggregationCursor~resultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {(object|null)} result The result object if the command was executed successfully. - */ - -/** - * Iterates over all the documents for this cursor. As with **{cursor.toArray}**, - * not all of the elements will be iterated if this cursor had been previously accessed. - * In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike - * **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements - * at any given time if batch size is specified. Otherwise, the caller is responsible - * for making sure that the entire result can fit the memory. - * @method AggregationCursor.prototype.each - * @deprecated - * @param {AggregationCursor~resultCallback} callback The result callback. - * @throws {MongoError} - * @return {null} - */ - -/** - * Close the cursor, sending a AggregationCursor command and emitting close. - * @method AggregationCursor.prototype.close - * @param {AggregationCursor~resultCallback} [callback] The result callback. - * @return {Promise} returns Promise if no callback passed - */ - -/** - * Is the cursor closed - * @method AggregationCursor.prototype.isClosed - * @return {boolean} - */ - -/** - * Execute the explain for the cursor - * @method AggregationCursor.prototype.explain - * @param {AggregationCursor~resultCallback} [callback] The result callback. - * @return {Promise} returns Promise if no callback passed - */ - -/** - * Clone the cursor - * @function AggregationCursor.prototype.clone - * @return {AggregationCursor} - */ - -/** - * Resets the cursor - * @function AggregationCursor.prototype.rewind - * @return {AggregationCursor} - */ - -/** - * The callback format for the forEach iterator method - * @callback AggregationCursor~iteratorCallback - * @param {Object} doc An emitted document for the iterator - */ - -/** - * The callback error format for the forEach iterator method - * @callback AggregationCursor~endCallback - * @param {MongoError} error An error instance representing the error during the execution. - */ - -/** - * Iterates over all the documents for this cursor using the iterator, callback pattern. - * @method AggregationCursor.prototype.forEach - * @param {AggregationCursor~iteratorCallback} iterator The iteration callback. - * @param {AggregationCursor~endCallback} callback The end callback. - * @throws {MongoError} - * @return {null} - */ - -module.exports = AggregationCursor; diff --git a/scripts/2.5/node_modules/mongodb/lib/apm.js b/scripts/2.5/node_modules/mongodb/lib/apm.js deleted file mode 100644 index f78e4aaf..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/apm.js +++ /dev/null @@ -1,31 +0,0 @@ -'use strict'; -const EventEmitter = require('events').EventEmitter; - -class Instrumentation extends EventEmitter { - constructor() { - super(); - } - - instrument(MongoClient, callback) { - // store a reference to the original functions - this.$MongoClient = MongoClient; - const $prototypeConnect = (this.$prototypeConnect = MongoClient.prototype.connect); - - const instrumentation = this; - MongoClient.prototype.connect = function(callback) { - this.s.options.monitorCommands = true; - this.on('commandStarted', event => instrumentation.emit('started', event)); - this.on('commandSucceeded', event => instrumentation.emit('succeeded', event)); - this.on('commandFailed', event => instrumentation.emit('failed', event)); - return $prototypeConnect.call(this, callback); - }; - - if (typeof callback === 'function') callback(null, this); - } - - uninstrument() { - this.$MongoClient.prototype.connect = this.$prototypeConnect; - } -} - -module.exports = Instrumentation; diff --git a/scripts/2.5/node_modules/mongodb/lib/async/.eslintrc b/scripts/2.5/node_modules/mongodb/lib/async/.eslintrc deleted file mode 100644 index 93b2f643..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/async/.eslintrc +++ /dev/null @@ -1,5 +0,0 @@ -{ - "parserOptions": { - "ecmaVersion": 2018 - } -} diff --git a/scripts/2.5/node_modules/mongodb/lib/async/async_iterator.js b/scripts/2.5/node_modules/mongodb/lib/async/async_iterator.js deleted file mode 100644 index 6021aadf..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/async/async_iterator.js +++ /dev/null @@ -1,33 +0,0 @@ -'use strict'; - -// async function* asyncIterator() { -// while (true) { -// const value = await this.next(); -// if (!value) { -// await this.close(); -// return; -// } - -// yield value; -// } -// } - -// TODO: change this to the async generator function above -function asyncIterator() { - const cursor = this; - - return { - next: function() { - return Promise.resolve() - .then(() => cursor.next()) - .then(value => { - if (!value) { - return cursor.close().then(() => ({ value, done: true })); - } - return { value, done: false }; - }); - } - }; -} - -exports.asyncIterator = asyncIterator; diff --git a/scripts/2.5/node_modules/mongodb/lib/bulk/common.js b/scripts/2.5/node_modules/mongodb/lib/bulk/common.js deleted file mode 100644 index 8f99c252..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/bulk/common.js +++ /dev/null @@ -1,1239 +0,0 @@ -'use strict'; - -const Long = require('../core').BSON.Long; -const MongoError = require('../core').MongoError; -const ObjectID = require('../core').BSON.ObjectID; -const BSON = require('../core').BSON; -const MongoWriteConcernError = require('../core').MongoWriteConcernError; -const toError = require('../utils').toError; -const handleCallback = require('../utils').handleCallback; -const applyRetryableWrites = require('../utils').applyRetryableWrites; -const applyWriteConcern = require('../utils').applyWriteConcern; -const executeLegacyOperation = require('../utils').executeLegacyOperation; -const isPromiseLike = require('../utils').isPromiseLike; - -// Error codes -const WRITE_CONCERN_ERROR = 64; - -// Insert types -const INSERT = 1; -const UPDATE = 2; -const REMOVE = 3; - -const bson = new BSON([ - BSON.Binary, - BSON.Code, - BSON.DBRef, - BSON.Decimal128, - BSON.Double, - BSON.Int32, - BSON.Long, - BSON.Map, - BSON.MaxKey, - BSON.MinKey, - BSON.ObjectId, - BSON.BSONRegExp, - BSON.Symbol, - BSON.Timestamp -]); - -/** - * Keeps the state of a unordered batch so we can rewrite the results - * correctly after command execution - * @ignore - */ -class Batch { - constructor(batchType, originalZeroIndex) { - this.originalZeroIndex = originalZeroIndex; - this.currentIndex = 0; - this.originalIndexes = []; - this.batchType = batchType; - this.operations = []; - this.size = 0; - this.sizeBytes = 0; - } -} - -/** - * @classdesc - * The result of a bulk write. - */ -class BulkWriteResult { - /** - * Create a new BulkWriteResult instance - * - * **NOTE:** Internal Type, do not instantiate directly - */ - constructor(bulkResult) { - this.result = bulkResult; - } - - /** - * Evaluates to true if the bulk operation correctly executes - * @type {boolean} - */ - get ok() { - return this.result.ok; - } - - /** - * The number of inserted documents - * @type {number} - */ - get nInserted() { - return this.result.nInserted; - } - - /** - * Number of upserted documents - * @type {number} - */ - get nUpserted() { - return this.result.nUpserted; - } - - /** - * Number of matched documents - * @type {number} - */ - get nMatched() { - return this.result.nMatched; - } - - /** - * Number of documents updated physically on disk - * @type {number} - */ - get nModified() { - return this.result.nModified; - } - - /** - * Number of removed documents - * @type {number} - */ - get nRemoved() { - return this.result.nRemoved; - } - - /** - * Returns an array of all inserted ids - * - * @return {object[]} - */ - getInsertedIds() { - return this.result.insertedIds; - } - - /** - * Returns an array of all upserted ids - * - * @return {object[]} - */ - getUpsertedIds() { - return this.result.upserted; - } - - /** - * Returns the upserted id at the given index - * - * @param {number} index the number of the upserted id to return, returns undefined if no result for passed in index - * @return {object} - */ - getUpsertedIdAt(index) { - return this.result.upserted[index]; - } - - /** - * Returns raw internal result - * - * @return {object} - */ - getRawResponse() { - return this.result; - } - - /** - * Returns true if the bulk operation contains a write error - * - * @return {boolean} - */ - hasWriteErrors() { - return this.result.writeErrors.length > 0; - } - - /** - * Returns the number of write errors off the bulk operation - * - * @return {number} - */ - getWriteErrorCount() { - return this.result.writeErrors.length; - } - - /** - * Returns a specific write error object - * - * @param {number} index of the write error to return, returns null if there is no result for passed in index - * @return {WriteError} - */ - getWriteErrorAt(index) { - if (index < this.result.writeErrors.length) { - return this.result.writeErrors[index]; - } - return null; - } - - /** - * Retrieve all write errors - * - * @return {WriteError[]} - */ - getWriteErrors() { - return this.result.writeErrors; - } - - /** - * Retrieve lastOp if available - * - * @return {object} - */ - getLastOp() { - return this.result.lastOp; - } - - /** - * Retrieve the write concern error if any - * - * @return {WriteConcernError} - */ - getWriteConcernError() { - if (this.result.writeConcernErrors.length === 0) { - return null; - } else if (this.result.writeConcernErrors.length === 1) { - // Return the error - return this.result.writeConcernErrors[0]; - } else { - // Combine the errors - let errmsg = ''; - for (let i = 0; i < this.result.writeConcernErrors.length; i++) { - const err = this.result.writeConcernErrors[i]; - errmsg = errmsg + err.errmsg; - - // TODO: Something better - if (i === 0) errmsg = errmsg + ' and '; - } - - return new WriteConcernError({ errmsg: errmsg, code: WRITE_CONCERN_ERROR }); - } - } - - /** - * @return {object} - */ - toJSON() { - return this.result; - } - - /** - * @return {string} - */ - toString() { - return `BulkWriteResult(${this.toJSON(this.result)})`; - } - - /** - * @return {boolean} - */ - isOk() { - return this.result.ok === 1; - } -} - -/** - * @classdesc An error representing a failure by the server to apply the requested write concern to the bulk operation. - */ -class WriteConcernError { - /** - * Create a new WriteConcernError instance - * - * **NOTE:** Internal Type, do not instantiate directly - */ - constructor(err) { - this.err = err; - } - - /** - * Write concern error code. - * @type {number} - */ - get code() { - return this.err.code; - } - - /** - * Write concern error message. - * @type {string} - */ - get errmsg() { - return this.err.errmsg; - } - - /** - * @return {object} - */ - toJSON() { - return { code: this.err.code, errmsg: this.err.errmsg }; - } - - /** - * @return {string} - */ - toString() { - return `WriteConcernError(${this.err.errmsg})`; - } -} - -/** - * @classdesc An error that occurred during a BulkWrite on the server. - */ -class WriteError { - /** - * Create a new WriteError instance - * - * **NOTE:** Internal Type, do not instantiate directly - */ - constructor(err) { - this.err = err; - } - - /** - * WriteError code. - * @type {number} - */ - get code() { - return this.err.code; - } - - /** - * WriteError original bulk operation index. - * @type {number} - */ - get index() { - return this.err.index; - } - - /** - * WriteError message. - * @type {string} - */ - get errmsg() { - return this.err.errmsg; - } - - /** - * Returns the underlying operation that caused the error - * @return {object} - */ - getOperation() { - return this.err.op; - } - - /** - * @return {object} - */ - toJSON() { - return { code: this.err.code, index: this.err.index, errmsg: this.err.errmsg, op: this.err.op }; - } - - /** - * @return {string} - */ - toString() { - return `WriteError(${JSON.stringify(this.toJSON())})`; - } -} - -/** - * Merges results into shared data structure - * @ignore - */ -function mergeBatchResults(batch, bulkResult, err, result) { - // If we have an error set the result to be the err object - if (err) { - result = err; - } else if (result && result.result) { - result = result.result; - } else if (result == null) { - return; - } - - // Do we have a top level error stop processing and return - if (result.ok === 0 && bulkResult.ok === 1) { - bulkResult.ok = 0; - - const writeError = { - index: 0, - code: result.code || 0, - errmsg: result.message, - op: batch.operations[0] - }; - - bulkResult.writeErrors.push(new WriteError(writeError)); - return; - } else if (result.ok === 0 && bulkResult.ok === 0) { - return; - } - - // Deal with opTime if available - if (result.opTime || result.lastOp) { - const opTime = result.lastOp || result.opTime; - let lastOpTS = null; - let lastOpT = null; - - // We have a time stamp - if (opTime && opTime._bsontype === 'Timestamp') { - if (bulkResult.lastOp == null) { - bulkResult.lastOp = opTime; - } else if (opTime.greaterThan(bulkResult.lastOp)) { - bulkResult.lastOp = opTime; - } - } else { - // Existing TS - if (bulkResult.lastOp) { - lastOpTS = - typeof bulkResult.lastOp.ts === 'number' - ? Long.fromNumber(bulkResult.lastOp.ts) - : bulkResult.lastOp.ts; - lastOpT = - typeof bulkResult.lastOp.t === 'number' - ? Long.fromNumber(bulkResult.lastOp.t) - : bulkResult.lastOp.t; - } - - // Current OpTime TS - const opTimeTS = typeof opTime.ts === 'number' ? Long.fromNumber(opTime.ts) : opTime.ts; - const opTimeT = typeof opTime.t === 'number' ? Long.fromNumber(opTime.t) : opTime.t; - - // Compare the opTime's - if (bulkResult.lastOp == null) { - bulkResult.lastOp = opTime; - } else if (opTimeTS.greaterThan(lastOpTS)) { - bulkResult.lastOp = opTime; - } else if (opTimeTS.equals(lastOpTS)) { - if (opTimeT.greaterThan(lastOpT)) { - bulkResult.lastOp = opTime; - } - } - } - } - - // If we have an insert Batch type - if (batch.batchType === INSERT && result.n) { - bulkResult.nInserted = bulkResult.nInserted + result.n; - } - - // If we have an insert Batch type - if (batch.batchType === REMOVE && result.n) { - bulkResult.nRemoved = bulkResult.nRemoved + result.n; - } - - let nUpserted = 0; - - // We have an array of upserted values, we need to rewrite the indexes - if (Array.isArray(result.upserted)) { - nUpserted = result.upserted.length; - - for (let i = 0; i < result.upserted.length; i++) { - bulkResult.upserted.push({ - index: result.upserted[i].index + batch.originalZeroIndex, - _id: result.upserted[i]._id - }); - } - } else if (result.upserted) { - nUpserted = 1; - - bulkResult.upserted.push({ - index: batch.originalZeroIndex, - _id: result.upserted - }); - } - - // If we have an update Batch type - if (batch.batchType === UPDATE && result.n) { - const nModified = result.nModified; - bulkResult.nUpserted = bulkResult.nUpserted + nUpserted; - bulkResult.nMatched = bulkResult.nMatched + (result.n - nUpserted); - - if (typeof nModified === 'number') { - bulkResult.nModified = bulkResult.nModified + nModified; - } else { - bulkResult.nModified = null; - } - } - - if (Array.isArray(result.writeErrors)) { - for (let i = 0; i < result.writeErrors.length; i++) { - const writeError = { - index: batch.originalZeroIndex + result.writeErrors[i].index, - code: result.writeErrors[i].code, - errmsg: result.writeErrors[i].errmsg, - op: batch.operations[result.writeErrors[i].index] - }; - - bulkResult.writeErrors.push(new WriteError(writeError)); - } - } - - if (result.writeConcernError) { - bulkResult.writeConcernErrors.push(new WriteConcernError(result.writeConcernError)); - } -} - -function executeCommands(bulkOperation, options, callback) { - if (bulkOperation.s.batches.length === 0) { - return handleCallback(callback, null, new BulkWriteResult(bulkOperation.s.bulkResult)); - } - - const batch = bulkOperation.s.batches.shift(); - - function resultHandler(err, result) { - // Error is a driver related error not a bulk op error, terminate - if (((err && err.driver) || (err && err.message)) && !(err instanceof MongoWriteConcernError)) { - return handleCallback(callback, err); - } - - // If we have and error - if (err) err.ok = 0; - if (err instanceof MongoWriteConcernError) { - return handleMongoWriteConcernError(batch, bulkOperation.s.bulkResult, err, callback); - } - - // Merge the results together - const writeResult = new BulkWriteResult(bulkOperation.s.bulkResult); - const mergeResult = mergeBatchResults(batch, bulkOperation.s.bulkResult, err, result); - if (mergeResult != null) { - return handleCallback(callback, null, writeResult); - } - - if (bulkOperation.handleWriteError(callback, writeResult)) return; - - // Execute the next command in line - executeCommands(bulkOperation, options, callback); - } - - bulkOperation.finalOptionsHandler({ options, batch, resultHandler }, callback); -} - -/** - * handles write concern error - * - * @ignore - * @param {object} batch - * @param {object} bulkResult - * @param {boolean} ordered - * @param {WriteConcernError} err - * @param {function} callback - */ -function handleMongoWriteConcernError(batch, bulkResult, err, callback) { - mergeBatchResults(batch, bulkResult, null, err.result); - - const wrappedWriteConcernError = new WriteConcernError({ - errmsg: err.result.writeConcernError.errmsg, - code: err.result.writeConcernError.result - }); - return handleCallback( - callback, - new BulkWriteError(toError(wrappedWriteConcernError), new BulkWriteResult(bulkResult)), - null - ); -} - -/** - * @classdesc An error indicating an unsuccessful Bulk Write - */ -class BulkWriteError extends MongoError { - /** - * Creates a new BulkWriteError - * - * @param {Error|string|object} message The error message - * @param {BulkWriteResult} result The result of the bulk write operation - * @extends {MongoError} - */ - constructor(error, result) { - const message = error.err || error.errmsg || error.errMessage || error; - super(message); - - Object.assign(this, error); - - this.name = 'BulkWriteError'; - this.result = result; - } -} - -/** - * @classdesc A builder object that is returned from {@link BulkOperationBase#find}. - * Is used to build a write operation that involves a query filter. - */ -class FindOperators { - /** - * Creates a new FindOperators object. - * - * **NOTE:** Internal Type, do not instantiate directly - * @param {OrderedBulkOperation|UnorderedBulkOperation} bulkOperation - */ - constructor(bulkOperation) { - this.s = bulkOperation.s; - } - - /** - * Add a multiple update operation to the bulk operation - * - * @method - * @param {object} updateDocument An update field for an update operation. See {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-u u documentation} - * @throws {MongoError} If operation cannot be added to bulk write - * @return {OrderedBulkOperation|UnorderedBulkOperation} A reference to the parent BulkOperation - */ - update(updateDocument) { - // Perform upsert - const upsert = typeof this.s.currentOp.upsert === 'boolean' ? this.s.currentOp.upsert : false; - - // Establish the update command - const document = { - q: this.s.currentOp.selector, - u: updateDocument, - multi: true, - upsert: upsert - }; - - // Clear out current Op - this.s.currentOp = null; - return this.s.options.addToOperationsList(this, UPDATE, document); - } - - /** - * Add a single update operation to the bulk operation - * - * @method - * @param {object} updateDocument An update field for an update operation. See {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-u u documentation} - * @throws {MongoError} If operation cannot be added to bulk write - * @return {OrderedBulkOperation|UnorderedBulkOperation} A reference to the parent BulkOperation - */ - updateOne(updateDocument) { - // Perform upsert - const upsert = typeof this.s.currentOp.upsert === 'boolean' ? this.s.currentOp.upsert : false; - - // Establish the update command - const document = { - q: this.s.currentOp.selector, - u: updateDocument, - multi: false, - upsert: upsert - }; - - // Clear out current Op - this.s.currentOp = null; - return this.s.options.addToOperationsList(this, UPDATE, document); - } - - /** - * Add a replace one operation to the bulk operation - * - * @method - * @param {object} updateDocument the new document to replace the existing one with - * @throws {MongoError} If operation cannot be added to bulk write - * @return {OrderedBulkOperation|UnorderedBulkOperation} A reference to the parent BulkOperation - */ - replaceOne(updateDocument) { - this.updateOne(updateDocument); - } - - /** - * Upsert modifier for update bulk operation, noting that this operation is an upsert. - * - * @method - * @throws {MongoError} If operation cannot be added to bulk write - * @return {FindOperators} reference to self - */ - upsert() { - this.s.currentOp.upsert = true; - return this; - } - - /** - * Add a delete one operation to the bulk operation - * - * @method - * @throws {MongoError} If operation cannot be added to bulk write - * @return {OrderedBulkOperation|UnorderedBulkOperation} A reference to the parent BulkOperation - */ - deleteOne() { - // Establish the update command - const document = { - q: this.s.currentOp.selector, - limit: 1 - }; - - // Clear out current Op - this.s.currentOp = null; - return this.s.options.addToOperationsList(this, REMOVE, document); - } - - /** - * Add a delete many operation to the bulk operation - * - * @method - * @throws {MongoError} If operation cannot be added to bulk write - * @return {OrderedBulkOperation|UnorderedBulkOperation} A reference to the parent BulkOperation - */ - delete() { - // Establish the update command - const document = { - q: this.s.currentOp.selector, - limit: 0 - }; - - // Clear out current Op - this.s.currentOp = null; - return this.s.options.addToOperationsList(this, REMOVE, document); - } - - /** - * backwards compatability for deleteOne - */ - removeOne() { - return this.deleteOne(); - } - - /** - * backwards compatability for delete - */ - remove() { - return this.delete(); - } -} - -/** - * @classdesc Parent class to OrderedBulkOperation and UnorderedBulkOperation - * - * **NOTE:** Internal Type, do not instantiate directly - */ -class BulkOperationBase { - /** - * Create a new OrderedBulkOperation or UnorderedBulkOperation instance - * @property {number} length Get the number of operations in the bulk. - */ - constructor(topology, collection, options, isOrdered) { - // determine whether bulkOperation is ordered or unordered - this.isOrdered = isOrdered; - - options = options == null ? {} : options; - // TODO Bring from driver information in isMaster - // Get the namespace for the write operations - const namespace = collection.s.namespace; - // Used to mark operation as executed - const executed = false; - - // Current item - const currentOp = null; - - // Handle to the bson serializer, used to calculate running sizes - const bson = topology.bson; - - // Set max byte size - const isMaster = topology.lastIsMaster(); - const maxBatchSizeBytes = - isMaster && isMaster.maxBsonObjectSize ? isMaster.maxBsonObjectSize : 1024 * 1024 * 16; - const maxWriteBatchSize = - isMaster && isMaster.maxWriteBatchSize ? isMaster.maxWriteBatchSize : 1000; - - // Calculates the largest possible size of an Array key, represented as a BSON string - // element. This calculation: - // 1 byte for BSON type - // # of bytes = length of (string representation of (maxWriteBatchSize - 1)) - // + 1 bytes for null terminator - const maxKeySize = (maxWriteBatchSize - 1).toString(10).length + 2; - - // Final options for retryable writes and write concern - let finalOptions = Object.assign({}, options); - finalOptions = applyRetryableWrites(finalOptions, collection.s.db); - finalOptions = applyWriteConcern(finalOptions, { collection: collection }, options); - const writeConcern = finalOptions.writeConcern; - - // Get the promiseLibrary - const promiseLibrary = options.promiseLibrary || Promise; - - // Final results - const bulkResult = { - ok: 1, - writeErrors: [], - writeConcernErrors: [], - insertedIds: [], - nInserted: 0, - nUpserted: 0, - nMatched: 0, - nModified: 0, - nRemoved: 0, - upserted: [] - }; - - // Internal state - this.s = { - // Final result - bulkResult: bulkResult, - // Current batch state - currentBatch: null, - currentIndex: 0, - // ordered specific - currentBatchSize: 0, - currentBatchSizeBytes: 0, - // unordered specific - currentInsertBatch: null, - currentUpdateBatch: null, - currentRemoveBatch: null, - batches: [], - // Write concern - writeConcern: writeConcern, - // Max batch size options - maxBatchSizeBytes: maxBatchSizeBytes, - maxWriteBatchSize: maxWriteBatchSize, - maxKeySize, - // Namespace - namespace: namespace, - // BSON - bson: bson, - // Topology - topology: topology, - // Options - options: finalOptions, - // Current operation - currentOp: currentOp, - // Executed - executed: executed, - // Collection - collection: collection, - // Promise Library - promiseLibrary: promiseLibrary, - // Fundamental error - err: null, - // check keys - checkKeys: typeof options.checkKeys === 'boolean' ? options.checkKeys : true - }; - - // bypass Validation - if (options.bypassDocumentValidation === true) { - this.s.bypassDocumentValidation = true; - } - } - - /** - * Add a single insert document to the bulk operation - * - * @param {object} document the document to insert - * @throws {MongoError} - * @return {BulkOperationBase} A reference to self - * - * @example - * const bulkOp = collection.initializeOrderedBulkOp(); - * // Adds three inserts to the bulkOp. - * bulkOp - * .insert({ a: 1 }) - * .insert({ b: 2 }) - * .insert({ c: 3 }); - * await bulkOp.execute(); - */ - insert(document) { - if (this.s.collection.s.db.options.forceServerObjectId !== true && document._id == null) - document._id = new ObjectID(); - return this.s.options.addToOperationsList(this, INSERT, document); - } - - /** - * Builds a find operation for an update/updateOne/delete/deleteOne/replaceOne. - * Returns a builder object used to complete the definition of the operation. - * - * @method - * @param {object} selector The selector for the bulk operation. See {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-q q documentation} - * @throws {MongoError} if a selector is not specified - * @return {FindOperators} A helper object with which the write operation can be defined. - * - * @example - * const bulkOp = collection.initializeOrderedBulkOp(); - * - * // Add an updateOne to the bulkOp - * bulkOp.find({ a: 1 }).updateOne({ $set: { b: 2 } }); - * - * // Add an updateMany to the bulkOp - * bulkOp.find({ c: 3 }).update({ $set: { d: 4 } }); - * - * // Add an upsert - * bulkOp.find({ e: 5 }).upsert().updateOne({ $set: { f: 6 } }); - * - * // Add a deletion - * bulkOp.find({ g: 7 }).deleteOne(); - * - * // Add a multi deletion - * bulkOp.find({ h: 8 }).delete(); - * - * // Add a replaceOne - * bulkOp.find({ i: 9 }).replaceOne({ j: 10 }); - * - * // Update using a pipeline (requires Mongodb 4.2 or higher) - * bulk.find({ k: 11, y: { $exists: true }, z: { $exists: true } }).updateOne([ - * { $set: { total: { $sum: [ '$y', '$z' ] } } } - * ]); - * - * // All of the ops will now be executed - * await bulkOp.execute(); - */ - find(selector) { - if (!selector) { - throw toError('Bulk find operation must specify a selector'); - } - - // Save a current selector - this.s.currentOp = { - selector: selector - }; - - return new FindOperators(this); - } - - /** - * Specifies a raw operation to perform in the bulk write. - * - * @method - * @param {object} op The raw operation to perform. - * @return {BulkOperationBase} A reference to self - */ - raw(op) { - const key = Object.keys(op)[0]; - - // Set up the force server object id - const forceServerObjectId = - typeof this.s.options.forceServerObjectId === 'boolean' - ? this.s.options.forceServerObjectId - : this.s.collection.s.db.options.forceServerObjectId; - - // Update operations - if ( - (op.updateOne && op.updateOne.q) || - (op.updateMany && op.updateMany.q) || - (op.replaceOne && op.replaceOne.q) - ) { - op[key].multi = op.updateOne || op.replaceOne ? false : true; - return this.s.options.addToOperationsList(this, UPDATE, op[key]); - } - - // Crud spec update format - if (op.updateOne || op.updateMany || op.replaceOne) { - const multi = op.updateOne || op.replaceOne ? false : true; - const operation = { - q: op[key].filter, - u: op[key].update || op[key].replacement, - multi: multi - }; - if (this.isOrdered) { - operation.upsert = op[key].upsert ? true : false; - if (op.collation) operation.collation = op.collation; - } else { - if (op[key].upsert) operation.upsert = true; - } - if (op[key].arrayFilters) operation.arrayFilters = op[key].arrayFilters; - return this.s.options.addToOperationsList(this, UPDATE, operation); - } - - // Remove operations - if ( - op.removeOne || - op.removeMany || - (op.deleteOne && op.deleteOne.q) || - (op.deleteMany && op.deleteMany.q) - ) { - op[key].limit = op.removeOne ? 1 : 0; - return this.s.options.addToOperationsList(this, REMOVE, op[key]); - } - - // Crud spec delete operations, less efficient - if (op.deleteOne || op.deleteMany) { - const limit = op.deleteOne ? 1 : 0; - const operation = { q: op[key].filter, limit: limit }; - if (this.isOrdered) { - if (op.collation) operation.collation = op.collation; - } - return this.s.options.addToOperationsList(this, REMOVE, operation); - } - - // Insert operations - if (op.insertOne && op.insertOne.document == null) { - if (forceServerObjectId !== true && op.insertOne._id == null) - op.insertOne._id = new ObjectID(); - return this.s.options.addToOperationsList(this, INSERT, op.insertOne); - } else if (op.insertOne && op.insertOne.document) { - if (forceServerObjectId !== true && op.insertOne.document._id == null) - op.insertOne.document._id = new ObjectID(); - return this.s.options.addToOperationsList(this, INSERT, op.insertOne.document); - } - - if (op.insertMany) { - for (let i = 0; i < op.insertMany.length; i++) { - if (forceServerObjectId !== true && op.insertMany[i]._id == null) - op.insertMany[i]._id = new ObjectID(); - this.s.options.addToOperationsList(this, INSERT, op.insertMany[i]); - } - - return; - } - - // No valid type of operation - throw toError( - 'bulkWrite only supports insertOne, insertMany, updateOne, updateMany, removeOne, removeMany, deleteOne, deleteMany' - ); - } - - /** - * helper function to assist with promiseOrCallback behavior - * @ignore - * @param {*} err - * @param {*} callback - */ - _handleEarlyError(err, callback) { - if (typeof callback === 'function') { - callback(err, null); - return; - } - - return this.s.promiseLibrary.reject(err); - } - - /** - * An internal helper method. Do not invoke directly. Will be going away in the future - * - * @ignore - * @method - * @param {class} bulk either OrderedBulkOperation or UnorderdBulkOperation - * @param {object} writeConcern - * @param {object} options - * @param {function} callback - */ - bulkExecute(_writeConcern, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - if (typeof _writeConcern === 'function') { - callback = _writeConcern; - } else if (_writeConcern && typeof _writeConcern === 'object') { - this.s.writeConcern = _writeConcern; - } - - if (this.s.executed) { - const executedError = toError('batch cannot be re-executed'); - return this._handleEarlyError(executedError, callback); - } - - // If we have current batch - if (this.isOrdered) { - if (this.s.currentBatch) this.s.batches.push(this.s.currentBatch); - } else { - if (this.s.currentInsertBatch) this.s.batches.push(this.s.currentInsertBatch); - if (this.s.currentUpdateBatch) this.s.batches.push(this.s.currentUpdateBatch); - if (this.s.currentRemoveBatch) this.s.batches.push(this.s.currentRemoveBatch); - } - // If we have no operations in the bulk raise an error - if (this.s.batches.length === 0) { - const emptyBatchError = toError('Invalid Operation, no operations specified'); - return this._handleEarlyError(emptyBatchError, callback); - } - return { options, callback }; - } - - /** - * The callback format for results - * @callback BulkOperationBase~resultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {BulkWriteResult} result The bulk write result. - */ - - /** - * Execute the bulk operation - * - * @method - * @param {WriteConcern} [_writeConcern] Optional write concern. Can also be specified through options. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.fsync=false] Specify a file sync write concern. - * @param {BulkOperationBase~resultCallback} [callback] A callback that will be invoked when bulkWrite finishes/errors - * @throws {MongoError} Throws error if the bulk object has already been executed - * @throws {MongoError} Throws error if the bulk object does not have any operations - * @return {Promise|void} returns Promise if no callback passed - */ - execute(_writeConcern, options, callback) { - const ret = this.bulkExecute(_writeConcern, options, callback); - if (!ret || isPromiseLike(ret)) { - return ret; - } - - options = ret.options; - callback = ret.callback; - - return executeLegacyOperation(this.s.topology, executeCommands, [this, options, callback]); - } - - /** - * Handles final options before executing command - * - * An internal method. Do not invoke. Will not be accessible in the future - * - * @ignore - * @param {object} config - * @param {object} config.options - * @param {number} config.batch - * @param {function} config.resultHandler - * @param {function} callback - */ - finalOptionsHandler(config, callback) { - const finalOptions = Object.assign({ ordered: this.isOrdered }, config.options); - if (this.s.writeConcern != null) { - finalOptions.writeConcern = this.s.writeConcern; - } - - if (finalOptions.bypassDocumentValidation !== true) { - delete finalOptions.bypassDocumentValidation; - } - - // Set an operationIf if provided - if (this.operationId) { - config.resultHandler.operationId = this.operationId; - } - - // Serialize functions - if (this.s.options.serializeFunctions) { - finalOptions.serializeFunctions = true; - } - - // Ignore undefined - if (this.s.options.ignoreUndefined) { - finalOptions.ignoreUndefined = true; - } - - // Is the bypassDocumentValidation options specific - if (this.s.bypassDocumentValidation === true) { - finalOptions.bypassDocumentValidation = true; - } - - // Is the checkKeys option disabled - if (this.s.checkKeys === false) { - finalOptions.checkKeys = false; - } - - if (finalOptions.retryWrites) { - if (config.batch.batchType === UPDATE) { - finalOptions.retryWrites = - finalOptions.retryWrites && !config.batch.operations.some(op => op.multi); - } - - if (config.batch.batchType === REMOVE) { - finalOptions.retryWrites = - finalOptions.retryWrites && !config.batch.operations.some(op => op.limit === 0); - } - } - - try { - if (config.batch.batchType === INSERT) { - this.s.topology.insert( - this.s.namespace, - config.batch.operations, - finalOptions, - config.resultHandler - ); - } else if (config.batch.batchType === UPDATE) { - this.s.topology.update( - this.s.namespace, - config.batch.operations, - finalOptions, - config.resultHandler - ); - } else if (config.batch.batchType === REMOVE) { - this.s.topology.remove( - this.s.namespace, - config.batch.operations, - finalOptions, - config.resultHandler - ); - } - } catch (err) { - // Force top level error - err.ok = 0; - // Merge top level error and return - handleCallback(callback, null, mergeBatchResults(config.batch, this.s.bulkResult, err, null)); - } - } - - /** - * Handles the write error before executing commands - * - * An internal helper method. Do not invoke directly. Will be going away in the future - * - * @ignore - * @param {function} callback - * @param {BulkWriteResult} writeResult - * @param {class} self either OrderedBulkOperation or UnorderdBulkOperation - */ - handleWriteError(callback, writeResult) { - if (this.s.bulkResult.writeErrors.length > 0) { - if (this.s.bulkResult.writeErrors.length === 1) { - handleCallback( - callback, - new BulkWriteError(toError(this.s.bulkResult.writeErrors[0]), writeResult), - null - ); - return true; - } - - const msg = this.s.bulkResult.writeErrors[0].errmsg - ? this.s.bulkResult.writeErrors[0].errmsg - : 'write operation failed'; - - handleCallback( - callback, - new BulkWriteError( - toError({ - message: msg, - code: this.s.bulkResult.writeErrors[0].code, - writeErrors: this.s.bulkResult.writeErrors - }), - writeResult - ), - null - ); - return true; - } else if (writeResult.getWriteConcernError()) { - handleCallback( - callback, - new BulkWriteError(toError(writeResult.getWriteConcernError()), writeResult), - null - ); - return true; - } - } -} - -Object.defineProperty(BulkOperationBase.prototype, 'length', { - enumerable: true, - get: function() { - return this.s.currentIndex; - } -}); - -// Exports symbols -module.exports = { - Batch, - BulkOperationBase, - bson, - INSERT: INSERT, - UPDATE: UPDATE, - REMOVE: REMOVE, - BulkWriteError -}; diff --git a/scripts/2.5/node_modules/mongodb/lib/bulk/ordered.js b/scripts/2.5/node_modules/mongodb/lib/bulk/ordered.js deleted file mode 100644 index e2507b86..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/bulk/ordered.js +++ /dev/null @@ -1,105 +0,0 @@ -'use strict'; - -const common = require('./common'); -const BulkOperationBase = common.BulkOperationBase; -const Batch = common.Batch; -const bson = common.bson; -const utils = require('../utils'); -const toError = utils.toError; - -/** - * Add to internal list of Operations - * - * @ignore - * @param {OrderedBulkOperation} bulkOperation - * @param {number} docType number indicating the document type - * @param {object} document - * @return {OrderedBulkOperation} - */ -function addToOperationsList(bulkOperation, docType, document) { - // Get the bsonSize - const bsonSize = bson.calculateObjectSize(document, { - checkKeys: false, - - // Since we don't know what the user selected for BSON options here, - // err on the safe side, and check the size with ignoreUndefined: false. - ignoreUndefined: false - }); - - // Throw error if the doc is bigger than the max BSON size - if (bsonSize >= bulkOperation.s.maxBatchSizeBytes) - throw toError('document is larger than the maximum size ' + bulkOperation.s.maxBatchSizeBytes); - - // Create a new batch object if we don't have a current one - if (bulkOperation.s.currentBatch == null) - bulkOperation.s.currentBatch = new Batch(docType, bulkOperation.s.currentIndex); - - const maxKeySize = bulkOperation.s.maxKeySize; - - // Check if we need to create a new batch - if ( - bulkOperation.s.currentBatchSize + 1 >= bulkOperation.s.maxWriteBatchSize || - bulkOperation.s.currentBatchSizeBytes + maxKeySize + bsonSize >= - bulkOperation.s.maxBatchSizeBytes || - bulkOperation.s.currentBatch.batchType !== docType - ) { - // Save the batch to the execution stack - bulkOperation.s.batches.push(bulkOperation.s.currentBatch); - - // Create a new batch - bulkOperation.s.currentBatch = new Batch(docType, bulkOperation.s.currentIndex); - - // Reset the current size trackers - bulkOperation.s.currentBatchSize = 0; - bulkOperation.s.currentBatchSizeBytes = 0; - } - - if (docType === common.INSERT) { - bulkOperation.s.bulkResult.insertedIds.push({ - index: bulkOperation.s.currentIndex, - _id: document._id - }); - } - - // We have an array of documents - if (Array.isArray(document)) { - throw toError('operation passed in cannot be an Array'); - } - - bulkOperation.s.currentBatch.originalIndexes.push(bulkOperation.s.currentIndex); - bulkOperation.s.currentBatch.operations.push(document); - bulkOperation.s.currentBatchSize += 1; - bulkOperation.s.currentBatchSizeBytes += maxKeySize + bsonSize; - bulkOperation.s.currentIndex += 1; - - // Return bulkOperation - return bulkOperation; -} - -/** - * Create a new OrderedBulkOperation instance (INTERNAL TYPE, do not instantiate directly) - * @class - * @extends BulkOperationBase - * @property {number} length Get the number of operations in the bulk. - * @return {OrderedBulkOperation} a OrderedBulkOperation instance. - */ -class OrderedBulkOperation extends BulkOperationBase { - constructor(topology, collection, options) { - options = options || {}; - options = Object.assign(options, { addToOperationsList }); - - super(topology, collection, options, true); - } -} - -/** - * Returns an unordered batch object - * @ignore - */ -function initializeOrderedBulkOp(topology, collection, options) { - return new OrderedBulkOperation(topology, collection, options); -} - -initializeOrderedBulkOp.OrderedBulkOperation = OrderedBulkOperation; -module.exports = initializeOrderedBulkOp; -module.exports.Bulk = OrderedBulkOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/bulk/unordered.js b/scripts/2.5/node_modules/mongodb/lib/bulk/unordered.js deleted file mode 100644 index 999de3c4..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/bulk/unordered.js +++ /dev/null @@ -1,118 +0,0 @@ -'use strict'; - -const common = require('./common'); -const BulkOperationBase = common.BulkOperationBase; -const Batch = common.Batch; -const bson = common.bson; -const utils = require('../utils'); -const toError = utils.toError; - -/** - * Add to internal list of Operations - * - * @ignore - * @param {UnorderedBulkOperation} bulkOperation - * @param {number} docType number indicating the document type - * @param {object} document - * @return {UnorderedBulkOperation} - */ -function addToOperationsList(bulkOperation, docType, document) { - // Get the bsonSize - const bsonSize = bson.calculateObjectSize(document, { - checkKeys: false, - - // Since we don't know what the user selected for BSON options here, - // err on the safe side, and check the size with ignoreUndefined: false. - ignoreUndefined: false - }); - // Throw error if the doc is bigger than the max BSON size - if (bsonSize >= bulkOperation.s.maxBatchSizeBytes) - throw toError('document is larger than the maximum size ' + bulkOperation.s.maxBatchSizeBytes); - // Holds the current batch - bulkOperation.s.currentBatch = null; - // Get the right type of batch - if (docType === common.INSERT) { - bulkOperation.s.currentBatch = bulkOperation.s.currentInsertBatch; - } else if (docType === common.UPDATE) { - bulkOperation.s.currentBatch = bulkOperation.s.currentUpdateBatch; - } else if (docType === common.REMOVE) { - bulkOperation.s.currentBatch = bulkOperation.s.currentRemoveBatch; - } - - const maxKeySize = bulkOperation.s.maxKeySize; - - // Create a new batch object if we don't have a current one - if (bulkOperation.s.currentBatch == null) - bulkOperation.s.currentBatch = new Batch(docType, bulkOperation.s.currentIndex); - - // Check if we need to create a new batch - if ( - bulkOperation.s.currentBatch.size + 1 >= bulkOperation.s.maxWriteBatchSize || - bulkOperation.s.currentBatch.sizeBytes + maxKeySize + bsonSize >= - bulkOperation.s.maxBatchSizeBytes || - bulkOperation.s.currentBatch.batchType !== docType - ) { - // Save the batch to the execution stack - bulkOperation.s.batches.push(bulkOperation.s.currentBatch); - - // Create a new batch - bulkOperation.s.currentBatch = new Batch(docType, bulkOperation.s.currentIndex); - } - - // We have an array of documents - if (Array.isArray(document)) { - throw toError('operation passed in cannot be an Array'); - } - - bulkOperation.s.currentBatch.operations.push(document); - bulkOperation.s.currentBatch.originalIndexes.push(bulkOperation.s.currentIndex); - bulkOperation.s.currentIndex = bulkOperation.s.currentIndex + 1; - - // Save back the current Batch to the right type - if (docType === common.INSERT) { - bulkOperation.s.currentInsertBatch = bulkOperation.s.currentBatch; - bulkOperation.s.bulkResult.insertedIds.push({ - index: bulkOperation.s.bulkResult.insertedIds.length, - _id: document._id - }); - } else if (docType === common.UPDATE) { - bulkOperation.s.currentUpdateBatch = bulkOperation.s.currentBatch; - } else if (docType === common.REMOVE) { - bulkOperation.s.currentRemoveBatch = bulkOperation.s.currentBatch; - } - - // Update current batch size - bulkOperation.s.currentBatch.size += 1; - bulkOperation.s.currentBatch.sizeBytes += maxKeySize + bsonSize; - - // Return bulkOperation - return bulkOperation; -} - -/** - * Create a new UnorderedBulkOperation instance (INTERNAL TYPE, do not instantiate directly) - * @class - * @extends BulkOperationBase - * @property {number} length Get the number of operations in the bulk. - * @return {UnorderedBulkOperation} a UnorderedBulkOperation instance. - */ -class UnorderedBulkOperation extends BulkOperationBase { - constructor(topology, collection, options) { - options = options || {}; - options = Object.assign(options, { addToOperationsList }); - - super(topology, collection, options, false); - } -} - -/** - * Returns an unordered batch object - * @ignore - */ -function initializeUnorderedBulkOp(topology, collection, options) { - return new UnorderedBulkOperation(topology, collection, options); -} - -initializeUnorderedBulkOp.UnorderedBulkOperation = UnorderedBulkOperation; -module.exports = initializeUnorderedBulkOp; -module.exports.Bulk = UnorderedBulkOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/change_stream.js b/scripts/2.5/node_modules/mongodb/lib/change_stream.js deleted file mode 100644 index 4cc779de..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/change_stream.js +++ /dev/null @@ -1,576 +0,0 @@ -'use strict'; - -const EventEmitter = require('events'); -const isResumableError = require('./error').isResumableError; -const MongoError = require('./core').MongoError; -const Cursor = require('./cursor'); -const relayEvents = require('./core/utils').relayEvents; -const maxWireVersion = require('./core/utils').maxWireVersion; -const AggregateOperation = require('./operations/aggregate'); - -const CHANGE_STREAM_OPTIONS = ['resumeAfter', 'startAfter', 'startAtOperationTime', 'fullDocument']; -const CURSOR_OPTIONS = ['batchSize', 'maxAwaitTimeMS', 'collation', 'readPreference'].concat( - CHANGE_STREAM_OPTIONS -); - -const CHANGE_DOMAIN_TYPES = { - COLLECTION: Symbol('Collection'), - DATABASE: Symbol('Database'), - CLUSTER: Symbol('Cluster') -}; - -/** - * @typedef ResumeToken - * @description Represents the logical starting point for a new or resuming {@link ChangeStream} on the server. - * @see https://docs.mongodb.com/master/changeStreams/#change-stream-resume-token - */ - -/** - * @typedef OperationTime - * @description Represents a specific point in time on a server. Can be retrieved by using {@link Db#command} - * @see https://docs.mongodb.com/manual/reference/method/db.runCommand/#response - */ - -/** - * @typedef ChangeStreamOptions - * @description Options that can be passed to a ChangeStream. Note that startAfter, resumeAfter, and startAtOperationTime are all mutually exclusive, and the server will error if more than one is specified. - * @property {string} [fullDocument='default'] Allowed values: ‘default’, ‘updateLookup’. When set to ‘updateLookup’, the change stream will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred. - * @property {number} [maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a change stream query. - * @property {ResumeToken} [resumeAfter] Allows you to start a changeStream after a specified event. See {@link https://docs.mongodb.com/master/changeStreams/#resumeafter-for-change-streams|ChangeStream documentation}. - * @property {ResumeToken} [startAfter] Similar to resumeAfter, but will allow you to start after an invalidated event. See {@link https://docs.mongodb.com/master/changeStreams/#startafter-for-change-streams|ChangeStream documentation}. - * @property {OperationTime} [startAtOperationTime] Will start the changeStream after the specified operationTime. - * @property {number} [batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. - * @property {object} [collation] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. - * @property {ReadPreference} [readPreference] The read preference. Defaults to the read preference of the database or collection. See {@link https://docs.mongodb.com/manual/reference/read-preference|read preference documentation}. - */ - -/** - * Creates a new Change Stream instance. Normally created using {@link Collection#watch|Collection.watch()}. - * @class ChangeStream - * @since 3.0.0 - * @param {(MongoClient|Db|Collection)} parent The parent object that created this change stream - * @param {Array} pipeline An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents - * @param {ChangeStreamOptions} [options] Optional settings - * @fires ChangeStream#close - * @fires ChangeStream#change - * @fires ChangeStream#end - * @fires ChangeStream#error - * @fires ChangeStream#resumeTokenChanged - * @return {ChangeStream} a ChangeStream instance. - */ -class ChangeStream extends EventEmitter { - constructor(parent, pipeline, options) { - super(); - const Collection = require('./collection'); - const Db = require('./db'); - const MongoClient = require('./mongo_client'); - - this.pipeline = pipeline || []; - this.options = options || {}; - - this.parent = parent; - this.namespace = parent.s.namespace; - if (parent instanceof Collection) { - this.type = CHANGE_DOMAIN_TYPES.COLLECTION; - this.topology = parent.s.db.serverConfig; - } else if (parent instanceof Db) { - this.type = CHANGE_DOMAIN_TYPES.DATABASE; - this.topology = parent.serverConfig; - } else if (parent instanceof MongoClient) { - this.type = CHANGE_DOMAIN_TYPES.CLUSTER; - this.topology = parent.topology; - } else { - throw new TypeError( - 'parent provided to ChangeStream constructor is not an instance of Collection, Db, or MongoClient' - ); - } - - this.promiseLibrary = parent.s.promiseLibrary; - if (!this.options.readPreference && parent.s.readPreference) { - this.options.readPreference = parent.s.readPreference; - } - - // Create contained Change Stream cursor - this.cursor = createChangeStreamCursor(this, options); - - // Listen for any `change` listeners being added to ChangeStream - this.on('newListener', eventName => { - if (eventName === 'change' && this.cursor && this.listenerCount('change') === 0) { - this.cursor.on('data', change => - processNewChange({ changeStream: this, change, eventEmitter: true }) - ); - } - }); - - // Listen for all `change` listeners being removed from ChangeStream - this.on('removeListener', eventName => { - if (eventName === 'change' && this.listenerCount('change') === 0 && this.cursor) { - this.cursor.removeAllListeners('data'); - } - }); - } - - /** - * @property {ResumeToken} resumeToken - * The cached resume token that will be used to resume - * after the most recently returned change. - */ - get resumeToken() { - return this.cursor.resumeToken; - } - - /** - * Check if there is any document still available in the Change Stream - * @function ChangeStream.prototype.hasNext - * @param {ChangeStream~resultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ - hasNext(callback) { - return this.cursor.hasNext(callback); - } - - /** - * Get the next available document from the Change Stream, returns null if no more documents are available. - * @function ChangeStream.prototype.next - * @param {ChangeStream~resultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ - next(callback) { - var self = this; - if (this.isClosed()) { - if (callback) return callback(new Error('Change Stream is not open.'), null); - return self.promiseLibrary.reject(new Error('Change Stream is not open.')); - } - - return this.cursor - .next() - .then(change => processNewChange({ changeStream: self, change, callback })) - .catch(error => processNewChange({ changeStream: self, error, callback })); - } - - /** - * Is the cursor closed - * @method ChangeStream.prototype.isClosed - * @return {boolean} - */ - isClosed() { - if (this.cursor) { - return this.cursor.isClosed(); - } - return true; - } - - /** - * Close the Change Stream - * @method ChangeStream.prototype.close - * @param {ChangeStream~resultCallback} [callback] The result callback. - * @return {Promise} returns Promise if no callback passed - */ - close(callback) { - if (!this.cursor) { - if (callback) return callback(); - return this.promiseLibrary.resolve(); - } - - // Tidy up the existing cursor - const cursor = this.cursor; - - if (callback) { - return cursor.close(err => { - ['data', 'close', 'end', 'error'].forEach(event => cursor.removeAllListeners(event)); - delete this.cursor; - - return callback(err); - }); - } - - const PromiseCtor = this.promiseLibrary || Promise; - return new PromiseCtor((resolve, reject) => { - cursor.close(err => { - ['data', 'close', 'end', 'error'].forEach(event => cursor.removeAllListeners(event)); - delete this.cursor; - - if (err) return reject(err); - resolve(); - }); - }); - } - - /** - * This method pulls all the data out of a readable stream, and writes it to the supplied destination, automatically managing the flow so that the destination is not overwhelmed by a fast readable stream. - * @method - * @param {Writable} destination The destination for writing data - * @param {object} [options] {@link https://nodejs.org/api/stream.html#stream_readable_pipe_destination_options|Pipe options} - * @return {null} - */ - pipe(destination, options) { - if (!this.pipeDestinations) { - this.pipeDestinations = []; - } - this.pipeDestinations.push(destination); - return this.cursor.pipe(destination, options); - } - - /** - * This method will remove the hooks set up for a previous pipe() call. - * @param {Writable} [destination] The destination for writing data - * @return {null} - */ - unpipe(destination) { - if (this.pipeDestinations && this.pipeDestinations.indexOf(destination) > -1) { - this.pipeDestinations.splice(this.pipeDestinations.indexOf(destination), 1); - } - return this.cursor.unpipe(destination); - } - - /** - * Return a modified Readable stream including a possible transform method. - * @method - * @param {object} [options] Optional settings. - * @param {function} [options.transform] A transformation method applied to each document emitted by the stream. - * @return {Cursor} - */ - stream(options) { - this.streamOptions = options; - return this.cursor.stream(options); - } - - /** - * This method will cause a stream in flowing mode to stop emitting data events. Any data that becomes available will remain in the internal buffer. - * @return {null} - */ - pause() { - return this.cursor.pause(); - } - - /** - * This method will cause the readable stream to resume emitting data events. - * @return {null} - */ - resume() { - return this.cursor.resume(); - } -} - -class ChangeStreamCursor extends Cursor { - constructor(topology, operation, options) { - super(topology, operation, options); - - options = options || {}; - this._resumeToken = null; - this.startAtOperationTime = options.startAtOperationTime; - - if (options.startAfter) { - this.resumeToken = options.startAfter; - } else if (options.resumeAfter) { - this.resumeToken = options.resumeAfter; - } - } - - set resumeToken(token) { - this._resumeToken = token; - this.emit('resumeTokenChanged', token); - } - - get resumeToken() { - return this._resumeToken; - } - - get resumeOptions() { - const result = {}; - for (const optionName of CURSOR_OPTIONS) { - if (this.options[optionName]) result[optionName] = this.options[optionName]; - } - - if (this.resumeToken || this.startAtOperationTime) { - ['resumeAfter', 'startAfter', 'startAtOperationTime'].forEach(key => delete result[key]); - - if (this.resumeToken) { - result.resumeAfter = this.resumeToken; - } else if (this.startAtOperationTime && maxWireVersion(this.server) >= 7) { - result.startAtOperationTime = this.startAtOperationTime; - } - } - - return result; - } - - _initializeCursor(callback) { - super._initializeCursor((err, result) => { - if (err) { - callback(err, null); - return; - } - - const response = result.documents[0]; - - if ( - this.startAtOperationTime == null && - this.resumeAfter == null && - this.startAfter == null && - maxWireVersion(this.server) >= 7 - ) { - this.startAtOperationTime = response.operationTime; - } - - const cursor = response.cursor; - if (cursor.postBatchResumeToken) { - this.cursorState.postBatchResumeToken = cursor.postBatchResumeToken; - - if (cursor.firstBatch.length === 0) { - this.resumeToken = cursor.postBatchResumeToken; - } - } - - this.emit('response'); - callback(err, result); - }); - } - - _getMore(callback) { - super._getMore((err, response) => { - if (err) { - callback(err, null); - return; - } - - const cursor = response.cursor; - if (cursor.postBatchResumeToken) { - this.cursorState.postBatchResumeToken = cursor.postBatchResumeToken; - - if (cursor.nextBatch.length === 0) { - this.resumeToken = cursor.postBatchResumeToken; - } - } - - this.emit('response'); - callback(err, response); - }); - } -} - -/** - * @event ChangeStreamCursor#response - * internal event DO NOT USE - * @ignore - */ - -// Create a new change stream cursor based on self's configuration -function createChangeStreamCursor(self, options) { - const changeStreamStageOptions = { fullDocument: options.fullDocument || 'default' }; - applyKnownOptions(changeStreamStageOptions, options, CHANGE_STREAM_OPTIONS); - if (self.type === CHANGE_DOMAIN_TYPES.CLUSTER) { - changeStreamStageOptions.allChangesForCluster = true; - } - - const pipeline = [{ $changeStream: changeStreamStageOptions }].concat(self.pipeline); - const cursorOptions = applyKnownOptions({}, options, CURSOR_OPTIONS); - const changeStreamCursor = new ChangeStreamCursor( - self.topology, - new AggregateOperation(self.parent, pipeline, options), - cursorOptions - ); - - relayEvents(changeStreamCursor, self, ['resumeTokenChanged', 'end', 'close']); - - /** - * Fired for each new matching change in the specified namespace. Attaching a `change` - * event listener to a Change Stream will switch the stream into flowing mode. Data will - * then be passed as soon as it is available. - * - * @event ChangeStream#change - * @type {object} - */ - if (self.listenerCount('change') > 0) { - changeStreamCursor.on('data', function(change) { - processNewChange({ changeStream: self, change, eventEmitter: true }); - }); - } - - /** - * Change stream close event - * - * @event ChangeStream#close - * @type {null} - */ - - /** - * Change stream end event - * - * @event ChangeStream#end - * @type {null} - */ - - /** - * Emitted each time the change stream stores a new resume token. - * - * @event ChangeStream#resumeTokenChanged - * @type {ResumeToken} - */ - - /** - * Fired when the stream encounters an error. - * - * @event ChangeStream#error - * @type {Error} - */ - changeStreamCursor.on('error', function(error) { - processNewChange({ changeStream: self, error, eventEmitter: true }); - }); - - if (self.pipeDestinations) { - const cursorStream = changeStreamCursor.stream(self.streamOptions); - for (let pipeDestination in self.pipeDestinations) { - cursorStream.pipe(pipeDestination); - } - } - - return changeStreamCursor; -} - -function applyKnownOptions(target, source, optionNames) { - optionNames.forEach(name => { - if (source[name]) { - target[name] = source[name]; - } - }); - - return target; -} - -// This method performs a basic server selection loop, satisfying the requirements of -// ChangeStream resumability until the new SDAM layer can be used. -const SELECTION_TIMEOUT = 30000; -function waitForTopologyConnected(topology, options, callback) { - setTimeout(() => { - if (options && options.start == null) options.start = process.hrtime(); - const start = options.start || process.hrtime(); - const timeout = options.timeout || SELECTION_TIMEOUT; - const readPreference = options.readPreference; - - if (topology.isConnected({ readPreference })) return callback(null, null); - const hrElapsed = process.hrtime(start); - const elapsed = (hrElapsed[0] * 1e9 + hrElapsed[1]) / 1e6; - if (elapsed > timeout) return callback(new MongoError('Timed out waiting for connection')); - waitForTopologyConnected(topology, options, callback); - }, 3000); // this is an arbitrary wait time to allow SDAM to transition -} - -// Handle new change events. This method brings together the routes from the callback, event emitter, and promise ways of using ChangeStream. -function processNewChange(args) { - const changeStream = args.changeStream; - const error = args.error; - const change = args.change; - const callback = args.callback; - const eventEmitter = args.eventEmitter || false; - - // If the changeStream is closed, then it should not process a change. - if (changeStream.isClosed()) { - // We do not error in the eventEmitter case. - if (eventEmitter) { - return; - } - - const error = new MongoError('ChangeStream is closed'); - return typeof callback === 'function' - ? callback(error, null) - : changeStream.promiseLibrary.reject(error); - } - - const cursor = changeStream.cursor; - const topology = changeStream.topology; - const options = changeStream.cursor.options; - - if (error) { - if (isResumableError(error) && !changeStream.attemptingResume) { - changeStream.attemptingResume = true; - - // stop listening to all events from old cursor - ['data', 'close', 'end', 'error'].forEach(event => - changeStream.cursor.removeAllListeners(event) - ); - - // close internal cursor, ignore errors - changeStream.cursor.close(); - - // attempt recreating the cursor - if (eventEmitter) { - waitForTopologyConnected(topology, { readPreference: options.readPreference }, err => { - if (err) { - changeStream.emit('error', err); - changeStream.emit('close'); - return; - } - changeStream.cursor = createChangeStreamCursor(changeStream, cursor.resumeOptions); - }); - - return; - } - - if (callback) { - waitForTopologyConnected(topology, { readPreference: options.readPreference }, err => { - if (err) return callback(err, null); - - changeStream.cursor = createChangeStreamCursor(changeStream, cursor.resumeOptions); - changeStream.next(callback); - }); - - return; - } - - return new Promise((resolve, reject) => { - waitForTopologyConnected(topology, { readPreference: options.readPreference }, err => { - if (err) return reject(err); - resolve(); - }); - }) - .then( - () => (changeStream.cursor = createChangeStreamCursor(changeStream, cursor.resumeOptions)) - ) - .then(() => changeStream.next()); - } - - if (eventEmitter) return changeStream.emit('error', error); - if (typeof callback === 'function') return callback(error, null); - return changeStream.promiseLibrary.reject(error); - } - - changeStream.attemptingResume = false; - - if (change && !change._id) { - const noResumeTokenError = new Error( - 'A change stream document has been received that lacks a resume token (_id).' - ); - - if (eventEmitter) return changeStream.emit('error', noResumeTokenError); - if (typeof callback === 'function') return callback(noResumeTokenError, null); - return changeStream.promiseLibrary.reject(noResumeTokenError); - } - - // cache the resume token - if (cursor.bufferedCount() === 0 && cursor.cursorState.postBatchResumeToken) { - cursor.resumeToken = cursor.cursorState.postBatchResumeToken; - } else { - cursor.resumeToken = change._id; - } - - // wipe the startAtOperationTime if there was one so that there won't be a conflict - // between resumeToken and startAtOperationTime if we need to reconnect the cursor - changeStream.options.startAtOperationTime = undefined; - - // Return the change - if (eventEmitter) return changeStream.emit('change', change); - if (typeof callback === 'function') return callback(error, change); - return changeStream.promiseLibrary.resolve(change); -} - -/** - * The callback format for results - * @callback ChangeStream~resultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {(object|null)} result The result object if the command was executed successfully. - */ - -module.exports = ChangeStream; diff --git a/scripts/2.5/node_modules/mongodb/lib/collection.js b/scripts/2.5/node_modules/mongodb/lib/collection.js deleted file mode 100644 index 49edbdbe..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/collection.js +++ /dev/null @@ -1,2113 +0,0 @@ -'use strict'; - -const deprecate = require('util').deprecate; -const deprecateOptions = require('./utils').deprecateOptions; -const checkCollectionName = require('./utils').checkCollectionName; -const ObjectID = require('./core').BSON.ObjectID; -const MongoError = require('./core').MongoError; -const toError = require('./utils').toError; -const normalizeHintField = require('./utils').normalizeHintField; -const decorateCommand = require('./utils').decorateCommand; -const decorateWithCollation = require('./utils').decorateWithCollation; -const decorateWithReadConcern = require('./utils').decorateWithReadConcern; -const formattedOrderClause = require('./utils').formattedOrderClause; -const ReadPreference = require('./core').ReadPreference; -const unordered = require('./bulk/unordered'); -const ordered = require('./bulk/ordered'); -const ChangeStream = require('./change_stream'); -const executeLegacyOperation = require('./utils').executeLegacyOperation; -const resolveReadPreference = require('./utils').resolveReadPreference; -const WriteConcern = require('./write_concern'); -const ReadConcern = require('./read_concern'); -const MongoDBNamespace = require('./utils').MongoDBNamespace; -const AggregationCursor = require('./aggregation_cursor'); -const CommandCursor = require('./command_cursor'); - -// Operations -const checkForAtomicOperators = require('./operations/collection_ops').checkForAtomicOperators; -const ensureIndex = require('./operations/collection_ops').ensureIndex; -const group = require('./operations/collection_ops').group; -const parallelCollectionScan = require('./operations/collection_ops').parallelCollectionScan; -const removeDocuments = require('./operations/common_functions').removeDocuments; -const save = require('./operations/collection_ops').save; -const updateDocuments = require('./operations/common_functions').updateDocuments; - -const AggregateOperation = require('./operations/aggregate'); -const BulkWriteOperation = require('./operations/bulk_write'); -const CountDocumentsOperation = require('./operations/count_documents'); -const CreateIndexOperation = require('./operations/create_index'); -const CreateIndexesOperation = require('./operations/create_indexes'); -const DeleteManyOperation = require('./operations/delete_many'); -const DeleteOneOperation = require('./operations/delete_one'); -const DistinctOperation = require('./operations/distinct'); -const DropCollectionOperation = require('./operations/drop').DropCollectionOperation; -const DropIndexOperation = require('./operations/drop_index'); -const DropIndexesOperation = require('./operations/drop_indexes'); -const EstimatedDocumentCountOperation = require('./operations/estimated_document_count'); -const FindOperation = require('./operations/find'); -const FindOneOperation = require('./operations/find_one'); -const FindAndModifyOperation = require('./operations/find_and_modify'); -const FindOneAndDeleteOperation = require('./operations/find_one_and_delete'); -const FindOneAndReplaceOperation = require('./operations/find_one_and_replace'); -const FindOneAndUpdateOperation = require('./operations/find_one_and_update'); -const GeoHaystackSearchOperation = require('./operations/geo_haystack_search'); -const IndexesOperation = require('./operations/indexes'); -const IndexExistsOperation = require('./operations/index_exists'); -const IndexInformationOperation = require('./operations/index_information'); -const InsertManyOperation = require('./operations/insert_many'); -const InsertOneOperation = require('./operations/insert_one'); -const IsCappedOperation = require('./operations/is_capped'); -const ListIndexesOperation = require('./operations/list_indexes'); -const MapReduceOperation = require('./operations/map_reduce'); -const OptionsOperation = require('./operations/options_operation'); -const RenameOperation = require('./operations/rename'); -const ReIndexOperation = require('./operations/re_index'); -const ReplaceOneOperation = require('./operations/replace_one'); -const StatsOperation = require('./operations/stats'); -const UpdateManyOperation = require('./operations/update_many'); -const UpdateOneOperation = require('./operations/update_one'); - -const executeOperation = require('./operations/execute_operation'); - -/** - * @fileOverview The **Collection** class is an internal class that embodies a MongoDB collection - * allowing for insert/update/remove/find and other command operation on that MongoDB collection. - * - * **COLLECTION Cannot directly be instantiated** - * @example - * const MongoClient = require('mongodb').MongoClient; - * const test = require('assert'); - * // Connection url - * const url = 'mongodb://localhost:27017'; - * // Database Name - * const dbName = 'test'; - * // Connect using MongoClient - * MongoClient.connect(url, function(err, client) { - * // Create a collection we want to drop later - * const col = client.db(dbName).collection('createIndexExample1'); - * // Show that duplicate records got dropped - * col.find({}).toArray(function(err, items) { - * test.equal(null, err); - * test.equal(4, items.length); - * client.close(); - * }); - * }); - */ - -const mergeKeys = ['ignoreUndefined']; - -/** - * Create a new Collection instance (INTERNAL TYPE, do not instantiate directly) - * @class - * @property {string} collectionName Get the collection name. - * @property {string} namespace Get the full collection namespace. - * @property {object} writeConcern The current write concern values. - * @property {object} readConcern The current read concern values. - * @property {object} hint Get current index hint for collection. - * @return {Collection} a Collection instance. - */ -function Collection(db, topology, dbName, name, pkFactory, options) { - checkCollectionName(name); - - // Unpack variables - const internalHint = null; - const slaveOk = options == null || options.slaveOk == null ? db.slaveOk : options.slaveOk; - const serializeFunctions = - options == null || options.serializeFunctions == null - ? db.s.options.serializeFunctions - : options.serializeFunctions; - const raw = options == null || options.raw == null ? db.s.options.raw : options.raw; - const promoteLongs = - options == null || options.promoteLongs == null - ? db.s.options.promoteLongs - : options.promoteLongs; - const promoteValues = - options == null || options.promoteValues == null - ? db.s.options.promoteValues - : options.promoteValues; - const promoteBuffers = - options == null || options.promoteBuffers == null - ? db.s.options.promoteBuffers - : options.promoteBuffers; - const collectionHint = null; - - const namespace = new MongoDBNamespace(dbName, name); - - // Get the promiseLibrary - const promiseLibrary = options.promiseLibrary || Promise; - - // Set custom primary key factory if provided - pkFactory = pkFactory == null ? ObjectID : pkFactory; - - // Internal state - this.s = { - // Set custom primary key factory if provided - pkFactory: pkFactory, - // Db - db: db, - // Topology - topology: topology, - // Options - options: options, - // Namespace - namespace: namespace, - // Read preference - readPreference: ReadPreference.fromOptions(options), - // SlaveOK - slaveOk: slaveOk, - // Serialize functions - serializeFunctions: serializeFunctions, - // Raw - raw: raw, - // promoteLongs - promoteLongs: promoteLongs, - // promoteValues - promoteValues: promoteValues, - // promoteBuffers - promoteBuffers: promoteBuffers, - // internalHint - internalHint: internalHint, - // collectionHint - collectionHint: collectionHint, - // Promise library - promiseLibrary: promiseLibrary, - // Read Concern - readConcern: ReadConcern.fromOptions(options), - // Write Concern - writeConcern: WriteConcern.fromOptions(options) - }; -} - -Object.defineProperty(Collection.prototype, 'dbName', { - enumerable: true, - get: function() { - return this.s.namespace.db; - } -}); - -Object.defineProperty(Collection.prototype, 'collectionName', { - enumerable: true, - get: function() { - return this.s.namespace.collection; - } -}); - -Object.defineProperty(Collection.prototype, 'namespace', { - enumerable: true, - get: function() { - return this.s.namespace.toString(); - } -}); - -Object.defineProperty(Collection.prototype, 'readConcern', { - enumerable: true, - get: function() { - if (this.s.readConcern == null) { - return this.s.db.readConcern; - } - return this.s.readConcern; - } -}); - -Object.defineProperty(Collection.prototype, 'readPreference', { - enumerable: true, - get: function() { - if (this.s.readPreference == null) { - return this.s.db.readPreference; - } - - return this.s.readPreference; - } -}); - -Object.defineProperty(Collection.prototype, 'writeConcern', { - enumerable: true, - get: function() { - if (this.s.writeConcern == null) { - return this.s.db.writeConcern; - } - return this.s.writeConcern; - } -}); - -/** - * @ignore - */ -Object.defineProperty(Collection.prototype, 'hint', { - enumerable: true, - get: function() { - return this.s.collectionHint; - }, - set: function(v) { - this.s.collectionHint = normalizeHintField(v); - } -}); - -const DEPRECATED_FIND_OPTIONS = ['maxScan', 'fields', 'snapshot']; - -/** - * Creates a cursor for a query that can be used to iterate over results from MongoDB - * @method - * @param {object} [query={}] The cursor query object. - * @param {object} [options] Optional settings. - * @param {number} [options.limit=0] Sets the limit of documents returned in the query. - * @param {(array|object)} [options.sort] Set to sort the documents coming back from the query. Array of indexes, [['a', 1]] etc. - * @param {object} [options.projection] The fields to return in the query. Object of fields to include or exclude (not both), {'a':1} - * @param {object} [options.fields] **Deprecated** Use `options.projection` instead - * @param {number} [options.skip=0] Set to skip N documents ahead in your query (useful for pagination). - * @param {Object} [options.hint] Tell the query to use specific indexes in the query. Object of indexes to use, {'_id':1} - * @param {boolean} [options.explain=false] Explain the query instead of returning the data. - * @param {boolean} [options.snapshot=false] DEPRECATED: Snapshot query. - * @param {boolean} [options.timeout=false] Specify if the cursor can timeout. - * @param {boolean} [options.tailable=false] Specify if the cursor is tailable. - * @param {number} [options.batchSize=1000] Set the batchSize for the getMoreCommand when iterating over the query results. - * @param {boolean} [options.returnKey=false] Only return the index key. - * @param {number} [options.maxScan] DEPRECATED: Limit the number of items to scan. - * @param {number} [options.min] Set index bounds. - * @param {number} [options.max] Set index bounds. - * @param {boolean} [options.showDiskLoc=false] Show disk location of results. - * @param {string} [options.comment] You can put a $comment field on a query to make looking in the profiler logs simpler. - * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. - * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution. - * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. - * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {boolean} [options.partial=false] Specify if the cursor should return partial results when querying against a sharded system - * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query. - * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {ClientSession} [options.session] optional session to use for this operation - * @throws {MongoError} - * @return {Cursor} - */ -Collection.prototype.find = deprecateOptions( - { - name: 'collection.find', - deprecatedOptions: DEPRECATED_FIND_OPTIONS, - optionsIndex: 1 - }, - function(query, options, callback) { - if (typeof callback === 'object') { - // TODO(MAJOR): throw in the future - console.warn('Third parameter to `find()` must be a callback or undefined'); - } - - let selector = query; - // figuring out arguments - if (typeof callback !== 'function') { - if (typeof options === 'function') { - callback = options; - options = undefined; - } else if (options == null) { - callback = typeof selector === 'function' ? selector : undefined; - selector = typeof selector === 'object' ? selector : undefined; - } - } - - // Ensure selector is not null - selector = selector == null ? {} : selector; - // Validate correctness off the selector - const object = selector; - if (Buffer.isBuffer(object)) { - const object_size = object[0] | (object[1] << 8) | (object[2] << 16) | (object[3] << 24); - if (object_size !== object.length) { - const error = new Error( - 'query selector raw message size does not match message header size [' + - object.length + - '] != [' + - object_size + - ']' - ); - error.name = 'MongoError'; - throw error; - } - } - - // Check special case where we are using an objectId - if (selector != null && selector._bsontype === 'ObjectID') { - selector = { _id: selector }; - } - - if (!options) options = {}; - - let projection = options.projection || options.fields; - - if (projection && !Buffer.isBuffer(projection) && Array.isArray(projection)) { - projection = projection.length - ? projection.reduce((result, field) => { - result[field] = 1; - return result; - }, {}) - : { _id: 1 }; - } - - // Make a shallow copy of options - let newOptions = Object.assign({}, options); - - // Make a shallow copy of the collection options - for (let key in this.s.options) { - if (mergeKeys.indexOf(key) !== -1) { - newOptions[key] = this.s.options[key]; - } - } - - // Unpack options - newOptions.skip = options.skip ? options.skip : 0; - newOptions.limit = options.limit ? options.limit : 0; - newOptions.raw = typeof options.raw === 'boolean' ? options.raw : this.s.raw; - newOptions.hint = - options.hint != null ? normalizeHintField(options.hint) : this.s.collectionHint; - newOptions.timeout = typeof options.timeout === 'undefined' ? undefined : options.timeout; - // // If we have overridden slaveOk otherwise use the default db setting - newOptions.slaveOk = options.slaveOk != null ? options.slaveOk : this.s.db.slaveOk; - - // Add read preference if needed - newOptions.readPreference = resolveReadPreference(this, newOptions); - - // Set slave ok to true if read preference different from primary - if ( - newOptions.readPreference != null && - (newOptions.readPreference !== 'primary' || newOptions.readPreference.mode !== 'primary') - ) { - newOptions.slaveOk = true; - } - - // Ensure the query is an object - if (selector != null && typeof selector !== 'object') { - throw MongoError.create({ message: 'query selector must be an object', driver: true }); - } - - // Build the find command - const findCommand = { - find: this.s.namespace.toString(), - limit: newOptions.limit, - skip: newOptions.skip, - query: selector - }; - - // Ensure we use the right await data option - if (typeof newOptions.awaitdata === 'boolean') { - newOptions.awaitData = newOptions.awaitdata; - } - - // Translate to new command option noCursorTimeout - if (typeof newOptions.timeout === 'boolean') newOptions.noCursorTimeout = newOptions.timeout; - - decorateCommand(findCommand, newOptions, ['session', 'collation']); - - if (projection) findCommand.fields = projection; - - // Add db object to the new options - newOptions.db = this.s.db; - - // Add the promise library - newOptions.promiseLibrary = this.s.promiseLibrary; - - // Set raw if available at collection level - if (newOptions.raw == null && typeof this.s.raw === 'boolean') newOptions.raw = this.s.raw; - // Set promoteLongs if available at collection level - if (newOptions.promoteLongs == null && typeof this.s.promoteLongs === 'boolean') - newOptions.promoteLongs = this.s.promoteLongs; - if (newOptions.promoteValues == null && typeof this.s.promoteValues === 'boolean') - newOptions.promoteValues = this.s.promoteValues; - if (newOptions.promoteBuffers == null && typeof this.s.promoteBuffers === 'boolean') - newOptions.promoteBuffers = this.s.promoteBuffers; - - // Sort options - if (findCommand.sort) { - findCommand.sort = formattedOrderClause(findCommand.sort); - } - - // Set the readConcern - decorateWithReadConcern(findCommand, this, options); - - // Decorate find command with collation options - try { - decorateWithCollation(findCommand, this, options); - } catch (err) { - if (typeof callback === 'function') return callback(err, null); - throw err; - } - - const cursor = this.s.topology.cursor( - new FindOperation(this, this.s.namespace, findCommand, newOptions), - newOptions - ); - - // TODO: remove this when NODE-2074 is resolved - if (typeof callback === 'function') { - callback(null, cursor); - return; - } - - return cursor; - } -); - -/** - * Inserts a single document into MongoDB. If documents passed in do not contain the **_id** field, - * one will be added to each of the documents missing it by the driver, mutating the document. This behavior - * can be overridden by setting the **forceServerObjectId** flag. - * - * @method - * @param {object} doc Document to insert. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~insertOneWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.insertOne = function(doc, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // Add ignoreUndefined - if (this.s.options.ignoreUndefined) { - options = Object.assign({}, options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - const insertOneOperation = new InsertOneOperation(this, doc, options); - - return executeOperation(this.s.topology, insertOneOperation, callback); -}; - -/** - * Inserts an array of documents into MongoDB. If documents passed in do not contain the **_id** field, - * one will be added to each of the documents missing it by the driver, mutating the document. This behavior - * can be overridden by setting the **forceServerObjectId** flag. - * - * @method - * @param {object[]} docs Documents to insert. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {boolean} [options.ordered=true] If true, when an insert fails, don't execute the remaining writes. If false, continue with remaining inserts when one fails. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~insertWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.insertMany = function(docs, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options ? Object.assign({}, options) : { ordered: true }; - - const insertManyOperation = new InsertManyOperation(this, docs, options); - - return executeOperation(this.s.topology, insertManyOperation, callback); -}; - -/** - * @typedef {Object} Collection~BulkWriteOpResult - * @property {number} insertedCount Number of documents inserted. - * @property {number} matchedCount Number of documents matched for update. - * @property {number} modifiedCount Number of documents modified. - * @property {number} deletedCount Number of documents deleted. - * @property {number} upsertedCount Number of documents upserted. - * @property {object} insertedIds Inserted document generated Id's, hash key is the index of the originating operation - * @property {object} upsertedIds Upserted document generated Id's, hash key is the index of the originating operation - * @property {object} result The command result object. - */ - -/** - * The callback format for inserts - * @callback Collection~bulkWriteOpCallback - * @param {BulkWriteError} error An error instance representing the error during the execution. - * @param {Collection~BulkWriteOpResult} result The result object if the command was executed successfully. - */ - -/** - * Perform a bulkWrite operation without a fluent API - * - * Legal operation types are - * - * { insertOne: { document: { a: 1 } } } - * - * { updateOne: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } } - * - * { updateMany: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } } - * - * { updateMany: { filter: {}, update: {$set: {"a.$[i].x": 5}}, arrayFilters: [{ "i.x": 5 }]} } - * - * { deleteOne: { filter: {c:1} } } - * - * { deleteMany: { filter: {c:1} } } - * - * { replaceOne: { filter: {c:3}, replacement: {c:4}, upsert:true}} - * - * If documents passed in do not contain the **_id** field, - * one will be added to each of the documents missing it by the driver, mutating the document. This behavior - * can be overridden by setting the **forceServerObjectId** flag. - * - * @method - * @param {object[]} operations Bulk operations to perform. - * @param {object} [options] Optional settings. - * @param {object[]} [options.arrayFilters] Determines which array elements to modify for update operation in MongoDB 3.6 or higher. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {boolean} [options.ordered=true] Execute write operation in ordered or unordered fashion. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~bulkWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.bulkWrite = function(operations, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || { ordered: true }; - - if (!Array.isArray(operations)) { - throw MongoError.create({ message: 'operations must be an array of documents', driver: true }); - } - - const bulkWriteOperation = new BulkWriteOperation(this, operations, options); - - return executeOperation(this.s.topology, bulkWriteOperation, callback); -}; - -/** - * @typedef {Object} Collection~WriteOpResult - * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany - * @property {object} connection The connection object used for the operation. - * @property {object} result The command result object. - */ - -/** - * The callback format for inserts - * @callback Collection~writeOpCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection~WriteOpResult} result The result object if the command was executed successfully. - */ - -/** - * @typedef {Object} Collection~insertWriteOpResult - * @property {Number} insertedCount The total amount of documents inserted. - * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany - * @property {Object.} insertedIds Map of the index of the inserted document to the id of the inserted document. - * @property {object} connection The connection object used for the operation. - * @property {object} result The raw command result object returned from MongoDB (content might vary by server version). - * @property {Number} result.ok Is 1 if the command executed correctly. - * @property {Number} result.n The total count of documents inserted. - */ - -/** - * @typedef {Object} Collection~insertOneWriteOpResult - * @property {Number} insertedCount The total amount of documents inserted. - * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany - * @property {ObjectId} insertedId The driver generated ObjectId for the insert operation. - * @property {object} connection The connection object used for the operation. - * @property {object} result The raw command result object returned from MongoDB (content might vary by server version). - * @property {Number} result.ok Is 1 if the command executed correctly. - * @property {Number} result.n The total count of documents inserted. - */ - -/** - * The callback format for inserts - * @callback Collection~insertWriteOpCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection~insertWriteOpResult} result The result object if the command was executed successfully. - */ - -/** - * The callback format for inserts - * @callback Collection~insertOneWriteOpCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection~insertOneWriteOpResult} result The result object if the command was executed successfully. - */ - -/** - * Inserts a single document or a an array of documents into MongoDB. If documents passed in do not contain the **_id** field, - * one will be added to each of the documents missing it by the driver, mutating the document. This behavior - * can be overridden by setting the **forceServerObjectId** flag. - * - * @method - * @param {(object|object[])} docs Documents to insert. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~insertWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - * @deprecated Use insertOne, insertMany or bulkWrite - */ -Collection.prototype.insert = deprecate(function(docs, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || { ordered: false }; - docs = !Array.isArray(docs) ? [docs] : docs; - - if (options.keepGoing === true) { - options.ordered = false; - } - - return this.insertMany(docs, options, callback); -}, 'collection.insert is deprecated. Use insertOne, insertMany or bulkWrite instead.'); - -/** - * @typedef {Object} Collection~updateWriteOpResult - * @property {Object} result The raw result returned from MongoDB. Will vary depending on server version. - * @property {Number} result.ok Is 1 if the command executed correctly. - * @property {Number} result.n The total count of documents scanned. - * @property {Number} result.nModified The total count of documents modified. - * @property {Object} connection The connection object used for the operation. - * @property {Number} matchedCount The number of documents that matched the filter. - * @property {Number} modifiedCount The number of documents that were modified. - * @property {Number} upsertedCount The number of documents upserted. - * @property {Object} upsertedId The upserted id. - * @property {ObjectId} upsertedId._id The upserted _id returned from the server. - * @property {Object} message - * @property {object[]} [ops] In a response to {@link Collection#replaceOne replaceOne}, contains the new value of the document on the server. This is the same document that was originally passed in, and is only here for legacy purposes. - */ - -/** - * The callback format for inserts - * @callback Collection~updateWriteOpCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection~updateWriteOpResult} result The result object if the command was executed successfully. - */ - -/** - * Update a single document in a collection - * @method - * @param {object} filter The Filter used to select the document to update - * @param {object} update The update operations to be applied to the document - * @param {object} [options] Optional settings. - * @param {boolean} [options.upsert=false] Update operation is an upsert. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {Array} [options.arrayFilters] optional list of array filters referenced in filtered positional operators - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~updateWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.updateOne = function(filter, update, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const err = checkForAtomicOperators(update); - if (err) { - if (typeof callback === 'function') return callback(err); - return this.s.promiseLibrary.reject(err); - } - - options = Object.assign({}, options); - - // Add ignoreUndefined - if (this.s.options.ignoreUndefined) { - options = Object.assign({}, options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - const updateOneOperation = new UpdateOneOperation(this, filter, update, options); - - return executeOperation(this.s.topology, updateOneOperation, callback); -}; - -/** - * Replace a document in a collection with another document - * @method - * @param {object} filter The Filter used to select the document to replace - * @param {object} doc The Document that replaces the matching document - * @param {object} [options] Optional settings. - * @param {boolean} [options.upsert=false] Update operation is an upsert. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~updateWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.replaceOne = function(filter, doc, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = Object.assign({}, options); - - // Add ignoreUndefined - if (this.s.options.ignoreUndefined) { - options = Object.assign({}, options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - const replaceOneOperation = new ReplaceOneOperation(this, filter, doc, options); - - return executeOperation(this.s.topology, replaceOneOperation, callback); -}; - -/** - * Update multiple documents in a collection - * @method - * @param {object} filter The Filter used to select the documents to update - * @param {object} update The update operations to be applied to the documents - * @param {object} [options] Optional settings. - * @param {boolean} [options.upsert=false] Update operation is an upsert. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {Array} [options.arrayFilters] optional list of array filters referenced in filtered positional operators - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~updateWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.updateMany = function(filter, update, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const err = checkForAtomicOperators(update); - if (err) { - if (typeof callback === 'function') return callback(err); - return this.s.promiseLibrary.reject(err); - } - - options = Object.assign({}, options); - - // Add ignoreUndefined - if (this.s.options.ignoreUndefined) { - options = Object.assign({}, options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - const updateManyOperation = new UpdateManyOperation(this, filter, update, options); - - return executeOperation(this.s.topology, updateManyOperation, callback); -}; - -/** - * Updates documents. - * @method - * @param {object} selector The selector for the update operation. - * @param {object} update The update operations to be applied to the documents - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.upsert=false] Update operation is an upsert. - * @param {boolean} [options.multi=false] Update one/all documents with operation. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {Array} [options.arrayFilters] optional list of array filters referenced in filtered positional operators - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~writeOpCallback} [callback] The command result callback - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - * @deprecated use updateOne, updateMany or bulkWrite - */ -Collection.prototype.update = deprecate(function(selector, update, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // Add ignoreUndefined - if (this.s.options.ignoreUndefined) { - options = Object.assign({}, options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - return executeLegacyOperation(this.s.topology, updateDocuments, [ - this, - selector, - update, - options, - callback - ]); -}, 'collection.update is deprecated. Use updateOne, updateMany, or bulkWrite instead.'); - -/** - * @typedef {Object} Collection~deleteWriteOpResult - * @property {Object} result The raw result returned from MongoDB. Will vary depending on server version. - * @property {Number} result.ok Is 1 if the command executed correctly. - * @property {Number} result.n The total count of documents deleted. - * @property {Object} connection The connection object used for the operation. - * @property {Number} deletedCount The number of documents deleted. - */ - -/** - * The callback format for inserts - * @callback Collection~deleteWriteOpCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection~deleteWriteOpResult} result The result object if the command was executed successfully. - */ - -/** - * Delete a document from a collection - * @method - * @param {object} filter The Filter used to select the document to remove - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~deleteWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.deleteOne = function(filter, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = Object.assign({}, options); - - // Add ignoreUndefined - if (this.s.options.ignoreUndefined) { - options = Object.assign({}, options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - const deleteOneOperation = new DeleteOneOperation(this, filter, options); - - return executeOperation(this.s.topology, deleteOneOperation, callback); -}; - -Collection.prototype.removeOne = Collection.prototype.deleteOne; - -/** - * Delete multiple documents from a collection - * @method - * @param {object} filter The Filter used to select the documents to remove - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~deleteWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.deleteMany = function(filter, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = Object.assign({}, options); - - // Add ignoreUndefined - if (this.s.options.ignoreUndefined) { - options = Object.assign({}, options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - const deleteManyOperation = new DeleteManyOperation(this, filter, options); - - return executeOperation(this.s.topology, deleteManyOperation, callback); -}; - -Collection.prototype.removeMany = Collection.prototype.deleteMany; - -/** - * Remove documents. - * @method - * @param {object} selector The selector for the update operation. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.single=false] Removes the first document found. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~writeOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - * @deprecated use deleteOne, deleteMany or bulkWrite - */ -Collection.prototype.remove = deprecate(function(selector, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // Add ignoreUndefined - if (this.s.options.ignoreUndefined) { - options = Object.assign({}, options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - return executeLegacyOperation(this.s.topology, removeDocuments, [ - this, - selector, - options, - callback - ]); -}, 'collection.remove is deprecated. Use deleteOne, deleteMany, or bulkWrite instead.'); - -/** - * Save a document. Simple full document replacement function. Not recommended for efficiency, use atomic - * operators and update instead for more efficient operations. - * @method - * @param {object} doc Document to save - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~writeOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - * @deprecated use insertOne, insertMany, updateOne or updateMany - */ -Collection.prototype.save = deprecate(function(doc, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // Add ignoreUndefined - if (this.s.options.ignoreUndefined) { - options = Object.assign({}, options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - return executeLegacyOperation(this.s.topology, save, [this, doc, options, callback]); -}, 'collection.save is deprecated. Use insertOne, insertMany, updateOne, or updateMany instead.'); - -/** - * The callback format for results - * @callback Collection~resultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {object} result The result object if the command was executed successfully. - */ - -/** - * The callback format for an aggregation call - * @callback Collection~aggregationCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {AggregationCursor} cursor The cursor if the aggregation command was executed successfully. - */ - -/** - * Fetches the first document that matches the query - * @method - * @param {object} query Query for find Operation - * @param {object} [options] Optional settings. - * @param {number} [options.limit=0] Sets the limit of documents returned in the query. - * @param {(array|object)} [options.sort] Set to sort the documents coming back from the query. Array of indexes, [['a', 1]] etc. - * @param {object} [options.projection] The fields to return in the query. Object of fields to include or exclude (not both), {'a':1} - * @param {object} [options.fields] **Deprecated** Use `options.projection` instead - * @param {number} [options.skip=0] Set to skip N documents ahead in your query (useful for pagination). - * @param {Object} [options.hint] Tell the query to use specific indexes in the query. Object of indexes to use, {'_id':1} - * @param {boolean} [options.explain=false] Explain the query instead of returning the data. - * @param {boolean} [options.snapshot=false] DEPRECATED: Snapshot query. - * @param {boolean} [options.timeout=false] Specify if the cursor can timeout. - * @param {boolean} [options.tailable=false] Specify if the cursor is tailable. - * @param {number} [options.batchSize=1] Set the batchSize for the getMoreCommand when iterating over the query results. - * @param {boolean} [options.returnKey=false] Only return the index key. - * @param {number} [options.maxScan] DEPRECATED: Limit the number of items to scan. - * @param {number} [options.min] Set index bounds. - * @param {number} [options.max] Set index bounds. - * @param {boolean} [options.showDiskLoc=false] Show disk location of results. - * @param {string} [options.comment] You can put a $comment field on a query to make looking in the profiler logs simpler. - * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. - * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution. - * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. - * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {boolean} [options.partial=false] Specify if the cursor should return partial results when querying against a sharded system - * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query. - * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.findOne = deprecateOptions( - { - name: 'collection.find', - deprecatedOptions: DEPRECATED_FIND_OPTIONS, - optionsIndex: 1 - }, - function(query, options, callback) { - if (typeof callback === 'object') { - // TODO(MAJOR): throw in the future - console.warn('Third parameter to `findOne()` must be a callback or undefined'); - } - - if (typeof query === 'function') (callback = query), (query = {}), (options = {}); - if (typeof options === 'function') (callback = options), (options = {}); - query = query || {}; - options = options || {}; - - const findOneOperation = new FindOneOperation(this, query, options); - - return executeOperation(this.s.topology, findOneOperation, callback); - } -); - -/** - * The callback format for the collection method, must be used if strict is specified - * @callback Collection~collectionResultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection} collection The collection instance. - */ - -/** - * Rename the collection. - * - * @method - * @param {string} newName New name of of the collection. - * @param {object} [options] Optional settings. - * @param {boolean} [options.dropTarget=false] Drop the target name collection if it previously exists. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~collectionResultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.rename = function(newName, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = Object.assign({}, options, { readPreference: ReadPreference.PRIMARY }); - - const renameOperation = new RenameOperation(this, newName, options); - - return executeOperation(this.s.topology, renameOperation, callback); -}; - -/** - * Drop the collection from the database, removing it permanently. New accesses will create a new collection. - * - * @method - * @param {object} [options] Optional settings. - * @param {WriteConcern} [options.writeConcern] A full WriteConcern object - * @param {(number|string)} [options.w] The write concern - * @param {number} [options.wtimeout] The write concern timeout - * @param {boolean} [options.j] The journal write concern - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.drop = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const dropCollectionOperation = new DropCollectionOperation( - this.s.db, - this.collectionName, - options - ); - - return executeOperation(this.s.topology, dropCollectionOperation, callback); -}; - -/** - * Returns the options of the collection. - * - * @method - * @param {Object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.options = function(opts, callback) { - if (typeof opts === 'function') (callback = opts), (opts = {}); - opts = opts || {}; - - const optionsOperation = new OptionsOperation(this, opts); - - return executeOperation(this.s.topology, optionsOperation, callback); -}; - -/** - * Returns if the collection is a capped collection - * - * @method - * @param {Object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.isCapped = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const isCappedOperation = new IsCappedOperation(this, options); - - return executeOperation(this.s.topology, isCappedOperation, callback); -}; - -/** - * Creates an index on the db and collection collection. - * @method - * @param {(string|array|object)} fieldOrSpec Defines the index. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.unique=false] Creates an unique index. - * @param {boolean} [options.sparse=false] Creates a sparse index. - * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. - * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value - * @param {number} [options.min] For geospatial indexes set the lower bound for the co-ordinates. - * @param {number} [options.max] For geospatial indexes set the high bound for the co-ordinates. - * @param {number} [options.v] Specify the format version of the indexes. - * @param {number} [options.expireAfterSeconds] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) - * @param {string} [options.name] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) - * @param {object} [options.partialFilterExpression] Creates a partial index based on the given filter object (MongoDB 3.2 or higher) - * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - * @example - * const collection = client.db('foo').collection('bar'); - * - * await collection.createIndex({ a: 1, b: -1 }); - * - * // Alternate syntax for { c: 1, d: -1 } that ensures order of indexes - * await collection.createIndex([ [c, 1], [d, -1] ]); - * - * // Equivalent to { e: 1 } - * await collection.createIndex('e'); - * - * // Equivalent to { f: 1, g: 1 } - * await collection.createIndex(['f', 'g']) - * - * // Equivalent to { h: 1, i: -1 } - * await collection.createIndex([ { h: 1 }, { i: -1 } ]); - * - * // Equivalent to { j: 1, k: -1, l: 2d } - * await collection.createIndex(['j', ['k', -1], { l: '2d' }]) - */ -Collection.prototype.createIndex = function(fieldOrSpec, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const createIndexOperation = new CreateIndexOperation( - this.s.db, - this.collectionName, - fieldOrSpec, - options - ); - - return executeOperation(this.s.topology, createIndexOperation, callback); -}; - -/** - * @typedef {object} Collection~IndexDefinition - * @description A definition for an index. Used by the createIndex command. - * @see https://docs.mongodb.com/manual/reference/command/createIndexes/ - */ - -/** - * Creates multiple indexes in the collection, this method is only supported for - * MongoDB 2.6 or higher. Earlier version of MongoDB will throw a command not supported - * error. - * - * **Note**: Unlike {@link Collection#createIndex createIndex}, this function takes in raw index specifications. - * Index specifications are defined {@link http://docs.mongodb.org/manual/reference/command/createIndexes/ here}. - * - * @method - * @param {Collection~IndexDefinition[]} indexSpecs An array of index specifications to be created - * @param {Object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - * @example - * const collection = client.db('foo').collection('bar'); - * await collection.createIndexes([ - * // Simple index on field fizz - * { - * key: { fizz: 1 }, - * } - * // wildcard index - * { - * key: { '$**': 1 } - * }, - * // named index on darmok and jalad - * { - * key: { darmok: 1, jalad: -1 } - * name: 'tanagra' - * } - * ]); - */ -Collection.prototype.createIndexes = function(indexSpecs, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - - options = options ? Object.assign({}, options) : {}; - if (typeof options.maxTimeMS !== 'number') delete options.maxTimeMS; - - const createIndexesOperation = new CreateIndexesOperation(this, indexSpecs, options); - - return executeOperation(this.s.topology, createIndexesOperation, callback); -}; - -/** - * Drops an index from this collection. - * @method - * @param {string} indexName Name of the index to drop. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query. - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.dropIndex = function(indexName, options, callback) { - const args = Array.prototype.slice.call(arguments, 1); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - - options = args.length ? args.shift() || {} : {}; - // Run only against primary - options.readPreference = ReadPreference.PRIMARY; - - const dropIndexOperation = new DropIndexOperation(this, indexName, options); - - return executeOperation(this.s.topology, dropIndexOperation, callback); -}; - -/** - * Drops all indexes from this collection. - * @method - * @param {Object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query. - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.dropIndexes = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options ? Object.assign({}, options) : {}; - - if (typeof options.maxTimeMS !== 'number') delete options.maxTimeMS; - - const dropIndexesOperation = new DropIndexesOperation(this, options); - - return executeOperation(this.s.topology, dropIndexesOperation, callback); -}; - -/** - * Drops all indexes from this collection. - * @method - * @deprecated use dropIndexes - * @param {Collection~resultCallback} callback The command result callback - * @return {Promise} returns Promise if no [callback] passed - */ -Collection.prototype.dropAllIndexes = deprecate( - Collection.prototype.dropIndexes, - 'collection.dropAllIndexes is deprecated. Use dropIndexes instead.' -); - -/** - * Reindex all indexes on the collection - * Warning: reIndex is a blocking operation (indexes are rebuilt in the foreground) and will be slow for large collections. - * @method - * @param {Object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.reIndex = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const reIndexOperation = new ReIndexOperation(this, options); - - return executeOperation(this.s.topology, reIndexOperation, callback); -}; - -/** - * Get the list of all indexes information for the collection. - * - * @method - * @param {object} [options] Optional settings. - * @param {number} [options.batchSize=1000] The batchSize for the returned command cursor or if pre 2.8 the systems batch collection - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {ClientSession} [options.session] optional session to use for this operation - * @return {CommandCursor} - */ -Collection.prototype.listIndexes = function(options) { - const cursor = new CommandCursor( - this.s.topology, - new ListIndexesOperation(this, options), - options - ); - - return cursor; -}; - -/** - * Ensures that an index exists, if it does not it creates it - * @method - * @deprecated use createIndexes instead - * @param {(string|object)} fieldOrSpec Defines the index. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.unique=false] Creates an unique index. - * @param {boolean} [options.sparse=false] Creates a sparse index. - * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. - * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value - * @param {number} [options.min] For geospatial indexes set the lower bound for the co-ordinates. - * @param {number} [options.max] For geospatial indexes set the high bound for the co-ordinates. - * @param {number} [options.v] Specify the format version of the indexes. - * @param {number} [options.expireAfterSeconds] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) - * @param {number} [options.name] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) - * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.ensureIndex = deprecate(function(fieldOrSpec, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - return executeLegacyOperation(this.s.topology, ensureIndex, [ - this, - fieldOrSpec, - options, - callback - ]); -}, 'collection.ensureIndex is deprecated. Use createIndexes instead.'); - -/** - * Checks if one or more indexes exist on the collection, fails on first non-existing index - * @method - * @param {(string|array)} indexes One or more index names to check. - * @param {Object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.indexExists = function(indexes, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const indexExistsOperation = new IndexExistsOperation(this, indexes, options); - - return executeOperation(this.s.topology, indexExistsOperation, callback); -}; - -/** - * Retrieves this collections index info. - * @method - * @param {object} [options] Optional settings. - * @param {boolean} [options.full=false] Returns the full raw index information. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.indexInformation = function(options, callback) { - const args = Array.prototype.slice.call(arguments, 0); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - options = args.length ? args.shift() || {} : {}; - - const indexInformationOperation = new IndexInformationOperation( - this.s.db, - this.collectionName, - options - ); - - return executeOperation(this.s.topology, indexInformationOperation, callback); -}; - -/** - * The callback format for results - * @callback Collection~countCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {number} result The count of documents that matched the query. - */ - -/** - * An estimated count of matching documents in the db to a query. - * - * **NOTE:** This method has been deprecated, since it does not provide an accurate count of the documents - * in a collection. To obtain an accurate count of documents in the collection, use {@link Collection#countDocuments countDocuments}. - * To obtain an estimated count of all documents in the collection, use {@link Collection#estimatedDocumentCount estimatedDocumentCount}. - * - * @method - * @param {object} [query={}] The query for the count. - * @param {object} [options] Optional settings. - * @param {boolean} [options.limit] The limit of documents to count. - * @param {boolean} [options.skip] The number of documents to skip for the count. - * @param {string} [options.hint] An index name hint for the query. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~countCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - * @deprecated use {@link Collection#countDocuments countDocuments} or {@link Collection#estimatedDocumentCount estimatedDocumentCount} instead - */ -Collection.prototype.count = deprecate(function(query, options, callback) { - const args = Array.prototype.slice.call(arguments, 0); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - query = args.length ? args.shift() || {} : {}; - options = args.length ? args.shift() || {} : {}; - - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - return executeOperation( - this.s.topology, - new EstimatedDocumentCountOperation(this, query, options), - callback - ); -}, 'collection.count is deprecated, and will be removed in a future version.' + - ' Use Collection.countDocuments or Collection.estimatedDocumentCount instead'); - -/** - * Gets an estimate of the count of documents in a collection using collection metadata. - * - * @method - * @param {object} [options] Optional settings. - * @param {number} [options.maxTimeMS] The maximum amount of time to allow the operation to run. - * @param {Collection~countCallback} [callback] The command result callback. - * @return {Promise} returns Promise if no callback passed. - */ -Collection.prototype.estimatedDocumentCount = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const estimatedDocumentCountOperation = new EstimatedDocumentCountOperation(this, options); - - return executeOperation(this.s.topology, estimatedDocumentCountOperation, callback); -}; - -/** - * Gets the number of documents matching the filter. - * For a fast count of the total documents in a collection see {@link Collection#estimatedDocumentCount estimatedDocumentCount}. - * **Note**: When migrating from {@link Collection#count count} to {@link Collection#countDocuments countDocuments} - * the following query operators must be replaced: - * - * | Operator | Replacement | - * | -------- | ----------- | - * | `$where` | [`$expr`][1] | - * | `$near` | [`$geoWithin`][2] with [`$center`][3] | - * | `$nearSphere` | [`$geoWithin`][2] with [`$centerSphere`][4] | - * - * [1]: https://docs.mongodb.com/manual/reference/operator/query/expr/ - * [2]: https://docs.mongodb.com/manual/reference/operator/query/geoWithin/ - * [3]: https://docs.mongodb.com/manual/reference/operator/query/center/#op._S_center - * [4]: https://docs.mongodb.com/manual/reference/operator/query/centerSphere/#op._S_centerSphere - * - * @param {object} [query] the query for the count - * @param {object} [options] Optional settings. - * @param {object} [options.collation] Specifies a collation. - * @param {string|object} [options.hint] The index to use. - * @param {number} [options.limit] The maximum number of document to count. - * @param {number} [options.maxTimeMS] The maximum amount of time to allow the operation to run. - * @param {number} [options.skip] The number of documents to skip before counting. - * @param {Collection~countCallback} [callback] The command result callback. - * @return {Promise} returns Promise if no callback passed. - * @see https://docs.mongodb.com/manual/reference/operator/query/expr/ - * @see https://docs.mongodb.com/manual/reference/operator/query/geoWithin/ - * @see https://docs.mongodb.com/manual/reference/operator/query/center/#op._S_center - * @see https://docs.mongodb.com/manual/reference/operator/query/centerSphere/#op._S_centerSphere - */ - -Collection.prototype.countDocuments = function(query, options, callback) { - const args = Array.prototype.slice.call(arguments, 0); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - query = args.length ? args.shift() || {} : {}; - options = args.length ? args.shift() || {} : {}; - - const countDocumentsOperation = new CountDocumentsOperation(this, query, options); - - return executeOperation(this.s.topology, countDocumentsOperation, callback); -}; - -/** - * The distinct command returns a list of distinct values for the given key across a collection. - * @method - * @param {string} key Field of the document to find distinct values for. - * @param {object} query The query for filtering the set of documents to which we apply the distinct filter. - * @param {object} [options] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.distinct = function(key, query, options, callback) { - const args = Array.prototype.slice.call(arguments, 1); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - const queryOption = args.length ? args.shift() || {} : {}; - const optionsOption = args.length ? args.shift() || {} : {}; - - const distinctOperation = new DistinctOperation(this, key, queryOption, optionsOption); - - return executeOperation(this.s.topology, distinctOperation, callback); -}; - -/** - * Retrieve all the indexes on the collection. - * @method - * @param {Object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.indexes = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const indexesOperation = new IndexesOperation(this, options); - - return executeOperation(this.s.topology, indexesOperation, callback); -}; - -/** - * Get all the collection statistics. - * - * @method - * @param {object} [options] Optional settings. - * @param {number} [options.scale] Divide the returned sizes by scale value. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The collection result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.stats = function(options, callback) { - const args = Array.prototype.slice.call(arguments, 0); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - options = args.length ? args.shift() || {} : {}; - - const statsOperation = new StatsOperation(this, options); - - return executeOperation(this.s.topology, statsOperation, callback); -}; - -/** - * @typedef {Object} Collection~findAndModifyWriteOpResult - * @property {object} value Document returned from the `findAndModify` command. If no documents were found, `value` will be `null` by default (`returnOriginal: true`), even if a document was upserted; if `returnOriginal` was false, the upserted document will be returned in that case. - * @property {object} lastErrorObject The raw lastErrorObject returned from the command. See {@link https://docs.mongodb.com/manual/reference/command/findAndModify/index.html#lasterrorobject|findAndModify command documentation}. - * @property {Number} ok Is 1 if the command executed correctly. - */ - -/** - * The callback format for inserts - * @callback Collection~findAndModifyCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection~findAndModifyWriteOpResult} result The result object if the command was executed successfully. - */ - -/** - * Find a document and delete it in one atomic operation. Requires a write lock for the duration of the operation. - * - * @method - * @param {object} filter The Filter used to select the document to remove - * @param {object} [options] Optional settings. - * @param {object} [options.projection] Limits the fields to return for all matching documents. - * @param {object} [options.sort] Determines which document the operation modifies if the query selects multiple documents. - * @param {number} [options.maxTimeMS] The maximum amount of time to allow the query to run. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~findAndModifyCallback} [callback] The collection result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.findOneAndDelete = function(filter, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // Basic validation - if (filter == null || typeof filter !== 'object') - throw toError('filter parameter must be an object'); - - const findOneAndDeleteOperation = new FindOneAndDeleteOperation(this, filter, options); - - return executeOperation(this.s.topology, findOneAndDeleteOperation, callback); -}; - -/** - * Find a document and replace it in one atomic operation. Requires a write lock for the duration of the operation. - * - * @method - * @param {object} filter The Filter used to select the document to replace - * @param {object} replacement The Document that replaces the matching document - * @param {object} [options] Optional settings. - * @param {object} [options.projection] Limits the fields to return for all matching documents. - * @param {object} [options.sort] Determines which document the operation modifies if the query selects multiple documents. - * @param {number} [options.maxTimeMS] The maximum amount of time to allow the query to run. - * @param {boolean} [options.upsert=false] Upsert the document if it does not exist. - * @param {boolean} [options.returnOriginal=true] When false, returns the updated document rather than the original. The default is true. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~findAndModifyCallback} [callback] The collection result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.findOneAndReplace = function(filter, replacement, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // Basic validation - if (filter == null || typeof filter !== 'object') - throw toError('filter parameter must be an object'); - if (replacement == null || typeof replacement !== 'object') - throw toError('replacement parameter must be an object'); - - // Check that there are no atomic operators - const keys = Object.keys(replacement); - - if (keys[0] && keys[0][0] === '$') { - throw toError('The replacement document must not contain atomic operators.'); - } - - const findOneAndReplaceOperation = new FindOneAndReplaceOperation( - this, - filter, - replacement, - options - ); - - return executeOperation(this.s.topology, findOneAndReplaceOperation, callback); -}; - -/** - * Find a document and update it in one atomic operation. Requires a write lock for the duration of the operation. - * - * @method - * @param {object} filter The Filter used to select the document to update - * @param {object} update Update operations to be performed on the document - * @param {object} [options] Optional settings. - * @param {object} [options.projection] Limits the fields to return for all matching documents. - * @param {object} [options.sort] Determines which document the operation modifies if the query selects multiple documents. - * @param {number} [options.maxTimeMS] The maximum amount of time to allow the query to run. - * @param {boolean} [options.upsert=false] Upsert the document if it does not exist. - * @param {boolean} [options.returnOriginal=true] When false, returns the updated document rather than the original. The default is true. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Array} [options.arrayFilters] optional list of array filters referenced in filtered positional operators - * @param {Collection~findAndModifyCallback} [callback] The collection result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.findOneAndUpdate = function(filter, update, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // Basic validation - if (filter == null || typeof filter !== 'object') - throw toError('filter parameter must be an object'); - if (update == null || typeof update !== 'object') - throw toError('update parameter must be an object'); - - const err = checkForAtomicOperators(update); - if (err) { - if (typeof callback === 'function') return callback(err); - return this.s.promiseLibrary.reject(err); - } - - const findOneAndUpdateOperation = new FindOneAndUpdateOperation(this, filter, update, options); - - return executeOperation(this.s.topology, findOneAndUpdateOperation, callback); -}; - -/** - * Find and update a document. - * @method - * @param {object} query Query object to locate the object to modify. - * @param {array} sort If multiple docs match, choose the first one in the specified sort order as the object to manipulate. - * @param {object} doc The fields/vals to be updated. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.remove=false] Set to true to remove the object before returning. - * @param {boolean} [options.upsert=false] Perform an upsert operation. - * @param {boolean} [options.new=false] Set to true if you want to return the modified object rather than the original. Ignored for remove. - * @param {object} [options.projection] Object containing the field projection for the result returned from the operation. - * @param {object} [options.fields] **Deprecated** Use `options.projection` instead - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Array} [options.arrayFilters] optional list of array filters referenced in filtered positional operators - * @param {Collection~findAndModifyCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - * @deprecated use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead - */ -Collection.prototype.findAndModify = deprecate( - _findAndModify, - 'collection.findAndModify is deprecated. Use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead.' -); - -/** - * @ignore - */ - -Collection.prototype._findAndModify = _findAndModify; - -function _findAndModify(query, sort, doc, options, callback) { - const args = Array.prototype.slice.call(arguments, 1); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - sort = args.length ? args.shift() || [] : []; - doc = args.length ? args.shift() : null; - options = args.length ? args.shift() || {} : {}; - - // Clone options - options = Object.assign({}, options); - // Force read preference primary - options.readPreference = ReadPreference.PRIMARY; - - return executeOperation( - this.s.topology, - new FindAndModifyOperation(this, query, sort, doc, options), - callback - ); -} - -/** - * Find and remove a document. - * @method - * @param {object} query Query object to locate the object to modify. - * @param {array} sort If multiple docs match, choose the first one in the specified sort order as the object to manipulate. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - * @deprecated use findOneAndDelete instead - */ -Collection.prototype.findAndRemove = deprecate(function(query, sort, options, callback) { - const args = Array.prototype.slice.call(arguments, 1); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - sort = args.length ? args.shift() || [] : []; - options = args.length ? args.shift() || {} : {}; - - // Add the remove option - options.remove = true; - - return executeOperation( - this.s.topology, - new FindAndModifyOperation(this, query, sort, null, options), - callback - ); -}, 'collection.findAndRemove is deprecated. Use findOneAndDelete instead.'); - -/** - * Execute an aggregation framework pipeline against the collection, needs MongoDB >= 2.2 - * @method - * @param {object} [pipeline=[]] Array containing all the aggregation framework commands for the execution. - * @param {object} [options] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {object} [options.cursor] Return the query as cursor, on 2.6 > it returns as a real cursor on pre 2.6 it returns as an emulated cursor. - * @param {number} [options.cursor.batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. - * @param {boolean} [options.explain=false] Explain returns the aggregation execution plan (requires mongodb 2.6 >). - * @param {boolean} [options.allowDiskUse=false] allowDiskUse lets the server know if it can use disk to store temporary results for the aggregation (requires mongodb 2.6 >). - * @param {number} [options.maxTimeMS] maxTimeMS specifies a cumulative time limit in milliseconds for processing operations on the cursor. MongoDB interrupts the operation at the earliest following interrupt point. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. - * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution. - * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. - * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. - * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {string} [options.comment] Add a comment to an aggregation command - * @param {string|object} [options.hint] Add an index selection hint to an aggregation command - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~aggregationCallback} callback The command result callback - * @return {(null|AggregationCursor)} - */ -Collection.prototype.aggregate = function(pipeline, options, callback) { - if (Array.isArray(pipeline)) { - // Set up callback if one is provided - if (typeof options === 'function') { - callback = options; - options = {}; - } - - // If we have no options or callback we are doing - // a cursor based aggregation - if (options == null && callback == null) { - options = {}; - } - } else { - // Aggregation pipeline passed as arguments on the method - const args = Array.prototype.slice.call(arguments, 0); - // Get the callback - callback = args.pop(); - // Get the possible options object - const opts = args[args.length - 1]; - // If it contains any of the admissible options pop it of the args - options = - opts && - (opts.readPreference || - opts.explain || - opts.cursor || - opts.out || - opts.maxTimeMS || - opts.hint || - opts.allowDiskUse) - ? args.pop() - : {}; - // Left over arguments is the pipeline - pipeline = args; - } - - const cursor = new AggregationCursor( - this.s.topology, - new AggregateOperation(this, pipeline, options), - options - ); - - // TODO: remove this when NODE-2074 is resolved - if (typeof callback === 'function') { - callback(null, cursor); - return; - } - - return cursor; -}; - -/** - * Create a new Change Stream, watching for new changes (insertions, updates, replacements, deletions, and invalidations) in this collection. - * @method - * @since 3.0.0 - * @param {Array} [pipeline] An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents. - * @param {object} [options] Optional settings - * @param {string} [options.fullDocument='default'] Allowed values: ‘default’, ‘updateLookup’. When set to ‘updateLookup’, the change stream will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred. - * @param {object} [options.resumeAfter] Specifies the logical starting point for the new change stream. This should be the _id field from a previously returned change stream document. - * @param {number} [options.maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a change stream query - * @param {number} [options.batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. - * @param {object} [options.collation] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. - * @param {ReadPreference} [options.readPreference] The read preference. Defaults to the read preference of the database or collection. See {@link https://docs.mongodb.com/manual/reference/read-preference|read preference documentation}. - * @param {Timestamp} [options.startAtOperationTime] receive change events that occur after the specified timestamp - * @param {ClientSession} [options.session] optional session to use for this operation - * @return {ChangeStream} a ChangeStream instance. - */ -Collection.prototype.watch = function(pipeline, options) { - pipeline = pipeline || []; - options = options || {}; - - // Allow optionally not specifying a pipeline - if (!Array.isArray(pipeline)) { - options = pipeline; - pipeline = []; - } - - return new ChangeStream(this, pipeline, options); -}; - -/** - * The callback format for results - * @callback Collection~parallelCollectionScanCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Cursor[]} cursors A list of cursors returned allowing for parallel reading of collection. - */ - -/** - * Return N number of parallel cursors for a collection allowing parallel reading of entire collection. There are - * no ordering guarantees for returned results. - * @method - * @param {object} [options] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {number} [options.batchSize=1000] Set the batchSize for the getMoreCommand when iterating over the query results. - * @param {number} [options.numCursors=1] The maximum number of parallel command cursors to return (the number of returned cursors will be in the range 1:numCursors) - * @param {boolean} [options.raw=false] Return all BSON documents as Raw Buffer documents. - * @param {Collection~parallelCollectionScanCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.parallelCollectionScan = deprecate(function(options, callback) { - if (typeof options === 'function') (callback = options), (options = { numCursors: 1 }); - // Set number of cursors to 1 - options.numCursors = options.numCursors || 1; - options.batchSize = options.batchSize || 1000; - - options = Object.assign({}, options); - // Ensure we have the right read preference inheritance - options.readPreference = resolveReadPreference(this, options); - - // Add a promiseLibrary - options.promiseLibrary = this.s.promiseLibrary; - - if (options.session) { - options.session = undefined; - } - - return executeLegacyOperation( - this.s.topology, - parallelCollectionScan, - [this, options, callback], - { skipSessions: true } - ); -}, 'parallelCollectionScan is deprecated in MongoDB v4.1'); - -/** - * Execute a geo search using a geo haystack index on a collection. - * - * @method - * @param {number} x Point to search on the x axis, ensure the indexes are ordered in the same order. - * @param {number} y Point to search on the y axis, ensure the indexes are ordered in the same order. - * @param {object} [options] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {number} [options.maxDistance] Include results up to maxDistance from the point. - * @param {object} [options.search] Filter the results by a query. - * @param {number} [options.limit=false] Max number of results to return. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.geoHaystackSearch = function(x, y, options, callback) { - const args = Array.prototype.slice.call(arguments, 2); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - options = args.length ? args.shift() || {} : {}; - - const geoHaystackSearchOperation = new GeoHaystackSearchOperation(this, x, y, options); - - return executeOperation(this.s.topology, geoHaystackSearchOperation, callback); -}; - -/** - * Run a group command across a collection - * - * @method - * @param {(object|array|function|code)} keys An object, array or function expressing the keys to group by. - * @param {object} condition An optional condition that must be true for a row to be considered. - * @param {object} initial Initial value of the aggregation counter object. - * @param {(function|Code)} reduce The reduce function aggregates (reduces) the objects iterated - * @param {(function|Code)} finalize An optional function to be run on each item in the result set just before the item is returned. - * @param {boolean} command Specify if you wish to run using the internal group command or using eval, default is true. - * @param {object} [options] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - * @deprecated MongoDB 3.6 or higher no longer supports the group command. We recommend rewriting using the aggregation framework. - */ -Collection.prototype.group = deprecate(function( - keys, - condition, - initial, - reduce, - finalize, - command, - options, - callback -) { - const args = Array.prototype.slice.call(arguments, 3); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - reduce = args.length ? args.shift() : null; - finalize = args.length ? args.shift() : null; - command = args.length ? args.shift() : null; - options = args.length ? args.shift() || {} : {}; - - // Make sure we are backward compatible - if (!(typeof finalize === 'function')) { - command = finalize; - finalize = null; - } - - if ( - !Array.isArray(keys) && - keys instanceof Object && - typeof keys !== 'function' && - !(keys._bsontype === 'Code') - ) { - keys = Object.keys(keys); - } - - if (typeof reduce === 'function') { - reduce = reduce.toString(); - } - - if (typeof finalize === 'function') { - finalize = finalize.toString(); - } - - // Set up the command as default - command = command == null ? true : command; - - return executeLegacyOperation(this.s.topology, group, [ - this, - keys, - condition, - initial, - reduce, - finalize, - command, - options, - callback - ]); -}, -'MongoDB 3.6 or higher no longer supports the group command. We recommend rewriting using the aggregation framework.'); - -/** - * Run Map Reduce across a collection. Be aware that the inline option for out will return an array of results not a collection. - * - * @method - * @param {(function|string)} map The mapping function. - * @param {(function|string)} reduce The reduce function. - * @param {object} [options] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {object} [options.out] Sets the output target for the map reduce job. *{inline:1} | {replace:'collectionName'} | {merge:'collectionName'} | {reduce:'collectionName'}* - * @param {object} [options.query] Query filter object. - * @param {object} [options.sort] Sorts the input objects using this key. Useful for optimization, like sorting by the emit key for fewer reduces. - * @param {number} [options.limit] Number of objects to return from collection. - * @param {boolean} [options.keeptemp=false] Keep temporary data. - * @param {(function|string)} [options.finalize] Finalize function. - * @param {object} [options.scope] Can pass in variables that can be access from map/reduce/finalize. - * @param {boolean} [options.jsMode=false] It is possible to make the execution stay in JS. Provided in MongoDB > 2.0.X. - * @param {boolean} [options.verbose=false] Provide statistics on job execution time. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The command result callback - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.mapReduce = function(map, reduce, options, callback) { - if ('function' === typeof options) (callback = options), (options = {}); - // Out must allways be defined (make sure we don't break weirdly on pre 1.8+ servers) - if (null == options.out) { - throw new Error( - 'the out option parameter must be defined, see mongodb docs for possible values' - ); - } - - if ('function' === typeof map) { - map = map.toString(); - } - - if ('function' === typeof reduce) { - reduce = reduce.toString(); - } - - if ('function' === typeof options.finalize) { - options.finalize = options.finalize.toString(); - } - const mapReduceOperation = new MapReduceOperation(this, map, reduce, options); - - return executeOperation(this.s.topology, mapReduceOperation, callback); -}; - -/** - * Initiate an Out of order batch write operation. All operations will be buffered into insert/update/remove commands executed out of order. - * - * @method - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session] optional session to use for this operation - * @return {UnorderedBulkOperation} - */ -Collection.prototype.initializeUnorderedBulkOp = function(options) { - options = options || {}; - // Give function's options precedence over session options. - if (options.ignoreUndefined == null) { - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - options.promiseLibrary = this.s.promiseLibrary; - return unordered(this.s.topology, this, options); -}; - -/** - * Initiate an In order bulk write operation. Operations will be serially executed in the order they are added, creating a new operation for each switch in types. - * - * @method - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {OrderedBulkOperation} callback The command result callback - * @return {null} - */ -Collection.prototype.initializeOrderedBulkOp = function(options) { - options = options || {}; - // Give function's options precedence over session's options. - if (options.ignoreUndefined == null) { - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - options.promiseLibrary = this.s.promiseLibrary; - return ordered(this.s.topology, this, options); -}; - -/** - * Return the db logger - * @method - * @return {Logger} return the db logger - * @ignore - */ -Collection.prototype.getLogger = function() { - return this.s.db.s.logger; -}; - -module.exports = Collection; diff --git a/scripts/2.5/node_modules/mongodb/lib/command_cursor.js b/scripts/2.5/node_modules/mongodb/lib/command_cursor.js deleted file mode 100644 index cd0f9d7a..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/command_cursor.js +++ /dev/null @@ -1,269 +0,0 @@ -'use strict'; - -const ReadPreference = require('./core').ReadPreference; -const MongoError = require('./core').MongoError; -const Cursor = require('./cursor'); -const CursorState = require('./core/cursor').CursorState; - -/** - * @fileOverview The **CommandCursor** class is an internal class that embodies a - * generalized cursor based on a MongoDB command allowing for iteration over the - * results returned. It supports one by one document iteration, conversion to an - * array or can be iterated as a Node 0.10.X or higher stream - * - * **CommandCursor Cannot directly be instantiated** - * @example - * const MongoClient = require('mongodb').MongoClient; - * const test = require('assert'); - * // Connection url - * const url = 'mongodb://localhost:27017'; - * // Database Name - * const dbName = 'test'; - * // Connect using MongoClient - * MongoClient.connect(url, function(err, client) { - * // Create a collection we want to drop later - * const col = client.db(dbName).collection('listCollectionsExample1'); - * // Insert a bunch of documents - * col.insert([{a:1, b:1} - * , {a:2, b:2}, {a:3, b:3} - * , {a:4, b:4}], {w:1}, function(err, result) { - * test.equal(null, err); - * // List the database collections available - * db.listCollections().toArray(function(err, items) { - * test.equal(null, err); - * client.close(); - * }); - * }); - * }); - */ - -/** - * Namespace provided by the browser. - * @external Readable - */ - -/** - * Creates a new Command Cursor instance (INTERNAL TYPE, do not instantiate directly) - * @class CommandCursor - * @extends external:Readable - * @fires CommandCursor#data - * @fires CommandCursor#end - * @fires CommandCursor#close - * @fires CommandCursor#readable - * @return {CommandCursor} an CommandCursor instance. - */ -class CommandCursor extends Cursor { - constructor(topology, ns, cmd, options) { - super(topology, ns, cmd, options); - } - - /** - * Set the ReadPreference for the cursor. - * @method - * @param {(string|ReadPreference)} readPreference The new read preference for the cursor. - * @throws {MongoError} - * @return {Cursor} - */ - setReadPreference(readPreference) { - if (this.s.state === CursorState.CLOSED || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - if (this.s.state !== CursorState.INIT) { - throw MongoError.create({ - message: 'cannot change cursor readPreference after cursor has been accessed', - driver: true - }); - } - - if (readPreference instanceof ReadPreference) { - this.options.readPreference = readPreference; - } else if (typeof readPreference === 'string') { - this.options.readPreference = new ReadPreference(readPreference); - } else { - throw new TypeError('Invalid read preference: ' + readPreference); - } - - return this; - } - - /** - * Set the batch size for the cursor. - * @method - * @param {number} value The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/find/|find command documentation}. - * @throws {MongoError} - * @return {CommandCursor} - */ - batchSize(value) { - if (this.s.state === CursorState.CLOSED || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - if (typeof value !== 'number') { - throw MongoError.create({ message: 'batchSize requires an integer', driver: true }); - } - - if (this.cmd.cursor) { - this.cmd.cursor.batchSize = value; - } - - this.setCursorBatchSize(value); - return this; - } - - /** - * Add a maxTimeMS stage to the aggregation pipeline - * @method - * @param {number} value The state maxTimeMS value. - * @return {CommandCursor} - */ - maxTimeMS(value) { - if (this.topology.lastIsMaster().minWireVersion > 2) { - this.cmd.maxTimeMS = value; - } - - return this; - } - - /** - * Return the cursor logger - * @method - * @return {Logger} return the cursor logger - * @ignore - */ - getLogger() { - return this.logger; - } -} - -// aliases -CommandCursor.prototype.get = CommandCursor.prototype.toArray; - -/** - * CommandCursor stream data event, fired for each document in the cursor. - * - * @event CommandCursor#data - * @type {object} - */ - -/** - * CommandCursor stream end event - * - * @event CommandCursor#end - * @type {null} - */ - -/** - * CommandCursor stream close event - * - * @event CommandCursor#close - * @type {null} - */ - -/** - * CommandCursor stream readable event - * - * @event CommandCursor#readable - * @type {null} - */ - -/** - * Get the next available document from the cursor, returns null if no more documents are available. - * @function CommandCursor.prototype.next - * @param {CommandCursor~resultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ - -/** - * Check if there is any document still available in the cursor - * @function CommandCursor.prototype.hasNext - * @param {CommandCursor~resultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ - -/** - * The callback format for results - * @callback CommandCursor~toArrayResultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {object[]} documents All the documents the satisfy the cursor. - */ - -/** - * Returns an array of documents. The caller is responsible for making sure that there - * is enough memory to store the results. Note that the array only contain partial - * results when this cursor had been previously accessed. - * @method CommandCursor.prototype.toArray - * @param {CommandCursor~toArrayResultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ - -/** - * The callback format for results - * @callback CommandCursor~resultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {(object|null)} result The result object if the command was executed successfully. - */ - -/** - * Iterates over all the documents for this cursor. As with **{cursor.toArray}**, - * not all of the elements will be iterated if this cursor had been previously accessed. - * In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike - * **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements - * at any given time if batch size is specified. Otherwise, the caller is responsible - * for making sure that the entire result can fit the memory. - * @method CommandCursor.prototype.each - * @param {CommandCursor~resultCallback} callback The result callback. - * @throws {MongoError} - * @return {null} - */ - -/** - * Close the cursor, sending a KillCursor command and emitting close. - * @method CommandCursor.prototype.close - * @param {CommandCursor~resultCallback} [callback] The result callback. - * @return {Promise} returns Promise if no callback passed - */ - -/** - * Is the cursor closed - * @method CommandCursor.prototype.isClosed - * @return {boolean} - */ - -/** - * Clone the cursor - * @function CommandCursor.prototype.clone - * @return {CommandCursor} - */ - -/** - * Resets the cursor - * @function CommandCursor.prototype.rewind - * @return {CommandCursor} - */ - -/** - * The callback format for the forEach iterator method - * @callback CommandCursor~iteratorCallback - * @param {Object} doc An emitted document for the iterator - */ - -/** - * The callback error format for the forEach iterator method - * @callback CommandCursor~endCallback - * @param {MongoError} error An error instance representing the error during the execution. - */ - -/* - * Iterates over all the documents for this cursor using the iterator, callback pattern. - * @method CommandCursor.prototype.forEach - * @param {CommandCursor~iteratorCallback} iterator The iteration callback. - * @param {CommandCursor~endCallback} callback The end callback. - * @throws {MongoError} - * @return {null} - */ - -module.exports = CommandCursor; diff --git a/scripts/2.5/node_modules/mongodb/lib/constants.js b/scripts/2.5/node_modules/mongodb/lib/constants.js deleted file mode 100644 index d6cc68ad..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/constants.js +++ /dev/null @@ -1,10 +0,0 @@ -'use strict'; - -module.exports = { - SYSTEM_NAMESPACE_COLLECTION: 'system.namespaces', - SYSTEM_INDEX_COLLECTION: 'system.indexes', - SYSTEM_PROFILE_COLLECTION: 'system.profile', - SYSTEM_USER_COLLECTION: 'system.users', - SYSTEM_COMMAND_COLLECTION: '$cmd', - SYSTEM_JS_COLLECTION: 'system.js' -}; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/auth/auth_provider.js b/scripts/2.5/node_modules/mongodb/lib/core/auth/auth_provider.js deleted file mode 100644 index 7597b728..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/core/auth/auth_provider.js +++ /dev/null @@ -1,158 +0,0 @@ -'use strict'; - -const MongoError = require('../error').MongoError; - -/** - * Creates a new AuthProvider, which dictates how to authenticate for a given - * mechanism. - * @class - */ -class AuthProvider { - constructor(bson) { - this.bson = bson; - this.authStore = []; - } - - /** - * Authenticate - * @method - * @param {SendAuthCommand} sendAuthCommand Writes an auth command directly to a specific connection - * @param {Connection[]} connections Connections to authenticate using this authenticator - * @param {MongoCredentials} credentials Authentication credentials - * @param {authResultCallback} callback The callback to return the result from the authentication - */ - auth(sendAuthCommand, connections, credentials, callback) { - // Total connections - let count = connections.length; - - if (count === 0) { - callback(null, null); - return; - } - - // Valid connections - let numberOfValidConnections = 0; - let errorObject = null; - - const execute = connection => { - this._authenticateSingleConnection(sendAuthCommand, connection, credentials, (err, r) => { - // Adjust count - count = count - 1; - - // If we have an error - if (err) { - errorObject = new MongoError(err); - } else if (r && (r.$err || r.errmsg)) { - errorObject = new MongoError(r); - } else { - numberOfValidConnections = numberOfValidConnections + 1; - } - - // Still authenticating against other connections. - if (count !== 0) { - return; - } - - // We have authenticated all connections - if (numberOfValidConnections > 0) { - // Store the auth details - this.addCredentials(credentials); - // Return correct authentication - callback(null, true); - } else { - if (errorObject == null) { - errorObject = new MongoError(`failed to authenticate using ${credentials.mechanism}`); - } - callback(errorObject, false); - } - }); - }; - - const executeInNextTick = _connection => process.nextTick(() => execute(_connection)); - - // For each connection we need to authenticate - while (connections.length > 0) { - executeInNextTick(connections.shift()); - } - } - - /** - * Implementation of a single connection authenticating. Is meant to be overridden. - * Will error if called directly - * @ignore - */ - _authenticateSingleConnection(/*sendAuthCommand, connection, credentials, callback*/) { - throw new Error('_authenticateSingleConnection must be overridden'); - } - - /** - * Adds credentials to store only if it does not exist - * @param {MongoCredentials} credentials credentials to add to store - */ - addCredentials(credentials) { - const found = this.authStore.some(cred => cred.equals(credentials)); - - if (!found) { - this.authStore.push(credentials); - } - } - - /** - * Re authenticate pool - * @method - * @param {SendAuthCommand} sendAuthCommand Writes an auth command directly to a specific connection - * @param {Connection[]} connections Connections to authenticate using this authenticator - * @param {authResultCallback} callback The callback to return the result from the authentication - */ - reauthenticate(sendAuthCommand, connections, callback) { - const authStore = this.authStore.slice(0); - let count = authStore.length; - if (count === 0) { - return callback(null, null); - } - - for (let i = 0; i < authStore.length; i++) { - this.auth(sendAuthCommand, connections, authStore[i], function(err) { - count = count - 1; - if (count === 0) { - callback(err, null); - } - }); - } - } - - /** - * Remove credentials that have been previously stored in the auth provider - * @method - * @param {string} source Name of database we are removing authStore details about - * @return {object} - */ - logout(source) { - this.authStore = this.authStore.filter(credentials => credentials.source !== source); - } -} - -/** - * A function that writes authentication commands to a specific connection - * @callback SendAuthCommand - * @param {Connection} connection The connection to write to - * @param {Command} command A command with a toBin method that can be written to a connection - * @param {AuthWriteCallback} callback Callback called when command response is received - */ - -/** - * A callback for a specific auth command - * @callback AuthWriteCallback - * @param {Error} err If command failed, an error from the server - * @param {object} r The response from the server - */ - -/** - * This is a result from an authentication strategy - * - * @callback authResultCallback - * @param {error} error An error object. Set to null if no error present - * @param {boolean} result The result of the authentication process - */ - -module.exports = { AuthProvider }; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/auth/defaultAuthProviders.js b/scripts/2.5/node_modules/mongodb/lib/core/auth/defaultAuthProviders.js deleted file mode 100644 index fc5f4c28..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/core/auth/defaultAuthProviders.js +++ /dev/null @@ -1,29 +0,0 @@ -'use strict'; - -const MongoCR = require('./mongocr'); -const X509 = require('./x509'); -const Plain = require('./plain'); -const GSSAPI = require('./gssapi'); -const SSPI = require('./sspi'); -const ScramSHA1 = require('./scram').ScramSHA1; -const ScramSHA256 = require('./scram').ScramSHA256; - -/** - * Returns the default authentication providers. - * - * @param {BSON} bson Bson definition - * @returns {Object} a mapping of auth names to auth types - */ -function defaultAuthProviders(bson) { - return { - mongocr: new MongoCR(bson), - x509: new X509(bson), - plain: new Plain(bson), - gssapi: new GSSAPI(bson), - sspi: new SSPI(bson), - 'scram-sha-1': new ScramSHA1(bson), - 'scram-sha-256': new ScramSHA256(bson) - }; -} - -module.exports = { defaultAuthProviders }; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/auth/gssapi.js b/scripts/2.5/node_modules/mongodb/lib/core/auth/gssapi.js deleted file mode 100644 index 936fb65a..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/core/auth/gssapi.js +++ /dev/null @@ -1,241 +0,0 @@ -'use strict'; - -const AuthProvider = require('./auth_provider').AuthProvider; -const retrieveKerberos = require('../utils').retrieveKerberos; -let kerberos; - -/** - * Creates a new GSSAPI authentication mechanism - * @class - * @extends AuthProvider - */ -class GSSAPI extends AuthProvider { - /** - * Implementation of authentication for a single connection - * @override - */ - _authenticateSingleConnection(sendAuthCommand, connection, credentials, callback) { - const source = credentials.source; - const username = credentials.username; - const password = credentials.password; - const mechanismProperties = credentials.mechanismProperties; - const gssapiServiceName = - mechanismProperties['gssapiservicename'] || - mechanismProperties['gssapiServiceName'] || - 'mongodb'; - - GSSAPIInitialize( - this, - kerberos.processes.MongoAuthProcess, - source, - username, - password, - source, - gssapiServiceName, - sendAuthCommand, - connection, - mechanismProperties, - callback - ); - } - - /** - * Authenticate - * @override - * @method - */ - auth(sendAuthCommand, connections, credentials, callback) { - if (kerberos == null) { - try { - kerberos = retrieveKerberos(); - } catch (e) { - return callback(e, null); - } - } - - super.auth(sendAuthCommand, connections, credentials, callback); - } -} - -// -// Initialize step -var GSSAPIInitialize = function( - self, - MongoAuthProcess, - db, - username, - password, - authdb, - gssapiServiceName, - sendAuthCommand, - connection, - options, - callback -) { - // Create authenticator - var mongo_auth_process = new MongoAuthProcess( - connection.host, - connection.port, - gssapiServiceName, - options - ); - - // Perform initialization - mongo_auth_process.init(username, password, function(err) { - if (err) return callback(err, false); - - // Perform the first step - mongo_auth_process.transition('', function(err, payload) { - if (err) return callback(err, false); - - // Call the next db step - MongoDBGSSAPIFirstStep( - self, - mongo_auth_process, - payload, - db, - username, - password, - authdb, - sendAuthCommand, - connection, - callback - ); - }); - }); -}; - -// -// Perform first step against mongodb -var MongoDBGSSAPIFirstStep = function( - self, - mongo_auth_process, - payload, - db, - username, - password, - authdb, - sendAuthCommand, - connection, - callback -) { - // Build the sasl start command - var command = { - saslStart: 1, - mechanism: 'GSSAPI', - payload: payload, - autoAuthorize: 1 - }; - - // Write the commmand on the connection - sendAuthCommand(connection, '$external.$cmd', command, (err, doc) => { - if (err) return callback(err, false); - // Execute mongodb transition - mongo_auth_process.transition(doc.payload, function(err, payload) { - if (err) return callback(err, false); - - // MongoDB API Second Step - MongoDBGSSAPISecondStep( - self, - mongo_auth_process, - payload, - doc, - db, - username, - password, - authdb, - sendAuthCommand, - connection, - callback - ); - }); - }); -}; - -// -// Perform first step against mongodb -var MongoDBGSSAPISecondStep = function( - self, - mongo_auth_process, - payload, - doc, - db, - username, - password, - authdb, - sendAuthCommand, - connection, - callback -) { - // Build Authentication command to send to MongoDB - var command = { - saslContinue: 1, - conversationId: doc.conversationId, - payload: payload - }; - - // Execute the command - // Write the commmand on the connection - sendAuthCommand(connection, '$external.$cmd', command, (err, doc) => { - if (err) return callback(err, false); - // Call next transition for kerberos - mongo_auth_process.transition(doc.payload, function(err, payload) { - if (err) return callback(err, false); - - // Call the last and third step - MongoDBGSSAPIThirdStep( - self, - mongo_auth_process, - payload, - doc, - db, - username, - password, - authdb, - sendAuthCommand, - connection, - callback - ); - }); - }); -}; - -var MongoDBGSSAPIThirdStep = function( - self, - mongo_auth_process, - payload, - doc, - db, - username, - password, - authdb, - sendAuthCommand, - connection, - callback -) { - // Build final command - var command = { - saslContinue: 1, - conversationId: doc.conversationId, - payload: payload - }; - - // Execute the command - sendAuthCommand(connection, '$external.$cmd', command, (err, r) => { - if (err) return callback(err, false); - mongo_auth_process.transition(null, function(err) { - if (err) return callback(err, null); - callback(null, r); - }); - }); -}; - -/** - * This is a result from a authentication strategy - * - * @callback authResultCallback - * @param {error} error An error object. Set to null if no error present - * @param {boolean} result The result of the authentication process - */ - -module.exports = GSSAPI; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/auth/mongo_credentials.js b/scripts/2.5/node_modules/mongodb/lib/core/auth/mongo_credentials.js deleted file mode 100644 index 13c00b14..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/core/auth/mongo_credentials.js +++ /dev/null @@ -1,81 +0,0 @@ -'use strict'; - -// Resolves the default auth mechanism according to -// https://github.com/mongodb/specifications/blob/master/source/auth/auth.rst -function getDefaultAuthMechanism(ismaster) { - if (ismaster) { - // If ismaster contains saslSupportedMechs, use scram-sha-256 - // if it is available, else scram-sha-1 - if (Array.isArray(ismaster.saslSupportedMechs)) { - return ismaster.saslSupportedMechs.indexOf('SCRAM-SHA-256') >= 0 - ? 'scram-sha-256' - : 'scram-sha-1'; - } - - // Fallback to legacy selection method. If wire version >= 3, use scram-sha-1 - if (ismaster.maxWireVersion >= 3) { - return 'scram-sha-1'; - } - } - - // Default for wireprotocol < 3 - return 'mongocr'; -} - -/** - * A representation of the credentials used by MongoDB - * @class - * @property {string} mechanism The method used to authenticate - * @property {string} [username] The username used for authentication - * @property {string} [password] The password used for authentication - * @property {string} [source] The database that the user should authenticate against - * @property {object} [mechanismProperties] Special properties used by some types of auth mechanisms - */ -class MongoCredentials { - /** - * Creates a new MongoCredentials object - * @param {object} [options] - * @param {string} [options.username] The username used for authentication - * @param {string} [options.password] The password used for authentication - * @param {string} [options.source] The database that the user should authenticate against - * @param {string} [options.mechanism] The method used to authenticate - * @param {object} [options.mechanismProperties] Special properties used by some types of auth mechanisms - */ - constructor(options) { - options = options || {}; - this.username = options.username; - this.password = options.password; - this.source = options.source || options.db; - this.mechanism = options.mechanism || 'default'; - this.mechanismProperties = options.mechanismProperties; - } - - /** - * Determines if two MongoCredentials objects are equivalent - * @param {MongoCredentials} other another MongoCredentials object - * @returns {boolean} true if the two objects are equal. - */ - equals(other) { - return ( - this.mechanism === other.mechanism && - this.username === other.username && - this.password === other.password && - this.source === other.source - ); - } - - /** - * If the authentication mechanism is set to "default", resolves the authMechanism - * based on the server version and server supported sasl mechanisms. - * - * @param {Object} [ismaster] An ismaster response from the server - */ - resolveAuthMechanism(ismaster) { - // If the mechanism is not "default", then it does not need to be resolved - if (this.mechanism.toLowerCase() === 'default') { - this.mechanism = getDefaultAuthMechanism(ismaster); - } - } -} - -module.exports = { MongoCredentials }; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/auth/mongocr.js b/scripts/2.5/node_modules/mongodb/lib/core/auth/mongocr.js deleted file mode 100644 index be8fcb6b..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/core/auth/mongocr.js +++ /dev/null @@ -1,51 +0,0 @@ -'use strict'; - -const crypto = require('crypto'); -const AuthProvider = require('./auth_provider').AuthProvider; - -/** - * Creates a new MongoCR authentication mechanism - * - * @extends AuthProvider - */ -class MongoCR extends AuthProvider { - /** - * Implementation of authentication for a single connection - * @override - */ - _authenticateSingleConnection(sendAuthCommand, connection, credentials, callback) { - const username = credentials.username; - const password = credentials.password; - const source = credentials.source; - - sendAuthCommand(connection, `${source}.$cmd`, { getnonce: 1 }, (err, r) => { - let nonce = null; - let key = null; - - // Get nonce - if (err == null) { - nonce = r.nonce; - // Use node md5 generator - let md5 = crypto.createHash('md5'); - // Generate keys used for authentication - md5.update(username + ':mongo:' + password, 'utf8'); - const hash_password = md5.digest('hex'); - // Final key - md5 = crypto.createHash('md5'); - md5.update(nonce + username + hash_password, 'utf8'); - key = md5.digest('hex'); - } - - const authenticateCommand = { - authenticate: 1, - user: username, - nonce, - key - }; - - sendAuthCommand(connection, `${source}.$cmd`, authenticateCommand, callback); - }); - } -} - -module.exports = MongoCR; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/auth/plain.js b/scripts/2.5/node_modules/mongodb/lib/core/auth/plain.js deleted file mode 100644 index 240de758..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/core/auth/plain.js +++ /dev/null @@ -1,35 +0,0 @@ -'use strict'; - -const retrieveBSON = require('../connection/utils').retrieveBSON; -const AuthProvider = require('./auth_provider').AuthProvider; - -// TODO: can we get the Binary type from this.bson instead? -const BSON = retrieveBSON(); -const Binary = BSON.Binary; - -/** - * Creates a new Plain authentication mechanism - * - * @extends AuthProvider - */ -class Plain extends AuthProvider { - /** - * Implementation of authentication for a single connection - * @override - */ - _authenticateSingleConnection(sendAuthCommand, connection, credentials, callback) { - const username = credentials.username; - const password = credentials.password; - const payload = new Binary(`\x00${username}\x00${password}`); - const command = { - saslStart: 1, - mechanism: 'PLAIN', - payload: payload, - autoAuthorize: 1 - }; - - sendAuthCommand(connection, '$external.$cmd', command, callback); - } -} - -module.exports = Plain; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/auth/scram.js b/scripts/2.5/node_modules/mongodb/lib/core/auth/scram.js deleted file mode 100644 index ac8853eb..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/core/auth/scram.js +++ /dev/null @@ -1,293 +0,0 @@ -'use strict'; - -const crypto = require('crypto'); -const Buffer = require('safe-buffer').Buffer; -const retrieveBSON = require('../connection/utils').retrieveBSON; -const MongoError = require('../error').MongoError; -const AuthProvider = require('./auth_provider').AuthProvider; - -const BSON = retrieveBSON(); -const Binary = BSON.Binary; - -let saslprep; -try { - saslprep = require('saslprep'); -} catch (e) { - // don't do anything; -} - -var parsePayload = function(payload) { - var dict = {}; - var parts = payload.split(','); - - for (var i = 0; i < parts.length; i++) { - var valueParts = parts[i].split('='); - dict[valueParts[0]] = valueParts[1]; - } - - return dict; -}; - -var passwordDigest = function(username, password) { - if (typeof username !== 'string') throw new MongoError('username must be a string'); - if (typeof password !== 'string') throw new MongoError('password must be a string'); - if (password.length === 0) throw new MongoError('password cannot be empty'); - // Use node md5 generator - var md5 = crypto.createHash('md5'); - // Generate keys used for authentication - md5.update(username + ':mongo:' + password, 'utf8'); - return md5.digest('hex'); -}; - -// XOR two buffers -function xor(a, b) { - if (!Buffer.isBuffer(a)) a = Buffer.from(a); - if (!Buffer.isBuffer(b)) b = Buffer.from(b); - const length = Math.max(a.length, b.length); - const res = []; - - for (let i = 0; i < length; i += 1) { - res.push(a[i] ^ b[i]); - } - - return Buffer.from(res).toString('base64'); -} - -function H(method, text) { - return crypto - .createHash(method) - .update(text) - .digest(); -} - -function HMAC(method, key, text) { - return crypto - .createHmac(method, key) - .update(text) - .digest(); -} - -var _hiCache = {}; -var _hiCacheCount = 0; -var _hiCachePurge = function() { - _hiCache = {}; - _hiCacheCount = 0; -}; - -const hiLengthMap = { - sha256: 32, - sha1: 20 -}; - -function HI(data, salt, iterations, cryptoMethod) { - // omit the work if already generated - const key = [data, salt.toString('base64'), iterations].join('_'); - if (_hiCache[key] !== undefined) { - return _hiCache[key]; - } - - // generate the salt - const saltedData = crypto.pbkdf2Sync( - data, - salt, - iterations, - hiLengthMap[cryptoMethod], - cryptoMethod - ); - - // cache a copy to speed up the next lookup, but prevent unbounded cache growth - if (_hiCacheCount >= 200) { - _hiCachePurge(); - } - - _hiCache[key] = saltedData; - _hiCacheCount += 1; - return saltedData; -} - -/** - * Creates a new ScramSHA authentication mechanism - * @class - * @extends AuthProvider - */ -class ScramSHA extends AuthProvider { - constructor(bson, cryptoMethod) { - super(bson); - this.cryptoMethod = cryptoMethod || 'sha1'; - } - - static _getError(err, r) { - if (err) { - return err; - } - - if (r.$err || r.errmsg) { - return new MongoError(r); - } - } - - /** - * @ignore - */ - _executeScram(sendAuthCommand, connection, credentials, nonce, callback) { - let username = credentials.username; - const password = credentials.password; - const db = credentials.source; - - const cryptoMethod = this.cryptoMethod; - let mechanism = 'SCRAM-SHA-1'; - let processedPassword; - - if (cryptoMethod === 'sha256') { - mechanism = 'SCRAM-SHA-256'; - - processedPassword = saslprep ? saslprep(password) : password; - } else { - try { - processedPassword = passwordDigest(username, password); - } catch (e) { - return callback(e); - } - } - - // Clean up the user - username = username.replace('=', '=3D').replace(',', '=2C'); - - // NOTE: This is done b/c Javascript uses UTF-16, but the server is hashing in UTF-8. - // Since the username is not sasl-prep-d, we need to do this here. - const firstBare = Buffer.concat([ - Buffer.from('n=', 'utf8'), - Buffer.from(username, 'utf8'), - Buffer.from(',r=', 'utf8'), - Buffer.from(nonce, 'utf8') - ]); - - // Build command structure - const saslStartCmd = { - saslStart: 1, - mechanism, - payload: new Binary(Buffer.concat([Buffer.from('n,,', 'utf8'), firstBare])), - autoAuthorize: 1 - }; - - // Write the commmand on the connection - sendAuthCommand(connection, `${db}.$cmd`, saslStartCmd, (err, r) => { - let tmpError = ScramSHA._getError(err, r); - if (tmpError) { - return callback(tmpError, null); - } - - const payload = Buffer.isBuffer(r.payload) ? new Binary(r.payload) : r.payload; - const dict = parsePayload(payload.value()); - const iterations = parseInt(dict.i, 10); - const salt = dict.s; - const rnonce = dict.r; - - // Set up start of proof - const withoutProof = `c=biws,r=${rnonce}`; - const saltedPassword = HI( - processedPassword, - Buffer.from(salt, 'base64'), - iterations, - cryptoMethod - ); - - if (iterations && iterations < 4096) { - const error = new MongoError(`Server returned an invalid iteration count ${iterations}`); - return callback(error, false); - } - - const clientKey = HMAC(cryptoMethod, saltedPassword, 'Client Key'); - const storedKey = H(cryptoMethod, clientKey); - const authMessage = [firstBare, payload.value().toString('base64'), withoutProof].join(','); - - const clientSignature = HMAC(cryptoMethod, storedKey, authMessage); - const clientProof = `p=${xor(clientKey, clientSignature)}`; - const clientFinal = [withoutProof, clientProof].join(','); - const saslContinueCmd = { - saslContinue: 1, - conversationId: r.conversationId, - payload: new Binary(Buffer.from(clientFinal)) - }; - - sendAuthCommand(connection, `${db}.$cmd`, saslContinueCmd, (err, r) => { - if (!r || r.done !== false) { - return callback(err, r); - } - - const retrySaslContinueCmd = { - saslContinue: 1, - conversationId: r.conversationId, - payload: Buffer.alloc(0) - }; - - sendAuthCommand(connection, `${db}.$cmd`, retrySaslContinueCmd, callback); - }); - }); - } - - /** - * Implementation of authentication for a single connection - * @override - */ - _authenticateSingleConnection(sendAuthCommand, connection, credentials, callback) { - // Create a random nonce - crypto.randomBytes(24, (err, buff) => { - if (err) { - return callback(err, null); - } - - return this._executeScram( - sendAuthCommand, - connection, - credentials, - buff.toString('base64'), - callback - ); - }); - } - - /** - * Authenticate - * @override - * @method - */ - auth(sendAuthCommand, connections, credentials, callback) { - this._checkSaslprep(); - super.auth(sendAuthCommand, connections, credentials, callback); - } - - _checkSaslprep() { - const cryptoMethod = this.cryptoMethod; - - if (cryptoMethod === 'sha256') { - if (!saslprep) { - console.warn('Warning: no saslprep library specified. Passwords will not be sanitized'); - } - } - } -} - -/** - * Creates a new ScramSHA1 authentication mechanism - * @class - * @extends ScramSHA - */ -class ScramSHA1 extends ScramSHA { - constructor(bson) { - super(bson, 'sha1'); - } -} - -/** - * Creates a new ScramSHA256 authentication mechanism - * @class - * @extends ScramSHA - */ -class ScramSHA256 extends ScramSHA { - constructor(bson) { - super(bson, 'sha256'); - } -} - -module.exports = { ScramSHA1, ScramSHA256 }; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/auth/sspi.js b/scripts/2.5/node_modules/mongodb/lib/core/auth/sspi.js deleted file mode 100644 index 8a3f5448..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/core/auth/sspi.js +++ /dev/null @@ -1,131 +0,0 @@ -'use strict'; - -const AuthProvider = require('./auth_provider').AuthProvider; -const retrieveKerberos = require('../utils').retrieveKerberos; -let kerberos; - -/** - * Creates a new SSPI authentication mechanism - * @class - * @extends AuthProvider - */ -class SSPI extends AuthProvider { - /** - * Implementation of authentication for a single connection - * @override - */ - _authenticateSingleConnection(sendAuthCommand, connection, credentials, callback) { - // TODO: Destructure this - const username = credentials.username; - const password = credentials.password; - const mechanismProperties = credentials.mechanismProperties; - const gssapiServiceName = - mechanismProperties['gssapiservicename'] || - mechanismProperties['gssapiServiceName'] || - 'mongodb'; - - SSIPAuthenticate( - this, - kerberos.processes.MongoAuthProcess, - username, - password, - gssapiServiceName, - sendAuthCommand, - connection, - mechanismProperties, - callback - ); - } - - /** - * Authenticate - * @override - * @method - */ - auth(sendAuthCommand, connections, credentials, callback) { - if (kerberos == null) { - try { - kerberos = retrieveKerberos(); - } catch (e) { - return callback(e, null); - } - } - - super.auth(sendAuthCommand, connections, credentials, callback); - } -} - -function SSIPAuthenticate( - self, - MongoAuthProcess, - username, - password, - gssapiServiceName, - sendAuthCommand, - connection, - options, - callback -) { - const authProcess = new MongoAuthProcess( - connection.host, - connection.port, - gssapiServiceName, - options - ); - - function authCommand(command, authCb) { - sendAuthCommand(connection, '$external.$cmd', command, authCb); - } - - authProcess.init(username, password, err => { - if (err) return callback(err, false); - - authProcess.transition('', (err, payload) => { - if (err) return callback(err, false); - - const command = { - saslStart: 1, - mechanism: 'GSSAPI', - payload, - autoAuthorize: 1 - }; - - authCommand(command, (err, doc) => { - if (err) return callback(err, false); - - authProcess.transition(doc.payload, (err, payload) => { - if (err) return callback(err, false); - const command = { - saslContinue: 1, - conversationId: doc.conversationId, - payload - }; - - authCommand(command, (err, doc) => { - if (err) return callback(err, false); - - authProcess.transition(doc.payload, (err, payload) => { - if (err) return callback(err, false); - const command = { - saslContinue: 1, - conversationId: doc.conversationId, - payload - }; - - authCommand(command, (err, response) => { - if (err) return callback(err, false); - - authProcess.transition(null, err => { - if (err) return callback(err, null); - callback(null, response); - }); - }); - }); - }); - }); - }); - }); - }); -} - -module.exports = SSPI; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/auth/x509.js b/scripts/2.5/node_modules/mongodb/lib/core/auth/x509.js deleted file mode 100644 index 10d5b588..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/core/auth/x509.js +++ /dev/null @@ -1,26 +0,0 @@ -'use strict'; - -const AuthProvider = require('./auth_provider').AuthProvider; - -/** - * Creates a new X509 authentication mechanism - * @class - * @extends AuthProvider - */ -class X509 extends AuthProvider { - /** - * Implementation of authentication for a single connection - * @override - */ - _authenticateSingleConnection(sendAuthCommand, connection, credentials, callback) { - const username = credentials.username; - const command = { authenticate: 1, mechanism: 'MONGODB-X509' }; - if (username) { - command.user = username; - } - - sendAuthCommand(connection, '$external.$cmd', command, callback); - } -} - -module.exports = X509; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/connection/apm.js b/scripts/2.5/node_modules/mongodb/lib/core/connection/apm.js deleted file mode 100644 index defc59a1..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/core/connection/apm.js +++ /dev/null @@ -1,236 +0,0 @@ -'use strict'; -const Msg = require('../connection/msg').Msg; -const KillCursor = require('../connection/commands').KillCursor; -const GetMore = require('../connection/commands').GetMore; -const calculateDurationInMs = require('../utils').calculateDurationInMs; - -/** Commands that we want to redact because of the sensitive nature of their contents */ -const SENSITIVE_COMMANDS = new Set([ - 'authenticate', - 'saslStart', - 'saslContinue', - 'getnonce', - 'createUser', - 'updateUser', - 'copydbgetnonce', - 'copydbsaslstart', - 'copydb' -]); - -// helper methods -const extractCommandName = commandDoc => Object.keys(commandDoc)[0]; -const namespace = command => command.ns; -const databaseName = command => command.ns.split('.')[0]; -const collectionName = command => command.ns.split('.')[1]; -const generateConnectionId = pool => `${pool.options.host}:${pool.options.port}`; -const maybeRedact = (commandName, result) => (SENSITIVE_COMMANDS.has(commandName) ? {} : result); - -const LEGACY_FIND_QUERY_MAP = { - $query: 'filter', - $orderby: 'sort', - $hint: 'hint', - $comment: 'comment', - $maxScan: 'maxScan', - $max: 'max', - $min: 'min', - $returnKey: 'returnKey', - $showDiskLoc: 'showRecordId', - $maxTimeMS: 'maxTimeMS', - $snapshot: 'snapshot' -}; - -const LEGACY_FIND_OPTIONS_MAP = { - numberToSkip: 'skip', - numberToReturn: 'batchSize', - returnFieldsSelector: 'projection' -}; - -const OP_QUERY_KEYS = [ - 'tailable', - 'oplogReplay', - 'noCursorTimeout', - 'awaitData', - 'partial', - 'exhaust' -]; - -/** - * Extract the actual command from the query, possibly upconverting if it's a legacy - * format - * - * @param {Object} command the command - */ -const extractCommand = command => { - if (command instanceof GetMore) { - return { - getMore: command.cursorId, - collection: collectionName(command), - batchSize: command.numberToReturn - }; - } - - if (command instanceof KillCursor) { - return { - killCursors: collectionName(command), - cursors: command.cursorIds - }; - } - - if (command instanceof Msg) { - return command.command; - } - - if (command.query && command.query.$query) { - let result; - if (command.ns === 'admin.$cmd') { - // upconvert legacy command - result = Object.assign({}, command.query.$query); - } else { - // upconvert legacy find command - result = { find: collectionName(command) }; - Object.keys(LEGACY_FIND_QUERY_MAP).forEach(key => { - if (typeof command.query[key] !== 'undefined') - result[LEGACY_FIND_QUERY_MAP[key]] = command.query[key]; - }); - } - - Object.keys(LEGACY_FIND_OPTIONS_MAP).forEach(key => { - if (typeof command[key] !== 'undefined') result[LEGACY_FIND_OPTIONS_MAP[key]] = command[key]; - }); - - OP_QUERY_KEYS.forEach(key => { - if (command[key]) result[key] = command[key]; - }); - - if (typeof command.pre32Limit !== 'undefined') { - result.limit = command.pre32Limit; - } - - if (command.query.$explain) { - return { explain: result }; - } - - return result; - } - - return command.query ? command.query : command; -}; - -const extractReply = (command, reply) => { - if (command instanceof GetMore) { - return { - ok: 1, - cursor: { - id: reply.message.cursorId, - ns: namespace(command), - nextBatch: reply.message.documents - } - }; - } - - if (command instanceof KillCursor) { - return { - ok: 1, - cursorsUnknown: command.cursorIds - }; - } - - // is this a legacy find command? - if (command.query && typeof command.query.$query !== 'undefined') { - return { - ok: 1, - cursor: { - id: reply.message.cursorId, - ns: namespace(command), - firstBatch: reply.message.documents - } - }; - } - - // in the event of a `noResponse` command, just return - if (reply === null) return reply; - - return reply.result; -}; - -/** An event indicating the start of a given command */ -class CommandStartedEvent { - /** - * Create a started event - * - * @param {Pool} pool the pool that originated the command - * @param {Object} command the command - */ - constructor(pool, command) { - const cmd = extractCommand(command); - const commandName = extractCommandName(cmd); - - // NOTE: remove in major revision, this is not spec behavior - if (SENSITIVE_COMMANDS.has(commandName)) { - this.commandObj = {}; - this.commandObj[commandName] = true; - } - - Object.assign(this, { - command: cmd, - databaseName: databaseName(command), - commandName, - requestId: command.requestId, - connectionId: generateConnectionId(pool) - }); - } -} - -/** An event indicating the success of a given command */ -class CommandSucceededEvent { - /** - * Create a succeeded event - * - * @param {Pool} pool the pool that originated the command - * @param {Object} command the command - * @param {Object} reply the reply for this command from the server - * @param {Array} started a high resolution tuple timestamp of when the command was first sent, to calculate duration - */ - constructor(pool, command, reply, started) { - const cmd = extractCommand(command); - const commandName = extractCommandName(cmd); - - Object.assign(this, { - duration: calculateDurationInMs(started), - commandName, - reply: maybeRedact(commandName, extractReply(command, reply)), - requestId: command.requestId, - connectionId: generateConnectionId(pool) - }); - } -} - -/** An event indicating the failure of a given command */ -class CommandFailedEvent { - /** - * Create a failure event - * - * @param {Pool} pool the pool that originated the command - * @param {Object} command the command - * @param {MongoError|Object} error the generated error or a server error response - * @param {Array} started a high resolution tuple timestamp of when the command was first sent, to calculate duration - */ - constructor(pool, command, error, started) { - const cmd = extractCommand(command); - const commandName = extractCommandName(cmd); - - Object.assign(this, { - duration: calculateDurationInMs(started), - commandName, - failure: maybeRedact(commandName, error), - requestId: command.requestId, - connectionId: generateConnectionId(pool) - }); - } -} - -module.exports = { - CommandStartedEvent, - CommandSucceededEvent, - CommandFailedEvent -}; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/connection/command_result.js b/scripts/2.5/node_modules/mongodb/lib/core/connection/command_result.js deleted file mode 100644 index 762aa3f1..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/core/connection/command_result.js +++ /dev/null @@ -1,36 +0,0 @@ -'use strict'; - -/** - * Creates a new CommandResult instance - * @class - * @param {object} result CommandResult object - * @param {Connection} connection A connection instance associated with this result - * @return {CommandResult} A cursor instance - */ -var CommandResult = function(result, connection, message) { - this.result = result; - this.connection = connection; - this.message = message; -}; - -/** - * Convert CommandResult to JSON - * @method - * @return {object} - */ -CommandResult.prototype.toJSON = function() { - let result = Object.assign({}, this, this.result); - delete result.message; - return result; -}; - -/** - * Convert CommandResult to String representation - * @method - * @return {string} - */ -CommandResult.prototype.toString = function() { - return JSON.stringify(this.toJSON()); -}; - -module.exports = CommandResult; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/connection/commands.js b/scripts/2.5/node_modules/mongodb/lib/core/connection/commands.js deleted file mode 100644 index b24ff848..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/core/connection/commands.js +++ /dev/null @@ -1,507 +0,0 @@ -'use strict'; - -var retrieveBSON = require('./utils').retrieveBSON; -var BSON = retrieveBSON(); -var Long = BSON.Long; -const Buffer = require('safe-buffer').Buffer; - -// Incrementing request id -var _requestId = 0; - -// Wire command operation ids -var opcodes = require('../wireprotocol/shared').opcodes; - -// Query flags -var OPTS_TAILABLE_CURSOR = 2; -var OPTS_SLAVE = 4; -var OPTS_OPLOG_REPLAY = 8; -var OPTS_NO_CURSOR_TIMEOUT = 16; -var OPTS_AWAIT_DATA = 32; -var OPTS_EXHAUST = 64; -var OPTS_PARTIAL = 128; - -// Response flags -var CURSOR_NOT_FOUND = 1; -var QUERY_FAILURE = 2; -var SHARD_CONFIG_STALE = 4; -var AWAIT_CAPABLE = 8; - -/************************************************************** - * QUERY - **************************************************************/ -var Query = function(bson, ns, query, options) { - var self = this; - // Basic options needed to be passed in - if (ns == null) throw new Error('ns must be specified for query'); - if (query == null) throw new Error('query must be specified for query'); - - // Validate that we are not passing 0x00 in the collection name - if (ns.indexOf('\x00') !== -1) { - throw new Error('namespace cannot contain a null character'); - } - - // Basic options - this.bson = bson; - this.ns = ns; - this.query = query; - - // Additional options - this.numberToSkip = options.numberToSkip || 0; - this.numberToReturn = options.numberToReturn || 0; - this.returnFieldSelector = options.returnFieldSelector || null; - this.requestId = Query.getRequestId(); - - // special case for pre-3.2 find commands, delete ASAP - this.pre32Limit = options.pre32Limit; - - // Serialization option - this.serializeFunctions = - typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; - this.ignoreUndefined = - typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : false; - this.maxBsonSize = options.maxBsonSize || 1024 * 1024 * 16; - this.checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : true; - this.batchSize = self.numberToReturn; - - // Flags - this.tailable = false; - this.slaveOk = typeof options.slaveOk === 'boolean' ? options.slaveOk : false; - this.oplogReplay = false; - this.noCursorTimeout = false; - this.awaitData = false; - this.exhaust = false; - this.partial = false; -}; - -// -// Assign a new request Id -Query.prototype.incRequestId = function() { - this.requestId = _requestId++; -}; - -// -// Assign a new request Id -Query.nextRequestId = function() { - return _requestId + 1; -}; - -// -// Uses a single allocated buffer for the process, avoiding multiple memory allocations -Query.prototype.toBin = function() { - var self = this; - var buffers = []; - var projection = null; - - // Set up the flags - var flags = 0; - if (this.tailable) { - flags |= OPTS_TAILABLE_CURSOR; - } - - if (this.slaveOk) { - flags |= OPTS_SLAVE; - } - - if (this.oplogReplay) { - flags |= OPTS_OPLOG_REPLAY; - } - - if (this.noCursorTimeout) { - flags |= OPTS_NO_CURSOR_TIMEOUT; - } - - if (this.awaitData) { - flags |= OPTS_AWAIT_DATA; - } - - if (this.exhaust) { - flags |= OPTS_EXHAUST; - } - - if (this.partial) { - flags |= OPTS_PARTIAL; - } - - // If batchSize is different to self.numberToReturn - if (self.batchSize !== self.numberToReturn) self.numberToReturn = self.batchSize; - - // Allocate write protocol header buffer - var header = Buffer.alloc( - 4 * 4 + // Header - 4 + // Flags - Buffer.byteLength(self.ns) + - 1 + // namespace - 4 + // numberToSkip - 4 // numberToReturn - ); - - // Add header to buffers - buffers.push(header); - - // Serialize the query - var query = self.bson.serialize(this.query, { - checkKeys: this.checkKeys, - serializeFunctions: this.serializeFunctions, - ignoreUndefined: this.ignoreUndefined - }); - - // Add query document - buffers.push(query); - - if (self.returnFieldSelector && Object.keys(self.returnFieldSelector).length > 0) { - // Serialize the projection document - projection = self.bson.serialize(this.returnFieldSelector, { - checkKeys: this.checkKeys, - serializeFunctions: this.serializeFunctions, - ignoreUndefined: this.ignoreUndefined - }); - // Add projection document - buffers.push(projection); - } - - // Total message size - var totalLength = header.length + query.length + (projection ? projection.length : 0); - - // Set up the index - var index = 4; - - // Write total document length - header[3] = (totalLength >> 24) & 0xff; - header[2] = (totalLength >> 16) & 0xff; - header[1] = (totalLength >> 8) & 0xff; - header[0] = totalLength & 0xff; - - // Write header information requestId - header[index + 3] = (this.requestId >> 24) & 0xff; - header[index + 2] = (this.requestId >> 16) & 0xff; - header[index + 1] = (this.requestId >> 8) & 0xff; - header[index] = this.requestId & 0xff; - index = index + 4; - - // Write header information responseTo - header[index + 3] = (0 >> 24) & 0xff; - header[index + 2] = (0 >> 16) & 0xff; - header[index + 1] = (0 >> 8) & 0xff; - header[index] = 0 & 0xff; - index = index + 4; - - // Write header information OP_QUERY - header[index + 3] = (opcodes.OP_QUERY >> 24) & 0xff; - header[index + 2] = (opcodes.OP_QUERY >> 16) & 0xff; - header[index + 1] = (opcodes.OP_QUERY >> 8) & 0xff; - header[index] = opcodes.OP_QUERY & 0xff; - index = index + 4; - - // Write header information flags - header[index + 3] = (flags >> 24) & 0xff; - header[index + 2] = (flags >> 16) & 0xff; - header[index + 1] = (flags >> 8) & 0xff; - header[index] = flags & 0xff; - index = index + 4; - - // Write collection name - index = index + header.write(this.ns, index, 'utf8') + 1; - header[index - 1] = 0; - - // Write header information flags numberToSkip - header[index + 3] = (this.numberToSkip >> 24) & 0xff; - header[index + 2] = (this.numberToSkip >> 16) & 0xff; - header[index + 1] = (this.numberToSkip >> 8) & 0xff; - header[index] = this.numberToSkip & 0xff; - index = index + 4; - - // Write header information flags numberToReturn - header[index + 3] = (this.numberToReturn >> 24) & 0xff; - header[index + 2] = (this.numberToReturn >> 16) & 0xff; - header[index + 1] = (this.numberToReturn >> 8) & 0xff; - header[index] = this.numberToReturn & 0xff; - index = index + 4; - - // Return the buffers - return buffers; -}; - -Query.getRequestId = function() { - return ++_requestId; -}; - -/************************************************************** - * GETMORE - **************************************************************/ -var GetMore = function(bson, ns, cursorId, opts) { - opts = opts || {}; - this.numberToReturn = opts.numberToReturn || 0; - this.requestId = _requestId++; - this.bson = bson; - this.ns = ns; - this.cursorId = cursorId; -}; - -// -// Uses a single allocated buffer for the process, avoiding multiple memory allocations -GetMore.prototype.toBin = function() { - var length = 4 + Buffer.byteLength(this.ns) + 1 + 4 + 8 + 4 * 4; - // Create command buffer - var index = 0; - // Allocate buffer - var _buffer = Buffer.alloc(length); - - // Write header information - // index = write32bit(index, _buffer, length); - _buffer[index + 3] = (length >> 24) & 0xff; - _buffer[index + 2] = (length >> 16) & 0xff; - _buffer[index + 1] = (length >> 8) & 0xff; - _buffer[index] = length & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, requestId); - _buffer[index + 3] = (this.requestId >> 24) & 0xff; - _buffer[index + 2] = (this.requestId >> 16) & 0xff; - _buffer[index + 1] = (this.requestId >> 8) & 0xff; - _buffer[index] = this.requestId & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, 0); - _buffer[index + 3] = (0 >> 24) & 0xff; - _buffer[index + 2] = (0 >> 16) & 0xff; - _buffer[index + 1] = (0 >> 8) & 0xff; - _buffer[index] = 0 & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, OP_GETMORE); - _buffer[index + 3] = (opcodes.OP_GETMORE >> 24) & 0xff; - _buffer[index + 2] = (opcodes.OP_GETMORE >> 16) & 0xff; - _buffer[index + 1] = (opcodes.OP_GETMORE >> 8) & 0xff; - _buffer[index] = opcodes.OP_GETMORE & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, 0); - _buffer[index + 3] = (0 >> 24) & 0xff; - _buffer[index + 2] = (0 >> 16) & 0xff; - _buffer[index + 1] = (0 >> 8) & 0xff; - _buffer[index] = 0 & 0xff; - index = index + 4; - - // Write collection name - index = index + _buffer.write(this.ns, index, 'utf8') + 1; - _buffer[index - 1] = 0; - - // Write batch size - // index = write32bit(index, _buffer, numberToReturn); - _buffer[index + 3] = (this.numberToReturn >> 24) & 0xff; - _buffer[index + 2] = (this.numberToReturn >> 16) & 0xff; - _buffer[index + 1] = (this.numberToReturn >> 8) & 0xff; - _buffer[index] = this.numberToReturn & 0xff; - index = index + 4; - - // Write cursor id - // index = write32bit(index, _buffer, cursorId.getLowBits()); - _buffer[index + 3] = (this.cursorId.getLowBits() >> 24) & 0xff; - _buffer[index + 2] = (this.cursorId.getLowBits() >> 16) & 0xff; - _buffer[index + 1] = (this.cursorId.getLowBits() >> 8) & 0xff; - _buffer[index] = this.cursorId.getLowBits() & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, cursorId.getHighBits()); - _buffer[index + 3] = (this.cursorId.getHighBits() >> 24) & 0xff; - _buffer[index + 2] = (this.cursorId.getHighBits() >> 16) & 0xff; - _buffer[index + 1] = (this.cursorId.getHighBits() >> 8) & 0xff; - _buffer[index] = this.cursorId.getHighBits() & 0xff; - index = index + 4; - - // Return buffer - return _buffer; -}; - -/************************************************************** - * KILLCURSOR - **************************************************************/ -var KillCursor = function(bson, ns, cursorIds) { - this.ns = ns; - this.requestId = _requestId++; - this.cursorIds = cursorIds; -}; - -// -// Uses a single allocated buffer for the process, avoiding multiple memory allocations -KillCursor.prototype.toBin = function() { - var length = 4 + 4 + 4 * 4 + this.cursorIds.length * 8; - - // Create command buffer - var index = 0; - var _buffer = Buffer.alloc(length); - - // Write header information - // index = write32bit(index, _buffer, length); - _buffer[index + 3] = (length >> 24) & 0xff; - _buffer[index + 2] = (length >> 16) & 0xff; - _buffer[index + 1] = (length >> 8) & 0xff; - _buffer[index] = length & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, requestId); - _buffer[index + 3] = (this.requestId >> 24) & 0xff; - _buffer[index + 2] = (this.requestId >> 16) & 0xff; - _buffer[index + 1] = (this.requestId >> 8) & 0xff; - _buffer[index] = this.requestId & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, 0); - _buffer[index + 3] = (0 >> 24) & 0xff; - _buffer[index + 2] = (0 >> 16) & 0xff; - _buffer[index + 1] = (0 >> 8) & 0xff; - _buffer[index] = 0 & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, OP_KILL_CURSORS); - _buffer[index + 3] = (opcodes.OP_KILL_CURSORS >> 24) & 0xff; - _buffer[index + 2] = (opcodes.OP_KILL_CURSORS >> 16) & 0xff; - _buffer[index + 1] = (opcodes.OP_KILL_CURSORS >> 8) & 0xff; - _buffer[index] = opcodes.OP_KILL_CURSORS & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, 0); - _buffer[index + 3] = (0 >> 24) & 0xff; - _buffer[index + 2] = (0 >> 16) & 0xff; - _buffer[index + 1] = (0 >> 8) & 0xff; - _buffer[index] = 0 & 0xff; - index = index + 4; - - // Write batch size - // index = write32bit(index, _buffer, this.cursorIds.length); - _buffer[index + 3] = (this.cursorIds.length >> 24) & 0xff; - _buffer[index + 2] = (this.cursorIds.length >> 16) & 0xff; - _buffer[index + 1] = (this.cursorIds.length >> 8) & 0xff; - _buffer[index] = this.cursorIds.length & 0xff; - index = index + 4; - - // Write all the cursor ids into the array - for (var i = 0; i < this.cursorIds.length; i++) { - // Write cursor id - // index = write32bit(index, _buffer, cursorIds[i].getLowBits()); - _buffer[index + 3] = (this.cursorIds[i].getLowBits() >> 24) & 0xff; - _buffer[index + 2] = (this.cursorIds[i].getLowBits() >> 16) & 0xff; - _buffer[index + 1] = (this.cursorIds[i].getLowBits() >> 8) & 0xff; - _buffer[index] = this.cursorIds[i].getLowBits() & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, cursorIds[i].getHighBits()); - _buffer[index + 3] = (this.cursorIds[i].getHighBits() >> 24) & 0xff; - _buffer[index + 2] = (this.cursorIds[i].getHighBits() >> 16) & 0xff; - _buffer[index + 1] = (this.cursorIds[i].getHighBits() >> 8) & 0xff; - _buffer[index] = this.cursorIds[i].getHighBits() & 0xff; - index = index + 4; - } - - // Return buffer - return _buffer; -}; - -var Response = function(bson, message, msgHeader, msgBody, opts) { - opts = opts || { promoteLongs: true, promoteValues: true, promoteBuffers: false }; - this.parsed = false; - this.raw = message; - this.data = msgBody; - this.bson = bson; - this.opts = opts; - - // Read the message header - this.length = msgHeader.length; - this.requestId = msgHeader.requestId; - this.responseTo = msgHeader.responseTo; - this.opCode = msgHeader.opCode; - this.fromCompressed = msgHeader.fromCompressed; - - // Read the message body - this.responseFlags = msgBody.readInt32LE(0); - this.cursorId = new Long(msgBody.readInt32LE(4), msgBody.readInt32LE(8)); - this.startingFrom = msgBody.readInt32LE(12); - this.numberReturned = msgBody.readInt32LE(16); - - // Preallocate document array - this.documents = new Array(this.numberReturned); - - // Flag values - this.cursorNotFound = (this.responseFlags & CURSOR_NOT_FOUND) !== 0; - this.queryFailure = (this.responseFlags & QUERY_FAILURE) !== 0; - this.shardConfigStale = (this.responseFlags & SHARD_CONFIG_STALE) !== 0; - this.awaitCapable = (this.responseFlags & AWAIT_CAPABLE) !== 0; - this.promoteLongs = typeof opts.promoteLongs === 'boolean' ? opts.promoteLongs : true; - this.promoteValues = typeof opts.promoteValues === 'boolean' ? opts.promoteValues : true; - this.promoteBuffers = typeof opts.promoteBuffers === 'boolean' ? opts.promoteBuffers : false; -}; - -Response.prototype.isParsed = function() { - return this.parsed; -}; - -Response.prototype.parse = function(options) { - // Don't parse again if not needed - if (this.parsed) return; - options = options || {}; - - // Allow the return of raw documents instead of parsing - var raw = options.raw || false; - var documentsReturnedIn = options.documentsReturnedIn || null; - var promoteLongs = - typeof options.promoteLongs === 'boolean' ? options.promoteLongs : this.opts.promoteLongs; - var promoteValues = - typeof options.promoteValues === 'boolean' ? options.promoteValues : this.opts.promoteValues; - var promoteBuffers = - typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : this.opts.promoteBuffers; - var bsonSize, _options; - - // Set up the options - _options = { - promoteLongs: promoteLongs, - promoteValues: promoteValues, - promoteBuffers: promoteBuffers - }; - - // Position within OP_REPLY at which documents start - // (See https://docs.mongodb.com/manual/reference/mongodb-wire-protocol/#wire-op-reply) - this.index = 20; - - // - // Parse Body - // - for (var i = 0; i < this.numberReturned; i++) { - bsonSize = - this.data[this.index] | - (this.data[this.index + 1] << 8) | - (this.data[this.index + 2] << 16) | - (this.data[this.index + 3] << 24); - - // If we have raw results specified slice the return document - if (raw) { - this.documents[i] = this.data.slice(this.index, this.index + bsonSize); - } else { - this.documents[i] = this.bson.deserialize( - this.data.slice(this.index, this.index + bsonSize), - _options - ); - } - - // Adjust the index - this.index = this.index + bsonSize; - } - - if (this.documents.length === 1 && documentsReturnedIn != null && raw) { - const fieldsAsRaw = {}; - fieldsAsRaw[documentsReturnedIn] = true; - _options.fieldsAsRaw = fieldsAsRaw; - - const doc = this.bson.deserialize(this.documents[0], _options); - this.documents = [doc]; - } - - // Set parsed - this.parsed = true; -}; - -module.exports = { - Query: Query, - GetMore: GetMore, - Response: Response, - KillCursor: KillCursor -}; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/connection/connect.js b/scripts/2.5/node_modules/mongodb/lib/core/connection/connect.js deleted file mode 100644 index e1a643e0..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/core/connection/connect.js +++ /dev/null @@ -1,370 +0,0 @@ -'use strict'; -const net = require('net'); -const tls = require('tls'); -const Connection = require('./connection'); -const Query = require('./commands').Query; -const createClientInfo = require('../topologies/shared').createClientInfo; -const MongoError = require('../error').MongoError; -const MongoNetworkError = require('../error').MongoNetworkError; -const defaultAuthProviders = require('../auth/defaultAuthProviders').defaultAuthProviders; -const WIRE_CONSTANTS = require('../wireprotocol/constants'); -const MAX_SUPPORTED_WIRE_VERSION = WIRE_CONSTANTS.MAX_SUPPORTED_WIRE_VERSION; -const MAX_SUPPORTED_SERVER_VERSION = WIRE_CONSTANTS.MAX_SUPPORTED_SERVER_VERSION; -const MIN_SUPPORTED_WIRE_VERSION = WIRE_CONSTANTS.MIN_SUPPORTED_WIRE_VERSION; -const MIN_SUPPORTED_SERVER_VERSION = WIRE_CONSTANTS.MIN_SUPPORTED_SERVER_VERSION; -let AUTH_PROVIDERS; - -function connect(options, callback) { - if (AUTH_PROVIDERS == null) { - AUTH_PROVIDERS = defaultAuthProviders(options.bson); - } - - if (options.family !== void 0) { - makeConnection(options.family, options, (err, socket) => { - if (err) { - callback(err, socket); // in the error case, `socket` is the originating error event name - return; - } - - performInitialHandshake(new Connection(socket, options), options, callback); - }); - - return; - } - - return makeConnection(6, options, (err, ipv6Socket) => { - if (err) { - makeConnection(4, options, (err, ipv4Socket) => { - if (err) { - callback(err, ipv4Socket); // in the error case, `ipv4Socket` is the originating error event name - return; - } - - performInitialHandshake(new Connection(ipv4Socket, options), options, callback); - }); - - return; - } - - performInitialHandshake(new Connection(ipv6Socket, options), options, callback); - }); -} - -function getSaslSupportedMechs(options) { - if (!(options && options.credentials)) { - return {}; - } - - const credentials = options.credentials; - - // TODO: revisit whether or not items like `options.user` and `options.dbName` should be checked here - const authMechanism = credentials.mechanism; - const authSource = credentials.source || options.dbName || 'admin'; - const user = credentials.username || options.user; - - if (typeof authMechanism === 'string' && authMechanism.toUpperCase() !== 'DEFAULT') { - return {}; - } - - if (!user) { - return {}; - } - - return { saslSupportedMechs: `${authSource}.${user}` }; -} - -function checkSupportedServer(ismaster, options) { - const serverVersionHighEnough = - ismaster && - typeof ismaster.maxWireVersion === 'number' && - ismaster.maxWireVersion >= MIN_SUPPORTED_WIRE_VERSION; - const serverVersionLowEnough = - ismaster && - typeof ismaster.minWireVersion === 'number' && - ismaster.minWireVersion <= MAX_SUPPORTED_WIRE_VERSION; - - if (serverVersionHighEnough) { - if (serverVersionLowEnough) { - return null; - } - - const message = `Server at ${options.host}:${options.port} reports minimum wire version ${ - ismaster.minWireVersion - }, but this version of the Node.js Driver requires at most ${MAX_SUPPORTED_WIRE_VERSION} (MongoDB ${MAX_SUPPORTED_SERVER_VERSION})`; - return new MongoError(message); - } - - const message = `Server at ${options.host}:${ - options.port - } reports maximum wire version ${ismaster.maxWireVersion || - 0}, but this version of the Node.js Driver requires at least ${MIN_SUPPORTED_WIRE_VERSION} (MongoDB ${MIN_SUPPORTED_SERVER_VERSION})`; - return new MongoError(message); -} - -function performInitialHandshake(conn, options, _callback) { - const callback = function(err, ret) { - if (err && conn) { - conn.destroy(); - } - _callback(err, ret); - }; - - let compressors = []; - if (options.compression && options.compression.compressors) { - compressors = options.compression.compressors; - } - - const handshakeDoc = Object.assign( - { - ismaster: true, - client: createClientInfo(options), - compression: compressors - }, - getSaslSupportedMechs(options) - ); - - const start = new Date().getTime(); - runCommand(conn, 'admin.$cmd', handshakeDoc, options, (err, ismaster) => { - if (err) { - callback(err, null); - return; - } - - if (ismaster.ok === 0) { - callback(new MongoError(ismaster), null); - return; - } - - const supportedServerErr = checkSupportedServer(ismaster, options); - if (supportedServerErr) { - callback(supportedServerErr, null); - return; - } - - // resolve compression - if (ismaster.compression) { - const agreedCompressors = compressors.filter( - compressor => ismaster.compression.indexOf(compressor) !== -1 - ); - - if (agreedCompressors.length) { - conn.agreedCompressor = agreedCompressors[0]; - } - - if (options.compression && options.compression.zlibCompressionLevel) { - conn.zlibCompressionLevel = options.compression.zlibCompressionLevel; - } - } - - // NOTE: This is metadata attached to the connection while porting away from - // handshake being done in the `Server` class. Likely, it should be - // relocated, or at very least restructured. - conn.ismaster = ismaster; - conn.lastIsMasterMS = new Date().getTime() - start; - - const credentials = options.credentials; - if (!ismaster.arbiterOnly && credentials) { - credentials.resolveAuthMechanism(ismaster); - authenticate(conn, credentials, callback); - return; - } - - callback(null, conn); - }); -} - -const LEGAL_SSL_SOCKET_OPTIONS = [ - 'pfx', - 'key', - 'passphrase', - 'cert', - 'ca', - 'ciphers', - 'NPNProtocols', - 'ALPNProtocols', - 'servername', - 'ecdhCurve', - 'secureProtocol', - 'secureContext', - 'session', - 'minDHSize', - 'crl', - 'rejectUnauthorized' -]; - -function parseConnectOptions(family, options) { - const host = typeof options.host === 'string' ? options.host : 'localhost'; - if (host.indexOf('/') !== -1) { - return { path: host }; - } - - const result = { - family, - host, - port: typeof options.port === 'number' ? options.port : 27017, - rejectUnauthorized: false - }; - - return result; -} - -function parseSslOptions(family, options) { - const result = parseConnectOptions(family, options); - - // Merge in valid SSL options - for (const name in options) { - if (options[name] != null && LEGAL_SSL_SOCKET_OPTIONS.indexOf(name) !== -1) { - result[name] = options[name]; - } - } - - // Override checkServerIdentity behavior - if (options.checkServerIdentity === false) { - // Skip the identiy check by retuning undefined as per node documents - // https://nodejs.org/api/tls.html#tls_tls_connect_options_callback - result.checkServerIdentity = function() { - return undefined; - }; - } else if (typeof options.checkServerIdentity === 'function') { - result.checkServerIdentity = options.checkServerIdentity; - } - - // Set default sni servername to be the same as host - if (result.servername == null) { - result.servername = result.host; - } - - return result; -} - -function makeConnection(family, options, _callback) { - const useSsl = typeof options.ssl === 'boolean' ? options.ssl : false; - const keepAlive = typeof options.keepAlive === 'boolean' ? options.keepAlive : true; - let keepAliveInitialDelay = - typeof options.keepAliveInitialDelay === 'number' ? options.keepAliveInitialDelay : 300000; - const noDelay = typeof options.noDelay === 'boolean' ? options.noDelay : true; - const connectionTimeout = - typeof options.connectionTimeout === 'number' ? options.connectionTimeout : 30000; - const socketTimeout = typeof options.socketTimeout === 'number' ? options.socketTimeout : 360000; - const rejectUnauthorized = - typeof options.rejectUnauthorized === 'boolean' ? options.rejectUnauthorized : true; - - if (keepAliveInitialDelay > socketTimeout) { - keepAliveInitialDelay = Math.round(socketTimeout / 2); - } - - let socket; - const callback = function(err, ret) { - if (err && socket) { - socket.destroy(); - } - _callback(err, ret); - }; - - try { - if (useSsl) { - socket = tls.connect(parseSslOptions(family, options)); - if (typeof socket.disableRenegotiation === 'function') { - socket.disableRenegotiation(); - } - } else { - socket = net.createConnection(parseConnectOptions(family, options)); - } - } catch (err) { - return callback(err); - } - - socket.setKeepAlive(keepAlive, keepAliveInitialDelay); - socket.setTimeout(connectionTimeout); - socket.setNoDelay(noDelay); - - const errorEvents = ['error', 'close', 'timeout', 'parseError']; - function errorHandler(eventName) { - return err => { - errorEvents.forEach(event => socket.removeAllListeners(event)); - socket.removeListener('connect', connectHandler); - callback(connectionFailureError(eventName, err), eventName); - }; - } - - function connectHandler() { - errorEvents.forEach(event => socket.removeAllListeners(event)); - if (socket.authorizationError && rejectUnauthorized) { - return callback(socket.authorizationError); - } - - socket.setTimeout(socketTimeout); - callback(null, socket); - } - - socket.once('error', errorHandler('error')); - socket.once('close', errorHandler('close')); - socket.once('timeout', errorHandler('timeout')); - socket.once('parseError', errorHandler('parseError')); - socket.once('connect', connectHandler); -} - -const CONNECTION_ERROR_EVENTS = ['error', 'close', 'timeout', 'parseError']; -function runCommand(conn, ns, command, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - const socketTimeout = typeof options.socketTimeout === 'number' ? options.socketTimeout : 360000; - const bson = conn.options.bson; - const query = new Query(bson, ns, command, { - numberToSkip: 0, - numberToReturn: 1 - }); - - function errorHandler(err) { - conn.resetSocketTimeout(); - CONNECTION_ERROR_EVENTS.forEach(eventName => conn.removeListener(eventName, errorHandler)); - conn.removeListener('message', messageHandler); - callback(err, null); - } - - function messageHandler(msg) { - if (msg.responseTo !== query.requestId) { - return; - } - - conn.resetSocketTimeout(); - CONNECTION_ERROR_EVENTS.forEach(eventName => conn.removeListener(eventName, errorHandler)); - conn.removeListener('message', messageHandler); - - msg.parse({ promoteValues: true }); - callback(null, msg.documents[0]); - } - - conn.setSocketTimeout(socketTimeout); - CONNECTION_ERROR_EVENTS.forEach(eventName => conn.once(eventName, errorHandler)); - conn.on('message', messageHandler); - conn.write(query.toBin()); -} - -function authenticate(conn, credentials, callback) { - const mechanism = credentials.mechanism; - if (!AUTH_PROVIDERS[mechanism]) { - callback(new MongoError(`authMechanism '${mechanism}' not supported`)); - return; - } - - const provider = AUTH_PROVIDERS[mechanism]; - provider.auth(runCommand, [conn], credentials, err => { - if (err) return callback(err); - callback(null, conn); - }); -} - -function connectionFailureError(type, err) { - switch (type) { - case 'error': - return new MongoNetworkError(err); - case 'timeout': - return new MongoNetworkError(`connection timed out`); - case 'close': - return new MongoNetworkError(`connection closed`); - default: - return new MongoNetworkError(`unknown network error`); - } -} - -module.exports = connect; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/connection/connection.js b/scripts/2.5/node_modules/mongodb/lib/core/connection/connection.js deleted file mode 100644 index 6f6ca6ad..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/core/connection/connection.js +++ /dev/null @@ -1,628 +0,0 @@ -'use strict'; - -const EventEmitter = require('events').EventEmitter; -const crypto = require('crypto'); -const debugOptions = require('./utils').debugOptions; -const parseHeader = require('../wireprotocol/shared').parseHeader; -const decompress = require('../wireprotocol/compression').decompress; -const Response = require('./commands').Response; -const BinMsg = require('./msg').BinMsg; -const MongoNetworkError = require('../error').MongoNetworkError; -const MongoError = require('../error').MongoError; -const Logger = require('./logger'); -const OP_COMPRESSED = require('../wireprotocol/shared').opcodes.OP_COMPRESSED; -const OP_MSG = require('../wireprotocol/shared').opcodes.OP_MSG; -const MESSAGE_HEADER_SIZE = require('../wireprotocol/shared').MESSAGE_HEADER_SIZE; -const Buffer = require('safe-buffer').Buffer; - -let _id = 0; - -const DEFAULT_MAX_BSON_MESSAGE_SIZE = 1024 * 1024 * 16 * 4; -const DEBUG_FIELDS = [ - 'host', - 'port', - 'size', - 'keepAlive', - 'keepAliveInitialDelay', - 'noDelay', - 'connectionTimeout', - 'socketTimeout', - 'ssl', - 'ca', - 'crl', - 'cert', - 'rejectUnauthorized', - 'promoteLongs', - 'promoteValues', - 'promoteBuffers', - 'checkServerIdentity' -]; - -let connectionAccountingSpy = undefined; -let connectionAccounting = false; -let connections = {}; - -/** - * A class representing a single connection to a MongoDB server - * - * @fires Connection#connect - * @fires Connection#close - * @fires Connection#error - * @fires Connection#timeout - * @fires Connection#parseError - * @fires Connection#message - */ -class Connection extends EventEmitter { - /** - * Creates a new Connection instance - * - * **NOTE**: Internal class, do not instantiate directly - * - * @param {Socket} socket The socket this connection wraps - * @param {Object} options Various settings - * @param {object} options.bson An implementation of bson serialize and deserialize - * @param {string} [options.host='localhost'] The host the socket is connected to - * @param {number} [options.port=27017] The port used for the socket connection - * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled - * @param {number} [options.keepAliveInitialDelay=300000] Initial delay before TCP keep alive enabled - * @param {number} [options.connectionTimeout=30000] TCP Connection timeout setting - * @param {number} [options.socketTimeout=360000] TCP Socket timeout setting - * @param {boolean} [options.promoteLongs] Convert Long values from the db into Numbers if they fit into 53 bits - * @param {boolean} [options.promoteValues] Promotes BSON values to native types where possible, set to false to only receive wrapper types. - * @param {boolean} [options.promoteBuffers] Promotes Binary BSON values to native Node Buffers. - * @param {number} [options.maxBsonMessageSize=0x4000000] Largest possible size of a BSON message (for legacy purposes) - */ - constructor(socket, options) { - super(); - - options = options || {}; - if (!options.bson) { - throw new TypeError('must pass in valid bson parser'); - } - - this.id = _id++; - this.options = options; - this.logger = Logger('Connection', options); - this.bson = options.bson; - this.tag = options.tag; - this.maxBsonMessageSize = options.maxBsonMessageSize || DEFAULT_MAX_BSON_MESSAGE_SIZE; - - this.port = options.port || 27017; - this.host = options.host || 'localhost'; - this.socketTimeout = typeof options.socketTimeout === 'number' ? options.socketTimeout : 360000; - - // These values are inspected directly in tests, but maybe not necessary to keep around - this.keepAlive = typeof options.keepAlive === 'boolean' ? options.keepAlive : true; - this.keepAliveInitialDelay = - typeof options.keepAliveInitialDelay === 'number' ? options.keepAliveInitialDelay : 300000; - this.connectionTimeout = - typeof options.connectionTimeout === 'number' ? options.connectionTimeout : 30000; - if (this.keepAliveInitialDelay > this.socketTimeout) { - this.keepAliveInitialDelay = Math.round(this.socketTimeout / 2); - } - - // Debug information - if (this.logger.isDebug()) { - this.logger.debug( - `creating connection ${this.id} with options [${JSON.stringify( - debugOptions(DEBUG_FIELDS, options) - )}]` - ); - } - - // Response options - this.responseOptions = { - promoteLongs: typeof options.promoteLongs === 'boolean' ? options.promoteLongs : true, - promoteValues: typeof options.promoteValues === 'boolean' ? options.promoteValues : true, - promoteBuffers: typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : false - }; - - // Flushing - this.flushing = false; - this.queue = []; - - // Internal state - this.writeStream = null; - this.destroyed = false; - - // Create hash method - const hash = crypto.createHash('sha1'); - hash.update(this.address); - this.hashedName = hash.digest('hex'); - - // All operations in flight on the connection - this.workItems = []; - - // setup socket - this.socket = socket; - this.socket.once('error', errorHandler(this)); - this.socket.once('timeout', timeoutHandler(this)); - this.socket.once('close', closeHandler(this)); - this.socket.on('data', dataHandler(this)); - - if (connectionAccounting) { - addConnection(this.id, this); - } - } - - setSocketTimeout(value) { - if (this.socket) { - this.socket.setTimeout(value); - } - } - - resetSocketTimeout() { - if (this.socket) { - this.socket.setTimeout(this.socketTimeout); - } - } - - static enableConnectionAccounting(spy) { - if (spy) { - connectionAccountingSpy = spy; - } - - connectionAccounting = true; - connections = {}; - } - - static disableConnectionAccounting() { - connectionAccounting = false; - connectionAccountingSpy = undefined; - } - - static connections() { - return connections; - } - - get address() { - return `${this.host}:${this.port}`; - } - - /** - * Unref this connection - * @method - * @return {boolean} - */ - unref() { - if (this.socket == null) { - this.once('connect', () => this.socket.unref()); - return; - } - - this.socket.unref(); - } - - /** - * Destroy connection - * @method - */ - destroy(options, callback) { - if (typeof options === 'function') { - callback = options; - options = {}; - } - - options = Object.assign({ force: false }, options); - - if (connectionAccounting) { - deleteConnection(this.id); - } - - if (this.socket == null) { - this.destroyed = true; - return; - } - - if (options.force) { - this.socket.destroy(); - this.destroyed = true; - if (typeof callback === 'function') callback(null, null); - return; - } - - this.socket.end(err => { - this.destroyed = true; - if (typeof callback === 'function') callback(err, null); - }); - } - - /** - * Write to connection - * @method - * @param {Command} command Command to write out need to implement toBin and toBinUnified - */ - write(buffer) { - // Debug Log - if (this.logger.isDebug()) { - if (!Array.isArray(buffer)) { - this.logger.debug(`writing buffer [${buffer.toString('hex')}] to ${this.address}`); - } else { - for (let i = 0; i < buffer.length; i++) - this.logger.debug(`writing buffer [${buffer[i].toString('hex')}] to ${this.address}`); - } - } - - // Double check that the connection is not destroyed - if (this.socket.destroyed === false) { - // Write out the command - if (!Array.isArray(buffer)) { - this.socket.write(buffer, 'binary'); - return true; - } - - // Iterate over all buffers and write them in order to the socket - for (let i = 0; i < buffer.length; i++) { - this.socket.write(buffer[i], 'binary'); - } - - return true; - } - - // Connection is destroyed return write failed - return false; - } - - /** - * Return id of connection as a string - * @method - * @return {string} - */ - toString() { - return '' + this.id; - } - - /** - * Return json object of connection - * @method - * @return {object} - */ - toJSON() { - return { id: this.id, host: this.host, port: this.port }; - } - - /** - * Is the connection connected - * @method - * @return {boolean} - */ - isConnected() { - if (this.destroyed) return false; - return !this.socket.destroyed && this.socket.writable; - } -} - -function deleteConnection(id) { - // console.log("=== deleted connection " + id + " :: " + (connections[id] ? connections[id].port : '')) - delete connections[id]; - - if (connectionAccountingSpy) { - connectionAccountingSpy.deleteConnection(id); - } -} - -function addConnection(id, connection) { - // console.log("=== added connection " + id + " :: " + connection.port) - connections[id] = connection; - - if (connectionAccountingSpy) { - connectionAccountingSpy.addConnection(id, connection); - } -} - -// -// Connection handlers -function errorHandler(conn) { - return function(err) { - if (connectionAccounting) deleteConnection(conn.id); - // Debug information - if (conn.logger.isDebug()) { - conn.logger.debug( - `connection ${conn.id} for [${conn.address}] errored out with [${JSON.stringify(err)}]` - ); - } - - conn.emit('error', new MongoNetworkError(err), conn); - }; -} - -function timeoutHandler(conn) { - return function() { - if (connectionAccounting) deleteConnection(conn.id); - - if (conn.logger.isDebug()) { - conn.logger.debug(`connection ${conn.id} for [${conn.address}] timed out`); - } - - conn.emit( - 'timeout', - new MongoNetworkError(`connection ${conn.id} to ${conn.address} timed out`), - conn - ); - }; -} - -function closeHandler(conn) { - return function(hadError) { - if (connectionAccounting) deleteConnection(conn.id); - - if (conn.logger.isDebug()) { - conn.logger.debug(`connection ${conn.id} with for [${conn.address}] closed`); - } - - if (!hadError) { - conn.emit( - 'close', - new MongoNetworkError(`connection ${conn.id} to ${conn.address} closed`), - conn - ); - } - }; -} - -// Handle a message once it is received -function processMessage(conn, message) { - const msgHeader = parseHeader(message); - if (msgHeader.opCode !== OP_COMPRESSED) { - const ResponseConstructor = msgHeader.opCode === OP_MSG ? BinMsg : Response; - conn.emit( - 'message', - new ResponseConstructor( - conn.bson, - message, - msgHeader, - message.slice(MESSAGE_HEADER_SIZE), - conn.responseOptions - ), - conn - ); - - return; - } - - msgHeader.fromCompressed = true; - let index = MESSAGE_HEADER_SIZE; - msgHeader.opCode = message.readInt32LE(index); - index += 4; - msgHeader.length = message.readInt32LE(index); - index += 4; - const compressorID = message[index]; - index++; - - decompress(compressorID, message.slice(index), (err, decompressedMsgBody) => { - if (err) { - conn.emit('error', err); - return; - } - - if (decompressedMsgBody.length !== msgHeader.length) { - conn.emit( - 'error', - new MongoError( - 'Decompressing a compressed message from the server failed. The message is corrupt.' - ) - ); - - return; - } - - const ResponseConstructor = msgHeader.opCode === OP_MSG ? BinMsg : Response; - conn.emit( - 'message', - new ResponseConstructor( - conn.bson, - message, - msgHeader, - decompressedMsgBody, - conn.responseOptions - ), - conn - ); - }); -} - -function dataHandler(conn) { - return function(data) { - // Parse until we are done with the data - while (data.length > 0) { - // If we still have bytes to read on the current message - if (conn.bytesRead > 0 && conn.sizeOfMessage > 0) { - // Calculate the amount of remaining bytes - const remainingBytesToRead = conn.sizeOfMessage - conn.bytesRead; - // Check if the current chunk contains the rest of the message - if (remainingBytesToRead > data.length) { - // Copy the new data into the exiting buffer (should have been allocated when we know the message size) - data.copy(conn.buffer, conn.bytesRead); - // Adjust the number of bytes read so it point to the correct index in the buffer - conn.bytesRead = conn.bytesRead + data.length; - - // Reset state of buffer - data = Buffer.alloc(0); - } else { - // Copy the missing part of the data into our current buffer - data.copy(conn.buffer, conn.bytesRead, 0, remainingBytesToRead); - // Slice the overflow into a new buffer that we will then re-parse - data = data.slice(remainingBytesToRead); - - // Emit current complete message - const emitBuffer = conn.buffer; - // Reset state of buffer - conn.buffer = null; - conn.sizeOfMessage = 0; - conn.bytesRead = 0; - conn.stubBuffer = null; - - processMessage(conn, emitBuffer); - } - } else { - // Stub buffer is kept in case we don't get enough bytes to determine the - // size of the message (< 4 bytes) - if (conn.stubBuffer != null && conn.stubBuffer.length > 0) { - // If we have enough bytes to determine the message size let's do it - if (conn.stubBuffer.length + data.length > 4) { - // Prepad the data - const newData = Buffer.alloc(conn.stubBuffer.length + data.length); - conn.stubBuffer.copy(newData, 0); - data.copy(newData, conn.stubBuffer.length); - // Reassign for parsing - data = newData; - - // Reset state of buffer - conn.buffer = null; - conn.sizeOfMessage = 0; - conn.bytesRead = 0; - conn.stubBuffer = null; - } else { - // Add the the bytes to the stub buffer - const newStubBuffer = Buffer.alloc(conn.stubBuffer.length + data.length); - // Copy existing stub buffer - conn.stubBuffer.copy(newStubBuffer, 0); - // Copy missing part of the data - data.copy(newStubBuffer, conn.stubBuffer.length); - // Exit parsing loop - data = Buffer.alloc(0); - } - } else { - if (data.length > 4) { - // Retrieve the message size - const sizeOfMessage = data[0] | (data[1] << 8) | (data[2] << 16) | (data[3] << 24); - // If we have a negative sizeOfMessage emit error and return - if (sizeOfMessage < 0 || sizeOfMessage > conn.maxBsonMessageSize) { - const errorObject = { - err: 'socketHandler', - trace: '', - bin: conn.buffer, - parseState: { - sizeOfMessage: sizeOfMessage, - bytesRead: conn.bytesRead, - stubBuffer: conn.stubBuffer - } - }; - // We got a parse Error fire it off then keep going - conn.emit('parseError', errorObject, conn); - return; - } - - // Ensure that the size of message is larger than 0 and less than the max allowed - if ( - sizeOfMessage > 4 && - sizeOfMessage < conn.maxBsonMessageSize && - sizeOfMessage > data.length - ) { - conn.buffer = Buffer.alloc(sizeOfMessage); - // Copy all the data into the buffer - data.copy(conn.buffer, 0); - // Update bytes read - conn.bytesRead = data.length; - // Update sizeOfMessage - conn.sizeOfMessage = sizeOfMessage; - // Ensure stub buffer is null - conn.stubBuffer = null; - // Exit parsing loop - data = Buffer.alloc(0); - } else if ( - sizeOfMessage > 4 && - sizeOfMessage < conn.maxBsonMessageSize && - sizeOfMessage === data.length - ) { - const emitBuffer = data; - // Reset state of buffer - conn.buffer = null; - conn.sizeOfMessage = 0; - conn.bytesRead = 0; - conn.stubBuffer = null; - // Exit parsing loop - data = Buffer.alloc(0); - // Emit the message - processMessage(conn, emitBuffer); - } else if (sizeOfMessage <= 4 || sizeOfMessage > conn.maxBsonMessageSize) { - const errorObject = { - err: 'socketHandler', - trace: null, - bin: data, - parseState: { - sizeOfMessage: sizeOfMessage, - bytesRead: 0, - buffer: null, - stubBuffer: null - } - }; - // We got a parse Error fire it off then keep going - conn.emit('parseError', errorObject, conn); - - // Clear out the state of the parser - conn.buffer = null; - conn.sizeOfMessage = 0; - conn.bytesRead = 0; - conn.stubBuffer = null; - // Exit parsing loop - data = Buffer.alloc(0); - } else { - const emitBuffer = data.slice(0, sizeOfMessage); - // Reset state of buffer - conn.buffer = null; - conn.sizeOfMessage = 0; - conn.bytesRead = 0; - conn.stubBuffer = null; - // Copy rest of message - data = data.slice(sizeOfMessage); - // Emit the message - processMessage(conn, emitBuffer); - } - } else { - // Create a buffer that contains the space for the non-complete message - conn.stubBuffer = Buffer.alloc(data.length); - // Copy the data to the stub buffer - data.copy(conn.stubBuffer, 0); - // Exit parsing loop - data = Buffer.alloc(0); - } - } - } - } - }; -} - -/** - * A server connect event, used to verify that the connection is up and running - * - * @event Connection#connect - * @type {Connection} - */ - -/** - * The server connection closed, all pool connections closed - * - * @event Connection#close - * @type {Connection} - */ - -/** - * The server connection caused an error, all pool connections closed - * - * @event Connection#error - * @type {Connection} - */ - -/** - * The server connection timed out, all pool connections closed - * - * @event Connection#timeout - * @type {Connection} - */ - -/** - * The driver experienced an invalid message, all pool connections closed - * - * @event Connection#parseError - * @type {Connection} - */ - -/** - * An event emitted each time the connection receives a parsed message from the wire - * - * @event Connection#message - * @type {Connection} - */ - -module.exports = Connection; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/connection/logger.js b/scripts/2.5/node_modules/mongodb/lib/core/connection/logger.js deleted file mode 100644 index eb11e43d..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/core/connection/logger.js +++ /dev/null @@ -1,246 +0,0 @@ -'use strict'; - -var f = require('util').format, - MongoError = require('../error').MongoError; - -// Filters for classes -var classFilters = {}; -var filteredClasses = {}; -var level = null; -// Save the process id -var pid = process.pid; -// current logger -var currentLogger = null; - -/** - * Creates a new Logger instance - * @class - * @param {string} className The Class name associated with the logging instance - * @param {object} [options=null] Optional settings. - * @param {Function} [options.logger=null] Custom logger function; - * @param {string} [options.loggerLevel=error] Override default global log level. - * @return {Logger} a Logger instance. - */ -var Logger = function(className, options) { - if (!(this instanceof Logger)) return new Logger(className, options); - options = options || {}; - - // Current reference - this.className = className; - - // Current logger - if (options.logger) { - currentLogger = options.logger; - } else if (currentLogger == null) { - currentLogger = console.log; - } - - // Set level of logging, default is error - if (options.loggerLevel) { - level = options.loggerLevel || 'error'; - } - - // Add all class names - if (filteredClasses[this.className] == null) classFilters[this.className] = true; -}; - -/** - * Log a message at the debug level - * @method - * @param {string} message The message to log - * @param {object} object additional meta data to log - * @return {null} - */ -Logger.prototype.debug = function(message, object) { - if ( - this.isDebug() && - ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) || - (Object.keys(filteredClasses).length === 0 && classFilters[this.className])) - ) { - var dateTime = new Date().getTime(); - var msg = f('[%s-%s:%s] %s %s', 'DEBUG', this.className, pid, dateTime, message); - var state = { - type: 'debug', - message: message, - className: this.className, - pid: pid, - date: dateTime - }; - if (object) state.meta = object; - currentLogger(msg, state); - } -}; - -/** - * Log a message at the warn level - * @method - * @param {string} message The message to log - * @param {object} object additional meta data to log - * @return {null} - */ -(Logger.prototype.warn = function(message, object) { - if ( - this.isWarn() && - ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) || - (Object.keys(filteredClasses).length === 0 && classFilters[this.className])) - ) { - var dateTime = new Date().getTime(); - var msg = f('[%s-%s:%s] %s %s', 'WARN', this.className, pid, dateTime, message); - var state = { - type: 'warn', - message: message, - className: this.className, - pid: pid, - date: dateTime - }; - if (object) state.meta = object; - currentLogger(msg, state); - } -}), - /** - * Log a message at the info level - * @method - * @param {string} message The message to log - * @param {object} object additional meta data to log - * @return {null} - */ - (Logger.prototype.info = function(message, object) { - if ( - this.isInfo() && - ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) || - (Object.keys(filteredClasses).length === 0 && classFilters[this.className])) - ) { - var dateTime = new Date().getTime(); - var msg = f('[%s-%s:%s] %s %s', 'INFO', this.className, pid, dateTime, message); - var state = { - type: 'info', - message: message, - className: this.className, - pid: pid, - date: dateTime - }; - if (object) state.meta = object; - currentLogger(msg, state); - } - }), - /** - * Log a message at the error level - * @method - * @param {string} message The message to log - * @param {object} object additional meta data to log - * @return {null} - */ - (Logger.prototype.error = function(message, object) { - if ( - this.isError() && - ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) || - (Object.keys(filteredClasses).length === 0 && classFilters[this.className])) - ) { - var dateTime = new Date().getTime(); - var msg = f('[%s-%s:%s] %s %s', 'ERROR', this.className, pid, dateTime, message); - var state = { - type: 'error', - message: message, - className: this.className, - pid: pid, - date: dateTime - }; - if (object) state.meta = object; - currentLogger(msg, state); - } - }), - /** - * Is the logger set at info level - * @method - * @return {boolean} - */ - (Logger.prototype.isInfo = function() { - return level === 'info' || level === 'debug'; - }), - /** - * Is the logger set at error level - * @method - * @return {boolean} - */ - (Logger.prototype.isError = function() { - return level === 'error' || level === 'info' || level === 'debug'; - }), - /** - * Is the logger set at error level - * @method - * @return {boolean} - */ - (Logger.prototype.isWarn = function() { - return level === 'error' || level === 'warn' || level === 'info' || level === 'debug'; - }), - /** - * Is the logger set at debug level - * @method - * @return {boolean} - */ - (Logger.prototype.isDebug = function() { - return level === 'debug'; - }); - -/** - * Resets the logger to default settings, error and no filtered classes - * @method - * @return {null} - */ -Logger.reset = function() { - level = 'error'; - filteredClasses = {}; -}; - -/** - * Get the current logger function - * @method - * @return {function} - */ -Logger.currentLogger = function() { - return currentLogger; -}; - -/** - * Set the current logger function - * @method - * @param {function} logger Logger function. - * @return {null} - */ -Logger.setCurrentLogger = function(logger) { - if (typeof logger !== 'function') throw new MongoError('current logger must be a function'); - currentLogger = logger; -}; - -/** - * Set what classes to log. - * @method - * @param {string} type The type of filter (currently only class) - * @param {string[]} values The filters to apply - * @return {null} - */ -Logger.filter = function(type, values) { - if (type === 'class' && Array.isArray(values)) { - filteredClasses = {}; - - values.forEach(function(x) { - filteredClasses[x] = true; - }); - } -}; - -/** - * Set the current log level - * @method - * @param {string} level Set current log level (debug, info, error) - * @return {null} - */ -Logger.setLevel = function(_level) { - if (_level !== 'info' && _level !== 'error' && _level !== 'debug' && _level !== 'warn') { - throw new Error(f('%s is an illegal logging level', _level)); - } - - level = _level; -}; - -module.exports = Logger; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/connection/msg.js b/scripts/2.5/node_modules/mongodb/lib/core/connection/msg.js deleted file mode 100644 index 7bee3c5e..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/core/connection/msg.js +++ /dev/null @@ -1,221 +0,0 @@ -'use strict'; - -// Implementation of OP_MSG spec: -// https://github.com/mongodb/specifications/blob/master/source/message/OP_MSG.rst -// -// struct Section { -// uint8 payloadType; -// union payload { -// document document; // payloadType == 0 -// struct sequence { // payloadType == 1 -// int32 size; -// cstring identifier; -// document* documents; -// }; -// }; -// }; - -// struct OP_MSG { -// struct MsgHeader { -// int32 messageLength; -// int32 requestID; -// int32 responseTo; -// int32 opCode = 2013; -// }; -// uint32 flagBits; -// Section+ sections; -// [uint32 checksum;] -// }; - -const Buffer = require('safe-buffer').Buffer; -const opcodes = require('../wireprotocol/shared').opcodes; -const databaseNamespace = require('../wireprotocol/shared').databaseNamespace; -const ReadPreference = require('../topologies/read_preference'); - -// Incrementing request id -let _requestId = 0; - -// Msg Flags -const OPTS_CHECKSUM_PRESENT = 1; -const OPTS_MORE_TO_COME = 2; -const OPTS_EXHAUST_ALLOWED = 1 << 16; - -class Msg { - constructor(bson, ns, command, options) { - // Basic options needed to be passed in - if (command == null) throw new Error('query must be specified for query'); - - // Basic options - this.bson = bson; - this.ns = ns; - this.command = command; - this.command.$db = databaseNamespace(ns); - - if (options.readPreference && options.readPreference.mode !== ReadPreference.PRIMARY) { - this.command.$readPreference = options.readPreference.toJSON(); - } - - // Ensure empty options - this.options = options || {}; - - // Additional options - this.requestId = Msg.getRequestId(); - - // Serialization option - this.serializeFunctions = - typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; - this.ignoreUndefined = - typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : false; - this.checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; - this.maxBsonSize = options.maxBsonSize || 1024 * 1024 * 16; - - // flags - this.checksumPresent = false; - this.moreToCome = options.moreToCome || false; - this.exhaustAllowed = false; - } - - toBin() { - const buffers = []; - let flags = 0; - - if (this.checksumPresent) { - flags |= OPTS_CHECKSUM_PRESENT; - } - - if (this.moreToCome) { - flags |= OPTS_MORE_TO_COME; - } - - if (this.exhaustAllowed) { - flags |= OPTS_EXHAUST_ALLOWED; - } - - const header = Buffer.alloc( - 4 * 4 + // Header - 4 // Flags - ); - - buffers.push(header); - - let totalLength = header.length; - const command = this.command; - totalLength += this.makeDocumentSegment(buffers, command); - - header.writeInt32LE(totalLength, 0); // messageLength - header.writeInt32LE(this.requestId, 4); // requestID - header.writeInt32LE(0, 8); // responseTo - header.writeInt32LE(opcodes.OP_MSG, 12); // opCode - header.writeUInt32LE(flags, 16); // flags - return buffers; - } - - makeDocumentSegment(buffers, document) { - const payloadTypeBuffer = Buffer.alloc(1); - payloadTypeBuffer[0] = 0; - - const documentBuffer = this.serializeBson(document); - buffers.push(payloadTypeBuffer); - buffers.push(documentBuffer); - - return payloadTypeBuffer.length + documentBuffer.length; - } - - serializeBson(document) { - return this.bson.serialize(document, { - checkKeys: this.checkKeys, - serializeFunctions: this.serializeFunctions, - ignoreUndefined: this.ignoreUndefined - }); - } -} - -Msg.getRequestId = function() { - _requestId = (_requestId + 1) & 0x7fffffff; - return _requestId; -}; - -class BinMsg { - constructor(bson, message, msgHeader, msgBody, opts) { - opts = opts || { promoteLongs: true, promoteValues: true, promoteBuffers: false }; - this.parsed = false; - this.raw = message; - this.data = msgBody; - this.bson = bson; - this.opts = opts; - - // Read the message header - this.length = msgHeader.length; - this.requestId = msgHeader.requestId; - this.responseTo = msgHeader.responseTo; - this.opCode = msgHeader.opCode; - this.fromCompressed = msgHeader.fromCompressed; - - // Read response flags - this.responseFlags = msgBody.readInt32LE(0); - this.checksumPresent = (this.responseFlags & OPTS_CHECKSUM_PRESENT) !== 0; - this.moreToCome = (this.responseFlags & OPTS_MORE_TO_COME) !== 0; - this.exhaustAllowed = (this.responseFlags & OPTS_EXHAUST_ALLOWED) !== 0; - this.promoteLongs = typeof opts.promoteLongs === 'boolean' ? opts.promoteLongs : true; - this.promoteValues = typeof opts.promoteValues === 'boolean' ? opts.promoteValues : true; - this.promoteBuffers = typeof opts.promoteBuffers === 'boolean' ? opts.promoteBuffers : false; - - this.documents = []; - } - - isParsed() { - return this.parsed; - } - - parse(options) { - // Don't parse again if not needed - if (this.parsed) return; - options = options || {}; - - this.index = 4; - // Allow the return of raw documents instead of parsing - const raw = options.raw || false; - const documentsReturnedIn = options.documentsReturnedIn || null; - const promoteLongs = - typeof options.promoteLongs === 'boolean' ? options.promoteLongs : this.opts.promoteLongs; - const promoteValues = - typeof options.promoteValues === 'boolean' ? options.promoteValues : this.opts.promoteValues; - const promoteBuffers = - typeof options.promoteBuffers === 'boolean' - ? options.promoteBuffers - : this.opts.promoteBuffers; - - // Set up the options - const _options = { - promoteLongs: promoteLongs, - promoteValues: promoteValues, - promoteBuffers: promoteBuffers - }; - - while (this.index < this.data.length) { - const payloadType = this.data.readUInt8(this.index++); - if (payloadType === 1) { - console.error('TYPE 1'); - } else if (payloadType === 0) { - const bsonSize = this.data.readUInt32LE(this.index); - const bin = this.data.slice(this.index, this.index + bsonSize); - this.documents.push(raw ? bin : this.bson.deserialize(bin, _options)); - - this.index += bsonSize; - } - } - - if (this.documents.length === 1 && documentsReturnedIn != null && raw) { - const fieldsAsRaw = {}; - fieldsAsRaw[documentsReturnedIn] = true; - _options.fieldsAsRaw = fieldsAsRaw; - - const doc = this.bson.deserialize(this.documents[0], _options); - this.documents = [doc]; - } - - this.parsed = true; - } -} - -module.exports = { Msg, BinMsg }; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/connection/pool.js b/scripts/2.5/node_modules/mongodb/lib/core/connection/pool.js deleted file mode 100644 index adc85900..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/core/connection/pool.js +++ /dev/null @@ -1,1256 +0,0 @@ -'use strict'; - -const inherits = require('util').inherits; -const EventEmitter = require('events').EventEmitter; -const MongoError = require('../error').MongoError; -const MongoTimeoutError = require('../error').MongoTimeoutError; -const MongoWriteConcernError = require('../error').MongoWriteConcernError; -const Logger = require('./logger'); -const f = require('util').format; -const Msg = require('./msg').Msg; -const CommandResult = require('./command_result'); -const MESSAGE_HEADER_SIZE = require('../wireprotocol/shared').MESSAGE_HEADER_SIZE; -const COMPRESSION_DETAILS_SIZE = require('../wireprotocol/shared').COMPRESSION_DETAILS_SIZE; -const opcodes = require('../wireprotocol/shared').opcodes; -const compress = require('../wireprotocol/compression').compress; -const compressorIDs = require('../wireprotocol/compression').compressorIDs; -const uncompressibleCommands = require('../wireprotocol/compression').uncompressibleCommands; -const apm = require('./apm'); -const Buffer = require('safe-buffer').Buffer; -const connect = require('./connect'); -const updateSessionFromResponse = require('../sessions').updateSessionFromResponse; -const eachAsync = require('../utils').eachAsync; - -var DISCONNECTED = 'disconnected'; -var CONNECTING = 'connecting'; -var CONNECTED = 'connected'; -var DESTROYING = 'destroying'; -var DESTROYED = 'destroyed'; - -const CONNECTION_EVENTS = new Set([ - 'error', - 'close', - 'timeout', - 'parseError', - 'connect', - 'message' -]); - -var _id = 0; - -/** - * Creates a new Pool instance - * @class - * @param {string} options.host The server host - * @param {number} options.port The server port - * @param {number} [options.size=5] Max server connection pool size - * @param {number} [options.minSize=0] Minimum server connection pool size - * @param {boolean} [options.reconnect=true] Server will attempt to reconnect on loss of connection - * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times - * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries - * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled - * @param {number} [options.keepAliveInitialDelay=300000] Initial delay before TCP keep alive enabled - * @param {boolean} [options.noDelay=true] TCP Connection no delay - * @param {number} [options.connectionTimeout=30000] TCP Connection timeout setting - * @param {number} [options.socketTimeout=360000] TCP Socket timeout setting - * @param {number} [options.monitoringSocketTimeout=30000] TCP Socket timeout setting for replicaset monitoring socket - * @param {boolean} [options.ssl=false] Use SSL for connection - * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. - * @param {Buffer} [options.ca] SSL Certificate store binary buffer - * @param {Buffer} [options.crl] SSL Certificate revocation store binary buffer - * @param {Buffer} [options.cert] SSL Certificate binary buffer - * @param {Buffer} [options.key] SSL Key file binary buffer - * @param {string} [options.passphrase] SSL Certificate pass phrase - * @param {boolean} [options.rejectUnauthorized=false] Reject unauthorized server certificates - * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits - * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. - * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. - * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. - * @fires Pool#connect - * @fires Pool#close - * @fires Pool#error - * @fires Pool#timeout - * @fires Pool#parseError - * @return {Pool} A cursor instance - */ -var Pool = function(topology, options) { - // Add event listener - EventEmitter.call(this); - - // Store topology for later use - this.topology = topology; - - // Add the options - this.options = Object.assign( - { - // Host and port settings - host: 'localhost', - port: 27017, - // Pool default max size - size: 5, - // Pool default min size - minSize: 0, - // socket settings - connectionTimeout: 30000, - socketTimeout: 360000, - keepAlive: true, - keepAliveInitialDelay: 300000, - noDelay: true, - // SSL Settings - ssl: false, - checkServerIdentity: true, - ca: null, - crl: null, - cert: null, - key: null, - passphrase: null, - rejectUnauthorized: false, - promoteLongs: true, - promoteValues: true, - promoteBuffers: false, - // Reconnection options - reconnect: true, - reconnectInterval: 1000, - reconnectTries: 30, - // Enable domains - domainsEnabled: false, - // feature flag for determining if we are running with the unified topology or not - legacyCompatMode: true - }, - options - ); - - // Identification information - this.id = _id++; - // Current reconnect retries - this.retriesLeft = this.options.reconnectTries; - this.reconnectId = null; - this.reconnectError = null; - // No bson parser passed in - if ( - !options.bson || - (options.bson && - (typeof options.bson.serialize !== 'function' || - typeof options.bson.deserialize !== 'function')) - ) { - throw new Error('must pass in valid bson parser'); - } - - // Logger instance - this.logger = Logger('Pool', options); - // Pool state - this.state = DISCONNECTED; - // Connections - this.availableConnections = []; - this.inUseConnections = []; - this.connectingConnections = 0; - // Currently executing - this.executing = false; - // Operation work queue - this.queue = []; - - // Number of consecutive timeouts caught - this.numberOfConsecutiveTimeouts = 0; - // Current pool Index - this.connectionIndex = 0; - - // event handlers - const pool = this; - this._messageHandler = messageHandler(this); - this._connectionCloseHandler = function(err) { - const connection = this; - connectionFailureHandler(pool, 'close', err, connection); - }; - - this._connectionErrorHandler = function(err) { - const connection = this; - connectionFailureHandler(pool, 'error', err, connection); - }; - - this._connectionTimeoutHandler = function(err) { - const connection = this; - connectionFailureHandler(pool, 'timeout', err, connection); - }; - - this._connectionParseErrorHandler = function(err) { - const connection = this; - connectionFailureHandler(pool, 'parseError', err, connection); - }; -}; - -inherits(Pool, EventEmitter); - -Object.defineProperty(Pool.prototype, 'size', { - enumerable: true, - get: function() { - return this.options.size; - } -}); - -Object.defineProperty(Pool.prototype, 'minSize', { - enumerable: true, - get: function() { - return this.options.minSize; - } -}); - -Object.defineProperty(Pool.prototype, 'connectionTimeout', { - enumerable: true, - get: function() { - return this.options.connectionTimeout; - } -}); - -Object.defineProperty(Pool.prototype, 'socketTimeout', { - enumerable: true, - get: function() { - return this.options.socketTimeout; - } -}); - -// clears all pool state -function resetPoolState(pool) { - pool.inUseConnections = []; - pool.availableConnections = []; - pool.connectingConnections = 0; - pool.executing = false; - pool.numberOfConsecutiveTimeouts = 0; - pool.connectionIndex = 0; - pool.retriesLeft = pool.options.reconnectTries; - pool.reconnectId = null; -} - -function stateTransition(self, newState) { - var legalTransitions = { - disconnected: [CONNECTING, DESTROYING, DISCONNECTED], - connecting: [CONNECTING, DESTROYING, CONNECTED, DISCONNECTED], - connected: [CONNECTED, DISCONNECTED, DESTROYING], - destroying: [DESTROYING, DESTROYED], - destroyed: [DESTROYED] - }; - - // Get current state - var legalStates = legalTransitions[self.state]; - if (legalStates && legalStates.indexOf(newState) !== -1) { - self.emit('stateChanged', self.state, newState); - self.state = newState; - } else { - self.logger.error( - f( - 'Pool with id [%s] failed attempted illegal state transition from [%s] to [%s] only following state allowed [%s]', - self.id, - self.state, - newState, - legalStates - ) - ); - } -} - -function connectionFailureHandler(pool, event, err, conn) { - if (conn) { - if (conn._connectionFailHandled) return; - conn._connectionFailHandled = true; - conn.destroy(); - - // Remove the connection - removeConnection(pool, conn); - - // Flush all work Items on this connection - while (conn.workItems.length > 0) { - const workItem = conn.workItems.shift(); - if (workItem.cb) workItem.cb(err); - } - } - - // Did we catch a timeout, increment the numberOfConsecutiveTimeouts - if (event === 'timeout') { - pool.numberOfConsecutiveTimeouts = pool.numberOfConsecutiveTimeouts + 1; - - // Have we timed out more than reconnectTries in a row ? - // Force close the pool as we are trying to connect to tcp sink hole - if (pool.numberOfConsecutiveTimeouts > pool.options.reconnectTries) { - pool.numberOfConsecutiveTimeouts = 0; - // Destroy all connections and pool - pool.destroy(true); - // Emit close event - return pool.emit('close', pool); - } - } - - // No more socket available propegate the event - if (pool.socketCount() === 0) { - if (pool.state !== DESTROYED && pool.state !== DESTROYING) { - stateTransition(pool, DISCONNECTED); - } - - // Do not emit error events, they are always close events - // do not trigger the low level error handler in node - event = event === 'error' ? 'close' : event; - pool.emit(event, err); - } - - // Start reconnection attempts - if (!pool.reconnectId && pool.options.reconnect) { - pool.reconnectError = err; - pool.reconnectId = setTimeout(attemptReconnect(pool), pool.options.reconnectInterval); - } - - // Do we need to do anything to maintain the minimum pool size - const totalConnections = totalConnectionCount(pool); - if (totalConnections < pool.minSize) { - createConnection(pool); - } -} - -function attemptReconnect(pool, callback) { - return function() { - pool.emit('attemptReconnect', pool); - - if (pool.state === DESTROYED || pool.state === DESTROYING) { - if (typeof callback === 'function') { - callback(new MongoError('Cannot create connection when pool is destroyed')); - } - - return; - } - - pool.retriesLeft = pool.retriesLeft - 1; - if (pool.retriesLeft <= 0) { - pool.destroy(); - - const error = new MongoTimeoutError( - `failed to reconnect after ${pool.options.reconnectTries} attempts with interval ${ - pool.options.reconnectInterval - } ms`, - pool.reconnectError - ); - - pool.emit('reconnectFailed', error); - if (typeof callback === 'function') { - callback(error); - } - - return; - } - - // clear the reconnect id on retry - pool.reconnectId = null; - - // now retry creating a connection - createConnection(pool, (err, conn) => { - if (err == null) { - pool.reconnectId = null; - pool.retriesLeft = pool.options.reconnectTries; - pool.emit('reconnect', pool); - } - - if (typeof callback === 'function') { - callback(err, conn); - } - }); - }; -} - -function moveConnectionBetween(connection, from, to) { - var index = from.indexOf(connection); - // Move the connection from connecting to available - if (index !== -1) { - from.splice(index, 1); - to.push(connection); - } -} - -function messageHandler(self) { - return function(message, connection) { - // workItem to execute - var workItem = null; - - // Locate the workItem - for (var i = 0; i < connection.workItems.length; i++) { - if (connection.workItems[i].requestId === message.responseTo) { - // Get the callback - workItem = connection.workItems[i]; - // Remove from list of workItems - connection.workItems.splice(i, 1); - } - } - - if (workItem && workItem.monitoring) { - moveConnectionBetween(connection, self.inUseConnections, self.availableConnections); - } - - // Reset timeout counter - self.numberOfConsecutiveTimeouts = 0; - - // Reset the connection timeout if we modified it for - // this operation - if (workItem && workItem.socketTimeout) { - connection.resetSocketTimeout(); - } - - // Log if debug enabled - if (self.logger.isDebug()) { - self.logger.debug( - f( - 'message [%s] received from %s:%s', - message.raw.toString('hex'), - self.options.host, - self.options.port - ) - ); - } - - function handleOperationCallback(self, cb, err, result) { - // No domain enabled - if (!self.options.domainsEnabled) { - return process.nextTick(function() { - return cb(err, result); - }); - } - - // Domain enabled just call the callback - cb(err, result); - } - - // Keep executing, ensure current message handler does not stop execution - if (!self.executing) { - process.nextTick(function() { - _execute(self)(); - }); - } - - // Time to dispatch the message if we have a callback - if (workItem && !workItem.immediateRelease) { - try { - // Parse the message according to the provided options - message.parse(workItem); - } catch (err) { - return handleOperationCallback(self, workItem.cb, new MongoError(err)); - } - - if (message.documents[0]) { - const document = message.documents[0]; - const session = workItem.session; - if (session) { - updateSessionFromResponse(session, document); - } - - if (document.$clusterTime) { - self.topology.clusterTime = document.$clusterTime; - } - } - - // Establish if we have an error - if (workItem.command && message.documents[0]) { - const responseDoc = message.documents[0]; - - if (responseDoc.writeConcernError) { - const err = new MongoWriteConcernError(responseDoc.writeConcernError, responseDoc); - return handleOperationCallback(self, workItem.cb, err); - } - - if (responseDoc.ok === 0 || responseDoc.$err || responseDoc.errmsg || responseDoc.code) { - return handleOperationCallback(self, workItem.cb, new MongoError(responseDoc)); - } - } - - // Add the connection details - message.hashedName = connection.hashedName; - - // Return the documents - handleOperationCallback( - self, - workItem.cb, - null, - new CommandResult(workItem.fullResult ? message : message.documents[0], connection, message) - ); - } - }; -} - -/** - * Return the total socket count in the pool. - * @method - * @return {Number} The number of socket available. - */ -Pool.prototype.socketCount = function() { - return this.availableConnections.length + this.inUseConnections.length; - // + this.connectingConnections.length; -}; - -function totalConnectionCount(pool) { - return ( - pool.availableConnections.length + pool.inUseConnections.length + pool.connectingConnections - ); -} - -/** - * Return all pool connections - * @method - * @return {Connection[]} The pool connections - */ -Pool.prototype.allConnections = function() { - return this.availableConnections.concat(this.inUseConnections); -}; - -/** - * Get a pool connection (round-robin) - * @method - * @return {Connection} - */ -Pool.prototype.get = function() { - return this.allConnections()[0]; -}; - -/** - * Is the pool connected - * @method - * @return {boolean} - */ -Pool.prototype.isConnected = function() { - // We are in a destroyed state - if (this.state === DESTROYED || this.state === DESTROYING) { - return false; - } - - // Get connections - var connections = this.availableConnections.concat(this.inUseConnections); - - // Check if we have any connected connections - for (var i = 0; i < connections.length; i++) { - if (connections[i].isConnected()) return true; - } - - // Not connected - return false; -}; - -/** - * Was the pool destroyed - * @method - * @return {boolean} - */ -Pool.prototype.isDestroyed = function() { - return this.state === DESTROYED || this.state === DESTROYING; -}; - -/** - * Is the pool in a disconnected state - * @method - * @return {boolean} - */ -Pool.prototype.isDisconnected = function() { - return this.state === DISCONNECTED; -}; - -/** - * Connect pool - */ -Pool.prototype.connect = function() { - if (this.state !== DISCONNECTED) { - throw new MongoError('connection in unlawful state ' + this.state); - } - - stateTransition(this, CONNECTING); - createConnection(this, (err, conn) => { - if (err) { - if (this.state === CONNECTING) { - this.emit('error', err); - } - - this.destroy(); - return; - } - - stateTransition(this, CONNECTED); - this.emit('connect', this, conn); - - // create min connections - if (this.minSize) { - for (let i = 0; i < this.minSize; i++) { - createConnection(this); - } - } - }); -}; - -/** - * Authenticate using a specified mechanism - * @param {authResultCallback} callback A callback function - */ -Pool.prototype.auth = function(credentials, callback) { - if (typeof callback === 'function') callback(null, null); -}; - -/** - * Logout all users against a database - * @param {authResultCallback} callback A callback function - */ -Pool.prototype.logout = function(dbName, callback) { - if (typeof callback === 'function') callback(null, null); -}; - -/** - * Unref the pool - * @method - */ -Pool.prototype.unref = function() { - // Get all the known connections - var connections = this.availableConnections.concat(this.inUseConnections); - - connections.forEach(function(c) { - c.unref(); - }); -}; - -// Destroy the connections -function destroy(self, connections, options, callback) { - eachAsync( - connections, - (conn, cb) => { - for (const eventName of CONNECTION_EVENTS) { - conn.removeAllListeners(eventName); - } - - conn.destroy(options, cb); - }, - err => { - if (err) { - if (typeof callback === 'function') callback(err, null); - return; - } - - resetPoolState(self); - self.queue = []; - - stateTransition(self, DESTROYED); - if (typeof callback === 'function') callback(null, null); - } - ); -} - -/** - * Destroy pool - * @method - */ -Pool.prototype.destroy = function(force, callback) { - var self = this; - // Do not try again if the pool is already dead - if (this.state === DESTROYED || self.state === DESTROYING) { - if (typeof callback === 'function') callback(null, null); - return; - } - - // Set state to destroyed - stateTransition(this, DESTROYING); - - // Are we force closing - if (force) { - // Get all the known connections - var connections = self.availableConnections.concat(self.inUseConnections); - - // Flush any remaining work items with - // an error - while (self.queue.length > 0) { - var workItem = self.queue.shift(); - if (typeof workItem.cb === 'function') { - workItem.cb(new MongoError('Pool was force destroyed')); - } - } - - // Destroy the topology - return destroy(self, connections, { force: true }, callback); - } - - // Clear out the reconnect if set - if (this.reconnectId) { - clearTimeout(this.reconnectId); - } - - // Wait for the operations to drain before we close the pool - function checkStatus() { - flushMonitoringOperations(self.queue); - - if (self.queue.length === 0) { - // Get all the known connections - var connections = self.availableConnections.concat(self.inUseConnections); - - // Check if we have any in flight operations - for (var i = 0; i < connections.length; i++) { - // There is an operation still in flight, reschedule a - // check waiting for it to drain - if (connections[i].workItems.length > 0) { - return setTimeout(checkStatus, 1); - } - } - - destroy(self, connections, { force: false }, callback); - // } else if (self.queue.length > 0 && !this.reconnectId) { - } else { - // Ensure we empty the queue - _execute(self)(); - // Set timeout - setTimeout(checkStatus, 1); - } - } - - // Initiate drain of operations - checkStatus(); -}; - -/** - * Reset all connections of this pool - * - * @param {function} [callback] - */ -Pool.prototype.reset = function(callback) { - const connections = this.availableConnections.concat(this.inUseConnections); - eachAsync( - connections, - (conn, cb) => { - for (const eventName of CONNECTION_EVENTS) { - conn.removeAllListeners(eventName); - } - - conn.destroy({ force: true }, cb); - }, - err => { - if (err) { - if (typeof callback === 'function') { - callback(err, null); - return; - } - } - - resetPoolState(this); - - // create an initial connection, and kick off execution again - createConnection(this); - - if (typeof callback === 'function') { - callback(null, null); - } - } - ); -}; - -// Prepare the buffer that Pool.prototype.write() uses to send to the server -function serializeCommand(self, command, callback) { - const originalCommandBuffer = command.toBin(); - - // Check whether we and the server have agreed to use a compressor - const shouldCompress = !!self.options.agreedCompressor; - if (!shouldCompress || !canCompress(command)) { - return callback(null, originalCommandBuffer); - } - - // Transform originalCommandBuffer into OP_COMPRESSED - const concatenatedOriginalCommandBuffer = Buffer.concat(originalCommandBuffer); - const messageToBeCompressed = concatenatedOriginalCommandBuffer.slice(MESSAGE_HEADER_SIZE); - - // Extract information needed for OP_COMPRESSED from the uncompressed message - const originalCommandOpCode = concatenatedOriginalCommandBuffer.readInt32LE(12); - - // Compress the message body - compress(self, messageToBeCompressed, function(err, compressedMessage) { - if (err) return callback(err, null); - - // Create the msgHeader of OP_COMPRESSED - const msgHeader = Buffer.alloc(MESSAGE_HEADER_SIZE); - msgHeader.writeInt32LE( - MESSAGE_HEADER_SIZE + COMPRESSION_DETAILS_SIZE + compressedMessage.length, - 0 - ); // messageLength - msgHeader.writeInt32LE(command.requestId, 4); // requestID - msgHeader.writeInt32LE(0, 8); // responseTo (zero) - msgHeader.writeInt32LE(opcodes.OP_COMPRESSED, 12); // opCode - - // Create the compression details of OP_COMPRESSED - const compressionDetails = Buffer.alloc(COMPRESSION_DETAILS_SIZE); - compressionDetails.writeInt32LE(originalCommandOpCode, 0); // originalOpcode - compressionDetails.writeInt32LE(messageToBeCompressed.length, 4); // Size of the uncompressed compressedMessage, excluding the MsgHeader - compressionDetails.writeUInt8(compressorIDs[self.options.agreedCompressor], 8); // compressorID - - return callback(null, [msgHeader, compressionDetails, compressedMessage]); - }); -} - -/** - * Write a message to MongoDB - * @method - * @return {Connection} - */ -Pool.prototype.write = function(command, options, cb) { - var self = this; - // Ensure we have a callback - if (typeof options === 'function') { - cb = options; - } - - // Always have options - options = options || {}; - - // We need to have a callback function unless the message returns no response - if (!(typeof cb === 'function') && !options.noResponse) { - throw new MongoError('write method must provide a callback'); - } - - // Pool was destroyed error out - if (this.state === DESTROYED || this.state === DESTROYING) { - // Callback with an error - if (cb) { - try { - cb(new MongoError('pool destroyed')); - } catch (err) { - process.nextTick(function() { - throw err; - }); - } - } - - return; - } - - if (this.options.domainsEnabled && process.domain && typeof cb === 'function') { - // if we have a domain bind to it - var oldCb = cb; - cb = process.domain.bind(function() { - // v8 - argumentsToArray one-liner - var args = new Array(arguments.length); - for (var i = 0; i < arguments.length; i++) { - args[i] = arguments[i]; - } - // bounce off event loop so domain switch takes place - process.nextTick(function() { - oldCb.apply(null, args); - }); - }); - } - - // Do we have an operation - var operation = { - cb: cb, - raw: false, - promoteLongs: true, - promoteValues: true, - promoteBuffers: false, - fullResult: false - }; - - // Set the options for the parsing - operation.promoteLongs = typeof options.promoteLongs === 'boolean' ? options.promoteLongs : true; - operation.promoteValues = - typeof options.promoteValues === 'boolean' ? options.promoteValues : true; - operation.promoteBuffers = - typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : false; - operation.raw = typeof options.raw === 'boolean' ? options.raw : false; - operation.immediateRelease = - typeof options.immediateRelease === 'boolean' ? options.immediateRelease : false; - operation.documentsReturnedIn = options.documentsReturnedIn; - operation.command = typeof options.command === 'boolean' ? options.command : false; - operation.fullResult = typeof options.fullResult === 'boolean' ? options.fullResult : false; - operation.noResponse = typeof options.noResponse === 'boolean' ? options.noResponse : false; - operation.session = options.session || null; - - // Optional per operation socketTimeout - operation.socketTimeout = options.socketTimeout; - operation.monitoring = options.monitoring; - // Custom socket Timeout - if (options.socketTimeout) { - operation.socketTimeout = options.socketTimeout; - } - - // Get the requestId - operation.requestId = command.requestId; - - // If command monitoring is enabled we need to modify the callback here - if (self.options.monitorCommands) { - this.emit('commandStarted', new apm.CommandStartedEvent(this, command)); - - operation.started = process.hrtime(); - operation.cb = (err, reply) => { - if (err) { - self.emit( - 'commandFailed', - new apm.CommandFailedEvent(this, command, err, operation.started) - ); - } else { - if (reply && reply.result && (reply.result.ok === 0 || reply.result.$err)) { - self.emit( - 'commandFailed', - new apm.CommandFailedEvent(this, command, reply.result, operation.started) - ); - } else { - self.emit( - 'commandSucceeded', - new apm.CommandSucceededEvent(this, command, reply, operation.started) - ); - } - } - - if (typeof cb === 'function') cb(err, reply); - }; - } - - // Prepare the operation buffer - serializeCommand(self, command, (err, serializedBuffers) => { - if (err) throw err; - - // Set the operation's buffer to the serialization of the commands - operation.buffer = serializedBuffers; - - // If we have a monitoring operation schedule as the very first operation - // Otherwise add to back of queue - if (options.monitoring) { - self.queue.unshift(operation); - } else { - self.queue.push(operation); - } - - // Attempt to execute the operation - if (!self.executing) { - process.nextTick(function() { - _execute(self)(); - }); - } - }); -}; - -// Return whether a command contains an uncompressible command term -// Will return true if command contains no uncompressible command terms -function canCompress(command) { - const commandDoc = command instanceof Msg ? command.command : command.query; - const commandName = Object.keys(commandDoc)[0]; - return uncompressibleCommands.indexOf(commandName) === -1; -} - -// Remove connection method -function remove(connection, connections) { - for (var i = 0; i < connections.length; i++) { - if (connections[i] === connection) { - connections.splice(i, 1); - return true; - } - } -} - -function removeConnection(self, connection) { - if (remove(connection, self.availableConnections)) return; - if (remove(connection, self.inUseConnections)) return; -} - -function createConnection(pool, callback) { - if (pool.state === DESTROYED || pool.state === DESTROYING) { - if (typeof callback === 'function') { - callback(new MongoError('Cannot create connection when pool is destroyed')); - } - - return; - } - - pool.connectingConnections++; - connect(pool.options, (err, connection) => { - pool.connectingConnections--; - - if (err) { - if (pool.logger.isDebug()) { - pool.logger.debug(`connection attempt failed with error [${JSON.stringify(err)}]`); - } - - if (pool.options.legacyCompatMode === false) { - // The unified topology uses the reported `error` from a pool to track what error - // reason is returned to the user during selection timeout. We only want to emit - // this if the pool is active because the listeners are removed on destruction. - if (pool.state !== DESTROYED && pool.state !== DESTROYING) { - pool.emit('error', err); - } - } - - // check if reconnect is enabled, and attempt retry if so - if (!pool.reconnectId && pool.options.reconnect) { - if (pool.state === CONNECTING && pool.options.legacyCompatMode) { - callback(err); - return; - } - - pool.reconnectError = err; - pool.reconnectId = setTimeout( - attemptReconnect(pool, callback), - pool.options.reconnectInterval - ); - - return; - } - - if (typeof callback === 'function') { - callback(err); - } - - return; - } - - // the pool might have been closed since we started creating the connection - if (pool.state === DESTROYED || pool.state === DESTROYING) { - if (typeof callback === 'function') { - callback(new MongoError('Pool was destroyed after connection creation')); - } - - connection.destroy(); - return; - } - - // otherwise, connect relevant event handlers and add it to our available connections - connection.on('error', pool._connectionErrorHandler); - connection.on('close', pool._connectionCloseHandler); - connection.on('timeout', pool._connectionTimeoutHandler); - connection.on('parseError', pool._connectionParseErrorHandler); - connection.on('message', pool._messageHandler); - - pool.availableConnections.push(connection); - - // if a callback was provided, return the connection - if (typeof callback === 'function') { - callback(null, connection); - } - - // immediately execute any waiting work - _execute(pool)(); - }); -} - -function flushMonitoringOperations(queue) { - for (var i = 0; i < queue.length; i++) { - if (queue[i].monitoring) { - var workItem = queue[i]; - queue.splice(i, 1); - workItem.cb( - new MongoError({ message: 'no connection available for monitoring', driver: true }) - ); - } - } -} - -function _execute(self) { - return function() { - if (self.state === DESTROYED) return; - // Already executing, skip - if (self.executing) return; - // Set pool as executing - self.executing = true; - - // New pool connections are in progress, wait them to finish - // before executing any more operation to ensure distribution of - // operations - if (self.connectingConnections > 0) { - self.executing = false; - return; - } - - // As long as we have available connections - // eslint-disable-next-line - while (true) { - // Total availble connections - const totalConnections = totalConnectionCount(self); - - // No available connections available, flush any monitoring ops - if (self.availableConnections.length === 0) { - // Flush any monitoring operations - flushMonitoringOperations(self.queue); - break; - } - - // No queue break - if (self.queue.length === 0) { - break; - } - - var connection = null; - const connections = self.availableConnections.filter(conn => conn.workItems.length === 0); - - // No connection found that has no work on it, just pick one for pipelining - if (connections.length === 0) { - connection = - self.availableConnections[self.connectionIndex++ % self.availableConnections.length]; - } else { - connection = connections[self.connectionIndex++ % connections.length]; - } - - // Is the connection connected - if (!connection.isConnected()) { - // Remove the disconnected connection - removeConnection(self, connection); - // Flush any monitoring operations in the queue, failing fast - flushMonitoringOperations(self.queue); - break; - } - - // Get the next work item - var workItem = self.queue.shift(); - - // If we are monitoring we need to use a connection that is not - // running another operation to avoid socket timeout changes - // affecting an existing operation - if (workItem.monitoring) { - var foundValidConnection = false; - - for (let i = 0; i < self.availableConnections.length; i++) { - // If the connection is connected - // And there are no pending workItems on it - // Then we can safely use it for monitoring. - if ( - self.availableConnections[i].isConnected() && - self.availableConnections[i].workItems.length === 0 - ) { - foundValidConnection = true; - connection = self.availableConnections[i]; - break; - } - } - - // No safe connection found, attempt to grow the connections - // if possible and break from the loop - if (!foundValidConnection) { - // Put workItem back on the queue - self.queue.unshift(workItem); - - // Attempt to grow the pool if it's not yet maxsize - if (totalConnections < self.options.size && self.queue.length > 0) { - // Create a new connection - createConnection(self); - } - - // Re-execute the operation - setTimeout(function() { - _execute(self)(); - }, 10); - - break; - } - } - - // Don't execute operation until we have a full pool - if (totalConnections < self.options.size) { - // Connection has work items, then put it back on the queue - // and create a new connection - if (connection.workItems.length > 0) { - // Lets put the workItem back on the list - self.queue.unshift(workItem); - // Create a new connection - createConnection(self); - // Break from the loop - break; - } - } - - // Get actual binary commands - var buffer = workItem.buffer; - - // If we are monitoring take the connection of the availableConnections - if (workItem.monitoring) { - moveConnectionBetween(connection, self.availableConnections, self.inUseConnections); - } - - // Track the executing commands on the mongo server - // as long as there is an expected response - if (!workItem.noResponse) { - connection.workItems.push(workItem); - } - - // We have a custom socketTimeout - if (!workItem.immediateRelease && typeof workItem.socketTimeout === 'number') { - connection.setSocketTimeout(workItem.socketTimeout); - } - - // Capture if write was successful - var writeSuccessful = true; - - // Put operation on the wire - if (Array.isArray(buffer)) { - for (let i = 0; i < buffer.length; i++) { - writeSuccessful = connection.write(buffer[i]); - } - } else { - writeSuccessful = connection.write(buffer); - } - - // if the command is designated noResponse, call the callback immeditely - if (workItem.noResponse && typeof workItem.cb === 'function') { - workItem.cb(null, null); - } - - if (writeSuccessful === false) { - // If write not successful put back on queue - self.queue.unshift(workItem); - // Remove the disconnected connection - removeConnection(self, connection); - // Flush any monitoring operations in the queue, failing fast - flushMonitoringOperations(self.queue); - break; - } - } - - self.executing = false; - }; -} - -// Make execution loop available for testing -Pool._execute = _execute; - -/** - * A server connect event, used to verify that the connection is up and running - * - * @event Pool#connect - * @type {Pool} - */ - -/** - * A server reconnect event, used to verify that pool reconnected. - * - * @event Pool#reconnect - * @type {Pool} - */ - -/** - * The server connection closed, all pool connections closed - * - * @event Pool#close - * @type {Pool} - */ - -/** - * The server connection caused an error, all pool connections closed - * - * @event Pool#error - * @type {Pool} - */ - -/** - * The server connection timed out, all pool connections closed - * - * @event Pool#timeout - * @type {Pool} - */ - -/** - * The driver experienced an invalid message, all pool connections closed - * - * @event Pool#parseError - * @type {Pool} - */ - -/** - * The driver attempted to reconnect - * - * @event Pool#attemptReconnect - * @type {Pool} - */ - -/** - * The driver exhausted all reconnect attempts - * - * @event Pool#reconnectFailed - * @type {Pool} - */ - -module.exports = Pool; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/connection/utils.js b/scripts/2.5/node_modules/mongodb/lib/core/connection/utils.js deleted file mode 100644 index 2f3d889f..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/core/connection/utils.js +++ /dev/null @@ -1,57 +0,0 @@ -'use strict'; - -const require_optional = require('require_optional'); - -function debugOptions(debugFields, options) { - var finaloptions = {}; - debugFields.forEach(function(n) { - finaloptions[n] = options[n]; - }); - - return finaloptions; -} - -function retrieveBSON() { - var BSON = require('bson'); - BSON.native = false; - - try { - var optionalBSON = require_optional('bson-ext'); - if (optionalBSON) { - optionalBSON.native = true; - return optionalBSON; - } - } catch (err) {} // eslint-disable-line - - return BSON; -} - -// Throw an error if an attempt to use Snappy is made when Snappy is not installed -function noSnappyWarning() { - throw new Error( - 'Attempted to use Snappy compression, but Snappy is not installed. Install or disable Snappy compression and try again.' - ); -} - -// Facilitate loading Snappy optionally -function retrieveSnappy() { - var snappy = null; - try { - snappy = require_optional('snappy'); - } catch (error) {} // eslint-disable-line - if (!snappy) { - snappy = { - compress: noSnappyWarning, - uncompress: noSnappyWarning, - compressSync: noSnappyWarning, - uncompressSync: noSnappyWarning - }; - } - return snappy; -} - -module.exports = { - debugOptions, - retrieveBSON, - retrieveSnappy -}; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/cursor.js b/scripts/2.5/node_modules/mongodb/lib/core/cursor.js deleted file mode 100644 index f5272182..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/core/cursor.js +++ /dev/null @@ -1,886 +0,0 @@ -'use strict'; - -const Logger = require('./connection/logger'); -const retrieveBSON = require('./connection/utils').retrieveBSON; -const MongoError = require('./error').MongoError; -const MongoNetworkError = require('./error').MongoNetworkError; -const mongoErrorContextSymbol = require('./error').mongoErrorContextSymbol; -const collationNotSupported = require('./utils').collationNotSupported; -const ReadPreference = require('./topologies/read_preference'); -const isUnifiedTopology = require('./utils').isUnifiedTopology; -const executeOperation = require('../operations/execute_operation'); -const Readable = require('stream').Readable; -const SUPPORTS = require('../utils').SUPPORTS; -const MongoDBNamespace = require('../utils').MongoDBNamespace; -const OperationBase = require('../operations/operation').OperationBase; - -const BSON = retrieveBSON(); -const Long = BSON.Long; - -// Possible states for a cursor -const CursorState = { - INIT: 0, - OPEN: 1, - CLOSED: 2, - GET_MORE: 3 -}; - -// -// Handle callback (including any exceptions thrown) -function handleCallback(callback, err, result) { - try { - callback(err, result); - } catch (err) { - process.nextTick(function() { - throw err; - }); - } -} - -/** - * This is a cursor results callback - * - * @callback resultCallback - * @param {error} error An error object. Set to null if no error present - * @param {object} document - */ - -/** - * @fileOverview The **Cursor** class is an internal class that embodies a cursor on MongoDB - * allowing for iteration over the results returned from the underlying query. - * - * **CURSORS Cannot directly be instantiated** - */ - -/** - * The core cursor class. All cursors in the driver build off of this one. - * - * @property {number} cursorBatchSize The current cursorBatchSize for the cursor - * @property {number} cursorLimit The current cursorLimit for the cursor - * @property {number} cursorSkip The current cursorSkip for the cursor - */ -class CoreCursor extends Readable { - /** - * Create a new core `Cursor` instance. - * **NOTE** Not to be instantiated directly - * - * @param {object} topology The server topology instance. - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {{object}|Long} cmd The selector (can be a command or a cursorId) - * @param {object} [options=null] Optional settings. - * @param {object} [options.batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/find/| find command documentation} and {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. - * @param {array} [options.documents=[]] Initial documents list for cursor - * @param {object} [options.transforms=null] Transform methods for the cursor results - * @param {function} [options.transforms.query] Transform the value returned from the initial query - * @param {function} [options.transforms.doc] Transform each document returned from Cursor.prototype._next - */ - constructor(topology, ns, cmd, options) { - super({ objectMode: true }); - options = options || {}; - - if (ns instanceof OperationBase) { - this.operation = ns; - ns = this.operation.ns.toString(); - options = this.operation.options; - cmd = this.operation.cmd ? this.operation.cmd : {}; - } - - // Cursor pool - this.pool = null; - // Cursor server - this.server = null; - - // Do we have a not connected handler - this.disconnectHandler = options.disconnectHandler; - - // Set local values - this.bson = topology.s.bson; - this.ns = ns; - this.namespace = MongoDBNamespace.fromString(ns); - this.cmd = cmd; - this.options = options; - this.topology = topology; - - // All internal state - this.cursorState = { - cursorId: null, - cmd, - documents: options.documents || [], - cursorIndex: 0, - dead: false, - killed: false, - init: false, - notified: false, - limit: options.limit || cmd.limit || 0, - skip: options.skip || cmd.skip || 0, - batchSize: options.batchSize || cmd.batchSize || 1000, - currentLimit: 0, - // Result field name if not a cursor (contains the array of results) - transforms: options.transforms, - raw: options.raw || (cmd && cmd.raw) - }; - - if (typeof options.session === 'object') { - this.cursorState.session = options.session; - } - - // Add promoteLong to cursor state - const topologyOptions = topology.s.options; - if (typeof topologyOptions.promoteLongs === 'boolean') { - this.cursorState.promoteLongs = topologyOptions.promoteLongs; - } else if (typeof options.promoteLongs === 'boolean') { - this.cursorState.promoteLongs = options.promoteLongs; - } - - // Add promoteValues to cursor state - if (typeof topologyOptions.promoteValues === 'boolean') { - this.cursorState.promoteValues = topologyOptions.promoteValues; - } else if (typeof options.promoteValues === 'boolean') { - this.cursorState.promoteValues = options.promoteValues; - } - - // Add promoteBuffers to cursor state - if (typeof topologyOptions.promoteBuffers === 'boolean') { - this.cursorState.promoteBuffers = topologyOptions.promoteBuffers; - } else if (typeof options.promoteBuffers === 'boolean') { - this.cursorState.promoteBuffers = options.promoteBuffers; - } - - if (topologyOptions.reconnect) { - this.cursorState.reconnect = topologyOptions.reconnect; - } - - // Logger - this.logger = Logger('Cursor', topologyOptions); - - // - // Did we pass in a cursor id - if (typeof cmd === 'number') { - this.cursorState.cursorId = Long.fromNumber(cmd); - this.cursorState.lastCursorId = this.cursorState.cursorId; - } else if (cmd instanceof Long) { - this.cursorState.cursorId = cmd; - this.cursorState.lastCursorId = cmd; - } - - // TODO: remove as part of NODE-2104 - if (this.operation) { - this.operation.cursorState = this.cursorState; - } - } - - setCursorBatchSize(value) { - this.cursorState.batchSize = value; - } - - cursorBatchSize() { - return this.cursorState.batchSize; - } - - setCursorLimit(value) { - this.cursorState.limit = value; - } - - cursorLimit() { - return this.cursorState.limit; - } - - setCursorSkip(value) { - this.cursorState.skip = value; - } - - cursorSkip() { - return this.cursorState.skip; - } - - /** - * Retrieve the next document from the cursor - * @method - * @param {resultCallback} callback A callback function - */ - _next(callback) { - nextFunction(this, callback); - } - - /** - * Clone the cursor - * @method - * @return {Cursor} - */ - clone() { - return this.topology.cursor(this.ns, this.cmd, this.options); - } - - /** - * Checks if the cursor is dead - * @method - * @return {boolean} A boolean signifying if the cursor is dead or not - */ - isDead() { - return this.cursorState.dead === true; - } - - /** - * Checks if the cursor was killed by the application - * @method - * @return {boolean} A boolean signifying if the cursor was killed by the application - */ - isKilled() { - return this.cursorState.killed === true; - } - - /** - * Checks if the cursor notified it's caller about it's death - * @method - * @return {boolean} A boolean signifying if the cursor notified the callback - */ - isNotified() { - return this.cursorState.notified === true; - } - - /** - * Returns current buffered documents length - * @method - * @return {number} The number of items in the buffered documents - */ - bufferedCount() { - return this.cursorState.documents.length - this.cursorState.cursorIndex; - } - - /** - * Returns current buffered documents - * @method - * @return {Array} An array of buffered documents - */ - readBufferedDocuments(number) { - const unreadDocumentsLength = this.cursorState.documents.length - this.cursorState.cursorIndex; - const length = number < unreadDocumentsLength ? number : unreadDocumentsLength; - let elements = this.cursorState.documents.slice( - this.cursorState.cursorIndex, - this.cursorState.cursorIndex + length - ); - - // Transform the doc with passed in transformation method if provided - if (this.cursorState.transforms && typeof this.cursorState.transforms.doc === 'function') { - // Transform all the elements - for (let i = 0; i < elements.length; i++) { - elements[i] = this.cursorState.transforms.doc(elements[i]); - } - } - - // Ensure we do not return any more documents than the limit imposed - // Just return the number of elements up to the limit - if ( - this.cursorState.limit > 0 && - this.cursorState.currentLimit + elements.length > this.cursorState.limit - ) { - elements = elements.slice(0, this.cursorState.limit - this.cursorState.currentLimit); - this.kill(); - } - - // Adjust current limit - this.cursorState.currentLimit = this.cursorState.currentLimit + elements.length; - this.cursorState.cursorIndex = this.cursorState.cursorIndex + elements.length; - - // Return elements - return elements; - } - - /** - * Resets local state for this cursor instance, and issues a `killCursors` command to the server - * - * @param {resultCallback} callback A callback function - */ - kill(callback) { - // Set cursor to dead - this.cursorState.dead = true; - this.cursorState.killed = true; - // Remove documents - this.cursorState.documents = []; - - // If no cursor id just return - if ( - this.cursorState.cursorId == null || - this.cursorState.cursorId.isZero() || - this.cursorState.init === false - ) { - if (callback) callback(null, null); - return; - } - - this.server.killCursors(this.ns, this.cursorState, callback); - } - - /** - * Resets the cursor - */ - rewind() { - if (this.cursorState.init) { - if (!this.cursorState.dead) { - this.kill(); - } - - this.cursorState.currentLimit = 0; - this.cursorState.init = false; - this.cursorState.dead = false; - this.cursorState.killed = false; - this.cursorState.notified = false; - this.cursorState.documents = []; - this.cursorState.cursorId = null; - this.cursorState.cursorIndex = 0; - } - } - - // Internal methods - _read() { - if ((this.s && this.s.state === CursorState.CLOSED) || this.isDead()) { - return this.push(null); - } - - // Get the next item - this._next((err, result) => { - if (err) { - if (this.listeners('error') && this.listeners('error').length > 0) { - this.emit('error', err); - } - if (!this.isDead()) this.close(); - - // Emit end event - this.emit('end'); - return this.emit('finish'); - } - - // If we provided a transformation method - if ( - this.cursorState.streamOptions && - typeof this.cursorState.streamOptions.transform === 'function' && - result != null - ) { - return this.push(this.cursorState.streamOptions.transform(result)); - } - - // If we provided a map function - if ( - this.cursorState.transforms && - typeof this.cursorState.transforms.doc === 'function' && - result != null - ) { - return this.push(this.cursorState.transforms.doc(result)); - } - - // Return the result - this.push(result); - - if (result === null && this.isDead()) { - this.once('end', () => { - this.close(); - this.emit('finish'); - }); - } - }); - } - - _endSession(options, callback) { - if (typeof options === 'function') { - callback = options; - options = {}; - } - options = options || {}; - - const session = this.cursorState.session; - - if (session && (options.force || session.owner === this)) { - this.cursorState.session = undefined; - - if (this.operation) { - this.operation.clearSession(); - } - - session.endSession(callback); - return true; - } - - if (callback) { - callback(); - } - - return false; - } - - _getMore(callback) { - if (this.logger.isDebug()) { - this.logger.debug(`schedule getMore call for query [${JSON.stringify(this.query)}]`); - } - - // Set the current batchSize - let batchSize = this.cursorState.batchSize; - if ( - this.cursorState.limit > 0 && - this.cursorState.currentLimit + batchSize > this.cursorState.limit - ) { - batchSize = this.cursorState.limit - this.cursorState.currentLimit; - } - - this.server.getMore(this.ns, this.cursorState, batchSize, this.options, callback); - } - - _initializeCursor(callback) { - const cursor = this; - - // NOTE: this goes away once cursors use `executeOperation` - if (isUnifiedTopology(cursor.topology) && cursor.topology.shouldCheckForSessionSupport()) { - cursor.topology.selectServer(ReadPreference.primaryPreferred, err => { - if (err) { - callback(err); - return; - } - - cursor._next(callback); - }); - - return; - } - - function done(err, result) { - if ( - cursor.cursorState.cursorId && - cursor.cursorState.cursorId.isZero() && - cursor._endSession - ) { - cursor._endSession(); - } - - if ( - cursor.cursorState.documents.length === 0 && - cursor.cursorState.cursorId && - cursor.cursorState.cursorId.isZero() && - !cursor.cmd.tailable && - !cursor.cmd.awaitData - ) { - return setCursorNotified(cursor, callback); - } - - callback(err, result); - } - - const queryCallback = (err, r) => { - if (err) { - return done(err); - } - - const result = r.message; - if (result.queryFailure) { - return done(new MongoError(result.documents[0]), null); - } - - // Check if we have a command cursor - if ( - Array.isArray(result.documents) && - result.documents.length === 1 && - (!cursor.cmd.find || (cursor.cmd.find && cursor.cmd.virtual === false)) && - (typeof result.documents[0].cursor !== 'string' || - result.documents[0]['$err'] || - result.documents[0]['errmsg'] || - Array.isArray(result.documents[0].result)) - ) { - // We have an error document, return the error - if (result.documents[0]['$err'] || result.documents[0]['errmsg']) { - return done(new MongoError(result.documents[0]), null); - } - - // We have a cursor document - if (result.documents[0].cursor != null && typeof result.documents[0].cursor !== 'string') { - const id = result.documents[0].cursor.id; - // If we have a namespace change set the new namespace for getmores - if (result.documents[0].cursor.ns) { - cursor.ns = result.documents[0].cursor.ns; - } - // Promote id to long if needed - cursor.cursorState.cursorId = typeof id === 'number' ? Long.fromNumber(id) : id; - cursor.cursorState.lastCursorId = cursor.cursorState.cursorId; - cursor.cursorState.operationTime = result.documents[0].operationTime; - - // If we have a firstBatch set it - if (Array.isArray(result.documents[0].cursor.firstBatch)) { - cursor.cursorState.documents = result.documents[0].cursor.firstBatch; //.reverse(); - } - - // Return after processing command cursor - return done(null, result); - } - - if (Array.isArray(result.documents[0].result)) { - cursor.cursorState.documents = result.documents[0].result; - cursor.cursorState.cursorId = Long.ZERO; - return done(null, result); - } - } - - // Otherwise fall back to regular find path - const cursorId = result.cursorId || 0; - cursor.cursorState.cursorId = cursorId instanceof Long ? cursorId : Long.fromNumber(cursorId); - cursor.cursorState.documents = result.documents; - cursor.cursorState.lastCursorId = result.cursorId; - - // Transform the results with passed in transformation method if provided - if ( - cursor.cursorState.transforms && - typeof cursor.cursorState.transforms.query === 'function' - ) { - cursor.cursorState.documents = cursor.cursorState.transforms.query(result); - } - - done(null, result); - }; - - if (cursor.operation) { - if (cursor.logger.isDebug()) { - cursor.logger.debug( - `issue initial query [${JSON.stringify(cursor.cmd)}] with flags [${JSON.stringify( - cursor.query - )}]` - ); - } - - executeOperation(cursor.topology, cursor.operation, (err, result) => { - if (err) { - done(err); - return; - } - - cursor.server = cursor.operation.server; - cursor.cursorState.init = true; - - // NOTE: this is a special internal method for cloning a cursor, consider removing - if (cursor.cursorState.cursorId != null) { - return done(); - } - - queryCallback(err, result); - }); - - return; - } - - // Very explicitly choose what is passed to selectServer - const serverSelectOptions = {}; - if (cursor.cursorState.session) { - serverSelectOptions.session = cursor.cursorState.session; - } - - if (cursor.operation) { - serverSelectOptions.readPreference = cursor.operation.readPreference; - } else if (cursor.options.readPreference) { - serverSelectOptions.readPreference = cursor.options.readPreference; - } - - return cursor.topology.selectServer(serverSelectOptions, (err, server) => { - if (err) { - const disconnectHandler = cursor.disconnectHandler; - if (disconnectHandler != null) { - return disconnectHandler.addObjectAndMethod( - 'cursor', - cursor, - 'next', - [callback], - callback - ); - } - - return callback(err); - } - - cursor.server = server; - cursor.cursorState.init = true; - if (collationNotSupported(cursor.server, cursor.cmd)) { - return callback(new MongoError(`server ${cursor.server.name} does not support collation`)); - } - - // NOTE: this is a special internal method for cloning a cursor, consider removing - if (cursor.cursorState.cursorId != null) { - return done(); - } - - if (cursor.logger.isDebug()) { - cursor.logger.debug( - `issue initial query [${JSON.stringify(cursor.cmd)}] with flags [${JSON.stringify( - cursor.query - )}]` - ); - } - - if (cursor.cmd.find != null) { - server.query(cursor.ns, cursor.cmd, cursor.cursorState, cursor.options, queryCallback); - return; - } - - const commandOptions = Object.assign({ session: cursor.cursorState.session }, cursor.options); - server.command(cursor.ns, cursor.cmd, commandOptions, queryCallback); - }); - } -} - -if (SUPPORTS.ASYNC_ITERATOR) { - CoreCursor.prototype[Symbol.asyncIterator] = require('../async/async_iterator').asyncIterator; -} - -/** - * Validate if the pool is dead and return error - */ -function isConnectionDead(self, callback) { - if (self.pool && self.pool.isDestroyed()) { - self.cursorState.killed = true; - const err = new MongoNetworkError( - `connection to host ${self.pool.host}:${self.pool.port} was destroyed` - ); - - _setCursorNotifiedImpl(self, () => callback(err)); - return true; - } - - return false; -} - -/** - * Validate if the cursor is dead but was not explicitly killed by user - */ -function isCursorDeadButNotkilled(self, callback) { - // Cursor is dead but not marked killed, return null - if (self.cursorState.dead && !self.cursorState.killed) { - self.cursorState.killed = true; - setCursorNotified(self, callback); - return true; - } - - return false; -} - -/** - * Validate if the cursor is dead and was killed by user - */ -function isCursorDeadAndKilled(self, callback) { - if (self.cursorState.dead && self.cursorState.killed) { - handleCallback(callback, new MongoError('cursor is dead')); - return true; - } - - return false; -} - -/** - * Validate if the cursor was killed by the user - */ -function isCursorKilled(self, callback) { - if (self.cursorState.killed) { - setCursorNotified(self, callback); - return true; - } - - return false; -} - -/** - * Mark cursor as being dead and notified - */ -function setCursorDeadAndNotified(self, callback) { - self.cursorState.dead = true; - setCursorNotified(self, callback); -} - -/** - * Mark cursor as being notified - */ -function setCursorNotified(self, callback) { - _setCursorNotifiedImpl(self, () => handleCallback(callback, null, null)); -} - -function _setCursorNotifiedImpl(self, callback) { - self.cursorState.notified = true; - self.cursorState.documents = []; - self.cursorState.cursorIndex = 0; - - if (self._endSession) { - self._endSession(undefined, () => callback()); - return; - } - - return callback(); -} - -function nextFunction(self, callback) { - // We have notified about it - if (self.cursorState.notified) { - return callback(new Error('cursor is exhausted')); - } - - // Cursor is killed return null - if (isCursorKilled(self, callback)) return; - - // Cursor is dead but not marked killed, return null - if (isCursorDeadButNotkilled(self, callback)) return; - - // We have a dead and killed cursor, attempting to call next should error - if (isCursorDeadAndKilled(self, callback)) return; - - // We have just started the cursor - if (!self.cursorState.init) { - // Topology is not connected, save the call in the provided store to be - // Executed at some point when the handler deems it's reconnected - if (!self.topology.isConnected(self.options)) { - // Only need this for single server, because repl sets and mongos - // will always continue trying to reconnect - if (self.topology._type === 'server' && !self.topology.s.options.reconnect) { - // Reconnect is disabled, so we'll never reconnect - return callback(new MongoError('no connection available')); - } - - if (self.disconnectHandler != null) { - if (self.topology.isDestroyed()) { - // Topology was destroyed, so don't try to wait for it to reconnect - return callback(new MongoError('Topology was destroyed')); - } - - self.disconnectHandler.addObjectAndMethod('cursor', self, 'next', [callback], callback); - return; - } - } - - self._initializeCursor((err, result) => { - if (err || result === null) { - callback(err, result); - return; - } - - nextFunction(self, callback); - }); - - return; - } - - if (self.cursorState.limit > 0 && self.cursorState.currentLimit >= self.cursorState.limit) { - // Ensure we kill the cursor on the server - self.kill(); - // Set cursor in dead and notified state - return setCursorDeadAndNotified(self, callback); - } else if ( - self.cursorState.cursorIndex === self.cursorState.documents.length && - !Long.ZERO.equals(self.cursorState.cursorId) - ) { - // Ensure an empty cursor state - self.cursorState.documents = []; - self.cursorState.cursorIndex = 0; - - // Check if topology is destroyed - if (self.topology.isDestroyed()) - return callback( - new MongoNetworkError('connection destroyed, not possible to instantiate cursor') - ); - - // Check if connection is dead and return if not possible to - // execute a getMore on this connection - if (isConnectionDead(self, callback)) return; - - // Execute the next get more - self._getMore(function(err, doc, connection) { - if (err) { - if (err instanceof MongoError) { - err[mongoErrorContextSymbol].isGetMore = true; - } - - return handleCallback(callback, err); - } - - if (self.cursorState.cursorId && self.cursorState.cursorId.isZero() && self._endSession) { - self._endSession(); - } - - // Save the returned connection to ensure all getMore's fire over the same connection - self.connection = connection; - - // Tailable cursor getMore result, notify owner about it - // No attempt is made here to retry, this is left to the user of the - // core module to handle to keep core simple - if ( - self.cursorState.documents.length === 0 && - self.cmd.tailable && - Long.ZERO.equals(self.cursorState.cursorId) - ) { - // No more documents in the tailed cursor - return handleCallback( - callback, - new MongoError({ - message: 'No more documents in tailed cursor', - tailable: self.cmd.tailable, - awaitData: self.cmd.awaitData - }) - ); - } else if ( - self.cursorState.documents.length === 0 && - self.cmd.tailable && - !Long.ZERO.equals(self.cursorState.cursorId) - ) { - return nextFunction(self, callback); - } - - if (self.cursorState.limit > 0 && self.cursorState.currentLimit >= self.cursorState.limit) { - return setCursorDeadAndNotified(self, callback); - } - - nextFunction(self, callback); - }); - } else if ( - self.cursorState.documents.length === self.cursorState.cursorIndex && - self.cmd.tailable && - Long.ZERO.equals(self.cursorState.cursorId) - ) { - return handleCallback( - callback, - new MongoError({ - message: 'No more documents in tailed cursor', - tailable: self.cmd.tailable, - awaitData: self.cmd.awaitData - }) - ); - } else if ( - self.cursorState.documents.length === self.cursorState.cursorIndex && - Long.ZERO.equals(self.cursorState.cursorId) - ) { - setCursorDeadAndNotified(self, callback); - } else { - if (self.cursorState.limit > 0 && self.cursorState.currentLimit >= self.cursorState.limit) { - // Ensure we kill the cursor on the server - self.kill(); - // Set cursor in dead and notified state - return setCursorDeadAndNotified(self, callback); - } - - // Increment the current cursor limit - self.cursorState.currentLimit += 1; - - // Get the document - let doc = self.cursorState.documents[self.cursorState.cursorIndex++]; - - // Doc overflow - if (!doc || doc.$err) { - // Ensure we kill the cursor on the server - self.kill(); - // Set cursor in dead and notified state - return setCursorDeadAndNotified(self, function() { - handleCallback(callback, new MongoError(doc ? doc.$err : undefined)); - }); - } - - // Transform the doc with passed in transformation method if provided - if (self.cursorState.transforms && typeof self.cursorState.transforms.doc === 'function') { - doc = self.cursorState.transforms.doc(doc); - } - - // Return the document - handleCallback(callback, null, doc); - } -} - -module.exports = { - CursorState, - CoreCursor -}; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/error.js b/scripts/2.5/node_modules/mongodb/lib/core/error.js deleted file mode 100644 index d35fbbef..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/core/error.js +++ /dev/null @@ -1,237 +0,0 @@ -'use strict'; - -const mongoErrorContextSymbol = Symbol('mongoErrorContextSymbol'); -const maxWireVersion = require('./utils').maxWireVersion; - -/** - * Creates a new MongoError - * - * @augments Error - * @param {Error|string|object} message The error message - * @property {string} message The error message - * @property {string} stack The error call stack - */ -class MongoError extends Error { - constructor(message) { - if (message instanceof Error) { - super(message.message); - this.stack = message.stack; - } else { - if (typeof message === 'string') { - super(message); - } else { - super(message.message || message.errmsg || message.$err || 'n/a'); - for (var name in message) { - this[name] = message[name]; - } - } - - Error.captureStackTrace(this, this.constructor); - } - - this.name = 'MongoError'; - this[mongoErrorContextSymbol] = this[mongoErrorContextSymbol] || {}; - } - - /** - * Creates a new MongoError object - * - * @param {Error|string|object} options The options used to create the error. - * @return {MongoError} A MongoError instance - * @deprecated Use `new MongoError()` instead. - */ - static create(options) { - return new MongoError(options); - } - - hasErrorLabel(label) { - return this.errorLabels && this.errorLabels.indexOf(label) !== -1; - } -} - -/** - * Creates a new MongoNetworkError - * - * @param {Error|string|object} message The error message - * @property {string} message The error message - * @property {string} stack The error call stack - */ -class MongoNetworkError extends MongoError { - constructor(message) { - super(message); - this.name = 'MongoNetworkError'; - - // This is added as part of the transactions specification - this.errorLabels = ['TransientTransactionError']; - } -} - -/** - * An error used when attempting to parse a value (like a connection string) - * - * @param {Error|string|object} message The error message - * @property {string} message The error message - */ -class MongoParseError extends MongoError { - constructor(message) { - super(message); - this.name = 'MongoParseError'; - } -} - -/** - * An error signifying a timeout event - * - * @param {Error|string|object} message The error message - * @param {string|object} [reason] The reason the timeout occured - * @property {string} message The error message - * @property {string} [reason] An optional reason context for the timeout, generally an error saved during flow of monitoring and selecting servers - */ -class MongoTimeoutError extends MongoError { - constructor(message, reason) { - super(message); - this.name = 'MongoTimeoutError'; - if (reason != null) { - this.reason = reason; - } - } -} - -function makeWriteConcernResultObject(input) { - const output = Object.assign({}, input); - - if (output.ok === 0) { - output.ok = 1; - delete output.errmsg; - delete output.code; - delete output.codeName; - } - - return output; -} - -/** - * An error thrown when the server reports a writeConcernError - * - * @param {Error|string|object} message The error message - * @param {object} result The result document (provided if ok: 1) - * @property {string} message The error message - * @property {object} [result] The result document (provided if ok: 1) - */ -class MongoWriteConcernError extends MongoError { - constructor(message, result) { - super(message); - this.name = 'MongoWriteConcernError'; - - if (result != null) { - this.result = makeWriteConcernResultObject(result); - } - } -} - -// see: https://github.com/mongodb/specifications/blob/master/source/retryable-writes/retryable-writes.rst#terms -const RETRYABLE_ERROR_CODES = new Set([ - 6, // HostUnreachable - 7, // HostNotFound - 89, // NetworkTimeout - 91, // ShutdownInProgress - 189, // PrimarySteppedDown - 9001, // SocketException - 10107, // NotMaster - 11600, // InterruptedAtShutdown - 11602, // InterruptedDueToReplStateChange - 13435, // NotMasterNoSlaveOk - 13436 // NotMasterOrSecondary -]); - -/** - * Determines whether an error is something the driver should attempt to retry - * - * @param {MongoError|Error} error - */ -function isRetryableError(error) { - return ( - RETRYABLE_ERROR_CODES.has(error.code) || - error instanceof MongoNetworkError || - error.message.match(/not master/) || - error.message.match(/node is recovering/) - ); -} - -const SDAM_RECOVERING_CODES = new Set([ - 91, // ShutdownInProgress - 189, // PrimarySteppedDown - 11600, // InterruptedAtShutdown - 11602, // InterruptedDueToReplStateChange - 13436 // NotMasterOrSecondary -]); - -const SDAM_NOTMASTER_CODES = new Set([ - 10107, // NotMaster - 13435 // NotMasterNoSlaveOk -]); - -const SDAM_NODE_SHUTTING_DOWN_ERROR_CODES = new Set([ - 11600, // InterruptedAtShutdown - 91 // ShutdownInProgress -]); - -function isRecoveringError(err) { - if (err.code && SDAM_RECOVERING_CODES.has(err.code)) { - return true; - } - - return err.message.match(/not master or secondary/) || err.message.match(/node is recovering/); -} - -function isNotMasterError(err) { - if (err.code && SDAM_NOTMASTER_CODES.has(err.code)) { - return true; - } - - if (isRecoveringError(err)) { - return false; - } - - return err.message.match(/not master/); -} - -function isNodeShuttingDownError(err) { - return err.code && SDAM_NODE_SHUTTING_DOWN_ERROR_CODES.has(err.code); -} - -/** - * Determines whether SDAM can recover from a given error. If it cannot - * then the pool will be cleared, and server state will completely reset - * locally. - * - * @see https://github.com/mongodb/specifications/blob/master/source/server-discovery-and-monitoring/server-discovery-and-monitoring.rst#not-master-and-node-is-recovering - * @param {MongoError|Error} error - * @param {Server} server - */ -function isSDAMUnrecoverableError(error, server) { - if (error instanceof MongoParseError) { - return true; - } - - if (isRecoveringError(error) || isNotMasterError(error)) { - if (maxWireVersion(server) >= 8 && !isNodeShuttingDownError(error)) { - return false; - } - - return true; - } - - return false; -} - -module.exports = { - MongoError, - MongoNetworkError, - MongoParseError, - MongoTimeoutError, - MongoWriteConcernError, - mongoErrorContextSymbol, - isRetryableError, - isSDAMUnrecoverableError -}; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/index.js b/scripts/2.5/node_modules/mongodb/lib/core/index.js deleted file mode 100644 index 8d1ca8f5..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/core/index.js +++ /dev/null @@ -1,50 +0,0 @@ -'use strict'; - -let BSON = require('bson'); -const require_optional = require('require_optional'); -const EJSON = require('./utils').retrieveEJSON(); - -try { - // Attempt to grab the native BSON parser - const BSONNative = require_optional('bson-ext'); - // If we got the native parser, use it instead of the - // Javascript one - if (BSONNative) { - BSON = BSONNative; - } -} catch (err) {} // eslint-disable-line - -module.exports = { - // Errors - MongoError: require('./error').MongoError, - MongoNetworkError: require('./error').MongoNetworkError, - MongoParseError: require('./error').MongoParseError, - MongoTimeoutError: require('./error').MongoTimeoutError, - MongoWriteConcernError: require('./error').MongoWriteConcernError, - mongoErrorContextSymbol: require('./error').mongoErrorContextSymbol, - // Core - Connection: require('./connection/connection'), - Server: require('./topologies/server'), - ReplSet: require('./topologies/replset'), - Mongos: require('./topologies/mongos'), - Logger: require('./connection/logger'), - Cursor: require('./cursor').CoreCursor, - ReadPreference: require('./topologies/read_preference'), - Sessions: require('./sessions'), - BSON: BSON, - EJSON: EJSON, - Topology: require('./sdam/topology'), - // Raw operations - Query: require('./connection/commands').Query, - // Auth mechanisms - MongoCredentials: require('./auth/mongo_credentials').MongoCredentials, - defaultAuthProviders: require('./auth/defaultAuthProviders').defaultAuthProviders, - MongoCR: require('./auth/mongocr'), - X509: require('./auth/x509'), - Plain: require('./auth/plain'), - GSSAPI: require('./auth/gssapi'), - ScramSHA1: require('./auth/scram').ScramSHA1, - ScramSHA256: require('./auth/scram').ScramSHA256, - // Utilities - parseConnectionString: require('./uri_parser') -}; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/sdam/monitoring.js b/scripts/2.5/node_modules/mongodb/lib/core/sdam/monitoring.js deleted file mode 100644 index 15f081c8..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/core/sdam/monitoring.js +++ /dev/null @@ -1,235 +0,0 @@ -'use strict'; - -const ServerDescription = require('./server_description').ServerDescription; -const calculateDurationInMs = require('../utils').calculateDurationInMs; - -// pulled from `Server` implementation -const STATE_DISCONNECTED = 'disconnected'; -const STATE_DISCONNECTING = 'disconnecting'; - -/** - * Published when server description changes, but does NOT include changes to the RTT. - * - * @property {Object} topologyId A unique identifier for the topology - * @property {ServerAddress} address The address (host/port pair) of the server - * @property {ServerDescription} previousDescription The previous server description - * @property {ServerDescription} newDescription The new server description - */ -class ServerDescriptionChangedEvent { - constructor(topologyId, address, previousDescription, newDescription) { - Object.assign(this, { topologyId, address, previousDescription, newDescription }); - } -} - -/** - * Published when server is initialized. - * - * @property {Object} topologyId A unique identifier for the topology - * @property {ServerAddress} address The address (host/port pair) of the server - */ -class ServerOpeningEvent { - constructor(topologyId, address) { - Object.assign(this, { topologyId, address }); - } -} - -/** - * Published when server is closed. - * - * @property {ServerAddress} address The address (host/port pair) of the server - * @property {Object} topologyId A unique identifier for the topology - */ -class ServerClosedEvent { - constructor(topologyId, address) { - Object.assign(this, { topologyId, address }); - } -} - -/** - * Published when topology description changes. - * - * @property {Object} topologyId - * @property {TopologyDescription} previousDescription The old topology description - * @property {TopologyDescription} newDescription The new topology description - */ -class TopologyDescriptionChangedEvent { - constructor(topologyId, previousDescription, newDescription) { - Object.assign(this, { topologyId, previousDescription, newDescription }); - } -} - -/** - * Published when topology is initialized. - * - * @param {Object} topologyId A unique identifier for the topology - */ -class TopologyOpeningEvent { - constructor(topologyId) { - Object.assign(this, { topologyId }); - } -} - -/** - * Published when topology is closed. - * - * @param {Object} topologyId A unique identifier for the topology - */ -class TopologyClosedEvent { - constructor(topologyId) { - Object.assign(this, { topologyId }); - } -} - -/** - * Fired when the server monitor’s ismaster command is started - immediately before - * the ismaster command is serialized into raw BSON and written to the socket. - * - * @property {Object} connectionId The connection id for the command - */ -class ServerHeartbeatStartedEvent { - constructor(connectionId) { - Object.assign(this, { connectionId }); - } -} - -/** - * Fired when the server monitor’s ismaster succeeds. - * - * @param {Number} duration The execution time of the event in ms - * @param {Object} reply The command reply - * @param {Object} connectionId The connection id for the command - */ -class ServerHeartbeatSucceededEvent { - constructor(duration, reply, connectionId) { - Object.assign(this, { duration, reply, connectionId }); - } -} - -/** - * Fired when the server monitor’s ismaster fails, either with an “ok: 0” or a socket exception. - * - * @param {Number} duration The execution time of the event in ms - * @param {MongoError|Object} failure The command failure - * @param {Object} connectionId The connection id for the command - */ -class ServerHeartbeatFailedEvent { - constructor(duration, failure, connectionId) { - Object.assign(this, { duration, failure, connectionId }); - } -} - -/** - * Performs a server check as described by the SDAM spec. - * - * NOTE: This method automatically reschedules itself, so that there is always an active - * monitoring process - * - * @param {Server} server The server to monitor - */ -function monitorServer(server, options) { - options = options || {}; - const heartbeatFrequencyMS = options.heartbeatFrequencyMS || 10000; - - if (options.initial === true) { - server.s.monitorId = setTimeout(() => monitorServer(server), heartbeatFrequencyMS); - return; - } - - // executes a single check of a server - const checkServer = callback => { - let start = process.hrtime(); - - // emit a signal indicating we have started the heartbeat - server.emit('serverHeartbeatStarted', new ServerHeartbeatStartedEvent(server.name)); - - // NOTE: legacy monitoring event - process.nextTick(() => server.emit('monitoring', server)); - - server.command( - 'admin.$cmd', - { ismaster: true }, - { - monitoring: true, - socketTimeout: server.s.options.connectionTimeout || 2000 - }, - (err, result) => { - let duration = calculateDurationInMs(start); - - if (err) { - server.emit( - 'serverHeartbeatFailed', - new ServerHeartbeatFailedEvent(duration, err, server.name) - ); - - return callback(err, null); - } - - const isMaster = result.result; - server.emit( - 'serverHeartbeatSucceeded', - new ServerHeartbeatSucceededEvent(duration, isMaster, server.name) - ); - - return callback(null, isMaster); - } - ); - }; - - const successHandler = isMaster => { - server.s.monitoring = false; - - // emit an event indicating that our description has changed - server.emit('descriptionReceived', new ServerDescription(server.description.address, isMaster)); - if (server.s.state === STATE_DISCONNECTED || server.s.state === STATE_DISCONNECTING) { - return; - } - - // schedule the next monitoring process - server.s.monitorId = setTimeout(() => monitorServer(server), heartbeatFrequencyMS); - }; - - // run the actual monitoring loop - server.s.monitoring = true; - checkServer((err, isMaster) => { - if (!err) { - successHandler(isMaster); - return; - } - - // According to the SDAM specification's "Network error during server check" section, if - // an ismaster call fails we reset the server's pool. If a server was once connected, - // change its type to `Unknown` only after retrying once. - server.s.pool.reset(() => { - // otherwise re-attempt monitoring once - checkServer((error, isMaster) => { - if (error) { - server.s.monitoring = false; - - // we revert to an `Unknown` by emitting a default description with no isMaster - server.emit( - 'descriptionReceived', - new ServerDescription(server.description.address, null, { error }) - ); - - // we do not reschedule monitoring in this case - return; - } - - successHandler(isMaster); - }); - }); - }); -} - -module.exports = { - ServerDescriptionChangedEvent, - ServerOpeningEvent, - ServerClosedEvent, - TopologyDescriptionChangedEvent, - TopologyOpeningEvent, - TopologyClosedEvent, - ServerHeartbeatStartedEvent, - ServerHeartbeatSucceededEvent, - ServerHeartbeatFailedEvent, - monitorServer -}; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/sdam/server.js b/scripts/2.5/node_modules/mongodb/lib/core/sdam/server.js deleted file mode 100644 index abb1570a..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/core/sdam/server.js +++ /dev/null @@ -1,511 +0,0 @@ -'use strict'; -const EventEmitter = require('events'); -const MongoError = require('../error').MongoError; -const Pool = require('../connection/pool'); -const relayEvents = require('../utils').relayEvents; -const wireProtocol = require('../wireprotocol'); -const BSON = require('../connection/utils').retrieveBSON(); -const createClientInfo = require('../topologies/shared').createClientInfo; -const Logger = require('../connection/logger'); -const ServerDescription = require('./server_description').ServerDescription; -const ReadPreference = require('../topologies/read_preference'); -const monitorServer = require('./monitoring').monitorServer; -const MongoParseError = require('../error').MongoParseError; -const MongoNetworkError = require('../error').MongoNetworkError; -const collationNotSupported = require('../utils').collationNotSupported; -const debugOptions = require('../connection/utils').debugOptions; -const isSDAMUnrecoverableError = require('../error').isSDAMUnrecoverableError; - -// Used for filtering out fields for logging -const DEBUG_FIELDS = [ - 'reconnect', - 'reconnectTries', - 'reconnectInterval', - 'emitError', - 'cursorFactory', - 'host', - 'port', - 'size', - 'keepAlive', - 'keepAliveInitialDelay', - 'noDelay', - 'connectionTimeout', - 'checkServerIdentity', - 'socketTimeout', - 'ssl', - 'ca', - 'crl', - 'cert', - 'key', - 'rejectUnauthorized', - 'promoteLongs', - 'promoteValues', - 'promoteBuffers', - 'servername' -]; - -const STATE_DISCONNECTING = 'disconnecting'; -const STATE_DISCONNECTED = 'disconnected'; -const STATE_CONNECTING = 'connecting'; -const STATE_CONNECTED = 'connected'; - -/** - * - * @fires Server#serverHeartbeatStarted - * @fires Server#serverHeartbeatSucceeded - * @fires Server#serverHeartbeatFailed - */ -class Server extends EventEmitter { - /** - * Create a server - * - * @param {ServerDescription} description - * @param {Object} options - */ - constructor(description, options, topology) { - super(); - - this.s = { - // the server description - description, - // a saved copy of the incoming options - options, - // the server logger - logger: Logger('Server', options), - // the bson parser - bson: - options.bson || - new BSON([ - BSON.Binary, - BSON.Code, - BSON.DBRef, - BSON.Decimal128, - BSON.Double, - BSON.Int32, - BSON.Long, - BSON.Map, - BSON.MaxKey, - BSON.MinKey, - BSON.ObjectId, - BSON.BSONRegExp, - BSON.Symbol, - BSON.Timestamp - ]), - // client metadata for the initial handshake - clientInfo: createClientInfo(options), - // state variable to determine if there is an active server check in progress - monitoring: false, - // the implementation of the monitoring method - monitorFunction: options.monitorFunction || monitorServer, - // the connection pool - pool: null, - // the server state - state: STATE_DISCONNECTED, - credentials: options.credentials, - topology - }; - } - - get description() { - return this.s.description; - } - - get name() { - return this.s.description.address; - } - - get autoEncrypter() { - if (this.s.options && this.s.options.autoEncrypter) { - return this.s.options.autoEncrypter; - } - return null; - } - - /** - * Initiate server connect - */ - connect(options) { - options = options || {}; - - // do not allow connect to be called on anything that's not disconnected - if (this.s.pool && !this.s.pool.isDisconnected() && !this.s.pool.isDestroyed()) { - throw new MongoError(`Server instance in invalid state ${this.s.pool.state}`); - } - - // create a pool - const addressParts = this.description.address.split(':'); - const poolOptions = Object.assign( - { host: addressParts[0], port: parseInt(addressParts[1], 10) }, - this.s.options, - options, - { bson: this.s.bson } - ); - - // NOTE: this should only be the case if we are connecting to a single server - poolOptions.reconnect = true; - poolOptions.legacyCompatMode = false; - - this.s.pool = new Pool(this, poolOptions); - - // setup listeners - this.s.pool.on('connect', connectEventHandler(this)); - this.s.pool.on('close', errorEventHandler(this)); - this.s.pool.on('error', errorEventHandler(this)); - this.s.pool.on('parseError', parseErrorEventHandler(this)); - - // it is unclear whether consumers should even know about these events - // this.s.pool.on('timeout', timeoutEventHandler(this)); - // this.s.pool.on('reconnect', reconnectEventHandler(this)); - // this.s.pool.on('reconnectFailed', errorEventHandler(this)); - - // relay all command monitoring events - relayEvents(this.s.pool, this, ['commandStarted', 'commandSucceeded', 'commandFailed']); - - this.s.state = STATE_CONNECTING; - - // If auth settings have been provided, use them - if (options.auth) { - this.s.pool.connect.apply(this.s.pool, options.auth); - return; - } - - this.s.pool.connect(); - } - - /** - * Destroy the server connection - * - * @param {Boolean} [options.force=false] Force destroy the pool - */ - destroy(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = Object.assign({}, { force: false }, options); - - this.s.state = STATE_DISCONNECTING; - const done = err => { - this.emit('closed'); - this.s.state = STATE_DISCONNECTED; - if (typeof callback === 'function') { - callback(err, null); - } - }; - - if (!this.s.pool) { - return done(); - } - - ['close', 'error', 'timeout', 'parseError', 'connect'].forEach(event => { - this.s.pool.removeAllListeners(event); - }); - - if (this.s.monitorId) { - clearTimeout(this.s.monitorId); - } - - this.s.pool.destroy(options.force, done); - } - - /** - * Immediately schedule monitoring of this server. If there already an attempt being made - * this will be a no-op. - */ - monitor(options) { - options = options || {}; - if (this.s.state !== STATE_CONNECTED || this.s.monitoring) return; - if (this.s.monitorId) clearTimeout(this.s.monitorId); - this.s.monitorFunction(this, options); - } - - /** - * Execute a command - * - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object} cmd The command hash - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.checkKeys=false] Specify if the bson parser should validate keys. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {Boolean} [options.fullResult=false] Return the full envelope instead of just the result document. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {opResultCallback} callback A callback function - */ - command(ns, cmd, options, callback) { - if (typeof options === 'function') { - (callback = options), (options = {}), (options = options || {}); - } - - const error = basicReadValidations(this, options); - if (error) { - return callback(error, null); - } - - // Clone the options - options = Object.assign({}, options, { wireProtocolCommand: false }); - - // Debug log - if (this.s.logger.isDebug()) { - this.s.logger.debug( - `executing command [${JSON.stringify({ - ns, - cmd, - options: debugOptions(DEBUG_FIELDS, options) - })}] against ${this.name}` - ); - } - - // error if collation not supported - if (collationNotSupported(this, cmd)) { - callback(new MongoError(`server ${this.name} does not support collation`)); - return; - } - - wireProtocol.command(this, ns, cmd, options, (err, result) => { - if (err) { - if (options.session && err instanceof MongoNetworkError) { - options.session.serverSession.isDirty = true; - } - - if (isSDAMUnrecoverableError(err, this)) { - this.emit('error', err); - } - } - - callback(err, result); - }); - } - - /** - * Execute a query against the server - * - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object} cmd The command document for the query - * @param {object} options Optional settings - * @param {function} callback - */ - query(ns, cmd, cursorState, options, callback) { - wireProtocol.query(this, ns, cmd, cursorState, options, (err, result) => { - if (err) { - if (options.session && err instanceof MongoNetworkError) { - options.session.serverSession.isDirty = true; - } - - if (isSDAMUnrecoverableError(err, this)) { - this.emit('error', err); - } - } - - callback(err, result); - }); - } - - /** - * Execute a `getMore` against the server - * - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object} cursorState State data associated with the cursor calling this method - * @param {object} options Optional settings - * @param {function} callback - */ - getMore(ns, cursorState, batchSize, options, callback) { - wireProtocol.getMore(this, ns, cursorState, batchSize, options, (err, result) => { - if (err) { - if (options.session && err instanceof MongoNetworkError) { - options.session.serverSession.isDirty = true; - } - - if (isSDAMUnrecoverableError(err, this)) { - this.emit('error', err); - } - } - - callback(err, result); - }); - } - - /** - * Execute a `killCursors` command against the server - * - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object} cursorState State data associated with the cursor calling this method - * @param {function} callback - */ - killCursors(ns, cursorState, callback) { - wireProtocol.killCursors(this, ns, cursorState, (err, result) => { - if (err && isSDAMUnrecoverableError(err, this)) { - this.emit('error', err); - } - - if (typeof callback === 'function') { - callback(err, result); - } - }); - } - - /** - * Insert one or more documents - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of documents to insert - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {opResultCallback} callback A callback function - */ - insert(ns, ops, options, callback) { - executeWriteOperation({ server: this, op: 'insert', ns, ops }, options, callback); - } - - /** - * Perform one or more update operations - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of updates - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {opResultCallback} callback A callback function - */ - update(ns, ops, options, callback) { - executeWriteOperation({ server: this, op: 'update', ns, ops }, options, callback); - } - - /** - * Perform one or more remove operations - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of removes - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {opResultCallback} callback A callback function - */ - remove(ns, ops, options, callback) { - executeWriteOperation({ server: this, op: 'remove', ns, ops }, options, callback); - } -} - -Object.defineProperty(Server.prototype, 'clusterTime', { - get: function() { - return this.s.topology.clusterTime; - }, - set: function(clusterTime) { - this.s.topology.clusterTime = clusterTime; - } -}); - -function basicWriteValidations(server) { - if (!server.s.pool) { - return new MongoError('server instance is not connected'); - } - - if (server.s.pool.isDestroyed()) { - return new MongoError('server instance pool was destroyed'); - } - - return null; -} - -function basicReadValidations(server, options) { - const error = basicWriteValidations(server, options); - if (error) { - return error; - } - - if (options.readPreference && !(options.readPreference instanceof ReadPreference)) { - return new MongoError('readPreference must be an instance of ReadPreference'); - } -} - -function executeWriteOperation(args, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // TODO: once we drop Node 4, use destructuring either here or in arguments. - const server = args.server; - const op = args.op; - const ns = args.ns; - const ops = Array.isArray(args.ops) ? args.ops : [args.ops]; - - const error = basicWriteValidations(server, options); - if (error) { - callback(error, null); - return; - } - - if (collationNotSupported(server, options)) { - callback(new MongoError(`server ${server.name} does not support collation`)); - return; - } - - return wireProtocol[op](server, ns, ops, options, (err, result) => { - if (err) { - if (options.session && err instanceof MongoNetworkError) { - options.session.serverSession.isDirty = true; - } - - if (isSDAMUnrecoverableError(err, server)) { - server.emit('error', err); - } - } - - callback(err, result); - }); -} - -function connectEventHandler(server) { - return function(pool, conn) { - const ismaster = conn.ismaster; - server.s.lastIsMasterMS = conn.lastIsMasterMS; - if (conn.agreedCompressor) { - server.s.pool.options.agreedCompressor = conn.agreedCompressor; - } - - if (conn.zlibCompressionLevel) { - server.s.pool.options.zlibCompressionLevel = conn.zlibCompressionLevel; - } - - if (conn.ismaster.$clusterTime) { - const $clusterTime = conn.ismaster.$clusterTime; - server.s.sclusterTime = $clusterTime; - } - - // log the connection event if requested - if (server.s.logger.isInfo()) { - server.s.logger.info( - `server ${server.name} connected with ismaster [${JSON.stringify(ismaster)}]` - ); - } - - // emit an event indicating that our description has changed - server.emit('descriptionReceived', new ServerDescription(server.description.address, ismaster)); - - // we are connected and handshaked (guaranteed by the pool) - server.s.state = STATE_CONNECTED; - server.emit('connect', server); - }; -} - -function errorEventHandler(server) { - return function(err) { - if (err) { - server.emit('error', new MongoNetworkError(err)); - } - - server.emit('close'); - }; -} - -function parseErrorEventHandler(server) { - return function(err) { - server.s.state = STATE_DISCONNECTED; - server.emit('error', new MongoParseError(err)); - }; -} - -module.exports = Server; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/sdam/server_description.js b/scripts/2.5/node_modules/mongodb/lib/core/sdam/server_description.js deleted file mode 100644 index 41a5cf5b..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/core/sdam/server_description.js +++ /dev/null @@ -1,163 +0,0 @@ -'use strict'; - -// An enumeration of server types we know about -const ServerType = { - Standalone: 'Standalone', - Mongos: 'Mongos', - PossiblePrimary: 'PossiblePrimary', - RSPrimary: 'RSPrimary', - RSSecondary: 'RSSecondary', - RSArbiter: 'RSArbiter', - RSOther: 'RSOther', - RSGhost: 'RSGhost', - Unknown: 'Unknown' -}; - -const WRITABLE_SERVER_TYPES = new Set([ - ServerType.RSPrimary, - ServerType.Standalone, - ServerType.Mongos -]); - -const DATA_BEARING_SERVER_TYPES = new Set([ - ServerType.RSPrimary, - ServerType.RSSecondary, - ServerType.Mongos, - ServerType.Standalone -]); - -const ISMASTER_FIELDS = [ - 'minWireVersion', - 'maxWireVersion', - 'maxBsonObjectSize', - 'maxMessageSizeBytes', - 'maxWriteBatchSize', - 'compression', - 'me', - 'hosts', - 'passives', - 'arbiters', - 'tags', - 'setName', - 'setVersion', - 'electionId', - 'primary', - 'logicalSessionTimeoutMinutes', - 'saslSupportedMechs', - '__nodejs_mock_server__', - '$clusterTime' -]; - -/** - * The client's view of a single server, based on the most recent ismaster outcome. - * - * Internal type, not meant to be directly instantiated - */ -class ServerDescription { - /** - * Create a ServerDescription - * @param {String} address The address of the server - * @param {Object} [ismaster] An optional ismaster response for this server - * @param {Object} [options] Optional settings - * @param {Number} [options.roundTripTime] The round trip time to ping this server (in ms) - */ - constructor(address, ismaster, options) { - options = options || {}; - ismaster = Object.assign( - { - minWireVersion: 0, - maxWireVersion: 0, - hosts: [], - passives: [], - arbiters: [], - tags: [] - }, - ismaster - ); - - this.address = address; - this.error = options.error || null; - this.roundTripTime = options.roundTripTime || 0; - this.lastUpdateTime = Date.now(); - this.lastWriteDate = ismaster.lastWrite ? ismaster.lastWrite.lastWriteDate : null; - this.opTime = ismaster.lastWrite ? ismaster.lastWrite.opTime : null; - this.type = parseServerType(ismaster); - - // direct mappings - ISMASTER_FIELDS.forEach(field => { - if (typeof ismaster[field] !== 'undefined') this[field] = ismaster[field]; - }); - - // normalize case for hosts - if (this.me) this.me = this.me.toLowerCase(); - this.hosts = this.hosts.map(host => host.toLowerCase()); - this.passives = this.passives.map(host => host.toLowerCase()); - this.arbiters = this.arbiters.map(host => host.toLowerCase()); - } - - get allHosts() { - return this.hosts.concat(this.arbiters).concat(this.passives); - } - - /** - * @return {Boolean} Is this server available for reads - */ - get isReadable() { - return this.type === ServerType.RSSecondary || this.isWritable; - } - - /** - * @return {Boolean} Is this server data bearing - */ - get isDataBearing() { - return DATA_BEARING_SERVER_TYPES.has(this.type); - } - - /** - * @return {Boolean} Is this server available for writes - */ - get isWritable() { - return WRITABLE_SERVER_TYPES.has(this.type); - } -} - -/** - * Parses an `ismaster` message and determines the server type - * - * @param {Object} ismaster The `ismaster` message to parse - * @return {ServerType} - */ -function parseServerType(ismaster) { - if (!ismaster || !ismaster.ok) { - return ServerType.Unknown; - } - - if (ismaster.isreplicaset) { - return ServerType.RSGhost; - } - - if (ismaster.msg && ismaster.msg === 'isdbgrid') { - return ServerType.Mongos; - } - - if (ismaster.setName) { - if (ismaster.hidden) { - return ServerType.RSOther; - } else if (ismaster.ismaster) { - return ServerType.RSPrimary; - } else if (ismaster.secondary) { - return ServerType.RSSecondary; - } else if (ismaster.arbiterOnly) { - return ServerType.RSArbiter; - } else { - return ServerType.RSOther; - } - } - - return ServerType.Standalone; -} - -module.exports = { - ServerDescription, - ServerType -}; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/sdam/server_selectors.js b/scripts/2.5/node_modules/mongodb/lib/core/sdam/server_selectors.js deleted file mode 100644 index f26d419e..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/core/sdam/server_selectors.js +++ /dev/null @@ -1,244 +0,0 @@ -'use strict'; -const ServerType = require('./server_description').ServerType; -const TopologyType = require('./topology_description').TopologyType; -const ReadPreference = require('../topologies/read_preference'); -const MongoError = require('../error').MongoError; - -// max staleness constants -const IDLE_WRITE_PERIOD = 10000; -const SMALLEST_MAX_STALENESS_SECONDS = 90; - -/** - * Returns a server selector that selects for writable servers - */ -function writableServerSelector() { - return function(topologyDescription, servers) { - return latencyWindowReducer(topologyDescription, servers.filter(s => s.isWritable)); - }; -} - -/** - * Reduces the passed in array of servers by the rules of the "Max Staleness" specification - * found here: https://github.com/mongodb/specifications/blob/master/source/max-staleness/max-staleness.rst - * - * @param {ReadPreference} readPreference The read preference providing max staleness guidance - * @param {topologyDescription} topologyDescription The topology description - * @param {ServerDescription[]} servers The list of server descriptions to be reduced - * @return {ServerDescription[]} The list of servers that satisfy the requirements of max staleness - */ -function maxStalenessReducer(readPreference, topologyDescription, servers) { - if (readPreference.maxStalenessSeconds == null || readPreference.maxStalenessSeconds < 0) { - return servers; - } - - const maxStaleness = readPreference.maxStalenessSeconds; - const maxStalenessVariance = - (topologyDescription.heartbeatFrequencyMS + IDLE_WRITE_PERIOD) / 1000; - if (maxStaleness < maxStalenessVariance) { - throw new MongoError(`maxStalenessSeconds must be at least ${maxStalenessVariance} seconds`); - } - - if (maxStaleness < SMALLEST_MAX_STALENESS_SECONDS) { - throw new MongoError( - `maxStalenessSeconds must be at least ${SMALLEST_MAX_STALENESS_SECONDS} seconds` - ); - } - - if (topologyDescription.type === TopologyType.ReplicaSetWithPrimary) { - const primary = servers.filter(primaryFilter)[0]; - return servers.reduce((result, server) => { - const stalenessMS = - server.lastUpdateTime - - server.lastWriteDate - - (primary.lastUpdateTime - primary.lastWriteDate) + - topologyDescription.heartbeatFrequencyMS; - - const staleness = stalenessMS / 1000; - if (staleness <= readPreference.maxStalenessSeconds) result.push(server); - return result; - }, []); - } else if (topologyDescription.type === TopologyType.ReplicaSetNoPrimary) { - const sMax = servers.reduce((max, s) => (s.lastWriteDate > max.lastWriteDate ? s : max)); - return servers.reduce((result, server) => { - const stalenessMS = - sMax.lastWriteDate - server.lastWriteDate + topologyDescription.heartbeatFrequencyMS; - - const staleness = stalenessMS / 1000; - if (staleness <= readPreference.maxStalenessSeconds) result.push(server); - return result; - }, []); - } - - return servers; -} - -/** - * Determines whether a server's tags match a given set of tags - * - * @param {String[]} tagSet The requested tag set to match - * @param {String[]} serverTags The server's tags - */ -function tagSetMatch(tagSet, serverTags) { - const keys = Object.keys(tagSet); - const serverTagKeys = Object.keys(serverTags); - for (let i = 0; i < keys.length; ++i) { - const key = keys[i]; - if (serverTagKeys.indexOf(key) === -1 || serverTags[key] !== tagSet[key]) { - return false; - } - } - - return true; -} - -/** - * Reduces a set of server descriptions based on tags requested by the read preference - * - * @param {ReadPreference} readPreference The read preference providing the requested tags - * @param {ServerDescription[]} servers The list of server descriptions to reduce - * @return {ServerDescription[]} The list of servers matching the requested tags - */ -function tagSetReducer(readPreference, servers) { - if ( - readPreference.tags == null || - (Array.isArray(readPreference.tags) && readPreference.tags.length === 0) - ) { - return servers; - } - - for (let i = 0; i < readPreference.tags.length; ++i) { - const tagSet = readPreference.tags[i]; - const serversMatchingTagset = servers.reduce((matched, server) => { - if (tagSetMatch(tagSet, server.tags)) matched.push(server); - return matched; - }, []); - - if (serversMatchingTagset.length) { - return serversMatchingTagset; - } - } - - return []; -} - -/** - * Reduces a list of servers to ensure they fall within an acceptable latency window. This is - * further specified in the "Server Selection" specification, found here: - * https://github.com/mongodb/specifications/blob/master/source/server-selection/server-selection.rst - * - * @param {topologyDescription} topologyDescription The topology description - * @param {ServerDescription[]} servers The list of servers to reduce - * @returns {ServerDescription[]} The servers which fall within an acceptable latency window - */ -function latencyWindowReducer(topologyDescription, servers) { - const low = servers.reduce( - (min, server) => (min === -1 ? server.roundTripTime : Math.min(server.roundTripTime, min)), - -1 - ); - - const high = low + topologyDescription.localThresholdMS; - - return servers.reduce((result, server) => { - if (server.roundTripTime <= high && server.roundTripTime >= low) result.push(server); - return result; - }, []); -} - -// filters -function primaryFilter(server) { - return server.type === ServerType.RSPrimary; -} - -function secondaryFilter(server) { - return server.type === ServerType.RSSecondary; -} - -function nearestFilter(server) { - return server.type === ServerType.RSSecondary || server.type === ServerType.RSPrimary; -} - -function knownFilter(server) { - return server.type !== ServerType.Unknown; -} - -/** - * Returns a function which selects servers based on a provided read preference - * - * @param {ReadPreference} readPreference The read preference to select with - */ -function readPreferenceServerSelector(readPreference) { - if (!readPreference.isValid()) { - throw new TypeError('Invalid read preference specified'); - } - - return function(topologyDescription, servers) { - const commonWireVersion = topologyDescription.commonWireVersion; - if ( - commonWireVersion && - (readPreference.minWireVersion && readPreference.minWireVersion > commonWireVersion) - ) { - throw new MongoError( - `Minimum wire version '${ - readPreference.minWireVersion - }' required, but found '${commonWireVersion}'` - ); - } - - if ( - topologyDescription.type === TopologyType.Single || - topologyDescription.type === TopologyType.Sharded - ) { - return latencyWindowReducer(topologyDescription, servers.filter(knownFilter)); - } - - if (readPreference.mode === ReadPreference.PRIMARY) { - return servers.filter(primaryFilter); - } - - if (readPreference.mode === ReadPreference.SECONDARY) { - return latencyWindowReducer( - topologyDescription, - tagSetReducer( - readPreference, - maxStalenessReducer(readPreference, topologyDescription, servers) - ) - ).filter(secondaryFilter); - } else if (readPreference.mode === ReadPreference.NEAREST) { - return latencyWindowReducer( - topologyDescription, - tagSetReducer( - readPreference, - maxStalenessReducer(readPreference, topologyDescription, servers) - ) - ).filter(nearestFilter); - } else if (readPreference.mode === ReadPreference.SECONDARY_PREFERRED) { - const result = latencyWindowReducer( - topologyDescription, - tagSetReducer( - readPreference, - maxStalenessReducer(readPreference, topologyDescription, servers) - ) - ).filter(secondaryFilter); - - return result.length === 0 ? servers.filter(primaryFilter) : result; - } else if (readPreference.mode === ReadPreference.PRIMARY_PREFERRED) { - const result = servers.filter(primaryFilter); - if (result.length) { - return result; - } - - return latencyWindowReducer( - topologyDescription, - tagSetReducer( - readPreference, - maxStalenessReducer(readPreference, topologyDescription, servers) - ) - ).filter(secondaryFilter); - } - }; -} - -module.exports = { - writableServerSelector, - readPreferenceServerSelector -}; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/sdam/srv_polling.js b/scripts/2.5/node_modules/mongodb/lib/core/sdam/srv_polling.js deleted file mode 100644 index 115ae45c..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/core/sdam/srv_polling.js +++ /dev/null @@ -1,135 +0,0 @@ -'use strict'; - -const Logger = require('../connection/logger'); -const EventEmitter = require('events').EventEmitter; -const dns = require('dns'); -/** - * Determines whether a provided address matches the provided parent domain in order - * to avoid certain attack vectors. - * - * @param {String} srvAddress The address to check against a domain - * @param {String} parentDomain The domain to check the provided address against - * @return {Boolean} Whether the provided address matches the parent domain - */ -function matchesParentDomain(srvAddress, parentDomain) { - const regex = /^.*?\./; - const srv = `.${srvAddress.replace(regex, '')}`; - const parent = `.${parentDomain.replace(regex, '')}`; - return srv.endsWith(parent); -} - -class SrvPollingEvent { - constructor(srvRecords) { - this.srvRecords = srvRecords; - } - - addresses() { - return new Set(this.srvRecords.map(record => `${record.name}:${record.port}`)); - } -} - -class SrvPoller extends EventEmitter { - /** - * @param {object} options - * @param {string} options.srvHost - * @param {number} [options.heartbeatFrequencyMS] - * @param {function} [options.logger] - * @param {string} [options.loggerLevel] - */ - constructor(options) { - super(); - - if (!options || !options.srvHost) { - throw new TypeError('options for SrvPoller must exist and include srvHost'); - } - - this.srvHost = options.srvHost; - this.rescanSrvIntervalMS = 60000; - this.heartbeatFrequencyMS = options.heartbeatFrequencyMS || 10000; - this.logger = Logger('srvPoller', options); - - this.haMode = false; - this.generation = 0; - - this._timeout = null; - } - - get srvAddress() { - return `_mongodb._tcp.${this.srvHost}`; - } - - get intervalMS() { - return this.haMode ? this.heartbeatFrequencyMS : this.rescanSrvIntervalMs; - } - - start() { - if (!this._timeout) { - this.schedule(); - } - } - - stop() { - if (this._timeout) { - clearTimeout(this._timeout); - this.generation += 1; - this._timeout = null; - } - } - - schedule() { - clearTimeout(this._timeout); - this._timeout = setTimeout(() => this._poll(), this.intervalMS); - } - - success(srvRecords) { - this.haMode = false; - this.schedule(); - this.emit('srvRecordDiscovery', new SrvPollingEvent(srvRecords)); - } - - failure(message, obj) { - this.logger.warn(message, obj); - this.haMode = true; - this.schedule(); - } - - parentDomainMismatch(srvRecord) { - this.logger.warn( - `parent domain mismatch on SRV record (${srvRecord.name}:${srvRecord.port})`, - srvRecord - ); - } - - _poll() { - const generation = this.generation; - dns.resolveSrv(this.srvAddress, (err, srvRecords) => { - if (generation !== this.generation) { - return; - } - - if (err) { - this.failure('DNS error', err); - return; - } - - const finalAddresses = []; - srvRecords.forEach(record => { - if (matchesParentDomain(record.name, this.srvHost)) { - finalAddresses.push(record); - } else { - this.parentDomainMismatch(record); - } - }); - - if (!finalAddresses.length) { - this.failure('No valid addresses found at host'); - return; - } - - this.success(finalAddresses); - }); - } -} - -module.exports.SrvPollingEvent = SrvPollingEvent; -module.exports.SrvPoller = SrvPoller; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/sdam/topology.js b/scripts/2.5/node_modules/mongodb/lib/core/sdam/topology.js deleted file mode 100644 index 5dab4b36..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/core/sdam/topology.js +++ /dev/null @@ -1,1186 +0,0 @@ -'use strict'; -const EventEmitter = require('events'); -const ServerDescription = require('./server_description').ServerDescription; -const ServerType = require('./server_description').ServerType; -const TopologyDescription = require('./topology_description').TopologyDescription; -const TopologyType = require('./topology_description').TopologyType; -const monitoring = require('./monitoring'); -const calculateDurationInMs = require('../utils').calculateDurationInMs; -const MongoTimeoutError = require('../error').MongoTimeoutError; -const Server = require('./server'); -const relayEvents = require('../utils').relayEvents; -const ReadPreference = require('../topologies/read_preference'); -const readPreferenceServerSelector = require('./server_selectors').readPreferenceServerSelector; -const writableServerSelector = require('./server_selectors').writableServerSelector; -const isRetryableWritesSupported = require('../topologies/shared').isRetryableWritesSupported; -const CoreCursor = require('../cursor').CoreCursor; -const deprecate = require('util').deprecate; -const BSON = require('../connection/utils').retrieveBSON(); -const createCompressionInfo = require('../topologies/shared').createCompressionInfo; -const isRetryableError = require('../error').isRetryableError; -const isSDAMUnrecoverableError = require('../error').isSDAMUnrecoverableError; -const ClientSession = require('../sessions').ClientSession; -const createClientInfo = require('../topologies/shared').createClientInfo; -const MongoError = require('../error').MongoError; -const resolveClusterTime = require('../topologies/shared').resolveClusterTime; -const SrvPoller = require('./srv_polling').SrvPoller; -const getMMAPError = require('../topologies/shared').getMMAPError; - -// Global state -let globalTopologyCounter = 0; - -// Constants -const TOPOLOGY_DEFAULTS = { - localThresholdMS: 15, - serverSelectionTimeoutMS: 30000, - heartbeatFrequencyMS: 10000, - minHeartbeatFrequencyMS: 500 -}; - -// events that we relay to the `Topology` -const SERVER_RELAY_EVENTS = [ - 'serverHeartbeatStarted', - 'serverHeartbeatSucceeded', - 'serverHeartbeatFailed', - 'commandStarted', - 'commandSucceeded', - 'commandFailed', - - // NOTE: Legacy events - 'monitoring' -]; - -// all events we listen to from `Server` instances -const LOCAL_SERVER_EVENTS = SERVER_RELAY_EVENTS.concat([ - 'error', - 'connect', - 'descriptionReceived', - 'close', - 'ended' -]); - -/** - * A container of server instances representing a connection to a MongoDB topology. - * - * @fires Topology#serverOpening - * @fires Topology#serverClosed - * @fires Topology#serverDescriptionChanged - * @fires Topology#topologyOpening - * @fires Topology#topologyClosed - * @fires Topology#topologyDescriptionChanged - * @fires Topology#serverHeartbeatStarted - * @fires Topology#serverHeartbeatSucceeded - * @fires Topology#serverHeartbeatFailed - */ -class Topology extends EventEmitter { - /** - * Create a topology - * - * @param {Array|String} [seedlist] a string list, or array of Server instances to connect to - * @param {Object} [options] Optional settings - * @param {Number} [options.localThresholdMS=15] The size of the latency window for selecting among multiple suitable servers - * @param {Number} [options.serverSelectionTimeoutMS=30000] How long to block for server selection before throwing an error - * @param {Number} [options.heartbeatFrequencyMS=10000] The frequency with which topology updates are scheduled - */ - constructor(seedlist, options) { - super(); - if (typeof options === 'undefined' && typeof seedlist !== 'string') { - options = seedlist; - seedlist = []; - - // this is for legacy single server constructor support - if (options.host) { - seedlist.push({ host: options.host, port: options.port }); - } - } - - seedlist = seedlist || []; - if (typeof seedlist === 'string') { - seedlist = parseStringSeedlist(seedlist); - } - - options = Object.assign({}, TOPOLOGY_DEFAULTS, options); - - const topologyType = topologyTypeFromSeedlist(seedlist, options); - const topologyId = globalTopologyCounter++; - const serverDescriptions = seedlist.reduce((result, seed) => { - if (seed.domain_socket) seed.host = seed.domain_socket; - const address = seed.port ? `${seed.host}:${seed.port}` : `${seed.host}:27017`; - result.set(address, new ServerDescription(address)); - return result; - }, new Map()); - - this.s = { - // the id of this topology - id: topologyId, - // passed in options - options, - // initial seedlist of servers to connect to - seedlist: seedlist, - // the topology description - description: new TopologyDescription( - topologyType, - serverDescriptions, - options.replicaSet, - null, - null, - null, - options - ), - serverSelectionTimeoutMS: options.serverSelectionTimeoutMS, - heartbeatFrequencyMS: options.heartbeatFrequencyMS, - minHeartbeatIntervalMS: options.minHeartbeatIntervalMS, - // allow users to override the cursor factory - Cursor: options.cursorFactory || CoreCursor, - // the bson parser - bson: - options.bson || - new BSON([ - BSON.Binary, - BSON.Code, - BSON.DBRef, - BSON.Decimal128, - BSON.Double, - BSON.Int32, - BSON.Long, - BSON.Map, - BSON.MaxKey, - BSON.MinKey, - BSON.ObjectId, - BSON.BSONRegExp, - BSON.Symbol, - BSON.Timestamp - ]), - // a map of server instances to normalized addresses - servers: new Map(), - // Server Session Pool - sessionPool: null, - // Active client sessions - sessions: new Set(), - // Promise library - promiseLibrary: options.promiseLibrary || Promise, - credentials: options.credentials, - clusterTime: null, - - // timer management - monitorTimers: [], - iterationTimers: [] - }; - - // amend options for server instance creation - this.s.options.compression = { compressors: createCompressionInfo(options) }; - - // add client info - this.s.clientInfo = createClientInfo(options); - - if (options.srvHost) { - this.s.srvPoller = - options.srvPoller || - new SrvPoller({ - heartbeatFrequencyMS: this.s.heartbeatFrequencyMS, - srvHost: options.srvHost, // TODO: GET THIS - logger: options.logger, - loggerLevel: options.loggerLevel - }); - this.s.detectTopologyDescriptionChange = ev => { - const previousType = ev.previousDescription.type; - const newType = ev.newDescription.type; - - if (previousType !== TopologyType.Sharded && newType === TopologyType.Sharded) { - this.s.handleSrvPolling = srvPollingHandler(this); - this.s.srvPoller.on('srvRecordDiscovery', this.s.handleSrvPolling); - this.s.srvPoller.start(); - } - }; - - this.on('topologyDescriptionChanged', this.s.detectTopologyDescriptionChange); - } - } - - /** - * @return A `TopologyDescription` for this topology - */ - get description() { - return this.s.description; - } - - get parserType() { - return BSON.native ? 'c++' : 'js'; - } - - /** - * All raw connections - * @method - * @return {Connection[]} - */ - connections() { - return Array.from(this.s.servers.values()).reduce((result, server) => { - return result.concat(server.s.pool.allConnections()); - }, []); - } - - /** - * Initiate server connect - * - * @param {Object} [options] Optional settings - * @param {Array} [options.auth=null] Array of auth options to apply on connect - * @param {function} [callback] An optional callback called once on the first connected server - */ - connect(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // emit SDAM monitoring events - this.emit('topologyOpening', new monitoring.TopologyOpeningEvent(this.s.id)); - - // emit an event for the topology change - this.emit( - 'topologyDescriptionChanged', - new monitoring.TopologyDescriptionChangedEvent( - this.s.id, - new TopologyDescription(TopologyType.Unknown), // initial is always Unknown - this.s.description - ) - ); - - connectServers(this, Array.from(this.s.description.servers.values())); - this.s.connected = true; - - // otherwise, wait for a server to properly connect based on user provided read preference, - // or primary. - - translateReadPreference(options); - const readPreference = options.readPreference || ReadPreference.primary; - - this.selectServer(readPreferenceServerSelector(readPreference), options, (err, server) => { - if (err) { - if (typeof callback === 'function') { - callback(err, null); - } else { - this.emit('error', err); - } - - return; - } - - const errorHandler = err => { - server.removeListener('connect', connectHandler); - if (typeof callback === 'function') callback(err, null); - }; - - const connectHandler = (_, err) => { - server.removeListener('error', errorHandler); - this.emit('open', err, this); - this.emit('connect', this); - - if (typeof callback === 'function') callback(err, this); - }; - - const STATE_CONNECTING = 1; - if (server.s.state === STATE_CONNECTING) { - server.once('error', errorHandler); - server.once('connect', connectHandler); - return; - } - - connectHandler(); - }); - } - - /** - * Close this topology - */ - close(options, callback) { - if (typeof options === 'function') { - callback = options; - options = {}; - } - - if (typeof options === 'boolean') { - options = { force: options }; - } - - options = options || {}; - - // clear all existing monitor timers - this.s.monitorTimers.map(timer => clearTimeout(timer)); - this.s.monitorTimers = []; - - this.s.iterationTimers.map(timer => clearTimeout(timer)); - this.s.iterationTimers = []; - - if (this.s.sessionPool) { - this.s.sessions.forEach(session => session.endSession()); - this.s.sessionPool.endAllPooledSessions(); - } - - if (this.s.srvPoller) { - this.s.srvPoller.stop(); - if (this.s.handleSrvPolling) { - this.s.srvPoller.removeListener('srvRecordDiscovery', this.s.handleSrvPolling); - delete this.s.handleSrvPolling; - } - } - - if (this.s.detectTopologyDescriptionChange) { - this.removeListener('topologyDescriptionChanged', this.s.detectTopologyDescriptionChange); - delete this.s.detectTopologyDescriptionChange; - } - - const servers = this.s.servers; - if (servers.size === 0) { - this.s.connected = false; - if (typeof callback === 'function') { - callback(null, null); - } - - return; - } - - // destroy all child servers - let destroyed = 0; - servers.forEach(server => - destroyServer(server, this, options, () => { - destroyed++; - if (destroyed === servers.size) { - // emit an event for close - this.emit('topologyClosed', new monitoring.TopologyClosedEvent(this.s.id)); - - this.s.connected = false; - if (typeof callback === 'function') { - callback(null, null); - } - } - }) - ); - } - - /** - * Selects a server according to the selection predicate provided - * - * @param {function} [selector] An optional selector to select servers by, defaults to a random selection within a latency window - * @param {object} [options] Optional settings related to server selection - * @param {number} [options.serverSelectionTimeoutMS] How long to block for server selection before throwing an error - * @param {function} callback The callback used to indicate success or failure - * @return {Server} An instance of a `Server` meeting the criteria of the predicate provided - */ - selectServer(selector, options, callback) { - if (typeof options === 'function') { - callback = options; - if (typeof selector !== 'function') { - options = selector; - - let readPreference; - if (selector instanceof ReadPreference) { - readPreference = selector; - } else { - translateReadPreference(options); - readPreference = options.readPreference || ReadPreference.primary; - } - - selector = readPreferenceServerSelector(readPreference); - } else { - options = {}; - } - } - - options = Object.assign( - {}, - { serverSelectionTimeoutMS: this.s.serverSelectionTimeoutMS }, - options - ); - - const isSharded = this.description.type === TopologyType.Sharded; - const session = options.session; - const transaction = session && session.transaction; - - if (isSharded && transaction && transaction.server) { - callback(null, transaction.server); - return; - } - - // clear out any existing iteration timers - this.s.iterationTimers.map(timer => clearTimeout(timer)); - this.s.iterationTimers = []; - - selectServers( - this, - selector, - options.serverSelectionTimeoutMS, - process.hrtime(), - (err, servers) => { - if (err) return callback(err, null); - - const selectedServer = randomSelection(servers); - if (isSharded && transaction && transaction.isActive) { - transaction.pinServer(selectedServer); - } - - callback(null, selectedServer); - } - ); - } - - // Sessions related methods - - /** - * @return Whether the topology should initiate selection to determine session support - */ - shouldCheckForSessionSupport() { - return ( - (this.description.type === TopologyType.Single && !this.description.hasKnownServers) || - !this.description.hasDataBearingServers - ); - } - - /** - * @return Whether sessions are supported on the current topology - */ - hasSessionSupport() { - return this.description.logicalSessionTimeoutMinutes != null; - } - - /** - * Start a logical session - */ - startSession(options, clientOptions) { - const session = new ClientSession(this, this.s.sessionPool, options, clientOptions); - session.once('ended', () => { - this.s.sessions.delete(session); - }); - - this.s.sessions.add(session); - return session; - } - - /** - * Send endSessions command(s) with the given session ids - * - * @param {Array} sessions The sessions to end - * @param {function} [callback] - */ - endSessions(sessions, callback) { - if (!Array.isArray(sessions)) { - sessions = [sessions]; - } - - this.command( - 'admin.$cmd', - { endSessions: sessions }, - { readPreference: ReadPreference.primaryPreferred, noResponse: true }, - () => { - // intentionally ignored, per spec - if (typeof callback === 'function') callback(); - } - ); - } - - /** - * Update the internal TopologyDescription with a ServerDescription - * - * @param {object} serverDescription The server to update in the internal list of server descriptions - */ - serverUpdateHandler(serverDescription) { - if (!this.s.description.hasServer(serverDescription.address)) { - return; - } - - // these will be used for monitoring events later - const previousTopologyDescription = this.s.description; - const previousServerDescription = this.s.description.servers.get(serverDescription.address); - - // first update the TopologyDescription - this.s.description = this.s.description.update(serverDescription); - if (this.s.description.compatibilityError) { - this.emit('error', new MongoError(this.s.description.compatibilityError)); - return; - } - - // emit monitoring events for this change - this.emit( - 'serverDescriptionChanged', - new monitoring.ServerDescriptionChangedEvent( - this.s.id, - serverDescription.address, - previousServerDescription, - this.s.description.servers.get(serverDescription.address) - ) - ); - - // update server list from updated descriptions - updateServers(this, serverDescription); - - // Driver Sessions Spec: "Whenever a driver receives a cluster time from - // a server it MUST compare it to the current highest seen cluster time - // for the deployment. If the new cluster time is higher than the - // highest seen cluster time it MUST become the new highest seen cluster - // time. Two cluster times are compared using only the BsonTimestamp - // value of the clusterTime embedded field." - const clusterTime = serverDescription.$clusterTime; - if (clusterTime) { - resolveClusterTime(this, clusterTime); - } - - this.emit( - 'topologyDescriptionChanged', - new monitoring.TopologyDescriptionChangedEvent( - this.s.id, - previousTopologyDescription, - this.s.description - ) - ); - } - - auth(credentials, callback) { - if (typeof credentials === 'function') (callback = credentials), (credentials = null); - if (typeof callback === 'function') callback(null, true); - } - - logout(callback) { - if (typeof callback === 'function') callback(null, true); - } - - // Basic operation support. Eventually this should be moved into command construction - // during the command refactor. - - /** - * Insert one or more documents - * - * @param {String} ns The full qualified namespace for this operation - * @param {Array} ops An array of documents to insert - * @param {Boolean} [options.ordered=true] Execute in order or out of order - * @param {Object} [options.writeConcern] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields - * @param {ClientSession} [options.session] Session to use for the operation - * @param {boolean} [options.retryWrites] Enable retryable writes for this operation - * @param {opResultCallback} callback A callback function - */ - insert(ns, ops, options, callback) { - executeWriteOperation({ topology: this, op: 'insert', ns, ops }, options, callback); - } - - /** - * Perform one or more update operations - * - * @param {string} ns The fully qualified namespace for this operation - * @param {array} ops An array of updates - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields - * @param {ClientSession} [options.session] Session to use for the operation - * @param {boolean} [options.retryWrites] Enable retryable writes for this operation - * @param {opResultCallback} callback A callback function - */ - update(ns, ops, options, callback) { - executeWriteOperation({ topology: this, op: 'update', ns, ops }, options, callback); - } - - /** - * Perform one or more remove operations - * - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of removes - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {boolean} [options.retryWrites] Enable retryable writes for this operation - * @param {opResultCallback} callback A callback function - */ - remove(ns, ops, options, callback) { - executeWriteOperation({ topology: this, op: 'remove', ns, ops }, options, callback); - } - - /** - * Execute a command - * - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object} cmd The command hash - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @param {Connection} [options.connection] Specify connection object to execute command against - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {opResultCallback} callback A callback function - */ - command(ns, cmd, options, callback) { - if (typeof options === 'function') { - (callback = options), (options = {}), (options = options || {}); - } - - translateReadPreference(options); - const readPreference = options.readPreference || ReadPreference.primary; - - this.selectServer(readPreferenceServerSelector(readPreference), options, (err, server) => { - if (err) { - callback(err, null); - return; - } - - const willRetryWrite = - !options.retrying && - !!options.retryWrites && - options.session && - isRetryableWritesSupported(this) && - !options.session.inTransaction() && - isWriteCommand(cmd); - - const cb = (err, result) => { - if (!err) return callback(null, result); - if (!isRetryableError(err)) { - return callback(err); - } - - if (willRetryWrite) { - const newOptions = Object.assign({}, options, { retrying: true }); - return this.command(ns, cmd, newOptions, callback); - } - - return callback(err); - }; - - // increment and assign txnNumber - if (willRetryWrite) { - options.session.incrementTransactionNumber(); - options.willRetryWrite = willRetryWrite; - } - - server.command(ns, cmd, options, cb); - }); - } - - /** - * Create a new cursor - * - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object|Long} cmd Can be either a command returning a cursor or a cursorId - * @param {object} [options] Options for the cursor - * @param {object} [options.batchSize=0] Batchsize for the operation - * @param {array} [options.documents=[]] Initial documents list for cursor - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {object} [options.topology] The internal topology of the created cursor - * @returns {Cursor} - */ - cursor(ns, cmd, options) { - options = options || {}; - const topology = options.topology || this; - const CursorClass = options.cursorFactory || this.s.Cursor; - translateReadPreference(options); - - return new CursorClass(topology, ns, cmd, options); - } - - get clientInfo() { - return this.s.clientInfo; - } - - // Legacy methods for compat with old topology types - isConnected() { - // console.log('not implemented: `isConnected`'); - return true; - } - - isDestroyed() { - // console.log('not implemented: `isDestroyed`'); - return false; - } - - unref() { - console.log('not implemented: `unref`'); - } - - // NOTE: There are many places in code where we explicitly check the last isMaster - // to do feature support detection. This should be done any other way, but for - // now we will just return the first isMaster seen, which should suffice. - lastIsMaster() { - const serverDescriptions = Array.from(this.description.servers.values()); - if (serverDescriptions.length === 0) return {}; - - const sd = serverDescriptions.filter(sd => sd.type !== ServerType.Unknown)[0]; - const result = sd || { maxWireVersion: this.description.commonWireVersion }; - return result; - } - - get logicalSessionTimeoutMinutes() { - return this.description.logicalSessionTimeoutMinutes; - } - - get bson() { - return this.s.bson; - } -} - -Object.defineProperty(Topology.prototype, 'clusterTime', { - enumerable: true, - get: function() { - return this.s.clusterTime; - }, - set: function(clusterTime) { - this.s.clusterTime = clusterTime; - } -}); - -// legacy aliases -Topology.prototype.destroy = deprecate( - Topology.prototype.close, - 'destroy() is deprecated, please use close() instead' -); - -const RETRYABLE_WRITE_OPERATIONS = ['findAndModify', 'insert', 'update', 'delete']; -function isWriteCommand(command) { - return RETRYABLE_WRITE_OPERATIONS.some(op => command[op]); -} - -/** - * Destroys a server, and removes all event listeners from the instance - * - * @param {Server} server - */ -function destroyServer(server, topology, options, callback) { - options = options || {}; - LOCAL_SERVER_EVENTS.forEach(event => server.removeAllListeners(event)); - - server.destroy(options, () => { - topology.emit( - 'serverClosed', - new monitoring.ServerClosedEvent(topology.s.id, server.description.address) - ); - - if (typeof callback === 'function') callback(null, null); - }); -} - -/** - * Parses a basic seedlist in string form - * - * @param {string} seedlist The seedlist to parse - */ -function parseStringSeedlist(seedlist) { - return seedlist.split(',').map(seed => ({ - host: seed.split(':')[0], - port: seed.split(':')[1] || 27017 - })); -} - -function topologyTypeFromSeedlist(seedlist, options) { - const replicaSet = options.replicaSet || options.setName || options.rs_name; - if (seedlist.length === 1 && !replicaSet) return TopologyType.Single; - if (replicaSet) return TopologyType.ReplicaSetNoPrimary; - return TopologyType.Unknown; -} - -function randomSelection(array) { - return array[Math.floor(Math.random() * array.length)]; -} - -/** - * Selects servers using the provided selector - * - * @private - * @param {Topology} topology The topology to select servers from - * @param {function} selector The actual predicate used for selecting servers - * @param {Number} timeout The max time we are willing wait for selection - * @param {Number} start A high precision timestamp for the start of the selection process - * @param {function} callback The callback used to convey errors or the resultant servers - */ -function selectServers(topology, selector, timeout, start, callback) { - const duration = calculateDurationInMs(start); - if (duration >= timeout) { - return callback( - new MongoTimeoutError(`Server selection timed out after ${timeout} ms`), - topology.description.error - ); - } - - // ensure we are connected - if (!topology.s.connected) { - topology.connect(); - - // we want to make sure we're still within the requested timeout window - const failToConnectTimer = setTimeout(() => { - topology.removeListener('connect', connectHandler); - callback( - new MongoTimeoutError('Server selection timed out waiting to connect'), - topology.description.error - ); - }, timeout - duration); - - const connectHandler = () => { - clearTimeout(failToConnectTimer); - selectServers(topology, selector, timeout, process.hrtime(), callback); - }; - - topology.once('connect', connectHandler); - return; - } - - // otherwise, attempt server selection - const serverDescriptions = Array.from(topology.description.servers.values()); - let descriptions; - - // support server selection by options with readPreference - if (typeof selector === 'object') { - const readPreference = selector.readPreference - ? selector.readPreference - : ReadPreference.primary; - - selector = readPreferenceServerSelector(readPreference); - } - - try { - descriptions = selector - ? selector(topology.description, serverDescriptions) - : serverDescriptions; - } catch (e) { - return callback(e, null); - } - - if (descriptions.length) { - const servers = descriptions.map(description => topology.s.servers.get(description.address)); - return callback(null, servers); - } - - const retrySelection = () => { - // clear all existing monitor timers - topology.s.monitorTimers.map(timer => clearTimeout(timer)); - topology.s.monitorTimers = []; - - // ensure all server monitors attempt monitoring soon - topology.s.servers.forEach(server => { - const timer = setTimeout( - () => server.monitor({ heartbeatFrequencyMS: topology.description.heartbeatFrequencyMS }), - TOPOLOGY_DEFAULTS.minHeartbeatFrequencyMS - ); - - topology.s.monitorTimers.push(timer); - }); - - const descriptionChangedHandler = () => { - // successful iteration, clear the check timer - clearTimeout(iterationTimer); - topology.s.iterationTimers.splice(timerIndex, 1); - - // topology description has changed due to monitoring, reattempt server selection - selectServers(topology, selector, timeout, start, callback); - }; - - const iterationTimer = setTimeout(() => { - topology.removeListener('topologyDescriptionChanged', descriptionChangedHandler); - callback( - new MongoTimeoutError( - `Server selection timed out after ${timeout} ms`, - topology.description.error - ) - ); - }, timeout - duration); - - // track this timer in case we need to clean it up outside this loop - const timerIndex = topology.s.iterationTimers.push(iterationTimer); - - topology.once('topologyDescriptionChanged', descriptionChangedHandler); - }; - - retrySelection(); -} - -function createAndConnectServer(topology, serverDescription) { - topology.emit( - 'serverOpening', - new monitoring.ServerOpeningEvent(topology.s.id, serverDescription.address) - ); - - const server = new Server(serverDescription, topology.s.options, topology); - relayEvents(server, topology, SERVER_RELAY_EVENTS); - - server.once('connect', serverConnectEventHandler(server, topology)); - server.on('descriptionReceived', topology.serverUpdateHandler.bind(topology)); - server.on('error', serverErrorEventHandler(server, topology)); - server.on('close', () => topology.emit('close', server)); - server.connect(); - return server; -} - -/** - * Create `Server` instances for all initially known servers, connect them, and assign - * them to the passed in `Topology`. - * - * @param {Topology} topology The topology responsible for the servers - * @param {ServerDescription[]} serverDescriptions A list of server descriptions to connect - */ -function connectServers(topology, serverDescriptions) { - topology.s.servers = serverDescriptions.reduce((servers, serverDescription) => { - const server = createAndConnectServer(topology, serverDescription); - servers.set(serverDescription.address, server); - return servers; - }, new Map()); -} - -function updateServers(topology, incomingServerDescription) { - // update the internal server's description - if (incomingServerDescription && topology.s.servers.has(incomingServerDescription.address)) { - const server = topology.s.servers.get(incomingServerDescription.address); - server.s.description = incomingServerDescription; - } - - // add new servers for all descriptions we currently don't know about locally - for (const serverDescription of topology.description.servers.values()) { - if (!topology.s.servers.has(serverDescription.address)) { - const server = createAndConnectServer(topology, serverDescription); - topology.s.servers.set(serverDescription.address, server); - } - } - - // for all servers no longer known, remove their descriptions and destroy their instances - for (const entry of topology.s.servers) { - const serverAddress = entry[0]; - if (topology.description.hasServer(serverAddress)) { - continue; - } - - const server = topology.s.servers.get(serverAddress); - topology.s.servers.delete(serverAddress); - - // prepare server for garbage collection - destroyServer(server, topology); - } -} - -function serverConnectEventHandler(server, topology) { - return function(/* isMaster, err */) { - server.monitor({ - initial: true, - heartbeatFrequencyMS: topology.description.heartbeatFrequencyMS - }); - }; -} - -function serverErrorEventHandler(server /*, topology */) { - return function(err) { - if (isSDAMUnrecoverableError(err, server)) { - resetServerState(server, err, { clearPool: true }); - return; - } - - resetServerState(server, err); - }; -} - -function executeWriteOperation(args, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // TODO: once we drop Node 4, use destructuring either here or in arguments. - const topology = args.topology; - const op = args.op; - const ns = args.ns; - const ops = args.ops; - - const willRetryWrite = - !args.retrying && - !!options.retryWrites && - options.session && - isRetryableWritesSupported(topology) && - !options.session.inTransaction(); - - topology.selectServer(writableServerSelector(), options, (err, server) => { - if (err) { - callback(err, null); - return; - } - - const handler = (err, result) => { - if (!err) return callback(null, result); - if (!isRetryableError(err)) { - err = getMMAPError(err); - return callback(err); - } - - if (willRetryWrite) { - const newArgs = Object.assign({}, args, { retrying: true }); - return executeWriteOperation(newArgs, options, callback); - } - - return callback(err); - }; - - if (callback.operationId) { - handler.operationId = callback.operationId; - } - - // increment and assign txnNumber - if (willRetryWrite) { - options.session.incrementTransactionNumber(); - options.willRetryWrite = willRetryWrite; - } - - // execute the write operation - server[op](ns, ops, options, handler); - }); -} - -/** - * Resets the internal state of this server to `Unknown` by simulating an empty ismaster - * - * @private - * @param {Server} server - * @param {MongoError} error The error that caused the state reset - * @param {object} [options] Optional settings - * @param {boolean} [options.clearPool=false] Pool should be cleared out on state reset - */ -function resetServerState(server, error, options) { - options = Object.assign({}, { clearPool: false }, options); - - function resetState() { - server.emit( - 'descriptionReceived', - new ServerDescription(server.description.address, null, { error }) - ); - - process.nextTick(() => server.monitor()); - } - - if (options.clearPool && server.s.pool) { - server.s.pool.reset(() => resetState()); - return; - } - - resetState(); -} - -function translateReadPreference(options) { - if (options.readPreference == null) { - return; - } - - let r = options.readPreference; - if (typeof r === 'string') { - options.readPreference = new ReadPreference(r); - } else if (r && !(r instanceof ReadPreference) && typeof r === 'object') { - const mode = r.mode || r.preference; - if (mode && typeof mode === 'string') { - options.readPreference = new ReadPreference(mode, r.tags, { - maxStalenessSeconds: r.maxStalenessSeconds - }); - } - } else if (!(r instanceof ReadPreference)) { - throw new TypeError('Invalid read preference: ' + r); - } - - return options; -} - -function srvPollingHandler(topology) { - return function handleSrvPolling(ev) { - const previousTopologyDescription = topology.s.description; - topology.s.description = topology.s.description.updateFromSrvPollingEvent(ev); - if (topology.s.description === previousTopologyDescription) { - // Nothing changed, so return - return; - } - - updateServers(topology); - - topology.emit( - 'topologyDescriptionChanged', - new monitoring.TopologyDescriptionChangedEvent( - topology.s.id, - previousTopologyDescription, - topology.s.description - ) - ); - }; -} - -/** - * A server opening SDAM monitoring event - * - * @event Topology#serverOpening - * @type {ServerOpeningEvent} - */ - -/** - * A server closed SDAM monitoring event - * - * @event Topology#serverClosed - * @type {ServerClosedEvent} - */ - -/** - * A server description SDAM change monitoring event - * - * @event Topology#serverDescriptionChanged - * @type {ServerDescriptionChangedEvent} - */ - -/** - * A topology open SDAM event - * - * @event Topology#topologyOpening - * @type {TopologyOpeningEvent} - */ - -/** - * A topology closed SDAM event - * - * @event Topology#topologyClosed - * @type {TopologyClosedEvent} - */ - -/** - * A topology structure SDAM change event - * - * @event Topology#topologyDescriptionChanged - * @type {TopologyDescriptionChangedEvent} - */ - -/** - * A topology serverHeartbeatStarted SDAM event - * - * @event Topology#serverHeartbeatStarted - * @type {ServerHeartbeatStartedEvent} - */ - -/** - * A topology serverHeartbeatFailed SDAM event - * - * @event Topology#serverHeartbeatFailed - * @type {ServerHearbeatFailedEvent} - */ - -/** - * A topology serverHeartbeatSucceeded SDAM change event - * - * @event Topology#serverHeartbeatSucceeded - * @type {ServerHeartbeatSucceededEvent} - */ - -/** - * An event emitted indicating a command was started, if command monitoring is enabled - * - * @event Topology#commandStarted - * @type {object} - */ - -/** - * An event emitted indicating a command succeeded, if command monitoring is enabled - * - * @event Topology#commandSucceeded - * @type {object} - */ - -/** - * An event emitted indicating a command failed, if command monitoring is enabled - * - * @event Topology#commandFailed - * @type {object} - */ - -module.exports = Topology; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/sdam/topology_description.js b/scripts/2.5/node_modules/mongodb/lib/core/sdam/topology_description.js deleted file mode 100644 index a94fb678..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/core/sdam/topology_description.js +++ /dev/null @@ -1,408 +0,0 @@ -'use strict'; -const ServerType = require('./server_description').ServerType; -const ServerDescription = require('./server_description').ServerDescription; -const WIRE_CONSTANTS = require('../wireprotocol/constants'); - -// contstants related to compatability checks -const MIN_SUPPORTED_SERVER_VERSION = WIRE_CONSTANTS.MIN_SUPPORTED_SERVER_VERSION; -const MAX_SUPPORTED_SERVER_VERSION = WIRE_CONSTANTS.MAX_SUPPORTED_SERVER_VERSION; -const MIN_SUPPORTED_WIRE_VERSION = WIRE_CONSTANTS.MIN_SUPPORTED_WIRE_VERSION; -const MAX_SUPPORTED_WIRE_VERSION = WIRE_CONSTANTS.MAX_SUPPORTED_WIRE_VERSION; - -// An enumeration of topology types we know about -const TopologyType = { - Single: 'Single', - ReplicaSetNoPrimary: 'ReplicaSetNoPrimary', - ReplicaSetWithPrimary: 'ReplicaSetWithPrimary', - Sharded: 'Sharded', - Unknown: 'Unknown' -}; - -// Representation of a deployment of servers -class TopologyDescription { - /** - * Create a TopologyDescription - * - * @param {string} topologyType - * @param {Map} serverDescriptions the a map of address to ServerDescription - * @param {string} setName - * @param {number} maxSetVersion - * @param {ObjectId} maxElectionId - */ - constructor( - topologyType, - serverDescriptions, - setName, - maxSetVersion, - maxElectionId, - commonWireVersion, - options, - error - ) { - options = options || {}; - - // TODO: consider assigning all these values to a temporary value `s` which - // we use `Object.freeze` on, ensuring the internal state of this type - // is immutable. - this.type = topologyType || TopologyType.Unknown; - this.setName = setName || null; - this.maxSetVersion = maxSetVersion || null; - this.maxElectionId = maxElectionId || null; - this.servers = serverDescriptions || new Map(); - this.stale = false; - this.compatible = true; - this.compatibilityError = null; - this.logicalSessionTimeoutMinutes = null; - this.heartbeatFrequencyMS = options.heartbeatFrequencyMS || 0; - this.localThresholdMS = options.localThresholdMS || 0; - this.options = options; - this.error = error; - this.commonWireVersion = commonWireVersion || null; - - // determine server compatibility - for (const serverDescription of this.servers.values()) { - if (serverDescription.type === ServerType.Unknown) continue; - - if (serverDescription.minWireVersion > MAX_SUPPORTED_WIRE_VERSION) { - this.compatible = false; - this.compatibilityError = `Server at ${serverDescription.address} requires wire version ${ - serverDescription.minWireVersion - }, but this version of the driver only supports up to ${MAX_SUPPORTED_WIRE_VERSION} (MongoDB ${MAX_SUPPORTED_SERVER_VERSION})`; - } - - if (serverDescription.maxWireVersion < MIN_SUPPORTED_WIRE_VERSION) { - this.compatible = false; - this.compatibilityError = `Server at ${serverDescription.address} reports wire version ${ - serverDescription.maxWireVersion - }, but this version of the driver requires at least ${MIN_SUPPORTED_WIRE_VERSION} (MongoDB ${MIN_SUPPORTED_SERVER_VERSION}).`; - break; - } - } - - // Whenever a client updates the TopologyDescription from an ismaster response, it MUST set - // TopologyDescription.logicalSessionTimeoutMinutes to the smallest logicalSessionTimeoutMinutes - // value among ServerDescriptions of all data-bearing server types. If any have a null - // logicalSessionTimeoutMinutes, then TopologyDescription.logicalSessionTimeoutMinutes MUST be - // set to null. - const readableServers = Array.from(this.servers.values()).filter(s => s.isReadable); - this.logicalSessionTimeoutMinutes = readableServers.reduce((result, server) => { - if (server.logicalSessionTimeoutMinutes == null) return null; - if (result == null) return server.logicalSessionTimeoutMinutes; - return Math.min(result, server.logicalSessionTimeoutMinutes); - }, null); - } - - /** - * Returns a new TopologyDescription based on the SrvPollingEvent - * @param {SrvPollingEvent} ev The event - */ - updateFromSrvPollingEvent(ev) { - const newAddresses = ev.addresses(); - const serverDescriptions = new Map(this.servers); - for (const server of this.servers) { - if (newAddresses.has(server[0])) { - newAddresses.delete(server[0]); - } else { - serverDescriptions.delete(server[0]); - } - } - - if (serverDescriptions.size === this.servers.size && newAddresses.size === 0) { - return this; - } - - for (const address of newAddresses) { - serverDescriptions.set(address, new ServerDescription(address)); - } - - return new TopologyDescription( - this.type, - serverDescriptions, - this.setName, - this.maxSetVersion, - this.maxElectionId, - this.commonWireVersion, - this.options, - null - ); - } - - /** - * Returns a copy of this description updated with a given ServerDescription - * - * @param {ServerDescription} serverDescription - */ - update(serverDescription) { - const address = serverDescription.address; - // NOTE: there are a number of prime targets for refactoring here - // once we support destructuring assignments - - // potentially mutated values - let topologyType = this.type; - let setName = this.setName; - let maxSetVersion = this.maxSetVersion; - let maxElectionId = this.maxElectionId; - let commonWireVersion = this.commonWireVersion; - let error = serverDescription.error || this.error; - - const serverType = serverDescription.type; - let serverDescriptions = new Map(this.servers); - - // update common wire version - if (serverDescription.maxWireVersion !== 0) { - if (commonWireVersion == null) { - commonWireVersion = serverDescription.maxWireVersion; - } else { - commonWireVersion = Math.min(commonWireVersion, serverDescription.maxWireVersion); - } - } - - // update the actual server description - serverDescriptions.set(address, serverDescription); - - if (topologyType === TopologyType.Single) { - // once we are defined as single, that never changes - return new TopologyDescription( - TopologyType.Single, - serverDescriptions, - setName, - maxSetVersion, - maxElectionId, - commonWireVersion, - this.options, - error - ); - } - - if (topologyType === TopologyType.Unknown) { - if (serverType === ServerType.Standalone) { - serverDescriptions.delete(address); - } else { - topologyType = topologyTypeForServerType(serverType); - } - } - - if (topologyType === TopologyType.Sharded) { - if ([ServerType.Mongos, ServerType.Unknown].indexOf(serverType) === -1) { - serverDescriptions.delete(address); - } - } - - if (topologyType === TopologyType.ReplicaSetNoPrimary) { - if ([ServerType.Mongos, ServerType.Unknown].indexOf(serverType) >= 0) { - serverDescriptions.delete(address); - } - - if (serverType === ServerType.RSPrimary) { - const result = updateRsFromPrimary( - serverDescriptions, - setName, - serverDescription, - maxSetVersion, - maxElectionId - ); - - (topologyType = result[0]), - (setName = result[1]), - (maxSetVersion = result[2]), - (maxElectionId = result[3]); - } else if ( - [ServerType.RSSecondary, ServerType.RSArbiter, ServerType.RSOther].indexOf(serverType) >= 0 - ) { - const result = updateRsNoPrimaryFromMember(serverDescriptions, setName, serverDescription); - (topologyType = result[0]), (setName = result[1]); - } - } - - if (topologyType === TopologyType.ReplicaSetWithPrimary) { - if ([ServerType.Standalone, ServerType.Mongos].indexOf(serverType) >= 0) { - serverDescriptions.delete(address); - topologyType = checkHasPrimary(serverDescriptions); - } else if (serverType === ServerType.RSPrimary) { - const result = updateRsFromPrimary( - serverDescriptions, - setName, - serverDescription, - maxSetVersion, - maxElectionId - ); - - (topologyType = result[0]), - (setName = result[1]), - (maxSetVersion = result[2]), - (maxElectionId = result[3]); - } else if ( - [ServerType.RSSecondary, ServerType.RSArbiter, ServerType.RSOther].indexOf(serverType) >= 0 - ) { - topologyType = updateRsWithPrimaryFromMember( - serverDescriptions, - setName, - serverDescription - ); - } else { - topologyType = checkHasPrimary(serverDescriptions); - } - } - - return new TopologyDescription( - topologyType, - serverDescriptions, - setName, - maxSetVersion, - maxElectionId, - commonWireVersion, - this.options, - error - ); - } - - /** - * Determines if the topology description has any known servers - */ - get hasKnownServers() { - return Array.from(this.servers.values()).some(sd => sd.type !== ServerDescription.Unknown); - } - - /** - * Determines if this topology description has a data-bearing server available. - */ - get hasDataBearingServers() { - return Array.from(this.servers.values()).some(sd => sd.isDataBearing); - } - - /** - * Determines if the topology has a definition for the provided address - * - * @param {String} address - * @return {Boolean} Whether the topology knows about this server - */ - hasServer(address) { - return this.servers.has(address); - } -} - -function topologyTypeForServerType(serverType) { - if (serverType === ServerType.Mongos) return TopologyType.Sharded; - if (serverType === ServerType.RSPrimary) return TopologyType.ReplicaSetWithPrimary; - return TopologyType.ReplicaSetNoPrimary; -} - -function updateRsFromPrimary( - serverDescriptions, - setName, - serverDescription, - maxSetVersion, - maxElectionId -) { - setName = setName || serverDescription.setName; - if (setName !== serverDescription.setName) { - serverDescriptions.delete(serverDescription.address); - return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId]; - } - - const electionIdOID = serverDescription.electionId ? serverDescription.electionId.$oid : null; - const maxElectionIdOID = maxElectionId ? maxElectionId.$oid : null; - if (serverDescription.setVersion != null && electionIdOID != null) { - if (maxSetVersion != null && maxElectionIdOID != null) { - if (maxSetVersion > serverDescription.setVersion || maxElectionIdOID > electionIdOID) { - // this primary is stale, we must remove it - serverDescriptions.set( - serverDescription.address, - new ServerDescription(serverDescription.address) - ); - - return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId]; - } - } - - maxElectionId = serverDescription.electionId; - } - - if ( - serverDescription.setVersion != null && - (maxSetVersion == null || serverDescription.setVersion > maxSetVersion) - ) { - maxSetVersion = serverDescription.setVersion; - } - - // We've heard from the primary. Is it the same primary as before? - for (const address of serverDescriptions.keys()) { - const server = serverDescriptions.get(address); - - if (server.type === ServerType.RSPrimary && server.address !== serverDescription.address) { - // Reset old primary's type to Unknown. - serverDescriptions.set(address, new ServerDescription(server.address)); - - // There can only be one primary - break; - } - } - - // Discover new hosts from this primary's response. - serverDescription.allHosts.forEach(address => { - if (!serverDescriptions.has(address)) { - serverDescriptions.set(address, new ServerDescription(address)); - } - }); - - // Remove hosts not in the response. - const currentAddresses = Array.from(serverDescriptions.keys()); - const responseAddresses = serverDescription.allHosts; - currentAddresses.filter(addr => responseAddresses.indexOf(addr) === -1).forEach(address => { - serverDescriptions.delete(address); - }); - - return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId]; -} - -function updateRsWithPrimaryFromMember(serverDescriptions, setName, serverDescription) { - if (setName == null) { - throw new TypeError('setName is required'); - } - - if ( - setName !== serverDescription.setName || - (serverDescription.me && serverDescription.address !== serverDescription.me) - ) { - serverDescriptions.delete(serverDescription.address); - } - - return checkHasPrimary(serverDescriptions); -} - -function updateRsNoPrimaryFromMember(serverDescriptions, setName, serverDescription) { - let topologyType = TopologyType.ReplicaSetNoPrimary; - - setName = setName || serverDescription.setName; - if (setName !== serverDescription.setName) { - serverDescriptions.delete(serverDescription.address); - return [topologyType, setName]; - } - - serverDescription.allHosts.forEach(address => { - if (!serverDescriptions.has(address)) { - serverDescriptions.set(address, new ServerDescription(address)); - } - }); - - if (serverDescription.me && serverDescription.address !== serverDescription.me) { - serverDescriptions.delete(serverDescription.address); - } - - return [topologyType, setName]; -} - -function checkHasPrimary(serverDescriptions) { - for (const addr of serverDescriptions.keys()) { - if (serverDescriptions.get(addr).type === ServerType.RSPrimary) { - return TopologyType.ReplicaSetWithPrimary; - } - } - - return TopologyType.ReplicaSetNoPrimary; -} - -module.exports = { - TopologyType, - TopologyDescription -}; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/sessions.js b/scripts/2.5/node_modules/mongodb/lib/core/sessions.js deleted file mode 100644 index d15015c8..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/core/sessions.js +++ /dev/null @@ -1,767 +0,0 @@ -'use strict'; - -const retrieveBSON = require('./connection/utils').retrieveBSON; -const EventEmitter = require('events'); -const BSON = retrieveBSON(); -const Binary = BSON.Binary; -const uuidV4 = require('./utils').uuidV4; -const MongoError = require('./error').MongoError; -const isRetryableError = require('././error').isRetryableError; -const MongoNetworkError = require('./error').MongoNetworkError; -const MongoWriteConcernError = require('./error').MongoWriteConcernError; -const Transaction = require('./transactions').Transaction; -const TxnState = require('./transactions').TxnState; -const isPromiseLike = require('./utils').isPromiseLike; -const ReadPreference = require('./topologies/read_preference'); -const isTransactionCommand = require('./transactions').isTransactionCommand; -const resolveClusterTime = require('./topologies/shared').resolveClusterTime; -const isSharded = require('./wireprotocol/shared').isSharded; -const maxWireVersion = require('./utils').maxWireVersion; - -const minWireVersionForShardedTransactions = 8; - -function assertAlive(session, callback) { - if (session.serverSession == null) { - const error = new MongoError('Cannot use a session that has ended'); - if (typeof callback === 'function') { - callback(error, null); - return false; - } - - throw error; - } - - return true; -} - -/** - * Options to pass when creating a Client Session - * @typedef {Object} SessionOptions - * @property {boolean} [causalConsistency=true] Whether causal consistency should be enabled on this session - * @property {TransactionOptions} [defaultTransactionOptions] The default TransactionOptions to use for transactions started on this session. - */ - -/** - * A BSON document reflecting the lsid of a {@link ClientSession} - * @typedef {Object} SessionId - */ - -/** - * A class representing a client session on the server - * WARNING: not meant to be instantiated directly. - * @class - * @hideconstructor - */ -class ClientSession extends EventEmitter { - /** - * Create a client session. - * WARNING: not meant to be instantiated directly - * - * @param {Topology} topology The current client's topology (Internal Class) - * @param {ServerSessionPool} sessionPool The server session pool (Internal Class) - * @param {SessionOptions} [options] Optional settings - * @param {Object} [clientOptions] Optional settings provided when creating a client in the porcelain driver - */ - constructor(topology, sessionPool, options, clientOptions) { - super(); - - if (topology == null) { - throw new Error('ClientSession requires a topology'); - } - - if (sessionPool == null || !(sessionPool instanceof ServerSessionPool)) { - throw new Error('ClientSession requires a ServerSessionPool'); - } - - options = options || {}; - clientOptions = clientOptions || {}; - - this.topology = topology; - this.sessionPool = sessionPool; - this.hasEnded = false; - this.serverSession = sessionPool.acquire(); - this.clientOptions = clientOptions; - - this.supports = { - causalConsistency: - typeof options.causalConsistency !== 'undefined' ? options.causalConsistency : true - }; - - this.clusterTime = options.initialClusterTime; - - this.operationTime = null; - this.explicit = !!options.explicit; - this.owner = options.owner; - this.defaultTransactionOptions = Object.assign({}, options.defaultTransactionOptions); - this.transaction = new Transaction(); - } - - /** - * The server id associated with this session - * @type {SessionId} - */ - get id() { - return this.serverSession.id; - } - - /** - * Ends this session on the server - * - * @param {Object} [options] Optional settings. Currently reserved for future use - * @param {Function} [callback] Optional callback for completion of this operation - */ - endSession(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - if (this.hasEnded) { - if (typeof callback === 'function') callback(null, null); - return; - } - - if (this.serverSession && this.inTransaction()) { - this.abortTransaction(); // pass in callback? - } - - // mark the session as ended, and emit a signal - this.hasEnded = true; - this.emit('ended', this); - - // release the server session back to the pool - this.sessionPool.release(this.serverSession); - this.serverSession = null; - - // spec indicates that we should ignore all errors for `endSessions` - if (typeof callback === 'function') callback(null, null); - } - - /** - * Advances the operationTime for a ClientSession. - * - * @param {Timestamp} operationTime the `BSON.Timestamp` of the operation type it is desired to advance to - */ - advanceOperationTime(operationTime) { - if (this.operationTime == null) { - this.operationTime = operationTime; - return; - } - - if (operationTime.greaterThan(this.operationTime)) { - this.operationTime = operationTime; - } - } - - /** - * Used to determine if this session equals another - * @param {ClientSession} session - * @return {boolean} true if the sessions are equal - */ - equals(session) { - if (!(session instanceof ClientSession)) { - return false; - } - - return this.id.id.buffer.equals(session.id.id.buffer); - } - - /** - * Increment the transaction number on the internal ServerSession - */ - incrementTransactionNumber() { - this.serverSession.txnNumber++; - } - - /** - * @returns {boolean} whether this session is currently in a transaction or not - */ - inTransaction() { - return this.transaction.isActive; - } - - /** - * Starts a new transaction with the given options. - * - * @param {TransactionOptions} options Options for the transaction - */ - startTransaction(options) { - assertAlive(this); - if (this.inTransaction()) { - throw new MongoError('Transaction already in progress'); - } - - const topologyMaxWireVersion = maxWireVersion(this.topology); - if ( - isSharded(this.topology) && - topologyMaxWireVersion != null && - topologyMaxWireVersion < minWireVersionForShardedTransactions - ) { - throw new MongoError('Transactions are not supported on sharded clusters in MongoDB < 4.2.'); - } - - // increment txnNumber - this.incrementTransactionNumber(); - - // create transaction state - this.transaction = new Transaction( - Object.assign({}, this.clientOptions, options || this.defaultTransactionOptions) - ); - - this.transaction.transition(TxnState.STARTING_TRANSACTION); - } - - /** - * Commits the currently active transaction in this session. - * - * @param {Function} [callback] optional callback for completion of this operation - * @return {Promise} A promise is returned if no callback is provided - */ - commitTransaction(callback) { - if (typeof callback === 'function') { - endTransaction(this, 'commitTransaction', callback); - return; - } - - return new Promise((resolve, reject) => { - endTransaction( - this, - 'commitTransaction', - (err, reply) => (err ? reject(err) : resolve(reply)) - ); - }); - } - - /** - * Aborts the currently active transaction in this session. - * - * @param {Function} [callback] optional callback for completion of this operation - * @return {Promise} A promise is returned if no callback is provided - */ - abortTransaction(callback) { - if (typeof callback === 'function') { - endTransaction(this, 'abortTransaction', callback); - return; - } - - return new Promise((resolve, reject) => { - endTransaction( - this, - 'abortTransaction', - (err, reply) => (err ? reject(err) : resolve(reply)) - ); - }); - } - - /** - * This is here to ensure that ClientSession is never serialized to BSON. - * @ignore - */ - toBSON() { - throw new Error('ClientSession cannot be serialized to BSON.'); - } - - /** - * A user provided function to be run within a transaction - * - * @callback WithTransactionCallback - * @param {ClientSession} session The parent session of the transaction running the operation. This should be passed into each operation within the lambda. - * @returns {Promise} The resulting Promise of operations run within this transaction - */ - - /** - * Runs a provided lambda within a transaction, retrying either the commit operation - * or entire transaction as needed (and when the error permits) to better ensure that - * the transaction can complete successfully. - * - * IMPORTANT: This method requires the user to return a Promise, all lambdas that do not - * return a Promise will result in undefined behavior. - * - * @param {WithTransactionCallback} fn - * @param {TransactionOptions} [options] Optional settings for the transaction - */ - withTransaction(fn, options) { - const startTime = Date.now(); - return attemptTransaction(this, startTime, fn, options); - } -} - -const MAX_WITH_TRANSACTION_TIMEOUT = 120000; -const UNSATISFIABLE_WRITE_CONCERN_CODE = 100; -const UNKNOWN_REPL_WRITE_CONCERN_CODE = 79; -const MAX_TIME_MS_EXPIRED_CODE = 50; -const NON_DETERMINISTIC_WRITE_CONCERN_ERRORS = new Set([ - 'CannotSatisfyWriteConcern', - 'UnknownReplWriteConcern', - 'UnsatisfiableWriteConcern' -]); - -function hasNotTimedOut(startTime, max) { - return Date.now() - startTime < max; -} - -function isUnknownTransactionCommitResult(err) { - return ( - isMaxTimeMSExpiredError(err) || - (!NON_DETERMINISTIC_WRITE_CONCERN_ERRORS.has(err.codeName) && - err.code !== UNSATISFIABLE_WRITE_CONCERN_CODE && - err.code !== UNKNOWN_REPL_WRITE_CONCERN_CODE) - ); -} - -function isMaxTimeMSExpiredError(err) { - return ( - err.code === MAX_TIME_MS_EXPIRED_CODE || - (err.writeConcernError && err.writeConcernError.code === MAX_TIME_MS_EXPIRED_CODE) - ); -} - -function attemptTransactionCommit(session, startTime, fn, options) { - return session.commitTransaction().catch(err => { - if ( - err instanceof MongoError && - hasNotTimedOut(startTime, MAX_WITH_TRANSACTION_TIMEOUT) && - !isMaxTimeMSExpiredError(err) - ) { - if (err.hasErrorLabel('UnknownTransactionCommitResult')) { - return attemptTransactionCommit(session, startTime, fn, options); - } - - if (err.hasErrorLabel('TransientTransactionError')) { - return attemptTransaction(session, startTime, fn, options); - } - } - - throw err; - }); -} - -const USER_EXPLICIT_TXN_END_STATES = new Set([ - TxnState.NO_TRANSACTION, - TxnState.TRANSACTION_COMMITTED, - TxnState.TRANSACTION_ABORTED -]); - -function userExplicitlyEndedTransaction(session) { - return USER_EXPLICIT_TXN_END_STATES.has(session.transaction.state); -} - -function attemptTransaction(session, startTime, fn, options) { - session.startTransaction(options); - - let promise; - try { - promise = fn(session); - } catch (err) { - promise = Promise.reject(err); - } - - if (!isPromiseLike(promise)) { - session.abortTransaction(); - throw new TypeError('Function provided to `withTransaction` must return a Promise'); - } - - return promise - .then(() => { - if (userExplicitlyEndedTransaction(session)) { - return; - } - - return attemptTransactionCommit(session, startTime, fn, options); - }) - .catch(err => { - function maybeRetryOrThrow(err) { - if ( - err instanceof MongoError && - err.hasErrorLabel('TransientTransactionError') && - hasNotTimedOut(startTime, MAX_WITH_TRANSACTION_TIMEOUT) - ) { - return attemptTransaction(session, startTime, fn, options); - } - - if (isMaxTimeMSExpiredError(err)) { - if (err.errorLabels == null) { - err.errorLabels = []; - } - err.errorLabels.push('UnknownTransactionCommitResult'); - } - - throw err; - } - - if (session.transaction.isActive) { - return session.abortTransaction().then(() => maybeRetryOrThrow(err)); - } - - return maybeRetryOrThrow(err); - }); -} - -function endTransaction(session, commandName, callback) { - if (!assertAlive(session, callback)) { - // checking result in case callback was called - return; - } - - // handle any initial problematic cases - let txnState = session.transaction.state; - - if (txnState === TxnState.NO_TRANSACTION) { - callback(new MongoError('No transaction started')); - return; - } - - if (commandName === 'commitTransaction') { - if ( - txnState === TxnState.STARTING_TRANSACTION || - txnState === TxnState.TRANSACTION_COMMITTED_EMPTY - ) { - // the transaction was never started, we can safely exit here - session.transaction.transition(TxnState.TRANSACTION_COMMITTED_EMPTY); - callback(null, null); - return; - } - - if (txnState === TxnState.TRANSACTION_ABORTED) { - callback(new MongoError('Cannot call commitTransaction after calling abortTransaction')); - return; - } - } else { - if (txnState === TxnState.STARTING_TRANSACTION) { - // the transaction was never started, we can safely exit here - session.transaction.transition(TxnState.TRANSACTION_ABORTED); - callback(null, null); - return; - } - - if (txnState === TxnState.TRANSACTION_ABORTED) { - callback(new MongoError('Cannot call abortTransaction twice')); - return; - } - - if ( - txnState === TxnState.TRANSACTION_COMMITTED || - txnState === TxnState.TRANSACTION_COMMITTED_EMPTY - ) { - callback(new MongoError('Cannot call abortTransaction after calling commitTransaction')); - return; - } - } - - // construct and send the command - const command = { [commandName]: 1 }; - - // apply a writeConcern if specified - let writeConcern; - if (session.transaction.options.writeConcern) { - writeConcern = Object.assign({}, session.transaction.options.writeConcern); - } else if (session.clientOptions && session.clientOptions.w) { - writeConcern = { w: session.clientOptions.w }; - } - - if (txnState === TxnState.TRANSACTION_COMMITTED) { - writeConcern = Object.assign({ wtimeout: 10000 }, writeConcern, { w: 'majority' }); - } - - if (writeConcern) { - Object.assign(command, { writeConcern }); - } - - if (commandName === 'commitTransaction' && session.transaction.options.maxTimeMS) { - Object.assign(command, { maxTimeMS: session.transaction.options.maxTimeMS }); - } - - function commandHandler(e, r) { - if (commandName === 'commitTransaction') { - session.transaction.transition(TxnState.TRANSACTION_COMMITTED); - - if ( - e && - (e instanceof MongoNetworkError || - e instanceof MongoWriteConcernError || - isRetryableError(e) || - isMaxTimeMSExpiredError(e)) - ) { - if (e.errorLabels) { - const idx = e.errorLabels.indexOf('TransientTransactionError'); - if (idx !== -1) { - e.errorLabels.splice(idx, 1); - } - } else { - e.errorLabels = []; - } - - if (isUnknownTransactionCommitResult(e)) { - e.errorLabels.push('UnknownTransactionCommitResult'); - - // per txns spec, must unpin session in this case - session.transaction.unpinServer(); - } - } - } else { - session.transaction.transition(TxnState.TRANSACTION_ABORTED); - } - - callback(e, r); - } - - // The spec indicates that we should ignore all errors on `abortTransaction` - function transactionError(err) { - return commandName === 'commitTransaction' ? err : null; - } - - if ( - // Assumption here that commandName is "commitTransaction" or "abortTransaction" - session.transaction.recoveryToken && - supportsRecoveryToken(session) - ) { - command.recoveryToken = session.transaction.recoveryToken; - } - - // send the command - session.topology.command('admin.$cmd', command, { session }, (err, reply) => { - if (err && isRetryableError(err)) { - // SPEC-1185: apply majority write concern when retrying commitTransaction - if (command.commitTransaction) { - // per txns spec, must unpin session in this case - session.transaction.unpinServer(); - - command.writeConcern = Object.assign({ wtimeout: 10000 }, command.writeConcern, { - w: 'majority' - }); - } - - return session.topology.command('admin.$cmd', command, { session }, (_err, _reply) => - commandHandler(transactionError(_err), _reply) - ); - } - - commandHandler(transactionError(err), reply); - }); -} - -function supportsRecoveryToken(session) { - const topology = session.topology; - return !!topology.s.options.useRecoveryToken; -} - -/** - * Reflects the existence of a session on the server. Can be reused by the session pool. - * WARNING: not meant to be instantiated directly. For internal use only. - * @ignore - */ -class ServerSession { - constructor() { - this.id = { id: new Binary(uuidV4(), Binary.SUBTYPE_UUID) }; - this.lastUse = Date.now(); - this.txnNumber = 0; - this.isDirty = false; - } - - /** - * Determines if the server session has timed out. - * @ignore - * @param {Date} sessionTimeoutMinutes The server's "logicalSessionTimeoutMinutes" - * @return {boolean} true if the session has timed out. - */ - hasTimedOut(sessionTimeoutMinutes) { - // Take the difference of the lastUse timestamp and now, which will result in a value in - // milliseconds, and then convert milliseconds to minutes to compare to `sessionTimeoutMinutes` - const idleTimeMinutes = Math.round( - (((Date.now() - this.lastUse) % 86400000) % 3600000) / 60000 - ); - - return idleTimeMinutes > sessionTimeoutMinutes - 1; - } -} - -/** - * Maintains a pool of Server Sessions. - * For internal use only - * @ignore - */ -class ServerSessionPool { - constructor(topology) { - if (topology == null) { - throw new Error('ServerSessionPool requires a topology'); - } - - this.topology = topology; - this.sessions = []; - } - - /** - * Ends all sessions in the session pool. - * @ignore - */ - endAllPooledSessions() { - if (this.sessions.length) { - this.topology.endSessions(this.sessions.map(session => session.id)); - this.sessions = []; - } - } - - /** - * Acquire a Server Session from the pool. - * Iterates through each session in the pool, removing any stale sessions - * along the way. The first non-stale session found is removed from the - * pool and returned. If no non-stale session is found, a new ServerSession - * is created. - * @ignore - * @returns {ServerSession} - */ - acquire() { - const sessionTimeoutMinutes = this.topology.logicalSessionTimeoutMinutes; - while (this.sessions.length) { - const session = this.sessions.shift(); - if (!session.hasTimedOut(sessionTimeoutMinutes)) { - return session; - } - } - - return new ServerSession(); - } - - /** - * Release a session to the session pool - * Adds the session back to the session pool if the session has not timed out yet. - * This method also removes any stale sessions from the pool. - * @ignore - * @param {ServerSession} session The session to release to the pool - */ - release(session) { - const sessionTimeoutMinutes = this.topology.logicalSessionTimeoutMinutes; - while (this.sessions.length) { - const pooledSession = this.sessions[this.sessions.length - 1]; - if (pooledSession.hasTimedOut(sessionTimeoutMinutes)) { - this.sessions.pop(); - } else { - break; - } - } - - if (!session.hasTimedOut(sessionTimeoutMinutes)) { - if (session.isDirty) { - return; - } - - // otherwise, readd this session to the session pool - this.sessions.unshift(session); - } - } -} - -// TODO: this should be codified in command construction -// @see https://github.com/mongodb/specifications/blob/master/source/read-write-concern/read-write-concern.rst#read-concern -function commandSupportsReadConcern(command, options) { - if ( - command.aggregate || - command.count || - command.distinct || - command.find || - command.parallelCollectionScan || - command.geoNear || - command.geoSearch - ) { - return true; - } - - if (command.mapReduce && options.out && (options.out.inline === 1 || options.out === 'inline')) { - return true; - } - - return false; -} - -/** - * Optionally decorate a command with sessions specific keys - * - * @param {ClientSession} session the session tracking transaction state - * @param {Object} command the command to decorate - * @param {Object} topology the topology for tracking the cluster time - * @param {Object} [options] Optional settings passed to calling operation - * @return {MongoError|null} An error, if some error condition was met - */ -function applySession(session, command, options) { - const serverSession = session.serverSession; - if (serverSession == null) { - // TODO: merge this with `assertAlive`, did not want to throw a try/catch here - return new MongoError('Cannot use a session that has ended'); - } - - // mark the last use of this session, and apply the `lsid` - serverSession.lastUse = Date.now(); - command.lsid = serverSession.id; - - // first apply non-transaction-specific sessions data - const inTransaction = session.inTransaction() || isTransactionCommand(command); - const isRetryableWrite = options.willRetryWrite; - const shouldApplyReadConcern = commandSupportsReadConcern(command); - - if (serverSession.txnNumber && (isRetryableWrite || inTransaction)) { - command.txnNumber = BSON.Long.fromNumber(serverSession.txnNumber); - } - - // now attempt to apply transaction-specific sessions data - if (!inTransaction) { - if (session.transaction.state !== TxnState.NO_TRANSACTION) { - session.transaction.transition(TxnState.NO_TRANSACTION); - } - - // TODO: the following should only be applied to read operation per spec. - // for causal consistency - if (session.supports.causalConsistency && session.operationTime && shouldApplyReadConcern) { - command.readConcern = command.readConcern || {}; - Object.assign(command.readConcern, { afterClusterTime: session.operationTime }); - } - - return; - } - - if (options.readPreference && !options.readPreference.equals(ReadPreference.primary)) { - return new MongoError( - `Read preference in a transaction must be primary, not: ${options.readPreference.mode}` - ); - } - - // `autocommit` must always be false to differentiate from retryable writes - command.autocommit = false; - - if (session.transaction.state === TxnState.STARTING_TRANSACTION) { - session.transaction.transition(TxnState.TRANSACTION_IN_PROGRESS); - command.startTransaction = true; - - const readConcern = - session.transaction.options.readConcern || session.clientOptions.readConcern; - if (readConcern) { - command.readConcern = readConcern; - } - - if (session.supports.causalConsistency && session.operationTime) { - command.readConcern = command.readConcern || {}; - Object.assign(command.readConcern, { afterClusterTime: session.operationTime }); - } - } -} - -function updateSessionFromResponse(session, document) { - if (document.$clusterTime) { - resolveClusterTime(session, document.$clusterTime); - } - - if (document.operationTime && session && session.supports.causalConsistency) { - session.advanceOperationTime(document.operationTime); - } - - if (document.recoveryToken && session && session.inTransaction()) { - session.transaction._recoveryToken = document.recoveryToken; - } -} - -module.exports = { - ClientSession, - ServerSession, - ServerSessionPool, - TxnState, - applySession, - updateSessionFromResponse, - commandSupportsReadConcern -}; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/tools/smoke_plugin.js b/scripts/2.5/node_modules/mongodb/lib/core/tools/smoke_plugin.js deleted file mode 100644 index 22d02986..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/core/tools/smoke_plugin.js +++ /dev/null @@ -1,61 +0,0 @@ -'use strict'; - -var fs = require('fs'); - -/* Note: because this plugin uses process.on('uncaughtException'), only one - * of these can exist at any given time. This plugin and anything else that - * uses process.on('uncaughtException') will conflict. */ -exports.attachToRunner = function(runner, outputFile) { - var smokeOutput = { results: [] }; - var runningTests = {}; - - var integraPlugin = { - beforeTest: function(test, callback) { - test.startTime = Date.now(); - runningTests[test.name] = test; - callback(); - }, - afterTest: function(test, callback) { - smokeOutput.results.push({ - status: test.status, - start: test.startTime, - end: Date.now(), - test_file: test.name, - exit_code: 0, - url: '' - }); - delete runningTests[test.name]; - callback(); - }, - beforeExit: function(obj, callback) { - fs.writeFile(outputFile, JSON.stringify(smokeOutput), function() { - callback(); - }); - } - }; - - // In case of exception, make sure we write file - process.on('uncaughtException', function(err) { - // Mark all currently running tests as failed - for (var testName in runningTests) { - smokeOutput.results.push({ - status: 'fail', - start: runningTests[testName].startTime, - end: Date.now(), - test_file: testName, - exit_code: 0, - url: '' - }); - } - - // write file - fs.writeFileSync(outputFile, JSON.stringify(smokeOutput)); - - // Standard NodeJS uncaught exception handler - console.error(err.stack); - process.exit(1); - }); - - runner.plugin(integraPlugin); - return integraPlugin; -}; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/topologies/mongos.js b/scripts/2.5/node_modules/mongodb/lib/core/topologies/mongos.js deleted file mode 100644 index 681b01fd..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/core/topologies/mongos.js +++ /dev/null @@ -1,1392 +0,0 @@ -'use strict'; - -const inherits = require('util').inherits; -const f = require('util').format; -const EventEmitter = require('events').EventEmitter; -const CoreCursor = require('../cursor').CoreCursor; -const Logger = require('../connection/logger'); -const retrieveBSON = require('../connection/utils').retrieveBSON; -const MongoError = require('../error').MongoError; -const Server = require('./server'); -const clone = require('./shared').clone; -const diff = require('./shared').diff; -const cloneOptions = require('./shared').cloneOptions; -const createClientInfo = require('./shared').createClientInfo; -const SessionMixins = require('./shared').SessionMixins; -const isRetryableWritesSupported = require('./shared').isRetryableWritesSupported; -const relayEvents = require('../utils').relayEvents; -const isRetryableError = require('../error').isRetryableError; -const BSON = retrieveBSON(); -const getMMAPError = require('./shared').getMMAPError; - -/** - * @fileOverview The **Mongos** class is a class that represents a Mongos Proxy topology and is - * used to construct connections. - */ - -// -// States -var DISCONNECTED = 'disconnected'; -var CONNECTING = 'connecting'; -var CONNECTED = 'connected'; -var UNREFERENCED = 'unreferenced'; -var DESTROYING = 'destroying'; -var DESTROYED = 'destroyed'; - -function stateTransition(self, newState) { - var legalTransitions = { - disconnected: [CONNECTING, DESTROYING, DESTROYED, DISCONNECTED], - connecting: [CONNECTING, DESTROYING, DESTROYED, CONNECTED, DISCONNECTED], - connected: [CONNECTED, DISCONNECTED, DESTROYING, DESTROYED, UNREFERENCED], - unreferenced: [UNREFERENCED, DESTROYING, DESTROYED], - destroyed: [DESTROYED] - }; - - // Get current state - var legalStates = legalTransitions[self.state]; - if (legalStates && legalStates.indexOf(newState) !== -1) { - self.state = newState; - } else { - self.s.logger.error( - f( - 'Mongos with id [%s] failed attempted illegal state transition from [%s] to [%s] only following state allowed [%s]', - self.id, - self.state, - newState, - legalStates - ) - ); - } -} - -// -// ReplSet instance id -var id = 1; -var handlers = ['connect', 'close', 'error', 'timeout', 'parseError']; - -/** - * Creates a new Mongos instance - * @class - * @param {array} seedlist A list of seeds for the replicaset - * @param {number} [options.haInterval=5000] The High availability period for replicaset inquiry - * @param {Cursor} [options.cursorFactory=Cursor] The cursor factory class used for all query cursors - * @param {number} [options.size=5] Server connection pool size - * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled - * @param {number} [options.keepAliveInitialDelay=0] Initial delay before TCP keep alive enabled - * @param {number} [options.localThresholdMS=15] Cutoff latency point in MS for MongoS proxy selection - * @param {boolean} [options.noDelay=true] TCP Connection no delay - * @param {number} [options.connectionTimeout=1000] TCP Connection timeout setting - * @param {number} [options.socketTimeout=0] TCP Socket timeout setting - * @param {boolean} [options.ssl=false] Use SSL for connection - * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. - * @param {Buffer} [options.ca] SSL Certificate store binary buffer - * @param {Buffer} [options.crl] SSL Certificate revocation store binary buffer - * @param {Buffer} [options.cert] SSL Certificate binary buffer - * @param {Buffer} [options.key] SSL Key file binary buffer - * @param {string} [options.passphrase] SSL Certificate pass phrase - * @param {string} [options.servername=null] String containing the server name requested via TLS SNI. - * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates - * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits - * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. - * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. - * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. - * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology - * @return {Mongos} A cursor instance - * @fires Mongos#connect - * @fires Mongos#reconnect - * @fires Mongos#joined - * @fires Mongos#left - * @fires Mongos#failed - * @fires Mongos#fullsetup - * @fires Mongos#all - * @fires Mongos#serverHeartbeatStarted - * @fires Mongos#serverHeartbeatSucceeded - * @fires Mongos#serverHeartbeatFailed - * @fires Mongos#topologyOpening - * @fires Mongos#topologyClosed - * @fires Mongos#topologyDescriptionChanged - * @property {string} type the topology type. - * @property {string} parserType the parser type used (c++ or js). - */ -var Mongos = function(seedlist, options) { - options = options || {}; - - // Get replSet Id - this.id = id++; - - // Internal state - this.s = { - options: Object.assign({}, options), - // BSON instance - bson: - options.bson || - new BSON([ - BSON.Binary, - BSON.Code, - BSON.DBRef, - BSON.Decimal128, - BSON.Double, - BSON.Int32, - BSON.Long, - BSON.Map, - BSON.MaxKey, - BSON.MinKey, - BSON.ObjectId, - BSON.BSONRegExp, - BSON.Symbol, - BSON.Timestamp - ]), - // Factory overrides - Cursor: options.cursorFactory || CoreCursor, - // Logger instance - logger: Logger('Mongos', options), - // Seedlist - seedlist: seedlist, - // Ha interval - haInterval: options.haInterval ? options.haInterval : 10000, - // Disconnect handler - disconnectHandler: options.disconnectHandler, - // Server selection index - index: 0, - // Connect function options passed in - connectOptions: {}, - // Are we running in debug mode - debug: typeof options.debug === 'boolean' ? options.debug : false, - // localThresholdMS - localThresholdMS: options.localThresholdMS || 15, - // Client info - clientInfo: createClientInfo(options) - }; - - // Set the client info - this.s.options.clientInfo = createClientInfo(options); - - // Log info warning if the socketTimeout < haInterval as it will cause - // a lot of recycled connections to happen. - if ( - this.s.logger.isWarn() && - this.s.options.socketTimeout !== 0 && - this.s.options.socketTimeout < this.s.haInterval - ) { - this.s.logger.warn( - f( - 'warning socketTimeout %s is less than haInterval %s. This might cause unnecessary server reconnections due to socket timeouts', - this.s.options.socketTimeout, - this.s.haInterval - ) - ); - } - - // Disconnected state - this.state = DISCONNECTED; - - // Current proxies we are connecting to - this.connectingProxies = []; - // Currently connected proxies - this.connectedProxies = []; - // Disconnected proxies - this.disconnectedProxies = []; - // Index of proxy to run operations against - this.index = 0; - // High availability timeout id - this.haTimeoutId = null; - // Last ismaster - this.ismaster = null; - - // Description of the Replicaset - this.topologyDescription = { - topologyType: 'Unknown', - servers: [] - }; - - // Highest clusterTime seen in responses from the current deployment - this.clusterTime = null; - - // Add event listener - EventEmitter.call(this); -}; - -inherits(Mongos, EventEmitter); -Object.assign(Mongos.prototype, SessionMixins); - -Object.defineProperty(Mongos.prototype, 'type', { - enumerable: true, - get: function() { - return 'mongos'; - } -}); - -Object.defineProperty(Mongos.prototype, 'parserType', { - enumerable: true, - get: function() { - return BSON.native ? 'c++' : 'js'; - } -}); - -Object.defineProperty(Mongos.prototype, 'logicalSessionTimeoutMinutes', { - enumerable: true, - get: function() { - if (!this.ismaster) return null; - return this.ismaster.logicalSessionTimeoutMinutes || null; - } -}); - -/** - * Emit event if it exists - * @method - */ -function emitSDAMEvent(self, event, description) { - if (self.listeners(event).length > 0) { - self.emit(event, description); - } -} - -const SERVER_EVENTS = ['serverDescriptionChanged', 'error', 'close', 'timeout', 'parseError']; -function destroyServer(server, options, callback) { - options = options || {}; - SERVER_EVENTS.forEach(event => server.removeAllListeners(event)); - server.destroy(options, callback); -} - -/** - * Initiate server connect - */ -Mongos.prototype.connect = function(options) { - var self = this; - // Add any connect level options to the internal state - this.s.connectOptions = options || {}; - - // Set connecting state - stateTransition(this, CONNECTING); - - // Create server instances - var servers = this.s.seedlist.map(function(x) { - const server = new Server( - Object.assign({}, self.s.options, x, options, { - reconnect: false, - monitoring: false, - parent: self, - clientInfo: clone(self.s.clientInfo) - }) - ); - - relayEvents(server, self, ['serverDescriptionChanged']); - return server; - }); - - // Emit the topology opening event - emitSDAMEvent(this, 'topologyOpening', { topologyId: this.id }); - - // Start all server connections - connectProxies(self, servers); -}; - -/** - * Authenticate the topology. - * @method - * @param {MongoCredentials} credentials The credentials for authentication we are using - * @param {authResultCallback} callback A callback function - */ -Mongos.prototype.auth = function(credentials, callback) { - if (typeof callback === 'function') callback(null, null); -}; - -function handleEvent(self) { - return function() { - if (self.state === DESTROYED || self.state === DESTROYING) { - return; - } - - // Move to list of disconnectedProxies - moveServerFrom(self.connectedProxies, self.disconnectedProxies, this); - // Emit the initial topology - emitTopologyDescriptionChanged(self); - // Emit the left signal - self.emit('left', 'mongos', this); - // Emit the sdam event - self.emit('serverClosed', { - topologyId: self.id, - address: this.name - }); - }; -} - -function handleInitialConnectEvent(self, event) { - return function() { - var _this = this; - - // Destroy the instance - if (self.state === DESTROYED) { - // Emit the initial topology - emitTopologyDescriptionChanged(self); - // Move from connectingProxies - moveServerFrom(self.connectingProxies, self.disconnectedProxies, this); - return this.destroy(); - } - - // Check the type of server - if (event === 'connect') { - // Get last known ismaster - self.ismaster = _this.lastIsMaster(); - - // Is this not a proxy, remove t - if (self.ismaster.msg === 'isdbgrid') { - // Add to the connectd list - for (let i = 0; i < self.connectedProxies.length; i++) { - if (self.connectedProxies[i].name === _this.name) { - // Move from connectingProxies - moveServerFrom(self.connectingProxies, self.disconnectedProxies, _this); - // Emit the initial topology - emitTopologyDescriptionChanged(self); - _this.destroy(); - return self.emit('failed', _this); - } - } - - // Remove the handlers - for (let i = 0; i < handlers.length; i++) { - _this.removeAllListeners(handlers[i]); - } - - // Add stable state handlers - _this.on('error', handleEvent(self, 'error')); - _this.on('close', handleEvent(self, 'close')); - _this.on('timeout', handleEvent(self, 'timeout')); - _this.on('parseError', handleEvent(self, 'parseError')); - - // Move from connecting proxies connected - moveServerFrom(self.connectingProxies, self.connectedProxies, _this); - // Emit the joined event - self.emit('joined', 'mongos', _this); - } else { - // Print warning if we did not find a mongos proxy - if (self.s.logger.isWarn()) { - var message = 'expected mongos proxy, but found replicaset member mongod for server %s'; - // We have a standalone server - if (!self.ismaster.hosts) { - message = 'expected mongos proxy, but found standalone mongod for server %s'; - } - - self.s.logger.warn(f(message, _this.name)); - } - - // This is not a mongos proxy, destroy and remove it completely - _this.destroy(true); - removeProxyFrom(self.connectingProxies, _this); - // Emit the left event - self.emit('left', 'server', _this); - // Emit failed event - self.emit('failed', _this); - } - } else { - moveServerFrom(self.connectingProxies, self.disconnectedProxies, this); - // Emit the left event - self.emit('left', 'mongos', this); - // Emit failed event - self.emit('failed', this); - } - - // Emit the initial topology - emitTopologyDescriptionChanged(self); - - // Trigger topologyMonitor - if (self.connectingProxies.length === 0) { - // Emit connected if we are connected - if (self.connectedProxies.length > 0 && self.state === CONNECTING) { - // Set the state to connected - stateTransition(self, CONNECTED); - // Emit the connect event - self.emit('connect', self); - self.emit('fullsetup', self); - self.emit('all', self); - } else if (self.disconnectedProxies.length === 0) { - // Print warning if we did not find a mongos proxy - if (self.s.logger.isWarn()) { - self.s.logger.warn( - f('no mongos proxies found in seed list, did you mean to connect to a replicaset') - ); - } - - // Emit the error that no proxies were found - return self.emit('error', new MongoError('no mongos proxies found in seed list')); - } - - // Topology monitor - topologyMonitor(self, { firstConnect: true }); - } - }; -} - -function connectProxies(self, servers) { - // Update connectingProxies - self.connectingProxies = self.connectingProxies.concat(servers); - - // Index used to interleaf the server connects, avoiding - // runtime issues on io constrained vm's - var timeoutInterval = 0; - - function connect(server, timeoutInterval) { - setTimeout(function() { - // Emit opening server event - self.emit('serverOpening', { - topologyId: self.id, - address: server.name - }); - - // Emit the initial topology - emitTopologyDescriptionChanged(self); - - // Add event handlers - server.once('close', handleInitialConnectEvent(self, 'close')); - server.once('timeout', handleInitialConnectEvent(self, 'timeout')); - server.once('parseError', handleInitialConnectEvent(self, 'parseError')); - server.once('error', handleInitialConnectEvent(self, 'error')); - server.once('connect', handleInitialConnectEvent(self, 'connect')); - - // Command Monitoring events - relayEvents(server, self, ['commandStarted', 'commandSucceeded', 'commandFailed']); - - // Start connection - server.connect(self.s.connectOptions); - }, timeoutInterval); - } - - // Start all the servers - servers.forEach(server => connect(server, timeoutInterval++)); -} - -function pickProxy(self, session) { - // TODO: Destructure :) - const transaction = session && session.transaction; - - if (transaction && transaction.server) { - if (transaction.server.isConnected()) { - return transaction.server; - } else { - transaction.unpinServer(); - } - } - - // Get the currently connected Proxies - var connectedProxies = self.connectedProxies.slice(0); - - // Set lower bound - var lowerBoundLatency = Number.MAX_VALUE; - - // Determine the lower bound for the Proxies - for (var i = 0; i < connectedProxies.length; i++) { - if (connectedProxies[i].lastIsMasterMS < lowerBoundLatency) { - lowerBoundLatency = connectedProxies[i].lastIsMasterMS; - } - } - - // Filter out the possible servers - connectedProxies = connectedProxies.filter(function(server) { - if ( - server.lastIsMasterMS <= lowerBoundLatency + self.s.localThresholdMS && - server.isConnected() - ) { - return true; - } - }); - - let proxy; - - // We have no connectedProxies pick first of the connected ones - if (connectedProxies.length === 0) { - proxy = self.connectedProxies[0]; - } else { - // Get proxy - proxy = connectedProxies[self.index % connectedProxies.length]; - // Update the index - self.index = (self.index + 1) % connectedProxies.length; - } - - if (transaction && transaction.isActive && proxy && proxy.isConnected()) { - transaction.pinServer(proxy); - } - - // Return the proxy - return proxy; -} - -function moveServerFrom(from, to, proxy) { - for (var i = 0; i < from.length; i++) { - if (from[i].name === proxy.name) { - from.splice(i, 1); - } - } - - for (i = 0; i < to.length; i++) { - if (to[i].name === proxy.name) { - to.splice(i, 1); - } - } - - to.push(proxy); -} - -function removeProxyFrom(from, proxy) { - for (var i = 0; i < from.length; i++) { - if (from[i].name === proxy.name) { - from.splice(i, 1); - } - } -} - -function reconnectProxies(self, proxies, callback) { - // Count lefts - var count = proxies.length; - - // Handle events - var _handleEvent = function(self, event) { - return function() { - var _self = this; - count = count - 1; - - // Destroyed - if (self.state === DESTROYED || self.state === DESTROYING || self.state === UNREFERENCED) { - moveServerFrom(self.connectingProxies, self.disconnectedProxies, _self); - return this.destroy(); - } - - if (event === 'connect') { - // Destroyed - if (self.state === DESTROYED || self.state === DESTROYING || self.state === UNREFERENCED) { - moveServerFrom(self.connectingProxies, self.disconnectedProxies, _self); - return _self.destroy(); - } - - // Remove the handlers - for (var i = 0; i < handlers.length; i++) { - _self.removeAllListeners(handlers[i]); - } - - // Add stable state handlers - _self.on('error', handleEvent(self, 'error')); - _self.on('close', handleEvent(self, 'close')); - _self.on('timeout', handleEvent(self, 'timeout')); - _self.on('parseError', handleEvent(self, 'parseError')); - - // Move to the connected servers - moveServerFrom(self.connectingProxies, self.connectedProxies, _self); - // Emit topology Change - emitTopologyDescriptionChanged(self); - // Emit joined event - self.emit('joined', 'mongos', _self); - } else { - // Move from connectingProxies - moveServerFrom(self.connectingProxies, self.disconnectedProxies, _self); - this.destroy(); - } - - // Are we done finish up callback - if (count === 0) { - callback(); - } - }; - }; - - // No new servers - if (count === 0) { - return callback(); - } - - // Execute method - function execute(_server, i) { - setTimeout(function() { - // Destroyed - if (self.state === DESTROYED || self.state === DESTROYING || self.state === UNREFERENCED) { - return; - } - - // Create a new server instance - var server = new Server( - Object.assign({}, self.s.options, { - host: _server.name.split(':')[0], - port: parseInt(_server.name.split(':')[1], 10), - reconnect: false, - monitoring: false, - parent: self, - clientInfo: clone(self.s.clientInfo) - }) - ); - - destroyServer(_server, { force: true }); - removeProxyFrom(self.disconnectedProxies, _server); - - // Relay the server description change - relayEvents(server, self, ['serverDescriptionChanged']); - - // Emit opening server event - self.emit('serverOpening', { - topologyId: server.s.topologyId !== -1 ? server.s.topologyId : self.id, - address: server.name - }); - - // Add temp handlers - server.once('connect', _handleEvent(self, 'connect')); - server.once('close', _handleEvent(self, 'close')); - server.once('timeout', _handleEvent(self, 'timeout')); - server.once('error', _handleEvent(self, 'error')); - server.once('parseError', _handleEvent(self, 'parseError')); - - // Command Monitoring events - relayEvents(server, self, ['commandStarted', 'commandSucceeded', 'commandFailed']); - - // Connect to proxy - self.connectingProxies.push(server); - server.connect(self.s.connectOptions); - }, i); - } - - // Create new instances - for (var i = 0; i < proxies.length; i++) { - execute(proxies[i], i); - } -} - -function topologyMonitor(self, options) { - options = options || {}; - - // no need to set up the monitor if we're already closed - if (self.state === DESTROYED || self.state === DESTROYING || self.state === UNREFERENCED) { - return; - } - - // Set momitoring timeout - self.haTimeoutId = setTimeout(function() { - if (self.state === DESTROYED || self.state === DESTROYING || self.state === UNREFERENCED) { - return; - } - - // If we have a primary and a disconnect handler, execute - // buffered operations - if (self.isConnected() && self.s.disconnectHandler) { - self.s.disconnectHandler.execute(); - } - - // Get the connectingServers - var proxies = self.connectedProxies.slice(0); - // Get the count - var count = proxies.length; - - // If the count is zero schedule a new fast - function pingServer(_self, _server, cb) { - // Measure running time - var start = new Date().getTime(); - - // Emit the server heartbeat start - emitSDAMEvent(self, 'serverHeartbeatStarted', { connectionId: _server.name }); - - // Execute ismaster - _server.command( - 'admin.$cmd', - { - ismaster: true - }, - { - monitoring: true, - socketTimeout: self.s.options.connectionTimeout || 2000 - }, - function(err, r) { - if ( - self.state === DESTROYED || - self.state === DESTROYING || - self.state === UNREFERENCED - ) { - // Move from connectingProxies - moveServerFrom(self.connectedProxies, self.disconnectedProxies, _server); - _server.destroy(); - return cb(err, r); - } - - // Calculate latency - var latencyMS = new Date().getTime() - start; - - // We had an error, remove it from the state - if (err) { - // Emit the server heartbeat failure - emitSDAMEvent(self, 'serverHeartbeatFailed', { - durationMS: latencyMS, - failure: err, - connectionId: _server.name - }); - // Move from connected proxies to disconnected proxies - moveServerFrom(self.connectedProxies, self.disconnectedProxies, _server); - } else { - // Update the server ismaster - _server.ismaster = r.result; - _server.lastIsMasterMS = latencyMS; - - // Server heart beat event - emitSDAMEvent(self, 'serverHeartbeatSucceeded', { - durationMS: latencyMS, - reply: r.result, - connectionId: _server.name - }); - } - - cb(err, r); - } - ); - } - - // No proxies initiate monitor again - if (proxies.length === 0) { - // Emit close event if any listeners registered - if (self.listeners('close').length > 0 && self.state === CONNECTING) { - self.emit('error', new MongoError('no mongos proxy available')); - } else { - self.emit('close', self); - } - - // Attempt to connect to any unknown servers - return reconnectProxies(self, self.disconnectedProxies, function() { - if (self.state === DESTROYED || self.state === DESTROYING || self.state === UNREFERENCED) { - return; - } - - // Are we connected ? emit connect event - if (self.state === CONNECTING && options.firstConnect) { - self.emit('connect', self); - self.emit('fullsetup', self); - self.emit('all', self); - } else if (self.isConnected()) { - self.emit('reconnect', self); - } else if (!self.isConnected() && self.listeners('close').length > 0) { - self.emit('close', self); - } - - // Perform topology monitor - topologyMonitor(self); - }); - } - - // Ping all servers - for (var i = 0; i < proxies.length; i++) { - pingServer(self, proxies[i], function() { - count = count - 1; - - if (count === 0) { - if ( - self.state === DESTROYED || - self.state === DESTROYING || - self.state === UNREFERENCED - ) { - return; - } - - // Attempt to connect to any unknown servers - reconnectProxies(self, self.disconnectedProxies, function() { - if ( - self.state === DESTROYED || - self.state === DESTROYING || - self.state === UNREFERENCED - ) { - return; - } - - // Perform topology monitor - topologyMonitor(self); - }); - } - }); - } - }, self.s.haInterval); -} - -/** - * Returns the last known ismaster document for this server - * @method - * @return {object} - */ -Mongos.prototype.lastIsMaster = function() { - return this.ismaster; -}; - -/** - * Unref all connections belong to this server - * @method - */ -Mongos.prototype.unref = function() { - // Transition state - stateTransition(this, UNREFERENCED); - // Get all proxies - var proxies = this.connectedProxies.concat(this.connectingProxies); - proxies.forEach(function(x) { - x.unref(); - }); - - clearTimeout(this.haTimeoutId); -}; - -/** - * Destroy the server connection - * @param {boolean} [options.force=false] Force destroy the pool - * @method - */ -Mongos.prototype.destroy = function(options, callback) { - if (typeof options === 'function') { - callback = options; - options = {}; - } - - options = options || {}; - - stateTransition(this, DESTROYING); - if (this.haTimeoutId) { - clearTimeout(this.haTimeoutId); - } - - const proxies = this.connectedProxies.concat(this.connectingProxies); - let serverCount = proxies.length; - const serverDestroyed = () => { - serverCount--; - if (serverCount > 0) { - return; - } - - emitTopologyDescriptionChanged(this); - emitSDAMEvent(this, 'topologyClosed', { topologyId: this.id }); - stateTransition(this, DESTROYED); - if (typeof callback === 'function') { - callback(null, null); - } - }; - - if (serverCount === 0) { - serverDestroyed(); - return; - } - - // Destroy all connecting servers - proxies.forEach(server => { - // Emit the sdam event - this.emit('serverClosed', { - topologyId: this.id, - address: server.name - }); - - destroyServer(server, options, serverDestroyed); - moveServerFrom(this.connectedProxies, this.disconnectedProxies, server); - }); -}; - -/** - * Figure out if the server is connected - * @method - * @return {boolean} - */ -Mongos.prototype.isConnected = function() { - return this.connectedProxies.length > 0; -}; - -/** - * Figure out if the server instance was destroyed by calling destroy - * @method - * @return {boolean} - */ -Mongos.prototype.isDestroyed = function() { - return this.state === DESTROYED; -}; - -// -// Operations -// - -function executeWriteOperation(args, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // TODO: once we drop Node 4, use destructuring either here or in arguments. - const self = args.self; - const op = args.op; - const ns = args.ns; - const ops = args.ops; - - // Pick a server - let server = pickProxy(self, options.session); - // No server found error out - if (!server) return callback(new MongoError('no mongos proxy available')); - - const willRetryWrite = - !args.retrying && - !!options.retryWrites && - options.session && - isRetryableWritesSupported(self) && - !options.session.inTransaction(); - - const handler = (err, result) => { - if (!err) return callback(null, result); - if (!isRetryableError(err) || !willRetryWrite) { - err = getMMAPError(err); - return callback(err); - } - - // Pick another server - server = pickProxy(self, options.session); - - // No server found error out with original error - if (!server) { - return callback(err); - } - - const newArgs = Object.assign({}, args, { retrying: true }); - return executeWriteOperation(newArgs, options, callback); - }; - - if (callback.operationId) { - handler.operationId = callback.operationId; - } - - // increment and assign txnNumber - if (willRetryWrite) { - options.session.incrementTransactionNumber(); - options.willRetryWrite = willRetryWrite; - } - - // rerun the operation - server[op](ns, ops, options, handler); -} - -/** - * Insert one or more documents - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of documents to insert - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {boolean} [options.retryWrites] Enable retryable writes for this operation - * @param {opResultCallback} callback A callback function - */ -Mongos.prototype.insert = function(ns, ops, options, callback) { - if (typeof options === 'function') { - (callback = options), (options = {}), (options = options || {}); - } - - if (this.state === DESTROYED) { - return callback(new MongoError(f('topology was destroyed'))); - } - - // Not connected but we have a disconnecthandler - if (!this.isConnected() && this.s.disconnectHandler != null) { - return this.s.disconnectHandler.add('insert', ns, ops, options, callback); - } - - // No mongos proxy available - if (!this.isConnected()) { - return callback(new MongoError('no mongos proxy available')); - } - - // Execute write operation - executeWriteOperation({ self: this, op: 'insert', ns, ops }, options, callback); -}; - -/** - * Perform one or more update operations - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of updates - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {boolean} [options.retryWrites] Enable retryable writes for this operation - * @param {opResultCallback} callback A callback function - */ -Mongos.prototype.update = function(ns, ops, options, callback) { - if (typeof options === 'function') { - (callback = options), (options = {}), (options = options || {}); - } - - if (this.state === DESTROYED) { - return callback(new MongoError(f('topology was destroyed'))); - } - - // Not connected but we have a disconnecthandler - if (!this.isConnected() && this.s.disconnectHandler != null) { - return this.s.disconnectHandler.add('update', ns, ops, options, callback); - } - - // No mongos proxy available - if (!this.isConnected()) { - return callback(new MongoError('no mongos proxy available')); - } - - // Execute write operation - executeWriteOperation({ self: this, op: 'update', ns, ops }, options, callback); -}; - -/** - * Perform one or more remove operations - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of removes - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {boolean} [options.retryWrites] Enable retryable writes for this operation - * @param {opResultCallback} callback A callback function - */ -Mongos.prototype.remove = function(ns, ops, options, callback) { - if (typeof options === 'function') { - (callback = options), (options = {}), (options = options || {}); - } - - if (this.state === DESTROYED) { - return callback(new MongoError(f('topology was destroyed'))); - } - - // Not connected but we have a disconnecthandler - if (!this.isConnected() && this.s.disconnectHandler != null) { - return this.s.disconnectHandler.add('remove', ns, ops, options, callback); - } - - // No mongos proxy available - if (!this.isConnected()) { - return callback(new MongoError('no mongos proxy available')); - } - - // Execute write operation - executeWriteOperation({ self: this, op: 'remove', ns, ops }, options, callback); -}; - -const RETRYABLE_WRITE_OPERATIONS = ['findAndModify', 'insert', 'update', 'delete']; - -function isWriteCommand(command) { - return RETRYABLE_WRITE_OPERATIONS.some(op => command[op]); -} - -/** - * Execute a command - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object} cmd The command hash - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @param {Connection} [options.connection] Specify connection object to execute command against - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {opResultCallback} callback A callback function - */ -Mongos.prototype.command = function(ns, cmd, options, callback) { - if (typeof options === 'function') { - (callback = options), (options = {}), (options = options || {}); - } - - if (this.state === DESTROYED) { - return callback(new MongoError(f('topology was destroyed'))); - } - - var self = this; - - // Pick a proxy - var server = pickProxy(self, options.session); - - // Topology is not connected, save the call in the provided store to be - // Executed at some point when the handler deems it's reconnected - if ((server == null || !server.isConnected()) && this.s.disconnectHandler != null) { - return this.s.disconnectHandler.add('command', ns, cmd, options, callback); - } - - // No server returned we had an error - if (server == null) { - return callback(new MongoError('no mongos proxy available')); - } - - // Cloned options - var clonedOptions = cloneOptions(options); - clonedOptions.topology = self; - - const willRetryWrite = - !options.retrying && - options.retryWrites && - options.session && - isRetryableWritesSupported(self) && - !options.session.inTransaction() && - isWriteCommand(cmd); - - const cb = (err, result) => { - if (!err) return callback(null, result); - if (!isRetryableError(err)) { - return callback(err); - } - - if (willRetryWrite) { - const newOptions = Object.assign({}, clonedOptions, { retrying: true }); - return this.command(ns, cmd, newOptions, callback); - } - - return callback(err); - }; - - // increment and assign txnNumber - if (willRetryWrite) { - options.session.incrementTransactionNumber(); - options.willRetryWrite = willRetryWrite; - } - - // Execute the command - server.command(ns, cmd, clonedOptions, cb); -}; - -/** - * Get a new cursor - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object|Long} cmd Can be either a command returning a cursor or a cursorId - * @param {object} [options] Options for the cursor - * @param {object} [options.batchSize=0] Batchsize for the operation - * @param {array} [options.documents=[]] Initial documents list for cursor - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {object} [options.topology] The internal topology of the created cursor - * @returns {Cursor} - */ -Mongos.prototype.cursor = function(ns, cmd, options) { - options = options || {}; - const topology = options.topology || this; - - // Set up final cursor type - var FinalCursor = options.cursorFactory || this.s.Cursor; - - // Return the cursor - return new FinalCursor(topology, ns, cmd, options); -}; - -/** - * Selects a server - * - * @method - * @param {function} selector Unused - * @param {ReadPreference} [options.readPreference] Unused - * @param {ClientSession} [options.session] Specify a session if it is being used - * @param {function} callback - */ -Mongos.prototype.selectServer = function(selector, options, callback) { - if (typeof selector === 'function' && typeof callback === 'undefined') - (callback = selector), (selector = undefined), (options = {}); - if (typeof options === 'function') - (callback = options), (options = selector), (selector = undefined); - options = options || {}; - - const server = pickProxy(this, options.session); - if (server == null) { - callback(new MongoError('server selection failed')); - return; - } - - if (this.s.debug) this.emit('pickedServer', null, server); - callback(null, server); -}; - -/** - * All raw connections - * @method - * @return {Connection[]} - */ -Mongos.prototype.connections = function() { - var connections = []; - - for (var i = 0; i < this.connectedProxies.length; i++) { - connections = connections.concat(this.connectedProxies[i].connections()); - } - - return connections; -}; - -function emitTopologyDescriptionChanged(self) { - if (self.listeners('topologyDescriptionChanged').length > 0) { - var topology = 'Unknown'; - if (self.connectedProxies.length > 0) { - topology = 'Sharded'; - } - - // Generate description - var description = { - topologyType: topology, - servers: [] - }; - - // All proxies - var proxies = self.disconnectedProxies.concat(self.connectingProxies); - - // Add all the disconnected proxies - description.servers = description.servers.concat( - proxies.map(function(x) { - var description = x.getDescription(); - description.type = 'Unknown'; - return description; - }) - ); - - // Add all the connected proxies - description.servers = description.servers.concat( - self.connectedProxies.map(function(x) { - var description = x.getDescription(); - description.type = 'Mongos'; - return description; - }) - ); - - // Get the diff - var diffResult = diff(self.topologyDescription, description); - - // Create the result - var result = { - topologyId: self.id, - previousDescription: self.topologyDescription, - newDescription: description, - diff: diffResult - }; - - // Emit the topologyDescription change - if (diffResult.servers.length > 0) { - self.emit('topologyDescriptionChanged', result); - } - - // Set the new description - self.topologyDescription = description; - } -} - -/** - * A mongos connect event, used to verify that the connection is up and running - * - * @event Mongos#connect - * @type {Mongos} - */ - -/** - * A mongos reconnect event, used to verify that the mongos topology has reconnected - * - * @event Mongos#reconnect - * @type {Mongos} - */ - -/** - * A mongos fullsetup event, used to signal that all topology members have been contacted. - * - * @event Mongos#fullsetup - * @type {Mongos} - */ - -/** - * A mongos all event, used to signal that all topology members have been contacted. - * - * @event Mongos#all - * @type {Mongos} - */ - -/** - * A server member left the mongos list - * - * @event Mongos#left - * @type {Mongos} - * @param {string} type The type of member that left (mongos) - * @param {Server} server The server object that left - */ - -/** - * A server member joined the mongos list - * - * @event Mongos#joined - * @type {Mongos} - * @param {string} type The type of member that left (mongos) - * @param {Server} server The server object that joined - */ - -/** - * A server opening SDAM monitoring event - * - * @event Mongos#serverOpening - * @type {object} - */ - -/** - * A server closed SDAM monitoring event - * - * @event Mongos#serverClosed - * @type {object} - */ - -/** - * A server description SDAM change monitoring event - * - * @event Mongos#serverDescriptionChanged - * @type {object} - */ - -/** - * A topology open SDAM event - * - * @event Mongos#topologyOpening - * @type {object} - */ - -/** - * A topology closed SDAM event - * - * @event Mongos#topologyClosed - * @type {object} - */ - -/** - * A topology structure SDAM change event - * - * @event Mongos#topologyDescriptionChanged - * @type {object} - */ - -/** - * A topology serverHeartbeatStarted SDAM event - * - * @event Mongos#serverHeartbeatStarted - * @type {object} - */ - -/** - * A topology serverHeartbeatFailed SDAM event - * - * @event Mongos#serverHeartbeatFailed - * @type {object} - */ - -/** - * A topology serverHeartbeatSucceeded SDAM change event - * - * @event Mongos#serverHeartbeatSucceeded - * @type {object} - */ - -/** - * An event emitted indicating a command was started, if command monitoring is enabled - * - * @event Mongos#commandStarted - * @type {object} - */ - -/** - * An event emitted indicating a command succeeded, if command monitoring is enabled - * - * @event Mongos#commandSucceeded - * @type {object} - */ - -/** - * An event emitted indicating a command failed, if command monitoring is enabled - * - * @event Mongos#commandFailed - * @type {object} - */ - -module.exports = Mongos; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/topologies/read_preference.js b/scripts/2.5/node_modules/mongodb/lib/core/topologies/read_preference.js deleted file mode 100644 index a813ec4f..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/core/topologies/read_preference.js +++ /dev/null @@ -1,202 +0,0 @@ -'use strict'; - -/** - * The **ReadPreference** class is a class that represents a MongoDB ReadPreference and is - * used to construct connections. - * @class - * @param {string} mode A string describing the read preference mode (primary|primaryPreferred|secondary|secondaryPreferred|nearest) - * @param {array} tags The tags object - * @param {object} [options] Additional read preference options - * @param {number} [options.maxStalenessSeconds] Max secondary read staleness in seconds, Minimum value is 90 seconds. - * @see https://docs.mongodb.com/manual/core/read-preference/ - * @return {ReadPreference} - */ -const ReadPreference = function(mode, tags, options) { - if (!ReadPreference.isValid(mode)) { - throw new TypeError(`Invalid read preference mode ${mode}`); - } - - // TODO(major): tags MUST be an array of tagsets - if (tags && !Array.isArray(tags)) { - console.warn( - 'ReadPreference tags must be an array, this will change in the next major version' - ); - - if (typeof tags.maxStalenessSeconds !== 'undefined') { - // this is likely an options object - options = tags; - tags = undefined; - } else { - tags = [tags]; - } - } - - this.mode = mode; - this.tags = tags; - - options = options || {}; - if (options.maxStalenessSeconds != null) { - if (options.maxStalenessSeconds <= 0) { - throw new TypeError('maxStalenessSeconds must be a positive integer'); - } - - this.maxStalenessSeconds = options.maxStalenessSeconds; - - // NOTE: The minimum required wire version is 5 for this read preference. If the existing - // topology has a lower value then a MongoError will be thrown during server selection. - this.minWireVersion = 5; - } - - if (this.mode === ReadPreference.PRIMARY) { - if (this.tags && Array.isArray(this.tags) && this.tags.length > 0) { - throw new TypeError('Primary read preference cannot be combined with tags'); - } - - if (this.maxStalenessSeconds) { - throw new TypeError('Primary read preference cannot be combined with maxStalenessSeconds'); - } - } -}; - -// Support the deprecated `preference` property introduced in the porcelain layer -Object.defineProperty(ReadPreference.prototype, 'preference', { - enumerable: true, - get: function() { - return this.mode; - } -}); - -/* - * Read preference mode constants - */ -ReadPreference.PRIMARY = 'primary'; -ReadPreference.PRIMARY_PREFERRED = 'primaryPreferred'; -ReadPreference.SECONDARY = 'secondary'; -ReadPreference.SECONDARY_PREFERRED = 'secondaryPreferred'; -ReadPreference.NEAREST = 'nearest'; - -const VALID_MODES = [ - ReadPreference.PRIMARY, - ReadPreference.PRIMARY_PREFERRED, - ReadPreference.SECONDARY, - ReadPreference.SECONDARY_PREFERRED, - ReadPreference.NEAREST, - null -]; - -/** - * Construct a ReadPreference given an options object. - * - * @param {object} options The options object from which to extract the read preference. - * @return {ReadPreference} - */ -ReadPreference.fromOptions = function(options) { - const readPreference = options.readPreference; - const readPreferenceTags = options.readPreferenceTags; - - if (readPreference == null) { - return null; - } - - if (typeof readPreference === 'string') { - return new ReadPreference(readPreference, readPreferenceTags); - } else if (!(readPreference instanceof ReadPreference) && typeof readPreference === 'object') { - const mode = readPreference.mode || readPreference.preference; - if (mode && typeof mode === 'string') { - return new ReadPreference(mode, readPreference.tags, { - maxStalenessSeconds: readPreference.maxStalenessSeconds - }); - } - } - - return readPreference; -}; - -/** - * Validate if a mode is legal - * - * @method - * @param {string} mode The string representing the read preference mode. - * @return {boolean} True if a mode is valid - */ -ReadPreference.isValid = function(mode) { - return VALID_MODES.indexOf(mode) !== -1; -}; - -/** - * Validate if a mode is legal - * - * @method - * @param {string} mode The string representing the read preference mode. - * @return {boolean} True if a mode is valid - */ -ReadPreference.prototype.isValid = function(mode) { - return ReadPreference.isValid(typeof mode === 'string' ? mode : this.mode); -}; - -const needSlaveOk = ['primaryPreferred', 'secondary', 'secondaryPreferred', 'nearest']; - -/** - * Indicates that this readPreference needs the "slaveOk" bit when sent over the wire - * @method - * @return {boolean} - * @see https://docs.mongodb.com/manual/reference/mongodb-wire-protocol/#op-query - */ -ReadPreference.prototype.slaveOk = function() { - return needSlaveOk.indexOf(this.mode) !== -1; -}; - -/** - * Are the two read preference equal - * @method - * @param {ReadPreference} readPreference The read preference with which to check equality - * @return {boolean} True if the two ReadPreferences are equivalent - */ -ReadPreference.prototype.equals = function(readPreference) { - return readPreference.mode === this.mode; -}; - -/** - * Return JSON representation - * @method - * @return {Object} A JSON representation of the ReadPreference - */ -ReadPreference.prototype.toJSON = function() { - const readPreference = { mode: this.mode }; - if (Array.isArray(this.tags)) readPreference.tags = this.tags; - if (this.maxStalenessSeconds) readPreference.maxStalenessSeconds = this.maxStalenessSeconds; - return readPreference; -}; - -/** - * Primary read preference - * @member - * @type {ReadPreference} - */ -ReadPreference.primary = new ReadPreference('primary'); -/** - * Primary Preferred read preference - * @member - * @type {ReadPreference} - */ -ReadPreference.primaryPreferred = new ReadPreference('primaryPreferred'); -/** - * Secondary read preference - * @member - * @type {ReadPreference} - */ -ReadPreference.secondary = new ReadPreference('secondary'); -/** - * Secondary Preferred read preference - * @member - * @type {ReadPreference} - */ -ReadPreference.secondaryPreferred = new ReadPreference('secondaryPreferred'); -/** - * Nearest read preference - * @member - * @type {ReadPreference} - */ -ReadPreference.nearest = new ReadPreference('nearest'); - -module.exports = ReadPreference; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/topologies/replset.js b/scripts/2.5/node_modules/mongodb/lib/core/topologies/replset.js deleted file mode 100644 index 89403ea4..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/core/topologies/replset.js +++ /dev/null @@ -1,1553 +0,0 @@ -'use strict'; - -const inherits = require('util').inherits; -const f = require('util').format; -const EventEmitter = require('events').EventEmitter; -const ReadPreference = require('./read_preference'); -const CoreCursor = require('../cursor').CoreCursor; -const retrieveBSON = require('../connection/utils').retrieveBSON; -const Logger = require('../connection/logger'); -const MongoError = require('../error').MongoError; -const Server = require('./server'); -const ReplSetState = require('./replset_state'); -const clone = require('./shared').clone; -const Timeout = require('./shared').Timeout; -const Interval = require('./shared').Interval; -const createClientInfo = require('./shared').createClientInfo; -const SessionMixins = require('./shared').SessionMixins; -const isRetryableWritesSupported = require('./shared').isRetryableWritesSupported; -const relayEvents = require('../utils').relayEvents; -const isRetryableError = require('../error').isRetryableError; -const BSON = retrieveBSON(); -const calculateDurationInMs = require('../utils').calculateDurationInMs; -const getMMAPError = require('./shared').getMMAPError; - -// -// States -var DISCONNECTED = 'disconnected'; -var CONNECTING = 'connecting'; -var CONNECTED = 'connected'; -var UNREFERENCED = 'unreferenced'; -var DESTROYED = 'destroyed'; - -function stateTransition(self, newState) { - var legalTransitions = { - disconnected: [CONNECTING, DESTROYED, DISCONNECTED], - connecting: [CONNECTING, DESTROYED, CONNECTED, DISCONNECTED], - connected: [CONNECTED, DISCONNECTED, DESTROYED, UNREFERENCED], - unreferenced: [UNREFERENCED, DESTROYED], - destroyed: [DESTROYED] - }; - - // Get current state - var legalStates = legalTransitions[self.state]; - if (legalStates && legalStates.indexOf(newState) !== -1) { - self.state = newState; - } else { - self.s.logger.error( - f( - 'Pool with id [%s] failed attempted illegal state transition from [%s] to [%s] only following state allowed [%s]', - self.id, - self.state, - newState, - legalStates - ) - ); - } -} - -// -// ReplSet instance id -var id = 1; -var handlers = ['connect', 'close', 'error', 'timeout', 'parseError']; - -/** - * Creates a new Replset instance - * @class - * @param {array} seedlist A list of seeds for the replicaset - * @param {boolean} options.setName The Replicaset set name - * @param {boolean} [options.secondaryOnlyConnectionAllowed=false] Allow connection to a secondary only replicaset - * @param {number} [options.haInterval=10000] The High availability period for replicaset inquiry - * @param {boolean} [options.emitError=false] Server will emit errors events - * @param {Cursor} [options.cursorFactory=Cursor] The cursor factory class used for all query cursors - * @param {number} [options.size=5] Server connection pool size - * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled - * @param {number} [options.keepAliveInitialDelay=0] Initial delay before TCP keep alive enabled - * @param {boolean} [options.noDelay=true] TCP Connection no delay - * @param {number} [options.connectionTimeout=10000] TCP Connection timeout setting - * @param {number} [options.socketTimeout=0] TCP Socket timeout setting - * @param {boolean} [options.ssl=false] Use SSL for connection - * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. - * @param {Buffer} [options.ca] SSL Certificate store binary buffer - * @param {Buffer} [options.crl] SSL Certificate revocation store binary buffer - * @param {Buffer} [options.cert] SSL Certificate binary buffer - * @param {Buffer} [options.key] SSL Key file binary buffer - * @param {string} [options.passphrase] SSL Certificate pass phrase - * @param {string} [options.servername=null] String containing the server name requested via TLS SNI. - * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates - * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits - * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. - * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. - * @param {number} [options.pingInterval=5000] Ping interval to check the response time to the different servers - * @param {number} [options.localThresholdMS=15] Cutoff latency point in MS for Replicaset member selection - * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. - * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology - * @return {ReplSet} A cursor instance - * @fires ReplSet#connect - * @fires ReplSet#ha - * @fires ReplSet#joined - * @fires ReplSet#left - * @fires ReplSet#failed - * @fires ReplSet#fullsetup - * @fires ReplSet#all - * @fires ReplSet#error - * @fires ReplSet#serverHeartbeatStarted - * @fires ReplSet#serverHeartbeatSucceeded - * @fires ReplSet#serverHeartbeatFailed - * @fires ReplSet#topologyOpening - * @fires ReplSet#topologyClosed - * @fires ReplSet#topologyDescriptionChanged - * @property {string} type the topology type. - * @property {string} parserType the parser type used (c++ or js). - */ -var ReplSet = function(seedlist, options) { - var self = this; - options = options || {}; - - // Validate seedlist - if (!Array.isArray(seedlist)) throw new MongoError('seedlist must be an array'); - // Validate list - if (seedlist.length === 0) throw new MongoError('seedlist must contain at least one entry'); - // Validate entries - seedlist.forEach(function(e) { - if (typeof e.host !== 'string' || typeof e.port !== 'number') - throw new MongoError('seedlist entry must contain a host and port'); - }); - - // Add event listener - EventEmitter.call(this); - - // Get replSet Id - this.id = id++; - - // Get the localThresholdMS - var localThresholdMS = options.localThresholdMS || 15; - // Backward compatibility - if (options.acceptableLatency) localThresholdMS = options.acceptableLatency; - - // Create a logger - var logger = Logger('ReplSet', options); - - // Internal state - this.s = { - options: Object.assign({}, options), - // BSON instance - bson: - options.bson || - new BSON([ - BSON.Binary, - BSON.Code, - BSON.DBRef, - BSON.Decimal128, - BSON.Double, - BSON.Int32, - BSON.Long, - BSON.Map, - BSON.MaxKey, - BSON.MinKey, - BSON.ObjectId, - BSON.BSONRegExp, - BSON.Symbol, - BSON.Timestamp - ]), - // Factory overrides - Cursor: options.cursorFactory || CoreCursor, - // Logger instance - logger: logger, - // Seedlist - seedlist: seedlist, - // Replicaset state - replicaSetState: new ReplSetState({ - id: this.id, - setName: options.setName, - acceptableLatency: localThresholdMS, - heartbeatFrequencyMS: options.haInterval ? options.haInterval : 10000, - logger: logger - }), - // Current servers we are connecting to - connectingServers: [], - // Ha interval - haInterval: options.haInterval ? options.haInterval : 10000, - // Minimum heartbeat frequency used if we detect a server close - minHeartbeatFrequencyMS: 500, - // Disconnect handler - disconnectHandler: options.disconnectHandler, - // Server selection index - index: 0, - // Connect function options passed in - connectOptions: {}, - // Are we running in debug mode - debug: typeof options.debug === 'boolean' ? options.debug : false, - // Client info - clientInfo: createClientInfo(options) - }; - - // Add handler for topology change - this.s.replicaSetState.on('topologyDescriptionChanged', function(r) { - self.emit('topologyDescriptionChanged', r); - }); - - // Log info warning if the socketTimeout < haInterval as it will cause - // a lot of recycled connections to happen. - if ( - this.s.logger.isWarn() && - this.s.options.socketTimeout !== 0 && - this.s.options.socketTimeout < this.s.haInterval - ) { - this.s.logger.warn( - f( - 'warning socketTimeout %s is less than haInterval %s. This might cause unnecessary server reconnections due to socket timeouts', - this.s.options.socketTimeout, - this.s.haInterval - ) - ); - } - - // Add forwarding of events from state handler - var types = ['joined', 'left']; - types.forEach(function(x) { - self.s.replicaSetState.on(x, function(t, s) { - self.emit(x, t, s); - }); - }); - - // Connect stat - this.initialConnectState = { - connect: false, - fullsetup: false, - all: false - }; - - // Disconnected state - this.state = DISCONNECTED; - this.haTimeoutId = null; - // Last ismaster - this.ismaster = null; - // Contains the intervalId - this.intervalIds = []; - - // Highest clusterTime seen in responses from the current deployment - this.clusterTime = null; -}; - -inherits(ReplSet, EventEmitter); -Object.assign(ReplSet.prototype, SessionMixins); - -Object.defineProperty(ReplSet.prototype, 'type', { - enumerable: true, - get: function() { - return 'replset'; - } -}); - -Object.defineProperty(ReplSet.prototype, 'parserType', { - enumerable: true, - get: function() { - return BSON.native ? 'c++' : 'js'; - } -}); - -Object.defineProperty(ReplSet.prototype, 'logicalSessionTimeoutMinutes', { - enumerable: true, - get: function() { - return this.s.replicaSetState.logicalSessionTimeoutMinutes || null; - } -}); - -function rexecuteOperations(self) { - // If we have a primary and a disconnect handler, execute - // buffered operations - if (self.s.replicaSetState.hasPrimaryAndSecondary() && self.s.disconnectHandler) { - self.s.disconnectHandler.execute(); - } else if (self.s.replicaSetState.hasPrimary() && self.s.disconnectHandler) { - self.s.disconnectHandler.execute({ executePrimary: true }); - } else if (self.s.replicaSetState.hasSecondary() && self.s.disconnectHandler) { - self.s.disconnectHandler.execute({ executeSecondary: true }); - } -} - -function connectNewServers(self, servers, callback) { - // Count lefts - var count = servers.length; - var error = null; - - // Handle events - var _handleEvent = function(self, event) { - return function(err) { - var _self = this; - count = count - 1; - - // Destroyed - if (self.state === DESTROYED || self.state === UNREFERENCED) { - return this.destroy({ force: true }); - } - - if (event === 'connect') { - // Destroyed - if (self.state === DESTROYED || self.state === UNREFERENCED) { - return _self.destroy({ force: true }); - } - - // Update the state - var result = self.s.replicaSetState.update(_self); - // Update the state with the new server - if (result) { - // Primary lastIsMaster store it - if (_self.lastIsMaster() && _self.lastIsMaster().ismaster) { - self.ismaster = _self.lastIsMaster(); - } - - // Remove the handlers - for (let i = 0; i < handlers.length; i++) { - _self.removeAllListeners(handlers[i]); - } - - // Add stable state handlers - _self.on('error', handleEvent(self, 'error')); - _self.on('close', handleEvent(self, 'close')); - _self.on('timeout', handleEvent(self, 'timeout')); - _self.on('parseError', handleEvent(self, 'parseError')); - - // Enalbe the monitoring of the new server - monitorServer(_self.lastIsMaster().me, self, {}); - - // Rexecute any stalled operation - rexecuteOperations(self); - } else { - _self.destroy({ force: true }); - } - } else if (event === 'error') { - error = err; - } - - // Rexecute any stalled operation - rexecuteOperations(self); - - // Are we done finish up callback - if (count === 0) { - callback(error); - } - }; - }; - - // No new servers - if (count === 0) return callback(); - - // Execute method - function execute(_server, i) { - setTimeout(function() { - // Destroyed - if (self.state === DESTROYED || self.state === UNREFERENCED) { - return; - } - - // Create a new server instance - var server = new Server( - Object.assign({}, self.s.options, { - host: _server.split(':')[0], - port: parseInt(_server.split(':')[1], 10), - reconnect: false, - monitoring: false, - parent: self, - clientInfo: clone(self.s.clientInfo) - }) - ); - - // Add temp handlers - server.once('connect', _handleEvent(self, 'connect')); - server.once('close', _handleEvent(self, 'close')); - server.once('timeout', _handleEvent(self, 'timeout')); - server.once('error', _handleEvent(self, 'error')); - server.once('parseError', _handleEvent(self, 'parseError')); - - // SDAM Monitoring events - server.on('serverOpening', e => self.emit('serverOpening', e)); - server.on('serverDescriptionChanged', e => self.emit('serverDescriptionChanged', e)); - server.on('serverClosed', e => self.emit('serverClosed', e)); - - // Command Monitoring events - relayEvents(server, self, ['commandStarted', 'commandSucceeded', 'commandFailed']); - - self.s.connectingServers.push(server); - server.connect(self.s.connectOptions); - }, i); - } - - // Create new instances - for (var i = 0; i < servers.length; i++) { - execute(servers[i], i); - } -} - -// Ping the server -var pingServer = function(self, server, cb) { - // Measure running time - var start = new Date().getTime(); - - // Emit the server heartbeat start - emitSDAMEvent(self, 'serverHeartbeatStarted', { connectionId: server.name }); - - // Execute ismaster - // Set the socketTimeout for a monitoring message to a low number - // Ensuring ismaster calls are timed out quickly - server.command( - 'admin.$cmd', - { - ismaster: true - }, - { - monitoring: true, - socketTimeout: self.s.options.connectionTimeout || 2000 - }, - function(err, r) { - if (self.state === DESTROYED || self.state === UNREFERENCED) { - server.destroy({ force: true }); - return cb(err, r); - } - - // Calculate latency - var latencyMS = new Date().getTime() - start; - - // Set the last updatedTime - var hrtime = process.hrtime(); - server.lastUpdateTime = (hrtime[0] * 1e9 + hrtime[1]) / 1e6; - - // We had an error, remove it from the state - if (err) { - // Emit the server heartbeat failure - emitSDAMEvent(self, 'serverHeartbeatFailed', { - durationMS: latencyMS, - failure: err, - connectionId: server.name - }); - - // Remove server from the state - self.s.replicaSetState.remove(server); - } else { - // Update the server ismaster - server.ismaster = r.result; - - // Check if we have a lastWriteDate convert it to MS - // and store on the server instance for later use - if (server.ismaster.lastWrite && server.ismaster.lastWrite.lastWriteDate) { - server.lastWriteDate = server.ismaster.lastWrite.lastWriteDate.getTime(); - } - - // Do we have a brand new server - if (server.lastIsMasterMS === -1) { - server.lastIsMasterMS = latencyMS; - } else if (server.lastIsMasterMS) { - // After the first measurement, average RTT MUST be computed using an - // exponentially-weighted moving average formula, with a weighting factor (alpha) of 0.2. - // If the prior average is denoted old_rtt, then the new average (new_rtt) is - // computed from a new RTT measurement (x) using the following formula: - // alpha = 0.2 - // new_rtt = alpha * x + (1 - alpha) * old_rtt - server.lastIsMasterMS = 0.2 * latencyMS + (1 - 0.2) * server.lastIsMasterMS; - } - - if (self.s.replicaSetState.update(server)) { - // Primary lastIsMaster store it - if (server.lastIsMaster() && server.lastIsMaster().ismaster) { - self.ismaster = server.lastIsMaster(); - } - } - - // Server heart beat event - emitSDAMEvent(self, 'serverHeartbeatSucceeded', { - durationMS: latencyMS, - reply: r.result, - connectionId: server.name - }); - } - - // Calculate the staleness for this server - self.s.replicaSetState.updateServerMaxStaleness(server, self.s.haInterval); - - // Callback - cb(err, r); - } - ); -}; - -// Each server is monitored in parallel in their own timeout loop -var monitorServer = function(host, self, options) { - // If this is not the initial scan - // Is this server already being monitoried, then skip monitoring - if (!options.haInterval) { - for (var i = 0; i < self.intervalIds.length; i++) { - if (self.intervalIds[i].__host === host) { - return; - } - } - } - - // Get the haInterval - var _process = options.haInterval ? Timeout : Interval; - var _haInterval = options.haInterval ? options.haInterval : self.s.haInterval; - - // Create the interval - var intervalId = new _process(function() { - if (self.state === DESTROYED || self.state === UNREFERENCED) { - // clearInterval(intervalId); - intervalId.stop(); - return; - } - - // Do we already have server connection available for this host - var _server = self.s.replicaSetState.get(host); - - // Check if we have a known server connection and reuse - if (_server) { - // Ping the server - return pingServer(self, _server, function(err) { - if (err) { - // NOTE: should something happen here? - return; - } - - if (self.state === DESTROYED || self.state === UNREFERENCED) { - intervalId.stop(); - return; - } - - // Filter out all called intervaliIds - self.intervalIds = self.intervalIds.filter(function(intervalId) { - return intervalId.isRunning(); - }); - - // Initial sweep - if (_process === Timeout) { - if ( - self.state === CONNECTING && - ((self.s.replicaSetState.hasSecondary() && - self.s.options.secondaryOnlyConnectionAllowed) || - self.s.replicaSetState.hasPrimary()) - ) { - self.state = CONNECTED; - - // Emit connected sign - process.nextTick(function() { - self.emit('connect', self); - }); - - // Start topology interval check - topologyMonitor(self, {}); - } - } else { - if ( - self.state === DISCONNECTED && - ((self.s.replicaSetState.hasSecondary() && - self.s.options.secondaryOnlyConnectionAllowed) || - self.s.replicaSetState.hasPrimary()) - ) { - self.state = CONNECTED; - - // Rexecute any stalled operation - rexecuteOperations(self); - - // Emit connected sign - process.nextTick(function() { - self.emit('reconnect', self); - }); - } - } - - if ( - self.initialConnectState.connect && - !self.initialConnectState.fullsetup && - self.s.replicaSetState.hasPrimaryAndSecondary() - ) { - // Set initial connect state - self.initialConnectState.fullsetup = true; - self.initialConnectState.all = true; - - process.nextTick(function() { - self.emit('fullsetup', self); - self.emit('all', self); - }); - } - }); - } - }, _haInterval); - - // Start the interval - intervalId.start(); - // Add the intervalId host name - intervalId.__host = host; - // Add the intervalId to our list of intervalIds - self.intervalIds.push(intervalId); -}; - -function topologyMonitor(self, options) { - if (self.state === DESTROYED || self.state === UNREFERENCED) return; - options = options || {}; - - // Get the servers - var servers = Object.keys(self.s.replicaSetState.set); - - // Get the haInterval - var _process = options.haInterval ? Timeout : Interval; - var _haInterval = options.haInterval ? options.haInterval : self.s.haInterval; - - if (_process === Timeout) { - return connectNewServers(self, self.s.replicaSetState.unknownServers, function(err) { - // Don't emit errors if the connection was already - if (self.state === DESTROYED || self.state === UNREFERENCED) { - return; - } - - if (!self.s.replicaSetState.hasPrimary() && !self.s.options.secondaryOnlyConnectionAllowed) { - if (err) { - return self.emit('error', err); - } - - self.emit( - 'error', - new MongoError('no primary found in replicaset or invalid replica set name') - ); - return self.destroy({ force: true }); - } else if ( - !self.s.replicaSetState.hasSecondary() && - self.s.options.secondaryOnlyConnectionAllowed - ) { - if (err) { - return self.emit('error', err); - } - - self.emit( - 'error', - new MongoError('no secondary found in replicaset or invalid replica set name') - ); - return self.destroy({ force: true }); - } - - for (var i = 0; i < servers.length; i++) { - monitorServer(servers[i], self, options); - } - }); - } else { - for (var i = 0; i < servers.length; i++) { - monitorServer(servers[i], self, options); - } - } - - // Run the reconnect process - function executeReconnect(self) { - return function() { - if (self.state === DESTROYED || self.state === UNREFERENCED) { - return; - } - - connectNewServers(self, self.s.replicaSetState.unknownServers, function() { - var monitoringFrequencey = self.s.replicaSetState.hasPrimary() - ? _haInterval - : self.s.minHeartbeatFrequencyMS; - - // Create a timeout - self.intervalIds.push(new Timeout(executeReconnect(self), monitoringFrequencey).start()); - }); - }; - } - - // Decide what kind of interval to use - var intervalTime = !self.s.replicaSetState.hasPrimary() - ? self.s.minHeartbeatFrequencyMS - : _haInterval; - - self.intervalIds.push(new Timeout(executeReconnect(self), intervalTime).start()); -} - -function addServerToList(list, server) { - for (var i = 0; i < list.length; i++) { - if (list[i].name.toLowerCase() === server.name.toLowerCase()) return true; - } - - list.push(server); -} - -function handleEvent(self, event) { - return function() { - if (self.state === DESTROYED || self.state === UNREFERENCED) return; - // Debug log - if (self.s.logger.isDebug()) { - self.s.logger.debug( - f('handleEvent %s from server %s in replset with id %s', event, this.name, self.id) - ); - } - - // Remove from the replicaset state - self.s.replicaSetState.remove(this); - - // Are we in a destroyed state return - if (self.state === DESTROYED || self.state === UNREFERENCED) return; - - // If no primary and secondary available - if ( - !self.s.replicaSetState.hasPrimary() && - !self.s.replicaSetState.hasSecondary() && - self.s.options.secondaryOnlyConnectionAllowed - ) { - stateTransition(self, DISCONNECTED); - } else if (!self.s.replicaSetState.hasPrimary()) { - stateTransition(self, DISCONNECTED); - } - - addServerToList(self.s.connectingServers, this); - }; -} - -function shouldTriggerConnect(self) { - const isConnecting = self.state === CONNECTING; - const hasPrimary = self.s.replicaSetState.hasPrimary(); - const hasSecondary = self.s.replicaSetState.hasSecondary(); - const secondaryOnlyConnectionAllowed = self.s.options.secondaryOnlyConnectionAllowed; - const readPreferenceSecondary = - self.s.connectOptions.readPreference && - self.s.connectOptions.readPreference.equals(ReadPreference.secondary); - - return ( - (isConnecting && - ((readPreferenceSecondary && hasSecondary) || (!readPreferenceSecondary && hasPrimary))) || - (hasSecondary && secondaryOnlyConnectionAllowed) - ); -} - -function handleInitialConnectEvent(self, event) { - return function() { - var _this = this; - // Debug log - if (self.s.logger.isDebug()) { - self.s.logger.debug( - f( - 'handleInitialConnectEvent %s from server %s in replset with id %s', - event, - this.name, - self.id - ) - ); - } - - // Destroy the instance - if (self.state === DESTROYED || self.state === UNREFERENCED) { - return this.destroy({ force: true }); - } - - // Check the type of server - if (event === 'connect') { - // Update the state - var result = self.s.replicaSetState.update(_this); - if (result === true) { - // Primary lastIsMaster store it - if (_this.lastIsMaster() && _this.lastIsMaster().ismaster) { - self.ismaster = _this.lastIsMaster(); - } - - // Debug log - if (self.s.logger.isDebug()) { - self.s.logger.debug( - f( - 'handleInitialConnectEvent %s from server %s in replset with id %s has state [%s]', - event, - _this.name, - self.id, - JSON.stringify(self.s.replicaSetState.set) - ) - ); - } - - // Remove the handlers - for (let i = 0; i < handlers.length; i++) { - _this.removeAllListeners(handlers[i]); - } - - // Add stable state handlers - _this.on('error', handleEvent(self, 'error')); - _this.on('close', handleEvent(self, 'close')); - _this.on('timeout', handleEvent(self, 'timeout')); - _this.on('parseError', handleEvent(self, 'parseError')); - - // Do we have a primary or primaryAndSecondary - if (shouldTriggerConnect(self)) { - // We are connected - self.state = CONNECTED; - - // Set initial connect state - self.initialConnectState.connect = true; - // Emit connect event - process.nextTick(function() { - self.emit('connect', self); - }); - - topologyMonitor(self, {}); - } - } else if (result instanceof MongoError) { - _this.destroy({ force: true }); - self.destroy({ force: true }); - return self.emit('error', result); - } else { - _this.destroy({ force: true }); - } - } else { - // Emit failure to connect - self.emit('failed', this); - - addServerToList(self.s.connectingServers, this); - // Remove from the state - self.s.replicaSetState.remove(this); - } - - if ( - self.initialConnectState.connect && - !self.initialConnectState.fullsetup && - self.s.replicaSetState.hasPrimaryAndSecondary() - ) { - // Set initial connect state - self.initialConnectState.fullsetup = true; - self.initialConnectState.all = true; - - process.nextTick(function() { - self.emit('fullsetup', self); - self.emit('all', self); - }); - } - - // Remove from the list from connectingServers - for (var i = 0; i < self.s.connectingServers.length; i++) { - if (self.s.connectingServers[i].equals(this)) { - self.s.connectingServers.splice(i, 1); - } - } - - // Trigger topologyMonitor - if (self.s.connectingServers.length === 0 && self.state === CONNECTING) { - topologyMonitor(self, { haInterval: 1 }); - } - }; -} - -function connectServers(self, servers) { - // Update connectingServers - self.s.connectingServers = self.s.connectingServers.concat(servers); - - // Index used to interleaf the server connects, avoiding - // runtime issues on io constrained vm's - var timeoutInterval = 0; - - function connect(server, timeoutInterval) { - setTimeout(function() { - // Add the server to the state - if (self.s.replicaSetState.update(server)) { - // Primary lastIsMaster store it - if (server.lastIsMaster() && server.lastIsMaster().ismaster) { - self.ismaster = server.lastIsMaster(); - } - } - - // Add event handlers - server.once('close', handleInitialConnectEvent(self, 'close')); - server.once('timeout', handleInitialConnectEvent(self, 'timeout')); - server.once('parseError', handleInitialConnectEvent(self, 'parseError')); - server.once('error', handleInitialConnectEvent(self, 'error')); - server.once('connect', handleInitialConnectEvent(self, 'connect')); - - // SDAM Monitoring events - server.on('serverOpening', e => self.emit('serverOpening', e)); - server.on('serverDescriptionChanged', e => self.emit('serverDescriptionChanged', e)); - server.on('serverClosed', e => self.emit('serverClosed', e)); - - // Command Monitoring events - relayEvents(server, self, ['commandStarted', 'commandSucceeded', 'commandFailed']); - - // Start connection - server.connect(self.s.connectOptions); - }, timeoutInterval); - } - - // Start all the servers - while (servers.length > 0) { - connect(servers.shift(), timeoutInterval++); - } -} - -/** - * Emit event if it exists - * @method - */ -function emitSDAMEvent(self, event, description) { - if (self.listeners(event).length > 0) { - self.emit(event, description); - } -} - -/** - * Initiate server connect - */ -ReplSet.prototype.connect = function(options) { - var self = this; - // Add any connect level options to the internal state - this.s.connectOptions = options || {}; - - // Set connecting state - stateTransition(this, CONNECTING); - - // Create server instances - var servers = this.s.seedlist.map(function(x) { - return new Server( - Object.assign({}, self.s.options, x, options, { - reconnect: false, - monitoring: false, - parent: self, - clientInfo: clone(self.s.clientInfo) - }) - ); - }); - - // Error out as high availbility interval must be < than socketTimeout - if ( - this.s.options.socketTimeout > 0 && - this.s.options.socketTimeout <= this.s.options.haInterval - ) { - return self.emit( - 'error', - new MongoError( - f( - 'haInterval [%s] MS must be set to less than socketTimeout [%s] MS', - this.s.options.haInterval, - this.s.options.socketTimeout - ) - ) - ); - } - - // Emit the topology opening event - emitSDAMEvent(this, 'topologyOpening', { topologyId: this.id }); - // Start all server connections - connectServers(self, servers); -}; - -/** - * Authenticate the topology. - * @method - * @param {MongoCredentials} credentials The credentials for authentication we are using - * @param {authResultCallback} callback A callback function - */ -ReplSet.prototype.auth = function(credentials, callback) { - if (typeof callback === 'function') callback(null, null); -}; - -/** - * Destroy the server connection - * @param {boolean} [options.force=false] Force destroy the pool - * @method - */ -ReplSet.prototype.destroy = function(options, callback) { - if (typeof options === 'function') { - callback = options; - options = {}; - } - - options = options || {}; - - let destroyCount = this.s.connectingServers.length + 1; // +1 for the callback from `replicaSetState.destroy` - const serverDestroyed = () => { - destroyCount--; - if (destroyCount > 0) { - return; - } - - // Emit toplogy closing event - emitSDAMEvent(this, 'topologyClosed', { topologyId: this.id }); - - // Transition state - stateTransition(this, DESTROYED); - - if (typeof callback === 'function') { - callback(null, null); - } - }; - - // Clear out any monitoring process - if (this.haTimeoutId) clearTimeout(this.haTimeoutId); - - // Clear out all monitoring - for (var i = 0; i < this.intervalIds.length; i++) { - this.intervalIds[i].stop(); - } - - // Reset list of intervalIds - this.intervalIds = []; - - if (destroyCount === 0) { - serverDestroyed(); - return; - } - - // Destroy the replicaset - this.s.replicaSetState.destroy(options, serverDestroyed); - - // Destroy all connecting servers - this.s.connectingServers.forEach(function(x) { - x.destroy(options, serverDestroyed); - }); -}; - -/** - * Unref all connections belong to this server - * @method - */ -ReplSet.prototype.unref = function() { - // Transition state - stateTransition(this, UNREFERENCED); - - this.s.replicaSetState.allServers().forEach(function(x) { - x.unref(); - }); - - clearTimeout(this.haTimeoutId); -}; - -/** - * Returns the last known ismaster document for this server - * @method - * @return {object} - */ -ReplSet.prototype.lastIsMaster = function() { - // If secondaryOnlyConnectionAllowed and no primary but secondary - // return the secondaries ismaster result. - if ( - this.s.options.secondaryOnlyConnectionAllowed && - !this.s.replicaSetState.hasPrimary() && - this.s.replicaSetState.hasSecondary() - ) { - return this.s.replicaSetState.secondaries[0].lastIsMaster(); - } - - return this.s.replicaSetState.primary - ? this.s.replicaSetState.primary.lastIsMaster() - : this.ismaster; -}; - -/** - * All raw connections - * @method - * @return {Connection[]} - */ -ReplSet.prototype.connections = function() { - var servers = this.s.replicaSetState.allServers(); - var connections = []; - for (var i = 0; i < servers.length; i++) { - connections = connections.concat(servers[i].connections()); - } - - return connections; -}; - -/** - * Figure out if the server is connected - * @method - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @return {boolean} - */ -ReplSet.prototype.isConnected = function(options) { - options = options || {}; - - // If we specified a read preference check if we are connected to something - // than can satisfy this - if (options.readPreference && options.readPreference.equals(ReadPreference.secondary)) { - return this.s.replicaSetState.hasSecondary(); - } - - if (options.readPreference && options.readPreference.equals(ReadPreference.primary)) { - return this.s.replicaSetState.hasPrimary(); - } - - if (options.readPreference && options.readPreference.equals(ReadPreference.primaryPreferred)) { - return this.s.replicaSetState.hasSecondary() || this.s.replicaSetState.hasPrimary(); - } - - if (options.readPreference && options.readPreference.equals(ReadPreference.secondaryPreferred)) { - return this.s.replicaSetState.hasSecondary() || this.s.replicaSetState.hasPrimary(); - } - - if (this.s.options.secondaryOnlyConnectionAllowed && this.s.replicaSetState.hasSecondary()) { - return true; - } - - return this.s.replicaSetState.hasPrimary(); -}; - -/** - * Figure out if the replicaset instance was destroyed by calling destroy - * @method - * @return {boolean} - */ -ReplSet.prototype.isDestroyed = function() { - return this.state === DESTROYED; -}; - -const SERVER_SELECTION_TIMEOUT_MS = 10000; // hardcoded `serverSelectionTimeoutMS` for legacy topology -const SERVER_SELECTION_INTERVAL_MS = 1000; // time to wait between selection attempts -/** - * Selects a server - * - * @method - * @param {function} selector Unused - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @param {ClientSession} [options.session] Unused - * @param {function} callback - */ -ReplSet.prototype.selectServer = function(selector, options, callback) { - if (typeof selector === 'function' && typeof callback === 'undefined') - (callback = selector), (selector = undefined), (options = {}); - if (typeof options === 'function') (callback = options), (options = selector); - options = options || {}; - - let readPreference; - if (selector instanceof ReadPreference) { - readPreference = selector; - } else { - readPreference = options.readPreference || ReadPreference.primary; - } - - let lastError; - const start = process.hrtime(); - const _selectServer = () => { - if (calculateDurationInMs(start) >= SERVER_SELECTION_TIMEOUT_MS) { - if (lastError != null) { - callback(lastError, null); - } else { - callback(new MongoError('Server selection timed out')); - } - - return; - } - - const server = this.s.replicaSetState.pickServer(readPreference); - if (server == null) { - setTimeout(_selectServer, SERVER_SELECTION_INTERVAL_MS); - return; - } - - if (!(server instanceof Server)) { - lastError = server; - setTimeout(_selectServer, SERVER_SELECTION_INTERVAL_MS); - return; - } - - if (this.s.debug) this.emit('pickedServer', options.readPreference, server); - callback(null, server); - }; - - _selectServer(); -}; - -/** - * Get all connected servers - * @method - * @return {Server[]} - */ -ReplSet.prototype.getServers = function() { - return this.s.replicaSetState.allServers(); -}; - -// -// Execute write operation -function executeWriteOperation(args, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // TODO: once we drop Node 4, use destructuring either here or in arguments. - const self = args.self; - const op = args.op; - const ns = args.ns; - const ops = args.ops; - - if (self.state === DESTROYED) { - return callback(new MongoError(f('topology was destroyed'))); - } - - const willRetryWrite = - !args.retrying && - !!options.retryWrites && - options.session && - isRetryableWritesSupported(self) && - !options.session.inTransaction(); - - if (!self.s.replicaSetState.hasPrimary()) { - if (self.s.disconnectHandler) { - // Not connected but we have a disconnecthandler - return self.s.disconnectHandler.add(op, ns, ops, options, callback); - } else if (!willRetryWrite) { - // No server returned we had an error - return callback(new MongoError('no primary server found')); - } - } - - const handler = (err, result) => { - if (!err) return callback(null, result); - if (!isRetryableError(err)) { - err = getMMAPError(err); - return callback(err); - } - - if (willRetryWrite) { - const newArgs = Object.assign({}, args, { retrying: true }); - return executeWriteOperation(newArgs, options, callback); - } - - // Per SDAM, remove primary from replicaset - if (self.s.replicaSetState.primary) { - self.s.replicaSetState.primary.destroy(); - self.s.replicaSetState.remove(self.s.replicaSetState.primary, { force: true }); - } - - return callback(err); - }; - - if (callback.operationId) { - handler.operationId = callback.operationId; - } - - // increment and assign txnNumber - if (willRetryWrite) { - options.session.incrementTransactionNumber(); - options.willRetryWrite = willRetryWrite; - } - - self.s.replicaSetState.primary[op](ns, ops, options, handler); -} - -/** - * Insert one or more documents - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of documents to insert - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {boolean} [options.retryWrites] Enable retryable writes for this operation - * @param {opResultCallback} callback A callback function - */ -ReplSet.prototype.insert = function(ns, ops, options, callback) { - // Execute write operation - executeWriteOperation({ self: this, op: 'insert', ns, ops }, options, callback); -}; - -/** - * Perform one or more update operations - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of updates - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {boolean} [options.retryWrites] Enable retryable writes for this operation - * @param {opResultCallback} callback A callback function - */ -ReplSet.prototype.update = function(ns, ops, options, callback) { - // Execute write operation - executeWriteOperation({ self: this, op: 'update', ns, ops }, options, callback); -}; - -/** - * Perform one or more remove operations - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of removes - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {boolean} [options.retryWrites] Enable retryable writes for this operation - * @param {opResultCallback} callback A callback function - */ -ReplSet.prototype.remove = function(ns, ops, options, callback) { - // Execute write operation - executeWriteOperation({ self: this, op: 'remove', ns, ops }, options, callback); -}; - -const RETRYABLE_WRITE_OPERATIONS = ['findAndModify', 'insert', 'update', 'delete']; - -function isWriteCommand(command) { - return RETRYABLE_WRITE_OPERATIONS.some(op => command[op]); -} - -/** - * Execute a command - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object} cmd The command hash - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @param {Connection} [options.connection] Specify connection object to execute command against - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {opResultCallback} callback A callback function - */ -ReplSet.prototype.command = function(ns, cmd, options, callback) { - if (typeof options === 'function') { - (callback = options), (options = {}), (options = options || {}); - } - - if (this.state === DESTROYED) return callback(new MongoError(f('topology was destroyed'))); - var self = this; - - // Establish readPreference - var readPreference = options.readPreference ? options.readPreference : ReadPreference.primary; - - // If the readPreference is primary and we have no primary, store it - if ( - readPreference.preference === 'primary' && - !this.s.replicaSetState.hasPrimary() && - this.s.disconnectHandler != null - ) { - return this.s.disconnectHandler.add('command', ns, cmd, options, callback); - } else if ( - readPreference.preference === 'secondary' && - !this.s.replicaSetState.hasSecondary() && - this.s.disconnectHandler != null - ) { - return this.s.disconnectHandler.add('command', ns, cmd, options, callback); - } else if ( - readPreference.preference !== 'primary' && - !this.s.replicaSetState.hasSecondary() && - !this.s.replicaSetState.hasPrimary() && - this.s.disconnectHandler != null - ) { - return this.s.disconnectHandler.add('command', ns, cmd, options, callback); - } - - // Pick a server - var server = this.s.replicaSetState.pickServer(readPreference); - // We received an error, return it - if (!(server instanceof Server)) return callback(server); - // Emit debug event - if (self.s.debug) self.emit('pickedServer', ReadPreference.primary, server); - - // No server returned we had an error - if (server == null) { - return callback( - new MongoError( - f('no server found that matches the provided readPreference %s', readPreference) - ) - ); - } - - const willRetryWrite = - !options.retrying && - !!options.retryWrites && - options.session && - isRetryableWritesSupported(self) && - !options.session.inTransaction() && - isWriteCommand(cmd); - - const cb = (err, result) => { - if (!err) return callback(null, result); - if (!isRetryableError(err)) { - return callback(err); - } - - if (willRetryWrite) { - const newOptions = Object.assign({}, options, { retrying: true }); - return this.command(ns, cmd, newOptions, callback); - } - - // Per SDAM, remove primary from replicaset - if (this.s.replicaSetState.primary) { - this.s.replicaSetState.primary.destroy(); - this.s.replicaSetState.remove(this.s.replicaSetState.primary, { force: true }); - } - - return callback(err); - }; - - // increment and assign txnNumber - if (willRetryWrite) { - options.session.incrementTransactionNumber(); - options.willRetryWrite = willRetryWrite; - } - - // Execute the command - server.command(ns, cmd, options, cb); -}; - -/** - * Get a new cursor - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object|Long} cmd Can be either a command returning a cursor or a cursorId - * @param {object} [options] Options for the cursor - * @param {object} [options.batchSize=0] Batchsize for the operation - * @param {array} [options.documents=[]] Initial documents list for cursor - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {object} [options.topology] The internal topology of the created cursor - * @returns {Cursor} - */ -ReplSet.prototype.cursor = function(ns, cmd, options) { - options = options || {}; - const topology = options.topology || this; - - // Set up final cursor type - var FinalCursor = options.cursorFactory || this.s.Cursor; - - // Return the cursor - return new FinalCursor(topology, ns, cmd, options); -}; - -/** - * A replset connect event, used to verify that the connection is up and running - * - * @event ReplSet#connect - * @type {ReplSet} - */ - -/** - * A replset reconnect event, used to verify that the topology reconnected - * - * @event ReplSet#reconnect - * @type {ReplSet} - */ - -/** - * A replset fullsetup event, used to signal that all topology members have been contacted. - * - * @event ReplSet#fullsetup - * @type {ReplSet} - */ - -/** - * A replset all event, used to signal that all topology members have been contacted. - * - * @event ReplSet#all - * @type {ReplSet} - */ - -/** - * A replset failed event, used to signal that initial replset connection failed. - * - * @event ReplSet#failed - * @type {ReplSet} - */ - -/** - * A server member left the replicaset - * - * @event ReplSet#left - * @type {function} - * @param {string} type The type of member that left (primary|secondary|arbiter) - * @param {Server} server The server object that left - */ - -/** - * A server member joined the replicaset - * - * @event ReplSet#joined - * @type {function} - * @param {string} type The type of member that joined (primary|secondary|arbiter) - * @param {Server} server The server object that joined - */ - -/** - * A server opening SDAM monitoring event - * - * @event ReplSet#serverOpening - * @type {object} - */ - -/** - * A server closed SDAM monitoring event - * - * @event ReplSet#serverClosed - * @type {object} - */ - -/** - * A server description SDAM change monitoring event - * - * @event ReplSet#serverDescriptionChanged - * @type {object} - */ - -/** - * A topology open SDAM event - * - * @event ReplSet#topologyOpening - * @type {object} - */ - -/** - * A topology closed SDAM event - * - * @event ReplSet#topologyClosed - * @type {object} - */ - -/** - * A topology structure SDAM change event - * - * @event ReplSet#topologyDescriptionChanged - * @type {object} - */ - -/** - * A topology serverHeartbeatStarted SDAM event - * - * @event ReplSet#serverHeartbeatStarted - * @type {object} - */ - -/** - * A topology serverHeartbeatFailed SDAM event - * - * @event ReplSet#serverHeartbeatFailed - * @type {object} - */ - -/** - * A topology serverHeartbeatSucceeded SDAM change event - * - * @event ReplSet#serverHeartbeatSucceeded - * @type {object} - */ - -/** - * An event emitted indicating a command was started, if command monitoring is enabled - * - * @event ReplSet#commandStarted - * @type {object} - */ - -/** - * An event emitted indicating a command succeeded, if command monitoring is enabled - * - * @event ReplSet#commandSucceeded - * @type {object} - */ - -/** - * An event emitted indicating a command failed, if command monitoring is enabled - * - * @event ReplSet#commandFailed - * @type {object} - */ - -module.exports = ReplSet; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/topologies/replset_state.js b/scripts/2.5/node_modules/mongodb/lib/core/topologies/replset_state.js deleted file mode 100644 index 24c16d6d..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/core/topologies/replset_state.js +++ /dev/null @@ -1,1121 +0,0 @@ -'use strict'; - -var inherits = require('util').inherits, - f = require('util').format, - diff = require('./shared').diff, - EventEmitter = require('events').EventEmitter, - Logger = require('../connection/logger'), - ReadPreference = require('./read_preference'), - MongoError = require('../error').MongoError, - Buffer = require('safe-buffer').Buffer; - -var TopologyType = { - Single: 'Single', - ReplicaSetNoPrimary: 'ReplicaSetNoPrimary', - ReplicaSetWithPrimary: 'ReplicaSetWithPrimary', - Sharded: 'Sharded', - Unknown: 'Unknown' -}; - -var ServerType = { - Standalone: 'Standalone', - Mongos: 'Mongos', - PossiblePrimary: 'PossiblePrimary', - RSPrimary: 'RSPrimary', - RSSecondary: 'RSSecondary', - RSArbiter: 'RSArbiter', - RSOther: 'RSOther', - RSGhost: 'RSGhost', - Unknown: 'Unknown' -}; - -var ReplSetState = function(options) { - options = options || {}; - // Add event listener - EventEmitter.call(this); - // Topology state - this.topologyType = TopologyType.ReplicaSetNoPrimary; - this.setName = options.setName; - - // Server set - this.set = {}; - - // Unpacked options - this.id = options.id; - this.setName = options.setName; - - // Replicaset logger - this.logger = options.logger || Logger('ReplSet', options); - - // Server selection index - this.index = 0; - // Acceptable latency - this.acceptableLatency = options.acceptableLatency || 15; - - // heartbeatFrequencyMS - this.heartbeatFrequencyMS = options.heartbeatFrequencyMS || 10000; - - // Server side - this.primary = null; - this.secondaries = []; - this.arbiters = []; - this.passives = []; - this.ghosts = []; - // Current unknown hosts - this.unknownServers = []; - // In set status - this.set = {}; - // Status - this.maxElectionId = null; - this.maxSetVersion = 0; - // Description of the Replicaset - this.replicasetDescription = { - topologyType: 'Unknown', - servers: [] - }; - - this.logicalSessionTimeoutMinutes = undefined; -}; - -inherits(ReplSetState, EventEmitter); - -ReplSetState.prototype.hasPrimaryAndSecondary = function() { - return this.primary != null && this.secondaries.length > 0; -}; - -ReplSetState.prototype.hasPrimaryOrSecondary = function() { - return this.hasPrimary() || this.hasSecondary(); -}; - -ReplSetState.prototype.hasPrimary = function() { - return this.primary != null; -}; - -ReplSetState.prototype.hasSecondary = function() { - return this.secondaries.length > 0; -}; - -ReplSetState.prototype.get = function(host) { - var servers = this.allServers(); - - for (var i = 0; i < servers.length; i++) { - if (servers[i].name.toLowerCase() === host.toLowerCase()) { - return servers[i]; - } - } - - return null; -}; - -ReplSetState.prototype.allServers = function(options) { - options = options || {}; - var servers = this.primary ? [this.primary] : []; - servers = servers.concat(this.secondaries); - if (!options.ignoreArbiters) servers = servers.concat(this.arbiters); - servers = servers.concat(this.passives); - return servers; -}; - -ReplSetState.prototype.destroy = function(options, callback) { - const serversToDestroy = this.secondaries - .concat(this.arbiters) - .concat(this.passives) - .concat(this.ghosts); - if (this.primary) serversToDestroy.push(this.primary); - - let serverCount = serversToDestroy.length; - const serverDestroyed = () => { - serverCount--; - if (serverCount > 0) { - return; - } - - // Clear out the complete state - this.secondaries = []; - this.arbiters = []; - this.passives = []; - this.ghosts = []; - this.unknownServers = []; - this.set = {}; - this.primary = null; - - // Emit the topology changed - emitTopologyDescriptionChanged(this); - - if (typeof callback === 'function') { - callback(null, null); - } - }; - - if (serverCount === 0) { - serverDestroyed(); - return; - } - - serversToDestroy.forEach(server => server.destroy(options, serverDestroyed)); -}; - -ReplSetState.prototype.remove = function(server, options) { - options = options || {}; - - // Get the server name and lowerCase it - var serverName = server.name.toLowerCase(); - - // Only remove if the current server is not connected - var servers = this.primary ? [this.primary] : []; - servers = servers.concat(this.secondaries); - servers = servers.concat(this.arbiters); - servers = servers.concat(this.passives); - - // Check if it's active and this is just a failed connection attempt - for (var i = 0; i < servers.length; i++) { - if ( - !options.force && - servers[i].equals(server) && - servers[i].isConnected && - servers[i].isConnected() - ) { - return; - } - } - - // If we have it in the set remove it - if (this.set[serverName]) { - this.set[serverName].type = ServerType.Unknown; - this.set[serverName].electionId = null; - this.set[serverName].setName = null; - this.set[serverName].setVersion = null; - } - - // Remove type - var removeType = null; - - // Remove from any lists - if (this.primary && this.primary.equals(server)) { - this.primary = null; - this.topologyType = TopologyType.ReplicaSetNoPrimary; - removeType = 'primary'; - } - - // Remove from any other server lists - removeType = removeFrom(server, this.secondaries) ? 'secondary' : removeType; - removeType = removeFrom(server, this.arbiters) ? 'arbiter' : removeType; - removeType = removeFrom(server, this.passives) ? 'secondary' : removeType; - removeFrom(server, this.ghosts); - removeFrom(server, this.unknownServers); - - // Push to unknownServers - this.unknownServers.push(serverName); - - // Do we have a removeType - if (removeType) { - this.emit('left', removeType, server); - } -}; - -const isArbiter = ismaster => ismaster.arbiterOnly && ismaster.setName; - -ReplSetState.prototype.update = function(server) { - var self = this; - // Get the current ismaster - var ismaster = server.lastIsMaster(); - - // Get the server name and lowerCase it - var serverName = server.name.toLowerCase(); - - // - // Add any hosts - // - if (ismaster) { - // Join all the possible new hosts - var hosts = Array.isArray(ismaster.hosts) ? ismaster.hosts : []; - hosts = hosts.concat(Array.isArray(ismaster.arbiters) ? ismaster.arbiters : []); - hosts = hosts.concat(Array.isArray(ismaster.passives) ? ismaster.passives : []); - hosts = hosts.map(function(s) { - return s.toLowerCase(); - }); - - // Add all hosts as unknownServers - for (var i = 0; i < hosts.length; i++) { - // Add to the list of unknown server - if ( - this.unknownServers.indexOf(hosts[i]) === -1 && - (!this.set[hosts[i]] || this.set[hosts[i]].type === ServerType.Unknown) - ) { - this.unknownServers.push(hosts[i].toLowerCase()); - } - - if (!this.set[hosts[i]]) { - this.set[hosts[i]] = { - type: ServerType.Unknown, - electionId: null, - setName: null, - setVersion: null - }; - } - } - } - - // - // Unknown server - // - if (!ismaster && !inList(ismaster, server, this.unknownServers)) { - self.set[serverName] = { - type: ServerType.Unknown, - setVersion: null, - electionId: null, - setName: null - }; - // Update set information about the server instance - self.set[serverName].type = ServerType.Unknown; - self.set[serverName].electionId = ismaster ? ismaster.electionId : ismaster; - self.set[serverName].setName = ismaster ? ismaster.setName : ismaster; - self.set[serverName].setVersion = ismaster ? ismaster.setVersion : ismaster; - - if (self.unknownServers.indexOf(server.name) === -1) { - self.unknownServers.push(serverName); - } - - // Set the topology - return false; - } - - // Update logicalSessionTimeoutMinutes - if (ismaster.logicalSessionTimeoutMinutes !== undefined && !isArbiter(ismaster)) { - if ( - self.logicalSessionTimeoutMinutes === undefined || - ismaster.logicalSessionTimeoutMinutes === null - ) { - self.logicalSessionTimeoutMinutes = ismaster.logicalSessionTimeoutMinutes; - } else { - self.logicalSessionTimeoutMinutes = Math.min( - self.logicalSessionTimeoutMinutes, - ismaster.logicalSessionTimeoutMinutes - ); - } - } - - // - // Is this a mongos - // - if (ismaster && ismaster.msg === 'isdbgrid') { - if (this.primary && this.primary.name === serverName) { - this.primary = null; - this.topologyType = TopologyType.ReplicaSetNoPrimary; - } - - return false; - } - - // A RSGhost instance - if (ismaster.isreplicaset) { - self.set[serverName] = { - type: ServerType.RSGhost, - setVersion: null, - electionId: null, - setName: ismaster.setName - }; - - if (this.primary && this.primary.name === serverName) { - this.primary = null; - } - - // Set the topology - this.topologyType = this.primary - ? TopologyType.ReplicaSetWithPrimary - : TopologyType.ReplicaSetNoPrimary; - if (ismaster.setName) this.setName = ismaster.setName; - - // Set the topology - return false; - } - - // A RSOther instance - if ( - (ismaster.setName && ismaster.hidden) || - (ismaster.setName && - !ismaster.ismaster && - !ismaster.secondary && - !ismaster.arbiterOnly && - !ismaster.passive) - ) { - self.set[serverName] = { - type: ServerType.RSOther, - setVersion: null, - electionId: null, - setName: ismaster.setName - }; - - // Set the topology - this.topologyType = this.primary - ? TopologyType.ReplicaSetWithPrimary - : TopologyType.ReplicaSetNoPrimary; - if (ismaster.setName) this.setName = ismaster.setName; - return false; - } - - // - // Standalone server, destroy and return - // - if (ismaster && ismaster.ismaster && !ismaster.setName) { - this.topologyType = this.primary ? TopologyType.ReplicaSetWithPrimary : TopologyType.Unknown; - this.remove(server, { force: true }); - return false; - } - - // - // Server in maintanance mode - // - if (ismaster && !ismaster.ismaster && !ismaster.secondary && !ismaster.arbiterOnly) { - this.remove(server, { force: true }); - return false; - } - - // - // If the .me field does not match the passed in server - // - if (ismaster.me && ismaster.me.toLowerCase() !== serverName) { - if (this.logger.isWarn()) { - this.logger.warn( - f( - 'the seedlist server was removed due to its address %s not matching its ismaster.me address %s', - server.name, - ismaster.me - ) - ); - } - - // Delete from the set - delete this.set[serverName]; - // Delete unknown servers - removeFrom(server, self.unknownServers); - - // Destroy the instance - server.destroy({ force: true }); - - // Set the type of topology we have - if (this.primary && !this.primary.equals(server)) { - this.topologyType = TopologyType.ReplicaSetWithPrimary; - } else { - this.topologyType = TopologyType.ReplicaSetNoPrimary; - } - - // - // We have a potential primary - // - if (!this.primary && ismaster.primary) { - this.set[ismaster.primary.toLowerCase()] = { - type: ServerType.PossiblePrimary, - setName: null, - electionId: null, - setVersion: null - }; - } - - return false; - } - - // - // Primary handling - // - if (!this.primary && ismaster.ismaster && ismaster.setName) { - var ismasterElectionId = server.lastIsMaster().electionId; - if (this.setName && this.setName !== ismaster.setName) { - this.topologyType = TopologyType.ReplicaSetNoPrimary; - return new MongoError( - f( - 'setName from ismaster does not match provided connection setName [%s] != [%s]', - ismaster.setName, - this.setName - ) - ); - } - - if (!this.maxElectionId && ismasterElectionId) { - this.maxElectionId = ismasterElectionId; - } else if (this.maxElectionId && ismasterElectionId) { - var result = compareObjectIds(this.maxElectionId, ismasterElectionId); - // Get the electionIds - var ismasterSetVersion = server.lastIsMaster().setVersion; - - if (result === 1) { - this.topologyType = TopologyType.ReplicaSetNoPrimary; - return false; - } else if (result === 0 && ismasterSetVersion) { - if (ismasterSetVersion < this.maxSetVersion) { - this.topologyType = TopologyType.ReplicaSetNoPrimary; - return false; - } - } - - this.maxSetVersion = ismasterSetVersion; - this.maxElectionId = ismasterElectionId; - } - - // Hande normalization of server names - var normalizedHosts = ismaster.hosts.map(function(x) { - return x.toLowerCase(); - }); - var locationIndex = normalizedHosts.indexOf(serverName); - - // Validate that the server exists in the host list - if (locationIndex !== -1) { - self.primary = server; - self.set[serverName] = { - type: ServerType.RSPrimary, - setVersion: ismaster.setVersion, - electionId: ismaster.electionId, - setName: ismaster.setName - }; - - // Set the topology - this.topologyType = TopologyType.ReplicaSetWithPrimary; - if (ismaster.setName) this.setName = ismaster.setName; - removeFrom(server, self.unknownServers); - removeFrom(server, self.secondaries); - removeFrom(server, self.passives); - self.emit('joined', 'primary', server); - } else { - this.topologyType = TopologyType.ReplicaSetNoPrimary; - } - - emitTopologyDescriptionChanged(self); - return true; - } else if (ismaster.ismaster && ismaster.setName) { - // Get the electionIds - var currentElectionId = self.set[self.primary.name.toLowerCase()].electionId; - var currentSetVersion = self.set[self.primary.name.toLowerCase()].setVersion; - var currentSetName = self.set[self.primary.name.toLowerCase()].setName; - ismasterElectionId = server.lastIsMaster().electionId; - ismasterSetVersion = server.lastIsMaster().setVersion; - var ismasterSetName = server.lastIsMaster().setName; - - // Is it the same server instance - if (this.primary.equals(server) && currentSetName === ismasterSetName) { - return false; - } - - // If we do not have the same rs name - if (currentSetName && currentSetName !== ismasterSetName) { - if (!this.primary.equals(server)) { - this.topologyType = TopologyType.ReplicaSetWithPrimary; - } else { - this.topologyType = TopologyType.ReplicaSetNoPrimary; - } - - return false; - } - - // Check if we need to replace the server - if (currentElectionId && ismasterElectionId) { - result = compareObjectIds(currentElectionId, ismasterElectionId); - - if (result === 1) { - return false; - } else if (result === 0 && currentSetVersion > ismasterSetVersion) { - return false; - } - } else if (!currentElectionId && ismasterElectionId && ismasterSetVersion) { - if (ismasterSetVersion < this.maxSetVersion) { - return false; - } - } - - if (!this.maxElectionId && ismasterElectionId) { - this.maxElectionId = ismasterElectionId; - } else if (this.maxElectionId && ismasterElectionId) { - result = compareObjectIds(this.maxElectionId, ismasterElectionId); - - if (result === 1) { - return false; - } else if (result === 0 && currentSetVersion && ismasterSetVersion) { - if (ismasterSetVersion < this.maxSetVersion) { - return false; - } - } else { - if (ismasterSetVersion < this.maxSetVersion) { - return false; - } - } - - this.maxElectionId = ismasterElectionId; - this.maxSetVersion = ismasterSetVersion; - } else { - this.maxSetVersion = ismasterSetVersion; - } - - // Modify the entry to unknown - self.set[self.primary.name.toLowerCase()] = { - type: ServerType.Unknown, - setVersion: null, - electionId: null, - setName: null - }; - - // Signal primary left - self.emit('left', 'primary', this.primary); - // Destroy the instance - self.primary.destroy({ force: true }); - // Set the new instance - self.primary = server; - // Set the set information - self.set[serverName] = { - type: ServerType.RSPrimary, - setVersion: ismaster.setVersion, - electionId: ismaster.electionId, - setName: ismaster.setName - }; - - // Set the topology - this.topologyType = TopologyType.ReplicaSetWithPrimary; - if (ismaster.setName) this.setName = ismaster.setName; - removeFrom(server, self.unknownServers); - removeFrom(server, self.secondaries); - removeFrom(server, self.passives); - self.emit('joined', 'primary', server); - emitTopologyDescriptionChanged(self); - return true; - } - - // A possible instance - if (!this.primary && ismaster.primary) { - self.set[ismaster.primary.toLowerCase()] = { - type: ServerType.PossiblePrimary, - setVersion: null, - electionId: null, - setName: null - }; - } - - // - // Secondary handling - // - if ( - ismaster.secondary && - ismaster.setName && - !inList(ismaster, server, this.secondaries) && - this.setName && - this.setName === ismaster.setName - ) { - addToList(self, ServerType.RSSecondary, ismaster, server, this.secondaries); - // Set the topology - this.topologyType = this.primary - ? TopologyType.ReplicaSetWithPrimary - : TopologyType.ReplicaSetNoPrimary; - if (ismaster.setName) this.setName = ismaster.setName; - removeFrom(server, self.unknownServers); - - // Remove primary - if (this.primary && this.primary.name.toLowerCase() === serverName) { - server.destroy({ force: true }); - this.primary = null; - self.emit('left', 'primary', server); - } - - // Emit secondary joined replicaset - self.emit('joined', 'secondary', server); - emitTopologyDescriptionChanged(self); - return true; - } - - // - // Arbiter handling - // - if ( - isArbiter(ismaster) && - !inList(ismaster, server, this.arbiters) && - this.setName && - this.setName === ismaster.setName - ) { - addToList(self, ServerType.RSArbiter, ismaster, server, this.arbiters); - // Set the topology - this.topologyType = this.primary - ? TopologyType.ReplicaSetWithPrimary - : TopologyType.ReplicaSetNoPrimary; - if (ismaster.setName) this.setName = ismaster.setName; - removeFrom(server, self.unknownServers); - self.emit('joined', 'arbiter', server); - emitTopologyDescriptionChanged(self); - return true; - } - - // - // Passive handling - // - if ( - ismaster.passive && - ismaster.setName && - !inList(ismaster, server, this.passives) && - this.setName && - this.setName === ismaster.setName - ) { - addToList(self, ServerType.RSSecondary, ismaster, server, this.passives); - // Set the topology - this.topologyType = this.primary - ? TopologyType.ReplicaSetWithPrimary - : TopologyType.ReplicaSetNoPrimary; - if (ismaster.setName) this.setName = ismaster.setName; - removeFrom(server, self.unknownServers); - - // Remove primary - if (this.primary && this.primary.name.toLowerCase() === serverName) { - server.destroy({ force: true }); - this.primary = null; - self.emit('left', 'primary', server); - } - - self.emit('joined', 'secondary', server); - emitTopologyDescriptionChanged(self); - return true; - } - - // - // Remove the primary - // - if (this.set[serverName] && this.set[serverName].type === ServerType.RSPrimary) { - self.emit('left', 'primary', this.primary); - this.primary.destroy({ force: true }); - this.primary = null; - this.topologyType = TopologyType.ReplicaSetNoPrimary; - return false; - } - - this.topologyType = this.primary - ? TopologyType.ReplicaSetWithPrimary - : TopologyType.ReplicaSetNoPrimary; - return false; -}; - -/** - * Recalculate single server max staleness - * @method - */ -ReplSetState.prototype.updateServerMaxStaleness = function(server, haInterval) { - // Locate the max secondary lastwrite - var max = 0; - // Go over all secondaries - for (var i = 0; i < this.secondaries.length; i++) { - max = Math.max(max, this.secondaries[i].lastWriteDate); - } - - // Perform this servers staleness calculation - if (server.ismaster.maxWireVersion >= 5 && server.ismaster.secondary && this.hasPrimary()) { - server.staleness = - server.lastUpdateTime - - server.lastWriteDate - - (this.primary.lastUpdateTime - this.primary.lastWriteDate) + - haInterval; - } else if (server.ismaster.maxWireVersion >= 5 && server.ismaster.secondary) { - server.staleness = max - server.lastWriteDate + haInterval; - } -}; - -/** - * Recalculate all the staleness values for secodaries - * @method - */ -ReplSetState.prototype.updateSecondariesMaxStaleness = function(haInterval) { - for (var i = 0; i < this.secondaries.length; i++) { - this.updateServerMaxStaleness(this.secondaries[i], haInterval); - } -}; - -/** - * Pick a server by the passed in ReadPreference - * @method - * @param {ReadPreference} readPreference The ReadPreference instance to use - */ -ReplSetState.prototype.pickServer = function(readPreference) { - // If no read Preference set to primary by default - readPreference = readPreference || ReadPreference.primary; - - // maxStalenessSeconds is not allowed with a primary read - if (readPreference.preference === 'primary' && readPreference.maxStalenessSeconds != null) { - return new MongoError('primary readPreference incompatible with maxStalenessSeconds'); - } - - // Check if we have any non compatible servers for maxStalenessSeconds - var allservers = this.primary ? [this.primary] : []; - allservers = allservers.concat(this.secondaries); - - // Does any of the servers not support the right wire protocol version - // for maxStalenessSeconds when maxStalenessSeconds specified on readPreference. Then error out - if (readPreference.maxStalenessSeconds != null) { - for (var i = 0; i < allservers.length; i++) { - if (allservers[i].ismaster.maxWireVersion < 5) { - return new MongoError( - 'maxStalenessSeconds not supported by at least one of the replicaset members' - ); - } - } - } - - // Do we have the nearest readPreference - if (readPreference.preference === 'nearest' && readPreference.maxStalenessSeconds == null) { - return pickNearest(this, readPreference); - } else if ( - readPreference.preference === 'nearest' && - readPreference.maxStalenessSeconds != null - ) { - return pickNearestMaxStalenessSeconds(this, readPreference); - } - - // Get all the secondaries - var secondaries = this.secondaries; - - // Check if we can satisfy and of the basic read Preferences - if (readPreference.equals(ReadPreference.secondary) && secondaries.length === 0) { - return new MongoError('no secondary server available'); - } - - if ( - readPreference.equals(ReadPreference.secondaryPreferred) && - secondaries.length === 0 && - this.primary == null - ) { - return new MongoError('no secondary or primary server available'); - } - - if (readPreference.equals(ReadPreference.primary) && this.primary == null) { - return new MongoError('no primary server available'); - } - - // Secondary preferred or just secondaries - if ( - readPreference.equals(ReadPreference.secondaryPreferred) || - readPreference.equals(ReadPreference.secondary) - ) { - if (secondaries.length > 0 && readPreference.maxStalenessSeconds == null) { - // Pick nearest of any other servers available - var server = pickNearest(this, readPreference); - // No server in the window return primary - if (server) { - return server; - } - } else if (secondaries.length > 0 && readPreference.maxStalenessSeconds != null) { - // Pick nearest of any other servers available - server = pickNearestMaxStalenessSeconds(this, readPreference); - // No server in the window return primary - if (server) { - return server; - } - } - - if (readPreference.equals(ReadPreference.secondaryPreferred)) { - return this.primary; - } - - return null; - } - - // Primary preferred - if (readPreference.equals(ReadPreference.primaryPreferred)) { - server = null; - - // We prefer the primary if it's available - if (this.primary) { - return this.primary; - } - - // Pick a secondary - if (secondaries.length > 0 && readPreference.maxStalenessSeconds == null) { - server = pickNearest(this, readPreference); - } else if (secondaries.length > 0 && readPreference.maxStalenessSeconds != null) { - server = pickNearestMaxStalenessSeconds(this, readPreference); - } - - // Did we find a server - if (server) return server; - } - - // Return the primary - return this.primary; -}; - -// -// Filter serves by tags -var filterByTags = function(readPreference, servers) { - if (readPreference.tags == null) return servers; - var filteredServers = []; - var tagsArray = Array.isArray(readPreference.tags) ? readPreference.tags : [readPreference.tags]; - - // Iterate over the tags - for (var j = 0; j < tagsArray.length; j++) { - var tags = tagsArray[j]; - - // Iterate over all the servers - for (var i = 0; i < servers.length; i++) { - var serverTag = servers[i].lastIsMaster().tags || {}; - - // Did we find the a matching server - var found = true; - // Check if the server is valid - for (var name in tags) { - if (serverTag[name] !== tags[name]) { - found = false; - } - } - - // Add to candidate list - if (found) { - filteredServers.push(servers[i]); - } - } - } - - // Returned filtered servers - return filteredServers; -}; - -function pickNearestMaxStalenessSeconds(self, readPreference) { - // Only get primary and secondaries as seeds - var servers = []; - - // Get the maxStalenessMS - var maxStalenessMS = readPreference.maxStalenessSeconds * 1000; - - // Check if the maxStalenessMS > 90 seconds - if (maxStalenessMS < 90 * 1000) { - return new MongoError('maxStalenessSeconds must be set to at least 90 seconds'); - } - - // Add primary to list if not a secondary read preference - if ( - self.primary && - readPreference.preference !== 'secondary' && - readPreference.preference !== 'secondaryPreferred' - ) { - servers.push(self.primary); - } - - // Add all the secondaries - for (var i = 0; i < self.secondaries.length; i++) { - servers.push(self.secondaries[i]); - } - - // If we have a secondaryPreferred readPreference and no server add the primary - if (self.primary && servers.length === 0 && readPreference.preference !== 'secondaryPreferred') { - servers.push(self.primary); - } - - // Filter by tags - servers = filterByTags(readPreference, servers); - - // Filter by latency - servers = servers.filter(function(s) { - return s.staleness <= maxStalenessMS; - }); - - // Sort by time - servers.sort(function(a, b) { - return a.lastIsMasterMS - b.lastIsMasterMS; - }); - - // No servers, default to primary - if (servers.length === 0) { - return null; - } - - // Ensure index does not overflow the number of available servers - self.index = self.index % servers.length; - - // Get the server - var server = servers[self.index]; - // Add to the index - self.index = self.index + 1; - // Return the first server of the sorted and filtered list - return server; -} - -function pickNearest(self, readPreference) { - // Only get primary and secondaries as seeds - var servers = []; - - // Add primary to list if not a secondary read preference - if ( - self.primary && - readPreference.preference !== 'secondary' && - readPreference.preference !== 'secondaryPreferred' - ) { - servers.push(self.primary); - } - - // Add all the secondaries - for (var i = 0; i < self.secondaries.length; i++) { - servers.push(self.secondaries[i]); - } - - // If we have a secondaryPreferred readPreference and no server add the primary - if (servers.length === 0 && self.primary && readPreference.preference !== 'secondaryPreferred') { - servers.push(self.primary); - } - - // Filter by tags - servers = filterByTags(readPreference, servers); - - // Sort by time - servers.sort(function(a, b) { - return a.lastIsMasterMS - b.lastIsMasterMS; - }); - - // Locate lowest time (picked servers are lowest time + acceptable Latency margin) - var lowest = servers.length > 0 ? servers[0].lastIsMasterMS : 0; - - // Filter by latency - servers = servers.filter(function(s) { - return s.lastIsMasterMS <= lowest + self.acceptableLatency; - }); - - // No servers, default to primary - if (servers.length === 0) { - return null; - } - - // Ensure index does not overflow the number of available servers - self.index = self.index % servers.length; - // Get the server - var server = servers[self.index]; - // Add to the index - self.index = self.index + 1; - // Return the first server of the sorted and filtered list - return server; -} - -function inList(ismaster, server, list) { - for (var i = 0; i < list.length; i++) { - if (list[i] && list[i].name && list[i].name.toLowerCase() === server.name.toLowerCase()) - return true; - } - - return false; -} - -function addToList(self, type, ismaster, server, list) { - var serverName = server.name.toLowerCase(); - // Update set information about the server instance - self.set[serverName].type = type; - self.set[serverName].electionId = ismaster ? ismaster.electionId : ismaster; - self.set[serverName].setName = ismaster ? ismaster.setName : ismaster; - self.set[serverName].setVersion = ismaster ? ismaster.setVersion : ismaster; - // Add to the list - list.push(server); -} - -function compareObjectIds(id1, id2) { - var a = Buffer.from(id1.toHexString(), 'hex'); - var b = Buffer.from(id2.toHexString(), 'hex'); - - if (a === b) { - return 0; - } - - if (typeof Buffer.compare === 'function') { - return Buffer.compare(a, b); - } - - var x = a.length; - var y = b.length; - var len = Math.min(x, y); - - for (var i = 0; i < len; i++) { - if (a[i] !== b[i]) { - break; - } - } - - if (i !== len) { - x = a[i]; - y = b[i]; - } - - return x < y ? -1 : y < x ? 1 : 0; -} - -function removeFrom(server, list) { - for (var i = 0; i < list.length; i++) { - if (list[i].equals && list[i].equals(server)) { - list.splice(i, 1); - return true; - } else if (typeof list[i] === 'string' && list[i].toLowerCase() === server.name.toLowerCase()) { - list.splice(i, 1); - return true; - } - } - - return false; -} - -function emitTopologyDescriptionChanged(self) { - if (self.listeners('topologyDescriptionChanged').length > 0) { - var topology = 'Unknown'; - var setName = self.setName; - - if (self.hasPrimaryAndSecondary()) { - topology = 'ReplicaSetWithPrimary'; - } else if (!self.hasPrimary() && self.hasSecondary()) { - topology = 'ReplicaSetNoPrimary'; - } - - // Generate description - var description = { - topologyType: topology, - setName: setName, - servers: [] - }; - - // Add the primary to the list - if (self.hasPrimary()) { - var desc = self.primary.getDescription(); - desc.type = 'RSPrimary'; - description.servers.push(desc); - } - - // Add all the secondaries - description.servers = description.servers.concat( - self.secondaries.map(function(x) { - var description = x.getDescription(); - description.type = 'RSSecondary'; - return description; - }) - ); - - // Add all the arbiters - description.servers = description.servers.concat( - self.arbiters.map(function(x) { - var description = x.getDescription(); - description.type = 'RSArbiter'; - return description; - }) - ); - - // Add all the passives - description.servers = description.servers.concat( - self.passives.map(function(x) { - var description = x.getDescription(); - description.type = 'RSSecondary'; - return description; - }) - ); - - // Get the diff - var diffResult = diff(self.replicasetDescription, description); - - // Create the result - var result = { - topologyId: self.id, - previousDescription: self.replicasetDescription, - newDescription: description, - diff: diffResult - }; - - // Emit the topologyDescription change - // if(diffResult.servers.length > 0) { - self.emit('topologyDescriptionChanged', result); - // } - - // Set the new description - self.replicasetDescription = description; - } -} - -module.exports = ReplSetState; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/topologies/server.js b/scripts/2.5/node_modules/mongodb/lib/core/topologies/server.js deleted file mode 100644 index c2f86421..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/core/topologies/server.js +++ /dev/null @@ -1,989 +0,0 @@ -'use strict'; - -var inherits = require('util').inherits, - f = require('util').format, - EventEmitter = require('events').EventEmitter, - ReadPreference = require('./read_preference'), - Logger = require('../connection/logger'), - debugOptions = require('../connection/utils').debugOptions, - retrieveBSON = require('../connection/utils').retrieveBSON, - Pool = require('../connection/pool'), - MongoError = require('../error').MongoError, - MongoNetworkError = require('../error').MongoNetworkError, - wireProtocol = require('../wireprotocol'), - CoreCursor = require('../cursor').CoreCursor, - sdam = require('./shared'), - createClientInfo = require('./shared').createClientInfo, - createCompressionInfo = require('./shared').createCompressionInfo, - resolveClusterTime = require('./shared').resolveClusterTime, - SessionMixins = require('./shared').SessionMixins, - relayEvents = require('../utils').relayEvents; - -const collationNotSupported = require('../utils').collationNotSupported; - -// Used for filtering out fields for loggin -var debugFields = [ - 'reconnect', - 'reconnectTries', - 'reconnectInterval', - 'emitError', - 'cursorFactory', - 'host', - 'port', - 'size', - 'keepAlive', - 'keepAliveInitialDelay', - 'noDelay', - 'connectionTimeout', - 'checkServerIdentity', - 'socketTimeout', - 'ssl', - 'ca', - 'crl', - 'cert', - 'key', - 'rejectUnauthorized', - 'promoteLongs', - 'promoteValues', - 'promoteBuffers', - 'servername' -]; - -// Server instance id -var id = 0; -var serverAccounting = false; -var servers = {}; -var BSON = retrieveBSON(); - -/** - * Creates a new Server instance - * @class - * @param {boolean} [options.reconnect=true] Server will attempt to reconnect on loss of connection - * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times - * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries - * @param {number} [options.monitoring=true] Enable the server state monitoring (calling ismaster at monitoringInterval) - * @param {number} [options.monitoringInterval=5000] The interval of calling ismaster when monitoring is enabled. - * @param {Cursor} [options.cursorFactory=Cursor] The cursor factory class used for all query cursors - * @param {string} options.host The server host - * @param {number} options.port The server port - * @param {number} [options.size=5] Server connection pool size - * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled - * @param {number} [options.keepAliveInitialDelay=300000] Initial delay before TCP keep alive enabled - * @param {boolean} [options.noDelay=true] TCP Connection no delay - * @param {number} [options.connectionTimeout=30000] TCP Connection timeout setting - * @param {number} [options.socketTimeout=360000] TCP Socket timeout setting - * @param {boolean} [options.ssl=false] Use SSL for connection - * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. - * @param {Buffer} [options.ca] SSL Certificate store binary buffer - * @param {Buffer} [options.crl] SSL Certificate revocation store binary buffer - * @param {Buffer} [options.cert] SSL Certificate binary buffer - * @param {Buffer} [options.key] SSL Key file binary buffer - * @param {string} [options.passphrase] SSL Certificate pass phrase - * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates - * @param {string} [options.servername=null] String containing the server name requested via TLS SNI. - * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits - * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. - * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. - * @param {string} [options.appname=null] Application name, passed in on ismaster call and logged in mongod server logs. Maximum size 128 bytes. - * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. - * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology - * @return {Server} A cursor instance - * @fires Server#connect - * @fires Server#close - * @fires Server#error - * @fires Server#timeout - * @fires Server#parseError - * @fires Server#reconnect - * @fires Server#reconnectFailed - * @fires Server#serverHeartbeatStarted - * @fires Server#serverHeartbeatSucceeded - * @fires Server#serverHeartbeatFailed - * @fires Server#topologyOpening - * @fires Server#topologyClosed - * @fires Server#topologyDescriptionChanged - * @property {string} type the topology type. - * @property {string} parserType the parser type used (c++ or js). - */ -var Server = function(options) { - options = options || {}; - - // Add event listener - EventEmitter.call(this); - - // Server instance id - this.id = id++; - - // Internal state - this.s = { - // Options - options: options, - // Logger - logger: Logger('Server', options), - // Factory overrides - Cursor: options.cursorFactory || CoreCursor, - // BSON instance - bson: - options.bson || - new BSON([ - BSON.Binary, - BSON.Code, - BSON.DBRef, - BSON.Decimal128, - BSON.Double, - BSON.Int32, - BSON.Long, - BSON.Map, - BSON.MaxKey, - BSON.MinKey, - BSON.ObjectId, - BSON.BSONRegExp, - BSON.Symbol, - BSON.Timestamp - ]), - // Pool - pool: null, - // Disconnect handler - disconnectHandler: options.disconnectHandler, - // Monitor thread (keeps the connection alive) - monitoring: typeof options.monitoring === 'boolean' ? options.monitoring : true, - // Is the server in a topology - inTopology: !!options.parent, - // Monitoring timeout - monitoringInterval: - typeof options.monitoringInterval === 'number' ? options.monitoringInterval : 5000, - // Topology id - topologyId: -1, - compression: { compressors: createCompressionInfo(options) }, - // Optional parent topology - parent: options.parent - }; - - // If this is a single deployment we need to track the clusterTime here - if (!this.s.parent) { - this.s.clusterTime = null; - } - - // Curent ismaster - this.ismaster = null; - // Current ping time - this.lastIsMasterMS = -1; - // The monitoringProcessId - this.monitoringProcessId = null; - // Initial connection - this.initialConnect = true; - // Default type - this._type = 'server'; - // Set the client info - this.clientInfo = createClientInfo(options); - - // Max Stalleness values - // last time we updated the ismaster state - this.lastUpdateTime = 0; - // Last write time - this.lastWriteDate = 0; - // Stalleness - this.staleness = 0; -}; - -inherits(Server, EventEmitter); -Object.assign(Server.prototype, SessionMixins); - -Object.defineProperty(Server.prototype, 'type', { - enumerable: true, - get: function() { - return this._type; - } -}); - -Object.defineProperty(Server.prototype, 'parserType', { - enumerable: true, - get: function() { - return BSON.native ? 'c++' : 'js'; - } -}); - -Object.defineProperty(Server.prototype, 'logicalSessionTimeoutMinutes', { - enumerable: true, - get: function() { - if (!this.ismaster) return null; - return this.ismaster.logicalSessionTimeoutMinutes || null; - } -}); - -// In single server deployments we track the clusterTime directly on the topology, however -// in Mongos and ReplSet deployments we instead need to delegate the clusterTime up to the -// tracking objects so we can ensure we are gossiping the maximum time received from the -// server. -Object.defineProperty(Server.prototype, 'clusterTime', { - enumerable: true, - set: function(clusterTime) { - const settings = this.s.parent ? this.s.parent : this.s; - resolveClusterTime(settings, clusterTime); - }, - get: function() { - const settings = this.s.parent ? this.s.parent : this.s; - return settings.clusterTime || null; - } -}); - -Server.enableServerAccounting = function() { - serverAccounting = true; - servers = {}; -}; - -Server.disableServerAccounting = function() { - serverAccounting = false; -}; - -Server.servers = function() { - return servers; -}; - -Object.defineProperty(Server.prototype, 'name', { - enumerable: true, - get: function() { - return this.s.options.host + ':' + this.s.options.port; - } -}); - -function disconnectHandler(self, type, ns, cmd, options, callback) { - // Topology is not connected, save the call in the provided store to be - // Executed at some point when the handler deems it's reconnected - if ( - !self.s.pool.isConnected() && - self.s.options.reconnect && - self.s.disconnectHandler != null && - !options.monitoring - ) { - self.s.disconnectHandler.add(type, ns, cmd, options, callback); - return true; - } - - // If we have no connection error - if (!self.s.pool.isConnected()) { - callback(new MongoError(f('no connection available to server %s', self.name))); - return true; - } -} - -function monitoringProcess(self) { - return function() { - // Pool was destroyed do not continue process - if (self.s.pool.isDestroyed()) return; - // Emit monitoring Process event - self.emit('monitoring', self); - // Perform ismaster call - // Get start time - var start = new Date().getTime(); - - // Execute the ismaster query - self.command( - 'admin.$cmd', - { ismaster: true }, - { - socketTimeout: - typeof self.s.options.connectionTimeout !== 'number' - ? 2000 - : self.s.options.connectionTimeout, - monitoring: true - }, - (err, result) => { - // Set initial lastIsMasterMS - self.lastIsMasterMS = new Date().getTime() - start; - if (self.s.pool.isDestroyed()) return; - // Update the ismaster view if we have a result - if (result) { - self.ismaster = result.result; - } - // Re-schedule the monitoring process - self.monitoringProcessId = setTimeout(monitoringProcess(self), self.s.monitoringInterval); - } - ); - }; -} - -var eventHandler = function(self, event) { - return function(err, conn) { - // Log information of received information if in info mode - if (self.s.logger.isInfo()) { - var object = err instanceof MongoError ? JSON.stringify(err) : {}; - self.s.logger.info( - f('server %s fired event %s out with message %s', self.name, event, object) - ); - } - - // Handle connect event - if (event === 'connect') { - self.initialConnect = false; - self.ismaster = conn.ismaster; - self.lastIsMasterMS = conn.lastIsMasterMS; - if (conn.agreedCompressor) { - self.s.pool.options.agreedCompressor = conn.agreedCompressor; - } - - if (conn.zlibCompressionLevel) { - self.s.pool.options.zlibCompressionLevel = conn.zlibCompressionLevel; - } - - if (conn.ismaster.$clusterTime) { - const $clusterTime = conn.ismaster.$clusterTime; - self.clusterTime = $clusterTime; - } - - // It's a proxy change the type so - // the wireprotocol will send $readPreference - if (self.ismaster.msg === 'isdbgrid') { - self._type = 'mongos'; - } - - // Have we defined self monitoring - if (self.s.monitoring) { - self.monitoringProcessId = setTimeout(monitoringProcess(self), self.s.monitoringInterval); - } - - // Emit server description changed if something listening - sdam.emitServerDescriptionChanged(self, { - address: self.name, - arbiters: [], - hosts: [], - passives: [], - type: sdam.getTopologyType(self) - }); - - if (!self.s.inTopology) { - // Emit topology description changed if something listening - sdam.emitTopologyDescriptionChanged(self, { - topologyType: 'Single', - servers: [ - { - address: self.name, - arbiters: [], - hosts: [], - passives: [], - type: sdam.getTopologyType(self) - } - ] - }); - } - - // Log the ismaster if available - if (self.s.logger.isInfo()) { - self.s.logger.info( - f('server %s connected with ismaster [%s]', self.name, JSON.stringify(self.ismaster)) - ); - } - - // Emit connect - self.emit('connect', self); - } else if ( - event === 'error' || - event === 'parseError' || - event === 'close' || - event === 'timeout' || - event === 'reconnect' || - event === 'attemptReconnect' || - 'reconnectFailed' - ) { - // Remove server instance from accounting - if ( - serverAccounting && - ['close', 'timeout', 'error', 'parseError', 'reconnectFailed'].indexOf(event) !== -1 - ) { - // Emit toplogy opening event if not in topology - if (!self.s.inTopology) { - self.emit('topologyOpening', { topologyId: self.id }); - } - - delete servers[self.id]; - } - - if (event === 'close') { - // Closing emits a server description changed event going to unknown. - sdam.emitServerDescriptionChanged(self, { - address: self.name, - arbiters: [], - hosts: [], - passives: [], - type: 'Unknown' - }); - } - - // Reconnect failed return error - if (event === 'reconnectFailed') { - self.emit('reconnectFailed', err); - // Emit error if any listeners - if (self.listeners('error').length > 0) { - self.emit('error', err); - } - // Terminate - return; - } - - // On first connect fail - if ( - ['disconnected', 'connecting'].indexOf(self.s.pool.state) !== -1 && - self.initialConnect && - ['close', 'timeout', 'error', 'parseError'].indexOf(event) !== -1 - ) { - self.initialConnect = false; - return self.emit( - 'error', - new MongoNetworkError( - f('failed to connect to server [%s] on first connect [%s]', self.name, err) - ) - ); - } - - // Reconnect event, emit the server - if (event === 'reconnect') { - // Reconnecting emits a server description changed event going from unknown to the - // current server type. - sdam.emitServerDescriptionChanged(self, { - address: self.name, - arbiters: [], - hosts: [], - passives: [], - type: sdam.getTopologyType(self) - }); - return self.emit(event, self); - } - - // Emit the event - self.emit(event, err); - } - }; -}; - -/** - * Initiate server connect - */ -Server.prototype.connect = function(options) { - var self = this; - options = options || {}; - - // Set the connections - if (serverAccounting) servers[this.id] = this; - - // Do not allow connect to be called on anything that's not disconnected - if (self.s.pool && !self.s.pool.isDisconnected() && !self.s.pool.isDestroyed()) { - throw new MongoError(f('server instance in invalid state %s', self.s.pool.state)); - } - - // Create a pool - self.s.pool = new Pool(this, Object.assign(self.s.options, options, { bson: this.s.bson })); - - // Set up listeners - self.s.pool.on('close', eventHandler(self, 'close')); - self.s.pool.on('error', eventHandler(self, 'error')); - self.s.pool.on('timeout', eventHandler(self, 'timeout')); - self.s.pool.on('parseError', eventHandler(self, 'parseError')); - self.s.pool.on('connect', eventHandler(self, 'connect')); - self.s.pool.on('reconnect', eventHandler(self, 'reconnect')); - self.s.pool.on('reconnectFailed', eventHandler(self, 'reconnectFailed')); - - // Set up listeners for command monitoring - relayEvents(self.s.pool, self, ['commandStarted', 'commandSucceeded', 'commandFailed']); - - // Emit toplogy opening event if not in topology - if (!self.s.inTopology) { - this.emit('topologyOpening', { topologyId: self.id }); - } - - // Emit opening server event - self.emit('serverOpening', { - topologyId: self.s.topologyId !== -1 ? self.s.topologyId : self.id, - address: self.name - }); - - self.s.pool.connect(); -}; - -/** - * Authenticate the topology. - * @method - * @param {MongoCredentials} credentials The credentials for authentication we are using - * @param {authResultCallback} callback A callback function - */ -Server.prototype.auth = function(credentials, callback) { - if (typeof callback === 'function') callback(null, null); -}; - -/** - * Get the server description - * @method - * @return {object} - */ -Server.prototype.getDescription = function() { - var ismaster = this.ismaster || {}; - var description = { - type: sdam.getTopologyType(this), - address: this.name - }; - - // Add fields if available - if (ismaster.hosts) description.hosts = ismaster.hosts; - if (ismaster.arbiters) description.arbiters = ismaster.arbiters; - if (ismaster.passives) description.passives = ismaster.passives; - if (ismaster.setName) description.setName = ismaster.setName; - return description; -}; - -/** - * Returns the last known ismaster document for this server - * @method - * @return {object} - */ -Server.prototype.lastIsMaster = function() { - return this.ismaster; -}; - -/** - * Unref all connections belong to this server - * @method - */ -Server.prototype.unref = function() { - this.s.pool.unref(); -}; - -/** - * Figure out if the server is connected - * @method - * @return {boolean} - */ -Server.prototype.isConnected = function() { - if (!this.s.pool) return false; - return this.s.pool.isConnected(); -}; - -/** - * Figure out if the server instance was destroyed by calling destroy - * @method - * @return {boolean} - */ -Server.prototype.isDestroyed = function() { - if (!this.s.pool) return false; - return this.s.pool.isDestroyed(); -}; - -function basicWriteValidations(self) { - if (!self.s.pool) return new MongoError('server instance is not connected'); - if (self.s.pool.isDestroyed()) return new MongoError('server instance pool was destroyed'); -} - -function basicReadValidations(self, options) { - basicWriteValidations(self, options); - - if (options.readPreference && !(options.readPreference instanceof ReadPreference)) { - throw new Error('readPreference must be an instance of ReadPreference'); - } -} - -/** - * Execute a command - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object} cmd The command hash - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.checkKeys=false] Specify if the bson parser should validate keys. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {Boolean} [options.fullResult=false] Return the full envelope instead of just the result document. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {opResultCallback} callback A callback function - */ -Server.prototype.command = function(ns, cmd, options, callback) { - var self = this; - if (typeof options === 'function') { - (callback = options), (options = {}), (options = options || {}); - } - - var result = basicReadValidations(self, options); - if (result) return callback(result); - - // Clone the options - options = Object.assign({}, options, { wireProtocolCommand: false }); - - // Debug log - if (self.s.logger.isDebug()) - self.s.logger.debug( - f( - 'executing command [%s] against %s', - JSON.stringify({ - ns: ns, - cmd: cmd, - options: debugOptions(debugFields, options) - }), - self.name - ) - ); - - // If we are not connected or have a disconnectHandler specified - if (disconnectHandler(self, 'command', ns, cmd, options, callback)) return; - - // error if collation not supported - if (collationNotSupported(this, cmd)) { - return callback(new MongoError(`server ${this.name} does not support collation`)); - } - - wireProtocol.command(self, ns, cmd, options, callback); -}; - -/** - * Execute a query against the server - * - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object} cmd The command document for the query - * @param {object} options Optional settings - * @param {function} callback - */ -Server.prototype.query = function(ns, cmd, cursorState, options, callback) { - wireProtocol.query(this, ns, cmd, cursorState, options, callback); -}; - -/** - * Execute a `getMore` against the server - * - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object} cursorState State data associated with the cursor calling this method - * @param {object} options Optional settings - * @param {function} callback - */ -Server.prototype.getMore = function(ns, cursorState, batchSize, options, callback) { - wireProtocol.getMore(this, ns, cursorState, batchSize, options, callback); -}; - -/** - * Execute a `killCursors` command against the server - * - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object} cursorState State data associated with the cursor calling this method - * @param {function} callback - */ -Server.prototype.killCursors = function(ns, cursorState, callback) { - wireProtocol.killCursors(this, ns, cursorState, callback); -}; - -/** - * Insert one or more documents - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of documents to insert - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {opResultCallback} callback A callback function - */ -Server.prototype.insert = function(ns, ops, options, callback) { - var self = this; - if (typeof options === 'function') { - (callback = options), (options = {}), (options = options || {}); - } - - var result = basicWriteValidations(self, options); - if (result) return callback(result); - - // If we are not connected or have a disconnectHandler specified - if (disconnectHandler(self, 'insert', ns, ops, options, callback)) return; - - // Setup the docs as an array - ops = Array.isArray(ops) ? ops : [ops]; - - // Execute write - return wireProtocol.insert(self, ns, ops, options, callback); -}; - -/** - * Perform one or more update operations - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of updates - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {opResultCallback} callback A callback function - */ -Server.prototype.update = function(ns, ops, options, callback) { - var self = this; - if (typeof options === 'function') { - (callback = options), (options = {}), (options = options || {}); - } - - var result = basicWriteValidations(self, options); - if (result) return callback(result); - - // If we are not connected or have a disconnectHandler specified - if (disconnectHandler(self, 'update', ns, ops, options, callback)) return; - - // error if collation not supported - if (collationNotSupported(this, options)) { - return callback(new MongoError(`server ${this.name} does not support collation`)); - } - - // Setup the docs as an array - ops = Array.isArray(ops) ? ops : [ops]; - // Execute write - return wireProtocol.update(self, ns, ops, options, callback); -}; - -/** - * Perform one or more remove operations - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of removes - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {opResultCallback} callback A callback function - */ -Server.prototype.remove = function(ns, ops, options, callback) { - var self = this; - if (typeof options === 'function') { - (callback = options), (options = {}), (options = options || {}); - } - - var result = basicWriteValidations(self, options); - if (result) return callback(result); - - // If we are not connected or have a disconnectHandler specified - if (disconnectHandler(self, 'remove', ns, ops, options, callback)) return; - - // error if collation not supported - if (collationNotSupported(this, options)) { - return callback(new MongoError(`server ${this.name} does not support collation`)); - } - - // Setup the docs as an array - ops = Array.isArray(ops) ? ops : [ops]; - // Execute write - return wireProtocol.remove(self, ns, ops, options, callback); -}; - -/** - * Get a new cursor - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object|Long} cmd Can be either a command returning a cursor or a cursorId - * @param {object} [options] Options for the cursor - * @param {object} [options.batchSize=0] Batchsize for the operation - * @param {array} [options.documents=[]] Initial documents list for cursor - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {object} [options.topology] The internal topology of the created cursor - * @returns {Cursor} - */ -Server.prototype.cursor = function(ns, cmd, options) { - options = options || {}; - const topology = options.topology || this; - - // Set up final cursor type - var FinalCursor = options.cursorFactory || this.s.Cursor; - - // Return the cursor - return new FinalCursor(topology, ns, cmd, options); -}; - -/** - * Compare two server instances - * @method - * @param {Server} server Server to compare equality against - * @return {boolean} - */ -Server.prototype.equals = function(server) { - if (typeof server === 'string') return this.name.toLowerCase() === server.toLowerCase(); - if (server.name) return this.name.toLowerCase() === server.name.toLowerCase(); - return false; -}; - -/** - * All raw connections - * @method - * @return {Connection[]} - */ -Server.prototype.connections = function() { - return this.s.pool.allConnections(); -}; - -/** - * Selects a server - * @method - * @param {function} selector Unused - * @param {ReadPreference} [options.readPreference] Unused - * @param {ClientSession} [options.session] Unused - * @return {Server} - */ -Server.prototype.selectServer = function(selector, options, callback) { - if (typeof selector === 'function' && typeof callback === 'undefined') - (callback = selector), (selector = undefined), (options = {}); - if (typeof options === 'function') - (callback = options), (options = selector), (selector = undefined); - - callback(null, this); -}; - -var listeners = ['close', 'error', 'timeout', 'parseError', 'connect']; - -/** - * Destroy the server connection - * @method - * @param {boolean} [options.emitClose=false] Emit close event on destroy - * @param {boolean} [options.emitDestroy=false] Emit destroy event on destroy - * @param {boolean} [options.force=false] Force destroy the pool - */ -Server.prototype.destroy = function(options, callback) { - if (this._destroyed) { - if (typeof callback === 'function') callback(null, null); - return; - } - - if (typeof options === 'function') { - callback = options; - options = {}; - } - - options = options || {}; - var self = this; - - // Set the connections - if (serverAccounting) delete servers[this.id]; - - // Destroy the monitoring process if any - if (this.monitoringProcessId) { - clearTimeout(this.monitoringProcessId); - } - - // No pool, return - if (!self.s.pool) { - this._destroyed = true; - if (typeof callback === 'function') callback(null, null); - return; - } - - // Emit close event - if (options.emitClose) { - self.emit('close', self); - } - - // Emit destroy event - if (options.emitDestroy) { - self.emit('destroy', self); - } - - // Remove all listeners - listeners.forEach(function(event) { - self.s.pool.removeAllListeners(event); - }); - - // Emit opening server event - if (self.listeners('serverClosed').length > 0) - self.emit('serverClosed', { - topologyId: self.s.topologyId !== -1 ? self.s.topologyId : self.id, - address: self.name - }); - - // Emit toplogy opening event if not in topology - if (self.listeners('topologyClosed').length > 0 && !self.s.inTopology) { - self.emit('topologyClosed', { topologyId: self.id }); - } - - if (self.s.logger.isDebug()) { - self.s.logger.debug(f('destroy called on server %s', self.name)); - } - - // Destroy the pool - this.s.pool.destroy(options.force, callback); - this._destroyed = true; -}; - -/** - * A server connect event, used to verify that the connection is up and running - * - * @event Server#connect - * @type {Server} - */ - -/** - * A server reconnect event, used to verify that the server topology has reconnected - * - * @event Server#reconnect - * @type {Server} - */ - -/** - * A server opening SDAM monitoring event - * - * @event Server#serverOpening - * @type {object} - */ - -/** - * A server closed SDAM monitoring event - * - * @event Server#serverClosed - * @type {object} - */ - -/** - * A server description SDAM change monitoring event - * - * @event Server#serverDescriptionChanged - * @type {object} - */ - -/** - * A topology open SDAM event - * - * @event Server#topologyOpening - * @type {object} - */ - -/** - * A topology closed SDAM event - * - * @event Server#topologyClosed - * @type {object} - */ - -/** - * A topology structure SDAM change event - * - * @event Server#topologyDescriptionChanged - * @type {object} - */ - -/** - * Server reconnect failed - * - * @event Server#reconnectFailed - * @type {Error} - */ - -/** - * Server connection pool closed - * - * @event Server#close - * @type {object} - */ - -/** - * Server connection pool caused an error - * - * @event Server#error - * @type {Error} - */ - -/** - * Server destroyed was called - * - * @event Server#destroy - * @type {Server} - */ - -module.exports = Server; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/topologies/shared.js b/scripts/2.5/node_modules/mongodb/lib/core/topologies/shared.js deleted file mode 100644 index 8e227bad..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/core/topologies/shared.js +++ /dev/null @@ -1,476 +0,0 @@ -'use strict'; - -const os = require('os'); -const f = require('util').format; -const ReadPreference = require('./read_preference'); -const Buffer = require('safe-buffer').Buffer; -const TopologyType = require('../sdam/topology_description').TopologyType; -const MongoError = require('../error').MongoError; - -const MMAPv1_RETRY_WRITES_ERROR_CODE = 20; - -/** - * Emit event if it exists - * @method - */ -function emitSDAMEvent(self, event, description) { - if (self.listeners(event).length > 0) { - self.emit(event, description); - } -} - -// Get package.json variable -var driverVersion = require('../../../package.json').version; -var nodejsversion = f('Node.js %s, %s', process.version, os.endianness()); -var type = os.type(); -var name = process.platform; -var architecture = process.arch; -var release = os.release(); - -function createClientInfo(options) { - // Build default client information - var clientInfo = options.clientInfo - ? clone(options.clientInfo) - : { - driver: { - name: 'nodejs-core', - version: driverVersion - }, - os: { - type: type, - name: name, - architecture: architecture, - version: release - } - }; - - // Is platform specified - if (clientInfo.platform && clientInfo.platform.indexOf('mongodb-core') === -1) { - clientInfo.platform = f('%s, mongodb-core: %s', clientInfo.platform, driverVersion); - } else if (!clientInfo.platform) { - clientInfo.platform = nodejsversion; - } - - // Do we have an application specific string - if (options.appname) { - // Cut at 128 bytes - var buffer = Buffer.from(options.appname); - // Return the truncated appname - var appname = buffer.length > 128 ? buffer.slice(0, 128).toString('utf8') : options.appname; - // Add to the clientInfo - clientInfo.application = { name: appname }; - } - - return clientInfo; -} - -function createCompressionInfo(options) { - if (!options.compression || !options.compression.compressors) { - return []; - } - - // Check that all supplied compressors are valid - options.compression.compressors.forEach(function(compressor) { - if (compressor !== 'snappy' && compressor !== 'zlib') { - throw new Error('compressors must be at least one of snappy or zlib'); - } - }); - - return options.compression.compressors; -} - -function clone(object) { - return JSON.parse(JSON.stringify(object)); -} - -var getPreviousDescription = function(self) { - if (!self.s.serverDescription) { - self.s.serverDescription = { - address: self.name, - arbiters: [], - hosts: [], - passives: [], - type: 'Unknown' - }; - } - - return self.s.serverDescription; -}; - -var emitServerDescriptionChanged = function(self, description) { - if (self.listeners('serverDescriptionChanged').length > 0) { - // Emit the server description changed events - self.emit('serverDescriptionChanged', { - topologyId: self.s.topologyId !== -1 ? self.s.topologyId : self.id, - address: self.name, - previousDescription: getPreviousDescription(self), - newDescription: description - }); - - self.s.serverDescription = description; - } -}; - -var getPreviousTopologyDescription = function(self) { - if (!self.s.topologyDescription) { - self.s.topologyDescription = { - topologyType: 'Unknown', - servers: [ - { - address: self.name, - arbiters: [], - hosts: [], - passives: [], - type: 'Unknown' - } - ] - }; - } - - return self.s.topologyDescription; -}; - -var emitTopologyDescriptionChanged = function(self, description) { - if (self.listeners('topologyDescriptionChanged').length > 0) { - // Emit the server description changed events - self.emit('topologyDescriptionChanged', { - topologyId: self.s.topologyId !== -1 ? self.s.topologyId : self.id, - address: self.name, - previousDescription: getPreviousTopologyDescription(self), - newDescription: description - }); - - self.s.serverDescription = description; - } -}; - -var changedIsMaster = function(self, currentIsmaster, ismaster) { - var currentType = getTopologyType(self, currentIsmaster); - var newType = getTopologyType(self, ismaster); - if (newType !== currentType) return true; - return false; -}; - -var getTopologyType = function(self, ismaster) { - if (!ismaster) { - ismaster = self.ismaster; - } - - if (!ismaster) return 'Unknown'; - if (ismaster.ismaster && ismaster.msg === 'isdbgrid') return 'Mongos'; - if (ismaster.ismaster && !ismaster.hosts) return 'Standalone'; - if (ismaster.ismaster) return 'RSPrimary'; - if (ismaster.secondary) return 'RSSecondary'; - if (ismaster.arbiterOnly) return 'RSArbiter'; - return 'Unknown'; -}; - -var inquireServerState = function(self) { - return function(callback) { - if (self.s.state === 'destroyed') return; - // Record response time - var start = new Date().getTime(); - - // emitSDAMEvent - emitSDAMEvent(self, 'serverHeartbeatStarted', { connectionId: self.name }); - - // Attempt to execute ismaster command - self.command('admin.$cmd', { ismaster: true }, { monitoring: true }, function(err, r) { - if (!err) { - // Legacy event sender - self.emit('ismaster', r, self); - - // Calculate latencyMS - var latencyMS = new Date().getTime() - start; - - // Server heart beat event - emitSDAMEvent(self, 'serverHeartbeatSucceeded', { - durationMS: latencyMS, - reply: r.result, - connectionId: self.name - }); - - // Did the server change - if (changedIsMaster(self, self.s.ismaster, r.result)) { - // Emit server description changed if something listening - emitServerDescriptionChanged(self, { - address: self.name, - arbiters: [], - hosts: [], - passives: [], - type: !self.s.inTopology ? 'Standalone' : getTopologyType(self) - }); - } - - // Updat ismaster view - self.s.ismaster = r.result; - - // Set server response time - self.s.isMasterLatencyMS = latencyMS; - } else { - emitSDAMEvent(self, 'serverHeartbeatFailed', { - durationMS: latencyMS, - failure: err, - connectionId: self.name - }); - } - - // Peforming an ismaster monitoring callback operation - if (typeof callback === 'function') { - return callback(err, r); - } - - // Perform another sweep - self.s.inquireServerStateTimeout = setTimeout(inquireServerState(self), self.s.haInterval); - }); - }; -}; - -// -// Clone the options -var cloneOptions = function(options) { - var opts = {}; - for (var name in options) { - opts[name] = options[name]; - } - return opts; -}; - -function Interval(fn, time) { - var timer = false; - - this.start = function() { - if (!this.isRunning()) { - timer = setInterval(fn, time); - } - - return this; - }; - - this.stop = function() { - clearInterval(timer); - timer = false; - return this; - }; - - this.isRunning = function() { - return timer !== false; - }; -} - -function Timeout(fn, time) { - var timer = false; - - this.start = function() { - if (!this.isRunning()) { - timer = setTimeout(fn, time); - } - return this; - }; - - this.stop = function() { - clearTimeout(timer); - timer = false; - return this; - }; - - this.isRunning = function() { - if (timer && timer._called) return false; - return timer !== false; - }; -} - -function diff(previous, current) { - // Difference document - var diff = { - servers: [] - }; - - // Previous entry - if (!previous) { - previous = { servers: [] }; - } - - // Check if we have any previous servers missing in the current ones - for (var i = 0; i < previous.servers.length; i++) { - var found = false; - - for (var j = 0; j < current.servers.length; j++) { - if (current.servers[j].address.toLowerCase() === previous.servers[i].address.toLowerCase()) { - found = true; - break; - } - } - - if (!found) { - // Add to the diff - diff.servers.push({ - address: previous.servers[i].address, - from: previous.servers[i].type, - to: 'Unknown' - }); - } - } - - // Check if there are any severs that don't exist - for (j = 0; j < current.servers.length; j++) { - found = false; - - // Go over all the previous servers - for (i = 0; i < previous.servers.length; i++) { - if (previous.servers[i].address.toLowerCase() === current.servers[j].address.toLowerCase()) { - found = true; - break; - } - } - - // Add the server to the diff - if (!found) { - diff.servers.push({ - address: current.servers[j].address, - from: 'Unknown', - to: current.servers[j].type - }); - } - } - - // Got through all the servers - for (i = 0; i < previous.servers.length; i++) { - var prevServer = previous.servers[i]; - - // Go through all current servers - for (j = 0; j < current.servers.length; j++) { - var currServer = current.servers[j]; - - // Matching server - if (prevServer.address.toLowerCase() === currServer.address.toLowerCase()) { - // We had a change in state - if (prevServer.type !== currServer.type) { - diff.servers.push({ - address: prevServer.address, - from: prevServer.type, - to: currServer.type - }); - } - } - } - } - - // Return difference - return diff; -} - -/** - * Shared function to determine clusterTime for a given topology - * - * @param {*} topology - * @param {*} clusterTime - */ -function resolveClusterTime(topology, $clusterTime) { - if (topology.clusterTime == null) { - topology.clusterTime = $clusterTime; - } else { - if ($clusterTime.clusterTime.greaterThan(topology.clusterTime.clusterTime)) { - topology.clusterTime = $clusterTime; - } - } -} - -// NOTE: this is a temporary move until the topologies can be more formally refactored -// to share code. -const SessionMixins = { - endSessions: function(sessions, callback) { - if (!Array.isArray(sessions)) { - sessions = [sessions]; - } - - // TODO: - // When connected to a sharded cluster the endSessions command - // can be sent to any mongos. When connected to a replica set the - // endSessions command MUST be sent to the primary if the primary - // is available, otherwise it MUST be sent to any available secondary. - // Is it enough to use: ReadPreference.primaryPreferred ? - this.command( - 'admin.$cmd', - { endSessions: sessions }, - { readPreference: ReadPreference.primaryPreferred }, - () => { - // intentionally ignored, per spec - if (typeof callback === 'function') callback(); - } - ); - } -}; - -function topologyType(topology) { - if (topology.description) { - return topology.description.type; - } - - if (topology.type === 'mongos') { - return TopologyType.Sharded; - } else if (topology.type === 'replset') { - return TopologyType.ReplicaSetWithPrimary; - } - - return TopologyType.Single; -} - -const RETRYABLE_WIRE_VERSION = 6; - -/** - * Determines whether the provided topology supports retryable writes - * - * @param {Mongos|Replset} topology - */ -const isRetryableWritesSupported = function(topology) { - const maxWireVersion = topology.lastIsMaster().maxWireVersion; - if (maxWireVersion < RETRYABLE_WIRE_VERSION) { - return false; - } - - if (!topology.logicalSessionTimeoutMinutes) { - return false; - } - - if (topologyType(topology) === TopologyType.Single) { - return false; - } - - return true; -}; - -const MMAPv1_RETRY_WRITES_ERROR_MESSAGE = - 'This MongoDB deployment does not support retryable writes. Please add retryWrites=false to your connection string.'; - -function getMMAPError(err) { - if (err.code !== MMAPv1_RETRY_WRITES_ERROR_CODE || !err.errmsg.includes('Transaction numbers')) { - return err; - } - - // According to the retryable writes spec, we must replace the error message in this case. - // We need to replace err.message so the thrown message is correct and we need to replace err.errmsg to meet the spec requirement. - const newErr = new MongoError({ - message: MMAPv1_RETRY_WRITES_ERROR_MESSAGE, - errmsg: MMAPv1_RETRY_WRITES_ERROR_MESSAGE, - originalError: err - }); - return newErr; -} - -module.exports.SessionMixins = SessionMixins; -module.exports.resolveClusterTime = resolveClusterTime; -module.exports.inquireServerState = inquireServerState; -module.exports.getTopologyType = getTopologyType; -module.exports.emitServerDescriptionChanged = emitServerDescriptionChanged; -module.exports.emitTopologyDescriptionChanged = emitTopologyDescriptionChanged; -module.exports.cloneOptions = cloneOptions; -module.exports.createClientInfo = createClientInfo; -module.exports.createCompressionInfo = createCompressionInfo; -module.exports.clone = clone; -module.exports.diff = diff; -module.exports.Interval = Interval; -module.exports.Timeout = Timeout; -module.exports.isRetryableWritesSupported = isRetryableWritesSupported; -module.exports.getMMAPError = getMMAPError; -module.exports.topologyType = topologyType; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/transactions.js b/scripts/2.5/node_modules/mongodb/lib/core/transactions.js deleted file mode 100644 index 891a8734..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/core/transactions.js +++ /dev/null @@ -1,168 +0,0 @@ -'use strict'; -const MongoError = require('./error').MongoError; - -let TxnState; -let stateMachine; - -(() => { - const NO_TRANSACTION = 'NO_TRANSACTION'; - const STARTING_TRANSACTION = 'STARTING_TRANSACTION'; - const TRANSACTION_IN_PROGRESS = 'TRANSACTION_IN_PROGRESS'; - const TRANSACTION_COMMITTED = 'TRANSACTION_COMMITTED'; - const TRANSACTION_COMMITTED_EMPTY = 'TRANSACTION_COMMITTED_EMPTY'; - const TRANSACTION_ABORTED = 'TRANSACTION_ABORTED'; - - TxnState = { - NO_TRANSACTION, - STARTING_TRANSACTION, - TRANSACTION_IN_PROGRESS, - TRANSACTION_COMMITTED, - TRANSACTION_COMMITTED_EMPTY, - TRANSACTION_ABORTED - }; - - stateMachine = { - [NO_TRANSACTION]: [NO_TRANSACTION, STARTING_TRANSACTION], - [STARTING_TRANSACTION]: [ - TRANSACTION_IN_PROGRESS, - TRANSACTION_COMMITTED, - TRANSACTION_COMMITTED_EMPTY, - TRANSACTION_ABORTED - ], - [TRANSACTION_IN_PROGRESS]: [ - TRANSACTION_IN_PROGRESS, - TRANSACTION_COMMITTED, - TRANSACTION_ABORTED - ], - [TRANSACTION_COMMITTED]: [ - TRANSACTION_COMMITTED, - TRANSACTION_COMMITTED_EMPTY, - STARTING_TRANSACTION, - NO_TRANSACTION - ], - [TRANSACTION_ABORTED]: [STARTING_TRANSACTION, NO_TRANSACTION], - [TRANSACTION_COMMITTED_EMPTY]: [TRANSACTION_COMMITTED_EMPTY, NO_TRANSACTION] - }; -})(); - -/** - * The MongoDB ReadConcern, which allows for control of the consistency and isolation properties - * of the data read from replica sets and replica set shards. - * @typedef {Object} ReadConcern - * @property {'local'|'available'|'majority'|'linearizable'|'snapshot'} level The readConcern Level - * @see https://docs.mongodb.com/manual/reference/read-concern/ - */ - -/** - * A MongoDB WriteConcern, which describes the level of acknowledgement - * requested from MongoDB for write operations. - * @typedef {Object} WriteConcern - * @property {number|'majority'|string} [w=1] requests acknowledgement that the write operation has - * propagated to a specified number of mongod hosts - * @property {boolean} [j=false] requests acknowledgement from MongoDB that the write operation has - * been written to the journal - * @property {number} [wtimeout] a time limit, in milliseconds, for the write concern - * @see https://docs.mongodb.com/manual/reference/write-concern/ - */ - -/** - * Configuration options for a transaction. - * @typedef {Object} TransactionOptions - * @property {ReadConcern} [readConcern] A default read concern for commands in this transaction - * @property {WriteConcern} [writeConcern] A default writeConcern for commands in this transaction - * @property {ReadPreference} [readPreference] A default read preference for commands in this transaction - */ - -/** - * A class maintaining state related to a server transaction. Internal Only - * @ignore - */ -class Transaction { - /** - * Create a transaction - * - * @ignore - * @param {TransactionOptions} [options] Optional settings - */ - constructor(options) { - options = options || {}; - - this.state = TxnState.NO_TRANSACTION; - this.options = {}; - - if (options.writeConcern || typeof options.w !== 'undefined') { - const w = options.writeConcern ? options.writeConcern.w : options.w; - if (w <= 0) { - throw new MongoError('Transactions do not support unacknowledged write concern'); - } - - this.options.writeConcern = options.writeConcern ? options.writeConcern : { w: options.w }; - } - - if (options.readConcern) this.options.readConcern = options.readConcern; - if (options.readPreference) this.options.readPreference = options.readPreference; - if (options.maxCommitTimeMS) this.options.maxTimeMS = options.maxCommitTimeMS; - - // TODO: This isn't technically necessary - this._pinnedServer = undefined; - this._recoveryToken = undefined; - } - - get server() { - return this._pinnedServer; - } - - get recoveryToken() { - return this._recoveryToken; - } - - get isPinned() { - return !!this.server; - } - - /** - * @ignore - * @return Whether this session is presently in a transaction - */ - get isActive() { - return ( - [TxnState.STARTING_TRANSACTION, TxnState.TRANSACTION_IN_PROGRESS].indexOf(this.state) !== -1 - ); - } - - /** - * Transition the transaction in the state machine - * @ignore - * @param {TxnState} state The new state to transition to - */ - transition(nextState) { - const nextStates = stateMachine[this.state]; - if (nextStates && nextStates.indexOf(nextState) !== -1) { - this.state = nextState; - if (this.state === TxnState.NO_TRANSACTION || this.state === TxnState.STARTING_TRANSACTION) { - this.unpinServer(); - } - return; - } - - throw new MongoError( - `Attempted illegal state transition from [${this.state}] to [${nextState}]` - ); - } - - pinServer(server) { - if (this.isActive) { - this._pinnedServer = server; - } - } - - unpinServer() { - this._pinnedServer = undefined; - } -} - -function isTransactionCommand(command) { - return !!(command.commitTransaction || command.abortTransaction); -} - -module.exports = { TxnState, Transaction, isTransactionCommand }; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/uri_parser.js b/scripts/2.5/node_modules/mongodb/lib/core/uri_parser.js deleted file mode 100644 index 1530d88d..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/core/uri_parser.js +++ /dev/null @@ -1,637 +0,0 @@ -'use strict'; -const URL = require('url'); -const qs = require('querystring'); -const dns = require('dns'); -const MongoParseError = require('./error').MongoParseError; -const ReadPreference = require('./topologies/read_preference'); - -/** - * The following regular expression validates a connection string and breaks the - * provide string into the following capture groups: [protocol, username, password, hosts] - */ -const HOSTS_RX = /(mongodb(?:\+srv|)):\/\/(?: (?:[^:]*) (?: : ([^@]*) )? @ )?([^/?]*)(?:\/|)(.*)/; - -/** - * Determines whether a provided address matches the provided parent domain in order - * to avoid certain attack vectors. - * - * @param {String} srvAddress The address to check against a domain - * @param {String} parentDomain The domain to check the provided address against - * @return {Boolean} Whether the provided address matches the parent domain - */ -function matchesParentDomain(srvAddress, parentDomain) { - const regex = /^.*?\./; - const srv = `.${srvAddress.replace(regex, '')}`; - const parent = `.${parentDomain.replace(regex, '')}`; - return srv.endsWith(parent); -} - -/** - * Lookup a `mongodb+srv` connection string, combine the parts and reparse it as a normal - * connection string. - * - * @param {string} uri The connection string to parse - * @param {object} options Optional user provided connection string options - * @param {function} callback - */ -function parseSrvConnectionString(uri, options, callback) { - const result = URL.parse(uri, true); - - if (result.hostname.split('.').length < 3) { - return callback(new MongoParseError('URI does not have hostname, domain name and tld')); - } - - result.domainLength = result.hostname.split('.').length; - if (result.pathname && result.pathname.match(',')) { - return callback(new MongoParseError('Invalid URI, cannot contain multiple hostnames')); - } - - if (result.port) { - return callback(new MongoParseError(`Ports not accepted with '${PROTOCOL_MONGODB_SRV}' URIs`)); - } - - // Resolve the SRV record and use the result as the list of hosts to connect to. - const lookupAddress = result.host; - dns.resolveSrv(`_mongodb._tcp.${lookupAddress}`, (err, addresses) => { - if (err) return callback(err); - - if (addresses.length === 0) { - return callback(new MongoParseError('No addresses found at host')); - } - - for (let i = 0; i < addresses.length; i++) { - if (!matchesParentDomain(addresses[i].name, result.hostname, result.domainLength)) { - return callback( - new MongoParseError('Server record does not share hostname with parent URI') - ); - } - } - - // Convert the original URL to a non-SRV URL. - result.protocol = 'mongodb'; - result.host = addresses.map(address => `${address.name}:${address.port}`).join(','); - - // Default to SSL true if it's not specified. - if ( - !('ssl' in options) && - (!result.search || !('ssl' in result.query) || result.query.ssl === null) - ) { - result.query.ssl = true; - } - - // Resolve TXT record and add options from there if they exist. - dns.resolveTxt(lookupAddress, (err, record) => { - if (err) { - if (err.code !== 'ENODATA') { - return callback(err); - } - record = null; - } - - if (record) { - if (record.length > 1) { - return callback(new MongoParseError('Multiple text records not allowed')); - } - - record = qs.parse(record[0].join('')); - if (Object.keys(record).some(key => key !== 'authSource' && key !== 'replicaSet')) { - return callback( - new MongoParseError('Text record must only set `authSource` or `replicaSet`') - ); - } - - Object.assign(result.query, record); - } - - // Set completed options back into the URL object. - result.search = qs.stringify(result.query); - - const finalString = URL.format(result); - parseConnectionString(finalString, options, (err, ret) => { - if (err) { - callback(err); - return; - } - - callback(null, Object.assign({}, ret, { srvHost: lookupAddress })); - }); - }); - }); -} - -/** - * Parses a query string item according to the connection string spec - * - * @param {string} key The key for the parsed value - * @param {Array|String} value The value to parse - * @return {Array|Object|String} The parsed value - */ -function parseQueryStringItemValue(key, value) { - if (Array.isArray(value)) { - // deduplicate and simplify arrays - value = value.filter((v, idx) => value.indexOf(v) === idx); - if (value.length === 1) value = value[0]; - } else if (value.indexOf(':') > 0) { - value = value.split(',').reduce((result, pair) => { - const parts = pair.split(':'); - result[parts[0]] = parseQueryStringItemValue(key, parts[1]); - return result; - }, {}); - } else if (value.indexOf(',') > 0) { - value = value.split(',').map(v => { - return parseQueryStringItemValue(key, v); - }); - } else if (value.toLowerCase() === 'true' || value.toLowerCase() === 'false') { - value = value.toLowerCase() === 'true'; - } else if (!Number.isNaN(value) && !STRING_OPTIONS.has(key)) { - const numericValue = parseFloat(value); - if (!Number.isNaN(numericValue)) { - value = parseFloat(value); - } - } - - return value; -} - -// Options that are known boolean types -const BOOLEAN_OPTIONS = new Set([ - 'slaveok', - 'slave_ok', - 'sslvalidate', - 'fsync', - 'safe', - 'retrywrites', - 'j' -]); - -// Known string options, only used to bypass Number coercion in `parseQueryStringItemValue` -const STRING_OPTIONS = new Set(['authsource', 'replicaset']); - -// Supported text representations of auth mechanisms -// NOTE: this list exists in native already, if it is merged here we should deduplicate -const AUTH_MECHANISMS = new Set([ - 'GSSAPI', - 'MONGODB-X509', - 'MONGODB-CR', - 'DEFAULT', - 'SCRAM-SHA-1', - 'SCRAM-SHA-256', - 'PLAIN' -]); - -// Lookup table used to translate normalized (lower-cased) forms of connection string -// options to their expected camelCase version -const CASE_TRANSLATION = { - replicaset: 'replicaSet', - connecttimeoutms: 'connectTimeoutMS', - sockettimeoutms: 'socketTimeoutMS', - maxpoolsize: 'maxPoolSize', - minpoolsize: 'minPoolSize', - maxidletimems: 'maxIdleTimeMS', - waitqueuemultiple: 'waitQueueMultiple', - waitqueuetimeoutms: 'waitQueueTimeoutMS', - wtimeoutms: 'wtimeoutMS', - readconcern: 'readConcern', - readconcernlevel: 'readConcernLevel', - readpreference: 'readPreference', - maxstalenessseconds: 'maxStalenessSeconds', - readpreferencetags: 'readPreferenceTags', - authsource: 'authSource', - authmechanism: 'authMechanism', - authmechanismproperties: 'authMechanismProperties', - gssapiservicename: 'gssapiServiceName', - localthresholdms: 'localThresholdMS', - serverselectiontimeoutms: 'serverSelectionTimeoutMS', - serverselectiontryonce: 'serverSelectionTryOnce', - heartbeatfrequencyms: 'heartbeatFrequencyMS', - retrywrites: 'retryWrites', - uuidrepresentation: 'uuidRepresentation', - zlibcompressionlevel: 'zlibCompressionLevel', - tlsallowinvalidcertificates: 'tlsAllowInvalidCertificates', - tlsallowinvalidhostnames: 'tlsAllowInvalidHostnames', - tlsinsecure: 'tlsInsecure', - tlscafile: 'tlsCAFile', - tlscertificatekeyfile: 'tlsCertificateKeyFile', - tlscertificatekeyfilepassword: 'tlsCertificateKeyFilePassword', - wtimeout: 'wTimeoutMS', - j: 'journal' -}; - -/** - * Sets the value for `key`, allowing for any required translation - * - * @param {object} obj The object to set the key on - * @param {string} key The key to set the value for - * @param {*} value The value to set - * @param {object} options The options used for option parsing - */ -function applyConnectionStringOption(obj, key, value, options) { - // simple key translation - if (key === 'journal') { - key = 'j'; - } else if (key === 'wtimeoutms') { - key = 'wtimeout'; - } - - // more complicated translation - if (BOOLEAN_OPTIONS.has(key)) { - value = value === 'true' || value === true; - } else if (key === 'appname') { - value = decodeURIComponent(value); - } else if (key === 'readconcernlevel') { - obj['readConcernLevel'] = value; - key = 'readconcern'; - value = { level: value }; - } - - // simple validation - if (key === 'compressors') { - value = Array.isArray(value) ? value : [value]; - - if (!value.every(c => c === 'snappy' || c === 'zlib')) { - throw new MongoParseError( - 'Value for `compressors` must be at least one of: `snappy`, `zlib`' - ); - } - } - - if (key === 'authmechanism' && !AUTH_MECHANISMS.has(value)) { - throw new MongoParseError( - 'Value for `authMechanism` must be one of: `DEFAULT`, `GSSAPI`, `PLAIN`, `MONGODB-X509`, `SCRAM-SHA-1`, `SCRAM-SHA-256`' - ); - } - - if (key === 'readpreference' && !ReadPreference.isValid(value)) { - throw new MongoParseError( - 'Value for `readPreference` must be one of: `primary`, `primaryPreferred`, `secondary`, `secondaryPreferred`, `nearest`' - ); - } - - if (key === 'zlibcompressionlevel' && (value < -1 || value > 9)) { - throw new MongoParseError('zlibCompressionLevel must be an integer between -1 and 9'); - } - - // special cases - if (key === 'compressors' || key === 'zlibcompressionlevel') { - obj.compression = obj.compression || {}; - obj = obj.compression; - } - - if (key === 'authmechanismproperties') { - if (typeof value.SERVICE_NAME === 'string') obj.gssapiServiceName = value.SERVICE_NAME; - if (typeof value.SERVICE_REALM === 'string') obj.gssapiServiceRealm = value.SERVICE_REALM; - if (typeof value.CANONICALIZE_HOST_NAME !== 'undefined') { - obj.gssapiCanonicalizeHostName = value.CANONICALIZE_HOST_NAME; - } - } - - if (key === 'readpreferencetags' && Array.isArray(value)) { - value = splitArrayOfMultipleReadPreferenceTags(value); - } - - // set the actual value - if (options.caseTranslate && CASE_TRANSLATION[key]) { - obj[CASE_TRANSLATION[key]] = value; - return; - } - - obj[key] = value; -} - -const USERNAME_REQUIRED_MECHANISMS = new Set([ - 'GSSAPI', - 'MONGODB-CR', - 'PLAIN', - 'SCRAM-SHA-1', - 'SCRAM-SHA-256' -]); - -function splitArrayOfMultipleReadPreferenceTags(value) { - const parsedTags = []; - - for (let i = 0; i < value.length; i++) { - parsedTags[i] = {}; - value[i].split(',').forEach(individualTag => { - const splitTag = individualTag.split(':'); - parsedTags[i][splitTag[0]] = splitTag[1]; - }); - } - - return parsedTags; -} - -/** - * Modifies the parsed connection string object taking into account expectations we - * have for authentication-related options. - * - * @param {object} parsed The parsed connection string result - * @return The parsed connection string result possibly modified for auth expectations - */ -function applyAuthExpectations(parsed) { - if (parsed.options == null) { - return; - } - - const options = parsed.options; - const authSource = options.authsource || options.authSource; - if (authSource != null) { - parsed.auth = Object.assign({}, parsed.auth, { db: authSource }); - } - - const authMechanism = options.authmechanism || options.authMechanism; - if (authMechanism != null) { - if ( - USERNAME_REQUIRED_MECHANISMS.has(authMechanism) && - (!parsed.auth || parsed.auth.username == null) - ) { - throw new MongoParseError(`Username required for mechanism \`${authMechanism}\``); - } - - if (authMechanism === 'GSSAPI') { - if (authSource != null && authSource !== '$external') { - throw new MongoParseError( - `Invalid source \`${authSource}\` for mechanism \`${authMechanism}\` specified.` - ); - } - - parsed.auth = Object.assign({}, parsed.auth, { db: '$external' }); - } - - if (authMechanism === 'MONGODB-X509') { - if (parsed.auth && parsed.auth.password != null) { - throw new MongoParseError(`Password not allowed for mechanism \`${authMechanism}\``); - } - - if (authSource != null && authSource !== '$external') { - throw new MongoParseError( - `Invalid source \`${authSource}\` for mechanism \`${authMechanism}\` specified.` - ); - } - - parsed.auth = Object.assign({}, parsed.auth, { db: '$external' }); - } - - if (authMechanism === 'PLAIN') { - if (parsed.auth && parsed.auth.db == null) { - parsed.auth = Object.assign({}, parsed.auth, { db: '$external' }); - } - } - } - - // default to `admin` if nothing else was resolved - if (parsed.auth && parsed.auth.db == null) { - parsed.auth = Object.assign({}, parsed.auth, { db: 'admin' }); - } - - return parsed; -} - -/** - * Parses a query string according the connection string spec. - * - * @param {String} query The query string to parse - * @param {object} [options] The options used for options parsing - * @return {Object|Error} The parsed query string as an object, or an error if one was encountered - */ -function parseQueryString(query, options) { - const result = {}; - let parsedQueryString = qs.parse(query); - - checkTLSOptions(parsedQueryString); - - for (const key in parsedQueryString) { - const value = parsedQueryString[key]; - if (value === '' || value == null) { - throw new MongoParseError('Incomplete key value pair for option'); - } - - const normalizedKey = key.toLowerCase(); - const parsedValue = parseQueryStringItemValue(normalizedKey, value); - applyConnectionStringOption(result, normalizedKey, parsedValue, options); - } - - // special cases for known deprecated options - if (result.wtimeout && result.wtimeoutms) { - delete result.wtimeout; - console.warn('Unsupported option `wtimeout` specified'); - } - - return Object.keys(result).length ? result : null; -} - -/** - * Checks a query string for invalid tls options according to the URI options spec. - * - * @param {string} queryString The query string to check - * @throws {MongoParseError} - */ -function checkTLSOptions(queryString) { - const queryStringKeys = Object.keys(queryString); - if ( - queryStringKeys.indexOf('tlsInsecure') !== -1 && - (queryStringKeys.indexOf('tlsAllowInvalidCertificates') !== -1 || - queryStringKeys.indexOf('tlsAllowInvalidHostnames') !== -1) - ) { - throw new MongoParseError( - 'The `tlsInsecure` option cannot be used with `tlsAllowInvalidCertificates` or `tlsAllowInvalidHostnames`.' - ); - } - - const tlsValue = assertTlsOptionsAreEqual('tls', queryString, queryStringKeys); - const sslValue = assertTlsOptionsAreEqual('ssl', queryString, queryStringKeys); - - if (tlsValue != null && sslValue != null) { - if (tlsValue !== sslValue) { - throw new MongoParseError('All values of `tls` and `ssl` must be the same.'); - } - } -} - -/** - * Checks a query string to ensure all tls/ssl options are the same. - * - * @param {string} key The key (tls or ssl) to check - * @param {string} queryString The query string to check - * @throws {MongoParseError} - * @return The value of the tls/ssl option - */ -function assertTlsOptionsAreEqual(optionName, queryString, queryStringKeys) { - const queryStringHasTLSOption = queryStringKeys.indexOf(optionName) !== -1; - - let optionValue; - if (Array.isArray(queryString[optionName])) { - optionValue = queryString[optionName][0]; - } else { - optionValue = queryString[optionName]; - } - - if (queryStringHasTLSOption) { - if (Array.isArray(queryString[optionName])) { - const firstValue = queryString[optionName][0]; - queryString[optionName].forEach(tlsValue => { - if (tlsValue !== firstValue) { - throw new MongoParseError('All values of ${optionName} must be the same.'); - } - }); - } - } - - return optionValue; -} - -const PROTOCOL_MONGODB = 'mongodb'; -const PROTOCOL_MONGODB_SRV = 'mongodb+srv'; -const SUPPORTED_PROTOCOLS = [PROTOCOL_MONGODB, PROTOCOL_MONGODB_SRV]; - -/** - * Parses a MongoDB connection string - * - * @param {*} uri the MongoDB connection string to parse - * @param {object} [options] Optional settings. - * @param {boolean} [options.caseTranslate] Whether the parser should translate options back into camelCase after normalization - * @param {parseCallback} callback - */ -function parseConnectionString(uri, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = Object.assign({}, { caseTranslate: true }, options); - - // Check for bad uris before we parse - try { - URL.parse(uri); - } catch (e) { - return callback(new MongoParseError('URI malformed, cannot be parsed')); - } - - const cap = uri.match(HOSTS_RX); - if (!cap) { - return callback(new MongoParseError('Invalid connection string')); - } - - const protocol = cap[1]; - if (SUPPORTED_PROTOCOLS.indexOf(protocol) === -1) { - return callback(new MongoParseError('Invalid protocol provided')); - } - - if (protocol === PROTOCOL_MONGODB_SRV) { - return parseSrvConnectionString(uri, options, callback); - } - - const dbAndQuery = cap[4].split('?'); - const db = dbAndQuery.length > 0 ? dbAndQuery[0] : null; - const query = dbAndQuery.length > 1 ? dbAndQuery[1] : null; - - let parsedOptions; - try { - parsedOptions = parseQueryString(query, options); - } catch (parseError) { - return callback(parseError); - } - - parsedOptions = Object.assign({}, parsedOptions, options); - const auth = { username: null, password: null, db: db && db !== '' ? qs.unescape(db) : null }; - if (parsedOptions.auth) { - // maintain support for legacy options passed into `MongoClient` - if (parsedOptions.auth.username) auth.username = parsedOptions.auth.username; - if (parsedOptions.auth.user) auth.username = parsedOptions.auth.user; - if (parsedOptions.auth.password) auth.password = parsedOptions.auth.password; - } else { - if (parsedOptions.username) auth.username = parsedOptions.username; - if (parsedOptions.user) auth.username = parsedOptions.user; - if (parsedOptions.password) auth.password = parsedOptions.password; - } - - if (cap[4].split('?')[0].indexOf('@') !== -1) { - return callback(new MongoParseError('Unescaped slash in userinfo section')); - } - - const authorityParts = cap[3].split('@'); - if (authorityParts.length > 2) { - return callback(new MongoParseError('Unescaped at-sign in authority section')); - } - - if (authorityParts.length > 1) { - const authParts = authorityParts.shift().split(':'); - if (authParts.length > 2) { - return callback(new MongoParseError('Unescaped colon in authority section')); - } - - if (!auth.username) auth.username = qs.unescape(authParts[0]); - if (!auth.password) auth.password = authParts[1] ? qs.unescape(authParts[1]) : null; - } - - let hostParsingError = null; - const hosts = authorityParts - .shift() - .split(',') - .map(host => { - let parsedHost = URL.parse(`mongodb://${host}`); - if (parsedHost.path === '/:') { - hostParsingError = new MongoParseError('Double colon in host identifier'); - return null; - } - - // heuristically determine if we're working with a domain socket - if (host.match(/\.sock/)) { - parsedHost.hostname = qs.unescape(host); - parsedHost.port = null; - } - - if (Number.isNaN(parsedHost.port)) { - hostParsingError = new MongoParseError('Invalid port (non-numeric string)'); - return; - } - - const result = { - host: parsedHost.hostname, - port: parsedHost.port ? parseInt(parsedHost.port) : 27017 - }; - - if (result.port === 0) { - hostParsingError = new MongoParseError('Invalid port (zero) with hostname'); - return; - } - - if (result.port > 65535) { - hostParsingError = new MongoParseError('Invalid port (larger than 65535) with hostname'); - return; - } - - if (result.port < 0) { - hostParsingError = new MongoParseError('Invalid port (negative number)'); - return; - } - - return result; - }) - .filter(host => !!host); - - if (hostParsingError) { - return callback(hostParsingError); - } - - if (hosts.length === 0 || hosts[0].host === '' || hosts[0].host === null) { - return callback(new MongoParseError('No hostname or hostnames provided in connection string')); - } - - const result = { - hosts: hosts, - auth: auth.db || auth.username ? auth : null, - options: Object.keys(parsedOptions).length ? parsedOptions : null - }; - - if (result.auth && result.auth.db) { - result.defaultDatabase = result.auth.db; - } else { - result.defaultDatabase = 'test'; - } - - try { - applyAuthExpectations(result); - } catch (authError) { - return callback(authError); - } - - callback(null, result); -} - -module.exports = parseConnectionString; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/utils.js b/scripts/2.5/node_modules/mongodb/lib/core/utils.js deleted file mode 100644 index 7581bf25..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/core/utils.js +++ /dev/null @@ -1,177 +0,0 @@ -'use strict'; - -const crypto = require('crypto'); -const requireOptional = require('require_optional'); - -/** - * Generate a UUIDv4 - */ -const uuidV4 = () => { - const result = crypto.randomBytes(16); - result[6] = (result[6] & 0x0f) | 0x40; - result[8] = (result[8] & 0x3f) | 0x80; - return result; -}; - -/** - * Returns the duration calculated from two high resolution timers in milliseconds - * - * @param {Object} started A high resolution timestamp created from `process.hrtime()` - * @returns {Number} The duration in milliseconds - */ -const calculateDurationInMs = started => { - const hrtime = process.hrtime(started); - return (hrtime[0] * 1e9 + hrtime[1]) / 1e6; -}; - -/** - * Relays events for a given listener and emitter - * - * @param {EventEmitter} listener the EventEmitter to listen to the events from - * @param {EventEmitter} emitter the EventEmitter to relay the events to - */ -function relayEvents(listener, emitter, events) { - events.forEach(eventName => listener.on(eventName, event => emitter.emit(eventName, event))); -} - -function retrieveKerberos() { - let kerberos; - - try { - kerberos = requireOptional('kerberos'); - } catch (err) { - if (err.code === 'MODULE_NOT_FOUND') { - throw new Error('The `kerberos` module was not found. Please install it and try again.'); - } - - throw err; - } - - return kerberos; -} - -// Throw an error if an attempt to use EJSON is made when it is not installed -const noEJSONError = function() { - throw new Error('The `mongodb-extjson` module was not found. Please install it and try again.'); -}; - -// Facilitate loading EJSON optionally -function retrieveEJSON() { - let EJSON = null; - try { - EJSON = requireOptional('mongodb-extjson'); - } catch (error) {} // eslint-disable-line - if (!EJSON) { - EJSON = { - parse: noEJSONError, - deserialize: noEJSONError, - serialize: noEJSONError, - stringify: noEJSONError, - setBSONModule: noEJSONError, - BSON: noEJSONError - }; - } - - return EJSON; -} - -/** - * A helper function for determining `maxWireVersion` between legacy and new topology - * instances - * - * @private - * @param {(Topology|Server)} topologyOrServer - */ -function maxWireVersion(topologyOrServer) { - if (topologyOrServer.ismaster) { - return topologyOrServer.ismaster.maxWireVersion; - } - - if (typeof topologyOrServer.lastIsMaster === 'function') { - const lastIsMaster = topologyOrServer.lastIsMaster(); - if (lastIsMaster) { - return lastIsMaster.maxWireVersion; - } - } - - if (topologyOrServer.description) { - return topologyOrServer.description.maxWireVersion; - } - - return null; -} - -/* - * Checks that collation is supported by server. - * - * @param {Server} [server] to check against - * @param {object} [cmd] object where collation may be specified - * @param {function} [callback] callback function - * @return true if server does not support collation - */ -function collationNotSupported(server, cmd) { - return cmd && cmd.collation && maxWireVersion(server) < 5; -} - -/** - * Checks if a given value is a Promise - * - * @param {*} maybePromise - * @return true if the provided value is a Promise - */ -function isPromiseLike(maybePromise) { - return maybePromise && typeof maybePromise.then === 'function'; -} - -/** - * Applies the function `eachFn` to each item in `arr`, in parallel. - * - * @param {array} arr an array of items to asynchronusly iterate over - * @param {function} eachFn A function to call on each item of the array. The callback signature is `(item, callback)`, where the callback indicates iteration is complete. - * @param {function} callback The callback called after every item has been iterated - */ -function eachAsync(arr, eachFn, callback) { - if (arr.length === 0) { - callback(null); - return; - } - - const length = arr.length; - let completed = 0; - function eachCallback(err) { - if (err) { - callback(err, null); - return; - } - - if (++completed === length) { - callback(null); - } - } - - for (let idx = 0; idx < length; ++idx) { - try { - eachFn(arr[idx], eachCallback); - } catch (err) { - callback(err); - return; - } - } -} - -function isUnifiedTopology(topology) { - return topology.description != null; -} - -module.exports = { - uuidV4, - calculateDurationInMs, - relayEvents, - collationNotSupported, - retrieveEJSON, - retrieveKerberos, - maxWireVersion, - isPromiseLike, - eachAsync, - isUnifiedTopology -}; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/wireprotocol/command.js b/scripts/2.5/node_modules/mongodb/lib/core/wireprotocol/command.js deleted file mode 100644 index 47107c62..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/core/wireprotocol/command.js +++ /dev/null @@ -1,170 +0,0 @@ -'use strict'; - -const Query = require('../connection/commands').Query; -const Msg = require('../connection/msg').Msg; -const MongoError = require('../error').MongoError; -const getReadPreference = require('./shared').getReadPreference; -const isSharded = require('./shared').isSharded; -const databaseNamespace = require('./shared').databaseNamespace; -const isTransactionCommand = require('../transactions').isTransactionCommand; -const applySession = require('../sessions').applySession; - -function isClientEncryptionEnabled(server) { - return server.autoEncrypter; -} - -function command(server, ns, cmd, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - if (cmd == null) { - return callback(new MongoError(`command ${JSON.stringify(cmd)} does not return a cursor`)); - } - - if (!isClientEncryptionEnabled(server)) { - _command(server, ns, cmd, options, callback); - return; - } - - _cryptCommand(server, ns, cmd, options, callback); -} - -function _command(server, ns, cmd, options, callback) { - const bson = server.s.bson; - const pool = server.s.pool; - const readPreference = getReadPreference(cmd, options); - const shouldUseOpMsg = supportsOpMsg(server); - const session = options.session; - - let clusterTime = server.clusterTime; - let finalCmd = Object.assign({}, cmd); - if (hasSessionSupport(server) && session) { - if ( - session.clusterTime && - session.clusterTime.clusterTime.greaterThan(clusterTime.clusterTime) - ) { - clusterTime = session.clusterTime; - } - - const err = applySession(session, finalCmd, options); - if (err) { - return callback(err); - } - } - - // if we have a known cluster time, gossip it - if (clusterTime) { - finalCmd.$clusterTime = clusterTime; - } - - if ( - isSharded(server) && - !shouldUseOpMsg && - readPreference && - readPreference.preference !== 'primary' - ) { - finalCmd = { - $query: finalCmd, - $readPreference: readPreference.toJSON() - }; - } - - const commandOptions = Object.assign( - { - command: true, - numberToSkip: 0, - numberToReturn: -1, - checkKeys: false - }, - options - ); - - // This value is not overridable - commandOptions.slaveOk = readPreference.slaveOk(); - - const cmdNs = `${databaseNamespace(ns)}.$cmd`; - const message = shouldUseOpMsg - ? new Msg(bson, cmdNs, finalCmd, commandOptions) - : new Query(bson, cmdNs, finalCmd, commandOptions); - - const inTransaction = session && (session.inTransaction() || isTransactionCommand(finalCmd)); - const commandResponseHandler = inTransaction - ? function(err) { - if ( - !cmd.commitTransaction && - err && - err instanceof MongoError && - err.hasErrorLabel('TransientTransactionError') - ) { - session.transaction.unpinServer(); - } - - return callback.apply(null, arguments); - } - : callback; - - try { - pool.write(message, commandOptions, commandResponseHandler); - } catch (err) { - commandResponseHandler(err); - } -} - -function hasSessionSupport(topology) { - if (topology == null) return false; - if (topology.description) { - return topology.description.maxWireVersion >= 6; - } - - return topology.ismaster == null ? false : topology.ismaster.maxWireVersion >= 6; -} - -function supportsOpMsg(topologyOrServer) { - const description = topologyOrServer.ismaster - ? topologyOrServer.ismaster - : topologyOrServer.description; - - if (description == null) { - return false; - } - - return description.maxWireVersion >= 6 && description.__nodejs_mock_server__ == null; -} - -function _cryptCommand(server, ns, cmd, options, callback) { - const shouldBypassAutoEncryption = !!server.s.options.bypassAutoEncryption; - const autoEncrypter = server.autoEncrypter; - function commandResponseHandler(err, response) { - if (err || response == null) { - callback(err, response); - return; - } - - autoEncrypter.decrypt(response.result, (err, decrypted) => { - if (err) { - callback(err, null); - return; - } - - response.result = decrypted; - response.message.documents = [decrypted]; - callback(null, response); - }); - } - - if (shouldBypassAutoEncryption) { - _command(server, ns, cmd, options, commandResponseHandler); - return; - } - - autoEncrypter.encrypt(ns, cmd, (err, encrypted) => { - if (err) { - callback(err, null); - return; - } - - _command(server, ns, encrypted, options, commandResponseHandler); - }); -} - -module.exports = command; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/wireprotocol/compression.js b/scripts/2.5/node_modules/mongodb/lib/core/wireprotocol/compression.js deleted file mode 100644 index 4b908e63..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/core/wireprotocol/compression.js +++ /dev/null @@ -1,73 +0,0 @@ -'use strict'; - -var Snappy = require('../connection/utils').retrieveSnappy(), - zlib = require('zlib'); - -var compressorIDs = { - snappy: 1, - zlib: 2 -}; - -var uncompressibleCommands = [ - 'ismaster', - 'saslStart', - 'saslContinue', - 'getnonce', - 'authenticate', - 'createUser', - 'updateUser', - 'copydbSaslStart', - 'copydbgetnonce', - 'copydb' -]; - -// Facilitate compressing a message using an agreed compressor -var compress = function(self, dataToBeCompressed, callback) { - switch (self.options.agreedCompressor) { - case 'snappy': - Snappy.compress(dataToBeCompressed, callback); - break; - case 'zlib': - // Determine zlibCompressionLevel - var zlibOptions = {}; - if (self.options.zlibCompressionLevel) { - zlibOptions.level = self.options.zlibCompressionLevel; - } - zlib.deflate(dataToBeCompressed, zlibOptions, callback); - break; - default: - throw new Error( - 'Attempt to compress message using unknown compressor "' + - self.options.agreedCompressor + - '".' - ); - } -}; - -// Decompress a message using the given compressor -var decompress = function(compressorID, compressedData, callback) { - if (compressorID < 0 || compressorID > compressorIDs.length) { - throw new Error( - 'Server sent message compressed using an unsupported compressor. (Received compressor ID ' + - compressorID + - ')' - ); - } - switch (compressorID) { - case compressorIDs.snappy: - Snappy.uncompress(compressedData, callback); - break; - case compressorIDs.zlib: - zlib.inflate(compressedData, callback); - break; - default: - callback(null, compressedData); - } -}; - -module.exports = { - compressorIDs: compressorIDs, - uncompressibleCommands: uncompressibleCommands, - compress: compress, - decompress: decompress -}; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/wireprotocol/constants.js b/scripts/2.5/node_modules/mongodb/lib/core/wireprotocol/constants.js deleted file mode 100644 index df2293b5..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/core/wireprotocol/constants.js +++ /dev/null @@ -1,13 +0,0 @@ -'use strict'; - -const MIN_SUPPORTED_SERVER_VERSION = '2.6'; -const MAX_SUPPORTED_SERVER_VERSION = '4.2'; -const MIN_SUPPORTED_WIRE_VERSION = 2; -const MAX_SUPPORTED_WIRE_VERSION = 8; - -module.exports = { - MIN_SUPPORTED_SERVER_VERSION, - MAX_SUPPORTED_SERVER_VERSION, - MIN_SUPPORTED_WIRE_VERSION, - MAX_SUPPORTED_WIRE_VERSION -}; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/wireprotocol/get_more.js b/scripts/2.5/node_modules/mongodb/lib/core/wireprotocol/get_more.js deleted file mode 100644 index b2db3202..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/core/wireprotocol/get_more.js +++ /dev/null @@ -1,90 +0,0 @@ -'use strict'; - -const GetMore = require('../connection/commands').GetMore; -const retrieveBSON = require('../connection/utils').retrieveBSON; -const MongoError = require('../error').MongoError; -const MongoNetworkError = require('../error').MongoNetworkError; -const BSON = retrieveBSON(); -const Long = BSON.Long; -const collectionNamespace = require('./shared').collectionNamespace; -const maxWireVersion = require('../utils').maxWireVersion; -const applyCommonQueryOptions = require('./shared').applyCommonQueryOptions; -const command = require('./command'); - -function getMore(server, ns, cursorState, batchSize, options, callback) { - options = options || {}; - - const wireVersion = maxWireVersion(server); - function queryCallback(err, result) { - if (err) return callback(err); - const response = result.message; - - // If we have a timed out query or a cursor that was killed - if (response.cursorNotFound) { - return callback(new MongoNetworkError('cursor killed or timed out'), null); - } - - if (wireVersion < 4) { - const cursorId = - typeof response.cursorId === 'number' - ? Long.fromNumber(response.cursorId) - : response.cursorId; - - cursorState.documents = response.documents; - cursorState.cursorId = cursorId; - - callback(null, null, response.connection); - return; - } - - // We have an error detected - if (response.documents[0].ok === 0) { - return callback(new MongoError(response.documents[0])); - } - - // Ensure we have a Long valid cursor id - const cursorId = - typeof response.documents[0].cursor.id === 'number' - ? Long.fromNumber(response.documents[0].cursor.id) - : response.documents[0].cursor.id; - - cursorState.documents = response.documents[0].cursor.nextBatch; - cursorState.cursorId = cursorId; - - callback(null, response.documents[0], response.connection); - } - - if (wireVersion < 4) { - const bson = server.s.bson; - const getMoreOp = new GetMore(bson, ns, cursorState.cursorId, { numberToReturn: batchSize }); - const queryOptions = applyCommonQueryOptions({}, cursorState); - server.s.pool.write(getMoreOp, queryOptions, queryCallback); - return; - } - - const getMoreCmd = { - getMore: cursorState.cursorId, - collection: collectionNamespace(ns), - batchSize: Math.abs(batchSize) - }; - - if (cursorState.cmd.tailable && typeof cursorState.cmd.maxAwaitTimeMS === 'number') { - getMoreCmd.maxTimeMS = cursorState.cmd.maxAwaitTimeMS; - } - - const commandOptions = Object.assign( - { - returnFieldSelector: null, - documentsReturnedIn: 'nextBatch' - }, - options - ); - - if (cursorState.session) { - commandOptions.session = cursorState.session; - } - - command(server, ns, getMoreCmd, commandOptions, queryCallback); -} - -module.exports = getMore; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/wireprotocol/index.js b/scripts/2.5/node_modules/mongodb/lib/core/wireprotocol/index.js deleted file mode 100644 index b6ffda7c..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/core/wireprotocol/index.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; -const writeCommand = require('./write_command'); - -module.exports = { - insert: function insert(server, ns, ops, options, callback) { - writeCommand(server, 'insert', 'documents', ns, ops, options, callback); - }, - update: function update(server, ns, ops, options, callback) { - writeCommand(server, 'update', 'updates', ns, ops, options, callback); - }, - remove: function remove(server, ns, ops, options, callback) { - writeCommand(server, 'delete', 'deletes', ns, ops, options, callback); - }, - killCursors: require('./kill_cursors'), - getMore: require('./get_more'), - query: require('./query'), - command: require('./command') -}; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/wireprotocol/kill_cursors.js b/scripts/2.5/node_modules/mongodb/lib/core/wireprotocol/kill_cursors.js deleted file mode 100644 index bb134773..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/core/wireprotocol/kill_cursors.js +++ /dev/null @@ -1,70 +0,0 @@ -'use strict'; - -const KillCursor = require('../connection/commands').KillCursor; -const MongoError = require('../error').MongoError; -const MongoNetworkError = require('../error').MongoNetworkError; -const collectionNamespace = require('./shared').collectionNamespace; -const maxWireVersion = require('../utils').maxWireVersion; -const command = require('./command'); - -function killCursors(server, ns, cursorState, callback) { - callback = typeof callback === 'function' ? callback : () => {}; - const cursorId = cursorState.cursorId; - - if (maxWireVersion(server) < 4) { - const bson = server.s.bson; - const pool = server.s.pool; - const killCursor = new KillCursor(bson, ns, [cursorId]); - const options = { - immediateRelease: true, - noResponse: true - }; - - if (typeof cursorState.session === 'object') { - options.session = cursorState.session; - } - - if (pool && pool.isConnected()) { - try { - pool.write(killCursor, options, callback); - } catch (err) { - if (typeof callback === 'function') { - callback(err, null); - } else { - console.warn(err); - } - } - } - - return; - } - - const killCursorCmd = { - killCursors: collectionNamespace(ns), - cursors: [cursorId] - }; - - const options = {}; - if (typeof cursorState.session === 'object') options.session = cursorState.session; - - command(server, ns, killCursorCmd, options, (err, result) => { - if (err) { - return callback(err); - } - - const response = result.message; - if (response.cursorNotFound) { - return callback(new MongoNetworkError('cursor killed or timed out'), null); - } - - if (!Array.isArray(response.documents) || response.documents.length === 0) { - return callback( - new MongoError(`invalid killCursors result returned for cursor id ${cursorId}`) - ); - } - - callback(null, response.documents[0]); - }); -} - -module.exports = killCursors; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/wireprotocol/query.js b/scripts/2.5/node_modules/mongodb/lib/core/wireprotocol/query.js deleted file mode 100644 index c501b506..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/core/wireprotocol/query.js +++ /dev/null @@ -1,231 +0,0 @@ -'use strict'; - -const Query = require('../connection/commands').Query; -const MongoError = require('../error').MongoError; -const getReadPreference = require('./shared').getReadPreference; -const collectionNamespace = require('./shared').collectionNamespace; -const isSharded = require('./shared').isSharded; -const maxWireVersion = require('../utils').maxWireVersion; -const applyCommonQueryOptions = require('./shared').applyCommonQueryOptions; -const command = require('./command'); - -function query(server, ns, cmd, cursorState, options, callback) { - options = options || {}; - if (cursorState.cursorId != null) { - return callback(); - } - - if (cmd == null) { - return callback(new MongoError(`command ${JSON.stringify(cmd)} does not return a cursor`)); - } - - if (maxWireVersion(server) < 4) { - const query = prepareLegacyFindQuery(server, ns, cmd, cursorState, options); - const queryOptions = applyCommonQueryOptions({}, cursorState); - if (typeof query.documentsReturnedIn === 'string') { - queryOptions.documentsReturnedIn = query.documentsReturnedIn; - } - - server.s.pool.write(query, queryOptions, callback); - return; - } - - const readPreference = getReadPreference(cmd, options); - const findCmd = prepareFindCommand(server, ns, cmd, cursorState, options); - - // NOTE: This actually modifies the passed in cmd, and our code _depends_ on this - // side-effect. Change this ASAP - cmd.virtual = false; - - const commandOptions = Object.assign( - { - documentsReturnedIn: 'firstBatch', - numberToReturn: 1, - slaveOk: readPreference.slaveOk() - }, - options - ); - - if (cmd.readPreference) { - commandOptions.readPreference = readPreference; - } - - if (cursorState.session) { - commandOptions.session = cursorState.session; - } - - command(server, ns, findCmd, commandOptions, callback); -} - -function prepareFindCommand(server, ns, cmd, cursorState) { - cursorState.batchSize = cmd.batchSize || cursorState.batchSize; - let findCmd = { - find: collectionNamespace(ns) - }; - - if (cmd.query) { - if (cmd.query['$query']) { - findCmd.filter = cmd.query['$query']; - } else { - findCmd.filter = cmd.query; - } - } - - let sortValue = cmd.sort; - if (Array.isArray(sortValue)) { - const sortObject = {}; - - if (sortValue.length > 0 && !Array.isArray(sortValue[0])) { - let sortDirection = sortValue[1]; - if (sortDirection === 'asc') { - sortDirection = 1; - } else if (sortDirection === 'desc') { - sortDirection = -1; - } - - sortObject[sortValue[0]] = sortDirection; - } else { - for (let i = 0; i < sortValue.length; i++) { - let sortDirection = sortValue[i][1]; - if (sortDirection === 'asc') { - sortDirection = 1; - } else if (sortDirection === 'desc') { - sortDirection = -1; - } - - sortObject[sortValue[i][0]] = sortDirection; - } - } - - sortValue = sortObject; - } - - if (cmd.sort) findCmd.sort = sortValue; - if (cmd.fields) findCmd.projection = cmd.fields; - if (cmd.hint) findCmd.hint = cmd.hint; - if (cmd.skip) findCmd.skip = cmd.skip; - if (cmd.limit) findCmd.limit = cmd.limit; - if (cmd.limit < 0) { - findCmd.limit = Math.abs(cmd.limit); - findCmd.singleBatch = true; - } - - if (typeof cmd.batchSize === 'number') { - if (cmd.batchSize < 0) { - if (cmd.limit !== 0 && Math.abs(cmd.batchSize) < Math.abs(cmd.limit)) { - findCmd.limit = Math.abs(cmd.batchSize); - } - - findCmd.singleBatch = true; - } - - findCmd.batchSize = Math.abs(cmd.batchSize); - } - - if (cmd.comment) findCmd.comment = cmd.comment; - if (cmd.maxScan) findCmd.maxScan = cmd.maxScan; - if (cmd.maxTimeMS) findCmd.maxTimeMS = cmd.maxTimeMS; - if (cmd.min) findCmd.min = cmd.min; - if (cmd.max) findCmd.max = cmd.max; - findCmd.returnKey = cmd.returnKey ? cmd.returnKey : false; - findCmd.showRecordId = cmd.showDiskLoc ? cmd.showDiskLoc : false; - if (cmd.snapshot) findCmd.snapshot = cmd.snapshot; - if (cmd.tailable) findCmd.tailable = cmd.tailable; - if (cmd.oplogReplay) findCmd.oplogReplay = cmd.oplogReplay; - if (cmd.noCursorTimeout) findCmd.noCursorTimeout = cmd.noCursorTimeout; - if (cmd.awaitData) findCmd.awaitData = cmd.awaitData; - if (cmd.awaitdata) findCmd.awaitData = cmd.awaitdata; - if (cmd.partial) findCmd.partial = cmd.partial; - if (cmd.collation) findCmd.collation = cmd.collation; - if (cmd.readConcern) findCmd.readConcern = cmd.readConcern; - - // If we have explain, we need to rewrite the find command - // to wrap it in the explain command - if (cmd.explain) { - findCmd = { - explain: findCmd - }; - } - - return findCmd; -} - -function prepareLegacyFindQuery(server, ns, cmd, cursorState, options) { - options = options || {}; - const bson = server.s.bson; - const readPreference = getReadPreference(cmd, options); - cursorState.batchSize = cmd.batchSize || cursorState.batchSize; - - let numberToReturn = 0; - if ( - cursorState.limit < 0 || - (cursorState.limit !== 0 && cursorState.limit < cursorState.batchSize) || - (cursorState.limit > 0 && cursorState.batchSize === 0) - ) { - numberToReturn = cursorState.limit; - } else { - numberToReturn = cursorState.batchSize; - } - - const numberToSkip = cursorState.skip || 0; - - const findCmd = {}; - if (isSharded(server) && readPreference) { - findCmd['$readPreference'] = readPreference.toJSON(); - } - - if (cmd.sort) findCmd['$orderby'] = cmd.sort; - if (cmd.hint) findCmd['$hint'] = cmd.hint; - if (cmd.snapshot) findCmd['$snapshot'] = cmd.snapshot; - if (typeof cmd.returnKey !== 'undefined') findCmd['$returnKey'] = cmd.returnKey; - if (cmd.maxScan) findCmd['$maxScan'] = cmd.maxScan; - if (cmd.min) findCmd['$min'] = cmd.min; - if (cmd.max) findCmd['$max'] = cmd.max; - if (typeof cmd.showDiskLoc !== 'undefined') findCmd['$showDiskLoc'] = cmd.showDiskLoc; - if (cmd.comment) findCmd['$comment'] = cmd.comment; - if (cmd.maxTimeMS) findCmd['$maxTimeMS'] = cmd.maxTimeMS; - if (cmd.explain) { - // nToReturn must be 0 (match all) or negative (match N and close cursor) - // nToReturn > 0 will give explain results equivalent to limit(0) - numberToReturn = -Math.abs(cmd.limit || 0); - findCmd['$explain'] = true; - } - - findCmd['$query'] = cmd.query; - if (cmd.readConcern && cmd.readConcern.level !== 'local') { - throw new MongoError( - `server find command does not support a readConcern level of ${cmd.readConcern.level}` - ); - } - - if (cmd.readConcern) { - cmd = Object.assign({}, cmd); - delete cmd['readConcern']; - } - - const serializeFunctions = - typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; - const ignoreUndefined = - typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : false; - - const query = new Query(bson, ns, findCmd, { - numberToSkip: numberToSkip, - numberToReturn: numberToReturn, - pre32Limit: typeof cmd.limit !== 'undefined' ? cmd.limit : undefined, - checkKeys: false, - returnFieldSelector: cmd.fields, - serializeFunctions: serializeFunctions, - ignoreUndefined: ignoreUndefined - }); - - if (typeof cmd.tailable === 'boolean') query.tailable = cmd.tailable; - if (typeof cmd.oplogReplay === 'boolean') query.oplogReplay = cmd.oplogReplay; - if (typeof cmd.noCursorTimeout === 'boolean') query.noCursorTimeout = cmd.noCursorTimeout; - if (typeof cmd.awaitData === 'boolean') query.awaitData = cmd.awaitData; - if (typeof cmd.partial === 'boolean') query.partial = cmd.partial; - - query.slaveOk = readPreference.slaveOk(); - return query; -} - -module.exports = query; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/wireprotocol/shared.js b/scripts/2.5/node_modules/mongodb/lib/core/wireprotocol/shared.js deleted file mode 100644 index 2574aade..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/core/wireprotocol/shared.js +++ /dev/null @@ -1,115 +0,0 @@ -'use strict'; - -const ReadPreference = require('../topologies/read_preference'); -const MongoError = require('../error').MongoError; -const ServerType = require('../sdam/server_description').ServerType; -const TopologyDescription = require('../sdam/topology_description').TopologyDescription; - -const MESSAGE_HEADER_SIZE = 16; -const COMPRESSION_DETAILS_SIZE = 9; // originalOpcode + uncompressedSize, compressorID - -// OPCODE Numbers -// Defined at https://docs.mongodb.com/manual/reference/mongodb-wire-protocol/#request-opcodes -var opcodes = { - OP_REPLY: 1, - OP_UPDATE: 2001, - OP_INSERT: 2002, - OP_QUERY: 2004, - OP_GETMORE: 2005, - OP_DELETE: 2006, - OP_KILL_CURSORS: 2007, - OP_COMPRESSED: 2012, - OP_MSG: 2013 -}; - -var getReadPreference = function(cmd, options) { - // Default to command version of the readPreference - var readPreference = cmd.readPreference || new ReadPreference('primary'); - // If we have an option readPreference override the command one - if (options.readPreference) { - readPreference = options.readPreference; - } - - if (typeof readPreference === 'string') { - readPreference = new ReadPreference(readPreference); - } - - if (!(readPreference instanceof ReadPreference)) { - throw new MongoError('read preference must be a ReadPreference instance'); - } - - return readPreference; -}; - -// Parses the header of a wire protocol message -var parseHeader = function(message) { - return { - length: message.readInt32LE(0), - requestId: message.readInt32LE(4), - responseTo: message.readInt32LE(8), - opCode: message.readInt32LE(12) - }; -}; - -function applyCommonQueryOptions(queryOptions, options) { - Object.assign(queryOptions, { - raw: typeof options.raw === 'boolean' ? options.raw : false, - promoteLongs: typeof options.promoteLongs === 'boolean' ? options.promoteLongs : true, - promoteValues: typeof options.promoteValues === 'boolean' ? options.promoteValues : true, - promoteBuffers: typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : false, - monitoring: typeof options.monitoring === 'boolean' ? options.monitoring : false, - fullResult: typeof options.fullResult === 'boolean' ? options.fullResult : false - }); - - if (typeof options.socketTimeout === 'number') { - queryOptions.socketTimeout = options.socketTimeout; - } - - if (options.session) { - queryOptions.session = options.session; - } - - if (typeof options.documentsReturnedIn === 'string') { - queryOptions.documentsReturnedIn = options.documentsReturnedIn; - } - - return queryOptions; -} - -function isSharded(topologyOrServer) { - if (topologyOrServer.type === 'mongos') return true; - if (topologyOrServer.description && topologyOrServer.description.type === ServerType.Mongos) { - return true; - } - - // NOTE: This is incredibly inefficient, and should be removed once command construction - // happens based on `Server` not `Topology`. - if (topologyOrServer.description && topologyOrServer.description instanceof TopologyDescription) { - const servers = Array.from(topologyOrServer.description.servers.values()); - return servers.some(server => server.type === ServerType.Mongos); - } - - return false; -} - -function databaseNamespace(ns) { - return ns.split('.')[0]; -} -function collectionNamespace(ns) { - return ns - .split('.') - .slice(1) - .join('.'); -} - -module.exports = { - getReadPreference, - MESSAGE_HEADER_SIZE, - COMPRESSION_DETAILS_SIZE, - opcodes, - parseHeader, - applyCommonQueryOptions, - isSharded, - databaseNamespace, - collectionNamespace -}; diff --git a/scripts/2.5/node_modules/mongodb/lib/core/wireprotocol/write_command.js b/scripts/2.5/node_modules/mongodb/lib/core/wireprotocol/write_command.js deleted file mode 100644 index e334d518..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/core/wireprotocol/write_command.js +++ /dev/null @@ -1,50 +0,0 @@ -'use strict'; - -const MongoError = require('../error').MongoError; -const collectionNamespace = require('./shared').collectionNamespace; -const command = require('./command'); - -function writeCommand(server, type, opsField, ns, ops, options, callback) { - if (ops.length === 0) throw new MongoError(`${type} must contain at least one document`); - if (typeof options === 'function') { - callback = options; - options = {}; - } - - options = options || {}; - const ordered = typeof options.ordered === 'boolean' ? options.ordered : true; - const writeConcern = options.writeConcern; - - const writeCommand = {}; - writeCommand[type] = collectionNamespace(ns); - writeCommand[opsField] = ops; - writeCommand.ordered = ordered; - - if (writeConcern && Object.keys(writeConcern).length > 0) { - writeCommand.writeConcern = writeConcern; - } - - if (options.collation) { - for (let i = 0; i < writeCommand[opsField].length; i++) { - if (!writeCommand[opsField][i].collation) { - writeCommand[opsField][i].collation = options.collation; - } - } - } - - if (options.bypassDocumentValidation === true) { - writeCommand.bypassDocumentValidation = options.bypassDocumentValidation; - } - - const commandOptions = Object.assign( - { - checkKeys: type === 'insert', - numberToReturn: 1 - }, - options - ); - - command(server, ns, writeCommand, commandOptions, callback); -} - -module.exports = writeCommand; diff --git a/scripts/2.5/node_modules/mongodb/lib/cursor.js b/scripts/2.5/node_modules/mongodb/lib/cursor.js deleted file mode 100644 index bed709be..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/cursor.js +++ /dev/null @@ -1,1089 +0,0 @@ -'use strict'; - -const Transform = require('stream').Transform; -const PassThrough = require('stream').PassThrough; -const deprecate = require('util').deprecate; -const handleCallback = require('./utils').handleCallback; -const ReadPreference = require('./core').ReadPreference; -const MongoError = require('./core').MongoError; -const CoreCursor = require('./core/cursor').CoreCursor; -const CursorState = require('./core/cursor').CursorState; -const Map = require('./core').BSON.Map; - -const each = require('./operations/cursor_ops').each; - -const CountOperation = require('./operations/count'); -const ExplainOperation = require('./operations/explain'); -const HasNextOperation = require('./operations/has_next'); -const NextOperation = require('./operations/next'); -const ToArrayOperation = require('./operations/to_array'); - -const executeOperation = require('./operations/execute_operation'); - -/** - * @fileOverview The **Cursor** class is an internal class that embodies a cursor on MongoDB - * allowing for iteration over the results returned from the underlying query. It supports - * one by one document iteration, conversion to an array or can be iterated as a Node 4.X - * or higher stream - * - * **CURSORS Cannot directly be instantiated** - * @example - * const MongoClient = require('mongodb').MongoClient; - * const test = require('assert'); - * // Connection url - * const url = 'mongodb://localhost:27017'; - * // Database Name - * const dbName = 'test'; - * // Connect using MongoClient - * MongoClient.connect(url, function(err, client) { - * // Create a collection we want to drop later - * const col = client.db(dbName).collection('createIndexExample1'); - * // Insert a bunch of documents - * col.insert([{a:1, b:1} - * , {a:2, b:2}, {a:3, b:3} - * , {a:4, b:4}], {w:1}, function(err, result) { - * test.equal(null, err); - * // Show that duplicate records got dropped - * col.find({}).toArray(function(err, items) { - * test.equal(null, err); - * test.equal(4, items.length); - * client.close(); - * }); - * }); - * }); - */ - -/** - * Namespace provided by the code module - * @external CoreCursor - * @external Readable - */ - -// Flags allowed for cursor -const flags = ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'exhaust', 'partial']; -const fields = ['numberOfRetries', 'tailableRetryInterval']; - -/** - * Creates a new Cursor instance (INTERNAL TYPE, do not instantiate directly) - * @class Cursor - * @extends external:CoreCursor - * @extends external:Readable - * @property {string} sortValue Cursor query sort setting. - * @property {boolean} timeout Is Cursor able to time out. - * @property {ReadPreference} readPreference Get cursor ReadPreference. - * @fires Cursor#data - * @fires Cursor#end - * @fires Cursor#close - * @fires Cursor#readable - * @return {Cursor} a Cursor instance. - * @example - * Cursor cursor options. - * - * collection.find({}).project({a:1}) // Create a projection of field a - * collection.find({}).skip(1).limit(10) // Skip 1 and limit 10 - * collection.find({}).batchSize(5) // Set batchSize on cursor to 5 - * collection.find({}).filter({a:1}) // Set query on the cursor - * collection.find({}).comment('add a comment') // Add a comment to the query, allowing to correlate queries - * collection.find({}).addCursorFlag('tailable', true) // Set cursor as tailable - * collection.find({}).addCursorFlag('oplogReplay', true) // Set cursor as oplogReplay - * collection.find({}).addCursorFlag('noCursorTimeout', true) // Set cursor as noCursorTimeout - * collection.find({}).addCursorFlag('awaitData', true) // Set cursor as awaitData - * collection.find({}).addCursorFlag('partial', true) // Set cursor as partial - * collection.find({}).addQueryModifier('$orderby', {a:1}) // Set $orderby {a:1} - * collection.find({}).max(10) // Set the cursor max - * collection.find({}).maxTimeMS(1000) // Set the cursor maxTimeMS - * collection.find({}).min(100) // Set the cursor min - * collection.find({}).returnKey(true) // Set the cursor returnKey - * collection.find({}).setReadPreference(ReadPreference.PRIMARY) // Set the cursor readPreference - * collection.find({}).showRecordId(true) // Set the cursor showRecordId - * collection.find({}).sort([['a', 1]]) // Sets the sort order of the cursor query - * collection.find({}).hint('a_1') // Set the cursor hint - * - * All options are chainable, so one can do the following. - * - * collection.find({}).maxTimeMS(1000).maxScan(100).skip(1).toArray(..) - */ -class Cursor extends CoreCursor { - constructor(topology, ns, cmd, options) { - super(topology, ns, cmd, options); - if (this.operation) { - options = this.operation.options; - } - - // Tailable cursor options - const numberOfRetries = options.numberOfRetries || 5; - const tailableRetryInterval = options.tailableRetryInterval || 500; - const currentNumberOfRetries = numberOfRetries; - - // Get the promiseLibrary - const promiseLibrary = options.promiseLibrary || Promise; - - // Internal cursor state - this.s = { - // Tailable cursor options - numberOfRetries: numberOfRetries, - tailableRetryInterval: tailableRetryInterval, - currentNumberOfRetries: currentNumberOfRetries, - // State - state: CursorState.INIT, - // Promise library - promiseLibrary, - // Current doc - currentDoc: null, - // explicitlyIgnoreSession - explicitlyIgnoreSession: !!options.explicitlyIgnoreSession - }; - - // Optional ClientSession - if (!options.explicitlyIgnoreSession && options.session) { - this.cursorState.session = options.session; - } - - // Translate correctly - if (this.options.noCursorTimeout === true) { - this.addCursorFlag('noCursorTimeout', true); - } - - // Get the batchSize - let batchSize = 1000; - if (this.cmd.cursor && this.cmd.cursor.batchSize) { - batchSize = this.cmd.cursor.batchSize; - } else if (options.cursor && options.cursor.batchSize) { - batchSize = options.cursor.batchSize; - } else if (typeof options.batchSize === 'number') { - batchSize = options.batchSize; - } - - // Set the batchSize - this.setCursorBatchSize(batchSize); - } - - get readPreference() { - if (this.operation) { - return this.operation.readPreference; - } - - return this.options.readPreference; - } - - get sortValue() { - return this.cmd.sort; - } - - _initializeCursor(callback) { - if (this.operation && this.operation.session != null) { - this.cursorState.session = this.operation.session; - } else { - // implicitly create a session if one has not been provided - if ( - !this.s.explicitlyIgnoreSession && - !this.cursorState.session && - this.topology.hasSessionSupport() - ) { - this.cursorState.session = this.topology.startSession({ owner: this }); - - if (this.operation) { - this.operation.session = this.cursorState.session; - } - } - } - - super._initializeCursor(callback); - } - - /** - * Check if there is any document still available in the cursor - * @method - * @param {Cursor~resultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ - hasNext(callback) { - const hasNextOperation = new HasNextOperation(this); - - return executeOperation(this.topology, hasNextOperation, callback); - } - - /** - * Get the next available document from the cursor, returns null if no more documents are available. - * @method - * @param {Cursor~resultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ - next(callback) { - const nextOperation = new NextOperation(this); - - return executeOperation(this.topology, nextOperation, callback); - } - - /** - * Set the cursor query - * @method - * @param {object} filter The filter object used for the cursor. - * @return {Cursor} - */ - filter(filter) { - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - this.cmd.query = filter; - return this; - } - - /** - * Set the cursor maxScan - * @method - * @param {object} maxScan Constrains the query to only scan the specified number of documents when fulfilling the query - * @deprecated as of MongoDB 4.0 - * @return {Cursor} - */ - maxScan(maxScan) { - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - this.cmd.maxScan = maxScan; - return this; - } - - /** - * Set the cursor hint - * @method - * @param {object} hint If specified, then the query system will only consider plans using the hinted index. - * @return {Cursor} - */ - hint(hint) { - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - this.cmd.hint = hint; - return this; - } - - /** - * Set the cursor min - * @method - * @param {object} min Specify a $min value to specify the inclusive lower bound for a specific index in order to constrain the results of find(). The $min specifies the lower bound for all keys of a specific index in order. - * @return {Cursor} - */ - min(min) { - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - this.cmd.min = min; - return this; - } - - /** - * Set the cursor max - * @method - * @param {object} max Specify a $max value to specify the exclusive upper bound for a specific index in order to constrain the results of find(). The $max specifies the upper bound for all keys of a specific index in order. - * @return {Cursor} - */ - max(max) { - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - this.cmd.max = max; - return this; - } - - /** - * Set the cursor returnKey. If set to true, modifies the cursor to only return the index field or fields for the results of the query, rather than documents. If set to true and the query does not use an index to perform the read operation, the returned documents will not contain any fields. - * @method - * @param {bool} returnKey the returnKey value. - * @return {Cursor} - */ - returnKey(value) { - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - this.cmd.returnKey = value; - return this; - } - - /** - * Set the cursor showRecordId - * @method - * @param {object} showRecordId The $showDiskLoc option has now been deprecated and replaced with the showRecordId field. $showDiskLoc will still be accepted for OP_QUERY stye find. - * @return {Cursor} - */ - showRecordId(value) { - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - this.cmd.showDiskLoc = value; - return this; - } - - /** - * Set the cursor snapshot - * @method - * @param {object} snapshot The $snapshot operator prevents the cursor from returning a document more than once because an intervening write operation results in a move of the document. - * @deprecated as of MongoDB 4.0 - * @return {Cursor} - */ - snapshot(value) { - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - this.cmd.snapshot = value; - return this; - } - - /** - * Set a node.js specific cursor option - * @method - * @param {string} field The cursor option to set ['numberOfRetries', 'tailableRetryInterval']. - * @param {object} value The field value. - * @throws {MongoError} - * @return {Cursor} - */ - setCursorOption(field, value) { - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - if (fields.indexOf(field) === -1) { - throw MongoError.create({ - message: `option ${field} is not a supported option ${fields}`, - driver: true - }); - } - - this.s[field] = value; - if (field === 'numberOfRetries') this.s.currentNumberOfRetries = value; - return this; - } - - /** - * Add a cursor flag to the cursor - * @method - * @param {string} flag The flag to set, must be one of following ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'partial']. - * @param {boolean} value The flag boolean value. - * @throws {MongoError} - * @return {Cursor} - */ - addCursorFlag(flag, value) { - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - if (flags.indexOf(flag) === -1) { - throw MongoError.create({ - message: `flag ${flag} is not a supported flag ${flags}`, - driver: true - }); - } - - if (typeof value !== 'boolean') { - throw MongoError.create({ message: `flag ${flag} must be a boolean value`, driver: true }); - } - - this.cmd[flag] = value; - return this; - } - - /** - * Add a query modifier to the cursor query - * @method - * @param {string} name The query modifier (must start with $, such as $orderby etc) - * @param {string|boolean|number} value The modifier value. - * @throws {MongoError} - * @return {Cursor} - */ - addQueryModifier(name, value) { - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - if (name[0] !== '$') { - throw MongoError.create({ message: `${name} is not a valid query modifier`, driver: true }); - } - - // Strip of the $ - const field = name.substr(1); - // Set on the command - this.cmd[field] = value; - // Deal with the special case for sort - if (field === 'orderby') this.cmd.sort = this.cmd[field]; - return this; - } - - /** - * Add a comment to the cursor query allowing for tracking the comment in the log. - * @method - * @param {string} value The comment attached to this query. - * @throws {MongoError} - * @return {Cursor} - */ - comment(value) { - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - this.cmd.comment = value; - return this; - } - - /** - * Set a maxAwaitTimeMS on a tailing cursor query to allow to customize the timeout value for the option awaitData (Only supported on MongoDB 3.2 or higher, ignored otherwise) - * @method - * @param {number} value Number of milliseconds to wait before aborting the tailed query. - * @throws {MongoError} - * @return {Cursor} - */ - maxAwaitTimeMS(value) { - if (typeof value !== 'number') { - throw MongoError.create({ message: 'maxAwaitTimeMS must be a number', driver: true }); - } - - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - this.cmd.maxAwaitTimeMS = value; - return this; - } - - /** - * Set a maxTimeMS on the cursor query, allowing for hard timeout limits on queries (Only supported on MongoDB 2.6 or higher) - * @method - * @param {number} value Number of milliseconds to wait before aborting the query. - * @throws {MongoError} - * @return {Cursor} - */ - maxTimeMS(value) { - if (typeof value !== 'number') { - throw MongoError.create({ message: 'maxTimeMS must be a number', driver: true }); - } - - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - this.cmd.maxTimeMS = value; - return this; - } - - /** - * Sets a field projection for the query. - * @method - * @param {object} value The field projection object. - * @throws {MongoError} - * @return {Cursor} - */ - project(value) { - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - this.cmd.fields = value; - return this; - } - - /** - * Sets the sort order of the cursor query. - * @method - * @param {(string|array|object)} keyOrList The key or keys set for the sort. - * @param {number} [direction] The direction of the sorting (1 or -1). - * @throws {MongoError} - * @return {Cursor} - */ - sort(keyOrList, direction) { - if (this.options.tailable) { - throw MongoError.create({ message: "Tailable cursor doesn't support sorting", driver: true }); - } - - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - let order = keyOrList; - - // We have an array of arrays, we need to preserve the order of the sort - // so we will us a Map - if (Array.isArray(order) && Array.isArray(order[0])) { - order = new Map( - order.map(x => { - const value = [x[0], null]; - if (x[1] === 'asc') { - value[1] = 1; - } else if (x[1] === 'desc') { - value[1] = -1; - } else if (x[1] === 1 || x[1] === -1 || x[1].$meta) { - value[1] = x[1]; - } else { - throw new MongoError( - "Illegal sort clause, must be of the form [['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]" - ); - } - - return value; - }) - ); - } - - if (direction != null) { - order = [[keyOrList, direction]]; - } - - this.cmd.sort = order; - return this; - } - - /** - * Set the batch size for the cursor. - * @method - * @param {number} value The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/find/|find command documentation}. - * @throws {MongoError} - * @return {Cursor} - */ - batchSize(value) { - if (this.options.tailable) { - throw MongoError.create({ - message: "Tailable cursor doesn't support batchSize", - driver: true - }); - } - - if (this.s.state === CursorState.CLOSED || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - if (typeof value !== 'number') { - throw MongoError.create({ message: 'batchSize requires an integer', driver: true }); - } - - this.cmd.batchSize = value; - this.setCursorBatchSize(value); - return this; - } - - /** - * Set the collation options for the cursor. - * @method - * @param {object} value The cursor collation options (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @throws {MongoError} - * @return {Cursor} - */ - collation(value) { - this.cmd.collation = value; - return this; - } - - /** - * Set the limit for the cursor. - * @method - * @param {number} value The limit for the cursor query. - * @throws {MongoError} - * @return {Cursor} - */ - limit(value) { - if (this.options.tailable) { - throw MongoError.create({ message: "Tailable cursor doesn't support limit", driver: true }); - } - - if (this.s.state === CursorState.OPEN || this.s.state === CursorState.CLOSED || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - if (typeof value !== 'number') { - throw MongoError.create({ message: 'limit requires an integer', driver: true }); - } - - this.cmd.limit = value; - this.setCursorLimit(value); - return this; - } - - /** - * Set the skip for the cursor. - * @method - * @param {number} value The skip for the cursor query. - * @throws {MongoError} - * @return {Cursor} - */ - skip(value) { - if (this.options.tailable) { - throw MongoError.create({ message: "Tailable cursor doesn't support skip", driver: true }); - } - - if (this.s.state === CursorState.OPEN || this.s.state === CursorState.CLOSED || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - if (typeof value !== 'number') { - throw MongoError.create({ message: 'skip requires an integer', driver: true }); - } - - this.cmd.skip = value; - this.setCursorSkip(value); - return this; - } - - /** - * The callback format for results - * @callback Cursor~resultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {(object|null|boolean)} result The result object if the command was executed successfully. - */ - - /** - * Clone the cursor - * @function external:CoreCursor#clone - * @return {Cursor} - */ - - /** - * Resets the cursor - * @function external:CoreCursor#rewind - * @return {null} - */ - - /** - * Iterates over all the documents for this cursor. As with **{cursor.toArray}**, - * not all of the elements will be iterated if this cursor had been previously accessed. - * In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike - * **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements - * at any given time if batch size is specified. Otherwise, the caller is responsible - * for making sure that the entire result can fit the memory. - * @method - * @deprecated - * @param {Cursor~resultCallback} callback The result callback. - * @throws {MongoError} - * @return {null} - */ - each(callback) { - // Rewind cursor state - this.rewind(); - // Set current cursor to INIT - this.s.state = CursorState.INIT; - // Run the query - each(this, callback); - } - - /** - * The callback format for the forEach iterator method - * @callback Cursor~iteratorCallback - * @param {Object} doc An emitted document for the iterator - */ - - /** - * The callback error format for the forEach iterator method - * @callback Cursor~endCallback - * @param {MongoError} error An error instance representing the error during the execution. - */ - - /** - * Iterates over all the documents for this cursor using the iterator, callback pattern. - * @method - * @param {Cursor~iteratorCallback} iterator The iteration callback. - * @param {Cursor~endCallback} callback The end callback. - * @throws {MongoError} - * @return {Promise} if no callback supplied - */ - forEach(iterator, callback) { - // Rewind cursor state - this.rewind(); - - // Set current cursor to INIT - this.s.state = CursorState.INIT; - - if (typeof callback === 'function') { - each(this, (err, doc) => { - if (err) { - callback(err); - return false; - } - if (doc != null) { - iterator(doc); - return true; - } - if (doc == null && callback) { - const internalCallback = callback; - callback = null; - internalCallback(null); - return false; - } - }); - } else { - return new this.s.promiseLibrary((fulfill, reject) => { - each(this, (err, doc) => { - if (err) { - reject(err); - return false; - } else if (doc == null) { - fulfill(null); - return false; - } else { - iterator(doc); - return true; - } - }); - }); - } - } - - /** - * Set the ReadPreference for the cursor. - * @method - * @param {(string|ReadPreference)} readPreference The new read preference for the cursor. - * @throws {MongoError} - * @return {Cursor} - */ - setReadPreference(readPreference) { - if (this.s.state !== CursorState.INIT) { - throw MongoError.create({ - message: 'cannot change cursor readPreference after cursor has been accessed', - driver: true - }); - } - - if (readPreference instanceof ReadPreference) { - this.options.readPreference = readPreference; - } else if (typeof readPreference === 'string') { - this.options.readPreference = new ReadPreference(readPreference); - } else { - throw new TypeError('Invalid read preference: ' + readPreference); - } - - return this; - } - - /** - * The callback format for results - * @callback Cursor~toArrayResultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {object[]} documents All the documents the satisfy the cursor. - */ - - /** - * Returns an array of documents. The caller is responsible for making sure that there - * is enough memory to store the results. Note that the array only contains partial - * results when this cursor had been previously accessed. In that case, - * cursor.rewind() can be used to reset the cursor. - * @method - * @param {Cursor~toArrayResultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ - toArray(callback) { - if (this.options.tailable) { - throw MongoError.create({ - message: 'Tailable cursor cannot be converted to array', - driver: true - }); - } - - const toArrayOperation = new ToArrayOperation(this); - - return executeOperation(this.topology, toArrayOperation, callback); - } - - /** - * The callback format for results - * @callback Cursor~countResultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {number} count The count of documents. - */ - - /** - * Get the count of documents for this cursor - * @method - * @param {boolean} [applySkipLimit=true] Should the count command apply limit and skip settings on the cursor or in the passed in options. - * @param {object} [options] Optional settings. - * @param {number} [options.skip] The number of documents to skip. - * @param {number} [options.limit] The maximum amounts to count before aborting. - * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query. - * @param {string} [options.hint] An index name hint for the query. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {Cursor~countResultCallback} [callback] The result callback. - * @return {Promise} returns Promise if no callback passed - */ - count(applySkipLimit, opts, callback) { - if (this.cmd.query == null) - throw MongoError.create({ - message: 'count can only be used with find command', - driver: true - }); - if (typeof opts === 'function') (callback = opts), (opts = {}); - opts = opts || {}; - - if (typeof applySkipLimit === 'function') { - callback = applySkipLimit; - applySkipLimit = true; - } - - if (this.cursorState.session) { - opts = Object.assign({}, opts, { session: this.cursorState.session }); - } - - const countOperation = new CountOperation(this, applySkipLimit, opts); - - return executeOperation(this.topology, countOperation, callback); - } - - /** - * Close the cursor, sending a KillCursor command and emitting close. - * @method - * @param {object} [options] Optional settings. - * @param {boolean} [options.skipKillCursors] Bypass calling killCursors when closing the cursor. - * @param {Cursor~resultCallback} [callback] The result callback. - * @return {Promise} returns Promise if no callback passed - */ - close(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = Object.assign({}, { skipKillCursors: false }, options); - - this.s.state = CursorState.CLOSED; - if (!options.skipKillCursors) { - // Kill the cursor - this.kill(); - } - - const completeClose = () => { - // Emit the close event for the cursor - this.emit('close'); - - // Callback if provided - if (typeof callback === 'function') { - return handleCallback(callback, null, this); - } - - // Return a Promise - return new this.s.promiseLibrary(resolve => { - resolve(); - }); - }; - - if (this.cursorState.session) { - if (typeof callback === 'function') { - return this._endSession(() => completeClose()); - } - - return new this.s.promiseLibrary(resolve => { - this._endSession(() => completeClose().then(resolve)); - }); - } - - return completeClose(); - } - - /** - * Map all documents using the provided function - * @method - * @param {function} [transform] The mapping transformation method. - * @return {Cursor} - */ - map(transform) { - if (this.cursorState.transforms && this.cursorState.transforms.doc) { - const oldTransform = this.cursorState.transforms.doc; - this.cursorState.transforms.doc = doc => { - return transform(oldTransform(doc)); - }; - } else { - this.cursorState.transforms = { doc: transform }; - } - - return this; - } - - /** - * Is the cursor closed - * @method - * @return {boolean} - */ - isClosed() { - return this.isDead(); - } - - destroy(err) { - if (err) this.emit('error', err); - this.pause(); - this.close(); - } - - /** - * Return a modified Readable stream including a possible transform method. - * @method - * @param {object} [options] Optional settings. - * @param {function} [options.transform] A transformation method applied to each document emitted by the stream. - * @return {Cursor} - * TODO: replace this method with transformStream in next major release - */ - stream(options) { - this.cursorState.streamOptions = options || {}; - return this; - } - - /** - * Return a modified Readable stream that applies a given transform function, if supplied. If none supplied, - * returns a stream of unmodified docs. - * @method - * @param {object} [options] Optional settings. - * @param {function} [options.transform] A transformation method applied to each document emitted by the stream. - * @return {stream} - */ - transformStream(options) { - const streamOptions = options || {}; - if (typeof streamOptions.transform === 'function') { - const stream = new Transform({ - objectMode: true, - transform: function(chunk, encoding, callback) { - this.push(streamOptions.transform(chunk)); - callback(); - } - }); - - return this.pipe(stream); - } - - return this.pipe(new PassThrough({ objectMode: true })); - } - - /** - * Execute the explain for the cursor - * @method - * @param {Cursor~resultCallback} [callback] The result callback. - * @return {Promise} returns Promise if no callback passed - */ - explain(callback) { - // NOTE: the next line includes a special case for operations which do not - // subclass `CommandOperationV2`. To be removed asap. - if (this.operation && this.operation.cmd == null) { - this.operation.options.explain = true; - this.operation.fullResponse = false; - return executeOperation(this.topology, this.operation, callback); - } - - this.cmd.explain = true; - - // Do we have a readConcern - if (this.cmd.readConcern) { - delete this.cmd['readConcern']; - } - - const explainOperation = new ExplainOperation(this); - - return executeOperation(this.topology, explainOperation, callback); - } - - /** - * Return the cursor logger - * @method - * @return {Logger} return the cursor logger - * @ignore - */ - getLogger() { - return this.logger; - } -} - -/** - * Cursor stream data event, fired for each document in the cursor. - * - * @event Cursor#data - * @type {object} - */ - -/** - * Cursor stream end event - * - * @event Cursor#end - * @type {null} - */ - -/** - * Cursor stream close event - * - * @event Cursor#close - * @type {null} - */ - -/** - * Cursor stream readable event - * - * @event Cursor#readable - * @type {null} - */ - -// aliases -Cursor.prototype.maxTimeMs = Cursor.prototype.maxTimeMS; - -// deprecated methods -deprecate(Cursor.prototype.each, 'Cursor.each is deprecated. Use Cursor.forEach instead.'); -deprecate( - Cursor.prototype.maxScan, - 'Cursor.maxScan is deprecated, and will be removed in a later version' -); - -deprecate( - Cursor.prototype.snapshot, - 'Cursor Snapshot is deprecated, and will be removed in a later version' -); - -/** - * The read() method pulls some data out of the internal buffer and returns it. If there is no data available, then it will return null. - * @function external:Readable#read - * @param {number} size Optional argument to specify how much data to read. - * @return {(String | Buffer | null)} - */ - -/** - * Call this function to cause the stream to return strings of the specified encoding instead of Buffer objects. - * @function external:Readable#setEncoding - * @param {string} encoding The encoding to use. - * @return {null} - */ - -/** - * This method will cause the readable stream to resume emitting data events. - * @function external:Readable#resume - * @return {null} - */ - -/** - * This method will cause a stream in flowing-mode to stop emitting data events. Any data that becomes available will remain in the internal buffer. - * @function external:Readable#pause - * @return {null} - */ - -/** - * This method pulls all the data out of a readable stream, and writes it to the supplied destination, automatically managing the flow so that the destination is not overwhelmed by a fast readable stream. - * @function external:Readable#pipe - * @param {Writable} destination The destination for writing data - * @param {object} [options] Pipe options - * @return {null} - */ - -/** - * This method will remove the hooks set up for a previous pipe() call. - * @function external:Readable#unpipe - * @param {Writable} [destination] The destination for writing data - * @return {null} - */ - -/** - * This is useful in certain cases where a stream is being consumed by a parser, which needs to "un-consume" some data that it has optimistically pulled out of the source, so that the stream can be passed on to some other party. - * @function external:Readable#unshift - * @param {(Buffer|string)} chunk Chunk of data to unshift onto the read queue. - * @return {null} - */ - -/** - * Versions of Node prior to v0.10 had streams that did not implement the entire Streams API as it is today. (See "Compatibility" below for more information.) - * @function external:Readable#wrap - * @param {Stream} stream An "old style" readable stream. - * @return {null} - */ - -module.exports = Cursor; diff --git a/scripts/2.5/node_modules/mongodb/lib/db.js b/scripts/2.5/node_modules/mongodb/lib/db.js deleted file mode 100644 index 5e68734a..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/db.js +++ /dev/null @@ -1,1029 +0,0 @@ -'use strict'; - -const EventEmitter = require('events').EventEmitter; -const inherits = require('util').inherits; -const getSingleProperty = require('./utils').getSingleProperty; -const CommandCursor = require('./command_cursor'); -const handleCallback = require('./utils').handleCallback; -const filterOptions = require('./utils').filterOptions; -const toError = require('./utils').toError; -const ReadPreference = require('./core').ReadPreference; -const MongoError = require('./core').MongoError; -const ObjectID = require('./core').ObjectID; -const Logger = require('./core').Logger; -const Collection = require('./collection'); -const mergeOptionsAndWriteConcern = require('./utils').mergeOptionsAndWriteConcern; -const executeLegacyOperation = require('./utils').executeLegacyOperation; -const resolveReadPreference = require('./utils').resolveReadPreference; -const ChangeStream = require('./change_stream'); -const deprecate = require('util').deprecate; -const deprecateOptions = require('./utils').deprecateOptions; -const MongoDBNamespace = require('./utils').MongoDBNamespace; -const CONSTANTS = require('./constants'); -const WriteConcern = require('./write_concern'); -const ReadConcern = require('./read_concern'); -const AggregationCursor = require('./aggregation_cursor'); - -// Operations -const createListener = require('./operations/db_ops').createListener; -const ensureIndex = require('./operations/db_ops').ensureIndex; -const evaluate = require('./operations/db_ops').evaluate; -const profilingInfo = require('./operations/db_ops').profilingInfo; -const validateDatabaseName = require('./operations/db_ops').validateDatabaseName; - -const AggregateOperation = require('./operations/aggregate'); -const AddUserOperation = require('./operations/add_user'); -const CollectionsOperation = require('./operations/collections'); -const CommandOperation = require('./operations/command'); -const CreateCollectionOperation = require('./operations/create_collection'); -const CreateIndexOperation = require('./operations/create_index'); -const DropCollectionOperation = require('./operations/drop').DropCollectionOperation; -const DropDatabaseOperation = require('./operations/drop').DropDatabaseOperation; -const ExecuteDbAdminCommandOperation = require('./operations/execute_db_admin_command'); -const IndexInformationOperation = require('./operations/index_information'); -const ListCollectionsOperation = require('./operations/list_collections'); -const ProfilingLevelOperation = require('./operations/profiling_level'); -const RemoveUserOperation = require('./operations/remove_user'); -const RenameOperation = require('./operations/rename'); -const SetProfilingLevelOperation = require('./operations/set_profiling_level'); - -const executeOperation = require('./operations/execute_operation'); - -/** - * @fileOverview The **Db** class is a class that represents a MongoDB Database. - * - * @example - * const MongoClient = require('mongodb').MongoClient; - * // Connection url - * const url = 'mongodb://localhost:27017'; - * // Database Name - * const dbName = 'test'; - * // Connect using MongoClient - * MongoClient.connect(url, function(err, client) { - * // Select the database by name - * const testDb = client.db(dbName); - * client.close(); - * }); - */ - -// Allowed parameters -const legalOptionNames = [ - 'w', - 'wtimeout', - 'fsync', - 'j', - 'readPreference', - 'readPreferenceTags', - 'native_parser', - 'forceServerObjectId', - 'pkFactory', - 'serializeFunctions', - 'raw', - 'bufferMaxEntries', - 'authSource', - 'ignoreUndefined', - 'promoteLongs', - 'promiseLibrary', - 'readConcern', - 'retryMiliSeconds', - 'numberOfRetries', - 'parentDb', - 'noListener', - 'loggerLevel', - 'logger', - 'promoteBuffers', - 'promoteLongs', - 'promoteValues', - 'compression', - 'retryWrites' -]; - -/** - * Creates a new Db instance - * @class - * @param {string} databaseName The name of the database this instance represents. - * @param {(Server|ReplSet|Mongos)} topology The server topology for the database. - * @param {object} [options] Optional settings. - * @param {string} [options.authSource] If the database authentication is dependent on another databaseName. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. - * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution. - * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. - * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. - * @param {number} [options.bufferMaxEntries=-1] Sets a cap on how many operations the driver will buffer up before giving up on getting a working connection, default is -1 which is unlimited. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {object} [options.pkFactory] A primary key factory object for generation of custom _id keys. - * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {object} [options.readConcern] Specify a read concern for the collection. (only MongoDB 3.2 or higher supported) - * @param {ReadConcernLevel} [options.readConcern.level='local'] Specify a read concern level for the collection operations (only MongoDB 3.2 or higher supported) - * @property {(Server|ReplSet|Mongos)} serverConfig Get the current db topology. - * @property {number} bufferMaxEntries Current bufferMaxEntries value for the database - * @property {string} databaseName The name of the database this instance represents. - * @property {object} options The options associated with the db instance. - * @property {boolean} native_parser The current value of the parameter native_parser. - * @property {boolean} slaveOk The current slaveOk value for the db instance. - * @property {object} writeConcern The current write concern values. - * @property {object} topology Access the topology object (single server, replicaset or mongos). - * @fires Db#close - * @fires Db#reconnect - * @fires Db#error - * @fires Db#timeout - * @fires Db#parseError - * @fires Db#fullsetup - * @return {Db} a Db instance. - */ -function Db(databaseName, topology, options) { - options = options || {}; - if (!(this instanceof Db)) return new Db(databaseName, topology, options); - EventEmitter.call(this); - - // Get the promiseLibrary - const promiseLibrary = options.promiseLibrary || Promise; - - // Filter the options - options = filterOptions(options, legalOptionNames); - - // Ensure we put the promiseLib in the options - options.promiseLibrary = promiseLibrary; - - // Internal state of the db object - this.s = { - // DbCache - dbCache: {}, - // Children db's - children: [], - // Topology - topology: topology, - // Options - options: options, - // Logger instance - logger: Logger('Db', options), - // Get the bson parser - bson: topology ? topology.bson : null, - // Unpack read preference - readPreference: ReadPreference.fromOptions(options), - // Set buffermaxEntries - bufferMaxEntries: typeof options.bufferMaxEntries === 'number' ? options.bufferMaxEntries : -1, - // Parent db (if chained) - parentDb: options.parentDb || null, - // Set up the primary key factory or fallback to ObjectID - pkFactory: options.pkFactory || ObjectID, - // Get native parser - nativeParser: options.nativeParser || options.native_parser, - // Promise library - promiseLibrary: promiseLibrary, - // No listener - noListener: typeof options.noListener === 'boolean' ? options.noListener : false, - // ReadConcern - readConcern: ReadConcern.fromOptions(options), - writeConcern: WriteConcern.fromOptions(options), - // Namespace - namespace: new MongoDBNamespace(databaseName) - }; - - // Ensure we have a valid db name - validateDatabaseName(databaseName); - - // Add a read Only property - getSingleProperty(this, 'serverConfig', this.s.topology); - getSingleProperty(this, 'bufferMaxEntries', this.s.bufferMaxEntries); - getSingleProperty(this, 'databaseName', this.s.namespace.db); - - // This is a child db, do not register any listeners - if (options.parentDb) return; - if (this.s.noListener) return; - - // Add listeners - topology.on('error', createListener(this, 'error', this)); - topology.on('timeout', createListener(this, 'timeout', this)); - topology.on('close', createListener(this, 'close', this)); - topology.on('parseError', createListener(this, 'parseError', this)); - topology.once('open', createListener(this, 'open', this)); - topology.once('fullsetup', createListener(this, 'fullsetup', this)); - topology.once('all', createListener(this, 'all', this)); - topology.on('reconnect', createListener(this, 'reconnect', this)); -} - -inherits(Db, EventEmitter); - -// Topology -Object.defineProperty(Db.prototype, 'topology', { - enumerable: true, - get: function() { - return this.s.topology; - } -}); - -// Options -Object.defineProperty(Db.prototype, 'options', { - enumerable: true, - get: function() { - return this.s.options; - } -}); - -// slaveOk specified -Object.defineProperty(Db.prototype, 'slaveOk', { - enumerable: true, - get: function() { - if ( - this.s.options.readPreference != null && - (this.s.options.readPreference !== 'primary' || - this.s.options.readPreference.mode !== 'primary') - ) { - return true; - } - return false; - } -}); - -Object.defineProperty(Db.prototype, 'readConcern', { - enumerable: true, - get: function() { - return this.s.readConcern; - } -}); - -Object.defineProperty(Db.prototype, 'readPreference', { - enumerable: true, - get: function() { - if (this.s.readPreference == null) { - // TODO: check client - return ReadPreference.primary; - } - - return this.s.readPreference; - } -}); - -// get the write Concern -Object.defineProperty(Db.prototype, 'writeConcern', { - enumerable: true, - get: function() { - return this.s.writeConcern; - } -}); - -Object.defineProperty(Db.prototype, 'namespace', { - enumerable: true, - get: function() { - return this.s.namespace.toString(); - } -}); - -/** - * Execute a command - * @method - * @param {object} command The command hash - * @param {object} [options] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.command = function(command, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = Object.assign({}, options); - - const commandOperation = new CommandOperation(this, options, null, command); - - return executeOperation(this.s.topology, commandOperation, callback); -}; - -/** - * Execute an aggregation framework pipeline against the database, needs MongoDB >= 3.6 - * @method - * @param {object} [pipeline=[]] Array containing all the aggregation framework commands for the execution. - * @param {object} [options] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {object} [options.cursor] Return the query as cursor, on 2.6 > it returns as a real cursor on pre 2.6 it returns as an emulated cursor. - * @param {number} [options.cursor.batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. - * @param {boolean} [options.explain=false] Explain returns the aggregation execution plan (requires mongodb 2.6 >). - * @param {boolean} [options.allowDiskUse=false] allowDiskUse lets the server know if it can use disk to store temporary results for the aggregation (requires mongodb 2.6 >). - * @param {number} [options.maxTimeMS] maxTimeMS specifies a cumulative time limit in milliseconds for processing operations on the cursor. MongoDB interrupts the operation at the earliest following interrupt point. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. - * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution. - * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. - * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. - * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {string} [options.comment] Add a comment to an aggregation command - * @param {string|object} [options.hint] Add an index selection hint to an aggregation command - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Database~aggregationCallback} callback The command result callback - * @return {(null|AggregationCursor)} - */ -Db.prototype.aggregate = function(pipeline, options, callback) { - if (typeof options === 'function') { - callback = options; - options = {}; - } - - // If we have no options or callback we are doing - // a cursor based aggregation - if (options == null && callback == null) { - options = {}; - } - - const cursor = new AggregationCursor( - this.s.topology, - new AggregateOperation(this, pipeline, options), - options - ); - - // TODO: remove this when NODE-2074 is resolved - if (typeof callback === 'function') { - callback(null, cursor); - return; - } - - return cursor; -}; - -/** - * Return the Admin db instance - * @method - * @return {Admin} return the new Admin db instance - */ -Db.prototype.admin = function() { - const Admin = require('./admin'); - - return new Admin(this, this.s.topology, this.s.promiseLibrary); -}; - -/** - * The callback format for the collection method, must be used if strict is specified - * @callback Db~collectionResultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection} collection The collection instance. - */ - -/** - * The callback format for an aggregation call - * @callback Database~aggregationCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {AggregationCursor} cursor The cursor if the aggregation command was executed successfully. - */ - -const collectionKeys = [ - 'pkFactory', - 'readPreference', - 'serializeFunctions', - 'strict', - 'readConcern', - 'ignoreUndefined', - 'promoteValues', - 'promoteBuffers', - 'promoteLongs' -]; - -/** - * Fetch a specific collection (containing the actual collection information). If the application does not use strict mode you - * can use it without a callback in the following way: `const collection = db.collection('mycollection');` - * - * @method - * @param {string} name the collection name we wish to access. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. - * @param {object} [options.pkFactory] A primary key factory object for generation of custom _id keys. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {boolean} [options.strict=false] Returns an error if the collection does not exist - * @param {object} [options.readConcern] Specify a read concern for the collection. (only MongoDB 3.2 or higher supported) - * @param {ReadConcernLevel} [options.readConcern.level='local'] Specify a read concern level for the collection operations (only MongoDB 3.2 or higher supported) - * @param {Db~collectionResultCallback} [callback] The collection result callback - * @return {Collection} return the new Collection instance if not in strict mode - */ -Db.prototype.collection = function(name, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - options = Object.assign({}, options); - - // Set the promise library - options.promiseLibrary = this.s.promiseLibrary; - - // If we have not set a collection level readConcern set the db level one - options.readConcern = options.readConcern - ? new ReadConcern(options.readConcern.level) - : this.readConcern; - - // Do we have ignoreUndefined set - if (this.s.options.ignoreUndefined) { - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - // Merge in all needed options and ensure correct writeConcern merging from db level - options = mergeOptionsAndWriteConcern(options, this.s.options, collectionKeys, true); - - // Execute - if (options == null || !options.strict) { - try { - const collection = new Collection( - this, - this.s.topology, - this.databaseName, - name, - this.s.pkFactory, - options - ); - if (callback) callback(null, collection); - return collection; - } catch (err) { - if (err instanceof MongoError && callback) return callback(err); - throw err; - } - } - - // Strict mode - if (typeof callback !== 'function') { - throw toError(`A callback is required in strict mode. While getting collection ${name}`); - } - - // Did the user destroy the topology - if (this.serverConfig && this.serverConfig.isDestroyed()) { - return callback(new MongoError('topology was destroyed')); - } - - const listCollectionOptions = Object.assign({}, options, { nameOnly: true }); - - // Strict mode - this.listCollections({ name: name }, listCollectionOptions).toArray((err, collections) => { - if (err != null) return handleCallback(callback, err, null); - if (collections.length === 0) - return handleCallback( - callback, - toError(`Collection ${name} does not exist. Currently in strict mode.`), - null - ); - - try { - return handleCallback( - callback, - null, - new Collection(this, this.s.topology, this.databaseName, name, this.s.pkFactory, options) - ); - } catch (err) { - return handleCallback(callback, err, null); - } - }); -}; - -/** - * Create a new collection on a server with the specified options. Use this to create capped collections. - * More information about command options available at https://docs.mongodb.com/manual/reference/command/create/ - * - * @method - * @param {string} name the collection name we wish to access. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. - * @param {object} [options.pkFactory] A primary key factory object for generation of custom _id keys. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {boolean} [options.strict=false] Returns an error if the collection does not exist - * @param {boolean} [options.capped=false] Create a capped collection. - * @param {boolean} [options.autoIndexId=true] DEPRECATED: Create an index on the _id field of the document, True by default on MongoDB 2.6 - 3.0 - * @param {number} [options.size] The size of the capped collection in bytes. - * @param {number} [options.max] The maximum number of documents in the capped collection. - * @param {number} [options.flags] Optional. Available for the MMAPv1 storage engine only to set the usePowerOf2Sizes and the noPadding flag. - * @param {object} [options.storageEngine] Allows users to specify configuration to the storage engine on a per-collection basis when creating a collection on MongoDB 3.0 or higher. - * @param {object} [options.validator] Allows users to specify validation rules or expressions for the collection. For more information, see Document Validation on MongoDB 3.2 or higher. - * @param {string} [options.validationLevel] Determines how strictly MongoDB applies the validation rules to existing documents during an update on MongoDB 3.2 or higher. - * @param {string} [options.validationAction] Determines whether to error on invalid documents or just warn about the violations but allow invalid documents to be inserted on MongoDB 3.2 or higher. - * @param {object} [options.indexOptionDefaults] Allows users to specify a default configuration for indexes when creating a collection on MongoDB 3.2 or higher. - * @param {string} [options.viewOn] The name of the source collection or view from which to create the view. The name is not the full namespace of the collection or view; i.e. does not include the database name and implies the same database as the view to create on MongoDB 3.4 or higher. - * @param {array} [options.pipeline] An array that consists of the aggregation pipeline stage. Creates the view by applying the specified pipeline to the viewOn collection or view on MongoDB 3.4 or higher. - * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~collectionResultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.createCollection = deprecateOptions( - { - name: 'Db.createCollection', - deprecatedOptions: ['autoIndexId'], - optionsIndex: 1 - }, - function(name, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - options.promiseLibrary = options.promiseLibrary || this.s.promiseLibrary; - options.readConcern = options.readConcern - ? new ReadConcern(options.readConcern.level) - : this.readConcern; - const createCollectionOperation = new CreateCollectionOperation(this, name, options); - - return executeOperation(this.s.topology, createCollectionOperation, callback); - } -); - -/** - * Get all the db statistics. - * - * @method - * @param {object} [options] Optional settings. - * @param {number} [options.scale] Divide the returned sizes by scale value. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The collection result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.stats = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - // Build command object - const commandObject = { dbStats: true }; - // Check if we have the scale value - if (options['scale'] != null) commandObject['scale'] = options['scale']; - - // If we have a readPreference set - if (options.readPreference == null && this.s.readPreference) { - options.readPreference = this.s.readPreference; - } - - const statsOperation = new CommandOperation(this, options, null, commandObject); - - // Execute the command - return executeOperation(this.s.topology, statsOperation, callback); -}; - -/** - * Get the list of all collection information for the specified db. - * - * @method - * @param {object} [filter={}] Query to filter collections by - * @param {object} [options] Optional settings. - * @param {boolean} [options.nameOnly=false] Since 4.0: If true, will only return the collection name in the response, and will omit additional info - * @param {number} [options.batchSize=1000] The batchSize for the returned command cursor or if pre 2.8 the systems batch collection - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {ClientSession} [options.session] optional session to use for this operation - * @return {CommandCursor} - */ -Db.prototype.listCollections = function(filter, options) { - filter = filter || {}; - options = options || {}; - - return new CommandCursor( - this.s.topology, - new ListCollectionsOperation(this, filter, options), - options - ); -}; - -/** - * Evaluate JavaScript on the server - * - * @method - * @param {Code} code JavaScript to execute on server. - * @param {(object|array)} parameters The parameters for the call. - * @param {object} [options] Optional settings. - * @param {boolean} [options.nolock=false] Tell MongoDB not to block on the evaluation of the javascript. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The results callback - * @deprecated Eval is deprecated on MongoDB 3.2 and forward - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.eval = deprecate(function(code, parameters, options, callback) { - const args = Array.prototype.slice.call(arguments, 1); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - parameters = args.length ? args.shift() : parameters; - options = args.length ? args.shift() || {} : {}; - - return executeLegacyOperation(this.s.topology, evaluate, [ - this, - code, - parameters, - options, - callback - ]); -}, 'Db.eval is deprecated as of MongoDB version 3.2'); - -/** - * Rename a collection. - * - * @method - * @param {string} fromCollection Name of current collection to rename. - * @param {string} toCollection New name of of the collection. - * @param {object} [options] Optional settings. - * @param {boolean} [options.dropTarget=false] Drop the target name collection if it previously exists. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~collectionResultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.renameCollection = function(fromCollection, toCollection, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = Object.assign({}, options, { readPreference: ReadPreference.PRIMARY }); - - // Add return new collection - options.new_collection = true; - - const renameOperation = new RenameOperation( - this.collection(fromCollection), - toCollection, - options - ); - - return executeOperation(this.s.topology, renameOperation, callback); -}; - -/** - * Drop a collection from the database, removing it permanently. New accesses will create a new collection. - * - * @method - * @param {string} name Name of collection to drop - * @param {Object} [options] Optional settings - * @param {WriteConcern} [options.writeConcern] A full WriteConcern object - * @param {(number|string)} [options.w] The write concern - * @param {number} [options.wtimeout] The write concern timeout - * @param {boolean} [options.j] The journal write concern - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.dropCollection = function(name, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const dropCollectionOperation = new DropCollectionOperation(this, name, options); - - return executeOperation(this.s.topology, dropCollectionOperation, callback); -}; - -/** - * Drop a database, removing it permanently from the server. - * - * @method - * @param {Object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.dropDatabase = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const dropDatabaseOperation = new DropDatabaseOperation(this, options); - - return executeOperation(this.s.topology, dropDatabaseOperation, callback); -}; - -/** - * Fetch all collections for the current db. - * - * @method - * @param {Object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~collectionsResultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.collections = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const collectionsOperation = new CollectionsOperation(this, options); - - return executeOperation(this.s.topology, collectionsOperation, callback); -}; - -/** - * Runs a command on the database as admin. - * @method - * @param {object} command The command hash - * @param {object} [options] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.executeDbAdminCommand = function(selector, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - options.readPreference = resolveReadPreference(this, options); - - const executeDbAdminCommandOperation = new ExecuteDbAdminCommandOperation( - this, - selector, - options - ); - - return executeOperation(this.s.topology, executeDbAdminCommandOperation, callback); -}; - -/** - * Creates an index on the db and collection. - * @method - * @param {string} name Name of the collection to create the index on. - * @param {(string|object)} fieldOrSpec Defines the index. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.unique=false] Creates an unique index. - * @param {boolean} [options.sparse=false] Creates a sparse index. - * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. - * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value - * @param {number} [options.min] For geospatial indexes set the lower bound for the co-ordinates. - * @param {number} [options.max] For geospatial indexes set the high bound for the co-ordinates. - * @param {number} [options.v] Specify the format version of the indexes. - * @param {number} [options.expireAfterSeconds] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) - * @param {string} [options.name] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) - * @param {object} [options.partialFilterExpression] Creates a partial index based on the given filter object (MongoDB 3.2 or higher) - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.createIndex = function(name, fieldOrSpec, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options ? Object.assign({}, options) : {}; - - const createIndexOperation = new CreateIndexOperation(this, name, fieldOrSpec, options); - - return executeOperation(this.s.topology, createIndexOperation, callback); -}; - -/** - * Ensures that an index exists, if it does not it creates it - * @method - * @deprecated since version 2.0 - * @param {string} name The index name - * @param {(string|object)} fieldOrSpec Defines the index. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.unique=false] Creates an unique index. - * @param {boolean} [options.sparse=false] Creates a sparse index. - * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. - * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value - * @param {number} [options.min] For geospatial indexes set the lower bound for the co-ordinates. - * @param {number} [options.max] For geospatial indexes set the high bound for the co-ordinates. - * @param {number} [options.v] Specify the format version of the indexes. - * @param {number} [options.expireAfterSeconds] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) - * @param {number} [options.name] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.ensureIndex = deprecate(function(name, fieldOrSpec, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - return executeLegacyOperation(this.s.topology, ensureIndex, [ - this, - name, - fieldOrSpec, - options, - callback - ]); -}, 'Db.ensureIndex is deprecated as of MongoDB version 3.0 / driver version 2.0'); - -Db.prototype.addChild = function(db) { - if (this.s.parentDb) return this.s.parentDb.addChild(db); - this.s.children.push(db); -}; - -/** - * Add a user to the database. - * @method - * @param {string} username The username. - * @param {string} password The password. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {object} [options.customData] Custom data associated with the user (only Mongodb 2.6 or higher) - * @param {object[]} [options.roles] Roles associated with the created user (only Mongodb 2.6 or higher) - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.addUser = function(username, password, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // Special case where there is no password ($external users) - if (typeof username === 'string' && password != null && typeof password === 'object') { - options = password; - password = null; - } - - const addUserOperation = new AddUserOperation(this, username, password, options); - - return executeOperation(this.s.topology, addUserOperation, callback); -}; - -/** - * Remove a user from a database - * @method - * @param {string} username The username. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.removeUser = function(username, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const removeUserOperation = new RemoveUserOperation(this, username, options); - - return executeOperation(this.s.topology, removeUserOperation, callback); -}; - -/** - * Set the current profiling level of MongoDB - * - * @param {string} level The new profiling level (off, slow_only, all). - * @param {Object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The command result callback. - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.setProfilingLevel = function(level, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const setProfilingLevelOperation = new SetProfilingLevelOperation(this, level, options); - - return executeOperation(this.s.topology, setProfilingLevelOperation, callback); -}; - -/** - * Retrieve the current profiling information for MongoDB - * - * @param {Object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The command result callback. - * @return {Promise} returns Promise if no callback passed - * @deprecated Query the system.profile collection directly. - */ -Db.prototype.profilingInfo = deprecate(function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - return executeLegacyOperation(this.s.topology, profilingInfo, [this, options, callback]); -}, 'Db.profilingInfo is deprecated. Query the system.profile collection directly.'); - -/** - * Retrieve the current profiling Level for MongoDB - * - * @param {Object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.profilingLevel = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const profilingLevelOperation = new ProfilingLevelOperation(this, options); - - return executeOperation(this.s.topology, profilingLevelOperation, callback); -}; - -/** - * Retrieves this collections index info. - * @method - * @param {string} name The name of the collection. - * @param {object} [options] Optional settings. - * @param {boolean} [options.full=false] Returns the full raw index information. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.indexInformation = function(name, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const indexInformationOperation = new IndexInformationOperation(this, name, options); - - return executeOperation(this.s.topology, indexInformationOperation, callback); -}; - -/** - * Unref all sockets - * @method - */ -Db.prototype.unref = function() { - this.s.topology.unref(); -}; - -/** - * Create a new Change Stream, watching for new changes (insertions, updates, replacements, deletions, and invalidations) in this database. Will ignore all changes to system collections. - * @method - * @since 3.1.0 - * @param {Array} [pipeline] An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents. - * @param {object} [options] Optional settings - * @param {string} [options.fullDocument='default'] Allowed values: ‘default’, ‘updateLookup’. When set to ‘updateLookup’, the change stream will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred. - * @param {object} [options.resumeAfter] Specifies the logical starting point for the new change stream. This should be the _id field from a previously returned change stream document. - * @param {number} [options.maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a change stream query - * @param {number} [options.batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. - * @param {object} [options.collation] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. - * @param {ReadPreference} [options.readPreference] The read preference. Defaults to the read preference of the database. See {@link https://docs.mongodb.com/manual/reference/read-preference|read preference documentation}. - * @param {Timestamp} [options.startAtOperationTime] receive change events that occur after the specified timestamp - * @param {ClientSession} [options.session] optional session to use for this operation - * @return {ChangeStream} a ChangeStream instance. - */ -Db.prototype.watch = function(pipeline, options) { - pipeline = pipeline || []; - options = options || {}; - - // Allow optionally not specifying a pipeline - if (!Array.isArray(pipeline)) { - options = pipeline; - pipeline = []; - } - - return new ChangeStream(this, pipeline, options); -}; - -/** - * Return the db logger - * @method - * @return {Logger} return the db logger - * @ignore - */ -Db.prototype.getLogger = function() { - return this.s.logger; -}; - -/** - * Db close event - * - * Emitted after a socket closed against a single server or mongos proxy. - * - * @event Db#close - * @type {MongoError} - */ - -/** - * Db reconnect event - * - * * Server: Emitted when the driver has reconnected and re-authenticated. - * * ReplicaSet: N/A - * * Mongos: Emitted when the driver reconnects and re-authenticates successfully against a Mongos. - * - * @event Db#reconnect - * @type {object} - */ - -/** - * Db error event - * - * Emitted after an error occurred against a single server or mongos proxy. - * - * @event Db#error - * @type {MongoError} - */ - -/** - * Db timeout event - * - * Emitted after a socket timeout occurred against a single server or mongos proxy. - * - * @event Db#timeout - * @type {MongoError} - */ - -/** - * Db parseError event - * - * The parseError event is emitted if the driver detects illegal or corrupt BSON being received from the server. - * - * @event Db#parseError - * @type {MongoError} - */ - -/** - * Db fullsetup event, emitted when all servers in the topology have been connected to at start up time. - * - * * Server: Emitted when the driver has connected to the single server and has authenticated. - * * ReplSet: Emitted after the driver has attempted to connect to all replicaset members. - * * Mongos: Emitted after the driver has attempted to connect to all mongos proxies. - * - * @event Db#fullsetup - * @type {Db} - */ - -// Constants -Db.SYSTEM_NAMESPACE_COLLECTION = CONSTANTS.SYSTEM_NAMESPACE_COLLECTION; -Db.SYSTEM_INDEX_COLLECTION = CONSTANTS.SYSTEM_INDEX_COLLECTION; -Db.SYSTEM_PROFILE_COLLECTION = CONSTANTS.SYSTEM_PROFILE_COLLECTION; -Db.SYSTEM_USER_COLLECTION = CONSTANTS.SYSTEM_USER_COLLECTION; -Db.SYSTEM_COMMAND_COLLECTION = CONSTANTS.SYSTEM_COMMAND_COLLECTION; -Db.SYSTEM_JS_COLLECTION = CONSTANTS.SYSTEM_JS_COLLECTION; - -module.exports = Db; diff --git a/scripts/2.5/node_modules/mongodb/lib/dynamic_loaders.js b/scripts/2.5/node_modules/mongodb/lib/dynamic_loaders.js deleted file mode 100644 index c4610023..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/dynamic_loaders.js +++ /dev/null @@ -1,32 +0,0 @@ -'use strict'; - -let collection; -let cursor; -let db; - -function loadCollection() { - if (!collection) { - collection = require('./collection'); - } - return collection; -} - -function loadCursor() { - if (!cursor) { - cursor = require('./cursor'); - } - return cursor; -} - -function loadDb() { - if (!db) { - db = require('./db'); - } - return db; -} - -module.exports = { - loadCollection, - loadCursor, - loadDb -}; diff --git a/scripts/2.5/node_modules/mongodb/lib/error.js b/scripts/2.5/node_modules/mongodb/lib/error.js deleted file mode 100644 index 4d104e9b..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/error.js +++ /dev/null @@ -1,45 +0,0 @@ -'use strict'; - -const MongoNetworkError = require('./core').MongoNetworkError; -const mongoErrorContextSymbol = require('./core').mongoErrorContextSymbol; - -const GET_MORE_NON_RESUMABLE_CODES = new Set([ - 136, // CappedPositionLost - 237, // CursorKilled - 11601 // Interrupted -]); - -// From spec@https://github.com/mongodb/specifications/blob/7a2e93d85935ee4b1046a8d2ad3514c657dc74fa/source/change-streams/change-streams.rst#resumable-error: -// -// An error is considered resumable if it meets any of the following criteria: -// - any error encountered which is not a server error (e.g. a timeout error or network error) -// - any server error response from a getMore command excluding those containing the error label -// NonRetryableChangeStreamError and those containing the following error codes: -// - Interrupted: 11601 -// - CappedPositionLost: 136 -// - CursorKilled: 237 -// -// An error on an aggregate command is not a resumable error. Only errors on a getMore command may be considered resumable errors. - -function isGetMoreError(error) { - if (error[mongoErrorContextSymbol]) { - return error[mongoErrorContextSymbol].isGetMore; - } -} - -function isResumableError(error) { - if (!isGetMoreError(error)) { - return false; - } - - if (error instanceof MongoNetworkError) { - return true; - } - - return !( - GET_MORE_NON_RESUMABLE_CODES.has(error.code) || - error.hasErrorLabel('NonRetryableChangeStreamError') - ); -} - -module.exports = { GET_MORE_NON_RESUMABLE_CODES, isResumableError }; diff --git a/scripts/2.5/node_modules/mongodb/lib/gridfs-stream/download.js b/scripts/2.5/node_modules/mongodb/lib/gridfs-stream/download.js deleted file mode 100644 index dfb1de57..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/gridfs-stream/download.js +++ /dev/null @@ -1,421 +0,0 @@ -'use strict'; - -var stream = require('stream'), - util = require('util'); - -module.exports = GridFSBucketReadStream; - -/** - * A readable stream that enables you to read buffers from GridFS. - * - * Do not instantiate this class directly. Use `openDownloadStream()` instead. - * - * @class - * @param {Collection} chunks Handle for chunks collection - * @param {Collection} files Handle for files collection - * @param {Object} readPreference The read preference to use - * @param {Object} filter The query to use to find the file document - * @param {Object} [options] Optional settings. - * @param {Number} [options.sort] Optional sort for the file find query - * @param {Number} [options.skip] Optional skip for the file find query - * @param {Number} [options.start] Optional 0-based offset in bytes to start streaming from - * @param {Number} [options.end] Optional 0-based offset in bytes to stop streaming before - * @fires GridFSBucketReadStream#error - * @fires GridFSBucketReadStream#file - * @return {GridFSBucketReadStream} a GridFSBucketReadStream instance. - */ - -function GridFSBucketReadStream(chunks, files, readPreference, filter, options) { - this.s = { - bytesRead: 0, - chunks: chunks, - cursor: null, - expected: 0, - files: files, - filter: filter, - init: false, - expectedEnd: 0, - file: null, - options: options, - readPreference: readPreference - }; - - stream.Readable.call(this); -} - -util.inherits(GridFSBucketReadStream, stream.Readable); - -/** - * An error occurred - * - * @event GridFSBucketReadStream#error - * @type {Error} - */ - -/** - * Fires when the stream loaded the file document corresponding to the - * provided id. - * - * @event GridFSBucketReadStream#file - * @type {object} - */ - -/** - * Emitted when a chunk of data is available to be consumed. - * - * @event GridFSBucketReadStream#data - * @type {object} - */ - -/** - * Fired when the stream is exhausted (no more data events). - * - * @event GridFSBucketReadStream#end - * @type {object} - */ - -/** - * Fired when the stream is exhausted and the underlying cursor is killed - * - * @event GridFSBucketReadStream#close - * @type {object} - */ - -/** - * Reads from the cursor and pushes to the stream. - * @method - */ - -GridFSBucketReadStream.prototype._read = function() { - var _this = this; - if (this.destroyed) { - return; - } - - waitForFile(_this, function() { - doRead(_this); - }); -}; - -/** - * Sets the 0-based offset in bytes to start streaming from. Throws - * an error if this stream has entered flowing mode - * (e.g. if you've already called `on('data')`) - * @method - * @param {Number} start Offset in bytes to start reading at - * @return {GridFSBucketReadStream} - */ - -GridFSBucketReadStream.prototype.start = function(start) { - throwIfInitialized(this); - this.s.options.start = start; - return this; -}; - -/** - * Sets the 0-based offset in bytes to start streaming from. Throws - * an error if this stream has entered flowing mode - * (e.g. if you've already called `on('data')`) - * @method - * @param {Number} end Offset in bytes to stop reading at - * @return {GridFSBucketReadStream} - */ - -GridFSBucketReadStream.prototype.end = function(end) { - throwIfInitialized(this); - this.s.options.end = end; - return this; -}; - -/** - * Marks this stream as aborted (will never push another `data` event) - * and kills the underlying cursor. Will emit the 'end' event, and then - * the 'close' event once the cursor is successfully killed. - * - * @method - * @param {GridFSBucket~errorCallback} [callback] called when the cursor is successfully closed or an error occurred. - * @fires GridFSBucketWriteStream#close - * @fires GridFSBucketWriteStream#end - */ - -GridFSBucketReadStream.prototype.abort = function(callback) { - var _this = this; - this.push(null); - this.destroyed = true; - if (this.s.cursor) { - this.s.cursor.close(function(error) { - _this.emit('close'); - callback && callback(error); - }); - } else { - if (!this.s.init) { - // If not initialized, fire close event because we will never - // get a cursor - _this.emit('close'); - } - callback && callback(); - } -}; - -/** - * @ignore - */ - -function throwIfInitialized(self) { - if (self.s.init) { - throw new Error('You cannot change options after the stream has entered' + 'flowing mode!'); - } -} - -/** - * @ignore - */ - -function doRead(_this) { - if (_this.destroyed) { - return; - } - - _this.s.cursor.next(function(error, doc) { - if (_this.destroyed) { - return; - } - if (error) { - return __handleError(_this, error); - } - if (!doc) { - _this.push(null); - - process.nextTick(() => { - _this.s.cursor.close(function(error) { - if (error) { - __handleError(_this, error); - return; - } - - _this.emit('close'); - }); - }); - - return; - } - - var bytesRemaining = _this.s.file.length - _this.s.bytesRead; - var expectedN = _this.s.expected++; - var expectedLength = Math.min(_this.s.file.chunkSize, bytesRemaining); - - if (doc.n > expectedN) { - var errmsg = 'ChunkIsMissing: Got unexpected n: ' + doc.n + ', expected: ' + expectedN; - return __handleError(_this, new Error(errmsg)); - } - - if (doc.n < expectedN) { - errmsg = 'ExtraChunk: Got unexpected n: ' + doc.n + ', expected: ' + expectedN; - return __handleError(_this, new Error(errmsg)); - } - - var buf = Buffer.isBuffer(doc.data) ? doc.data : doc.data.buffer; - - if (buf.length !== expectedLength) { - if (bytesRemaining <= 0) { - errmsg = 'ExtraChunk: Got unexpected n: ' + doc.n; - return __handleError(_this, new Error(errmsg)); - } - - errmsg = - 'ChunkIsWrongSize: Got unexpected length: ' + buf.length + ', expected: ' + expectedLength; - return __handleError(_this, new Error(errmsg)); - } - - _this.s.bytesRead += buf.length; - - if (buf.length === 0) { - return _this.push(null); - } - - var sliceStart = null; - var sliceEnd = null; - - if (_this.s.bytesToSkip != null) { - sliceStart = _this.s.bytesToSkip; - _this.s.bytesToSkip = 0; - } - - const atEndOfStream = expectedN === _this.s.expectedEnd - 1; - const bytesLeftToRead = _this.s.options.end - _this.s.bytesToSkip; - if (atEndOfStream && _this.s.bytesToTrim != null) { - sliceEnd = _this.s.file.chunkSize - _this.s.bytesToTrim; - } else if (_this.s.options.end && bytesLeftToRead < doc.data.length()) { - sliceEnd = bytesLeftToRead; - } - - if (sliceStart != null || sliceEnd != null) { - buf = buf.slice(sliceStart || 0, sliceEnd || buf.length); - } - - _this.push(buf); - }); -} - -/** - * @ignore - */ - -function init(self) { - var findOneOptions = {}; - if (self.s.readPreference) { - findOneOptions.readPreference = self.s.readPreference; - } - if (self.s.options && self.s.options.sort) { - findOneOptions.sort = self.s.options.sort; - } - if (self.s.options && self.s.options.skip) { - findOneOptions.skip = self.s.options.skip; - } - - self.s.files.findOne(self.s.filter, findOneOptions, function(error, doc) { - if (error) { - return __handleError(self, error); - } - if (!doc) { - var identifier = self.s.filter._id ? self.s.filter._id.toString() : self.s.filter.filename; - var errmsg = 'FileNotFound: file ' + identifier + ' was not found'; - var err = new Error(errmsg); - err.code = 'ENOENT'; - return __handleError(self, err); - } - - // If document is empty, kill the stream immediately and don't - // execute any reads - if (doc.length <= 0) { - self.push(null); - return; - } - - if (self.destroyed) { - // If user destroys the stream before we have a cursor, wait - // until the query is done to say we're 'closed' because we can't - // cancel a query. - self.emit('close'); - return; - } - - self.s.bytesToSkip = handleStartOption(self, doc, self.s.options); - - var filter = { files_id: doc._id }; - - // Currently (MongoDB 3.4.4) skip function does not support the index, - // it needs to retrieve all the documents first and then skip them. (CS-25811) - // As work around we use $gte on the "n" field. - if (self.s.options && self.s.options.start != null) { - var skip = Math.floor(self.s.options.start / doc.chunkSize); - if (skip > 0) { - filter['n'] = { $gte: skip }; - } - } - self.s.cursor = self.s.chunks.find(filter).sort({ n: 1 }); - - if (self.s.readPreference) { - self.s.cursor.setReadPreference(self.s.readPreference); - } - - self.s.expectedEnd = Math.ceil(doc.length / doc.chunkSize); - self.s.file = doc; - self.s.bytesToTrim = handleEndOption(self, doc, self.s.cursor, self.s.options); - self.emit('file', doc); - }); -} - -/** - * @ignore - */ - -function waitForFile(_this, callback) { - if (_this.s.file) { - return callback(); - } - - if (!_this.s.init) { - init(_this); - _this.s.init = true; - } - - _this.once('file', function() { - callback(); - }); -} - -/** - * @ignore - */ - -function handleStartOption(stream, doc, options) { - if (options && options.start != null) { - if (options.start > doc.length) { - throw new Error( - 'Stream start (' + - options.start + - ') must not be ' + - 'more than the length of the file (' + - doc.length + - ')' - ); - } - if (options.start < 0) { - throw new Error('Stream start (' + options.start + ') must not be ' + 'negative'); - } - if (options.end != null && options.end < options.start) { - throw new Error( - 'Stream start (' + - options.start + - ') must not be ' + - 'greater than stream end (' + - options.end + - ')' - ); - } - - stream.s.bytesRead = Math.floor(options.start / doc.chunkSize) * doc.chunkSize; - stream.s.expected = Math.floor(options.start / doc.chunkSize); - - return options.start - stream.s.bytesRead; - } -} - -/** - * @ignore - */ - -function handleEndOption(stream, doc, cursor, options) { - if (options && options.end != null) { - if (options.end > doc.length) { - throw new Error( - 'Stream end (' + - options.end + - ') must not be ' + - 'more than the length of the file (' + - doc.length + - ')' - ); - } - if (options.start < 0) { - throw new Error('Stream end (' + options.end + ') must not be ' + 'negative'); - } - - var start = options.start != null ? Math.floor(options.start / doc.chunkSize) : 0; - - cursor.limit(Math.ceil(options.end / doc.chunkSize) - start); - - stream.s.expectedEnd = Math.ceil(options.end / doc.chunkSize); - - return Math.ceil(options.end / doc.chunkSize) * doc.chunkSize - options.end; - } -} - -/** - * @ignore - */ - -function __handleError(_this, error) { - _this.emit('error', error); -} diff --git a/scripts/2.5/node_modules/mongodb/lib/gridfs-stream/index.js b/scripts/2.5/node_modules/mongodb/lib/gridfs-stream/index.js deleted file mode 100644 index 93b45ebf..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/gridfs-stream/index.js +++ /dev/null @@ -1,358 +0,0 @@ -'use strict'; - -var Emitter = require('events').EventEmitter; -var GridFSBucketReadStream = require('./download'); -var GridFSBucketWriteStream = require('./upload'); -var shallowClone = require('../utils').shallowClone; -var toError = require('../utils').toError; -var util = require('util'); -var executeLegacyOperation = require('../utils').executeLegacyOperation; - -var DEFAULT_GRIDFS_BUCKET_OPTIONS = { - bucketName: 'fs', - chunkSizeBytes: 255 * 1024 -}; - -module.exports = GridFSBucket; - -/** - * Constructor for a streaming GridFS interface - * @class - * @param {Db} db A db handle - * @param {object} [options] Optional settings. - * @param {string} [options.bucketName="fs"] The 'files' and 'chunks' collections will be prefixed with the bucket name followed by a dot. - * @param {number} [options.chunkSizeBytes=255 * 1024] Number of bytes stored in each chunk. Defaults to 255KB - * @param {object} [options.writeConcern] Optional write concern to be passed to write operations, for instance `{ w: 1 }` - * @param {object} [options.readPreference] Optional read preference to be passed to read operations - * @fires GridFSBucketWriteStream#index - * @return {GridFSBucket} - */ - -function GridFSBucket(db, options) { - Emitter.apply(this); - this.setMaxListeners(0); - - if (options && typeof options === 'object') { - options = shallowClone(options); - var keys = Object.keys(DEFAULT_GRIDFS_BUCKET_OPTIONS); - for (var i = 0; i < keys.length; ++i) { - if (!options[keys[i]]) { - options[keys[i]] = DEFAULT_GRIDFS_BUCKET_OPTIONS[keys[i]]; - } - } - } else { - options = DEFAULT_GRIDFS_BUCKET_OPTIONS; - } - - this.s = { - db: db, - options: options, - _chunksCollection: db.collection(options.bucketName + '.chunks'), - _filesCollection: db.collection(options.bucketName + '.files'), - checkedIndexes: false, - calledOpenUploadStream: false, - promiseLibrary: db.s.promiseLibrary || Promise - }; -} - -util.inherits(GridFSBucket, Emitter); - -/** - * When the first call to openUploadStream is made, the upload stream will - * check to see if it needs to create the proper indexes on the chunks and - * files collections. This event is fired either when 1) it determines that - * no index creation is necessary, 2) when it successfully creates the - * necessary indexes. - * - * @event GridFSBucket#index - * @type {Error} - */ - -/** - * Returns a writable stream (GridFSBucketWriteStream) for writing - * buffers to GridFS. The stream's 'id' property contains the resulting - * file's id. - * @method - * @param {string} filename The value of the 'filename' key in the files doc - * @param {object} [options] Optional settings. - * @param {number} [options.chunkSizeBytes] Optional overwrite this bucket's chunkSizeBytes for this file - * @param {object} [options.metadata] Optional object to store in the file document's `metadata` field - * @param {string} [options.contentType] Optional string to store in the file document's `contentType` field - * @param {array} [options.aliases] Optional array of strings to store in the file document's `aliases` field - * @param {boolean} [options.disableMD5=false] If true, disables adding an md5 field to file data - * @return {GridFSBucketWriteStream} - */ - -GridFSBucket.prototype.openUploadStream = function(filename, options) { - if (options) { - options = shallowClone(options); - } else { - options = {}; - } - if (!options.chunkSizeBytes) { - options.chunkSizeBytes = this.s.options.chunkSizeBytes; - } - return new GridFSBucketWriteStream(this, filename, options); -}; - -/** - * Returns a writable stream (GridFSBucketWriteStream) for writing - * buffers to GridFS for a custom file id. The stream's 'id' property contains the resulting - * file's id. - * @method - * @param {string|number|object} id A custom id used to identify the file - * @param {string} filename The value of the 'filename' key in the files doc - * @param {object} [options] Optional settings. - * @param {number} [options.chunkSizeBytes] Optional overwrite this bucket's chunkSizeBytes for this file - * @param {object} [options.metadata] Optional object to store in the file document's `metadata` field - * @param {string} [options.contentType] Optional string to store in the file document's `contentType` field - * @param {array} [options.aliases] Optional array of strings to store in the file document's `aliases` field - * @param {boolean} [options.disableMD5=false] If true, disables adding an md5 field to file data - * @return {GridFSBucketWriteStream} - */ - -GridFSBucket.prototype.openUploadStreamWithId = function(id, filename, options) { - if (options) { - options = shallowClone(options); - } else { - options = {}; - } - - if (!options.chunkSizeBytes) { - options.chunkSizeBytes = this.s.options.chunkSizeBytes; - } - - options.id = id; - - return new GridFSBucketWriteStream(this, filename, options); -}; - -/** - * Returns a readable stream (GridFSBucketReadStream) for streaming file - * data from GridFS. - * @method - * @param {ObjectId} id The id of the file doc - * @param {Object} [options] Optional settings. - * @param {Number} [options.start] Optional 0-based offset in bytes to start streaming from - * @param {Number} [options.end] Optional 0-based offset in bytes to stop streaming before - * @return {GridFSBucketReadStream} - */ - -GridFSBucket.prototype.openDownloadStream = function(id, options) { - var filter = { _id: id }; - options = { - start: options && options.start, - end: options && options.end - }; - - return new GridFSBucketReadStream( - this.s._chunksCollection, - this.s._filesCollection, - this.s.options.readPreference, - filter, - options - ); -}; - -/** - * Deletes a file with the given id - * @method - * @param {ObjectId} id The id of the file doc - * @param {GridFSBucket~errorCallback} [callback] - */ - -GridFSBucket.prototype.delete = function(id, callback) { - return executeLegacyOperation(this.s.db.s.topology, _delete, [this, id, callback], { - skipSessions: true - }); -}; - -/** - * @ignore - */ - -function _delete(_this, id, callback) { - _this.s._filesCollection.deleteOne({ _id: id }, function(error, res) { - if (error) { - return callback(error); - } - - _this.s._chunksCollection.deleteMany({ files_id: id }, function(error) { - if (error) { - return callback(error); - } - - // Delete orphaned chunks before returning FileNotFound - if (!res.result.n) { - var errmsg = 'FileNotFound: no file with id ' + id + ' found'; - return callback(new Error(errmsg)); - } - - callback(); - }); - }); -} - -/** - * Convenience wrapper around find on the files collection - * @method - * @param {Object} filter - * @param {Object} [options] Optional settings for cursor - * @param {number} [options.batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/find|find command documentation}. - * @param {number} [options.limit] Optional limit for cursor - * @param {number} [options.maxTimeMS] Optional maxTimeMS for cursor - * @param {boolean} [options.noCursorTimeout] Optionally set cursor's `noCursorTimeout` flag - * @param {number} [options.skip] Optional skip for cursor - * @param {object} [options.sort] Optional sort for cursor - * @return {Cursor} - */ - -GridFSBucket.prototype.find = function(filter, options) { - filter = filter || {}; - options = options || {}; - - var cursor = this.s._filesCollection.find(filter); - - if (options.batchSize != null) { - cursor.batchSize(options.batchSize); - } - if (options.limit != null) { - cursor.limit(options.limit); - } - if (options.maxTimeMS != null) { - cursor.maxTimeMS(options.maxTimeMS); - } - if (options.noCursorTimeout != null) { - cursor.addCursorFlag('noCursorTimeout', options.noCursorTimeout); - } - if (options.skip != null) { - cursor.skip(options.skip); - } - if (options.sort != null) { - cursor.sort(options.sort); - } - - return cursor; -}; - -/** - * Returns a readable stream (GridFSBucketReadStream) for streaming the - * file with the given name from GridFS. If there are multiple files with - * the same name, this will stream the most recent file with the given name - * (as determined by the `uploadDate` field). You can set the `revision` - * option to change this behavior. - * @method - * @param {String} filename The name of the file to stream - * @param {Object} [options] Optional settings - * @param {number} [options.revision=-1] The revision number relative to the oldest file with the given filename. 0 gets you the oldest file, 1 gets you the 2nd oldest, -1 gets you the newest. - * @param {Number} [options.start] Optional 0-based offset in bytes to start streaming from - * @param {Number} [options.end] Optional 0-based offset in bytes to stop streaming before - * @return {GridFSBucketReadStream} - */ - -GridFSBucket.prototype.openDownloadStreamByName = function(filename, options) { - var sort = { uploadDate: -1 }; - var skip = null; - if (options && options.revision != null) { - if (options.revision >= 0) { - sort = { uploadDate: 1 }; - skip = options.revision; - } else { - skip = -options.revision - 1; - } - } - - var filter = { filename: filename }; - options = { - sort: sort, - skip: skip, - start: options && options.start, - end: options && options.end - }; - return new GridFSBucketReadStream( - this.s._chunksCollection, - this.s._filesCollection, - this.s.options.readPreference, - filter, - options - ); -}; - -/** - * Renames the file with the given _id to the given string - * @method - * @param {ObjectId} id the id of the file to rename - * @param {String} filename new name for the file - * @param {GridFSBucket~errorCallback} [callback] - */ - -GridFSBucket.prototype.rename = function(id, filename, callback) { - return executeLegacyOperation(this.s.db.s.topology, _rename, [this, id, filename, callback], { - skipSessions: true - }); -}; - -/** - * @ignore - */ - -function _rename(_this, id, filename, callback) { - var filter = { _id: id }; - var update = { $set: { filename: filename } }; - _this.s._filesCollection.updateOne(filter, update, function(error, res) { - if (error) { - return callback(error); - } - if (!res.result.n) { - return callback(toError('File with id ' + id + ' not found')); - } - callback(); - }); -} - -/** - * Removes this bucket's files collection, followed by its chunks collection. - * @method - * @param {GridFSBucket~errorCallback} [callback] - */ - -GridFSBucket.prototype.drop = function(callback) { - return executeLegacyOperation(this.s.db.s.topology, _drop, [this, callback], { - skipSessions: true - }); -}; - -/** - * Return the db logger - * @method - * @return {Logger} return the db logger - * @ignore - */ -GridFSBucket.prototype.getLogger = function() { - return this.s.db.s.logger; -}; - -/** - * @ignore - */ - -function _drop(_this, callback) { - _this.s._filesCollection.drop(function(error) { - if (error) { - return callback(error); - } - _this.s._chunksCollection.drop(function(error) { - if (error) { - return callback(error); - } - - return callback(); - }); - }); -} - -/** - * Callback format for all GridFSBucket methods that can accept a callback. - * @callback GridFSBucket~errorCallback - * @param {MongoError} error An error instance representing any errors that occurred - */ diff --git a/scripts/2.5/node_modules/mongodb/lib/gridfs-stream/upload.js b/scripts/2.5/node_modules/mongodb/lib/gridfs-stream/upload.js deleted file mode 100644 index 3733f2cb..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/gridfs-stream/upload.js +++ /dev/null @@ -1,538 +0,0 @@ -'use strict'; - -var core = require('../core'); -var crypto = require('crypto'); -var stream = require('stream'); -var util = require('util'); -var Buffer = require('safe-buffer').Buffer; - -var ERROR_NAMESPACE_NOT_FOUND = 26; - -module.exports = GridFSBucketWriteStream; - -/** - * A writable stream that enables you to write buffers to GridFS. - * - * Do not instantiate this class directly. Use `openUploadStream()` instead. - * - * @class - * @param {GridFSBucket} bucket Handle for this stream's corresponding bucket - * @param {string} filename The value of the 'filename' key in the files doc - * @param {object} [options] Optional settings. - * @param {string|number|object} [options.id] Custom file id for the GridFS file. - * @param {number} [options.chunkSizeBytes] The chunk size to use, in bytes - * @param {number} [options.w] The write concern - * @param {number} [options.wtimeout] The write concern timeout - * @param {number} [options.j] The journal write concern - * @param {boolean} [options.disableMD5=false] If true, disables adding an md5 field to file data - * @fires GridFSBucketWriteStream#error - * @fires GridFSBucketWriteStream#finish - * @return {GridFSBucketWriteStream} a GridFSBucketWriteStream instance. - */ - -function GridFSBucketWriteStream(bucket, filename, options) { - options = options || {}; - this.bucket = bucket; - this.chunks = bucket.s._chunksCollection; - this.filename = filename; - this.files = bucket.s._filesCollection; - this.options = options; - // Signals the write is all done - this.done = false; - - this.id = options.id ? options.id : core.BSON.ObjectId(); - this.chunkSizeBytes = this.options.chunkSizeBytes; - this.bufToStore = Buffer.alloc(this.chunkSizeBytes); - this.length = 0; - this.md5 = !options.disableMD5 && crypto.createHash('md5'); - this.n = 0; - this.pos = 0; - this.state = { - streamEnd: false, - outstandingRequests: 0, - errored: false, - aborted: false, - promiseLibrary: this.bucket.s.promiseLibrary - }; - - if (!this.bucket.s.calledOpenUploadStream) { - this.bucket.s.calledOpenUploadStream = true; - - var _this = this; - checkIndexes(this, function() { - _this.bucket.s.checkedIndexes = true; - _this.bucket.emit('index'); - }); - } -} - -util.inherits(GridFSBucketWriteStream, stream.Writable); - -/** - * An error occurred - * - * @event GridFSBucketWriteStream#error - * @type {Error} - */ - -/** - * `end()` was called and the write stream successfully wrote the file - * metadata and all the chunks to MongoDB. - * - * @event GridFSBucketWriteStream#finish - * @type {object} - */ - -/** - * Write a buffer to the stream. - * - * @method - * @param {Buffer} chunk Buffer to write - * @param {String} encoding Optional encoding for the buffer - * @param {Function} callback Function to call when the chunk was added to the buffer, or if the entire chunk was persisted to MongoDB if this chunk caused a flush. - * @return {Boolean} False if this write required flushing a chunk to MongoDB. True otherwise. - */ - -GridFSBucketWriteStream.prototype.write = function(chunk, encoding, callback) { - var _this = this; - return waitForIndexes(this, function() { - return doWrite(_this, chunk, encoding, callback); - }); -}; - -/** - * Places this write stream into an aborted state (all future writes fail) - * and deletes all chunks that have already been written. - * - * @method - * @param {GridFSBucket~errorCallback} callback called when chunks are successfully removed or error occurred - * @return {Promise} if no callback specified - */ - -GridFSBucketWriteStream.prototype.abort = function(callback) { - if (this.state.streamEnd) { - var error = new Error('Cannot abort a stream that has already completed'); - if (typeof callback === 'function') { - return callback(error); - } - return this.state.promiseLibrary.reject(error); - } - if (this.state.aborted) { - error = new Error('Cannot call abort() on a stream twice'); - if (typeof callback === 'function') { - return callback(error); - } - return this.state.promiseLibrary.reject(error); - } - this.state.aborted = true; - this.chunks.deleteMany({ files_id: this.id }, function(error) { - if (typeof callback === 'function') callback(error); - }); -}; - -/** - * Tells the stream that no more data will be coming in. The stream will - * persist the remaining data to MongoDB, write the files document, and - * then emit a 'finish' event. - * - * @method - * @param {Buffer} chunk Buffer to write - * @param {String} encoding Optional encoding for the buffer - * @param {Function} callback Function to call when all files and chunks have been persisted to MongoDB - */ - -GridFSBucketWriteStream.prototype.end = function(chunk, encoding, callback) { - var _this = this; - if (typeof chunk === 'function') { - (callback = chunk), (chunk = null), (encoding = null); - } else if (typeof encoding === 'function') { - (callback = encoding), (encoding = null); - } - - if (checkAborted(this, callback)) { - return; - } - this.state.streamEnd = true; - - if (callback) { - this.once('finish', function(result) { - callback(null, result); - }); - } - - if (!chunk) { - waitForIndexes(this, function() { - writeRemnant(_this); - }); - return; - } - - this.write(chunk, encoding, function() { - writeRemnant(_this); - }); -}; - -/** - * @ignore - */ - -function __handleError(_this, error, callback) { - if (_this.state.errored) { - return; - } - _this.state.errored = true; - if (callback) { - return callback(error); - } - _this.emit('error', error); -} - -/** - * @ignore - */ - -function createChunkDoc(filesId, n, data) { - return { - _id: core.BSON.ObjectId(), - files_id: filesId, - n: n, - data: data - }; -} - -/** - * @ignore - */ - -function checkChunksIndex(_this, callback) { - _this.chunks.listIndexes().toArray(function(error, indexes) { - if (error) { - // Collection doesn't exist so create index - if (error.code === ERROR_NAMESPACE_NOT_FOUND) { - var index = { files_id: 1, n: 1 }; - _this.chunks.createIndex(index, { background: false, unique: true }, function(error) { - if (error) { - return callback(error); - } - - callback(); - }); - return; - } - return callback(error); - } - - var hasChunksIndex = false; - indexes.forEach(function(index) { - if (index.key) { - var keys = Object.keys(index.key); - if (keys.length === 2 && index.key.files_id === 1 && index.key.n === 1) { - hasChunksIndex = true; - } - } - }); - - if (hasChunksIndex) { - callback(); - } else { - index = { files_id: 1, n: 1 }; - var indexOptions = getWriteOptions(_this); - - indexOptions.background = false; - indexOptions.unique = true; - - _this.chunks.createIndex(index, indexOptions, function(error) { - if (error) { - return callback(error); - } - - callback(); - }); - } - }); -} - -/** - * @ignore - */ - -function checkDone(_this, callback) { - if (_this.done) return true; - if (_this.state.streamEnd && _this.state.outstandingRequests === 0 && !_this.state.errored) { - // Set done so we dont' trigger duplicate createFilesDoc - _this.done = true; - // Create a new files doc - var filesDoc = createFilesDoc( - _this.id, - _this.length, - _this.chunkSizeBytes, - _this.md5 && _this.md5.digest('hex'), - _this.filename, - _this.options.contentType, - _this.options.aliases, - _this.options.metadata - ); - - if (checkAborted(_this, callback)) { - return false; - } - - _this.files.insertOne(filesDoc, getWriteOptions(_this), function(error) { - if (error) { - return __handleError(_this, error, callback); - } - _this.emit('finish', filesDoc); - }); - - return true; - } - - return false; -} - -/** - * @ignore - */ - -function checkIndexes(_this, callback) { - _this.files.findOne({}, { _id: 1 }, function(error, doc) { - if (error) { - return callback(error); - } - if (doc) { - return callback(); - } - - _this.files.listIndexes().toArray(function(error, indexes) { - if (error) { - // Collection doesn't exist so create index - if (error.code === ERROR_NAMESPACE_NOT_FOUND) { - var index = { filename: 1, uploadDate: 1 }; - _this.files.createIndex(index, { background: false }, function(error) { - if (error) { - return callback(error); - } - - checkChunksIndex(_this, callback); - }); - return; - } - return callback(error); - } - - var hasFileIndex = false; - indexes.forEach(function(index) { - var keys = Object.keys(index.key); - if (keys.length === 2 && index.key.filename === 1 && index.key.uploadDate === 1) { - hasFileIndex = true; - } - }); - - if (hasFileIndex) { - checkChunksIndex(_this, callback); - } else { - index = { filename: 1, uploadDate: 1 }; - - var indexOptions = getWriteOptions(_this); - - indexOptions.background = false; - - _this.files.createIndex(index, indexOptions, function(error) { - if (error) { - return callback(error); - } - - checkChunksIndex(_this, callback); - }); - } - }); - }); -} - -/** - * @ignore - */ - -function createFilesDoc(_id, length, chunkSize, md5, filename, contentType, aliases, metadata) { - var ret = { - _id: _id, - length: length, - chunkSize: chunkSize, - uploadDate: new Date(), - filename: filename - }; - - if (md5) { - ret.md5 = md5; - } - - if (contentType) { - ret.contentType = contentType; - } - - if (aliases) { - ret.aliases = aliases; - } - - if (metadata) { - ret.metadata = metadata; - } - - return ret; -} - -/** - * @ignore - */ - -function doWrite(_this, chunk, encoding, callback) { - if (checkAborted(_this, callback)) { - return false; - } - - var inputBuf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding); - - _this.length += inputBuf.length; - - // Input is small enough to fit in our buffer - if (_this.pos + inputBuf.length < _this.chunkSizeBytes) { - inputBuf.copy(_this.bufToStore, _this.pos); - _this.pos += inputBuf.length; - - callback && callback(); - - // Note that we reverse the typical semantics of write's return value - // to be compatible with node's `.pipe()` function. - // True means client can keep writing. - return true; - } - - // Otherwise, buffer is too big for current chunk, so we need to flush - // to MongoDB. - var inputBufRemaining = inputBuf.length; - var spaceRemaining = _this.chunkSizeBytes - _this.pos; - var numToCopy = Math.min(spaceRemaining, inputBuf.length); - var outstandingRequests = 0; - while (inputBufRemaining > 0) { - var inputBufPos = inputBuf.length - inputBufRemaining; - inputBuf.copy(_this.bufToStore, _this.pos, inputBufPos, inputBufPos + numToCopy); - _this.pos += numToCopy; - spaceRemaining -= numToCopy; - if (spaceRemaining === 0) { - if (_this.md5) { - _this.md5.update(_this.bufToStore); - } - var doc = createChunkDoc(_this.id, _this.n, _this.bufToStore); - ++_this.state.outstandingRequests; - ++outstandingRequests; - - if (checkAborted(_this, callback)) { - return false; - } - - _this.chunks.insertOne(doc, getWriteOptions(_this), function(error) { - if (error) { - return __handleError(_this, error); - } - --_this.state.outstandingRequests; - --outstandingRequests; - - if (!outstandingRequests) { - _this.emit('drain', doc); - callback && callback(); - checkDone(_this); - } - }); - - spaceRemaining = _this.chunkSizeBytes; - _this.pos = 0; - ++_this.n; - } - inputBufRemaining -= numToCopy; - numToCopy = Math.min(spaceRemaining, inputBufRemaining); - } - - // Note that we reverse the typical semantics of write's return value - // to be compatible with node's `.pipe()` function. - // False means the client should wait for the 'drain' event. - return false; -} - -/** - * @ignore - */ - -function getWriteOptions(_this) { - var obj = {}; - if (_this.options.writeConcern) { - obj.w = _this.options.writeConcern.w; - obj.wtimeout = _this.options.writeConcern.wtimeout; - obj.j = _this.options.writeConcern.j; - } - return obj; -} - -/** - * @ignore - */ - -function waitForIndexes(_this, callback) { - if (_this.bucket.s.checkedIndexes) { - return callback(false); - } - - _this.bucket.once('index', function() { - callback(true); - }); - - return true; -} - -/** - * @ignore - */ - -function writeRemnant(_this, callback) { - // Buffer is empty, so don't bother to insert - if (_this.pos === 0) { - return checkDone(_this, callback); - } - - ++_this.state.outstandingRequests; - - // Create a new buffer to make sure the buffer isn't bigger than it needs - // to be. - var remnant = Buffer.alloc(_this.pos); - _this.bufToStore.copy(remnant, 0, 0, _this.pos); - if (_this.md5) { - _this.md5.update(remnant); - } - var doc = createChunkDoc(_this.id, _this.n, remnant); - - // If the stream was aborted, do not write remnant - if (checkAborted(_this, callback)) { - return false; - } - - _this.chunks.insertOne(doc, getWriteOptions(_this), function(error) { - if (error) { - return __handleError(_this, error); - } - --_this.state.outstandingRequests; - checkDone(_this); - }); -} - -/** - * @ignore - */ - -function checkAborted(_this, callback) { - if (_this.state.aborted) { - if (typeof callback === 'function') { - callback(new Error('this stream has been aborted')); - } - return true; - } - return false; -} diff --git a/scripts/2.5/node_modules/mongodb/lib/gridfs/chunk.js b/scripts/2.5/node_modules/mongodb/lib/gridfs/chunk.js deleted file mode 100644 index d276d720..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/gridfs/chunk.js +++ /dev/null @@ -1,236 +0,0 @@ -'use strict'; - -var Binary = require('../core').BSON.Binary, - ObjectID = require('../core').BSON.ObjectID; - -var Buffer = require('safe-buffer').Buffer; - -/** - * Class for representing a single chunk in GridFS. - * - * @class - * - * @param file {GridStore} The {@link GridStore} object holding this chunk. - * @param mongoObject {object} The mongo object representation of this chunk. - * - * @throws Error when the type of data field for {@link mongoObject} is not - * supported. Currently supported types for data field are instances of - * {@link String}, {@link Array}, {@link Binary} and {@link Binary} - * from the bson module - * - * @see Chunk#buildMongoObject - */ -var Chunk = function(file, mongoObject, writeConcern) { - if (!(this instanceof Chunk)) return new Chunk(file, mongoObject); - - this.file = file; - var mongoObjectFinal = mongoObject == null ? {} : mongoObject; - this.writeConcern = writeConcern || { w: 1 }; - this.objectId = mongoObjectFinal._id == null ? new ObjectID() : mongoObjectFinal._id; - this.chunkNumber = mongoObjectFinal.n == null ? 0 : mongoObjectFinal.n; - this.data = new Binary(); - - if (typeof mongoObjectFinal.data === 'string') { - var buffer = Buffer.alloc(mongoObjectFinal.data.length); - buffer.write(mongoObjectFinal.data, 0, mongoObjectFinal.data.length, 'binary'); - this.data = new Binary(buffer); - } else if (Array.isArray(mongoObjectFinal.data)) { - buffer = Buffer.alloc(mongoObjectFinal.data.length); - var data = mongoObjectFinal.data.join(''); - buffer.write(data, 0, data.length, 'binary'); - this.data = new Binary(buffer); - } else if (mongoObjectFinal.data && mongoObjectFinal.data._bsontype === 'Binary') { - this.data = mongoObjectFinal.data; - } else if (!Buffer.isBuffer(mongoObjectFinal.data) && !(mongoObjectFinal.data == null)) { - throw Error('Illegal chunk format'); - } - - // Update position - this.internalPosition = 0; -}; - -/** - * Writes a data to this object and advance the read/write head. - * - * @param data {string} the data to write - * @param callback {function(*, GridStore)} This will be called after executing - * this method. The first parameter will contain null and the second one - * will contain a reference to this object. - */ -Chunk.prototype.write = function(data, callback) { - this.data.write(data, this.internalPosition, data.length, 'binary'); - this.internalPosition = this.data.length(); - if (callback != null) return callback(null, this); - return this; -}; - -/** - * Reads data and advances the read/write head. - * - * @param length {number} The length of data to read. - * - * @return {string} The data read if the given length will not exceed the end of - * the chunk. Returns an empty String otherwise. - */ -Chunk.prototype.read = function(length) { - // Default to full read if no index defined - length = length == null || length === 0 ? this.length() : length; - - if (this.length() - this.internalPosition + 1 >= length) { - var data = this.data.read(this.internalPosition, length); - this.internalPosition = this.internalPosition + length; - return data; - } else { - return ''; - } -}; - -Chunk.prototype.readSlice = function(length) { - if (this.length() - this.internalPosition >= length) { - var data = null; - if (this.data.buffer != null) { - //Pure BSON - data = this.data.buffer.slice(this.internalPosition, this.internalPosition + length); - } else { - //Native BSON - data = Buffer.alloc(length); - length = this.data.readInto(data, this.internalPosition); - } - this.internalPosition = this.internalPosition + length; - return data; - } else { - return null; - } -}; - -/** - * Checks if the read/write head is at the end. - * - * @return {boolean} Whether the read/write head has reached the end of this - * chunk. - */ -Chunk.prototype.eof = function() { - return this.internalPosition === this.length() ? true : false; -}; - -/** - * Reads one character from the data of this chunk and advances the read/write - * head. - * - * @return {string} a single character data read if the the read/write head is - * not at the end of the chunk. Returns an empty String otherwise. - */ -Chunk.prototype.getc = function() { - return this.read(1); -}; - -/** - * Clears the contents of the data in this chunk and resets the read/write head - * to the initial position. - */ -Chunk.prototype.rewind = function() { - this.internalPosition = 0; - this.data = new Binary(); -}; - -/** - * Saves this chunk to the database. Also overwrites existing entries having the - * same id as this chunk. - * - * @param callback {function(*, GridStore)} This will be called after executing - * this method. The first parameter will contain null and the second one - * will contain a reference to this object. - */ -Chunk.prototype.save = function(options, callback) { - var self = this; - if (typeof options === 'function') { - callback = options; - options = {}; - } - - self.file.chunkCollection(function(err, collection) { - if (err) return callback(err); - - // Merge the options - var writeOptions = { upsert: true }; - for (var name in options) writeOptions[name] = options[name]; - for (name in self.writeConcern) writeOptions[name] = self.writeConcern[name]; - - if (self.data.length() > 0) { - self.buildMongoObject(function(mongoObject) { - var options = { forceServerObjectId: true }; - for (var name in self.writeConcern) { - options[name] = self.writeConcern[name]; - } - - collection.replaceOne({ _id: self.objectId }, mongoObject, writeOptions, function(err) { - callback(err, self); - }); - }); - } else { - callback(null, self); - } - // }); - }); -}; - -/** - * Creates a mongoDB object representation of this chunk. - * - * @param callback {function(Object)} This will be called after executing this - * method. The object will be passed to the first parameter and will have - * the structure: - * - *

- *        {
- *          '_id' : , // {number} id for this chunk
- *          'files_id' : , // {number} foreign key to the file collection
- *          'n' : , // {number} chunk number
- *          'data' : , // {bson#Binary} the chunk data itself
- *        }
- *        
- * - * @see MongoDB GridFS Chunk Object Structure - */ -Chunk.prototype.buildMongoObject = function(callback) { - var mongoObject = { - files_id: this.file.fileId, - n: this.chunkNumber, - data: this.data - }; - // If we are saving using a specific ObjectId - if (this.objectId != null) mongoObject._id = this.objectId; - - callback(mongoObject); -}; - -/** - * @return {number} the length of the data - */ -Chunk.prototype.length = function() { - return this.data.length(); -}; - -/** - * The position of the read/write head - * @name position - * @lends Chunk# - * @field - */ -Object.defineProperty(Chunk.prototype, 'position', { - enumerable: true, - get: function() { - return this.internalPosition; - }, - set: function(value) { - this.internalPosition = value; - } -}); - -/** - * The default chunk size - * @constant - */ -Chunk.DEFAULT_CHUNK_SIZE = 1024 * 255; - -module.exports = Chunk; diff --git a/scripts/2.5/node_modules/mongodb/lib/gridfs/grid_store.js b/scripts/2.5/node_modules/mongodb/lib/gridfs/grid_store.js deleted file mode 100644 index c8ccb850..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/gridfs/grid_store.js +++ /dev/null @@ -1,1913 +0,0 @@ -'use strict'; - -/** - * @fileOverview GridFS is a tool for MongoDB to store files to the database. - * Because of the restrictions of the object size the database can hold, a - * facility to split a file into several chunks is needed. The {@link GridStore} - * class offers a simplified api to interact with files while managing the - * chunks of split files behind the scenes. More information about GridFS can be - * found here. - * - * @example - * const MongoClient = require('mongodb').MongoClient; - * const GridStore = require('mongodb').GridStore; - * const ObjectID = require('mongodb').ObjectID; - * const test = require('assert'); - * // Connection url - * const url = 'mongodb://localhost:27017'; - * // Database Name - * const dbName = 'test'; - * // Connect using MongoClient - * MongoClient.connect(url, function(err, client) { - * const db = client.db(dbName); - * const gridStore = new GridStore(db, null, "w"); - * gridStore.open(function(err, gridStore) { - * gridStore.write("hello world!", function(err, gridStore) { - * gridStore.close(function(err, result) { - * // Let's read the file using object Id - * GridStore.read(db, result._id, function(err, data) { - * test.equal('hello world!', data); - * client.close(); - * test.done(); - * }); - * }); - * }); - * }); - * }); - */ -const Chunk = require('./chunk'); -const ObjectID = require('../core').BSON.ObjectID; -const ReadPreference = require('../core').ReadPreference; -const Buffer = require('safe-buffer').Buffer; -const fs = require('fs'); -const f = require('util').format; -const util = require('util'); -const MongoError = require('../core').MongoError; -const inherits = util.inherits; -const Duplex = require('stream').Duplex; -const shallowClone = require('../utils').shallowClone; -const executeLegacyOperation = require('../utils').executeLegacyOperation; -const deprecate = require('util').deprecate; - -var REFERENCE_BY_FILENAME = 0, - REFERENCE_BY_ID = 1; - -const deprecationFn = deprecate(() => {}, -'GridStore is deprecated, and will be removed in a future version. Please use GridFSBucket instead'); - -/** - * Namespace provided by the core module - * @external Duplex - */ - -/** - * Create a new GridStore instance - * - * Modes - * - **"r"** - read only. This is the default mode. - * - **"w"** - write in truncate mode. Existing data will be overwritten. - * - * @class - * @param {Db} db A database instance to interact with. - * @param {object} [id] optional unique id for this file - * @param {string} [filename] optional filename for this file, no unique constrain on the field - * @param {string} mode set the mode for this file. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.fsync=false] Specify a file sync write concern. - * @param {string} [options.root] Root collection to use. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**. - * @param {string} [options.content_type] MIME type of the file. Defaults to **{GridStore.DEFAULT_CONTENT_TYPE}**. - * @param {number} [options.chunk_size=261120] Size for the chunk. Defaults to **{Chunk.DEFAULT_CHUNK_SIZE}**. - * @param {object} [options.metadata] Arbitrary data the user wants to store. - * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @property {number} chunkSize Get the gridstore chunk size. - * @property {number} md5 The md5 checksum for this file. - * @property {number} chunkNumber The current chunk number the gridstore has materialized into memory - * @return {GridStore} a GridStore instance. - * @deprecated Use GridFSBucket API instead - */ -var GridStore = function GridStore(db, id, filename, mode, options) { - deprecationFn(); - if (!(this instanceof GridStore)) return new GridStore(db, id, filename, mode, options); - this.db = db; - - // Handle options - if (typeof options === 'undefined') options = {}; - // Handle mode - if (typeof mode === 'undefined') { - mode = filename; - filename = undefined; - } else if (typeof mode === 'object') { - options = mode; - mode = filename; - filename = undefined; - } - - if (id && id._bsontype === 'ObjectID') { - this.referenceBy = REFERENCE_BY_ID; - this.fileId = id; - this.filename = filename; - } else if (typeof filename === 'undefined') { - this.referenceBy = REFERENCE_BY_FILENAME; - this.filename = id; - if (mode.indexOf('w') != null) { - this.fileId = new ObjectID(); - } - } else { - this.referenceBy = REFERENCE_BY_ID; - this.fileId = id; - this.filename = filename; - } - - // Set up the rest - this.mode = mode == null ? 'r' : mode; - this.options = options || {}; - - // Opened - this.isOpen = false; - - // Set the root if overridden - this.root = - this.options['root'] == null ? GridStore.DEFAULT_ROOT_COLLECTION : this.options['root']; - this.position = 0; - this.readPreference = - this.options.readPreference || db.options.readPreference || ReadPreference.primary; - this.writeConcern = _getWriteConcern(db, this.options); - // Set default chunk size - this.internalChunkSize = - this.options['chunkSize'] == null ? Chunk.DEFAULT_CHUNK_SIZE : this.options['chunkSize']; - - // Get the promiseLibrary - var promiseLibrary = this.options.promiseLibrary || Promise; - - // Set the promiseLibrary - this.promiseLibrary = promiseLibrary; - - Object.defineProperty(this, 'chunkSize', { - enumerable: true, - get: function() { - return this.internalChunkSize; - }, - set: function(value) { - if (!(this.mode[0] === 'w' && this.position === 0 && this.uploadDate == null)) { - this.internalChunkSize = this.internalChunkSize; - } else { - this.internalChunkSize = value; - } - } - }); - - Object.defineProperty(this, 'md5', { - enumerable: true, - get: function() { - return this.internalMd5; - } - }); - - Object.defineProperty(this, 'chunkNumber', { - enumerable: true, - get: function() { - return this.currentChunk && this.currentChunk.chunkNumber - ? this.currentChunk.chunkNumber - : null; - } - }); -}; - -/** - * The callback format for the Gridstore.open method - * @callback GridStore~openCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {GridStore} gridStore The GridStore instance if the open method was successful. - */ - -/** - * Opens the file from the database and initialize this object. Also creates a - * new one if file does not exist. - * - * @method - * @param {object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {GridStore~openCallback} [callback] this will be called after executing this method - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.open = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - if (this.mode !== 'w' && this.mode !== 'w+' && this.mode !== 'r') { - throw MongoError.create({ message: 'Illegal mode ' + this.mode, driver: true }); - } - - return executeLegacyOperation(this.db.s.topology, open, [this, options, callback], { - skipSessions: true - }); -}; - -var open = function(self, options, callback) { - // Get the write concern - var writeConcern = _getWriteConcern(self.db, self.options); - - // If we are writing we need to ensure we have the right indexes for md5's - if (self.mode === 'w' || self.mode === 'w+') { - // Get files collection - var collection = self.collection(); - // Put index on filename - collection.ensureIndex([['filename', 1]], writeConcern, function() { - // Get chunk collection - var chunkCollection = self.chunkCollection(); - // Make an unique index for compatibility with mongo-cxx-driver:legacy - var chunkIndexOptions = shallowClone(writeConcern); - chunkIndexOptions.unique = true; - // Ensure index on chunk collection - chunkCollection.ensureIndex([['files_id', 1], ['n', 1]], chunkIndexOptions, function() { - // Open the connection - _open(self, writeConcern, function(err, r) { - if (err) return callback(err); - self.isOpen = true; - callback(err, r); - }); - }); - }); - } else { - // Open the gridstore - _open(self, writeConcern, function(err, r) { - if (err) return callback(err); - self.isOpen = true; - callback(err, r); - }); - } -}; - -/** - * Verify if the file is at EOF. - * - * @method - * @return {boolean} true if the read/write head is at the end of this file. - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.eof = function() { - return this.position === this.length ? true : false; -}; - -/** - * The callback result format. - * @callback GridStore~resultCallback - * @param {object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {MongoError} error An error instance representing the error during the execution. - * @param {object} result The result from the callback. - */ - -/** - * Retrieves a single character from this file. - * - * @method - * @param {GridStore~resultCallback} [callback] this gets called after this method is executed. Passes null to the first parameter and the character read to the second or null to the second if the read/write head is at the end of the file. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.getc = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - return executeLegacyOperation(this.db.s.topology, getc, [this, options, callback], { - skipSessions: true - }); -}; - -var getc = function(self, options, callback) { - if (self.eof()) { - callback(null, null); - } else if (self.currentChunk.eof()) { - nthChunk(self, self.currentChunk.chunkNumber + 1, function(err, chunk) { - self.currentChunk = chunk; - self.position = self.position + 1; - callback(err, self.currentChunk.getc()); - }); - } else { - self.position = self.position + 1; - callback(null, self.currentChunk.getc()); - } -}; - -/** - * Writes a string to the file with a newline character appended at the end if - * the given string does not have one. - * - * @method - * @param {string} string the string to write. - * @param {object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.puts = function(string, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - var finalString = string.match(/\n$/) == null ? string + '\n' : string; - return executeLegacyOperation( - this.db.s.topology, - this.write.bind(this), - [finalString, options, callback], - { skipSessions: true } - ); -}; - -/** - * Return a modified Readable stream including a possible transform method. - * - * @method - * @return {GridStoreStream} - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.stream = function() { - return new GridStoreStream(this); -}; - -/** - * Writes some data. This method will work properly only if initialized with mode "w" or "w+". - * - * @method - * @param {(string|Buffer)} data the data to write. - * @param {boolean} [close] closes this file after writing if set to true. - * @param {object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.write = function write(data, close, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - return executeLegacyOperation( - this.db.s.topology, - _writeNormal, - [this, data, close, options, callback], - { skipSessions: true } - ); -}; - -/** - * Handles the destroy part of a stream - * - * @method - * @result {null} - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.destroy = function destroy() { - // close and do not emit any more events. queued data is not sent. - if (!this.writable) return; - this.readable = false; - if (this.writable) { - this.writable = false; - this._q.length = 0; - this.emit('close'); - } -}; - -/** - * Stores a file from the file system to the GridFS database. - * - * @method - * @param {(string|Buffer|FileHandle)} file the file to store. - * @param {object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.writeFile = function(file, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - return executeLegacyOperation(this.db.s.topology, writeFile, [this, file, options, callback], { - skipSessions: true - }); -}; - -var writeFile = function(self, file, options, callback) { - if (typeof file === 'string') { - fs.open(file, 'r', function(err, fd) { - if (err) return callback(err); - self.writeFile(fd, callback); - }); - return; - } - - self.open(function(err, self) { - if (err) return callback(err, self); - - fs.fstat(file, function(err, stats) { - if (err) return callback(err, self); - - var offset = 0; - var index = 0; - - // Write a chunk - var writeChunk = function() { - // Allocate the buffer - var _buffer = Buffer.alloc(self.chunkSize); - // Read the file - fs.read(file, _buffer, 0, _buffer.length, offset, function(err, bytesRead, data) { - if (err) return callback(err, self); - - offset = offset + bytesRead; - - // Create a new chunk for the data - var chunk = new Chunk(self, { n: index++ }, self.writeConcern); - chunk.write(data.slice(0, bytesRead), function(err, chunk) { - if (err) return callback(err, self); - - chunk.save({}, function(err) { - if (err) return callback(err, self); - - self.position = self.position + bytesRead; - - // Point to current chunk - self.currentChunk = chunk; - - if (offset >= stats.size) { - fs.close(file, function(err) { - if (err) return callback(err); - - self.close(function(err) { - if (err) return callback(err, self); - return callback(null, self); - }); - }); - } else { - return process.nextTick(writeChunk); - } - }); - }); - }); - }; - - // Process the first write - process.nextTick(writeChunk); - }); - }); -}; - -/** - * Saves this file to the database. This will overwrite the old entry if it - * already exists. This will work properly only if mode was initialized to - * "w" or "w+". - * - * @method - * @param {object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.close = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - return executeLegacyOperation(this.db.s.topology, close, [this, options, callback], { - skipSessions: true - }); -}; - -var close = function(self, options, callback) { - if (self.mode[0] === 'w') { - // Set up options - options = Object.assign({}, self.writeConcern, options); - - if (self.currentChunk != null && self.currentChunk.position > 0) { - self.currentChunk.save({}, function(err) { - if (err && typeof callback === 'function') return callback(err); - - self.collection(function(err, files) { - if (err && typeof callback === 'function') return callback(err); - - // Build the mongo object - if (self.uploadDate != null) { - buildMongoObject(self, function(err, mongoObject) { - if (err) { - if (typeof callback === 'function') return callback(err); - else throw err; - } - - files.save(mongoObject, options, function(err) { - if (typeof callback === 'function') callback(err, mongoObject); - }); - }); - } else { - self.uploadDate = new Date(); - buildMongoObject(self, function(err, mongoObject) { - if (err) { - if (typeof callback === 'function') return callback(err); - else throw err; - } - - files.save(mongoObject, options, function(err) { - if (typeof callback === 'function') callback(err, mongoObject); - }); - }); - } - }); - }); - } else { - self.collection(function(err, files) { - if (err && typeof callback === 'function') return callback(err); - - self.uploadDate = new Date(); - buildMongoObject(self, function(err, mongoObject) { - if (err) { - if (typeof callback === 'function') return callback(err); - else throw err; - } - - files.save(mongoObject, options, function(err) { - if (typeof callback === 'function') callback(err, mongoObject); - }); - }); - }); - } - } else if (self.mode[0] === 'r') { - if (typeof callback === 'function') callback(null, null); - } else { - if (typeof callback === 'function') - callback(MongoError.create({ message: f('Illegal mode %s', self.mode), driver: true })); - } -}; - -/** - * The collection callback format. - * @callback GridStore~collectionCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection} collection The collection from the command execution. - */ - -/** - * Retrieve this file's chunks collection. - * - * @method - * @param {GridStore~collectionCallback} callback the command callback. - * @return {Collection} - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.chunkCollection = function(callback) { - if (typeof callback === 'function') return this.db.collection(this.root + '.chunks', callback); - return this.db.collection(this.root + '.chunks'); -}; - -/** - * Deletes all the chunks of this file in the database. - * - * @method - * @param {object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {GridStore~resultCallback} [callback] the command callback. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.unlink = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - return executeLegacyOperation(this.db.s.topology, unlink, [this, options, callback], { - skipSessions: true - }); -}; - -var unlink = function(self, options, callback) { - deleteChunks(self, function(err) { - if (err !== null) { - err.message = 'at deleteChunks: ' + err.message; - return callback(err); - } - - self.collection(function(err, collection) { - if (err !== null) { - err.message = 'at collection: ' + err.message; - return callback(err); - } - - collection.remove({ _id: self.fileId }, self.writeConcern, function(err) { - callback(err, self); - }); - }); - }); -}; - -/** - * Retrieves the file collection associated with this object. - * - * @method - * @param {GridStore~collectionCallback} callback the command callback. - * @return {Collection} - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.collection = function(callback) { - if (typeof callback === 'function') this.db.collection(this.root + '.files', callback); - return this.db.collection(this.root + '.files'); -}; - -/** - * The readlines callback format. - * @callback GridStore~readlinesCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {string[]} strings The array of strings returned. - */ - -/** - * Read the entire file as a list of strings splitting by the provided separator. - * - * @method - * @param {string} [separator] The character to be recognized as the newline separator. - * @param {object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {GridStore~readlinesCallback} [callback] the command callback. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.readlines = function(separator, options, callback) { - var args = Array.prototype.slice.call(arguments, 0); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - separator = args.length ? args.shift() : '\n'; - separator = separator || '\n'; - options = args.length ? args.shift() : {}; - - return executeLegacyOperation( - this.db.s.topology, - readlines, - [this, separator, options, callback], - { skipSessions: true } - ); -}; - -var readlines = function(self, separator, options, callback) { - self.read(function(err, data) { - if (err) return callback(err); - - var items = data.toString().split(separator); - items = items.length > 0 ? items.splice(0, items.length - 1) : []; - for (var i = 0; i < items.length; i++) { - items[i] = items[i] + separator; - } - - callback(null, items); - }); -}; - -/** - * Deletes all the chunks of this file in the database if mode was set to "w" or - * "w+" and resets the read/write head to the initial position. - * - * @method - * @param {object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.rewind = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - return executeLegacyOperation(this.db.s.topology, rewind, [this, options, callback], { - skipSessions: true - }); -}; - -var rewind = function(self, options, callback) { - if (self.currentChunk.chunkNumber !== 0) { - if (self.mode[0] === 'w') { - deleteChunks(self, function(err) { - if (err) return callback(err); - self.currentChunk = new Chunk(self, { n: 0 }, self.writeConcern); - self.position = 0; - callback(null, self); - }); - } else { - self.currentChunk(0, function(err, chunk) { - if (err) return callback(err); - self.currentChunk = chunk; - self.currentChunk.rewind(); - self.position = 0; - callback(null, self); - }); - } - } else { - self.currentChunk.rewind(); - self.position = 0; - callback(null, self); - } -}; - -/** - * The read callback format. - * @callback GridStore~readCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Buffer} data The data read from the GridStore object - */ - -/** - * Retrieves the contents of this file and advances the read/write head. Works with Buffers only. - * - * There are 3 signatures for this method: - * - * (callback) - * (length, callback) - * (length, buffer, callback) - * - * @method - * @param {number} [length] the number of characters to read. Reads all the characters from the read/write head to the EOF if not specified. - * @param {(string|Buffer)} [buffer] a string to hold temporary data. This is used for storing the string data read so far when recursively calling this method. - * @param {object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {GridStore~readCallback} [callback] the command callback. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.read = function(length, buffer, options, callback) { - var args = Array.prototype.slice.call(arguments, 0); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - length = args.length ? args.shift() : null; - buffer = args.length ? args.shift() : null; - options = args.length ? args.shift() : {}; - - return executeLegacyOperation( - this.db.s.topology, - read, - [this, length, buffer, options, callback], - { skipSessions: true } - ); -}; - -var read = function(self, length, buffer, options, callback) { - // The data is a c-terminated string and thus the length - 1 - var finalLength = length == null ? self.length - self.position : length; - var finalBuffer = buffer == null ? Buffer.alloc(finalLength) : buffer; - // Add a index to buffer to keep track of writing position or apply current index - finalBuffer._index = buffer != null && buffer._index != null ? buffer._index : 0; - - if (self.currentChunk.length() - self.currentChunk.position + finalBuffer._index >= finalLength) { - var slice = self.currentChunk.readSlice(finalLength - finalBuffer._index); - // Copy content to final buffer - slice.copy(finalBuffer, finalBuffer._index); - // Update internal position - self.position = self.position + finalBuffer.length; - // Check if we don't have a file at all - if (finalLength === 0 && finalBuffer.length === 0) - return callback(MongoError.create({ message: 'File does not exist', driver: true }), null); - // Else return data - return callback(null, finalBuffer); - } - - // Read the next chunk - slice = self.currentChunk.readSlice(self.currentChunk.length() - self.currentChunk.position); - // Copy content to final buffer - slice.copy(finalBuffer, finalBuffer._index); - // Update index position - finalBuffer._index += slice.length; - - // Load next chunk and read more - nthChunk(self, self.currentChunk.chunkNumber + 1, function(err, chunk) { - if (err) return callback(err); - - if (chunk.length() > 0) { - self.currentChunk = chunk; - self.read(length, finalBuffer, callback); - } else { - if (finalBuffer._index > 0) { - callback(null, finalBuffer); - } else { - callback( - MongoError.create({ - message: 'no chunks found for file, possibly corrupt', - driver: true - }), - null - ); - } - } - }); -}; - -/** - * The tell callback format. - * @callback GridStore~tellCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {number} position The current read position in the GridStore. - */ - -/** - * Retrieves the position of the read/write head of this file. - * - * @method - * @param {number} [length] the number of characters to read. Reads all the characters from the read/write head to the EOF if not specified. - * @param {(string|Buffer)} [buffer] a string to hold temporary data. This is used for storing the string data read so far when recursively calling this method. - * @param {object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {GridStore~tellCallback} [callback] the command callback. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.tell = function(callback) { - var self = this; - // We provided a callback leg - if (typeof callback === 'function') return callback(null, this.position); - // Return promise - return new self.promiseLibrary(function(resolve) { - resolve(self.position); - }); -}; - -/** - * The tell callback format. - * @callback GridStore~gridStoreCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {GridStore} gridStore The gridStore. - */ - -/** - * Moves the read/write head to a new location. - * - * There are 3 signatures for this method - * - * Seek Location Modes - * - **GridStore.IO_SEEK_SET**, **(default)** set the position from the start of the file. - * - **GridStore.IO_SEEK_CUR**, set the position from the current position in the file. - * - **GridStore.IO_SEEK_END**, set the position from the end of the file. - * - * @method - * @param {number} [position] the position to seek to - * @param {number} [seekLocation] seek mode. Use one of the Seek Location modes. - * @param {object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {GridStore~gridStoreCallback} [callback] the command callback. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.seek = function(position, seekLocation, options, callback) { - var args = Array.prototype.slice.call(arguments, 1); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - seekLocation = args.length ? args.shift() : null; - options = args.length ? args.shift() : {}; - - return executeLegacyOperation( - this.db.s.topology, - seek, - [this, position, seekLocation, options, callback], - { skipSessions: true } - ); -}; - -var seek = function(self, position, seekLocation, options, callback) { - // Seek only supports read mode - if (self.mode !== 'r') { - return callback( - MongoError.create({ message: 'seek is only supported for mode r', driver: true }) - ); - } - - var seekLocationFinal = seekLocation == null ? GridStore.IO_SEEK_SET : seekLocation; - var finalPosition = position; - var targetPosition = 0; - - // Calculate the position - if (seekLocationFinal === GridStore.IO_SEEK_CUR) { - targetPosition = self.position + finalPosition; - } else if (seekLocationFinal === GridStore.IO_SEEK_END) { - targetPosition = self.length + finalPosition; - } else { - targetPosition = finalPosition; - } - - // Get the chunk - var newChunkNumber = Math.floor(targetPosition / self.chunkSize); - var seekChunk = function() { - nthChunk(self, newChunkNumber, function(err, chunk) { - if (err) return callback(err, null); - if (chunk == null) return callback(new Error('no chunk found')); - - // Set the current chunk - self.currentChunk = chunk; - self.position = targetPosition; - self.currentChunk.position = self.position % self.chunkSize; - callback(err, self); - }); - }; - - seekChunk(); -}; - -/** - * @ignore - */ -var _open = function(self, options, callback) { - var collection = self.collection(); - // Create the query - var query = - self.referenceBy === REFERENCE_BY_ID ? { _id: self.fileId } : { filename: self.filename }; - query = null == self.fileId && self.filename == null ? null : query; - options.readPreference = self.readPreference; - - // Fetch the chunks - if (query != null) { - collection.findOne(query, options, function(err, doc) { - if (err) { - return error(err); - } - - // Check if the collection for the files exists otherwise prepare the new one - if (doc != null) { - self.fileId = doc._id; - // Prefer a new filename over the existing one if this is a write - self.filename = - self.mode === 'r' || self.filename === undefined ? doc.filename : self.filename; - self.contentType = doc.contentType; - self.internalChunkSize = doc.chunkSize; - self.uploadDate = doc.uploadDate; - self.aliases = doc.aliases; - self.length = doc.length; - self.metadata = doc.metadata; - self.internalMd5 = doc.md5; - } else if (self.mode !== 'r') { - self.fileId = self.fileId == null ? new ObjectID() : self.fileId; - self.contentType = GridStore.DEFAULT_CONTENT_TYPE; - self.internalChunkSize = - self.internalChunkSize == null ? Chunk.DEFAULT_CHUNK_SIZE : self.internalChunkSize; - self.length = 0; - } else { - self.length = 0; - var txtId = self.fileId._bsontype === 'ObjectID' ? self.fileId.toHexString() : self.fileId; - return error( - MongoError.create({ - message: f( - 'file with id %s not opened for writing', - self.referenceBy === REFERENCE_BY_ID ? txtId : self.filename - ), - driver: true - }), - self - ); - } - - // Process the mode of the object - if (self.mode === 'r') { - nthChunk(self, 0, options, function(err, chunk) { - if (err) return error(err); - self.currentChunk = chunk; - self.position = 0; - callback(null, self); - }); - } else if (self.mode === 'w' && doc) { - // Delete any existing chunks - deleteChunks(self, options, function(err) { - if (err) return error(err); - self.currentChunk = new Chunk(self, { n: 0 }, self.writeConcern); - self.contentType = - self.options['content_type'] == null ? self.contentType : self.options['content_type']; - self.internalChunkSize = - self.options['chunk_size'] == null - ? self.internalChunkSize - : self.options['chunk_size']; - self.metadata = - self.options['metadata'] == null ? self.metadata : self.options['metadata']; - self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; - self.position = 0; - callback(null, self); - }); - } else if (self.mode === 'w') { - self.currentChunk = new Chunk(self, { n: 0 }, self.writeConcern); - self.contentType = - self.options['content_type'] == null ? self.contentType : self.options['content_type']; - self.internalChunkSize = - self.options['chunk_size'] == null ? self.internalChunkSize : self.options['chunk_size']; - self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata']; - self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; - self.position = 0; - callback(null, self); - } else if (self.mode === 'w+') { - nthChunk(self, lastChunkNumber(self), options, function(err, chunk) { - if (err) return error(err); - // Set the current chunk - self.currentChunk = chunk == null ? new Chunk(self, { n: 0 }, self.writeConcern) : chunk; - self.currentChunk.position = self.currentChunk.data.length(); - self.metadata = - self.options['metadata'] == null ? self.metadata : self.options['metadata']; - self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; - self.position = self.length; - callback(null, self); - }); - } - }); - } else { - // Write only mode - self.fileId = null == self.fileId ? new ObjectID() : self.fileId; - self.contentType = GridStore.DEFAULT_CONTENT_TYPE; - self.internalChunkSize = - self.internalChunkSize == null ? Chunk.DEFAULT_CHUNK_SIZE : self.internalChunkSize; - self.length = 0; - - // No file exists set up write mode - if (self.mode === 'w') { - // Delete any existing chunks - deleteChunks(self, options, function(err) { - if (err) return error(err); - self.currentChunk = new Chunk(self, { n: 0 }, self.writeConcern); - self.contentType = - self.options['content_type'] == null ? self.contentType : self.options['content_type']; - self.internalChunkSize = - self.options['chunk_size'] == null ? self.internalChunkSize : self.options['chunk_size']; - self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata']; - self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; - self.position = 0; - callback(null, self); - }); - } else if (self.mode === 'w+') { - nthChunk(self, lastChunkNumber(self), options, function(err, chunk) { - if (err) return error(err); - // Set the current chunk - self.currentChunk = chunk == null ? new Chunk(self, { n: 0 }, self.writeConcern) : chunk; - self.currentChunk.position = self.currentChunk.data.length(); - self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata']; - self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; - self.position = self.length; - callback(null, self); - }); - } - } - - // only pass error to callback once - function error(err) { - if (error.err) return; - callback((error.err = err)); - } -}; - -/** - * @ignore - */ -var writeBuffer = function(self, buffer, close, callback) { - if (typeof close === 'function') { - callback = close; - close = null; - } - var finalClose = typeof close === 'boolean' ? close : false; - - if (self.mode !== 'w') { - callback( - MongoError.create({ - message: f( - 'file with id %s not opened for writing', - self.referenceBy === REFERENCE_BY_ID ? self.referenceBy : self.filename - ), - driver: true - }), - null - ); - } else { - if (self.currentChunk.position + buffer.length >= self.chunkSize) { - // Write out the current Chunk and then keep writing until we have less data left than a chunkSize left - // to a new chunk (recursively) - var previousChunkNumber = self.currentChunk.chunkNumber; - var leftOverDataSize = self.chunkSize - self.currentChunk.position; - var firstChunkData = buffer.slice(0, leftOverDataSize); - var leftOverData = buffer.slice(leftOverDataSize); - // A list of chunks to write out - var chunksToWrite = [self.currentChunk.write(firstChunkData)]; - // If we have more data left than the chunk size let's keep writing new chunks - while (leftOverData.length >= self.chunkSize) { - // Create a new chunk and write to it - var newChunk = new Chunk(self, { n: previousChunkNumber + 1 }, self.writeConcern); - firstChunkData = leftOverData.slice(0, self.chunkSize); - leftOverData = leftOverData.slice(self.chunkSize); - // Update chunk number - previousChunkNumber = previousChunkNumber + 1; - // Write data - newChunk.write(firstChunkData); - // Push chunk to save list - chunksToWrite.push(newChunk); - } - - // Set current chunk with remaining data - self.currentChunk = new Chunk(self, { n: previousChunkNumber + 1 }, self.writeConcern); - // If we have left over data write it - if (leftOverData.length > 0) self.currentChunk.write(leftOverData); - - // Update the position for the gridstore - self.position = self.position + buffer.length; - // Total number of chunks to write - var numberOfChunksToWrite = chunksToWrite.length; - - for (var i = 0; i < chunksToWrite.length; i++) { - chunksToWrite[i].save({}, function(err) { - if (err) return callback(err); - - numberOfChunksToWrite = numberOfChunksToWrite - 1; - - if (numberOfChunksToWrite <= 0) { - // We care closing the file before returning - if (finalClose) { - return self.close(function(err) { - callback(err, self); - }); - } - - // Return normally - return callback(null, self); - } - }); - } - } else { - // Update the position for the gridstore - self.position = self.position + buffer.length; - // We have less data than the chunk size just write it and callback - self.currentChunk.write(buffer); - // We care closing the file before returning - if (finalClose) { - return self.close(function(err) { - callback(err, self); - }); - } - // Return normally - return callback(null, self); - } - } -}; - -/** - * Creates a mongoDB object representation of this object. - * - *

- *        {
- *          '_id' : , // {number} id for this file
- *          'filename' : , // {string} name for this file
- *          'contentType' : , // {string} mime type for this file
- *          'length' : , // {number} size of this file?
- *          'chunksize' : , // {number} chunk size used by this file
- *          'uploadDate' : , // {Date}
- *          'aliases' : , // {array of string}
- *          'metadata' : , // {string}
- *        }
- *        
- * - * @ignore - */ -var buildMongoObject = function(self, callback) { - // Calcuate the length - var mongoObject = { - _id: self.fileId, - filename: self.filename, - contentType: self.contentType, - length: self.position ? self.position : 0, - chunkSize: self.chunkSize, - uploadDate: self.uploadDate, - aliases: self.aliases, - metadata: self.metadata - }; - - var md5Command = { filemd5: self.fileId, root: self.root }; - self.db.command(md5Command, function(err, results) { - if (err) return callback(err); - - mongoObject.md5 = results.md5; - callback(null, mongoObject); - }); -}; - -/** - * Gets the nth chunk of this file. - * @ignore - */ -var nthChunk = function(self, chunkNumber, options, callback) { - if (typeof options === 'function') { - callback = options; - options = {}; - } - - options = options || self.writeConcern; - options.readPreference = self.readPreference; - // Get the nth chunk - self - .chunkCollection() - .findOne({ files_id: self.fileId, n: chunkNumber }, options, function(err, chunk) { - if (err) return callback(err); - - var finalChunk = chunk == null ? {} : chunk; - callback(null, new Chunk(self, finalChunk, self.writeConcern)); - }); -}; - -/** - * @ignore - */ -var lastChunkNumber = function(self) { - return Math.floor((self.length ? self.length - 1 : 0) / self.chunkSize); -}; - -/** - * Deletes all the chunks of this file in the database. - * - * @ignore - */ -var deleteChunks = function(self, options, callback) { - if (typeof options === 'function') { - callback = options; - options = {}; - } - - options = options || self.writeConcern; - - if (self.fileId != null) { - self.chunkCollection().remove({ files_id: self.fileId }, options, function(err) { - if (err) return callback(err, false); - callback(null, true); - }); - } else { - callback(null, true); - } -}; - -/** - * The collection to be used for holding the files and chunks collection. - * - * @classconstant DEFAULT_ROOT_COLLECTION - */ -GridStore.DEFAULT_ROOT_COLLECTION = 'fs'; - -/** - * Default file mime type - * - * @classconstant DEFAULT_CONTENT_TYPE - */ -GridStore.DEFAULT_CONTENT_TYPE = 'binary/octet-stream'; - -/** - * Seek mode where the given length is absolute. - * - * @classconstant IO_SEEK_SET - */ -GridStore.IO_SEEK_SET = 0; - -/** - * Seek mode where the given length is an offset to the current read/write head. - * - * @classconstant IO_SEEK_CUR - */ -GridStore.IO_SEEK_CUR = 1; - -/** - * Seek mode where the given length is an offset to the end of the file. - * - * @classconstant IO_SEEK_END - */ -GridStore.IO_SEEK_END = 2; - -/** - * Checks if a file exists in the database. - * - * @method - * @static - * @param {Db} db the database to query. - * @param {string} name The name of the file to look for. - * @param {string} [rootCollection] The root collection that holds the files and chunks collection. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**. - * @param {object} [options] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {GridStore~resultCallback} [callback] result from exists. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.exist = function(db, fileIdObject, rootCollection, options, callback) { - var args = Array.prototype.slice.call(arguments, 2); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - rootCollection = args.length ? args.shift() : null; - options = args.length ? args.shift() : {}; - options = options || {}; - - return executeLegacyOperation( - db.s.topology, - exists, - [db, fileIdObject, rootCollection, options, callback], - { skipSessions: true } - ); -}; - -var exists = function(db, fileIdObject, rootCollection, options, callback) { - // Establish read preference - var readPreference = options.readPreference || ReadPreference.PRIMARY; - // Fetch collection - var rootCollectionFinal = - rootCollection != null ? rootCollection : GridStore.DEFAULT_ROOT_COLLECTION; - db.collection(rootCollectionFinal + '.files', function(err, collection) { - if (err) return callback(err); - - // Build query - var query = - typeof fileIdObject === 'string' || - Object.prototype.toString.call(fileIdObject) === '[object RegExp]' - ? { filename: fileIdObject } - : { _id: fileIdObject }; // Attempt to locate file - - // We have a specific query - if ( - fileIdObject != null && - typeof fileIdObject === 'object' && - Object.prototype.toString.call(fileIdObject) !== '[object RegExp]' - ) { - query = fileIdObject; - } - - // Check if the entry exists - collection.findOne(query, { readPreference: readPreference }, function(err, item) { - if (err) return callback(err); - callback(null, item == null ? false : true); - }); - }); -}; - -/** - * Gets the list of files stored in the GridFS. - * - * @method - * @static - * @param {Db} db the database to query. - * @param {string} [rootCollection] The root collection that holds the files and chunks collection. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**. - * @param {object} [options] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {GridStore~resultCallback} [callback] result from exists. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.list = function(db, rootCollection, options, callback) { - var args = Array.prototype.slice.call(arguments, 1); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - rootCollection = args.length ? args.shift() : null; - options = args.length ? args.shift() : {}; - options = options || {}; - - return executeLegacyOperation(db.s.topology, list, [db, rootCollection, options, callback], { - skipSessions: true - }); -}; - -var list = function(db, rootCollection, options, callback) { - // Ensure we have correct values - if (rootCollection != null && typeof rootCollection === 'object') { - options = rootCollection; - rootCollection = null; - } - - // Establish read preference - var readPreference = options.readPreference || ReadPreference.primary; - // Check if we are returning by id not filename - var byId = options['id'] != null ? options['id'] : false; - // Fetch item - var rootCollectionFinal = - rootCollection != null ? rootCollection : GridStore.DEFAULT_ROOT_COLLECTION; - var items = []; - db.collection(rootCollectionFinal + '.files', function(err, collection) { - if (err) return callback(err); - - collection.find({}, { readPreference: readPreference }, function(err, cursor) { - if (err) return callback(err); - - cursor.each(function(err, item) { - if (item != null) { - items.push(byId ? item._id : item.filename); - } else { - callback(err, items); - } - }); - }); - }); -}; - -/** - * Reads the contents of a file. - * - * This method has the following signatures - * - * (db, name, callback) - * (db, name, length, callback) - * (db, name, length, offset, callback) - * (db, name, length, offset, options, callback) - * - * @method - * @static - * @param {Db} db the database to query. - * @param {string} name The name of the file. - * @param {number} [length] The size of data to read. - * @param {number} [offset] The offset from the head of the file of which to start reading from. - * @param {object} [options] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {GridStore~readCallback} [callback] the command callback. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.read = function(db, name, length, offset, options, callback) { - var args = Array.prototype.slice.call(arguments, 2); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - length = args.length ? args.shift() : null; - offset = args.length ? args.shift() : null; - options = args.length ? args.shift() : null; - options = options || {}; - - return executeLegacyOperation( - db.s.topology, - readStatic, - [db, name, length, offset, options, callback], - { skipSessions: true } - ); -}; - -var readStatic = function(db, name, length, offset, options, callback) { - new GridStore(db, name, 'r', options).open(function(err, gridStore) { - if (err) return callback(err); - // Make sure we are not reading out of bounds - if (offset && offset >= gridStore.length) - return callback('offset larger than size of file', null); - if (length && length > gridStore.length) - return callback('length is larger than the size of the file', null); - if (offset && length && offset + length > gridStore.length) - return callback('offset and length is larger than the size of the file', null); - - if (offset != null) { - gridStore.seek(offset, function(err, gridStore) { - if (err) return callback(err); - gridStore.read(length, callback); - }); - } else { - gridStore.read(length, callback); - } - }); -}; - -/** - * Read the entire file as a list of strings splitting by the provided separator. - * - * @method - * @static - * @param {Db} db the database to query. - * @param {(String|object)} name the name of the file. - * @param {string} [separator] The character to be recognized as the newline separator. - * @param {object} [options] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {GridStore~readlinesCallback} [callback] the command callback. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.readlines = function(db, name, separator, options, callback) { - var args = Array.prototype.slice.call(arguments, 2); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - separator = args.length ? args.shift() : null; - options = args.length ? args.shift() : null; - options = options || {}; - - return executeLegacyOperation( - db.s.topology, - readlinesStatic, - [db, name, separator, options, callback], - { skipSessions: true } - ); -}; - -var readlinesStatic = function(db, name, separator, options, callback) { - var finalSeperator = separator == null ? '\n' : separator; - new GridStore(db, name, 'r', options).open(function(err, gridStore) { - if (err) return callback(err); - gridStore.readlines(finalSeperator, callback); - }); -}; - -/** - * Deletes the chunks and metadata information of a file from GridFS. - * - * @method - * @static - * @param {Db} db The database to query. - * @param {(string|array)} names The name/names of the files to delete. - * @param {object} [options] Optional settings. - * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {GridStore~resultCallback} [callback] the command callback. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.unlink = function(db, names, options, callback) { - var args = Array.prototype.slice.call(arguments, 2); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - options = args.length ? args.shift() : {}; - options = options || {}; - - return executeLegacyOperation(db.s.topology, unlinkStatic, [this, db, names, options, callback], { - skipSessions: true - }); -}; - -var unlinkStatic = function(self, db, names, options, callback) { - // Get the write concern - var writeConcern = _getWriteConcern(db, options); - - // List of names - if (names.constructor === Array) { - var tc = 0; - for (var i = 0; i < names.length; i++) { - ++tc; - GridStore.unlink(db, names[i], options, function() { - if (--tc === 0) { - callback(null, self); - } - }); - } - } else { - new GridStore(db, names, 'w', options).open(function(err, gridStore) { - if (err) return callback(err); - deleteChunks(gridStore, function(err) { - if (err) return callback(err); - gridStore.collection(function(err, collection) { - if (err) return callback(err); - collection.remove({ _id: gridStore.fileId }, writeConcern, function(err) { - callback(err, self); - }); - }); - }); - }); - } -}; - -/** - * @ignore - */ -var _writeNormal = function(self, data, close, options, callback) { - // If we have a buffer write it using the writeBuffer method - if (Buffer.isBuffer(data)) { - return writeBuffer(self, data, close, callback); - } else { - return writeBuffer(self, Buffer.from(data, 'binary'), close, callback); - } -}; - -/** - * @ignore - */ -var _setWriteConcernHash = function(options) { - var finalOptions = {}; - if (options.w != null) finalOptions.w = options.w; - if (options.journal === true) finalOptions.j = options.journal; - if (options.j === true) finalOptions.j = options.j; - if (options.fsync === true) finalOptions.fsync = options.fsync; - if (options.wtimeout != null) finalOptions.wtimeout = options.wtimeout; - return finalOptions; -}; - -/** - * @ignore - */ -var _getWriteConcern = function(self, options) { - // Final options - var finalOptions = { w: 1 }; - options = options || {}; - - // Local options verification - if ( - options.w != null || - typeof options.j === 'boolean' || - typeof options.journal === 'boolean' || - typeof options.fsync === 'boolean' - ) { - finalOptions = _setWriteConcernHash(options); - } else if (options.safe != null && typeof options.safe === 'object') { - finalOptions = _setWriteConcernHash(options.safe); - } else if (typeof options.safe === 'boolean') { - finalOptions = { w: options.safe ? 1 : 0 }; - } else if ( - self.options.w != null || - typeof self.options.j === 'boolean' || - typeof self.options.journal === 'boolean' || - typeof self.options.fsync === 'boolean' - ) { - finalOptions = _setWriteConcernHash(self.options); - } else if ( - self.safe && - (self.safe.w != null || - typeof self.safe.j === 'boolean' || - typeof self.safe.journal === 'boolean' || - typeof self.safe.fsync === 'boolean') - ) { - finalOptions = _setWriteConcernHash(self.safe); - } else if (typeof self.safe === 'boolean') { - finalOptions = { w: self.safe ? 1 : 0 }; - } - - // Ensure we don't have an invalid combination of write concerns - if ( - finalOptions.w < 1 && - (finalOptions.journal === true || finalOptions.j === true || finalOptions.fsync === true) - ) - throw MongoError.create({ - message: 'No acknowledgement using w < 1 cannot be combined with journal:true or fsync:true', - driver: true - }); - - // Return the options - return finalOptions; -}; - -/** - * Create a new GridStoreStream instance (INTERNAL TYPE, do not instantiate directly) - * - * @class - * @extends external:Duplex - * @return {GridStoreStream} a GridStoreStream instance. - * @deprecated Use GridFSBucket API instead - */ -var GridStoreStream = function(gs) { - // Initialize the duplex stream - Duplex.call(this); - - // Get the gridstore - this.gs = gs; - - // End called - this.endCalled = false; - - // If we have a seek - this.totalBytesToRead = this.gs.length - this.gs.position; - this.seekPosition = this.gs.position; -}; - -// -// Inherit duplex -inherits(GridStoreStream, Duplex); - -GridStoreStream.prototype._pipe = GridStoreStream.prototype.pipe; - -// Set up override -GridStoreStream.prototype.pipe = function(destination) { - var self = this; - - // Only open gridstore if not already open - if (!self.gs.isOpen) { - self.gs.open(function(err) { - if (err) return self.emit('error', err); - self.totalBytesToRead = self.gs.length - self.gs.position; - self._pipe.apply(self, [destination]); - }); - } else { - self.totalBytesToRead = self.gs.length - self.gs.position; - self._pipe.apply(self, [destination]); - } - - return destination; -}; - -// Called by stream -GridStoreStream.prototype._read = function() { - var self = this; - - var read = function() { - // Read data - self.gs.read(length, function(err, buffer) { - if (err && !self.endCalled) return self.emit('error', err); - - // Stream is closed - if (self.endCalled || buffer == null) return self.push(null); - // Remove bytes read - if (buffer.length <= self.totalBytesToRead) { - self.totalBytesToRead = self.totalBytesToRead - buffer.length; - self.push(buffer); - } else if (buffer.length > self.totalBytesToRead) { - self.totalBytesToRead = self.totalBytesToRead - buffer._index; - self.push(buffer.slice(0, buffer._index)); - } - - // Finished reading - if (self.totalBytesToRead <= 0) { - self.endCalled = true; - } - }); - }; - - // Set read length - var length = - self.gs.length < self.gs.chunkSize ? self.gs.length - self.seekPosition : self.gs.chunkSize; - if (!self.gs.isOpen) { - self.gs.open(function(err) { - self.totalBytesToRead = self.gs.length - self.gs.position; - if (err) return self.emit('error', err); - read(); - }); - } else { - read(); - } -}; - -GridStoreStream.prototype.destroy = function() { - this.pause(); - this.endCalled = true; - this.gs.close(); - this.emit('end'); -}; - -GridStoreStream.prototype.write = function(chunk) { - var self = this; - if (self.endCalled) - return self.emit( - 'error', - MongoError.create({ message: 'attempting to write to stream after end called', driver: true }) - ); - // Do we have to open the gridstore - if (!self.gs.isOpen) { - self.gs.open(function() { - self.gs.isOpen = true; - self.gs.write(chunk, function() { - process.nextTick(function() { - self.emit('drain'); - }); - }); - }); - return false; - } else { - self.gs.write(chunk, function() { - self.emit('drain'); - }); - return true; - } -}; - -GridStoreStream.prototype.end = function(chunk, encoding, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 0); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - chunk = args.length ? args.shift() : null; - encoding = args.length ? args.shift() : null; - self.endCalled = true; - - if (chunk) { - self.gs.write(chunk, function() { - self.gs.close(function() { - if (typeof callback === 'function') callback(); - self.emit('end'); - }); - }); - } - - self.gs.close(function() { - if (typeof callback === 'function') callback(); - self.emit('end'); - }); -}; - -/** - * The read() method pulls some data out of the internal buffer and returns it. If there is no data available, then it will return null. - * @function external:Duplex#read - * @param {number} size Optional argument to specify how much data to read. - * @return {(String | Buffer | null)} - */ - -/** - * Call this function to cause the stream to return strings of the specified encoding instead of Buffer objects. - * @function external:Duplex#setEncoding - * @param {string} encoding The encoding to use. - * @return {null} - */ - -/** - * This method will cause the readable stream to resume emitting data events. - * @function external:Duplex#resume - * @return {null} - */ - -/** - * This method will cause a stream in flowing-mode to stop emitting data events. Any data that becomes available will remain in the internal buffer. - * @function external:Duplex#pause - * @return {null} - */ - -/** - * This method pulls all the data out of a readable stream, and writes it to the supplied destination, automatically managing the flow so that the destination is not overwhelmed by a fast readable stream. - * @function external:Duplex#pipe - * @param {Writable} destination The destination for writing data - * @param {object} [options] Pipe options - * @return {null} - */ - -/** - * This method will remove the hooks set up for a previous pipe() call. - * @function external:Duplex#unpipe - * @param {Writable} [destination] The destination for writing data - * @return {null} - */ - -/** - * This is useful in certain cases where a stream is being consumed by a parser, which needs to "un-consume" some data that it has optimistically pulled out of the source, so that the stream can be passed on to some other party. - * @function external:Duplex#unshift - * @param {(Buffer|string)} chunk Chunk of data to unshift onto the read queue. - * @return {null} - */ - -/** - * Versions of Node prior to v0.10 had streams that did not implement the entire Streams API as it is today. (See "Compatibility" below for more information.) - * @function external:Duplex#wrap - * @param {Stream} stream An "old style" readable stream. - * @return {null} - */ - -/** - * This method writes some data to the underlying system, and calls the supplied callback once the data has been fully handled. - * @function external:Duplex#write - * @param {(string|Buffer)} chunk The data to write - * @param {string} encoding The encoding, if chunk is a String - * @param {function} callback Callback for when this chunk of data is flushed - * @return {boolean} - */ - -/** - * Call this method when no more data will be written to the stream. If supplied, the callback is attached as a listener on the finish event. - * @function external:Duplex#end - * @param {(string|Buffer)} chunk The data to write - * @param {string} encoding The encoding, if chunk is a String - * @param {function} callback Callback for when this chunk of data is flushed - * @return {null} - */ - -/** - * GridStoreStream stream data event, fired for each document in the cursor. - * - * @event GridStoreStream#data - * @type {object} - */ - -/** - * GridStoreStream stream end event - * - * @event GridStoreStream#end - * @type {null} - */ - -/** - * GridStoreStream stream close event - * - * @event GridStoreStream#close - * @type {null} - */ - -/** - * GridStoreStream stream readable event - * - * @event GridStoreStream#readable - * @type {null} - */ - -/** - * GridStoreStream stream drain event - * - * @event GridStoreStream#drain - * @type {null} - */ - -/** - * GridStoreStream stream finish event - * - * @event GridStoreStream#finish - * @type {null} - */ - -/** - * GridStoreStream stream pipe event - * - * @event GridStoreStream#pipe - * @type {null} - */ - -/** - * GridStoreStream stream unpipe event - * - * @event GridStoreStream#unpipe - * @type {null} - */ - -/** - * GridStoreStream stream error event - * - * @event GridStoreStream#error - * @type {null} - */ - -/** - * @ignore - */ -module.exports = GridStore; diff --git a/scripts/2.5/node_modules/mongodb/lib/mongo_client.js b/scripts/2.5/node_modules/mongodb/lib/mongo_client.js deleted file mode 100644 index 703eda64..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/mongo_client.js +++ /dev/null @@ -1,479 +0,0 @@ -'use strict'; - -const ChangeStream = require('./change_stream'); -const Db = require('./db'); -const EventEmitter = require('events').EventEmitter; -const executeOperation = require('./operations/execute_operation'); -const inherits = require('util').inherits; -const MongoError = require('./core').MongoError; -const deprecate = require('util').deprecate; -const WriteConcern = require('./write_concern'); -const MongoDBNamespace = require('./utils').MongoDBNamespace; -const ReadPreference = require('./core/topologies/read_preference'); - -// Operations -const ConnectOperation = require('./operations/connect'); -const CloseOperation = require('./operations/close'); - -/** - * @fileOverview The **MongoClient** class is a class that allows for making Connections to MongoDB. - * - * @example - * // Connect using a MongoClient instance - * const MongoClient = require('mongodb').MongoClient; - * const test = require('assert'); - * // Connection url - * const url = 'mongodb://localhost:27017'; - * // Database Name - * const dbName = 'test'; - * // Connect using MongoClient - * const mongoClient = new MongoClient(url); - * mongoClient.connect(function(err, client) { - * const db = client.db(dbName); - * client.close(); - * }); - * - * @example - * // Connect using the MongoClient.connect static method - * const MongoClient = require('mongodb').MongoClient; - * const test = require('assert'); - * // Connection url - * const url = 'mongodb://localhost:27017'; - * // Database Name - * const dbName = 'test'; - * // Connect using MongoClient - * MongoClient.connect(url, function(err, client) { - * const db = client.db(dbName); - * client.close(); - * }); - */ - -/** - * A string specifying the level of a ReadConcern - * @typedef {'local'|'available'|'majority'|'linearizable'|'snapshot'} ReadConcernLevel - * @see https://docs.mongodb.com/manual/reference/read-concern/index.html#read-concern-levels - */ - -/** - * Configuration options for a automatic client encryption. - * - * **NOTE**: Support for client side encryption is in beta. Backwards-breaking changes may be made before the final release. - * - * @typedef {Object} AutoEncryptionOptions - * @property {MongoClient} [keyVaultClient] A `MongoClient` used to fetch keys from a key vault - * @property {string} [keyVaultNamespace] The namespace where keys are stored in the key vault - * @property {object} [kmsProviders] Provider details for the desired Key Management Service to use for encryption - * @property {object} [kmsProviders.aws] Optional settings for the AWS KMS provider - * @property {string} [kmsProviders.aws.accessKeyId] The access key used for the AWS KMS provider - * @property {string} [kmsProviders.aws.secretAccessKey] The secret access key used for the AWS KMS provider - * @property {object} [kmsProviders.local] Optional settings for the local KMS provider - * @property {string} [kmsProviders.local.key] The master key used to encrypt/decrypt data keys - * @property {object} [schemaMap] A map of namespaces to a local JSON schema for encryption - * @property {boolean} [bypassAutoEncryption] Allows the user to bypass auto encryption, maintaining implicit decryption - * @property {object} [extraOptions] Extra options related to the mongocryptd process - * @property {string} [extraOptions.mongocryptURI] A local process the driver communicates with to determine how to encrypt values in a command. Defaults to "mongodb://%2Fvar%2Fmongocryptd.sock" if domain sockets are available or "mongodb://localhost:27020" otherwise - * @property {boolean} [extraOptions.mongocryptdBypassSpawn=false] If true, autoEncryption will not attempt to spawn a mongocryptd before connecting - * @property {string} [extraOptions.mongocryptdSpawnPath] The path to the mongocryptd executable on the system - * @property {string[]} [extraOptions.mongocryptdSpawnArgs] Command line arguments to use when auto-spawning a mongocryptd - */ - -/** - * Creates a new MongoClient instance - * @class - * @param {string} url The connection URI string - * @param {object} [options] Optional settings - * @param {number} [options.poolSize=5] The maximum size of the individual server pool - * @param {boolean} [options.ssl=false] Enable SSL connection. - * @param {boolean} [options.sslValidate=false] Validate mongod server certificate against Certificate Authority - * @param {buffer} [options.sslCA=undefined] SSL Certificate store binary buffer - * @param {buffer} [options.sslCert=undefined] SSL Certificate binary buffer - * @param {buffer} [options.sslKey=undefined] SSL Key file binary buffer - * @param {string} [options.sslPass=undefined] SSL Certificate pass phrase - * @param {buffer} [options.sslCRL=undefined] SSL Certificate revocation list binary buffer - * @param {boolean} [options.autoReconnect=true] Enable autoReconnect for single server instances - * @param {boolean} [options.noDelay=true] TCP Connection no delay - * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled - * @param {number} [options.keepAliveInitialDelay=30000] The number of milliseconds to wait before initiating keepAlive on the TCP socket - * @param {number} [options.connectTimeoutMS=30000] TCP Connection timeout setting - * @param {number} [options.family] Version of IP stack. Can be 4, 6 or null (default). - * If null, will attempt to connect with IPv6, and will fall back to IPv4 on failure - * @param {number} [options.socketTimeoutMS=360000] TCP Socket timeout setting - * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times - * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries - * @param {boolean} [options.ha=true] Control if high availability monitoring runs for Replicaset or Mongos proxies - * @param {number} [options.haInterval=10000] The High availability period for replicaset inquiry - * @param {string} [options.replicaSet=undefined] The Replicaset set name - * @param {number} [options.secondaryAcceptableLatencyMS=15] Cutoff latency point in MS for Replicaset member selection - * @param {number} [options.acceptableLatencyMS=15] Cutoff latency point in MS for Mongos proxies selection - * @param {boolean} [options.connectWithNoPrimary=false] Sets if the driver should connect even if no primary is available - * @param {string} [options.authSource=undefined] Define the database to authenticate against - * @param {(number|string)} [options.w] The write concern - * @param {number} [options.wtimeout] The write concern timeout - * @param {boolean} [options.j=false] Specify a journal write concern - * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields - * @param {boolean} [options.raw=false] Return document results as raw BSON buffers - * @param {number} [options.bufferMaxEntries=-1] Sets a cap on how many operations the driver will buffer up before giving up on getting a working connection, default is -1 which is unlimited - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST) - * @param {object} [options.pkFactory] A primary key factory object for generation of custom _id keys - * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {object} [options.readConcern] Specify a read concern for the collection (only MongoDB 3.2 or higher supported) - * @param {ReadConcernLevel} [options.readConcern.level='local'] Specify a read concern level for the collection operations (only MongoDB 3.2 or higher supported) - * @param {number} [options.maxStalenessSeconds=undefined] The max staleness to secondary reads (values under 10 seconds cannot be guaranteed) - * @param {string} [options.loggerLevel=undefined] The logging level (error/warn/info/debug) - * @param {object} [options.logger=undefined] Custom logger object - * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types - * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers - * @param {boolean} [options.promoteLongs=true] Promotes long values to number if they fit inside the 53 bits resolution - * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit - * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function - * @param {object} [options.validateOptions=false] Validate MongoClient passed in options for correctness - * @param {string} [options.appname=undefined] The name of the application that created this MongoClient instance. MongoDB 3.4 and newer will print this value in the server log upon establishing each connection. It is also recorded in the slow query log and profile collections - * @param {string} [options.auth.user=undefined] The username for auth - * @param {string} [options.auth.password=undefined] The password for auth - * @param {string} [options.authMechanism=undefined] Mechanism for authentication: MDEFAULT, GSSAPI, PLAIN, MONGODB-X509, or SCRAM-SHA-1 - * @param {object} [options.compression] Type of compression to use: snappy or zlib - * @param {boolean} [options.fsync=false] Specify a file sync write concern - * @param {array} [options.readPreferenceTags] Read preference tags - * @param {number} [options.numberOfRetries=5] The number of retries for a tailable cursor - * @param {boolean} [options.auto_reconnect=true] Enable auto reconnecting for single server instances - * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this client - * @param {number} [options.minSize] If present, the connection pool will be initialized with minSize connections, and will never dip below minSize connections - * @param {boolean} [options.useNewUrlParser=true] Determines whether or not to use the new url parser. Enables the new, spec-compliant, url parser shipped in the core driver. This url parser fixes a number of problems with the original parser, and aims to outright replace that parser in the near future. Defaults to true, and must be explicitly set to false to use the legacy url parser. - * @param {boolean} [options.useUnifiedTopology] Enables the new unified topology layer - * @param {AutoEncryptionOptions} [options.autoEncryption] Optionally enable client side auto encryption - * @param {MongoClient~connectCallback} [callback] The command result callback - * @return {MongoClient} a MongoClient instance - */ -function MongoClient(url, options) { - if (!(this instanceof MongoClient)) return new MongoClient(url, options); - // Set up event emitter - EventEmitter.call(this); - - // The internal state - this.s = { - url: url, - options: options || {}, - promiseLibrary: null, - dbCache: new Map(), - sessions: new Set(), - writeConcern: WriteConcern.fromOptions(options), - namespace: new MongoDBNamespace('admin') - }; - - // Get the promiseLibrary - const promiseLibrary = this.s.options.promiseLibrary || Promise; - - // Add the promise to the internal state - this.s.promiseLibrary = promiseLibrary; -} - -/** - * @ignore - */ -inherits(MongoClient, EventEmitter); - -Object.defineProperty(MongoClient.prototype, 'writeConcern', { - enumerable: true, - get: function() { - return this.s.writeConcern; - } -}); - -Object.defineProperty(MongoClient.prototype, 'readPreference', { - enumerable: true, - get: function() { - return ReadPreference.primary; - } -}); - -/** - * The callback format for results - * @callback MongoClient~connectCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {MongoClient} client The connected client. - */ - -/** - * Connect to MongoDB using a url as documented at - * - * docs.mongodb.org/manual/reference/connection-string/ - * - * Note that for replicasets the replicaSet query parameter is required in the 2.0 driver - * - * @method - * @param {MongoClient~connectCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -MongoClient.prototype.connect = function(callback) { - if (typeof callback === 'string') { - throw new TypeError('`connect` only accepts a callback'); - } - - const operation = new ConnectOperation(this); - - return executeOperation(this, operation, callback); -}; - -MongoClient.prototype.logout = deprecate(function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - if (typeof callback === 'function') callback(null, true); -}, 'Multiple authentication is prohibited on a connected client, please only authenticate once per MongoClient'); - -/** - * Close the db and its underlying connections - * @method - * @param {boolean} [force=false] Force close, emitting no events - * @param {Db~noResultCallback} [callback] The result callback - * @return {Promise} returns Promise if no callback passed - */ -MongoClient.prototype.close = function(force, callback) { - if (typeof force === 'function') (callback = force), (force = false); - const operation = new CloseOperation(this, force); - return executeOperation(this, operation, callback); -}; - -/** - * Create a new Db instance sharing the current socket connections. Be aware that the new db instances are - * related in a parent-child relationship to the original instance so that events are correctly emitted on child - * db instances. Child db instances are cached so performing db('db1') twice will return the same instance. - * You can control these behaviors with the options noListener and returnNonCachedInstance. - * - * @method - * @param {string} [dbName] The name of the database we want to use. If not provided, use database name from connection string. - * @param {object} [options] Optional settings. - * @param {boolean} [options.noListener=false] Do not make the db an event listener to the original connection. - * @param {boolean} [options.returnNonCachedInstance=false] Control if you want to return a cached instance or have a new one created - * @return {Db} - */ -MongoClient.prototype.db = function(dbName, options) { - options = options || {}; - - // Default to db from connection string if not provided - if (!dbName) { - dbName = this.s.options.dbName; - } - - // Copy the options and add out internal override of the not shared flag - const finalOptions = Object.assign({}, this.s.options, options); - - // Do we have the db in the cache already - if (this.s.dbCache.has(dbName) && finalOptions.returnNonCachedInstance !== true) { - return this.s.dbCache.get(dbName); - } - - // Add promiseLibrary - finalOptions.promiseLibrary = this.s.promiseLibrary; - - // If no topology throw an error message - if (!this.topology) { - throw new MongoError('MongoClient must be connected before calling MongoClient.prototype.db'); - } - - // Return the db object - const db = new Db(dbName, this.topology, finalOptions); - - // Add the db to the cache - this.s.dbCache.set(dbName, db); - // Return the database - return db; -}; - -/** - * Check if MongoClient is connected - * - * @method - * @param {object} [options] Optional settings. - * @param {boolean} [options.noListener=false] Do not make the db an event listener to the original connection. - * @param {boolean} [options.returnNonCachedInstance=false] Control if you want to return a cached instance or have a new one created - * @return {boolean} - */ -MongoClient.prototype.isConnected = function(options) { - options = options || {}; - - if (!this.topology) return false; - return this.topology.isConnected(options); -}; - -/** - * Connect to MongoDB using a url as documented at - * - * docs.mongodb.org/manual/reference/connection-string/ - * - * Note that for replicasets the replicaSet query parameter is required in the 2.0 driver - * - * @method - * @static - * @param {string} url The connection URI string - * @param {object} [options] Optional settings - * @param {number} [options.poolSize=5] The maximum size of the individual server pool - * @param {boolean} [options.ssl=false] Enable SSL connection. - * @param {boolean} [options.sslValidate=false] Validate mongod server certificate against Certificate Authority - * @param {buffer} [options.sslCA=undefined] SSL Certificate store binary buffer - * @param {buffer} [options.sslCert=undefined] SSL Certificate binary buffer - * @param {buffer} [options.sslKey=undefined] SSL Key file binary buffer - * @param {string} [options.sslPass=undefined] SSL Certificate pass phrase - * @param {buffer} [options.sslCRL=undefined] SSL Certificate revocation list binary buffer - * @param {boolean} [options.autoReconnect=true] Enable autoReconnect for single server instances - * @param {boolean} [options.noDelay=true] TCP Connection no delay - * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled - * @param {boolean} [options.keepAliveInitialDelay=30000] The number of milliseconds to wait before initiating keepAlive on the TCP socket - * @param {number} [options.connectTimeoutMS=30000] TCP Connection timeout setting - * @param {number} [options.family] Version of IP stack. Can be 4, 6 or null (default). - * If null, will attempt to connect with IPv6, and will fall back to IPv4 on failure - * @param {number} [options.socketTimeoutMS=360000] TCP Socket timeout setting - * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times - * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries - * @param {boolean} [options.ha=true] Control if high availability monitoring runs for Replicaset or Mongos proxies - * @param {number} [options.haInterval=10000] The High availability period for replicaset inquiry - * @param {string} [options.replicaSet=undefined] The Replicaset set name - * @param {number} [options.secondaryAcceptableLatencyMS=15] Cutoff latency point in MS for Replicaset member selection - * @param {number} [options.acceptableLatencyMS=15] Cutoff latency point in MS for Mongos proxies selection - * @param {boolean} [options.connectWithNoPrimary=false] Sets if the driver should connect even if no primary is available - * @param {string} [options.authSource=undefined] Define the database to authenticate against - * @param {(number|string)} [options.w] The write concern - * @param {number} [options.wtimeout] The write concern timeout - * @param {boolean} [options.j=false] Specify a journal write concern - * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields - * @param {boolean} [options.raw=false] Return document results as raw BSON buffers - * @param {number} [options.bufferMaxEntries=-1] Sets a cap on how many operations the driver will buffer up before giving up on getting a working connection, default is -1 which is unlimited - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST) - * @param {object} [options.pkFactory] A primary key factory object for generation of custom _id keys - * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {object} [options.readConcern] Specify a read concern for the collection (only MongoDB 3.2 or higher supported) - * @param {ReadConcernLevel} [options.readConcern.level='local'] Specify a read concern level for the collection operations (only MongoDB 3.2 or higher supported) - * @param {number} [options.maxStalenessSeconds=undefined] The max staleness to secondary reads (values under 10 seconds cannot be guaranteed) - * @param {string} [options.loggerLevel=undefined] The logging level (error/warn/info/debug) - * @param {object} [options.logger=undefined] Custom logger object - * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types - * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers - * @param {boolean} [options.promoteLongs=true] Promotes long values to number if they fit inside the 53 bits resolution - * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit - * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function - * @param {object} [options.validateOptions=false] Validate MongoClient passed in options for correctness - * @param {string} [options.appname=undefined] The name of the application that created this MongoClient instance. MongoDB 3.4 and newer will print this value in the server log upon establishing each connection. It is also recorded in the slow query log and profile collections - * @param {string} [options.auth.user=undefined] The username for auth - * @param {string} [options.auth.password=undefined] The password for auth - * @param {string} [options.authMechanism=undefined] Mechanism for authentication: MDEFAULT, GSSAPI, PLAIN, MONGODB-X509, or SCRAM-SHA-1 - * @param {object} [options.compression] Type of compression to use: snappy or zlib - * @param {boolean} [options.fsync=false] Specify a file sync write concern - * @param {array} [options.readPreferenceTags] Read preference tags - * @param {number} [options.numberOfRetries=5] The number of retries for a tailable cursor - * @param {boolean} [options.auto_reconnect=true] Enable auto reconnecting for single server instances - * @param {number} [options.minSize] If present, the connection pool will be initialized with minSize connections, and will never dip below minSize connections - * @param {MongoClient~connectCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -MongoClient.connect = function(url, options, callback) { - const args = Array.prototype.slice.call(arguments, 1); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - options = args.length ? args.shift() : null; - options = options || {}; - - // Create client - const mongoClient = new MongoClient(url, options); - // Execute the connect method - return mongoClient.connect(callback); -}; - -/** - * Starts a new session on the server - * - * @param {SessionOptions} [options] optional settings for a driver session - * @return {ClientSession} the newly established session - */ -MongoClient.prototype.startSession = function(options) { - options = Object.assign({ explicit: true }, options); - if (!this.topology) { - throw new MongoError('Must connect to a server before calling this method'); - } - - if (!this.topology.hasSessionSupport()) { - throw new MongoError('Current topology does not support sessions'); - } - - return this.topology.startSession(options, this.s.options); -}; - -/** - * Runs a given operation with an implicitly created session. The lifetime of the session - * will be handled without the need for user interaction. - * - * NOTE: presently the operation MUST return a Promise (either explicit or implicity as an async function) - * - * @param {Object} [options] Optional settings to be appled to implicitly created session - * @param {Function} operation An operation to execute with an implicitly created session. The signature of this MUST be `(session) => {}` - * @return {Promise} - */ -MongoClient.prototype.withSession = function(options, operation) { - if (typeof options === 'function') (operation = options), (options = undefined); - const session = this.startSession(options); - - let cleanupHandler = (err, result, opts) => { - // prevent multiple calls to cleanupHandler - cleanupHandler = () => { - throw new ReferenceError('cleanupHandler was called too many times'); - }; - - opts = Object.assign({ throw: true }, opts); - session.endSession(); - - if (err) { - if (opts.throw) throw err; - return Promise.reject(err); - } - }; - - try { - const result = operation(session); - return Promise.resolve(result) - .then(result => cleanupHandler(null, result)) - .catch(err => cleanupHandler(err, null, { throw: true })); - } catch (err) { - return cleanupHandler(err, null, { throw: false }); - } -}; -/** - * Create a new Change Stream, watching for new changes (insertions, updates, replacements, deletions, and invalidations) in this cluster. Will ignore all changes to system collections, as well as the local, admin, - * and config databases. - * @method - * @since 3.1.0 - * @param {Array} [pipeline] An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents. - * @param {object} [options] Optional settings - * @param {string} [options.fullDocument='default'] Allowed values: ‘default’, ‘updateLookup’. When set to ‘updateLookup’, the change stream will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred. - * @param {object} [options.resumeAfter] Specifies the logical starting point for the new change stream. This should be the _id field from a previously returned change stream document. - * @param {number} [options.maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a change stream query - * @param {number} [options.batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. - * @param {object} [options.collation] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. - * @param {ReadPreference} [options.readPreference] The read preference. See {@link https://docs.mongodb.com/manual/reference/read-preference|read preference documentation}. - * @param {Timestamp} [options.startAtOperationTime] receive change events that occur after the specified timestamp - * @param {ClientSession} [options.session] optional session to use for this operation - * @return {ChangeStream} a ChangeStream instance. - */ -MongoClient.prototype.watch = function(pipeline, options) { - pipeline = pipeline || []; - options = options || {}; - - // Allow optionally not specifying a pipeline - if (!Array.isArray(pipeline)) { - options = pipeline; - pipeline = []; - } - - return new ChangeStream(this, pipeline, options); -}; - -/** - * Return the mongo client logger - * @method - * @return {Logger} return the mongo client logger - * @ignore - */ -MongoClient.prototype.getLogger = function() { - return this.s.options.logger; -}; - -module.exports = MongoClient; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/add_user.js b/scripts/2.5/node_modules/mongodb/lib/operations/add_user.js deleted file mode 100644 index 1f3f3a6f..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/operations/add_user.js +++ /dev/null @@ -1,96 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const CommandOperation = require('./command'); -const defineAspects = require('./operation').defineAspects; -const crypto = require('crypto'); -const handleCallback = require('../utils').handleCallback; -const toError = require('../utils').toError; - -class AddUserOperation extends CommandOperation { - constructor(db, username, password, options) { - super(db, options); - - this.username = username; - this.password = password; - } - - _buildCommand() { - const db = this.db; - const username = this.username; - const password = this.password; - const options = this.options; - - // Get additional values - let roles = Array.isArray(options.roles) ? options.roles : []; - - // If not roles defined print deprecated message - // TODO: handle deprecation properly - if (roles.length === 0) { - console.log('Creating a user without roles is deprecated in MongoDB >= 2.6'); - } - - // Check the db name and add roles if needed - if ( - (db.databaseName.toLowerCase() === 'admin' || options.dbName === 'admin') && - !Array.isArray(options.roles) - ) { - roles = ['root']; - } else if (!Array.isArray(options.roles)) { - roles = ['dbOwner']; - } - - const digestPassword = db.s.topology.lastIsMaster().maxWireVersion >= 7; - - let userPassword = password; - - if (!digestPassword) { - // Use node md5 generator - const md5 = crypto.createHash('md5'); - // Generate keys used for authentication - md5.update(username + ':mongo:' + password); - userPassword = md5.digest('hex'); - } - - // Build the command to execute - const command = { - createUser: username, - customData: options.customData || {}, - roles: roles, - digestPassword - }; - - // No password - if (typeof password === 'string') { - command.pwd = userPassword; - } - - return command; - } - - execute(callback) { - const options = this.options; - - // Error out if digestPassword set - if (options.digestPassword != null) { - return callback( - toError( - "The digestPassword option is not supported via add_user. Please use db.command('createUser', ...) instead for this option." - ) - ); - } - - // Attempt to execute auth command - super.execute((err, r) => { - if (!err) { - return handleCallback(callback, err, r); - } - - return handleCallback(callback, err, null); - }); - } -} - -defineAspects(AddUserOperation, Aspect.WRITE_OPERATION); - -module.exports = AddUserOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/admin_ops.js b/scripts/2.5/node_modules/mongodb/lib/operations/admin_ops.js deleted file mode 100644 index b08071c3..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/operations/admin_ops.js +++ /dev/null @@ -1,62 +0,0 @@ -'use strict'; - -const executeCommand = require('./db_ops').executeCommand; -const executeDbAdminCommand = require('./db_ops').executeDbAdminCommand; - -/** - * Get ReplicaSet status - * - * @param {Admin} a collection instance. - * @param {Object} [options] Optional settings. See Admin.prototype.replSetGetStatus for a list of options. - * @param {Admin~resultCallback} [callback] The command result callback. - */ -function replSetGetStatus(admin, options, callback) { - executeDbAdminCommand(admin.s.db, { replSetGetStatus: 1 }, options, callback); -} - -/** - * Retrieve this db's server status. - * - * @param {Admin} a collection instance. - * @param {Object} [options] Optional settings. See Admin.prototype.serverStatus for a list of options. - * @param {Admin~resultCallback} [callback] The command result callback - */ -function serverStatus(admin, options, callback) { - executeDbAdminCommand(admin.s.db, { serverStatus: 1 }, options, callback); -} - -/** - * Validate an existing collection - * - * @param {Admin} a collection instance. - * @param {string} collectionName The name of the collection to validate. - * @param {Object} [options] Optional settings. See Admin.prototype.validateCollection for a list of options. - * @param {Admin~resultCallback} [callback] The command result callback. - */ -function validateCollection(admin, collectionName, options, callback) { - const command = { validate: collectionName }; - const keys = Object.keys(options); - - // Decorate command with extra options - for (let i = 0; i < keys.length; i++) { - if (options.hasOwnProperty(keys[i]) && keys[i] !== 'session') { - command[keys[i]] = options[keys[i]]; - } - } - - executeCommand(admin.s.db, command, options, (err, doc) => { - if (err != null) return callback(err, null); - - if (doc.ok === 0) return callback(new Error('Error with validate command'), null); - if (doc.result != null && doc.result.constructor !== String) - return callback(new Error('Error with validation data'), null); - if (doc.result != null && doc.result.match(/exception|corrupt/) != null) - return callback(new Error('Error: invalid collection ' + collectionName), null); - if (doc.valid != null && !doc.valid) - return callback(new Error('Error: invalid collection ' + collectionName), null); - - return callback(null, doc); - }); -} - -module.exports = { replSetGetStatus, serverStatus, validateCollection }; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/aggregate.js b/scripts/2.5/node_modules/mongodb/lib/operations/aggregate.js deleted file mode 100644 index e0f2da84..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/operations/aggregate.js +++ /dev/null @@ -1,106 +0,0 @@ -'use strict'; - -const CommandOperationV2 = require('./command_v2'); -const MongoError = require('../core').MongoError; -const maxWireVersion = require('../core/utils').maxWireVersion; -const ReadPreference = require('../core').ReadPreference; -const Aspect = require('./operation').Aspect; -const defineAspects = require('./operation').defineAspects; - -const DB_AGGREGATE_COLLECTION = 1; -const MIN_WIRE_VERSION_$OUT_READ_CONCERN_SUPPORT = 8; - -class AggregateOperation extends CommandOperationV2 { - constructor(parent, pipeline, options) { - super(parent, options, { fullResponse: true }); - - this.target = - parent.s.namespace && parent.s.namespace.collection - ? parent.s.namespace.collection - : DB_AGGREGATE_COLLECTION; - - this.pipeline = pipeline; - - // determine if we have a write stage, override read preference if so - this.hasWriteStage = false; - if (typeof options.out === 'string') { - this.pipeline = this.pipeline.concat({ $out: options.out }); - this.hasWriteStage = true; - } else if (pipeline.length > 0) { - const finalStage = pipeline[pipeline.length - 1]; - if (finalStage.$out || finalStage.$merge) { - this.hasWriteStage = true; - } - } - - if (this.hasWriteStage) { - this.readPreference = ReadPreference.primary; - } - - if (options.explain && (this.readConcern || this.writeConcern)) { - throw new MongoError( - '"explain" cannot be used on an aggregate call with readConcern/writeConcern' - ); - } - - if (options.cursor != null && typeof options.cursor !== 'object') { - throw new MongoError('cursor options must be an object'); - } - } - - get canRetryRead() { - return !this.hasWriteStage; - } - - addToPipeline(stage) { - this.pipeline.push(stage); - } - - execute(server, callback) { - const options = this.options; - const serverWireVersion = maxWireVersion(server); - const command = { aggregate: this.target, pipeline: this.pipeline }; - - if (this.hasWriteStage && serverWireVersion < MIN_WIRE_VERSION_$OUT_READ_CONCERN_SUPPORT) { - this.readConcern = null; - } - - if (serverWireVersion >= 5) { - if (this.hasWriteStage && this.writeConcern) { - Object.assign(command, { writeConcern: this.writeConcern }); - } - } - - if (options.bypassDocumentValidation === true) { - command.bypassDocumentValidation = options.bypassDocumentValidation; - } - - if (typeof options.allowDiskUse === 'boolean') { - command.allowDiskUse = options.allowDiskUse; - } - - if (options.hint) { - command.hint = options.hint; - } - - if (options.explain) { - options.full = false; - command.explain = options.explain; - } - - command.cursor = options.cursor || {}; - if (options.batchSize && !this.hasWriteStage) { - command.cursor.batchSize = options.batchSize; - } - - super.executeCommand(server, command, callback); - } -} - -defineAspects(AggregateOperation, [ - Aspect.READ_OPERATION, - Aspect.RETRYABLE, - Aspect.EXECUTE_WITH_SELECTION -]); - -module.exports = AggregateOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/bulk_write.js b/scripts/2.5/node_modules/mongodb/lib/operations/bulk_write.js deleted file mode 100644 index 8f14f021..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/operations/bulk_write.js +++ /dev/null @@ -1,104 +0,0 @@ -'use strict'; - -const applyRetryableWrites = require('../utils').applyRetryableWrites; -const applyWriteConcern = require('../utils').applyWriteConcern; -const MongoError = require('../core').MongoError; -const OperationBase = require('./operation').OperationBase; - -class BulkWriteOperation extends OperationBase { - constructor(collection, operations, options) { - super(options); - - this.collection = collection; - this.operations = operations; - } - - execute(callback) { - const coll = this.collection; - const operations = this.operations; - let options = this.options; - - // Add ignoreUndfined - if (coll.s.options.ignoreUndefined) { - options = Object.assign({}, options); - options.ignoreUndefined = coll.s.options.ignoreUndefined; - } - - // Create the bulk operation - const bulk = - options.ordered === true || options.ordered == null - ? coll.initializeOrderedBulkOp(options) - : coll.initializeUnorderedBulkOp(options); - - // Do we have a collation - let collation = false; - - // for each op go through and add to the bulk - try { - for (let i = 0; i < operations.length; i++) { - // Get the operation type - const key = Object.keys(operations[i])[0]; - // Check if we have a collation - if (operations[i][key].collation) { - collation = true; - } - - // Pass to the raw bulk - bulk.raw(operations[i]); - } - } catch (err) { - return callback(err, null); - } - - // Final options for retryable writes and write concern - let finalOptions = Object.assign({}, options); - finalOptions = applyRetryableWrites(finalOptions, coll.s.db); - finalOptions = applyWriteConcern(finalOptions, { db: coll.s.db, collection: coll }, options); - - const writeCon = finalOptions.writeConcern ? finalOptions.writeConcern : {}; - const capabilities = coll.s.topology.capabilities(); - - // Did the user pass in a collation, check if our write server supports it - if (collation && capabilities && !capabilities.commandsTakeCollation) { - return callback(new MongoError('server/primary/mongos does not support collation')); - } - - // Execute the bulk - bulk.execute(writeCon, finalOptions, (err, r) => { - // We have connection level error - if (!r && err) { - return callback(err, null); - } - - r.insertedCount = r.nInserted; - r.matchedCount = r.nMatched; - r.modifiedCount = r.nModified || 0; - r.deletedCount = r.nRemoved; - r.upsertedCount = r.getUpsertedIds().length; - r.upsertedIds = {}; - r.insertedIds = {}; - - // Update the n - r.n = r.insertedCount; - - // Inserted documents - const inserted = r.getInsertedIds(); - // Map inserted ids - for (let i = 0; i < inserted.length; i++) { - r.insertedIds[inserted[i].index] = inserted[i]._id; - } - - // Upserted documents - const upserted = r.getUpsertedIds(); - // Map upserted ids - for (let i = 0; i < upserted.length; i++) { - r.upsertedIds[upserted[i].index] = upserted[i]._id; - } - - // Return the results - callback(null, r); - }); - } -} - -module.exports = BulkWriteOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/close.js b/scripts/2.5/node_modules/mongodb/lib/operations/close.js deleted file mode 100644 index 57fdef6f..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/operations/close.js +++ /dev/null @@ -1,46 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const defineAspects = require('./operation').defineAspects; -const OperationBase = require('./operation').OperationBase; - -class CloseOperation extends OperationBase { - constructor(client, force) { - super(); - this.client = client; - this.force = force; - } - - execute(callback) { - const client = this.client; - const force = this.force; - const completeClose = err => { - client.emit('close', client); - for (const item of client.s.dbCache) { - item[1].emit('close', client); - } - - client.removeAllListeners('close'); - callback(err, null); - }; - - if (client.topology == null) { - completeClose(); - return; - } - - client.topology.close(force, err => { - const autoEncrypter = client.topology.s.options.autoEncrypter; - if (!autoEncrypter) { - completeClose(err); - return; - } - - autoEncrypter.teardown(force, err2 => completeClose(err || err2)); - }); - } -} - -defineAspects(CloseOperation, [Aspect.SKIP_SESSION]); - -module.exports = CloseOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/collection_ops.js b/scripts/2.5/node_modules/mongodb/lib/operations/collection_ops.js deleted file mode 100644 index df5995d7..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/operations/collection_ops.js +++ /dev/null @@ -1,374 +0,0 @@ -'use strict'; - -const applyWriteConcern = require('../utils').applyWriteConcern; -const Code = require('../core').BSON.Code; -const createIndexDb = require('./db_ops').createIndex; -const decorateWithCollation = require('../utils').decorateWithCollation; -const decorateWithReadConcern = require('../utils').decorateWithReadConcern; -const ensureIndexDb = require('./db_ops').ensureIndex; -const evaluate = require('./db_ops').evaluate; -const executeCommand = require('./db_ops').executeCommand; -const resolveReadPreference = require('../utils').resolveReadPreference; -const handleCallback = require('../utils').handleCallback; -const indexInformationDb = require('./db_ops').indexInformation; -const Long = require('../core').BSON.Long; -const MongoError = require('../core').MongoError; -const ReadPreference = require('../core').ReadPreference; -const toError = require('../utils').toError; -const insertDocuments = require('./common_functions').insertDocuments; -const updateDocuments = require('./common_functions').updateDocuments; - -/** - * Group function helper - * @ignore - */ -// var groupFunction = function () { -// var c = db[ns].find(condition); -// var map = new Map(); -// var reduce_function = reduce; -// -// while (c.hasNext()) { -// var obj = c.next(); -// var key = {}; -// -// for (var i = 0, len = keys.length; i < len; ++i) { -// var k = keys[i]; -// key[k] = obj[k]; -// } -// -// var aggObj = map.get(key); -// -// if (aggObj == null) { -// var newObj = Object.extend({}, key); -// aggObj = Object.extend(newObj, initial); -// map.put(key, aggObj); -// } -// -// reduce_function(obj, aggObj); -// } -// -// return { "result": map.values() }; -// }.toString(); -const groupFunction = - 'function () {\nvar c = db[ns].find(condition);\nvar map = new Map();\nvar reduce_function = reduce;\n\nwhile (c.hasNext()) {\nvar obj = c.next();\nvar key = {};\n\nfor (var i = 0, len = keys.length; i < len; ++i) {\nvar k = keys[i];\nkey[k] = obj[k];\n}\n\nvar aggObj = map.get(key);\n\nif (aggObj == null) {\nvar newObj = Object.extend({}, key);\naggObj = Object.extend(newObj, initial);\nmap.put(key, aggObj);\n}\n\nreduce_function(obj, aggObj);\n}\n\nreturn { "result": map.values() };\n}'; - -// Check the update operation to ensure it has atomic operators. -function checkForAtomicOperators(update) { - if (Array.isArray(update)) { - return update.reduce((err, u) => err || checkForAtomicOperators(u), null); - } - - const keys = Object.keys(update); - - // same errors as the server would give for update doc lacking atomic operators - if (keys.length === 0) { - return toError('The update operation document must contain at least one atomic operator.'); - } - - if (keys[0][0] !== '$') { - return toError('the update operation document must contain atomic operators.'); - } -} - -/** - * Create an index on the db and collection. - * - * @method - * @param {Collection} a Collection instance. - * @param {(string|object)} fieldOrSpec Defines the index. - * @param {object} [options] Optional settings. See Collection.prototype.createIndex for a list of options. - * @param {Collection~resultCallback} [callback] The command result callback - */ -function createIndex(coll, fieldOrSpec, options, callback) { - createIndexDb(coll.s.db, coll.collectionName, fieldOrSpec, options, callback); -} - -/** - * Create multiple indexes in the collection. This method is only supported for - * MongoDB 2.6 or higher. Earlier version of MongoDB will throw a command not supported - * error. Index specifications are defined at http://docs.mongodb.org/manual/reference/command/createIndexes/. - * - * @method - * @param {Collection} a Collection instance. - * @param {array} indexSpecs An array of index specifications to be created - * @param {Object} [options] Optional settings. See Collection.prototype.createIndexes for a list of options. - * @param {Collection~resultCallback} [callback] The command result callback - */ -function createIndexes(coll, indexSpecs, options, callback) { - const capabilities = coll.s.topology.capabilities(); - - // Ensure we generate the correct name if the parameter is not set - for (let i = 0; i < indexSpecs.length; i++) { - if (indexSpecs[i].name == null) { - const keys = []; - - // Did the user pass in a collation, check if our write server supports it - if (indexSpecs[i].collation && capabilities && !capabilities.commandsTakeCollation) { - return callback(new MongoError('server/primary/mongos does not support collation')); - } - - for (let name in indexSpecs[i].key) { - keys.push(`${name}_${indexSpecs[i].key[name]}`); - } - - // Set the name - indexSpecs[i].name = keys.join('_'); - } - } - - options = Object.assign({}, options, { readPreference: ReadPreference.PRIMARY }); - - // Execute the index - executeCommand( - coll.s.db, - { - createIndexes: coll.collectionName, - indexes: indexSpecs - }, - options, - callback - ); -} - -/** - * Ensure that an index exists. If the index does not exist, this function creates it. - * - * @method - * @param {Collection} a Collection instance. - * @param {(string|object)} fieldOrSpec Defines the index. - * @param {object} [options] Optional settings. See Collection.prototype.ensureIndex for a list of options. - * @param {Collection~resultCallback} [callback] The command result callback - */ -function ensureIndex(coll, fieldOrSpec, options, callback) { - ensureIndexDb(coll.s.db, coll.collectionName, fieldOrSpec, options, callback); -} - -/** - * Run a group command across a collection. - * - * @method - * @param {Collection} a Collection instance. - * @param {(object|array|function|code)} keys An object, array or function expressing the keys to group by. - * @param {object} condition An optional condition that must be true for a row to be considered. - * @param {object} initial Initial value of the aggregation counter object. - * @param {(function|Code)} reduce The reduce function aggregates (reduces) the objects iterated - * @param {(function|Code)} finalize An optional function to be run on each item in the result set just before the item is returned. - * @param {boolean} command Specify if you wish to run using the internal group command or using eval, default is true. - * @param {object} [options] Optional settings. See Collection.prototype.group for a list of options. - * @param {Collection~resultCallback} [callback] The command result callback - * @deprecated MongoDB 3.6 or higher will no longer support the group command. We recommend rewriting using the aggregation framework. - */ -function group(coll, keys, condition, initial, reduce, finalize, command, options, callback) { - // Execute using the command - if (command) { - const reduceFunction = reduce && reduce._bsontype === 'Code' ? reduce : new Code(reduce); - - const selector = { - group: { - ns: coll.collectionName, - $reduce: reduceFunction, - cond: condition, - initial: initial, - out: 'inline' - } - }; - - // if finalize is defined - if (finalize != null) selector.group['finalize'] = finalize; - // Set up group selector - if ('function' === typeof keys || (keys && keys._bsontype === 'Code')) { - selector.group.$keyf = keys && keys._bsontype === 'Code' ? keys : new Code(keys); - } else { - const hash = {}; - keys.forEach(key => { - hash[key] = 1; - }); - selector.group.key = hash; - } - - options = Object.assign({}, options); - // Ensure we have the right read preference inheritance - options.readPreference = resolveReadPreference(coll, options); - - // Do we have a readConcern specified - decorateWithReadConcern(selector, coll, options); - - // Have we specified collation - try { - decorateWithCollation(selector, coll, options); - } catch (err) { - return callback(err, null); - } - - // Execute command - executeCommand(coll.s.db, selector, options, (err, result) => { - if (err) return handleCallback(callback, err, null); - handleCallback(callback, null, result.retval); - }); - } else { - // Create execution scope - const scope = reduce != null && reduce._bsontype === 'Code' ? reduce.scope : {}; - - scope.ns = coll.collectionName; - scope.keys = keys; - scope.condition = condition; - scope.initial = initial; - - // Pass in the function text to execute within mongodb. - const groupfn = groupFunction.replace(/ reduce;/, reduce.toString() + ';'); - - evaluate(coll.s.db, new Code(groupfn, scope), null, options, (err, results) => { - if (err) return handleCallback(callback, err, null); - handleCallback(callback, null, results.result || results); - }); - } -} - -/** - * Retrieve all the indexes on the collection. - * - * @method - * @param {Collection} a Collection instance. - * @param {Object} [options] Optional settings. See Collection.prototype.indexes for a list of options. - * @param {Collection~resultCallback} [callback] The command result callback - */ -function indexes(coll, options, callback) { - options = Object.assign({}, { full: true }, options); - indexInformationDb(coll.s.db, coll.collectionName, options, callback); -} - -/** - * Check if one or more indexes exist on the collection. This fails on the first index that doesn't exist. - * - * @method - * @param {Collection} a Collection instance. - * @param {(string|array)} indexes One or more index names to check. - * @param {Object} [options] Optional settings. See Collection.prototype.indexExists for a list of options. - * @param {Collection~resultCallback} [callback] The command result callback - */ -function indexExists(coll, indexes, options, callback) { - indexInformation(coll, options, (err, indexInformation) => { - // If we have an error return - if (err != null) return handleCallback(callback, err, null); - // Let's check for the index names - if (!Array.isArray(indexes)) - return handleCallback(callback, null, indexInformation[indexes] != null); - // Check in list of indexes - for (let i = 0; i < indexes.length; i++) { - if (indexInformation[indexes[i]] == null) { - return handleCallback(callback, null, false); - } - } - - // All keys found return true - return handleCallback(callback, null, true); - }); -} - -/** - * Retrieve this collection's index info. - * - * @method - * @param {Collection} a Collection instance. - * @param {object} [options] Optional settings. See Collection.prototype.indexInformation for a list of options. - * @param {Collection~resultCallback} [callback] The command result callback - */ -function indexInformation(coll, options, callback) { - indexInformationDb(coll.s.db, coll.collectionName, options, callback); -} - -/** - * Return N parallel cursors for a collection to allow parallel reading of the entire collection. There are - * no ordering guarantees for returned results. - * - * @method - * @param {Collection} a Collection instance. - * @param {object} [options] Optional settings. See Collection.prototype.parallelCollectionScan for a list of options. - * @param {Collection~parallelCollectionScanCallback} [callback] The command result callback - */ -function parallelCollectionScan(coll, options, callback) { - // Create command object - const commandObject = { - parallelCollectionScan: coll.collectionName, - numCursors: options.numCursors - }; - - // Do we have a readConcern specified - decorateWithReadConcern(commandObject, coll, options); - - // Store the raw value - const raw = options.raw; - delete options['raw']; - - // Execute the command - executeCommand(coll.s.db, commandObject, options, (err, result) => { - if (err) return handleCallback(callback, err, null); - if (result == null) - return handleCallback( - callback, - new Error('no result returned for parallelCollectionScan'), - null - ); - - options = Object.assign({ explicitlyIgnoreSession: true }, options); - - const cursors = []; - // Add the raw back to the option - if (raw) options.raw = raw; - // Create command cursors for each item - for (let i = 0; i < result.cursors.length; i++) { - const rawId = result.cursors[i].cursor.id; - // Convert cursorId to Long if needed - const cursorId = typeof rawId === 'number' ? Long.fromNumber(rawId) : rawId; - // Add a command cursor - cursors.push(coll.s.topology.cursor(coll.namespace, cursorId, options)); - } - - handleCallback(callback, null, cursors); - }); -} - -/** - * Save a document. - * - * @method - * @param {Collection} a Collection instance. - * @param {object} doc Document to save - * @param {object} [options] Optional settings. See Collection.prototype.save for a list of options. - * @param {Collection~writeOpCallback} [callback] The command result callback - * @deprecated use insertOne, insertMany, updateOne or updateMany - */ -function save(coll, doc, options, callback) { - // Get the write concern options - const finalOptions = applyWriteConcern( - Object.assign({}, options), - { db: coll.s.db, collection: coll }, - options - ); - // Establish if we need to perform an insert or update - if (doc._id != null) { - finalOptions.upsert = true; - return updateDocuments(coll, { _id: doc._id }, doc, finalOptions, callback); - } - - // Insert the document - insertDocuments(coll, [doc], finalOptions, (err, result) => { - if (callback == null) return; - if (doc == null) return handleCallback(callback, null, null); - if (err) return handleCallback(callback, err, null); - handleCallback(callback, null, result); - }); -} - -module.exports = { - checkForAtomicOperators, - createIndex, - createIndexes, - ensureIndex, - group, - indexes, - indexExists, - indexInformation, - parallelCollectionScan, - save -}; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/collections.js b/scripts/2.5/node_modules/mongodb/lib/operations/collections.js deleted file mode 100644 index eac690a2..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/operations/collections.js +++ /dev/null @@ -1,55 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const handleCallback = require('../utils').handleCallback; - -let collection; -function loadCollection() { - if (!collection) { - collection = require('../collection'); - } - return collection; -} - -class CollectionsOperation extends OperationBase { - constructor(db, options) { - super(options); - - this.db = db; - } - - execute(callback) { - const db = this.db; - let options = this.options; - - let Collection = loadCollection(); - - options = Object.assign({}, options, { nameOnly: true }); - // Let's get the collection names - db.listCollections({}, options).toArray((err, documents) => { - if (err != null) return handleCallback(callback, err, null); - // Filter collections removing any illegal ones - documents = documents.filter(doc => { - return doc.name.indexOf('$') === -1; - }); - - // Return the collection objects - handleCallback( - callback, - null, - documents.map(d => { - return new Collection( - db, - db.s.topology, - db.databaseName, - d.name, - db.s.pkFactory, - db.s.options - ); - }) - ); - }); - } -} - -module.exports = CollectionsOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/command.js b/scripts/2.5/node_modules/mongodb/lib/operations/command.js deleted file mode 100644 index 3c795bef..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/operations/command.js +++ /dev/null @@ -1,120 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const OperationBase = require('./operation').OperationBase; -const applyWriteConcern = require('../utils').applyWriteConcern; -const debugOptions = require('../utils').debugOptions; -const handleCallback = require('../utils').handleCallback; -const MongoError = require('../core').MongoError; -const ReadPreference = require('../core').ReadPreference; -const resolveReadPreference = require('../utils').resolveReadPreference; -const MongoDBNamespace = require('../utils').MongoDBNamespace; - -const debugFields = [ - 'authSource', - 'w', - 'wtimeout', - 'j', - 'native_parser', - 'forceServerObjectId', - 'serializeFunctions', - 'raw', - 'promoteLongs', - 'promoteValues', - 'promoteBuffers', - 'bufferMaxEntries', - 'numberOfRetries', - 'retryMiliSeconds', - 'readPreference', - 'pkFactory', - 'parentDb', - 'promiseLibrary', - 'noListener' -]; - -class CommandOperation extends OperationBase { - constructor(db, options, collection, command) { - super(options); - - if (!this.hasAspect(Aspect.WRITE_OPERATION)) { - if (collection != null) { - this.options.readPreference = resolveReadPreference(collection, options); - } else { - this.options.readPreference = resolveReadPreference(db, options); - } - } else { - if (collection != null) { - applyWriteConcern(this.options, { db, coll: collection }, this.options); - } else { - applyWriteConcern(this.options, { db }, this.options); - } - this.options.readPreference = ReadPreference.primary; - } - - this.db = db; - - if (command != null) { - this.command = command; - } - - if (collection != null) { - this.collection = collection; - } - } - - _buildCommand() { - if (this.command != null) { - return this.command; - } - } - - execute(callback) { - const db = this.db; - const options = Object.assign({}, this.options); - - // Did the user destroy the topology - if (db.serverConfig && db.serverConfig.isDestroyed()) { - return callback(new MongoError('topology was destroyed')); - } - - let command; - try { - command = this._buildCommand(); - } catch (e) { - return callback(e); - } - - // Get the db name we are executing against - const dbName = options.dbName || options.authdb || db.databaseName; - - // Convert the readPreference if its not a write - if (this.hasAspect(Aspect.WRITE_OPERATION)) { - if (options.writeConcern && (!options.session || !options.session.inTransaction())) { - command.writeConcern = options.writeConcern; - } - } - - // Debug information - if (db.s.logger.isDebug()) { - db.s.logger.debug( - `executing command ${JSON.stringify( - command - )} against ${dbName}.$cmd with options [${JSON.stringify( - debugOptions(debugFields, options) - )}]` - ); - } - - const namespace = - this.namespace != null ? this.namespace : new MongoDBNamespace(dbName, '$cmd'); - - // Execute command - db.s.topology.command(namespace, command, options, (err, result) => { - if (err) return handleCallback(callback, err); - if (options.full) return handleCallback(callback, null, result); - handleCallback(callback, null, result.result); - }); - } -} - -module.exports = CommandOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/command_v2.js b/scripts/2.5/node_modules/mongodb/lib/operations/command_v2.js deleted file mode 100644 index 8df703fd..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/operations/command_v2.js +++ /dev/null @@ -1,109 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const OperationBase = require('./operation').OperationBase; -const resolveReadPreference = require('../utils').resolveReadPreference; -const ReadConcern = require('../read_concern'); -const WriteConcern = require('../write_concern'); -const maxWireVersion = require('../core/utils').maxWireVersion; -const commandSupportsReadConcern = require('../core/sessions').commandSupportsReadConcern; -const MongoError = require('../error').MongoError; - -const SUPPORTS_WRITE_CONCERN_AND_COLLATION = 5; - -class CommandOperationV2 extends OperationBase { - constructor(parent, options, operationOptions) { - super(options); - - this.ns = parent.s.namespace.withCollection('$cmd'); - this.readPreference = resolveReadPreference(parent, this.options); - this.readConcern = resolveReadConcern(parent, this.options); - this.writeConcern = resolveWriteConcern(parent, this.options); - this.explain = false; - - if (operationOptions && typeof operationOptions.fullResponse === 'boolean') { - this.fullResponse = true; - } - - // TODO: A lot of our code depends on having the read preference in the options. This should - // go away, but also requires massive test rewrites. - this.options.readPreference = this.readPreference; - - // TODO(NODE-2056): make logger another "inheritable" property - if (parent.s.logger) { - this.logger = parent.s.logger; - } else if (parent.s.db && parent.s.db.logger) { - this.logger = parent.s.db.logger; - } - } - - executeCommand(server, cmd, callback) { - // TODO: consider making this a non-enumerable property - this.server = server; - - const options = this.options; - const serverWireVersion = maxWireVersion(server); - const inTransaction = this.session && this.session.inTransaction(); - - if (this.readConcern && commandSupportsReadConcern(cmd) && !inTransaction) { - Object.assign(cmd, { readConcern: this.readConcern }); - } - - if (options.collation && serverWireVersion < SUPPORTS_WRITE_CONCERN_AND_COLLATION) { - callback( - new MongoError( - `Server ${ - server.name - }, which reports wire version ${serverWireVersion}, does not support collation` - ) - ); - return; - } - - if (serverWireVersion >= SUPPORTS_WRITE_CONCERN_AND_COLLATION) { - if (this.writeConcern && this.hasAspect(Aspect.WRITE_OPERATION)) { - Object.assign(cmd, { writeConcern: this.writeConcern }); - } - - if (options.collation && typeof options.collation === 'object') { - Object.assign(cmd, { collation: options.collation }); - } - } - - if (typeof options.maxTimeMS === 'number') { - cmd.maxTimeMS = options.maxTimeMS; - } - - if (typeof options.comment === 'string') { - cmd.comment = options.comment; - } - - if (this.logger && this.logger.isDebug()) { - this.logger.debug(`executing command ${JSON.stringify(cmd)} against ${this.ns}`); - } - - server.command(this.ns.toString(), cmd, this.options, (err, result) => { - if (err) { - callback(err, null); - return; - } - - if (this.fullResponse) { - callback(null, result); - return; - } - - callback(null, result.result); - }); - } -} - -function resolveWriteConcern(parent, options) { - return WriteConcern.fromOptions(options) || parent.writeConcern; -} - -function resolveReadConcern(parent, options) { - return ReadConcern.fromOptions(options) || parent.readConcern; -} - -module.exports = CommandOperationV2; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/common_functions.js b/scripts/2.5/node_modules/mongodb/lib/operations/common_functions.js deleted file mode 100644 index 20c2bc9a..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/operations/common_functions.js +++ /dev/null @@ -1,406 +0,0 @@ -'use strict'; - -const applyRetryableWrites = require('../utils').applyRetryableWrites; -const applyWriteConcern = require('../utils').applyWriteConcern; -const decorateWithCollation = require('../utils').decorateWithCollation; -const decorateWithReadConcern = require('../utils').decorateWithReadConcern; -const executeCommand = require('./db_ops').executeCommand; -const formattedOrderClause = require('../utils').formattedOrderClause; -const handleCallback = require('../utils').handleCallback; -const MongoError = require('../core').MongoError; -const ReadPreference = require('../core').ReadPreference; -const toError = require('../utils').toError; -const CursorState = require('../core/cursor').CursorState; - -/** - * Build the count command. - * - * @method - * @param {collectionOrCursor} an instance of a collection or cursor - * @param {object} query The query for the count. - * @param {object} [options] Optional settings. See Collection.prototype.count and Cursor.prototype.count for a list of options. - */ -function buildCountCommand(collectionOrCursor, query, options) { - const skip = options.skip; - const limit = options.limit; - let hint = options.hint; - const maxTimeMS = options.maxTimeMS; - query = query || {}; - - // Final query - const cmd = { - count: options.collectionName, - query: query - }; - - if (collectionOrCursor.s.numberOfRetries) { - // collectionOrCursor is a cursor - if (collectionOrCursor.options.hint) { - hint = collectionOrCursor.options.hint; - } else if (collectionOrCursor.cmd.hint) { - hint = collectionOrCursor.cmd.hint; - } - decorateWithCollation(cmd, collectionOrCursor, collectionOrCursor.cmd); - } else { - decorateWithCollation(cmd, collectionOrCursor, options); - } - - // Add limit, skip and maxTimeMS if defined - if (typeof skip === 'number') cmd.skip = skip; - if (typeof limit === 'number') cmd.limit = limit; - if (typeof maxTimeMS === 'number') cmd.maxTimeMS = maxTimeMS; - if (hint) cmd.hint = hint; - - // Do we have a readConcern specified - decorateWithReadConcern(cmd, collectionOrCursor); - - return cmd; -} - -function deleteCallback(err, r, callback) { - if (callback == null) return; - if (err && callback) return callback(err); - if (r == null) return callback(null, { result: { ok: 1 } }); - r.deletedCount = r.result.n; - if (callback) callback(null, r); -} - -/** - * Find and update a document. - * - * @method - * @param {Collection} a Collection instance. - * @param {object} query Query object to locate the object to modify. - * @param {array} sort If multiple docs match, choose the first one in the specified sort order as the object to manipulate. - * @param {object} doc The fields/vals to be updated. - * @param {object} [options] Optional settings. See Collection.prototype.findAndModify for a list of options. - * @param {Collection~findAndModifyCallback} [callback] The command result callback - * @deprecated use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead - */ -function findAndModify(coll, query, sort, doc, options, callback) { - // Create findAndModify command object - const queryObject = { - findAndModify: coll.collectionName, - query: query - }; - - sort = formattedOrderClause(sort); - if (sort) { - queryObject.sort = sort; - } - - queryObject.new = options.new ? true : false; - queryObject.remove = options.remove ? true : false; - queryObject.upsert = options.upsert ? true : false; - - const projection = options.projection || options.fields; - - if (projection) { - queryObject.fields = projection; - } - - if (options.arrayFilters) { - queryObject.arrayFilters = options.arrayFilters; - delete options.arrayFilters; - } - - if (doc && !options.remove) { - queryObject.update = doc; - } - - if (options.maxTimeMS) queryObject.maxTimeMS = options.maxTimeMS; - - // Either use override on the function, or go back to default on either the collection - // level or db - options.serializeFunctions = options.serializeFunctions || coll.s.serializeFunctions; - - // No check on the documents - options.checkKeys = false; - - // Final options for retryable writes and write concern - let finalOptions = Object.assign({}, options); - finalOptions = applyRetryableWrites(finalOptions, coll.s.db); - finalOptions = applyWriteConcern(finalOptions, { db: coll.s.db, collection: coll }, options); - - // Decorate the findAndModify command with the write Concern - if (finalOptions.writeConcern) { - queryObject.writeConcern = finalOptions.writeConcern; - } - - // Have we specified bypassDocumentValidation - if (finalOptions.bypassDocumentValidation === true) { - queryObject.bypassDocumentValidation = finalOptions.bypassDocumentValidation; - } - - finalOptions.readPreference = ReadPreference.primary; - - // Have we specified collation - try { - decorateWithCollation(queryObject, coll, finalOptions); - } catch (err) { - return callback(err, null); - } - - // Execute the command - executeCommand(coll.s.db, queryObject, finalOptions, (err, result) => { - if (err) return handleCallback(callback, err, null); - - return handleCallback(callback, null, result); - }); -} - -/** - * Retrieves this collections index info. - * - * @method - * @param {Db} db The Db instance on which to retrieve the index info. - * @param {string} name The name of the collection. - * @param {object} [options] Optional settings. See Db.prototype.indexInformation for a list of options. - * @param {Db~resultCallback} [callback] The command result callback - */ -function indexInformation(db, name, options, callback) { - // If we specified full information - const full = options['full'] == null ? false : options['full']; - - // Did the user destroy the topology - if (db.serverConfig && db.serverConfig.isDestroyed()) - return callback(new MongoError('topology was destroyed')); - // Process all the results from the index command and collection - function processResults(indexes) { - // Contains all the information - let info = {}; - // Process all the indexes - for (let i = 0; i < indexes.length; i++) { - const index = indexes[i]; - // Let's unpack the object - info[index.name] = []; - for (let name in index.key) { - info[index.name].push([name, index.key[name]]); - } - } - - return info; - } - - // Get the list of indexes of the specified collection - db - .collection(name) - .listIndexes(options) - .toArray((err, indexes) => { - if (err) return callback(toError(err)); - if (!Array.isArray(indexes)) return handleCallback(callback, null, []); - if (full) return handleCallback(callback, null, indexes); - handleCallback(callback, null, processResults(indexes)); - }); -} - -function prepareDocs(coll, docs, options) { - const forceServerObjectId = - typeof options.forceServerObjectId === 'boolean' - ? options.forceServerObjectId - : coll.s.db.options.forceServerObjectId; - - // no need to modify the docs if server sets the ObjectId - if (forceServerObjectId === true) { - return docs; - } - - return docs.map(doc => { - if (forceServerObjectId !== true && doc._id == null) { - doc._id = coll.s.pkFactory.createPk(); - } - - return doc; - }); -} - -// Get the next available document from the cursor, returns null if no more documents are available. -function nextObject(cursor, callback) { - if (cursor.s.state === CursorState.CLOSED || (cursor.isDead && cursor.isDead())) { - return handleCallback( - callback, - MongoError.create({ message: 'Cursor is closed', driver: true }) - ); - } - - if (cursor.s.state === CursorState.INIT && cursor.cmd && cursor.cmd.sort) { - try { - cursor.cmd.sort = formattedOrderClause(cursor.cmd.sort); - } catch (err) { - return handleCallback(callback, err); - } - } - - // Get the next object - cursor._next((err, doc) => { - cursor.s.state = CursorState.OPEN; - if (err) return handleCallback(callback, err); - handleCallback(callback, null, doc); - }); -} - -function insertDocuments(coll, docs, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - // Ensure we are operating on an array op docs - docs = Array.isArray(docs) ? docs : [docs]; - - // Final options for retryable writes and write concern - let finalOptions = Object.assign({}, options); - finalOptions = applyRetryableWrites(finalOptions, coll.s.db); - finalOptions = applyWriteConcern(finalOptions, { db: coll.s.db, collection: coll }, options); - - // If keep going set unordered - if (finalOptions.keepGoing === true) finalOptions.ordered = false; - finalOptions.serializeFunctions = options.serializeFunctions || coll.s.serializeFunctions; - - docs = prepareDocs(coll, docs, options); - - // File inserts - coll.s.topology.insert(coll.s.namespace, docs, finalOptions, (err, result) => { - if (callback == null) return; - if (err) return handleCallback(callback, err); - if (result == null) return handleCallback(callback, null, null); - if (result.result.code) return handleCallback(callback, toError(result.result)); - if (result.result.writeErrors) - return handleCallback(callback, toError(result.result.writeErrors[0])); - // Add docs to the list - result.ops = docs; - // Return the results - handleCallback(callback, null, result); - }); -} - -function removeDocuments(coll, selector, options, callback) { - if (typeof options === 'function') { - (callback = options), (options = {}); - } else if (typeof selector === 'function') { - callback = selector; - options = {}; - selector = {}; - } - - // Create an empty options object if the provided one is null - options = options || {}; - - // Final options for retryable writes and write concern - let finalOptions = Object.assign({}, options); - finalOptions = applyRetryableWrites(finalOptions, coll.s.db); - finalOptions = applyWriteConcern(finalOptions, { db: coll.s.db, collection: coll }, options); - - // If selector is null set empty - if (selector == null) selector = {}; - - // Build the op - const op = { q: selector, limit: 0 }; - if (options.single) { - op.limit = 1; - } else if (finalOptions.retryWrites) { - finalOptions.retryWrites = false; - } - - // Have we specified collation - try { - decorateWithCollation(finalOptions, coll, options); - } catch (err) { - return callback(err, null); - } - - // Execute the remove - coll.s.topology.remove(coll.s.namespace, [op], finalOptions, (err, result) => { - if (callback == null) return; - if (err) return handleCallback(callback, err, null); - if (result == null) return handleCallback(callback, null, null); - if (result.result.code) return handleCallback(callback, toError(result.result)); - if (result.result.writeErrors) { - return handleCallback(callback, toError(result.result.writeErrors[0])); - } - - // Return the results - handleCallback(callback, null, result); - }); -} - -function updateDocuments(coll, selector, document, options, callback) { - if ('function' === typeof options) (callback = options), (options = null); - if (options == null) options = {}; - if (!('function' === typeof callback)) callback = null; - - // If we are not providing a selector or document throw - if (selector == null || typeof selector !== 'object') - return callback(toError('selector must be a valid JavaScript object')); - if (document == null || typeof document !== 'object') - return callback(toError('document must be a valid JavaScript object')); - - // Final options for retryable writes and write concern - let finalOptions = Object.assign({}, options); - finalOptions = applyRetryableWrites(finalOptions, coll.s.db); - finalOptions = applyWriteConcern(finalOptions, { db: coll.s.db, collection: coll }, options); - - // Do we return the actual result document - // Either use override on the function, or go back to default on either the collection - // level or db - finalOptions.serializeFunctions = options.serializeFunctions || coll.s.serializeFunctions; - - // Execute the operation - const op = { q: selector, u: document }; - op.upsert = options.upsert !== void 0 ? !!options.upsert : false; - op.multi = options.multi !== void 0 ? !!options.multi : false; - - if (finalOptions.arrayFilters) { - op.arrayFilters = finalOptions.arrayFilters; - delete finalOptions.arrayFilters; - } - - if (finalOptions.retryWrites && op.multi) { - finalOptions.retryWrites = false; - } - - // Have we specified collation - try { - decorateWithCollation(finalOptions, coll, options); - } catch (err) { - return callback(err, null); - } - - // Update options - coll.s.topology.update(coll.s.namespace, [op], finalOptions, (err, result) => { - if (callback == null) return; - if (err) return handleCallback(callback, err, null); - if (result == null) return handleCallback(callback, null, null); - if (result.result.code) return handleCallback(callback, toError(result.result)); - if (result.result.writeErrors) - return handleCallback(callback, toError(result.result.writeErrors[0])); - // Return the results - handleCallback(callback, null, result); - }); -} - -function updateCallback(err, r, callback) { - if (callback == null) return; - if (err) return callback(err); - if (r == null) return callback(null, { result: { ok: 1 } }); - r.modifiedCount = r.result.nModified != null ? r.result.nModified : r.result.n; - r.upsertedId = - Array.isArray(r.result.upserted) && r.result.upserted.length > 0 - ? r.result.upserted[0] // FIXME(major): should be `r.result.upserted[0]._id` - : null; - r.upsertedCount = - Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0; - r.matchedCount = - Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? 0 : r.result.n; - callback(null, r); -} - -module.exports = { - buildCountCommand, - deleteCallback, - findAndModify, - indexInformation, - nextObject, - prepareDocs, - insertDocuments, - removeDocuments, - updateDocuments, - updateCallback -}; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/connect.js b/scripts/2.5/node_modules/mongodb/lib/operations/connect.js deleted file mode 100644 index e8f25187..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/operations/connect.js +++ /dev/null @@ -1,709 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const defineAspects = require('./operation').defineAspects; -const Aspect = require('./operation').Aspect; -const deprecate = require('util').deprecate; -const Logger = require('../core').Logger; -const MongoCredentials = require('../core').MongoCredentials; -const MongoError = require('../core').MongoError; -const Mongos = require('../topologies/mongos'); -const NativeTopology = require('../topologies/native_topology'); -const parse = require('../core').parseConnectionString; -const ReadConcern = require('../read_concern'); -const ReadPreference = require('../core').ReadPreference; -const ReplSet = require('../topologies/replset'); -const Server = require('../topologies/server'); -const ServerSessionPool = require('../core').Sessions.ServerSessionPool; - -let client; -function loadClient() { - if (!client) { - client = require('../mongo_client'); - } - return client; -} - -const legacyParse = deprecate( - require('../url_parser'), - 'current URL string parser is deprecated, and will be removed in a future version. ' + - 'To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.' -); - -const AUTH_MECHANISM_INTERNAL_MAP = { - DEFAULT: 'default', - 'MONGODB-CR': 'mongocr', - PLAIN: 'plain', - 'MONGODB-X509': 'x509', - 'SCRAM-SHA-1': 'scram-sha-1', - 'SCRAM-SHA-256': 'scram-sha-256' -}; - -const monitoringEvents = [ - 'timeout', - 'close', - 'serverOpening', - 'serverDescriptionChanged', - 'serverHeartbeatStarted', - 'serverHeartbeatSucceeded', - 'serverHeartbeatFailed', - 'serverClosed', - 'topologyOpening', - 'topologyClosed', - 'topologyDescriptionChanged', - 'commandStarted', - 'commandSucceeded', - 'commandFailed', - 'joined', - 'left', - 'ping', - 'ha', - 'all', - 'fullsetup', - 'open' -]; - -const VALID_AUTH_MECHANISMS = new Set([ - 'DEFAULT', - 'MONGODB-CR', - 'PLAIN', - 'MONGODB-X509', - 'SCRAM-SHA-1', - 'SCRAM-SHA-256', - 'GSSAPI' -]); - -const validOptionNames = [ - 'poolSize', - 'ssl', - 'sslValidate', - 'sslCA', - 'sslCert', - 'sslKey', - 'sslPass', - 'sslCRL', - 'autoReconnect', - 'noDelay', - 'keepAlive', - 'keepAliveInitialDelay', - 'connectTimeoutMS', - 'family', - 'socketTimeoutMS', - 'reconnectTries', - 'reconnectInterval', - 'ha', - 'haInterval', - 'replicaSet', - 'secondaryAcceptableLatencyMS', - 'acceptableLatencyMS', - 'connectWithNoPrimary', - 'authSource', - 'w', - 'wtimeout', - 'j', - 'forceServerObjectId', - 'serializeFunctions', - 'ignoreUndefined', - 'raw', - 'bufferMaxEntries', - 'readPreference', - 'pkFactory', - 'promiseLibrary', - 'readConcern', - 'maxStalenessSeconds', - 'loggerLevel', - 'logger', - 'promoteValues', - 'promoteBuffers', - 'promoteLongs', - 'domainsEnabled', - 'checkServerIdentity', - 'validateOptions', - 'appname', - 'auth', - 'user', - 'password', - 'authMechanism', - 'compression', - 'fsync', - 'readPreferenceTags', - 'numberOfRetries', - 'auto_reconnect', - 'minSize', - 'monitorCommands', - 'retryWrites', - 'retryReads', - 'useNewUrlParser', - 'useUnifiedTopology', - 'serverSelectionTimeoutMS', - 'useRecoveryToken', - 'autoEncryption' -]; - -const ignoreOptionNames = ['native_parser']; -const legacyOptionNames = ['server', 'replset', 'replSet', 'mongos', 'db']; - -// Validate options object -function validOptions(options) { - const _validOptions = validOptionNames.concat(legacyOptionNames); - - for (const name in options) { - if (ignoreOptionNames.indexOf(name) !== -1) { - continue; - } - - if (_validOptions.indexOf(name) === -1) { - if (options.validateOptions) { - return new MongoError(`option ${name} is not supported`); - } else { - console.warn(`the options [${name}] is not supported`); - } - } - - if (legacyOptionNames.indexOf(name) !== -1) { - console.warn( - `the server/replset/mongos/db options are deprecated, ` + - `all their options are supported at the top level of the options object [${validOptionNames}]` - ); - } - } -} - -const LEGACY_OPTIONS_MAP = validOptionNames.reduce((obj, name) => { - obj[name.toLowerCase()] = name; - return obj; -}, {}); - -class ConnectOperation extends OperationBase { - constructor(mongoClient) { - super(); - - this.mongoClient = mongoClient; - } - - execute(callback) { - const mongoClient = this.mongoClient; - const err = validOptions(mongoClient.s.options); - - // Did we have a validation error - if (err) return callback(err); - // Fallback to callback based connect - connect(mongoClient, mongoClient.s.url, mongoClient.s.options, err => { - if (err) return callback(err); - callback(null, mongoClient); - }); - } -} -defineAspects(ConnectOperation, [Aspect.SKIP_SESSION]); - -function addListeners(mongoClient, topology) { - topology.on('authenticated', createListener(mongoClient, 'authenticated')); - topology.on('error', createListener(mongoClient, 'error')); - topology.on('timeout', createListener(mongoClient, 'timeout')); - topology.on('close', createListener(mongoClient, 'close')); - topology.on('parseError', createListener(mongoClient, 'parseError')); - topology.once('open', createListener(mongoClient, 'open')); - topology.once('fullsetup', createListener(mongoClient, 'fullsetup')); - topology.once('all', createListener(mongoClient, 'all')); - topology.on('reconnect', createListener(mongoClient, 'reconnect')); -} - -function assignTopology(client, topology) { - client.topology = topology; - topology.s.sessionPool = - topology instanceof NativeTopology - ? new ServerSessionPool(topology) - : new ServerSessionPool(topology.s.coreTopology); -} - -// Clear out all events -function clearAllEvents(topology) { - monitoringEvents.forEach(event => topology.removeAllListeners(event)); -} - -// Collect all events in order from SDAM -function collectEvents(mongoClient, topology) { - let MongoClient = loadClient(); - const collectedEvents = []; - - if (mongoClient instanceof MongoClient) { - monitoringEvents.forEach(event => { - topology.on(event, (object1, object2) => { - if (event === 'open') { - collectedEvents.push({ event: event, object1: mongoClient }); - } else { - collectedEvents.push({ event: event, object1: object1, object2: object2 }); - } - }); - }); - } - - return collectedEvents; -} - -const emitDeprecationForNonUnifiedTopology = deprecate(() => {}, -'current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. ' + 'To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.'); - -function connect(mongoClient, url, options, callback) { - options = Object.assign({}, options); - - // If callback is null throw an exception - if (callback == null) { - throw new Error('no callback function provided'); - } - - let didRequestAuthentication = false; - const logger = Logger('MongoClient', options); - - // Did we pass in a Server/ReplSet/Mongos - if (url instanceof Server || url instanceof ReplSet || url instanceof Mongos) { - return connectWithUrl(mongoClient, url, options, connectCallback); - } - - const useNewUrlParser = options.useNewUrlParser !== false; - - const parseFn = useNewUrlParser ? parse : legacyParse; - const transform = useNewUrlParser ? transformUrlOptions : legacyTransformUrlOptions; - - parseFn(url, options, (err, _object) => { - // Do not attempt to connect if parsing error - if (err) return callback(err); - - // Flatten - const object = transform(_object); - - // Parse the string - const _finalOptions = createUnifiedOptions(object, options); - - // Check if we have connection and socket timeout set - if (_finalOptions.socketTimeoutMS == null) _finalOptions.socketTimeoutMS = 360000; - if (_finalOptions.connectTimeoutMS == null) _finalOptions.connectTimeoutMS = 30000; - if (_finalOptions.retryWrites == null) _finalOptions.retryWrites = true; - if (_finalOptions.useRecoveryToken == null) _finalOptions.useRecoveryToken = true; - if (_finalOptions.readPreference == null) _finalOptions.readPreference = 'primary'; - - if (_finalOptions.db_options && _finalOptions.db_options.auth) { - delete _finalOptions.db_options.auth; - } - - // Store the merged options object - mongoClient.s.options = _finalOptions; - - // Failure modes - if (object.servers.length === 0) { - return callback(new Error('connection string must contain at least one seed host')); - } - - if (_finalOptions.auth && !_finalOptions.credentials) { - try { - didRequestAuthentication = true; - _finalOptions.credentials = generateCredentials( - mongoClient, - _finalOptions.auth.user, - _finalOptions.auth.password, - _finalOptions - ); - } catch (err) { - return callback(err); - } - } - - if (_finalOptions.useUnifiedTopology) { - return createTopology(mongoClient, 'unified', _finalOptions, connectCallback); - } - - emitDeprecationForNonUnifiedTopology(); - - // Do we have a replicaset then skip discovery and go straight to connectivity - if (_finalOptions.replicaSet || _finalOptions.rs_name) { - return createTopology(mongoClient, 'replicaset', _finalOptions, connectCallback); - } else if (object.servers.length > 1) { - return createTopology(mongoClient, 'mongos', _finalOptions, connectCallback); - } else { - return createServer(mongoClient, _finalOptions, connectCallback); - } - }); - - function connectCallback(err, topology) { - const warningMessage = `seed list contains no mongos proxies, replicaset connections requires the parameter replicaSet to be supplied in the URI or options object, mongodb://server:port/db?replicaSet=name`; - if (err && err.message === 'no mongos proxies found in seed list') { - if (logger.isWarn()) { - logger.warn(warningMessage); - } - - // Return a more specific error message for MongoClient.connect - return callback(new MongoError(warningMessage)); - } - - if (didRequestAuthentication) { - mongoClient.emit('authenticated', null, true); - } - - // Return the error and db instance - callback(err, topology); - } -} - -function connectWithUrl(mongoClient, url, options, connectCallback) { - // Set the topology - assignTopology(mongoClient, url); - - // Add listeners - addListeners(mongoClient, url); - - // Propagate the events to the client - relayEvents(mongoClient, url); - - let finalOptions = Object.assign({}, options); - - // If we have a readPreference passed in by the db options, convert it from a string - if (typeof options.readPreference === 'string' || typeof options.read_preference === 'string') { - finalOptions.readPreference = new ReadPreference( - options.readPreference || options.read_preference - ); - } - - const isDoingAuth = finalOptions.user || finalOptions.password || finalOptions.authMechanism; - if (isDoingAuth && !finalOptions.credentials) { - try { - finalOptions.credentials = generateCredentials( - mongoClient, - finalOptions.user, - finalOptions.password, - finalOptions - ); - } catch (err) { - return connectCallback(err, url); - } - } - - return url.connect(finalOptions, connectCallback); -} - -function createListener(mongoClient, event) { - const eventSet = new Set(['all', 'fullsetup', 'open', 'reconnect']); - return (v1, v2) => { - if (eventSet.has(event)) { - return mongoClient.emit(event, mongoClient); - } - - mongoClient.emit(event, v1, v2); - }; -} - -function createServer(mongoClient, options, callback) { - // Pass in the promise library - options.promiseLibrary = mongoClient.s.promiseLibrary; - - // Set default options - const servers = translateOptions(options); - - const server = servers[0]; - - // Propagate the events to the client - const collectedEvents = collectEvents(mongoClient, server); - - // Connect to topology - server.connect(options, (err, topology) => { - if (err) { - server.close(true); - return callback(err); - } - // Clear out all the collected event listeners - clearAllEvents(server); - - // Relay all the events - relayEvents(mongoClient, server); - // Add listeners - addListeners(mongoClient, server); - // Check if we are really speaking to a mongos - const ismaster = topology.lastIsMaster(); - - // Set the topology - assignTopology(mongoClient, topology); - - // Do we actually have a mongos - if (ismaster && ismaster.msg === 'isdbgrid') { - // Destroy the current connection - topology.close(); - // Create mongos connection instead - return createTopology(mongoClient, 'mongos', options, callback); - } - - // Fire all the events - replayEvents(mongoClient, collectedEvents); - // Otherwise callback - callback(err, topology); - }); -} - -function createTopology(mongoClient, topologyType, options, callback) { - // Pass in the promise library - options.promiseLibrary = mongoClient.s.promiseLibrary; - - const translationOptions = {}; - if (topologyType === 'unified') translationOptions.createServers = false; - - // Set default options - const servers = translateOptions(options, translationOptions); - - // Create the topology - let topology; - if (topologyType === 'mongos') { - topology = new Mongos(servers, options); - } else if (topologyType === 'replicaset') { - topology = new ReplSet(servers, options); - } else if (topologyType === 'unified') { - topology = new NativeTopology(options.servers, options); - } - - // Add listeners - addListeners(mongoClient, topology); - - // Propagate the events to the client - relayEvents(mongoClient, topology); - - // Open the connection - assignTopology(mongoClient, topology); - topology.connect(options, err => { - if (err) { - topology.close(true); - return callback(err); - } - - if (options.autoEncryption == null) { - callback(null, topology); - return; - } - - // setup for client side encryption - let AutoEncrypter; - try { - require.resolve('mongodb-client-encryption'); - } catch (err) { - callback( - new MongoError( - 'Auto-encryption requested, but the module is not installed. Please add `mongodb-client-encryption` as a dependency of your project' - ) - ); - return; - } - try { - AutoEncrypter = require('mongodb-client-encryption')(require('../../index')).AutoEncrypter; - } catch (err) { - callback(err); - return; - } - - const mongoCryptOptions = Object.assign({}, options.autoEncryption); - topology.s.options.autoEncrypter = new AutoEncrypter(mongoClient, mongoCryptOptions); - topology.s.options.autoEncrypter.init(err => { - if (err) return callback(err, null); - callback(null, topology); - }); - }); -} - -function createUnifiedOptions(finalOptions, options) { - const childOptions = [ - 'mongos', - 'server', - 'db', - 'replset', - 'db_options', - 'server_options', - 'rs_options', - 'mongos_options' - ]; - const noMerge = ['readconcern', 'compression']; - - for (const name in options) { - if (noMerge.indexOf(name.toLowerCase()) !== -1) { - finalOptions[name] = options[name]; - } else if (childOptions.indexOf(name.toLowerCase()) !== -1) { - finalOptions = mergeOptions(finalOptions, options[name], false); - } else { - if ( - options[name] && - typeof options[name] === 'object' && - !Buffer.isBuffer(options[name]) && - !Array.isArray(options[name]) - ) { - finalOptions = mergeOptions(finalOptions, options[name], true); - } else { - finalOptions[name] = options[name]; - } - } - } - - return finalOptions; -} - -function generateCredentials(client, username, password, options) { - options = Object.assign({}, options); - - // the default db to authenticate against is 'self' - // if authententicate is called from a retry context, it may be another one, like admin - const source = options.authSource || options.authdb || options.dbName; - - // authMechanism - const authMechanismRaw = options.authMechanism || 'DEFAULT'; - const authMechanism = authMechanismRaw.toUpperCase(); - - if (!VALID_AUTH_MECHANISMS.has(authMechanism)) { - throw MongoError.create({ - message: `authentication mechanism ${authMechanismRaw} not supported', options.authMechanism`, - driver: true - }); - } - - if (authMechanism === 'GSSAPI') { - return new MongoCredentials({ - mechanism: process.platform === 'win32' ? 'sspi' : 'gssapi', - mechanismProperties: options, - source, - username, - password - }); - } - - return new MongoCredentials({ - mechanism: AUTH_MECHANISM_INTERNAL_MAP[authMechanism], - source, - username, - password - }); -} - -function legacyTransformUrlOptions(object) { - return mergeOptions(createUnifiedOptions({}, object), object, false); -} - -function mergeOptions(target, source, flatten) { - for (const name in source) { - if (source[name] && typeof source[name] === 'object' && flatten) { - target = mergeOptions(target, source[name], flatten); - } else { - target[name] = source[name]; - } - } - - return target; -} - -function relayEvents(mongoClient, topology) { - const serverOrCommandEvents = [ - 'serverOpening', - 'serverDescriptionChanged', - 'serverHeartbeatStarted', - 'serverHeartbeatSucceeded', - 'serverHeartbeatFailed', - 'serverClosed', - 'topologyOpening', - 'topologyClosed', - 'topologyDescriptionChanged', - 'commandStarted', - 'commandSucceeded', - 'commandFailed', - 'joined', - 'left', - 'ping', - 'ha' - ]; - - serverOrCommandEvents.forEach(event => { - topology.on(event, (object1, object2) => { - mongoClient.emit(event, object1, object2); - }); - }); -} - -// -// Replay any events due to single server connection switching to Mongos -// -function replayEvents(mongoClient, events) { - for (let i = 0; i < events.length; i++) { - mongoClient.emit(events[i].event, events[i].object1, events[i].object2); - } -} - -function transformUrlOptions(_object) { - let object = Object.assign({ servers: _object.hosts }, _object.options); - for (let name in object) { - const camelCaseName = LEGACY_OPTIONS_MAP[name]; - if (camelCaseName) { - object[camelCaseName] = object[name]; - } - } - - const hasUsername = _object.auth && _object.auth.username; - const hasAuthMechanism = _object.options && _object.options.authMechanism; - if (hasUsername || hasAuthMechanism) { - object.auth = Object.assign({}, _object.auth); - if (object.auth.db) { - object.authSource = object.authSource || object.auth.db; - } - - if (object.auth.username) { - object.auth.user = object.auth.username; - } - } - - if (_object.defaultDatabase) { - object.dbName = _object.defaultDatabase; - } - - if (object.maxPoolSize) { - object.poolSize = object.maxPoolSize; - } - - if (object.readConcernLevel) { - object.readConcern = new ReadConcern(object.readConcernLevel); - } - - if (object.wTimeoutMS) { - object.wtimeout = object.wTimeoutMS; - } - - if (_object.srvHost) { - object.srvHost = _object.srvHost; - } - - return object; -} - -function translateOptions(options, translationOptions) { - translationOptions = Object.assign({}, { createServers: true }, translationOptions); - - // If we have a readPreference passed in by the db options - if (typeof options.readPreference === 'string' || typeof options.read_preference === 'string') { - options.readPreference = new ReadPreference(options.readPreference || options.read_preference); - } - - // Do we have readPreference tags, add them - if (options.readPreference && (options.readPreferenceTags || options.read_preference_tags)) { - options.readPreference.tags = options.readPreferenceTags || options.read_preference_tags; - } - - // Do we have maxStalenessSeconds - if (options.maxStalenessSeconds) { - options.readPreference.maxStalenessSeconds = options.maxStalenessSeconds; - } - - // Set the socket and connection timeouts - if (options.socketTimeoutMS == null) options.socketTimeoutMS = 360000; - if (options.connectTimeoutMS == null) options.connectTimeoutMS = 30000; - - if (!translationOptions.createServers) { - return; - } - - // Create server instances - return options.servers.map(serverObj => { - return serverObj.domain_socket - ? new Server(serverObj.domain_socket, 27017, options) - : new Server(serverObj.host, serverObj.port, options); - }); -} - -module.exports = ConnectOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/count.js b/scripts/2.5/node_modules/mongodb/lib/operations/count.js deleted file mode 100644 index 5bf03f08..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/operations/count.js +++ /dev/null @@ -1,72 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const buildCountCommand = require('./common_functions').buildCountCommand; -const defineAspects = require('./operation').defineAspects; -const OperationBase = require('./operation').OperationBase; - -class CountOperation extends OperationBase { - constructor(cursor, applySkipLimit, options) { - super(options); - - this.cursor = cursor; - this.applySkipLimit = applySkipLimit; - } - - execute(callback) { - const cursor = this.cursor; - const applySkipLimit = this.applySkipLimit; - const options = this.options; - - if (applySkipLimit) { - if (typeof cursor.cursorSkip() === 'number') options.skip = cursor.cursorSkip(); - if (typeof cursor.cursorLimit() === 'number') options.limit = cursor.cursorLimit(); - } - - // Ensure we have the right read preference inheritance - if (options.readPreference) { - cursor.setReadPreference(options.readPreference); - } - - if ( - typeof options.maxTimeMS !== 'number' && - cursor.cmd && - typeof cursor.cmd.maxTimeMS === 'number' - ) { - options.maxTimeMS = cursor.cmd.maxTimeMS; - } - - let finalOptions = {}; - finalOptions.skip = options.skip; - finalOptions.limit = options.limit; - finalOptions.hint = options.hint; - finalOptions.maxTimeMS = options.maxTimeMS; - - // Command - finalOptions.collectionName = cursor.namespace.collection; - - let command; - try { - command = buildCountCommand(cursor, cursor.cmd.query, finalOptions); - } catch (err) { - return callback(err); - } - - // Set cursor server to the same as the topology - cursor.server = cursor.topology.s.coreTopology; - - // Execute the command - cursor.topology.command( - cursor.namespace.withCollection('$cmd'), - command, - cursor.options, - (err, result) => { - callback(err, result ? result.result.n : null); - } - ); - } -} - -defineAspects(CountOperation, Aspect.SKIP_SESSION); - -module.exports = CountOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/count_documents.js b/scripts/2.5/node_modules/mongodb/lib/operations/count_documents.js deleted file mode 100644 index d043abfa..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/operations/count_documents.js +++ /dev/null @@ -1,41 +0,0 @@ -'use strict'; - -const AggregateOperation = require('./aggregate'); - -class CountDocumentsOperation extends AggregateOperation { - constructor(collection, query, options) { - const pipeline = [{ $match: query }]; - if (typeof options.skip === 'number') { - pipeline.push({ $skip: options.skip }); - } - - if (typeof options.limit === 'number') { - pipeline.push({ $limit: options.limit }); - } - - pipeline.push({ $group: { _id: 1, n: { $sum: 1 } } }); - - super(collection, pipeline, options); - } - - execute(server, callback) { - super.execute(server, (err, result) => { - if (err) { - callback(err, null); - return; - } - - // NOTE: We're avoiding creating a cursor here to reduce the callstack. - const response = result.result; - if (response.cursor == null || response.cursor.firstBatch == null) { - callback(null, 0); - return; - } - - const docs = response.cursor.firstBatch; - callback(null, docs.length ? docs[0].n : 0); - }); - } -} - -module.exports = CountDocumentsOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/create_collection.js b/scripts/2.5/node_modules/mongodb/lib/operations/create_collection.js deleted file mode 100644 index 35c3a6f0..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/operations/create_collection.js +++ /dev/null @@ -1,118 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const defineAspects = require('./operation').defineAspects; -const CommandOperation = require('./command'); -const applyWriteConcern = require('../utils').applyWriteConcern; -const handleCallback = require('../utils').handleCallback; -const loadCollection = require('../dynamic_loaders').loadCollection; -const MongoError = require('../core').MongoError; -const ReadPreference = require('../core').ReadPreference; - -// Filter out any write concern options -const illegalCommandFields = [ - 'w', - 'wtimeout', - 'j', - 'fsync', - 'autoIndexId', - 'strict', - 'serializeFunctions', - 'pkFactory', - 'raw', - 'readPreference', - 'session', - 'readConcern', - 'writeConcern' -]; - -class CreateCollectionOperation extends CommandOperation { - constructor(db, name, options) { - super(db, options); - - this.name = name; - } - - _buildCommand() { - const name = this.name; - const options = this.options; - - // Create collection command - const cmd = { create: name }; - // Add all optional parameters - for (let n in options) { - if ( - options[n] != null && - typeof options[n] !== 'function' && - illegalCommandFields.indexOf(n) === -1 - ) { - cmd[n] = options[n]; - } - } - - return cmd; - } - - execute(callback) { - const db = this.db; - const name = this.name; - const options = this.options; - - let Collection = loadCollection(); - - // Did the user destroy the topology - if (db.serverConfig && db.serverConfig.isDestroyed()) { - return callback(new MongoError('topology was destroyed')); - } - - let listCollectionOptions = Object.assign({}, options, { nameOnly: true }); - listCollectionOptions = applyWriteConcern(listCollectionOptions, { db }, listCollectionOptions); - - // Check if we have the name - db - .listCollections({ name }, listCollectionOptions) - .setReadPreference(ReadPreference.PRIMARY) - .toArray((err, collections) => { - if (err != null) return handleCallback(callback, err, null); - if (collections.length > 0 && listCollectionOptions.strict) { - return handleCallback( - callback, - MongoError.create({ - message: `Collection ${name} already exists. Currently in strict mode.`, - driver: true - }), - null - ); - } else if (collections.length > 0) { - try { - return handleCallback( - callback, - null, - new Collection(db, db.s.topology, db.databaseName, name, db.s.pkFactory, options) - ); - } catch (err) { - return handleCallback(callback, err); - } - } - - // Execute command - super.execute(err => { - if (err) return handleCallback(callback, err); - - try { - return handleCallback( - callback, - null, - new Collection(db, db.s.topology, db.databaseName, name, db.s.pkFactory, options) - ); - } catch (err) { - return handleCallback(callback, err); - } - }); - }); - } -} - -defineAspects(CreateCollectionOperation, Aspect.WRITE_OPERATION); - -module.exports = CreateCollectionOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/create_index.js b/scripts/2.5/node_modules/mongodb/lib/operations/create_index.js deleted file mode 100644 index 98bba71e..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/operations/create_index.js +++ /dev/null @@ -1,92 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const CommandOperation = require('./command'); -const defineAspects = require('./operation').defineAspects; -const handleCallback = require('../utils').handleCallback; -const MongoError = require('../core').MongoError; -const parseIndexOptions = require('../utils').parseIndexOptions; - -const keysToOmit = new Set([ - 'name', - 'key', - 'writeConcern', - 'w', - 'wtimeout', - 'j', - 'fsync', - 'readPreference', - 'session' -]); - -class CreateIndexOperation extends CommandOperation { - constructor(db, name, fieldOrSpec, options) { - super(db, options); - - // Build the index - const indexParameters = parseIndexOptions(fieldOrSpec); - // Generate the index name - const indexName = typeof options.name === 'string' ? options.name : indexParameters.name; - // Set up the index - const indexesObject = { name: indexName, key: indexParameters.fieldHash }; - - this.name = name; - this.fieldOrSpec = fieldOrSpec; - this.indexes = indexesObject; - } - - _buildCommand() { - const options = this.options; - const name = this.name; - const indexes = this.indexes; - - // merge all the options - for (let optionName in options) { - if (!keysToOmit.has(optionName)) { - indexes[optionName] = options[optionName]; - } - } - - // Create command, apply write concern to command - const cmd = { createIndexes: name, indexes: [indexes] }; - - return cmd; - } - - execute(callback) { - const db = this.db; - const options = this.options; - const indexes = this.indexes; - - // Get capabilities - const capabilities = db.s.topology.capabilities(); - - // Did the user pass in a collation, check if our write server supports it - if (options.collation && capabilities && !capabilities.commandsTakeCollation) { - // Create a new error - const error = new MongoError('server/primary/mongos does not support collation'); - error.code = 67; - // Return the error - return callback(error); - } - - // Ensure we have a callback - if (options.writeConcern && typeof callback !== 'function') { - throw MongoError.create({ - message: 'Cannot use a writeConcern without a provided callback', - driver: true - }); - } - - // Attempt to run using createIndexes command - super.execute((err, result) => { - if (err == null) return handleCallback(callback, err, indexes.name); - - return handleCallback(callback, err, result); - }); - } -} - -defineAspects(CreateIndexOperation, Aspect.WRITE_OPERATION); - -module.exports = CreateIndexOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/create_indexes.js b/scripts/2.5/node_modules/mongodb/lib/operations/create_indexes.js deleted file mode 100644 index 46228e8c..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/operations/create_indexes.js +++ /dev/null @@ -1,61 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const defineAspects = require('./operation').defineAspects; -const OperationBase = require('./operation').OperationBase; -const executeCommand = require('./db_ops').executeCommand; -const MongoError = require('../core').MongoError; -const ReadPreference = require('../core').ReadPreference; - -class CreateIndexesOperation extends OperationBase { - constructor(collection, indexSpecs, options) { - super(options); - - this.collection = collection; - this.indexSpecs = indexSpecs; - } - - execute(callback) { - const coll = this.collection; - const indexSpecs = this.indexSpecs; - let options = this.options; - - const capabilities = coll.s.topology.capabilities(); - - // Ensure we generate the correct name if the parameter is not set - for (let i = 0; i < indexSpecs.length; i++) { - if (indexSpecs[i].name == null) { - const keys = []; - - // Did the user pass in a collation, check if our write server supports it - if (indexSpecs[i].collation && capabilities && !capabilities.commandsTakeCollation) { - return callback(new MongoError('server/primary/mongos does not support collation')); - } - - for (let name in indexSpecs[i].key) { - keys.push(`${name}_${indexSpecs[i].key[name]}`); - } - - // Set the name - indexSpecs[i].name = keys.join('_'); - } - } - - options = Object.assign({}, options, { readPreference: ReadPreference.PRIMARY }); - - // Execute the index - executeCommand( - coll.s.db, - { - createIndexes: coll.collectionName, - indexes: indexSpecs - }, - options, - callback - ); - } -} - -defineAspects(CreateIndexesOperation, Aspect.WRITE_OPERATION); - -module.exports = CreateIndexesOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/cursor_ops.js b/scripts/2.5/node_modules/mongodb/lib/operations/cursor_ops.js deleted file mode 100644 index 513624ff..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/operations/cursor_ops.js +++ /dev/null @@ -1,239 +0,0 @@ -'use strict'; - -const buildCountCommand = require('./collection_ops').buildCountCommand; -const formattedOrderClause = require('../utils').formattedOrderClause; -const handleCallback = require('../utils').handleCallback; -const MongoError = require('../core').MongoError; -const push = Array.prototype.push; -const CursorState = require('../core/cursor').CursorState; - -/** - * Get the count of documents for this cursor. - * - * @method - * @param {Cursor} cursor The Cursor instance on which to count. - * @param {boolean} [applySkipLimit=true] Specifies whether the count command apply limit and skip settings should be applied on the cursor or in the provided options. - * @param {object} [options] Optional settings. See Cursor.prototype.count for a list of options. - * @param {Cursor~countResultCallback} [callback] The result callback. - */ -function count(cursor, applySkipLimit, opts, callback) { - if (applySkipLimit) { - if (typeof cursor.cursorSkip() === 'number') opts.skip = cursor.cursorSkip(); - if (typeof cursor.cursorLimit() === 'number') opts.limit = cursor.cursorLimit(); - } - - // Ensure we have the right read preference inheritance - if (opts.readPreference) { - cursor.setReadPreference(opts.readPreference); - } - - if ( - typeof opts.maxTimeMS !== 'number' && - cursor.cmd && - typeof cursor.cmd.maxTimeMS === 'number' - ) { - opts.maxTimeMS = cursor.cmd.maxTimeMS; - } - - let options = {}; - options.skip = opts.skip; - options.limit = opts.limit; - options.hint = opts.hint; - options.maxTimeMS = opts.maxTimeMS; - - // Command - options.collectionName = cursor.namespace.collection; - - let command; - try { - command = buildCountCommand(cursor, cursor.cmd.query, options); - } catch (err) { - return callback(err); - } - - // Set cursor server to the same as the topology - cursor.server = cursor.topology.s.coreTopology; - - // Execute the command - cursor.topology.command( - cursor.namespace.withCollection('$cmd'), - command, - cursor.options, - (err, result) => { - callback(err, result ? result.result.n : null); - } - ); -} - -/** - * Iterates over all the documents for this cursor. See Cursor.prototype.each for more information. - * - * @method - * @deprecated - * @param {Cursor} cursor The Cursor instance on which to run. - * @param {Cursor~resultCallback} callback The result callback. - */ -function each(cursor, callback) { - if (!callback) throw MongoError.create({ message: 'callback is mandatory', driver: true }); - if (cursor.isNotified()) return; - if (cursor.s.state === CursorState.CLOSED || cursor.isDead()) { - return handleCallback( - callback, - MongoError.create({ message: 'Cursor is closed', driver: true }) - ); - } - - if (cursor.s.state === CursorState.INIT) { - cursor.s.state = CursorState.OPEN; - } - - // Define function to avoid global scope escape - let fn = null; - // Trampoline all the entries - if (cursor.bufferedCount() > 0) { - while ((fn = loop(cursor, callback))) fn(cursor, callback); - each(cursor, callback); - } else { - cursor.next((err, item) => { - if (err) return handleCallback(callback, err); - if (item == null) { - return cursor.close({ skipKillCursors: true }, () => handleCallback(callback, null, null)); - } - - if (handleCallback(callback, null, item) === false) return; - each(cursor, callback); - }); - } -} - -/** - * Check if there is any document still available in the cursor. - * - * @method - * @param {Cursor} cursor The Cursor instance on which to run. - * @param {Cursor~resultCallback} [callback] The result callback. - */ -function hasNext(cursor, callback) { - if (cursor.s.currentDoc) { - return callback(null, true); - } - - if (cursor.isNotified()) { - return callback(null, false); - } - - nextObject(cursor, (err, doc) => { - if (err) return callback(err, null); - if (cursor.s.state === CursorState.CLOSED || cursor.isDead()) { - return callback(null, false); - } - - if (!doc) return callback(null, false); - cursor.s.currentDoc = doc; - callback(null, true); - }); -} - -// Trampoline emptying the number of retrieved items -// without incurring a nextTick operation -function loop(cursor, callback) { - // No more items we are done - if (cursor.bufferedCount() === 0) return; - // Get the next document - cursor._next(callback); - // Loop - return loop; -} - -/** - * Get the next available document from the cursor. Returns null if no more documents are available. - * - * @method - * @param {Cursor} cursor The Cursor instance from which to get the next document. - * @param {Cursor~resultCallback} [callback] The result callback. - */ -function next(cursor, callback) { - // Return the currentDoc if someone called hasNext first - if (cursor.s.currentDoc) { - const doc = cursor.s.currentDoc; - cursor.s.currentDoc = null; - return callback(null, doc); - } - - // Return the next object - nextObject(cursor, callback); -} - -// Get the next available document from the cursor, returns null if no more documents are available. -function nextObject(cursor, callback) { - if (cursor.s.state === CursorState.CLOSED || (cursor.isDead && cursor.isDead())) - return handleCallback( - callback, - MongoError.create({ message: 'Cursor is closed', driver: true }) - ); - if (cursor.s.state === CursorState.INIT && cursor.cmd.sort) { - try { - cursor.cmd.sort = formattedOrderClause(cursor.cmd.sort); - } catch (err) { - return handleCallback(callback, err); - } - } - - // Get the next object - cursor._next((err, doc) => { - cursor.s.state = CursorState.OPEN; - if (err) return handleCallback(callback, err); - handleCallback(callback, null, doc); - }); -} - -/** - * Returns an array of documents. See Cursor.prototype.toArray for more information. - * - * @method - * @param {Cursor} cursor The Cursor instance from which to get the next document. - * @param {Cursor~toArrayResultCallback} [callback] The result callback. - */ -function toArray(cursor, callback) { - const items = []; - - // Reset cursor - cursor.rewind(); - cursor.s.state = CursorState.INIT; - - // Fetch all the documents - const fetchDocs = () => { - cursor._next((err, doc) => { - if (err) { - return cursor._endSession - ? cursor._endSession(() => handleCallback(callback, err)) - : handleCallback(callback, err); - } - if (doc == null) { - return cursor.close({ skipKillCursors: true }, () => handleCallback(callback, null, items)); - } - - // Add doc to items - items.push(doc); - - // Get all buffered objects - if (cursor.bufferedCount() > 0) { - let docs = cursor.readBufferedDocuments(cursor.bufferedCount()); - - // Transform the doc if transform method added - if (cursor.s.transforms && typeof cursor.s.transforms.doc === 'function') { - docs = docs.map(cursor.s.transforms.doc); - } - - push.apply(items, docs); - } - - // Attempt a fetch - fetchDocs(); - }); - }; - - fetchDocs(); -} - -module.exports = { count, each, hasNext, next, toArray }; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/db_ops.js b/scripts/2.5/node_modules/mongodb/lib/operations/db_ops.js deleted file mode 100644 index 08037620..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/operations/db_ops.js +++ /dev/null @@ -1,831 +0,0 @@ -'use strict'; - -const applyWriteConcern = require('../utils').applyWriteConcern; -const Code = require('../core').BSON.Code; -const resolveReadPreference = require('../utils').resolveReadPreference; -const crypto = require('crypto'); -const debugOptions = require('../utils').debugOptions; -const handleCallback = require('../utils').handleCallback; -const MongoError = require('../core').MongoError; -const parseIndexOptions = require('../utils').parseIndexOptions; -const ReadPreference = require('../core').ReadPreference; -const toError = require('../utils').toError; -const CONSTANTS = require('../constants'); -const MongoDBNamespace = require('../utils').MongoDBNamespace; - -const count = require('./collection_ops').count; -const findOne = require('./collection_ops').findOne; -const remove = require('./collection_ops').remove; -const updateOne = require('./collection_ops').updateOne; - -let collection; -function loadCollection() { - if (!collection) { - collection = require('../collection'); - } - return collection; -} -let db; -function loadDb() { - if (!db) { - db = require('../db'); - } - return db; -} - -const debugFields = [ - 'authSource', - 'w', - 'wtimeout', - 'j', - 'native_parser', - 'forceServerObjectId', - 'serializeFunctions', - 'raw', - 'promoteLongs', - 'promoteValues', - 'promoteBuffers', - 'bufferMaxEntries', - 'numberOfRetries', - 'retryMiliSeconds', - 'readPreference', - 'pkFactory', - 'parentDb', - 'promiseLibrary', - 'noListener' -]; - -/** - * Add a user to the database. - * @method - * @param {Db} db The Db instance on which to add a user. - * @param {string} username The username. - * @param {string} password The password. - * @param {object} [options] Optional settings. See Db.prototype.addUser for a list of options. - * @param {Db~resultCallback} [callback] The command result callback - */ -function addUser(db, username, password, options, callback) { - let Db = loadDb(); - - // Did the user destroy the topology - if (db.serverConfig && db.serverConfig.isDestroyed()) - return callback(new MongoError('topology was destroyed')); - // Attempt to execute auth command - executeAuthCreateUserCommand(db, username, password, options, (err, r) => { - // We need to perform the backward compatible insert operation - if (err && err.code === -5000) { - const finalOptions = applyWriteConcern(Object.assign({}, options), { db }, options); - - // Use node md5 generator - const md5 = crypto.createHash('md5'); - // Generate keys used for authentication - md5.update(username + ':mongo:' + password); - const userPassword = md5.digest('hex'); - - // If we have another db set - const dbToUse = options.dbName ? new Db(options.dbName, db.s.topology, db.s.options) : db; - - // Fetch a user collection - const collection = dbToUse.collection(CONSTANTS.SYSTEM_USER_COLLECTION); - - // Check if we are inserting the first user - count(collection, {}, finalOptions, (err, count) => { - // We got an error (f.ex not authorized) - if (err != null) return handleCallback(callback, err, null); - // Check if the user exists and update i - const findOptions = Object.assign({ projection: { dbName: 1 } }, finalOptions); - collection.find({ user: username }, findOptions).toArray(err => { - // We got an error (f.ex not authorized) - if (err != null) return handleCallback(callback, err, null); - // Add command keys - finalOptions.upsert = true; - - // We have a user, let's update the password or upsert if not - updateOne( - collection, - { user: username }, - { $set: { user: username, pwd: userPassword } }, - finalOptions, - err => { - if (count === 0 && err) - return handleCallback(callback, null, [{ user: username, pwd: userPassword }]); - if (err) return handleCallback(callback, err, null); - handleCallback(callback, null, [{ user: username, pwd: userPassword }]); - } - ); - }); - }); - - return; - } - - if (err) return handleCallback(callback, err); - handleCallback(callback, err, r); - }); -} - -/** - * Fetch all collections for the current db. - * - * @method - * @param {Db} db The Db instance on which to fetch collections. - * @param {object} [options] Optional settings. See Db.prototype.collections for a list of options. - * @param {Db~collectionsResultCallback} [callback] The results callback - */ -function collections(db, options, callback) { - let Collection = loadCollection(); - - options = Object.assign({}, options, { nameOnly: true }); - // Let's get the collection names - db.listCollections({}, options).toArray((err, documents) => { - if (err != null) return handleCallback(callback, err, null); - // Filter collections removing any illegal ones - documents = documents.filter(doc => { - return doc.name.indexOf('$') === -1; - }); - - // Return the collection objects - handleCallback( - callback, - null, - documents.map(d => { - return new Collection( - db, - db.s.topology, - db.databaseName, - d.name, - db.s.pkFactory, - db.s.options - ); - }) - ); - }); -} - -/** - * Creates an index on the db and collection. - * @method - * @param {Db} db The Db instance on which to create an index. - * @param {string} name Name of the collection to create the index on. - * @param {(string|object)} fieldOrSpec Defines the index. - * @param {object} [options] Optional settings. See Db.prototype.createIndex for a list of options. - * @param {Db~resultCallback} [callback] The command result callback - */ -function createIndex(db, name, fieldOrSpec, options, callback) { - // Get the write concern options - let finalOptions = Object.assign({}, { readPreference: ReadPreference.PRIMARY }, options); - finalOptions = applyWriteConcern(finalOptions, { db }, options); - - // Ensure we have a callback - if (finalOptions.writeConcern && typeof callback !== 'function') { - throw MongoError.create({ - message: 'Cannot use a writeConcern without a provided callback', - driver: true - }); - } - - // Did the user destroy the topology - if (db.serverConfig && db.serverConfig.isDestroyed()) - return callback(new MongoError('topology was destroyed')); - - // Attempt to run using createIndexes command - createIndexUsingCreateIndexes(db, name, fieldOrSpec, finalOptions, (err, result) => { - if (err == null) return handleCallback(callback, err, result); - - /** - * The following errors mean that the server recognized `createIndex` as a command so we don't need to fallback to an insert: - * 67 = 'CannotCreateIndex' (malformed index options) - * 85 = 'IndexOptionsConflict' (index already exists with different options) - * 86 = 'IndexKeySpecsConflict' (index already exists with the same name) - * 11000 = 'DuplicateKey' (couldn't build unique index because of dupes) - * 11600 = 'InterruptedAtShutdown' (interrupted at shutdown) - * 197 = 'InvalidIndexSpecificationOption' (`_id` with `background: true`) - */ - if ( - err.code === 67 || - err.code === 11000 || - err.code === 85 || - err.code === 86 || - err.code === 11600 || - err.code === 197 - ) { - return handleCallback(callback, err, result); - } - - // Create command - const doc = createCreateIndexCommand(db, name, fieldOrSpec, options); - // Set no key checking - finalOptions.checkKeys = false; - // Insert document - db.s.topology.insert( - db.s.namespace.withCollection(CONSTANTS.SYSTEM_INDEX_COLLECTION), - doc, - finalOptions, - (err, result) => { - if (callback == null) return; - if (err) return handleCallback(callback, err); - if (result == null) return handleCallback(callback, null, null); - if (result.result.writeErrors) - return handleCallback(callback, MongoError.create(result.result.writeErrors[0]), null); - handleCallback(callback, null, doc.name); - } - ); - }); -} - -// Add listeners to topology -function createListener(db, e, object) { - function listener(err) { - if (object.listeners(e).length > 0) { - object.emit(e, err, db); - - // Emit on all associated db's if available - for (let i = 0; i < db.s.children.length; i++) { - db.s.children[i].emit(e, err, db.s.children[i]); - } - } - } - return listener; -} - -/** - * Drop a collection from the database, removing it permanently. New accesses will create a new collection. - * - * @method - * @param {Db} db The Db instance on which to drop the collection. - * @param {string} name Name of collection to drop - * @param {Object} [options] Optional settings. See Db.prototype.dropCollection for a list of options. - * @param {Db~resultCallback} [callback] The results callback - */ -function dropCollection(db, name, options, callback) { - executeCommand(db, name, options, (err, result) => { - // Did the user destroy the topology - if (db.serverConfig && db.serverConfig.isDestroyed()) { - return callback(new MongoError('topology was destroyed')); - } - - if (err) return handleCallback(callback, err); - if (result.ok) return handleCallback(callback, null, true); - handleCallback(callback, null, false); - }); -} - -/** - * Drop a database, removing it permanently from the server. - * - * @method - * @param {Db} db The Db instance to drop. - * @param {Object} cmd The command document. - * @param {Object} [options] Optional settings. See Db.prototype.dropDatabase for a list of options. - * @param {Db~resultCallback} [callback] The results callback - */ -function dropDatabase(db, cmd, options, callback) { - executeCommand(db, cmd, options, (err, result) => { - // Did the user destroy the topology - if (db.serverConfig && db.serverConfig.isDestroyed()) { - return callback(new MongoError('topology was destroyed')); - } - - if (callback == null) return; - if (err) return handleCallback(callback, err, null); - handleCallback(callback, null, result.ok ? true : false); - }); -} - -/** - * Ensures that an index exists. If it does not, creates it. - * - * @method - * @param {Db} db The Db instance on which to ensure the index. - * @param {string} name The index name - * @param {(string|object)} fieldOrSpec Defines the index. - * @param {object} [options] Optional settings. See Db.prototype.ensureIndex for a list of options. - * @param {Db~resultCallback} [callback] The command result callback - */ -function ensureIndex(db, name, fieldOrSpec, options, callback) { - // Get the write concern options - const finalOptions = applyWriteConcern({}, { db }, options); - // Create command - const selector = createCreateIndexCommand(db, name, fieldOrSpec, options); - const index_name = selector.name; - - // Did the user destroy the topology - if (db.serverConfig && db.serverConfig.isDestroyed()) - return callback(new MongoError('topology was destroyed')); - - // Merge primary readPreference - finalOptions.readPreference = ReadPreference.PRIMARY; - - // Check if the index already exists - indexInformation(db, name, finalOptions, (err, indexInformation) => { - if (err != null && err.code !== 26) return handleCallback(callback, err, null); - // If the index does not exist, create it - if (indexInformation == null || !indexInformation[index_name]) { - createIndex(db, name, fieldOrSpec, options, callback); - } else { - if (typeof callback === 'function') return handleCallback(callback, null, index_name); - } - }); -} - -/** - * Evaluate JavaScript on the server - * - * @method - * @param {Db} db The Db instance. - * @param {Code} code JavaScript to execute on server. - * @param {(object|array)} parameters The parameters for the call. - * @param {object} [options] Optional settings. See Db.prototype.eval for a list of options. - * @param {Db~resultCallback} [callback] The results callback - * @deprecated Eval is deprecated on MongoDB 3.2 and forward - */ -function evaluate(db, code, parameters, options, callback) { - let finalCode = code; - let finalParameters = []; - - // Did the user destroy the topology - if (db.serverConfig && db.serverConfig.isDestroyed()) - return callback(new MongoError('topology was destroyed')); - - // If not a code object translate to one - if (!(finalCode && finalCode._bsontype === 'Code')) finalCode = new Code(finalCode); - // Ensure the parameters are correct - if (parameters != null && !Array.isArray(parameters) && typeof parameters !== 'function') { - finalParameters = [parameters]; - } else if (parameters != null && Array.isArray(parameters) && typeof parameters !== 'function') { - finalParameters = parameters; - } - - // Create execution selector - let cmd = { $eval: finalCode, args: finalParameters }; - // Check if the nolock parameter is passed in - if (options['nolock']) { - cmd['nolock'] = options['nolock']; - } - - // Set primary read preference - options.readPreference = new ReadPreference(ReadPreference.PRIMARY); - - // Execute the command - executeCommand(db, cmd, options, (err, result) => { - if (err) return handleCallback(callback, err, null); - if (result && result.ok === 1) return handleCallback(callback, null, result.retval); - if (result) - return handleCallback( - callback, - MongoError.create({ message: `eval failed: ${result.errmsg}`, driver: true }), - null - ); - handleCallback(callback, err, result); - }); -} - -/** - * Execute a command - * - * @method - * @param {Db} db The Db instance on which to execute the command. - * @param {object} command The command hash - * @param {object} [options] Optional settings. See Db.prototype.command for a list of options. - * @param {Db~resultCallback} [callback] The command result callback - */ -function executeCommand(db, command, options, callback) { - // Did the user destroy the topology - if (db.serverConfig && db.serverConfig.isDestroyed()) - return callback(new MongoError('topology was destroyed')); - // Get the db name we are executing against - const dbName = options.dbName || options.authdb || db.databaseName; - - // Convert the readPreference if its not a write - options.readPreference = resolveReadPreference(db, options); - - // Debug information - if (db.s.logger.isDebug()) - db.s.logger.debug( - `executing command ${JSON.stringify( - command - )} against ${dbName}.$cmd with options [${JSON.stringify( - debugOptions(debugFields, options) - )}]` - ); - - // Execute command - db.s.topology.command(db.s.namespace.withCollection('$cmd'), command, options, (err, result) => { - if (err) return handleCallback(callback, err); - if (options.full) return handleCallback(callback, null, result); - handleCallback(callback, null, result.result); - }); -} - -/** - * Runs a command on the database as admin. - * - * @method - * @param {Db} db The Db instance on which to execute the command. - * @param {object} command The command hash - * @param {object} [options] Optional settings. See Db.prototype.executeDbAdminCommand for a list of options. - * @param {Db~resultCallback} [callback] The command result callback - */ -function executeDbAdminCommand(db, command, options, callback) { - const namespace = new MongoDBNamespace('admin', '$cmd'); - - db.s.topology.command(namespace, command, options, (err, result) => { - // Did the user destroy the topology - if (db.serverConfig && db.serverConfig.isDestroyed()) { - return callback(new MongoError('topology was destroyed')); - } - - if (err) return handleCallback(callback, err); - handleCallback(callback, null, result.result); - }); -} - -/** - * Retrieves this collections index info. - * - * @method - * @param {Db} db The Db instance on which to retrieve the index info. - * @param {string} name The name of the collection. - * @param {object} [options] Optional settings. See Db.prototype.indexInformation for a list of options. - * @param {Db~resultCallback} [callback] The command result callback - */ -function indexInformation(db, name, options, callback) { - // If we specified full information - const full = options['full'] == null ? false : options['full']; - - // Did the user destroy the topology - if (db.serverConfig && db.serverConfig.isDestroyed()) - return callback(new MongoError('topology was destroyed')); - // Process all the results from the index command and collection - function processResults(indexes) { - // Contains all the information - let info = {}; - // Process all the indexes - for (let i = 0; i < indexes.length; i++) { - const index = indexes[i]; - // Let's unpack the object - info[index.name] = []; - for (let name in index.key) { - info[index.name].push([name, index.key[name]]); - } - } - - return info; - } - - // Get the list of indexes of the specified collection - db - .collection(name) - .listIndexes(options) - .toArray((err, indexes) => { - if (err) return callback(toError(err)); - if (!Array.isArray(indexes)) return handleCallback(callback, null, []); - if (full) return handleCallback(callback, null, indexes); - handleCallback(callback, null, processResults(indexes)); - }); -} - -/** - * Retrieve the current profiling information for MongoDB - * - * @method - * @param {Db} db The Db instance on which to retrieve the profiling info. - * @param {Object} [options] Optional settings. See Db.protoype.profilingInfo for a list of options. - * @param {Db~resultCallback} [callback] The command result callback. - * @deprecated Query the system.profile collection directly. - */ -function profilingInfo(db, options, callback) { - try { - db - .collection('system.profile') - .find({}, options) - .toArray(callback); - } catch (err) { - return callback(err, null); - } -} - -/** - * Remove a user from a database - * - * @method - * @param {Db} db The Db instance on which to remove the user. - * @param {string} username The username. - * @param {object} [options] Optional settings. See Db.prototype.removeUser for a list of options. - * @param {Db~resultCallback} [callback] The command result callback - */ -function removeUser(db, username, options, callback) { - let Db = loadDb(); - - // Attempt to execute command - executeAuthRemoveUserCommand(db, username, options, (err, result) => { - if (err && err.code === -5000) { - const finalOptions = applyWriteConcern(Object.assign({}, options), { db }, options); - // If we have another db set - const db = options.dbName ? new Db(options.dbName, db.s.topology, db.s.options) : db; - - // Fetch a user collection - const collection = db.collection(CONSTANTS.SYSTEM_USER_COLLECTION); - - // Locate the user - findOne(collection, { user: username }, finalOptions, (err, user) => { - if (user == null) return handleCallback(callback, err, false); - remove(collection, { user: username }, finalOptions, err => { - handleCallback(callback, err, true); - }); - }); - - return; - } - - if (err) return handleCallback(callback, err); - handleCallback(callback, err, result); - }); -} - -// Validate the database name -function validateDatabaseName(databaseName) { - if (typeof databaseName !== 'string') - throw MongoError.create({ message: 'database name must be a string', driver: true }); - if (databaseName.length === 0) - throw MongoError.create({ message: 'database name cannot be the empty string', driver: true }); - if (databaseName === '$external') return; - - const invalidChars = [' ', '.', '$', '/', '\\']; - for (let i = 0; i < invalidChars.length; i++) { - if (databaseName.indexOf(invalidChars[i]) !== -1) - throw MongoError.create({ - message: "database names cannot contain the character '" + invalidChars[i] + "'", - driver: true - }); - } -} - -/** - * Create the command object for Db.prototype.createIndex. - * - * @param {Db} db The Db instance on which to create the command. - * @param {string} name Name of the collection to create the index on. - * @param {(string|object)} fieldOrSpec Defines the index. - * @param {Object} [options] Optional settings. See Db.prototype.createIndex for a list of options. - * @return {Object} The insert command object. - */ -function createCreateIndexCommand(db, name, fieldOrSpec, options) { - const indexParameters = parseIndexOptions(fieldOrSpec); - const fieldHash = indexParameters.fieldHash; - - // Generate the index name - const indexName = typeof options.name === 'string' ? options.name : indexParameters.name; - const selector = { - ns: db.s.namespace.withCollection(name).toString(), - key: fieldHash, - name: indexName - }; - - // Ensure we have a correct finalUnique - const finalUnique = options == null || 'object' === typeof options ? false : options; - // Set up options - options = options == null || typeof options === 'boolean' ? {} : options; - - // Add all the options - const keysToOmit = Object.keys(selector); - for (let optionName in options) { - if (keysToOmit.indexOf(optionName) === -1) { - selector[optionName] = options[optionName]; - } - } - - if (selector['unique'] == null) selector['unique'] = finalUnique; - - // Remove any write concern operations - const removeKeys = ['w', 'wtimeout', 'j', 'fsync', 'readPreference', 'session']; - for (let i = 0; i < removeKeys.length; i++) { - delete selector[removeKeys[i]]; - } - - // Return the command creation selector - return selector; -} - -/** - * Create index using the createIndexes command. - * - * @param {Db} db The Db instance on which to execute the command. - * @param {string} name Name of the collection to create the index on. - * @param {(string|object)} fieldOrSpec Defines the index. - * @param {Object} [options] Optional settings. See Db.prototype.createIndex for a list of options. - * @param {Db~resultCallback} [callback] The command result callback. - */ -function createIndexUsingCreateIndexes(db, name, fieldOrSpec, options, callback) { - // Build the index - const indexParameters = parseIndexOptions(fieldOrSpec); - // Generate the index name - const indexName = typeof options.name === 'string' ? options.name : indexParameters.name; - // Set up the index - const indexes = [{ name: indexName, key: indexParameters.fieldHash }]; - // merge all the options - const keysToOmit = Object.keys(indexes[0]).concat([ - 'writeConcern', - 'w', - 'wtimeout', - 'j', - 'fsync', - 'readPreference', - 'session' - ]); - - for (let optionName in options) { - if (keysToOmit.indexOf(optionName) === -1) { - indexes[0][optionName] = options[optionName]; - } - } - - // Get capabilities - const capabilities = db.s.topology.capabilities(); - - // Did the user pass in a collation, check if our write server supports it - if (indexes[0].collation && capabilities && !capabilities.commandsTakeCollation) { - // Create a new error - const error = new MongoError('server/primary/mongos does not support collation'); - error.code = 67; - // Return the error - return callback(error); - } - - // Create command, apply write concern to command - const cmd = applyWriteConcern({ createIndexes: name, indexes }, { db }, options); - - // ReadPreference primary - options.readPreference = ReadPreference.PRIMARY; - - // Build the command - executeCommand(db, cmd, options, (err, result) => { - if (err) return handleCallback(callback, err, null); - if (result.ok === 0) return handleCallback(callback, toError(result), null); - // Return the indexName for backward compatibility - handleCallback(callback, null, indexName); - }); -} - -/** - * Run the createUser command. - * - * @param {Db} db The Db instance on which to execute the command. - * @param {string} username The username of the user to add. - * @param {string} password The password of the user to add. - * @param {object} [options] Optional settings. See Db.prototype.addUser for a list of options. - * @param {Db~resultCallback} [callback] The command result callback - */ -function executeAuthCreateUserCommand(db, username, password, options, callback) { - // Special case where there is no password ($external users) - if (typeof username === 'string' && password != null && typeof password === 'object') { - options = password; - password = null; - } - - // Unpack all options - if (typeof options === 'function') { - callback = options; - options = {}; - } - - // Error out if we digestPassword set - if (options.digestPassword != null) { - return callback( - toError( - "The digestPassword option is not supported via add_user. Please use db.command('createUser', ...) instead for this option." - ) - ); - } - - // Get additional values - const customData = options.customData != null ? options.customData : {}; - let roles = Array.isArray(options.roles) ? options.roles : []; - const maxTimeMS = typeof options.maxTimeMS === 'number' ? options.maxTimeMS : null; - - // If not roles defined print deprecated message - if (roles.length === 0) { - console.log('Creating a user without roles is deprecated in MongoDB >= 2.6'); - } - - // Get the error options - const commandOptions = { writeCommand: true }; - if (options['dbName']) commandOptions.dbName = options['dbName']; - - // Add maxTimeMS to options if set - if (maxTimeMS != null) commandOptions.maxTimeMS = maxTimeMS; - - // Check the db name and add roles if needed - if ( - (db.databaseName.toLowerCase() === 'admin' || options.dbName === 'admin') && - !Array.isArray(options.roles) - ) { - roles = ['root']; - } else if (!Array.isArray(options.roles)) { - roles = ['dbOwner']; - } - - const digestPassword = db.s.topology.lastIsMaster().maxWireVersion >= 7; - - // Build the command to execute - let command = { - createUser: username, - customData: customData, - roles: roles, - digestPassword - }; - - // Apply write concern to command - command = applyWriteConcern(command, { db }, options); - - let userPassword = password; - - if (!digestPassword) { - // Use node md5 generator - const md5 = crypto.createHash('md5'); - // Generate keys used for authentication - md5.update(username + ':mongo:' + password); - userPassword = md5.digest('hex'); - } - - // No password - if (typeof password === 'string') { - command.pwd = userPassword; - } - - // Force write using primary - commandOptions.readPreference = ReadPreference.primary; - - // Execute the command - executeCommand(db, command, commandOptions, (err, result) => { - if (err && err.ok === 0 && err.code === undefined) - return handleCallback(callback, { code: -5000 }, null); - if (err) return handleCallback(callback, err, null); - handleCallback( - callback, - !result.ok ? toError(result) : null, - result.ok ? [{ user: username, pwd: '' }] : null - ); - }); -} - -/** - * Run the dropUser command. - * - * @param {Db} db The Db instance on which to execute the command. - * @param {string} username The username of the user to remove. - * @param {object} [options] Optional settings. See Db.prototype.removeUser for a list of options. - * @param {Db~resultCallback} [callback] The command result callback - */ -function executeAuthRemoveUserCommand(db, username, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // Did the user destroy the topology - if (db.serverConfig && db.serverConfig.isDestroyed()) - return callback(new MongoError('topology was destroyed')); - // Get the error options - const commandOptions = { writeCommand: true }; - if (options['dbName']) commandOptions.dbName = options['dbName']; - - // Get additional values - const maxTimeMS = typeof options.maxTimeMS === 'number' ? options.maxTimeMS : null; - - // Add maxTimeMS to options if set - if (maxTimeMS != null) commandOptions.maxTimeMS = maxTimeMS; - - // Build the command to execute - let command = { - dropUser: username - }; - - // Apply write concern to command - command = applyWriteConcern(command, { db }, options); - - // Force write using primary - commandOptions.readPreference = ReadPreference.primary; - - // Execute the command - executeCommand(db, command, commandOptions, (err, result) => { - if (err && !err.ok && err.code === undefined) return handleCallback(callback, { code: -5000 }); - if (err) return handleCallback(callback, err, null); - handleCallback(callback, null, result.ok ? true : false); - }); -} - -module.exports = { - addUser, - collections, - createListener, - createIndex, - dropCollection, - dropDatabase, - ensureIndex, - evaluate, - executeCommand, - executeDbAdminCommand, - indexInformation, - profilingInfo, - removeUser, - validateDatabaseName -}; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/delete_many.js b/scripts/2.5/node_modules/mongodb/lib/operations/delete_many.js deleted file mode 100644 index d881f67d..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/operations/delete_many.js +++ /dev/null @@ -1,25 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const deleteCallback = require('./common_functions').deleteCallback; -const removeDocuments = require('./common_functions').removeDocuments; - -class DeleteManyOperation extends OperationBase { - constructor(collection, filter, options) { - super(options); - - this.collection = collection; - this.filter = filter; - } - - execute(callback) { - const coll = this.collection; - const filter = this.filter; - const options = this.options; - - options.single = false; - removeDocuments(coll, filter, options, (err, r) => deleteCallback(err, r, callback)); - } -} - -module.exports = DeleteManyOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/delete_one.js b/scripts/2.5/node_modules/mongodb/lib/operations/delete_one.js deleted file mode 100644 index b05597fd..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/operations/delete_one.js +++ /dev/null @@ -1,25 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const deleteCallback = require('./common_functions').deleteCallback; -const removeDocuments = require('./common_functions').removeDocuments; - -class DeleteOneOperation extends OperationBase { - constructor(collection, filter, options) { - super(options); - - this.collection = collection; - this.filter = filter; - } - - execute(callback) { - const coll = this.collection; - const filter = this.filter; - const options = this.options; - - options.single = true; - removeDocuments(coll, filter, options, (err, r) => deleteCallback(err, r, callback)); - } -} - -module.exports = DeleteOneOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/distinct.js b/scripts/2.5/node_modules/mongodb/lib/operations/distinct.js deleted file mode 100644 index dcf4f7e2..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/operations/distinct.js +++ /dev/null @@ -1,85 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const defineAspects = require('./operation').defineAspects; -const CommandOperationV2 = require('./command_v2'); -const decorateWithCollation = require('../utils').decorateWithCollation; -const decorateWithReadConcern = require('../utils').decorateWithReadConcern; - -/** - * Return a list of distinct values for the given key across a collection. - * - * @class - * @property {Collection} a Collection instance. - * @property {string} key Field of the document to find distinct values for. - * @property {object} query The query for filtering the set of documents to which we apply the distinct filter. - * @property {object} [options] Optional settings. See Collection.prototype.distinct for a list of options. - */ -class DistinctOperation extends CommandOperationV2 { - /** - * Construct a Distinct operation. - * - * @param {Collection} a Collection instance. - * @param {string} key Field of the document to find distinct values for. - * @param {object} query The query for filtering the set of documents to which we apply the distinct filter. - * @param {object} [options] Optional settings. See Collection.prototype.distinct for a list of options. - */ - constructor(collection, key, query, options) { - super(collection, options); - - this.collection = collection; - this.key = key; - this.query = query; - } - - /** - * Execute the operation. - * - * @param {Collection~resultCallback} [callback] The command result callback - */ - execute(server, callback) { - const coll = this.collection; - const key = this.key; - const query = this.query; - const options = this.options; - - // Distinct command - const cmd = { - distinct: coll.collectionName, - key: key, - query: query - }; - - // Add maxTimeMS if defined - if (typeof options.maxTimeMS === 'number') { - cmd.maxTimeMS = options.maxTimeMS; - } - - // Do we have a readConcern specified - decorateWithReadConcern(cmd, coll, options); - - // Have we specified collation - try { - decorateWithCollation(cmd, coll, options); - } catch (err) { - return callback(err, null); - } - - super.executeCommand(server, cmd, (err, result) => { - if (err) { - callback(err); - return; - } - - callback(null, this.options.full ? result : result.values); - }); - } -} - -defineAspects(DistinctOperation, [ - Aspect.READ_OPERATION, - Aspect.RETRYABLE, - Aspect.EXECUTE_WITH_SELECTION -]); - -module.exports = DistinctOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/drop.js b/scripts/2.5/node_modules/mongodb/lib/operations/drop.js deleted file mode 100644 index be03716f..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/operations/drop.js +++ /dev/null @@ -1,53 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const CommandOperation = require('./command'); -const defineAspects = require('./operation').defineAspects; -const handleCallback = require('../utils').handleCallback; - -class DropOperation extends CommandOperation { - constructor(db, options) { - const finalOptions = Object.assign({}, options, db.s.options); - - if (options.session) { - finalOptions.session = options.session; - } - - super(db, finalOptions); - } - - execute(callback) { - super.execute((err, result) => { - if (err) return handleCallback(callback, err); - if (result.ok) return handleCallback(callback, null, true); - handleCallback(callback, null, false); - }); - } -} - -defineAspects(DropOperation, Aspect.WRITE_OPERATION); - -class DropCollectionOperation extends DropOperation { - constructor(db, name, options) { - super(db, options); - - this.name = name; - this.namespace = `${db.namespace}.${name}`; - } - - _buildCommand() { - return { drop: this.name }; - } -} - -class DropDatabaseOperation extends DropOperation { - _buildCommand() { - return { dropDatabase: 1 }; - } -} - -module.exports = { - DropOperation, - DropCollectionOperation, - DropDatabaseOperation -}; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/drop_index.js b/scripts/2.5/node_modules/mongodb/lib/operations/drop_index.js deleted file mode 100644 index a6ca783d..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/operations/drop_index.js +++ /dev/null @@ -1,42 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const defineAspects = require('./operation').defineAspects; -const CommandOperation = require('./command'); -const applyWriteConcern = require('../utils').applyWriteConcern; -const handleCallback = require('../utils').handleCallback; - -class DropIndexOperation extends CommandOperation { - constructor(collection, indexName, options) { - super(collection.s.db, options, collection); - - this.collection = collection; - this.indexName = indexName; - } - - _buildCommand() { - const collection = this.collection; - const indexName = this.indexName; - const options = this.options; - - let cmd = { dropIndexes: collection.collectionName, index: indexName }; - - // Decorate command with writeConcern if supported - cmd = applyWriteConcern(cmd, { db: collection.s.db, collection }, options); - - return cmd; - } - - execute(callback) { - // Execute command - super.execute((err, result) => { - if (typeof callback !== 'function') return; - if (err) return handleCallback(callback, err, null); - handleCallback(callback, null, result); - }); - } -} - -defineAspects(DropIndexOperation, Aspect.WRITE_OPERATION); - -module.exports = DropIndexOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/drop_indexes.js b/scripts/2.5/node_modules/mongodb/lib/operations/drop_indexes.js deleted file mode 100644 index ed404ee9..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/operations/drop_indexes.js +++ /dev/null @@ -1,23 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const defineAspects = require('./operation').defineAspects; -const DropIndexOperation = require('./drop_index'); -const handleCallback = require('../utils').handleCallback; - -class DropIndexesOperation extends DropIndexOperation { - constructor(collection, options) { - super(collection, '*', options); - } - - execute(callback) { - super.execute(err => { - if (err) return handleCallback(callback, err, false); - handleCallback(callback, null, true); - }); - } -} - -defineAspects(DropIndexesOperation, Aspect.WRITE_OPERATION); - -module.exports = DropIndexesOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/estimated_document_count.js b/scripts/2.5/node_modules/mongodb/lib/operations/estimated_document_count.js deleted file mode 100644 index e2d65563..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/operations/estimated_document_count.js +++ /dev/null @@ -1,58 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const defineAspects = require('./operation').defineAspects; -const CommandOperationV2 = require('./command_v2'); - -class EstimatedDocumentCountOperation extends CommandOperationV2 { - constructor(collection, query, options) { - if (typeof options === 'undefined') { - options = query; - query = undefined; - } - - super(collection, options); - this.collectionName = collection.s.namespace.collection; - if (query) { - this.query = query; - } - } - - execute(server, callback) { - const options = this.options; - const cmd = { count: this.collectionName }; - - if (this.query) { - cmd.query = this.query; - } - - if (typeof options.skip === 'number') { - cmd.skip = options.skip; - } - - if (typeof options.limit === 'number') { - cmd.limit = options.limit; - } - - if (options.hint) { - cmd.hint = options.hint; - } - - super.executeCommand(server, cmd, (err, response) => { - if (err) { - callback(err); - return; - } - - callback(null, response.n); - }); - } -} - -defineAspects(EstimatedDocumentCountOperation, [ - Aspect.READ_OPERATION, - Aspect.RETRYABLE, - Aspect.EXECUTE_WITH_SELECTION -]); - -module.exports = EstimatedDocumentCountOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/execute_db_admin_command.js b/scripts/2.5/node_modules/mongodb/lib/operations/execute_db_admin_command.js deleted file mode 100644 index d15fc8e6..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/operations/execute_db_admin_command.js +++ /dev/null @@ -1,34 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const handleCallback = require('../utils').handleCallback; -const MongoError = require('../core').MongoError; -const MongoDBNamespace = require('../utils').MongoDBNamespace; - -class ExecuteDbAdminCommandOperation extends OperationBase { - constructor(db, selector, options) { - super(options); - - this.db = db; - this.selector = selector; - } - - execute(callback) { - const db = this.db; - const selector = this.selector; - const options = this.options; - - const namespace = new MongoDBNamespace('admin', '$cmd'); - db.s.topology.command(namespace, selector, options, (err, result) => { - // Did the user destroy the topology - if (db.serverConfig && db.serverConfig.isDestroyed()) { - return callback(new MongoError('topology was destroyed')); - } - - if (err) return handleCallback(callback, err); - handleCallback(callback, null, result.result); - }); - } -} - -module.exports = ExecuteDbAdminCommandOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/execute_operation.js b/scripts/2.5/node_modules/mongodb/lib/operations/execute_operation.js deleted file mode 100644 index e23a80c0..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/operations/execute_operation.js +++ /dev/null @@ -1,198 +0,0 @@ -'use strict'; - -const MongoError = require('../core/error').MongoError; -const Aspect = require('./operation').Aspect; -const OperationBase = require('./operation').OperationBase; -const ReadPreference = require('../core/topologies/read_preference'); -const isRetryableError = require('../core/error').isRetryableError; -const maxWireVersion = require('../core/utils').maxWireVersion; -const isUnifiedTopology = require('../core/utils').isUnifiedTopology; - -/** - * Executes the given operation with provided arguments. - * - * This method reduces large amounts of duplication in the entire codebase by providing - * a single point for determining whether callbacks or promises should be used. Additionally - * it allows for a single point of entry to provide features such as implicit sessions, which - * are required by the Driver Sessions specification in the event that a ClientSession is - * not provided - * - * @param {object} topology The topology to execute this operation on - * @param {Operation} operation The operation to execute - * @param {function} callback The command result callback - */ -function executeOperation(topology, operation, callback) { - if (topology == null) { - throw new TypeError('This method requires a valid topology instance'); - } - - if (!(operation instanceof OperationBase)) { - throw new TypeError('This method requires a valid operation instance'); - } - - if ( - isUnifiedTopology(topology) && - !operation.hasAspect(Aspect.SKIP_SESSION) && - topology.shouldCheckForSessionSupport() - ) { - return selectServerForSessionSupport(topology, operation, callback); - } - - const Promise = topology.s.promiseLibrary; - - // The driver sessions spec mandates that we implicitly create sessions for operations - // that are not explicitly provided with a session. - let session, owner; - if (!operation.hasAspect(Aspect.SKIP_SESSION) && topology.hasSessionSupport()) { - if (operation.session == null) { - owner = Symbol(); - session = topology.startSession({ owner }); - operation.session = session; - } else if (operation.session.hasEnded) { - throw new MongoError('Use of expired sessions is not permitted'); - } - } - - const makeExecuteCallback = (resolve, reject) => - function executeCallback(err, result) { - if (session && session.owner === owner) { - session.endSession(() => { - if (operation.session === session) { - operation.clearSession(); - } - if (err) return reject(err); - resolve(result); - }); - } else { - if (err) return reject(err); - resolve(result); - } - }; - - // Execute using callback - if (typeof callback === 'function') { - const handler = makeExecuteCallback( - result => callback(null, result), - err => callback(err, null) - ); - - try { - if (operation.hasAspect(Aspect.EXECUTE_WITH_SELECTION)) { - return executeWithServerSelection(topology, operation, handler); - } else { - return operation.execute(handler); - } - } catch (e) { - handler(e); - throw e; - } - } - - return new Promise(function(resolve, reject) { - const handler = makeExecuteCallback(resolve, reject); - - try { - if (operation.hasAspect(Aspect.EXECUTE_WITH_SELECTION)) { - return executeWithServerSelection(topology, operation, handler); - } else { - return operation.execute(handler); - } - } catch (e) { - handler(e); - } - }); -} - -function supportsRetryableReads(server) { - return maxWireVersion(server) >= 6; -} - -function executeWithServerSelection(topology, operation, callback) { - const readPreference = operation.readPreference || ReadPreference.primary; - const inTransaction = operation.session && operation.session.inTransaction(); - - if (inTransaction && !readPreference.equals(ReadPreference.primary)) { - callback( - new MongoError( - `Read preference in a transaction must be primary, not: ${readPreference.mode}` - ) - ); - - return; - } - - const serverSelectionOptions = { - readPreference, - session: operation.session - }; - - function callbackWithRetry(err, result) { - if (err == null) { - return callback(null, result); - } - - if (!isRetryableError(err)) { - return callback(err); - } - - // select a new server, and attempt to retry the operation - topology.selectServer(serverSelectionOptions, (err, server) => { - if (err || !supportsRetryableReads(server)) { - callback(err, null); - return; - } - - operation.execute(server, callback); - }); - } - - // select a server, and execute the operation against it - topology.selectServer(serverSelectionOptions, (err, server) => { - if (err) { - callback(err, null); - return; - } - - const shouldRetryReads = - topology.s.options.retryReads !== false && - (operation.session && !inTransaction) && - supportsRetryableReads(server) && - operation.canRetryRead; - - if (operation.hasAspect(Aspect.RETRYABLE) && shouldRetryReads) { - operation.execute(server, callbackWithRetry); - return; - } - - operation.execute(server, callback); - }); -} - -// TODO: This is only supported for unified topology, it should go away once -// we remove support for legacy topology types. -function selectServerForSessionSupport(topology, operation, callback) { - const Promise = topology.s.promiseLibrary; - - let result; - if (typeof callback !== 'function') { - result = new Promise((resolve, reject) => { - callback = (err, result) => { - if (err) return reject(err); - resolve(result); - }; - }); - } - - topology.selectServer(ReadPreference.primaryPreferred, err => { - if (err) { - callback(err); - return; - } - - executeOperation(topology, operation, callback); - }); - - return result; -} - -module.exports = executeOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/explain.js b/scripts/2.5/node_modules/mongodb/lib/operations/explain.js deleted file mode 100644 index 44f3b483..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/operations/explain.js +++ /dev/null @@ -1,23 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const CoreCursor = require('../core/cursor').CoreCursor; -const defineAspects = require('./operation').defineAspects; -const OperationBase = require('./operation').OperationBase; - -class ExplainOperation extends OperationBase { - constructor(cursor) { - super(); - - this.cursor = cursor; - } - - execute() { - const cursor = this.cursor; - return CoreCursor.prototype._next.apply(cursor, arguments); - } -} - -defineAspects(ExplainOperation, Aspect.SKIP_SESSION); - -module.exports = ExplainOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/find.js b/scripts/2.5/node_modules/mongodb/lib/operations/find.js deleted file mode 100644 index 6838213c..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/operations/find.js +++ /dev/null @@ -1,35 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const Aspect = require('./operation').Aspect; -const defineAspects = require('./operation').defineAspects; -const resolveReadPreference = require('../utils').resolveReadPreference; - -class FindOperation extends OperationBase { - constructor(collection, ns, command, options) { - super(options); - - this.ns = ns; - this.cmd = command; - this.readPreference = resolveReadPreference(collection, this.options); - } - - execute(server, callback) { - // copied from `CommandOperationV2`, to be subclassed in the future - this.server = server; - - const cursorState = this.cursorState || {}; - - // TOOD: use `MongoDBNamespace` through and through - server.query(this.ns.toString(), this.cmd, cursorState, this.options, callback); - } -} - -defineAspects(FindOperation, [ - Aspect.READ_OPERATION, - Aspect.RETRYABLE, - Aspect.EXECUTE_WITH_SELECTION, - Aspect.SKIP_SESSION -]); - -module.exports = FindOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/find_and_modify.js b/scripts/2.5/node_modules/mongodb/lib/operations/find_and_modify.js deleted file mode 100644 index 8965eb48..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/operations/find_and_modify.js +++ /dev/null @@ -1,98 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const applyRetryableWrites = require('../utils').applyRetryableWrites; -const applyWriteConcern = require('../utils').applyWriteConcern; -const decorateWithCollation = require('../utils').decorateWithCollation; -const executeCommand = require('./db_ops').executeCommand; -const formattedOrderClause = require('../utils').formattedOrderClause; -const handleCallback = require('../utils').handleCallback; -const ReadPreference = require('../core').ReadPreference; - -class FindAndModifyOperation extends OperationBase { - constructor(collection, query, sort, doc, options) { - super(options); - - this.collection = collection; - this.query = query; - this.sort = sort; - this.doc = doc; - } - - execute(callback) { - const coll = this.collection; - const query = this.query; - const sort = formattedOrderClause(this.sort); - const doc = this.doc; - let options = this.options; - - // Create findAndModify command object - const queryObject = { - findAndModify: coll.collectionName, - query: query - }; - - if (sort) { - queryObject.sort = sort; - } - - queryObject.new = options.new ? true : false; - queryObject.remove = options.remove ? true : false; - queryObject.upsert = options.upsert ? true : false; - - const projection = options.projection || options.fields; - - if (projection) { - queryObject.fields = projection; - } - - if (options.arrayFilters) { - queryObject.arrayFilters = options.arrayFilters; - } - - if (doc && !options.remove) { - queryObject.update = doc; - } - - if (options.maxTimeMS) queryObject.maxTimeMS = options.maxTimeMS; - - // Either use override on the function, or go back to default on either the collection - // level or db - options.serializeFunctions = options.serializeFunctions || coll.s.serializeFunctions; - - // No check on the documents - options.checkKeys = false; - - // Final options for retryable writes and write concern - options = applyRetryableWrites(options, coll.s.db); - options = applyWriteConcern(options, { db: coll.s.db, collection: coll }, options); - - // Decorate the findAndModify command with the write Concern - if (options.writeConcern) { - queryObject.writeConcern = options.writeConcern; - } - - // Have we specified bypassDocumentValidation - if (options.bypassDocumentValidation === true) { - queryObject.bypassDocumentValidation = options.bypassDocumentValidation; - } - - options.readPreference = ReadPreference.primary; - - // Have we specified collation - try { - decorateWithCollation(queryObject, coll, options); - } catch (err) { - return callback(err, null); - } - - // Execute the command - executeCommand(coll.s.db, queryObject, options, (err, result) => { - if (err) return handleCallback(callback, err, null); - - return handleCallback(callback, null, result); - }); - } -} - -module.exports = FindAndModifyOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/find_one.js b/scripts/2.5/node_modules/mongodb/lib/operations/find_one.js deleted file mode 100644 index d3037a6d..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/operations/find_one.js +++ /dev/null @@ -1,33 +0,0 @@ -'use strict'; - -const handleCallback = require('../utils').handleCallback; -const OperationBase = require('./operation').OperationBase; -const toError = require('../utils').toError; - -class FindOneOperation extends OperationBase { - constructor(collection, query, options) { - super(options); - - this.collection = collection; - this.query = query; - } - - execute(callback) { - const coll = this.collection; - const query = this.query; - const options = this.options; - - const cursor = coll - .find(query, options) - .limit(-1) - .batchSize(1); - - // Return the item - cursor.next((err, item) => { - if (err != null) return handleCallback(callback, toError(err), null); - handleCallback(callback, null, item); - }); - } -} - -module.exports = FindOneOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/find_one_and_delete.js b/scripts/2.5/node_modules/mongodb/lib/operations/find_one_and_delete.js deleted file mode 100644 index 1c7527dd..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/operations/find_one_and_delete.js +++ /dev/null @@ -1,16 +0,0 @@ -'use strict'; - -const FindAndModifyOperation = require('./find_and_modify'); - -class FindOneAndDeleteOperation extends FindAndModifyOperation { - constructor(collection, filter, options) { - // Final options - const finalOptions = Object.assign({}, options); - finalOptions.fields = options.projection; - finalOptions.remove = true; - - super(collection, filter, finalOptions.sort, null, finalOptions); - } -} - -module.exports = FindOneAndDeleteOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/find_one_and_replace.js b/scripts/2.5/node_modules/mongodb/lib/operations/find_one_and_replace.js deleted file mode 100644 index ae37df5d..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/operations/find_one_and_replace.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; - -const FindAndModifyOperation = require('./find_and_modify'); - -class FindOneAndReplaceOperation extends FindAndModifyOperation { - constructor(collection, filter, replacement, options) { - // Final options - const finalOptions = Object.assign({}, options); - finalOptions.fields = options.projection; - finalOptions.update = true; - finalOptions.new = options.returnOriginal !== void 0 ? !options.returnOriginal : false; - finalOptions.upsert = options.upsert !== void 0 ? !!options.upsert : false; - - super(collection, filter, finalOptions.sort, replacement, finalOptions); - } -} - -module.exports = FindOneAndReplaceOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/find_one_and_update.js b/scripts/2.5/node_modules/mongodb/lib/operations/find_one_and_update.js deleted file mode 100644 index 6a199652..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/operations/find_one_and_update.js +++ /dev/null @@ -1,19 +0,0 @@ -'use strict'; - -const FindAndModifyOperation = require('./find_and_modify'); - -class FindOneAndUpdateOperation extends FindAndModifyOperation { - constructor(collection, filter, update, options) { - // Final options - const finalOptions = Object.assign({}, options); - finalOptions.fields = options.projection; - finalOptions.update = true; - finalOptions.new = - typeof options.returnOriginal === 'boolean' ? !options.returnOriginal : false; - finalOptions.upsert = typeof options.upsert === 'boolean' ? options.upsert : false; - - super(collection, filter, finalOptions.sort, update, finalOptions); - } -} - -module.exports = FindOneAndUpdateOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/geo_haystack_search.js b/scripts/2.5/node_modules/mongodb/lib/operations/geo_haystack_search.js deleted file mode 100644 index edd1fb17..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/operations/geo_haystack_search.js +++ /dev/null @@ -1,79 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const defineAspects = require('./operation').defineAspects; -const OperationBase = require('./operation').OperationBase; -const decorateCommand = require('../utils').decorateCommand; -const decorateWithReadConcern = require('../utils').decorateWithReadConcern; -const executeCommand = require('./db_ops').executeCommand; -const handleCallback = require('../utils').handleCallback; -const resolveReadPreference = require('../utils').resolveReadPreference; -const toError = require('../utils').toError; - -/** - * Execute a geo search using a geo haystack index on a collection. - * - * @class - * @property {Collection} a Collection instance. - * @property {number} x Point to search on the x axis, ensure the indexes are ordered in the same order. - * @property {number} y Point to search on the y axis, ensure the indexes are ordered in the same order. - * @property {object} [options] Optional settings. See Collection.prototype.geoHaystackSearch for a list of options. - */ -class GeoHaystackSearchOperation extends OperationBase { - /** - * Construct a GeoHaystackSearch operation. - * - * @param {Collection} a Collection instance. - * @param {number} x Point to search on the x axis, ensure the indexes are ordered in the same order. - * @param {number} y Point to search on the y axis, ensure the indexes are ordered in the same order. - * @param {object} [options] Optional settings. See Collection.prototype.geoHaystackSearch for a list of options. - */ - constructor(collection, x, y, options) { - super(options); - - this.collection = collection; - this.x = x; - this.y = y; - } - - /** - * Execute the operation. - * - * @param {Collection~resultCallback} [callback] The command result callback - */ - execute(callback) { - const coll = this.collection; - const x = this.x; - const y = this.y; - let options = this.options; - - // Build command object - let commandObject = { - geoSearch: coll.collectionName, - near: [x, y] - }; - - // Remove read preference from hash if it exists - commandObject = decorateCommand(commandObject, options, ['readPreference', 'session']); - - options = Object.assign({}, options); - // Ensure we have the right read preference inheritance - options.readPreference = resolveReadPreference(coll, options); - - // Do we have a readConcern specified - decorateWithReadConcern(commandObject, coll, options); - - // Execute the command - executeCommand(coll.s.db, commandObject, options, (err, res) => { - if (err) return handleCallback(callback, err); - if (res.err || res.errmsg) handleCallback(callback, toError(res)); - // should we only be returning res.results here? Not sure if the user - // should see the other return information - handleCallback(callback, null, res); - }); - } -} - -defineAspects(GeoHaystackSearchOperation, Aspect.READ_OPERATION); - -module.exports = GeoHaystackSearchOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/has_next.js b/scripts/2.5/node_modules/mongodb/lib/operations/has_next.js deleted file mode 100644 index b2e4b861..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/operations/has_next.js +++ /dev/null @@ -1,40 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const defineAspects = require('./operation').defineAspects; -const loadCursor = require('../dynamic_loaders').loadCursor; -const OperationBase = require('./operation').OperationBase; -const nextObject = require('./common_functions').nextObject; - -class HasNextOperation extends OperationBase { - constructor(cursor) { - super(); - - this.cursor = cursor; - } - - execute(callback) { - const cursor = this.cursor; - let Cursor = loadCursor(); - - if (cursor.s.currentDoc) { - return callback(null, true); - } - - if (cursor.isNotified()) { - return callback(null, false); - } - - nextObject(cursor, (err, doc) => { - if (err) return callback(err, null); - if (cursor.s.state === Cursor.CLOSED || cursor.isDead()) return callback(null, false); - if (!doc) return callback(null, false); - cursor.s.currentDoc = doc; - callback(null, true); - }); - } -} - -defineAspects(HasNextOperation, Aspect.SKIP_SESSION); - -module.exports = HasNextOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/index_exists.js b/scripts/2.5/node_modules/mongodb/lib/operations/index_exists.js deleted file mode 100644 index bd9dc0e9..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/operations/index_exists.js +++ /dev/null @@ -1,39 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const handleCallback = require('../utils').handleCallback; -const indexInformationDb = require('./db_ops').indexInformation; - -class IndexExistsOperation extends OperationBase { - constructor(collection, indexes, options) { - super(options); - - this.collection = collection; - this.indexes = indexes; - } - - execute(callback) { - const coll = this.collection; - const indexes = this.indexes; - const options = this.options; - - indexInformationDb(coll.s.db, coll.collectionName, options, (err, indexInformation) => { - // If we have an error return - if (err != null) return handleCallback(callback, err, null); - // Let's check for the index names - if (!Array.isArray(indexes)) - return handleCallback(callback, null, indexInformation[indexes] != null); - // Check in list of indexes - for (let i = 0; i < indexes.length; i++) { - if (indexInformation[indexes[i]] == null) { - return handleCallback(callback, null, false); - } - } - - // All keys found return true - return handleCallback(callback, null, true); - }); - } -} - -module.exports = IndexExistsOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/index_information.js b/scripts/2.5/node_modules/mongodb/lib/operations/index_information.js deleted file mode 100644 index b18a603f..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/operations/index_information.js +++ /dev/null @@ -1,23 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const indexInformation = require('./common_functions').indexInformation; - -class IndexInformationOperation extends OperationBase { - constructor(db, name, options) { - super(options); - - this.db = db; - this.name = name; - } - - execute(callback) { - const db = this.db; - const name = this.name; - const options = this.options; - - indexInformation(db, name, options, callback); - } -} - -module.exports = IndexInformationOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/indexes.js b/scripts/2.5/node_modules/mongodb/lib/operations/indexes.js deleted file mode 100644 index e29a88aa..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/operations/indexes.js +++ /dev/null @@ -1,22 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const indexInformation = require('./common_functions').indexInformation; - -class IndexesOperation extends OperationBase { - constructor(collection, options) { - super(options); - - this.collection = collection; - } - - execute(callback) { - const coll = this.collection; - let options = this.options; - - options = Object.assign({}, { full: true }, options); - indexInformation(coll.s.db, coll.collectionName, options, callback); - } -} - -module.exports = IndexesOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/insert_many.js b/scripts/2.5/node_modules/mongodb/lib/operations/insert_many.js deleted file mode 100644 index 460a535d..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/operations/insert_many.js +++ /dev/null @@ -1,63 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const BulkWriteOperation = require('./bulk_write'); -const MongoError = require('../core').MongoError; -const prepareDocs = require('./common_functions').prepareDocs; - -class InsertManyOperation extends OperationBase { - constructor(collection, docs, options) { - super(options); - - this.collection = collection; - this.docs = docs; - } - - execute(callback) { - const coll = this.collection; - let docs = this.docs; - const options = this.options; - - if (!Array.isArray(docs)) { - return callback( - MongoError.create({ message: 'docs parameter must be an array of documents', driver: true }) - ); - } - - // If keep going set unordered - options['serializeFunctions'] = options['serializeFunctions'] || coll.s.serializeFunctions; - - docs = prepareDocs(coll, docs, options); - - // Generate the bulk write operations - const operations = [ - { - insertMany: docs - } - ]; - - const bulkWriteOperation = new BulkWriteOperation(coll, operations, options); - - bulkWriteOperation.execute((err, result) => { - if (err) return callback(err, null); - callback(null, mapInsertManyResults(docs, result)); - }); - } -} - -function mapInsertManyResults(docs, r) { - const finalResult = { - result: { ok: 1, n: r.insertedCount }, - ops: docs, - insertedCount: r.insertedCount, - insertedIds: r.insertedIds - }; - - if (r.getLastOp()) { - finalResult.result.opTime = r.getLastOp(); - } - - return finalResult; -} - -module.exports = InsertManyOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/insert_one.js b/scripts/2.5/node_modules/mongodb/lib/operations/insert_one.js deleted file mode 100644 index 5e708801..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/operations/insert_one.js +++ /dev/null @@ -1,39 +0,0 @@ -'use strict'; - -const MongoError = require('../core').MongoError; -const OperationBase = require('./operation').OperationBase; -const insertDocuments = require('./common_functions').insertDocuments; - -class InsertOneOperation extends OperationBase { - constructor(collection, doc, options) { - super(options); - - this.collection = collection; - this.doc = doc; - } - - execute(callback) { - const coll = this.collection; - const doc = this.doc; - const options = this.options; - - if (Array.isArray(doc)) { - return callback( - MongoError.create({ message: 'doc parameter must be an object', driver: true }) - ); - } - - insertDocuments(coll, [doc], options, (err, r) => { - if (callback == null) return; - if (err && callback) return callback(err); - // Workaround for pre 2.6 servers - if (r == null) return callback(null, { result: { ok: 1 } }); - // Add values to top level to ensure crud spec compatibility - r.insertedCount = r.result.n; - r.insertedId = doc._id; - if (callback) callback(null, r); - }); - } -} - -module.exports = InsertOneOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/is_capped.js b/scripts/2.5/node_modules/mongodb/lib/operations/is_capped.js deleted file mode 100644 index 3bfd9ffa..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/operations/is_capped.js +++ /dev/null @@ -1,19 +0,0 @@ -'use strict'; - -const OptionsOperation = require('./options_operation'); -const handleCallback = require('../utils').handleCallback; - -class IsCappedOperation extends OptionsOperation { - constructor(collection, options) { - super(collection, options); - } - - execute(callback) { - super.execute((err, document) => { - if (err) return handleCallback(callback, err); - handleCallback(callback, null, !!(document && document.capped)); - }); - } -} - -module.exports = IsCappedOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/list_collections.js b/scripts/2.5/node_modules/mongodb/lib/operations/list_collections.js deleted file mode 100644 index ee01d31e..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/operations/list_collections.js +++ /dev/null @@ -1,106 +0,0 @@ -'use strict'; - -const CommandOperationV2 = require('./command_v2'); -const Aspect = require('./operation').Aspect; -const defineAspects = require('./operation').defineAspects; -const maxWireVersion = require('../core/utils').maxWireVersion; -const CONSTANTS = require('../constants'); - -const LIST_COLLECTIONS_WIRE_VERSION = 3; - -function listCollectionsTransforms(databaseName) { - const matching = `${databaseName}.`; - - return { - doc: doc => { - const index = doc.name.indexOf(matching); - // Remove database name if available - if (doc.name && index === 0) { - doc.name = doc.name.substr(index + matching.length); - } - - return doc; - } - }; -} - -class ListCollectionsOperation extends CommandOperationV2 { - constructor(db, filter, options) { - super(db, options, { fullResponse: true }); - - this.db = db; - this.filter = filter; - this.nameOnly = !!this.options.nameOnly; - - if (typeof this.options.batchSize === 'number') { - this.batchSize = this.options.batchSize; - } - } - - execute(server, callback) { - if (maxWireVersion(server) < LIST_COLLECTIONS_WIRE_VERSION) { - let filter = this.filter; - const databaseName = this.db.s.namespace.db; - - // If we have legacy mode and have not provided a full db name filter it - if ( - typeof filter.name === 'string' && - !new RegExp('^' + databaseName + '\\.').test(filter.name) - ) { - filter = Object.assign({}, filter); - filter.name = this.db.s.namespace.withCollection(filter.name).toString(); - } - - // No filter, filter by current database - if (filter == null) { - filter.name = `/${databaseName}/`; - } - - // Rewrite the filter to use $and to filter out indexes - if (filter.name) { - filter = { $and: [{ name: filter.name }, { name: /^((?!\$).)*$/ }] }; - } else { - filter = { name: /^((?!\$).)*$/ }; - } - - const transforms = listCollectionsTransforms(databaseName); - server.query( - `${databaseName}.${CONSTANTS.SYSTEM_NAMESPACE_COLLECTION}`, - { query: filter }, - { batchSize: this.batchSize || 1000 }, - {}, - (err, result) => { - if ( - result && - result.message && - result.message.documents && - Array.isArray(result.message.documents) - ) { - result.message.documents = result.message.documents.map(transforms.doc); - } - - callback(err, result); - } - ); - - return; - } - - const command = { - listCollections: 1, - filter: this.filter, - cursor: this.batchSize ? { batchSize: this.batchSize } : {}, - nameOnly: this.nameOnly - }; - - return super.executeCommand(server, command, callback); - } -} - -defineAspects(ListCollectionsOperation, [ - Aspect.READ_OPERATION, - Aspect.RETRYABLE, - Aspect.EXECUTE_WITH_SELECTION -]); - -module.exports = ListCollectionsOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/list_databases.js b/scripts/2.5/node_modules/mongodb/lib/operations/list_databases.js deleted file mode 100644 index 62b2606f..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/operations/list_databases.js +++ /dev/null @@ -1,38 +0,0 @@ -'use strict'; - -const CommandOperationV2 = require('./command_v2'); -const Aspect = require('./operation').Aspect; -const defineAspects = require('./operation').defineAspects; -const MongoDBNamespace = require('../utils').MongoDBNamespace; - -class ListDatabasesOperation extends CommandOperationV2 { - constructor(db, options) { - super(db, options); - this.ns = new MongoDBNamespace('admin', '$cmd'); - } - - execute(server, callback) { - const cmd = { listDatabases: 1 }; - if (this.options.nameOnly) { - cmd.nameOnly = Number(cmd.nameOnly); - } - - if (this.options.filter) { - cmd.filter = this.options.filter; - } - - if (typeof this.options.authorizedDatabases === 'boolean') { - cmd.authorizedDatabases = this.options.authorizedDatabases; - } - - super.executeCommand(server, cmd, callback); - } -} - -defineAspects(ListDatabasesOperation, [ - Aspect.READ_OPERATION, - Aspect.RETRYABLE, - Aspect.EXECUTE_WITH_SELECTION -]); - -module.exports = ListDatabasesOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/list_indexes.js b/scripts/2.5/node_modules/mongodb/lib/operations/list_indexes.js deleted file mode 100644 index 302a31b7..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/operations/list_indexes.js +++ /dev/null @@ -1,42 +0,0 @@ -'use strict'; - -const CommandOperationV2 = require('./command_v2'); -const Aspect = require('./operation').Aspect; -const defineAspects = require('./operation').defineAspects; -const maxWireVersion = require('../core/utils').maxWireVersion; - -const LIST_INDEXES_WIRE_VERSION = 3; - -class ListIndexesOperation extends CommandOperationV2 { - constructor(collection, options) { - super(collection, options, { fullResponse: true }); - - this.collectionNamespace = collection.s.namespace; - } - - execute(server, callback) { - const serverWireVersion = maxWireVersion(server); - if (serverWireVersion < LIST_INDEXES_WIRE_VERSION) { - const systemIndexesNS = this.collectionNamespace.withCollection('system.indexes').toString(); - const collectionNS = this.collectionNamespace.toString(); - - server.query(systemIndexesNS, { query: { ns: collectionNS } }, {}, this.options, callback); - return; - } - - const cursor = this.options.batchSize ? { batchSize: this.options.batchSize } : {}; - super.executeCommand( - server, - { listIndexes: this.collectionNamespace.collection, cursor }, - callback - ); - } -} - -defineAspects(ListIndexesOperation, [ - Aspect.READ_OPERATION, - Aspect.RETRYABLE, - Aspect.EXECUTE_WITH_SELECTION -]); - -module.exports = ListIndexesOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/map_reduce.js b/scripts/2.5/node_modules/mongodb/lib/operations/map_reduce.js deleted file mode 100644 index 613f3f73..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/operations/map_reduce.js +++ /dev/null @@ -1,189 +0,0 @@ -'use strict'; - -const applyWriteConcern = require('../utils').applyWriteConcern; -const Code = require('../core').BSON.Code; -const decorateWithCollation = require('../utils').decorateWithCollation; -const decorateWithReadConcern = require('../utils').decorateWithReadConcern; -const executeCommand = require('./db_ops').executeCommand; -const handleCallback = require('../utils').handleCallback; -const isObject = require('../utils').isObject; -const loadDb = require('../dynamic_loaders').loadDb; -const OperationBase = require('./operation').OperationBase; -const resolveReadPreference = require('../utils').resolveReadPreference; -const toError = require('../utils').toError; - -const exclusionList = [ - 'readPreference', - 'session', - 'bypassDocumentValidation', - 'w', - 'wtimeout', - 'j', - 'writeConcern' -]; - -/** - * Run Map Reduce across a collection. Be aware that the inline option for out will return an array of results not a collection. - * - * @class - * @property {Collection} a Collection instance. - * @property {(function|string)} map The mapping function. - * @property {(function|string)} reduce The reduce function. - * @property {object} [options] Optional settings. See Collection.prototype.mapReduce for a list of options. - */ -class MapReduceOperation extends OperationBase { - /** - * Constructs a MapReduce operation. - * - * @param {Collection} a Collection instance. - * @param {(function|string)} map The mapping function. - * @param {(function|string)} reduce The reduce function. - * @param {object} [options] Optional settings. See Collection.prototype.mapReduce for a list of options. - */ - constructor(collection, map, reduce, options) { - super(options); - - this.collection = collection; - this.map = map; - this.reduce = reduce; - } - - /** - * Execute the operation. - * - * @param {Collection~resultCallback} [callback] The command result callback - */ - execute(callback) { - const coll = this.collection; - const map = this.map; - const reduce = this.reduce; - let options = this.options; - - const mapCommandHash = { - mapreduce: coll.collectionName, - map: map, - reduce: reduce - }; - - // Add any other options passed in - for (let n in options) { - if ('scope' === n) { - mapCommandHash[n] = processScope(options[n]); - } else { - // Only include if not in exclusion list - if (exclusionList.indexOf(n) === -1) { - mapCommandHash[n] = options[n]; - } - } - } - - options = Object.assign({}, options); - - // Ensure we have the right read preference inheritance - options.readPreference = resolveReadPreference(coll, options); - - // If we have a read preference and inline is not set as output fail hard - if ( - options.readPreference !== false && - options.readPreference !== 'primary' && - options['out'] && - (options['out'].inline !== 1 && options['out'] !== 'inline') - ) { - // Force readPreference to primary - options.readPreference = 'primary'; - // Decorate command with writeConcern if supported - applyWriteConcern(mapCommandHash, { db: coll.s.db, collection: coll }, options); - } else { - decorateWithReadConcern(mapCommandHash, coll, options); - } - - // Is bypassDocumentValidation specified - if (options.bypassDocumentValidation === true) { - mapCommandHash.bypassDocumentValidation = options.bypassDocumentValidation; - } - - // Have we specified collation - try { - decorateWithCollation(mapCommandHash, coll, options); - } catch (err) { - return callback(err, null); - } - - // Execute command - executeCommand(coll.s.db, mapCommandHash, options, (err, result) => { - if (err) return handleCallback(callback, err); - // Check if we have an error - if (1 !== result.ok || result.err || result.errmsg) { - return handleCallback(callback, toError(result)); - } - - // Create statistics value - const stats = {}; - if (result.timeMillis) stats['processtime'] = result.timeMillis; - if (result.counts) stats['counts'] = result.counts; - if (result.timing) stats['timing'] = result.timing; - - // invoked with inline? - if (result.results) { - // If we wish for no verbosity - if (options['verbose'] == null || !options['verbose']) { - return handleCallback(callback, null, result.results); - } - - return handleCallback(callback, null, { results: result.results, stats: stats }); - } - - // The returned collection - let collection = null; - - // If we have an object it's a different db - if (result.result != null && typeof result.result === 'object') { - const doc = result.result; - // Return a collection from another db - let Db = loadDb(); - collection = new Db(doc.db, coll.s.db.s.topology, coll.s.db.s.options).collection( - doc.collection - ); - } else { - // Create a collection object that wraps the result collection - collection = coll.s.db.collection(result.result); - } - - // If we wish for no verbosity - if (options['verbose'] == null || !options['verbose']) { - return handleCallback(callback, err, collection); - } - - // Return stats as third set of values - handleCallback(callback, err, { collection: collection, stats: stats }); - }); - } -} - -/** - * Functions that are passed as scope args must - * be converted to Code instances. - * @ignore - */ -function processScope(scope) { - if (!isObject(scope) || scope._bsontype === 'ObjectID') { - return scope; - } - - const keys = Object.keys(scope); - let key; - const new_scope = {}; - - for (let i = keys.length - 1; i >= 0; i--) { - key = keys[i]; - if ('function' === typeof scope[key]) { - new_scope[key] = new Code(String(scope[key])); - } else { - new_scope[key] = processScope(scope[key]); - } - } - - return new_scope; -} - -module.exports = MapReduceOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/next.js b/scripts/2.5/node_modules/mongodb/lib/operations/next.js deleted file mode 100644 index 72bc4eb9..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/operations/next.js +++ /dev/null @@ -1,32 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const defineAspects = require('./operation').defineAspects; -const OperationBase = require('./operation').OperationBase; -const nextObject = require('./common_functions').nextObject; - -class NextOperation extends OperationBase { - constructor(cursor) { - super(); - - this.cursor = cursor; - } - - execute(callback) { - const cursor = this.cursor; - - // Return the currentDoc if someone called hasNext first - if (cursor.s.currentDoc) { - const doc = cursor.s.currentDoc; - cursor.s.currentDoc = null; - return callback(null, doc); - } - - // Return the next object - nextObject(cursor, callback); - } -} - -defineAspects(NextOperation, Aspect.SKIP_SESSION); - -module.exports = NextOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/operation.js b/scripts/2.5/node_modules/mongodb/lib/operations/operation.js deleted file mode 100644 index 471627ad..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/operations/operation.js +++ /dev/null @@ -1,67 +0,0 @@ -'use strict'; - -const Aspect = { - READ_OPERATION: Symbol('READ_OPERATION'), - SKIP_SESSION: Symbol('SKIP_SESSION'), - WRITE_OPERATION: Symbol('WRITE_OPERATION'), - RETRYABLE: Symbol('RETRYABLE'), - EXECUTE_WITH_SELECTION: Symbol('EXECUTE_WITH_SELECTION') -}; - -/** - * This class acts as a parent class for any operation and is responsible for setting this.options, - * as well as setting and getting a session. - * Additionally, this class implements `hasAspect`, which determines whether an operation has - * a specific aspect, including `SKIP_SESSION` and other aspects to encode retryability - * and other functionality. - */ -class OperationBase { - constructor(options) { - this.options = Object.assign({}, options); - } - - hasAspect(aspect) { - if (this.constructor.aspects == null) { - return false; - } - return this.constructor.aspects.has(aspect); - } - - set session(session) { - Object.assign(this.options, { session }); - } - - get session() { - return this.options.session; - } - - clearSession() { - delete this.options.session; - } - - get canRetryRead() { - return true; - } - - execute() { - throw new TypeError('`execute` must be implemented for OperationBase subclasses'); - } -} - -function defineAspects(operation, aspects) { - if (!Array.isArray(aspects) && !(aspects instanceof Set)) { - aspects = [aspects]; - } - aspects = new Set(aspects); - Object.defineProperty(operation, 'aspects', { - value: aspects, - writable: false - }); - return aspects; -} - -module.exports = { - Aspect, - defineAspects, - OperationBase -}; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/options_operation.js b/scripts/2.5/node_modules/mongodb/lib/operations/options_operation.js deleted file mode 100644 index 9a739a51..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/operations/options_operation.js +++ /dev/null @@ -1,32 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const handleCallback = require('../utils').handleCallback; -const MongoError = require('../core').MongoError; - -class OptionsOperation extends OperationBase { - constructor(collection, options) { - super(options); - - this.collection = collection; - } - - execute(callback) { - const coll = this.collection; - const opts = this.options; - - coll.s.db.listCollections({ name: coll.collectionName }, opts).toArray((err, collections) => { - if (err) return handleCallback(callback, err); - if (collections.length === 0) { - return handleCallback( - callback, - MongoError.create({ message: `collection ${coll.namespace} not found`, driver: true }) - ); - } - - handleCallback(callback, err, collections[0].options || null); - }); - } -} - -module.exports = OptionsOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/profiling_level.js b/scripts/2.5/node_modules/mongodb/lib/operations/profiling_level.js deleted file mode 100644 index 3f7639b4..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/operations/profiling_level.js +++ /dev/null @@ -1,31 +0,0 @@ -'use strict'; - -const CommandOperation = require('./command'); - -class ProfilingLevelOperation extends CommandOperation { - constructor(db, command, options) { - super(db, options); - } - - _buildCommand() { - const command = { profile: -1 }; - - return command; - } - - execute(callback) { - super.execute((err, doc) => { - if (err == null && doc.ok === 1) { - const was = doc.was; - if (was === 0) return callback(null, 'off'); - if (was === 1) return callback(null, 'slow_only'); - if (was === 2) return callback(null, 'all'); - return callback(new Error('Error: illegal profiling level value ' + was), null); - } else { - err != null ? callback(err, null) : callback(new Error('Error with profile command'), null); - } - }); - } -} - -module.exports = ProfilingLevelOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/re_index.js b/scripts/2.5/node_modules/mongodb/lib/operations/re_index.js deleted file mode 100644 index 89437fe3..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/operations/re_index.js +++ /dev/null @@ -1,28 +0,0 @@ -'use strict'; - -const CommandOperation = require('./command'); -const handleCallback = require('../utils').handleCallback; - -class ReIndexOperation extends CommandOperation { - constructor(collection, options) { - super(collection.s.db, options, collection); - } - - _buildCommand() { - const collection = this.collection; - - const cmd = { reIndex: collection.collectionName }; - - return cmd; - } - - execute(callback) { - super.execute((err, result) => { - if (callback == null) return; - if (err) return handleCallback(callback, err, null); - handleCallback(callback, null, result.ok ? true : false); - }); - } -} - -module.exports = ReIndexOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/remove_user.js b/scripts/2.5/node_modules/mongodb/lib/operations/remove_user.js deleted file mode 100644 index 9a59744d..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/operations/remove_user.js +++ /dev/null @@ -1,52 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const CommandOperation = require('./command'); -const defineAspects = require('./operation').defineAspects; -const handleCallback = require('../utils').handleCallback; -const WriteConcern = require('../write_concern'); - -class RemoveUserOperation extends CommandOperation { - constructor(db, username, options) { - const commandOptions = {}; - - const writeConcern = WriteConcern.fromOptions(options); - if (writeConcern != null) { - commandOptions.writeConcern = writeConcern; - } - - if (options.dbName) { - commandOptions.dbName = options.dbName; - } - - // Add maxTimeMS to options if set - if (typeof options.maxTimeMS === 'number') { - commandOptions.maxTimeMS = options.maxTimeMS; - } - - super(db, commandOptions); - - this.username = username; - } - - _buildCommand() { - const username = this.username; - - // Build the command to execute - const command = { dropUser: username }; - - return command; - } - - execute(callback) { - // Attempt to execute command - super.execute((err, result) => { - if (err) return handleCallback(callback, err, null); - handleCallback(callback, err, result.ok ? true : false); - }); - } -} - -defineAspects(RemoveUserOperation, [Aspect.WRITE_OPERATION, Aspect.SKIP_SESSIONS]); - -module.exports = RemoveUserOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/rename.js b/scripts/2.5/node_modules/mongodb/lib/operations/rename.js deleted file mode 100644 index 8098fe6b..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/operations/rename.js +++ /dev/null @@ -1,61 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const applyWriteConcern = require('../utils').applyWriteConcern; -const checkCollectionName = require('../utils').checkCollectionName; -const executeDbAdminCommand = require('./db_ops').executeDbAdminCommand; -const handleCallback = require('../utils').handleCallback; -const loadCollection = require('../dynamic_loaders').loadCollection; -const toError = require('../utils').toError; - -class RenameOperation extends OperationBase { - constructor(collection, newName, options) { - super(options); - - this.collection = collection; - this.newName = newName; - } - - execute(callback) { - const coll = this.collection; - const newName = this.newName; - const options = this.options; - - let Collection = loadCollection(); - // Check the collection name - checkCollectionName(newName); - // Build the command - const renameCollection = coll.namespace; - const toCollection = coll.s.namespace.withCollection(newName).toString(); - const dropTarget = typeof options.dropTarget === 'boolean' ? options.dropTarget : false; - const cmd = { renameCollection: renameCollection, to: toCollection, dropTarget: dropTarget }; - - // Decorate command with writeConcern if supported - applyWriteConcern(cmd, { db: coll.s.db, collection: coll }, options); - - // Execute against admin - executeDbAdminCommand(coll.s.db.admin().s.db, cmd, options, (err, doc) => { - if (err) return handleCallback(callback, err, null); - // We have an error - if (doc.errmsg) return handleCallback(callback, toError(doc), null); - try { - return handleCallback( - callback, - null, - new Collection( - coll.s.db, - coll.s.topology, - coll.s.namespace.db, - newName, - coll.s.pkFactory, - coll.s.options - ) - ); - } catch (err) { - return handleCallback(callback, toError(err), null); - } - }); - } -} - -module.exports = RenameOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/replace_one.js b/scripts/2.5/node_modules/mongodb/lib/operations/replace_one.js deleted file mode 100644 index a5aa7608..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/operations/replace_one.js +++ /dev/null @@ -1,47 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const updateDocuments = require('./common_functions').updateDocuments; - -class ReplaceOneOperation extends OperationBase { - constructor(collection, filter, doc, options) { - super(options); - - this.collection = collection; - this.filter = filter; - this.doc = doc; - } - - execute(callback) { - const coll = this.collection; - const filter = this.filter; - const doc = this.doc; - const options = this.options; - - // Set single document update - options.multi = false; - - // Execute update - updateDocuments(coll, filter, doc, options, (err, r) => replaceCallback(err, r, doc, callback)); - } -} - -function replaceCallback(err, r, doc, callback) { - if (callback == null) return; - if (err && callback) return callback(err); - if (r == null) return callback(null, { result: { ok: 1 } }); - - r.modifiedCount = r.result.nModified != null ? r.result.nModified : r.result.n; - r.upsertedId = - Array.isArray(r.result.upserted) && r.result.upserted.length > 0 - ? r.result.upserted[0] // FIXME(major): should be `r.result.upserted[0]._id` - : null; - r.upsertedCount = - Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0; - r.matchedCount = - Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? 0 : r.result.n; - r.ops = [doc]; // TODO: Should we still have this? - if (callback) callback(null, r); -} - -module.exports = ReplaceOneOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/set_profiling_level.js b/scripts/2.5/node_modules/mongodb/lib/operations/set_profiling_level.js deleted file mode 100644 index b31cc130..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/operations/set_profiling_level.js +++ /dev/null @@ -1,48 +0,0 @@ -'use strict'; - -const CommandOperation = require('./command'); -const levelValues = new Set(['off', 'slow_only', 'all']); - -class SetProfilingLevelOperation extends CommandOperation { - constructor(db, level, options) { - let profile = 0; - - if (level === 'off') { - profile = 0; - } else if (level === 'slow_only') { - profile = 1; - } else if (level === 'all') { - profile = 2; - } - - super(db, options); - this.level = level; - this.profile = profile; - } - - _buildCommand() { - const profile = this.profile; - - // Set up the profile number - const command = { profile }; - - return command; - } - - execute(callback) { - const level = this.level; - - if (!levelValues.has(level)) { - return callback(new Error('Error: illegal profiling level value ' + level)); - } - - super.execute((err, doc) => { - if (err == null && doc.ok === 1) return callback(null, level); - return err != null - ? callback(err, null) - : callback(new Error('Error with profile command'), null); - }); - } -} - -module.exports = SetProfilingLevelOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/stats.js b/scripts/2.5/node_modules/mongodb/lib/operations/stats.js deleted file mode 100644 index ff79126e..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/operations/stats.js +++ /dev/null @@ -1,45 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const CommandOperation = require('./command'); -const defineAspects = require('./operation').defineAspects; - -/** - * Get all the collection statistics. - * - * @class - * @property {Collection} a Collection instance. - * @property {object} [options] Optional settings. See Collection.prototype.stats for a list of options. - */ -class StatsOperation extends CommandOperation { - /** - * Construct a Stats operation. - * - * @param {Collection} a Collection instance. - * @param {object} [options] Optional settings. See Collection.prototype.stats for a list of options. - */ - constructor(collection, options) { - super(collection.s.db, options, collection); - } - - _buildCommand() { - const collection = this.collection; - const options = this.options; - - // Build command object - const command = { - collStats: collection.collectionName - }; - - // Check if we have the scale value - if (options['scale'] != null) { - command['scale'] = options['scale']; - } - - return command; - } -} - -defineAspects(StatsOperation, Aspect.READ_OPERATION); - -module.exports = StatsOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/to_array.js b/scripts/2.5/node_modules/mongodb/lib/operations/to_array.js deleted file mode 100644 index db6d1a07..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/operations/to_array.js +++ /dev/null @@ -1,66 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const defineAspects = require('./operation').defineAspects; -const handleCallback = require('../utils').handleCallback; -const CursorState = require('../core/cursor').CursorState; -const OperationBase = require('./operation').OperationBase; -const push = Array.prototype.push; - -class ToArrayOperation extends OperationBase { - constructor(cursor) { - super(); - - this.cursor = cursor; - } - - execute(callback) { - const cursor = this.cursor; - const items = []; - - // Reset cursor - cursor.rewind(); - cursor.s.state = CursorState.INIT; - - // Fetch all the documents - const fetchDocs = () => { - cursor._next((err, doc) => { - if (err) { - return cursor._endSession - ? cursor._endSession(() => handleCallback(callback, err)) - : handleCallback(callback, err); - } - - if (doc == null) { - return cursor.close({ skipKillCursors: true }, () => - handleCallback(callback, null, items) - ); - } - - // Add doc to items - items.push(doc); - - // Get all buffered objects - if (cursor.bufferedCount() > 0) { - let docs = cursor.readBufferedDocuments(cursor.bufferedCount()); - - // Transform the doc if transform method added - if (cursor.s.transforms && typeof cursor.s.transforms.doc === 'function') { - docs = docs.map(cursor.s.transforms.doc); - } - - push.apply(items, docs); - } - - // Attempt a fetch - fetchDocs(); - }); - }; - - fetchDocs(); - } -} - -defineAspects(ToArrayOperation, Aspect.SKIP_SESSION); - -module.exports = ToArrayOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/update_many.js b/scripts/2.5/node_modules/mongodb/lib/operations/update_many.js deleted file mode 100644 index 9a18d253..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/operations/update_many.js +++ /dev/null @@ -1,29 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const updateCallback = require('./common_functions').updateCallback; -const updateDocuments = require('./common_functions').updateDocuments; - -class UpdateManyOperation extends OperationBase { - constructor(collection, filter, update, options) { - super(options); - - this.collection = collection; - this.filter = filter; - this.update = update; - } - - execute(callback) { - const coll = this.collection; - const filter = this.filter; - const update = this.update; - const options = this.options; - - // Set single document update - options.multi = true; - // Execute update - updateDocuments(coll, filter, update, options, (err, r) => updateCallback(err, r, callback)); - } -} - -module.exports = UpdateManyOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/update_one.js b/scripts/2.5/node_modules/mongodb/lib/operations/update_one.js deleted file mode 100644 index b1c1bc16..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/operations/update_one.js +++ /dev/null @@ -1,44 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const updateDocuments = require('./common_functions').updateDocuments; - -class UpdateOneOperation extends OperationBase { - constructor(collection, filter, update, options) { - super(options); - - this.collection = collection; - this.filter = filter; - this.update = update; - } - - execute(callback) { - const coll = this.collection; - const filter = this.filter; - const update = this.update; - const options = this.options; - - // Set single document update - options.multi = false; - // Execute update - updateDocuments(coll, filter, update, options, (err, r) => updateCallback(err, r, callback)); - } -} - -function updateCallback(err, r, callback) { - if (callback == null) return; - if (err) return callback(err); - if (r == null) return callback(null, { result: { ok: 1 } }); - r.modifiedCount = r.result.nModified != null ? r.result.nModified : r.result.n; - r.upsertedId = - Array.isArray(r.result.upserted) && r.result.upserted.length > 0 - ? r.result.upserted[0] // FIXME(major): should be `r.result.upserted[0]._id` - : null; - r.upsertedCount = - Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0; - r.matchedCount = - Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? 0 : r.result.n; - callback(null, r); -} - -module.exports = UpdateOneOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/operations/validate_collection.js b/scripts/2.5/node_modules/mongodb/lib/operations/validate_collection.js deleted file mode 100644 index 133c6c4b..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/operations/validate_collection.js +++ /dev/null @@ -1,40 +0,0 @@ -'use strict'; - -const CommandOperation = require('./command'); - -class ValidateCollectionOperation extends CommandOperation { - constructor(admin, collectionName, options) { - // Decorate command with extra options - let command = { validate: collectionName }; - const keys = Object.keys(options); - for (let i = 0; i < keys.length; i++) { - if (options.hasOwnProperty(keys[i]) && keys[i] !== 'session') { - command[keys[i]] = options[keys[i]]; - } - } - - super(admin.s.db, options, null, command); - - this.collectionName; - } - - execute(callback) { - const collectionName = this.collectionName; - - super.execute((err, doc) => { - if (err != null) return callback(err, null); - - if (doc.ok === 0) return callback(new Error('Error with validate command'), null); - if (doc.result != null && doc.result.constructor !== String) - return callback(new Error('Error with validation data'), null); - if (doc.result != null && doc.result.match(/exception|corrupt/) != null) - return callback(new Error('Error: invalid collection ' + collectionName), null); - if (doc.valid != null && !doc.valid) - return callback(new Error('Error: invalid collection ' + collectionName), null); - - return callback(null, doc); - }); - } -} - -module.exports = ValidateCollectionOperation; diff --git a/scripts/2.5/node_modules/mongodb/lib/read_concern.js b/scripts/2.5/node_modules/mongodb/lib/read_concern.js deleted file mode 100644 index b48b8e0e..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/read_concern.js +++ /dev/null @@ -1,61 +0,0 @@ -'use strict'; - -/** - * The **ReadConcern** class is a class that represents a MongoDB ReadConcern. - * @class - * @property {string} level The read concern level - * @see https://docs.mongodb.com/manual/reference/read-concern/index.html - */ -class ReadConcern { - /** - * Constructs a ReadConcern from the read concern properties. - * @param {string} [level] The read concern level ({'local'|'available'|'majority'|'linearizable'|'snapshot'}) - */ - constructor(level) { - if (level != null) { - this.level = level; - } - } - - /** - * Construct a ReadConcern given an options object. - * - * @param {object} options The options object from which to extract the write concern. - * @return {ReadConcern} - */ - static fromOptions(options) { - if (options == null) { - return; - } - - if (options.readConcern) { - if (options.readConcern instanceof ReadConcern) { - return options.readConcern; - } - - return new ReadConcern(options.readConcern.level); - } - - if (options.level) { - return new ReadConcern(options.level); - } - } - - static get MAJORITY() { - return 'majority'; - } - - static get AVAILABLE() { - return 'available'; - } - - static get LINEARIZABLE() { - return 'linearizable'; - } - - static get SNAPSHOT() { - return 'snapshot'; - } -} - -module.exports = ReadConcern; diff --git a/scripts/2.5/node_modules/mongodb/lib/topologies/mongos.js b/scripts/2.5/node_modules/mongodb/lib/topologies/mongos.js deleted file mode 100644 index ec14f485..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/topologies/mongos.js +++ /dev/null @@ -1,452 +0,0 @@ -'use strict'; - -const TopologyBase = require('./topology_base').TopologyBase; -const MongoError = require('../core').MongoError; -const CMongos = require('../core').Mongos; -const Cursor = require('../cursor'); -const Server = require('./server'); -const Store = require('./topology_base').Store; -const MAX_JS_INT = require('../utils').MAX_JS_INT; -const translateOptions = require('../utils').translateOptions; -const filterOptions = require('../utils').filterOptions; -const mergeOptions = require('../utils').mergeOptions; - -/** - * @fileOverview The **Mongos** class is a class that represents a Mongos Proxy topology and is - * used to construct connections. - * - * **Mongos Should not be used, use MongoClient.connect** - */ - -// Allowed parameters -var legalOptionNames = [ - 'ha', - 'haInterval', - 'acceptableLatencyMS', - 'poolSize', - 'ssl', - 'checkServerIdentity', - 'sslValidate', - 'sslCA', - 'sslCRL', - 'sslCert', - 'ciphers', - 'ecdhCurve', - 'sslKey', - 'sslPass', - 'socketOptions', - 'bufferMaxEntries', - 'store', - 'auto_reconnect', - 'autoReconnect', - 'emitError', - 'keepAlive', - 'keepAliveInitialDelay', - 'noDelay', - 'connectTimeoutMS', - 'socketTimeoutMS', - 'loggerLevel', - 'logger', - 'reconnectTries', - 'appname', - 'domainsEnabled', - 'servername', - 'promoteLongs', - 'promoteValues', - 'promoteBuffers', - 'promiseLibrary', - 'monitorCommands' -]; - -/** - * Creates a new Mongos instance - * @class - * @deprecated - * @param {Server[]} servers A seedlist of servers participating in the replicaset. - * @param {object} [options] Optional settings. - * @param {booelan} [options.ha=true] Turn on high availability monitoring. - * @param {number} [options.haInterval=5000] Time between each replicaset status check. - * @param {number} [options.poolSize=5] Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons. - * @param {number} [options.acceptableLatencyMS=15] Cutoff latency point in MS for MongoS proxy selection - * @param {boolean} [options.ssl=false] Use ssl connection (needs to have a mongod server with ssl support) - * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. - * @param {boolean} [options.sslValidate=false] Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {array} [options.sslCA] Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {array} [options.sslCRL] Array of revocation certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {string} [options.ciphers] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. - * @param {string} [options.ecdhCurve] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. - * @param {(Buffer|string)} [options.sslCert] String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {(Buffer|string)} [options.sslKey] String or buffer containing the certificate private key we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {(Buffer|string)} [options.sslPass] String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {string} [options.servername] String containing the server name requested via TLS SNI. - * @param {object} [options.socketOptions] Socket options - * @param {boolean} [options.socketOptions.noDelay=true] TCP Socket NoDelay option. - * @param {boolean} [options.socketOptions.keepAlive=true] TCP Connection keep alive enabled - * @param {number} [options.socketOptions.keepAliveInitialDelay=30000] The number of milliseconds to wait before initiating keepAlive on the TCP socket - * @param {number} [options.socketOptions.connectTimeoutMS=0] TCP Connection timeout setting - * @param {number} [options.socketOptions.socketTimeoutMS=0] TCP Socket timeout setting - * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. - * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology - * @fires Mongos#connect - * @fires Mongos#ha - * @fires Mongos#joined - * @fires Mongos#left - * @fires Mongos#fullsetup - * @fires Mongos#open - * @fires Mongos#close - * @fires Mongos#error - * @fires Mongos#timeout - * @fires Mongos#parseError - * @fires Mongos#commandStarted - * @fires Mongos#commandSucceeded - * @fires Mongos#commandFailed - * @property {string} parserType the parser type used (c++ or js). - * @return {Mongos} a Mongos instance. - */ -class Mongos extends TopologyBase { - constructor(servers, options) { - super(); - - options = options || {}; - var self = this; - - // Filter the options - options = filterOptions(options, legalOptionNames); - - // Ensure all the instances are Server - for (var i = 0; i < servers.length; i++) { - if (!(servers[i] instanceof Server)) { - throw MongoError.create({ - message: 'all seed list instances must be of the Server type', - driver: true - }); - } - } - - // Stored options - var storeOptions = { - force: false, - bufferMaxEntries: - typeof options.bufferMaxEntries === 'number' ? options.bufferMaxEntries : MAX_JS_INT - }; - - // Shared global store - var store = options.store || new Store(self, storeOptions); - - // Build seed list - var seedlist = servers.map(function(x) { - return { host: x.host, port: x.port }; - }); - - // Get the reconnect option - var reconnect = typeof options.auto_reconnect === 'boolean' ? options.auto_reconnect : true; - reconnect = typeof options.autoReconnect === 'boolean' ? options.autoReconnect : reconnect; - - // Clone options - var clonedOptions = mergeOptions( - {}, - { - disconnectHandler: store, - cursorFactory: Cursor, - reconnect: reconnect, - emitError: typeof options.emitError === 'boolean' ? options.emitError : true, - size: typeof options.poolSize === 'number' ? options.poolSize : 5, - monitorCommands: - typeof options.monitorCommands === 'boolean' ? options.monitorCommands : false - } - ); - - // Translate any SSL options and other connectivity options - clonedOptions = translateOptions(clonedOptions, options); - - // Socket options - var socketOptions = - options.socketOptions && Object.keys(options.socketOptions).length > 0 - ? options.socketOptions - : options; - - // Translate all the options to the core types - clonedOptions = translateOptions(clonedOptions, socketOptions); - - // Build default client information - clonedOptions.clientInfo = this.clientInfo; - // Do we have an application specific string - if (options.appname) { - clonedOptions.clientInfo.application = { name: options.appname }; - } - - // Internal state - this.s = { - // Create the Mongos - coreTopology: new CMongos(seedlist, clonedOptions), - // Server capabilities - sCapabilities: null, - // Debug turned on - debug: clonedOptions.debug, - // Store option defaults - storeOptions: storeOptions, - // Cloned options - clonedOptions: clonedOptions, - // Actual store of callbacks - store: store, - // Options - options: options, - // Server Session Pool - sessionPool: null, - // Active client sessions - sessions: new Set(), - // Promise library - promiseLibrary: options.promiseLibrary || Promise - }; - } - - // Connect - connect(_options, callback) { - var self = this; - if ('function' === typeof _options) (callback = _options), (_options = {}); - if (_options == null) _options = {}; - if (!('function' === typeof callback)) callback = null; - _options = Object.assign({}, this.s.clonedOptions, _options); - self.s.options = _options; - - // Update bufferMaxEntries - self.s.storeOptions.bufferMaxEntries = - typeof _options.bufferMaxEntries === 'number' ? _options.bufferMaxEntries : -1; - - // Error handler - var connectErrorHandler = function() { - return function(err) { - // Remove all event handlers - var events = ['timeout', 'error', 'close']; - events.forEach(function(e) { - self.removeListener(e, connectErrorHandler); - }); - - self.s.coreTopology.removeListener('connect', connectErrorHandler); - // Force close the topology - self.close(true); - - // Try to callback - try { - callback(err); - } catch (err) { - process.nextTick(function() { - throw err; - }); - } - }; - }; - - // Actual handler - var errorHandler = function(event) { - return function(err) { - if (event !== 'error') { - self.emit(event, err); - } - }; - }; - - // Error handler - var reconnectHandler = function() { - self.emit('reconnect'); - self.s.store.execute(); - }; - - // relay the event - var relay = function(event) { - return function(t, server) { - self.emit(event, t, server); - }; - }; - - // Connect handler - var connectHandler = function() { - // Clear out all the current handlers left over - var events = ['timeout', 'error', 'close', 'fullsetup']; - events.forEach(function(e) { - self.s.coreTopology.removeAllListeners(e); - }); - - // Set up listeners - self.s.coreTopology.on('timeout', errorHandler('timeout')); - self.s.coreTopology.on('error', errorHandler('error')); - self.s.coreTopology.on('close', errorHandler('close')); - - // Set up serverConfig listeners - self.s.coreTopology.on('fullsetup', function() { - self.emit('fullsetup', self); - }); - - // Emit open event - self.emit('open', null, self); - - // Return correctly - try { - callback(null, self); - } catch (err) { - process.nextTick(function() { - throw err; - }); - } - }; - - // Clear out all the current handlers left over - var events = [ - 'timeout', - 'error', - 'close', - 'serverOpening', - 'serverDescriptionChanged', - 'serverHeartbeatStarted', - 'serverHeartbeatSucceeded', - 'serverHeartbeatFailed', - 'serverClosed', - 'topologyOpening', - 'topologyClosed', - 'topologyDescriptionChanged', - 'commandStarted', - 'commandSucceeded', - 'commandFailed' - ]; - events.forEach(function(e) { - self.s.coreTopology.removeAllListeners(e); - }); - - // Set up SDAM listeners - self.s.coreTopology.on('serverDescriptionChanged', relay('serverDescriptionChanged')); - self.s.coreTopology.on('serverHeartbeatStarted', relay('serverHeartbeatStarted')); - self.s.coreTopology.on('serverHeartbeatSucceeded', relay('serverHeartbeatSucceeded')); - self.s.coreTopology.on('serverHeartbeatFailed', relay('serverHeartbeatFailed')); - self.s.coreTopology.on('serverOpening', relay('serverOpening')); - self.s.coreTopology.on('serverClosed', relay('serverClosed')); - self.s.coreTopology.on('topologyOpening', relay('topologyOpening')); - self.s.coreTopology.on('topologyClosed', relay('topologyClosed')); - self.s.coreTopology.on('topologyDescriptionChanged', relay('topologyDescriptionChanged')); - self.s.coreTopology.on('commandStarted', relay('commandStarted')); - self.s.coreTopology.on('commandSucceeded', relay('commandSucceeded')); - self.s.coreTopology.on('commandFailed', relay('commandFailed')); - - // Set up listeners - self.s.coreTopology.once('timeout', connectErrorHandler('timeout')); - self.s.coreTopology.once('error', connectErrorHandler('error')); - self.s.coreTopology.once('close', connectErrorHandler('close')); - self.s.coreTopology.once('connect', connectHandler); - // Join and leave events - self.s.coreTopology.on('joined', relay('joined')); - self.s.coreTopology.on('left', relay('left')); - - // Reconnect server - self.s.coreTopology.on('reconnect', reconnectHandler); - - // Start connection - self.s.coreTopology.connect(_options); - } -} - -Object.defineProperty(Mongos.prototype, 'haInterval', { - enumerable: true, - get: function() { - return this.s.coreTopology.s.haInterval; - } -}); - -/** - * A mongos connect event, used to verify that the connection is up and running - * - * @event Mongos#connect - * @type {Mongos} - */ - -/** - * The mongos high availability event - * - * @event Mongos#ha - * @type {function} - * @param {string} type The stage in the high availability event (start|end) - * @param {boolean} data.norepeat This is a repeating high availability process or a single execution only - * @param {number} data.id The id for this high availability request - * @param {object} data.state An object containing the information about the current replicaset - */ - -/** - * A server member left the mongos set - * - * @event Mongos#left - * @type {function} - * @param {string} type The type of member that left (primary|secondary|arbiter) - * @param {Server} server The server object that left - */ - -/** - * A server member joined the mongos set - * - * @event Mongos#joined - * @type {function} - * @param {string} type The type of member that joined (primary|secondary|arbiter) - * @param {Server} server The server object that joined - */ - -/** - * Mongos fullsetup event, emitted when all proxies in the topology have been connected to. - * - * @event Mongos#fullsetup - * @type {Mongos} - */ - -/** - * Mongos open event, emitted when mongos can start processing commands. - * - * @event Mongos#open - * @type {Mongos} - */ - -/** - * Mongos close event - * - * @event Mongos#close - * @type {object} - */ - -/** - * Mongos error event, emitted if there is an error listener. - * - * @event Mongos#error - * @type {MongoError} - */ - -/** - * Mongos timeout event - * - * @event Mongos#timeout - * @type {object} - */ - -/** - * Mongos parseError event - * - * @event Mongos#parseError - * @type {object} - */ - -/** - * An event emitted indicating a command was started, if command monitoring is enabled - * - * @event Mongos#commandStarted - * @type {object} - */ - -/** - * An event emitted indicating a command succeeded, if command monitoring is enabled - * - * @event Mongos#commandSucceeded - * @type {object} - */ - -/** - * An event emitted indicating a command failed, if command monitoring is enabled - * - * @event Mongos#commandFailed - * @type {object} - */ - -module.exports = Mongos; diff --git a/scripts/2.5/node_modules/mongodb/lib/topologies/native_topology.js b/scripts/2.5/node_modules/mongodb/lib/topologies/native_topology.js deleted file mode 100644 index 51574878..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/topologies/native_topology.js +++ /dev/null @@ -1,72 +0,0 @@ -'use strict'; - -const Topology = require('../core').Topology; -const ServerCapabilities = require('./topology_base').ServerCapabilities; -const Cursor = require('../cursor'); -const translateOptions = require('../utils').translateOptions; - -class NativeTopology extends Topology { - constructor(servers, options) { - options = options || {}; - - let clonedOptions = Object.assign( - {}, - { - cursorFactory: Cursor, - reconnect: false, - emitError: typeof options.emitError === 'boolean' ? options.emitError : true, - size: typeof options.poolSize === 'number' ? options.poolSize : 5, - monitorCommands: - typeof options.monitorCommands === 'boolean' ? options.monitorCommands : false - } - ); - - // Translate any SSL options and other connectivity options - clonedOptions = translateOptions(clonedOptions, options); - - // Socket options - var socketOptions = - options.socketOptions && Object.keys(options.socketOptions).length > 0 - ? options.socketOptions - : options; - - // Translate all the options to the core types - clonedOptions = translateOptions(clonedOptions, socketOptions); - - super(servers, clonedOptions); - - // Do we have an application specific string - if (options.appname) { - this.s.clientInfo.application = { name: options.appname }; - } - } - - capabilities() { - if (this.s.sCapabilities) return this.s.sCapabilities; - if (this.lastIsMaster() == null) return null; - this.s.sCapabilities = new ServerCapabilities(this.lastIsMaster()); - return this.s.sCapabilities; - } - - // Command - command(ns, cmd, options, callback) { - super.command(ns.toString(), cmd, options, callback); - } - - // Insert - insert(ns, ops, options, callback) { - super.insert(ns.toString(), ops, options, callback); - } - - // Update - update(ns, ops, options, callback) { - super.update(ns.toString(), ops, options, callback); - } - - // Remove - remove(ns, ops, options, callback) { - super.remove(ns.toString(), ops, options, callback); - } -} - -module.exports = NativeTopology; diff --git a/scripts/2.5/node_modules/mongodb/lib/topologies/replset.js b/scripts/2.5/node_modules/mongodb/lib/topologies/replset.js deleted file mode 100644 index 44e83d11..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/topologies/replset.js +++ /dev/null @@ -1,496 +0,0 @@ -'use strict'; - -const Server = require('./server'); -const Cursor = require('../cursor'); -const MongoError = require('../core').MongoError; -const TopologyBase = require('./topology_base').TopologyBase; -const Store = require('./topology_base').Store; -const CReplSet = require('../core').ReplSet; -const MAX_JS_INT = require('../utils').MAX_JS_INT; -const translateOptions = require('../utils').translateOptions; -const filterOptions = require('../utils').filterOptions; -const mergeOptions = require('../utils').mergeOptions; - -/** - * @fileOverview The **ReplSet** class is a class that represents a Replicaset topology and is - * used to construct connections. - * - * **ReplSet Should not be used, use MongoClient.connect** - */ - -// Allowed parameters -var legalOptionNames = [ - 'ha', - 'haInterval', - 'replicaSet', - 'rs_name', - 'secondaryAcceptableLatencyMS', - 'connectWithNoPrimary', - 'poolSize', - 'ssl', - 'checkServerIdentity', - 'sslValidate', - 'sslCA', - 'sslCert', - 'ciphers', - 'ecdhCurve', - 'sslCRL', - 'sslKey', - 'sslPass', - 'socketOptions', - 'bufferMaxEntries', - 'store', - 'auto_reconnect', - 'autoReconnect', - 'emitError', - 'keepAlive', - 'keepAliveInitialDelay', - 'noDelay', - 'connectTimeoutMS', - 'socketTimeoutMS', - 'strategy', - 'debug', - 'family', - 'loggerLevel', - 'logger', - 'reconnectTries', - 'appname', - 'domainsEnabled', - 'servername', - 'promoteLongs', - 'promoteValues', - 'promoteBuffers', - 'maxStalenessSeconds', - 'promiseLibrary', - 'minSize', - 'monitorCommands' -]; - -/** - * Creates a new ReplSet instance - * @class - * @deprecated - * @param {Server[]} servers A seedlist of servers participating in the replicaset. - * @param {object} [options] Optional settings. - * @param {boolean} [options.ha=true] Turn on high availability monitoring. - * @param {number} [options.haInterval=10000] Time between each replicaset status check. - * @param {string} [options.replicaSet] The name of the replicaset to connect to. - * @param {number} [options.secondaryAcceptableLatencyMS=15] Sets the range of servers to pick when using NEAREST (lowest ping ms + the latency fence, ex: range of 1 to (1 + 15) ms) - * @param {boolean} [options.connectWithNoPrimary=false] Sets if the driver should connect even if no primary is available - * @param {number} [options.poolSize=5] Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons. - * @param {boolean} [options.ssl=false] Use ssl connection (needs to have a mongod server with ssl support) - * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. - * @param {boolean} [options.sslValidate=false] Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {array} [options.sslCA] Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {array} [options.sslCRL] Array of revocation certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {(Buffer|string)} [options.sslCert] String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher. - * @param {string} [options.ciphers] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. - * @param {string} [options.ecdhCurve] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. - * @param {(Buffer|string)} [options.sslKey] String or buffer containing the certificate private key we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {(Buffer|string)} [options.sslPass] String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {string} [options.servername] String containing the server name requested via TLS SNI. - * @param {object} [options.socketOptions] Socket options - * @param {boolean} [options.socketOptions.noDelay=true] TCP Socket NoDelay option. - * @param {boolean} [options.socketOptions.keepAlive=true] TCP Connection keep alive enabled - * @param {number} [options.socketOptions.keepAliveInitialDelay=30000] The number of milliseconds to wait before initiating keepAlive on the TCP socket - * @param {number} [options.socketOptions.connectTimeoutMS=10000] TCP Connection timeout setting - * @param {number} [options.socketOptions.socketTimeoutMS=0] TCP Socket timeout setting - * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. - * @param {number} [options.maxStalenessSeconds=undefined] The max staleness to secondary reads (values under 10 seconds cannot be guaranteed); - * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology - * @fires ReplSet#connect - * @fires ReplSet#ha - * @fires ReplSet#joined - * @fires ReplSet#left - * @fires ReplSet#fullsetup - * @fires ReplSet#open - * @fires ReplSet#close - * @fires ReplSet#error - * @fires ReplSet#timeout - * @fires ReplSet#parseError - * @fires ReplSet#commandStarted - * @fires ReplSet#commandSucceeded - * @fires ReplSet#commandFailed - * @property {string} parserType the parser type used (c++ or js). - * @return {ReplSet} a ReplSet instance. - */ -class ReplSet extends TopologyBase { - constructor(servers, options) { - super(); - - options = options || {}; - var self = this; - - // Filter the options - options = filterOptions(options, legalOptionNames); - - // Ensure all the instances are Server - for (var i = 0; i < servers.length; i++) { - if (!(servers[i] instanceof Server)) { - throw MongoError.create({ - message: 'all seed list instances must be of the Server type', - driver: true - }); - } - } - - // Stored options - var storeOptions = { - force: false, - bufferMaxEntries: - typeof options.bufferMaxEntries === 'number' ? options.bufferMaxEntries : MAX_JS_INT - }; - - // Shared global store - var store = options.store || new Store(self, storeOptions); - - // Build seed list - var seedlist = servers.map(function(x) { - return { host: x.host, port: x.port }; - }); - - // Clone options - var clonedOptions = mergeOptions( - {}, - { - disconnectHandler: store, - cursorFactory: Cursor, - reconnect: false, - emitError: typeof options.emitError === 'boolean' ? options.emitError : true, - size: typeof options.poolSize === 'number' ? options.poolSize : 5, - monitorCommands: - typeof options.monitorCommands === 'boolean' ? options.monitorCommands : false - } - ); - - // Translate any SSL options and other connectivity options - clonedOptions = translateOptions(clonedOptions, options); - - // Socket options - var socketOptions = - options.socketOptions && Object.keys(options.socketOptions).length > 0 - ? options.socketOptions - : options; - - // Translate all the options to the core types - clonedOptions = translateOptions(clonedOptions, socketOptions); - - // Build default client information - clonedOptions.clientInfo = this.clientInfo; - // Do we have an application specific string - if (options.appname) { - clonedOptions.clientInfo.application = { name: options.appname }; - } - - // Create the ReplSet - var coreTopology = new CReplSet(seedlist, clonedOptions); - - // Listen to reconnect event - coreTopology.on('reconnect', function() { - self.emit('reconnect'); - store.execute(); - }); - - // Internal state - this.s = { - // Replicaset - coreTopology: coreTopology, - // Server capabilities - sCapabilities: null, - // Debug tag - tag: options.tag, - // Store options - storeOptions: storeOptions, - // Cloned options - clonedOptions: clonedOptions, - // Store - store: store, - // Options - options: options, - // Server Session Pool - sessionPool: null, - // Active client sessions - sessions: new Set(), - // Promise library - promiseLibrary: options.promiseLibrary || Promise - }; - - // Debug - if (clonedOptions.debug) { - // Last ismaster - Object.defineProperty(this, 'replset', { - enumerable: true, - get: function() { - return coreTopology; - } - }); - } - } - - // Connect method - connect(_options, callback) { - var self = this; - if ('function' === typeof _options) (callback = _options), (_options = {}); - if (_options == null) _options = {}; - if (!('function' === typeof callback)) callback = null; - _options = Object.assign({}, this.s.clonedOptions, _options); - self.s.options = _options; - - // Update bufferMaxEntries - self.s.storeOptions.bufferMaxEntries = - typeof _options.bufferMaxEntries === 'number' ? _options.bufferMaxEntries : -1; - - // Actual handler - var errorHandler = function(event) { - return function(err) { - if (event !== 'error') { - self.emit(event, err); - } - }; - }; - - // Clear out all the current handlers left over - var events = [ - 'timeout', - 'error', - 'close', - 'serverOpening', - 'serverDescriptionChanged', - 'serverHeartbeatStarted', - 'serverHeartbeatSucceeded', - 'serverHeartbeatFailed', - 'serverClosed', - 'topologyOpening', - 'topologyClosed', - 'topologyDescriptionChanged', - 'commandStarted', - 'commandSucceeded', - 'commandFailed', - 'joined', - 'left', - 'ping', - 'ha' - ]; - events.forEach(function(e) { - self.s.coreTopology.removeAllListeners(e); - }); - - // relay the event - var relay = function(event) { - return function(t, server) { - self.emit(event, t, server); - }; - }; - - // Replset events relay - var replsetRelay = function(event) { - return function(t, server) { - self.emit(event, t, server.lastIsMaster(), server); - }; - }; - - // Relay ha - var relayHa = function(t, state) { - self.emit('ha', t, state); - - if (t === 'start') { - self.emit('ha_connect', t, state); - } else if (t === 'end') { - self.emit('ha_ismaster', t, state); - } - }; - - // Set up serverConfig listeners - self.s.coreTopology.on('joined', replsetRelay('joined')); - self.s.coreTopology.on('left', relay('left')); - self.s.coreTopology.on('ping', relay('ping')); - self.s.coreTopology.on('ha', relayHa); - - // Set up SDAM listeners - self.s.coreTopology.on('serverDescriptionChanged', relay('serverDescriptionChanged')); - self.s.coreTopology.on('serverHeartbeatStarted', relay('serverHeartbeatStarted')); - self.s.coreTopology.on('serverHeartbeatSucceeded', relay('serverHeartbeatSucceeded')); - self.s.coreTopology.on('serverHeartbeatFailed', relay('serverHeartbeatFailed')); - self.s.coreTopology.on('serverOpening', relay('serverOpening')); - self.s.coreTopology.on('serverClosed', relay('serverClosed')); - self.s.coreTopology.on('topologyOpening', relay('topologyOpening')); - self.s.coreTopology.on('topologyClosed', relay('topologyClosed')); - self.s.coreTopology.on('topologyDescriptionChanged', relay('topologyDescriptionChanged')); - self.s.coreTopology.on('commandStarted', relay('commandStarted')); - self.s.coreTopology.on('commandSucceeded', relay('commandSucceeded')); - self.s.coreTopology.on('commandFailed', relay('commandFailed')); - - self.s.coreTopology.on('fullsetup', function() { - self.emit('fullsetup', self, self); - }); - - self.s.coreTopology.on('all', function() { - self.emit('all', null, self); - }); - - // Connect handler - var connectHandler = function() { - // Set up listeners - self.s.coreTopology.once('timeout', errorHandler('timeout')); - self.s.coreTopology.once('error', errorHandler('error')); - self.s.coreTopology.once('close', errorHandler('close')); - - // Emit open event - self.emit('open', null, self); - - // Return correctly - try { - callback(null, self); - } catch (err) { - process.nextTick(function() { - throw err; - }); - } - }; - - // Error handler - var connectErrorHandler = function() { - return function(err) { - ['timeout', 'error', 'close'].forEach(function(e) { - self.s.coreTopology.removeListener(e, connectErrorHandler); - }); - - self.s.coreTopology.removeListener('connect', connectErrorHandler); - // Destroy the replset - self.s.coreTopology.destroy(); - - // Try to callback - try { - callback(err); - } catch (err) { - if (!self.s.coreTopology.isConnected()) - process.nextTick(function() { - throw err; - }); - } - }; - }; - - // Set up listeners - self.s.coreTopology.once('timeout', connectErrorHandler('timeout')); - self.s.coreTopology.once('error', connectErrorHandler('error')); - self.s.coreTopology.once('close', connectErrorHandler('close')); - self.s.coreTopology.once('connect', connectHandler); - - // Start connection - self.s.coreTopology.connect(_options); - } - - close(forceClosed, callback) { - ['timeout', 'error', 'close', 'joined', 'left'].forEach(e => this.removeAllListeners(e)); - super.close(forceClosed, callback); - } -} - -Object.defineProperty(ReplSet.prototype, 'haInterval', { - enumerable: true, - get: function() { - return this.s.coreTopology.s.haInterval; - } -}); - -/** - * A replset connect event, used to verify that the connection is up and running - * - * @event ReplSet#connect - * @type {ReplSet} - */ - -/** - * The replset high availability event - * - * @event ReplSet#ha - * @type {function} - * @param {string} type The stage in the high availability event (start|end) - * @param {boolean} data.norepeat This is a repeating high availability process or a single execution only - * @param {number} data.id The id for this high availability request - * @param {object} data.state An object containing the information about the current replicaset - */ - -/** - * A server member left the replicaset - * - * @event ReplSet#left - * @type {function} - * @param {string} type The type of member that left (primary|secondary|arbiter) - * @param {Server} server The server object that left - */ - -/** - * A server member joined the replicaset - * - * @event ReplSet#joined - * @type {function} - * @param {string} type The type of member that joined (primary|secondary|arbiter) - * @param {Server} server The server object that joined - */ - -/** - * ReplSet open event, emitted when replicaset can start processing commands. - * - * @event ReplSet#open - * @type {Replset} - */ - -/** - * ReplSet fullsetup event, emitted when all servers in the topology have been connected to. - * - * @event ReplSet#fullsetup - * @type {Replset} - */ - -/** - * ReplSet close event - * - * @event ReplSet#close - * @type {object} - */ - -/** - * ReplSet error event, emitted if there is an error listener. - * - * @event ReplSet#error - * @type {MongoError} - */ - -/** - * ReplSet timeout event - * - * @event ReplSet#timeout - * @type {object} - */ - -/** - * ReplSet parseError event - * - * @event ReplSet#parseError - * @type {object} - */ - -/** - * An event emitted indicating a command was started, if command monitoring is enabled - * - * @event ReplSet#commandStarted - * @type {object} - */ - -/** - * An event emitted indicating a command succeeded, if command monitoring is enabled - * - * @event ReplSet#commandSucceeded - * @type {object} - */ - -/** - * An event emitted indicating a command failed, if command monitoring is enabled - * - * @event ReplSet#commandFailed - * @type {object} - */ - -module.exports = ReplSet; diff --git a/scripts/2.5/node_modules/mongodb/lib/topologies/server.js b/scripts/2.5/node_modules/mongodb/lib/topologies/server.js deleted file mode 100644 index 9bbe4350..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/topologies/server.js +++ /dev/null @@ -1,455 +0,0 @@ -'use strict'; - -const CServer = require('../core').Server; -const Cursor = require('../cursor'); -const TopologyBase = require('./topology_base').TopologyBase; -const Store = require('./topology_base').Store; -const MongoError = require('../core').MongoError; -const MAX_JS_INT = require('../utils').MAX_JS_INT; -const translateOptions = require('../utils').translateOptions; -const filterOptions = require('../utils').filterOptions; -const mergeOptions = require('../utils').mergeOptions; - -/** - * @fileOverview The **Server** class is a class that represents a single server topology and is - * used to construct connections. - * - * **Server Should not be used, use MongoClient.connect** - */ - -// Allowed parameters -var legalOptionNames = [ - 'ha', - 'haInterval', - 'acceptableLatencyMS', - 'poolSize', - 'ssl', - 'checkServerIdentity', - 'sslValidate', - 'sslCA', - 'sslCRL', - 'sslCert', - 'ciphers', - 'ecdhCurve', - 'sslKey', - 'sslPass', - 'socketOptions', - 'bufferMaxEntries', - 'store', - 'auto_reconnect', - 'autoReconnect', - 'emitError', - 'keepAlive', - 'keepAliveInitialDelay', - 'noDelay', - 'connectTimeoutMS', - 'socketTimeoutMS', - 'family', - 'loggerLevel', - 'logger', - 'reconnectTries', - 'reconnectInterval', - 'monitoring', - 'appname', - 'domainsEnabled', - 'servername', - 'promoteLongs', - 'promoteValues', - 'promoteBuffers', - 'compression', - 'promiseLibrary', - 'monitorCommands' -]; - -/** - * Creates a new Server instance - * @class - * @deprecated - * @param {string} host The host for the server, can be either an IP4, IP6 or domain socket style host. - * @param {number} [port] The server port if IP4. - * @param {object} [options] Optional settings. - * @param {number} [options.poolSize=5] Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons. - * @param {boolean} [options.ssl=false] Use ssl connection (needs to have a mongod server with ssl support) - * @param {boolean} [options.sslValidate=false] Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. - * @param {array} [options.sslCA] Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {array} [options.sslCRL] Array of revocation certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {(Buffer|string)} [options.sslCert] String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {string} [options.ciphers] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. - * @param {string} [options.ecdhCurve] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. - * @param {(Buffer|string)} [options.sslKey] String or buffer containing the certificate private key we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {(Buffer|string)} [options.sslPass] String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {string} [options.servername] String containing the server name requested via TLS SNI. - * @param {object} [options.socketOptions] Socket options - * @param {boolean} [options.socketOptions.autoReconnect=true] Reconnect on error. - * @param {boolean} [options.socketOptions.noDelay=true] TCP Socket NoDelay option. - * @param {boolean} [options.socketOptions.keepAlive=true] TCP Connection keep alive enabled - * @param {number} [options.socketOptions.keepAliveInitialDelay=30000] The number of milliseconds to wait before initiating keepAlive on the TCP socket - * @param {number} [options.socketOptions.connectTimeoutMS=0] TCP Connection timeout setting - * @param {number} [options.socketOptions.socketTimeoutMS=0] TCP Socket timeout setting - * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times - * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries - * @param {boolean} [options.monitoring=true] Triggers the server instance to call ismaster - * @param {number} [options.haInterval=10000] The interval of calling ismaster when monitoring is enabled. - * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. - * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology - * @fires Server#connect - * @fires Server#close - * @fires Server#error - * @fires Server#timeout - * @fires Server#parseError - * @fires Server#reconnect - * @fires Server#commandStarted - * @fires Server#commandSucceeded - * @fires Server#commandFailed - * @property {string} parserType the parser type used (c++ or js). - * @return {Server} a Server instance. - */ -class Server extends TopologyBase { - constructor(host, port, options) { - super(); - var self = this; - - // Filter the options - options = filterOptions(options, legalOptionNames); - - // Promise library - const promiseLibrary = options.promiseLibrary; - - // Stored options - var storeOptions = { - force: false, - bufferMaxEntries: - typeof options.bufferMaxEntries === 'number' ? options.bufferMaxEntries : MAX_JS_INT - }; - - // Shared global store - var store = options.store || new Store(self, storeOptions); - - // Detect if we have a socket connection - if (host.indexOf('/') !== -1) { - if (port != null && typeof port === 'object') { - options = port; - port = null; - } - } else if (port == null) { - throw MongoError.create({ message: 'port must be specified', driver: true }); - } - - // Get the reconnect option - var reconnect = typeof options.auto_reconnect === 'boolean' ? options.auto_reconnect : true; - reconnect = typeof options.autoReconnect === 'boolean' ? options.autoReconnect : reconnect; - - // Clone options - var clonedOptions = mergeOptions( - {}, - { - host: host, - port: port, - disconnectHandler: store, - cursorFactory: Cursor, - reconnect: reconnect, - emitError: typeof options.emitError === 'boolean' ? options.emitError : true, - size: typeof options.poolSize === 'number' ? options.poolSize : 5, - monitorCommands: - typeof options.monitorCommands === 'boolean' ? options.monitorCommands : false - } - ); - - // Translate any SSL options and other connectivity options - clonedOptions = translateOptions(clonedOptions, options); - - // Socket options - var socketOptions = - options.socketOptions && Object.keys(options.socketOptions).length > 0 - ? options.socketOptions - : options; - - // Translate all the options to the core types - clonedOptions = translateOptions(clonedOptions, socketOptions); - - // Build default client information - clonedOptions.clientInfo = this.clientInfo; - // Do we have an application specific string - if (options.appname) { - clonedOptions.clientInfo.application = { name: options.appname }; - } - - // Define the internal properties - this.s = { - // Create an instance of a server instance from core module - coreTopology: new CServer(clonedOptions), - // Server capabilities - sCapabilities: null, - // Cloned options - clonedOptions: clonedOptions, - // Reconnect - reconnect: clonedOptions.reconnect, - // Emit error - emitError: clonedOptions.emitError, - // Pool size - poolSize: clonedOptions.size, - // Store Options - storeOptions: storeOptions, - // Store - store: store, - // Host - host: host, - // Port - port: port, - // Options - options: options, - // Server Session Pool - sessionPool: null, - // Active client sessions - sessions: new Set(), - // Promise library - promiseLibrary: promiseLibrary || Promise - }; - } - - // Connect - connect(_options, callback) { - var self = this; - if ('function' === typeof _options) (callback = _options), (_options = {}); - if (_options == null) _options = this.s.clonedOptions; - if (!('function' === typeof callback)) callback = null; - _options = Object.assign({}, this.s.clonedOptions, _options); - self.s.options = _options; - - // Update bufferMaxEntries - self.s.storeOptions.bufferMaxEntries = - typeof _options.bufferMaxEntries === 'number' ? _options.bufferMaxEntries : -1; - - // Error handler - var connectErrorHandler = function() { - return function(err) { - // Remove all event handlers - var events = ['timeout', 'error', 'close']; - events.forEach(function(e) { - self.s.coreTopology.removeListener(e, connectHandlers[e]); - }); - - self.s.coreTopology.removeListener('connect', connectErrorHandler); - - // Try to callback - try { - callback(err); - } catch (err) { - process.nextTick(function() { - throw err; - }); - } - }; - }; - - // Actual handler - var errorHandler = function(event) { - return function(err) { - if (event !== 'error') { - self.emit(event, err); - } - }; - }; - - // Error handler - var reconnectHandler = function() { - self.emit('reconnect', self); - self.s.store.execute(); - }; - - // Reconnect failed - var reconnectFailedHandler = function(err) { - self.emit('reconnectFailed', err); - self.s.store.flush(err); - }; - - // Destroy called on topology, perform cleanup - var destroyHandler = function() { - self.s.store.flush(); - }; - - // relay the event - var relay = function(event) { - return function(t, server) { - self.emit(event, t, server); - }; - }; - - // Connect handler - var connectHandler = function() { - // Clear out all the current handlers left over - ['timeout', 'error', 'close', 'destroy'].forEach(function(e) { - self.s.coreTopology.removeAllListeners(e); - }); - - // Set up listeners - self.s.coreTopology.on('timeout', errorHandler('timeout')); - self.s.coreTopology.once('error', errorHandler('error')); - self.s.coreTopology.on('close', errorHandler('close')); - // Only called on destroy - self.s.coreTopology.on('destroy', destroyHandler); - - // Emit open event - self.emit('open', null, self); - - // Return correctly - try { - callback(null, self); - } catch (err) { - process.nextTick(function() { - throw err; - }); - } - }; - - // Set up listeners - var connectHandlers = { - timeout: connectErrorHandler('timeout'), - error: connectErrorHandler('error'), - close: connectErrorHandler('close') - }; - - // Clear out all the current handlers left over - [ - 'timeout', - 'error', - 'close', - 'serverOpening', - 'serverDescriptionChanged', - 'serverHeartbeatStarted', - 'serverHeartbeatSucceeded', - 'serverHeartbeatFailed', - 'serverClosed', - 'topologyOpening', - 'topologyClosed', - 'topologyDescriptionChanged', - 'commandStarted', - 'commandSucceeded', - 'commandFailed' - ].forEach(function(e) { - self.s.coreTopology.removeAllListeners(e); - }); - - // Add the event handlers - self.s.coreTopology.once('timeout', connectHandlers.timeout); - self.s.coreTopology.once('error', connectHandlers.error); - self.s.coreTopology.once('close', connectHandlers.close); - self.s.coreTopology.once('connect', connectHandler); - // Reconnect server - self.s.coreTopology.on('reconnect', reconnectHandler); - self.s.coreTopology.on('reconnectFailed', reconnectFailedHandler); - - // Set up SDAM listeners - self.s.coreTopology.on('serverDescriptionChanged', relay('serverDescriptionChanged')); - self.s.coreTopology.on('serverHeartbeatStarted', relay('serverHeartbeatStarted')); - self.s.coreTopology.on('serverHeartbeatSucceeded', relay('serverHeartbeatSucceeded')); - self.s.coreTopology.on('serverHeartbeatFailed', relay('serverHeartbeatFailed')); - self.s.coreTopology.on('serverOpening', relay('serverOpening')); - self.s.coreTopology.on('serverClosed', relay('serverClosed')); - self.s.coreTopology.on('topologyOpening', relay('topologyOpening')); - self.s.coreTopology.on('topologyClosed', relay('topologyClosed')); - self.s.coreTopology.on('topologyDescriptionChanged', relay('topologyDescriptionChanged')); - self.s.coreTopology.on('commandStarted', relay('commandStarted')); - self.s.coreTopology.on('commandSucceeded', relay('commandSucceeded')); - self.s.coreTopology.on('commandFailed', relay('commandFailed')); - self.s.coreTopology.on('attemptReconnect', relay('attemptReconnect')); - self.s.coreTopology.on('monitoring', relay('monitoring')); - - // Start connection - self.s.coreTopology.connect(_options); - } -} - -Object.defineProperty(Server.prototype, 'poolSize', { - enumerable: true, - get: function() { - return this.s.coreTopology.connections().length; - } -}); - -Object.defineProperty(Server.prototype, 'autoReconnect', { - enumerable: true, - get: function() { - return this.s.reconnect; - } -}); - -Object.defineProperty(Server.prototype, 'host', { - enumerable: true, - get: function() { - return this.s.host; - } -}); - -Object.defineProperty(Server.prototype, 'port', { - enumerable: true, - get: function() { - return this.s.port; - } -}); - -/** - * Server connect event - * - * @event Server#connect - * @type {object} - */ - -/** - * Server close event - * - * @event Server#close - * @type {object} - */ - -/** - * Server reconnect event - * - * @event Server#reconnect - * @type {object} - */ - -/** - * Server error event - * - * @event Server#error - * @type {MongoError} - */ - -/** - * Server timeout event - * - * @event Server#timeout - * @type {object} - */ - -/** - * Server parseError event - * - * @event Server#parseError - * @type {object} - */ - -/** - * An event emitted indicating a command was started, if command monitoring is enabled - * - * @event Server#commandStarted - * @type {object} - */ - -/** - * An event emitted indicating a command succeeded, if command monitoring is enabled - * - * @event Server#commandSucceeded - * @type {object} - */ - -/** - * An event emitted indicating a command failed, if command monitoring is enabled - * - * @event Server#commandFailed - * @type {object} - */ - -module.exports = Server; diff --git a/scripts/2.5/node_modules/mongodb/lib/topologies/topology_base.js b/scripts/2.5/node_modules/mongodb/lib/topologies/topology_base.js deleted file mode 100644 index e74cb9ff..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/topologies/topology_base.js +++ /dev/null @@ -1,438 +0,0 @@ -'use strict'; - -const EventEmitter = require('events'), - MongoError = require('../core').MongoError, - f = require('util').format, - os = require('os'), - translateReadPreference = require('../utils').translateReadPreference, - ClientSession = require('../core').Sessions.ClientSession; - -// The store of ops -var Store = function(topology, storeOptions) { - var self = this; - var storedOps = []; - storeOptions = storeOptions || { force: false, bufferMaxEntries: -1 }; - - // Internal state - this.s = { - storedOps: storedOps, - storeOptions: storeOptions, - topology: topology - }; - - Object.defineProperty(this, 'length', { - enumerable: true, - get: function() { - return self.s.storedOps.length; - } - }); -}; - -Store.prototype.add = function(opType, ns, ops, options, callback) { - if (this.s.storeOptions.force) { - return callback(MongoError.create({ message: 'db closed by application', driver: true })); - } - - if (this.s.storeOptions.bufferMaxEntries === 0) { - return callback( - MongoError.create({ - message: f( - 'no connection available for operation and number of stored operation > %s', - this.s.storeOptions.bufferMaxEntries - ), - driver: true - }) - ); - } - - if ( - this.s.storeOptions.bufferMaxEntries > 0 && - this.s.storedOps.length > this.s.storeOptions.bufferMaxEntries - ) { - while (this.s.storedOps.length > 0) { - var op = this.s.storedOps.shift(); - op.c( - MongoError.create({ - message: f( - 'no connection available for operation and number of stored operation > %s', - this.s.storeOptions.bufferMaxEntries - ), - driver: true - }) - ); - } - - return; - } - - this.s.storedOps.push({ t: opType, n: ns, o: ops, op: options, c: callback }); -}; - -Store.prototype.addObjectAndMethod = function(opType, object, method, params, callback) { - if (this.s.storeOptions.force) { - return callback(MongoError.create({ message: 'db closed by application', driver: true })); - } - - if (this.s.storeOptions.bufferMaxEntries === 0) { - return callback( - MongoError.create({ - message: f( - 'no connection available for operation and number of stored operation > %s', - this.s.storeOptions.bufferMaxEntries - ), - driver: true - }) - ); - } - - if ( - this.s.storeOptions.bufferMaxEntries > 0 && - this.s.storedOps.length > this.s.storeOptions.bufferMaxEntries - ) { - while (this.s.storedOps.length > 0) { - var op = this.s.storedOps.shift(); - op.c( - MongoError.create({ - message: f( - 'no connection available for operation and number of stored operation > %s', - this.s.storeOptions.bufferMaxEntries - ), - driver: true - }) - ); - } - - return; - } - - this.s.storedOps.push({ t: opType, m: method, o: object, p: params, c: callback }); -}; - -Store.prototype.flush = function(err) { - while (this.s.storedOps.length > 0) { - this.s.storedOps - .shift() - .c( - err || - MongoError.create({ message: f('no connection available for operation'), driver: true }) - ); - } -}; - -var primaryOptions = ['primary', 'primaryPreferred', 'nearest', 'secondaryPreferred']; -var secondaryOptions = ['secondary', 'secondaryPreferred']; - -Store.prototype.execute = function(options) { - options = options || {}; - // Get current ops - var ops = this.s.storedOps; - // Reset the ops - this.s.storedOps = []; - - // Unpack options - var executePrimary = typeof options.executePrimary === 'boolean' ? options.executePrimary : true; - var executeSecondary = - typeof options.executeSecondary === 'boolean' ? options.executeSecondary : true; - - // Execute all the stored ops - while (ops.length > 0) { - var op = ops.shift(); - - if (op.t === 'cursor') { - if (executePrimary && executeSecondary) { - op.o[op.m].apply(op.o, op.p); - } else if ( - executePrimary && - op.o.options && - op.o.options.readPreference && - primaryOptions.indexOf(op.o.options.readPreference.mode) !== -1 - ) { - op.o[op.m].apply(op.o, op.p); - } else if ( - !executePrimary && - executeSecondary && - op.o.options && - op.o.options.readPreference && - secondaryOptions.indexOf(op.o.options.readPreference.mode) !== -1 - ) { - op.o[op.m].apply(op.o, op.p); - } - } else if (op.t === 'auth') { - this.s.topology[op.t].apply(this.s.topology, op.o); - } else { - if (executePrimary && executeSecondary) { - this.s.topology[op.t](op.n, op.o, op.op, op.c); - } else if ( - executePrimary && - op.op && - op.op.readPreference && - primaryOptions.indexOf(op.op.readPreference.mode) !== -1 - ) { - this.s.topology[op.t](op.n, op.o, op.op, op.c); - } else if ( - !executePrimary && - executeSecondary && - op.op && - op.op.readPreference && - secondaryOptions.indexOf(op.op.readPreference.mode) !== -1 - ) { - this.s.topology[op.t](op.n, op.o, op.op, op.c); - } - } - } -}; - -Store.prototype.all = function() { - return this.s.storedOps; -}; - -// Server capabilities -var ServerCapabilities = function(ismaster) { - var setup_get_property = function(object, name, value) { - Object.defineProperty(object, name, { - enumerable: true, - get: function() { - return value; - } - }); - }; - - // Capabilities - var aggregationCursor = false; - var writeCommands = false; - var textSearch = false; - var authCommands = false; - var listCollections = false; - var listIndexes = false; - var maxNumberOfDocsInBatch = ismaster.maxWriteBatchSize || 1000; - var commandsTakeWriteConcern = false; - var commandsTakeCollation = false; - - if (ismaster.minWireVersion >= 0) { - textSearch = true; - } - - if (ismaster.maxWireVersion >= 1) { - aggregationCursor = true; - authCommands = true; - } - - if (ismaster.maxWireVersion >= 2) { - writeCommands = true; - } - - if (ismaster.maxWireVersion >= 3) { - listCollections = true; - listIndexes = true; - } - - if (ismaster.maxWireVersion >= 5) { - commandsTakeWriteConcern = true; - commandsTakeCollation = true; - } - - // If no min or max wire version set to 0 - if (ismaster.minWireVersion == null) { - ismaster.minWireVersion = 0; - } - - if (ismaster.maxWireVersion == null) { - ismaster.maxWireVersion = 0; - } - - // Map up read only parameters - setup_get_property(this, 'hasAggregationCursor', aggregationCursor); - setup_get_property(this, 'hasWriteCommands', writeCommands); - setup_get_property(this, 'hasTextSearch', textSearch); - setup_get_property(this, 'hasAuthCommands', authCommands); - setup_get_property(this, 'hasListCollectionsCommand', listCollections); - setup_get_property(this, 'hasListIndexesCommand', listIndexes); - setup_get_property(this, 'minWireVersion', ismaster.minWireVersion); - setup_get_property(this, 'maxWireVersion', ismaster.maxWireVersion); - setup_get_property(this, 'maxNumberOfDocsInBatch', maxNumberOfDocsInBatch); - setup_get_property(this, 'commandsTakeWriteConcern', commandsTakeWriteConcern); - setup_get_property(this, 'commandsTakeCollation', commandsTakeCollation); -}; - -// Get package.json variable -const driverVersion = require('../../package.json').version, - nodejsversion = f('Node.js %s, %s', process.version, os.endianness()), - type = os.type(), - name = process.platform, - architecture = process.arch, - release = os.release(); - -class TopologyBase extends EventEmitter { - constructor() { - super(); - - // Build default client information - this.clientInfo = { - driver: { - name: 'nodejs', - version: driverVersion - }, - os: { - type: type, - name: name, - architecture: architecture, - version: release - }, - platform: nodejsversion - }; - - this.setMaxListeners(Infinity); - } - - // Sessions related methods - hasSessionSupport() { - return this.logicalSessionTimeoutMinutes != null; - } - - startSession(options, clientOptions) { - const session = new ClientSession(this, this.s.sessionPool, options, clientOptions); - - session.once('ended', () => { - this.s.sessions.delete(session); - }); - - this.s.sessions.add(session); - return session; - } - - endSessions(sessions, callback) { - return this.s.coreTopology.endSessions(sessions, callback); - } - - // Server capabilities - capabilities() { - if (this.s.sCapabilities) return this.s.sCapabilities; - if (this.s.coreTopology.lastIsMaster() == null) return null; - this.s.sCapabilities = new ServerCapabilities(this.s.coreTopology.lastIsMaster()); - return this.s.sCapabilities; - } - - // Command - command(ns, cmd, options, callback) { - this.s.coreTopology.command(ns.toString(), cmd, translateReadPreference(options), callback); - } - - // Insert - insert(ns, ops, options, callback) { - this.s.coreTopology.insert(ns.toString(), ops, options, callback); - } - - // Update - update(ns, ops, options, callback) { - this.s.coreTopology.update(ns.toString(), ops, options, callback); - } - - // Remove - remove(ns, ops, options, callback) { - this.s.coreTopology.remove(ns.toString(), ops, options, callback); - } - - // IsConnected - isConnected(options) { - options = options || {}; - options = translateReadPreference(options); - - return this.s.coreTopology.isConnected(options); - } - - // IsDestroyed - isDestroyed() { - return this.s.coreTopology.isDestroyed(); - } - - // Cursor - cursor(ns, cmd, options) { - options = options || {}; - options = translateReadPreference(options); - options.disconnectHandler = this.s.store; - options.topology = this; - - return this.s.coreTopology.cursor(ns, cmd, options); - } - - lastIsMaster() { - return this.s.coreTopology.lastIsMaster(); - } - - selectServer(selector, options, callback) { - return this.s.coreTopology.selectServer(selector, options, callback); - } - - /** - * Unref all sockets - * @method - */ - unref() { - return this.s.coreTopology.unref(); - } - - /** - * All raw connections - * @method - * @return {array} - */ - connections() { - return this.s.coreTopology.connections(); - } - - close(forceClosed, callback) { - // If we have sessions, we want to individually move them to the session pool, - // and then send a single endSessions call. - this.s.sessions.forEach(session => session.endSession()); - - if (this.s.sessionPool) { - this.s.sessionPool.endAllPooledSessions(); - } - - // We need to wash out all stored processes - if (forceClosed === true) { - this.s.storeOptions.force = forceClosed; - this.s.store.flush(); - } - - this.s.coreTopology.destroy( - { - force: typeof forceClosed === 'boolean' ? forceClosed : false - }, - callback - ); - } -} - -// Properties -Object.defineProperty(TopologyBase.prototype, 'bson', { - enumerable: true, - get: function() { - return this.s.coreTopology.s.bson; - } -}); - -Object.defineProperty(TopologyBase.prototype, 'parserType', { - enumerable: true, - get: function() { - return this.s.coreTopology.parserType; - } -}); - -Object.defineProperty(TopologyBase.prototype, 'logicalSessionTimeoutMinutes', { - enumerable: true, - get: function() { - return this.s.coreTopology.logicalSessionTimeoutMinutes; - } -}); - -Object.defineProperty(TopologyBase.prototype, 'type', { - enumerable: true, - get: function() { - return this.s.coreTopology.type; - } -}); - -exports.Store = Store; -exports.ServerCapabilities = ServerCapabilities; -exports.TopologyBase = TopologyBase; diff --git a/scripts/2.5/node_modules/mongodb/lib/url_parser.js b/scripts/2.5/node_modules/mongodb/lib/url_parser.js deleted file mode 100644 index c0f10b46..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/url_parser.js +++ /dev/null @@ -1,623 +0,0 @@ -'use strict'; - -const ReadPreference = require('./core').ReadPreference, - parser = require('url'), - f = require('util').format, - Logger = require('./core').Logger, - dns = require('dns'); -const ReadConcern = require('./read_concern'); - -module.exports = function(url, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - let result; - try { - result = parser.parse(url, true); - } catch (e) { - return callback(new Error('URL malformed, cannot be parsed')); - } - - if (result.protocol !== 'mongodb:' && result.protocol !== 'mongodb+srv:') { - return callback(new Error('Invalid schema, expected `mongodb` or `mongodb+srv`')); - } - - if (result.protocol === 'mongodb:') { - return parseHandler(url, options, callback); - } - - // Otherwise parse this as an SRV record - if (result.hostname.split('.').length < 3) { - return callback(new Error('URI does not have hostname, domain name and tld')); - } - - result.domainLength = result.hostname.split('.').length; - - if (result.pathname && result.pathname.match(',')) { - return callback(new Error('Invalid URI, cannot contain multiple hostnames')); - } - - if (result.port) { - return callback(new Error('Ports not accepted with `mongodb+srv` URIs')); - } - - let srvAddress = `_mongodb._tcp.${result.host}`; - dns.resolveSrv(srvAddress, function(err, addresses) { - if (err) return callback(err); - - if (addresses.length === 0) { - return callback(new Error('No addresses found at host')); - } - - for (let i = 0; i < addresses.length; i++) { - if (!matchesParentDomain(addresses[i].name, result.hostname, result.domainLength)) { - return callback(new Error('Server record does not share hostname with parent URI')); - } - } - - let base = result.auth ? `mongodb://${result.auth}@` : `mongodb://`; - let connectionStrings = addresses.map(function(address, i) { - if (i === 0) return `${base}${address.name}:${address.port}`; - else return `${address.name}:${address.port}`; - }); - - let connectionString = connectionStrings.join(',') + '/'; - let connectionStringOptions = []; - - // Add the default database if needed - if (result.path) { - let defaultDb = result.path.slice(1); - if (defaultDb.indexOf('?') !== -1) { - defaultDb = defaultDb.slice(0, defaultDb.indexOf('?')); - } - - connectionString += defaultDb; - } - - // Default to SSL true - if (!options.ssl && !result.search) { - connectionStringOptions.push('ssl=true'); - } else if (!options.ssl && result.search && !result.search.match('ssl')) { - connectionStringOptions.push('ssl=true'); - } - - // Keep original uri options - if (result.search) { - connectionStringOptions.push(result.search.replace('?', '')); - } - - dns.resolveTxt(result.host, function(err, record) { - if (err && err.code !== 'ENODATA') return callback(err); - if (err && err.code === 'ENODATA') record = null; - - if (record) { - if (record.length > 1) { - return callback(new Error('Multiple text records not allowed')); - } - - record = record[0]; - if (record.length > 1) record = record.join(''); - else record = record[0]; - - if (!record.includes('authSource') && !record.includes('replicaSet')) { - return callback(new Error('Text record must only set `authSource` or `replicaSet`')); - } - - connectionStringOptions.push(record); - } - - // Add any options to the connection string - if (connectionStringOptions.length) { - connectionString += `?${connectionStringOptions.join('&')}`; - } - - parseHandler(connectionString, options, callback); - }); - }); -}; - -function matchesParentDomain(srvAddress, parentDomain) { - let regex = /^.*?\./; - let srv = `.${srvAddress.replace(regex, '')}`; - let parent = `.${parentDomain.replace(regex, '')}`; - if (srv.endsWith(parent)) return true; - else return false; -} - -function parseHandler(address, options, callback) { - let result, err; - try { - result = parseConnectionString(address, options); - } catch (e) { - err = e; - } - - return err ? callback(err, null) : callback(null, result); -} - -function parseConnectionString(url, options) { - // Variables - let connection_part = ''; - let auth_part = ''; - let query_string_part = ''; - let dbName = 'admin'; - - // Url parser result - let result = parser.parse(url, true); - if ((result.hostname == null || result.hostname === '') && url.indexOf('.sock') === -1) { - throw new Error('No hostname or hostnames provided in connection string'); - } - - if (result.port === '0') { - throw new Error('Invalid port (zero) with hostname'); - } - - if (!isNaN(parseInt(result.port, 10)) && parseInt(result.port, 10) > 65535) { - throw new Error('Invalid port (larger than 65535) with hostname'); - } - - if ( - result.path && - result.path.length > 0 && - result.path[0] !== '/' && - url.indexOf('.sock') === -1 - ) { - throw new Error('Missing delimiting slash between hosts and options'); - } - - if (result.query) { - for (let name in result.query) { - if (name.indexOf('::') !== -1) { - throw new Error('Double colon in host identifier'); - } - - if (result.query[name] === '') { - throw new Error('Query parameter ' + name + ' is an incomplete value pair'); - } - } - } - - if (result.auth) { - let parts = result.auth.split(':'); - if (url.indexOf(result.auth) !== -1 && parts.length > 2) { - throw new Error('Username with password containing an unescaped colon'); - } - - if (url.indexOf(result.auth) !== -1 && result.auth.indexOf('@') !== -1) { - throw new Error('Username containing an unescaped at-sign'); - } - } - - // Remove query - let clean = url.split('?').shift(); - - // Extract the list of hosts - let strings = clean.split(','); - let hosts = []; - - for (let i = 0; i < strings.length; i++) { - let hostString = strings[i]; - - if (hostString.indexOf('mongodb') !== -1) { - if (hostString.indexOf('@') !== -1) { - hosts.push(hostString.split('@').pop()); - } else { - hosts.push(hostString.substr('mongodb://'.length)); - } - } else if (hostString.indexOf('/') !== -1) { - hosts.push(hostString.split('/').shift()); - } else if (hostString.indexOf('/') === -1) { - hosts.push(hostString.trim()); - } - } - - for (let i = 0; i < hosts.length; i++) { - let r = parser.parse(f('mongodb://%s', hosts[i].trim())); - if (r.path && r.path.indexOf('.sock') !== -1) continue; - if (r.path && r.path.indexOf(':') !== -1) { - // Not connecting to a socket so check for an extra slash in the hostname. - // Using String#split as perf is better than match. - if (r.path.split('/').length > 1 && r.path.indexOf('::') === -1) { - throw new Error('Slash in host identifier'); - } else { - throw new Error('Double colon in host identifier'); - } - } - } - - // If we have a ? mark cut the query elements off - if (url.indexOf('?') !== -1) { - query_string_part = url.substr(url.indexOf('?') + 1); - connection_part = url.substring('mongodb://'.length, url.indexOf('?')); - } else { - connection_part = url.substring('mongodb://'.length); - } - - // Check if we have auth params - if (connection_part.indexOf('@') !== -1) { - auth_part = connection_part.split('@')[0]; - connection_part = connection_part.split('@')[1]; - } - - // Check there is not more than one unescaped slash - if (connection_part.split('/').length > 2) { - throw new Error( - "Unsupported host '" + - connection_part.split('?')[0] + - "', hosts must be URL encoded and contain at most one unencoded slash" - ); - } - - // Check if the connection string has a db - if (connection_part.indexOf('.sock') !== -1) { - if (connection_part.indexOf('.sock/') !== -1) { - dbName = connection_part.split('.sock/')[1]; - // Check if multiple database names provided, or just an illegal trailing backslash - if (dbName.indexOf('/') !== -1) { - if (dbName.split('/').length === 2 && dbName.split('/')[1].length === 0) { - throw new Error('Illegal trailing backslash after database name'); - } - throw new Error('More than 1 database name in URL'); - } - connection_part = connection_part.split( - '/', - connection_part.indexOf('.sock') + '.sock'.length - ); - } - } else if (connection_part.indexOf('/') !== -1) { - // Check if multiple database names provided, or just an illegal trailing backslash - if (connection_part.split('/').length > 2) { - if (connection_part.split('/')[2].length === 0) { - throw new Error('Illegal trailing backslash after database name'); - } - throw new Error('More than 1 database name in URL'); - } - dbName = connection_part.split('/')[1]; - connection_part = connection_part.split('/')[0]; - } - - // URI decode the host information - connection_part = decodeURIComponent(connection_part); - - // Result object - let object = {}; - - // Pick apart the authentication part of the string - let authPart = auth_part || ''; - let auth = authPart.split(':', 2); - - // Decode the authentication URI components and verify integrity - let user = decodeURIComponent(auth[0]); - if (auth[0] !== encodeURIComponent(user)) { - throw new Error('Username contains an illegal unescaped character'); - } - auth[0] = user; - - if (auth[1]) { - let pass = decodeURIComponent(auth[1]); - if (auth[1] !== encodeURIComponent(pass)) { - throw new Error('Password contains an illegal unescaped character'); - } - auth[1] = pass; - } - - // Add auth to final object if we have 2 elements - if (auth.length === 2) object.auth = { user: auth[0], password: auth[1] }; - // if user provided auth options, use that - if (options && options.auth != null) object.auth = options.auth; - - // Variables used for temporary storage - let hostPart; - let urlOptions; - let servers; - let compression; - let serverOptions = { socketOptions: {} }; - let dbOptions = { read_preference_tags: [] }; - let replSetServersOptions = { socketOptions: {} }; - let mongosOptions = { socketOptions: {} }; - // Add server options to final object - object.server_options = serverOptions; - object.db_options = dbOptions; - object.rs_options = replSetServersOptions; - object.mongos_options = mongosOptions; - - // Let's check if we are using a domain socket - if (url.match(/\.sock/)) { - // Split out the socket part - let domainSocket = url.substring( - url.indexOf('mongodb://') + 'mongodb://'.length, - url.lastIndexOf('.sock') + '.sock'.length - ); - // Clean out any auth stuff if any - if (domainSocket.indexOf('@') !== -1) domainSocket = domainSocket.split('@')[1]; - domainSocket = decodeURIComponent(domainSocket); - servers = [{ domain_socket: domainSocket }]; - } else { - // Split up the db - hostPart = connection_part; - // Deduplicate servers - let deduplicatedServers = {}; - - // Parse all server results - servers = hostPart - .split(',') - .map(function(h) { - let _host, _port, ipv6match; - //check if it matches [IPv6]:port, where the port number is optional - if ((ipv6match = /\[([^\]]+)\](?::(.+))?/.exec(h))) { - _host = ipv6match[1]; - _port = parseInt(ipv6match[2], 10) || 27017; - } else { - //otherwise assume it's IPv4, or plain hostname - let hostPort = h.split(':', 2); - _host = hostPort[0] || 'localhost'; - _port = hostPort[1] != null ? parseInt(hostPort[1], 10) : 27017; - // Check for localhost?safe=true style case - if (_host.indexOf('?') !== -1) _host = _host.split(/\?/)[0]; - } - - // No entry returned for duplicate server - if (deduplicatedServers[_host + '_' + _port]) return null; - deduplicatedServers[_host + '_' + _port] = 1; - - // Return the mapped object - return { host: _host, port: _port }; - }) - .filter(function(x) { - return x != null; - }); - } - - // Get the db name - object.dbName = dbName || 'admin'; - // Split up all the options - urlOptions = (query_string_part || '').split(/[&;]/); - // Ugh, we have to figure out which options go to which constructor manually. - urlOptions.forEach(function(opt) { - if (!opt) return; - var splitOpt = opt.split('='), - name = splitOpt[0], - value = splitOpt[1]; - - // Options implementations - switch (name) { - case 'slaveOk': - case 'slave_ok': - serverOptions.slave_ok = value === 'true'; - dbOptions.slaveOk = value === 'true'; - break; - case 'maxPoolSize': - case 'poolSize': - serverOptions.poolSize = parseInt(value, 10); - replSetServersOptions.poolSize = parseInt(value, 10); - break; - case 'appname': - object.appname = decodeURIComponent(value); - break; - case 'autoReconnect': - case 'auto_reconnect': - serverOptions.auto_reconnect = value === 'true'; - break; - case 'ssl': - if (value === 'prefer') { - serverOptions.ssl = value; - replSetServersOptions.ssl = value; - mongosOptions.ssl = value; - break; - } - serverOptions.ssl = value === 'true'; - replSetServersOptions.ssl = value === 'true'; - mongosOptions.ssl = value === 'true'; - break; - case 'sslValidate': - serverOptions.sslValidate = value === 'true'; - replSetServersOptions.sslValidate = value === 'true'; - mongosOptions.sslValidate = value === 'true'; - break; - case 'replicaSet': - case 'rs_name': - replSetServersOptions.rs_name = value; - break; - case 'reconnectWait': - replSetServersOptions.reconnectWait = parseInt(value, 10); - break; - case 'retries': - replSetServersOptions.retries = parseInt(value, 10); - break; - case 'readSecondary': - case 'read_secondary': - replSetServersOptions.read_secondary = value === 'true'; - break; - case 'fsync': - dbOptions.fsync = value === 'true'; - break; - case 'journal': - dbOptions.j = value === 'true'; - break; - case 'safe': - dbOptions.safe = value === 'true'; - break; - case 'nativeParser': - case 'native_parser': - dbOptions.native_parser = value === 'true'; - break; - case 'readConcernLevel': - dbOptions.readConcern = new ReadConcern(value); - break; - case 'connectTimeoutMS': - serverOptions.socketOptions.connectTimeoutMS = parseInt(value, 10); - replSetServersOptions.socketOptions.connectTimeoutMS = parseInt(value, 10); - mongosOptions.socketOptions.connectTimeoutMS = parseInt(value, 10); - break; - case 'socketTimeoutMS': - serverOptions.socketOptions.socketTimeoutMS = parseInt(value, 10); - replSetServersOptions.socketOptions.socketTimeoutMS = parseInt(value, 10); - mongosOptions.socketOptions.socketTimeoutMS = parseInt(value, 10); - break; - case 'w': - dbOptions.w = parseInt(value, 10); - if (isNaN(dbOptions.w)) dbOptions.w = value; - break; - case 'authSource': - dbOptions.authSource = value; - break; - case 'gssapiServiceName': - dbOptions.gssapiServiceName = value; - break; - case 'authMechanism': - if (value === 'GSSAPI') { - // If no password provided decode only the principal - if (object.auth == null) { - let urlDecodeAuthPart = decodeURIComponent(authPart); - if (urlDecodeAuthPart.indexOf('@') === -1) - throw new Error('GSSAPI requires a provided principal'); - object.auth = { user: urlDecodeAuthPart, password: null }; - } else { - object.auth.user = decodeURIComponent(object.auth.user); - } - } else if (value === 'MONGODB-X509') { - object.auth = { user: decodeURIComponent(authPart) }; - } - - // Only support GSSAPI or MONGODB-CR for now - if ( - value !== 'GSSAPI' && - value !== 'MONGODB-X509' && - value !== 'MONGODB-CR' && - value !== 'DEFAULT' && - value !== 'SCRAM-SHA-1' && - value !== 'SCRAM-SHA-256' && - value !== 'PLAIN' - ) - throw new Error( - 'Only DEFAULT, GSSAPI, PLAIN, MONGODB-X509, or SCRAM-SHA-1 is supported by authMechanism' - ); - - // Authentication mechanism - dbOptions.authMechanism = value; - break; - case 'authMechanismProperties': - { - // Split up into key, value pairs - let values = value.split(','); - let o = {}; - // For each value split into key, value - values.forEach(function(x) { - let v = x.split(':'); - o[v[0]] = v[1]; - }); - - // Set all authMechanismProperties - dbOptions.authMechanismProperties = o; - // Set the service name value - if (typeof o.SERVICE_NAME === 'string') dbOptions.gssapiServiceName = o.SERVICE_NAME; - if (typeof o.SERVICE_REALM === 'string') dbOptions.gssapiServiceRealm = o.SERVICE_REALM; - if (typeof o.CANONICALIZE_HOST_NAME === 'string') - dbOptions.gssapiCanonicalizeHostName = - o.CANONICALIZE_HOST_NAME === 'true' ? true : false; - } - break; - case 'wtimeoutMS': - dbOptions.wtimeout = parseInt(value, 10); - break; - case 'readPreference': - if (!ReadPreference.isValid(value)) - throw new Error( - 'readPreference must be either primary/primaryPreferred/secondary/secondaryPreferred/nearest' - ); - dbOptions.readPreference = value; - break; - case 'maxStalenessSeconds': - dbOptions.maxStalenessSeconds = parseInt(value, 10); - break; - case 'readPreferenceTags': - { - // Decode the value - value = decodeURIComponent(value); - // Contains the tag object - let tagObject = {}; - if (value == null || value === '') { - dbOptions.read_preference_tags.push(tagObject); - break; - } - - // Split up the tags - let tags = value.split(/,/); - for (let i = 0; i < tags.length; i++) { - let parts = tags[i].trim().split(/:/); - tagObject[parts[0]] = parts[1]; - } - - // Set the preferences tags - dbOptions.read_preference_tags.push(tagObject); - } - break; - case 'compressors': - { - compression = serverOptions.compression || {}; - let compressors = value.split(','); - if ( - !compressors.every(function(compressor) { - return compressor === 'snappy' || compressor === 'zlib'; - }) - ) { - throw new Error('Compressors must be at least one of snappy or zlib'); - } - - compression.compressors = compressors; - serverOptions.compression = compression; - } - break; - case 'zlibCompressionLevel': - { - compression = serverOptions.compression || {}; - let zlibCompressionLevel = parseInt(value, 10); - if (zlibCompressionLevel < -1 || zlibCompressionLevel > 9) { - throw new Error('zlibCompressionLevel must be an integer between -1 and 9'); - } - - compression.zlibCompressionLevel = zlibCompressionLevel; - serverOptions.compression = compression; - } - break; - case 'retryWrites': - dbOptions.retryWrites = value === 'true'; - break; - case 'minSize': - dbOptions.minSize = parseInt(value, 10); - break; - default: - { - let logger = Logger('URL Parser'); - logger.warn(`${name} is not supported as a connection string option`); - } - break; - } - }); - - // No tags: should be null (not []) - if (dbOptions.read_preference_tags.length === 0) { - dbOptions.read_preference_tags = null; - } - - // Validate if there are an invalid write concern combinations - if ( - (dbOptions.w === -1 || dbOptions.w === 0) && - (dbOptions.journal === true || dbOptions.fsync === true || dbOptions.safe === true) - ) - throw new Error('w set to -1 or 0 cannot be combined with safe/w/journal/fsync'); - - // If no read preference set it to primary - if (!dbOptions.readPreference) { - dbOptions.readPreference = 'primary'; - } - - // make sure that user-provided options are applied with priority - dbOptions = Object.assign(dbOptions, options); - - // Add servers to result - object.servers = servers; - - // Returned parsed object - return object; -} diff --git a/scripts/2.5/node_modules/mongodb/lib/utils.js b/scripts/2.5/node_modules/mongodb/lib/utils.js deleted file mode 100644 index 98dee668..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/utils.js +++ /dev/null @@ -1,716 +0,0 @@ -'use strict'; - -const MongoError = require('./core/error').MongoError; -const ReadPreference = require('./core/topologies/read_preference'); -const WriteConcern = require('./write_concern'); - -var shallowClone = function(obj) { - var copy = {}; - for (var name in obj) copy[name] = obj[name]; - return copy; -}; - -// Figure out the read preference -var translateReadPreference = function(options) { - var r = null; - if (options.readPreference) { - r = options.readPreference; - } else { - return options; - } - - if (typeof r === 'string') { - options.readPreference = new ReadPreference(r); - } else if (r && !(r instanceof ReadPreference) && typeof r === 'object') { - const mode = r.mode || r.preference; - if (mode && typeof mode === 'string') { - options.readPreference = new ReadPreference(mode, r.tags, { - maxStalenessSeconds: r.maxStalenessSeconds - }); - } - } else if (!(r instanceof ReadPreference)) { - throw new TypeError('Invalid read preference: ' + r); - } - - return options; -}; - -// Set simple property -var getSingleProperty = function(obj, name, value) { - Object.defineProperty(obj, name, { - enumerable: true, - get: function() { - return value; - } - }); -}; - -var formatSortValue = (exports.formatSortValue = function(sortDirection) { - var value = ('' + sortDirection).toLowerCase(); - - switch (value) { - case 'ascending': - case 'asc': - case '1': - return 1; - case 'descending': - case 'desc': - case '-1': - return -1; - default: - throw new Error( - 'Illegal sort clause, must be of the form ' + - "[['field1', '(ascending|descending)'], " + - "['field2', '(ascending|descending)']]" - ); - } -}); - -var formattedOrderClause = (exports.formattedOrderClause = function(sortValue) { - var orderBy = {}; - if (sortValue == null) return null; - if (Array.isArray(sortValue)) { - if (sortValue.length === 0) { - return null; - } - - for (var i = 0; i < sortValue.length; i++) { - if (sortValue[i].constructor === String) { - orderBy[sortValue[i]] = 1; - } else { - orderBy[sortValue[i][0]] = formatSortValue(sortValue[i][1]); - } - } - } else if (sortValue != null && typeof sortValue === 'object') { - orderBy = sortValue; - } else if (typeof sortValue === 'string') { - orderBy[sortValue] = 1; - } else { - throw new Error( - 'Illegal sort clause, must be of the form ' + - "[['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]" - ); - } - - return orderBy; -}); - -var checkCollectionName = function checkCollectionName(collectionName) { - if ('string' !== typeof collectionName) { - throw new MongoError('collection name must be a String'); - } - - if (!collectionName || collectionName.indexOf('..') !== -1) { - throw new MongoError('collection names cannot be empty'); - } - - if ( - collectionName.indexOf('$') !== -1 && - collectionName.match(/((^\$cmd)|(oplog\.\$main))/) == null - ) { - throw new MongoError("collection names must not contain '$'"); - } - - if (collectionName.match(/^\.|\.$/) != null) { - throw new MongoError("collection names must not start or end with '.'"); - } - - // Validate that we are not passing 0x00 in the collection name - if (collectionName.indexOf('\x00') !== -1) { - throw new MongoError('collection names cannot contain a null character'); - } -}; - -var handleCallback = function(callback, err, value1, value2) { - try { - if (callback == null) return; - - if (callback) { - return value2 ? callback(err, value1, value2) : callback(err, value1); - } - } catch (err) { - process.nextTick(function() { - throw err; - }); - return false; - } - - return true; -}; - -/** - * Wrap a Mongo error document in an Error instance - * @ignore - * @api private - */ -var toError = function(error) { - if (error instanceof Error) return error; - - var msg = error.err || error.errmsg || error.errMessage || error; - var e = MongoError.create({ message: msg, driver: true }); - - // Get all object keys - var keys = typeof error === 'object' ? Object.keys(error) : []; - - for (var i = 0; i < keys.length; i++) { - try { - e[keys[i]] = error[keys[i]]; - } catch (err) { - // continue - } - } - - return e; -}; - -/** - * @ignore - */ -var normalizeHintField = function normalizeHintField(hint) { - var finalHint = null; - - if (typeof hint === 'string') { - finalHint = hint; - } else if (Array.isArray(hint)) { - finalHint = {}; - - hint.forEach(function(param) { - finalHint[param] = 1; - }); - } else if (hint != null && typeof hint === 'object') { - finalHint = {}; - for (var name in hint) { - finalHint[name] = hint[name]; - } - } - - return finalHint; -}; - -/** - * Create index name based on field spec - * - * @ignore - * @api private - */ -var parseIndexOptions = function(fieldOrSpec) { - var fieldHash = {}; - var indexes = []; - var keys; - - // Get all the fields accordingly - if ('string' === typeof fieldOrSpec) { - // 'type' - indexes.push(fieldOrSpec + '_' + 1); - fieldHash[fieldOrSpec] = 1; - } else if (Array.isArray(fieldOrSpec)) { - fieldOrSpec.forEach(function(f) { - if ('string' === typeof f) { - // [{location:'2d'}, 'type'] - indexes.push(f + '_' + 1); - fieldHash[f] = 1; - } else if (Array.isArray(f)) { - // [['location', '2d'],['type', 1]] - indexes.push(f[0] + '_' + (f[1] || 1)); - fieldHash[f[0]] = f[1] || 1; - } else if (isObject(f)) { - // [{location:'2d'}, {type:1}] - keys = Object.keys(f); - keys.forEach(function(k) { - indexes.push(k + '_' + f[k]); - fieldHash[k] = f[k]; - }); - } else { - // undefined (ignore) - } - }); - } else if (isObject(fieldOrSpec)) { - // {location:'2d', type:1} - keys = Object.keys(fieldOrSpec); - keys.forEach(function(key) { - indexes.push(key + '_' + fieldOrSpec[key]); - fieldHash[key] = fieldOrSpec[key]; - }); - } - - return { - name: indexes.join('_'), - keys: keys, - fieldHash: fieldHash - }; -}; - -var isObject = (exports.isObject = function(arg) { - return '[object Object]' === Object.prototype.toString.call(arg); -}); - -var debugOptions = function(debugFields, options) { - var finaloptions = {}; - debugFields.forEach(function(n) { - finaloptions[n] = options[n]; - }); - - return finaloptions; -}; - -var decorateCommand = function(command, options, exclude) { - for (var name in options) { - if (exclude.indexOf(name) === -1) command[name] = options[name]; - } - - return command; -}; - -var mergeOptions = function(target, source) { - for (var name in source) { - target[name] = source[name]; - } - - return target; -}; - -// Merge options with translation -var translateOptions = function(target, source) { - var translations = { - // SSL translation options - sslCA: 'ca', - sslCRL: 'crl', - sslValidate: 'rejectUnauthorized', - sslKey: 'key', - sslCert: 'cert', - sslPass: 'passphrase', - // SocketTimeout translation options - socketTimeoutMS: 'socketTimeout', - connectTimeoutMS: 'connectionTimeout', - // Replicaset options - replicaSet: 'setName', - rs_name: 'setName', - secondaryAcceptableLatencyMS: 'acceptableLatency', - connectWithNoPrimary: 'secondaryOnlyConnectionAllowed', - // Mongos options - acceptableLatencyMS: 'localThresholdMS' - }; - - for (var name in source) { - if (translations[name]) { - target[translations[name]] = source[name]; - } else { - target[name] = source[name]; - } - } - - return target; -}; - -var filterOptions = function(options, names) { - var filterOptions = {}; - - for (var name in options) { - if (names.indexOf(name) !== -1) filterOptions[name] = options[name]; - } - - // Filtered options - return filterOptions; -}; - -// Write concern keys -var writeConcernKeys = ['w', 'j', 'wtimeout', 'fsync']; - -// Merge the write concern options -var mergeOptionsAndWriteConcern = function(targetOptions, sourceOptions, keys, mergeWriteConcern) { - // Mix in any allowed options - for (var i = 0; i < keys.length; i++) { - if (!targetOptions[keys[i]] && sourceOptions[keys[i]] !== undefined) { - targetOptions[keys[i]] = sourceOptions[keys[i]]; - } - } - - // No merging of write concern - if (!mergeWriteConcern) return targetOptions; - - // Found no write Concern options - var found = false; - for (i = 0; i < writeConcernKeys.length; i++) { - if (targetOptions[writeConcernKeys[i]]) { - found = true; - break; - } - } - - if (!found) { - for (i = 0; i < writeConcernKeys.length; i++) { - if (sourceOptions[writeConcernKeys[i]]) { - targetOptions[writeConcernKeys[i]] = sourceOptions[writeConcernKeys[i]]; - } - } - } - - return targetOptions; -}; - -/** - * Executes the given operation with provided arguments. - * - * This method reduces large amounts of duplication in the entire codebase by providing - * a single point for determining whether callbacks or promises should be used. Additionally - * it allows for a single point of entry to provide features such as implicit sessions, which - * are required by the Driver Sessions specification in the event that a ClientSession is - * not provided - * - * @param {object} topology The topology to execute this operation on - * @param {function} operation The operation to execute - * @param {array} args Arguments to apply the provided operation - * @param {object} [options] Options that modify the behavior of the method - */ -const executeLegacyOperation = (topology, operation, args, options) => { - if (topology == null) { - throw new TypeError('This method requires a valid topology instance'); - } - - if (!Array.isArray(args)) { - throw new TypeError('This method requires an array of arguments to apply'); - } - - options = options || {}; - const Promise = topology.s.promiseLibrary; - let callback = args[args.length - 1]; - - // The driver sessions spec mandates that we implicitly create sessions for operations - // that are not explicitly provided with a session. - let session, opOptions, owner; - if (!options.skipSessions && topology.hasSessionSupport()) { - opOptions = args[args.length - 2]; - if (opOptions == null || opOptions.session == null) { - owner = Symbol(); - session = topology.startSession({ owner }); - const optionsIndex = args.length - 2; - args[optionsIndex] = Object.assign({}, args[optionsIndex], { session: session }); - } else if (opOptions.session && opOptions.session.hasEnded) { - throw new MongoError('Use of expired sessions is not permitted'); - } - } - - const makeExecuteCallback = (resolve, reject) => - function executeCallback(err, result) { - if (session && session.owner === owner && !options.returnsCursor) { - session.endSession(() => { - delete opOptions.session; - if (err) return reject(err); - resolve(result); - }); - } else { - if (err) return reject(err); - resolve(result); - } - }; - - // Execute using callback - if (typeof callback === 'function') { - callback = args.pop(); - const handler = makeExecuteCallback( - result => callback(null, result), - err => callback(err, null) - ); - args.push(handler); - - try { - return operation.apply(null, args); - } catch (e) { - handler(e); - throw e; - } - } - - // Return a Promise - if (args[args.length - 1] != null) { - throw new TypeError('final argument to `executeLegacyOperation` must be a callback'); - } - - return new Promise(function(resolve, reject) { - const handler = makeExecuteCallback(resolve, reject); - args[args.length - 1] = handler; - - try { - return operation.apply(null, args); - } catch (e) { - handler(e); - } - }); -}; - -/** - * Applies retryWrites: true to a command if retryWrites is set on the command's database. - * - * @param {object} target The target command to which we will apply retryWrites. - * @param {object} db The database from which we can inherit a retryWrites value. - */ -function applyRetryableWrites(target, db) { - if (db && db.s.options.retryWrites) { - target.retryWrites = true; - } - - return target; -} - -/** - * Applies a write concern to a command based on well defined inheritance rules, optionally - * detecting support for the write concern in the first place. - * - * @param {Object} target the target command we will be applying the write concern to - * @param {Object} sources sources where we can inherit default write concerns from - * @param {Object} [options] optional settings passed into a command for write concern overrides - * @returns {Object} the (now) decorated target - */ -function applyWriteConcern(target, sources, options) { - options = options || {}; - const db = sources.db; - const coll = sources.collection; - - if (options.session && options.session.inTransaction()) { - // writeConcern is not allowed within a multi-statement transaction - if (target.writeConcern) { - delete target.writeConcern; - } - - return target; - } - - const writeConcern = WriteConcern.fromOptions(options); - if (writeConcern) { - return Object.assign(target, { writeConcern }); - } - - if (coll && coll.writeConcern) { - return Object.assign(target, { writeConcern: Object.assign({}, coll.writeConcern) }); - } - - if (db && db.writeConcern) { - return Object.assign(target, { writeConcern: Object.assign({}, db.writeConcern) }); - } - - return target; -} - -/** - * Resolves a read preference based on well-defined inheritance rules. This method will not only - * determine the read preference (if there is one), but will also ensure the returned value is a - * properly constructed instance of `ReadPreference`. - * - * @param {Collection|Db|MongoClient} parent The parent of the operation on which to determine the read - * preference, used for determining the inherited read preference. - * @param {Object} options The options passed into the method, potentially containing a read preference - * @returns {(ReadPreference|null)} The resolved read preference - */ -function resolveReadPreference(parent, options) { - options = options || {}; - const session = options.session; - - const inheritedReadPreference = parent.readPreference; - - let readPreference; - if (options.readPreference) { - readPreference = ReadPreference.fromOptions(options); - } else if (session && session.inTransaction() && session.transaction.options.readPreference) { - // The transaction’s read preference MUST override all other user configurable read preferences. - readPreference = session.transaction.options.readPreference; - } else if (inheritedReadPreference != null) { - readPreference = inheritedReadPreference; - } else { - throw new Error('No readPreference was provided or inherited.'); - } - - return typeof readPreference === 'string' ? new ReadPreference(readPreference) : readPreference; -} - -/** - * Checks if a given value is a Promise - * - * @param {*} maybePromise - * @return true if the provided value is a Promise - */ -function isPromiseLike(maybePromise) { - return maybePromise && typeof maybePromise.then === 'function'; -} - -/** - * Applies collation to a given command. - * - * @param {object} [command] the command on which to apply collation - * @param {(Cursor|Collection)} [target] target of command - * @param {object} [options] options containing collation settings - */ -function decorateWithCollation(command, target, options) { - const topology = (target.s && target.s.topology) || target.topology; - - if (!topology) { - throw new TypeError('parameter "target" is missing a topology'); - } - - const capabilities = topology.capabilities(); - if (options.collation && typeof options.collation === 'object') { - if (capabilities && capabilities.commandsTakeCollation) { - command.collation = options.collation; - } else { - throw new MongoError(`Current topology does not support collation`); - } - } -} - -/** - * Applies a read concern to a given command. - * - * @param {object} command the command on which to apply the read concern - * @param {Collection} coll the parent collection of the operation calling this method - */ -function decorateWithReadConcern(command, coll, options) { - if (options && options.session && options.session.inTransaction()) { - return; - } - let readConcern = Object.assign({}, command.readConcern || {}); - if (coll.s.readConcern) { - Object.assign(readConcern, coll.s.readConcern); - } - - if (Object.keys(readConcern).length > 0) { - Object.assign(command, { readConcern: readConcern }); - } -} - -const emitProcessWarning = msg => process.emitWarning(msg, 'DeprecationWarning'); -const emitConsoleWarning = msg => console.error(msg); -const emitDeprecationWarning = process.emitWarning ? emitProcessWarning : emitConsoleWarning; - -/** - * Default message handler for generating deprecation warnings. - * - * @param {string} name function name - * @param {string} option option name - * @return {string} warning message - * @ignore - * @api private - */ -function defaultMsgHandler(name, option) { - return `${name} option [${option}] is deprecated and will be removed in a later version.`; -} - -/** - * Deprecates a given function's options. - * - * @param {object} config configuration for deprecation - * @param {string} config.name function name - * @param {Array} config.deprecatedOptions options to deprecate - * @param {number} config.optionsIndex index of options object in function arguments array - * @param {function} [config.msgHandler] optional custom message handler to generate warnings - * @param {function} fn the target function of deprecation - * @return {function} modified function that warns once per deprecated option, and executes original function - * @ignore - * @api private - */ -function deprecateOptions(config, fn) { - if (process.noDeprecation === true) { - return fn; - } - - const msgHandler = config.msgHandler ? config.msgHandler : defaultMsgHandler; - - const optionsWarned = new Set(); - function deprecated() { - const options = arguments[config.optionsIndex]; - - // ensure options is a valid, non-empty object, otherwise short-circuit - if (!isObject(options) || Object.keys(options).length === 0) { - return fn.apply(this, arguments); - } - - config.deprecatedOptions.forEach(deprecatedOption => { - if (options.hasOwnProperty(deprecatedOption) && !optionsWarned.has(deprecatedOption)) { - optionsWarned.add(deprecatedOption); - const msg = msgHandler(config.name, deprecatedOption); - emitDeprecationWarning(msg); - if (this && this.getLogger) { - const logger = this.getLogger(); - if (logger) { - logger.warn(msg); - } - } - } - }); - - return fn.apply(this, arguments); - } - - // These lines copied from https://github.com/nodejs/node/blob/25e5ae41688676a5fd29b2e2e7602168eee4ceb5/lib/internal/util.js#L73-L80 - // The wrapper will keep the same prototype as fn to maintain prototype chain - Object.setPrototypeOf(deprecated, fn); - if (fn.prototype) { - // Setting this (rather than using Object.setPrototype, as above) ensures - // that calling the unwrapped constructor gives an instanceof the wrapped - // constructor. - deprecated.prototype = fn.prototype; - } - - return deprecated; -} - -const SUPPORTS = {}; -// Test asyncIterator support -try { - require('./async/async_iterator'); - SUPPORTS.ASYNC_ITERATOR = true; -} catch (e) { - SUPPORTS.ASYNC_ITERATOR = false; -} - -class MongoDBNamespace { - constructor(db, collection) { - this.db = db; - this.collection = collection; - } - - toString() { - return this.collection ? `${this.db}.${this.collection}` : this.db; - } - - withCollection(collection) { - return new MongoDBNamespace(this.db, collection); - } - - static fromString(namespace) { - if (!namespace) { - throw new Error(`Cannot parse namespace from "${namespace}"`); - } - - const index = namespace.indexOf('.'); - return new MongoDBNamespace(namespace.substring(0, index), namespace.substring(index + 1)); - } -} - -module.exports = { - filterOptions, - mergeOptions, - translateOptions, - shallowClone, - getSingleProperty, - checkCollectionName, - toError, - formattedOrderClause, - parseIndexOptions, - normalizeHintField, - handleCallback, - decorateCommand, - isObject, - debugOptions, - MAX_JS_INT: Number.MAX_SAFE_INTEGER + 1, - mergeOptionsAndWriteConcern, - translateReadPreference, - executeLegacyOperation, - applyRetryableWrites, - applyWriteConcern, - isPromiseLike, - decorateWithCollation, - decorateWithReadConcern, - deprecateOptions, - SUPPORTS, - MongoDBNamespace, - resolveReadPreference -}; diff --git a/scripts/2.5/node_modules/mongodb/lib/write_concern.js b/scripts/2.5/node_modules/mongodb/lib/write_concern.js deleted file mode 100644 index 79b0f092..00000000 --- a/scripts/2.5/node_modules/mongodb/lib/write_concern.js +++ /dev/null @@ -1,66 +0,0 @@ -'use strict'; - -/** - * The **WriteConcern** class is a class that represents a MongoDB WriteConcern. - * @class - * @property {(number|string)} w The write concern - * @property {number} wtimeout The write concern timeout - * @property {boolean} j The journal write concern - * @property {boolean} fsync The file sync write concern - * @see https://docs.mongodb.com/manual/reference/write-concern/index.html - */ -class WriteConcern { - /** - * Constructs a WriteConcern from the write concern properties. - * @param {(number|string)} [w] The write concern - * @param {number} [wtimeout] The write concern timeout - * @param {boolean} [j] The journal write concern - * @param {boolean} [fsync] The file sync write concern - */ - constructor(w, wtimeout, j, fsync) { - if (w != null) { - this.w = w; - } - if (wtimeout != null) { - this.wtimeout = wtimeout; - } - if (j != null) { - this.j = j; - } - if (fsync != null) { - this.fsync = fsync; - } - } - - /** - * Construct a WriteConcern given an options object. - * - * @param {object} options The options object from which to extract the write concern. - * @return {WriteConcern} - */ - static fromOptions(options) { - if ( - options == null || - (options.writeConcern == null && - options.w == null && - options.wtimeout == null && - options.j == null && - options.fsync == null) - ) { - return; - } - - if (options.writeConcern) { - return new WriteConcern( - options.writeConcern.w, - options.writeConcern.wtimeout, - options.writeConcern.j, - options.writeConcern.fsync - ); - } - - return new WriteConcern(options.w, options.wtimeout, options.j, options.fsync); - } -} - -module.exports = WriteConcern; diff --git a/scripts/2.5/node_modules/mongodb/package.json b/scripts/2.5/node_modules/mongodb/package.json deleted file mode 100644 index ad87330b..00000000 --- a/scripts/2.5/node_modules/mongodb/package.json +++ /dev/null @@ -1,104 +0,0 @@ -{ - "_from": "mongodb", - "_id": "mongodb@3.3.3", - "_inBundle": false, - "_integrity": "sha512-MdRnoOjstmnrKJsK8PY0PjP6fyF/SBS4R8coxmhsfEU7tQ46/J6j+aSHF2n4c2/H8B+Hc/Klbfp8vggZfI0mmA==", - "_location": "/mongodb", - "_phantomChildren": {}, - "_requested": { - "type": "tag", - "registry": true, - "raw": "mongodb", - "name": "mongodb", - "escapedName": "mongodb", - "rawSpec": "", - "saveSpec": null, - "fetchSpec": "latest" - }, - "_requiredBy": [ - "#USER", - "/" - ], - "_resolved": "https://registry.npmjs.org/mongodb/-/mongodb-3.3.3.tgz", - "_shasum": "509cad2225a1c56c65a331ed73a0d5d4ed5cbe67", - "_spec": "mongodb", - "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/2.5", - "bugs": { - "url": "https://github.com/mongodb/node-mongodb-native/issues" - }, - "bundleDependencies": false, - "dependencies": { - "bson": "^1.1.1", - "require_optional": "^1.0.1", - "safe-buffer": "^5.1.2", - "saslprep": "^1.0.0" - }, - "deprecated": false, - "description": "The official MongoDB driver for Node.js", - "devDependencies": { - "bluebird": "3.5.0", - "chai": "^4.1.1", - "chai-subset": "^1.6.0", - "chalk": "^2.4.2", - "co": "4.6.0", - "coveralls": "^2.11.6", - "eslint": "^4.5.0", - "eslint-plugin-prettier": "^2.2.0", - "istanbul": "^0.4.5", - "jsdoc": "3.5.5", - "lodash.camelcase": "^4.3.0", - "mocha": "5.2.0", - "mocha-sinon": "^2.1.0", - "mongodb-extjson": "^2.1.1", - "mongodb-mock-server": "^1.0.1", - "prettier": "~1.12.0", - "semver": "^5.5.0", - "sinon": "^4.3.0", - "sinon-chai": "^3.2.0", - "snappy": "^6.1.2", - "standard-version": "^4.4.0", - "worker-farm": "^1.5.0", - "wtfnode": "^0.8.0" - }, - "engines": { - "node": ">=4" - }, - "files": [ - "index.js", - "lib" - ], - "homepage": "https://github.com/mongodb/node-mongodb-native", - "keywords": [ - "mongodb", - "driver", - "official" - ], - "license": "Apache-2.0", - "main": "index.js", - "name": "mongodb", - "optionalDependencies": { - "saslprep": "^1.0.0" - }, - "peerOptionalDependencies": { - "kerberos": "^1.1.0", - "mongodb-client-encryption": "^1.0.0", - "mongodb-extjson": "^2.1.2", - "snappy": "^6.1.1", - "bson-ext": "^2.0.0" - }, - "repository": { - "type": "git", - "url": "git+ssh://git@github.com/mongodb/node-mongodb-native.git" - }, - "scripts": { - "atlas": "node ./test/atlas_connectivity_tests.js", - "bench": "node test/driverBench/", - "coverage": "istanbul cover mongodb-test-runner -- -t 60000 test/core test/unit test/functional", - "format": "prettier --print-width 100 --tab-width 2 --single-quote --write 'test/**/*.js' 'lib/**/*.js'", - "generate-evergreen": "node .evergreen/generate_evergreen_tasks.js", - "lint": "eslint lib test", - "release": "standard-version -i HISTORY.md", - "test": "npm run lint && mocha --recursive test/functional test/unit test/core" - }, - "version": "3.3.3" -} diff --git a/scripts/2.5/node_modules/object-inspect/.nycrc b/scripts/2.5/node_modules/object-inspect/.nycrc deleted file mode 100644 index e7064202..00000000 --- a/scripts/2.5/node_modules/object-inspect/.nycrc +++ /dev/null @@ -1,17 +0,0 @@ -{ - "all": true, - "check-coverage": true, - "instrumentation": false, - "sourceMap": false, - "reporter": "html", - "lines": 94.94, - "statements": 94.25, - "functions": 96, - "branches": 91.02, - "exclude": [ - "coverage", - "example", - "test", - "test-core-js.js" - ] -} diff --git a/scripts/2.5/node_modules/object-inspect/.travis.yml b/scripts/2.5/node_modules/object-inspect/.travis.yml deleted file mode 100644 index f17c43ba..00000000 --- a/scripts/2.5/node_modules/object-inspect/.travis.yml +++ /dev/null @@ -1,216 +0,0 @@ -language: node_js -os: - - linux -node_js: - - "10.0" - - "9.11" - - "8.11" - - "7.10" - - "6.14" - - "5.12" - - "4.9" - - "iojs-v3.3" - - "iojs-v2.5" - - "iojs-v1.8" - - "0.12" - - "0.10" - - "0.8" - - "0.6" -before_install: - - 'case "${TRAVIS_NODE_VERSION}" in 0.*) export NPM_CONFIG_STRICT_SSL=false ;; esac' - - 'nvm install-latest-npm' -install: - - 'if [ "${TRAVIS_NODE_VERSION}" = "0.6" ] || [ "${TRAVIS_NODE_VERSION}" = "0.9" ]; then nvm install --latest-npm 0.8 && npm install && nvm use "${TRAVIS_NODE_VERSION}"; else npm install; fi;' -script: - - 'if [ -n "${PRETEST-}" ]; then npm run pretest ; fi' - - 'if [ -n "${POSTTEST-}" ]; then npm run posttest ; fi' - - 'if [ -n "${COVERAGE-}" ]; then npm run coverage ; fi' - - 'if [ -n "${TEST-}" ]; then npm run tests-only ; fi' - - 'if [ -n "${BIGINT-}" ]; then npm run test:bigint ; fi' -sudo: false -env: - - TEST=true -matrix: - fast_finish: true - include: - - node_js: "10.0" - env: BIGINT=true - - node_js: "node" - env: COVERAGE=true - - node_js: "9.10" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.10" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.13" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.12" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.11" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.10" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.11" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.10" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v3.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v3.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v3.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "0.11" - env: TEST=true ALLOW_FAILURE=true - - node_js: "0.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "0.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "0.4" - env: TEST=true ALLOW_FAILURE=true - allow_failures: - - os: osx - - env: TEST=true ALLOW_FAILURE=true diff --git a/scripts/2.5/node_modules/object-inspect/LICENSE b/scripts/2.5/node_modules/object-inspect/LICENSE deleted file mode 100644 index ee27ba4b..00000000 --- a/scripts/2.5/node_modules/object-inspect/LICENSE +++ /dev/null @@ -1,18 +0,0 @@ -This software is released under the MIT license: - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software is furnished to do so, -subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS -FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR -COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/scripts/2.5/node_modules/object-inspect/example/all.js b/scripts/2.5/node_modules/object-inspect/example/all.js deleted file mode 100644 index a2c4d606..00000000 --- a/scripts/2.5/node_modules/object-inspect/example/all.js +++ /dev/null @@ -1,19 +0,0 @@ -var inspect = require('../'); -var Buffer = require('safer-buffer').Buffer; - -var holes = [ 'a', 'b' ]; -holes[4] = 'e', holes[6] = 'g'; -var obj = { - a: 1, - b: [ 3, 4, undefined, null ], - c: undefined, - d: null, - e: { - regex: /^x/i, - buf: Buffer.from('abc'), - holes: holes - }, - now: new Date -}; -obj.self = obj; -console.log(inspect(obj)); diff --git a/scripts/2.5/node_modules/object-inspect/example/circular.js b/scripts/2.5/node_modules/object-inspect/example/circular.js deleted file mode 100644 index 1006d0c0..00000000 --- a/scripts/2.5/node_modules/object-inspect/example/circular.js +++ /dev/null @@ -1,4 +0,0 @@ -var inspect = require('../'); -var obj = { a: 1, b: [3,4] }; -obj.c = obj; -console.log(inspect(obj)); diff --git a/scripts/2.5/node_modules/object-inspect/example/fn.js b/scripts/2.5/node_modules/object-inspect/example/fn.js deleted file mode 100644 index 4c00ba6d..00000000 --- a/scripts/2.5/node_modules/object-inspect/example/fn.js +++ /dev/null @@ -1,3 +0,0 @@ -var inspect = require('../'); -var obj = [ 1, 2, function f (n) { return n + 5 }, 4 ]; -console.log(inspect(obj)); diff --git a/scripts/2.5/node_modules/object-inspect/example/inspect.js b/scripts/2.5/node_modules/object-inspect/example/inspect.js deleted file mode 100644 index b5ad4d19..00000000 --- a/scripts/2.5/node_modules/object-inspect/example/inspect.js +++ /dev/null @@ -1,7 +0,0 @@ -var inspect = require('../'); - -var d = document.createElement('div'); -d.setAttribute('id', 'beep'); -d.innerHTML = 'woooiiiii'; - -console.log(inspect([ d, { a: 3, b : 4, c: [5,6,[7,[8,[9]]]] } ])); diff --git a/scripts/2.5/node_modules/object-inspect/index.js b/scripts/2.5/node_modules/object-inspect/index.js deleted file mode 100644 index 62069e3a..00000000 --- a/scripts/2.5/node_modules/object-inspect/index.js +++ /dev/null @@ -1,257 +0,0 @@ -var hasMap = typeof Map === 'function' && Map.prototype; -var mapSizeDescriptor = Object.getOwnPropertyDescriptor && hasMap ? Object.getOwnPropertyDescriptor(Map.prototype, 'size') : null; -var mapSize = hasMap && mapSizeDescriptor && typeof mapSizeDescriptor.get === 'function' ? mapSizeDescriptor.get : null; -var mapForEach = hasMap && Map.prototype.forEach; -var hasSet = typeof Set === 'function' && Set.prototype; -var setSizeDescriptor = Object.getOwnPropertyDescriptor && hasSet ? Object.getOwnPropertyDescriptor(Set.prototype, 'size') : null; -var setSize = hasSet && setSizeDescriptor && typeof setSizeDescriptor.get === 'function' ? setSizeDescriptor.get : null; -var setForEach = hasSet && Set.prototype.forEach; -var booleanValueOf = Boolean.prototype.valueOf; -var objectToString = Object.prototype.toString; -var bigIntValueOf = typeof BigInt === 'function' ? BigInt.prototype.valueOf : null; - -var inspectCustom = require('./util.inspect').custom; -var inspectSymbol = (inspectCustom && isSymbol(inspectCustom)) ? inspectCustom : null; - -module.exports = function inspect_ (obj, opts, depth, seen) { - if (!opts) opts = {}; - - if (has(opts, 'quoteStyle') && (opts.quoteStyle !== 'single' && opts.quoteStyle !== 'double')) { - throw new TypeError('option "quoteStyle" must be "single" or "double"'); - } - - if (typeof obj === 'undefined') { - return 'undefined'; - } - if (obj === null) { - return 'null'; - } - if (typeof obj === 'boolean') { - return obj ? 'true' : 'false'; - } - - if (typeof obj === 'string') { - return inspectString(obj, opts); - } - if (typeof obj === 'number') { - if (obj === 0) { - return Infinity / obj > 0 ? '0' : '-0'; - } - return String(obj); - } - if (typeof obj === 'bigint') { - return String(obj) + 'n'; - } - - var maxDepth = typeof opts.depth === 'undefined' ? 5 : opts.depth; - if (typeof depth === 'undefined') depth = 0; - if (depth >= maxDepth && maxDepth > 0 && typeof obj === 'object') { - return '[Object]'; - } - - if (typeof seen === 'undefined') seen = []; - else if (indexOf(seen, obj) >= 0) { - return '[Circular]'; - } - - function inspect (value, from) { - if (from) { - seen = seen.slice(); - seen.push(from); - } - return inspect_(value, opts, depth + 1, seen); - } - - if (typeof obj === 'function') { - var name = nameOf(obj); - return '[Function' + (name ? ': ' + name : '') + ']'; - } - if (isSymbol(obj)) { - var symString = Symbol.prototype.toString.call(obj); - return typeof obj === 'object' ? markBoxed(symString) : symString; - } - if (isElement(obj)) { - var s = '<' + String(obj.nodeName).toLowerCase(); - var attrs = obj.attributes || []; - for (var i = 0; i < attrs.length; i++) { - s += ' ' + attrs[i].name + '=' + wrapQuotes(quote(attrs[i].value), 'double', opts); - } - s += '>'; - if (obj.childNodes && obj.childNodes.length) s += '...'; - s += ''; - return s; - } - if (isArray(obj)) { - if (obj.length === 0) return '[]'; - return '[ ' + arrObjKeys(obj, inspect).join(', ') + ' ]'; - } - if (isError(obj)) { - var parts = arrObjKeys(obj, inspect); - if (parts.length === 0) return '[' + String(obj) + ']'; - return '{ [' + String(obj) + '] ' + parts.join(', ') + ' }'; - } - if (typeof obj === 'object') { - if (inspectSymbol && typeof obj[inspectSymbol] === 'function') { - return obj[inspectSymbol](); - } else if (typeof obj.inspect === 'function') { - return obj.inspect(); - } - } - if (isMap(obj)) { - var parts = []; - mapForEach.call(obj, function (value, key) { - parts.push(inspect(key, obj) + ' => ' + inspect(value, obj)); - }); - return collectionOf('Map', mapSize.call(obj), parts); - } - if (isSet(obj)) { - var parts = []; - setForEach.call(obj, function (value ) { - parts.push(inspect(value, obj)); - }); - return collectionOf('Set', setSize.call(obj), parts); - } - if (isNumber(obj)) { - return markBoxed(inspect(Number(obj))); - } - if (isBigInt(obj)) { - return markBoxed(inspect(bigIntValueOf.call(obj))); - } - if (isBoolean(obj)) { - return markBoxed(booleanValueOf.call(obj)); - } - if (isString(obj)) { - return markBoxed(inspect(String(obj))); - } - if (!isDate(obj) && !isRegExp(obj)) { - var xs = arrObjKeys(obj, inspect); - if (xs.length === 0) return '{}'; - return '{ ' + xs.join(', ') + ' }'; - } - return String(obj); -}; - -function wrapQuotes (s, defaultStyle, opts) { - var quoteChar = (opts.quoteStyle || defaultStyle) === 'double' ? '"' : "'"; - return quoteChar + s + quoteChar; -} - -function quote (s) { - return String(s).replace(/"/g, '"'); -} - -function isArray (obj) { return toStr(obj) === '[object Array]'; } -function isDate (obj) { return toStr(obj) === '[object Date]'; } -function isRegExp (obj) { return toStr(obj) === '[object RegExp]'; } -function isError (obj) { return toStr(obj) === '[object Error]'; } -function isSymbol (obj) { return toStr(obj) === '[object Symbol]'; } -function isString (obj) { return toStr(obj) === '[object String]'; } -function isNumber (obj) { return toStr(obj) === '[object Number]'; } -function isBigInt (obj) { return toStr(obj) === '[object BigInt]'; } -function isBoolean (obj) { return toStr(obj) === '[object Boolean]'; } - -var hasOwn = Object.prototype.hasOwnProperty || function (key) { return key in this; }; -function has (obj, key) { - return hasOwn.call(obj, key); -} - -function toStr (obj) { - return objectToString.call(obj); -} - -function nameOf (f) { - if (f.name) return f.name; - var m = String(f).match(/^function\s*([\w$]+)/); - if (m) return m[1]; -} - -function indexOf (xs, x) { - if (xs.indexOf) return xs.indexOf(x); - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; - } - return -1; -} - -function isMap (x) { - if (!mapSize) { - return false; - } - try { - mapSize.call(x); - try { - setSize.call(x); - } catch (s) { - return true; - } - return x instanceof Map; // core-js workaround, pre-v2.5.0 - } catch (e) {} - return false; -} - -function isSet (x) { - if (!setSize) { - return false; - } - try { - setSize.call(x); - try { - mapSize.call(x); - } catch (m) { - return true; - } - return x instanceof Set; // core-js workaround, pre-v2.5.0 - } catch (e) {} - return false; -} - -function isElement (x) { - if (!x || typeof x !== 'object') return false; - if (typeof HTMLElement !== 'undefined' && x instanceof HTMLElement) { - return true; - } - return typeof x.nodeName === 'string' - && typeof x.getAttribute === 'function' - ; -} - -function inspectString (str, opts) { - var s = str.replace(/(['\\])/g, '\\$1').replace(/[\x00-\x1f]/g, lowbyte); - return wrapQuotes(s, 'single', opts); -} - -function lowbyte (c) { - var n = c.charCodeAt(0); - var x = { 8: 'b', 9: 't', 10: 'n', 12: 'f', 13: 'r' }[n]; - if (x) return '\\' + x; - return '\\x' + (n < 0x10 ? '0' : '') + n.toString(16); -} - -function markBoxed (str) { - return 'Object(' + str + ')'; -} - -function collectionOf (type, size, entries) { - return type + ' (' + size + ') {' + entries.join(', ') + '}'; -} - -function arrObjKeys (obj, inspect) { - var isArr = isArray(obj); - var xs = []; - if (isArr) { - xs.length = obj.length; - for (var i = 0; i < obj.length; i++) { - xs[i] = has(obj, i) ? inspect(obj[i], obj) : ''; - } - } - for (var key in obj) { - if (!has(obj, key)) continue; - if (isArr && String(Number(key)) === key && key < obj.length) continue; - if (/[^\w$]/.test(key)) { - xs.push(inspect(key, obj) + ': ' + inspect(obj[key], obj)); - } else { - xs.push(key + ': ' + inspect(obj[key], obj)); - } - } - return xs; -} diff --git a/scripts/2.5/node_modules/object-inspect/package.json b/scripts/2.5/node_modules/object-inspect/package.json deleted file mode 100644 index fe4e997e..00000000 --- a/scripts/2.5/node_modules/object-inspect/package.json +++ /dev/null @@ -1,84 +0,0 @@ -{ - "_from": "object-inspect@^1.6.0", - "_id": "object-inspect@1.6.0", - "_inBundle": false, - "_integrity": "sha512-GJzfBZ6DgDAmnuaM3104jR4s1Myxr3Y3zfIyN4z3UdqN69oSRacNK8UhnobDdC+7J2AHCjGwxQubNJfE70SXXQ==", - "_location": "/object-inspect", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "object-inspect@^1.6.0", - "name": "object-inspect", - "escapedName": "object-inspect", - "rawSpec": "^1.6.0", - "saveSpec": null, - "fetchSpec": "^1.6.0" - }, - "_requiredBy": [ - "/es-abstract" - ], - "_resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.6.0.tgz", - "_shasum": "c70b6cbf72f274aab4c34c0c82f5167bf82cf15b", - "_spec": "object-inspect@^1.6.0", - "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/2.5/node_modules/es-abstract", - "author": { - "name": "James Halliday", - "email": "mail@substack.net", - "url": "http://substack.net" - }, - "browser": { - "./util.inspect.js": false - }, - "bugs": { - "url": "https://github.com/substack/object-inspect/issues" - }, - "bundleDependencies": false, - "deprecated": false, - "description": "string representations of objects in node and the browser", - "devDependencies": { - "core-js": "^2.5.5", - "nyc": "^10.3.2", - "tape": "^4.9.0" - }, - "homepage": "https://github.com/substack/object-inspect", - "keywords": [ - "inspect", - "util.inspect", - "object", - "stringify", - "pretty" - ], - "license": "MIT", - "main": "index.js", - "name": "object-inspect", - "repository": { - "type": "git", - "url": "git://github.com/substack/object-inspect.git" - }, - "scripts": { - "coverage": "nyc npm run tests-only", - "posttest": "npm run test:bigint", - "pretests-only": "node test-core-js", - "test": "npm run tests-only", - "test:bigint": "node --harmony-bigint test/bigint", - "tests-only": "tape test/*.js" - }, - "testling": { - "files": [ - "test/*.js", - "test/browser/*.js" - ], - "browsers": [ - "ie/6..latest", - "chrome/latest", - "firefox/latest", - "safari/latest", - "opera/latest", - "iphone/latest", - "ipad/latest", - "android/latest" - ] - }, - "version": "1.6.0" -} diff --git a/scripts/2.5/node_modules/object-inspect/readme.markdown b/scripts/2.5/node_modules/object-inspect/readme.markdown deleted file mode 100644 index 744eeb59..00000000 --- a/scripts/2.5/node_modules/object-inspect/readme.markdown +++ /dev/null @@ -1,61 +0,0 @@ -# object-inspect - -string representations of objects in node and the browser - -[![testling badge](https://ci.testling.com/substack/object-inspect.png)](https://ci.testling.com/substack/object-inspect) - -[![build status](https://secure.travis-ci.org/substack/object-inspect.png)](http://travis-ci.org/substack/object-inspect) - -# example - -## circular - -``` js -var inspect = require('object-inspect'); -var obj = { a: 1, b: [3,4] }; -obj.c = obj; -console.log(inspect(obj)); -``` - -## dom element - -``` js -var inspect = require('object-inspect'); - -var d = document.createElement('div'); -d.setAttribute('id', 'beep'); -d.innerHTML = 'woooiiiii'; - -console.log(inspect([ d, { a: 3, b : 4, c: [5,6,[7,[8,[9]]]] } ])); -``` - -output: - -``` -[
...
, { a: 3, b: 4, c: [ 5, 6, [ 7, [ 8, [ ... ] ] ] ] } ] -``` - -# methods - -``` js -var inspect = require('object-inspect') -``` - -## var s = inspect(obj, opts={}) - -Return a string `s` with the string representation of `obj` up to a depth of `opts.depth`. - -Additional options: - - `quoteStyle`: must be "single" or "double", if present - -# install - -With [npm](https://npmjs.org) do: - -``` -npm install object-inspect -``` - -# license - -MIT diff --git a/scripts/2.5/node_modules/object-inspect/test-core-js.js b/scripts/2.5/node_modules/object-inspect/test-core-js.js deleted file mode 100644 index 12c4e2ae..00000000 --- a/scripts/2.5/node_modules/object-inspect/test-core-js.js +++ /dev/null @@ -1,16 +0,0 @@ -'use strict'; - -require('core-js'); - -var inspect = require('./'); -var test = require('tape'); - -test('Maps', function (t) { - t.equal(inspect(new Map([[1, 2]])), 'Map (1) {1 => 2}'); - t.end(); -}); - -test('Sets', function (t) { - t.equal(inspect(new Set([[1, 2]])), 'Set (1) {[ 1, 2 ]}'); - t.end(); -}); diff --git a/scripts/2.5/node_modules/object-inspect/test/bigint.js b/scripts/2.5/node_modules/object-inspect/test/bigint.js deleted file mode 100644 index c9d918bf..00000000 --- a/scripts/2.5/node_modules/object-inspect/test/bigint.js +++ /dev/null @@ -1,30 +0,0 @@ -var inspect = require('../'); -var test = require('tape'); - -test('bigint', { skip: typeof BigInt === 'undefined' }, function (t) { - t.test('primitives', function (st) { - st.plan(3); - - st.equal(inspect(BigInt(-256)), '-256n'); - st.equal(inspect(BigInt(0)), '0n'); - st.equal(inspect(BigInt(256)), '256n'); - }); - - t.test('objects', function (st) { - st.plan(3); - - st.equal(inspect(Object(BigInt(-256))), 'Object(-256n)'); - st.equal(inspect(Object(BigInt(0))), 'Object(0n)'); - st.equal(inspect(Object(BigInt(256))), 'Object(256n)'); - }); - - t.test('syntactic primitives', function (st) { - st.plan(3); - - st.equal(inspect(Function('return -256n')()), '-256n'); - st.equal(inspect(Function('return 0n')()), '0n'); - st.equal(inspect(Function('return 256n')()), '256n'); - }); - - t.end(); -}); diff --git a/scripts/2.5/node_modules/object-inspect/test/browser/dom.js b/scripts/2.5/node_modules/object-inspect/test/browser/dom.js deleted file mode 100644 index 18a3d709..00000000 --- a/scripts/2.5/node_modules/object-inspect/test/browser/dom.js +++ /dev/null @@ -1,15 +0,0 @@ -var inspect = require('../../'); -var test = require('tape'); - -test('dom element', function (t) { - t.plan(1); - - var d = document.createElement('div'); - d.setAttribute('id', 'beep'); - d.innerHTML = 'woooiiiii'; - - t.equal( - inspect([ d, { a: 3, b : 4, c: [5,6,[7,[8,[9]]]] } ]), - '[
...
, { a: 3, b: 4, c: [ 5, 6, [ 7, [ 8, [Object] ] ] ] } ]' - ); -}); diff --git a/scripts/2.5/node_modules/object-inspect/test/circular.js b/scripts/2.5/node_modules/object-inspect/test/circular.js deleted file mode 100644 index 28598a7f..00000000 --- a/scripts/2.5/node_modules/object-inspect/test/circular.js +++ /dev/null @@ -1,9 +0,0 @@ -var inspect = require('../'); -var test = require('tape'); - -test('circular', function (t) { - t.plan(1); - var obj = { a: 1, b: [3,4] }; - obj.c = obj; - t.equal(inspect(obj), '{ a: 1, b: [ 3, 4 ], c: [Circular] }'); -}); diff --git a/scripts/2.5/node_modules/object-inspect/test/deep.js b/scripts/2.5/node_modules/object-inspect/test/deep.js deleted file mode 100644 index a8dbb58f..00000000 --- a/scripts/2.5/node_modules/object-inspect/test/deep.js +++ /dev/null @@ -1,9 +0,0 @@ -var inspect = require('../'); -var test = require('tape'); - -test('deep', function (t) { - t.plan(2); - var obj = [ [ [ [ [ [ 500 ] ] ] ] ] ]; - t.equal(inspect(obj), '[ [ [ [ [ [Object] ] ] ] ] ]'); - t.equal(inspect(obj, { depth: 2 }), '[ [ [Object] ] ]'); -}); diff --git a/scripts/2.5/node_modules/object-inspect/test/element.js b/scripts/2.5/node_modules/object-inspect/test/element.js deleted file mode 100644 index a36f4656..00000000 --- a/scripts/2.5/node_modules/object-inspect/test/element.js +++ /dev/null @@ -1,53 +0,0 @@ -var inspect = require('../'); -var test = require('tape'); - -test('element', function (t) { - t.plan(3); - var elem = { - nodeName: 'div', - attributes: [ { name: 'class', value: 'row' } ], - getAttribute: function (key) {}, - childNodes: [] - }; - var obj = [ 1, elem, 3 ]; - t.deepEqual(inspect(obj), '[ 1,
, 3 ]'); - t.deepEqual(inspect(obj, { quoteStyle: 'single' }), "[ 1,
, 3 ]"); - t.deepEqual(inspect(obj, { quoteStyle: 'double' }), '[ 1,
, 3 ]'); -}); - -test('element no attr', function (t) { - t.plan(1); - var elem = { - nodeName: 'div', - getAttribute: function (key) {}, - childNodes: [] - }; - var obj = [ 1, elem, 3 ]; - t.deepEqual(inspect(obj), '[ 1,
, 3 ]'); -}); - -test('element with contents', function (t) { - t.plan(1); - var elem = { - nodeName: 'div', - getAttribute: function (key) {}, - childNodes: [ { nodeName: 'b' } ] - }; - var obj = [ 1, elem, 3 ]; - t.deepEqual(inspect(obj), '[ 1,
...
, 3 ]'); -}); - -test('element instance', function (t) { - t.plan(1); - var h = global.HTMLElement; - global.HTMLElement = function (name, attr) { - this.nodeName = name; - this.attributes = attr; - }; - global.HTMLElement.prototype.getAttribute = function () {}; - - var elem = new(global.HTMLElement)('div', []); - var obj = [ 1, elem, 3 ]; - t.deepEqual(inspect(obj), '[ 1,
, 3 ]'); - global.HTMLElement = h; -}); diff --git a/scripts/2.5/node_modules/object-inspect/test/err.js b/scripts/2.5/node_modules/object-inspect/test/err.js deleted file mode 100644 index 0f313438..00000000 --- a/scripts/2.5/node_modules/object-inspect/test/err.js +++ /dev/null @@ -1,29 +0,0 @@ -var inspect = require('../'); -var test = require('tape'); - -test('type error', function (t) { - t.plan(1); - var aerr = new TypeError; - aerr.foo = 555; - aerr.bar = [1,2,3]; - - var berr = new TypeError('tuv'); - berr.baz = 555; - - var cerr = new SyntaxError; - cerr.message = 'whoa'; - cerr['a-b'] = 5; - - var obj = [ - new TypeError, - new TypeError('xxx'), - aerr, berr, cerr - ]; - t.equal(inspect(obj), '[ ' + [ - '[TypeError]', - '[TypeError: xxx]', - '{ [TypeError] foo: 555, bar: [ 1, 2, 3 ] }', - '{ [TypeError: tuv] baz: 555 }', - '{ [SyntaxError: whoa] message: \'whoa\', \'a-b\': 5 }' - ].join(', ') + ' ]'); -}); diff --git a/scripts/2.5/node_modules/object-inspect/test/fn.js b/scripts/2.5/node_modules/object-inspect/test/fn.js deleted file mode 100644 index c7d5712b..00000000 --- a/scripts/2.5/node_modules/object-inspect/test/fn.js +++ /dev/null @@ -1,28 +0,0 @@ -var inspect = require('../'); -var test = require('tape'); - -test('function', function (t) { - t.plan(1); - var obj = [ 1, 2, function f (n) {}, 4 ]; - t.equal(inspect(obj), '[ 1, 2, [Function: f], 4 ]'); -}); - -test('function name', function (t) { - t.plan(1); - var f = (function () { - return function () {}; - }()); - f.toString = function () { return 'function xxx () {}' }; - var obj = [ 1, 2, f, 4 ]; - t.equal(inspect(obj), '[ 1, 2, [Function: xxx], 4 ]'); -}); - -test('anon function', function (t) { - var f = (function () { - return function () {}; - }()); - var obj = [ 1, 2, f, 4 ]; - t.equal(inspect(obj), '[ 1, 2, [Function], 4 ]'); - - t.end(); -}); diff --git a/scripts/2.5/node_modules/object-inspect/test/has.js b/scripts/2.5/node_modules/object-inspect/test/has.js deleted file mode 100644 index e1970b31..00000000 --- a/scripts/2.5/node_modules/object-inspect/test/has.js +++ /dev/null @@ -1,31 +0,0 @@ -var inspect = require('../'); -var test = require('tape'); - -var withoutProperty = function (object, property, fn) { - var original; - if (Object.getOwnPropertyDescriptor) { - original = Object.getOwnPropertyDescriptor(object, property); - } else { - original = object[property]; - } - delete object[property]; - try { - fn(); - } finally { - if (Object.getOwnPropertyDescriptor) { - Object.defineProperty(object, property, original); - } else { - object[property] = original; - } - } -}; - -test('when Object#hasOwnProperty is deleted', function (t) { - t.plan(1); - var arr = [1, , 3]; - Array.prototype[1] = 2; // this is needed to account for "in" vs "hasOwnProperty" - withoutProperty(Object.prototype, 'hasOwnProperty', function () { - t.equal(inspect(arr), '[ 1, , 3 ]'); - }); - delete Array.prototype[1]; -}); diff --git a/scripts/2.5/node_modules/object-inspect/test/holes.js b/scripts/2.5/node_modules/object-inspect/test/holes.js deleted file mode 100644 index ae54de46..00000000 --- a/scripts/2.5/node_modules/object-inspect/test/holes.js +++ /dev/null @@ -1,15 +0,0 @@ -var test = require('tape'); -var inspect = require('../'); - -var xs = [ 'a', 'b' ]; -xs[5] = 'f'; -xs[7] = 'j'; -xs[8] = 'k'; - -test('holes', function (t) { - t.plan(1); - t.equal( - inspect(xs), - "[ 'a', 'b', , , , 'f', , 'j', 'k' ]" - ); -}); diff --git a/scripts/2.5/node_modules/object-inspect/test/inspect.js b/scripts/2.5/node_modules/object-inspect/test/inspect.js deleted file mode 100644 index 12e231af..00000000 --- a/scripts/2.5/node_modules/object-inspect/test/inspect.js +++ /dev/null @@ -1,8 +0,0 @@ -var inspect = require('../'); -var test = require('tape'); - -test('inspect', function (t) { - t.plan(1); - var obj = [ { inspect: function () { return '!XYZ¡' } }, [] ]; - t.equal(inspect(obj), '[ !XYZ¡, [] ]'); -}); diff --git a/scripts/2.5/node_modules/object-inspect/test/lowbyte.js b/scripts/2.5/node_modules/object-inspect/test/lowbyte.js deleted file mode 100644 index debd59cb..00000000 --- a/scripts/2.5/node_modules/object-inspect/test/lowbyte.js +++ /dev/null @@ -1,12 +0,0 @@ -var test = require('tape'); -var inspect = require('../'); - -var obj = { x: 'a\r\nb', y: '\5! \x1f \022' }; - -test('interpolate low bytes', function (t) { - t.plan(1); - t.equal( - inspect(obj), - "{ x: 'a\\r\\nb', y: '\\x05! \\x1f \\x12' }" - ); -}); diff --git a/scripts/2.5/node_modules/object-inspect/test/number.js b/scripts/2.5/node_modules/object-inspect/test/number.js deleted file mode 100644 index 448304e5..00000000 --- a/scripts/2.5/node_modules/object-inspect/test/number.js +++ /dev/null @@ -1,12 +0,0 @@ -var inspect = require('../'); -var test = require('tape'); - -test('negative zero', function (t) { - t.equal(inspect(0), '0', 'inspect(0) === "0"'); - t.equal(inspect(Object(0)), 'Object(0)', 'inspect(Object(0)) === "Object(0)"'); - - t.equal(inspect(-0), '-0', 'inspect(-0) === "-0"'); - t.equal(inspect(Object(-0)), 'Object(-0)', 'inspect(Object(-0)) === "Object(-0)"'); - - t.end(); -}); diff --git a/scripts/2.5/node_modules/object-inspect/test/quoteStyle.js b/scripts/2.5/node_modules/object-inspect/test/quoteStyle.js deleted file mode 100644 index ae4d734b..00000000 --- a/scripts/2.5/node_modules/object-inspect/test/quoteStyle.js +++ /dev/null @@ -1,17 +0,0 @@ -'use strict'; - -var inspect = require('../'); -var test = require('tape'); - -test('quoteStyle option', function (t) { - t['throws'](function () { inspect(null, { quoteStyle: false }); }, 'false is not a valid value'); - t['throws'](function () { inspect(null, { quoteStyle: true }); }, 'true is not a valid value'); - t['throws'](function () { inspect(null, { quoteStyle: '' }); }, '"" is not a valid value'); - t['throws'](function () { inspect(null, { quoteStyle: {} }); }, '{} is not a valid value'); - t['throws'](function () { inspect(null, { quoteStyle: [] }); }, '[] is not a valid value'); - t['throws'](function () { inspect(null, { quoteStyle: 42 }); }, '42 is not a valid value'); - t['throws'](function () { inspect(null, { quoteStyle: NaN }); }, 'NaN is not a valid value'); - t['throws'](function () { inspect(null, { quoteStyle: function () {} }); }, 'a function is not a valid value'); - - t.end(); -}); diff --git a/scripts/2.5/node_modules/object-inspect/test/undef.js b/scripts/2.5/node_modules/object-inspect/test/undef.js deleted file mode 100644 index 833238f8..00000000 --- a/scripts/2.5/node_modules/object-inspect/test/undef.js +++ /dev/null @@ -1,12 +0,0 @@ -var test = require('tape'); -var inspect = require('../'); - -var obj = { a: 1, b: [ 3, 4, undefined, null ], c: undefined, d: null }; - -test('undef and null', function (t) { - t.plan(1); - t.equal( - inspect(obj), - '{ a: 1, b: [ 3, 4, undefined, null ], c: undefined, d: null }' - ); -}); diff --git a/scripts/2.5/node_modules/object-inspect/test/values.js b/scripts/2.5/node_modules/object-inspect/test/values.js deleted file mode 100644 index 3e1954ba..00000000 --- a/scripts/2.5/node_modules/object-inspect/test/values.js +++ /dev/null @@ -1,136 +0,0 @@ -var inspect = require('../'); -var test = require('tape'); - -test('values', function (t) { - t.plan(1); - var obj = [ {}, [], { 'a-b': 5 } ]; - t.equal(inspect(obj), '[ {}, [], { \'a-b\': 5 } ]'); -}); - -test('arrays with properties', function (t) { - t.plan(1); - var arr = [3]; - arr.foo = 'bar'; - var obj = [1, 2, arr]; - obj.baz = 'quux'; - obj.index = -1; - t.equal(inspect(obj), '[ 1, 2, [ 3, foo: \'bar\' ], baz: \'quux\', index: -1 ]'); -}); - -test('has', function (t) { - t.plan(1); - var has = Object.prototype.hasOwnProperty; - delete Object.prototype.hasOwnProperty; - t.equal(inspect({ a: 1, b: 2 }), '{ a: 1, b: 2 }'); - Object.prototype.hasOwnProperty = has; -}); - -test('indexOf seen', function (t) { - t.plan(1); - var xs = [ 1, 2, 3, {} ]; - xs.push(xs); - - var seen = []; - seen.indexOf = undefined; - - t.equal( - inspect(xs, {}, 0, seen), - '[ 1, 2, 3, {}, [Circular] ]' - ); -}); - -test('seen seen', function (t) { - t.plan(1); - var xs = [ 1, 2, 3 ]; - - var seen = [ xs ]; - seen.indexOf = undefined; - - t.equal( - inspect(xs, {}, 0, seen), - '[Circular]' - ); -}); - -test('seen seen seen', function (t) { - t.plan(1); - var xs = [ 1, 2, 3 ]; - - var seen = [ 5, xs ]; - seen.indexOf = undefined; - - t.equal( - inspect(xs, {}, 0, seen), - '[Circular]' - ); -}); - -test('symbols', { skip: typeof Symbol !== 'function' }, function (t) { - var sym = Symbol('foo'); - t.equal(inspect(sym), 'Symbol(foo)', 'Symbol("foo") should be "Symbol(foo)"'); - t.equal(inspect(Object(sym)), 'Object(Symbol(foo))', 'Object(Symbol("foo")) should be "Object(Symbol(foo))"'); - t.end(); -}); - -test('Map', { skip: typeof Map !== 'function' }, function (t) { - var map = new Map(); - map.set({ a: 1 }, ['b']); - map.set(3, NaN); - var expectedString = 'Map (2) {' + inspect({ a: 1 }) + ' => ' + inspect(['b']) + ', 3 => NaN}'; - t.equal(inspect(map), expectedString, 'new Map([[{ a: 1 }, ["b"]], [3, NaN]]) should show size and contents'); - t.equal(inspect(new Map()), 'Map (0) {}', 'empty Map should show as empty'); - - var nestedMap = new Map(); - nestedMap.set(nestedMap, map); - t.equal(inspect(nestedMap), 'Map (1) {[Circular] => ' + expectedString + '}', 'Map containing a Map should work'); - - t.end(); -}); - -test('Set', { skip: typeof Set !== 'function' }, function (t) { - var set = new Set(); - set.add({ a: 1 }); - set.add(['b']); - var expectedString = 'Set (2) {' + inspect({ a: 1 }) + ', ' + inspect(['b']) + '}'; - t.equal(inspect(set), expectedString, 'new Set([{ a: 1 }, ["b"]]) should show size and contents'); - t.equal(inspect(new Set()), 'Set (0) {}', 'empty Set should show as empty'); - - var nestedSet = new Set(); - nestedSet.add(set); - nestedSet.add(nestedSet); - t.equal(inspect(nestedSet), 'Set (2) {' + expectedString + ', [Circular]}', 'Set containing a Set should work'); - - t.end(); -}); - -test('Strings', function (t) { - var str = 'abc'; - - t.equal(inspect(str), "'" + str + "'", 'primitive string shows as such'); - t.equal(inspect(str, { quoteStyle: 'single' }), "'" + str + "'", 'primitive string shows as such, single quoted'); - t.equal(inspect(str, { quoteStyle: 'double' }), '"' + str + '"', 'primitive string shows as such, double quoted'); - t.equal(inspect(Object(str)), 'Object(' + inspect(str) + ')', 'String object shows as such'); - t.equal(inspect(Object(str), { quoteStyle: 'single' }), 'Object(' + inspect(str, { quoteStyle: 'single' }) + ')', 'String object shows as such, single quoted'); - t.equal(inspect(Object(str), { quoteStyle: 'double' }), 'Object(' + inspect(str, { quoteStyle: 'double' }) + ')', 'String object shows as such, double quoted'); - - t.end(); -}); - -test('Numbers', function (t) { - var num = 42; - - t.equal(inspect(num), String(num), 'primitive number shows as such'); - t.equal(inspect(Object(num)), 'Object(' + inspect(num) + ')', 'Number object shows as such'); - - t.end(); -}); - -test('Booleans', function (t) { - t.equal(inspect(true), String(true), 'primitive true shows as such'); - t.equal(inspect(Object(true)), 'Object(' + inspect(true) + ')', 'Boolean object true shows as such'); - - t.equal(inspect(false), String(false), 'primitive false shows as such'); - t.equal(inspect(Object(false)), 'Object(' + inspect(false) + ')', 'Boolean false object shows as such'); - - t.end(); -}); diff --git a/scripts/2.5/node_modules/object-inspect/util.inspect.js b/scripts/2.5/node_modules/object-inspect/util.inspect.js deleted file mode 100644 index 7784fab5..00000000 --- a/scripts/2.5/node_modules/object-inspect/util.inspect.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require('util').inspect; diff --git a/scripts/2.5/node_modules/object-is/.jscs.json b/scripts/2.5/node_modules/object-is/.jscs.json deleted file mode 100644 index 97ab933d..00000000 --- a/scripts/2.5/node_modules/object-is/.jscs.json +++ /dev/null @@ -1,55 +0,0 @@ -{ - "requireCurlyBraces": ["if", "else", "for", "while", "do", "try", "catch"], - - "requireSpaceAfterKeywords": ["if", "else", "for", "while", "do", "switch", "return", "try", "catch", "function"], - - "disallowSpaceAfterKeywords": [], - - "requireSpacesInAnonymousFunctionExpression": { "beforeOpeningRoundBrace": true, "beforeOpeningCurlyBrace": true }, - "requireSpacesInNamedFunctionExpression": { "beforeOpeningCurlyBrace": true }, - "disallowSpacesInNamedFunctionExpression": { "beforeOpeningRoundBrace": true }, - "requireSpacesInFunctionDeclaration": { "beforeOpeningCurlyBrace": true }, - "disallowSpacesInFunctionDeclaration": { "beforeOpeningRoundBrace": true }, - - "disallowSpacesInsideParentheses": true, - - "disallowSpacesInsideArrayBrackets": true, - - "disallowQuotedKeysInObjects": "allButReserved", - - "disallowSpaceAfterObjectKeys": true, - - "requireCommaBeforeLineBreak": true, - - "disallowSpaceAfterPrefixUnaryOperators": ["++", "--", "+", "-", "~", "!"], - "requireSpaceAfterPrefixUnaryOperators": [], - - "disallowSpaceBeforePostfixUnaryOperators": ["++", "--"], - "requireSpaceBeforePostfixUnaryOperators": [], - - "disallowSpaceBeforeBinaryOperators": [], - "requireSpaceBeforeBinaryOperators": ["+", "-", "/", "*", "=", "==", "===", "!=", "!=="], - - "requireSpaceAfterBinaryOperators": ["+", "-", "/", "*", "=", "==", "===", "!=", "!=="], - "disallowSpaceAfterBinaryOperators": [], - - "disallowImplicitTypeConversion": ["binary", "string"], - - "disallowKeywords": ["with", "eval"], - - "validateLineBreaks": "LF", - - "requireKeywordsOnNewLine": [], - "disallowKeywordsOnNewLine": ["else"], - - "requireLineFeedAtFileEnd": true, - - "disallowTrailingWhitespace": true, - - "excludeFiles": ["node_modules/**", "vendor/**"], - - "disallowMultipleLineStrings": true, - - "additionalRules": [] -} - diff --git a/scripts/2.5/node_modules/object-is/.npmignore b/scripts/2.5/node_modules/object-is/.npmignore deleted file mode 100644 index a72b52eb..00000000 --- a/scripts/2.5/node_modules/object-is/.npmignore +++ /dev/null @@ -1,15 +0,0 @@ -lib-cov -*.seed -*.log -*.csv -*.dat -*.out -*.pid -*.gz - -pids -logs -results - -npm-debug.log -node_modules diff --git a/scripts/2.5/node_modules/object-is/.travis.yml b/scripts/2.5/node_modules/object-is/.travis.yml deleted file mode 100644 index 912080aa..00000000 --- a/scripts/2.5/node_modules/object-is/.travis.yml +++ /dev/null @@ -1,18 +0,0 @@ -language: node_js -node_js: - - "0.11" - - "0.10" - - "0.9" - - "0.8" - - "0.6" - - "0.4" -before_install: - - '[ "${TRAVIS_NODE_VERSION}" == "0.6" ] || npm install -g npm@~1.4.6' -matrix: - fast_finish: true - allow_failures: - - node_js: "0.11" - - node_js: "0.9" - - node_js: "0.6" - - node_js: "0.4" - diff --git a/scripts/2.5/node_modules/object-is/LICENSE b/scripts/2.5/node_modules/object-is/LICENSE deleted file mode 100644 index 47b7b507..00000000 --- a/scripts/2.5/node_modules/object-is/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014 Jordan Harband - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software is furnished to do so, -subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS -FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR -COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/scripts/2.5/node_modules/object-is/README.md b/scripts/2.5/node_modules/object-is/README.md deleted file mode 100644 index 4398954d..00000000 --- a/scripts/2.5/node_modules/object-is/README.md +++ /dev/null @@ -1,54 +0,0 @@ -#object-is [![Version Badge][2]][1] - -[![Build Status][3]][4] [![dependency status][5]][6] [![dev dependency status][7]][8] - -[![npm badge][11]][1] - -[![browser support][9]][10] - -ES6-compliant shim for Object.is - differentiates between -0 and +0, and can compare to NaN. - -Essentially, Object.is returns the same value as === - but true for NaN, and false for -0 and +0. - -## Example - -```js -Object.is = require('object-is'); -var assert = require('assert'); - -assert.ok(Object.is()); -assert.ok(Object.is(undefined)); -assert.ok(Object.is(undefined, undefined)); -assert.ok(Object.is(null, null)); -assert.ok(Object.is(true, true)); -assert.ok(Object.is(false, false)); -assert.ok(Object.is('foo', 'foo')); - -var arr = [1, 2]; -assert.ok(Object.is(arr, arr)); -assert.notOk(Object.is(arr, [1, 2])); - -assert.ok(Object.is(0, 0)); -assert.ok(Object.is(-0, -0)); -assert.notOk(Object.is(0, -0)); - -assert.ok(Object.is(NaN, NaN)); -assert.ok(Object.is(Infinity, Infinity)); -assert.ok(Object.is(-Infinity, -Infinity)); -``` - -## Tests -Simply clone the repo, `npm install`, and run `npm test` - -[1]: https://npmjs.org/package/object-is -[2]: http://vb.teelaun.ch/ljharb/object-is.svg -[3]: https://travis-ci.org/ljharb/object-is.svg -[4]: https://travis-ci.org/ljharb/object-is -[5]: https://david-dm.org/ljharb/object-is.svg -[6]: https://david-dm.org/ljharb/object-is -[7]: https://david-dm.org/ljharb/object-is/dev-status.svg -[8]: https://david-dm.org/ljharb/object-is#info=devDependencies -[9]: https://ci.testling.com/ljharb/object-is.png -[10]: https://ci.testling.com/ljharb/object-is -[11]: https://nodei.co/npm/object-is.png?downloads=true&stars=true - diff --git a/scripts/2.5/node_modules/object-is/index.js b/scripts/2.5/node_modules/object-is/index.js deleted file mode 100644 index 60f1cdc3..00000000 --- a/scripts/2.5/node_modules/object-is/index.js +++ /dev/null @@ -1,19 +0,0 @@ -"use strict"; - -/* https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.is */ - -var NumberIsNaN = function (value) { - return value !== value; -}; - -module.exports = function is(a, b) { - if (a === 0 && b === 0) { - return 1 / a === 1 / b; - } else if (a === b) { - return true; - } else if (NumberIsNaN(a) && NumberIsNaN(b)) { - return true; - } - return false; -}; - diff --git a/scripts/2.5/node_modules/object-is/package.json b/scripts/2.5/node_modules/object-is/package.json deleted file mode 100644 index cc6dbc84..00000000 --- a/scripts/2.5/node_modules/object-is/package.json +++ /dev/null @@ -1,86 +0,0 @@ -{ - "_from": "object-is@^1.0.1", - "_id": "object-is@1.0.1", - "_inBundle": false, - "_integrity": "sha1-CqYOyZiaCz7Xlc9NBvYs8a1lObY=", - "_location": "/object-is", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "object-is@^1.0.1", - "name": "object-is", - "escapedName": "object-is", - "rawSpec": "^1.0.1", - "saveSpec": null, - "fetchSpec": "^1.0.1" - }, - "_requiredBy": [ - "/assert" - ], - "_resolved": "https://registry.npmjs.org/object-is/-/object-is-1.0.1.tgz", - "_shasum": "0aa60ec9989a0b3ed795cf4d06f62cf1ad6539b6", - "_spec": "object-is@^1.0.1", - "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/2.5/node_modules/assert", - "author": { - "name": "Jordan Harband" - }, - "bugs": { - "url": "https://github.com/ljharb/object-is/issues" - }, - "bundleDependencies": false, - "dependencies": {}, - "deprecated": false, - "description": "ES6-compliant shim for Object.is - differentiates between -0 and +0", - "devDependencies": { - "covert": "~1.0.0", - "jscs": "~1.5.9", - "tape": "~2.14.0" - }, - "engines": { - "node": ">= 0.4" - }, - "homepage": "https://github.com/ljharb/object-is", - "keywords": [ - "is", - "Object.is", - "equality", - "sameValueZero", - "ES6", - "shim", - "polyfill" - ], - "license": "MIT", - "main": "index.js", - "name": "object-is", - "repository": { - "type": "git", - "url": "git://github.com/ljharb/object-is.git" - }, - "scripts": { - "coverage": "covert test.js", - "coverage-quiet": "covert test.js --quiet", - "lint": "jscs *.js", - "test": "npm run lint && node test.js && npm run coverage-quiet" - }, - "testling": { - "files": "test.js", - "browsers": [ - "iexplore/6.0..latest", - "firefox/3.0..6.0", - "firefox/15.0..latest", - "firefox/nightly", - "chrome/4.0..10.0", - "chrome/20.0..latest", - "chrome/canary", - "opera/10.0..12.0", - "opera/15.0..latest", - "opera/next", - "safari/4.0..latest", - "ipad/6.0..latest", - "iphone/6.0..latest", - "android-browser/4.2" - ] - }, - "version": "1.0.1" -} diff --git a/scripts/2.5/node_modules/object-is/test.js b/scripts/2.5/node_modules/object-is/test.js deleted file mode 100644 index 2a5e1c02..00000000 --- a/scripts/2.5/node_modules/object-is/test.js +++ /dev/null @@ -1,50 +0,0 @@ -"use strict"; - -var test = require('tape'); -var is = require('./'); - -test('works with primitives', function (t) { - t.ok(is(), 'two absent args are the same'); - t.ok(is(undefined), 'undefined & one absent arg are the same'); - t.ok(is(undefined, undefined), 'undefined is undefined'); - t.ok(is(null, null), 'null is null'); - t.ok(is(true, true), 'true is true'); - t.ok(is(false, false), 'false is false'); - t.notOk(is(true, false), 'true is not false'); - t.end(); -}); - -test('works with NaN', function (t) { - t.ok(is(NaN, NaN), 'NaN is NaN'); - t.end(); -}); - -test('differentiates zeroes', function (t) { - t.ok(is(0, 0), '+0 is +0'); - t.ok(is(-0, -0), '-0 is -0'); - t.notOk(is(0, -0), '+0 is not -0'); - t.end(); -}); - -test('nonzero numbers', function (t) { - t.ok(is(Infinity, Infinity), 'infinity is infinity'); - t.ok(is(-Infinity, -Infinity), 'infinity is infinity'); - t.ok(is(42, 42), '42 is 42'); - t.notOk(is(42, -42), '42 is not -42'); - t.end(); -}); - -test('strings', function (t) { - t.ok(is('', ''), 'empty string is empty string'); - t.ok(is('foo', 'foo'), 'string is string'); - t.notOk(is('foo', 'bar'), 'string is not different string'); - t.end(); -}); - -test('objects', function (t) { - var obj = {}; - t.ok(is(obj, obj), 'object is same object'); - t.notOk(is(obj, {}), 'object is not different object'); - t.end(); -}); - diff --git a/scripts/2.5/node_modules/object-keys/.editorconfig b/scripts/2.5/node_modules/object-keys/.editorconfig deleted file mode 100644 index eaa21416..00000000 --- a/scripts/2.5/node_modules/object-keys/.editorconfig +++ /dev/null @@ -1,13 +0,0 @@ -root = true - -[*] -indent_style = tab; -insert_final_newline = true; -quote_type = auto; -space_after_anonymous_functions = true; -space_after_control_statements = true; -spaces_around_operators = true; -trim_trailing_whitespace = true; -spaces_in_brackets = false; -end_of_line = lf; - diff --git a/scripts/2.5/node_modules/object-keys/.eslintrc b/scripts/2.5/node_modules/object-keys/.eslintrc deleted file mode 100644 index 9a8d5b0e..00000000 --- a/scripts/2.5/node_modules/object-keys/.eslintrc +++ /dev/null @@ -1,17 +0,0 @@ -{ - "root": true, - - "extends": "@ljharb", - - "rules": { - "complexity": [2, 23], - "id-length": [2, { "min": 1, "max": 40 }], - "max-params": [2, 3], - "max-statements": [2, 23], - "max-statements-per-line": [2, { "max": 2 }], - "no-extra-parens": [1], - "no-invalid-this": [1], - "no-restricted-syntax": [2, "BreakStatement", "ContinueStatement", "LabeledStatement", "WithStatement"], - "operator-linebreak": [2, "after"] - } -} diff --git a/scripts/2.5/node_modules/object-keys/.travis.yml b/scripts/2.5/node_modules/object-keys/.travis.yml deleted file mode 100644 index 94a6ce42..00000000 --- a/scripts/2.5/node_modules/object-keys/.travis.yml +++ /dev/null @@ -1,277 +0,0 @@ -language: node_js -os: - - linux -node_js: - - "11.8" - - "10.15" - - "9.11" - - "8.15" - - "7.10" - - "6.16" - - "5.12" - - "4.9" - - "iojs-v3.3" - - "iojs-v2.5" - - "iojs-v1.8" - - "0.12" - - "0.10" - - "0.8" -before_install: - - 'case "${TRAVIS_NODE_VERSION}" in 0.*) export NPM_CONFIG_STRICT_SSL=false ;; esac' - - 'nvm install-latest-npm' -install: - - 'if [ "${TRAVIS_NODE_VERSION}" = "0.6" ] || [ "${TRAVIS_NODE_VERSION}" = "0.9" ]; then nvm install --latest-npm 0.8 && npm install && nvm use "${TRAVIS_NODE_VERSION}"; else npm install; fi;' -script: - - 'if [ -n "${PRETEST-}" ]; then npm run pretest ; fi' - - 'if [ -n "${POSTTEST-}" ]; then npm run posttest ; fi' - - 'if [ -n "${COVERAGE-}" ]; then npm run coverage ; fi' - - 'if [ -n "${TEST-}" ]; then npm run tests-only ; fi' -sudo: false -env: - - TEST=true -matrix: - fast_finish: true - include: - - node_js: "lts/*" - env: PRETEST=true - - node_js: "lts/*" - env: POSTTEST=true - - node_js: "4" - env: COVERAGE=true - - node_js: "11.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "11.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "11.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "11.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "11.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "11.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "11.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "11.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.14" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.13" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.12" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.11" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.10" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.10" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.14" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.13" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.12" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.11" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.10" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.15" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.14" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.13" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.12" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.11" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.10" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.11" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.10" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v3.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v3.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v3.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "0.11" - env: TEST=true ALLOW_FAILURE=true - - node_js: "0.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "0.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "0.4" - env: TEST=true ALLOW_FAILURE=true - allow_failures: - - os: osx - - env: TEST=true ALLOW_FAILURE=true - - env: COVERAGE=true - - env: POSTTEST=true diff --git a/scripts/2.5/node_modules/object-keys/CHANGELOG.md b/scripts/2.5/node_modules/object-keys/CHANGELOG.md deleted file mode 100644 index b7d92df2..00000000 --- a/scripts/2.5/node_modules/object-keys/CHANGELOG.md +++ /dev/null @@ -1,232 +0,0 @@ -1.1.1 / 2019-04-06 -================= - * [Fix] exclude deprecated Firefox keys (#53) - -1.1.0 / 2019-02-10 -================= - * [New] [Refactor] move full implementation to `implementation` entry point - * [Refactor] only evaluate the implementation if `Object.keys` is not present - * [Tests] up to `node` `v11.8`, `v10.15`, `v8.15`, `v6.16` - * [Tests] remove jscs - * [Tests] switch to `npm audit` from `nsp` - -1.0.12 / 2018-06-18 -================= - * [Fix] avoid accessing `window.applicationCache`, to avoid issues with latest Chrome on HTTP (#46) - -1.0.11 / 2016-07-05 -================= - * [Fix] exclude keys regarding the style (eg. `pageYOffset`) on `window` to avoid reflow (#32) - -1.0.10 / 2016-07-04 -================= - * [Fix] exclude `height` and `width` keys on `window` to avoid reflow (#31) - * [Fix] In IE 6, `window.external` makes `Object.keys` throw - * [Tests] up to `node` `v6.2`, `v5.10`, `v4.4` - * [Tests] use pretest/posttest for linting/security - * [Dev Deps] update `tape`, `jscs`, `nsp`, `eslint`, `@ljharb/eslint-config` - * [Dev Deps] remove unused eccheck script + dep - -1.0.9 / 2015-10-19 -================= - * [Fix] Blacklist 'frame' property on window (#16, #17) - * [Dev Deps] update `jscs`, `eslint`, `@ljharb/eslint-config` - -1.0.8 / 2015-10-14 -================= - * [Fix] wrap automation equality bug checking in try/catch, per [es5-shim#327](https://github.com/es-shims/es5-shim/issues/327) - * [Fix] Blacklist 'window.frameElement' per [es5-shim#322](https://github.com/es-shims/es5-shim/issues/322) - * [Docs] Switch from vb.teelaun.ch to versionbadg.es for the npm version badge SVG - * [Tests] up to `io.js` `v3.3`, `node` `v4.2` - * [Dev Deps] update `eslint`, `tape`, `@ljharb/eslint-config`, `jscs` - -1.0.7 / 2015-07-18 -================= - * [Fix] A proper fix for 176f03335e90d5c8d0d8125a99f27819c9b9cdad / https://github.com/es-shims/es5-shim/issues/275 that doesn't break dontEnum/constructor fixes in IE 8. - * [Fix] Remove deprecation message in Chrome by touching deprecated window properties (#15) - * [Tests] Improve test output for automation equality bugfix - * [Tests] Test on `io.js` `v2.4` - -1.0.6 / 2015-07-09 -================= - * [Fix] Use an object lookup rather than ES5's `indexOf` (#14) - * [Tests] ES3 browsers don't have `Array.isArray` - * [Tests] Fix `no-shadow` rule, as well as an IE 8 bug caused by engine NFE shadowing bugs. - -1.0.5 / 2015-07-03 -================= - * [Fix] Fix a flabbergasting IE 8 bug where `localStorage.constructor.prototype === localStorage` throws - * [Tests] Test up to `io.js` `v2.3` - * [Dev Deps] Update `nsp`, `eslint` - -1.0.4 / 2015-05-23 -================= - * Fix a Safari 5.0 bug with `Object.keys` not working with `arguments` - * Test on latest `node` and `io.js` - * Update `jscs`, `tape`, `eslint`, `nsp`, `is`, `editorconfig-tools`, `covert` - -1.0.3 / 2015-01-06 -================= - * Revert "Make `object-keys` more robust against later environment tampering" to maintain ES3 compliance - -1.0.2 / 2014-12-28 -================= - * Update lots of dev dependencies - * Tweaks to README - * Make `object-keys` more robust against later environment tampering - -1.0.1 / 2014-09-03 -================= - * Update URLs and badges in README - -1.0.0 / 2014-08-26 -================= - * v1.0.0 - -0.6.1 / 2014-08-25 -================= - * v0.6.1 - * Updating dependencies (tape, covert, is) - * Update badges in readme - * Use separate var statements - -0.6.0 / 2014-04-23 -================= - * v0.6.0 - * Updating dependencies (tape, covert) - * Make sure boxed primitives, and arguments objects, work properly in ES3 browsers - * Improve test matrix: test all node versions, but only latest two stables are a failure - * Remove internal foreach shim. - -0.5.1 / 2014-03-09 -================= - * 0.5.1 - * Updating dependencies (tape, covert, is) - * Removing forEach from the module (but keeping it in tests) - -0.5.0 / 2014-01-30 -================= - * 0.5.0 - * Explicitly returning the shim, instead of returning native Object.keys when present - * Adding a changelog. - * Cleaning up IIFE wrapping - * Testing on node 0.4 through 0.11 - -0.4.0 / 2013-08-14 -================== - - * v0.4.0 - * In Chrome 4-10 and Safari 4, typeof (new RegExp) === 'function' - * If it's a string, make sure to use charAt instead of brackets. - * Only use Function#call if necessary. - * Making sure the context tests actually run. - * Better function detection - * Adding the android browser - * Fixing testling files - * Updating tape - * Removing the "is" dependency. - * Making an isArguments shim. - * Adding a local forEach shim and tests. - * Updating paths. - * Moving the shim test. - * v0.3.0 - -0.3.0 / 2013-05-18 -================== - - * README tweak. - * Fixing constructor enum issue. Fixes [#5](https://github.com/ljharb/object-keys/issues/5). - * Adding a test for [#5](https://github.com/ljharb/object-keys/issues/5) - * Updating readme. - * Updating dependencies. - * Giving credit to lodash. - * Make sure that a prototype's constructor property is not enumerable. Fixes [#3](https://github.com/ljharb/object-keys/issues/3). - * Adding additional tests to handle arguments objects, and to skip "prototype" in functions. Fixes [#2](https://github.com/ljharb/object-keys/issues/2). - * Fixing a typo on this test for [#3](https://github.com/ljharb/object-keys/issues/3). - * Adding node 0.10 to travis. - * Adding an IE < 9 test per [#3](https://github.com/ljharb/object-keys/issues/3) - * Adding an iOS 5 mobile Safari test per [#2](https://github.com/ljharb/object-keys/issues/2) - * Moving "indexof" and "is" to be dev dependencies. - * Making sure the shim works with functions. - * Flattening the tests. - -0.2.0 / 2013-05-10 -================== - - * v0.2.0 - * Object.keys should work with arrays. - -0.1.8 / 2013-05-10 -================== - - * v0.1.8 - * Upgrading dependencies. - * Using a simpler check. - * Fixing a bug in hasDontEnumBug browsers. - * Using the newest tape! - * Fixing this error test. - * "undefined" is probably a reserved word in ES3. - * Better test message. - -0.1.7 / 2013-04-17 -================== - - * Upgrading "is" once more. - * The key "null" is breaking some browsers. - -0.1.6 / 2013-04-17 -================== - - * v0.1.6 - * Upgrading "is" - -0.1.5 / 2013-04-14 -================== - - * Bumping version. - * Adding more testling browsers. - * Updating "is" - -0.1.4 / 2013-04-08 -================== - - * Using "is" instead of "is-extended". - -0.1.3 / 2013-04-07 -================== - - * Using "foreach" instead of my own shim. - * Removing "tap"; I'll just wait for "tape" to fix its node 0.10 bug. - -0.1.2 / 2013-04-03 -================== - - * Adding dependency status; moving links to an index at the bottom. - * Upgrading is-extended; version 0.1.2 - * Adding an npm version badge. - -0.1.1 / 2013-04-01 -================== - - * Adding Travis CI. - * Bumping the version. - * Adding indexOf since IE sucks. - * Adding a forEach shim since older browsers don't have Array#forEach. - * Upgrading tape - 0.3.2 uses Array#map - * Using explicit end instead of plan. - * Can't test with Array.isArray in older browsers. - * Using is-extended. - * Fixing testling files. - * JSHint/JSLint-ing. - * Removing an unused object. - * Using strict mode. - -0.1.0 / 2013-03-30 -================== - - * Changing the exports should have meant a higher version bump. - * Oops, fixing the repo URL. - * Adding more tests. - * 0.0.2 - * Merge branch 'export_one_thing'; closes [#1](https://github.com/ljharb/object-keys/issues/1) - * Move shim export to a separate file. diff --git a/scripts/2.5/node_modules/object-keys/LICENSE b/scripts/2.5/node_modules/object-keys/LICENSE deleted file mode 100644 index 28553fdd..00000000 --- a/scripts/2.5/node_modules/object-keys/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (C) 2013 Jordan Harband - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. \ No newline at end of file diff --git a/scripts/2.5/node_modules/object-keys/README.md b/scripts/2.5/node_modules/object-keys/README.md deleted file mode 100644 index ed4c2770..00000000 --- a/scripts/2.5/node_modules/object-keys/README.md +++ /dev/null @@ -1,76 +0,0 @@ -#object-keys [![Version Badge][npm-version-svg]][package-url] - -[![Build Status][travis-svg]][travis-url] -[![dependency status][deps-svg]][deps-url] -[![dev dependency status][dev-deps-svg]][dev-deps-url] -[![License][license-image]][license-url] -[![Downloads][downloads-image]][downloads-url] - -[![npm badge][npm-badge-png]][package-url] - -[![browser support][testling-svg]][testling-url] - -An Object.keys shim. Invoke its "shim" method to shim Object.keys if it is unavailable. - -Most common usage: -```js -var keys = Object.keys || require('object-keys'); -``` - -## Example - -```js -var keys = require('object-keys'); -var assert = require('assert'); -var obj = { - a: true, - b: true, - c: true -}; - -assert.deepEqual(keys(obj), ['a', 'b', 'c']); -``` - -```js -var keys = require('object-keys'); -var assert = require('assert'); -/* when Object.keys is not present */ -delete Object.keys; -var shimmedKeys = keys.shim(); -assert.equal(shimmedKeys, keys); -assert.deepEqual(Object.keys(obj), keys(obj)); -``` - -```js -var keys = require('object-keys'); -var assert = require('assert'); -/* when Object.keys is present */ -var shimmedKeys = keys.shim(); -assert.equal(shimmedKeys, Object.keys); -assert.deepEqual(Object.keys(obj), keys(obj)); -``` - -## Source -Implementation taken directly from [es5-shim][es5-shim-url], with modifications, including from [lodash][lodash-url]. - -## Tests -Simply clone the repo, `npm install`, and run `npm test` - -[package-url]: https://npmjs.org/package/object-keys -[npm-version-svg]: http://versionbadg.es/ljharb/object-keys.svg -[travis-svg]: https://travis-ci.org/ljharb/object-keys.svg -[travis-url]: https://travis-ci.org/ljharb/object-keys -[deps-svg]: https://david-dm.org/ljharb/object-keys.svg -[deps-url]: https://david-dm.org/ljharb/object-keys -[dev-deps-svg]: https://david-dm.org/ljharb/object-keys/dev-status.svg -[dev-deps-url]: https://david-dm.org/ljharb/object-keys#info=devDependencies -[testling-svg]: https://ci.testling.com/ljharb/object-keys.png -[testling-url]: https://ci.testling.com/ljharb/object-keys -[es5-shim-url]: https://github.com/es-shims/es5-shim/blob/master/es5-shim.js#L542-589 -[lodash-url]: https://github.com/lodash/lodash -[npm-badge-png]: https://nodei.co/npm/object-keys.png?downloads=true&stars=true -[license-image]: http://img.shields.io/npm/l/object-keys.svg -[license-url]: LICENSE -[downloads-image]: http://img.shields.io/npm/dm/object-keys.svg -[downloads-url]: http://npm-stat.com/charts.html?package=object-keys - diff --git a/scripts/2.5/node_modules/object-keys/implementation.js b/scripts/2.5/node_modules/object-keys/implementation.js deleted file mode 100644 index 5b329861..00000000 --- a/scripts/2.5/node_modules/object-keys/implementation.js +++ /dev/null @@ -1,122 +0,0 @@ -'use strict'; - -var keysShim; -if (!Object.keys) { - // modified from https://github.com/es-shims/es5-shim - var has = Object.prototype.hasOwnProperty; - var toStr = Object.prototype.toString; - var isArgs = require('./isArguments'); // eslint-disable-line global-require - var isEnumerable = Object.prototype.propertyIsEnumerable; - var hasDontEnumBug = !isEnumerable.call({ toString: null }, 'toString'); - var hasProtoEnumBug = isEnumerable.call(function () {}, 'prototype'); - var dontEnums = [ - 'toString', - 'toLocaleString', - 'valueOf', - 'hasOwnProperty', - 'isPrototypeOf', - 'propertyIsEnumerable', - 'constructor' - ]; - var equalsConstructorPrototype = function (o) { - var ctor = o.constructor; - return ctor && ctor.prototype === o; - }; - var excludedKeys = { - $applicationCache: true, - $console: true, - $external: true, - $frame: true, - $frameElement: true, - $frames: true, - $innerHeight: true, - $innerWidth: true, - $onmozfullscreenchange: true, - $onmozfullscreenerror: true, - $outerHeight: true, - $outerWidth: true, - $pageXOffset: true, - $pageYOffset: true, - $parent: true, - $scrollLeft: true, - $scrollTop: true, - $scrollX: true, - $scrollY: true, - $self: true, - $webkitIndexedDB: true, - $webkitStorageInfo: true, - $window: true - }; - var hasAutomationEqualityBug = (function () { - /* global window */ - if (typeof window === 'undefined') { return false; } - for (var k in window) { - try { - if (!excludedKeys['$' + k] && has.call(window, k) && window[k] !== null && typeof window[k] === 'object') { - try { - equalsConstructorPrototype(window[k]); - } catch (e) { - return true; - } - } - } catch (e) { - return true; - } - } - return false; - }()); - var equalsConstructorPrototypeIfNotBuggy = function (o) { - /* global window */ - if (typeof window === 'undefined' || !hasAutomationEqualityBug) { - return equalsConstructorPrototype(o); - } - try { - return equalsConstructorPrototype(o); - } catch (e) { - return false; - } - }; - - keysShim = function keys(object) { - var isObject = object !== null && typeof object === 'object'; - var isFunction = toStr.call(object) === '[object Function]'; - var isArguments = isArgs(object); - var isString = isObject && toStr.call(object) === '[object String]'; - var theKeys = []; - - if (!isObject && !isFunction && !isArguments) { - throw new TypeError('Object.keys called on a non-object'); - } - - var skipProto = hasProtoEnumBug && isFunction; - if (isString && object.length > 0 && !has.call(object, 0)) { - for (var i = 0; i < object.length; ++i) { - theKeys.push(String(i)); - } - } - - if (isArguments && object.length > 0) { - for (var j = 0; j < object.length; ++j) { - theKeys.push(String(j)); - } - } else { - for (var name in object) { - if (!(skipProto && name === 'prototype') && has.call(object, name)) { - theKeys.push(String(name)); - } - } - } - - if (hasDontEnumBug) { - var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object); - - for (var k = 0; k < dontEnums.length; ++k) { - if (!(skipConstructor && dontEnums[k] === 'constructor') && has.call(object, dontEnums[k])) { - theKeys.push(dontEnums[k]); - } - } - } - return theKeys; - }; -} -module.exports = keysShim; diff --git a/scripts/2.5/node_modules/object-keys/index.js b/scripts/2.5/node_modules/object-keys/index.js deleted file mode 100644 index a43807d2..00000000 --- a/scripts/2.5/node_modules/object-keys/index.js +++ /dev/null @@ -1,32 +0,0 @@ -'use strict'; - -var slice = Array.prototype.slice; -var isArgs = require('./isArguments'); - -var origKeys = Object.keys; -var keysShim = origKeys ? function keys(o) { return origKeys(o); } : require('./implementation'); - -var originalKeys = Object.keys; - -keysShim.shim = function shimObjectKeys() { - if (Object.keys) { - var keysWorksWithArguments = (function () { - // Safari 5.0 bug - var args = Object.keys(arguments); - return args && args.length === arguments.length; - }(1, 2)); - if (!keysWorksWithArguments) { - Object.keys = function keys(object) { // eslint-disable-line func-name-matching - if (isArgs(object)) { - return originalKeys(slice.call(object)); - } - return originalKeys(object); - }; - } - } else { - Object.keys = keysShim; - } - return Object.keys || keysShim; -}; - -module.exports = keysShim; diff --git a/scripts/2.5/node_modules/object-keys/isArguments.js b/scripts/2.5/node_modules/object-keys/isArguments.js deleted file mode 100644 index f2a2a901..00000000 --- a/scripts/2.5/node_modules/object-keys/isArguments.js +++ /dev/null @@ -1,17 +0,0 @@ -'use strict'; - -var toStr = Object.prototype.toString; - -module.exports = function isArguments(value) { - var str = toStr.call(value); - var isArgs = str === '[object Arguments]'; - if (!isArgs) { - isArgs = str !== '[object Array]' && - value !== null && - typeof value === 'object' && - typeof value.length === 'number' && - value.length >= 0 && - toStr.call(value.callee) === '[object Function]'; - } - return isArgs; -}; diff --git a/scripts/2.5/node_modules/object-keys/package.json b/scripts/2.5/node_modules/object-keys/package.json deleted file mode 100644 index a1575607..00000000 --- a/scripts/2.5/node_modules/object-keys/package.json +++ /dev/null @@ -1,118 +0,0 @@ -{ - "_from": "object-keys@^1.0.12", - "_id": "object-keys@1.1.1", - "_inBundle": false, - "_integrity": "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==", - "_location": "/object-keys", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "object-keys@^1.0.12", - "name": "object-keys", - "escapedName": "object-keys", - "rawSpec": "^1.0.12", - "saveSpec": null, - "fetchSpec": "^1.0.12" - }, - "_requiredBy": [ - "/define-properties", - "/es-abstract" - ], - "_resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz", - "_shasum": "1c47f272df277f3b1daf061677d9c82e2322c60e", - "_spec": "object-keys@^1.0.12", - "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/2.5/node_modules/define-properties", - "author": { - "name": "Jordan Harband", - "email": "ljharb@gmail.com", - "url": "http://ljharb.codes" - }, - "bugs": { - "url": "https://github.com/ljharb/object-keys/issues" - }, - "bundleDependencies": false, - "contributors": [ - { - "name": "Jordan Harband", - "email": "ljharb@gmail.com", - "url": "http://ljharb.codes" - }, - { - "name": "Raynos", - "email": "raynos2@gmail.com" - }, - { - "name": "Nathan Rajlich", - "email": "nathan@tootallnate.net" - }, - { - "name": "Ivan Starkov", - "email": "istarkov@gmail.com" - }, - { - "name": "Gary Katsevman", - "email": "git@gkatsev.com" - } - ], - "dependencies": {}, - "deprecated": false, - "description": "An Object.keys replacement, in case Object.keys is not available. From https://github.com/es-shims/es5-shim", - "devDependencies": { - "@ljharb/eslint-config": "^13.1.1", - "covert": "^1.1.1", - "eslint": "^5.13.0", - "foreach": "^2.0.5", - "indexof": "^0.0.1", - "is": "^3.3.0", - "tape": "^4.9.2" - }, - "engines": { - "node": ">= 0.4" - }, - "homepage": "https://github.com/ljharb/object-keys#readme", - "keywords": [ - "Object.keys", - "keys", - "ES5", - "shim" - ], - "license": "MIT", - "main": "index.js", - "name": "object-keys", - "repository": { - "type": "git", - "url": "git://github.com/ljharb/object-keys.git" - }, - "scripts": { - "audit": "npm audit", - "coverage": "covert test/*.js", - "coverage-quiet": "covert test/*.js --quiet", - "lint": "eslint .", - "postaudit": "rm package-lock.json", - "posttest": "npm run --silent audit", - "preaudit": "npm install --package-lock --package-lock-only", - "pretest": "npm run --silent lint", - "test": "npm run --silent tests-only", - "tests-only": "node test/index.js" - }, - "testling": { - "files": "test/index.js", - "browsers": [ - "iexplore/6.0..latest", - "firefox/3.0..6.0", - "firefox/15.0..latest", - "firefox/nightly", - "chrome/4.0..10.0", - "chrome/20.0..latest", - "chrome/canary", - "opera/10.0..latest", - "opera/next", - "safari/4.0..latest", - "ipad/6.0..latest", - "iphone/6.0..latest", - "android-browser/4.2" - ] - }, - "version": "1.1.1" -} diff --git a/scripts/2.5/node_modules/object-keys/test/index.js b/scripts/2.5/node_modules/object-keys/test/index.js deleted file mode 100644 index 5402465a..00000000 --- a/scripts/2.5/node_modules/object-keys/test/index.js +++ /dev/null @@ -1,5 +0,0 @@ -'use strict'; - -require('./isArguments'); - -require('./shim'); diff --git a/scripts/2.5/node_modules/object.entries/.editorconfig b/scripts/2.5/node_modules/object.entries/.editorconfig deleted file mode 100644 index bc228f82..00000000 --- a/scripts/2.5/node_modules/object.entries/.editorconfig +++ /dev/null @@ -1,20 +0,0 @@ -root = true - -[*] -indent_style = tab -indent_size = 4 -end_of_line = lf -charset = utf-8 -trim_trailing_whitespace = true -insert_final_newline = true -max_line_length = 150 - -[CHANGELOG.md] -indent_style = space -indent_size = 2 - -[*.json] -max_line_length = off - -[Makefile] -max_line_length = off diff --git a/scripts/2.5/node_modules/object.entries/.eslintrc b/scripts/2.5/node_modules/object.entries/.eslintrc deleted file mode 100644 index 3378618b..00000000 --- a/scripts/2.5/node_modules/object.entries/.eslintrc +++ /dev/null @@ -1,11 +0,0 @@ -{ - "root": true, - - "extends": "@ljharb", - - "rules": { - "new-cap": [2, { "capIsNewExceptions": ["RequireObjectCoercible"] }], - "no-magic-numbers": [0], - "no-restricted-syntax": [2, "BreakStatement", "ContinueStatement", "DebuggerStatement", "LabeledStatement", "WithStatement"] - } -} diff --git a/scripts/2.5/node_modules/object.entries/.travis.yml b/scripts/2.5/node_modules/object.entries/.travis.yml deleted file mode 100644 index 2056556d..00000000 --- a/scripts/2.5/node_modules/object.entries/.travis.yml +++ /dev/null @@ -1,269 +0,0 @@ -language: node_js -os: - - linux -node_js: - - "11.6" - - "10.15" - - "9.11" - - "8.15" - - "7.10" - - "6.16" - - "5.12" - - "4.9" - - "iojs-v3.3" - - "iojs-v2.5" - - "iojs-v1.8" - - "0.12" - - "0.10" - - "0.8" -before_install: - - 'case "${TRAVIS_NODE_VERSION}" in 0.*) export NPM_CONFIG_STRICT_SSL=false ;; esac' - - 'nvm install-latest-npm' -install: - - 'if [ "${TRAVIS_NODE_VERSION}" = "0.6" ] || [ "${TRAVIS_NODE_VERSION}" = "0.9" ]; then nvm install --latest-npm 0.8 && npm install && nvm use "${TRAVIS_NODE_VERSION}"; else npm install; fi;' -script: - - 'if [ -n "${PRETEST-}" ]; then npm run pretest ; fi' - - 'if [ -n "${POSTTEST-}" ]; then npm run posttest ; fi' - - 'if [ -n "${COVERAGE-}" ]; then npm run coverage ; fi' - - 'if [ -n "${TEST-}" ]; then npm run tests-only ; fi' -sudo: false -env: - - TEST=true -matrix: - fast_finish: true - include: - - node_js: "lts/*" - env: PRETEST=true - - node_js: "lts/*" - env: POSTTEST=true - - node_js: "11.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "11.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "11.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "11.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "11.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "11.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.14" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.13" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.12" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.11" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.10" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.10" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.14" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.13" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.12" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.11" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.10" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.15" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.14" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.13" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.12" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.11" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.10" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.11" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.10" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v3.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v3.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v3.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "0.11" - env: TEST=true ALLOW_FAILURE=true - - node_js: "0.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "0.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "0.4" - env: TEST=true ALLOW_FAILURE=true - allow_failures: - - os: osx - - env: TEST=true ALLOW_FAILURE=true diff --git a/scripts/2.5/node_modules/object.entries/CHANGELOG.md b/scripts/2.5/node_modules/object.entries/CHANGELOG.md deleted file mode 100644 index 35e6c3d1..00000000 --- a/scripts/2.5/node_modules/object.entries/CHANGELOG.md +++ /dev/null @@ -1,33 +0,0 @@ -1.1.0 / 2019-01-01 -================= - * [New] add `auto` entry point` - * [meta] exclude test.html from the npm package - * [Deps] update `define-properties`, `es-abstract`, `function-bind`, `has` - * [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `covert`, `tape` - * [Tests] up to `node` `v11.6`, `v10.15`, `v9.11`, `v8.15`, `v7.10`, `v6.16`, `v4.9`; use `nvm install-latest-npm` - * [Tests] use `npm audit` instead of `nsp` - * [Tests] remove `jscs` - -1.0.4 / 2016-12-04 -================= - * [Deps] update `es-abstract`, `function-bind`, `define-properties` - * [Dev Deps] update `tape`, `jscs`, `nsp`, `eslint`, `@ljharb/eslint-config` - * [Tests] up to `node` `v7.2`, `v6.9`, `v4.6`; improve test matrix. - -1.0.3 / 2015-10-06 -================= - * [Fix] Not-yet-visited keys made non-enumerable on a `[[Get]]` must not show up in the output (https://github.com/ljharb/proposal-object-values-entries/issues/5) - -1.0.2 / 2015-09-25 -================= - * [Fix] Not-yet-visited keys deleted on a `[[Get]]` must not show up in the output (#1) - -1.0.1 / 2015-09-21 -================= - * [Docs] update version badge URL - * [Tests] on `io.js` `v3.3`, up to `node` `v4.1` - * [Dev Deps] update `eslint`, `@ljharb/eslint-config` - -1.0.0 / 2015-09-02 -================= - * v1.0.0 diff --git a/scripts/2.5/node_modules/object.entries/LICENSE b/scripts/2.5/node_modules/object.entries/LICENSE deleted file mode 100644 index b43df444..00000000 --- a/scripts/2.5/node_modules/object.entries/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015 Jordan Harband - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - diff --git a/scripts/2.5/node_modules/object.entries/README.md b/scripts/2.5/node_modules/object.entries/README.md deleted file mode 100644 index f0cdbfdc..00000000 --- a/scripts/2.5/node_modules/object.entries/README.md +++ /dev/null @@ -1,59 +0,0 @@ -# object.entries [![Version Badge][npm-version-svg]][package-url] - -[![Build Status][travis-svg]][travis-url] -[![dependency status][deps-svg]][deps-url] -[![dev dependency status][dev-deps-svg]][dev-deps-url] -[![License][license-image]][license-url] -[![Downloads][downloads-image]][downloads-url] - -[![npm badge][npm-badge-png]][package-url] - -[![browser support][testling-svg]][testling-url] - -An ES2017 spec-compliant `Object.entries` shim. Invoke its "shim" method to shim `Object.entries` if it is unavailable or noncompliant. - -This package implements the [es-shim API](https://github.com/es-shims/api) interface. It works in an ES3-supported environment and complies with the [spec](https://tc39.github.io/ecma262/#sec-object.entries). - -Most common usage: -```js -var assert = require('assert'); -var entries = require('object.entries'); - -var obj = { a: 1, b: 2, c: 3 }; -var expected = [['a', 1], ['b', 2], ['c', 3]]; - -if (typeof Symbol === 'function' && typeof Symbol() === 'symbol') { - // for environments with Symbol support - var sym = Symbol(); - obj[sym] = 4; - obj.d = sym; - expected.push(['d', sym]); -} - -assert.deepEqual(entries(obj), expected); - -if (!Object.entries) { - entries.shim(); -} - -assert.deepEqual(Object.entries(obj), expected); -``` - -## Tests -Simply clone the repo, `npm install`, and run `npm test` - -[package-url]: https://npmjs.com/package/object.entries -[npm-version-svg]: http://versionbadg.es/es-shims/Object.entries.svg -[travis-svg]: https://travis-ci.org/es-shims/Object.entries.svg -[travis-url]: https://travis-ci.org/es-shims/Object.entries -[deps-svg]: https://david-dm.org/es-shims/Object.entries.svg -[deps-url]: https://david-dm.org/es-shims/Object.entries -[dev-deps-svg]: https://david-dm.org/es-shims/Object.entries/dev-status.svg -[dev-deps-url]: https://david-dm.org/es-shims/Object.entries#info=devDependencies -[testling-svg]: https://ci.testling.com/es-shims/Object.entries.png -[testling-url]: https://ci.testling.com/es-shims/Object.entries -[npm-badge-png]: https://nodei.co/npm/object.entries.png?downloads=true&stars=true -[license-image]: http://img.shields.io/npm/l/object.entries.svg -[license-url]: LICENSE -[downloads-image]: http://img.shields.io/npm/dm/object.entries.svg -[downloads-url]: http://npm-stat.com/charts.html?package=object.entries diff --git a/scripts/2.5/node_modules/object.entries/auto.js b/scripts/2.5/node_modules/object.entries/auto.js deleted file mode 100644 index 8ebf606c..00000000 --- a/scripts/2.5/node_modules/object.entries/auto.js +++ /dev/null @@ -1,3 +0,0 @@ -'use strict'; - -require('./shim')(); diff --git a/scripts/2.5/node_modules/object.entries/implementation.js b/scripts/2.5/node_modules/object.entries/implementation.js deleted file mode 100644 index 0310246d..00000000 --- a/scripts/2.5/node_modules/object.entries/implementation.js +++ /dev/null @@ -1,17 +0,0 @@ -'use strict'; - -var ES = require('es-abstract/es7'); -var has = require('has'); -var bind = require('function-bind'); -var isEnumerable = bind.call(Function.call, Object.prototype.propertyIsEnumerable); - -module.exports = function entries(O) { - var obj = ES.RequireObjectCoercible(O); - var entrys = []; - for (var key in obj) { - if (has(obj, key) && isEnumerable(obj, key)) { - entrys.push([key, obj[key]]); - } - } - return entrys; -}; diff --git a/scripts/2.5/node_modules/object.entries/index.js b/scripts/2.5/node_modules/object.entries/index.js deleted file mode 100644 index b8ba0910..00000000 --- a/scripts/2.5/node_modules/object.entries/index.js +++ /dev/null @@ -1,17 +0,0 @@ -'use strict'; - -var define = require('define-properties'); - -var implementation = require('./implementation'); -var getPolyfill = require('./polyfill'); -var shim = require('./shim'); - -var polyfill = getPolyfill(); - -define(polyfill, { - getPolyfill: getPolyfill, - implementation: implementation, - shim: shim -}); - -module.exports = polyfill; diff --git a/scripts/2.5/node_modules/object.entries/package.json b/scripts/2.5/node_modules/object.entries/package.json deleted file mode 100644 index e33d9f21..00000000 --- a/scripts/2.5/node_modules/object.entries/package.json +++ /dev/null @@ -1,107 +0,0 @@ -{ - "_from": "object.entries@^1.1.0", - "_id": "object.entries@1.1.0", - "_inBundle": false, - "_integrity": "sha512-l+H6EQ8qzGRxbkHOd5I/aHRhHDKoQXQ8g0BYt4uSweQU1/J6dZUOyWh9a2Vky35YCKjzmgxOzta2hH6kf9HuXA==", - "_location": "/object.entries", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "object.entries@^1.1.0", - "name": "object.entries", - "escapedName": "object.entries", - "rawSpec": "^1.1.0", - "saveSpec": null, - "fetchSpec": "^1.1.0" - }, - "_requiredBy": [ - "/util" - ], - "_resolved": "https://registry.npmjs.org/object.entries/-/object.entries-1.1.0.tgz", - "_shasum": "2024fc6d6ba246aee38bdb0ffd5cfbcf371b7519", - "_spec": "object.entries@^1.1.0", - "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/2.5/node_modules/util", - "author": { - "name": "Jordan Harband" - }, - "bugs": { - "url": "https://github.com/es-shims/Object.entries/issues" - }, - "bundleDependencies": false, - "dependencies": { - "define-properties": "^1.1.3", - "es-abstract": "^1.12.0", - "function-bind": "^1.1.1", - "has": "^1.0.3" - }, - "deprecated": false, - "description": "ES2017 spec-compliant Object.entries shim.", - "devDependencies": { - "@es-shims/api": "^2.1.2", - "@ljharb/eslint-config": "^13.1.1", - "array-map": "^0.0.0", - "covert": "^1.1.1", - "eslint": "^5.11.1", - "tape": "^4.9.2" - }, - "engines": { - "node": ">= 0.4" - }, - "homepage": "https://github.com/es-shims/Object.entries#readme", - "keywords": [ - "Object.entries", - "Object.values", - "Object.keys", - "entries", - "values", - "ES7", - "ES8", - "ES2017", - "shim", - "object", - "keys", - "polyfill", - "es-shim API" - ], - "license": "MIT", - "main": "index.js", - "name": "object.entries", - "repository": { - "type": "git", - "url": "git://github.com/es-shims/Object.entries.git" - }, - "scripts": { - "audit": "npm audit", - "coverage": "covert test/*.js", - "coverage-quiet": "covert test/*.js --quiet", - "lint": "eslint .", - "postaudit": "rm package-lock.json", - "posttest": "npm run audit", - "preaudit": "npm install --package-lock-only --package-lock", - "pretest": "npm run --silent lint", - "test": "npm run --silent tests-only", - "test:module": "node test/index.js", - "test:shimmed": "node test/shimmed.js", - "tests-only": "es-shim-api && npm run --silent test:shimmed && npm run --silent test:module" - }, - "testling": { - "files": "test/index.js", - "browsers": [ - "iexplore/9.0..latest", - "firefox/4.0..6.0", - "firefox/15.0..latest", - "firefox/nightly", - "chrome/4.0..10.0", - "chrome/20.0..latest", - "chrome/canary", - "opera/11.6..latest", - "opera/next", - "safari/5.0..latest", - "ipad/6.0..latest", - "iphone/6.0..latest", - "android-browser/4.2" - ] - }, - "version": "1.1.0" -} diff --git a/scripts/2.5/node_modules/object.entries/polyfill.js b/scripts/2.5/node_modules/object.entries/polyfill.js deleted file mode 100644 index 32e3238f..00000000 --- a/scripts/2.5/node_modules/object.entries/polyfill.js +++ /dev/null @@ -1,7 +0,0 @@ -'use strict'; - -var implementation = require('./implementation'); - -module.exports = function getPolyfill() { - return typeof Object.entries === 'function' ? Object.entries : implementation; -}; diff --git a/scripts/2.5/node_modules/object.entries/shim.js b/scripts/2.5/node_modules/object.entries/shim.js deleted file mode 100644 index 135defef..00000000 --- a/scripts/2.5/node_modules/object.entries/shim.js +++ /dev/null @@ -1,14 +0,0 @@ -'use strict'; - -var getPolyfill = require('./polyfill'); -var define = require('define-properties'); - -module.exports = function shimEntries() { - var polyfill = getPolyfill(); - define(Object, { entries: polyfill }, { - entries: function testEntries() { - return Object.entries !== polyfill; - } - }); - return polyfill; -}; diff --git a/scripts/2.5/node_modules/object.entries/test/.eslintrc b/scripts/2.5/node_modules/object.entries/test/.eslintrc deleted file mode 100644 index 5bddce79..00000000 --- a/scripts/2.5/node_modules/object.entries/test/.eslintrc +++ /dev/null @@ -1,11 +0,0 @@ -{ - "rules": { - "array-bracket-newline": 0, - "max-lines-per-function": 0, - "max-nested-callbacks": [2, 3], - "max-statements": [2, 12], - "max-statements-per-line": [2, { "max": 3 }], - "no-invalid-this": [1], - "object-curly-newline": 0, - } -} diff --git a/scripts/2.5/node_modules/object.entries/test/index.js b/scripts/2.5/node_modules/object.entries/test/index.js deleted file mode 100644 index 1859a3f8..00000000 --- a/scripts/2.5/node_modules/object.entries/test/index.js +++ /dev/null @@ -1,17 +0,0 @@ -'use strict'; - -var entries = require('../'); -var test = require('tape'); -var runTests = require('./tests'); - -test('as a function', function (t) { - t.test('bad array/this value', function (st) { - st['throws'](function () { entries(undefined); }, TypeError, 'undefined is not an object'); - st['throws'](function () { entries(null); }, TypeError, 'null is not an object'); - st.end(); - }); - - runTests(entries, t); - - t.end(); -}); diff --git a/scripts/2.5/node_modules/object.entries/test/shimmed.js b/scripts/2.5/node_modules/object.entries/test/shimmed.js deleted file mode 100644 index 3f1d3770..00000000 --- a/scripts/2.5/node_modules/object.entries/test/shimmed.js +++ /dev/null @@ -1,36 +0,0 @@ -'use strict'; - -var entries = require('../'); -entries.shim(); - -var test = require('tape'); -var defineProperties = require('define-properties'); -var isEnumerable = Object.prototype.propertyIsEnumerable; -var functionsHaveNames = function f() {}.name === 'f'; - -var runTests = require('./tests'); - -test('shimmed', function (t) { - t.equal(Object.entries.length, 1, 'Object.entries has a length of 1'); - t.test('Function name', { skip: !functionsHaveNames }, function (st) { - st.equal(Object.entries.name, 'entries', 'Object.entries has name "entries"'); - st.end(); - }); - - t.test('enumerability', { skip: !defineProperties.supportsDescriptors }, function (et) { - et.equal(false, isEnumerable.call(Object, 'entries'), 'Object.entries is not enumerable'); - et.end(); - }); - - var supportsStrictMode = (function () { return typeof this === 'undefined'; }()); - - t.test('bad object value', { skip: !supportsStrictMode }, function (st) { - st['throws'](function () { return Object.entries(undefined); }, TypeError, 'undefined is not an object'); - st['throws'](function () { return Object.entries(null); }, TypeError, 'null is not an object'); - st.end(); - }); - - runTests(Object.entries, t); - - t.end(); -}); diff --git a/scripts/2.5/node_modules/object.entries/test/tests.js b/scripts/2.5/node_modules/object.entries/test/tests.js deleted file mode 100644 index 03b8613e..00000000 --- a/scripts/2.5/node_modules/object.entries/test/tests.js +++ /dev/null @@ -1,84 +0,0 @@ -'use strict'; - -/* global Symbol */ - -var keys = require('object-keys'); -var map = require('array-map'); -var define = require('define-properties'); - -var hasSymbols = typeof Symbol === 'function' && typeof Symbol('foo') === 'symbol'; - -module.exports = function (entries, t) { - var a = {}; - var b = {}; - var c = {}; - var obj = { a: a, b: b, c: c }; - - t.deepEqual(entries(obj), [['a', a], ['b', b], ['c', c]], 'basic support'); - t.deepEqual(entries({ a: a, b: a, c: c }), [['a', a], ['b', a], ['c', c]], 'duplicate entries are included'); - - t.test('entries are in the same order as keys', function (st) { - var object = { a: a, b: b }; - object[0] = 3; - object.c = c; - object[1] = 4; - delete object[0]; - var objKeys = keys(object); - var objEntries = map(objKeys, function (key) { - return [key, object[key]]; - }); - st.deepEqual(entries(object), objEntries, 'entries match key order'); - st.end(); - }); - - t.test('non-enumerable properties are omitted', { skip: !Object.defineProperty }, function (st) { - var object = { a: a, b: b }; - Object.defineProperty(object, 'c', { enumerable: false, value: c }); - st.deepEqual(entries(object), [['a', a], ['b', b]], 'non-enumerable property‘s value is omitted'); - st.end(); - }); - - t.test('inherited properties are omitted', function (st) { - var F = function G() {}; - F.prototype.a = a; - var f = new F(); - f.b = b; - st.deepEqual(entries(f), [['b', b]], 'only own properties are included'); - st.end(); - }); - - t.test('Symbol properties are omitted', { skip: !hasSymbols }, function (st) { - var object = { a: a, b: b, c: c }; - var enumSym = Symbol('enum'); - var nonEnumSym = Symbol('non enum'); - object[enumSym] = enumSym; - object.d = enumSym; - Object.defineProperty(object, nonEnumSym, { enumerable: false, value: nonEnumSym }); - st.deepEqual(entries(object), [['a', a], ['b', b], ['c', c], ['d', enumSym]], 'symbol properties are omitted'); - st.end(); - }); - - t.test('not-yet-visited keys deleted on [[Get]] must not show up in output', { skip: !define.supportsDescriptors }, function (st) { - var o = { a: 1, b: 2, c: 3 }; - Object.defineProperty(o, 'a', { - get: function () { - delete this.b; - return 1; - } - }); - st.deepEqual(entries(o), [['a', 1], ['c', 3]], 'when "b" is deleted prior to being visited, it should not show up'); - st.end(); - }); - - t.test('not-yet-visited keys made non-enumerable on [[Get]] must not show up in output', { skip: !define.supportsDescriptors }, function (st) { - var o = { a: 'A', b: 'B' }; - Object.defineProperty(o, 'a', { - get: function () { - Object.defineProperty(o, 'b', { enumerable: false }); - return 'A'; - } - }); - st.deepEqual(entries(o), [['a', 'A']], 'when "b" is made non-enumerable prior to being visited, it should not show up'); - st.end(); - }); -}; diff --git a/scripts/2.5/node_modules/require_optional/.npmignore b/scripts/2.5/node_modules/require_optional/.npmignore deleted file mode 100644 index e920c167..00000000 --- a/scripts/2.5/node_modules/require_optional/.npmignore +++ /dev/null @@ -1,33 +0,0 @@ -# Logs -logs -*.log -npm-debug.log* - -# Runtime data -pids -*.pid -*.seed - -# Directory for instrumented libs generated by jscoverage/JSCover -lib-cov - -# Coverage directory used by tools like istanbul -coverage - -# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) -.grunt - -# node-waf configuration -.lock-wscript - -# Compiled binary addons (http://nodejs.org/api/addons.html) -build/Release - -# Dependency directory -node_modules - -# Optional npm cache directory -.npm - -# Optional REPL history -.node_repl_history diff --git a/scripts/2.5/node_modules/require_optional/.travis.yml b/scripts/2.5/node_modules/require_optional/.travis.yml deleted file mode 100644 index 72903c34..00000000 --- a/scripts/2.5/node_modules/require_optional/.travis.yml +++ /dev/null @@ -1,9 +0,0 @@ -language: node_js -node_js: - - "0.10" - - "0.12" - - "4" - - "6" - - "7" - - "8" -sudo: false diff --git a/scripts/2.5/node_modules/require_optional/HISTORY.md b/scripts/2.5/node_modules/require_optional/HISTORY.md deleted file mode 100644 index 7bee02fc..00000000 --- a/scripts/2.5/node_modules/require_optional/HISTORY.md +++ /dev/null @@ -1,7 +0,0 @@ -1.0.1 03-02-2016 -================ -* Fix dependency resolution issue when a component in peerOptionalDependencies is installed at the level of the module declaring in peerOptionalDependencies. - -1.0.0 03-02-2016 -================ -* Initial release allowing us to optionally resolve dependencies in the package.json file under the peerOptionalDependencies tag. \ No newline at end of file diff --git a/scripts/2.5/node_modules/require_optional/LICENSE b/scripts/2.5/node_modules/require_optional/LICENSE deleted file mode 100644 index 8dada3ed..00000000 --- a/scripts/2.5/node_modules/require_optional/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "{}" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright {yyyy} {name of copyright owner} - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/scripts/2.5/node_modules/require_optional/README.md b/scripts/2.5/node_modules/require_optional/README.md deleted file mode 100644 index c0323f06..00000000 --- a/scripts/2.5/node_modules/require_optional/README.md +++ /dev/null @@ -1,2 +0,0 @@ -# require_optional -Work around the problem that we do not have a optionalPeerDependencies concept in node.js making it a hassle to optionally include native modules diff --git a/scripts/2.5/node_modules/require_optional/index.js b/scripts/2.5/node_modules/require_optional/index.js deleted file mode 100644 index 3710319f..00000000 --- a/scripts/2.5/node_modules/require_optional/index.js +++ /dev/null @@ -1,128 +0,0 @@ -var path = require('path'), - fs = require('fs'), - f = require('util').format, - resolveFrom = require('resolve-from'), - semver = require('semver'); - -var exists = fs.existsSync || path.existsSync; - -// Find the location of a package.json file near or above the given location -var find_package_json = function(location) { - var found = false; - - while(!found) { - if (exists(location + '/package.json')) { - found = location; - } else if (location !== '/') { - location = path.dirname(location); - } else { - return false; - } - } - - return location; -} - -// Find the package.json object of the module closest up the module call tree that contains name in that module's peerOptionalDependencies -var find_package_json_with_name = function(name) { - // Walk up the module call tree until we find a module containing name in its peerOptionalDependencies - var currentModule = module; - var found = false; - while (currentModule) { - // Check currentModule has a package.json - location = currentModule.filename; - var location = find_package_json(location) - if (!location) { - currentModule = currentModule.parent; - continue; - } - - // Read the package.json file - var object = JSON.parse(fs.readFileSync(f('%s/package.json', location))); - // Is the name defined by interal file references - var parts = name.split(/\//); - - // Check whether this package.json contains peerOptionalDependencies containing the name we're searching for - if (!object.peerOptionalDependencies || (object.peerOptionalDependencies && !object.peerOptionalDependencies[parts[0]])) { - currentModule = currentModule.parent; - continue; - } - found = true; - break; - } - - // Check whether name has been found in currentModule's peerOptionalDependencies - if (!found) { - throw new Error(f('no optional dependency [%s] defined in peerOptionalDependencies in any package.json', parts[0])); - } - - return { - object: object, - parts: parts - } -} - -var require_optional = function(name, options) { - options = options || {}; - options.strict = typeof options.strict == 'boolean' ? options.strict : true; - - var res = find_package_json_with_name(name) - var object = res.object; - var parts = res.parts; - - // Unpack the expected version - var expectedVersions = object.peerOptionalDependencies[parts[0]]; - // The resolved package - var moduleEntry = undefined; - // Module file - var moduleEntryFile = name; - - try { - // Validate if it's possible to read the module - moduleEntry = require(moduleEntryFile); - } catch(err) { - // Attempt to resolve in top level package - try { - // Get the module entry file - moduleEntryFile = resolveFrom(process.cwd(), name); - if(moduleEntryFile == null) return undefined; - // Attempt to resolve the module - moduleEntry = require(moduleEntryFile); - } catch(err) { - if(err.code === 'MODULE_NOT_FOUND') return undefined; - } - } - - // Resolve the location of the module's package.json file - var location = find_package_json(require.resolve(moduleEntryFile)); - if(!location) { - throw new Error('package.json can not be located'); - } - - // Read the module file - var dependentOnModule = JSON.parse(fs.readFileSync(f('%s/package.json', location))); - // Get the version - var version = dependentOnModule.version; - // Validate if the found module satisfies the version id - if(semver.satisfies(version, expectedVersions) == false - && options.strict) { - var error = new Error(f('optional dependency [%s] found but version [%s] did not satisfy constraint [%s]', parts[0], version, expectedVersions)); - error.code = 'OPTIONAL_MODULE_NOT_FOUND'; - throw error; - } - - // Satifies the module requirement - return moduleEntry; -} - -require_optional.exists = function(name) { - try { - var m = require_optional(name); - if(m === undefined) return false; - return true; - } catch(err) { - return false; - } -} - -module.exports = require_optional; diff --git a/scripts/2.5/node_modules/require_optional/package.json b/scripts/2.5/node_modules/require_optional/package.json deleted file mode 100644 index 962396b0..00000000 --- a/scripts/2.5/node_modules/require_optional/package.json +++ /dev/null @@ -1,67 +0,0 @@ -{ - "_from": "require_optional@^1.0.1", - "_id": "require_optional@1.0.1", - "_inBundle": false, - "_integrity": "sha512-qhM/y57enGWHAe3v/NcwML6a3/vfESLe/sGM2dII+gEO0BpKRUkWZow/tyloNqJyN6kXSl3RyyM8Ll5D/sJP8g==", - "_location": "/require_optional", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "require_optional@^1.0.1", - "name": "require_optional", - "escapedName": "require_optional", - "rawSpec": "^1.0.1", - "saveSpec": null, - "fetchSpec": "^1.0.1" - }, - "_requiredBy": [ - "/mongodb" - ], - "_resolved": "https://registry.npmjs.org/require_optional/-/require_optional-1.0.1.tgz", - "_shasum": "4cf35a4247f64ca3df8c2ef208cc494b1ca8fc2e", - "_spec": "require_optional@^1.0.1", - "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/2.5/node_modules/mongodb", - "author": { - "name": "Christian Kvalheim Amor" - }, - "bugs": { - "url": "https://github.com/christkv/require_optional/issues" - }, - "bundleDependencies": false, - "dependencies": { - "resolve-from": "^2.0.0", - "semver": "^5.1.0" - }, - "deprecated": false, - "description": "Allows you declare optionalPeerDependencies that can be satisfied by the top level module but ignored if they are not.", - "devDependencies": { - "bson": "0.4.21", - "co": "4.6.0", - "es6-promise": "^3.0.2", - "mocha": "^2.4.5" - }, - "homepage": "https://github.com/christkv/require_optional", - "keywords": [ - "optional", - "require", - "optionalPeerDependencies" - ], - "license": "Apache-2.0", - "main": "index.js", - "name": "require_optional", - "peerOptionalDependencies": { - "co": ">=5.6.0", - "es6-promise": "^3.0.2", - "es6-promise2": "^4.0.2", - "bson": "0.4.21" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/christkv/require_optional.git" - }, - "scripts": { - "test": "mocha" - }, - "version": "1.0.1" -} diff --git a/scripts/2.5/node_modules/require_optional/test/nestedTest/index.js b/scripts/2.5/node_modules/require_optional/test/nestedTest/index.js deleted file mode 100644 index 76de2ab4..00000000 --- a/scripts/2.5/node_modules/require_optional/test/nestedTest/index.js +++ /dev/null @@ -1,8 +0,0 @@ -var require_optional = require('../../') - -function findPackage(packageName) { - var pkg = require_optional(packageName); - return pkg; -} - -module.exports.findPackage = findPackage diff --git a/scripts/2.5/node_modules/require_optional/test/nestedTest/package.json b/scripts/2.5/node_modules/require_optional/test/nestedTest/package.json deleted file mode 100644 index 4c456a6b..00000000 --- a/scripts/2.5/node_modules/require_optional/test/nestedTest/package.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "name": "nestedtest", - "version": "1.0.0", - "description": "A dummy package that facilitates testing that require_optional correctly walks up the module call stack", - "main": "index.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "author": "Sebastian Hallum Clarke", - "license": "ISC" -} diff --git a/scripts/2.5/node_modules/require_optional/test/require_optional_tests.js b/scripts/2.5/node_modules/require_optional/test/require_optional_tests.js deleted file mode 100644 index c9cc2a36..00000000 --- a/scripts/2.5/node_modules/require_optional/test/require_optional_tests.js +++ /dev/null @@ -1,59 +0,0 @@ -var assert = require('assert'), - require_optional = require('../'), - nestedTest = require('./nestedTest'); - -describe('Require Optional', function() { - describe('top level require', function() { - it('should correctly require co library', function() { - var promise = require_optional('es6-promise'); - assert.ok(promise); - }); - - it('should fail to require es6-promise library', function() { - try { - require_optional('co'); - } catch(e) { - assert.equal('OPTIONAL_MODULE_NOT_FOUND', e.code); - return; - } - - assert.ok(false); - }); - - it('should ignore optional library not defined', function() { - assert.equal(undefined, require_optional('es6-promise2')); - }); - }); - - describe('internal module file require', function() { - it('should correctly require co library', function() { - var Long = require_optional('bson/lib/bson/long.js'); - assert.ok(Long); - }); - }); - - describe('top level resolve', function() { - it('should correctly use exists method', function() { - assert.equal(false, require_optional.exists('co')); - assert.equal(true, require_optional.exists('es6-promise')); - assert.equal(true, require_optional.exists('bson/lib/bson/long.js')); - assert.equal(false, require_optional.exists('es6-promise2')); - }); - }); - - describe('require_optional inside dependencies', function() { - it('should correctly walk up module call stack searching for peerOptionalDependencies', function() { - assert.ok(nestedTest.findPackage('bson')) - }); - it('should return null when a package is defined in top-level package.json but not installed', function() { - assert.equal(null, nestedTest.findPackage('es6-promise2')) - }); - it('should error when searching for an optional dependency that is not defined in any ancestor package.json', function() { - try { - nestedTest.findPackage('bison') - } catch (err) { - assert.equal(err.message, 'no optional dependency [bison] defined in peerOptionalDependencies in any package.json') - } - }) - }); -}); diff --git a/scripts/2.5/node_modules/resolve-from/index.js b/scripts/2.5/node_modules/resolve-from/index.js deleted file mode 100644 index 434159f1..00000000 --- a/scripts/2.5/node_modules/resolve-from/index.js +++ /dev/null @@ -1,23 +0,0 @@ -'use strict'; -var path = require('path'); -var Module = require('module'); - -module.exports = function (fromDir, moduleId) { - if (typeof fromDir !== 'string' || typeof moduleId !== 'string') { - throw new TypeError('Expected `fromDir` and `moduleId` to be a string'); - } - - fromDir = path.resolve(fromDir); - - var fromFile = path.join(fromDir, 'noop.js'); - - try { - return Module._resolveFilename(moduleId, { - id: fromFile, - filename: fromFile, - paths: Module._nodeModulePaths(fromDir) - }); - } catch (err) { - return null; - } -}; diff --git a/scripts/2.5/node_modules/resolve-from/license b/scripts/2.5/node_modules/resolve-from/license deleted file mode 100644 index 654d0bfe..00000000 --- a/scripts/2.5/node_modules/resolve-from/license +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) Sindre Sorhus (sindresorhus.com) - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/scripts/2.5/node_modules/resolve-from/package.json b/scripts/2.5/node_modules/resolve-from/package.json deleted file mode 100644 index d0d20afd..00000000 --- a/scripts/2.5/node_modules/resolve-from/package.json +++ /dev/null @@ -1,66 +0,0 @@ -{ - "_from": "resolve-from@^2.0.0", - "_id": "resolve-from@2.0.0", - "_inBundle": false, - "_integrity": "sha1-lICrIOlP+h2egKgEx+oUdhGWa1c=", - "_location": "/resolve-from", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "resolve-from@^2.0.0", - "name": "resolve-from", - "escapedName": "resolve-from", - "rawSpec": "^2.0.0", - "saveSpec": null, - "fetchSpec": "^2.0.0" - }, - "_requiredBy": [ - "/require_optional" - ], - "_resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-2.0.0.tgz", - "_shasum": "9480ab20e94ffa1d9e80a804c7ea147611966b57", - "_spec": "resolve-from@^2.0.0", - "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/2.5/node_modules/require_optional", - "author": { - "name": "Sindre Sorhus", - "email": "sindresorhus@gmail.com", - "url": "sindresorhus.com" - }, - "bugs": { - "url": "https://github.com/sindresorhus/resolve-from/issues" - }, - "bundleDependencies": false, - "deprecated": false, - "description": "Resolve the path of a module like require.resolve() but from a given path", - "devDependencies": { - "ava": "*", - "xo": "*" - }, - "engines": { - "node": ">=0.10.0" - }, - "files": [ - "index.js" - ], - "homepage": "https://github.com/sindresorhus/resolve-from#readme", - "keywords": [ - "require", - "resolve", - "path", - "module", - "from", - "like", - "path" - ], - "license": "MIT", - "name": "resolve-from", - "repository": { - "type": "git", - "url": "git+https://github.com/sindresorhus/resolve-from.git" - }, - "scripts": { - "test": "xo && ava" - }, - "version": "2.0.0" -} diff --git a/scripts/2.5/node_modules/resolve-from/readme.md b/scripts/2.5/node_modules/resolve-from/readme.md deleted file mode 100644 index bb4ca91e..00000000 --- a/scripts/2.5/node_modules/resolve-from/readme.md +++ /dev/null @@ -1,58 +0,0 @@ -# resolve-from [![Build Status](https://travis-ci.org/sindresorhus/resolve-from.svg?branch=master)](https://travis-ci.org/sindresorhus/resolve-from) - -> Resolve the path of a module like [`require.resolve()`](http://nodejs.org/api/globals.html#globals_require_resolve) but from a given path - -Unlike `require.resolve()` it returns `null` instead of throwing when the module can't be found. - - -## Install - -``` -$ npm install --save resolve-from -``` - - -## Usage - -```js -const resolveFrom = require('resolve-from'); - -// there's a file at `./foo/bar.js` - -resolveFrom('foo', './bar'); -//=> '/Users/sindresorhus/dev/test/foo/bar.js' -``` - - -## API - -### resolveFrom(fromDir, moduleId) - -#### fromDir - -Type: `string` - -Directory to resolve from. - -#### moduleId - -Type: `string` - -What you would use in `require()`. - - -## Tip - -Create a partial using a bound function if you want to require from the same `fromDir` multiple times: - -```js -const resolveFromFoo = resolveFrom.bind(null, 'foo'); - -resolveFromFoo('./bar'); -resolveFromFoo('./baz'); -``` - - -## License - -MIT © [Sindre Sorhus](http://sindresorhus.com) diff --git a/scripts/2.5/node_modules/safe-buffer/LICENSE b/scripts/2.5/node_modules/safe-buffer/LICENSE deleted file mode 100644 index 0c068cee..00000000 --- a/scripts/2.5/node_modules/safe-buffer/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) Feross Aboukhadijeh - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/scripts/2.5/node_modules/safe-buffer/README.md b/scripts/2.5/node_modules/safe-buffer/README.md deleted file mode 100644 index 356e3519..00000000 --- a/scripts/2.5/node_modules/safe-buffer/README.md +++ /dev/null @@ -1,586 +0,0 @@ -# safe-buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] - -[travis-image]: https://img.shields.io/travis/feross/safe-buffer/master.svg -[travis-url]: https://travis-ci.org/feross/safe-buffer -[npm-image]: https://img.shields.io/npm/v/safe-buffer.svg -[npm-url]: https://npmjs.org/package/safe-buffer -[downloads-image]: https://img.shields.io/npm/dm/safe-buffer.svg -[downloads-url]: https://npmjs.org/package/safe-buffer -[standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg -[standard-url]: https://standardjs.com - -#### Safer Node.js Buffer API - -**Use the new Node.js Buffer APIs (`Buffer.from`, `Buffer.alloc`, -`Buffer.allocUnsafe`, `Buffer.allocUnsafeSlow`) in all versions of Node.js.** - -**Uses the built-in implementation when available.** - -## install - -``` -npm install safe-buffer -``` - -[Get supported safe-buffer with the Tidelift Subscription](https://tidelift.com/subscription/pkg/npm-safe-buffer?utm_source=npm-safe-buffer&utm_medium=referral&utm_campaign=readme) - -## usage - -The goal of this package is to provide a safe replacement for the node.js `Buffer`. - -It's a drop-in replacement for `Buffer`. You can use it by adding one `require` line to -the top of your node.js modules: - -```js -var Buffer = require('safe-buffer').Buffer - -// Existing buffer code will continue to work without issues: - -new Buffer('hey', 'utf8') -new Buffer([1, 2, 3], 'utf8') -new Buffer(obj) -new Buffer(16) // create an uninitialized buffer (potentially unsafe) - -// But you can use these new explicit APIs to make clear what you want: - -Buffer.from('hey', 'utf8') // convert from many types to a Buffer -Buffer.alloc(16) // create a zero-filled buffer (safe) -Buffer.allocUnsafe(16) // create an uninitialized buffer (potentially unsafe) -``` - -## api - -### Class Method: Buffer.from(array) - - -* `array` {Array} - -Allocates a new `Buffer` using an `array` of octets. - -```js -const buf = Buffer.from([0x62,0x75,0x66,0x66,0x65,0x72]); - // creates a new Buffer containing ASCII bytes - // ['b','u','f','f','e','r'] -``` - -A `TypeError` will be thrown if `array` is not an `Array`. - -### Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]]) - - -* `arrayBuffer` {ArrayBuffer} The `.buffer` property of a `TypedArray` or - a `new ArrayBuffer()` -* `byteOffset` {Number} Default: `0` -* `length` {Number} Default: `arrayBuffer.length - byteOffset` - -When passed a reference to the `.buffer` property of a `TypedArray` instance, -the newly created `Buffer` will share the same allocated memory as the -TypedArray. - -```js -const arr = new Uint16Array(2); -arr[0] = 5000; -arr[1] = 4000; - -const buf = Buffer.from(arr.buffer); // shares the memory with arr; - -console.log(buf); - // Prints: - -// changing the TypedArray changes the Buffer also -arr[1] = 6000; - -console.log(buf); - // Prints: -``` - -The optional `byteOffset` and `length` arguments specify a memory range within -the `arrayBuffer` that will be shared by the `Buffer`. - -```js -const ab = new ArrayBuffer(10); -const buf = Buffer.from(ab, 0, 2); -console.log(buf.length); - // Prints: 2 -``` - -A `TypeError` will be thrown if `arrayBuffer` is not an `ArrayBuffer`. - -### Class Method: Buffer.from(buffer) - - -* `buffer` {Buffer} - -Copies the passed `buffer` data onto a new `Buffer` instance. - -```js -const buf1 = Buffer.from('buffer'); -const buf2 = Buffer.from(buf1); - -buf1[0] = 0x61; -console.log(buf1.toString()); - // 'auffer' -console.log(buf2.toString()); - // 'buffer' (copy is not changed) -``` - -A `TypeError` will be thrown if `buffer` is not a `Buffer`. - -### Class Method: Buffer.from(str[, encoding]) - - -* `str` {String} String to encode. -* `encoding` {String} Encoding to use, Default: `'utf8'` - -Creates a new `Buffer` containing the given JavaScript string `str`. If -provided, the `encoding` parameter identifies the character encoding. -If not provided, `encoding` defaults to `'utf8'`. - -```js -const buf1 = Buffer.from('this is a tést'); -console.log(buf1.toString()); - // prints: this is a tést -console.log(buf1.toString('ascii')); - // prints: this is a tC)st - -const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex'); -console.log(buf2.toString()); - // prints: this is a tést -``` - -A `TypeError` will be thrown if `str` is not a string. - -### Class Method: Buffer.alloc(size[, fill[, encoding]]) - - -* `size` {Number} -* `fill` {Value} Default: `undefined` -* `encoding` {String} Default: `utf8` - -Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the -`Buffer` will be *zero-filled*. - -```js -const buf = Buffer.alloc(5); -console.log(buf); - // -``` - -The `size` must be less than or equal to the value of -`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is -`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will -be created if a `size` less than or equal to 0 is specified. - -If `fill` is specified, the allocated `Buffer` will be initialized by calling -`buf.fill(fill)`. See [`buf.fill()`][] for more information. - -```js -const buf = Buffer.alloc(5, 'a'); -console.log(buf); - // -``` - -If both `fill` and `encoding` are specified, the allocated `Buffer` will be -initialized by calling `buf.fill(fill, encoding)`. For example: - -```js -const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); -console.log(buf); - // -``` - -Calling `Buffer.alloc(size)` can be significantly slower than the alternative -`Buffer.allocUnsafe(size)` but ensures that the newly created `Buffer` instance -contents will *never contain sensitive data*. - -A `TypeError` will be thrown if `size` is not a number. - -### Class Method: Buffer.allocUnsafe(size) - - -* `size` {Number} - -Allocates a new *non-zero-filled* `Buffer` of `size` bytes. The `size` must -be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit -architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is -thrown. A zero-length Buffer will be created if a `size` less than or equal to -0 is specified. - -The underlying memory for `Buffer` instances created in this way is *not -initialized*. The contents of the newly created `Buffer` are unknown and -*may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such -`Buffer` instances to zeroes. - -```js -const buf = Buffer.allocUnsafe(5); -console.log(buf); - // - // (octets will be different, every time) -buf.fill(0); -console.log(buf); - // -``` - -A `TypeError` will be thrown if `size` is not a number. - -Note that the `Buffer` module pre-allocates an internal `Buffer` instance of -size `Buffer.poolSize` that is used as a pool for the fast allocation of new -`Buffer` instances created using `Buffer.allocUnsafe(size)` (and the deprecated -`new Buffer(size)` constructor) only when `size` is less than or equal to -`Buffer.poolSize >> 1` (floor of `Buffer.poolSize` divided by two). The default -value of `Buffer.poolSize` is `8192` but can be modified. - -Use of this pre-allocated internal memory pool is a key difference between -calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`. -Specifically, `Buffer.alloc(size, fill)` will *never* use the internal Buffer -pool, while `Buffer.allocUnsafe(size).fill(fill)` *will* use the internal -Buffer pool if `size` is less than or equal to half `Buffer.poolSize`. The -difference is subtle but can be important when an application requires the -additional performance that `Buffer.allocUnsafe(size)` provides. - -### Class Method: Buffer.allocUnsafeSlow(size) - - -* `size` {Number} - -Allocates a new *non-zero-filled* and non-pooled `Buffer` of `size` bytes. The -`size` must be less than or equal to the value of -`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is -`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will -be created if a `size` less than or equal to 0 is specified. - -The underlying memory for `Buffer` instances created in this way is *not -initialized*. The contents of the newly created `Buffer` are unknown and -*may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such -`Buffer` instances to zeroes. - -When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances, -allocations under 4KB are, by default, sliced from a single pre-allocated -`Buffer`. This allows applications to avoid the garbage collection overhead of -creating many individually allocated Buffers. This approach improves both -performance and memory usage by eliminating the need to track and cleanup as -many `Persistent` objects. - -However, in the case where a developer may need to retain a small chunk of -memory from a pool for an indeterminate amount of time, it may be appropriate -to create an un-pooled Buffer instance using `Buffer.allocUnsafeSlow()` then -copy out the relevant bits. - -```js -// need to keep around a few small chunks of memory -const store = []; - -socket.on('readable', () => { - const data = socket.read(); - // allocate for retained data - const sb = Buffer.allocUnsafeSlow(10); - // copy the data into the new allocation - data.copy(sb, 0, 0, 10); - store.push(sb); -}); -``` - -Use of `Buffer.allocUnsafeSlow()` should be used only as a last resort *after* -a developer has observed undue memory retention in their applications. - -A `TypeError` will be thrown if `size` is not a number. - -### All the Rest - -The rest of the `Buffer` API is exactly the same as in node.js. -[See the docs](https://nodejs.org/api/buffer.html). - - -## Related links - -- [Node.js issue: Buffer(number) is unsafe](https://github.com/nodejs/node/issues/4660) -- [Node.js Enhancement Proposal: Buffer.from/Buffer.alloc/Buffer.zalloc/Buffer() soft-deprecate](https://github.com/nodejs/node-eps/pull/4) - -## Why is `Buffer` unsafe? - -Today, the node.js `Buffer` constructor is overloaded to handle many different argument -types like `String`, `Array`, `Object`, `TypedArrayView` (`Uint8Array`, etc.), -`ArrayBuffer`, and also `Number`. - -The API is optimized for convenience: you can throw any type at it, and it will try to do -what you want. - -Because the Buffer constructor is so powerful, you often see code like this: - -```js -// Convert UTF-8 strings to hex -function toHex (str) { - return new Buffer(str).toString('hex') -} -``` - -***But what happens if `toHex` is called with a `Number` argument?*** - -### Remote Memory Disclosure - -If an attacker can make your program call the `Buffer` constructor with a `Number` -argument, then they can make it allocate uninitialized memory from the node.js process. -This could potentially disclose TLS private keys, user data, or database passwords. - -When the `Buffer` constructor is passed a `Number` argument, it returns an -**UNINITIALIZED** block of memory of the specified `size`. When you create a `Buffer` like -this, you **MUST** overwrite the contents before returning it to the user. - -From the [node.js docs](https://nodejs.org/api/buffer.html#buffer_new_buffer_size): - -> `new Buffer(size)` -> -> - `size` Number -> -> The underlying memory for `Buffer` instances created in this way is not initialized. -> **The contents of a newly created `Buffer` are unknown and could contain sensitive -> data.** Use `buf.fill(0)` to initialize a Buffer to zeroes. - -(Emphasis our own.) - -Whenever the programmer intended to create an uninitialized `Buffer` you often see code -like this: - -```js -var buf = new Buffer(16) - -// Immediately overwrite the uninitialized buffer with data from another buffer -for (var i = 0; i < buf.length; i++) { - buf[i] = otherBuf[i] -} -``` - - -### Would this ever be a problem in real code? - -Yes. It's surprisingly common to forget to check the type of your variables in a -dynamically-typed language like JavaScript. - -Usually the consequences of assuming the wrong type is that your program crashes with an -uncaught exception. But the failure mode for forgetting to check the type of arguments to -the `Buffer` constructor is more catastrophic. - -Here's an example of a vulnerable service that takes a JSON payload and converts it to -hex: - -```js -// Take a JSON payload {str: "some string"} and convert it to hex -var server = http.createServer(function (req, res) { - var data = '' - req.setEncoding('utf8') - req.on('data', function (chunk) { - data += chunk - }) - req.on('end', function () { - var body = JSON.parse(data) - res.end(new Buffer(body.str).toString('hex')) - }) -}) - -server.listen(8080) -``` - -In this example, an http client just has to send: - -```json -{ - "str": 1000 -} -``` - -and it will get back 1,000 bytes of uninitialized memory from the server. - -This is a very serious bug. It's similar in severity to the -[the Heartbleed bug](http://heartbleed.com/) that allowed disclosure of OpenSSL process -memory by remote attackers. - - -### Which real-world packages were vulnerable? - -#### [`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht) - -[Mathias Buus](https://github.com/mafintosh) and I -([Feross Aboukhadijeh](http://feross.org/)) found this issue in one of our own packages, -[`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht). The bug would allow -anyone on the internet to send a series of messages to a user of `bittorrent-dht` and get -them to reveal 20 bytes at a time of uninitialized memory from the node.js process. - -Here's -[the commit](https://github.com/feross/bittorrent-dht/commit/6c7da04025d5633699800a99ec3fbadf70ad35b8) -that fixed it. We released a new fixed version, created a -[Node Security Project disclosure](https://nodesecurity.io/advisories/68), and deprecated all -vulnerable versions on npm so users will get a warning to upgrade to a newer version. - -#### [`ws`](https://www.npmjs.com/package/ws) - -That got us wondering if there were other vulnerable packages. Sure enough, within a short -period of time, we found the same issue in [`ws`](https://www.npmjs.com/package/ws), the -most popular WebSocket implementation in node.js. - -If certain APIs were called with `Number` parameters instead of `String` or `Buffer` as -expected, then uninitialized server memory would be disclosed to the remote peer. - -These were the vulnerable methods: - -```js -socket.send(number) -socket.ping(number) -socket.pong(number) -``` - -Here's a vulnerable socket server with some echo functionality: - -```js -server.on('connection', function (socket) { - socket.on('message', function (message) { - message = JSON.parse(message) - if (message.type === 'echo') { - socket.send(message.data) // send back the user's message - } - }) -}) -``` - -`socket.send(number)` called on the server, will disclose server memory. - -Here's [the release](https://github.com/websockets/ws/releases/tag/1.0.1) where the issue -was fixed, with a more detailed explanation. Props to -[Arnout Kazemier](https://github.com/3rd-Eden) for the quick fix. Here's the -[Node Security Project disclosure](https://nodesecurity.io/advisories/67). - - -### What's the solution? - -It's important that node.js offers a fast way to get memory otherwise performance-critical -applications would needlessly get a lot slower. - -But we need a better way to *signal our intent* as programmers. **When we want -uninitialized memory, we should request it explicitly.** - -Sensitive functionality should not be packed into a developer-friendly API that loosely -accepts many different types. This type of API encourages the lazy practice of passing -variables in without checking the type very carefully. - -#### A new API: `Buffer.allocUnsafe(number)` - -The functionality of creating buffers with uninitialized memory should be part of another -API. We propose `Buffer.allocUnsafe(number)`. This way, it's not part of an API that -frequently gets user input of all sorts of different types passed into it. - -```js -var buf = Buffer.allocUnsafe(16) // careful, uninitialized memory! - -// Immediately overwrite the uninitialized buffer with data from another buffer -for (var i = 0; i < buf.length; i++) { - buf[i] = otherBuf[i] -} -``` - - -### How do we fix node.js core? - -We sent [a PR to node.js core](https://github.com/nodejs/node/pull/4514) (merged as -`semver-major`) which defends against one case: - -```js -var str = 16 -new Buffer(str, 'utf8') -``` - -In this situation, it's implied that the programmer intended the first argument to be a -string, since they passed an encoding as a second argument. Today, node.js will allocate -uninitialized memory in the case of `new Buffer(number, encoding)`, which is probably not -what the programmer intended. - -But this is only a partial solution, since if the programmer does `new Buffer(variable)` -(without an `encoding` parameter) there's no way to know what they intended. If `variable` -is sometimes a number, then uninitialized memory will sometimes be returned. - -### What's the real long-term fix? - -We could deprecate and remove `new Buffer(number)` and use `Buffer.allocUnsafe(number)` when -we need uninitialized memory. But that would break 1000s of packages. - -~~We believe the best solution is to:~~ - -~~1. Change `new Buffer(number)` to return safe, zeroed-out memory~~ - -~~2. Create a new API for creating uninitialized Buffers. We propose: `Buffer.allocUnsafe(number)`~~ - -#### Update - -We now support adding three new APIs: - -- `Buffer.from(value)` - convert from any type to a buffer -- `Buffer.alloc(size)` - create a zero-filled buffer -- `Buffer.allocUnsafe(size)` - create an uninitialized buffer with given size - -This solves the core problem that affected `ws` and `bittorrent-dht` which is -`Buffer(variable)` getting tricked into taking a number argument. - -This way, existing code continues working and the impact on the npm ecosystem will be -minimal. Over time, npm maintainers can migrate performance-critical code to use -`Buffer.allocUnsafe(number)` instead of `new Buffer(number)`. - - -### Conclusion - -We think there's a serious design issue with the `Buffer` API as it exists today. It -promotes insecure software by putting high-risk functionality into a convenient API -with friendly "developer ergonomics". - -This wasn't merely a theoretical exercise because we found the issue in some of the -most popular npm packages. - -Fortunately, there's an easy fix that can be applied today. Use `safe-buffer` in place of -`buffer`. - -```js -var Buffer = require('safe-buffer').Buffer -``` - -Eventually, we hope that node.js core can switch to this new, safer behavior. We believe -the impact on the ecosystem would be minimal since it's not a breaking change. -Well-maintained, popular packages would be updated to use `Buffer.alloc` quickly, while -older, insecure packages would magically become safe from this attack vector. - - -## links - -- [Node.js PR: buffer: throw if both length and enc are passed](https://github.com/nodejs/node/pull/4514) -- [Node Security Project disclosure for `ws`](https://nodesecurity.io/advisories/67) -- [Node Security Project disclosure for`bittorrent-dht`](https://nodesecurity.io/advisories/68) - - -## credit - -The original issues in `bittorrent-dht` -([disclosure](https://nodesecurity.io/advisories/68)) and -`ws` ([disclosure](https://nodesecurity.io/advisories/67)) were discovered by -[Mathias Buus](https://github.com/mafintosh) and -[Feross Aboukhadijeh](http://feross.org/). - -Thanks to [Adam Baldwin](https://github.com/evilpacket) for helping disclose these issues -and for his work running the [Node Security Project](https://nodesecurity.io/). - -Thanks to [John Hiesey](https://github.com/jhiesey) for proofreading this README and -auditing the code. - - -## license - -MIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org) diff --git a/scripts/2.5/node_modules/safe-buffer/index.d.ts b/scripts/2.5/node_modules/safe-buffer/index.d.ts deleted file mode 100644 index e9fed809..00000000 --- a/scripts/2.5/node_modules/safe-buffer/index.d.ts +++ /dev/null @@ -1,187 +0,0 @@ -declare module "safe-buffer" { - export class Buffer { - length: number - write(string: string, offset?: number, length?: number, encoding?: string): number; - toString(encoding?: string, start?: number, end?: number): string; - toJSON(): { type: 'Buffer', data: any[] }; - equals(otherBuffer: Buffer): boolean; - compare(otherBuffer: Buffer, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number; - copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; - slice(start?: number, end?: number): Buffer; - writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number; - readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number; - readIntLE(offset: number, byteLength: number, noAssert?: boolean): number; - readIntBE(offset: number, byteLength: number, noAssert?: boolean): number; - readUInt8(offset: number, noAssert?: boolean): number; - readUInt16LE(offset: number, noAssert?: boolean): number; - readUInt16BE(offset: number, noAssert?: boolean): number; - readUInt32LE(offset: number, noAssert?: boolean): number; - readUInt32BE(offset: number, noAssert?: boolean): number; - readInt8(offset: number, noAssert?: boolean): number; - readInt16LE(offset: number, noAssert?: boolean): number; - readInt16BE(offset: number, noAssert?: boolean): number; - readInt32LE(offset: number, noAssert?: boolean): number; - readInt32BE(offset: number, noAssert?: boolean): number; - readFloatLE(offset: number, noAssert?: boolean): number; - readFloatBE(offset: number, noAssert?: boolean): number; - readDoubleLE(offset: number, noAssert?: boolean): number; - readDoubleBE(offset: number, noAssert?: boolean): number; - swap16(): Buffer; - swap32(): Buffer; - swap64(): Buffer; - writeUInt8(value: number, offset: number, noAssert?: boolean): number; - writeUInt16LE(value: number, offset: number, noAssert?: boolean): number; - writeUInt16BE(value: number, offset: number, noAssert?: boolean): number; - writeUInt32LE(value: number, offset: number, noAssert?: boolean): number; - writeUInt32BE(value: number, offset: number, noAssert?: boolean): number; - writeInt8(value: number, offset: number, noAssert?: boolean): number; - writeInt16LE(value: number, offset: number, noAssert?: boolean): number; - writeInt16BE(value: number, offset: number, noAssert?: boolean): number; - writeInt32LE(value: number, offset: number, noAssert?: boolean): number; - writeInt32BE(value: number, offset: number, noAssert?: boolean): number; - writeFloatLE(value: number, offset: number, noAssert?: boolean): number; - writeFloatBE(value: number, offset: number, noAssert?: boolean): number; - writeDoubleLE(value: number, offset: number, noAssert?: boolean): number; - writeDoubleBE(value: number, offset: number, noAssert?: boolean): number; - fill(value: any, offset?: number, end?: number): this; - indexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; - lastIndexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; - includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean; - - /** - * Allocates a new buffer containing the given {str}. - * - * @param str String to store in buffer. - * @param encoding encoding to use, optional. Default is 'utf8' - */ - constructor (str: string, encoding?: string); - /** - * Allocates a new buffer of {size} octets. - * - * @param size count of octets to allocate. - */ - constructor (size: number); - /** - * Allocates a new buffer containing the given {array} of octets. - * - * @param array The octets to store. - */ - constructor (array: Uint8Array); - /** - * Produces a Buffer backed by the same allocated memory as - * the given {ArrayBuffer}. - * - * - * @param arrayBuffer The ArrayBuffer with which to share memory. - */ - constructor (arrayBuffer: ArrayBuffer); - /** - * Allocates a new buffer containing the given {array} of octets. - * - * @param array The octets to store. - */ - constructor (array: any[]); - /** - * Copies the passed {buffer} data onto a new {Buffer} instance. - * - * @param buffer The buffer to copy. - */ - constructor (buffer: Buffer); - prototype: Buffer; - /** - * Allocates a new Buffer using an {array} of octets. - * - * @param array - */ - static from(array: any[]): Buffer; - /** - * When passed a reference to the .buffer property of a TypedArray instance, - * the newly created Buffer will share the same allocated memory as the TypedArray. - * The optional {byteOffset} and {length} arguments specify a memory range - * within the {arrayBuffer} that will be shared by the Buffer. - * - * @param arrayBuffer The .buffer property of a TypedArray or a new ArrayBuffer() - * @param byteOffset - * @param length - */ - static from(arrayBuffer: ArrayBuffer, byteOffset?: number, length?: number): Buffer; - /** - * Copies the passed {buffer} data onto a new Buffer instance. - * - * @param buffer - */ - static from(buffer: Buffer): Buffer; - /** - * Creates a new Buffer containing the given JavaScript string {str}. - * If provided, the {encoding} parameter identifies the character encoding. - * If not provided, {encoding} defaults to 'utf8'. - * - * @param str - */ - static from(str: string, encoding?: string): Buffer; - /** - * Returns true if {obj} is a Buffer - * - * @param obj object to test. - */ - static isBuffer(obj: any): obj is Buffer; - /** - * Returns true if {encoding} is a valid encoding argument. - * Valid string encodings in Node 0.12: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' - * - * @param encoding string to test. - */ - static isEncoding(encoding: string): boolean; - /** - * Gives the actual byte length of a string. encoding defaults to 'utf8'. - * This is not the same as String.prototype.length since that returns the number of characters in a string. - * - * @param string string to test. - * @param encoding encoding used to evaluate (defaults to 'utf8') - */ - static byteLength(string: string, encoding?: string): number; - /** - * Returns a buffer which is the result of concatenating all the buffers in the list together. - * - * If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer. - * If the list has exactly one item, then the first item of the list is returned. - * If the list has more than one item, then a new Buffer is created. - * - * @param list An array of Buffer objects to concatenate - * @param totalLength Total length of the buffers when concatenated. - * If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly. - */ - static concat(list: Buffer[], totalLength?: number): Buffer; - /** - * The same as buf1.compare(buf2). - */ - static compare(buf1: Buffer, buf2: Buffer): number; - /** - * Allocates a new buffer of {size} octets. - * - * @param size count of octets to allocate. - * @param fill if specified, buffer will be initialized by calling buf.fill(fill). - * If parameter is omitted, buffer will be filled with zeros. - * @param encoding encoding used for call to buf.fill while initalizing - */ - static alloc(size: number, fill?: string | Buffer | number, encoding?: string): Buffer; - /** - * Allocates a new buffer of {size} octets, leaving memory not initialized, so the contents - * of the newly created Buffer are unknown and may contain sensitive data. - * - * @param size count of octets to allocate - */ - static allocUnsafe(size: number): Buffer; - /** - * Allocates a new non-pooled buffer of {size} octets, leaving memory not initialized, so the contents - * of the newly created Buffer are unknown and may contain sensitive data. - * - * @param size count of octets to allocate - */ - static allocUnsafeSlow(size: number): Buffer; - } -} \ No newline at end of file diff --git a/scripts/2.5/node_modules/safe-buffer/index.js b/scripts/2.5/node_modules/safe-buffer/index.js deleted file mode 100644 index 054c8d30..00000000 --- a/scripts/2.5/node_modules/safe-buffer/index.js +++ /dev/null @@ -1,64 +0,0 @@ -/* eslint-disable node/no-deprecated-api */ -var buffer = require('buffer') -var Buffer = buffer.Buffer - -// alternative to using Object.keys for old browsers -function copyProps (src, dst) { - for (var key in src) { - dst[key] = src[key] - } -} -if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { - module.exports = buffer -} else { - // Copy properties from require('buffer') - copyProps(buffer, exports) - exports.Buffer = SafeBuffer -} - -function SafeBuffer (arg, encodingOrOffset, length) { - return Buffer(arg, encodingOrOffset, length) -} - -SafeBuffer.prototype = Object.create(Buffer.prototype) - -// Copy static methods from Buffer -copyProps(Buffer, SafeBuffer) - -SafeBuffer.from = function (arg, encodingOrOffset, length) { - if (typeof arg === 'number') { - throw new TypeError('Argument must not be a number') - } - return Buffer(arg, encodingOrOffset, length) -} - -SafeBuffer.alloc = function (size, fill, encoding) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - var buf = Buffer(size) - if (fill !== undefined) { - if (typeof encoding === 'string') { - buf.fill(fill, encoding) - } else { - buf.fill(fill) - } - } else { - buf.fill(0) - } - return buf -} - -SafeBuffer.allocUnsafe = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - return Buffer(size) -} - -SafeBuffer.allocUnsafeSlow = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - return buffer.SlowBuffer(size) -} diff --git a/scripts/2.5/node_modules/safe-buffer/package.json b/scripts/2.5/node_modules/safe-buffer/package.json deleted file mode 100644 index b54facc5..00000000 --- a/scripts/2.5/node_modules/safe-buffer/package.json +++ /dev/null @@ -1,62 +0,0 @@ -{ - "_from": "safe-buffer@^5.1.2", - "_id": "safe-buffer@5.2.0", - "_inBundle": false, - "_integrity": "sha512-fZEwUGbVl7kouZs1jCdMLdt95hdIv0ZeHg6L7qPeciMZhZ+/gdesW4wgTARkrFWEpspjEATAzUGPG8N2jJiwbg==", - "_location": "/safe-buffer", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "safe-buffer@^5.1.2", - "name": "safe-buffer", - "escapedName": "safe-buffer", - "rawSpec": "^5.1.2", - "saveSpec": null, - "fetchSpec": "^5.1.2" - }, - "_requiredBy": [ - "/mongodb" - ], - "_resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.0.tgz", - "_shasum": "b74daec49b1148f88c64b68d49b1e815c1f2f519", - "_spec": "safe-buffer@^5.1.2", - "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/2.5/node_modules/mongodb", - "author": { - "name": "Feross Aboukhadijeh", - "email": "feross@feross.org", - "url": "http://feross.org" - }, - "bugs": { - "url": "https://github.com/feross/safe-buffer/issues" - }, - "bundleDependencies": false, - "deprecated": false, - "description": "Safer Node.js Buffer API", - "devDependencies": { - "standard": "*", - "tape": "^4.0.0" - }, - "homepage": "https://github.com/feross/safe-buffer", - "keywords": [ - "buffer", - "buffer allocate", - "node security", - "safe", - "safe-buffer", - "security", - "uninitialized" - ], - "license": "MIT", - "main": "index.js", - "name": "safe-buffer", - "repository": { - "type": "git", - "url": "git://github.com/feross/safe-buffer.git" - }, - "scripts": { - "test": "standard && tape test/*.js" - }, - "types": "index.d.ts", - "version": "5.2.0" -} diff --git a/scripts/2.5/node_modules/saslprep/.editorconfig b/scripts/2.5/node_modules/saslprep/.editorconfig deleted file mode 100644 index d1d8a417..00000000 --- a/scripts/2.5/node_modules/saslprep/.editorconfig +++ /dev/null @@ -1,10 +0,0 @@ -# http://editorconfig.org -root = true - -[*] -indent_style = space -indent_size = 2 -end_of_line = lf -charset = utf-8 -trim_trailing_whitespace = true -insert_final_newline = true diff --git a/scripts/2.5/node_modules/saslprep/.gitattributes b/scripts/2.5/node_modules/saslprep/.gitattributes deleted file mode 100644 index 3ba45360..00000000 --- a/scripts/2.5/node_modules/saslprep/.gitattributes +++ /dev/null @@ -1 +0,0 @@ -*.mem binary diff --git a/scripts/2.5/node_modules/saslprep/.travis.yml b/scripts/2.5/node_modules/saslprep/.travis.yml deleted file mode 100644 index 0bca8265..00000000 --- a/scripts/2.5/node_modules/saslprep/.travis.yml +++ /dev/null @@ -1,10 +0,0 @@ -sudo: false -language: node_js -node_js: - - "6" - - "8" - - "10" - - "12" - -before_install: -- npm install -g npm@6 diff --git a/scripts/2.5/node_modules/saslprep/CHANGELOG.md b/scripts/2.5/node_modules/saslprep/CHANGELOG.md deleted file mode 100644 index 77980787..00000000 --- a/scripts/2.5/node_modules/saslprep/CHANGELOG.md +++ /dev/null @@ -1,19 +0,0 @@ -# Change Log -All notable changes to the "saslprep" package will be documented in this file. - -## [1.0.3] - 2019-05-01 - -- Correctly get code points >U+FFFF ([#5](https://github.com/reklatsmasters/saslprep/pull/5)) -- Fix perfomance downgrades from [#5](https://github.com/reklatsmasters/saslprep/pull/5). - -## [1.0.2] - 2018-09-13 - -- Reduced initialization time ([#3](https://github.com/reklatsmasters/saslprep/issues/3)) - -## [1.0.1] - 2018-06-20 - -- Reduced stack overhead of range creation ([#2](https://github.com/reklatsmasters/saslprep/pull/2)) - -## [1.0.0] - 2017-06-21 - -- First release diff --git a/scripts/2.5/node_modules/saslprep/LICENSE b/scripts/2.5/node_modules/saslprep/LICENSE deleted file mode 100644 index 481c7a50..00000000 --- a/scripts/2.5/node_modules/saslprep/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -Copyright (c) 2014 Dmitry Tsvettsikh - -Permission is hereby granted, free of charge, to any person -obtaining a copy of this software and associated documentation -files (the "Software"), to deal in the Software without -restriction, including without limitation the rights to use, -copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the -Software is furnished to do so, subject to the following -conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/scripts/2.5/node_modules/saslprep/code-points.mem b/scripts/2.5/node_modules/saslprep/code-points.mem deleted file mode 100644 index 4781b066802688bdf954d2e89bcfac967db29c09..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 419864 zcmeI*O^9Si9RTop)4e+(t{DX(dsufSM8xBQfdsOo2lf&{@FWO&5cZ;Y@FWHe%nKV~ z@sxvzw;c53DIgdRk!c;t<{;##B4%51h#=^gL^8Y6+hx^z-92x{*9;3Umv`GA&vUy%enler!HTQKkA3&c=OSJMn7j|JGjl-d;Iey^#7>ZH0(RWYm^YJNA>kJ59aOu`p6X{MHRe9bu8cD2oYvN=9*ybv z%TyjdGTZ46aN&^<{xI6U)O2~U(!G+Yl0gPYRjbu8Wx~a<(#z+pIGvPkC#O7E&NgnV zIeue)&FW_ULfI&__U^^i@bTrer0O33=x2+%W4?Qo^)pjbsxinkv-K<<-Z9O6ZEyaQ zcB_@u#{%W}q9N0;ypzw%<*<}a^^Ob|R8?1xx0U*l{Mfi-J@SG5+xHJnzAqkVA73p) zfWWZ=`LSE4W4mY|K!5-N0t5&UATSizd-XW}{r>FO4Bx#OzCAE{nLD@VvjcA?1PBnA ze}O7c;{B8P-)Ji&@Gu01QMDYyI+%*sOCglv+~@Yqqm#Pz_SKwJ*n6ekt-IE7xb$i{ z#vJ7-%1?!2rG0Ri^X0*sx?FU--CIQw%Y*Zsb~)W#QAMFvj~+Qsr{Zh=QgU=xwFC$d zAV7cs0RjXF5FkK+009C72oNAZfB*pkrx2*aLB}2IZvhtFBipAEvDq7W9J^}&<>l~& z=Z6hT7u&hviF4icy{;$Z#$Rfh)bDEDcnTt22oNAJj{^NkPm$UP5FkK+009C72oNAZ zfB*pk1PBlya5e=N=WpRu-1tFH?r+Uep=aLS_2t}!1M%`E=_N&nH;IH{&FT4 zVA2E#5FkK+009C72oNAZfB*pk1PBlyK!5-N0tDtqVE;Gx53TDIQTIm zIQs(S*`MN>nqk~d)2W{+PVszkrlxK(QxGVpFoq#!SYT-_Rh1zb5B|v}x z0RjXF5FkK+009C72oNAZfB*pk1PBlyK!5;&ITaB9pVN)CECK`w5FkK+009C72oNAZ zfB*pk1PBlyK!5-N0t5&USSSJU|ApFaizPsS009C72oNAZfB*pk1PBlyK!5-N0t5&U zAV7csfjJcr|DV&1wJZVz2oNAZfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF5LhUI)_PiQ zY@~%+y~PqBK!5-N0t5&UAV7cs0RjXF5FkK+009C72oNAZfB=E{5NI_*|FQ%K5FkK+ z009C72oNAZfB*pk1PBlyK!5-N0t5&UAV7e?Yzp*ebJ}K2fB*pk1PBlyK!5-N0t5&U zAV7cs0RjXF5FkK+009C72s8ykSewfEzdsXvos!llv!K)XN+!bACMEW{kJW7s~i{EW^`xUX5|{=UXrRtoY&_gwz< zRvE$%TJf3i_%h&Xxb|Z>^W9wXR6Vl#j!mc_rtE>35?{Z6IbwcGK;>nSRoF zHt&;$O2P80zs-^hqp)?4qhw2`7#YP=_?Tw>wDeltgbe?$_^GM=@ z?HoDm9erzgM=HMNFC|BJRZD;X0RjXF5FkK+009C72oNAZfB*pk1PBlya0-DOe>pzY z-vZ3vILv9#>4l5=+gV#xaVim;YNYBg{{HIj=YJUg^!l*j-g~>b;hnpk&0)>Sr{)*n zj_ut&1&%HR2oRWKfn%Q^H4q>`fB*pk1PBlyK!5-N0t5&UAVA>E3Jm7>U0X{dK!5-N z0t5&U__zX7c= character.codePointAt(0); -const first = x => x[0]; -const last = x => x[x.length - 1]; - -/** - * Convert provided string into an array of Unicode Code Points. - * Based on https://stackoverflow.com/a/21409165/1556249 - * and https://www.npmjs.com/package/code-point-at. - * @param {string} input - * @returns {number[]} - */ -function toCodePoints(input) { - const codepoints = []; - const size = input.length; - - for (let i = 0; i < size; i += 1) { - const before = input.charCodeAt(i); - - if (before >= 0xd800 && before <= 0xdbff && size > i + 1) { - const next = input.charCodeAt(i + 1); - - if (next >= 0xdc00 && next <= 0xdfff) { - codepoints.push((before - 0xd800) * 0x400 + next - 0xdc00 + 0x10000); - i += 1; - continue; - } - } - - codepoints.push(before); - } - - return codepoints; -} - -/** - * SASLprep. - * @param {string} input - * @param {Object} opts - * @param {boolean} opts.allowUnassigned - * @returns {string} - */ -function saslprep(input, opts = {}) { - if (typeof input !== 'string') { - throw new TypeError('Expected string.'); - } - - if (input.length === 0) { - return ''; - } - - // 1. Map - const mapped_input = toCodePoints(input) - // 1.1 mapping to space - .map(character => (mapping2space.get(character) ? 0x20 : character)) - // 1.2 mapping to nothing - .filter(character => !mapping2nothing.get(character)); - - // 2. Normalize - const normalized_input = String.fromCodePoint - .apply(null, mapped_input) - .normalize('NFKC'); - - const normalized_map = toCodePoints(normalized_input); - - // 3. Prohibit - const hasProhibited = normalized_map.some(character => - prohibited_characters.get(character) - ); - - if (hasProhibited) { - throw new Error( - 'Prohibited character, see https://tools.ietf.org/html/rfc4013#section-2.3' - ); - } - - // Unassigned Code Points - if (opts.allowUnassigned !== true) { - const hasUnassigned = normalized_map.some(character => - unassigned_code_points.get(character) - ); - - if (hasUnassigned) { - throw new Error( - 'Unassigned code point, see https://tools.ietf.org/html/rfc4013#section-2.5' - ); - } - } - - // 4. check bidi - - const hasBidiRAL = normalized_map.some(character => - bidirectional_r_al.get(character) - ); - - const hasBidiL = normalized_map.some(character => - bidirectional_l.get(character) - ); - - // 4.1 If a string contains any RandALCat character, the string MUST NOT - // contain any LCat character. - if (hasBidiRAL && hasBidiL) { - throw new Error( - 'String must not contain RandALCat and LCat at the same time,' + - ' see https://tools.ietf.org/html/rfc3454#section-6' - ); - } - - /** - * 4.2 If a string contains any RandALCat character, a RandALCat - * character MUST be the first character of the string, and a - * RandALCat character MUST be the last character of the string. - */ - - const isFirstBidiRAL = bidirectional_r_al.get( - getCodePoint(first(normalized_input)) - ); - const isLastBidiRAL = bidirectional_r_al.get( - getCodePoint(last(normalized_input)) - ); - - if (hasBidiRAL && !(isFirstBidiRAL && isLastBidiRAL)) { - throw new Error( - 'Bidirectional RandALCat character must be the first and the last' + - ' character of the string, see https://tools.ietf.org/html/rfc3454#section-6' - ); - } - - return normalized_input; -} diff --git a/scripts/2.5/node_modules/saslprep/lib/code-points.js b/scripts/2.5/node_modules/saslprep/lib/code-points.js deleted file mode 100644 index 222182c8..00000000 --- a/scripts/2.5/node_modules/saslprep/lib/code-points.js +++ /dev/null @@ -1,996 +0,0 @@ -'use strict'; - -const { range } = require('./util'); - -/** - * A.1 Unassigned code points in Unicode 3.2 - * @link https://tools.ietf.org/html/rfc3454#appendix-A.1 - */ -const unassigned_code_points = new Set([ - 0x0221, - ...range(0x0234, 0x024f), - ...range(0x02ae, 0x02af), - ...range(0x02ef, 0x02ff), - ...range(0x0350, 0x035f), - ...range(0x0370, 0x0373), - ...range(0x0376, 0x0379), - ...range(0x037b, 0x037d), - ...range(0x037f, 0x0383), - 0x038b, - 0x038d, - 0x03a2, - 0x03cf, - ...range(0x03f7, 0x03ff), - 0x0487, - 0x04cf, - ...range(0x04f6, 0x04f7), - ...range(0x04fa, 0x04ff), - ...range(0x0510, 0x0530), - ...range(0x0557, 0x0558), - 0x0560, - 0x0588, - ...range(0x058b, 0x0590), - 0x05a2, - 0x05ba, - ...range(0x05c5, 0x05cf), - ...range(0x05eb, 0x05ef), - ...range(0x05f5, 0x060b), - ...range(0x060d, 0x061a), - ...range(0x061c, 0x061e), - 0x0620, - ...range(0x063b, 0x063f), - ...range(0x0656, 0x065f), - ...range(0x06ee, 0x06ef), - 0x06ff, - 0x070e, - ...range(0x072d, 0x072f), - ...range(0x074b, 0x077f), - ...range(0x07b2, 0x0900), - 0x0904, - ...range(0x093a, 0x093b), - ...range(0x094e, 0x094f), - ...range(0x0955, 0x0957), - ...range(0x0971, 0x0980), - 0x0984, - ...range(0x098d, 0x098e), - ...range(0x0991, 0x0992), - 0x09a9, - 0x09b1, - ...range(0x09b3, 0x09b5), - ...range(0x09ba, 0x09bb), - 0x09bd, - ...range(0x09c5, 0x09c6), - ...range(0x09c9, 0x09ca), - ...range(0x09ce, 0x09d6), - ...range(0x09d8, 0x09db), - 0x09de, - ...range(0x09e4, 0x09e5), - ...range(0x09fb, 0x0a01), - ...range(0x0a03, 0x0a04), - ...range(0x0a0b, 0x0a0e), - ...range(0x0a11, 0x0a12), - 0x0a29, - 0x0a31, - 0x0a34, - 0x0a37, - ...range(0x0a3a, 0x0a3b), - 0x0a3d, - ...range(0x0a43, 0x0a46), - ...range(0x0a49, 0x0a4a), - ...range(0x0a4e, 0x0a58), - 0x0a5d, - ...range(0x0a5f, 0x0a65), - ...range(0x0a75, 0x0a80), - 0x0a84, - 0x0a8c, - 0x0a8e, - 0x0a92, - 0x0aa9, - 0x0ab1, - 0x0ab4, - ...range(0x0aba, 0x0abb), - 0x0ac6, - 0x0aca, - ...range(0x0ace, 0x0acf), - ...range(0x0ad1, 0x0adf), - ...range(0x0ae1, 0x0ae5), - ...range(0x0af0, 0x0b00), - 0x0b04, - ...range(0x0b0d, 0x0b0e), - ...range(0x0b11, 0x0b12), - 0x0b29, - 0x0b31, - ...range(0x0b34, 0x0b35), - ...range(0x0b3a, 0x0b3b), - ...range(0x0b44, 0x0b46), - ...range(0x0b49, 0x0b4a), - ...range(0x0b4e, 0x0b55), - ...range(0x0b58, 0x0b5b), - 0x0b5e, - ...range(0x0b62, 0x0b65), - ...range(0x0b71, 0x0b81), - 0x0b84, - ...range(0x0b8b, 0x0b8d), - 0x0b91, - ...range(0x0b96, 0x0b98), - 0x0b9b, - 0x0b9d, - ...range(0x0ba0, 0x0ba2), - ...range(0x0ba5, 0x0ba7), - ...range(0x0bab, 0x0bad), - 0x0bb6, - ...range(0x0bba, 0x0bbd), - ...range(0x0bc3, 0x0bc5), - 0x0bc9, - ...range(0x0bce, 0x0bd6), - ...range(0x0bd8, 0x0be6), - ...range(0x0bf3, 0x0c00), - 0x0c04, - 0x0c0d, - 0x0c11, - 0x0c29, - 0x0c34, - ...range(0x0c3a, 0x0c3d), - 0x0c45, - 0x0c49, - ...range(0x0c4e, 0x0c54), - ...range(0x0c57, 0x0c5f), - ...range(0x0c62, 0x0c65), - ...range(0x0c70, 0x0c81), - 0x0c84, - 0x0c8d, - 0x0c91, - 0x0ca9, - 0x0cb4, - ...range(0x0cba, 0x0cbd), - 0x0cc5, - 0x0cc9, - ...range(0x0cce, 0x0cd4), - ...range(0x0cd7, 0x0cdd), - 0x0cdf, - ...range(0x0ce2, 0x0ce5), - ...range(0x0cf0, 0x0d01), - 0x0d04, - 0x0d0d, - 0x0d11, - 0x0d29, - ...range(0x0d3a, 0x0d3d), - ...range(0x0d44, 0x0d45), - 0x0d49, - ...range(0x0d4e, 0x0d56), - ...range(0x0d58, 0x0d5f), - ...range(0x0d62, 0x0d65), - ...range(0x0d70, 0x0d81), - 0x0d84, - ...range(0x0d97, 0x0d99), - 0x0db2, - 0x0dbc, - ...range(0x0dbe, 0x0dbf), - ...range(0x0dc7, 0x0dc9), - ...range(0x0dcb, 0x0dce), - 0x0dd5, - 0x0dd7, - ...range(0x0de0, 0x0df1), - ...range(0x0df5, 0x0e00), - ...range(0x0e3b, 0x0e3e), - ...range(0x0e5c, 0x0e80), - 0x0e83, - ...range(0x0e85, 0x0e86), - 0x0e89, - ...range(0x0e8b, 0x0e8c), - ...range(0x0e8e, 0x0e93), - 0x0e98, - 0x0ea0, - 0x0ea4, - 0x0ea6, - ...range(0x0ea8, 0x0ea9), - 0x0eac, - 0x0eba, - ...range(0x0ebe, 0x0ebf), - 0x0ec5, - 0x0ec7, - ...range(0x0ece, 0x0ecf), - ...range(0x0eda, 0x0edb), - ...range(0x0ede, 0x0eff), - 0x0f48, - ...range(0x0f6b, 0x0f70), - ...range(0x0f8c, 0x0f8f), - 0x0f98, - 0x0fbd, - ...range(0x0fcd, 0x0fce), - ...range(0x0fd0, 0x0fff), - 0x1022, - 0x1028, - 0x102b, - ...range(0x1033, 0x1035), - ...range(0x103a, 0x103f), - ...range(0x105a, 0x109f), - ...range(0x10c6, 0x10cf), - ...range(0x10f9, 0x10fa), - ...range(0x10fc, 0x10ff), - ...range(0x115a, 0x115e), - ...range(0x11a3, 0x11a7), - ...range(0x11fa, 0x11ff), - 0x1207, - 0x1247, - 0x1249, - ...range(0x124e, 0x124f), - 0x1257, - 0x1259, - ...range(0x125e, 0x125f), - 0x1287, - 0x1289, - ...range(0x128e, 0x128f), - 0x12af, - 0x12b1, - ...range(0x12b6, 0x12b7), - 0x12bf, - 0x12c1, - ...range(0x12c6, 0x12c7), - 0x12cf, - 0x12d7, - 0x12ef, - 0x130f, - 0x1311, - ...range(0x1316, 0x1317), - 0x131f, - 0x1347, - ...range(0x135b, 0x1360), - ...range(0x137d, 0x139f), - ...range(0x13f5, 0x1400), - ...range(0x1677, 0x167f), - ...range(0x169d, 0x169f), - ...range(0x16f1, 0x16ff), - 0x170d, - ...range(0x1715, 0x171f), - ...range(0x1737, 0x173f), - ...range(0x1754, 0x175f), - 0x176d, - 0x1771, - ...range(0x1774, 0x177f), - ...range(0x17dd, 0x17df), - ...range(0x17ea, 0x17ff), - 0x180f, - ...range(0x181a, 0x181f), - ...range(0x1878, 0x187f), - ...range(0x18aa, 0x1dff), - ...range(0x1e9c, 0x1e9f), - ...range(0x1efa, 0x1eff), - ...range(0x1f16, 0x1f17), - ...range(0x1f1e, 0x1f1f), - ...range(0x1f46, 0x1f47), - ...range(0x1f4e, 0x1f4f), - 0x1f58, - 0x1f5a, - 0x1f5c, - 0x1f5e, - ...range(0x1f7e, 0x1f7f), - 0x1fb5, - 0x1fc5, - ...range(0x1fd4, 0x1fd5), - 0x1fdc, - ...range(0x1ff0, 0x1ff1), - 0x1ff5, - 0x1fff, - ...range(0x2053, 0x2056), - ...range(0x2058, 0x205e), - ...range(0x2064, 0x2069), - ...range(0x2072, 0x2073), - ...range(0x208f, 0x209f), - ...range(0x20b2, 0x20cf), - ...range(0x20eb, 0x20ff), - ...range(0x213b, 0x213c), - ...range(0x214c, 0x2152), - ...range(0x2184, 0x218f), - ...range(0x23cf, 0x23ff), - ...range(0x2427, 0x243f), - ...range(0x244b, 0x245f), - 0x24ff, - ...range(0x2614, 0x2615), - 0x2618, - ...range(0x267e, 0x267f), - ...range(0x268a, 0x2700), - 0x2705, - ...range(0x270a, 0x270b), - 0x2728, - 0x274c, - 0x274e, - ...range(0x2753, 0x2755), - 0x2757, - ...range(0x275f, 0x2760), - ...range(0x2795, 0x2797), - 0x27b0, - ...range(0x27bf, 0x27cf), - ...range(0x27ec, 0x27ef), - ...range(0x2b00, 0x2e7f), - 0x2e9a, - ...range(0x2ef4, 0x2eff), - ...range(0x2fd6, 0x2fef), - ...range(0x2ffc, 0x2fff), - 0x3040, - ...range(0x3097, 0x3098), - ...range(0x3100, 0x3104), - ...range(0x312d, 0x3130), - 0x318f, - ...range(0x31b8, 0x31ef), - ...range(0x321d, 0x321f), - ...range(0x3244, 0x3250), - ...range(0x327c, 0x327e), - ...range(0x32cc, 0x32cf), - 0x32ff, - ...range(0x3377, 0x337a), - ...range(0x33de, 0x33df), - 0x33ff, - ...range(0x4db6, 0x4dff), - ...range(0x9fa6, 0x9fff), - ...range(0xa48d, 0xa48f), - ...range(0xa4c7, 0xabff), - ...range(0xd7a4, 0xd7ff), - ...range(0xfa2e, 0xfa2f), - ...range(0xfa6b, 0xfaff), - ...range(0xfb07, 0xfb12), - ...range(0xfb18, 0xfb1c), - 0xfb37, - 0xfb3d, - 0xfb3f, - 0xfb42, - 0xfb45, - ...range(0xfbb2, 0xfbd2), - ...range(0xfd40, 0xfd4f), - ...range(0xfd90, 0xfd91), - ...range(0xfdc8, 0xfdcf), - ...range(0xfdfd, 0xfdff), - ...range(0xfe10, 0xfe1f), - ...range(0xfe24, 0xfe2f), - ...range(0xfe47, 0xfe48), - 0xfe53, - 0xfe67, - ...range(0xfe6c, 0xfe6f), - 0xfe75, - ...range(0xfefd, 0xfefe), - 0xff00, - ...range(0xffbf, 0xffc1), - ...range(0xffc8, 0xffc9), - ...range(0xffd0, 0xffd1), - ...range(0xffd8, 0xffd9), - ...range(0xffdd, 0xffdf), - 0xffe7, - ...range(0xffef, 0xfff8), - ...range(0x10000, 0x102ff), - 0x1031f, - ...range(0x10324, 0x1032f), - ...range(0x1034b, 0x103ff), - ...range(0x10426, 0x10427), - ...range(0x1044e, 0x1cfff), - ...range(0x1d0f6, 0x1d0ff), - ...range(0x1d127, 0x1d129), - ...range(0x1d1de, 0x1d3ff), - 0x1d455, - 0x1d49d, - ...range(0x1d4a0, 0x1d4a1), - ...range(0x1d4a3, 0x1d4a4), - ...range(0x1d4a7, 0x1d4a8), - 0x1d4ad, - 0x1d4ba, - 0x1d4bc, - 0x1d4c1, - 0x1d4c4, - 0x1d506, - ...range(0x1d50b, 0x1d50c), - 0x1d515, - 0x1d51d, - 0x1d53a, - 0x1d53f, - 0x1d545, - ...range(0x1d547, 0x1d549), - 0x1d551, - ...range(0x1d6a4, 0x1d6a7), - ...range(0x1d7ca, 0x1d7cd), - ...range(0x1d800, 0x1fffd), - ...range(0x2a6d7, 0x2f7ff), - ...range(0x2fa1e, 0x2fffd), - ...range(0x30000, 0x3fffd), - ...range(0x40000, 0x4fffd), - ...range(0x50000, 0x5fffd), - ...range(0x60000, 0x6fffd), - ...range(0x70000, 0x7fffd), - ...range(0x80000, 0x8fffd), - ...range(0x90000, 0x9fffd), - ...range(0xa0000, 0xafffd), - ...range(0xb0000, 0xbfffd), - ...range(0xc0000, 0xcfffd), - ...range(0xd0000, 0xdfffd), - 0xe0000, - ...range(0xe0002, 0xe001f), - ...range(0xe0080, 0xefffd), -]); - -/** - * B.1 Commonly mapped to nothing - * @link https://tools.ietf.org/html/rfc3454#appendix-B.1 - */ -const commonly_mapped_to_nothing = new Set([ - 0x00ad, - 0x034f, - 0x1806, - 0x180b, - 0x180c, - 0x180d, - 0x200b, - 0x200c, - 0x200d, - 0x2060, - 0xfe00, - 0xfe01, - 0xfe02, - 0xfe03, - 0xfe04, - 0xfe05, - 0xfe06, - 0xfe07, - 0xfe08, - 0xfe09, - 0xfe0a, - 0xfe0b, - 0xfe0c, - 0xfe0d, - 0xfe0e, - 0xfe0f, - 0xfeff, -]); - -/** - * C.1.2 Non-ASCII space characters - * @link https://tools.ietf.org/html/rfc3454#appendix-C.1.2 - */ -const non_ASCII_space_characters = new Set([ - 0x00a0 /* NO-BREAK SPACE */, - 0x1680 /* OGHAM SPACE MARK */, - 0x2000 /* EN QUAD */, - 0x2001 /* EM QUAD */, - 0x2002 /* EN SPACE */, - 0x2003 /* EM SPACE */, - 0x2004 /* THREE-PER-EM SPACE */, - 0x2005 /* FOUR-PER-EM SPACE */, - 0x2006 /* SIX-PER-EM SPACE */, - 0x2007 /* FIGURE SPACE */, - 0x2008 /* PUNCTUATION SPACE */, - 0x2009 /* THIN SPACE */, - 0x200a /* HAIR SPACE */, - 0x200b /* ZERO WIDTH SPACE */, - 0x202f /* NARROW NO-BREAK SPACE */, - 0x205f /* MEDIUM MATHEMATICAL SPACE */, - 0x3000 /* IDEOGRAPHIC SPACE */, -]); - -/** - * 2.3. Prohibited Output - * @type {Set} - */ -const prohibited_characters = new Set([ - ...non_ASCII_space_characters, - - /** - * C.2.1 ASCII control characters - * @link https://tools.ietf.org/html/rfc3454#appendix-C.2.1 - */ - ...range(0, 0x001f) /* [CONTROL CHARACTERS] */, - 0x007f /* DELETE */, - - /** - * C.2.2 Non-ASCII control characters - * @link https://tools.ietf.org/html/rfc3454#appendix-C.2.2 - */ - ...range(0x0080, 0x009f) /* [CONTROL CHARACTERS] */, - 0x06dd /* ARABIC END OF AYAH */, - 0x070f /* SYRIAC ABBREVIATION MARK */, - 0x180e /* MONGOLIAN VOWEL SEPARATOR */, - 0x200c /* ZERO WIDTH NON-JOINER */, - 0x200d /* ZERO WIDTH JOINER */, - 0x2028 /* LINE SEPARATOR */, - 0x2029 /* PARAGRAPH SEPARATOR */, - 0x2060 /* WORD JOINER */, - 0x2061 /* FUNCTION APPLICATION */, - 0x2062 /* INVISIBLE TIMES */, - 0x2063 /* INVISIBLE SEPARATOR */, - ...range(0x206a, 0x206f) /* [CONTROL CHARACTERS] */, - 0xfeff /* ZERO WIDTH NO-BREAK SPACE */, - ...range(0xfff9, 0xfffc) /* [CONTROL CHARACTERS] */, - ...range(0x1d173, 0x1d17a) /* [MUSICAL CONTROL CHARACTERS] */, - - /** - * C.3 Private use - * @link https://tools.ietf.org/html/rfc3454#appendix-C.3 - */ - ...range(0xe000, 0xf8ff) /* [PRIVATE USE, PLANE 0] */, - ...range(0xf0000, 0xffffd) /* [PRIVATE USE, PLANE 15] */, - ...range(0x100000, 0x10fffd) /* [PRIVATE USE, PLANE 16] */, - - /** - * C.4 Non-character code points - * @link https://tools.ietf.org/html/rfc3454#appendix-C.4 - */ - ...range(0xfdd0, 0xfdef) /* [NONCHARACTER CODE POINTS] */, - ...range(0xfffe, 0xffff) /* [NONCHARACTER CODE POINTS] */, - ...range(0x1fffe, 0x1ffff) /* [NONCHARACTER CODE POINTS] */, - ...range(0x2fffe, 0x2ffff) /* [NONCHARACTER CODE POINTS] */, - ...range(0x3fffe, 0x3ffff) /* [NONCHARACTER CODE POINTS] */, - ...range(0x4fffe, 0x4ffff) /* [NONCHARACTER CODE POINTS] */, - ...range(0x5fffe, 0x5ffff) /* [NONCHARACTER CODE POINTS] */, - ...range(0x6fffe, 0x6ffff) /* [NONCHARACTER CODE POINTS] */, - ...range(0x7fffe, 0x7ffff) /* [NONCHARACTER CODE POINTS] */, - ...range(0x8fffe, 0x8ffff) /* [NONCHARACTER CODE POINTS] */, - ...range(0x9fffe, 0x9ffff) /* [NONCHARACTER CODE POINTS] */, - ...range(0xafffe, 0xaffff) /* [NONCHARACTER CODE POINTS] */, - ...range(0xbfffe, 0xbffff) /* [NONCHARACTER CODE POINTS] */, - ...range(0xcfffe, 0xcffff) /* [NONCHARACTER CODE POINTS] */, - ...range(0xdfffe, 0xdffff) /* [NONCHARACTER CODE POINTS] */, - ...range(0xefffe, 0xeffff) /* [NONCHARACTER CODE POINTS] */, - ...range(0x10fffe, 0x10ffff) /* [NONCHARACTER CODE POINTS] */, - - /** - * C.5 Surrogate codes - * @link https://tools.ietf.org/html/rfc3454#appendix-C.5 - */ - ...range(0xd800, 0xdfff), - - /** - * C.6 Inappropriate for plain text - * @link https://tools.ietf.org/html/rfc3454#appendix-C.6 - */ - 0xfff9 /* INTERLINEAR ANNOTATION ANCHOR */, - 0xfffa /* INTERLINEAR ANNOTATION SEPARATOR */, - 0xfffb /* INTERLINEAR ANNOTATION TERMINATOR */, - 0xfffc /* OBJECT REPLACEMENT CHARACTER */, - 0xfffd /* REPLACEMENT CHARACTER */, - - /** - * C.7 Inappropriate for canonical representation - * @link https://tools.ietf.org/html/rfc3454#appendix-C.7 - */ - ...range(0x2ff0, 0x2ffb) /* [IDEOGRAPHIC DESCRIPTION CHARACTERS] */, - - /** - * C.8 Change display properties or are deprecated - * @link https://tools.ietf.org/html/rfc3454#appendix-C.8 - */ - 0x0340 /* COMBINING GRAVE TONE MARK */, - 0x0341 /* COMBINING ACUTE TONE MARK */, - 0x200e /* LEFT-TO-RIGHT MARK */, - 0x200f /* RIGHT-TO-LEFT MARK */, - 0x202a /* LEFT-TO-RIGHT EMBEDDING */, - 0x202b /* RIGHT-TO-LEFT EMBEDDING */, - 0x202c /* POP DIRECTIONAL FORMATTING */, - 0x202d /* LEFT-TO-RIGHT OVERRIDE */, - 0x202e /* RIGHT-TO-LEFT OVERRIDE */, - 0x206a /* INHIBIT SYMMETRIC SWAPPING */, - 0x206b /* ACTIVATE SYMMETRIC SWAPPING */, - 0x206c /* INHIBIT ARABIC FORM SHAPING */, - 0x206d /* ACTIVATE ARABIC FORM SHAPING */, - 0x206e /* NATIONAL DIGIT SHAPES */, - 0x206f /* NOMINAL DIGIT SHAPES */, - - /** - * C.9 Tagging characters - * @link https://tools.ietf.org/html/rfc3454#appendix-C.9 - */ - 0xe0001 /* LANGUAGE TAG */, - ...range(0xe0020, 0xe007f) /* [TAGGING CHARACTERS] */, -]); - -/** - * D.1 Characters with bidirectional property "R" or "AL" - * @link https://tools.ietf.org/html/rfc3454#appendix-D.1 - */ -const bidirectional_r_al = new Set([ - 0x05be, - 0x05c0, - 0x05c3, - ...range(0x05d0, 0x05ea), - ...range(0x05f0, 0x05f4), - 0x061b, - 0x061f, - ...range(0x0621, 0x063a), - ...range(0x0640, 0x064a), - ...range(0x066d, 0x066f), - ...range(0x0671, 0x06d5), - 0x06dd, - ...range(0x06e5, 0x06e6), - ...range(0x06fa, 0x06fe), - ...range(0x0700, 0x070d), - 0x0710, - ...range(0x0712, 0x072c), - ...range(0x0780, 0x07a5), - 0x07b1, - 0x200f, - 0xfb1d, - ...range(0xfb1f, 0xfb28), - ...range(0xfb2a, 0xfb36), - ...range(0xfb38, 0xfb3c), - 0xfb3e, - ...range(0xfb40, 0xfb41), - ...range(0xfb43, 0xfb44), - ...range(0xfb46, 0xfbb1), - ...range(0xfbd3, 0xfd3d), - ...range(0xfd50, 0xfd8f), - ...range(0xfd92, 0xfdc7), - ...range(0xfdf0, 0xfdfc), - ...range(0xfe70, 0xfe74), - ...range(0xfe76, 0xfefc), -]); - -/** - * D.2 Characters with bidirectional property "L" - * @link https://tools.ietf.org/html/rfc3454#appendix-D.2 - */ -const bidirectional_l = new Set([ - ...range(0x0041, 0x005a), - ...range(0x0061, 0x007a), - 0x00aa, - 0x00b5, - 0x00ba, - ...range(0x00c0, 0x00d6), - ...range(0x00d8, 0x00f6), - ...range(0x00f8, 0x0220), - ...range(0x0222, 0x0233), - ...range(0x0250, 0x02ad), - ...range(0x02b0, 0x02b8), - ...range(0x02bb, 0x02c1), - ...range(0x02d0, 0x02d1), - ...range(0x02e0, 0x02e4), - 0x02ee, - 0x037a, - 0x0386, - ...range(0x0388, 0x038a), - 0x038c, - ...range(0x038e, 0x03a1), - ...range(0x03a3, 0x03ce), - ...range(0x03d0, 0x03f5), - ...range(0x0400, 0x0482), - ...range(0x048a, 0x04ce), - ...range(0x04d0, 0x04f5), - ...range(0x04f8, 0x04f9), - ...range(0x0500, 0x050f), - ...range(0x0531, 0x0556), - ...range(0x0559, 0x055f), - ...range(0x0561, 0x0587), - 0x0589, - 0x0903, - ...range(0x0905, 0x0939), - ...range(0x093d, 0x0940), - ...range(0x0949, 0x094c), - 0x0950, - ...range(0x0958, 0x0961), - ...range(0x0964, 0x0970), - ...range(0x0982, 0x0983), - ...range(0x0985, 0x098c), - ...range(0x098f, 0x0990), - ...range(0x0993, 0x09a8), - ...range(0x09aa, 0x09b0), - 0x09b2, - ...range(0x09b6, 0x09b9), - ...range(0x09be, 0x09c0), - ...range(0x09c7, 0x09c8), - ...range(0x09cb, 0x09cc), - 0x09d7, - ...range(0x09dc, 0x09dd), - ...range(0x09df, 0x09e1), - ...range(0x09e6, 0x09f1), - ...range(0x09f4, 0x09fa), - ...range(0x0a05, 0x0a0a), - ...range(0x0a0f, 0x0a10), - ...range(0x0a13, 0x0a28), - ...range(0x0a2a, 0x0a30), - ...range(0x0a32, 0x0a33), - ...range(0x0a35, 0x0a36), - ...range(0x0a38, 0x0a39), - ...range(0x0a3e, 0x0a40), - ...range(0x0a59, 0x0a5c), - 0x0a5e, - ...range(0x0a66, 0x0a6f), - ...range(0x0a72, 0x0a74), - 0x0a83, - ...range(0x0a85, 0x0a8b), - 0x0a8d, - ...range(0x0a8f, 0x0a91), - ...range(0x0a93, 0x0aa8), - ...range(0x0aaa, 0x0ab0), - ...range(0x0ab2, 0x0ab3), - ...range(0x0ab5, 0x0ab9), - ...range(0x0abd, 0x0ac0), - 0x0ac9, - ...range(0x0acb, 0x0acc), - 0x0ad0, - 0x0ae0, - ...range(0x0ae6, 0x0aef), - ...range(0x0b02, 0x0b03), - ...range(0x0b05, 0x0b0c), - ...range(0x0b0f, 0x0b10), - ...range(0x0b13, 0x0b28), - ...range(0x0b2a, 0x0b30), - ...range(0x0b32, 0x0b33), - ...range(0x0b36, 0x0b39), - ...range(0x0b3d, 0x0b3e), - 0x0b40, - ...range(0x0b47, 0x0b48), - ...range(0x0b4b, 0x0b4c), - 0x0b57, - ...range(0x0b5c, 0x0b5d), - ...range(0x0b5f, 0x0b61), - ...range(0x0b66, 0x0b70), - 0x0b83, - ...range(0x0b85, 0x0b8a), - ...range(0x0b8e, 0x0b90), - ...range(0x0b92, 0x0b95), - ...range(0x0b99, 0x0b9a), - 0x0b9c, - ...range(0x0b9e, 0x0b9f), - ...range(0x0ba3, 0x0ba4), - ...range(0x0ba8, 0x0baa), - ...range(0x0bae, 0x0bb5), - ...range(0x0bb7, 0x0bb9), - ...range(0x0bbe, 0x0bbf), - ...range(0x0bc1, 0x0bc2), - ...range(0x0bc6, 0x0bc8), - ...range(0x0bca, 0x0bcc), - 0x0bd7, - ...range(0x0be7, 0x0bf2), - ...range(0x0c01, 0x0c03), - ...range(0x0c05, 0x0c0c), - ...range(0x0c0e, 0x0c10), - ...range(0x0c12, 0x0c28), - ...range(0x0c2a, 0x0c33), - ...range(0x0c35, 0x0c39), - ...range(0x0c41, 0x0c44), - ...range(0x0c60, 0x0c61), - ...range(0x0c66, 0x0c6f), - ...range(0x0c82, 0x0c83), - ...range(0x0c85, 0x0c8c), - ...range(0x0c8e, 0x0c90), - ...range(0x0c92, 0x0ca8), - ...range(0x0caa, 0x0cb3), - ...range(0x0cb5, 0x0cb9), - 0x0cbe, - ...range(0x0cc0, 0x0cc4), - ...range(0x0cc7, 0x0cc8), - ...range(0x0cca, 0x0ccb), - ...range(0x0cd5, 0x0cd6), - 0x0cde, - ...range(0x0ce0, 0x0ce1), - ...range(0x0ce6, 0x0cef), - ...range(0x0d02, 0x0d03), - ...range(0x0d05, 0x0d0c), - ...range(0x0d0e, 0x0d10), - ...range(0x0d12, 0x0d28), - ...range(0x0d2a, 0x0d39), - ...range(0x0d3e, 0x0d40), - ...range(0x0d46, 0x0d48), - ...range(0x0d4a, 0x0d4c), - 0x0d57, - ...range(0x0d60, 0x0d61), - ...range(0x0d66, 0x0d6f), - ...range(0x0d82, 0x0d83), - ...range(0x0d85, 0x0d96), - ...range(0x0d9a, 0x0db1), - ...range(0x0db3, 0x0dbb), - 0x0dbd, - ...range(0x0dc0, 0x0dc6), - ...range(0x0dcf, 0x0dd1), - ...range(0x0dd8, 0x0ddf), - ...range(0x0df2, 0x0df4), - ...range(0x0e01, 0x0e30), - ...range(0x0e32, 0x0e33), - ...range(0x0e40, 0x0e46), - ...range(0x0e4f, 0x0e5b), - ...range(0x0e81, 0x0e82), - 0x0e84, - ...range(0x0e87, 0x0e88), - 0x0e8a, - 0x0e8d, - ...range(0x0e94, 0x0e97), - ...range(0x0e99, 0x0e9f), - ...range(0x0ea1, 0x0ea3), - 0x0ea5, - 0x0ea7, - ...range(0x0eaa, 0x0eab), - ...range(0x0ead, 0x0eb0), - ...range(0x0eb2, 0x0eb3), - 0x0ebd, - ...range(0x0ec0, 0x0ec4), - 0x0ec6, - ...range(0x0ed0, 0x0ed9), - ...range(0x0edc, 0x0edd), - ...range(0x0f00, 0x0f17), - ...range(0x0f1a, 0x0f34), - 0x0f36, - 0x0f38, - ...range(0x0f3e, 0x0f47), - ...range(0x0f49, 0x0f6a), - 0x0f7f, - 0x0f85, - ...range(0x0f88, 0x0f8b), - ...range(0x0fbe, 0x0fc5), - ...range(0x0fc7, 0x0fcc), - 0x0fcf, - ...range(0x1000, 0x1021), - ...range(0x1023, 0x1027), - ...range(0x1029, 0x102a), - 0x102c, - 0x1031, - 0x1038, - ...range(0x1040, 0x1057), - ...range(0x10a0, 0x10c5), - ...range(0x10d0, 0x10f8), - 0x10fb, - ...range(0x1100, 0x1159), - ...range(0x115f, 0x11a2), - ...range(0x11a8, 0x11f9), - ...range(0x1200, 0x1206), - ...range(0x1208, 0x1246), - 0x1248, - ...range(0x124a, 0x124d), - ...range(0x1250, 0x1256), - 0x1258, - ...range(0x125a, 0x125d), - ...range(0x1260, 0x1286), - 0x1288, - ...range(0x128a, 0x128d), - ...range(0x1290, 0x12ae), - 0x12b0, - ...range(0x12b2, 0x12b5), - ...range(0x12b8, 0x12be), - 0x12c0, - ...range(0x12c2, 0x12c5), - ...range(0x12c8, 0x12ce), - ...range(0x12d0, 0x12d6), - ...range(0x12d8, 0x12ee), - ...range(0x12f0, 0x130e), - 0x1310, - ...range(0x1312, 0x1315), - ...range(0x1318, 0x131e), - ...range(0x1320, 0x1346), - ...range(0x1348, 0x135a), - ...range(0x1361, 0x137c), - ...range(0x13a0, 0x13f4), - ...range(0x1401, 0x1676), - ...range(0x1681, 0x169a), - ...range(0x16a0, 0x16f0), - ...range(0x1700, 0x170c), - ...range(0x170e, 0x1711), - ...range(0x1720, 0x1731), - ...range(0x1735, 0x1736), - ...range(0x1740, 0x1751), - ...range(0x1760, 0x176c), - ...range(0x176e, 0x1770), - ...range(0x1780, 0x17b6), - ...range(0x17be, 0x17c5), - ...range(0x17c7, 0x17c8), - ...range(0x17d4, 0x17da), - 0x17dc, - ...range(0x17e0, 0x17e9), - ...range(0x1810, 0x1819), - ...range(0x1820, 0x1877), - ...range(0x1880, 0x18a8), - ...range(0x1e00, 0x1e9b), - ...range(0x1ea0, 0x1ef9), - ...range(0x1f00, 0x1f15), - ...range(0x1f18, 0x1f1d), - ...range(0x1f20, 0x1f45), - ...range(0x1f48, 0x1f4d), - ...range(0x1f50, 0x1f57), - 0x1f59, - 0x1f5b, - 0x1f5d, - ...range(0x1f5f, 0x1f7d), - ...range(0x1f80, 0x1fb4), - ...range(0x1fb6, 0x1fbc), - 0x1fbe, - ...range(0x1fc2, 0x1fc4), - ...range(0x1fc6, 0x1fcc), - ...range(0x1fd0, 0x1fd3), - ...range(0x1fd6, 0x1fdb), - ...range(0x1fe0, 0x1fec), - ...range(0x1ff2, 0x1ff4), - ...range(0x1ff6, 0x1ffc), - 0x200e, - 0x2071, - 0x207f, - 0x2102, - 0x2107, - ...range(0x210a, 0x2113), - 0x2115, - ...range(0x2119, 0x211d), - 0x2124, - 0x2126, - 0x2128, - ...range(0x212a, 0x212d), - ...range(0x212f, 0x2131), - ...range(0x2133, 0x2139), - ...range(0x213d, 0x213f), - ...range(0x2145, 0x2149), - ...range(0x2160, 0x2183), - ...range(0x2336, 0x237a), - 0x2395, - ...range(0x249c, 0x24e9), - ...range(0x3005, 0x3007), - ...range(0x3021, 0x3029), - ...range(0x3031, 0x3035), - ...range(0x3038, 0x303c), - ...range(0x3041, 0x3096), - ...range(0x309d, 0x309f), - ...range(0x30a1, 0x30fa), - ...range(0x30fc, 0x30ff), - ...range(0x3105, 0x312c), - ...range(0x3131, 0x318e), - ...range(0x3190, 0x31b7), - ...range(0x31f0, 0x321c), - ...range(0x3220, 0x3243), - ...range(0x3260, 0x327b), - ...range(0x327f, 0x32b0), - ...range(0x32c0, 0x32cb), - ...range(0x32d0, 0x32fe), - ...range(0x3300, 0x3376), - ...range(0x337b, 0x33dd), - ...range(0x33e0, 0x33fe), - ...range(0x3400, 0x4db5), - ...range(0x4e00, 0x9fa5), - ...range(0xa000, 0xa48c), - ...range(0xac00, 0xd7a3), - ...range(0xd800, 0xfa2d), - ...range(0xfa30, 0xfa6a), - ...range(0xfb00, 0xfb06), - ...range(0xfb13, 0xfb17), - ...range(0xff21, 0xff3a), - ...range(0xff41, 0xff5a), - ...range(0xff66, 0xffbe), - ...range(0xffc2, 0xffc7), - ...range(0xffca, 0xffcf), - ...range(0xffd2, 0xffd7), - ...range(0xffda, 0xffdc), - ...range(0x10300, 0x1031e), - ...range(0x10320, 0x10323), - ...range(0x10330, 0x1034a), - ...range(0x10400, 0x10425), - ...range(0x10428, 0x1044d), - ...range(0x1d000, 0x1d0f5), - ...range(0x1d100, 0x1d126), - ...range(0x1d12a, 0x1d166), - ...range(0x1d16a, 0x1d172), - ...range(0x1d183, 0x1d184), - ...range(0x1d18c, 0x1d1a9), - ...range(0x1d1ae, 0x1d1dd), - ...range(0x1d400, 0x1d454), - ...range(0x1d456, 0x1d49c), - ...range(0x1d49e, 0x1d49f), - 0x1d4a2, - ...range(0x1d4a5, 0x1d4a6), - ...range(0x1d4a9, 0x1d4ac), - ...range(0x1d4ae, 0x1d4b9), - 0x1d4bb, - ...range(0x1d4bd, 0x1d4c0), - ...range(0x1d4c2, 0x1d4c3), - ...range(0x1d4c5, 0x1d505), - ...range(0x1d507, 0x1d50a), - ...range(0x1d50d, 0x1d514), - ...range(0x1d516, 0x1d51c), - ...range(0x1d51e, 0x1d539), - ...range(0x1d53b, 0x1d53e), - ...range(0x1d540, 0x1d544), - 0x1d546, - ...range(0x1d54a, 0x1d550), - ...range(0x1d552, 0x1d6a3), - ...range(0x1d6a8, 0x1d7c9), - ...range(0x20000, 0x2a6d6), - ...range(0x2f800, 0x2fa1d), - ...range(0xf0000, 0xffffd), - ...range(0x100000, 0x10fffd), -]); - -module.exports = { - unassigned_code_points, - commonly_mapped_to_nothing, - non_ASCII_space_characters, - prohibited_characters, - bidirectional_r_al, - bidirectional_l, -}; diff --git a/scripts/2.5/node_modules/saslprep/lib/memory-code-points.js b/scripts/2.5/node_modules/saslprep/lib/memory-code-points.js deleted file mode 100644 index cb0289c8..00000000 --- a/scripts/2.5/node_modules/saslprep/lib/memory-code-points.js +++ /dev/null @@ -1,39 +0,0 @@ -'use strict'; - -const fs = require('fs'); -const path = require('path'); -const bitfield = require('sparse-bitfield'); - -/* eslint-disable-next-line security/detect-non-literal-fs-filename */ -const memory = fs.readFileSync(path.resolve(__dirname, '../code-points.mem')); -let offset = 0; - -/** - * Loads each code points sequence from buffer. - * @returns {bitfield} - */ -function read() { - const size = memory.readUInt32BE(offset); - offset += 4; - - const codepoints = memory.slice(offset, offset + size); - offset += size; - - return bitfield({ buffer: codepoints }); -} - -const unassigned_code_points = read(); -const commonly_mapped_to_nothing = read(); -const non_ASCII_space_characters = read(); -const prohibited_characters = read(); -const bidirectional_r_al = read(); -const bidirectional_l = read(); - -module.exports = { - unassigned_code_points, - commonly_mapped_to_nothing, - non_ASCII_space_characters, - prohibited_characters, - bidirectional_r_al, - bidirectional_l, -}; diff --git a/scripts/2.5/node_modules/saslprep/lib/util.js b/scripts/2.5/node_modules/saslprep/lib/util.js deleted file mode 100644 index 506bdc99..00000000 --- a/scripts/2.5/node_modules/saslprep/lib/util.js +++ /dev/null @@ -1,21 +0,0 @@ -'use strict'; - -/** - * Create an array of numbers. - * @param {number} from - * @param {number} to - * @returns {number[]} - */ -function range(from, to) { - // TODO: make this inlined. - const list = new Array(to - from + 1); - - for (let i = 0; i < list.length; i += 1) { - list[i] = from + i; - } - return list; -} - -module.exports = { - range, -}; diff --git a/scripts/2.5/node_modules/saslprep/package.json b/scripts/2.5/node_modules/saslprep/package.json deleted file mode 100644 index ab6adaf5..00000000 --- a/scripts/2.5/node_modules/saslprep/package.json +++ /dev/null @@ -1,100 +0,0 @@ -{ - "_from": "saslprep@^1.0.0", - "_id": "saslprep@1.0.3", - "_inBundle": false, - "_integrity": "sha512-/MY/PEMbk2SuY5sScONwhUDsV2p77Znkb/q3nSVstq/yQzYJOH/Azh29p9oJLsl3LnQwSvZDKagDGBsBwSooag==", - "_location": "/saslprep", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "saslprep@^1.0.0", - "name": "saslprep", - "escapedName": "saslprep", - "rawSpec": "^1.0.0", - "saveSpec": null, - "fetchSpec": "^1.0.0" - }, - "_requiredBy": [ - "/mongodb" - ], - "_resolved": "https://registry.npmjs.org/saslprep/-/saslprep-1.0.3.tgz", - "_shasum": "4c02f946b56cf54297e347ba1093e7acac4cf226", - "_spec": "saslprep@^1.0.0", - "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/2.5/node_modules/mongodb", - "author": { - "name": "Dmitry Tsvettsikh", - "email": "me@reklatsmasters.com" - }, - "bugs": { - "url": "https://github.com/reklatsmasters/saslprep/issues" - }, - "bundleDependencies": false, - "dependencies": { - "sparse-bitfield": "^3.0.3" - }, - "deprecated": false, - "description": "SASLprep: Stringprep Profile for User Names and Passwords, rfc4013.", - "devDependencies": { - "@nodertc/eslint-config": "^0.2.1", - "eslint": "^5.16.0", - "jest": "^23.6.0", - "prettier": "^1.14.3" - }, - "engines": { - "node": ">=6" - }, - "eslintConfig": { - "extends": "@nodertc", - "rules": { - "camelcase": "off", - "no-continue": "off" - }, - "overrides": [ - { - "files": [ - "test/*.js" - ], - "env": { - "jest": true - }, - "rules": { - "require-jsdoc": "off" - } - } - ] - }, - "homepage": "https://github.com/reklatsmasters/saslprep#readme", - "jest": { - "modulePaths": [ - "" - ], - "testMatch": [ - "**/test/*.js" - ], - "testPathIgnorePatterns": [ - "/node_modules/" - ] - }, - "keywords": [ - "sasl", - "saslprep", - "stringprep", - "rfc4013", - "4013" - ], - "license": "MIT", - "main": "index.js", - "name": "saslprep", - "repository": { - "type": "git", - "url": "git+https://github.com/reklatsmasters/saslprep.git" - }, - "scripts": { - "gen-code-points": "node generate-code-points.js > code-points.mem", - "lint": "npx eslint --quiet .", - "test": "npm run lint && npm run unit-test", - "unit-test": "npx jest" - }, - "version": "1.0.3" -} diff --git a/scripts/2.5/node_modules/saslprep/readme.md b/scripts/2.5/node_modules/saslprep/readme.md deleted file mode 100644 index 8ff3d70d..00000000 --- a/scripts/2.5/node_modules/saslprep/readme.md +++ /dev/null @@ -1,31 +0,0 @@ -# saslprep -[![Build Status](https://travis-ci.org/reklatsmasters/saslprep.svg?branch=master)](https://travis-ci.org/reklatsmasters/saslprep) -[![npm](https://img.shields.io/npm/v/saslprep.svg)](https://npmjs.org/package/saslprep) -[![node](https://img.shields.io/node/v/saslprep.svg)](https://npmjs.org/package/saslprep) -[![license](https://img.shields.io/npm/l/saslprep.svg)](https://npmjs.org/package/saslprep) -[![downloads](https://img.shields.io/npm/dm/saslprep.svg)](https://npmjs.org/package/saslprep) - -Stringprep Profile for User Names and Passwords, [rfc4013](https://tools.ietf.org/html/rfc4013) - -### Usage - -```js -const saslprep = require('saslprep') - -saslprep('password\u00AD') // password -saslprep('password\u0007') // Error: prohibited character -``` - -### API - -##### `saslprep(input: String, opts: Options): String` - -Normalize user name or password. - -##### `Options.allowUnassigned: bool` - -A special behavior for unassigned code points, see https://tools.ietf.org/html/rfc4013#section-2.5. Disabled by default. - -## License - -MIT, 2017-2019 (c) Dmitriy Tsvettsikh diff --git a/scripts/2.5/node_modules/saslprep/test/index.js b/scripts/2.5/node_modules/saslprep/test/index.js deleted file mode 100644 index 80c71af5..00000000 --- a/scripts/2.5/node_modules/saslprep/test/index.js +++ /dev/null @@ -1,76 +0,0 @@ -'use strict'; - -const saslprep = require('..'); - -const chr = String.fromCodePoint; - -test('should work with liatin letters', () => { - const str = 'user'; - expect(saslprep(str)).toEqual(str); -}); - -test('should work be case preserved', () => { - const str = 'USER'; - expect(saslprep(str)).toEqual(str); -}); - -test('should work with high code points (> U+FFFF)', () => { - const str = '\uD83D\uDE00'; - expect(saslprep(str, { allowUnassigned: true })).toEqual(str); -}); - -test('should remove `mapped to nothing` characters', () => { - expect(saslprep('I\u00ADX')).toEqual('IX'); -}); - -test('should replace `Non-ASCII space characters` with space', () => { - expect(saslprep('a\u00A0b')).toEqual('a\u0020b'); -}); - -test('should normalize as NFKC', () => { - expect(saslprep('\u00AA')).toEqual('a'); - expect(saslprep('\u2168')).toEqual('IX'); -}); - -test('should throws when prohibited characters', () => { - // C.2.1 ASCII control characters - expect(() => saslprep('a\u007Fb')).toThrow(); - - // C.2.2 Non-ASCII control characters - expect(() => saslprep('a\u06DDb')).toThrow(); - - // C.3 Private use - expect(() => saslprep('a\uE000b')).toThrow(); - - // C.4 Non-character code points - expect(() => saslprep(`a${chr(0x1fffe)}b`)).toThrow(); - - // C.5 Surrogate codes - expect(() => saslprep('a\uD800b')).toThrow(); - - // C.6 Inappropriate for plain text - expect(() => saslprep('a\uFFF9b')).toThrow(); - - // C.7 Inappropriate for canonical representation - expect(() => saslprep('a\u2FF0b')).toThrow(); - - // C.8 Change display properties or are deprecated - expect(() => saslprep('a\u200Eb')).toThrow(); - - // C.9 Tagging characters - expect(() => saslprep(`a${chr(0xe0001)}b`)).toThrow(); -}); - -test('should not containt RandALCat and LCat bidi', () => { - expect(() => saslprep('a\u06DD\u00AAb')).toThrow(); -}); - -test('RandALCat should be first and last', () => { - expect(() => saslprep('\u0627\u0031\u0628')).not.toThrow(); - expect(() => saslprep('\u0627\u0031')).toThrow(); -}); - -test('should handle unassigned code points', () => { - expect(() => saslprep('a\u0487')).toThrow(); - expect(() => saslprep('a\u0487', { allowUnassigned: true })).not.toThrow(); -}); diff --git a/scripts/2.5/node_modules/saslprep/test/util.js b/scripts/2.5/node_modules/saslprep/test/util.js deleted file mode 100644 index 355db3f8..00000000 --- a/scripts/2.5/node_modules/saslprep/test/util.js +++ /dev/null @@ -1,16 +0,0 @@ -'use strict'; - -const { setFlagsFromString } = require('v8'); -const { range } = require('../lib/util'); - -// 984 by default. -setFlagsFromString('--stack_size=500'); - -test('should work', () => { - const list = range(1, 3); - expect(list).toEqual([1, 2, 3]); -}); - -test('should work for large ranges', () => { - expect(() => range(1, 1e6)).not.toThrow(); -}); diff --git a/scripts/2.5/node_modules/semver/CHANGELOG.md b/scripts/2.5/node_modules/semver/CHANGELOG.md deleted file mode 100644 index 66304fdd..00000000 --- a/scripts/2.5/node_modules/semver/CHANGELOG.md +++ /dev/null @@ -1,39 +0,0 @@ -# changes log - -## 5.7 - -* Add `minVersion` method - -## 5.6 - -* Move boolean `loose` param to an options object, with - backwards-compatibility protection. -* Add ability to opt out of special prerelease version handling with - the `includePrerelease` option flag. - -## 5.5 - -* Add version coercion capabilities - -## 5.4 - -* Add intersection checking - -## 5.3 - -* Add `minSatisfying` method - -## 5.2 - -* Add `prerelease(v)` that returns prerelease components - -## 5.1 - -* Add Backus-Naur for ranges -* Remove excessively cute inspection methods - -## 5.0 - -* Remove AMD/Browserified build artifacts -* Fix ltr and gtr when using the `*` range -* Fix for range `*` with a prerelease identifier diff --git a/scripts/2.5/node_modules/semver/LICENSE b/scripts/2.5/node_modules/semver/LICENSE deleted file mode 100644 index 19129e31..00000000 --- a/scripts/2.5/node_modules/semver/LICENSE +++ /dev/null @@ -1,15 +0,0 @@ -The ISC License - -Copyright (c) Isaac Z. Schlueter and Contributors - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted, provided that the above -copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR -IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/scripts/2.5/node_modules/semver/README.md b/scripts/2.5/node_modules/semver/README.md deleted file mode 100644 index f8dfa5a0..00000000 --- a/scripts/2.5/node_modules/semver/README.md +++ /dev/null @@ -1,412 +0,0 @@ -semver(1) -- The semantic versioner for npm -=========================================== - -## Install - -```bash -npm install --save semver -```` - -## Usage - -As a node module: - -```js -const semver = require('semver') - -semver.valid('1.2.3') // '1.2.3' -semver.valid('a.b.c') // null -semver.clean(' =v1.2.3 ') // '1.2.3' -semver.satisfies('1.2.3', '1.x || >=2.5.0 || 5.0.0 - 7.2.3') // true -semver.gt('1.2.3', '9.8.7') // false -semver.lt('1.2.3', '9.8.7') // true -semver.minVersion('>=1.0.0') // '1.0.0' -semver.valid(semver.coerce('v2')) // '2.0.0' -semver.valid(semver.coerce('42.6.7.9.3-alpha')) // '42.6.7' -``` - -As a command-line utility: - -``` -$ semver -h - -A JavaScript implementation of the https://semver.org/ specification -Copyright Isaac Z. Schlueter - -Usage: semver [options] [ [...]] -Prints valid versions sorted by SemVer precedence - -Options: --r --range - Print versions that match the specified range. - --i --increment [] - Increment a version by the specified level. Level can - be one of: major, minor, patch, premajor, preminor, - prepatch, or prerelease. Default level is 'patch'. - Only one version may be specified. - ---preid - Identifier to be used to prefix premajor, preminor, - prepatch or prerelease version increments. - --l --loose - Interpret versions and ranges loosely - --p --include-prerelease - Always include prerelease versions in range matching - --c --coerce - Coerce a string into SemVer if possible - (does not imply --loose) - -Program exits successfully if any valid version satisfies -all supplied ranges, and prints all satisfying versions. - -If no satisfying versions are found, then exits failure. - -Versions are printed in ascending order, so supplying -multiple versions to the utility will just sort them. -``` - -## Versions - -A "version" is described by the `v2.0.0` specification found at -. - -A leading `"="` or `"v"` character is stripped off and ignored. - -## Ranges - -A `version range` is a set of `comparators` which specify versions -that satisfy the range. - -A `comparator` is composed of an `operator` and a `version`. The set -of primitive `operators` is: - -* `<` Less than -* `<=` Less than or equal to -* `>` Greater than -* `>=` Greater than or equal to -* `=` Equal. If no operator is specified, then equality is assumed, - so this operator is optional, but MAY be included. - -For example, the comparator `>=1.2.7` would match the versions -`1.2.7`, `1.2.8`, `2.5.3`, and `1.3.9`, but not the versions `1.2.6` -or `1.1.0`. - -Comparators can be joined by whitespace to form a `comparator set`, -which is satisfied by the **intersection** of all of the comparators -it includes. - -A range is composed of one or more comparator sets, joined by `||`. A -version matches a range if and only if every comparator in at least -one of the `||`-separated comparator sets is satisfied by the version. - -For example, the range `>=1.2.7 <1.3.0` would match the versions -`1.2.7`, `1.2.8`, and `1.2.99`, but not the versions `1.2.6`, `1.3.0`, -or `1.1.0`. - -The range `1.2.7 || >=1.2.9 <2.0.0` would match the versions `1.2.7`, -`1.2.9`, and `1.4.6`, but not the versions `1.2.8` or `2.0.0`. - -### Prerelease Tags - -If a version has a prerelease tag (for example, `1.2.3-alpha.3`) then -it will only be allowed to satisfy comparator sets if at least one -comparator with the same `[major, minor, patch]` tuple also has a -prerelease tag. - -For example, the range `>1.2.3-alpha.3` would be allowed to match the -version `1.2.3-alpha.7`, but it would *not* be satisfied by -`3.4.5-alpha.9`, even though `3.4.5-alpha.9` is technically "greater -than" `1.2.3-alpha.3` according to the SemVer sort rules. The version -range only accepts prerelease tags on the `1.2.3` version. The -version `3.4.5` *would* satisfy the range, because it does not have a -prerelease flag, and `3.4.5` is greater than `1.2.3-alpha.7`. - -The purpose for this behavior is twofold. First, prerelease versions -frequently are updated very quickly, and contain many breaking changes -that are (by the author's design) not yet fit for public consumption. -Therefore, by default, they are excluded from range matching -semantics. - -Second, a user who has opted into using a prerelease version has -clearly indicated the intent to use *that specific* set of -alpha/beta/rc versions. By including a prerelease tag in the range, -the user is indicating that they are aware of the risk. However, it -is still not appropriate to assume that they have opted into taking a -similar risk on the *next* set of prerelease versions. - -Note that this behavior can be suppressed (treating all prerelease -versions as if they were normal versions, for the purpose of range -matching) by setting the `includePrerelease` flag on the options -object to any -[functions](https://github.com/npm/node-semver#functions) that do -range matching. - -#### Prerelease Identifiers - -The method `.inc` takes an additional `identifier` string argument that -will append the value of the string as a prerelease identifier: - -```javascript -semver.inc('1.2.3', 'prerelease', 'beta') -// '1.2.4-beta.0' -``` - -command-line example: - -```bash -$ semver 1.2.3 -i prerelease --preid beta -1.2.4-beta.0 -``` - -Which then can be used to increment further: - -```bash -$ semver 1.2.4-beta.0 -i prerelease -1.2.4-beta.1 -``` - -### Advanced Range Syntax - -Advanced range syntax desugars to primitive comparators in -deterministic ways. - -Advanced ranges may be combined in the same way as primitive -comparators using white space or `||`. - -#### Hyphen Ranges `X.Y.Z - A.B.C` - -Specifies an inclusive set. - -* `1.2.3 - 2.3.4` := `>=1.2.3 <=2.3.4` - -If a partial version is provided as the first version in the inclusive -range, then the missing pieces are replaced with zeroes. - -* `1.2 - 2.3.4` := `>=1.2.0 <=2.3.4` - -If a partial version is provided as the second version in the -inclusive range, then all versions that start with the supplied parts -of the tuple are accepted, but nothing that would be greater than the -provided tuple parts. - -* `1.2.3 - 2.3` := `>=1.2.3 <2.4.0` -* `1.2.3 - 2` := `>=1.2.3 <3.0.0` - -#### X-Ranges `1.2.x` `1.X` `1.2.*` `*` - -Any of `X`, `x`, or `*` may be used to "stand in" for one of the -numeric values in the `[major, minor, patch]` tuple. - -* `*` := `>=0.0.0` (Any version satisfies) -* `1.x` := `>=1.0.0 <2.0.0` (Matching major version) -* `1.2.x` := `>=1.2.0 <1.3.0` (Matching major and minor versions) - -A partial version range is treated as an X-Range, so the special -character is in fact optional. - -* `""` (empty string) := `*` := `>=0.0.0` -* `1` := `1.x.x` := `>=1.0.0 <2.0.0` -* `1.2` := `1.2.x` := `>=1.2.0 <1.3.0` - -#### Tilde Ranges `~1.2.3` `~1.2` `~1` - -Allows patch-level changes if a minor version is specified on the -comparator. Allows minor-level changes if not. - -* `~1.2.3` := `>=1.2.3 <1.(2+1).0` := `>=1.2.3 <1.3.0` -* `~1.2` := `>=1.2.0 <1.(2+1).0` := `>=1.2.0 <1.3.0` (Same as `1.2.x`) -* `~1` := `>=1.0.0 <(1+1).0.0` := `>=1.0.0 <2.0.0` (Same as `1.x`) -* `~0.2.3` := `>=0.2.3 <0.(2+1).0` := `>=0.2.3 <0.3.0` -* `~0.2` := `>=0.2.0 <0.(2+1).0` := `>=0.2.0 <0.3.0` (Same as `0.2.x`) -* `~0` := `>=0.0.0 <(0+1).0.0` := `>=0.0.0 <1.0.0` (Same as `0.x`) -* `~1.2.3-beta.2` := `>=1.2.3-beta.2 <1.3.0` Note that prereleases in - the `1.2.3` version will be allowed, if they are greater than or - equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but - `1.2.4-beta.2` would not, because it is a prerelease of a - different `[major, minor, patch]` tuple. - -#### Caret Ranges `^1.2.3` `^0.2.5` `^0.0.4` - -Allows changes that do not modify the left-most non-zero digit in the -`[major, minor, patch]` tuple. In other words, this allows patch and -minor updates for versions `1.0.0` and above, patch updates for -versions `0.X >=0.1.0`, and *no* updates for versions `0.0.X`. - -Many authors treat a `0.x` version as if the `x` were the major -"breaking-change" indicator. - -Caret ranges are ideal when an author may make breaking changes -between `0.2.4` and `0.3.0` releases, which is a common practice. -However, it presumes that there will *not* be breaking changes between -`0.2.4` and `0.2.5`. It allows for changes that are presumed to be -additive (but non-breaking), according to commonly observed practices. - -* `^1.2.3` := `>=1.2.3 <2.0.0` -* `^0.2.3` := `>=0.2.3 <0.3.0` -* `^0.0.3` := `>=0.0.3 <0.0.4` -* `^1.2.3-beta.2` := `>=1.2.3-beta.2 <2.0.0` Note that prereleases in - the `1.2.3` version will be allowed, if they are greater than or - equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but - `1.2.4-beta.2` would not, because it is a prerelease of a - different `[major, minor, patch]` tuple. -* `^0.0.3-beta` := `>=0.0.3-beta <0.0.4` Note that prereleases in the - `0.0.3` version *only* will be allowed, if they are greater than or - equal to `beta`. So, `0.0.3-pr.2` would be allowed. - -When parsing caret ranges, a missing `patch` value desugars to the -number `0`, but will allow flexibility within that value, even if the -major and minor versions are both `0`. - -* `^1.2.x` := `>=1.2.0 <2.0.0` -* `^0.0.x` := `>=0.0.0 <0.1.0` -* `^0.0` := `>=0.0.0 <0.1.0` - -A missing `minor` and `patch` values will desugar to zero, but also -allow flexibility within those values, even if the major version is -zero. - -* `^1.x` := `>=1.0.0 <2.0.0` -* `^0.x` := `>=0.0.0 <1.0.0` - -### Range Grammar - -Putting all this together, here is a Backus-Naur grammar for ranges, -for the benefit of parser authors: - -```bnf -range-set ::= range ( logical-or range ) * -logical-or ::= ( ' ' ) * '||' ( ' ' ) * -range ::= hyphen | simple ( ' ' simple ) * | '' -hyphen ::= partial ' - ' partial -simple ::= primitive | partial | tilde | caret -primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial -partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? -xr ::= 'x' | 'X' | '*' | nr -nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * -tilde ::= '~' partial -caret ::= '^' partial -qualifier ::= ( '-' pre )? ( '+' build )? -pre ::= parts -build ::= parts -parts ::= part ( '.' part ) * -part ::= nr | [-0-9A-Za-z]+ -``` - -## Functions - -All methods and classes take a final `options` object argument. All -options in this object are `false` by default. The options supported -are: - -- `loose` Be more forgiving about not-quite-valid semver strings. - (Any resulting output will always be 100% strict compliant, of - course.) For backwards compatibility reasons, if the `options` - argument is a boolean value instead of an object, it is interpreted - to be the `loose` param. -- `includePrerelease` Set to suppress the [default - behavior](https://github.com/npm/node-semver#prerelease-tags) of - excluding prerelease tagged versions from ranges unless they are - explicitly opted into. - -Strict-mode Comparators and Ranges will be strict about the SemVer -strings that they parse. - -* `valid(v)`: Return the parsed version, or null if it's not valid. -* `inc(v, release)`: Return the version incremented by the release - type (`major`, `premajor`, `minor`, `preminor`, `patch`, - `prepatch`, or `prerelease`), or null if it's not valid - * `premajor` in one call will bump the version up to the next major - version and down to a prerelease of that major version. - `preminor`, and `prepatch` work the same way. - * If called from a non-prerelease version, the `prerelease` will work the - same as `prepatch`. It increments the patch version, then makes a - prerelease. If the input version is already a prerelease it simply - increments it. -* `prerelease(v)`: Returns an array of prerelease components, or null - if none exist. Example: `prerelease('1.2.3-alpha.1') -> ['alpha', 1]` -* `major(v)`: Return the major version number. -* `minor(v)`: Return the minor version number. -* `patch(v)`: Return the patch version number. -* `intersects(r1, r2, loose)`: Return true if the two supplied ranges - or comparators intersect. -* `parse(v)`: Attempt to parse a string as a semantic version, returning either - a `SemVer` object or `null`. - -### Comparison - -* `gt(v1, v2)`: `v1 > v2` -* `gte(v1, v2)`: `v1 >= v2` -* `lt(v1, v2)`: `v1 < v2` -* `lte(v1, v2)`: `v1 <= v2` -* `eq(v1, v2)`: `v1 == v2` This is true if they're logically equivalent, - even if they're not the exact same string. You already know how to - compare strings. -* `neq(v1, v2)`: `v1 != v2` The opposite of `eq`. -* `cmp(v1, comparator, v2)`: Pass in a comparison string, and it'll call - the corresponding function above. `"==="` and `"!=="` do simple - string comparison, but are included for completeness. Throws if an - invalid comparison string is provided. -* `compare(v1, v2)`: Return `0` if `v1 == v2`, or `1` if `v1` is greater, or `-1` if - `v2` is greater. Sorts in ascending order if passed to `Array.sort()`. -* `rcompare(v1, v2)`: The reverse of compare. Sorts an array of versions - in descending order when passed to `Array.sort()`. -* `diff(v1, v2)`: Returns difference between two versions by the release type - (`major`, `premajor`, `minor`, `preminor`, `patch`, `prepatch`, or `prerelease`), - or null if the versions are the same. - -### Comparators - -* `intersects(comparator)`: Return true if the comparators intersect - -### Ranges - -* `validRange(range)`: Return the valid range or null if it's not valid -* `satisfies(version, range)`: Return true if the version satisfies the - range. -* `maxSatisfying(versions, range)`: Return the highest version in the list - that satisfies the range, or `null` if none of them do. -* `minSatisfying(versions, range)`: Return the lowest version in the list - that satisfies the range, or `null` if none of them do. -* `minVersion(range)`: Return the lowest version that can possibly match - the given range. -* `gtr(version, range)`: Return `true` if version is greater than all the - versions possible in the range. -* `ltr(version, range)`: Return `true` if version is less than all the - versions possible in the range. -* `outside(version, range, hilo)`: Return true if the version is outside - the bounds of the range in either the high or low direction. The - `hilo` argument must be either the string `'>'` or `'<'`. (This is - the function called by `gtr` and `ltr`.) -* `intersects(range)`: Return true if any of the ranges comparators intersect - -Note that, since ranges may be non-contiguous, a version might not be -greater than a range, less than a range, *or* satisfy a range! For -example, the range `1.2 <1.2.9 || >2.0.0` would have a hole from `1.2.9` -until `2.0.0`, so the version `1.2.10` would not be greater than the -range (because `2.0.1` satisfies, which is higher), nor less than the -range (since `1.2.8` satisfies, which is lower), and it also does not -satisfy the range. - -If you want to know if a version satisfies or does not satisfy a -range, use the `satisfies(version, range)` function. - -### Coercion - -* `coerce(version)`: Coerces a string to semver if possible - -This aims to provide a very forgiving translation of a non-semver string to -semver. It looks for the first digit in a string, and consumes all -remaining characters which satisfy at least a partial semver (e.g., `1`, -`1.2`, `1.2.3`) up to the max permitted length (256 characters). Longer -versions are simply truncated (`4.6.3.9.2-alpha2` becomes `4.6.3`). All -surrounding text is simply ignored (`v3.4 replaces v3.3.1` becomes -`3.4.0`). Only text which lacks digits will fail coercion (`version one` -is not valid). The maximum length for any semver component considered for -coercion is 16 characters; longer components will be ignored -(`10000000000000000.4.7.4` becomes `4.7.4`). The maximum value for any -semver component is `Number.MAX_SAFE_INTEGER || (2**53 - 1)`; higher value -components are invalid (`9999999999999999.4.7.4` is likely invalid). diff --git a/scripts/2.5/node_modules/semver/bin/semver b/scripts/2.5/node_modules/semver/bin/semver deleted file mode 100755 index 801e77f1..00000000 --- a/scripts/2.5/node_modules/semver/bin/semver +++ /dev/null @@ -1,160 +0,0 @@ -#!/usr/bin/env node -// Standalone semver comparison program. -// Exits successfully and prints matching version(s) if -// any supplied version is valid and passes all tests. - -var argv = process.argv.slice(2) - -var versions = [] - -var range = [] - -var inc = null - -var version = require('../package.json').version - -var loose = false - -var includePrerelease = false - -var coerce = false - -var identifier - -var semver = require('../semver') - -var reverse = false - -var options = {} - -main() - -function main () { - if (!argv.length) return help() - while (argv.length) { - var a = argv.shift() - var indexOfEqualSign = a.indexOf('=') - if (indexOfEqualSign !== -1) { - a = a.slice(0, indexOfEqualSign) - argv.unshift(a.slice(indexOfEqualSign + 1)) - } - switch (a) { - case '-rv': case '-rev': case '--rev': case '--reverse': - reverse = true - break - case '-l': case '--loose': - loose = true - break - case '-p': case '--include-prerelease': - includePrerelease = true - break - case '-v': case '--version': - versions.push(argv.shift()) - break - case '-i': case '--inc': case '--increment': - switch (argv[0]) { - case 'major': case 'minor': case 'patch': case 'prerelease': - case 'premajor': case 'preminor': case 'prepatch': - inc = argv.shift() - break - default: - inc = 'patch' - break - } - break - case '--preid': - identifier = argv.shift() - break - case '-r': case '--range': - range.push(argv.shift()) - break - case '-c': case '--coerce': - coerce = true - break - case '-h': case '--help': case '-?': - return help() - default: - versions.push(a) - break - } - } - - var options = { loose: loose, includePrerelease: includePrerelease } - - versions = versions.map(function (v) { - return coerce ? (semver.coerce(v) || { version: v }).version : v - }).filter(function (v) { - return semver.valid(v) - }) - if (!versions.length) return fail() - if (inc && (versions.length !== 1 || range.length)) { return failInc() } - - for (var i = 0, l = range.length; i < l; i++) { - versions = versions.filter(function (v) { - return semver.satisfies(v, range[i], options) - }) - if (!versions.length) return fail() - } - return success(versions) -} - -function failInc () { - console.error('--inc can only be used on a single version with no range') - fail() -} - -function fail () { process.exit(1) } - -function success () { - var compare = reverse ? 'rcompare' : 'compare' - versions.sort(function (a, b) { - return semver[compare](a, b, options) - }).map(function (v) { - return semver.clean(v, options) - }).map(function (v) { - return inc ? semver.inc(v, inc, options, identifier) : v - }).forEach(function (v, i, _) { console.log(v) }) -} - -function help () { - console.log(['SemVer ' + version, - '', - 'A JavaScript implementation of the https://semver.org/ specification', - 'Copyright Isaac Z. Schlueter', - '', - 'Usage: semver [options] [ [...]]', - 'Prints valid versions sorted by SemVer precedence', - '', - 'Options:', - '-r --range ', - ' Print versions that match the specified range.', - '', - '-i --increment []', - ' Increment a version by the specified level. Level can', - ' be one of: major, minor, patch, premajor, preminor,', - " prepatch, or prerelease. Default level is 'patch'.", - ' Only one version may be specified.', - '', - '--preid ', - ' Identifier to be used to prefix premajor, preminor,', - ' prepatch or prerelease version increments.', - '', - '-l --loose', - ' Interpret versions and ranges loosely', - '', - '-p --include-prerelease', - ' Always include prerelease versions in range matching', - '', - '-c --coerce', - ' Coerce a string into SemVer if possible', - ' (does not imply --loose)', - '', - 'Program exits successfully if any valid version satisfies', - 'all supplied ranges, and prints all satisfying versions.', - '', - 'If no satisfying versions are found, then exits failure.', - '', - 'Versions are printed in ascending order, so supplying', - 'multiple versions to the utility will just sort them.' - ].join('\n')) -} diff --git a/scripts/2.5/node_modules/semver/package.json b/scripts/2.5/node_modules/semver/package.json deleted file mode 100644 index 61475155..00000000 --- a/scripts/2.5/node_modules/semver/package.json +++ /dev/null @@ -1,60 +0,0 @@ -{ - "_from": "semver@^5.1.0", - "_id": "semver@5.7.1", - "_inBundle": false, - "_integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==", - "_location": "/semver", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "semver@^5.1.0", - "name": "semver", - "escapedName": "semver", - "rawSpec": "^5.1.0", - "saveSpec": null, - "fetchSpec": "^5.1.0" - }, - "_requiredBy": [ - "/require_optional" - ], - "_resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz", - "_shasum": "a954f931aeba508d307bbf069eff0c01c96116f7", - "_spec": "semver@^5.1.0", - "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/2.5/node_modules/require_optional", - "bin": { - "semver": "./bin/semver" - }, - "bugs": { - "url": "https://github.com/npm/node-semver/issues" - }, - "bundleDependencies": false, - "deprecated": false, - "description": "The semantic version parser used by npm.", - "devDependencies": { - "tap": "^13.0.0-rc.18" - }, - "files": [ - "bin", - "range.bnf", - "semver.js" - ], - "homepage": "https://github.com/npm/node-semver#readme", - "license": "ISC", - "main": "semver.js", - "name": "semver", - "repository": { - "type": "git", - "url": "git+https://github.com/npm/node-semver.git" - }, - "scripts": { - "postpublish": "git push origin --all; git push origin --tags", - "postversion": "npm publish", - "preversion": "npm test", - "test": "tap" - }, - "tap": { - "check-coverage": true - }, - "version": "5.7.1" -} diff --git a/scripts/2.5/node_modules/semver/range.bnf b/scripts/2.5/node_modules/semver/range.bnf deleted file mode 100644 index d4c6ae0d..00000000 --- a/scripts/2.5/node_modules/semver/range.bnf +++ /dev/null @@ -1,16 +0,0 @@ -range-set ::= range ( logical-or range ) * -logical-or ::= ( ' ' ) * '||' ( ' ' ) * -range ::= hyphen | simple ( ' ' simple ) * | '' -hyphen ::= partial ' - ' partial -simple ::= primitive | partial | tilde | caret -primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial -partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? -xr ::= 'x' | 'X' | '*' | nr -nr ::= '0' | [1-9] ( [0-9] ) * -tilde ::= '~' partial -caret ::= '^' partial -qualifier ::= ( '-' pre )? ( '+' build )? -pre ::= parts -build ::= parts -parts ::= part ( '.' part ) * -part ::= nr | [-0-9A-Za-z]+ diff --git a/scripts/2.5/node_modules/semver/semver.js b/scripts/2.5/node_modules/semver/semver.js deleted file mode 100644 index d315d5d6..00000000 --- a/scripts/2.5/node_modules/semver/semver.js +++ /dev/null @@ -1,1483 +0,0 @@ -exports = module.exports = SemVer - -var debug -/* istanbul ignore next */ -if (typeof process === 'object' && - process.env && - process.env.NODE_DEBUG && - /\bsemver\b/i.test(process.env.NODE_DEBUG)) { - debug = function () { - var args = Array.prototype.slice.call(arguments, 0) - args.unshift('SEMVER') - console.log.apply(console, args) - } -} else { - debug = function () {} -} - -// Note: this is the semver.org version of the spec that it implements -// Not necessarily the package version of this code. -exports.SEMVER_SPEC_VERSION = '2.0.0' - -var MAX_LENGTH = 256 -var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || - /* istanbul ignore next */ 9007199254740991 - -// Max safe segment length for coercion. -var MAX_SAFE_COMPONENT_LENGTH = 16 - -// The actual regexps go on exports.re -var re = exports.re = [] -var src = exports.src = [] -var R = 0 - -// The following Regular Expressions can be used for tokenizing, -// validating, and parsing SemVer version strings. - -// ## Numeric Identifier -// A single `0`, or a non-zero digit followed by zero or more digits. - -var NUMERICIDENTIFIER = R++ -src[NUMERICIDENTIFIER] = '0|[1-9]\\d*' -var NUMERICIDENTIFIERLOOSE = R++ -src[NUMERICIDENTIFIERLOOSE] = '[0-9]+' - -// ## Non-numeric Identifier -// Zero or more digits, followed by a letter or hyphen, and then zero or -// more letters, digits, or hyphens. - -var NONNUMERICIDENTIFIER = R++ -src[NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*' - -// ## Main Version -// Three dot-separated numeric identifiers. - -var MAINVERSION = R++ -src[MAINVERSION] = '(' + src[NUMERICIDENTIFIER] + ')\\.' + - '(' + src[NUMERICIDENTIFIER] + ')\\.' + - '(' + src[NUMERICIDENTIFIER] + ')' - -var MAINVERSIONLOOSE = R++ -src[MAINVERSIONLOOSE] = '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + - '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + - '(' + src[NUMERICIDENTIFIERLOOSE] + ')' - -// ## Pre-release Version Identifier -// A numeric identifier, or a non-numeric identifier. - -var PRERELEASEIDENTIFIER = R++ -src[PRERELEASEIDENTIFIER] = '(?:' + src[NUMERICIDENTIFIER] + - '|' + src[NONNUMERICIDENTIFIER] + ')' - -var PRERELEASEIDENTIFIERLOOSE = R++ -src[PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[NUMERICIDENTIFIERLOOSE] + - '|' + src[NONNUMERICIDENTIFIER] + ')' - -// ## Pre-release Version -// Hyphen, followed by one or more dot-separated pre-release version -// identifiers. - -var PRERELEASE = R++ -src[PRERELEASE] = '(?:-(' + src[PRERELEASEIDENTIFIER] + - '(?:\\.' + src[PRERELEASEIDENTIFIER] + ')*))' - -var PRERELEASELOOSE = R++ -src[PRERELEASELOOSE] = '(?:-?(' + src[PRERELEASEIDENTIFIERLOOSE] + - '(?:\\.' + src[PRERELEASEIDENTIFIERLOOSE] + ')*))' - -// ## Build Metadata Identifier -// Any combination of digits, letters, or hyphens. - -var BUILDIDENTIFIER = R++ -src[BUILDIDENTIFIER] = '[0-9A-Za-z-]+' - -// ## Build Metadata -// Plus sign, followed by one or more period-separated build metadata -// identifiers. - -var BUILD = R++ -src[BUILD] = '(?:\\+(' + src[BUILDIDENTIFIER] + - '(?:\\.' + src[BUILDIDENTIFIER] + ')*))' - -// ## Full Version String -// A main version, followed optionally by a pre-release version and -// build metadata. - -// Note that the only major, minor, patch, and pre-release sections of -// the version string are capturing groups. The build metadata is not a -// capturing group, because it should not ever be used in version -// comparison. - -var FULL = R++ -var FULLPLAIN = 'v?' + src[MAINVERSION] + - src[PRERELEASE] + '?' + - src[BUILD] + '?' - -src[FULL] = '^' + FULLPLAIN + '$' - -// like full, but allows v1.2.3 and =1.2.3, which people do sometimes. -// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty -// common in the npm registry. -var LOOSEPLAIN = '[v=\\s]*' + src[MAINVERSIONLOOSE] + - src[PRERELEASELOOSE] + '?' + - src[BUILD] + '?' - -var LOOSE = R++ -src[LOOSE] = '^' + LOOSEPLAIN + '$' - -var GTLT = R++ -src[GTLT] = '((?:<|>)?=?)' - -// Something like "2.*" or "1.2.x". -// Note that "x.x" is a valid xRange identifer, meaning "any version" -// Only the first item is strictly required. -var XRANGEIDENTIFIERLOOSE = R++ -src[XRANGEIDENTIFIERLOOSE] = src[NUMERICIDENTIFIERLOOSE] + '|x|X|\\*' -var XRANGEIDENTIFIER = R++ -src[XRANGEIDENTIFIER] = src[NUMERICIDENTIFIER] + '|x|X|\\*' - -var XRANGEPLAIN = R++ -src[XRANGEPLAIN] = '[v=\\s]*(' + src[XRANGEIDENTIFIER] + ')' + - '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + - '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + - '(?:' + src[PRERELEASE] + ')?' + - src[BUILD] + '?' + - ')?)?' - -var XRANGEPLAINLOOSE = R++ -src[XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[XRANGEIDENTIFIERLOOSE] + ')' + - '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + - '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + - '(?:' + src[PRERELEASELOOSE] + ')?' + - src[BUILD] + '?' + - ')?)?' - -var XRANGE = R++ -src[XRANGE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAIN] + '$' -var XRANGELOOSE = R++ -src[XRANGELOOSE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAINLOOSE] + '$' - -// Coercion. -// Extract anything that could conceivably be a part of a valid semver -var COERCE = R++ -src[COERCE] = '(?:^|[^\\d])' + - '(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' + - '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + - '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + - '(?:$|[^\\d])' - -// Tilde ranges. -// Meaning is "reasonably at or greater than" -var LONETILDE = R++ -src[LONETILDE] = '(?:~>?)' - -var TILDETRIM = R++ -src[TILDETRIM] = '(\\s*)' + src[LONETILDE] + '\\s+' -re[TILDETRIM] = new RegExp(src[TILDETRIM], 'g') -var tildeTrimReplace = '$1~' - -var TILDE = R++ -src[TILDE] = '^' + src[LONETILDE] + src[XRANGEPLAIN] + '$' -var TILDELOOSE = R++ -src[TILDELOOSE] = '^' + src[LONETILDE] + src[XRANGEPLAINLOOSE] + '$' - -// Caret ranges. -// Meaning is "at least and backwards compatible with" -var LONECARET = R++ -src[LONECARET] = '(?:\\^)' - -var CARETTRIM = R++ -src[CARETTRIM] = '(\\s*)' + src[LONECARET] + '\\s+' -re[CARETTRIM] = new RegExp(src[CARETTRIM], 'g') -var caretTrimReplace = '$1^' - -var CARET = R++ -src[CARET] = '^' + src[LONECARET] + src[XRANGEPLAIN] + '$' -var CARETLOOSE = R++ -src[CARETLOOSE] = '^' + src[LONECARET] + src[XRANGEPLAINLOOSE] + '$' - -// A simple gt/lt/eq thing, or just "" to indicate "any version" -var COMPARATORLOOSE = R++ -src[COMPARATORLOOSE] = '^' + src[GTLT] + '\\s*(' + LOOSEPLAIN + ')$|^$' -var COMPARATOR = R++ -src[COMPARATOR] = '^' + src[GTLT] + '\\s*(' + FULLPLAIN + ')$|^$' - -// An expression to strip any whitespace between the gtlt and the thing -// it modifies, so that `> 1.2.3` ==> `>1.2.3` -var COMPARATORTRIM = R++ -src[COMPARATORTRIM] = '(\\s*)' + src[GTLT] + - '\\s*(' + LOOSEPLAIN + '|' + src[XRANGEPLAIN] + ')' - -// this one has to use the /g flag -re[COMPARATORTRIM] = new RegExp(src[COMPARATORTRIM], 'g') -var comparatorTrimReplace = '$1$2$3' - -// Something like `1.2.3 - 1.2.4` -// Note that these all use the loose form, because they'll be -// checked against either the strict or loose comparator form -// later. -var HYPHENRANGE = R++ -src[HYPHENRANGE] = '^\\s*(' + src[XRANGEPLAIN] + ')' + - '\\s+-\\s+' + - '(' + src[XRANGEPLAIN] + ')' + - '\\s*$' - -var HYPHENRANGELOOSE = R++ -src[HYPHENRANGELOOSE] = '^\\s*(' + src[XRANGEPLAINLOOSE] + ')' + - '\\s+-\\s+' + - '(' + src[XRANGEPLAINLOOSE] + ')' + - '\\s*$' - -// Star ranges basically just allow anything at all. -var STAR = R++ -src[STAR] = '(<|>)?=?\\s*\\*' - -// Compile to actual regexp objects. -// All are flag-free, unless they were created above with a flag. -for (var i = 0; i < R; i++) { - debug(i, src[i]) - if (!re[i]) { - re[i] = new RegExp(src[i]) - } -} - -exports.parse = parse -function parse (version, options) { - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - } - } - - if (version instanceof SemVer) { - return version - } - - if (typeof version !== 'string') { - return null - } - - if (version.length > MAX_LENGTH) { - return null - } - - var r = options.loose ? re[LOOSE] : re[FULL] - if (!r.test(version)) { - return null - } - - try { - return new SemVer(version, options) - } catch (er) { - return null - } -} - -exports.valid = valid -function valid (version, options) { - var v = parse(version, options) - return v ? v.version : null -} - -exports.clean = clean -function clean (version, options) { - var s = parse(version.trim().replace(/^[=v]+/, ''), options) - return s ? s.version : null -} - -exports.SemVer = SemVer - -function SemVer (version, options) { - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - } - } - if (version instanceof SemVer) { - if (version.loose === options.loose) { - return version - } else { - version = version.version - } - } else if (typeof version !== 'string') { - throw new TypeError('Invalid Version: ' + version) - } - - if (version.length > MAX_LENGTH) { - throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters') - } - - if (!(this instanceof SemVer)) { - return new SemVer(version, options) - } - - debug('SemVer', version, options) - this.options = options - this.loose = !!options.loose - - var m = version.trim().match(options.loose ? re[LOOSE] : re[FULL]) - - if (!m) { - throw new TypeError('Invalid Version: ' + version) - } - - this.raw = version - - // these are actually numbers - this.major = +m[1] - this.minor = +m[2] - this.patch = +m[3] - - if (this.major > MAX_SAFE_INTEGER || this.major < 0) { - throw new TypeError('Invalid major version') - } - - if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { - throw new TypeError('Invalid minor version') - } - - if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { - throw new TypeError('Invalid patch version') - } - - // numberify any prerelease numeric ids - if (!m[4]) { - this.prerelease = [] - } else { - this.prerelease = m[4].split('.').map(function (id) { - if (/^[0-9]+$/.test(id)) { - var num = +id - if (num >= 0 && num < MAX_SAFE_INTEGER) { - return num - } - } - return id - }) - } - - this.build = m[5] ? m[5].split('.') : [] - this.format() -} - -SemVer.prototype.format = function () { - this.version = this.major + '.' + this.minor + '.' + this.patch - if (this.prerelease.length) { - this.version += '-' + this.prerelease.join('.') - } - return this.version -} - -SemVer.prototype.toString = function () { - return this.version -} - -SemVer.prototype.compare = function (other) { - debug('SemVer.compare', this.version, this.options, other) - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options) - } - - return this.compareMain(other) || this.comparePre(other) -} - -SemVer.prototype.compareMain = function (other) { - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options) - } - - return compareIdentifiers(this.major, other.major) || - compareIdentifiers(this.minor, other.minor) || - compareIdentifiers(this.patch, other.patch) -} - -SemVer.prototype.comparePre = function (other) { - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options) - } - - // NOT having a prerelease is > having one - if (this.prerelease.length && !other.prerelease.length) { - return -1 - } else if (!this.prerelease.length && other.prerelease.length) { - return 1 - } else if (!this.prerelease.length && !other.prerelease.length) { - return 0 - } - - var i = 0 - do { - var a = this.prerelease[i] - var b = other.prerelease[i] - debug('prerelease compare', i, a, b) - if (a === undefined && b === undefined) { - return 0 - } else if (b === undefined) { - return 1 - } else if (a === undefined) { - return -1 - } else if (a === b) { - continue - } else { - return compareIdentifiers(a, b) - } - } while (++i) -} - -// preminor will bump the version up to the next minor release, and immediately -// down to pre-release. premajor and prepatch work the same way. -SemVer.prototype.inc = function (release, identifier) { - switch (release) { - case 'premajor': - this.prerelease.length = 0 - this.patch = 0 - this.minor = 0 - this.major++ - this.inc('pre', identifier) - break - case 'preminor': - this.prerelease.length = 0 - this.patch = 0 - this.minor++ - this.inc('pre', identifier) - break - case 'prepatch': - // If this is already a prerelease, it will bump to the next version - // drop any prereleases that might already exist, since they are not - // relevant at this point. - this.prerelease.length = 0 - this.inc('patch', identifier) - this.inc('pre', identifier) - break - // If the input is a non-prerelease version, this acts the same as - // prepatch. - case 'prerelease': - if (this.prerelease.length === 0) { - this.inc('patch', identifier) - } - this.inc('pre', identifier) - break - - case 'major': - // If this is a pre-major version, bump up to the same major version. - // Otherwise increment major. - // 1.0.0-5 bumps to 1.0.0 - // 1.1.0 bumps to 2.0.0 - if (this.minor !== 0 || - this.patch !== 0 || - this.prerelease.length === 0) { - this.major++ - } - this.minor = 0 - this.patch = 0 - this.prerelease = [] - break - case 'minor': - // If this is a pre-minor version, bump up to the same minor version. - // Otherwise increment minor. - // 1.2.0-5 bumps to 1.2.0 - // 1.2.1 bumps to 1.3.0 - if (this.patch !== 0 || this.prerelease.length === 0) { - this.minor++ - } - this.patch = 0 - this.prerelease = [] - break - case 'patch': - // If this is not a pre-release version, it will increment the patch. - // If it is a pre-release it will bump up to the same patch version. - // 1.2.0-5 patches to 1.2.0 - // 1.2.0 patches to 1.2.1 - if (this.prerelease.length === 0) { - this.patch++ - } - this.prerelease = [] - break - // This probably shouldn't be used publicly. - // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction. - case 'pre': - if (this.prerelease.length === 0) { - this.prerelease = [0] - } else { - var i = this.prerelease.length - while (--i >= 0) { - if (typeof this.prerelease[i] === 'number') { - this.prerelease[i]++ - i = -2 - } - } - if (i === -1) { - // didn't increment anything - this.prerelease.push(0) - } - } - if (identifier) { - // 1.2.0-beta.1 bumps to 1.2.0-beta.2, - // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 - if (this.prerelease[0] === identifier) { - if (isNaN(this.prerelease[1])) { - this.prerelease = [identifier, 0] - } - } else { - this.prerelease = [identifier, 0] - } - } - break - - default: - throw new Error('invalid increment argument: ' + release) - } - this.format() - this.raw = this.version - return this -} - -exports.inc = inc -function inc (version, release, loose, identifier) { - if (typeof (loose) === 'string') { - identifier = loose - loose = undefined - } - - try { - return new SemVer(version, loose).inc(release, identifier).version - } catch (er) { - return null - } -} - -exports.diff = diff -function diff (version1, version2) { - if (eq(version1, version2)) { - return null - } else { - var v1 = parse(version1) - var v2 = parse(version2) - var prefix = '' - if (v1.prerelease.length || v2.prerelease.length) { - prefix = 'pre' - var defaultResult = 'prerelease' - } - for (var key in v1) { - if (key === 'major' || key === 'minor' || key === 'patch') { - if (v1[key] !== v2[key]) { - return prefix + key - } - } - } - return defaultResult // may be undefined - } -} - -exports.compareIdentifiers = compareIdentifiers - -var numeric = /^[0-9]+$/ -function compareIdentifiers (a, b) { - var anum = numeric.test(a) - var bnum = numeric.test(b) - - if (anum && bnum) { - a = +a - b = +b - } - - return a === b ? 0 - : (anum && !bnum) ? -1 - : (bnum && !anum) ? 1 - : a < b ? -1 - : 1 -} - -exports.rcompareIdentifiers = rcompareIdentifiers -function rcompareIdentifiers (a, b) { - return compareIdentifiers(b, a) -} - -exports.major = major -function major (a, loose) { - return new SemVer(a, loose).major -} - -exports.minor = minor -function minor (a, loose) { - return new SemVer(a, loose).minor -} - -exports.patch = patch -function patch (a, loose) { - return new SemVer(a, loose).patch -} - -exports.compare = compare -function compare (a, b, loose) { - return new SemVer(a, loose).compare(new SemVer(b, loose)) -} - -exports.compareLoose = compareLoose -function compareLoose (a, b) { - return compare(a, b, true) -} - -exports.rcompare = rcompare -function rcompare (a, b, loose) { - return compare(b, a, loose) -} - -exports.sort = sort -function sort (list, loose) { - return list.sort(function (a, b) { - return exports.compare(a, b, loose) - }) -} - -exports.rsort = rsort -function rsort (list, loose) { - return list.sort(function (a, b) { - return exports.rcompare(a, b, loose) - }) -} - -exports.gt = gt -function gt (a, b, loose) { - return compare(a, b, loose) > 0 -} - -exports.lt = lt -function lt (a, b, loose) { - return compare(a, b, loose) < 0 -} - -exports.eq = eq -function eq (a, b, loose) { - return compare(a, b, loose) === 0 -} - -exports.neq = neq -function neq (a, b, loose) { - return compare(a, b, loose) !== 0 -} - -exports.gte = gte -function gte (a, b, loose) { - return compare(a, b, loose) >= 0 -} - -exports.lte = lte -function lte (a, b, loose) { - return compare(a, b, loose) <= 0 -} - -exports.cmp = cmp -function cmp (a, op, b, loose) { - switch (op) { - case '===': - if (typeof a === 'object') - a = a.version - if (typeof b === 'object') - b = b.version - return a === b - - case '!==': - if (typeof a === 'object') - a = a.version - if (typeof b === 'object') - b = b.version - return a !== b - - case '': - case '=': - case '==': - return eq(a, b, loose) - - case '!=': - return neq(a, b, loose) - - case '>': - return gt(a, b, loose) - - case '>=': - return gte(a, b, loose) - - case '<': - return lt(a, b, loose) - - case '<=': - return lte(a, b, loose) - - default: - throw new TypeError('Invalid operator: ' + op) - } -} - -exports.Comparator = Comparator -function Comparator (comp, options) { - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - } - } - - if (comp instanceof Comparator) { - if (comp.loose === !!options.loose) { - return comp - } else { - comp = comp.value - } - } - - if (!(this instanceof Comparator)) { - return new Comparator(comp, options) - } - - debug('comparator', comp, options) - this.options = options - this.loose = !!options.loose - this.parse(comp) - - if (this.semver === ANY) { - this.value = '' - } else { - this.value = this.operator + this.semver.version - } - - debug('comp', this) -} - -var ANY = {} -Comparator.prototype.parse = function (comp) { - var r = this.options.loose ? re[COMPARATORLOOSE] : re[COMPARATOR] - var m = comp.match(r) - - if (!m) { - throw new TypeError('Invalid comparator: ' + comp) - } - - this.operator = m[1] - if (this.operator === '=') { - this.operator = '' - } - - // if it literally is just '>' or '' then allow anything. - if (!m[2]) { - this.semver = ANY - } else { - this.semver = new SemVer(m[2], this.options.loose) - } -} - -Comparator.prototype.toString = function () { - return this.value -} - -Comparator.prototype.test = function (version) { - debug('Comparator.test', version, this.options.loose) - - if (this.semver === ANY) { - return true - } - - if (typeof version === 'string') { - version = new SemVer(version, this.options) - } - - return cmp(version, this.operator, this.semver, this.options) -} - -Comparator.prototype.intersects = function (comp, options) { - if (!(comp instanceof Comparator)) { - throw new TypeError('a Comparator is required') - } - - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - } - } - - var rangeTmp - - if (this.operator === '') { - rangeTmp = new Range(comp.value, options) - return satisfies(this.value, rangeTmp, options) - } else if (comp.operator === '') { - rangeTmp = new Range(this.value, options) - return satisfies(comp.semver, rangeTmp, options) - } - - var sameDirectionIncreasing = - (this.operator === '>=' || this.operator === '>') && - (comp.operator === '>=' || comp.operator === '>') - var sameDirectionDecreasing = - (this.operator === '<=' || this.operator === '<') && - (comp.operator === '<=' || comp.operator === '<') - var sameSemVer = this.semver.version === comp.semver.version - var differentDirectionsInclusive = - (this.operator === '>=' || this.operator === '<=') && - (comp.operator === '>=' || comp.operator === '<=') - var oppositeDirectionsLessThan = - cmp(this.semver, '<', comp.semver, options) && - ((this.operator === '>=' || this.operator === '>') && - (comp.operator === '<=' || comp.operator === '<')) - var oppositeDirectionsGreaterThan = - cmp(this.semver, '>', comp.semver, options) && - ((this.operator === '<=' || this.operator === '<') && - (comp.operator === '>=' || comp.operator === '>')) - - return sameDirectionIncreasing || sameDirectionDecreasing || - (sameSemVer && differentDirectionsInclusive) || - oppositeDirectionsLessThan || oppositeDirectionsGreaterThan -} - -exports.Range = Range -function Range (range, options) { - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - } - } - - if (range instanceof Range) { - if (range.loose === !!options.loose && - range.includePrerelease === !!options.includePrerelease) { - return range - } else { - return new Range(range.raw, options) - } - } - - if (range instanceof Comparator) { - return new Range(range.value, options) - } - - if (!(this instanceof Range)) { - return new Range(range, options) - } - - this.options = options - this.loose = !!options.loose - this.includePrerelease = !!options.includePrerelease - - // First, split based on boolean or || - this.raw = range - this.set = range.split(/\s*\|\|\s*/).map(function (range) { - return this.parseRange(range.trim()) - }, this).filter(function (c) { - // throw out any that are not relevant for whatever reason - return c.length - }) - - if (!this.set.length) { - throw new TypeError('Invalid SemVer Range: ' + range) - } - - this.format() -} - -Range.prototype.format = function () { - this.range = this.set.map(function (comps) { - return comps.join(' ').trim() - }).join('||').trim() - return this.range -} - -Range.prototype.toString = function () { - return this.range -} - -Range.prototype.parseRange = function (range) { - var loose = this.options.loose - range = range.trim() - // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` - var hr = loose ? re[HYPHENRANGELOOSE] : re[HYPHENRANGE] - range = range.replace(hr, hyphenReplace) - debug('hyphen replace', range) - // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` - range = range.replace(re[COMPARATORTRIM], comparatorTrimReplace) - debug('comparator trim', range, re[COMPARATORTRIM]) - - // `~ 1.2.3` => `~1.2.3` - range = range.replace(re[TILDETRIM], tildeTrimReplace) - - // `^ 1.2.3` => `^1.2.3` - range = range.replace(re[CARETTRIM], caretTrimReplace) - - // normalize spaces - range = range.split(/\s+/).join(' ') - - // At this point, the range is completely trimmed and - // ready to be split into comparators. - - var compRe = loose ? re[COMPARATORLOOSE] : re[COMPARATOR] - var set = range.split(' ').map(function (comp) { - return parseComparator(comp, this.options) - }, this).join(' ').split(/\s+/) - if (this.options.loose) { - // in loose mode, throw out any that are not valid comparators - set = set.filter(function (comp) { - return !!comp.match(compRe) - }) - } - set = set.map(function (comp) { - return new Comparator(comp, this.options) - }, this) - - return set -} - -Range.prototype.intersects = function (range, options) { - if (!(range instanceof Range)) { - throw new TypeError('a Range is required') - } - - return this.set.some(function (thisComparators) { - return thisComparators.every(function (thisComparator) { - return range.set.some(function (rangeComparators) { - return rangeComparators.every(function (rangeComparator) { - return thisComparator.intersects(rangeComparator, options) - }) - }) - }) - }) -} - -// Mostly just for testing and legacy API reasons -exports.toComparators = toComparators -function toComparators (range, options) { - return new Range(range, options).set.map(function (comp) { - return comp.map(function (c) { - return c.value - }).join(' ').trim().split(' ') - }) -} - -// comprised of xranges, tildes, stars, and gtlt's at this point. -// already replaced the hyphen ranges -// turn into a set of JUST comparators. -function parseComparator (comp, options) { - debug('comp', comp, options) - comp = replaceCarets(comp, options) - debug('caret', comp) - comp = replaceTildes(comp, options) - debug('tildes', comp) - comp = replaceXRanges(comp, options) - debug('xrange', comp) - comp = replaceStars(comp, options) - debug('stars', comp) - return comp -} - -function isX (id) { - return !id || id.toLowerCase() === 'x' || id === '*' -} - -// ~, ~> --> * (any, kinda silly) -// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0 -// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0 -// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0 -// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0 -// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0 -function replaceTildes (comp, options) { - return comp.trim().split(/\s+/).map(function (comp) { - return replaceTilde(comp, options) - }).join(' ') -} - -function replaceTilde (comp, options) { - var r = options.loose ? re[TILDELOOSE] : re[TILDE] - return comp.replace(r, function (_, M, m, p, pr) { - debug('tilde', comp, _, M, m, p, pr) - var ret - - if (isX(M)) { - ret = '' - } else if (isX(m)) { - ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' - } else if (isX(p)) { - // ~1.2 == >=1.2.0 <1.3.0 - ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' - } else if (pr) { - debug('replaceTilde pr', pr) - ret = '>=' + M + '.' + m + '.' + p + '-' + pr + - ' <' + M + '.' + (+m + 1) + '.0' - } else { - // ~1.2.3 == >=1.2.3 <1.3.0 - ret = '>=' + M + '.' + m + '.' + p + - ' <' + M + '.' + (+m + 1) + '.0' - } - - debug('tilde return', ret) - return ret - }) -} - -// ^ --> * (any, kinda silly) -// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0 -// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0 -// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0 -// ^1.2.3 --> >=1.2.3 <2.0.0 -// ^1.2.0 --> >=1.2.0 <2.0.0 -function replaceCarets (comp, options) { - return comp.trim().split(/\s+/).map(function (comp) { - return replaceCaret(comp, options) - }).join(' ') -} - -function replaceCaret (comp, options) { - debug('caret', comp, options) - var r = options.loose ? re[CARETLOOSE] : re[CARET] - return comp.replace(r, function (_, M, m, p, pr) { - debug('caret', comp, _, M, m, p, pr) - var ret - - if (isX(M)) { - ret = '' - } else if (isX(m)) { - ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' - } else if (isX(p)) { - if (M === '0') { - ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' - } else { - ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0' - } - } else if (pr) { - debug('replaceCaret pr', pr) - if (M === '0') { - if (m === '0') { - ret = '>=' + M + '.' + m + '.' + p + '-' + pr + - ' <' + M + '.' + m + '.' + (+p + 1) - } else { - ret = '>=' + M + '.' + m + '.' + p + '-' + pr + - ' <' + M + '.' + (+m + 1) + '.0' - } - } else { - ret = '>=' + M + '.' + m + '.' + p + '-' + pr + - ' <' + (+M + 1) + '.0.0' - } - } else { - debug('no pr') - if (M === '0') { - if (m === '0') { - ret = '>=' + M + '.' + m + '.' + p + - ' <' + M + '.' + m + '.' + (+p + 1) - } else { - ret = '>=' + M + '.' + m + '.' + p + - ' <' + M + '.' + (+m + 1) + '.0' - } - } else { - ret = '>=' + M + '.' + m + '.' + p + - ' <' + (+M + 1) + '.0.0' - } - } - - debug('caret return', ret) - return ret - }) -} - -function replaceXRanges (comp, options) { - debug('replaceXRanges', comp, options) - return comp.split(/\s+/).map(function (comp) { - return replaceXRange(comp, options) - }).join(' ') -} - -function replaceXRange (comp, options) { - comp = comp.trim() - var r = options.loose ? re[XRANGELOOSE] : re[XRANGE] - return comp.replace(r, function (ret, gtlt, M, m, p, pr) { - debug('xRange', comp, ret, gtlt, M, m, p, pr) - var xM = isX(M) - var xm = xM || isX(m) - var xp = xm || isX(p) - var anyX = xp - - if (gtlt === '=' && anyX) { - gtlt = '' - } - - if (xM) { - if (gtlt === '>' || gtlt === '<') { - // nothing is allowed - ret = '<0.0.0' - } else { - // nothing is forbidden - ret = '*' - } - } else if (gtlt && anyX) { - // we know patch is an x, because we have any x at all. - // replace X with 0 - if (xm) { - m = 0 - } - p = 0 - - if (gtlt === '>') { - // >1 => >=2.0.0 - // >1.2 => >=1.3.0 - // >1.2.3 => >= 1.2.4 - gtlt = '>=' - if (xm) { - M = +M + 1 - m = 0 - p = 0 - } else { - m = +m + 1 - p = 0 - } - } else if (gtlt === '<=') { - // <=0.7.x is actually <0.8.0, since any 0.7.x should - // pass. Similarly, <=7.x is actually <8.0.0, etc. - gtlt = '<' - if (xm) { - M = +M + 1 - } else { - m = +m + 1 - } - } - - ret = gtlt + M + '.' + m + '.' + p - } else if (xm) { - ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' - } else if (xp) { - ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' - } - - debug('xRange return', ret) - - return ret - }) -} - -// Because * is AND-ed with everything else in the comparator, -// and '' means "any version", just remove the *s entirely. -function replaceStars (comp, options) { - debug('replaceStars', comp, options) - // Looseness is ignored here. star is always as loose as it gets! - return comp.trim().replace(re[STAR], '') -} - -// This function is passed to string.replace(re[HYPHENRANGE]) -// M, m, patch, prerelease, build -// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 -// 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do -// 1.2 - 3.4 => >=1.2.0 <3.5.0 -function hyphenReplace ($0, - from, fM, fm, fp, fpr, fb, - to, tM, tm, tp, tpr, tb) { - if (isX(fM)) { - from = '' - } else if (isX(fm)) { - from = '>=' + fM + '.0.0' - } else if (isX(fp)) { - from = '>=' + fM + '.' + fm + '.0' - } else { - from = '>=' + from - } - - if (isX(tM)) { - to = '' - } else if (isX(tm)) { - to = '<' + (+tM + 1) + '.0.0' - } else if (isX(tp)) { - to = '<' + tM + '.' + (+tm + 1) + '.0' - } else if (tpr) { - to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr - } else { - to = '<=' + to - } - - return (from + ' ' + to).trim() -} - -// if ANY of the sets match ALL of its comparators, then pass -Range.prototype.test = function (version) { - if (!version) { - return false - } - - if (typeof version === 'string') { - version = new SemVer(version, this.options) - } - - for (var i = 0; i < this.set.length; i++) { - if (testSet(this.set[i], version, this.options)) { - return true - } - } - return false -} - -function testSet (set, version, options) { - for (var i = 0; i < set.length; i++) { - if (!set[i].test(version)) { - return false - } - } - - if (version.prerelease.length && !options.includePrerelease) { - // Find the set of versions that are allowed to have prereleases - // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 - // That should allow `1.2.3-pr.2` to pass. - // However, `1.2.4-alpha.notready` should NOT be allowed, - // even though it's within the range set by the comparators. - for (i = 0; i < set.length; i++) { - debug(set[i].semver) - if (set[i].semver === ANY) { - continue - } - - if (set[i].semver.prerelease.length > 0) { - var allowed = set[i].semver - if (allowed.major === version.major && - allowed.minor === version.minor && - allowed.patch === version.patch) { - return true - } - } - } - - // Version has a -pre, but it's not one of the ones we like. - return false - } - - return true -} - -exports.satisfies = satisfies -function satisfies (version, range, options) { - try { - range = new Range(range, options) - } catch (er) { - return false - } - return range.test(version) -} - -exports.maxSatisfying = maxSatisfying -function maxSatisfying (versions, range, options) { - var max = null - var maxSV = null - try { - var rangeObj = new Range(range, options) - } catch (er) { - return null - } - versions.forEach(function (v) { - if (rangeObj.test(v)) { - // satisfies(v, range, options) - if (!max || maxSV.compare(v) === -1) { - // compare(max, v, true) - max = v - maxSV = new SemVer(max, options) - } - } - }) - return max -} - -exports.minSatisfying = minSatisfying -function minSatisfying (versions, range, options) { - var min = null - var minSV = null - try { - var rangeObj = new Range(range, options) - } catch (er) { - return null - } - versions.forEach(function (v) { - if (rangeObj.test(v)) { - // satisfies(v, range, options) - if (!min || minSV.compare(v) === 1) { - // compare(min, v, true) - min = v - minSV = new SemVer(min, options) - } - } - }) - return min -} - -exports.minVersion = minVersion -function minVersion (range, loose) { - range = new Range(range, loose) - - var minver = new SemVer('0.0.0') - if (range.test(minver)) { - return minver - } - - minver = new SemVer('0.0.0-0') - if (range.test(minver)) { - return minver - } - - minver = null - for (var i = 0; i < range.set.length; ++i) { - var comparators = range.set[i] - - comparators.forEach(function (comparator) { - // Clone to avoid manipulating the comparator's semver object. - var compver = new SemVer(comparator.semver.version) - switch (comparator.operator) { - case '>': - if (compver.prerelease.length === 0) { - compver.patch++ - } else { - compver.prerelease.push(0) - } - compver.raw = compver.format() - /* fallthrough */ - case '': - case '>=': - if (!minver || gt(minver, compver)) { - minver = compver - } - break - case '<': - case '<=': - /* Ignore maximum versions */ - break - /* istanbul ignore next */ - default: - throw new Error('Unexpected operation: ' + comparator.operator) - } - }) - } - - if (minver && range.test(minver)) { - return minver - } - - return null -} - -exports.validRange = validRange -function validRange (range, options) { - try { - // Return '*' instead of '' so that truthiness works. - // This will throw if it's invalid anyway - return new Range(range, options).range || '*' - } catch (er) { - return null - } -} - -// Determine if version is less than all the versions possible in the range -exports.ltr = ltr -function ltr (version, range, options) { - return outside(version, range, '<', options) -} - -// Determine if version is greater than all the versions possible in the range. -exports.gtr = gtr -function gtr (version, range, options) { - return outside(version, range, '>', options) -} - -exports.outside = outside -function outside (version, range, hilo, options) { - version = new SemVer(version, options) - range = new Range(range, options) - - var gtfn, ltefn, ltfn, comp, ecomp - switch (hilo) { - case '>': - gtfn = gt - ltefn = lte - ltfn = lt - comp = '>' - ecomp = '>=' - break - case '<': - gtfn = lt - ltefn = gte - ltfn = gt - comp = '<' - ecomp = '<=' - break - default: - throw new TypeError('Must provide a hilo val of "<" or ">"') - } - - // If it satisifes the range it is not outside - if (satisfies(version, range, options)) { - return false - } - - // From now on, variable terms are as if we're in "gtr" mode. - // but note that everything is flipped for the "ltr" function. - - for (var i = 0; i < range.set.length; ++i) { - var comparators = range.set[i] - - var high = null - var low = null - - comparators.forEach(function (comparator) { - if (comparator.semver === ANY) { - comparator = new Comparator('>=0.0.0') - } - high = high || comparator - low = low || comparator - if (gtfn(comparator.semver, high.semver, options)) { - high = comparator - } else if (ltfn(comparator.semver, low.semver, options)) { - low = comparator - } - }) - - // If the edge version comparator has a operator then our version - // isn't outside it - if (high.operator === comp || high.operator === ecomp) { - return false - } - - // If the lowest version comparator has an operator and our version - // is less than it then it isn't higher than the range - if ((!low.operator || low.operator === comp) && - ltefn(version, low.semver)) { - return false - } else if (low.operator === ecomp && ltfn(version, low.semver)) { - return false - } - } - return true -} - -exports.prerelease = prerelease -function prerelease (version, options) { - var parsed = parse(version, options) - return (parsed && parsed.prerelease.length) ? parsed.prerelease : null -} - -exports.intersects = intersects -function intersects (r1, r2, options) { - r1 = new Range(r1, options) - r2 = new Range(r2, options) - return r1.intersects(r2) -} - -exports.coerce = coerce -function coerce (version) { - if (version instanceof SemVer) { - return version - } - - if (typeof version !== 'string') { - return null - } - - var match = version.match(re[COERCE]) - - if (match == null) { - return null - } - - return parse(match[1] + - '.' + (match[2] || '0') + - '.' + (match[3] || '0')) -} diff --git a/scripts/2.5/node_modules/sparse-bitfield/.npmignore b/scripts/2.5/node_modules/sparse-bitfield/.npmignore deleted file mode 100644 index 3c3629e6..00000000 --- a/scripts/2.5/node_modules/sparse-bitfield/.npmignore +++ /dev/null @@ -1 +0,0 @@ -node_modules diff --git a/scripts/2.5/node_modules/sparse-bitfield/.travis.yml b/scripts/2.5/node_modules/sparse-bitfield/.travis.yml deleted file mode 100644 index c0428217..00000000 --- a/scripts/2.5/node_modules/sparse-bitfield/.travis.yml +++ /dev/null @@ -1,6 +0,0 @@ -language: node_js -node_js: - - '0.10' - - '0.12' - - '4.0' - - '5.0' diff --git a/scripts/2.5/node_modules/sparse-bitfield/LICENSE b/scripts/2.5/node_modules/sparse-bitfield/LICENSE deleted file mode 100644 index bae9da7b..00000000 --- a/scripts/2.5/node_modules/sparse-bitfield/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2016 Mathias Buus - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/scripts/2.5/node_modules/sparse-bitfield/README.md b/scripts/2.5/node_modules/sparse-bitfield/README.md deleted file mode 100644 index 7b6b8f9e..00000000 --- a/scripts/2.5/node_modules/sparse-bitfield/README.md +++ /dev/null @@ -1,62 +0,0 @@ -# sparse-bitfield - -Bitfield implementation that allocates a series of 1kb buffers to support sparse bitfields -without allocating a massive buffer. If you want to simple implementation of a flat bitfield -see the [bitfield](https://github.com/fb55/bitfield) module. - -This module is mostly useful if you need a big bitfield where you won't nessecarily set every bit. - -``` -npm install sparse-bitfield -``` - -[![build status](http://img.shields.io/travis/mafintosh/sparse-bitfield.svg?style=flat)](http://travis-ci.org/mafintosh/sparse-bitfield) - -## Usage - -``` js -var bitfield = require('sparse-bitfield') -var bits = bitfield() - -bits.set(0, true) // set first bit -bits.set(1, true) // set second bit -bits.set(1000000000000, true) // set the 1.000.000.000.000th bit -``` - -Running the above example will allocate two 1kb buffers internally. -Each 1kb buffer can hold information about 8192 bits so the first one will be used to store information about the first two bits and the second will be used to store the 1.000.000.000.000th bit. - -## API - -#### `var bits = bitfield([options])` - -Create a new bitfield. Options include - -``` js -{ - pageSize: 1024, // how big should the partial buffers be - buffer: anExistingBitfield, - trackUpdates: false // track when pages are being updated in the pager -} -``` - -#### `bits.set(index, value)` - -Set a bit to true or false. - -#### `bits.get(index)` - -Get the value of a bit. - -#### `bits.pages` - -A [memory-pager](https://github.com/mafintosh/memory-pager) instance that is managing the underlying memory. -If you set `trackUpdates` to true in the constructor you can use `.lastUpdate()` on this instance to get the last updated memory page. - -#### `var buffer = bits.toBuffer()` - -Get a single buffer representing the entire bitfield. - -## License - -MIT diff --git a/scripts/2.5/node_modules/sparse-bitfield/index.js b/scripts/2.5/node_modules/sparse-bitfield/index.js deleted file mode 100644 index ff458c97..00000000 --- a/scripts/2.5/node_modules/sparse-bitfield/index.js +++ /dev/null @@ -1,95 +0,0 @@ -var pager = require('memory-pager') - -module.exports = Bitfield - -function Bitfield (opts) { - if (!(this instanceof Bitfield)) return new Bitfield(opts) - if (!opts) opts = {} - if (Buffer.isBuffer(opts)) opts = {buffer: opts} - - this.pageOffset = opts.pageOffset || 0 - this.pageSize = opts.pageSize || 1024 - this.pages = opts.pages || pager(this.pageSize) - - this.byteLength = this.pages.length * this.pageSize - this.length = 8 * this.byteLength - - if (!powerOfTwo(this.pageSize)) throw new Error('The page size should be a power of two') - - this._trackUpdates = !!opts.trackUpdates - this._pageMask = this.pageSize - 1 - - if (opts.buffer) { - for (var i = 0; i < opts.buffer.length; i += this.pageSize) { - this.pages.set(i / this.pageSize, opts.buffer.slice(i, i + this.pageSize)) - } - this.byteLength = opts.buffer.length - this.length = 8 * this.byteLength - } -} - -Bitfield.prototype.get = function (i) { - var o = i & 7 - var j = (i - o) / 8 - - return !!(this.getByte(j) & (128 >> o)) -} - -Bitfield.prototype.getByte = function (i) { - var o = i & this._pageMask - var j = (i - o) / this.pageSize - var page = this.pages.get(j, true) - - return page ? page.buffer[o + this.pageOffset] : 0 -} - -Bitfield.prototype.set = function (i, v) { - var o = i & 7 - var j = (i - o) / 8 - var b = this.getByte(j) - - return this.setByte(j, v ? b | (128 >> o) : b & (255 ^ (128 >> o))) -} - -Bitfield.prototype.toBuffer = function () { - var all = alloc(this.pages.length * this.pageSize) - - for (var i = 0; i < this.pages.length; i++) { - var next = this.pages.get(i, true) - var allOffset = i * this.pageSize - if (next) next.buffer.copy(all, allOffset, this.pageOffset, this.pageOffset + this.pageSize) - } - - return all -} - -Bitfield.prototype.setByte = function (i, b) { - var o = i & this._pageMask - var j = (i - o) / this.pageSize - var page = this.pages.get(j, false) - - o += this.pageOffset - - if (page.buffer[o] === b) return false - page.buffer[o] = b - - if (i >= this.byteLength) { - this.byteLength = i + 1 - this.length = this.byteLength * 8 - } - - if (this._trackUpdates) this.pages.updated(page) - - return true -} - -function alloc (n) { - if (Buffer.alloc) return Buffer.alloc(n) - var b = new Buffer(n) - b.fill(0) - return b -} - -function powerOfTwo (x) { - return !(x & (x - 1)) -} diff --git a/scripts/2.5/node_modules/sparse-bitfield/package.json b/scripts/2.5/node_modules/sparse-bitfield/package.json deleted file mode 100644 index 1df0ac00..00000000 --- a/scripts/2.5/node_modules/sparse-bitfield/package.json +++ /dev/null @@ -1,55 +0,0 @@ -{ - "_from": "sparse-bitfield@^3.0.3", - "_id": "sparse-bitfield@3.0.3", - "_inBundle": false, - "_integrity": "sha1-/0rm5oZWBWuks+eSqzM004JzyhE=", - "_location": "/sparse-bitfield", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "sparse-bitfield@^3.0.3", - "name": "sparse-bitfield", - "escapedName": "sparse-bitfield", - "rawSpec": "^3.0.3", - "saveSpec": null, - "fetchSpec": "^3.0.3" - }, - "_requiredBy": [ - "/saslprep" - ], - "_resolved": "https://registry.npmjs.org/sparse-bitfield/-/sparse-bitfield-3.0.3.tgz", - "_shasum": "ff4ae6e68656056ba4b3e792ab3334d38273ca11", - "_spec": "sparse-bitfield@^3.0.3", - "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/2.5/node_modules/saslprep", - "author": { - "name": "Mathias Buus", - "url": "@mafintosh" - }, - "bugs": { - "url": "https://github.com/mafintosh/sparse-bitfield/issues" - }, - "bundleDependencies": false, - "dependencies": { - "memory-pager": "^1.0.2" - }, - "deprecated": false, - "description": "Bitfield that allocates a series of small buffers to support sparse bits without allocating a massive buffer", - "devDependencies": { - "buffer-alloc": "^1.1.0", - "standard": "^9.0.0", - "tape": "^4.6.3" - }, - "homepage": "https://github.com/mafintosh/sparse-bitfield", - "license": "MIT", - "main": "index.js", - "name": "sparse-bitfield", - "repository": { - "type": "git", - "url": "git+https://github.com/mafintosh/sparse-bitfield.git" - }, - "scripts": { - "test": "standard && tape test.js" - }, - "version": "3.0.3" -} diff --git a/scripts/2.5/node_modules/sparse-bitfield/test.js b/scripts/2.5/node_modules/sparse-bitfield/test.js deleted file mode 100644 index ae42ef46..00000000 --- a/scripts/2.5/node_modules/sparse-bitfield/test.js +++ /dev/null @@ -1,79 +0,0 @@ -var alloc = require('buffer-alloc') -var tape = require('tape') -var bitfield = require('./') - -tape('set and get', function (t) { - var bits = bitfield() - - t.same(bits.get(0), false, 'first bit is false') - bits.set(0, true) - t.same(bits.get(0), true, 'first bit is true') - t.same(bits.get(1), false, 'second bit is false') - bits.set(0, false) - t.same(bits.get(0), false, 'first bit is reset') - t.end() -}) - -tape('set large and get', function (t) { - var bits = bitfield() - - t.same(bits.get(9999999999999), false, 'large bit is false') - bits.set(9999999999999, true) - t.same(bits.get(9999999999999), true, 'large bit is true') - t.same(bits.get(9999999999999 + 1), false, 'large bit + 1 is false') - bits.set(9999999999999, false) - t.same(bits.get(9999999999999), false, 'large bit is reset') - t.end() -}) - -tape('get and set buffer', function (t) { - var bits = bitfield({trackUpdates: true}) - - t.same(bits.pages.get(0, true), undefined) - t.same(bits.pages.get(Math.floor(9999999999999 / 8 / 1024), true), undefined) - bits.set(9999999999999, true) - - var bits2 = bitfield() - var upd = bits.pages.lastUpdate() - bits2.pages.set(Math.floor(upd.offset / 1024), upd.buffer) - t.same(bits2.get(9999999999999), true, 'bit is set') - t.end() -}) - -tape('toBuffer', function (t) { - var bits = bitfield() - - t.same(bits.toBuffer(), alloc(0)) - - bits.set(0, true) - - t.same(bits.toBuffer(), bits.pages.get(0).buffer) - - bits.set(9000, true) - - t.same(bits.toBuffer(), Buffer.concat([bits.pages.get(0).buffer, bits.pages.get(1).buffer])) - t.end() -}) - -tape('pass in buffer', function (t) { - var bits = bitfield() - - bits.set(0, true) - bits.set(9000, true) - - var clone = bitfield(bits.toBuffer()) - - t.same(clone.get(0), true) - t.same(clone.get(9000), true) - t.end() -}) - -tape('set small buffer', function (t) { - var buf = alloc(1) - buf[0] = 255 - var bits = bitfield(buf) - - t.same(bits.get(0), true) - t.same(bits.pages.get(0).buffer.length, bits.pageSize) - t.end() -}) diff --git a/scripts/2.5/node_modules/string.prototype.trimleft/.editorconfig b/scripts/2.5/node_modules/string.prototype.trimleft/.editorconfig deleted file mode 100644 index bc228f82..00000000 --- a/scripts/2.5/node_modules/string.prototype.trimleft/.editorconfig +++ /dev/null @@ -1,20 +0,0 @@ -root = true - -[*] -indent_style = tab -indent_size = 4 -end_of_line = lf -charset = utf-8 -trim_trailing_whitespace = true -insert_final_newline = true -max_line_length = 150 - -[CHANGELOG.md] -indent_style = space -indent_size = 2 - -[*.json] -max_line_length = off - -[Makefile] -max_line_length = off diff --git a/scripts/2.5/node_modules/string.prototype.trimleft/.eslintrc b/scripts/2.5/node_modules/string.prototype.trimleft/.eslintrc deleted file mode 100644 index 1fa95428..00000000 --- a/scripts/2.5/node_modules/string.prototype.trimleft/.eslintrc +++ /dev/null @@ -1,15 +0,0 @@ -{ - "root": true, - - "extends": "@ljharb", - - "overrides": [ - { - "files": "test/*", - "rules": { - "id-length": 0, - "no-invalid-this": 1, - }, - }, - ], -} diff --git a/scripts/2.5/node_modules/string.prototype.trimleft/.travis.yml b/scripts/2.5/node_modules/string.prototype.trimleft/.travis.yml deleted file mode 100644 index 87a3b02c..00000000 --- a/scripts/2.5/node_modules/string.prototype.trimleft/.travis.yml +++ /dev/null @@ -1,317 +0,0 @@ -language: node_js -os: - - linux -node_js: - - "12.10" - - "11.15" - - "10.16" - - "9.11" - - "8.16" - - "7.10" - - "6.17" - - "5.12" - - "4.9" - - "iojs-v3.3" - - "iojs-v2.5" - - "iojs-v1.8" - - "0.12" - - "0.10" - - "0.8" -before_install: - - 'case "${TRAVIS_NODE_VERSION}" in 0.*) export NPM_CONFIG_STRICT_SSL=false ;; esac' - - 'nvm install-latest-npm' -install: - - 'if [ "${TRAVIS_NODE_VERSION}" = "0.6" ] || [ "${TRAVIS_NODE_VERSION}" = "0.9" ]; then nvm install --latest-npm 0.8 && npm install && nvm use "${TRAVIS_NODE_VERSION}"; else npm install; fi;' -script: - - 'if [ -n "${PRETEST-}" ]; then npm run pretest ; fi' - - 'if [ -n "${POSTTEST-}" ]; then npm run posttest ; fi' - - 'if [ -n "${COVERAGE-}" ]; then npm run coverage ; fi' - - 'if [ -n "${TEST-}" ]; then npm run tests-only ; fi' -sudo: false -env: - - TEST=true -matrix: - fast_finish: true - include: - - node_js: "lts/*" - env: PRETEST=true - - node_js: "lts/*" - env: POSTTEST=true - - node_js: "4" - env: COVERAGE=true - - node_js: "12.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "12.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "12.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "12.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "12.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "12.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "12.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "12.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "12.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "12.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "11.14" - env: TEST=true ALLOW_FAILURE=true - - node_js: "11.13" - env: TEST=true ALLOW_FAILURE=true - - node_js: "11.12" - env: TEST=true ALLOW_FAILURE=true - - node_js: "11.11" - env: TEST=true ALLOW_FAILURE=true - - node_js: "11.10" - env: TEST=true ALLOW_FAILURE=true - - node_js: "11.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "11.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "11.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "11.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "11.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "11.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "11.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "11.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "11.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "11.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.15" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.14" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.13" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.12" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.11" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.10" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.10" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.15" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.14" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.13" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.12" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.11" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.10" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.16" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.15" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.14" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.13" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.12" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.11" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.10" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.11" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.10" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v3.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v3.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v3.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "0.11" - env: TEST=true ALLOW_FAILURE=true - - node_js: "0.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "0.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "0.4" - env: TEST=true ALLOW_FAILURE=true - allow_failures: - - os: osx - - env: TEST=true ALLOW_FAILURE=true - - env: COVERAGE=true diff --git a/scripts/2.5/node_modules/string.prototype.trimleft/CHANGELOG.md b/scripts/2.5/node_modules/string.prototype.trimleft/CHANGELOG.md deleted file mode 100644 index 535068f2..00000000 --- a/scripts/2.5/node_modules/string.prototype.trimleft/CHANGELOG.md +++ /dev/null @@ -1,30 +0,0 @@ -2.1.0 / 2019-09-09 -================= - * [New] add `auto` entry point - * [Deps] update `function-bind`, `define-properties` - * [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `covert`, `tape`, `@es-shims/api` - * [meta] clean up scripts - * [meta] Only apps should have lockfiles - * [Tests] up to `node` `v12.10`, `v11.15`, `v10.16`, `v9.11`, `v8.16`, `v7.10`, `v6.17`, `v5.10`, `v4.9`; use `nvm install-latest-npm` - * [Tests] allow a name of `trimLeft` or `trimStart` - * [Tests] fix tests for the mongolian vowel separator - * [Tests] use `functions-have-names` - * [Tests] use `npx aud` instead of `nsp` or `npm audit` with hoops - * [Tests] remove `jscs` - * [Tests] use pretest/posttest for linting/security - -2.0.0 / 2016-02-06 -================= - * [Breaking] conform to the es-shim API - * [Deps] update `define-properties` - * [Dev Deps] update `tape`, `jscs`, `nsp`, `eslint`, `@ljharb/eslint-config` - * [Tests] up to `node` `v5.5` - * [Tests] fix npm upgrades on older nodes - -1.0.1 / 2015-07-29 -================= - * Fix deps mistakenly being dev deps - -1.0.0 / 2015-07-29 -================= - * v1.0.0 diff --git a/scripts/2.5/node_modules/string.prototype.trimleft/LICENSE b/scripts/2.5/node_modules/string.prototype.trimleft/LICENSE deleted file mode 100644 index b43df444..00000000 --- a/scripts/2.5/node_modules/string.prototype.trimleft/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015 Jordan Harband - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - diff --git a/scripts/2.5/node_modules/string.prototype.trimleft/README.md b/scripts/2.5/node_modules/string.prototype.trimleft/README.md deleted file mode 100644 index bd3f82f9..00000000 --- a/scripts/2.5/node_modules/string.prototype.trimleft/README.md +++ /dev/null @@ -1,47 +0,0 @@ -String.prototype.trimLeft [![Version Badge][npm-version-svg]][package-url] - -[![Build Status][travis-svg]][travis-url] -[![dependency status][deps-svg]][deps-url] -[![dev dependency status][dev-deps-svg]][dev-deps-url] -[![License][license-image]][license-url] -[![Downloads][downloads-image]][downloads-url] - -[![npm badge][npm-badge-png]][package-url] - -[![browser support][testling-svg]][testling-url] - -A spec-proposal-compliant `String.prototype.trimLeft` shim. Invoke its "shim" method to shim `String.prototype.trimLeft` if it is unavailable. - -This package implements the [es-shim API](https://github.com/es-shims/api) interface. It works in an ES3-supported environment and complies with the [spec](http://www.ecma-international.org/ecma-262/6.0/#sec-object.assign). In an ES6 environment, it will also work properly with `Symbol`s. - -Most common usage: -```js -var trimLeft = require('string.prototype.trimleft'); - -assert(trimLeft(' \t\na \t\n') === 'a \t\n'); - -if (!String.prototype.trimLeft) { - trimLeft.shim(); -} - -assert(trimLeft(' \t\na \t\n') === ' \t\na \t\n'.trimLeft()); -``` - -## Tests -Simply clone the repo, `npm install`, and run `npm test` - -[package-url]: https://npmjs.com/package/string.prototype.trimleft -[npm-version-svg]: http://vb.teelaun.ch/es-shims/String.prototype.trimLeft.svg -[travis-svg]: https://travis-ci.org/es-shims/String.prototype.trimLeft.svg -[travis-url]: https://travis-ci.org/es-shims/String.prototype.trimLeft -[deps-svg]: https://david-dm.org/es-shims/String.prototype.trimLeft.svg -[deps-url]: https://david-dm.org/es-shims/String.prototype.trimLeft -[dev-deps-svg]: https://david-dm.org/es-shims/String.prototype.trimLeft/dev-status.svg -[dev-deps-url]: https://david-dm.org/es-shims/String.prototype.trimLeft#info=devDependencies -[testling-svg]: https://ci.testling.com/es-shims/String.prototype.trimLeft.png -[testling-url]: https://ci.testling.com/es-shims/String.prototype.trimLeft -[npm-badge-png]: https://nodei.co/npm/string.prototype.trimleft.png?downloads=true&stars=true -[license-image]: http://img.shields.io/npm/l/string.prototype.trimleft.svg -[license-url]: LICENSE -[downloads-image]: http://img.shields.io/npm/dm/string.prototype.trimleft.svg -[downloads-url]: http://npm-stat.com/charts.html?package=string.prototype.trimleft diff --git a/scripts/2.5/node_modules/string.prototype.trimleft/auto.js b/scripts/2.5/node_modules/string.prototype.trimleft/auto.js deleted file mode 100644 index 8ebf606c..00000000 --- a/scripts/2.5/node_modules/string.prototype.trimleft/auto.js +++ /dev/null @@ -1,3 +0,0 @@ -'use strict'; - -require('./shim')(); diff --git a/scripts/2.5/node_modules/string.prototype.trimleft/implementation.js b/scripts/2.5/node_modules/string.prototype.trimleft/implementation.js deleted file mode 100644 index 5df533ea..00000000 --- a/scripts/2.5/node_modules/string.prototype.trimleft/implementation.js +++ /dev/null @@ -1,12 +0,0 @@ -'use strict'; - -var bind = require('function-bind'); -var replace = bind.call(Function.call, String.prototype.replace); - -/* eslint-disable no-control-regex */ -var leftWhitespace = /^[\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF]*/; -/* eslint-enable no-control-regex */ - -module.exports = function trimLeft() { - return replace(this, leftWhitespace, ''); -}; diff --git a/scripts/2.5/node_modules/string.prototype.trimleft/index.js b/scripts/2.5/node_modules/string.prototype.trimleft/index.js deleted file mode 100644 index 7fe48cf5..00000000 --- a/scripts/2.5/node_modules/string.prototype.trimleft/index.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; - -var bind = require('function-bind'); -var define = require('define-properties'); - -var implementation = require('./implementation'); -var getPolyfill = require('./polyfill'); -var shim = require('./shim'); - -var bound = bind.call(Function.call, getPolyfill()); - -define(bound, { - getPolyfill: getPolyfill, - implementation: implementation, - shim: shim -}); - -module.exports = bound; diff --git a/scripts/2.5/node_modules/string.prototype.trimleft/package.json b/scripts/2.5/node_modules/string.prototype.trimleft/package.json deleted file mode 100644 index e5a3ea3b..00000000 --- a/scripts/2.5/node_modules/string.prototype.trimleft/package.json +++ /dev/null @@ -1,97 +0,0 @@ -{ - "_from": "string.prototype.trimleft@^2.1.0", - "_id": "string.prototype.trimleft@2.1.0", - "_inBundle": false, - "_integrity": "sha512-FJ6b7EgdKxxbDxc79cOlok6Afd++TTs5szo+zJTUyow3ycrRfJVE2pq3vcN53XexvKZu/DJMDfeI/qMiZTrjTw==", - "_location": "/string.prototype.trimleft", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "string.prototype.trimleft@^2.1.0", - "name": "string.prototype.trimleft", - "escapedName": "string.prototype.trimleft", - "rawSpec": "^2.1.0", - "saveSpec": null, - "fetchSpec": "^2.1.0" - }, - "_requiredBy": [ - "/es-abstract" - ], - "_resolved": "https://registry.npmjs.org/string.prototype.trimleft/-/string.prototype.trimleft-2.1.0.tgz", - "_shasum": "6cc47f0d7eb8d62b0f3701611715a3954591d634", - "_spec": "string.prototype.trimleft@^2.1.0", - "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/2.5/node_modules/es-abstract", - "author": { - "name": "Jordan Harband" - }, - "bugs": { - "url": "https://github.com/es-shims/String.prototype.trimLeft/issues" - }, - "bundleDependencies": false, - "dependencies": { - "define-properties": "^1.1.3", - "function-bind": "^1.1.1" - }, - "deprecated": false, - "description": "ES7 spec-compliant String.prototype.trimLeft shim.", - "devDependencies": { - "@es-shims/api": "^2.1.2", - "@ljharb/eslint-config": "^14.1.0", - "covert": "^1.1.1", - "eslint": "^6.3.0", - "functions-have-names": "^1.1.1", - "tape": "^4.11.0" - }, - "engines": { - "node": ">= 0.4" - }, - "homepage": "https://github.com/es-shims/String.prototype.trimLeft#readme", - "keywords": [ - "String.prototype.trimLeft", - "string", - "ES7", - "shim", - "trim", - "trimLeft", - "trimRight", - "polyfill", - "es-shim API" - ], - "license": "MIT", - "main": "index.js", - "name": "string.prototype.trimleft", - "repository": { - "type": "git", - "url": "git://github.com/es-shims/String.prototype.trimLeft.git" - }, - "scripts": { - "coverage": "covert test/*.js", - "lint": "eslint .", - "posttest": "npx aud", - "pretest": "npm run lint && es-shim-api --bound", - "test": "npm run tests-only", - "test:module": "node test", - "test:shimmed": "node test/shimmed", - "tests-only": "npm run --silent test:shimmed && npm run --silent test:module" - }, - "testling": { - "files": "test/index.js", - "browsers": [ - "iexplore/9.0..latest", - "firefox/4.0..6.0", - "firefox/15.0..latest", - "firefox/nightly", - "chrome/4.0..10.0", - "chrome/20.0..latest", - "chrome/canary", - "opera/11.6..latest", - "opera/next", - "safari/5.0..latest", - "ipad/6.0..latest", - "iphone/6.0..latest", - "android-browser/4.2" - ] - }, - "version": "2.1.0" -} diff --git a/scripts/2.5/node_modules/string.prototype.trimleft/polyfill.js b/scripts/2.5/node_modules/string.prototype.trimleft/polyfill.js deleted file mode 100644 index dc33a23e..00000000 --- a/scripts/2.5/node_modules/string.prototype.trimleft/polyfill.js +++ /dev/null @@ -1,14 +0,0 @@ -'use strict'; - -var implementation = require('./implementation'); - -module.exports = function getPolyfill() { - if (!String.prototype.trimLeft) { - return implementation; - } - var zeroWidthSpace = '\u200b'; - if (zeroWidthSpace.trimLeft() !== zeroWidthSpace) { - return implementation; - } - return String.prototype.trimLeft; -}; diff --git a/scripts/2.5/node_modules/string.prototype.trimleft/shim.js b/scripts/2.5/node_modules/string.prototype.trimleft/shim.js deleted file mode 100644 index 23314f04..00000000 --- a/scripts/2.5/node_modules/string.prototype.trimleft/shim.js +++ /dev/null @@ -1,14 +0,0 @@ -'use strict'; - -var define = require('define-properties'); -var getPolyfill = require('./polyfill'); - -module.exports = function shimTrimLeft() { - var polyfill = getPolyfill(); - define( - String.prototype, - { trimLeft: polyfill }, - { trimLeft: function () { return String.prototype.trimLeft !== polyfill; } } - ); - return polyfill; -}; diff --git a/scripts/2.5/node_modules/string.prototype.trimleft/test/index.js b/scripts/2.5/node_modules/string.prototype.trimleft/test/index.js deleted file mode 100644 index 99795074..00000000 --- a/scripts/2.5/node_modules/string.prototype.trimleft/test/index.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; - -var trimLeft = require('../'); -var test = require('tape'); - -var runTests = require('./tests'); - -test('as a function', function (t) { - t.test('bad array/this value', function (st) { - st['throws'](function () { trimLeft(undefined, 'a'); }, TypeError, 'undefined is not an object'); - st['throws'](function () { trimLeft(null, 'a'); }, TypeError, 'null is not an object'); - st.end(); - }); - - runTests(trimLeft, t); - - t.end(); -}); diff --git a/scripts/2.5/node_modules/string.prototype.trimleft/test/shimmed.js b/scripts/2.5/node_modules/string.prototype.trimleft/test/shimmed.js deleted file mode 100644 index c2ebfd43..00000000 --- a/scripts/2.5/node_modules/string.prototype.trimleft/test/shimmed.js +++ /dev/null @@ -1,37 +0,0 @@ -'use strict'; - -var trimLeft = require('../'); -trimLeft.shim(); - -var runTests = require('./tests'); - -var test = require('tape'); -var defineProperties = require('define-properties'); -var bind = require('function-bind'); -var isEnumerable = Object.prototype.propertyIsEnumerable; -var functionsHaveNames = require('functions-have-names')(); - -test('shimmed', function (t) { - t.equal(String.prototype.trimLeft.length, 0, 'String#trimLeft has a length of 0'); - t.test('Function name', { skip: !functionsHaveNames }, function (st) { - st.equal((/^(?:trimLeft|trimStart)$/).test(String.prototype.trimLeft.name), true, 'String#trimLeft has name "trimLeft" or "trimStart"'); - st.end(); - }); - - t.test('enumerability', { skip: !defineProperties.supportsDescriptors }, function (et) { - et.equal(false, isEnumerable.call(String.prototype, 'trimLeft'), 'String#trimLeft is not enumerable'); - et.end(); - }); - - var supportsStrictMode = (function () { return typeof this === 'undefined'; }()); - - t.test('bad string/this value', { skip: !supportsStrictMode }, function (st) { - st['throws'](function () { return trimLeft(undefined, 'a'); }, TypeError, 'undefined is not an object'); - st['throws'](function () { return trimLeft(null, 'a'); }, TypeError, 'null is not an object'); - st.end(); - }); - - runTests(bind.call(Function.call, String.prototype.trimLeft), t); - - t.end(); -}); diff --git a/scripts/2.5/node_modules/string.prototype.trimleft/test/tests.js b/scripts/2.5/node_modules/string.prototype.trimleft/test/tests.js deleted file mode 100644 index fe7926ac..00000000 --- a/scripts/2.5/node_modules/string.prototype.trimleft/test/tests.js +++ /dev/null @@ -1,26 +0,0 @@ -'use strict'; - -module.exports = function (trimLeft, t) { - t.test('normal cases', function (st) { - st.equal(trimLeft(' \t\na \t\n'), 'a \t\n', 'strips whitespace off the left side'); - st.equal(trimLeft('a'), 'a', 'noop when no whitespace'); - - var allWhitespaceChars = '\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF'; - st.equal(trimLeft(allWhitespaceChars + 'a' + allWhitespaceChars), 'a' + allWhitespaceChars, 'all expected whitespace chars are trimmed'); - - st.end(); - }); - - // see https://codeblog.jonskeet.uk/2014/12/01/when-is-an-identifier-not-an-identifier-attack-of-the-mongolian-vowel-separator/ - var mongolianVowelSeparator = '\u180E'; - t.test('unicode >= 4 && < 6.3', { skip: !(/^\s$/).test(mongolianVowelSeparator) }, function (st) { - st.equal(trimLeft(mongolianVowelSeparator + 'a' + mongolianVowelSeparator), 'a' + mongolianVowelSeparator, 'mongolian vowel separator is whitespace'); - st.end(); - }); - - t.test('zero-width spaces', function (st) { - var zeroWidth = '\u200b'; - st.equal(trimLeft(zeroWidth), zeroWidth, 'zero width space does not trim'); - st.end(); - }); -}; diff --git a/scripts/2.5/node_modules/string.prototype.trimright/.editorconfig b/scripts/2.5/node_modules/string.prototype.trimright/.editorconfig deleted file mode 100644 index bc228f82..00000000 --- a/scripts/2.5/node_modules/string.prototype.trimright/.editorconfig +++ /dev/null @@ -1,20 +0,0 @@ -root = true - -[*] -indent_style = tab -indent_size = 4 -end_of_line = lf -charset = utf-8 -trim_trailing_whitespace = true -insert_final_newline = true -max_line_length = 150 - -[CHANGELOG.md] -indent_style = space -indent_size = 2 - -[*.json] -max_line_length = off - -[Makefile] -max_line_length = off diff --git a/scripts/2.5/node_modules/string.prototype.trimright/.eslintrc b/scripts/2.5/node_modules/string.prototype.trimright/.eslintrc deleted file mode 100644 index 1fa95428..00000000 --- a/scripts/2.5/node_modules/string.prototype.trimright/.eslintrc +++ /dev/null @@ -1,15 +0,0 @@ -{ - "root": true, - - "extends": "@ljharb", - - "overrides": [ - { - "files": "test/*", - "rules": { - "id-length": 0, - "no-invalid-this": 1, - }, - }, - ], -} diff --git a/scripts/2.5/node_modules/string.prototype.trimright/.travis.yml b/scripts/2.5/node_modules/string.prototype.trimright/.travis.yml deleted file mode 100644 index 87a3b02c..00000000 --- a/scripts/2.5/node_modules/string.prototype.trimright/.travis.yml +++ /dev/null @@ -1,317 +0,0 @@ -language: node_js -os: - - linux -node_js: - - "12.10" - - "11.15" - - "10.16" - - "9.11" - - "8.16" - - "7.10" - - "6.17" - - "5.12" - - "4.9" - - "iojs-v3.3" - - "iojs-v2.5" - - "iojs-v1.8" - - "0.12" - - "0.10" - - "0.8" -before_install: - - 'case "${TRAVIS_NODE_VERSION}" in 0.*) export NPM_CONFIG_STRICT_SSL=false ;; esac' - - 'nvm install-latest-npm' -install: - - 'if [ "${TRAVIS_NODE_VERSION}" = "0.6" ] || [ "${TRAVIS_NODE_VERSION}" = "0.9" ]; then nvm install --latest-npm 0.8 && npm install && nvm use "${TRAVIS_NODE_VERSION}"; else npm install; fi;' -script: - - 'if [ -n "${PRETEST-}" ]; then npm run pretest ; fi' - - 'if [ -n "${POSTTEST-}" ]; then npm run posttest ; fi' - - 'if [ -n "${COVERAGE-}" ]; then npm run coverage ; fi' - - 'if [ -n "${TEST-}" ]; then npm run tests-only ; fi' -sudo: false -env: - - TEST=true -matrix: - fast_finish: true - include: - - node_js: "lts/*" - env: PRETEST=true - - node_js: "lts/*" - env: POSTTEST=true - - node_js: "4" - env: COVERAGE=true - - node_js: "12.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "12.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "12.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "12.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "12.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "12.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "12.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "12.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "12.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "12.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "11.14" - env: TEST=true ALLOW_FAILURE=true - - node_js: "11.13" - env: TEST=true ALLOW_FAILURE=true - - node_js: "11.12" - env: TEST=true ALLOW_FAILURE=true - - node_js: "11.11" - env: TEST=true ALLOW_FAILURE=true - - node_js: "11.10" - env: TEST=true ALLOW_FAILURE=true - - node_js: "11.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "11.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "11.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "11.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "11.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "11.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "11.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "11.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "11.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "11.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.15" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.14" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.13" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.12" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.11" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.10" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "10.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.10" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "9.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.15" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.14" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.13" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.12" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.11" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.10" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "8.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "7.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.16" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.15" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.14" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.13" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.12" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.11" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.10" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "6.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.11" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.10" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "5.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.8" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "4.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v3.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v3.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v3.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v2.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.7" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.5" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.4" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.3" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.2" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.1" - env: TEST=true ALLOW_FAILURE=true - - node_js: "iojs-v1.0" - env: TEST=true ALLOW_FAILURE=true - - node_js: "0.11" - env: TEST=true ALLOW_FAILURE=true - - node_js: "0.9" - env: TEST=true ALLOW_FAILURE=true - - node_js: "0.6" - env: TEST=true ALLOW_FAILURE=true - - node_js: "0.4" - env: TEST=true ALLOW_FAILURE=true - allow_failures: - - os: osx - - env: TEST=true ALLOW_FAILURE=true - - env: COVERAGE=true diff --git a/scripts/2.5/node_modules/string.prototype.trimright/CHANGELOG.md b/scripts/2.5/node_modules/string.prototype.trimright/CHANGELOG.md deleted file mode 100644 index 535068f2..00000000 --- a/scripts/2.5/node_modules/string.prototype.trimright/CHANGELOG.md +++ /dev/null @@ -1,30 +0,0 @@ -2.1.0 / 2019-09-09 -================= - * [New] add `auto` entry point - * [Deps] update `function-bind`, `define-properties` - * [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `covert`, `tape`, `@es-shims/api` - * [meta] clean up scripts - * [meta] Only apps should have lockfiles - * [Tests] up to `node` `v12.10`, `v11.15`, `v10.16`, `v9.11`, `v8.16`, `v7.10`, `v6.17`, `v5.10`, `v4.9`; use `nvm install-latest-npm` - * [Tests] allow a name of `trimLeft` or `trimStart` - * [Tests] fix tests for the mongolian vowel separator - * [Tests] use `functions-have-names` - * [Tests] use `npx aud` instead of `nsp` or `npm audit` with hoops - * [Tests] remove `jscs` - * [Tests] use pretest/posttest for linting/security - -2.0.0 / 2016-02-06 -================= - * [Breaking] conform to the es-shim API - * [Deps] update `define-properties` - * [Dev Deps] update `tape`, `jscs`, `nsp`, `eslint`, `@ljharb/eslint-config` - * [Tests] up to `node` `v5.5` - * [Tests] fix npm upgrades on older nodes - -1.0.1 / 2015-07-29 -================= - * Fix deps mistakenly being dev deps - -1.0.0 / 2015-07-29 -================= - * v1.0.0 diff --git a/scripts/2.5/node_modules/string.prototype.trimright/LICENSE b/scripts/2.5/node_modules/string.prototype.trimright/LICENSE deleted file mode 100644 index b43df444..00000000 --- a/scripts/2.5/node_modules/string.prototype.trimright/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015 Jordan Harband - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - diff --git a/scripts/2.5/node_modules/string.prototype.trimright/README.md b/scripts/2.5/node_modules/string.prototype.trimright/README.md deleted file mode 100644 index 6d736f50..00000000 --- a/scripts/2.5/node_modules/string.prototype.trimright/README.md +++ /dev/null @@ -1,47 +0,0 @@ -String.prototype.trimRight [![Version Badge][npm-version-svg]][package-url] - -[![Build Status][travis-svg]][travis-url] -[![dependency status][deps-svg]][deps-url] -[![dev dependency status][dev-deps-svg]][dev-deps-url] -[![License][license-image]][license-url] -[![Downloads][downloads-image]][downloads-url] - -[![npm badge][npm-badge-png]][package-url] - -[![browser support][testling-svg]][testling-url] - -A spec-proposal-compliant `String.prototype.trimRight` shim. Invoke its "shim" method to shim `String.prototype.trimRight` if it is unavailable. - -This package implements the [es-shim API](https://github.com/es-shims/api) interface. It works in an ES3-supported environment and complies with the [spec](http://www.ecma-international.org/ecma-262/6.0/#sec-object.assign). In an ES6 environment, it will also work properly with `Symbol`s. - -Most common usage: -```js -var trimRight = require('string.prototype.trimright'); - -assert(trimRight(' \t\na \t\n') === 'a \t\n'); - -if (!String.prototype.trimRight) { - trimRight.shim(); -} - -assert(trimRight(' \t\na \t\n ') === ' \t\na \t\n '.trimRight()); -``` - -## Tests -Simply clone the repo, `npm install`, and run `npm test` - -[package-url]: https://npmjs.com/package/string.prototype.trimright -[npm-version-svg]: http://vb.teelaun.ch/es-shims/String.prototype.trimRight.svg -[travis-svg]: https://travis-ci.org/es-shims/String.prototype.trimRight.svg -[travis-url]: https://travis-ci.org/es-shims/String.prototype.trimRight -[deps-svg]: https://david-dm.org/es-shims/String.prototype.trimRight.svg -[deps-url]: https://david-dm.org/es-shims/String.prototype.trimRight -[dev-deps-svg]: https://david-dm.org/es-shims/String.prototype.trimRight/dev-status.svg -[dev-deps-url]: https://david-dm.org/es-shims/String.prototype.trimRight#info=devDependencies -[testling-svg]: https://ci.testling.com/es-shims/String.prototype.trimRight.png -[testling-url]: https://ci.testling.com/es-shims/String.prototype.trimRight -[npm-badge-png]: https://nodei.co/npm/string.prototype.trimright.png?downloads=true&stars=true -[license-image]: http://img.shields.io/npm/l/string.prototype.trimright.svg -[license-url]: LICENSE -[downloads-image]: http://img.shields.io/npm/dm/string.prototype.trimright.svg -[downloads-url]: http://npm-stat.com/charts.html?package=string.prototype.trimright diff --git a/scripts/2.5/node_modules/string.prototype.trimright/auto.js b/scripts/2.5/node_modules/string.prototype.trimright/auto.js deleted file mode 100644 index 8ebf606c..00000000 --- a/scripts/2.5/node_modules/string.prototype.trimright/auto.js +++ /dev/null @@ -1,3 +0,0 @@ -'use strict'; - -require('./shim')(); diff --git a/scripts/2.5/node_modules/string.prototype.trimright/implementation.js b/scripts/2.5/node_modules/string.prototype.trimright/implementation.js deleted file mode 100644 index ce995545..00000000 --- a/scripts/2.5/node_modules/string.prototype.trimright/implementation.js +++ /dev/null @@ -1,12 +0,0 @@ -'use strict'; - -var bind = require('function-bind'); -var replace = bind.call(Function.call, String.prototype.replace); - -/* eslint-disable no-control-regex */ -var rightWhitespace = /[\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF]*$/; -/* eslint-enable no-control-regex */ - -module.exports = function trimRight() { - return replace(this, rightWhitespace, ''); -}; diff --git a/scripts/2.5/node_modules/string.prototype.trimright/index.js b/scripts/2.5/node_modules/string.prototype.trimright/index.js deleted file mode 100644 index 7fe48cf5..00000000 --- a/scripts/2.5/node_modules/string.prototype.trimright/index.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; - -var bind = require('function-bind'); -var define = require('define-properties'); - -var implementation = require('./implementation'); -var getPolyfill = require('./polyfill'); -var shim = require('./shim'); - -var bound = bind.call(Function.call, getPolyfill()); - -define(bound, { - getPolyfill: getPolyfill, - implementation: implementation, - shim: shim -}); - -module.exports = bound; diff --git a/scripts/2.5/node_modules/string.prototype.trimright/package.json b/scripts/2.5/node_modules/string.prototype.trimright/package.json deleted file mode 100644 index 38dfc66d..00000000 --- a/scripts/2.5/node_modules/string.prototype.trimright/package.json +++ /dev/null @@ -1,97 +0,0 @@ -{ - "_from": "string.prototype.trimright@^2.1.0", - "_id": "string.prototype.trimright@2.1.0", - "_inBundle": false, - "_integrity": "sha512-fXZTSV55dNBwv16uw+hh5jkghxSnc5oHq+5K/gXgizHwAvMetdAJlHqqoFC1FSDVPYWLkAKl2cxpUT41sV7nSg==", - "_location": "/string.prototype.trimright", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "string.prototype.trimright@^2.1.0", - "name": "string.prototype.trimright", - "escapedName": "string.prototype.trimright", - "rawSpec": "^2.1.0", - "saveSpec": null, - "fetchSpec": "^2.1.0" - }, - "_requiredBy": [ - "/es-abstract" - ], - "_resolved": "https://registry.npmjs.org/string.prototype.trimright/-/string.prototype.trimright-2.1.0.tgz", - "_shasum": "669d164be9df9b6f7559fa8e89945b168a5a6c58", - "_spec": "string.prototype.trimright@^2.1.0", - "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/2.5/node_modules/es-abstract", - "author": { - "name": "Jordan Harband" - }, - "bugs": { - "url": "https://github.com/es-shims/String.prototype.trimRight/issues" - }, - "bundleDependencies": false, - "dependencies": { - "define-properties": "^1.1.3", - "function-bind": "^1.1.1" - }, - "deprecated": false, - "description": "ES7 spec-compliant String.prototype.trimRight shim.", - "devDependencies": { - "@es-shims/api": "^2.1.2", - "@ljharb/eslint-config": "^14.1.0", - "covert": "^1.1.1", - "eslint": "^6.3.0", - "functions-have-names": "^1.1.1", - "tape": "^4.11.0" - }, - "engines": { - "node": ">= 0.4" - }, - "homepage": "https://github.com/es-shims/String.prototype.trimRight#readme", - "keywords": [ - "String.prototype.trimRight", - "string", - "ES7", - "shim", - "trim", - "trimLeft", - "trimRight", - "polyfill", - "es-shim API" - ], - "license": "MIT", - "main": "index.js", - "name": "string.prototype.trimright", - "repository": { - "type": "git", - "url": "git://github.com/es-shims/String.prototype.trimRight.git" - }, - "scripts": { - "coverage": "covert test/*.js", - "lint": "eslint .", - "posttest": "npx aud", - "pretest": "npm run lint && es-shim-api --bound", - "test": "npm run tests-only", - "test:module": "node test", - "test:shimmed": "node test/shimmed", - "tests-only": "npm run test:shimmed && npm run test:module" - }, - "testling": { - "files": "test/index.js", - "browsers": [ - "iexplore/9.0..latest", - "firefox/4.0..6.0", - "firefox/15.0..latest", - "firefox/nightly", - "chrome/4.0..10.0", - "chrome/20.0..latest", - "chrome/canary", - "opera/11.6..latest", - "opera/next", - "safari/5.0..latest", - "ipad/6.0..latest", - "iphone/6.0..latest", - "android-browser/4.2" - ] - }, - "version": "2.1.0" -} diff --git a/scripts/2.5/node_modules/string.prototype.trimright/polyfill.js b/scripts/2.5/node_modules/string.prototype.trimright/polyfill.js deleted file mode 100644 index 7c2aa99b..00000000 --- a/scripts/2.5/node_modules/string.prototype.trimright/polyfill.js +++ /dev/null @@ -1,14 +0,0 @@ -'use strict'; - -var implementation = require('./implementation'); - -module.exports = function getPolyfill() { - if (!String.prototype.trimRight) { - return implementation; - } - var zeroWidthSpace = '\u200b'; - if (zeroWidthSpace.trimRight() !== zeroWidthSpace) { - return implementation; - } - return String.prototype.trimRight; -}; diff --git a/scripts/2.5/node_modules/string.prototype.trimright/shim.js b/scripts/2.5/node_modules/string.prototype.trimright/shim.js deleted file mode 100644 index e073afec..00000000 --- a/scripts/2.5/node_modules/string.prototype.trimright/shim.js +++ /dev/null @@ -1,14 +0,0 @@ -'use strict'; - -var define = require('define-properties'); -var getPolyfill = require('./polyfill'); - -module.exports = function shimTrimRight() { - var polyfill = getPolyfill(); - define( - String.prototype, - { trimRight: polyfill }, - { trimRight: function () { return String.prototype.trimRight !== polyfill; } } - ); - return polyfill; -}; diff --git a/scripts/2.5/node_modules/string.prototype.trimright/test/index.js b/scripts/2.5/node_modules/string.prototype.trimright/test/index.js deleted file mode 100644 index 84e5e3df..00000000 --- a/scripts/2.5/node_modules/string.prototype.trimright/test/index.js +++ /dev/null @@ -1,17 +0,0 @@ -'use strict'; - -var trimRight = require('../'); -var test = require('tape'); -var runTests = require('./tests'); - -test('as a function', function (t) { - t.test('bad array/this value', function (st) { - st['throws'](function () { trimRight(undefined, 'a'); }, TypeError, 'undefined is not an object'); - st['throws'](function () { trimRight(null, 'a'); }, TypeError, 'null is not an object'); - st.end(); - }); - - runTests(trimRight, t); - - t.end(); -}); diff --git a/scripts/2.5/node_modules/string.prototype.trimright/test/shimmed.js b/scripts/2.5/node_modules/string.prototype.trimright/test/shimmed.js deleted file mode 100644 index 92287efd..00000000 --- a/scripts/2.5/node_modules/string.prototype.trimright/test/shimmed.js +++ /dev/null @@ -1,37 +0,0 @@ -'use strict'; - -var trimRight = require('../'); -trimRight.shim(); - -var runTests = require('./tests'); - -var test = require('tape'); -var defineProperties = require('define-properties'); -var bind = require('function-bind'); -var isEnumerable = Object.prototype.propertyIsEnumerable; -var functionsHaveNames = require('functions-have-names')(); - -test('shimmed', function (t) { - t.equal(String.prototype.trimRight.length, 0, 'String#trimRight has a length of 0'); - t.test('Function name', { skip: !functionsHaveNames }, function (st) { - st.equal((/^(?:trimRight|trimEnd)$/).test(String.prototype.trimRight.name), true, 'String#trimRight has name "trimRight" or "trimEnd"'); - st.end(); - }); - - t.test('enumerability', { skip: !defineProperties.supportsDescriptors }, function (et) { - et.equal(false, isEnumerable.call(String.prototype, 'trimRight'), 'String#trimRight is not enumerable'); - et.end(); - }); - - var supportsStrictMode = (function () { return typeof this === 'undefined'; }()); - - t.test('bad string/this value', { skip: !supportsStrictMode }, function (st) { - st['throws'](function () { return trimRight(undefined, 'a'); }, TypeError, 'undefined is not an object'); - st['throws'](function () { return trimRight(null, 'a'); }, TypeError, 'null is not an object'); - st.end(); - }); - - runTests(bind.call(Function.call, String.prototype.trimRight), t); - - t.end(); -}); diff --git a/scripts/2.5/node_modules/string.prototype.trimright/test/tests.js b/scripts/2.5/node_modules/string.prototype.trimright/test/tests.js deleted file mode 100644 index b62a413d..00000000 --- a/scripts/2.5/node_modules/string.prototype.trimright/test/tests.js +++ /dev/null @@ -1,26 +0,0 @@ -'use strict'; - -module.exports = function (trimRight, t) { - t.test('normal cases', function (st) { - st.equal(trimRight(' \t\na \t\n'), ' \t\na', 'strips whitespace off the left side'); - st.equal(trimRight('a'), 'a', 'noop when no whitespace'); - - var allWhitespaceChars = '\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF'; - st.equal(trimRight(allWhitespaceChars + 'a' + allWhitespaceChars), allWhitespaceChars + 'a', 'all expected whitespace chars are trimmed'); - - st.end(); - }); - - // see https://codeblog.jonskeet.uk/2014/12/01/when-is-an-identifier-not-an-identifier-attack-of-the-mongolian-vowel-separator/ - var mongolianVowelSeparator = '\u180E'; - t.test('unicode >= 4 && < 6.3', { skip: !(/^\s$/).test(mongolianVowelSeparator) }, function (st) { - st.equal(trimRight(mongolianVowelSeparator + 'a' + mongolianVowelSeparator), mongolianVowelSeparator + 'a', 'mongolian vowel separator is whitespace'); - st.end(); - }); - - t.test('zero-width spaces', function (st) { - var zeroWidth = '\u200b'; - st.equal(trimRight(zeroWidth), zeroWidth, 'zero width space does not trim'); - st.end(); - }); -}; diff --git a/scripts/2.5/node_modules/util/CHANGELOG.md b/scripts/2.5/node_modules/util/CHANGELOG.md deleted file mode 100644 index c96019f7..00000000 --- a/scripts/2.5/node_modules/util/CHANGELOG.md +++ /dev/null @@ -1,22 +0,0 @@ -# util change log - -All notable changes to this project will be documented in this file. - -This project adheres to [Semantic Versioning](http://semver.org/). - -## 0.12.1 -* Update `util.debuglog` compatibility to Node 10.4.0. ([@goto-bus-stop](https://github.com/goto-bus-stop) in [#27](https://github.com/browserify/node-util/pull/27)) -* Allow newer versions of `inherits`. ([@snyamathi](https://github.com/snyamathi) in [#39](https://github.com/browserify/node-util/pull/39)) - -## 0.12.0 -* Add `util.types`. ([@lukechilds](https://github.com/lukechilds) in [#32](https://github.com/browserify/node-util/pull/35)) - -## 0.11.1 -* Fix an infinite loop in `util.deprecate` some build configurations. ([@bernardmcmanus](https://github.com/bernardmcmanus) in [#12](https://github.com/browserify/node-util/pull/12)) - -## 0.11.0 -* Add `util.promisify`. -* Add `util.callbackify`. - -## 0.10.4 -* Update `inherits` dependency. diff --git a/scripts/2.5/node_modules/util/LICENSE b/scripts/2.5/node_modules/util/LICENSE deleted file mode 100644 index e3d4e695..00000000 --- a/scripts/2.5/node_modules/util/LICENSE +++ /dev/null @@ -1,18 +0,0 @@ -Copyright Joyent, Inc. and other Node contributors. All rights reserved. -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to -deal in the Software without restriction, including without limitation the -rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -sell copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -IN THE SOFTWARE. diff --git a/scripts/2.5/node_modules/util/README.md b/scripts/2.5/node_modules/util/README.md deleted file mode 100644 index eb630582..00000000 --- a/scripts/2.5/node_modules/util/README.md +++ /dev/null @@ -1,48 +0,0 @@ -# util [![Build Status](https://travis-ci.org/browserify/node-util.png?branch=master)](https://travis-ci.org/browserify/node-util) - -> Node.js's [util][util] module for all engines. - -This implements the Node.js [`util`][util] module for environments that do not have it, like browsers. - -## Install - -You usually do not have to install `util` yourself. If your code runs in Node.js, `util` is built in. If your code runs in the browser, bundlers like [browserify](https://github.com/browserify/browserify) or [webpack](https://github.com/webpack/webpack) also include the `util` module. - -But if none of those apply, with npm do: - -```shell -npm install util -``` - -## Usage - -```javascript -var util = require('util') -var EventEmitter = require('events') - -function MyClass() { EventEmitter.call(this) } -util.inherits(MyClass, EventEmitter) -``` - -## Browser Support - -The `util` module uses ES5 features. If you need to support very old browsers like IE8, use a shim like [`es5-shim`](https://www.npmjs.com/package/es5-shim). You need both the shim and the sham versions of `es5-shim`. - -To use `util.promisify` and `util.callbackify`, Promises must already be available. If you need to support browsers like IE11 that do not support Promises, use a shim. [es6-promise](https://github.com/stefanpenner/es6-promise) is a popular one but there are many others available on npm. - -## API - -See the [Node.js util docs][util]. `util` currently supports the Node 8 LTS API. However, some of the methods are outdated. The `inspect` and `format` methods included in this module are a lot more simple and barebones than the ones in Node.js. - -## Contributing - -PRs are very welcome! The main way to contribute to `util` is by porting features, bugfixes and tests from Node.js. Ideally, code contributions to this module are copy-pasted from Node.js and transpiled to ES5, rather than reimplemented from scratch. Matching the Node.js code as closely as possible makes maintenance simpler when new changes land in Node.js. -This module intends to provide exactly the same API as Node.js, so features that are not available in the core `util` module will not be accepted. Feature requests should instead be directed at [nodejs/node](https://github.com/nodejs/node) and will be added to this module once they are implemented in Node.js. - -If there is a difference in behaviour between Node.js's `util` module and this module, please open an issue! - -## License - -[MIT](./LICENSE) - -[util]: https://nodejs.org/docs/latest-v8.x/api/util.html diff --git a/scripts/2.5/node_modules/util/package.json b/scripts/2.5/node_modules/util/package.json deleted file mode 100644 index 4feaba66..00000000 --- a/scripts/2.5/node_modules/util/package.json +++ /dev/null @@ -1,73 +0,0 @@ -{ - "_from": "util@^0.12.0", - "_id": "util@0.12.1", - "_inBundle": false, - "_integrity": "sha512-MREAtYOp+GTt9/+kwf00IYoHZyjM8VU4aVrkzUlejyqaIjd2GztVl5V9hGXKlvBKE3gENn/FMfHE5v6hElXGcQ==", - "_location": "/util", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "util@^0.12.0", - "name": "util", - "escapedName": "util", - "rawSpec": "^0.12.0", - "saveSpec": null, - "fetchSpec": "^0.12.0" - }, - "_requiredBy": [ - "/assert" - ], - "_resolved": "https://registry.npmjs.org/util/-/util-0.12.1.tgz", - "_shasum": "f908e7b633e7396c764e694dd14e716256ce8ade", - "_spec": "util@^0.12.0", - "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/2.5/node_modules/assert", - "author": { - "name": "Joyent", - "url": "http://www.joyent.com" - }, - "browser": { - "./support/isBuffer.js": "./support/isBufferBrowser.js" - }, - "bugs": { - "url": "https://github.com/browserify/node-util/issues" - }, - "bundleDependencies": false, - "dependencies": { - "inherits": "^2.0.3", - "is-arguments": "^1.0.4", - "is-generator-function": "^1.0.7", - "object.entries": "^1.1.0", - "safe-buffer": "^5.1.2" - }, - "deprecated": false, - "description": "Node.js's util module for all engines", - "devDependencies": { - "airtap": "~1.0.0", - "is-async-supported": "~1.2.0", - "object.assign": "~4.1.0", - "run-series": "~1.1.4", - "tape": "~4.9.0" - }, - "files": [ - "util.js", - "support" - ], - "homepage": "https://github.com/browserify/node-util", - "keywords": [ - "util" - ], - "license": "MIT", - "main": "./util.js", - "name": "util", - "repository": { - "type": "git", - "url": "git://github.com/browserify/node-util.git" - }, - "scripts": { - "test": "node test/node/index.js", - "test:browsers": "airtap test/browser/index.js", - "test:browsers:local": "npm run test:browsers -- --local" - }, - "version": "0.12.1" -} diff --git a/scripts/2.5/node_modules/util/support/isBuffer.js b/scripts/2.5/node_modules/util/support/isBuffer.js deleted file mode 100644 index ace9ac00..00000000 --- a/scripts/2.5/node_modules/util/support/isBuffer.js +++ /dev/null @@ -1,3 +0,0 @@ -module.exports = function isBuffer(arg) { - return arg instanceof Buffer; -} diff --git a/scripts/2.5/node_modules/util/support/isBufferBrowser.js b/scripts/2.5/node_modules/util/support/isBufferBrowser.js deleted file mode 100644 index 0e1bee1e..00000000 --- a/scripts/2.5/node_modules/util/support/isBufferBrowser.js +++ /dev/null @@ -1,6 +0,0 @@ -module.exports = function isBuffer(arg) { - return arg && typeof arg === 'object' - && typeof arg.copy === 'function' - && typeof arg.fill === 'function' - && typeof arg.readUInt8 === 'function'; -} \ No newline at end of file diff --git a/scripts/2.5/node_modules/util/support/types.js b/scripts/2.5/node_modules/util/support/types.js deleted file mode 100644 index b1fedf26..00000000 --- a/scripts/2.5/node_modules/util/support/types.js +++ /dev/null @@ -1,422 +0,0 @@ -// Currently in sync with Node.js lib/internal/util/types.js -// https://github.com/nodejs/node/commit/112cc7c27551254aa2b17098fb774867f05ed0d9 - -'use strict'; - -var isBuffer = require('./isBuffer'); - -var isArgumentsObject = require('is-arguments'); -var isGeneratorFunction = require('is-generator-function'); - -function uncurryThis(f) { - return f.call.bind(f); -} - -var BigIntSupported = typeof BigInt !== 'undefined'; -var SymbolSupported = typeof Symbol !== 'undefined'; -var SymbolToStringTagSupported = SymbolSupported && typeof Symbol.toStringTag !== 'undefined'; -var Uint8ArraySupported = typeof Uint8Array !== 'undefined'; -var ArrayBufferSupported = typeof ArrayBuffer !== 'undefined'; - -if (Uint8ArraySupported && SymbolToStringTagSupported) { - var TypedArrayPrototype = Object.getPrototypeOf(Uint8Array.prototype); - - var TypedArrayProto_toStringTag = - uncurryThis( - Object.getOwnPropertyDescriptor(TypedArrayPrototype, - Symbol.toStringTag).get); - -} - -var ObjectToString = uncurryThis(Object.prototype.toString); - -var numberValue = uncurryThis(Number.prototype.valueOf); -var stringValue = uncurryThis(String.prototype.valueOf); -var booleanValue = uncurryThis(Boolean.prototype.valueOf); - -if (BigIntSupported) { - var bigIntValue = uncurryThis(BigInt.prototype.valueOf); -} - -if (SymbolSupported) { - var symbolValue = uncurryThis(Symbol.prototype.valueOf); -} - -function checkBoxedPrimitive(value, prototypeValueOf) { - if (typeof value !== 'object') { - return false; - } - try { - prototypeValueOf(value); - return true; - } catch(e) { - return false; - } -} - -exports.isArgumentsObject = isArgumentsObject; - -exports.isGeneratorFunction = isGeneratorFunction; - -// Taken from here and modified for better browser support -// https://github.com/sindresorhus/p-is-promise/blob/cda35a513bda03f977ad5cde3a079d237e82d7ef/index.js -function isPromise(input) { - return ( - ( - typeof Promise !== 'undefined' && - input instanceof Promise - ) || - ( - input !== null && - typeof input === 'object' && - typeof input.then === 'function' && - typeof input.catch === 'function' - ) - ); -} -exports.isPromise = isPromise; - -function isArrayBufferView(value) { - if (ArrayBufferSupported && ArrayBuffer.isView) { - return ArrayBuffer.isView(value); - } - - return ( - isTypedArray(value) || - isDataView(value) - ); -} -exports.isArrayBufferView = isArrayBufferView; - -function isTypedArray(value) { - if (Uint8ArraySupported && SymbolToStringTagSupported) { - return TypedArrayProto_toStringTag(value) !== undefined; - } else { - return ( - isUint8Array(value) || - isUint8ClampedArray(value) || - isUint16Array(value) || - isUint32Array(value) || - isInt8Array(value) || - isInt16Array(value) || - isInt32Array(value) || - isFloat32Array(value) || - isFloat64Array(value) || - isBigInt64Array(value) || - isBigUint64Array(value) - ); - } -} -exports.isTypedArray = isTypedArray; - -function isUint8Array(value) { - if (Uint8ArraySupported && SymbolToStringTagSupported) { - return TypedArrayProto_toStringTag(value) === 'Uint8Array'; - } else { - return ( - ObjectToString(value) === '[object Uint8Array]' || - // If it's a Buffer instance _and_ has a `.buffer` property, - // this is an ArrayBuffer based buffer; thus it's an Uint8Array - // (Old Node.js had a custom non-Uint8Array implementation) - isBuffer(value) && value.buffer !== undefined - ); - } -} -exports.isUint8Array = isUint8Array; - -function isUint8ClampedArray(value) { - if (Uint8ArraySupported && SymbolToStringTagSupported) { - return TypedArrayProto_toStringTag(value) === 'Uint8ClampedArray'; - } else { - return ObjectToString(value) === '[object Uint8ClampedArray]'; - } -} -exports.isUint8ClampedArray = isUint8ClampedArray; - -function isUint16Array(value) { - if (Uint8ArraySupported && SymbolToStringTagSupported) { - return TypedArrayProto_toStringTag(value) === 'Uint16Array'; - } else { - return ObjectToString(value) === '[object Uint16Array]'; - } -} -exports.isUint16Array = isUint16Array; - -function isUint32Array(value) { - if (Uint8ArraySupported && SymbolToStringTagSupported) { - return TypedArrayProto_toStringTag(value) === 'Uint32Array'; - } else { - return ObjectToString(value) === '[object Uint32Array]'; - } -} -exports.isUint32Array = isUint32Array; - -function isInt8Array(value) { - if (Uint8ArraySupported && SymbolToStringTagSupported) { - return TypedArrayProto_toStringTag(value) === 'Int8Array'; - } else { - return ObjectToString(value) === '[object Int8Array]'; - } -} -exports.isInt8Array = isInt8Array; - -function isInt16Array(value) { - if (Uint8ArraySupported && SymbolToStringTagSupported) { - return TypedArrayProto_toStringTag(value) === 'Int16Array'; - } else { - return ObjectToString(value) === '[object Int16Array]'; - } -} -exports.isInt16Array = isInt16Array; - -function isInt32Array(value) { - if (Uint8ArraySupported && SymbolToStringTagSupported) { - return TypedArrayProto_toStringTag(value) === 'Int32Array'; - } else { - return ObjectToString(value) === '[object Int32Array]'; - } -} -exports.isInt32Array = isInt32Array; - -function isFloat32Array(value) { - if (Uint8ArraySupported && SymbolToStringTagSupported) { - return TypedArrayProto_toStringTag(value) === 'Float32Array'; - } else { - return ObjectToString(value) === '[object Float32Array]'; - } -} -exports.isFloat32Array = isFloat32Array; - -function isFloat64Array(value) { - if (Uint8ArraySupported && SymbolToStringTagSupported) { - return TypedArrayProto_toStringTag(value) === 'Float64Array'; - } else { - return ObjectToString(value) === '[object Float64Array]'; - } -} -exports.isFloat64Array = isFloat64Array; - -function isBigInt64Array(value) { - if (Uint8ArraySupported && SymbolToStringTagSupported) { - return TypedArrayProto_toStringTag(value) === 'BigInt64Array'; - } else { - return ObjectToString(value) === '[object BigInt64Array]'; - } -} -exports.isBigInt64Array = isBigInt64Array; - -function isBigUint64Array(value) { - if (Uint8ArraySupported && SymbolToStringTagSupported) { - return TypedArrayProto_toStringTag(value) === 'BigUint64Array'; - } else { - return ObjectToString(value) === '[object BigUint64Array]'; - } -} -exports.isBigUint64Array = isBigUint64Array; - -function isMapToString(value) { - return ObjectToString(value) === '[object Map]'; -} -isMapToString.working = ( - typeof Map !== 'undefined' && - isMapToString(new Map()) -); - -function isMap(value) { - if (typeof Map === 'undefined') { - return false; - } - - return isMapToString.working - ? isMapToString(value) - : value instanceof Map; -} -exports.isMap = isMap; - -function isSetToString(value) { - return ObjectToString(value) === '[object Set]'; -} -isSetToString.working = ( - typeof Set !== 'undefined' && - isSetToString(new Set()) -); -function isSet(value) { - if (typeof Set === 'undefined') { - return false; - } - - return isSetToString.working - ? isSetToString(value) - : value instanceof Set; -} -exports.isSet = isSet; - -function isWeakMapToString(value) { - return ObjectToString(value) === '[object WeakMap]'; -} -isWeakMapToString.working = ( - typeof WeakMap !== 'undefined' && - isWeakMapToString(new WeakMap()) -); -function isWeakMap(value) { - if (typeof WeakMap === 'undefined') { - return false; - } - - return isWeakMapToString.working - ? isWeakMapToString(value) - : value instanceof WeakMap; -} -exports.isWeakMap = isWeakMap; - -function isWeakSetToString(value) { - return ObjectToString(value) === '[object WeakSet]'; -} -isWeakSetToString.working = ( - typeof WeakSet !== 'undefined' && - isWeakSetToString(new WeakSet()) -); -function isWeakSet(value) { - return isWeakSetToString(value); - if (typeof WeakSet === 'undefined') { - return false; - } - - return isWeakSetToString.working - ? isWeakSetToString(value) - : value instanceof WeakSet; -} -exports.isWeakSet = isWeakSet; - -function isArrayBufferToString(value) { - return ObjectToString(value) === '[object ArrayBuffer]'; -} -isArrayBufferToString.working = ( - typeof ArrayBuffer !== 'undefined' && - isArrayBufferToString(new ArrayBuffer()) -); -function isArrayBuffer(value) { - if (typeof ArrayBuffer === 'undefined') { - return false; - } - - return isArrayBufferToString.working - ? isArrayBufferToString(value) - : value instanceof ArrayBuffer; -} -exports.isArrayBuffer = isArrayBuffer; - -function isDataViewToString(value) { - return ObjectToString(value) === '[object DataView]'; -} -isDataViewToString.working = ( - typeof ArrayBuffer !== 'undefined' && - typeof DataView !== 'undefined' && - isDataViewToString(new DataView(new ArrayBuffer(1), 0, 1)) -); -function isDataView(value) { - if (typeof DataView === 'undefined') { - return false; - } - - return isDataViewToString.working - ? isDataViewToString(value) - : value instanceof DataView; -} -exports.isDataView = isDataView; - -function isSharedArrayBufferToString(value) { - return ObjectToString(value) === '[object SharedArrayBuffer]'; -} -isSharedArrayBufferToString.working = ( - typeof SharedArrayBuffer !== 'undefined' && - isSharedArrayBufferToString(new SharedArrayBuffer()) -); -function isSharedArrayBuffer(value) { - if (typeof SharedArrayBuffer === 'undefined') { - return false; - } - - return isSharedArrayBufferToString.working - ? isSharedArrayBufferToString(value) - : value instanceof SharedArrayBuffer; -} -exports.isSharedArrayBuffer = isSharedArrayBuffer; - -function isAsyncFunction(value) { - return ObjectToString(value) === '[object AsyncFunction]'; -} -exports.isAsyncFunction = isAsyncFunction; - -function isMapIterator(value) { - return ObjectToString(value) === '[object Map Iterator]'; -} -exports.isMapIterator = isMapIterator; - -function isSetIterator(value) { - return ObjectToString(value) === '[object Set Iterator]'; -} -exports.isSetIterator = isSetIterator; - -function isGeneratorObject(value) { - return ObjectToString(value) === '[object Generator]'; -} -exports.isGeneratorObject = isGeneratorObject; - -function isWebAssemblyCompiledModule(value) { - return ObjectToString(value) === '[object WebAssembly.Module]'; -} -exports.isWebAssemblyCompiledModule = isWebAssemblyCompiledModule; - -function isNumberObject(value) { - return checkBoxedPrimitive(value, numberValue); -} -exports.isNumberObject = isNumberObject; - -function isStringObject(value) { - return checkBoxedPrimitive(value, stringValue); -} -exports.isStringObject = isStringObject; - -function isBooleanObject(value) { - return checkBoxedPrimitive(value, booleanValue); -} -exports.isBooleanObject = isBooleanObject; - -function isBigIntObject(value) { - return BigIntSupported && checkBoxedPrimitive(value, bigIntValue); -} -exports.isBigIntObject = isBigIntObject; - -function isSymbolObject(value) { - return SymbolSupported && checkBoxedPrimitive(value, symbolValue); -} -exports.isSymbolObject = isSymbolObject; - -function isBoxedPrimitive(value) { - return ( - isNumberObject(value) || - isStringObject(value) || - isBooleanObject(value) || - isBigIntObject(value) || - isSymbolObject(value) - ); -} -exports.isBoxedPrimitive = isBoxedPrimitive; - -function isAnyArrayBuffer(value) { - return Uint8ArraySupported && ( - isArrayBuffer(value) || - isSharedArrayBuffer(value) - ); -} -exports.isAnyArrayBuffer = isAnyArrayBuffer; - -['isProxy', 'isExternal', 'isModuleNamespaceObject'].forEach(function(method) { - Object.defineProperty(exports, method, { - enumerable: false, - value: function() { - throw new Error(method + ' is not supported in userland'); - } - }); -}); diff --git a/scripts/2.5/node_modules/util/util.js b/scripts/2.5/node_modules/util/util.js deleted file mode 100644 index 6eea6572..00000000 --- a/scripts/2.5/node_modules/util/util.js +++ /dev/null @@ -1,715 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors || - function getOwnPropertyDescriptors(obj) { - var keys = Object.keys(obj); - var descriptors = {}; - for (var i = 0; i < keys.length; i++) { - descriptors[keys[i]] = Object.getOwnPropertyDescriptor(obj, keys[i]); - } - return descriptors; - }; - -var formatRegExp = /%[sdj%]/g; -exports.format = function(f) { - if (!isString(f)) { - var objects = []; - for (var i = 0; i < arguments.length; i++) { - objects.push(inspect(arguments[i])); - } - return objects.join(' '); - } - - var i = 1; - var args = arguments; - var len = args.length; - var str = String(f).replace(formatRegExp, function(x) { - if (x === '%%') return '%'; - if (i >= len) return x; - switch (x) { - case '%s': return String(args[i++]); - case '%d': return Number(args[i++]); - case '%j': - try { - return JSON.stringify(args[i++]); - } catch (_) { - return '[Circular]'; - } - default: - return x; - } - }); - for (var x = args[i]; i < len; x = args[++i]) { - if (isNull(x) || !isObject(x)) { - str += ' ' + x; - } else { - str += ' ' + inspect(x); - } - } - return str; -}; - - -// Mark that a method should not be used. -// Returns a modified function which warns once by default. -// If --no-deprecation is set, then it is a no-op. -exports.deprecate = function(fn, msg) { - if (typeof process !== 'undefined' && process.noDeprecation === true) { - return fn; - } - - // Allow for deprecating things in the process of starting up. - if (typeof process === 'undefined') { - return function() { - return exports.deprecate(fn, msg).apply(this, arguments); - }; - } - - var warned = false; - function deprecated() { - if (!warned) { - if (process.throwDeprecation) { - throw new Error(msg); - } else if (process.traceDeprecation) { - console.trace(msg); - } else { - console.error(msg); - } - warned = true; - } - return fn.apply(this, arguments); - } - - return deprecated; -}; - - -var debugs = {}; -var debugEnvRegex = /^$/; - -if (process.env.NODE_DEBUG) { - var debugEnv = process.env.NODE_DEBUG; - debugEnv = debugEnv.replace(/[|\\{}()[\]^$+?.]/g, '\\$&') - .replace(/\*/g, '.*') - .replace(/,/g, '$|^') - .toUpperCase(); - debugEnvRegex = new RegExp('^' + debugEnv + '$', 'i'); -} -exports.debuglog = function(set) { - set = set.toUpperCase(); - if (!debugs[set]) { - if (debugEnvRegex.test(set)) { - var pid = process.pid; - debugs[set] = function() { - var msg = exports.format.apply(exports, arguments); - console.error('%s %d: %s', set, pid, msg); - }; - } else { - debugs[set] = function() {}; - } - } - return debugs[set]; -}; - - -/** - * Echos the value of a value. Trys to print the value out - * in the best way possible given the different types. - * - * @param {Object} obj The object to print out. - * @param {Object} opts Optional options object that alters the output. - */ -/* legacy: obj, showHidden, depth, colors*/ -function inspect(obj, opts) { - // default options - var ctx = { - seen: [], - stylize: stylizeNoColor - }; - // legacy... - if (arguments.length >= 3) ctx.depth = arguments[2]; - if (arguments.length >= 4) ctx.colors = arguments[3]; - if (isBoolean(opts)) { - // legacy... - ctx.showHidden = opts; - } else if (opts) { - // got an "options" object - exports._extend(ctx, opts); - } - // set default options - if (isUndefined(ctx.showHidden)) ctx.showHidden = false; - if (isUndefined(ctx.depth)) ctx.depth = 2; - if (isUndefined(ctx.colors)) ctx.colors = false; - if (isUndefined(ctx.customInspect)) ctx.customInspect = true; - if (ctx.colors) ctx.stylize = stylizeWithColor; - return formatValue(ctx, obj, ctx.depth); -} -exports.inspect = inspect; - - -// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics -inspect.colors = { - 'bold' : [1, 22], - 'italic' : [3, 23], - 'underline' : [4, 24], - 'inverse' : [7, 27], - 'white' : [37, 39], - 'grey' : [90, 39], - 'black' : [30, 39], - 'blue' : [34, 39], - 'cyan' : [36, 39], - 'green' : [32, 39], - 'magenta' : [35, 39], - 'red' : [31, 39], - 'yellow' : [33, 39] -}; - -// Don't use 'blue' not visible on cmd.exe -inspect.styles = { - 'special': 'cyan', - 'number': 'yellow', - 'boolean': 'yellow', - 'undefined': 'grey', - 'null': 'bold', - 'string': 'green', - 'date': 'magenta', - // "name": intentionally not styling - 'regexp': 'red' -}; - - -function stylizeWithColor(str, styleType) { - var style = inspect.styles[styleType]; - - if (style) { - return '\u001b[' + inspect.colors[style][0] + 'm' + str + - '\u001b[' + inspect.colors[style][1] + 'm'; - } else { - return str; - } -} - - -function stylizeNoColor(str, styleType) { - return str; -} - - -function arrayToHash(array) { - var hash = {}; - - array.forEach(function(val, idx) { - hash[val] = true; - }); - - return hash; -} - - -function formatValue(ctx, value, recurseTimes) { - // Provide a hook for user-specified inspect functions. - // Check that value is an object with an inspect function on it - if (ctx.customInspect && - value && - isFunction(value.inspect) && - // Filter out the util module, it's inspect function is special - value.inspect !== exports.inspect && - // Also filter out any prototype objects using the circular check. - !(value.constructor && value.constructor.prototype === value)) { - var ret = value.inspect(recurseTimes, ctx); - if (!isString(ret)) { - ret = formatValue(ctx, ret, recurseTimes); - } - return ret; - } - - // Primitive types cannot have properties - var primitive = formatPrimitive(ctx, value); - if (primitive) { - return primitive; - } - - // Look up the keys of the object. - var keys = Object.keys(value); - var visibleKeys = arrayToHash(keys); - - if (ctx.showHidden) { - keys = Object.getOwnPropertyNames(value); - } - - // IE doesn't make error fields non-enumerable - // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx - if (isError(value) - && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { - return formatError(value); - } - - // Some type of object without properties can be shortcutted. - if (keys.length === 0) { - if (isFunction(value)) { - var name = value.name ? ': ' + value.name : ''; - return ctx.stylize('[Function' + name + ']', 'special'); - } - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } - if (isDate(value)) { - return ctx.stylize(Date.prototype.toString.call(value), 'date'); - } - if (isError(value)) { - return formatError(value); - } - } - - var base = '', array = false, braces = ['{', '}']; - - // Make Array say that they are Array - if (isArray(value)) { - array = true; - braces = ['[', ']']; - } - - // Make functions say that they are functions - if (isFunction(value)) { - var n = value.name ? ': ' + value.name : ''; - base = ' [Function' + n + ']'; - } - - // Make RegExps say that they are RegExps - if (isRegExp(value)) { - base = ' ' + RegExp.prototype.toString.call(value); - } - - // Make dates with properties first say the date - if (isDate(value)) { - base = ' ' + Date.prototype.toUTCString.call(value); - } - - // Make error with message first say the error - if (isError(value)) { - base = ' ' + formatError(value); - } - - if (keys.length === 0 && (!array || value.length == 0)) { - return braces[0] + base + braces[1]; - } - - if (recurseTimes < 0) { - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } else { - return ctx.stylize('[Object]', 'special'); - } - } - - ctx.seen.push(value); - - var output; - if (array) { - output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); - } else { - output = keys.map(function(key) { - return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); - }); - } - - ctx.seen.pop(); - - return reduceToSingleString(output, base, braces); -} - - -function formatPrimitive(ctx, value) { - if (isUndefined(value)) - return ctx.stylize('undefined', 'undefined'); - if (isString(value)) { - var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') - .replace(/'/g, "\\'") - .replace(/\\"/g, '"') + '\''; - return ctx.stylize(simple, 'string'); - } - if (isNumber(value)) - return ctx.stylize('' + value, 'number'); - if (isBoolean(value)) - return ctx.stylize('' + value, 'boolean'); - // For some reason typeof null is "object", so special case here. - if (isNull(value)) - return ctx.stylize('null', 'null'); -} - - -function formatError(value) { - return '[' + Error.prototype.toString.call(value) + ']'; -} - - -function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { - var output = []; - for (var i = 0, l = value.length; i < l; ++i) { - if (hasOwnProperty(value, String(i))) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - String(i), true)); - } else { - output.push(''); - } - } - keys.forEach(function(key) { - if (!key.match(/^\d+$/)) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - key, true)); - } - }); - return output; -} - - -function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { - var name, str, desc; - desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; - if (desc.get) { - if (desc.set) { - str = ctx.stylize('[Getter/Setter]', 'special'); - } else { - str = ctx.stylize('[Getter]', 'special'); - } - } else { - if (desc.set) { - str = ctx.stylize('[Setter]', 'special'); - } - } - if (!hasOwnProperty(visibleKeys, key)) { - name = '[' + key + ']'; - } - if (!str) { - if (ctx.seen.indexOf(desc.value) < 0) { - if (isNull(recurseTimes)) { - str = formatValue(ctx, desc.value, null); - } else { - str = formatValue(ctx, desc.value, recurseTimes - 1); - } - if (str.indexOf('\n') > -1) { - if (array) { - str = str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n').substr(2); - } else { - str = '\n' + str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n'); - } - } - } else { - str = ctx.stylize('[Circular]', 'special'); - } - } - if (isUndefined(name)) { - if (array && key.match(/^\d+$/)) { - return str; - } - name = JSON.stringify('' + key); - if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { - name = name.substr(1, name.length - 2); - name = ctx.stylize(name, 'name'); - } else { - name = name.replace(/'/g, "\\'") - .replace(/\\"/g, '"') - .replace(/(^"|"$)/g, "'"); - name = ctx.stylize(name, 'string'); - } - } - - return name + ': ' + str; -} - - -function reduceToSingleString(output, base, braces) { - var numLinesEst = 0; - var length = output.reduce(function(prev, cur) { - numLinesEst++; - if (cur.indexOf('\n') >= 0) numLinesEst++; - return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; - }, 0); - - if (length > 60) { - return braces[0] + - (base === '' ? '' : base + '\n ') + - ' ' + - output.join(',\n ') + - ' ' + - braces[1]; - } - - return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; -} - - -// NOTE: These type checking functions intentionally don't use `instanceof` -// because it is fragile and can be easily faked with `Object.create()`. -exports.types = require('./support/types'); - -function isArray(ar) { - return Array.isArray(ar); -} -exports.isArray = isArray; - -function isBoolean(arg) { - return typeof arg === 'boolean'; -} -exports.isBoolean = isBoolean; - -function isNull(arg) { - return arg === null; -} -exports.isNull = isNull; - -function isNullOrUndefined(arg) { - return arg == null; -} -exports.isNullOrUndefined = isNullOrUndefined; - -function isNumber(arg) { - return typeof arg === 'number'; -} -exports.isNumber = isNumber; - -function isString(arg) { - return typeof arg === 'string'; -} -exports.isString = isString; - -function isSymbol(arg) { - return typeof arg === 'symbol'; -} -exports.isSymbol = isSymbol; - -function isUndefined(arg) { - return arg === void 0; -} -exports.isUndefined = isUndefined; - -function isRegExp(re) { - return isObject(re) && objectToString(re) === '[object RegExp]'; -} -exports.isRegExp = isRegExp; -exports.types.isRegExp = isRegExp; - -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} -exports.isObject = isObject; - -function isDate(d) { - return isObject(d) && objectToString(d) === '[object Date]'; -} -exports.isDate = isDate; -exports.types.isDate = isDate; - -function isError(e) { - return isObject(e) && - (objectToString(e) === '[object Error]' || e instanceof Error); -} -exports.isError = isError; -exports.types.isNativeError = isError; - -function isFunction(arg) { - return typeof arg === 'function'; -} -exports.isFunction = isFunction; - -function isPrimitive(arg) { - return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; -} -exports.isPrimitive = isPrimitive; - -exports.isBuffer = require('./support/isBuffer'); - -function objectToString(o) { - return Object.prototype.toString.call(o); -} - - -function pad(n) { - return n < 10 ? '0' + n.toString(10) : n.toString(10); -} - - -var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', - 'Oct', 'Nov', 'Dec']; - -// 26 Feb 16:19:34 -function timestamp() { - var d = new Date(); - var time = [pad(d.getHours()), - pad(d.getMinutes()), - pad(d.getSeconds())].join(':'); - return [d.getDate(), months[d.getMonth()], time].join(' '); -} - - -// log is just a thin wrapper to console.log that prepends a timestamp -exports.log = function() { - console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); -}; - - -/** - * Inherit the prototype methods from one constructor into another. - * - * The Function.prototype.inherits from lang.js rewritten as a standalone - * function (not on Function.prototype). NOTE: If this file is to be loaded - * during bootstrapping this function needs to be rewritten using some native - * functions as prototype setup using normal JavaScript does not work as - * expected during bootstrapping (see mirror.js in r114903). - * - * @param {function} ctor Constructor function which needs to inherit the - * prototype. - * @param {function} superCtor Constructor function to inherit prototype from. - */ -exports.inherits = require('inherits'); - -exports._extend = function(origin, add) { - // Don't do anything if add isn't an object - if (!add || !isObject(add)) return origin; - - var keys = Object.keys(add); - var i = keys.length; - while (i--) { - origin[keys[i]] = add[keys[i]]; - } - return origin; -}; - -function hasOwnProperty(obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop); -} - -var kCustomPromisifiedSymbol = typeof Symbol !== 'undefined' ? Symbol('util.promisify.custom') : undefined; - -exports.promisify = function promisify(original) { - if (typeof original !== 'function') - throw new TypeError('The "original" argument must be of type Function'); - - if (kCustomPromisifiedSymbol && original[kCustomPromisifiedSymbol]) { - var fn = original[kCustomPromisifiedSymbol]; - if (typeof fn !== 'function') { - throw new TypeError('The "util.promisify.custom" argument must be of type Function'); - } - Object.defineProperty(fn, kCustomPromisifiedSymbol, { - value: fn, enumerable: false, writable: false, configurable: true - }); - return fn; - } - - function fn() { - var promiseResolve, promiseReject; - var promise = new Promise(function (resolve, reject) { - promiseResolve = resolve; - promiseReject = reject; - }); - - var args = []; - for (var i = 0; i < arguments.length; i++) { - args.push(arguments[i]); - } - args.push(function (err, value) { - if (err) { - promiseReject(err); - } else { - promiseResolve(value); - } - }); - - try { - original.apply(this, args); - } catch (err) { - promiseReject(err); - } - - return promise; - } - - Object.setPrototypeOf(fn, Object.getPrototypeOf(original)); - - if (kCustomPromisifiedSymbol) Object.defineProperty(fn, kCustomPromisifiedSymbol, { - value: fn, enumerable: false, writable: false, configurable: true - }); - return Object.defineProperties( - fn, - getOwnPropertyDescriptors(original) - ); -} - -exports.promisify.custom = kCustomPromisifiedSymbol - -function callbackifyOnRejected(reason, cb) { - // `!reason` guard inspired by bluebird (Ref: https://goo.gl/t5IS6M). - // Because `null` is a special error value in callbacks which means "no error - // occurred", we error-wrap so the callback consumer can distinguish between - // "the promise rejected with null" or "the promise fulfilled with undefined". - if (!reason) { - var newReason = new Error('Promise was rejected with a falsy value'); - newReason.reason = reason; - reason = newReason; - } - return cb(reason); -} - -function callbackify(original) { - if (typeof original !== 'function') { - throw new TypeError('The "original" argument must be of type Function'); - } - - // We DO NOT return the promise as it gives the user a false sense that - // the promise is actually somehow related to the callback's execution - // and that the callback throwing will reject the promise. - function callbackified() { - var args = []; - for (var i = 0; i < arguments.length; i++) { - args.push(arguments[i]); - } - - var maybeCb = args.pop(); - if (typeof maybeCb !== 'function') { - throw new TypeError('The last argument must be of type Function'); - } - var self = this; - var cb = function() { - return maybeCb.apply(self, arguments); - }; - // In true node style we process the callback on `nextTick` with all the - // implications (stack, `uncaughtException`, `async_hooks`) - original.apply(this, args) - .then(function(ret) { process.nextTick(cb.bind(null, null, ret)) }, - function(rej) { process.nextTick(callbackifyOnRejected.bind(null, rej, cb)) }); - } - - Object.setPrototypeOf(callbackified, Object.getPrototypeOf(original)); - Object.defineProperties(callbackified, - getOwnPropertyDescriptors(original)); - return callbackified; -} -exports.callbackify = callbackify; From 9b75fff1ea5ab8f09e35e9119b2f5754750cfcad Mon Sep 17 00:00:00 2001 From: Becky Reamy Date: Tue, 29 Oct 2019 10:54:59 -0400 Subject: [PATCH 25/26] KPMP-1270: Remove node_modules --- scripts/node_modules/.bin/semver | 1 - scripts/node_modules/bson/HISTORY.md | 268 - scripts/node_modules/bson/LICENSE.md | 201 - scripts/node_modules/bson/README.md | 170 - scripts/node_modules/bson/bower.json | 25 - .../node_modules/bson/browser_build/bson.js | 17769 ---------------- .../bson/browser_build/package.json | 8 - scripts/node_modules/bson/index.js | 46 - scripts/node_modules/bson/lib/bson/binary.js | 384 - scripts/node_modules/bson/lib/bson/bson.js | 386 - scripts/node_modules/bson/lib/bson/code.js | 24 - scripts/node_modules/bson/lib/bson/db_ref.js | 32 - .../node_modules/bson/lib/bson/decimal128.js | 820 - scripts/node_modules/bson/lib/bson/double.js | 33 - .../bson/lib/bson/float_parser.js | 124 - scripts/node_modules/bson/lib/bson/int_32.js | 33 - scripts/node_modules/bson/lib/bson/long.js | 851 - scripts/node_modules/bson/lib/bson/map.js | 128 - scripts/node_modules/bson/lib/bson/max_key.js | 14 - scripts/node_modules/bson/lib/bson/min_key.js | 14 - .../node_modules/bson/lib/bson/objectid.js | 389 - .../bson/lib/bson/parser/calculate_size.js | 255 - .../bson/lib/bson/parser/deserializer.js | 782 - .../bson/lib/bson/parser/serializer.js | 1182 - .../bson/lib/bson/parser/utils.js | 28 - scripts/node_modules/bson/lib/bson/regexp.js | 33 - scripts/node_modules/bson/lib/bson/symbol.js | 50 - .../node_modules/bson/lib/bson/timestamp.js | 854 - scripts/node_modules/bson/package.json | 87 - scripts/node_modules/memory-pager/.travis.yml | 4 - scripts/node_modules/memory-pager/LICENSE | 21 - scripts/node_modules/memory-pager/README.md | 65 - scripts/node_modules/memory-pager/index.js | 160 - .../node_modules/memory-pager/package.json | 52 - scripts/node_modules/memory-pager/test.js | 80 - scripts/node_modules/mongodb/HISTORY.md | 2485 --- scripts/node_modules/mongodb/LICENSE.md | 201 - scripts/node_modules/mongodb/README.md | 499 - scripts/node_modules/mongodb/index.js | 68 - scripts/node_modules/mongodb/lib/admin.js | 293 - .../mongodb/lib/aggregation_cursor.js | 370 - scripts/node_modules/mongodb/lib/apm.js | 31 - .../node_modules/mongodb/lib/async/.eslintrc | 5 - .../mongodb/lib/async/async_iterator.js | 33 - .../node_modules/mongodb/lib/bulk/common.js | 1239 -- .../node_modules/mongodb/lib/bulk/ordered.js | 105 - .../mongodb/lib/bulk/unordered.js | 118 - .../node_modules/mongodb/lib/change_stream.js | 576 - .../node_modules/mongodb/lib/collection.js | 2113 -- .../mongodb/lib/command_cursor.js | 269 - scripts/node_modules/mongodb/lib/constants.js | 10 - .../mongodb/lib/core/auth/auth_provider.js | 158 - .../lib/core/auth/defaultAuthProviders.js | 29 - .../mongodb/lib/core/auth/gssapi.js | 241 - .../lib/core/auth/mongo_credentials.js | 81 - .../mongodb/lib/core/auth/mongocr.js | 51 - .../mongodb/lib/core/auth/plain.js | 35 - .../mongodb/lib/core/auth/scram.js | 293 - .../mongodb/lib/core/auth/sspi.js | 131 - .../mongodb/lib/core/auth/x509.js | 26 - .../mongodb/lib/core/connection/apm.js | 236 - .../lib/core/connection/command_result.js | 36 - .../mongodb/lib/core/connection/commands.js | 507 - .../mongodb/lib/core/connection/connect.js | 370 - .../mongodb/lib/core/connection/connection.js | 628 - .../mongodb/lib/core/connection/logger.js | 246 - .../mongodb/lib/core/connection/msg.js | 221 - .../mongodb/lib/core/connection/pool.js | 1256 -- .../mongodb/lib/core/connection/utils.js | 57 - .../node_modules/mongodb/lib/core/cursor.js | 886 - .../node_modules/mongodb/lib/core/error.js | 237 - .../node_modules/mongodb/lib/core/index.js | 50 - .../mongodb/lib/core/sdam/monitoring.js | 235 - .../mongodb/lib/core/sdam/server.js | 511 - .../lib/core/sdam/server_description.js | 163 - .../mongodb/lib/core/sdam/server_selectors.js | 244 - .../mongodb/lib/core/sdam/srv_polling.js | 135 - .../mongodb/lib/core/sdam/topology.js | 1186 -- .../lib/core/sdam/topology_description.js | 408 - .../node_modules/mongodb/lib/core/sessions.js | 767 - .../mongodb/lib/core/tools/smoke_plugin.js | 61 - .../mongodb/lib/core/topologies/mongos.js | 1392 -- .../lib/core/topologies/read_preference.js | 202 - .../mongodb/lib/core/topologies/replset.js | 1553 -- .../lib/core/topologies/replset_state.js | 1121 - .../mongodb/lib/core/topologies/server.js | 989 - .../mongodb/lib/core/topologies/shared.js | 476 - .../mongodb/lib/core/transactions.js | 168 - .../mongodb/lib/core/uri_parser.js | 637 - .../node_modules/mongodb/lib/core/utils.js | 177 - .../mongodb/lib/core/wireprotocol/command.js | 170 - .../lib/core/wireprotocol/compression.js | 73 - .../lib/core/wireprotocol/constants.js | 13 - .../mongodb/lib/core/wireprotocol/get_more.js | 90 - .../mongodb/lib/core/wireprotocol/index.js | 18 - .../lib/core/wireprotocol/kill_cursors.js | 70 - .../mongodb/lib/core/wireprotocol/query.js | 231 - .../mongodb/lib/core/wireprotocol/shared.js | 115 - .../lib/core/wireprotocol/write_command.js | 50 - scripts/node_modules/mongodb/lib/cursor.js | 1089 - scripts/node_modules/mongodb/lib/db.js | 1029 - .../mongodb/lib/dynamic_loaders.js | 32 - scripts/node_modules/mongodb/lib/error.js | 45 - .../mongodb/lib/gridfs-stream/download.js | 421 - .../mongodb/lib/gridfs-stream/index.js | 358 - .../mongodb/lib/gridfs-stream/upload.js | 538 - .../node_modules/mongodb/lib/gridfs/chunk.js | 236 - .../mongodb/lib/gridfs/grid_store.js | 1913 -- .../node_modules/mongodb/lib/mongo_client.js | 479 - .../mongodb/lib/operations/add_user.js | 96 - .../mongodb/lib/operations/admin_ops.js | 62 - .../mongodb/lib/operations/aggregate.js | 106 - .../mongodb/lib/operations/bulk_write.js | 104 - .../mongodb/lib/operations/close.js | 46 - .../mongodb/lib/operations/collection_ops.js | 374 - .../mongodb/lib/operations/collections.js | 55 - .../mongodb/lib/operations/command.js | 120 - .../mongodb/lib/operations/command_v2.js | 109 - .../lib/operations/common_functions.js | 406 - .../mongodb/lib/operations/connect.js | 709 - .../mongodb/lib/operations/count.js | 72 - .../mongodb/lib/operations/count_documents.js | 41 - .../lib/operations/create_collection.js | 118 - .../mongodb/lib/operations/create_index.js | 92 - .../mongodb/lib/operations/create_indexes.js | 61 - .../mongodb/lib/operations/cursor_ops.js | 239 - .../mongodb/lib/operations/db_ops.js | 831 - .../mongodb/lib/operations/delete_many.js | 25 - .../mongodb/lib/operations/delete_one.js | 25 - .../mongodb/lib/operations/distinct.js | 85 - .../mongodb/lib/operations/drop.js | 53 - .../mongodb/lib/operations/drop_index.js | 42 - .../mongodb/lib/operations/drop_indexes.js | 23 - .../operations/estimated_document_count.js | 58 - .../operations/execute_db_admin_command.js | 34 - .../lib/operations/execute_operation.js | 198 - .../mongodb/lib/operations/explain.js | 23 - .../mongodb/lib/operations/find.js | 35 - .../mongodb/lib/operations/find_and_modify.js | 98 - .../mongodb/lib/operations/find_one.js | 33 - .../lib/operations/find_one_and_delete.js | 16 - .../lib/operations/find_one_and_replace.js | 18 - .../lib/operations/find_one_and_update.js | 19 - .../lib/operations/geo_haystack_search.js | 79 - .../mongodb/lib/operations/has_next.js | 40 - .../mongodb/lib/operations/index_exists.js | 39 - .../lib/operations/index_information.js | 23 - .../mongodb/lib/operations/indexes.js | 22 - .../mongodb/lib/operations/insert_many.js | 63 - .../mongodb/lib/operations/insert_one.js | 39 - .../mongodb/lib/operations/is_capped.js | 19 - .../lib/operations/list_collections.js | 106 - .../mongodb/lib/operations/list_databases.js | 38 - .../mongodb/lib/operations/list_indexes.js | 42 - .../mongodb/lib/operations/map_reduce.js | 189 - .../mongodb/lib/operations/next.js | 32 - .../mongodb/lib/operations/operation.js | 67 - .../lib/operations/options_operation.js | 32 - .../mongodb/lib/operations/profiling_level.js | 31 - .../mongodb/lib/operations/re_index.js | 28 - .../mongodb/lib/operations/remove_user.js | 52 - .../mongodb/lib/operations/rename.js | 61 - .../mongodb/lib/operations/replace_one.js | 47 - .../lib/operations/set_profiling_level.js | 48 - .../mongodb/lib/operations/stats.js | 45 - .../mongodb/lib/operations/to_array.js | 66 - .../mongodb/lib/operations/update_many.js | 29 - .../mongodb/lib/operations/update_one.js | 44 - .../lib/operations/validate_collection.js | 40 - .../node_modules/mongodb/lib/read_concern.js | 61 - .../mongodb/lib/topologies/mongos.js | 452 - .../mongodb/lib/topologies/native_topology.js | 72 - .../mongodb/lib/topologies/replset.js | 496 - .../mongodb/lib/topologies/server.js | 455 - .../mongodb/lib/topologies/topology_base.js | 438 - .../node_modules/mongodb/lib/url_parser.js | 623 - scripts/node_modules/mongodb/lib/utils.js | 716 - .../node_modules/mongodb/lib/write_concern.js | 66 - scripts/node_modules/mongodb/package.json | 104 - .../node_modules/require_optional/.npmignore | 33 - .../node_modules/require_optional/.travis.yml | 9 - .../node_modules/require_optional/HISTORY.md | 7 - scripts/node_modules/require_optional/LICENSE | 201 - .../node_modules/require_optional/README.md | 2 - .../node_modules/require_optional/index.js | 128 - .../require_optional/package.json | 67 - .../require_optional/test/nestedTest/index.js | 8 - .../test/nestedTest/package.json | 11 - .../test/require_optional_tests.js | 59 - scripts/node_modules/resolve-from/index.js | 23 - scripts/node_modules/resolve-from/license | 21 - .../node_modules/resolve-from/package.json | 66 - scripts/node_modules/resolve-from/readme.md | 58 - scripts/node_modules/safe-buffer/LICENSE | 21 - scripts/node_modules/safe-buffer/README.md | 586 - scripts/node_modules/safe-buffer/index.d.ts | 187 - scripts/node_modules/safe-buffer/index.js | 64 - scripts/node_modules/safe-buffer/package.json | 62 - scripts/node_modules/saslprep/.editorconfig | 10 - scripts/node_modules/saslprep/.gitattributes | 1 - scripts/node_modules/saslprep/.travis.yml | 10 - scripts/node_modules/saslprep/CHANGELOG.md | 19 - scripts/node_modules/saslprep/LICENSE | 22 - scripts/node_modules/saslprep/code-points.mem | Bin 419864 -> 0 bytes .../saslprep/generate-code-points.js | 51 - scripts/node_modules/saslprep/index.js | 157 - .../node_modules/saslprep/lib/code-points.js | 996 - .../saslprep/lib/memory-code-points.js | 39 - scripts/node_modules/saslprep/lib/util.js | 21 - scripts/node_modules/saslprep/package.json | 100 - scripts/node_modules/saslprep/readme.md | 31 - scripts/node_modules/saslprep/test/index.js | 76 - scripts/node_modules/saslprep/test/util.js | 16 - scripts/node_modules/semver/CHANGELOG.md | 39 - scripts/node_modules/semver/LICENSE | 15 - scripts/node_modules/semver/README.md | 412 - scripts/node_modules/semver/bin/semver | 160 - scripts/node_modules/semver/package.json | 60 - scripts/node_modules/semver/range.bnf | 16 - scripts/node_modules/semver/semver.js | 1483 -- .../node_modules/sparse-bitfield/.npmignore | 1 - .../node_modules/sparse-bitfield/.travis.yml | 6 - scripts/node_modules/sparse-bitfield/LICENSE | 21 - .../node_modules/sparse-bitfield/README.md | 62 - scripts/node_modules/sparse-bitfield/index.js | 95 - .../node_modules/sparse-bitfield/package.json | 55 - scripts/node_modules/sparse-bitfield/test.js | 79 - 227 files changed, 71854 deletions(-) delete mode 120000 scripts/node_modules/.bin/semver delete mode 100644 scripts/node_modules/bson/HISTORY.md delete mode 100644 scripts/node_modules/bson/LICENSE.md delete mode 100644 scripts/node_modules/bson/README.md delete mode 100644 scripts/node_modules/bson/bower.json delete mode 100644 scripts/node_modules/bson/browser_build/bson.js delete mode 100644 scripts/node_modules/bson/browser_build/package.json delete mode 100644 scripts/node_modules/bson/index.js delete mode 100644 scripts/node_modules/bson/lib/bson/binary.js delete mode 100644 scripts/node_modules/bson/lib/bson/bson.js delete mode 100644 scripts/node_modules/bson/lib/bson/code.js delete mode 100644 scripts/node_modules/bson/lib/bson/db_ref.js delete mode 100644 scripts/node_modules/bson/lib/bson/decimal128.js delete mode 100644 scripts/node_modules/bson/lib/bson/double.js delete mode 100644 scripts/node_modules/bson/lib/bson/float_parser.js delete mode 100644 scripts/node_modules/bson/lib/bson/int_32.js delete mode 100644 scripts/node_modules/bson/lib/bson/long.js delete mode 100644 scripts/node_modules/bson/lib/bson/map.js delete mode 100644 scripts/node_modules/bson/lib/bson/max_key.js delete mode 100644 scripts/node_modules/bson/lib/bson/min_key.js delete mode 100644 scripts/node_modules/bson/lib/bson/objectid.js delete mode 100644 scripts/node_modules/bson/lib/bson/parser/calculate_size.js delete mode 100644 scripts/node_modules/bson/lib/bson/parser/deserializer.js delete mode 100644 scripts/node_modules/bson/lib/bson/parser/serializer.js delete mode 100644 scripts/node_modules/bson/lib/bson/parser/utils.js delete mode 100644 scripts/node_modules/bson/lib/bson/regexp.js delete mode 100644 scripts/node_modules/bson/lib/bson/symbol.js delete mode 100644 scripts/node_modules/bson/lib/bson/timestamp.js delete mode 100644 scripts/node_modules/bson/package.json delete mode 100644 scripts/node_modules/memory-pager/.travis.yml delete mode 100644 scripts/node_modules/memory-pager/LICENSE delete mode 100644 scripts/node_modules/memory-pager/README.md delete mode 100644 scripts/node_modules/memory-pager/index.js delete mode 100644 scripts/node_modules/memory-pager/package.json delete mode 100644 scripts/node_modules/memory-pager/test.js delete mode 100644 scripts/node_modules/mongodb/HISTORY.md delete mode 100644 scripts/node_modules/mongodb/LICENSE.md delete mode 100644 scripts/node_modules/mongodb/README.md delete mode 100644 scripts/node_modules/mongodb/index.js delete mode 100644 scripts/node_modules/mongodb/lib/admin.js delete mode 100644 scripts/node_modules/mongodb/lib/aggregation_cursor.js delete mode 100644 scripts/node_modules/mongodb/lib/apm.js delete mode 100644 scripts/node_modules/mongodb/lib/async/.eslintrc delete mode 100644 scripts/node_modules/mongodb/lib/async/async_iterator.js delete mode 100644 scripts/node_modules/mongodb/lib/bulk/common.js delete mode 100644 scripts/node_modules/mongodb/lib/bulk/ordered.js delete mode 100644 scripts/node_modules/mongodb/lib/bulk/unordered.js delete mode 100644 scripts/node_modules/mongodb/lib/change_stream.js delete mode 100644 scripts/node_modules/mongodb/lib/collection.js delete mode 100644 scripts/node_modules/mongodb/lib/command_cursor.js delete mode 100644 scripts/node_modules/mongodb/lib/constants.js delete mode 100644 scripts/node_modules/mongodb/lib/core/auth/auth_provider.js delete mode 100644 scripts/node_modules/mongodb/lib/core/auth/defaultAuthProviders.js delete mode 100644 scripts/node_modules/mongodb/lib/core/auth/gssapi.js delete mode 100644 scripts/node_modules/mongodb/lib/core/auth/mongo_credentials.js delete mode 100644 scripts/node_modules/mongodb/lib/core/auth/mongocr.js delete mode 100644 scripts/node_modules/mongodb/lib/core/auth/plain.js delete mode 100644 scripts/node_modules/mongodb/lib/core/auth/scram.js delete mode 100644 scripts/node_modules/mongodb/lib/core/auth/sspi.js delete mode 100644 scripts/node_modules/mongodb/lib/core/auth/x509.js delete mode 100644 scripts/node_modules/mongodb/lib/core/connection/apm.js delete mode 100644 scripts/node_modules/mongodb/lib/core/connection/command_result.js delete mode 100644 scripts/node_modules/mongodb/lib/core/connection/commands.js delete mode 100644 scripts/node_modules/mongodb/lib/core/connection/connect.js delete mode 100644 scripts/node_modules/mongodb/lib/core/connection/connection.js delete mode 100644 scripts/node_modules/mongodb/lib/core/connection/logger.js delete mode 100644 scripts/node_modules/mongodb/lib/core/connection/msg.js delete mode 100644 scripts/node_modules/mongodb/lib/core/connection/pool.js delete mode 100644 scripts/node_modules/mongodb/lib/core/connection/utils.js delete mode 100644 scripts/node_modules/mongodb/lib/core/cursor.js delete mode 100644 scripts/node_modules/mongodb/lib/core/error.js delete mode 100644 scripts/node_modules/mongodb/lib/core/index.js delete mode 100644 scripts/node_modules/mongodb/lib/core/sdam/monitoring.js delete mode 100644 scripts/node_modules/mongodb/lib/core/sdam/server.js delete mode 100644 scripts/node_modules/mongodb/lib/core/sdam/server_description.js delete mode 100644 scripts/node_modules/mongodb/lib/core/sdam/server_selectors.js delete mode 100644 scripts/node_modules/mongodb/lib/core/sdam/srv_polling.js delete mode 100644 scripts/node_modules/mongodb/lib/core/sdam/topology.js delete mode 100644 scripts/node_modules/mongodb/lib/core/sdam/topology_description.js delete mode 100644 scripts/node_modules/mongodb/lib/core/sessions.js delete mode 100644 scripts/node_modules/mongodb/lib/core/tools/smoke_plugin.js delete mode 100644 scripts/node_modules/mongodb/lib/core/topologies/mongos.js delete mode 100644 scripts/node_modules/mongodb/lib/core/topologies/read_preference.js delete mode 100644 scripts/node_modules/mongodb/lib/core/topologies/replset.js delete mode 100644 scripts/node_modules/mongodb/lib/core/topologies/replset_state.js delete mode 100644 scripts/node_modules/mongodb/lib/core/topologies/server.js delete mode 100644 scripts/node_modules/mongodb/lib/core/topologies/shared.js delete mode 100644 scripts/node_modules/mongodb/lib/core/transactions.js delete mode 100644 scripts/node_modules/mongodb/lib/core/uri_parser.js delete mode 100644 scripts/node_modules/mongodb/lib/core/utils.js delete mode 100644 scripts/node_modules/mongodb/lib/core/wireprotocol/command.js delete mode 100644 scripts/node_modules/mongodb/lib/core/wireprotocol/compression.js delete mode 100644 scripts/node_modules/mongodb/lib/core/wireprotocol/constants.js delete mode 100644 scripts/node_modules/mongodb/lib/core/wireprotocol/get_more.js delete mode 100644 scripts/node_modules/mongodb/lib/core/wireprotocol/index.js delete mode 100644 scripts/node_modules/mongodb/lib/core/wireprotocol/kill_cursors.js delete mode 100644 scripts/node_modules/mongodb/lib/core/wireprotocol/query.js delete mode 100644 scripts/node_modules/mongodb/lib/core/wireprotocol/shared.js delete mode 100644 scripts/node_modules/mongodb/lib/core/wireprotocol/write_command.js delete mode 100644 scripts/node_modules/mongodb/lib/cursor.js delete mode 100644 scripts/node_modules/mongodb/lib/db.js delete mode 100644 scripts/node_modules/mongodb/lib/dynamic_loaders.js delete mode 100644 scripts/node_modules/mongodb/lib/error.js delete mode 100644 scripts/node_modules/mongodb/lib/gridfs-stream/download.js delete mode 100644 scripts/node_modules/mongodb/lib/gridfs-stream/index.js delete mode 100644 scripts/node_modules/mongodb/lib/gridfs-stream/upload.js delete mode 100644 scripts/node_modules/mongodb/lib/gridfs/chunk.js delete mode 100644 scripts/node_modules/mongodb/lib/gridfs/grid_store.js delete mode 100644 scripts/node_modules/mongodb/lib/mongo_client.js delete mode 100644 scripts/node_modules/mongodb/lib/operations/add_user.js delete mode 100644 scripts/node_modules/mongodb/lib/operations/admin_ops.js delete mode 100644 scripts/node_modules/mongodb/lib/operations/aggregate.js delete mode 100644 scripts/node_modules/mongodb/lib/operations/bulk_write.js delete mode 100644 scripts/node_modules/mongodb/lib/operations/close.js delete mode 100644 scripts/node_modules/mongodb/lib/operations/collection_ops.js delete mode 100644 scripts/node_modules/mongodb/lib/operations/collections.js delete mode 100644 scripts/node_modules/mongodb/lib/operations/command.js delete mode 100644 scripts/node_modules/mongodb/lib/operations/command_v2.js delete mode 100644 scripts/node_modules/mongodb/lib/operations/common_functions.js delete mode 100644 scripts/node_modules/mongodb/lib/operations/connect.js delete mode 100644 scripts/node_modules/mongodb/lib/operations/count.js delete mode 100644 scripts/node_modules/mongodb/lib/operations/count_documents.js delete mode 100644 scripts/node_modules/mongodb/lib/operations/create_collection.js delete mode 100644 scripts/node_modules/mongodb/lib/operations/create_index.js delete mode 100644 scripts/node_modules/mongodb/lib/operations/create_indexes.js delete mode 100644 scripts/node_modules/mongodb/lib/operations/cursor_ops.js delete mode 100644 scripts/node_modules/mongodb/lib/operations/db_ops.js delete mode 100644 scripts/node_modules/mongodb/lib/operations/delete_many.js delete mode 100644 scripts/node_modules/mongodb/lib/operations/delete_one.js delete mode 100644 scripts/node_modules/mongodb/lib/operations/distinct.js delete mode 100644 scripts/node_modules/mongodb/lib/operations/drop.js delete mode 100644 scripts/node_modules/mongodb/lib/operations/drop_index.js delete mode 100644 scripts/node_modules/mongodb/lib/operations/drop_indexes.js delete mode 100644 scripts/node_modules/mongodb/lib/operations/estimated_document_count.js delete mode 100644 scripts/node_modules/mongodb/lib/operations/execute_db_admin_command.js delete mode 100644 scripts/node_modules/mongodb/lib/operations/execute_operation.js delete mode 100644 scripts/node_modules/mongodb/lib/operations/explain.js delete mode 100644 scripts/node_modules/mongodb/lib/operations/find.js delete mode 100644 scripts/node_modules/mongodb/lib/operations/find_and_modify.js delete mode 100644 scripts/node_modules/mongodb/lib/operations/find_one.js delete mode 100644 scripts/node_modules/mongodb/lib/operations/find_one_and_delete.js delete mode 100644 scripts/node_modules/mongodb/lib/operations/find_one_and_replace.js delete mode 100644 scripts/node_modules/mongodb/lib/operations/find_one_and_update.js delete mode 100644 scripts/node_modules/mongodb/lib/operations/geo_haystack_search.js delete mode 100644 scripts/node_modules/mongodb/lib/operations/has_next.js delete mode 100644 scripts/node_modules/mongodb/lib/operations/index_exists.js delete mode 100644 scripts/node_modules/mongodb/lib/operations/index_information.js delete mode 100644 scripts/node_modules/mongodb/lib/operations/indexes.js delete mode 100644 scripts/node_modules/mongodb/lib/operations/insert_many.js delete mode 100644 scripts/node_modules/mongodb/lib/operations/insert_one.js delete mode 100644 scripts/node_modules/mongodb/lib/operations/is_capped.js delete mode 100644 scripts/node_modules/mongodb/lib/operations/list_collections.js delete mode 100644 scripts/node_modules/mongodb/lib/operations/list_databases.js delete mode 100644 scripts/node_modules/mongodb/lib/operations/list_indexes.js delete mode 100644 scripts/node_modules/mongodb/lib/operations/map_reduce.js delete mode 100644 scripts/node_modules/mongodb/lib/operations/next.js delete mode 100644 scripts/node_modules/mongodb/lib/operations/operation.js delete mode 100644 scripts/node_modules/mongodb/lib/operations/options_operation.js delete mode 100644 scripts/node_modules/mongodb/lib/operations/profiling_level.js delete mode 100644 scripts/node_modules/mongodb/lib/operations/re_index.js delete mode 100644 scripts/node_modules/mongodb/lib/operations/remove_user.js delete mode 100644 scripts/node_modules/mongodb/lib/operations/rename.js delete mode 100644 scripts/node_modules/mongodb/lib/operations/replace_one.js delete mode 100644 scripts/node_modules/mongodb/lib/operations/set_profiling_level.js delete mode 100644 scripts/node_modules/mongodb/lib/operations/stats.js delete mode 100644 scripts/node_modules/mongodb/lib/operations/to_array.js delete mode 100644 scripts/node_modules/mongodb/lib/operations/update_many.js delete mode 100644 scripts/node_modules/mongodb/lib/operations/update_one.js delete mode 100644 scripts/node_modules/mongodb/lib/operations/validate_collection.js delete mode 100644 scripts/node_modules/mongodb/lib/read_concern.js delete mode 100644 scripts/node_modules/mongodb/lib/topologies/mongos.js delete mode 100644 scripts/node_modules/mongodb/lib/topologies/native_topology.js delete mode 100644 scripts/node_modules/mongodb/lib/topologies/replset.js delete mode 100644 scripts/node_modules/mongodb/lib/topologies/server.js delete mode 100644 scripts/node_modules/mongodb/lib/topologies/topology_base.js delete mode 100644 scripts/node_modules/mongodb/lib/url_parser.js delete mode 100644 scripts/node_modules/mongodb/lib/utils.js delete mode 100644 scripts/node_modules/mongodb/lib/write_concern.js delete mode 100644 scripts/node_modules/mongodb/package.json delete mode 100644 scripts/node_modules/require_optional/.npmignore delete mode 100644 scripts/node_modules/require_optional/.travis.yml delete mode 100644 scripts/node_modules/require_optional/HISTORY.md delete mode 100644 scripts/node_modules/require_optional/LICENSE delete mode 100644 scripts/node_modules/require_optional/README.md delete mode 100644 scripts/node_modules/require_optional/index.js delete mode 100644 scripts/node_modules/require_optional/package.json delete mode 100644 scripts/node_modules/require_optional/test/nestedTest/index.js delete mode 100644 scripts/node_modules/require_optional/test/nestedTest/package.json delete mode 100644 scripts/node_modules/require_optional/test/require_optional_tests.js delete mode 100644 scripts/node_modules/resolve-from/index.js delete mode 100644 scripts/node_modules/resolve-from/license delete mode 100644 scripts/node_modules/resolve-from/package.json delete mode 100644 scripts/node_modules/resolve-from/readme.md delete mode 100644 scripts/node_modules/safe-buffer/LICENSE delete mode 100644 scripts/node_modules/safe-buffer/README.md delete mode 100644 scripts/node_modules/safe-buffer/index.d.ts delete mode 100644 scripts/node_modules/safe-buffer/index.js delete mode 100644 scripts/node_modules/safe-buffer/package.json delete mode 100644 scripts/node_modules/saslprep/.editorconfig delete mode 100644 scripts/node_modules/saslprep/.gitattributes delete mode 100644 scripts/node_modules/saslprep/.travis.yml delete mode 100644 scripts/node_modules/saslprep/CHANGELOG.md delete mode 100644 scripts/node_modules/saslprep/LICENSE delete mode 100644 scripts/node_modules/saslprep/code-points.mem delete mode 100644 scripts/node_modules/saslprep/generate-code-points.js delete mode 100644 scripts/node_modules/saslprep/index.js delete mode 100644 scripts/node_modules/saslprep/lib/code-points.js delete mode 100644 scripts/node_modules/saslprep/lib/memory-code-points.js delete mode 100644 scripts/node_modules/saslprep/lib/util.js delete mode 100644 scripts/node_modules/saslprep/package.json delete mode 100644 scripts/node_modules/saslprep/readme.md delete mode 100644 scripts/node_modules/saslprep/test/index.js delete mode 100644 scripts/node_modules/saslprep/test/util.js delete mode 100644 scripts/node_modules/semver/CHANGELOG.md delete mode 100644 scripts/node_modules/semver/LICENSE delete mode 100644 scripts/node_modules/semver/README.md delete mode 100755 scripts/node_modules/semver/bin/semver delete mode 100644 scripts/node_modules/semver/package.json delete mode 100644 scripts/node_modules/semver/range.bnf delete mode 100644 scripts/node_modules/semver/semver.js delete mode 100644 scripts/node_modules/sparse-bitfield/.npmignore delete mode 100644 scripts/node_modules/sparse-bitfield/.travis.yml delete mode 100644 scripts/node_modules/sparse-bitfield/LICENSE delete mode 100644 scripts/node_modules/sparse-bitfield/README.md delete mode 100644 scripts/node_modules/sparse-bitfield/index.js delete mode 100644 scripts/node_modules/sparse-bitfield/package.json delete mode 100644 scripts/node_modules/sparse-bitfield/test.js diff --git a/scripts/node_modules/.bin/semver b/scripts/node_modules/.bin/semver deleted file mode 120000 index 317eb293..00000000 --- a/scripts/node_modules/.bin/semver +++ /dev/null @@ -1 +0,0 @@ -../semver/bin/semver \ No newline at end of file diff --git a/scripts/node_modules/bson/HISTORY.md b/scripts/node_modules/bson/HISTORY.md deleted file mode 100644 index 0da8acef..00000000 --- a/scripts/node_modules/bson/HISTORY.md +++ /dev/null @@ -1,268 +0,0 @@ - -## [1.1.1](https://github.com/mongodb/js-bson/compare/v1.1.0...v1.1.1) (2019-03-08) - - -### Bug Fixes - -* **object-id:** support 4.x->1.x interop for MinKey and ObjectId ([53419a5](https://github.com/mongodb/js-bson/commit/53419a5)) - - -### Features - -* replace new Buffer with modern versions ([24aefba](https://github.com/mongodb/js-bson/commit/24aefba)) - - - - -# [1.1.0](https://github.com/mongodb/js-bson/compare/v1.0.9...v1.1.0) (2018-08-13) - - -### Bug Fixes - -* **serializer:** do not use checkKeys for $clusterTime ([573e141](https://github.com/mongodb/js-bson/commit/573e141)) - - - - -## [1.0.9](https://github.com/mongodb/js-bson/compare/v1.0.8...v1.0.9) (2018-06-07) - - -### Bug Fixes - -* **serializer:** remove use of `const` ([5feb12f](https://github.com/mongodb/js-bson/commit/5feb12f)) - - - - -## [1.0.7](https://github.com/mongodb/js-bson/compare/v1.0.6...v1.0.7) (2018-06-06) - - -### Bug Fixes - -* **binary:** add type checking for buffer ([26b05b5](https://github.com/mongodb/js-bson/commit/26b05b5)) -* **bson:** fix custom inspect property ([080323b](https://github.com/mongodb/js-bson/commit/080323b)) -* **readme:** clarify documentation about deserialize methods ([20f764c](https://github.com/mongodb/js-bson/commit/20f764c)) -* **serialization:** normalize function stringification ([1320c10](https://github.com/mongodb/js-bson/commit/1320c10)) - - - - -## [1.0.6](https://github.com/mongodb/js-bson/compare/v1.0.5...v1.0.6) (2018-03-12) - - -### Features - -* **serialization:** support arbitrary sizes for the internal serialization buffer ([abe97bc](https://github.com/mongodb/js-bson/commit/abe97bc)) - - - - -## 1.0.5 (2018-02-26) - - -### Bug Fixes - -* **decimal128:** add basic guard against REDOS attacks ([bd61c45](https://github.com/mongodb/js-bson/commit/bd61c45)) -* **objectid:** if pid is 1, use random value ([e188ae6](https://github.com/mongodb/js-bson/commit/e188ae6)) - - - -1.0.4 2016-01-11 ----------------- -- #204 remove Buffer.from as it's partially broken in early 4.x.x. series of node releases. - -1.0.3 2016-01-03 ----------------- -- Fixed toString for ObjectId so it will work with inspect. - -1.0.2 2016-01-02 ----------------- -- Minor optimizations for ObjectID to use Buffer.from where available. - -1.0.1 2016-12-06 ----------------- -- Reverse behavior for undefined to be serialized as NULL. MongoDB 3.4 does not allow for undefined comparisons. - -1.0.0 2016-12-06 ----------------- -- Introduced new BSON API and documentation. - -0.5.7 2016-11-18 ------------------ -- NODE-848 BSON Regex flags must be alphabetically ordered. - -0.5.6 2016-10-19 ------------------ -- NODE-833, Detects cyclic dependencies in documents and throws error if one is found. -- Fix(deserializer): corrected the check for (size + index) comparison… (Issue #195, https://github.com/JoelParke). - -0.5.5 2016-09-15 ------------------ -- Added DBPointer up conversion to DBRef - -0.5.4 2016-08-23 ------------------ -- Added promoteValues flag (default to true) allowing user to specify if deserialization should be into wrapper classes only. - -0.5.3 2016-07-11 ------------------ -- Throw error if ObjectId is not a string or a buffer. - -0.5.2 2016-07-11 ------------------ -- All values encoded big-endian style for ObjectId. - -0.5.1 2016-07-11 ------------------ -- Fixed encoding/decoding issue in ObjectId timestamp generation. -- Removed BinaryParser dependency from the serializer/deserializer. - -0.5.0 2016-07-05 ------------------ -- Added Decimal128 type and extended test suite to include entire bson corpus. - -0.4.23 2016-04-08 ------------------ -- Allow for proper detection of ObjectId or objects that look like ObjectId, improving compatibility across third party libraries. -- Remove one package from dependency due to having been pulled from NPM. - -0.4.22 2016-03-04 ------------------ -- Fix "TypeError: data.copy is not a function" in Electron (Issue #170, https://github.com/kangas). -- Fixed issue with undefined type on deserializing. - -0.4.21 2016-01-12 ------------------ -- Minor optimizations to avoid non needed object creation. - -0.4.20 2015-10-15 ------------------ -- Added bower file to repository. -- Fixed browser pid sometimes set greater than 0xFFFF on browsers (Issue #155, https://github.com/rahatarmanahmed) - -0.4.19 2015-10-15 ------------------ -- Remove all support for bson-ext. - -0.4.18 2015-10-15 ------------------ -- ObjectID equality check should return boolean instead of throwing exception for invalid oid string #139 -- add option for deserializing binary into Buffer object #116 - -0.4.17 2015-10-15 ------------------ -- Validate regexp string for null bytes and throw if there is one. - -0.4.16 2015-10-07 ------------------ -- Fixed issue with return statement in Map.js. - -0.4.15 2015-10-06 ------------------ -- Exposed Map correctly via index.js file. - -0.4.14 2015-10-06 ------------------ -- Exposed Map correctly via bson.js file. - -0.4.13 2015-10-06 ------------------ -- Added ES6 Map type serialization as well as a polyfill for ES5. - -0.4.12 2015-09-18 ------------------ -- Made ignore undefined an optional parameter. - -0.4.11 2015-08-06 ------------------ -- Minor fix for invalid key checking. - -0.4.10 2015-08-06 ------------------ -- NODE-38 Added new BSONRegExp type to allow direct serialization to MongoDB type. -- Some performance improvements by in lining code. - -0.4.9 2015-08-06 ----------------- -- Undefined fields are omitted from serialization in objects. - -0.4.8 2015-07-14 ----------------- -- Fixed size validation to ensure we can deserialize from dumped files. - -0.4.7 2015-06-26 ----------------- -- Added ability to instruct deserializer to return raw BSON buffers for named array fields. -- Minor deserialization optimization by moving inlined function out. - -0.4.6 2015-06-17 ----------------- -- Fixed serializeWithBufferAndIndex bug. - -0.4.5 2015-06-17 ----------------- -- Removed any references to the shared buffer to avoid non GC collectible bson instances. - -0.4.4 2015-06-17 ----------------- -- Fixed rethrowing of error when not RangeError. - -0.4.3 2015-06-17 ----------------- -- Start buffer at 64K and double as needed, meaning we keep a low memory profile until needed. - -0.4.2 2015-06-16 ----------------- -- More fixes for corrupt Bson - -0.4.1 2015-06-16 ----------------- -- More fixes for corrupt Bson - -0.4.0 2015-06-16 ----------------- -- New JS serializer serializing into a single buffer then copying out the new buffer. Performance is similar to current C++ parser. -- Removed bson-ext extension dependency for now. - -0.3.2 2015-03-27 ----------------- -- Removed node-gyp from install script in package.json. - -0.3.1 2015-03-27 ----------------- -- Return pure js version on native() call if failed to initialize. - -0.3.0 2015-03-26 ----------------- -- Pulled out all C++ code into bson-ext and made it an optional dependency. - -0.2.21 2015-03-21 ------------------ -- Updated Nan to 1.7.0 to support io.js and node 0.12.0 - -0.2.19 2015-02-16 ------------------ -- Updated Nan to 1.6.2 to support io.js and node 0.12.0 - -0.2.18 2015-01-20 ------------------ -- Updated Nan to 1.5.1 to support io.js - -0.2.16 2014-12-17 ------------------ -- Made pid cycle on 0xffff to avoid weird overflows on creation of ObjectID's - -0.2.12 2014-08-24 ------------------ -- Fixes for fortify review of c++ extension -- toBSON correctly allows returns of non objects - -0.2.3 2013-10-01 ----------------- -- Drying of ObjectId code for generation of id (Issue #54, https://github.com/moredip) -- Fixed issue where corrupt CString's could cause endless loop -- Support for Node 0.11.X > (Issue #49, https://github.com/kkoopa) - -0.1.4 2012-09-25 ----------------- -- Added precompiled c++ native extensions for win32 ia32 and x64 diff --git a/scripts/node_modules/bson/LICENSE.md b/scripts/node_modules/bson/LICENSE.md deleted file mode 100644 index 261eeb9e..00000000 --- a/scripts/node_modules/bson/LICENSE.md +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/scripts/node_modules/bson/README.md b/scripts/node_modules/bson/README.md deleted file mode 100644 index 06883410..00000000 --- a/scripts/node_modules/bson/README.md +++ /dev/null @@ -1,170 +0,0 @@ -# BSON parser - -BSON is short for Bin­ary JSON and is the bin­ary-en­coded seri­al­iz­a­tion of JSON-like doc­u­ments. You can learn more about it in [the specification](http://bsonspec.org). - -This browser version of the BSON parser is compiled using [webpack](https://webpack.js.org/) and the current version is pre-compiled in the `browser_build` directory. - -This is the default BSON parser, however, there is a C++ Node.js addon version as well that does not support the browser. It can be found at [mongod-js/bson-ext](https://github.com/mongodb-js/bson-ext). - -## Usage - -To build a new version perform the following operations: - -``` -npm install -npm run build -``` - -A simple example of how to use BSON in the browser: - -```html - - - -``` - -A simple example of how to use BSON in `Node.js`: - -```js -// Get BSON parser class -var BSON = require('bson') -// Get the Long type -var Long = BSON.Long; -// Create a bson parser instance -var bson = new BSON(); - -// Serialize document -var doc = { long: Long.fromNumber(100) } - -// Serialize a document -var data = bson.serialize(doc) -console.log('data:', data) - -// Deserialize the resulting Buffer -var doc_2 = bson.deserialize(data) -console.log('doc_2:', doc_2) -``` - -## Installation - -`npm install bson` - -## API - -### BSON types - -For all BSON types documentation, please refer to the following sources: - * [MongoDB BSON Type Reference](https://docs.mongodb.com/manual/reference/bson-types/) - * [BSON Spec](https://bsonspec.org/) - -### BSON serialization and deserialiation - -**`new BSON()`** - Creates a new BSON serializer/deserializer you can use to serialize and deserialize BSON. - -#### BSON.serialize - -The BSON `serialize` method takes a JavaScript object and an optional options object and returns a Node.js Buffer. - - * `BSON.serialize(object, options)` - * @param {Object} object the JavaScript object to serialize. - * @param {Boolean} [options.checkKeys=false] the serializer will check if keys are valid. - * @param {Boolean} [options.serializeFunctions=false] serialize the JavaScript functions. - * @param {Boolean} [options.ignoreUndefined=true] - * @return {Buffer} returns a Buffer instance. - -#### BSON.serializeWithBufferAndIndex - -The BSON `serializeWithBufferAndIndex` method takes an object, a target buffer instance and an optional options object and returns the end serialization index in the final buffer. - - * `BSON.serializeWithBufferAndIndex(object, buffer, options)` - * @param {Object} object the JavaScript object to serialize. - * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. - * @param {Boolean} [options.checkKeys=false] the serializer will check if keys are valid. - * @param {Boolean} [options.serializeFunctions=false] serialize the JavaScript functions. - * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields. - * @param {Number} [options.index=0] the index in the buffer where we wish to start serializing into. - * @return {Number} returns the index pointing to the last written byte in the buffer. - -#### BSON.calculateObjectSize - -The BSON `calculateObjectSize` method takes a JavaScript object and an optional options object and returns the size of the BSON object. - - * `BSON.calculateObjectSize(object, options)` - * @param {Object} object the JavaScript object to serialize. - * @param {Boolean} [options.serializeFunctions=false] serialize the JavaScript functions. - * @param {Boolean} [options.ignoreUndefined=true] - * @return {Buffer} returns a Buffer instance. - -#### BSON.deserialize - -The BSON `deserialize` method takes a Node.js Buffer and an optional options object and returns a deserialized JavaScript object. - - * `BSON.deserialize(buffer, options)` - * @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized. - * @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse. - * @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function. - * @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits - * @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a Node.js Buffer instance. - * @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types. - * @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer. - * @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances. - * @return {Object} returns the deserialized Javascript Object. - -#### BSON.deserializeStream - -The BSON `deserializeStream` method takes a Node.js Buffer, `startIndex` and allow more control over deserialization of a Buffer containing concatenated BSON documents. - - * `BSON.deserializeStream(buffer, startIndex, numberOfDocuments, documents, docStartIndex, options)` - * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. - * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. - * @param {Number} numberOfDocuments number of documents to deserialize. - * @param {Array} documents an array where to store the deserialized documents. - * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. - * @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized. - * @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse. - * @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function. - * @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits - * @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a Node.js Buffer instance. - * @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types. - * @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer. - * @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances. - * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. - -## FAQ - -#### Why does `undefined` get converted to `null`? - -The `undefined` BSON type has been [deprecated for many years](http://bsonspec.org/spec.html), so this library has dropped support for it. Use the `ignoreUndefined` option (for example, from the [driver](http://mongodb.github.io/node-mongodb-native/2.2/api/MongoClient.html#connect) ) to instead remove `undefined` keys. - -#### How do I add custom serialization logic? - -This library looks for `toBSON()` functions on every path, and calls the `toBSON()` function to get the value to serialize. - -```javascript -var bson = new BSON(); - -class CustomSerialize { - toBSON() { - return 42; - } -} - -const obj = { answer: new CustomSerialize() }; -// "{ answer: 42 }" -console.log(bson.deserialize(bson.serialize(obj))); -``` diff --git a/scripts/node_modules/bson/bower.json b/scripts/node_modules/bson/bower.json deleted file mode 100644 index b32140ea..00000000 --- a/scripts/node_modules/bson/bower.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "name": "bson", - "description": "A bson parser for node.js and the browser", - "keywords": [ - "mongodb", - "bson", - "parser" - ], - "author": "Christian Amor Kvalheim ", - "main": "./browser_build/bson.js", - "license": "Apache-2.0", - "moduleType": [ - "globals", - "node" - ], - "ignore": [ - "**/.*", - "alternate_parsers", - "benchmarks", - "bower_components", - "node_modules", - "test", - "tools" - ] -} diff --git a/scripts/node_modules/bson/browser_build/bson.js b/scripts/node_modules/bson/browser_build/bson.js deleted file mode 100644 index e601c992..00000000 --- a/scripts/node_modules/bson/browser_build/bson.js +++ /dev/null @@ -1,17769 +0,0 @@ -(function webpackUniversalModuleDefinition(root, factory) { - if(typeof exports === 'object' && typeof module === 'object') - module.exports = factory(); - else if(typeof define === 'function' && define.amd) - define([], factory); - else { - var a = factory(); - for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i]; - } -})(this, function() { -return /******/ (function(modules) { // webpackBootstrap -/******/ // The module cache -/******/ var installedModules = {}; - -/******/ // The require function -/******/ function __webpack_require__(moduleId) { - -/******/ // Check if module is in cache -/******/ if(installedModules[moduleId]) -/******/ return installedModules[moduleId].exports; - -/******/ // Create a new module (and put it into the cache) -/******/ var module = installedModules[moduleId] = { -/******/ exports: {}, -/******/ id: moduleId, -/******/ loaded: false -/******/ }; - -/******/ // Execute the module function -/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); - -/******/ // Flag the module as loaded -/******/ module.loaded = true; - -/******/ // Return the exports of the module -/******/ return module.exports; -/******/ } - - -/******/ // expose the modules object (__webpack_modules__) -/******/ __webpack_require__.m = modules; - -/******/ // expose the module cache -/******/ __webpack_require__.c = installedModules; - -/******/ // __webpack_public_path__ -/******/ __webpack_require__.p = "/"; - -/******/ // Load entry module and return exports -/******/ return __webpack_require__(0); -/******/ }) -/************************************************************************/ -/******/ ([ -/* 0 */ -/***/ (function(module, exports, __webpack_require__) { - - __webpack_require__(1); - module.exports = __webpack_require__(327); - - -/***/ }), -/* 1 */ -/***/ (function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(global) {"use strict"; - - __webpack_require__(2); - - __webpack_require__(323); - - __webpack_require__(324); - - if (global._babelPolyfill) { - throw new Error("only one instance of babel-polyfill is allowed"); - } - global._babelPolyfill = true; - - var DEFINE_PROPERTY = "defineProperty"; - function define(O, key, value) { - O[key] || Object[DEFINE_PROPERTY](O, key, { - writable: true, - configurable: true, - value: value - }); - } - - define(String.prototype, "padLeft", "".padStart); - define(String.prototype, "padRight", "".padEnd); - - "pop,reverse,shift,keys,values,entries,indexOf,every,some,forEach,map,filter,find,findIndex,includes,join,slice,concat,push,splice,unshift,sort,lastIndexOf,reduce,reduceRight,copyWithin,fill".split(",").forEach(function (key) { - [][key] && define(Array, key, Function.call.bind([][key])); - }); - /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) - -/***/ }), -/* 2 */ -/***/ (function(module, exports, __webpack_require__) { - - __webpack_require__(3); - __webpack_require__(51); - __webpack_require__(52); - __webpack_require__(53); - __webpack_require__(54); - __webpack_require__(56); - __webpack_require__(59); - __webpack_require__(60); - __webpack_require__(61); - __webpack_require__(62); - __webpack_require__(63); - __webpack_require__(64); - __webpack_require__(65); - __webpack_require__(66); - __webpack_require__(67); - __webpack_require__(69); - __webpack_require__(71); - __webpack_require__(73); - __webpack_require__(75); - __webpack_require__(78); - __webpack_require__(79); - __webpack_require__(80); - __webpack_require__(84); - __webpack_require__(86); - __webpack_require__(88); - __webpack_require__(91); - __webpack_require__(92); - __webpack_require__(93); - __webpack_require__(94); - __webpack_require__(96); - __webpack_require__(97); - __webpack_require__(98); - __webpack_require__(99); - __webpack_require__(100); - __webpack_require__(101); - __webpack_require__(102); - __webpack_require__(104); - __webpack_require__(105); - __webpack_require__(106); - __webpack_require__(108); - __webpack_require__(109); - __webpack_require__(110); - __webpack_require__(112); - __webpack_require__(114); - __webpack_require__(115); - __webpack_require__(116); - __webpack_require__(117); - __webpack_require__(118); - __webpack_require__(119); - __webpack_require__(120); - __webpack_require__(121); - __webpack_require__(122); - __webpack_require__(123); - __webpack_require__(124); - __webpack_require__(125); - __webpack_require__(126); - __webpack_require__(131); - __webpack_require__(132); - __webpack_require__(136); - __webpack_require__(137); - __webpack_require__(138); - __webpack_require__(139); - __webpack_require__(141); - __webpack_require__(142); - __webpack_require__(143); - __webpack_require__(144); - __webpack_require__(145); - __webpack_require__(146); - __webpack_require__(147); - __webpack_require__(148); - __webpack_require__(149); - __webpack_require__(150); - __webpack_require__(151); - __webpack_require__(152); - __webpack_require__(153); - __webpack_require__(154); - __webpack_require__(155); - __webpack_require__(157); - __webpack_require__(158); - __webpack_require__(160); - __webpack_require__(161); - __webpack_require__(167); - __webpack_require__(168); - __webpack_require__(170); - __webpack_require__(171); - __webpack_require__(172); - __webpack_require__(176); - __webpack_require__(177); - __webpack_require__(178); - __webpack_require__(179); - __webpack_require__(180); - __webpack_require__(182); - __webpack_require__(183); - __webpack_require__(184); - __webpack_require__(185); - __webpack_require__(188); - __webpack_require__(190); - __webpack_require__(191); - __webpack_require__(192); - __webpack_require__(194); - __webpack_require__(196); - __webpack_require__(198); - __webpack_require__(199); - __webpack_require__(200); - __webpack_require__(202); - __webpack_require__(203); - __webpack_require__(204); - __webpack_require__(205); - __webpack_require__(216); - __webpack_require__(220); - __webpack_require__(221); - __webpack_require__(223); - __webpack_require__(224); - __webpack_require__(228); - __webpack_require__(229); - __webpack_require__(231); - __webpack_require__(232); - __webpack_require__(233); - __webpack_require__(234); - __webpack_require__(235); - __webpack_require__(236); - __webpack_require__(237); - __webpack_require__(238); - __webpack_require__(239); - __webpack_require__(240); - __webpack_require__(241); - __webpack_require__(242); - __webpack_require__(243); - __webpack_require__(244); - __webpack_require__(245); - __webpack_require__(246); - __webpack_require__(247); - __webpack_require__(248); - __webpack_require__(249); - __webpack_require__(251); - __webpack_require__(252); - __webpack_require__(253); - __webpack_require__(254); - __webpack_require__(255); - __webpack_require__(257); - __webpack_require__(258); - __webpack_require__(259); - __webpack_require__(261); - __webpack_require__(262); - __webpack_require__(263); - __webpack_require__(264); - __webpack_require__(265); - __webpack_require__(266); - __webpack_require__(267); - __webpack_require__(268); - __webpack_require__(270); - __webpack_require__(271); - __webpack_require__(273); - __webpack_require__(274); - __webpack_require__(275); - __webpack_require__(276); - __webpack_require__(279); - __webpack_require__(280); - __webpack_require__(282); - __webpack_require__(283); - __webpack_require__(284); - __webpack_require__(285); - __webpack_require__(287); - __webpack_require__(288); - __webpack_require__(289); - __webpack_require__(290); - __webpack_require__(291); - __webpack_require__(292); - __webpack_require__(293); - __webpack_require__(294); - __webpack_require__(295); - __webpack_require__(296); - __webpack_require__(298); - __webpack_require__(299); - __webpack_require__(300); - __webpack_require__(301); - __webpack_require__(302); - __webpack_require__(303); - __webpack_require__(304); - __webpack_require__(305); - __webpack_require__(306); - __webpack_require__(307); - __webpack_require__(308); - __webpack_require__(310); - __webpack_require__(311); - __webpack_require__(312); - __webpack_require__(313); - __webpack_require__(314); - __webpack_require__(315); - __webpack_require__(316); - __webpack_require__(317); - __webpack_require__(318); - __webpack_require__(319); - __webpack_require__(320); - __webpack_require__(321); - __webpack_require__(322); - module.exports = __webpack_require__(9); - - -/***/ }), -/* 3 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // ECMAScript 6 symbols shim - var global = __webpack_require__(4); - var has = __webpack_require__(5); - var DESCRIPTORS = __webpack_require__(6); - var $export = __webpack_require__(8); - var redefine = __webpack_require__(18); - var META = __webpack_require__(22).KEY; - var $fails = __webpack_require__(7); - var shared = __webpack_require__(23); - var setToStringTag = __webpack_require__(25); - var uid = __webpack_require__(19); - var wks = __webpack_require__(26); - var wksExt = __webpack_require__(27); - var wksDefine = __webpack_require__(28); - var enumKeys = __webpack_require__(29); - var isArray = __webpack_require__(44); - var anObject = __webpack_require__(12); - var isObject = __webpack_require__(13); - var toIObject = __webpack_require__(32); - var toPrimitive = __webpack_require__(16); - var createDesc = __webpack_require__(17); - var _create = __webpack_require__(45); - var gOPNExt = __webpack_require__(48); - var $GOPD = __webpack_require__(50); - var $DP = __webpack_require__(11); - var $keys = __webpack_require__(30); - var gOPD = $GOPD.f; - var dP = $DP.f; - var gOPN = gOPNExt.f; - var $Symbol = global.Symbol; - var $JSON = global.JSON; - var _stringify = $JSON && $JSON.stringify; - var PROTOTYPE = 'prototype'; - var HIDDEN = wks('_hidden'); - var TO_PRIMITIVE = wks('toPrimitive'); - var isEnum = {}.propertyIsEnumerable; - var SymbolRegistry = shared('symbol-registry'); - var AllSymbols = shared('symbols'); - var OPSymbols = shared('op-symbols'); - var ObjectProto = Object[PROTOTYPE]; - var USE_NATIVE = typeof $Symbol == 'function'; - var QObject = global.QObject; - // Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173 - var setter = !QObject || !QObject[PROTOTYPE] || !QObject[PROTOTYPE].findChild; - - // fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687 - var setSymbolDesc = DESCRIPTORS && $fails(function () { - return _create(dP({}, 'a', { - get: function () { return dP(this, 'a', { value: 7 }).a; } - })).a != 7; - }) ? function (it, key, D) { - var protoDesc = gOPD(ObjectProto, key); - if (protoDesc) delete ObjectProto[key]; - dP(it, key, D); - if (protoDesc && it !== ObjectProto) dP(ObjectProto, key, protoDesc); - } : dP; - - var wrap = function (tag) { - var sym = AllSymbols[tag] = _create($Symbol[PROTOTYPE]); - sym._k = tag; - return sym; - }; - - var isSymbol = USE_NATIVE && typeof $Symbol.iterator == 'symbol' ? function (it) { - return typeof it == 'symbol'; - } : function (it) { - return it instanceof $Symbol; - }; - - var $defineProperty = function defineProperty(it, key, D) { - if (it === ObjectProto) $defineProperty(OPSymbols, key, D); - anObject(it); - key = toPrimitive(key, true); - anObject(D); - if (has(AllSymbols, key)) { - if (!D.enumerable) { - if (!has(it, HIDDEN)) dP(it, HIDDEN, createDesc(1, {})); - it[HIDDEN][key] = true; - } else { - if (has(it, HIDDEN) && it[HIDDEN][key]) it[HIDDEN][key] = false; - D = _create(D, { enumerable: createDesc(0, false) }); - } return setSymbolDesc(it, key, D); - } return dP(it, key, D); - }; - var $defineProperties = function defineProperties(it, P) { - anObject(it); - var keys = enumKeys(P = toIObject(P)); - var i = 0; - var l = keys.length; - var key; - while (l > i) $defineProperty(it, key = keys[i++], P[key]); - return it; - }; - var $create = function create(it, P) { - return P === undefined ? _create(it) : $defineProperties(_create(it), P); - }; - var $propertyIsEnumerable = function propertyIsEnumerable(key) { - var E = isEnum.call(this, key = toPrimitive(key, true)); - if (this === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key)) return false; - return E || !has(this, key) || !has(AllSymbols, key) || has(this, HIDDEN) && this[HIDDEN][key] ? E : true; - }; - var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(it, key) { - it = toIObject(it); - key = toPrimitive(key, true); - if (it === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key)) return; - var D = gOPD(it, key); - if (D && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key])) D.enumerable = true; - return D; - }; - var $getOwnPropertyNames = function getOwnPropertyNames(it) { - var names = gOPN(toIObject(it)); - var result = []; - var i = 0; - var key; - while (names.length > i) { - if (!has(AllSymbols, key = names[i++]) && key != HIDDEN && key != META) result.push(key); - } return result; - }; - var $getOwnPropertySymbols = function getOwnPropertySymbols(it) { - var IS_OP = it === ObjectProto; - var names = gOPN(IS_OP ? OPSymbols : toIObject(it)); - var result = []; - var i = 0; - var key; - while (names.length > i) { - if (has(AllSymbols, key = names[i++]) && (IS_OP ? has(ObjectProto, key) : true)) result.push(AllSymbols[key]); - } return result; - }; - - // 19.4.1.1 Symbol([description]) - if (!USE_NATIVE) { - $Symbol = function Symbol() { - if (this instanceof $Symbol) throw TypeError('Symbol is not a constructor!'); - var tag = uid(arguments.length > 0 ? arguments[0] : undefined); - var $set = function (value) { - if (this === ObjectProto) $set.call(OPSymbols, value); - if (has(this, HIDDEN) && has(this[HIDDEN], tag)) this[HIDDEN][tag] = false; - setSymbolDesc(this, tag, createDesc(1, value)); - }; - if (DESCRIPTORS && setter) setSymbolDesc(ObjectProto, tag, { configurable: true, set: $set }); - return wrap(tag); - }; - redefine($Symbol[PROTOTYPE], 'toString', function toString() { - return this._k; - }); - - $GOPD.f = $getOwnPropertyDescriptor; - $DP.f = $defineProperty; - __webpack_require__(49).f = gOPNExt.f = $getOwnPropertyNames; - __webpack_require__(43).f = $propertyIsEnumerable; - __webpack_require__(42).f = $getOwnPropertySymbols; - - if (DESCRIPTORS && !__webpack_require__(24)) { - redefine(ObjectProto, 'propertyIsEnumerable', $propertyIsEnumerable, true); - } - - wksExt.f = function (name) { - return wrap(wks(name)); - }; - } - - $export($export.G + $export.W + $export.F * !USE_NATIVE, { Symbol: $Symbol }); - - for (var es6Symbols = ( - // 19.4.2.2, 19.4.2.3, 19.4.2.4, 19.4.2.6, 19.4.2.8, 19.4.2.9, 19.4.2.10, 19.4.2.11, 19.4.2.12, 19.4.2.13, 19.4.2.14 - 'hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables' - ).split(','), j = 0; es6Symbols.length > j;)wks(es6Symbols[j++]); - - for (var wellKnownSymbols = $keys(wks.store), k = 0; wellKnownSymbols.length > k;) wksDefine(wellKnownSymbols[k++]); - - $export($export.S + $export.F * !USE_NATIVE, 'Symbol', { - // 19.4.2.1 Symbol.for(key) - 'for': function (key) { - return has(SymbolRegistry, key += '') - ? SymbolRegistry[key] - : SymbolRegistry[key] = $Symbol(key); - }, - // 19.4.2.5 Symbol.keyFor(sym) - keyFor: function keyFor(sym) { - if (!isSymbol(sym)) throw TypeError(sym + ' is not a symbol!'); - for (var key in SymbolRegistry) if (SymbolRegistry[key] === sym) return key; - }, - useSetter: function () { setter = true; }, - useSimple: function () { setter = false; } - }); - - $export($export.S + $export.F * !USE_NATIVE, 'Object', { - // 19.1.2.2 Object.create(O [, Properties]) - create: $create, - // 19.1.2.4 Object.defineProperty(O, P, Attributes) - defineProperty: $defineProperty, - // 19.1.2.3 Object.defineProperties(O, Properties) - defineProperties: $defineProperties, - // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P) - getOwnPropertyDescriptor: $getOwnPropertyDescriptor, - // 19.1.2.7 Object.getOwnPropertyNames(O) - getOwnPropertyNames: $getOwnPropertyNames, - // 19.1.2.8 Object.getOwnPropertySymbols(O) - getOwnPropertySymbols: $getOwnPropertySymbols - }); - - // 24.3.2 JSON.stringify(value [, replacer [, space]]) - $JSON && $export($export.S + $export.F * (!USE_NATIVE || $fails(function () { - var S = $Symbol(); - // MS Edge converts symbol values to JSON as {} - // WebKit converts symbol values to JSON as null - // V8 throws on boxed symbols - return _stringify([S]) != '[null]' || _stringify({ a: S }) != '{}' || _stringify(Object(S)) != '{}'; - })), 'JSON', { - stringify: function stringify(it) { - var args = [it]; - var i = 1; - var replacer, $replacer; - while (arguments.length > i) args.push(arguments[i++]); - $replacer = replacer = args[1]; - if (!isObject(replacer) && it === undefined || isSymbol(it)) return; // IE8 returns string on undefined - if (!isArray(replacer)) replacer = function (key, value) { - if (typeof $replacer == 'function') value = $replacer.call(this, key, value); - if (!isSymbol(value)) return value; - }; - args[1] = replacer; - return _stringify.apply($JSON, args); - } - }); - - // 19.4.3.4 Symbol.prototype[@@toPrimitive](hint) - $Symbol[PROTOTYPE][TO_PRIMITIVE] || __webpack_require__(10)($Symbol[PROTOTYPE], TO_PRIMITIVE, $Symbol[PROTOTYPE].valueOf); - // 19.4.3.5 Symbol.prototype[@@toStringTag] - setToStringTag($Symbol, 'Symbol'); - // 20.2.1.9 Math[@@toStringTag] - setToStringTag(Math, 'Math', true); - // 24.3.3 JSON[@@toStringTag] - setToStringTag(global.JSON, 'JSON', true); - - -/***/ }), -/* 4 */ -/***/ (function(module, exports) { - - // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 - var global = module.exports = typeof window != 'undefined' && window.Math == Math - ? window : typeof self != 'undefined' && self.Math == Math ? self - // eslint-disable-next-line no-new-func - : Function('return this')(); - if (typeof __g == 'number') __g = global; // eslint-disable-line no-undef - - -/***/ }), -/* 5 */ -/***/ (function(module, exports) { - - var hasOwnProperty = {}.hasOwnProperty; - module.exports = function (it, key) { - return hasOwnProperty.call(it, key); - }; - - -/***/ }), -/* 6 */ -/***/ (function(module, exports, __webpack_require__) { - - // Thank's IE8 for his funny defineProperty - module.exports = !__webpack_require__(7)(function () { - return Object.defineProperty({}, 'a', { get: function () { return 7; } }).a != 7; - }); - - -/***/ }), -/* 7 */ -/***/ (function(module, exports) { - - module.exports = function (exec) { - try { - return !!exec(); - } catch (e) { - return true; - } - }; - - -/***/ }), -/* 8 */ -/***/ (function(module, exports, __webpack_require__) { - - var global = __webpack_require__(4); - var core = __webpack_require__(9); - var hide = __webpack_require__(10); - var redefine = __webpack_require__(18); - var ctx = __webpack_require__(20); - var PROTOTYPE = 'prototype'; - - var $export = function (type, name, source) { - var IS_FORCED = type & $export.F; - var IS_GLOBAL = type & $export.G; - var IS_STATIC = type & $export.S; - var IS_PROTO = type & $export.P; - var IS_BIND = type & $export.B; - var target = IS_GLOBAL ? global : IS_STATIC ? global[name] || (global[name] = {}) : (global[name] || {})[PROTOTYPE]; - var exports = IS_GLOBAL ? core : core[name] || (core[name] = {}); - var expProto = exports[PROTOTYPE] || (exports[PROTOTYPE] = {}); - var key, own, out, exp; - if (IS_GLOBAL) source = name; - for (key in source) { - // contains in native - own = !IS_FORCED && target && target[key] !== undefined; - // export native or passed - out = (own ? target : source)[key]; - // bind timers to global for call from export context - exp = IS_BIND && own ? ctx(out, global) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out; - // extend global - if (target) redefine(target, key, out, type & $export.U); - // export - if (exports[key] != out) hide(exports, key, exp); - if (IS_PROTO && expProto[key] != out) expProto[key] = out; - } - }; - global.core = core; - // type bitmap - $export.F = 1; // forced - $export.G = 2; // global - $export.S = 4; // static - $export.P = 8; // proto - $export.B = 16; // bind - $export.W = 32; // wrap - $export.U = 64; // safe - $export.R = 128; // real proto method for `library` - module.exports = $export; - - -/***/ }), -/* 9 */ -/***/ (function(module, exports) { - - var core = module.exports = { version: '2.5.7' }; - if (typeof __e == 'number') __e = core; // eslint-disable-line no-undef - - -/***/ }), -/* 10 */ -/***/ (function(module, exports, __webpack_require__) { - - var dP = __webpack_require__(11); - var createDesc = __webpack_require__(17); - module.exports = __webpack_require__(6) ? function (object, key, value) { - return dP.f(object, key, createDesc(1, value)); - } : function (object, key, value) { - object[key] = value; - return object; - }; - - -/***/ }), -/* 11 */ -/***/ (function(module, exports, __webpack_require__) { - - var anObject = __webpack_require__(12); - var IE8_DOM_DEFINE = __webpack_require__(14); - var toPrimitive = __webpack_require__(16); - var dP = Object.defineProperty; - - exports.f = __webpack_require__(6) ? Object.defineProperty : function defineProperty(O, P, Attributes) { - anObject(O); - P = toPrimitive(P, true); - anObject(Attributes); - if (IE8_DOM_DEFINE) try { - return dP(O, P, Attributes); - } catch (e) { /* empty */ } - if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported!'); - if ('value' in Attributes) O[P] = Attributes.value; - return O; - }; - - -/***/ }), -/* 12 */ -/***/ (function(module, exports, __webpack_require__) { - - var isObject = __webpack_require__(13); - module.exports = function (it) { - if (!isObject(it)) throw TypeError(it + ' is not an object!'); - return it; - }; - - -/***/ }), -/* 13 */ -/***/ (function(module, exports) { - - module.exports = function (it) { - return typeof it === 'object' ? it !== null : typeof it === 'function'; - }; - - -/***/ }), -/* 14 */ -/***/ (function(module, exports, __webpack_require__) { - - module.exports = !__webpack_require__(6) && !__webpack_require__(7)(function () { - return Object.defineProperty(__webpack_require__(15)('div'), 'a', { get: function () { return 7; } }).a != 7; - }); - - -/***/ }), -/* 15 */ -/***/ (function(module, exports, __webpack_require__) { - - var isObject = __webpack_require__(13); - var document = __webpack_require__(4).document; - // typeof document.createElement is 'object' in old IE - var is = isObject(document) && isObject(document.createElement); - module.exports = function (it) { - return is ? document.createElement(it) : {}; - }; - - -/***/ }), -/* 16 */ -/***/ (function(module, exports, __webpack_require__) { - - // 7.1.1 ToPrimitive(input [, PreferredType]) - var isObject = __webpack_require__(13); - // instead of the ES6 spec version, we didn't implement @@toPrimitive case - // and the second argument - flag - preferred type is a string - module.exports = function (it, S) { - if (!isObject(it)) return it; - var fn, val; - if (S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val; - if (typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it))) return val; - if (!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val; - throw TypeError("Can't convert object to primitive value"); - }; - - -/***/ }), -/* 17 */ -/***/ (function(module, exports) { - - module.exports = function (bitmap, value) { - return { - enumerable: !(bitmap & 1), - configurable: !(bitmap & 2), - writable: !(bitmap & 4), - value: value - }; - }; - - -/***/ }), -/* 18 */ -/***/ (function(module, exports, __webpack_require__) { - - var global = __webpack_require__(4); - var hide = __webpack_require__(10); - var has = __webpack_require__(5); - var SRC = __webpack_require__(19)('src'); - var TO_STRING = 'toString'; - var $toString = Function[TO_STRING]; - var TPL = ('' + $toString).split(TO_STRING); - - __webpack_require__(9).inspectSource = function (it) { - return $toString.call(it); - }; - - (module.exports = function (O, key, val, safe) { - var isFunction = typeof val == 'function'; - if (isFunction) has(val, 'name') || hide(val, 'name', key); - if (O[key] === val) return; - if (isFunction) has(val, SRC) || hide(val, SRC, O[key] ? '' + O[key] : TPL.join(String(key))); - if (O === global) { - O[key] = val; - } else if (!safe) { - delete O[key]; - hide(O, key, val); - } else if (O[key]) { - O[key] = val; - } else { - hide(O, key, val); - } - // add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative - })(Function.prototype, TO_STRING, function toString() { - return typeof this == 'function' && this[SRC] || $toString.call(this); - }); - - -/***/ }), -/* 19 */ -/***/ (function(module, exports) { - - var id = 0; - var px = Math.random(); - module.exports = function (key) { - return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36)); - }; - - -/***/ }), -/* 20 */ -/***/ (function(module, exports, __webpack_require__) { - - // optional / simple context binding - var aFunction = __webpack_require__(21); - module.exports = function (fn, that, length) { - aFunction(fn); - if (that === undefined) return fn; - switch (length) { - case 1: return function (a) { - return fn.call(that, a); - }; - case 2: return function (a, b) { - return fn.call(that, a, b); - }; - case 3: return function (a, b, c) { - return fn.call(that, a, b, c); - }; - } - return function (/* ...args */) { - return fn.apply(that, arguments); - }; - }; - - -/***/ }), -/* 21 */ -/***/ (function(module, exports) { - - module.exports = function (it) { - if (typeof it != 'function') throw TypeError(it + ' is not a function!'); - return it; - }; - - -/***/ }), -/* 22 */ -/***/ (function(module, exports, __webpack_require__) { - - var META = __webpack_require__(19)('meta'); - var isObject = __webpack_require__(13); - var has = __webpack_require__(5); - var setDesc = __webpack_require__(11).f; - var id = 0; - var isExtensible = Object.isExtensible || function () { - return true; - }; - var FREEZE = !__webpack_require__(7)(function () { - return isExtensible(Object.preventExtensions({})); - }); - var setMeta = function (it) { - setDesc(it, META, { value: { - i: 'O' + ++id, // object ID - w: {} // weak collections IDs - } }); - }; - var fastKey = function (it, create) { - // return primitive with prefix - if (!isObject(it)) return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it; - if (!has(it, META)) { - // can't set metadata to uncaught frozen object - if (!isExtensible(it)) return 'F'; - // not necessary to add metadata - if (!create) return 'E'; - // add missing metadata - setMeta(it); - // return object ID - } return it[META].i; - }; - var getWeak = function (it, create) { - if (!has(it, META)) { - // can't set metadata to uncaught frozen object - if (!isExtensible(it)) return true; - // not necessary to add metadata - if (!create) return false; - // add missing metadata - setMeta(it); - // return hash weak collections IDs - } return it[META].w; - }; - // add metadata on freeze-family methods calling - var onFreeze = function (it) { - if (FREEZE && meta.NEED && isExtensible(it) && !has(it, META)) setMeta(it); - return it; - }; - var meta = module.exports = { - KEY: META, - NEED: false, - fastKey: fastKey, - getWeak: getWeak, - onFreeze: onFreeze - }; - - -/***/ }), -/* 23 */ -/***/ (function(module, exports, __webpack_require__) { - - var core = __webpack_require__(9); - var global = __webpack_require__(4); - var SHARED = '__core-js_shared__'; - var store = global[SHARED] || (global[SHARED] = {}); - - (module.exports = function (key, value) { - return store[key] || (store[key] = value !== undefined ? value : {}); - })('versions', []).push({ - version: core.version, - mode: __webpack_require__(24) ? 'pure' : 'global', - copyright: '© 2018 Denis Pushkarev (zloirock.ru)' - }); - - -/***/ }), -/* 24 */ -/***/ (function(module, exports) { - - module.exports = false; - - -/***/ }), -/* 25 */ -/***/ (function(module, exports, __webpack_require__) { - - var def = __webpack_require__(11).f; - var has = __webpack_require__(5); - var TAG = __webpack_require__(26)('toStringTag'); - - module.exports = function (it, tag, stat) { - if (it && !has(it = stat ? it : it.prototype, TAG)) def(it, TAG, { configurable: true, value: tag }); - }; - - -/***/ }), -/* 26 */ -/***/ (function(module, exports, __webpack_require__) { - - var store = __webpack_require__(23)('wks'); - var uid = __webpack_require__(19); - var Symbol = __webpack_require__(4).Symbol; - var USE_SYMBOL = typeof Symbol == 'function'; - - var $exports = module.exports = function (name) { - return store[name] || (store[name] = - USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)('Symbol.' + name)); - }; - - $exports.store = store; - - -/***/ }), -/* 27 */ -/***/ (function(module, exports, __webpack_require__) { - - exports.f = __webpack_require__(26); - - -/***/ }), -/* 28 */ -/***/ (function(module, exports, __webpack_require__) { - - var global = __webpack_require__(4); - var core = __webpack_require__(9); - var LIBRARY = __webpack_require__(24); - var wksExt = __webpack_require__(27); - var defineProperty = __webpack_require__(11).f; - module.exports = function (name) { - var $Symbol = core.Symbol || (core.Symbol = LIBRARY ? {} : global.Symbol || {}); - if (name.charAt(0) != '_' && !(name in $Symbol)) defineProperty($Symbol, name, { value: wksExt.f(name) }); - }; - - -/***/ }), -/* 29 */ -/***/ (function(module, exports, __webpack_require__) { - - // all enumerable object keys, includes symbols - var getKeys = __webpack_require__(30); - var gOPS = __webpack_require__(42); - var pIE = __webpack_require__(43); - module.exports = function (it) { - var result = getKeys(it); - var getSymbols = gOPS.f; - if (getSymbols) { - var symbols = getSymbols(it); - var isEnum = pIE.f; - var i = 0; - var key; - while (symbols.length > i) if (isEnum.call(it, key = symbols[i++])) result.push(key); - } return result; - }; - - -/***/ }), -/* 30 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.2.14 / 15.2.3.14 Object.keys(O) - var $keys = __webpack_require__(31); - var enumBugKeys = __webpack_require__(41); - - module.exports = Object.keys || function keys(O) { - return $keys(O, enumBugKeys); - }; - - -/***/ }), -/* 31 */ -/***/ (function(module, exports, __webpack_require__) { - - var has = __webpack_require__(5); - var toIObject = __webpack_require__(32); - var arrayIndexOf = __webpack_require__(36)(false); - var IE_PROTO = __webpack_require__(40)('IE_PROTO'); - - module.exports = function (object, names) { - var O = toIObject(object); - var i = 0; - var result = []; - var key; - for (key in O) if (key != IE_PROTO) has(O, key) && result.push(key); - // Don't enum bug & hidden keys - while (names.length > i) if (has(O, key = names[i++])) { - ~arrayIndexOf(result, key) || result.push(key); - } - return result; - }; - - -/***/ }), -/* 32 */ -/***/ (function(module, exports, __webpack_require__) { - - // to indexed object, toObject with fallback for non-array-like ES3 strings - var IObject = __webpack_require__(33); - var defined = __webpack_require__(35); - module.exports = function (it) { - return IObject(defined(it)); - }; - - -/***/ }), -/* 33 */ -/***/ (function(module, exports, __webpack_require__) { - - // fallback for non-array-like ES3 and non-enumerable old V8 strings - var cof = __webpack_require__(34); - // eslint-disable-next-line no-prototype-builtins - module.exports = Object('z').propertyIsEnumerable(0) ? Object : function (it) { - return cof(it) == 'String' ? it.split('') : Object(it); - }; - - -/***/ }), -/* 34 */ -/***/ (function(module, exports) { - - var toString = {}.toString; - - module.exports = function (it) { - return toString.call(it).slice(8, -1); - }; - - -/***/ }), -/* 35 */ -/***/ (function(module, exports) { - - // 7.2.1 RequireObjectCoercible(argument) - module.exports = function (it) { - if (it == undefined) throw TypeError("Can't call method on " + it); - return it; - }; - - -/***/ }), -/* 36 */ -/***/ (function(module, exports, __webpack_require__) { - - // false -> Array#indexOf - // true -> Array#includes - var toIObject = __webpack_require__(32); - var toLength = __webpack_require__(37); - var toAbsoluteIndex = __webpack_require__(39); - module.exports = function (IS_INCLUDES) { - return function ($this, el, fromIndex) { - var O = toIObject($this); - var length = toLength(O.length); - var index = toAbsoluteIndex(fromIndex, length); - var value; - // Array#includes uses SameValueZero equality algorithm - // eslint-disable-next-line no-self-compare - if (IS_INCLUDES && el != el) while (length > index) { - value = O[index++]; - // eslint-disable-next-line no-self-compare - if (value != value) return true; - // Array#indexOf ignores holes, Array#includes - not - } else for (;length > index; index++) if (IS_INCLUDES || index in O) { - if (O[index] === el) return IS_INCLUDES || index || 0; - } return !IS_INCLUDES && -1; - }; - }; - - -/***/ }), -/* 37 */ -/***/ (function(module, exports, __webpack_require__) { - - // 7.1.15 ToLength - var toInteger = __webpack_require__(38); - var min = Math.min; - module.exports = function (it) { - return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991 - }; - - -/***/ }), -/* 38 */ -/***/ (function(module, exports) { - - // 7.1.4 ToInteger - var ceil = Math.ceil; - var floor = Math.floor; - module.exports = function (it) { - return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it); - }; - - -/***/ }), -/* 39 */ -/***/ (function(module, exports, __webpack_require__) { - - var toInteger = __webpack_require__(38); - var max = Math.max; - var min = Math.min; - module.exports = function (index, length) { - index = toInteger(index); - return index < 0 ? max(index + length, 0) : min(index, length); - }; - - -/***/ }), -/* 40 */ -/***/ (function(module, exports, __webpack_require__) { - - var shared = __webpack_require__(23)('keys'); - var uid = __webpack_require__(19); - module.exports = function (key) { - return shared[key] || (shared[key] = uid(key)); - }; - - -/***/ }), -/* 41 */ -/***/ (function(module, exports) { - - // IE 8- don't enum bug keys - module.exports = ( - 'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf' - ).split(','); - - -/***/ }), -/* 42 */ -/***/ (function(module, exports) { - - exports.f = Object.getOwnPropertySymbols; - - -/***/ }), -/* 43 */ -/***/ (function(module, exports) { - - exports.f = {}.propertyIsEnumerable; - - -/***/ }), -/* 44 */ -/***/ (function(module, exports, __webpack_require__) { - - // 7.2.2 IsArray(argument) - var cof = __webpack_require__(34); - module.exports = Array.isArray || function isArray(arg) { - return cof(arg) == 'Array'; - }; - - -/***/ }), -/* 45 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) - var anObject = __webpack_require__(12); - var dPs = __webpack_require__(46); - var enumBugKeys = __webpack_require__(41); - var IE_PROTO = __webpack_require__(40)('IE_PROTO'); - var Empty = function () { /* empty */ }; - var PROTOTYPE = 'prototype'; - - // Create object with fake `null` prototype: use iframe Object with cleared prototype - var createDict = function () { - // Thrash, waste and sodomy: IE GC bug - var iframe = __webpack_require__(15)('iframe'); - var i = enumBugKeys.length; - var lt = '<'; - var gt = '>'; - var iframeDocument; - iframe.style.display = 'none'; - __webpack_require__(47).appendChild(iframe); - iframe.src = 'javascript:'; // eslint-disable-line no-script-url - // createDict = iframe.contentWindow.Object; - // html.removeChild(iframe); - iframeDocument = iframe.contentWindow.document; - iframeDocument.open(); - iframeDocument.write(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt); - iframeDocument.close(); - createDict = iframeDocument.F; - while (i--) delete createDict[PROTOTYPE][enumBugKeys[i]]; - return createDict(); - }; - - module.exports = Object.create || function create(O, Properties) { - var result; - if (O !== null) { - Empty[PROTOTYPE] = anObject(O); - result = new Empty(); - Empty[PROTOTYPE] = null; - // add "__proto__" for Object.getPrototypeOf polyfill - result[IE_PROTO] = O; - } else result = createDict(); - return Properties === undefined ? result : dPs(result, Properties); - }; - - -/***/ }), -/* 46 */ -/***/ (function(module, exports, __webpack_require__) { - - var dP = __webpack_require__(11); - var anObject = __webpack_require__(12); - var getKeys = __webpack_require__(30); - - module.exports = __webpack_require__(6) ? Object.defineProperties : function defineProperties(O, Properties) { - anObject(O); - var keys = getKeys(Properties); - var length = keys.length; - var i = 0; - var P; - while (length > i) dP.f(O, P = keys[i++], Properties[P]); - return O; - }; - - -/***/ }), -/* 47 */ -/***/ (function(module, exports, __webpack_require__) { - - var document = __webpack_require__(4).document; - module.exports = document && document.documentElement; - - -/***/ }), -/* 48 */ -/***/ (function(module, exports, __webpack_require__) { - - // fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window - var toIObject = __webpack_require__(32); - var gOPN = __webpack_require__(49).f; - var toString = {}.toString; - - var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames - ? Object.getOwnPropertyNames(window) : []; - - var getWindowNames = function (it) { - try { - return gOPN(it); - } catch (e) { - return windowNames.slice(); - } - }; - - module.exports.f = function getOwnPropertyNames(it) { - return windowNames && toString.call(it) == '[object Window]' ? getWindowNames(it) : gOPN(toIObject(it)); - }; - - -/***/ }), -/* 49 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O) - var $keys = __webpack_require__(31); - var hiddenKeys = __webpack_require__(41).concat('length', 'prototype'); - - exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) { - return $keys(O, hiddenKeys); - }; - - -/***/ }), -/* 50 */ -/***/ (function(module, exports, __webpack_require__) { - - var pIE = __webpack_require__(43); - var createDesc = __webpack_require__(17); - var toIObject = __webpack_require__(32); - var toPrimitive = __webpack_require__(16); - var has = __webpack_require__(5); - var IE8_DOM_DEFINE = __webpack_require__(14); - var gOPD = Object.getOwnPropertyDescriptor; - - exports.f = __webpack_require__(6) ? gOPD : function getOwnPropertyDescriptor(O, P) { - O = toIObject(O); - P = toPrimitive(P, true); - if (IE8_DOM_DEFINE) try { - return gOPD(O, P); - } catch (e) { /* empty */ } - if (has(O, P)) return createDesc(!pIE.f.call(O, P), O[P]); - }; - - -/***/ }), -/* 51 */ -/***/ (function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8); - // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) - $export($export.S, 'Object', { create: __webpack_require__(45) }); - - -/***/ }), -/* 52 */ -/***/ (function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8); - // 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes) - $export($export.S + $export.F * !__webpack_require__(6), 'Object', { defineProperty: __webpack_require__(11).f }); - - -/***/ }), -/* 53 */ -/***/ (function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8); - // 19.1.2.3 / 15.2.3.7 Object.defineProperties(O, Properties) - $export($export.S + $export.F * !__webpack_require__(6), 'Object', { defineProperties: __webpack_require__(46) }); - - -/***/ }), -/* 54 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P) - var toIObject = __webpack_require__(32); - var $getOwnPropertyDescriptor = __webpack_require__(50).f; - - __webpack_require__(55)('getOwnPropertyDescriptor', function () { - return function getOwnPropertyDescriptor(it, key) { - return $getOwnPropertyDescriptor(toIObject(it), key); - }; - }); - - -/***/ }), -/* 55 */ -/***/ (function(module, exports, __webpack_require__) { - - // most Object methods by ES6 should accept primitives - var $export = __webpack_require__(8); - var core = __webpack_require__(9); - var fails = __webpack_require__(7); - module.exports = function (KEY, exec) { - var fn = (core.Object || {})[KEY] || Object[KEY]; - var exp = {}; - exp[KEY] = exec(fn); - $export($export.S + $export.F * fails(function () { fn(1); }), 'Object', exp); - }; - - -/***/ }), -/* 56 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.2.9 Object.getPrototypeOf(O) - var toObject = __webpack_require__(57); - var $getPrototypeOf = __webpack_require__(58); - - __webpack_require__(55)('getPrototypeOf', function () { - return function getPrototypeOf(it) { - return $getPrototypeOf(toObject(it)); - }; - }); - - -/***/ }), -/* 57 */ -/***/ (function(module, exports, __webpack_require__) { - - // 7.1.13 ToObject(argument) - var defined = __webpack_require__(35); - module.exports = function (it) { - return Object(defined(it)); - }; - - -/***/ }), -/* 58 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O) - var has = __webpack_require__(5); - var toObject = __webpack_require__(57); - var IE_PROTO = __webpack_require__(40)('IE_PROTO'); - var ObjectProto = Object.prototype; - - module.exports = Object.getPrototypeOf || function (O) { - O = toObject(O); - if (has(O, IE_PROTO)) return O[IE_PROTO]; - if (typeof O.constructor == 'function' && O instanceof O.constructor) { - return O.constructor.prototype; - } return O instanceof Object ? ObjectProto : null; - }; - - -/***/ }), -/* 59 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.2.14 Object.keys(O) - var toObject = __webpack_require__(57); - var $keys = __webpack_require__(30); - - __webpack_require__(55)('keys', function () { - return function keys(it) { - return $keys(toObject(it)); - }; - }); - - -/***/ }), -/* 60 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.2.7 Object.getOwnPropertyNames(O) - __webpack_require__(55)('getOwnPropertyNames', function () { - return __webpack_require__(48).f; - }); - - -/***/ }), -/* 61 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.2.5 Object.freeze(O) - var isObject = __webpack_require__(13); - var meta = __webpack_require__(22).onFreeze; - - __webpack_require__(55)('freeze', function ($freeze) { - return function freeze(it) { - return $freeze && isObject(it) ? $freeze(meta(it)) : it; - }; - }); - - -/***/ }), -/* 62 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.2.17 Object.seal(O) - var isObject = __webpack_require__(13); - var meta = __webpack_require__(22).onFreeze; - - __webpack_require__(55)('seal', function ($seal) { - return function seal(it) { - return $seal && isObject(it) ? $seal(meta(it)) : it; - }; - }); - - -/***/ }), -/* 63 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.2.15 Object.preventExtensions(O) - var isObject = __webpack_require__(13); - var meta = __webpack_require__(22).onFreeze; - - __webpack_require__(55)('preventExtensions', function ($preventExtensions) { - return function preventExtensions(it) { - return $preventExtensions && isObject(it) ? $preventExtensions(meta(it)) : it; - }; - }); - - -/***/ }), -/* 64 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.2.12 Object.isFrozen(O) - var isObject = __webpack_require__(13); - - __webpack_require__(55)('isFrozen', function ($isFrozen) { - return function isFrozen(it) { - return isObject(it) ? $isFrozen ? $isFrozen(it) : false : true; - }; - }); - - -/***/ }), -/* 65 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.2.13 Object.isSealed(O) - var isObject = __webpack_require__(13); - - __webpack_require__(55)('isSealed', function ($isSealed) { - return function isSealed(it) { - return isObject(it) ? $isSealed ? $isSealed(it) : false : true; - }; - }); - - -/***/ }), -/* 66 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.2.11 Object.isExtensible(O) - var isObject = __webpack_require__(13); - - __webpack_require__(55)('isExtensible', function ($isExtensible) { - return function isExtensible(it) { - return isObject(it) ? $isExtensible ? $isExtensible(it) : true : false; - }; - }); - - -/***/ }), -/* 67 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.3.1 Object.assign(target, source) - var $export = __webpack_require__(8); - - $export($export.S + $export.F, 'Object', { assign: __webpack_require__(68) }); - - -/***/ }), -/* 68 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // 19.1.2.1 Object.assign(target, source, ...) - var getKeys = __webpack_require__(30); - var gOPS = __webpack_require__(42); - var pIE = __webpack_require__(43); - var toObject = __webpack_require__(57); - var IObject = __webpack_require__(33); - var $assign = Object.assign; - - // should work with symbols and should have deterministic property order (V8 bug) - module.exports = !$assign || __webpack_require__(7)(function () { - var A = {}; - var B = {}; - // eslint-disable-next-line no-undef - var S = Symbol(); - var K = 'abcdefghijklmnopqrst'; - A[S] = 7; - K.split('').forEach(function (k) { B[k] = k; }); - return $assign({}, A)[S] != 7 || Object.keys($assign({}, B)).join('') != K; - }) ? function assign(target, source) { // eslint-disable-line no-unused-vars - var T = toObject(target); - var aLen = arguments.length; - var index = 1; - var getSymbols = gOPS.f; - var isEnum = pIE.f; - while (aLen > index) { - var S = IObject(arguments[index++]); - var keys = getSymbols ? getKeys(S).concat(getSymbols(S)) : getKeys(S); - var length = keys.length; - var j = 0; - var key; - while (length > j) if (isEnum.call(S, key = keys[j++])) T[key] = S[key]; - } return T; - } : $assign; - - -/***/ }), -/* 69 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.3.10 Object.is(value1, value2) - var $export = __webpack_require__(8); - $export($export.S, 'Object', { is: __webpack_require__(70) }); - - -/***/ }), -/* 70 */ -/***/ (function(module, exports) { - - // 7.2.9 SameValue(x, y) - module.exports = Object.is || function is(x, y) { - // eslint-disable-next-line no-self-compare - return x === y ? x !== 0 || 1 / x === 1 / y : x != x && y != y; - }; - - -/***/ }), -/* 71 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.1.3.19 Object.setPrototypeOf(O, proto) - var $export = __webpack_require__(8); - $export($export.S, 'Object', { setPrototypeOf: __webpack_require__(72).set }); - - -/***/ }), -/* 72 */ -/***/ (function(module, exports, __webpack_require__) { - - // Works with __proto__ only. Old v8 can't work with null proto objects. - /* eslint-disable no-proto */ - var isObject = __webpack_require__(13); - var anObject = __webpack_require__(12); - var check = function (O, proto) { - anObject(O); - if (!isObject(proto) && proto !== null) throw TypeError(proto + ": can't set as prototype!"); - }; - module.exports = { - set: Object.setPrototypeOf || ('__proto__' in {} ? // eslint-disable-line - function (test, buggy, set) { - try { - set = __webpack_require__(20)(Function.call, __webpack_require__(50).f(Object.prototype, '__proto__').set, 2); - set(test, []); - buggy = !(test instanceof Array); - } catch (e) { buggy = true; } - return function setPrototypeOf(O, proto) { - check(O, proto); - if (buggy) O.__proto__ = proto; - else set(O, proto); - return O; - }; - }({}, false) : undefined), - check: check - }; - - -/***/ }), -/* 73 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // 19.1.3.6 Object.prototype.toString() - var classof = __webpack_require__(74); - var test = {}; - test[__webpack_require__(26)('toStringTag')] = 'z'; - if (test + '' != '[object z]') { - __webpack_require__(18)(Object.prototype, 'toString', function toString() { - return '[object ' + classof(this) + ']'; - }, true); - } - - -/***/ }), -/* 74 */ -/***/ (function(module, exports, __webpack_require__) { - - // getting tag from 19.1.3.6 Object.prototype.toString() - var cof = __webpack_require__(34); - var TAG = __webpack_require__(26)('toStringTag'); - // ES3 wrong here - var ARG = cof(function () { return arguments; }()) == 'Arguments'; - - // fallback for IE11 Script Access Denied error - var tryGet = function (it, key) { - try { - return it[key]; - } catch (e) { /* empty */ } - }; - - module.exports = function (it) { - var O, T, B; - return it === undefined ? 'Undefined' : it === null ? 'Null' - // @@toStringTag case - : typeof (T = tryGet(O = Object(it), TAG)) == 'string' ? T - // builtinTag case - : ARG ? cof(O) - // ES3 arguments fallback - : (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B; - }; - - -/***/ }), -/* 75 */ -/***/ (function(module, exports, __webpack_require__) { - - // 19.2.3.2 / 15.3.4.5 Function.prototype.bind(thisArg, args...) - var $export = __webpack_require__(8); - - $export($export.P, 'Function', { bind: __webpack_require__(76) }); - - -/***/ }), -/* 76 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var aFunction = __webpack_require__(21); - var isObject = __webpack_require__(13); - var invoke = __webpack_require__(77); - var arraySlice = [].slice; - var factories = {}; - - var construct = function (F, len, args) { - if (!(len in factories)) { - for (var n = [], i = 0; i < len; i++) n[i] = 'a[' + i + ']'; - // eslint-disable-next-line no-new-func - factories[len] = Function('F,a', 'return new F(' + n.join(',') + ')'); - } return factories[len](F, args); - }; - - module.exports = Function.bind || function bind(that /* , ...args */) { - var fn = aFunction(this); - var partArgs = arraySlice.call(arguments, 1); - var bound = function (/* args... */) { - var args = partArgs.concat(arraySlice.call(arguments)); - return this instanceof bound ? construct(fn, args.length, args) : invoke(fn, args, that); - }; - if (isObject(fn.prototype)) bound.prototype = fn.prototype; - return bound; - }; - - -/***/ }), -/* 77 */ -/***/ (function(module, exports) { - - // fast apply, http://jsperf.lnkit.com/fast-apply/5 - module.exports = function (fn, args, that) { - var un = that === undefined; - switch (args.length) { - case 0: return un ? fn() - : fn.call(that); - case 1: return un ? fn(args[0]) - : fn.call(that, args[0]); - case 2: return un ? fn(args[0], args[1]) - : fn.call(that, args[0], args[1]); - case 3: return un ? fn(args[0], args[1], args[2]) - : fn.call(that, args[0], args[1], args[2]); - case 4: return un ? fn(args[0], args[1], args[2], args[3]) - : fn.call(that, args[0], args[1], args[2], args[3]); - } return fn.apply(that, args); - }; - - -/***/ }), -/* 78 */ -/***/ (function(module, exports, __webpack_require__) { - - var dP = __webpack_require__(11).f; - var FProto = Function.prototype; - var nameRE = /^\s*function ([^ (]*)/; - var NAME = 'name'; - - // 19.2.4.2 name - NAME in FProto || __webpack_require__(6) && dP(FProto, NAME, { - configurable: true, - get: function () { - try { - return ('' + this).match(nameRE)[1]; - } catch (e) { - return ''; - } - } - }); - - -/***/ }), -/* 79 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var isObject = __webpack_require__(13); - var getPrototypeOf = __webpack_require__(58); - var HAS_INSTANCE = __webpack_require__(26)('hasInstance'); - var FunctionProto = Function.prototype; - // 19.2.3.6 Function.prototype[@@hasInstance](V) - if (!(HAS_INSTANCE in FunctionProto)) __webpack_require__(11).f(FunctionProto, HAS_INSTANCE, { value: function (O) { - if (typeof this != 'function' || !isObject(O)) return false; - if (!isObject(this.prototype)) return O instanceof this; - // for environment w/o native `@@hasInstance` logic enough `instanceof`, but add this: - while (O = getPrototypeOf(O)) if (this.prototype === O) return true; - return false; - } }); - - -/***/ }), -/* 80 */ -/***/ (function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8); - var $parseInt = __webpack_require__(81); - // 18.2.5 parseInt(string, radix) - $export($export.G + $export.F * (parseInt != $parseInt), { parseInt: $parseInt }); - - -/***/ }), -/* 81 */ -/***/ (function(module, exports, __webpack_require__) { - - var $parseInt = __webpack_require__(4).parseInt; - var $trim = __webpack_require__(82).trim; - var ws = __webpack_require__(83); - var hex = /^[-+]?0[xX]/; - - module.exports = $parseInt(ws + '08') !== 8 || $parseInt(ws + '0x16') !== 22 ? function parseInt(str, radix) { - var string = $trim(String(str), 3); - return $parseInt(string, (radix >>> 0) || (hex.test(string) ? 16 : 10)); - } : $parseInt; - - -/***/ }), -/* 82 */ -/***/ (function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8); - var defined = __webpack_require__(35); - var fails = __webpack_require__(7); - var spaces = __webpack_require__(83); - var space = '[' + spaces + ']'; - var non = '\u200b\u0085'; - var ltrim = RegExp('^' + space + space + '*'); - var rtrim = RegExp(space + space + '*$'); - - var exporter = function (KEY, exec, ALIAS) { - var exp = {}; - var FORCE = fails(function () { - return !!spaces[KEY]() || non[KEY]() != non; - }); - var fn = exp[KEY] = FORCE ? exec(trim) : spaces[KEY]; - if (ALIAS) exp[ALIAS] = fn; - $export($export.P + $export.F * FORCE, 'String', exp); - }; - - // 1 -> String#trimLeft - // 2 -> String#trimRight - // 3 -> String#trim - var trim = exporter.trim = function (string, TYPE) { - string = String(defined(string)); - if (TYPE & 1) string = string.replace(ltrim, ''); - if (TYPE & 2) string = string.replace(rtrim, ''); - return string; - }; - - module.exports = exporter; - - -/***/ }), -/* 83 */ -/***/ (function(module, exports) { - - module.exports = '\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003' + - '\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF'; - - -/***/ }), -/* 84 */ -/***/ (function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8); - var $parseFloat = __webpack_require__(85); - // 18.2.4 parseFloat(string) - $export($export.G + $export.F * (parseFloat != $parseFloat), { parseFloat: $parseFloat }); - - -/***/ }), -/* 85 */ -/***/ (function(module, exports, __webpack_require__) { - - var $parseFloat = __webpack_require__(4).parseFloat; - var $trim = __webpack_require__(82).trim; - - module.exports = 1 / $parseFloat(__webpack_require__(83) + '-0') !== -Infinity ? function parseFloat(str) { - var string = $trim(String(str), 3); - var result = $parseFloat(string); - return result === 0 && string.charAt(0) == '-' ? -0 : result; - } : $parseFloat; - - -/***/ }), -/* 86 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var global = __webpack_require__(4); - var has = __webpack_require__(5); - var cof = __webpack_require__(34); - var inheritIfRequired = __webpack_require__(87); - var toPrimitive = __webpack_require__(16); - var fails = __webpack_require__(7); - var gOPN = __webpack_require__(49).f; - var gOPD = __webpack_require__(50).f; - var dP = __webpack_require__(11).f; - var $trim = __webpack_require__(82).trim; - var NUMBER = 'Number'; - var $Number = global[NUMBER]; - var Base = $Number; - var proto = $Number.prototype; - // Opera ~12 has broken Object#toString - var BROKEN_COF = cof(__webpack_require__(45)(proto)) == NUMBER; - var TRIM = 'trim' in String.prototype; - - // 7.1.3 ToNumber(argument) - var toNumber = function (argument) { - var it = toPrimitive(argument, false); - if (typeof it == 'string' && it.length > 2) { - it = TRIM ? it.trim() : $trim(it, 3); - var first = it.charCodeAt(0); - var third, radix, maxCode; - if (first === 43 || first === 45) { - third = it.charCodeAt(2); - if (third === 88 || third === 120) return NaN; // Number('+0x1') should be NaN, old V8 fix - } else if (first === 48) { - switch (it.charCodeAt(1)) { - case 66: case 98: radix = 2; maxCode = 49; break; // fast equal /^0b[01]+$/i - case 79: case 111: radix = 8; maxCode = 55; break; // fast equal /^0o[0-7]+$/i - default: return +it; - } - for (var digits = it.slice(2), i = 0, l = digits.length, code; i < l; i++) { - code = digits.charCodeAt(i); - // parseInt parses a string to a first unavailable symbol - // but ToNumber should return NaN if a string contains unavailable symbols - if (code < 48 || code > maxCode) return NaN; - } return parseInt(digits, radix); - } - } return +it; - }; - - if (!$Number(' 0o1') || !$Number('0b1') || $Number('+0x1')) { - $Number = function Number(value) { - var it = arguments.length < 1 ? 0 : value; - var that = this; - return that instanceof $Number - // check on 1..constructor(foo) case - && (BROKEN_COF ? fails(function () { proto.valueOf.call(that); }) : cof(that) != NUMBER) - ? inheritIfRequired(new Base(toNumber(it)), that, $Number) : toNumber(it); - }; - for (var keys = __webpack_require__(6) ? gOPN(Base) : ( - // ES3: - 'MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,' + - // ES6 (in case, if modules with ES6 Number statics required before): - 'EPSILON,isFinite,isInteger,isNaN,isSafeInteger,MAX_SAFE_INTEGER,' + - 'MIN_SAFE_INTEGER,parseFloat,parseInt,isInteger' - ).split(','), j = 0, key; keys.length > j; j++) { - if (has(Base, key = keys[j]) && !has($Number, key)) { - dP($Number, key, gOPD(Base, key)); - } - } - $Number.prototype = proto; - proto.constructor = $Number; - __webpack_require__(18)(global, NUMBER, $Number); - } - - -/***/ }), -/* 87 */ -/***/ (function(module, exports, __webpack_require__) { - - var isObject = __webpack_require__(13); - var setPrototypeOf = __webpack_require__(72).set; - module.exports = function (that, target, C) { - var S = target.constructor; - var P; - if (S !== C && typeof S == 'function' && (P = S.prototype) !== C.prototype && isObject(P) && setPrototypeOf) { - setPrototypeOf(that, P); - } return that; - }; - - -/***/ }), -/* 88 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var toInteger = __webpack_require__(38); - var aNumberValue = __webpack_require__(89); - var repeat = __webpack_require__(90); - var $toFixed = 1.0.toFixed; - var floor = Math.floor; - var data = [0, 0, 0, 0, 0, 0]; - var ERROR = 'Number.toFixed: incorrect invocation!'; - var ZERO = '0'; - - var multiply = function (n, c) { - var i = -1; - var c2 = c; - while (++i < 6) { - c2 += n * data[i]; - data[i] = c2 % 1e7; - c2 = floor(c2 / 1e7); - } - }; - var divide = function (n) { - var i = 6; - var c = 0; - while (--i >= 0) { - c += data[i]; - data[i] = floor(c / n); - c = (c % n) * 1e7; - } - }; - var numToString = function () { - var i = 6; - var s = ''; - while (--i >= 0) { - if (s !== '' || i === 0 || data[i] !== 0) { - var t = String(data[i]); - s = s === '' ? t : s + repeat.call(ZERO, 7 - t.length) + t; - } - } return s; - }; - var pow = function (x, n, acc) { - return n === 0 ? acc : n % 2 === 1 ? pow(x, n - 1, acc * x) : pow(x * x, n / 2, acc); - }; - var log = function (x) { - var n = 0; - var x2 = x; - while (x2 >= 4096) { - n += 12; - x2 /= 4096; - } - while (x2 >= 2) { - n += 1; - x2 /= 2; - } return n; - }; - - $export($export.P + $export.F * (!!$toFixed && ( - 0.00008.toFixed(3) !== '0.000' || - 0.9.toFixed(0) !== '1' || - 1.255.toFixed(2) !== '1.25' || - 1000000000000000128.0.toFixed(0) !== '1000000000000000128' - ) || !__webpack_require__(7)(function () { - // V8 ~ Android 4.3- - $toFixed.call({}); - })), 'Number', { - toFixed: function toFixed(fractionDigits) { - var x = aNumberValue(this, ERROR); - var f = toInteger(fractionDigits); - var s = ''; - var m = ZERO; - var e, z, j, k; - if (f < 0 || f > 20) throw RangeError(ERROR); - // eslint-disable-next-line no-self-compare - if (x != x) return 'NaN'; - if (x <= -1e21 || x >= 1e21) return String(x); - if (x < 0) { - s = '-'; - x = -x; - } - if (x > 1e-21) { - e = log(x * pow(2, 69, 1)) - 69; - z = e < 0 ? x * pow(2, -e, 1) : x / pow(2, e, 1); - z *= 0x10000000000000; - e = 52 - e; - if (e > 0) { - multiply(0, z); - j = f; - while (j >= 7) { - multiply(1e7, 0); - j -= 7; - } - multiply(pow(10, j, 1), 0); - j = e - 1; - while (j >= 23) { - divide(1 << 23); - j -= 23; - } - divide(1 << j); - multiply(1, 1); - divide(2); - m = numToString(); - } else { - multiply(0, z); - multiply(1 << -e, 0); - m = numToString() + repeat.call(ZERO, f); - } - } - if (f > 0) { - k = m.length; - m = s + (k <= f ? '0.' + repeat.call(ZERO, f - k) + m : m.slice(0, k - f) + '.' + m.slice(k - f)); - } else { - m = s + m; - } return m; - } - }); - - -/***/ }), -/* 89 */ -/***/ (function(module, exports, __webpack_require__) { - - var cof = __webpack_require__(34); - module.exports = function (it, msg) { - if (typeof it != 'number' && cof(it) != 'Number') throw TypeError(msg); - return +it; - }; - - -/***/ }), -/* 90 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var toInteger = __webpack_require__(38); - var defined = __webpack_require__(35); - - module.exports = function repeat(count) { - var str = String(defined(this)); - var res = ''; - var n = toInteger(count); - if (n < 0 || n == Infinity) throw RangeError("Count can't be negative"); - for (;n > 0; (n >>>= 1) && (str += str)) if (n & 1) res += str; - return res; - }; - - -/***/ }), -/* 91 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var $fails = __webpack_require__(7); - var aNumberValue = __webpack_require__(89); - var $toPrecision = 1.0.toPrecision; - - $export($export.P + $export.F * ($fails(function () { - // IE7- - return $toPrecision.call(1, undefined) !== '1'; - }) || !$fails(function () { - // V8 ~ Android 4.3- - $toPrecision.call({}); - })), 'Number', { - toPrecision: function toPrecision(precision) { - var that = aNumberValue(this, 'Number#toPrecision: incorrect invocation!'); - return precision === undefined ? $toPrecision.call(that) : $toPrecision.call(that, precision); - } - }); - - -/***/ }), -/* 92 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.1.2.1 Number.EPSILON - var $export = __webpack_require__(8); - - $export($export.S, 'Number', { EPSILON: Math.pow(2, -52) }); - - -/***/ }), -/* 93 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.1.2.2 Number.isFinite(number) - var $export = __webpack_require__(8); - var _isFinite = __webpack_require__(4).isFinite; - - $export($export.S, 'Number', { - isFinite: function isFinite(it) { - return typeof it == 'number' && _isFinite(it); - } - }); - - -/***/ }), -/* 94 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.1.2.3 Number.isInteger(number) - var $export = __webpack_require__(8); - - $export($export.S, 'Number', { isInteger: __webpack_require__(95) }); - - -/***/ }), -/* 95 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.1.2.3 Number.isInteger(number) - var isObject = __webpack_require__(13); - var floor = Math.floor; - module.exports = function isInteger(it) { - return !isObject(it) && isFinite(it) && floor(it) === it; - }; - - -/***/ }), -/* 96 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.1.2.4 Number.isNaN(number) - var $export = __webpack_require__(8); - - $export($export.S, 'Number', { - isNaN: function isNaN(number) { - // eslint-disable-next-line no-self-compare - return number != number; - } - }); - - -/***/ }), -/* 97 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.1.2.5 Number.isSafeInteger(number) - var $export = __webpack_require__(8); - var isInteger = __webpack_require__(95); - var abs = Math.abs; - - $export($export.S, 'Number', { - isSafeInteger: function isSafeInteger(number) { - return isInteger(number) && abs(number) <= 0x1fffffffffffff; - } - }); - - -/***/ }), -/* 98 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.1.2.6 Number.MAX_SAFE_INTEGER - var $export = __webpack_require__(8); - - $export($export.S, 'Number', { MAX_SAFE_INTEGER: 0x1fffffffffffff }); - - -/***/ }), -/* 99 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.1.2.10 Number.MIN_SAFE_INTEGER - var $export = __webpack_require__(8); - - $export($export.S, 'Number', { MIN_SAFE_INTEGER: -0x1fffffffffffff }); - - -/***/ }), -/* 100 */ -/***/ (function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8); - var $parseFloat = __webpack_require__(85); - // 20.1.2.12 Number.parseFloat(string) - $export($export.S + $export.F * (Number.parseFloat != $parseFloat), 'Number', { parseFloat: $parseFloat }); - - -/***/ }), -/* 101 */ -/***/ (function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8); - var $parseInt = __webpack_require__(81); - // 20.1.2.13 Number.parseInt(string, radix) - $export($export.S + $export.F * (Number.parseInt != $parseInt), 'Number', { parseInt: $parseInt }); - - -/***/ }), -/* 102 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.3 Math.acosh(x) - var $export = __webpack_require__(8); - var log1p = __webpack_require__(103); - var sqrt = Math.sqrt; - var $acosh = Math.acosh; - - $export($export.S + $export.F * !($acosh - // V8 bug: https://code.google.com/p/v8/issues/detail?id=3509 - && Math.floor($acosh(Number.MAX_VALUE)) == 710 - // Tor Browser bug: Math.acosh(Infinity) -> NaN - && $acosh(Infinity) == Infinity - ), 'Math', { - acosh: function acosh(x) { - return (x = +x) < 1 ? NaN : x > 94906265.62425156 - ? Math.log(x) + Math.LN2 - : log1p(x - 1 + sqrt(x - 1) * sqrt(x + 1)); - } - }); - - -/***/ }), -/* 103 */ -/***/ (function(module, exports) { - - // 20.2.2.20 Math.log1p(x) - module.exports = Math.log1p || function log1p(x) { - return (x = +x) > -1e-8 && x < 1e-8 ? x - x * x / 2 : Math.log(1 + x); - }; - - -/***/ }), -/* 104 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.5 Math.asinh(x) - var $export = __webpack_require__(8); - var $asinh = Math.asinh; - - function asinh(x) { - return !isFinite(x = +x) || x == 0 ? x : x < 0 ? -asinh(-x) : Math.log(x + Math.sqrt(x * x + 1)); - } - - // Tor Browser bug: Math.asinh(0) -> -0 - $export($export.S + $export.F * !($asinh && 1 / $asinh(0) > 0), 'Math', { asinh: asinh }); - - -/***/ }), -/* 105 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.7 Math.atanh(x) - var $export = __webpack_require__(8); - var $atanh = Math.atanh; - - // Tor Browser bug: Math.atanh(-0) -> 0 - $export($export.S + $export.F * !($atanh && 1 / $atanh(-0) < 0), 'Math', { - atanh: function atanh(x) { - return (x = +x) == 0 ? x : Math.log((1 + x) / (1 - x)) / 2; - } - }); - - -/***/ }), -/* 106 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.9 Math.cbrt(x) - var $export = __webpack_require__(8); - var sign = __webpack_require__(107); - - $export($export.S, 'Math', { - cbrt: function cbrt(x) { - return sign(x = +x) * Math.pow(Math.abs(x), 1 / 3); - } - }); - - -/***/ }), -/* 107 */ -/***/ (function(module, exports) { - - // 20.2.2.28 Math.sign(x) - module.exports = Math.sign || function sign(x) { - // eslint-disable-next-line no-self-compare - return (x = +x) == 0 || x != x ? x : x < 0 ? -1 : 1; - }; - - -/***/ }), -/* 108 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.11 Math.clz32(x) - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { - clz32: function clz32(x) { - return (x >>>= 0) ? 31 - Math.floor(Math.log(x + 0.5) * Math.LOG2E) : 32; - } - }); - - -/***/ }), -/* 109 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.12 Math.cosh(x) - var $export = __webpack_require__(8); - var exp = Math.exp; - - $export($export.S, 'Math', { - cosh: function cosh(x) { - return (exp(x = +x) + exp(-x)) / 2; - } - }); - - -/***/ }), -/* 110 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.14 Math.expm1(x) - var $export = __webpack_require__(8); - var $expm1 = __webpack_require__(111); - - $export($export.S + $export.F * ($expm1 != Math.expm1), 'Math', { expm1: $expm1 }); - - -/***/ }), -/* 111 */ -/***/ (function(module, exports) { - - // 20.2.2.14 Math.expm1(x) - var $expm1 = Math.expm1; - module.exports = (!$expm1 - // Old FF bug - || $expm1(10) > 22025.465794806719 || $expm1(10) < 22025.4657948067165168 - // Tor Browser bug - || $expm1(-2e-17) != -2e-17 - ) ? function expm1(x) { - return (x = +x) == 0 ? x : x > -1e-6 && x < 1e-6 ? x + x * x / 2 : Math.exp(x) - 1; - } : $expm1; - - -/***/ }), -/* 112 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.16 Math.fround(x) - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { fround: __webpack_require__(113) }); - - -/***/ }), -/* 113 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.16 Math.fround(x) - var sign = __webpack_require__(107); - var pow = Math.pow; - var EPSILON = pow(2, -52); - var EPSILON32 = pow(2, -23); - var MAX32 = pow(2, 127) * (2 - EPSILON32); - var MIN32 = pow(2, -126); - - var roundTiesToEven = function (n) { - return n + 1 / EPSILON - 1 / EPSILON; - }; - - module.exports = Math.fround || function fround(x) { - var $abs = Math.abs(x); - var $sign = sign(x); - var a, result; - if ($abs < MIN32) return $sign * roundTiesToEven($abs / MIN32 / EPSILON32) * MIN32 * EPSILON32; - a = (1 + EPSILON32 / EPSILON) * $abs; - result = a - (a - $abs); - // eslint-disable-next-line no-self-compare - if (result > MAX32 || result != result) return $sign * Infinity; - return $sign * result; - }; - - -/***/ }), -/* 114 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.17 Math.hypot([value1[, value2[, … ]]]) - var $export = __webpack_require__(8); - var abs = Math.abs; - - $export($export.S, 'Math', { - hypot: function hypot(value1, value2) { // eslint-disable-line no-unused-vars - var sum = 0; - var i = 0; - var aLen = arguments.length; - var larg = 0; - var arg, div; - while (i < aLen) { - arg = abs(arguments[i++]); - if (larg < arg) { - div = larg / arg; - sum = sum * div * div + 1; - larg = arg; - } else if (arg > 0) { - div = arg / larg; - sum += div * div; - } else sum += arg; - } - return larg === Infinity ? Infinity : larg * Math.sqrt(sum); - } - }); - - -/***/ }), -/* 115 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.18 Math.imul(x, y) - var $export = __webpack_require__(8); - var $imul = Math.imul; - - // some WebKit versions fails with big numbers, some has wrong arity - $export($export.S + $export.F * __webpack_require__(7)(function () { - return $imul(0xffffffff, 5) != -5 || $imul.length != 2; - }), 'Math', { - imul: function imul(x, y) { - var UINT16 = 0xffff; - var xn = +x; - var yn = +y; - var xl = UINT16 & xn; - var yl = UINT16 & yn; - return 0 | xl * yl + ((UINT16 & xn >>> 16) * yl + xl * (UINT16 & yn >>> 16) << 16 >>> 0); - } - }); - - -/***/ }), -/* 116 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.21 Math.log10(x) - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { - log10: function log10(x) { - return Math.log(x) * Math.LOG10E; - } - }); - - -/***/ }), -/* 117 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.20 Math.log1p(x) - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { log1p: __webpack_require__(103) }); - - -/***/ }), -/* 118 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.22 Math.log2(x) - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { - log2: function log2(x) { - return Math.log(x) / Math.LN2; - } - }); - - -/***/ }), -/* 119 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.28 Math.sign(x) - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { sign: __webpack_require__(107) }); - - -/***/ }), -/* 120 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.30 Math.sinh(x) - var $export = __webpack_require__(8); - var expm1 = __webpack_require__(111); - var exp = Math.exp; - - // V8 near Chromium 38 has a problem with very small numbers - $export($export.S + $export.F * __webpack_require__(7)(function () { - return !Math.sinh(-2e-17) != -2e-17; - }), 'Math', { - sinh: function sinh(x) { - return Math.abs(x = +x) < 1 - ? (expm1(x) - expm1(-x)) / 2 - : (exp(x - 1) - exp(-x - 1)) * (Math.E / 2); - } - }); - - -/***/ }), -/* 121 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.33 Math.tanh(x) - var $export = __webpack_require__(8); - var expm1 = __webpack_require__(111); - var exp = Math.exp; - - $export($export.S, 'Math', { - tanh: function tanh(x) { - var a = expm1(x = +x); - var b = expm1(-x); - return a == Infinity ? 1 : b == Infinity ? -1 : (a - b) / (exp(x) + exp(-x)); - } - }); - - -/***/ }), -/* 122 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.2.2.34 Math.trunc(x) - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { - trunc: function trunc(it) { - return (it > 0 ? Math.floor : Math.ceil)(it); - } - }); - - -/***/ }), -/* 123 */ -/***/ (function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8); - var toAbsoluteIndex = __webpack_require__(39); - var fromCharCode = String.fromCharCode; - var $fromCodePoint = String.fromCodePoint; - - // length should be 1, old FF problem - $export($export.S + $export.F * (!!$fromCodePoint && $fromCodePoint.length != 1), 'String', { - // 21.1.2.2 String.fromCodePoint(...codePoints) - fromCodePoint: function fromCodePoint(x) { // eslint-disable-line no-unused-vars - var res = []; - var aLen = arguments.length; - var i = 0; - var code; - while (aLen > i) { - code = +arguments[i++]; - if (toAbsoluteIndex(code, 0x10ffff) !== code) throw RangeError(code + ' is not a valid code point'); - res.push(code < 0x10000 - ? fromCharCode(code) - : fromCharCode(((code -= 0x10000) >> 10) + 0xd800, code % 0x400 + 0xdc00) - ); - } return res.join(''); - } - }); - - -/***/ }), -/* 124 */ -/***/ (function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8); - var toIObject = __webpack_require__(32); - var toLength = __webpack_require__(37); - - $export($export.S, 'String', { - // 21.1.2.4 String.raw(callSite, ...substitutions) - raw: function raw(callSite) { - var tpl = toIObject(callSite.raw); - var len = toLength(tpl.length); - var aLen = arguments.length; - var res = []; - var i = 0; - while (len > i) { - res.push(String(tpl[i++])); - if (i < aLen) res.push(String(arguments[i])); - } return res.join(''); - } - }); - - -/***/ }), -/* 125 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // 21.1.3.25 String.prototype.trim() - __webpack_require__(82)('trim', function ($trim) { - return function trim() { - return $trim(this, 3); - }; - }); - - -/***/ }), -/* 126 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $at = __webpack_require__(127)(true); - - // 21.1.3.27 String.prototype[@@iterator]() - __webpack_require__(128)(String, 'String', function (iterated) { - this._t = String(iterated); // target - this._i = 0; // next index - // 21.1.5.2.1 %StringIteratorPrototype%.next() - }, function () { - var O = this._t; - var index = this._i; - var point; - if (index >= O.length) return { value: undefined, done: true }; - point = $at(O, index); - this._i += point.length; - return { value: point, done: false }; - }); - - -/***/ }), -/* 127 */ -/***/ (function(module, exports, __webpack_require__) { - - var toInteger = __webpack_require__(38); - var defined = __webpack_require__(35); - // true -> String#at - // false -> String#codePointAt - module.exports = function (TO_STRING) { - return function (that, pos) { - var s = String(defined(that)); - var i = toInteger(pos); - var l = s.length; - var a, b; - if (i < 0 || i >= l) return TO_STRING ? '' : undefined; - a = s.charCodeAt(i); - return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff - ? TO_STRING ? s.charAt(i) : a - : TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000; - }; - }; - - -/***/ }), -/* 128 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var LIBRARY = __webpack_require__(24); - var $export = __webpack_require__(8); - var redefine = __webpack_require__(18); - var hide = __webpack_require__(10); - var Iterators = __webpack_require__(129); - var $iterCreate = __webpack_require__(130); - var setToStringTag = __webpack_require__(25); - var getPrototypeOf = __webpack_require__(58); - var ITERATOR = __webpack_require__(26)('iterator'); - var BUGGY = !([].keys && 'next' in [].keys()); // Safari has buggy iterators w/o `next` - var FF_ITERATOR = '@@iterator'; - var KEYS = 'keys'; - var VALUES = 'values'; - - var returnThis = function () { return this; }; - - module.exports = function (Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED) { - $iterCreate(Constructor, NAME, next); - var getMethod = function (kind) { - if (!BUGGY && kind in proto) return proto[kind]; - switch (kind) { - case KEYS: return function keys() { return new Constructor(this, kind); }; - case VALUES: return function values() { return new Constructor(this, kind); }; - } return function entries() { return new Constructor(this, kind); }; - }; - var TAG = NAME + ' Iterator'; - var DEF_VALUES = DEFAULT == VALUES; - var VALUES_BUG = false; - var proto = Base.prototype; - var $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT]; - var $default = $native || getMethod(DEFAULT); - var $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined; - var $anyNative = NAME == 'Array' ? proto.entries || $native : $native; - var methods, key, IteratorPrototype; - // Fix native - if ($anyNative) { - IteratorPrototype = getPrototypeOf($anyNative.call(new Base())); - if (IteratorPrototype !== Object.prototype && IteratorPrototype.next) { - // Set @@toStringTag to native iterators - setToStringTag(IteratorPrototype, TAG, true); - // fix for some old engines - if (!LIBRARY && typeof IteratorPrototype[ITERATOR] != 'function') hide(IteratorPrototype, ITERATOR, returnThis); - } - } - // fix Array#{values, @@iterator}.name in V8 / FF - if (DEF_VALUES && $native && $native.name !== VALUES) { - VALUES_BUG = true; - $default = function values() { return $native.call(this); }; - } - // Define iterator - if ((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])) { - hide(proto, ITERATOR, $default); - } - // Plug for library - Iterators[NAME] = $default; - Iterators[TAG] = returnThis; - if (DEFAULT) { - methods = { - values: DEF_VALUES ? $default : getMethod(VALUES), - keys: IS_SET ? $default : getMethod(KEYS), - entries: $entries - }; - if (FORCED) for (key in methods) { - if (!(key in proto)) redefine(proto, key, methods[key]); - } else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods); - } - return methods; - }; - - -/***/ }), -/* 129 */ -/***/ (function(module, exports) { - - module.exports = {}; - - -/***/ }), -/* 130 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var create = __webpack_require__(45); - var descriptor = __webpack_require__(17); - var setToStringTag = __webpack_require__(25); - var IteratorPrototype = {}; - - // 25.1.2.1.1 %IteratorPrototype%[@@iterator]() - __webpack_require__(10)(IteratorPrototype, __webpack_require__(26)('iterator'), function () { return this; }); - - module.exports = function (Constructor, NAME, next) { - Constructor.prototype = create(IteratorPrototype, { next: descriptor(1, next) }); - setToStringTag(Constructor, NAME + ' Iterator'); - }; - - -/***/ }), -/* 131 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var $at = __webpack_require__(127)(false); - $export($export.P, 'String', { - // 21.1.3.3 String.prototype.codePointAt(pos) - codePointAt: function codePointAt(pos) { - return $at(this, pos); - } - }); - - -/***/ }), -/* 132 */ -/***/ (function(module, exports, __webpack_require__) { - - // 21.1.3.6 String.prototype.endsWith(searchString [, endPosition]) - 'use strict'; - var $export = __webpack_require__(8); - var toLength = __webpack_require__(37); - var context = __webpack_require__(133); - var ENDS_WITH = 'endsWith'; - var $endsWith = ''[ENDS_WITH]; - - $export($export.P + $export.F * __webpack_require__(135)(ENDS_WITH), 'String', { - endsWith: function endsWith(searchString /* , endPosition = @length */) { - var that = context(this, searchString, ENDS_WITH); - var endPosition = arguments.length > 1 ? arguments[1] : undefined; - var len = toLength(that.length); - var end = endPosition === undefined ? len : Math.min(toLength(endPosition), len); - var search = String(searchString); - return $endsWith - ? $endsWith.call(that, search, end) - : that.slice(end - search.length, end) === search; - } - }); - - -/***/ }), -/* 133 */ -/***/ (function(module, exports, __webpack_require__) { - - // helper for String#{startsWith, endsWith, includes} - var isRegExp = __webpack_require__(134); - var defined = __webpack_require__(35); - - module.exports = function (that, searchString, NAME) { - if (isRegExp(searchString)) throw TypeError('String#' + NAME + " doesn't accept regex!"); - return String(defined(that)); - }; - - -/***/ }), -/* 134 */ -/***/ (function(module, exports, __webpack_require__) { - - // 7.2.8 IsRegExp(argument) - var isObject = __webpack_require__(13); - var cof = __webpack_require__(34); - var MATCH = __webpack_require__(26)('match'); - module.exports = function (it) { - var isRegExp; - return isObject(it) && ((isRegExp = it[MATCH]) !== undefined ? !!isRegExp : cof(it) == 'RegExp'); - }; - - -/***/ }), -/* 135 */ -/***/ (function(module, exports, __webpack_require__) { - - var MATCH = __webpack_require__(26)('match'); - module.exports = function (KEY) { - var re = /./; - try { - '/./'[KEY](re); - } catch (e) { - try { - re[MATCH] = false; - return !'/./'[KEY](re); - } catch (f) { /* empty */ } - } return true; - }; - - -/***/ }), -/* 136 */ -/***/ (function(module, exports, __webpack_require__) { - - // 21.1.3.7 String.prototype.includes(searchString, position = 0) - 'use strict'; - var $export = __webpack_require__(8); - var context = __webpack_require__(133); - var INCLUDES = 'includes'; - - $export($export.P + $export.F * __webpack_require__(135)(INCLUDES), 'String', { - includes: function includes(searchString /* , position = 0 */) { - return !!~context(this, searchString, INCLUDES) - .indexOf(searchString, arguments.length > 1 ? arguments[1] : undefined); - } - }); - - -/***/ }), -/* 137 */ -/***/ (function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8); - - $export($export.P, 'String', { - // 21.1.3.13 String.prototype.repeat(count) - repeat: __webpack_require__(90) - }); - - -/***/ }), -/* 138 */ -/***/ (function(module, exports, __webpack_require__) { - - // 21.1.3.18 String.prototype.startsWith(searchString [, position ]) - 'use strict'; - var $export = __webpack_require__(8); - var toLength = __webpack_require__(37); - var context = __webpack_require__(133); - var STARTS_WITH = 'startsWith'; - var $startsWith = ''[STARTS_WITH]; - - $export($export.P + $export.F * __webpack_require__(135)(STARTS_WITH), 'String', { - startsWith: function startsWith(searchString /* , position = 0 */) { - var that = context(this, searchString, STARTS_WITH); - var index = toLength(Math.min(arguments.length > 1 ? arguments[1] : undefined, that.length)); - var search = String(searchString); - return $startsWith - ? $startsWith.call(that, search, index) - : that.slice(index, index + search.length) === search; - } - }); - - -/***/ }), -/* 139 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.2 String.prototype.anchor(name) - __webpack_require__(140)('anchor', function (createHTML) { - return function anchor(name) { - return createHTML(this, 'a', 'name', name); - }; - }); - - -/***/ }), -/* 140 */ -/***/ (function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8); - var fails = __webpack_require__(7); - var defined = __webpack_require__(35); - var quot = /"/g; - // B.2.3.2.1 CreateHTML(string, tag, attribute, value) - var createHTML = function (string, tag, attribute, value) { - var S = String(defined(string)); - var p1 = '<' + tag; - if (attribute !== '') p1 += ' ' + attribute + '="' + String(value).replace(quot, '"') + '"'; - return p1 + '>' + S + ''; - }; - module.exports = function (NAME, exec) { - var O = {}; - O[NAME] = exec(createHTML); - $export($export.P + $export.F * fails(function () { - var test = ''[NAME]('"'); - return test !== test.toLowerCase() || test.split('"').length > 3; - }), 'String', O); - }; - - -/***/ }), -/* 141 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.3 String.prototype.big() - __webpack_require__(140)('big', function (createHTML) { - return function big() { - return createHTML(this, 'big', '', ''); - }; - }); - - -/***/ }), -/* 142 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.4 String.prototype.blink() - __webpack_require__(140)('blink', function (createHTML) { - return function blink() { - return createHTML(this, 'blink', '', ''); - }; - }); - - -/***/ }), -/* 143 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.5 String.prototype.bold() - __webpack_require__(140)('bold', function (createHTML) { - return function bold() { - return createHTML(this, 'b', '', ''); - }; - }); - - -/***/ }), -/* 144 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.6 String.prototype.fixed() - __webpack_require__(140)('fixed', function (createHTML) { - return function fixed() { - return createHTML(this, 'tt', '', ''); - }; - }); - - -/***/ }), -/* 145 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.7 String.prototype.fontcolor(color) - __webpack_require__(140)('fontcolor', function (createHTML) { - return function fontcolor(color) { - return createHTML(this, 'font', 'color', color); - }; - }); - - -/***/ }), -/* 146 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.8 String.prototype.fontsize(size) - __webpack_require__(140)('fontsize', function (createHTML) { - return function fontsize(size) { - return createHTML(this, 'font', 'size', size); - }; - }); - - -/***/ }), -/* 147 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.9 String.prototype.italics() - __webpack_require__(140)('italics', function (createHTML) { - return function italics() { - return createHTML(this, 'i', '', ''); - }; - }); - - -/***/ }), -/* 148 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.10 String.prototype.link(url) - __webpack_require__(140)('link', function (createHTML) { - return function link(url) { - return createHTML(this, 'a', 'href', url); - }; - }); - - -/***/ }), -/* 149 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.11 String.prototype.small() - __webpack_require__(140)('small', function (createHTML) { - return function small() { - return createHTML(this, 'small', '', ''); - }; - }); - - -/***/ }), -/* 150 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.12 String.prototype.strike() - __webpack_require__(140)('strike', function (createHTML) { - return function strike() { - return createHTML(this, 'strike', '', ''); - }; - }); - - -/***/ }), -/* 151 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.13 String.prototype.sub() - __webpack_require__(140)('sub', function (createHTML) { - return function sub() { - return createHTML(this, 'sub', '', ''); - }; - }); - - -/***/ }), -/* 152 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // B.2.3.14 String.prototype.sup() - __webpack_require__(140)('sup', function (createHTML) { - return function sup() { - return createHTML(this, 'sup', '', ''); - }; - }); - - -/***/ }), -/* 153 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.3.3.1 / 15.9.4.4 Date.now() - var $export = __webpack_require__(8); - - $export($export.S, 'Date', { now: function () { return new Date().getTime(); } }); - - -/***/ }), -/* 154 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var toObject = __webpack_require__(57); - var toPrimitive = __webpack_require__(16); - - $export($export.P + $export.F * __webpack_require__(7)(function () { - return new Date(NaN).toJSON() !== null - || Date.prototype.toJSON.call({ toISOString: function () { return 1; } }) !== 1; - }), 'Date', { - // eslint-disable-next-line no-unused-vars - toJSON: function toJSON(key) { - var O = toObject(this); - var pv = toPrimitive(O); - return typeof pv == 'number' && !isFinite(pv) ? null : O.toISOString(); - } - }); - - -/***/ }), -/* 155 */ -/***/ (function(module, exports, __webpack_require__) { - - // 20.3.4.36 / 15.9.5.43 Date.prototype.toISOString() - var $export = __webpack_require__(8); - var toISOString = __webpack_require__(156); - - // PhantomJS / old WebKit has a broken implementations - $export($export.P + $export.F * (Date.prototype.toISOString !== toISOString), 'Date', { - toISOString: toISOString - }); - - -/***/ }), -/* 156 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // 20.3.4.36 / 15.9.5.43 Date.prototype.toISOString() - var fails = __webpack_require__(7); - var getTime = Date.prototype.getTime; - var $toISOString = Date.prototype.toISOString; - - var lz = function (num) { - return num > 9 ? num : '0' + num; - }; - - // PhantomJS / old WebKit has a broken implementations - module.exports = (fails(function () { - return $toISOString.call(new Date(-5e13 - 1)) != '0385-07-25T07:06:39.999Z'; - }) || !fails(function () { - $toISOString.call(new Date(NaN)); - })) ? function toISOString() { - if (!isFinite(getTime.call(this))) throw RangeError('Invalid time value'); - var d = this; - var y = d.getUTCFullYear(); - var m = d.getUTCMilliseconds(); - var s = y < 0 ? '-' : y > 9999 ? '+' : ''; - return s + ('00000' + Math.abs(y)).slice(s ? -6 : -4) + - '-' + lz(d.getUTCMonth() + 1) + '-' + lz(d.getUTCDate()) + - 'T' + lz(d.getUTCHours()) + ':' + lz(d.getUTCMinutes()) + - ':' + lz(d.getUTCSeconds()) + '.' + (m > 99 ? m : '0' + lz(m)) + 'Z'; - } : $toISOString; - - -/***/ }), -/* 157 */ -/***/ (function(module, exports, __webpack_require__) { - - var DateProto = Date.prototype; - var INVALID_DATE = 'Invalid Date'; - var TO_STRING = 'toString'; - var $toString = DateProto[TO_STRING]; - var getTime = DateProto.getTime; - if (new Date(NaN) + '' != INVALID_DATE) { - __webpack_require__(18)(DateProto, TO_STRING, function toString() { - var value = getTime.call(this); - // eslint-disable-next-line no-self-compare - return value === value ? $toString.call(this) : INVALID_DATE; - }); - } - - -/***/ }), -/* 158 */ -/***/ (function(module, exports, __webpack_require__) { - - var TO_PRIMITIVE = __webpack_require__(26)('toPrimitive'); - var proto = Date.prototype; - - if (!(TO_PRIMITIVE in proto)) __webpack_require__(10)(proto, TO_PRIMITIVE, __webpack_require__(159)); - - -/***/ }), -/* 159 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var anObject = __webpack_require__(12); - var toPrimitive = __webpack_require__(16); - var NUMBER = 'number'; - - module.exports = function (hint) { - if (hint !== 'string' && hint !== NUMBER && hint !== 'default') throw TypeError('Incorrect hint'); - return toPrimitive(anObject(this), hint != NUMBER); - }; - - -/***/ }), -/* 160 */ -/***/ (function(module, exports, __webpack_require__) { - - // 22.1.2.2 / 15.4.3.2 Array.isArray(arg) - var $export = __webpack_require__(8); - - $export($export.S, 'Array', { isArray: __webpack_require__(44) }); - - -/***/ }), -/* 161 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var ctx = __webpack_require__(20); - var $export = __webpack_require__(8); - var toObject = __webpack_require__(57); - var call = __webpack_require__(162); - var isArrayIter = __webpack_require__(163); - var toLength = __webpack_require__(37); - var createProperty = __webpack_require__(164); - var getIterFn = __webpack_require__(165); - - $export($export.S + $export.F * !__webpack_require__(166)(function (iter) { Array.from(iter); }), 'Array', { - // 22.1.2.1 Array.from(arrayLike, mapfn = undefined, thisArg = undefined) - from: function from(arrayLike /* , mapfn = undefined, thisArg = undefined */) { - var O = toObject(arrayLike); - var C = typeof this == 'function' ? this : Array; - var aLen = arguments.length; - var mapfn = aLen > 1 ? arguments[1] : undefined; - var mapping = mapfn !== undefined; - var index = 0; - var iterFn = getIterFn(O); - var length, result, step, iterator; - if (mapping) mapfn = ctx(mapfn, aLen > 2 ? arguments[2] : undefined, 2); - // if object isn't iterable or it's array with default iterator - use simple case - if (iterFn != undefined && !(C == Array && isArrayIter(iterFn))) { - for (iterator = iterFn.call(O), result = new C(); !(step = iterator.next()).done; index++) { - createProperty(result, index, mapping ? call(iterator, mapfn, [step.value, index], true) : step.value); - } - } else { - length = toLength(O.length); - for (result = new C(length); length > index; index++) { - createProperty(result, index, mapping ? mapfn(O[index], index) : O[index]); - } - } - result.length = index; - return result; - } - }); - - -/***/ }), -/* 162 */ -/***/ (function(module, exports, __webpack_require__) { - - // call something on iterator step with safe closing on error - var anObject = __webpack_require__(12); - module.exports = function (iterator, fn, value, entries) { - try { - return entries ? fn(anObject(value)[0], value[1]) : fn(value); - // 7.4.6 IteratorClose(iterator, completion) - } catch (e) { - var ret = iterator['return']; - if (ret !== undefined) anObject(ret.call(iterator)); - throw e; - } - }; - - -/***/ }), -/* 163 */ -/***/ (function(module, exports, __webpack_require__) { - - // check on default Array iterator - var Iterators = __webpack_require__(129); - var ITERATOR = __webpack_require__(26)('iterator'); - var ArrayProto = Array.prototype; - - module.exports = function (it) { - return it !== undefined && (Iterators.Array === it || ArrayProto[ITERATOR] === it); - }; - - -/***/ }), -/* 164 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $defineProperty = __webpack_require__(11); - var createDesc = __webpack_require__(17); - - module.exports = function (object, index, value) { - if (index in object) $defineProperty.f(object, index, createDesc(0, value)); - else object[index] = value; - }; - - -/***/ }), -/* 165 */ -/***/ (function(module, exports, __webpack_require__) { - - var classof = __webpack_require__(74); - var ITERATOR = __webpack_require__(26)('iterator'); - var Iterators = __webpack_require__(129); - module.exports = __webpack_require__(9).getIteratorMethod = function (it) { - if (it != undefined) return it[ITERATOR] - || it['@@iterator'] - || Iterators[classof(it)]; - }; - - -/***/ }), -/* 166 */ -/***/ (function(module, exports, __webpack_require__) { - - var ITERATOR = __webpack_require__(26)('iterator'); - var SAFE_CLOSING = false; - - try { - var riter = [7][ITERATOR](); - riter['return'] = function () { SAFE_CLOSING = true; }; - // eslint-disable-next-line no-throw-literal - Array.from(riter, function () { throw 2; }); - } catch (e) { /* empty */ } - - module.exports = function (exec, skipClosing) { - if (!skipClosing && !SAFE_CLOSING) return false; - var safe = false; - try { - var arr = [7]; - var iter = arr[ITERATOR](); - iter.next = function () { return { done: safe = true }; }; - arr[ITERATOR] = function () { return iter; }; - exec(arr); - } catch (e) { /* empty */ } - return safe; - }; - - -/***/ }), -/* 167 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var createProperty = __webpack_require__(164); - - // WebKit Array.of isn't generic - $export($export.S + $export.F * __webpack_require__(7)(function () { - function F() { /* empty */ } - return !(Array.of.call(F) instanceof F); - }), 'Array', { - // 22.1.2.3 Array.of( ...items) - of: function of(/* ...args */) { - var index = 0; - var aLen = arguments.length; - var result = new (typeof this == 'function' ? this : Array)(aLen); - while (aLen > index) createProperty(result, index, arguments[index++]); - result.length = aLen; - return result; - } - }); - - -/***/ }), -/* 168 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // 22.1.3.13 Array.prototype.join(separator) - var $export = __webpack_require__(8); - var toIObject = __webpack_require__(32); - var arrayJoin = [].join; - - // fallback for not array-like strings - $export($export.P + $export.F * (__webpack_require__(33) != Object || !__webpack_require__(169)(arrayJoin)), 'Array', { - join: function join(separator) { - return arrayJoin.call(toIObject(this), separator === undefined ? ',' : separator); - } - }); - - -/***/ }), -/* 169 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var fails = __webpack_require__(7); - - module.exports = function (method, arg) { - return !!method && fails(function () { - // eslint-disable-next-line no-useless-call - arg ? method.call(null, function () { /* empty */ }, 1) : method.call(null); - }); - }; - - -/***/ }), -/* 170 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var html = __webpack_require__(47); - var cof = __webpack_require__(34); - var toAbsoluteIndex = __webpack_require__(39); - var toLength = __webpack_require__(37); - var arraySlice = [].slice; - - // fallback for not array-like ES3 strings and DOM objects - $export($export.P + $export.F * __webpack_require__(7)(function () { - if (html) arraySlice.call(html); - }), 'Array', { - slice: function slice(begin, end) { - var len = toLength(this.length); - var klass = cof(this); - end = end === undefined ? len : end; - if (klass == 'Array') return arraySlice.call(this, begin, end); - var start = toAbsoluteIndex(begin, len); - var upTo = toAbsoluteIndex(end, len); - var size = toLength(upTo - start); - var cloned = new Array(size); - var i = 0; - for (; i < size; i++) cloned[i] = klass == 'String' - ? this.charAt(start + i) - : this[start + i]; - return cloned; - } - }); - - -/***/ }), -/* 171 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var aFunction = __webpack_require__(21); - var toObject = __webpack_require__(57); - var fails = __webpack_require__(7); - var $sort = [].sort; - var test = [1, 2, 3]; - - $export($export.P + $export.F * (fails(function () { - // IE8- - test.sort(undefined); - }) || !fails(function () { - // V8 bug - test.sort(null); - // Old WebKit - }) || !__webpack_require__(169)($sort)), 'Array', { - // 22.1.3.25 Array.prototype.sort(comparefn) - sort: function sort(comparefn) { - return comparefn === undefined - ? $sort.call(toObject(this)) - : $sort.call(toObject(this), aFunction(comparefn)); - } - }); - - -/***/ }), -/* 172 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var $forEach = __webpack_require__(173)(0); - var STRICT = __webpack_require__(169)([].forEach, true); - - $export($export.P + $export.F * !STRICT, 'Array', { - // 22.1.3.10 / 15.4.4.18 Array.prototype.forEach(callbackfn [, thisArg]) - forEach: function forEach(callbackfn /* , thisArg */) { - return $forEach(this, callbackfn, arguments[1]); - } - }); - - -/***/ }), -/* 173 */ -/***/ (function(module, exports, __webpack_require__) { - - // 0 -> Array#forEach - // 1 -> Array#map - // 2 -> Array#filter - // 3 -> Array#some - // 4 -> Array#every - // 5 -> Array#find - // 6 -> Array#findIndex - var ctx = __webpack_require__(20); - var IObject = __webpack_require__(33); - var toObject = __webpack_require__(57); - var toLength = __webpack_require__(37); - var asc = __webpack_require__(174); - module.exports = function (TYPE, $create) { - var IS_MAP = TYPE == 1; - var IS_FILTER = TYPE == 2; - var IS_SOME = TYPE == 3; - var IS_EVERY = TYPE == 4; - var IS_FIND_INDEX = TYPE == 6; - var NO_HOLES = TYPE == 5 || IS_FIND_INDEX; - var create = $create || asc; - return function ($this, callbackfn, that) { - var O = toObject($this); - var self = IObject(O); - var f = ctx(callbackfn, that, 3); - var length = toLength(self.length); - var index = 0; - var result = IS_MAP ? create($this, length) : IS_FILTER ? create($this, 0) : undefined; - var val, res; - for (;length > index; index++) if (NO_HOLES || index in self) { - val = self[index]; - res = f(val, index, O); - if (TYPE) { - if (IS_MAP) result[index] = res; // map - else if (res) switch (TYPE) { - case 3: return true; // some - case 5: return val; // find - case 6: return index; // findIndex - case 2: result.push(val); // filter - } else if (IS_EVERY) return false; // every - } - } - return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : result; - }; - }; - - -/***/ }), -/* 174 */ -/***/ (function(module, exports, __webpack_require__) { - - // 9.4.2.3 ArraySpeciesCreate(originalArray, length) - var speciesConstructor = __webpack_require__(175); - - module.exports = function (original, length) { - return new (speciesConstructor(original))(length); - }; - - -/***/ }), -/* 175 */ -/***/ (function(module, exports, __webpack_require__) { - - var isObject = __webpack_require__(13); - var isArray = __webpack_require__(44); - var SPECIES = __webpack_require__(26)('species'); - - module.exports = function (original) { - var C; - if (isArray(original)) { - C = original.constructor; - // cross-realm fallback - if (typeof C == 'function' && (C === Array || isArray(C.prototype))) C = undefined; - if (isObject(C)) { - C = C[SPECIES]; - if (C === null) C = undefined; - } - } return C === undefined ? Array : C; - }; - - -/***/ }), -/* 176 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var $map = __webpack_require__(173)(1); - - $export($export.P + $export.F * !__webpack_require__(169)([].map, true), 'Array', { - // 22.1.3.15 / 15.4.4.19 Array.prototype.map(callbackfn [, thisArg]) - map: function map(callbackfn /* , thisArg */) { - return $map(this, callbackfn, arguments[1]); - } - }); - - -/***/ }), -/* 177 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var $filter = __webpack_require__(173)(2); - - $export($export.P + $export.F * !__webpack_require__(169)([].filter, true), 'Array', { - // 22.1.3.7 / 15.4.4.20 Array.prototype.filter(callbackfn [, thisArg]) - filter: function filter(callbackfn /* , thisArg */) { - return $filter(this, callbackfn, arguments[1]); - } - }); - - -/***/ }), -/* 178 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var $some = __webpack_require__(173)(3); - - $export($export.P + $export.F * !__webpack_require__(169)([].some, true), 'Array', { - // 22.1.3.23 / 15.4.4.17 Array.prototype.some(callbackfn [, thisArg]) - some: function some(callbackfn /* , thisArg */) { - return $some(this, callbackfn, arguments[1]); - } - }); - - -/***/ }), -/* 179 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var $every = __webpack_require__(173)(4); - - $export($export.P + $export.F * !__webpack_require__(169)([].every, true), 'Array', { - // 22.1.3.5 / 15.4.4.16 Array.prototype.every(callbackfn [, thisArg]) - every: function every(callbackfn /* , thisArg */) { - return $every(this, callbackfn, arguments[1]); - } - }); - - -/***/ }), -/* 180 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var $reduce = __webpack_require__(181); - - $export($export.P + $export.F * !__webpack_require__(169)([].reduce, true), 'Array', { - // 22.1.3.18 / 15.4.4.21 Array.prototype.reduce(callbackfn [, initialValue]) - reduce: function reduce(callbackfn /* , initialValue */) { - return $reduce(this, callbackfn, arguments.length, arguments[1], false); - } - }); - - -/***/ }), -/* 181 */ -/***/ (function(module, exports, __webpack_require__) { - - var aFunction = __webpack_require__(21); - var toObject = __webpack_require__(57); - var IObject = __webpack_require__(33); - var toLength = __webpack_require__(37); - - module.exports = function (that, callbackfn, aLen, memo, isRight) { - aFunction(callbackfn); - var O = toObject(that); - var self = IObject(O); - var length = toLength(O.length); - var index = isRight ? length - 1 : 0; - var i = isRight ? -1 : 1; - if (aLen < 2) for (;;) { - if (index in self) { - memo = self[index]; - index += i; - break; - } - index += i; - if (isRight ? index < 0 : length <= index) { - throw TypeError('Reduce of empty array with no initial value'); - } - } - for (;isRight ? index >= 0 : length > index; index += i) if (index in self) { - memo = callbackfn(memo, self[index], index, O); - } - return memo; - }; - - -/***/ }), -/* 182 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var $reduce = __webpack_require__(181); - - $export($export.P + $export.F * !__webpack_require__(169)([].reduceRight, true), 'Array', { - // 22.1.3.19 / 15.4.4.22 Array.prototype.reduceRight(callbackfn [, initialValue]) - reduceRight: function reduceRight(callbackfn /* , initialValue */) { - return $reduce(this, callbackfn, arguments.length, arguments[1], true); - } - }); - - -/***/ }), -/* 183 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var $indexOf = __webpack_require__(36)(false); - var $native = [].indexOf; - var NEGATIVE_ZERO = !!$native && 1 / [1].indexOf(1, -0) < 0; - - $export($export.P + $export.F * (NEGATIVE_ZERO || !__webpack_require__(169)($native)), 'Array', { - // 22.1.3.11 / 15.4.4.14 Array.prototype.indexOf(searchElement [, fromIndex]) - indexOf: function indexOf(searchElement /* , fromIndex = 0 */) { - return NEGATIVE_ZERO - // convert -0 to +0 - ? $native.apply(this, arguments) || 0 - : $indexOf(this, searchElement, arguments[1]); - } - }); - - -/***/ }), -/* 184 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var toIObject = __webpack_require__(32); - var toInteger = __webpack_require__(38); - var toLength = __webpack_require__(37); - var $native = [].lastIndexOf; - var NEGATIVE_ZERO = !!$native && 1 / [1].lastIndexOf(1, -0) < 0; - - $export($export.P + $export.F * (NEGATIVE_ZERO || !__webpack_require__(169)($native)), 'Array', { - // 22.1.3.14 / 15.4.4.15 Array.prototype.lastIndexOf(searchElement [, fromIndex]) - lastIndexOf: function lastIndexOf(searchElement /* , fromIndex = @[*-1] */) { - // convert -0 to +0 - if (NEGATIVE_ZERO) return $native.apply(this, arguments) || 0; - var O = toIObject(this); - var length = toLength(O.length); - var index = length - 1; - if (arguments.length > 1) index = Math.min(index, toInteger(arguments[1])); - if (index < 0) index = length + index; - for (;index >= 0; index--) if (index in O) if (O[index] === searchElement) return index || 0; - return -1; - } - }); - - -/***/ }), -/* 185 */ -/***/ (function(module, exports, __webpack_require__) { - - // 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length) - var $export = __webpack_require__(8); - - $export($export.P, 'Array', { copyWithin: __webpack_require__(186) }); - - __webpack_require__(187)('copyWithin'); - - -/***/ }), -/* 186 */ -/***/ (function(module, exports, __webpack_require__) { - - // 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length) - 'use strict'; - var toObject = __webpack_require__(57); - var toAbsoluteIndex = __webpack_require__(39); - var toLength = __webpack_require__(37); - - module.exports = [].copyWithin || function copyWithin(target /* = 0 */, start /* = 0, end = @length */) { - var O = toObject(this); - var len = toLength(O.length); - var to = toAbsoluteIndex(target, len); - var from = toAbsoluteIndex(start, len); - var end = arguments.length > 2 ? arguments[2] : undefined; - var count = Math.min((end === undefined ? len : toAbsoluteIndex(end, len)) - from, len - to); - var inc = 1; - if (from < to && to < from + count) { - inc = -1; - from += count - 1; - to += count - 1; - } - while (count-- > 0) { - if (from in O) O[to] = O[from]; - else delete O[to]; - to += inc; - from += inc; - } return O; - }; - - -/***/ }), -/* 187 */ -/***/ (function(module, exports, __webpack_require__) { - - // 22.1.3.31 Array.prototype[@@unscopables] - var UNSCOPABLES = __webpack_require__(26)('unscopables'); - var ArrayProto = Array.prototype; - if (ArrayProto[UNSCOPABLES] == undefined) __webpack_require__(10)(ArrayProto, UNSCOPABLES, {}); - module.exports = function (key) { - ArrayProto[UNSCOPABLES][key] = true; - }; - - -/***/ }), -/* 188 */ -/***/ (function(module, exports, __webpack_require__) { - - // 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length) - var $export = __webpack_require__(8); - - $export($export.P, 'Array', { fill: __webpack_require__(189) }); - - __webpack_require__(187)('fill'); - - -/***/ }), -/* 189 */ -/***/ (function(module, exports, __webpack_require__) { - - // 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length) - 'use strict'; - var toObject = __webpack_require__(57); - var toAbsoluteIndex = __webpack_require__(39); - var toLength = __webpack_require__(37); - module.exports = function fill(value /* , start = 0, end = @length */) { - var O = toObject(this); - var length = toLength(O.length); - var aLen = arguments.length; - var index = toAbsoluteIndex(aLen > 1 ? arguments[1] : undefined, length); - var end = aLen > 2 ? arguments[2] : undefined; - var endPos = end === undefined ? length : toAbsoluteIndex(end, length); - while (endPos > index) O[index++] = value; - return O; - }; - - -/***/ }), -/* 190 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // 22.1.3.8 Array.prototype.find(predicate, thisArg = undefined) - var $export = __webpack_require__(8); - var $find = __webpack_require__(173)(5); - var KEY = 'find'; - var forced = true; - // Shouldn't skip holes - if (KEY in []) Array(1)[KEY](function () { forced = false; }); - $export($export.P + $export.F * forced, 'Array', { - find: function find(callbackfn /* , that = undefined */) { - return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); - } - }); - __webpack_require__(187)(KEY); - - -/***/ }), -/* 191 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // 22.1.3.9 Array.prototype.findIndex(predicate, thisArg = undefined) - var $export = __webpack_require__(8); - var $find = __webpack_require__(173)(6); - var KEY = 'findIndex'; - var forced = true; - // Shouldn't skip holes - if (KEY in []) Array(1)[KEY](function () { forced = false; }); - $export($export.P + $export.F * forced, 'Array', { - findIndex: function findIndex(callbackfn /* , that = undefined */) { - return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); - } - }); - __webpack_require__(187)(KEY); - - -/***/ }), -/* 192 */ -/***/ (function(module, exports, __webpack_require__) { - - __webpack_require__(193)('Array'); - - -/***/ }), -/* 193 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var global = __webpack_require__(4); - var dP = __webpack_require__(11); - var DESCRIPTORS = __webpack_require__(6); - var SPECIES = __webpack_require__(26)('species'); - - module.exports = function (KEY) { - var C = global[KEY]; - if (DESCRIPTORS && C && !C[SPECIES]) dP.f(C, SPECIES, { - configurable: true, - get: function () { return this; } - }); - }; - - -/***/ }), -/* 194 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var addToUnscopables = __webpack_require__(187); - var step = __webpack_require__(195); - var Iterators = __webpack_require__(129); - var toIObject = __webpack_require__(32); - - // 22.1.3.4 Array.prototype.entries() - // 22.1.3.13 Array.prototype.keys() - // 22.1.3.29 Array.prototype.values() - // 22.1.3.30 Array.prototype[@@iterator]() - module.exports = __webpack_require__(128)(Array, 'Array', function (iterated, kind) { - this._t = toIObject(iterated); // target - this._i = 0; // next index - this._k = kind; // kind - // 22.1.5.2.1 %ArrayIteratorPrototype%.next() - }, function () { - var O = this._t; - var kind = this._k; - var index = this._i++; - if (!O || index >= O.length) { - this._t = undefined; - return step(1); - } - if (kind == 'keys') return step(0, index); - if (kind == 'values') return step(0, O[index]); - return step(0, [index, O[index]]); - }, 'values'); - - // argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7) - Iterators.Arguments = Iterators.Array; - - addToUnscopables('keys'); - addToUnscopables('values'); - addToUnscopables('entries'); - - -/***/ }), -/* 195 */ -/***/ (function(module, exports) { - - module.exports = function (done, value) { - return { value: value, done: !!done }; - }; - - -/***/ }), -/* 196 */ -/***/ (function(module, exports, __webpack_require__) { - - var global = __webpack_require__(4); - var inheritIfRequired = __webpack_require__(87); - var dP = __webpack_require__(11).f; - var gOPN = __webpack_require__(49).f; - var isRegExp = __webpack_require__(134); - var $flags = __webpack_require__(197); - var $RegExp = global.RegExp; - var Base = $RegExp; - var proto = $RegExp.prototype; - var re1 = /a/g; - var re2 = /a/g; - // "new" creates a new object, old webkit buggy here - var CORRECT_NEW = new $RegExp(re1) !== re1; - - if (__webpack_require__(6) && (!CORRECT_NEW || __webpack_require__(7)(function () { - re2[__webpack_require__(26)('match')] = false; - // RegExp constructor can alter flags and IsRegExp works correct with @@match - return $RegExp(re1) != re1 || $RegExp(re2) == re2 || $RegExp(re1, 'i') != '/a/i'; - }))) { - $RegExp = function RegExp(p, f) { - var tiRE = this instanceof $RegExp; - var piRE = isRegExp(p); - var fiU = f === undefined; - return !tiRE && piRE && p.constructor === $RegExp && fiU ? p - : inheritIfRequired(CORRECT_NEW - ? new Base(piRE && !fiU ? p.source : p, f) - : Base((piRE = p instanceof $RegExp) ? p.source : p, piRE && fiU ? $flags.call(p) : f) - , tiRE ? this : proto, $RegExp); - }; - var proxy = function (key) { - key in $RegExp || dP($RegExp, key, { - configurable: true, - get: function () { return Base[key]; }, - set: function (it) { Base[key] = it; } - }); - }; - for (var keys = gOPN(Base), i = 0; keys.length > i;) proxy(keys[i++]); - proto.constructor = $RegExp; - $RegExp.prototype = proto; - __webpack_require__(18)(global, 'RegExp', $RegExp); - } - - __webpack_require__(193)('RegExp'); - - -/***/ }), -/* 197 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // 21.2.5.3 get RegExp.prototype.flags - var anObject = __webpack_require__(12); - module.exports = function () { - var that = anObject(this); - var result = ''; - if (that.global) result += 'g'; - if (that.ignoreCase) result += 'i'; - if (that.multiline) result += 'm'; - if (that.unicode) result += 'u'; - if (that.sticky) result += 'y'; - return result; - }; - - -/***/ }), -/* 198 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - __webpack_require__(199); - var anObject = __webpack_require__(12); - var $flags = __webpack_require__(197); - var DESCRIPTORS = __webpack_require__(6); - var TO_STRING = 'toString'; - var $toString = /./[TO_STRING]; - - var define = function (fn) { - __webpack_require__(18)(RegExp.prototype, TO_STRING, fn, true); - }; - - // 21.2.5.14 RegExp.prototype.toString() - if (__webpack_require__(7)(function () { return $toString.call({ source: 'a', flags: 'b' }) != '/a/b'; })) { - define(function toString() { - var R = anObject(this); - return '/'.concat(R.source, '/', - 'flags' in R ? R.flags : !DESCRIPTORS && R instanceof RegExp ? $flags.call(R) : undefined); - }); - // FF44- RegExp#toString has a wrong name - } else if ($toString.name != TO_STRING) { - define(function toString() { - return $toString.call(this); - }); - } - - -/***/ }), -/* 199 */ -/***/ (function(module, exports, __webpack_require__) { - - // 21.2.5.3 get RegExp.prototype.flags() - if (__webpack_require__(6) && /./g.flags != 'g') __webpack_require__(11).f(RegExp.prototype, 'flags', { - configurable: true, - get: __webpack_require__(197) - }); - - -/***/ }), -/* 200 */ -/***/ (function(module, exports, __webpack_require__) { - - // @@match logic - __webpack_require__(201)('match', 1, function (defined, MATCH, $match) { - // 21.1.3.11 String.prototype.match(regexp) - return [function match(regexp) { - 'use strict'; - var O = defined(this); - var fn = regexp == undefined ? undefined : regexp[MATCH]; - return fn !== undefined ? fn.call(regexp, O) : new RegExp(regexp)[MATCH](String(O)); - }, $match]; - }); - - -/***/ }), -/* 201 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var hide = __webpack_require__(10); - var redefine = __webpack_require__(18); - var fails = __webpack_require__(7); - var defined = __webpack_require__(35); - var wks = __webpack_require__(26); - - module.exports = function (KEY, length, exec) { - var SYMBOL = wks(KEY); - var fns = exec(defined, SYMBOL, ''[KEY]); - var strfn = fns[0]; - var rxfn = fns[1]; - if (fails(function () { - var O = {}; - O[SYMBOL] = function () { return 7; }; - return ''[KEY](O) != 7; - })) { - redefine(String.prototype, KEY, strfn); - hide(RegExp.prototype, SYMBOL, length == 2 - // 21.2.5.8 RegExp.prototype[@@replace](string, replaceValue) - // 21.2.5.11 RegExp.prototype[@@split](string, limit) - ? function (string, arg) { return rxfn.call(string, this, arg); } - // 21.2.5.6 RegExp.prototype[@@match](string) - // 21.2.5.9 RegExp.prototype[@@search](string) - : function (string) { return rxfn.call(string, this); } - ); - } - }; - - -/***/ }), -/* 202 */ -/***/ (function(module, exports, __webpack_require__) { - - // @@replace logic - __webpack_require__(201)('replace', 2, function (defined, REPLACE, $replace) { - // 21.1.3.14 String.prototype.replace(searchValue, replaceValue) - return [function replace(searchValue, replaceValue) { - 'use strict'; - var O = defined(this); - var fn = searchValue == undefined ? undefined : searchValue[REPLACE]; - return fn !== undefined - ? fn.call(searchValue, O, replaceValue) - : $replace.call(String(O), searchValue, replaceValue); - }, $replace]; - }); - - -/***/ }), -/* 203 */ -/***/ (function(module, exports, __webpack_require__) { - - // @@search logic - __webpack_require__(201)('search', 1, function (defined, SEARCH, $search) { - // 21.1.3.15 String.prototype.search(regexp) - return [function search(regexp) { - 'use strict'; - var O = defined(this); - var fn = regexp == undefined ? undefined : regexp[SEARCH]; - return fn !== undefined ? fn.call(regexp, O) : new RegExp(regexp)[SEARCH](String(O)); - }, $search]; - }); - - -/***/ }), -/* 204 */ -/***/ (function(module, exports, __webpack_require__) { - - // @@split logic - __webpack_require__(201)('split', 2, function (defined, SPLIT, $split) { - 'use strict'; - var isRegExp = __webpack_require__(134); - var _split = $split; - var $push = [].push; - var $SPLIT = 'split'; - var LENGTH = 'length'; - var LAST_INDEX = 'lastIndex'; - if ( - 'abbc'[$SPLIT](/(b)*/)[1] == 'c' || - 'test'[$SPLIT](/(?:)/, -1)[LENGTH] != 4 || - 'ab'[$SPLIT](/(?:ab)*/)[LENGTH] != 2 || - '.'[$SPLIT](/(.?)(.?)/)[LENGTH] != 4 || - '.'[$SPLIT](/()()/)[LENGTH] > 1 || - ''[$SPLIT](/.?/)[LENGTH] - ) { - var NPCG = /()??/.exec('')[1] === undefined; // nonparticipating capturing group - // based on es5-shim implementation, need to rework it - $split = function (separator, limit) { - var string = String(this); - if (separator === undefined && limit === 0) return []; - // If `separator` is not a regex, use native split - if (!isRegExp(separator)) return _split.call(string, separator, limit); - var output = []; - var flags = (separator.ignoreCase ? 'i' : '') + - (separator.multiline ? 'm' : '') + - (separator.unicode ? 'u' : '') + - (separator.sticky ? 'y' : ''); - var lastLastIndex = 0; - var splitLimit = limit === undefined ? 4294967295 : limit >>> 0; - // Make `global` and avoid `lastIndex` issues by working with a copy - var separatorCopy = new RegExp(separator.source, flags + 'g'); - var separator2, match, lastIndex, lastLength, i; - // Doesn't need flags gy, but they don't hurt - if (!NPCG) separator2 = new RegExp('^' + separatorCopy.source + '$(?!\\s)', flags); - while (match = separatorCopy.exec(string)) { - // `separatorCopy.lastIndex` is not reliable cross-browser - lastIndex = match.index + match[0][LENGTH]; - if (lastIndex > lastLastIndex) { - output.push(string.slice(lastLastIndex, match.index)); - // Fix browsers whose `exec` methods don't consistently return `undefined` for NPCG - // eslint-disable-next-line no-loop-func - if (!NPCG && match[LENGTH] > 1) match[0].replace(separator2, function () { - for (i = 1; i < arguments[LENGTH] - 2; i++) if (arguments[i] === undefined) match[i] = undefined; - }); - if (match[LENGTH] > 1 && match.index < string[LENGTH]) $push.apply(output, match.slice(1)); - lastLength = match[0][LENGTH]; - lastLastIndex = lastIndex; - if (output[LENGTH] >= splitLimit) break; - } - if (separatorCopy[LAST_INDEX] === match.index) separatorCopy[LAST_INDEX]++; // Avoid an infinite loop - } - if (lastLastIndex === string[LENGTH]) { - if (lastLength || !separatorCopy.test('')) output.push(''); - } else output.push(string.slice(lastLastIndex)); - return output[LENGTH] > splitLimit ? output.slice(0, splitLimit) : output; - }; - // Chakra, V8 - } else if ('0'[$SPLIT](undefined, 0)[LENGTH]) { - $split = function (separator, limit) { - return separator === undefined && limit === 0 ? [] : _split.call(this, separator, limit); - }; - } - // 21.1.3.17 String.prototype.split(separator, limit) - return [function split(separator, limit) { - var O = defined(this); - var fn = separator == undefined ? undefined : separator[SPLIT]; - return fn !== undefined ? fn.call(separator, O, limit) : $split.call(String(O), separator, limit); - }, $split]; - }); - - -/***/ }), -/* 205 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var LIBRARY = __webpack_require__(24); - var global = __webpack_require__(4); - var ctx = __webpack_require__(20); - var classof = __webpack_require__(74); - var $export = __webpack_require__(8); - var isObject = __webpack_require__(13); - var aFunction = __webpack_require__(21); - var anInstance = __webpack_require__(206); - var forOf = __webpack_require__(207); - var speciesConstructor = __webpack_require__(208); - var task = __webpack_require__(209).set; - var microtask = __webpack_require__(210)(); - var newPromiseCapabilityModule = __webpack_require__(211); - var perform = __webpack_require__(212); - var userAgent = __webpack_require__(213); - var promiseResolve = __webpack_require__(214); - var PROMISE = 'Promise'; - var TypeError = global.TypeError; - var process = global.process; - var versions = process && process.versions; - var v8 = versions && versions.v8 || ''; - var $Promise = global[PROMISE]; - var isNode = classof(process) == 'process'; - var empty = function () { /* empty */ }; - var Internal, newGenericPromiseCapability, OwnPromiseCapability, Wrapper; - var newPromiseCapability = newGenericPromiseCapability = newPromiseCapabilityModule.f; - - var USE_NATIVE = !!function () { - try { - // correct subclassing with @@species support - var promise = $Promise.resolve(1); - var FakePromise = (promise.constructor = {})[__webpack_require__(26)('species')] = function (exec) { - exec(empty, empty); - }; - // unhandled rejections tracking support, NodeJS Promise without it fails @@species test - return (isNode || typeof PromiseRejectionEvent == 'function') - && promise.then(empty) instanceof FakePromise - // v8 6.6 (Node 10 and Chrome 66) have a bug with resolving custom thenables - // https://bugs.chromium.org/p/chromium/issues/detail?id=830565 - // we can't detect it synchronously, so just check versions - && v8.indexOf('6.6') !== 0 - && userAgent.indexOf('Chrome/66') === -1; - } catch (e) { /* empty */ } - }(); - - // helpers - var isThenable = function (it) { - var then; - return isObject(it) && typeof (then = it.then) == 'function' ? then : false; - }; - var notify = function (promise, isReject) { - if (promise._n) return; - promise._n = true; - var chain = promise._c; - microtask(function () { - var value = promise._v; - var ok = promise._s == 1; - var i = 0; - var run = function (reaction) { - var handler = ok ? reaction.ok : reaction.fail; - var resolve = reaction.resolve; - var reject = reaction.reject; - var domain = reaction.domain; - var result, then, exited; - try { - if (handler) { - if (!ok) { - if (promise._h == 2) onHandleUnhandled(promise); - promise._h = 1; - } - if (handler === true) result = value; - else { - if (domain) domain.enter(); - result = handler(value); // may throw - if (domain) { - domain.exit(); - exited = true; - } - } - if (result === reaction.promise) { - reject(TypeError('Promise-chain cycle')); - } else if (then = isThenable(result)) { - then.call(result, resolve, reject); - } else resolve(result); - } else reject(value); - } catch (e) { - if (domain && !exited) domain.exit(); - reject(e); - } - }; - while (chain.length > i) run(chain[i++]); // variable length - can't use forEach - promise._c = []; - promise._n = false; - if (isReject && !promise._h) onUnhandled(promise); - }); - }; - var onUnhandled = function (promise) { - task.call(global, function () { - var value = promise._v; - var unhandled = isUnhandled(promise); - var result, handler, console; - if (unhandled) { - result = perform(function () { - if (isNode) { - process.emit('unhandledRejection', value, promise); - } else if (handler = global.onunhandledrejection) { - handler({ promise: promise, reason: value }); - } else if ((console = global.console) && console.error) { - console.error('Unhandled promise rejection', value); - } - }); - // Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should - promise._h = isNode || isUnhandled(promise) ? 2 : 1; - } promise._a = undefined; - if (unhandled && result.e) throw result.v; - }); - }; - var isUnhandled = function (promise) { - return promise._h !== 1 && (promise._a || promise._c).length === 0; - }; - var onHandleUnhandled = function (promise) { - task.call(global, function () { - var handler; - if (isNode) { - process.emit('rejectionHandled', promise); - } else if (handler = global.onrejectionhandled) { - handler({ promise: promise, reason: promise._v }); - } - }); - }; - var $reject = function (value) { - var promise = this; - if (promise._d) return; - promise._d = true; - promise = promise._w || promise; // unwrap - promise._v = value; - promise._s = 2; - if (!promise._a) promise._a = promise._c.slice(); - notify(promise, true); - }; - var $resolve = function (value) { - var promise = this; - var then; - if (promise._d) return; - promise._d = true; - promise = promise._w || promise; // unwrap - try { - if (promise === value) throw TypeError("Promise can't be resolved itself"); - if (then = isThenable(value)) { - microtask(function () { - var wrapper = { _w: promise, _d: false }; // wrap - try { - then.call(value, ctx($resolve, wrapper, 1), ctx($reject, wrapper, 1)); - } catch (e) { - $reject.call(wrapper, e); - } - }); - } else { - promise._v = value; - promise._s = 1; - notify(promise, false); - } - } catch (e) { - $reject.call({ _w: promise, _d: false }, e); // wrap - } - }; - - // constructor polyfill - if (!USE_NATIVE) { - // 25.4.3.1 Promise(executor) - $Promise = function Promise(executor) { - anInstance(this, $Promise, PROMISE, '_h'); - aFunction(executor); - Internal.call(this); - try { - executor(ctx($resolve, this, 1), ctx($reject, this, 1)); - } catch (err) { - $reject.call(this, err); - } - }; - // eslint-disable-next-line no-unused-vars - Internal = function Promise(executor) { - this._c = []; // <- awaiting reactions - this._a = undefined; // <- checked in isUnhandled reactions - this._s = 0; // <- state - this._d = false; // <- done - this._v = undefined; // <- value - this._h = 0; // <- rejection state, 0 - default, 1 - handled, 2 - unhandled - this._n = false; // <- notify - }; - Internal.prototype = __webpack_require__(215)($Promise.prototype, { - // 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected) - then: function then(onFulfilled, onRejected) { - var reaction = newPromiseCapability(speciesConstructor(this, $Promise)); - reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true; - reaction.fail = typeof onRejected == 'function' && onRejected; - reaction.domain = isNode ? process.domain : undefined; - this._c.push(reaction); - if (this._a) this._a.push(reaction); - if (this._s) notify(this, false); - return reaction.promise; - }, - // 25.4.5.1 Promise.prototype.catch(onRejected) - 'catch': function (onRejected) { - return this.then(undefined, onRejected); - } - }); - OwnPromiseCapability = function () { - var promise = new Internal(); - this.promise = promise; - this.resolve = ctx($resolve, promise, 1); - this.reject = ctx($reject, promise, 1); - }; - newPromiseCapabilityModule.f = newPromiseCapability = function (C) { - return C === $Promise || C === Wrapper - ? new OwnPromiseCapability(C) - : newGenericPromiseCapability(C); - }; - } - - $export($export.G + $export.W + $export.F * !USE_NATIVE, { Promise: $Promise }); - __webpack_require__(25)($Promise, PROMISE); - __webpack_require__(193)(PROMISE); - Wrapper = __webpack_require__(9)[PROMISE]; - - // statics - $export($export.S + $export.F * !USE_NATIVE, PROMISE, { - // 25.4.4.5 Promise.reject(r) - reject: function reject(r) { - var capability = newPromiseCapability(this); - var $$reject = capability.reject; - $$reject(r); - return capability.promise; - } - }); - $export($export.S + $export.F * (LIBRARY || !USE_NATIVE), PROMISE, { - // 25.4.4.6 Promise.resolve(x) - resolve: function resolve(x) { - return promiseResolve(LIBRARY && this === Wrapper ? $Promise : this, x); - } - }); - $export($export.S + $export.F * !(USE_NATIVE && __webpack_require__(166)(function (iter) { - $Promise.all(iter)['catch'](empty); - })), PROMISE, { - // 25.4.4.1 Promise.all(iterable) - all: function all(iterable) { - var C = this; - var capability = newPromiseCapability(C); - var resolve = capability.resolve; - var reject = capability.reject; - var result = perform(function () { - var values = []; - var index = 0; - var remaining = 1; - forOf(iterable, false, function (promise) { - var $index = index++; - var alreadyCalled = false; - values.push(undefined); - remaining++; - C.resolve(promise).then(function (value) { - if (alreadyCalled) return; - alreadyCalled = true; - values[$index] = value; - --remaining || resolve(values); - }, reject); - }); - --remaining || resolve(values); - }); - if (result.e) reject(result.v); - return capability.promise; - }, - // 25.4.4.4 Promise.race(iterable) - race: function race(iterable) { - var C = this; - var capability = newPromiseCapability(C); - var reject = capability.reject; - var result = perform(function () { - forOf(iterable, false, function (promise) { - C.resolve(promise).then(capability.resolve, reject); - }); - }); - if (result.e) reject(result.v); - return capability.promise; - } - }); - - -/***/ }), -/* 206 */ -/***/ (function(module, exports) { - - module.exports = function (it, Constructor, name, forbiddenField) { - if (!(it instanceof Constructor) || (forbiddenField !== undefined && forbiddenField in it)) { - throw TypeError(name + ': incorrect invocation!'); - } return it; - }; - - -/***/ }), -/* 207 */ -/***/ (function(module, exports, __webpack_require__) { - - var ctx = __webpack_require__(20); - var call = __webpack_require__(162); - var isArrayIter = __webpack_require__(163); - var anObject = __webpack_require__(12); - var toLength = __webpack_require__(37); - var getIterFn = __webpack_require__(165); - var BREAK = {}; - var RETURN = {}; - var exports = module.exports = function (iterable, entries, fn, that, ITERATOR) { - var iterFn = ITERATOR ? function () { return iterable; } : getIterFn(iterable); - var f = ctx(fn, that, entries ? 2 : 1); - var index = 0; - var length, step, iterator, result; - if (typeof iterFn != 'function') throw TypeError(iterable + ' is not iterable!'); - // fast case for arrays with default iterator - if (isArrayIter(iterFn)) for (length = toLength(iterable.length); length > index; index++) { - result = entries ? f(anObject(step = iterable[index])[0], step[1]) : f(iterable[index]); - if (result === BREAK || result === RETURN) return result; - } else for (iterator = iterFn.call(iterable); !(step = iterator.next()).done;) { - result = call(iterator, f, step.value, entries); - if (result === BREAK || result === RETURN) return result; - } - }; - exports.BREAK = BREAK; - exports.RETURN = RETURN; - - -/***/ }), -/* 208 */ -/***/ (function(module, exports, __webpack_require__) { - - // 7.3.20 SpeciesConstructor(O, defaultConstructor) - var anObject = __webpack_require__(12); - var aFunction = __webpack_require__(21); - var SPECIES = __webpack_require__(26)('species'); - module.exports = function (O, D) { - var C = anObject(O).constructor; - var S; - return C === undefined || (S = anObject(C)[SPECIES]) == undefined ? D : aFunction(S); - }; - - -/***/ }), -/* 209 */ -/***/ (function(module, exports, __webpack_require__) { - - var ctx = __webpack_require__(20); - var invoke = __webpack_require__(77); - var html = __webpack_require__(47); - var cel = __webpack_require__(15); - var global = __webpack_require__(4); - var process = global.process; - var setTask = global.setImmediate; - var clearTask = global.clearImmediate; - var MessageChannel = global.MessageChannel; - var Dispatch = global.Dispatch; - var counter = 0; - var queue = {}; - var ONREADYSTATECHANGE = 'onreadystatechange'; - var defer, channel, port; - var run = function () { - var id = +this; - // eslint-disable-next-line no-prototype-builtins - if (queue.hasOwnProperty(id)) { - var fn = queue[id]; - delete queue[id]; - fn(); - } - }; - var listener = function (event) { - run.call(event.data); - }; - // Node.js 0.9+ & IE10+ has setImmediate, otherwise: - if (!setTask || !clearTask) { - setTask = function setImmediate(fn) { - var args = []; - var i = 1; - while (arguments.length > i) args.push(arguments[i++]); - queue[++counter] = function () { - // eslint-disable-next-line no-new-func - invoke(typeof fn == 'function' ? fn : Function(fn), args); - }; - defer(counter); - return counter; - }; - clearTask = function clearImmediate(id) { - delete queue[id]; - }; - // Node.js 0.8- - if (__webpack_require__(34)(process) == 'process') { - defer = function (id) { - process.nextTick(ctx(run, id, 1)); - }; - // Sphere (JS game engine) Dispatch API - } else if (Dispatch && Dispatch.now) { - defer = function (id) { - Dispatch.now(ctx(run, id, 1)); - }; - // Browsers with MessageChannel, includes WebWorkers - } else if (MessageChannel) { - channel = new MessageChannel(); - port = channel.port2; - channel.port1.onmessage = listener; - defer = ctx(port.postMessage, port, 1); - // Browsers with postMessage, skip WebWorkers - // IE8 has postMessage, but it's sync & typeof its postMessage is 'object' - } else if (global.addEventListener && typeof postMessage == 'function' && !global.importScripts) { - defer = function (id) { - global.postMessage(id + '', '*'); - }; - global.addEventListener('message', listener, false); - // IE8- - } else if (ONREADYSTATECHANGE in cel('script')) { - defer = function (id) { - html.appendChild(cel('script'))[ONREADYSTATECHANGE] = function () { - html.removeChild(this); - run.call(id); - }; - }; - // Rest old browsers - } else { - defer = function (id) { - setTimeout(ctx(run, id, 1), 0); - }; - } - } - module.exports = { - set: setTask, - clear: clearTask - }; - - -/***/ }), -/* 210 */ -/***/ (function(module, exports, __webpack_require__) { - - var global = __webpack_require__(4); - var macrotask = __webpack_require__(209).set; - var Observer = global.MutationObserver || global.WebKitMutationObserver; - var process = global.process; - var Promise = global.Promise; - var isNode = __webpack_require__(34)(process) == 'process'; - - module.exports = function () { - var head, last, notify; - - var flush = function () { - var parent, fn; - if (isNode && (parent = process.domain)) parent.exit(); - while (head) { - fn = head.fn; - head = head.next; - try { - fn(); - } catch (e) { - if (head) notify(); - else last = undefined; - throw e; - } - } last = undefined; - if (parent) parent.enter(); - }; - - // Node.js - if (isNode) { - notify = function () { - process.nextTick(flush); - }; - // browsers with MutationObserver, except iOS Safari - https://github.com/zloirock/core-js/issues/339 - } else if (Observer && !(global.navigator && global.navigator.standalone)) { - var toggle = true; - var node = document.createTextNode(''); - new Observer(flush).observe(node, { characterData: true }); // eslint-disable-line no-new - notify = function () { - node.data = toggle = !toggle; - }; - // environments with maybe non-completely correct, but existent Promise - } else if (Promise && Promise.resolve) { - // Promise.resolve without an argument throws an error in LG WebOS 2 - var promise = Promise.resolve(undefined); - notify = function () { - promise.then(flush); - }; - // for other environments - macrotask based on: - // - setImmediate - // - MessageChannel - // - window.postMessag - // - onreadystatechange - // - setTimeout - } else { - notify = function () { - // strange IE + webpack dev server bug - use .call(global) - macrotask.call(global, flush); - }; - } - - return function (fn) { - var task = { fn: fn, next: undefined }; - if (last) last.next = task; - if (!head) { - head = task; - notify(); - } last = task; - }; - }; - - -/***/ }), -/* 211 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // 25.4.1.5 NewPromiseCapability(C) - var aFunction = __webpack_require__(21); - - function PromiseCapability(C) { - var resolve, reject; - this.promise = new C(function ($$resolve, $$reject) { - if (resolve !== undefined || reject !== undefined) throw TypeError('Bad Promise constructor'); - resolve = $$resolve; - reject = $$reject; - }); - this.resolve = aFunction(resolve); - this.reject = aFunction(reject); - } - - module.exports.f = function (C) { - return new PromiseCapability(C); - }; - - -/***/ }), -/* 212 */ -/***/ (function(module, exports) { - - module.exports = function (exec) { - try { - return { e: false, v: exec() }; - } catch (e) { - return { e: true, v: e }; - } - }; - - -/***/ }), -/* 213 */ -/***/ (function(module, exports, __webpack_require__) { - - var global = __webpack_require__(4); - var navigator = global.navigator; - - module.exports = navigator && navigator.userAgent || ''; - - -/***/ }), -/* 214 */ -/***/ (function(module, exports, __webpack_require__) { - - var anObject = __webpack_require__(12); - var isObject = __webpack_require__(13); - var newPromiseCapability = __webpack_require__(211); - - module.exports = function (C, x) { - anObject(C); - if (isObject(x) && x.constructor === C) return x; - var promiseCapability = newPromiseCapability.f(C); - var resolve = promiseCapability.resolve; - resolve(x); - return promiseCapability.promise; - }; - - -/***/ }), -/* 215 */ -/***/ (function(module, exports, __webpack_require__) { - - var redefine = __webpack_require__(18); - module.exports = function (target, src, safe) { - for (var key in src) redefine(target, key, src[key], safe); - return target; - }; - - -/***/ }), -/* 216 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var strong = __webpack_require__(217); - var validate = __webpack_require__(218); - var MAP = 'Map'; - - // 23.1 Map Objects - module.exports = __webpack_require__(219)(MAP, function (get) { - return function Map() { return get(this, arguments.length > 0 ? arguments[0] : undefined); }; - }, { - // 23.1.3.6 Map.prototype.get(key) - get: function get(key) { - var entry = strong.getEntry(validate(this, MAP), key); - return entry && entry.v; - }, - // 23.1.3.9 Map.prototype.set(key, value) - set: function set(key, value) { - return strong.def(validate(this, MAP), key === 0 ? 0 : key, value); - } - }, strong, true); - - -/***/ }), -/* 217 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var dP = __webpack_require__(11).f; - var create = __webpack_require__(45); - var redefineAll = __webpack_require__(215); - var ctx = __webpack_require__(20); - var anInstance = __webpack_require__(206); - var forOf = __webpack_require__(207); - var $iterDefine = __webpack_require__(128); - var step = __webpack_require__(195); - var setSpecies = __webpack_require__(193); - var DESCRIPTORS = __webpack_require__(6); - var fastKey = __webpack_require__(22).fastKey; - var validate = __webpack_require__(218); - var SIZE = DESCRIPTORS ? '_s' : 'size'; - - var getEntry = function (that, key) { - // fast case - var index = fastKey(key); - var entry; - if (index !== 'F') return that._i[index]; - // frozen object case - for (entry = that._f; entry; entry = entry.n) { - if (entry.k == key) return entry; - } - }; - - module.exports = { - getConstructor: function (wrapper, NAME, IS_MAP, ADDER) { - var C = wrapper(function (that, iterable) { - anInstance(that, C, NAME, '_i'); - that._t = NAME; // collection type - that._i = create(null); // index - that._f = undefined; // first entry - that._l = undefined; // last entry - that[SIZE] = 0; // size - if (iterable != undefined) forOf(iterable, IS_MAP, that[ADDER], that); - }); - redefineAll(C.prototype, { - // 23.1.3.1 Map.prototype.clear() - // 23.2.3.2 Set.prototype.clear() - clear: function clear() { - for (var that = validate(this, NAME), data = that._i, entry = that._f; entry; entry = entry.n) { - entry.r = true; - if (entry.p) entry.p = entry.p.n = undefined; - delete data[entry.i]; - } - that._f = that._l = undefined; - that[SIZE] = 0; - }, - // 23.1.3.3 Map.prototype.delete(key) - // 23.2.3.4 Set.prototype.delete(value) - 'delete': function (key) { - var that = validate(this, NAME); - var entry = getEntry(that, key); - if (entry) { - var next = entry.n; - var prev = entry.p; - delete that._i[entry.i]; - entry.r = true; - if (prev) prev.n = next; - if (next) next.p = prev; - if (that._f == entry) that._f = next; - if (that._l == entry) that._l = prev; - that[SIZE]--; - } return !!entry; - }, - // 23.2.3.6 Set.prototype.forEach(callbackfn, thisArg = undefined) - // 23.1.3.5 Map.prototype.forEach(callbackfn, thisArg = undefined) - forEach: function forEach(callbackfn /* , that = undefined */) { - validate(this, NAME); - var f = ctx(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3); - var entry; - while (entry = entry ? entry.n : this._f) { - f(entry.v, entry.k, this); - // revert to the last existing entry - while (entry && entry.r) entry = entry.p; - } - }, - // 23.1.3.7 Map.prototype.has(key) - // 23.2.3.7 Set.prototype.has(value) - has: function has(key) { - return !!getEntry(validate(this, NAME), key); - } - }); - if (DESCRIPTORS) dP(C.prototype, 'size', { - get: function () { - return validate(this, NAME)[SIZE]; - } - }); - return C; - }, - def: function (that, key, value) { - var entry = getEntry(that, key); - var prev, index; - // change existing entry - if (entry) { - entry.v = value; - // create new entry - } else { - that._l = entry = { - i: index = fastKey(key, true), // <- index - k: key, // <- key - v: value, // <- value - p: prev = that._l, // <- previous entry - n: undefined, // <- next entry - r: false // <- removed - }; - if (!that._f) that._f = entry; - if (prev) prev.n = entry; - that[SIZE]++; - // add to index - if (index !== 'F') that._i[index] = entry; - } return that; - }, - getEntry: getEntry, - setStrong: function (C, NAME, IS_MAP) { - // add .keys, .values, .entries, [@@iterator] - // 23.1.3.4, 23.1.3.8, 23.1.3.11, 23.1.3.12, 23.2.3.5, 23.2.3.8, 23.2.3.10, 23.2.3.11 - $iterDefine(C, NAME, function (iterated, kind) { - this._t = validate(iterated, NAME); // target - this._k = kind; // kind - this._l = undefined; // previous - }, function () { - var that = this; - var kind = that._k; - var entry = that._l; - // revert to the last existing entry - while (entry && entry.r) entry = entry.p; - // get next entry - if (!that._t || !(that._l = entry = entry ? entry.n : that._t._f)) { - // or finish the iteration - that._t = undefined; - return step(1); - } - // return step by kind - if (kind == 'keys') return step(0, entry.k); - if (kind == 'values') return step(0, entry.v); - return step(0, [entry.k, entry.v]); - }, IS_MAP ? 'entries' : 'values', !IS_MAP, true); - - // add [@@species], 23.1.2.2, 23.2.2.2 - setSpecies(NAME); - } - }; - - -/***/ }), -/* 218 */ -/***/ (function(module, exports, __webpack_require__) { - - var isObject = __webpack_require__(13); - module.exports = function (it, TYPE) { - if (!isObject(it) || it._t !== TYPE) throw TypeError('Incompatible receiver, ' + TYPE + ' required!'); - return it; - }; - - -/***/ }), -/* 219 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var global = __webpack_require__(4); - var $export = __webpack_require__(8); - var redefine = __webpack_require__(18); - var redefineAll = __webpack_require__(215); - var meta = __webpack_require__(22); - var forOf = __webpack_require__(207); - var anInstance = __webpack_require__(206); - var isObject = __webpack_require__(13); - var fails = __webpack_require__(7); - var $iterDetect = __webpack_require__(166); - var setToStringTag = __webpack_require__(25); - var inheritIfRequired = __webpack_require__(87); - - module.exports = function (NAME, wrapper, methods, common, IS_MAP, IS_WEAK) { - var Base = global[NAME]; - var C = Base; - var ADDER = IS_MAP ? 'set' : 'add'; - var proto = C && C.prototype; - var O = {}; - var fixMethod = function (KEY) { - var fn = proto[KEY]; - redefine(proto, KEY, - KEY == 'delete' ? function (a) { - return IS_WEAK && !isObject(a) ? false : fn.call(this, a === 0 ? 0 : a); - } : KEY == 'has' ? function has(a) { - return IS_WEAK && !isObject(a) ? false : fn.call(this, a === 0 ? 0 : a); - } : KEY == 'get' ? function get(a) { - return IS_WEAK && !isObject(a) ? undefined : fn.call(this, a === 0 ? 0 : a); - } : KEY == 'add' ? function add(a) { fn.call(this, a === 0 ? 0 : a); return this; } - : function set(a, b) { fn.call(this, a === 0 ? 0 : a, b); return this; } - ); - }; - if (typeof C != 'function' || !(IS_WEAK || proto.forEach && !fails(function () { - new C().entries().next(); - }))) { - // create collection constructor - C = common.getConstructor(wrapper, NAME, IS_MAP, ADDER); - redefineAll(C.prototype, methods); - meta.NEED = true; - } else { - var instance = new C(); - // early implementations not supports chaining - var HASNT_CHAINING = instance[ADDER](IS_WEAK ? {} : -0, 1) != instance; - // V8 ~ Chromium 40- weak-collections throws on primitives, but should return false - var THROWS_ON_PRIMITIVES = fails(function () { instance.has(1); }); - // most early implementations doesn't supports iterables, most modern - not close it correctly - var ACCEPT_ITERABLES = $iterDetect(function (iter) { new C(iter); }); // eslint-disable-line no-new - // for early implementations -0 and +0 not the same - var BUGGY_ZERO = !IS_WEAK && fails(function () { - // V8 ~ Chromium 42- fails only with 5+ elements - var $instance = new C(); - var index = 5; - while (index--) $instance[ADDER](index, index); - return !$instance.has(-0); - }); - if (!ACCEPT_ITERABLES) { - C = wrapper(function (target, iterable) { - anInstance(target, C, NAME); - var that = inheritIfRequired(new Base(), target, C); - if (iterable != undefined) forOf(iterable, IS_MAP, that[ADDER], that); - return that; - }); - C.prototype = proto; - proto.constructor = C; - } - if (THROWS_ON_PRIMITIVES || BUGGY_ZERO) { - fixMethod('delete'); - fixMethod('has'); - IS_MAP && fixMethod('get'); - } - if (BUGGY_ZERO || HASNT_CHAINING) fixMethod(ADDER); - // weak collections should not contains .clear method - if (IS_WEAK && proto.clear) delete proto.clear; - } - - setToStringTag(C, NAME); - - O[NAME] = C; - $export($export.G + $export.W + $export.F * (C != Base), O); - - if (!IS_WEAK) common.setStrong(C, NAME, IS_MAP); - - return C; - }; - - -/***/ }), -/* 220 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var strong = __webpack_require__(217); - var validate = __webpack_require__(218); - var SET = 'Set'; - - // 23.2 Set Objects - module.exports = __webpack_require__(219)(SET, function (get) { - return function Set() { return get(this, arguments.length > 0 ? arguments[0] : undefined); }; - }, { - // 23.2.3.1 Set.prototype.add(value) - add: function add(value) { - return strong.def(validate(this, SET), value = value === 0 ? 0 : value, value); - } - }, strong); - - -/***/ }), -/* 221 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var each = __webpack_require__(173)(0); - var redefine = __webpack_require__(18); - var meta = __webpack_require__(22); - var assign = __webpack_require__(68); - var weak = __webpack_require__(222); - var isObject = __webpack_require__(13); - var fails = __webpack_require__(7); - var validate = __webpack_require__(218); - var WEAK_MAP = 'WeakMap'; - var getWeak = meta.getWeak; - var isExtensible = Object.isExtensible; - var uncaughtFrozenStore = weak.ufstore; - var tmp = {}; - var InternalMap; - - var wrapper = function (get) { - return function WeakMap() { - return get(this, arguments.length > 0 ? arguments[0] : undefined); - }; - }; - - var methods = { - // 23.3.3.3 WeakMap.prototype.get(key) - get: function get(key) { - if (isObject(key)) { - var data = getWeak(key); - if (data === true) return uncaughtFrozenStore(validate(this, WEAK_MAP)).get(key); - return data ? data[this._i] : undefined; - } - }, - // 23.3.3.5 WeakMap.prototype.set(key, value) - set: function set(key, value) { - return weak.def(validate(this, WEAK_MAP), key, value); - } - }; - - // 23.3 WeakMap Objects - var $WeakMap = module.exports = __webpack_require__(219)(WEAK_MAP, wrapper, methods, weak, true, true); - - // IE11 WeakMap frozen keys fix - if (fails(function () { return new $WeakMap().set((Object.freeze || Object)(tmp), 7).get(tmp) != 7; })) { - InternalMap = weak.getConstructor(wrapper, WEAK_MAP); - assign(InternalMap.prototype, methods); - meta.NEED = true; - each(['delete', 'has', 'get', 'set'], function (key) { - var proto = $WeakMap.prototype; - var method = proto[key]; - redefine(proto, key, function (a, b) { - // store frozen objects on internal weakmap shim - if (isObject(a) && !isExtensible(a)) { - if (!this._f) this._f = new InternalMap(); - var result = this._f[key](a, b); - return key == 'set' ? this : result; - // store all the rest on native weakmap - } return method.call(this, a, b); - }); - }); - } - - -/***/ }), -/* 222 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var redefineAll = __webpack_require__(215); - var getWeak = __webpack_require__(22).getWeak; - var anObject = __webpack_require__(12); - var isObject = __webpack_require__(13); - var anInstance = __webpack_require__(206); - var forOf = __webpack_require__(207); - var createArrayMethod = __webpack_require__(173); - var $has = __webpack_require__(5); - var validate = __webpack_require__(218); - var arrayFind = createArrayMethod(5); - var arrayFindIndex = createArrayMethod(6); - var id = 0; - - // fallback for uncaught frozen keys - var uncaughtFrozenStore = function (that) { - return that._l || (that._l = new UncaughtFrozenStore()); - }; - var UncaughtFrozenStore = function () { - this.a = []; - }; - var findUncaughtFrozen = function (store, key) { - return arrayFind(store.a, function (it) { - return it[0] === key; - }); - }; - UncaughtFrozenStore.prototype = { - get: function (key) { - var entry = findUncaughtFrozen(this, key); - if (entry) return entry[1]; - }, - has: function (key) { - return !!findUncaughtFrozen(this, key); - }, - set: function (key, value) { - var entry = findUncaughtFrozen(this, key); - if (entry) entry[1] = value; - else this.a.push([key, value]); - }, - 'delete': function (key) { - var index = arrayFindIndex(this.a, function (it) { - return it[0] === key; - }); - if (~index) this.a.splice(index, 1); - return !!~index; - } - }; - - module.exports = { - getConstructor: function (wrapper, NAME, IS_MAP, ADDER) { - var C = wrapper(function (that, iterable) { - anInstance(that, C, NAME, '_i'); - that._t = NAME; // collection type - that._i = id++; // collection id - that._l = undefined; // leak store for uncaught frozen objects - if (iterable != undefined) forOf(iterable, IS_MAP, that[ADDER], that); - }); - redefineAll(C.prototype, { - // 23.3.3.2 WeakMap.prototype.delete(key) - // 23.4.3.3 WeakSet.prototype.delete(value) - 'delete': function (key) { - if (!isObject(key)) return false; - var data = getWeak(key); - if (data === true) return uncaughtFrozenStore(validate(this, NAME))['delete'](key); - return data && $has(data, this._i) && delete data[this._i]; - }, - // 23.3.3.4 WeakMap.prototype.has(key) - // 23.4.3.4 WeakSet.prototype.has(value) - has: function has(key) { - if (!isObject(key)) return false; - var data = getWeak(key); - if (data === true) return uncaughtFrozenStore(validate(this, NAME)).has(key); - return data && $has(data, this._i); - } - }); - return C; - }, - def: function (that, key, value) { - var data = getWeak(anObject(key), true); - if (data === true) uncaughtFrozenStore(that).set(key, value); - else data[that._i] = value; - return that; - }, - ufstore: uncaughtFrozenStore - }; - - -/***/ }), -/* 223 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var weak = __webpack_require__(222); - var validate = __webpack_require__(218); - var WEAK_SET = 'WeakSet'; - - // 23.4 WeakSet Objects - __webpack_require__(219)(WEAK_SET, function (get) { - return function WeakSet() { return get(this, arguments.length > 0 ? arguments[0] : undefined); }; - }, { - // 23.4.3.1 WeakSet.prototype.add(value) - add: function add(value) { - return weak.def(validate(this, WEAK_SET), value, true); - } - }, weak, false, true); - - -/***/ }), -/* 224 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var $typed = __webpack_require__(225); - var buffer = __webpack_require__(226); - var anObject = __webpack_require__(12); - var toAbsoluteIndex = __webpack_require__(39); - var toLength = __webpack_require__(37); - var isObject = __webpack_require__(13); - var ArrayBuffer = __webpack_require__(4).ArrayBuffer; - var speciesConstructor = __webpack_require__(208); - var $ArrayBuffer = buffer.ArrayBuffer; - var $DataView = buffer.DataView; - var $isView = $typed.ABV && ArrayBuffer.isView; - var $slice = $ArrayBuffer.prototype.slice; - var VIEW = $typed.VIEW; - var ARRAY_BUFFER = 'ArrayBuffer'; - - $export($export.G + $export.W + $export.F * (ArrayBuffer !== $ArrayBuffer), { ArrayBuffer: $ArrayBuffer }); - - $export($export.S + $export.F * !$typed.CONSTR, ARRAY_BUFFER, { - // 24.1.3.1 ArrayBuffer.isView(arg) - isView: function isView(it) { - return $isView && $isView(it) || isObject(it) && VIEW in it; - } - }); - - $export($export.P + $export.U + $export.F * __webpack_require__(7)(function () { - return !new $ArrayBuffer(2).slice(1, undefined).byteLength; - }), ARRAY_BUFFER, { - // 24.1.4.3 ArrayBuffer.prototype.slice(start, end) - slice: function slice(start, end) { - if ($slice !== undefined && end === undefined) return $slice.call(anObject(this), start); // FF fix - var len = anObject(this).byteLength; - var first = toAbsoluteIndex(start, len); - var fin = toAbsoluteIndex(end === undefined ? len : end, len); - var result = new (speciesConstructor(this, $ArrayBuffer))(toLength(fin - first)); - var viewS = new $DataView(this); - var viewT = new $DataView(result); - var index = 0; - while (first < fin) { - viewT.setUint8(index++, viewS.getUint8(first++)); - } return result; - } - }); - - __webpack_require__(193)(ARRAY_BUFFER); - - -/***/ }), -/* 225 */ -/***/ (function(module, exports, __webpack_require__) { - - var global = __webpack_require__(4); - var hide = __webpack_require__(10); - var uid = __webpack_require__(19); - var TYPED = uid('typed_array'); - var VIEW = uid('view'); - var ABV = !!(global.ArrayBuffer && global.DataView); - var CONSTR = ABV; - var i = 0; - var l = 9; - var Typed; - - var TypedArrayConstructors = ( - 'Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array' - ).split(','); - - while (i < l) { - if (Typed = global[TypedArrayConstructors[i++]]) { - hide(Typed.prototype, TYPED, true); - hide(Typed.prototype, VIEW, true); - } else CONSTR = false; - } - - module.exports = { - ABV: ABV, - CONSTR: CONSTR, - TYPED: TYPED, - VIEW: VIEW - }; - - -/***/ }), -/* 226 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var global = __webpack_require__(4); - var DESCRIPTORS = __webpack_require__(6); - var LIBRARY = __webpack_require__(24); - var $typed = __webpack_require__(225); - var hide = __webpack_require__(10); - var redefineAll = __webpack_require__(215); - var fails = __webpack_require__(7); - var anInstance = __webpack_require__(206); - var toInteger = __webpack_require__(38); - var toLength = __webpack_require__(37); - var toIndex = __webpack_require__(227); - var gOPN = __webpack_require__(49).f; - var dP = __webpack_require__(11).f; - var arrayFill = __webpack_require__(189); - var setToStringTag = __webpack_require__(25); - var ARRAY_BUFFER = 'ArrayBuffer'; - var DATA_VIEW = 'DataView'; - var PROTOTYPE = 'prototype'; - var WRONG_LENGTH = 'Wrong length!'; - var WRONG_INDEX = 'Wrong index!'; - var $ArrayBuffer = global[ARRAY_BUFFER]; - var $DataView = global[DATA_VIEW]; - var Math = global.Math; - var RangeError = global.RangeError; - // eslint-disable-next-line no-shadow-restricted-names - var Infinity = global.Infinity; - var BaseBuffer = $ArrayBuffer; - var abs = Math.abs; - var pow = Math.pow; - var floor = Math.floor; - var log = Math.log; - var LN2 = Math.LN2; - var BUFFER = 'buffer'; - var BYTE_LENGTH = 'byteLength'; - var BYTE_OFFSET = 'byteOffset'; - var $BUFFER = DESCRIPTORS ? '_b' : BUFFER; - var $LENGTH = DESCRIPTORS ? '_l' : BYTE_LENGTH; - var $OFFSET = DESCRIPTORS ? '_o' : BYTE_OFFSET; - - // IEEE754 conversions based on https://github.com/feross/ieee754 - function packIEEE754(value, mLen, nBytes) { - var buffer = new Array(nBytes); - var eLen = nBytes * 8 - mLen - 1; - var eMax = (1 << eLen) - 1; - var eBias = eMax >> 1; - var rt = mLen === 23 ? pow(2, -24) - pow(2, -77) : 0; - var i = 0; - var s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0; - var e, m, c; - value = abs(value); - // eslint-disable-next-line no-self-compare - if (value != value || value === Infinity) { - // eslint-disable-next-line no-self-compare - m = value != value ? 1 : 0; - e = eMax; - } else { - e = floor(log(value) / LN2); - if (value * (c = pow(2, -e)) < 1) { - e--; - c *= 2; - } - if (e + eBias >= 1) { - value += rt / c; - } else { - value += rt * pow(2, 1 - eBias); - } - if (value * c >= 2) { - e++; - c /= 2; - } - if (e + eBias >= eMax) { - m = 0; - e = eMax; - } else if (e + eBias >= 1) { - m = (value * c - 1) * pow(2, mLen); - e = e + eBias; - } else { - m = value * pow(2, eBias - 1) * pow(2, mLen); - e = 0; - } - } - for (; mLen >= 8; buffer[i++] = m & 255, m /= 256, mLen -= 8); - e = e << mLen | m; - eLen += mLen; - for (; eLen > 0; buffer[i++] = e & 255, e /= 256, eLen -= 8); - buffer[--i] |= s * 128; - return buffer; - } - function unpackIEEE754(buffer, mLen, nBytes) { - var eLen = nBytes * 8 - mLen - 1; - var eMax = (1 << eLen) - 1; - var eBias = eMax >> 1; - var nBits = eLen - 7; - var i = nBytes - 1; - var s = buffer[i--]; - var e = s & 127; - var m; - s >>= 7; - for (; nBits > 0; e = e * 256 + buffer[i], i--, nBits -= 8); - m = e & (1 << -nBits) - 1; - e >>= -nBits; - nBits += mLen; - for (; nBits > 0; m = m * 256 + buffer[i], i--, nBits -= 8); - if (e === 0) { - e = 1 - eBias; - } else if (e === eMax) { - return m ? NaN : s ? -Infinity : Infinity; - } else { - m = m + pow(2, mLen); - e = e - eBias; - } return (s ? -1 : 1) * m * pow(2, e - mLen); - } - - function unpackI32(bytes) { - return bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0]; - } - function packI8(it) { - return [it & 0xff]; - } - function packI16(it) { - return [it & 0xff, it >> 8 & 0xff]; - } - function packI32(it) { - return [it & 0xff, it >> 8 & 0xff, it >> 16 & 0xff, it >> 24 & 0xff]; - } - function packF64(it) { - return packIEEE754(it, 52, 8); - } - function packF32(it) { - return packIEEE754(it, 23, 4); - } - - function addGetter(C, key, internal) { - dP(C[PROTOTYPE], key, { get: function () { return this[internal]; } }); - } - - function get(view, bytes, index, isLittleEndian) { - var numIndex = +index; - var intIndex = toIndex(numIndex); - if (intIndex + bytes > view[$LENGTH]) throw RangeError(WRONG_INDEX); - var store = view[$BUFFER]._b; - var start = intIndex + view[$OFFSET]; - var pack = store.slice(start, start + bytes); - return isLittleEndian ? pack : pack.reverse(); - } - function set(view, bytes, index, conversion, value, isLittleEndian) { - var numIndex = +index; - var intIndex = toIndex(numIndex); - if (intIndex + bytes > view[$LENGTH]) throw RangeError(WRONG_INDEX); - var store = view[$BUFFER]._b; - var start = intIndex + view[$OFFSET]; - var pack = conversion(+value); - for (var i = 0; i < bytes; i++) store[start + i] = pack[isLittleEndian ? i : bytes - i - 1]; - } - - if (!$typed.ABV) { - $ArrayBuffer = function ArrayBuffer(length) { - anInstance(this, $ArrayBuffer, ARRAY_BUFFER); - var byteLength = toIndex(length); - this._b = arrayFill.call(new Array(byteLength), 0); - this[$LENGTH] = byteLength; - }; - - $DataView = function DataView(buffer, byteOffset, byteLength) { - anInstance(this, $DataView, DATA_VIEW); - anInstance(buffer, $ArrayBuffer, DATA_VIEW); - var bufferLength = buffer[$LENGTH]; - var offset = toInteger(byteOffset); - if (offset < 0 || offset > bufferLength) throw RangeError('Wrong offset!'); - byteLength = byteLength === undefined ? bufferLength - offset : toLength(byteLength); - if (offset + byteLength > bufferLength) throw RangeError(WRONG_LENGTH); - this[$BUFFER] = buffer; - this[$OFFSET] = offset; - this[$LENGTH] = byteLength; - }; - - if (DESCRIPTORS) { - addGetter($ArrayBuffer, BYTE_LENGTH, '_l'); - addGetter($DataView, BUFFER, '_b'); - addGetter($DataView, BYTE_LENGTH, '_l'); - addGetter($DataView, BYTE_OFFSET, '_o'); - } - - redefineAll($DataView[PROTOTYPE], { - getInt8: function getInt8(byteOffset) { - return get(this, 1, byteOffset)[0] << 24 >> 24; - }, - getUint8: function getUint8(byteOffset) { - return get(this, 1, byteOffset)[0]; - }, - getInt16: function getInt16(byteOffset /* , littleEndian */) { - var bytes = get(this, 2, byteOffset, arguments[1]); - return (bytes[1] << 8 | bytes[0]) << 16 >> 16; - }, - getUint16: function getUint16(byteOffset /* , littleEndian */) { - var bytes = get(this, 2, byteOffset, arguments[1]); - return bytes[1] << 8 | bytes[0]; - }, - getInt32: function getInt32(byteOffset /* , littleEndian */) { - return unpackI32(get(this, 4, byteOffset, arguments[1])); - }, - getUint32: function getUint32(byteOffset /* , littleEndian */) { - return unpackI32(get(this, 4, byteOffset, arguments[1])) >>> 0; - }, - getFloat32: function getFloat32(byteOffset /* , littleEndian */) { - return unpackIEEE754(get(this, 4, byteOffset, arguments[1]), 23, 4); - }, - getFloat64: function getFloat64(byteOffset /* , littleEndian */) { - return unpackIEEE754(get(this, 8, byteOffset, arguments[1]), 52, 8); - }, - setInt8: function setInt8(byteOffset, value) { - set(this, 1, byteOffset, packI8, value); - }, - setUint8: function setUint8(byteOffset, value) { - set(this, 1, byteOffset, packI8, value); - }, - setInt16: function setInt16(byteOffset, value /* , littleEndian */) { - set(this, 2, byteOffset, packI16, value, arguments[2]); - }, - setUint16: function setUint16(byteOffset, value /* , littleEndian */) { - set(this, 2, byteOffset, packI16, value, arguments[2]); - }, - setInt32: function setInt32(byteOffset, value /* , littleEndian */) { - set(this, 4, byteOffset, packI32, value, arguments[2]); - }, - setUint32: function setUint32(byteOffset, value /* , littleEndian */) { - set(this, 4, byteOffset, packI32, value, arguments[2]); - }, - setFloat32: function setFloat32(byteOffset, value /* , littleEndian */) { - set(this, 4, byteOffset, packF32, value, arguments[2]); - }, - setFloat64: function setFloat64(byteOffset, value /* , littleEndian */) { - set(this, 8, byteOffset, packF64, value, arguments[2]); - } - }); - } else { - if (!fails(function () { - $ArrayBuffer(1); - }) || !fails(function () { - new $ArrayBuffer(-1); // eslint-disable-line no-new - }) || fails(function () { - new $ArrayBuffer(); // eslint-disable-line no-new - new $ArrayBuffer(1.5); // eslint-disable-line no-new - new $ArrayBuffer(NaN); // eslint-disable-line no-new - return $ArrayBuffer.name != ARRAY_BUFFER; - })) { - $ArrayBuffer = function ArrayBuffer(length) { - anInstance(this, $ArrayBuffer); - return new BaseBuffer(toIndex(length)); - }; - var ArrayBufferProto = $ArrayBuffer[PROTOTYPE] = BaseBuffer[PROTOTYPE]; - for (var keys = gOPN(BaseBuffer), j = 0, key; keys.length > j;) { - if (!((key = keys[j++]) in $ArrayBuffer)) hide($ArrayBuffer, key, BaseBuffer[key]); - } - if (!LIBRARY) ArrayBufferProto.constructor = $ArrayBuffer; - } - // iOS Safari 7.x bug - var view = new $DataView(new $ArrayBuffer(2)); - var $setInt8 = $DataView[PROTOTYPE].setInt8; - view.setInt8(0, 2147483648); - view.setInt8(1, 2147483649); - if (view.getInt8(0) || !view.getInt8(1)) redefineAll($DataView[PROTOTYPE], { - setInt8: function setInt8(byteOffset, value) { - $setInt8.call(this, byteOffset, value << 24 >> 24); - }, - setUint8: function setUint8(byteOffset, value) { - $setInt8.call(this, byteOffset, value << 24 >> 24); - } - }, true); - } - setToStringTag($ArrayBuffer, ARRAY_BUFFER); - setToStringTag($DataView, DATA_VIEW); - hide($DataView[PROTOTYPE], $typed.VIEW, true); - exports[ARRAY_BUFFER] = $ArrayBuffer; - exports[DATA_VIEW] = $DataView; - - -/***/ }), -/* 227 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://tc39.github.io/ecma262/#sec-toindex - var toInteger = __webpack_require__(38); - var toLength = __webpack_require__(37); - module.exports = function (it) { - if (it === undefined) return 0; - var number = toInteger(it); - var length = toLength(number); - if (number !== length) throw RangeError('Wrong length!'); - return length; - }; - - -/***/ }), -/* 228 */ -/***/ (function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8); - $export($export.G + $export.W + $export.F * !__webpack_require__(225).ABV, { - DataView: __webpack_require__(226).DataView - }); - - -/***/ }), -/* 229 */ -/***/ (function(module, exports, __webpack_require__) { - - __webpack_require__(230)('Int8', 1, function (init) { - return function Int8Array(data, byteOffset, length) { - return init(this, data, byteOffset, length); - }; - }); - - -/***/ }), -/* 230 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - if (__webpack_require__(6)) { - var LIBRARY = __webpack_require__(24); - var global = __webpack_require__(4); - var fails = __webpack_require__(7); - var $export = __webpack_require__(8); - var $typed = __webpack_require__(225); - var $buffer = __webpack_require__(226); - var ctx = __webpack_require__(20); - var anInstance = __webpack_require__(206); - var propertyDesc = __webpack_require__(17); - var hide = __webpack_require__(10); - var redefineAll = __webpack_require__(215); - var toInteger = __webpack_require__(38); - var toLength = __webpack_require__(37); - var toIndex = __webpack_require__(227); - var toAbsoluteIndex = __webpack_require__(39); - var toPrimitive = __webpack_require__(16); - var has = __webpack_require__(5); - var classof = __webpack_require__(74); - var isObject = __webpack_require__(13); - var toObject = __webpack_require__(57); - var isArrayIter = __webpack_require__(163); - var create = __webpack_require__(45); - var getPrototypeOf = __webpack_require__(58); - var gOPN = __webpack_require__(49).f; - var getIterFn = __webpack_require__(165); - var uid = __webpack_require__(19); - var wks = __webpack_require__(26); - var createArrayMethod = __webpack_require__(173); - var createArrayIncludes = __webpack_require__(36); - var speciesConstructor = __webpack_require__(208); - var ArrayIterators = __webpack_require__(194); - var Iterators = __webpack_require__(129); - var $iterDetect = __webpack_require__(166); - var setSpecies = __webpack_require__(193); - var arrayFill = __webpack_require__(189); - var arrayCopyWithin = __webpack_require__(186); - var $DP = __webpack_require__(11); - var $GOPD = __webpack_require__(50); - var dP = $DP.f; - var gOPD = $GOPD.f; - var RangeError = global.RangeError; - var TypeError = global.TypeError; - var Uint8Array = global.Uint8Array; - var ARRAY_BUFFER = 'ArrayBuffer'; - var SHARED_BUFFER = 'Shared' + ARRAY_BUFFER; - var BYTES_PER_ELEMENT = 'BYTES_PER_ELEMENT'; - var PROTOTYPE = 'prototype'; - var ArrayProto = Array[PROTOTYPE]; - var $ArrayBuffer = $buffer.ArrayBuffer; - var $DataView = $buffer.DataView; - var arrayForEach = createArrayMethod(0); - var arrayFilter = createArrayMethod(2); - var arraySome = createArrayMethod(3); - var arrayEvery = createArrayMethod(4); - var arrayFind = createArrayMethod(5); - var arrayFindIndex = createArrayMethod(6); - var arrayIncludes = createArrayIncludes(true); - var arrayIndexOf = createArrayIncludes(false); - var arrayValues = ArrayIterators.values; - var arrayKeys = ArrayIterators.keys; - var arrayEntries = ArrayIterators.entries; - var arrayLastIndexOf = ArrayProto.lastIndexOf; - var arrayReduce = ArrayProto.reduce; - var arrayReduceRight = ArrayProto.reduceRight; - var arrayJoin = ArrayProto.join; - var arraySort = ArrayProto.sort; - var arraySlice = ArrayProto.slice; - var arrayToString = ArrayProto.toString; - var arrayToLocaleString = ArrayProto.toLocaleString; - var ITERATOR = wks('iterator'); - var TAG = wks('toStringTag'); - var TYPED_CONSTRUCTOR = uid('typed_constructor'); - var DEF_CONSTRUCTOR = uid('def_constructor'); - var ALL_CONSTRUCTORS = $typed.CONSTR; - var TYPED_ARRAY = $typed.TYPED; - var VIEW = $typed.VIEW; - var WRONG_LENGTH = 'Wrong length!'; - - var $map = createArrayMethod(1, function (O, length) { - return allocate(speciesConstructor(O, O[DEF_CONSTRUCTOR]), length); - }); - - var LITTLE_ENDIAN = fails(function () { - // eslint-disable-next-line no-undef - return new Uint8Array(new Uint16Array([1]).buffer)[0] === 1; - }); - - var FORCED_SET = !!Uint8Array && !!Uint8Array[PROTOTYPE].set && fails(function () { - new Uint8Array(1).set({}); - }); - - var toOffset = function (it, BYTES) { - var offset = toInteger(it); - if (offset < 0 || offset % BYTES) throw RangeError('Wrong offset!'); - return offset; - }; - - var validate = function (it) { - if (isObject(it) && TYPED_ARRAY in it) return it; - throw TypeError(it + ' is not a typed array!'); - }; - - var allocate = function (C, length) { - if (!(isObject(C) && TYPED_CONSTRUCTOR in C)) { - throw TypeError('It is not a typed array constructor!'); - } return new C(length); - }; - - var speciesFromList = function (O, list) { - return fromList(speciesConstructor(O, O[DEF_CONSTRUCTOR]), list); - }; - - var fromList = function (C, list) { - var index = 0; - var length = list.length; - var result = allocate(C, length); - while (length > index) result[index] = list[index++]; - return result; - }; - - var addGetter = function (it, key, internal) { - dP(it, key, { get: function () { return this._d[internal]; } }); - }; - - var $from = function from(source /* , mapfn, thisArg */) { - var O = toObject(source); - var aLen = arguments.length; - var mapfn = aLen > 1 ? arguments[1] : undefined; - var mapping = mapfn !== undefined; - var iterFn = getIterFn(O); - var i, length, values, result, step, iterator; - if (iterFn != undefined && !isArrayIter(iterFn)) { - for (iterator = iterFn.call(O), values = [], i = 0; !(step = iterator.next()).done; i++) { - values.push(step.value); - } O = values; - } - if (mapping && aLen > 2) mapfn = ctx(mapfn, arguments[2], 2); - for (i = 0, length = toLength(O.length), result = allocate(this, length); length > i; i++) { - result[i] = mapping ? mapfn(O[i], i) : O[i]; - } - return result; - }; - - var $of = function of(/* ...items */) { - var index = 0; - var length = arguments.length; - var result = allocate(this, length); - while (length > index) result[index] = arguments[index++]; - return result; - }; - - // iOS Safari 6.x fails here - var TO_LOCALE_BUG = !!Uint8Array && fails(function () { arrayToLocaleString.call(new Uint8Array(1)); }); - - var $toLocaleString = function toLocaleString() { - return arrayToLocaleString.apply(TO_LOCALE_BUG ? arraySlice.call(validate(this)) : validate(this), arguments); - }; - - var proto = { - copyWithin: function copyWithin(target, start /* , end */) { - return arrayCopyWithin.call(validate(this), target, start, arguments.length > 2 ? arguments[2] : undefined); - }, - every: function every(callbackfn /* , thisArg */) { - return arrayEvery(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined); - }, - fill: function fill(value /* , start, end */) { // eslint-disable-line no-unused-vars - return arrayFill.apply(validate(this), arguments); - }, - filter: function filter(callbackfn /* , thisArg */) { - return speciesFromList(this, arrayFilter(validate(this), callbackfn, - arguments.length > 1 ? arguments[1] : undefined)); - }, - find: function find(predicate /* , thisArg */) { - return arrayFind(validate(this), predicate, arguments.length > 1 ? arguments[1] : undefined); - }, - findIndex: function findIndex(predicate /* , thisArg */) { - return arrayFindIndex(validate(this), predicate, arguments.length > 1 ? arguments[1] : undefined); - }, - forEach: function forEach(callbackfn /* , thisArg */) { - arrayForEach(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined); - }, - indexOf: function indexOf(searchElement /* , fromIndex */) { - return arrayIndexOf(validate(this), searchElement, arguments.length > 1 ? arguments[1] : undefined); - }, - includes: function includes(searchElement /* , fromIndex */) { - return arrayIncludes(validate(this), searchElement, arguments.length > 1 ? arguments[1] : undefined); - }, - join: function join(separator) { // eslint-disable-line no-unused-vars - return arrayJoin.apply(validate(this), arguments); - }, - lastIndexOf: function lastIndexOf(searchElement /* , fromIndex */) { // eslint-disable-line no-unused-vars - return arrayLastIndexOf.apply(validate(this), arguments); - }, - map: function map(mapfn /* , thisArg */) { - return $map(validate(this), mapfn, arguments.length > 1 ? arguments[1] : undefined); - }, - reduce: function reduce(callbackfn /* , initialValue */) { // eslint-disable-line no-unused-vars - return arrayReduce.apply(validate(this), arguments); - }, - reduceRight: function reduceRight(callbackfn /* , initialValue */) { // eslint-disable-line no-unused-vars - return arrayReduceRight.apply(validate(this), arguments); - }, - reverse: function reverse() { - var that = this; - var length = validate(that).length; - var middle = Math.floor(length / 2); - var index = 0; - var value; - while (index < middle) { - value = that[index]; - that[index++] = that[--length]; - that[length] = value; - } return that; - }, - some: function some(callbackfn /* , thisArg */) { - return arraySome(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined); - }, - sort: function sort(comparefn) { - return arraySort.call(validate(this), comparefn); - }, - subarray: function subarray(begin, end) { - var O = validate(this); - var length = O.length; - var $begin = toAbsoluteIndex(begin, length); - return new (speciesConstructor(O, O[DEF_CONSTRUCTOR]))( - O.buffer, - O.byteOffset + $begin * O.BYTES_PER_ELEMENT, - toLength((end === undefined ? length : toAbsoluteIndex(end, length)) - $begin) - ); - } - }; - - var $slice = function slice(start, end) { - return speciesFromList(this, arraySlice.call(validate(this), start, end)); - }; - - var $set = function set(arrayLike /* , offset */) { - validate(this); - var offset = toOffset(arguments[1], 1); - var length = this.length; - var src = toObject(arrayLike); - var len = toLength(src.length); - var index = 0; - if (len + offset > length) throw RangeError(WRONG_LENGTH); - while (index < len) this[offset + index] = src[index++]; - }; - - var $iterators = { - entries: function entries() { - return arrayEntries.call(validate(this)); - }, - keys: function keys() { - return arrayKeys.call(validate(this)); - }, - values: function values() { - return arrayValues.call(validate(this)); - } - }; - - var isTAIndex = function (target, key) { - return isObject(target) - && target[TYPED_ARRAY] - && typeof key != 'symbol' - && key in target - && String(+key) == String(key); - }; - var $getDesc = function getOwnPropertyDescriptor(target, key) { - return isTAIndex(target, key = toPrimitive(key, true)) - ? propertyDesc(2, target[key]) - : gOPD(target, key); - }; - var $setDesc = function defineProperty(target, key, desc) { - if (isTAIndex(target, key = toPrimitive(key, true)) - && isObject(desc) - && has(desc, 'value') - && !has(desc, 'get') - && !has(desc, 'set') - // TODO: add validation descriptor w/o calling accessors - && !desc.configurable - && (!has(desc, 'writable') || desc.writable) - && (!has(desc, 'enumerable') || desc.enumerable) - ) { - target[key] = desc.value; - return target; - } return dP(target, key, desc); - }; - - if (!ALL_CONSTRUCTORS) { - $GOPD.f = $getDesc; - $DP.f = $setDesc; - } - - $export($export.S + $export.F * !ALL_CONSTRUCTORS, 'Object', { - getOwnPropertyDescriptor: $getDesc, - defineProperty: $setDesc - }); - - if (fails(function () { arrayToString.call({}); })) { - arrayToString = arrayToLocaleString = function toString() { - return arrayJoin.call(this); - }; - } - - var $TypedArrayPrototype$ = redefineAll({}, proto); - redefineAll($TypedArrayPrototype$, $iterators); - hide($TypedArrayPrototype$, ITERATOR, $iterators.values); - redefineAll($TypedArrayPrototype$, { - slice: $slice, - set: $set, - constructor: function () { /* noop */ }, - toString: arrayToString, - toLocaleString: $toLocaleString - }); - addGetter($TypedArrayPrototype$, 'buffer', 'b'); - addGetter($TypedArrayPrototype$, 'byteOffset', 'o'); - addGetter($TypedArrayPrototype$, 'byteLength', 'l'); - addGetter($TypedArrayPrototype$, 'length', 'e'); - dP($TypedArrayPrototype$, TAG, { - get: function () { return this[TYPED_ARRAY]; } - }); - - // eslint-disable-next-line max-statements - module.exports = function (KEY, BYTES, wrapper, CLAMPED) { - CLAMPED = !!CLAMPED; - var NAME = KEY + (CLAMPED ? 'Clamped' : '') + 'Array'; - var GETTER = 'get' + KEY; - var SETTER = 'set' + KEY; - var TypedArray = global[NAME]; - var Base = TypedArray || {}; - var TAC = TypedArray && getPrototypeOf(TypedArray); - var FORCED = !TypedArray || !$typed.ABV; - var O = {}; - var TypedArrayPrototype = TypedArray && TypedArray[PROTOTYPE]; - var getter = function (that, index) { - var data = that._d; - return data.v[GETTER](index * BYTES + data.o, LITTLE_ENDIAN); - }; - var setter = function (that, index, value) { - var data = that._d; - if (CLAMPED) value = (value = Math.round(value)) < 0 ? 0 : value > 0xff ? 0xff : value & 0xff; - data.v[SETTER](index * BYTES + data.o, value, LITTLE_ENDIAN); - }; - var addElement = function (that, index) { - dP(that, index, { - get: function () { - return getter(this, index); - }, - set: function (value) { - return setter(this, index, value); - }, - enumerable: true - }); - }; - if (FORCED) { - TypedArray = wrapper(function (that, data, $offset, $length) { - anInstance(that, TypedArray, NAME, '_d'); - var index = 0; - var offset = 0; - var buffer, byteLength, length, klass; - if (!isObject(data)) { - length = toIndex(data); - byteLength = length * BYTES; - buffer = new $ArrayBuffer(byteLength); - } else if (data instanceof $ArrayBuffer || (klass = classof(data)) == ARRAY_BUFFER || klass == SHARED_BUFFER) { - buffer = data; - offset = toOffset($offset, BYTES); - var $len = data.byteLength; - if ($length === undefined) { - if ($len % BYTES) throw RangeError(WRONG_LENGTH); - byteLength = $len - offset; - if (byteLength < 0) throw RangeError(WRONG_LENGTH); - } else { - byteLength = toLength($length) * BYTES; - if (byteLength + offset > $len) throw RangeError(WRONG_LENGTH); - } - length = byteLength / BYTES; - } else if (TYPED_ARRAY in data) { - return fromList(TypedArray, data); - } else { - return $from.call(TypedArray, data); - } - hide(that, '_d', { - b: buffer, - o: offset, - l: byteLength, - e: length, - v: new $DataView(buffer) - }); - while (index < length) addElement(that, index++); - }); - TypedArrayPrototype = TypedArray[PROTOTYPE] = create($TypedArrayPrototype$); - hide(TypedArrayPrototype, 'constructor', TypedArray); - } else if (!fails(function () { - TypedArray(1); - }) || !fails(function () { - new TypedArray(-1); // eslint-disable-line no-new - }) || !$iterDetect(function (iter) { - new TypedArray(); // eslint-disable-line no-new - new TypedArray(null); // eslint-disable-line no-new - new TypedArray(1.5); // eslint-disable-line no-new - new TypedArray(iter); // eslint-disable-line no-new - }, true)) { - TypedArray = wrapper(function (that, data, $offset, $length) { - anInstance(that, TypedArray, NAME); - var klass; - // `ws` module bug, temporarily remove validation length for Uint8Array - // https://github.com/websockets/ws/pull/645 - if (!isObject(data)) return new Base(toIndex(data)); - if (data instanceof $ArrayBuffer || (klass = classof(data)) == ARRAY_BUFFER || klass == SHARED_BUFFER) { - return $length !== undefined - ? new Base(data, toOffset($offset, BYTES), $length) - : $offset !== undefined - ? new Base(data, toOffset($offset, BYTES)) - : new Base(data); - } - if (TYPED_ARRAY in data) return fromList(TypedArray, data); - return $from.call(TypedArray, data); - }); - arrayForEach(TAC !== Function.prototype ? gOPN(Base).concat(gOPN(TAC)) : gOPN(Base), function (key) { - if (!(key in TypedArray)) hide(TypedArray, key, Base[key]); - }); - TypedArray[PROTOTYPE] = TypedArrayPrototype; - if (!LIBRARY) TypedArrayPrototype.constructor = TypedArray; - } - var $nativeIterator = TypedArrayPrototype[ITERATOR]; - var CORRECT_ITER_NAME = !!$nativeIterator - && ($nativeIterator.name == 'values' || $nativeIterator.name == undefined); - var $iterator = $iterators.values; - hide(TypedArray, TYPED_CONSTRUCTOR, true); - hide(TypedArrayPrototype, TYPED_ARRAY, NAME); - hide(TypedArrayPrototype, VIEW, true); - hide(TypedArrayPrototype, DEF_CONSTRUCTOR, TypedArray); - - if (CLAMPED ? new TypedArray(1)[TAG] != NAME : !(TAG in TypedArrayPrototype)) { - dP(TypedArrayPrototype, TAG, { - get: function () { return NAME; } - }); - } - - O[NAME] = TypedArray; - - $export($export.G + $export.W + $export.F * (TypedArray != Base), O); - - $export($export.S, NAME, { - BYTES_PER_ELEMENT: BYTES - }); - - $export($export.S + $export.F * fails(function () { Base.of.call(TypedArray, 1); }), NAME, { - from: $from, - of: $of - }); - - if (!(BYTES_PER_ELEMENT in TypedArrayPrototype)) hide(TypedArrayPrototype, BYTES_PER_ELEMENT, BYTES); - - $export($export.P, NAME, proto); - - setSpecies(NAME); - - $export($export.P + $export.F * FORCED_SET, NAME, { set: $set }); - - $export($export.P + $export.F * !CORRECT_ITER_NAME, NAME, $iterators); - - if (!LIBRARY && TypedArrayPrototype.toString != arrayToString) TypedArrayPrototype.toString = arrayToString; - - $export($export.P + $export.F * fails(function () { - new TypedArray(1).slice(); - }), NAME, { slice: $slice }); - - $export($export.P + $export.F * (fails(function () { - return [1, 2].toLocaleString() != new TypedArray([1, 2]).toLocaleString(); - }) || !fails(function () { - TypedArrayPrototype.toLocaleString.call([1, 2]); - })), NAME, { toLocaleString: $toLocaleString }); - - Iterators[NAME] = CORRECT_ITER_NAME ? $nativeIterator : $iterator; - if (!LIBRARY && !CORRECT_ITER_NAME) hide(TypedArrayPrototype, ITERATOR, $iterator); - }; - } else module.exports = function () { /* empty */ }; - - -/***/ }), -/* 231 */ -/***/ (function(module, exports, __webpack_require__) { - - __webpack_require__(230)('Uint8', 1, function (init) { - return function Uint8Array(data, byteOffset, length) { - return init(this, data, byteOffset, length); - }; - }); - - -/***/ }), -/* 232 */ -/***/ (function(module, exports, __webpack_require__) { - - __webpack_require__(230)('Uint8', 1, function (init) { - return function Uint8ClampedArray(data, byteOffset, length) { - return init(this, data, byteOffset, length); - }; - }, true); - - -/***/ }), -/* 233 */ -/***/ (function(module, exports, __webpack_require__) { - - __webpack_require__(230)('Int16', 2, function (init) { - return function Int16Array(data, byteOffset, length) { - return init(this, data, byteOffset, length); - }; - }); - - -/***/ }), -/* 234 */ -/***/ (function(module, exports, __webpack_require__) { - - __webpack_require__(230)('Uint16', 2, function (init) { - return function Uint16Array(data, byteOffset, length) { - return init(this, data, byteOffset, length); - }; - }); - - -/***/ }), -/* 235 */ -/***/ (function(module, exports, __webpack_require__) { - - __webpack_require__(230)('Int32', 4, function (init) { - return function Int32Array(data, byteOffset, length) { - return init(this, data, byteOffset, length); - }; - }); - - -/***/ }), -/* 236 */ -/***/ (function(module, exports, __webpack_require__) { - - __webpack_require__(230)('Uint32', 4, function (init) { - return function Uint32Array(data, byteOffset, length) { - return init(this, data, byteOffset, length); - }; - }); - - -/***/ }), -/* 237 */ -/***/ (function(module, exports, __webpack_require__) { - - __webpack_require__(230)('Float32', 4, function (init) { - return function Float32Array(data, byteOffset, length) { - return init(this, data, byteOffset, length); - }; - }); - - -/***/ }), -/* 238 */ -/***/ (function(module, exports, __webpack_require__) { - - __webpack_require__(230)('Float64', 8, function (init) { - return function Float64Array(data, byteOffset, length) { - return init(this, data, byteOffset, length); - }; - }); - - -/***/ }), -/* 239 */ -/***/ (function(module, exports, __webpack_require__) { - - // 26.1.1 Reflect.apply(target, thisArgument, argumentsList) - var $export = __webpack_require__(8); - var aFunction = __webpack_require__(21); - var anObject = __webpack_require__(12); - var rApply = (__webpack_require__(4).Reflect || {}).apply; - var fApply = Function.apply; - // MS Edge argumentsList argument is optional - $export($export.S + $export.F * !__webpack_require__(7)(function () { - rApply(function () { /* empty */ }); - }), 'Reflect', { - apply: function apply(target, thisArgument, argumentsList) { - var T = aFunction(target); - var L = anObject(argumentsList); - return rApply ? rApply(T, thisArgument, L) : fApply.call(T, thisArgument, L); - } - }); - - -/***/ }), -/* 240 */ -/***/ (function(module, exports, __webpack_require__) { - - // 26.1.2 Reflect.construct(target, argumentsList [, newTarget]) - var $export = __webpack_require__(8); - var create = __webpack_require__(45); - var aFunction = __webpack_require__(21); - var anObject = __webpack_require__(12); - var isObject = __webpack_require__(13); - var fails = __webpack_require__(7); - var bind = __webpack_require__(76); - var rConstruct = (__webpack_require__(4).Reflect || {}).construct; - - // MS Edge supports only 2 arguments and argumentsList argument is optional - // FF Nightly sets third argument as `new.target`, but does not create `this` from it - var NEW_TARGET_BUG = fails(function () { - function F() { /* empty */ } - return !(rConstruct(function () { /* empty */ }, [], F) instanceof F); - }); - var ARGS_BUG = !fails(function () { - rConstruct(function () { /* empty */ }); - }); - - $export($export.S + $export.F * (NEW_TARGET_BUG || ARGS_BUG), 'Reflect', { - construct: function construct(Target, args /* , newTarget */) { - aFunction(Target); - anObject(args); - var newTarget = arguments.length < 3 ? Target : aFunction(arguments[2]); - if (ARGS_BUG && !NEW_TARGET_BUG) return rConstruct(Target, args, newTarget); - if (Target == newTarget) { - // w/o altered newTarget, optimization for 0-4 arguments - switch (args.length) { - case 0: return new Target(); - case 1: return new Target(args[0]); - case 2: return new Target(args[0], args[1]); - case 3: return new Target(args[0], args[1], args[2]); - case 4: return new Target(args[0], args[1], args[2], args[3]); - } - // w/o altered newTarget, lot of arguments case - var $args = [null]; - $args.push.apply($args, args); - return new (bind.apply(Target, $args))(); - } - // with altered newTarget, not support built-in constructors - var proto = newTarget.prototype; - var instance = create(isObject(proto) ? proto : Object.prototype); - var result = Function.apply.call(Target, instance, args); - return isObject(result) ? result : instance; - } - }); - - -/***/ }), -/* 241 */ -/***/ (function(module, exports, __webpack_require__) { - - // 26.1.3 Reflect.defineProperty(target, propertyKey, attributes) - var dP = __webpack_require__(11); - var $export = __webpack_require__(8); - var anObject = __webpack_require__(12); - var toPrimitive = __webpack_require__(16); - - // MS Edge has broken Reflect.defineProperty - throwing instead of returning false - $export($export.S + $export.F * __webpack_require__(7)(function () { - // eslint-disable-next-line no-undef - Reflect.defineProperty(dP.f({}, 1, { value: 1 }), 1, { value: 2 }); - }), 'Reflect', { - defineProperty: function defineProperty(target, propertyKey, attributes) { - anObject(target); - propertyKey = toPrimitive(propertyKey, true); - anObject(attributes); - try { - dP.f(target, propertyKey, attributes); - return true; - } catch (e) { - return false; - } - } - }); - - -/***/ }), -/* 242 */ -/***/ (function(module, exports, __webpack_require__) { - - // 26.1.4 Reflect.deleteProperty(target, propertyKey) - var $export = __webpack_require__(8); - var gOPD = __webpack_require__(50).f; - var anObject = __webpack_require__(12); - - $export($export.S, 'Reflect', { - deleteProperty: function deleteProperty(target, propertyKey) { - var desc = gOPD(anObject(target), propertyKey); - return desc && !desc.configurable ? false : delete target[propertyKey]; - } - }); - - -/***/ }), -/* 243 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // 26.1.5 Reflect.enumerate(target) - var $export = __webpack_require__(8); - var anObject = __webpack_require__(12); - var Enumerate = function (iterated) { - this._t = anObject(iterated); // target - this._i = 0; // next index - var keys = this._k = []; // keys - var key; - for (key in iterated) keys.push(key); - }; - __webpack_require__(130)(Enumerate, 'Object', function () { - var that = this; - var keys = that._k; - var key; - do { - if (that._i >= keys.length) return { value: undefined, done: true }; - } while (!((key = keys[that._i++]) in that._t)); - return { value: key, done: false }; - }); - - $export($export.S, 'Reflect', { - enumerate: function enumerate(target) { - return new Enumerate(target); - } - }); - - -/***/ }), -/* 244 */ -/***/ (function(module, exports, __webpack_require__) { - - // 26.1.6 Reflect.get(target, propertyKey [, receiver]) - var gOPD = __webpack_require__(50); - var getPrototypeOf = __webpack_require__(58); - var has = __webpack_require__(5); - var $export = __webpack_require__(8); - var isObject = __webpack_require__(13); - var anObject = __webpack_require__(12); - - function get(target, propertyKey /* , receiver */) { - var receiver = arguments.length < 3 ? target : arguments[2]; - var desc, proto; - if (anObject(target) === receiver) return target[propertyKey]; - if (desc = gOPD.f(target, propertyKey)) return has(desc, 'value') - ? desc.value - : desc.get !== undefined - ? desc.get.call(receiver) - : undefined; - if (isObject(proto = getPrototypeOf(target))) return get(proto, propertyKey, receiver); - } - - $export($export.S, 'Reflect', { get: get }); - - -/***/ }), -/* 245 */ -/***/ (function(module, exports, __webpack_require__) { - - // 26.1.7 Reflect.getOwnPropertyDescriptor(target, propertyKey) - var gOPD = __webpack_require__(50); - var $export = __webpack_require__(8); - var anObject = __webpack_require__(12); - - $export($export.S, 'Reflect', { - getOwnPropertyDescriptor: function getOwnPropertyDescriptor(target, propertyKey) { - return gOPD.f(anObject(target), propertyKey); - } - }); - - -/***/ }), -/* 246 */ -/***/ (function(module, exports, __webpack_require__) { - - // 26.1.8 Reflect.getPrototypeOf(target) - var $export = __webpack_require__(8); - var getProto = __webpack_require__(58); - var anObject = __webpack_require__(12); - - $export($export.S, 'Reflect', { - getPrototypeOf: function getPrototypeOf(target) { - return getProto(anObject(target)); - } - }); - - -/***/ }), -/* 247 */ -/***/ (function(module, exports, __webpack_require__) { - - // 26.1.9 Reflect.has(target, propertyKey) - var $export = __webpack_require__(8); - - $export($export.S, 'Reflect', { - has: function has(target, propertyKey) { - return propertyKey in target; - } - }); - - -/***/ }), -/* 248 */ -/***/ (function(module, exports, __webpack_require__) { - - // 26.1.10 Reflect.isExtensible(target) - var $export = __webpack_require__(8); - var anObject = __webpack_require__(12); - var $isExtensible = Object.isExtensible; - - $export($export.S, 'Reflect', { - isExtensible: function isExtensible(target) { - anObject(target); - return $isExtensible ? $isExtensible(target) : true; - } - }); - - -/***/ }), -/* 249 */ -/***/ (function(module, exports, __webpack_require__) { - - // 26.1.11 Reflect.ownKeys(target) - var $export = __webpack_require__(8); - - $export($export.S, 'Reflect', { ownKeys: __webpack_require__(250) }); - - -/***/ }), -/* 250 */ -/***/ (function(module, exports, __webpack_require__) { - - // all object keys, includes non-enumerable and symbols - var gOPN = __webpack_require__(49); - var gOPS = __webpack_require__(42); - var anObject = __webpack_require__(12); - var Reflect = __webpack_require__(4).Reflect; - module.exports = Reflect && Reflect.ownKeys || function ownKeys(it) { - var keys = gOPN.f(anObject(it)); - var getSymbols = gOPS.f; - return getSymbols ? keys.concat(getSymbols(it)) : keys; - }; - - -/***/ }), -/* 251 */ -/***/ (function(module, exports, __webpack_require__) { - - // 26.1.12 Reflect.preventExtensions(target) - var $export = __webpack_require__(8); - var anObject = __webpack_require__(12); - var $preventExtensions = Object.preventExtensions; - - $export($export.S, 'Reflect', { - preventExtensions: function preventExtensions(target) { - anObject(target); - try { - if ($preventExtensions) $preventExtensions(target); - return true; - } catch (e) { - return false; - } - } - }); - - -/***/ }), -/* 252 */ -/***/ (function(module, exports, __webpack_require__) { - - // 26.1.13 Reflect.set(target, propertyKey, V [, receiver]) - var dP = __webpack_require__(11); - var gOPD = __webpack_require__(50); - var getPrototypeOf = __webpack_require__(58); - var has = __webpack_require__(5); - var $export = __webpack_require__(8); - var createDesc = __webpack_require__(17); - var anObject = __webpack_require__(12); - var isObject = __webpack_require__(13); - - function set(target, propertyKey, V /* , receiver */) { - var receiver = arguments.length < 4 ? target : arguments[3]; - var ownDesc = gOPD.f(anObject(target), propertyKey); - var existingDescriptor, proto; - if (!ownDesc) { - if (isObject(proto = getPrototypeOf(target))) { - return set(proto, propertyKey, V, receiver); - } - ownDesc = createDesc(0); - } - if (has(ownDesc, 'value')) { - if (ownDesc.writable === false || !isObject(receiver)) return false; - if (existingDescriptor = gOPD.f(receiver, propertyKey)) { - if (existingDescriptor.get || existingDescriptor.set || existingDescriptor.writable === false) return false; - existingDescriptor.value = V; - dP.f(receiver, propertyKey, existingDescriptor); - } else dP.f(receiver, propertyKey, createDesc(0, V)); - return true; - } - return ownDesc.set === undefined ? false : (ownDesc.set.call(receiver, V), true); - } - - $export($export.S, 'Reflect', { set: set }); - - -/***/ }), -/* 253 */ -/***/ (function(module, exports, __webpack_require__) { - - // 26.1.14 Reflect.setPrototypeOf(target, proto) - var $export = __webpack_require__(8); - var setProto = __webpack_require__(72); - - if (setProto) $export($export.S, 'Reflect', { - setPrototypeOf: function setPrototypeOf(target, proto) { - setProto.check(target, proto); - try { - setProto.set(target, proto); - return true; - } catch (e) { - return false; - } - } - }); - - -/***/ }), -/* 254 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // https://github.com/tc39/Array.prototype.includes - var $export = __webpack_require__(8); - var $includes = __webpack_require__(36)(true); - - $export($export.P, 'Array', { - includes: function includes(el /* , fromIndex = 0 */) { - return $includes(this, el, arguments.length > 1 ? arguments[1] : undefined); - } - }); - - __webpack_require__(187)('includes'); - - -/***/ }), -/* 255 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // https://tc39.github.io/proposal-flatMap/#sec-Array.prototype.flatMap - var $export = __webpack_require__(8); - var flattenIntoArray = __webpack_require__(256); - var toObject = __webpack_require__(57); - var toLength = __webpack_require__(37); - var aFunction = __webpack_require__(21); - var arraySpeciesCreate = __webpack_require__(174); - - $export($export.P, 'Array', { - flatMap: function flatMap(callbackfn /* , thisArg */) { - var O = toObject(this); - var sourceLen, A; - aFunction(callbackfn); - sourceLen = toLength(O.length); - A = arraySpeciesCreate(O, 0); - flattenIntoArray(A, O, O, sourceLen, 0, 1, callbackfn, arguments[1]); - return A; - } - }); - - __webpack_require__(187)('flatMap'); - - -/***/ }), -/* 256 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // https://tc39.github.io/proposal-flatMap/#sec-FlattenIntoArray - var isArray = __webpack_require__(44); - var isObject = __webpack_require__(13); - var toLength = __webpack_require__(37); - var ctx = __webpack_require__(20); - var IS_CONCAT_SPREADABLE = __webpack_require__(26)('isConcatSpreadable'); - - function flattenIntoArray(target, original, source, sourceLen, start, depth, mapper, thisArg) { - var targetIndex = start; - var sourceIndex = 0; - var mapFn = mapper ? ctx(mapper, thisArg, 3) : false; - var element, spreadable; - - while (sourceIndex < sourceLen) { - if (sourceIndex in source) { - element = mapFn ? mapFn(source[sourceIndex], sourceIndex, original) : source[sourceIndex]; - - spreadable = false; - if (isObject(element)) { - spreadable = element[IS_CONCAT_SPREADABLE]; - spreadable = spreadable !== undefined ? !!spreadable : isArray(element); - } - - if (spreadable && depth > 0) { - targetIndex = flattenIntoArray(target, original, element, toLength(element.length), targetIndex, depth - 1) - 1; - } else { - if (targetIndex >= 0x1fffffffffffff) throw TypeError(); - target[targetIndex] = element; - } - - targetIndex++; - } - sourceIndex++; - } - return targetIndex; - } - - module.exports = flattenIntoArray; - - -/***/ }), -/* 257 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // https://tc39.github.io/proposal-flatMap/#sec-Array.prototype.flatten - var $export = __webpack_require__(8); - var flattenIntoArray = __webpack_require__(256); - var toObject = __webpack_require__(57); - var toLength = __webpack_require__(37); - var toInteger = __webpack_require__(38); - var arraySpeciesCreate = __webpack_require__(174); - - $export($export.P, 'Array', { - flatten: function flatten(/* depthArg = 1 */) { - var depthArg = arguments[0]; - var O = toObject(this); - var sourceLen = toLength(O.length); - var A = arraySpeciesCreate(O, 0); - flattenIntoArray(A, O, O, sourceLen, 0, depthArg === undefined ? 1 : toInteger(depthArg)); - return A; - } - }); - - __webpack_require__(187)('flatten'); - - -/***/ }), -/* 258 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // https://github.com/mathiasbynens/String.prototype.at - var $export = __webpack_require__(8); - var $at = __webpack_require__(127)(true); - - $export($export.P, 'String', { - at: function at(pos) { - return $at(this, pos); - } - }); - - -/***/ }), -/* 259 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // https://github.com/tc39/proposal-string-pad-start-end - var $export = __webpack_require__(8); - var $pad = __webpack_require__(260); - var userAgent = __webpack_require__(213); - - // https://github.com/zloirock/core-js/issues/280 - $export($export.P + $export.F * /Version\/10\.\d+(\.\d+)? Safari\//.test(userAgent), 'String', { - padStart: function padStart(maxLength /* , fillString = ' ' */) { - return $pad(this, maxLength, arguments.length > 1 ? arguments[1] : undefined, true); - } - }); - - -/***/ }), -/* 260 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://github.com/tc39/proposal-string-pad-start-end - var toLength = __webpack_require__(37); - var repeat = __webpack_require__(90); - var defined = __webpack_require__(35); - - module.exports = function (that, maxLength, fillString, left) { - var S = String(defined(that)); - var stringLength = S.length; - var fillStr = fillString === undefined ? ' ' : String(fillString); - var intMaxLength = toLength(maxLength); - if (intMaxLength <= stringLength || fillStr == '') return S; - var fillLen = intMaxLength - stringLength; - var stringFiller = repeat.call(fillStr, Math.ceil(fillLen / fillStr.length)); - if (stringFiller.length > fillLen) stringFiller = stringFiller.slice(0, fillLen); - return left ? stringFiller + S : S + stringFiller; - }; - - -/***/ }), -/* 261 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // https://github.com/tc39/proposal-string-pad-start-end - var $export = __webpack_require__(8); - var $pad = __webpack_require__(260); - var userAgent = __webpack_require__(213); - - // https://github.com/zloirock/core-js/issues/280 - $export($export.P + $export.F * /Version\/10\.\d+(\.\d+)? Safari\//.test(userAgent), 'String', { - padEnd: function padEnd(maxLength /* , fillString = ' ' */) { - return $pad(this, maxLength, arguments.length > 1 ? arguments[1] : undefined, false); - } - }); - - -/***/ }), -/* 262 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // https://github.com/sebmarkbage/ecmascript-string-left-right-trim - __webpack_require__(82)('trimLeft', function ($trim) { - return function trimLeft() { - return $trim(this, 1); - }; - }, 'trimStart'); - - -/***/ }), -/* 263 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // https://github.com/sebmarkbage/ecmascript-string-left-right-trim - __webpack_require__(82)('trimRight', function ($trim) { - return function trimRight() { - return $trim(this, 2); - }; - }, 'trimEnd'); - - -/***/ }), -/* 264 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // https://tc39.github.io/String.prototype.matchAll/ - var $export = __webpack_require__(8); - var defined = __webpack_require__(35); - var toLength = __webpack_require__(37); - var isRegExp = __webpack_require__(134); - var getFlags = __webpack_require__(197); - var RegExpProto = RegExp.prototype; - - var $RegExpStringIterator = function (regexp, string) { - this._r = regexp; - this._s = string; - }; - - __webpack_require__(130)($RegExpStringIterator, 'RegExp String', function next() { - var match = this._r.exec(this._s); - return { value: match, done: match === null }; - }); - - $export($export.P, 'String', { - matchAll: function matchAll(regexp) { - defined(this); - if (!isRegExp(regexp)) throw TypeError(regexp + ' is not a regexp!'); - var S = String(this); - var flags = 'flags' in RegExpProto ? String(regexp.flags) : getFlags.call(regexp); - var rx = new RegExp(regexp.source, ~flags.indexOf('g') ? flags : 'g' + flags); - rx.lastIndex = toLength(regexp.lastIndex); - return new $RegExpStringIterator(rx, S); - } - }); - - -/***/ }), -/* 265 */ -/***/ (function(module, exports, __webpack_require__) { - - __webpack_require__(28)('asyncIterator'); - - -/***/ }), -/* 266 */ -/***/ (function(module, exports, __webpack_require__) { - - __webpack_require__(28)('observable'); - - -/***/ }), -/* 267 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://github.com/tc39/proposal-object-getownpropertydescriptors - var $export = __webpack_require__(8); - var ownKeys = __webpack_require__(250); - var toIObject = __webpack_require__(32); - var gOPD = __webpack_require__(50); - var createProperty = __webpack_require__(164); - - $export($export.S, 'Object', { - getOwnPropertyDescriptors: function getOwnPropertyDescriptors(object) { - var O = toIObject(object); - var getDesc = gOPD.f; - var keys = ownKeys(O); - var result = {}; - var i = 0; - var key, desc; - while (keys.length > i) { - desc = getDesc(O, key = keys[i++]); - if (desc !== undefined) createProperty(result, key, desc); - } - return result; - } - }); - - -/***/ }), -/* 268 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://github.com/tc39/proposal-object-values-entries - var $export = __webpack_require__(8); - var $values = __webpack_require__(269)(false); - - $export($export.S, 'Object', { - values: function values(it) { - return $values(it); - } - }); - - -/***/ }), -/* 269 */ -/***/ (function(module, exports, __webpack_require__) { - - var getKeys = __webpack_require__(30); - var toIObject = __webpack_require__(32); - var isEnum = __webpack_require__(43).f; - module.exports = function (isEntries) { - return function (it) { - var O = toIObject(it); - var keys = getKeys(O); - var length = keys.length; - var i = 0; - var result = []; - var key; - while (length > i) if (isEnum.call(O, key = keys[i++])) { - result.push(isEntries ? [key, O[key]] : O[key]); - } return result; - }; - }; - - -/***/ }), -/* 270 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://github.com/tc39/proposal-object-values-entries - var $export = __webpack_require__(8); - var $entries = __webpack_require__(269)(true); - - $export($export.S, 'Object', { - entries: function entries(it) { - return $entries(it); - } - }); - - -/***/ }), -/* 271 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var toObject = __webpack_require__(57); - var aFunction = __webpack_require__(21); - var $defineProperty = __webpack_require__(11); - - // B.2.2.2 Object.prototype.__defineGetter__(P, getter) - __webpack_require__(6) && $export($export.P + __webpack_require__(272), 'Object', { - __defineGetter__: function __defineGetter__(P, getter) { - $defineProperty.f(toObject(this), P, { get: aFunction(getter), enumerable: true, configurable: true }); - } - }); - - -/***/ }), -/* 272 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // Forced replacement prototype accessors methods - module.exports = __webpack_require__(24) || !__webpack_require__(7)(function () { - var K = Math.random(); - // In FF throws only define methods - // eslint-disable-next-line no-undef, no-useless-call - __defineSetter__.call(null, K, function () { /* empty */ }); - delete __webpack_require__(4)[K]; - }); - - -/***/ }), -/* 273 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var toObject = __webpack_require__(57); - var aFunction = __webpack_require__(21); - var $defineProperty = __webpack_require__(11); - - // B.2.2.3 Object.prototype.__defineSetter__(P, setter) - __webpack_require__(6) && $export($export.P + __webpack_require__(272), 'Object', { - __defineSetter__: function __defineSetter__(P, setter) { - $defineProperty.f(toObject(this), P, { set: aFunction(setter), enumerable: true, configurable: true }); - } - }); - - -/***/ }), -/* 274 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var toObject = __webpack_require__(57); - var toPrimitive = __webpack_require__(16); - var getPrototypeOf = __webpack_require__(58); - var getOwnPropertyDescriptor = __webpack_require__(50).f; - - // B.2.2.4 Object.prototype.__lookupGetter__(P) - __webpack_require__(6) && $export($export.P + __webpack_require__(272), 'Object', { - __lookupGetter__: function __lookupGetter__(P) { - var O = toObject(this); - var K = toPrimitive(P, true); - var D; - do { - if (D = getOwnPropertyDescriptor(O, K)) return D.get; - } while (O = getPrototypeOf(O)); - } - }); - - -/***/ }), -/* 275 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - var $export = __webpack_require__(8); - var toObject = __webpack_require__(57); - var toPrimitive = __webpack_require__(16); - var getPrototypeOf = __webpack_require__(58); - var getOwnPropertyDescriptor = __webpack_require__(50).f; - - // B.2.2.5 Object.prototype.__lookupSetter__(P) - __webpack_require__(6) && $export($export.P + __webpack_require__(272), 'Object', { - __lookupSetter__: function __lookupSetter__(P) { - var O = toObject(this); - var K = toPrimitive(P, true); - var D; - do { - if (D = getOwnPropertyDescriptor(O, K)) return D.set; - } while (O = getPrototypeOf(O)); - } - }); - - -/***/ }), -/* 276 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://github.com/DavidBruant/Map-Set.prototype.toJSON - var $export = __webpack_require__(8); - - $export($export.P + $export.R, 'Map', { toJSON: __webpack_require__(277)('Map') }); - - -/***/ }), -/* 277 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://github.com/DavidBruant/Map-Set.prototype.toJSON - var classof = __webpack_require__(74); - var from = __webpack_require__(278); - module.exports = function (NAME) { - return function toJSON() { - if (classof(this) != NAME) throw TypeError(NAME + "#toJSON isn't generic"); - return from(this); - }; - }; - - -/***/ }), -/* 278 */ -/***/ (function(module, exports, __webpack_require__) { - - var forOf = __webpack_require__(207); - - module.exports = function (iter, ITERATOR) { - var result = []; - forOf(iter, false, result.push, result, ITERATOR); - return result; - }; - - -/***/ }), -/* 279 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://github.com/DavidBruant/Map-Set.prototype.toJSON - var $export = __webpack_require__(8); - - $export($export.P + $export.R, 'Set', { toJSON: __webpack_require__(277)('Set') }); - - -/***/ }), -/* 280 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://tc39.github.io/proposal-setmap-offrom/#sec-map.of - __webpack_require__(281)('Map'); - - -/***/ }), -/* 281 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // https://tc39.github.io/proposal-setmap-offrom/ - var $export = __webpack_require__(8); - - module.exports = function (COLLECTION) { - $export($export.S, COLLECTION, { of: function of() { - var length = arguments.length; - var A = new Array(length); - while (length--) A[length] = arguments[length]; - return new this(A); - } }); - }; - - -/***/ }), -/* 282 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://tc39.github.io/proposal-setmap-offrom/#sec-set.of - __webpack_require__(281)('Set'); - - -/***/ }), -/* 283 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://tc39.github.io/proposal-setmap-offrom/#sec-weakmap.of - __webpack_require__(281)('WeakMap'); - - -/***/ }), -/* 284 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://tc39.github.io/proposal-setmap-offrom/#sec-weakset.of - __webpack_require__(281)('WeakSet'); - - -/***/ }), -/* 285 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://tc39.github.io/proposal-setmap-offrom/#sec-map.from - __webpack_require__(286)('Map'); - - -/***/ }), -/* 286 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // https://tc39.github.io/proposal-setmap-offrom/ - var $export = __webpack_require__(8); - var aFunction = __webpack_require__(21); - var ctx = __webpack_require__(20); - var forOf = __webpack_require__(207); - - module.exports = function (COLLECTION) { - $export($export.S, COLLECTION, { from: function from(source /* , mapFn, thisArg */) { - var mapFn = arguments[1]; - var mapping, A, n, cb; - aFunction(this); - mapping = mapFn !== undefined; - if (mapping) aFunction(mapFn); - if (source == undefined) return new this(); - A = []; - if (mapping) { - n = 0; - cb = ctx(mapFn, arguments[2], 2); - forOf(source, false, function (nextItem) { - A.push(cb(nextItem, n++)); - }); - } else { - forOf(source, false, A.push, A); - } - return new this(A); - } }); - }; - - -/***/ }), -/* 287 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://tc39.github.io/proposal-setmap-offrom/#sec-set.from - __webpack_require__(286)('Set'); - - -/***/ }), -/* 288 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://tc39.github.io/proposal-setmap-offrom/#sec-weakmap.from - __webpack_require__(286)('WeakMap'); - - -/***/ }), -/* 289 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://tc39.github.io/proposal-setmap-offrom/#sec-weakset.from - __webpack_require__(286)('WeakSet'); - - -/***/ }), -/* 290 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://github.com/tc39/proposal-global - var $export = __webpack_require__(8); - - $export($export.G, { global: __webpack_require__(4) }); - - -/***/ }), -/* 291 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://github.com/tc39/proposal-global - var $export = __webpack_require__(8); - - $export($export.S, 'System', { global: __webpack_require__(4) }); - - -/***/ }), -/* 292 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://github.com/ljharb/proposal-is-error - var $export = __webpack_require__(8); - var cof = __webpack_require__(34); - - $export($export.S, 'Error', { - isError: function isError(it) { - return cof(it) === 'Error'; - } - }); - - -/***/ }), -/* 293 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://rwaldron.github.io/proposal-math-extensions/ - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { - clamp: function clamp(x, lower, upper) { - return Math.min(upper, Math.max(lower, x)); - } - }); - - -/***/ }), -/* 294 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://rwaldron.github.io/proposal-math-extensions/ - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { DEG_PER_RAD: Math.PI / 180 }); - - -/***/ }), -/* 295 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://rwaldron.github.io/proposal-math-extensions/ - var $export = __webpack_require__(8); - var RAD_PER_DEG = 180 / Math.PI; - - $export($export.S, 'Math', { - degrees: function degrees(radians) { - return radians * RAD_PER_DEG; - } - }); - - -/***/ }), -/* 296 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://rwaldron.github.io/proposal-math-extensions/ - var $export = __webpack_require__(8); - var scale = __webpack_require__(297); - var fround = __webpack_require__(113); - - $export($export.S, 'Math', { - fscale: function fscale(x, inLow, inHigh, outLow, outHigh) { - return fround(scale(x, inLow, inHigh, outLow, outHigh)); - } - }); - - -/***/ }), -/* 297 */ -/***/ (function(module, exports) { - - // https://rwaldron.github.io/proposal-math-extensions/ - module.exports = Math.scale || function scale(x, inLow, inHigh, outLow, outHigh) { - if ( - arguments.length === 0 - // eslint-disable-next-line no-self-compare - || x != x - // eslint-disable-next-line no-self-compare - || inLow != inLow - // eslint-disable-next-line no-self-compare - || inHigh != inHigh - // eslint-disable-next-line no-self-compare - || outLow != outLow - // eslint-disable-next-line no-self-compare - || outHigh != outHigh - ) return NaN; - if (x === Infinity || x === -Infinity) return x; - return (x - inLow) * (outHigh - outLow) / (inHigh - inLow) + outLow; - }; - - -/***/ }), -/* 298 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://gist.github.com/BrendanEich/4294d5c212a6d2254703 - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { - iaddh: function iaddh(x0, x1, y0, y1) { - var $x0 = x0 >>> 0; - var $x1 = x1 >>> 0; - var $y0 = y0 >>> 0; - return $x1 + (y1 >>> 0) + (($x0 & $y0 | ($x0 | $y0) & ~($x0 + $y0 >>> 0)) >>> 31) | 0; - } - }); - - -/***/ }), -/* 299 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://gist.github.com/BrendanEich/4294d5c212a6d2254703 - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { - isubh: function isubh(x0, x1, y0, y1) { - var $x0 = x0 >>> 0; - var $x1 = x1 >>> 0; - var $y0 = y0 >>> 0; - return $x1 - (y1 >>> 0) - ((~$x0 & $y0 | ~($x0 ^ $y0) & $x0 - $y0 >>> 0) >>> 31) | 0; - } - }); - - -/***/ }), -/* 300 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://gist.github.com/BrendanEich/4294d5c212a6d2254703 - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { - imulh: function imulh(u, v) { - var UINT16 = 0xffff; - var $u = +u; - var $v = +v; - var u0 = $u & UINT16; - var v0 = $v & UINT16; - var u1 = $u >> 16; - var v1 = $v >> 16; - var t = (u1 * v0 >>> 0) + (u0 * v0 >>> 16); - return u1 * v1 + (t >> 16) + ((u0 * v1 >>> 0) + (t & UINT16) >> 16); - } - }); - - -/***/ }), -/* 301 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://rwaldron.github.io/proposal-math-extensions/ - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { RAD_PER_DEG: 180 / Math.PI }); - - -/***/ }), -/* 302 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://rwaldron.github.io/proposal-math-extensions/ - var $export = __webpack_require__(8); - var DEG_PER_RAD = Math.PI / 180; - - $export($export.S, 'Math', { - radians: function radians(degrees) { - return degrees * DEG_PER_RAD; - } - }); - - -/***/ }), -/* 303 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://rwaldron.github.io/proposal-math-extensions/ - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { scale: __webpack_require__(297) }); - - -/***/ }), -/* 304 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://gist.github.com/BrendanEich/4294d5c212a6d2254703 - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { - umulh: function umulh(u, v) { - var UINT16 = 0xffff; - var $u = +u; - var $v = +v; - var u0 = $u & UINT16; - var v0 = $v & UINT16; - var u1 = $u >>> 16; - var v1 = $v >>> 16; - var t = (u1 * v0 >>> 0) + (u0 * v0 >>> 16); - return u1 * v1 + (t >>> 16) + ((u0 * v1 >>> 0) + (t & UINT16) >>> 16); - } - }); - - -/***/ }), -/* 305 */ -/***/ (function(module, exports, __webpack_require__) { - - // http://jfbastien.github.io/papers/Math.signbit.html - var $export = __webpack_require__(8); - - $export($export.S, 'Math', { signbit: function signbit(x) { - // eslint-disable-next-line no-self-compare - return (x = +x) != x ? x : x == 0 ? 1 / x == Infinity : x > 0; - } }); - - -/***/ }), -/* 306 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://github.com/tc39/proposal-promise-finally - 'use strict'; - var $export = __webpack_require__(8); - var core = __webpack_require__(9); - var global = __webpack_require__(4); - var speciesConstructor = __webpack_require__(208); - var promiseResolve = __webpack_require__(214); - - $export($export.P + $export.R, 'Promise', { 'finally': function (onFinally) { - var C = speciesConstructor(this, core.Promise || global.Promise); - var isFunction = typeof onFinally == 'function'; - return this.then( - isFunction ? function (x) { - return promiseResolve(C, onFinally()).then(function () { return x; }); - } : onFinally, - isFunction ? function (e) { - return promiseResolve(C, onFinally()).then(function () { throw e; }); - } : onFinally - ); - } }); - - -/***/ }), -/* 307 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // https://github.com/tc39/proposal-promise-try - var $export = __webpack_require__(8); - var newPromiseCapability = __webpack_require__(211); - var perform = __webpack_require__(212); - - $export($export.S, 'Promise', { 'try': function (callbackfn) { - var promiseCapability = newPromiseCapability.f(this); - var result = perform(callbackfn); - (result.e ? promiseCapability.reject : promiseCapability.resolve)(result.v); - return promiseCapability.promise; - } }); - - -/***/ }), -/* 308 */ -/***/ (function(module, exports, __webpack_require__) { - - var metadata = __webpack_require__(309); - var anObject = __webpack_require__(12); - var toMetaKey = metadata.key; - var ordinaryDefineOwnMetadata = metadata.set; - - metadata.exp({ defineMetadata: function defineMetadata(metadataKey, metadataValue, target, targetKey) { - ordinaryDefineOwnMetadata(metadataKey, metadataValue, anObject(target), toMetaKey(targetKey)); - } }); - - -/***/ }), -/* 309 */ -/***/ (function(module, exports, __webpack_require__) { - - var Map = __webpack_require__(216); - var $export = __webpack_require__(8); - var shared = __webpack_require__(23)('metadata'); - var store = shared.store || (shared.store = new (__webpack_require__(221))()); - - var getOrCreateMetadataMap = function (target, targetKey, create) { - var targetMetadata = store.get(target); - if (!targetMetadata) { - if (!create) return undefined; - store.set(target, targetMetadata = new Map()); - } - var keyMetadata = targetMetadata.get(targetKey); - if (!keyMetadata) { - if (!create) return undefined; - targetMetadata.set(targetKey, keyMetadata = new Map()); - } return keyMetadata; - }; - var ordinaryHasOwnMetadata = function (MetadataKey, O, P) { - var metadataMap = getOrCreateMetadataMap(O, P, false); - return metadataMap === undefined ? false : metadataMap.has(MetadataKey); - }; - var ordinaryGetOwnMetadata = function (MetadataKey, O, P) { - var metadataMap = getOrCreateMetadataMap(O, P, false); - return metadataMap === undefined ? undefined : metadataMap.get(MetadataKey); - }; - var ordinaryDefineOwnMetadata = function (MetadataKey, MetadataValue, O, P) { - getOrCreateMetadataMap(O, P, true).set(MetadataKey, MetadataValue); - }; - var ordinaryOwnMetadataKeys = function (target, targetKey) { - var metadataMap = getOrCreateMetadataMap(target, targetKey, false); - var keys = []; - if (metadataMap) metadataMap.forEach(function (_, key) { keys.push(key); }); - return keys; - }; - var toMetaKey = function (it) { - return it === undefined || typeof it == 'symbol' ? it : String(it); - }; - var exp = function (O) { - $export($export.S, 'Reflect', O); - }; - - module.exports = { - store: store, - map: getOrCreateMetadataMap, - has: ordinaryHasOwnMetadata, - get: ordinaryGetOwnMetadata, - set: ordinaryDefineOwnMetadata, - keys: ordinaryOwnMetadataKeys, - key: toMetaKey, - exp: exp - }; - - -/***/ }), -/* 310 */ -/***/ (function(module, exports, __webpack_require__) { - - var metadata = __webpack_require__(309); - var anObject = __webpack_require__(12); - var toMetaKey = metadata.key; - var getOrCreateMetadataMap = metadata.map; - var store = metadata.store; - - metadata.exp({ deleteMetadata: function deleteMetadata(metadataKey, target /* , targetKey */) { - var targetKey = arguments.length < 3 ? undefined : toMetaKey(arguments[2]); - var metadataMap = getOrCreateMetadataMap(anObject(target), targetKey, false); - if (metadataMap === undefined || !metadataMap['delete'](metadataKey)) return false; - if (metadataMap.size) return true; - var targetMetadata = store.get(target); - targetMetadata['delete'](targetKey); - return !!targetMetadata.size || store['delete'](target); - } }); - - -/***/ }), -/* 311 */ -/***/ (function(module, exports, __webpack_require__) { - - var metadata = __webpack_require__(309); - var anObject = __webpack_require__(12); - var getPrototypeOf = __webpack_require__(58); - var ordinaryHasOwnMetadata = metadata.has; - var ordinaryGetOwnMetadata = metadata.get; - var toMetaKey = metadata.key; - - var ordinaryGetMetadata = function (MetadataKey, O, P) { - var hasOwn = ordinaryHasOwnMetadata(MetadataKey, O, P); - if (hasOwn) return ordinaryGetOwnMetadata(MetadataKey, O, P); - var parent = getPrototypeOf(O); - return parent !== null ? ordinaryGetMetadata(MetadataKey, parent, P) : undefined; - }; - - metadata.exp({ getMetadata: function getMetadata(metadataKey, target /* , targetKey */) { - return ordinaryGetMetadata(metadataKey, anObject(target), arguments.length < 3 ? undefined : toMetaKey(arguments[2])); - } }); - - -/***/ }), -/* 312 */ -/***/ (function(module, exports, __webpack_require__) { - - var Set = __webpack_require__(220); - var from = __webpack_require__(278); - var metadata = __webpack_require__(309); - var anObject = __webpack_require__(12); - var getPrototypeOf = __webpack_require__(58); - var ordinaryOwnMetadataKeys = metadata.keys; - var toMetaKey = metadata.key; - - var ordinaryMetadataKeys = function (O, P) { - var oKeys = ordinaryOwnMetadataKeys(O, P); - var parent = getPrototypeOf(O); - if (parent === null) return oKeys; - var pKeys = ordinaryMetadataKeys(parent, P); - return pKeys.length ? oKeys.length ? from(new Set(oKeys.concat(pKeys))) : pKeys : oKeys; - }; - - metadata.exp({ getMetadataKeys: function getMetadataKeys(target /* , targetKey */) { - return ordinaryMetadataKeys(anObject(target), arguments.length < 2 ? undefined : toMetaKey(arguments[1])); - } }); - - -/***/ }), -/* 313 */ -/***/ (function(module, exports, __webpack_require__) { - - var metadata = __webpack_require__(309); - var anObject = __webpack_require__(12); - var ordinaryGetOwnMetadata = metadata.get; - var toMetaKey = metadata.key; - - metadata.exp({ getOwnMetadata: function getOwnMetadata(metadataKey, target /* , targetKey */) { - return ordinaryGetOwnMetadata(metadataKey, anObject(target) - , arguments.length < 3 ? undefined : toMetaKey(arguments[2])); - } }); - - -/***/ }), -/* 314 */ -/***/ (function(module, exports, __webpack_require__) { - - var metadata = __webpack_require__(309); - var anObject = __webpack_require__(12); - var ordinaryOwnMetadataKeys = metadata.keys; - var toMetaKey = metadata.key; - - metadata.exp({ getOwnMetadataKeys: function getOwnMetadataKeys(target /* , targetKey */) { - return ordinaryOwnMetadataKeys(anObject(target), arguments.length < 2 ? undefined : toMetaKey(arguments[1])); - } }); - - -/***/ }), -/* 315 */ -/***/ (function(module, exports, __webpack_require__) { - - var metadata = __webpack_require__(309); - var anObject = __webpack_require__(12); - var getPrototypeOf = __webpack_require__(58); - var ordinaryHasOwnMetadata = metadata.has; - var toMetaKey = metadata.key; - - var ordinaryHasMetadata = function (MetadataKey, O, P) { - var hasOwn = ordinaryHasOwnMetadata(MetadataKey, O, P); - if (hasOwn) return true; - var parent = getPrototypeOf(O); - return parent !== null ? ordinaryHasMetadata(MetadataKey, parent, P) : false; - }; - - metadata.exp({ hasMetadata: function hasMetadata(metadataKey, target /* , targetKey */) { - return ordinaryHasMetadata(metadataKey, anObject(target), arguments.length < 3 ? undefined : toMetaKey(arguments[2])); - } }); - - -/***/ }), -/* 316 */ -/***/ (function(module, exports, __webpack_require__) { - - var metadata = __webpack_require__(309); - var anObject = __webpack_require__(12); - var ordinaryHasOwnMetadata = metadata.has; - var toMetaKey = metadata.key; - - metadata.exp({ hasOwnMetadata: function hasOwnMetadata(metadataKey, target /* , targetKey */) { - return ordinaryHasOwnMetadata(metadataKey, anObject(target) - , arguments.length < 3 ? undefined : toMetaKey(arguments[2])); - } }); - - -/***/ }), -/* 317 */ -/***/ (function(module, exports, __webpack_require__) { - - var $metadata = __webpack_require__(309); - var anObject = __webpack_require__(12); - var aFunction = __webpack_require__(21); - var toMetaKey = $metadata.key; - var ordinaryDefineOwnMetadata = $metadata.set; - - $metadata.exp({ metadata: function metadata(metadataKey, metadataValue) { - return function decorator(target, targetKey) { - ordinaryDefineOwnMetadata( - metadataKey, metadataValue, - (targetKey !== undefined ? anObject : aFunction)(target), - toMetaKey(targetKey) - ); - }; - } }); - - -/***/ }), -/* 318 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://github.com/rwaldron/tc39-notes/blob/master/es6/2014-09/sept-25.md#510-globalasap-for-enqueuing-a-microtask - var $export = __webpack_require__(8); - var microtask = __webpack_require__(210)(); - var process = __webpack_require__(4).process; - var isNode = __webpack_require__(34)(process) == 'process'; - - $export($export.G, { - asap: function asap(fn) { - var domain = isNode && process.domain; - microtask(domain ? domain.bind(fn) : fn); - } - }); - - -/***/ }), -/* 319 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - // https://github.com/zenparsing/es-observable - var $export = __webpack_require__(8); - var global = __webpack_require__(4); - var core = __webpack_require__(9); - var microtask = __webpack_require__(210)(); - var OBSERVABLE = __webpack_require__(26)('observable'); - var aFunction = __webpack_require__(21); - var anObject = __webpack_require__(12); - var anInstance = __webpack_require__(206); - var redefineAll = __webpack_require__(215); - var hide = __webpack_require__(10); - var forOf = __webpack_require__(207); - var RETURN = forOf.RETURN; - - var getMethod = function (fn) { - return fn == null ? undefined : aFunction(fn); - }; - - var cleanupSubscription = function (subscription) { - var cleanup = subscription._c; - if (cleanup) { - subscription._c = undefined; - cleanup(); - } - }; - - var subscriptionClosed = function (subscription) { - return subscription._o === undefined; - }; - - var closeSubscription = function (subscription) { - if (!subscriptionClosed(subscription)) { - subscription._o = undefined; - cleanupSubscription(subscription); - } - }; - - var Subscription = function (observer, subscriber) { - anObject(observer); - this._c = undefined; - this._o = observer; - observer = new SubscriptionObserver(this); - try { - var cleanup = subscriber(observer); - var subscription = cleanup; - if (cleanup != null) { - if (typeof cleanup.unsubscribe === 'function') cleanup = function () { subscription.unsubscribe(); }; - else aFunction(cleanup); - this._c = cleanup; - } - } catch (e) { - observer.error(e); - return; - } if (subscriptionClosed(this)) cleanupSubscription(this); - }; - - Subscription.prototype = redefineAll({}, { - unsubscribe: function unsubscribe() { closeSubscription(this); } - }); - - var SubscriptionObserver = function (subscription) { - this._s = subscription; - }; - - SubscriptionObserver.prototype = redefineAll({}, { - next: function next(value) { - var subscription = this._s; - if (!subscriptionClosed(subscription)) { - var observer = subscription._o; - try { - var m = getMethod(observer.next); - if (m) return m.call(observer, value); - } catch (e) { - try { - closeSubscription(subscription); - } finally { - throw e; - } - } - } - }, - error: function error(value) { - var subscription = this._s; - if (subscriptionClosed(subscription)) throw value; - var observer = subscription._o; - subscription._o = undefined; - try { - var m = getMethod(observer.error); - if (!m) throw value; - value = m.call(observer, value); - } catch (e) { - try { - cleanupSubscription(subscription); - } finally { - throw e; - } - } cleanupSubscription(subscription); - return value; - }, - complete: function complete(value) { - var subscription = this._s; - if (!subscriptionClosed(subscription)) { - var observer = subscription._o; - subscription._o = undefined; - try { - var m = getMethod(observer.complete); - value = m ? m.call(observer, value) : undefined; - } catch (e) { - try { - cleanupSubscription(subscription); - } finally { - throw e; - } - } cleanupSubscription(subscription); - return value; - } - } - }); - - var $Observable = function Observable(subscriber) { - anInstance(this, $Observable, 'Observable', '_f')._f = aFunction(subscriber); - }; - - redefineAll($Observable.prototype, { - subscribe: function subscribe(observer) { - return new Subscription(observer, this._f); - }, - forEach: function forEach(fn) { - var that = this; - return new (core.Promise || global.Promise)(function (resolve, reject) { - aFunction(fn); - var subscription = that.subscribe({ - next: function (value) { - try { - return fn(value); - } catch (e) { - reject(e); - subscription.unsubscribe(); - } - }, - error: reject, - complete: resolve - }); - }); - } - }); - - redefineAll($Observable, { - from: function from(x) { - var C = typeof this === 'function' ? this : $Observable; - var method = getMethod(anObject(x)[OBSERVABLE]); - if (method) { - var observable = anObject(method.call(x)); - return observable.constructor === C ? observable : new C(function (observer) { - return observable.subscribe(observer); - }); - } - return new C(function (observer) { - var done = false; - microtask(function () { - if (!done) { - try { - if (forOf(x, false, function (it) { - observer.next(it); - if (done) return RETURN; - }) === RETURN) return; - } catch (e) { - if (done) throw e; - observer.error(e); - return; - } observer.complete(); - } - }); - return function () { done = true; }; - }); - }, - of: function of() { - for (var i = 0, l = arguments.length, items = new Array(l); i < l;) items[i] = arguments[i++]; - return new (typeof this === 'function' ? this : $Observable)(function (observer) { - var done = false; - microtask(function () { - if (!done) { - for (var j = 0; j < items.length; ++j) { - observer.next(items[j]); - if (done) return; - } observer.complete(); - } - }); - return function () { done = true; }; - }); - } - }); - - hide($Observable.prototype, OBSERVABLE, function () { return this; }); - - $export($export.G, { Observable: $Observable }); - - __webpack_require__(193)('Observable'); - - -/***/ }), -/* 320 */ -/***/ (function(module, exports, __webpack_require__) { - - // ie9- setTimeout & setInterval additional parameters fix - var global = __webpack_require__(4); - var $export = __webpack_require__(8); - var userAgent = __webpack_require__(213); - var slice = [].slice; - var MSIE = /MSIE .\./.test(userAgent); // <- dirty ie9- check - var wrap = function (set) { - return function (fn, time /* , ...args */) { - var boundArgs = arguments.length > 2; - var args = boundArgs ? slice.call(arguments, 2) : false; - return set(boundArgs ? function () { - // eslint-disable-next-line no-new-func - (typeof fn == 'function' ? fn : Function(fn)).apply(this, args); - } : fn, time); - }; - }; - $export($export.G + $export.B + $export.F * MSIE, { - setTimeout: wrap(global.setTimeout), - setInterval: wrap(global.setInterval) - }); - - -/***/ }), -/* 321 */ -/***/ (function(module, exports, __webpack_require__) { - - var $export = __webpack_require__(8); - var $task = __webpack_require__(209); - $export($export.G + $export.B, { - setImmediate: $task.set, - clearImmediate: $task.clear - }); - - -/***/ }), -/* 322 */ -/***/ (function(module, exports, __webpack_require__) { - - var $iterators = __webpack_require__(194); - var getKeys = __webpack_require__(30); - var redefine = __webpack_require__(18); - var global = __webpack_require__(4); - var hide = __webpack_require__(10); - var Iterators = __webpack_require__(129); - var wks = __webpack_require__(26); - var ITERATOR = wks('iterator'); - var TO_STRING_TAG = wks('toStringTag'); - var ArrayValues = Iterators.Array; - - var DOMIterables = { - CSSRuleList: true, // TODO: Not spec compliant, should be false. - CSSStyleDeclaration: false, - CSSValueList: false, - ClientRectList: false, - DOMRectList: false, - DOMStringList: false, - DOMTokenList: true, - DataTransferItemList: false, - FileList: false, - HTMLAllCollection: false, - HTMLCollection: false, - HTMLFormElement: false, - HTMLSelectElement: false, - MediaList: true, // TODO: Not spec compliant, should be false. - MimeTypeArray: false, - NamedNodeMap: false, - NodeList: true, - PaintRequestList: false, - Plugin: false, - PluginArray: false, - SVGLengthList: false, - SVGNumberList: false, - SVGPathSegList: false, - SVGPointList: false, - SVGStringList: false, - SVGTransformList: false, - SourceBufferList: false, - StyleSheetList: true, // TODO: Not spec compliant, should be false. - TextTrackCueList: false, - TextTrackList: false, - TouchList: false - }; - - for (var collections = getKeys(DOMIterables), i = 0; i < collections.length; i++) { - var NAME = collections[i]; - var explicit = DOMIterables[NAME]; - var Collection = global[NAME]; - var proto = Collection && Collection.prototype; - var key; - if (proto) { - if (!proto[ITERATOR]) hide(proto, ITERATOR, ArrayValues); - if (!proto[TO_STRING_TAG]) hide(proto, TO_STRING_TAG, NAME); - Iterators[NAME] = ArrayValues; - if (explicit) for (key in $iterators) if (!proto[key]) redefine(proto, key, $iterators[key], true); - } - } - - -/***/ }), -/* 323 */ -/***/ (function(module, exports) { - - /* WEBPACK VAR INJECTION */(function(global) {/** - * Copyright (c) 2014, Facebook, Inc. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * https://raw.github.com/facebook/regenerator/master/LICENSE file. An - * additional grant of patent rights can be found in the PATENTS file in - * the same directory. - */ - - !(function(global) { - "use strict"; - - var Op = Object.prototype; - var hasOwn = Op.hasOwnProperty; - var undefined; // More compressible than void 0. - var $Symbol = typeof Symbol === "function" ? Symbol : {}; - var iteratorSymbol = $Symbol.iterator || "@@iterator"; - var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator"; - var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; - - var inModule = typeof module === "object"; - var runtime = global.regeneratorRuntime; - if (runtime) { - if (inModule) { - // If regeneratorRuntime is defined globally and we're in a module, - // make the exports object identical to regeneratorRuntime. - module.exports = runtime; - } - // Don't bother evaluating the rest of this file if the runtime was - // already defined globally. - return; - } - - // Define the runtime globally (as expected by generated code) as either - // module.exports (if we're in a module) or a new, empty object. - runtime = global.regeneratorRuntime = inModule ? module.exports : {}; - - function wrap(innerFn, outerFn, self, tryLocsList) { - // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator. - var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator; - var generator = Object.create(protoGenerator.prototype); - var context = new Context(tryLocsList || []); - - // The ._invoke method unifies the implementations of the .next, - // .throw, and .return methods. - generator._invoke = makeInvokeMethod(innerFn, self, context); - - return generator; - } - runtime.wrap = wrap; - - // Try/catch helper to minimize deoptimizations. Returns a completion - // record like context.tryEntries[i].completion. This interface could - // have been (and was previously) designed to take a closure to be - // invoked without arguments, but in all the cases we care about we - // already have an existing method we want to call, so there's no need - // to create a new function object. We can even get away with assuming - // the method takes exactly one argument, since that happens to be true - // in every case, so we don't have to touch the arguments object. The - // only additional allocation required is the completion record, which - // has a stable shape and so hopefully should be cheap to allocate. - function tryCatch(fn, obj, arg) { - try { - return { type: "normal", arg: fn.call(obj, arg) }; - } catch (err) { - return { type: "throw", arg: err }; - } - } - - var GenStateSuspendedStart = "suspendedStart"; - var GenStateSuspendedYield = "suspendedYield"; - var GenStateExecuting = "executing"; - var GenStateCompleted = "completed"; - - // Returning this object from the innerFn has the same effect as - // breaking out of the dispatch switch statement. - var ContinueSentinel = {}; - - // Dummy constructor functions that we use as the .constructor and - // .constructor.prototype properties for functions that return Generator - // objects. For full spec compliance, you may wish to configure your - // minifier not to mangle the names of these two functions. - function Generator() {} - function GeneratorFunction() {} - function GeneratorFunctionPrototype() {} - - // This is a polyfill for %IteratorPrototype% for environments that - // don't natively support it. - var IteratorPrototype = {}; - IteratorPrototype[iteratorSymbol] = function () { - return this; - }; - - var getProto = Object.getPrototypeOf; - var NativeIteratorPrototype = getProto && getProto(getProto(values([]))); - if (NativeIteratorPrototype && - NativeIteratorPrototype !== Op && - hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) { - // This environment has a native %IteratorPrototype%; use it instead - // of the polyfill. - IteratorPrototype = NativeIteratorPrototype; - } - - var Gp = GeneratorFunctionPrototype.prototype = - Generator.prototype = Object.create(IteratorPrototype); - GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype; - GeneratorFunctionPrototype.constructor = GeneratorFunction; - GeneratorFunctionPrototype[toStringTagSymbol] = - GeneratorFunction.displayName = "GeneratorFunction"; - - // Helper for defining the .next, .throw, and .return methods of the - // Iterator interface in terms of a single ._invoke method. - function defineIteratorMethods(prototype) { - ["next", "throw", "return"].forEach(function(method) { - prototype[method] = function(arg) { - return this._invoke(method, arg); - }; - }); - } - - runtime.isGeneratorFunction = function(genFun) { - var ctor = typeof genFun === "function" && genFun.constructor; - return ctor - ? ctor === GeneratorFunction || - // For the native GeneratorFunction constructor, the best we can - // do is to check its .name property. - (ctor.displayName || ctor.name) === "GeneratorFunction" - : false; - }; - - runtime.mark = function(genFun) { - if (Object.setPrototypeOf) { - Object.setPrototypeOf(genFun, GeneratorFunctionPrototype); - } else { - genFun.__proto__ = GeneratorFunctionPrototype; - if (!(toStringTagSymbol in genFun)) { - genFun[toStringTagSymbol] = "GeneratorFunction"; - } - } - genFun.prototype = Object.create(Gp); - return genFun; - }; - - // Within the body of any async function, `await x` is transformed to - // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test - // `hasOwn.call(value, "__await")` to determine if the yielded value is - // meant to be awaited. - runtime.awrap = function(arg) { - return { __await: arg }; - }; - - function AsyncIterator(generator) { - function invoke(method, arg, resolve, reject) { - var record = tryCatch(generator[method], generator, arg); - if (record.type === "throw") { - reject(record.arg); - } else { - var result = record.arg; - var value = result.value; - if (value && - typeof value === "object" && - hasOwn.call(value, "__await")) { - return Promise.resolve(value.__await).then(function(value) { - invoke("next", value, resolve, reject); - }, function(err) { - invoke("throw", err, resolve, reject); - }); - } - - return Promise.resolve(value).then(function(unwrapped) { - // When a yielded Promise is resolved, its final value becomes - // the .value of the Promise<{value,done}> result for the - // current iteration. If the Promise is rejected, however, the - // result for this iteration will be rejected with the same - // reason. Note that rejections of yielded Promises are not - // thrown back into the generator function, as is the case - // when an awaited Promise is rejected. This difference in - // behavior between yield and await is important, because it - // allows the consumer to decide what to do with the yielded - // rejection (swallow it and continue, manually .throw it back - // into the generator, abandon iteration, whatever). With - // await, by contrast, there is no opportunity to examine the - // rejection reason outside the generator function, so the - // only option is to throw it from the await expression, and - // let the generator function handle the exception. - result.value = unwrapped; - resolve(result); - }, reject); - } - } - - if (typeof global.process === "object" && global.process.domain) { - invoke = global.process.domain.bind(invoke); - } - - var previousPromise; - - function enqueue(method, arg) { - function callInvokeWithMethodAndArg() { - return new Promise(function(resolve, reject) { - invoke(method, arg, resolve, reject); - }); - } - - return previousPromise = - // If enqueue has been called before, then we want to wait until - // all previous Promises have been resolved before calling invoke, - // so that results are always delivered in the correct order. If - // enqueue has not been called before, then it is important to - // call invoke immediately, without waiting on a callback to fire, - // so that the async generator function has the opportunity to do - // any necessary setup in a predictable way. This predictability - // is why the Promise constructor synchronously invokes its - // executor callback, and why async functions synchronously - // execute code before the first await. Since we implement simple - // async functions in terms of async generators, it is especially - // important to get this right, even though it requires care. - previousPromise ? previousPromise.then( - callInvokeWithMethodAndArg, - // Avoid propagating failures to Promises returned by later - // invocations of the iterator. - callInvokeWithMethodAndArg - ) : callInvokeWithMethodAndArg(); - } - - // Define the unified helper method that is used to implement .next, - // .throw, and .return (see defineIteratorMethods). - this._invoke = enqueue; - } - - defineIteratorMethods(AsyncIterator.prototype); - AsyncIterator.prototype[asyncIteratorSymbol] = function () { - return this; - }; - runtime.AsyncIterator = AsyncIterator; - - // Note that simple async functions are implemented on top of - // AsyncIterator objects; they just return a Promise for the value of - // the final result produced by the iterator. - runtime.async = function(innerFn, outerFn, self, tryLocsList) { - var iter = new AsyncIterator( - wrap(innerFn, outerFn, self, tryLocsList) - ); - - return runtime.isGeneratorFunction(outerFn) - ? iter // If outerFn is a generator, return the full iterator. - : iter.next().then(function(result) { - return result.done ? result.value : iter.next(); - }); - }; - - function makeInvokeMethod(innerFn, self, context) { - var state = GenStateSuspendedStart; - - return function invoke(method, arg) { - if (state === GenStateExecuting) { - throw new Error("Generator is already running"); - } - - if (state === GenStateCompleted) { - if (method === "throw") { - throw arg; - } - - // Be forgiving, per 25.3.3.3.3 of the spec: - // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume - return doneResult(); - } - - context.method = method; - context.arg = arg; - - while (true) { - var delegate = context.delegate; - if (delegate) { - var delegateResult = maybeInvokeDelegate(delegate, context); - if (delegateResult) { - if (delegateResult === ContinueSentinel) continue; - return delegateResult; - } - } - - if (context.method === "next") { - // Setting context._sent for legacy support of Babel's - // function.sent implementation. - context.sent = context._sent = context.arg; - - } else if (context.method === "throw") { - if (state === GenStateSuspendedStart) { - state = GenStateCompleted; - throw context.arg; - } - - context.dispatchException(context.arg); - - } else if (context.method === "return") { - context.abrupt("return", context.arg); - } - - state = GenStateExecuting; - - var record = tryCatch(innerFn, self, context); - if (record.type === "normal") { - // If an exception is thrown from innerFn, we leave state === - // GenStateExecuting and loop back for another invocation. - state = context.done - ? GenStateCompleted - : GenStateSuspendedYield; - - if (record.arg === ContinueSentinel) { - continue; - } - - return { - value: record.arg, - done: context.done - }; - - } else if (record.type === "throw") { - state = GenStateCompleted; - // Dispatch the exception by looping back around to the - // context.dispatchException(context.arg) call above. - context.method = "throw"; - context.arg = record.arg; - } - } - }; - } - - // Call delegate.iterator[context.method](context.arg) and handle the - // result, either by returning a { value, done } result from the - // delegate iterator, or by modifying context.method and context.arg, - // setting context.delegate to null, and returning the ContinueSentinel. - function maybeInvokeDelegate(delegate, context) { - var method = delegate.iterator[context.method]; - if (method === undefined) { - // A .throw or .return when the delegate iterator has no .throw - // method always terminates the yield* loop. - context.delegate = null; - - if (context.method === "throw") { - if (delegate.iterator.return) { - // If the delegate iterator has a return method, give it a - // chance to clean up. - context.method = "return"; - context.arg = undefined; - maybeInvokeDelegate(delegate, context); - - if (context.method === "throw") { - // If maybeInvokeDelegate(context) changed context.method from - // "return" to "throw", let that override the TypeError below. - return ContinueSentinel; - } - } - - context.method = "throw"; - context.arg = new TypeError( - "The iterator does not provide a 'throw' method"); - } - - return ContinueSentinel; - } - - var record = tryCatch(method, delegate.iterator, context.arg); - - if (record.type === "throw") { - context.method = "throw"; - context.arg = record.arg; - context.delegate = null; - return ContinueSentinel; - } - - var info = record.arg; - - if (! info) { - context.method = "throw"; - context.arg = new TypeError("iterator result is not an object"); - context.delegate = null; - return ContinueSentinel; - } - - if (info.done) { - // Assign the result of the finished delegate to the temporary - // variable specified by delegate.resultName (see delegateYield). - context[delegate.resultName] = info.value; - - // Resume execution at the desired location (see delegateYield). - context.next = delegate.nextLoc; - - // If context.method was "throw" but the delegate handled the - // exception, let the outer generator proceed normally. If - // context.method was "next", forget context.arg since it has been - // "consumed" by the delegate iterator. If context.method was - // "return", allow the original .return call to continue in the - // outer generator. - if (context.method !== "return") { - context.method = "next"; - context.arg = undefined; - } - - } else { - // Re-yield the result returned by the delegate method. - return info; - } - - // The delegate iterator is finished, so forget it and continue with - // the outer generator. - context.delegate = null; - return ContinueSentinel; - } - - // Define Generator.prototype.{next,throw,return} in terms of the - // unified ._invoke helper method. - defineIteratorMethods(Gp); - - Gp[toStringTagSymbol] = "Generator"; - - // A Generator should always return itself as the iterator object when the - // @@iterator function is called on it. Some browsers' implementations of the - // iterator prototype chain incorrectly implement this, causing the Generator - // object to not be returned from this call. This ensures that doesn't happen. - // See https://github.com/facebook/regenerator/issues/274 for more details. - Gp[iteratorSymbol] = function() { - return this; - }; - - Gp.toString = function() { - return "[object Generator]"; - }; - - function pushTryEntry(locs) { - var entry = { tryLoc: locs[0] }; - - if (1 in locs) { - entry.catchLoc = locs[1]; - } - - if (2 in locs) { - entry.finallyLoc = locs[2]; - entry.afterLoc = locs[3]; - } - - this.tryEntries.push(entry); - } - - function resetTryEntry(entry) { - var record = entry.completion || {}; - record.type = "normal"; - delete record.arg; - entry.completion = record; - } - - function Context(tryLocsList) { - // The root entry object (effectively a try statement without a catch - // or a finally block) gives us a place to store values thrown from - // locations where there is no enclosing try statement. - this.tryEntries = [{ tryLoc: "root" }]; - tryLocsList.forEach(pushTryEntry, this); - this.reset(true); - } - - runtime.keys = function(object) { - var keys = []; - for (var key in object) { - keys.push(key); - } - keys.reverse(); - - // Rather than returning an object with a next method, we keep - // things simple and return the next function itself. - return function next() { - while (keys.length) { - var key = keys.pop(); - if (key in object) { - next.value = key; - next.done = false; - return next; - } - } - - // To avoid creating an additional object, we just hang the .value - // and .done properties off the next function object itself. This - // also ensures that the minifier will not anonymize the function. - next.done = true; - return next; - }; - }; - - function values(iterable) { - if (iterable) { - var iteratorMethod = iterable[iteratorSymbol]; - if (iteratorMethod) { - return iteratorMethod.call(iterable); - } - - if (typeof iterable.next === "function") { - return iterable; - } - - if (!isNaN(iterable.length)) { - var i = -1, next = function next() { - while (++i < iterable.length) { - if (hasOwn.call(iterable, i)) { - next.value = iterable[i]; - next.done = false; - return next; - } - } - - next.value = undefined; - next.done = true; - - return next; - }; - - return next.next = next; - } - } - - // Return an iterator with no values. - return { next: doneResult }; - } - runtime.values = values; - - function doneResult() { - return { value: undefined, done: true }; - } - - Context.prototype = { - constructor: Context, - - reset: function(skipTempReset) { - this.prev = 0; - this.next = 0; - // Resetting context._sent for legacy support of Babel's - // function.sent implementation. - this.sent = this._sent = undefined; - this.done = false; - this.delegate = null; - - this.method = "next"; - this.arg = undefined; - - this.tryEntries.forEach(resetTryEntry); - - if (!skipTempReset) { - for (var name in this) { - // Not sure about the optimal order of these conditions: - if (name.charAt(0) === "t" && - hasOwn.call(this, name) && - !isNaN(+name.slice(1))) { - this[name] = undefined; - } - } - } - }, - - stop: function() { - this.done = true; - - var rootEntry = this.tryEntries[0]; - var rootRecord = rootEntry.completion; - if (rootRecord.type === "throw") { - throw rootRecord.arg; - } - - return this.rval; - }, - - dispatchException: function(exception) { - if (this.done) { - throw exception; - } - - var context = this; - function handle(loc, caught) { - record.type = "throw"; - record.arg = exception; - context.next = loc; - - if (caught) { - // If the dispatched exception was caught by a catch block, - // then let that catch block handle the exception normally. - context.method = "next"; - context.arg = undefined; - } - - return !! caught; - } - - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - var record = entry.completion; - - if (entry.tryLoc === "root") { - // Exception thrown outside of any try block that could handle - // it, so set the completion value of the entire function to - // throw the exception. - return handle("end"); - } - - if (entry.tryLoc <= this.prev) { - var hasCatch = hasOwn.call(entry, "catchLoc"); - var hasFinally = hasOwn.call(entry, "finallyLoc"); - - if (hasCatch && hasFinally) { - if (this.prev < entry.catchLoc) { - return handle(entry.catchLoc, true); - } else if (this.prev < entry.finallyLoc) { - return handle(entry.finallyLoc); - } - - } else if (hasCatch) { - if (this.prev < entry.catchLoc) { - return handle(entry.catchLoc, true); - } - - } else if (hasFinally) { - if (this.prev < entry.finallyLoc) { - return handle(entry.finallyLoc); - } - - } else { - throw new Error("try statement without catch or finally"); - } - } - } - }, - - abrupt: function(type, arg) { - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - if (entry.tryLoc <= this.prev && - hasOwn.call(entry, "finallyLoc") && - this.prev < entry.finallyLoc) { - var finallyEntry = entry; - break; - } - } - - if (finallyEntry && - (type === "break" || - type === "continue") && - finallyEntry.tryLoc <= arg && - arg <= finallyEntry.finallyLoc) { - // Ignore the finally entry if control is not jumping to a - // location outside the try/catch block. - finallyEntry = null; - } - - var record = finallyEntry ? finallyEntry.completion : {}; - record.type = type; - record.arg = arg; - - if (finallyEntry) { - this.method = "next"; - this.next = finallyEntry.finallyLoc; - return ContinueSentinel; - } - - return this.complete(record); - }, - - complete: function(record, afterLoc) { - if (record.type === "throw") { - throw record.arg; - } - - if (record.type === "break" || - record.type === "continue") { - this.next = record.arg; - } else if (record.type === "return") { - this.rval = this.arg = record.arg; - this.method = "return"; - this.next = "end"; - } else if (record.type === "normal" && afterLoc) { - this.next = afterLoc; - } - - return ContinueSentinel; - }, - - finish: function(finallyLoc) { - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - if (entry.finallyLoc === finallyLoc) { - this.complete(entry.completion, entry.afterLoc); - resetTryEntry(entry); - return ContinueSentinel; - } - } - }, - - "catch": function(tryLoc) { - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - if (entry.tryLoc === tryLoc) { - var record = entry.completion; - if (record.type === "throw") { - var thrown = record.arg; - resetTryEntry(entry); - } - return thrown; - } - } - - // The context.catch method must only be called with a location - // argument that corresponds to a known catch block. - throw new Error("illegal catch attempt"); - }, - - delegateYield: function(iterable, resultName, nextLoc) { - this.delegate = { - iterator: values(iterable), - resultName: resultName, - nextLoc: nextLoc - }; - - if (this.method === "next") { - // Deliberately forget the last sent value so that we don't - // accidentally pass it on to the delegate. - this.arg = undefined; - } - - return ContinueSentinel; - } - }; - })( - // Among the various tricks for obtaining a reference to the global - // object, this seems to be the most reliable technique that does not - // use indirect eval (which violates Content Security Policy). - typeof global === "object" ? global : - typeof window === "object" ? window : - typeof self === "object" ? self : this - ); - - /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) - -/***/ }), -/* 324 */ -/***/ (function(module, exports, __webpack_require__) { - - __webpack_require__(325); - module.exports = __webpack_require__(9).RegExp.escape; - - -/***/ }), -/* 325 */ -/***/ (function(module, exports, __webpack_require__) { - - // https://github.com/benjamingr/RexExp.escape - var $export = __webpack_require__(8); - var $re = __webpack_require__(326)(/[\\^$*+?.()|[\]{}]/g, '\\$&'); - - $export($export.S, 'RegExp', { escape: function escape(it) { return $re(it); } }); - - -/***/ }), -/* 326 */ -/***/ (function(module, exports) { - - module.exports = function (regExp, replace) { - var replacer = replace === Object(replace) ? function (part) { - return replace[part]; - } : replace; - return function (it) { - return String(it).replace(regExp, replacer); - }; - }; - - -/***/ }), -/* 327 */ -/***/ (function(module, exports, __webpack_require__) { - - var BSON = __webpack_require__(328), - Binary = __webpack_require__(351), - Code = __webpack_require__(346), - DBRef = __webpack_require__(350), - Decimal128 = __webpack_require__(347), - Double = __webpack_require__(331), - Int32 = __webpack_require__(345), - Long = __webpack_require__(330), - Map = __webpack_require__(329), - MaxKey = __webpack_require__(349), - MinKey = __webpack_require__(348), - ObjectId = __webpack_require__(333), - BSONRegExp = __webpack_require__(343), - Symbol = __webpack_require__(344), - Timestamp = __webpack_require__(332); - - // BSON MAX VALUES - BSON.BSON_INT32_MAX = 0x7fffffff; - BSON.BSON_INT32_MIN = -0x80000000; - - BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; - BSON.BSON_INT64_MIN = -Math.pow(2, 63); - - // JS MAX PRECISE VALUES - BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. - BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. - - // Add BSON types to function creation - BSON.Binary = Binary; - BSON.Code = Code; - BSON.DBRef = DBRef; - BSON.Decimal128 = Decimal128; - BSON.Double = Double; - BSON.Int32 = Int32; - BSON.Long = Long; - BSON.Map = Map; - BSON.MaxKey = MaxKey; - BSON.MinKey = MinKey; - BSON.ObjectId = ObjectId; - BSON.ObjectID = ObjectId; - BSON.BSONRegExp = BSONRegExp; - BSON.Symbol = Symbol; - BSON.Timestamp = Timestamp; - - // Return the BSON - module.exports = BSON; - -/***/ }), -/* 328 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - - var Map = __webpack_require__(329), - Long = __webpack_require__(330), - Double = __webpack_require__(331), - Timestamp = __webpack_require__(332), - ObjectID = __webpack_require__(333), - BSONRegExp = __webpack_require__(343), - Symbol = __webpack_require__(344), - Int32 = __webpack_require__(345), - Code = __webpack_require__(346), - Decimal128 = __webpack_require__(347), - MinKey = __webpack_require__(348), - MaxKey = __webpack_require__(349), - DBRef = __webpack_require__(350), - Binary = __webpack_require__(351); - - // Parts of the parser - var deserialize = __webpack_require__(352), - serializer = __webpack_require__(353), - calculateObjectSize = __webpack_require__(355), - utils = __webpack_require__(339); - - /** - * @ignore - * @api private - */ - // Default Max Size - var MAXSIZE = 1024 * 1024 * 17; - - // Current Internal Temporary Serialization Buffer - var buffer = utils.allocBuffer(MAXSIZE); - - var BSON = function () {}; - - /** - * Serialize a Javascript object. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} [options.checkKeys] the serializer will check if keys are valid. - * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. - * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. - * @param {Number} [options.minInternalBufferSize=1024*1024*17] minimum size of the internal temporary serialization buffer **(default:1024*1024*17)**. - * @return {Buffer} returns the Buffer object containing the serialized object. - * @api public - */ - BSON.prototype.serialize = function serialize(object, options) { - options = options || {}; - // Unpack the options - var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; - var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; - var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; - var minInternalBufferSize = typeof options.minInternalBufferSize === 'number' ? options.minInternalBufferSize : MAXSIZE; - - // Resize the internal serialization buffer if needed - if (buffer.length < minInternalBufferSize) { - buffer = utils.allocBuffer(minInternalBufferSize); - } - - // Attempt to serialize - var serializationIndex = serializer(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, []); - // Create the final buffer - var finishedBuffer = utils.allocBuffer(serializationIndex); - // Copy into the finished buffer - buffer.copy(finishedBuffer, 0, 0, finishedBuffer.length); - // Return the buffer - return finishedBuffer; - }; - - /** - * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. - * - * @param {Object} object the Javascript object to serialize. - * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. - * @param {Boolean} [options.checkKeys] the serializer will check if keys are valid. - * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. - * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. - * @param {Number} [options.index] the index in the buffer where we wish to start serializing into. - * @return {Number} returns the index pointing to the last written byte in the buffer. - * @api public - */ - BSON.prototype.serializeWithBufferAndIndex = function (object, finalBuffer, options) { - options = options || {}; - // Unpack the options - var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; - var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; - var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; - var startIndex = typeof options.index === 'number' ? options.index : 0; - - // Attempt to serialize - var serializationIndex = serializer(finalBuffer, object, checkKeys, startIndex || 0, 0, serializeFunctions, ignoreUndefined); - - // Return the index - return serializationIndex - 1; - }; - - /** - * Deserialize data as BSON. - * - * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. - * @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized. - * @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse. - * @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function. - * @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits - * @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a node.js Buffer instance. - * @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types. - * @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer. - * @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances. - * @return {Object} returns the deserialized Javascript Object. - * @api public - */ - BSON.prototype.deserialize = function (buffer, options) { - return deserialize(buffer, options); - }; - - /** - * Calculate the bson size for a passed in Javascript object. - * - * @param {Object} object the Javascript object to calculate the BSON byte size for. - * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. - * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. - * @return {Number} returns the number of bytes the BSON object will take up. - * @api public - */ - BSON.prototype.calculateObjectSize = function (object, options) { - options = options || {}; - - var serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; - var ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; - - return calculateObjectSize(object, serializeFunctions, ignoreUndefined); - }; - - /** - * Deserialize stream data as BSON documents. - * - * @param {Buffer} data the buffer containing the serialized set of BSON documents. - * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. - * @param {Number} numberOfDocuments number of documents to deserialize. - * @param {Array} documents an array where to store the deserialized documents. - * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. - * @param {Object} [options] additional options used for the deserialization. - * @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized. - * @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse. - * @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function. - * @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits - * @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a node.js Buffer instance. - * @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types. - * @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer. - * @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances. - * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. - * @api public - */ - BSON.prototype.deserializeStream = function (data, startIndex, numberOfDocuments, documents, docStartIndex, options) { - options = options != null ? options : {}; - var index = startIndex; - // Loop over all documents - for (var i = 0; i < numberOfDocuments; i++) { - // Find size of the document - var size = data[index] | data[index + 1] << 8 | data[index + 2] << 16 | data[index + 3] << 24; - // Update options with index - options['index'] = index; - // Parse the document at this point - documents[docStartIndex + i] = this.deserialize(data, options); - // Adjust index by the document size - index = index + size; - } - - // Return object containing end index of parsing and list of documents - return index; - }; - - /** - * @ignore - * @api private - */ - // BSON MAX VALUES - BSON.BSON_INT32_MAX = 0x7fffffff; - BSON.BSON_INT32_MIN = -0x80000000; - - BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; - BSON.BSON_INT64_MIN = -Math.pow(2, 63); - - // JS MAX PRECISE VALUES - BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. - BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. - - // Internal long versions - // var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. - // var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. - - /** - * Number BSON Type - * - * @classconstant BSON_DATA_NUMBER - **/ - BSON.BSON_DATA_NUMBER = 1; - /** - * String BSON Type - * - * @classconstant BSON_DATA_STRING - **/ - BSON.BSON_DATA_STRING = 2; - /** - * Object BSON Type - * - * @classconstant BSON_DATA_OBJECT - **/ - BSON.BSON_DATA_OBJECT = 3; - /** - * Array BSON Type - * - * @classconstant BSON_DATA_ARRAY - **/ - BSON.BSON_DATA_ARRAY = 4; - /** - * Binary BSON Type - * - * @classconstant BSON_DATA_BINARY - **/ - BSON.BSON_DATA_BINARY = 5; - /** - * ObjectID BSON Type - * - * @classconstant BSON_DATA_OID - **/ - BSON.BSON_DATA_OID = 7; - /** - * Boolean BSON Type - * - * @classconstant BSON_DATA_BOOLEAN - **/ - BSON.BSON_DATA_BOOLEAN = 8; - /** - * Date BSON Type - * - * @classconstant BSON_DATA_DATE - **/ - BSON.BSON_DATA_DATE = 9; - /** - * null BSON Type - * - * @classconstant BSON_DATA_NULL - **/ - BSON.BSON_DATA_NULL = 10; - /** - * RegExp BSON Type - * - * @classconstant BSON_DATA_REGEXP - **/ - BSON.BSON_DATA_REGEXP = 11; - /** - * Code BSON Type - * - * @classconstant BSON_DATA_CODE - **/ - BSON.BSON_DATA_CODE = 13; - /** - * Symbol BSON Type - * - * @classconstant BSON_DATA_SYMBOL - **/ - BSON.BSON_DATA_SYMBOL = 14; - /** - * Code with Scope BSON Type - * - * @classconstant BSON_DATA_CODE_W_SCOPE - **/ - BSON.BSON_DATA_CODE_W_SCOPE = 15; - /** - * 32 bit Integer BSON Type - * - * @classconstant BSON_DATA_INT - **/ - BSON.BSON_DATA_INT = 16; - /** - * Timestamp BSON Type - * - * @classconstant BSON_DATA_TIMESTAMP - **/ - BSON.BSON_DATA_TIMESTAMP = 17; - /** - * Long BSON Type - * - * @classconstant BSON_DATA_LONG - **/ - BSON.BSON_DATA_LONG = 18; - /** - * MinKey BSON Type - * - * @classconstant BSON_DATA_MIN_KEY - **/ - BSON.BSON_DATA_MIN_KEY = 0xff; - /** - * MaxKey BSON Type - * - * @classconstant BSON_DATA_MAX_KEY - **/ - BSON.BSON_DATA_MAX_KEY = 0x7f; - - /** - * Binary Default Type - * - * @classconstant BSON_BINARY_SUBTYPE_DEFAULT - **/ - BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; - /** - * Binary Function Type - * - * @classconstant BSON_BINARY_SUBTYPE_FUNCTION - **/ - BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; - /** - * Binary Byte Array Type - * - * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY - **/ - BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; - /** - * Binary UUID Type - * - * @classconstant BSON_BINARY_SUBTYPE_UUID - **/ - BSON.BSON_BINARY_SUBTYPE_UUID = 3; - /** - * Binary MD5 Type - * - * @classconstant BSON_BINARY_SUBTYPE_MD5 - **/ - BSON.BSON_BINARY_SUBTYPE_MD5 = 4; - /** - * Binary User Defined Type - * - * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED - **/ - BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; - - // Return BSON - module.exports = BSON; - module.exports.Code = Code; - module.exports.Map = Map; - module.exports.Symbol = Symbol; - module.exports.BSON = BSON; - module.exports.DBRef = DBRef; - module.exports.Binary = Binary; - module.exports.ObjectID = ObjectID; - module.exports.Long = Long; - module.exports.Timestamp = Timestamp; - module.exports.Double = Double; - module.exports.Int32 = Int32; - module.exports.MinKey = MinKey; - module.exports.MaxKey = MaxKey; - module.exports.BSONRegExp = BSONRegExp; - module.exports.Decimal128 = Decimal128; - -/***/ }), -/* 329 */ -/***/ (function(module, exports) { - - /* WEBPACK VAR INJECTION */(function(global) {'use strict'; - - // We have an ES6 Map available, return the native instance - - if (typeof global.Map !== 'undefined') { - module.exports = global.Map; - module.exports.Map = global.Map; - } else { - // We will return a polyfill - var Map = function (array) { - this._keys = []; - this._values = {}; - - for (var i = 0; i < array.length; i++) { - if (array[i] == null) continue; // skip null and undefined - var entry = array[i]; - var key = entry[0]; - var value = entry[1]; - // Add the key to the list of keys in order - this._keys.push(key); - // Add the key and value to the values dictionary with a point - // to the location in the ordered keys list - this._values[key] = { v: value, i: this._keys.length - 1 }; - } - }; - - Map.prototype.clear = function () { - this._keys = []; - this._values = {}; - }; - - Map.prototype.delete = function (key) { - var value = this._values[key]; - if (value == null) return false; - // Delete entry - delete this._values[key]; - // Remove the key from the ordered keys list - this._keys.splice(value.i, 1); - return true; - }; - - Map.prototype.entries = function () { - var self = this; - var index = 0; - - return { - next: function () { - var key = self._keys[index++]; - return { - value: key !== undefined ? [key, self._values[key].v] : undefined, - done: key !== undefined ? false : true - }; - } - }; - }; - - Map.prototype.forEach = function (callback, self) { - self = self || this; - - for (var i = 0; i < this._keys.length; i++) { - var key = this._keys[i]; - // Call the forEach callback - callback.call(self, this._values[key].v, key, self); - } - }; - - Map.prototype.get = function (key) { - return this._values[key] ? this._values[key].v : undefined; - }; - - Map.prototype.has = function (key) { - return this._values[key] != null; - }; - - Map.prototype.keys = function () { - var self = this; - var index = 0; - - return { - next: function () { - var key = self._keys[index++]; - return { - value: key !== undefined ? key : undefined, - done: key !== undefined ? false : true - }; - } - }; - }; - - Map.prototype.set = function (key, value) { - if (this._values[key]) { - this._values[key].v = value; - return this; - } - - // Add the key to the list of keys in order - this._keys.push(key); - // Add the key and value to the values dictionary with a point - // to the location in the ordered keys list - this._values[key] = { v: value, i: this._keys.length - 1 }; - return this; - }; - - Map.prototype.values = function () { - var self = this; - var index = 0; - - return { - next: function () { - var key = self._keys[index++]; - return { - value: key !== undefined ? self._values[key].v : undefined, - done: key !== undefined ? false : true - }; - } - }; - }; - - // Last ismaster - Object.defineProperty(Map.prototype, 'size', { - enumerable: true, - get: function () { - return this._keys.length; - } - }); - - module.exports = Map; - module.exports.Map = Map; - } - /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) - -/***/ }), -/* 330 */ -/***/ (function(module, exports) { - - // Licensed under the Apache License, Version 2.0 (the "License"); - // you may not use this file except in compliance with the License. - // You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - // Copyright 2009 Google Inc. All Rights Reserved - - /** - * Defines a Long class for representing a 64-bit two's-complement - * integer value, which faithfully simulates the behavior of a Java "Long". This - * implementation is derived from LongLib in GWT. - * - * Constructs a 64-bit two's-complement integer, given its low and high 32-bit - * values as *signed* integers. See the from* functions below for more - * convenient ways of constructing Longs. - * - * The internal representation of a Long is the two given signed, 32-bit values. - * We use 32-bit pieces because these are the size of integers on which - * Javascript performs bit-operations. For operations like addition and - * multiplication, we split each number into 16-bit pieces, which can easily be - * multiplied within Javascript's floating-point representation without overflow - * or change in sign. - * - * In the algorithms below, we frequently reduce the negative case to the - * positive case by negating the input(s) and then post-processing the result. - * Note that we must ALWAYS check specially whether those values are MIN_VALUE - * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as - * a positive number, it overflows back into a negative). Not handling this - * case would often result in infinite recursion. - * - * @class - * @param {number} low the low (signed) 32 bits of the Long. - * @param {number} high the high (signed) 32 bits of the Long. - * @return {Long} - */ - function Long(low, high) { - if (!(this instanceof Long)) return new Long(low, high); - - this._bsontype = 'Long'; - /** - * @type {number} - * @ignore - */ - this.low_ = low | 0; // force into 32 signed bits. - - /** - * @type {number} - * @ignore - */ - this.high_ = high | 0; // force into 32 signed bits. - } - - /** - * Return the int value. - * - * @method - * @return {number} the value, assuming it is a 32-bit integer. - */ - Long.prototype.toInt = function () { - return this.low_; - }; - - /** - * Return the Number value. - * - * @method - * @return {number} the closest floating-point representation to this value. - */ - Long.prototype.toNumber = function () { - return this.high_ * Long.TWO_PWR_32_DBL_ + this.getLowBitsUnsigned(); - }; - - /** - * Return the JSON value. - * - * @method - * @return {string} the JSON representation. - */ - Long.prototype.toJSON = function () { - return this.toString(); - }; - - /** - * Return the String value. - * - * @method - * @param {number} [opt_radix] the radix in which the text should be written. - * @return {string} the textual representation of this value. - */ - Long.prototype.toString = function (opt_radix) { - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (this.isZero()) { - return '0'; - } - - if (this.isNegative()) { - if (this.equals(Long.MIN_VALUE)) { - // We need to change the Long value before it can be negated, so we remove - // the bottom-most digit in this base and then recurse to do the rest. - var radixLong = Long.fromNumber(radix); - var div = this.div(radixLong); - var rem = div.multiply(radixLong).subtract(this); - return div.toString(radix) + rem.toInt().toString(radix); - } else { - return '-' + this.negate().toString(radix); - } - } - - // Do several (6) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Long.fromNumber(Math.pow(radix, 6)); - - rem = this; - var result = ''; - - while (!rem.isZero()) { - var remDiv = rem.div(radixToPower); - var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); - var digits = intval.toString(radix); - - rem = remDiv; - if (rem.isZero()) { - return digits + result; - } else { - while (digits.length < 6) { - digits = '0' + digits; - } - result = '' + digits + result; - } - } - }; - - /** - * Return the high 32-bits value. - * - * @method - * @return {number} the high 32-bits as a signed value. - */ - Long.prototype.getHighBits = function () { - return this.high_; - }; - - /** - * Return the low 32-bits value. - * - * @method - * @return {number} the low 32-bits as a signed value. - */ - Long.prototype.getLowBits = function () { - return this.low_; - }; - - /** - * Return the low unsigned 32-bits value. - * - * @method - * @return {number} the low 32-bits as an unsigned value. - */ - Long.prototype.getLowBitsUnsigned = function () { - return this.low_ >= 0 ? this.low_ : Long.TWO_PWR_32_DBL_ + this.low_; - }; - - /** - * Returns the number of bits needed to represent the absolute value of this Long. - * - * @method - * @return {number} Returns the number of bits needed to represent the absolute value of this Long. - */ - Long.prototype.getNumBitsAbs = function () { - if (this.isNegative()) { - if (this.equals(Long.MIN_VALUE)) { - return 64; - } else { - return this.negate().getNumBitsAbs(); - } - } else { - var val = this.high_ !== 0 ? this.high_ : this.low_; - for (var bit = 31; bit > 0; bit--) { - if ((val & 1 << bit) !== 0) { - break; - } - } - return this.high_ !== 0 ? bit + 33 : bit + 1; - } - }; - - /** - * Return whether this value is zero. - * - * @method - * @return {boolean} whether this value is zero. - */ - Long.prototype.isZero = function () { - return this.high_ === 0 && this.low_ === 0; - }; - - /** - * Return whether this value is negative. - * - * @method - * @return {boolean} whether this value is negative. - */ - Long.prototype.isNegative = function () { - return this.high_ < 0; - }; - - /** - * Return whether this value is odd. - * - * @method - * @return {boolean} whether this value is odd. - */ - Long.prototype.isOdd = function () { - return (this.low_ & 1) === 1; - }; - - /** - * Return whether this Long equals the other - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long equals the other - */ - Long.prototype.equals = function (other) { - return this.high_ === other.high_ && this.low_ === other.low_; - }; - - /** - * Return whether this Long does not equal the other. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long does not equal the other. - */ - Long.prototype.notEquals = function (other) { - return this.high_ !== other.high_ || this.low_ !== other.low_; - }; - - /** - * Return whether this Long is less than the other. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long is less than the other. - */ - Long.prototype.lessThan = function (other) { - return this.compare(other) < 0; - }; - - /** - * Return whether this Long is less than or equal to the other. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long is less than or equal to the other. - */ - Long.prototype.lessThanOrEqual = function (other) { - return this.compare(other) <= 0; - }; - - /** - * Return whether this Long is greater than the other. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long is greater than the other. - */ - Long.prototype.greaterThan = function (other) { - return this.compare(other) > 0; - }; - - /** - * Return whether this Long is greater than or equal to the other. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long is greater than or equal to the other. - */ - Long.prototype.greaterThanOrEqual = function (other) { - return this.compare(other) >= 0; - }; - - /** - * Compares this Long with the given one. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. - */ - Long.prototype.compare = function (other) { - if (this.equals(other)) { - return 0; - } - - var thisNeg = this.isNegative(); - var otherNeg = other.isNegative(); - if (thisNeg && !otherNeg) { - return -1; - } - if (!thisNeg && otherNeg) { - return 1; - } - - // at this point, the signs are the same, so subtraction will not overflow - if (this.subtract(other).isNegative()) { - return -1; - } else { - return 1; - } - }; - - /** - * The negation of this value. - * - * @method - * @return {Long} the negation of this value. - */ - Long.prototype.negate = function () { - if (this.equals(Long.MIN_VALUE)) { - return Long.MIN_VALUE; - } else { - return this.not().add(Long.ONE); - } - }; - - /** - * Returns the sum of this and the given Long. - * - * @method - * @param {Long} other Long to add to this one. - * @return {Long} the sum of this and the given Long. - */ - Long.prototype.add = function (other) { - // Divide each number into 4 chunks of 16 bits, and then sum the chunks. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xffff; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xffff; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xffff; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xffff; - - var c48 = 0, - c32 = 0, - c16 = 0, - c00 = 0; - c00 += a00 + b00; - c16 += c00 >>> 16; - c00 &= 0xffff; - c16 += a16 + b16; - c32 += c16 >>> 16; - c16 &= 0xffff; - c32 += a32 + b32; - c48 += c32 >>> 16; - c32 &= 0xffff; - c48 += a48 + b48; - c48 &= 0xffff; - return Long.fromBits(c16 << 16 | c00, c48 << 16 | c32); - }; - - /** - * Returns the difference of this and the given Long. - * - * @method - * @param {Long} other Long to subtract from this. - * @return {Long} the difference of this and the given Long. - */ - Long.prototype.subtract = function (other) { - return this.add(other.negate()); - }; - - /** - * Returns the product of this and the given Long. - * - * @method - * @param {Long} other Long to multiply with this. - * @return {Long} the product of this and the other. - */ - Long.prototype.multiply = function (other) { - if (this.isZero()) { - return Long.ZERO; - } else if (other.isZero()) { - return Long.ZERO; - } - - if (this.equals(Long.MIN_VALUE)) { - return other.isOdd() ? Long.MIN_VALUE : Long.ZERO; - } else if (other.equals(Long.MIN_VALUE)) { - return this.isOdd() ? Long.MIN_VALUE : Long.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().multiply(other.negate()); - } else { - return this.negate().multiply(other).negate(); - } - } else if (other.isNegative()) { - return this.multiply(other.negate()).negate(); - } - - // If both Longs are small, use float multiplication - if (this.lessThan(Long.TWO_PWR_24_) && other.lessThan(Long.TWO_PWR_24_)) { - return Long.fromNumber(this.toNumber() * other.toNumber()); - } - - // Divide each Long into 4 chunks of 16 bits, and then add up 4x4 products. - // We can skip products that would overflow. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xffff; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xffff; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xffff; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xffff; - - var c48 = 0, - c32 = 0, - c16 = 0, - c00 = 0; - c00 += a00 * b00; - c16 += c00 >>> 16; - c00 &= 0xffff; - c16 += a16 * b00; - c32 += c16 >>> 16; - c16 &= 0xffff; - c16 += a00 * b16; - c32 += c16 >>> 16; - c16 &= 0xffff; - c32 += a32 * b00; - c48 += c32 >>> 16; - c32 &= 0xffff; - c32 += a16 * b16; - c48 += c32 >>> 16; - c32 &= 0xffff; - c32 += a00 * b32; - c48 += c32 >>> 16; - c32 &= 0xffff; - c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; - c48 &= 0xffff; - return Long.fromBits(c16 << 16 | c00, c48 << 16 | c32); - }; - - /** - * Returns this Long divided by the given one. - * - * @method - * @param {Long} other Long by which to divide. - * @return {Long} this Long divided by the given one. - */ - Long.prototype.div = function (other) { - if (other.isZero()) { - throw Error('division by zero'); - } else if (this.isZero()) { - return Long.ZERO; - } - - if (this.equals(Long.MIN_VALUE)) { - if (other.equals(Long.ONE) || other.equals(Long.NEG_ONE)) { - return Long.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE - } else if (other.equals(Long.MIN_VALUE)) { - return Long.ONE; - } else { - // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. - var halfThis = this.shiftRight(1); - var approx = halfThis.div(other).shiftLeft(1); - if (approx.equals(Long.ZERO)) { - return other.isNegative() ? Long.ONE : Long.NEG_ONE; - } else { - var rem = this.subtract(other.multiply(approx)); - var result = approx.add(rem.div(other)); - return result; - } - } - } else if (other.equals(Long.MIN_VALUE)) { - return Long.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().div(other.negate()); - } else { - return this.negate().div(other).negate(); - } - } else if (other.isNegative()) { - return this.div(other.negate()).negate(); - } - - // Repeat the following until the remainder is less than other: find a - // floating-point that approximates remainder / other *from below*, add this - // into the result, and subtract it from the remainder. It is critical that - // the approximate value is less than or equal to the real value so that the - // remainder never becomes negative. - var res = Long.ZERO; - rem = this; - while (rem.greaterThanOrEqual(other)) { - // Approximate the result of division. This may be a little greater or - // smaller than the actual value. - approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); - - // We will tweak the approximate result by changing it in the 48-th digit or - // the smallest non-fractional digit, whichever is larger. - var log2 = Math.ceil(Math.log(approx) / Math.LN2); - var delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48); - - // Decrease the approximation until it is smaller than the remainder. Note - // that if it is too large, the product overflows and is negative. - var approxRes = Long.fromNumber(approx); - var approxRem = approxRes.multiply(other); - while (approxRem.isNegative() || approxRem.greaterThan(rem)) { - approx -= delta; - approxRes = Long.fromNumber(approx); - approxRem = approxRes.multiply(other); - } - - // We know the answer can't be zero... and actually, zero would cause - // infinite recursion since we would make no progress. - if (approxRes.isZero()) { - approxRes = Long.ONE; - } - - res = res.add(approxRes); - rem = rem.subtract(approxRem); - } - return res; - }; - - /** - * Returns this Long modulo the given one. - * - * @method - * @param {Long} other Long by which to mod. - * @return {Long} this Long modulo the given one. - */ - Long.prototype.modulo = function (other) { - return this.subtract(this.div(other).multiply(other)); - }; - - /** - * The bitwise-NOT of this value. - * - * @method - * @return {Long} the bitwise-NOT of this value. - */ - Long.prototype.not = function () { - return Long.fromBits(~this.low_, ~this.high_); - }; - - /** - * Returns the bitwise-AND of this Long and the given one. - * - * @method - * @param {Long} other the Long with which to AND. - * @return {Long} the bitwise-AND of this and the other. - */ - Long.prototype.and = function (other) { - return Long.fromBits(this.low_ & other.low_, this.high_ & other.high_); - }; - - /** - * Returns the bitwise-OR of this Long and the given one. - * - * @method - * @param {Long} other the Long with which to OR. - * @return {Long} the bitwise-OR of this and the other. - */ - Long.prototype.or = function (other) { - return Long.fromBits(this.low_ | other.low_, this.high_ | other.high_); - }; - - /** - * Returns the bitwise-XOR of this Long and the given one. - * - * @method - * @param {Long} other the Long with which to XOR. - * @return {Long} the bitwise-XOR of this and the other. - */ - Long.prototype.xor = function (other) { - return Long.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); - }; - - /** - * Returns this Long with bits shifted to the left by the given amount. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Long} this shifted to the left by the given amount. - */ - Long.prototype.shiftLeft = function (numBits) { - numBits &= 63; - if (numBits === 0) { - return this; - } else { - var low = this.low_; - if (numBits < 32) { - var high = this.high_; - return Long.fromBits(low << numBits, high << numBits | low >>> 32 - numBits); - } else { - return Long.fromBits(0, low << numBits - 32); - } - } - }; - - /** - * Returns this Long with bits shifted to the right by the given amount. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Long} this shifted to the right by the given amount. - */ - Long.prototype.shiftRight = function (numBits) { - numBits &= 63; - if (numBits === 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Long.fromBits(low >>> numBits | high << 32 - numBits, high >> numBits); - } else { - return Long.fromBits(high >> numBits - 32, high >= 0 ? 0 : -1); - } - } - }; - - /** - * Returns this Long with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Long} this shifted to the right by the given amount, with zeros placed into the new leading bits. - */ - Long.prototype.shiftRightUnsigned = function (numBits) { - numBits &= 63; - if (numBits === 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Long.fromBits(low >>> numBits | high << 32 - numBits, high >>> numBits); - } else if (numBits === 32) { - return Long.fromBits(high, 0); - } else { - return Long.fromBits(high >>> numBits - 32, 0); - } - } - }; - - /** - * Returns a Long representing the given (32-bit) integer value. - * - * @method - * @param {number} value the 32-bit integer in question. - * @return {Long} the corresponding Long value. - */ - Long.fromInt = function (value) { - if (-128 <= value && value < 128) { - var cachedObj = Long.INT_CACHE_[value]; - if (cachedObj) { - return cachedObj; - } - } - - var obj = new Long(value | 0, value < 0 ? -1 : 0); - if (-128 <= value && value < 128) { - Long.INT_CACHE_[value] = obj; - } - return obj; - }; - - /** - * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. - * - * @method - * @param {number} value the number in question. - * @return {Long} the corresponding Long value. - */ - Long.fromNumber = function (value) { - if (isNaN(value) || !isFinite(value)) { - return Long.ZERO; - } else if (value <= -Long.TWO_PWR_63_DBL_) { - return Long.MIN_VALUE; - } else if (value + 1 >= Long.TWO_PWR_63_DBL_) { - return Long.MAX_VALUE; - } else if (value < 0) { - return Long.fromNumber(-value).negate(); - } else { - return new Long(value % Long.TWO_PWR_32_DBL_ | 0, value / Long.TWO_PWR_32_DBL_ | 0); - } - }; - - /** - * Returns a Long representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. - * - * @method - * @param {number} lowBits the low 32-bits. - * @param {number} highBits the high 32-bits. - * @return {Long} the corresponding Long value. - */ - Long.fromBits = function (lowBits, highBits) { - return new Long(lowBits, highBits); - }; - - /** - * Returns a Long representation of the given string, written using the given radix. - * - * @method - * @param {string} str the textual representation of the Long. - * @param {number} opt_radix the radix in which the text is written. - * @return {Long} the corresponding Long value. - */ - Long.fromString = function (str, opt_radix) { - if (str.length === 0) { - throw Error('number format error: empty string'); - } - - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (str.charAt(0) === '-') { - return Long.fromString(str.substring(1), radix).negate(); - } else if (str.indexOf('-') >= 0) { - throw Error('number format error: interior "-" character: ' + str); - } - - // Do several (8) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Long.fromNumber(Math.pow(radix, 8)); - - var result = Long.ZERO; - for (var i = 0; i < str.length; i += 8) { - var size = Math.min(8, str.length - i); - var value = parseInt(str.substring(i, i + size), radix); - if (size < 8) { - var power = Long.fromNumber(Math.pow(radix, size)); - result = result.multiply(power).add(Long.fromNumber(value)); - } else { - result = result.multiply(radixToPower); - result = result.add(Long.fromNumber(value)); - } - } - return result; - }; - - // NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the - // from* methods on which they depend. - - /** - * A cache of the Long representations of small integer values. - * @type {Object} - * @ignore - */ - Long.INT_CACHE_ = {}; - - // NOTE: the compiler should inline these constant values below and then remove - // these variables, so there should be no runtime penalty for these. - - /** - * Number used repeated below in calculations. This must appear before the - * first call to any from* function below. - * @type {number} - * @ignore - */ - Long.TWO_PWR_16_DBL_ = 1 << 16; - - /** - * @type {number} - * @ignore - */ - Long.TWO_PWR_24_DBL_ = 1 << 24; - - /** - * @type {number} - * @ignore - */ - Long.TWO_PWR_32_DBL_ = Long.TWO_PWR_16_DBL_ * Long.TWO_PWR_16_DBL_; - - /** - * @type {number} - * @ignore - */ - Long.TWO_PWR_31_DBL_ = Long.TWO_PWR_32_DBL_ / 2; - - /** - * @type {number} - * @ignore - */ - Long.TWO_PWR_48_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_16_DBL_; - - /** - * @type {number} - * @ignore - */ - Long.TWO_PWR_64_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_32_DBL_; - - /** - * @type {number} - * @ignore - */ - Long.TWO_PWR_63_DBL_ = Long.TWO_PWR_64_DBL_ / 2; - - /** @type {Long} */ - Long.ZERO = Long.fromInt(0); - - /** @type {Long} */ - Long.ONE = Long.fromInt(1); - - /** @type {Long} */ - Long.NEG_ONE = Long.fromInt(-1); - - /** @type {Long} */ - Long.MAX_VALUE = Long.fromBits(0xffffffff | 0, 0x7fffffff | 0); - - /** @type {Long} */ - Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0); - - /** - * @type {Long} - * @ignore - */ - Long.TWO_PWR_24_ = Long.fromInt(1 << 24); - - /** - * Expose. - */ - module.exports = Long; - module.exports.Long = Long; - -/***/ }), -/* 331 */ -/***/ (function(module, exports) { - - /** - * A class representation of the BSON Double type. - * - * @class - * @param {number} value the number we want to represent as a double. - * @return {Double} - */ - function Double(value) { - if (!(this instanceof Double)) return new Double(value); - - this._bsontype = 'Double'; - this.value = value; - } - - /** - * Access the number value. - * - * @method - * @return {number} returns the wrapped double number. - */ - Double.prototype.valueOf = function () { - return this.value; - }; - - /** - * @ignore - */ - Double.prototype.toJSON = function () { - return this.value; - }; - - module.exports = Double; - module.exports.Double = Double; - -/***/ }), -/* 332 */ -/***/ (function(module, exports) { - - // Licensed under the Apache License, Version 2.0 (the "License"); - // you may not use this file except in compliance with the License. - // You may obtain a copy of the License at - // - // http://www.apache.org/licenses/LICENSE-2.0 - // - // Unless required by applicable law or agreed to in writing, software - // distributed under the License is distributed on an "AS IS" BASIS, - // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - // See the License for the specific language governing permissions and - // limitations under the License. - // - // Copyright 2009 Google Inc. All Rights Reserved - - /** - * This type is for INTERNAL use in MongoDB only and should not be used in applications. - * The appropriate corresponding type is the JavaScript Date type. - * - * Defines a Timestamp class for representing a 64-bit two's-complement - * integer value, which faithfully simulates the behavior of a Java "Timestamp". This - * implementation is derived from TimestampLib in GWT. - * - * Constructs a 64-bit two's-complement integer, given its low and high 32-bit - * values as *signed* integers. See the from* functions below for more - * convenient ways of constructing Timestamps. - * - * The internal representation of a Timestamp is the two given signed, 32-bit values. - * We use 32-bit pieces because these are the size of integers on which - * Javascript performs bit-operations. For operations like addition and - * multiplication, we split each number into 16-bit pieces, which can easily be - * multiplied within Javascript's floating-point representation without overflow - * or change in sign. - * - * In the algorithms below, we frequently reduce the negative case to the - * positive case by negating the input(s) and then post-processing the result. - * Note that we must ALWAYS check specially whether those values are MIN_VALUE - * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as - * a positive number, it overflows back into a negative). Not handling this - * case would often result in infinite recursion. - * - * @class - * @param {number} low the low (signed) 32 bits of the Timestamp. - * @param {number} high the high (signed) 32 bits of the Timestamp. - */ - function Timestamp(low, high) { - if (!(this instanceof Timestamp)) return new Timestamp(low, high); - this._bsontype = 'Timestamp'; - /** - * @type {number} - * @ignore - */ - this.low_ = low | 0; // force into 32 signed bits. - - /** - * @type {number} - * @ignore - */ - this.high_ = high | 0; // force into 32 signed bits. - } - - /** - * Return the int value. - * - * @return {number} the value, assuming it is a 32-bit integer. - */ - Timestamp.prototype.toInt = function () { - return this.low_; - }; - - /** - * Return the Number value. - * - * @method - * @return {number} the closest floating-point representation to this value. - */ - Timestamp.prototype.toNumber = function () { - return this.high_ * Timestamp.TWO_PWR_32_DBL_ + this.getLowBitsUnsigned(); - }; - - /** - * Return the JSON value. - * - * @method - * @return {string} the JSON representation. - */ - Timestamp.prototype.toJSON = function () { - return this.toString(); - }; - - /** - * Return the String value. - * - * @method - * @param {number} [opt_radix] the radix in which the text should be written. - * @return {string} the textual representation of this value. - */ - Timestamp.prototype.toString = function (opt_radix) { - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (this.isZero()) { - return '0'; - } - - if (this.isNegative()) { - if (this.equals(Timestamp.MIN_VALUE)) { - // We need to change the Timestamp value before it can be negated, so we remove - // the bottom-most digit in this base and then recurse to do the rest. - var radixTimestamp = Timestamp.fromNumber(radix); - var div = this.div(radixTimestamp); - var rem = div.multiply(radixTimestamp).subtract(this); - return div.toString(radix) + rem.toInt().toString(radix); - } else { - return '-' + this.negate().toString(radix); - } - } - - // Do several (6) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Timestamp.fromNumber(Math.pow(radix, 6)); - - rem = this; - var result = ''; - - while (!rem.isZero()) { - var remDiv = rem.div(radixToPower); - var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); - var digits = intval.toString(radix); - - rem = remDiv; - if (rem.isZero()) { - return digits + result; - } else { - while (digits.length < 6) { - digits = '0' + digits; - } - result = '' + digits + result; - } - } - }; - - /** - * Return the high 32-bits value. - * - * @method - * @return {number} the high 32-bits as a signed value. - */ - Timestamp.prototype.getHighBits = function () { - return this.high_; - }; - - /** - * Return the low 32-bits value. - * - * @method - * @return {number} the low 32-bits as a signed value. - */ - Timestamp.prototype.getLowBits = function () { - return this.low_; - }; - - /** - * Return the low unsigned 32-bits value. - * - * @method - * @return {number} the low 32-bits as an unsigned value. - */ - Timestamp.prototype.getLowBitsUnsigned = function () { - return this.low_ >= 0 ? this.low_ : Timestamp.TWO_PWR_32_DBL_ + this.low_; - }; - - /** - * Returns the number of bits needed to represent the absolute value of this Timestamp. - * - * @method - * @return {number} Returns the number of bits needed to represent the absolute value of this Timestamp. - */ - Timestamp.prototype.getNumBitsAbs = function () { - if (this.isNegative()) { - if (this.equals(Timestamp.MIN_VALUE)) { - return 64; - } else { - return this.negate().getNumBitsAbs(); - } - } else { - var val = this.high_ !== 0 ? this.high_ : this.low_; - for (var bit = 31; bit > 0; bit--) { - if ((val & 1 << bit) !== 0) { - break; - } - } - return this.high_ !== 0 ? bit + 33 : bit + 1; - } - }; - - /** - * Return whether this value is zero. - * - * @method - * @return {boolean} whether this value is zero. - */ - Timestamp.prototype.isZero = function () { - return this.high_ === 0 && this.low_ === 0; - }; - - /** - * Return whether this value is negative. - * - * @method - * @return {boolean} whether this value is negative. - */ - Timestamp.prototype.isNegative = function () { - return this.high_ < 0; - }; - - /** - * Return whether this value is odd. - * - * @method - * @return {boolean} whether this value is odd. - */ - Timestamp.prototype.isOdd = function () { - return (this.low_ & 1) === 1; - }; - - /** - * Return whether this Timestamp equals the other - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp equals the other - */ - Timestamp.prototype.equals = function (other) { - return this.high_ === other.high_ && this.low_ === other.low_; - }; - - /** - * Return whether this Timestamp does not equal the other. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp does not equal the other. - */ - Timestamp.prototype.notEquals = function (other) { - return this.high_ !== other.high_ || this.low_ !== other.low_; - }; - - /** - * Return whether this Timestamp is less than the other. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp is less than the other. - */ - Timestamp.prototype.lessThan = function (other) { - return this.compare(other) < 0; - }; - - /** - * Return whether this Timestamp is less than or equal to the other. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp is less than or equal to the other. - */ - Timestamp.prototype.lessThanOrEqual = function (other) { - return this.compare(other) <= 0; - }; - - /** - * Return whether this Timestamp is greater than the other. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp is greater than the other. - */ - Timestamp.prototype.greaterThan = function (other) { - return this.compare(other) > 0; - }; - - /** - * Return whether this Timestamp is greater than or equal to the other. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp is greater than or equal to the other. - */ - Timestamp.prototype.greaterThanOrEqual = function (other) { - return this.compare(other) >= 0; - }; - - /** - * Compares this Timestamp with the given one. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. - */ - Timestamp.prototype.compare = function (other) { - if (this.equals(other)) { - return 0; - } - - var thisNeg = this.isNegative(); - var otherNeg = other.isNegative(); - if (thisNeg && !otherNeg) { - return -1; - } - if (!thisNeg && otherNeg) { - return 1; - } - - // at this point, the signs are the same, so subtraction will not overflow - if (this.subtract(other).isNegative()) { - return -1; - } else { - return 1; - } - }; - - /** - * The negation of this value. - * - * @method - * @return {Timestamp} the negation of this value. - */ - Timestamp.prototype.negate = function () { - if (this.equals(Timestamp.MIN_VALUE)) { - return Timestamp.MIN_VALUE; - } else { - return this.not().add(Timestamp.ONE); - } - }; - - /** - * Returns the sum of this and the given Timestamp. - * - * @method - * @param {Timestamp} other Timestamp to add to this one. - * @return {Timestamp} the sum of this and the given Timestamp. - */ - Timestamp.prototype.add = function (other) { - // Divide each number into 4 chunks of 16 bits, and then sum the chunks. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xffff; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xffff; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xffff; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xffff; - - var c48 = 0, - c32 = 0, - c16 = 0, - c00 = 0; - c00 += a00 + b00; - c16 += c00 >>> 16; - c00 &= 0xffff; - c16 += a16 + b16; - c32 += c16 >>> 16; - c16 &= 0xffff; - c32 += a32 + b32; - c48 += c32 >>> 16; - c32 &= 0xffff; - c48 += a48 + b48; - c48 &= 0xffff; - return Timestamp.fromBits(c16 << 16 | c00, c48 << 16 | c32); - }; - - /** - * Returns the difference of this and the given Timestamp. - * - * @method - * @param {Timestamp} other Timestamp to subtract from this. - * @return {Timestamp} the difference of this and the given Timestamp. - */ - Timestamp.prototype.subtract = function (other) { - return this.add(other.negate()); - }; - - /** - * Returns the product of this and the given Timestamp. - * - * @method - * @param {Timestamp} other Timestamp to multiply with this. - * @return {Timestamp} the product of this and the other. - */ - Timestamp.prototype.multiply = function (other) { - if (this.isZero()) { - return Timestamp.ZERO; - } else if (other.isZero()) { - return Timestamp.ZERO; - } - - if (this.equals(Timestamp.MIN_VALUE)) { - return other.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; - } else if (other.equals(Timestamp.MIN_VALUE)) { - return this.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().multiply(other.negate()); - } else { - return this.negate().multiply(other).negate(); - } - } else if (other.isNegative()) { - return this.multiply(other.negate()).negate(); - } - - // If both Timestamps are small, use float multiplication - if (this.lessThan(Timestamp.TWO_PWR_24_) && other.lessThan(Timestamp.TWO_PWR_24_)) { - return Timestamp.fromNumber(this.toNumber() * other.toNumber()); - } - - // Divide each Timestamp into 4 chunks of 16 bits, and then add up 4x4 products. - // We can skip products that would overflow. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xffff; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xffff; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xffff; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xffff; - - var c48 = 0, - c32 = 0, - c16 = 0, - c00 = 0; - c00 += a00 * b00; - c16 += c00 >>> 16; - c00 &= 0xffff; - c16 += a16 * b00; - c32 += c16 >>> 16; - c16 &= 0xffff; - c16 += a00 * b16; - c32 += c16 >>> 16; - c16 &= 0xffff; - c32 += a32 * b00; - c48 += c32 >>> 16; - c32 &= 0xffff; - c32 += a16 * b16; - c48 += c32 >>> 16; - c32 &= 0xffff; - c32 += a00 * b32; - c48 += c32 >>> 16; - c32 &= 0xffff; - c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; - c48 &= 0xffff; - return Timestamp.fromBits(c16 << 16 | c00, c48 << 16 | c32); - }; - - /** - * Returns this Timestamp divided by the given one. - * - * @method - * @param {Timestamp} other Timestamp by which to divide. - * @return {Timestamp} this Timestamp divided by the given one. - */ - Timestamp.prototype.div = function (other) { - if (other.isZero()) { - throw Error('division by zero'); - } else if (this.isZero()) { - return Timestamp.ZERO; - } - - if (this.equals(Timestamp.MIN_VALUE)) { - if (other.equals(Timestamp.ONE) || other.equals(Timestamp.NEG_ONE)) { - return Timestamp.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE - } else if (other.equals(Timestamp.MIN_VALUE)) { - return Timestamp.ONE; - } else { - // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. - var halfThis = this.shiftRight(1); - var approx = halfThis.div(other).shiftLeft(1); - if (approx.equals(Timestamp.ZERO)) { - return other.isNegative() ? Timestamp.ONE : Timestamp.NEG_ONE; - } else { - var rem = this.subtract(other.multiply(approx)); - var result = approx.add(rem.div(other)); - return result; - } - } - } else if (other.equals(Timestamp.MIN_VALUE)) { - return Timestamp.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().div(other.negate()); - } else { - return this.negate().div(other).negate(); - } - } else if (other.isNegative()) { - return this.div(other.negate()).negate(); - } - - // Repeat the following until the remainder is less than other: find a - // floating-point that approximates remainder / other *from below*, add this - // into the result, and subtract it from the remainder. It is critical that - // the approximate value is less than or equal to the real value so that the - // remainder never becomes negative. - var res = Timestamp.ZERO; - rem = this; - while (rem.greaterThanOrEqual(other)) { - // Approximate the result of division. This may be a little greater or - // smaller than the actual value. - approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); - - // We will tweak the approximate result by changing it in the 48-th digit or - // the smallest non-fractional digit, whichever is larger. - var log2 = Math.ceil(Math.log(approx) / Math.LN2); - var delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48); - - // Decrease the approximation until it is smaller than the remainder. Note - // that if it is too large, the product overflows and is negative. - var approxRes = Timestamp.fromNumber(approx); - var approxRem = approxRes.multiply(other); - while (approxRem.isNegative() || approxRem.greaterThan(rem)) { - approx -= delta; - approxRes = Timestamp.fromNumber(approx); - approxRem = approxRes.multiply(other); - } - - // We know the answer can't be zero... and actually, zero would cause - // infinite recursion since we would make no progress. - if (approxRes.isZero()) { - approxRes = Timestamp.ONE; - } - - res = res.add(approxRes); - rem = rem.subtract(approxRem); - } - return res; - }; - - /** - * Returns this Timestamp modulo the given one. - * - * @method - * @param {Timestamp} other Timestamp by which to mod. - * @return {Timestamp} this Timestamp modulo the given one. - */ - Timestamp.prototype.modulo = function (other) { - return this.subtract(this.div(other).multiply(other)); - }; - - /** - * The bitwise-NOT of this value. - * - * @method - * @return {Timestamp} the bitwise-NOT of this value. - */ - Timestamp.prototype.not = function () { - return Timestamp.fromBits(~this.low_, ~this.high_); - }; - - /** - * Returns the bitwise-AND of this Timestamp and the given one. - * - * @method - * @param {Timestamp} other the Timestamp with which to AND. - * @return {Timestamp} the bitwise-AND of this and the other. - */ - Timestamp.prototype.and = function (other) { - return Timestamp.fromBits(this.low_ & other.low_, this.high_ & other.high_); - }; - - /** - * Returns the bitwise-OR of this Timestamp and the given one. - * - * @method - * @param {Timestamp} other the Timestamp with which to OR. - * @return {Timestamp} the bitwise-OR of this and the other. - */ - Timestamp.prototype.or = function (other) { - return Timestamp.fromBits(this.low_ | other.low_, this.high_ | other.high_); - }; - - /** - * Returns the bitwise-XOR of this Timestamp and the given one. - * - * @method - * @param {Timestamp} other the Timestamp with which to XOR. - * @return {Timestamp} the bitwise-XOR of this and the other. - */ - Timestamp.prototype.xor = function (other) { - return Timestamp.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); - }; - - /** - * Returns this Timestamp with bits shifted to the left by the given amount. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Timestamp} this shifted to the left by the given amount. - */ - Timestamp.prototype.shiftLeft = function (numBits) { - numBits &= 63; - if (numBits === 0) { - return this; - } else { - var low = this.low_; - if (numBits < 32) { - var high = this.high_; - return Timestamp.fromBits(low << numBits, high << numBits | low >>> 32 - numBits); - } else { - return Timestamp.fromBits(0, low << numBits - 32); - } - } - }; - - /** - * Returns this Timestamp with bits shifted to the right by the given amount. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Timestamp} this shifted to the right by the given amount. - */ - Timestamp.prototype.shiftRight = function (numBits) { - numBits &= 63; - if (numBits === 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Timestamp.fromBits(low >>> numBits | high << 32 - numBits, high >> numBits); - } else { - return Timestamp.fromBits(high >> numBits - 32, high >= 0 ? 0 : -1); - } - } - }; - - /** - * Returns this Timestamp with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Timestamp} this shifted to the right by the given amount, with zeros placed into the new leading bits. - */ - Timestamp.prototype.shiftRightUnsigned = function (numBits) { - numBits &= 63; - if (numBits === 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Timestamp.fromBits(low >>> numBits | high << 32 - numBits, high >>> numBits); - } else if (numBits === 32) { - return Timestamp.fromBits(high, 0); - } else { - return Timestamp.fromBits(high >>> numBits - 32, 0); - } - } - }; - - /** - * Returns a Timestamp representing the given (32-bit) integer value. - * - * @method - * @param {number} value the 32-bit integer in question. - * @return {Timestamp} the corresponding Timestamp value. - */ - Timestamp.fromInt = function (value) { - if (-128 <= value && value < 128) { - var cachedObj = Timestamp.INT_CACHE_[value]; - if (cachedObj) { - return cachedObj; - } - } - - var obj = new Timestamp(value | 0, value < 0 ? -1 : 0); - if (-128 <= value && value < 128) { - Timestamp.INT_CACHE_[value] = obj; - } - return obj; - }; - - /** - * Returns a Timestamp representing the given value, provided that it is a finite number. Otherwise, zero is returned. - * - * @method - * @param {number} value the number in question. - * @return {Timestamp} the corresponding Timestamp value. - */ - Timestamp.fromNumber = function (value) { - if (isNaN(value) || !isFinite(value)) { - return Timestamp.ZERO; - } else if (value <= -Timestamp.TWO_PWR_63_DBL_) { - return Timestamp.MIN_VALUE; - } else if (value + 1 >= Timestamp.TWO_PWR_63_DBL_) { - return Timestamp.MAX_VALUE; - } else if (value < 0) { - return Timestamp.fromNumber(-value).negate(); - } else { - return new Timestamp(value % Timestamp.TWO_PWR_32_DBL_ | 0, value / Timestamp.TWO_PWR_32_DBL_ | 0); - } - }; - - /** - * Returns a Timestamp representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. - * - * @method - * @param {number} lowBits the low 32-bits. - * @param {number} highBits the high 32-bits. - * @return {Timestamp} the corresponding Timestamp value. - */ - Timestamp.fromBits = function (lowBits, highBits) { - return new Timestamp(lowBits, highBits); - }; - - /** - * Returns a Timestamp representation of the given string, written using the given radix. - * - * @method - * @param {string} str the textual representation of the Timestamp. - * @param {number} opt_radix the radix in which the text is written. - * @return {Timestamp} the corresponding Timestamp value. - */ - Timestamp.fromString = function (str, opt_radix) { - if (str.length === 0) { - throw Error('number format error: empty string'); - } - - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (str.charAt(0) === '-') { - return Timestamp.fromString(str.substring(1), radix).negate(); - } else if (str.indexOf('-') >= 0) { - throw Error('number format error: interior "-" character: ' + str); - } - - // Do several (8) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Timestamp.fromNumber(Math.pow(radix, 8)); - - var result = Timestamp.ZERO; - for (var i = 0; i < str.length; i += 8) { - var size = Math.min(8, str.length - i); - var value = parseInt(str.substring(i, i + size), radix); - if (size < 8) { - var power = Timestamp.fromNumber(Math.pow(radix, size)); - result = result.multiply(power).add(Timestamp.fromNumber(value)); - } else { - result = result.multiply(radixToPower); - result = result.add(Timestamp.fromNumber(value)); - } - } - return result; - }; - - // NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the - // from* methods on which they depend. - - /** - * A cache of the Timestamp representations of small integer values. - * @type {Object} - * @ignore - */ - Timestamp.INT_CACHE_ = {}; - - // NOTE: the compiler should inline these constant values below and then remove - // these variables, so there should be no runtime penalty for these. - - /** - * Number used repeated below in calculations. This must appear before the - * first call to any from* function below. - * @type {number} - * @ignore - */ - Timestamp.TWO_PWR_16_DBL_ = 1 << 16; - - /** - * @type {number} - * @ignore - */ - Timestamp.TWO_PWR_24_DBL_ = 1 << 24; - - /** - * @type {number} - * @ignore - */ - Timestamp.TWO_PWR_32_DBL_ = Timestamp.TWO_PWR_16_DBL_ * Timestamp.TWO_PWR_16_DBL_; - - /** - * @type {number} - * @ignore - */ - Timestamp.TWO_PWR_31_DBL_ = Timestamp.TWO_PWR_32_DBL_ / 2; - - /** - * @type {number} - * @ignore - */ - Timestamp.TWO_PWR_48_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_16_DBL_; - - /** - * @type {number} - * @ignore - */ - Timestamp.TWO_PWR_64_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_32_DBL_; - - /** - * @type {number} - * @ignore - */ - Timestamp.TWO_PWR_63_DBL_ = Timestamp.TWO_PWR_64_DBL_ / 2; - - /** @type {Timestamp} */ - Timestamp.ZERO = Timestamp.fromInt(0); - - /** @type {Timestamp} */ - Timestamp.ONE = Timestamp.fromInt(1); - - /** @type {Timestamp} */ - Timestamp.NEG_ONE = Timestamp.fromInt(-1); - - /** @type {Timestamp} */ - Timestamp.MAX_VALUE = Timestamp.fromBits(0xffffffff | 0, 0x7fffffff | 0); - - /** @type {Timestamp} */ - Timestamp.MIN_VALUE = Timestamp.fromBits(0, 0x80000000 | 0); - - /** - * @type {Timestamp} - * @ignore - */ - Timestamp.TWO_PWR_24_ = Timestamp.fromInt(1 << 24); - - /** - * Expose. - */ - module.exports = Timestamp; - module.exports.Timestamp = Timestamp; - -/***/ }), -/* 333 */ -/***/ (function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(Buffer, process) {// Custom inspect property name / symbol. - var inspect = 'inspect'; - - var utils = __webpack_require__(339); - - /** - * Machine id. - * - * Create a random 3-byte value (i.e. unique for this - * process). Other drivers use a md5 of the machine id here, but - * that would mean an asyc call to gethostname, so we don't bother. - * @ignore - */ - var MACHINE_ID = parseInt(Math.random() * 0xffffff, 10); - - // Regular expression that checks for hex value - var checkForHexRegExp = new RegExp('^[0-9a-fA-F]{24}$'); - - // Check if buffer exists - try { - if (Buffer && Buffer.from) { - var hasBufferType = true; - inspect = __webpack_require__(340).inspect.custom || 'inspect'; - } - } catch (err) { - hasBufferType = false; - } - - /** - * Create a new ObjectID instance - * - * @class - * @param {(string|number)} id Can be a 24 byte hex string, 12 byte binary string or a Number. - * @property {number} generationTime The generation time of this ObjectId instance - * @return {ObjectID} instance of ObjectID. - */ - var ObjectID = function ObjectID(id) { - // Duck-typing to support ObjectId from different npm packages - if (id instanceof ObjectID) return id; - if (!(this instanceof ObjectID)) return new ObjectID(id); - - this._bsontype = 'ObjectID'; - - // The most common usecase (blank id, new objectId instance) - if (id == null || typeof id === 'number') { - // Generate a new id - this.id = this.generate(id); - // If we are caching the hex string - if (ObjectID.cacheHexString) this.__id = this.toString('hex'); - // Return the object - return; - } - - // Check if the passed in id is valid - var valid = ObjectID.isValid(id); - - // Throw an error if it's not a valid setup - if (!valid && id != null) { - throw new Error('Argument passed in must be a single String of 12 bytes or a string of 24 hex characters'); - } else if (valid && typeof id === 'string' && id.length === 24 && hasBufferType) { - return new ObjectID(utils.toBuffer(id, 'hex')); - } else if (valid && typeof id === 'string' && id.length === 24) { - return ObjectID.createFromHexString(id); - } else if (id != null && id.length === 12) { - // assume 12 byte string - this.id = id; - } else if (id != null && id.toHexString) { - // Duck-typing to support ObjectId from different npm packages - return id; - } else { - throw new Error('Argument passed in must be a single String of 12 bytes or a string of 24 hex characters'); - } - - if (ObjectID.cacheHexString) this.__id = this.toString('hex'); - }; - - // Allow usage of ObjectId as well as ObjectID - // var ObjectId = ObjectID; - - // Precomputed hex table enables speedy hex string conversion - var hexTable = []; - for (var i = 0; i < 256; i++) { - hexTable[i] = (i <= 15 ? '0' : '') + i.toString(16); - } - - /** - * Return the ObjectID id as a 24 byte hex string representation - * - * @method - * @return {string} return the 24 byte hex string representation. - */ - ObjectID.prototype.toHexString = function () { - if (ObjectID.cacheHexString && this.__id) return this.__id; - - var hexString = ''; - if (!this.id || !this.id.length) { - throw new Error('invalid ObjectId, ObjectId.id must be either a string or a Buffer, but is [' + JSON.stringify(this.id) + ']'); - } - - if (this.id instanceof _Buffer) { - hexString = convertToHex(this.id); - if (ObjectID.cacheHexString) this.__id = hexString; - return hexString; - } - - for (var i = 0; i < this.id.length; i++) { - hexString += hexTable[this.id.charCodeAt(i)]; - } - - if (ObjectID.cacheHexString) this.__id = hexString; - return hexString; - }; - - /** - * Update the ObjectID index used in generating new ObjectID's on the driver - * - * @method - * @return {number} returns next index value. - * @ignore - */ - ObjectID.prototype.get_inc = function () { - return ObjectID.index = (ObjectID.index + 1) % 0xffffff; - }; - - /** - * Update the ObjectID index used in generating new ObjectID's on the driver - * - * @method - * @return {number} returns next index value. - * @ignore - */ - ObjectID.prototype.getInc = function () { - return this.get_inc(); - }; - - /** - * Generate a 12 byte id buffer used in ObjectID's - * - * @method - * @param {number} [time] optional parameter allowing to pass in a second based timestamp. - * @return {Buffer} return the 12 byte id buffer string. - */ - ObjectID.prototype.generate = function (time) { - if ('number' !== typeof time) { - time = ~~(Date.now() / 1000); - } - - // Use pid - var pid = (typeof process === 'undefined' || process.pid === 1 ? Math.floor(Math.random() * 100000) : process.pid) % 0xffff; - var inc = this.get_inc(); - // Buffer used - var buffer = utils.allocBuffer(12); - // Encode time - buffer[3] = time & 0xff; - buffer[2] = time >> 8 & 0xff; - buffer[1] = time >> 16 & 0xff; - buffer[0] = time >> 24 & 0xff; - // Encode machine - buffer[6] = MACHINE_ID & 0xff; - buffer[5] = MACHINE_ID >> 8 & 0xff; - buffer[4] = MACHINE_ID >> 16 & 0xff; - // Encode pid - buffer[8] = pid & 0xff; - buffer[7] = pid >> 8 & 0xff; - // Encode index - buffer[11] = inc & 0xff; - buffer[10] = inc >> 8 & 0xff; - buffer[9] = inc >> 16 & 0xff; - // Return the buffer - return buffer; - }; - - /** - * Converts the id into a 24 byte hex string for printing - * - * @param {String} format The Buffer toString format parameter. - * @return {String} return the 24 byte hex string representation. - * @ignore - */ - ObjectID.prototype.toString = function (format) { - // Is the id a buffer then use the buffer toString method to return the format - if (this.id && this.id.copy) { - return this.id.toString(typeof format === 'string' ? format : 'hex'); - } - - // if(this.buffer ) - return this.toHexString(); - }; - - /** - * Converts to a string representation of this Id. - * - * @return {String} return the 24 byte hex string representation. - * @ignore - */ - ObjectID.prototype[inspect] = ObjectID.prototype.toString; - - /** - * Converts to its JSON representation. - * - * @return {String} return the 24 byte hex string representation. - * @ignore - */ - ObjectID.prototype.toJSON = function () { - return this.toHexString(); - }; - - /** - * Compares the equality of this ObjectID with `otherID`. - * - * @method - * @param {object} otherID ObjectID instance to compare against. - * @return {boolean} the result of comparing two ObjectID's - */ - ObjectID.prototype.equals = function equals(otherId) { - // var id; - - if (otherId instanceof ObjectID) { - return this.toString() === otherId.toString(); - } else if (typeof otherId === 'string' && ObjectID.isValid(otherId) && otherId.length === 12 && this.id instanceof _Buffer) { - return otherId === this.id.toString('binary'); - } else if (typeof otherId === 'string' && ObjectID.isValid(otherId) && otherId.length === 24) { - return otherId.toLowerCase() === this.toHexString(); - } else if (typeof otherId === 'string' && ObjectID.isValid(otherId) && otherId.length === 12) { - return otherId === this.id; - } else if (otherId != null && (otherId instanceof ObjectID || otherId.toHexString)) { - return otherId.toHexString() === this.toHexString(); - } else { - return false; - } - }; - - /** - * Returns the generation date (accurate up to the second) that this ID was generated. - * - * @method - * @return {date} the generation date - */ - ObjectID.prototype.getTimestamp = function () { - var timestamp = new Date(); - var time = this.id[3] | this.id[2] << 8 | this.id[1] << 16 | this.id[0] << 24; - timestamp.setTime(Math.floor(time) * 1000); - return timestamp; - }; - - /** - * @ignore - */ - ObjectID.index = ~~(Math.random() * 0xffffff); - - /** - * @ignore - */ - ObjectID.createPk = function createPk() { - return new ObjectID(); - }; - - /** - * Creates an ObjectID from a second based number, with the rest of the ObjectID zeroed out. Used for comparisons or sorting the ObjectID. - * - * @method - * @param {number} time an integer number representing a number of seconds. - * @return {ObjectID} return the created ObjectID - */ - ObjectID.createFromTime = function createFromTime(time) { - var buffer = utils.toBuffer([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); - // Encode time into first 4 bytes - buffer[3] = time & 0xff; - buffer[2] = time >> 8 & 0xff; - buffer[1] = time >> 16 & 0xff; - buffer[0] = time >> 24 & 0xff; - // Return the new objectId - return new ObjectID(buffer); - }; - - // Lookup tables - //var encodeLookup = '0123456789abcdef'.split(''); - var decodeLookup = []; - i = 0; - while (i < 10) decodeLookup[0x30 + i] = i++; - while (i < 16) decodeLookup[0x41 - 10 + i] = decodeLookup[0x61 - 10 + i] = i++; - - var _Buffer = Buffer; - var convertToHex = function (bytes) { - return bytes.toString('hex'); - }; - - /** - * Creates an ObjectID from a hex string representation of an ObjectID. - * - * @method - * @param {string} hexString create a ObjectID from a passed in 24 byte hexstring. - * @return {ObjectID} return the created ObjectID - */ - ObjectID.createFromHexString = function createFromHexString(string) { - // Throw an error if it's not a valid setup - if (typeof string === 'undefined' || string != null && string.length !== 24) { - throw new Error('Argument passed in must be a single String of 12 bytes or a string of 24 hex characters'); - } - - // Use Buffer.from method if available - if (hasBufferType) return new ObjectID(utils.toBuffer(string, 'hex')); - - // Calculate lengths - var array = new _Buffer(12); - var n = 0; - var i = 0; - - while (i < 24) { - array[n++] = decodeLookup[string.charCodeAt(i++)] << 4 | decodeLookup[string.charCodeAt(i++)]; - } - - return new ObjectID(array); - }; - - /** - * Checks if a value is a valid bson ObjectId - * - * @method - * @return {boolean} return true if the value is a valid bson ObjectId, return false otherwise. - */ - ObjectID.isValid = function isValid(id) { - if (id == null) return false; - - if (typeof id === 'number') { - return true; - } - - if (typeof id === 'string') { - return id.length === 12 || id.length === 24 && checkForHexRegExp.test(id); - } - - if (id instanceof ObjectID) { - return true; - } - - if (id instanceof _Buffer) { - return true; - } - - // Duck-Typing detection of ObjectId like objects - if (id.toHexString) { - return id.id.length === 12 || id.id.length === 24 && checkForHexRegExp.test(id.id); - } - - return false; - }; - - /** - * @ignore - */ - Object.defineProperty(ObjectID.prototype, 'generationTime', { - enumerable: true, - get: function () { - return this.id[3] | this.id[2] << 8 | this.id[1] << 16 | this.id[0] << 24; - }, - set: function (value) { - // Encode time into first 4 bytes - this.id[3] = value & 0xff; - this.id[2] = value >> 8 & 0xff; - this.id[1] = value >> 16 & 0xff; - this.id[0] = value >> 24 & 0xff; - } - }); - - /** - * Expose. - */ - module.exports = ObjectID; - module.exports.ObjectID = ObjectID; - module.exports.ObjectId = ObjectID; - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(334).Buffer, __webpack_require__(338))) - -/***/ }), -/* 334 */ -/***/ (function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(global) {/*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - */ - /* eslint-disable no-proto */ - - 'use strict' - - var base64 = __webpack_require__(335) - var ieee754 = __webpack_require__(336) - var isArray = __webpack_require__(337) - - exports.Buffer = Buffer - exports.SlowBuffer = SlowBuffer - exports.INSPECT_MAX_BYTES = 50 - - /** - * If `Buffer.TYPED_ARRAY_SUPPORT`: - * === true Use Uint8Array implementation (fastest) - * === false Use Object implementation (most compatible, even IE6) - * - * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, - * Opera 11.6+, iOS 4.2+. - * - * Due to various browser bugs, sometimes the Object implementation will be used even - * when the browser supports typed arrays. - * - * Note: - * - * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, - * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. - * - * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. - * - * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of - * incorrect length in some situations. - - * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they - * get the Object implementation, which is slower but behaves correctly. - */ - Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined - ? global.TYPED_ARRAY_SUPPORT - : typedArraySupport() - - /* - * Export kMaxLength after typed array support is determined. - */ - exports.kMaxLength = kMaxLength() - - function typedArraySupport () { - try { - var arr = new Uint8Array(1) - arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }} - return arr.foo() === 42 && // typed array instances can be augmented - typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray` - arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray` - } catch (e) { - return false - } - } - - function kMaxLength () { - return Buffer.TYPED_ARRAY_SUPPORT - ? 0x7fffffff - : 0x3fffffff - } - - function createBuffer (that, length) { - if (kMaxLength() < length) { - throw new RangeError('Invalid typed array length') - } - if (Buffer.TYPED_ARRAY_SUPPORT) { - // Return an augmented `Uint8Array` instance, for best performance - that = new Uint8Array(length) - that.__proto__ = Buffer.prototype - } else { - // Fallback: Return an object instance of the Buffer class - if (that === null) { - that = new Buffer(length) - } - that.length = length - } - - return that - } - - /** - * The Buffer constructor returns instances of `Uint8Array` that have their - * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of - * `Uint8Array`, so the returned instances will have all the node `Buffer` methods - * and the `Uint8Array` methods. Square bracket notation works as expected -- it - * returns a single octet. - * - * The `Uint8Array` prototype remains unmodified. - */ - - function Buffer (arg, encodingOrOffset, length) { - if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { - return new Buffer(arg, encodingOrOffset, length) - } - - // Common case. - if (typeof arg === 'number') { - if (typeof encodingOrOffset === 'string') { - throw new Error( - 'If encoding is specified then the first argument must be a string' - ) - } - return allocUnsafe(this, arg) - } - return from(this, arg, encodingOrOffset, length) - } - - Buffer.poolSize = 8192 // not used by this implementation - - // TODO: Legacy, not needed anymore. Remove in next major version. - Buffer._augment = function (arr) { - arr.__proto__ = Buffer.prototype - return arr - } - - function from (that, value, encodingOrOffset, length) { - if (typeof value === 'number') { - throw new TypeError('"value" argument must not be a number') - } - - if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { - return fromArrayBuffer(that, value, encodingOrOffset, length) - } - - if (typeof value === 'string') { - return fromString(that, value, encodingOrOffset) - } - - return fromObject(that, value) - } - - /** - * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError - * if value is a number. - * Buffer.from(str[, encoding]) - * Buffer.from(array) - * Buffer.from(buffer) - * Buffer.from(arrayBuffer[, byteOffset[, length]]) - **/ - Buffer.from = function (value, encodingOrOffset, length) { - return from(null, value, encodingOrOffset, length) - } - - if (Buffer.TYPED_ARRAY_SUPPORT) { - Buffer.prototype.__proto__ = Uint8Array.prototype - Buffer.__proto__ = Uint8Array - if (typeof Symbol !== 'undefined' && Symbol.species && - Buffer[Symbol.species] === Buffer) { - // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 - Object.defineProperty(Buffer, Symbol.species, { - value: null, - configurable: true - }) - } - } - - function assertSize (size) { - if (typeof size !== 'number') { - throw new TypeError('"size" argument must be a number') - } else if (size < 0) { - throw new RangeError('"size" argument must not be negative') - } - } - - function alloc (that, size, fill, encoding) { - assertSize(size) - if (size <= 0) { - return createBuffer(that, size) - } - if (fill !== undefined) { - // Only pay attention to encoding if it's a string. This - // prevents accidentally sending in a number that would - // be interpretted as a start offset. - return typeof encoding === 'string' - ? createBuffer(that, size).fill(fill, encoding) - : createBuffer(that, size).fill(fill) - } - return createBuffer(that, size) - } - - /** - * Creates a new filled Buffer instance. - * alloc(size[, fill[, encoding]]) - **/ - Buffer.alloc = function (size, fill, encoding) { - return alloc(null, size, fill, encoding) - } - - function allocUnsafe (that, size) { - assertSize(size) - that = createBuffer(that, size < 0 ? 0 : checked(size) | 0) - if (!Buffer.TYPED_ARRAY_SUPPORT) { - for (var i = 0; i < size; ++i) { - that[i] = 0 - } - } - return that - } - - /** - * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. - * */ - Buffer.allocUnsafe = function (size) { - return allocUnsafe(null, size) - } - /** - * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. - */ - Buffer.allocUnsafeSlow = function (size) { - return allocUnsafe(null, size) - } - - function fromString (that, string, encoding) { - if (typeof encoding !== 'string' || encoding === '') { - encoding = 'utf8' - } - - if (!Buffer.isEncoding(encoding)) { - throw new TypeError('"encoding" must be a valid string encoding') - } - - var length = byteLength(string, encoding) | 0 - that = createBuffer(that, length) - - var actual = that.write(string, encoding) - - if (actual !== length) { - // Writing a hex string, for example, that contains invalid characters will - // cause everything after the first invalid character to be ignored. (e.g. - // 'abxxcd' will be treated as 'ab') - that = that.slice(0, actual) - } - - return that - } - - function fromArrayLike (that, array) { - var length = array.length < 0 ? 0 : checked(array.length) | 0 - that = createBuffer(that, length) - for (var i = 0; i < length; i += 1) { - that[i] = array[i] & 255 - } - return that - } - - function fromArrayBuffer (that, array, byteOffset, length) { - array.byteLength // this throws if `array` is not a valid ArrayBuffer - - if (byteOffset < 0 || array.byteLength < byteOffset) { - throw new RangeError('\'offset\' is out of bounds') - } - - if (array.byteLength < byteOffset + (length || 0)) { - throw new RangeError('\'length\' is out of bounds') - } - - if (byteOffset === undefined && length === undefined) { - array = new Uint8Array(array) - } else if (length === undefined) { - array = new Uint8Array(array, byteOffset) - } else { - array = new Uint8Array(array, byteOffset, length) - } - - if (Buffer.TYPED_ARRAY_SUPPORT) { - // Return an augmented `Uint8Array` instance, for best performance - that = array - that.__proto__ = Buffer.prototype - } else { - // Fallback: Return an object instance of the Buffer class - that = fromArrayLike(that, array) - } - return that - } - - function fromObject (that, obj) { - if (Buffer.isBuffer(obj)) { - var len = checked(obj.length) | 0 - that = createBuffer(that, len) - - if (that.length === 0) { - return that - } - - obj.copy(that, 0, 0, len) - return that - } - - if (obj) { - if ((typeof ArrayBuffer !== 'undefined' && - obj.buffer instanceof ArrayBuffer) || 'length' in obj) { - if (typeof obj.length !== 'number' || isnan(obj.length)) { - return createBuffer(that, 0) - } - return fromArrayLike(that, obj) - } - - if (obj.type === 'Buffer' && isArray(obj.data)) { - return fromArrayLike(that, obj.data) - } - } - - throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') - } - - function checked (length) { - // Note: cannot use `length < kMaxLength()` here because that fails when - // length is NaN (which is otherwise coerced to zero.) - if (length >= kMaxLength()) { - throw new RangeError('Attempt to allocate Buffer larger than maximum ' + - 'size: 0x' + kMaxLength().toString(16) + ' bytes') - } - return length | 0 - } - - function SlowBuffer (length) { - if (+length != length) { // eslint-disable-line eqeqeq - length = 0 - } - return Buffer.alloc(+length) - } - - Buffer.isBuffer = function isBuffer (b) { - return !!(b != null && b._isBuffer) - } - - Buffer.compare = function compare (a, b) { - if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { - throw new TypeError('Arguments must be Buffers') - } - - if (a === b) return 0 - - var x = a.length - var y = b.length - - for (var i = 0, len = Math.min(x, y); i < len; ++i) { - if (a[i] !== b[i]) { - x = a[i] - y = b[i] - break - } - } - - if (x < y) return -1 - if (y < x) return 1 - return 0 - } - - Buffer.isEncoding = function isEncoding (encoding) { - switch (String(encoding).toLowerCase()) { - case 'hex': - case 'utf8': - case 'utf-8': - case 'ascii': - case 'latin1': - case 'binary': - case 'base64': - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return true - default: - return false - } - } - - Buffer.concat = function concat (list, length) { - if (!isArray(list)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - - if (list.length === 0) { - return Buffer.alloc(0) - } - - var i - if (length === undefined) { - length = 0 - for (i = 0; i < list.length; ++i) { - length += list[i].length - } - } - - var buffer = Buffer.allocUnsafe(length) - var pos = 0 - for (i = 0; i < list.length; ++i) { - var buf = list[i] - if (!Buffer.isBuffer(buf)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - buf.copy(buffer, pos) - pos += buf.length - } - return buffer - } - - function byteLength (string, encoding) { - if (Buffer.isBuffer(string)) { - return string.length - } - if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && - (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { - return string.byteLength - } - if (typeof string !== 'string') { - string = '' + string - } - - var len = string.length - if (len === 0) return 0 - - // Use a for loop to avoid recursion - var loweredCase = false - for (;;) { - switch (encoding) { - case 'ascii': - case 'latin1': - case 'binary': - return len - case 'utf8': - case 'utf-8': - case undefined: - return utf8ToBytes(string).length - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return len * 2 - case 'hex': - return len >>> 1 - case 'base64': - return base64ToBytes(string).length - default: - if (loweredCase) return utf8ToBytes(string).length // assume utf8 - encoding = ('' + encoding).toLowerCase() - loweredCase = true - } - } - } - Buffer.byteLength = byteLength - - function slowToString (encoding, start, end) { - var loweredCase = false - - // No need to verify that "this.length <= MAX_UINT32" since it's a read-only - // property of a typed array. - - // This behaves neither like String nor Uint8Array in that we set start/end - // to their upper/lower bounds if the value passed is out of range. - // undefined is handled specially as per ECMA-262 6th Edition, - // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. - if (start === undefined || start < 0) { - start = 0 - } - // Return early if start > this.length. Done here to prevent potential uint32 - // coercion fail below. - if (start > this.length) { - return '' - } - - if (end === undefined || end > this.length) { - end = this.length - } - - if (end <= 0) { - return '' - } - - // Force coersion to uint32. This will also coerce falsey/NaN values to 0. - end >>>= 0 - start >>>= 0 - - if (end <= start) { - return '' - } - - if (!encoding) encoding = 'utf8' - - while (true) { - switch (encoding) { - case 'hex': - return hexSlice(this, start, end) - - case 'utf8': - case 'utf-8': - return utf8Slice(this, start, end) - - case 'ascii': - return asciiSlice(this, start, end) - - case 'latin1': - case 'binary': - return latin1Slice(this, start, end) - - case 'base64': - return base64Slice(this, start, end) - - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return utf16leSlice(this, start, end) - - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = (encoding + '').toLowerCase() - loweredCase = true - } - } - } - - // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect - // Buffer instances. - Buffer.prototype._isBuffer = true - - function swap (b, n, m) { - var i = b[n] - b[n] = b[m] - b[m] = i - } - - Buffer.prototype.swap16 = function swap16 () { - var len = this.length - if (len % 2 !== 0) { - throw new RangeError('Buffer size must be a multiple of 16-bits') - } - for (var i = 0; i < len; i += 2) { - swap(this, i, i + 1) - } - return this - } - - Buffer.prototype.swap32 = function swap32 () { - var len = this.length - if (len % 4 !== 0) { - throw new RangeError('Buffer size must be a multiple of 32-bits') - } - for (var i = 0; i < len; i += 4) { - swap(this, i, i + 3) - swap(this, i + 1, i + 2) - } - return this - } - - Buffer.prototype.swap64 = function swap64 () { - var len = this.length - if (len % 8 !== 0) { - throw new RangeError('Buffer size must be a multiple of 64-bits') - } - for (var i = 0; i < len; i += 8) { - swap(this, i, i + 7) - swap(this, i + 1, i + 6) - swap(this, i + 2, i + 5) - swap(this, i + 3, i + 4) - } - return this - } - - Buffer.prototype.toString = function toString () { - var length = this.length | 0 - if (length === 0) return '' - if (arguments.length === 0) return utf8Slice(this, 0, length) - return slowToString.apply(this, arguments) - } - - Buffer.prototype.equals = function equals (b) { - if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') - if (this === b) return true - return Buffer.compare(this, b) === 0 - } - - Buffer.prototype.inspect = function inspect () { - var str = '' - var max = exports.INSPECT_MAX_BYTES - if (this.length > 0) { - str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') - if (this.length > max) str += ' ... ' - } - return '' - } - - Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { - if (!Buffer.isBuffer(target)) { - throw new TypeError('Argument must be a Buffer') - } - - if (start === undefined) { - start = 0 - } - if (end === undefined) { - end = target ? target.length : 0 - } - if (thisStart === undefined) { - thisStart = 0 - } - if (thisEnd === undefined) { - thisEnd = this.length - } - - if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { - throw new RangeError('out of range index') - } - - if (thisStart >= thisEnd && start >= end) { - return 0 - } - if (thisStart >= thisEnd) { - return -1 - } - if (start >= end) { - return 1 - } - - start >>>= 0 - end >>>= 0 - thisStart >>>= 0 - thisEnd >>>= 0 - - if (this === target) return 0 - - var x = thisEnd - thisStart - var y = end - start - var len = Math.min(x, y) - - var thisCopy = this.slice(thisStart, thisEnd) - var targetCopy = target.slice(start, end) - - for (var i = 0; i < len; ++i) { - if (thisCopy[i] !== targetCopy[i]) { - x = thisCopy[i] - y = targetCopy[i] - break - } - } - - if (x < y) return -1 - if (y < x) return 1 - return 0 - } - - // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, - // OR the last index of `val` in `buffer` at offset <= `byteOffset`. - // - // Arguments: - // - buffer - a Buffer to search - // - val - a string, Buffer, or number - // - byteOffset - an index into `buffer`; will be clamped to an int32 - // - encoding - an optional encoding, relevant is val is a string - // - dir - true for indexOf, false for lastIndexOf - function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { - // Empty buffer means no match - if (buffer.length === 0) return -1 - - // Normalize byteOffset - if (typeof byteOffset === 'string') { - encoding = byteOffset - byteOffset = 0 - } else if (byteOffset > 0x7fffffff) { - byteOffset = 0x7fffffff - } else if (byteOffset < -0x80000000) { - byteOffset = -0x80000000 - } - byteOffset = +byteOffset // Coerce to Number. - if (isNaN(byteOffset)) { - // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer - byteOffset = dir ? 0 : (buffer.length - 1) - } - - // Normalize byteOffset: negative offsets start from the end of the buffer - if (byteOffset < 0) byteOffset = buffer.length + byteOffset - if (byteOffset >= buffer.length) { - if (dir) return -1 - else byteOffset = buffer.length - 1 - } else if (byteOffset < 0) { - if (dir) byteOffset = 0 - else return -1 - } - - // Normalize val - if (typeof val === 'string') { - val = Buffer.from(val, encoding) - } - - // Finally, search either indexOf (if dir is true) or lastIndexOf - if (Buffer.isBuffer(val)) { - // Special case: looking for empty string/buffer always fails - if (val.length === 0) { - return -1 - } - return arrayIndexOf(buffer, val, byteOffset, encoding, dir) - } else if (typeof val === 'number') { - val = val & 0xFF // Search for a byte value [0-255] - if (Buffer.TYPED_ARRAY_SUPPORT && - typeof Uint8Array.prototype.indexOf === 'function') { - if (dir) { - return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) - } else { - return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) - } - } - return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) - } - - throw new TypeError('val must be string, number or Buffer') - } - - function arrayIndexOf (arr, val, byteOffset, encoding, dir) { - var indexSize = 1 - var arrLength = arr.length - var valLength = val.length - - if (encoding !== undefined) { - encoding = String(encoding).toLowerCase() - if (encoding === 'ucs2' || encoding === 'ucs-2' || - encoding === 'utf16le' || encoding === 'utf-16le') { - if (arr.length < 2 || val.length < 2) { - return -1 - } - indexSize = 2 - arrLength /= 2 - valLength /= 2 - byteOffset /= 2 - } - } - - function read (buf, i) { - if (indexSize === 1) { - return buf[i] - } else { - return buf.readUInt16BE(i * indexSize) - } - } - - var i - if (dir) { - var foundIndex = -1 - for (i = byteOffset; i < arrLength; i++) { - if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { - if (foundIndex === -1) foundIndex = i - if (i - foundIndex + 1 === valLength) return foundIndex * indexSize - } else { - if (foundIndex !== -1) i -= i - foundIndex - foundIndex = -1 - } - } - } else { - if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength - for (i = byteOffset; i >= 0; i--) { - var found = true - for (var j = 0; j < valLength; j++) { - if (read(arr, i + j) !== read(val, j)) { - found = false - break - } - } - if (found) return i - } - } - - return -1 - } - - Buffer.prototype.includes = function includes (val, byteOffset, encoding) { - return this.indexOf(val, byteOffset, encoding) !== -1 - } - - Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, true) - } - - Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, false) - } - - function hexWrite (buf, string, offset, length) { - offset = Number(offset) || 0 - var remaining = buf.length - offset - if (!length) { - length = remaining - } else { - length = Number(length) - if (length > remaining) { - length = remaining - } - } - - // must be an even number of digits - var strLen = string.length - if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') - - if (length > strLen / 2) { - length = strLen / 2 - } - for (var i = 0; i < length; ++i) { - var parsed = parseInt(string.substr(i * 2, 2), 16) - if (isNaN(parsed)) return i - buf[offset + i] = parsed - } - return i - } - - function utf8Write (buf, string, offset, length) { - return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) - } - - function asciiWrite (buf, string, offset, length) { - return blitBuffer(asciiToBytes(string), buf, offset, length) - } - - function latin1Write (buf, string, offset, length) { - return asciiWrite(buf, string, offset, length) - } - - function base64Write (buf, string, offset, length) { - return blitBuffer(base64ToBytes(string), buf, offset, length) - } - - function ucs2Write (buf, string, offset, length) { - return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) - } - - Buffer.prototype.write = function write (string, offset, length, encoding) { - // Buffer#write(string) - if (offset === undefined) { - encoding = 'utf8' - length = this.length - offset = 0 - // Buffer#write(string, encoding) - } else if (length === undefined && typeof offset === 'string') { - encoding = offset - length = this.length - offset = 0 - // Buffer#write(string, offset[, length][, encoding]) - } else if (isFinite(offset)) { - offset = offset | 0 - if (isFinite(length)) { - length = length | 0 - if (encoding === undefined) encoding = 'utf8' - } else { - encoding = length - length = undefined - } - // legacy write(string, encoding, offset, length) - remove in v0.13 - } else { - throw new Error( - 'Buffer.write(string, encoding, offset[, length]) is no longer supported' - ) - } - - var remaining = this.length - offset - if (length === undefined || length > remaining) length = remaining - - if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { - throw new RangeError('Attempt to write outside buffer bounds') - } - - if (!encoding) encoding = 'utf8' - - var loweredCase = false - for (;;) { - switch (encoding) { - case 'hex': - return hexWrite(this, string, offset, length) - - case 'utf8': - case 'utf-8': - return utf8Write(this, string, offset, length) - - case 'ascii': - return asciiWrite(this, string, offset, length) - - case 'latin1': - case 'binary': - return latin1Write(this, string, offset, length) - - case 'base64': - // Warning: maxLength not taken into account in base64Write - return base64Write(this, string, offset, length) - - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return ucs2Write(this, string, offset, length) - - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = ('' + encoding).toLowerCase() - loweredCase = true - } - } - } - - Buffer.prototype.toJSON = function toJSON () { - return { - type: 'Buffer', - data: Array.prototype.slice.call(this._arr || this, 0) - } - } - - function base64Slice (buf, start, end) { - if (start === 0 && end === buf.length) { - return base64.fromByteArray(buf) - } else { - return base64.fromByteArray(buf.slice(start, end)) - } - } - - function utf8Slice (buf, start, end) { - end = Math.min(buf.length, end) - var res = [] - - var i = start - while (i < end) { - var firstByte = buf[i] - var codePoint = null - var bytesPerSequence = (firstByte > 0xEF) ? 4 - : (firstByte > 0xDF) ? 3 - : (firstByte > 0xBF) ? 2 - : 1 - - if (i + bytesPerSequence <= end) { - var secondByte, thirdByte, fourthByte, tempCodePoint - - switch (bytesPerSequence) { - case 1: - if (firstByte < 0x80) { - codePoint = firstByte - } - break - case 2: - secondByte = buf[i + 1] - if ((secondByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) - if (tempCodePoint > 0x7F) { - codePoint = tempCodePoint - } - } - break - case 3: - secondByte = buf[i + 1] - thirdByte = buf[i + 2] - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) - if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { - codePoint = tempCodePoint - } - } - break - case 4: - secondByte = buf[i + 1] - thirdByte = buf[i + 2] - fourthByte = buf[i + 3] - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) - if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { - codePoint = tempCodePoint - } - } - } - } - - if (codePoint === null) { - // we did not generate a valid codePoint so insert a - // replacement char (U+FFFD) and advance only 1 byte - codePoint = 0xFFFD - bytesPerSequence = 1 - } else if (codePoint > 0xFFFF) { - // encode to utf16 (surrogate pair dance) - codePoint -= 0x10000 - res.push(codePoint >>> 10 & 0x3FF | 0xD800) - codePoint = 0xDC00 | codePoint & 0x3FF - } - - res.push(codePoint) - i += bytesPerSequence - } - - return decodeCodePointsArray(res) - } - - // Based on http://stackoverflow.com/a/22747272/680742, the browser with - // the lowest limit is Chrome, with 0x10000 args. - // We go 1 magnitude less, for safety - var MAX_ARGUMENTS_LENGTH = 0x1000 - - function decodeCodePointsArray (codePoints) { - var len = codePoints.length - if (len <= MAX_ARGUMENTS_LENGTH) { - return String.fromCharCode.apply(String, codePoints) // avoid extra slice() - } - - // Decode in chunks to avoid "call stack size exceeded". - var res = '' - var i = 0 - while (i < len) { - res += String.fromCharCode.apply( - String, - codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) - ) - } - return res - } - - function asciiSlice (buf, start, end) { - var ret = '' - end = Math.min(buf.length, end) - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i] & 0x7F) - } - return ret - } - - function latin1Slice (buf, start, end) { - var ret = '' - end = Math.min(buf.length, end) - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i]) - } - return ret - } - - function hexSlice (buf, start, end) { - var len = buf.length - - if (!start || start < 0) start = 0 - if (!end || end < 0 || end > len) end = len - - var out = '' - for (var i = start; i < end; ++i) { - out += toHex(buf[i]) - } - return out - } - - function utf16leSlice (buf, start, end) { - var bytes = buf.slice(start, end) - var res = '' - for (var i = 0; i < bytes.length; i += 2) { - res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256) - } - return res - } - - Buffer.prototype.slice = function slice (start, end) { - var len = this.length - start = ~~start - end = end === undefined ? len : ~~end - - if (start < 0) { - start += len - if (start < 0) start = 0 - } else if (start > len) { - start = len - } - - if (end < 0) { - end += len - if (end < 0) end = 0 - } else if (end > len) { - end = len - } - - if (end < start) end = start - - var newBuf - if (Buffer.TYPED_ARRAY_SUPPORT) { - newBuf = this.subarray(start, end) - newBuf.__proto__ = Buffer.prototype - } else { - var sliceLen = end - start - newBuf = new Buffer(sliceLen, undefined) - for (var i = 0; i < sliceLen; ++i) { - newBuf[i] = this[i + start] - } - } - - return newBuf - } - - /* - * Need to make sure that buffer isn't trying to write out of bounds. - */ - function checkOffset (offset, ext, length) { - if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') - if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') - } - - Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var val = this[offset] - var mul = 1 - var i = 0 - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul - } - - return val - } - - Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) { - checkOffset(offset, byteLength, this.length) - } - - var val = this[offset + --byteLength] - var mul = 1 - while (byteLength > 0 && (mul *= 0x100)) { - val += this[offset + --byteLength] * mul - } - - return val - } - - Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { - if (!noAssert) checkOffset(offset, 1, this.length) - return this[offset] - } - - Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - return this[offset] | (this[offset + 1] << 8) - } - - Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - return (this[offset] << 8) | this[offset + 1] - } - - Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - - return ((this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16)) + - (this[offset + 3] * 0x1000000) - } - - Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset] * 0x1000000) + - ((this[offset + 1] << 16) | - (this[offset + 2] << 8) | - this[offset + 3]) - } - - Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var val = this[offset] - var mul = 1 - var i = 0 - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul - } - mul *= 0x80 - - if (val >= mul) val -= Math.pow(2, 8 * byteLength) - - return val - } - - Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var i = byteLength - var mul = 1 - var val = this[offset + --i] - while (i > 0 && (mul *= 0x100)) { - val += this[offset + --i] * mul - } - mul *= 0x80 - - if (val >= mul) val -= Math.pow(2, 8 * byteLength) - - return val - } - - Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { - if (!noAssert) checkOffset(offset, 1, this.length) - if (!(this[offset] & 0x80)) return (this[offset]) - return ((0xff - this[offset] + 1) * -1) - } - - Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - var val = this[offset] | (this[offset + 1] << 8) - return (val & 0x8000) ? val | 0xFFFF0000 : val - } - - Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length) - var val = this[offset + 1] | (this[offset] << 8) - return (val & 0x8000) ? val | 0xFFFF0000 : val - } - - Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16) | - (this[offset + 3] << 24) - } - - Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset] << 24) | - (this[offset + 1] << 16) | - (this[offset + 2] << 8) | - (this[offset + 3]) - } - - Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - return ieee754.read(this, offset, true, 23, 4) - } - - Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length) - return ieee754.read(this, offset, false, 23, 4) - } - - Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 8, this.length) - return ieee754.read(this, offset, true, 52, 8) - } - - Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 8, this.length) - return ieee754.read(this, offset, false, 52, 8) - } - - function checkInt (buf, value, offset, ext, max, min) { - if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') - if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') - if (offset + ext > buf.length) throw new RangeError('Index out of range') - } - - Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { - value = +value - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1 - checkInt(this, value, offset, byteLength, maxBytes, 0) - } - - var mul = 1 - var i = 0 - this[offset] = value & 0xFF - while (++i < byteLength && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF - } - - return offset + byteLength - } - - Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { - value = +value - offset = offset | 0 - byteLength = byteLength | 0 - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1 - checkInt(this, value, offset, byteLength, maxBytes, 0) - } - - var i = byteLength - 1 - var mul = 1 - this[offset + i] = value & 0xFF - while (--i >= 0 && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF - } - - return offset + byteLength - } - - Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) - if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) - this[offset] = (value & 0xff) - return offset + 1 - } - - function objectWriteUInt16 (buf, value, offset, littleEndian) { - if (value < 0) value = 0xffff + value + 1 - for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { - buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> - (littleEndian ? i : 1 - i) * 8 - } - } - - Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - } else { - objectWriteUInt16(this, value, offset, true) - } - return offset + 2 - } - - Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 8) - this[offset + 1] = (value & 0xff) - } else { - objectWriteUInt16(this, value, offset, false) - } - return offset + 2 - } - - function objectWriteUInt32 (buf, value, offset, littleEndian) { - if (value < 0) value = 0xffffffff + value + 1 - for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { - buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff - } - } - - Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset + 3] = (value >>> 24) - this[offset + 2] = (value >>> 16) - this[offset + 1] = (value >>> 8) - this[offset] = (value & 0xff) - } else { - objectWriteUInt32(this, value, offset, true) - } - return offset + 4 - } - - Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = (value & 0xff) - } else { - objectWriteUInt32(this, value, offset, false) - } - return offset + 4 - } - - Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength - 1) - - checkInt(this, value, offset, byteLength, limit - 1, -limit) - } - - var i = 0 - var mul = 1 - var sub = 0 - this[offset] = value & 0xFF - while (++i < byteLength && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { - sub = 1 - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF - } - - return offset + byteLength - } - - Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength - 1) - - checkInt(this, value, offset, byteLength, limit - 1, -limit) - } - - var i = byteLength - 1 - var mul = 1 - var sub = 0 - this[offset + i] = value & 0xFF - while (--i >= 0 && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { - sub = 1 - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF - } - - return offset + byteLength - } - - Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) - if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) - if (value < 0) value = 0xff + value + 1 - this[offset] = (value & 0xff) - return offset + 1 - } - - Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - } else { - objectWriteUInt16(this, value, offset, true) - } - return offset + 2 - } - - Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 8) - this[offset + 1] = (value & 0xff) - } else { - objectWriteUInt16(this, value, offset, false) - } - return offset + 2 - } - - Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - this[offset + 2] = (value >>> 16) - this[offset + 3] = (value >>> 24) - } else { - objectWriteUInt32(this, value, offset, true) - } - return offset + 4 - } - - Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { - value = +value - offset = offset | 0 - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - if (value < 0) value = 0xffffffff + value + 1 - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = (value & 0xff) - } else { - objectWriteUInt32(this, value, offset, false) - } - return offset + 4 - } - - function checkIEEE754 (buf, value, offset, ext, max, min) { - if (offset + ext > buf.length) throw new RangeError('Index out of range') - if (offset < 0) throw new RangeError('Index out of range') - } - - function writeFloat (buf, value, offset, littleEndian, noAssert) { - if (!noAssert) { - checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) - } - ieee754.write(buf, value, offset, littleEndian, 23, 4) - return offset + 4 - } - - Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { - return writeFloat(this, value, offset, true, noAssert) - } - - Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { - return writeFloat(this, value, offset, false, noAssert) - } - - function writeDouble (buf, value, offset, littleEndian, noAssert) { - if (!noAssert) { - checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) - } - ieee754.write(buf, value, offset, littleEndian, 52, 8) - return offset + 8 - } - - Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { - return writeDouble(this, value, offset, true, noAssert) - } - - Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { - return writeDouble(this, value, offset, false, noAssert) - } - - // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) - Buffer.prototype.copy = function copy (target, targetStart, start, end) { - if (!start) start = 0 - if (!end && end !== 0) end = this.length - if (targetStart >= target.length) targetStart = target.length - if (!targetStart) targetStart = 0 - if (end > 0 && end < start) end = start - - // Copy 0 bytes; we're done - if (end === start) return 0 - if (target.length === 0 || this.length === 0) return 0 - - // Fatal error conditions - if (targetStart < 0) { - throw new RangeError('targetStart out of bounds') - } - if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') - if (end < 0) throw new RangeError('sourceEnd out of bounds') - - // Are we oob? - if (end > this.length) end = this.length - if (target.length - targetStart < end - start) { - end = target.length - targetStart + start - } - - var len = end - start - var i - - if (this === target && start < targetStart && targetStart < end) { - // descending copy from end - for (i = len - 1; i >= 0; --i) { - target[i + targetStart] = this[i + start] - } - } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { - // ascending copy from start - for (i = 0; i < len; ++i) { - target[i + targetStart] = this[i + start] - } - } else { - Uint8Array.prototype.set.call( - target, - this.subarray(start, start + len), - targetStart - ) - } - - return len - } - - // Usage: - // buffer.fill(number[, offset[, end]]) - // buffer.fill(buffer[, offset[, end]]) - // buffer.fill(string[, offset[, end]][, encoding]) - Buffer.prototype.fill = function fill (val, start, end, encoding) { - // Handle string cases: - if (typeof val === 'string') { - if (typeof start === 'string') { - encoding = start - start = 0 - end = this.length - } else if (typeof end === 'string') { - encoding = end - end = this.length - } - if (val.length === 1) { - var code = val.charCodeAt(0) - if (code < 256) { - val = code - } - } - if (encoding !== undefined && typeof encoding !== 'string') { - throw new TypeError('encoding must be a string') - } - if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { - throw new TypeError('Unknown encoding: ' + encoding) - } - } else if (typeof val === 'number') { - val = val & 255 - } - - // Invalid ranges are not set to a default, so can range check early. - if (start < 0 || this.length < start || this.length < end) { - throw new RangeError('Out of range index') - } - - if (end <= start) { - return this - } - - start = start >>> 0 - end = end === undefined ? this.length : end >>> 0 - - if (!val) val = 0 - - var i - if (typeof val === 'number') { - for (i = start; i < end; ++i) { - this[i] = val - } - } else { - var bytes = Buffer.isBuffer(val) - ? val - : utf8ToBytes(new Buffer(val, encoding).toString()) - var len = bytes.length - for (i = 0; i < end - start; ++i) { - this[i + start] = bytes[i % len] - } - } - - return this - } - - // HELPER FUNCTIONS - // ================ - - var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g - - function base64clean (str) { - // Node strips out invalid characters like \n and \t from the string, base64-js does not - str = stringtrim(str).replace(INVALID_BASE64_RE, '') - // Node converts strings with length < 2 to '' - if (str.length < 2) return '' - // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not - while (str.length % 4 !== 0) { - str = str + '=' - } - return str - } - - function stringtrim (str) { - if (str.trim) return str.trim() - return str.replace(/^\s+|\s+$/g, '') - } - - function toHex (n) { - if (n < 16) return '0' + n.toString(16) - return n.toString(16) - } - - function utf8ToBytes (string, units) { - units = units || Infinity - var codePoint - var length = string.length - var leadSurrogate = null - var bytes = [] - - for (var i = 0; i < length; ++i) { - codePoint = string.charCodeAt(i) - - // is surrogate component - if (codePoint > 0xD7FF && codePoint < 0xE000) { - // last char was a lead - if (!leadSurrogate) { - // no lead yet - if (codePoint > 0xDBFF) { - // unexpected trail - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } else if (i + 1 === length) { - // unpaired lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } - - // valid lead - leadSurrogate = codePoint - - continue - } - - // 2 leads in a row - if (codePoint < 0xDC00) { - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - leadSurrogate = codePoint - continue - } - - // valid surrogate pair - codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 - } else if (leadSurrogate) { - // valid bmp char, but last char was a lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - } - - leadSurrogate = null - - // encode utf8 - if (codePoint < 0x80) { - if ((units -= 1) < 0) break - bytes.push(codePoint) - } else if (codePoint < 0x800) { - if ((units -= 2) < 0) break - bytes.push( - codePoint >> 0x6 | 0xC0, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x10000) { - if ((units -= 3) < 0) break - bytes.push( - codePoint >> 0xC | 0xE0, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x110000) { - if ((units -= 4) < 0) break - bytes.push( - codePoint >> 0x12 | 0xF0, - codePoint >> 0xC & 0x3F | 0x80, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else { - throw new Error('Invalid code point') - } - } - - return bytes - } - - function asciiToBytes (str) { - var byteArray = [] - for (var i = 0; i < str.length; ++i) { - // Node's code seems to be doing this and not & 0x7F.. - byteArray.push(str.charCodeAt(i) & 0xFF) - } - return byteArray - } - - function utf16leToBytes (str, units) { - var c, hi, lo - var byteArray = [] - for (var i = 0; i < str.length; ++i) { - if ((units -= 2) < 0) break - - c = str.charCodeAt(i) - hi = c >> 8 - lo = c % 256 - byteArray.push(lo) - byteArray.push(hi) - } - - return byteArray - } - - function base64ToBytes (str) { - return base64.toByteArray(base64clean(str)) - } - - function blitBuffer (src, dst, offset, length) { - for (var i = 0; i < length; ++i) { - if ((i + offset >= dst.length) || (i >= src.length)) break - dst[i + offset] = src[i] - } - return i - } - - function isnan (val) { - return val !== val // eslint-disable-line no-self-compare - } - - /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) - -/***/ }), -/* 335 */ -/***/ (function(module, exports) { - - 'use strict' - - exports.byteLength = byteLength - exports.toByteArray = toByteArray - exports.fromByteArray = fromByteArray - - var lookup = [] - var revLookup = [] - var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array - - var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' - for (var i = 0, len = code.length; i < len; ++i) { - lookup[i] = code[i] - revLookup[code.charCodeAt(i)] = i - } - - // Support decoding URL-safe base64 strings, as Node.js does. - // See: https://en.wikipedia.org/wiki/Base64#URL_applications - revLookup['-'.charCodeAt(0)] = 62 - revLookup['_'.charCodeAt(0)] = 63 - - function getLens (b64) { - var len = b64.length - - if (len % 4 > 0) { - throw new Error('Invalid string. Length must be a multiple of 4') - } - - // Trim off extra bytes after placeholder bytes are found - // See: https://github.com/beatgammit/base64-js/issues/42 - var validLen = b64.indexOf('=') - if (validLen === -1) validLen = len - - var placeHoldersLen = validLen === len - ? 0 - : 4 - (validLen % 4) - - return [validLen, placeHoldersLen] - } - - // base64 is 4/3 + up to two characters of the original data - function byteLength (b64) { - var lens = getLens(b64) - var validLen = lens[0] - var placeHoldersLen = lens[1] - return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen - } - - function _byteLength (b64, validLen, placeHoldersLen) { - return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen - } - - function toByteArray (b64) { - var tmp - var lens = getLens(b64) - var validLen = lens[0] - var placeHoldersLen = lens[1] - - var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)) - - var curByte = 0 - - // if there are placeholders, only get up to the last complete 4 chars - var len = placeHoldersLen > 0 - ? validLen - 4 - : validLen - - for (var i = 0; i < len; i += 4) { - tmp = - (revLookup[b64.charCodeAt(i)] << 18) | - (revLookup[b64.charCodeAt(i + 1)] << 12) | - (revLookup[b64.charCodeAt(i + 2)] << 6) | - revLookup[b64.charCodeAt(i + 3)] - arr[curByte++] = (tmp >> 16) & 0xFF - arr[curByte++] = (tmp >> 8) & 0xFF - arr[curByte++] = tmp & 0xFF - } - - if (placeHoldersLen === 2) { - tmp = - (revLookup[b64.charCodeAt(i)] << 2) | - (revLookup[b64.charCodeAt(i + 1)] >> 4) - arr[curByte++] = tmp & 0xFF - } - - if (placeHoldersLen === 1) { - tmp = - (revLookup[b64.charCodeAt(i)] << 10) | - (revLookup[b64.charCodeAt(i + 1)] << 4) | - (revLookup[b64.charCodeAt(i + 2)] >> 2) - arr[curByte++] = (tmp >> 8) & 0xFF - arr[curByte++] = tmp & 0xFF - } - - return arr - } - - function tripletToBase64 (num) { - return lookup[num >> 18 & 0x3F] + - lookup[num >> 12 & 0x3F] + - lookup[num >> 6 & 0x3F] + - lookup[num & 0x3F] - } - - function encodeChunk (uint8, start, end) { - var tmp - var output = [] - for (var i = start; i < end; i += 3) { - tmp = - ((uint8[i] << 16) & 0xFF0000) + - ((uint8[i + 1] << 8) & 0xFF00) + - (uint8[i + 2] & 0xFF) - output.push(tripletToBase64(tmp)) - } - return output.join('') - } - - function fromByteArray (uint8) { - var tmp - var len = uint8.length - var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes - var parts = [] - var maxChunkLength = 16383 // must be multiple of 3 - - // go through the array every three bytes, we'll deal with trailing stuff later - for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { - parts.push(encodeChunk( - uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength) - )) - } - - // pad the end with zeros, but make sure to not forget the extra bytes - if (extraBytes === 1) { - tmp = uint8[len - 1] - parts.push( - lookup[tmp >> 2] + - lookup[(tmp << 4) & 0x3F] + - '==' - ) - } else if (extraBytes === 2) { - tmp = (uint8[len - 2] << 8) + uint8[len - 1] - parts.push( - lookup[tmp >> 10] + - lookup[(tmp >> 4) & 0x3F] + - lookup[(tmp << 2) & 0x3F] + - '=' - ) - } - - return parts.join('') - } - - -/***/ }), -/* 336 */ -/***/ (function(module, exports) { - - exports.read = function (buffer, offset, isLE, mLen, nBytes) { - var e, m - var eLen = (nBytes * 8) - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 1 - var nBits = -7 - var i = isLE ? (nBytes - 1) : 0 - var d = isLE ? -1 : 1 - var s = buffer[offset + i] - - i += d - - e = s & ((1 << (-nBits)) - 1) - s >>= (-nBits) - nBits += eLen - for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {} - - m = e & ((1 << (-nBits)) - 1) - e >>= (-nBits) - nBits += mLen - for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} - - if (e === 0) { - e = 1 - eBias - } else if (e === eMax) { - return m ? NaN : ((s ? -1 : 1) * Infinity) - } else { - m = m + Math.pow(2, mLen) - e = e - eBias - } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen) - } - - exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { - var e, m, c - var eLen = (nBytes * 8) - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 1 - var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) - var i = isLE ? 0 : (nBytes - 1) - var d = isLE ? 1 : -1 - var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 - - value = Math.abs(value) - - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0 - e = eMax - } else { - e = Math.floor(Math.log(value) / Math.LN2) - if (value * (c = Math.pow(2, -e)) < 1) { - e-- - c *= 2 - } - if (e + eBias >= 1) { - value += rt / c - } else { - value += rt * Math.pow(2, 1 - eBias) - } - if (value * c >= 2) { - e++ - c /= 2 - } - - if (e + eBias >= eMax) { - m = 0 - e = eMax - } else if (e + eBias >= 1) { - m = ((value * c) - 1) * Math.pow(2, mLen) - e = e + eBias - } else { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) - e = 0 - } - } - - for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} - - e = (e << mLen) | m - eLen += mLen - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} - - buffer[offset + i - d] |= s * 128 - } - - -/***/ }), -/* 337 */ -/***/ (function(module, exports) { - - var toString = {}.toString; - - module.exports = Array.isArray || function (arr) { - return toString.call(arr) == '[object Array]'; - }; - - -/***/ }), -/* 338 */ -/***/ (function(module, exports) { - - // shim for using process in browser - var process = module.exports = {}; - - // cached from whatever global is present so that test runners that stub it - // don't break things. But we need to wrap it in a try catch in case it is - // wrapped in strict mode code which doesn't define any globals. It's inside a - // function because try/catches deoptimize in certain engines. - - var cachedSetTimeout; - var cachedClearTimeout; - - function defaultSetTimout() { - throw new Error('setTimeout has not been defined'); - } - function defaultClearTimeout () { - throw new Error('clearTimeout has not been defined'); - } - (function () { - try { - if (typeof setTimeout === 'function') { - cachedSetTimeout = setTimeout; - } else { - cachedSetTimeout = defaultSetTimout; - } - } catch (e) { - cachedSetTimeout = defaultSetTimout; - } - try { - if (typeof clearTimeout === 'function') { - cachedClearTimeout = clearTimeout; - } else { - cachedClearTimeout = defaultClearTimeout; - } - } catch (e) { - cachedClearTimeout = defaultClearTimeout; - } - } ()) - function runTimeout(fun) { - if (cachedSetTimeout === setTimeout) { - //normal enviroments in sane situations - return setTimeout(fun, 0); - } - // if setTimeout wasn't available but was latter defined - if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { - cachedSetTimeout = setTimeout; - return setTimeout(fun, 0); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedSetTimeout(fun, 0); - } catch(e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedSetTimeout.call(null, fun, 0); - } catch(e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error - return cachedSetTimeout.call(this, fun, 0); - } - } - - - } - function runClearTimeout(marker) { - if (cachedClearTimeout === clearTimeout) { - //normal enviroments in sane situations - return clearTimeout(marker); - } - // if clearTimeout wasn't available but was latter defined - if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { - cachedClearTimeout = clearTimeout; - return clearTimeout(marker); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedClearTimeout(marker); - } catch (e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedClearTimeout.call(null, marker); - } catch (e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. - // Some versions of I.E. have different rules for clearTimeout vs setTimeout - return cachedClearTimeout.call(this, marker); - } - } - - - - } - var queue = []; - var draining = false; - var currentQueue; - var queueIndex = -1; - - function cleanUpNextTick() { - if (!draining || !currentQueue) { - return; - } - draining = false; - if (currentQueue.length) { - queue = currentQueue.concat(queue); - } else { - queueIndex = -1; - } - if (queue.length) { - drainQueue(); - } - } - - function drainQueue() { - if (draining) { - return; - } - var timeout = runTimeout(cleanUpNextTick); - draining = true; - - var len = queue.length; - while(len) { - currentQueue = queue; - queue = []; - while (++queueIndex < len) { - if (currentQueue) { - currentQueue[queueIndex].run(); - } - } - queueIndex = -1; - len = queue.length; - } - currentQueue = null; - draining = false; - runClearTimeout(timeout); - } - - process.nextTick = function (fun) { - var args = new Array(arguments.length - 1); - if (arguments.length > 1) { - for (var i = 1; i < arguments.length; i++) { - args[i - 1] = arguments[i]; - } - } - queue.push(new Item(fun, args)); - if (queue.length === 1 && !draining) { - runTimeout(drainQueue); - } - }; - - // v8 likes predictible objects - function Item(fun, array) { - this.fun = fun; - this.array = array; - } - Item.prototype.run = function () { - this.fun.apply(null, this.array); - }; - process.title = 'browser'; - process.browser = true; - process.env = {}; - process.argv = []; - process.version = ''; // empty string to avoid regexp issues - process.versions = {}; - - function noop() {} - - process.on = noop; - process.addListener = noop; - process.once = noop; - process.off = noop; - process.removeListener = noop; - process.removeAllListeners = noop; - process.emit = noop; - process.prependListener = noop; - process.prependOnceListener = noop; - - process.listeners = function (name) { return [] } - - process.binding = function (name) { - throw new Error('process.binding is not supported'); - }; - - process.cwd = function () { return '/' }; - process.chdir = function (dir) { - throw new Error('process.chdir is not supported'); - }; - process.umask = function() { return 0; }; - - -/***/ }), -/* 339 */ -/***/ (function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(Buffer) {'use strict'; - - /** - * Normalizes our expected stringified form of a function across versions of node - * @param {Function} fn The function to stringify - */ - - function normalizedFunctionString(fn) { - return fn.toString().replace(/function *\(/, 'function ('); - } - - function newBuffer(item, encoding) { - return new Buffer(item, encoding); - } - - function allocBuffer() { - return Buffer.alloc.apply(Buffer, arguments); - } - - function toBuffer() { - return Buffer.from.apply(Buffer, arguments); - } - - module.exports = { - normalizedFunctionString: normalizedFunctionString, - allocBuffer: typeof Buffer.alloc === 'function' ? allocBuffer : newBuffer, - toBuffer: typeof Buffer.from === 'function' ? toBuffer : newBuffer - }; - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(334).Buffer)) - -/***/ }), -/* 340 */ -/***/ (function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(global, process) {// Copyright Joyent, Inc. and other Node contributors. - // - // Permission is hereby granted, free of charge, to any person obtaining a - // copy of this software and associated documentation files (the - // "Software"), to deal in the Software without restriction, including - // without limitation the rights to use, copy, modify, merge, publish, - // distribute, sublicense, and/or sell copies of the Software, and to permit - // persons to whom the Software is furnished to do so, subject to the - // following conditions: - // - // The above copyright notice and this permission notice shall be included - // in all copies or substantial portions of the Software. - // - // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS - // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN - // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR - // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE - // USE OR OTHER DEALINGS IN THE SOFTWARE. - - var formatRegExp = /%[sdj%]/g; - exports.format = function(f) { - if (!isString(f)) { - var objects = []; - for (var i = 0; i < arguments.length; i++) { - objects.push(inspect(arguments[i])); - } - return objects.join(' '); - } - - var i = 1; - var args = arguments; - var len = args.length; - var str = String(f).replace(formatRegExp, function(x) { - if (x === '%%') return '%'; - if (i >= len) return x; - switch (x) { - case '%s': return String(args[i++]); - case '%d': return Number(args[i++]); - case '%j': - try { - return JSON.stringify(args[i++]); - } catch (_) { - return '[Circular]'; - } - default: - return x; - } - }); - for (var x = args[i]; i < len; x = args[++i]) { - if (isNull(x) || !isObject(x)) { - str += ' ' + x; - } else { - str += ' ' + inspect(x); - } - } - return str; - }; - - - // Mark that a method should not be used. - // Returns a modified function which warns once by default. - // If --no-deprecation is set, then it is a no-op. - exports.deprecate = function(fn, msg) { - // Allow for deprecating things in the process of starting up. - if (isUndefined(global.process)) { - return function() { - return exports.deprecate(fn, msg).apply(this, arguments); - }; - } - - if (process.noDeprecation === true) { - return fn; - } - - var warned = false; - function deprecated() { - if (!warned) { - if (process.throwDeprecation) { - throw new Error(msg); - } else if (process.traceDeprecation) { - console.trace(msg); - } else { - console.error(msg); - } - warned = true; - } - return fn.apply(this, arguments); - } - - return deprecated; - }; - - - var debugs = {}; - var debugEnviron; - exports.debuglog = function(set) { - if (isUndefined(debugEnviron)) - debugEnviron = process.env.NODE_DEBUG || ''; - set = set.toUpperCase(); - if (!debugs[set]) { - if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { - var pid = process.pid; - debugs[set] = function() { - var msg = exports.format.apply(exports, arguments); - console.error('%s %d: %s', set, pid, msg); - }; - } else { - debugs[set] = function() {}; - } - } - return debugs[set]; - }; - - - /** - * Echos the value of a value. Trys to print the value out - * in the best way possible given the different types. - * - * @param {Object} obj The object to print out. - * @param {Object} opts Optional options object that alters the output. - */ - /* legacy: obj, showHidden, depth, colors*/ - function inspect(obj, opts) { - // default options - var ctx = { - seen: [], - stylize: stylizeNoColor - }; - // legacy... - if (arguments.length >= 3) ctx.depth = arguments[2]; - if (arguments.length >= 4) ctx.colors = arguments[3]; - if (isBoolean(opts)) { - // legacy... - ctx.showHidden = opts; - } else if (opts) { - // got an "options" object - exports._extend(ctx, opts); - } - // set default options - if (isUndefined(ctx.showHidden)) ctx.showHidden = false; - if (isUndefined(ctx.depth)) ctx.depth = 2; - if (isUndefined(ctx.colors)) ctx.colors = false; - if (isUndefined(ctx.customInspect)) ctx.customInspect = true; - if (ctx.colors) ctx.stylize = stylizeWithColor; - return formatValue(ctx, obj, ctx.depth); - } - exports.inspect = inspect; - - - // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics - inspect.colors = { - 'bold' : [1, 22], - 'italic' : [3, 23], - 'underline' : [4, 24], - 'inverse' : [7, 27], - 'white' : [37, 39], - 'grey' : [90, 39], - 'black' : [30, 39], - 'blue' : [34, 39], - 'cyan' : [36, 39], - 'green' : [32, 39], - 'magenta' : [35, 39], - 'red' : [31, 39], - 'yellow' : [33, 39] - }; - - // Don't use 'blue' not visible on cmd.exe - inspect.styles = { - 'special': 'cyan', - 'number': 'yellow', - 'boolean': 'yellow', - 'undefined': 'grey', - 'null': 'bold', - 'string': 'green', - 'date': 'magenta', - // "name": intentionally not styling - 'regexp': 'red' - }; - - - function stylizeWithColor(str, styleType) { - var style = inspect.styles[styleType]; - - if (style) { - return '\u001b[' + inspect.colors[style][0] + 'm' + str + - '\u001b[' + inspect.colors[style][1] + 'm'; - } else { - return str; - } - } - - - function stylizeNoColor(str, styleType) { - return str; - } - - - function arrayToHash(array) { - var hash = {}; - - array.forEach(function(val, idx) { - hash[val] = true; - }); - - return hash; - } - - - function formatValue(ctx, value, recurseTimes) { - // Provide a hook for user-specified inspect functions. - // Check that value is an object with an inspect function on it - if (ctx.customInspect && - value && - isFunction(value.inspect) && - // Filter out the util module, it's inspect function is special - value.inspect !== exports.inspect && - // Also filter out any prototype objects using the circular check. - !(value.constructor && value.constructor.prototype === value)) { - var ret = value.inspect(recurseTimes, ctx); - if (!isString(ret)) { - ret = formatValue(ctx, ret, recurseTimes); - } - return ret; - } - - // Primitive types cannot have properties - var primitive = formatPrimitive(ctx, value); - if (primitive) { - return primitive; - } - - // Look up the keys of the object. - var keys = Object.keys(value); - var visibleKeys = arrayToHash(keys); - - if (ctx.showHidden) { - keys = Object.getOwnPropertyNames(value); - } - - // IE doesn't make error fields non-enumerable - // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx - if (isError(value) - && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { - return formatError(value); - } - - // Some type of object without properties can be shortcutted. - if (keys.length === 0) { - if (isFunction(value)) { - var name = value.name ? ': ' + value.name : ''; - return ctx.stylize('[Function' + name + ']', 'special'); - } - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } - if (isDate(value)) { - return ctx.stylize(Date.prototype.toString.call(value), 'date'); - } - if (isError(value)) { - return formatError(value); - } - } - - var base = '', array = false, braces = ['{', '}']; - - // Make Array say that they are Array - if (isArray(value)) { - array = true; - braces = ['[', ']']; - } - - // Make functions say that they are functions - if (isFunction(value)) { - var n = value.name ? ': ' + value.name : ''; - base = ' [Function' + n + ']'; - } - - // Make RegExps say that they are RegExps - if (isRegExp(value)) { - base = ' ' + RegExp.prototype.toString.call(value); - } - - // Make dates with properties first say the date - if (isDate(value)) { - base = ' ' + Date.prototype.toUTCString.call(value); - } - - // Make error with message first say the error - if (isError(value)) { - base = ' ' + formatError(value); - } - - if (keys.length === 0 && (!array || value.length == 0)) { - return braces[0] + base + braces[1]; - } - - if (recurseTimes < 0) { - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } else { - return ctx.stylize('[Object]', 'special'); - } - } - - ctx.seen.push(value); - - var output; - if (array) { - output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); - } else { - output = keys.map(function(key) { - return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); - }); - } - - ctx.seen.pop(); - - return reduceToSingleString(output, base, braces); - } - - - function formatPrimitive(ctx, value) { - if (isUndefined(value)) - return ctx.stylize('undefined', 'undefined'); - if (isString(value)) { - var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') - .replace(/'/g, "\\'") - .replace(/\\"/g, '"') + '\''; - return ctx.stylize(simple, 'string'); - } - if (isNumber(value)) - return ctx.stylize('' + value, 'number'); - if (isBoolean(value)) - return ctx.stylize('' + value, 'boolean'); - // For some reason typeof null is "object", so special case here. - if (isNull(value)) - return ctx.stylize('null', 'null'); - } - - - function formatError(value) { - return '[' + Error.prototype.toString.call(value) + ']'; - } - - - function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { - var output = []; - for (var i = 0, l = value.length; i < l; ++i) { - if (hasOwnProperty(value, String(i))) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - String(i), true)); - } else { - output.push(''); - } - } - keys.forEach(function(key) { - if (!key.match(/^\d+$/)) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - key, true)); - } - }); - return output; - } - - - function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { - var name, str, desc; - desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; - if (desc.get) { - if (desc.set) { - str = ctx.stylize('[Getter/Setter]', 'special'); - } else { - str = ctx.stylize('[Getter]', 'special'); - } - } else { - if (desc.set) { - str = ctx.stylize('[Setter]', 'special'); - } - } - if (!hasOwnProperty(visibleKeys, key)) { - name = '[' + key + ']'; - } - if (!str) { - if (ctx.seen.indexOf(desc.value) < 0) { - if (isNull(recurseTimes)) { - str = formatValue(ctx, desc.value, null); - } else { - str = formatValue(ctx, desc.value, recurseTimes - 1); - } - if (str.indexOf('\n') > -1) { - if (array) { - str = str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n').substr(2); - } else { - str = '\n' + str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n'); - } - } - } else { - str = ctx.stylize('[Circular]', 'special'); - } - } - if (isUndefined(name)) { - if (array && key.match(/^\d+$/)) { - return str; - } - name = JSON.stringify('' + key); - if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { - name = name.substr(1, name.length - 2); - name = ctx.stylize(name, 'name'); - } else { - name = name.replace(/'/g, "\\'") - .replace(/\\"/g, '"') - .replace(/(^"|"$)/g, "'"); - name = ctx.stylize(name, 'string'); - } - } - - return name + ': ' + str; - } - - - function reduceToSingleString(output, base, braces) { - var numLinesEst = 0; - var length = output.reduce(function(prev, cur) { - numLinesEst++; - if (cur.indexOf('\n') >= 0) numLinesEst++; - return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; - }, 0); - - if (length > 60) { - return braces[0] + - (base === '' ? '' : base + '\n ') + - ' ' + - output.join(',\n ') + - ' ' + - braces[1]; - } - - return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; - } - - - // NOTE: These type checking functions intentionally don't use `instanceof` - // because it is fragile and can be easily faked with `Object.create()`. - function isArray(ar) { - return Array.isArray(ar); - } - exports.isArray = isArray; - - function isBoolean(arg) { - return typeof arg === 'boolean'; - } - exports.isBoolean = isBoolean; - - function isNull(arg) { - return arg === null; - } - exports.isNull = isNull; - - function isNullOrUndefined(arg) { - return arg == null; - } - exports.isNullOrUndefined = isNullOrUndefined; - - function isNumber(arg) { - return typeof arg === 'number'; - } - exports.isNumber = isNumber; - - function isString(arg) { - return typeof arg === 'string'; - } - exports.isString = isString; - - function isSymbol(arg) { - return typeof arg === 'symbol'; - } - exports.isSymbol = isSymbol; - - function isUndefined(arg) { - return arg === void 0; - } - exports.isUndefined = isUndefined; - - function isRegExp(re) { - return isObject(re) && objectToString(re) === '[object RegExp]'; - } - exports.isRegExp = isRegExp; - - function isObject(arg) { - return typeof arg === 'object' && arg !== null; - } - exports.isObject = isObject; - - function isDate(d) { - return isObject(d) && objectToString(d) === '[object Date]'; - } - exports.isDate = isDate; - - function isError(e) { - return isObject(e) && - (objectToString(e) === '[object Error]' || e instanceof Error); - } - exports.isError = isError; - - function isFunction(arg) { - return typeof arg === 'function'; - } - exports.isFunction = isFunction; - - function isPrimitive(arg) { - return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; - } - exports.isPrimitive = isPrimitive; - - exports.isBuffer = __webpack_require__(341); - - function objectToString(o) { - return Object.prototype.toString.call(o); - } - - - function pad(n) { - return n < 10 ? '0' + n.toString(10) : n.toString(10); - } - - - var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', - 'Oct', 'Nov', 'Dec']; - - // 26 Feb 16:19:34 - function timestamp() { - var d = new Date(); - var time = [pad(d.getHours()), - pad(d.getMinutes()), - pad(d.getSeconds())].join(':'); - return [d.getDate(), months[d.getMonth()], time].join(' '); - } - - - // log is just a thin wrapper to console.log that prepends a timestamp - exports.log = function() { - console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); - }; - - - /** - * Inherit the prototype methods from one constructor into another. - * - * The Function.prototype.inherits from lang.js rewritten as a standalone - * function (not on Function.prototype). NOTE: If this file is to be loaded - * during bootstrapping this function needs to be rewritten using some native - * functions as prototype setup using normal JavaScript does not work as - * expected during bootstrapping (see mirror.js in r114903). - * - * @param {function} ctor Constructor function which needs to inherit the - * prototype. - * @param {function} superCtor Constructor function to inherit prototype from. - */ - exports.inherits = __webpack_require__(342); - - exports._extend = function(origin, add) { - // Don't do anything if add isn't an object - if (!add || !isObject(add)) return origin; - - var keys = Object.keys(add); - var i = keys.length; - while (i--) { - origin[keys[i]] = add[keys[i]]; - } - return origin; - }; - - function hasOwnProperty(obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop); - } - - /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()), __webpack_require__(338))) - -/***/ }), -/* 341 */ -/***/ (function(module, exports) { - - module.exports = function isBuffer(arg) { - return arg && typeof arg === 'object' - && typeof arg.copy === 'function' - && typeof arg.fill === 'function' - && typeof arg.readUInt8 === 'function'; - } - -/***/ }), -/* 342 */ -/***/ (function(module, exports) { - - if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }); - }; - } else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - var TempCtor = function () {} - TempCtor.prototype = superCtor.prototype - ctor.prototype = new TempCtor() - ctor.prototype.constructor = ctor - } - } - - -/***/ }), -/* 343 */ -/***/ (function(module, exports) { - - /** - * A class representation of the BSON RegExp type. - * - * @class - * @return {BSONRegExp} A MinKey instance - */ - function BSONRegExp(pattern, options) { - if (!(this instanceof BSONRegExp)) return new BSONRegExp(); - - // Execute - this._bsontype = 'BSONRegExp'; - this.pattern = pattern || ''; - this.options = options || ''; - - // Validate options - for (var i = 0; i < this.options.length; i++) { - if (!(this.options[i] === 'i' || this.options[i] === 'm' || this.options[i] === 'x' || this.options[i] === 'l' || this.options[i] === 's' || this.options[i] === 'u')) { - throw new Error('the regular expression options [' + this.options[i] + '] is not supported'); - } - } - } - - module.exports = BSONRegExp; - module.exports.BSONRegExp = BSONRegExp; - -/***/ }), -/* 344 */ -/***/ (function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(Buffer) {// Custom inspect property name / symbol. - var inspect = Buffer ? __webpack_require__(340).inspect.custom || 'inspect' : 'inspect'; - - /** - * A class representation of the BSON Symbol type. - * - * @class - * @deprecated - * @param {string} value the string representing the symbol. - * @return {Symbol} - */ - function Symbol(value) { - if (!(this instanceof Symbol)) return new Symbol(value); - this._bsontype = 'Symbol'; - this.value = value; - } - - /** - * Access the wrapped string value. - * - * @method - * @return {String} returns the wrapped string. - */ - Symbol.prototype.valueOf = function () { - return this.value; - }; - - /** - * @ignore - */ - Symbol.prototype.toString = function () { - return this.value; - }; - - /** - * @ignore - */ - Symbol.prototype[inspect] = function () { - return this.value; - }; - - /** - * @ignore - */ - Symbol.prototype.toJSON = function () { - return this.value; - }; - - module.exports = Symbol; - module.exports.Symbol = Symbol; - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(334).Buffer)) - -/***/ }), -/* 345 */ -/***/ (function(module, exports) { - - /** - * A class representation of a BSON Int32 type. - * - * @class - * @param {number} value the number we want to represent as an int32. - * @return {Int32} - */ - var Int32 = function (value) { - if (!(this instanceof Int32)) return new Int32(value); - - this._bsontype = 'Int32'; - this.value = value; - }; - - /** - * Access the number value. - * - * @method - * @return {number} returns the wrapped int32 number. - */ - Int32.prototype.valueOf = function () { - return this.value; - }; - - /** - * @ignore - */ - Int32.prototype.toJSON = function () { - return this.value; - }; - - module.exports = Int32; - module.exports.Int32 = Int32; - -/***/ }), -/* 346 */ -/***/ (function(module, exports) { - - /** - * A class representation of the BSON Code type. - * - * @class - * @param {(string|function)} code a string or function. - * @param {Object} [scope] an optional scope for the function. - * @return {Code} - */ - var Code = function Code(code, scope) { - if (!(this instanceof Code)) return new Code(code, scope); - this._bsontype = 'Code'; - this.code = code; - this.scope = scope; - }; - - /** - * @ignore - */ - Code.prototype.toJSON = function () { - return { scope: this.scope, code: this.code }; - }; - - module.exports = Code; - module.exports.Code = Code; - -/***/ }), -/* 347 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - - var Long = __webpack_require__(330); - - var PARSE_STRING_REGEXP = /^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/; - var PARSE_INF_REGEXP = /^(\+|-)?(Infinity|inf)$/i; - var PARSE_NAN_REGEXP = /^(\+|-)?NaN$/i; - - var EXPONENT_MAX = 6111; - var EXPONENT_MIN = -6176; - var EXPONENT_BIAS = 6176; - var MAX_DIGITS = 34; - - // Nan value bits as 32 bit values (due to lack of longs) - var NAN_BUFFER = [0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00].reverse(); - // Infinity value bits 32 bit values (due to lack of longs) - var INF_NEGATIVE_BUFFER = [0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00].reverse(); - var INF_POSITIVE_BUFFER = [0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00].reverse(); - - var EXPONENT_REGEX = /^([-+])?(\d+)?$/; - - var utils = __webpack_require__(339); - - // Detect if the value is a digit - var isDigit = function (value) { - return !isNaN(parseInt(value, 10)); - }; - - // Divide two uint128 values - var divideu128 = function (value) { - var DIVISOR = Long.fromNumber(1000 * 1000 * 1000); - var _rem = Long.fromNumber(0); - var i = 0; - - if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) { - return { quotient: value, rem: _rem }; - } - - for (i = 0; i <= 3; i++) { - // Adjust remainder to match value of next dividend - _rem = _rem.shiftLeft(32); - // Add the divided to _rem - _rem = _rem.add(new Long(value.parts[i], 0)); - value.parts[i] = _rem.div(DIVISOR).low_; - _rem = _rem.modulo(DIVISOR); - } - - return { quotient: value, rem: _rem }; - }; - - // Multiply two Long values and return the 128 bit value - var multiply64x2 = function (left, right) { - if (!left && !right) { - return { high: Long.fromNumber(0), low: Long.fromNumber(0) }; - } - - var leftHigh = left.shiftRightUnsigned(32); - var leftLow = new Long(left.getLowBits(), 0); - var rightHigh = right.shiftRightUnsigned(32); - var rightLow = new Long(right.getLowBits(), 0); - - var productHigh = leftHigh.multiply(rightHigh); - var productMid = leftHigh.multiply(rightLow); - var productMid2 = leftLow.multiply(rightHigh); - var productLow = leftLow.multiply(rightLow); - - productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); - productMid = new Long(productMid.getLowBits(), 0).add(productMid2).add(productLow.shiftRightUnsigned(32)); - - productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); - productLow = productMid.shiftLeft(32).add(new Long(productLow.getLowBits(), 0)); - - // Return the 128 bit result - return { high: productHigh, low: productLow }; - }; - - var lessThan = function (left, right) { - // Make values unsigned - var uhleft = left.high_ >>> 0; - var uhright = right.high_ >>> 0; - - // Compare high bits first - if (uhleft < uhright) { - return true; - } else if (uhleft === uhright) { - var ulleft = left.low_ >>> 0; - var ulright = right.low_ >>> 0; - if (ulleft < ulright) return true; - } - - return false; - }; - - // var longtoHex = function(value) { - // var buffer = utils.allocBuffer(8); - // var index = 0; - // // Encode the low 64 bits of the decimal - // // Encode low bits - // buffer[index++] = value.low_ & 0xff; - // buffer[index++] = (value.low_ >> 8) & 0xff; - // buffer[index++] = (value.low_ >> 16) & 0xff; - // buffer[index++] = (value.low_ >> 24) & 0xff; - // // Encode high bits - // buffer[index++] = value.high_ & 0xff; - // buffer[index++] = (value.high_ >> 8) & 0xff; - // buffer[index++] = (value.high_ >> 16) & 0xff; - // buffer[index++] = (value.high_ >> 24) & 0xff; - // return buffer.reverse().toString('hex'); - // }; - - // var int32toHex = function(value) { - // var buffer = utils.allocBuffer(4); - // var index = 0; - // // Encode the low 64 bits of the decimal - // // Encode low bits - // buffer[index++] = value & 0xff; - // buffer[index++] = (value >> 8) & 0xff; - // buffer[index++] = (value >> 16) & 0xff; - // buffer[index++] = (value >> 24) & 0xff; - // return buffer.reverse().toString('hex'); - // }; - - /** - * A class representation of the BSON Decimal128 type. - * - * @class - * @param {Buffer} bytes a buffer containing the raw Decimal128 bytes. - * @return {Double} - */ - var Decimal128 = function (bytes) { - this._bsontype = 'Decimal128'; - this.bytes = bytes; - }; - - /** - * Create a Decimal128 instance from a string representation - * - * @method - * @param {string} string a numeric string representation. - * @return {Decimal128} returns a Decimal128 instance. - */ - Decimal128.fromString = function (string) { - // Parse state tracking - var isNegative = false; - var sawRadix = false; - var foundNonZero = false; - - // Total number of significant digits (no leading or trailing zero) - var significantDigits = 0; - // Total number of significand digits read - var nDigitsRead = 0; - // Total number of digits (no leading zeros) - var nDigits = 0; - // The number of the digits after radix - var radixPosition = 0; - // The index of the first non-zero in *str* - var firstNonZero = 0; - - // Digits Array - var digits = [0]; - // The number of digits in digits - var nDigitsStored = 0; - // Insertion pointer for digits - var digitsInsert = 0; - // The index of the first non-zero digit - var firstDigit = 0; - // The index of the last digit - var lastDigit = 0; - - // Exponent - var exponent = 0; - // loop index over array - var i = 0; - // The high 17 digits of the significand - var significandHigh = [0, 0]; - // The low 17 digits of the significand - var significandLow = [0, 0]; - // The biased exponent - var biasedExponent = 0; - - // Read index - var index = 0; - - // Trim the string - string = string.trim(); - - // Naively prevent against REDOS attacks. - // TODO: implementing a custom parsing for this, or refactoring the regex would yield - // further gains. - if (string.length >= 7000) { - throw new Error('' + string + ' not a valid Decimal128 string'); - } - - // Results - var stringMatch = string.match(PARSE_STRING_REGEXP); - var infMatch = string.match(PARSE_INF_REGEXP); - var nanMatch = string.match(PARSE_NAN_REGEXP); - - // Validate the string - if (!stringMatch && !infMatch && !nanMatch || string.length === 0) { - throw new Error('' + string + ' not a valid Decimal128 string'); - } - - // Check if we have an illegal exponent format - if (stringMatch && stringMatch[4] && stringMatch[2] === undefined) { - throw new Error('' + string + ' not a valid Decimal128 string'); - } - - // Get the negative or positive sign - if (string[index] === '+' || string[index] === '-') { - isNegative = string[index++] === '-'; - } - - // Check if user passed Infinity or NaN - if (!isDigit(string[index]) && string[index] !== '.') { - if (string[index] === 'i' || string[index] === 'I') { - return new Decimal128(utils.toBuffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); - } else if (string[index] === 'N') { - return new Decimal128(utils.toBuffer(NAN_BUFFER)); - } - } - - // Read all the digits - while (isDigit(string[index]) || string[index] === '.') { - if (string[index] === '.') { - if (sawRadix) { - return new Decimal128(utils.toBuffer(NAN_BUFFER)); - } - - sawRadix = true; - index = index + 1; - continue; - } - - if (nDigitsStored < 34) { - if (string[index] !== '0' || foundNonZero) { - if (!foundNonZero) { - firstNonZero = nDigitsRead; - } - - foundNonZero = true; - - // Only store 34 digits - digits[digitsInsert++] = parseInt(string[index], 10); - nDigitsStored = nDigitsStored + 1; - } - } - - if (foundNonZero) { - nDigits = nDigits + 1; - } - - if (sawRadix) { - radixPosition = radixPosition + 1; - } - - nDigitsRead = nDigitsRead + 1; - index = index + 1; - } - - if (sawRadix && !nDigitsRead) { - throw new Error('' + string + ' not a valid Decimal128 string'); - } - - // Read exponent if exists - if (string[index] === 'e' || string[index] === 'E') { - // Read exponent digits - var match = string.substr(++index).match(EXPONENT_REGEX); - - // No digits read - if (!match || !match[2]) { - return new Decimal128(utils.toBuffer(NAN_BUFFER)); - } - - // Get exponent - exponent = parseInt(match[0], 10); - - // Adjust the index - index = index + match[0].length; - } - - // Return not a number - if (string[index]) { - return new Decimal128(utils.toBuffer(NAN_BUFFER)); - } - - // Done reading input - // Find first non-zero digit in digits - firstDigit = 0; - - if (!nDigitsStored) { - firstDigit = 0; - lastDigit = 0; - digits[0] = 0; - nDigits = 1; - nDigitsStored = 1; - significantDigits = 0; - } else { - lastDigit = nDigitsStored - 1; - significantDigits = nDigits; - - if (exponent !== 0 && significantDigits !== 1) { - while (string[firstNonZero + significantDigits - 1] === '0') { - significantDigits = significantDigits - 1; - } - } - } - - // Normalization of exponent - // Correct exponent based on radix position, and shift significand as needed - // to represent user input - - // Overflow prevention - if (exponent <= radixPosition && radixPosition - exponent > 1 << 14) { - exponent = EXPONENT_MIN; - } else { - exponent = exponent - radixPosition; - } - - // Attempt to normalize the exponent - while (exponent > EXPONENT_MAX) { - // Shift exponent to significand and decrease - lastDigit = lastDigit + 1; - - if (lastDigit - firstDigit > MAX_DIGITS) { - // Check if we have a zero then just hard clamp, otherwise fail - var digitsString = digits.join(''); - if (digitsString.match(/^0+$/)) { - exponent = EXPONENT_MAX; - break; - } else { - return new Decimal128(utils.toBuffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); - } - } - - exponent = exponent - 1; - } - - while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) { - // Shift last digit - if (lastDigit === 0) { - exponent = EXPONENT_MIN; - significantDigits = 0; - break; - } - - if (nDigitsStored < nDigits) { - // adjust to match digits not stored - nDigits = nDigits - 1; - } else { - // adjust to round - lastDigit = lastDigit - 1; - } - - if (exponent < EXPONENT_MAX) { - exponent = exponent + 1; - } else { - // Check if we have a zero then just hard clamp, otherwise fail - digitsString = digits.join(''); - if (digitsString.match(/^0+$/)) { - exponent = EXPONENT_MAX; - break; - } else { - return new Decimal128(utils.toBuffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); - } - } - } - - // Round - // We've normalized the exponent, but might still need to round. - if (lastDigit - firstDigit + 1 < significantDigits && string[significantDigits] !== '0') { - var endOfString = nDigitsRead; - - // If we have seen a radix point, 'string' is 1 longer than we have - // documented with ndigits_read, so inc the position of the first nonzero - // digit and the position that digits are read to. - if (sawRadix && exponent === EXPONENT_MIN) { - firstNonZero = firstNonZero + 1; - endOfString = endOfString + 1; - } - - var roundDigit = parseInt(string[firstNonZero + lastDigit + 1], 10); - var roundBit = 0; - - if (roundDigit >= 5) { - roundBit = 1; - - if (roundDigit === 5) { - roundBit = digits[lastDigit] % 2 === 1; - - for (i = firstNonZero + lastDigit + 2; i < endOfString; i++) { - if (parseInt(string[i], 10)) { - roundBit = 1; - break; - } - } - } - } - - if (roundBit) { - var dIdx = lastDigit; - - for (; dIdx >= 0; dIdx--) { - if (++digits[dIdx] > 9) { - digits[dIdx] = 0; - - // overflowed most significant digit - if (dIdx === 0) { - if (exponent < EXPONENT_MAX) { - exponent = exponent + 1; - digits[dIdx] = 1; - } else { - return new Decimal128(utils.toBuffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); - } - } - } else { - break; - } - } - } - } - - // Encode significand - // The high 17 digits of the significand - significandHigh = Long.fromNumber(0); - // The low 17 digits of the significand - significandLow = Long.fromNumber(0); - - // read a zero - if (significantDigits === 0) { - significandHigh = Long.fromNumber(0); - significandLow = Long.fromNumber(0); - } else if (lastDigit - firstDigit < 17) { - dIdx = firstDigit; - significandLow = Long.fromNumber(digits[dIdx++]); - significandHigh = new Long(0, 0); - - for (; dIdx <= lastDigit; dIdx++) { - significandLow = significandLow.multiply(Long.fromNumber(10)); - significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); - } - } else { - dIdx = firstDigit; - significandHigh = Long.fromNumber(digits[dIdx++]); - - for (; dIdx <= lastDigit - 17; dIdx++) { - significandHigh = significandHigh.multiply(Long.fromNumber(10)); - significandHigh = significandHigh.add(Long.fromNumber(digits[dIdx])); - } - - significandLow = Long.fromNumber(digits[dIdx++]); - - for (; dIdx <= lastDigit; dIdx++) { - significandLow = significandLow.multiply(Long.fromNumber(10)); - significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); - } - } - - var significand = multiply64x2(significandHigh, Long.fromString('100000000000000000')); - - significand.low = significand.low.add(significandLow); - - if (lessThan(significand.low, significandLow)) { - significand.high = significand.high.add(Long.fromNumber(1)); - } - - // Biased exponent - biasedExponent = exponent + EXPONENT_BIAS; - var dec = { low: Long.fromNumber(0), high: Long.fromNumber(0) }; - - // Encode combination, exponent, and significand. - if (significand.high.shiftRightUnsigned(49).and(Long.fromNumber(1)).equals(Long.fromNumber)) { - // Encode '11' into bits 1 to 3 - dec.high = dec.high.or(Long.fromNumber(0x3).shiftLeft(61)); - dec.high = dec.high.or(Long.fromNumber(biasedExponent).and(Long.fromNumber(0x3fff).shiftLeft(47))); - dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x7fffffffffff))); - } else { - dec.high = dec.high.or(Long.fromNumber(biasedExponent & 0x3fff).shiftLeft(49)); - dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x1ffffffffffff))); - } - - dec.low = significand.low; - - // Encode sign - if (isNegative) { - dec.high = dec.high.or(Long.fromString('9223372036854775808')); - } - - // Encode into a buffer - var buffer = utils.allocBuffer(16); - index = 0; - - // Encode the low 64 bits of the decimal - // Encode low bits - buffer[index++] = dec.low.low_ & 0xff; - buffer[index++] = dec.low.low_ >> 8 & 0xff; - buffer[index++] = dec.low.low_ >> 16 & 0xff; - buffer[index++] = dec.low.low_ >> 24 & 0xff; - // Encode high bits - buffer[index++] = dec.low.high_ & 0xff; - buffer[index++] = dec.low.high_ >> 8 & 0xff; - buffer[index++] = dec.low.high_ >> 16 & 0xff; - buffer[index++] = dec.low.high_ >> 24 & 0xff; - - // Encode the high 64 bits of the decimal - // Encode low bits - buffer[index++] = dec.high.low_ & 0xff; - buffer[index++] = dec.high.low_ >> 8 & 0xff; - buffer[index++] = dec.high.low_ >> 16 & 0xff; - buffer[index++] = dec.high.low_ >> 24 & 0xff; - // Encode high bits - buffer[index++] = dec.high.high_ & 0xff; - buffer[index++] = dec.high.high_ >> 8 & 0xff; - buffer[index++] = dec.high.high_ >> 16 & 0xff; - buffer[index++] = dec.high.high_ >> 24 & 0xff; - - // Return the new Decimal128 - return new Decimal128(buffer); - }; - - // Extract least significant 5 bits - var COMBINATION_MASK = 0x1f; - // Extract least significant 14 bits - var EXPONENT_MASK = 0x3fff; - // Value of combination field for Inf - var COMBINATION_INFINITY = 30; - // Value of combination field for NaN - var COMBINATION_NAN = 31; - // Value of combination field for NaN - // var COMBINATION_SNAN = 32; - // decimal128 exponent bias - EXPONENT_BIAS = 6176; - - /** - * Create a string representation of the raw Decimal128 value - * - * @method - * @return {string} returns a Decimal128 string representation. - */ - Decimal128.prototype.toString = function () { - // Note: bits in this routine are referred to starting at 0, - // from the sign bit, towards the coefficient. - - // bits 0 - 31 - var high; - // bits 32 - 63 - var midh; - // bits 64 - 95 - var midl; - // bits 96 - 127 - var low; - // bits 1 - 5 - var combination; - // decoded biased exponent (14 bits) - var biased_exponent; - // the number of significand digits - var significand_digits = 0; - // the base-10 digits in the significand - var significand = new Array(36); - for (var i = 0; i < significand.length; i++) significand[i] = 0; - // read pointer into significand - var index = 0; - - // unbiased exponent - var exponent; - // the exponent if scientific notation is used - var scientific_exponent; - - // true if the number is zero - var is_zero = false; - - // the most signifcant significand bits (50-46) - var significand_msb; - // temporary storage for significand decoding - var significand128 = { parts: new Array(4) }; - // indexing variables - i; - var j, k; - - // Output string - var string = []; - - // Unpack index - index = 0; - - // Buffer reference - var buffer = this.bytes; - - // Unpack the low 64bits into a long - low = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - midl = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - - // Unpack the high 64bits into a long - midh = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - high = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - - // Unpack index - index = 0; - - // Create the state of the decimal - var dec = { - low: new Long(low, midl), - high: new Long(midh, high) - }; - - if (dec.high.lessThan(Long.ZERO)) { - string.push('-'); - } - - // Decode combination field and exponent - combination = high >> 26 & COMBINATION_MASK; - - if (combination >> 3 === 3) { - // Check for 'special' values - if (combination === COMBINATION_INFINITY) { - return string.join('') + 'Infinity'; - } else if (combination === COMBINATION_NAN) { - return 'NaN'; - } else { - biased_exponent = high >> 15 & EXPONENT_MASK; - significand_msb = 0x08 + (high >> 14 & 0x01); - } - } else { - significand_msb = high >> 14 & 0x07; - biased_exponent = high >> 17 & EXPONENT_MASK; - } - - exponent = biased_exponent - EXPONENT_BIAS; - - // Create string of significand digits - - // Convert the 114-bit binary number represented by - // (significand_high, significand_low) to at most 34 decimal - // digits through modulo and division. - significand128.parts[0] = (high & 0x3fff) + ((significand_msb & 0xf) << 14); - significand128.parts[1] = midh; - significand128.parts[2] = midl; - significand128.parts[3] = low; - - if (significand128.parts[0] === 0 && significand128.parts[1] === 0 && significand128.parts[2] === 0 && significand128.parts[3] === 0) { - is_zero = true; - } else { - for (k = 3; k >= 0; k--) { - var least_digits = 0; - // Peform the divide - var result = divideu128(significand128); - significand128 = result.quotient; - least_digits = result.rem.low_; - - // We now have the 9 least significant digits (in base 2). - // Convert and output to string. - if (!least_digits) continue; - - for (j = 8; j >= 0; j--) { - // significand[k * 9 + j] = Math.round(least_digits % 10); - significand[k * 9 + j] = least_digits % 10; - // least_digits = Math.round(least_digits / 10); - least_digits = Math.floor(least_digits / 10); - } - } - } - - // Output format options: - // Scientific - [-]d.dddE(+/-)dd or [-]dE(+/-)dd - // Regular - ddd.ddd - - if (is_zero) { - significand_digits = 1; - significand[index] = 0; - } else { - significand_digits = 36; - i = 0; - - while (!significand[index]) { - i++; - significand_digits = significand_digits - 1; - index = index + 1; - } - } - - scientific_exponent = significand_digits - 1 + exponent; - - // The scientific exponent checks are dictated by the string conversion - // specification and are somewhat arbitrary cutoffs. - // - // We must check exponent > 0, because if this is the case, the number - // has trailing zeros. However, we *cannot* output these trailing zeros, - // because doing so would change the precision of the value, and would - // change stored data if the string converted number is round tripped. - - if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) { - // Scientific format - string.push(significand[index++]); - significand_digits = significand_digits - 1; - - if (significand_digits) { - string.push('.'); - } - - for (i = 0; i < significand_digits; i++) { - string.push(significand[index++]); - } - - // Exponent - string.push('E'); - if (scientific_exponent > 0) { - string.push('+' + scientific_exponent); - } else { - string.push(scientific_exponent); - } - } else { - // Regular format with no decimal place - if (exponent >= 0) { - for (i = 0; i < significand_digits; i++) { - string.push(significand[index++]); - } - } else { - var radix_position = significand_digits + exponent; - - // non-zero digits before radix - if (radix_position > 0) { - for (i = 0; i < radix_position; i++) { - string.push(significand[index++]); - } - } else { - string.push('0'); - } - - string.push('.'); - // add leading zeros after radix - while (radix_position++ < 0) { - string.push('0'); - } - - for (i = 0; i < significand_digits - Math.max(radix_position - 1, 0); i++) { - string.push(significand[index++]); - } - } - } - - return string.join(''); - }; - - Decimal128.prototype.toJSON = function () { - return { $numberDecimal: this.toString() }; - }; - - module.exports = Decimal128; - module.exports.Decimal128 = Decimal128; - -/***/ }), -/* 348 */ -/***/ (function(module, exports) { - - /** - * A class representation of the BSON MinKey type. - * - * @class - * @return {MinKey} A MinKey instance - */ - function MinKey() { - if (!(this instanceof MinKey)) return new MinKey(); - - this._bsontype = 'MinKey'; - } - - module.exports = MinKey; - module.exports.MinKey = MinKey; - -/***/ }), -/* 349 */ -/***/ (function(module, exports) { - - /** - * A class representation of the BSON MaxKey type. - * - * @class - * @return {MaxKey} A MaxKey instance - */ - function MaxKey() { - if (!(this instanceof MaxKey)) return new MaxKey(); - - this._bsontype = 'MaxKey'; - } - - module.exports = MaxKey; - module.exports.MaxKey = MaxKey; - -/***/ }), -/* 350 */ -/***/ (function(module, exports) { - - /** - * A class representation of the BSON DBRef type. - * - * @class - * @param {string} namespace the collection name. - * @param {ObjectID} oid the reference ObjectID. - * @param {string} [db] optional db name, if omitted the reference is local to the current db. - * @return {DBRef} - */ - function DBRef(namespace, oid, db) { - if (!(this instanceof DBRef)) return new DBRef(namespace, oid, db); - - this._bsontype = 'DBRef'; - this.namespace = namespace; - this.oid = oid; - this.db = db; - } - - /** - * @ignore - * @api private - */ - DBRef.prototype.toJSON = function () { - return { - $ref: this.namespace, - $id: this.oid, - $db: this.db == null ? '' : this.db - }; - }; - - module.exports = DBRef; - module.exports.DBRef = DBRef; - -/***/ }), -/* 351 */ -/***/ (function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(global) {/** - * Module dependencies. - * @ignore - */ - - // Test if we're in Node via presence of "global" not absence of "window" - // to support hybrid environments like Electron - if (typeof global !== 'undefined') { - var Buffer = __webpack_require__(334).Buffer; // TODO just use global Buffer - } - - var utils = __webpack_require__(339); - - /** - * A class representation of the BSON Binary type. - * - * Sub types - * - **BSON.BSON_BINARY_SUBTYPE_DEFAULT**, default BSON type. - * - **BSON.BSON_BINARY_SUBTYPE_FUNCTION**, BSON function type. - * - **BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY**, BSON byte array type. - * - **BSON.BSON_BINARY_SUBTYPE_UUID**, BSON uuid type. - * - **BSON.BSON_BINARY_SUBTYPE_MD5**, BSON md5 type. - * - **BSON.BSON_BINARY_SUBTYPE_USER_DEFINED**, BSON user defined type. - * - * @class - * @param {Buffer} buffer a buffer object containing the binary data. - * @param {Number} [subType] the option binary type. - * @return {Binary} - */ - function Binary(buffer, subType) { - if (!(this instanceof Binary)) return new Binary(buffer, subType); - - if (buffer != null && !(typeof buffer === 'string') && !Buffer.isBuffer(buffer) && !(buffer instanceof Uint8Array) && !Array.isArray(buffer)) { - throw new Error('only String, Buffer, Uint8Array or Array accepted'); - } - - this._bsontype = 'Binary'; - - if (buffer instanceof Number) { - this.sub_type = buffer; - this.position = 0; - } else { - this.sub_type = subType == null ? BSON_BINARY_SUBTYPE_DEFAULT : subType; - this.position = 0; - } - - if (buffer != null && !(buffer instanceof Number)) { - // Only accept Buffer, Uint8Array or Arrays - if (typeof buffer === 'string') { - // Different ways of writing the length of the string for the different types - if (typeof Buffer !== 'undefined') { - this.buffer = utils.toBuffer(buffer); - } else if (typeof Uint8Array !== 'undefined' || Object.prototype.toString.call(buffer) === '[object Array]') { - this.buffer = writeStringToArray(buffer); - } else { - throw new Error('only String, Buffer, Uint8Array or Array accepted'); - } - } else { - this.buffer = buffer; - } - this.position = buffer.length; - } else { - if (typeof Buffer !== 'undefined') { - this.buffer = utils.allocBuffer(Binary.BUFFER_SIZE); - } else if (typeof Uint8Array !== 'undefined') { - this.buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE)); - } else { - this.buffer = new Array(Binary.BUFFER_SIZE); - } - // Set position to start of buffer - this.position = 0; - } - } - - /** - * Updates this binary with byte_value. - * - * @method - * @param {string} byte_value a single byte we wish to write. - */ - Binary.prototype.put = function put(byte_value) { - // If it's a string and a has more than one character throw an error - if (byte_value['length'] != null && typeof byte_value !== 'number' && byte_value.length !== 1) throw new Error('only accepts single character String, Uint8Array or Array'); - if (typeof byte_value !== 'number' && byte_value < 0 || byte_value > 255) throw new Error('only accepts number in a valid unsigned byte range 0-255'); - - // Decode the byte value once - var decoded_byte = null; - if (typeof byte_value === 'string') { - decoded_byte = byte_value.charCodeAt(0); - } else if (byte_value['length'] != null) { - decoded_byte = byte_value[0]; - } else { - decoded_byte = byte_value; - } - - if (this.buffer.length > this.position) { - this.buffer[this.position++] = decoded_byte; - } else { - if (typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer)) { - // Create additional overflow buffer - var buffer = utils.allocBuffer(Binary.BUFFER_SIZE + this.buffer.length); - // Combine the two buffers together - this.buffer.copy(buffer, 0, 0, this.buffer.length); - this.buffer = buffer; - this.buffer[this.position++] = decoded_byte; - } else { - buffer = null; - // Create a new buffer (typed or normal array) - if (Object.prototype.toString.call(this.buffer) === '[object Uint8Array]') { - buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE + this.buffer.length)); - } else { - buffer = new Array(Binary.BUFFER_SIZE + this.buffer.length); - } - - // We need to copy all the content to the new array - for (var i = 0; i < this.buffer.length; i++) { - buffer[i] = this.buffer[i]; - } - - // Reassign the buffer - this.buffer = buffer; - // Write the byte - this.buffer[this.position++] = decoded_byte; - } - } - }; - - /** - * Writes a buffer or string to the binary. - * - * @method - * @param {(Buffer|string)} string a string or buffer to be written to the Binary BSON object. - * @param {number} offset specify the binary of where to write the content. - * @return {null} - */ - Binary.prototype.write = function write(string, offset) { - offset = typeof offset === 'number' ? offset : this.position; - - // If the buffer is to small let's extend the buffer - if (this.buffer.length < offset + string.length) { - var buffer = null; - // If we are in node.js - if (typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer)) { - buffer = utils.allocBuffer(this.buffer.length + string.length); - this.buffer.copy(buffer, 0, 0, this.buffer.length); - } else if (Object.prototype.toString.call(this.buffer) === '[object Uint8Array]') { - // Create a new buffer - buffer = new Uint8Array(new ArrayBuffer(this.buffer.length + string.length)); - // Copy the content - for (var i = 0; i < this.position; i++) { - buffer[i] = this.buffer[i]; - } - } - - // Assign the new buffer - this.buffer = buffer; - } - - if (typeof Buffer !== 'undefined' && Buffer.isBuffer(string) && Buffer.isBuffer(this.buffer)) { - string.copy(this.buffer, offset, 0, string.length); - this.position = offset + string.length > this.position ? offset + string.length : this.position; - // offset = string.length - } else if (typeof Buffer !== 'undefined' && typeof string === 'string' && Buffer.isBuffer(this.buffer)) { - this.buffer.write(string, offset, 'binary'); - this.position = offset + string.length > this.position ? offset + string.length : this.position; - // offset = string.length; - } else if (Object.prototype.toString.call(string) === '[object Uint8Array]' || Object.prototype.toString.call(string) === '[object Array]' && typeof string !== 'string') { - for (i = 0; i < string.length; i++) { - this.buffer[offset++] = string[i]; - } - - this.position = offset > this.position ? offset : this.position; - } else if (typeof string === 'string') { - for (i = 0; i < string.length; i++) { - this.buffer[offset++] = string.charCodeAt(i); - } - - this.position = offset > this.position ? offset : this.position; - } - }; - - /** - * Reads **length** bytes starting at **position**. - * - * @method - * @param {number} position read from the given position in the Binary. - * @param {number} length the number of bytes to read. - * @return {Buffer} - */ - Binary.prototype.read = function read(position, length) { - length = length && length > 0 ? length : this.position; - - // Let's return the data based on the type we have - if (this.buffer['slice']) { - return this.buffer.slice(position, position + length); - } else { - // Create a buffer to keep the result - var buffer = typeof Uint8Array !== 'undefined' ? new Uint8Array(new ArrayBuffer(length)) : new Array(length); - for (var i = 0; i < length; i++) { - buffer[i] = this.buffer[position++]; - } - } - // Return the buffer - return buffer; - }; - - /** - * Returns the value of this binary as a string. - * - * @method - * @return {string} - */ - Binary.prototype.value = function value(asRaw) { - asRaw = asRaw == null ? false : asRaw; - - // Optimize to serialize for the situation where the data == size of buffer - if (asRaw && typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer) && this.buffer.length === this.position) return this.buffer; - - // If it's a node.js buffer object - if (typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer)) { - return asRaw ? this.buffer.slice(0, this.position) : this.buffer.toString('binary', 0, this.position); - } else { - if (asRaw) { - // we support the slice command use it - if (this.buffer['slice'] != null) { - return this.buffer.slice(0, this.position); - } else { - // Create a new buffer to copy content to - var newBuffer = Object.prototype.toString.call(this.buffer) === '[object Uint8Array]' ? new Uint8Array(new ArrayBuffer(this.position)) : new Array(this.position); - // Copy content - for (var i = 0; i < this.position; i++) { - newBuffer[i] = this.buffer[i]; - } - // Return the buffer - return newBuffer; - } - } else { - return convertArraytoUtf8BinaryString(this.buffer, 0, this.position); - } - } - }; - - /** - * Length. - * - * @method - * @return {number} the length of the binary. - */ - Binary.prototype.length = function length() { - return this.position; - }; - - /** - * @ignore - */ - Binary.prototype.toJSON = function () { - return this.buffer != null ? this.buffer.toString('base64') : ''; - }; - - /** - * @ignore - */ - Binary.prototype.toString = function (format) { - return this.buffer != null ? this.buffer.slice(0, this.position).toString(format) : ''; - }; - - /** - * Binary default subtype - * @ignore - */ - var BSON_BINARY_SUBTYPE_DEFAULT = 0; - - /** - * @ignore - */ - var writeStringToArray = function (data) { - // Create a buffer - var buffer = typeof Uint8Array !== 'undefined' ? new Uint8Array(new ArrayBuffer(data.length)) : new Array(data.length); - // Write the content to the buffer - for (var i = 0; i < data.length; i++) { - buffer[i] = data.charCodeAt(i); - } - // Write the string to the buffer - return buffer; - }; - - /** - * Convert Array ot Uint8Array to Binary String - * - * @ignore - */ - var convertArraytoUtf8BinaryString = function (byteArray, startIndex, endIndex) { - var result = ''; - for (var i = startIndex; i < endIndex; i++) { - result = result + String.fromCharCode(byteArray[i]); - } - return result; - }; - - Binary.BUFFER_SIZE = 256; - - /** - * Default BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ - Binary.SUBTYPE_DEFAULT = 0; - /** - * Function BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ - Binary.SUBTYPE_FUNCTION = 1; - /** - * Byte Array BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ - Binary.SUBTYPE_BYTE_ARRAY = 2; - /** - * OLD UUID BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ - Binary.SUBTYPE_UUID_OLD = 3; - /** - * UUID BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ - Binary.SUBTYPE_UUID = 4; - /** - * MD5 BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ - Binary.SUBTYPE_MD5 = 5; - /** - * User BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ - Binary.SUBTYPE_USER_DEFINED = 128; - - /** - * Expose. - */ - module.exports = Binary; - module.exports.Binary = Binary; - /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) - -/***/ }), -/* 352 */ -/***/ (function(module, exports, __webpack_require__) { - - 'use strict'; - - var Long = __webpack_require__(330).Long, - Double = __webpack_require__(331).Double, - Timestamp = __webpack_require__(332).Timestamp, - ObjectID = __webpack_require__(333).ObjectID, - Symbol = __webpack_require__(344).Symbol, - Code = __webpack_require__(346).Code, - MinKey = __webpack_require__(348).MinKey, - MaxKey = __webpack_require__(349).MaxKey, - Decimal128 = __webpack_require__(347), - Int32 = __webpack_require__(345), - DBRef = __webpack_require__(350).DBRef, - BSONRegExp = __webpack_require__(343).BSONRegExp, - Binary = __webpack_require__(351).Binary; - - var utils = __webpack_require__(339); - - var deserialize = function (buffer, options, isArray) { - options = options == null ? {} : options; - var index = options && options.index ? options.index : 0; - // Read the document size - var size = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - - // Ensure buffer is valid size - if (size < 5 || buffer.length < size || size + index > buffer.length) { - throw new Error('corrupt bson message'); - } - - // Illegal end value - if (buffer[index + size - 1] !== 0) { - throw new Error("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00"); - } - - // Start deserializtion - return deserializeObject(buffer, index, options, isArray); - }; - - var deserializeObject = function (buffer, index, options, isArray) { - var evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions']; - var cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions']; - var cacheFunctionsCrc32 = options['cacheFunctionsCrc32'] == null ? false : options['cacheFunctionsCrc32']; - - if (!cacheFunctionsCrc32) var crc32 = null; - - var fieldsAsRaw = options['fieldsAsRaw'] == null ? null : options['fieldsAsRaw']; - - // Return raw bson buffer instead of parsing it - var raw = options['raw'] == null ? false : options['raw']; - - // Return BSONRegExp objects instead of native regular expressions - var bsonRegExp = typeof options['bsonRegExp'] === 'boolean' ? options['bsonRegExp'] : false; - - // Controls the promotion of values vs wrapper classes - var promoteBuffers = options['promoteBuffers'] == null ? false : options['promoteBuffers']; - var promoteLongs = options['promoteLongs'] == null ? true : options['promoteLongs']; - var promoteValues = options['promoteValues'] == null ? true : options['promoteValues']; - - // Set the start index - var startIndex = index; - - // Validate that we have at least 4 bytes of buffer - if (buffer.length < 5) throw new Error('corrupt bson message < 5 bytes long'); - - // Read the document size - var size = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - - // Ensure buffer is valid size - if (size < 5 || size > buffer.length) throw new Error('corrupt bson message'); - - // Create holding object - var object = isArray ? [] : {}; - // Used for arrays to skip having to perform utf8 decoding - var arrayIndex = 0; - - var done = false; - - // While we have more left data left keep parsing - // while (buffer[index + 1] !== 0) { - while (!done) { - // Read the type - var elementType = buffer[index++]; - // If we get a zero it's the last byte, exit - if (elementType === 0) break; - - // Get the start search index - var i = index; - // Locate the end of the c string - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - - // If are at the end of the buffer there is a problem with the document - if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); - var name = isArray ? arrayIndex++ : buffer.toString('utf8', index, i); - - index = i + 1; - - if (elementType === BSON.BSON_DATA_STRING) { - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - if (stringSize <= 0 || stringSize > buffer.length - index || buffer[index + stringSize - 1] !== 0) throw new Error('bad string length in bson'); - object[name] = buffer.toString('utf8', index, index + stringSize - 1); - index = index + stringSize; - } else if (elementType === BSON.BSON_DATA_OID) { - var oid = utils.allocBuffer(12); - buffer.copy(oid, 0, index, index + 12); - object[name] = new ObjectID(oid); - index = index + 12; - } else if (elementType === BSON.BSON_DATA_INT && promoteValues === false) { - object[name] = new Int32(buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24); - } else if (elementType === BSON.BSON_DATA_INT) { - object[name] = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - } else if (elementType === BSON.BSON_DATA_NUMBER && promoteValues === false) { - object[name] = new Double(buffer.readDoubleLE(index)); - index = index + 8; - } else if (elementType === BSON.BSON_DATA_NUMBER) { - object[name] = buffer.readDoubleLE(index); - index = index + 8; - } else if (elementType === BSON.BSON_DATA_DATE) { - var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - object[name] = new Date(new Long(lowBits, highBits).toNumber()); - } else if (elementType === BSON.BSON_DATA_BOOLEAN) { - if (buffer[index] !== 0 && buffer[index] !== 1) throw new Error('illegal boolean type value'); - object[name] = buffer[index++] === 1; - } else if (elementType === BSON.BSON_DATA_OBJECT) { - var _index = index; - var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - if (objectSize <= 0 || objectSize > buffer.length - index) throw new Error('bad embedded document length in bson'); - - // We have a raw value - if (raw) { - object[name] = buffer.slice(index, index + objectSize); - } else { - object[name] = deserializeObject(buffer, _index, options, false); - } - - index = index + objectSize; - } else if (elementType === BSON.BSON_DATA_ARRAY) { - _index = index; - objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - var arrayOptions = options; - - // Stop index - var stopIndex = index + objectSize; - - // All elements of array to be returned as raw bson - if (fieldsAsRaw && fieldsAsRaw[name]) { - arrayOptions = {}; - for (var n in options) arrayOptions[n] = options[n]; - arrayOptions['raw'] = true; - } - - object[name] = deserializeObject(buffer, _index, arrayOptions, true); - index = index + objectSize; - - if (buffer[index - 1] !== 0) throw new Error('invalid array terminator byte'); - if (index !== stopIndex) throw new Error('corrupted array bson'); - } else if (elementType === BSON.BSON_DATA_UNDEFINED) { - object[name] = undefined; - } else if (elementType === BSON.BSON_DATA_NULL) { - object[name] = null; - } else if (elementType === BSON.BSON_DATA_LONG) { - // Unpack the low and high bits - lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var long = new Long(lowBits, highBits); - // Promote the long if possible - if (promoteLongs && promoteValues === true) { - object[name] = long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) ? long.toNumber() : long; - } else { - object[name] = long; - } - } else if (elementType === BSON.BSON_DATA_DECIMAL128) { - // Buffer to contain the decimal bytes - var bytes = utils.allocBuffer(16); - // Copy the next 16 bytes into the bytes buffer - buffer.copy(bytes, 0, index, index + 16); - // Update index - index = index + 16; - // Assign the new Decimal128 value - var decimal128 = new Decimal128(bytes); - // If we have an alternative mapper use that - object[name] = decimal128.toObject ? decimal128.toObject() : decimal128; - } else if (elementType === BSON.BSON_DATA_BINARY) { - var binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var totalBinarySize = binarySize; - var subType = buffer[index++]; - - // Did we have a negative binary size, throw - if (binarySize < 0) throw new Error('Negative binary type element size found'); - - // Is the length longer than the document - if (binarySize > buffer.length) throw new Error('Binary type size larger than document size'); - - // Decode as raw Buffer object if options specifies it - if (buffer['slice'] != null) { - // If we have subtype 2 skip the 4 bytes for the size - if (subType === Binary.SUBTYPE_BYTE_ARRAY) { - binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - if (binarySize < 0) throw new Error('Negative binary type element size found for subtype 0x02'); - if (binarySize > totalBinarySize - 4) throw new Error('Binary type with subtype 0x02 contains to long binary size'); - if (binarySize < totalBinarySize - 4) throw new Error('Binary type with subtype 0x02 contains to short binary size'); - } - - if (promoteBuffers && promoteValues) { - object[name] = buffer.slice(index, index + binarySize); - } else { - object[name] = new Binary(buffer.slice(index, index + binarySize), subType); - } - } else { - var _buffer = typeof Uint8Array !== 'undefined' ? new Uint8Array(new ArrayBuffer(binarySize)) : new Array(binarySize); - // If we have subtype 2 skip the 4 bytes for the size - if (subType === Binary.SUBTYPE_BYTE_ARRAY) { - binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - if (binarySize < 0) throw new Error('Negative binary type element size found for subtype 0x02'); - if (binarySize > totalBinarySize - 4) throw new Error('Binary type with subtype 0x02 contains to long binary size'); - if (binarySize < totalBinarySize - 4) throw new Error('Binary type with subtype 0x02 contains to short binary size'); - } - - // Copy the data - for (i = 0; i < binarySize; i++) { - _buffer[i] = buffer[index + i]; - } - - if (promoteBuffers && promoteValues) { - object[name] = _buffer; - } else { - object[name] = new Binary(_buffer, subType); - } - } - - // Update the index - index = index + binarySize; - } else if (elementType === BSON.BSON_DATA_REGEXP && bsonRegExp === false) { - // Get the start search index - i = index; - // Locate the end of the c string - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - // If are at the end of the buffer there is a problem with the document - if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); - // Return the C string - var source = buffer.toString('utf8', index, i); - // Create the regexp - index = i + 1; - - // Get the start search index - i = index; - // Locate the end of the c string - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - // If are at the end of the buffer there is a problem with the document - if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); - // Return the C string - var regExpOptions = buffer.toString('utf8', index, i); - index = i + 1; - - // For each option add the corresponding one for javascript - var optionsArray = new Array(regExpOptions.length); - - // Parse options - for (i = 0; i < regExpOptions.length; i++) { - switch (regExpOptions[i]) { - case 'm': - optionsArray[i] = 'm'; - break; - case 's': - optionsArray[i] = 'g'; - break; - case 'i': - optionsArray[i] = 'i'; - break; - } - } - - object[name] = new RegExp(source, optionsArray.join('')); - } else if (elementType === BSON.BSON_DATA_REGEXP && bsonRegExp === true) { - // Get the start search index - i = index; - // Locate the end of the c string - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - // If are at the end of the buffer there is a problem with the document - if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); - // Return the C string - source = buffer.toString('utf8', index, i); - index = i + 1; - - // Get the start search index - i = index; - // Locate the end of the c string - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - // If are at the end of the buffer there is a problem with the document - if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); - // Return the C string - regExpOptions = buffer.toString('utf8', index, i); - index = i + 1; - - // Set the object - object[name] = new BSONRegExp(source, regExpOptions); - } else if (elementType === BSON.BSON_DATA_SYMBOL) { - stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - if (stringSize <= 0 || stringSize > buffer.length - index || buffer[index + stringSize - 1] !== 0) throw new Error('bad string length in bson'); - object[name] = new Symbol(buffer.toString('utf8', index, index + stringSize - 1)); - index = index + stringSize; - } else if (elementType === BSON.BSON_DATA_TIMESTAMP) { - lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - object[name] = new Timestamp(lowBits, highBits); - } else if (elementType === BSON.BSON_DATA_MIN_KEY) { - object[name] = new MinKey(); - } else if (elementType === BSON.BSON_DATA_MAX_KEY) { - object[name] = new MaxKey(); - } else if (elementType === BSON.BSON_DATA_CODE) { - stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - if (stringSize <= 0 || stringSize > buffer.length - index || buffer[index + stringSize - 1] !== 0) throw new Error('bad string length in bson'); - var functionString = buffer.toString('utf8', index, index + stringSize - 1); - - // If we are evaluating the functions - if (evalFunctions) { - // If we have cache enabled let's look for the md5 of the function in the cache - if (cacheFunctions) { - var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; - // Got to do this to avoid V8 deoptimizing the call due to finding eval - object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); - } else { - object[name] = isolateEval(functionString); - } - } else { - object[name] = new Code(functionString); - } - - // Update parse index position - index = index + stringSize; - } else if (elementType === BSON.BSON_DATA_CODE_W_SCOPE) { - var totalSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - - // Element cannot be shorter than totalSize + stringSize + documentSize + terminator - if (totalSize < 4 + 4 + 4 + 1) { - throw new Error('code_w_scope total size shorter minimum expected length'); - } - - // Get the code string size - stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Check if we have a valid string - if (stringSize <= 0 || stringSize > buffer.length - index || buffer[index + stringSize - 1] !== 0) throw new Error('bad string length in bson'); - - // Javascript function - functionString = buffer.toString('utf8', index, index + stringSize - 1); - // Update parse index position - index = index + stringSize; - // Parse the element - _index = index; - // Decode the size of the object document - objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - // Decode the scope object - var scopeObject = deserializeObject(buffer, _index, options, false); - // Adjust the index - index = index + objectSize; - - // Check if field length is to short - if (totalSize < 4 + 4 + objectSize + stringSize) { - throw new Error('code_w_scope total size is to short, truncating scope'); - } - - // Check if totalSize field is to long - if (totalSize > 4 + 4 + objectSize + stringSize) { - throw new Error('code_w_scope total size is to long, clips outer document'); - } - - // If we are evaluating the functions - if (evalFunctions) { - // If we have cache enabled let's look for the md5 of the function in the cache - if (cacheFunctions) { - hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; - // Got to do this to avoid V8 deoptimizing the call due to finding eval - object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); - } else { - object[name] = isolateEval(functionString); - } - - object[name].scope = scopeObject; - } else { - object[name] = new Code(functionString, scopeObject); - } - } else if (elementType === BSON.BSON_DATA_DBPOINTER) { - // Get the code string size - stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Check if we have a valid string - if (stringSize <= 0 || stringSize > buffer.length - index || buffer[index + stringSize - 1] !== 0) throw new Error('bad string length in bson'); - // Namespace - var namespace = buffer.toString('utf8', index, index + stringSize - 1); - // Update parse index position - index = index + stringSize; - - // Read the oid - var oidBuffer = utils.allocBuffer(12); - buffer.copy(oidBuffer, 0, index, index + 12); - oid = new ObjectID(oidBuffer); - - // Update the index - index = index + 12; - - // Split the namespace - var parts = namespace.split('.'); - var db = parts.shift(); - var collection = parts.join('.'); - // Upgrade to DBRef type - object[name] = new DBRef(collection, oid, db); - } else { - throw new Error('Detected unknown BSON type ' + elementType.toString(16) + ' for fieldname "' + name + '", are you using the latest BSON parser'); - } - } - - // Check if the deserialization was against a valid array/object - if (size !== index - startIndex) { - if (isArray) throw new Error('corrupt array bson'); - throw new Error('corrupt object bson'); - } - - // Check if we have a db ref object - if (object['$id'] != null) object = new DBRef(object['$ref'], object['$id'], object['$db']); - return object; - }; - - /** - * Ensure eval is isolated. - * - * @ignore - * @api private - */ - var isolateEvalWithHash = function (functionCache, hash, functionString, object) { - // Contains the value we are going to set - var value = null; - - // Check for cache hit, eval if missing and return cached function - if (functionCache[hash] == null) { - eval('value = ' + functionString); - functionCache[hash] = value; - } - // Set the object - return functionCache[hash].bind(object); - }; - - /** - * Ensure eval is isolated. - * - * @ignore - * @api private - */ - var isolateEval = function (functionString) { - // Contains the value we are going to set - var value = null; - // Eval the function - eval('value = ' + functionString); - return value; - }; - - var BSON = {}; - - /** - * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 - * - * @ignore - * @api private - */ - var functionCache = BSON.functionCache = {}; - - /** - * Number BSON Type - * - * @classconstant BSON_DATA_NUMBER - **/ - BSON.BSON_DATA_NUMBER = 1; - /** - * String BSON Type - * - * @classconstant BSON_DATA_STRING - **/ - BSON.BSON_DATA_STRING = 2; - /** - * Object BSON Type - * - * @classconstant BSON_DATA_OBJECT - **/ - BSON.BSON_DATA_OBJECT = 3; - /** - * Array BSON Type - * - * @classconstant BSON_DATA_ARRAY - **/ - BSON.BSON_DATA_ARRAY = 4; - /** - * Binary BSON Type - * - * @classconstant BSON_DATA_BINARY - **/ - BSON.BSON_DATA_BINARY = 5; - /** - * Binary BSON Type - * - * @classconstant BSON_DATA_UNDEFINED - **/ - BSON.BSON_DATA_UNDEFINED = 6; - /** - * ObjectID BSON Type - * - * @classconstant BSON_DATA_OID - **/ - BSON.BSON_DATA_OID = 7; - /** - * Boolean BSON Type - * - * @classconstant BSON_DATA_BOOLEAN - **/ - BSON.BSON_DATA_BOOLEAN = 8; - /** - * Date BSON Type - * - * @classconstant BSON_DATA_DATE - **/ - BSON.BSON_DATA_DATE = 9; - /** - * null BSON Type - * - * @classconstant BSON_DATA_NULL - **/ - BSON.BSON_DATA_NULL = 10; - /** - * RegExp BSON Type - * - * @classconstant BSON_DATA_REGEXP - **/ - BSON.BSON_DATA_REGEXP = 11; - /** - * Code BSON Type - * - * @classconstant BSON_DATA_DBPOINTER - **/ - BSON.BSON_DATA_DBPOINTER = 12; - /** - * Code BSON Type - * - * @classconstant BSON_DATA_CODE - **/ - BSON.BSON_DATA_CODE = 13; - /** - * Symbol BSON Type - * - * @classconstant BSON_DATA_SYMBOL - **/ - BSON.BSON_DATA_SYMBOL = 14; - /** - * Code with Scope BSON Type - * - * @classconstant BSON_DATA_CODE_W_SCOPE - **/ - BSON.BSON_DATA_CODE_W_SCOPE = 15; - /** - * 32 bit Integer BSON Type - * - * @classconstant BSON_DATA_INT - **/ - BSON.BSON_DATA_INT = 16; - /** - * Timestamp BSON Type - * - * @classconstant BSON_DATA_TIMESTAMP - **/ - BSON.BSON_DATA_TIMESTAMP = 17; - /** - * Long BSON Type - * - * @classconstant BSON_DATA_LONG - **/ - BSON.BSON_DATA_LONG = 18; - /** - * Long BSON Type - * - * @classconstant BSON_DATA_DECIMAL128 - **/ - BSON.BSON_DATA_DECIMAL128 = 19; - /** - * MinKey BSON Type - * - * @classconstant BSON_DATA_MIN_KEY - **/ - BSON.BSON_DATA_MIN_KEY = 0xff; - /** - * MaxKey BSON Type - * - * @classconstant BSON_DATA_MAX_KEY - **/ - BSON.BSON_DATA_MAX_KEY = 0x7f; - - /** - * Binary Default Type - * - * @classconstant BSON_BINARY_SUBTYPE_DEFAULT - **/ - BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; - /** - * Binary Function Type - * - * @classconstant BSON_BINARY_SUBTYPE_FUNCTION - **/ - BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; - /** - * Binary Byte Array Type - * - * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY - **/ - BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; - /** - * Binary UUID Type - * - * @classconstant BSON_BINARY_SUBTYPE_UUID - **/ - BSON.BSON_BINARY_SUBTYPE_UUID = 3; - /** - * Binary MD5 Type - * - * @classconstant BSON_BINARY_SUBTYPE_MD5 - **/ - BSON.BSON_BINARY_SUBTYPE_MD5 = 4; - /** - * Binary User Defined Type - * - * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED - **/ - BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; - - // BSON MAX VALUES - BSON.BSON_INT32_MAX = 0x7fffffff; - BSON.BSON_INT32_MIN = -0x80000000; - - BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; - BSON.BSON_INT64_MIN = -Math.pow(2, 63); - - // JS MAX PRECISE VALUES - BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. - BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. - - // Internal long versions - var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. - var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. - - module.exports = deserialize; - -/***/ }), -/* 353 */ -/***/ (function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(Buffer) {'use strict'; - - var writeIEEE754 = __webpack_require__(354).writeIEEE754, - Long = __webpack_require__(330).Long, - Map = __webpack_require__(329), - Binary = __webpack_require__(351).Binary; - - var normalizedFunctionString = __webpack_require__(339).normalizedFunctionString; - - // try { - // var _Buffer = Uint8Array; - // } catch (e) { - // _Buffer = Buffer; - // } - - var regexp = /\x00/; // eslint-disable-line no-control-regex - var ignoreKeys = ['$db', '$ref', '$id', '$clusterTime']; - - // To ensure that 0.4 of node works correctly - var isDate = function isDate(d) { - return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; - }; - - var isRegExp = function isRegExp(d) { - return Object.prototype.toString.call(d) === '[object RegExp]'; - }; - - var serializeString = function (buffer, key, value, index, isArray) { - // Encode String type - buffer[index++] = BSON.BSON_DATA_STRING; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write the string - var size = buffer.write(value, index + 4, 'utf8'); - // Write the size of the string to buffer - buffer[index + 3] = size + 1 >> 24 & 0xff; - buffer[index + 2] = size + 1 >> 16 & 0xff; - buffer[index + 1] = size + 1 >> 8 & 0xff; - buffer[index] = size + 1 & 0xff; - // Update index - index = index + 4 + size; - // Write zero - buffer[index++] = 0; - return index; - }; - - var serializeNumber = function (buffer, key, value, index, isArray) { - // We have an integer value - if (Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - // If the value fits in 32 bits encode as int, if it fits in a double - // encode it as a double, otherwise long - if (value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { - // Set int type 32 bits or less - buffer[index++] = BSON.BSON_DATA_INT; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the int value - buffer[index++] = value & 0xff; - buffer[index++] = value >> 8 & 0xff; - buffer[index++] = value >> 16 & 0xff; - buffer[index++] = value >> 24 & 0xff; - } else if (value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - } else { - // Set long type - buffer[index++] = BSON.BSON_DATA_LONG; - // Number of written bytes - numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - var longVal = Long.fromNumber(value); - var lowBits = longVal.getLowBits(); - var highBits = longVal.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = lowBits >> 8 & 0xff; - buffer[index++] = lowBits >> 16 & 0xff; - buffer[index++] = lowBits >> 24 & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = highBits >> 8 & 0xff; - buffer[index++] = highBits >> 16 & 0xff; - buffer[index++] = highBits >> 24 & 0xff; - } - } else { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - } - - return index; - }; - - var serializeNull = function (buffer, key, value, index, isArray) { - // Set long type - buffer[index++] = BSON.BSON_DATA_NULL; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - return index; - }; - - var serializeBoolean = function (buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_BOOLEAN; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Encode the boolean value - buffer[index++] = value ? 1 : 0; - return index; - }; - - var serializeDate = function (buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_DATE; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - - // Write the date - var dateInMilis = Long.fromNumber(value.getTime()); - var lowBits = dateInMilis.getLowBits(); - var highBits = dateInMilis.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = lowBits >> 8 & 0xff; - buffer[index++] = lowBits >> 16 & 0xff; - buffer[index++] = lowBits >> 24 & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = highBits >> 8 & 0xff; - buffer[index++] = highBits >> 16 & 0xff; - buffer[index++] = highBits >> 24 & 0xff; - return index; - }; - - var serializeRegExp = function (buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_REGEXP; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - if (value.source && value.source.match(regexp) != null) { - throw Error('value ' + value.source + ' must not contain null bytes'); - } - // Adjust the index - index = index + buffer.write(value.source, index, 'utf8'); - // Write zero - buffer[index++] = 0x00; - // Write the parameters - if (value.global) buffer[index++] = 0x73; // s - if (value.ignoreCase) buffer[index++] = 0x69; // i - if (value.multiline) buffer[index++] = 0x6d; // m - // Add ending zero - buffer[index++] = 0x00; - return index; - }; - - var serializeBSONRegExp = function (buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_REGEXP; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - - // Check the pattern for 0 bytes - if (value.pattern.match(regexp) != null) { - // The BSON spec doesn't allow keys with null bytes because keys are - // null-terminated. - throw Error('pattern ' + value.pattern + ' must not contain null bytes'); - } - - // Adjust the index - index = index + buffer.write(value.pattern, index, 'utf8'); - // Write zero - buffer[index++] = 0x00; - // Write the options - index = index + buffer.write(value.options.split('').sort().join(''), index, 'utf8'); - // Add ending zero - buffer[index++] = 0x00; - return index; - }; - - var serializeMinMax = function (buffer, key, value, index, isArray) { - // Write the type of either min or max key - if (value === null) { - buffer[index++] = BSON.BSON_DATA_NULL; - } else if (value._bsontype === 'MinKey') { - buffer[index++] = BSON.BSON_DATA_MIN_KEY; - } else { - buffer[index++] = BSON.BSON_DATA_MAX_KEY; - } - - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - return index; - }; - - var serializeObjectId = function (buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_OID; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - - // Write the objectId into the shared buffer - if (typeof value.id === 'string') { - buffer.write(value.id, index, 'binary'); - } else if (value.id && value.id.copy) { - value.id.copy(buffer, index, 0, 12); - } else { - throw new Error('object [' + JSON.stringify(value) + '] is not a valid ObjectId'); - } - - // Ajust index - return index + 12; - }; - - var serializeBuffer = function (buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_BINARY; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Get size of the buffer (current write point) - var size = value.length; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = size >> 8 & 0xff; - buffer[index++] = size >> 16 & 0xff; - buffer[index++] = size >> 24 & 0xff; - // Write the default subtype - buffer[index++] = BSON.BSON_BINARY_SUBTYPE_DEFAULT; - // Copy the content form the binary field to the buffer - value.copy(buffer, index, 0, size); - // Adjust the index - index = index + size; - return index; - }; - - var serializeObject = function (buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, isArray, path) { - for (var i = 0; i < path.length; i++) { - if (path[i] === value) throw new Error('cyclic dependency detected'); - } - - // Push value to stack - path.push(value); - // Write the type - buffer[index++] = Array.isArray(value) ? BSON.BSON_DATA_ARRAY : BSON.BSON_DATA_OBJECT; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - var endIndex = serializeInto(buffer, value, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path); - // Pop stack - path.pop(); - // Write size - return endIndex; - }; - - var serializeDecimal128 = function (buffer, key, value, index, isArray) { - buffer[index++] = BSON.BSON_DATA_DECIMAL128; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the data from the value - value.bytes.copy(buffer, index, 0, 16); - return index + 16; - }; - - var serializeLong = function (buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = value._bsontype === 'Long' ? BSON.BSON_DATA_LONG : BSON.BSON_DATA_TIMESTAMP; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the date - var lowBits = value.getLowBits(); - var highBits = value.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = lowBits >> 8 & 0xff; - buffer[index++] = lowBits >> 16 & 0xff; - buffer[index++] = lowBits >> 24 & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = highBits >> 8 & 0xff; - buffer[index++] = highBits >> 16 & 0xff; - buffer[index++] = highBits >> 24 & 0xff; - return index; - }; - - var serializeInt32 = function (buffer, key, value, index, isArray) { - // Set int type 32 bits or less - buffer[index++] = BSON.BSON_DATA_INT; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the int value - buffer[index++] = value & 0xff; - buffer[index++] = value >> 8 & 0xff; - buffer[index++] = value >> 16 & 0xff; - buffer[index++] = value >> 24 & 0xff; - return index; - }; - - var serializeDouble = function (buffer, key, value, index, isArray) { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - return index; - }; - - var serializeFunction = function (buffer, key, value, index, checkKeys, depth, isArray) { - buffer[index++] = BSON.BSON_DATA_CODE; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Function string - var functionString = normalizedFunctionString(value); - - // Write the string - var size = buffer.write(functionString, index + 4, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = size & 0xff; - buffer[index + 1] = size >> 8 & 0xff; - buffer[index + 2] = size >> 16 & 0xff; - buffer[index + 3] = size >> 24 & 0xff; - // Update index - index = index + 4 + size - 1; - // Write zero - buffer[index++] = 0; - return index; - }; - - var serializeCode = function (buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, isArray) { - if (value.scope && typeof value.scope === 'object') { - // Write the type - buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - - // Starting index - var startIndex = index; - - // Serialize the function - // Get the function string - var functionString = typeof value.code === 'string' ? value.code : value.code.toString(); - // Index adjustment - index = index + 4; - // Write string into buffer - var codeSize = buffer.write(functionString, index + 4, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = codeSize & 0xff; - buffer[index + 1] = codeSize >> 8 & 0xff; - buffer[index + 2] = codeSize >> 16 & 0xff; - buffer[index + 3] = codeSize >> 24 & 0xff; - // Write end 0 - buffer[index + 4 + codeSize - 1] = 0; - // Write the - index = index + codeSize + 4; - - // - // Serialize the scope value - var endIndex = serializeInto(buffer, value.scope, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined); - index = endIndex - 1; - - // Writ the total - var totalSize = endIndex - startIndex; - - // Write the total size of the object - buffer[startIndex++] = totalSize & 0xff; - buffer[startIndex++] = totalSize >> 8 & 0xff; - buffer[startIndex++] = totalSize >> 16 & 0xff; - buffer[startIndex++] = totalSize >> 24 & 0xff; - // Write trailing zero - buffer[index++] = 0; - } else { - buffer[index++] = BSON.BSON_DATA_CODE; - // Number of written bytes - numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Function string - functionString = value.code.toString(); - // Write the string - var size = buffer.write(functionString, index + 4, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = size & 0xff; - buffer[index + 1] = size >> 8 & 0xff; - buffer[index + 2] = size >> 16 & 0xff; - buffer[index + 3] = size >> 24 & 0xff; - // Update index - index = index + 4 + size - 1; - // Write zero - buffer[index++] = 0; - } - - return index; - }; - - var serializeBinary = function (buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_BINARY; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Extract the buffer - var data = value.value(true); - // Calculate size - var size = value.position; - // Add the deprecated 02 type 4 bytes of size to total - if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) size = size + 4; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = size >> 8 & 0xff; - buffer[index++] = size >> 16 & 0xff; - buffer[index++] = size >> 24 & 0xff; - // Write the subtype to the buffer - buffer[index++] = value.sub_type; - - // If we have binary type 2 the 4 first bytes are the size - if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { - size = size - 4; - buffer[index++] = size & 0xff; - buffer[index++] = size >> 8 & 0xff; - buffer[index++] = size >> 16 & 0xff; - buffer[index++] = size >> 24 & 0xff; - } - - // Write the data to the object - data.copy(buffer, index, 0, value.position); - // Adjust the index - index = index + value.position; - return index; - }; - - var serializeSymbol = function (buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_SYMBOL; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the string - var size = buffer.write(value.value, index + 4, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = size & 0xff; - buffer[index + 1] = size >> 8 & 0xff; - buffer[index + 2] = size >> 16 & 0xff; - buffer[index + 3] = size >> 24 & 0xff; - // Update index - index = index + 4 + size - 1; - // Write zero - buffer[index++] = 0x00; - return index; - }; - - var serializeDBRef = function (buffer, key, value, index, depth, serializeFunctions, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_OBJECT; - // Number of written bytes - var numberOfWrittenBytes = !isArray ? buffer.write(key, index, 'utf8') : buffer.write(key, index, 'ascii'); - - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - - var startIndex = index; - var endIndex; - - // Serialize object - if (null != value.db) { - endIndex = serializeInto(buffer, { - $ref: value.namespace, - $id: value.oid, - $db: value.db - }, false, index, depth + 1, serializeFunctions); - } else { - endIndex = serializeInto(buffer, { - $ref: value.namespace, - $id: value.oid - }, false, index, depth + 1, serializeFunctions); - } - - // Calculate object size - var size = endIndex - startIndex; - // Write the size - buffer[startIndex++] = size & 0xff; - buffer[startIndex++] = size >> 8 & 0xff; - buffer[startIndex++] = size >> 16 & 0xff; - buffer[startIndex++] = size >> 24 & 0xff; - // Set index - return endIndex; - }; - - var serializeInto = function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializeFunctions, ignoreUndefined, path) { - startingIndex = startingIndex || 0; - path = path || []; - - // Push the object to the path - path.push(object); - - // Start place to serialize into - var index = startingIndex + 4; - // var self = this; - - // Special case isArray - if (Array.isArray(object)) { - // Get object keys - for (var i = 0; i < object.length; i++) { - var key = '' + i; - var value = object[i]; - - // Is there an override value - if (value && value.toBSON) { - if (typeof value.toBSON !== 'function') throw new Error('toBSON is not a function'); - value = value.toBSON(); - } - - var type = typeof value; - if (type === 'string') { - index = serializeString(buffer, key, value, index, true); - } else if (type === 'number') { - index = serializeNumber(buffer, key, value, index, true); - } else if (type === 'boolean') { - index = serializeBoolean(buffer, key, value, index, true); - } else if (value instanceof Date || isDate(value)) { - index = serializeDate(buffer, key, value, index, true); - } else if (value === undefined) { - index = serializeNull(buffer, key, value, index, true); - } else if (value === null) { - index = serializeNull(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'ObjectID' || value['_bsontype'] === 'ObjectId') { - index = serializeObjectId(buffer, key, value, index, true); - } else if (Buffer.isBuffer(value)) { - index = serializeBuffer(buffer, key, value, index, true); - } else if (value instanceof RegExp || isRegExp(value)) { - index = serializeRegExp(buffer, key, value, index, true); - } else if (type === 'object' && value['_bsontype'] == null) { - index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, true, path); - } else if (type === 'object' && value['_bsontype'] === 'Decimal128') { - index = serializeDecimal128(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { - index = serializeLong(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'Double') { - index = serializeDouble(buffer, key, value, index, true); - } else if (typeof value === 'function' && serializeFunctions) { - index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions, true); - } else if (value['_bsontype'] === 'Code') { - index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, true); - } else if (value['_bsontype'] === 'Binary') { - index = serializeBinary(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'Symbol') { - index = serializeSymbol(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'DBRef') { - index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, true); - } else if (value['_bsontype'] === 'BSONRegExp') { - index = serializeBSONRegExp(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'Int32') { - index = serializeInt32(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { - index = serializeMinMax(buffer, key, value, index, true); - } - } - } else if (object instanceof Map) { - var iterator = object.entries(); - var done = false; - - while (!done) { - // Unpack the next entry - var entry = iterator.next(); - done = entry.done; - // Are we done, then skip and terminate - if (done) continue; - - // Get the entry values - key = entry.value[0]; - value = entry.value[1]; - - // Check the type of the value - type = typeof value; - - // Check the key and throw error if it's illegal - if (typeof key === 'string' && ignoreKeys.indexOf(key) === -1) { - if (key.match(regexp) != null) { - // The BSON spec doesn't allow keys with null bytes because keys are - // null-terminated. - throw Error('key ' + key + ' must not contain null bytes'); - } - - if (checkKeys) { - if ('$' === key[0]) { - throw Error('key ' + key + " must not start with '$'"); - } else if (~key.indexOf('.')) { - throw Error('key ' + key + " must not contain '.'"); - } - } - } - - if (type === 'string') { - index = serializeString(buffer, key, value, index); - } else if (type === 'number') { - index = serializeNumber(buffer, key, value, index); - } else if (type === 'boolean') { - index = serializeBoolean(buffer, key, value, index); - } else if (value instanceof Date || isDate(value)) { - index = serializeDate(buffer, key, value, index); - // } else if (value === undefined && ignoreUndefined === true) { - } else if (value === null || value === undefined && ignoreUndefined === false) { - index = serializeNull(buffer, key, value, index); - } else if (value['_bsontype'] === 'ObjectID' || value['_bsontype'] === 'ObjectId') { - index = serializeObjectId(buffer, key, value, index); - } else if (Buffer.isBuffer(value)) { - index = serializeBuffer(buffer, key, value, index); - } else if (value instanceof RegExp || isRegExp(value)) { - index = serializeRegExp(buffer, key, value, index); - } else if (type === 'object' && value['_bsontype'] == null) { - index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, false, path); - } else if (type === 'object' && value['_bsontype'] === 'Decimal128') { - index = serializeDecimal128(buffer, key, value, index); - } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { - index = serializeLong(buffer, key, value, index); - } else if (value['_bsontype'] === 'Double') { - index = serializeDouble(buffer, key, value, index); - } else if (value['_bsontype'] === 'Code') { - index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); - } else if (typeof value === 'function' && serializeFunctions) { - index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); - } else if (value['_bsontype'] === 'Binary') { - index = serializeBinary(buffer, key, value, index); - } else if (value['_bsontype'] === 'Symbol') { - index = serializeSymbol(buffer, key, value, index); - } else if (value['_bsontype'] === 'DBRef') { - index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); - } else if (value['_bsontype'] === 'BSONRegExp') { - index = serializeBSONRegExp(buffer, key, value, index); - } else if (value['_bsontype'] === 'Int32') { - index = serializeInt32(buffer, key, value, index); - } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { - index = serializeMinMax(buffer, key, value, index); - } - } - } else { - // Did we provide a custom serialization method - if (object.toBSON) { - if (typeof object.toBSON !== 'function') throw new Error('toBSON is not a function'); - object = object.toBSON(); - if (object != null && typeof object !== 'object') throw new Error('toBSON function did not return an object'); - } - - // Iterate over all the keys - for (key in object) { - value = object[key]; - // Is there an override value - if (value && value.toBSON) { - if (typeof value.toBSON !== 'function') throw new Error('toBSON is not a function'); - value = value.toBSON(); - } - - // Check the type of the value - type = typeof value; - - // Check the key and throw error if it's illegal - if (typeof key === 'string' && ignoreKeys.indexOf(key) === -1) { - if (key.match(regexp) != null) { - // The BSON spec doesn't allow keys with null bytes because keys are - // null-terminated. - throw Error('key ' + key + ' must not contain null bytes'); - } - - if (checkKeys) { - if ('$' === key[0]) { - throw Error('key ' + key + " must not start with '$'"); - } else if (~key.indexOf('.')) { - throw Error('key ' + key + " must not contain '.'"); - } - } - } - - if (type === 'string') { - index = serializeString(buffer, key, value, index); - } else if (type === 'number') { - index = serializeNumber(buffer, key, value, index); - } else if (type === 'boolean') { - index = serializeBoolean(buffer, key, value, index); - } else if (value instanceof Date || isDate(value)) { - index = serializeDate(buffer, key, value, index); - } else if (value === undefined) { - if (ignoreUndefined === false) index = serializeNull(buffer, key, value, index); - } else if (value === null) { - index = serializeNull(buffer, key, value, index); - } else if (value['_bsontype'] === 'ObjectID' || value['_bsontype'] === 'ObjectId') { - index = serializeObjectId(buffer, key, value, index); - } else if (Buffer.isBuffer(value)) { - index = serializeBuffer(buffer, key, value, index); - } else if (value instanceof RegExp || isRegExp(value)) { - index = serializeRegExp(buffer, key, value, index); - } else if (type === 'object' && value['_bsontype'] == null) { - index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, false, path); - } else if (type === 'object' && value['_bsontype'] === 'Decimal128') { - index = serializeDecimal128(buffer, key, value, index); - } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { - index = serializeLong(buffer, key, value, index); - } else if (value['_bsontype'] === 'Double') { - index = serializeDouble(buffer, key, value, index); - } else if (value['_bsontype'] === 'Code') { - index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); - } else if (typeof value === 'function' && serializeFunctions) { - index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); - } else if (value['_bsontype'] === 'Binary') { - index = serializeBinary(buffer, key, value, index); - } else if (value['_bsontype'] === 'Symbol') { - index = serializeSymbol(buffer, key, value, index); - } else if (value['_bsontype'] === 'DBRef') { - index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); - } else if (value['_bsontype'] === 'BSONRegExp') { - index = serializeBSONRegExp(buffer, key, value, index); - } else if (value['_bsontype'] === 'Int32') { - index = serializeInt32(buffer, key, value, index); - } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { - index = serializeMinMax(buffer, key, value, index); - } - } - } - - // Remove the path - path.pop(); - - // Final padding byte for object - buffer[index++] = 0x00; - - // Final size - var size = index - startingIndex; - // Write the size of the object - buffer[startingIndex++] = size & 0xff; - buffer[startingIndex++] = size >> 8 & 0xff; - buffer[startingIndex++] = size >> 16 & 0xff; - buffer[startingIndex++] = size >> 24 & 0xff; - return index; - }; - - var BSON = {}; - - /** - * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 - * - * @ignore - * @api private - */ - // var functionCache = (BSON.functionCache = {}); - - /** - * Number BSON Type - * - * @classconstant BSON_DATA_NUMBER - **/ - BSON.BSON_DATA_NUMBER = 1; - /** - * String BSON Type - * - * @classconstant BSON_DATA_STRING - **/ - BSON.BSON_DATA_STRING = 2; - /** - * Object BSON Type - * - * @classconstant BSON_DATA_OBJECT - **/ - BSON.BSON_DATA_OBJECT = 3; - /** - * Array BSON Type - * - * @classconstant BSON_DATA_ARRAY - **/ - BSON.BSON_DATA_ARRAY = 4; - /** - * Binary BSON Type - * - * @classconstant BSON_DATA_BINARY - **/ - BSON.BSON_DATA_BINARY = 5; - /** - * ObjectID BSON Type, deprecated - * - * @classconstant BSON_DATA_UNDEFINED - **/ - BSON.BSON_DATA_UNDEFINED = 6; - /** - * ObjectID BSON Type - * - * @classconstant BSON_DATA_OID - **/ - BSON.BSON_DATA_OID = 7; - /** - * Boolean BSON Type - * - * @classconstant BSON_DATA_BOOLEAN - **/ - BSON.BSON_DATA_BOOLEAN = 8; - /** - * Date BSON Type - * - * @classconstant BSON_DATA_DATE - **/ - BSON.BSON_DATA_DATE = 9; - /** - * null BSON Type - * - * @classconstant BSON_DATA_NULL - **/ - BSON.BSON_DATA_NULL = 10; - /** - * RegExp BSON Type - * - * @classconstant BSON_DATA_REGEXP - **/ - BSON.BSON_DATA_REGEXP = 11; - /** - * Code BSON Type - * - * @classconstant BSON_DATA_CODE - **/ - BSON.BSON_DATA_CODE = 13; - /** - * Symbol BSON Type - * - * @classconstant BSON_DATA_SYMBOL - **/ - BSON.BSON_DATA_SYMBOL = 14; - /** - * Code with Scope BSON Type - * - * @classconstant BSON_DATA_CODE_W_SCOPE - **/ - BSON.BSON_DATA_CODE_W_SCOPE = 15; - /** - * 32 bit Integer BSON Type - * - * @classconstant BSON_DATA_INT - **/ - BSON.BSON_DATA_INT = 16; - /** - * Timestamp BSON Type - * - * @classconstant BSON_DATA_TIMESTAMP - **/ - BSON.BSON_DATA_TIMESTAMP = 17; - /** - * Long BSON Type - * - * @classconstant BSON_DATA_LONG - **/ - BSON.BSON_DATA_LONG = 18; - /** - * Long BSON Type - * - * @classconstant BSON_DATA_DECIMAL128 - **/ - BSON.BSON_DATA_DECIMAL128 = 19; - /** - * MinKey BSON Type - * - * @classconstant BSON_DATA_MIN_KEY - **/ - BSON.BSON_DATA_MIN_KEY = 0xff; - /** - * MaxKey BSON Type - * - * @classconstant BSON_DATA_MAX_KEY - **/ - BSON.BSON_DATA_MAX_KEY = 0x7f; - /** - * Binary Default Type - * - * @classconstant BSON_BINARY_SUBTYPE_DEFAULT - **/ - BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; - /** - * Binary Function Type - * - * @classconstant BSON_BINARY_SUBTYPE_FUNCTION - **/ - BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; - /** - * Binary Byte Array Type - * - * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY - **/ - BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; - /** - * Binary UUID Type - * - * @classconstant BSON_BINARY_SUBTYPE_UUID - **/ - BSON.BSON_BINARY_SUBTYPE_UUID = 3; - /** - * Binary MD5 Type - * - * @classconstant BSON_BINARY_SUBTYPE_MD5 - **/ - BSON.BSON_BINARY_SUBTYPE_MD5 = 4; - /** - * Binary User Defined Type - * - * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED - **/ - BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; - - // BSON MAX VALUES - BSON.BSON_INT32_MAX = 0x7fffffff; - BSON.BSON_INT32_MIN = -0x80000000; - - BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; - BSON.BSON_INT64_MIN = -Math.pow(2, 63); - - // JS MAX PRECISE VALUES - BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. - BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. - - // Internal long versions - // var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. - // var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. - - module.exports = serializeInto; - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(334).Buffer)) - -/***/ }), -/* 354 */ -/***/ (function(module, exports) { - - // Copyright (c) 2008, Fair Oaks Labs, Inc. - // All rights reserved. - // - // Redistribution and use in source and binary forms, with or without - // modification, are permitted provided that the following conditions are met: - // - // * Redistributions of source code must retain the above copyright notice, - // this list of conditions and the following disclaimer. - // - // * Redistributions in binary form must reproduce the above copyright notice, - // this list of conditions and the following disclaimer in the documentation - // and/or other materials provided with the distribution. - // - // * Neither the name of Fair Oaks Labs, Inc. nor the names of its contributors - // may be used to endorse or promote products derived from this software - // without specific prior written permission. - // - // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - // POSSIBILITY OF SUCH DAMAGE. - // - // - // Modifications to writeIEEE754 to support negative zeroes made by Brian White - - var readIEEE754 = function (buffer, offset, endian, mLen, nBytes) { - var e, - m, - bBE = endian === 'big', - eLen = nBytes * 8 - mLen - 1, - eMax = (1 << eLen) - 1, - eBias = eMax >> 1, - nBits = -7, - i = bBE ? 0 : nBytes - 1, - d = bBE ? 1 : -1, - s = buffer[offset + i]; - - i += d; - - e = s & (1 << -nBits) - 1; - s >>= -nBits; - nBits += eLen; - for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8); - - m = e & (1 << -nBits) - 1; - e >>= -nBits; - nBits += mLen; - for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8); - - if (e === 0) { - e = 1 - eBias; - } else if (e === eMax) { - return m ? NaN : (s ? -1 : 1) * Infinity; - } else { - m = m + Math.pow(2, mLen); - e = e - eBias; - } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen); - }; - - var writeIEEE754 = function (buffer, value, offset, endian, mLen, nBytes) { - var e, - m, - c, - bBE = endian === 'big', - eLen = nBytes * 8 - mLen - 1, - eMax = (1 << eLen) - 1, - eBias = eMax >> 1, - rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0, - i = bBE ? nBytes - 1 : 0, - d = bBE ? -1 : 1, - s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0; - - value = Math.abs(value); - - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0; - e = eMax; - } else { - e = Math.floor(Math.log(value) / Math.LN2); - if (value * (c = Math.pow(2, -e)) < 1) { - e--; - c *= 2; - } - if (e + eBias >= 1) { - value += rt / c; - } else { - value += rt * Math.pow(2, 1 - eBias); - } - if (value * c >= 2) { - e++; - c /= 2; - } - - if (e + eBias >= eMax) { - m = 0; - e = eMax; - } else if (e + eBias >= 1) { - m = (value * c - 1) * Math.pow(2, mLen); - e = e + eBias; - } else { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); - e = 0; - } - } - - for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8); - - e = e << mLen | m; - eLen += mLen; - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8); - - buffer[offset + i - d] |= s * 128; - }; - - exports.readIEEE754 = readIEEE754; - exports.writeIEEE754 = writeIEEE754; - -/***/ }), -/* 355 */ -/***/ (function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(Buffer) {'use strict'; - - var Long = __webpack_require__(330).Long, - Double = __webpack_require__(331).Double, - Timestamp = __webpack_require__(332).Timestamp, - ObjectID = __webpack_require__(333).ObjectID, - Symbol = __webpack_require__(344).Symbol, - BSONRegExp = __webpack_require__(343).BSONRegExp, - Code = __webpack_require__(346).Code, - Decimal128 = __webpack_require__(347), - MinKey = __webpack_require__(348).MinKey, - MaxKey = __webpack_require__(349).MaxKey, - DBRef = __webpack_require__(350).DBRef, - Binary = __webpack_require__(351).Binary; - - var normalizedFunctionString = __webpack_require__(339).normalizedFunctionString; - - // To ensure that 0.4 of node works correctly - var isDate = function isDate(d) { - return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; - }; - - var calculateObjectSize = function calculateObjectSize(object, serializeFunctions, ignoreUndefined) { - var totalLength = 4 + 1; - - if (Array.isArray(object)) { - for (var i = 0; i < object.length; i++) { - totalLength += calculateElement(i.toString(), object[i], serializeFunctions, true, ignoreUndefined); - } - } else { - // If we have toBSON defined, override the current object - if (object.toBSON) { - object = object.toBSON(); - } - - // Calculate size - for (var key in object) { - totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined); - } - } - - return totalLength; - }; - - /** - * @ignore - * @api private - */ - function calculateElement(name, value, serializeFunctions, isArray, ignoreUndefined) { - // If we have toBSON defined, override the current object - if (value && value.toBSON) { - value = value.toBSON(); - } - - switch (typeof value) { - case 'string': - return 1 + Buffer.byteLength(name, 'utf8') + 1 + 4 + Buffer.byteLength(value, 'utf8') + 1; - case 'number': - if (Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - if (value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { - // 32 bit - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (4 + 1); - } else { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); - } - } else { - // 64 bit - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); - } - case 'undefined': - if (isArray || !ignoreUndefined) return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1; - return 0; - case 'boolean': - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (1 + 1); - case 'object': - if (value == null || value instanceof MinKey || value instanceof MaxKey || value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1; - } else if (value instanceof ObjectID || value['_bsontype'] === 'ObjectID' || value['_bsontype'] === 'ObjectId') { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (12 + 1); - } else if (value instanceof Date || isDate(value)) { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); - } else if (typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (1 + 4 + 1) + value.length; - } else if (value instanceof Long || value instanceof Double || value instanceof Timestamp || value['_bsontype'] === 'Long' || value['_bsontype'] === 'Double' || value['_bsontype'] === 'Timestamp') { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); - } else if (value instanceof Decimal128 || value['_bsontype'] === 'Decimal128') { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (16 + 1); - } else if (value instanceof Code || value['_bsontype'] === 'Code') { - // Calculate size depending on the availability of a scope - if (value.scope != null && Object.keys(value.scope).length > 0) { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + 4 + 4 + Buffer.byteLength(value.code.toString(), 'utf8') + 1 + calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined); - } else { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + 4 + Buffer.byteLength(value.code.toString(), 'utf8') + 1; - } - } else if (value instanceof Binary || value['_bsontype'] === 'Binary') { - // Check what kind of subtype we have - if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (value.position + 1 + 4 + 1 + 4); - } else { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (value.position + 1 + 4 + 1); - } - } else if (value instanceof Symbol || value['_bsontype'] === 'Symbol') { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + Buffer.byteLength(value.value, 'utf8') + 4 + 1 + 1; - } else if (value instanceof DBRef || value['_bsontype'] === 'DBRef') { - // Set up correct object for serialization - var ordered_values = { - $ref: value.namespace, - $id: value.oid - }; - - // Add db reference if it exists - if (null != value.db) { - ordered_values['$db'] = value.db; - } - - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + calculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined); - } else if (value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]') { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + Buffer.byteLength(value.source, 'utf8') + 1 + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1; - } else if (value instanceof BSONRegExp || value['_bsontype'] === 'BSONRegExp') { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + Buffer.byteLength(value.pattern, 'utf8') + 1 + Buffer.byteLength(value.options, 'utf8') + 1; - } else { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + calculateObjectSize(value, serializeFunctions, ignoreUndefined) + 1; - } - case 'function': - // WTF for 0.4.X where typeof /someregexp/ === 'function' - if (value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]' || String.call(value) === '[object RegExp]') { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + Buffer.byteLength(value.source, 'utf8') + 1 + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1; - } else { - if (serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + 4 + 4 + Buffer.byteLength(normalizedFunctionString(value), 'utf8') + 1 + calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined); - } else if (serializeFunctions) { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1 + 4 + Buffer.byteLength(normalizedFunctionString(value), 'utf8') + 1; - } - } - } - - return 0; - } - - var BSON = {}; - - // BSON MAX VALUES - BSON.BSON_INT32_MAX = 0x7fffffff; - BSON.BSON_INT32_MIN = -0x80000000; - - // JS MAX PRECISE VALUES - BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. - BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. - - module.exports = calculateObjectSize; - /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(334).Buffer)) - -/***/ }) -/******/ ]) -}); -; \ No newline at end of file diff --git a/scripts/node_modules/bson/browser_build/package.json b/scripts/node_modules/bson/browser_build/package.json deleted file mode 100644 index 980db7f9..00000000 --- a/scripts/node_modules/bson/browser_build/package.json +++ /dev/null @@ -1,8 +0,0 @@ -{ "name" : "bson" -, "description" : "A bson parser for node.js and the browser" -, "main": "../" -, "directories" : { "lib" : "../lib/bson" } -, "engines" : { "node" : ">=0.6.0" } -, "licenses" : [ { "type" : "Apache License, Version 2.0" - , "url" : "http://www.apache.org/licenses/LICENSE-2.0" } ] -} diff --git a/scripts/node_modules/bson/index.js b/scripts/node_modules/bson/index.js deleted file mode 100644 index 6502552d..00000000 --- a/scripts/node_modules/bson/index.js +++ /dev/null @@ -1,46 +0,0 @@ -var BSON = require('./lib/bson/bson'), - Binary = require('./lib/bson/binary'), - Code = require('./lib/bson/code'), - DBRef = require('./lib/bson/db_ref'), - Decimal128 = require('./lib/bson/decimal128'), - Double = require('./lib/bson/double'), - Int32 = require('./lib/bson/int_32'), - Long = require('./lib/bson/long'), - Map = require('./lib/bson/map'), - MaxKey = require('./lib/bson/max_key'), - MinKey = require('./lib/bson/min_key'), - ObjectId = require('./lib/bson/objectid'), - BSONRegExp = require('./lib/bson/regexp'), - Symbol = require('./lib/bson/symbol'), - Timestamp = require('./lib/bson/timestamp'); - -// BSON MAX VALUES -BSON.BSON_INT32_MAX = 0x7fffffff; -BSON.BSON_INT32_MIN = -0x80000000; - -BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; -BSON.BSON_INT64_MIN = -Math.pow(2, 63); - -// JS MAX PRECISE VALUES -BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. -BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. - -// Add BSON types to function creation -BSON.Binary = Binary; -BSON.Code = Code; -BSON.DBRef = DBRef; -BSON.Decimal128 = Decimal128; -BSON.Double = Double; -BSON.Int32 = Int32; -BSON.Long = Long; -BSON.Map = Map; -BSON.MaxKey = MaxKey; -BSON.MinKey = MinKey; -BSON.ObjectId = ObjectId; -BSON.ObjectID = ObjectId; -BSON.BSONRegExp = BSONRegExp; -BSON.Symbol = Symbol; -BSON.Timestamp = Timestamp; - -// Return the BSON -module.exports = BSON; diff --git a/scripts/node_modules/bson/lib/bson/binary.js b/scripts/node_modules/bson/lib/bson/binary.js deleted file mode 100644 index 6d190bca..00000000 --- a/scripts/node_modules/bson/lib/bson/binary.js +++ /dev/null @@ -1,384 +0,0 @@ -/** - * Module dependencies. - * @ignore - */ - -// Test if we're in Node via presence of "global" not absence of "window" -// to support hybrid environments like Electron -if (typeof global !== 'undefined') { - var Buffer = require('buffer').Buffer; // TODO just use global Buffer -} - -var utils = require('./parser/utils'); - -/** - * A class representation of the BSON Binary type. - * - * Sub types - * - **BSON.BSON_BINARY_SUBTYPE_DEFAULT**, default BSON type. - * - **BSON.BSON_BINARY_SUBTYPE_FUNCTION**, BSON function type. - * - **BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY**, BSON byte array type. - * - **BSON.BSON_BINARY_SUBTYPE_UUID**, BSON uuid type. - * - **BSON.BSON_BINARY_SUBTYPE_MD5**, BSON md5 type. - * - **BSON.BSON_BINARY_SUBTYPE_USER_DEFINED**, BSON user defined type. - * - * @class - * @param {Buffer} buffer a buffer object containing the binary data. - * @param {Number} [subType] the option binary type. - * @return {Binary} - */ -function Binary(buffer, subType) { - if (!(this instanceof Binary)) return new Binary(buffer, subType); - - if ( - buffer != null && - !(typeof buffer === 'string') && - !Buffer.isBuffer(buffer) && - !(buffer instanceof Uint8Array) && - !Array.isArray(buffer) - ) { - throw new Error('only String, Buffer, Uint8Array or Array accepted'); - } - - this._bsontype = 'Binary'; - - if (buffer instanceof Number) { - this.sub_type = buffer; - this.position = 0; - } else { - this.sub_type = subType == null ? BSON_BINARY_SUBTYPE_DEFAULT : subType; - this.position = 0; - } - - if (buffer != null && !(buffer instanceof Number)) { - // Only accept Buffer, Uint8Array or Arrays - if (typeof buffer === 'string') { - // Different ways of writing the length of the string for the different types - if (typeof Buffer !== 'undefined') { - this.buffer = utils.toBuffer(buffer); - } else if ( - typeof Uint8Array !== 'undefined' || - Object.prototype.toString.call(buffer) === '[object Array]' - ) { - this.buffer = writeStringToArray(buffer); - } else { - throw new Error('only String, Buffer, Uint8Array or Array accepted'); - } - } else { - this.buffer = buffer; - } - this.position = buffer.length; - } else { - if (typeof Buffer !== 'undefined') { - this.buffer = utils.allocBuffer(Binary.BUFFER_SIZE); - } else if (typeof Uint8Array !== 'undefined') { - this.buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE)); - } else { - this.buffer = new Array(Binary.BUFFER_SIZE); - } - // Set position to start of buffer - this.position = 0; - } -} - -/** - * Updates this binary with byte_value. - * - * @method - * @param {string} byte_value a single byte we wish to write. - */ -Binary.prototype.put = function put(byte_value) { - // If it's a string and a has more than one character throw an error - if (byte_value['length'] != null && typeof byte_value !== 'number' && byte_value.length !== 1) - throw new Error('only accepts single character String, Uint8Array or Array'); - if ((typeof byte_value !== 'number' && byte_value < 0) || byte_value > 255) - throw new Error('only accepts number in a valid unsigned byte range 0-255'); - - // Decode the byte value once - var decoded_byte = null; - if (typeof byte_value === 'string') { - decoded_byte = byte_value.charCodeAt(0); - } else if (byte_value['length'] != null) { - decoded_byte = byte_value[0]; - } else { - decoded_byte = byte_value; - } - - if (this.buffer.length > this.position) { - this.buffer[this.position++] = decoded_byte; - } else { - if (typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer)) { - // Create additional overflow buffer - var buffer = utils.allocBuffer(Binary.BUFFER_SIZE + this.buffer.length); - // Combine the two buffers together - this.buffer.copy(buffer, 0, 0, this.buffer.length); - this.buffer = buffer; - this.buffer[this.position++] = decoded_byte; - } else { - buffer = null; - // Create a new buffer (typed or normal array) - if (Object.prototype.toString.call(this.buffer) === '[object Uint8Array]') { - buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE + this.buffer.length)); - } else { - buffer = new Array(Binary.BUFFER_SIZE + this.buffer.length); - } - - // We need to copy all the content to the new array - for (var i = 0; i < this.buffer.length; i++) { - buffer[i] = this.buffer[i]; - } - - // Reassign the buffer - this.buffer = buffer; - // Write the byte - this.buffer[this.position++] = decoded_byte; - } - } -}; - -/** - * Writes a buffer or string to the binary. - * - * @method - * @param {(Buffer|string)} string a string or buffer to be written to the Binary BSON object. - * @param {number} offset specify the binary of where to write the content. - * @return {null} - */ -Binary.prototype.write = function write(string, offset) { - offset = typeof offset === 'number' ? offset : this.position; - - // If the buffer is to small let's extend the buffer - if (this.buffer.length < offset + string.length) { - var buffer = null; - // If we are in node.js - if (typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer)) { - buffer = utils.allocBuffer(this.buffer.length + string.length); - this.buffer.copy(buffer, 0, 0, this.buffer.length); - } else if (Object.prototype.toString.call(this.buffer) === '[object Uint8Array]') { - // Create a new buffer - buffer = new Uint8Array(new ArrayBuffer(this.buffer.length + string.length)); - // Copy the content - for (var i = 0; i < this.position; i++) { - buffer[i] = this.buffer[i]; - } - } - - // Assign the new buffer - this.buffer = buffer; - } - - if (typeof Buffer !== 'undefined' && Buffer.isBuffer(string) && Buffer.isBuffer(this.buffer)) { - string.copy(this.buffer, offset, 0, string.length); - this.position = offset + string.length > this.position ? offset + string.length : this.position; - // offset = string.length - } else if ( - typeof Buffer !== 'undefined' && - typeof string === 'string' && - Buffer.isBuffer(this.buffer) - ) { - this.buffer.write(string, offset, 'binary'); - this.position = offset + string.length > this.position ? offset + string.length : this.position; - // offset = string.length; - } else if ( - Object.prototype.toString.call(string) === '[object Uint8Array]' || - (Object.prototype.toString.call(string) === '[object Array]' && typeof string !== 'string') - ) { - for (i = 0; i < string.length; i++) { - this.buffer[offset++] = string[i]; - } - - this.position = offset > this.position ? offset : this.position; - } else if (typeof string === 'string') { - for (i = 0; i < string.length; i++) { - this.buffer[offset++] = string.charCodeAt(i); - } - - this.position = offset > this.position ? offset : this.position; - } -}; - -/** - * Reads **length** bytes starting at **position**. - * - * @method - * @param {number} position read from the given position in the Binary. - * @param {number} length the number of bytes to read. - * @return {Buffer} - */ -Binary.prototype.read = function read(position, length) { - length = length && length > 0 ? length : this.position; - - // Let's return the data based on the type we have - if (this.buffer['slice']) { - return this.buffer.slice(position, position + length); - } else { - // Create a buffer to keep the result - var buffer = - typeof Uint8Array !== 'undefined' - ? new Uint8Array(new ArrayBuffer(length)) - : new Array(length); - for (var i = 0; i < length; i++) { - buffer[i] = this.buffer[position++]; - } - } - // Return the buffer - return buffer; -}; - -/** - * Returns the value of this binary as a string. - * - * @method - * @return {string} - */ -Binary.prototype.value = function value(asRaw) { - asRaw = asRaw == null ? false : asRaw; - - // Optimize to serialize for the situation where the data == size of buffer - if ( - asRaw && - typeof Buffer !== 'undefined' && - Buffer.isBuffer(this.buffer) && - this.buffer.length === this.position - ) - return this.buffer; - - // If it's a node.js buffer object - if (typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer)) { - return asRaw - ? this.buffer.slice(0, this.position) - : this.buffer.toString('binary', 0, this.position); - } else { - if (asRaw) { - // we support the slice command use it - if (this.buffer['slice'] != null) { - return this.buffer.slice(0, this.position); - } else { - // Create a new buffer to copy content to - var newBuffer = - Object.prototype.toString.call(this.buffer) === '[object Uint8Array]' - ? new Uint8Array(new ArrayBuffer(this.position)) - : new Array(this.position); - // Copy content - for (var i = 0; i < this.position; i++) { - newBuffer[i] = this.buffer[i]; - } - // Return the buffer - return newBuffer; - } - } else { - return convertArraytoUtf8BinaryString(this.buffer, 0, this.position); - } - } -}; - -/** - * Length. - * - * @method - * @return {number} the length of the binary. - */ -Binary.prototype.length = function length() { - return this.position; -}; - -/** - * @ignore - */ -Binary.prototype.toJSON = function() { - return this.buffer != null ? this.buffer.toString('base64') : ''; -}; - -/** - * @ignore - */ -Binary.prototype.toString = function(format) { - return this.buffer != null ? this.buffer.slice(0, this.position).toString(format) : ''; -}; - -/** - * Binary default subtype - * @ignore - */ -var BSON_BINARY_SUBTYPE_DEFAULT = 0; - -/** - * @ignore - */ -var writeStringToArray = function(data) { - // Create a buffer - var buffer = - typeof Uint8Array !== 'undefined' - ? new Uint8Array(new ArrayBuffer(data.length)) - : new Array(data.length); - // Write the content to the buffer - for (var i = 0; i < data.length; i++) { - buffer[i] = data.charCodeAt(i); - } - // Write the string to the buffer - return buffer; -}; - -/** - * Convert Array ot Uint8Array to Binary String - * - * @ignore - */ -var convertArraytoUtf8BinaryString = function(byteArray, startIndex, endIndex) { - var result = ''; - for (var i = startIndex; i < endIndex; i++) { - result = result + String.fromCharCode(byteArray[i]); - } - return result; -}; - -Binary.BUFFER_SIZE = 256; - -/** - * Default BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_DEFAULT = 0; -/** - * Function BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_FUNCTION = 1; -/** - * Byte Array BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_BYTE_ARRAY = 2; -/** - * OLD UUID BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_UUID_OLD = 3; -/** - * UUID BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_UUID = 4; -/** - * MD5 BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_MD5 = 5; -/** - * User BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_USER_DEFINED = 128; - -/** - * Expose. - */ -module.exports = Binary; -module.exports.Binary = Binary; diff --git a/scripts/node_modules/bson/lib/bson/bson.js b/scripts/node_modules/bson/lib/bson/bson.js deleted file mode 100644 index 912c5b92..00000000 --- a/scripts/node_modules/bson/lib/bson/bson.js +++ /dev/null @@ -1,386 +0,0 @@ -'use strict'; - -var Map = require('./map'), - Long = require('./long'), - Double = require('./double'), - Timestamp = require('./timestamp'), - ObjectID = require('./objectid'), - BSONRegExp = require('./regexp'), - Symbol = require('./symbol'), - Int32 = require('./int_32'), - Code = require('./code'), - Decimal128 = require('./decimal128'), - MinKey = require('./min_key'), - MaxKey = require('./max_key'), - DBRef = require('./db_ref'), - Binary = require('./binary'); - -// Parts of the parser -var deserialize = require('./parser/deserializer'), - serializer = require('./parser/serializer'), - calculateObjectSize = require('./parser/calculate_size'), - utils = require('./parser/utils'); - -/** - * @ignore - * @api private - */ -// Default Max Size -var MAXSIZE = 1024 * 1024 * 17; - -// Current Internal Temporary Serialization Buffer -var buffer = utils.allocBuffer(MAXSIZE); - -var BSON = function() {}; - -/** - * Serialize a Javascript object. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} [options.checkKeys] the serializer will check if keys are valid. - * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. - * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. - * @param {Number} [options.minInternalBufferSize=1024*1024*17] minimum size of the internal temporary serialization buffer **(default:1024*1024*17)**. - * @return {Buffer} returns the Buffer object containing the serialized object. - * @api public - */ -BSON.prototype.serialize = function serialize(object, options) { - options = options || {}; - // Unpack the options - var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; - var serializeFunctions = - typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; - var ignoreUndefined = - typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; - var minInternalBufferSize = - typeof options.minInternalBufferSize === 'number' ? options.minInternalBufferSize : MAXSIZE; - - // Resize the internal serialization buffer if needed - if (buffer.length < minInternalBufferSize) { - buffer = utils.allocBuffer(minInternalBufferSize); - } - - // Attempt to serialize - var serializationIndex = serializer( - buffer, - object, - checkKeys, - 0, - 0, - serializeFunctions, - ignoreUndefined, - [] - ); - // Create the final buffer - var finishedBuffer = utils.allocBuffer(serializationIndex); - // Copy into the finished buffer - buffer.copy(finishedBuffer, 0, 0, finishedBuffer.length); - // Return the buffer - return finishedBuffer; -}; - -/** - * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. - * - * @param {Object} object the Javascript object to serialize. - * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. - * @param {Boolean} [options.checkKeys] the serializer will check if keys are valid. - * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. - * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. - * @param {Number} [options.index] the index in the buffer where we wish to start serializing into. - * @return {Number} returns the index pointing to the last written byte in the buffer. - * @api public - */ -BSON.prototype.serializeWithBufferAndIndex = function(object, finalBuffer, options) { - options = options || {}; - // Unpack the options - var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; - var serializeFunctions = - typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; - var ignoreUndefined = - typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; - var startIndex = typeof options.index === 'number' ? options.index : 0; - - // Attempt to serialize - var serializationIndex = serializer( - finalBuffer, - object, - checkKeys, - startIndex || 0, - 0, - serializeFunctions, - ignoreUndefined - ); - - // Return the index - return serializationIndex - 1; -}; - -/** - * Deserialize data as BSON. - * - * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. - * @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized. - * @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse. - * @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function. - * @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits - * @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a node.js Buffer instance. - * @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types. - * @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer. - * @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances. - * @return {Object} returns the deserialized Javascript Object. - * @api public - */ -BSON.prototype.deserialize = function(buffer, options) { - return deserialize(buffer, options); -}; - -/** - * Calculate the bson size for a passed in Javascript object. - * - * @param {Object} object the Javascript object to calculate the BSON byte size for. - * @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. - * @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. - * @return {Number} returns the number of bytes the BSON object will take up. - * @api public - */ -BSON.prototype.calculateObjectSize = function(object, options) { - options = options || {}; - - var serializeFunctions = - typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; - var ignoreUndefined = - typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; - - return calculateObjectSize(object, serializeFunctions, ignoreUndefined); -}; - -/** - * Deserialize stream data as BSON documents. - * - * @param {Buffer} data the buffer containing the serialized set of BSON documents. - * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. - * @param {Number} numberOfDocuments number of documents to deserialize. - * @param {Array} documents an array where to store the deserialized documents. - * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. - * @param {Object} [options] additional options used for the deserialization. - * @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized. - * @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse. - * @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function. - * @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits - * @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a node.js Buffer instance. - * @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types. - * @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer. - * @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances. - * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. - * @api public - */ -BSON.prototype.deserializeStream = function( - data, - startIndex, - numberOfDocuments, - documents, - docStartIndex, - options -) { - options = options != null ? options : {}; - var index = startIndex; - // Loop over all documents - for (var i = 0; i < numberOfDocuments; i++) { - // Find size of the document - var size = - data[index] | (data[index + 1] << 8) | (data[index + 2] << 16) | (data[index + 3] << 24); - // Update options with index - options['index'] = index; - // Parse the document at this point - documents[docStartIndex + i] = this.deserialize(data, options); - // Adjust index by the document size - index = index + size; - } - - // Return object containing end index of parsing and list of documents - return index; -}; - -/** - * @ignore - * @api private - */ -// BSON MAX VALUES -BSON.BSON_INT32_MAX = 0x7fffffff; -BSON.BSON_INT32_MIN = -0x80000000; - -BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; -BSON.BSON_INT64_MIN = -Math.pow(2, 63); - -// JS MAX PRECISE VALUES -BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. -BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. - -// Internal long versions -// var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. -// var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. - -/** - * Number BSON Type - * - * @classconstant BSON_DATA_NUMBER - **/ -BSON.BSON_DATA_NUMBER = 1; -/** - * String BSON Type - * - * @classconstant BSON_DATA_STRING - **/ -BSON.BSON_DATA_STRING = 2; -/** - * Object BSON Type - * - * @classconstant BSON_DATA_OBJECT - **/ -BSON.BSON_DATA_OBJECT = 3; -/** - * Array BSON Type - * - * @classconstant BSON_DATA_ARRAY - **/ -BSON.BSON_DATA_ARRAY = 4; -/** - * Binary BSON Type - * - * @classconstant BSON_DATA_BINARY - **/ -BSON.BSON_DATA_BINARY = 5; -/** - * ObjectID BSON Type - * - * @classconstant BSON_DATA_OID - **/ -BSON.BSON_DATA_OID = 7; -/** - * Boolean BSON Type - * - * @classconstant BSON_DATA_BOOLEAN - **/ -BSON.BSON_DATA_BOOLEAN = 8; -/** - * Date BSON Type - * - * @classconstant BSON_DATA_DATE - **/ -BSON.BSON_DATA_DATE = 9; -/** - * null BSON Type - * - * @classconstant BSON_DATA_NULL - **/ -BSON.BSON_DATA_NULL = 10; -/** - * RegExp BSON Type - * - * @classconstant BSON_DATA_REGEXP - **/ -BSON.BSON_DATA_REGEXP = 11; -/** - * Code BSON Type - * - * @classconstant BSON_DATA_CODE - **/ -BSON.BSON_DATA_CODE = 13; -/** - * Symbol BSON Type - * - * @classconstant BSON_DATA_SYMBOL - **/ -BSON.BSON_DATA_SYMBOL = 14; -/** - * Code with Scope BSON Type - * - * @classconstant BSON_DATA_CODE_W_SCOPE - **/ -BSON.BSON_DATA_CODE_W_SCOPE = 15; -/** - * 32 bit Integer BSON Type - * - * @classconstant BSON_DATA_INT - **/ -BSON.BSON_DATA_INT = 16; -/** - * Timestamp BSON Type - * - * @classconstant BSON_DATA_TIMESTAMP - **/ -BSON.BSON_DATA_TIMESTAMP = 17; -/** - * Long BSON Type - * - * @classconstant BSON_DATA_LONG - **/ -BSON.BSON_DATA_LONG = 18; -/** - * MinKey BSON Type - * - * @classconstant BSON_DATA_MIN_KEY - **/ -BSON.BSON_DATA_MIN_KEY = 0xff; -/** - * MaxKey BSON Type - * - * @classconstant BSON_DATA_MAX_KEY - **/ -BSON.BSON_DATA_MAX_KEY = 0x7f; - -/** - * Binary Default Type - * - * @classconstant BSON_BINARY_SUBTYPE_DEFAULT - **/ -BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; -/** - * Binary Function Type - * - * @classconstant BSON_BINARY_SUBTYPE_FUNCTION - **/ -BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; -/** - * Binary Byte Array Type - * - * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY - **/ -BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; -/** - * Binary UUID Type - * - * @classconstant BSON_BINARY_SUBTYPE_UUID - **/ -BSON.BSON_BINARY_SUBTYPE_UUID = 3; -/** - * Binary MD5 Type - * - * @classconstant BSON_BINARY_SUBTYPE_MD5 - **/ -BSON.BSON_BINARY_SUBTYPE_MD5 = 4; -/** - * Binary User Defined Type - * - * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED - **/ -BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; - -// Return BSON -module.exports = BSON; -module.exports.Code = Code; -module.exports.Map = Map; -module.exports.Symbol = Symbol; -module.exports.BSON = BSON; -module.exports.DBRef = DBRef; -module.exports.Binary = Binary; -module.exports.ObjectID = ObjectID; -module.exports.Long = Long; -module.exports.Timestamp = Timestamp; -module.exports.Double = Double; -module.exports.Int32 = Int32; -module.exports.MinKey = MinKey; -module.exports.MaxKey = MaxKey; -module.exports.BSONRegExp = BSONRegExp; -module.exports.Decimal128 = Decimal128; diff --git a/scripts/node_modules/bson/lib/bson/code.js b/scripts/node_modules/bson/lib/bson/code.js deleted file mode 100644 index c2984cd5..00000000 --- a/scripts/node_modules/bson/lib/bson/code.js +++ /dev/null @@ -1,24 +0,0 @@ -/** - * A class representation of the BSON Code type. - * - * @class - * @param {(string|function)} code a string or function. - * @param {Object} [scope] an optional scope for the function. - * @return {Code} - */ -var Code = function Code(code, scope) { - if (!(this instanceof Code)) return new Code(code, scope); - this._bsontype = 'Code'; - this.code = code; - this.scope = scope; -}; - -/** - * @ignore - */ -Code.prototype.toJSON = function() { - return { scope: this.scope, code: this.code }; -}; - -module.exports = Code; -module.exports.Code = Code; diff --git a/scripts/node_modules/bson/lib/bson/db_ref.js b/scripts/node_modules/bson/lib/bson/db_ref.js deleted file mode 100644 index f95795b1..00000000 --- a/scripts/node_modules/bson/lib/bson/db_ref.js +++ /dev/null @@ -1,32 +0,0 @@ -/** - * A class representation of the BSON DBRef type. - * - * @class - * @param {string} namespace the collection name. - * @param {ObjectID} oid the reference ObjectID. - * @param {string} [db] optional db name, if omitted the reference is local to the current db. - * @return {DBRef} - */ -function DBRef(namespace, oid, db) { - if (!(this instanceof DBRef)) return new DBRef(namespace, oid, db); - - this._bsontype = 'DBRef'; - this.namespace = namespace; - this.oid = oid; - this.db = db; -} - -/** - * @ignore - * @api private - */ -DBRef.prototype.toJSON = function() { - return { - $ref: this.namespace, - $id: this.oid, - $db: this.db == null ? '' : this.db - }; -}; - -module.exports = DBRef; -module.exports.DBRef = DBRef; diff --git a/scripts/node_modules/bson/lib/bson/decimal128.js b/scripts/node_modules/bson/lib/bson/decimal128.js deleted file mode 100644 index 924513f4..00000000 --- a/scripts/node_modules/bson/lib/bson/decimal128.js +++ /dev/null @@ -1,820 +0,0 @@ -'use strict'; - -var Long = require('./long'); - -var PARSE_STRING_REGEXP = /^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/; -var PARSE_INF_REGEXP = /^(\+|-)?(Infinity|inf)$/i; -var PARSE_NAN_REGEXP = /^(\+|-)?NaN$/i; - -var EXPONENT_MAX = 6111; -var EXPONENT_MIN = -6176; -var EXPONENT_BIAS = 6176; -var MAX_DIGITS = 34; - -// Nan value bits as 32 bit values (due to lack of longs) -var NAN_BUFFER = [ - 0x7c, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00 -].reverse(); -// Infinity value bits 32 bit values (due to lack of longs) -var INF_NEGATIVE_BUFFER = [ - 0xf8, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00 -].reverse(); -var INF_POSITIVE_BUFFER = [ - 0x78, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00, - 0x00 -].reverse(); - -var EXPONENT_REGEX = /^([-+])?(\d+)?$/; - -var utils = require('./parser/utils'); - -// Detect if the value is a digit -var isDigit = function(value) { - return !isNaN(parseInt(value, 10)); -}; - -// Divide two uint128 values -var divideu128 = function(value) { - var DIVISOR = Long.fromNumber(1000 * 1000 * 1000); - var _rem = Long.fromNumber(0); - var i = 0; - - if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) { - return { quotient: value, rem: _rem }; - } - - for (i = 0; i <= 3; i++) { - // Adjust remainder to match value of next dividend - _rem = _rem.shiftLeft(32); - // Add the divided to _rem - _rem = _rem.add(new Long(value.parts[i], 0)); - value.parts[i] = _rem.div(DIVISOR).low_; - _rem = _rem.modulo(DIVISOR); - } - - return { quotient: value, rem: _rem }; -}; - -// Multiply two Long values and return the 128 bit value -var multiply64x2 = function(left, right) { - if (!left && !right) { - return { high: Long.fromNumber(0), low: Long.fromNumber(0) }; - } - - var leftHigh = left.shiftRightUnsigned(32); - var leftLow = new Long(left.getLowBits(), 0); - var rightHigh = right.shiftRightUnsigned(32); - var rightLow = new Long(right.getLowBits(), 0); - - var productHigh = leftHigh.multiply(rightHigh); - var productMid = leftHigh.multiply(rightLow); - var productMid2 = leftLow.multiply(rightHigh); - var productLow = leftLow.multiply(rightLow); - - productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); - productMid = new Long(productMid.getLowBits(), 0) - .add(productMid2) - .add(productLow.shiftRightUnsigned(32)); - - productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); - productLow = productMid.shiftLeft(32).add(new Long(productLow.getLowBits(), 0)); - - // Return the 128 bit result - return { high: productHigh, low: productLow }; -}; - -var lessThan = function(left, right) { - // Make values unsigned - var uhleft = left.high_ >>> 0; - var uhright = right.high_ >>> 0; - - // Compare high bits first - if (uhleft < uhright) { - return true; - } else if (uhleft === uhright) { - var ulleft = left.low_ >>> 0; - var ulright = right.low_ >>> 0; - if (ulleft < ulright) return true; - } - - return false; -}; - -// var longtoHex = function(value) { -// var buffer = utils.allocBuffer(8); -// var index = 0; -// // Encode the low 64 bits of the decimal -// // Encode low bits -// buffer[index++] = value.low_ & 0xff; -// buffer[index++] = (value.low_ >> 8) & 0xff; -// buffer[index++] = (value.low_ >> 16) & 0xff; -// buffer[index++] = (value.low_ >> 24) & 0xff; -// // Encode high bits -// buffer[index++] = value.high_ & 0xff; -// buffer[index++] = (value.high_ >> 8) & 0xff; -// buffer[index++] = (value.high_ >> 16) & 0xff; -// buffer[index++] = (value.high_ >> 24) & 0xff; -// return buffer.reverse().toString('hex'); -// }; - -// var int32toHex = function(value) { -// var buffer = utils.allocBuffer(4); -// var index = 0; -// // Encode the low 64 bits of the decimal -// // Encode low bits -// buffer[index++] = value & 0xff; -// buffer[index++] = (value >> 8) & 0xff; -// buffer[index++] = (value >> 16) & 0xff; -// buffer[index++] = (value >> 24) & 0xff; -// return buffer.reverse().toString('hex'); -// }; - -/** - * A class representation of the BSON Decimal128 type. - * - * @class - * @param {Buffer} bytes a buffer containing the raw Decimal128 bytes. - * @return {Double} - */ -var Decimal128 = function(bytes) { - this._bsontype = 'Decimal128'; - this.bytes = bytes; -}; - -/** - * Create a Decimal128 instance from a string representation - * - * @method - * @param {string} string a numeric string representation. - * @return {Decimal128} returns a Decimal128 instance. - */ -Decimal128.fromString = function(string) { - // Parse state tracking - var isNegative = false; - var sawRadix = false; - var foundNonZero = false; - - // Total number of significant digits (no leading or trailing zero) - var significantDigits = 0; - // Total number of significand digits read - var nDigitsRead = 0; - // Total number of digits (no leading zeros) - var nDigits = 0; - // The number of the digits after radix - var radixPosition = 0; - // The index of the first non-zero in *str* - var firstNonZero = 0; - - // Digits Array - var digits = [0]; - // The number of digits in digits - var nDigitsStored = 0; - // Insertion pointer for digits - var digitsInsert = 0; - // The index of the first non-zero digit - var firstDigit = 0; - // The index of the last digit - var lastDigit = 0; - - // Exponent - var exponent = 0; - // loop index over array - var i = 0; - // The high 17 digits of the significand - var significandHigh = [0, 0]; - // The low 17 digits of the significand - var significandLow = [0, 0]; - // The biased exponent - var biasedExponent = 0; - - // Read index - var index = 0; - - // Trim the string - string = string.trim(); - - // Naively prevent against REDOS attacks. - // TODO: implementing a custom parsing for this, or refactoring the regex would yield - // further gains. - if (string.length >= 7000) { - throw new Error('' + string + ' not a valid Decimal128 string'); - } - - // Results - var stringMatch = string.match(PARSE_STRING_REGEXP); - var infMatch = string.match(PARSE_INF_REGEXP); - var nanMatch = string.match(PARSE_NAN_REGEXP); - - // Validate the string - if ((!stringMatch && !infMatch && !nanMatch) || string.length === 0) { - throw new Error('' + string + ' not a valid Decimal128 string'); - } - - // Check if we have an illegal exponent format - if (stringMatch && stringMatch[4] && stringMatch[2] === undefined) { - throw new Error('' + string + ' not a valid Decimal128 string'); - } - - // Get the negative or positive sign - if (string[index] === '+' || string[index] === '-') { - isNegative = string[index++] === '-'; - } - - // Check if user passed Infinity or NaN - if (!isDigit(string[index]) && string[index] !== '.') { - if (string[index] === 'i' || string[index] === 'I') { - return new Decimal128(utils.toBuffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); - } else if (string[index] === 'N') { - return new Decimal128(utils.toBuffer(NAN_BUFFER)); - } - } - - // Read all the digits - while (isDigit(string[index]) || string[index] === '.') { - if (string[index] === '.') { - if (sawRadix) { - return new Decimal128(utils.toBuffer(NAN_BUFFER)); - } - - sawRadix = true; - index = index + 1; - continue; - } - - if (nDigitsStored < 34) { - if (string[index] !== '0' || foundNonZero) { - if (!foundNonZero) { - firstNonZero = nDigitsRead; - } - - foundNonZero = true; - - // Only store 34 digits - digits[digitsInsert++] = parseInt(string[index], 10); - nDigitsStored = nDigitsStored + 1; - } - } - - if (foundNonZero) { - nDigits = nDigits + 1; - } - - if (sawRadix) { - radixPosition = radixPosition + 1; - } - - nDigitsRead = nDigitsRead + 1; - index = index + 1; - } - - if (sawRadix && !nDigitsRead) { - throw new Error('' + string + ' not a valid Decimal128 string'); - } - - // Read exponent if exists - if (string[index] === 'e' || string[index] === 'E') { - // Read exponent digits - var match = string.substr(++index).match(EXPONENT_REGEX); - - // No digits read - if (!match || !match[2]) { - return new Decimal128(utils.toBuffer(NAN_BUFFER)); - } - - // Get exponent - exponent = parseInt(match[0], 10); - - // Adjust the index - index = index + match[0].length; - } - - // Return not a number - if (string[index]) { - return new Decimal128(utils.toBuffer(NAN_BUFFER)); - } - - // Done reading input - // Find first non-zero digit in digits - firstDigit = 0; - - if (!nDigitsStored) { - firstDigit = 0; - lastDigit = 0; - digits[0] = 0; - nDigits = 1; - nDigitsStored = 1; - significantDigits = 0; - } else { - lastDigit = nDigitsStored - 1; - significantDigits = nDigits; - - if (exponent !== 0 && significantDigits !== 1) { - while (string[firstNonZero + significantDigits - 1] === '0') { - significantDigits = significantDigits - 1; - } - } - } - - // Normalization of exponent - // Correct exponent based on radix position, and shift significand as needed - // to represent user input - - // Overflow prevention - if (exponent <= radixPosition && radixPosition - exponent > 1 << 14) { - exponent = EXPONENT_MIN; - } else { - exponent = exponent - radixPosition; - } - - // Attempt to normalize the exponent - while (exponent > EXPONENT_MAX) { - // Shift exponent to significand and decrease - lastDigit = lastDigit + 1; - - if (lastDigit - firstDigit > MAX_DIGITS) { - // Check if we have a zero then just hard clamp, otherwise fail - var digitsString = digits.join(''); - if (digitsString.match(/^0+$/)) { - exponent = EXPONENT_MAX; - break; - } else { - return new Decimal128(utils.toBuffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); - } - } - - exponent = exponent - 1; - } - - while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) { - // Shift last digit - if (lastDigit === 0) { - exponent = EXPONENT_MIN; - significantDigits = 0; - break; - } - - if (nDigitsStored < nDigits) { - // adjust to match digits not stored - nDigits = nDigits - 1; - } else { - // adjust to round - lastDigit = lastDigit - 1; - } - - if (exponent < EXPONENT_MAX) { - exponent = exponent + 1; - } else { - // Check if we have a zero then just hard clamp, otherwise fail - digitsString = digits.join(''); - if (digitsString.match(/^0+$/)) { - exponent = EXPONENT_MAX; - break; - } else { - return new Decimal128(utils.toBuffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); - } - } - } - - // Round - // We've normalized the exponent, but might still need to round. - if (lastDigit - firstDigit + 1 < significantDigits && string[significantDigits] !== '0') { - var endOfString = nDigitsRead; - - // If we have seen a radix point, 'string' is 1 longer than we have - // documented with ndigits_read, so inc the position of the first nonzero - // digit and the position that digits are read to. - if (sawRadix && exponent === EXPONENT_MIN) { - firstNonZero = firstNonZero + 1; - endOfString = endOfString + 1; - } - - var roundDigit = parseInt(string[firstNonZero + lastDigit + 1], 10); - var roundBit = 0; - - if (roundDigit >= 5) { - roundBit = 1; - - if (roundDigit === 5) { - roundBit = digits[lastDigit] % 2 === 1; - - for (i = firstNonZero + lastDigit + 2; i < endOfString; i++) { - if (parseInt(string[i], 10)) { - roundBit = 1; - break; - } - } - } - } - - if (roundBit) { - var dIdx = lastDigit; - - for (; dIdx >= 0; dIdx--) { - if (++digits[dIdx] > 9) { - digits[dIdx] = 0; - - // overflowed most significant digit - if (dIdx === 0) { - if (exponent < EXPONENT_MAX) { - exponent = exponent + 1; - digits[dIdx] = 1; - } else { - return new Decimal128( - utils.toBuffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER) - ); - } - } - } else { - break; - } - } - } - } - - // Encode significand - // The high 17 digits of the significand - significandHigh = Long.fromNumber(0); - // The low 17 digits of the significand - significandLow = Long.fromNumber(0); - - // read a zero - if (significantDigits === 0) { - significandHigh = Long.fromNumber(0); - significandLow = Long.fromNumber(0); - } else if (lastDigit - firstDigit < 17) { - dIdx = firstDigit; - significandLow = Long.fromNumber(digits[dIdx++]); - significandHigh = new Long(0, 0); - - for (; dIdx <= lastDigit; dIdx++) { - significandLow = significandLow.multiply(Long.fromNumber(10)); - significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); - } - } else { - dIdx = firstDigit; - significandHigh = Long.fromNumber(digits[dIdx++]); - - for (; dIdx <= lastDigit - 17; dIdx++) { - significandHigh = significandHigh.multiply(Long.fromNumber(10)); - significandHigh = significandHigh.add(Long.fromNumber(digits[dIdx])); - } - - significandLow = Long.fromNumber(digits[dIdx++]); - - for (; dIdx <= lastDigit; dIdx++) { - significandLow = significandLow.multiply(Long.fromNumber(10)); - significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); - } - } - - var significand = multiply64x2(significandHigh, Long.fromString('100000000000000000')); - - significand.low = significand.low.add(significandLow); - - if (lessThan(significand.low, significandLow)) { - significand.high = significand.high.add(Long.fromNumber(1)); - } - - // Biased exponent - biasedExponent = exponent + EXPONENT_BIAS; - var dec = { low: Long.fromNumber(0), high: Long.fromNumber(0) }; - - // Encode combination, exponent, and significand. - if ( - significand.high - .shiftRightUnsigned(49) - .and(Long.fromNumber(1)) - .equals(Long.fromNumber) - ) { - // Encode '11' into bits 1 to 3 - dec.high = dec.high.or(Long.fromNumber(0x3).shiftLeft(61)); - dec.high = dec.high.or( - Long.fromNumber(biasedExponent).and(Long.fromNumber(0x3fff).shiftLeft(47)) - ); - dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x7fffffffffff))); - } else { - dec.high = dec.high.or(Long.fromNumber(biasedExponent & 0x3fff).shiftLeft(49)); - dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x1ffffffffffff))); - } - - dec.low = significand.low; - - // Encode sign - if (isNegative) { - dec.high = dec.high.or(Long.fromString('9223372036854775808')); - } - - // Encode into a buffer - var buffer = utils.allocBuffer(16); - index = 0; - - // Encode the low 64 bits of the decimal - // Encode low bits - buffer[index++] = dec.low.low_ & 0xff; - buffer[index++] = (dec.low.low_ >> 8) & 0xff; - buffer[index++] = (dec.low.low_ >> 16) & 0xff; - buffer[index++] = (dec.low.low_ >> 24) & 0xff; - // Encode high bits - buffer[index++] = dec.low.high_ & 0xff; - buffer[index++] = (dec.low.high_ >> 8) & 0xff; - buffer[index++] = (dec.low.high_ >> 16) & 0xff; - buffer[index++] = (dec.low.high_ >> 24) & 0xff; - - // Encode the high 64 bits of the decimal - // Encode low bits - buffer[index++] = dec.high.low_ & 0xff; - buffer[index++] = (dec.high.low_ >> 8) & 0xff; - buffer[index++] = (dec.high.low_ >> 16) & 0xff; - buffer[index++] = (dec.high.low_ >> 24) & 0xff; - // Encode high bits - buffer[index++] = dec.high.high_ & 0xff; - buffer[index++] = (dec.high.high_ >> 8) & 0xff; - buffer[index++] = (dec.high.high_ >> 16) & 0xff; - buffer[index++] = (dec.high.high_ >> 24) & 0xff; - - // Return the new Decimal128 - return new Decimal128(buffer); -}; - -// Extract least significant 5 bits -var COMBINATION_MASK = 0x1f; -// Extract least significant 14 bits -var EXPONENT_MASK = 0x3fff; -// Value of combination field for Inf -var COMBINATION_INFINITY = 30; -// Value of combination field for NaN -var COMBINATION_NAN = 31; -// Value of combination field for NaN -// var COMBINATION_SNAN = 32; -// decimal128 exponent bias -EXPONENT_BIAS = 6176; - -/** - * Create a string representation of the raw Decimal128 value - * - * @method - * @return {string} returns a Decimal128 string representation. - */ -Decimal128.prototype.toString = function() { - // Note: bits in this routine are referred to starting at 0, - // from the sign bit, towards the coefficient. - - // bits 0 - 31 - var high; - // bits 32 - 63 - var midh; - // bits 64 - 95 - var midl; - // bits 96 - 127 - var low; - // bits 1 - 5 - var combination; - // decoded biased exponent (14 bits) - var biased_exponent; - // the number of significand digits - var significand_digits = 0; - // the base-10 digits in the significand - var significand = new Array(36); - for (var i = 0; i < significand.length; i++) significand[i] = 0; - // read pointer into significand - var index = 0; - - // unbiased exponent - var exponent; - // the exponent if scientific notation is used - var scientific_exponent; - - // true if the number is zero - var is_zero = false; - - // the most signifcant significand bits (50-46) - var significand_msb; - // temporary storage for significand decoding - var significand128 = { parts: new Array(4) }; - // indexing variables - i; - var j, k; - - // Output string - var string = []; - - // Unpack index - index = 0; - - // Buffer reference - var buffer = this.bytes; - - // Unpack the low 64bits into a long - low = - buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); - midl = - buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); - - // Unpack the high 64bits into a long - midh = - buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); - high = - buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); - - // Unpack index - index = 0; - - // Create the state of the decimal - var dec = { - low: new Long(low, midl), - high: new Long(midh, high) - }; - - if (dec.high.lessThan(Long.ZERO)) { - string.push('-'); - } - - // Decode combination field and exponent - combination = (high >> 26) & COMBINATION_MASK; - - if (combination >> 3 === 3) { - // Check for 'special' values - if (combination === COMBINATION_INFINITY) { - return string.join('') + 'Infinity'; - } else if (combination === COMBINATION_NAN) { - return 'NaN'; - } else { - biased_exponent = (high >> 15) & EXPONENT_MASK; - significand_msb = 0x08 + ((high >> 14) & 0x01); - } - } else { - significand_msb = (high >> 14) & 0x07; - biased_exponent = (high >> 17) & EXPONENT_MASK; - } - - exponent = biased_exponent - EXPONENT_BIAS; - - // Create string of significand digits - - // Convert the 114-bit binary number represented by - // (significand_high, significand_low) to at most 34 decimal - // digits through modulo and division. - significand128.parts[0] = (high & 0x3fff) + ((significand_msb & 0xf) << 14); - significand128.parts[1] = midh; - significand128.parts[2] = midl; - significand128.parts[3] = low; - - if ( - significand128.parts[0] === 0 && - significand128.parts[1] === 0 && - significand128.parts[2] === 0 && - significand128.parts[3] === 0 - ) { - is_zero = true; - } else { - for (k = 3; k >= 0; k--) { - var least_digits = 0; - // Peform the divide - var result = divideu128(significand128); - significand128 = result.quotient; - least_digits = result.rem.low_; - - // We now have the 9 least significant digits (in base 2). - // Convert and output to string. - if (!least_digits) continue; - - for (j = 8; j >= 0; j--) { - // significand[k * 9 + j] = Math.round(least_digits % 10); - significand[k * 9 + j] = least_digits % 10; - // least_digits = Math.round(least_digits / 10); - least_digits = Math.floor(least_digits / 10); - } - } - } - - // Output format options: - // Scientific - [-]d.dddE(+/-)dd or [-]dE(+/-)dd - // Regular - ddd.ddd - - if (is_zero) { - significand_digits = 1; - significand[index] = 0; - } else { - significand_digits = 36; - i = 0; - - while (!significand[index]) { - i++; - significand_digits = significand_digits - 1; - index = index + 1; - } - } - - scientific_exponent = significand_digits - 1 + exponent; - - // The scientific exponent checks are dictated by the string conversion - // specification and are somewhat arbitrary cutoffs. - // - // We must check exponent > 0, because if this is the case, the number - // has trailing zeros. However, we *cannot* output these trailing zeros, - // because doing so would change the precision of the value, and would - // change stored data if the string converted number is round tripped. - - if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) { - // Scientific format - string.push(significand[index++]); - significand_digits = significand_digits - 1; - - if (significand_digits) { - string.push('.'); - } - - for (i = 0; i < significand_digits; i++) { - string.push(significand[index++]); - } - - // Exponent - string.push('E'); - if (scientific_exponent > 0) { - string.push('+' + scientific_exponent); - } else { - string.push(scientific_exponent); - } - } else { - // Regular format with no decimal place - if (exponent >= 0) { - for (i = 0; i < significand_digits; i++) { - string.push(significand[index++]); - } - } else { - var radix_position = significand_digits + exponent; - - // non-zero digits before radix - if (radix_position > 0) { - for (i = 0; i < radix_position; i++) { - string.push(significand[index++]); - } - } else { - string.push('0'); - } - - string.push('.'); - // add leading zeros after radix - while (radix_position++ < 0) { - string.push('0'); - } - - for (i = 0; i < significand_digits - Math.max(radix_position - 1, 0); i++) { - string.push(significand[index++]); - } - } - } - - return string.join(''); -}; - -Decimal128.prototype.toJSON = function() { - return { $numberDecimal: this.toString() }; -}; - -module.exports = Decimal128; -module.exports.Decimal128 = Decimal128; diff --git a/scripts/node_modules/bson/lib/bson/double.js b/scripts/node_modules/bson/lib/bson/double.js deleted file mode 100644 index 523c21f8..00000000 --- a/scripts/node_modules/bson/lib/bson/double.js +++ /dev/null @@ -1,33 +0,0 @@ -/** - * A class representation of the BSON Double type. - * - * @class - * @param {number} value the number we want to represent as a double. - * @return {Double} - */ -function Double(value) { - if (!(this instanceof Double)) return new Double(value); - - this._bsontype = 'Double'; - this.value = value; -} - -/** - * Access the number value. - * - * @method - * @return {number} returns the wrapped double number. - */ -Double.prototype.valueOf = function() { - return this.value; -}; - -/** - * @ignore - */ -Double.prototype.toJSON = function() { - return this.value; -}; - -module.exports = Double; -module.exports.Double = Double; diff --git a/scripts/node_modules/bson/lib/bson/float_parser.js b/scripts/node_modules/bson/lib/bson/float_parser.js deleted file mode 100644 index 0054a2f6..00000000 --- a/scripts/node_modules/bson/lib/bson/float_parser.js +++ /dev/null @@ -1,124 +0,0 @@ -// Copyright (c) 2008, Fair Oaks Labs, Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * Neither the name of Fair Oaks Labs, Inc. nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. -// -// -// Modifications to writeIEEE754 to support negative zeroes made by Brian White - -var readIEEE754 = function(buffer, offset, endian, mLen, nBytes) { - var e, - m, - bBE = endian === 'big', - eLen = nBytes * 8 - mLen - 1, - eMax = (1 << eLen) - 1, - eBias = eMax >> 1, - nBits = -7, - i = bBE ? 0 : nBytes - 1, - d = bBE ? 1 : -1, - s = buffer[offset + i]; - - i += d; - - e = s & ((1 << -nBits) - 1); - s >>= -nBits; - nBits += eLen; - for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8); - - m = e & ((1 << -nBits) - 1); - e >>= -nBits; - nBits += mLen; - for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8); - - if (e === 0) { - e = 1 - eBias; - } else if (e === eMax) { - return m ? NaN : (s ? -1 : 1) * Infinity; - } else { - m = m + Math.pow(2, mLen); - e = e - eBias; - } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen); -}; - -var writeIEEE754 = function(buffer, value, offset, endian, mLen, nBytes) { - var e, - m, - c, - bBE = endian === 'big', - eLen = nBytes * 8 - mLen - 1, - eMax = (1 << eLen) - 1, - eBias = eMax >> 1, - rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0, - i = bBE ? nBytes - 1 : 0, - d = bBE ? -1 : 1, - s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; - - value = Math.abs(value); - - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0; - e = eMax; - } else { - e = Math.floor(Math.log(value) / Math.LN2); - if (value * (c = Math.pow(2, -e)) < 1) { - e--; - c *= 2; - } - if (e + eBias >= 1) { - value += rt / c; - } else { - value += rt * Math.pow(2, 1 - eBias); - } - if (value * c >= 2) { - e++; - c /= 2; - } - - if (e + eBias >= eMax) { - m = 0; - e = eMax; - } else if (e + eBias >= 1) { - m = (value * c - 1) * Math.pow(2, mLen); - e = e + eBias; - } else { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); - e = 0; - } - } - - for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8); - - e = (e << mLen) | m; - eLen += mLen; - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8); - - buffer[offset + i - d] |= s * 128; -}; - -exports.readIEEE754 = readIEEE754; -exports.writeIEEE754 = writeIEEE754; diff --git a/scripts/node_modules/bson/lib/bson/int_32.js b/scripts/node_modules/bson/lib/bson/int_32.js deleted file mode 100644 index 85dbdec6..00000000 --- a/scripts/node_modules/bson/lib/bson/int_32.js +++ /dev/null @@ -1,33 +0,0 @@ -/** - * A class representation of a BSON Int32 type. - * - * @class - * @param {number} value the number we want to represent as an int32. - * @return {Int32} - */ -var Int32 = function(value) { - if (!(this instanceof Int32)) return new Int32(value); - - this._bsontype = 'Int32'; - this.value = value; -}; - -/** - * Access the number value. - * - * @method - * @return {number} returns the wrapped int32 number. - */ -Int32.prototype.valueOf = function() { - return this.value; -}; - -/** - * @ignore - */ -Int32.prototype.toJSON = function() { - return this.value; -}; - -module.exports = Int32; -module.exports.Int32 = Int32; diff --git a/scripts/node_modules/bson/lib/bson/long.js b/scripts/node_modules/bson/lib/bson/long.js deleted file mode 100644 index 78215aa3..00000000 --- a/scripts/node_modules/bson/lib/bson/long.js +++ /dev/null @@ -1,851 +0,0 @@ -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// Copyright 2009 Google Inc. All Rights Reserved - -/** - * Defines a Long class for representing a 64-bit two's-complement - * integer value, which faithfully simulates the behavior of a Java "Long". This - * implementation is derived from LongLib in GWT. - * - * Constructs a 64-bit two's-complement integer, given its low and high 32-bit - * values as *signed* integers. See the from* functions below for more - * convenient ways of constructing Longs. - * - * The internal representation of a Long is the two given signed, 32-bit values. - * We use 32-bit pieces because these are the size of integers on which - * Javascript performs bit-operations. For operations like addition and - * multiplication, we split each number into 16-bit pieces, which can easily be - * multiplied within Javascript's floating-point representation without overflow - * or change in sign. - * - * In the algorithms below, we frequently reduce the negative case to the - * positive case by negating the input(s) and then post-processing the result. - * Note that we must ALWAYS check specially whether those values are MIN_VALUE - * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as - * a positive number, it overflows back into a negative). Not handling this - * case would often result in infinite recursion. - * - * @class - * @param {number} low the low (signed) 32 bits of the Long. - * @param {number} high the high (signed) 32 bits of the Long. - * @return {Long} - */ -function Long(low, high) { - if (!(this instanceof Long)) return new Long(low, high); - - this._bsontype = 'Long'; - /** - * @type {number} - * @ignore - */ - this.low_ = low | 0; // force into 32 signed bits. - - /** - * @type {number} - * @ignore - */ - this.high_ = high | 0; // force into 32 signed bits. -} - -/** - * Return the int value. - * - * @method - * @return {number} the value, assuming it is a 32-bit integer. - */ -Long.prototype.toInt = function() { - return this.low_; -}; - -/** - * Return the Number value. - * - * @method - * @return {number} the closest floating-point representation to this value. - */ -Long.prototype.toNumber = function() { - return this.high_ * Long.TWO_PWR_32_DBL_ + this.getLowBitsUnsigned(); -}; - -/** - * Return the JSON value. - * - * @method - * @return {string} the JSON representation. - */ -Long.prototype.toJSON = function() { - return this.toString(); -}; - -/** - * Return the String value. - * - * @method - * @param {number} [opt_radix] the radix in which the text should be written. - * @return {string} the textual representation of this value. - */ -Long.prototype.toString = function(opt_radix) { - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (this.isZero()) { - return '0'; - } - - if (this.isNegative()) { - if (this.equals(Long.MIN_VALUE)) { - // We need to change the Long value before it can be negated, so we remove - // the bottom-most digit in this base and then recurse to do the rest. - var radixLong = Long.fromNumber(radix); - var div = this.div(radixLong); - var rem = div.multiply(radixLong).subtract(this); - return div.toString(radix) + rem.toInt().toString(radix); - } else { - return '-' + this.negate().toString(radix); - } - } - - // Do several (6) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Long.fromNumber(Math.pow(radix, 6)); - - rem = this; - var result = ''; - - while (!rem.isZero()) { - var remDiv = rem.div(radixToPower); - var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); - var digits = intval.toString(radix); - - rem = remDiv; - if (rem.isZero()) { - return digits + result; - } else { - while (digits.length < 6) { - digits = '0' + digits; - } - result = '' + digits + result; - } - } -}; - -/** - * Return the high 32-bits value. - * - * @method - * @return {number} the high 32-bits as a signed value. - */ -Long.prototype.getHighBits = function() { - return this.high_; -}; - -/** - * Return the low 32-bits value. - * - * @method - * @return {number} the low 32-bits as a signed value. - */ -Long.prototype.getLowBits = function() { - return this.low_; -}; - -/** - * Return the low unsigned 32-bits value. - * - * @method - * @return {number} the low 32-bits as an unsigned value. - */ -Long.prototype.getLowBitsUnsigned = function() { - return this.low_ >= 0 ? this.low_ : Long.TWO_PWR_32_DBL_ + this.low_; -}; - -/** - * Returns the number of bits needed to represent the absolute value of this Long. - * - * @method - * @return {number} Returns the number of bits needed to represent the absolute value of this Long. - */ -Long.prototype.getNumBitsAbs = function() { - if (this.isNegative()) { - if (this.equals(Long.MIN_VALUE)) { - return 64; - } else { - return this.negate().getNumBitsAbs(); - } - } else { - var val = this.high_ !== 0 ? this.high_ : this.low_; - for (var bit = 31; bit > 0; bit--) { - if ((val & (1 << bit)) !== 0) { - break; - } - } - return this.high_ !== 0 ? bit + 33 : bit + 1; - } -}; - -/** - * Return whether this value is zero. - * - * @method - * @return {boolean} whether this value is zero. - */ -Long.prototype.isZero = function() { - return this.high_ === 0 && this.low_ === 0; -}; - -/** - * Return whether this value is negative. - * - * @method - * @return {boolean} whether this value is negative. - */ -Long.prototype.isNegative = function() { - return this.high_ < 0; -}; - -/** - * Return whether this value is odd. - * - * @method - * @return {boolean} whether this value is odd. - */ -Long.prototype.isOdd = function() { - return (this.low_ & 1) === 1; -}; - -/** - * Return whether this Long equals the other - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long equals the other - */ -Long.prototype.equals = function(other) { - return this.high_ === other.high_ && this.low_ === other.low_; -}; - -/** - * Return whether this Long does not equal the other. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long does not equal the other. - */ -Long.prototype.notEquals = function(other) { - return this.high_ !== other.high_ || this.low_ !== other.low_; -}; - -/** - * Return whether this Long is less than the other. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long is less than the other. - */ -Long.prototype.lessThan = function(other) { - return this.compare(other) < 0; -}; - -/** - * Return whether this Long is less than or equal to the other. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long is less than or equal to the other. - */ -Long.prototype.lessThanOrEqual = function(other) { - return this.compare(other) <= 0; -}; - -/** - * Return whether this Long is greater than the other. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long is greater than the other. - */ -Long.prototype.greaterThan = function(other) { - return this.compare(other) > 0; -}; - -/** - * Return whether this Long is greater than or equal to the other. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long is greater than or equal to the other. - */ -Long.prototype.greaterThanOrEqual = function(other) { - return this.compare(other) >= 0; -}; - -/** - * Compares this Long with the given one. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. - */ -Long.prototype.compare = function(other) { - if (this.equals(other)) { - return 0; - } - - var thisNeg = this.isNegative(); - var otherNeg = other.isNegative(); - if (thisNeg && !otherNeg) { - return -1; - } - if (!thisNeg && otherNeg) { - return 1; - } - - // at this point, the signs are the same, so subtraction will not overflow - if (this.subtract(other).isNegative()) { - return -1; - } else { - return 1; - } -}; - -/** - * The negation of this value. - * - * @method - * @return {Long} the negation of this value. - */ -Long.prototype.negate = function() { - if (this.equals(Long.MIN_VALUE)) { - return Long.MIN_VALUE; - } else { - return this.not().add(Long.ONE); - } -}; - -/** - * Returns the sum of this and the given Long. - * - * @method - * @param {Long} other Long to add to this one. - * @return {Long} the sum of this and the given Long. - */ -Long.prototype.add = function(other) { - // Divide each number into 4 chunks of 16 bits, and then sum the chunks. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xffff; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xffff; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xffff; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xffff; - - var c48 = 0, - c32 = 0, - c16 = 0, - c00 = 0; - c00 += a00 + b00; - c16 += c00 >>> 16; - c00 &= 0xffff; - c16 += a16 + b16; - c32 += c16 >>> 16; - c16 &= 0xffff; - c32 += a32 + b32; - c48 += c32 >>> 16; - c32 &= 0xffff; - c48 += a48 + b48; - c48 &= 0xffff; - return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32); -}; - -/** - * Returns the difference of this and the given Long. - * - * @method - * @param {Long} other Long to subtract from this. - * @return {Long} the difference of this and the given Long. - */ -Long.prototype.subtract = function(other) { - return this.add(other.negate()); -}; - -/** - * Returns the product of this and the given Long. - * - * @method - * @param {Long} other Long to multiply with this. - * @return {Long} the product of this and the other. - */ -Long.prototype.multiply = function(other) { - if (this.isZero()) { - return Long.ZERO; - } else if (other.isZero()) { - return Long.ZERO; - } - - if (this.equals(Long.MIN_VALUE)) { - return other.isOdd() ? Long.MIN_VALUE : Long.ZERO; - } else if (other.equals(Long.MIN_VALUE)) { - return this.isOdd() ? Long.MIN_VALUE : Long.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().multiply(other.negate()); - } else { - return this.negate() - .multiply(other) - .negate(); - } - } else if (other.isNegative()) { - return this.multiply(other.negate()).negate(); - } - - // If both Longs are small, use float multiplication - if (this.lessThan(Long.TWO_PWR_24_) && other.lessThan(Long.TWO_PWR_24_)) { - return Long.fromNumber(this.toNumber() * other.toNumber()); - } - - // Divide each Long into 4 chunks of 16 bits, and then add up 4x4 products. - // We can skip products that would overflow. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xffff; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xffff; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xffff; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xffff; - - var c48 = 0, - c32 = 0, - c16 = 0, - c00 = 0; - c00 += a00 * b00; - c16 += c00 >>> 16; - c00 &= 0xffff; - c16 += a16 * b00; - c32 += c16 >>> 16; - c16 &= 0xffff; - c16 += a00 * b16; - c32 += c16 >>> 16; - c16 &= 0xffff; - c32 += a32 * b00; - c48 += c32 >>> 16; - c32 &= 0xffff; - c32 += a16 * b16; - c48 += c32 >>> 16; - c32 &= 0xffff; - c32 += a00 * b32; - c48 += c32 >>> 16; - c32 &= 0xffff; - c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; - c48 &= 0xffff; - return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32); -}; - -/** - * Returns this Long divided by the given one. - * - * @method - * @param {Long} other Long by which to divide. - * @return {Long} this Long divided by the given one. - */ -Long.prototype.div = function(other) { - if (other.isZero()) { - throw Error('division by zero'); - } else if (this.isZero()) { - return Long.ZERO; - } - - if (this.equals(Long.MIN_VALUE)) { - if (other.equals(Long.ONE) || other.equals(Long.NEG_ONE)) { - return Long.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE - } else if (other.equals(Long.MIN_VALUE)) { - return Long.ONE; - } else { - // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. - var halfThis = this.shiftRight(1); - var approx = halfThis.div(other).shiftLeft(1); - if (approx.equals(Long.ZERO)) { - return other.isNegative() ? Long.ONE : Long.NEG_ONE; - } else { - var rem = this.subtract(other.multiply(approx)); - var result = approx.add(rem.div(other)); - return result; - } - } - } else if (other.equals(Long.MIN_VALUE)) { - return Long.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().div(other.negate()); - } else { - return this.negate() - .div(other) - .negate(); - } - } else if (other.isNegative()) { - return this.div(other.negate()).negate(); - } - - // Repeat the following until the remainder is less than other: find a - // floating-point that approximates remainder / other *from below*, add this - // into the result, and subtract it from the remainder. It is critical that - // the approximate value is less than or equal to the real value so that the - // remainder never becomes negative. - var res = Long.ZERO; - rem = this; - while (rem.greaterThanOrEqual(other)) { - // Approximate the result of division. This may be a little greater or - // smaller than the actual value. - approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); - - // We will tweak the approximate result by changing it in the 48-th digit or - // the smallest non-fractional digit, whichever is larger. - var log2 = Math.ceil(Math.log(approx) / Math.LN2); - var delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48); - - // Decrease the approximation until it is smaller than the remainder. Note - // that if it is too large, the product overflows and is negative. - var approxRes = Long.fromNumber(approx); - var approxRem = approxRes.multiply(other); - while (approxRem.isNegative() || approxRem.greaterThan(rem)) { - approx -= delta; - approxRes = Long.fromNumber(approx); - approxRem = approxRes.multiply(other); - } - - // We know the answer can't be zero... and actually, zero would cause - // infinite recursion since we would make no progress. - if (approxRes.isZero()) { - approxRes = Long.ONE; - } - - res = res.add(approxRes); - rem = rem.subtract(approxRem); - } - return res; -}; - -/** - * Returns this Long modulo the given one. - * - * @method - * @param {Long} other Long by which to mod. - * @return {Long} this Long modulo the given one. - */ -Long.prototype.modulo = function(other) { - return this.subtract(this.div(other).multiply(other)); -}; - -/** - * The bitwise-NOT of this value. - * - * @method - * @return {Long} the bitwise-NOT of this value. - */ -Long.prototype.not = function() { - return Long.fromBits(~this.low_, ~this.high_); -}; - -/** - * Returns the bitwise-AND of this Long and the given one. - * - * @method - * @param {Long} other the Long with which to AND. - * @return {Long} the bitwise-AND of this and the other. - */ -Long.prototype.and = function(other) { - return Long.fromBits(this.low_ & other.low_, this.high_ & other.high_); -}; - -/** - * Returns the bitwise-OR of this Long and the given one. - * - * @method - * @param {Long} other the Long with which to OR. - * @return {Long} the bitwise-OR of this and the other. - */ -Long.prototype.or = function(other) { - return Long.fromBits(this.low_ | other.low_, this.high_ | other.high_); -}; - -/** - * Returns the bitwise-XOR of this Long and the given one. - * - * @method - * @param {Long} other the Long with which to XOR. - * @return {Long} the bitwise-XOR of this and the other. - */ -Long.prototype.xor = function(other) { - return Long.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); -}; - -/** - * Returns this Long with bits shifted to the left by the given amount. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Long} this shifted to the left by the given amount. - */ -Long.prototype.shiftLeft = function(numBits) { - numBits &= 63; - if (numBits === 0) { - return this; - } else { - var low = this.low_; - if (numBits < 32) { - var high = this.high_; - return Long.fromBits(low << numBits, (high << numBits) | (low >>> (32 - numBits))); - } else { - return Long.fromBits(0, low << (numBits - 32)); - } - } -}; - -/** - * Returns this Long with bits shifted to the right by the given amount. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Long} this shifted to the right by the given amount. - */ -Long.prototype.shiftRight = function(numBits) { - numBits &= 63; - if (numBits === 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Long.fromBits((low >>> numBits) | (high << (32 - numBits)), high >> numBits); - } else { - return Long.fromBits(high >> (numBits - 32), high >= 0 ? 0 : -1); - } - } -}; - -/** - * Returns this Long with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Long} this shifted to the right by the given amount, with zeros placed into the new leading bits. - */ -Long.prototype.shiftRightUnsigned = function(numBits) { - numBits &= 63; - if (numBits === 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Long.fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits); - } else if (numBits === 32) { - return Long.fromBits(high, 0); - } else { - return Long.fromBits(high >>> (numBits - 32), 0); - } - } -}; - -/** - * Returns a Long representing the given (32-bit) integer value. - * - * @method - * @param {number} value the 32-bit integer in question. - * @return {Long} the corresponding Long value. - */ -Long.fromInt = function(value) { - if (-128 <= value && value < 128) { - var cachedObj = Long.INT_CACHE_[value]; - if (cachedObj) { - return cachedObj; - } - } - - var obj = new Long(value | 0, value < 0 ? -1 : 0); - if (-128 <= value && value < 128) { - Long.INT_CACHE_[value] = obj; - } - return obj; -}; - -/** - * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. - * - * @method - * @param {number} value the number in question. - * @return {Long} the corresponding Long value. - */ -Long.fromNumber = function(value) { - if (isNaN(value) || !isFinite(value)) { - return Long.ZERO; - } else if (value <= -Long.TWO_PWR_63_DBL_) { - return Long.MIN_VALUE; - } else if (value + 1 >= Long.TWO_PWR_63_DBL_) { - return Long.MAX_VALUE; - } else if (value < 0) { - return Long.fromNumber(-value).negate(); - } else { - return new Long((value % Long.TWO_PWR_32_DBL_) | 0, (value / Long.TWO_PWR_32_DBL_) | 0); - } -}; - -/** - * Returns a Long representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. - * - * @method - * @param {number} lowBits the low 32-bits. - * @param {number} highBits the high 32-bits. - * @return {Long} the corresponding Long value. - */ -Long.fromBits = function(lowBits, highBits) { - return new Long(lowBits, highBits); -}; - -/** - * Returns a Long representation of the given string, written using the given radix. - * - * @method - * @param {string} str the textual representation of the Long. - * @param {number} opt_radix the radix in which the text is written. - * @return {Long} the corresponding Long value. - */ -Long.fromString = function(str, opt_radix) { - if (str.length === 0) { - throw Error('number format error: empty string'); - } - - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (str.charAt(0) === '-') { - return Long.fromString(str.substring(1), radix).negate(); - } else if (str.indexOf('-') >= 0) { - throw Error('number format error: interior "-" character: ' + str); - } - - // Do several (8) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Long.fromNumber(Math.pow(radix, 8)); - - var result = Long.ZERO; - for (var i = 0; i < str.length; i += 8) { - var size = Math.min(8, str.length - i); - var value = parseInt(str.substring(i, i + size), radix); - if (size < 8) { - var power = Long.fromNumber(Math.pow(radix, size)); - result = result.multiply(power).add(Long.fromNumber(value)); - } else { - result = result.multiply(radixToPower); - result = result.add(Long.fromNumber(value)); - } - } - return result; -}; - -// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the -// from* methods on which they depend. - -/** - * A cache of the Long representations of small integer values. - * @type {Object} - * @ignore - */ -Long.INT_CACHE_ = {}; - -// NOTE: the compiler should inline these constant values below and then remove -// these variables, so there should be no runtime penalty for these. - -/** - * Number used repeated below in calculations. This must appear before the - * first call to any from* function below. - * @type {number} - * @ignore - */ -Long.TWO_PWR_16_DBL_ = 1 << 16; - -/** - * @type {number} - * @ignore - */ -Long.TWO_PWR_24_DBL_ = 1 << 24; - -/** - * @type {number} - * @ignore - */ -Long.TWO_PWR_32_DBL_ = Long.TWO_PWR_16_DBL_ * Long.TWO_PWR_16_DBL_; - -/** - * @type {number} - * @ignore - */ -Long.TWO_PWR_31_DBL_ = Long.TWO_PWR_32_DBL_ / 2; - -/** - * @type {number} - * @ignore - */ -Long.TWO_PWR_48_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_16_DBL_; - -/** - * @type {number} - * @ignore - */ -Long.TWO_PWR_64_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_32_DBL_; - -/** - * @type {number} - * @ignore - */ -Long.TWO_PWR_63_DBL_ = Long.TWO_PWR_64_DBL_ / 2; - -/** @type {Long} */ -Long.ZERO = Long.fromInt(0); - -/** @type {Long} */ -Long.ONE = Long.fromInt(1); - -/** @type {Long} */ -Long.NEG_ONE = Long.fromInt(-1); - -/** @type {Long} */ -Long.MAX_VALUE = Long.fromBits(0xffffffff | 0, 0x7fffffff | 0); - -/** @type {Long} */ -Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0); - -/** - * @type {Long} - * @ignore - */ -Long.TWO_PWR_24_ = Long.fromInt(1 << 24); - -/** - * Expose. - */ -module.exports = Long; -module.exports.Long = Long; diff --git a/scripts/node_modules/bson/lib/bson/map.js b/scripts/node_modules/bson/lib/bson/map.js deleted file mode 100644 index 7edb4f2a..00000000 --- a/scripts/node_modules/bson/lib/bson/map.js +++ /dev/null @@ -1,128 +0,0 @@ -'use strict'; - -// We have an ES6 Map available, return the native instance -if (typeof global.Map !== 'undefined') { - module.exports = global.Map; - module.exports.Map = global.Map; -} else { - // We will return a polyfill - var Map = function(array) { - this._keys = []; - this._values = {}; - - for (var i = 0; i < array.length; i++) { - if (array[i] == null) continue; // skip null and undefined - var entry = array[i]; - var key = entry[0]; - var value = entry[1]; - // Add the key to the list of keys in order - this._keys.push(key); - // Add the key and value to the values dictionary with a point - // to the location in the ordered keys list - this._values[key] = { v: value, i: this._keys.length - 1 }; - } - }; - - Map.prototype.clear = function() { - this._keys = []; - this._values = {}; - }; - - Map.prototype.delete = function(key) { - var value = this._values[key]; - if (value == null) return false; - // Delete entry - delete this._values[key]; - // Remove the key from the ordered keys list - this._keys.splice(value.i, 1); - return true; - }; - - Map.prototype.entries = function() { - var self = this; - var index = 0; - - return { - next: function() { - var key = self._keys[index++]; - return { - value: key !== undefined ? [key, self._values[key].v] : undefined, - done: key !== undefined ? false : true - }; - } - }; - }; - - Map.prototype.forEach = function(callback, self) { - self = self || this; - - for (var i = 0; i < this._keys.length; i++) { - var key = this._keys[i]; - // Call the forEach callback - callback.call(self, this._values[key].v, key, self); - } - }; - - Map.prototype.get = function(key) { - return this._values[key] ? this._values[key].v : undefined; - }; - - Map.prototype.has = function(key) { - return this._values[key] != null; - }; - - Map.prototype.keys = function() { - var self = this; - var index = 0; - - return { - next: function() { - var key = self._keys[index++]; - return { - value: key !== undefined ? key : undefined, - done: key !== undefined ? false : true - }; - } - }; - }; - - Map.prototype.set = function(key, value) { - if (this._values[key]) { - this._values[key].v = value; - return this; - } - - // Add the key to the list of keys in order - this._keys.push(key); - // Add the key and value to the values dictionary with a point - // to the location in the ordered keys list - this._values[key] = { v: value, i: this._keys.length - 1 }; - return this; - }; - - Map.prototype.values = function() { - var self = this; - var index = 0; - - return { - next: function() { - var key = self._keys[index++]; - return { - value: key !== undefined ? self._values[key].v : undefined, - done: key !== undefined ? false : true - }; - } - }; - }; - - // Last ismaster - Object.defineProperty(Map.prototype, 'size', { - enumerable: true, - get: function() { - return this._keys.length; - } - }); - - module.exports = Map; - module.exports.Map = Map; -} diff --git a/scripts/node_modules/bson/lib/bson/max_key.js b/scripts/node_modules/bson/lib/bson/max_key.js deleted file mode 100644 index eebca7bc..00000000 --- a/scripts/node_modules/bson/lib/bson/max_key.js +++ /dev/null @@ -1,14 +0,0 @@ -/** - * A class representation of the BSON MaxKey type. - * - * @class - * @return {MaxKey} A MaxKey instance - */ -function MaxKey() { - if (!(this instanceof MaxKey)) return new MaxKey(); - - this._bsontype = 'MaxKey'; -} - -module.exports = MaxKey; -module.exports.MaxKey = MaxKey; diff --git a/scripts/node_modules/bson/lib/bson/min_key.js b/scripts/node_modules/bson/lib/bson/min_key.js deleted file mode 100644 index 15f45228..00000000 --- a/scripts/node_modules/bson/lib/bson/min_key.js +++ /dev/null @@ -1,14 +0,0 @@ -/** - * A class representation of the BSON MinKey type. - * - * @class - * @return {MinKey} A MinKey instance - */ -function MinKey() { - if (!(this instanceof MinKey)) return new MinKey(); - - this._bsontype = 'MinKey'; -} - -module.exports = MinKey; -module.exports.MinKey = MinKey; diff --git a/scripts/node_modules/bson/lib/bson/objectid.js b/scripts/node_modules/bson/lib/bson/objectid.js deleted file mode 100644 index 79de40d2..00000000 --- a/scripts/node_modules/bson/lib/bson/objectid.js +++ /dev/null @@ -1,389 +0,0 @@ -// Custom inspect property name / symbol. -var inspect = 'inspect'; - -var utils = require('./parser/utils'); - -/** - * Machine id. - * - * Create a random 3-byte value (i.e. unique for this - * process). Other drivers use a md5 of the machine id here, but - * that would mean an asyc call to gethostname, so we don't bother. - * @ignore - */ -var MACHINE_ID = parseInt(Math.random() * 0xffffff, 10); - -// Regular expression that checks for hex value -var checkForHexRegExp = new RegExp('^[0-9a-fA-F]{24}$'); - -// Check if buffer exists -try { - if (Buffer && Buffer.from) { - var hasBufferType = true; - inspect = require('util').inspect.custom || 'inspect'; - } -} catch (err) { - hasBufferType = false; -} - -/** -* Create a new ObjectID instance -* -* @class -* @param {(string|number)} id Can be a 24 byte hex string, 12 byte binary string or a Number. -* @property {number} generationTime The generation time of this ObjectId instance -* @return {ObjectID} instance of ObjectID. -*/ -var ObjectID = function ObjectID(id) { - // Duck-typing to support ObjectId from different npm packages - if (id instanceof ObjectID) return id; - if (!(this instanceof ObjectID)) return new ObjectID(id); - - this._bsontype = 'ObjectID'; - - // The most common usecase (blank id, new objectId instance) - if (id == null || typeof id === 'number') { - // Generate a new id - this.id = this.generate(id); - // If we are caching the hex string - if (ObjectID.cacheHexString) this.__id = this.toString('hex'); - // Return the object - return; - } - - // Check if the passed in id is valid - var valid = ObjectID.isValid(id); - - // Throw an error if it's not a valid setup - if (!valid && id != null) { - throw new Error( - 'Argument passed in must be a single String of 12 bytes or a string of 24 hex characters' - ); - } else if (valid && typeof id === 'string' && id.length === 24 && hasBufferType) { - return new ObjectID(utils.toBuffer(id, 'hex')); - } else if (valid && typeof id === 'string' && id.length === 24) { - return ObjectID.createFromHexString(id); - } else if (id != null && id.length === 12) { - // assume 12 byte string - this.id = id; - } else if (id != null && id.toHexString) { - // Duck-typing to support ObjectId from different npm packages - return id; - } else { - throw new Error( - 'Argument passed in must be a single String of 12 bytes or a string of 24 hex characters' - ); - } - - if (ObjectID.cacheHexString) this.__id = this.toString('hex'); -}; - -// Allow usage of ObjectId as well as ObjectID -// var ObjectId = ObjectID; - -// Precomputed hex table enables speedy hex string conversion -var hexTable = []; -for (var i = 0; i < 256; i++) { - hexTable[i] = (i <= 15 ? '0' : '') + i.toString(16); -} - -/** -* Return the ObjectID id as a 24 byte hex string representation -* -* @method -* @return {string} return the 24 byte hex string representation. -*/ -ObjectID.prototype.toHexString = function() { - if (ObjectID.cacheHexString && this.__id) return this.__id; - - var hexString = ''; - if (!this.id || !this.id.length) { - throw new Error( - 'invalid ObjectId, ObjectId.id must be either a string or a Buffer, but is [' + - JSON.stringify(this.id) + - ']' - ); - } - - if (this.id instanceof _Buffer) { - hexString = convertToHex(this.id); - if (ObjectID.cacheHexString) this.__id = hexString; - return hexString; - } - - for (var i = 0; i < this.id.length; i++) { - hexString += hexTable[this.id.charCodeAt(i)]; - } - - if (ObjectID.cacheHexString) this.__id = hexString; - return hexString; -}; - -/** -* Update the ObjectID index used in generating new ObjectID's on the driver -* -* @method -* @return {number} returns next index value. -* @ignore -*/ -ObjectID.prototype.get_inc = function() { - return (ObjectID.index = (ObjectID.index + 1) % 0xffffff); -}; - -/** -* Update the ObjectID index used in generating new ObjectID's on the driver -* -* @method -* @return {number} returns next index value. -* @ignore -*/ -ObjectID.prototype.getInc = function() { - return this.get_inc(); -}; - -/** -* Generate a 12 byte id buffer used in ObjectID's -* -* @method -* @param {number} [time] optional parameter allowing to pass in a second based timestamp. -* @return {Buffer} return the 12 byte id buffer string. -*/ -ObjectID.prototype.generate = function(time) { - if ('number' !== typeof time) { - time = ~~(Date.now() / 1000); - } - - // Use pid - var pid = - (typeof process === 'undefined' || process.pid === 1 - ? Math.floor(Math.random() * 100000) - : process.pid) % 0xffff; - var inc = this.get_inc(); - // Buffer used - var buffer = utils.allocBuffer(12); - // Encode time - buffer[3] = time & 0xff; - buffer[2] = (time >> 8) & 0xff; - buffer[1] = (time >> 16) & 0xff; - buffer[0] = (time >> 24) & 0xff; - // Encode machine - buffer[6] = MACHINE_ID & 0xff; - buffer[5] = (MACHINE_ID >> 8) & 0xff; - buffer[4] = (MACHINE_ID >> 16) & 0xff; - // Encode pid - buffer[8] = pid & 0xff; - buffer[7] = (pid >> 8) & 0xff; - // Encode index - buffer[11] = inc & 0xff; - buffer[10] = (inc >> 8) & 0xff; - buffer[9] = (inc >> 16) & 0xff; - // Return the buffer - return buffer; -}; - -/** -* Converts the id into a 24 byte hex string for printing -* -* @param {String} format The Buffer toString format parameter. -* @return {String} return the 24 byte hex string representation. -* @ignore -*/ -ObjectID.prototype.toString = function(format) { - // Is the id a buffer then use the buffer toString method to return the format - if (this.id && this.id.copy) { - return this.id.toString(typeof format === 'string' ? format : 'hex'); - } - - // if(this.buffer ) - return this.toHexString(); -}; - -/** -* Converts to a string representation of this Id. -* -* @return {String} return the 24 byte hex string representation. -* @ignore -*/ -ObjectID.prototype[inspect] = ObjectID.prototype.toString; - -/** -* Converts to its JSON representation. -* -* @return {String} return the 24 byte hex string representation. -* @ignore -*/ -ObjectID.prototype.toJSON = function() { - return this.toHexString(); -}; - -/** -* Compares the equality of this ObjectID with `otherID`. -* -* @method -* @param {object} otherID ObjectID instance to compare against. -* @return {boolean} the result of comparing two ObjectID's -*/ -ObjectID.prototype.equals = function equals(otherId) { - // var id; - - if (otherId instanceof ObjectID) { - return this.toString() === otherId.toString(); - } else if ( - typeof otherId === 'string' && - ObjectID.isValid(otherId) && - otherId.length === 12 && - this.id instanceof _Buffer - ) { - return otherId === this.id.toString('binary'); - } else if (typeof otherId === 'string' && ObjectID.isValid(otherId) && otherId.length === 24) { - return otherId.toLowerCase() === this.toHexString(); - } else if (typeof otherId === 'string' && ObjectID.isValid(otherId) && otherId.length === 12) { - return otherId === this.id; - } else if (otherId != null && (otherId instanceof ObjectID || otherId.toHexString)) { - return otherId.toHexString() === this.toHexString(); - } else { - return false; - } -}; - -/** -* Returns the generation date (accurate up to the second) that this ID was generated. -* -* @method -* @return {date} the generation date -*/ -ObjectID.prototype.getTimestamp = function() { - var timestamp = new Date(); - var time = this.id[3] | (this.id[2] << 8) | (this.id[1] << 16) | (this.id[0] << 24); - timestamp.setTime(Math.floor(time) * 1000); - return timestamp; -}; - -/** -* @ignore -*/ -ObjectID.index = ~~(Math.random() * 0xffffff); - -/** -* @ignore -*/ -ObjectID.createPk = function createPk() { - return new ObjectID(); -}; - -/** -* Creates an ObjectID from a second based number, with the rest of the ObjectID zeroed out. Used for comparisons or sorting the ObjectID. -* -* @method -* @param {number} time an integer number representing a number of seconds. -* @return {ObjectID} return the created ObjectID -*/ -ObjectID.createFromTime = function createFromTime(time) { - var buffer = utils.toBuffer([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); - // Encode time into first 4 bytes - buffer[3] = time & 0xff; - buffer[2] = (time >> 8) & 0xff; - buffer[1] = (time >> 16) & 0xff; - buffer[0] = (time >> 24) & 0xff; - // Return the new objectId - return new ObjectID(buffer); -}; - -// Lookup tables -//var encodeLookup = '0123456789abcdef'.split(''); -var decodeLookup = []; -i = 0; -while (i < 10) decodeLookup[0x30 + i] = i++; -while (i < 16) decodeLookup[0x41 - 10 + i] = decodeLookup[0x61 - 10 + i] = i++; - -var _Buffer = Buffer; -var convertToHex = function(bytes) { - return bytes.toString('hex'); -}; - -/** -* Creates an ObjectID from a hex string representation of an ObjectID. -* -* @method -* @param {string} hexString create a ObjectID from a passed in 24 byte hexstring. -* @return {ObjectID} return the created ObjectID -*/ -ObjectID.createFromHexString = function createFromHexString(string) { - // Throw an error if it's not a valid setup - if (typeof string === 'undefined' || (string != null && string.length !== 24)) { - throw new Error( - 'Argument passed in must be a single String of 12 bytes or a string of 24 hex characters' - ); - } - - // Use Buffer.from method if available - if (hasBufferType) return new ObjectID(utils.toBuffer(string, 'hex')); - - // Calculate lengths - var array = new _Buffer(12); - var n = 0; - var i = 0; - - while (i < 24) { - array[n++] = (decodeLookup[string.charCodeAt(i++)] << 4) | decodeLookup[string.charCodeAt(i++)]; - } - - return new ObjectID(array); -}; - -/** -* Checks if a value is a valid bson ObjectId -* -* @method -* @return {boolean} return true if the value is a valid bson ObjectId, return false otherwise. -*/ -ObjectID.isValid = function isValid(id) { - if (id == null) return false; - - if (typeof id === 'number') { - return true; - } - - if (typeof id === 'string') { - return id.length === 12 || (id.length === 24 && checkForHexRegExp.test(id)); - } - - if (id instanceof ObjectID) { - return true; - } - - if (id instanceof _Buffer) { - return true; - } - - // Duck-Typing detection of ObjectId like objects - if (id.toHexString) { - return id.id.length === 12 || (id.id.length === 24 && checkForHexRegExp.test(id.id)); - } - - return false; -}; - -/** -* @ignore -*/ -Object.defineProperty(ObjectID.prototype, 'generationTime', { - enumerable: true, - get: function() { - return this.id[3] | (this.id[2] << 8) | (this.id[1] << 16) | (this.id[0] << 24); - }, - set: function(value) { - // Encode time into first 4 bytes - this.id[3] = value & 0xff; - this.id[2] = (value >> 8) & 0xff; - this.id[1] = (value >> 16) & 0xff; - this.id[0] = (value >> 24) & 0xff; - } -}); - -/** - * Expose. - */ -module.exports = ObjectID; -module.exports.ObjectID = ObjectID; -module.exports.ObjectId = ObjectID; diff --git a/scripts/node_modules/bson/lib/bson/parser/calculate_size.js b/scripts/node_modules/bson/lib/bson/parser/calculate_size.js deleted file mode 100644 index 7e0026ca..00000000 --- a/scripts/node_modules/bson/lib/bson/parser/calculate_size.js +++ /dev/null @@ -1,255 +0,0 @@ -'use strict'; - -var Long = require('../long').Long, - Double = require('../double').Double, - Timestamp = require('../timestamp').Timestamp, - ObjectID = require('../objectid').ObjectID, - Symbol = require('../symbol').Symbol, - BSONRegExp = require('../regexp').BSONRegExp, - Code = require('../code').Code, - Decimal128 = require('../decimal128'), - MinKey = require('../min_key').MinKey, - MaxKey = require('../max_key').MaxKey, - DBRef = require('../db_ref').DBRef, - Binary = require('../binary').Binary; - -var normalizedFunctionString = require('./utils').normalizedFunctionString; - -// To ensure that 0.4 of node works correctly -var isDate = function isDate(d) { - return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; -}; - -var calculateObjectSize = function calculateObjectSize( - object, - serializeFunctions, - ignoreUndefined -) { - var totalLength = 4 + 1; - - if (Array.isArray(object)) { - for (var i = 0; i < object.length; i++) { - totalLength += calculateElement( - i.toString(), - object[i], - serializeFunctions, - true, - ignoreUndefined - ); - } - } else { - // If we have toBSON defined, override the current object - if (object.toBSON) { - object = object.toBSON(); - } - - // Calculate size - for (var key in object) { - totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined); - } - } - - return totalLength; -}; - -/** - * @ignore - * @api private - */ -function calculateElement(name, value, serializeFunctions, isArray, ignoreUndefined) { - // If we have toBSON defined, override the current object - if (value && value.toBSON) { - value = value.toBSON(); - } - - switch (typeof value) { - case 'string': - return 1 + Buffer.byteLength(name, 'utf8') + 1 + 4 + Buffer.byteLength(value, 'utf8') + 1; - case 'number': - if (Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - if (value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { - // 32 bit - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (4 + 1); - } else { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); - } - } else { - // 64 bit - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); - } - case 'undefined': - if (isArray || !ignoreUndefined) - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1; - return 0; - case 'boolean': - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (1 + 1); - case 'object': - if ( - value == null || - value instanceof MinKey || - value instanceof MaxKey || - value['_bsontype'] === 'MinKey' || - value['_bsontype'] === 'MaxKey' - ) { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1; - } else if (value instanceof ObjectID || value['_bsontype'] === 'ObjectID' || value['_bsontype'] === 'ObjectId') { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (12 + 1); - } else if (value instanceof Date || isDate(value)) { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); - } else if (typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { - return ( - (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (1 + 4 + 1) + value.length - ); - } else if ( - value instanceof Long || - value instanceof Double || - value instanceof Timestamp || - value['_bsontype'] === 'Long' || - value['_bsontype'] === 'Double' || - value['_bsontype'] === 'Timestamp' - ) { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); - } else if (value instanceof Decimal128 || value['_bsontype'] === 'Decimal128') { - return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (16 + 1); - } else if (value instanceof Code || value['_bsontype'] === 'Code') { - // Calculate size depending on the availability of a scope - if (value.scope != null && Object.keys(value.scope).length > 0) { - return ( - (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - 1 + - 4 + - 4 + - Buffer.byteLength(value.code.toString(), 'utf8') + - 1 + - calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined) - ); - } else { - return ( - (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - 1 + - 4 + - Buffer.byteLength(value.code.toString(), 'utf8') + - 1 - ); - } - } else if (value instanceof Binary || value['_bsontype'] === 'Binary') { - // Check what kind of subtype we have - if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { - return ( - (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - (value.position + 1 + 4 + 1 + 4) - ); - } else { - return ( - (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (value.position + 1 + 4 + 1) - ); - } - } else if (value instanceof Symbol || value['_bsontype'] === 'Symbol') { - return ( - (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - Buffer.byteLength(value.value, 'utf8') + - 4 + - 1 + - 1 - ); - } else if (value instanceof DBRef || value['_bsontype'] === 'DBRef') { - // Set up correct object for serialization - var ordered_values = { - $ref: value.namespace, - $id: value.oid - }; - - // Add db reference if it exists - if (null != value.db) { - ordered_values['$db'] = value.db; - } - - return ( - (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - 1 + - calculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined) - ); - } else if ( - value instanceof RegExp || - Object.prototype.toString.call(value) === '[object RegExp]' - ) { - return ( - (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - 1 + - Buffer.byteLength(value.source, 'utf8') + - 1 + - (value.global ? 1 : 0) + - (value.ignoreCase ? 1 : 0) + - (value.multiline ? 1 : 0) + - 1 - ); - } else if (value instanceof BSONRegExp || value['_bsontype'] === 'BSONRegExp') { - return ( - (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - 1 + - Buffer.byteLength(value.pattern, 'utf8') + - 1 + - Buffer.byteLength(value.options, 'utf8') + - 1 - ); - } else { - return ( - (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - calculateObjectSize(value, serializeFunctions, ignoreUndefined) + - 1 - ); - } - case 'function': - // WTF for 0.4.X where typeof /someregexp/ === 'function' - if ( - value instanceof RegExp || - Object.prototype.toString.call(value) === '[object RegExp]' || - String.call(value) === '[object RegExp]' - ) { - return ( - (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - 1 + - Buffer.byteLength(value.source, 'utf8') + - 1 + - (value.global ? 1 : 0) + - (value.ignoreCase ? 1 : 0) + - (value.multiline ? 1 : 0) + - 1 - ); - } else { - if (serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { - return ( - (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - 1 + - 4 + - 4 + - Buffer.byteLength(normalizedFunctionString(value), 'utf8') + - 1 + - calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined) - ); - } else if (serializeFunctions) { - return ( - (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + - 1 + - 4 + - Buffer.byteLength(normalizedFunctionString(value), 'utf8') + - 1 - ); - } - } - } - - return 0; -} - -var BSON = {}; - -// BSON MAX VALUES -BSON.BSON_INT32_MAX = 0x7fffffff; -BSON.BSON_INT32_MIN = -0x80000000; - -// JS MAX PRECISE VALUES -BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. -BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. - -module.exports = calculateObjectSize; diff --git a/scripts/node_modules/bson/lib/bson/parser/deserializer.js b/scripts/node_modules/bson/lib/bson/parser/deserializer.js deleted file mode 100644 index be3c8654..00000000 --- a/scripts/node_modules/bson/lib/bson/parser/deserializer.js +++ /dev/null @@ -1,782 +0,0 @@ -'use strict'; - -var Long = require('../long').Long, - Double = require('../double').Double, - Timestamp = require('../timestamp').Timestamp, - ObjectID = require('../objectid').ObjectID, - Symbol = require('../symbol').Symbol, - Code = require('../code').Code, - MinKey = require('../min_key').MinKey, - MaxKey = require('../max_key').MaxKey, - Decimal128 = require('../decimal128'), - Int32 = require('../int_32'), - DBRef = require('../db_ref').DBRef, - BSONRegExp = require('../regexp').BSONRegExp, - Binary = require('../binary').Binary; - -var utils = require('./utils'); - -var deserialize = function(buffer, options, isArray) { - options = options == null ? {} : options; - var index = options && options.index ? options.index : 0; - // Read the document size - var size = - buffer[index] | - (buffer[index + 1] << 8) | - (buffer[index + 2] << 16) | - (buffer[index + 3] << 24); - - // Ensure buffer is valid size - if (size < 5 || buffer.length < size || size + index > buffer.length) { - throw new Error('corrupt bson message'); - } - - // Illegal end value - if (buffer[index + size - 1] !== 0) { - throw new Error("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00"); - } - - // Start deserializtion - return deserializeObject(buffer, index, options, isArray); -}; - -var deserializeObject = function(buffer, index, options, isArray) { - var evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions']; - var cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions']; - var cacheFunctionsCrc32 = - options['cacheFunctionsCrc32'] == null ? false : options['cacheFunctionsCrc32']; - - if (!cacheFunctionsCrc32) var crc32 = null; - - var fieldsAsRaw = options['fieldsAsRaw'] == null ? null : options['fieldsAsRaw']; - - // Return raw bson buffer instead of parsing it - var raw = options['raw'] == null ? false : options['raw']; - - // Return BSONRegExp objects instead of native regular expressions - var bsonRegExp = typeof options['bsonRegExp'] === 'boolean' ? options['bsonRegExp'] : false; - - // Controls the promotion of values vs wrapper classes - var promoteBuffers = options['promoteBuffers'] == null ? false : options['promoteBuffers']; - var promoteLongs = options['promoteLongs'] == null ? true : options['promoteLongs']; - var promoteValues = options['promoteValues'] == null ? true : options['promoteValues']; - - // Set the start index - var startIndex = index; - - // Validate that we have at least 4 bytes of buffer - if (buffer.length < 5) throw new Error('corrupt bson message < 5 bytes long'); - - // Read the document size - var size = - buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); - - // Ensure buffer is valid size - if (size < 5 || size > buffer.length) throw new Error('corrupt bson message'); - - // Create holding object - var object = isArray ? [] : {}; - // Used for arrays to skip having to perform utf8 decoding - var arrayIndex = 0; - - var done = false; - - // While we have more left data left keep parsing - // while (buffer[index + 1] !== 0) { - while (!done) { - // Read the type - var elementType = buffer[index++]; - // If we get a zero it's the last byte, exit - if (elementType === 0) break; - - // Get the start search index - var i = index; - // Locate the end of the c string - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - - // If are at the end of the buffer there is a problem with the document - if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); - var name = isArray ? arrayIndex++ : buffer.toString('utf8', index, i); - - index = i + 1; - - if (elementType === BSON.BSON_DATA_STRING) { - var stringSize = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - if ( - stringSize <= 0 || - stringSize > buffer.length - index || - buffer[index + stringSize - 1] !== 0 - ) - throw new Error('bad string length in bson'); - object[name] = buffer.toString('utf8', index, index + stringSize - 1); - index = index + stringSize; - } else if (elementType === BSON.BSON_DATA_OID) { - var oid = utils.allocBuffer(12); - buffer.copy(oid, 0, index, index + 12); - object[name] = new ObjectID(oid); - index = index + 12; - } else if (elementType === BSON.BSON_DATA_INT && promoteValues === false) { - object[name] = new Int32( - buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24) - ); - } else if (elementType === BSON.BSON_DATA_INT) { - object[name] = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - } else if (elementType === BSON.BSON_DATA_NUMBER && promoteValues === false) { - object[name] = new Double(buffer.readDoubleLE(index)); - index = index + 8; - } else if (elementType === BSON.BSON_DATA_NUMBER) { - object[name] = buffer.readDoubleLE(index); - index = index + 8; - } else if (elementType === BSON.BSON_DATA_DATE) { - var lowBits = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - var highBits = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - object[name] = new Date(new Long(lowBits, highBits).toNumber()); - } else if (elementType === BSON.BSON_DATA_BOOLEAN) { - if (buffer[index] !== 0 && buffer[index] !== 1) throw new Error('illegal boolean type value'); - object[name] = buffer[index++] === 1; - } else if (elementType === BSON.BSON_DATA_OBJECT) { - var _index = index; - var objectSize = - buffer[index] | - (buffer[index + 1] << 8) | - (buffer[index + 2] << 16) | - (buffer[index + 3] << 24); - if (objectSize <= 0 || objectSize > buffer.length - index) - throw new Error('bad embedded document length in bson'); - - // We have a raw value - if (raw) { - object[name] = buffer.slice(index, index + objectSize); - } else { - object[name] = deserializeObject(buffer, _index, options, false); - } - - index = index + objectSize; - } else if (elementType === BSON.BSON_DATA_ARRAY) { - _index = index; - objectSize = - buffer[index] | - (buffer[index + 1] << 8) | - (buffer[index + 2] << 16) | - (buffer[index + 3] << 24); - var arrayOptions = options; - - // Stop index - var stopIndex = index + objectSize; - - // All elements of array to be returned as raw bson - if (fieldsAsRaw && fieldsAsRaw[name]) { - arrayOptions = {}; - for (var n in options) arrayOptions[n] = options[n]; - arrayOptions['raw'] = true; - } - - object[name] = deserializeObject(buffer, _index, arrayOptions, true); - index = index + objectSize; - - if (buffer[index - 1] !== 0) throw new Error('invalid array terminator byte'); - if (index !== stopIndex) throw new Error('corrupted array bson'); - } else if (elementType === BSON.BSON_DATA_UNDEFINED) { - object[name] = undefined; - } else if (elementType === BSON.BSON_DATA_NULL) { - object[name] = null; - } else if (elementType === BSON.BSON_DATA_LONG) { - // Unpack the low and high bits - lowBits = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - highBits = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - var long = new Long(lowBits, highBits); - // Promote the long if possible - if (promoteLongs && promoteValues === true) { - object[name] = - long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) - ? long.toNumber() - : long; - } else { - object[name] = long; - } - } else if (elementType === BSON.BSON_DATA_DECIMAL128) { - // Buffer to contain the decimal bytes - var bytes = utils.allocBuffer(16); - // Copy the next 16 bytes into the bytes buffer - buffer.copy(bytes, 0, index, index + 16); - // Update index - index = index + 16; - // Assign the new Decimal128 value - var decimal128 = new Decimal128(bytes); - // If we have an alternative mapper use that - object[name] = decimal128.toObject ? decimal128.toObject() : decimal128; - } else if (elementType === BSON.BSON_DATA_BINARY) { - var binarySize = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - var totalBinarySize = binarySize; - var subType = buffer[index++]; - - // Did we have a negative binary size, throw - if (binarySize < 0) throw new Error('Negative binary type element size found'); - - // Is the length longer than the document - if (binarySize > buffer.length) throw new Error('Binary type size larger than document size'); - - // Decode as raw Buffer object if options specifies it - if (buffer['slice'] != null) { - // If we have subtype 2 skip the 4 bytes for the size - if (subType === Binary.SUBTYPE_BYTE_ARRAY) { - binarySize = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - if (binarySize < 0) - throw new Error('Negative binary type element size found for subtype 0x02'); - if (binarySize > totalBinarySize - 4) - throw new Error('Binary type with subtype 0x02 contains to long binary size'); - if (binarySize < totalBinarySize - 4) - throw new Error('Binary type with subtype 0x02 contains to short binary size'); - } - - if (promoteBuffers && promoteValues) { - object[name] = buffer.slice(index, index + binarySize); - } else { - object[name] = new Binary(buffer.slice(index, index + binarySize), subType); - } - } else { - var _buffer = - typeof Uint8Array !== 'undefined' - ? new Uint8Array(new ArrayBuffer(binarySize)) - : new Array(binarySize); - // If we have subtype 2 skip the 4 bytes for the size - if (subType === Binary.SUBTYPE_BYTE_ARRAY) { - binarySize = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - if (binarySize < 0) - throw new Error('Negative binary type element size found for subtype 0x02'); - if (binarySize > totalBinarySize - 4) - throw new Error('Binary type with subtype 0x02 contains to long binary size'); - if (binarySize < totalBinarySize - 4) - throw new Error('Binary type with subtype 0x02 contains to short binary size'); - } - - // Copy the data - for (i = 0; i < binarySize; i++) { - _buffer[i] = buffer[index + i]; - } - - if (promoteBuffers && promoteValues) { - object[name] = _buffer; - } else { - object[name] = new Binary(_buffer, subType); - } - } - - // Update the index - index = index + binarySize; - } else if (elementType === BSON.BSON_DATA_REGEXP && bsonRegExp === false) { - // Get the start search index - i = index; - // Locate the end of the c string - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - // If are at the end of the buffer there is a problem with the document - if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); - // Return the C string - var source = buffer.toString('utf8', index, i); - // Create the regexp - index = i + 1; - - // Get the start search index - i = index; - // Locate the end of the c string - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - // If are at the end of the buffer there is a problem with the document - if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); - // Return the C string - var regExpOptions = buffer.toString('utf8', index, i); - index = i + 1; - - // For each option add the corresponding one for javascript - var optionsArray = new Array(regExpOptions.length); - - // Parse options - for (i = 0; i < regExpOptions.length; i++) { - switch (regExpOptions[i]) { - case 'm': - optionsArray[i] = 'm'; - break; - case 's': - optionsArray[i] = 'g'; - break; - case 'i': - optionsArray[i] = 'i'; - break; - } - } - - object[name] = new RegExp(source, optionsArray.join('')); - } else if (elementType === BSON.BSON_DATA_REGEXP && bsonRegExp === true) { - // Get the start search index - i = index; - // Locate the end of the c string - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - // If are at the end of the buffer there is a problem with the document - if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); - // Return the C string - source = buffer.toString('utf8', index, i); - index = i + 1; - - // Get the start search index - i = index; - // Locate the end of the c string - while (buffer[i] !== 0x00 && i < buffer.length) { - i++; - } - // If are at the end of the buffer there is a problem with the document - if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); - // Return the C string - regExpOptions = buffer.toString('utf8', index, i); - index = i + 1; - - // Set the object - object[name] = new BSONRegExp(source, regExpOptions); - } else if (elementType === BSON.BSON_DATA_SYMBOL) { - stringSize = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - if ( - stringSize <= 0 || - stringSize > buffer.length - index || - buffer[index + stringSize - 1] !== 0 - ) - throw new Error('bad string length in bson'); - object[name] = new Symbol(buffer.toString('utf8', index, index + stringSize - 1)); - index = index + stringSize; - } else if (elementType === BSON.BSON_DATA_TIMESTAMP) { - lowBits = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - highBits = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - object[name] = new Timestamp(lowBits, highBits); - } else if (elementType === BSON.BSON_DATA_MIN_KEY) { - object[name] = new MinKey(); - } else if (elementType === BSON.BSON_DATA_MAX_KEY) { - object[name] = new MaxKey(); - } else if (elementType === BSON.BSON_DATA_CODE) { - stringSize = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - if ( - stringSize <= 0 || - stringSize > buffer.length - index || - buffer[index + stringSize - 1] !== 0 - ) - throw new Error('bad string length in bson'); - var functionString = buffer.toString('utf8', index, index + stringSize - 1); - - // If we are evaluating the functions - if (evalFunctions) { - // If we have cache enabled let's look for the md5 of the function in the cache - if (cacheFunctions) { - var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; - // Got to do this to avoid V8 deoptimizing the call due to finding eval - object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); - } else { - object[name] = isolateEval(functionString); - } - } else { - object[name] = new Code(functionString); - } - - // Update parse index position - index = index + stringSize; - } else if (elementType === BSON.BSON_DATA_CODE_W_SCOPE) { - var totalSize = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - - // Element cannot be shorter than totalSize + stringSize + documentSize + terminator - if (totalSize < 4 + 4 + 4 + 1) { - throw new Error('code_w_scope total size shorter minimum expected length'); - } - - // Get the code string size - stringSize = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - // Check if we have a valid string - if ( - stringSize <= 0 || - stringSize > buffer.length - index || - buffer[index + stringSize - 1] !== 0 - ) - throw new Error('bad string length in bson'); - - // Javascript function - functionString = buffer.toString('utf8', index, index + stringSize - 1); - // Update parse index position - index = index + stringSize; - // Parse the element - _index = index; - // Decode the size of the object document - objectSize = - buffer[index] | - (buffer[index + 1] << 8) | - (buffer[index + 2] << 16) | - (buffer[index + 3] << 24); - // Decode the scope object - var scopeObject = deserializeObject(buffer, _index, options, false); - // Adjust the index - index = index + objectSize; - - // Check if field length is to short - if (totalSize < 4 + 4 + objectSize + stringSize) { - throw new Error('code_w_scope total size is to short, truncating scope'); - } - - // Check if totalSize field is to long - if (totalSize > 4 + 4 + objectSize + stringSize) { - throw new Error('code_w_scope total size is to long, clips outer document'); - } - - // If we are evaluating the functions - if (evalFunctions) { - // If we have cache enabled let's look for the md5 of the function in the cache - if (cacheFunctions) { - hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; - // Got to do this to avoid V8 deoptimizing the call due to finding eval - object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); - } else { - object[name] = isolateEval(functionString); - } - - object[name].scope = scopeObject; - } else { - object[name] = new Code(functionString, scopeObject); - } - } else if (elementType === BSON.BSON_DATA_DBPOINTER) { - // Get the code string size - stringSize = - buffer[index++] | - (buffer[index++] << 8) | - (buffer[index++] << 16) | - (buffer[index++] << 24); - // Check if we have a valid string - if ( - stringSize <= 0 || - stringSize > buffer.length - index || - buffer[index + stringSize - 1] !== 0 - ) - throw new Error('bad string length in bson'); - // Namespace - var namespace = buffer.toString('utf8', index, index + stringSize - 1); - // Update parse index position - index = index + stringSize; - - // Read the oid - var oidBuffer = utils.allocBuffer(12); - buffer.copy(oidBuffer, 0, index, index + 12); - oid = new ObjectID(oidBuffer); - - // Update the index - index = index + 12; - - // Split the namespace - var parts = namespace.split('.'); - var db = parts.shift(); - var collection = parts.join('.'); - // Upgrade to DBRef type - object[name] = new DBRef(collection, oid, db); - } else { - throw new Error( - 'Detected unknown BSON type ' + - elementType.toString(16) + - ' for fieldname "' + - name + - '", are you using the latest BSON parser' - ); - } - } - - // Check if the deserialization was against a valid array/object - if (size !== index - startIndex) { - if (isArray) throw new Error('corrupt array bson'); - throw new Error('corrupt object bson'); - } - - // Check if we have a db ref object - if (object['$id'] != null) object = new DBRef(object['$ref'], object['$id'], object['$db']); - return object; -}; - -/** - * Ensure eval is isolated. - * - * @ignore - * @api private - */ -var isolateEvalWithHash = function(functionCache, hash, functionString, object) { - // Contains the value we are going to set - var value = null; - - // Check for cache hit, eval if missing and return cached function - if (functionCache[hash] == null) { - eval('value = ' + functionString); - functionCache[hash] = value; - } - // Set the object - return functionCache[hash].bind(object); -}; - -/** - * Ensure eval is isolated. - * - * @ignore - * @api private - */ -var isolateEval = function(functionString) { - // Contains the value we are going to set - var value = null; - // Eval the function - eval('value = ' + functionString); - return value; -}; - -var BSON = {}; - -/** - * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 - * - * @ignore - * @api private - */ -var functionCache = (BSON.functionCache = {}); - -/** - * Number BSON Type - * - * @classconstant BSON_DATA_NUMBER - **/ -BSON.BSON_DATA_NUMBER = 1; -/** - * String BSON Type - * - * @classconstant BSON_DATA_STRING - **/ -BSON.BSON_DATA_STRING = 2; -/** - * Object BSON Type - * - * @classconstant BSON_DATA_OBJECT - **/ -BSON.BSON_DATA_OBJECT = 3; -/** - * Array BSON Type - * - * @classconstant BSON_DATA_ARRAY - **/ -BSON.BSON_DATA_ARRAY = 4; -/** - * Binary BSON Type - * - * @classconstant BSON_DATA_BINARY - **/ -BSON.BSON_DATA_BINARY = 5; -/** - * Binary BSON Type - * - * @classconstant BSON_DATA_UNDEFINED - **/ -BSON.BSON_DATA_UNDEFINED = 6; -/** - * ObjectID BSON Type - * - * @classconstant BSON_DATA_OID - **/ -BSON.BSON_DATA_OID = 7; -/** - * Boolean BSON Type - * - * @classconstant BSON_DATA_BOOLEAN - **/ -BSON.BSON_DATA_BOOLEAN = 8; -/** - * Date BSON Type - * - * @classconstant BSON_DATA_DATE - **/ -BSON.BSON_DATA_DATE = 9; -/** - * null BSON Type - * - * @classconstant BSON_DATA_NULL - **/ -BSON.BSON_DATA_NULL = 10; -/** - * RegExp BSON Type - * - * @classconstant BSON_DATA_REGEXP - **/ -BSON.BSON_DATA_REGEXP = 11; -/** - * Code BSON Type - * - * @classconstant BSON_DATA_DBPOINTER - **/ -BSON.BSON_DATA_DBPOINTER = 12; -/** - * Code BSON Type - * - * @classconstant BSON_DATA_CODE - **/ -BSON.BSON_DATA_CODE = 13; -/** - * Symbol BSON Type - * - * @classconstant BSON_DATA_SYMBOL - **/ -BSON.BSON_DATA_SYMBOL = 14; -/** - * Code with Scope BSON Type - * - * @classconstant BSON_DATA_CODE_W_SCOPE - **/ -BSON.BSON_DATA_CODE_W_SCOPE = 15; -/** - * 32 bit Integer BSON Type - * - * @classconstant BSON_DATA_INT - **/ -BSON.BSON_DATA_INT = 16; -/** - * Timestamp BSON Type - * - * @classconstant BSON_DATA_TIMESTAMP - **/ -BSON.BSON_DATA_TIMESTAMP = 17; -/** - * Long BSON Type - * - * @classconstant BSON_DATA_LONG - **/ -BSON.BSON_DATA_LONG = 18; -/** - * Long BSON Type - * - * @classconstant BSON_DATA_DECIMAL128 - **/ -BSON.BSON_DATA_DECIMAL128 = 19; -/** - * MinKey BSON Type - * - * @classconstant BSON_DATA_MIN_KEY - **/ -BSON.BSON_DATA_MIN_KEY = 0xff; -/** - * MaxKey BSON Type - * - * @classconstant BSON_DATA_MAX_KEY - **/ -BSON.BSON_DATA_MAX_KEY = 0x7f; - -/** - * Binary Default Type - * - * @classconstant BSON_BINARY_SUBTYPE_DEFAULT - **/ -BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; -/** - * Binary Function Type - * - * @classconstant BSON_BINARY_SUBTYPE_FUNCTION - **/ -BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; -/** - * Binary Byte Array Type - * - * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY - **/ -BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; -/** - * Binary UUID Type - * - * @classconstant BSON_BINARY_SUBTYPE_UUID - **/ -BSON.BSON_BINARY_SUBTYPE_UUID = 3; -/** - * Binary MD5 Type - * - * @classconstant BSON_BINARY_SUBTYPE_MD5 - **/ -BSON.BSON_BINARY_SUBTYPE_MD5 = 4; -/** - * Binary User Defined Type - * - * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED - **/ -BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; - -// BSON MAX VALUES -BSON.BSON_INT32_MAX = 0x7fffffff; -BSON.BSON_INT32_MIN = -0x80000000; - -BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; -BSON.BSON_INT64_MIN = -Math.pow(2, 63); - -// JS MAX PRECISE VALUES -BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. -BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. - -// Internal long versions -var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. -var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. - -module.exports = deserialize; diff --git a/scripts/node_modules/bson/lib/bson/parser/serializer.js b/scripts/node_modules/bson/lib/bson/parser/serializer.js deleted file mode 100644 index e4ff2bd9..00000000 --- a/scripts/node_modules/bson/lib/bson/parser/serializer.js +++ /dev/null @@ -1,1182 +0,0 @@ -'use strict'; - -var writeIEEE754 = require('../float_parser').writeIEEE754, - Long = require('../long').Long, - Map = require('../map'), - Binary = require('../binary').Binary; - -var normalizedFunctionString = require('./utils').normalizedFunctionString; - -// try { -// var _Buffer = Uint8Array; -// } catch (e) { -// _Buffer = Buffer; -// } - -var regexp = /\x00/; // eslint-disable-line no-control-regex -var ignoreKeys = ['$db', '$ref', '$id', '$clusterTime']; - -// To ensure that 0.4 of node works correctly -var isDate = function isDate(d) { - return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; -}; - -var isRegExp = function isRegExp(d) { - return Object.prototype.toString.call(d) === '[object RegExp]'; -}; - -var serializeString = function(buffer, key, value, index, isArray) { - // Encode String type - buffer[index++] = BSON.BSON_DATA_STRING; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write the string - var size = buffer.write(value, index + 4, 'utf8'); - // Write the size of the string to buffer - buffer[index + 3] = ((size + 1) >> 24) & 0xff; - buffer[index + 2] = ((size + 1) >> 16) & 0xff; - buffer[index + 1] = ((size + 1) >> 8) & 0xff; - buffer[index] = (size + 1) & 0xff; - // Update index - index = index + 4 + size; - // Write zero - buffer[index++] = 0; - return index; -}; - -var serializeNumber = function(buffer, key, value, index, isArray) { - // We have an integer value - if (Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - // If the value fits in 32 bits encode as int, if it fits in a double - // encode it as a double, otherwise long - if (value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { - // Set int type 32 bits or less - buffer[index++] = BSON.BSON_DATA_INT; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the int value - buffer[index++] = value & 0xff; - buffer[index++] = (value >> 8) & 0xff; - buffer[index++] = (value >> 16) & 0xff; - buffer[index++] = (value >> 24) & 0xff; - } else if (value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - } else { - // Set long type - buffer[index++] = BSON.BSON_DATA_LONG; - // Number of written bytes - numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - var longVal = Long.fromNumber(value); - var lowBits = longVal.getLowBits(); - var highBits = longVal.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - } - } else { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - } - - return index; -}; - -var serializeNull = function(buffer, key, value, index, isArray) { - // Set long type - buffer[index++] = BSON.BSON_DATA_NULL; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - return index; -}; - -var serializeBoolean = function(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_BOOLEAN; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Encode the boolean value - buffer[index++] = value ? 1 : 0; - return index; -}; - -var serializeDate = function(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_DATE; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - - // Write the date - var dateInMilis = Long.fromNumber(value.getTime()); - var lowBits = dateInMilis.getLowBits(); - var highBits = dateInMilis.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - return index; -}; - -var serializeRegExp = function(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_REGEXP; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - if (value.source && value.source.match(regexp) != null) { - throw Error('value ' + value.source + ' must not contain null bytes'); - } - // Adjust the index - index = index + buffer.write(value.source, index, 'utf8'); - // Write zero - buffer[index++] = 0x00; - // Write the parameters - if (value.global) buffer[index++] = 0x73; // s - if (value.ignoreCase) buffer[index++] = 0x69; // i - if (value.multiline) buffer[index++] = 0x6d; // m - // Add ending zero - buffer[index++] = 0x00; - return index; -}; - -var serializeBSONRegExp = function(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_REGEXP; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - - // Check the pattern for 0 bytes - if (value.pattern.match(regexp) != null) { - // The BSON spec doesn't allow keys with null bytes because keys are - // null-terminated. - throw Error('pattern ' + value.pattern + ' must not contain null bytes'); - } - - // Adjust the index - index = index + buffer.write(value.pattern, index, 'utf8'); - // Write zero - buffer[index++] = 0x00; - // Write the options - index = - index + - buffer.write( - value.options - .split('') - .sort() - .join(''), - index, - 'utf8' - ); - // Add ending zero - buffer[index++] = 0x00; - return index; -}; - -var serializeMinMax = function(buffer, key, value, index, isArray) { - // Write the type of either min or max key - if (value === null) { - buffer[index++] = BSON.BSON_DATA_NULL; - } else if (value._bsontype === 'MinKey') { - buffer[index++] = BSON.BSON_DATA_MIN_KEY; - } else { - buffer[index++] = BSON.BSON_DATA_MAX_KEY; - } - - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - return index; -}; - -var serializeObjectId = function(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_OID; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - - // Write the objectId into the shared buffer - if (typeof value.id === 'string') { - buffer.write(value.id, index, 'binary'); - } else if (value.id && value.id.copy) { - value.id.copy(buffer, index, 0, 12); - } else { - throw new Error('object [' + JSON.stringify(value) + '] is not a valid ObjectId'); - } - - // Ajust index - return index + 12; -}; - -var serializeBuffer = function(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_BINARY; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Get size of the buffer (current write point) - var size = value.length; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the default subtype - buffer[index++] = BSON.BSON_BINARY_SUBTYPE_DEFAULT; - // Copy the content form the binary field to the buffer - value.copy(buffer, index, 0, size); - // Adjust the index - index = index + size; - return index; -}; - -var serializeObject = function( - buffer, - key, - value, - index, - checkKeys, - depth, - serializeFunctions, - ignoreUndefined, - isArray, - path -) { - for (var i = 0; i < path.length; i++) { - if (path[i] === value) throw new Error('cyclic dependency detected'); - } - - // Push value to stack - path.push(value); - // Write the type - buffer[index++] = Array.isArray(value) ? BSON.BSON_DATA_ARRAY : BSON.BSON_DATA_OBJECT; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - var endIndex = serializeInto( - buffer, - value, - checkKeys, - index, - depth + 1, - serializeFunctions, - ignoreUndefined, - path - ); - // Pop stack - path.pop(); - // Write size - return endIndex; -}; - -var serializeDecimal128 = function(buffer, key, value, index, isArray) { - buffer[index++] = BSON.BSON_DATA_DECIMAL128; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the data from the value - value.bytes.copy(buffer, index, 0, 16); - return index + 16; -}; - -var serializeLong = function(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = value._bsontype === 'Long' ? BSON.BSON_DATA_LONG : BSON.BSON_DATA_TIMESTAMP; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the date - var lowBits = value.getLowBits(); - var highBits = value.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - return index; -}; - -var serializeInt32 = function(buffer, key, value, index, isArray) { - // Set int type 32 bits or less - buffer[index++] = BSON.BSON_DATA_INT; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the int value - buffer[index++] = value & 0xff; - buffer[index++] = (value >> 8) & 0xff; - buffer[index++] = (value >> 16) & 0xff; - buffer[index++] = (value >> 24) & 0xff; - return index; -}; - -var serializeDouble = function(buffer, key, value, index, isArray) { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - return index; -}; - -var serializeFunction = function(buffer, key, value, index, checkKeys, depth, isArray) { - buffer[index++] = BSON.BSON_DATA_CODE; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Function string - var functionString = normalizedFunctionString(value); - - // Write the string - var size = buffer.write(functionString, index + 4, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = size & 0xff; - buffer[index + 1] = (size >> 8) & 0xff; - buffer[index + 2] = (size >> 16) & 0xff; - buffer[index + 3] = (size >> 24) & 0xff; - // Update index - index = index + 4 + size - 1; - // Write zero - buffer[index++] = 0; - return index; -}; - -var serializeCode = function( - buffer, - key, - value, - index, - checkKeys, - depth, - serializeFunctions, - ignoreUndefined, - isArray -) { - if (value.scope && typeof value.scope === 'object') { - // Write the type - buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - - // Starting index - var startIndex = index; - - // Serialize the function - // Get the function string - var functionString = typeof value.code === 'string' ? value.code : value.code.toString(); - // Index adjustment - index = index + 4; - // Write string into buffer - var codeSize = buffer.write(functionString, index + 4, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = codeSize & 0xff; - buffer[index + 1] = (codeSize >> 8) & 0xff; - buffer[index + 2] = (codeSize >> 16) & 0xff; - buffer[index + 3] = (codeSize >> 24) & 0xff; - // Write end 0 - buffer[index + 4 + codeSize - 1] = 0; - // Write the - index = index + codeSize + 4; - - // - // Serialize the scope value - var endIndex = serializeInto( - buffer, - value.scope, - checkKeys, - index, - depth + 1, - serializeFunctions, - ignoreUndefined - ); - index = endIndex - 1; - - // Writ the total - var totalSize = endIndex - startIndex; - - // Write the total size of the object - buffer[startIndex++] = totalSize & 0xff; - buffer[startIndex++] = (totalSize >> 8) & 0xff; - buffer[startIndex++] = (totalSize >> 16) & 0xff; - buffer[startIndex++] = (totalSize >> 24) & 0xff; - // Write trailing zero - buffer[index++] = 0; - } else { - buffer[index++] = BSON.BSON_DATA_CODE; - // Number of written bytes - numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Function string - functionString = value.code.toString(); - // Write the string - var size = buffer.write(functionString, index + 4, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = size & 0xff; - buffer[index + 1] = (size >> 8) & 0xff; - buffer[index + 2] = (size >> 16) & 0xff; - buffer[index + 3] = (size >> 24) & 0xff; - // Update index - index = index + 4 + size - 1; - // Write zero - buffer[index++] = 0; - } - - return index; -}; - -var serializeBinary = function(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_BINARY; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Extract the buffer - var data = value.value(true); - // Calculate size - var size = value.position; - // Add the deprecated 02 type 4 bytes of size to total - if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) size = size + 4; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the subtype to the buffer - buffer[index++] = value.sub_type; - - // If we have binary type 2 the 4 first bytes are the size - if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { - size = size - 4; - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - } - - // Write the data to the object - data.copy(buffer, index, 0, value.position); - // Adjust the index - index = index + value.position; - return index; -}; - -var serializeSymbol = function(buffer, key, value, index, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_SYMBOL; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the string - var size = buffer.write(value.value, index + 4, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = size & 0xff; - buffer[index + 1] = (size >> 8) & 0xff; - buffer[index + 2] = (size >> 16) & 0xff; - buffer[index + 3] = (size >> 24) & 0xff; - // Update index - index = index + 4 + size - 1; - // Write zero - buffer[index++] = 0x00; - return index; -}; - -var serializeDBRef = function(buffer, key, value, index, depth, serializeFunctions, isArray) { - // Write the type - buffer[index++] = BSON.BSON_DATA_OBJECT; - // Number of written bytes - var numberOfWrittenBytes = !isArray - ? buffer.write(key, index, 'utf8') - : buffer.write(key, index, 'ascii'); - - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - - var startIndex = index; - var endIndex; - - // Serialize object - if (null != value.db) { - endIndex = serializeInto( - buffer, - { - $ref: value.namespace, - $id: value.oid, - $db: value.db - }, - false, - index, - depth + 1, - serializeFunctions - ); - } else { - endIndex = serializeInto( - buffer, - { - $ref: value.namespace, - $id: value.oid - }, - false, - index, - depth + 1, - serializeFunctions - ); - } - - // Calculate object size - var size = endIndex - startIndex; - // Write the size - buffer[startIndex++] = size & 0xff; - buffer[startIndex++] = (size >> 8) & 0xff; - buffer[startIndex++] = (size >> 16) & 0xff; - buffer[startIndex++] = (size >> 24) & 0xff; - // Set index - return endIndex; -}; - -var serializeInto = function serializeInto( - buffer, - object, - checkKeys, - startingIndex, - depth, - serializeFunctions, - ignoreUndefined, - path -) { - startingIndex = startingIndex || 0; - path = path || []; - - // Push the object to the path - path.push(object); - - // Start place to serialize into - var index = startingIndex + 4; - // var self = this; - - // Special case isArray - if (Array.isArray(object)) { - // Get object keys - for (var i = 0; i < object.length; i++) { - var key = '' + i; - var value = object[i]; - - // Is there an override value - if (value && value.toBSON) { - if (typeof value.toBSON !== 'function') throw new Error('toBSON is not a function'); - value = value.toBSON(); - } - - var type = typeof value; - if (type === 'string') { - index = serializeString(buffer, key, value, index, true); - } else if (type === 'number') { - index = serializeNumber(buffer, key, value, index, true); - } else if (type === 'boolean') { - index = serializeBoolean(buffer, key, value, index, true); - } else if (value instanceof Date || isDate(value)) { - index = serializeDate(buffer, key, value, index, true); - } else if (value === undefined) { - index = serializeNull(buffer, key, value, index, true); - } else if (value === null) { - index = serializeNull(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'ObjectID' || value['_bsontype'] === 'ObjectId') { - index = serializeObjectId(buffer, key, value, index, true); - } else if (Buffer.isBuffer(value)) { - index = serializeBuffer(buffer, key, value, index, true); - } else if (value instanceof RegExp || isRegExp(value)) { - index = serializeRegExp(buffer, key, value, index, true); - } else if (type === 'object' && value['_bsontype'] == null) { - index = serializeObject( - buffer, - key, - value, - index, - checkKeys, - depth, - serializeFunctions, - ignoreUndefined, - true, - path - ); - } else if (type === 'object' && value['_bsontype'] === 'Decimal128') { - index = serializeDecimal128(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { - index = serializeLong(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'Double') { - index = serializeDouble(buffer, key, value, index, true); - } else if (typeof value === 'function' && serializeFunctions) { - index = serializeFunction( - buffer, - key, - value, - index, - checkKeys, - depth, - serializeFunctions, - true - ); - } else if (value['_bsontype'] === 'Code') { - index = serializeCode( - buffer, - key, - value, - index, - checkKeys, - depth, - serializeFunctions, - ignoreUndefined, - true - ); - } else if (value['_bsontype'] === 'Binary') { - index = serializeBinary(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'Symbol') { - index = serializeSymbol(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'DBRef') { - index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, true); - } else if (value['_bsontype'] === 'BSONRegExp') { - index = serializeBSONRegExp(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'Int32') { - index = serializeInt32(buffer, key, value, index, true); - } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { - index = serializeMinMax(buffer, key, value, index, true); - } - } - } else if (object instanceof Map) { - var iterator = object.entries(); - var done = false; - - while (!done) { - // Unpack the next entry - var entry = iterator.next(); - done = entry.done; - // Are we done, then skip and terminate - if (done) continue; - - // Get the entry values - key = entry.value[0]; - value = entry.value[1]; - - // Check the type of the value - type = typeof value; - - // Check the key and throw error if it's illegal - if (typeof key === 'string' && ignoreKeys.indexOf(key) === -1) { - if (key.match(regexp) != null) { - // The BSON spec doesn't allow keys with null bytes because keys are - // null-terminated. - throw Error('key ' + key + ' must not contain null bytes'); - } - - if (checkKeys) { - if ('$' === key[0]) { - throw Error('key ' + key + " must not start with '$'"); - } else if (~key.indexOf('.')) { - throw Error('key ' + key + " must not contain '.'"); - } - } - } - - if (type === 'string') { - index = serializeString(buffer, key, value, index); - } else if (type === 'number') { - index = serializeNumber(buffer, key, value, index); - } else if (type === 'boolean') { - index = serializeBoolean(buffer, key, value, index); - } else if (value instanceof Date || isDate(value)) { - index = serializeDate(buffer, key, value, index); - // } else if (value === undefined && ignoreUndefined === true) { - } else if (value === null || (value === undefined && ignoreUndefined === false)) { - index = serializeNull(buffer, key, value, index); - } else if (value['_bsontype'] === 'ObjectID' || value['_bsontype'] === 'ObjectId') { - index = serializeObjectId(buffer, key, value, index); - } else if (Buffer.isBuffer(value)) { - index = serializeBuffer(buffer, key, value, index); - } else if (value instanceof RegExp || isRegExp(value)) { - index = serializeRegExp(buffer, key, value, index); - } else if (type === 'object' && value['_bsontype'] == null) { - index = serializeObject( - buffer, - key, - value, - index, - checkKeys, - depth, - serializeFunctions, - ignoreUndefined, - false, - path - ); - } else if (type === 'object' && value['_bsontype'] === 'Decimal128') { - index = serializeDecimal128(buffer, key, value, index); - } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { - index = serializeLong(buffer, key, value, index); - } else if (value['_bsontype'] === 'Double') { - index = serializeDouble(buffer, key, value, index); - } else if (value['_bsontype'] === 'Code') { - index = serializeCode( - buffer, - key, - value, - index, - checkKeys, - depth, - serializeFunctions, - ignoreUndefined - ); - } else if (typeof value === 'function' && serializeFunctions) { - index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); - } else if (value['_bsontype'] === 'Binary') { - index = serializeBinary(buffer, key, value, index); - } else if (value['_bsontype'] === 'Symbol') { - index = serializeSymbol(buffer, key, value, index); - } else if (value['_bsontype'] === 'DBRef') { - index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); - } else if (value['_bsontype'] === 'BSONRegExp') { - index = serializeBSONRegExp(buffer, key, value, index); - } else if (value['_bsontype'] === 'Int32') { - index = serializeInt32(buffer, key, value, index); - } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { - index = serializeMinMax(buffer, key, value, index); - } - } - } else { - // Did we provide a custom serialization method - if (object.toBSON) { - if (typeof object.toBSON !== 'function') throw new Error('toBSON is not a function'); - object = object.toBSON(); - if (object != null && typeof object !== 'object') - throw new Error('toBSON function did not return an object'); - } - - // Iterate over all the keys - for (key in object) { - value = object[key]; - // Is there an override value - if (value && value.toBSON) { - if (typeof value.toBSON !== 'function') throw new Error('toBSON is not a function'); - value = value.toBSON(); - } - - // Check the type of the value - type = typeof value; - - // Check the key and throw error if it's illegal - if (typeof key === 'string' && ignoreKeys.indexOf(key) === -1) { - if (key.match(regexp) != null) { - // The BSON spec doesn't allow keys with null bytes because keys are - // null-terminated. - throw Error('key ' + key + ' must not contain null bytes'); - } - - if (checkKeys) { - if ('$' === key[0]) { - throw Error('key ' + key + " must not start with '$'"); - } else if (~key.indexOf('.')) { - throw Error('key ' + key + " must not contain '.'"); - } - } - } - - if (type === 'string') { - index = serializeString(buffer, key, value, index); - } else if (type === 'number') { - index = serializeNumber(buffer, key, value, index); - } else if (type === 'boolean') { - index = serializeBoolean(buffer, key, value, index); - } else if (value instanceof Date || isDate(value)) { - index = serializeDate(buffer, key, value, index); - } else if (value === undefined) { - if (ignoreUndefined === false) index = serializeNull(buffer, key, value, index); - } else if (value === null) { - index = serializeNull(buffer, key, value, index); - } else if (value['_bsontype'] === 'ObjectID' || value['_bsontype'] === 'ObjectId') { - index = serializeObjectId(buffer, key, value, index); - } else if (Buffer.isBuffer(value)) { - index = serializeBuffer(buffer, key, value, index); - } else if (value instanceof RegExp || isRegExp(value)) { - index = serializeRegExp(buffer, key, value, index); - } else if (type === 'object' && value['_bsontype'] == null) { - index = serializeObject( - buffer, - key, - value, - index, - checkKeys, - depth, - serializeFunctions, - ignoreUndefined, - false, - path - ); - } else if (type === 'object' && value['_bsontype'] === 'Decimal128') { - index = serializeDecimal128(buffer, key, value, index); - } else if (value['_bsontype'] === 'Long' || value['_bsontype'] === 'Timestamp') { - index = serializeLong(buffer, key, value, index); - } else if (value['_bsontype'] === 'Double') { - index = serializeDouble(buffer, key, value, index); - } else if (value['_bsontype'] === 'Code') { - index = serializeCode( - buffer, - key, - value, - index, - checkKeys, - depth, - serializeFunctions, - ignoreUndefined - ); - } else if (typeof value === 'function' && serializeFunctions) { - index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); - } else if (value['_bsontype'] === 'Binary') { - index = serializeBinary(buffer, key, value, index); - } else if (value['_bsontype'] === 'Symbol') { - index = serializeSymbol(buffer, key, value, index); - } else if (value['_bsontype'] === 'DBRef') { - index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); - } else if (value['_bsontype'] === 'BSONRegExp') { - index = serializeBSONRegExp(buffer, key, value, index); - } else if (value['_bsontype'] === 'Int32') { - index = serializeInt32(buffer, key, value, index); - } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { - index = serializeMinMax(buffer, key, value, index); - } - } - } - - // Remove the path - path.pop(); - - // Final padding byte for object - buffer[index++] = 0x00; - - // Final size - var size = index - startingIndex; - // Write the size of the object - buffer[startingIndex++] = size & 0xff; - buffer[startingIndex++] = (size >> 8) & 0xff; - buffer[startingIndex++] = (size >> 16) & 0xff; - buffer[startingIndex++] = (size >> 24) & 0xff; - return index; -}; - -var BSON = {}; - -/** - * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 - * - * @ignore - * @api private - */ -// var functionCache = (BSON.functionCache = {}); - -/** - * Number BSON Type - * - * @classconstant BSON_DATA_NUMBER - **/ -BSON.BSON_DATA_NUMBER = 1; -/** - * String BSON Type - * - * @classconstant BSON_DATA_STRING - **/ -BSON.BSON_DATA_STRING = 2; -/** - * Object BSON Type - * - * @classconstant BSON_DATA_OBJECT - **/ -BSON.BSON_DATA_OBJECT = 3; -/** - * Array BSON Type - * - * @classconstant BSON_DATA_ARRAY - **/ -BSON.BSON_DATA_ARRAY = 4; -/** - * Binary BSON Type - * - * @classconstant BSON_DATA_BINARY - **/ -BSON.BSON_DATA_BINARY = 5; -/** - * ObjectID BSON Type, deprecated - * - * @classconstant BSON_DATA_UNDEFINED - **/ -BSON.BSON_DATA_UNDEFINED = 6; -/** - * ObjectID BSON Type - * - * @classconstant BSON_DATA_OID - **/ -BSON.BSON_DATA_OID = 7; -/** - * Boolean BSON Type - * - * @classconstant BSON_DATA_BOOLEAN - **/ -BSON.BSON_DATA_BOOLEAN = 8; -/** - * Date BSON Type - * - * @classconstant BSON_DATA_DATE - **/ -BSON.BSON_DATA_DATE = 9; -/** - * null BSON Type - * - * @classconstant BSON_DATA_NULL - **/ -BSON.BSON_DATA_NULL = 10; -/** - * RegExp BSON Type - * - * @classconstant BSON_DATA_REGEXP - **/ -BSON.BSON_DATA_REGEXP = 11; -/** - * Code BSON Type - * - * @classconstant BSON_DATA_CODE - **/ -BSON.BSON_DATA_CODE = 13; -/** - * Symbol BSON Type - * - * @classconstant BSON_DATA_SYMBOL - **/ -BSON.BSON_DATA_SYMBOL = 14; -/** - * Code with Scope BSON Type - * - * @classconstant BSON_DATA_CODE_W_SCOPE - **/ -BSON.BSON_DATA_CODE_W_SCOPE = 15; -/** - * 32 bit Integer BSON Type - * - * @classconstant BSON_DATA_INT - **/ -BSON.BSON_DATA_INT = 16; -/** - * Timestamp BSON Type - * - * @classconstant BSON_DATA_TIMESTAMP - **/ -BSON.BSON_DATA_TIMESTAMP = 17; -/** - * Long BSON Type - * - * @classconstant BSON_DATA_LONG - **/ -BSON.BSON_DATA_LONG = 18; -/** - * Long BSON Type - * - * @classconstant BSON_DATA_DECIMAL128 - **/ -BSON.BSON_DATA_DECIMAL128 = 19; -/** - * MinKey BSON Type - * - * @classconstant BSON_DATA_MIN_KEY - **/ -BSON.BSON_DATA_MIN_KEY = 0xff; -/** - * MaxKey BSON Type - * - * @classconstant BSON_DATA_MAX_KEY - **/ -BSON.BSON_DATA_MAX_KEY = 0x7f; -/** - * Binary Default Type - * - * @classconstant BSON_BINARY_SUBTYPE_DEFAULT - **/ -BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; -/** - * Binary Function Type - * - * @classconstant BSON_BINARY_SUBTYPE_FUNCTION - **/ -BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; -/** - * Binary Byte Array Type - * - * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY - **/ -BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; -/** - * Binary UUID Type - * - * @classconstant BSON_BINARY_SUBTYPE_UUID - **/ -BSON.BSON_BINARY_SUBTYPE_UUID = 3; -/** - * Binary MD5 Type - * - * @classconstant BSON_BINARY_SUBTYPE_MD5 - **/ -BSON.BSON_BINARY_SUBTYPE_MD5 = 4; -/** - * Binary User Defined Type - * - * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED - **/ -BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; - -// BSON MAX VALUES -BSON.BSON_INT32_MAX = 0x7fffffff; -BSON.BSON_INT32_MIN = -0x80000000; - -BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; -BSON.BSON_INT64_MIN = -Math.pow(2, 63); - -// JS MAX PRECISE VALUES -BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. -BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. - -// Internal long versions -// var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. -// var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. - -module.exports = serializeInto; diff --git a/scripts/node_modules/bson/lib/bson/parser/utils.js b/scripts/node_modules/bson/lib/bson/parser/utils.js deleted file mode 100644 index 6faa4396..00000000 --- a/scripts/node_modules/bson/lib/bson/parser/utils.js +++ /dev/null @@ -1,28 +0,0 @@ -'use strict'; - -/** - * Normalizes our expected stringified form of a function across versions of node - * @param {Function} fn The function to stringify - */ -function normalizedFunctionString(fn) { - return fn.toString().replace(/function *\(/, 'function ('); -} - -function newBuffer(item, encoding) { - return new Buffer(item, encoding); -} - -function allocBuffer() { - return Buffer.alloc.apply(Buffer, arguments); -} - -function toBuffer() { - return Buffer.from.apply(Buffer, arguments); -} - -module.exports = { - normalizedFunctionString: normalizedFunctionString, - allocBuffer: typeof Buffer.alloc === 'function' ? allocBuffer : newBuffer, - toBuffer: typeof Buffer.from === 'function' ? toBuffer : newBuffer -}; - diff --git a/scripts/node_modules/bson/lib/bson/regexp.js b/scripts/node_modules/bson/lib/bson/regexp.js deleted file mode 100644 index 108f0166..00000000 --- a/scripts/node_modules/bson/lib/bson/regexp.js +++ /dev/null @@ -1,33 +0,0 @@ -/** - * A class representation of the BSON RegExp type. - * - * @class - * @return {BSONRegExp} A MinKey instance - */ -function BSONRegExp(pattern, options) { - if (!(this instanceof BSONRegExp)) return new BSONRegExp(); - - // Execute - this._bsontype = 'BSONRegExp'; - this.pattern = pattern || ''; - this.options = options || ''; - - // Validate options - for (var i = 0; i < this.options.length; i++) { - if ( - !( - this.options[i] === 'i' || - this.options[i] === 'm' || - this.options[i] === 'x' || - this.options[i] === 'l' || - this.options[i] === 's' || - this.options[i] === 'u' - ) - ) { - throw new Error('the regular expression options [' + this.options[i] + '] is not supported'); - } - } -} - -module.exports = BSONRegExp; -module.exports.BSONRegExp = BSONRegExp; diff --git a/scripts/node_modules/bson/lib/bson/symbol.js b/scripts/node_modules/bson/lib/bson/symbol.js deleted file mode 100644 index ba20cabe..00000000 --- a/scripts/node_modules/bson/lib/bson/symbol.js +++ /dev/null @@ -1,50 +0,0 @@ -// Custom inspect property name / symbol. -var inspect = Buffer ? require('util').inspect.custom || 'inspect' : 'inspect'; - -/** - * A class representation of the BSON Symbol type. - * - * @class - * @deprecated - * @param {string} value the string representing the symbol. - * @return {Symbol} - */ -function Symbol(value) { - if (!(this instanceof Symbol)) return new Symbol(value); - this._bsontype = 'Symbol'; - this.value = value; -} - -/** - * Access the wrapped string value. - * - * @method - * @return {String} returns the wrapped string. - */ -Symbol.prototype.valueOf = function() { - return this.value; -}; - -/** - * @ignore - */ -Symbol.prototype.toString = function() { - return this.value; -}; - -/** - * @ignore - */ -Symbol.prototype[inspect] = function() { - return this.value; -}; - -/** - * @ignore - */ -Symbol.prototype.toJSON = function() { - return this.value; -}; - -module.exports = Symbol; -module.exports.Symbol = Symbol; diff --git a/scripts/node_modules/bson/lib/bson/timestamp.js b/scripts/node_modules/bson/lib/bson/timestamp.js deleted file mode 100644 index dc61a6cc..00000000 --- a/scripts/node_modules/bson/lib/bson/timestamp.js +++ /dev/null @@ -1,854 +0,0 @@ -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// Copyright 2009 Google Inc. All Rights Reserved - -/** - * This type is for INTERNAL use in MongoDB only and should not be used in applications. - * The appropriate corresponding type is the JavaScript Date type. - * - * Defines a Timestamp class for representing a 64-bit two's-complement - * integer value, which faithfully simulates the behavior of a Java "Timestamp". This - * implementation is derived from TimestampLib in GWT. - * - * Constructs a 64-bit two's-complement integer, given its low and high 32-bit - * values as *signed* integers. See the from* functions below for more - * convenient ways of constructing Timestamps. - * - * The internal representation of a Timestamp is the two given signed, 32-bit values. - * We use 32-bit pieces because these are the size of integers on which - * Javascript performs bit-operations. For operations like addition and - * multiplication, we split each number into 16-bit pieces, which can easily be - * multiplied within Javascript's floating-point representation without overflow - * or change in sign. - * - * In the algorithms below, we frequently reduce the negative case to the - * positive case by negating the input(s) and then post-processing the result. - * Note that we must ALWAYS check specially whether those values are MIN_VALUE - * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as - * a positive number, it overflows back into a negative). Not handling this - * case would often result in infinite recursion. - * - * @class - * @param {number} low the low (signed) 32 bits of the Timestamp. - * @param {number} high the high (signed) 32 bits of the Timestamp. - */ -function Timestamp(low, high) { - if (!(this instanceof Timestamp)) return new Timestamp(low, high); - this._bsontype = 'Timestamp'; - /** - * @type {number} - * @ignore - */ - this.low_ = low | 0; // force into 32 signed bits. - - /** - * @type {number} - * @ignore - */ - this.high_ = high | 0; // force into 32 signed bits. -} - -/** - * Return the int value. - * - * @return {number} the value, assuming it is a 32-bit integer. - */ -Timestamp.prototype.toInt = function() { - return this.low_; -}; - -/** - * Return the Number value. - * - * @method - * @return {number} the closest floating-point representation to this value. - */ -Timestamp.prototype.toNumber = function() { - return this.high_ * Timestamp.TWO_PWR_32_DBL_ + this.getLowBitsUnsigned(); -}; - -/** - * Return the JSON value. - * - * @method - * @return {string} the JSON representation. - */ -Timestamp.prototype.toJSON = function() { - return this.toString(); -}; - -/** - * Return the String value. - * - * @method - * @param {number} [opt_radix] the radix in which the text should be written. - * @return {string} the textual representation of this value. - */ -Timestamp.prototype.toString = function(opt_radix) { - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (this.isZero()) { - return '0'; - } - - if (this.isNegative()) { - if (this.equals(Timestamp.MIN_VALUE)) { - // We need to change the Timestamp value before it can be negated, so we remove - // the bottom-most digit in this base and then recurse to do the rest. - var radixTimestamp = Timestamp.fromNumber(radix); - var div = this.div(radixTimestamp); - var rem = div.multiply(radixTimestamp).subtract(this); - return div.toString(radix) + rem.toInt().toString(radix); - } else { - return '-' + this.negate().toString(radix); - } - } - - // Do several (6) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Timestamp.fromNumber(Math.pow(radix, 6)); - - rem = this; - var result = ''; - - while (!rem.isZero()) { - var remDiv = rem.div(radixToPower); - var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); - var digits = intval.toString(radix); - - rem = remDiv; - if (rem.isZero()) { - return digits + result; - } else { - while (digits.length < 6) { - digits = '0' + digits; - } - result = '' + digits + result; - } - } -}; - -/** - * Return the high 32-bits value. - * - * @method - * @return {number} the high 32-bits as a signed value. - */ -Timestamp.prototype.getHighBits = function() { - return this.high_; -}; - -/** - * Return the low 32-bits value. - * - * @method - * @return {number} the low 32-bits as a signed value. - */ -Timestamp.prototype.getLowBits = function() { - return this.low_; -}; - -/** - * Return the low unsigned 32-bits value. - * - * @method - * @return {number} the low 32-bits as an unsigned value. - */ -Timestamp.prototype.getLowBitsUnsigned = function() { - return this.low_ >= 0 ? this.low_ : Timestamp.TWO_PWR_32_DBL_ + this.low_; -}; - -/** - * Returns the number of bits needed to represent the absolute value of this Timestamp. - * - * @method - * @return {number} Returns the number of bits needed to represent the absolute value of this Timestamp. - */ -Timestamp.prototype.getNumBitsAbs = function() { - if (this.isNegative()) { - if (this.equals(Timestamp.MIN_VALUE)) { - return 64; - } else { - return this.negate().getNumBitsAbs(); - } - } else { - var val = this.high_ !== 0 ? this.high_ : this.low_; - for (var bit = 31; bit > 0; bit--) { - if ((val & (1 << bit)) !== 0) { - break; - } - } - return this.high_ !== 0 ? bit + 33 : bit + 1; - } -}; - -/** - * Return whether this value is zero. - * - * @method - * @return {boolean} whether this value is zero. - */ -Timestamp.prototype.isZero = function() { - return this.high_ === 0 && this.low_ === 0; -}; - -/** - * Return whether this value is negative. - * - * @method - * @return {boolean} whether this value is negative. - */ -Timestamp.prototype.isNegative = function() { - return this.high_ < 0; -}; - -/** - * Return whether this value is odd. - * - * @method - * @return {boolean} whether this value is odd. - */ -Timestamp.prototype.isOdd = function() { - return (this.low_ & 1) === 1; -}; - -/** - * Return whether this Timestamp equals the other - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp equals the other - */ -Timestamp.prototype.equals = function(other) { - return this.high_ === other.high_ && this.low_ === other.low_; -}; - -/** - * Return whether this Timestamp does not equal the other. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp does not equal the other. - */ -Timestamp.prototype.notEquals = function(other) { - return this.high_ !== other.high_ || this.low_ !== other.low_; -}; - -/** - * Return whether this Timestamp is less than the other. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp is less than the other. - */ -Timestamp.prototype.lessThan = function(other) { - return this.compare(other) < 0; -}; - -/** - * Return whether this Timestamp is less than or equal to the other. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp is less than or equal to the other. - */ -Timestamp.prototype.lessThanOrEqual = function(other) { - return this.compare(other) <= 0; -}; - -/** - * Return whether this Timestamp is greater than the other. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp is greater than the other. - */ -Timestamp.prototype.greaterThan = function(other) { - return this.compare(other) > 0; -}; - -/** - * Return whether this Timestamp is greater than or equal to the other. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp is greater than or equal to the other. - */ -Timestamp.prototype.greaterThanOrEqual = function(other) { - return this.compare(other) >= 0; -}; - -/** - * Compares this Timestamp with the given one. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. - */ -Timestamp.prototype.compare = function(other) { - if (this.equals(other)) { - return 0; - } - - var thisNeg = this.isNegative(); - var otherNeg = other.isNegative(); - if (thisNeg && !otherNeg) { - return -1; - } - if (!thisNeg && otherNeg) { - return 1; - } - - // at this point, the signs are the same, so subtraction will not overflow - if (this.subtract(other).isNegative()) { - return -1; - } else { - return 1; - } -}; - -/** - * The negation of this value. - * - * @method - * @return {Timestamp} the negation of this value. - */ -Timestamp.prototype.negate = function() { - if (this.equals(Timestamp.MIN_VALUE)) { - return Timestamp.MIN_VALUE; - } else { - return this.not().add(Timestamp.ONE); - } -}; - -/** - * Returns the sum of this and the given Timestamp. - * - * @method - * @param {Timestamp} other Timestamp to add to this one. - * @return {Timestamp} the sum of this and the given Timestamp. - */ -Timestamp.prototype.add = function(other) { - // Divide each number into 4 chunks of 16 bits, and then sum the chunks. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xffff; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xffff; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xffff; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xffff; - - var c48 = 0, - c32 = 0, - c16 = 0, - c00 = 0; - c00 += a00 + b00; - c16 += c00 >>> 16; - c00 &= 0xffff; - c16 += a16 + b16; - c32 += c16 >>> 16; - c16 &= 0xffff; - c32 += a32 + b32; - c48 += c32 >>> 16; - c32 &= 0xffff; - c48 += a48 + b48; - c48 &= 0xffff; - return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32); -}; - -/** - * Returns the difference of this and the given Timestamp. - * - * @method - * @param {Timestamp} other Timestamp to subtract from this. - * @return {Timestamp} the difference of this and the given Timestamp. - */ -Timestamp.prototype.subtract = function(other) { - return this.add(other.negate()); -}; - -/** - * Returns the product of this and the given Timestamp. - * - * @method - * @param {Timestamp} other Timestamp to multiply with this. - * @return {Timestamp} the product of this and the other. - */ -Timestamp.prototype.multiply = function(other) { - if (this.isZero()) { - return Timestamp.ZERO; - } else if (other.isZero()) { - return Timestamp.ZERO; - } - - if (this.equals(Timestamp.MIN_VALUE)) { - return other.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; - } else if (other.equals(Timestamp.MIN_VALUE)) { - return this.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().multiply(other.negate()); - } else { - return this.negate() - .multiply(other) - .negate(); - } - } else if (other.isNegative()) { - return this.multiply(other.negate()).negate(); - } - - // If both Timestamps are small, use float multiplication - if (this.lessThan(Timestamp.TWO_PWR_24_) && other.lessThan(Timestamp.TWO_PWR_24_)) { - return Timestamp.fromNumber(this.toNumber() * other.toNumber()); - } - - // Divide each Timestamp into 4 chunks of 16 bits, and then add up 4x4 products. - // We can skip products that would overflow. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xffff; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xffff; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xffff; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xffff; - - var c48 = 0, - c32 = 0, - c16 = 0, - c00 = 0; - c00 += a00 * b00; - c16 += c00 >>> 16; - c00 &= 0xffff; - c16 += a16 * b00; - c32 += c16 >>> 16; - c16 &= 0xffff; - c16 += a00 * b16; - c32 += c16 >>> 16; - c16 &= 0xffff; - c32 += a32 * b00; - c48 += c32 >>> 16; - c32 &= 0xffff; - c32 += a16 * b16; - c48 += c32 >>> 16; - c32 &= 0xffff; - c32 += a00 * b32; - c48 += c32 >>> 16; - c32 &= 0xffff; - c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; - c48 &= 0xffff; - return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32); -}; - -/** - * Returns this Timestamp divided by the given one. - * - * @method - * @param {Timestamp} other Timestamp by which to divide. - * @return {Timestamp} this Timestamp divided by the given one. - */ -Timestamp.prototype.div = function(other) { - if (other.isZero()) { - throw Error('division by zero'); - } else if (this.isZero()) { - return Timestamp.ZERO; - } - - if (this.equals(Timestamp.MIN_VALUE)) { - if (other.equals(Timestamp.ONE) || other.equals(Timestamp.NEG_ONE)) { - return Timestamp.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE - } else if (other.equals(Timestamp.MIN_VALUE)) { - return Timestamp.ONE; - } else { - // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. - var halfThis = this.shiftRight(1); - var approx = halfThis.div(other).shiftLeft(1); - if (approx.equals(Timestamp.ZERO)) { - return other.isNegative() ? Timestamp.ONE : Timestamp.NEG_ONE; - } else { - var rem = this.subtract(other.multiply(approx)); - var result = approx.add(rem.div(other)); - return result; - } - } - } else if (other.equals(Timestamp.MIN_VALUE)) { - return Timestamp.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().div(other.negate()); - } else { - return this.negate() - .div(other) - .negate(); - } - } else if (other.isNegative()) { - return this.div(other.negate()).negate(); - } - - // Repeat the following until the remainder is less than other: find a - // floating-point that approximates remainder / other *from below*, add this - // into the result, and subtract it from the remainder. It is critical that - // the approximate value is less than or equal to the real value so that the - // remainder never becomes negative. - var res = Timestamp.ZERO; - rem = this; - while (rem.greaterThanOrEqual(other)) { - // Approximate the result of division. This may be a little greater or - // smaller than the actual value. - approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); - - // We will tweak the approximate result by changing it in the 48-th digit or - // the smallest non-fractional digit, whichever is larger. - var log2 = Math.ceil(Math.log(approx) / Math.LN2); - var delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48); - - // Decrease the approximation until it is smaller than the remainder. Note - // that if it is too large, the product overflows and is negative. - var approxRes = Timestamp.fromNumber(approx); - var approxRem = approxRes.multiply(other); - while (approxRem.isNegative() || approxRem.greaterThan(rem)) { - approx -= delta; - approxRes = Timestamp.fromNumber(approx); - approxRem = approxRes.multiply(other); - } - - // We know the answer can't be zero... and actually, zero would cause - // infinite recursion since we would make no progress. - if (approxRes.isZero()) { - approxRes = Timestamp.ONE; - } - - res = res.add(approxRes); - rem = rem.subtract(approxRem); - } - return res; -}; - -/** - * Returns this Timestamp modulo the given one. - * - * @method - * @param {Timestamp} other Timestamp by which to mod. - * @return {Timestamp} this Timestamp modulo the given one. - */ -Timestamp.prototype.modulo = function(other) { - return this.subtract(this.div(other).multiply(other)); -}; - -/** - * The bitwise-NOT of this value. - * - * @method - * @return {Timestamp} the bitwise-NOT of this value. - */ -Timestamp.prototype.not = function() { - return Timestamp.fromBits(~this.low_, ~this.high_); -}; - -/** - * Returns the bitwise-AND of this Timestamp and the given one. - * - * @method - * @param {Timestamp} other the Timestamp with which to AND. - * @return {Timestamp} the bitwise-AND of this and the other. - */ -Timestamp.prototype.and = function(other) { - return Timestamp.fromBits(this.low_ & other.low_, this.high_ & other.high_); -}; - -/** - * Returns the bitwise-OR of this Timestamp and the given one. - * - * @method - * @param {Timestamp} other the Timestamp with which to OR. - * @return {Timestamp} the bitwise-OR of this and the other. - */ -Timestamp.prototype.or = function(other) { - return Timestamp.fromBits(this.low_ | other.low_, this.high_ | other.high_); -}; - -/** - * Returns the bitwise-XOR of this Timestamp and the given one. - * - * @method - * @param {Timestamp} other the Timestamp with which to XOR. - * @return {Timestamp} the bitwise-XOR of this and the other. - */ -Timestamp.prototype.xor = function(other) { - return Timestamp.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); -}; - -/** - * Returns this Timestamp with bits shifted to the left by the given amount. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Timestamp} this shifted to the left by the given amount. - */ -Timestamp.prototype.shiftLeft = function(numBits) { - numBits &= 63; - if (numBits === 0) { - return this; - } else { - var low = this.low_; - if (numBits < 32) { - var high = this.high_; - return Timestamp.fromBits(low << numBits, (high << numBits) | (low >>> (32 - numBits))); - } else { - return Timestamp.fromBits(0, low << (numBits - 32)); - } - } -}; - -/** - * Returns this Timestamp with bits shifted to the right by the given amount. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Timestamp} this shifted to the right by the given amount. - */ -Timestamp.prototype.shiftRight = function(numBits) { - numBits &= 63; - if (numBits === 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Timestamp.fromBits((low >>> numBits) | (high << (32 - numBits)), high >> numBits); - } else { - return Timestamp.fromBits(high >> (numBits - 32), high >= 0 ? 0 : -1); - } - } -}; - -/** - * Returns this Timestamp with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Timestamp} this shifted to the right by the given amount, with zeros placed into the new leading bits. - */ -Timestamp.prototype.shiftRightUnsigned = function(numBits) { - numBits &= 63; - if (numBits === 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Timestamp.fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits); - } else if (numBits === 32) { - return Timestamp.fromBits(high, 0); - } else { - return Timestamp.fromBits(high >>> (numBits - 32), 0); - } - } -}; - -/** - * Returns a Timestamp representing the given (32-bit) integer value. - * - * @method - * @param {number} value the 32-bit integer in question. - * @return {Timestamp} the corresponding Timestamp value. - */ -Timestamp.fromInt = function(value) { - if (-128 <= value && value < 128) { - var cachedObj = Timestamp.INT_CACHE_[value]; - if (cachedObj) { - return cachedObj; - } - } - - var obj = new Timestamp(value | 0, value < 0 ? -1 : 0); - if (-128 <= value && value < 128) { - Timestamp.INT_CACHE_[value] = obj; - } - return obj; -}; - -/** - * Returns a Timestamp representing the given value, provided that it is a finite number. Otherwise, zero is returned. - * - * @method - * @param {number} value the number in question. - * @return {Timestamp} the corresponding Timestamp value. - */ -Timestamp.fromNumber = function(value) { - if (isNaN(value) || !isFinite(value)) { - return Timestamp.ZERO; - } else if (value <= -Timestamp.TWO_PWR_63_DBL_) { - return Timestamp.MIN_VALUE; - } else if (value + 1 >= Timestamp.TWO_PWR_63_DBL_) { - return Timestamp.MAX_VALUE; - } else if (value < 0) { - return Timestamp.fromNumber(-value).negate(); - } else { - return new Timestamp( - (value % Timestamp.TWO_PWR_32_DBL_) | 0, - (value / Timestamp.TWO_PWR_32_DBL_) | 0 - ); - } -}; - -/** - * Returns a Timestamp representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. - * - * @method - * @param {number} lowBits the low 32-bits. - * @param {number} highBits the high 32-bits. - * @return {Timestamp} the corresponding Timestamp value. - */ -Timestamp.fromBits = function(lowBits, highBits) { - return new Timestamp(lowBits, highBits); -}; - -/** - * Returns a Timestamp representation of the given string, written using the given radix. - * - * @method - * @param {string} str the textual representation of the Timestamp. - * @param {number} opt_radix the radix in which the text is written. - * @return {Timestamp} the corresponding Timestamp value. - */ -Timestamp.fromString = function(str, opt_radix) { - if (str.length === 0) { - throw Error('number format error: empty string'); - } - - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (str.charAt(0) === '-') { - return Timestamp.fromString(str.substring(1), radix).negate(); - } else if (str.indexOf('-') >= 0) { - throw Error('number format error: interior "-" character: ' + str); - } - - // Do several (8) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Timestamp.fromNumber(Math.pow(radix, 8)); - - var result = Timestamp.ZERO; - for (var i = 0; i < str.length; i += 8) { - var size = Math.min(8, str.length - i); - var value = parseInt(str.substring(i, i + size), radix); - if (size < 8) { - var power = Timestamp.fromNumber(Math.pow(radix, size)); - result = result.multiply(power).add(Timestamp.fromNumber(value)); - } else { - result = result.multiply(radixToPower); - result = result.add(Timestamp.fromNumber(value)); - } - } - return result; -}; - -// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the -// from* methods on which they depend. - -/** - * A cache of the Timestamp representations of small integer values. - * @type {Object} - * @ignore - */ -Timestamp.INT_CACHE_ = {}; - -// NOTE: the compiler should inline these constant values below and then remove -// these variables, so there should be no runtime penalty for these. - -/** - * Number used repeated below in calculations. This must appear before the - * first call to any from* function below. - * @type {number} - * @ignore - */ -Timestamp.TWO_PWR_16_DBL_ = 1 << 16; - -/** - * @type {number} - * @ignore - */ -Timestamp.TWO_PWR_24_DBL_ = 1 << 24; - -/** - * @type {number} - * @ignore - */ -Timestamp.TWO_PWR_32_DBL_ = Timestamp.TWO_PWR_16_DBL_ * Timestamp.TWO_PWR_16_DBL_; - -/** - * @type {number} - * @ignore - */ -Timestamp.TWO_PWR_31_DBL_ = Timestamp.TWO_PWR_32_DBL_ / 2; - -/** - * @type {number} - * @ignore - */ -Timestamp.TWO_PWR_48_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_16_DBL_; - -/** - * @type {number} - * @ignore - */ -Timestamp.TWO_PWR_64_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_32_DBL_; - -/** - * @type {number} - * @ignore - */ -Timestamp.TWO_PWR_63_DBL_ = Timestamp.TWO_PWR_64_DBL_ / 2; - -/** @type {Timestamp} */ -Timestamp.ZERO = Timestamp.fromInt(0); - -/** @type {Timestamp} */ -Timestamp.ONE = Timestamp.fromInt(1); - -/** @type {Timestamp} */ -Timestamp.NEG_ONE = Timestamp.fromInt(-1); - -/** @type {Timestamp} */ -Timestamp.MAX_VALUE = Timestamp.fromBits(0xffffffff | 0, 0x7fffffff | 0); - -/** @type {Timestamp} */ -Timestamp.MIN_VALUE = Timestamp.fromBits(0, 0x80000000 | 0); - -/** - * @type {Timestamp} - * @ignore - */ -Timestamp.TWO_PWR_24_ = Timestamp.fromInt(1 << 24); - -/** - * Expose. - */ -module.exports = Timestamp; -module.exports.Timestamp = Timestamp; diff --git a/scripts/node_modules/bson/package.json b/scripts/node_modules/bson/package.json deleted file mode 100644 index d37778ab..00000000 --- a/scripts/node_modules/bson/package.json +++ /dev/null @@ -1,87 +0,0 @@ -{ - "_from": "bson@^1.1.1", - "_id": "bson@1.1.1", - "_inBundle": false, - "_integrity": "sha512-jCGVYLoYMHDkOsbwJZBCqwMHyH4c+wzgI9hG7Z6SZJRXWr+x58pdIbm2i9a/jFGCkRJqRUr8eoI7lDWa0hTkxg==", - "_location": "/bson", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "bson@^1.1.1", - "name": "bson", - "escapedName": "bson", - "rawSpec": "^1.1.1", - "saveSpec": null, - "fetchSpec": "^1.1.1" - }, - "_requiredBy": [ - "/mongodb" - ], - "_resolved": "https://registry.npmjs.org/bson/-/bson-1.1.1.tgz", - "_shasum": "4330f5e99104c4e751e7351859e2d408279f2f13", - "_spec": "bson@^1.1.1", - "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/node_modules/mongodb", - "author": { - "name": "Christian Amor Kvalheim", - "email": "christkv@gmail.com" - }, - "browser": "lib/bson/bson.js", - "bugs": { - "url": "https://github.com/mongodb/js-bson/issues" - }, - "bundleDependencies": false, - "config": { - "native": false - }, - "contributors": [], - "deprecated": false, - "description": "A bson parser for node.js and the browser", - "devDependencies": { - "babel-core": "^6.14.0", - "babel-loader": "^6.2.5", - "babel-polyfill": "^6.13.0", - "babel-preset-es2015": "^6.14.0", - "babel-preset-stage-0": "^6.5.0", - "babel-register": "^6.14.0", - "benchmark": "1.0.0", - "colors": "1.1.0", - "conventional-changelog-cli": "^1.3.5", - "nodeunit": "0.9.0", - "webpack": "^1.13.2", - "webpack-polyfills-plugin": "0.0.9" - }, - "directories": { - "lib": "./lib/bson" - }, - "engines": { - "node": ">=0.6.19" - }, - "files": [ - "lib", - "index.js", - "browser_build", - "bower.json" - ], - "homepage": "https://github.com/mongodb/js-bson#readme", - "keywords": [ - "mongodb", - "bson", - "parser" - ], - "license": "Apache-2.0", - "main": "./index", - "name": "bson", - "repository": { - "type": "git", - "url": "git+https://github.com/mongodb/js-bson.git" - }, - "scripts": { - "build": "webpack --config ./webpack.dist.config.js", - "changelog": "conventional-changelog -p angular -i HISTORY.md -s", - "format": "prettier --print-width 100 --tab-width 2 --single-quote --write 'test/**/*.js' 'lib/**/*.js'", - "lint": "eslint lib test", - "test": "nodeunit ./test/node" - }, - "version": "1.1.1" -} diff --git a/scripts/node_modules/memory-pager/.travis.yml b/scripts/node_modules/memory-pager/.travis.yml deleted file mode 100644 index 1c4ab31e..00000000 --- a/scripts/node_modules/memory-pager/.travis.yml +++ /dev/null @@ -1,4 +0,0 @@ -language: node_js -node_js: - - '4' - - '6' diff --git a/scripts/node_modules/memory-pager/LICENSE b/scripts/node_modules/memory-pager/LICENSE deleted file mode 100644 index 56fce089..00000000 --- a/scripts/node_modules/memory-pager/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2017 Mathias Buus - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/scripts/node_modules/memory-pager/README.md b/scripts/node_modules/memory-pager/README.md deleted file mode 100644 index aed17614..00000000 --- a/scripts/node_modules/memory-pager/README.md +++ /dev/null @@ -1,65 +0,0 @@ -# memory-pager - -Access memory using small fixed sized buffers instead of allocating a huge buffer. -Useful if you are implementing sparse data structures (such as large bitfield). - -![travis](https://travis-ci.org/mafintosh/memory-pager.svg?branch=master) - -``` -npm install memory-pager -``` - -## Usage - -``` js -var pager = require('paged-memory') - -var pages = pager(1024) // use 1kb per page - -var page = pages.get(10) // get page #10 - -console.log(page.offset) // 10240 -console.log(page.buffer) // a blank 1kb buffer -``` - -## API - -#### `var pages = pager(pageSize)` - -Create a new pager. `pageSize` defaults to `1024`. - -#### `var page = pages.get(pageNumber, [noAllocate])` - -Get a page. The page will be allocated at first access. - -Optionally you can set the `noAllocate` flag which will make the -method return undefined if no page has been allocated already - -A page looks like this - -``` js -{ - offset: byteOffset, - buffer: bufferWithPageSize -} -``` - -#### `pages.set(pageNumber, buffer)` - -Explicitly set the buffer for a page. - -#### `pages.updated(page)` - -Mark a page as updated. - -#### `pages.lastUpdate()` - -Get the last page that was updated. - -#### `var buf = pages.toBuffer()` - -Concat all pages allocated pages into a single buffer - -## License - -MIT diff --git a/scripts/node_modules/memory-pager/index.js b/scripts/node_modules/memory-pager/index.js deleted file mode 100644 index 687f346f..00000000 --- a/scripts/node_modules/memory-pager/index.js +++ /dev/null @@ -1,160 +0,0 @@ -module.exports = Pager - -function Pager (pageSize, opts) { - if (!(this instanceof Pager)) return new Pager(pageSize, opts) - - this.length = 0 - this.updates = [] - this.path = new Uint16Array(4) - this.pages = new Array(32768) - this.maxPages = this.pages.length - this.level = 0 - this.pageSize = pageSize || 1024 - this.deduplicate = opts ? opts.deduplicate : null - this.zeros = this.deduplicate ? alloc(this.deduplicate.length) : null -} - -Pager.prototype.updated = function (page) { - while (this.deduplicate && page.buffer[page.deduplicate] === this.deduplicate[page.deduplicate]) { - page.deduplicate++ - if (page.deduplicate === this.deduplicate.length) { - page.deduplicate = 0 - if (page.buffer.equals && page.buffer.equals(this.deduplicate)) page.buffer = this.deduplicate - break - } - } - if (page.updated || !this.updates) return - page.updated = true - this.updates.push(page) -} - -Pager.prototype.lastUpdate = function () { - if (!this.updates || !this.updates.length) return null - var page = this.updates.pop() - page.updated = false - return page -} - -Pager.prototype._array = function (i, noAllocate) { - if (i >= this.maxPages) { - if (noAllocate) return - grow(this, i) - } - - factor(i, this.path) - - var arr = this.pages - - for (var j = this.level; j > 0; j--) { - var p = this.path[j] - var next = arr[p] - - if (!next) { - if (noAllocate) return - next = arr[p] = new Array(32768) - } - - arr = next - } - - return arr -} - -Pager.prototype.get = function (i, noAllocate) { - var arr = this._array(i, noAllocate) - var first = this.path[0] - var page = arr && arr[first] - - if (!page && !noAllocate) { - page = arr[first] = new Page(i, alloc(this.pageSize)) - if (i >= this.length) this.length = i + 1 - } - - if (page && page.buffer === this.deduplicate && this.deduplicate && !noAllocate) { - page.buffer = copy(page.buffer) - page.deduplicate = 0 - } - - return page -} - -Pager.prototype.set = function (i, buf) { - var arr = this._array(i, false) - var first = this.path[0] - - if (i >= this.length) this.length = i + 1 - - if (!buf || (this.zeros && buf.equals && buf.equals(this.zeros))) { - arr[first] = undefined - return - } - - if (this.deduplicate && buf.equals && buf.equals(this.deduplicate)) { - buf = this.deduplicate - } - - var page = arr[first] - var b = truncate(buf, this.pageSize) - - if (page) page.buffer = b - else arr[first] = new Page(i, b) -} - -Pager.prototype.toBuffer = function () { - var list = new Array(this.length) - var empty = alloc(this.pageSize) - var ptr = 0 - - while (ptr < list.length) { - var arr = this._array(ptr, true) - for (var i = 0; i < 32768 && ptr < list.length; i++) { - list[ptr++] = (arr && arr[i]) ? arr[i].buffer : empty - } - } - - return Buffer.concat(list) -} - -function grow (pager, index) { - while (pager.maxPages < index) { - var old = pager.pages - pager.pages = new Array(32768) - pager.pages[0] = old - pager.level++ - pager.maxPages *= 32768 - } -} - -function truncate (buf, len) { - if (buf.length === len) return buf - if (buf.length > len) return buf.slice(0, len) - var cpy = alloc(len) - buf.copy(cpy) - return cpy -} - -function alloc (size) { - if (Buffer.alloc) return Buffer.alloc(size) - var buf = new Buffer(size) - buf.fill(0) - return buf -} - -function copy (buf) { - var cpy = Buffer.allocUnsafe ? Buffer.allocUnsafe(buf.length) : new Buffer(buf.length) - buf.copy(cpy) - return cpy -} - -function Page (i, buf) { - this.offset = i * buf.length - this.buffer = buf - this.updated = false - this.deduplicate = 0 -} - -function factor (n, out) { - n = (n - (out[0] = (n & 32767))) / 32768 - n = (n - (out[1] = (n & 32767))) / 32768 - out[3] = ((n - (out[2] = (n & 32767))) / 32768) & 32767 -} diff --git a/scripts/node_modules/memory-pager/package.json b/scripts/node_modules/memory-pager/package.json deleted file mode 100644 index 4d426e44..00000000 --- a/scripts/node_modules/memory-pager/package.json +++ /dev/null @@ -1,52 +0,0 @@ -{ - "_from": "memory-pager@^1.0.2", - "_id": "memory-pager@1.5.0", - "_inBundle": false, - "_integrity": "sha512-ZS4Bp4r/Zoeq6+NLJpP+0Zzm0pR8whtGPf1XExKLJBAczGMnSi3It14OiNCStjQjM6NU1okjQGSxgEZN8eBYKg==", - "_location": "/memory-pager", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "memory-pager@^1.0.2", - "name": "memory-pager", - "escapedName": "memory-pager", - "rawSpec": "^1.0.2", - "saveSpec": null, - "fetchSpec": "^1.0.2" - }, - "_requiredBy": [ - "/sparse-bitfield" - ], - "_resolved": "https://registry.npmjs.org/memory-pager/-/memory-pager-1.5.0.tgz", - "_shasum": "d8751655d22d384682741c972f2c3d6dfa3e66b5", - "_spec": "memory-pager@^1.0.2", - "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/node_modules/sparse-bitfield", - "author": { - "name": "Mathias Buus", - "url": "@mafintosh" - }, - "bugs": { - "url": "https://github.com/mafintosh/memory-pager/issues" - }, - "bundleDependencies": false, - "dependencies": {}, - "deprecated": false, - "description": "Access memory using small fixed sized buffers", - "devDependencies": { - "standard": "^9.0.0", - "tape": "^4.6.3" - }, - "homepage": "https://github.com/mafintosh/memory-pager", - "license": "MIT", - "main": "index.js", - "name": "memory-pager", - "repository": { - "type": "git", - "url": "git+https://github.com/mafintosh/memory-pager.git" - }, - "scripts": { - "test": "standard && tape test.js" - }, - "version": "1.5.0" -} diff --git a/scripts/node_modules/memory-pager/test.js b/scripts/node_modules/memory-pager/test.js deleted file mode 100644 index 16382100..00000000 --- a/scripts/node_modules/memory-pager/test.js +++ /dev/null @@ -1,80 +0,0 @@ -var tape = require('tape') -var pager = require('./') - -tape('get page', function (t) { - var pages = pager(1024) - - var page = pages.get(0) - - t.same(page.offset, 0) - t.same(page.buffer, Buffer.alloc(1024)) - t.end() -}) - -tape('get page twice', function (t) { - var pages = pager(1024) - t.same(pages.length, 0) - - var page = pages.get(0) - - t.same(page.offset, 0) - t.same(page.buffer, Buffer.alloc(1024)) - t.same(pages.length, 1) - - var other = pages.get(0) - - t.same(other, page) - t.end() -}) - -tape('get no mutable page', function (t) { - var pages = pager(1024) - - t.ok(!pages.get(141, true)) - t.ok(pages.get(141)) - t.ok(pages.get(141, true)) - - t.end() -}) - -tape('get far out page', function (t) { - var pages = pager(1024) - - var page = pages.get(1000000) - - t.same(page.offset, 1000000 * 1024) - t.same(page.buffer, Buffer.alloc(1024)) - t.same(pages.length, 1000000 + 1) - - var other = pages.get(1) - - t.same(other.offset, 1024) - t.same(other.buffer, Buffer.alloc(1024)) - t.same(pages.length, 1000000 + 1) - t.ok(other !== page) - - t.end() -}) - -tape('updates', function (t) { - var pages = pager(1024) - - t.same(pages.lastUpdate(), null) - - var page = pages.get(10) - - page.buffer[42] = 1 - pages.updated(page) - - t.same(pages.lastUpdate(), page) - t.same(pages.lastUpdate(), null) - - page.buffer[42] = 2 - pages.updated(page) - pages.updated(page) - - t.same(pages.lastUpdate(), page) - t.same(pages.lastUpdate(), null) - - t.end() -}) diff --git a/scripts/node_modules/mongodb/HISTORY.md b/scripts/node_modules/mongodb/HISTORY.md deleted file mode 100644 index 73cbab99..00000000 --- a/scripts/node_modules/mongodb/HISTORY.md +++ /dev/null @@ -1,2485 +0,0 @@ -# Change Log - -All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. - - -## [3.3.3](https://github.com/mongodb/node-mongodb-native/compare/v3.3.2...v3.3.3) (2019-10-16) - - -### Bug Fixes - -* **change_stream:** emit 'close' event if reconnecting failed ([f24c084](https://github.com/mongodb/node-mongodb-native/commit/f24c084)) -* **ChangeStream:** remove startAtOperationTime once we have resumeToken ([362afd8](https://github.com/mongodb/node-mongodb-native/commit/362afd8)) -* **connect:** Switch new Buffer(size) -> Buffer.alloc(size) ([da90c3a](https://github.com/mongodb/node-mongodb-native/commit/da90c3a)) -* **MongoClient:** only check own properties for valid options ([9cde4b9](https://github.com/mongodb/node-mongodb-native/commit/9cde4b9)) -* **mongos:** disconnect proxies which are not mongos instances ([ee53983](https://github.com/mongodb/node-mongodb-native/commit/ee53983)) -* **mongos:** force close servers during reconnect flow ([186263f](https://github.com/mongodb/node-mongodb-native/commit/186263f)) -* **monitoring:** correct spelling mistake for heartbeat event ([21aa117](https://github.com/mongodb/node-mongodb-native/commit/21aa117)) -* **replset:** correct server leak on initial connect ([da39d1e](https://github.com/mongodb/node-mongodb-native/commit/da39d1e)) -* **replset:** destroy primary before removing from replsetstate ([45ac09a](https://github.com/mongodb/node-mongodb-native/commit/45ac09a)) -* **replset:** destroy servers that are removed during SDAM flow ([9ea0190](https://github.com/mongodb/node-mongodb-native/commit/9ea0190)) -* **saslprep:** add in missing saslprep dependency ([41f1165](https://github.com/mongodb/node-mongodb-native/commit/41f1165)) -* **topology:** don't early abort server selection on network errors ([2b6a359](https://github.com/mongodb/node-mongodb-native/commit/2b6a359)) -* **topology:** don't emit server closed event on network error ([194dcf0](https://github.com/mongodb/node-mongodb-native/commit/194dcf0)) -* **topology:** include all BSON types in ctor for bson-ext support ([aa4c832](https://github.com/mongodb/node-mongodb-native/commit/aa4c832)) -* **topology:** respect the `force` parameter for topology close ([d6e8936](https://github.com/mongodb/node-mongodb-native/commit/d6e8936)) - -### Features - -* **Update:** add the ability to specify a pipeline to an update command ([#2017](https://github.com/mongodb/node-mongodb-native/issues/2017)) ([44a4110](https://github.com/mongodb/node-mongodb-native/commit/44a4110)) -* **urlParser:** default useNewUrlParser to true ([52d76e3](https://github.com/mongodb/node-mongodb-native/commit/52d76e3)) - - -## [3.2.7](https://github.com/mongodb/node-mongodb-native/compare/v3.2.6...v3.2.7) (2019-06-04) - - -### Bug Fixes - -* **core:** updating core to version 3.2.7 ([2f91466](https://github.com/mongodb/node-mongodb-native/commit/2f91466)) -* **findOneAndReplace:** throw error if atomic operators provided for findOneAndReplace ([6a860a3](https://github.com/mongodb/node-mongodb-native/commit/6a860a3)) - - - - -## [3.3.2](https://github.com/mongodb/node-mongodb-native/compare/v3.3.1...v3.3.2) (2019-08-28) - - -### Bug Fixes - -* **change-stream:** default to server default batch size ([b3ae4c5](https://github.com/mongodb/node-mongodb-native/commit/b3ae4c5)) -* **execute-operation:** return promise on session support check ([a976c14](https://github.com/mongodb/node-mongodb-native/commit/a976c14)) -* **gridfs-stream:** ensure `close` is emitted after last chunk ([ae94cb9](https://github.com/mongodb/node-mongodb-native/commit/ae94cb9)) - - - - -## [3.3.1](https://github.com/mongodb/node-mongodb-native/compare/v3.3.0...v3.3.1) (2019-08-23) - - -### Bug Fixes - -* **find:** respect client-level provided read preference ([fec4f15](https://github.com/mongodb/node-mongodb-native/commit/fec4f15)) -* correct inverted defaults for unified topology ([cf598e1](https://github.com/mongodb/node-mongodb-native/commit/cf598e1)) - - - - -# [3.3.0](https://github.com/mongodb/node-mongodb-native/compare/v3.3.0-alpha1...v3.3.0) (2019-08-13) - - -### Bug Fixes - -* **aggregate-operation:** move type assertions to constructor ([25b27ff](https://github.com/mongodb/node-mongodb-native/commit/25b27ff)) -* **autoEncryption:** tear down mongocryptd client when main client closes ([fe2f57e](https://github.com/mongodb/node-mongodb-native/commit/fe2f57e)) -* **autoEncryption:** use new url parser for autoEncryption client ([d3670c2](https://github.com/mongodb/node-mongodb-native/commit/d3670c2)) -* **Bulk:** change BulkWriteError message to first item from writeErrors ([#2013](https://github.com/mongodb/node-mongodb-native/issues/2013)) ([6bcf1e4](https://github.com/mongodb/node-mongodb-native/commit/6bcf1e4)) -* **change_stream:** emit 'close' event if reconnecting failed ([41aba90](https://github.com/mongodb/node-mongodb-native/commit/41aba90)) -* **change_stream:** emit close event after cursor is closed during error ([c2d80b2](https://github.com/mongodb/node-mongodb-native/commit/c2d80b2)) -* **change-streams:** don't copy irrelevant resume options ([f190072](https://github.com/mongodb/node-mongodb-native/commit/f190072)) -* **changestream:** removes all event listeners on close ([30eeeb5](https://github.com/mongodb/node-mongodb-native/commit/30eeeb5)) -* **ChangeStream:** remove startAtOperationTime once we have resumeToken ([8d27e6e](https://github.com/mongodb/node-mongodb-native/commit/8d27e6e)) -* **ClientSessions:** initialize clientOptions and cluster time ([b95d64e](https://github.com/mongodb/node-mongodb-native/commit/b95d64e)) -* **connect:** don't treat 'connect' as an error event ([170a011](https://github.com/mongodb/node-mongodb-native/commit/170a011)) -* **connect:** fixed syntax issue in connect error handler ([ff7166d](https://github.com/mongodb/node-mongodb-native/commit/ff7166d)) -* **connections_stepdown_tests:** use correct version of mongo for tests ([ce2c9af](https://github.com/mongodb/node-mongodb-native/commit/ce2c9af)) -* **createCollection:** Db.createCollection should pass readConcern to new collection ([#2026](https://github.com/mongodb/node-mongodb-native/issues/2026)) ([6145d4b](https://github.com/mongodb/node-mongodb-native/commit/6145d4b)) -* **cursor:** do not truncate an existing Long ([317055b](https://github.com/mongodb/node-mongodb-native/commit/317055b)), closes [mongodb-js/mongodb-core#441](https://github.com/mongodb-js/mongodb-core/issues/441) -* **distinct:** return full response if `full` option was specified ([95a7d05](https://github.com/mongodb/node-mongodb-native/commit/95a7d05)) -* **MongoClient:** allow Object.prototype items as db names ([dc6fc37](https://github.com/mongodb/node-mongodb-native/commit/dc6fc37)) -* **MongoClient:** only check own properties for valid options ([c9dc717](https://github.com/mongodb/node-mongodb-native/commit/c9dc717)) -* **OpMsg:** cap requestIds at 0x7fffffff ([c0e87d5](https://github.com/mongodb/node-mongodb-native/commit/c0e87d5)) -* **read-operations:** send sessions on all read operations ([4d45c8a](https://github.com/mongodb/node-mongodb-native/commit/4d45c8a)) -* **ReadPreference:** improve ReadPreference error message and remove irrelevant sharding test ([dd34ce4](https://github.com/mongodb/node-mongodb-native/commit/dd34ce4)) -* **ReadPreference:** only allow valid ReadPreference modes ([06bbef2](https://github.com/mongodb/node-mongodb-native/commit/06bbef2)) -* **replset:** correct legacy max staleness calculation ([2eab8aa](https://github.com/mongodb/node-mongodb-native/commit/2eab8aa)) -* **replset:** introduce a fixed-time server selection loop ([cf53299](https://github.com/mongodb/node-mongodb-native/commit/cf53299)) -* **server:** emit "first connect" error if initial connect fails due to ECONNREFUSED ([#2016](https://github.com/mongodb/node-mongodb-native/issues/2016)) ([5a7b15b](https://github.com/mongodb/node-mongodb-native/commit/5a7b15b)) -* **serverSelection:** make sure to pass session to serverSelection ([eb5cc6b](https://github.com/mongodb/node-mongodb-native/commit/eb5cc6b)) -* **sessions:** ensure an error is thrown when attempting sharded transactions ([3a1fdc1](https://github.com/mongodb/node-mongodb-native/commit/3a1fdc1)) -* **topology:** add new error for retryWrites on MMAPv1 ([392f5a6](https://github.com/mongodb/node-mongodb-native/commit/392f5a6)) -* don't check non-unified topologies for session support check ([2bccd3f](https://github.com/mongodb/node-mongodb-native/commit/2bccd3f)) -* maintain internal database name on collection rename ([884d46f](https://github.com/mongodb/node-mongodb-native/commit/884d46f)) -* only check for transaction state if session exists ([360975a](https://github.com/mongodb/node-mongodb-native/commit/360975a)) -* preserve aggregate explain support for legacy servers ([032b204](https://github.com/mongodb/node-mongodb-native/commit/032b204)) -* read concern only supported for `mapReduce` without inline ([51a36f3](https://github.com/mongodb/node-mongodb-native/commit/51a36f3)) -* reintroduce support for 2.6 listIndexes ([c3bfc05](https://github.com/mongodb/node-mongodb-native/commit/c3bfc05)) -* return `executeOperation` for explain, if promise is desired ([b4a7ad7](https://github.com/mongodb/node-mongodb-native/commit/b4a7ad7)) -* validate atomic operations in all update methods ([88bb77e](https://github.com/mongodb/node-mongodb-native/commit/88bb77e)) -* **transactions:** fix error message for attempting sharded ([eb5dfc9](https://github.com/mongodb/node-mongodb-native/commit/eb5dfc9)) -* **transactions:** fix sharded transaction error logic ([083e18a](https://github.com/mongodb/node-mongodb-native/commit/083e18a)) - - -### Features - -* **Aggregate:** support ReadConcern in aggregates with $out ([21cdcf0](https://github.com/mongodb/node-mongodb-native/commit/21cdcf0)) -* **AutoEncryption:** improve error message for missing mongodb-client-encryption ([583f29f](https://github.com/mongodb/node-mongodb-native/commit/583f29f)) -* **ChangeStream:** adds new resume functionality to ChangeStreams ([9ec9b8f](https://github.com/mongodb/node-mongodb-native/commit/9ec9b8f)) -* **ChangeStreamCursor:** introduce new cursor type for change streams ([8813eb0](https://github.com/mongodb/node-mongodb-native/commit/8813eb0)) -* **cryptdConnectionString:** makes mongocryptd uri configurable ([#2049](https://github.com/mongodb/node-mongodb-native/issues/2049)) ([a487be4](https://github.com/mongodb/node-mongodb-native/commit/a487be4)) -* **eachAsync:** dedupe async iteration with a common helper ([c296f3a](https://github.com/mongodb/node-mongodb-native/commit/c296f3a)) -* **execute-operation:** allow execution with server selection ([36bc1fd](https://github.com/mongodb/node-mongodb-native/commit/36bc1fd)) -* **pool:** add support for resetting the connection pool ([2d1ff40](https://github.com/mongodb/node-mongodb-native/commit/2d1ff40)) -* **sessions:** track dirty state of sessions, drop after use ([f61df16](https://github.com/mongodb/node-mongodb-native/commit/f61df16)) -* add concept of `data-bearing` type to `ServerDescription` ([852e14f](https://github.com/mongodb/node-mongodb-native/commit/852e14f)) -* **transaction:** allow applications to set maxTimeMS for commitTransaction ([b3948aa](https://github.com/mongodb/node-mongodb-native/commit/b3948aa)) -* **Update:** add the ability to specify a pipeline to an update command ([#2017](https://github.com/mongodb/node-mongodb-native/issues/2017)) ([dc1387e](https://github.com/mongodb/node-mongodb-native/commit/dc1387e)) -* add `known`, `data-bearing` filters to `TopologyDescription` ([d0ccb56](https://github.com/mongodb/node-mongodb-native/commit/d0ccb56)) -* perform selection before cursor operation execution if needed ([808cf37](https://github.com/mongodb/node-mongodb-native/commit/808cf37)) -* perform selection before operation execution if needed ([1a25876](https://github.com/mongodb/node-mongodb-native/commit/1a25876)) -* support explain operations in `CommandOperationV2` ([86f5ba5](https://github.com/mongodb/node-mongodb-native/commit/86f5ba5)) -* support operations passed to a `Cursor` or subclass ([b78bb89](https://github.com/mongodb/node-mongodb-native/commit/b78bb89)) - - - - -## [3.2.7](https://github.com/mongodb/node-mongodb-native/compare/v3.2.6...v3.2.7) (2019-06-04) - - -### Bug Fixes - -* **core:** updating core to version 3.2.7 ([2f91466](https://github.com/mongodb/node-mongodb-native/commit/2f91466)) -* **findOneAndReplace:** throw error if atomic operators provided for findOneAndReplace ([6a860a3](https://github.com/mongodb/node-mongodb-native/commit/6a860a3)) - - - - -## [3.2.6](https://github.com/mongodb/node-mongodb-native/compare/v3.2.5...v3.2.6) (2019-05-24) - - - - -## [3.2.5](https://github.com/mongodb/node-mongodb-native/compare/v3.2.4...v3.2.5) (2019-05-17) - - -### Bug Fixes - -* **core:** updating core to 3.2.5 ([a2766c1](https://github.com/mongodb/node-mongodb-native/commit/a2766c1)) - - - - -## [3.2.4](https://github.com/mongodb/node-mongodb-native/compare/v3.2.2...v3.2.4) (2019-05-08) - - -### Bug Fixes - -* **aggregation:** fix field name typo ([4235d04](https://github.com/mongodb/node-mongodb-native/commit/4235d04)) -* **async:** rewrote asyncGenerator in node < 10 syntax ([49c8cef](https://github.com/mongodb/node-mongodb-native/commit/49c8cef)) -* **BulkOp:** run unordered bulk ops in serial ([f548bd7](https://github.com/mongodb/node-mongodb-native/commit/f548bd7)) -* **bulkWrite:** fix issue with bulkWrite continuing w/ callback ([2a4a42c](https://github.com/mongodb/node-mongodb-native/commit/2a4a42c)) -* **docs:** correctly document that default for `sslValidate` is false ([1f8e7fa](https://github.com/mongodb/node-mongodb-native/commit/1f8e7fa)) -* **gridfs-stream:** honor chunk size ([9eeb114](https://github.com/mongodb/node-mongodb-native/commit/9eeb114)) -* **unified-topology:** only clone pool size if provided ([8dc2416](https://github.com/mongodb/node-mongodb-native/commit/8dc2416)) - - -### Features - -* update to mongodb-core v3.2.3 ([1c5357a](https://github.com/mongodb/node-mongodb-native/commit/1c5357a)) -* **core:** update to mongodb-core v3.2.4 ([2059260](https://github.com/mongodb/node-mongodb-native/commit/2059260)) -* **lib:** implement executeOperationV2 ([67d4edf](https://github.com/mongodb/node-mongodb-native/commit/67d4edf)) - - - - -## [3.2.3](https://github.com/mongodb/node-mongodb-native/compare/v3.2.2...v3.2.3) (2019-04-05) - - -### Bug Fixes - -* **aggregation:** fix field name typo ([4235d04](https://github.com/mongodb/node-mongodb-native/commit/4235d04)) -* **async:** rewrote asyncGenerator in node < 10 syntax ([49c8cef](https://github.com/mongodb/node-mongodb-native/commit/49c8cef)) -* **bulkWrite:** fix issue with bulkWrite continuing w/ callback ([2a4a42c](https://github.com/mongodb/node-mongodb-native/commit/2a4a42c)) -* **docs:** correctly document that default for `sslValidate` is false ([1f8e7fa](https://github.com/mongodb/node-mongodb-native/commit/1f8e7fa)) - - -### Features - -* update to mongodb-core v3.2.3 ([1c5357a](https://github.com/mongodb/node-mongodb-native/commit/1c5357a)) - - - - -## [3.2.2](https://github.com/mongodb/node-mongodb-native/compare/v3.2.1...v3.2.2) (2019-03-22) - - -### Bug Fixes - -* **asyncIterator:** stronger guard against importing async generator ([e0826fb](https://github.com/mongodb/node-mongodb-native/commit/e0826fb)) - - -### Features - -* update to mongodb-core v3.2.2 ([868cfc3](https://github.com/mongodb/node-mongodb-native/commit/868cfc3)) - - - - -## [3.2.1](https://github.com/mongodb/node-mongodb-native/compare/v3.2.0...v3.2.1) (2019-03-21) - - -### Features - -* **core:** update to mongodb-core v3.2.1 ([30b0100](https://github.com/mongodb/node-mongodb-native/commit/30b0100)) - - - - -# [3.2.0](https://github.com/mongodb/node-mongodb-native/compare/v3.1.13...v3.2.0) (2019-03-21) - - -### Bug Fixes - -* **aggregate:** do not send batchSize for aggregation with $out ([ddb8d90](https://github.com/mongodb/node-mongodb-native/commit/ddb8d90)) -* **bulkWrite:** always count undefined values in bson size for bulk ([436d340](https://github.com/mongodb/node-mongodb-native/commit/436d340)) -* **db_ops:** rename db to add user on ([79931af](https://github.com/mongodb/node-mongodb-native/commit/79931af)) -* **mongo_client_ops:** only skip authentication if no authMechanism is specified ([3b6957d](https://github.com/mongodb/node-mongodb-native/commit/3b6957d)) -* **mongo-client:** ensure close callback is called with client ([f39e881](https://github.com/mongodb/node-mongodb-native/commit/f39e881)) - - -### Features - -* **core:** pin to mongodb-core v3.2.0 ([22af15a](https://github.com/mongodb/node-mongodb-native/commit/22af15a)) -* **Cursor:** adds support for AsyncIterator in cursors ([b972c1e](https://github.com/mongodb/node-mongodb-native/commit/b972c1e)) -* **db:** add database-level aggregation ([b629b21](https://github.com/mongodb/node-mongodb-native/commit/b629b21)) -* **mongo-client:** remove deprecated `logout` and print warning ([542859d](https://github.com/mongodb/node-mongodb-native/commit/542859d)) -* **topology-base:** support passing callbacks to `close` method ([7c111e0](https://github.com/mongodb/node-mongodb-native/commit/7c111e0)) -* **transactions:** support pinning mongos for sharded txns ([3886127](https://github.com/mongodb/node-mongodb-native/commit/3886127)) -* **unified-sdam:** backport unified SDAM to master for v3.2.0 ([79f33ca](https://github.com/mongodb/node-mongodb-native/commit/79f33ca)) - - - - -## [3.1.13](https://github.com/mongodb/node-mongodb-native/compare/v3.1.12...v3.1.13) (2019-01-23) - - -### Bug Fixes - -* restore ability to webpack by removing `makeLazyLoader` ([050267d](https://github.com/mongodb/node-mongodb-native/commit/050267d)) -* **bulk:** honor ignoreUndefined in initializeUnorderedBulkOp ([e806be4](https://github.com/mongodb/node-mongodb-native/commit/e806be4)) -* **changeStream:** properly handle changeStream event mid-close ([#1902](https://github.com/mongodb/node-mongodb-native/issues/1902)) ([5ad9fa9](https://github.com/mongodb/node-mongodb-native/commit/5ad9fa9)) -* **db_ops:** ensure we async resolve errors in createCollection ([210c71d](https://github.com/mongodb/node-mongodb-native/commit/210c71d)) - - - - -## [3.1.12](https://github.com/mongodb/node-mongodb-native/compare/v3.1.11...v3.1.12) (2019-01-16) - - -### Features - -* **core:** update to mongodb-core v3.1.11 ([9bef6e7](https://github.com/mongodb/node-mongodb-native/commit/9bef6e7)) - - - - -## [3.1.11](https://github.com/mongodb/node-mongodb-native/compare/v3.1.10...v3.1.11) (2019-01-15) - - -### Bug Fixes - -* **bulk:** fix error propagation in empty bulk.execute ([a3adb3f](https://github.com/mongodb/node-mongodb-native/commit/a3adb3f)) -* **bulk:** make sure that any error in bulk write is propagated ([bedc2d2](https://github.com/mongodb/node-mongodb-native/commit/bedc2d2)) -* **bulk:** properly calculate batch size for bulk writes ([aafe71b](https://github.com/mongodb/node-mongodb-native/commit/aafe71b)) -* **operations:** do not call require in a hot path ([ff82ff4](https://github.com/mongodb/node-mongodb-native/commit/ff82ff4)) - - - - -## [3.1.10](https://github.com/mongodb/node-mongodb-native/compare/v3.1.9...v3.1.10) (2018-11-16) - - -### Bug Fixes - -* **auth:** remember to default to admin database ([c7dec28](https://github.com/mongodb/node-mongodb-native/commit/c7dec28)) - - -### Features - -* **core:** update to mongodb-core v3.1.9 ([bd3355b](https://github.com/mongodb/node-mongodb-native/commit/bd3355b)) - - - - -## [3.1.9](https://github.com/mongodb/node-mongodb-native/compare/v3.1.8...v3.1.9) (2018-11-06) - - -### Bug Fixes - -* **db:** move db constants to other file to avoid circular ref ([#1858](https://github.com/mongodb/node-mongodb-native/issues/1858)) ([239036f](https://github.com/mongodb/node-mongodb-native/commit/239036f)) -* **estimated-document-count:** support options other than maxTimeMs ([36c3c7d](https://github.com/mongodb/node-mongodb-native/commit/36c3c7d)) - - -### Features - -* **core:** update to mongodb-core v3.1.8 ([80d7c79](https://github.com/mongodb/node-mongodb-native/commit/80d7c79)) - - - - -## [3.1.8](https://github.com/mongodb/node-mongodb-native/compare/v3.1.7...v3.1.8) (2018-10-10) - - -### Bug Fixes - -* **connect:** use reported default databse from new uri parser ([811f8f8](https://github.com/mongodb/node-mongodb-native/commit/811f8f8)) - - -### Features - -* **core:** update to mongodb-core v3.1.7 ([dbfc905](https://github.com/mongodb/node-mongodb-native/commit/dbfc905)) - - - - -## [3.1.7](https://github.com/mongodb/node-mongodb-native/compare/v3.1.6...v3.1.7) (2018-10-09) - - -### Features - -* **core:** update mongodb-core to v3.1.6 ([61b054e](https://github.com/mongodb/node-mongodb-native/commit/61b054e)) - - - - -## [3.1.6](https://github.com/mongodb/node-mongodb-native/compare/v3.1.5...v3.1.6) (2018-09-15) - - -### Features - -* **core:** update to core v3.1.5 ([c5f823d](https://github.com/mongodb/node-mongodb-native/commit/c5f823d)) - - - - -## [3.1.5](https://github.com/mongodb/node-mongodb-native/compare/v3.1.4...v3.1.5) (2018-09-14) - - -### Bug Fixes - -* **cursor:** allow `$meta` based sort when passing an array to `sort()` ([f93a8c3](https://github.com/mongodb/node-mongodb-native/commit/f93a8c3)) -* **utils:** only set retryWrites to true for valid operations ([3b725ef](https://github.com/mongodb/node-mongodb-native/commit/3b725ef)) - - -### Features - -* **core:** bump core to v3.1.4 ([805d58a](https://github.com/mongodb/node-mongodb-native/commit/805d58a)) - - - - -## [3.1.4](https://github.com/mongodb/node-mongodb-native/compare/v3.1.3...v3.1.4) (2018-08-25) - - -### Bug Fixes - -* **buffer:** use safe-buffer polyfill to maintain compatibility ([327da95](https://github.com/mongodb/node-mongodb-native/commit/327da95)) -* **change-stream:** properly support resumablity in stream mode ([c43a34b](https://github.com/mongodb/node-mongodb-native/commit/c43a34b)) -* **connect:** correct replacement of topology on connect callback ([918a1e0](https://github.com/mongodb/node-mongodb-native/commit/918a1e0)) -* **cursor:** remove deprecated notice on forEach ([a474158](https://github.com/mongodb/node-mongodb-native/commit/a474158)) -* **url-parser:** bail early on validation when using domain socket ([3cb3da3](https://github.com/mongodb/node-mongodb-native/commit/3cb3da3)) - - -### Features - -* **client-ops:** allow bypassing creation of topologies on connect ([fe39b93](https://github.com/mongodb/node-mongodb-native/commit/fe39b93)) -* **core:** update mongodb-core to 3.1.3 ([a029047](https://github.com/mongodb/node-mongodb-native/commit/a029047)) -* **test:** use connection strings for all calls to `newClient` ([1dac18f](https://github.com/mongodb/node-mongodb-native/commit/1dac18f)) - - - - -## [3.1.3](https://github.com/mongodb/node-mongodb-native/compare/v3.1.2...v3.1.3) (2018-08-13) - - -### Features - -* **core:** update to mongodb-core 3.1.2 ([337cb79](https://github.com/mongodb/node-mongodb-native/commit/337cb79)) - - - - -## [3.1.2](https://github.com/mongodb/node-mongodb-native/compare/v3.0.6...v3.1.2) (2018-08-13) - - -### Bug Fixes - -* **aggregate:** support user-provided `batchSize` ([ad10dee](https://github.com/mongodb/node-mongodb-native/commit/ad10dee)) -* **buffer:** replace deprecated Buffer constructor ([759dd85](https://github.com/mongodb/node-mongodb-native/commit/759dd85)) -* **bulk:** fixing retryable writes for mass-change ops ([0604036](https://github.com/mongodb/node-mongodb-native/commit/0604036)) -* **bulk:** handle MongoWriteConcernErrors ([12ff392](https://github.com/mongodb/node-mongodb-native/commit/12ff392)) -* **change_stream:** do not check isGetMore if error[mongoErrorContextSymbol] is undefined ([#1720](https://github.com/mongodb/node-mongodb-native/issues/1720)) ([844c2c8](https://github.com/mongodb/node-mongodb-native/commit/844c2c8)) -* **change-stream:** fix change stream resuming with promises ([3063f00](https://github.com/mongodb/node-mongodb-native/commit/3063f00)) -* **client-ops:** return transform map to map rather than function ([cfb7d83](https://github.com/mongodb/node-mongodb-native/commit/cfb7d83)) -* **collection:** correctly shallow clone passed in options ([7727700](https://github.com/mongodb/node-mongodb-native/commit/7727700)) -* **collection:** countDocuments throws error when query doesn't match docs ([09c7d8e](https://github.com/mongodb/node-mongodb-native/commit/09c7d8e)) -* **collection:** depend on `resolveReadPreference` for inheritance ([a649e35](https://github.com/mongodb/node-mongodb-native/commit/a649e35)) -* **collection:** ensure findAndModify always use readPreference primary ([86344f4](https://github.com/mongodb/node-mongodb-native/commit/86344f4)) -* **collection:** isCapped returns false instead of undefined ([b8471f1](https://github.com/mongodb/node-mongodb-native/commit/b8471f1)) -* **collection:** only send bypassDocumentValidation if true ([fdb828b](https://github.com/mongodb/node-mongodb-native/commit/fdb828b)) -* **count-documents:** return callback on error case ([fca1185](https://github.com/mongodb/node-mongodb-native/commit/fca1185)) -* **cursor:** cursor count with collation fix ([71879c3](https://github.com/mongodb/node-mongodb-native/commit/71879c3)) -* **cursor:** cursor hasNext returns false when exhausted ([184b817](https://github.com/mongodb/node-mongodb-native/commit/184b817)) -* **cursor:** cursor.count not respecting parent readPreference ([5a9fdf0](https://github.com/mongodb/node-mongodb-native/commit/5a9fdf0)) -* **cursor:** set readPreference for cursor.count ([13d776f](https://github.com/mongodb/node-mongodb-native/commit/13d776f)) -* **db:** don't send session down to createIndex command ([559c195](https://github.com/mongodb/node-mongodb-native/commit/559c195)) -* **db:** throw readable error when creating `_id` with background: true ([b3ff3ed](https://github.com/mongodb/node-mongodb-native/commit/b3ff3ed)) -* **db_ops:** call collection.find() with correct parameters ([#1795](https://github.com/mongodb/node-mongodb-native/issues/1795)) ([36e92f1](https://github.com/mongodb/node-mongodb-native/commit/36e92f1)) -* **db_ops:** fix two incorrectly named variables ([15dc808](https://github.com/mongodb/node-mongodb-native/commit/15dc808)) -* **findOneAndUpdate:** ensure that update documents contain atomic operators ([eb68074](https://github.com/mongodb/node-mongodb-native/commit/eb68074)) -* **index:** export MongoNetworkError ([98ab29e](https://github.com/mongodb/node-mongodb-native/commit/98ab29e)) -* **mongo_client:** translate options for connectWithUrl ([78f6977](https://github.com/mongodb/node-mongodb-native/commit/78f6977)) -* **mongo-client:** pass arguments to ctor when new keyword is used ([d6c3417](https://github.com/mongodb/node-mongodb-native/commit/d6c3417)) -* **mongos:** bubble up close events after the first one ([#1713](https://github.com/mongodb/node-mongodb-native/issues/1713)) ([3e91d77](https://github.com/mongodb/node-mongodb-native/commit/3e91d77)), closes [Automattic/mongoose#6249](https://github.com/Automattic/mongoose/issues/6249) [#1685](https://github.com/mongodb/node-mongodb-native/issues/1685) -* **parallelCollectionScan:** do not use implicit sessions on cursors ([2de470a](https://github.com/mongodb/node-mongodb-native/commit/2de470a)) -* **retryWrites:** fixes more bulk ops to not use retryWrites ([69e5254](https://github.com/mongodb/node-mongodb-native/commit/69e5254)) -* **server:** remove unnecessary print statement ([2bcbc12](https://github.com/mongodb/node-mongodb-native/commit/2bcbc12)) -* **teardown:** properly destroy a topology when initial connect fails ([b8d2f1d](https://github.com/mongodb/node-mongodb-native/commit/b8d2f1d)) -* **topology-base:** sending `endSessions` is always skipped now ([a276cbe](https://github.com/mongodb/node-mongodb-native/commit/a276cbe)) -* **txns:** omit writeConcern when in a transaction ([b88c938](https://github.com/mongodb/node-mongodb-native/commit/b88c938)) -* **utils:** restructure inheritance rules for read preferences ([6a7dac1](https://github.com/mongodb/node-mongodb-native/commit/6a7dac1)) - - -### Features - -* **auth:** add support for SCRAM-SHA-256 ([f53195d](https://github.com/mongodb/node-mongodb-native/commit/f53195d)) -* **changeStream:** Adding new 4.0 ChangeStream features ([2cb4894](https://github.com/mongodb/node-mongodb-native/commit/2cb4894)) -* **changeStream:** allow resuming on getMore errors ([4ba5adc](https://github.com/mongodb/node-mongodb-native/commit/4ba5adc)) -* **changeStream:** expanding changeStream resumable errors ([49fbafd](https://github.com/mongodb/node-mongodb-native/commit/49fbafd)) -* **ChangeStream:** update default startAtOperationTime ([50a9f65](https://github.com/mongodb/node-mongodb-native/commit/50a9f65)) -* **collection:** add colleciton level document mapping/unmapping ([d03335e](https://github.com/mongodb/node-mongodb-native/commit/d03335e)) -* **collection:** Implement new count API ([a5240ae](https://github.com/mongodb/node-mongodb-native/commit/a5240ae)) -* **Collection:** warn if callback is not function in find and findOne ([cddaba0](https://github.com/mongodb/node-mongodb-native/commit/cddaba0)) -* **core:** bump core dependency to v3.1.0 ([4937240](https://github.com/mongodb/node-mongodb-native/commit/4937240)) -* **cursor:** new cursor.transformStream method ([397fcd2](https://github.com/mongodb/node-mongodb-native/commit/397fcd2)) -* **deprecation:** create deprecation function ([4f907a0](https://github.com/mongodb/node-mongodb-native/commit/4f907a0)) -* **deprecation:** wrap deprecated functions ([a5d0f1d](https://github.com/mongodb/node-mongodb-native/commit/a5d0f1d)) -* **GridFS:** add option to disable md5 in file upload ([704a88e](https://github.com/mongodb/node-mongodb-native/commit/704a88e)) -* **listCollections:** add support for nameOnly option ([d2d0367](https://github.com/mongodb/node-mongodb-native/commit/d2d0367)) -* **parallelCollectionScan:** does not allow user to pass a session ([4da9e03](https://github.com/mongodb/node-mongodb-native/commit/4da9e03)) -* **read-preference:** add transaction to inheritance rules ([18ca41d](https://github.com/mongodb/node-mongodb-native/commit/18ca41d)) -* **read-preference:** unify means of read preference resolution ([#1738](https://github.com/mongodb/node-mongodb-native/issues/1738)) ([2995e11](https://github.com/mongodb/node-mongodb-native/commit/2995e11)) -* **urlParser:** use core URL parser ([c1c5d8d](https://github.com/mongodb/node-mongodb-native/commit/c1c5d8d)) -* **withSession:** add top level helper for session lifetime ([9976b86](https://github.com/mongodb/node-mongodb-native/commit/9976b86)) - - -### Reverts - -* **collection:** reverting collection-mapping features ([7298c76](https://github.com/mongodb/node-mongodb-native/commit/7298c76)), closes [#1698](https://github.com/mongodb/node-mongodb-native/issues/1698) [mongodb/js-bson#253](https://github.com/mongodb/js-bson/issues/253) - - - - -## [3.1.1](https://github.com/mongodb/node-mongodb-native/compare/v3.1.0...v3.1.1) (2018-07-05) - - -### Bug Fixes - -* **client-ops:** return transform map to map rather than function ([b8b4bfa](https://github.com/mongodb/node-mongodb-native/commit/b8b4bfa)) -* **collection:** correctly shallow clone passed in options ([2e6c4fa](https://github.com/mongodb/node-mongodb-native/commit/2e6c4fa)) -* **collection:** countDocuments throws error when query doesn't match docs ([4e83556](https://github.com/mongodb/node-mongodb-native/commit/4e83556)) -* **server:** remove unnecessary print statement ([20e11b3](https://github.com/mongodb/node-mongodb-native/commit/20e11b3)) - - - - -# [3.1.0](https://github.com/mongodb/node-mongodb-native/compare/v3.0.6...v3.1.0) (2018-06-27) - - -### Bug Fixes - -* **aggregate:** support user-provided `batchSize` ([ad10dee](https://github.com/mongodb/node-mongodb-native/commit/ad10dee)) -* **bulk:** fixing retryable writes for mass-change ops ([0604036](https://github.com/mongodb/node-mongodb-native/commit/0604036)) -* **bulk:** handle MongoWriteConcernErrors ([12ff392](https://github.com/mongodb/node-mongodb-native/commit/12ff392)) -* **change_stream:** do not check isGetMore if error[mongoErrorContextSymbol] is undefined ([#1720](https://github.com/mongodb/node-mongodb-native/issues/1720)) ([844c2c8](https://github.com/mongodb/node-mongodb-native/commit/844c2c8)) -* **change-stream:** fix change stream resuming with promises ([3063f00](https://github.com/mongodb/node-mongodb-native/commit/3063f00)) -* **collection:** depend on `resolveReadPreference` for inheritance ([a649e35](https://github.com/mongodb/node-mongodb-native/commit/a649e35)) -* **collection:** only send bypassDocumentValidation if true ([fdb828b](https://github.com/mongodb/node-mongodb-native/commit/fdb828b)) -* **cursor:** cursor count with collation fix ([71879c3](https://github.com/mongodb/node-mongodb-native/commit/71879c3)) -* **cursor:** cursor hasNext returns false when exhausted ([184b817](https://github.com/mongodb/node-mongodb-native/commit/184b817)) -* **cursor:** cursor.count not respecting parent readPreference ([5a9fdf0](https://github.com/mongodb/node-mongodb-native/commit/5a9fdf0)) -* **db:** don't send session down to createIndex command ([559c195](https://github.com/mongodb/node-mongodb-native/commit/559c195)) -* **db:** throw readable error when creating `_id` with background: true ([b3ff3ed](https://github.com/mongodb/node-mongodb-native/commit/b3ff3ed)) -* **findOneAndUpdate:** ensure that update documents contain atomic operators ([eb68074](https://github.com/mongodb/node-mongodb-native/commit/eb68074)) -* **index:** export MongoNetworkError ([98ab29e](https://github.com/mongodb/node-mongodb-native/commit/98ab29e)) -* **mongo-client:** pass arguments to ctor when new keyword is used ([d6c3417](https://github.com/mongodb/node-mongodb-native/commit/d6c3417)) -* **mongos:** bubble up close events after the first one ([#1713](https://github.com/mongodb/node-mongodb-native/issues/1713)) ([3e91d77](https://github.com/mongodb/node-mongodb-native/commit/3e91d77)), closes [Automattic/mongoose#6249](https://github.com/Automattic/mongoose/issues/6249) [#1685](https://github.com/mongodb/node-mongodb-native/issues/1685) -* **parallelCollectionScan:** do not use implicit sessions on cursors ([2de470a](https://github.com/mongodb/node-mongodb-native/commit/2de470a)) -* **retryWrites:** fixes more bulk ops to not use retryWrites ([69e5254](https://github.com/mongodb/node-mongodb-native/commit/69e5254)) -* **topology-base:** sending `endSessions` is always skipped now ([a276cbe](https://github.com/mongodb/node-mongodb-native/commit/a276cbe)) -* **txns:** omit writeConcern when in a transaction ([b88c938](https://github.com/mongodb/node-mongodb-native/commit/b88c938)) -* **utils:** restructure inheritance rules for read preferences ([6a7dac1](https://github.com/mongodb/node-mongodb-native/commit/6a7dac1)) - - -### Features - -* **auth:** add support for SCRAM-SHA-256 ([f53195d](https://github.com/mongodb/node-mongodb-native/commit/f53195d)) -* **changeStream:** Adding new 4.0 ChangeStream features ([2cb4894](https://github.com/mongodb/node-mongodb-native/commit/2cb4894)) -* **changeStream:** allow resuming on getMore errors ([4ba5adc](https://github.com/mongodb/node-mongodb-native/commit/4ba5adc)) -* **changeStream:** expanding changeStream resumable errors ([49fbafd](https://github.com/mongodb/node-mongodb-native/commit/49fbafd)) -* **ChangeStream:** update default startAtOperationTime ([50a9f65](https://github.com/mongodb/node-mongodb-native/commit/50a9f65)) -* **collection:** add colleciton level document mapping/unmapping ([d03335e](https://github.com/mongodb/node-mongodb-native/commit/d03335e)) -* **collection:** Implement new count API ([a5240ae](https://github.com/mongodb/node-mongodb-native/commit/a5240ae)) -* **Collection:** warn if callback is not function in find and findOne ([cddaba0](https://github.com/mongodb/node-mongodb-native/commit/cddaba0)) -* **core:** bump core dependency to v3.1.0 ([855bfdb](https://github.com/mongodb/node-mongodb-native/commit/855bfdb)) -* **cursor:** new cursor.transformStream method ([397fcd2](https://github.com/mongodb/node-mongodb-native/commit/397fcd2)) -* **GridFS:** add option to disable md5 in file upload ([704a88e](https://github.com/mongodb/node-mongodb-native/commit/704a88e)) -* **listCollections:** add support for nameOnly option ([d2d0367](https://github.com/mongodb/node-mongodb-native/commit/d2d0367)) -* **parallelCollectionScan:** does not allow user to pass a session ([4da9e03](https://github.com/mongodb/node-mongodb-native/commit/4da9e03)) -* **read-preference:** add transaction to inheritance rules ([18ca41d](https://github.com/mongodb/node-mongodb-native/commit/18ca41d)) -* **read-preference:** unify means of read preference resolution ([#1738](https://github.com/mongodb/node-mongodb-native/issues/1738)) ([2995e11](https://github.com/mongodb/node-mongodb-native/commit/2995e11)) -* **urlParser:** use core URL parser ([c1c5d8d](https://github.com/mongodb/node-mongodb-native/commit/c1c5d8d)) -* **withSession:** add top level helper for session lifetime ([9976b86](https://github.com/mongodb/node-mongodb-native/commit/9976b86)) - - -### Reverts - -* **collection:** reverting collection-mapping features ([7298c76](https://github.com/mongodb/node-mongodb-native/commit/7298c76)), closes [#1698](https://github.com/mongodb/node-mongodb-native/issues/1698) [mongodb/js-bson#253](https://github.com/mongodb/js-bson/issues/253) - - - - -## [3.0.6](https://github.com/mongodb/node-mongodb-native/compare/v3.0.5...v3.0.6) (2018-04-09) - - -### Bug Fixes - -* **db:** ensure `dropDatabase` always uses primary read preference ([e62e5c9](https://github.com/mongodb/node-mongodb-native/commit/e62e5c9)) -* **driverBench:** driverBench has default options object now ([c557817](https://github.com/mongodb/node-mongodb-native/commit/c557817)) - - -### Features - -* **command-monitoring:** support enabling command monitoring ([5903680](https://github.com/mongodb/node-mongodb-native/commit/5903680)) -* **core:** update to mongodb-core v3.0.6 ([cfdd0ae](https://github.com/mongodb/node-mongodb-native/commit/cfdd0ae)) -* **driverBench:** Implementing DriverBench ([d10fbad](https://github.com/mongodb/node-mongodb-native/commit/d10fbad)) - - - - -## [3.0.5](https://github.com/mongodb/node-mongodb-native/compare/v3.0.4...v3.0.5) (2018-03-23) - - -### Bug Fixes - -* **AggregationCursor:** adding session tracking to AggregationCursor ([baca5b7](https://github.com/mongodb/node-mongodb-native/commit/baca5b7)) -* **Collection:** fix session leak in parallelCollectonScan ([3331ec9](https://github.com/mongodb/node-mongodb-native/commit/3331ec9)) -* **comments:** adding fixes for PR comments ([ee110ac](https://github.com/mongodb/node-mongodb-native/commit/ee110ac)) -* **url_parser:** support a default database on mongodb+srv uris ([6d39b2a](https://github.com/mongodb/node-mongodb-native/commit/6d39b2a)) - - -### Features - -* **sessions:** adding implicit cursor session support ([a81245b](https://github.com/mongodb/node-mongodb-native/commit/a81245b)) - - - - -## [3.0.4](https://github.com/mongodb/node-mongodb-native/compare/v3.0.2...v3.0.4) (2018-03-05) - - -### Bug Fixes - -* **collection:** fix error when calling remove with no args ([#1657](https://github.com/mongodb/node-mongodb-native/issues/1657)) ([4c9b0f8](https://github.com/mongodb/node-mongodb-native/commit/4c9b0f8)) -* **executeOperation:** don't mutate options passed to commands ([934a43a](https://github.com/mongodb/node-mongodb-native/commit/934a43a)) -* **jsdoc:** mark db.collection callback as optional + typo fix ([#1658](https://github.com/mongodb/node-mongodb-native/issues/1658)) ([c519b9b](https://github.com/mongodb/node-mongodb-native/commit/c519b9b)) -* **sessions:** move active session tracking to topology base ([#1665](https://github.com/mongodb/node-mongodb-native/issues/1665)) ([b1f296f](https://github.com/mongodb/node-mongodb-native/commit/b1f296f)) -* **utils:** fixes executeOperation to clean up sessions ([04e6ef6](https://github.com/mongodb/node-mongodb-native/commit/04e6ef6)) - - -### Features - -* **default-db:** use dbName from uri if none provided ([23b1938](https://github.com/mongodb/node-mongodb-native/commit/23b1938)) -* **mongodb-core:** update to mongodb-core 3.0.4 ([1fdbaa5](https://github.com/mongodb/node-mongodb-native/commit/1fdbaa5)) - - - - -## [3.0.3](https://github.com/mongodb/node-mongodb-native/compare/v3.0.2...v3.0.3) (2018-02-23) - - -### Bug Fixes - -* **collection:** fix error when calling remove with no args ([#1657](https://github.com/mongodb/node-mongodb-native/issues/1657)) ([4c9b0f8](https://github.com/mongodb/node-mongodb-native/commit/4c9b0f8)) -* **executeOperation:** don't mutate options passed to commands ([934a43a](https://github.com/mongodb/node-mongodb-native/commit/934a43a)) -* **jsdoc:** mark db.collection callback as optional + typo fix ([#1658](https://github.com/mongodb/node-mongodb-native/issues/1658)) ([c519b9b](https://github.com/mongodb/node-mongodb-native/commit/c519b9b)) -* **sessions:** move active session tracking to topology base ([#1665](https://github.com/mongodb/node-mongodb-native/issues/1665)) ([b1f296f](https://github.com/mongodb/node-mongodb-native/commit/b1f296f)) - - - - -## [3.0.2](https://github.com/mongodb/node-mongodb-native/compare/v3.0.1...v3.0.2) (2018-01-29) - - -### Bug Fixes - -* **collection:** ensure dynamic require of `db` is wrapped in parentheses ([efa78f0](https://github.com/mongodb/node-mongodb-native/commit/efa78f0)) -* **db:** only callback with MongoError NODE-1293 ([#1652](https://github.com/mongodb/node-mongodb-native/issues/1652)) ([45bc722](https://github.com/mongodb/node-mongodb-native/commit/45bc722)) -* **topology base:** allow more than 10 event listeners ([#1630](https://github.com/mongodb/node-mongodb-native/issues/1630)) ([d9fb750](https://github.com/mongodb/node-mongodb-native/commit/d9fb750)) -* **url parser:** preserve auth creds when composing conn string ([#1640](https://github.com/mongodb/node-mongodb-native/issues/1640)) ([eddca5e](https://github.com/mongodb/node-mongodb-native/commit/eddca5e)) - - -### Features - -* **bulk:** forward 'checkKeys' option for ordered and unordered bulk operations ([421a6b2](https://github.com/mongodb/node-mongodb-native/commit/421a6b2)) -* **collection:** expose `dbName` property of collection ([6fd05c1](https://github.com/mongodb/node-mongodb-native/commit/6fd05c1)) - - - - -## [3.0.1](https://github.com/mongodb/node-mongodb-native/compare/v3.0.0...v3.0.1) (2017-12-24) - -* update mongodb-core to 3.0.1 - - -# [3.0.0](https://github.com/mongodb/node-mongodb-native/compare/v3.0.0-rc0...v3.0.0) (2017-12-24) - - -### Bug Fixes - -* **aggregate:** remove support for inline results for aggregate ([#1620](https://github.com/mongodb/node-mongodb-native/issues/1620)) ([84457ec](https://github.com/mongodb/node-mongodb-native/commit/84457ec)) -* **topologies:** unify topologies connect API ([#1615](https://github.com/mongodb/node-mongodb-native/issues/1615)) ([0fb4658](https://github.com/mongodb/node-mongodb-native/commit/0fb4658)) - - -### Features - -* **keepAlive:** make keepAlive options consistent ([#1612](https://github.com/mongodb/node-mongodb-native/issues/1612)) ([f608f44](https://github.com/mongodb/node-mongodb-native/commit/f608f44)) - - -### BREAKING CHANGES - -* **topologies:** Function signature for `.connect` method on replset and mongos has changed. You shouldn't have been using this anyway, but if you were, you only should pass `options` and `callback`. - -Part of NODE-1089 -* **keepAlive:** option `keepAlive` is now split into boolean `keepAlive` and -number `keepAliveInitialDelay` - -Fixes NODE-998 - - - - -# [3.0.0-rc0](https://github.com/mongodb/node-mongodb-native/compare/v2.2.31...v3.0.0-rc0) (2017-12-05) - - -### Bug Fixes - -* **aggregation:** ensure that the `cursor` key is always present ([f16f314](https://github.com/mongodb/node-mongodb-native/commit/f16f314)) -* **apm:** give users access to raw server responses ([88b206b](https://github.com/mongodb/node-mongodb-native/commit/88b206b)) -* **apm:** only rebuilt cursor if reply is non-null ([96052c8](https://github.com/mongodb/node-mongodb-native/commit/96052c8)) -* **apm:** rebuild lost `cursor` info on pre-OP_QUERY responses ([4242d49](https://github.com/mongodb/node-mongodb-native/commit/4242d49)) -* **bulk-unordered:** add check for ignoreUndefined ([f38641a](https://github.com/mongodb/node-mongodb-native/commit/f38641a)) -* **change stream examples:** use timeouts, cleanup ([c5fec5f](https://github.com/mongodb/node-mongodb-native/commit/c5fec5f)) -* **change-streams:** ensure a majority read concern on initial agg ([23011e9](https://github.com/mongodb/node-mongodb-native/commit/23011e9)) -* **changeStreams:** fixing node4 issue with util.inherits ([#1587](https://github.com/mongodb/node-mongodb-native/issues/1587)) ([168bb3d](https://github.com/mongodb/node-mongodb-native/commit/168bb3d)) -* **collection:** allow { upsert: 1 } for findOneAndUpdate() and update() ([5bcedd6](https://github.com/mongodb/node-mongodb-native/commit/5bcedd6)) -* **collection:** allow passing `noCursorTimeout` as an option to `find()` ([e9c4ffc](https://github.com/mongodb/node-mongodb-native/commit/e9c4ffc)) -* **collection:** make the parameters of findOne very explicit ([3054f1a](https://github.com/mongodb/node-mongodb-native/commit/3054f1a)) -* **cursor:** `hasNext` should propagate errors when using callback ([6339625](https://github.com/mongodb/node-mongodb-native/commit/6339625)) -* **cursor:** close readable on `null` response for dead cursor ([6aca2c5](https://github.com/mongodb/node-mongodb-native/commit/6aca2c5)) -* **dns txt records:** check options are set ([e5caf4f](https://github.com/mongodb/node-mongodb-native/commit/e5caf4f)) -* **docs:** Represent each valid option in docs in both places ([fde6e5d](https://github.com/mongodb/node-mongodb-native/commit/fde6e5d)) -* **grid-store:** add missing callback ([66a9a05](https://github.com/mongodb/node-mongodb-native/commit/66a9a05)) -* **grid-store:** move into callback scope ([b53f65f](https://github.com/mongodb/node-mongodb-native/commit/b53f65f)) -* **GridFS:** fix TypeError: doc.data.length is not a function ([#1570](https://github.com/mongodb/node-mongodb-native/issues/1570)) ([22a4628](https://github.com/mongodb/node-mongodb-native/commit/22a4628)) -* **list-collections:** ensure default of primary ReadPreference ([4a0cfeb](https://github.com/mongodb/node-mongodb-native/commit/4a0cfeb)) -* **mongo client:** close client before calling done ([c828aab](https://github.com/mongodb/node-mongodb-native/commit/c828aab)) -* **mongo client:** do not connect if url parse error ([cd10084](https://github.com/mongodb/node-mongodb-native/commit/cd10084)) -* **mongo client:** send error to cb ([eafc9e2](https://github.com/mongodb/node-mongodb-native/commit/eafc9e2)) -* **mongo-client:** move to inside of callback ([68b0fca](https://github.com/mongodb/node-mongodb-native/commit/68b0fca)) -* **mongo-client:** options should not be passed to `connect` ([474ac65](https://github.com/mongodb/node-mongodb-native/commit/474ac65)) -* **tests:** migrate 2.x tests to 3.x ([3a5232a](https://github.com/mongodb/node-mongodb-native/commit/3a5232a)) -* **updateOne/updateMany:** ensure that update documents contain atomic operators ([8b4255a](https://github.com/mongodb/node-mongodb-native/commit/8b4255a)) -* **url parser:** add check for options as cb ([52b6039](https://github.com/mongodb/node-mongodb-native/commit/52b6039)) -* **url parser:** compare srv address and parent domains ([daa186d](https://github.com/mongodb/node-mongodb-native/commit/daa186d)) -* **url parser:** compare string from first period on ([9e5d77e](https://github.com/mongodb/node-mongodb-native/commit/9e5d77e)) -* **url parser:** default to ssl true for mongodb+srv ([0fbca4b](https://github.com/mongodb/node-mongodb-native/commit/0fbca4b)) -* **url parser:** error when multiple hostnames used ([c1aa681](https://github.com/mongodb/node-mongodb-native/commit/c1aa681)) -* **url parser:** keep original uri options and default to ssl true ([e876a72](https://github.com/mongodb/node-mongodb-native/commit/e876a72)) -* **url parser:** log instead of throw error for unsupported url options ([155de2d](https://github.com/mongodb/node-mongodb-native/commit/155de2d)) -* **url parser:** make sure uri has 3 parts ([aa9871b](https://github.com/mongodb/node-mongodb-native/commit/aa9871b)) -* **url parser:** only 1 txt record allowed with 2 possible options ([d9f4218](https://github.com/mongodb/node-mongodb-native/commit/d9f4218)) -* **url parser:** only check for multiple hostnames with srv protocol ([5542bcc](https://github.com/mongodb/node-mongodb-native/commit/5542bcc)) -* **url parser:** remove .only from test ([642e39e](https://github.com/mongodb/node-mongodb-native/commit/642e39e)) -* **url parser:** return callback ([6096afc](https://github.com/mongodb/node-mongodb-native/commit/6096afc)) -* **url parser:** support single text record with multiple strings ([356fa57](https://github.com/mongodb/node-mongodb-native/commit/356fa57)) -* **url parser:** try catch bug, not actually returning from try loop ([758892b](https://github.com/mongodb/node-mongodb-native/commit/758892b)) -* **url parser:** use warn instead of info ([40ed27d](https://github.com/mongodb/node-mongodb-native/commit/40ed27d)) -* **url-parser:** remove comment, send error to cb ([d44420b](https://github.com/mongodb/node-mongodb-native/commit/d44420b)) - - -### Features - -* **aggregate:** support hit field for aggregate command ([aa7da15](https://github.com/mongodb/node-mongodb-native/commit/aa7da15)) -* **aggregation:** adds support for comment in aggregation command ([#1571](https://github.com/mongodb/node-mongodb-native/issues/1571)) ([4ac475c](https://github.com/mongodb/node-mongodb-native/commit/4ac475c)) -* **aggregation:** fail aggregation on explain + readConcern/writeConcern ([e0ca1b4](https://github.com/mongodb/node-mongodb-native/commit/e0ca1b4)) -* **causal-consistency:** support `afterClusterTime` in readConcern ([a9097f7](https://github.com/mongodb/node-mongodb-native/commit/a9097f7)) -* **change-streams:** add support for change streams ([c02d25c](https://github.com/mongodb/node-mongodb-native/commit/c02d25c)) -* **collection:** updating find API ([f26362d](https://github.com/mongodb/node-mongodb-native/commit/f26362d)) -* **execute-operation:** implementation for common op execution ([67c344f](https://github.com/mongodb/node-mongodb-native/commit/67c344f)) -* **listDatabases:** add support for nameOnly option to listDatabases ([eb79b5a](https://github.com/mongodb/node-mongodb-native/commit/eb79b5a)) -* **maxTimeMS:** adding maxTimeMS option to createIndexes and dropIndexes ([90d4a63](https://github.com/mongodb/node-mongodb-native/commit/90d4a63)) -* **mongo-client:** implement `MongoClient.prototype.startSession` ([bce5adf](https://github.com/mongodb/node-mongodb-native/commit/bce5adf)) -* **retryable-writes:** add support for `retryWrites` cs option ([2321870](https://github.com/mongodb/node-mongodb-native/commit/2321870)) -* **sessions:** MongoClient will now track sessions and release ([6829f47](https://github.com/mongodb/node-mongodb-native/commit/6829f47)) -* **sessions:** support passing sessions via objects in all methods ([a531f05](https://github.com/mongodb/node-mongodb-native/commit/a531f05)) -* **shared:** add helper utilities for assertion and suite setup ([b6cc34e](https://github.com/mongodb/node-mongodb-native/commit/b6cc34e)) -* **ssl:** adds missing ssl options ssl options for `ciphers` and `ecdhCurve` ([441b7b1](https://github.com/mongodb/node-mongodb-native/commit/441b7b1)) -* **test-shared:** add `notEqual` assertion ([41d93fd](https://github.com/mongodb/node-mongodb-native/commit/41d93fd)) -* **test-shared:** add `strictEqual` assertion method ([cad8e19](https://github.com/mongodb/node-mongodb-native/commit/cad8e19)) -* **topologies:** expose underlaying `logicalSessionTimeoutMinutes' ([1609a37](https://github.com/mongodb/node-mongodb-native/commit/1609a37)) -* **url parser:** better error message for slash in hostname ([457bc29](https://github.com/mongodb/node-mongodb-native/commit/457bc29)) - - -### BREAKING CHANGES - -* **aggregation:** If you use aggregation, and try to use the explain flag while you -have a readConcern or writeConcern, your query will fail -* **collection:** `find` and `findOne` no longer support the `fields` parameter. -You can achieve the same results as the `fields` parameter by -either using `Cursor.prototype.project`, or by passing the `projection` -property in on the `options` object. Additionally, `find` does not -support individual options like `skip` and `limit` as positional -parameters. You must pass in these parameters in the `options` object - - - -3.0.0 2017-??-?? ----------------- -* NODE-1043 URI-escaping authentication and hostname details in connection string - -2.2.31 2017-08-08 ------------------ -* update mongodb-core to 2.2.15 -* allow auth option in MongoClient.connect -* remove duplicate option `promoteLongs` from MongoClient's `connect` -* bulk operations should not throw an error on empty batch - -2.2.30 2017-07-07 ------------------ -* Update mongodb-core to 2.2.14 -* MongoClient - * add `appname` to list of valid option names - * added test for passing appname as option -* NODE-1052 ensure user options are applied while parsing connection string uris - -2.2.29 2017-06-19 ------------------ -* Update mongodb-core to 2.1.13 - * NODE-1039 ensure we force destroy server instances, forcing queue to be flushed. - * Use actual server type in standalone SDAM events. -* Allow multiple map calls (Issue #1521, https://github.com/Robbilie). -* Clone insertMany options before mutating (Issue #1522, https://github.com/vkarpov15). -* NODE-1034 Fix GridStore issue caused by Node 8.0.0 breaking backward compatible fs.read API. -* NODE-1026, use operator instead of skip function in order to avoid useless fetch stage. - -2.2.28 2017-06-02 ------------------ -* Update mongodb-core to 2.1.12 - * NODE-1019 Set keepAlive to 300 seconds or 1/2 of socketTimeout if socketTimeout < keepAlive. - * Minor fix to report the correct state on error. - * NODE-1020 'family' was added to options to provide high priority for ipv6 addresses (Issue #1518, https://github.com/firej). - * Fix require_optional loading of bson-ext. - * Ensure no errors are thrown by replset if topology is destroyed before it finished connecting. - * NODE-999 SDAM fixes for Mongos and single Server event emitting. - * NODE-1014 Set socketTimeout to default to 360 seconds. - * NODE-1019 Set keepAlive to 300 seconds or 1/2 of socketTimeout if socketTimeout < keepAlive. -* Just handle Collection name errors distinctly from general callback errors avoiding double callbacks in Db.collection. -* NODE-999 SDAM fixes for Mongos and single Server event emitting. -* NODE-1000 Added guard condition for upload.js checkDone function in case of race condition caused by late arriving chunk write. - -2.2.27 2017-05-22 ------------------ -* Updated mongodb-core to 2.1.11 - * NODE-987 Clear out old intervalIds on when calling topologyMonitor. - * NODE-987 Moved filtering to pingServer method and added test case. - * Check for connection destroyed just before writing out and flush out operations correctly if it is (Issue #179, https://github.com/jmholzinger). - * NODE-989 Refactored Replicaset monitoring to correcly monitor newly added servers, Also extracted setTimeout and setInterval to use custom wrappers Timeout and Interval. -* NODE-985 Deprecated Db.authenticate and Admin.authenticate and moved auth methods into authenticate.js to ensure MongoClient.connect does not print deprecation warnings. -* NODE-988 Merged readConcern and hint correctly on collection(...).find(...).count() -* Fix passing the readConcern option to MongoClient.connect (Issue #1514, https://github.com/bausmeier). -* NODE-996 Propegate all events up to a MongoClient instance. -* Allow saving doc with null `_id` (Issue #1517, https://github.com/vkarpov15). -* NODE-993 Expose hasNext for command cursor and add docs for both CommandCursor and Aggregation Cursor. - -2.2.26 2017-04-18 ------------------ -* Updated mongodb-core to 2.1.10 - * NODE-981 delegate auth to replset/mongos if inTopology is set. - * NODE-978 Wrap connection.end in try/catch for node 0.10.x issue causing exceptions to be thrown, Also surfaced getConnection for mongos and replset. - * Remove dynamic require (Issue #175, https://github.com/tellnes). - * NODE-696 Handle interrupted error for createIndexes. - * Fixed isse when user is executing find command using Server.command and it get interpreted as a wire protcol message, #172. - * NODE-966 promoteValues not being promoted correctly to getMore. - * Merged in fix for flushing out monitoring operations. -* NODE-983 Add cursorId to aggregate and listCollections commands (Issue, #1510). -* Mark group and profilingInfo as deprecated methods -* NODE-956 DOCS Examples. -* Update readable-stream to version 2.2.7. -* NODE-978 Added test case to uncover connection.end issue for node 0.10.x. -* NODE-972 Fix(db): don't remove database name if collectionName == dbName (Issue, #1502) -* Fixed merging of writeConcerns on db.collection method. -* NODE-970 mix in readPreference for strict mode listCollections callback. -* NODE-966 added testcase for promoteValues being applied to getMore commands. -* NODE-962 Merge in ignoreUndefined from collection level for find/findOne. -* Remove multi option from updateMany tests/docs (Issue #1499, https://github.com/spratt). -* NODE-963 Correctly handle cursor.count when using APM. - -2.2.25 2017-03-17 ------------------ -* Don't rely on global toString() for checking if object (Issue #1494, https://github.com/vkarpov15). -* Remove obsolete option uri_decode_auth (Issue #1488, https://github.com/kamagatos). -* NODE-936 Correctly translate ReadPreference to CoreReadPreference for mongos queries. -* Exposed BSONRegExp type. -* NODE-950 push correct index for INSERT ops (https://github.com/mbroadst). -* NODE-951 Added support for sslCRL option and added a test case for it. -* NODE-953 Made batchSize issue general at cursor level. -* NODE-954 Remove write concern from reindex helper as it will not be supported in 3.6. -* Updated mongodb-core to 2.1.9. - * Return lastIsMaster correctly when connecting with secondaryOnlyConnectionAllowed is set to true and only a secondary is available in replica state. - * Clone options when passed to wireProtocol handler to avoid intermittent modifications causing errors. - * Ensure SSL error propegates better for Replset connections when there is a SSL validation error. - * NODE-957 Fixed issue where < batchSize not causing cursor to be closed on execution of first batch. - * NODE-958 Store reconnectConnection on pool object to allow destroy to close immediately. - -2.2.24 2017-02-14 ------------------ -* NODE-935, NODE-931 Make MongoClient strict options validation optional and instead print annoying console.warn entries. - -2.2.23 2017-02-13 ------------------ -* Updated mongodb-core to 2.1.8. - * NODE-925 ensure we reschedule operations while pool is < poolSize while pool is growing and there are no connections with not currently performing work. - * NODE-927 fixes issue where authentication was performed against arbiter instances. - * NODE-915 Normalize all host names to avoid comparison issues. - * Fixed issue where pool.destroy would never finish due to a single operation not being executed and keeping it open. -* NODE-931 Validates all the options for MongoClient.connect and fixes missing connection settings. -* NODE-929 Update SSL tutorial to correctly reflect the non-need for server/mongos/replset subobjects -* Fix sensitive command check (Issue #1473, https://github.com/Annoraaq) - -2.2.22 2017-01-24 ------------------ -* Updated mongodb-core to 2.1.7. - * NODE-919 ReplicaSet connection does not close immediately (Issue #156). - * NODE-901 Fixed bug when normalizing host names. - * NODE-909 Fixed readPreference issue caused by direct connection to primary. - * NODE-910 Fixed issue when bufferMaxEntries == 0 and read preference set to nearest. -* Add missing unref implementations for replset, mongos (Issue #1455, https://github.com/zbjornson) - -2.2.21 2017-01-13 ------------------ -* Updated mongodb-core to 2.1.6. - * NODE-908 Keep auth contexts in replset and mongos topology to ensure correct application of authentication credentials when primary is first server to be detected causing an immediate connect event to happen. - -2.2.20 2017-01-11 ------------------ -* Updated mongodb-core to 2.1.5 to include bson 1.0.4 and bson-ext 1.0.4 due to Buffer.from being broken in early node 4.x versions. - -2.2.19 2017-01-03 ------------------ -* Corrupted Npm release fix. - -2.2.18 2017-01-03 ------------------ -* Updated mongodb-core to 2.1.4 to fix bson ObjectId toString issue with utils.inspect messing with toString parameters in node 6. - -2.2.17 2017-01-02 ------------------ -* updated createCollection doc options and linked to create command. -* Updated mongodb-core to 2.1.3. - * Monitoring operations are re-scheduled in pool if it cannot find a connection that does not already have scheduled work on it, this is to avoid the monitoring socket timeout being applied to any existing operations on the socket due to pipelining - * Moved replicaset monitoring away from serial mode and to parallel mode. - * updated bson and bson-ext dependencies to 1.0.2. - -2.2.16 2016-12-13 ------------------ -* NODE-899 reversed upsertedId change to bring back old behavior. - -2.2.15 2016-12-10 ------------------ -* Updated mongodb-core to 2.1.2. - * Delay topologyMonitoring on successful attemptReconnect as no need to run a full scan immediately. - * Emit reconnect event in primary joining when in connected status for a replicaset (Fixes mongoose reconnect issue). - -2.2.14 2016-12-08 ------------------ -* Updated mongodb-core to 2.1.1. -* NODE-892 Passthrough options.readPreference to mongodb-core ReplSet instance. - -2.2.13 2016-12-05 ------------------ -* Updated mongodb-core to 2.1.0. -* NODE-889 Fixed issue where legacy killcursor wire protocol messages would not be sent when APM is enabled. -* Expose parserType as property on topology objects. - -2.2.12 2016-11-29 ------------------ -* Updated mongodb-core to 2.0.14. - * Updated bson library to 0.5.7. - * Dont leak connection.workItems elments when killCursor is called (Issue #150, https://github.com/mdlavin). - * Remove unnecessary errors formatting (Issue #149, https://github.com/akryvomaz). - * Only check isConnected against availableConnections (Issue #142). - * NODE-838 Provide better error message on failed to connect on first retry for Mongos topology. - * Set default servername to host is not passed through for sni. - * Made monitoring happen on exclusive connection and using connectionTimeout to handle the wait time before failure (Issue #148). - * NODE-859 Make minimum value of maxStalenessSeconds 90 seconds. - * NODE-852 Fix Kerberos module deprecations on linux and windows and release new kerberos version. - * NODE-850 Update Max Staleness implementation. - * NODE-849 username no longer required for MONGODB-X509 auth. - * NODE-848 BSON Regex flags must be alphabetically ordered. - * NODE-846 Create notice for all third party libraries. - * NODE-843 Executing bulk operations overwrites write concern parameter. - * NODE-842 Re-sync SDAM and SDAM Monitoring tests from Specs repo. - * NODE-840 Resync CRUD spec tests. - * Unescapable while(true) loop (Issue #152). -* NODE-864 close event not emits during network issues using single server topology. -* Introduced maxStalenessSeconds. -* NODE-840 Added CRUD specification test cases and fix minor issues with upserts reporting matchedCount > 0. -* Don't ignore Db-level authSource when using auth method. (https://github.com/donaldguy). - -2.2.11 2016-10-21 ------------------ -* Updated mongodb-core to 2.0.13. - - Fire callback when topology was destroyed (Issue #147, https://github.com/vkarpov15). - - Refactoring to support pipelining ala 1.4.x branch will retaining the benefits of the growing/shrinking pool (Issue #146). - - Fix typo in serverHeartbeatFailed event name (Issue #143, https://github.com/jakesjews). - - NODE-798 Driver hangs on count command in replica set with one member (Issue #141, https://github.com/isayme). -* Updated bson library to 0.5.6. - - Included cyclic dependency detection -* Fix typo in serverHeartbeatFailed event name (Issue #1418, https://github.com/jakesjews). -* NODE-824, readPreference "nearest" does not work when specified at collection level. -* NODE-822, GridFSBucketWriteStream end method does not handle optional parameters. -* NODE-823, GridFSBucketWriteStream end: callback is invoked with invalid parameters. -* NODE-829, Using Start/End offset option in GridFSBucketReadStream doesn't return the right sized buffer. - -2.2.10 2016-09-15 ------------------ -* Updated mongodb-core to 2.0.12. -* fix debug logging message not printing server name. -* fixed application metadata being sent by wrong ismaster. -* NODE-812 Fixed mongos stall due to proxy monitoring ismaster failure causing reconnect. -* NODE-818 Replicaset timeouts in initial connect sequence can "no primary found". -* Updated bson library to 0.5.5. -* Added DBPointer up conversion to DBRef. -* MongoDB 3.4-RC Pass **appname** through MongoClient.connect uri or options to allow metadata to be passed. -* MongoDB 3.4-RC Pass collation options on update, findOne, find, createIndex, aggregate. -* MongoDB 3.4-RC Allow write concerns to be passed to all supporting server commands. -* MongoDB 3.4-RC Allow passing of **servername** as SSL options to support SNI. - -2.2.9 2016-08-29 ----------------- -* Updated mongodb-core to 2.0.11. -* NODE-803, Fixed issue in how the latency window is calculated for Mongos topology causing issues for single proxy connections. -* Avoid timeout in attemptReconnect causing multiple attemptReconnect attempts to happen (Issue #134, https://github.com/dead-horse). -* Ensure promoteBuffers is propegated in same fashion as promoteValues and promoteLongs. -* Don't treat ObjectId as object for mapReduce scope (Issue #1397, https://github.com/vkarpov15). - -2.2.8 2016-08-23 ----------------- -* Updated mongodb-core to 2.0.10. -* Added promoteValues flag (default to true) to allow user to specify they only want wrapped BSON values back instead of promotion to native types. -* Do not close mongos proxy connection on failed ismaster check in ha process (Issue #130). - -2.2.7 2016-08-19 ----------------- -* If only a single mongos is provided in the seedlist, fix issue where it would be assigned as single standalone server instead of mongos topology (Issue #130). -* Updated mongodb-core to 2.0.9. -* Allow promoteLongs to be passed in through Response.parse method and overrides default set on the connection. -* NODE-798 Driver hangs on count command in replica set with one member. -* Allow promoteLongs to be passed in through Response.parse method and overrides default set on the connection. -* Allow passing in servername for TLS connections for SNI support. - -2.2.6 2016-08-16 ----------------- -* Updated mongodb-core to 2.0.8. -* Allow execution of store operations independent of having both a primary and secondary available (Issue #123). -* Fixed command execution issue for mongos to ensure buffering of commands when no mongos available. -* Allow passing in an array of tags to ReadPreference constructor (Issue #1382, https://github.com/vkarpov15) -* Added hashed connection names and fullResult. -* Updated bson library to 0.5.3. -* Enable maxTimeMS in count, distinct, findAndModify. - -2.2.5 2016-07-28 ----------------- -* Updated mongodb-core to 2.0.7. -* Allow primary to be returned when secondaryPreferred is passed (Issue #117, https://github.com/dhendo). -* Added better warnings when passing in illegal seed list members to a Mongos topology. -* Minor attemptReconnect bug that would cause multiple attemptReconnect to run in parallel. -* Fix wrong opType passed to disconnectHandler.add (Issue #121, https://github.com/adrian-gierakowski) -* Implemented domain backward comp support enabled via domainsEnabled options on Server/ReplSet/Mongos and MongoClient.connect. - -2.2.4 2016-07-19 ----------------- -* NPM corrupted upload fix. - -2.2.3 2016-07-19 ----------------- -* Updated mongodb-core to 2.0.6. -* Destroy connection on socket timeout due to newer node versions not closing the socket. - -2.2.2 2016-07-15 ----------------- -* Updated mongodb-core to 2.0.5. -* Minor fixes to handle faster MongoClient connectivity from the driver, allowing single server instances to detect if they are a proxy. -* Added numberOfConsecutiveTimeouts to pool that will destroy the pool if the number of consecutive timeouts > reconnectTries. -* Print warning if seedlist servers host name does not match the one provided in it's ismaster.me field for Replicaset members. -* Fix issue where Replicaset connection would not succeeed if there the replicaset was a single primary server setup. - -2.2.1 2016-07-11 ----------------- -* Updated mongodb-core to 2.0.4. -* handle situation where user is providing seedlist names that do not match host list. fix allows for a single full discovery connection sweep before erroring out. -* NODE-747 Polyfill for Object.assign for 0.12.x or 0.10.x. -* NODE-746 Improves replicaset errors for wrong setName. - -2.2.0 2016-07-05 ----------------- -* Updated mongodb-core to 2.0.3. -* Moved all authentication and handling of growing/shrinking of pool connections into actual pool. -* All authentication methods now handle both auth/reauthenticate and logout events. -* Introduced logout method to get rid of onAll option for logout command. -* Updated bson to 0.5.0 that includes Decimal128 support. -* Fixed logger error serialization issue. -* Documentation fixes. -* Implemented Server Selection Specification test suite. -* Added warning level to logger. -* Added warning message when sockeTimeout < haInterval for Replset/Mongos. -* Mongos emits close event on no proxies available or when reconnect attempt fails. -* Replset emits close event when no servers available or when attemptReconnect fails to reconnect. -* Don't throw in auth methods but return error in callback. - -2.1.21 2016-05-30 ------------------ -* Updated mongodb-core to 1.3.21. -* Pool gets stuck if a connection marked for immediateRelease times out (Issue #99, https://github.com/nbrachet). -* Make authentication process retry up to authenticationRetries at authenticationRetryIntervalMS interval. -* Made ismaster replicaset calls operate with connectTimeout or monitorSocketTimeout to lower impact of big socketTimeouts on monitoring performance. -* Make sure connections mark as "immediateRelease" don't linger the inUserConnections list. Otherwise, after that connection times out, getAll() incorrectly returns more connections than are effectively present, causing the pool to not get restarted by reconnectServer. (Issue #99, https://github.com/nbrachet). -* Make cursor getMore or killCursor correctly trigger pool reconnect to single server if pool has not been destroyed. -* Make ismaster monitoring for single server connection default to avoid user confusion due to change in behavior. - -2.1.20 2016-05-25 ------------------ -* Refactored MongoClient options handling to simplify the logic, unifying it. -* NODE-707 Implemented openUploadStreamWithId on GridFS to allow for custom fileIds so users are able to customize shard key and shard distribution. -* NODE-710 Allow setting driver loggerLevel and logger function from MongoClient options. -* Updated mongodb-core to 1.3.20. -* Minor fix for SSL errors on connection attempts, minor fix to reconnect handler for the server. -* Don't write to socket before having registered the callback for commands, work around for windows issuing error events twice on node.js when socket gets destroyed by firewall. -* Fix minor issue where connectingServers would not be removed correctly causing single server connections to not auto-reconnect. - -2.1.19 2016-05-17 ----------------- -* Handle situation where a server connection in a replicaset sometimes fails to be destroyed properly due to being in the middle of authentication when the destroy method is called on the replicaset causing it to be orphaned and never collected. -* Ensure replicaset topology destroy is never called by SDAM. -* Ensure all paths are correctly returned on inspectServer in replset. -* Updated mongodb-core to 1.3.19 to fix minor connectivity issue on quick open/close of MongoClient connections on auth enabled mongodb Replicasets. - -2.1.18 2016-04-27 ------------------ -* Updated mongodb-core to 1.3.18 to fix Node 6.0 issues. - -2.1.17 2016-04-26 ------------------ -* Updated mongodb-core to 1.3.16 to work around issue with early versions of node 0.10.x due to missing unref method on ClearText streams. -* INT-1308: Allow listIndexes to inherit readPreference from Collection or DB. -* Fix timeout issue using new flags #1361. -* Updated mongodb-core to 1.3.17. -* Better handling of unique createIndex error. -* Emit error only if db instance has an error listener. -* DEFAULT authMechanism; don't throw error if explicitly set by user. - -2.1.16 2016-04-06 ------------------ -* Updated mongodb-core to 1.3.16. - -2.1.15 2016-04-06 ------------------ -* Updated mongodb-core to 1.3.15. -* Set ssl, sslValidate etc to mongosOptions on url_parser (Issue #1352, https://github.com/rubenstolk). -- NODE-687 Fixed issue where a server object failed to be destroyed if the replicaset state did not update successfully. This could leave active connections accumulating over time. -- Fixed some situations where all connections are flushed due to a single connection in the connection pool closing. - -2.1.14 2016-03-29 ------------------ -* Updated mongodb-core to 1.3.13. -* Handle missing cursor on getMore when going through a mongos proxy by pinning to socket connection and not server. - -2.1.13 2016-03-29 ------------------ -* Updated mongodb-core to 1.3.12. - -2.1.12 2016-03-29 ------------------ -* Updated mongodb-core to 1.3.11. -* Mongos setting acceptableLatencyMS exposed to control the latency women for mongos selection. -* Mongos pickProxies fall back to closest mongos if no proxies meet latency window specified. -* isConnected method for mongos uses same selection code as getServer. -* Exceptions in cursor getServer trapped and correctly delegated to high level handler. - -2.1.11 2016-03-23 ------------------ -* Updated mongodb-core to 1.3.10. -* Introducing simplified connections settings. - -2.1.10 2016-03-21 ------------------ -* Updated mongodb-core to 1.3.9. -* Fixing issue that prevented mapReduce stats from being resolved (Issue #1351, https://github.com/davidgtonge) -* Forwards SDAM monitoring events from mongodb-core. - -2.1.9 2016-03-16 ----------------- -* Updated mongodb-core to 1.3.7 to fix intermittent race condition that causes some users to experience big amounts of socket connections. -* Makde bson parser in ordered/unordered bulk be directly from mongodb-core to avoid intermittent null error on mongoose. - -2.1.8 2016-03-14 ----------------- -* Updated mongodb-core to 1.3.5. -* NODE-660 TypeError: Cannot read property 'noRelease' of undefined. -* Harden MessageHandler in server.js to avoid issues where we cannot find a callback for an operation. -* Ensure RequestId can never be larger than Max Number integer size. -* NODE-661 typo in url_parser.js resulting in replSetServerOptions is not defined when connecting over ssl. -* Confusing error with invalid partial index filter (Issue #1341, https://github.com/vkarpov15). -* NODE-669 Should only error out promise for bulkWrite when error is a driver level error not a write error or write concern error. -* NODE-662 shallow copy options on methods that are not currently doing it to avoid passed in options mutiation. -* NODE-663 added lookup helper on aggregation cursor. -* NODE-585 Result object specified incorrectly for findAndModify?. -* NODE-666 harden validation for findAndModify CRUD methods. - -2.1.7 2016-02-09 ----------------- -* NODE-656 fixed corner case where cursor count command could be left without a connection available. -* NODE-658 Work around issue that bufferMaxEntries:-1 for js gets interpreted wrongly due to double nature of Javascript numbers. -* Fix: GridFS always returns the oldest version due to incorrect field name (Issue #1338, https://github.com/mdebruijne). -* NODE-655 GridFS stream support for cancelling upload streams and download streams (Issue #1339, https://github.com/vkarpov15). -* NODE-657 insertOne don`t return promise in some cases. -* Added destroy alias for abort function on GridFSBucketWriteStream. - -2.1.6 2016-02-05 ----------------- -* Updated mongodb-core to 1.3.1. - -2.1.5 2016-02-04 ----------------- -* Updated mongodb-core to 1.3.0. -* Added raw support for the command function on topologies. -* Fixed issue where raw results that fell on batchSize boundaries failed (Issue #72) -* Copy over all the properties to the callback returned from bindToDomain, (Issue #72) -* Added connection hash id to be able to reference connection host/name without leaking it outside of driver. -* NODE-638, Cannot authenticate database user with utf-8 password. -* Refactored pool to be worker queue based, minimizing the impact a slow query have on throughput as long as # slow queries < # connections in the pool. -* Pool now grows and shrinks correctly depending on demand not causing a full pool reconnect. -* Improvements in monitoring of a Replicaset where in certain situations the inquiry process could get exited. -* Switched to using Array.push instead of concat for use cases of a lot of documents. -* Fixed issue where re-authentication could loose the credentials if whole Replicaset disconnected at once. -* Added peer optional dependencies support using require_optional module. -* Bug is listCollections for collection names that start with db name (Issue #1333, https://github.com/flyingfisher) -* Emit error before closing stream (Issue #1335, https://github.com/eagleeye) - -2.1.4 2016-01-12 ----------------- -* Restricted node engine to >0.10.3 (https://jira.mongodb.org/browse/NODE-635). -* Multiple database names ignored without a warning (https://jira.mongodb.org/browse/NODE-636, Issue #1324, https://github.com/yousefhamza). -* Convert custom readPreference objects in collection.js (Issue #1326, https://github.com/Machyne). - -2.1.3 2016-01-04 ----------------- -* Updated mongodb-core to 1.2.31. -* Allow connection to secondary if primaryPreferred or secondaryPreferred (Issue #70, https://github.com/leichter) - -2.1.2 2015-12-23 ----------------- -* Updated mongodb-core to 1.2.30. -* Pool allocates size + 1 connections when using replicasets, reserving additional pool connection for monitoring exclusively. -* Fixes bug when all replicaset members are down, that would cause it to fail to reconnect using the originally provided seedlist. - -2.1.1 2015-12-13 ----------------- -* Surfaced checkServerIdentity options for MongoClient, Server, ReplSet and Mongos to allow for control of the checkServerIdentity method available in Node.s 0.12.x or higher. -* Added readPreference support to listCollections and listIndexes helpers. -* Updated mongodb-core to 1.2.28. - -2.1.0 2015-12-06 ----------------- -* Implements the connection string specification, https://github.com/mongodb/specifications/blob/master/source/connection-string/connection-string-spec.rst. -* Implements the new GridFS specification, https://github.com/mongodb/specifications/blob/master/source/gridfs/gridfs-spec.rst. -* Full MongoDB 3.2 support. -* NODE-601 Added maxAwaitTimeMS support for 3.2 getMore to allow for custom timeouts on tailable cursors. -* Updated mongodb-core to 1.2.26. -* Return destination in GridStore pipe function. -* NODE-606 better error handling on destroyed topology for db.js methods. -* Added isDestroyed method to server, replset and mongos topologies. -* Upgraded test suite to run using mongodb-topology-manager. - -2.0.53 2015-12-23 ------------------ -* Updated mongodb-core to 1.2.30. -* Pool allocates size + 1 connections when using replicasets, reserving additional pool connection for monitoring exclusively. -* Fixes bug when all replicaset members are down, that would cause it to fail to reconnect using the originally provided seedlist. - -2.0.52 2015-12-14 ------------------ -* removed remove from Gridstore.close. - -2.0.51 2015-12-13 ------------------ -* Surfaced checkServerIdentity options for MongoClient, Server, ReplSet and Mongos to allow for control of the checkServerIdentity method available in Node.s 0.12.x or higher. -* Added readPreference support to listCollections and listIndexes helpers. -* Updated mongodb-core to 1.2.28. - -2.0.50 2015-12-06 ------------------ -* Updated mongodb-core to 1.2.26. - -2.0.49 2015-11-20 ------------------ -* Updated mongodb-core to 1.2.24 with several fixes. - * Fix Automattic/mongoose#3481; flush callbacks on error, (Issue #57, https://github.com/vkarpov15). - * $explain query for wire protocol 2.6 and 2.4 does not set number of returned documents to -1 but to 0. - * ismaster runs against admin.$cmd instead of system.$cmd. - * Fixes to handle getMore command errors for MongoDB 3.2 - * Allows the process to properly close upon a Db.close() call on the replica set by shutting down the haTimer and closing arbiter connections. - -2.0.48 2015-11-07 ------------------ -* GridFS no longer performs any deletes when writing a brand new file that does not have any previous .fs.chunks or .fs.files documents. -* Updated mongodb-core to 1.2.21. -* Hardened the checking for replicaset equality checks. -* OpReplay flag correctly set on Wire protocol query. -* Mongos load balancing added, introduced localThresholdMS to control the feature. -* Kerberos now a peerDependency, making it not install it by default in Node 5.0 or higher. - -2.0.47 2015-10-28 ------------------ -* Updated mongodb-core to 1.2.20. -* Fixed bug in arbiter connection capping code. -* NODE-599 correctly handle arrays of server tags in order of priority. -* Fix for 2.6 wire protocol handler related to readPreference handling. -* Added maxAwaitTimeMS support for 3.2 getMore to allow for custom timeouts on tailable cursors. -* Make CoreCursor check for $err before saying that 'next' succeeded (Issue #53, https://github.com/vkarpov15). - -2.0.46 2015-10-15 ------------------ -* Updated mongodb-core to 1.2.19. -* NODE-578 Order of sort fields is lost for numeric field names. -* Expose BSON Map (ES6 Map or polyfill). -* Minor fixes for APM support to pass extended APM test suite. - -2.0.45 2015-09-30 ------------------ -* NODE-566 Fix issue with rewind on capped collections causing cursor state to be reset on connection loss. - -2.0.44 2015-09-28 ------------------ -* Bug fixes for APM upconverting of legacy INSERT/UPDATE/REMOVE wire protocol messages. -* NODE-562, fixed issue where a Replicaset MongoDB URI with a single seed and replSet name set would cause a single direct connection instead of topology discovery. -* Updated mongodb-core to 1.2.14. -* NODE-563 Introduced options.ignoreUndefined for db class and MongoClient db options, made serialize undefined to null default again but allowing for overrides on insert/update/delete operations. -* Use handleCallback if result is an error for count queries. (Issue #1298, https://github.com/agclever) -* Rewind cursor to correctly force reconnect on capped collections when first query comes back empty. -* NODE-571 added code 59 to legacy server errors when SCRAM-SHA-1 mechanism fails. -* NODE-572 Remove examples that use the second parameter to `find()`. - -2.0.43 2015-09-14 ------------------ -* Propagate timeout event correctly to db instances. -* Application Monitoring API (APM) implemented. -* NOT providing replSet name in MongoClient connection URI will force single server connection. Fixes issue where it was impossible to directly connect to a replicaset member server. -* Updated mongodb-core to 1.2.12. -* NODE-541 Initial Support "read committed" isolation level where "committed" means confimed by the voting majority of a replica set. -* GridStore doesn't share readPreference setting from connection string. (Issue #1295, https://github.com/zhangyaoxing) -* fixed forceServerObjectId calls (Issue #1292, https://github.com/d-mon-) -* Pass promise library through to DB function (Issue #1294, https://github.com/RovingCodeMonkey) - -2.0.42 2015-08-18 ------------------ -* Added test case to exercise all non-crud methods on mongos topologies, fixed numberOfConnectedServers on mongos topology instance. - -2.0.41 2015-08-14 ------------------ -* Added missing Mongos.prototype.parserType function. -* Updated mongodb-core to 1.2.10. - -2.0.40 2015-07-14 ------------------ -* Updated mongodb-core to 1.2.9 for 2.4 wire protocol error handler fix. -* NODE-525 Reset connectionTimeout after it's overwritten by tls.connect. -* NODE-518 connectTimeoutMS is doubled in 2.0.39. -* NODE-506 Ensures that errors from bulk unordered and ordered are instanceof Error (Issue #1282, https://github.com/owenallenaz). -* NODE-526 Unique index not throwing duplicate key error. -* NODE-528 Ignore undefined fields in Collection.find(). -* NODE-527 The API example for collection.createIndex shows Db.createIndex functionality. - -2.0.39 2015-07-14 ------------------ -* Updated mongodb-core to 1.2.6 for NODE-505. - -2.0.38 2015-07-14 ------------------ -* NODE-505 Query fails to find records that have a 'result' property with an array value. - -2.0.37 2015-07-14 ------------------ -* NODE-504 Collection * Default options when using promiseLibrary. -* NODE-500 Accidental repeat of hostname in seed list multiplies total connections persistently. -* Updated mongodb-core to 1.2.5 to fix NODE-492. - -2.0.36 2015-07-07 ------------------ -* Fully promisified allowing the use of ES6 generators and libraries like co. Also allows for BYOP (Bring your own promises). -* NODE-493 updated mongodb-core to 1.2.4 to ensure we cannot DDOS the mongod or mongos process on large connection pool sizes. - -2.0.35 2015-06-17 ------------------ -* Upgraded to mongodb-core 1.2.2 including removing warnings when C++ bson parser is not available and a fix for SCRAM authentication. - -2.0.34 2015-06-17 ------------------ -* Upgraded to mongodb-core 1.2.1 speeding up serialization and removing the need for the c++ bson extension. -* NODE-486 fixed issue related to limit and skip when calling toArray in 2.0 driver. -* NODE-483 throw error if capabilities of topology is queries before topology has performed connection setup. -* NODE-482 fixed issue where MongoClient.connect would incorrectly identify a replset seed list server as a non replicaset member. -* NODE-487 fixed issue where killcursor command was not being sent correctly on limit and skip queries. - -2.0.33 2015-05-20 ------------------ -* Bumped mongodb-core to 1.1.32. - -2.0.32 2015-05-19 ------------------ -* NODE-463 db.close immediately executes its callback. -* Don't only emit server close event once (Issue #1276, https://github.com/vkarpov15). -* NODE-464 Updated mongodb-core to 1.1.31 that uses a single socket connection to arbiters and hidden servers as well as emitting all event correctly. - -2.0.31 2015-05-08 ------------------ -* NODE-461 Tripping on error "no chunks found for file, possibly corrupt" when there is no error. - -2.0.30 2015-05-07 ------------------ -* NODE-460 fix; don't set authMechanism for user in db.authenticate() to avoid mongoose authentication issue. - -2.0.29 2015-05-07 ------------------ -* NODE-444 Possible memory leak, too many listeners added. -* NODE-459 Auth failure using Node 0.8.28, MongoDB 3.0.2 & mongodb-node-native 1.4.35. -* Bumped mongodb-core to 1.1.26. - -2.0.28 2015-04-24 ------------------ -* Bumped mongodb-core to 1.1.25 -* Added Cursor.prototype.setCursorOption to allow for setting node specific cursor options for tailable cursors. -* NODE-430 Cursor.count() opts argument masked by var opts = {} -* NODE-406 Implemented Cursor.prototype.map function tapping into MongoClient cursor transforms. -* NODE-438 replaceOne is not returning the result.ops property as described in the docs. -* NODE-433 _read, pipe and write all open gridstore automatically if not open. -* NODE-426 ensure drain event is emitted after write function returns, fixes intermittent issues in writing files to gridstore. -* NODE-440 GridStoreStream._read() doesn't check GridStore.read() error. -* Always use readPreference = primary for findAndModify command (ignore passed in read preferences) (Issue #1274, https://github.com/vkarpov15). -* Minor fix in GridStore.exists for dealing with regular expressions searches. - -2.0.27 2015-04-07 ------------------ -* NODE-410 Correctly handle issue with pause/resume in Node 0.10.x that causes exceptions when using the Node 0.12.0 style streams. - -2.0.26 2015-04-07 ------------------ -* Implements the Common Index specification Standard API at https://github.com/mongodb/specifications/blob/master/source/index-management.rst. -* NODE-408 Expose GridStore.currentChunk.chunkNumber. - -2.0.25 2015-03-26 ------------------ -* Upgraded mongodb-core to 1.1.21, making the C++ bson code an optional dependency to the bson module. - -2.0.24 2015-03-24 ------------------ -* NODE-395 Socket Not Closing, db.close called before full set finished initalizing leading to server connections in progress not being closed properly. -* Upgraded mongodb-core to 1.1.20. - -2.0.23 2015-03-21 ------------------ -* NODE-380 Correctly return MongoError from toError method. -* Fixed issue where addCursorFlag was not correctly setting the flag on the command for mongodb-core. -* NODE-388 Changed length from method to property on order.js/unordered.js bulk operations. -* Upgraded mongodb-core to 1.1.19. - -2.0.22 2015-03-16 ------------------ -* NODE-377, fixed issue where tags would correctly be checked on secondary and nearest to filter out eligible server candidates. -* Upgraded mongodb-core to 1.1.17. - -2.0.21 2015-03-06 ------------------ -* Upgraded mongodb-core to 1.1.16 making sslValidate default to true to force validation on connection unless overriden by the user. - -2.0.20 2015-03-04 ------------------ -* Updated mongodb-core 1.1.15 to relax pickserver method. - -2.0.19 2015-03-03 ------------------ -* NODE-376 Fixes issue * Unordered batch incorrectly tracks batch size when switching batch types (Issue #1261, https://github.com/meirgottlieb) -* NODE-379 Fixes bug in cursor.count() that causes the result to always be zero for dotted collection names (Issue #1262, https://github.com/vsivsi) -* Expose MongoError from mongodb-core (Issue #1260, https://github.com/tjconcept) - -2.0.18 2015-02-27 ------------------ -* Bumped mongodb-core 1.1.14 to ensure passives are correctly added as secondaries. - -2.0.17 2015-02-27 ------------------ -* NODE-336 Added length function to ordered and unordered bulk operations to be able know the amount of current operations in bulk. -* Bumped mongodb-core 1.1.13 to ensure passives are correctly added as secondaries. - -2.0.16 2015-02-16 ------------------ -* listCollection now returns filtered result correctly removing db name for 2.6 or earlier servers. -* Bumped mongodb-core 1.1.12 to correctly work for node 0.12.0 and io.js. -* Add ability to get collection name from cursor (Issue #1253, https://github.com/vkarpov15) - -2.0.15 2015-02-02 ------------------ -* Unified behavior of listCollections results so 3.0 and pre 3.0 return same type of results. -* Bumped mongodb-core to 1.1.11 to support per document tranforms in cursors as well as relaxing the setName requirement. -* NODE-360 Aggregation cursor and command correctly passing down the maxTimeMS property. -* Added ~1.0 mongodb-tools module for test running. -* Remove the required setName for replicaset connections, if not set it will pick the first setName returned. - -2.0.14 2015-01-21 ------------------ -* Fixed some MongoClient.connect options pass through issues and added test coverage. -* Bumped mongodb-core to 1.1.9 including fixes for io.js - -2.0.13 2015-01-09 ------------------ -* Bumped mongodb-core to 1.1.8. -* Optimized query path for performance, moving Object.defineProperty outside of constructors. - -2.0.12 2014-12-22 ------------------ -* Minor fixes to listCollections to ensure correct querying of a collection when using a string. - -2.0.11 2014-12-19 ------------------ -* listCollections filters out index namespaces on < 2.8 correctly -* Bumped mongo-client to 1.1.7 - -2.0.10 2014-12-18 ------------------ -* NODE-328 fixed db.open return when no callback available issue and added test. -* NODE-327 Refactored listCollections to return cursor to support 2.8. -* NODE-327 Added listIndexes method and refactored internal methods to use the new command helper. -* NODE-335 Cannot create index for nested objects fixed by relaxing key checking for createIndex helper. -* Enable setting of connectTimeoutMS (Issue #1235, https://github.com/vkarpov15) -* Bumped mongo-client to 1.1.6 - -2.0.9 2014-12-01 ----------------- -* Bumped mongodb-core to 1.1.3 fixing global leaked variables and introducing strict across all classes. -* All classes are now strict (Issue #1233) -* NODE-324 Refactored insert/update/remove and all other crud opts to rely on internal methods to avoid any recursion. -* Fixed recursion issues in debug logging due to JSON.stringify() -* Documentation fixes (Issue #1232, https://github.com/wsmoak) -* Fix writeConcern in Db.prototype.ensureIndex (Issue #1231, https://github.com/Qard) - -2.0.8 2014-11-28 ----------------- -* NODE-322 Finished up prototype refactoring of Db class. -* NODE-322 Exposed Cursor in index.js for New Relic. - -2.0.7 2014-11-20 ----------------- -* Bumped mongodb-core to 1.1.2 fixing a UTF8 encoding issue for collection names. -* NODE-318 collection.update error while setting a function with serializeFunctions option. -* Documentation fixes. - -2.0.6 2014-11-14 ----------------- -* Refactored code to be prototype based instead of privileged methods. -* Bumped mongodb-core to 1.1.1 to take advantage of the prototype based refactorings. -* Implemented missing aspects of the CRUD specification. -* Fixed documentation issues. -* Fixed global leak REFERENCE_BY_ID in gridfs grid_store (Issue #1225, https://github.com/j) -* Fix LearnBoost/mongoose#2313: don't let user accidentally clobber geoNear params (Issue #1223, https://github.com/vkarpov15) - -2.0.5 2014-10-29 ----------------- -* Minor fixes to documentation and generation of documentation. -* NODE-306 (No results in aggregation cursor when collection name contains a dot), Merged code for cursor and aggregation cursor. - -2.0.4 2014-10-23 ----------------- -* Allow for single replicaset seed list with no setName specified (Issue #1220, https://github.com/imaman) -* Made each rewind on each call allowing for re-using the cursor. -* Fixed issue where incorrect iterations would happen on each for extensive batchSizes. -* NODE-301 specifying maxTimeMS on find causes all fields to be omitted from result. - -2.0.3 2014-10-14 ----------------- -* NODE-297 Aggregate Broken for case of pipeline with no options. - -2.0.2 2014-10-08 ----------------- -* Bumped mongodb-core to 1.0.2. -* Fixed bson module dependency issue by relying on the mongodb-core one. -* Use findOne instead of find followed by nextObject (Issue #1216, https://github.com/sergeyksv) - -2.0.1 2014-10-07 ----------------- -* Dependency fix - -2.0.0 2014-10-07 ----------------- -* First release of 2.0 driver - -2.0.0-alpha2 2014-10-02 ------------------------ -* CRUD API (insertOne, insertMany, updateOne, updateMany, removeOne, removeMany, bulkWrite, findOneAndDelete, findOneAndUpdate, findOneAndReplace) -* Cluster Management Spec compatible. - -2.0.0-alpha1 2014-09-08 ------------------------ -* Insert method allows only up 1000 pr batch for legacy as well as 2.6 mode -* Streaming behavior is 0.10.x or higher with backwards compatibility using readable-stream npm package -* Gridfs stream only available through .stream() method due to overlapping names on Gridstore object and streams in 0.10.x and higher of node -* remove third result on update and remove and return the whole result document instead (getting rid of the weird 3 result parameters) - * Might break some application -* Returns the actual mongodb-core result instead of just the number of records changed for insert/update/remove -* MongoClient only has the connect method (no ability instantiate with Server, ReplSet or similar) -* Removed Grid class -* GridStore only supports w+ for metadata updates, no appending to file as it's not thread safe and can cause corruption of the data - + seek will fail if attempt to use with w or w+ - + write will fail if attempted with w+ or r - + w+ only works for updating metadata on a file -* Cursor toArray and each resets and re-runs the cursor -* FindAndModify returns whole result document instead of just value -* Extend cursor to allow for setting all the options via methods instead of dealing with the current messed up find -* Removed db.dereference method -* Removed db.cursorInfo method -* Removed db.stats method -* Removed db.collectionNames not needed anymore as it's just a specialized case of listCollections -* Removed db.collectionInfo removed due to not being compatible with new storage engines in 2.8 as they need to use the listCollections command due to system collections not working for namespaces. -* Added db.listCollections to replace several methods above - -1.4.10 2014-09-04 ------------------ -* Fixed BSON and Kerberos compilation issues -* Bumped BSON to ~0.2 always installing latest BSON 0.2.x series -* Fixed Kerberos and bumped to 0.0.4 - -1.4.9 2014-08-26 ----------------- -* Check _bsonType for Binary (Issue #1202, https://github.com/mchapman) -* Remove duplicate Cursor constructor (Issue #1201, https://github.com/KenPowers) -* Added missing parameter in the documentation (Issue #1199, https://github.com/wpjunior) -* Documented third parameter on the update callback(Issue #1196, https://github.com/gabmontes) -* NODE-240 Operations on SSL connection hang on node 0.11.x -* NODE-235 writeResult is not being passed on when error occurs in insert -* NODE-229 Allow count to work with query hints -* NODE-233 collection.save() does not support fullResult -* NODE-244 Should parseError also emit a `disconnected` event? -* NODE-246 Cursors are inefficiently constructed and consequently cannot be promisified. -* NODE-248 Crash with X509 auth -* NODE-252 Uncaught Exception in Base.__executeAllServerSpecificErrorCallbacks -* Bumped BSON parser to 0.2.12 - - -1.4.8 2014-08-01 ----------------- -* NODE-205 correctly emit authenticate event -* NODE-210 ensure no undefined connection error when checking server state -* NODE-212 correctly inherit socketTimeoutMS from replicaset when HA process adds new servers or reconnects to existing ones -* NODE-220 don't throw error if ensureIndex errors out in Gridstore -* Updated bson to 0.2.11 to ensure correct toBSON behavior when returning non object in nested classes -* Fixed test running filters -* Wrap debug log in a call to format (Issue #1187, https://github.com/andyroyle) -* False option values should not trigger w:1 (Issue #1186, https://github.com/jsdevel) -* Fix aggregatestream.close(Issue #1194, https://github.com/jonathanong) -* Fixed parsing issue for w:0 in url parser when in connection string -* Modified collection.geoNear to support a geoJSON point or legacy coordinate pair (Issue #1198, https://github.com/mmacmillan) - -1.4.7 2014-06-18 ----------------- -* Make callbacks to be executed in right domain when server comes back up (Issue #1184, https://github.com/anton-kotenko) -* Fix issue where currentOp query against mongos would fail due to mongos passing through $readPreference field to mongod (CS-X) - -1.4.6 2014-06-12 ----------------- -* Added better support for MongoClient IP6 parsing (Issue #1181, https://github.com/micovery) -* Remove options check on index creation (Issue #1179, Issue #1183, https://github.com/jdesboeufs, https://github.com/rubenvereecken) -* Added missing type check before calling optional callback function (Issue #1180) - -1.4.5 2014-05-21 ----------------- -* Added fullResult flag to insert/update/remove which will pass raw result document back. Document contents will vary depending on the server version the driver is talking to. No attempt is made to coerce a joint response. -* Fix to avoid MongoClient.connect hanging during auth when secondaries building indexes pre 2.6. -* return the destination stream in GridStore.pipe (Issue #1176, https://github.com/iamdoron) - -1.4.4 2014-05-13 ----------------- -* Bumped BSON version to use the NaN 1.0 package, fixed strict comparison issue for ObjectID -* Removed leaking global variable (Issue #1174, https://github.com/dainis) -* MongoClient respects connectTimeoutMS for initial discovery process (NODE-185) -* Fix bug with return messages larger than 16MB but smaller than max BSON Message Size (NODE-184) - -1.4.3 2014-05-01 ----------------- -* Clone options for commands to avoid polluting original options passed from Mongoose (Issue #1171, https://github.com/vkarpov15) -* Made geoNear and geoHaystackSearch only clean out allowed options from command generation (Issue #1167) -* Fixed typo for allowDiskUse (Issue #1168, https://github.com/joaofranca) -* A 'mapReduce' function changed 'function' to instance '\' of 'Code' class (Issue #1165, https://github.com/exabugs) -* Made findAndModify set sort only when explicitly set (Issue #1163, https://github.com/sars) -* Rewriting a gridStore file by id should use a new filename if provided (Issue #1169, https://github.com/vsivsi) - -1.4.2 2014-04-15 ----------------- -* Fix for inheritance of readPreferences from MongoClient NODE-168/NODE-169 -* Merged in fix for ping strategy to avoid hitting non-pinged servers (Issue #1161, https://github.com/vaseker) -* Merged in fix for correct debug output for connection messages (Issue #1158, https://github.com/vaseker) -* Fixed global variable leak (Issue #1160, https://github.com/vaseker) - -1.4.1 2014-04-09 ----------------- -* Correctly emit joined event when primary change -* Add _id to documents correctly when using bulk operations - -1.4.0 2014-04-03 ----------------- -* All node exceptions will no longer be caught if on('error') is defined -* Added X509 auth support -* Fix for MongoClient connection timeout issue (NODE-97) -* Pass through error messages from parseError instead of just text (Issue #1125) -* Close db connection on error (Issue #1128, https://github.com/benighted) -* Fixed documentation generation -* Added aggregation cursor for 2.6 and emulated cursor for pre 2.6 (uses stream2) -* New Bulk API implementation using write commands for 2.6 and down converts for pre 2.6 -* Insert/Update/Remove using new write commands when available -* Added support for new roles based API's in 2.6 for addUser/removeUser -* Added bufferMaxEntries to start failing if the buffer hits the specified number of entries -* Upgraded BSON parser to version 0.2.7 to work with < 0.11.10 C++ API changes -* Support for OP_LOG_REPLAY flag (NODE-94) -* Fixes for SSL HA ping and discovery. -* Uses createIndexes if available for ensureIndex/createIndex -* Added parallelCollectionScan method to collection returning CommandCursor instances for cursors -* Made CommandCursor behave as Readable stream. -* Only Db honors readPreference settings, removed Server.js legacy readPreference settings due to user confusion. -* Reconnect event emitted by ReplSet/Mongos/Server after reconnect and before replaying of buffered operations. -* GridFS buildMongoObject returns error on illegal md5 (NODE-157, https://github.com/iantocristian) -* Default GridFS chunk size changed to (255 * 1024) bytes to optimize for collections defaulting to power of 2 sizes on 2.6. -* Refactored commands to all go through command function ensuring consistent command execution. -* Fixed issues where readPreferences where not correctly passed to mongos. -* Catch error == null and make err detection more prominent (NODE-130) -* Allow reads from arbiter for single server connection (NODE-117) -* Handle error coming back with no documents (NODE-130) -* Correctly use close parameter in Gridstore.write() (NODE-125) -* Throw an error on a bulk find with no selector (NODE-129, https://github.com/vkarpov15) -* Use a shallow copy of options in find() (NODE-124, https://github.com/vkarpov15) -* Fix statistical strategy (NODE-158, https://github.com/vkarpov15) -* GridFS off-by-one bug in lastChunkNumber() causes uncaught throw and data loss (Issue #1154, https://github.com/vsivsi) -* GridStore drops passed `aliases` option, always results in `null` value in GridFS files (Issue #1152, https://github.com/vsivsi) -* Remove superfluous connect object copying in index.js (Issue #1145, https://github.com/thomseddon) -* Do not return false when the connection buffer is still empty (Issue #1143, https://github.com/eknkc) -* Check ReadPreference object on ReplSet.canRead (Issue #1142, https://github.com/eknkc) -* Fix unpack error on _executeQueryCommand (Issue #1141, https://github.com/eknkc) -* Close db on failed connect so node can exit (Issue #1128, https://github.com/benighted) -* Fix global leak with _write_concern (Issue #1126, https://github.com/shanejonas) - -1.3.19 2013-08-21 ------------------ -* Correctly rethrowing errors after change from event emission to callbacks, compatibility with 0.10.X domains without breaking 0.8.X support. -* Small fix to return the entire findAndModify result as the third parameter (Issue #1068) -* No removal of "close" event handlers on server reconnect, emits "reconnect" event when reconnection happens. Reconnect Only applies for single server connections as of now as semantics for ReplSet and Mongos is not clear (Issue #1056) - -1.3.18 2013-08-10 ------------------ -* Fixed issue when throwing exceptions in MongoClient.connect/Db.open (Issue #1057) -* Fixed an issue where _events is not cleaned up correctly causing a slow steady memory leak. - -1.3.17 2013-08-07 ------------------ -* Ignore return commands that have no registered callback -* Made collection.count not use the db.command function -* Fix throw exception on ping command (Issue #1055) - -1.3.16 2013-08-02 ------------------ -* Fixes connection issue where lots of connections would happen if a server is in recovery mode during connection (Issue #1050, NODE-50, NODE-51) -* Bug in unlink mulit filename (Issue #1054) - -1.3.15 2013-08-01 ------------------ -* Memory leak issue due to node Issue #4390 where _events[id] is set to undefined instead of deleted leading to leaks in the Event Emitter over time - -1.3.14 2013-08-01 ------------------ -* Fixed issue with checkKeys where it would error on X.X - -1.3.13 2013-07-31 ------------------ -* Added override for checkKeys on insert/update (Warning will expose you to injection attacks) (Issue #1046) -* BSON size checking now done pre serialization (Issue #1037) -* Added isConnected returns false when no connection Pool exists (Issue #1043) -* Unified command handling to ensure same handling (Issue #1041, #1042) -* Correctly emit "open" and "fullsetup" across all Db's associated with Mongos, ReplSet or Server (Issue #1040) -* Correctly handles bug in authentication when attempting to connect to a recovering node in a replicaset. -* Correctly remove recovering servers from available servers in replicaset. Piggybacks on the ping command. -* Removed findAndModify chaining to be compliant with behavior in other official drivers and to fix a known mongos issue. -* Fixed issue with Kerberos authentication on Windows for re-authentication. -* Fixed Mongos failover behavior to correctly throw out old servers. -* Ensure stored queries/write ops are executed correctly after connection timeout -* Added promoteLongs option for to allow for overriding the promotion of Longs to Numbers and return the actual Long. - -1.3.12 2013-07-19 ------------------ -* Fixed issue where timeouts sometimes would behave wrongly (Issue #1032) -* Fixed bug with callback third parameter on some commands (Issue #1033) -* Fixed possible issue where killcursor command might leave hanging functions -* Fixed issue where Mongos was not correctly removing dead servers from the pool of eligable servers -* Throw error if dbName or collection name contains null character (at command level and at collection level) -* Updated bson parser to 0.2.1 with security fix and non-promotion of Long values to javascript Numbers (once a long always a long) - -1.3.11 2013-07-04 ------------------ -* Fixed errors on geoNear and geoSearch (Issue #1024, https://github.com/ebensing) -* Add driver version to export (Issue #1021, https://github.com/aheckmann) -* Add text to readpreference obedient commands (Issue #1019) -* Drivers should check the query failure bit even on getmore response (Issue #1018) -* Map reduce has incorrect expectations of 'inline' value for 'out' option (Issue #1016, https://github.com/rcotter) -* Support SASL PLAIN authentication (Issue #1009) -* Ability to use different Service Name on the driver for Kerberos Authentication (Issue #1008) -* Remove unnecessary octal literal to allow the code to run in strict mode (Issue #1005, https://github.com/jamesallardice) -* Proper handling of recovering nodes (when they go into recovery and when they return from recovery, Issue #1027) - -1.3.10 2013-06-17 ------------------ -* Guard against possible undefined in server::canCheckoutWriter (Issue #992, https://github.com/willyaranda) -* Fixed some duplicate test names (Issue #993, https://github.com/kawanet) -* Introduced write and read concerns for GridFS (Issue #996) -* Fixed commands not correctly respecting Collection level read preference (Issue #995, #999) -* Fixed issue with pool size on replicaset connections (Issue #1000) -* Execute all query commands on master switch (Issue #1002, https://github.com/fogaztuc) - -1.3.9 2013-06-05 ----------------- -* Fixed memory leak when findAndModify errors out on w>1 and chained callbacks not properly cleaned up. - -1.3.8 2013-05-31 ----------------- -* Fixed issue with socket death on windows where it emits error event instead of close event (Issue #987) -* Emit authenticate event on db after authenticate method has finished on db instance (Issue #984) -* Allows creation of MongoClient and do new MongoClient().connect(..). Emits open event when connection correct allowing for apps to react on event. - -1.3.7 2013-05-29 ----------------- -* After reconnect, tailable getMores go on inconsistent connections (Issue #981, #982, https://github.com/glasser) -* Updated Bson to 0.1.9 to fix ARM support (Issue #985) - -1.3.6 2013-05-21 ----------------- -* Fixed issue where single server reconnect attempt would throw due to missing options variable (Issue #979) -* Fixed issue where difference in ismaster server name and seed list caused connections issues, (Issue #976) - -1.3.5 2013-05-14 ----------------- -* Fixed issue where HA for replicaset would pick the same broken connection when attempting to ping the replicaset causing the replicaset to never recover. - -1.3.4 2013-05-14 ----------------- -* Fixed bug where options not correctly passed in for uri parser (Issue #973, https://github.com/supershabam) -* Fixed bug when passing a named index hint (Issue #974) - -1.3.3 2013-05-09 ----------------- -* Fixed auto-reconnect issue with single server instance. - -1.3.2 2013-05-08 ----------------- -* Fixes for an issue where replicaset would be pronounced dead when high priority primary caused double elections. - -1.3.1 2013-05-06 ----------------- -* Fix for replicaset consisting of primary/secondary/arbiter with priority applied failing to reconnect properly -* Applied auth before server instance is set as connected when single server connection -* Throw error if array of documents passed to save method - -1.3.0 2013-04-25 ----------------- -* Whole High availability handling for Replicaset, Server and Mongos connections refactored to ensure better handling of failover cases. -* Fixed issue where findAndModify would not correctly skip issuing of chained getLastError (Issue #941) -* Fixed throw error issue on errors with findAndModify during write out operation (Issue #939, https://github.com/autopulated) -* Gridstore.prototype.writeFile now returns gridstore object correctly (Issue #938) -* Kerberos support is now an optional module that allows for use of GSSAPI authentication using MongoDB Subscriber edition -* Fixed issue where cursor.toArray could blow the stack on node 0.10.X (#950) - -1.2.14 2013-03-14 ------------------ -* Refactored test suite to speed up running of replicaset tests -* Fix of async error handling when error happens in callback (Issue #909, https://github.com/medikoo) -* Corrected a slaveOk setting issue (Issue #906, #905) -* Fixed HA issue where ping's would not go to correct server on HA server connection failure. -* Uses setImmediate if on 0.10 otherwise nextTick for cursor stream -* Fixed race condition in Cursor stream (NODE-31) -* Fixed issues related to node 0.10 and process.nextTick now correctly using setImmediate where needed on node 0.10 -* Added support for maxMessageSizeBytes if available (DRIVERS-1) -* Added support for authSource (2.4) to MongoClient URL and db.authenticate method (DRIVER-69/NODE-34) -* Fixed issue in GridStore seek and GridStore read to correctly work on multiple seeks (Issue #895) - -1.2.13 2013-02-22 ------------------ -* Allow strategy 'none' for repliaset if no strategy wanted (will default to round robin selection of servers on a set readPreference) -* Fixed missing MongoErrors on some cursor methods (Issue #882) -* Correctly returning a null for the db instance on MongoClient.connect when auth fails (Issue #890) -* Added dropTarget option support for renameCollection/rename (Issue #891, help from https://github.com/jbottigliero) -* Fixed issue where connection using MongoClient.connect would fail if first server did not exist (Issue #885) - -1.2.12 2013-02-13 ------------------ -* Added limit/skip options to Collection.count (Issue #870) -* Added applySkipLimit option to Cursor.count (Issue #870) -* Enabled ping strategy as default for Replicaset if none specified (Issue #876) -* Should correctly pick nearest server for SECONDARY/SECONDARY_PREFERRED/NEAREST (Issue #878) - -1.2.11 2013-01-29 ------------------ -* Added fixes for handling type 2 binary due to PHP driver (Issue #864) -* Moved callBackStore to Base class to have single unified store (Issue #866) -* Ping strategy now reuses sockets unless they are closed by the server to avoid overhead - -1.2.10 2013-01-25 ------------------ -* Merged in SSL support for 2.4 supporting certificate validation and presenting certificates to the server. -* Only open a new HA socket when previous one dead (Issue #859, #857) -* Minor fixes - -1.2.9 2013-01-15 ----------------- -* Fixed bug in SSL support for MongoClient/Db.connect when discovering servers (Issue #849) -* Connection string with no db specified should default to admin db (Issue #848) -* Support port passed as string to Server class (Issue #844) -* Removed noOpen support for MongoClient/Db.connect as auto discovery of servers for Mongod/Mongos makes it not possible (Issue #842) -* Included toError wrapper code moved to utils.js file (Issue #839, #840) -* Rewrote cursor handling to avoid process.nextTick using trampoline instead to avoid stack overflow, speedup about 40% - -1.2.8 2013-01-07 ----------------- -* Accept function in a Map Reduce scope object not only a function string (Issue #826, https://github.com/aheckmann) -* Typo in db.authenticate caused a check (for provided connection) to return false, causing a connection AND onAll=true to be passed into __executeQueryCommand downstream (Issue #831, https://github.com/m4tty) -* Allow gridfs objects to use non ObjectID ids (Issue #825, https://github.com/nailgun) -* Removed the double wrap, by not passing an Error object to the wrap function (Issue #832, https://github.com/m4tty) -* Fix connection leak (gh-827) for HA replicaset health checks (Issue #833, https://github.com/aheckmann) -* Modified findOne to use nextObject instead of toArray avoiding a nextTick operation (Issue #836) -* Fixes for cursor stream to avoid multiple getmore issues when one in progress (Issue #818) -* Fixes .open replaying all backed up commands correctly if called after operations performed, (Issue #829 and #823) - -1.2.7 2012-12-23 ----------------- -* Rolled back batches as they hang in certain situations -* Fixes for NODE-25, keep reading from secondaries when primary goes down - -1.2.6 2012-12-21 ----------------- -* domain sockets shouldn't require a port arg (Issue #815, https://github.com/aheckmann) -* Cannot read property 'info' of null (Issue #809, https://github.com/thesmart) -* Cursor.each should work in batches (Issue #804, https://github.com/Swatinem) -* Cursor readPreference bug for non-supported read preferences (Issue #817) - -1.2.5 2012-12-12 ----------------- -* Fixed ssl regression, added more test coverage (Issue #800) -* Added better error reporting to the Db.connect if no valid serverConfig setup found (Issue #798) - -1.2.4 2012-12-11 ----------------- -* Fix to ensure authentication is correctly applied across all secondaries when using MongoClient. - -1.2.3 2012-12-10 ----------------- -* Fix for new replicaset members correctly authenticating when being added (Issue #791, https://github.com/m4tty) -* Fixed seek issue in gridstore when using stream (Issue #790) - -1.2.2 2012-12-03 ----------------- -* Fix for journal write concern not correctly being passed under some circumstances. -* Fixed correct behavior and re-auth for servers that get stepped down (Issue #779). - -1.2.1 2012-11-30 ----------------- -* Fix for double callback on insert with w:0 specified (Issue #783) -* Small cleanup of urlparser. - -1.2.0 2012-11-27 ----------------- -* Honor connectTimeoutMS option for replicasets (Issue #750, https://github.com/aheckmann) -* Fix ping strategy regression (Issue #738, https://github.com/aheckmann) -* Small cleanup of code (Issue #753, https://github.com/sokra/node-mongodb-native) -* Fixed index declaration using objects/arrays from other contexts (Issue #755, https://github.com/sokra/node-mongodb-native) -* Intermittent (and rare) null callback exception when using ReplicaSets (Issue #752) -* Force correct setting of read_secondary based on the read preference (Issue #741) -* If using read preferences with secondaries queries will not fail if primary is down (Issue #744) -* noOpen connection for Db.connect removed as not compatible with autodetection of Mongo type -* Mongos connection with auth not working (Issue #737) -* Use the connect method directly from the require. require('mongodb')("mongodb://localhost:27017/db") -* new MongoClient introduced as the point of connecting to MongoDB's instead of the Db - * open/close/db/connect methods implemented -* Implemented common URL connection format using MongoClient.connect allowing for simialar interface across all drivers. -* Fixed a bug with aggregation helper not properly accepting readPreference - -1.1.11 2012-10-10 ------------------ -* Removed strict mode and introduced normal handling of safe at DB level. - -1.1.10 2012-10-08 ------------------ -* fix Admin.serverStatus (Issue #723, https://github.com/Contra) -* logging on connection open/close(Issue #721, https://github.com/asiletto) -* more fixes for windows bson install (Issue #724) - -1.1.9 2012-10-05 ----------------- -* Updated bson to 0.1.5 to fix build problem on sunos/windows. - -1.1.8 2012-10-01 ----------------- -* Fixed db.eval to correctly handle system.js global javascript functions (Issue #709) -* Cleanup of non-closing connections (Issue #706) -* More cleanup of connections under replicaset (Issue #707, https://github.com/elbert3) -* Set keepalive on as default, override if not needed -* Cleanup of jsbon install to correctly build without install.js script (https://github.com/shtylman) -* Added domain socket support new Server("/tmp/mongodb.sock") style - -1.1.7 2012-09-10 ----------------- -* Protect against starting PingStrategy being called more than once (Issue #694, https://github.com/aheckmann) -* Make PingStrategy interval configurable (was 1 second, relaxed to 5) (Issue #693, https://github.com/aheckmann) -* Made PingStrategy api more consistant, callback to start/stop methods are optional (Issue #693, https://github.com/aheckmann) -* Proper stopping of strategy on replicaset stop -* Throw error when gridstore file is not found in read mode (Issue #702, https://github.com/jbrumwell) -* Cursor stream resume now using nextTick to avoid duplicated records (Issue #696) - -1.1.6 2012-09-01 ----------------- -* Fix for readPreference NEAREST for replicasets (Issue #693, https://github.com/aheckmann) -* Emit end correctly on stream cursor (Issue #692, https://github.com/Raynos) - -1.1.5 2012-08-29 ----------------- -* Fix for eval on replicaset Issue #684 -* Use helpful error msg when native parser not compiled (Issue #685, https://github.com/aheckmann) -* Arbiter connect hotfix (Issue #681, https://github.com/fengmk2) -* Upgraded bson parser to 0.1.2 using gyp, deprecated support for node 0.4.X -* Added name parameter to createIndex/ensureIndex to be able to override index names larger than 128 bytes -* Added exhaust option for find for feature completion (not recommended for normal use) -* Added tailableRetryInterval to find for tailable cursors to allow to control getMore retry time interval -* Fixes for read preferences when using MongoS to correctly handle no read preference set when iterating over a cursor (Issue #686) - -1.1.4 2012-08-12 ----------------- -* Added Mongos connection type with a fallback list for mongos proxies, supports ha (on by default) and will attempt to reconnect to failed proxies. -* Documents can now have a toBSON method that lets the user control the serialization behavior for documents being saved. -* Gridstore instance object now works as a readstream or writestream (thanks to code from Aaron heckmann (https://github.com/aheckmann/gridfs-stream)). -* Fix gridfs readstream (Issue #607, https://github.com/tedeh). -* Added disableDriverBSONSizeCheck property to Server.js for people who wish to push the inserts to the limit (Issue #609). -* Fixed bug where collection.group keyf given as Code is processed as a regular object (Issue #608, https://github.com/rrusso2007). -* Case mismatch between driver's ObjectID and mongo's ObjectId, allow both (Issue #618). -* Cleanup map reduce (Issue #614, https://github.com/aheckmann). -* Add proper error handling to gridfs (Issue #615, https://github.com/aheckmann). -* Ensure cursor is using same connection for all operations to avoid potential jump of servers when using replicasets. -* Date identification handled correctly in bson js parser when running in vm context. -* Documentation updates -* GridStore filename not set on read (Issue #621) -* Optimizations on the C++ bson parser to fix a potential memory leak and avoid non-needed calls -* Added support for awaitdata for tailable cursors (Issue #624) -* Implementing read preference setting at collection and cursor level - * collection.find().setReadPreference(Server.SECONDARY_PREFERRED) - * db.collection("some", {readPreference:Server.SECONDARY}) -* Replicaset now returns when the master is discovered on db.open and lets the rest of the connections happen asynchronous. - * ReplSet/ReplSetServers emits "fullsetup" when all servers have been connected to -* Prevent callback from executing more than once in getMore function (Issue #631, https://github.com/shankar0306) -* Corrupt bson messages now errors out to all callbacks and closes up connections correctly, Issue #634 -* Replica set member status update when primary changes bug (Issue #635, https://github.com/alinsilvian) -* Fixed auth to work better when multiple connections are involved. -* Default connection pool size increased to 5 connections. -* Fixes for the ReadStream class to work properly with 0.8 of Node.js -* Added explain function support to aggregation helper -* Added socketTimeoutMS and connectTimeoutMS to socket options for repl_set.js and server.js -* Fixed addUser to correctly handle changes in 2.2 for getLastError authentication required -* Added index to gridstore chunks on file_id (Issue #649, https://github.com/jacobbubu) -* Fixed Always emit db events (Issue #657) -* Close event not correctly resets DB openCalled variable to allow reconnect -* Added open event on connection established for replicaset, mongos and server -* Much faster BSON C++ parser thanks to Lucasfilm Singapore. -* Refactoring of replicaset connection logic to simplify the code. -* Add `options.connectArbiter` to decide connect arbiters or not (Issue #675) -* Minor optimization for findAndModify when not using j,w or fsync for safe - -1.0.2 2012-05-15 ----------------- -* Reconnect functionality for replicaset fix for mongodb 2.0.5 - -1.0.1 2012-05-12 ----------------- -* Passing back getLastError object as 3rd parameter on findAndModify command. -* Fixed a bunch of performance regressions in objectId and cursor. -* Fixed issue #600 allowing for single document delete to be passed in remove command. - -1.0.0 2012-04-25 ----------------- -* Fixes to handling of failover on server error -* Only emits error messages if there are error listeners to avoid uncaught events -* Server.isConnected using the server state variable not the connection pool state - -0.9.9.8 2012-04-12 ------------------- -* _id=0 is being turned into an ObjectID (Issue #551) -* fix for error in GridStore write method (Issue #559) -* Fix for reading a GridStore from arbitrary, non-chunk aligned offsets, added test (Issue #563, https://github.com/subroutine) -* Modified limitRequest to allow negative limits to pass through to Mongo, added test (Issue #561) -* Corrupt GridFS files when chunkSize < fileSize, fixed concurrency issue (Issue #555) -* Handle dead tailable cursors (Issue #568, https://github.com/aheckmann) -* Connection pools handles closing themselves down and clearing the state -* Check bson size of documents against maxBsonSize and throw client error instead of server error, (Issue #553) -* Returning update status document at the end of the callback for updates, (Issue #569) -* Refactor use of Arguments object to gain performance (Issue #574, https://github.com/AaronAsAChimp) - -0.9.9.7 2012-03-16 ------------------- -* Stats not returned from map reduce with inline results (Issue #542) -* Re-enable testing of whether or not the callback is called in the multi-chunk seek, fix small GridStore bug (Issue #543, https://github.com/pgebheim) -* Streaming large files from GridFS causes truncation (Issue #540) -* Make callback type checks agnostic to V8 context boundaries (Issue #545) -* Correctly throw error if an attempt is made to execute an insert/update/remove/createIndex/ensureIndex with safe enabled and no callback -* Db.open throws if the application attemps to call open again without calling close first - -0.9.9.6 2012-03-12 ------------------- -* BSON parser is externalized in it's own repository, currently using git master -* Fixes for Replicaset connectivity issue (Issue #537) -* Fixed issues with node 0.4.X vs 0.6.X (Issue #534) -* Removed SimpleEmitter and replaced with standard EventEmitter -* GridStore.seek fails to change chunks and call callback when in read mode (Issue #532) - -0.9.9.5 2012-03-07 ------------------- -* Merged in replSetGetStatus helper to admin class (Issue #515, https://github.com/mojodna) -* Merged in serverStatus helper to admin class (Issue #516, https://github.com/mojodna) -* Fixed memory leak in C++ bson parser (Issue #526) -* Fix empty MongoError "message" property (Issue #530, https://github.com/aheckmann) -* Cannot save files with the same file name to GridFS (Issue #531) - -0.9.9.4 2012-02-26 ------------------- -* bugfix for findAndModify: Error: corrupt bson message < 5 bytes long (Issue #519) - -0.9.9.3 2012-02-23 ------------------- -* document: save callback arguments are both undefined, (Issue #518) -* Native BSON parser install error with npm, (Issue #517) - -0.9.9.2 2012-02-17 ------------------- -* Improved detection of Buffers using Buffer.isBuffer instead of instanceof. -* Added wrap error around db.dropDatabase to catch all errors (Issue #512) -* Added aggregate helper to collection, only for MongoDB >= 2.1 - -0.9.9.1 2012-02-15 ------------------- -* Better handling of safe when using some commands such as createIndex, ensureIndex, addUser, removeUser, createCollection. -* Mapreduce now throws error if out parameter is not specified. - -0.9.9 2012-02-13 ----------------- -* Added createFromTime method on ObjectID to allow for queries against _id more easily using the timestamp. -* Db.close(true) now makes connection unusable as it's been force closed by app. -* Fixed mapReduce and group functions to correctly send slaveOk on queries. -* Fixes for find method to correctly work with find(query, fields, callback) (Issue #506). -* A fix for connection error handling when using the SSL on MongoDB. - -0.9.8-7 2012-02-06 ------------------- -* Simplified findOne to use the find command instead of the custom code (Issue #498). -* BSON JS parser not also checks for _bsonType variable in case BSON object is in weird scope (Issue #495). - -0.9.8-6 2012-02-04 ------------------- -* Removed the check for replicaset change code as it will never work with node.js. - -0.9.8-5 2012-02-02 ------------------- -* Added geoNear command to Collection. -* Added geoHaystackSearch command to Collection. -* Added indexes command to collection to retrieve the indexes on a Collection. -* Added stats command to collection to retrieve the statistics on a Collection. -* Added listDatabases command to admin object to allow retrieval of all available dbs. -* Changed createCreateIndexCommand to work better with options. -* Fixed dereference method on Db class to correctly dereference Db reference objects. -* Moved connect object onto Db class(Db.connect) as well as keeping backward compatibility. -* Removed writeBuffer method from gridstore, write handles switching automatically now. -* Changed readBuffer to read on Gridstore, Gridstore now only supports Binary Buffers no Strings anymore. -* Moved Long class to bson directory. - -0.9.8-4 2012-01-28 ------------------- -* Added reIndex command to collection and db level. -* Added support for $returnKey, $maxScan, $min, $max, $showDiskLoc, $comment to cursor and find/findOne methods. -* Added dropDups and v option to createIndex and ensureIndex. -* Added isCapped method to Collection. -* Added indexExists method to Collection. -* Added findAndRemove method to Collection. -* Fixed bug for replicaset connection when no active servers in the set. -* Fixed bug for replicaset connections when errors occur during connection. -* Merged in patch for BSON Number handling from Lee Salzman, did some small fixes and added test coverage. - -0.9.8-3 2012-01-21 ------------------- -* Workaround for issue with Object.defineProperty (Issue #484) -* ObjectID generation with date does not set rest of fields to zero (Issue #482) - -0.9.8-2 2012-01-20 ------------------- -* Fixed a missing this in the ReplSetServers constructor. - -0.9.8-1 2012-01-17 ------------------- -* FindAndModify bug fix for duplicate errors (Issue #481) - -0.9.8 2012-01-17 ----------------- -* Replicasets now correctly adjusts to live changes in the replicaset configuration on the servers, reconnecting correctly. - * Set the interval for checking for changes setting the replicaSetCheckInterval property when creating the ReplSetServers instance or on db.serverConfig.replicaSetCheckInterval. (default 1000 miliseconds) -* Fixes formattedOrderClause in collection.js to accept a plain hash as a parameter (Issue #469) https://github.com/tedeh -* Removed duplicate code for formattedOrderClause and moved to utils module -* Pass in poolSize for ReplSetServers to set default poolSize for new replicaset members -* Bug fix for BSON JS deserializer. Isolating the eval functions in separate functions to avoid V8 deoptimizations -* Correct handling of illegal BSON messages during deserialization -* Fixed Infinite loop when reading GridFs file with no chunks (Issue #471) -* Correctly update existing user password when using addUser (Issue #470) - -0.9.7.3-5 2012-01-04 --------------------- -* Fix for RegExp serialization for 0.4.X where typeof /regexp/ == 'function' vs in 0.6.X typeof /regexp/ == 'object' -* Don't allow keepAlive and setNoDelay for 0.4.X as it throws errors - -0.9.7.3-4 2012-01-04 --------------------- -* Chased down potential memory leak on findAndModify, Issue #467 (node.js removeAllListeners leaves the key in the _events object, node.js bug on eventlistener?, leads to extremely slow memory leak on listener object) -* Sanity checks for GridFS performance with benchmark added - -0.9.7.3-3 2012-01-04 --------------------- -* Bug fixes for performance issues going form 0.9.6.X to 0.9.7.X on linux -* BSON bug fixes for performance - -0.9.7.3-2 2012-01-02 --------------------- -* Fixed up documentation to reflect the preferred way of instantiating bson types -* GC bug fix for JS bson parser to avoid stop-and-go GC collection - -0.9.7.3-1 2012-01-02 --------------------- -* Fix to make db.bson_serializer and db.bson_deserializer work as it did previously - -0.9.7.3 2011-12-30 --------------------- -* Moved BSON_BINARY_SUBTYPE_DEFAULT from BSON object to Binary object and removed the BSON_BINARY_ prefixes -* Removed Native BSON types, C++ parser uses JS types (faster due to cost of crossing the JS-C++ barrier for each call) -* Added build fix for 0.4.X branch of Node.js where GetOwnPropertyNames is not defined in v8 -* Fix for wire protocol parser for corner situation where the message is larger than the maximum socket buffer in node.js (Issue #464, #461, #447) -* Connection pool status set to connected on poolReady, isConnected returns false on anything but connected status (Issue #455) - -0.9.7.2-5 2011-12-22 --------------------- -* Brand spanking new Streaming Cursor support Issue #458 (https://github.com/christkv/node-mongodb-native/pull/458) thanks to Mr Aaron Heckmann - -0.9.7.2-4 2011-12-21 --------------------- -* Refactoring of callback code to work around performance regression on linux -* Fixed group function to correctly use the command mode as default - -0.9.7.2-3 2011-12-18 --------------------- -* Fixed error handling for findAndModify while still working for mongodb 1.8.6 (Issue #450). -* Allow for force send query to primary, pass option (read:'primary') on find command. - * ``find({a:1}, {read:'primary'}).toArray(function(err, items) {});`` - -0.9.7.2-2 2011-12-16 --------------------- -* Fixes infinite streamRecords QueryFailure fix when using Mongos (Issue #442) - -0.9.7.2-1 2011-12-16 --------------------- -* ~10% perf improvement for ObjectId#toHexString (Issue #448, https://github.com/aheckmann) -* Only using process.nextTick on errors emitted on callbacks not on all parsing, reduces number of ticks in the driver -* Changed parsing off bson messages to use process.nextTick to do bson parsing in batches if the message is over 10K as to yield more time to the event look increasing concurrency on big mongoreply messages with multiple documents - -0.9.7.2 2011-12-15 ------------------- -* Added SSL support for future version of mongodb (VERY VERY EXPERIMENTAL) - * pass in the ssl:true option to the server or replicaset server config to enable - * a bug either in mongodb or node.js does not allow for more than 1 connection pr db instance (poolSize:1). -* Added getTimestamp() method to objectID that returns a date object -* Added finalize function to collection.group - * function group (keys, condition, initial, reduce, finalize, command, callback) -* Reaper no longer using setTimeout to handle reaping. Triggering is done in the general flow leading to predictable behavior. - * reaperInterval, set interval for reaper (default 10000 miliseconds) - * reaperTimeout, set timeout for calls (default 30000 miliseconds) - * reaper, enable/disable reaper (default false) -* Work around for issues with findAndModify during high concurrency load, insure that the behavior is the same across the 1.8.X branch and 2.X branch of MongoDb -* Reworked multiple db's sharing same connection pool to behave correctly on error, timeout and close -* EnsureIndex command can be executed without a callback (Issue #438) -* Eval function no accepts options including nolock (Issue #432) - * eval(code, parameters, options, callback) (where options = {nolock:true}) - -0.9.7.1-4 2011-11-27 --------------------- -* Replaced install.sh with install.js to install correctly on all supported os's - -0.9.7.1-3 2011-11-27 --------------------- -* Fixes incorrect scope for ensureIndex error wrapping (Issue #419) https://github.com/ritch - -0.9.7.1-2 2011-11-27 --------------------- -* Set statistical selection strategy as default for secondary choice. - -0.9.7.1-1 2011-11-27 --------------------- -* Better handling of single server reconnect (fixes some bugs) -* Better test coverage of single server failure -* Correct handling of callbacks on replicaset servers when firewall dropping packets, correct reconnect - -0.9.7.1 2011-11-24 ------------------- -* Better handling of dead server for single server instances -* FindOne and find treats selector == null as {}, Issue #403 -* Possible to pass in a strategy for the replicaset to pick secondary reader node - * parameter strategy - * ping (default), pings the servers and picks the one with the lowest ping time - * statistical, measures each request and pick the one with the lowest mean and std deviation -* Set replicaset read preference replicaset.setReadPreference() - * Server.READ_PRIMARY (use primary server for reads) - * Server.READ_SECONDARY (from a secondary server (uses the strategy set)) - * tags, {object of tags} -* Added replay of commands issued to a closed connection when the connection is re-established -* Fix isConnected and close on unopened connections. Issue #409, fix by (https://github.com/sethml) -* Moved reaper to db.open instead of constructor (Issue #406) -* Allows passing through of socket connection settings to Server or ReplSetServer under the option socketOptions - * timeout = set seconds before connection times out (default 0) - * noDelay = Disables the Nagle algorithm (default true) - * keepAlive = Set if keepAlive is used (default 0, which means no keepAlive, set higher than 0 for keepAlive) - * encoding = ['ascii', 'utf8', or 'base64'] (default null) -* Fixes for handling of errors during shutdown off a socket connection -* Correctly applies socket options including timeout -* Cleanup of test management code to close connections correctly -* Handle parser errors better, closing down the connection and emitting an error -* Correctly emit errors from server.js only wrapping errors that are strings - -0.9.7 2011-11-10 ----------------- -* Added priority setting to replicaset manager -* Added correct handling of passive servers in replicaset -* Reworked socket code for simpler clearer handling -* Correct handling of connections in test helpers -* Added control of retries on failure - * control with parameters retryMiliSeconds and numberOfRetries when creating a db instance -* Added reaper that will timeout and cleanup queries that never return - * control with parameters reaperInterval and reaperTimeout when creating a db instance -* Refactored test helper classes for replicaset tests -* Allows raw (no bson parser mode for insert, update, remove, find and findOne) - * control raw mode passing in option raw:true on the commands - * will return buffers with the binary bson objects -* Fixed memory leak in cursor.toArray -* Fixed bug in command creation for mongodb server with wrong scope of call -* Added db(dbName) method to db.js to allow for reuse of connections against other databases -* Serialization of functions in an object is off by default, override with parameter - * serializeFunctions [true/false] on db level, collection level or individual insert/update/findAndModify -* Added Long.fromString to c++ class and fixed minor bug in the code (Test case for $gt operator on 64-bit integers, Issue #394) -* FindOne and find now share same code execution and will work in the same manner, Issue #399 -* Fix for tailable cursors, Issue #384 -* Fix for Cursor rewind broken, Issue #389 -* Allow Gridstore.exist to query using regexp, Issue #387, fix by (https://github.com/kaij) -* Updated documentation on https://github.com/christkv/node-mongodb-native -* Fixed toJSON methods across all objects for BSON, Binary return Base64 Encoded data - -0.9.6-22 2011-10-15 -------------------- -* Fixed bug in js bson parser that could cause wrong object size on serialization, Issue #370 -* Fixed bug in findAndModify that did not throw error on replicaset timeout, Issue #373 - -0.9.6-21 2011-10-05 -------------------- -* Reworked reconnect code to work correctly -* Handling errors in different parts of the code to ensure that it does not lock the connection -* Consistent error handling for Object.createFromHexString for JS and C++ - -0.9.6-20 2011-10-04 -------------------- -* Reworked bson.js parser to get rid off Array.shift() due to it allocating new memory for each call. Speedup varies between 5-15% depending on doc -* Reworked bson.cc to throw error when trying to serialize js bson types -* Added MinKey, MaxKey and Double support for JS and C++ parser -* Reworked socket handling code to emit errors on unparsable messages -* Added logger option for Db class, lets you pass in a function in the shape - { - log : function(message, object) {}, - error : function(errorMessage, errorObject) {}, - debug : function(debugMessage, object) {}, - } - - Usage is new Db(new Server(..), {logger: loggerInstance}) - -0.9.6-19 2011-09-29 -------------------- -* Fixing compatibility issues between C++ bson parser and js parser -* Added Symbol support to C++ parser -* Fixed socket handling bug for seldom misaligned message from mongodb -* Correctly handles serialization of functions using the C++ bson parser - -0.9.6-18 2011-09-22 -------------------- -* Fixed bug in waitForConnection that would lead to 100% cpu usage, Issue #352 - -0.9.6-17 2011-09-21 -------------------- -* Fixed broken exception test causing bamboo to hang -* Handling correctly command+lastError when both return results as in findAndModify, Issue #351 - -0.9.6-16 2011-09-14 -------------------- -* Fixing a bunch of issues with compatibility with MongoDB 2.0.X branch. Some fairly big changes in behavior from 1.8.X to 2.0.X on the server. -* Error Connection MongoDB V2.0.0 with Auth=true, Issue #348 - -0.9.6-15 2011-09-09 -------------------- -* Fixed issue where pools would not be correctly cleaned up after an error, Issue #345 -* Fixed authentication issue with secondary servers in Replicaset, Issue #334 -* Duplicate replica-set servers when omitting port, Issue #341 -* Fixing findAndModify to correctly work with Replicasets ensuring proper error handling, Issue #336 -* Merged in code from (https://github.com/aheckmann) that checks for global variable leaks - -0.9.6-14 2011-09-05 -------------------- -* Minor fixes for error handling in cursor streaming (https://github.com/sethml), Issue #332 -* Minor doc fixes -* Some more cursor sort tests added, Issue #333 -* Fixes to work with 0.5.X branch -* Fix Db not removing reconnect listener from serverConfig, (https://github.com/sbrekken), Issue #337 -* Removed node_events.h includes (https://github.com/jannehietamaki), Issue #339 -* Implement correct safe/strict mode for findAndModify. - -0.9.6-13 2011-08-24 -------------------- -* Db names correctly error checked for illegal characters - -0.9.6-12 2011-08-24 -------------------- -* Nasty bug in GridFS if you changed the default chunk size -* Fixed error handling bug in findOne - -0.9.6-11 2011-08-23 -------------------- -* Timeout option not correctly making it to the cursor, Issue #320, Fix from (https://github.com/year2013) -* Fixes for memory leaks when using buffers and C++ parser -* Fixes to make tests pass on 0.5.X -* Cleanup of bson.js to remove duplicated code paths -* Fix for errors occurring in ensureIndex, Issue #326 -* Removing require.paths to make tests work with the 0.5.X branch - -0.9.6-10 2011-08-11 -------------------- -* Specific type Double for capped collections (https://github.com/mbostock), Issue #312 -* Decorating Errors with all all object info from Mongo (https://github.com/laurie71), Issue #308 -* Implementing fixes for mongodb 1.9.1 and higher to make tests pass -* Admin validateCollection now takes an options argument for you to pass in full option -* Implemented keepGoing parameter for mongodb 1.9.1 or higher, Issue #310 -* Added test for read_secondary count issue, merged in fix from (https://github.com/year2013), Issue #317 - -0.9.6-9 -------- -* Bug fix for bson parsing the key '':'' correctly without crashing - -0.9.6-8 -------- -* Changed to using node.js crypto library MD5 digest -* Connect method support documented mongodb: syntax by (https://github.com/sethml) -* Support Symbol type for BSON, serializes to it's own type Symbol, Issue #302, #288 -* Code object without scope serializing to correct BSON type -* Lot's of fixes to avoid double callbacks (https://github.com/aheckmann) Issue #304 -* Long deserializes as Number for values in the range -2^53 to 2^53, Issue #305 (https://github.com/sethml) -* Fixed C++ parser to reflect JS parser handling of long deserialization -* Bson small optimizations - -0.9.6-7 2011-07-13 ------------------- -* JS Bson deserialization bug #287 - -0.9.6-6 2011-07-12 ------------------- -* FindAndModify not returning error message as other methods Issue #277 -* Added test coverage for $push, $pushAll and $inc atomic operations -* Correct Error handling for non 12/24 bit ids on Pure JS ObjectID class Issue #276 -* Fixed terrible deserialization bug in js bson code #285 -* Fix by andrewjstone to avoid throwing errors when this.primary not defined - -0.9.6-5 2011-07-06 ------------------- -* Rewritten BSON js parser now faster than the C parser on my core2duo laptop -* Added option full to indexInformation to get all index info Issue #265 -* Passing in ObjectID for new Gridstore works correctly Issue #272 - -0.9.6-4 2011-07-01 ------------------- -* Added test and bug fix for insert/update/remove without callback supplied - -0.9.6-3 2011-07-01 ------------------- -* Added simple grid class called Grid with put, get, delete methods -* Fixed writeBuffer/readBuffer methods on GridStore so they work correctly -* Automatic handling of buffers when using write method on GridStore -* GridStore now accepts a ObjectID instead of file name for write and read methods -* GridStore.list accepts id option to return of file ids instead of filenames -* GridStore close method returns document for the file allowing user to reference _id field - -0.9.6-2 2011-06-30 ------------------- -* Fixes for reconnect logic for server object (replays auth correctly) -* More testcases for auth -* Fixes in error handling for replicaset -* Fixed bug with safe parameter that would fail to execute safe when passing w or wtimeout -* Fixed slaveOk bug for findOne method -* Implemented auth support for replicaset and test cases -* Fixed error when not passing in rs_name - -0.9.6-1 2011-06-25 ------------------- -* Fixes for test to run properly using c++ bson parser -* Fixes for dbref in native parser (correctly handles ref without db component) -* Connection fixes for replicasets to avoid runtime conditions in cygwin (https://github.com/vincentcr) -* Fixes for timestamp in js bson parser (distinct timestamp type now) - -0.9.6 2011-06-21 ----------------- -* Worked around npm version handling bug -* Race condition fix for cygwin (https://github.com/vincentcr) - -0.9.5-1 2011-06-21 ------------------- -* Extracted Timestamp as separate class for bson js parser to avoid instanceof problems -* Fixed driver strict mode issue - -0.9.5 2011-06-20 ----------------- -* Replicaset support (failover and reading from secondary servers) -* Removed ServerPair and ServerCluster -* Added connection pool functionality -* Fixed serious bug in C++ bson parser where bytes > 127 would generate 2 byte sequences -* Allows for forcing the server to assign ObjectID's using the option {forceServerObjectId: true} - -0.6.8 ------ -* Removed multiple message concept from bson -* Changed db.open(db) to be db.open(err, db) - -0.1 2010-01-30 --------------- -* Initial release support of driver using native node.js interface -* Supports gridfs specification -* Supports admin functionality diff --git a/scripts/node_modules/mongodb/LICENSE.md b/scripts/node_modules/mongodb/LICENSE.md deleted file mode 100644 index ad410e11..00000000 --- a/scripts/node_modules/mongodb/LICENSE.md +++ /dev/null @@ -1,201 +0,0 @@ -Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "{}" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright {yyyy} {name of copyright owner} - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. \ No newline at end of file diff --git a/scripts/node_modules/mongodb/README.md b/scripts/node_modules/mongodb/README.md deleted file mode 100644 index 672ccf39..00000000 --- a/scripts/node_modules/mongodb/README.md +++ /dev/null @@ -1,499 +0,0 @@ -[![npm](https://nodei.co/npm/mongodb.png?downloads=true&downloadRank=true)](https://nodei.co/npm/mongodb/) [![npm](https://nodei.co/npm-dl/mongodb.png?months=6&height=3)](https://nodei.co/npm/mongodb/) - -[![Build Status](https://secure.travis-ci.org/mongodb/node-mongodb-native.svg?branch=2.1)](http://travis-ci.org/mongodb/node-mongodb-native) -[![Coverage Status](https://coveralls.io/repos/github/mongodb/node-mongodb-native/badge.svg?branch=2.1)](https://coveralls.io/github/mongodb/node-mongodb-native?branch=2.1) -[![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/mongodb/node-mongodb-native?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) - -# Description - -The official [MongoDB](https://www.mongodb.com/) driver for Node.js. Provides a high-level API on top of [mongodb-core](https://www.npmjs.com/package/mongodb-core) that is meant for end users. - -**NOTE: v3.x was recently released with breaking API changes. You can find a list of changes [here](CHANGES_3.0.0.md).** - -## MongoDB Node.JS Driver - -| what | where | -|---------------|------------------------------------------------| -| documentation | http://mongodb.github.io/node-mongodb-native | -| api-doc | http://mongodb.github.io/node-mongodb-native/3.1/api | -| source | https://github.com/mongodb/node-mongodb-native | -| mongodb | http://www.mongodb.org | - -### Bugs / Feature Requests - -Think you’ve found a bug? Want to see a new feature in `node-mongodb-native`? Please open a -case in our issue management tool, JIRA: - -- Create an account and login [jira.mongodb.org](https://jira.mongodb.org). -- Navigate to the NODE project [jira.mongodb.org/browse/NODE](https://jira.mongodb.org/browse/NODE). -- Click **Create Issue** - Please provide as much information as possible about the issue type and how to reproduce it. - -Bug reports in JIRA for all driver projects (i.e. NODE, PYTHON, CSHARP, JAVA) and the -Core Server (i.e. SERVER) project are **public**. - -### Support / Feedback - -For issues with, questions about, or feedback for the Node.js driver, please look into our [support channels](http://www.mongodb.org/about/support). Please do not email any of the driver developers directly with issues or questions - you're more likely to get an answer on the [mongodb-user](http://groups.google.com/group/mongodb-user>) list on Google Groups. - -### Change Log - -Change history can be found in [`HISTORY.md`](HISTORY.md). - -### Compatibility - -For version compatibility matrices, please refer to the following links: - - * [MongoDB](https://docs.mongodb.com/ecosystem/drivers/driver-compatibility-reference/#reference-compatibility-mongodb-node) - * [NodeJS](https://docs.mongodb.com/ecosystem/drivers/driver-compatibility-reference/#reference-compatibility-language-node) - -# Installation - -The recommended way to get started using the Node.js 3.0 driver is by using the `npm` (Node Package Manager) to install the dependency in your project. - -## MongoDB Driver - -Given that you have created your own project using `npm init` we install the MongoDB driver and its dependencies by executing the following `npm` command. - -```bash -npm install mongodb --save -``` - -This will download the MongoDB driver and add a dependency entry in your `package.json` file. - -You can also use the [Yarn](https://yarnpkg.com/en) package manager. - -## Troubleshooting - -The MongoDB driver depends on several other packages. These are: - -* [mongodb-core](https://github.com/mongodb-js/mongodb-core) -* [bson](https://github.com/mongodb/js-bson) -* [kerberos](https://github.com/mongodb-js/kerberos) -* [node-gyp](https://github.com/nodejs/node-gyp) - -The `kerberos` package is a C++ extension that requires a build environment to be installed on your system. You must be able to build Node.js itself in order to compile and install the `kerberos` module. Furthermore, the `kerberos` module requires the MIT Kerberos package to correctly compile on UNIX operating systems. Consult your UNIX operation system package manager for what libraries to install. - -**Windows already contains the SSPI API used for Kerberos authentication. However, you will need to install a full compiler tool chain using Visual Studio C++ to correctly install the Kerberos extension.** - -### Diagnosing on UNIX - -If you don’t have the build-essentials, this module won’t build. In the case of Linux, you will need gcc, g++, Node.js with all the headers and Python. The easiest way to figure out what’s missing is by trying to build the Kerberos project. You can do this by performing the following steps. - -```bash -git clone https://github.com/mongodb-js/kerberos -cd kerberos -npm install -``` - -If all the steps complete, you have the right toolchain installed. If you get the error "node-gyp not found," you need to install `node-gyp` globally: - -```bash -npm install -g node-gyp -``` - -If it correctly compiles and runs the tests you are golden. We can now try to install the `mongod` driver by performing the following command. - -```bash -cd yourproject -npm install mongodb --save -``` - -If it still fails the next step is to examine the npm log. Rerun the command but in this case in verbose mode. - -```bash -npm --loglevel verbose install mongodb -``` - -This will print out all the steps npm is performing while trying to install the module. - -### Diagnosing on Windows - -A compiler tool chain known to work for compiling `kerberos` on Windows is the following. - -* Visual Studio C++ 2010 (do not use higher versions) -* Windows 7 64bit SDK -* Python 2.7 or higher - -Open the Visual Studio command prompt. Ensure `node.exe` is in your path and install `node-gyp`. - -```bash -npm install -g node-gyp -``` - -Next, you will have to build the project manually to test it. Clone the repo, install dependencies and rebuild: - -```bash -git clone https://github.com/christkv/kerberos.git -cd kerberos -npm install -node-gyp rebuild -``` - -This should rebuild the driver successfully if you have everything set up correctly. - -### Other possible issues - -Your Python installation might be hosed making gyp break. Test your deployment environment first by trying to build Node.js itself on the server in question, as this should unearth any issues with broken packages (and there are a lot of broken packages out there). - -Another tip is to ensure your user has write permission to wherever the Node.js modules are being installed. - -## Quick Start - -This guide will show you how to set up a simple application using Node.js and MongoDB. Its scope is only how to set up the driver and perform the simple CRUD operations. For more in-depth coverage, see the [tutorials](docs/reference/content/tutorials/main.md). - -### Create the `package.json` file - -First, create a directory where your application will live. - -```bash -mkdir myproject -cd myproject -``` - -Enter the following command and answer the questions to create the initial structure for your new project: - -```bash -npm init -``` - -Next, install the driver dependency. - -```bash -npm install mongodb --save -``` - -You should see **NPM** download a lot of files. Once it's done you'll find all the downloaded packages under the **node_modules** directory. - -### Start a MongoDB Server - -For complete MongoDB installation instructions, see [the manual](https://docs.mongodb.org/manual/installation/). - -1. Download the right MongoDB version from [MongoDB](https://www.mongodb.org/downloads) -2. Create a database directory (in this case under **/data**). -3. Install and start a ``mongod`` process. - -```bash -mongod --dbpath=/data -``` - -You should see the **mongod** process start up and print some status information. - -### Connect to MongoDB - -Create a new **app.js** file and add the following code to try out some basic CRUD -operations using the MongoDB driver. - -Add code to connect to the server and the database **myproject**: - -```js -const MongoClient = require('mongodb').MongoClient; -const assert = require('assert'); - -// Connection URL -const url = 'mongodb://localhost:27017'; - -// Database Name -const dbName = 'myproject'; - -// Use connect method to connect to the server -MongoClient.connect(url, function(err, client) { - assert.equal(null, err); - console.log("Connected successfully to server"); - - const db = client.db(dbName); - - client.close(); -}); -``` - -Run your app from the command line with: - -```bash -node app.js -``` - -The application should print **Connected successfully to server** to the console. - -### Insert a Document - -Add to **app.js** the following function which uses the **insertMany** -method to add three documents to the **documents** collection. - -```js -const insertDocuments = function(db, callback) { - // Get the documents collection - const collection = db.collection('documents'); - // Insert some documents - collection.insertMany([ - {a : 1}, {a : 2}, {a : 3} - ], function(err, result) { - assert.equal(err, null); - assert.equal(3, result.result.n); - assert.equal(3, result.ops.length); - console.log("Inserted 3 documents into the collection"); - callback(result); - }); -} -``` - -The **insert** command returns an object with the following fields: - -* **result** Contains the result document from MongoDB -* **ops** Contains the documents inserted with added **_id** fields -* **connection** Contains the connection used to perform the insert - -Add the following code to call the **insertDocuments** function: - -```js -const MongoClient = require('mongodb').MongoClient; -const assert = require('assert'); - -// Connection URL -const url = 'mongodb://localhost:27017'; - -// Database Name -const dbName = 'myproject'; - -// Use connect method to connect to the server -MongoClient.connect(url, function(err, client) { - assert.equal(null, err); - console.log("Connected successfully to server"); - - const db = client.db(dbName); - - insertDocuments(db, function() { - client.close(); - }); -}); -``` - -Run the updated **app.js** file: - -```bash -node app.js -``` - -The operation returns the following output: - -```bash -Connected successfully to server -Inserted 3 documents into the collection -``` - -### Find All Documents - -Add a query that returns all the documents. - -```js -const findDocuments = function(db, callback) { - // Get the documents collection - const collection = db.collection('documents'); - // Find some documents - collection.find({}).toArray(function(err, docs) { - assert.equal(err, null); - console.log("Found the following records"); - console.log(docs) - callback(docs); - }); -} -``` - -This query returns all the documents in the **documents** collection. Add the **findDocument** method to the **MongoClient.connect** callback: - -```js -const MongoClient = require('mongodb').MongoClient; -const assert = require('assert'); - -// Connection URL -const url = 'mongodb://localhost:27017'; - -// Database Name -const dbName = 'myproject'; - -// Use connect method to connect to the server -MongoClient.connect(url, function(err, client) { - assert.equal(null, err); - console.log("Connected correctly to server"); - - const db = client.db(dbName); - - insertDocuments(db, function() { - findDocuments(db, function() { - client.close(); - }); - }); -}); -``` - -### Find Documents with a Query Filter - -Add a query filter to find only documents which meet the query criteria. - -```js -const findDocuments = function(db, callback) { - // Get the documents collection - const collection = db.collection('documents'); - // Find some documents - collection.find({'a': 3}).toArray(function(err, docs) { - assert.equal(err, null); - console.log("Found the following records"); - console.log(docs); - callback(docs); - }); -} -``` - -Only the documents which match ``'a' : 3`` should be returned. - -### Update a document - -The following operation updates a document in the **documents** collection. - -```js -const updateDocument = function(db, callback) { - // Get the documents collection - const collection = db.collection('documents'); - // Update document where a is 2, set b equal to 1 - collection.updateOne({ a : 2 } - , { $set: { b : 1 } }, function(err, result) { - assert.equal(err, null); - assert.equal(1, result.result.n); - console.log("Updated the document with the field a equal to 2"); - callback(result); - }); -} -``` - -The method updates the first document where the field **a** is equal to **2** by adding a new field **b** to the document set to **1**. Next, update the callback function from **MongoClient.connect** to include the update method. - -```js -const MongoClient = require('mongodb').MongoClient; -const assert = require('assert'); - -// Connection URL -const url = 'mongodb://localhost:27017'; - -// Database Name -const dbName = 'myproject'; - -// Use connect method to connect to the server -MongoClient.connect(url, function(err, client) { - assert.equal(null, err); - console.log("Connected successfully to server"); - - const db = client.db(dbName); - - insertDocuments(db, function() { - updateDocument(db, function() { - client.close(); - }); - }); -}); -``` - -### Remove a document - -Remove the document where the field **a** is equal to **3**. - -```js -const removeDocument = function(db, callback) { - // Get the documents collection - const collection = db.collection('documents'); - // Delete document where a is 3 - collection.deleteOne({ a : 3 }, function(err, result) { - assert.equal(err, null); - assert.equal(1, result.result.n); - console.log("Removed the document with the field a equal to 3"); - callback(result); - }); -} -``` - -Add the new method to the **MongoClient.connect** callback function. - -```js -const MongoClient = require('mongodb').MongoClient; -const assert = require('assert'); - -// Connection URL -const url = 'mongodb://localhost:27017'; - -// Database Name -const dbName = 'myproject'; - -// Use connect method to connect to the server -MongoClient.connect(url, function(err, client) { - assert.equal(null, err); - console.log("Connected successfully to server"); - - const db = client.db(dbName); - - insertDocuments(db, function() { - updateDocument(db, function() { - removeDocument(db, function() { - client.close(); - }); - }); - }); -}); -``` - -### Index a Collection - -[Indexes](https://docs.mongodb.org/manual/indexes/) can improve your application's -performance. The following function creates an index on the **a** field in the -**documents** collection. - -```js -const indexCollection = function(db, callback) { - db.collection('documents').createIndex( - { "a": 1 }, - null, - function(err, results) { - console.log(results); - callback(); - } - ); -}; -``` - -Add the ``indexCollection`` method to your app: - -```js -const MongoClient = require('mongodb').MongoClient; -const assert = require('assert'); - -// Connection URL -const url = 'mongodb://localhost:27017'; - -const dbName = 'myproject'; - -// Use connect method to connect to the server -MongoClient.connect(url, function(err, client) { - assert.equal(null, err); - console.log("Connected successfully to server"); - - const db = client.db(dbName); - - insertDocuments(db, function() { - indexCollection(db, function() { - client.close(); - }); - }); -}); -``` - -For more detailed information, see the [tutorials](docs/reference/content/tutorials/main.md). - -## Next Steps - - * [MongoDB Documentation](http://mongodb.org) - * [Read about Schemas](http://learnmongodbthehardway.com) - * [Star us on GitHub](https://github.com/mongodb/node-mongodb-native) - -## License - -[Apache 2.0](LICENSE.md) - -© 2009-2012 Christian Amor Kvalheim -© 2012-present MongoDB [Contributors](CONTRIBUTORS.md) diff --git a/scripts/node_modules/mongodb/index.js b/scripts/node_modules/mongodb/index.js deleted file mode 100644 index 3ce36f59..00000000 --- a/scripts/node_modules/mongodb/index.js +++ /dev/null @@ -1,68 +0,0 @@ -'use strict'; - -// Core module -const core = require('./lib/core'); -const Instrumentation = require('./lib/apm'); - -// Set up the connect function -const connect = require('./lib/mongo_client').connect; - -// Expose error class -connect.MongoError = core.MongoError; -connect.MongoNetworkError = core.MongoNetworkError; -connect.MongoTimeoutError = core.MongoTimeoutError; - -// Actual driver classes exported -connect.Admin = require('./lib/admin'); -connect.MongoClient = require('./lib/mongo_client'); -connect.Db = require('./lib/db'); -connect.Collection = require('./lib/collection'); -connect.Server = require('./lib/topologies/server'); -connect.ReplSet = require('./lib/topologies/replset'); -connect.Mongos = require('./lib/topologies/mongos'); -connect.ReadPreference = core.ReadPreference; -connect.GridStore = require('./lib/gridfs/grid_store'); -connect.Chunk = require('./lib/gridfs/chunk'); -connect.Logger = core.Logger; -connect.AggregationCursor = require('./lib/aggregation_cursor'); -connect.CommandCursor = require('./lib/command_cursor'); -connect.Cursor = require('./lib/cursor'); -connect.GridFSBucket = require('./lib/gridfs-stream'); -// Exported to be used in tests not to be used anywhere else -connect.CoreServer = core.Server; -connect.CoreConnection = core.Connection; - -// BSON types exported -connect.Binary = core.BSON.Binary; -connect.Code = core.BSON.Code; -connect.Map = core.BSON.Map; -connect.DBRef = core.BSON.DBRef; -connect.Double = core.BSON.Double; -connect.Int32 = core.BSON.Int32; -connect.Long = core.BSON.Long; -connect.MinKey = core.BSON.MinKey; -connect.MaxKey = core.BSON.MaxKey; -connect.ObjectID = core.BSON.ObjectID; -connect.ObjectId = core.BSON.ObjectID; -connect.Symbol = core.BSON.Symbol; -connect.Timestamp = core.BSON.Timestamp; -connect.BSONRegExp = core.BSON.BSONRegExp; -connect.Decimal128 = core.BSON.Decimal128; - -// Add connect method -connect.connect = connect; - -// Set up the instrumentation method -connect.instrument = function(options, callback) { - if (typeof options === 'function') { - callback = options; - options = {}; - } - - const instrumentation = new Instrumentation(); - instrumentation.instrument(connect.MongoClient, callback); - return instrumentation; -}; - -// Set our exports to be the connect function -module.exports = connect; diff --git a/scripts/node_modules/mongodb/lib/admin.js b/scripts/node_modules/mongodb/lib/admin.js deleted file mode 100644 index 716844bb..00000000 --- a/scripts/node_modules/mongodb/lib/admin.js +++ /dev/null @@ -1,293 +0,0 @@ -'use strict'; - -const applyWriteConcern = require('./utils').applyWriteConcern; - -const AddUserOperation = require('./operations/add_user'); -const ExecuteDbAdminCommandOperation = require('./operations/execute_db_admin_command'); -const RemoveUserOperation = require('./operations/remove_user'); -const ValidateCollectionOperation = require('./operations/validate_collection'); -const ListDatabasesOperation = require('./operations/list_databases'); - -const executeOperation = require('./operations/execute_operation'); - -/** - * @fileOverview The **Admin** class is an internal class that allows convenient access to - * the admin functionality and commands for MongoDB. - * - * **ADMIN Cannot directly be instantiated** - * @example - * const MongoClient = require('mongodb').MongoClient; - * const test = require('assert'); - * // Connection url - * const url = 'mongodb://localhost:27017'; - * // Database Name - * const dbName = 'test'; - * - * // Connect using MongoClient - * MongoClient.connect(url, function(err, client) { - * // Use the admin database for the operation - * const adminDb = client.db(dbName).admin(); - * - * // List all the available databases - * adminDb.listDatabases(function(err, dbs) { - * test.equal(null, err); - * test.ok(dbs.databases.length > 0); - * client.close(); - * }); - * }); - */ - -/** - * Create a new Admin instance (INTERNAL TYPE, do not instantiate directly) - * @class - * @return {Admin} a collection instance. - */ -function Admin(db, topology, promiseLibrary) { - if (!(this instanceof Admin)) return new Admin(db, topology); - - // Internal state - this.s = { - db: db, - topology: topology, - promiseLibrary: promiseLibrary - }; -} - -/** - * The callback format for results - * @callback Admin~resultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {object} result The result object if the command was executed successfully. - */ - -/** - * Execute a command - * @method - * @param {object} command The command hash - * @param {object} [options] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query. - * @param {Admin~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.command = function(command, options, callback) { - const args = Array.prototype.slice.call(arguments, 1); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - options = args.length ? args.shift() : {}; - - const commandOperation = new ExecuteDbAdminCommandOperation(this.s.db, command, options); - - return executeOperation(this.s.db.s.topology, commandOperation, callback); -}; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @param {Object} [options] optional parameters for this operation - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Admin~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.buildInfo = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const cmd = { buildinfo: 1 }; - - const buildInfoOperation = new ExecuteDbAdminCommandOperation(this.s.db, cmd, options); - - return executeOperation(this.s.db.s.topology, buildInfoOperation, callback); -}; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @param {Object} [options] optional parameters for this operation - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Admin~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.serverInfo = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const cmd = { buildinfo: 1 }; - - const serverInfoOperation = new ExecuteDbAdminCommandOperation(this.s.db, cmd, options); - - return executeOperation(this.s.db.s.topology, serverInfoOperation, callback); -}; - -/** - * Retrieve this db's server status. - * - * @param {Object} [options] optional parameters for this operation - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Admin~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.serverStatus = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const serverStatusOperation = new ExecuteDbAdminCommandOperation( - this.s.db, - { serverStatus: 1 }, - options - ); - - return executeOperation(this.s.db.s.topology, serverStatusOperation, callback); -}; - -/** - * Ping the MongoDB server and retrieve results - * - * @param {Object} [options] optional parameters for this operation - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Admin~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.ping = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const cmd = { ping: 1 }; - - const pingOperation = new ExecuteDbAdminCommandOperation(this.s.db, cmd, options); - - return executeOperation(this.s.db.s.topology, pingOperation, callback); -}; - -/** - * Add a user to the database. - * @method - * @param {string} username The username. - * @param {string} password The password. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.fsync=false] Specify a file sync write concern. - * @param {object} [options.customData] Custom data associated with the user (only Mongodb 2.6 or higher) - * @param {object[]} [options.roles] Roles associated with the created user (only Mongodb 2.6 or higher) - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Admin~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.addUser = function(username, password, options, callback) { - const args = Array.prototype.slice.call(arguments, 2); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - - // Special case where there is no password ($external users) - if (typeof username === 'string' && password != null && typeof password === 'object') { - options = password; - password = null; - } - - options = args.length ? args.shift() : {}; - options = Object.assign({}, options); - // Get the options - options = applyWriteConcern(options, { db: this.s.db }); - // Set the db name to admin - options.dbName = 'admin'; - - const addUserOperation = new AddUserOperation(this.s.db, username, password, options); - - return executeOperation(this.s.db.s.topology, addUserOperation, callback); -}; - -/** - * Remove a user from a database - * @method - * @param {string} username The username. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.fsync=false] Specify a file sync write concern. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Admin~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.removeUser = function(username, options, callback) { - const args = Array.prototype.slice.call(arguments, 1); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - - options = args.length ? args.shift() : {}; - options = Object.assign({}, options); - // Get the options - options = applyWriteConcern(options, { db: this.s.db }); - // Set the db name - options.dbName = 'admin'; - - const removeUserOperation = new RemoveUserOperation(this.s.db, username, options); - - return executeOperation(this.s.db.s.topology, removeUserOperation, callback); -}; - -/** - * Validate an existing collection - * - * @param {string} collectionName The name of the collection to validate. - * @param {object} [options] Optional settings. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Admin~resultCallback} [callback] The command result callback. - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.validateCollection = function(collectionName, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const validateCollectionOperation = new ValidateCollectionOperation( - this, - collectionName, - options - ); - - return executeOperation(this.s.db.s.topology, validateCollectionOperation, callback); -}; - -/** - * List the available databases - * - * @param {object} [options] Optional settings. - * @param {boolean} [options.nameOnly=false] Whether the command should return only db names, or names and size info. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Admin~resultCallback} [callback] The command result callback. - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.listDatabases = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - return executeOperation( - this.s.db.s.topology, - new ListDatabasesOperation(this.s.db, options), - callback - ); -}; - -/** - * Get ReplicaSet status - * - * @param {Object} [options] optional parameters for this operation - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Admin~resultCallback} [callback] The command result callback. - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.replSetGetStatus = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const replSetGetStatusOperation = new ExecuteDbAdminCommandOperation( - this.s.db, - { replSetGetStatus: 1 }, - options - ); - - return executeOperation(this.s.db.s.topology, replSetGetStatusOperation, callback); -}; - -module.exports = Admin; diff --git a/scripts/node_modules/mongodb/lib/aggregation_cursor.js b/scripts/node_modules/mongodb/lib/aggregation_cursor.js deleted file mode 100644 index b0977c69..00000000 --- a/scripts/node_modules/mongodb/lib/aggregation_cursor.js +++ /dev/null @@ -1,370 +0,0 @@ -'use strict'; - -const MongoError = require('./core').MongoError; -const Cursor = require('./cursor'); -const CursorState = require('./core/cursor').CursorState; -const deprecate = require('util').deprecate; - -/** - * @fileOverview The **AggregationCursor** class is an internal class that embodies an aggregation cursor on MongoDB - * allowing for iteration over the results returned from the underlying query. It supports - * one by one document iteration, conversion to an array or can be iterated as a Node 4.X - * or higher stream - * - * **AGGREGATIONCURSOR Cannot directly be instantiated** - * @example - * const MongoClient = require('mongodb').MongoClient; - * const test = require('assert'); - * // Connection url - * const url = 'mongodb://localhost:27017'; - * // Database Name - * const dbName = 'test'; - * // Connect using MongoClient - * MongoClient.connect(url, function(err, client) { - * // Create a collection we want to drop later - * const col = client.db(dbName).collection('createIndexExample1'); - * // Insert a bunch of documents - * col.insert([{a:1, b:1} - * , {a:2, b:2}, {a:3, b:3} - * , {a:4, b:4}], {w:1}, function(err, result) { - * test.equal(null, err); - * // Show that duplicate records got dropped - * col.aggregation({}, {cursor: {}}).toArray(function(err, items) { - * test.equal(null, err); - * test.equal(4, items.length); - * client.close(); - * }); - * }); - * }); - */ - -/** - * Namespace provided by the browser. - * @external Readable - */ - -/** - * Creates a new Aggregation Cursor instance (INTERNAL TYPE, do not instantiate directly) - * @class AggregationCursor - * @extends external:Readable - * @fires AggregationCursor#data - * @fires AggregationCursor#end - * @fires AggregationCursor#close - * @fires AggregationCursor#readable - * @return {AggregationCursor} an AggregationCursor instance. - */ -class AggregationCursor extends Cursor { - constructor(topology, operation, options) { - super(topology, operation, options); - } - - /** - * Set the batch size for the cursor. - * @method - * @param {number} value The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. - * @throws {MongoError} - * @return {AggregationCursor} - */ - batchSize(value) { - if (this.s.state === CursorState.CLOSED || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - if (typeof value !== 'number') { - throw MongoError.create({ message: 'batchSize requires an integer', driver: true }); - } - - this.operation.options.batchSize = value; - this.setCursorBatchSize(value); - return this; - } - - /** - * Add a geoNear stage to the aggregation pipeline - * @method - * @param {object} document The geoNear stage document. - * @return {AggregationCursor} - */ - geoNear(document) { - this.operation.addToPipeline({ $geoNear: document }); - return this; - } - - /** - * Add a group stage to the aggregation pipeline - * @method - * @param {object} document The group stage document. - * @return {AggregationCursor} - */ - group(document) { - this.operation.addToPipeline({ $group: document }); - return this; - } - - /** - * Add a limit stage to the aggregation pipeline - * @method - * @param {number} value The state limit value. - * @return {AggregationCursor} - */ - limit(value) { - this.operation.addToPipeline({ $limit: value }); - return this; - } - - /** - * Add a match stage to the aggregation pipeline - * @method - * @param {object} document The match stage document. - * @return {AggregationCursor} - */ - match(document) { - this.operation.addToPipeline({ $match: document }); - return this; - } - - /** - * Add a maxTimeMS stage to the aggregation pipeline - * @method - * @param {number} value The state maxTimeMS value. - * @return {AggregationCursor} - */ - maxTimeMS(value) { - this.operation.options.maxTimeMS = value; - return this; - } - - /** - * Add a out stage to the aggregation pipeline - * @method - * @param {number} destination The destination name. - * @return {AggregationCursor} - */ - out(destination) { - this.operation.addToPipeline({ $out: destination }); - return this; - } - - /** - * Add a project stage to the aggregation pipeline - * @method - * @param {object} document The project stage document. - * @return {AggregationCursor} - */ - project(document) { - this.operation.addToPipeline({ $project: document }); - return this; - } - - /** - * Add a lookup stage to the aggregation pipeline - * @method - * @param {object} document The lookup stage document. - * @return {AggregationCursor} - */ - lookup(document) { - this.operation.addToPipeline({ $lookup: document }); - return this; - } - - /** - * Add a redact stage to the aggregation pipeline - * @method - * @param {object} document The redact stage document. - * @return {AggregationCursor} - */ - redact(document) { - this.operation.addToPipeline({ $redact: document }); - return this; - } - - /** - * Add a skip stage to the aggregation pipeline - * @method - * @param {number} value The state skip value. - * @return {AggregationCursor} - */ - skip(value) { - this.operation.addToPipeline({ $skip: value }); - return this; - } - - /** - * Add a sort stage to the aggregation pipeline - * @method - * @param {object} document The sort stage document. - * @return {AggregationCursor} - */ - sort(document) { - this.operation.addToPipeline({ $sort: document }); - return this; - } - - /** - * Add a unwind stage to the aggregation pipeline - * @method - * @param {number} field The unwind field name. - * @return {AggregationCursor} - */ - unwind(field) { - this.operation.addToPipeline({ $unwind: field }); - return this; - } - - /** - * Return the cursor logger - * @method - * @return {Logger} return the cursor logger - * @ignore - */ - getLogger() { - return this.logger; - } -} - -// aliases -AggregationCursor.prototype.get = AggregationCursor.prototype.toArray; - -// deprecated methods -deprecate( - AggregationCursor.prototype.geoNear, - 'The `$geoNear` stage is deprecated in MongoDB 4.0, and removed in version 4.2.' -); - -/** - * AggregationCursor stream data event, fired for each document in the cursor. - * - * @event AggregationCursor#data - * @type {object} - */ - -/** - * AggregationCursor stream end event - * - * @event AggregationCursor#end - * @type {null} - */ - -/** - * AggregationCursor stream close event - * - * @event AggregationCursor#close - * @type {null} - */ - -/** - * AggregationCursor stream readable event - * - * @event AggregationCursor#readable - * @type {null} - */ - -/** - * Get the next available document from the cursor, returns null if no more documents are available. - * @function AggregationCursor.prototype.next - * @param {AggregationCursor~resultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ - -/** - * Check if there is any document still available in the cursor - * @function AggregationCursor.prototype.hasNext - * @param {AggregationCursor~resultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ - -/** - * The callback format for results - * @callback AggregationCursor~toArrayResultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {object[]} documents All the documents the satisfy the cursor. - */ - -/** - * Returns an array of documents. The caller is responsible for making sure that there - * is enough memory to store the results. Note that the array only contain partial - * results when this cursor had been previously accessed. In that case, - * cursor.rewind() can be used to reset the cursor. - * @method AggregationCursor.prototype.toArray - * @param {AggregationCursor~toArrayResultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ - -/** - * The callback format for results - * @callback AggregationCursor~resultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {(object|null)} result The result object if the command was executed successfully. - */ - -/** - * Iterates over all the documents for this cursor. As with **{cursor.toArray}**, - * not all of the elements will be iterated if this cursor had been previously accessed. - * In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike - * **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements - * at any given time if batch size is specified. Otherwise, the caller is responsible - * for making sure that the entire result can fit the memory. - * @method AggregationCursor.prototype.each - * @deprecated - * @param {AggregationCursor~resultCallback} callback The result callback. - * @throws {MongoError} - * @return {null} - */ - -/** - * Close the cursor, sending a AggregationCursor command and emitting close. - * @method AggregationCursor.prototype.close - * @param {AggregationCursor~resultCallback} [callback] The result callback. - * @return {Promise} returns Promise if no callback passed - */ - -/** - * Is the cursor closed - * @method AggregationCursor.prototype.isClosed - * @return {boolean} - */ - -/** - * Execute the explain for the cursor - * @method AggregationCursor.prototype.explain - * @param {AggregationCursor~resultCallback} [callback] The result callback. - * @return {Promise} returns Promise if no callback passed - */ - -/** - * Clone the cursor - * @function AggregationCursor.prototype.clone - * @return {AggregationCursor} - */ - -/** - * Resets the cursor - * @function AggregationCursor.prototype.rewind - * @return {AggregationCursor} - */ - -/** - * The callback format for the forEach iterator method - * @callback AggregationCursor~iteratorCallback - * @param {Object} doc An emitted document for the iterator - */ - -/** - * The callback error format for the forEach iterator method - * @callback AggregationCursor~endCallback - * @param {MongoError} error An error instance representing the error during the execution. - */ - -/** - * Iterates over all the documents for this cursor using the iterator, callback pattern. - * @method AggregationCursor.prototype.forEach - * @param {AggregationCursor~iteratorCallback} iterator The iteration callback. - * @param {AggregationCursor~endCallback} callback The end callback. - * @throws {MongoError} - * @return {null} - */ - -module.exports = AggregationCursor; diff --git a/scripts/node_modules/mongodb/lib/apm.js b/scripts/node_modules/mongodb/lib/apm.js deleted file mode 100644 index f78e4aaf..00000000 --- a/scripts/node_modules/mongodb/lib/apm.js +++ /dev/null @@ -1,31 +0,0 @@ -'use strict'; -const EventEmitter = require('events').EventEmitter; - -class Instrumentation extends EventEmitter { - constructor() { - super(); - } - - instrument(MongoClient, callback) { - // store a reference to the original functions - this.$MongoClient = MongoClient; - const $prototypeConnect = (this.$prototypeConnect = MongoClient.prototype.connect); - - const instrumentation = this; - MongoClient.prototype.connect = function(callback) { - this.s.options.monitorCommands = true; - this.on('commandStarted', event => instrumentation.emit('started', event)); - this.on('commandSucceeded', event => instrumentation.emit('succeeded', event)); - this.on('commandFailed', event => instrumentation.emit('failed', event)); - return $prototypeConnect.call(this, callback); - }; - - if (typeof callback === 'function') callback(null, this); - } - - uninstrument() { - this.$MongoClient.prototype.connect = this.$prototypeConnect; - } -} - -module.exports = Instrumentation; diff --git a/scripts/node_modules/mongodb/lib/async/.eslintrc b/scripts/node_modules/mongodb/lib/async/.eslintrc deleted file mode 100644 index 93b2f643..00000000 --- a/scripts/node_modules/mongodb/lib/async/.eslintrc +++ /dev/null @@ -1,5 +0,0 @@ -{ - "parserOptions": { - "ecmaVersion": 2018 - } -} diff --git a/scripts/node_modules/mongodb/lib/async/async_iterator.js b/scripts/node_modules/mongodb/lib/async/async_iterator.js deleted file mode 100644 index 6021aadf..00000000 --- a/scripts/node_modules/mongodb/lib/async/async_iterator.js +++ /dev/null @@ -1,33 +0,0 @@ -'use strict'; - -// async function* asyncIterator() { -// while (true) { -// const value = await this.next(); -// if (!value) { -// await this.close(); -// return; -// } - -// yield value; -// } -// } - -// TODO: change this to the async generator function above -function asyncIterator() { - const cursor = this; - - return { - next: function() { - return Promise.resolve() - .then(() => cursor.next()) - .then(value => { - if (!value) { - return cursor.close().then(() => ({ value, done: true })); - } - return { value, done: false }; - }); - } - }; -} - -exports.asyncIterator = asyncIterator; diff --git a/scripts/node_modules/mongodb/lib/bulk/common.js b/scripts/node_modules/mongodb/lib/bulk/common.js deleted file mode 100644 index 8f99c252..00000000 --- a/scripts/node_modules/mongodb/lib/bulk/common.js +++ /dev/null @@ -1,1239 +0,0 @@ -'use strict'; - -const Long = require('../core').BSON.Long; -const MongoError = require('../core').MongoError; -const ObjectID = require('../core').BSON.ObjectID; -const BSON = require('../core').BSON; -const MongoWriteConcernError = require('../core').MongoWriteConcernError; -const toError = require('../utils').toError; -const handleCallback = require('../utils').handleCallback; -const applyRetryableWrites = require('../utils').applyRetryableWrites; -const applyWriteConcern = require('../utils').applyWriteConcern; -const executeLegacyOperation = require('../utils').executeLegacyOperation; -const isPromiseLike = require('../utils').isPromiseLike; - -// Error codes -const WRITE_CONCERN_ERROR = 64; - -// Insert types -const INSERT = 1; -const UPDATE = 2; -const REMOVE = 3; - -const bson = new BSON([ - BSON.Binary, - BSON.Code, - BSON.DBRef, - BSON.Decimal128, - BSON.Double, - BSON.Int32, - BSON.Long, - BSON.Map, - BSON.MaxKey, - BSON.MinKey, - BSON.ObjectId, - BSON.BSONRegExp, - BSON.Symbol, - BSON.Timestamp -]); - -/** - * Keeps the state of a unordered batch so we can rewrite the results - * correctly after command execution - * @ignore - */ -class Batch { - constructor(batchType, originalZeroIndex) { - this.originalZeroIndex = originalZeroIndex; - this.currentIndex = 0; - this.originalIndexes = []; - this.batchType = batchType; - this.operations = []; - this.size = 0; - this.sizeBytes = 0; - } -} - -/** - * @classdesc - * The result of a bulk write. - */ -class BulkWriteResult { - /** - * Create a new BulkWriteResult instance - * - * **NOTE:** Internal Type, do not instantiate directly - */ - constructor(bulkResult) { - this.result = bulkResult; - } - - /** - * Evaluates to true if the bulk operation correctly executes - * @type {boolean} - */ - get ok() { - return this.result.ok; - } - - /** - * The number of inserted documents - * @type {number} - */ - get nInserted() { - return this.result.nInserted; - } - - /** - * Number of upserted documents - * @type {number} - */ - get nUpserted() { - return this.result.nUpserted; - } - - /** - * Number of matched documents - * @type {number} - */ - get nMatched() { - return this.result.nMatched; - } - - /** - * Number of documents updated physically on disk - * @type {number} - */ - get nModified() { - return this.result.nModified; - } - - /** - * Number of removed documents - * @type {number} - */ - get nRemoved() { - return this.result.nRemoved; - } - - /** - * Returns an array of all inserted ids - * - * @return {object[]} - */ - getInsertedIds() { - return this.result.insertedIds; - } - - /** - * Returns an array of all upserted ids - * - * @return {object[]} - */ - getUpsertedIds() { - return this.result.upserted; - } - - /** - * Returns the upserted id at the given index - * - * @param {number} index the number of the upserted id to return, returns undefined if no result for passed in index - * @return {object} - */ - getUpsertedIdAt(index) { - return this.result.upserted[index]; - } - - /** - * Returns raw internal result - * - * @return {object} - */ - getRawResponse() { - return this.result; - } - - /** - * Returns true if the bulk operation contains a write error - * - * @return {boolean} - */ - hasWriteErrors() { - return this.result.writeErrors.length > 0; - } - - /** - * Returns the number of write errors off the bulk operation - * - * @return {number} - */ - getWriteErrorCount() { - return this.result.writeErrors.length; - } - - /** - * Returns a specific write error object - * - * @param {number} index of the write error to return, returns null if there is no result for passed in index - * @return {WriteError} - */ - getWriteErrorAt(index) { - if (index < this.result.writeErrors.length) { - return this.result.writeErrors[index]; - } - return null; - } - - /** - * Retrieve all write errors - * - * @return {WriteError[]} - */ - getWriteErrors() { - return this.result.writeErrors; - } - - /** - * Retrieve lastOp if available - * - * @return {object} - */ - getLastOp() { - return this.result.lastOp; - } - - /** - * Retrieve the write concern error if any - * - * @return {WriteConcernError} - */ - getWriteConcernError() { - if (this.result.writeConcernErrors.length === 0) { - return null; - } else if (this.result.writeConcernErrors.length === 1) { - // Return the error - return this.result.writeConcernErrors[0]; - } else { - // Combine the errors - let errmsg = ''; - for (let i = 0; i < this.result.writeConcernErrors.length; i++) { - const err = this.result.writeConcernErrors[i]; - errmsg = errmsg + err.errmsg; - - // TODO: Something better - if (i === 0) errmsg = errmsg + ' and '; - } - - return new WriteConcernError({ errmsg: errmsg, code: WRITE_CONCERN_ERROR }); - } - } - - /** - * @return {object} - */ - toJSON() { - return this.result; - } - - /** - * @return {string} - */ - toString() { - return `BulkWriteResult(${this.toJSON(this.result)})`; - } - - /** - * @return {boolean} - */ - isOk() { - return this.result.ok === 1; - } -} - -/** - * @classdesc An error representing a failure by the server to apply the requested write concern to the bulk operation. - */ -class WriteConcernError { - /** - * Create a new WriteConcernError instance - * - * **NOTE:** Internal Type, do not instantiate directly - */ - constructor(err) { - this.err = err; - } - - /** - * Write concern error code. - * @type {number} - */ - get code() { - return this.err.code; - } - - /** - * Write concern error message. - * @type {string} - */ - get errmsg() { - return this.err.errmsg; - } - - /** - * @return {object} - */ - toJSON() { - return { code: this.err.code, errmsg: this.err.errmsg }; - } - - /** - * @return {string} - */ - toString() { - return `WriteConcernError(${this.err.errmsg})`; - } -} - -/** - * @classdesc An error that occurred during a BulkWrite on the server. - */ -class WriteError { - /** - * Create a new WriteError instance - * - * **NOTE:** Internal Type, do not instantiate directly - */ - constructor(err) { - this.err = err; - } - - /** - * WriteError code. - * @type {number} - */ - get code() { - return this.err.code; - } - - /** - * WriteError original bulk operation index. - * @type {number} - */ - get index() { - return this.err.index; - } - - /** - * WriteError message. - * @type {string} - */ - get errmsg() { - return this.err.errmsg; - } - - /** - * Returns the underlying operation that caused the error - * @return {object} - */ - getOperation() { - return this.err.op; - } - - /** - * @return {object} - */ - toJSON() { - return { code: this.err.code, index: this.err.index, errmsg: this.err.errmsg, op: this.err.op }; - } - - /** - * @return {string} - */ - toString() { - return `WriteError(${JSON.stringify(this.toJSON())})`; - } -} - -/** - * Merges results into shared data structure - * @ignore - */ -function mergeBatchResults(batch, bulkResult, err, result) { - // If we have an error set the result to be the err object - if (err) { - result = err; - } else if (result && result.result) { - result = result.result; - } else if (result == null) { - return; - } - - // Do we have a top level error stop processing and return - if (result.ok === 0 && bulkResult.ok === 1) { - bulkResult.ok = 0; - - const writeError = { - index: 0, - code: result.code || 0, - errmsg: result.message, - op: batch.operations[0] - }; - - bulkResult.writeErrors.push(new WriteError(writeError)); - return; - } else if (result.ok === 0 && bulkResult.ok === 0) { - return; - } - - // Deal with opTime if available - if (result.opTime || result.lastOp) { - const opTime = result.lastOp || result.opTime; - let lastOpTS = null; - let lastOpT = null; - - // We have a time stamp - if (opTime && opTime._bsontype === 'Timestamp') { - if (bulkResult.lastOp == null) { - bulkResult.lastOp = opTime; - } else if (opTime.greaterThan(bulkResult.lastOp)) { - bulkResult.lastOp = opTime; - } - } else { - // Existing TS - if (bulkResult.lastOp) { - lastOpTS = - typeof bulkResult.lastOp.ts === 'number' - ? Long.fromNumber(bulkResult.lastOp.ts) - : bulkResult.lastOp.ts; - lastOpT = - typeof bulkResult.lastOp.t === 'number' - ? Long.fromNumber(bulkResult.lastOp.t) - : bulkResult.lastOp.t; - } - - // Current OpTime TS - const opTimeTS = typeof opTime.ts === 'number' ? Long.fromNumber(opTime.ts) : opTime.ts; - const opTimeT = typeof opTime.t === 'number' ? Long.fromNumber(opTime.t) : opTime.t; - - // Compare the opTime's - if (bulkResult.lastOp == null) { - bulkResult.lastOp = opTime; - } else if (opTimeTS.greaterThan(lastOpTS)) { - bulkResult.lastOp = opTime; - } else if (opTimeTS.equals(lastOpTS)) { - if (opTimeT.greaterThan(lastOpT)) { - bulkResult.lastOp = opTime; - } - } - } - } - - // If we have an insert Batch type - if (batch.batchType === INSERT && result.n) { - bulkResult.nInserted = bulkResult.nInserted + result.n; - } - - // If we have an insert Batch type - if (batch.batchType === REMOVE && result.n) { - bulkResult.nRemoved = bulkResult.nRemoved + result.n; - } - - let nUpserted = 0; - - // We have an array of upserted values, we need to rewrite the indexes - if (Array.isArray(result.upserted)) { - nUpserted = result.upserted.length; - - for (let i = 0; i < result.upserted.length; i++) { - bulkResult.upserted.push({ - index: result.upserted[i].index + batch.originalZeroIndex, - _id: result.upserted[i]._id - }); - } - } else if (result.upserted) { - nUpserted = 1; - - bulkResult.upserted.push({ - index: batch.originalZeroIndex, - _id: result.upserted - }); - } - - // If we have an update Batch type - if (batch.batchType === UPDATE && result.n) { - const nModified = result.nModified; - bulkResult.nUpserted = bulkResult.nUpserted + nUpserted; - bulkResult.nMatched = bulkResult.nMatched + (result.n - nUpserted); - - if (typeof nModified === 'number') { - bulkResult.nModified = bulkResult.nModified + nModified; - } else { - bulkResult.nModified = null; - } - } - - if (Array.isArray(result.writeErrors)) { - for (let i = 0; i < result.writeErrors.length; i++) { - const writeError = { - index: batch.originalZeroIndex + result.writeErrors[i].index, - code: result.writeErrors[i].code, - errmsg: result.writeErrors[i].errmsg, - op: batch.operations[result.writeErrors[i].index] - }; - - bulkResult.writeErrors.push(new WriteError(writeError)); - } - } - - if (result.writeConcernError) { - bulkResult.writeConcernErrors.push(new WriteConcernError(result.writeConcernError)); - } -} - -function executeCommands(bulkOperation, options, callback) { - if (bulkOperation.s.batches.length === 0) { - return handleCallback(callback, null, new BulkWriteResult(bulkOperation.s.bulkResult)); - } - - const batch = bulkOperation.s.batches.shift(); - - function resultHandler(err, result) { - // Error is a driver related error not a bulk op error, terminate - if (((err && err.driver) || (err && err.message)) && !(err instanceof MongoWriteConcernError)) { - return handleCallback(callback, err); - } - - // If we have and error - if (err) err.ok = 0; - if (err instanceof MongoWriteConcernError) { - return handleMongoWriteConcernError(batch, bulkOperation.s.bulkResult, err, callback); - } - - // Merge the results together - const writeResult = new BulkWriteResult(bulkOperation.s.bulkResult); - const mergeResult = mergeBatchResults(batch, bulkOperation.s.bulkResult, err, result); - if (mergeResult != null) { - return handleCallback(callback, null, writeResult); - } - - if (bulkOperation.handleWriteError(callback, writeResult)) return; - - // Execute the next command in line - executeCommands(bulkOperation, options, callback); - } - - bulkOperation.finalOptionsHandler({ options, batch, resultHandler }, callback); -} - -/** - * handles write concern error - * - * @ignore - * @param {object} batch - * @param {object} bulkResult - * @param {boolean} ordered - * @param {WriteConcernError} err - * @param {function} callback - */ -function handleMongoWriteConcernError(batch, bulkResult, err, callback) { - mergeBatchResults(batch, bulkResult, null, err.result); - - const wrappedWriteConcernError = new WriteConcernError({ - errmsg: err.result.writeConcernError.errmsg, - code: err.result.writeConcernError.result - }); - return handleCallback( - callback, - new BulkWriteError(toError(wrappedWriteConcernError), new BulkWriteResult(bulkResult)), - null - ); -} - -/** - * @classdesc An error indicating an unsuccessful Bulk Write - */ -class BulkWriteError extends MongoError { - /** - * Creates a new BulkWriteError - * - * @param {Error|string|object} message The error message - * @param {BulkWriteResult} result The result of the bulk write operation - * @extends {MongoError} - */ - constructor(error, result) { - const message = error.err || error.errmsg || error.errMessage || error; - super(message); - - Object.assign(this, error); - - this.name = 'BulkWriteError'; - this.result = result; - } -} - -/** - * @classdesc A builder object that is returned from {@link BulkOperationBase#find}. - * Is used to build a write operation that involves a query filter. - */ -class FindOperators { - /** - * Creates a new FindOperators object. - * - * **NOTE:** Internal Type, do not instantiate directly - * @param {OrderedBulkOperation|UnorderedBulkOperation} bulkOperation - */ - constructor(bulkOperation) { - this.s = bulkOperation.s; - } - - /** - * Add a multiple update operation to the bulk operation - * - * @method - * @param {object} updateDocument An update field for an update operation. See {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-u u documentation} - * @throws {MongoError} If operation cannot be added to bulk write - * @return {OrderedBulkOperation|UnorderedBulkOperation} A reference to the parent BulkOperation - */ - update(updateDocument) { - // Perform upsert - const upsert = typeof this.s.currentOp.upsert === 'boolean' ? this.s.currentOp.upsert : false; - - // Establish the update command - const document = { - q: this.s.currentOp.selector, - u: updateDocument, - multi: true, - upsert: upsert - }; - - // Clear out current Op - this.s.currentOp = null; - return this.s.options.addToOperationsList(this, UPDATE, document); - } - - /** - * Add a single update operation to the bulk operation - * - * @method - * @param {object} updateDocument An update field for an update operation. See {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-u u documentation} - * @throws {MongoError} If operation cannot be added to bulk write - * @return {OrderedBulkOperation|UnorderedBulkOperation} A reference to the parent BulkOperation - */ - updateOne(updateDocument) { - // Perform upsert - const upsert = typeof this.s.currentOp.upsert === 'boolean' ? this.s.currentOp.upsert : false; - - // Establish the update command - const document = { - q: this.s.currentOp.selector, - u: updateDocument, - multi: false, - upsert: upsert - }; - - // Clear out current Op - this.s.currentOp = null; - return this.s.options.addToOperationsList(this, UPDATE, document); - } - - /** - * Add a replace one operation to the bulk operation - * - * @method - * @param {object} updateDocument the new document to replace the existing one with - * @throws {MongoError} If operation cannot be added to bulk write - * @return {OrderedBulkOperation|UnorderedBulkOperation} A reference to the parent BulkOperation - */ - replaceOne(updateDocument) { - this.updateOne(updateDocument); - } - - /** - * Upsert modifier for update bulk operation, noting that this operation is an upsert. - * - * @method - * @throws {MongoError} If operation cannot be added to bulk write - * @return {FindOperators} reference to self - */ - upsert() { - this.s.currentOp.upsert = true; - return this; - } - - /** - * Add a delete one operation to the bulk operation - * - * @method - * @throws {MongoError} If operation cannot be added to bulk write - * @return {OrderedBulkOperation|UnorderedBulkOperation} A reference to the parent BulkOperation - */ - deleteOne() { - // Establish the update command - const document = { - q: this.s.currentOp.selector, - limit: 1 - }; - - // Clear out current Op - this.s.currentOp = null; - return this.s.options.addToOperationsList(this, REMOVE, document); - } - - /** - * Add a delete many operation to the bulk operation - * - * @method - * @throws {MongoError} If operation cannot be added to bulk write - * @return {OrderedBulkOperation|UnorderedBulkOperation} A reference to the parent BulkOperation - */ - delete() { - // Establish the update command - const document = { - q: this.s.currentOp.selector, - limit: 0 - }; - - // Clear out current Op - this.s.currentOp = null; - return this.s.options.addToOperationsList(this, REMOVE, document); - } - - /** - * backwards compatability for deleteOne - */ - removeOne() { - return this.deleteOne(); - } - - /** - * backwards compatability for delete - */ - remove() { - return this.delete(); - } -} - -/** - * @classdesc Parent class to OrderedBulkOperation and UnorderedBulkOperation - * - * **NOTE:** Internal Type, do not instantiate directly - */ -class BulkOperationBase { - /** - * Create a new OrderedBulkOperation or UnorderedBulkOperation instance - * @property {number} length Get the number of operations in the bulk. - */ - constructor(topology, collection, options, isOrdered) { - // determine whether bulkOperation is ordered or unordered - this.isOrdered = isOrdered; - - options = options == null ? {} : options; - // TODO Bring from driver information in isMaster - // Get the namespace for the write operations - const namespace = collection.s.namespace; - // Used to mark operation as executed - const executed = false; - - // Current item - const currentOp = null; - - // Handle to the bson serializer, used to calculate running sizes - const bson = topology.bson; - - // Set max byte size - const isMaster = topology.lastIsMaster(); - const maxBatchSizeBytes = - isMaster && isMaster.maxBsonObjectSize ? isMaster.maxBsonObjectSize : 1024 * 1024 * 16; - const maxWriteBatchSize = - isMaster && isMaster.maxWriteBatchSize ? isMaster.maxWriteBatchSize : 1000; - - // Calculates the largest possible size of an Array key, represented as a BSON string - // element. This calculation: - // 1 byte for BSON type - // # of bytes = length of (string representation of (maxWriteBatchSize - 1)) - // + 1 bytes for null terminator - const maxKeySize = (maxWriteBatchSize - 1).toString(10).length + 2; - - // Final options for retryable writes and write concern - let finalOptions = Object.assign({}, options); - finalOptions = applyRetryableWrites(finalOptions, collection.s.db); - finalOptions = applyWriteConcern(finalOptions, { collection: collection }, options); - const writeConcern = finalOptions.writeConcern; - - // Get the promiseLibrary - const promiseLibrary = options.promiseLibrary || Promise; - - // Final results - const bulkResult = { - ok: 1, - writeErrors: [], - writeConcernErrors: [], - insertedIds: [], - nInserted: 0, - nUpserted: 0, - nMatched: 0, - nModified: 0, - nRemoved: 0, - upserted: [] - }; - - // Internal state - this.s = { - // Final result - bulkResult: bulkResult, - // Current batch state - currentBatch: null, - currentIndex: 0, - // ordered specific - currentBatchSize: 0, - currentBatchSizeBytes: 0, - // unordered specific - currentInsertBatch: null, - currentUpdateBatch: null, - currentRemoveBatch: null, - batches: [], - // Write concern - writeConcern: writeConcern, - // Max batch size options - maxBatchSizeBytes: maxBatchSizeBytes, - maxWriteBatchSize: maxWriteBatchSize, - maxKeySize, - // Namespace - namespace: namespace, - // BSON - bson: bson, - // Topology - topology: topology, - // Options - options: finalOptions, - // Current operation - currentOp: currentOp, - // Executed - executed: executed, - // Collection - collection: collection, - // Promise Library - promiseLibrary: promiseLibrary, - // Fundamental error - err: null, - // check keys - checkKeys: typeof options.checkKeys === 'boolean' ? options.checkKeys : true - }; - - // bypass Validation - if (options.bypassDocumentValidation === true) { - this.s.bypassDocumentValidation = true; - } - } - - /** - * Add a single insert document to the bulk operation - * - * @param {object} document the document to insert - * @throws {MongoError} - * @return {BulkOperationBase} A reference to self - * - * @example - * const bulkOp = collection.initializeOrderedBulkOp(); - * // Adds three inserts to the bulkOp. - * bulkOp - * .insert({ a: 1 }) - * .insert({ b: 2 }) - * .insert({ c: 3 }); - * await bulkOp.execute(); - */ - insert(document) { - if (this.s.collection.s.db.options.forceServerObjectId !== true && document._id == null) - document._id = new ObjectID(); - return this.s.options.addToOperationsList(this, INSERT, document); - } - - /** - * Builds a find operation for an update/updateOne/delete/deleteOne/replaceOne. - * Returns a builder object used to complete the definition of the operation. - * - * @method - * @param {object} selector The selector for the bulk operation. See {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-q q documentation} - * @throws {MongoError} if a selector is not specified - * @return {FindOperators} A helper object with which the write operation can be defined. - * - * @example - * const bulkOp = collection.initializeOrderedBulkOp(); - * - * // Add an updateOne to the bulkOp - * bulkOp.find({ a: 1 }).updateOne({ $set: { b: 2 } }); - * - * // Add an updateMany to the bulkOp - * bulkOp.find({ c: 3 }).update({ $set: { d: 4 } }); - * - * // Add an upsert - * bulkOp.find({ e: 5 }).upsert().updateOne({ $set: { f: 6 } }); - * - * // Add a deletion - * bulkOp.find({ g: 7 }).deleteOne(); - * - * // Add a multi deletion - * bulkOp.find({ h: 8 }).delete(); - * - * // Add a replaceOne - * bulkOp.find({ i: 9 }).replaceOne({ j: 10 }); - * - * // Update using a pipeline (requires Mongodb 4.2 or higher) - * bulk.find({ k: 11, y: { $exists: true }, z: { $exists: true } }).updateOne([ - * { $set: { total: { $sum: [ '$y', '$z' ] } } } - * ]); - * - * // All of the ops will now be executed - * await bulkOp.execute(); - */ - find(selector) { - if (!selector) { - throw toError('Bulk find operation must specify a selector'); - } - - // Save a current selector - this.s.currentOp = { - selector: selector - }; - - return new FindOperators(this); - } - - /** - * Specifies a raw operation to perform in the bulk write. - * - * @method - * @param {object} op The raw operation to perform. - * @return {BulkOperationBase} A reference to self - */ - raw(op) { - const key = Object.keys(op)[0]; - - // Set up the force server object id - const forceServerObjectId = - typeof this.s.options.forceServerObjectId === 'boolean' - ? this.s.options.forceServerObjectId - : this.s.collection.s.db.options.forceServerObjectId; - - // Update operations - if ( - (op.updateOne && op.updateOne.q) || - (op.updateMany && op.updateMany.q) || - (op.replaceOne && op.replaceOne.q) - ) { - op[key].multi = op.updateOne || op.replaceOne ? false : true; - return this.s.options.addToOperationsList(this, UPDATE, op[key]); - } - - // Crud spec update format - if (op.updateOne || op.updateMany || op.replaceOne) { - const multi = op.updateOne || op.replaceOne ? false : true; - const operation = { - q: op[key].filter, - u: op[key].update || op[key].replacement, - multi: multi - }; - if (this.isOrdered) { - operation.upsert = op[key].upsert ? true : false; - if (op.collation) operation.collation = op.collation; - } else { - if (op[key].upsert) operation.upsert = true; - } - if (op[key].arrayFilters) operation.arrayFilters = op[key].arrayFilters; - return this.s.options.addToOperationsList(this, UPDATE, operation); - } - - // Remove operations - if ( - op.removeOne || - op.removeMany || - (op.deleteOne && op.deleteOne.q) || - (op.deleteMany && op.deleteMany.q) - ) { - op[key].limit = op.removeOne ? 1 : 0; - return this.s.options.addToOperationsList(this, REMOVE, op[key]); - } - - // Crud spec delete operations, less efficient - if (op.deleteOne || op.deleteMany) { - const limit = op.deleteOne ? 1 : 0; - const operation = { q: op[key].filter, limit: limit }; - if (this.isOrdered) { - if (op.collation) operation.collation = op.collation; - } - return this.s.options.addToOperationsList(this, REMOVE, operation); - } - - // Insert operations - if (op.insertOne && op.insertOne.document == null) { - if (forceServerObjectId !== true && op.insertOne._id == null) - op.insertOne._id = new ObjectID(); - return this.s.options.addToOperationsList(this, INSERT, op.insertOne); - } else if (op.insertOne && op.insertOne.document) { - if (forceServerObjectId !== true && op.insertOne.document._id == null) - op.insertOne.document._id = new ObjectID(); - return this.s.options.addToOperationsList(this, INSERT, op.insertOne.document); - } - - if (op.insertMany) { - for (let i = 0; i < op.insertMany.length; i++) { - if (forceServerObjectId !== true && op.insertMany[i]._id == null) - op.insertMany[i]._id = new ObjectID(); - this.s.options.addToOperationsList(this, INSERT, op.insertMany[i]); - } - - return; - } - - // No valid type of operation - throw toError( - 'bulkWrite only supports insertOne, insertMany, updateOne, updateMany, removeOne, removeMany, deleteOne, deleteMany' - ); - } - - /** - * helper function to assist with promiseOrCallback behavior - * @ignore - * @param {*} err - * @param {*} callback - */ - _handleEarlyError(err, callback) { - if (typeof callback === 'function') { - callback(err, null); - return; - } - - return this.s.promiseLibrary.reject(err); - } - - /** - * An internal helper method. Do not invoke directly. Will be going away in the future - * - * @ignore - * @method - * @param {class} bulk either OrderedBulkOperation or UnorderdBulkOperation - * @param {object} writeConcern - * @param {object} options - * @param {function} callback - */ - bulkExecute(_writeConcern, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - if (typeof _writeConcern === 'function') { - callback = _writeConcern; - } else if (_writeConcern && typeof _writeConcern === 'object') { - this.s.writeConcern = _writeConcern; - } - - if (this.s.executed) { - const executedError = toError('batch cannot be re-executed'); - return this._handleEarlyError(executedError, callback); - } - - // If we have current batch - if (this.isOrdered) { - if (this.s.currentBatch) this.s.batches.push(this.s.currentBatch); - } else { - if (this.s.currentInsertBatch) this.s.batches.push(this.s.currentInsertBatch); - if (this.s.currentUpdateBatch) this.s.batches.push(this.s.currentUpdateBatch); - if (this.s.currentRemoveBatch) this.s.batches.push(this.s.currentRemoveBatch); - } - // If we have no operations in the bulk raise an error - if (this.s.batches.length === 0) { - const emptyBatchError = toError('Invalid Operation, no operations specified'); - return this._handleEarlyError(emptyBatchError, callback); - } - return { options, callback }; - } - - /** - * The callback format for results - * @callback BulkOperationBase~resultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {BulkWriteResult} result The bulk write result. - */ - - /** - * Execute the bulk operation - * - * @method - * @param {WriteConcern} [_writeConcern] Optional write concern. Can also be specified through options. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.fsync=false] Specify a file sync write concern. - * @param {BulkOperationBase~resultCallback} [callback] A callback that will be invoked when bulkWrite finishes/errors - * @throws {MongoError} Throws error if the bulk object has already been executed - * @throws {MongoError} Throws error if the bulk object does not have any operations - * @return {Promise|void} returns Promise if no callback passed - */ - execute(_writeConcern, options, callback) { - const ret = this.bulkExecute(_writeConcern, options, callback); - if (!ret || isPromiseLike(ret)) { - return ret; - } - - options = ret.options; - callback = ret.callback; - - return executeLegacyOperation(this.s.topology, executeCommands, [this, options, callback]); - } - - /** - * Handles final options before executing command - * - * An internal method. Do not invoke. Will not be accessible in the future - * - * @ignore - * @param {object} config - * @param {object} config.options - * @param {number} config.batch - * @param {function} config.resultHandler - * @param {function} callback - */ - finalOptionsHandler(config, callback) { - const finalOptions = Object.assign({ ordered: this.isOrdered }, config.options); - if (this.s.writeConcern != null) { - finalOptions.writeConcern = this.s.writeConcern; - } - - if (finalOptions.bypassDocumentValidation !== true) { - delete finalOptions.bypassDocumentValidation; - } - - // Set an operationIf if provided - if (this.operationId) { - config.resultHandler.operationId = this.operationId; - } - - // Serialize functions - if (this.s.options.serializeFunctions) { - finalOptions.serializeFunctions = true; - } - - // Ignore undefined - if (this.s.options.ignoreUndefined) { - finalOptions.ignoreUndefined = true; - } - - // Is the bypassDocumentValidation options specific - if (this.s.bypassDocumentValidation === true) { - finalOptions.bypassDocumentValidation = true; - } - - // Is the checkKeys option disabled - if (this.s.checkKeys === false) { - finalOptions.checkKeys = false; - } - - if (finalOptions.retryWrites) { - if (config.batch.batchType === UPDATE) { - finalOptions.retryWrites = - finalOptions.retryWrites && !config.batch.operations.some(op => op.multi); - } - - if (config.batch.batchType === REMOVE) { - finalOptions.retryWrites = - finalOptions.retryWrites && !config.batch.operations.some(op => op.limit === 0); - } - } - - try { - if (config.batch.batchType === INSERT) { - this.s.topology.insert( - this.s.namespace, - config.batch.operations, - finalOptions, - config.resultHandler - ); - } else if (config.batch.batchType === UPDATE) { - this.s.topology.update( - this.s.namespace, - config.batch.operations, - finalOptions, - config.resultHandler - ); - } else if (config.batch.batchType === REMOVE) { - this.s.topology.remove( - this.s.namespace, - config.batch.operations, - finalOptions, - config.resultHandler - ); - } - } catch (err) { - // Force top level error - err.ok = 0; - // Merge top level error and return - handleCallback(callback, null, mergeBatchResults(config.batch, this.s.bulkResult, err, null)); - } - } - - /** - * Handles the write error before executing commands - * - * An internal helper method. Do not invoke directly. Will be going away in the future - * - * @ignore - * @param {function} callback - * @param {BulkWriteResult} writeResult - * @param {class} self either OrderedBulkOperation or UnorderdBulkOperation - */ - handleWriteError(callback, writeResult) { - if (this.s.bulkResult.writeErrors.length > 0) { - if (this.s.bulkResult.writeErrors.length === 1) { - handleCallback( - callback, - new BulkWriteError(toError(this.s.bulkResult.writeErrors[0]), writeResult), - null - ); - return true; - } - - const msg = this.s.bulkResult.writeErrors[0].errmsg - ? this.s.bulkResult.writeErrors[0].errmsg - : 'write operation failed'; - - handleCallback( - callback, - new BulkWriteError( - toError({ - message: msg, - code: this.s.bulkResult.writeErrors[0].code, - writeErrors: this.s.bulkResult.writeErrors - }), - writeResult - ), - null - ); - return true; - } else if (writeResult.getWriteConcernError()) { - handleCallback( - callback, - new BulkWriteError(toError(writeResult.getWriteConcernError()), writeResult), - null - ); - return true; - } - } -} - -Object.defineProperty(BulkOperationBase.prototype, 'length', { - enumerable: true, - get: function() { - return this.s.currentIndex; - } -}); - -// Exports symbols -module.exports = { - Batch, - BulkOperationBase, - bson, - INSERT: INSERT, - UPDATE: UPDATE, - REMOVE: REMOVE, - BulkWriteError -}; diff --git a/scripts/node_modules/mongodb/lib/bulk/ordered.js b/scripts/node_modules/mongodb/lib/bulk/ordered.js deleted file mode 100644 index e2507b86..00000000 --- a/scripts/node_modules/mongodb/lib/bulk/ordered.js +++ /dev/null @@ -1,105 +0,0 @@ -'use strict'; - -const common = require('./common'); -const BulkOperationBase = common.BulkOperationBase; -const Batch = common.Batch; -const bson = common.bson; -const utils = require('../utils'); -const toError = utils.toError; - -/** - * Add to internal list of Operations - * - * @ignore - * @param {OrderedBulkOperation} bulkOperation - * @param {number} docType number indicating the document type - * @param {object} document - * @return {OrderedBulkOperation} - */ -function addToOperationsList(bulkOperation, docType, document) { - // Get the bsonSize - const bsonSize = bson.calculateObjectSize(document, { - checkKeys: false, - - // Since we don't know what the user selected for BSON options here, - // err on the safe side, and check the size with ignoreUndefined: false. - ignoreUndefined: false - }); - - // Throw error if the doc is bigger than the max BSON size - if (bsonSize >= bulkOperation.s.maxBatchSizeBytes) - throw toError('document is larger than the maximum size ' + bulkOperation.s.maxBatchSizeBytes); - - // Create a new batch object if we don't have a current one - if (bulkOperation.s.currentBatch == null) - bulkOperation.s.currentBatch = new Batch(docType, bulkOperation.s.currentIndex); - - const maxKeySize = bulkOperation.s.maxKeySize; - - // Check if we need to create a new batch - if ( - bulkOperation.s.currentBatchSize + 1 >= bulkOperation.s.maxWriteBatchSize || - bulkOperation.s.currentBatchSizeBytes + maxKeySize + bsonSize >= - bulkOperation.s.maxBatchSizeBytes || - bulkOperation.s.currentBatch.batchType !== docType - ) { - // Save the batch to the execution stack - bulkOperation.s.batches.push(bulkOperation.s.currentBatch); - - // Create a new batch - bulkOperation.s.currentBatch = new Batch(docType, bulkOperation.s.currentIndex); - - // Reset the current size trackers - bulkOperation.s.currentBatchSize = 0; - bulkOperation.s.currentBatchSizeBytes = 0; - } - - if (docType === common.INSERT) { - bulkOperation.s.bulkResult.insertedIds.push({ - index: bulkOperation.s.currentIndex, - _id: document._id - }); - } - - // We have an array of documents - if (Array.isArray(document)) { - throw toError('operation passed in cannot be an Array'); - } - - bulkOperation.s.currentBatch.originalIndexes.push(bulkOperation.s.currentIndex); - bulkOperation.s.currentBatch.operations.push(document); - bulkOperation.s.currentBatchSize += 1; - bulkOperation.s.currentBatchSizeBytes += maxKeySize + bsonSize; - bulkOperation.s.currentIndex += 1; - - // Return bulkOperation - return bulkOperation; -} - -/** - * Create a new OrderedBulkOperation instance (INTERNAL TYPE, do not instantiate directly) - * @class - * @extends BulkOperationBase - * @property {number} length Get the number of operations in the bulk. - * @return {OrderedBulkOperation} a OrderedBulkOperation instance. - */ -class OrderedBulkOperation extends BulkOperationBase { - constructor(topology, collection, options) { - options = options || {}; - options = Object.assign(options, { addToOperationsList }); - - super(topology, collection, options, true); - } -} - -/** - * Returns an unordered batch object - * @ignore - */ -function initializeOrderedBulkOp(topology, collection, options) { - return new OrderedBulkOperation(topology, collection, options); -} - -initializeOrderedBulkOp.OrderedBulkOperation = OrderedBulkOperation; -module.exports = initializeOrderedBulkOp; -module.exports.Bulk = OrderedBulkOperation; diff --git a/scripts/node_modules/mongodb/lib/bulk/unordered.js b/scripts/node_modules/mongodb/lib/bulk/unordered.js deleted file mode 100644 index 999de3c4..00000000 --- a/scripts/node_modules/mongodb/lib/bulk/unordered.js +++ /dev/null @@ -1,118 +0,0 @@ -'use strict'; - -const common = require('./common'); -const BulkOperationBase = common.BulkOperationBase; -const Batch = common.Batch; -const bson = common.bson; -const utils = require('../utils'); -const toError = utils.toError; - -/** - * Add to internal list of Operations - * - * @ignore - * @param {UnorderedBulkOperation} bulkOperation - * @param {number} docType number indicating the document type - * @param {object} document - * @return {UnorderedBulkOperation} - */ -function addToOperationsList(bulkOperation, docType, document) { - // Get the bsonSize - const bsonSize = bson.calculateObjectSize(document, { - checkKeys: false, - - // Since we don't know what the user selected for BSON options here, - // err on the safe side, and check the size with ignoreUndefined: false. - ignoreUndefined: false - }); - // Throw error if the doc is bigger than the max BSON size - if (bsonSize >= bulkOperation.s.maxBatchSizeBytes) - throw toError('document is larger than the maximum size ' + bulkOperation.s.maxBatchSizeBytes); - // Holds the current batch - bulkOperation.s.currentBatch = null; - // Get the right type of batch - if (docType === common.INSERT) { - bulkOperation.s.currentBatch = bulkOperation.s.currentInsertBatch; - } else if (docType === common.UPDATE) { - bulkOperation.s.currentBatch = bulkOperation.s.currentUpdateBatch; - } else if (docType === common.REMOVE) { - bulkOperation.s.currentBatch = bulkOperation.s.currentRemoveBatch; - } - - const maxKeySize = bulkOperation.s.maxKeySize; - - // Create a new batch object if we don't have a current one - if (bulkOperation.s.currentBatch == null) - bulkOperation.s.currentBatch = new Batch(docType, bulkOperation.s.currentIndex); - - // Check if we need to create a new batch - if ( - bulkOperation.s.currentBatch.size + 1 >= bulkOperation.s.maxWriteBatchSize || - bulkOperation.s.currentBatch.sizeBytes + maxKeySize + bsonSize >= - bulkOperation.s.maxBatchSizeBytes || - bulkOperation.s.currentBatch.batchType !== docType - ) { - // Save the batch to the execution stack - bulkOperation.s.batches.push(bulkOperation.s.currentBatch); - - // Create a new batch - bulkOperation.s.currentBatch = new Batch(docType, bulkOperation.s.currentIndex); - } - - // We have an array of documents - if (Array.isArray(document)) { - throw toError('operation passed in cannot be an Array'); - } - - bulkOperation.s.currentBatch.operations.push(document); - bulkOperation.s.currentBatch.originalIndexes.push(bulkOperation.s.currentIndex); - bulkOperation.s.currentIndex = bulkOperation.s.currentIndex + 1; - - // Save back the current Batch to the right type - if (docType === common.INSERT) { - bulkOperation.s.currentInsertBatch = bulkOperation.s.currentBatch; - bulkOperation.s.bulkResult.insertedIds.push({ - index: bulkOperation.s.bulkResult.insertedIds.length, - _id: document._id - }); - } else if (docType === common.UPDATE) { - bulkOperation.s.currentUpdateBatch = bulkOperation.s.currentBatch; - } else if (docType === common.REMOVE) { - bulkOperation.s.currentRemoveBatch = bulkOperation.s.currentBatch; - } - - // Update current batch size - bulkOperation.s.currentBatch.size += 1; - bulkOperation.s.currentBatch.sizeBytes += maxKeySize + bsonSize; - - // Return bulkOperation - return bulkOperation; -} - -/** - * Create a new UnorderedBulkOperation instance (INTERNAL TYPE, do not instantiate directly) - * @class - * @extends BulkOperationBase - * @property {number} length Get the number of operations in the bulk. - * @return {UnorderedBulkOperation} a UnorderedBulkOperation instance. - */ -class UnorderedBulkOperation extends BulkOperationBase { - constructor(topology, collection, options) { - options = options || {}; - options = Object.assign(options, { addToOperationsList }); - - super(topology, collection, options, false); - } -} - -/** - * Returns an unordered batch object - * @ignore - */ -function initializeUnorderedBulkOp(topology, collection, options) { - return new UnorderedBulkOperation(topology, collection, options); -} - -initializeUnorderedBulkOp.UnorderedBulkOperation = UnorderedBulkOperation; -module.exports = initializeUnorderedBulkOp; -module.exports.Bulk = UnorderedBulkOperation; diff --git a/scripts/node_modules/mongodb/lib/change_stream.js b/scripts/node_modules/mongodb/lib/change_stream.js deleted file mode 100644 index 4cc779de..00000000 --- a/scripts/node_modules/mongodb/lib/change_stream.js +++ /dev/null @@ -1,576 +0,0 @@ -'use strict'; - -const EventEmitter = require('events'); -const isResumableError = require('./error').isResumableError; -const MongoError = require('./core').MongoError; -const Cursor = require('./cursor'); -const relayEvents = require('./core/utils').relayEvents; -const maxWireVersion = require('./core/utils').maxWireVersion; -const AggregateOperation = require('./operations/aggregate'); - -const CHANGE_STREAM_OPTIONS = ['resumeAfter', 'startAfter', 'startAtOperationTime', 'fullDocument']; -const CURSOR_OPTIONS = ['batchSize', 'maxAwaitTimeMS', 'collation', 'readPreference'].concat( - CHANGE_STREAM_OPTIONS -); - -const CHANGE_DOMAIN_TYPES = { - COLLECTION: Symbol('Collection'), - DATABASE: Symbol('Database'), - CLUSTER: Symbol('Cluster') -}; - -/** - * @typedef ResumeToken - * @description Represents the logical starting point for a new or resuming {@link ChangeStream} on the server. - * @see https://docs.mongodb.com/master/changeStreams/#change-stream-resume-token - */ - -/** - * @typedef OperationTime - * @description Represents a specific point in time on a server. Can be retrieved by using {@link Db#command} - * @see https://docs.mongodb.com/manual/reference/method/db.runCommand/#response - */ - -/** - * @typedef ChangeStreamOptions - * @description Options that can be passed to a ChangeStream. Note that startAfter, resumeAfter, and startAtOperationTime are all mutually exclusive, and the server will error if more than one is specified. - * @property {string} [fullDocument='default'] Allowed values: ‘default’, ‘updateLookup’. When set to ‘updateLookup’, the change stream will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred. - * @property {number} [maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a change stream query. - * @property {ResumeToken} [resumeAfter] Allows you to start a changeStream after a specified event. See {@link https://docs.mongodb.com/master/changeStreams/#resumeafter-for-change-streams|ChangeStream documentation}. - * @property {ResumeToken} [startAfter] Similar to resumeAfter, but will allow you to start after an invalidated event. See {@link https://docs.mongodb.com/master/changeStreams/#startafter-for-change-streams|ChangeStream documentation}. - * @property {OperationTime} [startAtOperationTime] Will start the changeStream after the specified operationTime. - * @property {number} [batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. - * @property {object} [collation] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. - * @property {ReadPreference} [readPreference] The read preference. Defaults to the read preference of the database or collection. See {@link https://docs.mongodb.com/manual/reference/read-preference|read preference documentation}. - */ - -/** - * Creates a new Change Stream instance. Normally created using {@link Collection#watch|Collection.watch()}. - * @class ChangeStream - * @since 3.0.0 - * @param {(MongoClient|Db|Collection)} parent The parent object that created this change stream - * @param {Array} pipeline An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents - * @param {ChangeStreamOptions} [options] Optional settings - * @fires ChangeStream#close - * @fires ChangeStream#change - * @fires ChangeStream#end - * @fires ChangeStream#error - * @fires ChangeStream#resumeTokenChanged - * @return {ChangeStream} a ChangeStream instance. - */ -class ChangeStream extends EventEmitter { - constructor(parent, pipeline, options) { - super(); - const Collection = require('./collection'); - const Db = require('./db'); - const MongoClient = require('./mongo_client'); - - this.pipeline = pipeline || []; - this.options = options || {}; - - this.parent = parent; - this.namespace = parent.s.namespace; - if (parent instanceof Collection) { - this.type = CHANGE_DOMAIN_TYPES.COLLECTION; - this.topology = parent.s.db.serverConfig; - } else if (parent instanceof Db) { - this.type = CHANGE_DOMAIN_TYPES.DATABASE; - this.topology = parent.serverConfig; - } else if (parent instanceof MongoClient) { - this.type = CHANGE_DOMAIN_TYPES.CLUSTER; - this.topology = parent.topology; - } else { - throw new TypeError( - 'parent provided to ChangeStream constructor is not an instance of Collection, Db, or MongoClient' - ); - } - - this.promiseLibrary = parent.s.promiseLibrary; - if (!this.options.readPreference && parent.s.readPreference) { - this.options.readPreference = parent.s.readPreference; - } - - // Create contained Change Stream cursor - this.cursor = createChangeStreamCursor(this, options); - - // Listen for any `change` listeners being added to ChangeStream - this.on('newListener', eventName => { - if (eventName === 'change' && this.cursor && this.listenerCount('change') === 0) { - this.cursor.on('data', change => - processNewChange({ changeStream: this, change, eventEmitter: true }) - ); - } - }); - - // Listen for all `change` listeners being removed from ChangeStream - this.on('removeListener', eventName => { - if (eventName === 'change' && this.listenerCount('change') === 0 && this.cursor) { - this.cursor.removeAllListeners('data'); - } - }); - } - - /** - * @property {ResumeToken} resumeToken - * The cached resume token that will be used to resume - * after the most recently returned change. - */ - get resumeToken() { - return this.cursor.resumeToken; - } - - /** - * Check if there is any document still available in the Change Stream - * @function ChangeStream.prototype.hasNext - * @param {ChangeStream~resultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ - hasNext(callback) { - return this.cursor.hasNext(callback); - } - - /** - * Get the next available document from the Change Stream, returns null if no more documents are available. - * @function ChangeStream.prototype.next - * @param {ChangeStream~resultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ - next(callback) { - var self = this; - if (this.isClosed()) { - if (callback) return callback(new Error('Change Stream is not open.'), null); - return self.promiseLibrary.reject(new Error('Change Stream is not open.')); - } - - return this.cursor - .next() - .then(change => processNewChange({ changeStream: self, change, callback })) - .catch(error => processNewChange({ changeStream: self, error, callback })); - } - - /** - * Is the cursor closed - * @method ChangeStream.prototype.isClosed - * @return {boolean} - */ - isClosed() { - if (this.cursor) { - return this.cursor.isClosed(); - } - return true; - } - - /** - * Close the Change Stream - * @method ChangeStream.prototype.close - * @param {ChangeStream~resultCallback} [callback] The result callback. - * @return {Promise} returns Promise if no callback passed - */ - close(callback) { - if (!this.cursor) { - if (callback) return callback(); - return this.promiseLibrary.resolve(); - } - - // Tidy up the existing cursor - const cursor = this.cursor; - - if (callback) { - return cursor.close(err => { - ['data', 'close', 'end', 'error'].forEach(event => cursor.removeAllListeners(event)); - delete this.cursor; - - return callback(err); - }); - } - - const PromiseCtor = this.promiseLibrary || Promise; - return new PromiseCtor((resolve, reject) => { - cursor.close(err => { - ['data', 'close', 'end', 'error'].forEach(event => cursor.removeAllListeners(event)); - delete this.cursor; - - if (err) return reject(err); - resolve(); - }); - }); - } - - /** - * This method pulls all the data out of a readable stream, and writes it to the supplied destination, automatically managing the flow so that the destination is not overwhelmed by a fast readable stream. - * @method - * @param {Writable} destination The destination for writing data - * @param {object} [options] {@link https://nodejs.org/api/stream.html#stream_readable_pipe_destination_options|Pipe options} - * @return {null} - */ - pipe(destination, options) { - if (!this.pipeDestinations) { - this.pipeDestinations = []; - } - this.pipeDestinations.push(destination); - return this.cursor.pipe(destination, options); - } - - /** - * This method will remove the hooks set up for a previous pipe() call. - * @param {Writable} [destination] The destination for writing data - * @return {null} - */ - unpipe(destination) { - if (this.pipeDestinations && this.pipeDestinations.indexOf(destination) > -1) { - this.pipeDestinations.splice(this.pipeDestinations.indexOf(destination), 1); - } - return this.cursor.unpipe(destination); - } - - /** - * Return a modified Readable stream including a possible transform method. - * @method - * @param {object} [options] Optional settings. - * @param {function} [options.transform] A transformation method applied to each document emitted by the stream. - * @return {Cursor} - */ - stream(options) { - this.streamOptions = options; - return this.cursor.stream(options); - } - - /** - * This method will cause a stream in flowing mode to stop emitting data events. Any data that becomes available will remain in the internal buffer. - * @return {null} - */ - pause() { - return this.cursor.pause(); - } - - /** - * This method will cause the readable stream to resume emitting data events. - * @return {null} - */ - resume() { - return this.cursor.resume(); - } -} - -class ChangeStreamCursor extends Cursor { - constructor(topology, operation, options) { - super(topology, operation, options); - - options = options || {}; - this._resumeToken = null; - this.startAtOperationTime = options.startAtOperationTime; - - if (options.startAfter) { - this.resumeToken = options.startAfter; - } else if (options.resumeAfter) { - this.resumeToken = options.resumeAfter; - } - } - - set resumeToken(token) { - this._resumeToken = token; - this.emit('resumeTokenChanged', token); - } - - get resumeToken() { - return this._resumeToken; - } - - get resumeOptions() { - const result = {}; - for (const optionName of CURSOR_OPTIONS) { - if (this.options[optionName]) result[optionName] = this.options[optionName]; - } - - if (this.resumeToken || this.startAtOperationTime) { - ['resumeAfter', 'startAfter', 'startAtOperationTime'].forEach(key => delete result[key]); - - if (this.resumeToken) { - result.resumeAfter = this.resumeToken; - } else if (this.startAtOperationTime && maxWireVersion(this.server) >= 7) { - result.startAtOperationTime = this.startAtOperationTime; - } - } - - return result; - } - - _initializeCursor(callback) { - super._initializeCursor((err, result) => { - if (err) { - callback(err, null); - return; - } - - const response = result.documents[0]; - - if ( - this.startAtOperationTime == null && - this.resumeAfter == null && - this.startAfter == null && - maxWireVersion(this.server) >= 7 - ) { - this.startAtOperationTime = response.operationTime; - } - - const cursor = response.cursor; - if (cursor.postBatchResumeToken) { - this.cursorState.postBatchResumeToken = cursor.postBatchResumeToken; - - if (cursor.firstBatch.length === 0) { - this.resumeToken = cursor.postBatchResumeToken; - } - } - - this.emit('response'); - callback(err, result); - }); - } - - _getMore(callback) { - super._getMore((err, response) => { - if (err) { - callback(err, null); - return; - } - - const cursor = response.cursor; - if (cursor.postBatchResumeToken) { - this.cursorState.postBatchResumeToken = cursor.postBatchResumeToken; - - if (cursor.nextBatch.length === 0) { - this.resumeToken = cursor.postBatchResumeToken; - } - } - - this.emit('response'); - callback(err, response); - }); - } -} - -/** - * @event ChangeStreamCursor#response - * internal event DO NOT USE - * @ignore - */ - -// Create a new change stream cursor based on self's configuration -function createChangeStreamCursor(self, options) { - const changeStreamStageOptions = { fullDocument: options.fullDocument || 'default' }; - applyKnownOptions(changeStreamStageOptions, options, CHANGE_STREAM_OPTIONS); - if (self.type === CHANGE_DOMAIN_TYPES.CLUSTER) { - changeStreamStageOptions.allChangesForCluster = true; - } - - const pipeline = [{ $changeStream: changeStreamStageOptions }].concat(self.pipeline); - const cursorOptions = applyKnownOptions({}, options, CURSOR_OPTIONS); - const changeStreamCursor = new ChangeStreamCursor( - self.topology, - new AggregateOperation(self.parent, pipeline, options), - cursorOptions - ); - - relayEvents(changeStreamCursor, self, ['resumeTokenChanged', 'end', 'close']); - - /** - * Fired for each new matching change in the specified namespace. Attaching a `change` - * event listener to a Change Stream will switch the stream into flowing mode. Data will - * then be passed as soon as it is available. - * - * @event ChangeStream#change - * @type {object} - */ - if (self.listenerCount('change') > 0) { - changeStreamCursor.on('data', function(change) { - processNewChange({ changeStream: self, change, eventEmitter: true }); - }); - } - - /** - * Change stream close event - * - * @event ChangeStream#close - * @type {null} - */ - - /** - * Change stream end event - * - * @event ChangeStream#end - * @type {null} - */ - - /** - * Emitted each time the change stream stores a new resume token. - * - * @event ChangeStream#resumeTokenChanged - * @type {ResumeToken} - */ - - /** - * Fired when the stream encounters an error. - * - * @event ChangeStream#error - * @type {Error} - */ - changeStreamCursor.on('error', function(error) { - processNewChange({ changeStream: self, error, eventEmitter: true }); - }); - - if (self.pipeDestinations) { - const cursorStream = changeStreamCursor.stream(self.streamOptions); - for (let pipeDestination in self.pipeDestinations) { - cursorStream.pipe(pipeDestination); - } - } - - return changeStreamCursor; -} - -function applyKnownOptions(target, source, optionNames) { - optionNames.forEach(name => { - if (source[name]) { - target[name] = source[name]; - } - }); - - return target; -} - -// This method performs a basic server selection loop, satisfying the requirements of -// ChangeStream resumability until the new SDAM layer can be used. -const SELECTION_TIMEOUT = 30000; -function waitForTopologyConnected(topology, options, callback) { - setTimeout(() => { - if (options && options.start == null) options.start = process.hrtime(); - const start = options.start || process.hrtime(); - const timeout = options.timeout || SELECTION_TIMEOUT; - const readPreference = options.readPreference; - - if (topology.isConnected({ readPreference })) return callback(null, null); - const hrElapsed = process.hrtime(start); - const elapsed = (hrElapsed[0] * 1e9 + hrElapsed[1]) / 1e6; - if (elapsed > timeout) return callback(new MongoError('Timed out waiting for connection')); - waitForTopologyConnected(topology, options, callback); - }, 3000); // this is an arbitrary wait time to allow SDAM to transition -} - -// Handle new change events. This method brings together the routes from the callback, event emitter, and promise ways of using ChangeStream. -function processNewChange(args) { - const changeStream = args.changeStream; - const error = args.error; - const change = args.change; - const callback = args.callback; - const eventEmitter = args.eventEmitter || false; - - // If the changeStream is closed, then it should not process a change. - if (changeStream.isClosed()) { - // We do not error in the eventEmitter case. - if (eventEmitter) { - return; - } - - const error = new MongoError('ChangeStream is closed'); - return typeof callback === 'function' - ? callback(error, null) - : changeStream.promiseLibrary.reject(error); - } - - const cursor = changeStream.cursor; - const topology = changeStream.topology; - const options = changeStream.cursor.options; - - if (error) { - if (isResumableError(error) && !changeStream.attemptingResume) { - changeStream.attemptingResume = true; - - // stop listening to all events from old cursor - ['data', 'close', 'end', 'error'].forEach(event => - changeStream.cursor.removeAllListeners(event) - ); - - // close internal cursor, ignore errors - changeStream.cursor.close(); - - // attempt recreating the cursor - if (eventEmitter) { - waitForTopologyConnected(topology, { readPreference: options.readPreference }, err => { - if (err) { - changeStream.emit('error', err); - changeStream.emit('close'); - return; - } - changeStream.cursor = createChangeStreamCursor(changeStream, cursor.resumeOptions); - }); - - return; - } - - if (callback) { - waitForTopologyConnected(topology, { readPreference: options.readPreference }, err => { - if (err) return callback(err, null); - - changeStream.cursor = createChangeStreamCursor(changeStream, cursor.resumeOptions); - changeStream.next(callback); - }); - - return; - } - - return new Promise((resolve, reject) => { - waitForTopologyConnected(topology, { readPreference: options.readPreference }, err => { - if (err) return reject(err); - resolve(); - }); - }) - .then( - () => (changeStream.cursor = createChangeStreamCursor(changeStream, cursor.resumeOptions)) - ) - .then(() => changeStream.next()); - } - - if (eventEmitter) return changeStream.emit('error', error); - if (typeof callback === 'function') return callback(error, null); - return changeStream.promiseLibrary.reject(error); - } - - changeStream.attemptingResume = false; - - if (change && !change._id) { - const noResumeTokenError = new Error( - 'A change stream document has been received that lacks a resume token (_id).' - ); - - if (eventEmitter) return changeStream.emit('error', noResumeTokenError); - if (typeof callback === 'function') return callback(noResumeTokenError, null); - return changeStream.promiseLibrary.reject(noResumeTokenError); - } - - // cache the resume token - if (cursor.bufferedCount() === 0 && cursor.cursorState.postBatchResumeToken) { - cursor.resumeToken = cursor.cursorState.postBatchResumeToken; - } else { - cursor.resumeToken = change._id; - } - - // wipe the startAtOperationTime if there was one so that there won't be a conflict - // between resumeToken and startAtOperationTime if we need to reconnect the cursor - changeStream.options.startAtOperationTime = undefined; - - // Return the change - if (eventEmitter) return changeStream.emit('change', change); - if (typeof callback === 'function') return callback(error, change); - return changeStream.promiseLibrary.resolve(change); -} - -/** - * The callback format for results - * @callback ChangeStream~resultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {(object|null)} result The result object if the command was executed successfully. - */ - -module.exports = ChangeStream; diff --git a/scripts/node_modules/mongodb/lib/collection.js b/scripts/node_modules/mongodb/lib/collection.js deleted file mode 100644 index 49edbdbe..00000000 --- a/scripts/node_modules/mongodb/lib/collection.js +++ /dev/null @@ -1,2113 +0,0 @@ -'use strict'; - -const deprecate = require('util').deprecate; -const deprecateOptions = require('./utils').deprecateOptions; -const checkCollectionName = require('./utils').checkCollectionName; -const ObjectID = require('./core').BSON.ObjectID; -const MongoError = require('./core').MongoError; -const toError = require('./utils').toError; -const normalizeHintField = require('./utils').normalizeHintField; -const decorateCommand = require('./utils').decorateCommand; -const decorateWithCollation = require('./utils').decorateWithCollation; -const decorateWithReadConcern = require('./utils').decorateWithReadConcern; -const formattedOrderClause = require('./utils').formattedOrderClause; -const ReadPreference = require('./core').ReadPreference; -const unordered = require('./bulk/unordered'); -const ordered = require('./bulk/ordered'); -const ChangeStream = require('./change_stream'); -const executeLegacyOperation = require('./utils').executeLegacyOperation; -const resolveReadPreference = require('./utils').resolveReadPreference; -const WriteConcern = require('./write_concern'); -const ReadConcern = require('./read_concern'); -const MongoDBNamespace = require('./utils').MongoDBNamespace; -const AggregationCursor = require('./aggregation_cursor'); -const CommandCursor = require('./command_cursor'); - -// Operations -const checkForAtomicOperators = require('./operations/collection_ops').checkForAtomicOperators; -const ensureIndex = require('./operations/collection_ops').ensureIndex; -const group = require('./operations/collection_ops').group; -const parallelCollectionScan = require('./operations/collection_ops').parallelCollectionScan; -const removeDocuments = require('./operations/common_functions').removeDocuments; -const save = require('./operations/collection_ops').save; -const updateDocuments = require('./operations/common_functions').updateDocuments; - -const AggregateOperation = require('./operations/aggregate'); -const BulkWriteOperation = require('./operations/bulk_write'); -const CountDocumentsOperation = require('./operations/count_documents'); -const CreateIndexOperation = require('./operations/create_index'); -const CreateIndexesOperation = require('./operations/create_indexes'); -const DeleteManyOperation = require('./operations/delete_many'); -const DeleteOneOperation = require('./operations/delete_one'); -const DistinctOperation = require('./operations/distinct'); -const DropCollectionOperation = require('./operations/drop').DropCollectionOperation; -const DropIndexOperation = require('./operations/drop_index'); -const DropIndexesOperation = require('./operations/drop_indexes'); -const EstimatedDocumentCountOperation = require('./operations/estimated_document_count'); -const FindOperation = require('./operations/find'); -const FindOneOperation = require('./operations/find_one'); -const FindAndModifyOperation = require('./operations/find_and_modify'); -const FindOneAndDeleteOperation = require('./operations/find_one_and_delete'); -const FindOneAndReplaceOperation = require('./operations/find_one_and_replace'); -const FindOneAndUpdateOperation = require('./operations/find_one_and_update'); -const GeoHaystackSearchOperation = require('./operations/geo_haystack_search'); -const IndexesOperation = require('./operations/indexes'); -const IndexExistsOperation = require('./operations/index_exists'); -const IndexInformationOperation = require('./operations/index_information'); -const InsertManyOperation = require('./operations/insert_many'); -const InsertOneOperation = require('./operations/insert_one'); -const IsCappedOperation = require('./operations/is_capped'); -const ListIndexesOperation = require('./operations/list_indexes'); -const MapReduceOperation = require('./operations/map_reduce'); -const OptionsOperation = require('./operations/options_operation'); -const RenameOperation = require('./operations/rename'); -const ReIndexOperation = require('./operations/re_index'); -const ReplaceOneOperation = require('./operations/replace_one'); -const StatsOperation = require('./operations/stats'); -const UpdateManyOperation = require('./operations/update_many'); -const UpdateOneOperation = require('./operations/update_one'); - -const executeOperation = require('./operations/execute_operation'); - -/** - * @fileOverview The **Collection** class is an internal class that embodies a MongoDB collection - * allowing for insert/update/remove/find and other command operation on that MongoDB collection. - * - * **COLLECTION Cannot directly be instantiated** - * @example - * const MongoClient = require('mongodb').MongoClient; - * const test = require('assert'); - * // Connection url - * const url = 'mongodb://localhost:27017'; - * // Database Name - * const dbName = 'test'; - * // Connect using MongoClient - * MongoClient.connect(url, function(err, client) { - * // Create a collection we want to drop later - * const col = client.db(dbName).collection('createIndexExample1'); - * // Show that duplicate records got dropped - * col.find({}).toArray(function(err, items) { - * test.equal(null, err); - * test.equal(4, items.length); - * client.close(); - * }); - * }); - */ - -const mergeKeys = ['ignoreUndefined']; - -/** - * Create a new Collection instance (INTERNAL TYPE, do not instantiate directly) - * @class - * @property {string} collectionName Get the collection name. - * @property {string} namespace Get the full collection namespace. - * @property {object} writeConcern The current write concern values. - * @property {object} readConcern The current read concern values. - * @property {object} hint Get current index hint for collection. - * @return {Collection} a Collection instance. - */ -function Collection(db, topology, dbName, name, pkFactory, options) { - checkCollectionName(name); - - // Unpack variables - const internalHint = null; - const slaveOk = options == null || options.slaveOk == null ? db.slaveOk : options.slaveOk; - const serializeFunctions = - options == null || options.serializeFunctions == null - ? db.s.options.serializeFunctions - : options.serializeFunctions; - const raw = options == null || options.raw == null ? db.s.options.raw : options.raw; - const promoteLongs = - options == null || options.promoteLongs == null - ? db.s.options.promoteLongs - : options.promoteLongs; - const promoteValues = - options == null || options.promoteValues == null - ? db.s.options.promoteValues - : options.promoteValues; - const promoteBuffers = - options == null || options.promoteBuffers == null - ? db.s.options.promoteBuffers - : options.promoteBuffers; - const collectionHint = null; - - const namespace = new MongoDBNamespace(dbName, name); - - // Get the promiseLibrary - const promiseLibrary = options.promiseLibrary || Promise; - - // Set custom primary key factory if provided - pkFactory = pkFactory == null ? ObjectID : pkFactory; - - // Internal state - this.s = { - // Set custom primary key factory if provided - pkFactory: pkFactory, - // Db - db: db, - // Topology - topology: topology, - // Options - options: options, - // Namespace - namespace: namespace, - // Read preference - readPreference: ReadPreference.fromOptions(options), - // SlaveOK - slaveOk: slaveOk, - // Serialize functions - serializeFunctions: serializeFunctions, - // Raw - raw: raw, - // promoteLongs - promoteLongs: promoteLongs, - // promoteValues - promoteValues: promoteValues, - // promoteBuffers - promoteBuffers: promoteBuffers, - // internalHint - internalHint: internalHint, - // collectionHint - collectionHint: collectionHint, - // Promise library - promiseLibrary: promiseLibrary, - // Read Concern - readConcern: ReadConcern.fromOptions(options), - // Write Concern - writeConcern: WriteConcern.fromOptions(options) - }; -} - -Object.defineProperty(Collection.prototype, 'dbName', { - enumerable: true, - get: function() { - return this.s.namespace.db; - } -}); - -Object.defineProperty(Collection.prototype, 'collectionName', { - enumerable: true, - get: function() { - return this.s.namespace.collection; - } -}); - -Object.defineProperty(Collection.prototype, 'namespace', { - enumerable: true, - get: function() { - return this.s.namespace.toString(); - } -}); - -Object.defineProperty(Collection.prototype, 'readConcern', { - enumerable: true, - get: function() { - if (this.s.readConcern == null) { - return this.s.db.readConcern; - } - return this.s.readConcern; - } -}); - -Object.defineProperty(Collection.prototype, 'readPreference', { - enumerable: true, - get: function() { - if (this.s.readPreference == null) { - return this.s.db.readPreference; - } - - return this.s.readPreference; - } -}); - -Object.defineProperty(Collection.prototype, 'writeConcern', { - enumerable: true, - get: function() { - if (this.s.writeConcern == null) { - return this.s.db.writeConcern; - } - return this.s.writeConcern; - } -}); - -/** - * @ignore - */ -Object.defineProperty(Collection.prototype, 'hint', { - enumerable: true, - get: function() { - return this.s.collectionHint; - }, - set: function(v) { - this.s.collectionHint = normalizeHintField(v); - } -}); - -const DEPRECATED_FIND_OPTIONS = ['maxScan', 'fields', 'snapshot']; - -/** - * Creates a cursor for a query that can be used to iterate over results from MongoDB - * @method - * @param {object} [query={}] The cursor query object. - * @param {object} [options] Optional settings. - * @param {number} [options.limit=0] Sets the limit of documents returned in the query. - * @param {(array|object)} [options.sort] Set to sort the documents coming back from the query. Array of indexes, [['a', 1]] etc. - * @param {object} [options.projection] The fields to return in the query. Object of fields to include or exclude (not both), {'a':1} - * @param {object} [options.fields] **Deprecated** Use `options.projection` instead - * @param {number} [options.skip=0] Set to skip N documents ahead in your query (useful for pagination). - * @param {Object} [options.hint] Tell the query to use specific indexes in the query. Object of indexes to use, {'_id':1} - * @param {boolean} [options.explain=false] Explain the query instead of returning the data. - * @param {boolean} [options.snapshot=false] DEPRECATED: Snapshot query. - * @param {boolean} [options.timeout=false] Specify if the cursor can timeout. - * @param {boolean} [options.tailable=false] Specify if the cursor is tailable. - * @param {number} [options.batchSize=1000] Set the batchSize for the getMoreCommand when iterating over the query results. - * @param {boolean} [options.returnKey=false] Only return the index key. - * @param {number} [options.maxScan] DEPRECATED: Limit the number of items to scan. - * @param {number} [options.min] Set index bounds. - * @param {number} [options.max] Set index bounds. - * @param {boolean} [options.showDiskLoc=false] Show disk location of results. - * @param {string} [options.comment] You can put a $comment field on a query to make looking in the profiler logs simpler. - * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. - * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution. - * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. - * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {boolean} [options.partial=false] Specify if the cursor should return partial results when querying against a sharded system - * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query. - * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {ClientSession} [options.session] optional session to use for this operation - * @throws {MongoError} - * @return {Cursor} - */ -Collection.prototype.find = deprecateOptions( - { - name: 'collection.find', - deprecatedOptions: DEPRECATED_FIND_OPTIONS, - optionsIndex: 1 - }, - function(query, options, callback) { - if (typeof callback === 'object') { - // TODO(MAJOR): throw in the future - console.warn('Third parameter to `find()` must be a callback or undefined'); - } - - let selector = query; - // figuring out arguments - if (typeof callback !== 'function') { - if (typeof options === 'function') { - callback = options; - options = undefined; - } else if (options == null) { - callback = typeof selector === 'function' ? selector : undefined; - selector = typeof selector === 'object' ? selector : undefined; - } - } - - // Ensure selector is not null - selector = selector == null ? {} : selector; - // Validate correctness off the selector - const object = selector; - if (Buffer.isBuffer(object)) { - const object_size = object[0] | (object[1] << 8) | (object[2] << 16) | (object[3] << 24); - if (object_size !== object.length) { - const error = new Error( - 'query selector raw message size does not match message header size [' + - object.length + - '] != [' + - object_size + - ']' - ); - error.name = 'MongoError'; - throw error; - } - } - - // Check special case where we are using an objectId - if (selector != null && selector._bsontype === 'ObjectID') { - selector = { _id: selector }; - } - - if (!options) options = {}; - - let projection = options.projection || options.fields; - - if (projection && !Buffer.isBuffer(projection) && Array.isArray(projection)) { - projection = projection.length - ? projection.reduce((result, field) => { - result[field] = 1; - return result; - }, {}) - : { _id: 1 }; - } - - // Make a shallow copy of options - let newOptions = Object.assign({}, options); - - // Make a shallow copy of the collection options - for (let key in this.s.options) { - if (mergeKeys.indexOf(key) !== -1) { - newOptions[key] = this.s.options[key]; - } - } - - // Unpack options - newOptions.skip = options.skip ? options.skip : 0; - newOptions.limit = options.limit ? options.limit : 0; - newOptions.raw = typeof options.raw === 'boolean' ? options.raw : this.s.raw; - newOptions.hint = - options.hint != null ? normalizeHintField(options.hint) : this.s.collectionHint; - newOptions.timeout = typeof options.timeout === 'undefined' ? undefined : options.timeout; - // // If we have overridden slaveOk otherwise use the default db setting - newOptions.slaveOk = options.slaveOk != null ? options.slaveOk : this.s.db.slaveOk; - - // Add read preference if needed - newOptions.readPreference = resolveReadPreference(this, newOptions); - - // Set slave ok to true if read preference different from primary - if ( - newOptions.readPreference != null && - (newOptions.readPreference !== 'primary' || newOptions.readPreference.mode !== 'primary') - ) { - newOptions.slaveOk = true; - } - - // Ensure the query is an object - if (selector != null && typeof selector !== 'object') { - throw MongoError.create({ message: 'query selector must be an object', driver: true }); - } - - // Build the find command - const findCommand = { - find: this.s.namespace.toString(), - limit: newOptions.limit, - skip: newOptions.skip, - query: selector - }; - - // Ensure we use the right await data option - if (typeof newOptions.awaitdata === 'boolean') { - newOptions.awaitData = newOptions.awaitdata; - } - - // Translate to new command option noCursorTimeout - if (typeof newOptions.timeout === 'boolean') newOptions.noCursorTimeout = newOptions.timeout; - - decorateCommand(findCommand, newOptions, ['session', 'collation']); - - if (projection) findCommand.fields = projection; - - // Add db object to the new options - newOptions.db = this.s.db; - - // Add the promise library - newOptions.promiseLibrary = this.s.promiseLibrary; - - // Set raw if available at collection level - if (newOptions.raw == null && typeof this.s.raw === 'boolean') newOptions.raw = this.s.raw; - // Set promoteLongs if available at collection level - if (newOptions.promoteLongs == null && typeof this.s.promoteLongs === 'boolean') - newOptions.promoteLongs = this.s.promoteLongs; - if (newOptions.promoteValues == null && typeof this.s.promoteValues === 'boolean') - newOptions.promoteValues = this.s.promoteValues; - if (newOptions.promoteBuffers == null && typeof this.s.promoteBuffers === 'boolean') - newOptions.promoteBuffers = this.s.promoteBuffers; - - // Sort options - if (findCommand.sort) { - findCommand.sort = formattedOrderClause(findCommand.sort); - } - - // Set the readConcern - decorateWithReadConcern(findCommand, this, options); - - // Decorate find command with collation options - try { - decorateWithCollation(findCommand, this, options); - } catch (err) { - if (typeof callback === 'function') return callback(err, null); - throw err; - } - - const cursor = this.s.topology.cursor( - new FindOperation(this, this.s.namespace, findCommand, newOptions), - newOptions - ); - - // TODO: remove this when NODE-2074 is resolved - if (typeof callback === 'function') { - callback(null, cursor); - return; - } - - return cursor; - } -); - -/** - * Inserts a single document into MongoDB. If documents passed in do not contain the **_id** field, - * one will be added to each of the documents missing it by the driver, mutating the document. This behavior - * can be overridden by setting the **forceServerObjectId** flag. - * - * @method - * @param {object} doc Document to insert. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~insertOneWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.insertOne = function(doc, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // Add ignoreUndefined - if (this.s.options.ignoreUndefined) { - options = Object.assign({}, options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - const insertOneOperation = new InsertOneOperation(this, doc, options); - - return executeOperation(this.s.topology, insertOneOperation, callback); -}; - -/** - * Inserts an array of documents into MongoDB. If documents passed in do not contain the **_id** field, - * one will be added to each of the documents missing it by the driver, mutating the document. This behavior - * can be overridden by setting the **forceServerObjectId** flag. - * - * @method - * @param {object[]} docs Documents to insert. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {boolean} [options.ordered=true] If true, when an insert fails, don't execute the remaining writes. If false, continue with remaining inserts when one fails. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~insertWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.insertMany = function(docs, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options ? Object.assign({}, options) : { ordered: true }; - - const insertManyOperation = new InsertManyOperation(this, docs, options); - - return executeOperation(this.s.topology, insertManyOperation, callback); -}; - -/** - * @typedef {Object} Collection~BulkWriteOpResult - * @property {number} insertedCount Number of documents inserted. - * @property {number} matchedCount Number of documents matched for update. - * @property {number} modifiedCount Number of documents modified. - * @property {number} deletedCount Number of documents deleted. - * @property {number} upsertedCount Number of documents upserted. - * @property {object} insertedIds Inserted document generated Id's, hash key is the index of the originating operation - * @property {object} upsertedIds Upserted document generated Id's, hash key is the index of the originating operation - * @property {object} result The command result object. - */ - -/** - * The callback format for inserts - * @callback Collection~bulkWriteOpCallback - * @param {BulkWriteError} error An error instance representing the error during the execution. - * @param {Collection~BulkWriteOpResult} result The result object if the command was executed successfully. - */ - -/** - * Perform a bulkWrite operation without a fluent API - * - * Legal operation types are - * - * { insertOne: { document: { a: 1 } } } - * - * { updateOne: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } } - * - * { updateMany: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } } - * - * { updateMany: { filter: {}, update: {$set: {"a.$[i].x": 5}}, arrayFilters: [{ "i.x": 5 }]} } - * - * { deleteOne: { filter: {c:1} } } - * - * { deleteMany: { filter: {c:1} } } - * - * { replaceOne: { filter: {c:3}, replacement: {c:4}, upsert:true}} - * - * If documents passed in do not contain the **_id** field, - * one will be added to each of the documents missing it by the driver, mutating the document. This behavior - * can be overridden by setting the **forceServerObjectId** flag. - * - * @method - * @param {object[]} operations Bulk operations to perform. - * @param {object} [options] Optional settings. - * @param {object[]} [options.arrayFilters] Determines which array elements to modify for update operation in MongoDB 3.6 or higher. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {boolean} [options.ordered=true] Execute write operation in ordered or unordered fashion. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~bulkWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.bulkWrite = function(operations, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || { ordered: true }; - - if (!Array.isArray(operations)) { - throw MongoError.create({ message: 'operations must be an array of documents', driver: true }); - } - - const bulkWriteOperation = new BulkWriteOperation(this, operations, options); - - return executeOperation(this.s.topology, bulkWriteOperation, callback); -}; - -/** - * @typedef {Object} Collection~WriteOpResult - * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany - * @property {object} connection The connection object used for the operation. - * @property {object} result The command result object. - */ - -/** - * The callback format for inserts - * @callback Collection~writeOpCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection~WriteOpResult} result The result object if the command was executed successfully. - */ - -/** - * @typedef {Object} Collection~insertWriteOpResult - * @property {Number} insertedCount The total amount of documents inserted. - * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany - * @property {Object.} insertedIds Map of the index of the inserted document to the id of the inserted document. - * @property {object} connection The connection object used for the operation. - * @property {object} result The raw command result object returned from MongoDB (content might vary by server version). - * @property {Number} result.ok Is 1 if the command executed correctly. - * @property {Number} result.n The total count of documents inserted. - */ - -/** - * @typedef {Object} Collection~insertOneWriteOpResult - * @property {Number} insertedCount The total amount of documents inserted. - * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany - * @property {ObjectId} insertedId The driver generated ObjectId for the insert operation. - * @property {object} connection The connection object used for the operation. - * @property {object} result The raw command result object returned from MongoDB (content might vary by server version). - * @property {Number} result.ok Is 1 if the command executed correctly. - * @property {Number} result.n The total count of documents inserted. - */ - -/** - * The callback format for inserts - * @callback Collection~insertWriteOpCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection~insertWriteOpResult} result The result object if the command was executed successfully. - */ - -/** - * The callback format for inserts - * @callback Collection~insertOneWriteOpCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection~insertOneWriteOpResult} result The result object if the command was executed successfully. - */ - -/** - * Inserts a single document or a an array of documents into MongoDB. If documents passed in do not contain the **_id** field, - * one will be added to each of the documents missing it by the driver, mutating the document. This behavior - * can be overridden by setting the **forceServerObjectId** flag. - * - * @method - * @param {(object|object[])} docs Documents to insert. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~insertWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - * @deprecated Use insertOne, insertMany or bulkWrite - */ -Collection.prototype.insert = deprecate(function(docs, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || { ordered: false }; - docs = !Array.isArray(docs) ? [docs] : docs; - - if (options.keepGoing === true) { - options.ordered = false; - } - - return this.insertMany(docs, options, callback); -}, 'collection.insert is deprecated. Use insertOne, insertMany or bulkWrite instead.'); - -/** - * @typedef {Object} Collection~updateWriteOpResult - * @property {Object} result The raw result returned from MongoDB. Will vary depending on server version. - * @property {Number} result.ok Is 1 if the command executed correctly. - * @property {Number} result.n The total count of documents scanned. - * @property {Number} result.nModified The total count of documents modified. - * @property {Object} connection The connection object used for the operation. - * @property {Number} matchedCount The number of documents that matched the filter. - * @property {Number} modifiedCount The number of documents that were modified. - * @property {Number} upsertedCount The number of documents upserted. - * @property {Object} upsertedId The upserted id. - * @property {ObjectId} upsertedId._id The upserted _id returned from the server. - * @property {Object} message - * @property {object[]} [ops] In a response to {@link Collection#replaceOne replaceOne}, contains the new value of the document on the server. This is the same document that was originally passed in, and is only here for legacy purposes. - */ - -/** - * The callback format for inserts - * @callback Collection~updateWriteOpCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection~updateWriteOpResult} result The result object if the command was executed successfully. - */ - -/** - * Update a single document in a collection - * @method - * @param {object} filter The Filter used to select the document to update - * @param {object} update The update operations to be applied to the document - * @param {object} [options] Optional settings. - * @param {boolean} [options.upsert=false] Update operation is an upsert. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {Array} [options.arrayFilters] optional list of array filters referenced in filtered positional operators - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~updateWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.updateOne = function(filter, update, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const err = checkForAtomicOperators(update); - if (err) { - if (typeof callback === 'function') return callback(err); - return this.s.promiseLibrary.reject(err); - } - - options = Object.assign({}, options); - - // Add ignoreUndefined - if (this.s.options.ignoreUndefined) { - options = Object.assign({}, options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - const updateOneOperation = new UpdateOneOperation(this, filter, update, options); - - return executeOperation(this.s.topology, updateOneOperation, callback); -}; - -/** - * Replace a document in a collection with another document - * @method - * @param {object} filter The Filter used to select the document to replace - * @param {object} doc The Document that replaces the matching document - * @param {object} [options] Optional settings. - * @param {boolean} [options.upsert=false] Update operation is an upsert. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~updateWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.replaceOne = function(filter, doc, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = Object.assign({}, options); - - // Add ignoreUndefined - if (this.s.options.ignoreUndefined) { - options = Object.assign({}, options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - const replaceOneOperation = new ReplaceOneOperation(this, filter, doc, options); - - return executeOperation(this.s.topology, replaceOneOperation, callback); -}; - -/** - * Update multiple documents in a collection - * @method - * @param {object} filter The Filter used to select the documents to update - * @param {object} update The update operations to be applied to the documents - * @param {object} [options] Optional settings. - * @param {boolean} [options.upsert=false] Update operation is an upsert. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {Array} [options.arrayFilters] optional list of array filters referenced in filtered positional operators - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~updateWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.updateMany = function(filter, update, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const err = checkForAtomicOperators(update); - if (err) { - if (typeof callback === 'function') return callback(err); - return this.s.promiseLibrary.reject(err); - } - - options = Object.assign({}, options); - - // Add ignoreUndefined - if (this.s.options.ignoreUndefined) { - options = Object.assign({}, options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - const updateManyOperation = new UpdateManyOperation(this, filter, update, options); - - return executeOperation(this.s.topology, updateManyOperation, callback); -}; - -/** - * Updates documents. - * @method - * @param {object} selector The selector for the update operation. - * @param {object} update The update operations to be applied to the documents - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.upsert=false] Update operation is an upsert. - * @param {boolean} [options.multi=false] Update one/all documents with operation. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {Array} [options.arrayFilters] optional list of array filters referenced in filtered positional operators - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~writeOpCallback} [callback] The command result callback - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - * @deprecated use updateOne, updateMany or bulkWrite - */ -Collection.prototype.update = deprecate(function(selector, update, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // Add ignoreUndefined - if (this.s.options.ignoreUndefined) { - options = Object.assign({}, options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - return executeLegacyOperation(this.s.topology, updateDocuments, [ - this, - selector, - update, - options, - callback - ]); -}, 'collection.update is deprecated. Use updateOne, updateMany, or bulkWrite instead.'); - -/** - * @typedef {Object} Collection~deleteWriteOpResult - * @property {Object} result The raw result returned from MongoDB. Will vary depending on server version. - * @property {Number} result.ok Is 1 if the command executed correctly. - * @property {Number} result.n The total count of documents deleted. - * @property {Object} connection The connection object used for the operation. - * @property {Number} deletedCount The number of documents deleted. - */ - -/** - * The callback format for inserts - * @callback Collection~deleteWriteOpCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection~deleteWriteOpResult} result The result object if the command was executed successfully. - */ - -/** - * Delete a document from a collection - * @method - * @param {object} filter The Filter used to select the document to remove - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~deleteWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.deleteOne = function(filter, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = Object.assign({}, options); - - // Add ignoreUndefined - if (this.s.options.ignoreUndefined) { - options = Object.assign({}, options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - const deleteOneOperation = new DeleteOneOperation(this, filter, options); - - return executeOperation(this.s.topology, deleteOneOperation, callback); -}; - -Collection.prototype.removeOne = Collection.prototype.deleteOne; - -/** - * Delete multiple documents from a collection - * @method - * @param {object} filter The Filter used to select the documents to remove - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~deleteWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.deleteMany = function(filter, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = Object.assign({}, options); - - // Add ignoreUndefined - if (this.s.options.ignoreUndefined) { - options = Object.assign({}, options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - const deleteManyOperation = new DeleteManyOperation(this, filter, options); - - return executeOperation(this.s.topology, deleteManyOperation, callback); -}; - -Collection.prototype.removeMany = Collection.prototype.deleteMany; - -/** - * Remove documents. - * @method - * @param {object} selector The selector for the update operation. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.single=false] Removes the first document found. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~writeOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - * @deprecated use deleteOne, deleteMany or bulkWrite - */ -Collection.prototype.remove = deprecate(function(selector, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // Add ignoreUndefined - if (this.s.options.ignoreUndefined) { - options = Object.assign({}, options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - return executeLegacyOperation(this.s.topology, removeDocuments, [ - this, - selector, - options, - callback - ]); -}, 'collection.remove is deprecated. Use deleteOne, deleteMany, or bulkWrite instead.'); - -/** - * Save a document. Simple full document replacement function. Not recommended for efficiency, use atomic - * operators and update instead for more efficient operations. - * @method - * @param {object} doc Document to save - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~writeOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - * @deprecated use insertOne, insertMany, updateOne or updateMany - */ -Collection.prototype.save = deprecate(function(doc, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // Add ignoreUndefined - if (this.s.options.ignoreUndefined) { - options = Object.assign({}, options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - return executeLegacyOperation(this.s.topology, save, [this, doc, options, callback]); -}, 'collection.save is deprecated. Use insertOne, insertMany, updateOne, or updateMany instead.'); - -/** - * The callback format for results - * @callback Collection~resultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {object} result The result object if the command was executed successfully. - */ - -/** - * The callback format for an aggregation call - * @callback Collection~aggregationCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {AggregationCursor} cursor The cursor if the aggregation command was executed successfully. - */ - -/** - * Fetches the first document that matches the query - * @method - * @param {object} query Query for find Operation - * @param {object} [options] Optional settings. - * @param {number} [options.limit=0] Sets the limit of documents returned in the query. - * @param {(array|object)} [options.sort] Set to sort the documents coming back from the query. Array of indexes, [['a', 1]] etc. - * @param {object} [options.projection] The fields to return in the query. Object of fields to include or exclude (not both), {'a':1} - * @param {object} [options.fields] **Deprecated** Use `options.projection` instead - * @param {number} [options.skip=0] Set to skip N documents ahead in your query (useful for pagination). - * @param {Object} [options.hint] Tell the query to use specific indexes in the query. Object of indexes to use, {'_id':1} - * @param {boolean} [options.explain=false] Explain the query instead of returning the data. - * @param {boolean} [options.snapshot=false] DEPRECATED: Snapshot query. - * @param {boolean} [options.timeout=false] Specify if the cursor can timeout. - * @param {boolean} [options.tailable=false] Specify if the cursor is tailable. - * @param {number} [options.batchSize=1] Set the batchSize for the getMoreCommand when iterating over the query results. - * @param {boolean} [options.returnKey=false] Only return the index key. - * @param {number} [options.maxScan] DEPRECATED: Limit the number of items to scan. - * @param {number} [options.min] Set index bounds. - * @param {number} [options.max] Set index bounds. - * @param {boolean} [options.showDiskLoc=false] Show disk location of results. - * @param {string} [options.comment] You can put a $comment field on a query to make looking in the profiler logs simpler. - * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. - * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution. - * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. - * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {boolean} [options.partial=false] Specify if the cursor should return partial results when querying against a sharded system - * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query. - * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.findOne = deprecateOptions( - { - name: 'collection.find', - deprecatedOptions: DEPRECATED_FIND_OPTIONS, - optionsIndex: 1 - }, - function(query, options, callback) { - if (typeof callback === 'object') { - // TODO(MAJOR): throw in the future - console.warn('Third parameter to `findOne()` must be a callback or undefined'); - } - - if (typeof query === 'function') (callback = query), (query = {}), (options = {}); - if (typeof options === 'function') (callback = options), (options = {}); - query = query || {}; - options = options || {}; - - const findOneOperation = new FindOneOperation(this, query, options); - - return executeOperation(this.s.topology, findOneOperation, callback); - } -); - -/** - * The callback format for the collection method, must be used if strict is specified - * @callback Collection~collectionResultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection} collection The collection instance. - */ - -/** - * Rename the collection. - * - * @method - * @param {string} newName New name of of the collection. - * @param {object} [options] Optional settings. - * @param {boolean} [options.dropTarget=false] Drop the target name collection if it previously exists. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~collectionResultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.rename = function(newName, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = Object.assign({}, options, { readPreference: ReadPreference.PRIMARY }); - - const renameOperation = new RenameOperation(this, newName, options); - - return executeOperation(this.s.topology, renameOperation, callback); -}; - -/** - * Drop the collection from the database, removing it permanently. New accesses will create a new collection. - * - * @method - * @param {object} [options] Optional settings. - * @param {WriteConcern} [options.writeConcern] A full WriteConcern object - * @param {(number|string)} [options.w] The write concern - * @param {number} [options.wtimeout] The write concern timeout - * @param {boolean} [options.j] The journal write concern - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.drop = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const dropCollectionOperation = new DropCollectionOperation( - this.s.db, - this.collectionName, - options - ); - - return executeOperation(this.s.topology, dropCollectionOperation, callback); -}; - -/** - * Returns the options of the collection. - * - * @method - * @param {Object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.options = function(opts, callback) { - if (typeof opts === 'function') (callback = opts), (opts = {}); - opts = opts || {}; - - const optionsOperation = new OptionsOperation(this, opts); - - return executeOperation(this.s.topology, optionsOperation, callback); -}; - -/** - * Returns if the collection is a capped collection - * - * @method - * @param {Object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.isCapped = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const isCappedOperation = new IsCappedOperation(this, options); - - return executeOperation(this.s.topology, isCappedOperation, callback); -}; - -/** - * Creates an index on the db and collection collection. - * @method - * @param {(string|array|object)} fieldOrSpec Defines the index. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.unique=false] Creates an unique index. - * @param {boolean} [options.sparse=false] Creates a sparse index. - * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. - * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value - * @param {number} [options.min] For geospatial indexes set the lower bound for the co-ordinates. - * @param {number} [options.max] For geospatial indexes set the high bound for the co-ordinates. - * @param {number} [options.v] Specify the format version of the indexes. - * @param {number} [options.expireAfterSeconds] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) - * @param {string} [options.name] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) - * @param {object} [options.partialFilterExpression] Creates a partial index based on the given filter object (MongoDB 3.2 or higher) - * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - * @example - * const collection = client.db('foo').collection('bar'); - * - * await collection.createIndex({ a: 1, b: -1 }); - * - * // Alternate syntax for { c: 1, d: -1 } that ensures order of indexes - * await collection.createIndex([ [c, 1], [d, -1] ]); - * - * // Equivalent to { e: 1 } - * await collection.createIndex('e'); - * - * // Equivalent to { f: 1, g: 1 } - * await collection.createIndex(['f', 'g']) - * - * // Equivalent to { h: 1, i: -1 } - * await collection.createIndex([ { h: 1 }, { i: -1 } ]); - * - * // Equivalent to { j: 1, k: -1, l: 2d } - * await collection.createIndex(['j', ['k', -1], { l: '2d' }]) - */ -Collection.prototype.createIndex = function(fieldOrSpec, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const createIndexOperation = new CreateIndexOperation( - this.s.db, - this.collectionName, - fieldOrSpec, - options - ); - - return executeOperation(this.s.topology, createIndexOperation, callback); -}; - -/** - * @typedef {object} Collection~IndexDefinition - * @description A definition for an index. Used by the createIndex command. - * @see https://docs.mongodb.com/manual/reference/command/createIndexes/ - */ - -/** - * Creates multiple indexes in the collection, this method is only supported for - * MongoDB 2.6 or higher. Earlier version of MongoDB will throw a command not supported - * error. - * - * **Note**: Unlike {@link Collection#createIndex createIndex}, this function takes in raw index specifications. - * Index specifications are defined {@link http://docs.mongodb.org/manual/reference/command/createIndexes/ here}. - * - * @method - * @param {Collection~IndexDefinition[]} indexSpecs An array of index specifications to be created - * @param {Object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - * @example - * const collection = client.db('foo').collection('bar'); - * await collection.createIndexes([ - * // Simple index on field fizz - * { - * key: { fizz: 1 }, - * } - * // wildcard index - * { - * key: { '$**': 1 } - * }, - * // named index on darmok and jalad - * { - * key: { darmok: 1, jalad: -1 } - * name: 'tanagra' - * } - * ]); - */ -Collection.prototype.createIndexes = function(indexSpecs, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - - options = options ? Object.assign({}, options) : {}; - if (typeof options.maxTimeMS !== 'number') delete options.maxTimeMS; - - const createIndexesOperation = new CreateIndexesOperation(this, indexSpecs, options); - - return executeOperation(this.s.topology, createIndexesOperation, callback); -}; - -/** - * Drops an index from this collection. - * @method - * @param {string} indexName Name of the index to drop. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query. - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.dropIndex = function(indexName, options, callback) { - const args = Array.prototype.slice.call(arguments, 1); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - - options = args.length ? args.shift() || {} : {}; - // Run only against primary - options.readPreference = ReadPreference.PRIMARY; - - const dropIndexOperation = new DropIndexOperation(this, indexName, options); - - return executeOperation(this.s.topology, dropIndexOperation, callback); -}; - -/** - * Drops all indexes from this collection. - * @method - * @param {Object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query. - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.dropIndexes = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options ? Object.assign({}, options) : {}; - - if (typeof options.maxTimeMS !== 'number') delete options.maxTimeMS; - - const dropIndexesOperation = new DropIndexesOperation(this, options); - - return executeOperation(this.s.topology, dropIndexesOperation, callback); -}; - -/** - * Drops all indexes from this collection. - * @method - * @deprecated use dropIndexes - * @param {Collection~resultCallback} callback The command result callback - * @return {Promise} returns Promise if no [callback] passed - */ -Collection.prototype.dropAllIndexes = deprecate( - Collection.prototype.dropIndexes, - 'collection.dropAllIndexes is deprecated. Use dropIndexes instead.' -); - -/** - * Reindex all indexes on the collection - * Warning: reIndex is a blocking operation (indexes are rebuilt in the foreground) and will be slow for large collections. - * @method - * @param {Object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.reIndex = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const reIndexOperation = new ReIndexOperation(this, options); - - return executeOperation(this.s.topology, reIndexOperation, callback); -}; - -/** - * Get the list of all indexes information for the collection. - * - * @method - * @param {object} [options] Optional settings. - * @param {number} [options.batchSize=1000] The batchSize for the returned command cursor or if pre 2.8 the systems batch collection - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {ClientSession} [options.session] optional session to use for this operation - * @return {CommandCursor} - */ -Collection.prototype.listIndexes = function(options) { - const cursor = new CommandCursor( - this.s.topology, - new ListIndexesOperation(this, options), - options - ); - - return cursor; -}; - -/** - * Ensures that an index exists, if it does not it creates it - * @method - * @deprecated use createIndexes instead - * @param {(string|object)} fieldOrSpec Defines the index. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.unique=false] Creates an unique index. - * @param {boolean} [options.sparse=false] Creates a sparse index. - * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. - * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value - * @param {number} [options.min] For geospatial indexes set the lower bound for the co-ordinates. - * @param {number} [options.max] For geospatial indexes set the high bound for the co-ordinates. - * @param {number} [options.v] Specify the format version of the indexes. - * @param {number} [options.expireAfterSeconds] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) - * @param {number} [options.name] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) - * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.ensureIndex = deprecate(function(fieldOrSpec, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - return executeLegacyOperation(this.s.topology, ensureIndex, [ - this, - fieldOrSpec, - options, - callback - ]); -}, 'collection.ensureIndex is deprecated. Use createIndexes instead.'); - -/** - * Checks if one or more indexes exist on the collection, fails on first non-existing index - * @method - * @param {(string|array)} indexes One or more index names to check. - * @param {Object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.indexExists = function(indexes, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const indexExistsOperation = new IndexExistsOperation(this, indexes, options); - - return executeOperation(this.s.topology, indexExistsOperation, callback); -}; - -/** - * Retrieves this collections index info. - * @method - * @param {object} [options] Optional settings. - * @param {boolean} [options.full=false] Returns the full raw index information. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.indexInformation = function(options, callback) { - const args = Array.prototype.slice.call(arguments, 0); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - options = args.length ? args.shift() || {} : {}; - - const indexInformationOperation = new IndexInformationOperation( - this.s.db, - this.collectionName, - options - ); - - return executeOperation(this.s.topology, indexInformationOperation, callback); -}; - -/** - * The callback format for results - * @callback Collection~countCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {number} result The count of documents that matched the query. - */ - -/** - * An estimated count of matching documents in the db to a query. - * - * **NOTE:** This method has been deprecated, since it does not provide an accurate count of the documents - * in a collection. To obtain an accurate count of documents in the collection, use {@link Collection#countDocuments countDocuments}. - * To obtain an estimated count of all documents in the collection, use {@link Collection#estimatedDocumentCount estimatedDocumentCount}. - * - * @method - * @param {object} [query={}] The query for the count. - * @param {object} [options] Optional settings. - * @param {boolean} [options.limit] The limit of documents to count. - * @param {boolean} [options.skip] The number of documents to skip for the count. - * @param {string} [options.hint] An index name hint for the query. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~countCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - * @deprecated use {@link Collection#countDocuments countDocuments} or {@link Collection#estimatedDocumentCount estimatedDocumentCount} instead - */ -Collection.prototype.count = deprecate(function(query, options, callback) { - const args = Array.prototype.slice.call(arguments, 0); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - query = args.length ? args.shift() || {} : {}; - options = args.length ? args.shift() || {} : {}; - - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - return executeOperation( - this.s.topology, - new EstimatedDocumentCountOperation(this, query, options), - callback - ); -}, 'collection.count is deprecated, and will be removed in a future version.' + - ' Use Collection.countDocuments or Collection.estimatedDocumentCount instead'); - -/** - * Gets an estimate of the count of documents in a collection using collection metadata. - * - * @method - * @param {object} [options] Optional settings. - * @param {number} [options.maxTimeMS] The maximum amount of time to allow the operation to run. - * @param {Collection~countCallback} [callback] The command result callback. - * @return {Promise} returns Promise if no callback passed. - */ -Collection.prototype.estimatedDocumentCount = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const estimatedDocumentCountOperation = new EstimatedDocumentCountOperation(this, options); - - return executeOperation(this.s.topology, estimatedDocumentCountOperation, callback); -}; - -/** - * Gets the number of documents matching the filter. - * For a fast count of the total documents in a collection see {@link Collection#estimatedDocumentCount estimatedDocumentCount}. - * **Note**: When migrating from {@link Collection#count count} to {@link Collection#countDocuments countDocuments} - * the following query operators must be replaced: - * - * | Operator | Replacement | - * | -------- | ----------- | - * | `$where` | [`$expr`][1] | - * | `$near` | [`$geoWithin`][2] with [`$center`][3] | - * | `$nearSphere` | [`$geoWithin`][2] with [`$centerSphere`][4] | - * - * [1]: https://docs.mongodb.com/manual/reference/operator/query/expr/ - * [2]: https://docs.mongodb.com/manual/reference/operator/query/geoWithin/ - * [3]: https://docs.mongodb.com/manual/reference/operator/query/center/#op._S_center - * [4]: https://docs.mongodb.com/manual/reference/operator/query/centerSphere/#op._S_centerSphere - * - * @param {object} [query] the query for the count - * @param {object} [options] Optional settings. - * @param {object} [options.collation] Specifies a collation. - * @param {string|object} [options.hint] The index to use. - * @param {number} [options.limit] The maximum number of document to count. - * @param {number} [options.maxTimeMS] The maximum amount of time to allow the operation to run. - * @param {number} [options.skip] The number of documents to skip before counting. - * @param {Collection~countCallback} [callback] The command result callback. - * @return {Promise} returns Promise if no callback passed. - * @see https://docs.mongodb.com/manual/reference/operator/query/expr/ - * @see https://docs.mongodb.com/manual/reference/operator/query/geoWithin/ - * @see https://docs.mongodb.com/manual/reference/operator/query/center/#op._S_center - * @see https://docs.mongodb.com/manual/reference/operator/query/centerSphere/#op._S_centerSphere - */ - -Collection.prototype.countDocuments = function(query, options, callback) { - const args = Array.prototype.slice.call(arguments, 0); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - query = args.length ? args.shift() || {} : {}; - options = args.length ? args.shift() || {} : {}; - - const countDocumentsOperation = new CountDocumentsOperation(this, query, options); - - return executeOperation(this.s.topology, countDocumentsOperation, callback); -}; - -/** - * The distinct command returns a list of distinct values for the given key across a collection. - * @method - * @param {string} key Field of the document to find distinct values for. - * @param {object} query The query for filtering the set of documents to which we apply the distinct filter. - * @param {object} [options] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.distinct = function(key, query, options, callback) { - const args = Array.prototype.slice.call(arguments, 1); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - const queryOption = args.length ? args.shift() || {} : {}; - const optionsOption = args.length ? args.shift() || {} : {}; - - const distinctOperation = new DistinctOperation(this, key, queryOption, optionsOption); - - return executeOperation(this.s.topology, distinctOperation, callback); -}; - -/** - * Retrieve all the indexes on the collection. - * @method - * @param {Object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.indexes = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const indexesOperation = new IndexesOperation(this, options); - - return executeOperation(this.s.topology, indexesOperation, callback); -}; - -/** - * Get all the collection statistics. - * - * @method - * @param {object} [options] Optional settings. - * @param {number} [options.scale] Divide the returned sizes by scale value. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The collection result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.stats = function(options, callback) { - const args = Array.prototype.slice.call(arguments, 0); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - options = args.length ? args.shift() || {} : {}; - - const statsOperation = new StatsOperation(this, options); - - return executeOperation(this.s.topology, statsOperation, callback); -}; - -/** - * @typedef {Object} Collection~findAndModifyWriteOpResult - * @property {object} value Document returned from the `findAndModify` command. If no documents were found, `value` will be `null` by default (`returnOriginal: true`), even if a document was upserted; if `returnOriginal` was false, the upserted document will be returned in that case. - * @property {object} lastErrorObject The raw lastErrorObject returned from the command. See {@link https://docs.mongodb.com/manual/reference/command/findAndModify/index.html#lasterrorobject|findAndModify command documentation}. - * @property {Number} ok Is 1 if the command executed correctly. - */ - -/** - * The callback format for inserts - * @callback Collection~findAndModifyCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection~findAndModifyWriteOpResult} result The result object if the command was executed successfully. - */ - -/** - * Find a document and delete it in one atomic operation. Requires a write lock for the duration of the operation. - * - * @method - * @param {object} filter The Filter used to select the document to remove - * @param {object} [options] Optional settings. - * @param {object} [options.projection] Limits the fields to return for all matching documents. - * @param {object} [options.sort] Determines which document the operation modifies if the query selects multiple documents. - * @param {number} [options.maxTimeMS] The maximum amount of time to allow the query to run. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~findAndModifyCallback} [callback] The collection result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.findOneAndDelete = function(filter, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // Basic validation - if (filter == null || typeof filter !== 'object') - throw toError('filter parameter must be an object'); - - const findOneAndDeleteOperation = new FindOneAndDeleteOperation(this, filter, options); - - return executeOperation(this.s.topology, findOneAndDeleteOperation, callback); -}; - -/** - * Find a document and replace it in one atomic operation. Requires a write lock for the duration of the operation. - * - * @method - * @param {object} filter The Filter used to select the document to replace - * @param {object} replacement The Document that replaces the matching document - * @param {object} [options] Optional settings. - * @param {object} [options.projection] Limits the fields to return for all matching documents. - * @param {object} [options.sort] Determines which document the operation modifies if the query selects multiple documents. - * @param {number} [options.maxTimeMS] The maximum amount of time to allow the query to run. - * @param {boolean} [options.upsert=false] Upsert the document if it does not exist. - * @param {boolean} [options.returnOriginal=true] When false, returns the updated document rather than the original. The default is true. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~findAndModifyCallback} [callback] The collection result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.findOneAndReplace = function(filter, replacement, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // Basic validation - if (filter == null || typeof filter !== 'object') - throw toError('filter parameter must be an object'); - if (replacement == null || typeof replacement !== 'object') - throw toError('replacement parameter must be an object'); - - // Check that there are no atomic operators - const keys = Object.keys(replacement); - - if (keys[0] && keys[0][0] === '$') { - throw toError('The replacement document must not contain atomic operators.'); - } - - const findOneAndReplaceOperation = new FindOneAndReplaceOperation( - this, - filter, - replacement, - options - ); - - return executeOperation(this.s.topology, findOneAndReplaceOperation, callback); -}; - -/** - * Find a document and update it in one atomic operation. Requires a write lock for the duration of the operation. - * - * @method - * @param {object} filter The Filter used to select the document to update - * @param {object} update Update operations to be performed on the document - * @param {object} [options] Optional settings. - * @param {object} [options.projection] Limits the fields to return for all matching documents. - * @param {object} [options.sort] Determines which document the operation modifies if the query selects multiple documents. - * @param {number} [options.maxTimeMS] The maximum amount of time to allow the query to run. - * @param {boolean} [options.upsert=false] Upsert the document if it does not exist. - * @param {boolean} [options.returnOriginal=true] When false, returns the updated document rather than the original. The default is true. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Array} [options.arrayFilters] optional list of array filters referenced in filtered positional operators - * @param {Collection~findAndModifyCallback} [callback] The collection result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.findOneAndUpdate = function(filter, update, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // Basic validation - if (filter == null || typeof filter !== 'object') - throw toError('filter parameter must be an object'); - if (update == null || typeof update !== 'object') - throw toError('update parameter must be an object'); - - const err = checkForAtomicOperators(update); - if (err) { - if (typeof callback === 'function') return callback(err); - return this.s.promiseLibrary.reject(err); - } - - const findOneAndUpdateOperation = new FindOneAndUpdateOperation(this, filter, update, options); - - return executeOperation(this.s.topology, findOneAndUpdateOperation, callback); -}; - -/** - * Find and update a document. - * @method - * @param {object} query Query object to locate the object to modify. - * @param {array} sort If multiple docs match, choose the first one in the specified sort order as the object to manipulate. - * @param {object} doc The fields/vals to be updated. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.remove=false] Set to true to remove the object before returning. - * @param {boolean} [options.upsert=false] Perform an upsert operation. - * @param {boolean} [options.new=false] Set to true if you want to return the modified object rather than the original. Ignored for remove. - * @param {object} [options.projection] Object containing the field projection for the result returned from the operation. - * @param {object} [options.fields] **Deprecated** Use `options.projection` instead - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Array} [options.arrayFilters] optional list of array filters referenced in filtered positional operators - * @param {Collection~findAndModifyCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - * @deprecated use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead - */ -Collection.prototype.findAndModify = deprecate( - _findAndModify, - 'collection.findAndModify is deprecated. Use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead.' -); - -/** - * @ignore - */ - -Collection.prototype._findAndModify = _findAndModify; - -function _findAndModify(query, sort, doc, options, callback) { - const args = Array.prototype.slice.call(arguments, 1); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - sort = args.length ? args.shift() || [] : []; - doc = args.length ? args.shift() : null; - options = args.length ? args.shift() || {} : {}; - - // Clone options - options = Object.assign({}, options); - // Force read preference primary - options.readPreference = ReadPreference.PRIMARY; - - return executeOperation( - this.s.topology, - new FindAndModifyOperation(this, query, sort, doc, options), - callback - ); -} - -/** - * Find and remove a document. - * @method - * @param {object} query Query object to locate the object to modify. - * @param {array} sort If multiple docs match, choose the first one in the specified sort order as the object to manipulate. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - * @deprecated use findOneAndDelete instead - */ -Collection.prototype.findAndRemove = deprecate(function(query, sort, options, callback) { - const args = Array.prototype.slice.call(arguments, 1); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - sort = args.length ? args.shift() || [] : []; - options = args.length ? args.shift() || {} : {}; - - // Add the remove option - options.remove = true; - - return executeOperation( - this.s.topology, - new FindAndModifyOperation(this, query, sort, null, options), - callback - ); -}, 'collection.findAndRemove is deprecated. Use findOneAndDelete instead.'); - -/** - * Execute an aggregation framework pipeline against the collection, needs MongoDB >= 2.2 - * @method - * @param {object} [pipeline=[]] Array containing all the aggregation framework commands for the execution. - * @param {object} [options] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {object} [options.cursor] Return the query as cursor, on 2.6 > it returns as a real cursor on pre 2.6 it returns as an emulated cursor. - * @param {number} [options.cursor.batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. - * @param {boolean} [options.explain=false] Explain returns the aggregation execution plan (requires mongodb 2.6 >). - * @param {boolean} [options.allowDiskUse=false] allowDiskUse lets the server know if it can use disk to store temporary results for the aggregation (requires mongodb 2.6 >). - * @param {number} [options.maxTimeMS] maxTimeMS specifies a cumulative time limit in milliseconds for processing operations on the cursor. MongoDB interrupts the operation at the earliest following interrupt point. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. - * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution. - * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. - * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. - * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {string} [options.comment] Add a comment to an aggregation command - * @param {string|object} [options.hint] Add an index selection hint to an aggregation command - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~aggregationCallback} callback The command result callback - * @return {(null|AggregationCursor)} - */ -Collection.prototype.aggregate = function(pipeline, options, callback) { - if (Array.isArray(pipeline)) { - // Set up callback if one is provided - if (typeof options === 'function') { - callback = options; - options = {}; - } - - // If we have no options or callback we are doing - // a cursor based aggregation - if (options == null && callback == null) { - options = {}; - } - } else { - // Aggregation pipeline passed as arguments on the method - const args = Array.prototype.slice.call(arguments, 0); - // Get the callback - callback = args.pop(); - // Get the possible options object - const opts = args[args.length - 1]; - // If it contains any of the admissible options pop it of the args - options = - opts && - (opts.readPreference || - opts.explain || - opts.cursor || - opts.out || - opts.maxTimeMS || - opts.hint || - opts.allowDiskUse) - ? args.pop() - : {}; - // Left over arguments is the pipeline - pipeline = args; - } - - const cursor = new AggregationCursor( - this.s.topology, - new AggregateOperation(this, pipeline, options), - options - ); - - // TODO: remove this when NODE-2074 is resolved - if (typeof callback === 'function') { - callback(null, cursor); - return; - } - - return cursor; -}; - -/** - * Create a new Change Stream, watching for new changes (insertions, updates, replacements, deletions, and invalidations) in this collection. - * @method - * @since 3.0.0 - * @param {Array} [pipeline] An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents. - * @param {object} [options] Optional settings - * @param {string} [options.fullDocument='default'] Allowed values: ‘default’, ‘updateLookup’. When set to ‘updateLookup’, the change stream will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred. - * @param {object} [options.resumeAfter] Specifies the logical starting point for the new change stream. This should be the _id field from a previously returned change stream document. - * @param {number} [options.maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a change stream query - * @param {number} [options.batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. - * @param {object} [options.collation] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. - * @param {ReadPreference} [options.readPreference] The read preference. Defaults to the read preference of the database or collection. See {@link https://docs.mongodb.com/manual/reference/read-preference|read preference documentation}. - * @param {Timestamp} [options.startAtOperationTime] receive change events that occur after the specified timestamp - * @param {ClientSession} [options.session] optional session to use for this operation - * @return {ChangeStream} a ChangeStream instance. - */ -Collection.prototype.watch = function(pipeline, options) { - pipeline = pipeline || []; - options = options || {}; - - // Allow optionally not specifying a pipeline - if (!Array.isArray(pipeline)) { - options = pipeline; - pipeline = []; - } - - return new ChangeStream(this, pipeline, options); -}; - -/** - * The callback format for results - * @callback Collection~parallelCollectionScanCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Cursor[]} cursors A list of cursors returned allowing for parallel reading of collection. - */ - -/** - * Return N number of parallel cursors for a collection allowing parallel reading of entire collection. There are - * no ordering guarantees for returned results. - * @method - * @param {object} [options] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {number} [options.batchSize=1000] Set the batchSize for the getMoreCommand when iterating over the query results. - * @param {number} [options.numCursors=1] The maximum number of parallel command cursors to return (the number of returned cursors will be in the range 1:numCursors) - * @param {boolean} [options.raw=false] Return all BSON documents as Raw Buffer documents. - * @param {Collection~parallelCollectionScanCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.parallelCollectionScan = deprecate(function(options, callback) { - if (typeof options === 'function') (callback = options), (options = { numCursors: 1 }); - // Set number of cursors to 1 - options.numCursors = options.numCursors || 1; - options.batchSize = options.batchSize || 1000; - - options = Object.assign({}, options); - // Ensure we have the right read preference inheritance - options.readPreference = resolveReadPreference(this, options); - - // Add a promiseLibrary - options.promiseLibrary = this.s.promiseLibrary; - - if (options.session) { - options.session = undefined; - } - - return executeLegacyOperation( - this.s.topology, - parallelCollectionScan, - [this, options, callback], - { skipSessions: true } - ); -}, 'parallelCollectionScan is deprecated in MongoDB v4.1'); - -/** - * Execute a geo search using a geo haystack index on a collection. - * - * @method - * @param {number} x Point to search on the x axis, ensure the indexes are ordered in the same order. - * @param {number} y Point to search on the y axis, ensure the indexes are ordered in the same order. - * @param {object} [options] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {number} [options.maxDistance] Include results up to maxDistance from the point. - * @param {object} [options.search] Filter the results by a query. - * @param {number} [options.limit=false] Max number of results to return. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.geoHaystackSearch = function(x, y, options, callback) { - const args = Array.prototype.slice.call(arguments, 2); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - options = args.length ? args.shift() || {} : {}; - - const geoHaystackSearchOperation = new GeoHaystackSearchOperation(this, x, y, options); - - return executeOperation(this.s.topology, geoHaystackSearchOperation, callback); -}; - -/** - * Run a group command across a collection - * - * @method - * @param {(object|array|function|code)} keys An object, array or function expressing the keys to group by. - * @param {object} condition An optional condition that must be true for a row to be considered. - * @param {object} initial Initial value of the aggregation counter object. - * @param {(function|Code)} reduce The reduce function aggregates (reduces) the objects iterated - * @param {(function|Code)} finalize An optional function to be run on each item in the result set just before the item is returned. - * @param {boolean} command Specify if you wish to run using the internal group command or using eval, default is true. - * @param {object} [options] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - * @deprecated MongoDB 3.6 or higher no longer supports the group command. We recommend rewriting using the aggregation framework. - */ -Collection.prototype.group = deprecate(function( - keys, - condition, - initial, - reduce, - finalize, - command, - options, - callback -) { - const args = Array.prototype.slice.call(arguments, 3); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - reduce = args.length ? args.shift() : null; - finalize = args.length ? args.shift() : null; - command = args.length ? args.shift() : null; - options = args.length ? args.shift() || {} : {}; - - // Make sure we are backward compatible - if (!(typeof finalize === 'function')) { - command = finalize; - finalize = null; - } - - if ( - !Array.isArray(keys) && - keys instanceof Object && - typeof keys !== 'function' && - !(keys._bsontype === 'Code') - ) { - keys = Object.keys(keys); - } - - if (typeof reduce === 'function') { - reduce = reduce.toString(); - } - - if (typeof finalize === 'function') { - finalize = finalize.toString(); - } - - // Set up the command as default - command = command == null ? true : command; - - return executeLegacyOperation(this.s.topology, group, [ - this, - keys, - condition, - initial, - reduce, - finalize, - command, - options, - callback - ]); -}, -'MongoDB 3.6 or higher no longer supports the group command. We recommend rewriting using the aggregation framework.'); - -/** - * Run Map Reduce across a collection. Be aware that the inline option for out will return an array of results not a collection. - * - * @method - * @param {(function|string)} map The mapping function. - * @param {(function|string)} reduce The reduce function. - * @param {object} [options] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {object} [options.out] Sets the output target for the map reduce job. *{inline:1} | {replace:'collectionName'} | {merge:'collectionName'} | {reduce:'collectionName'}* - * @param {object} [options.query] Query filter object. - * @param {object} [options.sort] Sorts the input objects using this key. Useful for optimization, like sorting by the emit key for fewer reduces. - * @param {number} [options.limit] Number of objects to return from collection. - * @param {boolean} [options.keeptemp=false] Keep temporary data. - * @param {(function|string)} [options.finalize] Finalize function. - * @param {object} [options.scope] Can pass in variables that can be access from map/reduce/finalize. - * @param {boolean} [options.jsMode=false] It is possible to make the execution stay in JS. Provided in MongoDB > 2.0.X. - * @param {boolean} [options.verbose=false] Provide statistics on job execution time. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Collection~resultCallback} [callback] The command result callback - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.mapReduce = function(map, reduce, options, callback) { - if ('function' === typeof options) (callback = options), (options = {}); - // Out must allways be defined (make sure we don't break weirdly on pre 1.8+ servers) - if (null == options.out) { - throw new Error( - 'the out option parameter must be defined, see mongodb docs for possible values' - ); - } - - if ('function' === typeof map) { - map = map.toString(); - } - - if ('function' === typeof reduce) { - reduce = reduce.toString(); - } - - if ('function' === typeof options.finalize) { - options.finalize = options.finalize.toString(); - } - const mapReduceOperation = new MapReduceOperation(this, map, reduce, options); - - return executeOperation(this.s.topology, mapReduceOperation, callback); -}; - -/** - * Initiate an Out of order batch write operation. All operations will be buffered into insert/update/remove commands executed out of order. - * - * @method - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session] optional session to use for this operation - * @return {UnorderedBulkOperation} - */ -Collection.prototype.initializeUnorderedBulkOp = function(options) { - options = options || {}; - // Give function's options precedence over session options. - if (options.ignoreUndefined == null) { - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - options.promiseLibrary = this.s.promiseLibrary; - return unordered(this.s.topology, this, options); -}; - -/** - * Initiate an In order bulk write operation. Operations will be serially executed in the order they are added, creating a new operation for each switch in types. - * - * @method - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {OrderedBulkOperation} callback The command result callback - * @return {null} - */ -Collection.prototype.initializeOrderedBulkOp = function(options) { - options = options || {}; - // Give function's options precedence over session's options. - if (options.ignoreUndefined == null) { - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - options.promiseLibrary = this.s.promiseLibrary; - return ordered(this.s.topology, this, options); -}; - -/** - * Return the db logger - * @method - * @return {Logger} return the db logger - * @ignore - */ -Collection.prototype.getLogger = function() { - return this.s.db.s.logger; -}; - -module.exports = Collection; diff --git a/scripts/node_modules/mongodb/lib/command_cursor.js b/scripts/node_modules/mongodb/lib/command_cursor.js deleted file mode 100644 index cd0f9d7a..00000000 --- a/scripts/node_modules/mongodb/lib/command_cursor.js +++ /dev/null @@ -1,269 +0,0 @@ -'use strict'; - -const ReadPreference = require('./core').ReadPreference; -const MongoError = require('./core').MongoError; -const Cursor = require('./cursor'); -const CursorState = require('./core/cursor').CursorState; - -/** - * @fileOverview The **CommandCursor** class is an internal class that embodies a - * generalized cursor based on a MongoDB command allowing for iteration over the - * results returned. It supports one by one document iteration, conversion to an - * array or can be iterated as a Node 0.10.X or higher stream - * - * **CommandCursor Cannot directly be instantiated** - * @example - * const MongoClient = require('mongodb').MongoClient; - * const test = require('assert'); - * // Connection url - * const url = 'mongodb://localhost:27017'; - * // Database Name - * const dbName = 'test'; - * // Connect using MongoClient - * MongoClient.connect(url, function(err, client) { - * // Create a collection we want to drop later - * const col = client.db(dbName).collection('listCollectionsExample1'); - * // Insert a bunch of documents - * col.insert([{a:1, b:1} - * , {a:2, b:2}, {a:3, b:3} - * , {a:4, b:4}], {w:1}, function(err, result) { - * test.equal(null, err); - * // List the database collections available - * db.listCollections().toArray(function(err, items) { - * test.equal(null, err); - * client.close(); - * }); - * }); - * }); - */ - -/** - * Namespace provided by the browser. - * @external Readable - */ - -/** - * Creates a new Command Cursor instance (INTERNAL TYPE, do not instantiate directly) - * @class CommandCursor - * @extends external:Readable - * @fires CommandCursor#data - * @fires CommandCursor#end - * @fires CommandCursor#close - * @fires CommandCursor#readable - * @return {CommandCursor} an CommandCursor instance. - */ -class CommandCursor extends Cursor { - constructor(topology, ns, cmd, options) { - super(topology, ns, cmd, options); - } - - /** - * Set the ReadPreference for the cursor. - * @method - * @param {(string|ReadPreference)} readPreference The new read preference for the cursor. - * @throws {MongoError} - * @return {Cursor} - */ - setReadPreference(readPreference) { - if (this.s.state === CursorState.CLOSED || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - if (this.s.state !== CursorState.INIT) { - throw MongoError.create({ - message: 'cannot change cursor readPreference after cursor has been accessed', - driver: true - }); - } - - if (readPreference instanceof ReadPreference) { - this.options.readPreference = readPreference; - } else if (typeof readPreference === 'string') { - this.options.readPreference = new ReadPreference(readPreference); - } else { - throw new TypeError('Invalid read preference: ' + readPreference); - } - - return this; - } - - /** - * Set the batch size for the cursor. - * @method - * @param {number} value The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/find/|find command documentation}. - * @throws {MongoError} - * @return {CommandCursor} - */ - batchSize(value) { - if (this.s.state === CursorState.CLOSED || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - if (typeof value !== 'number') { - throw MongoError.create({ message: 'batchSize requires an integer', driver: true }); - } - - if (this.cmd.cursor) { - this.cmd.cursor.batchSize = value; - } - - this.setCursorBatchSize(value); - return this; - } - - /** - * Add a maxTimeMS stage to the aggregation pipeline - * @method - * @param {number} value The state maxTimeMS value. - * @return {CommandCursor} - */ - maxTimeMS(value) { - if (this.topology.lastIsMaster().minWireVersion > 2) { - this.cmd.maxTimeMS = value; - } - - return this; - } - - /** - * Return the cursor logger - * @method - * @return {Logger} return the cursor logger - * @ignore - */ - getLogger() { - return this.logger; - } -} - -// aliases -CommandCursor.prototype.get = CommandCursor.prototype.toArray; - -/** - * CommandCursor stream data event, fired for each document in the cursor. - * - * @event CommandCursor#data - * @type {object} - */ - -/** - * CommandCursor stream end event - * - * @event CommandCursor#end - * @type {null} - */ - -/** - * CommandCursor stream close event - * - * @event CommandCursor#close - * @type {null} - */ - -/** - * CommandCursor stream readable event - * - * @event CommandCursor#readable - * @type {null} - */ - -/** - * Get the next available document from the cursor, returns null if no more documents are available. - * @function CommandCursor.prototype.next - * @param {CommandCursor~resultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ - -/** - * Check if there is any document still available in the cursor - * @function CommandCursor.prototype.hasNext - * @param {CommandCursor~resultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ - -/** - * The callback format for results - * @callback CommandCursor~toArrayResultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {object[]} documents All the documents the satisfy the cursor. - */ - -/** - * Returns an array of documents. The caller is responsible for making sure that there - * is enough memory to store the results. Note that the array only contain partial - * results when this cursor had been previously accessed. - * @method CommandCursor.prototype.toArray - * @param {CommandCursor~toArrayResultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ - -/** - * The callback format for results - * @callback CommandCursor~resultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {(object|null)} result The result object if the command was executed successfully. - */ - -/** - * Iterates over all the documents for this cursor. As with **{cursor.toArray}**, - * not all of the elements will be iterated if this cursor had been previously accessed. - * In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike - * **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements - * at any given time if batch size is specified. Otherwise, the caller is responsible - * for making sure that the entire result can fit the memory. - * @method CommandCursor.prototype.each - * @param {CommandCursor~resultCallback} callback The result callback. - * @throws {MongoError} - * @return {null} - */ - -/** - * Close the cursor, sending a KillCursor command and emitting close. - * @method CommandCursor.prototype.close - * @param {CommandCursor~resultCallback} [callback] The result callback. - * @return {Promise} returns Promise if no callback passed - */ - -/** - * Is the cursor closed - * @method CommandCursor.prototype.isClosed - * @return {boolean} - */ - -/** - * Clone the cursor - * @function CommandCursor.prototype.clone - * @return {CommandCursor} - */ - -/** - * Resets the cursor - * @function CommandCursor.prototype.rewind - * @return {CommandCursor} - */ - -/** - * The callback format for the forEach iterator method - * @callback CommandCursor~iteratorCallback - * @param {Object} doc An emitted document for the iterator - */ - -/** - * The callback error format for the forEach iterator method - * @callback CommandCursor~endCallback - * @param {MongoError} error An error instance representing the error during the execution. - */ - -/* - * Iterates over all the documents for this cursor using the iterator, callback pattern. - * @method CommandCursor.prototype.forEach - * @param {CommandCursor~iteratorCallback} iterator The iteration callback. - * @param {CommandCursor~endCallback} callback The end callback. - * @throws {MongoError} - * @return {null} - */ - -module.exports = CommandCursor; diff --git a/scripts/node_modules/mongodb/lib/constants.js b/scripts/node_modules/mongodb/lib/constants.js deleted file mode 100644 index d6cc68ad..00000000 --- a/scripts/node_modules/mongodb/lib/constants.js +++ /dev/null @@ -1,10 +0,0 @@ -'use strict'; - -module.exports = { - SYSTEM_NAMESPACE_COLLECTION: 'system.namespaces', - SYSTEM_INDEX_COLLECTION: 'system.indexes', - SYSTEM_PROFILE_COLLECTION: 'system.profile', - SYSTEM_USER_COLLECTION: 'system.users', - SYSTEM_COMMAND_COLLECTION: '$cmd', - SYSTEM_JS_COLLECTION: 'system.js' -}; diff --git a/scripts/node_modules/mongodb/lib/core/auth/auth_provider.js b/scripts/node_modules/mongodb/lib/core/auth/auth_provider.js deleted file mode 100644 index 7597b728..00000000 --- a/scripts/node_modules/mongodb/lib/core/auth/auth_provider.js +++ /dev/null @@ -1,158 +0,0 @@ -'use strict'; - -const MongoError = require('../error').MongoError; - -/** - * Creates a new AuthProvider, which dictates how to authenticate for a given - * mechanism. - * @class - */ -class AuthProvider { - constructor(bson) { - this.bson = bson; - this.authStore = []; - } - - /** - * Authenticate - * @method - * @param {SendAuthCommand} sendAuthCommand Writes an auth command directly to a specific connection - * @param {Connection[]} connections Connections to authenticate using this authenticator - * @param {MongoCredentials} credentials Authentication credentials - * @param {authResultCallback} callback The callback to return the result from the authentication - */ - auth(sendAuthCommand, connections, credentials, callback) { - // Total connections - let count = connections.length; - - if (count === 0) { - callback(null, null); - return; - } - - // Valid connections - let numberOfValidConnections = 0; - let errorObject = null; - - const execute = connection => { - this._authenticateSingleConnection(sendAuthCommand, connection, credentials, (err, r) => { - // Adjust count - count = count - 1; - - // If we have an error - if (err) { - errorObject = new MongoError(err); - } else if (r && (r.$err || r.errmsg)) { - errorObject = new MongoError(r); - } else { - numberOfValidConnections = numberOfValidConnections + 1; - } - - // Still authenticating against other connections. - if (count !== 0) { - return; - } - - // We have authenticated all connections - if (numberOfValidConnections > 0) { - // Store the auth details - this.addCredentials(credentials); - // Return correct authentication - callback(null, true); - } else { - if (errorObject == null) { - errorObject = new MongoError(`failed to authenticate using ${credentials.mechanism}`); - } - callback(errorObject, false); - } - }); - }; - - const executeInNextTick = _connection => process.nextTick(() => execute(_connection)); - - // For each connection we need to authenticate - while (connections.length > 0) { - executeInNextTick(connections.shift()); - } - } - - /** - * Implementation of a single connection authenticating. Is meant to be overridden. - * Will error if called directly - * @ignore - */ - _authenticateSingleConnection(/*sendAuthCommand, connection, credentials, callback*/) { - throw new Error('_authenticateSingleConnection must be overridden'); - } - - /** - * Adds credentials to store only if it does not exist - * @param {MongoCredentials} credentials credentials to add to store - */ - addCredentials(credentials) { - const found = this.authStore.some(cred => cred.equals(credentials)); - - if (!found) { - this.authStore.push(credentials); - } - } - - /** - * Re authenticate pool - * @method - * @param {SendAuthCommand} sendAuthCommand Writes an auth command directly to a specific connection - * @param {Connection[]} connections Connections to authenticate using this authenticator - * @param {authResultCallback} callback The callback to return the result from the authentication - */ - reauthenticate(sendAuthCommand, connections, callback) { - const authStore = this.authStore.slice(0); - let count = authStore.length; - if (count === 0) { - return callback(null, null); - } - - for (let i = 0; i < authStore.length; i++) { - this.auth(sendAuthCommand, connections, authStore[i], function(err) { - count = count - 1; - if (count === 0) { - callback(err, null); - } - }); - } - } - - /** - * Remove credentials that have been previously stored in the auth provider - * @method - * @param {string} source Name of database we are removing authStore details about - * @return {object} - */ - logout(source) { - this.authStore = this.authStore.filter(credentials => credentials.source !== source); - } -} - -/** - * A function that writes authentication commands to a specific connection - * @callback SendAuthCommand - * @param {Connection} connection The connection to write to - * @param {Command} command A command with a toBin method that can be written to a connection - * @param {AuthWriteCallback} callback Callback called when command response is received - */ - -/** - * A callback for a specific auth command - * @callback AuthWriteCallback - * @param {Error} err If command failed, an error from the server - * @param {object} r The response from the server - */ - -/** - * This is a result from an authentication strategy - * - * @callback authResultCallback - * @param {error} error An error object. Set to null if no error present - * @param {boolean} result The result of the authentication process - */ - -module.exports = { AuthProvider }; diff --git a/scripts/node_modules/mongodb/lib/core/auth/defaultAuthProviders.js b/scripts/node_modules/mongodb/lib/core/auth/defaultAuthProviders.js deleted file mode 100644 index fc5f4c28..00000000 --- a/scripts/node_modules/mongodb/lib/core/auth/defaultAuthProviders.js +++ /dev/null @@ -1,29 +0,0 @@ -'use strict'; - -const MongoCR = require('./mongocr'); -const X509 = require('./x509'); -const Plain = require('./plain'); -const GSSAPI = require('./gssapi'); -const SSPI = require('./sspi'); -const ScramSHA1 = require('./scram').ScramSHA1; -const ScramSHA256 = require('./scram').ScramSHA256; - -/** - * Returns the default authentication providers. - * - * @param {BSON} bson Bson definition - * @returns {Object} a mapping of auth names to auth types - */ -function defaultAuthProviders(bson) { - return { - mongocr: new MongoCR(bson), - x509: new X509(bson), - plain: new Plain(bson), - gssapi: new GSSAPI(bson), - sspi: new SSPI(bson), - 'scram-sha-1': new ScramSHA1(bson), - 'scram-sha-256': new ScramSHA256(bson) - }; -} - -module.exports = { defaultAuthProviders }; diff --git a/scripts/node_modules/mongodb/lib/core/auth/gssapi.js b/scripts/node_modules/mongodb/lib/core/auth/gssapi.js deleted file mode 100644 index 936fb65a..00000000 --- a/scripts/node_modules/mongodb/lib/core/auth/gssapi.js +++ /dev/null @@ -1,241 +0,0 @@ -'use strict'; - -const AuthProvider = require('./auth_provider').AuthProvider; -const retrieveKerberos = require('../utils').retrieveKerberos; -let kerberos; - -/** - * Creates a new GSSAPI authentication mechanism - * @class - * @extends AuthProvider - */ -class GSSAPI extends AuthProvider { - /** - * Implementation of authentication for a single connection - * @override - */ - _authenticateSingleConnection(sendAuthCommand, connection, credentials, callback) { - const source = credentials.source; - const username = credentials.username; - const password = credentials.password; - const mechanismProperties = credentials.mechanismProperties; - const gssapiServiceName = - mechanismProperties['gssapiservicename'] || - mechanismProperties['gssapiServiceName'] || - 'mongodb'; - - GSSAPIInitialize( - this, - kerberos.processes.MongoAuthProcess, - source, - username, - password, - source, - gssapiServiceName, - sendAuthCommand, - connection, - mechanismProperties, - callback - ); - } - - /** - * Authenticate - * @override - * @method - */ - auth(sendAuthCommand, connections, credentials, callback) { - if (kerberos == null) { - try { - kerberos = retrieveKerberos(); - } catch (e) { - return callback(e, null); - } - } - - super.auth(sendAuthCommand, connections, credentials, callback); - } -} - -// -// Initialize step -var GSSAPIInitialize = function( - self, - MongoAuthProcess, - db, - username, - password, - authdb, - gssapiServiceName, - sendAuthCommand, - connection, - options, - callback -) { - // Create authenticator - var mongo_auth_process = new MongoAuthProcess( - connection.host, - connection.port, - gssapiServiceName, - options - ); - - // Perform initialization - mongo_auth_process.init(username, password, function(err) { - if (err) return callback(err, false); - - // Perform the first step - mongo_auth_process.transition('', function(err, payload) { - if (err) return callback(err, false); - - // Call the next db step - MongoDBGSSAPIFirstStep( - self, - mongo_auth_process, - payload, - db, - username, - password, - authdb, - sendAuthCommand, - connection, - callback - ); - }); - }); -}; - -// -// Perform first step against mongodb -var MongoDBGSSAPIFirstStep = function( - self, - mongo_auth_process, - payload, - db, - username, - password, - authdb, - sendAuthCommand, - connection, - callback -) { - // Build the sasl start command - var command = { - saslStart: 1, - mechanism: 'GSSAPI', - payload: payload, - autoAuthorize: 1 - }; - - // Write the commmand on the connection - sendAuthCommand(connection, '$external.$cmd', command, (err, doc) => { - if (err) return callback(err, false); - // Execute mongodb transition - mongo_auth_process.transition(doc.payload, function(err, payload) { - if (err) return callback(err, false); - - // MongoDB API Second Step - MongoDBGSSAPISecondStep( - self, - mongo_auth_process, - payload, - doc, - db, - username, - password, - authdb, - sendAuthCommand, - connection, - callback - ); - }); - }); -}; - -// -// Perform first step against mongodb -var MongoDBGSSAPISecondStep = function( - self, - mongo_auth_process, - payload, - doc, - db, - username, - password, - authdb, - sendAuthCommand, - connection, - callback -) { - // Build Authentication command to send to MongoDB - var command = { - saslContinue: 1, - conversationId: doc.conversationId, - payload: payload - }; - - // Execute the command - // Write the commmand on the connection - sendAuthCommand(connection, '$external.$cmd', command, (err, doc) => { - if (err) return callback(err, false); - // Call next transition for kerberos - mongo_auth_process.transition(doc.payload, function(err, payload) { - if (err) return callback(err, false); - - // Call the last and third step - MongoDBGSSAPIThirdStep( - self, - mongo_auth_process, - payload, - doc, - db, - username, - password, - authdb, - sendAuthCommand, - connection, - callback - ); - }); - }); -}; - -var MongoDBGSSAPIThirdStep = function( - self, - mongo_auth_process, - payload, - doc, - db, - username, - password, - authdb, - sendAuthCommand, - connection, - callback -) { - // Build final command - var command = { - saslContinue: 1, - conversationId: doc.conversationId, - payload: payload - }; - - // Execute the command - sendAuthCommand(connection, '$external.$cmd', command, (err, r) => { - if (err) return callback(err, false); - mongo_auth_process.transition(null, function(err) { - if (err) return callback(err, null); - callback(null, r); - }); - }); -}; - -/** - * This is a result from a authentication strategy - * - * @callback authResultCallback - * @param {error} error An error object. Set to null if no error present - * @param {boolean} result The result of the authentication process - */ - -module.exports = GSSAPI; diff --git a/scripts/node_modules/mongodb/lib/core/auth/mongo_credentials.js b/scripts/node_modules/mongodb/lib/core/auth/mongo_credentials.js deleted file mode 100644 index 13c00b14..00000000 --- a/scripts/node_modules/mongodb/lib/core/auth/mongo_credentials.js +++ /dev/null @@ -1,81 +0,0 @@ -'use strict'; - -// Resolves the default auth mechanism according to -// https://github.com/mongodb/specifications/blob/master/source/auth/auth.rst -function getDefaultAuthMechanism(ismaster) { - if (ismaster) { - // If ismaster contains saslSupportedMechs, use scram-sha-256 - // if it is available, else scram-sha-1 - if (Array.isArray(ismaster.saslSupportedMechs)) { - return ismaster.saslSupportedMechs.indexOf('SCRAM-SHA-256') >= 0 - ? 'scram-sha-256' - : 'scram-sha-1'; - } - - // Fallback to legacy selection method. If wire version >= 3, use scram-sha-1 - if (ismaster.maxWireVersion >= 3) { - return 'scram-sha-1'; - } - } - - // Default for wireprotocol < 3 - return 'mongocr'; -} - -/** - * A representation of the credentials used by MongoDB - * @class - * @property {string} mechanism The method used to authenticate - * @property {string} [username] The username used for authentication - * @property {string} [password] The password used for authentication - * @property {string} [source] The database that the user should authenticate against - * @property {object} [mechanismProperties] Special properties used by some types of auth mechanisms - */ -class MongoCredentials { - /** - * Creates a new MongoCredentials object - * @param {object} [options] - * @param {string} [options.username] The username used for authentication - * @param {string} [options.password] The password used for authentication - * @param {string} [options.source] The database that the user should authenticate against - * @param {string} [options.mechanism] The method used to authenticate - * @param {object} [options.mechanismProperties] Special properties used by some types of auth mechanisms - */ - constructor(options) { - options = options || {}; - this.username = options.username; - this.password = options.password; - this.source = options.source || options.db; - this.mechanism = options.mechanism || 'default'; - this.mechanismProperties = options.mechanismProperties; - } - - /** - * Determines if two MongoCredentials objects are equivalent - * @param {MongoCredentials} other another MongoCredentials object - * @returns {boolean} true if the two objects are equal. - */ - equals(other) { - return ( - this.mechanism === other.mechanism && - this.username === other.username && - this.password === other.password && - this.source === other.source - ); - } - - /** - * If the authentication mechanism is set to "default", resolves the authMechanism - * based on the server version and server supported sasl mechanisms. - * - * @param {Object} [ismaster] An ismaster response from the server - */ - resolveAuthMechanism(ismaster) { - // If the mechanism is not "default", then it does not need to be resolved - if (this.mechanism.toLowerCase() === 'default') { - this.mechanism = getDefaultAuthMechanism(ismaster); - } - } -} - -module.exports = { MongoCredentials }; diff --git a/scripts/node_modules/mongodb/lib/core/auth/mongocr.js b/scripts/node_modules/mongodb/lib/core/auth/mongocr.js deleted file mode 100644 index be8fcb6b..00000000 --- a/scripts/node_modules/mongodb/lib/core/auth/mongocr.js +++ /dev/null @@ -1,51 +0,0 @@ -'use strict'; - -const crypto = require('crypto'); -const AuthProvider = require('./auth_provider').AuthProvider; - -/** - * Creates a new MongoCR authentication mechanism - * - * @extends AuthProvider - */ -class MongoCR extends AuthProvider { - /** - * Implementation of authentication for a single connection - * @override - */ - _authenticateSingleConnection(sendAuthCommand, connection, credentials, callback) { - const username = credentials.username; - const password = credentials.password; - const source = credentials.source; - - sendAuthCommand(connection, `${source}.$cmd`, { getnonce: 1 }, (err, r) => { - let nonce = null; - let key = null; - - // Get nonce - if (err == null) { - nonce = r.nonce; - // Use node md5 generator - let md5 = crypto.createHash('md5'); - // Generate keys used for authentication - md5.update(username + ':mongo:' + password, 'utf8'); - const hash_password = md5.digest('hex'); - // Final key - md5 = crypto.createHash('md5'); - md5.update(nonce + username + hash_password, 'utf8'); - key = md5.digest('hex'); - } - - const authenticateCommand = { - authenticate: 1, - user: username, - nonce, - key - }; - - sendAuthCommand(connection, `${source}.$cmd`, authenticateCommand, callback); - }); - } -} - -module.exports = MongoCR; diff --git a/scripts/node_modules/mongodb/lib/core/auth/plain.js b/scripts/node_modules/mongodb/lib/core/auth/plain.js deleted file mode 100644 index 240de758..00000000 --- a/scripts/node_modules/mongodb/lib/core/auth/plain.js +++ /dev/null @@ -1,35 +0,0 @@ -'use strict'; - -const retrieveBSON = require('../connection/utils').retrieveBSON; -const AuthProvider = require('./auth_provider').AuthProvider; - -// TODO: can we get the Binary type from this.bson instead? -const BSON = retrieveBSON(); -const Binary = BSON.Binary; - -/** - * Creates a new Plain authentication mechanism - * - * @extends AuthProvider - */ -class Plain extends AuthProvider { - /** - * Implementation of authentication for a single connection - * @override - */ - _authenticateSingleConnection(sendAuthCommand, connection, credentials, callback) { - const username = credentials.username; - const password = credentials.password; - const payload = new Binary(`\x00${username}\x00${password}`); - const command = { - saslStart: 1, - mechanism: 'PLAIN', - payload: payload, - autoAuthorize: 1 - }; - - sendAuthCommand(connection, '$external.$cmd', command, callback); - } -} - -module.exports = Plain; diff --git a/scripts/node_modules/mongodb/lib/core/auth/scram.js b/scripts/node_modules/mongodb/lib/core/auth/scram.js deleted file mode 100644 index ac8853eb..00000000 --- a/scripts/node_modules/mongodb/lib/core/auth/scram.js +++ /dev/null @@ -1,293 +0,0 @@ -'use strict'; - -const crypto = require('crypto'); -const Buffer = require('safe-buffer').Buffer; -const retrieveBSON = require('../connection/utils').retrieveBSON; -const MongoError = require('../error').MongoError; -const AuthProvider = require('./auth_provider').AuthProvider; - -const BSON = retrieveBSON(); -const Binary = BSON.Binary; - -let saslprep; -try { - saslprep = require('saslprep'); -} catch (e) { - // don't do anything; -} - -var parsePayload = function(payload) { - var dict = {}; - var parts = payload.split(','); - - for (var i = 0; i < parts.length; i++) { - var valueParts = parts[i].split('='); - dict[valueParts[0]] = valueParts[1]; - } - - return dict; -}; - -var passwordDigest = function(username, password) { - if (typeof username !== 'string') throw new MongoError('username must be a string'); - if (typeof password !== 'string') throw new MongoError('password must be a string'); - if (password.length === 0) throw new MongoError('password cannot be empty'); - // Use node md5 generator - var md5 = crypto.createHash('md5'); - // Generate keys used for authentication - md5.update(username + ':mongo:' + password, 'utf8'); - return md5.digest('hex'); -}; - -// XOR two buffers -function xor(a, b) { - if (!Buffer.isBuffer(a)) a = Buffer.from(a); - if (!Buffer.isBuffer(b)) b = Buffer.from(b); - const length = Math.max(a.length, b.length); - const res = []; - - for (let i = 0; i < length; i += 1) { - res.push(a[i] ^ b[i]); - } - - return Buffer.from(res).toString('base64'); -} - -function H(method, text) { - return crypto - .createHash(method) - .update(text) - .digest(); -} - -function HMAC(method, key, text) { - return crypto - .createHmac(method, key) - .update(text) - .digest(); -} - -var _hiCache = {}; -var _hiCacheCount = 0; -var _hiCachePurge = function() { - _hiCache = {}; - _hiCacheCount = 0; -}; - -const hiLengthMap = { - sha256: 32, - sha1: 20 -}; - -function HI(data, salt, iterations, cryptoMethod) { - // omit the work if already generated - const key = [data, salt.toString('base64'), iterations].join('_'); - if (_hiCache[key] !== undefined) { - return _hiCache[key]; - } - - // generate the salt - const saltedData = crypto.pbkdf2Sync( - data, - salt, - iterations, - hiLengthMap[cryptoMethod], - cryptoMethod - ); - - // cache a copy to speed up the next lookup, but prevent unbounded cache growth - if (_hiCacheCount >= 200) { - _hiCachePurge(); - } - - _hiCache[key] = saltedData; - _hiCacheCount += 1; - return saltedData; -} - -/** - * Creates a new ScramSHA authentication mechanism - * @class - * @extends AuthProvider - */ -class ScramSHA extends AuthProvider { - constructor(bson, cryptoMethod) { - super(bson); - this.cryptoMethod = cryptoMethod || 'sha1'; - } - - static _getError(err, r) { - if (err) { - return err; - } - - if (r.$err || r.errmsg) { - return new MongoError(r); - } - } - - /** - * @ignore - */ - _executeScram(sendAuthCommand, connection, credentials, nonce, callback) { - let username = credentials.username; - const password = credentials.password; - const db = credentials.source; - - const cryptoMethod = this.cryptoMethod; - let mechanism = 'SCRAM-SHA-1'; - let processedPassword; - - if (cryptoMethod === 'sha256') { - mechanism = 'SCRAM-SHA-256'; - - processedPassword = saslprep ? saslprep(password) : password; - } else { - try { - processedPassword = passwordDigest(username, password); - } catch (e) { - return callback(e); - } - } - - // Clean up the user - username = username.replace('=', '=3D').replace(',', '=2C'); - - // NOTE: This is done b/c Javascript uses UTF-16, but the server is hashing in UTF-8. - // Since the username is not sasl-prep-d, we need to do this here. - const firstBare = Buffer.concat([ - Buffer.from('n=', 'utf8'), - Buffer.from(username, 'utf8'), - Buffer.from(',r=', 'utf8'), - Buffer.from(nonce, 'utf8') - ]); - - // Build command structure - const saslStartCmd = { - saslStart: 1, - mechanism, - payload: new Binary(Buffer.concat([Buffer.from('n,,', 'utf8'), firstBare])), - autoAuthorize: 1 - }; - - // Write the commmand on the connection - sendAuthCommand(connection, `${db}.$cmd`, saslStartCmd, (err, r) => { - let tmpError = ScramSHA._getError(err, r); - if (tmpError) { - return callback(tmpError, null); - } - - const payload = Buffer.isBuffer(r.payload) ? new Binary(r.payload) : r.payload; - const dict = parsePayload(payload.value()); - const iterations = parseInt(dict.i, 10); - const salt = dict.s; - const rnonce = dict.r; - - // Set up start of proof - const withoutProof = `c=biws,r=${rnonce}`; - const saltedPassword = HI( - processedPassword, - Buffer.from(salt, 'base64'), - iterations, - cryptoMethod - ); - - if (iterations && iterations < 4096) { - const error = new MongoError(`Server returned an invalid iteration count ${iterations}`); - return callback(error, false); - } - - const clientKey = HMAC(cryptoMethod, saltedPassword, 'Client Key'); - const storedKey = H(cryptoMethod, clientKey); - const authMessage = [firstBare, payload.value().toString('base64'), withoutProof].join(','); - - const clientSignature = HMAC(cryptoMethod, storedKey, authMessage); - const clientProof = `p=${xor(clientKey, clientSignature)}`; - const clientFinal = [withoutProof, clientProof].join(','); - const saslContinueCmd = { - saslContinue: 1, - conversationId: r.conversationId, - payload: new Binary(Buffer.from(clientFinal)) - }; - - sendAuthCommand(connection, `${db}.$cmd`, saslContinueCmd, (err, r) => { - if (!r || r.done !== false) { - return callback(err, r); - } - - const retrySaslContinueCmd = { - saslContinue: 1, - conversationId: r.conversationId, - payload: Buffer.alloc(0) - }; - - sendAuthCommand(connection, `${db}.$cmd`, retrySaslContinueCmd, callback); - }); - }); - } - - /** - * Implementation of authentication for a single connection - * @override - */ - _authenticateSingleConnection(sendAuthCommand, connection, credentials, callback) { - // Create a random nonce - crypto.randomBytes(24, (err, buff) => { - if (err) { - return callback(err, null); - } - - return this._executeScram( - sendAuthCommand, - connection, - credentials, - buff.toString('base64'), - callback - ); - }); - } - - /** - * Authenticate - * @override - * @method - */ - auth(sendAuthCommand, connections, credentials, callback) { - this._checkSaslprep(); - super.auth(sendAuthCommand, connections, credentials, callback); - } - - _checkSaslprep() { - const cryptoMethod = this.cryptoMethod; - - if (cryptoMethod === 'sha256') { - if (!saslprep) { - console.warn('Warning: no saslprep library specified. Passwords will not be sanitized'); - } - } - } -} - -/** - * Creates a new ScramSHA1 authentication mechanism - * @class - * @extends ScramSHA - */ -class ScramSHA1 extends ScramSHA { - constructor(bson) { - super(bson, 'sha1'); - } -} - -/** - * Creates a new ScramSHA256 authentication mechanism - * @class - * @extends ScramSHA - */ -class ScramSHA256 extends ScramSHA { - constructor(bson) { - super(bson, 'sha256'); - } -} - -module.exports = { ScramSHA1, ScramSHA256 }; diff --git a/scripts/node_modules/mongodb/lib/core/auth/sspi.js b/scripts/node_modules/mongodb/lib/core/auth/sspi.js deleted file mode 100644 index 8a3f5448..00000000 --- a/scripts/node_modules/mongodb/lib/core/auth/sspi.js +++ /dev/null @@ -1,131 +0,0 @@ -'use strict'; - -const AuthProvider = require('./auth_provider').AuthProvider; -const retrieveKerberos = require('../utils').retrieveKerberos; -let kerberos; - -/** - * Creates a new SSPI authentication mechanism - * @class - * @extends AuthProvider - */ -class SSPI extends AuthProvider { - /** - * Implementation of authentication for a single connection - * @override - */ - _authenticateSingleConnection(sendAuthCommand, connection, credentials, callback) { - // TODO: Destructure this - const username = credentials.username; - const password = credentials.password; - const mechanismProperties = credentials.mechanismProperties; - const gssapiServiceName = - mechanismProperties['gssapiservicename'] || - mechanismProperties['gssapiServiceName'] || - 'mongodb'; - - SSIPAuthenticate( - this, - kerberos.processes.MongoAuthProcess, - username, - password, - gssapiServiceName, - sendAuthCommand, - connection, - mechanismProperties, - callback - ); - } - - /** - * Authenticate - * @override - * @method - */ - auth(sendAuthCommand, connections, credentials, callback) { - if (kerberos == null) { - try { - kerberos = retrieveKerberos(); - } catch (e) { - return callback(e, null); - } - } - - super.auth(sendAuthCommand, connections, credentials, callback); - } -} - -function SSIPAuthenticate( - self, - MongoAuthProcess, - username, - password, - gssapiServiceName, - sendAuthCommand, - connection, - options, - callback -) { - const authProcess = new MongoAuthProcess( - connection.host, - connection.port, - gssapiServiceName, - options - ); - - function authCommand(command, authCb) { - sendAuthCommand(connection, '$external.$cmd', command, authCb); - } - - authProcess.init(username, password, err => { - if (err) return callback(err, false); - - authProcess.transition('', (err, payload) => { - if (err) return callback(err, false); - - const command = { - saslStart: 1, - mechanism: 'GSSAPI', - payload, - autoAuthorize: 1 - }; - - authCommand(command, (err, doc) => { - if (err) return callback(err, false); - - authProcess.transition(doc.payload, (err, payload) => { - if (err) return callback(err, false); - const command = { - saslContinue: 1, - conversationId: doc.conversationId, - payload - }; - - authCommand(command, (err, doc) => { - if (err) return callback(err, false); - - authProcess.transition(doc.payload, (err, payload) => { - if (err) return callback(err, false); - const command = { - saslContinue: 1, - conversationId: doc.conversationId, - payload - }; - - authCommand(command, (err, response) => { - if (err) return callback(err, false); - - authProcess.transition(null, err => { - if (err) return callback(err, null); - callback(null, response); - }); - }); - }); - }); - }); - }); - }); - }); -} - -module.exports = SSPI; diff --git a/scripts/node_modules/mongodb/lib/core/auth/x509.js b/scripts/node_modules/mongodb/lib/core/auth/x509.js deleted file mode 100644 index 10d5b588..00000000 --- a/scripts/node_modules/mongodb/lib/core/auth/x509.js +++ /dev/null @@ -1,26 +0,0 @@ -'use strict'; - -const AuthProvider = require('./auth_provider').AuthProvider; - -/** - * Creates a new X509 authentication mechanism - * @class - * @extends AuthProvider - */ -class X509 extends AuthProvider { - /** - * Implementation of authentication for a single connection - * @override - */ - _authenticateSingleConnection(sendAuthCommand, connection, credentials, callback) { - const username = credentials.username; - const command = { authenticate: 1, mechanism: 'MONGODB-X509' }; - if (username) { - command.user = username; - } - - sendAuthCommand(connection, '$external.$cmd', command, callback); - } -} - -module.exports = X509; diff --git a/scripts/node_modules/mongodb/lib/core/connection/apm.js b/scripts/node_modules/mongodb/lib/core/connection/apm.js deleted file mode 100644 index defc59a1..00000000 --- a/scripts/node_modules/mongodb/lib/core/connection/apm.js +++ /dev/null @@ -1,236 +0,0 @@ -'use strict'; -const Msg = require('../connection/msg').Msg; -const KillCursor = require('../connection/commands').KillCursor; -const GetMore = require('../connection/commands').GetMore; -const calculateDurationInMs = require('../utils').calculateDurationInMs; - -/** Commands that we want to redact because of the sensitive nature of their contents */ -const SENSITIVE_COMMANDS = new Set([ - 'authenticate', - 'saslStart', - 'saslContinue', - 'getnonce', - 'createUser', - 'updateUser', - 'copydbgetnonce', - 'copydbsaslstart', - 'copydb' -]); - -// helper methods -const extractCommandName = commandDoc => Object.keys(commandDoc)[0]; -const namespace = command => command.ns; -const databaseName = command => command.ns.split('.')[0]; -const collectionName = command => command.ns.split('.')[1]; -const generateConnectionId = pool => `${pool.options.host}:${pool.options.port}`; -const maybeRedact = (commandName, result) => (SENSITIVE_COMMANDS.has(commandName) ? {} : result); - -const LEGACY_FIND_QUERY_MAP = { - $query: 'filter', - $orderby: 'sort', - $hint: 'hint', - $comment: 'comment', - $maxScan: 'maxScan', - $max: 'max', - $min: 'min', - $returnKey: 'returnKey', - $showDiskLoc: 'showRecordId', - $maxTimeMS: 'maxTimeMS', - $snapshot: 'snapshot' -}; - -const LEGACY_FIND_OPTIONS_MAP = { - numberToSkip: 'skip', - numberToReturn: 'batchSize', - returnFieldsSelector: 'projection' -}; - -const OP_QUERY_KEYS = [ - 'tailable', - 'oplogReplay', - 'noCursorTimeout', - 'awaitData', - 'partial', - 'exhaust' -]; - -/** - * Extract the actual command from the query, possibly upconverting if it's a legacy - * format - * - * @param {Object} command the command - */ -const extractCommand = command => { - if (command instanceof GetMore) { - return { - getMore: command.cursorId, - collection: collectionName(command), - batchSize: command.numberToReturn - }; - } - - if (command instanceof KillCursor) { - return { - killCursors: collectionName(command), - cursors: command.cursorIds - }; - } - - if (command instanceof Msg) { - return command.command; - } - - if (command.query && command.query.$query) { - let result; - if (command.ns === 'admin.$cmd') { - // upconvert legacy command - result = Object.assign({}, command.query.$query); - } else { - // upconvert legacy find command - result = { find: collectionName(command) }; - Object.keys(LEGACY_FIND_QUERY_MAP).forEach(key => { - if (typeof command.query[key] !== 'undefined') - result[LEGACY_FIND_QUERY_MAP[key]] = command.query[key]; - }); - } - - Object.keys(LEGACY_FIND_OPTIONS_MAP).forEach(key => { - if (typeof command[key] !== 'undefined') result[LEGACY_FIND_OPTIONS_MAP[key]] = command[key]; - }); - - OP_QUERY_KEYS.forEach(key => { - if (command[key]) result[key] = command[key]; - }); - - if (typeof command.pre32Limit !== 'undefined') { - result.limit = command.pre32Limit; - } - - if (command.query.$explain) { - return { explain: result }; - } - - return result; - } - - return command.query ? command.query : command; -}; - -const extractReply = (command, reply) => { - if (command instanceof GetMore) { - return { - ok: 1, - cursor: { - id: reply.message.cursorId, - ns: namespace(command), - nextBatch: reply.message.documents - } - }; - } - - if (command instanceof KillCursor) { - return { - ok: 1, - cursorsUnknown: command.cursorIds - }; - } - - // is this a legacy find command? - if (command.query && typeof command.query.$query !== 'undefined') { - return { - ok: 1, - cursor: { - id: reply.message.cursorId, - ns: namespace(command), - firstBatch: reply.message.documents - } - }; - } - - // in the event of a `noResponse` command, just return - if (reply === null) return reply; - - return reply.result; -}; - -/** An event indicating the start of a given command */ -class CommandStartedEvent { - /** - * Create a started event - * - * @param {Pool} pool the pool that originated the command - * @param {Object} command the command - */ - constructor(pool, command) { - const cmd = extractCommand(command); - const commandName = extractCommandName(cmd); - - // NOTE: remove in major revision, this is not spec behavior - if (SENSITIVE_COMMANDS.has(commandName)) { - this.commandObj = {}; - this.commandObj[commandName] = true; - } - - Object.assign(this, { - command: cmd, - databaseName: databaseName(command), - commandName, - requestId: command.requestId, - connectionId: generateConnectionId(pool) - }); - } -} - -/** An event indicating the success of a given command */ -class CommandSucceededEvent { - /** - * Create a succeeded event - * - * @param {Pool} pool the pool that originated the command - * @param {Object} command the command - * @param {Object} reply the reply for this command from the server - * @param {Array} started a high resolution tuple timestamp of when the command was first sent, to calculate duration - */ - constructor(pool, command, reply, started) { - const cmd = extractCommand(command); - const commandName = extractCommandName(cmd); - - Object.assign(this, { - duration: calculateDurationInMs(started), - commandName, - reply: maybeRedact(commandName, extractReply(command, reply)), - requestId: command.requestId, - connectionId: generateConnectionId(pool) - }); - } -} - -/** An event indicating the failure of a given command */ -class CommandFailedEvent { - /** - * Create a failure event - * - * @param {Pool} pool the pool that originated the command - * @param {Object} command the command - * @param {MongoError|Object} error the generated error or a server error response - * @param {Array} started a high resolution tuple timestamp of when the command was first sent, to calculate duration - */ - constructor(pool, command, error, started) { - const cmd = extractCommand(command); - const commandName = extractCommandName(cmd); - - Object.assign(this, { - duration: calculateDurationInMs(started), - commandName, - failure: maybeRedact(commandName, error), - requestId: command.requestId, - connectionId: generateConnectionId(pool) - }); - } -} - -module.exports = { - CommandStartedEvent, - CommandSucceededEvent, - CommandFailedEvent -}; diff --git a/scripts/node_modules/mongodb/lib/core/connection/command_result.js b/scripts/node_modules/mongodb/lib/core/connection/command_result.js deleted file mode 100644 index 762aa3f1..00000000 --- a/scripts/node_modules/mongodb/lib/core/connection/command_result.js +++ /dev/null @@ -1,36 +0,0 @@ -'use strict'; - -/** - * Creates a new CommandResult instance - * @class - * @param {object} result CommandResult object - * @param {Connection} connection A connection instance associated with this result - * @return {CommandResult} A cursor instance - */ -var CommandResult = function(result, connection, message) { - this.result = result; - this.connection = connection; - this.message = message; -}; - -/** - * Convert CommandResult to JSON - * @method - * @return {object} - */ -CommandResult.prototype.toJSON = function() { - let result = Object.assign({}, this, this.result); - delete result.message; - return result; -}; - -/** - * Convert CommandResult to String representation - * @method - * @return {string} - */ -CommandResult.prototype.toString = function() { - return JSON.stringify(this.toJSON()); -}; - -module.exports = CommandResult; diff --git a/scripts/node_modules/mongodb/lib/core/connection/commands.js b/scripts/node_modules/mongodb/lib/core/connection/commands.js deleted file mode 100644 index b24ff848..00000000 --- a/scripts/node_modules/mongodb/lib/core/connection/commands.js +++ /dev/null @@ -1,507 +0,0 @@ -'use strict'; - -var retrieveBSON = require('./utils').retrieveBSON; -var BSON = retrieveBSON(); -var Long = BSON.Long; -const Buffer = require('safe-buffer').Buffer; - -// Incrementing request id -var _requestId = 0; - -// Wire command operation ids -var opcodes = require('../wireprotocol/shared').opcodes; - -// Query flags -var OPTS_TAILABLE_CURSOR = 2; -var OPTS_SLAVE = 4; -var OPTS_OPLOG_REPLAY = 8; -var OPTS_NO_CURSOR_TIMEOUT = 16; -var OPTS_AWAIT_DATA = 32; -var OPTS_EXHAUST = 64; -var OPTS_PARTIAL = 128; - -// Response flags -var CURSOR_NOT_FOUND = 1; -var QUERY_FAILURE = 2; -var SHARD_CONFIG_STALE = 4; -var AWAIT_CAPABLE = 8; - -/************************************************************** - * QUERY - **************************************************************/ -var Query = function(bson, ns, query, options) { - var self = this; - // Basic options needed to be passed in - if (ns == null) throw new Error('ns must be specified for query'); - if (query == null) throw new Error('query must be specified for query'); - - // Validate that we are not passing 0x00 in the collection name - if (ns.indexOf('\x00') !== -1) { - throw new Error('namespace cannot contain a null character'); - } - - // Basic options - this.bson = bson; - this.ns = ns; - this.query = query; - - // Additional options - this.numberToSkip = options.numberToSkip || 0; - this.numberToReturn = options.numberToReturn || 0; - this.returnFieldSelector = options.returnFieldSelector || null; - this.requestId = Query.getRequestId(); - - // special case for pre-3.2 find commands, delete ASAP - this.pre32Limit = options.pre32Limit; - - // Serialization option - this.serializeFunctions = - typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; - this.ignoreUndefined = - typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : false; - this.maxBsonSize = options.maxBsonSize || 1024 * 1024 * 16; - this.checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : true; - this.batchSize = self.numberToReturn; - - // Flags - this.tailable = false; - this.slaveOk = typeof options.slaveOk === 'boolean' ? options.slaveOk : false; - this.oplogReplay = false; - this.noCursorTimeout = false; - this.awaitData = false; - this.exhaust = false; - this.partial = false; -}; - -// -// Assign a new request Id -Query.prototype.incRequestId = function() { - this.requestId = _requestId++; -}; - -// -// Assign a new request Id -Query.nextRequestId = function() { - return _requestId + 1; -}; - -// -// Uses a single allocated buffer for the process, avoiding multiple memory allocations -Query.prototype.toBin = function() { - var self = this; - var buffers = []; - var projection = null; - - // Set up the flags - var flags = 0; - if (this.tailable) { - flags |= OPTS_TAILABLE_CURSOR; - } - - if (this.slaveOk) { - flags |= OPTS_SLAVE; - } - - if (this.oplogReplay) { - flags |= OPTS_OPLOG_REPLAY; - } - - if (this.noCursorTimeout) { - flags |= OPTS_NO_CURSOR_TIMEOUT; - } - - if (this.awaitData) { - flags |= OPTS_AWAIT_DATA; - } - - if (this.exhaust) { - flags |= OPTS_EXHAUST; - } - - if (this.partial) { - flags |= OPTS_PARTIAL; - } - - // If batchSize is different to self.numberToReturn - if (self.batchSize !== self.numberToReturn) self.numberToReturn = self.batchSize; - - // Allocate write protocol header buffer - var header = Buffer.alloc( - 4 * 4 + // Header - 4 + // Flags - Buffer.byteLength(self.ns) + - 1 + // namespace - 4 + // numberToSkip - 4 // numberToReturn - ); - - // Add header to buffers - buffers.push(header); - - // Serialize the query - var query = self.bson.serialize(this.query, { - checkKeys: this.checkKeys, - serializeFunctions: this.serializeFunctions, - ignoreUndefined: this.ignoreUndefined - }); - - // Add query document - buffers.push(query); - - if (self.returnFieldSelector && Object.keys(self.returnFieldSelector).length > 0) { - // Serialize the projection document - projection = self.bson.serialize(this.returnFieldSelector, { - checkKeys: this.checkKeys, - serializeFunctions: this.serializeFunctions, - ignoreUndefined: this.ignoreUndefined - }); - // Add projection document - buffers.push(projection); - } - - // Total message size - var totalLength = header.length + query.length + (projection ? projection.length : 0); - - // Set up the index - var index = 4; - - // Write total document length - header[3] = (totalLength >> 24) & 0xff; - header[2] = (totalLength >> 16) & 0xff; - header[1] = (totalLength >> 8) & 0xff; - header[0] = totalLength & 0xff; - - // Write header information requestId - header[index + 3] = (this.requestId >> 24) & 0xff; - header[index + 2] = (this.requestId >> 16) & 0xff; - header[index + 1] = (this.requestId >> 8) & 0xff; - header[index] = this.requestId & 0xff; - index = index + 4; - - // Write header information responseTo - header[index + 3] = (0 >> 24) & 0xff; - header[index + 2] = (0 >> 16) & 0xff; - header[index + 1] = (0 >> 8) & 0xff; - header[index] = 0 & 0xff; - index = index + 4; - - // Write header information OP_QUERY - header[index + 3] = (opcodes.OP_QUERY >> 24) & 0xff; - header[index + 2] = (opcodes.OP_QUERY >> 16) & 0xff; - header[index + 1] = (opcodes.OP_QUERY >> 8) & 0xff; - header[index] = opcodes.OP_QUERY & 0xff; - index = index + 4; - - // Write header information flags - header[index + 3] = (flags >> 24) & 0xff; - header[index + 2] = (flags >> 16) & 0xff; - header[index + 1] = (flags >> 8) & 0xff; - header[index] = flags & 0xff; - index = index + 4; - - // Write collection name - index = index + header.write(this.ns, index, 'utf8') + 1; - header[index - 1] = 0; - - // Write header information flags numberToSkip - header[index + 3] = (this.numberToSkip >> 24) & 0xff; - header[index + 2] = (this.numberToSkip >> 16) & 0xff; - header[index + 1] = (this.numberToSkip >> 8) & 0xff; - header[index] = this.numberToSkip & 0xff; - index = index + 4; - - // Write header information flags numberToReturn - header[index + 3] = (this.numberToReturn >> 24) & 0xff; - header[index + 2] = (this.numberToReturn >> 16) & 0xff; - header[index + 1] = (this.numberToReturn >> 8) & 0xff; - header[index] = this.numberToReturn & 0xff; - index = index + 4; - - // Return the buffers - return buffers; -}; - -Query.getRequestId = function() { - return ++_requestId; -}; - -/************************************************************** - * GETMORE - **************************************************************/ -var GetMore = function(bson, ns, cursorId, opts) { - opts = opts || {}; - this.numberToReturn = opts.numberToReturn || 0; - this.requestId = _requestId++; - this.bson = bson; - this.ns = ns; - this.cursorId = cursorId; -}; - -// -// Uses a single allocated buffer for the process, avoiding multiple memory allocations -GetMore.prototype.toBin = function() { - var length = 4 + Buffer.byteLength(this.ns) + 1 + 4 + 8 + 4 * 4; - // Create command buffer - var index = 0; - // Allocate buffer - var _buffer = Buffer.alloc(length); - - // Write header information - // index = write32bit(index, _buffer, length); - _buffer[index + 3] = (length >> 24) & 0xff; - _buffer[index + 2] = (length >> 16) & 0xff; - _buffer[index + 1] = (length >> 8) & 0xff; - _buffer[index] = length & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, requestId); - _buffer[index + 3] = (this.requestId >> 24) & 0xff; - _buffer[index + 2] = (this.requestId >> 16) & 0xff; - _buffer[index + 1] = (this.requestId >> 8) & 0xff; - _buffer[index] = this.requestId & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, 0); - _buffer[index + 3] = (0 >> 24) & 0xff; - _buffer[index + 2] = (0 >> 16) & 0xff; - _buffer[index + 1] = (0 >> 8) & 0xff; - _buffer[index] = 0 & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, OP_GETMORE); - _buffer[index + 3] = (opcodes.OP_GETMORE >> 24) & 0xff; - _buffer[index + 2] = (opcodes.OP_GETMORE >> 16) & 0xff; - _buffer[index + 1] = (opcodes.OP_GETMORE >> 8) & 0xff; - _buffer[index] = opcodes.OP_GETMORE & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, 0); - _buffer[index + 3] = (0 >> 24) & 0xff; - _buffer[index + 2] = (0 >> 16) & 0xff; - _buffer[index + 1] = (0 >> 8) & 0xff; - _buffer[index] = 0 & 0xff; - index = index + 4; - - // Write collection name - index = index + _buffer.write(this.ns, index, 'utf8') + 1; - _buffer[index - 1] = 0; - - // Write batch size - // index = write32bit(index, _buffer, numberToReturn); - _buffer[index + 3] = (this.numberToReturn >> 24) & 0xff; - _buffer[index + 2] = (this.numberToReturn >> 16) & 0xff; - _buffer[index + 1] = (this.numberToReturn >> 8) & 0xff; - _buffer[index] = this.numberToReturn & 0xff; - index = index + 4; - - // Write cursor id - // index = write32bit(index, _buffer, cursorId.getLowBits()); - _buffer[index + 3] = (this.cursorId.getLowBits() >> 24) & 0xff; - _buffer[index + 2] = (this.cursorId.getLowBits() >> 16) & 0xff; - _buffer[index + 1] = (this.cursorId.getLowBits() >> 8) & 0xff; - _buffer[index] = this.cursorId.getLowBits() & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, cursorId.getHighBits()); - _buffer[index + 3] = (this.cursorId.getHighBits() >> 24) & 0xff; - _buffer[index + 2] = (this.cursorId.getHighBits() >> 16) & 0xff; - _buffer[index + 1] = (this.cursorId.getHighBits() >> 8) & 0xff; - _buffer[index] = this.cursorId.getHighBits() & 0xff; - index = index + 4; - - // Return buffer - return _buffer; -}; - -/************************************************************** - * KILLCURSOR - **************************************************************/ -var KillCursor = function(bson, ns, cursorIds) { - this.ns = ns; - this.requestId = _requestId++; - this.cursorIds = cursorIds; -}; - -// -// Uses a single allocated buffer for the process, avoiding multiple memory allocations -KillCursor.prototype.toBin = function() { - var length = 4 + 4 + 4 * 4 + this.cursorIds.length * 8; - - // Create command buffer - var index = 0; - var _buffer = Buffer.alloc(length); - - // Write header information - // index = write32bit(index, _buffer, length); - _buffer[index + 3] = (length >> 24) & 0xff; - _buffer[index + 2] = (length >> 16) & 0xff; - _buffer[index + 1] = (length >> 8) & 0xff; - _buffer[index] = length & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, requestId); - _buffer[index + 3] = (this.requestId >> 24) & 0xff; - _buffer[index + 2] = (this.requestId >> 16) & 0xff; - _buffer[index + 1] = (this.requestId >> 8) & 0xff; - _buffer[index] = this.requestId & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, 0); - _buffer[index + 3] = (0 >> 24) & 0xff; - _buffer[index + 2] = (0 >> 16) & 0xff; - _buffer[index + 1] = (0 >> 8) & 0xff; - _buffer[index] = 0 & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, OP_KILL_CURSORS); - _buffer[index + 3] = (opcodes.OP_KILL_CURSORS >> 24) & 0xff; - _buffer[index + 2] = (opcodes.OP_KILL_CURSORS >> 16) & 0xff; - _buffer[index + 1] = (opcodes.OP_KILL_CURSORS >> 8) & 0xff; - _buffer[index] = opcodes.OP_KILL_CURSORS & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, 0); - _buffer[index + 3] = (0 >> 24) & 0xff; - _buffer[index + 2] = (0 >> 16) & 0xff; - _buffer[index + 1] = (0 >> 8) & 0xff; - _buffer[index] = 0 & 0xff; - index = index + 4; - - // Write batch size - // index = write32bit(index, _buffer, this.cursorIds.length); - _buffer[index + 3] = (this.cursorIds.length >> 24) & 0xff; - _buffer[index + 2] = (this.cursorIds.length >> 16) & 0xff; - _buffer[index + 1] = (this.cursorIds.length >> 8) & 0xff; - _buffer[index] = this.cursorIds.length & 0xff; - index = index + 4; - - // Write all the cursor ids into the array - for (var i = 0; i < this.cursorIds.length; i++) { - // Write cursor id - // index = write32bit(index, _buffer, cursorIds[i].getLowBits()); - _buffer[index + 3] = (this.cursorIds[i].getLowBits() >> 24) & 0xff; - _buffer[index + 2] = (this.cursorIds[i].getLowBits() >> 16) & 0xff; - _buffer[index + 1] = (this.cursorIds[i].getLowBits() >> 8) & 0xff; - _buffer[index] = this.cursorIds[i].getLowBits() & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, cursorIds[i].getHighBits()); - _buffer[index + 3] = (this.cursorIds[i].getHighBits() >> 24) & 0xff; - _buffer[index + 2] = (this.cursorIds[i].getHighBits() >> 16) & 0xff; - _buffer[index + 1] = (this.cursorIds[i].getHighBits() >> 8) & 0xff; - _buffer[index] = this.cursorIds[i].getHighBits() & 0xff; - index = index + 4; - } - - // Return buffer - return _buffer; -}; - -var Response = function(bson, message, msgHeader, msgBody, opts) { - opts = opts || { promoteLongs: true, promoteValues: true, promoteBuffers: false }; - this.parsed = false; - this.raw = message; - this.data = msgBody; - this.bson = bson; - this.opts = opts; - - // Read the message header - this.length = msgHeader.length; - this.requestId = msgHeader.requestId; - this.responseTo = msgHeader.responseTo; - this.opCode = msgHeader.opCode; - this.fromCompressed = msgHeader.fromCompressed; - - // Read the message body - this.responseFlags = msgBody.readInt32LE(0); - this.cursorId = new Long(msgBody.readInt32LE(4), msgBody.readInt32LE(8)); - this.startingFrom = msgBody.readInt32LE(12); - this.numberReturned = msgBody.readInt32LE(16); - - // Preallocate document array - this.documents = new Array(this.numberReturned); - - // Flag values - this.cursorNotFound = (this.responseFlags & CURSOR_NOT_FOUND) !== 0; - this.queryFailure = (this.responseFlags & QUERY_FAILURE) !== 0; - this.shardConfigStale = (this.responseFlags & SHARD_CONFIG_STALE) !== 0; - this.awaitCapable = (this.responseFlags & AWAIT_CAPABLE) !== 0; - this.promoteLongs = typeof opts.promoteLongs === 'boolean' ? opts.promoteLongs : true; - this.promoteValues = typeof opts.promoteValues === 'boolean' ? opts.promoteValues : true; - this.promoteBuffers = typeof opts.promoteBuffers === 'boolean' ? opts.promoteBuffers : false; -}; - -Response.prototype.isParsed = function() { - return this.parsed; -}; - -Response.prototype.parse = function(options) { - // Don't parse again if not needed - if (this.parsed) return; - options = options || {}; - - // Allow the return of raw documents instead of parsing - var raw = options.raw || false; - var documentsReturnedIn = options.documentsReturnedIn || null; - var promoteLongs = - typeof options.promoteLongs === 'boolean' ? options.promoteLongs : this.opts.promoteLongs; - var promoteValues = - typeof options.promoteValues === 'boolean' ? options.promoteValues : this.opts.promoteValues; - var promoteBuffers = - typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : this.opts.promoteBuffers; - var bsonSize, _options; - - // Set up the options - _options = { - promoteLongs: promoteLongs, - promoteValues: promoteValues, - promoteBuffers: promoteBuffers - }; - - // Position within OP_REPLY at which documents start - // (See https://docs.mongodb.com/manual/reference/mongodb-wire-protocol/#wire-op-reply) - this.index = 20; - - // - // Parse Body - // - for (var i = 0; i < this.numberReturned; i++) { - bsonSize = - this.data[this.index] | - (this.data[this.index + 1] << 8) | - (this.data[this.index + 2] << 16) | - (this.data[this.index + 3] << 24); - - // If we have raw results specified slice the return document - if (raw) { - this.documents[i] = this.data.slice(this.index, this.index + bsonSize); - } else { - this.documents[i] = this.bson.deserialize( - this.data.slice(this.index, this.index + bsonSize), - _options - ); - } - - // Adjust the index - this.index = this.index + bsonSize; - } - - if (this.documents.length === 1 && documentsReturnedIn != null && raw) { - const fieldsAsRaw = {}; - fieldsAsRaw[documentsReturnedIn] = true; - _options.fieldsAsRaw = fieldsAsRaw; - - const doc = this.bson.deserialize(this.documents[0], _options); - this.documents = [doc]; - } - - // Set parsed - this.parsed = true; -}; - -module.exports = { - Query: Query, - GetMore: GetMore, - Response: Response, - KillCursor: KillCursor -}; diff --git a/scripts/node_modules/mongodb/lib/core/connection/connect.js b/scripts/node_modules/mongodb/lib/core/connection/connect.js deleted file mode 100644 index e1a643e0..00000000 --- a/scripts/node_modules/mongodb/lib/core/connection/connect.js +++ /dev/null @@ -1,370 +0,0 @@ -'use strict'; -const net = require('net'); -const tls = require('tls'); -const Connection = require('./connection'); -const Query = require('./commands').Query; -const createClientInfo = require('../topologies/shared').createClientInfo; -const MongoError = require('../error').MongoError; -const MongoNetworkError = require('../error').MongoNetworkError; -const defaultAuthProviders = require('../auth/defaultAuthProviders').defaultAuthProviders; -const WIRE_CONSTANTS = require('../wireprotocol/constants'); -const MAX_SUPPORTED_WIRE_VERSION = WIRE_CONSTANTS.MAX_SUPPORTED_WIRE_VERSION; -const MAX_SUPPORTED_SERVER_VERSION = WIRE_CONSTANTS.MAX_SUPPORTED_SERVER_VERSION; -const MIN_SUPPORTED_WIRE_VERSION = WIRE_CONSTANTS.MIN_SUPPORTED_WIRE_VERSION; -const MIN_SUPPORTED_SERVER_VERSION = WIRE_CONSTANTS.MIN_SUPPORTED_SERVER_VERSION; -let AUTH_PROVIDERS; - -function connect(options, callback) { - if (AUTH_PROVIDERS == null) { - AUTH_PROVIDERS = defaultAuthProviders(options.bson); - } - - if (options.family !== void 0) { - makeConnection(options.family, options, (err, socket) => { - if (err) { - callback(err, socket); // in the error case, `socket` is the originating error event name - return; - } - - performInitialHandshake(new Connection(socket, options), options, callback); - }); - - return; - } - - return makeConnection(6, options, (err, ipv6Socket) => { - if (err) { - makeConnection(4, options, (err, ipv4Socket) => { - if (err) { - callback(err, ipv4Socket); // in the error case, `ipv4Socket` is the originating error event name - return; - } - - performInitialHandshake(new Connection(ipv4Socket, options), options, callback); - }); - - return; - } - - performInitialHandshake(new Connection(ipv6Socket, options), options, callback); - }); -} - -function getSaslSupportedMechs(options) { - if (!(options && options.credentials)) { - return {}; - } - - const credentials = options.credentials; - - // TODO: revisit whether or not items like `options.user` and `options.dbName` should be checked here - const authMechanism = credentials.mechanism; - const authSource = credentials.source || options.dbName || 'admin'; - const user = credentials.username || options.user; - - if (typeof authMechanism === 'string' && authMechanism.toUpperCase() !== 'DEFAULT') { - return {}; - } - - if (!user) { - return {}; - } - - return { saslSupportedMechs: `${authSource}.${user}` }; -} - -function checkSupportedServer(ismaster, options) { - const serverVersionHighEnough = - ismaster && - typeof ismaster.maxWireVersion === 'number' && - ismaster.maxWireVersion >= MIN_SUPPORTED_WIRE_VERSION; - const serverVersionLowEnough = - ismaster && - typeof ismaster.minWireVersion === 'number' && - ismaster.minWireVersion <= MAX_SUPPORTED_WIRE_VERSION; - - if (serverVersionHighEnough) { - if (serverVersionLowEnough) { - return null; - } - - const message = `Server at ${options.host}:${options.port} reports minimum wire version ${ - ismaster.minWireVersion - }, but this version of the Node.js Driver requires at most ${MAX_SUPPORTED_WIRE_VERSION} (MongoDB ${MAX_SUPPORTED_SERVER_VERSION})`; - return new MongoError(message); - } - - const message = `Server at ${options.host}:${ - options.port - } reports maximum wire version ${ismaster.maxWireVersion || - 0}, but this version of the Node.js Driver requires at least ${MIN_SUPPORTED_WIRE_VERSION} (MongoDB ${MIN_SUPPORTED_SERVER_VERSION})`; - return new MongoError(message); -} - -function performInitialHandshake(conn, options, _callback) { - const callback = function(err, ret) { - if (err && conn) { - conn.destroy(); - } - _callback(err, ret); - }; - - let compressors = []; - if (options.compression && options.compression.compressors) { - compressors = options.compression.compressors; - } - - const handshakeDoc = Object.assign( - { - ismaster: true, - client: createClientInfo(options), - compression: compressors - }, - getSaslSupportedMechs(options) - ); - - const start = new Date().getTime(); - runCommand(conn, 'admin.$cmd', handshakeDoc, options, (err, ismaster) => { - if (err) { - callback(err, null); - return; - } - - if (ismaster.ok === 0) { - callback(new MongoError(ismaster), null); - return; - } - - const supportedServerErr = checkSupportedServer(ismaster, options); - if (supportedServerErr) { - callback(supportedServerErr, null); - return; - } - - // resolve compression - if (ismaster.compression) { - const agreedCompressors = compressors.filter( - compressor => ismaster.compression.indexOf(compressor) !== -1 - ); - - if (agreedCompressors.length) { - conn.agreedCompressor = agreedCompressors[0]; - } - - if (options.compression && options.compression.zlibCompressionLevel) { - conn.zlibCompressionLevel = options.compression.zlibCompressionLevel; - } - } - - // NOTE: This is metadata attached to the connection while porting away from - // handshake being done in the `Server` class. Likely, it should be - // relocated, or at very least restructured. - conn.ismaster = ismaster; - conn.lastIsMasterMS = new Date().getTime() - start; - - const credentials = options.credentials; - if (!ismaster.arbiterOnly && credentials) { - credentials.resolveAuthMechanism(ismaster); - authenticate(conn, credentials, callback); - return; - } - - callback(null, conn); - }); -} - -const LEGAL_SSL_SOCKET_OPTIONS = [ - 'pfx', - 'key', - 'passphrase', - 'cert', - 'ca', - 'ciphers', - 'NPNProtocols', - 'ALPNProtocols', - 'servername', - 'ecdhCurve', - 'secureProtocol', - 'secureContext', - 'session', - 'minDHSize', - 'crl', - 'rejectUnauthorized' -]; - -function parseConnectOptions(family, options) { - const host = typeof options.host === 'string' ? options.host : 'localhost'; - if (host.indexOf('/') !== -1) { - return { path: host }; - } - - const result = { - family, - host, - port: typeof options.port === 'number' ? options.port : 27017, - rejectUnauthorized: false - }; - - return result; -} - -function parseSslOptions(family, options) { - const result = parseConnectOptions(family, options); - - // Merge in valid SSL options - for (const name in options) { - if (options[name] != null && LEGAL_SSL_SOCKET_OPTIONS.indexOf(name) !== -1) { - result[name] = options[name]; - } - } - - // Override checkServerIdentity behavior - if (options.checkServerIdentity === false) { - // Skip the identiy check by retuning undefined as per node documents - // https://nodejs.org/api/tls.html#tls_tls_connect_options_callback - result.checkServerIdentity = function() { - return undefined; - }; - } else if (typeof options.checkServerIdentity === 'function') { - result.checkServerIdentity = options.checkServerIdentity; - } - - // Set default sni servername to be the same as host - if (result.servername == null) { - result.servername = result.host; - } - - return result; -} - -function makeConnection(family, options, _callback) { - const useSsl = typeof options.ssl === 'boolean' ? options.ssl : false; - const keepAlive = typeof options.keepAlive === 'boolean' ? options.keepAlive : true; - let keepAliveInitialDelay = - typeof options.keepAliveInitialDelay === 'number' ? options.keepAliveInitialDelay : 300000; - const noDelay = typeof options.noDelay === 'boolean' ? options.noDelay : true; - const connectionTimeout = - typeof options.connectionTimeout === 'number' ? options.connectionTimeout : 30000; - const socketTimeout = typeof options.socketTimeout === 'number' ? options.socketTimeout : 360000; - const rejectUnauthorized = - typeof options.rejectUnauthorized === 'boolean' ? options.rejectUnauthorized : true; - - if (keepAliveInitialDelay > socketTimeout) { - keepAliveInitialDelay = Math.round(socketTimeout / 2); - } - - let socket; - const callback = function(err, ret) { - if (err && socket) { - socket.destroy(); - } - _callback(err, ret); - }; - - try { - if (useSsl) { - socket = tls.connect(parseSslOptions(family, options)); - if (typeof socket.disableRenegotiation === 'function') { - socket.disableRenegotiation(); - } - } else { - socket = net.createConnection(parseConnectOptions(family, options)); - } - } catch (err) { - return callback(err); - } - - socket.setKeepAlive(keepAlive, keepAliveInitialDelay); - socket.setTimeout(connectionTimeout); - socket.setNoDelay(noDelay); - - const errorEvents = ['error', 'close', 'timeout', 'parseError']; - function errorHandler(eventName) { - return err => { - errorEvents.forEach(event => socket.removeAllListeners(event)); - socket.removeListener('connect', connectHandler); - callback(connectionFailureError(eventName, err), eventName); - }; - } - - function connectHandler() { - errorEvents.forEach(event => socket.removeAllListeners(event)); - if (socket.authorizationError && rejectUnauthorized) { - return callback(socket.authorizationError); - } - - socket.setTimeout(socketTimeout); - callback(null, socket); - } - - socket.once('error', errorHandler('error')); - socket.once('close', errorHandler('close')); - socket.once('timeout', errorHandler('timeout')); - socket.once('parseError', errorHandler('parseError')); - socket.once('connect', connectHandler); -} - -const CONNECTION_ERROR_EVENTS = ['error', 'close', 'timeout', 'parseError']; -function runCommand(conn, ns, command, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - const socketTimeout = typeof options.socketTimeout === 'number' ? options.socketTimeout : 360000; - const bson = conn.options.bson; - const query = new Query(bson, ns, command, { - numberToSkip: 0, - numberToReturn: 1 - }); - - function errorHandler(err) { - conn.resetSocketTimeout(); - CONNECTION_ERROR_EVENTS.forEach(eventName => conn.removeListener(eventName, errorHandler)); - conn.removeListener('message', messageHandler); - callback(err, null); - } - - function messageHandler(msg) { - if (msg.responseTo !== query.requestId) { - return; - } - - conn.resetSocketTimeout(); - CONNECTION_ERROR_EVENTS.forEach(eventName => conn.removeListener(eventName, errorHandler)); - conn.removeListener('message', messageHandler); - - msg.parse({ promoteValues: true }); - callback(null, msg.documents[0]); - } - - conn.setSocketTimeout(socketTimeout); - CONNECTION_ERROR_EVENTS.forEach(eventName => conn.once(eventName, errorHandler)); - conn.on('message', messageHandler); - conn.write(query.toBin()); -} - -function authenticate(conn, credentials, callback) { - const mechanism = credentials.mechanism; - if (!AUTH_PROVIDERS[mechanism]) { - callback(new MongoError(`authMechanism '${mechanism}' not supported`)); - return; - } - - const provider = AUTH_PROVIDERS[mechanism]; - provider.auth(runCommand, [conn], credentials, err => { - if (err) return callback(err); - callback(null, conn); - }); -} - -function connectionFailureError(type, err) { - switch (type) { - case 'error': - return new MongoNetworkError(err); - case 'timeout': - return new MongoNetworkError(`connection timed out`); - case 'close': - return new MongoNetworkError(`connection closed`); - default: - return new MongoNetworkError(`unknown network error`); - } -} - -module.exports = connect; diff --git a/scripts/node_modules/mongodb/lib/core/connection/connection.js b/scripts/node_modules/mongodb/lib/core/connection/connection.js deleted file mode 100644 index 6f6ca6ad..00000000 --- a/scripts/node_modules/mongodb/lib/core/connection/connection.js +++ /dev/null @@ -1,628 +0,0 @@ -'use strict'; - -const EventEmitter = require('events').EventEmitter; -const crypto = require('crypto'); -const debugOptions = require('./utils').debugOptions; -const parseHeader = require('../wireprotocol/shared').parseHeader; -const decompress = require('../wireprotocol/compression').decompress; -const Response = require('./commands').Response; -const BinMsg = require('./msg').BinMsg; -const MongoNetworkError = require('../error').MongoNetworkError; -const MongoError = require('../error').MongoError; -const Logger = require('./logger'); -const OP_COMPRESSED = require('../wireprotocol/shared').opcodes.OP_COMPRESSED; -const OP_MSG = require('../wireprotocol/shared').opcodes.OP_MSG; -const MESSAGE_HEADER_SIZE = require('../wireprotocol/shared').MESSAGE_HEADER_SIZE; -const Buffer = require('safe-buffer').Buffer; - -let _id = 0; - -const DEFAULT_MAX_BSON_MESSAGE_SIZE = 1024 * 1024 * 16 * 4; -const DEBUG_FIELDS = [ - 'host', - 'port', - 'size', - 'keepAlive', - 'keepAliveInitialDelay', - 'noDelay', - 'connectionTimeout', - 'socketTimeout', - 'ssl', - 'ca', - 'crl', - 'cert', - 'rejectUnauthorized', - 'promoteLongs', - 'promoteValues', - 'promoteBuffers', - 'checkServerIdentity' -]; - -let connectionAccountingSpy = undefined; -let connectionAccounting = false; -let connections = {}; - -/** - * A class representing a single connection to a MongoDB server - * - * @fires Connection#connect - * @fires Connection#close - * @fires Connection#error - * @fires Connection#timeout - * @fires Connection#parseError - * @fires Connection#message - */ -class Connection extends EventEmitter { - /** - * Creates a new Connection instance - * - * **NOTE**: Internal class, do not instantiate directly - * - * @param {Socket} socket The socket this connection wraps - * @param {Object} options Various settings - * @param {object} options.bson An implementation of bson serialize and deserialize - * @param {string} [options.host='localhost'] The host the socket is connected to - * @param {number} [options.port=27017] The port used for the socket connection - * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled - * @param {number} [options.keepAliveInitialDelay=300000] Initial delay before TCP keep alive enabled - * @param {number} [options.connectionTimeout=30000] TCP Connection timeout setting - * @param {number} [options.socketTimeout=360000] TCP Socket timeout setting - * @param {boolean} [options.promoteLongs] Convert Long values from the db into Numbers if they fit into 53 bits - * @param {boolean} [options.promoteValues] Promotes BSON values to native types where possible, set to false to only receive wrapper types. - * @param {boolean} [options.promoteBuffers] Promotes Binary BSON values to native Node Buffers. - * @param {number} [options.maxBsonMessageSize=0x4000000] Largest possible size of a BSON message (for legacy purposes) - */ - constructor(socket, options) { - super(); - - options = options || {}; - if (!options.bson) { - throw new TypeError('must pass in valid bson parser'); - } - - this.id = _id++; - this.options = options; - this.logger = Logger('Connection', options); - this.bson = options.bson; - this.tag = options.tag; - this.maxBsonMessageSize = options.maxBsonMessageSize || DEFAULT_MAX_BSON_MESSAGE_SIZE; - - this.port = options.port || 27017; - this.host = options.host || 'localhost'; - this.socketTimeout = typeof options.socketTimeout === 'number' ? options.socketTimeout : 360000; - - // These values are inspected directly in tests, but maybe not necessary to keep around - this.keepAlive = typeof options.keepAlive === 'boolean' ? options.keepAlive : true; - this.keepAliveInitialDelay = - typeof options.keepAliveInitialDelay === 'number' ? options.keepAliveInitialDelay : 300000; - this.connectionTimeout = - typeof options.connectionTimeout === 'number' ? options.connectionTimeout : 30000; - if (this.keepAliveInitialDelay > this.socketTimeout) { - this.keepAliveInitialDelay = Math.round(this.socketTimeout / 2); - } - - // Debug information - if (this.logger.isDebug()) { - this.logger.debug( - `creating connection ${this.id} with options [${JSON.stringify( - debugOptions(DEBUG_FIELDS, options) - )}]` - ); - } - - // Response options - this.responseOptions = { - promoteLongs: typeof options.promoteLongs === 'boolean' ? options.promoteLongs : true, - promoteValues: typeof options.promoteValues === 'boolean' ? options.promoteValues : true, - promoteBuffers: typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : false - }; - - // Flushing - this.flushing = false; - this.queue = []; - - // Internal state - this.writeStream = null; - this.destroyed = false; - - // Create hash method - const hash = crypto.createHash('sha1'); - hash.update(this.address); - this.hashedName = hash.digest('hex'); - - // All operations in flight on the connection - this.workItems = []; - - // setup socket - this.socket = socket; - this.socket.once('error', errorHandler(this)); - this.socket.once('timeout', timeoutHandler(this)); - this.socket.once('close', closeHandler(this)); - this.socket.on('data', dataHandler(this)); - - if (connectionAccounting) { - addConnection(this.id, this); - } - } - - setSocketTimeout(value) { - if (this.socket) { - this.socket.setTimeout(value); - } - } - - resetSocketTimeout() { - if (this.socket) { - this.socket.setTimeout(this.socketTimeout); - } - } - - static enableConnectionAccounting(spy) { - if (spy) { - connectionAccountingSpy = spy; - } - - connectionAccounting = true; - connections = {}; - } - - static disableConnectionAccounting() { - connectionAccounting = false; - connectionAccountingSpy = undefined; - } - - static connections() { - return connections; - } - - get address() { - return `${this.host}:${this.port}`; - } - - /** - * Unref this connection - * @method - * @return {boolean} - */ - unref() { - if (this.socket == null) { - this.once('connect', () => this.socket.unref()); - return; - } - - this.socket.unref(); - } - - /** - * Destroy connection - * @method - */ - destroy(options, callback) { - if (typeof options === 'function') { - callback = options; - options = {}; - } - - options = Object.assign({ force: false }, options); - - if (connectionAccounting) { - deleteConnection(this.id); - } - - if (this.socket == null) { - this.destroyed = true; - return; - } - - if (options.force) { - this.socket.destroy(); - this.destroyed = true; - if (typeof callback === 'function') callback(null, null); - return; - } - - this.socket.end(err => { - this.destroyed = true; - if (typeof callback === 'function') callback(err, null); - }); - } - - /** - * Write to connection - * @method - * @param {Command} command Command to write out need to implement toBin and toBinUnified - */ - write(buffer) { - // Debug Log - if (this.logger.isDebug()) { - if (!Array.isArray(buffer)) { - this.logger.debug(`writing buffer [${buffer.toString('hex')}] to ${this.address}`); - } else { - for (let i = 0; i < buffer.length; i++) - this.logger.debug(`writing buffer [${buffer[i].toString('hex')}] to ${this.address}`); - } - } - - // Double check that the connection is not destroyed - if (this.socket.destroyed === false) { - // Write out the command - if (!Array.isArray(buffer)) { - this.socket.write(buffer, 'binary'); - return true; - } - - // Iterate over all buffers and write them in order to the socket - for (let i = 0; i < buffer.length; i++) { - this.socket.write(buffer[i], 'binary'); - } - - return true; - } - - // Connection is destroyed return write failed - return false; - } - - /** - * Return id of connection as a string - * @method - * @return {string} - */ - toString() { - return '' + this.id; - } - - /** - * Return json object of connection - * @method - * @return {object} - */ - toJSON() { - return { id: this.id, host: this.host, port: this.port }; - } - - /** - * Is the connection connected - * @method - * @return {boolean} - */ - isConnected() { - if (this.destroyed) return false; - return !this.socket.destroyed && this.socket.writable; - } -} - -function deleteConnection(id) { - // console.log("=== deleted connection " + id + " :: " + (connections[id] ? connections[id].port : '')) - delete connections[id]; - - if (connectionAccountingSpy) { - connectionAccountingSpy.deleteConnection(id); - } -} - -function addConnection(id, connection) { - // console.log("=== added connection " + id + " :: " + connection.port) - connections[id] = connection; - - if (connectionAccountingSpy) { - connectionAccountingSpy.addConnection(id, connection); - } -} - -// -// Connection handlers -function errorHandler(conn) { - return function(err) { - if (connectionAccounting) deleteConnection(conn.id); - // Debug information - if (conn.logger.isDebug()) { - conn.logger.debug( - `connection ${conn.id} for [${conn.address}] errored out with [${JSON.stringify(err)}]` - ); - } - - conn.emit('error', new MongoNetworkError(err), conn); - }; -} - -function timeoutHandler(conn) { - return function() { - if (connectionAccounting) deleteConnection(conn.id); - - if (conn.logger.isDebug()) { - conn.logger.debug(`connection ${conn.id} for [${conn.address}] timed out`); - } - - conn.emit( - 'timeout', - new MongoNetworkError(`connection ${conn.id} to ${conn.address} timed out`), - conn - ); - }; -} - -function closeHandler(conn) { - return function(hadError) { - if (connectionAccounting) deleteConnection(conn.id); - - if (conn.logger.isDebug()) { - conn.logger.debug(`connection ${conn.id} with for [${conn.address}] closed`); - } - - if (!hadError) { - conn.emit( - 'close', - new MongoNetworkError(`connection ${conn.id} to ${conn.address} closed`), - conn - ); - } - }; -} - -// Handle a message once it is received -function processMessage(conn, message) { - const msgHeader = parseHeader(message); - if (msgHeader.opCode !== OP_COMPRESSED) { - const ResponseConstructor = msgHeader.opCode === OP_MSG ? BinMsg : Response; - conn.emit( - 'message', - new ResponseConstructor( - conn.bson, - message, - msgHeader, - message.slice(MESSAGE_HEADER_SIZE), - conn.responseOptions - ), - conn - ); - - return; - } - - msgHeader.fromCompressed = true; - let index = MESSAGE_HEADER_SIZE; - msgHeader.opCode = message.readInt32LE(index); - index += 4; - msgHeader.length = message.readInt32LE(index); - index += 4; - const compressorID = message[index]; - index++; - - decompress(compressorID, message.slice(index), (err, decompressedMsgBody) => { - if (err) { - conn.emit('error', err); - return; - } - - if (decompressedMsgBody.length !== msgHeader.length) { - conn.emit( - 'error', - new MongoError( - 'Decompressing a compressed message from the server failed. The message is corrupt.' - ) - ); - - return; - } - - const ResponseConstructor = msgHeader.opCode === OP_MSG ? BinMsg : Response; - conn.emit( - 'message', - new ResponseConstructor( - conn.bson, - message, - msgHeader, - decompressedMsgBody, - conn.responseOptions - ), - conn - ); - }); -} - -function dataHandler(conn) { - return function(data) { - // Parse until we are done with the data - while (data.length > 0) { - // If we still have bytes to read on the current message - if (conn.bytesRead > 0 && conn.sizeOfMessage > 0) { - // Calculate the amount of remaining bytes - const remainingBytesToRead = conn.sizeOfMessage - conn.bytesRead; - // Check if the current chunk contains the rest of the message - if (remainingBytesToRead > data.length) { - // Copy the new data into the exiting buffer (should have been allocated when we know the message size) - data.copy(conn.buffer, conn.bytesRead); - // Adjust the number of bytes read so it point to the correct index in the buffer - conn.bytesRead = conn.bytesRead + data.length; - - // Reset state of buffer - data = Buffer.alloc(0); - } else { - // Copy the missing part of the data into our current buffer - data.copy(conn.buffer, conn.bytesRead, 0, remainingBytesToRead); - // Slice the overflow into a new buffer that we will then re-parse - data = data.slice(remainingBytesToRead); - - // Emit current complete message - const emitBuffer = conn.buffer; - // Reset state of buffer - conn.buffer = null; - conn.sizeOfMessage = 0; - conn.bytesRead = 0; - conn.stubBuffer = null; - - processMessage(conn, emitBuffer); - } - } else { - // Stub buffer is kept in case we don't get enough bytes to determine the - // size of the message (< 4 bytes) - if (conn.stubBuffer != null && conn.stubBuffer.length > 0) { - // If we have enough bytes to determine the message size let's do it - if (conn.stubBuffer.length + data.length > 4) { - // Prepad the data - const newData = Buffer.alloc(conn.stubBuffer.length + data.length); - conn.stubBuffer.copy(newData, 0); - data.copy(newData, conn.stubBuffer.length); - // Reassign for parsing - data = newData; - - // Reset state of buffer - conn.buffer = null; - conn.sizeOfMessage = 0; - conn.bytesRead = 0; - conn.stubBuffer = null; - } else { - // Add the the bytes to the stub buffer - const newStubBuffer = Buffer.alloc(conn.stubBuffer.length + data.length); - // Copy existing stub buffer - conn.stubBuffer.copy(newStubBuffer, 0); - // Copy missing part of the data - data.copy(newStubBuffer, conn.stubBuffer.length); - // Exit parsing loop - data = Buffer.alloc(0); - } - } else { - if (data.length > 4) { - // Retrieve the message size - const sizeOfMessage = data[0] | (data[1] << 8) | (data[2] << 16) | (data[3] << 24); - // If we have a negative sizeOfMessage emit error and return - if (sizeOfMessage < 0 || sizeOfMessage > conn.maxBsonMessageSize) { - const errorObject = { - err: 'socketHandler', - trace: '', - bin: conn.buffer, - parseState: { - sizeOfMessage: sizeOfMessage, - bytesRead: conn.bytesRead, - stubBuffer: conn.stubBuffer - } - }; - // We got a parse Error fire it off then keep going - conn.emit('parseError', errorObject, conn); - return; - } - - // Ensure that the size of message is larger than 0 and less than the max allowed - if ( - sizeOfMessage > 4 && - sizeOfMessage < conn.maxBsonMessageSize && - sizeOfMessage > data.length - ) { - conn.buffer = Buffer.alloc(sizeOfMessage); - // Copy all the data into the buffer - data.copy(conn.buffer, 0); - // Update bytes read - conn.bytesRead = data.length; - // Update sizeOfMessage - conn.sizeOfMessage = sizeOfMessage; - // Ensure stub buffer is null - conn.stubBuffer = null; - // Exit parsing loop - data = Buffer.alloc(0); - } else if ( - sizeOfMessage > 4 && - sizeOfMessage < conn.maxBsonMessageSize && - sizeOfMessage === data.length - ) { - const emitBuffer = data; - // Reset state of buffer - conn.buffer = null; - conn.sizeOfMessage = 0; - conn.bytesRead = 0; - conn.stubBuffer = null; - // Exit parsing loop - data = Buffer.alloc(0); - // Emit the message - processMessage(conn, emitBuffer); - } else if (sizeOfMessage <= 4 || sizeOfMessage > conn.maxBsonMessageSize) { - const errorObject = { - err: 'socketHandler', - trace: null, - bin: data, - parseState: { - sizeOfMessage: sizeOfMessage, - bytesRead: 0, - buffer: null, - stubBuffer: null - } - }; - // We got a parse Error fire it off then keep going - conn.emit('parseError', errorObject, conn); - - // Clear out the state of the parser - conn.buffer = null; - conn.sizeOfMessage = 0; - conn.bytesRead = 0; - conn.stubBuffer = null; - // Exit parsing loop - data = Buffer.alloc(0); - } else { - const emitBuffer = data.slice(0, sizeOfMessage); - // Reset state of buffer - conn.buffer = null; - conn.sizeOfMessage = 0; - conn.bytesRead = 0; - conn.stubBuffer = null; - // Copy rest of message - data = data.slice(sizeOfMessage); - // Emit the message - processMessage(conn, emitBuffer); - } - } else { - // Create a buffer that contains the space for the non-complete message - conn.stubBuffer = Buffer.alloc(data.length); - // Copy the data to the stub buffer - data.copy(conn.stubBuffer, 0); - // Exit parsing loop - data = Buffer.alloc(0); - } - } - } - } - }; -} - -/** - * A server connect event, used to verify that the connection is up and running - * - * @event Connection#connect - * @type {Connection} - */ - -/** - * The server connection closed, all pool connections closed - * - * @event Connection#close - * @type {Connection} - */ - -/** - * The server connection caused an error, all pool connections closed - * - * @event Connection#error - * @type {Connection} - */ - -/** - * The server connection timed out, all pool connections closed - * - * @event Connection#timeout - * @type {Connection} - */ - -/** - * The driver experienced an invalid message, all pool connections closed - * - * @event Connection#parseError - * @type {Connection} - */ - -/** - * An event emitted each time the connection receives a parsed message from the wire - * - * @event Connection#message - * @type {Connection} - */ - -module.exports = Connection; diff --git a/scripts/node_modules/mongodb/lib/core/connection/logger.js b/scripts/node_modules/mongodb/lib/core/connection/logger.js deleted file mode 100644 index eb11e43d..00000000 --- a/scripts/node_modules/mongodb/lib/core/connection/logger.js +++ /dev/null @@ -1,246 +0,0 @@ -'use strict'; - -var f = require('util').format, - MongoError = require('../error').MongoError; - -// Filters for classes -var classFilters = {}; -var filteredClasses = {}; -var level = null; -// Save the process id -var pid = process.pid; -// current logger -var currentLogger = null; - -/** - * Creates a new Logger instance - * @class - * @param {string} className The Class name associated with the logging instance - * @param {object} [options=null] Optional settings. - * @param {Function} [options.logger=null] Custom logger function; - * @param {string} [options.loggerLevel=error] Override default global log level. - * @return {Logger} a Logger instance. - */ -var Logger = function(className, options) { - if (!(this instanceof Logger)) return new Logger(className, options); - options = options || {}; - - // Current reference - this.className = className; - - // Current logger - if (options.logger) { - currentLogger = options.logger; - } else if (currentLogger == null) { - currentLogger = console.log; - } - - // Set level of logging, default is error - if (options.loggerLevel) { - level = options.loggerLevel || 'error'; - } - - // Add all class names - if (filteredClasses[this.className] == null) classFilters[this.className] = true; -}; - -/** - * Log a message at the debug level - * @method - * @param {string} message The message to log - * @param {object} object additional meta data to log - * @return {null} - */ -Logger.prototype.debug = function(message, object) { - if ( - this.isDebug() && - ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) || - (Object.keys(filteredClasses).length === 0 && classFilters[this.className])) - ) { - var dateTime = new Date().getTime(); - var msg = f('[%s-%s:%s] %s %s', 'DEBUG', this.className, pid, dateTime, message); - var state = { - type: 'debug', - message: message, - className: this.className, - pid: pid, - date: dateTime - }; - if (object) state.meta = object; - currentLogger(msg, state); - } -}; - -/** - * Log a message at the warn level - * @method - * @param {string} message The message to log - * @param {object} object additional meta data to log - * @return {null} - */ -(Logger.prototype.warn = function(message, object) { - if ( - this.isWarn() && - ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) || - (Object.keys(filteredClasses).length === 0 && classFilters[this.className])) - ) { - var dateTime = new Date().getTime(); - var msg = f('[%s-%s:%s] %s %s', 'WARN', this.className, pid, dateTime, message); - var state = { - type: 'warn', - message: message, - className: this.className, - pid: pid, - date: dateTime - }; - if (object) state.meta = object; - currentLogger(msg, state); - } -}), - /** - * Log a message at the info level - * @method - * @param {string} message The message to log - * @param {object} object additional meta data to log - * @return {null} - */ - (Logger.prototype.info = function(message, object) { - if ( - this.isInfo() && - ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) || - (Object.keys(filteredClasses).length === 0 && classFilters[this.className])) - ) { - var dateTime = new Date().getTime(); - var msg = f('[%s-%s:%s] %s %s', 'INFO', this.className, pid, dateTime, message); - var state = { - type: 'info', - message: message, - className: this.className, - pid: pid, - date: dateTime - }; - if (object) state.meta = object; - currentLogger(msg, state); - } - }), - /** - * Log a message at the error level - * @method - * @param {string} message The message to log - * @param {object} object additional meta data to log - * @return {null} - */ - (Logger.prototype.error = function(message, object) { - if ( - this.isError() && - ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) || - (Object.keys(filteredClasses).length === 0 && classFilters[this.className])) - ) { - var dateTime = new Date().getTime(); - var msg = f('[%s-%s:%s] %s %s', 'ERROR', this.className, pid, dateTime, message); - var state = { - type: 'error', - message: message, - className: this.className, - pid: pid, - date: dateTime - }; - if (object) state.meta = object; - currentLogger(msg, state); - } - }), - /** - * Is the logger set at info level - * @method - * @return {boolean} - */ - (Logger.prototype.isInfo = function() { - return level === 'info' || level === 'debug'; - }), - /** - * Is the logger set at error level - * @method - * @return {boolean} - */ - (Logger.prototype.isError = function() { - return level === 'error' || level === 'info' || level === 'debug'; - }), - /** - * Is the logger set at error level - * @method - * @return {boolean} - */ - (Logger.prototype.isWarn = function() { - return level === 'error' || level === 'warn' || level === 'info' || level === 'debug'; - }), - /** - * Is the logger set at debug level - * @method - * @return {boolean} - */ - (Logger.prototype.isDebug = function() { - return level === 'debug'; - }); - -/** - * Resets the logger to default settings, error and no filtered classes - * @method - * @return {null} - */ -Logger.reset = function() { - level = 'error'; - filteredClasses = {}; -}; - -/** - * Get the current logger function - * @method - * @return {function} - */ -Logger.currentLogger = function() { - return currentLogger; -}; - -/** - * Set the current logger function - * @method - * @param {function} logger Logger function. - * @return {null} - */ -Logger.setCurrentLogger = function(logger) { - if (typeof logger !== 'function') throw new MongoError('current logger must be a function'); - currentLogger = logger; -}; - -/** - * Set what classes to log. - * @method - * @param {string} type The type of filter (currently only class) - * @param {string[]} values The filters to apply - * @return {null} - */ -Logger.filter = function(type, values) { - if (type === 'class' && Array.isArray(values)) { - filteredClasses = {}; - - values.forEach(function(x) { - filteredClasses[x] = true; - }); - } -}; - -/** - * Set the current log level - * @method - * @param {string} level Set current log level (debug, info, error) - * @return {null} - */ -Logger.setLevel = function(_level) { - if (_level !== 'info' && _level !== 'error' && _level !== 'debug' && _level !== 'warn') { - throw new Error(f('%s is an illegal logging level', _level)); - } - - level = _level; -}; - -module.exports = Logger; diff --git a/scripts/node_modules/mongodb/lib/core/connection/msg.js b/scripts/node_modules/mongodb/lib/core/connection/msg.js deleted file mode 100644 index 7bee3c5e..00000000 --- a/scripts/node_modules/mongodb/lib/core/connection/msg.js +++ /dev/null @@ -1,221 +0,0 @@ -'use strict'; - -// Implementation of OP_MSG spec: -// https://github.com/mongodb/specifications/blob/master/source/message/OP_MSG.rst -// -// struct Section { -// uint8 payloadType; -// union payload { -// document document; // payloadType == 0 -// struct sequence { // payloadType == 1 -// int32 size; -// cstring identifier; -// document* documents; -// }; -// }; -// }; - -// struct OP_MSG { -// struct MsgHeader { -// int32 messageLength; -// int32 requestID; -// int32 responseTo; -// int32 opCode = 2013; -// }; -// uint32 flagBits; -// Section+ sections; -// [uint32 checksum;] -// }; - -const Buffer = require('safe-buffer').Buffer; -const opcodes = require('../wireprotocol/shared').opcodes; -const databaseNamespace = require('../wireprotocol/shared').databaseNamespace; -const ReadPreference = require('../topologies/read_preference'); - -// Incrementing request id -let _requestId = 0; - -// Msg Flags -const OPTS_CHECKSUM_PRESENT = 1; -const OPTS_MORE_TO_COME = 2; -const OPTS_EXHAUST_ALLOWED = 1 << 16; - -class Msg { - constructor(bson, ns, command, options) { - // Basic options needed to be passed in - if (command == null) throw new Error('query must be specified for query'); - - // Basic options - this.bson = bson; - this.ns = ns; - this.command = command; - this.command.$db = databaseNamespace(ns); - - if (options.readPreference && options.readPreference.mode !== ReadPreference.PRIMARY) { - this.command.$readPreference = options.readPreference.toJSON(); - } - - // Ensure empty options - this.options = options || {}; - - // Additional options - this.requestId = Msg.getRequestId(); - - // Serialization option - this.serializeFunctions = - typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; - this.ignoreUndefined = - typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : false; - this.checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; - this.maxBsonSize = options.maxBsonSize || 1024 * 1024 * 16; - - // flags - this.checksumPresent = false; - this.moreToCome = options.moreToCome || false; - this.exhaustAllowed = false; - } - - toBin() { - const buffers = []; - let flags = 0; - - if (this.checksumPresent) { - flags |= OPTS_CHECKSUM_PRESENT; - } - - if (this.moreToCome) { - flags |= OPTS_MORE_TO_COME; - } - - if (this.exhaustAllowed) { - flags |= OPTS_EXHAUST_ALLOWED; - } - - const header = Buffer.alloc( - 4 * 4 + // Header - 4 // Flags - ); - - buffers.push(header); - - let totalLength = header.length; - const command = this.command; - totalLength += this.makeDocumentSegment(buffers, command); - - header.writeInt32LE(totalLength, 0); // messageLength - header.writeInt32LE(this.requestId, 4); // requestID - header.writeInt32LE(0, 8); // responseTo - header.writeInt32LE(opcodes.OP_MSG, 12); // opCode - header.writeUInt32LE(flags, 16); // flags - return buffers; - } - - makeDocumentSegment(buffers, document) { - const payloadTypeBuffer = Buffer.alloc(1); - payloadTypeBuffer[0] = 0; - - const documentBuffer = this.serializeBson(document); - buffers.push(payloadTypeBuffer); - buffers.push(documentBuffer); - - return payloadTypeBuffer.length + documentBuffer.length; - } - - serializeBson(document) { - return this.bson.serialize(document, { - checkKeys: this.checkKeys, - serializeFunctions: this.serializeFunctions, - ignoreUndefined: this.ignoreUndefined - }); - } -} - -Msg.getRequestId = function() { - _requestId = (_requestId + 1) & 0x7fffffff; - return _requestId; -}; - -class BinMsg { - constructor(bson, message, msgHeader, msgBody, opts) { - opts = opts || { promoteLongs: true, promoteValues: true, promoteBuffers: false }; - this.parsed = false; - this.raw = message; - this.data = msgBody; - this.bson = bson; - this.opts = opts; - - // Read the message header - this.length = msgHeader.length; - this.requestId = msgHeader.requestId; - this.responseTo = msgHeader.responseTo; - this.opCode = msgHeader.opCode; - this.fromCompressed = msgHeader.fromCompressed; - - // Read response flags - this.responseFlags = msgBody.readInt32LE(0); - this.checksumPresent = (this.responseFlags & OPTS_CHECKSUM_PRESENT) !== 0; - this.moreToCome = (this.responseFlags & OPTS_MORE_TO_COME) !== 0; - this.exhaustAllowed = (this.responseFlags & OPTS_EXHAUST_ALLOWED) !== 0; - this.promoteLongs = typeof opts.promoteLongs === 'boolean' ? opts.promoteLongs : true; - this.promoteValues = typeof opts.promoteValues === 'boolean' ? opts.promoteValues : true; - this.promoteBuffers = typeof opts.promoteBuffers === 'boolean' ? opts.promoteBuffers : false; - - this.documents = []; - } - - isParsed() { - return this.parsed; - } - - parse(options) { - // Don't parse again if not needed - if (this.parsed) return; - options = options || {}; - - this.index = 4; - // Allow the return of raw documents instead of parsing - const raw = options.raw || false; - const documentsReturnedIn = options.documentsReturnedIn || null; - const promoteLongs = - typeof options.promoteLongs === 'boolean' ? options.promoteLongs : this.opts.promoteLongs; - const promoteValues = - typeof options.promoteValues === 'boolean' ? options.promoteValues : this.opts.promoteValues; - const promoteBuffers = - typeof options.promoteBuffers === 'boolean' - ? options.promoteBuffers - : this.opts.promoteBuffers; - - // Set up the options - const _options = { - promoteLongs: promoteLongs, - promoteValues: promoteValues, - promoteBuffers: promoteBuffers - }; - - while (this.index < this.data.length) { - const payloadType = this.data.readUInt8(this.index++); - if (payloadType === 1) { - console.error('TYPE 1'); - } else if (payloadType === 0) { - const bsonSize = this.data.readUInt32LE(this.index); - const bin = this.data.slice(this.index, this.index + bsonSize); - this.documents.push(raw ? bin : this.bson.deserialize(bin, _options)); - - this.index += bsonSize; - } - } - - if (this.documents.length === 1 && documentsReturnedIn != null && raw) { - const fieldsAsRaw = {}; - fieldsAsRaw[documentsReturnedIn] = true; - _options.fieldsAsRaw = fieldsAsRaw; - - const doc = this.bson.deserialize(this.documents[0], _options); - this.documents = [doc]; - } - - this.parsed = true; - } -} - -module.exports = { Msg, BinMsg }; diff --git a/scripts/node_modules/mongodb/lib/core/connection/pool.js b/scripts/node_modules/mongodb/lib/core/connection/pool.js deleted file mode 100644 index adc85900..00000000 --- a/scripts/node_modules/mongodb/lib/core/connection/pool.js +++ /dev/null @@ -1,1256 +0,0 @@ -'use strict'; - -const inherits = require('util').inherits; -const EventEmitter = require('events').EventEmitter; -const MongoError = require('../error').MongoError; -const MongoTimeoutError = require('../error').MongoTimeoutError; -const MongoWriteConcernError = require('../error').MongoWriteConcernError; -const Logger = require('./logger'); -const f = require('util').format; -const Msg = require('./msg').Msg; -const CommandResult = require('./command_result'); -const MESSAGE_HEADER_SIZE = require('../wireprotocol/shared').MESSAGE_HEADER_SIZE; -const COMPRESSION_DETAILS_SIZE = require('../wireprotocol/shared').COMPRESSION_DETAILS_SIZE; -const opcodes = require('../wireprotocol/shared').opcodes; -const compress = require('../wireprotocol/compression').compress; -const compressorIDs = require('../wireprotocol/compression').compressorIDs; -const uncompressibleCommands = require('../wireprotocol/compression').uncompressibleCommands; -const apm = require('./apm'); -const Buffer = require('safe-buffer').Buffer; -const connect = require('./connect'); -const updateSessionFromResponse = require('../sessions').updateSessionFromResponse; -const eachAsync = require('../utils').eachAsync; - -var DISCONNECTED = 'disconnected'; -var CONNECTING = 'connecting'; -var CONNECTED = 'connected'; -var DESTROYING = 'destroying'; -var DESTROYED = 'destroyed'; - -const CONNECTION_EVENTS = new Set([ - 'error', - 'close', - 'timeout', - 'parseError', - 'connect', - 'message' -]); - -var _id = 0; - -/** - * Creates a new Pool instance - * @class - * @param {string} options.host The server host - * @param {number} options.port The server port - * @param {number} [options.size=5] Max server connection pool size - * @param {number} [options.minSize=0] Minimum server connection pool size - * @param {boolean} [options.reconnect=true] Server will attempt to reconnect on loss of connection - * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times - * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries - * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled - * @param {number} [options.keepAliveInitialDelay=300000] Initial delay before TCP keep alive enabled - * @param {boolean} [options.noDelay=true] TCP Connection no delay - * @param {number} [options.connectionTimeout=30000] TCP Connection timeout setting - * @param {number} [options.socketTimeout=360000] TCP Socket timeout setting - * @param {number} [options.monitoringSocketTimeout=30000] TCP Socket timeout setting for replicaset monitoring socket - * @param {boolean} [options.ssl=false] Use SSL for connection - * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. - * @param {Buffer} [options.ca] SSL Certificate store binary buffer - * @param {Buffer} [options.crl] SSL Certificate revocation store binary buffer - * @param {Buffer} [options.cert] SSL Certificate binary buffer - * @param {Buffer} [options.key] SSL Key file binary buffer - * @param {string} [options.passphrase] SSL Certificate pass phrase - * @param {boolean} [options.rejectUnauthorized=false] Reject unauthorized server certificates - * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits - * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. - * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. - * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. - * @fires Pool#connect - * @fires Pool#close - * @fires Pool#error - * @fires Pool#timeout - * @fires Pool#parseError - * @return {Pool} A cursor instance - */ -var Pool = function(topology, options) { - // Add event listener - EventEmitter.call(this); - - // Store topology for later use - this.topology = topology; - - // Add the options - this.options = Object.assign( - { - // Host and port settings - host: 'localhost', - port: 27017, - // Pool default max size - size: 5, - // Pool default min size - minSize: 0, - // socket settings - connectionTimeout: 30000, - socketTimeout: 360000, - keepAlive: true, - keepAliveInitialDelay: 300000, - noDelay: true, - // SSL Settings - ssl: false, - checkServerIdentity: true, - ca: null, - crl: null, - cert: null, - key: null, - passphrase: null, - rejectUnauthorized: false, - promoteLongs: true, - promoteValues: true, - promoteBuffers: false, - // Reconnection options - reconnect: true, - reconnectInterval: 1000, - reconnectTries: 30, - // Enable domains - domainsEnabled: false, - // feature flag for determining if we are running with the unified topology or not - legacyCompatMode: true - }, - options - ); - - // Identification information - this.id = _id++; - // Current reconnect retries - this.retriesLeft = this.options.reconnectTries; - this.reconnectId = null; - this.reconnectError = null; - // No bson parser passed in - if ( - !options.bson || - (options.bson && - (typeof options.bson.serialize !== 'function' || - typeof options.bson.deserialize !== 'function')) - ) { - throw new Error('must pass in valid bson parser'); - } - - // Logger instance - this.logger = Logger('Pool', options); - // Pool state - this.state = DISCONNECTED; - // Connections - this.availableConnections = []; - this.inUseConnections = []; - this.connectingConnections = 0; - // Currently executing - this.executing = false; - // Operation work queue - this.queue = []; - - // Number of consecutive timeouts caught - this.numberOfConsecutiveTimeouts = 0; - // Current pool Index - this.connectionIndex = 0; - - // event handlers - const pool = this; - this._messageHandler = messageHandler(this); - this._connectionCloseHandler = function(err) { - const connection = this; - connectionFailureHandler(pool, 'close', err, connection); - }; - - this._connectionErrorHandler = function(err) { - const connection = this; - connectionFailureHandler(pool, 'error', err, connection); - }; - - this._connectionTimeoutHandler = function(err) { - const connection = this; - connectionFailureHandler(pool, 'timeout', err, connection); - }; - - this._connectionParseErrorHandler = function(err) { - const connection = this; - connectionFailureHandler(pool, 'parseError', err, connection); - }; -}; - -inherits(Pool, EventEmitter); - -Object.defineProperty(Pool.prototype, 'size', { - enumerable: true, - get: function() { - return this.options.size; - } -}); - -Object.defineProperty(Pool.prototype, 'minSize', { - enumerable: true, - get: function() { - return this.options.minSize; - } -}); - -Object.defineProperty(Pool.prototype, 'connectionTimeout', { - enumerable: true, - get: function() { - return this.options.connectionTimeout; - } -}); - -Object.defineProperty(Pool.prototype, 'socketTimeout', { - enumerable: true, - get: function() { - return this.options.socketTimeout; - } -}); - -// clears all pool state -function resetPoolState(pool) { - pool.inUseConnections = []; - pool.availableConnections = []; - pool.connectingConnections = 0; - pool.executing = false; - pool.numberOfConsecutiveTimeouts = 0; - pool.connectionIndex = 0; - pool.retriesLeft = pool.options.reconnectTries; - pool.reconnectId = null; -} - -function stateTransition(self, newState) { - var legalTransitions = { - disconnected: [CONNECTING, DESTROYING, DISCONNECTED], - connecting: [CONNECTING, DESTROYING, CONNECTED, DISCONNECTED], - connected: [CONNECTED, DISCONNECTED, DESTROYING], - destroying: [DESTROYING, DESTROYED], - destroyed: [DESTROYED] - }; - - // Get current state - var legalStates = legalTransitions[self.state]; - if (legalStates && legalStates.indexOf(newState) !== -1) { - self.emit('stateChanged', self.state, newState); - self.state = newState; - } else { - self.logger.error( - f( - 'Pool with id [%s] failed attempted illegal state transition from [%s] to [%s] only following state allowed [%s]', - self.id, - self.state, - newState, - legalStates - ) - ); - } -} - -function connectionFailureHandler(pool, event, err, conn) { - if (conn) { - if (conn._connectionFailHandled) return; - conn._connectionFailHandled = true; - conn.destroy(); - - // Remove the connection - removeConnection(pool, conn); - - // Flush all work Items on this connection - while (conn.workItems.length > 0) { - const workItem = conn.workItems.shift(); - if (workItem.cb) workItem.cb(err); - } - } - - // Did we catch a timeout, increment the numberOfConsecutiveTimeouts - if (event === 'timeout') { - pool.numberOfConsecutiveTimeouts = pool.numberOfConsecutiveTimeouts + 1; - - // Have we timed out more than reconnectTries in a row ? - // Force close the pool as we are trying to connect to tcp sink hole - if (pool.numberOfConsecutiveTimeouts > pool.options.reconnectTries) { - pool.numberOfConsecutiveTimeouts = 0; - // Destroy all connections and pool - pool.destroy(true); - // Emit close event - return pool.emit('close', pool); - } - } - - // No more socket available propegate the event - if (pool.socketCount() === 0) { - if (pool.state !== DESTROYED && pool.state !== DESTROYING) { - stateTransition(pool, DISCONNECTED); - } - - // Do not emit error events, they are always close events - // do not trigger the low level error handler in node - event = event === 'error' ? 'close' : event; - pool.emit(event, err); - } - - // Start reconnection attempts - if (!pool.reconnectId && pool.options.reconnect) { - pool.reconnectError = err; - pool.reconnectId = setTimeout(attemptReconnect(pool), pool.options.reconnectInterval); - } - - // Do we need to do anything to maintain the minimum pool size - const totalConnections = totalConnectionCount(pool); - if (totalConnections < pool.minSize) { - createConnection(pool); - } -} - -function attemptReconnect(pool, callback) { - return function() { - pool.emit('attemptReconnect', pool); - - if (pool.state === DESTROYED || pool.state === DESTROYING) { - if (typeof callback === 'function') { - callback(new MongoError('Cannot create connection when pool is destroyed')); - } - - return; - } - - pool.retriesLeft = pool.retriesLeft - 1; - if (pool.retriesLeft <= 0) { - pool.destroy(); - - const error = new MongoTimeoutError( - `failed to reconnect after ${pool.options.reconnectTries} attempts with interval ${ - pool.options.reconnectInterval - } ms`, - pool.reconnectError - ); - - pool.emit('reconnectFailed', error); - if (typeof callback === 'function') { - callback(error); - } - - return; - } - - // clear the reconnect id on retry - pool.reconnectId = null; - - // now retry creating a connection - createConnection(pool, (err, conn) => { - if (err == null) { - pool.reconnectId = null; - pool.retriesLeft = pool.options.reconnectTries; - pool.emit('reconnect', pool); - } - - if (typeof callback === 'function') { - callback(err, conn); - } - }); - }; -} - -function moveConnectionBetween(connection, from, to) { - var index = from.indexOf(connection); - // Move the connection from connecting to available - if (index !== -1) { - from.splice(index, 1); - to.push(connection); - } -} - -function messageHandler(self) { - return function(message, connection) { - // workItem to execute - var workItem = null; - - // Locate the workItem - for (var i = 0; i < connection.workItems.length; i++) { - if (connection.workItems[i].requestId === message.responseTo) { - // Get the callback - workItem = connection.workItems[i]; - // Remove from list of workItems - connection.workItems.splice(i, 1); - } - } - - if (workItem && workItem.monitoring) { - moveConnectionBetween(connection, self.inUseConnections, self.availableConnections); - } - - // Reset timeout counter - self.numberOfConsecutiveTimeouts = 0; - - // Reset the connection timeout if we modified it for - // this operation - if (workItem && workItem.socketTimeout) { - connection.resetSocketTimeout(); - } - - // Log if debug enabled - if (self.logger.isDebug()) { - self.logger.debug( - f( - 'message [%s] received from %s:%s', - message.raw.toString('hex'), - self.options.host, - self.options.port - ) - ); - } - - function handleOperationCallback(self, cb, err, result) { - // No domain enabled - if (!self.options.domainsEnabled) { - return process.nextTick(function() { - return cb(err, result); - }); - } - - // Domain enabled just call the callback - cb(err, result); - } - - // Keep executing, ensure current message handler does not stop execution - if (!self.executing) { - process.nextTick(function() { - _execute(self)(); - }); - } - - // Time to dispatch the message if we have a callback - if (workItem && !workItem.immediateRelease) { - try { - // Parse the message according to the provided options - message.parse(workItem); - } catch (err) { - return handleOperationCallback(self, workItem.cb, new MongoError(err)); - } - - if (message.documents[0]) { - const document = message.documents[0]; - const session = workItem.session; - if (session) { - updateSessionFromResponse(session, document); - } - - if (document.$clusterTime) { - self.topology.clusterTime = document.$clusterTime; - } - } - - // Establish if we have an error - if (workItem.command && message.documents[0]) { - const responseDoc = message.documents[0]; - - if (responseDoc.writeConcernError) { - const err = new MongoWriteConcernError(responseDoc.writeConcernError, responseDoc); - return handleOperationCallback(self, workItem.cb, err); - } - - if (responseDoc.ok === 0 || responseDoc.$err || responseDoc.errmsg || responseDoc.code) { - return handleOperationCallback(self, workItem.cb, new MongoError(responseDoc)); - } - } - - // Add the connection details - message.hashedName = connection.hashedName; - - // Return the documents - handleOperationCallback( - self, - workItem.cb, - null, - new CommandResult(workItem.fullResult ? message : message.documents[0], connection, message) - ); - } - }; -} - -/** - * Return the total socket count in the pool. - * @method - * @return {Number} The number of socket available. - */ -Pool.prototype.socketCount = function() { - return this.availableConnections.length + this.inUseConnections.length; - // + this.connectingConnections.length; -}; - -function totalConnectionCount(pool) { - return ( - pool.availableConnections.length + pool.inUseConnections.length + pool.connectingConnections - ); -} - -/** - * Return all pool connections - * @method - * @return {Connection[]} The pool connections - */ -Pool.prototype.allConnections = function() { - return this.availableConnections.concat(this.inUseConnections); -}; - -/** - * Get a pool connection (round-robin) - * @method - * @return {Connection} - */ -Pool.prototype.get = function() { - return this.allConnections()[0]; -}; - -/** - * Is the pool connected - * @method - * @return {boolean} - */ -Pool.prototype.isConnected = function() { - // We are in a destroyed state - if (this.state === DESTROYED || this.state === DESTROYING) { - return false; - } - - // Get connections - var connections = this.availableConnections.concat(this.inUseConnections); - - // Check if we have any connected connections - for (var i = 0; i < connections.length; i++) { - if (connections[i].isConnected()) return true; - } - - // Not connected - return false; -}; - -/** - * Was the pool destroyed - * @method - * @return {boolean} - */ -Pool.prototype.isDestroyed = function() { - return this.state === DESTROYED || this.state === DESTROYING; -}; - -/** - * Is the pool in a disconnected state - * @method - * @return {boolean} - */ -Pool.prototype.isDisconnected = function() { - return this.state === DISCONNECTED; -}; - -/** - * Connect pool - */ -Pool.prototype.connect = function() { - if (this.state !== DISCONNECTED) { - throw new MongoError('connection in unlawful state ' + this.state); - } - - stateTransition(this, CONNECTING); - createConnection(this, (err, conn) => { - if (err) { - if (this.state === CONNECTING) { - this.emit('error', err); - } - - this.destroy(); - return; - } - - stateTransition(this, CONNECTED); - this.emit('connect', this, conn); - - // create min connections - if (this.minSize) { - for (let i = 0; i < this.minSize; i++) { - createConnection(this); - } - } - }); -}; - -/** - * Authenticate using a specified mechanism - * @param {authResultCallback} callback A callback function - */ -Pool.prototype.auth = function(credentials, callback) { - if (typeof callback === 'function') callback(null, null); -}; - -/** - * Logout all users against a database - * @param {authResultCallback} callback A callback function - */ -Pool.prototype.logout = function(dbName, callback) { - if (typeof callback === 'function') callback(null, null); -}; - -/** - * Unref the pool - * @method - */ -Pool.prototype.unref = function() { - // Get all the known connections - var connections = this.availableConnections.concat(this.inUseConnections); - - connections.forEach(function(c) { - c.unref(); - }); -}; - -// Destroy the connections -function destroy(self, connections, options, callback) { - eachAsync( - connections, - (conn, cb) => { - for (const eventName of CONNECTION_EVENTS) { - conn.removeAllListeners(eventName); - } - - conn.destroy(options, cb); - }, - err => { - if (err) { - if (typeof callback === 'function') callback(err, null); - return; - } - - resetPoolState(self); - self.queue = []; - - stateTransition(self, DESTROYED); - if (typeof callback === 'function') callback(null, null); - } - ); -} - -/** - * Destroy pool - * @method - */ -Pool.prototype.destroy = function(force, callback) { - var self = this; - // Do not try again if the pool is already dead - if (this.state === DESTROYED || self.state === DESTROYING) { - if (typeof callback === 'function') callback(null, null); - return; - } - - // Set state to destroyed - stateTransition(this, DESTROYING); - - // Are we force closing - if (force) { - // Get all the known connections - var connections = self.availableConnections.concat(self.inUseConnections); - - // Flush any remaining work items with - // an error - while (self.queue.length > 0) { - var workItem = self.queue.shift(); - if (typeof workItem.cb === 'function') { - workItem.cb(new MongoError('Pool was force destroyed')); - } - } - - // Destroy the topology - return destroy(self, connections, { force: true }, callback); - } - - // Clear out the reconnect if set - if (this.reconnectId) { - clearTimeout(this.reconnectId); - } - - // Wait for the operations to drain before we close the pool - function checkStatus() { - flushMonitoringOperations(self.queue); - - if (self.queue.length === 0) { - // Get all the known connections - var connections = self.availableConnections.concat(self.inUseConnections); - - // Check if we have any in flight operations - for (var i = 0; i < connections.length; i++) { - // There is an operation still in flight, reschedule a - // check waiting for it to drain - if (connections[i].workItems.length > 0) { - return setTimeout(checkStatus, 1); - } - } - - destroy(self, connections, { force: false }, callback); - // } else if (self.queue.length > 0 && !this.reconnectId) { - } else { - // Ensure we empty the queue - _execute(self)(); - // Set timeout - setTimeout(checkStatus, 1); - } - } - - // Initiate drain of operations - checkStatus(); -}; - -/** - * Reset all connections of this pool - * - * @param {function} [callback] - */ -Pool.prototype.reset = function(callback) { - const connections = this.availableConnections.concat(this.inUseConnections); - eachAsync( - connections, - (conn, cb) => { - for (const eventName of CONNECTION_EVENTS) { - conn.removeAllListeners(eventName); - } - - conn.destroy({ force: true }, cb); - }, - err => { - if (err) { - if (typeof callback === 'function') { - callback(err, null); - return; - } - } - - resetPoolState(this); - - // create an initial connection, and kick off execution again - createConnection(this); - - if (typeof callback === 'function') { - callback(null, null); - } - } - ); -}; - -// Prepare the buffer that Pool.prototype.write() uses to send to the server -function serializeCommand(self, command, callback) { - const originalCommandBuffer = command.toBin(); - - // Check whether we and the server have agreed to use a compressor - const shouldCompress = !!self.options.agreedCompressor; - if (!shouldCompress || !canCompress(command)) { - return callback(null, originalCommandBuffer); - } - - // Transform originalCommandBuffer into OP_COMPRESSED - const concatenatedOriginalCommandBuffer = Buffer.concat(originalCommandBuffer); - const messageToBeCompressed = concatenatedOriginalCommandBuffer.slice(MESSAGE_HEADER_SIZE); - - // Extract information needed for OP_COMPRESSED from the uncompressed message - const originalCommandOpCode = concatenatedOriginalCommandBuffer.readInt32LE(12); - - // Compress the message body - compress(self, messageToBeCompressed, function(err, compressedMessage) { - if (err) return callback(err, null); - - // Create the msgHeader of OP_COMPRESSED - const msgHeader = Buffer.alloc(MESSAGE_HEADER_SIZE); - msgHeader.writeInt32LE( - MESSAGE_HEADER_SIZE + COMPRESSION_DETAILS_SIZE + compressedMessage.length, - 0 - ); // messageLength - msgHeader.writeInt32LE(command.requestId, 4); // requestID - msgHeader.writeInt32LE(0, 8); // responseTo (zero) - msgHeader.writeInt32LE(opcodes.OP_COMPRESSED, 12); // opCode - - // Create the compression details of OP_COMPRESSED - const compressionDetails = Buffer.alloc(COMPRESSION_DETAILS_SIZE); - compressionDetails.writeInt32LE(originalCommandOpCode, 0); // originalOpcode - compressionDetails.writeInt32LE(messageToBeCompressed.length, 4); // Size of the uncompressed compressedMessage, excluding the MsgHeader - compressionDetails.writeUInt8(compressorIDs[self.options.agreedCompressor], 8); // compressorID - - return callback(null, [msgHeader, compressionDetails, compressedMessage]); - }); -} - -/** - * Write a message to MongoDB - * @method - * @return {Connection} - */ -Pool.prototype.write = function(command, options, cb) { - var self = this; - // Ensure we have a callback - if (typeof options === 'function') { - cb = options; - } - - // Always have options - options = options || {}; - - // We need to have a callback function unless the message returns no response - if (!(typeof cb === 'function') && !options.noResponse) { - throw new MongoError('write method must provide a callback'); - } - - // Pool was destroyed error out - if (this.state === DESTROYED || this.state === DESTROYING) { - // Callback with an error - if (cb) { - try { - cb(new MongoError('pool destroyed')); - } catch (err) { - process.nextTick(function() { - throw err; - }); - } - } - - return; - } - - if (this.options.domainsEnabled && process.domain && typeof cb === 'function') { - // if we have a domain bind to it - var oldCb = cb; - cb = process.domain.bind(function() { - // v8 - argumentsToArray one-liner - var args = new Array(arguments.length); - for (var i = 0; i < arguments.length; i++) { - args[i] = arguments[i]; - } - // bounce off event loop so domain switch takes place - process.nextTick(function() { - oldCb.apply(null, args); - }); - }); - } - - // Do we have an operation - var operation = { - cb: cb, - raw: false, - promoteLongs: true, - promoteValues: true, - promoteBuffers: false, - fullResult: false - }; - - // Set the options for the parsing - operation.promoteLongs = typeof options.promoteLongs === 'boolean' ? options.promoteLongs : true; - operation.promoteValues = - typeof options.promoteValues === 'boolean' ? options.promoteValues : true; - operation.promoteBuffers = - typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : false; - operation.raw = typeof options.raw === 'boolean' ? options.raw : false; - operation.immediateRelease = - typeof options.immediateRelease === 'boolean' ? options.immediateRelease : false; - operation.documentsReturnedIn = options.documentsReturnedIn; - operation.command = typeof options.command === 'boolean' ? options.command : false; - operation.fullResult = typeof options.fullResult === 'boolean' ? options.fullResult : false; - operation.noResponse = typeof options.noResponse === 'boolean' ? options.noResponse : false; - operation.session = options.session || null; - - // Optional per operation socketTimeout - operation.socketTimeout = options.socketTimeout; - operation.monitoring = options.monitoring; - // Custom socket Timeout - if (options.socketTimeout) { - operation.socketTimeout = options.socketTimeout; - } - - // Get the requestId - operation.requestId = command.requestId; - - // If command monitoring is enabled we need to modify the callback here - if (self.options.monitorCommands) { - this.emit('commandStarted', new apm.CommandStartedEvent(this, command)); - - operation.started = process.hrtime(); - operation.cb = (err, reply) => { - if (err) { - self.emit( - 'commandFailed', - new apm.CommandFailedEvent(this, command, err, operation.started) - ); - } else { - if (reply && reply.result && (reply.result.ok === 0 || reply.result.$err)) { - self.emit( - 'commandFailed', - new apm.CommandFailedEvent(this, command, reply.result, operation.started) - ); - } else { - self.emit( - 'commandSucceeded', - new apm.CommandSucceededEvent(this, command, reply, operation.started) - ); - } - } - - if (typeof cb === 'function') cb(err, reply); - }; - } - - // Prepare the operation buffer - serializeCommand(self, command, (err, serializedBuffers) => { - if (err) throw err; - - // Set the operation's buffer to the serialization of the commands - operation.buffer = serializedBuffers; - - // If we have a monitoring operation schedule as the very first operation - // Otherwise add to back of queue - if (options.monitoring) { - self.queue.unshift(operation); - } else { - self.queue.push(operation); - } - - // Attempt to execute the operation - if (!self.executing) { - process.nextTick(function() { - _execute(self)(); - }); - } - }); -}; - -// Return whether a command contains an uncompressible command term -// Will return true if command contains no uncompressible command terms -function canCompress(command) { - const commandDoc = command instanceof Msg ? command.command : command.query; - const commandName = Object.keys(commandDoc)[0]; - return uncompressibleCommands.indexOf(commandName) === -1; -} - -// Remove connection method -function remove(connection, connections) { - for (var i = 0; i < connections.length; i++) { - if (connections[i] === connection) { - connections.splice(i, 1); - return true; - } - } -} - -function removeConnection(self, connection) { - if (remove(connection, self.availableConnections)) return; - if (remove(connection, self.inUseConnections)) return; -} - -function createConnection(pool, callback) { - if (pool.state === DESTROYED || pool.state === DESTROYING) { - if (typeof callback === 'function') { - callback(new MongoError('Cannot create connection when pool is destroyed')); - } - - return; - } - - pool.connectingConnections++; - connect(pool.options, (err, connection) => { - pool.connectingConnections--; - - if (err) { - if (pool.logger.isDebug()) { - pool.logger.debug(`connection attempt failed with error [${JSON.stringify(err)}]`); - } - - if (pool.options.legacyCompatMode === false) { - // The unified topology uses the reported `error` from a pool to track what error - // reason is returned to the user during selection timeout. We only want to emit - // this if the pool is active because the listeners are removed on destruction. - if (pool.state !== DESTROYED && pool.state !== DESTROYING) { - pool.emit('error', err); - } - } - - // check if reconnect is enabled, and attempt retry if so - if (!pool.reconnectId && pool.options.reconnect) { - if (pool.state === CONNECTING && pool.options.legacyCompatMode) { - callback(err); - return; - } - - pool.reconnectError = err; - pool.reconnectId = setTimeout( - attemptReconnect(pool, callback), - pool.options.reconnectInterval - ); - - return; - } - - if (typeof callback === 'function') { - callback(err); - } - - return; - } - - // the pool might have been closed since we started creating the connection - if (pool.state === DESTROYED || pool.state === DESTROYING) { - if (typeof callback === 'function') { - callback(new MongoError('Pool was destroyed after connection creation')); - } - - connection.destroy(); - return; - } - - // otherwise, connect relevant event handlers and add it to our available connections - connection.on('error', pool._connectionErrorHandler); - connection.on('close', pool._connectionCloseHandler); - connection.on('timeout', pool._connectionTimeoutHandler); - connection.on('parseError', pool._connectionParseErrorHandler); - connection.on('message', pool._messageHandler); - - pool.availableConnections.push(connection); - - // if a callback was provided, return the connection - if (typeof callback === 'function') { - callback(null, connection); - } - - // immediately execute any waiting work - _execute(pool)(); - }); -} - -function flushMonitoringOperations(queue) { - for (var i = 0; i < queue.length; i++) { - if (queue[i].monitoring) { - var workItem = queue[i]; - queue.splice(i, 1); - workItem.cb( - new MongoError({ message: 'no connection available for monitoring', driver: true }) - ); - } - } -} - -function _execute(self) { - return function() { - if (self.state === DESTROYED) return; - // Already executing, skip - if (self.executing) return; - // Set pool as executing - self.executing = true; - - // New pool connections are in progress, wait them to finish - // before executing any more operation to ensure distribution of - // operations - if (self.connectingConnections > 0) { - self.executing = false; - return; - } - - // As long as we have available connections - // eslint-disable-next-line - while (true) { - // Total availble connections - const totalConnections = totalConnectionCount(self); - - // No available connections available, flush any monitoring ops - if (self.availableConnections.length === 0) { - // Flush any monitoring operations - flushMonitoringOperations(self.queue); - break; - } - - // No queue break - if (self.queue.length === 0) { - break; - } - - var connection = null; - const connections = self.availableConnections.filter(conn => conn.workItems.length === 0); - - // No connection found that has no work on it, just pick one for pipelining - if (connections.length === 0) { - connection = - self.availableConnections[self.connectionIndex++ % self.availableConnections.length]; - } else { - connection = connections[self.connectionIndex++ % connections.length]; - } - - // Is the connection connected - if (!connection.isConnected()) { - // Remove the disconnected connection - removeConnection(self, connection); - // Flush any monitoring operations in the queue, failing fast - flushMonitoringOperations(self.queue); - break; - } - - // Get the next work item - var workItem = self.queue.shift(); - - // If we are monitoring we need to use a connection that is not - // running another operation to avoid socket timeout changes - // affecting an existing operation - if (workItem.monitoring) { - var foundValidConnection = false; - - for (let i = 0; i < self.availableConnections.length; i++) { - // If the connection is connected - // And there are no pending workItems on it - // Then we can safely use it for monitoring. - if ( - self.availableConnections[i].isConnected() && - self.availableConnections[i].workItems.length === 0 - ) { - foundValidConnection = true; - connection = self.availableConnections[i]; - break; - } - } - - // No safe connection found, attempt to grow the connections - // if possible and break from the loop - if (!foundValidConnection) { - // Put workItem back on the queue - self.queue.unshift(workItem); - - // Attempt to grow the pool if it's not yet maxsize - if (totalConnections < self.options.size && self.queue.length > 0) { - // Create a new connection - createConnection(self); - } - - // Re-execute the operation - setTimeout(function() { - _execute(self)(); - }, 10); - - break; - } - } - - // Don't execute operation until we have a full pool - if (totalConnections < self.options.size) { - // Connection has work items, then put it back on the queue - // and create a new connection - if (connection.workItems.length > 0) { - // Lets put the workItem back on the list - self.queue.unshift(workItem); - // Create a new connection - createConnection(self); - // Break from the loop - break; - } - } - - // Get actual binary commands - var buffer = workItem.buffer; - - // If we are monitoring take the connection of the availableConnections - if (workItem.monitoring) { - moveConnectionBetween(connection, self.availableConnections, self.inUseConnections); - } - - // Track the executing commands on the mongo server - // as long as there is an expected response - if (!workItem.noResponse) { - connection.workItems.push(workItem); - } - - // We have a custom socketTimeout - if (!workItem.immediateRelease && typeof workItem.socketTimeout === 'number') { - connection.setSocketTimeout(workItem.socketTimeout); - } - - // Capture if write was successful - var writeSuccessful = true; - - // Put operation on the wire - if (Array.isArray(buffer)) { - for (let i = 0; i < buffer.length; i++) { - writeSuccessful = connection.write(buffer[i]); - } - } else { - writeSuccessful = connection.write(buffer); - } - - // if the command is designated noResponse, call the callback immeditely - if (workItem.noResponse && typeof workItem.cb === 'function') { - workItem.cb(null, null); - } - - if (writeSuccessful === false) { - // If write not successful put back on queue - self.queue.unshift(workItem); - // Remove the disconnected connection - removeConnection(self, connection); - // Flush any monitoring operations in the queue, failing fast - flushMonitoringOperations(self.queue); - break; - } - } - - self.executing = false; - }; -} - -// Make execution loop available for testing -Pool._execute = _execute; - -/** - * A server connect event, used to verify that the connection is up and running - * - * @event Pool#connect - * @type {Pool} - */ - -/** - * A server reconnect event, used to verify that pool reconnected. - * - * @event Pool#reconnect - * @type {Pool} - */ - -/** - * The server connection closed, all pool connections closed - * - * @event Pool#close - * @type {Pool} - */ - -/** - * The server connection caused an error, all pool connections closed - * - * @event Pool#error - * @type {Pool} - */ - -/** - * The server connection timed out, all pool connections closed - * - * @event Pool#timeout - * @type {Pool} - */ - -/** - * The driver experienced an invalid message, all pool connections closed - * - * @event Pool#parseError - * @type {Pool} - */ - -/** - * The driver attempted to reconnect - * - * @event Pool#attemptReconnect - * @type {Pool} - */ - -/** - * The driver exhausted all reconnect attempts - * - * @event Pool#reconnectFailed - * @type {Pool} - */ - -module.exports = Pool; diff --git a/scripts/node_modules/mongodb/lib/core/connection/utils.js b/scripts/node_modules/mongodb/lib/core/connection/utils.js deleted file mode 100644 index 2f3d889f..00000000 --- a/scripts/node_modules/mongodb/lib/core/connection/utils.js +++ /dev/null @@ -1,57 +0,0 @@ -'use strict'; - -const require_optional = require('require_optional'); - -function debugOptions(debugFields, options) { - var finaloptions = {}; - debugFields.forEach(function(n) { - finaloptions[n] = options[n]; - }); - - return finaloptions; -} - -function retrieveBSON() { - var BSON = require('bson'); - BSON.native = false; - - try { - var optionalBSON = require_optional('bson-ext'); - if (optionalBSON) { - optionalBSON.native = true; - return optionalBSON; - } - } catch (err) {} // eslint-disable-line - - return BSON; -} - -// Throw an error if an attempt to use Snappy is made when Snappy is not installed -function noSnappyWarning() { - throw new Error( - 'Attempted to use Snappy compression, but Snappy is not installed. Install or disable Snappy compression and try again.' - ); -} - -// Facilitate loading Snappy optionally -function retrieveSnappy() { - var snappy = null; - try { - snappy = require_optional('snappy'); - } catch (error) {} // eslint-disable-line - if (!snappy) { - snappy = { - compress: noSnappyWarning, - uncompress: noSnappyWarning, - compressSync: noSnappyWarning, - uncompressSync: noSnappyWarning - }; - } - return snappy; -} - -module.exports = { - debugOptions, - retrieveBSON, - retrieveSnappy -}; diff --git a/scripts/node_modules/mongodb/lib/core/cursor.js b/scripts/node_modules/mongodb/lib/core/cursor.js deleted file mode 100644 index f5272182..00000000 --- a/scripts/node_modules/mongodb/lib/core/cursor.js +++ /dev/null @@ -1,886 +0,0 @@ -'use strict'; - -const Logger = require('./connection/logger'); -const retrieveBSON = require('./connection/utils').retrieveBSON; -const MongoError = require('./error').MongoError; -const MongoNetworkError = require('./error').MongoNetworkError; -const mongoErrorContextSymbol = require('./error').mongoErrorContextSymbol; -const collationNotSupported = require('./utils').collationNotSupported; -const ReadPreference = require('./topologies/read_preference'); -const isUnifiedTopology = require('./utils').isUnifiedTopology; -const executeOperation = require('../operations/execute_operation'); -const Readable = require('stream').Readable; -const SUPPORTS = require('../utils').SUPPORTS; -const MongoDBNamespace = require('../utils').MongoDBNamespace; -const OperationBase = require('../operations/operation').OperationBase; - -const BSON = retrieveBSON(); -const Long = BSON.Long; - -// Possible states for a cursor -const CursorState = { - INIT: 0, - OPEN: 1, - CLOSED: 2, - GET_MORE: 3 -}; - -// -// Handle callback (including any exceptions thrown) -function handleCallback(callback, err, result) { - try { - callback(err, result); - } catch (err) { - process.nextTick(function() { - throw err; - }); - } -} - -/** - * This is a cursor results callback - * - * @callback resultCallback - * @param {error} error An error object. Set to null if no error present - * @param {object} document - */ - -/** - * @fileOverview The **Cursor** class is an internal class that embodies a cursor on MongoDB - * allowing for iteration over the results returned from the underlying query. - * - * **CURSORS Cannot directly be instantiated** - */ - -/** - * The core cursor class. All cursors in the driver build off of this one. - * - * @property {number} cursorBatchSize The current cursorBatchSize for the cursor - * @property {number} cursorLimit The current cursorLimit for the cursor - * @property {number} cursorSkip The current cursorSkip for the cursor - */ -class CoreCursor extends Readable { - /** - * Create a new core `Cursor` instance. - * **NOTE** Not to be instantiated directly - * - * @param {object} topology The server topology instance. - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {{object}|Long} cmd The selector (can be a command or a cursorId) - * @param {object} [options=null] Optional settings. - * @param {object} [options.batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/find/| find command documentation} and {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. - * @param {array} [options.documents=[]] Initial documents list for cursor - * @param {object} [options.transforms=null] Transform methods for the cursor results - * @param {function} [options.transforms.query] Transform the value returned from the initial query - * @param {function} [options.transforms.doc] Transform each document returned from Cursor.prototype._next - */ - constructor(topology, ns, cmd, options) { - super({ objectMode: true }); - options = options || {}; - - if (ns instanceof OperationBase) { - this.operation = ns; - ns = this.operation.ns.toString(); - options = this.operation.options; - cmd = this.operation.cmd ? this.operation.cmd : {}; - } - - // Cursor pool - this.pool = null; - // Cursor server - this.server = null; - - // Do we have a not connected handler - this.disconnectHandler = options.disconnectHandler; - - // Set local values - this.bson = topology.s.bson; - this.ns = ns; - this.namespace = MongoDBNamespace.fromString(ns); - this.cmd = cmd; - this.options = options; - this.topology = topology; - - // All internal state - this.cursorState = { - cursorId: null, - cmd, - documents: options.documents || [], - cursorIndex: 0, - dead: false, - killed: false, - init: false, - notified: false, - limit: options.limit || cmd.limit || 0, - skip: options.skip || cmd.skip || 0, - batchSize: options.batchSize || cmd.batchSize || 1000, - currentLimit: 0, - // Result field name if not a cursor (contains the array of results) - transforms: options.transforms, - raw: options.raw || (cmd && cmd.raw) - }; - - if (typeof options.session === 'object') { - this.cursorState.session = options.session; - } - - // Add promoteLong to cursor state - const topologyOptions = topology.s.options; - if (typeof topologyOptions.promoteLongs === 'boolean') { - this.cursorState.promoteLongs = topologyOptions.promoteLongs; - } else if (typeof options.promoteLongs === 'boolean') { - this.cursorState.promoteLongs = options.promoteLongs; - } - - // Add promoteValues to cursor state - if (typeof topologyOptions.promoteValues === 'boolean') { - this.cursorState.promoteValues = topologyOptions.promoteValues; - } else if (typeof options.promoteValues === 'boolean') { - this.cursorState.promoteValues = options.promoteValues; - } - - // Add promoteBuffers to cursor state - if (typeof topologyOptions.promoteBuffers === 'boolean') { - this.cursorState.promoteBuffers = topologyOptions.promoteBuffers; - } else if (typeof options.promoteBuffers === 'boolean') { - this.cursorState.promoteBuffers = options.promoteBuffers; - } - - if (topologyOptions.reconnect) { - this.cursorState.reconnect = topologyOptions.reconnect; - } - - // Logger - this.logger = Logger('Cursor', topologyOptions); - - // - // Did we pass in a cursor id - if (typeof cmd === 'number') { - this.cursorState.cursorId = Long.fromNumber(cmd); - this.cursorState.lastCursorId = this.cursorState.cursorId; - } else if (cmd instanceof Long) { - this.cursorState.cursorId = cmd; - this.cursorState.lastCursorId = cmd; - } - - // TODO: remove as part of NODE-2104 - if (this.operation) { - this.operation.cursorState = this.cursorState; - } - } - - setCursorBatchSize(value) { - this.cursorState.batchSize = value; - } - - cursorBatchSize() { - return this.cursorState.batchSize; - } - - setCursorLimit(value) { - this.cursorState.limit = value; - } - - cursorLimit() { - return this.cursorState.limit; - } - - setCursorSkip(value) { - this.cursorState.skip = value; - } - - cursorSkip() { - return this.cursorState.skip; - } - - /** - * Retrieve the next document from the cursor - * @method - * @param {resultCallback} callback A callback function - */ - _next(callback) { - nextFunction(this, callback); - } - - /** - * Clone the cursor - * @method - * @return {Cursor} - */ - clone() { - return this.topology.cursor(this.ns, this.cmd, this.options); - } - - /** - * Checks if the cursor is dead - * @method - * @return {boolean} A boolean signifying if the cursor is dead or not - */ - isDead() { - return this.cursorState.dead === true; - } - - /** - * Checks if the cursor was killed by the application - * @method - * @return {boolean} A boolean signifying if the cursor was killed by the application - */ - isKilled() { - return this.cursorState.killed === true; - } - - /** - * Checks if the cursor notified it's caller about it's death - * @method - * @return {boolean} A boolean signifying if the cursor notified the callback - */ - isNotified() { - return this.cursorState.notified === true; - } - - /** - * Returns current buffered documents length - * @method - * @return {number} The number of items in the buffered documents - */ - bufferedCount() { - return this.cursorState.documents.length - this.cursorState.cursorIndex; - } - - /** - * Returns current buffered documents - * @method - * @return {Array} An array of buffered documents - */ - readBufferedDocuments(number) { - const unreadDocumentsLength = this.cursorState.documents.length - this.cursorState.cursorIndex; - const length = number < unreadDocumentsLength ? number : unreadDocumentsLength; - let elements = this.cursorState.documents.slice( - this.cursorState.cursorIndex, - this.cursorState.cursorIndex + length - ); - - // Transform the doc with passed in transformation method if provided - if (this.cursorState.transforms && typeof this.cursorState.transforms.doc === 'function') { - // Transform all the elements - for (let i = 0; i < elements.length; i++) { - elements[i] = this.cursorState.transforms.doc(elements[i]); - } - } - - // Ensure we do not return any more documents than the limit imposed - // Just return the number of elements up to the limit - if ( - this.cursorState.limit > 0 && - this.cursorState.currentLimit + elements.length > this.cursorState.limit - ) { - elements = elements.slice(0, this.cursorState.limit - this.cursorState.currentLimit); - this.kill(); - } - - // Adjust current limit - this.cursorState.currentLimit = this.cursorState.currentLimit + elements.length; - this.cursorState.cursorIndex = this.cursorState.cursorIndex + elements.length; - - // Return elements - return elements; - } - - /** - * Resets local state for this cursor instance, and issues a `killCursors` command to the server - * - * @param {resultCallback} callback A callback function - */ - kill(callback) { - // Set cursor to dead - this.cursorState.dead = true; - this.cursorState.killed = true; - // Remove documents - this.cursorState.documents = []; - - // If no cursor id just return - if ( - this.cursorState.cursorId == null || - this.cursorState.cursorId.isZero() || - this.cursorState.init === false - ) { - if (callback) callback(null, null); - return; - } - - this.server.killCursors(this.ns, this.cursorState, callback); - } - - /** - * Resets the cursor - */ - rewind() { - if (this.cursorState.init) { - if (!this.cursorState.dead) { - this.kill(); - } - - this.cursorState.currentLimit = 0; - this.cursorState.init = false; - this.cursorState.dead = false; - this.cursorState.killed = false; - this.cursorState.notified = false; - this.cursorState.documents = []; - this.cursorState.cursorId = null; - this.cursorState.cursorIndex = 0; - } - } - - // Internal methods - _read() { - if ((this.s && this.s.state === CursorState.CLOSED) || this.isDead()) { - return this.push(null); - } - - // Get the next item - this._next((err, result) => { - if (err) { - if (this.listeners('error') && this.listeners('error').length > 0) { - this.emit('error', err); - } - if (!this.isDead()) this.close(); - - // Emit end event - this.emit('end'); - return this.emit('finish'); - } - - // If we provided a transformation method - if ( - this.cursorState.streamOptions && - typeof this.cursorState.streamOptions.transform === 'function' && - result != null - ) { - return this.push(this.cursorState.streamOptions.transform(result)); - } - - // If we provided a map function - if ( - this.cursorState.transforms && - typeof this.cursorState.transforms.doc === 'function' && - result != null - ) { - return this.push(this.cursorState.transforms.doc(result)); - } - - // Return the result - this.push(result); - - if (result === null && this.isDead()) { - this.once('end', () => { - this.close(); - this.emit('finish'); - }); - } - }); - } - - _endSession(options, callback) { - if (typeof options === 'function') { - callback = options; - options = {}; - } - options = options || {}; - - const session = this.cursorState.session; - - if (session && (options.force || session.owner === this)) { - this.cursorState.session = undefined; - - if (this.operation) { - this.operation.clearSession(); - } - - session.endSession(callback); - return true; - } - - if (callback) { - callback(); - } - - return false; - } - - _getMore(callback) { - if (this.logger.isDebug()) { - this.logger.debug(`schedule getMore call for query [${JSON.stringify(this.query)}]`); - } - - // Set the current batchSize - let batchSize = this.cursorState.batchSize; - if ( - this.cursorState.limit > 0 && - this.cursorState.currentLimit + batchSize > this.cursorState.limit - ) { - batchSize = this.cursorState.limit - this.cursorState.currentLimit; - } - - this.server.getMore(this.ns, this.cursorState, batchSize, this.options, callback); - } - - _initializeCursor(callback) { - const cursor = this; - - // NOTE: this goes away once cursors use `executeOperation` - if (isUnifiedTopology(cursor.topology) && cursor.topology.shouldCheckForSessionSupport()) { - cursor.topology.selectServer(ReadPreference.primaryPreferred, err => { - if (err) { - callback(err); - return; - } - - cursor._next(callback); - }); - - return; - } - - function done(err, result) { - if ( - cursor.cursorState.cursorId && - cursor.cursorState.cursorId.isZero() && - cursor._endSession - ) { - cursor._endSession(); - } - - if ( - cursor.cursorState.documents.length === 0 && - cursor.cursorState.cursorId && - cursor.cursorState.cursorId.isZero() && - !cursor.cmd.tailable && - !cursor.cmd.awaitData - ) { - return setCursorNotified(cursor, callback); - } - - callback(err, result); - } - - const queryCallback = (err, r) => { - if (err) { - return done(err); - } - - const result = r.message; - if (result.queryFailure) { - return done(new MongoError(result.documents[0]), null); - } - - // Check if we have a command cursor - if ( - Array.isArray(result.documents) && - result.documents.length === 1 && - (!cursor.cmd.find || (cursor.cmd.find && cursor.cmd.virtual === false)) && - (typeof result.documents[0].cursor !== 'string' || - result.documents[0]['$err'] || - result.documents[0]['errmsg'] || - Array.isArray(result.documents[0].result)) - ) { - // We have an error document, return the error - if (result.documents[0]['$err'] || result.documents[0]['errmsg']) { - return done(new MongoError(result.documents[0]), null); - } - - // We have a cursor document - if (result.documents[0].cursor != null && typeof result.documents[0].cursor !== 'string') { - const id = result.documents[0].cursor.id; - // If we have a namespace change set the new namespace for getmores - if (result.documents[0].cursor.ns) { - cursor.ns = result.documents[0].cursor.ns; - } - // Promote id to long if needed - cursor.cursorState.cursorId = typeof id === 'number' ? Long.fromNumber(id) : id; - cursor.cursorState.lastCursorId = cursor.cursorState.cursorId; - cursor.cursorState.operationTime = result.documents[0].operationTime; - - // If we have a firstBatch set it - if (Array.isArray(result.documents[0].cursor.firstBatch)) { - cursor.cursorState.documents = result.documents[0].cursor.firstBatch; //.reverse(); - } - - // Return after processing command cursor - return done(null, result); - } - - if (Array.isArray(result.documents[0].result)) { - cursor.cursorState.documents = result.documents[0].result; - cursor.cursorState.cursorId = Long.ZERO; - return done(null, result); - } - } - - // Otherwise fall back to regular find path - const cursorId = result.cursorId || 0; - cursor.cursorState.cursorId = cursorId instanceof Long ? cursorId : Long.fromNumber(cursorId); - cursor.cursorState.documents = result.documents; - cursor.cursorState.lastCursorId = result.cursorId; - - // Transform the results with passed in transformation method if provided - if ( - cursor.cursorState.transforms && - typeof cursor.cursorState.transforms.query === 'function' - ) { - cursor.cursorState.documents = cursor.cursorState.transforms.query(result); - } - - done(null, result); - }; - - if (cursor.operation) { - if (cursor.logger.isDebug()) { - cursor.logger.debug( - `issue initial query [${JSON.stringify(cursor.cmd)}] with flags [${JSON.stringify( - cursor.query - )}]` - ); - } - - executeOperation(cursor.topology, cursor.operation, (err, result) => { - if (err) { - done(err); - return; - } - - cursor.server = cursor.operation.server; - cursor.cursorState.init = true; - - // NOTE: this is a special internal method for cloning a cursor, consider removing - if (cursor.cursorState.cursorId != null) { - return done(); - } - - queryCallback(err, result); - }); - - return; - } - - // Very explicitly choose what is passed to selectServer - const serverSelectOptions = {}; - if (cursor.cursorState.session) { - serverSelectOptions.session = cursor.cursorState.session; - } - - if (cursor.operation) { - serverSelectOptions.readPreference = cursor.operation.readPreference; - } else if (cursor.options.readPreference) { - serverSelectOptions.readPreference = cursor.options.readPreference; - } - - return cursor.topology.selectServer(serverSelectOptions, (err, server) => { - if (err) { - const disconnectHandler = cursor.disconnectHandler; - if (disconnectHandler != null) { - return disconnectHandler.addObjectAndMethod( - 'cursor', - cursor, - 'next', - [callback], - callback - ); - } - - return callback(err); - } - - cursor.server = server; - cursor.cursorState.init = true; - if (collationNotSupported(cursor.server, cursor.cmd)) { - return callback(new MongoError(`server ${cursor.server.name} does not support collation`)); - } - - // NOTE: this is a special internal method for cloning a cursor, consider removing - if (cursor.cursorState.cursorId != null) { - return done(); - } - - if (cursor.logger.isDebug()) { - cursor.logger.debug( - `issue initial query [${JSON.stringify(cursor.cmd)}] with flags [${JSON.stringify( - cursor.query - )}]` - ); - } - - if (cursor.cmd.find != null) { - server.query(cursor.ns, cursor.cmd, cursor.cursorState, cursor.options, queryCallback); - return; - } - - const commandOptions = Object.assign({ session: cursor.cursorState.session }, cursor.options); - server.command(cursor.ns, cursor.cmd, commandOptions, queryCallback); - }); - } -} - -if (SUPPORTS.ASYNC_ITERATOR) { - CoreCursor.prototype[Symbol.asyncIterator] = require('../async/async_iterator').asyncIterator; -} - -/** - * Validate if the pool is dead and return error - */ -function isConnectionDead(self, callback) { - if (self.pool && self.pool.isDestroyed()) { - self.cursorState.killed = true; - const err = new MongoNetworkError( - `connection to host ${self.pool.host}:${self.pool.port} was destroyed` - ); - - _setCursorNotifiedImpl(self, () => callback(err)); - return true; - } - - return false; -} - -/** - * Validate if the cursor is dead but was not explicitly killed by user - */ -function isCursorDeadButNotkilled(self, callback) { - // Cursor is dead but not marked killed, return null - if (self.cursorState.dead && !self.cursorState.killed) { - self.cursorState.killed = true; - setCursorNotified(self, callback); - return true; - } - - return false; -} - -/** - * Validate if the cursor is dead and was killed by user - */ -function isCursorDeadAndKilled(self, callback) { - if (self.cursorState.dead && self.cursorState.killed) { - handleCallback(callback, new MongoError('cursor is dead')); - return true; - } - - return false; -} - -/** - * Validate if the cursor was killed by the user - */ -function isCursorKilled(self, callback) { - if (self.cursorState.killed) { - setCursorNotified(self, callback); - return true; - } - - return false; -} - -/** - * Mark cursor as being dead and notified - */ -function setCursorDeadAndNotified(self, callback) { - self.cursorState.dead = true; - setCursorNotified(self, callback); -} - -/** - * Mark cursor as being notified - */ -function setCursorNotified(self, callback) { - _setCursorNotifiedImpl(self, () => handleCallback(callback, null, null)); -} - -function _setCursorNotifiedImpl(self, callback) { - self.cursorState.notified = true; - self.cursorState.documents = []; - self.cursorState.cursorIndex = 0; - - if (self._endSession) { - self._endSession(undefined, () => callback()); - return; - } - - return callback(); -} - -function nextFunction(self, callback) { - // We have notified about it - if (self.cursorState.notified) { - return callback(new Error('cursor is exhausted')); - } - - // Cursor is killed return null - if (isCursorKilled(self, callback)) return; - - // Cursor is dead but not marked killed, return null - if (isCursorDeadButNotkilled(self, callback)) return; - - // We have a dead and killed cursor, attempting to call next should error - if (isCursorDeadAndKilled(self, callback)) return; - - // We have just started the cursor - if (!self.cursorState.init) { - // Topology is not connected, save the call in the provided store to be - // Executed at some point when the handler deems it's reconnected - if (!self.topology.isConnected(self.options)) { - // Only need this for single server, because repl sets and mongos - // will always continue trying to reconnect - if (self.topology._type === 'server' && !self.topology.s.options.reconnect) { - // Reconnect is disabled, so we'll never reconnect - return callback(new MongoError('no connection available')); - } - - if (self.disconnectHandler != null) { - if (self.topology.isDestroyed()) { - // Topology was destroyed, so don't try to wait for it to reconnect - return callback(new MongoError('Topology was destroyed')); - } - - self.disconnectHandler.addObjectAndMethod('cursor', self, 'next', [callback], callback); - return; - } - } - - self._initializeCursor((err, result) => { - if (err || result === null) { - callback(err, result); - return; - } - - nextFunction(self, callback); - }); - - return; - } - - if (self.cursorState.limit > 0 && self.cursorState.currentLimit >= self.cursorState.limit) { - // Ensure we kill the cursor on the server - self.kill(); - // Set cursor in dead and notified state - return setCursorDeadAndNotified(self, callback); - } else if ( - self.cursorState.cursorIndex === self.cursorState.documents.length && - !Long.ZERO.equals(self.cursorState.cursorId) - ) { - // Ensure an empty cursor state - self.cursorState.documents = []; - self.cursorState.cursorIndex = 0; - - // Check if topology is destroyed - if (self.topology.isDestroyed()) - return callback( - new MongoNetworkError('connection destroyed, not possible to instantiate cursor') - ); - - // Check if connection is dead and return if not possible to - // execute a getMore on this connection - if (isConnectionDead(self, callback)) return; - - // Execute the next get more - self._getMore(function(err, doc, connection) { - if (err) { - if (err instanceof MongoError) { - err[mongoErrorContextSymbol].isGetMore = true; - } - - return handleCallback(callback, err); - } - - if (self.cursorState.cursorId && self.cursorState.cursorId.isZero() && self._endSession) { - self._endSession(); - } - - // Save the returned connection to ensure all getMore's fire over the same connection - self.connection = connection; - - // Tailable cursor getMore result, notify owner about it - // No attempt is made here to retry, this is left to the user of the - // core module to handle to keep core simple - if ( - self.cursorState.documents.length === 0 && - self.cmd.tailable && - Long.ZERO.equals(self.cursorState.cursorId) - ) { - // No more documents in the tailed cursor - return handleCallback( - callback, - new MongoError({ - message: 'No more documents in tailed cursor', - tailable: self.cmd.tailable, - awaitData: self.cmd.awaitData - }) - ); - } else if ( - self.cursorState.documents.length === 0 && - self.cmd.tailable && - !Long.ZERO.equals(self.cursorState.cursorId) - ) { - return nextFunction(self, callback); - } - - if (self.cursorState.limit > 0 && self.cursorState.currentLimit >= self.cursorState.limit) { - return setCursorDeadAndNotified(self, callback); - } - - nextFunction(self, callback); - }); - } else if ( - self.cursorState.documents.length === self.cursorState.cursorIndex && - self.cmd.tailable && - Long.ZERO.equals(self.cursorState.cursorId) - ) { - return handleCallback( - callback, - new MongoError({ - message: 'No more documents in tailed cursor', - tailable: self.cmd.tailable, - awaitData: self.cmd.awaitData - }) - ); - } else if ( - self.cursorState.documents.length === self.cursorState.cursorIndex && - Long.ZERO.equals(self.cursorState.cursorId) - ) { - setCursorDeadAndNotified(self, callback); - } else { - if (self.cursorState.limit > 0 && self.cursorState.currentLimit >= self.cursorState.limit) { - // Ensure we kill the cursor on the server - self.kill(); - // Set cursor in dead and notified state - return setCursorDeadAndNotified(self, callback); - } - - // Increment the current cursor limit - self.cursorState.currentLimit += 1; - - // Get the document - let doc = self.cursorState.documents[self.cursorState.cursorIndex++]; - - // Doc overflow - if (!doc || doc.$err) { - // Ensure we kill the cursor on the server - self.kill(); - // Set cursor in dead and notified state - return setCursorDeadAndNotified(self, function() { - handleCallback(callback, new MongoError(doc ? doc.$err : undefined)); - }); - } - - // Transform the doc with passed in transformation method if provided - if (self.cursorState.transforms && typeof self.cursorState.transforms.doc === 'function') { - doc = self.cursorState.transforms.doc(doc); - } - - // Return the document - handleCallback(callback, null, doc); - } -} - -module.exports = { - CursorState, - CoreCursor -}; diff --git a/scripts/node_modules/mongodb/lib/core/error.js b/scripts/node_modules/mongodb/lib/core/error.js deleted file mode 100644 index d35fbbef..00000000 --- a/scripts/node_modules/mongodb/lib/core/error.js +++ /dev/null @@ -1,237 +0,0 @@ -'use strict'; - -const mongoErrorContextSymbol = Symbol('mongoErrorContextSymbol'); -const maxWireVersion = require('./utils').maxWireVersion; - -/** - * Creates a new MongoError - * - * @augments Error - * @param {Error|string|object} message The error message - * @property {string} message The error message - * @property {string} stack The error call stack - */ -class MongoError extends Error { - constructor(message) { - if (message instanceof Error) { - super(message.message); - this.stack = message.stack; - } else { - if (typeof message === 'string') { - super(message); - } else { - super(message.message || message.errmsg || message.$err || 'n/a'); - for (var name in message) { - this[name] = message[name]; - } - } - - Error.captureStackTrace(this, this.constructor); - } - - this.name = 'MongoError'; - this[mongoErrorContextSymbol] = this[mongoErrorContextSymbol] || {}; - } - - /** - * Creates a new MongoError object - * - * @param {Error|string|object} options The options used to create the error. - * @return {MongoError} A MongoError instance - * @deprecated Use `new MongoError()` instead. - */ - static create(options) { - return new MongoError(options); - } - - hasErrorLabel(label) { - return this.errorLabels && this.errorLabels.indexOf(label) !== -1; - } -} - -/** - * Creates a new MongoNetworkError - * - * @param {Error|string|object} message The error message - * @property {string} message The error message - * @property {string} stack The error call stack - */ -class MongoNetworkError extends MongoError { - constructor(message) { - super(message); - this.name = 'MongoNetworkError'; - - // This is added as part of the transactions specification - this.errorLabels = ['TransientTransactionError']; - } -} - -/** - * An error used when attempting to parse a value (like a connection string) - * - * @param {Error|string|object} message The error message - * @property {string} message The error message - */ -class MongoParseError extends MongoError { - constructor(message) { - super(message); - this.name = 'MongoParseError'; - } -} - -/** - * An error signifying a timeout event - * - * @param {Error|string|object} message The error message - * @param {string|object} [reason] The reason the timeout occured - * @property {string} message The error message - * @property {string} [reason] An optional reason context for the timeout, generally an error saved during flow of monitoring and selecting servers - */ -class MongoTimeoutError extends MongoError { - constructor(message, reason) { - super(message); - this.name = 'MongoTimeoutError'; - if (reason != null) { - this.reason = reason; - } - } -} - -function makeWriteConcernResultObject(input) { - const output = Object.assign({}, input); - - if (output.ok === 0) { - output.ok = 1; - delete output.errmsg; - delete output.code; - delete output.codeName; - } - - return output; -} - -/** - * An error thrown when the server reports a writeConcernError - * - * @param {Error|string|object} message The error message - * @param {object} result The result document (provided if ok: 1) - * @property {string} message The error message - * @property {object} [result] The result document (provided if ok: 1) - */ -class MongoWriteConcernError extends MongoError { - constructor(message, result) { - super(message); - this.name = 'MongoWriteConcernError'; - - if (result != null) { - this.result = makeWriteConcernResultObject(result); - } - } -} - -// see: https://github.com/mongodb/specifications/blob/master/source/retryable-writes/retryable-writes.rst#terms -const RETRYABLE_ERROR_CODES = new Set([ - 6, // HostUnreachable - 7, // HostNotFound - 89, // NetworkTimeout - 91, // ShutdownInProgress - 189, // PrimarySteppedDown - 9001, // SocketException - 10107, // NotMaster - 11600, // InterruptedAtShutdown - 11602, // InterruptedDueToReplStateChange - 13435, // NotMasterNoSlaveOk - 13436 // NotMasterOrSecondary -]); - -/** - * Determines whether an error is something the driver should attempt to retry - * - * @param {MongoError|Error} error - */ -function isRetryableError(error) { - return ( - RETRYABLE_ERROR_CODES.has(error.code) || - error instanceof MongoNetworkError || - error.message.match(/not master/) || - error.message.match(/node is recovering/) - ); -} - -const SDAM_RECOVERING_CODES = new Set([ - 91, // ShutdownInProgress - 189, // PrimarySteppedDown - 11600, // InterruptedAtShutdown - 11602, // InterruptedDueToReplStateChange - 13436 // NotMasterOrSecondary -]); - -const SDAM_NOTMASTER_CODES = new Set([ - 10107, // NotMaster - 13435 // NotMasterNoSlaveOk -]); - -const SDAM_NODE_SHUTTING_DOWN_ERROR_CODES = new Set([ - 11600, // InterruptedAtShutdown - 91 // ShutdownInProgress -]); - -function isRecoveringError(err) { - if (err.code && SDAM_RECOVERING_CODES.has(err.code)) { - return true; - } - - return err.message.match(/not master or secondary/) || err.message.match(/node is recovering/); -} - -function isNotMasterError(err) { - if (err.code && SDAM_NOTMASTER_CODES.has(err.code)) { - return true; - } - - if (isRecoveringError(err)) { - return false; - } - - return err.message.match(/not master/); -} - -function isNodeShuttingDownError(err) { - return err.code && SDAM_NODE_SHUTTING_DOWN_ERROR_CODES.has(err.code); -} - -/** - * Determines whether SDAM can recover from a given error. If it cannot - * then the pool will be cleared, and server state will completely reset - * locally. - * - * @see https://github.com/mongodb/specifications/blob/master/source/server-discovery-and-monitoring/server-discovery-and-monitoring.rst#not-master-and-node-is-recovering - * @param {MongoError|Error} error - * @param {Server} server - */ -function isSDAMUnrecoverableError(error, server) { - if (error instanceof MongoParseError) { - return true; - } - - if (isRecoveringError(error) || isNotMasterError(error)) { - if (maxWireVersion(server) >= 8 && !isNodeShuttingDownError(error)) { - return false; - } - - return true; - } - - return false; -} - -module.exports = { - MongoError, - MongoNetworkError, - MongoParseError, - MongoTimeoutError, - MongoWriteConcernError, - mongoErrorContextSymbol, - isRetryableError, - isSDAMUnrecoverableError -}; diff --git a/scripts/node_modules/mongodb/lib/core/index.js b/scripts/node_modules/mongodb/lib/core/index.js deleted file mode 100644 index 8d1ca8f5..00000000 --- a/scripts/node_modules/mongodb/lib/core/index.js +++ /dev/null @@ -1,50 +0,0 @@ -'use strict'; - -let BSON = require('bson'); -const require_optional = require('require_optional'); -const EJSON = require('./utils').retrieveEJSON(); - -try { - // Attempt to grab the native BSON parser - const BSONNative = require_optional('bson-ext'); - // If we got the native parser, use it instead of the - // Javascript one - if (BSONNative) { - BSON = BSONNative; - } -} catch (err) {} // eslint-disable-line - -module.exports = { - // Errors - MongoError: require('./error').MongoError, - MongoNetworkError: require('./error').MongoNetworkError, - MongoParseError: require('./error').MongoParseError, - MongoTimeoutError: require('./error').MongoTimeoutError, - MongoWriteConcernError: require('./error').MongoWriteConcernError, - mongoErrorContextSymbol: require('./error').mongoErrorContextSymbol, - // Core - Connection: require('./connection/connection'), - Server: require('./topologies/server'), - ReplSet: require('./topologies/replset'), - Mongos: require('./topologies/mongos'), - Logger: require('./connection/logger'), - Cursor: require('./cursor').CoreCursor, - ReadPreference: require('./topologies/read_preference'), - Sessions: require('./sessions'), - BSON: BSON, - EJSON: EJSON, - Topology: require('./sdam/topology'), - // Raw operations - Query: require('./connection/commands').Query, - // Auth mechanisms - MongoCredentials: require('./auth/mongo_credentials').MongoCredentials, - defaultAuthProviders: require('./auth/defaultAuthProviders').defaultAuthProviders, - MongoCR: require('./auth/mongocr'), - X509: require('./auth/x509'), - Plain: require('./auth/plain'), - GSSAPI: require('./auth/gssapi'), - ScramSHA1: require('./auth/scram').ScramSHA1, - ScramSHA256: require('./auth/scram').ScramSHA256, - // Utilities - parseConnectionString: require('./uri_parser') -}; diff --git a/scripts/node_modules/mongodb/lib/core/sdam/monitoring.js b/scripts/node_modules/mongodb/lib/core/sdam/monitoring.js deleted file mode 100644 index 15f081c8..00000000 --- a/scripts/node_modules/mongodb/lib/core/sdam/monitoring.js +++ /dev/null @@ -1,235 +0,0 @@ -'use strict'; - -const ServerDescription = require('./server_description').ServerDescription; -const calculateDurationInMs = require('../utils').calculateDurationInMs; - -// pulled from `Server` implementation -const STATE_DISCONNECTED = 'disconnected'; -const STATE_DISCONNECTING = 'disconnecting'; - -/** - * Published when server description changes, but does NOT include changes to the RTT. - * - * @property {Object} topologyId A unique identifier for the topology - * @property {ServerAddress} address The address (host/port pair) of the server - * @property {ServerDescription} previousDescription The previous server description - * @property {ServerDescription} newDescription The new server description - */ -class ServerDescriptionChangedEvent { - constructor(topologyId, address, previousDescription, newDescription) { - Object.assign(this, { topologyId, address, previousDescription, newDescription }); - } -} - -/** - * Published when server is initialized. - * - * @property {Object} topologyId A unique identifier for the topology - * @property {ServerAddress} address The address (host/port pair) of the server - */ -class ServerOpeningEvent { - constructor(topologyId, address) { - Object.assign(this, { topologyId, address }); - } -} - -/** - * Published when server is closed. - * - * @property {ServerAddress} address The address (host/port pair) of the server - * @property {Object} topologyId A unique identifier for the topology - */ -class ServerClosedEvent { - constructor(topologyId, address) { - Object.assign(this, { topologyId, address }); - } -} - -/** - * Published when topology description changes. - * - * @property {Object} topologyId - * @property {TopologyDescription} previousDescription The old topology description - * @property {TopologyDescription} newDescription The new topology description - */ -class TopologyDescriptionChangedEvent { - constructor(topologyId, previousDescription, newDescription) { - Object.assign(this, { topologyId, previousDescription, newDescription }); - } -} - -/** - * Published when topology is initialized. - * - * @param {Object} topologyId A unique identifier for the topology - */ -class TopologyOpeningEvent { - constructor(topologyId) { - Object.assign(this, { topologyId }); - } -} - -/** - * Published when topology is closed. - * - * @param {Object} topologyId A unique identifier for the topology - */ -class TopologyClosedEvent { - constructor(topologyId) { - Object.assign(this, { topologyId }); - } -} - -/** - * Fired when the server monitor’s ismaster command is started - immediately before - * the ismaster command is serialized into raw BSON and written to the socket. - * - * @property {Object} connectionId The connection id for the command - */ -class ServerHeartbeatStartedEvent { - constructor(connectionId) { - Object.assign(this, { connectionId }); - } -} - -/** - * Fired when the server monitor’s ismaster succeeds. - * - * @param {Number} duration The execution time of the event in ms - * @param {Object} reply The command reply - * @param {Object} connectionId The connection id for the command - */ -class ServerHeartbeatSucceededEvent { - constructor(duration, reply, connectionId) { - Object.assign(this, { duration, reply, connectionId }); - } -} - -/** - * Fired when the server monitor’s ismaster fails, either with an “ok: 0” or a socket exception. - * - * @param {Number} duration The execution time of the event in ms - * @param {MongoError|Object} failure The command failure - * @param {Object} connectionId The connection id for the command - */ -class ServerHeartbeatFailedEvent { - constructor(duration, failure, connectionId) { - Object.assign(this, { duration, failure, connectionId }); - } -} - -/** - * Performs a server check as described by the SDAM spec. - * - * NOTE: This method automatically reschedules itself, so that there is always an active - * monitoring process - * - * @param {Server} server The server to monitor - */ -function monitorServer(server, options) { - options = options || {}; - const heartbeatFrequencyMS = options.heartbeatFrequencyMS || 10000; - - if (options.initial === true) { - server.s.monitorId = setTimeout(() => monitorServer(server), heartbeatFrequencyMS); - return; - } - - // executes a single check of a server - const checkServer = callback => { - let start = process.hrtime(); - - // emit a signal indicating we have started the heartbeat - server.emit('serverHeartbeatStarted', new ServerHeartbeatStartedEvent(server.name)); - - // NOTE: legacy monitoring event - process.nextTick(() => server.emit('monitoring', server)); - - server.command( - 'admin.$cmd', - { ismaster: true }, - { - monitoring: true, - socketTimeout: server.s.options.connectionTimeout || 2000 - }, - (err, result) => { - let duration = calculateDurationInMs(start); - - if (err) { - server.emit( - 'serverHeartbeatFailed', - new ServerHeartbeatFailedEvent(duration, err, server.name) - ); - - return callback(err, null); - } - - const isMaster = result.result; - server.emit( - 'serverHeartbeatSucceeded', - new ServerHeartbeatSucceededEvent(duration, isMaster, server.name) - ); - - return callback(null, isMaster); - } - ); - }; - - const successHandler = isMaster => { - server.s.monitoring = false; - - // emit an event indicating that our description has changed - server.emit('descriptionReceived', new ServerDescription(server.description.address, isMaster)); - if (server.s.state === STATE_DISCONNECTED || server.s.state === STATE_DISCONNECTING) { - return; - } - - // schedule the next monitoring process - server.s.monitorId = setTimeout(() => monitorServer(server), heartbeatFrequencyMS); - }; - - // run the actual monitoring loop - server.s.monitoring = true; - checkServer((err, isMaster) => { - if (!err) { - successHandler(isMaster); - return; - } - - // According to the SDAM specification's "Network error during server check" section, if - // an ismaster call fails we reset the server's pool. If a server was once connected, - // change its type to `Unknown` only after retrying once. - server.s.pool.reset(() => { - // otherwise re-attempt monitoring once - checkServer((error, isMaster) => { - if (error) { - server.s.monitoring = false; - - // we revert to an `Unknown` by emitting a default description with no isMaster - server.emit( - 'descriptionReceived', - new ServerDescription(server.description.address, null, { error }) - ); - - // we do not reschedule monitoring in this case - return; - } - - successHandler(isMaster); - }); - }); - }); -} - -module.exports = { - ServerDescriptionChangedEvent, - ServerOpeningEvent, - ServerClosedEvent, - TopologyDescriptionChangedEvent, - TopologyOpeningEvent, - TopologyClosedEvent, - ServerHeartbeatStartedEvent, - ServerHeartbeatSucceededEvent, - ServerHeartbeatFailedEvent, - monitorServer -}; diff --git a/scripts/node_modules/mongodb/lib/core/sdam/server.js b/scripts/node_modules/mongodb/lib/core/sdam/server.js deleted file mode 100644 index abb1570a..00000000 --- a/scripts/node_modules/mongodb/lib/core/sdam/server.js +++ /dev/null @@ -1,511 +0,0 @@ -'use strict'; -const EventEmitter = require('events'); -const MongoError = require('../error').MongoError; -const Pool = require('../connection/pool'); -const relayEvents = require('../utils').relayEvents; -const wireProtocol = require('../wireprotocol'); -const BSON = require('../connection/utils').retrieveBSON(); -const createClientInfo = require('../topologies/shared').createClientInfo; -const Logger = require('../connection/logger'); -const ServerDescription = require('./server_description').ServerDescription; -const ReadPreference = require('../topologies/read_preference'); -const monitorServer = require('./monitoring').monitorServer; -const MongoParseError = require('../error').MongoParseError; -const MongoNetworkError = require('../error').MongoNetworkError; -const collationNotSupported = require('../utils').collationNotSupported; -const debugOptions = require('../connection/utils').debugOptions; -const isSDAMUnrecoverableError = require('../error').isSDAMUnrecoverableError; - -// Used for filtering out fields for logging -const DEBUG_FIELDS = [ - 'reconnect', - 'reconnectTries', - 'reconnectInterval', - 'emitError', - 'cursorFactory', - 'host', - 'port', - 'size', - 'keepAlive', - 'keepAliveInitialDelay', - 'noDelay', - 'connectionTimeout', - 'checkServerIdentity', - 'socketTimeout', - 'ssl', - 'ca', - 'crl', - 'cert', - 'key', - 'rejectUnauthorized', - 'promoteLongs', - 'promoteValues', - 'promoteBuffers', - 'servername' -]; - -const STATE_DISCONNECTING = 'disconnecting'; -const STATE_DISCONNECTED = 'disconnected'; -const STATE_CONNECTING = 'connecting'; -const STATE_CONNECTED = 'connected'; - -/** - * - * @fires Server#serverHeartbeatStarted - * @fires Server#serverHeartbeatSucceeded - * @fires Server#serverHeartbeatFailed - */ -class Server extends EventEmitter { - /** - * Create a server - * - * @param {ServerDescription} description - * @param {Object} options - */ - constructor(description, options, topology) { - super(); - - this.s = { - // the server description - description, - // a saved copy of the incoming options - options, - // the server logger - logger: Logger('Server', options), - // the bson parser - bson: - options.bson || - new BSON([ - BSON.Binary, - BSON.Code, - BSON.DBRef, - BSON.Decimal128, - BSON.Double, - BSON.Int32, - BSON.Long, - BSON.Map, - BSON.MaxKey, - BSON.MinKey, - BSON.ObjectId, - BSON.BSONRegExp, - BSON.Symbol, - BSON.Timestamp - ]), - // client metadata for the initial handshake - clientInfo: createClientInfo(options), - // state variable to determine if there is an active server check in progress - monitoring: false, - // the implementation of the monitoring method - monitorFunction: options.monitorFunction || monitorServer, - // the connection pool - pool: null, - // the server state - state: STATE_DISCONNECTED, - credentials: options.credentials, - topology - }; - } - - get description() { - return this.s.description; - } - - get name() { - return this.s.description.address; - } - - get autoEncrypter() { - if (this.s.options && this.s.options.autoEncrypter) { - return this.s.options.autoEncrypter; - } - return null; - } - - /** - * Initiate server connect - */ - connect(options) { - options = options || {}; - - // do not allow connect to be called on anything that's not disconnected - if (this.s.pool && !this.s.pool.isDisconnected() && !this.s.pool.isDestroyed()) { - throw new MongoError(`Server instance in invalid state ${this.s.pool.state}`); - } - - // create a pool - const addressParts = this.description.address.split(':'); - const poolOptions = Object.assign( - { host: addressParts[0], port: parseInt(addressParts[1], 10) }, - this.s.options, - options, - { bson: this.s.bson } - ); - - // NOTE: this should only be the case if we are connecting to a single server - poolOptions.reconnect = true; - poolOptions.legacyCompatMode = false; - - this.s.pool = new Pool(this, poolOptions); - - // setup listeners - this.s.pool.on('connect', connectEventHandler(this)); - this.s.pool.on('close', errorEventHandler(this)); - this.s.pool.on('error', errorEventHandler(this)); - this.s.pool.on('parseError', parseErrorEventHandler(this)); - - // it is unclear whether consumers should even know about these events - // this.s.pool.on('timeout', timeoutEventHandler(this)); - // this.s.pool.on('reconnect', reconnectEventHandler(this)); - // this.s.pool.on('reconnectFailed', errorEventHandler(this)); - - // relay all command monitoring events - relayEvents(this.s.pool, this, ['commandStarted', 'commandSucceeded', 'commandFailed']); - - this.s.state = STATE_CONNECTING; - - // If auth settings have been provided, use them - if (options.auth) { - this.s.pool.connect.apply(this.s.pool, options.auth); - return; - } - - this.s.pool.connect(); - } - - /** - * Destroy the server connection - * - * @param {Boolean} [options.force=false] Force destroy the pool - */ - destroy(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = Object.assign({}, { force: false }, options); - - this.s.state = STATE_DISCONNECTING; - const done = err => { - this.emit('closed'); - this.s.state = STATE_DISCONNECTED; - if (typeof callback === 'function') { - callback(err, null); - } - }; - - if (!this.s.pool) { - return done(); - } - - ['close', 'error', 'timeout', 'parseError', 'connect'].forEach(event => { - this.s.pool.removeAllListeners(event); - }); - - if (this.s.monitorId) { - clearTimeout(this.s.monitorId); - } - - this.s.pool.destroy(options.force, done); - } - - /** - * Immediately schedule monitoring of this server. If there already an attempt being made - * this will be a no-op. - */ - monitor(options) { - options = options || {}; - if (this.s.state !== STATE_CONNECTED || this.s.monitoring) return; - if (this.s.monitorId) clearTimeout(this.s.monitorId); - this.s.monitorFunction(this, options); - } - - /** - * Execute a command - * - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object} cmd The command hash - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.checkKeys=false] Specify if the bson parser should validate keys. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {Boolean} [options.fullResult=false] Return the full envelope instead of just the result document. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {opResultCallback} callback A callback function - */ - command(ns, cmd, options, callback) { - if (typeof options === 'function') { - (callback = options), (options = {}), (options = options || {}); - } - - const error = basicReadValidations(this, options); - if (error) { - return callback(error, null); - } - - // Clone the options - options = Object.assign({}, options, { wireProtocolCommand: false }); - - // Debug log - if (this.s.logger.isDebug()) { - this.s.logger.debug( - `executing command [${JSON.stringify({ - ns, - cmd, - options: debugOptions(DEBUG_FIELDS, options) - })}] against ${this.name}` - ); - } - - // error if collation not supported - if (collationNotSupported(this, cmd)) { - callback(new MongoError(`server ${this.name} does not support collation`)); - return; - } - - wireProtocol.command(this, ns, cmd, options, (err, result) => { - if (err) { - if (options.session && err instanceof MongoNetworkError) { - options.session.serverSession.isDirty = true; - } - - if (isSDAMUnrecoverableError(err, this)) { - this.emit('error', err); - } - } - - callback(err, result); - }); - } - - /** - * Execute a query against the server - * - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object} cmd The command document for the query - * @param {object} options Optional settings - * @param {function} callback - */ - query(ns, cmd, cursorState, options, callback) { - wireProtocol.query(this, ns, cmd, cursorState, options, (err, result) => { - if (err) { - if (options.session && err instanceof MongoNetworkError) { - options.session.serverSession.isDirty = true; - } - - if (isSDAMUnrecoverableError(err, this)) { - this.emit('error', err); - } - } - - callback(err, result); - }); - } - - /** - * Execute a `getMore` against the server - * - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object} cursorState State data associated with the cursor calling this method - * @param {object} options Optional settings - * @param {function} callback - */ - getMore(ns, cursorState, batchSize, options, callback) { - wireProtocol.getMore(this, ns, cursorState, batchSize, options, (err, result) => { - if (err) { - if (options.session && err instanceof MongoNetworkError) { - options.session.serverSession.isDirty = true; - } - - if (isSDAMUnrecoverableError(err, this)) { - this.emit('error', err); - } - } - - callback(err, result); - }); - } - - /** - * Execute a `killCursors` command against the server - * - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object} cursorState State data associated with the cursor calling this method - * @param {function} callback - */ - killCursors(ns, cursorState, callback) { - wireProtocol.killCursors(this, ns, cursorState, (err, result) => { - if (err && isSDAMUnrecoverableError(err, this)) { - this.emit('error', err); - } - - if (typeof callback === 'function') { - callback(err, result); - } - }); - } - - /** - * Insert one or more documents - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of documents to insert - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {opResultCallback} callback A callback function - */ - insert(ns, ops, options, callback) { - executeWriteOperation({ server: this, op: 'insert', ns, ops }, options, callback); - } - - /** - * Perform one or more update operations - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of updates - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {opResultCallback} callback A callback function - */ - update(ns, ops, options, callback) { - executeWriteOperation({ server: this, op: 'update', ns, ops }, options, callback); - } - - /** - * Perform one or more remove operations - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of removes - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {opResultCallback} callback A callback function - */ - remove(ns, ops, options, callback) { - executeWriteOperation({ server: this, op: 'remove', ns, ops }, options, callback); - } -} - -Object.defineProperty(Server.prototype, 'clusterTime', { - get: function() { - return this.s.topology.clusterTime; - }, - set: function(clusterTime) { - this.s.topology.clusterTime = clusterTime; - } -}); - -function basicWriteValidations(server) { - if (!server.s.pool) { - return new MongoError('server instance is not connected'); - } - - if (server.s.pool.isDestroyed()) { - return new MongoError('server instance pool was destroyed'); - } - - return null; -} - -function basicReadValidations(server, options) { - const error = basicWriteValidations(server, options); - if (error) { - return error; - } - - if (options.readPreference && !(options.readPreference instanceof ReadPreference)) { - return new MongoError('readPreference must be an instance of ReadPreference'); - } -} - -function executeWriteOperation(args, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // TODO: once we drop Node 4, use destructuring either here or in arguments. - const server = args.server; - const op = args.op; - const ns = args.ns; - const ops = Array.isArray(args.ops) ? args.ops : [args.ops]; - - const error = basicWriteValidations(server, options); - if (error) { - callback(error, null); - return; - } - - if (collationNotSupported(server, options)) { - callback(new MongoError(`server ${server.name} does not support collation`)); - return; - } - - return wireProtocol[op](server, ns, ops, options, (err, result) => { - if (err) { - if (options.session && err instanceof MongoNetworkError) { - options.session.serverSession.isDirty = true; - } - - if (isSDAMUnrecoverableError(err, server)) { - server.emit('error', err); - } - } - - callback(err, result); - }); -} - -function connectEventHandler(server) { - return function(pool, conn) { - const ismaster = conn.ismaster; - server.s.lastIsMasterMS = conn.lastIsMasterMS; - if (conn.agreedCompressor) { - server.s.pool.options.agreedCompressor = conn.agreedCompressor; - } - - if (conn.zlibCompressionLevel) { - server.s.pool.options.zlibCompressionLevel = conn.zlibCompressionLevel; - } - - if (conn.ismaster.$clusterTime) { - const $clusterTime = conn.ismaster.$clusterTime; - server.s.sclusterTime = $clusterTime; - } - - // log the connection event if requested - if (server.s.logger.isInfo()) { - server.s.logger.info( - `server ${server.name} connected with ismaster [${JSON.stringify(ismaster)}]` - ); - } - - // emit an event indicating that our description has changed - server.emit('descriptionReceived', new ServerDescription(server.description.address, ismaster)); - - // we are connected and handshaked (guaranteed by the pool) - server.s.state = STATE_CONNECTED; - server.emit('connect', server); - }; -} - -function errorEventHandler(server) { - return function(err) { - if (err) { - server.emit('error', new MongoNetworkError(err)); - } - - server.emit('close'); - }; -} - -function parseErrorEventHandler(server) { - return function(err) { - server.s.state = STATE_DISCONNECTED; - server.emit('error', new MongoParseError(err)); - }; -} - -module.exports = Server; diff --git a/scripts/node_modules/mongodb/lib/core/sdam/server_description.js b/scripts/node_modules/mongodb/lib/core/sdam/server_description.js deleted file mode 100644 index 41a5cf5b..00000000 --- a/scripts/node_modules/mongodb/lib/core/sdam/server_description.js +++ /dev/null @@ -1,163 +0,0 @@ -'use strict'; - -// An enumeration of server types we know about -const ServerType = { - Standalone: 'Standalone', - Mongos: 'Mongos', - PossiblePrimary: 'PossiblePrimary', - RSPrimary: 'RSPrimary', - RSSecondary: 'RSSecondary', - RSArbiter: 'RSArbiter', - RSOther: 'RSOther', - RSGhost: 'RSGhost', - Unknown: 'Unknown' -}; - -const WRITABLE_SERVER_TYPES = new Set([ - ServerType.RSPrimary, - ServerType.Standalone, - ServerType.Mongos -]); - -const DATA_BEARING_SERVER_TYPES = new Set([ - ServerType.RSPrimary, - ServerType.RSSecondary, - ServerType.Mongos, - ServerType.Standalone -]); - -const ISMASTER_FIELDS = [ - 'minWireVersion', - 'maxWireVersion', - 'maxBsonObjectSize', - 'maxMessageSizeBytes', - 'maxWriteBatchSize', - 'compression', - 'me', - 'hosts', - 'passives', - 'arbiters', - 'tags', - 'setName', - 'setVersion', - 'electionId', - 'primary', - 'logicalSessionTimeoutMinutes', - 'saslSupportedMechs', - '__nodejs_mock_server__', - '$clusterTime' -]; - -/** - * The client's view of a single server, based on the most recent ismaster outcome. - * - * Internal type, not meant to be directly instantiated - */ -class ServerDescription { - /** - * Create a ServerDescription - * @param {String} address The address of the server - * @param {Object} [ismaster] An optional ismaster response for this server - * @param {Object} [options] Optional settings - * @param {Number} [options.roundTripTime] The round trip time to ping this server (in ms) - */ - constructor(address, ismaster, options) { - options = options || {}; - ismaster = Object.assign( - { - minWireVersion: 0, - maxWireVersion: 0, - hosts: [], - passives: [], - arbiters: [], - tags: [] - }, - ismaster - ); - - this.address = address; - this.error = options.error || null; - this.roundTripTime = options.roundTripTime || 0; - this.lastUpdateTime = Date.now(); - this.lastWriteDate = ismaster.lastWrite ? ismaster.lastWrite.lastWriteDate : null; - this.opTime = ismaster.lastWrite ? ismaster.lastWrite.opTime : null; - this.type = parseServerType(ismaster); - - // direct mappings - ISMASTER_FIELDS.forEach(field => { - if (typeof ismaster[field] !== 'undefined') this[field] = ismaster[field]; - }); - - // normalize case for hosts - if (this.me) this.me = this.me.toLowerCase(); - this.hosts = this.hosts.map(host => host.toLowerCase()); - this.passives = this.passives.map(host => host.toLowerCase()); - this.arbiters = this.arbiters.map(host => host.toLowerCase()); - } - - get allHosts() { - return this.hosts.concat(this.arbiters).concat(this.passives); - } - - /** - * @return {Boolean} Is this server available for reads - */ - get isReadable() { - return this.type === ServerType.RSSecondary || this.isWritable; - } - - /** - * @return {Boolean} Is this server data bearing - */ - get isDataBearing() { - return DATA_BEARING_SERVER_TYPES.has(this.type); - } - - /** - * @return {Boolean} Is this server available for writes - */ - get isWritable() { - return WRITABLE_SERVER_TYPES.has(this.type); - } -} - -/** - * Parses an `ismaster` message and determines the server type - * - * @param {Object} ismaster The `ismaster` message to parse - * @return {ServerType} - */ -function parseServerType(ismaster) { - if (!ismaster || !ismaster.ok) { - return ServerType.Unknown; - } - - if (ismaster.isreplicaset) { - return ServerType.RSGhost; - } - - if (ismaster.msg && ismaster.msg === 'isdbgrid') { - return ServerType.Mongos; - } - - if (ismaster.setName) { - if (ismaster.hidden) { - return ServerType.RSOther; - } else if (ismaster.ismaster) { - return ServerType.RSPrimary; - } else if (ismaster.secondary) { - return ServerType.RSSecondary; - } else if (ismaster.arbiterOnly) { - return ServerType.RSArbiter; - } else { - return ServerType.RSOther; - } - } - - return ServerType.Standalone; -} - -module.exports = { - ServerDescription, - ServerType -}; diff --git a/scripts/node_modules/mongodb/lib/core/sdam/server_selectors.js b/scripts/node_modules/mongodb/lib/core/sdam/server_selectors.js deleted file mode 100644 index f26d419e..00000000 --- a/scripts/node_modules/mongodb/lib/core/sdam/server_selectors.js +++ /dev/null @@ -1,244 +0,0 @@ -'use strict'; -const ServerType = require('./server_description').ServerType; -const TopologyType = require('./topology_description').TopologyType; -const ReadPreference = require('../topologies/read_preference'); -const MongoError = require('../error').MongoError; - -// max staleness constants -const IDLE_WRITE_PERIOD = 10000; -const SMALLEST_MAX_STALENESS_SECONDS = 90; - -/** - * Returns a server selector that selects for writable servers - */ -function writableServerSelector() { - return function(topologyDescription, servers) { - return latencyWindowReducer(topologyDescription, servers.filter(s => s.isWritable)); - }; -} - -/** - * Reduces the passed in array of servers by the rules of the "Max Staleness" specification - * found here: https://github.com/mongodb/specifications/blob/master/source/max-staleness/max-staleness.rst - * - * @param {ReadPreference} readPreference The read preference providing max staleness guidance - * @param {topologyDescription} topologyDescription The topology description - * @param {ServerDescription[]} servers The list of server descriptions to be reduced - * @return {ServerDescription[]} The list of servers that satisfy the requirements of max staleness - */ -function maxStalenessReducer(readPreference, topologyDescription, servers) { - if (readPreference.maxStalenessSeconds == null || readPreference.maxStalenessSeconds < 0) { - return servers; - } - - const maxStaleness = readPreference.maxStalenessSeconds; - const maxStalenessVariance = - (topologyDescription.heartbeatFrequencyMS + IDLE_WRITE_PERIOD) / 1000; - if (maxStaleness < maxStalenessVariance) { - throw new MongoError(`maxStalenessSeconds must be at least ${maxStalenessVariance} seconds`); - } - - if (maxStaleness < SMALLEST_MAX_STALENESS_SECONDS) { - throw new MongoError( - `maxStalenessSeconds must be at least ${SMALLEST_MAX_STALENESS_SECONDS} seconds` - ); - } - - if (topologyDescription.type === TopologyType.ReplicaSetWithPrimary) { - const primary = servers.filter(primaryFilter)[0]; - return servers.reduce((result, server) => { - const stalenessMS = - server.lastUpdateTime - - server.lastWriteDate - - (primary.lastUpdateTime - primary.lastWriteDate) + - topologyDescription.heartbeatFrequencyMS; - - const staleness = stalenessMS / 1000; - if (staleness <= readPreference.maxStalenessSeconds) result.push(server); - return result; - }, []); - } else if (topologyDescription.type === TopologyType.ReplicaSetNoPrimary) { - const sMax = servers.reduce((max, s) => (s.lastWriteDate > max.lastWriteDate ? s : max)); - return servers.reduce((result, server) => { - const stalenessMS = - sMax.lastWriteDate - server.lastWriteDate + topologyDescription.heartbeatFrequencyMS; - - const staleness = stalenessMS / 1000; - if (staleness <= readPreference.maxStalenessSeconds) result.push(server); - return result; - }, []); - } - - return servers; -} - -/** - * Determines whether a server's tags match a given set of tags - * - * @param {String[]} tagSet The requested tag set to match - * @param {String[]} serverTags The server's tags - */ -function tagSetMatch(tagSet, serverTags) { - const keys = Object.keys(tagSet); - const serverTagKeys = Object.keys(serverTags); - for (let i = 0; i < keys.length; ++i) { - const key = keys[i]; - if (serverTagKeys.indexOf(key) === -1 || serverTags[key] !== tagSet[key]) { - return false; - } - } - - return true; -} - -/** - * Reduces a set of server descriptions based on tags requested by the read preference - * - * @param {ReadPreference} readPreference The read preference providing the requested tags - * @param {ServerDescription[]} servers The list of server descriptions to reduce - * @return {ServerDescription[]} The list of servers matching the requested tags - */ -function tagSetReducer(readPreference, servers) { - if ( - readPreference.tags == null || - (Array.isArray(readPreference.tags) && readPreference.tags.length === 0) - ) { - return servers; - } - - for (let i = 0; i < readPreference.tags.length; ++i) { - const tagSet = readPreference.tags[i]; - const serversMatchingTagset = servers.reduce((matched, server) => { - if (tagSetMatch(tagSet, server.tags)) matched.push(server); - return matched; - }, []); - - if (serversMatchingTagset.length) { - return serversMatchingTagset; - } - } - - return []; -} - -/** - * Reduces a list of servers to ensure they fall within an acceptable latency window. This is - * further specified in the "Server Selection" specification, found here: - * https://github.com/mongodb/specifications/blob/master/source/server-selection/server-selection.rst - * - * @param {topologyDescription} topologyDescription The topology description - * @param {ServerDescription[]} servers The list of servers to reduce - * @returns {ServerDescription[]} The servers which fall within an acceptable latency window - */ -function latencyWindowReducer(topologyDescription, servers) { - const low = servers.reduce( - (min, server) => (min === -1 ? server.roundTripTime : Math.min(server.roundTripTime, min)), - -1 - ); - - const high = low + topologyDescription.localThresholdMS; - - return servers.reduce((result, server) => { - if (server.roundTripTime <= high && server.roundTripTime >= low) result.push(server); - return result; - }, []); -} - -// filters -function primaryFilter(server) { - return server.type === ServerType.RSPrimary; -} - -function secondaryFilter(server) { - return server.type === ServerType.RSSecondary; -} - -function nearestFilter(server) { - return server.type === ServerType.RSSecondary || server.type === ServerType.RSPrimary; -} - -function knownFilter(server) { - return server.type !== ServerType.Unknown; -} - -/** - * Returns a function which selects servers based on a provided read preference - * - * @param {ReadPreference} readPreference The read preference to select with - */ -function readPreferenceServerSelector(readPreference) { - if (!readPreference.isValid()) { - throw new TypeError('Invalid read preference specified'); - } - - return function(topologyDescription, servers) { - const commonWireVersion = topologyDescription.commonWireVersion; - if ( - commonWireVersion && - (readPreference.minWireVersion && readPreference.minWireVersion > commonWireVersion) - ) { - throw new MongoError( - `Minimum wire version '${ - readPreference.minWireVersion - }' required, but found '${commonWireVersion}'` - ); - } - - if ( - topologyDescription.type === TopologyType.Single || - topologyDescription.type === TopologyType.Sharded - ) { - return latencyWindowReducer(topologyDescription, servers.filter(knownFilter)); - } - - if (readPreference.mode === ReadPreference.PRIMARY) { - return servers.filter(primaryFilter); - } - - if (readPreference.mode === ReadPreference.SECONDARY) { - return latencyWindowReducer( - topologyDescription, - tagSetReducer( - readPreference, - maxStalenessReducer(readPreference, topologyDescription, servers) - ) - ).filter(secondaryFilter); - } else if (readPreference.mode === ReadPreference.NEAREST) { - return latencyWindowReducer( - topologyDescription, - tagSetReducer( - readPreference, - maxStalenessReducer(readPreference, topologyDescription, servers) - ) - ).filter(nearestFilter); - } else if (readPreference.mode === ReadPreference.SECONDARY_PREFERRED) { - const result = latencyWindowReducer( - topologyDescription, - tagSetReducer( - readPreference, - maxStalenessReducer(readPreference, topologyDescription, servers) - ) - ).filter(secondaryFilter); - - return result.length === 0 ? servers.filter(primaryFilter) : result; - } else if (readPreference.mode === ReadPreference.PRIMARY_PREFERRED) { - const result = servers.filter(primaryFilter); - if (result.length) { - return result; - } - - return latencyWindowReducer( - topologyDescription, - tagSetReducer( - readPreference, - maxStalenessReducer(readPreference, topologyDescription, servers) - ) - ).filter(secondaryFilter); - } - }; -} - -module.exports = { - writableServerSelector, - readPreferenceServerSelector -}; diff --git a/scripts/node_modules/mongodb/lib/core/sdam/srv_polling.js b/scripts/node_modules/mongodb/lib/core/sdam/srv_polling.js deleted file mode 100644 index 115ae45c..00000000 --- a/scripts/node_modules/mongodb/lib/core/sdam/srv_polling.js +++ /dev/null @@ -1,135 +0,0 @@ -'use strict'; - -const Logger = require('../connection/logger'); -const EventEmitter = require('events').EventEmitter; -const dns = require('dns'); -/** - * Determines whether a provided address matches the provided parent domain in order - * to avoid certain attack vectors. - * - * @param {String} srvAddress The address to check against a domain - * @param {String} parentDomain The domain to check the provided address against - * @return {Boolean} Whether the provided address matches the parent domain - */ -function matchesParentDomain(srvAddress, parentDomain) { - const regex = /^.*?\./; - const srv = `.${srvAddress.replace(regex, '')}`; - const parent = `.${parentDomain.replace(regex, '')}`; - return srv.endsWith(parent); -} - -class SrvPollingEvent { - constructor(srvRecords) { - this.srvRecords = srvRecords; - } - - addresses() { - return new Set(this.srvRecords.map(record => `${record.name}:${record.port}`)); - } -} - -class SrvPoller extends EventEmitter { - /** - * @param {object} options - * @param {string} options.srvHost - * @param {number} [options.heartbeatFrequencyMS] - * @param {function} [options.logger] - * @param {string} [options.loggerLevel] - */ - constructor(options) { - super(); - - if (!options || !options.srvHost) { - throw new TypeError('options for SrvPoller must exist and include srvHost'); - } - - this.srvHost = options.srvHost; - this.rescanSrvIntervalMS = 60000; - this.heartbeatFrequencyMS = options.heartbeatFrequencyMS || 10000; - this.logger = Logger('srvPoller', options); - - this.haMode = false; - this.generation = 0; - - this._timeout = null; - } - - get srvAddress() { - return `_mongodb._tcp.${this.srvHost}`; - } - - get intervalMS() { - return this.haMode ? this.heartbeatFrequencyMS : this.rescanSrvIntervalMs; - } - - start() { - if (!this._timeout) { - this.schedule(); - } - } - - stop() { - if (this._timeout) { - clearTimeout(this._timeout); - this.generation += 1; - this._timeout = null; - } - } - - schedule() { - clearTimeout(this._timeout); - this._timeout = setTimeout(() => this._poll(), this.intervalMS); - } - - success(srvRecords) { - this.haMode = false; - this.schedule(); - this.emit('srvRecordDiscovery', new SrvPollingEvent(srvRecords)); - } - - failure(message, obj) { - this.logger.warn(message, obj); - this.haMode = true; - this.schedule(); - } - - parentDomainMismatch(srvRecord) { - this.logger.warn( - `parent domain mismatch on SRV record (${srvRecord.name}:${srvRecord.port})`, - srvRecord - ); - } - - _poll() { - const generation = this.generation; - dns.resolveSrv(this.srvAddress, (err, srvRecords) => { - if (generation !== this.generation) { - return; - } - - if (err) { - this.failure('DNS error', err); - return; - } - - const finalAddresses = []; - srvRecords.forEach(record => { - if (matchesParentDomain(record.name, this.srvHost)) { - finalAddresses.push(record); - } else { - this.parentDomainMismatch(record); - } - }); - - if (!finalAddresses.length) { - this.failure('No valid addresses found at host'); - return; - } - - this.success(finalAddresses); - }); - } -} - -module.exports.SrvPollingEvent = SrvPollingEvent; -module.exports.SrvPoller = SrvPoller; diff --git a/scripts/node_modules/mongodb/lib/core/sdam/topology.js b/scripts/node_modules/mongodb/lib/core/sdam/topology.js deleted file mode 100644 index 5dab4b36..00000000 --- a/scripts/node_modules/mongodb/lib/core/sdam/topology.js +++ /dev/null @@ -1,1186 +0,0 @@ -'use strict'; -const EventEmitter = require('events'); -const ServerDescription = require('./server_description').ServerDescription; -const ServerType = require('./server_description').ServerType; -const TopologyDescription = require('./topology_description').TopologyDescription; -const TopologyType = require('./topology_description').TopologyType; -const monitoring = require('./monitoring'); -const calculateDurationInMs = require('../utils').calculateDurationInMs; -const MongoTimeoutError = require('../error').MongoTimeoutError; -const Server = require('./server'); -const relayEvents = require('../utils').relayEvents; -const ReadPreference = require('../topologies/read_preference'); -const readPreferenceServerSelector = require('./server_selectors').readPreferenceServerSelector; -const writableServerSelector = require('./server_selectors').writableServerSelector; -const isRetryableWritesSupported = require('../topologies/shared').isRetryableWritesSupported; -const CoreCursor = require('../cursor').CoreCursor; -const deprecate = require('util').deprecate; -const BSON = require('../connection/utils').retrieveBSON(); -const createCompressionInfo = require('../topologies/shared').createCompressionInfo; -const isRetryableError = require('../error').isRetryableError; -const isSDAMUnrecoverableError = require('../error').isSDAMUnrecoverableError; -const ClientSession = require('../sessions').ClientSession; -const createClientInfo = require('../topologies/shared').createClientInfo; -const MongoError = require('../error').MongoError; -const resolveClusterTime = require('../topologies/shared').resolveClusterTime; -const SrvPoller = require('./srv_polling').SrvPoller; -const getMMAPError = require('../topologies/shared').getMMAPError; - -// Global state -let globalTopologyCounter = 0; - -// Constants -const TOPOLOGY_DEFAULTS = { - localThresholdMS: 15, - serverSelectionTimeoutMS: 30000, - heartbeatFrequencyMS: 10000, - minHeartbeatFrequencyMS: 500 -}; - -// events that we relay to the `Topology` -const SERVER_RELAY_EVENTS = [ - 'serverHeartbeatStarted', - 'serverHeartbeatSucceeded', - 'serverHeartbeatFailed', - 'commandStarted', - 'commandSucceeded', - 'commandFailed', - - // NOTE: Legacy events - 'monitoring' -]; - -// all events we listen to from `Server` instances -const LOCAL_SERVER_EVENTS = SERVER_RELAY_EVENTS.concat([ - 'error', - 'connect', - 'descriptionReceived', - 'close', - 'ended' -]); - -/** - * A container of server instances representing a connection to a MongoDB topology. - * - * @fires Topology#serverOpening - * @fires Topology#serverClosed - * @fires Topology#serverDescriptionChanged - * @fires Topology#topologyOpening - * @fires Topology#topologyClosed - * @fires Topology#topologyDescriptionChanged - * @fires Topology#serverHeartbeatStarted - * @fires Topology#serverHeartbeatSucceeded - * @fires Topology#serverHeartbeatFailed - */ -class Topology extends EventEmitter { - /** - * Create a topology - * - * @param {Array|String} [seedlist] a string list, or array of Server instances to connect to - * @param {Object} [options] Optional settings - * @param {Number} [options.localThresholdMS=15] The size of the latency window for selecting among multiple suitable servers - * @param {Number} [options.serverSelectionTimeoutMS=30000] How long to block for server selection before throwing an error - * @param {Number} [options.heartbeatFrequencyMS=10000] The frequency with which topology updates are scheduled - */ - constructor(seedlist, options) { - super(); - if (typeof options === 'undefined' && typeof seedlist !== 'string') { - options = seedlist; - seedlist = []; - - // this is for legacy single server constructor support - if (options.host) { - seedlist.push({ host: options.host, port: options.port }); - } - } - - seedlist = seedlist || []; - if (typeof seedlist === 'string') { - seedlist = parseStringSeedlist(seedlist); - } - - options = Object.assign({}, TOPOLOGY_DEFAULTS, options); - - const topologyType = topologyTypeFromSeedlist(seedlist, options); - const topologyId = globalTopologyCounter++; - const serverDescriptions = seedlist.reduce((result, seed) => { - if (seed.domain_socket) seed.host = seed.domain_socket; - const address = seed.port ? `${seed.host}:${seed.port}` : `${seed.host}:27017`; - result.set(address, new ServerDescription(address)); - return result; - }, new Map()); - - this.s = { - // the id of this topology - id: topologyId, - // passed in options - options, - // initial seedlist of servers to connect to - seedlist: seedlist, - // the topology description - description: new TopologyDescription( - topologyType, - serverDescriptions, - options.replicaSet, - null, - null, - null, - options - ), - serverSelectionTimeoutMS: options.serverSelectionTimeoutMS, - heartbeatFrequencyMS: options.heartbeatFrequencyMS, - minHeartbeatIntervalMS: options.minHeartbeatIntervalMS, - // allow users to override the cursor factory - Cursor: options.cursorFactory || CoreCursor, - // the bson parser - bson: - options.bson || - new BSON([ - BSON.Binary, - BSON.Code, - BSON.DBRef, - BSON.Decimal128, - BSON.Double, - BSON.Int32, - BSON.Long, - BSON.Map, - BSON.MaxKey, - BSON.MinKey, - BSON.ObjectId, - BSON.BSONRegExp, - BSON.Symbol, - BSON.Timestamp - ]), - // a map of server instances to normalized addresses - servers: new Map(), - // Server Session Pool - sessionPool: null, - // Active client sessions - sessions: new Set(), - // Promise library - promiseLibrary: options.promiseLibrary || Promise, - credentials: options.credentials, - clusterTime: null, - - // timer management - monitorTimers: [], - iterationTimers: [] - }; - - // amend options for server instance creation - this.s.options.compression = { compressors: createCompressionInfo(options) }; - - // add client info - this.s.clientInfo = createClientInfo(options); - - if (options.srvHost) { - this.s.srvPoller = - options.srvPoller || - new SrvPoller({ - heartbeatFrequencyMS: this.s.heartbeatFrequencyMS, - srvHost: options.srvHost, // TODO: GET THIS - logger: options.logger, - loggerLevel: options.loggerLevel - }); - this.s.detectTopologyDescriptionChange = ev => { - const previousType = ev.previousDescription.type; - const newType = ev.newDescription.type; - - if (previousType !== TopologyType.Sharded && newType === TopologyType.Sharded) { - this.s.handleSrvPolling = srvPollingHandler(this); - this.s.srvPoller.on('srvRecordDiscovery', this.s.handleSrvPolling); - this.s.srvPoller.start(); - } - }; - - this.on('topologyDescriptionChanged', this.s.detectTopologyDescriptionChange); - } - } - - /** - * @return A `TopologyDescription` for this topology - */ - get description() { - return this.s.description; - } - - get parserType() { - return BSON.native ? 'c++' : 'js'; - } - - /** - * All raw connections - * @method - * @return {Connection[]} - */ - connections() { - return Array.from(this.s.servers.values()).reduce((result, server) => { - return result.concat(server.s.pool.allConnections()); - }, []); - } - - /** - * Initiate server connect - * - * @param {Object} [options] Optional settings - * @param {Array} [options.auth=null] Array of auth options to apply on connect - * @param {function} [callback] An optional callback called once on the first connected server - */ - connect(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // emit SDAM monitoring events - this.emit('topologyOpening', new monitoring.TopologyOpeningEvent(this.s.id)); - - // emit an event for the topology change - this.emit( - 'topologyDescriptionChanged', - new monitoring.TopologyDescriptionChangedEvent( - this.s.id, - new TopologyDescription(TopologyType.Unknown), // initial is always Unknown - this.s.description - ) - ); - - connectServers(this, Array.from(this.s.description.servers.values())); - this.s.connected = true; - - // otherwise, wait for a server to properly connect based on user provided read preference, - // or primary. - - translateReadPreference(options); - const readPreference = options.readPreference || ReadPreference.primary; - - this.selectServer(readPreferenceServerSelector(readPreference), options, (err, server) => { - if (err) { - if (typeof callback === 'function') { - callback(err, null); - } else { - this.emit('error', err); - } - - return; - } - - const errorHandler = err => { - server.removeListener('connect', connectHandler); - if (typeof callback === 'function') callback(err, null); - }; - - const connectHandler = (_, err) => { - server.removeListener('error', errorHandler); - this.emit('open', err, this); - this.emit('connect', this); - - if (typeof callback === 'function') callback(err, this); - }; - - const STATE_CONNECTING = 1; - if (server.s.state === STATE_CONNECTING) { - server.once('error', errorHandler); - server.once('connect', connectHandler); - return; - } - - connectHandler(); - }); - } - - /** - * Close this topology - */ - close(options, callback) { - if (typeof options === 'function') { - callback = options; - options = {}; - } - - if (typeof options === 'boolean') { - options = { force: options }; - } - - options = options || {}; - - // clear all existing monitor timers - this.s.monitorTimers.map(timer => clearTimeout(timer)); - this.s.monitorTimers = []; - - this.s.iterationTimers.map(timer => clearTimeout(timer)); - this.s.iterationTimers = []; - - if (this.s.sessionPool) { - this.s.sessions.forEach(session => session.endSession()); - this.s.sessionPool.endAllPooledSessions(); - } - - if (this.s.srvPoller) { - this.s.srvPoller.stop(); - if (this.s.handleSrvPolling) { - this.s.srvPoller.removeListener('srvRecordDiscovery', this.s.handleSrvPolling); - delete this.s.handleSrvPolling; - } - } - - if (this.s.detectTopologyDescriptionChange) { - this.removeListener('topologyDescriptionChanged', this.s.detectTopologyDescriptionChange); - delete this.s.detectTopologyDescriptionChange; - } - - const servers = this.s.servers; - if (servers.size === 0) { - this.s.connected = false; - if (typeof callback === 'function') { - callback(null, null); - } - - return; - } - - // destroy all child servers - let destroyed = 0; - servers.forEach(server => - destroyServer(server, this, options, () => { - destroyed++; - if (destroyed === servers.size) { - // emit an event for close - this.emit('topologyClosed', new monitoring.TopologyClosedEvent(this.s.id)); - - this.s.connected = false; - if (typeof callback === 'function') { - callback(null, null); - } - } - }) - ); - } - - /** - * Selects a server according to the selection predicate provided - * - * @param {function} [selector] An optional selector to select servers by, defaults to a random selection within a latency window - * @param {object} [options] Optional settings related to server selection - * @param {number} [options.serverSelectionTimeoutMS] How long to block for server selection before throwing an error - * @param {function} callback The callback used to indicate success or failure - * @return {Server} An instance of a `Server` meeting the criteria of the predicate provided - */ - selectServer(selector, options, callback) { - if (typeof options === 'function') { - callback = options; - if (typeof selector !== 'function') { - options = selector; - - let readPreference; - if (selector instanceof ReadPreference) { - readPreference = selector; - } else { - translateReadPreference(options); - readPreference = options.readPreference || ReadPreference.primary; - } - - selector = readPreferenceServerSelector(readPreference); - } else { - options = {}; - } - } - - options = Object.assign( - {}, - { serverSelectionTimeoutMS: this.s.serverSelectionTimeoutMS }, - options - ); - - const isSharded = this.description.type === TopologyType.Sharded; - const session = options.session; - const transaction = session && session.transaction; - - if (isSharded && transaction && transaction.server) { - callback(null, transaction.server); - return; - } - - // clear out any existing iteration timers - this.s.iterationTimers.map(timer => clearTimeout(timer)); - this.s.iterationTimers = []; - - selectServers( - this, - selector, - options.serverSelectionTimeoutMS, - process.hrtime(), - (err, servers) => { - if (err) return callback(err, null); - - const selectedServer = randomSelection(servers); - if (isSharded && transaction && transaction.isActive) { - transaction.pinServer(selectedServer); - } - - callback(null, selectedServer); - } - ); - } - - // Sessions related methods - - /** - * @return Whether the topology should initiate selection to determine session support - */ - shouldCheckForSessionSupport() { - return ( - (this.description.type === TopologyType.Single && !this.description.hasKnownServers) || - !this.description.hasDataBearingServers - ); - } - - /** - * @return Whether sessions are supported on the current topology - */ - hasSessionSupport() { - return this.description.logicalSessionTimeoutMinutes != null; - } - - /** - * Start a logical session - */ - startSession(options, clientOptions) { - const session = new ClientSession(this, this.s.sessionPool, options, clientOptions); - session.once('ended', () => { - this.s.sessions.delete(session); - }); - - this.s.sessions.add(session); - return session; - } - - /** - * Send endSessions command(s) with the given session ids - * - * @param {Array} sessions The sessions to end - * @param {function} [callback] - */ - endSessions(sessions, callback) { - if (!Array.isArray(sessions)) { - sessions = [sessions]; - } - - this.command( - 'admin.$cmd', - { endSessions: sessions }, - { readPreference: ReadPreference.primaryPreferred, noResponse: true }, - () => { - // intentionally ignored, per spec - if (typeof callback === 'function') callback(); - } - ); - } - - /** - * Update the internal TopologyDescription with a ServerDescription - * - * @param {object} serverDescription The server to update in the internal list of server descriptions - */ - serverUpdateHandler(serverDescription) { - if (!this.s.description.hasServer(serverDescription.address)) { - return; - } - - // these will be used for monitoring events later - const previousTopologyDescription = this.s.description; - const previousServerDescription = this.s.description.servers.get(serverDescription.address); - - // first update the TopologyDescription - this.s.description = this.s.description.update(serverDescription); - if (this.s.description.compatibilityError) { - this.emit('error', new MongoError(this.s.description.compatibilityError)); - return; - } - - // emit monitoring events for this change - this.emit( - 'serverDescriptionChanged', - new monitoring.ServerDescriptionChangedEvent( - this.s.id, - serverDescription.address, - previousServerDescription, - this.s.description.servers.get(serverDescription.address) - ) - ); - - // update server list from updated descriptions - updateServers(this, serverDescription); - - // Driver Sessions Spec: "Whenever a driver receives a cluster time from - // a server it MUST compare it to the current highest seen cluster time - // for the deployment. If the new cluster time is higher than the - // highest seen cluster time it MUST become the new highest seen cluster - // time. Two cluster times are compared using only the BsonTimestamp - // value of the clusterTime embedded field." - const clusterTime = serverDescription.$clusterTime; - if (clusterTime) { - resolveClusterTime(this, clusterTime); - } - - this.emit( - 'topologyDescriptionChanged', - new monitoring.TopologyDescriptionChangedEvent( - this.s.id, - previousTopologyDescription, - this.s.description - ) - ); - } - - auth(credentials, callback) { - if (typeof credentials === 'function') (callback = credentials), (credentials = null); - if (typeof callback === 'function') callback(null, true); - } - - logout(callback) { - if (typeof callback === 'function') callback(null, true); - } - - // Basic operation support. Eventually this should be moved into command construction - // during the command refactor. - - /** - * Insert one or more documents - * - * @param {String} ns The full qualified namespace for this operation - * @param {Array} ops An array of documents to insert - * @param {Boolean} [options.ordered=true] Execute in order or out of order - * @param {Object} [options.writeConcern] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields - * @param {ClientSession} [options.session] Session to use for the operation - * @param {boolean} [options.retryWrites] Enable retryable writes for this operation - * @param {opResultCallback} callback A callback function - */ - insert(ns, ops, options, callback) { - executeWriteOperation({ topology: this, op: 'insert', ns, ops }, options, callback); - } - - /** - * Perform one or more update operations - * - * @param {string} ns The fully qualified namespace for this operation - * @param {array} ops An array of updates - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields - * @param {ClientSession} [options.session] Session to use for the operation - * @param {boolean} [options.retryWrites] Enable retryable writes for this operation - * @param {opResultCallback} callback A callback function - */ - update(ns, ops, options, callback) { - executeWriteOperation({ topology: this, op: 'update', ns, ops }, options, callback); - } - - /** - * Perform one or more remove operations - * - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of removes - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {boolean} [options.retryWrites] Enable retryable writes for this operation - * @param {opResultCallback} callback A callback function - */ - remove(ns, ops, options, callback) { - executeWriteOperation({ topology: this, op: 'remove', ns, ops }, options, callback); - } - - /** - * Execute a command - * - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object} cmd The command hash - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @param {Connection} [options.connection] Specify connection object to execute command against - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {opResultCallback} callback A callback function - */ - command(ns, cmd, options, callback) { - if (typeof options === 'function') { - (callback = options), (options = {}), (options = options || {}); - } - - translateReadPreference(options); - const readPreference = options.readPreference || ReadPreference.primary; - - this.selectServer(readPreferenceServerSelector(readPreference), options, (err, server) => { - if (err) { - callback(err, null); - return; - } - - const willRetryWrite = - !options.retrying && - !!options.retryWrites && - options.session && - isRetryableWritesSupported(this) && - !options.session.inTransaction() && - isWriteCommand(cmd); - - const cb = (err, result) => { - if (!err) return callback(null, result); - if (!isRetryableError(err)) { - return callback(err); - } - - if (willRetryWrite) { - const newOptions = Object.assign({}, options, { retrying: true }); - return this.command(ns, cmd, newOptions, callback); - } - - return callback(err); - }; - - // increment and assign txnNumber - if (willRetryWrite) { - options.session.incrementTransactionNumber(); - options.willRetryWrite = willRetryWrite; - } - - server.command(ns, cmd, options, cb); - }); - } - - /** - * Create a new cursor - * - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object|Long} cmd Can be either a command returning a cursor or a cursorId - * @param {object} [options] Options for the cursor - * @param {object} [options.batchSize=0] Batchsize for the operation - * @param {array} [options.documents=[]] Initial documents list for cursor - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {object} [options.topology] The internal topology of the created cursor - * @returns {Cursor} - */ - cursor(ns, cmd, options) { - options = options || {}; - const topology = options.topology || this; - const CursorClass = options.cursorFactory || this.s.Cursor; - translateReadPreference(options); - - return new CursorClass(topology, ns, cmd, options); - } - - get clientInfo() { - return this.s.clientInfo; - } - - // Legacy methods for compat with old topology types - isConnected() { - // console.log('not implemented: `isConnected`'); - return true; - } - - isDestroyed() { - // console.log('not implemented: `isDestroyed`'); - return false; - } - - unref() { - console.log('not implemented: `unref`'); - } - - // NOTE: There are many places in code where we explicitly check the last isMaster - // to do feature support detection. This should be done any other way, but for - // now we will just return the first isMaster seen, which should suffice. - lastIsMaster() { - const serverDescriptions = Array.from(this.description.servers.values()); - if (serverDescriptions.length === 0) return {}; - - const sd = serverDescriptions.filter(sd => sd.type !== ServerType.Unknown)[0]; - const result = sd || { maxWireVersion: this.description.commonWireVersion }; - return result; - } - - get logicalSessionTimeoutMinutes() { - return this.description.logicalSessionTimeoutMinutes; - } - - get bson() { - return this.s.bson; - } -} - -Object.defineProperty(Topology.prototype, 'clusterTime', { - enumerable: true, - get: function() { - return this.s.clusterTime; - }, - set: function(clusterTime) { - this.s.clusterTime = clusterTime; - } -}); - -// legacy aliases -Topology.prototype.destroy = deprecate( - Topology.prototype.close, - 'destroy() is deprecated, please use close() instead' -); - -const RETRYABLE_WRITE_OPERATIONS = ['findAndModify', 'insert', 'update', 'delete']; -function isWriteCommand(command) { - return RETRYABLE_WRITE_OPERATIONS.some(op => command[op]); -} - -/** - * Destroys a server, and removes all event listeners from the instance - * - * @param {Server} server - */ -function destroyServer(server, topology, options, callback) { - options = options || {}; - LOCAL_SERVER_EVENTS.forEach(event => server.removeAllListeners(event)); - - server.destroy(options, () => { - topology.emit( - 'serverClosed', - new monitoring.ServerClosedEvent(topology.s.id, server.description.address) - ); - - if (typeof callback === 'function') callback(null, null); - }); -} - -/** - * Parses a basic seedlist in string form - * - * @param {string} seedlist The seedlist to parse - */ -function parseStringSeedlist(seedlist) { - return seedlist.split(',').map(seed => ({ - host: seed.split(':')[0], - port: seed.split(':')[1] || 27017 - })); -} - -function topologyTypeFromSeedlist(seedlist, options) { - const replicaSet = options.replicaSet || options.setName || options.rs_name; - if (seedlist.length === 1 && !replicaSet) return TopologyType.Single; - if (replicaSet) return TopologyType.ReplicaSetNoPrimary; - return TopologyType.Unknown; -} - -function randomSelection(array) { - return array[Math.floor(Math.random() * array.length)]; -} - -/** - * Selects servers using the provided selector - * - * @private - * @param {Topology} topology The topology to select servers from - * @param {function} selector The actual predicate used for selecting servers - * @param {Number} timeout The max time we are willing wait for selection - * @param {Number} start A high precision timestamp for the start of the selection process - * @param {function} callback The callback used to convey errors or the resultant servers - */ -function selectServers(topology, selector, timeout, start, callback) { - const duration = calculateDurationInMs(start); - if (duration >= timeout) { - return callback( - new MongoTimeoutError(`Server selection timed out after ${timeout} ms`), - topology.description.error - ); - } - - // ensure we are connected - if (!topology.s.connected) { - topology.connect(); - - // we want to make sure we're still within the requested timeout window - const failToConnectTimer = setTimeout(() => { - topology.removeListener('connect', connectHandler); - callback( - new MongoTimeoutError('Server selection timed out waiting to connect'), - topology.description.error - ); - }, timeout - duration); - - const connectHandler = () => { - clearTimeout(failToConnectTimer); - selectServers(topology, selector, timeout, process.hrtime(), callback); - }; - - topology.once('connect', connectHandler); - return; - } - - // otherwise, attempt server selection - const serverDescriptions = Array.from(topology.description.servers.values()); - let descriptions; - - // support server selection by options with readPreference - if (typeof selector === 'object') { - const readPreference = selector.readPreference - ? selector.readPreference - : ReadPreference.primary; - - selector = readPreferenceServerSelector(readPreference); - } - - try { - descriptions = selector - ? selector(topology.description, serverDescriptions) - : serverDescriptions; - } catch (e) { - return callback(e, null); - } - - if (descriptions.length) { - const servers = descriptions.map(description => topology.s.servers.get(description.address)); - return callback(null, servers); - } - - const retrySelection = () => { - // clear all existing monitor timers - topology.s.monitorTimers.map(timer => clearTimeout(timer)); - topology.s.monitorTimers = []; - - // ensure all server monitors attempt monitoring soon - topology.s.servers.forEach(server => { - const timer = setTimeout( - () => server.monitor({ heartbeatFrequencyMS: topology.description.heartbeatFrequencyMS }), - TOPOLOGY_DEFAULTS.minHeartbeatFrequencyMS - ); - - topology.s.monitorTimers.push(timer); - }); - - const descriptionChangedHandler = () => { - // successful iteration, clear the check timer - clearTimeout(iterationTimer); - topology.s.iterationTimers.splice(timerIndex, 1); - - // topology description has changed due to monitoring, reattempt server selection - selectServers(topology, selector, timeout, start, callback); - }; - - const iterationTimer = setTimeout(() => { - topology.removeListener('topologyDescriptionChanged', descriptionChangedHandler); - callback( - new MongoTimeoutError( - `Server selection timed out after ${timeout} ms`, - topology.description.error - ) - ); - }, timeout - duration); - - // track this timer in case we need to clean it up outside this loop - const timerIndex = topology.s.iterationTimers.push(iterationTimer); - - topology.once('topologyDescriptionChanged', descriptionChangedHandler); - }; - - retrySelection(); -} - -function createAndConnectServer(topology, serverDescription) { - topology.emit( - 'serverOpening', - new monitoring.ServerOpeningEvent(topology.s.id, serverDescription.address) - ); - - const server = new Server(serverDescription, topology.s.options, topology); - relayEvents(server, topology, SERVER_RELAY_EVENTS); - - server.once('connect', serverConnectEventHandler(server, topology)); - server.on('descriptionReceived', topology.serverUpdateHandler.bind(topology)); - server.on('error', serverErrorEventHandler(server, topology)); - server.on('close', () => topology.emit('close', server)); - server.connect(); - return server; -} - -/** - * Create `Server` instances for all initially known servers, connect them, and assign - * them to the passed in `Topology`. - * - * @param {Topology} topology The topology responsible for the servers - * @param {ServerDescription[]} serverDescriptions A list of server descriptions to connect - */ -function connectServers(topology, serverDescriptions) { - topology.s.servers = serverDescriptions.reduce((servers, serverDescription) => { - const server = createAndConnectServer(topology, serverDescription); - servers.set(serverDescription.address, server); - return servers; - }, new Map()); -} - -function updateServers(topology, incomingServerDescription) { - // update the internal server's description - if (incomingServerDescription && topology.s.servers.has(incomingServerDescription.address)) { - const server = topology.s.servers.get(incomingServerDescription.address); - server.s.description = incomingServerDescription; - } - - // add new servers for all descriptions we currently don't know about locally - for (const serverDescription of topology.description.servers.values()) { - if (!topology.s.servers.has(serverDescription.address)) { - const server = createAndConnectServer(topology, serverDescription); - topology.s.servers.set(serverDescription.address, server); - } - } - - // for all servers no longer known, remove their descriptions and destroy their instances - for (const entry of topology.s.servers) { - const serverAddress = entry[0]; - if (topology.description.hasServer(serverAddress)) { - continue; - } - - const server = topology.s.servers.get(serverAddress); - topology.s.servers.delete(serverAddress); - - // prepare server for garbage collection - destroyServer(server, topology); - } -} - -function serverConnectEventHandler(server, topology) { - return function(/* isMaster, err */) { - server.monitor({ - initial: true, - heartbeatFrequencyMS: topology.description.heartbeatFrequencyMS - }); - }; -} - -function serverErrorEventHandler(server /*, topology */) { - return function(err) { - if (isSDAMUnrecoverableError(err, server)) { - resetServerState(server, err, { clearPool: true }); - return; - } - - resetServerState(server, err); - }; -} - -function executeWriteOperation(args, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // TODO: once we drop Node 4, use destructuring either here or in arguments. - const topology = args.topology; - const op = args.op; - const ns = args.ns; - const ops = args.ops; - - const willRetryWrite = - !args.retrying && - !!options.retryWrites && - options.session && - isRetryableWritesSupported(topology) && - !options.session.inTransaction(); - - topology.selectServer(writableServerSelector(), options, (err, server) => { - if (err) { - callback(err, null); - return; - } - - const handler = (err, result) => { - if (!err) return callback(null, result); - if (!isRetryableError(err)) { - err = getMMAPError(err); - return callback(err); - } - - if (willRetryWrite) { - const newArgs = Object.assign({}, args, { retrying: true }); - return executeWriteOperation(newArgs, options, callback); - } - - return callback(err); - }; - - if (callback.operationId) { - handler.operationId = callback.operationId; - } - - // increment and assign txnNumber - if (willRetryWrite) { - options.session.incrementTransactionNumber(); - options.willRetryWrite = willRetryWrite; - } - - // execute the write operation - server[op](ns, ops, options, handler); - }); -} - -/** - * Resets the internal state of this server to `Unknown` by simulating an empty ismaster - * - * @private - * @param {Server} server - * @param {MongoError} error The error that caused the state reset - * @param {object} [options] Optional settings - * @param {boolean} [options.clearPool=false] Pool should be cleared out on state reset - */ -function resetServerState(server, error, options) { - options = Object.assign({}, { clearPool: false }, options); - - function resetState() { - server.emit( - 'descriptionReceived', - new ServerDescription(server.description.address, null, { error }) - ); - - process.nextTick(() => server.monitor()); - } - - if (options.clearPool && server.s.pool) { - server.s.pool.reset(() => resetState()); - return; - } - - resetState(); -} - -function translateReadPreference(options) { - if (options.readPreference == null) { - return; - } - - let r = options.readPreference; - if (typeof r === 'string') { - options.readPreference = new ReadPreference(r); - } else if (r && !(r instanceof ReadPreference) && typeof r === 'object') { - const mode = r.mode || r.preference; - if (mode && typeof mode === 'string') { - options.readPreference = new ReadPreference(mode, r.tags, { - maxStalenessSeconds: r.maxStalenessSeconds - }); - } - } else if (!(r instanceof ReadPreference)) { - throw new TypeError('Invalid read preference: ' + r); - } - - return options; -} - -function srvPollingHandler(topology) { - return function handleSrvPolling(ev) { - const previousTopologyDescription = topology.s.description; - topology.s.description = topology.s.description.updateFromSrvPollingEvent(ev); - if (topology.s.description === previousTopologyDescription) { - // Nothing changed, so return - return; - } - - updateServers(topology); - - topology.emit( - 'topologyDescriptionChanged', - new monitoring.TopologyDescriptionChangedEvent( - topology.s.id, - previousTopologyDescription, - topology.s.description - ) - ); - }; -} - -/** - * A server opening SDAM monitoring event - * - * @event Topology#serverOpening - * @type {ServerOpeningEvent} - */ - -/** - * A server closed SDAM monitoring event - * - * @event Topology#serverClosed - * @type {ServerClosedEvent} - */ - -/** - * A server description SDAM change monitoring event - * - * @event Topology#serverDescriptionChanged - * @type {ServerDescriptionChangedEvent} - */ - -/** - * A topology open SDAM event - * - * @event Topology#topologyOpening - * @type {TopologyOpeningEvent} - */ - -/** - * A topology closed SDAM event - * - * @event Topology#topologyClosed - * @type {TopologyClosedEvent} - */ - -/** - * A topology structure SDAM change event - * - * @event Topology#topologyDescriptionChanged - * @type {TopologyDescriptionChangedEvent} - */ - -/** - * A topology serverHeartbeatStarted SDAM event - * - * @event Topology#serverHeartbeatStarted - * @type {ServerHeartbeatStartedEvent} - */ - -/** - * A topology serverHeartbeatFailed SDAM event - * - * @event Topology#serverHeartbeatFailed - * @type {ServerHearbeatFailedEvent} - */ - -/** - * A topology serverHeartbeatSucceeded SDAM change event - * - * @event Topology#serverHeartbeatSucceeded - * @type {ServerHeartbeatSucceededEvent} - */ - -/** - * An event emitted indicating a command was started, if command monitoring is enabled - * - * @event Topology#commandStarted - * @type {object} - */ - -/** - * An event emitted indicating a command succeeded, if command monitoring is enabled - * - * @event Topology#commandSucceeded - * @type {object} - */ - -/** - * An event emitted indicating a command failed, if command monitoring is enabled - * - * @event Topology#commandFailed - * @type {object} - */ - -module.exports = Topology; diff --git a/scripts/node_modules/mongodb/lib/core/sdam/topology_description.js b/scripts/node_modules/mongodb/lib/core/sdam/topology_description.js deleted file mode 100644 index a94fb678..00000000 --- a/scripts/node_modules/mongodb/lib/core/sdam/topology_description.js +++ /dev/null @@ -1,408 +0,0 @@ -'use strict'; -const ServerType = require('./server_description').ServerType; -const ServerDescription = require('./server_description').ServerDescription; -const WIRE_CONSTANTS = require('../wireprotocol/constants'); - -// contstants related to compatability checks -const MIN_SUPPORTED_SERVER_VERSION = WIRE_CONSTANTS.MIN_SUPPORTED_SERVER_VERSION; -const MAX_SUPPORTED_SERVER_VERSION = WIRE_CONSTANTS.MAX_SUPPORTED_SERVER_VERSION; -const MIN_SUPPORTED_WIRE_VERSION = WIRE_CONSTANTS.MIN_SUPPORTED_WIRE_VERSION; -const MAX_SUPPORTED_WIRE_VERSION = WIRE_CONSTANTS.MAX_SUPPORTED_WIRE_VERSION; - -// An enumeration of topology types we know about -const TopologyType = { - Single: 'Single', - ReplicaSetNoPrimary: 'ReplicaSetNoPrimary', - ReplicaSetWithPrimary: 'ReplicaSetWithPrimary', - Sharded: 'Sharded', - Unknown: 'Unknown' -}; - -// Representation of a deployment of servers -class TopologyDescription { - /** - * Create a TopologyDescription - * - * @param {string} topologyType - * @param {Map} serverDescriptions the a map of address to ServerDescription - * @param {string} setName - * @param {number} maxSetVersion - * @param {ObjectId} maxElectionId - */ - constructor( - topologyType, - serverDescriptions, - setName, - maxSetVersion, - maxElectionId, - commonWireVersion, - options, - error - ) { - options = options || {}; - - // TODO: consider assigning all these values to a temporary value `s` which - // we use `Object.freeze` on, ensuring the internal state of this type - // is immutable. - this.type = topologyType || TopologyType.Unknown; - this.setName = setName || null; - this.maxSetVersion = maxSetVersion || null; - this.maxElectionId = maxElectionId || null; - this.servers = serverDescriptions || new Map(); - this.stale = false; - this.compatible = true; - this.compatibilityError = null; - this.logicalSessionTimeoutMinutes = null; - this.heartbeatFrequencyMS = options.heartbeatFrequencyMS || 0; - this.localThresholdMS = options.localThresholdMS || 0; - this.options = options; - this.error = error; - this.commonWireVersion = commonWireVersion || null; - - // determine server compatibility - for (const serverDescription of this.servers.values()) { - if (serverDescription.type === ServerType.Unknown) continue; - - if (serverDescription.minWireVersion > MAX_SUPPORTED_WIRE_VERSION) { - this.compatible = false; - this.compatibilityError = `Server at ${serverDescription.address} requires wire version ${ - serverDescription.minWireVersion - }, but this version of the driver only supports up to ${MAX_SUPPORTED_WIRE_VERSION} (MongoDB ${MAX_SUPPORTED_SERVER_VERSION})`; - } - - if (serverDescription.maxWireVersion < MIN_SUPPORTED_WIRE_VERSION) { - this.compatible = false; - this.compatibilityError = `Server at ${serverDescription.address} reports wire version ${ - serverDescription.maxWireVersion - }, but this version of the driver requires at least ${MIN_SUPPORTED_WIRE_VERSION} (MongoDB ${MIN_SUPPORTED_SERVER_VERSION}).`; - break; - } - } - - // Whenever a client updates the TopologyDescription from an ismaster response, it MUST set - // TopologyDescription.logicalSessionTimeoutMinutes to the smallest logicalSessionTimeoutMinutes - // value among ServerDescriptions of all data-bearing server types. If any have a null - // logicalSessionTimeoutMinutes, then TopologyDescription.logicalSessionTimeoutMinutes MUST be - // set to null. - const readableServers = Array.from(this.servers.values()).filter(s => s.isReadable); - this.logicalSessionTimeoutMinutes = readableServers.reduce((result, server) => { - if (server.logicalSessionTimeoutMinutes == null) return null; - if (result == null) return server.logicalSessionTimeoutMinutes; - return Math.min(result, server.logicalSessionTimeoutMinutes); - }, null); - } - - /** - * Returns a new TopologyDescription based on the SrvPollingEvent - * @param {SrvPollingEvent} ev The event - */ - updateFromSrvPollingEvent(ev) { - const newAddresses = ev.addresses(); - const serverDescriptions = new Map(this.servers); - for (const server of this.servers) { - if (newAddresses.has(server[0])) { - newAddresses.delete(server[0]); - } else { - serverDescriptions.delete(server[0]); - } - } - - if (serverDescriptions.size === this.servers.size && newAddresses.size === 0) { - return this; - } - - for (const address of newAddresses) { - serverDescriptions.set(address, new ServerDescription(address)); - } - - return new TopologyDescription( - this.type, - serverDescriptions, - this.setName, - this.maxSetVersion, - this.maxElectionId, - this.commonWireVersion, - this.options, - null - ); - } - - /** - * Returns a copy of this description updated with a given ServerDescription - * - * @param {ServerDescription} serverDescription - */ - update(serverDescription) { - const address = serverDescription.address; - // NOTE: there are a number of prime targets for refactoring here - // once we support destructuring assignments - - // potentially mutated values - let topologyType = this.type; - let setName = this.setName; - let maxSetVersion = this.maxSetVersion; - let maxElectionId = this.maxElectionId; - let commonWireVersion = this.commonWireVersion; - let error = serverDescription.error || this.error; - - const serverType = serverDescription.type; - let serverDescriptions = new Map(this.servers); - - // update common wire version - if (serverDescription.maxWireVersion !== 0) { - if (commonWireVersion == null) { - commonWireVersion = serverDescription.maxWireVersion; - } else { - commonWireVersion = Math.min(commonWireVersion, serverDescription.maxWireVersion); - } - } - - // update the actual server description - serverDescriptions.set(address, serverDescription); - - if (topologyType === TopologyType.Single) { - // once we are defined as single, that never changes - return new TopologyDescription( - TopologyType.Single, - serverDescriptions, - setName, - maxSetVersion, - maxElectionId, - commonWireVersion, - this.options, - error - ); - } - - if (topologyType === TopologyType.Unknown) { - if (serverType === ServerType.Standalone) { - serverDescriptions.delete(address); - } else { - topologyType = topologyTypeForServerType(serverType); - } - } - - if (topologyType === TopologyType.Sharded) { - if ([ServerType.Mongos, ServerType.Unknown].indexOf(serverType) === -1) { - serverDescriptions.delete(address); - } - } - - if (topologyType === TopologyType.ReplicaSetNoPrimary) { - if ([ServerType.Mongos, ServerType.Unknown].indexOf(serverType) >= 0) { - serverDescriptions.delete(address); - } - - if (serverType === ServerType.RSPrimary) { - const result = updateRsFromPrimary( - serverDescriptions, - setName, - serverDescription, - maxSetVersion, - maxElectionId - ); - - (topologyType = result[0]), - (setName = result[1]), - (maxSetVersion = result[2]), - (maxElectionId = result[3]); - } else if ( - [ServerType.RSSecondary, ServerType.RSArbiter, ServerType.RSOther].indexOf(serverType) >= 0 - ) { - const result = updateRsNoPrimaryFromMember(serverDescriptions, setName, serverDescription); - (topologyType = result[0]), (setName = result[1]); - } - } - - if (topologyType === TopologyType.ReplicaSetWithPrimary) { - if ([ServerType.Standalone, ServerType.Mongos].indexOf(serverType) >= 0) { - serverDescriptions.delete(address); - topologyType = checkHasPrimary(serverDescriptions); - } else if (serverType === ServerType.RSPrimary) { - const result = updateRsFromPrimary( - serverDescriptions, - setName, - serverDescription, - maxSetVersion, - maxElectionId - ); - - (topologyType = result[0]), - (setName = result[1]), - (maxSetVersion = result[2]), - (maxElectionId = result[3]); - } else if ( - [ServerType.RSSecondary, ServerType.RSArbiter, ServerType.RSOther].indexOf(serverType) >= 0 - ) { - topologyType = updateRsWithPrimaryFromMember( - serverDescriptions, - setName, - serverDescription - ); - } else { - topologyType = checkHasPrimary(serverDescriptions); - } - } - - return new TopologyDescription( - topologyType, - serverDescriptions, - setName, - maxSetVersion, - maxElectionId, - commonWireVersion, - this.options, - error - ); - } - - /** - * Determines if the topology description has any known servers - */ - get hasKnownServers() { - return Array.from(this.servers.values()).some(sd => sd.type !== ServerDescription.Unknown); - } - - /** - * Determines if this topology description has a data-bearing server available. - */ - get hasDataBearingServers() { - return Array.from(this.servers.values()).some(sd => sd.isDataBearing); - } - - /** - * Determines if the topology has a definition for the provided address - * - * @param {String} address - * @return {Boolean} Whether the topology knows about this server - */ - hasServer(address) { - return this.servers.has(address); - } -} - -function topologyTypeForServerType(serverType) { - if (serverType === ServerType.Mongos) return TopologyType.Sharded; - if (serverType === ServerType.RSPrimary) return TopologyType.ReplicaSetWithPrimary; - return TopologyType.ReplicaSetNoPrimary; -} - -function updateRsFromPrimary( - serverDescriptions, - setName, - serverDescription, - maxSetVersion, - maxElectionId -) { - setName = setName || serverDescription.setName; - if (setName !== serverDescription.setName) { - serverDescriptions.delete(serverDescription.address); - return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId]; - } - - const electionIdOID = serverDescription.electionId ? serverDescription.electionId.$oid : null; - const maxElectionIdOID = maxElectionId ? maxElectionId.$oid : null; - if (serverDescription.setVersion != null && electionIdOID != null) { - if (maxSetVersion != null && maxElectionIdOID != null) { - if (maxSetVersion > serverDescription.setVersion || maxElectionIdOID > electionIdOID) { - // this primary is stale, we must remove it - serverDescriptions.set( - serverDescription.address, - new ServerDescription(serverDescription.address) - ); - - return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId]; - } - } - - maxElectionId = serverDescription.electionId; - } - - if ( - serverDescription.setVersion != null && - (maxSetVersion == null || serverDescription.setVersion > maxSetVersion) - ) { - maxSetVersion = serverDescription.setVersion; - } - - // We've heard from the primary. Is it the same primary as before? - for (const address of serverDescriptions.keys()) { - const server = serverDescriptions.get(address); - - if (server.type === ServerType.RSPrimary && server.address !== serverDescription.address) { - // Reset old primary's type to Unknown. - serverDescriptions.set(address, new ServerDescription(server.address)); - - // There can only be one primary - break; - } - } - - // Discover new hosts from this primary's response. - serverDescription.allHosts.forEach(address => { - if (!serverDescriptions.has(address)) { - serverDescriptions.set(address, new ServerDescription(address)); - } - }); - - // Remove hosts not in the response. - const currentAddresses = Array.from(serverDescriptions.keys()); - const responseAddresses = serverDescription.allHosts; - currentAddresses.filter(addr => responseAddresses.indexOf(addr) === -1).forEach(address => { - serverDescriptions.delete(address); - }); - - return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId]; -} - -function updateRsWithPrimaryFromMember(serverDescriptions, setName, serverDescription) { - if (setName == null) { - throw new TypeError('setName is required'); - } - - if ( - setName !== serverDescription.setName || - (serverDescription.me && serverDescription.address !== serverDescription.me) - ) { - serverDescriptions.delete(serverDescription.address); - } - - return checkHasPrimary(serverDescriptions); -} - -function updateRsNoPrimaryFromMember(serverDescriptions, setName, serverDescription) { - let topologyType = TopologyType.ReplicaSetNoPrimary; - - setName = setName || serverDescription.setName; - if (setName !== serverDescription.setName) { - serverDescriptions.delete(serverDescription.address); - return [topologyType, setName]; - } - - serverDescription.allHosts.forEach(address => { - if (!serverDescriptions.has(address)) { - serverDescriptions.set(address, new ServerDescription(address)); - } - }); - - if (serverDescription.me && serverDescription.address !== serverDescription.me) { - serverDescriptions.delete(serverDescription.address); - } - - return [topologyType, setName]; -} - -function checkHasPrimary(serverDescriptions) { - for (const addr of serverDescriptions.keys()) { - if (serverDescriptions.get(addr).type === ServerType.RSPrimary) { - return TopologyType.ReplicaSetWithPrimary; - } - } - - return TopologyType.ReplicaSetNoPrimary; -} - -module.exports = { - TopologyType, - TopologyDescription -}; diff --git a/scripts/node_modules/mongodb/lib/core/sessions.js b/scripts/node_modules/mongodb/lib/core/sessions.js deleted file mode 100644 index d15015c8..00000000 --- a/scripts/node_modules/mongodb/lib/core/sessions.js +++ /dev/null @@ -1,767 +0,0 @@ -'use strict'; - -const retrieveBSON = require('./connection/utils').retrieveBSON; -const EventEmitter = require('events'); -const BSON = retrieveBSON(); -const Binary = BSON.Binary; -const uuidV4 = require('./utils').uuidV4; -const MongoError = require('./error').MongoError; -const isRetryableError = require('././error').isRetryableError; -const MongoNetworkError = require('./error').MongoNetworkError; -const MongoWriteConcernError = require('./error').MongoWriteConcernError; -const Transaction = require('./transactions').Transaction; -const TxnState = require('./transactions').TxnState; -const isPromiseLike = require('./utils').isPromiseLike; -const ReadPreference = require('./topologies/read_preference'); -const isTransactionCommand = require('./transactions').isTransactionCommand; -const resolveClusterTime = require('./topologies/shared').resolveClusterTime; -const isSharded = require('./wireprotocol/shared').isSharded; -const maxWireVersion = require('./utils').maxWireVersion; - -const minWireVersionForShardedTransactions = 8; - -function assertAlive(session, callback) { - if (session.serverSession == null) { - const error = new MongoError('Cannot use a session that has ended'); - if (typeof callback === 'function') { - callback(error, null); - return false; - } - - throw error; - } - - return true; -} - -/** - * Options to pass when creating a Client Session - * @typedef {Object} SessionOptions - * @property {boolean} [causalConsistency=true] Whether causal consistency should be enabled on this session - * @property {TransactionOptions} [defaultTransactionOptions] The default TransactionOptions to use for transactions started on this session. - */ - -/** - * A BSON document reflecting the lsid of a {@link ClientSession} - * @typedef {Object} SessionId - */ - -/** - * A class representing a client session on the server - * WARNING: not meant to be instantiated directly. - * @class - * @hideconstructor - */ -class ClientSession extends EventEmitter { - /** - * Create a client session. - * WARNING: not meant to be instantiated directly - * - * @param {Topology} topology The current client's topology (Internal Class) - * @param {ServerSessionPool} sessionPool The server session pool (Internal Class) - * @param {SessionOptions} [options] Optional settings - * @param {Object} [clientOptions] Optional settings provided when creating a client in the porcelain driver - */ - constructor(topology, sessionPool, options, clientOptions) { - super(); - - if (topology == null) { - throw new Error('ClientSession requires a topology'); - } - - if (sessionPool == null || !(sessionPool instanceof ServerSessionPool)) { - throw new Error('ClientSession requires a ServerSessionPool'); - } - - options = options || {}; - clientOptions = clientOptions || {}; - - this.topology = topology; - this.sessionPool = sessionPool; - this.hasEnded = false; - this.serverSession = sessionPool.acquire(); - this.clientOptions = clientOptions; - - this.supports = { - causalConsistency: - typeof options.causalConsistency !== 'undefined' ? options.causalConsistency : true - }; - - this.clusterTime = options.initialClusterTime; - - this.operationTime = null; - this.explicit = !!options.explicit; - this.owner = options.owner; - this.defaultTransactionOptions = Object.assign({}, options.defaultTransactionOptions); - this.transaction = new Transaction(); - } - - /** - * The server id associated with this session - * @type {SessionId} - */ - get id() { - return this.serverSession.id; - } - - /** - * Ends this session on the server - * - * @param {Object} [options] Optional settings. Currently reserved for future use - * @param {Function} [callback] Optional callback for completion of this operation - */ - endSession(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - if (this.hasEnded) { - if (typeof callback === 'function') callback(null, null); - return; - } - - if (this.serverSession && this.inTransaction()) { - this.abortTransaction(); // pass in callback? - } - - // mark the session as ended, and emit a signal - this.hasEnded = true; - this.emit('ended', this); - - // release the server session back to the pool - this.sessionPool.release(this.serverSession); - this.serverSession = null; - - // spec indicates that we should ignore all errors for `endSessions` - if (typeof callback === 'function') callback(null, null); - } - - /** - * Advances the operationTime for a ClientSession. - * - * @param {Timestamp} operationTime the `BSON.Timestamp` of the operation type it is desired to advance to - */ - advanceOperationTime(operationTime) { - if (this.operationTime == null) { - this.operationTime = operationTime; - return; - } - - if (operationTime.greaterThan(this.operationTime)) { - this.operationTime = operationTime; - } - } - - /** - * Used to determine if this session equals another - * @param {ClientSession} session - * @return {boolean} true if the sessions are equal - */ - equals(session) { - if (!(session instanceof ClientSession)) { - return false; - } - - return this.id.id.buffer.equals(session.id.id.buffer); - } - - /** - * Increment the transaction number on the internal ServerSession - */ - incrementTransactionNumber() { - this.serverSession.txnNumber++; - } - - /** - * @returns {boolean} whether this session is currently in a transaction or not - */ - inTransaction() { - return this.transaction.isActive; - } - - /** - * Starts a new transaction with the given options. - * - * @param {TransactionOptions} options Options for the transaction - */ - startTransaction(options) { - assertAlive(this); - if (this.inTransaction()) { - throw new MongoError('Transaction already in progress'); - } - - const topologyMaxWireVersion = maxWireVersion(this.topology); - if ( - isSharded(this.topology) && - topologyMaxWireVersion != null && - topologyMaxWireVersion < minWireVersionForShardedTransactions - ) { - throw new MongoError('Transactions are not supported on sharded clusters in MongoDB < 4.2.'); - } - - // increment txnNumber - this.incrementTransactionNumber(); - - // create transaction state - this.transaction = new Transaction( - Object.assign({}, this.clientOptions, options || this.defaultTransactionOptions) - ); - - this.transaction.transition(TxnState.STARTING_TRANSACTION); - } - - /** - * Commits the currently active transaction in this session. - * - * @param {Function} [callback] optional callback for completion of this operation - * @return {Promise} A promise is returned if no callback is provided - */ - commitTransaction(callback) { - if (typeof callback === 'function') { - endTransaction(this, 'commitTransaction', callback); - return; - } - - return new Promise((resolve, reject) => { - endTransaction( - this, - 'commitTransaction', - (err, reply) => (err ? reject(err) : resolve(reply)) - ); - }); - } - - /** - * Aborts the currently active transaction in this session. - * - * @param {Function} [callback] optional callback for completion of this operation - * @return {Promise} A promise is returned if no callback is provided - */ - abortTransaction(callback) { - if (typeof callback === 'function') { - endTransaction(this, 'abortTransaction', callback); - return; - } - - return new Promise((resolve, reject) => { - endTransaction( - this, - 'abortTransaction', - (err, reply) => (err ? reject(err) : resolve(reply)) - ); - }); - } - - /** - * This is here to ensure that ClientSession is never serialized to BSON. - * @ignore - */ - toBSON() { - throw new Error('ClientSession cannot be serialized to BSON.'); - } - - /** - * A user provided function to be run within a transaction - * - * @callback WithTransactionCallback - * @param {ClientSession} session The parent session of the transaction running the operation. This should be passed into each operation within the lambda. - * @returns {Promise} The resulting Promise of operations run within this transaction - */ - - /** - * Runs a provided lambda within a transaction, retrying either the commit operation - * or entire transaction as needed (and when the error permits) to better ensure that - * the transaction can complete successfully. - * - * IMPORTANT: This method requires the user to return a Promise, all lambdas that do not - * return a Promise will result in undefined behavior. - * - * @param {WithTransactionCallback} fn - * @param {TransactionOptions} [options] Optional settings for the transaction - */ - withTransaction(fn, options) { - const startTime = Date.now(); - return attemptTransaction(this, startTime, fn, options); - } -} - -const MAX_WITH_TRANSACTION_TIMEOUT = 120000; -const UNSATISFIABLE_WRITE_CONCERN_CODE = 100; -const UNKNOWN_REPL_WRITE_CONCERN_CODE = 79; -const MAX_TIME_MS_EXPIRED_CODE = 50; -const NON_DETERMINISTIC_WRITE_CONCERN_ERRORS = new Set([ - 'CannotSatisfyWriteConcern', - 'UnknownReplWriteConcern', - 'UnsatisfiableWriteConcern' -]); - -function hasNotTimedOut(startTime, max) { - return Date.now() - startTime < max; -} - -function isUnknownTransactionCommitResult(err) { - return ( - isMaxTimeMSExpiredError(err) || - (!NON_DETERMINISTIC_WRITE_CONCERN_ERRORS.has(err.codeName) && - err.code !== UNSATISFIABLE_WRITE_CONCERN_CODE && - err.code !== UNKNOWN_REPL_WRITE_CONCERN_CODE) - ); -} - -function isMaxTimeMSExpiredError(err) { - return ( - err.code === MAX_TIME_MS_EXPIRED_CODE || - (err.writeConcernError && err.writeConcernError.code === MAX_TIME_MS_EXPIRED_CODE) - ); -} - -function attemptTransactionCommit(session, startTime, fn, options) { - return session.commitTransaction().catch(err => { - if ( - err instanceof MongoError && - hasNotTimedOut(startTime, MAX_WITH_TRANSACTION_TIMEOUT) && - !isMaxTimeMSExpiredError(err) - ) { - if (err.hasErrorLabel('UnknownTransactionCommitResult')) { - return attemptTransactionCommit(session, startTime, fn, options); - } - - if (err.hasErrorLabel('TransientTransactionError')) { - return attemptTransaction(session, startTime, fn, options); - } - } - - throw err; - }); -} - -const USER_EXPLICIT_TXN_END_STATES = new Set([ - TxnState.NO_TRANSACTION, - TxnState.TRANSACTION_COMMITTED, - TxnState.TRANSACTION_ABORTED -]); - -function userExplicitlyEndedTransaction(session) { - return USER_EXPLICIT_TXN_END_STATES.has(session.transaction.state); -} - -function attemptTransaction(session, startTime, fn, options) { - session.startTransaction(options); - - let promise; - try { - promise = fn(session); - } catch (err) { - promise = Promise.reject(err); - } - - if (!isPromiseLike(promise)) { - session.abortTransaction(); - throw new TypeError('Function provided to `withTransaction` must return a Promise'); - } - - return promise - .then(() => { - if (userExplicitlyEndedTransaction(session)) { - return; - } - - return attemptTransactionCommit(session, startTime, fn, options); - }) - .catch(err => { - function maybeRetryOrThrow(err) { - if ( - err instanceof MongoError && - err.hasErrorLabel('TransientTransactionError') && - hasNotTimedOut(startTime, MAX_WITH_TRANSACTION_TIMEOUT) - ) { - return attemptTransaction(session, startTime, fn, options); - } - - if (isMaxTimeMSExpiredError(err)) { - if (err.errorLabels == null) { - err.errorLabels = []; - } - err.errorLabels.push('UnknownTransactionCommitResult'); - } - - throw err; - } - - if (session.transaction.isActive) { - return session.abortTransaction().then(() => maybeRetryOrThrow(err)); - } - - return maybeRetryOrThrow(err); - }); -} - -function endTransaction(session, commandName, callback) { - if (!assertAlive(session, callback)) { - // checking result in case callback was called - return; - } - - // handle any initial problematic cases - let txnState = session.transaction.state; - - if (txnState === TxnState.NO_TRANSACTION) { - callback(new MongoError('No transaction started')); - return; - } - - if (commandName === 'commitTransaction') { - if ( - txnState === TxnState.STARTING_TRANSACTION || - txnState === TxnState.TRANSACTION_COMMITTED_EMPTY - ) { - // the transaction was never started, we can safely exit here - session.transaction.transition(TxnState.TRANSACTION_COMMITTED_EMPTY); - callback(null, null); - return; - } - - if (txnState === TxnState.TRANSACTION_ABORTED) { - callback(new MongoError('Cannot call commitTransaction after calling abortTransaction')); - return; - } - } else { - if (txnState === TxnState.STARTING_TRANSACTION) { - // the transaction was never started, we can safely exit here - session.transaction.transition(TxnState.TRANSACTION_ABORTED); - callback(null, null); - return; - } - - if (txnState === TxnState.TRANSACTION_ABORTED) { - callback(new MongoError('Cannot call abortTransaction twice')); - return; - } - - if ( - txnState === TxnState.TRANSACTION_COMMITTED || - txnState === TxnState.TRANSACTION_COMMITTED_EMPTY - ) { - callback(new MongoError('Cannot call abortTransaction after calling commitTransaction')); - return; - } - } - - // construct and send the command - const command = { [commandName]: 1 }; - - // apply a writeConcern if specified - let writeConcern; - if (session.transaction.options.writeConcern) { - writeConcern = Object.assign({}, session.transaction.options.writeConcern); - } else if (session.clientOptions && session.clientOptions.w) { - writeConcern = { w: session.clientOptions.w }; - } - - if (txnState === TxnState.TRANSACTION_COMMITTED) { - writeConcern = Object.assign({ wtimeout: 10000 }, writeConcern, { w: 'majority' }); - } - - if (writeConcern) { - Object.assign(command, { writeConcern }); - } - - if (commandName === 'commitTransaction' && session.transaction.options.maxTimeMS) { - Object.assign(command, { maxTimeMS: session.transaction.options.maxTimeMS }); - } - - function commandHandler(e, r) { - if (commandName === 'commitTransaction') { - session.transaction.transition(TxnState.TRANSACTION_COMMITTED); - - if ( - e && - (e instanceof MongoNetworkError || - e instanceof MongoWriteConcernError || - isRetryableError(e) || - isMaxTimeMSExpiredError(e)) - ) { - if (e.errorLabels) { - const idx = e.errorLabels.indexOf('TransientTransactionError'); - if (idx !== -1) { - e.errorLabels.splice(idx, 1); - } - } else { - e.errorLabels = []; - } - - if (isUnknownTransactionCommitResult(e)) { - e.errorLabels.push('UnknownTransactionCommitResult'); - - // per txns spec, must unpin session in this case - session.transaction.unpinServer(); - } - } - } else { - session.transaction.transition(TxnState.TRANSACTION_ABORTED); - } - - callback(e, r); - } - - // The spec indicates that we should ignore all errors on `abortTransaction` - function transactionError(err) { - return commandName === 'commitTransaction' ? err : null; - } - - if ( - // Assumption here that commandName is "commitTransaction" or "abortTransaction" - session.transaction.recoveryToken && - supportsRecoveryToken(session) - ) { - command.recoveryToken = session.transaction.recoveryToken; - } - - // send the command - session.topology.command('admin.$cmd', command, { session }, (err, reply) => { - if (err && isRetryableError(err)) { - // SPEC-1185: apply majority write concern when retrying commitTransaction - if (command.commitTransaction) { - // per txns spec, must unpin session in this case - session.transaction.unpinServer(); - - command.writeConcern = Object.assign({ wtimeout: 10000 }, command.writeConcern, { - w: 'majority' - }); - } - - return session.topology.command('admin.$cmd', command, { session }, (_err, _reply) => - commandHandler(transactionError(_err), _reply) - ); - } - - commandHandler(transactionError(err), reply); - }); -} - -function supportsRecoveryToken(session) { - const topology = session.topology; - return !!topology.s.options.useRecoveryToken; -} - -/** - * Reflects the existence of a session on the server. Can be reused by the session pool. - * WARNING: not meant to be instantiated directly. For internal use only. - * @ignore - */ -class ServerSession { - constructor() { - this.id = { id: new Binary(uuidV4(), Binary.SUBTYPE_UUID) }; - this.lastUse = Date.now(); - this.txnNumber = 0; - this.isDirty = false; - } - - /** - * Determines if the server session has timed out. - * @ignore - * @param {Date} sessionTimeoutMinutes The server's "logicalSessionTimeoutMinutes" - * @return {boolean} true if the session has timed out. - */ - hasTimedOut(sessionTimeoutMinutes) { - // Take the difference of the lastUse timestamp and now, which will result in a value in - // milliseconds, and then convert milliseconds to minutes to compare to `sessionTimeoutMinutes` - const idleTimeMinutes = Math.round( - (((Date.now() - this.lastUse) % 86400000) % 3600000) / 60000 - ); - - return idleTimeMinutes > sessionTimeoutMinutes - 1; - } -} - -/** - * Maintains a pool of Server Sessions. - * For internal use only - * @ignore - */ -class ServerSessionPool { - constructor(topology) { - if (topology == null) { - throw new Error('ServerSessionPool requires a topology'); - } - - this.topology = topology; - this.sessions = []; - } - - /** - * Ends all sessions in the session pool. - * @ignore - */ - endAllPooledSessions() { - if (this.sessions.length) { - this.topology.endSessions(this.sessions.map(session => session.id)); - this.sessions = []; - } - } - - /** - * Acquire a Server Session from the pool. - * Iterates through each session in the pool, removing any stale sessions - * along the way. The first non-stale session found is removed from the - * pool and returned. If no non-stale session is found, a new ServerSession - * is created. - * @ignore - * @returns {ServerSession} - */ - acquire() { - const sessionTimeoutMinutes = this.topology.logicalSessionTimeoutMinutes; - while (this.sessions.length) { - const session = this.sessions.shift(); - if (!session.hasTimedOut(sessionTimeoutMinutes)) { - return session; - } - } - - return new ServerSession(); - } - - /** - * Release a session to the session pool - * Adds the session back to the session pool if the session has not timed out yet. - * This method also removes any stale sessions from the pool. - * @ignore - * @param {ServerSession} session The session to release to the pool - */ - release(session) { - const sessionTimeoutMinutes = this.topology.logicalSessionTimeoutMinutes; - while (this.sessions.length) { - const pooledSession = this.sessions[this.sessions.length - 1]; - if (pooledSession.hasTimedOut(sessionTimeoutMinutes)) { - this.sessions.pop(); - } else { - break; - } - } - - if (!session.hasTimedOut(sessionTimeoutMinutes)) { - if (session.isDirty) { - return; - } - - // otherwise, readd this session to the session pool - this.sessions.unshift(session); - } - } -} - -// TODO: this should be codified in command construction -// @see https://github.com/mongodb/specifications/blob/master/source/read-write-concern/read-write-concern.rst#read-concern -function commandSupportsReadConcern(command, options) { - if ( - command.aggregate || - command.count || - command.distinct || - command.find || - command.parallelCollectionScan || - command.geoNear || - command.geoSearch - ) { - return true; - } - - if (command.mapReduce && options.out && (options.out.inline === 1 || options.out === 'inline')) { - return true; - } - - return false; -} - -/** - * Optionally decorate a command with sessions specific keys - * - * @param {ClientSession} session the session tracking transaction state - * @param {Object} command the command to decorate - * @param {Object} topology the topology for tracking the cluster time - * @param {Object} [options] Optional settings passed to calling operation - * @return {MongoError|null} An error, if some error condition was met - */ -function applySession(session, command, options) { - const serverSession = session.serverSession; - if (serverSession == null) { - // TODO: merge this with `assertAlive`, did not want to throw a try/catch here - return new MongoError('Cannot use a session that has ended'); - } - - // mark the last use of this session, and apply the `lsid` - serverSession.lastUse = Date.now(); - command.lsid = serverSession.id; - - // first apply non-transaction-specific sessions data - const inTransaction = session.inTransaction() || isTransactionCommand(command); - const isRetryableWrite = options.willRetryWrite; - const shouldApplyReadConcern = commandSupportsReadConcern(command); - - if (serverSession.txnNumber && (isRetryableWrite || inTransaction)) { - command.txnNumber = BSON.Long.fromNumber(serverSession.txnNumber); - } - - // now attempt to apply transaction-specific sessions data - if (!inTransaction) { - if (session.transaction.state !== TxnState.NO_TRANSACTION) { - session.transaction.transition(TxnState.NO_TRANSACTION); - } - - // TODO: the following should only be applied to read operation per spec. - // for causal consistency - if (session.supports.causalConsistency && session.operationTime && shouldApplyReadConcern) { - command.readConcern = command.readConcern || {}; - Object.assign(command.readConcern, { afterClusterTime: session.operationTime }); - } - - return; - } - - if (options.readPreference && !options.readPreference.equals(ReadPreference.primary)) { - return new MongoError( - `Read preference in a transaction must be primary, not: ${options.readPreference.mode}` - ); - } - - // `autocommit` must always be false to differentiate from retryable writes - command.autocommit = false; - - if (session.transaction.state === TxnState.STARTING_TRANSACTION) { - session.transaction.transition(TxnState.TRANSACTION_IN_PROGRESS); - command.startTransaction = true; - - const readConcern = - session.transaction.options.readConcern || session.clientOptions.readConcern; - if (readConcern) { - command.readConcern = readConcern; - } - - if (session.supports.causalConsistency && session.operationTime) { - command.readConcern = command.readConcern || {}; - Object.assign(command.readConcern, { afterClusterTime: session.operationTime }); - } - } -} - -function updateSessionFromResponse(session, document) { - if (document.$clusterTime) { - resolveClusterTime(session, document.$clusterTime); - } - - if (document.operationTime && session && session.supports.causalConsistency) { - session.advanceOperationTime(document.operationTime); - } - - if (document.recoveryToken && session && session.inTransaction()) { - session.transaction._recoveryToken = document.recoveryToken; - } -} - -module.exports = { - ClientSession, - ServerSession, - ServerSessionPool, - TxnState, - applySession, - updateSessionFromResponse, - commandSupportsReadConcern -}; diff --git a/scripts/node_modules/mongodb/lib/core/tools/smoke_plugin.js b/scripts/node_modules/mongodb/lib/core/tools/smoke_plugin.js deleted file mode 100644 index 22d02986..00000000 --- a/scripts/node_modules/mongodb/lib/core/tools/smoke_plugin.js +++ /dev/null @@ -1,61 +0,0 @@ -'use strict'; - -var fs = require('fs'); - -/* Note: because this plugin uses process.on('uncaughtException'), only one - * of these can exist at any given time. This plugin and anything else that - * uses process.on('uncaughtException') will conflict. */ -exports.attachToRunner = function(runner, outputFile) { - var smokeOutput = { results: [] }; - var runningTests = {}; - - var integraPlugin = { - beforeTest: function(test, callback) { - test.startTime = Date.now(); - runningTests[test.name] = test; - callback(); - }, - afterTest: function(test, callback) { - smokeOutput.results.push({ - status: test.status, - start: test.startTime, - end: Date.now(), - test_file: test.name, - exit_code: 0, - url: '' - }); - delete runningTests[test.name]; - callback(); - }, - beforeExit: function(obj, callback) { - fs.writeFile(outputFile, JSON.stringify(smokeOutput), function() { - callback(); - }); - } - }; - - // In case of exception, make sure we write file - process.on('uncaughtException', function(err) { - // Mark all currently running tests as failed - for (var testName in runningTests) { - smokeOutput.results.push({ - status: 'fail', - start: runningTests[testName].startTime, - end: Date.now(), - test_file: testName, - exit_code: 0, - url: '' - }); - } - - // write file - fs.writeFileSync(outputFile, JSON.stringify(smokeOutput)); - - // Standard NodeJS uncaught exception handler - console.error(err.stack); - process.exit(1); - }); - - runner.plugin(integraPlugin); - return integraPlugin; -}; diff --git a/scripts/node_modules/mongodb/lib/core/topologies/mongos.js b/scripts/node_modules/mongodb/lib/core/topologies/mongos.js deleted file mode 100644 index 681b01fd..00000000 --- a/scripts/node_modules/mongodb/lib/core/topologies/mongos.js +++ /dev/null @@ -1,1392 +0,0 @@ -'use strict'; - -const inherits = require('util').inherits; -const f = require('util').format; -const EventEmitter = require('events').EventEmitter; -const CoreCursor = require('../cursor').CoreCursor; -const Logger = require('../connection/logger'); -const retrieveBSON = require('../connection/utils').retrieveBSON; -const MongoError = require('../error').MongoError; -const Server = require('./server'); -const clone = require('./shared').clone; -const diff = require('./shared').diff; -const cloneOptions = require('./shared').cloneOptions; -const createClientInfo = require('./shared').createClientInfo; -const SessionMixins = require('./shared').SessionMixins; -const isRetryableWritesSupported = require('./shared').isRetryableWritesSupported; -const relayEvents = require('../utils').relayEvents; -const isRetryableError = require('../error').isRetryableError; -const BSON = retrieveBSON(); -const getMMAPError = require('./shared').getMMAPError; - -/** - * @fileOverview The **Mongos** class is a class that represents a Mongos Proxy topology and is - * used to construct connections. - */ - -// -// States -var DISCONNECTED = 'disconnected'; -var CONNECTING = 'connecting'; -var CONNECTED = 'connected'; -var UNREFERENCED = 'unreferenced'; -var DESTROYING = 'destroying'; -var DESTROYED = 'destroyed'; - -function stateTransition(self, newState) { - var legalTransitions = { - disconnected: [CONNECTING, DESTROYING, DESTROYED, DISCONNECTED], - connecting: [CONNECTING, DESTROYING, DESTROYED, CONNECTED, DISCONNECTED], - connected: [CONNECTED, DISCONNECTED, DESTROYING, DESTROYED, UNREFERENCED], - unreferenced: [UNREFERENCED, DESTROYING, DESTROYED], - destroyed: [DESTROYED] - }; - - // Get current state - var legalStates = legalTransitions[self.state]; - if (legalStates && legalStates.indexOf(newState) !== -1) { - self.state = newState; - } else { - self.s.logger.error( - f( - 'Mongos with id [%s] failed attempted illegal state transition from [%s] to [%s] only following state allowed [%s]', - self.id, - self.state, - newState, - legalStates - ) - ); - } -} - -// -// ReplSet instance id -var id = 1; -var handlers = ['connect', 'close', 'error', 'timeout', 'parseError']; - -/** - * Creates a new Mongos instance - * @class - * @param {array} seedlist A list of seeds for the replicaset - * @param {number} [options.haInterval=5000] The High availability period for replicaset inquiry - * @param {Cursor} [options.cursorFactory=Cursor] The cursor factory class used for all query cursors - * @param {number} [options.size=5] Server connection pool size - * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled - * @param {number} [options.keepAliveInitialDelay=0] Initial delay before TCP keep alive enabled - * @param {number} [options.localThresholdMS=15] Cutoff latency point in MS for MongoS proxy selection - * @param {boolean} [options.noDelay=true] TCP Connection no delay - * @param {number} [options.connectionTimeout=1000] TCP Connection timeout setting - * @param {number} [options.socketTimeout=0] TCP Socket timeout setting - * @param {boolean} [options.ssl=false] Use SSL for connection - * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. - * @param {Buffer} [options.ca] SSL Certificate store binary buffer - * @param {Buffer} [options.crl] SSL Certificate revocation store binary buffer - * @param {Buffer} [options.cert] SSL Certificate binary buffer - * @param {Buffer} [options.key] SSL Key file binary buffer - * @param {string} [options.passphrase] SSL Certificate pass phrase - * @param {string} [options.servername=null] String containing the server name requested via TLS SNI. - * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates - * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits - * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. - * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. - * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. - * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology - * @return {Mongos} A cursor instance - * @fires Mongos#connect - * @fires Mongos#reconnect - * @fires Mongos#joined - * @fires Mongos#left - * @fires Mongos#failed - * @fires Mongos#fullsetup - * @fires Mongos#all - * @fires Mongos#serverHeartbeatStarted - * @fires Mongos#serverHeartbeatSucceeded - * @fires Mongos#serverHeartbeatFailed - * @fires Mongos#topologyOpening - * @fires Mongos#topologyClosed - * @fires Mongos#topologyDescriptionChanged - * @property {string} type the topology type. - * @property {string} parserType the parser type used (c++ or js). - */ -var Mongos = function(seedlist, options) { - options = options || {}; - - // Get replSet Id - this.id = id++; - - // Internal state - this.s = { - options: Object.assign({}, options), - // BSON instance - bson: - options.bson || - new BSON([ - BSON.Binary, - BSON.Code, - BSON.DBRef, - BSON.Decimal128, - BSON.Double, - BSON.Int32, - BSON.Long, - BSON.Map, - BSON.MaxKey, - BSON.MinKey, - BSON.ObjectId, - BSON.BSONRegExp, - BSON.Symbol, - BSON.Timestamp - ]), - // Factory overrides - Cursor: options.cursorFactory || CoreCursor, - // Logger instance - logger: Logger('Mongos', options), - // Seedlist - seedlist: seedlist, - // Ha interval - haInterval: options.haInterval ? options.haInterval : 10000, - // Disconnect handler - disconnectHandler: options.disconnectHandler, - // Server selection index - index: 0, - // Connect function options passed in - connectOptions: {}, - // Are we running in debug mode - debug: typeof options.debug === 'boolean' ? options.debug : false, - // localThresholdMS - localThresholdMS: options.localThresholdMS || 15, - // Client info - clientInfo: createClientInfo(options) - }; - - // Set the client info - this.s.options.clientInfo = createClientInfo(options); - - // Log info warning if the socketTimeout < haInterval as it will cause - // a lot of recycled connections to happen. - if ( - this.s.logger.isWarn() && - this.s.options.socketTimeout !== 0 && - this.s.options.socketTimeout < this.s.haInterval - ) { - this.s.logger.warn( - f( - 'warning socketTimeout %s is less than haInterval %s. This might cause unnecessary server reconnections due to socket timeouts', - this.s.options.socketTimeout, - this.s.haInterval - ) - ); - } - - // Disconnected state - this.state = DISCONNECTED; - - // Current proxies we are connecting to - this.connectingProxies = []; - // Currently connected proxies - this.connectedProxies = []; - // Disconnected proxies - this.disconnectedProxies = []; - // Index of proxy to run operations against - this.index = 0; - // High availability timeout id - this.haTimeoutId = null; - // Last ismaster - this.ismaster = null; - - // Description of the Replicaset - this.topologyDescription = { - topologyType: 'Unknown', - servers: [] - }; - - // Highest clusterTime seen in responses from the current deployment - this.clusterTime = null; - - // Add event listener - EventEmitter.call(this); -}; - -inherits(Mongos, EventEmitter); -Object.assign(Mongos.prototype, SessionMixins); - -Object.defineProperty(Mongos.prototype, 'type', { - enumerable: true, - get: function() { - return 'mongos'; - } -}); - -Object.defineProperty(Mongos.prototype, 'parserType', { - enumerable: true, - get: function() { - return BSON.native ? 'c++' : 'js'; - } -}); - -Object.defineProperty(Mongos.prototype, 'logicalSessionTimeoutMinutes', { - enumerable: true, - get: function() { - if (!this.ismaster) return null; - return this.ismaster.logicalSessionTimeoutMinutes || null; - } -}); - -/** - * Emit event if it exists - * @method - */ -function emitSDAMEvent(self, event, description) { - if (self.listeners(event).length > 0) { - self.emit(event, description); - } -} - -const SERVER_EVENTS = ['serverDescriptionChanged', 'error', 'close', 'timeout', 'parseError']; -function destroyServer(server, options, callback) { - options = options || {}; - SERVER_EVENTS.forEach(event => server.removeAllListeners(event)); - server.destroy(options, callback); -} - -/** - * Initiate server connect - */ -Mongos.prototype.connect = function(options) { - var self = this; - // Add any connect level options to the internal state - this.s.connectOptions = options || {}; - - // Set connecting state - stateTransition(this, CONNECTING); - - // Create server instances - var servers = this.s.seedlist.map(function(x) { - const server = new Server( - Object.assign({}, self.s.options, x, options, { - reconnect: false, - monitoring: false, - parent: self, - clientInfo: clone(self.s.clientInfo) - }) - ); - - relayEvents(server, self, ['serverDescriptionChanged']); - return server; - }); - - // Emit the topology opening event - emitSDAMEvent(this, 'topologyOpening', { topologyId: this.id }); - - // Start all server connections - connectProxies(self, servers); -}; - -/** - * Authenticate the topology. - * @method - * @param {MongoCredentials} credentials The credentials for authentication we are using - * @param {authResultCallback} callback A callback function - */ -Mongos.prototype.auth = function(credentials, callback) { - if (typeof callback === 'function') callback(null, null); -}; - -function handleEvent(self) { - return function() { - if (self.state === DESTROYED || self.state === DESTROYING) { - return; - } - - // Move to list of disconnectedProxies - moveServerFrom(self.connectedProxies, self.disconnectedProxies, this); - // Emit the initial topology - emitTopologyDescriptionChanged(self); - // Emit the left signal - self.emit('left', 'mongos', this); - // Emit the sdam event - self.emit('serverClosed', { - topologyId: self.id, - address: this.name - }); - }; -} - -function handleInitialConnectEvent(self, event) { - return function() { - var _this = this; - - // Destroy the instance - if (self.state === DESTROYED) { - // Emit the initial topology - emitTopologyDescriptionChanged(self); - // Move from connectingProxies - moveServerFrom(self.connectingProxies, self.disconnectedProxies, this); - return this.destroy(); - } - - // Check the type of server - if (event === 'connect') { - // Get last known ismaster - self.ismaster = _this.lastIsMaster(); - - // Is this not a proxy, remove t - if (self.ismaster.msg === 'isdbgrid') { - // Add to the connectd list - for (let i = 0; i < self.connectedProxies.length; i++) { - if (self.connectedProxies[i].name === _this.name) { - // Move from connectingProxies - moveServerFrom(self.connectingProxies, self.disconnectedProxies, _this); - // Emit the initial topology - emitTopologyDescriptionChanged(self); - _this.destroy(); - return self.emit('failed', _this); - } - } - - // Remove the handlers - for (let i = 0; i < handlers.length; i++) { - _this.removeAllListeners(handlers[i]); - } - - // Add stable state handlers - _this.on('error', handleEvent(self, 'error')); - _this.on('close', handleEvent(self, 'close')); - _this.on('timeout', handleEvent(self, 'timeout')); - _this.on('parseError', handleEvent(self, 'parseError')); - - // Move from connecting proxies connected - moveServerFrom(self.connectingProxies, self.connectedProxies, _this); - // Emit the joined event - self.emit('joined', 'mongos', _this); - } else { - // Print warning if we did not find a mongos proxy - if (self.s.logger.isWarn()) { - var message = 'expected mongos proxy, but found replicaset member mongod for server %s'; - // We have a standalone server - if (!self.ismaster.hosts) { - message = 'expected mongos proxy, but found standalone mongod for server %s'; - } - - self.s.logger.warn(f(message, _this.name)); - } - - // This is not a mongos proxy, destroy and remove it completely - _this.destroy(true); - removeProxyFrom(self.connectingProxies, _this); - // Emit the left event - self.emit('left', 'server', _this); - // Emit failed event - self.emit('failed', _this); - } - } else { - moveServerFrom(self.connectingProxies, self.disconnectedProxies, this); - // Emit the left event - self.emit('left', 'mongos', this); - // Emit failed event - self.emit('failed', this); - } - - // Emit the initial topology - emitTopologyDescriptionChanged(self); - - // Trigger topologyMonitor - if (self.connectingProxies.length === 0) { - // Emit connected if we are connected - if (self.connectedProxies.length > 0 && self.state === CONNECTING) { - // Set the state to connected - stateTransition(self, CONNECTED); - // Emit the connect event - self.emit('connect', self); - self.emit('fullsetup', self); - self.emit('all', self); - } else if (self.disconnectedProxies.length === 0) { - // Print warning if we did not find a mongos proxy - if (self.s.logger.isWarn()) { - self.s.logger.warn( - f('no mongos proxies found in seed list, did you mean to connect to a replicaset') - ); - } - - // Emit the error that no proxies were found - return self.emit('error', new MongoError('no mongos proxies found in seed list')); - } - - // Topology monitor - topologyMonitor(self, { firstConnect: true }); - } - }; -} - -function connectProxies(self, servers) { - // Update connectingProxies - self.connectingProxies = self.connectingProxies.concat(servers); - - // Index used to interleaf the server connects, avoiding - // runtime issues on io constrained vm's - var timeoutInterval = 0; - - function connect(server, timeoutInterval) { - setTimeout(function() { - // Emit opening server event - self.emit('serverOpening', { - topologyId: self.id, - address: server.name - }); - - // Emit the initial topology - emitTopologyDescriptionChanged(self); - - // Add event handlers - server.once('close', handleInitialConnectEvent(self, 'close')); - server.once('timeout', handleInitialConnectEvent(self, 'timeout')); - server.once('parseError', handleInitialConnectEvent(self, 'parseError')); - server.once('error', handleInitialConnectEvent(self, 'error')); - server.once('connect', handleInitialConnectEvent(self, 'connect')); - - // Command Monitoring events - relayEvents(server, self, ['commandStarted', 'commandSucceeded', 'commandFailed']); - - // Start connection - server.connect(self.s.connectOptions); - }, timeoutInterval); - } - - // Start all the servers - servers.forEach(server => connect(server, timeoutInterval++)); -} - -function pickProxy(self, session) { - // TODO: Destructure :) - const transaction = session && session.transaction; - - if (transaction && transaction.server) { - if (transaction.server.isConnected()) { - return transaction.server; - } else { - transaction.unpinServer(); - } - } - - // Get the currently connected Proxies - var connectedProxies = self.connectedProxies.slice(0); - - // Set lower bound - var lowerBoundLatency = Number.MAX_VALUE; - - // Determine the lower bound for the Proxies - for (var i = 0; i < connectedProxies.length; i++) { - if (connectedProxies[i].lastIsMasterMS < lowerBoundLatency) { - lowerBoundLatency = connectedProxies[i].lastIsMasterMS; - } - } - - // Filter out the possible servers - connectedProxies = connectedProxies.filter(function(server) { - if ( - server.lastIsMasterMS <= lowerBoundLatency + self.s.localThresholdMS && - server.isConnected() - ) { - return true; - } - }); - - let proxy; - - // We have no connectedProxies pick first of the connected ones - if (connectedProxies.length === 0) { - proxy = self.connectedProxies[0]; - } else { - // Get proxy - proxy = connectedProxies[self.index % connectedProxies.length]; - // Update the index - self.index = (self.index + 1) % connectedProxies.length; - } - - if (transaction && transaction.isActive && proxy && proxy.isConnected()) { - transaction.pinServer(proxy); - } - - // Return the proxy - return proxy; -} - -function moveServerFrom(from, to, proxy) { - for (var i = 0; i < from.length; i++) { - if (from[i].name === proxy.name) { - from.splice(i, 1); - } - } - - for (i = 0; i < to.length; i++) { - if (to[i].name === proxy.name) { - to.splice(i, 1); - } - } - - to.push(proxy); -} - -function removeProxyFrom(from, proxy) { - for (var i = 0; i < from.length; i++) { - if (from[i].name === proxy.name) { - from.splice(i, 1); - } - } -} - -function reconnectProxies(self, proxies, callback) { - // Count lefts - var count = proxies.length; - - // Handle events - var _handleEvent = function(self, event) { - return function() { - var _self = this; - count = count - 1; - - // Destroyed - if (self.state === DESTROYED || self.state === DESTROYING || self.state === UNREFERENCED) { - moveServerFrom(self.connectingProxies, self.disconnectedProxies, _self); - return this.destroy(); - } - - if (event === 'connect') { - // Destroyed - if (self.state === DESTROYED || self.state === DESTROYING || self.state === UNREFERENCED) { - moveServerFrom(self.connectingProxies, self.disconnectedProxies, _self); - return _self.destroy(); - } - - // Remove the handlers - for (var i = 0; i < handlers.length; i++) { - _self.removeAllListeners(handlers[i]); - } - - // Add stable state handlers - _self.on('error', handleEvent(self, 'error')); - _self.on('close', handleEvent(self, 'close')); - _self.on('timeout', handleEvent(self, 'timeout')); - _self.on('parseError', handleEvent(self, 'parseError')); - - // Move to the connected servers - moveServerFrom(self.connectingProxies, self.connectedProxies, _self); - // Emit topology Change - emitTopologyDescriptionChanged(self); - // Emit joined event - self.emit('joined', 'mongos', _self); - } else { - // Move from connectingProxies - moveServerFrom(self.connectingProxies, self.disconnectedProxies, _self); - this.destroy(); - } - - // Are we done finish up callback - if (count === 0) { - callback(); - } - }; - }; - - // No new servers - if (count === 0) { - return callback(); - } - - // Execute method - function execute(_server, i) { - setTimeout(function() { - // Destroyed - if (self.state === DESTROYED || self.state === DESTROYING || self.state === UNREFERENCED) { - return; - } - - // Create a new server instance - var server = new Server( - Object.assign({}, self.s.options, { - host: _server.name.split(':')[0], - port: parseInt(_server.name.split(':')[1], 10), - reconnect: false, - monitoring: false, - parent: self, - clientInfo: clone(self.s.clientInfo) - }) - ); - - destroyServer(_server, { force: true }); - removeProxyFrom(self.disconnectedProxies, _server); - - // Relay the server description change - relayEvents(server, self, ['serverDescriptionChanged']); - - // Emit opening server event - self.emit('serverOpening', { - topologyId: server.s.topologyId !== -1 ? server.s.topologyId : self.id, - address: server.name - }); - - // Add temp handlers - server.once('connect', _handleEvent(self, 'connect')); - server.once('close', _handleEvent(self, 'close')); - server.once('timeout', _handleEvent(self, 'timeout')); - server.once('error', _handleEvent(self, 'error')); - server.once('parseError', _handleEvent(self, 'parseError')); - - // Command Monitoring events - relayEvents(server, self, ['commandStarted', 'commandSucceeded', 'commandFailed']); - - // Connect to proxy - self.connectingProxies.push(server); - server.connect(self.s.connectOptions); - }, i); - } - - // Create new instances - for (var i = 0; i < proxies.length; i++) { - execute(proxies[i], i); - } -} - -function topologyMonitor(self, options) { - options = options || {}; - - // no need to set up the monitor if we're already closed - if (self.state === DESTROYED || self.state === DESTROYING || self.state === UNREFERENCED) { - return; - } - - // Set momitoring timeout - self.haTimeoutId = setTimeout(function() { - if (self.state === DESTROYED || self.state === DESTROYING || self.state === UNREFERENCED) { - return; - } - - // If we have a primary and a disconnect handler, execute - // buffered operations - if (self.isConnected() && self.s.disconnectHandler) { - self.s.disconnectHandler.execute(); - } - - // Get the connectingServers - var proxies = self.connectedProxies.slice(0); - // Get the count - var count = proxies.length; - - // If the count is zero schedule a new fast - function pingServer(_self, _server, cb) { - // Measure running time - var start = new Date().getTime(); - - // Emit the server heartbeat start - emitSDAMEvent(self, 'serverHeartbeatStarted', { connectionId: _server.name }); - - // Execute ismaster - _server.command( - 'admin.$cmd', - { - ismaster: true - }, - { - monitoring: true, - socketTimeout: self.s.options.connectionTimeout || 2000 - }, - function(err, r) { - if ( - self.state === DESTROYED || - self.state === DESTROYING || - self.state === UNREFERENCED - ) { - // Move from connectingProxies - moveServerFrom(self.connectedProxies, self.disconnectedProxies, _server); - _server.destroy(); - return cb(err, r); - } - - // Calculate latency - var latencyMS = new Date().getTime() - start; - - // We had an error, remove it from the state - if (err) { - // Emit the server heartbeat failure - emitSDAMEvent(self, 'serverHeartbeatFailed', { - durationMS: latencyMS, - failure: err, - connectionId: _server.name - }); - // Move from connected proxies to disconnected proxies - moveServerFrom(self.connectedProxies, self.disconnectedProxies, _server); - } else { - // Update the server ismaster - _server.ismaster = r.result; - _server.lastIsMasterMS = latencyMS; - - // Server heart beat event - emitSDAMEvent(self, 'serverHeartbeatSucceeded', { - durationMS: latencyMS, - reply: r.result, - connectionId: _server.name - }); - } - - cb(err, r); - } - ); - } - - // No proxies initiate monitor again - if (proxies.length === 0) { - // Emit close event if any listeners registered - if (self.listeners('close').length > 0 && self.state === CONNECTING) { - self.emit('error', new MongoError('no mongos proxy available')); - } else { - self.emit('close', self); - } - - // Attempt to connect to any unknown servers - return reconnectProxies(self, self.disconnectedProxies, function() { - if (self.state === DESTROYED || self.state === DESTROYING || self.state === UNREFERENCED) { - return; - } - - // Are we connected ? emit connect event - if (self.state === CONNECTING && options.firstConnect) { - self.emit('connect', self); - self.emit('fullsetup', self); - self.emit('all', self); - } else if (self.isConnected()) { - self.emit('reconnect', self); - } else if (!self.isConnected() && self.listeners('close').length > 0) { - self.emit('close', self); - } - - // Perform topology monitor - topologyMonitor(self); - }); - } - - // Ping all servers - for (var i = 0; i < proxies.length; i++) { - pingServer(self, proxies[i], function() { - count = count - 1; - - if (count === 0) { - if ( - self.state === DESTROYED || - self.state === DESTROYING || - self.state === UNREFERENCED - ) { - return; - } - - // Attempt to connect to any unknown servers - reconnectProxies(self, self.disconnectedProxies, function() { - if ( - self.state === DESTROYED || - self.state === DESTROYING || - self.state === UNREFERENCED - ) { - return; - } - - // Perform topology monitor - topologyMonitor(self); - }); - } - }); - } - }, self.s.haInterval); -} - -/** - * Returns the last known ismaster document for this server - * @method - * @return {object} - */ -Mongos.prototype.lastIsMaster = function() { - return this.ismaster; -}; - -/** - * Unref all connections belong to this server - * @method - */ -Mongos.prototype.unref = function() { - // Transition state - stateTransition(this, UNREFERENCED); - // Get all proxies - var proxies = this.connectedProxies.concat(this.connectingProxies); - proxies.forEach(function(x) { - x.unref(); - }); - - clearTimeout(this.haTimeoutId); -}; - -/** - * Destroy the server connection - * @param {boolean} [options.force=false] Force destroy the pool - * @method - */ -Mongos.prototype.destroy = function(options, callback) { - if (typeof options === 'function') { - callback = options; - options = {}; - } - - options = options || {}; - - stateTransition(this, DESTROYING); - if (this.haTimeoutId) { - clearTimeout(this.haTimeoutId); - } - - const proxies = this.connectedProxies.concat(this.connectingProxies); - let serverCount = proxies.length; - const serverDestroyed = () => { - serverCount--; - if (serverCount > 0) { - return; - } - - emitTopologyDescriptionChanged(this); - emitSDAMEvent(this, 'topologyClosed', { topologyId: this.id }); - stateTransition(this, DESTROYED); - if (typeof callback === 'function') { - callback(null, null); - } - }; - - if (serverCount === 0) { - serverDestroyed(); - return; - } - - // Destroy all connecting servers - proxies.forEach(server => { - // Emit the sdam event - this.emit('serverClosed', { - topologyId: this.id, - address: server.name - }); - - destroyServer(server, options, serverDestroyed); - moveServerFrom(this.connectedProxies, this.disconnectedProxies, server); - }); -}; - -/** - * Figure out if the server is connected - * @method - * @return {boolean} - */ -Mongos.prototype.isConnected = function() { - return this.connectedProxies.length > 0; -}; - -/** - * Figure out if the server instance was destroyed by calling destroy - * @method - * @return {boolean} - */ -Mongos.prototype.isDestroyed = function() { - return this.state === DESTROYED; -}; - -// -// Operations -// - -function executeWriteOperation(args, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // TODO: once we drop Node 4, use destructuring either here or in arguments. - const self = args.self; - const op = args.op; - const ns = args.ns; - const ops = args.ops; - - // Pick a server - let server = pickProxy(self, options.session); - // No server found error out - if (!server) return callback(new MongoError('no mongos proxy available')); - - const willRetryWrite = - !args.retrying && - !!options.retryWrites && - options.session && - isRetryableWritesSupported(self) && - !options.session.inTransaction(); - - const handler = (err, result) => { - if (!err) return callback(null, result); - if (!isRetryableError(err) || !willRetryWrite) { - err = getMMAPError(err); - return callback(err); - } - - // Pick another server - server = pickProxy(self, options.session); - - // No server found error out with original error - if (!server) { - return callback(err); - } - - const newArgs = Object.assign({}, args, { retrying: true }); - return executeWriteOperation(newArgs, options, callback); - }; - - if (callback.operationId) { - handler.operationId = callback.operationId; - } - - // increment and assign txnNumber - if (willRetryWrite) { - options.session.incrementTransactionNumber(); - options.willRetryWrite = willRetryWrite; - } - - // rerun the operation - server[op](ns, ops, options, handler); -} - -/** - * Insert one or more documents - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of documents to insert - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {boolean} [options.retryWrites] Enable retryable writes for this operation - * @param {opResultCallback} callback A callback function - */ -Mongos.prototype.insert = function(ns, ops, options, callback) { - if (typeof options === 'function') { - (callback = options), (options = {}), (options = options || {}); - } - - if (this.state === DESTROYED) { - return callback(new MongoError(f('topology was destroyed'))); - } - - // Not connected but we have a disconnecthandler - if (!this.isConnected() && this.s.disconnectHandler != null) { - return this.s.disconnectHandler.add('insert', ns, ops, options, callback); - } - - // No mongos proxy available - if (!this.isConnected()) { - return callback(new MongoError('no mongos proxy available')); - } - - // Execute write operation - executeWriteOperation({ self: this, op: 'insert', ns, ops }, options, callback); -}; - -/** - * Perform one or more update operations - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of updates - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {boolean} [options.retryWrites] Enable retryable writes for this operation - * @param {opResultCallback} callback A callback function - */ -Mongos.prototype.update = function(ns, ops, options, callback) { - if (typeof options === 'function') { - (callback = options), (options = {}), (options = options || {}); - } - - if (this.state === DESTROYED) { - return callback(new MongoError(f('topology was destroyed'))); - } - - // Not connected but we have a disconnecthandler - if (!this.isConnected() && this.s.disconnectHandler != null) { - return this.s.disconnectHandler.add('update', ns, ops, options, callback); - } - - // No mongos proxy available - if (!this.isConnected()) { - return callback(new MongoError('no mongos proxy available')); - } - - // Execute write operation - executeWriteOperation({ self: this, op: 'update', ns, ops }, options, callback); -}; - -/** - * Perform one or more remove operations - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of removes - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {boolean} [options.retryWrites] Enable retryable writes for this operation - * @param {opResultCallback} callback A callback function - */ -Mongos.prototype.remove = function(ns, ops, options, callback) { - if (typeof options === 'function') { - (callback = options), (options = {}), (options = options || {}); - } - - if (this.state === DESTROYED) { - return callback(new MongoError(f('topology was destroyed'))); - } - - // Not connected but we have a disconnecthandler - if (!this.isConnected() && this.s.disconnectHandler != null) { - return this.s.disconnectHandler.add('remove', ns, ops, options, callback); - } - - // No mongos proxy available - if (!this.isConnected()) { - return callback(new MongoError('no mongos proxy available')); - } - - // Execute write operation - executeWriteOperation({ self: this, op: 'remove', ns, ops }, options, callback); -}; - -const RETRYABLE_WRITE_OPERATIONS = ['findAndModify', 'insert', 'update', 'delete']; - -function isWriteCommand(command) { - return RETRYABLE_WRITE_OPERATIONS.some(op => command[op]); -} - -/** - * Execute a command - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object} cmd The command hash - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @param {Connection} [options.connection] Specify connection object to execute command against - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {opResultCallback} callback A callback function - */ -Mongos.prototype.command = function(ns, cmd, options, callback) { - if (typeof options === 'function') { - (callback = options), (options = {}), (options = options || {}); - } - - if (this.state === DESTROYED) { - return callback(new MongoError(f('topology was destroyed'))); - } - - var self = this; - - // Pick a proxy - var server = pickProxy(self, options.session); - - // Topology is not connected, save the call in the provided store to be - // Executed at some point when the handler deems it's reconnected - if ((server == null || !server.isConnected()) && this.s.disconnectHandler != null) { - return this.s.disconnectHandler.add('command', ns, cmd, options, callback); - } - - // No server returned we had an error - if (server == null) { - return callback(new MongoError('no mongos proxy available')); - } - - // Cloned options - var clonedOptions = cloneOptions(options); - clonedOptions.topology = self; - - const willRetryWrite = - !options.retrying && - options.retryWrites && - options.session && - isRetryableWritesSupported(self) && - !options.session.inTransaction() && - isWriteCommand(cmd); - - const cb = (err, result) => { - if (!err) return callback(null, result); - if (!isRetryableError(err)) { - return callback(err); - } - - if (willRetryWrite) { - const newOptions = Object.assign({}, clonedOptions, { retrying: true }); - return this.command(ns, cmd, newOptions, callback); - } - - return callback(err); - }; - - // increment and assign txnNumber - if (willRetryWrite) { - options.session.incrementTransactionNumber(); - options.willRetryWrite = willRetryWrite; - } - - // Execute the command - server.command(ns, cmd, clonedOptions, cb); -}; - -/** - * Get a new cursor - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object|Long} cmd Can be either a command returning a cursor or a cursorId - * @param {object} [options] Options for the cursor - * @param {object} [options.batchSize=0] Batchsize for the operation - * @param {array} [options.documents=[]] Initial documents list for cursor - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {object} [options.topology] The internal topology of the created cursor - * @returns {Cursor} - */ -Mongos.prototype.cursor = function(ns, cmd, options) { - options = options || {}; - const topology = options.topology || this; - - // Set up final cursor type - var FinalCursor = options.cursorFactory || this.s.Cursor; - - // Return the cursor - return new FinalCursor(topology, ns, cmd, options); -}; - -/** - * Selects a server - * - * @method - * @param {function} selector Unused - * @param {ReadPreference} [options.readPreference] Unused - * @param {ClientSession} [options.session] Specify a session if it is being used - * @param {function} callback - */ -Mongos.prototype.selectServer = function(selector, options, callback) { - if (typeof selector === 'function' && typeof callback === 'undefined') - (callback = selector), (selector = undefined), (options = {}); - if (typeof options === 'function') - (callback = options), (options = selector), (selector = undefined); - options = options || {}; - - const server = pickProxy(this, options.session); - if (server == null) { - callback(new MongoError('server selection failed')); - return; - } - - if (this.s.debug) this.emit('pickedServer', null, server); - callback(null, server); -}; - -/** - * All raw connections - * @method - * @return {Connection[]} - */ -Mongos.prototype.connections = function() { - var connections = []; - - for (var i = 0; i < this.connectedProxies.length; i++) { - connections = connections.concat(this.connectedProxies[i].connections()); - } - - return connections; -}; - -function emitTopologyDescriptionChanged(self) { - if (self.listeners('topologyDescriptionChanged').length > 0) { - var topology = 'Unknown'; - if (self.connectedProxies.length > 0) { - topology = 'Sharded'; - } - - // Generate description - var description = { - topologyType: topology, - servers: [] - }; - - // All proxies - var proxies = self.disconnectedProxies.concat(self.connectingProxies); - - // Add all the disconnected proxies - description.servers = description.servers.concat( - proxies.map(function(x) { - var description = x.getDescription(); - description.type = 'Unknown'; - return description; - }) - ); - - // Add all the connected proxies - description.servers = description.servers.concat( - self.connectedProxies.map(function(x) { - var description = x.getDescription(); - description.type = 'Mongos'; - return description; - }) - ); - - // Get the diff - var diffResult = diff(self.topologyDescription, description); - - // Create the result - var result = { - topologyId: self.id, - previousDescription: self.topologyDescription, - newDescription: description, - diff: diffResult - }; - - // Emit the topologyDescription change - if (diffResult.servers.length > 0) { - self.emit('topologyDescriptionChanged', result); - } - - // Set the new description - self.topologyDescription = description; - } -} - -/** - * A mongos connect event, used to verify that the connection is up and running - * - * @event Mongos#connect - * @type {Mongos} - */ - -/** - * A mongos reconnect event, used to verify that the mongos topology has reconnected - * - * @event Mongos#reconnect - * @type {Mongos} - */ - -/** - * A mongos fullsetup event, used to signal that all topology members have been contacted. - * - * @event Mongos#fullsetup - * @type {Mongos} - */ - -/** - * A mongos all event, used to signal that all topology members have been contacted. - * - * @event Mongos#all - * @type {Mongos} - */ - -/** - * A server member left the mongos list - * - * @event Mongos#left - * @type {Mongos} - * @param {string} type The type of member that left (mongos) - * @param {Server} server The server object that left - */ - -/** - * A server member joined the mongos list - * - * @event Mongos#joined - * @type {Mongos} - * @param {string} type The type of member that left (mongos) - * @param {Server} server The server object that joined - */ - -/** - * A server opening SDAM monitoring event - * - * @event Mongos#serverOpening - * @type {object} - */ - -/** - * A server closed SDAM monitoring event - * - * @event Mongos#serverClosed - * @type {object} - */ - -/** - * A server description SDAM change monitoring event - * - * @event Mongos#serverDescriptionChanged - * @type {object} - */ - -/** - * A topology open SDAM event - * - * @event Mongos#topologyOpening - * @type {object} - */ - -/** - * A topology closed SDAM event - * - * @event Mongos#topologyClosed - * @type {object} - */ - -/** - * A topology structure SDAM change event - * - * @event Mongos#topologyDescriptionChanged - * @type {object} - */ - -/** - * A topology serverHeartbeatStarted SDAM event - * - * @event Mongos#serverHeartbeatStarted - * @type {object} - */ - -/** - * A topology serverHeartbeatFailed SDAM event - * - * @event Mongos#serverHeartbeatFailed - * @type {object} - */ - -/** - * A topology serverHeartbeatSucceeded SDAM change event - * - * @event Mongos#serverHeartbeatSucceeded - * @type {object} - */ - -/** - * An event emitted indicating a command was started, if command monitoring is enabled - * - * @event Mongos#commandStarted - * @type {object} - */ - -/** - * An event emitted indicating a command succeeded, if command monitoring is enabled - * - * @event Mongos#commandSucceeded - * @type {object} - */ - -/** - * An event emitted indicating a command failed, if command monitoring is enabled - * - * @event Mongos#commandFailed - * @type {object} - */ - -module.exports = Mongos; diff --git a/scripts/node_modules/mongodb/lib/core/topologies/read_preference.js b/scripts/node_modules/mongodb/lib/core/topologies/read_preference.js deleted file mode 100644 index a813ec4f..00000000 --- a/scripts/node_modules/mongodb/lib/core/topologies/read_preference.js +++ /dev/null @@ -1,202 +0,0 @@ -'use strict'; - -/** - * The **ReadPreference** class is a class that represents a MongoDB ReadPreference and is - * used to construct connections. - * @class - * @param {string} mode A string describing the read preference mode (primary|primaryPreferred|secondary|secondaryPreferred|nearest) - * @param {array} tags The tags object - * @param {object} [options] Additional read preference options - * @param {number} [options.maxStalenessSeconds] Max secondary read staleness in seconds, Minimum value is 90 seconds. - * @see https://docs.mongodb.com/manual/core/read-preference/ - * @return {ReadPreference} - */ -const ReadPreference = function(mode, tags, options) { - if (!ReadPreference.isValid(mode)) { - throw new TypeError(`Invalid read preference mode ${mode}`); - } - - // TODO(major): tags MUST be an array of tagsets - if (tags && !Array.isArray(tags)) { - console.warn( - 'ReadPreference tags must be an array, this will change in the next major version' - ); - - if (typeof tags.maxStalenessSeconds !== 'undefined') { - // this is likely an options object - options = tags; - tags = undefined; - } else { - tags = [tags]; - } - } - - this.mode = mode; - this.tags = tags; - - options = options || {}; - if (options.maxStalenessSeconds != null) { - if (options.maxStalenessSeconds <= 0) { - throw new TypeError('maxStalenessSeconds must be a positive integer'); - } - - this.maxStalenessSeconds = options.maxStalenessSeconds; - - // NOTE: The minimum required wire version is 5 for this read preference. If the existing - // topology has a lower value then a MongoError will be thrown during server selection. - this.minWireVersion = 5; - } - - if (this.mode === ReadPreference.PRIMARY) { - if (this.tags && Array.isArray(this.tags) && this.tags.length > 0) { - throw new TypeError('Primary read preference cannot be combined with tags'); - } - - if (this.maxStalenessSeconds) { - throw new TypeError('Primary read preference cannot be combined with maxStalenessSeconds'); - } - } -}; - -// Support the deprecated `preference` property introduced in the porcelain layer -Object.defineProperty(ReadPreference.prototype, 'preference', { - enumerable: true, - get: function() { - return this.mode; - } -}); - -/* - * Read preference mode constants - */ -ReadPreference.PRIMARY = 'primary'; -ReadPreference.PRIMARY_PREFERRED = 'primaryPreferred'; -ReadPreference.SECONDARY = 'secondary'; -ReadPreference.SECONDARY_PREFERRED = 'secondaryPreferred'; -ReadPreference.NEAREST = 'nearest'; - -const VALID_MODES = [ - ReadPreference.PRIMARY, - ReadPreference.PRIMARY_PREFERRED, - ReadPreference.SECONDARY, - ReadPreference.SECONDARY_PREFERRED, - ReadPreference.NEAREST, - null -]; - -/** - * Construct a ReadPreference given an options object. - * - * @param {object} options The options object from which to extract the read preference. - * @return {ReadPreference} - */ -ReadPreference.fromOptions = function(options) { - const readPreference = options.readPreference; - const readPreferenceTags = options.readPreferenceTags; - - if (readPreference == null) { - return null; - } - - if (typeof readPreference === 'string') { - return new ReadPreference(readPreference, readPreferenceTags); - } else if (!(readPreference instanceof ReadPreference) && typeof readPreference === 'object') { - const mode = readPreference.mode || readPreference.preference; - if (mode && typeof mode === 'string') { - return new ReadPreference(mode, readPreference.tags, { - maxStalenessSeconds: readPreference.maxStalenessSeconds - }); - } - } - - return readPreference; -}; - -/** - * Validate if a mode is legal - * - * @method - * @param {string} mode The string representing the read preference mode. - * @return {boolean} True if a mode is valid - */ -ReadPreference.isValid = function(mode) { - return VALID_MODES.indexOf(mode) !== -1; -}; - -/** - * Validate if a mode is legal - * - * @method - * @param {string} mode The string representing the read preference mode. - * @return {boolean} True if a mode is valid - */ -ReadPreference.prototype.isValid = function(mode) { - return ReadPreference.isValid(typeof mode === 'string' ? mode : this.mode); -}; - -const needSlaveOk = ['primaryPreferred', 'secondary', 'secondaryPreferred', 'nearest']; - -/** - * Indicates that this readPreference needs the "slaveOk" bit when sent over the wire - * @method - * @return {boolean} - * @see https://docs.mongodb.com/manual/reference/mongodb-wire-protocol/#op-query - */ -ReadPreference.prototype.slaveOk = function() { - return needSlaveOk.indexOf(this.mode) !== -1; -}; - -/** - * Are the two read preference equal - * @method - * @param {ReadPreference} readPreference The read preference with which to check equality - * @return {boolean} True if the two ReadPreferences are equivalent - */ -ReadPreference.prototype.equals = function(readPreference) { - return readPreference.mode === this.mode; -}; - -/** - * Return JSON representation - * @method - * @return {Object} A JSON representation of the ReadPreference - */ -ReadPreference.prototype.toJSON = function() { - const readPreference = { mode: this.mode }; - if (Array.isArray(this.tags)) readPreference.tags = this.tags; - if (this.maxStalenessSeconds) readPreference.maxStalenessSeconds = this.maxStalenessSeconds; - return readPreference; -}; - -/** - * Primary read preference - * @member - * @type {ReadPreference} - */ -ReadPreference.primary = new ReadPreference('primary'); -/** - * Primary Preferred read preference - * @member - * @type {ReadPreference} - */ -ReadPreference.primaryPreferred = new ReadPreference('primaryPreferred'); -/** - * Secondary read preference - * @member - * @type {ReadPreference} - */ -ReadPreference.secondary = new ReadPreference('secondary'); -/** - * Secondary Preferred read preference - * @member - * @type {ReadPreference} - */ -ReadPreference.secondaryPreferred = new ReadPreference('secondaryPreferred'); -/** - * Nearest read preference - * @member - * @type {ReadPreference} - */ -ReadPreference.nearest = new ReadPreference('nearest'); - -module.exports = ReadPreference; diff --git a/scripts/node_modules/mongodb/lib/core/topologies/replset.js b/scripts/node_modules/mongodb/lib/core/topologies/replset.js deleted file mode 100644 index 89403ea4..00000000 --- a/scripts/node_modules/mongodb/lib/core/topologies/replset.js +++ /dev/null @@ -1,1553 +0,0 @@ -'use strict'; - -const inherits = require('util').inherits; -const f = require('util').format; -const EventEmitter = require('events').EventEmitter; -const ReadPreference = require('./read_preference'); -const CoreCursor = require('../cursor').CoreCursor; -const retrieveBSON = require('../connection/utils').retrieveBSON; -const Logger = require('../connection/logger'); -const MongoError = require('../error').MongoError; -const Server = require('./server'); -const ReplSetState = require('./replset_state'); -const clone = require('./shared').clone; -const Timeout = require('./shared').Timeout; -const Interval = require('./shared').Interval; -const createClientInfo = require('./shared').createClientInfo; -const SessionMixins = require('./shared').SessionMixins; -const isRetryableWritesSupported = require('./shared').isRetryableWritesSupported; -const relayEvents = require('../utils').relayEvents; -const isRetryableError = require('../error').isRetryableError; -const BSON = retrieveBSON(); -const calculateDurationInMs = require('../utils').calculateDurationInMs; -const getMMAPError = require('./shared').getMMAPError; - -// -// States -var DISCONNECTED = 'disconnected'; -var CONNECTING = 'connecting'; -var CONNECTED = 'connected'; -var UNREFERENCED = 'unreferenced'; -var DESTROYED = 'destroyed'; - -function stateTransition(self, newState) { - var legalTransitions = { - disconnected: [CONNECTING, DESTROYED, DISCONNECTED], - connecting: [CONNECTING, DESTROYED, CONNECTED, DISCONNECTED], - connected: [CONNECTED, DISCONNECTED, DESTROYED, UNREFERENCED], - unreferenced: [UNREFERENCED, DESTROYED], - destroyed: [DESTROYED] - }; - - // Get current state - var legalStates = legalTransitions[self.state]; - if (legalStates && legalStates.indexOf(newState) !== -1) { - self.state = newState; - } else { - self.s.logger.error( - f( - 'Pool with id [%s] failed attempted illegal state transition from [%s] to [%s] only following state allowed [%s]', - self.id, - self.state, - newState, - legalStates - ) - ); - } -} - -// -// ReplSet instance id -var id = 1; -var handlers = ['connect', 'close', 'error', 'timeout', 'parseError']; - -/** - * Creates a new Replset instance - * @class - * @param {array} seedlist A list of seeds for the replicaset - * @param {boolean} options.setName The Replicaset set name - * @param {boolean} [options.secondaryOnlyConnectionAllowed=false] Allow connection to a secondary only replicaset - * @param {number} [options.haInterval=10000] The High availability period for replicaset inquiry - * @param {boolean} [options.emitError=false] Server will emit errors events - * @param {Cursor} [options.cursorFactory=Cursor] The cursor factory class used for all query cursors - * @param {number} [options.size=5] Server connection pool size - * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled - * @param {number} [options.keepAliveInitialDelay=0] Initial delay before TCP keep alive enabled - * @param {boolean} [options.noDelay=true] TCP Connection no delay - * @param {number} [options.connectionTimeout=10000] TCP Connection timeout setting - * @param {number} [options.socketTimeout=0] TCP Socket timeout setting - * @param {boolean} [options.ssl=false] Use SSL for connection - * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. - * @param {Buffer} [options.ca] SSL Certificate store binary buffer - * @param {Buffer} [options.crl] SSL Certificate revocation store binary buffer - * @param {Buffer} [options.cert] SSL Certificate binary buffer - * @param {Buffer} [options.key] SSL Key file binary buffer - * @param {string} [options.passphrase] SSL Certificate pass phrase - * @param {string} [options.servername=null] String containing the server name requested via TLS SNI. - * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates - * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits - * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. - * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. - * @param {number} [options.pingInterval=5000] Ping interval to check the response time to the different servers - * @param {number} [options.localThresholdMS=15] Cutoff latency point in MS for Replicaset member selection - * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. - * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology - * @return {ReplSet} A cursor instance - * @fires ReplSet#connect - * @fires ReplSet#ha - * @fires ReplSet#joined - * @fires ReplSet#left - * @fires ReplSet#failed - * @fires ReplSet#fullsetup - * @fires ReplSet#all - * @fires ReplSet#error - * @fires ReplSet#serverHeartbeatStarted - * @fires ReplSet#serverHeartbeatSucceeded - * @fires ReplSet#serverHeartbeatFailed - * @fires ReplSet#topologyOpening - * @fires ReplSet#topologyClosed - * @fires ReplSet#topologyDescriptionChanged - * @property {string} type the topology type. - * @property {string} parserType the parser type used (c++ or js). - */ -var ReplSet = function(seedlist, options) { - var self = this; - options = options || {}; - - // Validate seedlist - if (!Array.isArray(seedlist)) throw new MongoError('seedlist must be an array'); - // Validate list - if (seedlist.length === 0) throw new MongoError('seedlist must contain at least one entry'); - // Validate entries - seedlist.forEach(function(e) { - if (typeof e.host !== 'string' || typeof e.port !== 'number') - throw new MongoError('seedlist entry must contain a host and port'); - }); - - // Add event listener - EventEmitter.call(this); - - // Get replSet Id - this.id = id++; - - // Get the localThresholdMS - var localThresholdMS = options.localThresholdMS || 15; - // Backward compatibility - if (options.acceptableLatency) localThresholdMS = options.acceptableLatency; - - // Create a logger - var logger = Logger('ReplSet', options); - - // Internal state - this.s = { - options: Object.assign({}, options), - // BSON instance - bson: - options.bson || - new BSON([ - BSON.Binary, - BSON.Code, - BSON.DBRef, - BSON.Decimal128, - BSON.Double, - BSON.Int32, - BSON.Long, - BSON.Map, - BSON.MaxKey, - BSON.MinKey, - BSON.ObjectId, - BSON.BSONRegExp, - BSON.Symbol, - BSON.Timestamp - ]), - // Factory overrides - Cursor: options.cursorFactory || CoreCursor, - // Logger instance - logger: logger, - // Seedlist - seedlist: seedlist, - // Replicaset state - replicaSetState: new ReplSetState({ - id: this.id, - setName: options.setName, - acceptableLatency: localThresholdMS, - heartbeatFrequencyMS: options.haInterval ? options.haInterval : 10000, - logger: logger - }), - // Current servers we are connecting to - connectingServers: [], - // Ha interval - haInterval: options.haInterval ? options.haInterval : 10000, - // Minimum heartbeat frequency used if we detect a server close - minHeartbeatFrequencyMS: 500, - // Disconnect handler - disconnectHandler: options.disconnectHandler, - // Server selection index - index: 0, - // Connect function options passed in - connectOptions: {}, - // Are we running in debug mode - debug: typeof options.debug === 'boolean' ? options.debug : false, - // Client info - clientInfo: createClientInfo(options) - }; - - // Add handler for topology change - this.s.replicaSetState.on('topologyDescriptionChanged', function(r) { - self.emit('topologyDescriptionChanged', r); - }); - - // Log info warning if the socketTimeout < haInterval as it will cause - // a lot of recycled connections to happen. - if ( - this.s.logger.isWarn() && - this.s.options.socketTimeout !== 0 && - this.s.options.socketTimeout < this.s.haInterval - ) { - this.s.logger.warn( - f( - 'warning socketTimeout %s is less than haInterval %s. This might cause unnecessary server reconnections due to socket timeouts', - this.s.options.socketTimeout, - this.s.haInterval - ) - ); - } - - // Add forwarding of events from state handler - var types = ['joined', 'left']; - types.forEach(function(x) { - self.s.replicaSetState.on(x, function(t, s) { - self.emit(x, t, s); - }); - }); - - // Connect stat - this.initialConnectState = { - connect: false, - fullsetup: false, - all: false - }; - - // Disconnected state - this.state = DISCONNECTED; - this.haTimeoutId = null; - // Last ismaster - this.ismaster = null; - // Contains the intervalId - this.intervalIds = []; - - // Highest clusterTime seen in responses from the current deployment - this.clusterTime = null; -}; - -inherits(ReplSet, EventEmitter); -Object.assign(ReplSet.prototype, SessionMixins); - -Object.defineProperty(ReplSet.prototype, 'type', { - enumerable: true, - get: function() { - return 'replset'; - } -}); - -Object.defineProperty(ReplSet.prototype, 'parserType', { - enumerable: true, - get: function() { - return BSON.native ? 'c++' : 'js'; - } -}); - -Object.defineProperty(ReplSet.prototype, 'logicalSessionTimeoutMinutes', { - enumerable: true, - get: function() { - return this.s.replicaSetState.logicalSessionTimeoutMinutes || null; - } -}); - -function rexecuteOperations(self) { - // If we have a primary and a disconnect handler, execute - // buffered operations - if (self.s.replicaSetState.hasPrimaryAndSecondary() && self.s.disconnectHandler) { - self.s.disconnectHandler.execute(); - } else if (self.s.replicaSetState.hasPrimary() && self.s.disconnectHandler) { - self.s.disconnectHandler.execute({ executePrimary: true }); - } else if (self.s.replicaSetState.hasSecondary() && self.s.disconnectHandler) { - self.s.disconnectHandler.execute({ executeSecondary: true }); - } -} - -function connectNewServers(self, servers, callback) { - // Count lefts - var count = servers.length; - var error = null; - - // Handle events - var _handleEvent = function(self, event) { - return function(err) { - var _self = this; - count = count - 1; - - // Destroyed - if (self.state === DESTROYED || self.state === UNREFERENCED) { - return this.destroy({ force: true }); - } - - if (event === 'connect') { - // Destroyed - if (self.state === DESTROYED || self.state === UNREFERENCED) { - return _self.destroy({ force: true }); - } - - // Update the state - var result = self.s.replicaSetState.update(_self); - // Update the state with the new server - if (result) { - // Primary lastIsMaster store it - if (_self.lastIsMaster() && _self.lastIsMaster().ismaster) { - self.ismaster = _self.lastIsMaster(); - } - - // Remove the handlers - for (let i = 0; i < handlers.length; i++) { - _self.removeAllListeners(handlers[i]); - } - - // Add stable state handlers - _self.on('error', handleEvent(self, 'error')); - _self.on('close', handleEvent(self, 'close')); - _self.on('timeout', handleEvent(self, 'timeout')); - _self.on('parseError', handleEvent(self, 'parseError')); - - // Enalbe the monitoring of the new server - monitorServer(_self.lastIsMaster().me, self, {}); - - // Rexecute any stalled operation - rexecuteOperations(self); - } else { - _self.destroy({ force: true }); - } - } else if (event === 'error') { - error = err; - } - - // Rexecute any stalled operation - rexecuteOperations(self); - - // Are we done finish up callback - if (count === 0) { - callback(error); - } - }; - }; - - // No new servers - if (count === 0) return callback(); - - // Execute method - function execute(_server, i) { - setTimeout(function() { - // Destroyed - if (self.state === DESTROYED || self.state === UNREFERENCED) { - return; - } - - // Create a new server instance - var server = new Server( - Object.assign({}, self.s.options, { - host: _server.split(':')[0], - port: parseInt(_server.split(':')[1], 10), - reconnect: false, - monitoring: false, - parent: self, - clientInfo: clone(self.s.clientInfo) - }) - ); - - // Add temp handlers - server.once('connect', _handleEvent(self, 'connect')); - server.once('close', _handleEvent(self, 'close')); - server.once('timeout', _handleEvent(self, 'timeout')); - server.once('error', _handleEvent(self, 'error')); - server.once('parseError', _handleEvent(self, 'parseError')); - - // SDAM Monitoring events - server.on('serverOpening', e => self.emit('serverOpening', e)); - server.on('serverDescriptionChanged', e => self.emit('serverDescriptionChanged', e)); - server.on('serverClosed', e => self.emit('serverClosed', e)); - - // Command Monitoring events - relayEvents(server, self, ['commandStarted', 'commandSucceeded', 'commandFailed']); - - self.s.connectingServers.push(server); - server.connect(self.s.connectOptions); - }, i); - } - - // Create new instances - for (var i = 0; i < servers.length; i++) { - execute(servers[i], i); - } -} - -// Ping the server -var pingServer = function(self, server, cb) { - // Measure running time - var start = new Date().getTime(); - - // Emit the server heartbeat start - emitSDAMEvent(self, 'serverHeartbeatStarted', { connectionId: server.name }); - - // Execute ismaster - // Set the socketTimeout for a monitoring message to a low number - // Ensuring ismaster calls are timed out quickly - server.command( - 'admin.$cmd', - { - ismaster: true - }, - { - monitoring: true, - socketTimeout: self.s.options.connectionTimeout || 2000 - }, - function(err, r) { - if (self.state === DESTROYED || self.state === UNREFERENCED) { - server.destroy({ force: true }); - return cb(err, r); - } - - // Calculate latency - var latencyMS = new Date().getTime() - start; - - // Set the last updatedTime - var hrtime = process.hrtime(); - server.lastUpdateTime = (hrtime[0] * 1e9 + hrtime[1]) / 1e6; - - // We had an error, remove it from the state - if (err) { - // Emit the server heartbeat failure - emitSDAMEvent(self, 'serverHeartbeatFailed', { - durationMS: latencyMS, - failure: err, - connectionId: server.name - }); - - // Remove server from the state - self.s.replicaSetState.remove(server); - } else { - // Update the server ismaster - server.ismaster = r.result; - - // Check if we have a lastWriteDate convert it to MS - // and store on the server instance for later use - if (server.ismaster.lastWrite && server.ismaster.lastWrite.lastWriteDate) { - server.lastWriteDate = server.ismaster.lastWrite.lastWriteDate.getTime(); - } - - // Do we have a brand new server - if (server.lastIsMasterMS === -1) { - server.lastIsMasterMS = latencyMS; - } else if (server.lastIsMasterMS) { - // After the first measurement, average RTT MUST be computed using an - // exponentially-weighted moving average formula, with a weighting factor (alpha) of 0.2. - // If the prior average is denoted old_rtt, then the new average (new_rtt) is - // computed from a new RTT measurement (x) using the following formula: - // alpha = 0.2 - // new_rtt = alpha * x + (1 - alpha) * old_rtt - server.lastIsMasterMS = 0.2 * latencyMS + (1 - 0.2) * server.lastIsMasterMS; - } - - if (self.s.replicaSetState.update(server)) { - // Primary lastIsMaster store it - if (server.lastIsMaster() && server.lastIsMaster().ismaster) { - self.ismaster = server.lastIsMaster(); - } - } - - // Server heart beat event - emitSDAMEvent(self, 'serverHeartbeatSucceeded', { - durationMS: latencyMS, - reply: r.result, - connectionId: server.name - }); - } - - // Calculate the staleness for this server - self.s.replicaSetState.updateServerMaxStaleness(server, self.s.haInterval); - - // Callback - cb(err, r); - } - ); -}; - -// Each server is monitored in parallel in their own timeout loop -var monitorServer = function(host, self, options) { - // If this is not the initial scan - // Is this server already being monitoried, then skip monitoring - if (!options.haInterval) { - for (var i = 0; i < self.intervalIds.length; i++) { - if (self.intervalIds[i].__host === host) { - return; - } - } - } - - // Get the haInterval - var _process = options.haInterval ? Timeout : Interval; - var _haInterval = options.haInterval ? options.haInterval : self.s.haInterval; - - // Create the interval - var intervalId = new _process(function() { - if (self.state === DESTROYED || self.state === UNREFERENCED) { - // clearInterval(intervalId); - intervalId.stop(); - return; - } - - // Do we already have server connection available for this host - var _server = self.s.replicaSetState.get(host); - - // Check if we have a known server connection and reuse - if (_server) { - // Ping the server - return pingServer(self, _server, function(err) { - if (err) { - // NOTE: should something happen here? - return; - } - - if (self.state === DESTROYED || self.state === UNREFERENCED) { - intervalId.stop(); - return; - } - - // Filter out all called intervaliIds - self.intervalIds = self.intervalIds.filter(function(intervalId) { - return intervalId.isRunning(); - }); - - // Initial sweep - if (_process === Timeout) { - if ( - self.state === CONNECTING && - ((self.s.replicaSetState.hasSecondary() && - self.s.options.secondaryOnlyConnectionAllowed) || - self.s.replicaSetState.hasPrimary()) - ) { - self.state = CONNECTED; - - // Emit connected sign - process.nextTick(function() { - self.emit('connect', self); - }); - - // Start topology interval check - topologyMonitor(self, {}); - } - } else { - if ( - self.state === DISCONNECTED && - ((self.s.replicaSetState.hasSecondary() && - self.s.options.secondaryOnlyConnectionAllowed) || - self.s.replicaSetState.hasPrimary()) - ) { - self.state = CONNECTED; - - // Rexecute any stalled operation - rexecuteOperations(self); - - // Emit connected sign - process.nextTick(function() { - self.emit('reconnect', self); - }); - } - } - - if ( - self.initialConnectState.connect && - !self.initialConnectState.fullsetup && - self.s.replicaSetState.hasPrimaryAndSecondary() - ) { - // Set initial connect state - self.initialConnectState.fullsetup = true; - self.initialConnectState.all = true; - - process.nextTick(function() { - self.emit('fullsetup', self); - self.emit('all', self); - }); - } - }); - } - }, _haInterval); - - // Start the interval - intervalId.start(); - // Add the intervalId host name - intervalId.__host = host; - // Add the intervalId to our list of intervalIds - self.intervalIds.push(intervalId); -}; - -function topologyMonitor(self, options) { - if (self.state === DESTROYED || self.state === UNREFERENCED) return; - options = options || {}; - - // Get the servers - var servers = Object.keys(self.s.replicaSetState.set); - - // Get the haInterval - var _process = options.haInterval ? Timeout : Interval; - var _haInterval = options.haInterval ? options.haInterval : self.s.haInterval; - - if (_process === Timeout) { - return connectNewServers(self, self.s.replicaSetState.unknownServers, function(err) { - // Don't emit errors if the connection was already - if (self.state === DESTROYED || self.state === UNREFERENCED) { - return; - } - - if (!self.s.replicaSetState.hasPrimary() && !self.s.options.secondaryOnlyConnectionAllowed) { - if (err) { - return self.emit('error', err); - } - - self.emit( - 'error', - new MongoError('no primary found in replicaset or invalid replica set name') - ); - return self.destroy({ force: true }); - } else if ( - !self.s.replicaSetState.hasSecondary() && - self.s.options.secondaryOnlyConnectionAllowed - ) { - if (err) { - return self.emit('error', err); - } - - self.emit( - 'error', - new MongoError('no secondary found in replicaset or invalid replica set name') - ); - return self.destroy({ force: true }); - } - - for (var i = 0; i < servers.length; i++) { - monitorServer(servers[i], self, options); - } - }); - } else { - for (var i = 0; i < servers.length; i++) { - monitorServer(servers[i], self, options); - } - } - - // Run the reconnect process - function executeReconnect(self) { - return function() { - if (self.state === DESTROYED || self.state === UNREFERENCED) { - return; - } - - connectNewServers(self, self.s.replicaSetState.unknownServers, function() { - var monitoringFrequencey = self.s.replicaSetState.hasPrimary() - ? _haInterval - : self.s.minHeartbeatFrequencyMS; - - // Create a timeout - self.intervalIds.push(new Timeout(executeReconnect(self), monitoringFrequencey).start()); - }); - }; - } - - // Decide what kind of interval to use - var intervalTime = !self.s.replicaSetState.hasPrimary() - ? self.s.minHeartbeatFrequencyMS - : _haInterval; - - self.intervalIds.push(new Timeout(executeReconnect(self), intervalTime).start()); -} - -function addServerToList(list, server) { - for (var i = 0; i < list.length; i++) { - if (list[i].name.toLowerCase() === server.name.toLowerCase()) return true; - } - - list.push(server); -} - -function handleEvent(self, event) { - return function() { - if (self.state === DESTROYED || self.state === UNREFERENCED) return; - // Debug log - if (self.s.logger.isDebug()) { - self.s.logger.debug( - f('handleEvent %s from server %s in replset with id %s', event, this.name, self.id) - ); - } - - // Remove from the replicaset state - self.s.replicaSetState.remove(this); - - // Are we in a destroyed state return - if (self.state === DESTROYED || self.state === UNREFERENCED) return; - - // If no primary and secondary available - if ( - !self.s.replicaSetState.hasPrimary() && - !self.s.replicaSetState.hasSecondary() && - self.s.options.secondaryOnlyConnectionAllowed - ) { - stateTransition(self, DISCONNECTED); - } else if (!self.s.replicaSetState.hasPrimary()) { - stateTransition(self, DISCONNECTED); - } - - addServerToList(self.s.connectingServers, this); - }; -} - -function shouldTriggerConnect(self) { - const isConnecting = self.state === CONNECTING; - const hasPrimary = self.s.replicaSetState.hasPrimary(); - const hasSecondary = self.s.replicaSetState.hasSecondary(); - const secondaryOnlyConnectionAllowed = self.s.options.secondaryOnlyConnectionAllowed; - const readPreferenceSecondary = - self.s.connectOptions.readPreference && - self.s.connectOptions.readPreference.equals(ReadPreference.secondary); - - return ( - (isConnecting && - ((readPreferenceSecondary && hasSecondary) || (!readPreferenceSecondary && hasPrimary))) || - (hasSecondary && secondaryOnlyConnectionAllowed) - ); -} - -function handleInitialConnectEvent(self, event) { - return function() { - var _this = this; - // Debug log - if (self.s.logger.isDebug()) { - self.s.logger.debug( - f( - 'handleInitialConnectEvent %s from server %s in replset with id %s', - event, - this.name, - self.id - ) - ); - } - - // Destroy the instance - if (self.state === DESTROYED || self.state === UNREFERENCED) { - return this.destroy({ force: true }); - } - - // Check the type of server - if (event === 'connect') { - // Update the state - var result = self.s.replicaSetState.update(_this); - if (result === true) { - // Primary lastIsMaster store it - if (_this.lastIsMaster() && _this.lastIsMaster().ismaster) { - self.ismaster = _this.lastIsMaster(); - } - - // Debug log - if (self.s.logger.isDebug()) { - self.s.logger.debug( - f( - 'handleInitialConnectEvent %s from server %s in replset with id %s has state [%s]', - event, - _this.name, - self.id, - JSON.stringify(self.s.replicaSetState.set) - ) - ); - } - - // Remove the handlers - for (let i = 0; i < handlers.length; i++) { - _this.removeAllListeners(handlers[i]); - } - - // Add stable state handlers - _this.on('error', handleEvent(self, 'error')); - _this.on('close', handleEvent(self, 'close')); - _this.on('timeout', handleEvent(self, 'timeout')); - _this.on('parseError', handleEvent(self, 'parseError')); - - // Do we have a primary or primaryAndSecondary - if (shouldTriggerConnect(self)) { - // We are connected - self.state = CONNECTED; - - // Set initial connect state - self.initialConnectState.connect = true; - // Emit connect event - process.nextTick(function() { - self.emit('connect', self); - }); - - topologyMonitor(self, {}); - } - } else if (result instanceof MongoError) { - _this.destroy({ force: true }); - self.destroy({ force: true }); - return self.emit('error', result); - } else { - _this.destroy({ force: true }); - } - } else { - // Emit failure to connect - self.emit('failed', this); - - addServerToList(self.s.connectingServers, this); - // Remove from the state - self.s.replicaSetState.remove(this); - } - - if ( - self.initialConnectState.connect && - !self.initialConnectState.fullsetup && - self.s.replicaSetState.hasPrimaryAndSecondary() - ) { - // Set initial connect state - self.initialConnectState.fullsetup = true; - self.initialConnectState.all = true; - - process.nextTick(function() { - self.emit('fullsetup', self); - self.emit('all', self); - }); - } - - // Remove from the list from connectingServers - for (var i = 0; i < self.s.connectingServers.length; i++) { - if (self.s.connectingServers[i].equals(this)) { - self.s.connectingServers.splice(i, 1); - } - } - - // Trigger topologyMonitor - if (self.s.connectingServers.length === 0 && self.state === CONNECTING) { - topologyMonitor(self, { haInterval: 1 }); - } - }; -} - -function connectServers(self, servers) { - // Update connectingServers - self.s.connectingServers = self.s.connectingServers.concat(servers); - - // Index used to interleaf the server connects, avoiding - // runtime issues on io constrained vm's - var timeoutInterval = 0; - - function connect(server, timeoutInterval) { - setTimeout(function() { - // Add the server to the state - if (self.s.replicaSetState.update(server)) { - // Primary lastIsMaster store it - if (server.lastIsMaster() && server.lastIsMaster().ismaster) { - self.ismaster = server.lastIsMaster(); - } - } - - // Add event handlers - server.once('close', handleInitialConnectEvent(self, 'close')); - server.once('timeout', handleInitialConnectEvent(self, 'timeout')); - server.once('parseError', handleInitialConnectEvent(self, 'parseError')); - server.once('error', handleInitialConnectEvent(self, 'error')); - server.once('connect', handleInitialConnectEvent(self, 'connect')); - - // SDAM Monitoring events - server.on('serverOpening', e => self.emit('serverOpening', e)); - server.on('serverDescriptionChanged', e => self.emit('serverDescriptionChanged', e)); - server.on('serverClosed', e => self.emit('serverClosed', e)); - - // Command Monitoring events - relayEvents(server, self, ['commandStarted', 'commandSucceeded', 'commandFailed']); - - // Start connection - server.connect(self.s.connectOptions); - }, timeoutInterval); - } - - // Start all the servers - while (servers.length > 0) { - connect(servers.shift(), timeoutInterval++); - } -} - -/** - * Emit event if it exists - * @method - */ -function emitSDAMEvent(self, event, description) { - if (self.listeners(event).length > 0) { - self.emit(event, description); - } -} - -/** - * Initiate server connect - */ -ReplSet.prototype.connect = function(options) { - var self = this; - // Add any connect level options to the internal state - this.s.connectOptions = options || {}; - - // Set connecting state - stateTransition(this, CONNECTING); - - // Create server instances - var servers = this.s.seedlist.map(function(x) { - return new Server( - Object.assign({}, self.s.options, x, options, { - reconnect: false, - monitoring: false, - parent: self, - clientInfo: clone(self.s.clientInfo) - }) - ); - }); - - // Error out as high availbility interval must be < than socketTimeout - if ( - this.s.options.socketTimeout > 0 && - this.s.options.socketTimeout <= this.s.options.haInterval - ) { - return self.emit( - 'error', - new MongoError( - f( - 'haInterval [%s] MS must be set to less than socketTimeout [%s] MS', - this.s.options.haInterval, - this.s.options.socketTimeout - ) - ) - ); - } - - // Emit the topology opening event - emitSDAMEvent(this, 'topologyOpening', { topologyId: this.id }); - // Start all server connections - connectServers(self, servers); -}; - -/** - * Authenticate the topology. - * @method - * @param {MongoCredentials} credentials The credentials for authentication we are using - * @param {authResultCallback} callback A callback function - */ -ReplSet.prototype.auth = function(credentials, callback) { - if (typeof callback === 'function') callback(null, null); -}; - -/** - * Destroy the server connection - * @param {boolean} [options.force=false] Force destroy the pool - * @method - */ -ReplSet.prototype.destroy = function(options, callback) { - if (typeof options === 'function') { - callback = options; - options = {}; - } - - options = options || {}; - - let destroyCount = this.s.connectingServers.length + 1; // +1 for the callback from `replicaSetState.destroy` - const serverDestroyed = () => { - destroyCount--; - if (destroyCount > 0) { - return; - } - - // Emit toplogy closing event - emitSDAMEvent(this, 'topologyClosed', { topologyId: this.id }); - - // Transition state - stateTransition(this, DESTROYED); - - if (typeof callback === 'function') { - callback(null, null); - } - }; - - // Clear out any monitoring process - if (this.haTimeoutId) clearTimeout(this.haTimeoutId); - - // Clear out all monitoring - for (var i = 0; i < this.intervalIds.length; i++) { - this.intervalIds[i].stop(); - } - - // Reset list of intervalIds - this.intervalIds = []; - - if (destroyCount === 0) { - serverDestroyed(); - return; - } - - // Destroy the replicaset - this.s.replicaSetState.destroy(options, serverDestroyed); - - // Destroy all connecting servers - this.s.connectingServers.forEach(function(x) { - x.destroy(options, serverDestroyed); - }); -}; - -/** - * Unref all connections belong to this server - * @method - */ -ReplSet.prototype.unref = function() { - // Transition state - stateTransition(this, UNREFERENCED); - - this.s.replicaSetState.allServers().forEach(function(x) { - x.unref(); - }); - - clearTimeout(this.haTimeoutId); -}; - -/** - * Returns the last known ismaster document for this server - * @method - * @return {object} - */ -ReplSet.prototype.lastIsMaster = function() { - // If secondaryOnlyConnectionAllowed and no primary but secondary - // return the secondaries ismaster result. - if ( - this.s.options.secondaryOnlyConnectionAllowed && - !this.s.replicaSetState.hasPrimary() && - this.s.replicaSetState.hasSecondary() - ) { - return this.s.replicaSetState.secondaries[0].lastIsMaster(); - } - - return this.s.replicaSetState.primary - ? this.s.replicaSetState.primary.lastIsMaster() - : this.ismaster; -}; - -/** - * All raw connections - * @method - * @return {Connection[]} - */ -ReplSet.prototype.connections = function() { - var servers = this.s.replicaSetState.allServers(); - var connections = []; - for (var i = 0; i < servers.length; i++) { - connections = connections.concat(servers[i].connections()); - } - - return connections; -}; - -/** - * Figure out if the server is connected - * @method - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @return {boolean} - */ -ReplSet.prototype.isConnected = function(options) { - options = options || {}; - - // If we specified a read preference check if we are connected to something - // than can satisfy this - if (options.readPreference && options.readPreference.equals(ReadPreference.secondary)) { - return this.s.replicaSetState.hasSecondary(); - } - - if (options.readPreference && options.readPreference.equals(ReadPreference.primary)) { - return this.s.replicaSetState.hasPrimary(); - } - - if (options.readPreference && options.readPreference.equals(ReadPreference.primaryPreferred)) { - return this.s.replicaSetState.hasSecondary() || this.s.replicaSetState.hasPrimary(); - } - - if (options.readPreference && options.readPreference.equals(ReadPreference.secondaryPreferred)) { - return this.s.replicaSetState.hasSecondary() || this.s.replicaSetState.hasPrimary(); - } - - if (this.s.options.secondaryOnlyConnectionAllowed && this.s.replicaSetState.hasSecondary()) { - return true; - } - - return this.s.replicaSetState.hasPrimary(); -}; - -/** - * Figure out if the replicaset instance was destroyed by calling destroy - * @method - * @return {boolean} - */ -ReplSet.prototype.isDestroyed = function() { - return this.state === DESTROYED; -}; - -const SERVER_SELECTION_TIMEOUT_MS = 10000; // hardcoded `serverSelectionTimeoutMS` for legacy topology -const SERVER_SELECTION_INTERVAL_MS = 1000; // time to wait between selection attempts -/** - * Selects a server - * - * @method - * @param {function} selector Unused - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @param {ClientSession} [options.session] Unused - * @param {function} callback - */ -ReplSet.prototype.selectServer = function(selector, options, callback) { - if (typeof selector === 'function' && typeof callback === 'undefined') - (callback = selector), (selector = undefined), (options = {}); - if (typeof options === 'function') (callback = options), (options = selector); - options = options || {}; - - let readPreference; - if (selector instanceof ReadPreference) { - readPreference = selector; - } else { - readPreference = options.readPreference || ReadPreference.primary; - } - - let lastError; - const start = process.hrtime(); - const _selectServer = () => { - if (calculateDurationInMs(start) >= SERVER_SELECTION_TIMEOUT_MS) { - if (lastError != null) { - callback(lastError, null); - } else { - callback(new MongoError('Server selection timed out')); - } - - return; - } - - const server = this.s.replicaSetState.pickServer(readPreference); - if (server == null) { - setTimeout(_selectServer, SERVER_SELECTION_INTERVAL_MS); - return; - } - - if (!(server instanceof Server)) { - lastError = server; - setTimeout(_selectServer, SERVER_SELECTION_INTERVAL_MS); - return; - } - - if (this.s.debug) this.emit('pickedServer', options.readPreference, server); - callback(null, server); - }; - - _selectServer(); -}; - -/** - * Get all connected servers - * @method - * @return {Server[]} - */ -ReplSet.prototype.getServers = function() { - return this.s.replicaSetState.allServers(); -}; - -// -// Execute write operation -function executeWriteOperation(args, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // TODO: once we drop Node 4, use destructuring either here or in arguments. - const self = args.self; - const op = args.op; - const ns = args.ns; - const ops = args.ops; - - if (self.state === DESTROYED) { - return callback(new MongoError(f('topology was destroyed'))); - } - - const willRetryWrite = - !args.retrying && - !!options.retryWrites && - options.session && - isRetryableWritesSupported(self) && - !options.session.inTransaction(); - - if (!self.s.replicaSetState.hasPrimary()) { - if (self.s.disconnectHandler) { - // Not connected but we have a disconnecthandler - return self.s.disconnectHandler.add(op, ns, ops, options, callback); - } else if (!willRetryWrite) { - // No server returned we had an error - return callback(new MongoError('no primary server found')); - } - } - - const handler = (err, result) => { - if (!err) return callback(null, result); - if (!isRetryableError(err)) { - err = getMMAPError(err); - return callback(err); - } - - if (willRetryWrite) { - const newArgs = Object.assign({}, args, { retrying: true }); - return executeWriteOperation(newArgs, options, callback); - } - - // Per SDAM, remove primary from replicaset - if (self.s.replicaSetState.primary) { - self.s.replicaSetState.primary.destroy(); - self.s.replicaSetState.remove(self.s.replicaSetState.primary, { force: true }); - } - - return callback(err); - }; - - if (callback.operationId) { - handler.operationId = callback.operationId; - } - - // increment and assign txnNumber - if (willRetryWrite) { - options.session.incrementTransactionNumber(); - options.willRetryWrite = willRetryWrite; - } - - self.s.replicaSetState.primary[op](ns, ops, options, handler); -} - -/** - * Insert one or more documents - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of documents to insert - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {boolean} [options.retryWrites] Enable retryable writes for this operation - * @param {opResultCallback} callback A callback function - */ -ReplSet.prototype.insert = function(ns, ops, options, callback) { - // Execute write operation - executeWriteOperation({ self: this, op: 'insert', ns, ops }, options, callback); -}; - -/** - * Perform one or more update operations - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of updates - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {boolean} [options.retryWrites] Enable retryable writes for this operation - * @param {opResultCallback} callback A callback function - */ -ReplSet.prototype.update = function(ns, ops, options, callback) { - // Execute write operation - executeWriteOperation({ self: this, op: 'update', ns, ops }, options, callback); -}; - -/** - * Perform one or more remove operations - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of removes - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {boolean} [options.retryWrites] Enable retryable writes for this operation - * @param {opResultCallback} callback A callback function - */ -ReplSet.prototype.remove = function(ns, ops, options, callback) { - // Execute write operation - executeWriteOperation({ self: this, op: 'remove', ns, ops }, options, callback); -}; - -const RETRYABLE_WRITE_OPERATIONS = ['findAndModify', 'insert', 'update', 'delete']; - -function isWriteCommand(command) { - return RETRYABLE_WRITE_OPERATIONS.some(op => command[op]); -} - -/** - * Execute a command - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object} cmd The command hash - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @param {Connection} [options.connection] Specify connection object to execute command against - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {opResultCallback} callback A callback function - */ -ReplSet.prototype.command = function(ns, cmd, options, callback) { - if (typeof options === 'function') { - (callback = options), (options = {}), (options = options || {}); - } - - if (this.state === DESTROYED) return callback(new MongoError(f('topology was destroyed'))); - var self = this; - - // Establish readPreference - var readPreference = options.readPreference ? options.readPreference : ReadPreference.primary; - - // If the readPreference is primary and we have no primary, store it - if ( - readPreference.preference === 'primary' && - !this.s.replicaSetState.hasPrimary() && - this.s.disconnectHandler != null - ) { - return this.s.disconnectHandler.add('command', ns, cmd, options, callback); - } else if ( - readPreference.preference === 'secondary' && - !this.s.replicaSetState.hasSecondary() && - this.s.disconnectHandler != null - ) { - return this.s.disconnectHandler.add('command', ns, cmd, options, callback); - } else if ( - readPreference.preference !== 'primary' && - !this.s.replicaSetState.hasSecondary() && - !this.s.replicaSetState.hasPrimary() && - this.s.disconnectHandler != null - ) { - return this.s.disconnectHandler.add('command', ns, cmd, options, callback); - } - - // Pick a server - var server = this.s.replicaSetState.pickServer(readPreference); - // We received an error, return it - if (!(server instanceof Server)) return callback(server); - // Emit debug event - if (self.s.debug) self.emit('pickedServer', ReadPreference.primary, server); - - // No server returned we had an error - if (server == null) { - return callback( - new MongoError( - f('no server found that matches the provided readPreference %s', readPreference) - ) - ); - } - - const willRetryWrite = - !options.retrying && - !!options.retryWrites && - options.session && - isRetryableWritesSupported(self) && - !options.session.inTransaction() && - isWriteCommand(cmd); - - const cb = (err, result) => { - if (!err) return callback(null, result); - if (!isRetryableError(err)) { - return callback(err); - } - - if (willRetryWrite) { - const newOptions = Object.assign({}, options, { retrying: true }); - return this.command(ns, cmd, newOptions, callback); - } - - // Per SDAM, remove primary from replicaset - if (this.s.replicaSetState.primary) { - this.s.replicaSetState.primary.destroy(); - this.s.replicaSetState.remove(this.s.replicaSetState.primary, { force: true }); - } - - return callback(err); - }; - - // increment and assign txnNumber - if (willRetryWrite) { - options.session.incrementTransactionNumber(); - options.willRetryWrite = willRetryWrite; - } - - // Execute the command - server.command(ns, cmd, options, cb); -}; - -/** - * Get a new cursor - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object|Long} cmd Can be either a command returning a cursor or a cursorId - * @param {object} [options] Options for the cursor - * @param {object} [options.batchSize=0] Batchsize for the operation - * @param {array} [options.documents=[]] Initial documents list for cursor - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {object} [options.topology] The internal topology of the created cursor - * @returns {Cursor} - */ -ReplSet.prototype.cursor = function(ns, cmd, options) { - options = options || {}; - const topology = options.topology || this; - - // Set up final cursor type - var FinalCursor = options.cursorFactory || this.s.Cursor; - - // Return the cursor - return new FinalCursor(topology, ns, cmd, options); -}; - -/** - * A replset connect event, used to verify that the connection is up and running - * - * @event ReplSet#connect - * @type {ReplSet} - */ - -/** - * A replset reconnect event, used to verify that the topology reconnected - * - * @event ReplSet#reconnect - * @type {ReplSet} - */ - -/** - * A replset fullsetup event, used to signal that all topology members have been contacted. - * - * @event ReplSet#fullsetup - * @type {ReplSet} - */ - -/** - * A replset all event, used to signal that all topology members have been contacted. - * - * @event ReplSet#all - * @type {ReplSet} - */ - -/** - * A replset failed event, used to signal that initial replset connection failed. - * - * @event ReplSet#failed - * @type {ReplSet} - */ - -/** - * A server member left the replicaset - * - * @event ReplSet#left - * @type {function} - * @param {string} type The type of member that left (primary|secondary|arbiter) - * @param {Server} server The server object that left - */ - -/** - * A server member joined the replicaset - * - * @event ReplSet#joined - * @type {function} - * @param {string} type The type of member that joined (primary|secondary|arbiter) - * @param {Server} server The server object that joined - */ - -/** - * A server opening SDAM monitoring event - * - * @event ReplSet#serverOpening - * @type {object} - */ - -/** - * A server closed SDAM monitoring event - * - * @event ReplSet#serverClosed - * @type {object} - */ - -/** - * A server description SDAM change monitoring event - * - * @event ReplSet#serverDescriptionChanged - * @type {object} - */ - -/** - * A topology open SDAM event - * - * @event ReplSet#topologyOpening - * @type {object} - */ - -/** - * A topology closed SDAM event - * - * @event ReplSet#topologyClosed - * @type {object} - */ - -/** - * A topology structure SDAM change event - * - * @event ReplSet#topologyDescriptionChanged - * @type {object} - */ - -/** - * A topology serverHeartbeatStarted SDAM event - * - * @event ReplSet#serverHeartbeatStarted - * @type {object} - */ - -/** - * A topology serverHeartbeatFailed SDAM event - * - * @event ReplSet#serverHeartbeatFailed - * @type {object} - */ - -/** - * A topology serverHeartbeatSucceeded SDAM change event - * - * @event ReplSet#serverHeartbeatSucceeded - * @type {object} - */ - -/** - * An event emitted indicating a command was started, if command monitoring is enabled - * - * @event ReplSet#commandStarted - * @type {object} - */ - -/** - * An event emitted indicating a command succeeded, if command monitoring is enabled - * - * @event ReplSet#commandSucceeded - * @type {object} - */ - -/** - * An event emitted indicating a command failed, if command monitoring is enabled - * - * @event ReplSet#commandFailed - * @type {object} - */ - -module.exports = ReplSet; diff --git a/scripts/node_modules/mongodb/lib/core/topologies/replset_state.js b/scripts/node_modules/mongodb/lib/core/topologies/replset_state.js deleted file mode 100644 index 24c16d6d..00000000 --- a/scripts/node_modules/mongodb/lib/core/topologies/replset_state.js +++ /dev/null @@ -1,1121 +0,0 @@ -'use strict'; - -var inherits = require('util').inherits, - f = require('util').format, - diff = require('./shared').diff, - EventEmitter = require('events').EventEmitter, - Logger = require('../connection/logger'), - ReadPreference = require('./read_preference'), - MongoError = require('../error').MongoError, - Buffer = require('safe-buffer').Buffer; - -var TopologyType = { - Single: 'Single', - ReplicaSetNoPrimary: 'ReplicaSetNoPrimary', - ReplicaSetWithPrimary: 'ReplicaSetWithPrimary', - Sharded: 'Sharded', - Unknown: 'Unknown' -}; - -var ServerType = { - Standalone: 'Standalone', - Mongos: 'Mongos', - PossiblePrimary: 'PossiblePrimary', - RSPrimary: 'RSPrimary', - RSSecondary: 'RSSecondary', - RSArbiter: 'RSArbiter', - RSOther: 'RSOther', - RSGhost: 'RSGhost', - Unknown: 'Unknown' -}; - -var ReplSetState = function(options) { - options = options || {}; - // Add event listener - EventEmitter.call(this); - // Topology state - this.topologyType = TopologyType.ReplicaSetNoPrimary; - this.setName = options.setName; - - // Server set - this.set = {}; - - // Unpacked options - this.id = options.id; - this.setName = options.setName; - - // Replicaset logger - this.logger = options.logger || Logger('ReplSet', options); - - // Server selection index - this.index = 0; - // Acceptable latency - this.acceptableLatency = options.acceptableLatency || 15; - - // heartbeatFrequencyMS - this.heartbeatFrequencyMS = options.heartbeatFrequencyMS || 10000; - - // Server side - this.primary = null; - this.secondaries = []; - this.arbiters = []; - this.passives = []; - this.ghosts = []; - // Current unknown hosts - this.unknownServers = []; - // In set status - this.set = {}; - // Status - this.maxElectionId = null; - this.maxSetVersion = 0; - // Description of the Replicaset - this.replicasetDescription = { - topologyType: 'Unknown', - servers: [] - }; - - this.logicalSessionTimeoutMinutes = undefined; -}; - -inherits(ReplSetState, EventEmitter); - -ReplSetState.prototype.hasPrimaryAndSecondary = function() { - return this.primary != null && this.secondaries.length > 0; -}; - -ReplSetState.prototype.hasPrimaryOrSecondary = function() { - return this.hasPrimary() || this.hasSecondary(); -}; - -ReplSetState.prototype.hasPrimary = function() { - return this.primary != null; -}; - -ReplSetState.prototype.hasSecondary = function() { - return this.secondaries.length > 0; -}; - -ReplSetState.prototype.get = function(host) { - var servers = this.allServers(); - - for (var i = 0; i < servers.length; i++) { - if (servers[i].name.toLowerCase() === host.toLowerCase()) { - return servers[i]; - } - } - - return null; -}; - -ReplSetState.prototype.allServers = function(options) { - options = options || {}; - var servers = this.primary ? [this.primary] : []; - servers = servers.concat(this.secondaries); - if (!options.ignoreArbiters) servers = servers.concat(this.arbiters); - servers = servers.concat(this.passives); - return servers; -}; - -ReplSetState.prototype.destroy = function(options, callback) { - const serversToDestroy = this.secondaries - .concat(this.arbiters) - .concat(this.passives) - .concat(this.ghosts); - if (this.primary) serversToDestroy.push(this.primary); - - let serverCount = serversToDestroy.length; - const serverDestroyed = () => { - serverCount--; - if (serverCount > 0) { - return; - } - - // Clear out the complete state - this.secondaries = []; - this.arbiters = []; - this.passives = []; - this.ghosts = []; - this.unknownServers = []; - this.set = {}; - this.primary = null; - - // Emit the topology changed - emitTopologyDescriptionChanged(this); - - if (typeof callback === 'function') { - callback(null, null); - } - }; - - if (serverCount === 0) { - serverDestroyed(); - return; - } - - serversToDestroy.forEach(server => server.destroy(options, serverDestroyed)); -}; - -ReplSetState.prototype.remove = function(server, options) { - options = options || {}; - - // Get the server name and lowerCase it - var serverName = server.name.toLowerCase(); - - // Only remove if the current server is not connected - var servers = this.primary ? [this.primary] : []; - servers = servers.concat(this.secondaries); - servers = servers.concat(this.arbiters); - servers = servers.concat(this.passives); - - // Check if it's active and this is just a failed connection attempt - for (var i = 0; i < servers.length; i++) { - if ( - !options.force && - servers[i].equals(server) && - servers[i].isConnected && - servers[i].isConnected() - ) { - return; - } - } - - // If we have it in the set remove it - if (this.set[serverName]) { - this.set[serverName].type = ServerType.Unknown; - this.set[serverName].electionId = null; - this.set[serverName].setName = null; - this.set[serverName].setVersion = null; - } - - // Remove type - var removeType = null; - - // Remove from any lists - if (this.primary && this.primary.equals(server)) { - this.primary = null; - this.topologyType = TopologyType.ReplicaSetNoPrimary; - removeType = 'primary'; - } - - // Remove from any other server lists - removeType = removeFrom(server, this.secondaries) ? 'secondary' : removeType; - removeType = removeFrom(server, this.arbiters) ? 'arbiter' : removeType; - removeType = removeFrom(server, this.passives) ? 'secondary' : removeType; - removeFrom(server, this.ghosts); - removeFrom(server, this.unknownServers); - - // Push to unknownServers - this.unknownServers.push(serverName); - - // Do we have a removeType - if (removeType) { - this.emit('left', removeType, server); - } -}; - -const isArbiter = ismaster => ismaster.arbiterOnly && ismaster.setName; - -ReplSetState.prototype.update = function(server) { - var self = this; - // Get the current ismaster - var ismaster = server.lastIsMaster(); - - // Get the server name and lowerCase it - var serverName = server.name.toLowerCase(); - - // - // Add any hosts - // - if (ismaster) { - // Join all the possible new hosts - var hosts = Array.isArray(ismaster.hosts) ? ismaster.hosts : []; - hosts = hosts.concat(Array.isArray(ismaster.arbiters) ? ismaster.arbiters : []); - hosts = hosts.concat(Array.isArray(ismaster.passives) ? ismaster.passives : []); - hosts = hosts.map(function(s) { - return s.toLowerCase(); - }); - - // Add all hosts as unknownServers - for (var i = 0; i < hosts.length; i++) { - // Add to the list of unknown server - if ( - this.unknownServers.indexOf(hosts[i]) === -1 && - (!this.set[hosts[i]] || this.set[hosts[i]].type === ServerType.Unknown) - ) { - this.unknownServers.push(hosts[i].toLowerCase()); - } - - if (!this.set[hosts[i]]) { - this.set[hosts[i]] = { - type: ServerType.Unknown, - electionId: null, - setName: null, - setVersion: null - }; - } - } - } - - // - // Unknown server - // - if (!ismaster && !inList(ismaster, server, this.unknownServers)) { - self.set[serverName] = { - type: ServerType.Unknown, - setVersion: null, - electionId: null, - setName: null - }; - // Update set information about the server instance - self.set[serverName].type = ServerType.Unknown; - self.set[serverName].electionId = ismaster ? ismaster.electionId : ismaster; - self.set[serverName].setName = ismaster ? ismaster.setName : ismaster; - self.set[serverName].setVersion = ismaster ? ismaster.setVersion : ismaster; - - if (self.unknownServers.indexOf(server.name) === -1) { - self.unknownServers.push(serverName); - } - - // Set the topology - return false; - } - - // Update logicalSessionTimeoutMinutes - if (ismaster.logicalSessionTimeoutMinutes !== undefined && !isArbiter(ismaster)) { - if ( - self.logicalSessionTimeoutMinutes === undefined || - ismaster.logicalSessionTimeoutMinutes === null - ) { - self.logicalSessionTimeoutMinutes = ismaster.logicalSessionTimeoutMinutes; - } else { - self.logicalSessionTimeoutMinutes = Math.min( - self.logicalSessionTimeoutMinutes, - ismaster.logicalSessionTimeoutMinutes - ); - } - } - - // - // Is this a mongos - // - if (ismaster && ismaster.msg === 'isdbgrid') { - if (this.primary && this.primary.name === serverName) { - this.primary = null; - this.topologyType = TopologyType.ReplicaSetNoPrimary; - } - - return false; - } - - // A RSGhost instance - if (ismaster.isreplicaset) { - self.set[serverName] = { - type: ServerType.RSGhost, - setVersion: null, - electionId: null, - setName: ismaster.setName - }; - - if (this.primary && this.primary.name === serverName) { - this.primary = null; - } - - // Set the topology - this.topologyType = this.primary - ? TopologyType.ReplicaSetWithPrimary - : TopologyType.ReplicaSetNoPrimary; - if (ismaster.setName) this.setName = ismaster.setName; - - // Set the topology - return false; - } - - // A RSOther instance - if ( - (ismaster.setName && ismaster.hidden) || - (ismaster.setName && - !ismaster.ismaster && - !ismaster.secondary && - !ismaster.arbiterOnly && - !ismaster.passive) - ) { - self.set[serverName] = { - type: ServerType.RSOther, - setVersion: null, - electionId: null, - setName: ismaster.setName - }; - - // Set the topology - this.topologyType = this.primary - ? TopologyType.ReplicaSetWithPrimary - : TopologyType.ReplicaSetNoPrimary; - if (ismaster.setName) this.setName = ismaster.setName; - return false; - } - - // - // Standalone server, destroy and return - // - if (ismaster && ismaster.ismaster && !ismaster.setName) { - this.topologyType = this.primary ? TopologyType.ReplicaSetWithPrimary : TopologyType.Unknown; - this.remove(server, { force: true }); - return false; - } - - // - // Server in maintanance mode - // - if (ismaster && !ismaster.ismaster && !ismaster.secondary && !ismaster.arbiterOnly) { - this.remove(server, { force: true }); - return false; - } - - // - // If the .me field does not match the passed in server - // - if (ismaster.me && ismaster.me.toLowerCase() !== serverName) { - if (this.logger.isWarn()) { - this.logger.warn( - f( - 'the seedlist server was removed due to its address %s not matching its ismaster.me address %s', - server.name, - ismaster.me - ) - ); - } - - // Delete from the set - delete this.set[serverName]; - // Delete unknown servers - removeFrom(server, self.unknownServers); - - // Destroy the instance - server.destroy({ force: true }); - - // Set the type of topology we have - if (this.primary && !this.primary.equals(server)) { - this.topologyType = TopologyType.ReplicaSetWithPrimary; - } else { - this.topologyType = TopologyType.ReplicaSetNoPrimary; - } - - // - // We have a potential primary - // - if (!this.primary && ismaster.primary) { - this.set[ismaster.primary.toLowerCase()] = { - type: ServerType.PossiblePrimary, - setName: null, - electionId: null, - setVersion: null - }; - } - - return false; - } - - // - // Primary handling - // - if (!this.primary && ismaster.ismaster && ismaster.setName) { - var ismasterElectionId = server.lastIsMaster().electionId; - if (this.setName && this.setName !== ismaster.setName) { - this.topologyType = TopologyType.ReplicaSetNoPrimary; - return new MongoError( - f( - 'setName from ismaster does not match provided connection setName [%s] != [%s]', - ismaster.setName, - this.setName - ) - ); - } - - if (!this.maxElectionId && ismasterElectionId) { - this.maxElectionId = ismasterElectionId; - } else if (this.maxElectionId && ismasterElectionId) { - var result = compareObjectIds(this.maxElectionId, ismasterElectionId); - // Get the electionIds - var ismasterSetVersion = server.lastIsMaster().setVersion; - - if (result === 1) { - this.topologyType = TopologyType.ReplicaSetNoPrimary; - return false; - } else if (result === 0 && ismasterSetVersion) { - if (ismasterSetVersion < this.maxSetVersion) { - this.topologyType = TopologyType.ReplicaSetNoPrimary; - return false; - } - } - - this.maxSetVersion = ismasterSetVersion; - this.maxElectionId = ismasterElectionId; - } - - // Hande normalization of server names - var normalizedHosts = ismaster.hosts.map(function(x) { - return x.toLowerCase(); - }); - var locationIndex = normalizedHosts.indexOf(serverName); - - // Validate that the server exists in the host list - if (locationIndex !== -1) { - self.primary = server; - self.set[serverName] = { - type: ServerType.RSPrimary, - setVersion: ismaster.setVersion, - electionId: ismaster.electionId, - setName: ismaster.setName - }; - - // Set the topology - this.topologyType = TopologyType.ReplicaSetWithPrimary; - if (ismaster.setName) this.setName = ismaster.setName; - removeFrom(server, self.unknownServers); - removeFrom(server, self.secondaries); - removeFrom(server, self.passives); - self.emit('joined', 'primary', server); - } else { - this.topologyType = TopologyType.ReplicaSetNoPrimary; - } - - emitTopologyDescriptionChanged(self); - return true; - } else if (ismaster.ismaster && ismaster.setName) { - // Get the electionIds - var currentElectionId = self.set[self.primary.name.toLowerCase()].electionId; - var currentSetVersion = self.set[self.primary.name.toLowerCase()].setVersion; - var currentSetName = self.set[self.primary.name.toLowerCase()].setName; - ismasterElectionId = server.lastIsMaster().electionId; - ismasterSetVersion = server.lastIsMaster().setVersion; - var ismasterSetName = server.lastIsMaster().setName; - - // Is it the same server instance - if (this.primary.equals(server) && currentSetName === ismasterSetName) { - return false; - } - - // If we do not have the same rs name - if (currentSetName && currentSetName !== ismasterSetName) { - if (!this.primary.equals(server)) { - this.topologyType = TopologyType.ReplicaSetWithPrimary; - } else { - this.topologyType = TopologyType.ReplicaSetNoPrimary; - } - - return false; - } - - // Check if we need to replace the server - if (currentElectionId && ismasterElectionId) { - result = compareObjectIds(currentElectionId, ismasterElectionId); - - if (result === 1) { - return false; - } else if (result === 0 && currentSetVersion > ismasterSetVersion) { - return false; - } - } else if (!currentElectionId && ismasterElectionId && ismasterSetVersion) { - if (ismasterSetVersion < this.maxSetVersion) { - return false; - } - } - - if (!this.maxElectionId && ismasterElectionId) { - this.maxElectionId = ismasterElectionId; - } else if (this.maxElectionId && ismasterElectionId) { - result = compareObjectIds(this.maxElectionId, ismasterElectionId); - - if (result === 1) { - return false; - } else if (result === 0 && currentSetVersion && ismasterSetVersion) { - if (ismasterSetVersion < this.maxSetVersion) { - return false; - } - } else { - if (ismasterSetVersion < this.maxSetVersion) { - return false; - } - } - - this.maxElectionId = ismasterElectionId; - this.maxSetVersion = ismasterSetVersion; - } else { - this.maxSetVersion = ismasterSetVersion; - } - - // Modify the entry to unknown - self.set[self.primary.name.toLowerCase()] = { - type: ServerType.Unknown, - setVersion: null, - electionId: null, - setName: null - }; - - // Signal primary left - self.emit('left', 'primary', this.primary); - // Destroy the instance - self.primary.destroy({ force: true }); - // Set the new instance - self.primary = server; - // Set the set information - self.set[serverName] = { - type: ServerType.RSPrimary, - setVersion: ismaster.setVersion, - electionId: ismaster.electionId, - setName: ismaster.setName - }; - - // Set the topology - this.topologyType = TopologyType.ReplicaSetWithPrimary; - if (ismaster.setName) this.setName = ismaster.setName; - removeFrom(server, self.unknownServers); - removeFrom(server, self.secondaries); - removeFrom(server, self.passives); - self.emit('joined', 'primary', server); - emitTopologyDescriptionChanged(self); - return true; - } - - // A possible instance - if (!this.primary && ismaster.primary) { - self.set[ismaster.primary.toLowerCase()] = { - type: ServerType.PossiblePrimary, - setVersion: null, - electionId: null, - setName: null - }; - } - - // - // Secondary handling - // - if ( - ismaster.secondary && - ismaster.setName && - !inList(ismaster, server, this.secondaries) && - this.setName && - this.setName === ismaster.setName - ) { - addToList(self, ServerType.RSSecondary, ismaster, server, this.secondaries); - // Set the topology - this.topologyType = this.primary - ? TopologyType.ReplicaSetWithPrimary - : TopologyType.ReplicaSetNoPrimary; - if (ismaster.setName) this.setName = ismaster.setName; - removeFrom(server, self.unknownServers); - - // Remove primary - if (this.primary && this.primary.name.toLowerCase() === serverName) { - server.destroy({ force: true }); - this.primary = null; - self.emit('left', 'primary', server); - } - - // Emit secondary joined replicaset - self.emit('joined', 'secondary', server); - emitTopologyDescriptionChanged(self); - return true; - } - - // - // Arbiter handling - // - if ( - isArbiter(ismaster) && - !inList(ismaster, server, this.arbiters) && - this.setName && - this.setName === ismaster.setName - ) { - addToList(self, ServerType.RSArbiter, ismaster, server, this.arbiters); - // Set the topology - this.topologyType = this.primary - ? TopologyType.ReplicaSetWithPrimary - : TopologyType.ReplicaSetNoPrimary; - if (ismaster.setName) this.setName = ismaster.setName; - removeFrom(server, self.unknownServers); - self.emit('joined', 'arbiter', server); - emitTopologyDescriptionChanged(self); - return true; - } - - // - // Passive handling - // - if ( - ismaster.passive && - ismaster.setName && - !inList(ismaster, server, this.passives) && - this.setName && - this.setName === ismaster.setName - ) { - addToList(self, ServerType.RSSecondary, ismaster, server, this.passives); - // Set the topology - this.topologyType = this.primary - ? TopologyType.ReplicaSetWithPrimary - : TopologyType.ReplicaSetNoPrimary; - if (ismaster.setName) this.setName = ismaster.setName; - removeFrom(server, self.unknownServers); - - // Remove primary - if (this.primary && this.primary.name.toLowerCase() === serverName) { - server.destroy({ force: true }); - this.primary = null; - self.emit('left', 'primary', server); - } - - self.emit('joined', 'secondary', server); - emitTopologyDescriptionChanged(self); - return true; - } - - // - // Remove the primary - // - if (this.set[serverName] && this.set[serverName].type === ServerType.RSPrimary) { - self.emit('left', 'primary', this.primary); - this.primary.destroy({ force: true }); - this.primary = null; - this.topologyType = TopologyType.ReplicaSetNoPrimary; - return false; - } - - this.topologyType = this.primary - ? TopologyType.ReplicaSetWithPrimary - : TopologyType.ReplicaSetNoPrimary; - return false; -}; - -/** - * Recalculate single server max staleness - * @method - */ -ReplSetState.prototype.updateServerMaxStaleness = function(server, haInterval) { - // Locate the max secondary lastwrite - var max = 0; - // Go over all secondaries - for (var i = 0; i < this.secondaries.length; i++) { - max = Math.max(max, this.secondaries[i].lastWriteDate); - } - - // Perform this servers staleness calculation - if (server.ismaster.maxWireVersion >= 5 && server.ismaster.secondary && this.hasPrimary()) { - server.staleness = - server.lastUpdateTime - - server.lastWriteDate - - (this.primary.lastUpdateTime - this.primary.lastWriteDate) + - haInterval; - } else if (server.ismaster.maxWireVersion >= 5 && server.ismaster.secondary) { - server.staleness = max - server.lastWriteDate + haInterval; - } -}; - -/** - * Recalculate all the staleness values for secodaries - * @method - */ -ReplSetState.prototype.updateSecondariesMaxStaleness = function(haInterval) { - for (var i = 0; i < this.secondaries.length; i++) { - this.updateServerMaxStaleness(this.secondaries[i], haInterval); - } -}; - -/** - * Pick a server by the passed in ReadPreference - * @method - * @param {ReadPreference} readPreference The ReadPreference instance to use - */ -ReplSetState.prototype.pickServer = function(readPreference) { - // If no read Preference set to primary by default - readPreference = readPreference || ReadPreference.primary; - - // maxStalenessSeconds is not allowed with a primary read - if (readPreference.preference === 'primary' && readPreference.maxStalenessSeconds != null) { - return new MongoError('primary readPreference incompatible with maxStalenessSeconds'); - } - - // Check if we have any non compatible servers for maxStalenessSeconds - var allservers = this.primary ? [this.primary] : []; - allservers = allservers.concat(this.secondaries); - - // Does any of the servers not support the right wire protocol version - // for maxStalenessSeconds when maxStalenessSeconds specified on readPreference. Then error out - if (readPreference.maxStalenessSeconds != null) { - for (var i = 0; i < allservers.length; i++) { - if (allservers[i].ismaster.maxWireVersion < 5) { - return new MongoError( - 'maxStalenessSeconds not supported by at least one of the replicaset members' - ); - } - } - } - - // Do we have the nearest readPreference - if (readPreference.preference === 'nearest' && readPreference.maxStalenessSeconds == null) { - return pickNearest(this, readPreference); - } else if ( - readPreference.preference === 'nearest' && - readPreference.maxStalenessSeconds != null - ) { - return pickNearestMaxStalenessSeconds(this, readPreference); - } - - // Get all the secondaries - var secondaries = this.secondaries; - - // Check if we can satisfy and of the basic read Preferences - if (readPreference.equals(ReadPreference.secondary) && secondaries.length === 0) { - return new MongoError('no secondary server available'); - } - - if ( - readPreference.equals(ReadPreference.secondaryPreferred) && - secondaries.length === 0 && - this.primary == null - ) { - return new MongoError('no secondary or primary server available'); - } - - if (readPreference.equals(ReadPreference.primary) && this.primary == null) { - return new MongoError('no primary server available'); - } - - // Secondary preferred or just secondaries - if ( - readPreference.equals(ReadPreference.secondaryPreferred) || - readPreference.equals(ReadPreference.secondary) - ) { - if (secondaries.length > 0 && readPreference.maxStalenessSeconds == null) { - // Pick nearest of any other servers available - var server = pickNearest(this, readPreference); - // No server in the window return primary - if (server) { - return server; - } - } else if (secondaries.length > 0 && readPreference.maxStalenessSeconds != null) { - // Pick nearest of any other servers available - server = pickNearestMaxStalenessSeconds(this, readPreference); - // No server in the window return primary - if (server) { - return server; - } - } - - if (readPreference.equals(ReadPreference.secondaryPreferred)) { - return this.primary; - } - - return null; - } - - // Primary preferred - if (readPreference.equals(ReadPreference.primaryPreferred)) { - server = null; - - // We prefer the primary if it's available - if (this.primary) { - return this.primary; - } - - // Pick a secondary - if (secondaries.length > 0 && readPreference.maxStalenessSeconds == null) { - server = pickNearest(this, readPreference); - } else if (secondaries.length > 0 && readPreference.maxStalenessSeconds != null) { - server = pickNearestMaxStalenessSeconds(this, readPreference); - } - - // Did we find a server - if (server) return server; - } - - // Return the primary - return this.primary; -}; - -// -// Filter serves by tags -var filterByTags = function(readPreference, servers) { - if (readPreference.tags == null) return servers; - var filteredServers = []; - var tagsArray = Array.isArray(readPreference.tags) ? readPreference.tags : [readPreference.tags]; - - // Iterate over the tags - for (var j = 0; j < tagsArray.length; j++) { - var tags = tagsArray[j]; - - // Iterate over all the servers - for (var i = 0; i < servers.length; i++) { - var serverTag = servers[i].lastIsMaster().tags || {}; - - // Did we find the a matching server - var found = true; - // Check if the server is valid - for (var name in tags) { - if (serverTag[name] !== tags[name]) { - found = false; - } - } - - // Add to candidate list - if (found) { - filteredServers.push(servers[i]); - } - } - } - - // Returned filtered servers - return filteredServers; -}; - -function pickNearestMaxStalenessSeconds(self, readPreference) { - // Only get primary and secondaries as seeds - var servers = []; - - // Get the maxStalenessMS - var maxStalenessMS = readPreference.maxStalenessSeconds * 1000; - - // Check if the maxStalenessMS > 90 seconds - if (maxStalenessMS < 90 * 1000) { - return new MongoError('maxStalenessSeconds must be set to at least 90 seconds'); - } - - // Add primary to list if not a secondary read preference - if ( - self.primary && - readPreference.preference !== 'secondary' && - readPreference.preference !== 'secondaryPreferred' - ) { - servers.push(self.primary); - } - - // Add all the secondaries - for (var i = 0; i < self.secondaries.length; i++) { - servers.push(self.secondaries[i]); - } - - // If we have a secondaryPreferred readPreference and no server add the primary - if (self.primary && servers.length === 0 && readPreference.preference !== 'secondaryPreferred') { - servers.push(self.primary); - } - - // Filter by tags - servers = filterByTags(readPreference, servers); - - // Filter by latency - servers = servers.filter(function(s) { - return s.staleness <= maxStalenessMS; - }); - - // Sort by time - servers.sort(function(a, b) { - return a.lastIsMasterMS - b.lastIsMasterMS; - }); - - // No servers, default to primary - if (servers.length === 0) { - return null; - } - - // Ensure index does not overflow the number of available servers - self.index = self.index % servers.length; - - // Get the server - var server = servers[self.index]; - // Add to the index - self.index = self.index + 1; - // Return the first server of the sorted and filtered list - return server; -} - -function pickNearest(self, readPreference) { - // Only get primary and secondaries as seeds - var servers = []; - - // Add primary to list if not a secondary read preference - if ( - self.primary && - readPreference.preference !== 'secondary' && - readPreference.preference !== 'secondaryPreferred' - ) { - servers.push(self.primary); - } - - // Add all the secondaries - for (var i = 0; i < self.secondaries.length; i++) { - servers.push(self.secondaries[i]); - } - - // If we have a secondaryPreferred readPreference and no server add the primary - if (servers.length === 0 && self.primary && readPreference.preference !== 'secondaryPreferred') { - servers.push(self.primary); - } - - // Filter by tags - servers = filterByTags(readPreference, servers); - - // Sort by time - servers.sort(function(a, b) { - return a.lastIsMasterMS - b.lastIsMasterMS; - }); - - // Locate lowest time (picked servers are lowest time + acceptable Latency margin) - var lowest = servers.length > 0 ? servers[0].lastIsMasterMS : 0; - - // Filter by latency - servers = servers.filter(function(s) { - return s.lastIsMasterMS <= lowest + self.acceptableLatency; - }); - - // No servers, default to primary - if (servers.length === 0) { - return null; - } - - // Ensure index does not overflow the number of available servers - self.index = self.index % servers.length; - // Get the server - var server = servers[self.index]; - // Add to the index - self.index = self.index + 1; - // Return the first server of the sorted and filtered list - return server; -} - -function inList(ismaster, server, list) { - for (var i = 0; i < list.length; i++) { - if (list[i] && list[i].name && list[i].name.toLowerCase() === server.name.toLowerCase()) - return true; - } - - return false; -} - -function addToList(self, type, ismaster, server, list) { - var serverName = server.name.toLowerCase(); - // Update set information about the server instance - self.set[serverName].type = type; - self.set[serverName].electionId = ismaster ? ismaster.electionId : ismaster; - self.set[serverName].setName = ismaster ? ismaster.setName : ismaster; - self.set[serverName].setVersion = ismaster ? ismaster.setVersion : ismaster; - // Add to the list - list.push(server); -} - -function compareObjectIds(id1, id2) { - var a = Buffer.from(id1.toHexString(), 'hex'); - var b = Buffer.from(id2.toHexString(), 'hex'); - - if (a === b) { - return 0; - } - - if (typeof Buffer.compare === 'function') { - return Buffer.compare(a, b); - } - - var x = a.length; - var y = b.length; - var len = Math.min(x, y); - - for (var i = 0; i < len; i++) { - if (a[i] !== b[i]) { - break; - } - } - - if (i !== len) { - x = a[i]; - y = b[i]; - } - - return x < y ? -1 : y < x ? 1 : 0; -} - -function removeFrom(server, list) { - for (var i = 0; i < list.length; i++) { - if (list[i].equals && list[i].equals(server)) { - list.splice(i, 1); - return true; - } else if (typeof list[i] === 'string' && list[i].toLowerCase() === server.name.toLowerCase()) { - list.splice(i, 1); - return true; - } - } - - return false; -} - -function emitTopologyDescriptionChanged(self) { - if (self.listeners('topologyDescriptionChanged').length > 0) { - var topology = 'Unknown'; - var setName = self.setName; - - if (self.hasPrimaryAndSecondary()) { - topology = 'ReplicaSetWithPrimary'; - } else if (!self.hasPrimary() && self.hasSecondary()) { - topology = 'ReplicaSetNoPrimary'; - } - - // Generate description - var description = { - topologyType: topology, - setName: setName, - servers: [] - }; - - // Add the primary to the list - if (self.hasPrimary()) { - var desc = self.primary.getDescription(); - desc.type = 'RSPrimary'; - description.servers.push(desc); - } - - // Add all the secondaries - description.servers = description.servers.concat( - self.secondaries.map(function(x) { - var description = x.getDescription(); - description.type = 'RSSecondary'; - return description; - }) - ); - - // Add all the arbiters - description.servers = description.servers.concat( - self.arbiters.map(function(x) { - var description = x.getDescription(); - description.type = 'RSArbiter'; - return description; - }) - ); - - // Add all the passives - description.servers = description.servers.concat( - self.passives.map(function(x) { - var description = x.getDescription(); - description.type = 'RSSecondary'; - return description; - }) - ); - - // Get the diff - var diffResult = diff(self.replicasetDescription, description); - - // Create the result - var result = { - topologyId: self.id, - previousDescription: self.replicasetDescription, - newDescription: description, - diff: diffResult - }; - - // Emit the topologyDescription change - // if(diffResult.servers.length > 0) { - self.emit('topologyDescriptionChanged', result); - // } - - // Set the new description - self.replicasetDescription = description; - } -} - -module.exports = ReplSetState; diff --git a/scripts/node_modules/mongodb/lib/core/topologies/server.js b/scripts/node_modules/mongodb/lib/core/topologies/server.js deleted file mode 100644 index c2f86421..00000000 --- a/scripts/node_modules/mongodb/lib/core/topologies/server.js +++ /dev/null @@ -1,989 +0,0 @@ -'use strict'; - -var inherits = require('util').inherits, - f = require('util').format, - EventEmitter = require('events').EventEmitter, - ReadPreference = require('./read_preference'), - Logger = require('../connection/logger'), - debugOptions = require('../connection/utils').debugOptions, - retrieveBSON = require('../connection/utils').retrieveBSON, - Pool = require('../connection/pool'), - MongoError = require('../error').MongoError, - MongoNetworkError = require('../error').MongoNetworkError, - wireProtocol = require('../wireprotocol'), - CoreCursor = require('../cursor').CoreCursor, - sdam = require('./shared'), - createClientInfo = require('./shared').createClientInfo, - createCompressionInfo = require('./shared').createCompressionInfo, - resolveClusterTime = require('./shared').resolveClusterTime, - SessionMixins = require('./shared').SessionMixins, - relayEvents = require('../utils').relayEvents; - -const collationNotSupported = require('../utils').collationNotSupported; - -// Used for filtering out fields for loggin -var debugFields = [ - 'reconnect', - 'reconnectTries', - 'reconnectInterval', - 'emitError', - 'cursorFactory', - 'host', - 'port', - 'size', - 'keepAlive', - 'keepAliveInitialDelay', - 'noDelay', - 'connectionTimeout', - 'checkServerIdentity', - 'socketTimeout', - 'ssl', - 'ca', - 'crl', - 'cert', - 'key', - 'rejectUnauthorized', - 'promoteLongs', - 'promoteValues', - 'promoteBuffers', - 'servername' -]; - -// Server instance id -var id = 0; -var serverAccounting = false; -var servers = {}; -var BSON = retrieveBSON(); - -/** - * Creates a new Server instance - * @class - * @param {boolean} [options.reconnect=true] Server will attempt to reconnect on loss of connection - * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times - * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries - * @param {number} [options.monitoring=true] Enable the server state monitoring (calling ismaster at monitoringInterval) - * @param {number} [options.monitoringInterval=5000] The interval of calling ismaster when monitoring is enabled. - * @param {Cursor} [options.cursorFactory=Cursor] The cursor factory class used for all query cursors - * @param {string} options.host The server host - * @param {number} options.port The server port - * @param {number} [options.size=5] Server connection pool size - * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled - * @param {number} [options.keepAliveInitialDelay=300000] Initial delay before TCP keep alive enabled - * @param {boolean} [options.noDelay=true] TCP Connection no delay - * @param {number} [options.connectionTimeout=30000] TCP Connection timeout setting - * @param {number} [options.socketTimeout=360000] TCP Socket timeout setting - * @param {boolean} [options.ssl=false] Use SSL for connection - * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. - * @param {Buffer} [options.ca] SSL Certificate store binary buffer - * @param {Buffer} [options.crl] SSL Certificate revocation store binary buffer - * @param {Buffer} [options.cert] SSL Certificate binary buffer - * @param {Buffer} [options.key] SSL Key file binary buffer - * @param {string} [options.passphrase] SSL Certificate pass phrase - * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates - * @param {string} [options.servername=null] String containing the server name requested via TLS SNI. - * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits - * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. - * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. - * @param {string} [options.appname=null] Application name, passed in on ismaster call and logged in mongod server logs. Maximum size 128 bytes. - * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. - * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology - * @return {Server} A cursor instance - * @fires Server#connect - * @fires Server#close - * @fires Server#error - * @fires Server#timeout - * @fires Server#parseError - * @fires Server#reconnect - * @fires Server#reconnectFailed - * @fires Server#serverHeartbeatStarted - * @fires Server#serverHeartbeatSucceeded - * @fires Server#serverHeartbeatFailed - * @fires Server#topologyOpening - * @fires Server#topologyClosed - * @fires Server#topologyDescriptionChanged - * @property {string} type the topology type. - * @property {string} parserType the parser type used (c++ or js). - */ -var Server = function(options) { - options = options || {}; - - // Add event listener - EventEmitter.call(this); - - // Server instance id - this.id = id++; - - // Internal state - this.s = { - // Options - options: options, - // Logger - logger: Logger('Server', options), - // Factory overrides - Cursor: options.cursorFactory || CoreCursor, - // BSON instance - bson: - options.bson || - new BSON([ - BSON.Binary, - BSON.Code, - BSON.DBRef, - BSON.Decimal128, - BSON.Double, - BSON.Int32, - BSON.Long, - BSON.Map, - BSON.MaxKey, - BSON.MinKey, - BSON.ObjectId, - BSON.BSONRegExp, - BSON.Symbol, - BSON.Timestamp - ]), - // Pool - pool: null, - // Disconnect handler - disconnectHandler: options.disconnectHandler, - // Monitor thread (keeps the connection alive) - monitoring: typeof options.monitoring === 'boolean' ? options.monitoring : true, - // Is the server in a topology - inTopology: !!options.parent, - // Monitoring timeout - monitoringInterval: - typeof options.monitoringInterval === 'number' ? options.monitoringInterval : 5000, - // Topology id - topologyId: -1, - compression: { compressors: createCompressionInfo(options) }, - // Optional parent topology - parent: options.parent - }; - - // If this is a single deployment we need to track the clusterTime here - if (!this.s.parent) { - this.s.clusterTime = null; - } - - // Curent ismaster - this.ismaster = null; - // Current ping time - this.lastIsMasterMS = -1; - // The monitoringProcessId - this.monitoringProcessId = null; - // Initial connection - this.initialConnect = true; - // Default type - this._type = 'server'; - // Set the client info - this.clientInfo = createClientInfo(options); - - // Max Stalleness values - // last time we updated the ismaster state - this.lastUpdateTime = 0; - // Last write time - this.lastWriteDate = 0; - // Stalleness - this.staleness = 0; -}; - -inherits(Server, EventEmitter); -Object.assign(Server.prototype, SessionMixins); - -Object.defineProperty(Server.prototype, 'type', { - enumerable: true, - get: function() { - return this._type; - } -}); - -Object.defineProperty(Server.prototype, 'parserType', { - enumerable: true, - get: function() { - return BSON.native ? 'c++' : 'js'; - } -}); - -Object.defineProperty(Server.prototype, 'logicalSessionTimeoutMinutes', { - enumerable: true, - get: function() { - if (!this.ismaster) return null; - return this.ismaster.logicalSessionTimeoutMinutes || null; - } -}); - -// In single server deployments we track the clusterTime directly on the topology, however -// in Mongos and ReplSet deployments we instead need to delegate the clusterTime up to the -// tracking objects so we can ensure we are gossiping the maximum time received from the -// server. -Object.defineProperty(Server.prototype, 'clusterTime', { - enumerable: true, - set: function(clusterTime) { - const settings = this.s.parent ? this.s.parent : this.s; - resolveClusterTime(settings, clusterTime); - }, - get: function() { - const settings = this.s.parent ? this.s.parent : this.s; - return settings.clusterTime || null; - } -}); - -Server.enableServerAccounting = function() { - serverAccounting = true; - servers = {}; -}; - -Server.disableServerAccounting = function() { - serverAccounting = false; -}; - -Server.servers = function() { - return servers; -}; - -Object.defineProperty(Server.prototype, 'name', { - enumerable: true, - get: function() { - return this.s.options.host + ':' + this.s.options.port; - } -}); - -function disconnectHandler(self, type, ns, cmd, options, callback) { - // Topology is not connected, save the call in the provided store to be - // Executed at some point when the handler deems it's reconnected - if ( - !self.s.pool.isConnected() && - self.s.options.reconnect && - self.s.disconnectHandler != null && - !options.monitoring - ) { - self.s.disconnectHandler.add(type, ns, cmd, options, callback); - return true; - } - - // If we have no connection error - if (!self.s.pool.isConnected()) { - callback(new MongoError(f('no connection available to server %s', self.name))); - return true; - } -} - -function monitoringProcess(self) { - return function() { - // Pool was destroyed do not continue process - if (self.s.pool.isDestroyed()) return; - // Emit monitoring Process event - self.emit('monitoring', self); - // Perform ismaster call - // Get start time - var start = new Date().getTime(); - - // Execute the ismaster query - self.command( - 'admin.$cmd', - { ismaster: true }, - { - socketTimeout: - typeof self.s.options.connectionTimeout !== 'number' - ? 2000 - : self.s.options.connectionTimeout, - monitoring: true - }, - (err, result) => { - // Set initial lastIsMasterMS - self.lastIsMasterMS = new Date().getTime() - start; - if (self.s.pool.isDestroyed()) return; - // Update the ismaster view if we have a result - if (result) { - self.ismaster = result.result; - } - // Re-schedule the monitoring process - self.monitoringProcessId = setTimeout(monitoringProcess(self), self.s.monitoringInterval); - } - ); - }; -} - -var eventHandler = function(self, event) { - return function(err, conn) { - // Log information of received information if in info mode - if (self.s.logger.isInfo()) { - var object = err instanceof MongoError ? JSON.stringify(err) : {}; - self.s.logger.info( - f('server %s fired event %s out with message %s', self.name, event, object) - ); - } - - // Handle connect event - if (event === 'connect') { - self.initialConnect = false; - self.ismaster = conn.ismaster; - self.lastIsMasterMS = conn.lastIsMasterMS; - if (conn.agreedCompressor) { - self.s.pool.options.agreedCompressor = conn.agreedCompressor; - } - - if (conn.zlibCompressionLevel) { - self.s.pool.options.zlibCompressionLevel = conn.zlibCompressionLevel; - } - - if (conn.ismaster.$clusterTime) { - const $clusterTime = conn.ismaster.$clusterTime; - self.clusterTime = $clusterTime; - } - - // It's a proxy change the type so - // the wireprotocol will send $readPreference - if (self.ismaster.msg === 'isdbgrid') { - self._type = 'mongos'; - } - - // Have we defined self monitoring - if (self.s.monitoring) { - self.monitoringProcessId = setTimeout(monitoringProcess(self), self.s.monitoringInterval); - } - - // Emit server description changed if something listening - sdam.emitServerDescriptionChanged(self, { - address: self.name, - arbiters: [], - hosts: [], - passives: [], - type: sdam.getTopologyType(self) - }); - - if (!self.s.inTopology) { - // Emit topology description changed if something listening - sdam.emitTopologyDescriptionChanged(self, { - topologyType: 'Single', - servers: [ - { - address: self.name, - arbiters: [], - hosts: [], - passives: [], - type: sdam.getTopologyType(self) - } - ] - }); - } - - // Log the ismaster if available - if (self.s.logger.isInfo()) { - self.s.logger.info( - f('server %s connected with ismaster [%s]', self.name, JSON.stringify(self.ismaster)) - ); - } - - // Emit connect - self.emit('connect', self); - } else if ( - event === 'error' || - event === 'parseError' || - event === 'close' || - event === 'timeout' || - event === 'reconnect' || - event === 'attemptReconnect' || - 'reconnectFailed' - ) { - // Remove server instance from accounting - if ( - serverAccounting && - ['close', 'timeout', 'error', 'parseError', 'reconnectFailed'].indexOf(event) !== -1 - ) { - // Emit toplogy opening event if not in topology - if (!self.s.inTopology) { - self.emit('topologyOpening', { topologyId: self.id }); - } - - delete servers[self.id]; - } - - if (event === 'close') { - // Closing emits a server description changed event going to unknown. - sdam.emitServerDescriptionChanged(self, { - address: self.name, - arbiters: [], - hosts: [], - passives: [], - type: 'Unknown' - }); - } - - // Reconnect failed return error - if (event === 'reconnectFailed') { - self.emit('reconnectFailed', err); - // Emit error if any listeners - if (self.listeners('error').length > 0) { - self.emit('error', err); - } - // Terminate - return; - } - - // On first connect fail - if ( - ['disconnected', 'connecting'].indexOf(self.s.pool.state) !== -1 && - self.initialConnect && - ['close', 'timeout', 'error', 'parseError'].indexOf(event) !== -1 - ) { - self.initialConnect = false; - return self.emit( - 'error', - new MongoNetworkError( - f('failed to connect to server [%s] on first connect [%s]', self.name, err) - ) - ); - } - - // Reconnect event, emit the server - if (event === 'reconnect') { - // Reconnecting emits a server description changed event going from unknown to the - // current server type. - sdam.emitServerDescriptionChanged(self, { - address: self.name, - arbiters: [], - hosts: [], - passives: [], - type: sdam.getTopologyType(self) - }); - return self.emit(event, self); - } - - // Emit the event - self.emit(event, err); - } - }; -}; - -/** - * Initiate server connect - */ -Server.prototype.connect = function(options) { - var self = this; - options = options || {}; - - // Set the connections - if (serverAccounting) servers[this.id] = this; - - // Do not allow connect to be called on anything that's not disconnected - if (self.s.pool && !self.s.pool.isDisconnected() && !self.s.pool.isDestroyed()) { - throw new MongoError(f('server instance in invalid state %s', self.s.pool.state)); - } - - // Create a pool - self.s.pool = new Pool(this, Object.assign(self.s.options, options, { bson: this.s.bson })); - - // Set up listeners - self.s.pool.on('close', eventHandler(self, 'close')); - self.s.pool.on('error', eventHandler(self, 'error')); - self.s.pool.on('timeout', eventHandler(self, 'timeout')); - self.s.pool.on('parseError', eventHandler(self, 'parseError')); - self.s.pool.on('connect', eventHandler(self, 'connect')); - self.s.pool.on('reconnect', eventHandler(self, 'reconnect')); - self.s.pool.on('reconnectFailed', eventHandler(self, 'reconnectFailed')); - - // Set up listeners for command monitoring - relayEvents(self.s.pool, self, ['commandStarted', 'commandSucceeded', 'commandFailed']); - - // Emit toplogy opening event if not in topology - if (!self.s.inTopology) { - this.emit('topologyOpening', { topologyId: self.id }); - } - - // Emit opening server event - self.emit('serverOpening', { - topologyId: self.s.topologyId !== -1 ? self.s.topologyId : self.id, - address: self.name - }); - - self.s.pool.connect(); -}; - -/** - * Authenticate the topology. - * @method - * @param {MongoCredentials} credentials The credentials for authentication we are using - * @param {authResultCallback} callback A callback function - */ -Server.prototype.auth = function(credentials, callback) { - if (typeof callback === 'function') callback(null, null); -}; - -/** - * Get the server description - * @method - * @return {object} - */ -Server.prototype.getDescription = function() { - var ismaster = this.ismaster || {}; - var description = { - type: sdam.getTopologyType(this), - address: this.name - }; - - // Add fields if available - if (ismaster.hosts) description.hosts = ismaster.hosts; - if (ismaster.arbiters) description.arbiters = ismaster.arbiters; - if (ismaster.passives) description.passives = ismaster.passives; - if (ismaster.setName) description.setName = ismaster.setName; - return description; -}; - -/** - * Returns the last known ismaster document for this server - * @method - * @return {object} - */ -Server.prototype.lastIsMaster = function() { - return this.ismaster; -}; - -/** - * Unref all connections belong to this server - * @method - */ -Server.prototype.unref = function() { - this.s.pool.unref(); -}; - -/** - * Figure out if the server is connected - * @method - * @return {boolean} - */ -Server.prototype.isConnected = function() { - if (!this.s.pool) return false; - return this.s.pool.isConnected(); -}; - -/** - * Figure out if the server instance was destroyed by calling destroy - * @method - * @return {boolean} - */ -Server.prototype.isDestroyed = function() { - if (!this.s.pool) return false; - return this.s.pool.isDestroyed(); -}; - -function basicWriteValidations(self) { - if (!self.s.pool) return new MongoError('server instance is not connected'); - if (self.s.pool.isDestroyed()) return new MongoError('server instance pool was destroyed'); -} - -function basicReadValidations(self, options) { - basicWriteValidations(self, options); - - if (options.readPreference && !(options.readPreference instanceof ReadPreference)) { - throw new Error('readPreference must be an instance of ReadPreference'); - } -} - -/** - * Execute a command - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object} cmd The command hash - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.checkKeys=false] Specify if the bson parser should validate keys. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {Boolean} [options.fullResult=false] Return the full envelope instead of just the result document. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {opResultCallback} callback A callback function - */ -Server.prototype.command = function(ns, cmd, options, callback) { - var self = this; - if (typeof options === 'function') { - (callback = options), (options = {}), (options = options || {}); - } - - var result = basicReadValidations(self, options); - if (result) return callback(result); - - // Clone the options - options = Object.assign({}, options, { wireProtocolCommand: false }); - - // Debug log - if (self.s.logger.isDebug()) - self.s.logger.debug( - f( - 'executing command [%s] against %s', - JSON.stringify({ - ns: ns, - cmd: cmd, - options: debugOptions(debugFields, options) - }), - self.name - ) - ); - - // If we are not connected or have a disconnectHandler specified - if (disconnectHandler(self, 'command', ns, cmd, options, callback)) return; - - // error if collation not supported - if (collationNotSupported(this, cmd)) { - return callback(new MongoError(`server ${this.name} does not support collation`)); - } - - wireProtocol.command(self, ns, cmd, options, callback); -}; - -/** - * Execute a query against the server - * - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object} cmd The command document for the query - * @param {object} options Optional settings - * @param {function} callback - */ -Server.prototype.query = function(ns, cmd, cursorState, options, callback) { - wireProtocol.query(this, ns, cmd, cursorState, options, callback); -}; - -/** - * Execute a `getMore` against the server - * - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object} cursorState State data associated with the cursor calling this method - * @param {object} options Optional settings - * @param {function} callback - */ -Server.prototype.getMore = function(ns, cursorState, batchSize, options, callback) { - wireProtocol.getMore(this, ns, cursorState, batchSize, options, callback); -}; - -/** - * Execute a `killCursors` command against the server - * - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object} cursorState State data associated with the cursor calling this method - * @param {function} callback - */ -Server.prototype.killCursors = function(ns, cursorState, callback) { - wireProtocol.killCursors(this, ns, cursorState, callback); -}; - -/** - * Insert one or more documents - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of documents to insert - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {opResultCallback} callback A callback function - */ -Server.prototype.insert = function(ns, ops, options, callback) { - var self = this; - if (typeof options === 'function') { - (callback = options), (options = {}), (options = options || {}); - } - - var result = basicWriteValidations(self, options); - if (result) return callback(result); - - // If we are not connected or have a disconnectHandler specified - if (disconnectHandler(self, 'insert', ns, ops, options, callback)) return; - - // Setup the docs as an array - ops = Array.isArray(ops) ? ops : [ops]; - - // Execute write - return wireProtocol.insert(self, ns, ops, options, callback); -}; - -/** - * Perform one or more update operations - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of updates - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {opResultCallback} callback A callback function - */ -Server.prototype.update = function(ns, ops, options, callback) { - var self = this; - if (typeof options === 'function') { - (callback = options), (options = {}), (options = options || {}); - } - - var result = basicWriteValidations(self, options); - if (result) return callback(result); - - // If we are not connected or have a disconnectHandler specified - if (disconnectHandler(self, 'update', ns, ops, options, callback)) return; - - // error if collation not supported - if (collationNotSupported(this, options)) { - return callback(new MongoError(`server ${this.name} does not support collation`)); - } - - // Setup the docs as an array - ops = Array.isArray(ops) ? ops : [ops]; - // Execute write - return wireProtocol.update(self, ns, ops, options, callback); -}; - -/** - * Perform one or more remove operations - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of removes - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {opResultCallback} callback A callback function - */ -Server.prototype.remove = function(ns, ops, options, callback) { - var self = this; - if (typeof options === 'function') { - (callback = options), (options = {}), (options = options || {}); - } - - var result = basicWriteValidations(self, options); - if (result) return callback(result); - - // If we are not connected or have a disconnectHandler specified - if (disconnectHandler(self, 'remove', ns, ops, options, callback)) return; - - // error if collation not supported - if (collationNotSupported(this, options)) { - return callback(new MongoError(`server ${this.name} does not support collation`)); - } - - // Setup the docs as an array - ops = Array.isArray(ops) ? ops : [ops]; - // Execute write - return wireProtocol.remove(self, ns, ops, options, callback); -}; - -/** - * Get a new cursor - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object|Long} cmd Can be either a command returning a cursor or a cursorId - * @param {object} [options] Options for the cursor - * @param {object} [options.batchSize=0] Batchsize for the operation - * @param {array} [options.documents=[]] Initial documents list for cursor - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {ClientSession} [options.session=null] Session to use for the operation - * @param {object} [options.topology] The internal topology of the created cursor - * @returns {Cursor} - */ -Server.prototype.cursor = function(ns, cmd, options) { - options = options || {}; - const topology = options.topology || this; - - // Set up final cursor type - var FinalCursor = options.cursorFactory || this.s.Cursor; - - // Return the cursor - return new FinalCursor(topology, ns, cmd, options); -}; - -/** - * Compare two server instances - * @method - * @param {Server} server Server to compare equality against - * @return {boolean} - */ -Server.prototype.equals = function(server) { - if (typeof server === 'string') return this.name.toLowerCase() === server.toLowerCase(); - if (server.name) return this.name.toLowerCase() === server.name.toLowerCase(); - return false; -}; - -/** - * All raw connections - * @method - * @return {Connection[]} - */ -Server.prototype.connections = function() { - return this.s.pool.allConnections(); -}; - -/** - * Selects a server - * @method - * @param {function} selector Unused - * @param {ReadPreference} [options.readPreference] Unused - * @param {ClientSession} [options.session] Unused - * @return {Server} - */ -Server.prototype.selectServer = function(selector, options, callback) { - if (typeof selector === 'function' && typeof callback === 'undefined') - (callback = selector), (selector = undefined), (options = {}); - if (typeof options === 'function') - (callback = options), (options = selector), (selector = undefined); - - callback(null, this); -}; - -var listeners = ['close', 'error', 'timeout', 'parseError', 'connect']; - -/** - * Destroy the server connection - * @method - * @param {boolean} [options.emitClose=false] Emit close event on destroy - * @param {boolean} [options.emitDestroy=false] Emit destroy event on destroy - * @param {boolean} [options.force=false] Force destroy the pool - */ -Server.prototype.destroy = function(options, callback) { - if (this._destroyed) { - if (typeof callback === 'function') callback(null, null); - return; - } - - if (typeof options === 'function') { - callback = options; - options = {}; - } - - options = options || {}; - var self = this; - - // Set the connections - if (serverAccounting) delete servers[this.id]; - - // Destroy the monitoring process if any - if (this.monitoringProcessId) { - clearTimeout(this.monitoringProcessId); - } - - // No pool, return - if (!self.s.pool) { - this._destroyed = true; - if (typeof callback === 'function') callback(null, null); - return; - } - - // Emit close event - if (options.emitClose) { - self.emit('close', self); - } - - // Emit destroy event - if (options.emitDestroy) { - self.emit('destroy', self); - } - - // Remove all listeners - listeners.forEach(function(event) { - self.s.pool.removeAllListeners(event); - }); - - // Emit opening server event - if (self.listeners('serverClosed').length > 0) - self.emit('serverClosed', { - topologyId: self.s.topologyId !== -1 ? self.s.topologyId : self.id, - address: self.name - }); - - // Emit toplogy opening event if not in topology - if (self.listeners('topologyClosed').length > 0 && !self.s.inTopology) { - self.emit('topologyClosed', { topologyId: self.id }); - } - - if (self.s.logger.isDebug()) { - self.s.logger.debug(f('destroy called on server %s', self.name)); - } - - // Destroy the pool - this.s.pool.destroy(options.force, callback); - this._destroyed = true; -}; - -/** - * A server connect event, used to verify that the connection is up and running - * - * @event Server#connect - * @type {Server} - */ - -/** - * A server reconnect event, used to verify that the server topology has reconnected - * - * @event Server#reconnect - * @type {Server} - */ - -/** - * A server opening SDAM monitoring event - * - * @event Server#serverOpening - * @type {object} - */ - -/** - * A server closed SDAM monitoring event - * - * @event Server#serverClosed - * @type {object} - */ - -/** - * A server description SDAM change monitoring event - * - * @event Server#serverDescriptionChanged - * @type {object} - */ - -/** - * A topology open SDAM event - * - * @event Server#topologyOpening - * @type {object} - */ - -/** - * A topology closed SDAM event - * - * @event Server#topologyClosed - * @type {object} - */ - -/** - * A topology structure SDAM change event - * - * @event Server#topologyDescriptionChanged - * @type {object} - */ - -/** - * Server reconnect failed - * - * @event Server#reconnectFailed - * @type {Error} - */ - -/** - * Server connection pool closed - * - * @event Server#close - * @type {object} - */ - -/** - * Server connection pool caused an error - * - * @event Server#error - * @type {Error} - */ - -/** - * Server destroyed was called - * - * @event Server#destroy - * @type {Server} - */ - -module.exports = Server; diff --git a/scripts/node_modules/mongodb/lib/core/topologies/shared.js b/scripts/node_modules/mongodb/lib/core/topologies/shared.js deleted file mode 100644 index 8e227bad..00000000 --- a/scripts/node_modules/mongodb/lib/core/topologies/shared.js +++ /dev/null @@ -1,476 +0,0 @@ -'use strict'; - -const os = require('os'); -const f = require('util').format; -const ReadPreference = require('./read_preference'); -const Buffer = require('safe-buffer').Buffer; -const TopologyType = require('../sdam/topology_description').TopologyType; -const MongoError = require('../error').MongoError; - -const MMAPv1_RETRY_WRITES_ERROR_CODE = 20; - -/** - * Emit event if it exists - * @method - */ -function emitSDAMEvent(self, event, description) { - if (self.listeners(event).length > 0) { - self.emit(event, description); - } -} - -// Get package.json variable -var driverVersion = require('../../../package.json').version; -var nodejsversion = f('Node.js %s, %s', process.version, os.endianness()); -var type = os.type(); -var name = process.platform; -var architecture = process.arch; -var release = os.release(); - -function createClientInfo(options) { - // Build default client information - var clientInfo = options.clientInfo - ? clone(options.clientInfo) - : { - driver: { - name: 'nodejs-core', - version: driverVersion - }, - os: { - type: type, - name: name, - architecture: architecture, - version: release - } - }; - - // Is platform specified - if (clientInfo.platform && clientInfo.platform.indexOf('mongodb-core') === -1) { - clientInfo.platform = f('%s, mongodb-core: %s', clientInfo.platform, driverVersion); - } else if (!clientInfo.platform) { - clientInfo.platform = nodejsversion; - } - - // Do we have an application specific string - if (options.appname) { - // Cut at 128 bytes - var buffer = Buffer.from(options.appname); - // Return the truncated appname - var appname = buffer.length > 128 ? buffer.slice(0, 128).toString('utf8') : options.appname; - // Add to the clientInfo - clientInfo.application = { name: appname }; - } - - return clientInfo; -} - -function createCompressionInfo(options) { - if (!options.compression || !options.compression.compressors) { - return []; - } - - // Check that all supplied compressors are valid - options.compression.compressors.forEach(function(compressor) { - if (compressor !== 'snappy' && compressor !== 'zlib') { - throw new Error('compressors must be at least one of snappy or zlib'); - } - }); - - return options.compression.compressors; -} - -function clone(object) { - return JSON.parse(JSON.stringify(object)); -} - -var getPreviousDescription = function(self) { - if (!self.s.serverDescription) { - self.s.serverDescription = { - address: self.name, - arbiters: [], - hosts: [], - passives: [], - type: 'Unknown' - }; - } - - return self.s.serverDescription; -}; - -var emitServerDescriptionChanged = function(self, description) { - if (self.listeners('serverDescriptionChanged').length > 0) { - // Emit the server description changed events - self.emit('serverDescriptionChanged', { - topologyId: self.s.topologyId !== -1 ? self.s.topologyId : self.id, - address: self.name, - previousDescription: getPreviousDescription(self), - newDescription: description - }); - - self.s.serverDescription = description; - } -}; - -var getPreviousTopologyDescription = function(self) { - if (!self.s.topologyDescription) { - self.s.topologyDescription = { - topologyType: 'Unknown', - servers: [ - { - address: self.name, - arbiters: [], - hosts: [], - passives: [], - type: 'Unknown' - } - ] - }; - } - - return self.s.topologyDescription; -}; - -var emitTopologyDescriptionChanged = function(self, description) { - if (self.listeners('topologyDescriptionChanged').length > 0) { - // Emit the server description changed events - self.emit('topologyDescriptionChanged', { - topologyId: self.s.topologyId !== -1 ? self.s.topologyId : self.id, - address: self.name, - previousDescription: getPreviousTopologyDescription(self), - newDescription: description - }); - - self.s.serverDescription = description; - } -}; - -var changedIsMaster = function(self, currentIsmaster, ismaster) { - var currentType = getTopologyType(self, currentIsmaster); - var newType = getTopologyType(self, ismaster); - if (newType !== currentType) return true; - return false; -}; - -var getTopologyType = function(self, ismaster) { - if (!ismaster) { - ismaster = self.ismaster; - } - - if (!ismaster) return 'Unknown'; - if (ismaster.ismaster && ismaster.msg === 'isdbgrid') return 'Mongos'; - if (ismaster.ismaster && !ismaster.hosts) return 'Standalone'; - if (ismaster.ismaster) return 'RSPrimary'; - if (ismaster.secondary) return 'RSSecondary'; - if (ismaster.arbiterOnly) return 'RSArbiter'; - return 'Unknown'; -}; - -var inquireServerState = function(self) { - return function(callback) { - if (self.s.state === 'destroyed') return; - // Record response time - var start = new Date().getTime(); - - // emitSDAMEvent - emitSDAMEvent(self, 'serverHeartbeatStarted', { connectionId: self.name }); - - // Attempt to execute ismaster command - self.command('admin.$cmd', { ismaster: true }, { monitoring: true }, function(err, r) { - if (!err) { - // Legacy event sender - self.emit('ismaster', r, self); - - // Calculate latencyMS - var latencyMS = new Date().getTime() - start; - - // Server heart beat event - emitSDAMEvent(self, 'serverHeartbeatSucceeded', { - durationMS: latencyMS, - reply: r.result, - connectionId: self.name - }); - - // Did the server change - if (changedIsMaster(self, self.s.ismaster, r.result)) { - // Emit server description changed if something listening - emitServerDescriptionChanged(self, { - address: self.name, - arbiters: [], - hosts: [], - passives: [], - type: !self.s.inTopology ? 'Standalone' : getTopologyType(self) - }); - } - - // Updat ismaster view - self.s.ismaster = r.result; - - // Set server response time - self.s.isMasterLatencyMS = latencyMS; - } else { - emitSDAMEvent(self, 'serverHeartbeatFailed', { - durationMS: latencyMS, - failure: err, - connectionId: self.name - }); - } - - // Peforming an ismaster monitoring callback operation - if (typeof callback === 'function') { - return callback(err, r); - } - - // Perform another sweep - self.s.inquireServerStateTimeout = setTimeout(inquireServerState(self), self.s.haInterval); - }); - }; -}; - -// -// Clone the options -var cloneOptions = function(options) { - var opts = {}; - for (var name in options) { - opts[name] = options[name]; - } - return opts; -}; - -function Interval(fn, time) { - var timer = false; - - this.start = function() { - if (!this.isRunning()) { - timer = setInterval(fn, time); - } - - return this; - }; - - this.stop = function() { - clearInterval(timer); - timer = false; - return this; - }; - - this.isRunning = function() { - return timer !== false; - }; -} - -function Timeout(fn, time) { - var timer = false; - - this.start = function() { - if (!this.isRunning()) { - timer = setTimeout(fn, time); - } - return this; - }; - - this.stop = function() { - clearTimeout(timer); - timer = false; - return this; - }; - - this.isRunning = function() { - if (timer && timer._called) return false; - return timer !== false; - }; -} - -function diff(previous, current) { - // Difference document - var diff = { - servers: [] - }; - - // Previous entry - if (!previous) { - previous = { servers: [] }; - } - - // Check if we have any previous servers missing in the current ones - for (var i = 0; i < previous.servers.length; i++) { - var found = false; - - for (var j = 0; j < current.servers.length; j++) { - if (current.servers[j].address.toLowerCase() === previous.servers[i].address.toLowerCase()) { - found = true; - break; - } - } - - if (!found) { - // Add to the diff - diff.servers.push({ - address: previous.servers[i].address, - from: previous.servers[i].type, - to: 'Unknown' - }); - } - } - - // Check if there are any severs that don't exist - for (j = 0; j < current.servers.length; j++) { - found = false; - - // Go over all the previous servers - for (i = 0; i < previous.servers.length; i++) { - if (previous.servers[i].address.toLowerCase() === current.servers[j].address.toLowerCase()) { - found = true; - break; - } - } - - // Add the server to the diff - if (!found) { - diff.servers.push({ - address: current.servers[j].address, - from: 'Unknown', - to: current.servers[j].type - }); - } - } - - // Got through all the servers - for (i = 0; i < previous.servers.length; i++) { - var prevServer = previous.servers[i]; - - // Go through all current servers - for (j = 0; j < current.servers.length; j++) { - var currServer = current.servers[j]; - - // Matching server - if (prevServer.address.toLowerCase() === currServer.address.toLowerCase()) { - // We had a change in state - if (prevServer.type !== currServer.type) { - diff.servers.push({ - address: prevServer.address, - from: prevServer.type, - to: currServer.type - }); - } - } - } - } - - // Return difference - return diff; -} - -/** - * Shared function to determine clusterTime for a given topology - * - * @param {*} topology - * @param {*} clusterTime - */ -function resolveClusterTime(topology, $clusterTime) { - if (topology.clusterTime == null) { - topology.clusterTime = $clusterTime; - } else { - if ($clusterTime.clusterTime.greaterThan(topology.clusterTime.clusterTime)) { - topology.clusterTime = $clusterTime; - } - } -} - -// NOTE: this is a temporary move until the topologies can be more formally refactored -// to share code. -const SessionMixins = { - endSessions: function(sessions, callback) { - if (!Array.isArray(sessions)) { - sessions = [sessions]; - } - - // TODO: - // When connected to a sharded cluster the endSessions command - // can be sent to any mongos. When connected to a replica set the - // endSessions command MUST be sent to the primary if the primary - // is available, otherwise it MUST be sent to any available secondary. - // Is it enough to use: ReadPreference.primaryPreferred ? - this.command( - 'admin.$cmd', - { endSessions: sessions }, - { readPreference: ReadPreference.primaryPreferred }, - () => { - // intentionally ignored, per spec - if (typeof callback === 'function') callback(); - } - ); - } -}; - -function topologyType(topology) { - if (topology.description) { - return topology.description.type; - } - - if (topology.type === 'mongos') { - return TopologyType.Sharded; - } else if (topology.type === 'replset') { - return TopologyType.ReplicaSetWithPrimary; - } - - return TopologyType.Single; -} - -const RETRYABLE_WIRE_VERSION = 6; - -/** - * Determines whether the provided topology supports retryable writes - * - * @param {Mongos|Replset} topology - */ -const isRetryableWritesSupported = function(topology) { - const maxWireVersion = topology.lastIsMaster().maxWireVersion; - if (maxWireVersion < RETRYABLE_WIRE_VERSION) { - return false; - } - - if (!topology.logicalSessionTimeoutMinutes) { - return false; - } - - if (topologyType(topology) === TopologyType.Single) { - return false; - } - - return true; -}; - -const MMAPv1_RETRY_WRITES_ERROR_MESSAGE = - 'This MongoDB deployment does not support retryable writes. Please add retryWrites=false to your connection string.'; - -function getMMAPError(err) { - if (err.code !== MMAPv1_RETRY_WRITES_ERROR_CODE || !err.errmsg.includes('Transaction numbers')) { - return err; - } - - // According to the retryable writes spec, we must replace the error message in this case. - // We need to replace err.message so the thrown message is correct and we need to replace err.errmsg to meet the spec requirement. - const newErr = new MongoError({ - message: MMAPv1_RETRY_WRITES_ERROR_MESSAGE, - errmsg: MMAPv1_RETRY_WRITES_ERROR_MESSAGE, - originalError: err - }); - return newErr; -} - -module.exports.SessionMixins = SessionMixins; -module.exports.resolveClusterTime = resolveClusterTime; -module.exports.inquireServerState = inquireServerState; -module.exports.getTopologyType = getTopologyType; -module.exports.emitServerDescriptionChanged = emitServerDescriptionChanged; -module.exports.emitTopologyDescriptionChanged = emitTopologyDescriptionChanged; -module.exports.cloneOptions = cloneOptions; -module.exports.createClientInfo = createClientInfo; -module.exports.createCompressionInfo = createCompressionInfo; -module.exports.clone = clone; -module.exports.diff = diff; -module.exports.Interval = Interval; -module.exports.Timeout = Timeout; -module.exports.isRetryableWritesSupported = isRetryableWritesSupported; -module.exports.getMMAPError = getMMAPError; -module.exports.topologyType = topologyType; diff --git a/scripts/node_modules/mongodb/lib/core/transactions.js b/scripts/node_modules/mongodb/lib/core/transactions.js deleted file mode 100644 index 891a8734..00000000 --- a/scripts/node_modules/mongodb/lib/core/transactions.js +++ /dev/null @@ -1,168 +0,0 @@ -'use strict'; -const MongoError = require('./error').MongoError; - -let TxnState; -let stateMachine; - -(() => { - const NO_TRANSACTION = 'NO_TRANSACTION'; - const STARTING_TRANSACTION = 'STARTING_TRANSACTION'; - const TRANSACTION_IN_PROGRESS = 'TRANSACTION_IN_PROGRESS'; - const TRANSACTION_COMMITTED = 'TRANSACTION_COMMITTED'; - const TRANSACTION_COMMITTED_EMPTY = 'TRANSACTION_COMMITTED_EMPTY'; - const TRANSACTION_ABORTED = 'TRANSACTION_ABORTED'; - - TxnState = { - NO_TRANSACTION, - STARTING_TRANSACTION, - TRANSACTION_IN_PROGRESS, - TRANSACTION_COMMITTED, - TRANSACTION_COMMITTED_EMPTY, - TRANSACTION_ABORTED - }; - - stateMachine = { - [NO_TRANSACTION]: [NO_TRANSACTION, STARTING_TRANSACTION], - [STARTING_TRANSACTION]: [ - TRANSACTION_IN_PROGRESS, - TRANSACTION_COMMITTED, - TRANSACTION_COMMITTED_EMPTY, - TRANSACTION_ABORTED - ], - [TRANSACTION_IN_PROGRESS]: [ - TRANSACTION_IN_PROGRESS, - TRANSACTION_COMMITTED, - TRANSACTION_ABORTED - ], - [TRANSACTION_COMMITTED]: [ - TRANSACTION_COMMITTED, - TRANSACTION_COMMITTED_EMPTY, - STARTING_TRANSACTION, - NO_TRANSACTION - ], - [TRANSACTION_ABORTED]: [STARTING_TRANSACTION, NO_TRANSACTION], - [TRANSACTION_COMMITTED_EMPTY]: [TRANSACTION_COMMITTED_EMPTY, NO_TRANSACTION] - }; -})(); - -/** - * The MongoDB ReadConcern, which allows for control of the consistency and isolation properties - * of the data read from replica sets and replica set shards. - * @typedef {Object} ReadConcern - * @property {'local'|'available'|'majority'|'linearizable'|'snapshot'} level The readConcern Level - * @see https://docs.mongodb.com/manual/reference/read-concern/ - */ - -/** - * A MongoDB WriteConcern, which describes the level of acknowledgement - * requested from MongoDB for write operations. - * @typedef {Object} WriteConcern - * @property {number|'majority'|string} [w=1] requests acknowledgement that the write operation has - * propagated to a specified number of mongod hosts - * @property {boolean} [j=false] requests acknowledgement from MongoDB that the write operation has - * been written to the journal - * @property {number} [wtimeout] a time limit, in milliseconds, for the write concern - * @see https://docs.mongodb.com/manual/reference/write-concern/ - */ - -/** - * Configuration options for a transaction. - * @typedef {Object} TransactionOptions - * @property {ReadConcern} [readConcern] A default read concern for commands in this transaction - * @property {WriteConcern} [writeConcern] A default writeConcern for commands in this transaction - * @property {ReadPreference} [readPreference] A default read preference for commands in this transaction - */ - -/** - * A class maintaining state related to a server transaction. Internal Only - * @ignore - */ -class Transaction { - /** - * Create a transaction - * - * @ignore - * @param {TransactionOptions} [options] Optional settings - */ - constructor(options) { - options = options || {}; - - this.state = TxnState.NO_TRANSACTION; - this.options = {}; - - if (options.writeConcern || typeof options.w !== 'undefined') { - const w = options.writeConcern ? options.writeConcern.w : options.w; - if (w <= 0) { - throw new MongoError('Transactions do not support unacknowledged write concern'); - } - - this.options.writeConcern = options.writeConcern ? options.writeConcern : { w: options.w }; - } - - if (options.readConcern) this.options.readConcern = options.readConcern; - if (options.readPreference) this.options.readPreference = options.readPreference; - if (options.maxCommitTimeMS) this.options.maxTimeMS = options.maxCommitTimeMS; - - // TODO: This isn't technically necessary - this._pinnedServer = undefined; - this._recoveryToken = undefined; - } - - get server() { - return this._pinnedServer; - } - - get recoveryToken() { - return this._recoveryToken; - } - - get isPinned() { - return !!this.server; - } - - /** - * @ignore - * @return Whether this session is presently in a transaction - */ - get isActive() { - return ( - [TxnState.STARTING_TRANSACTION, TxnState.TRANSACTION_IN_PROGRESS].indexOf(this.state) !== -1 - ); - } - - /** - * Transition the transaction in the state machine - * @ignore - * @param {TxnState} state The new state to transition to - */ - transition(nextState) { - const nextStates = stateMachine[this.state]; - if (nextStates && nextStates.indexOf(nextState) !== -1) { - this.state = nextState; - if (this.state === TxnState.NO_TRANSACTION || this.state === TxnState.STARTING_TRANSACTION) { - this.unpinServer(); - } - return; - } - - throw new MongoError( - `Attempted illegal state transition from [${this.state}] to [${nextState}]` - ); - } - - pinServer(server) { - if (this.isActive) { - this._pinnedServer = server; - } - } - - unpinServer() { - this._pinnedServer = undefined; - } -} - -function isTransactionCommand(command) { - return !!(command.commitTransaction || command.abortTransaction); -} - -module.exports = { TxnState, Transaction, isTransactionCommand }; diff --git a/scripts/node_modules/mongodb/lib/core/uri_parser.js b/scripts/node_modules/mongodb/lib/core/uri_parser.js deleted file mode 100644 index 1530d88d..00000000 --- a/scripts/node_modules/mongodb/lib/core/uri_parser.js +++ /dev/null @@ -1,637 +0,0 @@ -'use strict'; -const URL = require('url'); -const qs = require('querystring'); -const dns = require('dns'); -const MongoParseError = require('./error').MongoParseError; -const ReadPreference = require('./topologies/read_preference'); - -/** - * The following regular expression validates a connection string and breaks the - * provide string into the following capture groups: [protocol, username, password, hosts] - */ -const HOSTS_RX = /(mongodb(?:\+srv|)):\/\/(?: (?:[^:]*) (?: : ([^@]*) )? @ )?([^/?]*)(?:\/|)(.*)/; - -/** - * Determines whether a provided address matches the provided parent domain in order - * to avoid certain attack vectors. - * - * @param {String} srvAddress The address to check against a domain - * @param {String} parentDomain The domain to check the provided address against - * @return {Boolean} Whether the provided address matches the parent domain - */ -function matchesParentDomain(srvAddress, parentDomain) { - const regex = /^.*?\./; - const srv = `.${srvAddress.replace(regex, '')}`; - const parent = `.${parentDomain.replace(regex, '')}`; - return srv.endsWith(parent); -} - -/** - * Lookup a `mongodb+srv` connection string, combine the parts and reparse it as a normal - * connection string. - * - * @param {string} uri The connection string to parse - * @param {object} options Optional user provided connection string options - * @param {function} callback - */ -function parseSrvConnectionString(uri, options, callback) { - const result = URL.parse(uri, true); - - if (result.hostname.split('.').length < 3) { - return callback(new MongoParseError('URI does not have hostname, domain name and tld')); - } - - result.domainLength = result.hostname.split('.').length; - if (result.pathname && result.pathname.match(',')) { - return callback(new MongoParseError('Invalid URI, cannot contain multiple hostnames')); - } - - if (result.port) { - return callback(new MongoParseError(`Ports not accepted with '${PROTOCOL_MONGODB_SRV}' URIs`)); - } - - // Resolve the SRV record and use the result as the list of hosts to connect to. - const lookupAddress = result.host; - dns.resolveSrv(`_mongodb._tcp.${lookupAddress}`, (err, addresses) => { - if (err) return callback(err); - - if (addresses.length === 0) { - return callback(new MongoParseError('No addresses found at host')); - } - - for (let i = 0; i < addresses.length; i++) { - if (!matchesParentDomain(addresses[i].name, result.hostname, result.domainLength)) { - return callback( - new MongoParseError('Server record does not share hostname with parent URI') - ); - } - } - - // Convert the original URL to a non-SRV URL. - result.protocol = 'mongodb'; - result.host = addresses.map(address => `${address.name}:${address.port}`).join(','); - - // Default to SSL true if it's not specified. - if ( - !('ssl' in options) && - (!result.search || !('ssl' in result.query) || result.query.ssl === null) - ) { - result.query.ssl = true; - } - - // Resolve TXT record and add options from there if they exist. - dns.resolveTxt(lookupAddress, (err, record) => { - if (err) { - if (err.code !== 'ENODATA') { - return callback(err); - } - record = null; - } - - if (record) { - if (record.length > 1) { - return callback(new MongoParseError('Multiple text records not allowed')); - } - - record = qs.parse(record[0].join('')); - if (Object.keys(record).some(key => key !== 'authSource' && key !== 'replicaSet')) { - return callback( - new MongoParseError('Text record must only set `authSource` or `replicaSet`') - ); - } - - Object.assign(result.query, record); - } - - // Set completed options back into the URL object. - result.search = qs.stringify(result.query); - - const finalString = URL.format(result); - parseConnectionString(finalString, options, (err, ret) => { - if (err) { - callback(err); - return; - } - - callback(null, Object.assign({}, ret, { srvHost: lookupAddress })); - }); - }); - }); -} - -/** - * Parses a query string item according to the connection string spec - * - * @param {string} key The key for the parsed value - * @param {Array|String} value The value to parse - * @return {Array|Object|String} The parsed value - */ -function parseQueryStringItemValue(key, value) { - if (Array.isArray(value)) { - // deduplicate and simplify arrays - value = value.filter((v, idx) => value.indexOf(v) === idx); - if (value.length === 1) value = value[0]; - } else if (value.indexOf(':') > 0) { - value = value.split(',').reduce((result, pair) => { - const parts = pair.split(':'); - result[parts[0]] = parseQueryStringItemValue(key, parts[1]); - return result; - }, {}); - } else if (value.indexOf(',') > 0) { - value = value.split(',').map(v => { - return parseQueryStringItemValue(key, v); - }); - } else if (value.toLowerCase() === 'true' || value.toLowerCase() === 'false') { - value = value.toLowerCase() === 'true'; - } else if (!Number.isNaN(value) && !STRING_OPTIONS.has(key)) { - const numericValue = parseFloat(value); - if (!Number.isNaN(numericValue)) { - value = parseFloat(value); - } - } - - return value; -} - -// Options that are known boolean types -const BOOLEAN_OPTIONS = new Set([ - 'slaveok', - 'slave_ok', - 'sslvalidate', - 'fsync', - 'safe', - 'retrywrites', - 'j' -]); - -// Known string options, only used to bypass Number coercion in `parseQueryStringItemValue` -const STRING_OPTIONS = new Set(['authsource', 'replicaset']); - -// Supported text representations of auth mechanisms -// NOTE: this list exists in native already, if it is merged here we should deduplicate -const AUTH_MECHANISMS = new Set([ - 'GSSAPI', - 'MONGODB-X509', - 'MONGODB-CR', - 'DEFAULT', - 'SCRAM-SHA-1', - 'SCRAM-SHA-256', - 'PLAIN' -]); - -// Lookup table used to translate normalized (lower-cased) forms of connection string -// options to their expected camelCase version -const CASE_TRANSLATION = { - replicaset: 'replicaSet', - connecttimeoutms: 'connectTimeoutMS', - sockettimeoutms: 'socketTimeoutMS', - maxpoolsize: 'maxPoolSize', - minpoolsize: 'minPoolSize', - maxidletimems: 'maxIdleTimeMS', - waitqueuemultiple: 'waitQueueMultiple', - waitqueuetimeoutms: 'waitQueueTimeoutMS', - wtimeoutms: 'wtimeoutMS', - readconcern: 'readConcern', - readconcernlevel: 'readConcernLevel', - readpreference: 'readPreference', - maxstalenessseconds: 'maxStalenessSeconds', - readpreferencetags: 'readPreferenceTags', - authsource: 'authSource', - authmechanism: 'authMechanism', - authmechanismproperties: 'authMechanismProperties', - gssapiservicename: 'gssapiServiceName', - localthresholdms: 'localThresholdMS', - serverselectiontimeoutms: 'serverSelectionTimeoutMS', - serverselectiontryonce: 'serverSelectionTryOnce', - heartbeatfrequencyms: 'heartbeatFrequencyMS', - retrywrites: 'retryWrites', - uuidrepresentation: 'uuidRepresentation', - zlibcompressionlevel: 'zlibCompressionLevel', - tlsallowinvalidcertificates: 'tlsAllowInvalidCertificates', - tlsallowinvalidhostnames: 'tlsAllowInvalidHostnames', - tlsinsecure: 'tlsInsecure', - tlscafile: 'tlsCAFile', - tlscertificatekeyfile: 'tlsCertificateKeyFile', - tlscertificatekeyfilepassword: 'tlsCertificateKeyFilePassword', - wtimeout: 'wTimeoutMS', - j: 'journal' -}; - -/** - * Sets the value for `key`, allowing for any required translation - * - * @param {object} obj The object to set the key on - * @param {string} key The key to set the value for - * @param {*} value The value to set - * @param {object} options The options used for option parsing - */ -function applyConnectionStringOption(obj, key, value, options) { - // simple key translation - if (key === 'journal') { - key = 'j'; - } else if (key === 'wtimeoutms') { - key = 'wtimeout'; - } - - // more complicated translation - if (BOOLEAN_OPTIONS.has(key)) { - value = value === 'true' || value === true; - } else if (key === 'appname') { - value = decodeURIComponent(value); - } else if (key === 'readconcernlevel') { - obj['readConcernLevel'] = value; - key = 'readconcern'; - value = { level: value }; - } - - // simple validation - if (key === 'compressors') { - value = Array.isArray(value) ? value : [value]; - - if (!value.every(c => c === 'snappy' || c === 'zlib')) { - throw new MongoParseError( - 'Value for `compressors` must be at least one of: `snappy`, `zlib`' - ); - } - } - - if (key === 'authmechanism' && !AUTH_MECHANISMS.has(value)) { - throw new MongoParseError( - 'Value for `authMechanism` must be one of: `DEFAULT`, `GSSAPI`, `PLAIN`, `MONGODB-X509`, `SCRAM-SHA-1`, `SCRAM-SHA-256`' - ); - } - - if (key === 'readpreference' && !ReadPreference.isValid(value)) { - throw new MongoParseError( - 'Value for `readPreference` must be one of: `primary`, `primaryPreferred`, `secondary`, `secondaryPreferred`, `nearest`' - ); - } - - if (key === 'zlibcompressionlevel' && (value < -1 || value > 9)) { - throw new MongoParseError('zlibCompressionLevel must be an integer between -1 and 9'); - } - - // special cases - if (key === 'compressors' || key === 'zlibcompressionlevel') { - obj.compression = obj.compression || {}; - obj = obj.compression; - } - - if (key === 'authmechanismproperties') { - if (typeof value.SERVICE_NAME === 'string') obj.gssapiServiceName = value.SERVICE_NAME; - if (typeof value.SERVICE_REALM === 'string') obj.gssapiServiceRealm = value.SERVICE_REALM; - if (typeof value.CANONICALIZE_HOST_NAME !== 'undefined') { - obj.gssapiCanonicalizeHostName = value.CANONICALIZE_HOST_NAME; - } - } - - if (key === 'readpreferencetags' && Array.isArray(value)) { - value = splitArrayOfMultipleReadPreferenceTags(value); - } - - // set the actual value - if (options.caseTranslate && CASE_TRANSLATION[key]) { - obj[CASE_TRANSLATION[key]] = value; - return; - } - - obj[key] = value; -} - -const USERNAME_REQUIRED_MECHANISMS = new Set([ - 'GSSAPI', - 'MONGODB-CR', - 'PLAIN', - 'SCRAM-SHA-1', - 'SCRAM-SHA-256' -]); - -function splitArrayOfMultipleReadPreferenceTags(value) { - const parsedTags = []; - - for (let i = 0; i < value.length; i++) { - parsedTags[i] = {}; - value[i].split(',').forEach(individualTag => { - const splitTag = individualTag.split(':'); - parsedTags[i][splitTag[0]] = splitTag[1]; - }); - } - - return parsedTags; -} - -/** - * Modifies the parsed connection string object taking into account expectations we - * have for authentication-related options. - * - * @param {object} parsed The parsed connection string result - * @return The parsed connection string result possibly modified for auth expectations - */ -function applyAuthExpectations(parsed) { - if (parsed.options == null) { - return; - } - - const options = parsed.options; - const authSource = options.authsource || options.authSource; - if (authSource != null) { - parsed.auth = Object.assign({}, parsed.auth, { db: authSource }); - } - - const authMechanism = options.authmechanism || options.authMechanism; - if (authMechanism != null) { - if ( - USERNAME_REQUIRED_MECHANISMS.has(authMechanism) && - (!parsed.auth || parsed.auth.username == null) - ) { - throw new MongoParseError(`Username required for mechanism \`${authMechanism}\``); - } - - if (authMechanism === 'GSSAPI') { - if (authSource != null && authSource !== '$external') { - throw new MongoParseError( - `Invalid source \`${authSource}\` for mechanism \`${authMechanism}\` specified.` - ); - } - - parsed.auth = Object.assign({}, parsed.auth, { db: '$external' }); - } - - if (authMechanism === 'MONGODB-X509') { - if (parsed.auth && parsed.auth.password != null) { - throw new MongoParseError(`Password not allowed for mechanism \`${authMechanism}\``); - } - - if (authSource != null && authSource !== '$external') { - throw new MongoParseError( - `Invalid source \`${authSource}\` for mechanism \`${authMechanism}\` specified.` - ); - } - - parsed.auth = Object.assign({}, parsed.auth, { db: '$external' }); - } - - if (authMechanism === 'PLAIN') { - if (parsed.auth && parsed.auth.db == null) { - parsed.auth = Object.assign({}, parsed.auth, { db: '$external' }); - } - } - } - - // default to `admin` if nothing else was resolved - if (parsed.auth && parsed.auth.db == null) { - parsed.auth = Object.assign({}, parsed.auth, { db: 'admin' }); - } - - return parsed; -} - -/** - * Parses a query string according the connection string spec. - * - * @param {String} query The query string to parse - * @param {object} [options] The options used for options parsing - * @return {Object|Error} The parsed query string as an object, or an error if one was encountered - */ -function parseQueryString(query, options) { - const result = {}; - let parsedQueryString = qs.parse(query); - - checkTLSOptions(parsedQueryString); - - for (const key in parsedQueryString) { - const value = parsedQueryString[key]; - if (value === '' || value == null) { - throw new MongoParseError('Incomplete key value pair for option'); - } - - const normalizedKey = key.toLowerCase(); - const parsedValue = parseQueryStringItemValue(normalizedKey, value); - applyConnectionStringOption(result, normalizedKey, parsedValue, options); - } - - // special cases for known deprecated options - if (result.wtimeout && result.wtimeoutms) { - delete result.wtimeout; - console.warn('Unsupported option `wtimeout` specified'); - } - - return Object.keys(result).length ? result : null; -} - -/** - * Checks a query string for invalid tls options according to the URI options spec. - * - * @param {string} queryString The query string to check - * @throws {MongoParseError} - */ -function checkTLSOptions(queryString) { - const queryStringKeys = Object.keys(queryString); - if ( - queryStringKeys.indexOf('tlsInsecure') !== -1 && - (queryStringKeys.indexOf('tlsAllowInvalidCertificates') !== -1 || - queryStringKeys.indexOf('tlsAllowInvalidHostnames') !== -1) - ) { - throw new MongoParseError( - 'The `tlsInsecure` option cannot be used with `tlsAllowInvalidCertificates` or `tlsAllowInvalidHostnames`.' - ); - } - - const tlsValue = assertTlsOptionsAreEqual('tls', queryString, queryStringKeys); - const sslValue = assertTlsOptionsAreEqual('ssl', queryString, queryStringKeys); - - if (tlsValue != null && sslValue != null) { - if (tlsValue !== sslValue) { - throw new MongoParseError('All values of `tls` and `ssl` must be the same.'); - } - } -} - -/** - * Checks a query string to ensure all tls/ssl options are the same. - * - * @param {string} key The key (tls or ssl) to check - * @param {string} queryString The query string to check - * @throws {MongoParseError} - * @return The value of the tls/ssl option - */ -function assertTlsOptionsAreEqual(optionName, queryString, queryStringKeys) { - const queryStringHasTLSOption = queryStringKeys.indexOf(optionName) !== -1; - - let optionValue; - if (Array.isArray(queryString[optionName])) { - optionValue = queryString[optionName][0]; - } else { - optionValue = queryString[optionName]; - } - - if (queryStringHasTLSOption) { - if (Array.isArray(queryString[optionName])) { - const firstValue = queryString[optionName][0]; - queryString[optionName].forEach(tlsValue => { - if (tlsValue !== firstValue) { - throw new MongoParseError('All values of ${optionName} must be the same.'); - } - }); - } - } - - return optionValue; -} - -const PROTOCOL_MONGODB = 'mongodb'; -const PROTOCOL_MONGODB_SRV = 'mongodb+srv'; -const SUPPORTED_PROTOCOLS = [PROTOCOL_MONGODB, PROTOCOL_MONGODB_SRV]; - -/** - * Parses a MongoDB connection string - * - * @param {*} uri the MongoDB connection string to parse - * @param {object} [options] Optional settings. - * @param {boolean} [options.caseTranslate] Whether the parser should translate options back into camelCase after normalization - * @param {parseCallback} callback - */ -function parseConnectionString(uri, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = Object.assign({}, { caseTranslate: true }, options); - - // Check for bad uris before we parse - try { - URL.parse(uri); - } catch (e) { - return callback(new MongoParseError('URI malformed, cannot be parsed')); - } - - const cap = uri.match(HOSTS_RX); - if (!cap) { - return callback(new MongoParseError('Invalid connection string')); - } - - const protocol = cap[1]; - if (SUPPORTED_PROTOCOLS.indexOf(protocol) === -1) { - return callback(new MongoParseError('Invalid protocol provided')); - } - - if (protocol === PROTOCOL_MONGODB_SRV) { - return parseSrvConnectionString(uri, options, callback); - } - - const dbAndQuery = cap[4].split('?'); - const db = dbAndQuery.length > 0 ? dbAndQuery[0] : null; - const query = dbAndQuery.length > 1 ? dbAndQuery[1] : null; - - let parsedOptions; - try { - parsedOptions = parseQueryString(query, options); - } catch (parseError) { - return callback(parseError); - } - - parsedOptions = Object.assign({}, parsedOptions, options); - const auth = { username: null, password: null, db: db && db !== '' ? qs.unescape(db) : null }; - if (parsedOptions.auth) { - // maintain support for legacy options passed into `MongoClient` - if (parsedOptions.auth.username) auth.username = parsedOptions.auth.username; - if (parsedOptions.auth.user) auth.username = parsedOptions.auth.user; - if (parsedOptions.auth.password) auth.password = parsedOptions.auth.password; - } else { - if (parsedOptions.username) auth.username = parsedOptions.username; - if (parsedOptions.user) auth.username = parsedOptions.user; - if (parsedOptions.password) auth.password = parsedOptions.password; - } - - if (cap[4].split('?')[0].indexOf('@') !== -1) { - return callback(new MongoParseError('Unescaped slash in userinfo section')); - } - - const authorityParts = cap[3].split('@'); - if (authorityParts.length > 2) { - return callback(new MongoParseError('Unescaped at-sign in authority section')); - } - - if (authorityParts.length > 1) { - const authParts = authorityParts.shift().split(':'); - if (authParts.length > 2) { - return callback(new MongoParseError('Unescaped colon in authority section')); - } - - if (!auth.username) auth.username = qs.unescape(authParts[0]); - if (!auth.password) auth.password = authParts[1] ? qs.unescape(authParts[1]) : null; - } - - let hostParsingError = null; - const hosts = authorityParts - .shift() - .split(',') - .map(host => { - let parsedHost = URL.parse(`mongodb://${host}`); - if (parsedHost.path === '/:') { - hostParsingError = new MongoParseError('Double colon in host identifier'); - return null; - } - - // heuristically determine if we're working with a domain socket - if (host.match(/\.sock/)) { - parsedHost.hostname = qs.unescape(host); - parsedHost.port = null; - } - - if (Number.isNaN(parsedHost.port)) { - hostParsingError = new MongoParseError('Invalid port (non-numeric string)'); - return; - } - - const result = { - host: parsedHost.hostname, - port: parsedHost.port ? parseInt(parsedHost.port) : 27017 - }; - - if (result.port === 0) { - hostParsingError = new MongoParseError('Invalid port (zero) with hostname'); - return; - } - - if (result.port > 65535) { - hostParsingError = new MongoParseError('Invalid port (larger than 65535) with hostname'); - return; - } - - if (result.port < 0) { - hostParsingError = new MongoParseError('Invalid port (negative number)'); - return; - } - - return result; - }) - .filter(host => !!host); - - if (hostParsingError) { - return callback(hostParsingError); - } - - if (hosts.length === 0 || hosts[0].host === '' || hosts[0].host === null) { - return callback(new MongoParseError('No hostname or hostnames provided in connection string')); - } - - const result = { - hosts: hosts, - auth: auth.db || auth.username ? auth : null, - options: Object.keys(parsedOptions).length ? parsedOptions : null - }; - - if (result.auth && result.auth.db) { - result.defaultDatabase = result.auth.db; - } else { - result.defaultDatabase = 'test'; - } - - try { - applyAuthExpectations(result); - } catch (authError) { - return callback(authError); - } - - callback(null, result); -} - -module.exports = parseConnectionString; diff --git a/scripts/node_modules/mongodb/lib/core/utils.js b/scripts/node_modules/mongodb/lib/core/utils.js deleted file mode 100644 index 7581bf25..00000000 --- a/scripts/node_modules/mongodb/lib/core/utils.js +++ /dev/null @@ -1,177 +0,0 @@ -'use strict'; - -const crypto = require('crypto'); -const requireOptional = require('require_optional'); - -/** - * Generate a UUIDv4 - */ -const uuidV4 = () => { - const result = crypto.randomBytes(16); - result[6] = (result[6] & 0x0f) | 0x40; - result[8] = (result[8] & 0x3f) | 0x80; - return result; -}; - -/** - * Returns the duration calculated from two high resolution timers in milliseconds - * - * @param {Object} started A high resolution timestamp created from `process.hrtime()` - * @returns {Number} The duration in milliseconds - */ -const calculateDurationInMs = started => { - const hrtime = process.hrtime(started); - return (hrtime[0] * 1e9 + hrtime[1]) / 1e6; -}; - -/** - * Relays events for a given listener and emitter - * - * @param {EventEmitter} listener the EventEmitter to listen to the events from - * @param {EventEmitter} emitter the EventEmitter to relay the events to - */ -function relayEvents(listener, emitter, events) { - events.forEach(eventName => listener.on(eventName, event => emitter.emit(eventName, event))); -} - -function retrieveKerberos() { - let kerberos; - - try { - kerberos = requireOptional('kerberos'); - } catch (err) { - if (err.code === 'MODULE_NOT_FOUND') { - throw new Error('The `kerberos` module was not found. Please install it and try again.'); - } - - throw err; - } - - return kerberos; -} - -// Throw an error if an attempt to use EJSON is made when it is not installed -const noEJSONError = function() { - throw new Error('The `mongodb-extjson` module was not found. Please install it and try again.'); -}; - -// Facilitate loading EJSON optionally -function retrieveEJSON() { - let EJSON = null; - try { - EJSON = requireOptional('mongodb-extjson'); - } catch (error) {} // eslint-disable-line - if (!EJSON) { - EJSON = { - parse: noEJSONError, - deserialize: noEJSONError, - serialize: noEJSONError, - stringify: noEJSONError, - setBSONModule: noEJSONError, - BSON: noEJSONError - }; - } - - return EJSON; -} - -/** - * A helper function for determining `maxWireVersion` between legacy and new topology - * instances - * - * @private - * @param {(Topology|Server)} topologyOrServer - */ -function maxWireVersion(topologyOrServer) { - if (topologyOrServer.ismaster) { - return topologyOrServer.ismaster.maxWireVersion; - } - - if (typeof topologyOrServer.lastIsMaster === 'function') { - const lastIsMaster = topologyOrServer.lastIsMaster(); - if (lastIsMaster) { - return lastIsMaster.maxWireVersion; - } - } - - if (topologyOrServer.description) { - return topologyOrServer.description.maxWireVersion; - } - - return null; -} - -/* - * Checks that collation is supported by server. - * - * @param {Server} [server] to check against - * @param {object} [cmd] object where collation may be specified - * @param {function} [callback] callback function - * @return true if server does not support collation - */ -function collationNotSupported(server, cmd) { - return cmd && cmd.collation && maxWireVersion(server) < 5; -} - -/** - * Checks if a given value is a Promise - * - * @param {*} maybePromise - * @return true if the provided value is a Promise - */ -function isPromiseLike(maybePromise) { - return maybePromise && typeof maybePromise.then === 'function'; -} - -/** - * Applies the function `eachFn` to each item in `arr`, in parallel. - * - * @param {array} arr an array of items to asynchronusly iterate over - * @param {function} eachFn A function to call on each item of the array. The callback signature is `(item, callback)`, where the callback indicates iteration is complete. - * @param {function} callback The callback called after every item has been iterated - */ -function eachAsync(arr, eachFn, callback) { - if (arr.length === 0) { - callback(null); - return; - } - - const length = arr.length; - let completed = 0; - function eachCallback(err) { - if (err) { - callback(err, null); - return; - } - - if (++completed === length) { - callback(null); - } - } - - for (let idx = 0; idx < length; ++idx) { - try { - eachFn(arr[idx], eachCallback); - } catch (err) { - callback(err); - return; - } - } -} - -function isUnifiedTopology(topology) { - return topology.description != null; -} - -module.exports = { - uuidV4, - calculateDurationInMs, - relayEvents, - collationNotSupported, - retrieveEJSON, - retrieveKerberos, - maxWireVersion, - isPromiseLike, - eachAsync, - isUnifiedTopology -}; diff --git a/scripts/node_modules/mongodb/lib/core/wireprotocol/command.js b/scripts/node_modules/mongodb/lib/core/wireprotocol/command.js deleted file mode 100644 index 47107c62..00000000 --- a/scripts/node_modules/mongodb/lib/core/wireprotocol/command.js +++ /dev/null @@ -1,170 +0,0 @@ -'use strict'; - -const Query = require('../connection/commands').Query; -const Msg = require('../connection/msg').Msg; -const MongoError = require('../error').MongoError; -const getReadPreference = require('./shared').getReadPreference; -const isSharded = require('./shared').isSharded; -const databaseNamespace = require('./shared').databaseNamespace; -const isTransactionCommand = require('../transactions').isTransactionCommand; -const applySession = require('../sessions').applySession; - -function isClientEncryptionEnabled(server) { - return server.autoEncrypter; -} - -function command(server, ns, cmd, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - if (cmd == null) { - return callback(new MongoError(`command ${JSON.stringify(cmd)} does not return a cursor`)); - } - - if (!isClientEncryptionEnabled(server)) { - _command(server, ns, cmd, options, callback); - return; - } - - _cryptCommand(server, ns, cmd, options, callback); -} - -function _command(server, ns, cmd, options, callback) { - const bson = server.s.bson; - const pool = server.s.pool; - const readPreference = getReadPreference(cmd, options); - const shouldUseOpMsg = supportsOpMsg(server); - const session = options.session; - - let clusterTime = server.clusterTime; - let finalCmd = Object.assign({}, cmd); - if (hasSessionSupport(server) && session) { - if ( - session.clusterTime && - session.clusterTime.clusterTime.greaterThan(clusterTime.clusterTime) - ) { - clusterTime = session.clusterTime; - } - - const err = applySession(session, finalCmd, options); - if (err) { - return callback(err); - } - } - - // if we have a known cluster time, gossip it - if (clusterTime) { - finalCmd.$clusterTime = clusterTime; - } - - if ( - isSharded(server) && - !shouldUseOpMsg && - readPreference && - readPreference.preference !== 'primary' - ) { - finalCmd = { - $query: finalCmd, - $readPreference: readPreference.toJSON() - }; - } - - const commandOptions = Object.assign( - { - command: true, - numberToSkip: 0, - numberToReturn: -1, - checkKeys: false - }, - options - ); - - // This value is not overridable - commandOptions.slaveOk = readPreference.slaveOk(); - - const cmdNs = `${databaseNamespace(ns)}.$cmd`; - const message = shouldUseOpMsg - ? new Msg(bson, cmdNs, finalCmd, commandOptions) - : new Query(bson, cmdNs, finalCmd, commandOptions); - - const inTransaction = session && (session.inTransaction() || isTransactionCommand(finalCmd)); - const commandResponseHandler = inTransaction - ? function(err) { - if ( - !cmd.commitTransaction && - err && - err instanceof MongoError && - err.hasErrorLabel('TransientTransactionError') - ) { - session.transaction.unpinServer(); - } - - return callback.apply(null, arguments); - } - : callback; - - try { - pool.write(message, commandOptions, commandResponseHandler); - } catch (err) { - commandResponseHandler(err); - } -} - -function hasSessionSupport(topology) { - if (topology == null) return false; - if (topology.description) { - return topology.description.maxWireVersion >= 6; - } - - return topology.ismaster == null ? false : topology.ismaster.maxWireVersion >= 6; -} - -function supportsOpMsg(topologyOrServer) { - const description = topologyOrServer.ismaster - ? topologyOrServer.ismaster - : topologyOrServer.description; - - if (description == null) { - return false; - } - - return description.maxWireVersion >= 6 && description.__nodejs_mock_server__ == null; -} - -function _cryptCommand(server, ns, cmd, options, callback) { - const shouldBypassAutoEncryption = !!server.s.options.bypassAutoEncryption; - const autoEncrypter = server.autoEncrypter; - function commandResponseHandler(err, response) { - if (err || response == null) { - callback(err, response); - return; - } - - autoEncrypter.decrypt(response.result, (err, decrypted) => { - if (err) { - callback(err, null); - return; - } - - response.result = decrypted; - response.message.documents = [decrypted]; - callback(null, response); - }); - } - - if (shouldBypassAutoEncryption) { - _command(server, ns, cmd, options, commandResponseHandler); - return; - } - - autoEncrypter.encrypt(ns, cmd, (err, encrypted) => { - if (err) { - callback(err, null); - return; - } - - _command(server, ns, encrypted, options, commandResponseHandler); - }); -} - -module.exports = command; diff --git a/scripts/node_modules/mongodb/lib/core/wireprotocol/compression.js b/scripts/node_modules/mongodb/lib/core/wireprotocol/compression.js deleted file mode 100644 index 4b908e63..00000000 --- a/scripts/node_modules/mongodb/lib/core/wireprotocol/compression.js +++ /dev/null @@ -1,73 +0,0 @@ -'use strict'; - -var Snappy = require('../connection/utils').retrieveSnappy(), - zlib = require('zlib'); - -var compressorIDs = { - snappy: 1, - zlib: 2 -}; - -var uncompressibleCommands = [ - 'ismaster', - 'saslStart', - 'saslContinue', - 'getnonce', - 'authenticate', - 'createUser', - 'updateUser', - 'copydbSaslStart', - 'copydbgetnonce', - 'copydb' -]; - -// Facilitate compressing a message using an agreed compressor -var compress = function(self, dataToBeCompressed, callback) { - switch (self.options.agreedCompressor) { - case 'snappy': - Snappy.compress(dataToBeCompressed, callback); - break; - case 'zlib': - // Determine zlibCompressionLevel - var zlibOptions = {}; - if (self.options.zlibCompressionLevel) { - zlibOptions.level = self.options.zlibCompressionLevel; - } - zlib.deflate(dataToBeCompressed, zlibOptions, callback); - break; - default: - throw new Error( - 'Attempt to compress message using unknown compressor "' + - self.options.agreedCompressor + - '".' - ); - } -}; - -// Decompress a message using the given compressor -var decompress = function(compressorID, compressedData, callback) { - if (compressorID < 0 || compressorID > compressorIDs.length) { - throw new Error( - 'Server sent message compressed using an unsupported compressor. (Received compressor ID ' + - compressorID + - ')' - ); - } - switch (compressorID) { - case compressorIDs.snappy: - Snappy.uncompress(compressedData, callback); - break; - case compressorIDs.zlib: - zlib.inflate(compressedData, callback); - break; - default: - callback(null, compressedData); - } -}; - -module.exports = { - compressorIDs: compressorIDs, - uncompressibleCommands: uncompressibleCommands, - compress: compress, - decompress: decompress -}; diff --git a/scripts/node_modules/mongodb/lib/core/wireprotocol/constants.js b/scripts/node_modules/mongodb/lib/core/wireprotocol/constants.js deleted file mode 100644 index df2293b5..00000000 --- a/scripts/node_modules/mongodb/lib/core/wireprotocol/constants.js +++ /dev/null @@ -1,13 +0,0 @@ -'use strict'; - -const MIN_SUPPORTED_SERVER_VERSION = '2.6'; -const MAX_SUPPORTED_SERVER_VERSION = '4.2'; -const MIN_SUPPORTED_WIRE_VERSION = 2; -const MAX_SUPPORTED_WIRE_VERSION = 8; - -module.exports = { - MIN_SUPPORTED_SERVER_VERSION, - MAX_SUPPORTED_SERVER_VERSION, - MIN_SUPPORTED_WIRE_VERSION, - MAX_SUPPORTED_WIRE_VERSION -}; diff --git a/scripts/node_modules/mongodb/lib/core/wireprotocol/get_more.js b/scripts/node_modules/mongodb/lib/core/wireprotocol/get_more.js deleted file mode 100644 index b2db3202..00000000 --- a/scripts/node_modules/mongodb/lib/core/wireprotocol/get_more.js +++ /dev/null @@ -1,90 +0,0 @@ -'use strict'; - -const GetMore = require('../connection/commands').GetMore; -const retrieveBSON = require('../connection/utils').retrieveBSON; -const MongoError = require('../error').MongoError; -const MongoNetworkError = require('../error').MongoNetworkError; -const BSON = retrieveBSON(); -const Long = BSON.Long; -const collectionNamespace = require('./shared').collectionNamespace; -const maxWireVersion = require('../utils').maxWireVersion; -const applyCommonQueryOptions = require('./shared').applyCommonQueryOptions; -const command = require('./command'); - -function getMore(server, ns, cursorState, batchSize, options, callback) { - options = options || {}; - - const wireVersion = maxWireVersion(server); - function queryCallback(err, result) { - if (err) return callback(err); - const response = result.message; - - // If we have a timed out query or a cursor that was killed - if (response.cursorNotFound) { - return callback(new MongoNetworkError('cursor killed or timed out'), null); - } - - if (wireVersion < 4) { - const cursorId = - typeof response.cursorId === 'number' - ? Long.fromNumber(response.cursorId) - : response.cursorId; - - cursorState.documents = response.documents; - cursorState.cursorId = cursorId; - - callback(null, null, response.connection); - return; - } - - // We have an error detected - if (response.documents[0].ok === 0) { - return callback(new MongoError(response.documents[0])); - } - - // Ensure we have a Long valid cursor id - const cursorId = - typeof response.documents[0].cursor.id === 'number' - ? Long.fromNumber(response.documents[0].cursor.id) - : response.documents[0].cursor.id; - - cursorState.documents = response.documents[0].cursor.nextBatch; - cursorState.cursorId = cursorId; - - callback(null, response.documents[0], response.connection); - } - - if (wireVersion < 4) { - const bson = server.s.bson; - const getMoreOp = new GetMore(bson, ns, cursorState.cursorId, { numberToReturn: batchSize }); - const queryOptions = applyCommonQueryOptions({}, cursorState); - server.s.pool.write(getMoreOp, queryOptions, queryCallback); - return; - } - - const getMoreCmd = { - getMore: cursorState.cursorId, - collection: collectionNamespace(ns), - batchSize: Math.abs(batchSize) - }; - - if (cursorState.cmd.tailable && typeof cursorState.cmd.maxAwaitTimeMS === 'number') { - getMoreCmd.maxTimeMS = cursorState.cmd.maxAwaitTimeMS; - } - - const commandOptions = Object.assign( - { - returnFieldSelector: null, - documentsReturnedIn: 'nextBatch' - }, - options - ); - - if (cursorState.session) { - commandOptions.session = cursorState.session; - } - - command(server, ns, getMoreCmd, commandOptions, queryCallback); -} - -module.exports = getMore; diff --git a/scripts/node_modules/mongodb/lib/core/wireprotocol/index.js b/scripts/node_modules/mongodb/lib/core/wireprotocol/index.js deleted file mode 100644 index b6ffda7c..00000000 --- a/scripts/node_modules/mongodb/lib/core/wireprotocol/index.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; -const writeCommand = require('./write_command'); - -module.exports = { - insert: function insert(server, ns, ops, options, callback) { - writeCommand(server, 'insert', 'documents', ns, ops, options, callback); - }, - update: function update(server, ns, ops, options, callback) { - writeCommand(server, 'update', 'updates', ns, ops, options, callback); - }, - remove: function remove(server, ns, ops, options, callback) { - writeCommand(server, 'delete', 'deletes', ns, ops, options, callback); - }, - killCursors: require('./kill_cursors'), - getMore: require('./get_more'), - query: require('./query'), - command: require('./command') -}; diff --git a/scripts/node_modules/mongodb/lib/core/wireprotocol/kill_cursors.js b/scripts/node_modules/mongodb/lib/core/wireprotocol/kill_cursors.js deleted file mode 100644 index bb134773..00000000 --- a/scripts/node_modules/mongodb/lib/core/wireprotocol/kill_cursors.js +++ /dev/null @@ -1,70 +0,0 @@ -'use strict'; - -const KillCursor = require('../connection/commands').KillCursor; -const MongoError = require('../error').MongoError; -const MongoNetworkError = require('../error').MongoNetworkError; -const collectionNamespace = require('./shared').collectionNamespace; -const maxWireVersion = require('../utils').maxWireVersion; -const command = require('./command'); - -function killCursors(server, ns, cursorState, callback) { - callback = typeof callback === 'function' ? callback : () => {}; - const cursorId = cursorState.cursorId; - - if (maxWireVersion(server) < 4) { - const bson = server.s.bson; - const pool = server.s.pool; - const killCursor = new KillCursor(bson, ns, [cursorId]); - const options = { - immediateRelease: true, - noResponse: true - }; - - if (typeof cursorState.session === 'object') { - options.session = cursorState.session; - } - - if (pool && pool.isConnected()) { - try { - pool.write(killCursor, options, callback); - } catch (err) { - if (typeof callback === 'function') { - callback(err, null); - } else { - console.warn(err); - } - } - } - - return; - } - - const killCursorCmd = { - killCursors: collectionNamespace(ns), - cursors: [cursorId] - }; - - const options = {}; - if (typeof cursorState.session === 'object') options.session = cursorState.session; - - command(server, ns, killCursorCmd, options, (err, result) => { - if (err) { - return callback(err); - } - - const response = result.message; - if (response.cursorNotFound) { - return callback(new MongoNetworkError('cursor killed or timed out'), null); - } - - if (!Array.isArray(response.documents) || response.documents.length === 0) { - return callback( - new MongoError(`invalid killCursors result returned for cursor id ${cursorId}`) - ); - } - - callback(null, response.documents[0]); - }); -} - -module.exports = killCursors; diff --git a/scripts/node_modules/mongodb/lib/core/wireprotocol/query.js b/scripts/node_modules/mongodb/lib/core/wireprotocol/query.js deleted file mode 100644 index c501b506..00000000 --- a/scripts/node_modules/mongodb/lib/core/wireprotocol/query.js +++ /dev/null @@ -1,231 +0,0 @@ -'use strict'; - -const Query = require('../connection/commands').Query; -const MongoError = require('../error').MongoError; -const getReadPreference = require('./shared').getReadPreference; -const collectionNamespace = require('./shared').collectionNamespace; -const isSharded = require('./shared').isSharded; -const maxWireVersion = require('../utils').maxWireVersion; -const applyCommonQueryOptions = require('./shared').applyCommonQueryOptions; -const command = require('./command'); - -function query(server, ns, cmd, cursorState, options, callback) { - options = options || {}; - if (cursorState.cursorId != null) { - return callback(); - } - - if (cmd == null) { - return callback(new MongoError(`command ${JSON.stringify(cmd)} does not return a cursor`)); - } - - if (maxWireVersion(server) < 4) { - const query = prepareLegacyFindQuery(server, ns, cmd, cursorState, options); - const queryOptions = applyCommonQueryOptions({}, cursorState); - if (typeof query.documentsReturnedIn === 'string') { - queryOptions.documentsReturnedIn = query.documentsReturnedIn; - } - - server.s.pool.write(query, queryOptions, callback); - return; - } - - const readPreference = getReadPreference(cmd, options); - const findCmd = prepareFindCommand(server, ns, cmd, cursorState, options); - - // NOTE: This actually modifies the passed in cmd, and our code _depends_ on this - // side-effect. Change this ASAP - cmd.virtual = false; - - const commandOptions = Object.assign( - { - documentsReturnedIn: 'firstBatch', - numberToReturn: 1, - slaveOk: readPreference.slaveOk() - }, - options - ); - - if (cmd.readPreference) { - commandOptions.readPreference = readPreference; - } - - if (cursorState.session) { - commandOptions.session = cursorState.session; - } - - command(server, ns, findCmd, commandOptions, callback); -} - -function prepareFindCommand(server, ns, cmd, cursorState) { - cursorState.batchSize = cmd.batchSize || cursorState.batchSize; - let findCmd = { - find: collectionNamespace(ns) - }; - - if (cmd.query) { - if (cmd.query['$query']) { - findCmd.filter = cmd.query['$query']; - } else { - findCmd.filter = cmd.query; - } - } - - let sortValue = cmd.sort; - if (Array.isArray(sortValue)) { - const sortObject = {}; - - if (sortValue.length > 0 && !Array.isArray(sortValue[0])) { - let sortDirection = sortValue[1]; - if (sortDirection === 'asc') { - sortDirection = 1; - } else if (sortDirection === 'desc') { - sortDirection = -1; - } - - sortObject[sortValue[0]] = sortDirection; - } else { - for (let i = 0; i < sortValue.length; i++) { - let sortDirection = sortValue[i][1]; - if (sortDirection === 'asc') { - sortDirection = 1; - } else if (sortDirection === 'desc') { - sortDirection = -1; - } - - sortObject[sortValue[i][0]] = sortDirection; - } - } - - sortValue = sortObject; - } - - if (cmd.sort) findCmd.sort = sortValue; - if (cmd.fields) findCmd.projection = cmd.fields; - if (cmd.hint) findCmd.hint = cmd.hint; - if (cmd.skip) findCmd.skip = cmd.skip; - if (cmd.limit) findCmd.limit = cmd.limit; - if (cmd.limit < 0) { - findCmd.limit = Math.abs(cmd.limit); - findCmd.singleBatch = true; - } - - if (typeof cmd.batchSize === 'number') { - if (cmd.batchSize < 0) { - if (cmd.limit !== 0 && Math.abs(cmd.batchSize) < Math.abs(cmd.limit)) { - findCmd.limit = Math.abs(cmd.batchSize); - } - - findCmd.singleBatch = true; - } - - findCmd.batchSize = Math.abs(cmd.batchSize); - } - - if (cmd.comment) findCmd.comment = cmd.comment; - if (cmd.maxScan) findCmd.maxScan = cmd.maxScan; - if (cmd.maxTimeMS) findCmd.maxTimeMS = cmd.maxTimeMS; - if (cmd.min) findCmd.min = cmd.min; - if (cmd.max) findCmd.max = cmd.max; - findCmd.returnKey = cmd.returnKey ? cmd.returnKey : false; - findCmd.showRecordId = cmd.showDiskLoc ? cmd.showDiskLoc : false; - if (cmd.snapshot) findCmd.snapshot = cmd.snapshot; - if (cmd.tailable) findCmd.tailable = cmd.tailable; - if (cmd.oplogReplay) findCmd.oplogReplay = cmd.oplogReplay; - if (cmd.noCursorTimeout) findCmd.noCursorTimeout = cmd.noCursorTimeout; - if (cmd.awaitData) findCmd.awaitData = cmd.awaitData; - if (cmd.awaitdata) findCmd.awaitData = cmd.awaitdata; - if (cmd.partial) findCmd.partial = cmd.partial; - if (cmd.collation) findCmd.collation = cmd.collation; - if (cmd.readConcern) findCmd.readConcern = cmd.readConcern; - - // If we have explain, we need to rewrite the find command - // to wrap it in the explain command - if (cmd.explain) { - findCmd = { - explain: findCmd - }; - } - - return findCmd; -} - -function prepareLegacyFindQuery(server, ns, cmd, cursorState, options) { - options = options || {}; - const bson = server.s.bson; - const readPreference = getReadPreference(cmd, options); - cursorState.batchSize = cmd.batchSize || cursorState.batchSize; - - let numberToReturn = 0; - if ( - cursorState.limit < 0 || - (cursorState.limit !== 0 && cursorState.limit < cursorState.batchSize) || - (cursorState.limit > 0 && cursorState.batchSize === 0) - ) { - numberToReturn = cursorState.limit; - } else { - numberToReturn = cursorState.batchSize; - } - - const numberToSkip = cursorState.skip || 0; - - const findCmd = {}; - if (isSharded(server) && readPreference) { - findCmd['$readPreference'] = readPreference.toJSON(); - } - - if (cmd.sort) findCmd['$orderby'] = cmd.sort; - if (cmd.hint) findCmd['$hint'] = cmd.hint; - if (cmd.snapshot) findCmd['$snapshot'] = cmd.snapshot; - if (typeof cmd.returnKey !== 'undefined') findCmd['$returnKey'] = cmd.returnKey; - if (cmd.maxScan) findCmd['$maxScan'] = cmd.maxScan; - if (cmd.min) findCmd['$min'] = cmd.min; - if (cmd.max) findCmd['$max'] = cmd.max; - if (typeof cmd.showDiskLoc !== 'undefined') findCmd['$showDiskLoc'] = cmd.showDiskLoc; - if (cmd.comment) findCmd['$comment'] = cmd.comment; - if (cmd.maxTimeMS) findCmd['$maxTimeMS'] = cmd.maxTimeMS; - if (cmd.explain) { - // nToReturn must be 0 (match all) or negative (match N and close cursor) - // nToReturn > 0 will give explain results equivalent to limit(0) - numberToReturn = -Math.abs(cmd.limit || 0); - findCmd['$explain'] = true; - } - - findCmd['$query'] = cmd.query; - if (cmd.readConcern && cmd.readConcern.level !== 'local') { - throw new MongoError( - `server find command does not support a readConcern level of ${cmd.readConcern.level}` - ); - } - - if (cmd.readConcern) { - cmd = Object.assign({}, cmd); - delete cmd['readConcern']; - } - - const serializeFunctions = - typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; - const ignoreUndefined = - typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : false; - - const query = new Query(bson, ns, findCmd, { - numberToSkip: numberToSkip, - numberToReturn: numberToReturn, - pre32Limit: typeof cmd.limit !== 'undefined' ? cmd.limit : undefined, - checkKeys: false, - returnFieldSelector: cmd.fields, - serializeFunctions: serializeFunctions, - ignoreUndefined: ignoreUndefined - }); - - if (typeof cmd.tailable === 'boolean') query.tailable = cmd.tailable; - if (typeof cmd.oplogReplay === 'boolean') query.oplogReplay = cmd.oplogReplay; - if (typeof cmd.noCursorTimeout === 'boolean') query.noCursorTimeout = cmd.noCursorTimeout; - if (typeof cmd.awaitData === 'boolean') query.awaitData = cmd.awaitData; - if (typeof cmd.partial === 'boolean') query.partial = cmd.partial; - - query.slaveOk = readPreference.slaveOk(); - return query; -} - -module.exports = query; diff --git a/scripts/node_modules/mongodb/lib/core/wireprotocol/shared.js b/scripts/node_modules/mongodb/lib/core/wireprotocol/shared.js deleted file mode 100644 index 2574aade..00000000 --- a/scripts/node_modules/mongodb/lib/core/wireprotocol/shared.js +++ /dev/null @@ -1,115 +0,0 @@ -'use strict'; - -const ReadPreference = require('../topologies/read_preference'); -const MongoError = require('../error').MongoError; -const ServerType = require('../sdam/server_description').ServerType; -const TopologyDescription = require('../sdam/topology_description').TopologyDescription; - -const MESSAGE_HEADER_SIZE = 16; -const COMPRESSION_DETAILS_SIZE = 9; // originalOpcode + uncompressedSize, compressorID - -// OPCODE Numbers -// Defined at https://docs.mongodb.com/manual/reference/mongodb-wire-protocol/#request-opcodes -var opcodes = { - OP_REPLY: 1, - OP_UPDATE: 2001, - OP_INSERT: 2002, - OP_QUERY: 2004, - OP_GETMORE: 2005, - OP_DELETE: 2006, - OP_KILL_CURSORS: 2007, - OP_COMPRESSED: 2012, - OP_MSG: 2013 -}; - -var getReadPreference = function(cmd, options) { - // Default to command version of the readPreference - var readPreference = cmd.readPreference || new ReadPreference('primary'); - // If we have an option readPreference override the command one - if (options.readPreference) { - readPreference = options.readPreference; - } - - if (typeof readPreference === 'string') { - readPreference = new ReadPreference(readPreference); - } - - if (!(readPreference instanceof ReadPreference)) { - throw new MongoError('read preference must be a ReadPreference instance'); - } - - return readPreference; -}; - -// Parses the header of a wire protocol message -var parseHeader = function(message) { - return { - length: message.readInt32LE(0), - requestId: message.readInt32LE(4), - responseTo: message.readInt32LE(8), - opCode: message.readInt32LE(12) - }; -}; - -function applyCommonQueryOptions(queryOptions, options) { - Object.assign(queryOptions, { - raw: typeof options.raw === 'boolean' ? options.raw : false, - promoteLongs: typeof options.promoteLongs === 'boolean' ? options.promoteLongs : true, - promoteValues: typeof options.promoteValues === 'boolean' ? options.promoteValues : true, - promoteBuffers: typeof options.promoteBuffers === 'boolean' ? options.promoteBuffers : false, - monitoring: typeof options.monitoring === 'boolean' ? options.monitoring : false, - fullResult: typeof options.fullResult === 'boolean' ? options.fullResult : false - }); - - if (typeof options.socketTimeout === 'number') { - queryOptions.socketTimeout = options.socketTimeout; - } - - if (options.session) { - queryOptions.session = options.session; - } - - if (typeof options.documentsReturnedIn === 'string') { - queryOptions.documentsReturnedIn = options.documentsReturnedIn; - } - - return queryOptions; -} - -function isSharded(topologyOrServer) { - if (topologyOrServer.type === 'mongos') return true; - if (topologyOrServer.description && topologyOrServer.description.type === ServerType.Mongos) { - return true; - } - - // NOTE: This is incredibly inefficient, and should be removed once command construction - // happens based on `Server` not `Topology`. - if (topologyOrServer.description && topologyOrServer.description instanceof TopologyDescription) { - const servers = Array.from(topologyOrServer.description.servers.values()); - return servers.some(server => server.type === ServerType.Mongos); - } - - return false; -} - -function databaseNamespace(ns) { - return ns.split('.')[0]; -} -function collectionNamespace(ns) { - return ns - .split('.') - .slice(1) - .join('.'); -} - -module.exports = { - getReadPreference, - MESSAGE_HEADER_SIZE, - COMPRESSION_DETAILS_SIZE, - opcodes, - parseHeader, - applyCommonQueryOptions, - isSharded, - databaseNamespace, - collectionNamespace -}; diff --git a/scripts/node_modules/mongodb/lib/core/wireprotocol/write_command.js b/scripts/node_modules/mongodb/lib/core/wireprotocol/write_command.js deleted file mode 100644 index e334d518..00000000 --- a/scripts/node_modules/mongodb/lib/core/wireprotocol/write_command.js +++ /dev/null @@ -1,50 +0,0 @@ -'use strict'; - -const MongoError = require('../error').MongoError; -const collectionNamespace = require('./shared').collectionNamespace; -const command = require('./command'); - -function writeCommand(server, type, opsField, ns, ops, options, callback) { - if (ops.length === 0) throw new MongoError(`${type} must contain at least one document`); - if (typeof options === 'function') { - callback = options; - options = {}; - } - - options = options || {}; - const ordered = typeof options.ordered === 'boolean' ? options.ordered : true; - const writeConcern = options.writeConcern; - - const writeCommand = {}; - writeCommand[type] = collectionNamespace(ns); - writeCommand[opsField] = ops; - writeCommand.ordered = ordered; - - if (writeConcern && Object.keys(writeConcern).length > 0) { - writeCommand.writeConcern = writeConcern; - } - - if (options.collation) { - for (let i = 0; i < writeCommand[opsField].length; i++) { - if (!writeCommand[opsField][i].collation) { - writeCommand[opsField][i].collation = options.collation; - } - } - } - - if (options.bypassDocumentValidation === true) { - writeCommand.bypassDocumentValidation = options.bypassDocumentValidation; - } - - const commandOptions = Object.assign( - { - checkKeys: type === 'insert', - numberToReturn: 1 - }, - options - ); - - command(server, ns, writeCommand, commandOptions, callback); -} - -module.exports = writeCommand; diff --git a/scripts/node_modules/mongodb/lib/cursor.js b/scripts/node_modules/mongodb/lib/cursor.js deleted file mode 100644 index bed709be..00000000 --- a/scripts/node_modules/mongodb/lib/cursor.js +++ /dev/null @@ -1,1089 +0,0 @@ -'use strict'; - -const Transform = require('stream').Transform; -const PassThrough = require('stream').PassThrough; -const deprecate = require('util').deprecate; -const handleCallback = require('./utils').handleCallback; -const ReadPreference = require('./core').ReadPreference; -const MongoError = require('./core').MongoError; -const CoreCursor = require('./core/cursor').CoreCursor; -const CursorState = require('./core/cursor').CursorState; -const Map = require('./core').BSON.Map; - -const each = require('./operations/cursor_ops').each; - -const CountOperation = require('./operations/count'); -const ExplainOperation = require('./operations/explain'); -const HasNextOperation = require('./operations/has_next'); -const NextOperation = require('./operations/next'); -const ToArrayOperation = require('./operations/to_array'); - -const executeOperation = require('./operations/execute_operation'); - -/** - * @fileOverview The **Cursor** class is an internal class that embodies a cursor on MongoDB - * allowing for iteration over the results returned from the underlying query. It supports - * one by one document iteration, conversion to an array or can be iterated as a Node 4.X - * or higher stream - * - * **CURSORS Cannot directly be instantiated** - * @example - * const MongoClient = require('mongodb').MongoClient; - * const test = require('assert'); - * // Connection url - * const url = 'mongodb://localhost:27017'; - * // Database Name - * const dbName = 'test'; - * // Connect using MongoClient - * MongoClient.connect(url, function(err, client) { - * // Create a collection we want to drop later - * const col = client.db(dbName).collection('createIndexExample1'); - * // Insert a bunch of documents - * col.insert([{a:1, b:1} - * , {a:2, b:2}, {a:3, b:3} - * , {a:4, b:4}], {w:1}, function(err, result) { - * test.equal(null, err); - * // Show that duplicate records got dropped - * col.find({}).toArray(function(err, items) { - * test.equal(null, err); - * test.equal(4, items.length); - * client.close(); - * }); - * }); - * }); - */ - -/** - * Namespace provided by the code module - * @external CoreCursor - * @external Readable - */ - -// Flags allowed for cursor -const flags = ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'exhaust', 'partial']; -const fields = ['numberOfRetries', 'tailableRetryInterval']; - -/** - * Creates a new Cursor instance (INTERNAL TYPE, do not instantiate directly) - * @class Cursor - * @extends external:CoreCursor - * @extends external:Readable - * @property {string} sortValue Cursor query sort setting. - * @property {boolean} timeout Is Cursor able to time out. - * @property {ReadPreference} readPreference Get cursor ReadPreference. - * @fires Cursor#data - * @fires Cursor#end - * @fires Cursor#close - * @fires Cursor#readable - * @return {Cursor} a Cursor instance. - * @example - * Cursor cursor options. - * - * collection.find({}).project({a:1}) // Create a projection of field a - * collection.find({}).skip(1).limit(10) // Skip 1 and limit 10 - * collection.find({}).batchSize(5) // Set batchSize on cursor to 5 - * collection.find({}).filter({a:1}) // Set query on the cursor - * collection.find({}).comment('add a comment') // Add a comment to the query, allowing to correlate queries - * collection.find({}).addCursorFlag('tailable', true) // Set cursor as tailable - * collection.find({}).addCursorFlag('oplogReplay', true) // Set cursor as oplogReplay - * collection.find({}).addCursorFlag('noCursorTimeout', true) // Set cursor as noCursorTimeout - * collection.find({}).addCursorFlag('awaitData', true) // Set cursor as awaitData - * collection.find({}).addCursorFlag('partial', true) // Set cursor as partial - * collection.find({}).addQueryModifier('$orderby', {a:1}) // Set $orderby {a:1} - * collection.find({}).max(10) // Set the cursor max - * collection.find({}).maxTimeMS(1000) // Set the cursor maxTimeMS - * collection.find({}).min(100) // Set the cursor min - * collection.find({}).returnKey(true) // Set the cursor returnKey - * collection.find({}).setReadPreference(ReadPreference.PRIMARY) // Set the cursor readPreference - * collection.find({}).showRecordId(true) // Set the cursor showRecordId - * collection.find({}).sort([['a', 1]]) // Sets the sort order of the cursor query - * collection.find({}).hint('a_1') // Set the cursor hint - * - * All options are chainable, so one can do the following. - * - * collection.find({}).maxTimeMS(1000).maxScan(100).skip(1).toArray(..) - */ -class Cursor extends CoreCursor { - constructor(topology, ns, cmd, options) { - super(topology, ns, cmd, options); - if (this.operation) { - options = this.operation.options; - } - - // Tailable cursor options - const numberOfRetries = options.numberOfRetries || 5; - const tailableRetryInterval = options.tailableRetryInterval || 500; - const currentNumberOfRetries = numberOfRetries; - - // Get the promiseLibrary - const promiseLibrary = options.promiseLibrary || Promise; - - // Internal cursor state - this.s = { - // Tailable cursor options - numberOfRetries: numberOfRetries, - tailableRetryInterval: tailableRetryInterval, - currentNumberOfRetries: currentNumberOfRetries, - // State - state: CursorState.INIT, - // Promise library - promiseLibrary, - // Current doc - currentDoc: null, - // explicitlyIgnoreSession - explicitlyIgnoreSession: !!options.explicitlyIgnoreSession - }; - - // Optional ClientSession - if (!options.explicitlyIgnoreSession && options.session) { - this.cursorState.session = options.session; - } - - // Translate correctly - if (this.options.noCursorTimeout === true) { - this.addCursorFlag('noCursorTimeout', true); - } - - // Get the batchSize - let batchSize = 1000; - if (this.cmd.cursor && this.cmd.cursor.batchSize) { - batchSize = this.cmd.cursor.batchSize; - } else if (options.cursor && options.cursor.batchSize) { - batchSize = options.cursor.batchSize; - } else if (typeof options.batchSize === 'number') { - batchSize = options.batchSize; - } - - // Set the batchSize - this.setCursorBatchSize(batchSize); - } - - get readPreference() { - if (this.operation) { - return this.operation.readPreference; - } - - return this.options.readPreference; - } - - get sortValue() { - return this.cmd.sort; - } - - _initializeCursor(callback) { - if (this.operation && this.operation.session != null) { - this.cursorState.session = this.operation.session; - } else { - // implicitly create a session if one has not been provided - if ( - !this.s.explicitlyIgnoreSession && - !this.cursorState.session && - this.topology.hasSessionSupport() - ) { - this.cursorState.session = this.topology.startSession({ owner: this }); - - if (this.operation) { - this.operation.session = this.cursorState.session; - } - } - } - - super._initializeCursor(callback); - } - - /** - * Check if there is any document still available in the cursor - * @method - * @param {Cursor~resultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ - hasNext(callback) { - const hasNextOperation = new HasNextOperation(this); - - return executeOperation(this.topology, hasNextOperation, callback); - } - - /** - * Get the next available document from the cursor, returns null if no more documents are available. - * @method - * @param {Cursor~resultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ - next(callback) { - const nextOperation = new NextOperation(this); - - return executeOperation(this.topology, nextOperation, callback); - } - - /** - * Set the cursor query - * @method - * @param {object} filter The filter object used for the cursor. - * @return {Cursor} - */ - filter(filter) { - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - this.cmd.query = filter; - return this; - } - - /** - * Set the cursor maxScan - * @method - * @param {object} maxScan Constrains the query to only scan the specified number of documents when fulfilling the query - * @deprecated as of MongoDB 4.0 - * @return {Cursor} - */ - maxScan(maxScan) { - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - this.cmd.maxScan = maxScan; - return this; - } - - /** - * Set the cursor hint - * @method - * @param {object} hint If specified, then the query system will only consider plans using the hinted index. - * @return {Cursor} - */ - hint(hint) { - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - this.cmd.hint = hint; - return this; - } - - /** - * Set the cursor min - * @method - * @param {object} min Specify a $min value to specify the inclusive lower bound for a specific index in order to constrain the results of find(). The $min specifies the lower bound for all keys of a specific index in order. - * @return {Cursor} - */ - min(min) { - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - this.cmd.min = min; - return this; - } - - /** - * Set the cursor max - * @method - * @param {object} max Specify a $max value to specify the exclusive upper bound for a specific index in order to constrain the results of find(). The $max specifies the upper bound for all keys of a specific index in order. - * @return {Cursor} - */ - max(max) { - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - this.cmd.max = max; - return this; - } - - /** - * Set the cursor returnKey. If set to true, modifies the cursor to only return the index field or fields for the results of the query, rather than documents. If set to true and the query does not use an index to perform the read operation, the returned documents will not contain any fields. - * @method - * @param {bool} returnKey the returnKey value. - * @return {Cursor} - */ - returnKey(value) { - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - this.cmd.returnKey = value; - return this; - } - - /** - * Set the cursor showRecordId - * @method - * @param {object} showRecordId The $showDiskLoc option has now been deprecated and replaced with the showRecordId field. $showDiskLoc will still be accepted for OP_QUERY stye find. - * @return {Cursor} - */ - showRecordId(value) { - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - this.cmd.showDiskLoc = value; - return this; - } - - /** - * Set the cursor snapshot - * @method - * @param {object} snapshot The $snapshot operator prevents the cursor from returning a document more than once because an intervening write operation results in a move of the document. - * @deprecated as of MongoDB 4.0 - * @return {Cursor} - */ - snapshot(value) { - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - this.cmd.snapshot = value; - return this; - } - - /** - * Set a node.js specific cursor option - * @method - * @param {string} field The cursor option to set ['numberOfRetries', 'tailableRetryInterval']. - * @param {object} value The field value. - * @throws {MongoError} - * @return {Cursor} - */ - setCursorOption(field, value) { - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - if (fields.indexOf(field) === -1) { - throw MongoError.create({ - message: `option ${field} is not a supported option ${fields}`, - driver: true - }); - } - - this.s[field] = value; - if (field === 'numberOfRetries') this.s.currentNumberOfRetries = value; - return this; - } - - /** - * Add a cursor flag to the cursor - * @method - * @param {string} flag The flag to set, must be one of following ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'partial']. - * @param {boolean} value The flag boolean value. - * @throws {MongoError} - * @return {Cursor} - */ - addCursorFlag(flag, value) { - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - if (flags.indexOf(flag) === -1) { - throw MongoError.create({ - message: `flag ${flag} is not a supported flag ${flags}`, - driver: true - }); - } - - if (typeof value !== 'boolean') { - throw MongoError.create({ message: `flag ${flag} must be a boolean value`, driver: true }); - } - - this.cmd[flag] = value; - return this; - } - - /** - * Add a query modifier to the cursor query - * @method - * @param {string} name The query modifier (must start with $, such as $orderby etc) - * @param {string|boolean|number} value The modifier value. - * @throws {MongoError} - * @return {Cursor} - */ - addQueryModifier(name, value) { - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - if (name[0] !== '$') { - throw MongoError.create({ message: `${name} is not a valid query modifier`, driver: true }); - } - - // Strip of the $ - const field = name.substr(1); - // Set on the command - this.cmd[field] = value; - // Deal with the special case for sort - if (field === 'orderby') this.cmd.sort = this.cmd[field]; - return this; - } - - /** - * Add a comment to the cursor query allowing for tracking the comment in the log. - * @method - * @param {string} value The comment attached to this query. - * @throws {MongoError} - * @return {Cursor} - */ - comment(value) { - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - this.cmd.comment = value; - return this; - } - - /** - * Set a maxAwaitTimeMS on a tailing cursor query to allow to customize the timeout value for the option awaitData (Only supported on MongoDB 3.2 or higher, ignored otherwise) - * @method - * @param {number} value Number of milliseconds to wait before aborting the tailed query. - * @throws {MongoError} - * @return {Cursor} - */ - maxAwaitTimeMS(value) { - if (typeof value !== 'number') { - throw MongoError.create({ message: 'maxAwaitTimeMS must be a number', driver: true }); - } - - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - this.cmd.maxAwaitTimeMS = value; - return this; - } - - /** - * Set a maxTimeMS on the cursor query, allowing for hard timeout limits on queries (Only supported on MongoDB 2.6 or higher) - * @method - * @param {number} value Number of milliseconds to wait before aborting the query. - * @throws {MongoError} - * @return {Cursor} - */ - maxTimeMS(value) { - if (typeof value !== 'number') { - throw MongoError.create({ message: 'maxTimeMS must be a number', driver: true }); - } - - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - this.cmd.maxTimeMS = value; - return this; - } - - /** - * Sets a field projection for the query. - * @method - * @param {object} value The field projection object. - * @throws {MongoError} - * @return {Cursor} - */ - project(value) { - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - this.cmd.fields = value; - return this; - } - - /** - * Sets the sort order of the cursor query. - * @method - * @param {(string|array|object)} keyOrList The key or keys set for the sort. - * @param {number} [direction] The direction of the sorting (1 or -1). - * @throws {MongoError} - * @return {Cursor} - */ - sort(keyOrList, direction) { - if (this.options.tailable) { - throw MongoError.create({ message: "Tailable cursor doesn't support sorting", driver: true }); - } - - if (this.s.state === CursorState.CLOSED || this.s.state === CursorState.OPEN || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - let order = keyOrList; - - // We have an array of arrays, we need to preserve the order of the sort - // so we will us a Map - if (Array.isArray(order) && Array.isArray(order[0])) { - order = new Map( - order.map(x => { - const value = [x[0], null]; - if (x[1] === 'asc') { - value[1] = 1; - } else if (x[1] === 'desc') { - value[1] = -1; - } else if (x[1] === 1 || x[1] === -1 || x[1].$meta) { - value[1] = x[1]; - } else { - throw new MongoError( - "Illegal sort clause, must be of the form [['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]" - ); - } - - return value; - }) - ); - } - - if (direction != null) { - order = [[keyOrList, direction]]; - } - - this.cmd.sort = order; - return this; - } - - /** - * Set the batch size for the cursor. - * @method - * @param {number} value The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/find/|find command documentation}. - * @throws {MongoError} - * @return {Cursor} - */ - batchSize(value) { - if (this.options.tailable) { - throw MongoError.create({ - message: "Tailable cursor doesn't support batchSize", - driver: true - }); - } - - if (this.s.state === CursorState.CLOSED || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - if (typeof value !== 'number') { - throw MongoError.create({ message: 'batchSize requires an integer', driver: true }); - } - - this.cmd.batchSize = value; - this.setCursorBatchSize(value); - return this; - } - - /** - * Set the collation options for the cursor. - * @method - * @param {object} value The cursor collation options (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @throws {MongoError} - * @return {Cursor} - */ - collation(value) { - this.cmd.collation = value; - return this; - } - - /** - * Set the limit for the cursor. - * @method - * @param {number} value The limit for the cursor query. - * @throws {MongoError} - * @return {Cursor} - */ - limit(value) { - if (this.options.tailable) { - throw MongoError.create({ message: "Tailable cursor doesn't support limit", driver: true }); - } - - if (this.s.state === CursorState.OPEN || this.s.state === CursorState.CLOSED || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - if (typeof value !== 'number') { - throw MongoError.create({ message: 'limit requires an integer', driver: true }); - } - - this.cmd.limit = value; - this.setCursorLimit(value); - return this; - } - - /** - * Set the skip for the cursor. - * @method - * @param {number} value The skip for the cursor query. - * @throws {MongoError} - * @return {Cursor} - */ - skip(value) { - if (this.options.tailable) { - throw MongoError.create({ message: "Tailable cursor doesn't support skip", driver: true }); - } - - if (this.s.state === CursorState.OPEN || this.s.state === CursorState.CLOSED || this.isDead()) { - throw MongoError.create({ message: 'Cursor is closed', driver: true }); - } - - if (typeof value !== 'number') { - throw MongoError.create({ message: 'skip requires an integer', driver: true }); - } - - this.cmd.skip = value; - this.setCursorSkip(value); - return this; - } - - /** - * The callback format for results - * @callback Cursor~resultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {(object|null|boolean)} result The result object if the command was executed successfully. - */ - - /** - * Clone the cursor - * @function external:CoreCursor#clone - * @return {Cursor} - */ - - /** - * Resets the cursor - * @function external:CoreCursor#rewind - * @return {null} - */ - - /** - * Iterates over all the documents for this cursor. As with **{cursor.toArray}**, - * not all of the elements will be iterated if this cursor had been previously accessed. - * In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike - * **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements - * at any given time if batch size is specified. Otherwise, the caller is responsible - * for making sure that the entire result can fit the memory. - * @method - * @deprecated - * @param {Cursor~resultCallback} callback The result callback. - * @throws {MongoError} - * @return {null} - */ - each(callback) { - // Rewind cursor state - this.rewind(); - // Set current cursor to INIT - this.s.state = CursorState.INIT; - // Run the query - each(this, callback); - } - - /** - * The callback format for the forEach iterator method - * @callback Cursor~iteratorCallback - * @param {Object} doc An emitted document for the iterator - */ - - /** - * The callback error format for the forEach iterator method - * @callback Cursor~endCallback - * @param {MongoError} error An error instance representing the error during the execution. - */ - - /** - * Iterates over all the documents for this cursor using the iterator, callback pattern. - * @method - * @param {Cursor~iteratorCallback} iterator The iteration callback. - * @param {Cursor~endCallback} callback The end callback. - * @throws {MongoError} - * @return {Promise} if no callback supplied - */ - forEach(iterator, callback) { - // Rewind cursor state - this.rewind(); - - // Set current cursor to INIT - this.s.state = CursorState.INIT; - - if (typeof callback === 'function') { - each(this, (err, doc) => { - if (err) { - callback(err); - return false; - } - if (doc != null) { - iterator(doc); - return true; - } - if (doc == null && callback) { - const internalCallback = callback; - callback = null; - internalCallback(null); - return false; - } - }); - } else { - return new this.s.promiseLibrary((fulfill, reject) => { - each(this, (err, doc) => { - if (err) { - reject(err); - return false; - } else if (doc == null) { - fulfill(null); - return false; - } else { - iterator(doc); - return true; - } - }); - }); - } - } - - /** - * Set the ReadPreference for the cursor. - * @method - * @param {(string|ReadPreference)} readPreference The new read preference for the cursor. - * @throws {MongoError} - * @return {Cursor} - */ - setReadPreference(readPreference) { - if (this.s.state !== CursorState.INIT) { - throw MongoError.create({ - message: 'cannot change cursor readPreference after cursor has been accessed', - driver: true - }); - } - - if (readPreference instanceof ReadPreference) { - this.options.readPreference = readPreference; - } else if (typeof readPreference === 'string') { - this.options.readPreference = new ReadPreference(readPreference); - } else { - throw new TypeError('Invalid read preference: ' + readPreference); - } - - return this; - } - - /** - * The callback format for results - * @callback Cursor~toArrayResultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {object[]} documents All the documents the satisfy the cursor. - */ - - /** - * Returns an array of documents. The caller is responsible for making sure that there - * is enough memory to store the results. Note that the array only contains partial - * results when this cursor had been previously accessed. In that case, - * cursor.rewind() can be used to reset the cursor. - * @method - * @param {Cursor~toArrayResultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ - toArray(callback) { - if (this.options.tailable) { - throw MongoError.create({ - message: 'Tailable cursor cannot be converted to array', - driver: true - }); - } - - const toArrayOperation = new ToArrayOperation(this); - - return executeOperation(this.topology, toArrayOperation, callback); - } - - /** - * The callback format for results - * @callback Cursor~countResultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {number} count The count of documents. - */ - - /** - * Get the count of documents for this cursor - * @method - * @param {boolean} [applySkipLimit=true] Should the count command apply limit and skip settings on the cursor or in the passed in options. - * @param {object} [options] Optional settings. - * @param {number} [options.skip] The number of documents to skip. - * @param {number} [options.limit] The maximum amounts to count before aborting. - * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query. - * @param {string} [options.hint] An index name hint for the query. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {Cursor~countResultCallback} [callback] The result callback. - * @return {Promise} returns Promise if no callback passed - */ - count(applySkipLimit, opts, callback) { - if (this.cmd.query == null) - throw MongoError.create({ - message: 'count can only be used with find command', - driver: true - }); - if (typeof opts === 'function') (callback = opts), (opts = {}); - opts = opts || {}; - - if (typeof applySkipLimit === 'function') { - callback = applySkipLimit; - applySkipLimit = true; - } - - if (this.cursorState.session) { - opts = Object.assign({}, opts, { session: this.cursorState.session }); - } - - const countOperation = new CountOperation(this, applySkipLimit, opts); - - return executeOperation(this.topology, countOperation, callback); - } - - /** - * Close the cursor, sending a KillCursor command and emitting close. - * @method - * @param {object} [options] Optional settings. - * @param {boolean} [options.skipKillCursors] Bypass calling killCursors when closing the cursor. - * @param {Cursor~resultCallback} [callback] The result callback. - * @return {Promise} returns Promise if no callback passed - */ - close(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = Object.assign({}, { skipKillCursors: false }, options); - - this.s.state = CursorState.CLOSED; - if (!options.skipKillCursors) { - // Kill the cursor - this.kill(); - } - - const completeClose = () => { - // Emit the close event for the cursor - this.emit('close'); - - // Callback if provided - if (typeof callback === 'function') { - return handleCallback(callback, null, this); - } - - // Return a Promise - return new this.s.promiseLibrary(resolve => { - resolve(); - }); - }; - - if (this.cursorState.session) { - if (typeof callback === 'function') { - return this._endSession(() => completeClose()); - } - - return new this.s.promiseLibrary(resolve => { - this._endSession(() => completeClose().then(resolve)); - }); - } - - return completeClose(); - } - - /** - * Map all documents using the provided function - * @method - * @param {function} [transform] The mapping transformation method. - * @return {Cursor} - */ - map(transform) { - if (this.cursorState.transforms && this.cursorState.transforms.doc) { - const oldTransform = this.cursorState.transforms.doc; - this.cursorState.transforms.doc = doc => { - return transform(oldTransform(doc)); - }; - } else { - this.cursorState.transforms = { doc: transform }; - } - - return this; - } - - /** - * Is the cursor closed - * @method - * @return {boolean} - */ - isClosed() { - return this.isDead(); - } - - destroy(err) { - if (err) this.emit('error', err); - this.pause(); - this.close(); - } - - /** - * Return a modified Readable stream including a possible transform method. - * @method - * @param {object} [options] Optional settings. - * @param {function} [options.transform] A transformation method applied to each document emitted by the stream. - * @return {Cursor} - * TODO: replace this method with transformStream in next major release - */ - stream(options) { - this.cursorState.streamOptions = options || {}; - return this; - } - - /** - * Return a modified Readable stream that applies a given transform function, if supplied. If none supplied, - * returns a stream of unmodified docs. - * @method - * @param {object} [options] Optional settings. - * @param {function} [options.transform] A transformation method applied to each document emitted by the stream. - * @return {stream} - */ - transformStream(options) { - const streamOptions = options || {}; - if (typeof streamOptions.transform === 'function') { - const stream = new Transform({ - objectMode: true, - transform: function(chunk, encoding, callback) { - this.push(streamOptions.transform(chunk)); - callback(); - } - }); - - return this.pipe(stream); - } - - return this.pipe(new PassThrough({ objectMode: true })); - } - - /** - * Execute the explain for the cursor - * @method - * @param {Cursor~resultCallback} [callback] The result callback. - * @return {Promise} returns Promise if no callback passed - */ - explain(callback) { - // NOTE: the next line includes a special case for operations which do not - // subclass `CommandOperationV2`. To be removed asap. - if (this.operation && this.operation.cmd == null) { - this.operation.options.explain = true; - this.operation.fullResponse = false; - return executeOperation(this.topology, this.operation, callback); - } - - this.cmd.explain = true; - - // Do we have a readConcern - if (this.cmd.readConcern) { - delete this.cmd['readConcern']; - } - - const explainOperation = new ExplainOperation(this); - - return executeOperation(this.topology, explainOperation, callback); - } - - /** - * Return the cursor logger - * @method - * @return {Logger} return the cursor logger - * @ignore - */ - getLogger() { - return this.logger; - } -} - -/** - * Cursor stream data event, fired for each document in the cursor. - * - * @event Cursor#data - * @type {object} - */ - -/** - * Cursor stream end event - * - * @event Cursor#end - * @type {null} - */ - -/** - * Cursor stream close event - * - * @event Cursor#close - * @type {null} - */ - -/** - * Cursor stream readable event - * - * @event Cursor#readable - * @type {null} - */ - -// aliases -Cursor.prototype.maxTimeMs = Cursor.prototype.maxTimeMS; - -// deprecated methods -deprecate(Cursor.prototype.each, 'Cursor.each is deprecated. Use Cursor.forEach instead.'); -deprecate( - Cursor.prototype.maxScan, - 'Cursor.maxScan is deprecated, and will be removed in a later version' -); - -deprecate( - Cursor.prototype.snapshot, - 'Cursor Snapshot is deprecated, and will be removed in a later version' -); - -/** - * The read() method pulls some data out of the internal buffer and returns it. If there is no data available, then it will return null. - * @function external:Readable#read - * @param {number} size Optional argument to specify how much data to read. - * @return {(String | Buffer | null)} - */ - -/** - * Call this function to cause the stream to return strings of the specified encoding instead of Buffer objects. - * @function external:Readable#setEncoding - * @param {string} encoding The encoding to use. - * @return {null} - */ - -/** - * This method will cause the readable stream to resume emitting data events. - * @function external:Readable#resume - * @return {null} - */ - -/** - * This method will cause a stream in flowing-mode to stop emitting data events. Any data that becomes available will remain in the internal buffer. - * @function external:Readable#pause - * @return {null} - */ - -/** - * This method pulls all the data out of a readable stream, and writes it to the supplied destination, automatically managing the flow so that the destination is not overwhelmed by a fast readable stream. - * @function external:Readable#pipe - * @param {Writable} destination The destination for writing data - * @param {object} [options] Pipe options - * @return {null} - */ - -/** - * This method will remove the hooks set up for a previous pipe() call. - * @function external:Readable#unpipe - * @param {Writable} [destination] The destination for writing data - * @return {null} - */ - -/** - * This is useful in certain cases where a stream is being consumed by a parser, which needs to "un-consume" some data that it has optimistically pulled out of the source, so that the stream can be passed on to some other party. - * @function external:Readable#unshift - * @param {(Buffer|string)} chunk Chunk of data to unshift onto the read queue. - * @return {null} - */ - -/** - * Versions of Node prior to v0.10 had streams that did not implement the entire Streams API as it is today. (See "Compatibility" below for more information.) - * @function external:Readable#wrap - * @param {Stream} stream An "old style" readable stream. - * @return {null} - */ - -module.exports = Cursor; diff --git a/scripts/node_modules/mongodb/lib/db.js b/scripts/node_modules/mongodb/lib/db.js deleted file mode 100644 index 5e68734a..00000000 --- a/scripts/node_modules/mongodb/lib/db.js +++ /dev/null @@ -1,1029 +0,0 @@ -'use strict'; - -const EventEmitter = require('events').EventEmitter; -const inherits = require('util').inherits; -const getSingleProperty = require('./utils').getSingleProperty; -const CommandCursor = require('./command_cursor'); -const handleCallback = require('./utils').handleCallback; -const filterOptions = require('./utils').filterOptions; -const toError = require('./utils').toError; -const ReadPreference = require('./core').ReadPreference; -const MongoError = require('./core').MongoError; -const ObjectID = require('./core').ObjectID; -const Logger = require('./core').Logger; -const Collection = require('./collection'); -const mergeOptionsAndWriteConcern = require('./utils').mergeOptionsAndWriteConcern; -const executeLegacyOperation = require('./utils').executeLegacyOperation; -const resolveReadPreference = require('./utils').resolveReadPreference; -const ChangeStream = require('./change_stream'); -const deprecate = require('util').deprecate; -const deprecateOptions = require('./utils').deprecateOptions; -const MongoDBNamespace = require('./utils').MongoDBNamespace; -const CONSTANTS = require('./constants'); -const WriteConcern = require('./write_concern'); -const ReadConcern = require('./read_concern'); -const AggregationCursor = require('./aggregation_cursor'); - -// Operations -const createListener = require('./operations/db_ops').createListener; -const ensureIndex = require('./operations/db_ops').ensureIndex; -const evaluate = require('./operations/db_ops').evaluate; -const profilingInfo = require('./operations/db_ops').profilingInfo; -const validateDatabaseName = require('./operations/db_ops').validateDatabaseName; - -const AggregateOperation = require('./operations/aggregate'); -const AddUserOperation = require('./operations/add_user'); -const CollectionsOperation = require('./operations/collections'); -const CommandOperation = require('./operations/command'); -const CreateCollectionOperation = require('./operations/create_collection'); -const CreateIndexOperation = require('./operations/create_index'); -const DropCollectionOperation = require('./operations/drop').DropCollectionOperation; -const DropDatabaseOperation = require('./operations/drop').DropDatabaseOperation; -const ExecuteDbAdminCommandOperation = require('./operations/execute_db_admin_command'); -const IndexInformationOperation = require('./operations/index_information'); -const ListCollectionsOperation = require('./operations/list_collections'); -const ProfilingLevelOperation = require('./operations/profiling_level'); -const RemoveUserOperation = require('./operations/remove_user'); -const RenameOperation = require('./operations/rename'); -const SetProfilingLevelOperation = require('./operations/set_profiling_level'); - -const executeOperation = require('./operations/execute_operation'); - -/** - * @fileOverview The **Db** class is a class that represents a MongoDB Database. - * - * @example - * const MongoClient = require('mongodb').MongoClient; - * // Connection url - * const url = 'mongodb://localhost:27017'; - * // Database Name - * const dbName = 'test'; - * // Connect using MongoClient - * MongoClient.connect(url, function(err, client) { - * // Select the database by name - * const testDb = client.db(dbName); - * client.close(); - * }); - */ - -// Allowed parameters -const legalOptionNames = [ - 'w', - 'wtimeout', - 'fsync', - 'j', - 'readPreference', - 'readPreferenceTags', - 'native_parser', - 'forceServerObjectId', - 'pkFactory', - 'serializeFunctions', - 'raw', - 'bufferMaxEntries', - 'authSource', - 'ignoreUndefined', - 'promoteLongs', - 'promiseLibrary', - 'readConcern', - 'retryMiliSeconds', - 'numberOfRetries', - 'parentDb', - 'noListener', - 'loggerLevel', - 'logger', - 'promoteBuffers', - 'promoteLongs', - 'promoteValues', - 'compression', - 'retryWrites' -]; - -/** - * Creates a new Db instance - * @class - * @param {string} databaseName The name of the database this instance represents. - * @param {(Server|ReplSet|Mongos)} topology The server topology for the database. - * @param {object} [options] Optional settings. - * @param {string} [options.authSource] If the database authentication is dependent on another databaseName. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. - * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution. - * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. - * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. - * @param {number} [options.bufferMaxEntries=-1] Sets a cap on how many operations the driver will buffer up before giving up on getting a working connection, default is -1 which is unlimited. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {object} [options.pkFactory] A primary key factory object for generation of custom _id keys. - * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {object} [options.readConcern] Specify a read concern for the collection. (only MongoDB 3.2 or higher supported) - * @param {ReadConcernLevel} [options.readConcern.level='local'] Specify a read concern level for the collection operations (only MongoDB 3.2 or higher supported) - * @property {(Server|ReplSet|Mongos)} serverConfig Get the current db topology. - * @property {number} bufferMaxEntries Current bufferMaxEntries value for the database - * @property {string} databaseName The name of the database this instance represents. - * @property {object} options The options associated with the db instance. - * @property {boolean} native_parser The current value of the parameter native_parser. - * @property {boolean} slaveOk The current slaveOk value for the db instance. - * @property {object} writeConcern The current write concern values. - * @property {object} topology Access the topology object (single server, replicaset or mongos). - * @fires Db#close - * @fires Db#reconnect - * @fires Db#error - * @fires Db#timeout - * @fires Db#parseError - * @fires Db#fullsetup - * @return {Db} a Db instance. - */ -function Db(databaseName, topology, options) { - options = options || {}; - if (!(this instanceof Db)) return new Db(databaseName, topology, options); - EventEmitter.call(this); - - // Get the promiseLibrary - const promiseLibrary = options.promiseLibrary || Promise; - - // Filter the options - options = filterOptions(options, legalOptionNames); - - // Ensure we put the promiseLib in the options - options.promiseLibrary = promiseLibrary; - - // Internal state of the db object - this.s = { - // DbCache - dbCache: {}, - // Children db's - children: [], - // Topology - topology: topology, - // Options - options: options, - // Logger instance - logger: Logger('Db', options), - // Get the bson parser - bson: topology ? topology.bson : null, - // Unpack read preference - readPreference: ReadPreference.fromOptions(options), - // Set buffermaxEntries - bufferMaxEntries: typeof options.bufferMaxEntries === 'number' ? options.bufferMaxEntries : -1, - // Parent db (if chained) - parentDb: options.parentDb || null, - // Set up the primary key factory or fallback to ObjectID - pkFactory: options.pkFactory || ObjectID, - // Get native parser - nativeParser: options.nativeParser || options.native_parser, - // Promise library - promiseLibrary: promiseLibrary, - // No listener - noListener: typeof options.noListener === 'boolean' ? options.noListener : false, - // ReadConcern - readConcern: ReadConcern.fromOptions(options), - writeConcern: WriteConcern.fromOptions(options), - // Namespace - namespace: new MongoDBNamespace(databaseName) - }; - - // Ensure we have a valid db name - validateDatabaseName(databaseName); - - // Add a read Only property - getSingleProperty(this, 'serverConfig', this.s.topology); - getSingleProperty(this, 'bufferMaxEntries', this.s.bufferMaxEntries); - getSingleProperty(this, 'databaseName', this.s.namespace.db); - - // This is a child db, do not register any listeners - if (options.parentDb) return; - if (this.s.noListener) return; - - // Add listeners - topology.on('error', createListener(this, 'error', this)); - topology.on('timeout', createListener(this, 'timeout', this)); - topology.on('close', createListener(this, 'close', this)); - topology.on('parseError', createListener(this, 'parseError', this)); - topology.once('open', createListener(this, 'open', this)); - topology.once('fullsetup', createListener(this, 'fullsetup', this)); - topology.once('all', createListener(this, 'all', this)); - topology.on('reconnect', createListener(this, 'reconnect', this)); -} - -inherits(Db, EventEmitter); - -// Topology -Object.defineProperty(Db.prototype, 'topology', { - enumerable: true, - get: function() { - return this.s.topology; - } -}); - -// Options -Object.defineProperty(Db.prototype, 'options', { - enumerable: true, - get: function() { - return this.s.options; - } -}); - -// slaveOk specified -Object.defineProperty(Db.prototype, 'slaveOk', { - enumerable: true, - get: function() { - if ( - this.s.options.readPreference != null && - (this.s.options.readPreference !== 'primary' || - this.s.options.readPreference.mode !== 'primary') - ) { - return true; - } - return false; - } -}); - -Object.defineProperty(Db.prototype, 'readConcern', { - enumerable: true, - get: function() { - return this.s.readConcern; - } -}); - -Object.defineProperty(Db.prototype, 'readPreference', { - enumerable: true, - get: function() { - if (this.s.readPreference == null) { - // TODO: check client - return ReadPreference.primary; - } - - return this.s.readPreference; - } -}); - -// get the write Concern -Object.defineProperty(Db.prototype, 'writeConcern', { - enumerable: true, - get: function() { - return this.s.writeConcern; - } -}); - -Object.defineProperty(Db.prototype, 'namespace', { - enumerable: true, - get: function() { - return this.s.namespace.toString(); - } -}); - -/** - * Execute a command - * @method - * @param {object} command The command hash - * @param {object} [options] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.command = function(command, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = Object.assign({}, options); - - const commandOperation = new CommandOperation(this, options, null, command); - - return executeOperation(this.s.topology, commandOperation, callback); -}; - -/** - * Execute an aggregation framework pipeline against the database, needs MongoDB >= 3.6 - * @method - * @param {object} [pipeline=[]] Array containing all the aggregation framework commands for the execution. - * @param {object} [options] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {object} [options.cursor] Return the query as cursor, on 2.6 > it returns as a real cursor on pre 2.6 it returns as an emulated cursor. - * @param {number} [options.cursor.batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. - * @param {boolean} [options.explain=false] Explain returns the aggregation execution plan (requires mongodb 2.6 >). - * @param {boolean} [options.allowDiskUse=false] allowDiskUse lets the server know if it can use disk to store temporary results for the aggregation (requires mongodb 2.6 >). - * @param {number} [options.maxTimeMS] maxTimeMS specifies a cumulative time limit in milliseconds for processing operations on the cursor. MongoDB interrupts the operation at the earliest following interrupt point. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. - * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution. - * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. - * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. - * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {string} [options.comment] Add a comment to an aggregation command - * @param {string|object} [options.hint] Add an index selection hint to an aggregation command - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Database~aggregationCallback} callback The command result callback - * @return {(null|AggregationCursor)} - */ -Db.prototype.aggregate = function(pipeline, options, callback) { - if (typeof options === 'function') { - callback = options; - options = {}; - } - - // If we have no options or callback we are doing - // a cursor based aggregation - if (options == null && callback == null) { - options = {}; - } - - const cursor = new AggregationCursor( - this.s.topology, - new AggregateOperation(this, pipeline, options), - options - ); - - // TODO: remove this when NODE-2074 is resolved - if (typeof callback === 'function') { - callback(null, cursor); - return; - } - - return cursor; -}; - -/** - * Return the Admin db instance - * @method - * @return {Admin} return the new Admin db instance - */ -Db.prototype.admin = function() { - const Admin = require('./admin'); - - return new Admin(this, this.s.topology, this.s.promiseLibrary); -}; - -/** - * The callback format for the collection method, must be used if strict is specified - * @callback Db~collectionResultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection} collection The collection instance. - */ - -/** - * The callback format for an aggregation call - * @callback Database~aggregationCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {AggregationCursor} cursor The cursor if the aggregation command was executed successfully. - */ - -const collectionKeys = [ - 'pkFactory', - 'readPreference', - 'serializeFunctions', - 'strict', - 'readConcern', - 'ignoreUndefined', - 'promoteValues', - 'promoteBuffers', - 'promoteLongs' -]; - -/** - * Fetch a specific collection (containing the actual collection information). If the application does not use strict mode you - * can use it without a callback in the following way: `const collection = db.collection('mycollection');` - * - * @method - * @param {string} name the collection name we wish to access. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. - * @param {object} [options.pkFactory] A primary key factory object for generation of custom _id keys. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {boolean} [options.strict=false] Returns an error if the collection does not exist - * @param {object} [options.readConcern] Specify a read concern for the collection. (only MongoDB 3.2 or higher supported) - * @param {ReadConcernLevel} [options.readConcern.level='local'] Specify a read concern level for the collection operations (only MongoDB 3.2 or higher supported) - * @param {Db~collectionResultCallback} [callback] The collection result callback - * @return {Collection} return the new Collection instance if not in strict mode - */ -Db.prototype.collection = function(name, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - options = Object.assign({}, options); - - // Set the promise library - options.promiseLibrary = this.s.promiseLibrary; - - // If we have not set a collection level readConcern set the db level one - options.readConcern = options.readConcern - ? new ReadConcern(options.readConcern.level) - : this.readConcern; - - // Do we have ignoreUndefined set - if (this.s.options.ignoreUndefined) { - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - // Merge in all needed options and ensure correct writeConcern merging from db level - options = mergeOptionsAndWriteConcern(options, this.s.options, collectionKeys, true); - - // Execute - if (options == null || !options.strict) { - try { - const collection = new Collection( - this, - this.s.topology, - this.databaseName, - name, - this.s.pkFactory, - options - ); - if (callback) callback(null, collection); - return collection; - } catch (err) { - if (err instanceof MongoError && callback) return callback(err); - throw err; - } - } - - // Strict mode - if (typeof callback !== 'function') { - throw toError(`A callback is required in strict mode. While getting collection ${name}`); - } - - // Did the user destroy the topology - if (this.serverConfig && this.serverConfig.isDestroyed()) { - return callback(new MongoError('topology was destroyed')); - } - - const listCollectionOptions = Object.assign({}, options, { nameOnly: true }); - - // Strict mode - this.listCollections({ name: name }, listCollectionOptions).toArray((err, collections) => { - if (err != null) return handleCallback(callback, err, null); - if (collections.length === 0) - return handleCallback( - callback, - toError(`Collection ${name} does not exist. Currently in strict mode.`), - null - ); - - try { - return handleCallback( - callback, - null, - new Collection(this, this.s.topology, this.databaseName, name, this.s.pkFactory, options) - ); - } catch (err) { - return handleCallback(callback, err, null); - } - }); -}; - -/** - * Create a new collection on a server with the specified options. Use this to create capped collections. - * More information about command options available at https://docs.mongodb.com/manual/reference/command/create/ - * - * @method - * @param {string} name the collection name we wish to access. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. - * @param {object} [options.pkFactory] A primary key factory object for generation of custom _id keys. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {boolean} [options.strict=false] Returns an error if the collection does not exist - * @param {boolean} [options.capped=false] Create a capped collection. - * @param {boolean} [options.autoIndexId=true] DEPRECATED: Create an index on the _id field of the document, True by default on MongoDB 2.6 - 3.0 - * @param {number} [options.size] The size of the capped collection in bytes. - * @param {number} [options.max] The maximum number of documents in the capped collection. - * @param {number} [options.flags] Optional. Available for the MMAPv1 storage engine only to set the usePowerOf2Sizes and the noPadding flag. - * @param {object} [options.storageEngine] Allows users to specify configuration to the storage engine on a per-collection basis when creating a collection on MongoDB 3.0 or higher. - * @param {object} [options.validator] Allows users to specify validation rules or expressions for the collection. For more information, see Document Validation on MongoDB 3.2 or higher. - * @param {string} [options.validationLevel] Determines how strictly MongoDB applies the validation rules to existing documents during an update on MongoDB 3.2 or higher. - * @param {string} [options.validationAction] Determines whether to error on invalid documents or just warn about the violations but allow invalid documents to be inserted on MongoDB 3.2 or higher. - * @param {object} [options.indexOptionDefaults] Allows users to specify a default configuration for indexes when creating a collection on MongoDB 3.2 or higher. - * @param {string} [options.viewOn] The name of the source collection or view from which to create the view. The name is not the full namespace of the collection or view; i.e. does not include the database name and implies the same database as the view to create on MongoDB 3.4 or higher. - * @param {array} [options.pipeline] An array that consists of the aggregation pipeline stage. Creates the view by applying the specified pipeline to the viewOn collection or view on MongoDB 3.4 or higher. - * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~collectionResultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.createCollection = deprecateOptions( - { - name: 'Db.createCollection', - deprecatedOptions: ['autoIndexId'], - optionsIndex: 1 - }, - function(name, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - options.promiseLibrary = options.promiseLibrary || this.s.promiseLibrary; - options.readConcern = options.readConcern - ? new ReadConcern(options.readConcern.level) - : this.readConcern; - const createCollectionOperation = new CreateCollectionOperation(this, name, options); - - return executeOperation(this.s.topology, createCollectionOperation, callback); - } -); - -/** - * Get all the db statistics. - * - * @method - * @param {object} [options] Optional settings. - * @param {number} [options.scale] Divide the returned sizes by scale value. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The collection result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.stats = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - // Build command object - const commandObject = { dbStats: true }; - // Check if we have the scale value - if (options['scale'] != null) commandObject['scale'] = options['scale']; - - // If we have a readPreference set - if (options.readPreference == null && this.s.readPreference) { - options.readPreference = this.s.readPreference; - } - - const statsOperation = new CommandOperation(this, options, null, commandObject); - - // Execute the command - return executeOperation(this.s.topology, statsOperation, callback); -}; - -/** - * Get the list of all collection information for the specified db. - * - * @method - * @param {object} [filter={}] Query to filter collections by - * @param {object} [options] Optional settings. - * @param {boolean} [options.nameOnly=false] Since 4.0: If true, will only return the collection name in the response, and will omit additional info - * @param {number} [options.batchSize=1000] The batchSize for the returned command cursor or if pre 2.8 the systems batch collection - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {ClientSession} [options.session] optional session to use for this operation - * @return {CommandCursor} - */ -Db.prototype.listCollections = function(filter, options) { - filter = filter || {}; - options = options || {}; - - return new CommandCursor( - this.s.topology, - new ListCollectionsOperation(this, filter, options), - options - ); -}; - -/** - * Evaluate JavaScript on the server - * - * @method - * @param {Code} code JavaScript to execute on server. - * @param {(object|array)} parameters The parameters for the call. - * @param {object} [options] Optional settings. - * @param {boolean} [options.nolock=false] Tell MongoDB not to block on the evaluation of the javascript. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The results callback - * @deprecated Eval is deprecated on MongoDB 3.2 and forward - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.eval = deprecate(function(code, parameters, options, callback) { - const args = Array.prototype.slice.call(arguments, 1); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - parameters = args.length ? args.shift() : parameters; - options = args.length ? args.shift() || {} : {}; - - return executeLegacyOperation(this.s.topology, evaluate, [ - this, - code, - parameters, - options, - callback - ]); -}, 'Db.eval is deprecated as of MongoDB version 3.2'); - -/** - * Rename a collection. - * - * @method - * @param {string} fromCollection Name of current collection to rename. - * @param {string} toCollection New name of of the collection. - * @param {object} [options] Optional settings. - * @param {boolean} [options.dropTarget=false] Drop the target name collection if it previously exists. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~collectionResultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.renameCollection = function(fromCollection, toCollection, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = Object.assign({}, options, { readPreference: ReadPreference.PRIMARY }); - - // Add return new collection - options.new_collection = true; - - const renameOperation = new RenameOperation( - this.collection(fromCollection), - toCollection, - options - ); - - return executeOperation(this.s.topology, renameOperation, callback); -}; - -/** - * Drop a collection from the database, removing it permanently. New accesses will create a new collection. - * - * @method - * @param {string} name Name of collection to drop - * @param {Object} [options] Optional settings - * @param {WriteConcern} [options.writeConcern] A full WriteConcern object - * @param {(number|string)} [options.w] The write concern - * @param {number} [options.wtimeout] The write concern timeout - * @param {boolean} [options.j] The journal write concern - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.dropCollection = function(name, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const dropCollectionOperation = new DropCollectionOperation(this, name, options); - - return executeOperation(this.s.topology, dropCollectionOperation, callback); -}; - -/** - * Drop a database, removing it permanently from the server. - * - * @method - * @param {Object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.dropDatabase = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const dropDatabaseOperation = new DropDatabaseOperation(this, options); - - return executeOperation(this.s.topology, dropDatabaseOperation, callback); -}; - -/** - * Fetch all collections for the current db. - * - * @method - * @param {Object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~collectionsResultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.collections = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const collectionsOperation = new CollectionsOperation(this, options); - - return executeOperation(this.s.topology, collectionsOperation, callback); -}; - -/** - * Runs a command on the database as admin. - * @method - * @param {object} command The command hash - * @param {object} [options] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.executeDbAdminCommand = function(selector, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - options.readPreference = resolveReadPreference(this, options); - - const executeDbAdminCommandOperation = new ExecuteDbAdminCommandOperation( - this, - selector, - options - ); - - return executeOperation(this.s.topology, executeDbAdminCommandOperation, callback); -}; - -/** - * Creates an index on the db and collection. - * @method - * @param {string} name Name of the collection to create the index on. - * @param {(string|object)} fieldOrSpec Defines the index. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.unique=false] Creates an unique index. - * @param {boolean} [options.sparse=false] Creates a sparse index. - * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. - * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value - * @param {number} [options.min] For geospatial indexes set the lower bound for the co-ordinates. - * @param {number} [options.max] For geospatial indexes set the high bound for the co-ordinates. - * @param {number} [options.v] Specify the format version of the indexes. - * @param {number} [options.expireAfterSeconds] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) - * @param {string} [options.name] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) - * @param {object} [options.partialFilterExpression] Creates a partial index based on the given filter object (MongoDB 3.2 or higher) - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.createIndex = function(name, fieldOrSpec, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options ? Object.assign({}, options) : {}; - - const createIndexOperation = new CreateIndexOperation(this, name, fieldOrSpec, options); - - return executeOperation(this.s.topology, createIndexOperation, callback); -}; - -/** - * Ensures that an index exists, if it does not it creates it - * @method - * @deprecated since version 2.0 - * @param {string} name The index name - * @param {(string|object)} fieldOrSpec Defines the index. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.unique=false] Creates an unique index. - * @param {boolean} [options.sparse=false] Creates a sparse index. - * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. - * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value - * @param {number} [options.min] For geospatial indexes set the lower bound for the co-ordinates. - * @param {number} [options.max] For geospatial indexes set the high bound for the co-ordinates. - * @param {number} [options.v] Specify the format version of the indexes. - * @param {number} [options.expireAfterSeconds] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) - * @param {number} [options.name] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.ensureIndex = deprecate(function(name, fieldOrSpec, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - return executeLegacyOperation(this.s.topology, ensureIndex, [ - this, - name, - fieldOrSpec, - options, - callback - ]); -}, 'Db.ensureIndex is deprecated as of MongoDB version 3.0 / driver version 2.0'); - -Db.prototype.addChild = function(db) { - if (this.s.parentDb) return this.s.parentDb.addChild(db); - this.s.children.push(db); -}; - -/** - * Add a user to the database. - * @method - * @param {string} username The username. - * @param {string} password The password. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {object} [options.customData] Custom data associated with the user (only Mongodb 2.6 or higher) - * @param {object[]} [options.roles] Roles associated with the created user (only Mongodb 2.6 or higher) - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.addUser = function(username, password, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // Special case where there is no password ($external users) - if (typeof username === 'string' && password != null && typeof password === 'object') { - options = password; - password = null; - } - - const addUserOperation = new AddUserOperation(this, username, password, options); - - return executeOperation(this.s.topology, addUserOperation, callback); -}; - -/** - * Remove a user from a database - * @method - * @param {string} username The username. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.removeUser = function(username, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const removeUserOperation = new RemoveUserOperation(this, username, options); - - return executeOperation(this.s.topology, removeUserOperation, callback); -}; - -/** - * Set the current profiling level of MongoDB - * - * @param {string} level The new profiling level (off, slow_only, all). - * @param {Object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The command result callback. - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.setProfilingLevel = function(level, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const setProfilingLevelOperation = new SetProfilingLevelOperation(this, level, options); - - return executeOperation(this.s.topology, setProfilingLevelOperation, callback); -}; - -/** - * Retrieve the current profiling information for MongoDB - * - * @param {Object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The command result callback. - * @return {Promise} returns Promise if no callback passed - * @deprecated Query the system.profile collection directly. - */ -Db.prototype.profilingInfo = deprecate(function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - return executeLegacyOperation(this.s.topology, profilingInfo, [this, options, callback]); -}, 'Db.profilingInfo is deprecated. Query the system.profile collection directly.'); - -/** - * Retrieve the current profiling Level for MongoDB - * - * @param {Object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.profilingLevel = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const profilingLevelOperation = new ProfilingLevelOperation(this, options); - - return executeOperation(this.s.topology, profilingLevelOperation, callback); -}; - -/** - * Retrieves this collections index info. - * @method - * @param {string} name The name of the collection. - * @param {object} [options] Optional settings. - * @param {boolean} [options.full=false] Returns the full raw index information. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {Db~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.indexInformation = function(name, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - const indexInformationOperation = new IndexInformationOperation(this, name, options); - - return executeOperation(this.s.topology, indexInformationOperation, callback); -}; - -/** - * Unref all sockets - * @method - */ -Db.prototype.unref = function() { - this.s.topology.unref(); -}; - -/** - * Create a new Change Stream, watching for new changes (insertions, updates, replacements, deletions, and invalidations) in this database. Will ignore all changes to system collections. - * @method - * @since 3.1.0 - * @param {Array} [pipeline] An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents. - * @param {object} [options] Optional settings - * @param {string} [options.fullDocument='default'] Allowed values: ‘default’, ‘updateLookup’. When set to ‘updateLookup’, the change stream will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred. - * @param {object} [options.resumeAfter] Specifies the logical starting point for the new change stream. This should be the _id field from a previously returned change stream document. - * @param {number} [options.maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a change stream query - * @param {number} [options.batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. - * @param {object} [options.collation] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. - * @param {ReadPreference} [options.readPreference] The read preference. Defaults to the read preference of the database. See {@link https://docs.mongodb.com/manual/reference/read-preference|read preference documentation}. - * @param {Timestamp} [options.startAtOperationTime] receive change events that occur after the specified timestamp - * @param {ClientSession} [options.session] optional session to use for this operation - * @return {ChangeStream} a ChangeStream instance. - */ -Db.prototype.watch = function(pipeline, options) { - pipeline = pipeline || []; - options = options || {}; - - // Allow optionally not specifying a pipeline - if (!Array.isArray(pipeline)) { - options = pipeline; - pipeline = []; - } - - return new ChangeStream(this, pipeline, options); -}; - -/** - * Return the db logger - * @method - * @return {Logger} return the db logger - * @ignore - */ -Db.prototype.getLogger = function() { - return this.s.logger; -}; - -/** - * Db close event - * - * Emitted after a socket closed against a single server or mongos proxy. - * - * @event Db#close - * @type {MongoError} - */ - -/** - * Db reconnect event - * - * * Server: Emitted when the driver has reconnected and re-authenticated. - * * ReplicaSet: N/A - * * Mongos: Emitted when the driver reconnects and re-authenticates successfully against a Mongos. - * - * @event Db#reconnect - * @type {object} - */ - -/** - * Db error event - * - * Emitted after an error occurred against a single server or mongos proxy. - * - * @event Db#error - * @type {MongoError} - */ - -/** - * Db timeout event - * - * Emitted after a socket timeout occurred against a single server or mongos proxy. - * - * @event Db#timeout - * @type {MongoError} - */ - -/** - * Db parseError event - * - * The parseError event is emitted if the driver detects illegal or corrupt BSON being received from the server. - * - * @event Db#parseError - * @type {MongoError} - */ - -/** - * Db fullsetup event, emitted when all servers in the topology have been connected to at start up time. - * - * * Server: Emitted when the driver has connected to the single server and has authenticated. - * * ReplSet: Emitted after the driver has attempted to connect to all replicaset members. - * * Mongos: Emitted after the driver has attempted to connect to all mongos proxies. - * - * @event Db#fullsetup - * @type {Db} - */ - -// Constants -Db.SYSTEM_NAMESPACE_COLLECTION = CONSTANTS.SYSTEM_NAMESPACE_COLLECTION; -Db.SYSTEM_INDEX_COLLECTION = CONSTANTS.SYSTEM_INDEX_COLLECTION; -Db.SYSTEM_PROFILE_COLLECTION = CONSTANTS.SYSTEM_PROFILE_COLLECTION; -Db.SYSTEM_USER_COLLECTION = CONSTANTS.SYSTEM_USER_COLLECTION; -Db.SYSTEM_COMMAND_COLLECTION = CONSTANTS.SYSTEM_COMMAND_COLLECTION; -Db.SYSTEM_JS_COLLECTION = CONSTANTS.SYSTEM_JS_COLLECTION; - -module.exports = Db; diff --git a/scripts/node_modules/mongodb/lib/dynamic_loaders.js b/scripts/node_modules/mongodb/lib/dynamic_loaders.js deleted file mode 100644 index c4610023..00000000 --- a/scripts/node_modules/mongodb/lib/dynamic_loaders.js +++ /dev/null @@ -1,32 +0,0 @@ -'use strict'; - -let collection; -let cursor; -let db; - -function loadCollection() { - if (!collection) { - collection = require('./collection'); - } - return collection; -} - -function loadCursor() { - if (!cursor) { - cursor = require('./cursor'); - } - return cursor; -} - -function loadDb() { - if (!db) { - db = require('./db'); - } - return db; -} - -module.exports = { - loadCollection, - loadCursor, - loadDb -}; diff --git a/scripts/node_modules/mongodb/lib/error.js b/scripts/node_modules/mongodb/lib/error.js deleted file mode 100644 index 4d104e9b..00000000 --- a/scripts/node_modules/mongodb/lib/error.js +++ /dev/null @@ -1,45 +0,0 @@ -'use strict'; - -const MongoNetworkError = require('./core').MongoNetworkError; -const mongoErrorContextSymbol = require('./core').mongoErrorContextSymbol; - -const GET_MORE_NON_RESUMABLE_CODES = new Set([ - 136, // CappedPositionLost - 237, // CursorKilled - 11601 // Interrupted -]); - -// From spec@https://github.com/mongodb/specifications/blob/7a2e93d85935ee4b1046a8d2ad3514c657dc74fa/source/change-streams/change-streams.rst#resumable-error: -// -// An error is considered resumable if it meets any of the following criteria: -// - any error encountered which is not a server error (e.g. a timeout error or network error) -// - any server error response from a getMore command excluding those containing the error label -// NonRetryableChangeStreamError and those containing the following error codes: -// - Interrupted: 11601 -// - CappedPositionLost: 136 -// - CursorKilled: 237 -// -// An error on an aggregate command is not a resumable error. Only errors on a getMore command may be considered resumable errors. - -function isGetMoreError(error) { - if (error[mongoErrorContextSymbol]) { - return error[mongoErrorContextSymbol].isGetMore; - } -} - -function isResumableError(error) { - if (!isGetMoreError(error)) { - return false; - } - - if (error instanceof MongoNetworkError) { - return true; - } - - return !( - GET_MORE_NON_RESUMABLE_CODES.has(error.code) || - error.hasErrorLabel('NonRetryableChangeStreamError') - ); -} - -module.exports = { GET_MORE_NON_RESUMABLE_CODES, isResumableError }; diff --git a/scripts/node_modules/mongodb/lib/gridfs-stream/download.js b/scripts/node_modules/mongodb/lib/gridfs-stream/download.js deleted file mode 100644 index dfb1de57..00000000 --- a/scripts/node_modules/mongodb/lib/gridfs-stream/download.js +++ /dev/null @@ -1,421 +0,0 @@ -'use strict'; - -var stream = require('stream'), - util = require('util'); - -module.exports = GridFSBucketReadStream; - -/** - * A readable stream that enables you to read buffers from GridFS. - * - * Do not instantiate this class directly. Use `openDownloadStream()` instead. - * - * @class - * @param {Collection} chunks Handle for chunks collection - * @param {Collection} files Handle for files collection - * @param {Object} readPreference The read preference to use - * @param {Object} filter The query to use to find the file document - * @param {Object} [options] Optional settings. - * @param {Number} [options.sort] Optional sort for the file find query - * @param {Number} [options.skip] Optional skip for the file find query - * @param {Number} [options.start] Optional 0-based offset in bytes to start streaming from - * @param {Number} [options.end] Optional 0-based offset in bytes to stop streaming before - * @fires GridFSBucketReadStream#error - * @fires GridFSBucketReadStream#file - * @return {GridFSBucketReadStream} a GridFSBucketReadStream instance. - */ - -function GridFSBucketReadStream(chunks, files, readPreference, filter, options) { - this.s = { - bytesRead: 0, - chunks: chunks, - cursor: null, - expected: 0, - files: files, - filter: filter, - init: false, - expectedEnd: 0, - file: null, - options: options, - readPreference: readPreference - }; - - stream.Readable.call(this); -} - -util.inherits(GridFSBucketReadStream, stream.Readable); - -/** - * An error occurred - * - * @event GridFSBucketReadStream#error - * @type {Error} - */ - -/** - * Fires when the stream loaded the file document corresponding to the - * provided id. - * - * @event GridFSBucketReadStream#file - * @type {object} - */ - -/** - * Emitted when a chunk of data is available to be consumed. - * - * @event GridFSBucketReadStream#data - * @type {object} - */ - -/** - * Fired when the stream is exhausted (no more data events). - * - * @event GridFSBucketReadStream#end - * @type {object} - */ - -/** - * Fired when the stream is exhausted and the underlying cursor is killed - * - * @event GridFSBucketReadStream#close - * @type {object} - */ - -/** - * Reads from the cursor and pushes to the stream. - * @method - */ - -GridFSBucketReadStream.prototype._read = function() { - var _this = this; - if (this.destroyed) { - return; - } - - waitForFile(_this, function() { - doRead(_this); - }); -}; - -/** - * Sets the 0-based offset in bytes to start streaming from. Throws - * an error if this stream has entered flowing mode - * (e.g. if you've already called `on('data')`) - * @method - * @param {Number} start Offset in bytes to start reading at - * @return {GridFSBucketReadStream} - */ - -GridFSBucketReadStream.prototype.start = function(start) { - throwIfInitialized(this); - this.s.options.start = start; - return this; -}; - -/** - * Sets the 0-based offset in bytes to start streaming from. Throws - * an error if this stream has entered flowing mode - * (e.g. if you've already called `on('data')`) - * @method - * @param {Number} end Offset in bytes to stop reading at - * @return {GridFSBucketReadStream} - */ - -GridFSBucketReadStream.prototype.end = function(end) { - throwIfInitialized(this); - this.s.options.end = end; - return this; -}; - -/** - * Marks this stream as aborted (will never push another `data` event) - * and kills the underlying cursor. Will emit the 'end' event, and then - * the 'close' event once the cursor is successfully killed. - * - * @method - * @param {GridFSBucket~errorCallback} [callback] called when the cursor is successfully closed or an error occurred. - * @fires GridFSBucketWriteStream#close - * @fires GridFSBucketWriteStream#end - */ - -GridFSBucketReadStream.prototype.abort = function(callback) { - var _this = this; - this.push(null); - this.destroyed = true; - if (this.s.cursor) { - this.s.cursor.close(function(error) { - _this.emit('close'); - callback && callback(error); - }); - } else { - if (!this.s.init) { - // If not initialized, fire close event because we will never - // get a cursor - _this.emit('close'); - } - callback && callback(); - } -}; - -/** - * @ignore - */ - -function throwIfInitialized(self) { - if (self.s.init) { - throw new Error('You cannot change options after the stream has entered' + 'flowing mode!'); - } -} - -/** - * @ignore - */ - -function doRead(_this) { - if (_this.destroyed) { - return; - } - - _this.s.cursor.next(function(error, doc) { - if (_this.destroyed) { - return; - } - if (error) { - return __handleError(_this, error); - } - if (!doc) { - _this.push(null); - - process.nextTick(() => { - _this.s.cursor.close(function(error) { - if (error) { - __handleError(_this, error); - return; - } - - _this.emit('close'); - }); - }); - - return; - } - - var bytesRemaining = _this.s.file.length - _this.s.bytesRead; - var expectedN = _this.s.expected++; - var expectedLength = Math.min(_this.s.file.chunkSize, bytesRemaining); - - if (doc.n > expectedN) { - var errmsg = 'ChunkIsMissing: Got unexpected n: ' + doc.n + ', expected: ' + expectedN; - return __handleError(_this, new Error(errmsg)); - } - - if (doc.n < expectedN) { - errmsg = 'ExtraChunk: Got unexpected n: ' + doc.n + ', expected: ' + expectedN; - return __handleError(_this, new Error(errmsg)); - } - - var buf = Buffer.isBuffer(doc.data) ? doc.data : doc.data.buffer; - - if (buf.length !== expectedLength) { - if (bytesRemaining <= 0) { - errmsg = 'ExtraChunk: Got unexpected n: ' + doc.n; - return __handleError(_this, new Error(errmsg)); - } - - errmsg = - 'ChunkIsWrongSize: Got unexpected length: ' + buf.length + ', expected: ' + expectedLength; - return __handleError(_this, new Error(errmsg)); - } - - _this.s.bytesRead += buf.length; - - if (buf.length === 0) { - return _this.push(null); - } - - var sliceStart = null; - var sliceEnd = null; - - if (_this.s.bytesToSkip != null) { - sliceStart = _this.s.bytesToSkip; - _this.s.bytesToSkip = 0; - } - - const atEndOfStream = expectedN === _this.s.expectedEnd - 1; - const bytesLeftToRead = _this.s.options.end - _this.s.bytesToSkip; - if (atEndOfStream && _this.s.bytesToTrim != null) { - sliceEnd = _this.s.file.chunkSize - _this.s.bytesToTrim; - } else if (_this.s.options.end && bytesLeftToRead < doc.data.length()) { - sliceEnd = bytesLeftToRead; - } - - if (sliceStart != null || sliceEnd != null) { - buf = buf.slice(sliceStart || 0, sliceEnd || buf.length); - } - - _this.push(buf); - }); -} - -/** - * @ignore - */ - -function init(self) { - var findOneOptions = {}; - if (self.s.readPreference) { - findOneOptions.readPreference = self.s.readPreference; - } - if (self.s.options && self.s.options.sort) { - findOneOptions.sort = self.s.options.sort; - } - if (self.s.options && self.s.options.skip) { - findOneOptions.skip = self.s.options.skip; - } - - self.s.files.findOne(self.s.filter, findOneOptions, function(error, doc) { - if (error) { - return __handleError(self, error); - } - if (!doc) { - var identifier = self.s.filter._id ? self.s.filter._id.toString() : self.s.filter.filename; - var errmsg = 'FileNotFound: file ' + identifier + ' was not found'; - var err = new Error(errmsg); - err.code = 'ENOENT'; - return __handleError(self, err); - } - - // If document is empty, kill the stream immediately and don't - // execute any reads - if (doc.length <= 0) { - self.push(null); - return; - } - - if (self.destroyed) { - // If user destroys the stream before we have a cursor, wait - // until the query is done to say we're 'closed' because we can't - // cancel a query. - self.emit('close'); - return; - } - - self.s.bytesToSkip = handleStartOption(self, doc, self.s.options); - - var filter = { files_id: doc._id }; - - // Currently (MongoDB 3.4.4) skip function does not support the index, - // it needs to retrieve all the documents first and then skip them. (CS-25811) - // As work around we use $gte on the "n" field. - if (self.s.options && self.s.options.start != null) { - var skip = Math.floor(self.s.options.start / doc.chunkSize); - if (skip > 0) { - filter['n'] = { $gte: skip }; - } - } - self.s.cursor = self.s.chunks.find(filter).sort({ n: 1 }); - - if (self.s.readPreference) { - self.s.cursor.setReadPreference(self.s.readPreference); - } - - self.s.expectedEnd = Math.ceil(doc.length / doc.chunkSize); - self.s.file = doc; - self.s.bytesToTrim = handleEndOption(self, doc, self.s.cursor, self.s.options); - self.emit('file', doc); - }); -} - -/** - * @ignore - */ - -function waitForFile(_this, callback) { - if (_this.s.file) { - return callback(); - } - - if (!_this.s.init) { - init(_this); - _this.s.init = true; - } - - _this.once('file', function() { - callback(); - }); -} - -/** - * @ignore - */ - -function handleStartOption(stream, doc, options) { - if (options && options.start != null) { - if (options.start > doc.length) { - throw new Error( - 'Stream start (' + - options.start + - ') must not be ' + - 'more than the length of the file (' + - doc.length + - ')' - ); - } - if (options.start < 0) { - throw new Error('Stream start (' + options.start + ') must not be ' + 'negative'); - } - if (options.end != null && options.end < options.start) { - throw new Error( - 'Stream start (' + - options.start + - ') must not be ' + - 'greater than stream end (' + - options.end + - ')' - ); - } - - stream.s.bytesRead = Math.floor(options.start / doc.chunkSize) * doc.chunkSize; - stream.s.expected = Math.floor(options.start / doc.chunkSize); - - return options.start - stream.s.bytesRead; - } -} - -/** - * @ignore - */ - -function handleEndOption(stream, doc, cursor, options) { - if (options && options.end != null) { - if (options.end > doc.length) { - throw new Error( - 'Stream end (' + - options.end + - ') must not be ' + - 'more than the length of the file (' + - doc.length + - ')' - ); - } - if (options.start < 0) { - throw new Error('Stream end (' + options.end + ') must not be ' + 'negative'); - } - - var start = options.start != null ? Math.floor(options.start / doc.chunkSize) : 0; - - cursor.limit(Math.ceil(options.end / doc.chunkSize) - start); - - stream.s.expectedEnd = Math.ceil(options.end / doc.chunkSize); - - return Math.ceil(options.end / doc.chunkSize) * doc.chunkSize - options.end; - } -} - -/** - * @ignore - */ - -function __handleError(_this, error) { - _this.emit('error', error); -} diff --git a/scripts/node_modules/mongodb/lib/gridfs-stream/index.js b/scripts/node_modules/mongodb/lib/gridfs-stream/index.js deleted file mode 100644 index 93b45ebf..00000000 --- a/scripts/node_modules/mongodb/lib/gridfs-stream/index.js +++ /dev/null @@ -1,358 +0,0 @@ -'use strict'; - -var Emitter = require('events').EventEmitter; -var GridFSBucketReadStream = require('./download'); -var GridFSBucketWriteStream = require('./upload'); -var shallowClone = require('../utils').shallowClone; -var toError = require('../utils').toError; -var util = require('util'); -var executeLegacyOperation = require('../utils').executeLegacyOperation; - -var DEFAULT_GRIDFS_BUCKET_OPTIONS = { - bucketName: 'fs', - chunkSizeBytes: 255 * 1024 -}; - -module.exports = GridFSBucket; - -/** - * Constructor for a streaming GridFS interface - * @class - * @param {Db} db A db handle - * @param {object} [options] Optional settings. - * @param {string} [options.bucketName="fs"] The 'files' and 'chunks' collections will be prefixed with the bucket name followed by a dot. - * @param {number} [options.chunkSizeBytes=255 * 1024] Number of bytes stored in each chunk. Defaults to 255KB - * @param {object} [options.writeConcern] Optional write concern to be passed to write operations, for instance `{ w: 1 }` - * @param {object} [options.readPreference] Optional read preference to be passed to read operations - * @fires GridFSBucketWriteStream#index - * @return {GridFSBucket} - */ - -function GridFSBucket(db, options) { - Emitter.apply(this); - this.setMaxListeners(0); - - if (options && typeof options === 'object') { - options = shallowClone(options); - var keys = Object.keys(DEFAULT_GRIDFS_BUCKET_OPTIONS); - for (var i = 0; i < keys.length; ++i) { - if (!options[keys[i]]) { - options[keys[i]] = DEFAULT_GRIDFS_BUCKET_OPTIONS[keys[i]]; - } - } - } else { - options = DEFAULT_GRIDFS_BUCKET_OPTIONS; - } - - this.s = { - db: db, - options: options, - _chunksCollection: db.collection(options.bucketName + '.chunks'), - _filesCollection: db.collection(options.bucketName + '.files'), - checkedIndexes: false, - calledOpenUploadStream: false, - promiseLibrary: db.s.promiseLibrary || Promise - }; -} - -util.inherits(GridFSBucket, Emitter); - -/** - * When the first call to openUploadStream is made, the upload stream will - * check to see if it needs to create the proper indexes on the chunks and - * files collections. This event is fired either when 1) it determines that - * no index creation is necessary, 2) when it successfully creates the - * necessary indexes. - * - * @event GridFSBucket#index - * @type {Error} - */ - -/** - * Returns a writable stream (GridFSBucketWriteStream) for writing - * buffers to GridFS. The stream's 'id' property contains the resulting - * file's id. - * @method - * @param {string} filename The value of the 'filename' key in the files doc - * @param {object} [options] Optional settings. - * @param {number} [options.chunkSizeBytes] Optional overwrite this bucket's chunkSizeBytes for this file - * @param {object} [options.metadata] Optional object to store in the file document's `metadata` field - * @param {string} [options.contentType] Optional string to store in the file document's `contentType` field - * @param {array} [options.aliases] Optional array of strings to store in the file document's `aliases` field - * @param {boolean} [options.disableMD5=false] If true, disables adding an md5 field to file data - * @return {GridFSBucketWriteStream} - */ - -GridFSBucket.prototype.openUploadStream = function(filename, options) { - if (options) { - options = shallowClone(options); - } else { - options = {}; - } - if (!options.chunkSizeBytes) { - options.chunkSizeBytes = this.s.options.chunkSizeBytes; - } - return new GridFSBucketWriteStream(this, filename, options); -}; - -/** - * Returns a writable stream (GridFSBucketWriteStream) for writing - * buffers to GridFS for a custom file id. The stream's 'id' property contains the resulting - * file's id. - * @method - * @param {string|number|object} id A custom id used to identify the file - * @param {string} filename The value of the 'filename' key in the files doc - * @param {object} [options] Optional settings. - * @param {number} [options.chunkSizeBytes] Optional overwrite this bucket's chunkSizeBytes for this file - * @param {object} [options.metadata] Optional object to store in the file document's `metadata` field - * @param {string} [options.contentType] Optional string to store in the file document's `contentType` field - * @param {array} [options.aliases] Optional array of strings to store in the file document's `aliases` field - * @param {boolean} [options.disableMD5=false] If true, disables adding an md5 field to file data - * @return {GridFSBucketWriteStream} - */ - -GridFSBucket.prototype.openUploadStreamWithId = function(id, filename, options) { - if (options) { - options = shallowClone(options); - } else { - options = {}; - } - - if (!options.chunkSizeBytes) { - options.chunkSizeBytes = this.s.options.chunkSizeBytes; - } - - options.id = id; - - return new GridFSBucketWriteStream(this, filename, options); -}; - -/** - * Returns a readable stream (GridFSBucketReadStream) for streaming file - * data from GridFS. - * @method - * @param {ObjectId} id The id of the file doc - * @param {Object} [options] Optional settings. - * @param {Number} [options.start] Optional 0-based offset in bytes to start streaming from - * @param {Number} [options.end] Optional 0-based offset in bytes to stop streaming before - * @return {GridFSBucketReadStream} - */ - -GridFSBucket.prototype.openDownloadStream = function(id, options) { - var filter = { _id: id }; - options = { - start: options && options.start, - end: options && options.end - }; - - return new GridFSBucketReadStream( - this.s._chunksCollection, - this.s._filesCollection, - this.s.options.readPreference, - filter, - options - ); -}; - -/** - * Deletes a file with the given id - * @method - * @param {ObjectId} id The id of the file doc - * @param {GridFSBucket~errorCallback} [callback] - */ - -GridFSBucket.prototype.delete = function(id, callback) { - return executeLegacyOperation(this.s.db.s.topology, _delete, [this, id, callback], { - skipSessions: true - }); -}; - -/** - * @ignore - */ - -function _delete(_this, id, callback) { - _this.s._filesCollection.deleteOne({ _id: id }, function(error, res) { - if (error) { - return callback(error); - } - - _this.s._chunksCollection.deleteMany({ files_id: id }, function(error) { - if (error) { - return callback(error); - } - - // Delete orphaned chunks before returning FileNotFound - if (!res.result.n) { - var errmsg = 'FileNotFound: no file with id ' + id + ' found'; - return callback(new Error(errmsg)); - } - - callback(); - }); - }); -} - -/** - * Convenience wrapper around find on the files collection - * @method - * @param {Object} filter - * @param {Object} [options] Optional settings for cursor - * @param {number} [options.batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/find|find command documentation}. - * @param {number} [options.limit] Optional limit for cursor - * @param {number} [options.maxTimeMS] Optional maxTimeMS for cursor - * @param {boolean} [options.noCursorTimeout] Optionally set cursor's `noCursorTimeout` flag - * @param {number} [options.skip] Optional skip for cursor - * @param {object} [options.sort] Optional sort for cursor - * @return {Cursor} - */ - -GridFSBucket.prototype.find = function(filter, options) { - filter = filter || {}; - options = options || {}; - - var cursor = this.s._filesCollection.find(filter); - - if (options.batchSize != null) { - cursor.batchSize(options.batchSize); - } - if (options.limit != null) { - cursor.limit(options.limit); - } - if (options.maxTimeMS != null) { - cursor.maxTimeMS(options.maxTimeMS); - } - if (options.noCursorTimeout != null) { - cursor.addCursorFlag('noCursorTimeout', options.noCursorTimeout); - } - if (options.skip != null) { - cursor.skip(options.skip); - } - if (options.sort != null) { - cursor.sort(options.sort); - } - - return cursor; -}; - -/** - * Returns a readable stream (GridFSBucketReadStream) for streaming the - * file with the given name from GridFS. If there are multiple files with - * the same name, this will stream the most recent file with the given name - * (as determined by the `uploadDate` field). You can set the `revision` - * option to change this behavior. - * @method - * @param {String} filename The name of the file to stream - * @param {Object} [options] Optional settings - * @param {number} [options.revision=-1] The revision number relative to the oldest file with the given filename. 0 gets you the oldest file, 1 gets you the 2nd oldest, -1 gets you the newest. - * @param {Number} [options.start] Optional 0-based offset in bytes to start streaming from - * @param {Number} [options.end] Optional 0-based offset in bytes to stop streaming before - * @return {GridFSBucketReadStream} - */ - -GridFSBucket.prototype.openDownloadStreamByName = function(filename, options) { - var sort = { uploadDate: -1 }; - var skip = null; - if (options && options.revision != null) { - if (options.revision >= 0) { - sort = { uploadDate: 1 }; - skip = options.revision; - } else { - skip = -options.revision - 1; - } - } - - var filter = { filename: filename }; - options = { - sort: sort, - skip: skip, - start: options && options.start, - end: options && options.end - }; - return new GridFSBucketReadStream( - this.s._chunksCollection, - this.s._filesCollection, - this.s.options.readPreference, - filter, - options - ); -}; - -/** - * Renames the file with the given _id to the given string - * @method - * @param {ObjectId} id the id of the file to rename - * @param {String} filename new name for the file - * @param {GridFSBucket~errorCallback} [callback] - */ - -GridFSBucket.prototype.rename = function(id, filename, callback) { - return executeLegacyOperation(this.s.db.s.topology, _rename, [this, id, filename, callback], { - skipSessions: true - }); -}; - -/** - * @ignore - */ - -function _rename(_this, id, filename, callback) { - var filter = { _id: id }; - var update = { $set: { filename: filename } }; - _this.s._filesCollection.updateOne(filter, update, function(error, res) { - if (error) { - return callback(error); - } - if (!res.result.n) { - return callback(toError('File with id ' + id + ' not found')); - } - callback(); - }); -} - -/** - * Removes this bucket's files collection, followed by its chunks collection. - * @method - * @param {GridFSBucket~errorCallback} [callback] - */ - -GridFSBucket.prototype.drop = function(callback) { - return executeLegacyOperation(this.s.db.s.topology, _drop, [this, callback], { - skipSessions: true - }); -}; - -/** - * Return the db logger - * @method - * @return {Logger} return the db logger - * @ignore - */ -GridFSBucket.prototype.getLogger = function() { - return this.s.db.s.logger; -}; - -/** - * @ignore - */ - -function _drop(_this, callback) { - _this.s._filesCollection.drop(function(error) { - if (error) { - return callback(error); - } - _this.s._chunksCollection.drop(function(error) { - if (error) { - return callback(error); - } - - return callback(); - }); - }); -} - -/** - * Callback format for all GridFSBucket methods that can accept a callback. - * @callback GridFSBucket~errorCallback - * @param {MongoError} error An error instance representing any errors that occurred - */ diff --git a/scripts/node_modules/mongodb/lib/gridfs-stream/upload.js b/scripts/node_modules/mongodb/lib/gridfs-stream/upload.js deleted file mode 100644 index 3733f2cb..00000000 --- a/scripts/node_modules/mongodb/lib/gridfs-stream/upload.js +++ /dev/null @@ -1,538 +0,0 @@ -'use strict'; - -var core = require('../core'); -var crypto = require('crypto'); -var stream = require('stream'); -var util = require('util'); -var Buffer = require('safe-buffer').Buffer; - -var ERROR_NAMESPACE_NOT_FOUND = 26; - -module.exports = GridFSBucketWriteStream; - -/** - * A writable stream that enables you to write buffers to GridFS. - * - * Do not instantiate this class directly. Use `openUploadStream()` instead. - * - * @class - * @param {GridFSBucket} bucket Handle for this stream's corresponding bucket - * @param {string} filename The value of the 'filename' key in the files doc - * @param {object} [options] Optional settings. - * @param {string|number|object} [options.id] Custom file id for the GridFS file. - * @param {number} [options.chunkSizeBytes] The chunk size to use, in bytes - * @param {number} [options.w] The write concern - * @param {number} [options.wtimeout] The write concern timeout - * @param {number} [options.j] The journal write concern - * @param {boolean} [options.disableMD5=false] If true, disables adding an md5 field to file data - * @fires GridFSBucketWriteStream#error - * @fires GridFSBucketWriteStream#finish - * @return {GridFSBucketWriteStream} a GridFSBucketWriteStream instance. - */ - -function GridFSBucketWriteStream(bucket, filename, options) { - options = options || {}; - this.bucket = bucket; - this.chunks = bucket.s._chunksCollection; - this.filename = filename; - this.files = bucket.s._filesCollection; - this.options = options; - // Signals the write is all done - this.done = false; - - this.id = options.id ? options.id : core.BSON.ObjectId(); - this.chunkSizeBytes = this.options.chunkSizeBytes; - this.bufToStore = Buffer.alloc(this.chunkSizeBytes); - this.length = 0; - this.md5 = !options.disableMD5 && crypto.createHash('md5'); - this.n = 0; - this.pos = 0; - this.state = { - streamEnd: false, - outstandingRequests: 0, - errored: false, - aborted: false, - promiseLibrary: this.bucket.s.promiseLibrary - }; - - if (!this.bucket.s.calledOpenUploadStream) { - this.bucket.s.calledOpenUploadStream = true; - - var _this = this; - checkIndexes(this, function() { - _this.bucket.s.checkedIndexes = true; - _this.bucket.emit('index'); - }); - } -} - -util.inherits(GridFSBucketWriteStream, stream.Writable); - -/** - * An error occurred - * - * @event GridFSBucketWriteStream#error - * @type {Error} - */ - -/** - * `end()` was called and the write stream successfully wrote the file - * metadata and all the chunks to MongoDB. - * - * @event GridFSBucketWriteStream#finish - * @type {object} - */ - -/** - * Write a buffer to the stream. - * - * @method - * @param {Buffer} chunk Buffer to write - * @param {String} encoding Optional encoding for the buffer - * @param {Function} callback Function to call when the chunk was added to the buffer, or if the entire chunk was persisted to MongoDB if this chunk caused a flush. - * @return {Boolean} False if this write required flushing a chunk to MongoDB. True otherwise. - */ - -GridFSBucketWriteStream.prototype.write = function(chunk, encoding, callback) { - var _this = this; - return waitForIndexes(this, function() { - return doWrite(_this, chunk, encoding, callback); - }); -}; - -/** - * Places this write stream into an aborted state (all future writes fail) - * and deletes all chunks that have already been written. - * - * @method - * @param {GridFSBucket~errorCallback} callback called when chunks are successfully removed or error occurred - * @return {Promise} if no callback specified - */ - -GridFSBucketWriteStream.prototype.abort = function(callback) { - if (this.state.streamEnd) { - var error = new Error('Cannot abort a stream that has already completed'); - if (typeof callback === 'function') { - return callback(error); - } - return this.state.promiseLibrary.reject(error); - } - if (this.state.aborted) { - error = new Error('Cannot call abort() on a stream twice'); - if (typeof callback === 'function') { - return callback(error); - } - return this.state.promiseLibrary.reject(error); - } - this.state.aborted = true; - this.chunks.deleteMany({ files_id: this.id }, function(error) { - if (typeof callback === 'function') callback(error); - }); -}; - -/** - * Tells the stream that no more data will be coming in. The stream will - * persist the remaining data to MongoDB, write the files document, and - * then emit a 'finish' event. - * - * @method - * @param {Buffer} chunk Buffer to write - * @param {String} encoding Optional encoding for the buffer - * @param {Function} callback Function to call when all files and chunks have been persisted to MongoDB - */ - -GridFSBucketWriteStream.prototype.end = function(chunk, encoding, callback) { - var _this = this; - if (typeof chunk === 'function') { - (callback = chunk), (chunk = null), (encoding = null); - } else if (typeof encoding === 'function') { - (callback = encoding), (encoding = null); - } - - if (checkAborted(this, callback)) { - return; - } - this.state.streamEnd = true; - - if (callback) { - this.once('finish', function(result) { - callback(null, result); - }); - } - - if (!chunk) { - waitForIndexes(this, function() { - writeRemnant(_this); - }); - return; - } - - this.write(chunk, encoding, function() { - writeRemnant(_this); - }); -}; - -/** - * @ignore - */ - -function __handleError(_this, error, callback) { - if (_this.state.errored) { - return; - } - _this.state.errored = true; - if (callback) { - return callback(error); - } - _this.emit('error', error); -} - -/** - * @ignore - */ - -function createChunkDoc(filesId, n, data) { - return { - _id: core.BSON.ObjectId(), - files_id: filesId, - n: n, - data: data - }; -} - -/** - * @ignore - */ - -function checkChunksIndex(_this, callback) { - _this.chunks.listIndexes().toArray(function(error, indexes) { - if (error) { - // Collection doesn't exist so create index - if (error.code === ERROR_NAMESPACE_NOT_FOUND) { - var index = { files_id: 1, n: 1 }; - _this.chunks.createIndex(index, { background: false, unique: true }, function(error) { - if (error) { - return callback(error); - } - - callback(); - }); - return; - } - return callback(error); - } - - var hasChunksIndex = false; - indexes.forEach(function(index) { - if (index.key) { - var keys = Object.keys(index.key); - if (keys.length === 2 && index.key.files_id === 1 && index.key.n === 1) { - hasChunksIndex = true; - } - } - }); - - if (hasChunksIndex) { - callback(); - } else { - index = { files_id: 1, n: 1 }; - var indexOptions = getWriteOptions(_this); - - indexOptions.background = false; - indexOptions.unique = true; - - _this.chunks.createIndex(index, indexOptions, function(error) { - if (error) { - return callback(error); - } - - callback(); - }); - } - }); -} - -/** - * @ignore - */ - -function checkDone(_this, callback) { - if (_this.done) return true; - if (_this.state.streamEnd && _this.state.outstandingRequests === 0 && !_this.state.errored) { - // Set done so we dont' trigger duplicate createFilesDoc - _this.done = true; - // Create a new files doc - var filesDoc = createFilesDoc( - _this.id, - _this.length, - _this.chunkSizeBytes, - _this.md5 && _this.md5.digest('hex'), - _this.filename, - _this.options.contentType, - _this.options.aliases, - _this.options.metadata - ); - - if (checkAborted(_this, callback)) { - return false; - } - - _this.files.insertOne(filesDoc, getWriteOptions(_this), function(error) { - if (error) { - return __handleError(_this, error, callback); - } - _this.emit('finish', filesDoc); - }); - - return true; - } - - return false; -} - -/** - * @ignore - */ - -function checkIndexes(_this, callback) { - _this.files.findOne({}, { _id: 1 }, function(error, doc) { - if (error) { - return callback(error); - } - if (doc) { - return callback(); - } - - _this.files.listIndexes().toArray(function(error, indexes) { - if (error) { - // Collection doesn't exist so create index - if (error.code === ERROR_NAMESPACE_NOT_FOUND) { - var index = { filename: 1, uploadDate: 1 }; - _this.files.createIndex(index, { background: false }, function(error) { - if (error) { - return callback(error); - } - - checkChunksIndex(_this, callback); - }); - return; - } - return callback(error); - } - - var hasFileIndex = false; - indexes.forEach(function(index) { - var keys = Object.keys(index.key); - if (keys.length === 2 && index.key.filename === 1 && index.key.uploadDate === 1) { - hasFileIndex = true; - } - }); - - if (hasFileIndex) { - checkChunksIndex(_this, callback); - } else { - index = { filename: 1, uploadDate: 1 }; - - var indexOptions = getWriteOptions(_this); - - indexOptions.background = false; - - _this.files.createIndex(index, indexOptions, function(error) { - if (error) { - return callback(error); - } - - checkChunksIndex(_this, callback); - }); - } - }); - }); -} - -/** - * @ignore - */ - -function createFilesDoc(_id, length, chunkSize, md5, filename, contentType, aliases, metadata) { - var ret = { - _id: _id, - length: length, - chunkSize: chunkSize, - uploadDate: new Date(), - filename: filename - }; - - if (md5) { - ret.md5 = md5; - } - - if (contentType) { - ret.contentType = contentType; - } - - if (aliases) { - ret.aliases = aliases; - } - - if (metadata) { - ret.metadata = metadata; - } - - return ret; -} - -/** - * @ignore - */ - -function doWrite(_this, chunk, encoding, callback) { - if (checkAborted(_this, callback)) { - return false; - } - - var inputBuf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding); - - _this.length += inputBuf.length; - - // Input is small enough to fit in our buffer - if (_this.pos + inputBuf.length < _this.chunkSizeBytes) { - inputBuf.copy(_this.bufToStore, _this.pos); - _this.pos += inputBuf.length; - - callback && callback(); - - // Note that we reverse the typical semantics of write's return value - // to be compatible with node's `.pipe()` function. - // True means client can keep writing. - return true; - } - - // Otherwise, buffer is too big for current chunk, so we need to flush - // to MongoDB. - var inputBufRemaining = inputBuf.length; - var spaceRemaining = _this.chunkSizeBytes - _this.pos; - var numToCopy = Math.min(spaceRemaining, inputBuf.length); - var outstandingRequests = 0; - while (inputBufRemaining > 0) { - var inputBufPos = inputBuf.length - inputBufRemaining; - inputBuf.copy(_this.bufToStore, _this.pos, inputBufPos, inputBufPos + numToCopy); - _this.pos += numToCopy; - spaceRemaining -= numToCopy; - if (spaceRemaining === 0) { - if (_this.md5) { - _this.md5.update(_this.bufToStore); - } - var doc = createChunkDoc(_this.id, _this.n, _this.bufToStore); - ++_this.state.outstandingRequests; - ++outstandingRequests; - - if (checkAborted(_this, callback)) { - return false; - } - - _this.chunks.insertOne(doc, getWriteOptions(_this), function(error) { - if (error) { - return __handleError(_this, error); - } - --_this.state.outstandingRequests; - --outstandingRequests; - - if (!outstandingRequests) { - _this.emit('drain', doc); - callback && callback(); - checkDone(_this); - } - }); - - spaceRemaining = _this.chunkSizeBytes; - _this.pos = 0; - ++_this.n; - } - inputBufRemaining -= numToCopy; - numToCopy = Math.min(spaceRemaining, inputBufRemaining); - } - - // Note that we reverse the typical semantics of write's return value - // to be compatible with node's `.pipe()` function. - // False means the client should wait for the 'drain' event. - return false; -} - -/** - * @ignore - */ - -function getWriteOptions(_this) { - var obj = {}; - if (_this.options.writeConcern) { - obj.w = _this.options.writeConcern.w; - obj.wtimeout = _this.options.writeConcern.wtimeout; - obj.j = _this.options.writeConcern.j; - } - return obj; -} - -/** - * @ignore - */ - -function waitForIndexes(_this, callback) { - if (_this.bucket.s.checkedIndexes) { - return callback(false); - } - - _this.bucket.once('index', function() { - callback(true); - }); - - return true; -} - -/** - * @ignore - */ - -function writeRemnant(_this, callback) { - // Buffer is empty, so don't bother to insert - if (_this.pos === 0) { - return checkDone(_this, callback); - } - - ++_this.state.outstandingRequests; - - // Create a new buffer to make sure the buffer isn't bigger than it needs - // to be. - var remnant = Buffer.alloc(_this.pos); - _this.bufToStore.copy(remnant, 0, 0, _this.pos); - if (_this.md5) { - _this.md5.update(remnant); - } - var doc = createChunkDoc(_this.id, _this.n, remnant); - - // If the stream was aborted, do not write remnant - if (checkAborted(_this, callback)) { - return false; - } - - _this.chunks.insertOne(doc, getWriteOptions(_this), function(error) { - if (error) { - return __handleError(_this, error); - } - --_this.state.outstandingRequests; - checkDone(_this); - }); -} - -/** - * @ignore - */ - -function checkAborted(_this, callback) { - if (_this.state.aborted) { - if (typeof callback === 'function') { - callback(new Error('this stream has been aborted')); - } - return true; - } - return false; -} diff --git a/scripts/node_modules/mongodb/lib/gridfs/chunk.js b/scripts/node_modules/mongodb/lib/gridfs/chunk.js deleted file mode 100644 index d276d720..00000000 --- a/scripts/node_modules/mongodb/lib/gridfs/chunk.js +++ /dev/null @@ -1,236 +0,0 @@ -'use strict'; - -var Binary = require('../core').BSON.Binary, - ObjectID = require('../core').BSON.ObjectID; - -var Buffer = require('safe-buffer').Buffer; - -/** - * Class for representing a single chunk in GridFS. - * - * @class - * - * @param file {GridStore} The {@link GridStore} object holding this chunk. - * @param mongoObject {object} The mongo object representation of this chunk. - * - * @throws Error when the type of data field for {@link mongoObject} is not - * supported. Currently supported types for data field are instances of - * {@link String}, {@link Array}, {@link Binary} and {@link Binary} - * from the bson module - * - * @see Chunk#buildMongoObject - */ -var Chunk = function(file, mongoObject, writeConcern) { - if (!(this instanceof Chunk)) return new Chunk(file, mongoObject); - - this.file = file; - var mongoObjectFinal = mongoObject == null ? {} : mongoObject; - this.writeConcern = writeConcern || { w: 1 }; - this.objectId = mongoObjectFinal._id == null ? new ObjectID() : mongoObjectFinal._id; - this.chunkNumber = mongoObjectFinal.n == null ? 0 : mongoObjectFinal.n; - this.data = new Binary(); - - if (typeof mongoObjectFinal.data === 'string') { - var buffer = Buffer.alloc(mongoObjectFinal.data.length); - buffer.write(mongoObjectFinal.data, 0, mongoObjectFinal.data.length, 'binary'); - this.data = new Binary(buffer); - } else if (Array.isArray(mongoObjectFinal.data)) { - buffer = Buffer.alloc(mongoObjectFinal.data.length); - var data = mongoObjectFinal.data.join(''); - buffer.write(data, 0, data.length, 'binary'); - this.data = new Binary(buffer); - } else if (mongoObjectFinal.data && mongoObjectFinal.data._bsontype === 'Binary') { - this.data = mongoObjectFinal.data; - } else if (!Buffer.isBuffer(mongoObjectFinal.data) && !(mongoObjectFinal.data == null)) { - throw Error('Illegal chunk format'); - } - - // Update position - this.internalPosition = 0; -}; - -/** - * Writes a data to this object and advance the read/write head. - * - * @param data {string} the data to write - * @param callback {function(*, GridStore)} This will be called after executing - * this method. The first parameter will contain null and the second one - * will contain a reference to this object. - */ -Chunk.prototype.write = function(data, callback) { - this.data.write(data, this.internalPosition, data.length, 'binary'); - this.internalPosition = this.data.length(); - if (callback != null) return callback(null, this); - return this; -}; - -/** - * Reads data and advances the read/write head. - * - * @param length {number} The length of data to read. - * - * @return {string} The data read if the given length will not exceed the end of - * the chunk. Returns an empty String otherwise. - */ -Chunk.prototype.read = function(length) { - // Default to full read if no index defined - length = length == null || length === 0 ? this.length() : length; - - if (this.length() - this.internalPosition + 1 >= length) { - var data = this.data.read(this.internalPosition, length); - this.internalPosition = this.internalPosition + length; - return data; - } else { - return ''; - } -}; - -Chunk.prototype.readSlice = function(length) { - if (this.length() - this.internalPosition >= length) { - var data = null; - if (this.data.buffer != null) { - //Pure BSON - data = this.data.buffer.slice(this.internalPosition, this.internalPosition + length); - } else { - //Native BSON - data = Buffer.alloc(length); - length = this.data.readInto(data, this.internalPosition); - } - this.internalPosition = this.internalPosition + length; - return data; - } else { - return null; - } -}; - -/** - * Checks if the read/write head is at the end. - * - * @return {boolean} Whether the read/write head has reached the end of this - * chunk. - */ -Chunk.prototype.eof = function() { - return this.internalPosition === this.length() ? true : false; -}; - -/** - * Reads one character from the data of this chunk and advances the read/write - * head. - * - * @return {string} a single character data read if the the read/write head is - * not at the end of the chunk. Returns an empty String otherwise. - */ -Chunk.prototype.getc = function() { - return this.read(1); -}; - -/** - * Clears the contents of the data in this chunk and resets the read/write head - * to the initial position. - */ -Chunk.prototype.rewind = function() { - this.internalPosition = 0; - this.data = new Binary(); -}; - -/** - * Saves this chunk to the database. Also overwrites existing entries having the - * same id as this chunk. - * - * @param callback {function(*, GridStore)} This will be called after executing - * this method. The first parameter will contain null and the second one - * will contain a reference to this object. - */ -Chunk.prototype.save = function(options, callback) { - var self = this; - if (typeof options === 'function') { - callback = options; - options = {}; - } - - self.file.chunkCollection(function(err, collection) { - if (err) return callback(err); - - // Merge the options - var writeOptions = { upsert: true }; - for (var name in options) writeOptions[name] = options[name]; - for (name in self.writeConcern) writeOptions[name] = self.writeConcern[name]; - - if (self.data.length() > 0) { - self.buildMongoObject(function(mongoObject) { - var options = { forceServerObjectId: true }; - for (var name in self.writeConcern) { - options[name] = self.writeConcern[name]; - } - - collection.replaceOne({ _id: self.objectId }, mongoObject, writeOptions, function(err) { - callback(err, self); - }); - }); - } else { - callback(null, self); - } - // }); - }); -}; - -/** - * Creates a mongoDB object representation of this chunk. - * - * @param callback {function(Object)} This will be called after executing this - * method. The object will be passed to the first parameter and will have - * the structure: - * - *

- *        {
- *          '_id' : , // {number} id for this chunk
- *          'files_id' : , // {number} foreign key to the file collection
- *          'n' : , // {number} chunk number
- *          'data' : , // {bson#Binary} the chunk data itself
- *        }
- *        
- * - * @see MongoDB GridFS Chunk Object Structure - */ -Chunk.prototype.buildMongoObject = function(callback) { - var mongoObject = { - files_id: this.file.fileId, - n: this.chunkNumber, - data: this.data - }; - // If we are saving using a specific ObjectId - if (this.objectId != null) mongoObject._id = this.objectId; - - callback(mongoObject); -}; - -/** - * @return {number} the length of the data - */ -Chunk.prototype.length = function() { - return this.data.length(); -}; - -/** - * The position of the read/write head - * @name position - * @lends Chunk# - * @field - */ -Object.defineProperty(Chunk.prototype, 'position', { - enumerable: true, - get: function() { - return this.internalPosition; - }, - set: function(value) { - this.internalPosition = value; - } -}); - -/** - * The default chunk size - * @constant - */ -Chunk.DEFAULT_CHUNK_SIZE = 1024 * 255; - -module.exports = Chunk; diff --git a/scripts/node_modules/mongodb/lib/gridfs/grid_store.js b/scripts/node_modules/mongodb/lib/gridfs/grid_store.js deleted file mode 100644 index c8ccb850..00000000 --- a/scripts/node_modules/mongodb/lib/gridfs/grid_store.js +++ /dev/null @@ -1,1913 +0,0 @@ -'use strict'; - -/** - * @fileOverview GridFS is a tool for MongoDB to store files to the database. - * Because of the restrictions of the object size the database can hold, a - * facility to split a file into several chunks is needed. The {@link GridStore} - * class offers a simplified api to interact with files while managing the - * chunks of split files behind the scenes. More information about GridFS can be - * found here. - * - * @example - * const MongoClient = require('mongodb').MongoClient; - * const GridStore = require('mongodb').GridStore; - * const ObjectID = require('mongodb').ObjectID; - * const test = require('assert'); - * // Connection url - * const url = 'mongodb://localhost:27017'; - * // Database Name - * const dbName = 'test'; - * // Connect using MongoClient - * MongoClient.connect(url, function(err, client) { - * const db = client.db(dbName); - * const gridStore = new GridStore(db, null, "w"); - * gridStore.open(function(err, gridStore) { - * gridStore.write("hello world!", function(err, gridStore) { - * gridStore.close(function(err, result) { - * // Let's read the file using object Id - * GridStore.read(db, result._id, function(err, data) { - * test.equal('hello world!', data); - * client.close(); - * test.done(); - * }); - * }); - * }); - * }); - * }); - */ -const Chunk = require('./chunk'); -const ObjectID = require('../core').BSON.ObjectID; -const ReadPreference = require('../core').ReadPreference; -const Buffer = require('safe-buffer').Buffer; -const fs = require('fs'); -const f = require('util').format; -const util = require('util'); -const MongoError = require('../core').MongoError; -const inherits = util.inherits; -const Duplex = require('stream').Duplex; -const shallowClone = require('../utils').shallowClone; -const executeLegacyOperation = require('../utils').executeLegacyOperation; -const deprecate = require('util').deprecate; - -var REFERENCE_BY_FILENAME = 0, - REFERENCE_BY_ID = 1; - -const deprecationFn = deprecate(() => {}, -'GridStore is deprecated, and will be removed in a future version. Please use GridFSBucket instead'); - -/** - * Namespace provided by the core module - * @external Duplex - */ - -/** - * Create a new GridStore instance - * - * Modes - * - **"r"** - read only. This is the default mode. - * - **"w"** - write in truncate mode. Existing data will be overwritten. - * - * @class - * @param {Db} db A database instance to interact with. - * @param {object} [id] optional unique id for this file - * @param {string} [filename] optional filename for this file, no unique constrain on the field - * @param {string} mode set the mode for this file. - * @param {object} [options] Optional settings. - * @param {(number|string)} [options.w] The write concern. - * @param {number} [options.wtimeout] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.fsync=false] Specify a file sync write concern. - * @param {string} [options.root] Root collection to use. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**. - * @param {string} [options.content_type] MIME type of the file. Defaults to **{GridStore.DEFAULT_CONTENT_TYPE}**. - * @param {number} [options.chunk_size=261120] Size for the chunk. Defaults to **{Chunk.DEFAULT_CHUNK_SIZE}**. - * @param {object} [options.metadata] Arbitrary data the user wants to store. - * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @property {number} chunkSize Get the gridstore chunk size. - * @property {number} md5 The md5 checksum for this file. - * @property {number} chunkNumber The current chunk number the gridstore has materialized into memory - * @return {GridStore} a GridStore instance. - * @deprecated Use GridFSBucket API instead - */ -var GridStore = function GridStore(db, id, filename, mode, options) { - deprecationFn(); - if (!(this instanceof GridStore)) return new GridStore(db, id, filename, mode, options); - this.db = db; - - // Handle options - if (typeof options === 'undefined') options = {}; - // Handle mode - if (typeof mode === 'undefined') { - mode = filename; - filename = undefined; - } else if (typeof mode === 'object') { - options = mode; - mode = filename; - filename = undefined; - } - - if (id && id._bsontype === 'ObjectID') { - this.referenceBy = REFERENCE_BY_ID; - this.fileId = id; - this.filename = filename; - } else if (typeof filename === 'undefined') { - this.referenceBy = REFERENCE_BY_FILENAME; - this.filename = id; - if (mode.indexOf('w') != null) { - this.fileId = new ObjectID(); - } - } else { - this.referenceBy = REFERENCE_BY_ID; - this.fileId = id; - this.filename = filename; - } - - // Set up the rest - this.mode = mode == null ? 'r' : mode; - this.options = options || {}; - - // Opened - this.isOpen = false; - - // Set the root if overridden - this.root = - this.options['root'] == null ? GridStore.DEFAULT_ROOT_COLLECTION : this.options['root']; - this.position = 0; - this.readPreference = - this.options.readPreference || db.options.readPreference || ReadPreference.primary; - this.writeConcern = _getWriteConcern(db, this.options); - // Set default chunk size - this.internalChunkSize = - this.options['chunkSize'] == null ? Chunk.DEFAULT_CHUNK_SIZE : this.options['chunkSize']; - - // Get the promiseLibrary - var promiseLibrary = this.options.promiseLibrary || Promise; - - // Set the promiseLibrary - this.promiseLibrary = promiseLibrary; - - Object.defineProperty(this, 'chunkSize', { - enumerable: true, - get: function() { - return this.internalChunkSize; - }, - set: function(value) { - if (!(this.mode[0] === 'w' && this.position === 0 && this.uploadDate == null)) { - this.internalChunkSize = this.internalChunkSize; - } else { - this.internalChunkSize = value; - } - } - }); - - Object.defineProperty(this, 'md5', { - enumerable: true, - get: function() { - return this.internalMd5; - } - }); - - Object.defineProperty(this, 'chunkNumber', { - enumerable: true, - get: function() { - return this.currentChunk && this.currentChunk.chunkNumber - ? this.currentChunk.chunkNumber - : null; - } - }); -}; - -/** - * The callback format for the Gridstore.open method - * @callback GridStore~openCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {GridStore} gridStore The GridStore instance if the open method was successful. - */ - -/** - * Opens the file from the database and initialize this object. Also creates a - * new one if file does not exist. - * - * @method - * @param {object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {GridStore~openCallback} [callback] this will be called after executing this method - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.open = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - if (this.mode !== 'w' && this.mode !== 'w+' && this.mode !== 'r') { - throw MongoError.create({ message: 'Illegal mode ' + this.mode, driver: true }); - } - - return executeLegacyOperation(this.db.s.topology, open, [this, options, callback], { - skipSessions: true - }); -}; - -var open = function(self, options, callback) { - // Get the write concern - var writeConcern = _getWriteConcern(self.db, self.options); - - // If we are writing we need to ensure we have the right indexes for md5's - if (self.mode === 'w' || self.mode === 'w+') { - // Get files collection - var collection = self.collection(); - // Put index on filename - collection.ensureIndex([['filename', 1]], writeConcern, function() { - // Get chunk collection - var chunkCollection = self.chunkCollection(); - // Make an unique index for compatibility with mongo-cxx-driver:legacy - var chunkIndexOptions = shallowClone(writeConcern); - chunkIndexOptions.unique = true; - // Ensure index on chunk collection - chunkCollection.ensureIndex([['files_id', 1], ['n', 1]], chunkIndexOptions, function() { - // Open the connection - _open(self, writeConcern, function(err, r) { - if (err) return callback(err); - self.isOpen = true; - callback(err, r); - }); - }); - }); - } else { - // Open the gridstore - _open(self, writeConcern, function(err, r) { - if (err) return callback(err); - self.isOpen = true; - callback(err, r); - }); - } -}; - -/** - * Verify if the file is at EOF. - * - * @method - * @return {boolean} true if the read/write head is at the end of this file. - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.eof = function() { - return this.position === this.length ? true : false; -}; - -/** - * The callback result format. - * @callback GridStore~resultCallback - * @param {object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {MongoError} error An error instance representing the error during the execution. - * @param {object} result The result from the callback. - */ - -/** - * Retrieves a single character from this file. - * - * @method - * @param {GridStore~resultCallback} [callback] this gets called after this method is executed. Passes null to the first parameter and the character read to the second or null to the second if the read/write head is at the end of the file. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.getc = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - return executeLegacyOperation(this.db.s.topology, getc, [this, options, callback], { - skipSessions: true - }); -}; - -var getc = function(self, options, callback) { - if (self.eof()) { - callback(null, null); - } else if (self.currentChunk.eof()) { - nthChunk(self, self.currentChunk.chunkNumber + 1, function(err, chunk) { - self.currentChunk = chunk; - self.position = self.position + 1; - callback(err, self.currentChunk.getc()); - }); - } else { - self.position = self.position + 1; - callback(null, self.currentChunk.getc()); - } -}; - -/** - * Writes a string to the file with a newline character appended at the end if - * the given string does not have one. - * - * @method - * @param {string} string the string to write. - * @param {object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.puts = function(string, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - var finalString = string.match(/\n$/) == null ? string + '\n' : string; - return executeLegacyOperation( - this.db.s.topology, - this.write.bind(this), - [finalString, options, callback], - { skipSessions: true } - ); -}; - -/** - * Return a modified Readable stream including a possible transform method. - * - * @method - * @return {GridStoreStream} - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.stream = function() { - return new GridStoreStream(this); -}; - -/** - * Writes some data. This method will work properly only if initialized with mode "w" or "w+". - * - * @method - * @param {(string|Buffer)} data the data to write. - * @param {boolean} [close] closes this file after writing if set to true. - * @param {object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.write = function write(data, close, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - return executeLegacyOperation( - this.db.s.topology, - _writeNormal, - [this, data, close, options, callback], - { skipSessions: true } - ); -}; - -/** - * Handles the destroy part of a stream - * - * @method - * @result {null} - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.destroy = function destroy() { - // close and do not emit any more events. queued data is not sent. - if (!this.writable) return; - this.readable = false; - if (this.writable) { - this.writable = false; - this._q.length = 0; - this.emit('close'); - } -}; - -/** - * Stores a file from the file system to the GridFS database. - * - * @method - * @param {(string|Buffer|FileHandle)} file the file to store. - * @param {object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.writeFile = function(file, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - return executeLegacyOperation(this.db.s.topology, writeFile, [this, file, options, callback], { - skipSessions: true - }); -}; - -var writeFile = function(self, file, options, callback) { - if (typeof file === 'string') { - fs.open(file, 'r', function(err, fd) { - if (err) return callback(err); - self.writeFile(fd, callback); - }); - return; - } - - self.open(function(err, self) { - if (err) return callback(err, self); - - fs.fstat(file, function(err, stats) { - if (err) return callback(err, self); - - var offset = 0; - var index = 0; - - // Write a chunk - var writeChunk = function() { - // Allocate the buffer - var _buffer = Buffer.alloc(self.chunkSize); - // Read the file - fs.read(file, _buffer, 0, _buffer.length, offset, function(err, bytesRead, data) { - if (err) return callback(err, self); - - offset = offset + bytesRead; - - // Create a new chunk for the data - var chunk = new Chunk(self, { n: index++ }, self.writeConcern); - chunk.write(data.slice(0, bytesRead), function(err, chunk) { - if (err) return callback(err, self); - - chunk.save({}, function(err) { - if (err) return callback(err, self); - - self.position = self.position + bytesRead; - - // Point to current chunk - self.currentChunk = chunk; - - if (offset >= stats.size) { - fs.close(file, function(err) { - if (err) return callback(err); - - self.close(function(err) { - if (err) return callback(err, self); - return callback(null, self); - }); - }); - } else { - return process.nextTick(writeChunk); - } - }); - }); - }); - }; - - // Process the first write - process.nextTick(writeChunk); - }); - }); -}; - -/** - * Saves this file to the database. This will overwrite the old entry if it - * already exists. This will work properly only if mode was initialized to - * "w" or "w+". - * - * @method - * @param {object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.close = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - return executeLegacyOperation(this.db.s.topology, close, [this, options, callback], { - skipSessions: true - }); -}; - -var close = function(self, options, callback) { - if (self.mode[0] === 'w') { - // Set up options - options = Object.assign({}, self.writeConcern, options); - - if (self.currentChunk != null && self.currentChunk.position > 0) { - self.currentChunk.save({}, function(err) { - if (err && typeof callback === 'function') return callback(err); - - self.collection(function(err, files) { - if (err && typeof callback === 'function') return callback(err); - - // Build the mongo object - if (self.uploadDate != null) { - buildMongoObject(self, function(err, mongoObject) { - if (err) { - if (typeof callback === 'function') return callback(err); - else throw err; - } - - files.save(mongoObject, options, function(err) { - if (typeof callback === 'function') callback(err, mongoObject); - }); - }); - } else { - self.uploadDate = new Date(); - buildMongoObject(self, function(err, mongoObject) { - if (err) { - if (typeof callback === 'function') return callback(err); - else throw err; - } - - files.save(mongoObject, options, function(err) { - if (typeof callback === 'function') callback(err, mongoObject); - }); - }); - } - }); - }); - } else { - self.collection(function(err, files) { - if (err && typeof callback === 'function') return callback(err); - - self.uploadDate = new Date(); - buildMongoObject(self, function(err, mongoObject) { - if (err) { - if (typeof callback === 'function') return callback(err); - else throw err; - } - - files.save(mongoObject, options, function(err) { - if (typeof callback === 'function') callback(err, mongoObject); - }); - }); - }); - } - } else if (self.mode[0] === 'r') { - if (typeof callback === 'function') callback(null, null); - } else { - if (typeof callback === 'function') - callback(MongoError.create({ message: f('Illegal mode %s', self.mode), driver: true })); - } -}; - -/** - * The collection callback format. - * @callback GridStore~collectionCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection} collection The collection from the command execution. - */ - -/** - * Retrieve this file's chunks collection. - * - * @method - * @param {GridStore~collectionCallback} callback the command callback. - * @return {Collection} - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.chunkCollection = function(callback) { - if (typeof callback === 'function') return this.db.collection(this.root + '.chunks', callback); - return this.db.collection(this.root + '.chunks'); -}; - -/** - * Deletes all the chunks of this file in the database. - * - * @method - * @param {object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {GridStore~resultCallback} [callback] the command callback. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.unlink = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - return executeLegacyOperation(this.db.s.topology, unlink, [this, options, callback], { - skipSessions: true - }); -}; - -var unlink = function(self, options, callback) { - deleteChunks(self, function(err) { - if (err !== null) { - err.message = 'at deleteChunks: ' + err.message; - return callback(err); - } - - self.collection(function(err, collection) { - if (err !== null) { - err.message = 'at collection: ' + err.message; - return callback(err); - } - - collection.remove({ _id: self.fileId }, self.writeConcern, function(err) { - callback(err, self); - }); - }); - }); -}; - -/** - * Retrieves the file collection associated with this object. - * - * @method - * @param {GridStore~collectionCallback} callback the command callback. - * @return {Collection} - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.collection = function(callback) { - if (typeof callback === 'function') this.db.collection(this.root + '.files', callback); - return this.db.collection(this.root + '.files'); -}; - -/** - * The readlines callback format. - * @callback GridStore~readlinesCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {string[]} strings The array of strings returned. - */ - -/** - * Read the entire file as a list of strings splitting by the provided separator. - * - * @method - * @param {string} [separator] The character to be recognized as the newline separator. - * @param {object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {GridStore~readlinesCallback} [callback] the command callback. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.readlines = function(separator, options, callback) { - var args = Array.prototype.slice.call(arguments, 0); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - separator = args.length ? args.shift() : '\n'; - separator = separator || '\n'; - options = args.length ? args.shift() : {}; - - return executeLegacyOperation( - this.db.s.topology, - readlines, - [this, separator, options, callback], - { skipSessions: true } - ); -}; - -var readlines = function(self, separator, options, callback) { - self.read(function(err, data) { - if (err) return callback(err); - - var items = data.toString().split(separator); - items = items.length > 0 ? items.splice(0, items.length - 1) : []; - for (var i = 0; i < items.length; i++) { - items[i] = items[i] + separator; - } - - callback(null, items); - }); -}; - -/** - * Deletes all the chunks of this file in the database if mode was set to "w" or - * "w+" and resets the read/write head to the initial position. - * - * @method - * @param {object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.rewind = function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - return executeLegacyOperation(this.db.s.topology, rewind, [this, options, callback], { - skipSessions: true - }); -}; - -var rewind = function(self, options, callback) { - if (self.currentChunk.chunkNumber !== 0) { - if (self.mode[0] === 'w') { - deleteChunks(self, function(err) { - if (err) return callback(err); - self.currentChunk = new Chunk(self, { n: 0 }, self.writeConcern); - self.position = 0; - callback(null, self); - }); - } else { - self.currentChunk(0, function(err, chunk) { - if (err) return callback(err); - self.currentChunk = chunk; - self.currentChunk.rewind(); - self.position = 0; - callback(null, self); - }); - } - } else { - self.currentChunk.rewind(); - self.position = 0; - callback(null, self); - } -}; - -/** - * The read callback format. - * @callback GridStore~readCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Buffer} data The data read from the GridStore object - */ - -/** - * Retrieves the contents of this file and advances the read/write head. Works with Buffers only. - * - * There are 3 signatures for this method: - * - * (callback) - * (length, callback) - * (length, buffer, callback) - * - * @method - * @param {number} [length] the number of characters to read. Reads all the characters from the read/write head to the EOF if not specified. - * @param {(string|Buffer)} [buffer] a string to hold temporary data. This is used for storing the string data read so far when recursively calling this method. - * @param {object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {GridStore~readCallback} [callback] the command callback. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.read = function(length, buffer, options, callback) { - var args = Array.prototype.slice.call(arguments, 0); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - length = args.length ? args.shift() : null; - buffer = args.length ? args.shift() : null; - options = args.length ? args.shift() : {}; - - return executeLegacyOperation( - this.db.s.topology, - read, - [this, length, buffer, options, callback], - { skipSessions: true } - ); -}; - -var read = function(self, length, buffer, options, callback) { - // The data is a c-terminated string and thus the length - 1 - var finalLength = length == null ? self.length - self.position : length; - var finalBuffer = buffer == null ? Buffer.alloc(finalLength) : buffer; - // Add a index to buffer to keep track of writing position or apply current index - finalBuffer._index = buffer != null && buffer._index != null ? buffer._index : 0; - - if (self.currentChunk.length() - self.currentChunk.position + finalBuffer._index >= finalLength) { - var slice = self.currentChunk.readSlice(finalLength - finalBuffer._index); - // Copy content to final buffer - slice.copy(finalBuffer, finalBuffer._index); - // Update internal position - self.position = self.position + finalBuffer.length; - // Check if we don't have a file at all - if (finalLength === 0 && finalBuffer.length === 0) - return callback(MongoError.create({ message: 'File does not exist', driver: true }), null); - // Else return data - return callback(null, finalBuffer); - } - - // Read the next chunk - slice = self.currentChunk.readSlice(self.currentChunk.length() - self.currentChunk.position); - // Copy content to final buffer - slice.copy(finalBuffer, finalBuffer._index); - // Update index position - finalBuffer._index += slice.length; - - // Load next chunk and read more - nthChunk(self, self.currentChunk.chunkNumber + 1, function(err, chunk) { - if (err) return callback(err); - - if (chunk.length() > 0) { - self.currentChunk = chunk; - self.read(length, finalBuffer, callback); - } else { - if (finalBuffer._index > 0) { - callback(null, finalBuffer); - } else { - callback( - MongoError.create({ - message: 'no chunks found for file, possibly corrupt', - driver: true - }), - null - ); - } - } - }); -}; - -/** - * The tell callback format. - * @callback GridStore~tellCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {number} position The current read position in the GridStore. - */ - -/** - * Retrieves the position of the read/write head of this file. - * - * @method - * @param {number} [length] the number of characters to read. Reads all the characters from the read/write head to the EOF if not specified. - * @param {(string|Buffer)} [buffer] a string to hold temporary data. This is used for storing the string data read so far when recursively calling this method. - * @param {object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {GridStore~tellCallback} [callback] the command callback. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.tell = function(callback) { - var self = this; - // We provided a callback leg - if (typeof callback === 'function') return callback(null, this.position); - // Return promise - return new self.promiseLibrary(function(resolve) { - resolve(self.position); - }); -}; - -/** - * The tell callback format. - * @callback GridStore~gridStoreCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {GridStore} gridStore The gridStore. - */ - -/** - * Moves the read/write head to a new location. - * - * There are 3 signatures for this method - * - * Seek Location Modes - * - **GridStore.IO_SEEK_SET**, **(default)** set the position from the start of the file. - * - **GridStore.IO_SEEK_CUR**, set the position from the current position in the file. - * - **GridStore.IO_SEEK_END**, set the position from the end of the file. - * - * @method - * @param {number} [position] the position to seek to - * @param {number} [seekLocation] seek mode. Use one of the Seek Location modes. - * @param {object} [options] Optional settings - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {GridStore~gridStoreCallback} [callback] the command callback. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.prototype.seek = function(position, seekLocation, options, callback) { - var args = Array.prototype.slice.call(arguments, 1); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - seekLocation = args.length ? args.shift() : null; - options = args.length ? args.shift() : {}; - - return executeLegacyOperation( - this.db.s.topology, - seek, - [this, position, seekLocation, options, callback], - { skipSessions: true } - ); -}; - -var seek = function(self, position, seekLocation, options, callback) { - // Seek only supports read mode - if (self.mode !== 'r') { - return callback( - MongoError.create({ message: 'seek is only supported for mode r', driver: true }) - ); - } - - var seekLocationFinal = seekLocation == null ? GridStore.IO_SEEK_SET : seekLocation; - var finalPosition = position; - var targetPosition = 0; - - // Calculate the position - if (seekLocationFinal === GridStore.IO_SEEK_CUR) { - targetPosition = self.position + finalPosition; - } else if (seekLocationFinal === GridStore.IO_SEEK_END) { - targetPosition = self.length + finalPosition; - } else { - targetPosition = finalPosition; - } - - // Get the chunk - var newChunkNumber = Math.floor(targetPosition / self.chunkSize); - var seekChunk = function() { - nthChunk(self, newChunkNumber, function(err, chunk) { - if (err) return callback(err, null); - if (chunk == null) return callback(new Error('no chunk found')); - - // Set the current chunk - self.currentChunk = chunk; - self.position = targetPosition; - self.currentChunk.position = self.position % self.chunkSize; - callback(err, self); - }); - }; - - seekChunk(); -}; - -/** - * @ignore - */ -var _open = function(self, options, callback) { - var collection = self.collection(); - // Create the query - var query = - self.referenceBy === REFERENCE_BY_ID ? { _id: self.fileId } : { filename: self.filename }; - query = null == self.fileId && self.filename == null ? null : query; - options.readPreference = self.readPreference; - - // Fetch the chunks - if (query != null) { - collection.findOne(query, options, function(err, doc) { - if (err) { - return error(err); - } - - // Check if the collection for the files exists otherwise prepare the new one - if (doc != null) { - self.fileId = doc._id; - // Prefer a new filename over the existing one if this is a write - self.filename = - self.mode === 'r' || self.filename === undefined ? doc.filename : self.filename; - self.contentType = doc.contentType; - self.internalChunkSize = doc.chunkSize; - self.uploadDate = doc.uploadDate; - self.aliases = doc.aliases; - self.length = doc.length; - self.metadata = doc.metadata; - self.internalMd5 = doc.md5; - } else if (self.mode !== 'r') { - self.fileId = self.fileId == null ? new ObjectID() : self.fileId; - self.contentType = GridStore.DEFAULT_CONTENT_TYPE; - self.internalChunkSize = - self.internalChunkSize == null ? Chunk.DEFAULT_CHUNK_SIZE : self.internalChunkSize; - self.length = 0; - } else { - self.length = 0; - var txtId = self.fileId._bsontype === 'ObjectID' ? self.fileId.toHexString() : self.fileId; - return error( - MongoError.create({ - message: f( - 'file with id %s not opened for writing', - self.referenceBy === REFERENCE_BY_ID ? txtId : self.filename - ), - driver: true - }), - self - ); - } - - // Process the mode of the object - if (self.mode === 'r') { - nthChunk(self, 0, options, function(err, chunk) { - if (err) return error(err); - self.currentChunk = chunk; - self.position = 0; - callback(null, self); - }); - } else if (self.mode === 'w' && doc) { - // Delete any existing chunks - deleteChunks(self, options, function(err) { - if (err) return error(err); - self.currentChunk = new Chunk(self, { n: 0 }, self.writeConcern); - self.contentType = - self.options['content_type'] == null ? self.contentType : self.options['content_type']; - self.internalChunkSize = - self.options['chunk_size'] == null - ? self.internalChunkSize - : self.options['chunk_size']; - self.metadata = - self.options['metadata'] == null ? self.metadata : self.options['metadata']; - self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; - self.position = 0; - callback(null, self); - }); - } else if (self.mode === 'w') { - self.currentChunk = new Chunk(self, { n: 0 }, self.writeConcern); - self.contentType = - self.options['content_type'] == null ? self.contentType : self.options['content_type']; - self.internalChunkSize = - self.options['chunk_size'] == null ? self.internalChunkSize : self.options['chunk_size']; - self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata']; - self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; - self.position = 0; - callback(null, self); - } else if (self.mode === 'w+') { - nthChunk(self, lastChunkNumber(self), options, function(err, chunk) { - if (err) return error(err); - // Set the current chunk - self.currentChunk = chunk == null ? new Chunk(self, { n: 0 }, self.writeConcern) : chunk; - self.currentChunk.position = self.currentChunk.data.length(); - self.metadata = - self.options['metadata'] == null ? self.metadata : self.options['metadata']; - self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; - self.position = self.length; - callback(null, self); - }); - } - }); - } else { - // Write only mode - self.fileId = null == self.fileId ? new ObjectID() : self.fileId; - self.contentType = GridStore.DEFAULT_CONTENT_TYPE; - self.internalChunkSize = - self.internalChunkSize == null ? Chunk.DEFAULT_CHUNK_SIZE : self.internalChunkSize; - self.length = 0; - - // No file exists set up write mode - if (self.mode === 'w') { - // Delete any existing chunks - deleteChunks(self, options, function(err) { - if (err) return error(err); - self.currentChunk = new Chunk(self, { n: 0 }, self.writeConcern); - self.contentType = - self.options['content_type'] == null ? self.contentType : self.options['content_type']; - self.internalChunkSize = - self.options['chunk_size'] == null ? self.internalChunkSize : self.options['chunk_size']; - self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata']; - self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; - self.position = 0; - callback(null, self); - }); - } else if (self.mode === 'w+') { - nthChunk(self, lastChunkNumber(self), options, function(err, chunk) { - if (err) return error(err); - // Set the current chunk - self.currentChunk = chunk == null ? new Chunk(self, { n: 0 }, self.writeConcern) : chunk; - self.currentChunk.position = self.currentChunk.data.length(); - self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata']; - self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; - self.position = self.length; - callback(null, self); - }); - } - } - - // only pass error to callback once - function error(err) { - if (error.err) return; - callback((error.err = err)); - } -}; - -/** - * @ignore - */ -var writeBuffer = function(self, buffer, close, callback) { - if (typeof close === 'function') { - callback = close; - close = null; - } - var finalClose = typeof close === 'boolean' ? close : false; - - if (self.mode !== 'w') { - callback( - MongoError.create({ - message: f( - 'file with id %s not opened for writing', - self.referenceBy === REFERENCE_BY_ID ? self.referenceBy : self.filename - ), - driver: true - }), - null - ); - } else { - if (self.currentChunk.position + buffer.length >= self.chunkSize) { - // Write out the current Chunk and then keep writing until we have less data left than a chunkSize left - // to a new chunk (recursively) - var previousChunkNumber = self.currentChunk.chunkNumber; - var leftOverDataSize = self.chunkSize - self.currentChunk.position; - var firstChunkData = buffer.slice(0, leftOverDataSize); - var leftOverData = buffer.slice(leftOverDataSize); - // A list of chunks to write out - var chunksToWrite = [self.currentChunk.write(firstChunkData)]; - // If we have more data left than the chunk size let's keep writing new chunks - while (leftOverData.length >= self.chunkSize) { - // Create a new chunk and write to it - var newChunk = new Chunk(self, { n: previousChunkNumber + 1 }, self.writeConcern); - firstChunkData = leftOverData.slice(0, self.chunkSize); - leftOverData = leftOverData.slice(self.chunkSize); - // Update chunk number - previousChunkNumber = previousChunkNumber + 1; - // Write data - newChunk.write(firstChunkData); - // Push chunk to save list - chunksToWrite.push(newChunk); - } - - // Set current chunk with remaining data - self.currentChunk = new Chunk(self, { n: previousChunkNumber + 1 }, self.writeConcern); - // If we have left over data write it - if (leftOverData.length > 0) self.currentChunk.write(leftOverData); - - // Update the position for the gridstore - self.position = self.position + buffer.length; - // Total number of chunks to write - var numberOfChunksToWrite = chunksToWrite.length; - - for (var i = 0; i < chunksToWrite.length; i++) { - chunksToWrite[i].save({}, function(err) { - if (err) return callback(err); - - numberOfChunksToWrite = numberOfChunksToWrite - 1; - - if (numberOfChunksToWrite <= 0) { - // We care closing the file before returning - if (finalClose) { - return self.close(function(err) { - callback(err, self); - }); - } - - // Return normally - return callback(null, self); - } - }); - } - } else { - // Update the position for the gridstore - self.position = self.position + buffer.length; - // We have less data than the chunk size just write it and callback - self.currentChunk.write(buffer); - // We care closing the file before returning - if (finalClose) { - return self.close(function(err) { - callback(err, self); - }); - } - // Return normally - return callback(null, self); - } - } -}; - -/** - * Creates a mongoDB object representation of this object. - * - *

- *        {
- *          '_id' : , // {number} id for this file
- *          'filename' : , // {string} name for this file
- *          'contentType' : , // {string} mime type for this file
- *          'length' : , // {number} size of this file?
- *          'chunksize' : , // {number} chunk size used by this file
- *          'uploadDate' : , // {Date}
- *          'aliases' : , // {array of string}
- *          'metadata' : , // {string}
- *        }
- *        
- * - * @ignore - */ -var buildMongoObject = function(self, callback) { - // Calcuate the length - var mongoObject = { - _id: self.fileId, - filename: self.filename, - contentType: self.contentType, - length: self.position ? self.position : 0, - chunkSize: self.chunkSize, - uploadDate: self.uploadDate, - aliases: self.aliases, - metadata: self.metadata - }; - - var md5Command = { filemd5: self.fileId, root: self.root }; - self.db.command(md5Command, function(err, results) { - if (err) return callback(err); - - mongoObject.md5 = results.md5; - callback(null, mongoObject); - }); -}; - -/** - * Gets the nth chunk of this file. - * @ignore - */ -var nthChunk = function(self, chunkNumber, options, callback) { - if (typeof options === 'function') { - callback = options; - options = {}; - } - - options = options || self.writeConcern; - options.readPreference = self.readPreference; - // Get the nth chunk - self - .chunkCollection() - .findOne({ files_id: self.fileId, n: chunkNumber }, options, function(err, chunk) { - if (err) return callback(err); - - var finalChunk = chunk == null ? {} : chunk; - callback(null, new Chunk(self, finalChunk, self.writeConcern)); - }); -}; - -/** - * @ignore - */ -var lastChunkNumber = function(self) { - return Math.floor((self.length ? self.length - 1 : 0) / self.chunkSize); -}; - -/** - * Deletes all the chunks of this file in the database. - * - * @ignore - */ -var deleteChunks = function(self, options, callback) { - if (typeof options === 'function') { - callback = options; - options = {}; - } - - options = options || self.writeConcern; - - if (self.fileId != null) { - self.chunkCollection().remove({ files_id: self.fileId }, options, function(err) { - if (err) return callback(err, false); - callback(null, true); - }); - } else { - callback(null, true); - } -}; - -/** - * The collection to be used for holding the files and chunks collection. - * - * @classconstant DEFAULT_ROOT_COLLECTION - */ -GridStore.DEFAULT_ROOT_COLLECTION = 'fs'; - -/** - * Default file mime type - * - * @classconstant DEFAULT_CONTENT_TYPE - */ -GridStore.DEFAULT_CONTENT_TYPE = 'binary/octet-stream'; - -/** - * Seek mode where the given length is absolute. - * - * @classconstant IO_SEEK_SET - */ -GridStore.IO_SEEK_SET = 0; - -/** - * Seek mode where the given length is an offset to the current read/write head. - * - * @classconstant IO_SEEK_CUR - */ -GridStore.IO_SEEK_CUR = 1; - -/** - * Seek mode where the given length is an offset to the end of the file. - * - * @classconstant IO_SEEK_END - */ -GridStore.IO_SEEK_END = 2; - -/** - * Checks if a file exists in the database. - * - * @method - * @static - * @param {Db} db the database to query. - * @param {string} name The name of the file to look for. - * @param {string} [rootCollection] The root collection that holds the files and chunks collection. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**. - * @param {object} [options] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {GridStore~resultCallback} [callback] result from exists. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.exist = function(db, fileIdObject, rootCollection, options, callback) { - var args = Array.prototype.slice.call(arguments, 2); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - rootCollection = args.length ? args.shift() : null; - options = args.length ? args.shift() : {}; - options = options || {}; - - return executeLegacyOperation( - db.s.topology, - exists, - [db, fileIdObject, rootCollection, options, callback], - { skipSessions: true } - ); -}; - -var exists = function(db, fileIdObject, rootCollection, options, callback) { - // Establish read preference - var readPreference = options.readPreference || ReadPreference.PRIMARY; - // Fetch collection - var rootCollectionFinal = - rootCollection != null ? rootCollection : GridStore.DEFAULT_ROOT_COLLECTION; - db.collection(rootCollectionFinal + '.files', function(err, collection) { - if (err) return callback(err); - - // Build query - var query = - typeof fileIdObject === 'string' || - Object.prototype.toString.call(fileIdObject) === '[object RegExp]' - ? { filename: fileIdObject } - : { _id: fileIdObject }; // Attempt to locate file - - // We have a specific query - if ( - fileIdObject != null && - typeof fileIdObject === 'object' && - Object.prototype.toString.call(fileIdObject) !== '[object RegExp]' - ) { - query = fileIdObject; - } - - // Check if the entry exists - collection.findOne(query, { readPreference: readPreference }, function(err, item) { - if (err) return callback(err); - callback(null, item == null ? false : true); - }); - }); -}; - -/** - * Gets the list of files stored in the GridFS. - * - * @method - * @static - * @param {Db} db the database to query. - * @param {string} [rootCollection] The root collection that holds the files and chunks collection. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**. - * @param {object} [options] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {GridStore~resultCallback} [callback] result from exists. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.list = function(db, rootCollection, options, callback) { - var args = Array.prototype.slice.call(arguments, 1); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - rootCollection = args.length ? args.shift() : null; - options = args.length ? args.shift() : {}; - options = options || {}; - - return executeLegacyOperation(db.s.topology, list, [db, rootCollection, options, callback], { - skipSessions: true - }); -}; - -var list = function(db, rootCollection, options, callback) { - // Ensure we have correct values - if (rootCollection != null && typeof rootCollection === 'object') { - options = rootCollection; - rootCollection = null; - } - - // Establish read preference - var readPreference = options.readPreference || ReadPreference.primary; - // Check if we are returning by id not filename - var byId = options['id'] != null ? options['id'] : false; - // Fetch item - var rootCollectionFinal = - rootCollection != null ? rootCollection : GridStore.DEFAULT_ROOT_COLLECTION; - var items = []; - db.collection(rootCollectionFinal + '.files', function(err, collection) { - if (err) return callback(err); - - collection.find({}, { readPreference: readPreference }, function(err, cursor) { - if (err) return callback(err); - - cursor.each(function(err, item) { - if (item != null) { - items.push(byId ? item._id : item.filename); - } else { - callback(err, items); - } - }); - }); - }); -}; - -/** - * Reads the contents of a file. - * - * This method has the following signatures - * - * (db, name, callback) - * (db, name, length, callback) - * (db, name, length, offset, callback) - * (db, name, length, offset, options, callback) - * - * @method - * @static - * @param {Db} db the database to query. - * @param {string} name The name of the file. - * @param {number} [length] The size of data to read. - * @param {number} [offset] The offset from the head of the file of which to start reading from. - * @param {object} [options] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {GridStore~readCallback} [callback] the command callback. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.read = function(db, name, length, offset, options, callback) { - var args = Array.prototype.slice.call(arguments, 2); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - length = args.length ? args.shift() : null; - offset = args.length ? args.shift() : null; - options = args.length ? args.shift() : null; - options = options || {}; - - return executeLegacyOperation( - db.s.topology, - readStatic, - [db, name, length, offset, options, callback], - { skipSessions: true } - ); -}; - -var readStatic = function(db, name, length, offset, options, callback) { - new GridStore(db, name, 'r', options).open(function(err, gridStore) { - if (err) return callback(err); - // Make sure we are not reading out of bounds - if (offset && offset >= gridStore.length) - return callback('offset larger than size of file', null); - if (length && length > gridStore.length) - return callback('length is larger than the size of the file', null); - if (offset && length && offset + length > gridStore.length) - return callback('offset and length is larger than the size of the file', null); - - if (offset != null) { - gridStore.seek(offset, function(err, gridStore) { - if (err) return callback(err); - gridStore.read(length, callback); - }); - } else { - gridStore.read(length, callback); - } - }); -}; - -/** - * Read the entire file as a list of strings splitting by the provided separator. - * - * @method - * @static - * @param {Db} db the database to query. - * @param {(String|object)} name the name of the file. - * @param {string} [separator] The character to be recognized as the newline separator. - * @param {object} [options] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {GridStore~readlinesCallback} [callback] the command callback. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.readlines = function(db, name, separator, options, callback) { - var args = Array.prototype.slice.call(arguments, 2); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - separator = args.length ? args.shift() : null; - options = args.length ? args.shift() : null; - options = options || {}; - - return executeLegacyOperation( - db.s.topology, - readlinesStatic, - [db, name, separator, options, callback], - { skipSessions: true } - ); -}; - -var readlinesStatic = function(db, name, separator, options, callback) { - var finalSeperator = separator == null ? '\n' : separator; - new GridStore(db, name, 'r', options).open(function(err, gridStore) { - if (err) return callback(err); - gridStore.readlines(finalSeperator, callback); - }); -}; - -/** - * Deletes the chunks and metadata information of a file from GridFS. - * - * @method - * @static - * @param {Db} db The database to query. - * @param {(string|array)} names The name/names of the files to delete. - * @param {object} [options] Optional settings. - * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {ClientSession} [options.session] optional session to use for this operation - * @param {GridStore~resultCallback} [callback] the command callback. - * @return {Promise} returns Promise if no callback passed - * @deprecated Use GridFSBucket API instead - */ -GridStore.unlink = function(db, names, options, callback) { - var args = Array.prototype.slice.call(arguments, 2); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - options = args.length ? args.shift() : {}; - options = options || {}; - - return executeLegacyOperation(db.s.topology, unlinkStatic, [this, db, names, options, callback], { - skipSessions: true - }); -}; - -var unlinkStatic = function(self, db, names, options, callback) { - // Get the write concern - var writeConcern = _getWriteConcern(db, options); - - // List of names - if (names.constructor === Array) { - var tc = 0; - for (var i = 0; i < names.length; i++) { - ++tc; - GridStore.unlink(db, names[i], options, function() { - if (--tc === 0) { - callback(null, self); - } - }); - } - } else { - new GridStore(db, names, 'w', options).open(function(err, gridStore) { - if (err) return callback(err); - deleteChunks(gridStore, function(err) { - if (err) return callback(err); - gridStore.collection(function(err, collection) { - if (err) return callback(err); - collection.remove({ _id: gridStore.fileId }, writeConcern, function(err) { - callback(err, self); - }); - }); - }); - }); - } -}; - -/** - * @ignore - */ -var _writeNormal = function(self, data, close, options, callback) { - // If we have a buffer write it using the writeBuffer method - if (Buffer.isBuffer(data)) { - return writeBuffer(self, data, close, callback); - } else { - return writeBuffer(self, Buffer.from(data, 'binary'), close, callback); - } -}; - -/** - * @ignore - */ -var _setWriteConcernHash = function(options) { - var finalOptions = {}; - if (options.w != null) finalOptions.w = options.w; - if (options.journal === true) finalOptions.j = options.journal; - if (options.j === true) finalOptions.j = options.j; - if (options.fsync === true) finalOptions.fsync = options.fsync; - if (options.wtimeout != null) finalOptions.wtimeout = options.wtimeout; - return finalOptions; -}; - -/** - * @ignore - */ -var _getWriteConcern = function(self, options) { - // Final options - var finalOptions = { w: 1 }; - options = options || {}; - - // Local options verification - if ( - options.w != null || - typeof options.j === 'boolean' || - typeof options.journal === 'boolean' || - typeof options.fsync === 'boolean' - ) { - finalOptions = _setWriteConcernHash(options); - } else if (options.safe != null && typeof options.safe === 'object') { - finalOptions = _setWriteConcernHash(options.safe); - } else if (typeof options.safe === 'boolean') { - finalOptions = { w: options.safe ? 1 : 0 }; - } else if ( - self.options.w != null || - typeof self.options.j === 'boolean' || - typeof self.options.journal === 'boolean' || - typeof self.options.fsync === 'boolean' - ) { - finalOptions = _setWriteConcernHash(self.options); - } else if ( - self.safe && - (self.safe.w != null || - typeof self.safe.j === 'boolean' || - typeof self.safe.journal === 'boolean' || - typeof self.safe.fsync === 'boolean') - ) { - finalOptions = _setWriteConcernHash(self.safe); - } else if (typeof self.safe === 'boolean') { - finalOptions = { w: self.safe ? 1 : 0 }; - } - - // Ensure we don't have an invalid combination of write concerns - if ( - finalOptions.w < 1 && - (finalOptions.journal === true || finalOptions.j === true || finalOptions.fsync === true) - ) - throw MongoError.create({ - message: 'No acknowledgement using w < 1 cannot be combined with journal:true or fsync:true', - driver: true - }); - - // Return the options - return finalOptions; -}; - -/** - * Create a new GridStoreStream instance (INTERNAL TYPE, do not instantiate directly) - * - * @class - * @extends external:Duplex - * @return {GridStoreStream} a GridStoreStream instance. - * @deprecated Use GridFSBucket API instead - */ -var GridStoreStream = function(gs) { - // Initialize the duplex stream - Duplex.call(this); - - // Get the gridstore - this.gs = gs; - - // End called - this.endCalled = false; - - // If we have a seek - this.totalBytesToRead = this.gs.length - this.gs.position; - this.seekPosition = this.gs.position; -}; - -// -// Inherit duplex -inherits(GridStoreStream, Duplex); - -GridStoreStream.prototype._pipe = GridStoreStream.prototype.pipe; - -// Set up override -GridStoreStream.prototype.pipe = function(destination) { - var self = this; - - // Only open gridstore if not already open - if (!self.gs.isOpen) { - self.gs.open(function(err) { - if (err) return self.emit('error', err); - self.totalBytesToRead = self.gs.length - self.gs.position; - self._pipe.apply(self, [destination]); - }); - } else { - self.totalBytesToRead = self.gs.length - self.gs.position; - self._pipe.apply(self, [destination]); - } - - return destination; -}; - -// Called by stream -GridStoreStream.prototype._read = function() { - var self = this; - - var read = function() { - // Read data - self.gs.read(length, function(err, buffer) { - if (err && !self.endCalled) return self.emit('error', err); - - // Stream is closed - if (self.endCalled || buffer == null) return self.push(null); - // Remove bytes read - if (buffer.length <= self.totalBytesToRead) { - self.totalBytesToRead = self.totalBytesToRead - buffer.length; - self.push(buffer); - } else if (buffer.length > self.totalBytesToRead) { - self.totalBytesToRead = self.totalBytesToRead - buffer._index; - self.push(buffer.slice(0, buffer._index)); - } - - // Finished reading - if (self.totalBytesToRead <= 0) { - self.endCalled = true; - } - }); - }; - - // Set read length - var length = - self.gs.length < self.gs.chunkSize ? self.gs.length - self.seekPosition : self.gs.chunkSize; - if (!self.gs.isOpen) { - self.gs.open(function(err) { - self.totalBytesToRead = self.gs.length - self.gs.position; - if (err) return self.emit('error', err); - read(); - }); - } else { - read(); - } -}; - -GridStoreStream.prototype.destroy = function() { - this.pause(); - this.endCalled = true; - this.gs.close(); - this.emit('end'); -}; - -GridStoreStream.prototype.write = function(chunk) { - var self = this; - if (self.endCalled) - return self.emit( - 'error', - MongoError.create({ message: 'attempting to write to stream after end called', driver: true }) - ); - // Do we have to open the gridstore - if (!self.gs.isOpen) { - self.gs.open(function() { - self.gs.isOpen = true; - self.gs.write(chunk, function() { - process.nextTick(function() { - self.emit('drain'); - }); - }); - }); - return false; - } else { - self.gs.write(chunk, function() { - self.emit('drain'); - }); - return true; - } -}; - -GridStoreStream.prototype.end = function(chunk, encoding, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 0); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - chunk = args.length ? args.shift() : null; - encoding = args.length ? args.shift() : null; - self.endCalled = true; - - if (chunk) { - self.gs.write(chunk, function() { - self.gs.close(function() { - if (typeof callback === 'function') callback(); - self.emit('end'); - }); - }); - } - - self.gs.close(function() { - if (typeof callback === 'function') callback(); - self.emit('end'); - }); -}; - -/** - * The read() method pulls some data out of the internal buffer and returns it. If there is no data available, then it will return null. - * @function external:Duplex#read - * @param {number} size Optional argument to specify how much data to read. - * @return {(String | Buffer | null)} - */ - -/** - * Call this function to cause the stream to return strings of the specified encoding instead of Buffer objects. - * @function external:Duplex#setEncoding - * @param {string} encoding The encoding to use. - * @return {null} - */ - -/** - * This method will cause the readable stream to resume emitting data events. - * @function external:Duplex#resume - * @return {null} - */ - -/** - * This method will cause a stream in flowing-mode to stop emitting data events. Any data that becomes available will remain in the internal buffer. - * @function external:Duplex#pause - * @return {null} - */ - -/** - * This method pulls all the data out of a readable stream, and writes it to the supplied destination, automatically managing the flow so that the destination is not overwhelmed by a fast readable stream. - * @function external:Duplex#pipe - * @param {Writable} destination The destination for writing data - * @param {object} [options] Pipe options - * @return {null} - */ - -/** - * This method will remove the hooks set up for a previous pipe() call. - * @function external:Duplex#unpipe - * @param {Writable} [destination] The destination for writing data - * @return {null} - */ - -/** - * This is useful in certain cases where a stream is being consumed by a parser, which needs to "un-consume" some data that it has optimistically pulled out of the source, so that the stream can be passed on to some other party. - * @function external:Duplex#unshift - * @param {(Buffer|string)} chunk Chunk of data to unshift onto the read queue. - * @return {null} - */ - -/** - * Versions of Node prior to v0.10 had streams that did not implement the entire Streams API as it is today. (See "Compatibility" below for more information.) - * @function external:Duplex#wrap - * @param {Stream} stream An "old style" readable stream. - * @return {null} - */ - -/** - * This method writes some data to the underlying system, and calls the supplied callback once the data has been fully handled. - * @function external:Duplex#write - * @param {(string|Buffer)} chunk The data to write - * @param {string} encoding The encoding, if chunk is a String - * @param {function} callback Callback for when this chunk of data is flushed - * @return {boolean} - */ - -/** - * Call this method when no more data will be written to the stream. If supplied, the callback is attached as a listener on the finish event. - * @function external:Duplex#end - * @param {(string|Buffer)} chunk The data to write - * @param {string} encoding The encoding, if chunk is a String - * @param {function} callback Callback for when this chunk of data is flushed - * @return {null} - */ - -/** - * GridStoreStream stream data event, fired for each document in the cursor. - * - * @event GridStoreStream#data - * @type {object} - */ - -/** - * GridStoreStream stream end event - * - * @event GridStoreStream#end - * @type {null} - */ - -/** - * GridStoreStream stream close event - * - * @event GridStoreStream#close - * @type {null} - */ - -/** - * GridStoreStream stream readable event - * - * @event GridStoreStream#readable - * @type {null} - */ - -/** - * GridStoreStream stream drain event - * - * @event GridStoreStream#drain - * @type {null} - */ - -/** - * GridStoreStream stream finish event - * - * @event GridStoreStream#finish - * @type {null} - */ - -/** - * GridStoreStream stream pipe event - * - * @event GridStoreStream#pipe - * @type {null} - */ - -/** - * GridStoreStream stream unpipe event - * - * @event GridStoreStream#unpipe - * @type {null} - */ - -/** - * GridStoreStream stream error event - * - * @event GridStoreStream#error - * @type {null} - */ - -/** - * @ignore - */ -module.exports = GridStore; diff --git a/scripts/node_modules/mongodb/lib/mongo_client.js b/scripts/node_modules/mongodb/lib/mongo_client.js deleted file mode 100644 index 703eda64..00000000 --- a/scripts/node_modules/mongodb/lib/mongo_client.js +++ /dev/null @@ -1,479 +0,0 @@ -'use strict'; - -const ChangeStream = require('./change_stream'); -const Db = require('./db'); -const EventEmitter = require('events').EventEmitter; -const executeOperation = require('./operations/execute_operation'); -const inherits = require('util').inherits; -const MongoError = require('./core').MongoError; -const deprecate = require('util').deprecate; -const WriteConcern = require('./write_concern'); -const MongoDBNamespace = require('./utils').MongoDBNamespace; -const ReadPreference = require('./core/topologies/read_preference'); - -// Operations -const ConnectOperation = require('./operations/connect'); -const CloseOperation = require('./operations/close'); - -/** - * @fileOverview The **MongoClient** class is a class that allows for making Connections to MongoDB. - * - * @example - * // Connect using a MongoClient instance - * const MongoClient = require('mongodb').MongoClient; - * const test = require('assert'); - * // Connection url - * const url = 'mongodb://localhost:27017'; - * // Database Name - * const dbName = 'test'; - * // Connect using MongoClient - * const mongoClient = new MongoClient(url); - * mongoClient.connect(function(err, client) { - * const db = client.db(dbName); - * client.close(); - * }); - * - * @example - * // Connect using the MongoClient.connect static method - * const MongoClient = require('mongodb').MongoClient; - * const test = require('assert'); - * // Connection url - * const url = 'mongodb://localhost:27017'; - * // Database Name - * const dbName = 'test'; - * // Connect using MongoClient - * MongoClient.connect(url, function(err, client) { - * const db = client.db(dbName); - * client.close(); - * }); - */ - -/** - * A string specifying the level of a ReadConcern - * @typedef {'local'|'available'|'majority'|'linearizable'|'snapshot'} ReadConcernLevel - * @see https://docs.mongodb.com/manual/reference/read-concern/index.html#read-concern-levels - */ - -/** - * Configuration options for a automatic client encryption. - * - * **NOTE**: Support for client side encryption is in beta. Backwards-breaking changes may be made before the final release. - * - * @typedef {Object} AutoEncryptionOptions - * @property {MongoClient} [keyVaultClient] A `MongoClient` used to fetch keys from a key vault - * @property {string} [keyVaultNamespace] The namespace where keys are stored in the key vault - * @property {object} [kmsProviders] Provider details for the desired Key Management Service to use for encryption - * @property {object} [kmsProviders.aws] Optional settings for the AWS KMS provider - * @property {string} [kmsProviders.aws.accessKeyId] The access key used for the AWS KMS provider - * @property {string} [kmsProviders.aws.secretAccessKey] The secret access key used for the AWS KMS provider - * @property {object} [kmsProviders.local] Optional settings for the local KMS provider - * @property {string} [kmsProviders.local.key] The master key used to encrypt/decrypt data keys - * @property {object} [schemaMap] A map of namespaces to a local JSON schema for encryption - * @property {boolean} [bypassAutoEncryption] Allows the user to bypass auto encryption, maintaining implicit decryption - * @property {object} [extraOptions] Extra options related to the mongocryptd process - * @property {string} [extraOptions.mongocryptURI] A local process the driver communicates with to determine how to encrypt values in a command. Defaults to "mongodb://%2Fvar%2Fmongocryptd.sock" if domain sockets are available or "mongodb://localhost:27020" otherwise - * @property {boolean} [extraOptions.mongocryptdBypassSpawn=false] If true, autoEncryption will not attempt to spawn a mongocryptd before connecting - * @property {string} [extraOptions.mongocryptdSpawnPath] The path to the mongocryptd executable on the system - * @property {string[]} [extraOptions.mongocryptdSpawnArgs] Command line arguments to use when auto-spawning a mongocryptd - */ - -/** - * Creates a new MongoClient instance - * @class - * @param {string} url The connection URI string - * @param {object} [options] Optional settings - * @param {number} [options.poolSize=5] The maximum size of the individual server pool - * @param {boolean} [options.ssl=false] Enable SSL connection. - * @param {boolean} [options.sslValidate=false] Validate mongod server certificate against Certificate Authority - * @param {buffer} [options.sslCA=undefined] SSL Certificate store binary buffer - * @param {buffer} [options.sslCert=undefined] SSL Certificate binary buffer - * @param {buffer} [options.sslKey=undefined] SSL Key file binary buffer - * @param {string} [options.sslPass=undefined] SSL Certificate pass phrase - * @param {buffer} [options.sslCRL=undefined] SSL Certificate revocation list binary buffer - * @param {boolean} [options.autoReconnect=true] Enable autoReconnect for single server instances - * @param {boolean} [options.noDelay=true] TCP Connection no delay - * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled - * @param {number} [options.keepAliveInitialDelay=30000] The number of milliseconds to wait before initiating keepAlive on the TCP socket - * @param {number} [options.connectTimeoutMS=30000] TCP Connection timeout setting - * @param {number} [options.family] Version of IP stack. Can be 4, 6 or null (default). - * If null, will attempt to connect with IPv6, and will fall back to IPv4 on failure - * @param {number} [options.socketTimeoutMS=360000] TCP Socket timeout setting - * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times - * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries - * @param {boolean} [options.ha=true] Control if high availability monitoring runs for Replicaset or Mongos proxies - * @param {number} [options.haInterval=10000] The High availability period for replicaset inquiry - * @param {string} [options.replicaSet=undefined] The Replicaset set name - * @param {number} [options.secondaryAcceptableLatencyMS=15] Cutoff latency point in MS for Replicaset member selection - * @param {number} [options.acceptableLatencyMS=15] Cutoff latency point in MS for Mongos proxies selection - * @param {boolean} [options.connectWithNoPrimary=false] Sets if the driver should connect even if no primary is available - * @param {string} [options.authSource=undefined] Define the database to authenticate against - * @param {(number|string)} [options.w] The write concern - * @param {number} [options.wtimeout] The write concern timeout - * @param {boolean} [options.j=false] Specify a journal write concern - * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields - * @param {boolean} [options.raw=false] Return document results as raw BSON buffers - * @param {number} [options.bufferMaxEntries=-1] Sets a cap on how many operations the driver will buffer up before giving up on getting a working connection, default is -1 which is unlimited - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST) - * @param {object} [options.pkFactory] A primary key factory object for generation of custom _id keys - * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {object} [options.readConcern] Specify a read concern for the collection (only MongoDB 3.2 or higher supported) - * @param {ReadConcernLevel} [options.readConcern.level='local'] Specify a read concern level for the collection operations (only MongoDB 3.2 or higher supported) - * @param {number} [options.maxStalenessSeconds=undefined] The max staleness to secondary reads (values under 10 seconds cannot be guaranteed) - * @param {string} [options.loggerLevel=undefined] The logging level (error/warn/info/debug) - * @param {object} [options.logger=undefined] Custom logger object - * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types - * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers - * @param {boolean} [options.promoteLongs=true] Promotes long values to number if they fit inside the 53 bits resolution - * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit - * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function - * @param {object} [options.validateOptions=false] Validate MongoClient passed in options for correctness - * @param {string} [options.appname=undefined] The name of the application that created this MongoClient instance. MongoDB 3.4 and newer will print this value in the server log upon establishing each connection. It is also recorded in the slow query log and profile collections - * @param {string} [options.auth.user=undefined] The username for auth - * @param {string} [options.auth.password=undefined] The password for auth - * @param {string} [options.authMechanism=undefined] Mechanism for authentication: MDEFAULT, GSSAPI, PLAIN, MONGODB-X509, or SCRAM-SHA-1 - * @param {object} [options.compression] Type of compression to use: snappy or zlib - * @param {boolean} [options.fsync=false] Specify a file sync write concern - * @param {array} [options.readPreferenceTags] Read preference tags - * @param {number} [options.numberOfRetries=5] The number of retries for a tailable cursor - * @param {boolean} [options.auto_reconnect=true] Enable auto reconnecting for single server instances - * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this client - * @param {number} [options.minSize] If present, the connection pool will be initialized with minSize connections, and will never dip below minSize connections - * @param {boolean} [options.useNewUrlParser=true] Determines whether or not to use the new url parser. Enables the new, spec-compliant, url parser shipped in the core driver. This url parser fixes a number of problems with the original parser, and aims to outright replace that parser in the near future. Defaults to true, and must be explicitly set to false to use the legacy url parser. - * @param {boolean} [options.useUnifiedTopology] Enables the new unified topology layer - * @param {AutoEncryptionOptions} [options.autoEncryption] Optionally enable client side auto encryption - * @param {MongoClient~connectCallback} [callback] The command result callback - * @return {MongoClient} a MongoClient instance - */ -function MongoClient(url, options) { - if (!(this instanceof MongoClient)) return new MongoClient(url, options); - // Set up event emitter - EventEmitter.call(this); - - // The internal state - this.s = { - url: url, - options: options || {}, - promiseLibrary: null, - dbCache: new Map(), - sessions: new Set(), - writeConcern: WriteConcern.fromOptions(options), - namespace: new MongoDBNamespace('admin') - }; - - // Get the promiseLibrary - const promiseLibrary = this.s.options.promiseLibrary || Promise; - - // Add the promise to the internal state - this.s.promiseLibrary = promiseLibrary; -} - -/** - * @ignore - */ -inherits(MongoClient, EventEmitter); - -Object.defineProperty(MongoClient.prototype, 'writeConcern', { - enumerable: true, - get: function() { - return this.s.writeConcern; - } -}); - -Object.defineProperty(MongoClient.prototype, 'readPreference', { - enumerable: true, - get: function() { - return ReadPreference.primary; - } -}); - -/** - * The callback format for results - * @callback MongoClient~connectCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {MongoClient} client The connected client. - */ - -/** - * Connect to MongoDB using a url as documented at - * - * docs.mongodb.org/manual/reference/connection-string/ - * - * Note that for replicasets the replicaSet query parameter is required in the 2.0 driver - * - * @method - * @param {MongoClient~connectCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -MongoClient.prototype.connect = function(callback) { - if (typeof callback === 'string') { - throw new TypeError('`connect` only accepts a callback'); - } - - const operation = new ConnectOperation(this); - - return executeOperation(this, operation, callback); -}; - -MongoClient.prototype.logout = deprecate(function(options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - if (typeof callback === 'function') callback(null, true); -}, 'Multiple authentication is prohibited on a connected client, please only authenticate once per MongoClient'); - -/** - * Close the db and its underlying connections - * @method - * @param {boolean} [force=false] Force close, emitting no events - * @param {Db~noResultCallback} [callback] The result callback - * @return {Promise} returns Promise if no callback passed - */ -MongoClient.prototype.close = function(force, callback) { - if (typeof force === 'function') (callback = force), (force = false); - const operation = new CloseOperation(this, force); - return executeOperation(this, operation, callback); -}; - -/** - * Create a new Db instance sharing the current socket connections. Be aware that the new db instances are - * related in a parent-child relationship to the original instance so that events are correctly emitted on child - * db instances. Child db instances are cached so performing db('db1') twice will return the same instance. - * You can control these behaviors with the options noListener and returnNonCachedInstance. - * - * @method - * @param {string} [dbName] The name of the database we want to use. If not provided, use database name from connection string. - * @param {object} [options] Optional settings. - * @param {boolean} [options.noListener=false] Do not make the db an event listener to the original connection. - * @param {boolean} [options.returnNonCachedInstance=false] Control if you want to return a cached instance or have a new one created - * @return {Db} - */ -MongoClient.prototype.db = function(dbName, options) { - options = options || {}; - - // Default to db from connection string if not provided - if (!dbName) { - dbName = this.s.options.dbName; - } - - // Copy the options and add out internal override of the not shared flag - const finalOptions = Object.assign({}, this.s.options, options); - - // Do we have the db in the cache already - if (this.s.dbCache.has(dbName) && finalOptions.returnNonCachedInstance !== true) { - return this.s.dbCache.get(dbName); - } - - // Add promiseLibrary - finalOptions.promiseLibrary = this.s.promiseLibrary; - - // If no topology throw an error message - if (!this.topology) { - throw new MongoError('MongoClient must be connected before calling MongoClient.prototype.db'); - } - - // Return the db object - const db = new Db(dbName, this.topology, finalOptions); - - // Add the db to the cache - this.s.dbCache.set(dbName, db); - // Return the database - return db; -}; - -/** - * Check if MongoClient is connected - * - * @method - * @param {object} [options] Optional settings. - * @param {boolean} [options.noListener=false] Do not make the db an event listener to the original connection. - * @param {boolean} [options.returnNonCachedInstance=false] Control if you want to return a cached instance or have a new one created - * @return {boolean} - */ -MongoClient.prototype.isConnected = function(options) { - options = options || {}; - - if (!this.topology) return false; - return this.topology.isConnected(options); -}; - -/** - * Connect to MongoDB using a url as documented at - * - * docs.mongodb.org/manual/reference/connection-string/ - * - * Note that for replicasets the replicaSet query parameter is required in the 2.0 driver - * - * @method - * @static - * @param {string} url The connection URI string - * @param {object} [options] Optional settings - * @param {number} [options.poolSize=5] The maximum size of the individual server pool - * @param {boolean} [options.ssl=false] Enable SSL connection. - * @param {boolean} [options.sslValidate=false] Validate mongod server certificate against Certificate Authority - * @param {buffer} [options.sslCA=undefined] SSL Certificate store binary buffer - * @param {buffer} [options.sslCert=undefined] SSL Certificate binary buffer - * @param {buffer} [options.sslKey=undefined] SSL Key file binary buffer - * @param {string} [options.sslPass=undefined] SSL Certificate pass phrase - * @param {buffer} [options.sslCRL=undefined] SSL Certificate revocation list binary buffer - * @param {boolean} [options.autoReconnect=true] Enable autoReconnect for single server instances - * @param {boolean} [options.noDelay=true] TCP Connection no delay - * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled - * @param {boolean} [options.keepAliveInitialDelay=30000] The number of milliseconds to wait before initiating keepAlive on the TCP socket - * @param {number} [options.connectTimeoutMS=30000] TCP Connection timeout setting - * @param {number} [options.family] Version of IP stack. Can be 4, 6 or null (default). - * If null, will attempt to connect with IPv6, and will fall back to IPv4 on failure - * @param {number} [options.socketTimeoutMS=360000] TCP Socket timeout setting - * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times - * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries - * @param {boolean} [options.ha=true] Control if high availability monitoring runs for Replicaset or Mongos proxies - * @param {number} [options.haInterval=10000] The High availability period for replicaset inquiry - * @param {string} [options.replicaSet=undefined] The Replicaset set name - * @param {number} [options.secondaryAcceptableLatencyMS=15] Cutoff latency point in MS for Replicaset member selection - * @param {number} [options.acceptableLatencyMS=15] Cutoff latency point in MS for Mongos proxies selection - * @param {boolean} [options.connectWithNoPrimary=false] Sets if the driver should connect even if no primary is available - * @param {string} [options.authSource=undefined] Define the database to authenticate against - * @param {(number|string)} [options.w] The write concern - * @param {number} [options.wtimeout] The write concern timeout - * @param {boolean} [options.j=false] Specify a journal write concern - * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields - * @param {boolean} [options.raw=false] Return document results as raw BSON buffers - * @param {number} [options.bufferMaxEntries=-1] Sets a cap on how many operations the driver will buffer up before giving up on getting a working connection, default is -1 which is unlimited - * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST) - * @param {object} [options.pkFactory] A primary key factory object for generation of custom _id keys - * @param {object} [options.promiseLibrary] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {object} [options.readConcern] Specify a read concern for the collection (only MongoDB 3.2 or higher supported) - * @param {ReadConcernLevel} [options.readConcern.level='local'] Specify a read concern level for the collection operations (only MongoDB 3.2 or higher supported) - * @param {number} [options.maxStalenessSeconds=undefined] The max staleness to secondary reads (values under 10 seconds cannot be guaranteed) - * @param {string} [options.loggerLevel=undefined] The logging level (error/warn/info/debug) - * @param {object} [options.logger=undefined] Custom logger object - * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types - * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers - * @param {boolean} [options.promoteLongs=true] Promotes long values to number if they fit inside the 53 bits resolution - * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit - * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function - * @param {object} [options.validateOptions=false] Validate MongoClient passed in options for correctness - * @param {string} [options.appname=undefined] The name of the application that created this MongoClient instance. MongoDB 3.4 and newer will print this value in the server log upon establishing each connection. It is also recorded in the slow query log and profile collections - * @param {string} [options.auth.user=undefined] The username for auth - * @param {string} [options.auth.password=undefined] The password for auth - * @param {string} [options.authMechanism=undefined] Mechanism for authentication: MDEFAULT, GSSAPI, PLAIN, MONGODB-X509, or SCRAM-SHA-1 - * @param {object} [options.compression] Type of compression to use: snappy or zlib - * @param {boolean} [options.fsync=false] Specify a file sync write concern - * @param {array} [options.readPreferenceTags] Read preference tags - * @param {number} [options.numberOfRetries=5] The number of retries for a tailable cursor - * @param {boolean} [options.auto_reconnect=true] Enable auto reconnecting for single server instances - * @param {number} [options.minSize] If present, the connection pool will be initialized with minSize connections, and will never dip below minSize connections - * @param {MongoClient~connectCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -MongoClient.connect = function(url, options, callback) { - const args = Array.prototype.slice.call(arguments, 1); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; - options = args.length ? args.shift() : null; - options = options || {}; - - // Create client - const mongoClient = new MongoClient(url, options); - // Execute the connect method - return mongoClient.connect(callback); -}; - -/** - * Starts a new session on the server - * - * @param {SessionOptions} [options] optional settings for a driver session - * @return {ClientSession} the newly established session - */ -MongoClient.prototype.startSession = function(options) { - options = Object.assign({ explicit: true }, options); - if (!this.topology) { - throw new MongoError('Must connect to a server before calling this method'); - } - - if (!this.topology.hasSessionSupport()) { - throw new MongoError('Current topology does not support sessions'); - } - - return this.topology.startSession(options, this.s.options); -}; - -/** - * Runs a given operation with an implicitly created session. The lifetime of the session - * will be handled without the need for user interaction. - * - * NOTE: presently the operation MUST return a Promise (either explicit or implicity as an async function) - * - * @param {Object} [options] Optional settings to be appled to implicitly created session - * @param {Function} operation An operation to execute with an implicitly created session. The signature of this MUST be `(session) => {}` - * @return {Promise} - */ -MongoClient.prototype.withSession = function(options, operation) { - if (typeof options === 'function') (operation = options), (options = undefined); - const session = this.startSession(options); - - let cleanupHandler = (err, result, opts) => { - // prevent multiple calls to cleanupHandler - cleanupHandler = () => { - throw new ReferenceError('cleanupHandler was called too many times'); - }; - - opts = Object.assign({ throw: true }, opts); - session.endSession(); - - if (err) { - if (opts.throw) throw err; - return Promise.reject(err); - } - }; - - try { - const result = operation(session); - return Promise.resolve(result) - .then(result => cleanupHandler(null, result)) - .catch(err => cleanupHandler(err, null, { throw: true })); - } catch (err) { - return cleanupHandler(err, null, { throw: false }); - } -}; -/** - * Create a new Change Stream, watching for new changes (insertions, updates, replacements, deletions, and invalidations) in this cluster. Will ignore all changes to system collections, as well as the local, admin, - * and config databases. - * @method - * @since 3.1.0 - * @param {Array} [pipeline] An array of {@link https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents. - * @param {object} [options] Optional settings - * @param {string} [options.fullDocument='default'] Allowed values: ‘default’, ‘updateLookup’. When set to ‘updateLookup’, the change stream will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred. - * @param {object} [options.resumeAfter] Specifies the logical starting point for the new change stream. This should be the _id field from a previously returned change stream document. - * @param {number} [options.maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a change stream query - * @param {number} [options.batchSize=1000] The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. - * @param {object} [options.collation] Specify collation settings for operation. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. - * @param {ReadPreference} [options.readPreference] The read preference. See {@link https://docs.mongodb.com/manual/reference/read-preference|read preference documentation}. - * @param {Timestamp} [options.startAtOperationTime] receive change events that occur after the specified timestamp - * @param {ClientSession} [options.session] optional session to use for this operation - * @return {ChangeStream} a ChangeStream instance. - */ -MongoClient.prototype.watch = function(pipeline, options) { - pipeline = pipeline || []; - options = options || {}; - - // Allow optionally not specifying a pipeline - if (!Array.isArray(pipeline)) { - options = pipeline; - pipeline = []; - } - - return new ChangeStream(this, pipeline, options); -}; - -/** - * Return the mongo client logger - * @method - * @return {Logger} return the mongo client logger - * @ignore - */ -MongoClient.prototype.getLogger = function() { - return this.s.options.logger; -}; - -module.exports = MongoClient; diff --git a/scripts/node_modules/mongodb/lib/operations/add_user.js b/scripts/node_modules/mongodb/lib/operations/add_user.js deleted file mode 100644 index 1f3f3a6f..00000000 --- a/scripts/node_modules/mongodb/lib/operations/add_user.js +++ /dev/null @@ -1,96 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const CommandOperation = require('./command'); -const defineAspects = require('./operation').defineAspects; -const crypto = require('crypto'); -const handleCallback = require('../utils').handleCallback; -const toError = require('../utils').toError; - -class AddUserOperation extends CommandOperation { - constructor(db, username, password, options) { - super(db, options); - - this.username = username; - this.password = password; - } - - _buildCommand() { - const db = this.db; - const username = this.username; - const password = this.password; - const options = this.options; - - // Get additional values - let roles = Array.isArray(options.roles) ? options.roles : []; - - // If not roles defined print deprecated message - // TODO: handle deprecation properly - if (roles.length === 0) { - console.log('Creating a user without roles is deprecated in MongoDB >= 2.6'); - } - - // Check the db name and add roles if needed - if ( - (db.databaseName.toLowerCase() === 'admin' || options.dbName === 'admin') && - !Array.isArray(options.roles) - ) { - roles = ['root']; - } else if (!Array.isArray(options.roles)) { - roles = ['dbOwner']; - } - - const digestPassword = db.s.topology.lastIsMaster().maxWireVersion >= 7; - - let userPassword = password; - - if (!digestPassword) { - // Use node md5 generator - const md5 = crypto.createHash('md5'); - // Generate keys used for authentication - md5.update(username + ':mongo:' + password); - userPassword = md5.digest('hex'); - } - - // Build the command to execute - const command = { - createUser: username, - customData: options.customData || {}, - roles: roles, - digestPassword - }; - - // No password - if (typeof password === 'string') { - command.pwd = userPassword; - } - - return command; - } - - execute(callback) { - const options = this.options; - - // Error out if digestPassword set - if (options.digestPassword != null) { - return callback( - toError( - "The digestPassword option is not supported via add_user. Please use db.command('createUser', ...) instead for this option." - ) - ); - } - - // Attempt to execute auth command - super.execute((err, r) => { - if (!err) { - return handleCallback(callback, err, r); - } - - return handleCallback(callback, err, null); - }); - } -} - -defineAspects(AddUserOperation, Aspect.WRITE_OPERATION); - -module.exports = AddUserOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/admin_ops.js b/scripts/node_modules/mongodb/lib/operations/admin_ops.js deleted file mode 100644 index b08071c3..00000000 --- a/scripts/node_modules/mongodb/lib/operations/admin_ops.js +++ /dev/null @@ -1,62 +0,0 @@ -'use strict'; - -const executeCommand = require('./db_ops').executeCommand; -const executeDbAdminCommand = require('./db_ops').executeDbAdminCommand; - -/** - * Get ReplicaSet status - * - * @param {Admin} a collection instance. - * @param {Object} [options] Optional settings. See Admin.prototype.replSetGetStatus for a list of options. - * @param {Admin~resultCallback} [callback] The command result callback. - */ -function replSetGetStatus(admin, options, callback) { - executeDbAdminCommand(admin.s.db, { replSetGetStatus: 1 }, options, callback); -} - -/** - * Retrieve this db's server status. - * - * @param {Admin} a collection instance. - * @param {Object} [options] Optional settings. See Admin.prototype.serverStatus for a list of options. - * @param {Admin~resultCallback} [callback] The command result callback - */ -function serverStatus(admin, options, callback) { - executeDbAdminCommand(admin.s.db, { serverStatus: 1 }, options, callback); -} - -/** - * Validate an existing collection - * - * @param {Admin} a collection instance. - * @param {string} collectionName The name of the collection to validate. - * @param {Object} [options] Optional settings. See Admin.prototype.validateCollection for a list of options. - * @param {Admin~resultCallback} [callback] The command result callback. - */ -function validateCollection(admin, collectionName, options, callback) { - const command = { validate: collectionName }; - const keys = Object.keys(options); - - // Decorate command with extra options - for (let i = 0; i < keys.length; i++) { - if (options.hasOwnProperty(keys[i]) && keys[i] !== 'session') { - command[keys[i]] = options[keys[i]]; - } - } - - executeCommand(admin.s.db, command, options, (err, doc) => { - if (err != null) return callback(err, null); - - if (doc.ok === 0) return callback(new Error('Error with validate command'), null); - if (doc.result != null && doc.result.constructor !== String) - return callback(new Error('Error with validation data'), null); - if (doc.result != null && doc.result.match(/exception|corrupt/) != null) - return callback(new Error('Error: invalid collection ' + collectionName), null); - if (doc.valid != null && !doc.valid) - return callback(new Error('Error: invalid collection ' + collectionName), null); - - return callback(null, doc); - }); -} - -module.exports = { replSetGetStatus, serverStatus, validateCollection }; diff --git a/scripts/node_modules/mongodb/lib/operations/aggregate.js b/scripts/node_modules/mongodb/lib/operations/aggregate.js deleted file mode 100644 index e0f2da84..00000000 --- a/scripts/node_modules/mongodb/lib/operations/aggregate.js +++ /dev/null @@ -1,106 +0,0 @@ -'use strict'; - -const CommandOperationV2 = require('./command_v2'); -const MongoError = require('../core').MongoError; -const maxWireVersion = require('../core/utils').maxWireVersion; -const ReadPreference = require('../core').ReadPreference; -const Aspect = require('./operation').Aspect; -const defineAspects = require('./operation').defineAspects; - -const DB_AGGREGATE_COLLECTION = 1; -const MIN_WIRE_VERSION_$OUT_READ_CONCERN_SUPPORT = 8; - -class AggregateOperation extends CommandOperationV2 { - constructor(parent, pipeline, options) { - super(parent, options, { fullResponse: true }); - - this.target = - parent.s.namespace && parent.s.namespace.collection - ? parent.s.namespace.collection - : DB_AGGREGATE_COLLECTION; - - this.pipeline = pipeline; - - // determine if we have a write stage, override read preference if so - this.hasWriteStage = false; - if (typeof options.out === 'string') { - this.pipeline = this.pipeline.concat({ $out: options.out }); - this.hasWriteStage = true; - } else if (pipeline.length > 0) { - const finalStage = pipeline[pipeline.length - 1]; - if (finalStage.$out || finalStage.$merge) { - this.hasWriteStage = true; - } - } - - if (this.hasWriteStage) { - this.readPreference = ReadPreference.primary; - } - - if (options.explain && (this.readConcern || this.writeConcern)) { - throw new MongoError( - '"explain" cannot be used on an aggregate call with readConcern/writeConcern' - ); - } - - if (options.cursor != null && typeof options.cursor !== 'object') { - throw new MongoError('cursor options must be an object'); - } - } - - get canRetryRead() { - return !this.hasWriteStage; - } - - addToPipeline(stage) { - this.pipeline.push(stage); - } - - execute(server, callback) { - const options = this.options; - const serverWireVersion = maxWireVersion(server); - const command = { aggregate: this.target, pipeline: this.pipeline }; - - if (this.hasWriteStage && serverWireVersion < MIN_WIRE_VERSION_$OUT_READ_CONCERN_SUPPORT) { - this.readConcern = null; - } - - if (serverWireVersion >= 5) { - if (this.hasWriteStage && this.writeConcern) { - Object.assign(command, { writeConcern: this.writeConcern }); - } - } - - if (options.bypassDocumentValidation === true) { - command.bypassDocumentValidation = options.bypassDocumentValidation; - } - - if (typeof options.allowDiskUse === 'boolean') { - command.allowDiskUse = options.allowDiskUse; - } - - if (options.hint) { - command.hint = options.hint; - } - - if (options.explain) { - options.full = false; - command.explain = options.explain; - } - - command.cursor = options.cursor || {}; - if (options.batchSize && !this.hasWriteStage) { - command.cursor.batchSize = options.batchSize; - } - - super.executeCommand(server, command, callback); - } -} - -defineAspects(AggregateOperation, [ - Aspect.READ_OPERATION, - Aspect.RETRYABLE, - Aspect.EXECUTE_WITH_SELECTION -]); - -module.exports = AggregateOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/bulk_write.js b/scripts/node_modules/mongodb/lib/operations/bulk_write.js deleted file mode 100644 index 8f14f021..00000000 --- a/scripts/node_modules/mongodb/lib/operations/bulk_write.js +++ /dev/null @@ -1,104 +0,0 @@ -'use strict'; - -const applyRetryableWrites = require('../utils').applyRetryableWrites; -const applyWriteConcern = require('../utils').applyWriteConcern; -const MongoError = require('../core').MongoError; -const OperationBase = require('./operation').OperationBase; - -class BulkWriteOperation extends OperationBase { - constructor(collection, operations, options) { - super(options); - - this.collection = collection; - this.operations = operations; - } - - execute(callback) { - const coll = this.collection; - const operations = this.operations; - let options = this.options; - - // Add ignoreUndfined - if (coll.s.options.ignoreUndefined) { - options = Object.assign({}, options); - options.ignoreUndefined = coll.s.options.ignoreUndefined; - } - - // Create the bulk operation - const bulk = - options.ordered === true || options.ordered == null - ? coll.initializeOrderedBulkOp(options) - : coll.initializeUnorderedBulkOp(options); - - // Do we have a collation - let collation = false; - - // for each op go through and add to the bulk - try { - for (let i = 0; i < operations.length; i++) { - // Get the operation type - const key = Object.keys(operations[i])[0]; - // Check if we have a collation - if (operations[i][key].collation) { - collation = true; - } - - // Pass to the raw bulk - bulk.raw(operations[i]); - } - } catch (err) { - return callback(err, null); - } - - // Final options for retryable writes and write concern - let finalOptions = Object.assign({}, options); - finalOptions = applyRetryableWrites(finalOptions, coll.s.db); - finalOptions = applyWriteConcern(finalOptions, { db: coll.s.db, collection: coll }, options); - - const writeCon = finalOptions.writeConcern ? finalOptions.writeConcern : {}; - const capabilities = coll.s.topology.capabilities(); - - // Did the user pass in a collation, check if our write server supports it - if (collation && capabilities && !capabilities.commandsTakeCollation) { - return callback(new MongoError('server/primary/mongos does not support collation')); - } - - // Execute the bulk - bulk.execute(writeCon, finalOptions, (err, r) => { - // We have connection level error - if (!r && err) { - return callback(err, null); - } - - r.insertedCount = r.nInserted; - r.matchedCount = r.nMatched; - r.modifiedCount = r.nModified || 0; - r.deletedCount = r.nRemoved; - r.upsertedCount = r.getUpsertedIds().length; - r.upsertedIds = {}; - r.insertedIds = {}; - - // Update the n - r.n = r.insertedCount; - - // Inserted documents - const inserted = r.getInsertedIds(); - // Map inserted ids - for (let i = 0; i < inserted.length; i++) { - r.insertedIds[inserted[i].index] = inserted[i]._id; - } - - // Upserted documents - const upserted = r.getUpsertedIds(); - // Map upserted ids - for (let i = 0; i < upserted.length; i++) { - r.upsertedIds[upserted[i].index] = upserted[i]._id; - } - - // Return the results - callback(null, r); - }); - } -} - -module.exports = BulkWriteOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/close.js b/scripts/node_modules/mongodb/lib/operations/close.js deleted file mode 100644 index 57fdef6f..00000000 --- a/scripts/node_modules/mongodb/lib/operations/close.js +++ /dev/null @@ -1,46 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const defineAspects = require('./operation').defineAspects; -const OperationBase = require('./operation').OperationBase; - -class CloseOperation extends OperationBase { - constructor(client, force) { - super(); - this.client = client; - this.force = force; - } - - execute(callback) { - const client = this.client; - const force = this.force; - const completeClose = err => { - client.emit('close', client); - for (const item of client.s.dbCache) { - item[1].emit('close', client); - } - - client.removeAllListeners('close'); - callback(err, null); - }; - - if (client.topology == null) { - completeClose(); - return; - } - - client.topology.close(force, err => { - const autoEncrypter = client.topology.s.options.autoEncrypter; - if (!autoEncrypter) { - completeClose(err); - return; - } - - autoEncrypter.teardown(force, err2 => completeClose(err || err2)); - }); - } -} - -defineAspects(CloseOperation, [Aspect.SKIP_SESSION]); - -module.exports = CloseOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/collection_ops.js b/scripts/node_modules/mongodb/lib/operations/collection_ops.js deleted file mode 100644 index df5995d7..00000000 --- a/scripts/node_modules/mongodb/lib/operations/collection_ops.js +++ /dev/null @@ -1,374 +0,0 @@ -'use strict'; - -const applyWriteConcern = require('../utils').applyWriteConcern; -const Code = require('../core').BSON.Code; -const createIndexDb = require('./db_ops').createIndex; -const decorateWithCollation = require('../utils').decorateWithCollation; -const decorateWithReadConcern = require('../utils').decorateWithReadConcern; -const ensureIndexDb = require('./db_ops').ensureIndex; -const evaluate = require('./db_ops').evaluate; -const executeCommand = require('./db_ops').executeCommand; -const resolveReadPreference = require('../utils').resolveReadPreference; -const handleCallback = require('../utils').handleCallback; -const indexInformationDb = require('./db_ops').indexInformation; -const Long = require('../core').BSON.Long; -const MongoError = require('../core').MongoError; -const ReadPreference = require('../core').ReadPreference; -const toError = require('../utils').toError; -const insertDocuments = require('./common_functions').insertDocuments; -const updateDocuments = require('./common_functions').updateDocuments; - -/** - * Group function helper - * @ignore - */ -// var groupFunction = function () { -// var c = db[ns].find(condition); -// var map = new Map(); -// var reduce_function = reduce; -// -// while (c.hasNext()) { -// var obj = c.next(); -// var key = {}; -// -// for (var i = 0, len = keys.length; i < len; ++i) { -// var k = keys[i]; -// key[k] = obj[k]; -// } -// -// var aggObj = map.get(key); -// -// if (aggObj == null) { -// var newObj = Object.extend({}, key); -// aggObj = Object.extend(newObj, initial); -// map.put(key, aggObj); -// } -// -// reduce_function(obj, aggObj); -// } -// -// return { "result": map.values() }; -// }.toString(); -const groupFunction = - 'function () {\nvar c = db[ns].find(condition);\nvar map = new Map();\nvar reduce_function = reduce;\n\nwhile (c.hasNext()) {\nvar obj = c.next();\nvar key = {};\n\nfor (var i = 0, len = keys.length; i < len; ++i) {\nvar k = keys[i];\nkey[k] = obj[k];\n}\n\nvar aggObj = map.get(key);\n\nif (aggObj == null) {\nvar newObj = Object.extend({}, key);\naggObj = Object.extend(newObj, initial);\nmap.put(key, aggObj);\n}\n\nreduce_function(obj, aggObj);\n}\n\nreturn { "result": map.values() };\n}'; - -// Check the update operation to ensure it has atomic operators. -function checkForAtomicOperators(update) { - if (Array.isArray(update)) { - return update.reduce((err, u) => err || checkForAtomicOperators(u), null); - } - - const keys = Object.keys(update); - - // same errors as the server would give for update doc lacking atomic operators - if (keys.length === 0) { - return toError('The update operation document must contain at least one atomic operator.'); - } - - if (keys[0][0] !== '$') { - return toError('the update operation document must contain atomic operators.'); - } -} - -/** - * Create an index on the db and collection. - * - * @method - * @param {Collection} a Collection instance. - * @param {(string|object)} fieldOrSpec Defines the index. - * @param {object} [options] Optional settings. See Collection.prototype.createIndex for a list of options. - * @param {Collection~resultCallback} [callback] The command result callback - */ -function createIndex(coll, fieldOrSpec, options, callback) { - createIndexDb(coll.s.db, coll.collectionName, fieldOrSpec, options, callback); -} - -/** - * Create multiple indexes in the collection. This method is only supported for - * MongoDB 2.6 or higher. Earlier version of MongoDB will throw a command not supported - * error. Index specifications are defined at http://docs.mongodb.org/manual/reference/command/createIndexes/. - * - * @method - * @param {Collection} a Collection instance. - * @param {array} indexSpecs An array of index specifications to be created - * @param {Object} [options] Optional settings. See Collection.prototype.createIndexes for a list of options. - * @param {Collection~resultCallback} [callback] The command result callback - */ -function createIndexes(coll, indexSpecs, options, callback) { - const capabilities = coll.s.topology.capabilities(); - - // Ensure we generate the correct name if the parameter is not set - for (let i = 0; i < indexSpecs.length; i++) { - if (indexSpecs[i].name == null) { - const keys = []; - - // Did the user pass in a collation, check if our write server supports it - if (indexSpecs[i].collation && capabilities && !capabilities.commandsTakeCollation) { - return callback(new MongoError('server/primary/mongos does not support collation')); - } - - for (let name in indexSpecs[i].key) { - keys.push(`${name}_${indexSpecs[i].key[name]}`); - } - - // Set the name - indexSpecs[i].name = keys.join('_'); - } - } - - options = Object.assign({}, options, { readPreference: ReadPreference.PRIMARY }); - - // Execute the index - executeCommand( - coll.s.db, - { - createIndexes: coll.collectionName, - indexes: indexSpecs - }, - options, - callback - ); -} - -/** - * Ensure that an index exists. If the index does not exist, this function creates it. - * - * @method - * @param {Collection} a Collection instance. - * @param {(string|object)} fieldOrSpec Defines the index. - * @param {object} [options] Optional settings. See Collection.prototype.ensureIndex for a list of options. - * @param {Collection~resultCallback} [callback] The command result callback - */ -function ensureIndex(coll, fieldOrSpec, options, callback) { - ensureIndexDb(coll.s.db, coll.collectionName, fieldOrSpec, options, callback); -} - -/** - * Run a group command across a collection. - * - * @method - * @param {Collection} a Collection instance. - * @param {(object|array|function|code)} keys An object, array or function expressing the keys to group by. - * @param {object} condition An optional condition that must be true for a row to be considered. - * @param {object} initial Initial value of the aggregation counter object. - * @param {(function|Code)} reduce The reduce function aggregates (reduces) the objects iterated - * @param {(function|Code)} finalize An optional function to be run on each item in the result set just before the item is returned. - * @param {boolean} command Specify if you wish to run using the internal group command or using eval, default is true. - * @param {object} [options] Optional settings. See Collection.prototype.group for a list of options. - * @param {Collection~resultCallback} [callback] The command result callback - * @deprecated MongoDB 3.6 or higher will no longer support the group command. We recommend rewriting using the aggregation framework. - */ -function group(coll, keys, condition, initial, reduce, finalize, command, options, callback) { - // Execute using the command - if (command) { - const reduceFunction = reduce && reduce._bsontype === 'Code' ? reduce : new Code(reduce); - - const selector = { - group: { - ns: coll.collectionName, - $reduce: reduceFunction, - cond: condition, - initial: initial, - out: 'inline' - } - }; - - // if finalize is defined - if (finalize != null) selector.group['finalize'] = finalize; - // Set up group selector - if ('function' === typeof keys || (keys && keys._bsontype === 'Code')) { - selector.group.$keyf = keys && keys._bsontype === 'Code' ? keys : new Code(keys); - } else { - const hash = {}; - keys.forEach(key => { - hash[key] = 1; - }); - selector.group.key = hash; - } - - options = Object.assign({}, options); - // Ensure we have the right read preference inheritance - options.readPreference = resolveReadPreference(coll, options); - - // Do we have a readConcern specified - decorateWithReadConcern(selector, coll, options); - - // Have we specified collation - try { - decorateWithCollation(selector, coll, options); - } catch (err) { - return callback(err, null); - } - - // Execute command - executeCommand(coll.s.db, selector, options, (err, result) => { - if (err) return handleCallback(callback, err, null); - handleCallback(callback, null, result.retval); - }); - } else { - // Create execution scope - const scope = reduce != null && reduce._bsontype === 'Code' ? reduce.scope : {}; - - scope.ns = coll.collectionName; - scope.keys = keys; - scope.condition = condition; - scope.initial = initial; - - // Pass in the function text to execute within mongodb. - const groupfn = groupFunction.replace(/ reduce;/, reduce.toString() + ';'); - - evaluate(coll.s.db, new Code(groupfn, scope), null, options, (err, results) => { - if (err) return handleCallback(callback, err, null); - handleCallback(callback, null, results.result || results); - }); - } -} - -/** - * Retrieve all the indexes on the collection. - * - * @method - * @param {Collection} a Collection instance. - * @param {Object} [options] Optional settings. See Collection.prototype.indexes for a list of options. - * @param {Collection~resultCallback} [callback] The command result callback - */ -function indexes(coll, options, callback) { - options = Object.assign({}, { full: true }, options); - indexInformationDb(coll.s.db, coll.collectionName, options, callback); -} - -/** - * Check if one or more indexes exist on the collection. This fails on the first index that doesn't exist. - * - * @method - * @param {Collection} a Collection instance. - * @param {(string|array)} indexes One or more index names to check. - * @param {Object} [options] Optional settings. See Collection.prototype.indexExists for a list of options. - * @param {Collection~resultCallback} [callback] The command result callback - */ -function indexExists(coll, indexes, options, callback) { - indexInformation(coll, options, (err, indexInformation) => { - // If we have an error return - if (err != null) return handleCallback(callback, err, null); - // Let's check for the index names - if (!Array.isArray(indexes)) - return handleCallback(callback, null, indexInformation[indexes] != null); - // Check in list of indexes - for (let i = 0; i < indexes.length; i++) { - if (indexInformation[indexes[i]] == null) { - return handleCallback(callback, null, false); - } - } - - // All keys found return true - return handleCallback(callback, null, true); - }); -} - -/** - * Retrieve this collection's index info. - * - * @method - * @param {Collection} a Collection instance. - * @param {object} [options] Optional settings. See Collection.prototype.indexInformation for a list of options. - * @param {Collection~resultCallback} [callback] The command result callback - */ -function indexInformation(coll, options, callback) { - indexInformationDb(coll.s.db, coll.collectionName, options, callback); -} - -/** - * Return N parallel cursors for a collection to allow parallel reading of the entire collection. There are - * no ordering guarantees for returned results. - * - * @method - * @param {Collection} a Collection instance. - * @param {object} [options] Optional settings. See Collection.prototype.parallelCollectionScan for a list of options. - * @param {Collection~parallelCollectionScanCallback} [callback] The command result callback - */ -function parallelCollectionScan(coll, options, callback) { - // Create command object - const commandObject = { - parallelCollectionScan: coll.collectionName, - numCursors: options.numCursors - }; - - // Do we have a readConcern specified - decorateWithReadConcern(commandObject, coll, options); - - // Store the raw value - const raw = options.raw; - delete options['raw']; - - // Execute the command - executeCommand(coll.s.db, commandObject, options, (err, result) => { - if (err) return handleCallback(callback, err, null); - if (result == null) - return handleCallback( - callback, - new Error('no result returned for parallelCollectionScan'), - null - ); - - options = Object.assign({ explicitlyIgnoreSession: true }, options); - - const cursors = []; - // Add the raw back to the option - if (raw) options.raw = raw; - // Create command cursors for each item - for (let i = 0; i < result.cursors.length; i++) { - const rawId = result.cursors[i].cursor.id; - // Convert cursorId to Long if needed - const cursorId = typeof rawId === 'number' ? Long.fromNumber(rawId) : rawId; - // Add a command cursor - cursors.push(coll.s.topology.cursor(coll.namespace, cursorId, options)); - } - - handleCallback(callback, null, cursors); - }); -} - -/** - * Save a document. - * - * @method - * @param {Collection} a Collection instance. - * @param {object} doc Document to save - * @param {object} [options] Optional settings. See Collection.prototype.save for a list of options. - * @param {Collection~writeOpCallback} [callback] The command result callback - * @deprecated use insertOne, insertMany, updateOne or updateMany - */ -function save(coll, doc, options, callback) { - // Get the write concern options - const finalOptions = applyWriteConcern( - Object.assign({}, options), - { db: coll.s.db, collection: coll }, - options - ); - // Establish if we need to perform an insert or update - if (doc._id != null) { - finalOptions.upsert = true; - return updateDocuments(coll, { _id: doc._id }, doc, finalOptions, callback); - } - - // Insert the document - insertDocuments(coll, [doc], finalOptions, (err, result) => { - if (callback == null) return; - if (doc == null) return handleCallback(callback, null, null); - if (err) return handleCallback(callback, err, null); - handleCallback(callback, null, result); - }); -} - -module.exports = { - checkForAtomicOperators, - createIndex, - createIndexes, - ensureIndex, - group, - indexes, - indexExists, - indexInformation, - parallelCollectionScan, - save -}; diff --git a/scripts/node_modules/mongodb/lib/operations/collections.js b/scripts/node_modules/mongodb/lib/operations/collections.js deleted file mode 100644 index eac690a2..00000000 --- a/scripts/node_modules/mongodb/lib/operations/collections.js +++ /dev/null @@ -1,55 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const handleCallback = require('../utils').handleCallback; - -let collection; -function loadCollection() { - if (!collection) { - collection = require('../collection'); - } - return collection; -} - -class CollectionsOperation extends OperationBase { - constructor(db, options) { - super(options); - - this.db = db; - } - - execute(callback) { - const db = this.db; - let options = this.options; - - let Collection = loadCollection(); - - options = Object.assign({}, options, { nameOnly: true }); - // Let's get the collection names - db.listCollections({}, options).toArray((err, documents) => { - if (err != null) return handleCallback(callback, err, null); - // Filter collections removing any illegal ones - documents = documents.filter(doc => { - return doc.name.indexOf('$') === -1; - }); - - // Return the collection objects - handleCallback( - callback, - null, - documents.map(d => { - return new Collection( - db, - db.s.topology, - db.databaseName, - d.name, - db.s.pkFactory, - db.s.options - ); - }) - ); - }); - } -} - -module.exports = CollectionsOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/command.js b/scripts/node_modules/mongodb/lib/operations/command.js deleted file mode 100644 index 3c795bef..00000000 --- a/scripts/node_modules/mongodb/lib/operations/command.js +++ /dev/null @@ -1,120 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const OperationBase = require('./operation').OperationBase; -const applyWriteConcern = require('../utils').applyWriteConcern; -const debugOptions = require('../utils').debugOptions; -const handleCallback = require('../utils').handleCallback; -const MongoError = require('../core').MongoError; -const ReadPreference = require('../core').ReadPreference; -const resolveReadPreference = require('../utils').resolveReadPreference; -const MongoDBNamespace = require('../utils').MongoDBNamespace; - -const debugFields = [ - 'authSource', - 'w', - 'wtimeout', - 'j', - 'native_parser', - 'forceServerObjectId', - 'serializeFunctions', - 'raw', - 'promoteLongs', - 'promoteValues', - 'promoteBuffers', - 'bufferMaxEntries', - 'numberOfRetries', - 'retryMiliSeconds', - 'readPreference', - 'pkFactory', - 'parentDb', - 'promiseLibrary', - 'noListener' -]; - -class CommandOperation extends OperationBase { - constructor(db, options, collection, command) { - super(options); - - if (!this.hasAspect(Aspect.WRITE_OPERATION)) { - if (collection != null) { - this.options.readPreference = resolveReadPreference(collection, options); - } else { - this.options.readPreference = resolveReadPreference(db, options); - } - } else { - if (collection != null) { - applyWriteConcern(this.options, { db, coll: collection }, this.options); - } else { - applyWriteConcern(this.options, { db }, this.options); - } - this.options.readPreference = ReadPreference.primary; - } - - this.db = db; - - if (command != null) { - this.command = command; - } - - if (collection != null) { - this.collection = collection; - } - } - - _buildCommand() { - if (this.command != null) { - return this.command; - } - } - - execute(callback) { - const db = this.db; - const options = Object.assign({}, this.options); - - // Did the user destroy the topology - if (db.serverConfig && db.serverConfig.isDestroyed()) { - return callback(new MongoError('topology was destroyed')); - } - - let command; - try { - command = this._buildCommand(); - } catch (e) { - return callback(e); - } - - // Get the db name we are executing against - const dbName = options.dbName || options.authdb || db.databaseName; - - // Convert the readPreference if its not a write - if (this.hasAspect(Aspect.WRITE_OPERATION)) { - if (options.writeConcern && (!options.session || !options.session.inTransaction())) { - command.writeConcern = options.writeConcern; - } - } - - // Debug information - if (db.s.logger.isDebug()) { - db.s.logger.debug( - `executing command ${JSON.stringify( - command - )} against ${dbName}.$cmd with options [${JSON.stringify( - debugOptions(debugFields, options) - )}]` - ); - } - - const namespace = - this.namespace != null ? this.namespace : new MongoDBNamespace(dbName, '$cmd'); - - // Execute command - db.s.topology.command(namespace, command, options, (err, result) => { - if (err) return handleCallback(callback, err); - if (options.full) return handleCallback(callback, null, result); - handleCallback(callback, null, result.result); - }); - } -} - -module.exports = CommandOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/command_v2.js b/scripts/node_modules/mongodb/lib/operations/command_v2.js deleted file mode 100644 index 8df703fd..00000000 --- a/scripts/node_modules/mongodb/lib/operations/command_v2.js +++ /dev/null @@ -1,109 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const OperationBase = require('./operation').OperationBase; -const resolveReadPreference = require('../utils').resolveReadPreference; -const ReadConcern = require('../read_concern'); -const WriteConcern = require('../write_concern'); -const maxWireVersion = require('../core/utils').maxWireVersion; -const commandSupportsReadConcern = require('../core/sessions').commandSupportsReadConcern; -const MongoError = require('../error').MongoError; - -const SUPPORTS_WRITE_CONCERN_AND_COLLATION = 5; - -class CommandOperationV2 extends OperationBase { - constructor(parent, options, operationOptions) { - super(options); - - this.ns = parent.s.namespace.withCollection('$cmd'); - this.readPreference = resolveReadPreference(parent, this.options); - this.readConcern = resolveReadConcern(parent, this.options); - this.writeConcern = resolveWriteConcern(parent, this.options); - this.explain = false; - - if (operationOptions && typeof operationOptions.fullResponse === 'boolean') { - this.fullResponse = true; - } - - // TODO: A lot of our code depends on having the read preference in the options. This should - // go away, but also requires massive test rewrites. - this.options.readPreference = this.readPreference; - - // TODO(NODE-2056): make logger another "inheritable" property - if (parent.s.logger) { - this.logger = parent.s.logger; - } else if (parent.s.db && parent.s.db.logger) { - this.logger = parent.s.db.logger; - } - } - - executeCommand(server, cmd, callback) { - // TODO: consider making this a non-enumerable property - this.server = server; - - const options = this.options; - const serverWireVersion = maxWireVersion(server); - const inTransaction = this.session && this.session.inTransaction(); - - if (this.readConcern && commandSupportsReadConcern(cmd) && !inTransaction) { - Object.assign(cmd, { readConcern: this.readConcern }); - } - - if (options.collation && serverWireVersion < SUPPORTS_WRITE_CONCERN_AND_COLLATION) { - callback( - new MongoError( - `Server ${ - server.name - }, which reports wire version ${serverWireVersion}, does not support collation` - ) - ); - return; - } - - if (serverWireVersion >= SUPPORTS_WRITE_CONCERN_AND_COLLATION) { - if (this.writeConcern && this.hasAspect(Aspect.WRITE_OPERATION)) { - Object.assign(cmd, { writeConcern: this.writeConcern }); - } - - if (options.collation && typeof options.collation === 'object') { - Object.assign(cmd, { collation: options.collation }); - } - } - - if (typeof options.maxTimeMS === 'number') { - cmd.maxTimeMS = options.maxTimeMS; - } - - if (typeof options.comment === 'string') { - cmd.comment = options.comment; - } - - if (this.logger && this.logger.isDebug()) { - this.logger.debug(`executing command ${JSON.stringify(cmd)} against ${this.ns}`); - } - - server.command(this.ns.toString(), cmd, this.options, (err, result) => { - if (err) { - callback(err, null); - return; - } - - if (this.fullResponse) { - callback(null, result); - return; - } - - callback(null, result.result); - }); - } -} - -function resolveWriteConcern(parent, options) { - return WriteConcern.fromOptions(options) || parent.writeConcern; -} - -function resolveReadConcern(parent, options) { - return ReadConcern.fromOptions(options) || parent.readConcern; -} - -module.exports = CommandOperationV2; diff --git a/scripts/node_modules/mongodb/lib/operations/common_functions.js b/scripts/node_modules/mongodb/lib/operations/common_functions.js deleted file mode 100644 index 20c2bc9a..00000000 --- a/scripts/node_modules/mongodb/lib/operations/common_functions.js +++ /dev/null @@ -1,406 +0,0 @@ -'use strict'; - -const applyRetryableWrites = require('../utils').applyRetryableWrites; -const applyWriteConcern = require('../utils').applyWriteConcern; -const decorateWithCollation = require('../utils').decorateWithCollation; -const decorateWithReadConcern = require('../utils').decorateWithReadConcern; -const executeCommand = require('./db_ops').executeCommand; -const formattedOrderClause = require('../utils').formattedOrderClause; -const handleCallback = require('../utils').handleCallback; -const MongoError = require('../core').MongoError; -const ReadPreference = require('../core').ReadPreference; -const toError = require('../utils').toError; -const CursorState = require('../core/cursor').CursorState; - -/** - * Build the count command. - * - * @method - * @param {collectionOrCursor} an instance of a collection or cursor - * @param {object} query The query for the count. - * @param {object} [options] Optional settings. See Collection.prototype.count and Cursor.prototype.count for a list of options. - */ -function buildCountCommand(collectionOrCursor, query, options) { - const skip = options.skip; - const limit = options.limit; - let hint = options.hint; - const maxTimeMS = options.maxTimeMS; - query = query || {}; - - // Final query - const cmd = { - count: options.collectionName, - query: query - }; - - if (collectionOrCursor.s.numberOfRetries) { - // collectionOrCursor is a cursor - if (collectionOrCursor.options.hint) { - hint = collectionOrCursor.options.hint; - } else if (collectionOrCursor.cmd.hint) { - hint = collectionOrCursor.cmd.hint; - } - decorateWithCollation(cmd, collectionOrCursor, collectionOrCursor.cmd); - } else { - decorateWithCollation(cmd, collectionOrCursor, options); - } - - // Add limit, skip and maxTimeMS if defined - if (typeof skip === 'number') cmd.skip = skip; - if (typeof limit === 'number') cmd.limit = limit; - if (typeof maxTimeMS === 'number') cmd.maxTimeMS = maxTimeMS; - if (hint) cmd.hint = hint; - - // Do we have a readConcern specified - decorateWithReadConcern(cmd, collectionOrCursor); - - return cmd; -} - -function deleteCallback(err, r, callback) { - if (callback == null) return; - if (err && callback) return callback(err); - if (r == null) return callback(null, { result: { ok: 1 } }); - r.deletedCount = r.result.n; - if (callback) callback(null, r); -} - -/** - * Find and update a document. - * - * @method - * @param {Collection} a Collection instance. - * @param {object} query Query object to locate the object to modify. - * @param {array} sort If multiple docs match, choose the first one in the specified sort order as the object to manipulate. - * @param {object} doc The fields/vals to be updated. - * @param {object} [options] Optional settings. See Collection.prototype.findAndModify for a list of options. - * @param {Collection~findAndModifyCallback} [callback] The command result callback - * @deprecated use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead - */ -function findAndModify(coll, query, sort, doc, options, callback) { - // Create findAndModify command object - const queryObject = { - findAndModify: coll.collectionName, - query: query - }; - - sort = formattedOrderClause(sort); - if (sort) { - queryObject.sort = sort; - } - - queryObject.new = options.new ? true : false; - queryObject.remove = options.remove ? true : false; - queryObject.upsert = options.upsert ? true : false; - - const projection = options.projection || options.fields; - - if (projection) { - queryObject.fields = projection; - } - - if (options.arrayFilters) { - queryObject.arrayFilters = options.arrayFilters; - delete options.arrayFilters; - } - - if (doc && !options.remove) { - queryObject.update = doc; - } - - if (options.maxTimeMS) queryObject.maxTimeMS = options.maxTimeMS; - - // Either use override on the function, or go back to default on either the collection - // level or db - options.serializeFunctions = options.serializeFunctions || coll.s.serializeFunctions; - - // No check on the documents - options.checkKeys = false; - - // Final options for retryable writes and write concern - let finalOptions = Object.assign({}, options); - finalOptions = applyRetryableWrites(finalOptions, coll.s.db); - finalOptions = applyWriteConcern(finalOptions, { db: coll.s.db, collection: coll }, options); - - // Decorate the findAndModify command with the write Concern - if (finalOptions.writeConcern) { - queryObject.writeConcern = finalOptions.writeConcern; - } - - // Have we specified bypassDocumentValidation - if (finalOptions.bypassDocumentValidation === true) { - queryObject.bypassDocumentValidation = finalOptions.bypassDocumentValidation; - } - - finalOptions.readPreference = ReadPreference.primary; - - // Have we specified collation - try { - decorateWithCollation(queryObject, coll, finalOptions); - } catch (err) { - return callback(err, null); - } - - // Execute the command - executeCommand(coll.s.db, queryObject, finalOptions, (err, result) => { - if (err) return handleCallback(callback, err, null); - - return handleCallback(callback, null, result); - }); -} - -/** - * Retrieves this collections index info. - * - * @method - * @param {Db} db The Db instance on which to retrieve the index info. - * @param {string} name The name of the collection. - * @param {object} [options] Optional settings. See Db.prototype.indexInformation for a list of options. - * @param {Db~resultCallback} [callback] The command result callback - */ -function indexInformation(db, name, options, callback) { - // If we specified full information - const full = options['full'] == null ? false : options['full']; - - // Did the user destroy the topology - if (db.serverConfig && db.serverConfig.isDestroyed()) - return callback(new MongoError('topology was destroyed')); - // Process all the results from the index command and collection - function processResults(indexes) { - // Contains all the information - let info = {}; - // Process all the indexes - for (let i = 0; i < indexes.length; i++) { - const index = indexes[i]; - // Let's unpack the object - info[index.name] = []; - for (let name in index.key) { - info[index.name].push([name, index.key[name]]); - } - } - - return info; - } - - // Get the list of indexes of the specified collection - db - .collection(name) - .listIndexes(options) - .toArray((err, indexes) => { - if (err) return callback(toError(err)); - if (!Array.isArray(indexes)) return handleCallback(callback, null, []); - if (full) return handleCallback(callback, null, indexes); - handleCallback(callback, null, processResults(indexes)); - }); -} - -function prepareDocs(coll, docs, options) { - const forceServerObjectId = - typeof options.forceServerObjectId === 'boolean' - ? options.forceServerObjectId - : coll.s.db.options.forceServerObjectId; - - // no need to modify the docs if server sets the ObjectId - if (forceServerObjectId === true) { - return docs; - } - - return docs.map(doc => { - if (forceServerObjectId !== true && doc._id == null) { - doc._id = coll.s.pkFactory.createPk(); - } - - return doc; - }); -} - -// Get the next available document from the cursor, returns null if no more documents are available. -function nextObject(cursor, callback) { - if (cursor.s.state === CursorState.CLOSED || (cursor.isDead && cursor.isDead())) { - return handleCallback( - callback, - MongoError.create({ message: 'Cursor is closed', driver: true }) - ); - } - - if (cursor.s.state === CursorState.INIT && cursor.cmd && cursor.cmd.sort) { - try { - cursor.cmd.sort = formattedOrderClause(cursor.cmd.sort); - } catch (err) { - return handleCallback(callback, err); - } - } - - // Get the next object - cursor._next((err, doc) => { - cursor.s.state = CursorState.OPEN; - if (err) return handleCallback(callback, err); - handleCallback(callback, null, doc); - }); -} - -function insertDocuments(coll, docs, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - // Ensure we are operating on an array op docs - docs = Array.isArray(docs) ? docs : [docs]; - - // Final options for retryable writes and write concern - let finalOptions = Object.assign({}, options); - finalOptions = applyRetryableWrites(finalOptions, coll.s.db); - finalOptions = applyWriteConcern(finalOptions, { db: coll.s.db, collection: coll }, options); - - // If keep going set unordered - if (finalOptions.keepGoing === true) finalOptions.ordered = false; - finalOptions.serializeFunctions = options.serializeFunctions || coll.s.serializeFunctions; - - docs = prepareDocs(coll, docs, options); - - // File inserts - coll.s.topology.insert(coll.s.namespace, docs, finalOptions, (err, result) => { - if (callback == null) return; - if (err) return handleCallback(callback, err); - if (result == null) return handleCallback(callback, null, null); - if (result.result.code) return handleCallback(callback, toError(result.result)); - if (result.result.writeErrors) - return handleCallback(callback, toError(result.result.writeErrors[0])); - // Add docs to the list - result.ops = docs; - // Return the results - handleCallback(callback, null, result); - }); -} - -function removeDocuments(coll, selector, options, callback) { - if (typeof options === 'function') { - (callback = options), (options = {}); - } else if (typeof selector === 'function') { - callback = selector; - options = {}; - selector = {}; - } - - // Create an empty options object if the provided one is null - options = options || {}; - - // Final options for retryable writes and write concern - let finalOptions = Object.assign({}, options); - finalOptions = applyRetryableWrites(finalOptions, coll.s.db); - finalOptions = applyWriteConcern(finalOptions, { db: coll.s.db, collection: coll }, options); - - // If selector is null set empty - if (selector == null) selector = {}; - - // Build the op - const op = { q: selector, limit: 0 }; - if (options.single) { - op.limit = 1; - } else if (finalOptions.retryWrites) { - finalOptions.retryWrites = false; - } - - // Have we specified collation - try { - decorateWithCollation(finalOptions, coll, options); - } catch (err) { - return callback(err, null); - } - - // Execute the remove - coll.s.topology.remove(coll.s.namespace, [op], finalOptions, (err, result) => { - if (callback == null) return; - if (err) return handleCallback(callback, err, null); - if (result == null) return handleCallback(callback, null, null); - if (result.result.code) return handleCallback(callback, toError(result.result)); - if (result.result.writeErrors) { - return handleCallback(callback, toError(result.result.writeErrors[0])); - } - - // Return the results - handleCallback(callback, null, result); - }); -} - -function updateDocuments(coll, selector, document, options, callback) { - if ('function' === typeof options) (callback = options), (options = null); - if (options == null) options = {}; - if (!('function' === typeof callback)) callback = null; - - // If we are not providing a selector or document throw - if (selector == null || typeof selector !== 'object') - return callback(toError('selector must be a valid JavaScript object')); - if (document == null || typeof document !== 'object') - return callback(toError('document must be a valid JavaScript object')); - - // Final options for retryable writes and write concern - let finalOptions = Object.assign({}, options); - finalOptions = applyRetryableWrites(finalOptions, coll.s.db); - finalOptions = applyWriteConcern(finalOptions, { db: coll.s.db, collection: coll }, options); - - // Do we return the actual result document - // Either use override on the function, or go back to default on either the collection - // level or db - finalOptions.serializeFunctions = options.serializeFunctions || coll.s.serializeFunctions; - - // Execute the operation - const op = { q: selector, u: document }; - op.upsert = options.upsert !== void 0 ? !!options.upsert : false; - op.multi = options.multi !== void 0 ? !!options.multi : false; - - if (finalOptions.arrayFilters) { - op.arrayFilters = finalOptions.arrayFilters; - delete finalOptions.arrayFilters; - } - - if (finalOptions.retryWrites && op.multi) { - finalOptions.retryWrites = false; - } - - // Have we specified collation - try { - decorateWithCollation(finalOptions, coll, options); - } catch (err) { - return callback(err, null); - } - - // Update options - coll.s.topology.update(coll.s.namespace, [op], finalOptions, (err, result) => { - if (callback == null) return; - if (err) return handleCallback(callback, err, null); - if (result == null) return handleCallback(callback, null, null); - if (result.result.code) return handleCallback(callback, toError(result.result)); - if (result.result.writeErrors) - return handleCallback(callback, toError(result.result.writeErrors[0])); - // Return the results - handleCallback(callback, null, result); - }); -} - -function updateCallback(err, r, callback) { - if (callback == null) return; - if (err) return callback(err); - if (r == null) return callback(null, { result: { ok: 1 } }); - r.modifiedCount = r.result.nModified != null ? r.result.nModified : r.result.n; - r.upsertedId = - Array.isArray(r.result.upserted) && r.result.upserted.length > 0 - ? r.result.upserted[0] // FIXME(major): should be `r.result.upserted[0]._id` - : null; - r.upsertedCount = - Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0; - r.matchedCount = - Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? 0 : r.result.n; - callback(null, r); -} - -module.exports = { - buildCountCommand, - deleteCallback, - findAndModify, - indexInformation, - nextObject, - prepareDocs, - insertDocuments, - removeDocuments, - updateDocuments, - updateCallback -}; diff --git a/scripts/node_modules/mongodb/lib/operations/connect.js b/scripts/node_modules/mongodb/lib/operations/connect.js deleted file mode 100644 index e8f25187..00000000 --- a/scripts/node_modules/mongodb/lib/operations/connect.js +++ /dev/null @@ -1,709 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const defineAspects = require('./operation').defineAspects; -const Aspect = require('./operation').Aspect; -const deprecate = require('util').deprecate; -const Logger = require('../core').Logger; -const MongoCredentials = require('../core').MongoCredentials; -const MongoError = require('../core').MongoError; -const Mongos = require('../topologies/mongos'); -const NativeTopology = require('../topologies/native_topology'); -const parse = require('../core').parseConnectionString; -const ReadConcern = require('../read_concern'); -const ReadPreference = require('../core').ReadPreference; -const ReplSet = require('../topologies/replset'); -const Server = require('../topologies/server'); -const ServerSessionPool = require('../core').Sessions.ServerSessionPool; - -let client; -function loadClient() { - if (!client) { - client = require('../mongo_client'); - } - return client; -} - -const legacyParse = deprecate( - require('../url_parser'), - 'current URL string parser is deprecated, and will be removed in a future version. ' + - 'To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.' -); - -const AUTH_MECHANISM_INTERNAL_MAP = { - DEFAULT: 'default', - 'MONGODB-CR': 'mongocr', - PLAIN: 'plain', - 'MONGODB-X509': 'x509', - 'SCRAM-SHA-1': 'scram-sha-1', - 'SCRAM-SHA-256': 'scram-sha-256' -}; - -const monitoringEvents = [ - 'timeout', - 'close', - 'serverOpening', - 'serverDescriptionChanged', - 'serverHeartbeatStarted', - 'serverHeartbeatSucceeded', - 'serverHeartbeatFailed', - 'serverClosed', - 'topologyOpening', - 'topologyClosed', - 'topologyDescriptionChanged', - 'commandStarted', - 'commandSucceeded', - 'commandFailed', - 'joined', - 'left', - 'ping', - 'ha', - 'all', - 'fullsetup', - 'open' -]; - -const VALID_AUTH_MECHANISMS = new Set([ - 'DEFAULT', - 'MONGODB-CR', - 'PLAIN', - 'MONGODB-X509', - 'SCRAM-SHA-1', - 'SCRAM-SHA-256', - 'GSSAPI' -]); - -const validOptionNames = [ - 'poolSize', - 'ssl', - 'sslValidate', - 'sslCA', - 'sslCert', - 'sslKey', - 'sslPass', - 'sslCRL', - 'autoReconnect', - 'noDelay', - 'keepAlive', - 'keepAliveInitialDelay', - 'connectTimeoutMS', - 'family', - 'socketTimeoutMS', - 'reconnectTries', - 'reconnectInterval', - 'ha', - 'haInterval', - 'replicaSet', - 'secondaryAcceptableLatencyMS', - 'acceptableLatencyMS', - 'connectWithNoPrimary', - 'authSource', - 'w', - 'wtimeout', - 'j', - 'forceServerObjectId', - 'serializeFunctions', - 'ignoreUndefined', - 'raw', - 'bufferMaxEntries', - 'readPreference', - 'pkFactory', - 'promiseLibrary', - 'readConcern', - 'maxStalenessSeconds', - 'loggerLevel', - 'logger', - 'promoteValues', - 'promoteBuffers', - 'promoteLongs', - 'domainsEnabled', - 'checkServerIdentity', - 'validateOptions', - 'appname', - 'auth', - 'user', - 'password', - 'authMechanism', - 'compression', - 'fsync', - 'readPreferenceTags', - 'numberOfRetries', - 'auto_reconnect', - 'minSize', - 'monitorCommands', - 'retryWrites', - 'retryReads', - 'useNewUrlParser', - 'useUnifiedTopology', - 'serverSelectionTimeoutMS', - 'useRecoveryToken', - 'autoEncryption' -]; - -const ignoreOptionNames = ['native_parser']; -const legacyOptionNames = ['server', 'replset', 'replSet', 'mongos', 'db']; - -// Validate options object -function validOptions(options) { - const _validOptions = validOptionNames.concat(legacyOptionNames); - - for (const name in options) { - if (ignoreOptionNames.indexOf(name) !== -1) { - continue; - } - - if (_validOptions.indexOf(name) === -1) { - if (options.validateOptions) { - return new MongoError(`option ${name} is not supported`); - } else { - console.warn(`the options [${name}] is not supported`); - } - } - - if (legacyOptionNames.indexOf(name) !== -1) { - console.warn( - `the server/replset/mongos/db options are deprecated, ` + - `all their options are supported at the top level of the options object [${validOptionNames}]` - ); - } - } -} - -const LEGACY_OPTIONS_MAP = validOptionNames.reduce((obj, name) => { - obj[name.toLowerCase()] = name; - return obj; -}, {}); - -class ConnectOperation extends OperationBase { - constructor(mongoClient) { - super(); - - this.mongoClient = mongoClient; - } - - execute(callback) { - const mongoClient = this.mongoClient; - const err = validOptions(mongoClient.s.options); - - // Did we have a validation error - if (err) return callback(err); - // Fallback to callback based connect - connect(mongoClient, mongoClient.s.url, mongoClient.s.options, err => { - if (err) return callback(err); - callback(null, mongoClient); - }); - } -} -defineAspects(ConnectOperation, [Aspect.SKIP_SESSION]); - -function addListeners(mongoClient, topology) { - topology.on('authenticated', createListener(mongoClient, 'authenticated')); - topology.on('error', createListener(mongoClient, 'error')); - topology.on('timeout', createListener(mongoClient, 'timeout')); - topology.on('close', createListener(mongoClient, 'close')); - topology.on('parseError', createListener(mongoClient, 'parseError')); - topology.once('open', createListener(mongoClient, 'open')); - topology.once('fullsetup', createListener(mongoClient, 'fullsetup')); - topology.once('all', createListener(mongoClient, 'all')); - topology.on('reconnect', createListener(mongoClient, 'reconnect')); -} - -function assignTopology(client, topology) { - client.topology = topology; - topology.s.sessionPool = - topology instanceof NativeTopology - ? new ServerSessionPool(topology) - : new ServerSessionPool(topology.s.coreTopology); -} - -// Clear out all events -function clearAllEvents(topology) { - monitoringEvents.forEach(event => topology.removeAllListeners(event)); -} - -// Collect all events in order from SDAM -function collectEvents(mongoClient, topology) { - let MongoClient = loadClient(); - const collectedEvents = []; - - if (mongoClient instanceof MongoClient) { - monitoringEvents.forEach(event => { - topology.on(event, (object1, object2) => { - if (event === 'open') { - collectedEvents.push({ event: event, object1: mongoClient }); - } else { - collectedEvents.push({ event: event, object1: object1, object2: object2 }); - } - }); - }); - } - - return collectedEvents; -} - -const emitDeprecationForNonUnifiedTopology = deprecate(() => {}, -'current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. ' + 'To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.'); - -function connect(mongoClient, url, options, callback) { - options = Object.assign({}, options); - - // If callback is null throw an exception - if (callback == null) { - throw new Error('no callback function provided'); - } - - let didRequestAuthentication = false; - const logger = Logger('MongoClient', options); - - // Did we pass in a Server/ReplSet/Mongos - if (url instanceof Server || url instanceof ReplSet || url instanceof Mongos) { - return connectWithUrl(mongoClient, url, options, connectCallback); - } - - const useNewUrlParser = options.useNewUrlParser !== false; - - const parseFn = useNewUrlParser ? parse : legacyParse; - const transform = useNewUrlParser ? transformUrlOptions : legacyTransformUrlOptions; - - parseFn(url, options, (err, _object) => { - // Do not attempt to connect if parsing error - if (err) return callback(err); - - // Flatten - const object = transform(_object); - - // Parse the string - const _finalOptions = createUnifiedOptions(object, options); - - // Check if we have connection and socket timeout set - if (_finalOptions.socketTimeoutMS == null) _finalOptions.socketTimeoutMS = 360000; - if (_finalOptions.connectTimeoutMS == null) _finalOptions.connectTimeoutMS = 30000; - if (_finalOptions.retryWrites == null) _finalOptions.retryWrites = true; - if (_finalOptions.useRecoveryToken == null) _finalOptions.useRecoveryToken = true; - if (_finalOptions.readPreference == null) _finalOptions.readPreference = 'primary'; - - if (_finalOptions.db_options && _finalOptions.db_options.auth) { - delete _finalOptions.db_options.auth; - } - - // Store the merged options object - mongoClient.s.options = _finalOptions; - - // Failure modes - if (object.servers.length === 0) { - return callback(new Error('connection string must contain at least one seed host')); - } - - if (_finalOptions.auth && !_finalOptions.credentials) { - try { - didRequestAuthentication = true; - _finalOptions.credentials = generateCredentials( - mongoClient, - _finalOptions.auth.user, - _finalOptions.auth.password, - _finalOptions - ); - } catch (err) { - return callback(err); - } - } - - if (_finalOptions.useUnifiedTopology) { - return createTopology(mongoClient, 'unified', _finalOptions, connectCallback); - } - - emitDeprecationForNonUnifiedTopology(); - - // Do we have a replicaset then skip discovery and go straight to connectivity - if (_finalOptions.replicaSet || _finalOptions.rs_name) { - return createTopology(mongoClient, 'replicaset', _finalOptions, connectCallback); - } else if (object.servers.length > 1) { - return createTopology(mongoClient, 'mongos', _finalOptions, connectCallback); - } else { - return createServer(mongoClient, _finalOptions, connectCallback); - } - }); - - function connectCallback(err, topology) { - const warningMessage = `seed list contains no mongos proxies, replicaset connections requires the parameter replicaSet to be supplied in the URI or options object, mongodb://server:port/db?replicaSet=name`; - if (err && err.message === 'no mongos proxies found in seed list') { - if (logger.isWarn()) { - logger.warn(warningMessage); - } - - // Return a more specific error message for MongoClient.connect - return callback(new MongoError(warningMessage)); - } - - if (didRequestAuthentication) { - mongoClient.emit('authenticated', null, true); - } - - // Return the error and db instance - callback(err, topology); - } -} - -function connectWithUrl(mongoClient, url, options, connectCallback) { - // Set the topology - assignTopology(mongoClient, url); - - // Add listeners - addListeners(mongoClient, url); - - // Propagate the events to the client - relayEvents(mongoClient, url); - - let finalOptions = Object.assign({}, options); - - // If we have a readPreference passed in by the db options, convert it from a string - if (typeof options.readPreference === 'string' || typeof options.read_preference === 'string') { - finalOptions.readPreference = new ReadPreference( - options.readPreference || options.read_preference - ); - } - - const isDoingAuth = finalOptions.user || finalOptions.password || finalOptions.authMechanism; - if (isDoingAuth && !finalOptions.credentials) { - try { - finalOptions.credentials = generateCredentials( - mongoClient, - finalOptions.user, - finalOptions.password, - finalOptions - ); - } catch (err) { - return connectCallback(err, url); - } - } - - return url.connect(finalOptions, connectCallback); -} - -function createListener(mongoClient, event) { - const eventSet = new Set(['all', 'fullsetup', 'open', 'reconnect']); - return (v1, v2) => { - if (eventSet.has(event)) { - return mongoClient.emit(event, mongoClient); - } - - mongoClient.emit(event, v1, v2); - }; -} - -function createServer(mongoClient, options, callback) { - // Pass in the promise library - options.promiseLibrary = mongoClient.s.promiseLibrary; - - // Set default options - const servers = translateOptions(options); - - const server = servers[0]; - - // Propagate the events to the client - const collectedEvents = collectEvents(mongoClient, server); - - // Connect to topology - server.connect(options, (err, topology) => { - if (err) { - server.close(true); - return callback(err); - } - // Clear out all the collected event listeners - clearAllEvents(server); - - // Relay all the events - relayEvents(mongoClient, server); - // Add listeners - addListeners(mongoClient, server); - // Check if we are really speaking to a mongos - const ismaster = topology.lastIsMaster(); - - // Set the topology - assignTopology(mongoClient, topology); - - // Do we actually have a mongos - if (ismaster && ismaster.msg === 'isdbgrid') { - // Destroy the current connection - topology.close(); - // Create mongos connection instead - return createTopology(mongoClient, 'mongos', options, callback); - } - - // Fire all the events - replayEvents(mongoClient, collectedEvents); - // Otherwise callback - callback(err, topology); - }); -} - -function createTopology(mongoClient, topologyType, options, callback) { - // Pass in the promise library - options.promiseLibrary = mongoClient.s.promiseLibrary; - - const translationOptions = {}; - if (topologyType === 'unified') translationOptions.createServers = false; - - // Set default options - const servers = translateOptions(options, translationOptions); - - // Create the topology - let topology; - if (topologyType === 'mongos') { - topology = new Mongos(servers, options); - } else if (topologyType === 'replicaset') { - topology = new ReplSet(servers, options); - } else if (topologyType === 'unified') { - topology = new NativeTopology(options.servers, options); - } - - // Add listeners - addListeners(mongoClient, topology); - - // Propagate the events to the client - relayEvents(mongoClient, topology); - - // Open the connection - assignTopology(mongoClient, topology); - topology.connect(options, err => { - if (err) { - topology.close(true); - return callback(err); - } - - if (options.autoEncryption == null) { - callback(null, topology); - return; - } - - // setup for client side encryption - let AutoEncrypter; - try { - require.resolve('mongodb-client-encryption'); - } catch (err) { - callback( - new MongoError( - 'Auto-encryption requested, but the module is not installed. Please add `mongodb-client-encryption` as a dependency of your project' - ) - ); - return; - } - try { - AutoEncrypter = require('mongodb-client-encryption')(require('../../index')).AutoEncrypter; - } catch (err) { - callback(err); - return; - } - - const mongoCryptOptions = Object.assign({}, options.autoEncryption); - topology.s.options.autoEncrypter = new AutoEncrypter(mongoClient, mongoCryptOptions); - topology.s.options.autoEncrypter.init(err => { - if (err) return callback(err, null); - callback(null, topology); - }); - }); -} - -function createUnifiedOptions(finalOptions, options) { - const childOptions = [ - 'mongos', - 'server', - 'db', - 'replset', - 'db_options', - 'server_options', - 'rs_options', - 'mongos_options' - ]; - const noMerge = ['readconcern', 'compression']; - - for (const name in options) { - if (noMerge.indexOf(name.toLowerCase()) !== -1) { - finalOptions[name] = options[name]; - } else if (childOptions.indexOf(name.toLowerCase()) !== -1) { - finalOptions = mergeOptions(finalOptions, options[name], false); - } else { - if ( - options[name] && - typeof options[name] === 'object' && - !Buffer.isBuffer(options[name]) && - !Array.isArray(options[name]) - ) { - finalOptions = mergeOptions(finalOptions, options[name], true); - } else { - finalOptions[name] = options[name]; - } - } - } - - return finalOptions; -} - -function generateCredentials(client, username, password, options) { - options = Object.assign({}, options); - - // the default db to authenticate against is 'self' - // if authententicate is called from a retry context, it may be another one, like admin - const source = options.authSource || options.authdb || options.dbName; - - // authMechanism - const authMechanismRaw = options.authMechanism || 'DEFAULT'; - const authMechanism = authMechanismRaw.toUpperCase(); - - if (!VALID_AUTH_MECHANISMS.has(authMechanism)) { - throw MongoError.create({ - message: `authentication mechanism ${authMechanismRaw} not supported', options.authMechanism`, - driver: true - }); - } - - if (authMechanism === 'GSSAPI') { - return new MongoCredentials({ - mechanism: process.platform === 'win32' ? 'sspi' : 'gssapi', - mechanismProperties: options, - source, - username, - password - }); - } - - return new MongoCredentials({ - mechanism: AUTH_MECHANISM_INTERNAL_MAP[authMechanism], - source, - username, - password - }); -} - -function legacyTransformUrlOptions(object) { - return mergeOptions(createUnifiedOptions({}, object), object, false); -} - -function mergeOptions(target, source, flatten) { - for (const name in source) { - if (source[name] && typeof source[name] === 'object' && flatten) { - target = mergeOptions(target, source[name], flatten); - } else { - target[name] = source[name]; - } - } - - return target; -} - -function relayEvents(mongoClient, topology) { - const serverOrCommandEvents = [ - 'serverOpening', - 'serverDescriptionChanged', - 'serverHeartbeatStarted', - 'serverHeartbeatSucceeded', - 'serverHeartbeatFailed', - 'serverClosed', - 'topologyOpening', - 'topologyClosed', - 'topologyDescriptionChanged', - 'commandStarted', - 'commandSucceeded', - 'commandFailed', - 'joined', - 'left', - 'ping', - 'ha' - ]; - - serverOrCommandEvents.forEach(event => { - topology.on(event, (object1, object2) => { - mongoClient.emit(event, object1, object2); - }); - }); -} - -// -// Replay any events due to single server connection switching to Mongos -// -function replayEvents(mongoClient, events) { - for (let i = 0; i < events.length; i++) { - mongoClient.emit(events[i].event, events[i].object1, events[i].object2); - } -} - -function transformUrlOptions(_object) { - let object = Object.assign({ servers: _object.hosts }, _object.options); - for (let name in object) { - const camelCaseName = LEGACY_OPTIONS_MAP[name]; - if (camelCaseName) { - object[camelCaseName] = object[name]; - } - } - - const hasUsername = _object.auth && _object.auth.username; - const hasAuthMechanism = _object.options && _object.options.authMechanism; - if (hasUsername || hasAuthMechanism) { - object.auth = Object.assign({}, _object.auth); - if (object.auth.db) { - object.authSource = object.authSource || object.auth.db; - } - - if (object.auth.username) { - object.auth.user = object.auth.username; - } - } - - if (_object.defaultDatabase) { - object.dbName = _object.defaultDatabase; - } - - if (object.maxPoolSize) { - object.poolSize = object.maxPoolSize; - } - - if (object.readConcernLevel) { - object.readConcern = new ReadConcern(object.readConcernLevel); - } - - if (object.wTimeoutMS) { - object.wtimeout = object.wTimeoutMS; - } - - if (_object.srvHost) { - object.srvHost = _object.srvHost; - } - - return object; -} - -function translateOptions(options, translationOptions) { - translationOptions = Object.assign({}, { createServers: true }, translationOptions); - - // If we have a readPreference passed in by the db options - if (typeof options.readPreference === 'string' || typeof options.read_preference === 'string') { - options.readPreference = new ReadPreference(options.readPreference || options.read_preference); - } - - // Do we have readPreference tags, add them - if (options.readPreference && (options.readPreferenceTags || options.read_preference_tags)) { - options.readPreference.tags = options.readPreferenceTags || options.read_preference_tags; - } - - // Do we have maxStalenessSeconds - if (options.maxStalenessSeconds) { - options.readPreference.maxStalenessSeconds = options.maxStalenessSeconds; - } - - // Set the socket and connection timeouts - if (options.socketTimeoutMS == null) options.socketTimeoutMS = 360000; - if (options.connectTimeoutMS == null) options.connectTimeoutMS = 30000; - - if (!translationOptions.createServers) { - return; - } - - // Create server instances - return options.servers.map(serverObj => { - return serverObj.domain_socket - ? new Server(serverObj.domain_socket, 27017, options) - : new Server(serverObj.host, serverObj.port, options); - }); -} - -module.exports = ConnectOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/count.js b/scripts/node_modules/mongodb/lib/operations/count.js deleted file mode 100644 index 5bf03f08..00000000 --- a/scripts/node_modules/mongodb/lib/operations/count.js +++ /dev/null @@ -1,72 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const buildCountCommand = require('./common_functions').buildCountCommand; -const defineAspects = require('./operation').defineAspects; -const OperationBase = require('./operation').OperationBase; - -class CountOperation extends OperationBase { - constructor(cursor, applySkipLimit, options) { - super(options); - - this.cursor = cursor; - this.applySkipLimit = applySkipLimit; - } - - execute(callback) { - const cursor = this.cursor; - const applySkipLimit = this.applySkipLimit; - const options = this.options; - - if (applySkipLimit) { - if (typeof cursor.cursorSkip() === 'number') options.skip = cursor.cursorSkip(); - if (typeof cursor.cursorLimit() === 'number') options.limit = cursor.cursorLimit(); - } - - // Ensure we have the right read preference inheritance - if (options.readPreference) { - cursor.setReadPreference(options.readPreference); - } - - if ( - typeof options.maxTimeMS !== 'number' && - cursor.cmd && - typeof cursor.cmd.maxTimeMS === 'number' - ) { - options.maxTimeMS = cursor.cmd.maxTimeMS; - } - - let finalOptions = {}; - finalOptions.skip = options.skip; - finalOptions.limit = options.limit; - finalOptions.hint = options.hint; - finalOptions.maxTimeMS = options.maxTimeMS; - - // Command - finalOptions.collectionName = cursor.namespace.collection; - - let command; - try { - command = buildCountCommand(cursor, cursor.cmd.query, finalOptions); - } catch (err) { - return callback(err); - } - - // Set cursor server to the same as the topology - cursor.server = cursor.topology.s.coreTopology; - - // Execute the command - cursor.topology.command( - cursor.namespace.withCollection('$cmd'), - command, - cursor.options, - (err, result) => { - callback(err, result ? result.result.n : null); - } - ); - } -} - -defineAspects(CountOperation, Aspect.SKIP_SESSION); - -module.exports = CountOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/count_documents.js b/scripts/node_modules/mongodb/lib/operations/count_documents.js deleted file mode 100644 index d043abfa..00000000 --- a/scripts/node_modules/mongodb/lib/operations/count_documents.js +++ /dev/null @@ -1,41 +0,0 @@ -'use strict'; - -const AggregateOperation = require('./aggregate'); - -class CountDocumentsOperation extends AggregateOperation { - constructor(collection, query, options) { - const pipeline = [{ $match: query }]; - if (typeof options.skip === 'number') { - pipeline.push({ $skip: options.skip }); - } - - if (typeof options.limit === 'number') { - pipeline.push({ $limit: options.limit }); - } - - pipeline.push({ $group: { _id: 1, n: { $sum: 1 } } }); - - super(collection, pipeline, options); - } - - execute(server, callback) { - super.execute(server, (err, result) => { - if (err) { - callback(err, null); - return; - } - - // NOTE: We're avoiding creating a cursor here to reduce the callstack. - const response = result.result; - if (response.cursor == null || response.cursor.firstBatch == null) { - callback(null, 0); - return; - } - - const docs = response.cursor.firstBatch; - callback(null, docs.length ? docs[0].n : 0); - }); - } -} - -module.exports = CountDocumentsOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/create_collection.js b/scripts/node_modules/mongodb/lib/operations/create_collection.js deleted file mode 100644 index 35c3a6f0..00000000 --- a/scripts/node_modules/mongodb/lib/operations/create_collection.js +++ /dev/null @@ -1,118 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const defineAspects = require('./operation').defineAspects; -const CommandOperation = require('./command'); -const applyWriteConcern = require('../utils').applyWriteConcern; -const handleCallback = require('../utils').handleCallback; -const loadCollection = require('../dynamic_loaders').loadCollection; -const MongoError = require('../core').MongoError; -const ReadPreference = require('../core').ReadPreference; - -// Filter out any write concern options -const illegalCommandFields = [ - 'w', - 'wtimeout', - 'j', - 'fsync', - 'autoIndexId', - 'strict', - 'serializeFunctions', - 'pkFactory', - 'raw', - 'readPreference', - 'session', - 'readConcern', - 'writeConcern' -]; - -class CreateCollectionOperation extends CommandOperation { - constructor(db, name, options) { - super(db, options); - - this.name = name; - } - - _buildCommand() { - const name = this.name; - const options = this.options; - - // Create collection command - const cmd = { create: name }; - // Add all optional parameters - for (let n in options) { - if ( - options[n] != null && - typeof options[n] !== 'function' && - illegalCommandFields.indexOf(n) === -1 - ) { - cmd[n] = options[n]; - } - } - - return cmd; - } - - execute(callback) { - const db = this.db; - const name = this.name; - const options = this.options; - - let Collection = loadCollection(); - - // Did the user destroy the topology - if (db.serverConfig && db.serverConfig.isDestroyed()) { - return callback(new MongoError('topology was destroyed')); - } - - let listCollectionOptions = Object.assign({}, options, { nameOnly: true }); - listCollectionOptions = applyWriteConcern(listCollectionOptions, { db }, listCollectionOptions); - - // Check if we have the name - db - .listCollections({ name }, listCollectionOptions) - .setReadPreference(ReadPreference.PRIMARY) - .toArray((err, collections) => { - if (err != null) return handleCallback(callback, err, null); - if (collections.length > 0 && listCollectionOptions.strict) { - return handleCallback( - callback, - MongoError.create({ - message: `Collection ${name} already exists. Currently in strict mode.`, - driver: true - }), - null - ); - } else if (collections.length > 0) { - try { - return handleCallback( - callback, - null, - new Collection(db, db.s.topology, db.databaseName, name, db.s.pkFactory, options) - ); - } catch (err) { - return handleCallback(callback, err); - } - } - - // Execute command - super.execute(err => { - if (err) return handleCallback(callback, err); - - try { - return handleCallback( - callback, - null, - new Collection(db, db.s.topology, db.databaseName, name, db.s.pkFactory, options) - ); - } catch (err) { - return handleCallback(callback, err); - } - }); - }); - } -} - -defineAspects(CreateCollectionOperation, Aspect.WRITE_OPERATION); - -module.exports = CreateCollectionOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/create_index.js b/scripts/node_modules/mongodb/lib/operations/create_index.js deleted file mode 100644 index 98bba71e..00000000 --- a/scripts/node_modules/mongodb/lib/operations/create_index.js +++ /dev/null @@ -1,92 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const CommandOperation = require('./command'); -const defineAspects = require('./operation').defineAspects; -const handleCallback = require('../utils').handleCallback; -const MongoError = require('../core').MongoError; -const parseIndexOptions = require('../utils').parseIndexOptions; - -const keysToOmit = new Set([ - 'name', - 'key', - 'writeConcern', - 'w', - 'wtimeout', - 'j', - 'fsync', - 'readPreference', - 'session' -]); - -class CreateIndexOperation extends CommandOperation { - constructor(db, name, fieldOrSpec, options) { - super(db, options); - - // Build the index - const indexParameters = parseIndexOptions(fieldOrSpec); - // Generate the index name - const indexName = typeof options.name === 'string' ? options.name : indexParameters.name; - // Set up the index - const indexesObject = { name: indexName, key: indexParameters.fieldHash }; - - this.name = name; - this.fieldOrSpec = fieldOrSpec; - this.indexes = indexesObject; - } - - _buildCommand() { - const options = this.options; - const name = this.name; - const indexes = this.indexes; - - // merge all the options - for (let optionName in options) { - if (!keysToOmit.has(optionName)) { - indexes[optionName] = options[optionName]; - } - } - - // Create command, apply write concern to command - const cmd = { createIndexes: name, indexes: [indexes] }; - - return cmd; - } - - execute(callback) { - const db = this.db; - const options = this.options; - const indexes = this.indexes; - - // Get capabilities - const capabilities = db.s.topology.capabilities(); - - // Did the user pass in a collation, check if our write server supports it - if (options.collation && capabilities && !capabilities.commandsTakeCollation) { - // Create a new error - const error = new MongoError('server/primary/mongos does not support collation'); - error.code = 67; - // Return the error - return callback(error); - } - - // Ensure we have a callback - if (options.writeConcern && typeof callback !== 'function') { - throw MongoError.create({ - message: 'Cannot use a writeConcern without a provided callback', - driver: true - }); - } - - // Attempt to run using createIndexes command - super.execute((err, result) => { - if (err == null) return handleCallback(callback, err, indexes.name); - - return handleCallback(callback, err, result); - }); - } -} - -defineAspects(CreateIndexOperation, Aspect.WRITE_OPERATION); - -module.exports = CreateIndexOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/create_indexes.js b/scripts/node_modules/mongodb/lib/operations/create_indexes.js deleted file mode 100644 index 46228e8c..00000000 --- a/scripts/node_modules/mongodb/lib/operations/create_indexes.js +++ /dev/null @@ -1,61 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const defineAspects = require('./operation').defineAspects; -const OperationBase = require('./operation').OperationBase; -const executeCommand = require('./db_ops').executeCommand; -const MongoError = require('../core').MongoError; -const ReadPreference = require('../core').ReadPreference; - -class CreateIndexesOperation extends OperationBase { - constructor(collection, indexSpecs, options) { - super(options); - - this.collection = collection; - this.indexSpecs = indexSpecs; - } - - execute(callback) { - const coll = this.collection; - const indexSpecs = this.indexSpecs; - let options = this.options; - - const capabilities = coll.s.topology.capabilities(); - - // Ensure we generate the correct name if the parameter is not set - for (let i = 0; i < indexSpecs.length; i++) { - if (indexSpecs[i].name == null) { - const keys = []; - - // Did the user pass in a collation, check if our write server supports it - if (indexSpecs[i].collation && capabilities && !capabilities.commandsTakeCollation) { - return callback(new MongoError('server/primary/mongos does not support collation')); - } - - for (let name in indexSpecs[i].key) { - keys.push(`${name}_${indexSpecs[i].key[name]}`); - } - - // Set the name - indexSpecs[i].name = keys.join('_'); - } - } - - options = Object.assign({}, options, { readPreference: ReadPreference.PRIMARY }); - - // Execute the index - executeCommand( - coll.s.db, - { - createIndexes: coll.collectionName, - indexes: indexSpecs - }, - options, - callback - ); - } -} - -defineAspects(CreateIndexesOperation, Aspect.WRITE_OPERATION); - -module.exports = CreateIndexesOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/cursor_ops.js b/scripts/node_modules/mongodb/lib/operations/cursor_ops.js deleted file mode 100644 index 513624ff..00000000 --- a/scripts/node_modules/mongodb/lib/operations/cursor_ops.js +++ /dev/null @@ -1,239 +0,0 @@ -'use strict'; - -const buildCountCommand = require('./collection_ops').buildCountCommand; -const formattedOrderClause = require('../utils').formattedOrderClause; -const handleCallback = require('../utils').handleCallback; -const MongoError = require('../core').MongoError; -const push = Array.prototype.push; -const CursorState = require('../core/cursor').CursorState; - -/** - * Get the count of documents for this cursor. - * - * @method - * @param {Cursor} cursor The Cursor instance on which to count. - * @param {boolean} [applySkipLimit=true] Specifies whether the count command apply limit and skip settings should be applied on the cursor or in the provided options. - * @param {object} [options] Optional settings. See Cursor.prototype.count for a list of options. - * @param {Cursor~countResultCallback} [callback] The result callback. - */ -function count(cursor, applySkipLimit, opts, callback) { - if (applySkipLimit) { - if (typeof cursor.cursorSkip() === 'number') opts.skip = cursor.cursorSkip(); - if (typeof cursor.cursorLimit() === 'number') opts.limit = cursor.cursorLimit(); - } - - // Ensure we have the right read preference inheritance - if (opts.readPreference) { - cursor.setReadPreference(opts.readPreference); - } - - if ( - typeof opts.maxTimeMS !== 'number' && - cursor.cmd && - typeof cursor.cmd.maxTimeMS === 'number' - ) { - opts.maxTimeMS = cursor.cmd.maxTimeMS; - } - - let options = {}; - options.skip = opts.skip; - options.limit = opts.limit; - options.hint = opts.hint; - options.maxTimeMS = opts.maxTimeMS; - - // Command - options.collectionName = cursor.namespace.collection; - - let command; - try { - command = buildCountCommand(cursor, cursor.cmd.query, options); - } catch (err) { - return callback(err); - } - - // Set cursor server to the same as the topology - cursor.server = cursor.topology.s.coreTopology; - - // Execute the command - cursor.topology.command( - cursor.namespace.withCollection('$cmd'), - command, - cursor.options, - (err, result) => { - callback(err, result ? result.result.n : null); - } - ); -} - -/** - * Iterates over all the documents for this cursor. See Cursor.prototype.each for more information. - * - * @method - * @deprecated - * @param {Cursor} cursor The Cursor instance on which to run. - * @param {Cursor~resultCallback} callback The result callback. - */ -function each(cursor, callback) { - if (!callback) throw MongoError.create({ message: 'callback is mandatory', driver: true }); - if (cursor.isNotified()) return; - if (cursor.s.state === CursorState.CLOSED || cursor.isDead()) { - return handleCallback( - callback, - MongoError.create({ message: 'Cursor is closed', driver: true }) - ); - } - - if (cursor.s.state === CursorState.INIT) { - cursor.s.state = CursorState.OPEN; - } - - // Define function to avoid global scope escape - let fn = null; - // Trampoline all the entries - if (cursor.bufferedCount() > 0) { - while ((fn = loop(cursor, callback))) fn(cursor, callback); - each(cursor, callback); - } else { - cursor.next((err, item) => { - if (err) return handleCallback(callback, err); - if (item == null) { - return cursor.close({ skipKillCursors: true }, () => handleCallback(callback, null, null)); - } - - if (handleCallback(callback, null, item) === false) return; - each(cursor, callback); - }); - } -} - -/** - * Check if there is any document still available in the cursor. - * - * @method - * @param {Cursor} cursor The Cursor instance on which to run. - * @param {Cursor~resultCallback} [callback] The result callback. - */ -function hasNext(cursor, callback) { - if (cursor.s.currentDoc) { - return callback(null, true); - } - - if (cursor.isNotified()) { - return callback(null, false); - } - - nextObject(cursor, (err, doc) => { - if (err) return callback(err, null); - if (cursor.s.state === CursorState.CLOSED || cursor.isDead()) { - return callback(null, false); - } - - if (!doc) return callback(null, false); - cursor.s.currentDoc = doc; - callback(null, true); - }); -} - -// Trampoline emptying the number of retrieved items -// without incurring a nextTick operation -function loop(cursor, callback) { - // No more items we are done - if (cursor.bufferedCount() === 0) return; - // Get the next document - cursor._next(callback); - // Loop - return loop; -} - -/** - * Get the next available document from the cursor. Returns null if no more documents are available. - * - * @method - * @param {Cursor} cursor The Cursor instance from which to get the next document. - * @param {Cursor~resultCallback} [callback] The result callback. - */ -function next(cursor, callback) { - // Return the currentDoc if someone called hasNext first - if (cursor.s.currentDoc) { - const doc = cursor.s.currentDoc; - cursor.s.currentDoc = null; - return callback(null, doc); - } - - // Return the next object - nextObject(cursor, callback); -} - -// Get the next available document from the cursor, returns null if no more documents are available. -function nextObject(cursor, callback) { - if (cursor.s.state === CursorState.CLOSED || (cursor.isDead && cursor.isDead())) - return handleCallback( - callback, - MongoError.create({ message: 'Cursor is closed', driver: true }) - ); - if (cursor.s.state === CursorState.INIT && cursor.cmd.sort) { - try { - cursor.cmd.sort = formattedOrderClause(cursor.cmd.sort); - } catch (err) { - return handleCallback(callback, err); - } - } - - // Get the next object - cursor._next((err, doc) => { - cursor.s.state = CursorState.OPEN; - if (err) return handleCallback(callback, err); - handleCallback(callback, null, doc); - }); -} - -/** - * Returns an array of documents. See Cursor.prototype.toArray for more information. - * - * @method - * @param {Cursor} cursor The Cursor instance from which to get the next document. - * @param {Cursor~toArrayResultCallback} [callback] The result callback. - */ -function toArray(cursor, callback) { - const items = []; - - // Reset cursor - cursor.rewind(); - cursor.s.state = CursorState.INIT; - - // Fetch all the documents - const fetchDocs = () => { - cursor._next((err, doc) => { - if (err) { - return cursor._endSession - ? cursor._endSession(() => handleCallback(callback, err)) - : handleCallback(callback, err); - } - if (doc == null) { - return cursor.close({ skipKillCursors: true }, () => handleCallback(callback, null, items)); - } - - // Add doc to items - items.push(doc); - - // Get all buffered objects - if (cursor.bufferedCount() > 0) { - let docs = cursor.readBufferedDocuments(cursor.bufferedCount()); - - // Transform the doc if transform method added - if (cursor.s.transforms && typeof cursor.s.transforms.doc === 'function') { - docs = docs.map(cursor.s.transforms.doc); - } - - push.apply(items, docs); - } - - // Attempt a fetch - fetchDocs(); - }); - }; - - fetchDocs(); -} - -module.exports = { count, each, hasNext, next, toArray }; diff --git a/scripts/node_modules/mongodb/lib/operations/db_ops.js b/scripts/node_modules/mongodb/lib/operations/db_ops.js deleted file mode 100644 index 08037620..00000000 --- a/scripts/node_modules/mongodb/lib/operations/db_ops.js +++ /dev/null @@ -1,831 +0,0 @@ -'use strict'; - -const applyWriteConcern = require('../utils').applyWriteConcern; -const Code = require('../core').BSON.Code; -const resolveReadPreference = require('../utils').resolveReadPreference; -const crypto = require('crypto'); -const debugOptions = require('../utils').debugOptions; -const handleCallback = require('../utils').handleCallback; -const MongoError = require('../core').MongoError; -const parseIndexOptions = require('../utils').parseIndexOptions; -const ReadPreference = require('../core').ReadPreference; -const toError = require('../utils').toError; -const CONSTANTS = require('../constants'); -const MongoDBNamespace = require('../utils').MongoDBNamespace; - -const count = require('./collection_ops').count; -const findOne = require('./collection_ops').findOne; -const remove = require('./collection_ops').remove; -const updateOne = require('./collection_ops').updateOne; - -let collection; -function loadCollection() { - if (!collection) { - collection = require('../collection'); - } - return collection; -} -let db; -function loadDb() { - if (!db) { - db = require('../db'); - } - return db; -} - -const debugFields = [ - 'authSource', - 'w', - 'wtimeout', - 'j', - 'native_parser', - 'forceServerObjectId', - 'serializeFunctions', - 'raw', - 'promoteLongs', - 'promoteValues', - 'promoteBuffers', - 'bufferMaxEntries', - 'numberOfRetries', - 'retryMiliSeconds', - 'readPreference', - 'pkFactory', - 'parentDb', - 'promiseLibrary', - 'noListener' -]; - -/** - * Add a user to the database. - * @method - * @param {Db} db The Db instance on which to add a user. - * @param {string} username The username. - * @param {string} password The password. - * @param {object} [options] Optional settings. See Db.prototype.addUser for a list of options. - * @param {Db~resultCallback} [callback] The command result callback - */ -function addUser(db, username, password, options, callback) { - let Db = loadDb(); - - // Did the user destroy the topology - if (db.serverConfig && db.serverConfig.isDestroyed()) - return callback(new MongoError('topology was destroyed')); - // Attempt to execute auth command - executeAuthCreateUserCommand(db, username, password, options, (err, r) => { - // We need to perform the backward compatible insert operation - if (err && err.code === -5000) { - const finalOptions = applyWriteConcern(Object.assign({}, options), { db }, options); - - // Use node md5 generator - const md5 = crypto.createHash('md5'); - // Generate keys used for authentication - md5.update(username + ':mongo:' + password); - const userPassword = md5.digest('hex'); - - // If we have another db set - const dbToUse = options.dbName ? new Db(options.dbName, db.s.topology, db.s.options) : db; - - // Fetch a user collection - const collection = dbToUse.collection(CONSTANTS.SYSTEM_USER_COLLECTION); - - // Check if we are inserting the first user - count(collection, {}, finalOptions, (err, count) => { - // We got an error (f.ex not authorized) - if (err != null) return handleCallback(callback, err, null); - // Check if the user exists and update i - const findOptions = Object.assign({ projection: { dbName: 1 } }, finalOptions); - collection.find({ user: username }, findOptions).toArray(err => { - // We got an error (f.ex not authorized) - if (err != null) return handleCallback(callback, err, null); - // Add command keys - finalOptions.upsert = true; - - // We have a user, let's update the password or upsert if not - updateOne( - collection, - { user: username }, - { $set: { user: username, pwd: userPassword } }, - finalOptions, - err => { - if (count === 0 && err) - return handleCallback(callback, null, [{ user: username, pwd: userPassword }]); - if (err) return handleCallback(callback, err, null); - handleCallback(callback, null, [{ user: username, pwd: userPassword }]); - } - ); - }); - }); - - return; - } - - if (err) return handleCallback(callback, err); - handleCallback(callback, err, r); - }); -} - -/** - * Fetch all collections for the current db. - * - * @method - * @param {Db} db The Db instance on which to fetch collections. - * @param {object} [options] Optional settings. See Db.prototype.collections for a list of options. - * @param {Db~collectionsResultCallback} [callback] The results callback - */ -function collections(db, options, callback) { - let Collection = loadCollection(); - - options = Object.assign({}, options, { nameOnly: true }); - // Let's get the collection names - db.listCollections({}, options).toArray((err, documents) => { - if (err != null) return handleCallback(callback, err, null); - // Filter collections removing any illegal ones - documents = documents.filter(doc => { - return doc.name.indexOf('$') === -1; - }); - - // Return the collection objects - handleCallback( - callback, - null, - documents.map(d => { - return new Collection( - db, - db.s.topology, - db.databaseName, - d.name, - db.s.pkFactory, - db.s.options - ); - }) - ); - }); -} - -/** - * Creates an index on the db and collection. - * @method - * @param {Db} db The Db instance on which to create an index. - * @param {string} name Name of the collection to create the index on. - * @param {(string|object)} fieldOrSpec Defines the index. - * @param {object} [options] Optional settings. See Db.prototype.createIndex for a list of options. - * @param {Db~resultCallback} [callback] The command result callback - */ -function createIndex(db, name, fieldOrSpec, options, callback) { - // Get the write concern options - let finalOptions = Object.assign({}, { readPreference: ReadPreference.PRIMARY }, options); - finalOptions = applyWriteConcern(finalOptions, { db }, options); - - // Ensure we have a callback - if (finalOptions.writeConcern && typeof callback !== 'function') { - throw MongoError.create({ - message: 'Cannot use a writeConcern without a provided callback', - driver: true - }); - } - - // Did the user destroy the topology - if (db.serverConfig && db.serverConfig.isDestroyed()) - return callback(new MongoError('topology was destroyed')); - - // Attempt to run using createIndexes command - createIndexUsingCreateIndexes(db, name, fieldOrSpec, finalOptions, (err, result) => { - if (err == null) return handleCallback(callback, err, result); - - /** - * The following errors mean that the server recognized `createIndex` as a command so we don't need to fallback to an insert: - * 67 = 'CannotCreateIndex' (malformed index options) - * 85 = 'IndexOptionsConflict' (index already exists with different options) - * 86 = 'IndexKeySpecsConflict' (index already exists with the same name) - * 11000 = 'DuplicateKey' (couldn't build unique index because of dupes) - * 11600 = 'InterruptedAtShutdown' (interrupted at shutdown) - * 197 = 'InvalidIndexSpecificationOption' (`_id` with `background: true`) - */ - if ( - err.code === 67 || - err.code === 11000 || - err.code === 85 || - err.code === 86 || - err.code === 11600 || - err.code === 197 - ) { - return handleCallback(callback, err, result); - } - - // Create command - const doc = createCreateIndexCommand(db, name, fieldOrSpec, options); - // Set no key checking - finalOptions.checkKeys = false; - // Insert document - db.s.topology.insert( - db.s.namespace.withCollection(CONSTANTS.SYSTEM_INDEX_COLLECTION), - doc, - finalOptions, - (err, result) => { - if (callback == null) return; - if (err) return handleCallback(callback, err); - if (result == null) return handleCallback(callback, null, null); - if (result.result.writeErrors) - return handleCallback(callback, MongoError.create(result.result.writeErrors[0]), null); - handleCallback(callback, null, doc.name); - } - ); - }); -} - -// Add listeners to topology -function createListener(db, e, object) { - function listener(err) { - if (object.listeners(e).length > 0) { - object.emit(e, err, db); - - // Emit on all associated db's if available - for (let i = 0; i < db.s.children.length; i++) { - db.s.children[i].emit(e, err, db.s.children[i]); - } - } - } - return listener; -} - -/** - * Drop a collection from the database, removing it permanently. New accesses will create a new collection. - * - * @method - * @param {Db} db The Db instance on which to drop the collection. - * @param {string} name Name of collection to drop - * @param {Object} [options] Optional settings. See Db.prototype.dropCollection for a list of options. - * @param {Db~resultCallback} [callback] The results callback - */ -function dropCollection(db, name, options, callback) { - executeCommand(db, name, options, (err, result) => { - // Did the user destroy the topology - if (db.serverConfig && db.serverConfig.isDestroyed()) { - return callback(new MongoError('topology was destroyed')); - } - - if (err) return handleCallback(callback, err); - if (result.ok) return handleCallback(callback, null, true); - handleCallback(callback, null, false); - }); -} - -/** - * Drop a database, removing it permanently from the server. - * - * @method - * @param {Db} db The Db instance to drop. - * @param {Object} cmd The command document. - * @param {Object} [options] Optional settings. See Db.prototype.dropDatabase for a list of options. - * @param {Db~resultCallback} [callback] The results callback - */ -function dropDatabase(db, cmd, options, callback) { - executeCommand(db, cmd, options, (err, result) => { - // Did the user destroy the topology - if (db.serverConfig && db.serverConfig.isDestroyed()) { - return callback(new MongoError('topology was destroyed')); - } - - if (callback == null) return; - if (err) return handleCallback(callback, err, null); - handleCallback(callback, null, result.ok ? true : false); - }); -} - -/** - * Ensures that an index exists. If it does not, creates it. - * - * @method - * @param {Db} db The Db instance on which to ensure the index. - * @param {string} name The index name - * @param {(string|object)} fieldOrSpec Defines the index. - * @param {object} [options] Optional settings. See Db.prototype.ensureIndex for a list of options. - * @param {Db~resultCallback} [callback] The command result callback - */ -function ensureIndex(db, name, fieldOrSpec, options, callback) { - // Get the write concern options - const finalOptions = applyWriteConcern({}, { db }, options); - // Create command - const selector = createCreateIndexCommand(db, name, fieldOrSpec, options); - const index_name = selector.name; - - // Did the user destroy the topology - if (db.serverConfig && db.serverConfig.isDestroyed()) - return callback(new MongoError('topology was destroyed')); - - // Merge primary readPreference - finalOptions.readPreference = ReadPreference.PRIMARY; - - // Check if the index already exists - indexInformation(db, name, finalOptions, (err, indexInformation) => { - if (err != null && err.code !== 26) return handleCallback(callback, err, null); - // If the index does not exist, create it - if (indexInformation == null || !indexInformation[index_name]) { - createIndex(db, name, fieldOrSpec, options, callback); - } else { - if (typeof callback === 'function') return handleCallback(callback, null, index_name); - } - }); -} - -/** - * Evaluate JavaScript on the server - * - * @method - * @param {Db} db The Db instance. - * @param {Code} code JavaScript to execute on server. - * @param {(object|array)} parameters The parameters for the call. - * @param {object} [options] Optional settings. See Db.prototype.eval for a list of options. - * @param {Db~resultCallback} [callback] The results callback - * @deprecated Eval is deprecated on MongoDB 3.2 and forward - */ -function evaluate(db, code, parameters, options, callback) { - let finalCode = code; - let finalParameters = []; - - // Did the user destroy the topology - if (db.serverConfig && db.serverConfig.isDestroyed()) - return callback(new MongoError('topology was destroyed')); - - // If not a code object translate to one - if (!(finalCode && finalCode._bsontype === 'Code')) finalCode = new Code(finalCode); - // Ensure the parameters are correct - if (parameters != null && !Array.isArray(parameters) && typeof parameters !== 'function') { - finalParameters = [parameters]; - } else if (parameters != null && Array.isArray(parameters) && typeof parameters !== 'function') { - finalParameters = parameters; - } - - // Create execution selector - let cmd = { $eval: finalCode, args: finalParameters }; - // Check if the nolock parameter is passed in - if (options['nolock']) { - cmd['nolock'] = options['nolock']; - } - - // Set primary read preference - options.readPreference = new ReadPreference(ReadPreference.PRIMARY); - - // Execute the command - executeCommand(db, cmd, options, (err, result) => { - if (err) return handleCallback(callback, err, null); - if (result && result.ok === 1) return handleCallback(callback, null, result.retval); - if (result) - return handleCallback( - callback, - MongoError.create({ message: `eval failed: ${result.errmsg}`, driver: true }), - null - ); - handleCallback(callback, err, result); - }); -} - -/** - * Execute a command - * - * @method - * @param {Db} db The Db instance on which to execute the command. - * @param {object} command The command hash - * @param {object} [options] Optional settings. See Db.prototype.command for a list of options. - * @param {Db~resultCallback} [callback] The command result callback - */ -function executeCommand(db, command, options, callback) { - // Did the user destroy the topology - if (db.serverConfig && db.serverConfig.isDestroyed()) - return callback(new MongoError('topology was destroyed')); - // Get the db name we are executing against - const dbName = options.dbName || options.authdb || db.databaseName; - - // Convert the readPreference if its not a write - options.readPreference = resolveReadPreference(db, options); - - // Debug information - if (db.s.logger.isDebug()) - db.s.logger.debug( - `executing command ${JSON.stringify( - command - )} against ${dbName}.$cmd with options [${JSON.stringify( - debugOptions(debugFields, options) - )}]` - ); - - // Execute command - db.s.topology.command(db.s.namespace.withCollection('$cmd'), command, options, (err, result) => { - if (err) return handleCallback(callback, err); - if (options.full) return handleCallback(callback, null, result); - handleCallback(callback, null, result.result); - }); -} - -/** - * Runs a command on the database as admin. - * - * @method - * @param {Db} db The Db instance on which to execute the command. - * @param {object} command The command hash - * @param {object} [options] Optional settings. See Db.prototype.executeDbAdminCommand for a list of options. - * @param {Db~resultCallback} [callback] The command result callback - */ -function executeDbAdminCommand(db, command, options, callback) { - const namespace = new MongoDBNamespace('admin', '$cmd'); - - db.s.topology.command(namespace, command, options, (err, result) => { - // Did the user destroy the topology - if (db.serverConfig && db.serverConfig.isDestroyed()) { - return callback(new MongoError('topology was destroyed')); - } - - if (err) return handleCallback(callback, err); - handleCallback(callback, null, result.result); - }); -} - -/** - * Retrieves this collections index info. - * - * @method - * @param {Db} db The Db instance on which to retrieve the index info. - * @param {string} name The name of the collection. - * @param {object} [options] Optional settings. See Db.prototype.indexInformation for a list of options. - * @param {Db~resultCallback} [callback] The command result callback - */ -function indexInformation(db, name, options, callback) { - // If we specified full information - const full = options['full'] == null ? false : options['full']; - - // Did the user destroy the topology - if (db.serverConfig && db.serverConfig.isDestroyed()) - return callback(new MongoError('topology was destroyed')); - // Process all the results from the index command and collection - function processResults(indexes) { - // Contains all the information - let info = {}; - // Process all the indexes - for (let i = 0; i < indexes.length; i++) { - const index = indexes[i]; - // Let's unpack the object - info[index.name] = []; - for (let name in index.key) { - info[index.name].push([name, index.key[name]]); - } - } - - return info; - } - - // Get the list of indexes of the specified collection - db - .collection(name) - .listIndexes(options) - .toArray((err, indexes) => { - if (err) return callback(toError(err)); - if (!Array.isArray(indexes)) return handleCallback(callback, null, []); - if (full) return handleCallback(callback, null, indexes); - handleCallback(callback, null, processResults(indexes)); - }); -} - -/** - * Retrieve the current profiling information for MongoDB - * - * @method - * @param {Db} db The Db instance on which to retrieve the profiling info. - * @param {Object} [options] Optional settings. See Db.protoype.profilingInfo for a list of options. - * @param {Db~resultCallback} [callback] The command result callback. - * @deprecated Query the system.profile collection directly. - */ -function profilingInfo(db, options, callback) { - try { - db - .collection('system.profile') - .find({}, options) - .toArray(callback); - } catch (err) { - return callback(err, null); - } -} - -/** - * Remove a user from a database - * - * @method - * @param {Db} db The Db instance on which to remove the user. - * @param {string} username The username. - * @param {object} [options] Optional settings. See Db.prototype.removeUser for a list of options. - * @param {Db~resultCallback} [callback] The command result callback - */ -function removeUser(db, username, options, callback) { - let Db = loadDb(); - - // Attempt to execute command - executeAuthRemoveUserCommand(db, username, options, (err, result) => { - if (err && err.code === -5000) { - const finalOptions = applyWriteConcern(Object.assign({}, options), { db }, options); - // If we have another db set - const db = options.dbName ? new Db(options.dbName, db.s.topology, db.s.options) : db; - - // Fetch a user collection - const collection = db.collection(CONSTANTS.SYSTEM_USER_COLLECTION); - - // Locate the user - findOne(collection, { user: username }, finalOptions, (err, user) => { - if (user == null) return handleCallback(callback, err, false); - remove(collection, { user: username }, finalOptions, err => { - handleCallback(callback, err, true); - }); - }); - - return; - } - - if (err) return handleCallback(callback, err); - handleCallback(callback, err, result); - }); -} - -// Validate the database name -function validateDatabaseName(databaseName) { - if (typeof databaseName !== 'string') - throw MongoError.create({ message: 'database name must be a string', driver: true }); - if (databaseName.length === 0) - throw MongoError.create({ message: 'database name cannot be the empty string', driver: true }); - if (databaseName === '$external') return; - - const invalidChars = [' ', '.', '$', '/', '\\']; - for (let i = 0; i < invalidChars.length; i++) { - if (databaseName.indexOf(invalidChars[i]) !== -1) - throw MongoError.create({ - message: "database names cannot contain the character '" + invalidChars[i] + "'", - driver: true - }); - } -} - -/** - * Create the command object for Db.prototype.createIndex. - * - * @param {Db} db The Db instance on which to create the command. - * @param {string} name Name of the collection to create the index on. - * @param {(string|object)} fieldOrSpec Defines the index. - * @param {Object} [options] Optional settings. See Db.prototype.createIndex for a list of options. - * @return {Object} The insert command object. - */ -function createCreateIndexCommand(db, name, fieldOrSpec, options) { - const indexParameters = parseIndexOptions(fieldOrSpec); - const fieldHash = indexParameters.fieldHash; - - // Generate the index name - const indexName = typeof options.name === 'string' ? options.name : indexParameters.name; - const selector = { - ns: db.s.namespace.withCollection(name).toString(), - key: fieldHash, - name: indexName - }; - - // Ensure we have a correct finalUnique - const finalUnique = options == null || 'object' === typeof options ? false : options; - // Set up options - options = options == null || typeof options === 'boolean' ? {} : options; - - // Add all the options - const keysToOmit = Object.keys(selector); - for (let optionName in options) { - if (keysToOmit.indexOf(optionName) === -1) { - selector[optionName] = options[optionName]; - } - } - - if (selector['unique'] == null) selector['unique'] = finalUnique; - - // Remove any write concern operations - const removeKeys = ['w', 'wtimeout', 'j', 'fsync', 'readPreference', 'session']; - for (let i = 0; i < removeKeys.length; i++) { - delete selector[removeKeys[i]]; - } - - // Return the command creation selector - return selector; -} - -/** - * Create index using the createIndexes command. - * - * @param {Db} db The Db instance on which to execute the command. - * @param {string} name Name of the collection to create the index on. - * @param {(string|object)} fieldOrSpec Defines the index. - * @param {Object} [options] Optional settings. See Db.prototype.createIndex for a list of options. - * @param {Db~resultCallback} [callback] The command result callback. - */ -function createIndexUsingCreateIndexes(db, name, fieldOrSpec, options, callback) { - // Build the index - const indexParameters = parseIndexOptions(fieldOrSpec); - // Generate the index name - const indexName = typeof options.name === 'string' ? options.name : indexParameters.name; - // Set up the index - const indexes = [{ name: indexName, key: indexParameters.fieldHash }]; - // merge all the options - const keysToOmit = Object.keys(indexes[0]).concat([ - 'writeConcern', - 'w', - 'wtimeout', - 'j', - 'fsync', - 'readPreference', - 'session' - ]); - - for (let optionName in options) { - if (keysToOmit.indexOf(optionName) === -1) { - indexes[0][optionName] = options[optionName]; - } - } - - // Get capabilities - const capabilities = db.s.topology.capabilities(); - - // Did the user pass in a collation, check if our write server supports it - if (indexes[0].collation && capabilities && !capabilities.commandsTakeCollation) { - // Create a new error - const error = new MongoError('server/primary/mongos does not support collation'); - error.code = 67; - // Return the error - return callback(error); - } - - // Create command, apply write concern to command - const cmd = applyWriteConcern({ createIndexes: name, indexes }, { db }, options); - - // ReadPreference primary - options.readPreference = ReadPreference.PRIMARY; - - // Build the command - executeCommand(db, cmd, options, (err, result) => { - if (err) return handleCallback(callback, err, null); - if (result.ok === 0) return handleCallback(callback, toError(result), null); - // Return the indexName for backward compatibility - handleCallback(callback, null, indexName); - }); -} - -/** - * Run the createUser command. - * - * @param {Db} db The Db instance on which to execute the command. - * @param {string} username The username of the user to add. - * @param {string} password The password of the user to add. - * @param {object} [options] Optional settings. See Db.prototype.addUser for a list of options. - * @param {Db~resultCallback} [callback] The command result callback - */ -function executeAuthCreateUserCommand(db, username, password, options, callback) { - // Special case where there is no password ($external users) - if (typeof username === 'string' && password != null && typeof password === 'object') { - options = password; - password = null; - } - - // Unpack all options - if (typeof options === 'function') { - callback = options; - options = {}; - } - - // Error out if we digestPassword set - if (options.digestPassword != null) { - return callback( - toError( - "The digestPassword option is not supported via add_user. Please use db.command('createUser', ...) instead for this option." - ) - ); - } - - // Get additional values - const customData = options.customData != null ? options.customData : {}; - let roles = Array.isArray(options.roles) ? options.roles : []; - const maxTimeMS = typeof options.maxTimeMS === 'number' ? options.maxTimeMS : null; - - // If not roles defined print deprecated message - if (roles.length === 0) { - console.log('Creating a user without roles is deprecated in MongoDB >= 2.6'); - } - - // Get the error options - const commandOptions = { writeCommand: true }; - if (options['dbName']) commandOptions.dbName = options['dbName']; - - // Add maxTimeMS to options if set - if (maxTimeMS != null) commandOptions.maxTimeMS = maxTimeMS; - - // Check the db name and add roles if needed - if ( - (db.databaseName.toLowerCase() === 'admin' || options.dbName === 'admin') && - !Array.isArray(options.roles) - ) { - roles = ['root']; - } else if (!Array.isArray(options.roles)) { - roles = ['dbOwner']; - } - - const digestPassword = db.s.topology.lastIsMaster().maxWireVersion >= 7; - - // Build the command to execute - let command = { - createUser: username, - customData: customData, - roles: roles, - digestPassword - }; - - // Apply write concern to command - command = applyWriteConcern(command, { db }, options); - - let userPassword = password; - - if (!digestPassword) { - // Use node md5 generator - const md5 = crypto.createHash('md5'); - // Generate keys used for authentication - md5.update(username + ':mongo:' + password); - userPassword = md5.digest('hex'); - } - - // No password - if (typeof password === 'string') { - command.pwd = userPassword; - } - - // Force write using primary - commandOptions.readPreference = ReadPreference.primary; - - // Execute the command - executeCommand(db, command, commandOptions, (err, result) => { - if (err && err.ok === 0 && err.code === undefined) - return handleCallback(callback, { code: -5000 }, null); - if (err) return handleCallback(callback, err, null); - handleCallback( - callback, - !result.ok ? toError(result) : null, - result.ok ? [{ user: username, pwd: '' }] : null - ); - }); -} - -/** - * Run the dropUser command. - * - * @param {Db} db The Db instance on which to execute the command. - * @param {string} username The username of the user to remove. - * @param {object} [options] Optional settings. See Db.prototype.removeUser for a list of options. - * @param {Db~resultCallback} [callback] The command result callback - */ -function executeAuthRemoveUserCommand(db, username, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - // Did the user destroy the topology - if (db.serverConfig && db.serverConfig.isDestroyed()) - return callback(new MongoError('topology was destroyed')); - // Get the error options - const commandOptions = { writeCommand: true }; - if (options['dbName']) commandOptions.dbName = options['dbName']; - - // Get additional values - const maxTimeMS = typeof options.maxTimeMS === 'number' ? options.maxTimeMS : null; - - // Add maxTimeMS to options if set - if (maxTimeMS != null) commandOptions.maxTimeMS = maxTimeMS; - - // Build the command to execute - let command = { - dropUser: username - }; - - // Apply write concern to command - command = applyWriteConcern(command, { db }, options); - - // Force write using primary - commandOptions.readPreference = ReadPreference.primary; - - // Execute the command - executeCommand(db, command, commandOptions, (err, result) => { - if (err && !err.ok && err.code === undefined) return handleCallback(callback, { code: -5000 }); - if (err) return handleCallback(callback, err, null); - handleCallback(callback, null, result.ok ? true : false); - }); -} - -module.exports = { - addUser, - collections, - createListener, - createIndex, - dropCollection, - dropDatabase, - ensureIndex, - evaluate, - executeCommand, - executeDbAdminCommand, - indexInformation, - profilingInfo, - removeUser, - validateDatabaseName -}; diff --git a/scripts/node_modules/mongodb/lib/operations/delete_many.js b/scripts/node_modules/mongodb/lib/operations/delete_many.js deleted file mode 100644 index d881f67d..00000000 --- a/scripts/node_modules/mongodb/lib/operations/delete_many.js +++ /dev/null @@ -1,25 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const deleteCallback = require('./common_functions').deleteCallback; -const removeDocuments = require('./common_functions').removeDocuments; - -class DeleteManyOperation extends OperationBase { - constructor(collection, filter, options) { - super(options); - - this.collection = collection; - this.filter = filter; - } - - execute(callback) { - const coll = this.collection; - const filter = this.filter; - const options = this.options; - - options.single = false; - removeDocuments(coll, filter, options, (err, r) => deleteCallback(err, r, callback)); - } -} - -module.exports = DeleteManyOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/delete_one.js b/scripts/node_modules/mongodb/lib/operations/delete_one.js deleted file mode 100644 index b05597fd..00000000 --- a/scripts/node_modules/mongodb/lib/operations/delete_one.js +++ /dev/null @@ -1,25 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const deleteCallback = require('./common_functions').deleteCallback; -const removeDocuments = require('./common_functions').removeDocuments; - -class DeleteOneOperation extends OperationBase { - constructor(collection, filter, options) { - super(options); - - this.collection = collection; - this.filter = filter; - } - - execute(callback) { - const coll = this.collection; - const filter = this.filter; - const options = this.options; - - options.single = true; - removeDocuments(coll, filter, options, (err, r) => deleteCallback(err, r, callback)); - } -} - -module.exports = DeleteOneOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/distinct.js b/scripts/node_modules/mongodb/lib/operations/distinct.js deleted file mode 100644 index dcf4f7e2..00000000 --- a/scripts/node_modules/mongodb/lib/operations/distinct.js +++ /dev/null @@ -1,85 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const defineAspects = require('./operation').defineAspects; -const CommandOperationV2 = require('./command_v2'); -const decorateWithCollation = require('../utils').decorateWithCollation; -const decorateWithReadConcern = require('../utils').decorateWithReadConcern; - -/** - * Return a list of distinct values for the given key across a collection. - * - * @class - * @property {Collection} a Collection instance. - * @property {string} key Field of the document to find distinct values for. - * @property {object} query The query for filtering the set of documents to which we apply the distinct filter. - * @property {object} [options] Optional settings. See Collection.prototype.distinct for a list of options. - */ -class DistinctOperation extends CommandOperationV2 { - /** - * Construct a Distinct operation. - * - * @param {Collection} a Collection instance. - * @param {string} key Field of the document to find distinct values for. - * @param {object} query The query for filtering the set of documents to which we apply the distinct filter. - * @param {object} [options] Optional settings. See Collection.prototype.distinct for a list of options. - */ - constructor(collection, key, query, options) { - super(collection, options); - - this.collection = collection; - this.key = key; - this.query = query; - } - - /** - * Execute the operation. - * - * @param {Collection~resultCallback} [callback] The command result callback - */ - execute(server, callback) { - const coll = this.collection; - const key = this.key; - const query = this.query; - const options = this.options; - - // Distinct command - const cmd = { - distinct: coll.collectionName, - key: key, - query: query - }; - - // Add maxTimeMS if defined - if (typeof options.maxTimeMS === 'number') { - cmd.maxTimeMS = options.maxTimeMS; - } - - // Do we have a readConcern specified - decorateWithReadConcern(cmd, coll, options); - - // Have we specified collation - try { - decorateWithCollation(cmd, coll, options); - } catch (err) { - return callback(err, null); - } - - super.executeCommand(server, cmd, (err, result) => { - if (err) { - callback(err); - return; - } - - callback(null, this.options.full ? result : result.values); - }); - } -} - -defineAspects(DistinctOperation, [ - Aspect.READ_OPERATION, - Aspect.RETRYABLE, - Aspect.EXECUTE_WITH_SELECTION -]); - -module.exports = DistinctOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/drop.js b/scripts/node_modules/mongodb/lib/operations/drop.js deleted file mode 100644 index be03716f..00000000 --- a/scripts/node_modules/mongodb/lib/operations/drop.js +++ /dev/null @@ -1,53 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const CommandOperation = require('./command'); -const defineAspects = require('./operation').defineAspects; -const handleCallback = require('../utils').handleCallback; - -class DropOperation extends CommandOperation { - constructor(db, options) { - const finalOptions = Object.assign({}, options, db.s.options); - - if (options.session) { - finalOptions.session = options.session; - } - - super(db, finalOptions); - } - - execute(callback) { - super.execute((err, result) => { - if (err) return handleCallback(callback, err); - if (result.ok) return handleCallback(callback, null, true); - handleCallback(callback, null, false); - }); - } -} - -defineAspects(DropOperation, Aspect.WRITE_OPERATION); - -class DropCollectionOperation extends DropOperation { - constructor(db, name, options) { - super(db, options); - - this.name = name; - this.namespace = `${db.namespace}.${name}`; - } - - _buildCommand() { - return { drop: this.name }; - } -} - -class DropDatabaseOperation extends DropOperation { - _buildCommand() { - return { dropDatabase: 1 }; - } -} - -module.exports = { - DropOperation, - DropCollectionOperation, - DropDatabaseOperation -}; diff --git a/scripts/node_modules/mongodb/lib/operations/drop_index.js b/scripts/node_modules/mongodb/lib/operations/drop_index.js deleted file mode 100644 index a6ca783d..00000000 --- a/scripts/node_modules/mongodb/lib/operations/drop_index.js +++ /dev/null @@ -1,42 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const defineAspects = require('./operation').defineAspects; -const CommandOperation = require('./command'); -const applyWriteConcern = require('../utils').applyWriteConcern; -const handleCallback = require('../utils').handleCallback; - -class DropIndexOperation extends CommandOperation { - constructor(collection, indexName, options) { - super(collection.s.db, options, collection); - - this.collection = collection; - this.indexName = indexName; - } - - _buildCommand() { - const collection = this.collection; - const indexName = this.indexName; - const options = this.options; - - let cmd = { dropIndexes: collection.collectionName, index: indexName }; - - // Decorate command with writeConcern if supported - cmd = applyWriteConcern(cmd, { db: collection.s.db, collection }, options); - - return cmd; - } - - execute(callback) { - // Execute command - super.execute((err, result) => { - if (typeof callback !== 'function') return; - if (err) return handleCallback(callback, err, null); - handleCallback(callback, null, result); - }); - } -} - -defineAspects(DropIndexOperation, Aspect.WRITE_OPERATION); - -module.exports = DropIndexOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/drop_indexes.js b/scripts/node_modules/mongodb/lib/operations/drop_indexes.js deleted file mode 100644 index ed404ee9..00000000 --- a/scripts/node_modules/mongodb/lib/operations/drop_indexes.js +++ /dev/null @@ -1,23 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const defineAspects = require('./operation').defineAspects; -const DropIndexOperation = require('./drop_index'); -const handleCallback = require('../utils').handleCallback; - -class DropIndexesOperation extends DropIndexOperation { - constructor(collection, options) { - super(collection, '*', options); - } - - execute(callback) { - super.execute(err => { - if (err) return handleCallback(callback, err, false); - handleCallback(callback, null, true); - }); - } -} - -defineAspects(DropIndexesOperation, Aspect.WRITE_OPERATION); - -module.exports = DropIndexesOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/estimated_document_count.js b/scripts/node_modules/mongodb/lib/operations/estimated_document_count.js deleted file mode 100644 index e2d65563..00000000 --- a/scripts/node_modules/mongodb/lib/operations/estimated_document_count.js +++ /dev/null @@ -1,58 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const defineAspects = require('./operation').defineAspects; -const CommandOperationV2 = require('./command_v2'); - -class EstimatedDocumentCountOperation extends CommandOperationV2 { - constructor(collection, query, options) { - if (typeof options === 'undefined') { - options = query; - query = undefined; - } - - super(collection, options); - this.collectionName = collection.s.namespace.collection; - if (query) { - this.query = query; - } - } - - execute(server, callback) { - const options = this.options; - const cmd = { count: this.collectionName }; - - if (this.query) { - cmd.query = this.query; - } - - if (typeof options.skip === 'number') { - cmd.skip = options.skip; - } - - if (typeof options.limit === 'number') { - cmd.limit = options.limit; - } - - if (options.hint) { - cmd.hint = options.hint; - } - - super.executeCommand(server, cmd, (err, response) => { - if (err) { - callback(err); - return; - } - - callback(null, response.n); - }); - } -} - -defineAspects(EstimatedDocumentCountOperation, [ - Aspect.READ_OPERATION, - Aspect.RETRYABLE, - Aspect.EXECUTE_WITH_SELECTION -]); - -module.exports = EstimatedDocumentCountOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/execute_db_admin_command.js b/scripts/node_modules/mongodb/lib/operations/execute_db_admin_command.js deleted file mode 100644 index d15fc8e6..00000000 --- a/scripts/node_modules/mongodb/lib/operations/execute_db_admin_command.js +++ /dev/null @@ -1,34 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const handleCallback = require('../utils').handleCallback; -const MongoError = require('../core').MongoError; -const MongoDBNamespace = require('../utils').MongoDBNamespace; - -class ExecuteDbAdminCommandOperation extends OperationBase { - constructor(db, selector, options) { - super(options); - - this.db = db; - this.selector = selector; - } - - execute(callback) { - const db = this.db; - const selector = this.selector; - const options = this.options; - - const namespace = new MongoDBNamespace('admin', '$cmd'); - db.s.topology.command(namespace, selector, options, (err, result) => { - // Did the user destroy the topology - if (db.serverConfig && db.serverConfig.isDestroyed()) { - return callback(new MongoError('topology was destroyed')); - } - - if (err) return handleCallback(callback, err); - handleCallback(callback, null, result.result); - }); - } -} - -module.exports = ExecuteDbAdminCommandOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/execute_operation.js b/scripts/node_modules/mongodb/lib/operations/execute_operation.js deleted file mode 100644 index e23a80c0..00000000 --- a/scripts/node_modules/mongodb/lib/operations/execute_operation.js +++ /dev/null @@ -1,198 +0,0 @@ -'use strict'; - -const MongoError = require('../core/error').MongoError; -const Aspect = require('./operation').Aspect; -const OperationBase = require('./operation').OperationBase; -const ReadPreference = require('../core/topologies/read_preference'); -const isRetryableError = require('../core/error').isRetryableError; -const maxWireVersion = require('../core/utils').maxWireVersion; -const isUnifiedTopology = require('../core/utils').isUnifiedTopology; - -/** - * Executes the given operation with provided arguments. - * - * This method reduces large amounts of duplication in the entire codebase by providing - * a single point for determining whether callbacks or promises should be used. Additionally - * it allows for a single point of entry to provide features such as implicit sessions, which - * are required by the Driver Sessions specification in the event that a ClientSession is - * not provided - * - * @param {object} topology The topology to execute this operation on - * @param {Operation} operation The operation to execute - * @param {function} callback The command result callback - */ -function executeOperation(topology, operation, callback) { - if (topology == null) { - throw new TypeError('This method requires a valid topology instance'); - } - - if (!(operation instanceof OperationBase)) { - throw new TypeError('This method requires a valid operation instance'); - } - - if ( - isUnifiedTopology(topology) && - !operation.hasAspect(Aspect.SKIP_SESSION) && - topology.shouldCheckForSessionSupport() - ) { - return selectServerForSessionSupport(topology, operation, callback); - } - - const Promise = topology.s.promiseLibrary; - - // The driver sessions spec mandates that we implicitly create sessions for operations - // that are not explicitly provided with a session. - let session, owner; - if (!operation.hasAspect(Aspect.SKIP_SESSION) && topology.hasSessionSupport()) { - if (operation.session == null) { - owner = Symbol(); - session = topology.startSession({ owner }); - operation.session = session; - } else if (operation.session.hasEnded) { - throw new MongoError('Use of expired sessions is not permitted'); - } - } - - const makeExecuteCallback = (resolve, reject) => - function executeCallback(err, result) { - if (session && session.owner === owner) { - session.endSession(() => { - if (operation.session === session) { - operation.clearSession(); - } - if (err) return reject(err); - resolve(result); - }); - } else { - if (err) return reject(err); - resolve(result); - } - }; - - // Execute using callback - if (typeof callback === 'function') { - const handler = makeExecuteCallback( - result => callback(null, result), - err => callback(err, null) - ); - - try { - if (operation.hasAspect(Aspect.EXECUTE_WITH_SELECTION)) { - return executeWithServerSelection(topology, operation, handler); - } else { - return operation.execute(handler); - } - } catch (e) { - handler(e); - throw e; - } - } - - return new Promise(function(resolve, reject) { - const handler = makeExecuteCallback(resolve, reject); - - try { - if (operation.hasAspect(Aspect.EXECUTE_WITH_SELECTION)) { - return executeWithServerSelection(topology, operation, handler); - } else { - return operation.execute(handler); - } - } catch (e) { - handler(e); - } - }); -} - -function supportsRetryableReads(server) { - return maxWireVersion(server) >= 6; -} - -function executeWithServerSelection(topology, operation, callback) { - const readPreference = operation.readPreference || ReadPreference.primary; - const inTransaction = operation.session && operation.session.inTransaction(); - - if (inTransaction && !readPreference.equals(ReadPreference.primary)) { - callback( - new MongoError( - `Read preference in a transaction must be primary, not: ${readPreference.mode}` - ) - ); - - return; - } - - const serverSelectionOptions = { - readPreference, - session: operation.session - }; - - function callbackWithRetry(err, result) { - if (err == null) { - return callback(null, result); - } - - if (!isRetryableError(err)) { - return callback(err); - } - - // select a new server, and attempt to retry the operation - topology.selectServer(serverSelectionOptions, (err, server) => { - if (err || !supportsRetryableReads(server)) { - callback(err, null); - return; - } - - operation.execute(server, callback); - }); - } - - // select a server, and execute the operation against it - topology.selectServer(serverSelectionOptions, (err, server) => { - if (err) { - callback(err, null); - return; - } - - const shouldRetryReads = - topology.s.options.retryReads !== false && - (operation.session && !inTransaction) && - supportsRetryableReads(server) && - operation.canRetryRead; - - if (operation.hasAspect(Aspect.RETRYABLE) && shouldRetryReads) { - operation.execute(server, callbackWithRetry); - return; - } - - operation.execute(server, callback); - }); -} - -// TODO: This is only supported for unified topology, it should go away once -// we remove support for legacy topology types. -function selectServerForSessionSupport(topology, operation, callback) { - const Promise = topology.s.promiseLibrary; - - let result; - if (typeof callback !== 'function') { - result = new Promise((resolve, reject) => { - callback = (err, result) => { - if (err) return reject(err); - resolve(result); - }; - }); - } - - topology.selectServer(ReadPreference.primaryPreferred, err => { - if (err) { - callback(err); - return; - } - - executeOperation(topology, operation, callback); - }); - - return result; -} - -module.exports = executeOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/explain.js b/scripts/node_modules/mongodb/lib/operations/explain.js deleted file mode 100644 index 44f3b483..00000000 --- a/scripts/node_modules/mongodb/lib/operations/explain.js +++ /dev/null @@ -1,23 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const CoreCursor = require('../core/cursor').CoreCursor; -const defineAspects = require('./operation').defineAspects; -const OperationBase = require('./operation').OperationBase; - -class ExplainOperation extends OperationBase { - constructor(cursor) { - super(); - - this.cursor = cursor; - } - - execute() { - const cursor = this.cursor; - return CoreCursor.prototype._next.apply(cursor, arguments); - } -} - -defineAspects(ExplainOperation, Aspect.SKIP_SESSION); - -module.exports = ExplainOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/find.js b/scripts/node_modules/mongodb/lib/operations/find.js deleted file mode 100644 index 6838213c..00000000 --- a/scripts/node_modules/mongodb/lib/operations/find.js +++ /dev/null @@ -1,35 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const Aspect = require('./operation').Aspect; -const defineAspects = require('./operation').defineAspects; -const resolveReadPreference = require('../utils').resolveReadPreference; - -class FindOperation extends OperationBase { - constructor(collection, ns, command, options) { - super(options); - - this.ns = ns; - this.cmd = command; - this.readPreference = resolveReadPreference(collection, this.options); - } - - execute(server, callback) { - // copied from `CommandOperationV2`, to be subclassed in the future - this.server = server; - - const cursorState = this.cursorState || {}; - - // TOOD: use `MongoDBNamespace` through and through - server.query(this.ns.toString(), this.cmd, cursorState, this.options, callback); - } -} - -defineAspects(FindOperation, [ - Aspect.READ_OPERATION, - Aspect.RETRYABLE, - Aspect.EXECUTE_WITH_SELECTION, - Aspect.SKIP_SESSION -]); - -module.exports = FindOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/find_and_modify.js b/scripts/node_modules/mongodb/lib/operations/find_and_modify.js deleted file mode 100644 index 8965eb48..00000000 --- a/scripts/node_modules/mongodb/lib/operations/find_and_modify.js +++ /dev/null @@ -1,98 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const applyRetryableWrites = require('../utils').applyRetryableWrites; -const applyWriteConcern = require('../utils').applyWriteConcern; -const decorateWithCollation = require('../utils').decorateWithCollation; -const executeCommand = require('./db_ops').executeCommand; -const formattedOrderClause = require('../utils').formattedOrderClause; -const handleCallback = require('../utils').handleCallback; -const ReadPreference = require('../core').ReadPreference; - -class FindAndModifyOperation extends OperationBase { - constructor(collection, query, sort, doc, options) { - super(options); - - this.collection = collection; - this.query = query; - this.sort = sort; - this.doc = doc; - } - - execute(callback) { - const coll = this.collection; - const query = this.query; - const sort = formattedOrderClause(this.sort); - const doc = this.doc; - let options = this.options; - - // Create findAndModify command object - const queryObject = { - findAndModify: coll.collectionName, - query: query - }; - - if (sort) { - queryObject.sort = sort; - } - - queryObject.new = options.new ? true : false; - queryObject.remove = options.remove ? true : false; - queryObject.upsert = options.upsert ? true : false; - - const projection = options.projection || options.fields; - - if (projection) { - queryObject.fields = projection; - } - - if (options.arrayFilters) { - queryObject.arrayFilters = options.arrayFilters; - } - - if (doc && !options.remove) { - queryObject.update = doc; - } - - if (options.maxTimeMS) queryObject.maxTimeMS = options.maxTimeMS; - - // Either use override on the function, or go back to default on either the collection - // level or db - options.serializeFunctions = options.serializeFunctions || coll.s.serializeFunctions; - - // No check on the documents - options.checkKeys = false; - - // Final options for retryable writes and write concern - options = applyRetryableWrites(options, coll.s.db); - options = applyWriteConcern(options, { db: coll.s.db, collection: coll }, options); - - // Decorate the findAndModify command with the write Concern - if (options.writeConcern) { - queryObject.writeConcern = options.writeConcern; - } - - // Have we specified bypassDocumentValidation - if (options.bypassDocumentValidation === true) { - queryObject.bypassDocumentValidation = options.bypassDocumentValidation; - } - - options.readPreference = ReadPreference.primary; - - // Have we specified collation - try { - decorateWithCollation(queryObject, coll, options); - } catch (err) { - return callback(err, null); - } - - // Execute the command - executeCommand(coll.s.db, queryObject, options, (err, result) => { - if (err) return handleCallback(callback, err, null); - - return handleCallback(callback, null, result); - }); - } -} - -module.exports = FindAndModifyOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/find_one.js b/scripts/node_modules/mongodb/lib/operations/find_one.js deleted file mode 100644 index d3037a6d..00000000 --- a/scripts/node_modules/mongodb/lib/operations/find_one.js +++ /dev/null @@ -1,33 +0,0 @@ -'use strict'; - -const handleCallback = require('../utils').handleCallback; -const OperationBase = require('./operation').OperationBase; -const toError = require('../utils').toError; - -class FindOneOperation extends OperationBase { - constructor(collection, query, options) { - super(options); - - this.collection = collection; - this.query = query; - } - - execute(callback) { - const coll = this.collection; - const query = this.query; - const options = this.options; - - const cursor = coll - .find(query, options) - .limit(-1) - .batchSize(1); - - // Return the item - cursor.next((err, item) => { - if (err != null) return handleCallback(callback, toError(err), null); - handleCallback(callback, null, item); - }); - } -} - -module.exports = FindOneOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/find_one_and_delete.js b/scripts/node_modules/mongodb/lib/operations/find_one_and_delete.js deleted file mode 100644 index 1c7527dd..00000000 --- a/scripts/node_modules/mongodb/lib/operations/find_one_and_delete.js +++ /dev/null @@ -1,16 +0,0 @@ -'use strict'; - -const FindAndModifyOperation = require('./find_and_modify'); - -class FindOneAndDeleteOperation extends FindAndModifyOperation { - constructor(collection, filter, options) { - // Final options - const finalOptions = Object.assign({}, options); - finalOptions.fields = options.projection; - finalOptions.remove = true; - - super(collection, filter, finalOptions.sort, null, finalOptions); - } -} - -module.exports = FindOneAndDeleteOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/find_one_and_replace.js b/scripts/node_modules/mongodb/lib/operations/find_one_and_replace.js deleted file mode 100644 index ae37df5d..00000000 --- a/scripts/node_modules/mongodb/lib/operations/find_one_and_replace.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; - -const FindAndModifyOperation = require('./find_and_modify'); - -class FindOneAndReplaceOperation extends FindAndModifyOperation { - constructor(collection, filter, replacement, options) { - // Final options - const finalOptions = Object.assign({}, options); - finalOptions.fields = options.projection; - finalOptions.update = true; - finalOptions.new = options.returnOriginal !== void 0 ? !options.returnOriginal : false; - finalOptions.upsert = options.upsert !== void 0 ? !!options.upsert : false; - - super(collection, filter, finalOptions.sort, replacement, finalOptions); - } -} - -module.exports = FindOneAndReplaceOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/find_one_and_update.js b/scripts/node_modules/mongodb/lib/operations/find_one_and_update.js deleted file mode 100644 index 6a199652..00000000 --- a/scripts/node_modules/mongodb/lib/operations/find_one_and_update.js +++ /dev/null @@ -1,19 +0,0 @@ -'use strict'; - -const FindAndModifyOperation = require('./find_and_modify'); - -class FindOneAndUpdateOperation extends FindAndModifyOperation { - constructor(collection, filter, update, options) { - // Final options - const finalOptions = Object.assign({}, options); - finalOptions.fields = options.projection; - finalOptions.update = true; - finalOptions.new = - typeof options.returnOriginal === 'boolean' ? !options.returnOriginal : false; - finalOptions.upsert = typeof options.upsert === 'boolean' ? options.upsert : false; - - super(collection, filter, finalOptions.sort, update, finalOptions); - } -} - -module.exports = FindOneAndUpdateOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/geo_haystack_search.js b/scripts/node_modules/mongodb/lib/operations/geo_haystack_search.js deleted file mode 100644 index edd1fb17..00000000 --- a/scripts/node_modules/mongodb/lib/operations/geo_haystack_search.js +++ /dev/null @@ -1,79 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const defineAspects = require('./operation').defineAspects; -const OperationBase = require('./operation').OperationBase; -const decorateCommand = require('../utils').decorateCommand; -const decorateWithReadConcern = require('../utils').decorateWithReadConcern; -const executeCommand = require('./db_ops').executeCommand; -const handleCallback = require('../utils').handleCallback; -const resolveReadPreference = require('../utils').resolveReadPreference; -const toError = require('../utils').toError; - -/** - * Execute a geo search using a geo haystack index on a collection. - * - * @class - * @property {Collection} a Collection instance. - * @property {number} x Point to search on the x axis, ensure the indexes are ordered in the same order. - * @property {number} y Point to search on the y axis, ensure the indexes are ordered in the same order. - * @property {object} [options] Optional settings. See Collection.prototype.geoHaystackSearch for a list of options. - */ -class GeoHaystackSearchOperation extends OperationBase { - /** - * Construct a GeoHaystackSearch operation. - * - * @param {Collection} a Collection instance. - * @param {number} x Point to search on the x axis, ensure the indexes are ordered in the same order. - * @param {number} y Point to search on the y axis, ensure the indexes are ordered in the same order. - * @param {object} [options] Optional settings. See Collection.prototype.geoHaystackSearch for a list of options. - */ - constructor(collection, x, y, options) { - super(options); - - this.collection = collection; - this.x = x; - this.y = y; - } - - /** - * Execute the operation. - * - * @param {Collection~resultCallback} [callback] The command result callback - */ - execute(callback) { - const coll = this.collection; - const x = this.x; - const y = this.y; - let options = this.options; - - // Build command object - let commandObject = { - geoSearch: coll.collectionName, - near: [x, y] - }; - - // Remove read preference from hash if it exists - commandObject = decorateCommand(commandObject, options, ['readPreference', 'session']); - - options = Object.assign({}, options); - // Ensure we have the right read preference inheritance - options.readPreference = resolveReadPreference(coll, options); - - // Do we have a readConcern specified - decorateWithReadConcern(commandObject, coll, options); - - // Execute the command - executeCommand(coll.s.db, commandObject, options, (err, res) => { - if (err) return handleCallback(callback, err); - if (res.err || res.errmsg) handleCallback(callback, toError(res)); - // should we only be returning res.results here? Not sure if the user - // should see the other return information - handleCallback(callback, null, res); - }); - } -} - -defineAspects(GeoHaystackSearchOperation, Aspect.READ_OPERATION); - -module.exports = GeoHaystackSearchOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/has_next.js b/scripts/node_modules/mongodb/lib/operations/has_next.js deleted file mode 100644 index b2e4b861..00000000 --- a/scripts/node_modules/mongodb/lib/operations/has_next.js +++ /dev/null @@ -1,40 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const defineAspects = require('./operation').defineAspects; -const loadCursor = require('../dynamic_loaders').loadCursor; -const OperationBase = require('./operation').OperationBase; -const nextObject = require('./common_functions').nextObject; - -class HasNextOperation extends OperationBase { - constructor(cursor) { - super(); - - this.cursor = cursor; - } - - execute(callback) { - const cursor = this.cursor; - let Cursor = loadCursor(); - - if (cursor.s.currentDoc) { - return callback(null, true); - } - - if (cursor.isNotified()) { - return callback(null, false); - } - - nextObject(cursor, (err, doc) => { - if (err) return callback(err, null); - if (cursor.s.state === Cursor.CLOSED || cursor.isDead()) return callback(null, false); - if (!doc) return callback(null, false); - cursor.s.currentDoc = doc; - callback(null, true); - }); - } -} - -defineAspects(HasNextOperation, Aspect.SKIP_SESSION); - -module.exports = HasNextOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/index_exists.js b/scripts/node_modules/mongodb/lib/operations/index_exists.js deleted file mode 100644 index bd9dc0e9..00000000 --- a/scripts/node_modules/mongodb/lib/operations/index_exists.js +++ /dev/null @@ -1,39 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const handleCallback = require('../utils').handleCallback; -const indexInformationDb = require('./db_ops').indexInformation; - -class IndexExistsOperation extends OperationBase { - constructor(collection, indexes, options) { - super(options); - - this.collection = collection; - this.indexes = indexes; - } - - execute(callback) { - const coll = this.collection; - const indexes = this.indexes; - const options = this.options; - - indexInformationDb(coll.s.db, coll.collectionName, options, (err, indexInformation) => { - // If we have an error return - if (err != null) return handleCallback(callback, err, null); - // Let's check for the index names - if (!Array.isArray(indexes)) - return handleCallback(callback, null, indexInformation[indexes] != null); - // Check in list of indexes - for (let i = 0; i < indexes.length; i++) { - if (indexInformation[indexes[i]] == null) { - return handleCallback(callback, null, false); - } - } - - // All keys found return true - return handleCallback(callback, null, true); - }); - } -} - -module.exports = IndexExistsOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/index_information.js b/scripts/node_modules/mongodb/lib/operations/index_information.js deleted file mode 100644 index b18a603f..00000000 --- a/scripts/node_modules/mongodb/lib/operations/index_information.js +++ /dev/null @@ -1,23 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const indexInformation = require('./common_functions').indexInformation; - -class IndexInformationOperation extends OperationBase { - constructor(db, name, options) { - super(options); - - this.db = db; - this.name = name; - } - - execute(callback) { - const db = this.db; - const name = this.name; - const options = this.options; - - indexInformation(db, name, options, callback); - } -} - -module.exports = IndexInformationOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/indexes.js b/scripts/node_modules/mongodb/lib/operations/indexes.js deleted file mode 100644 index e29a88aa..00000000 --- a/scripts/node_modules/mongodb/lib/operations/indexes.js +++ /dev/null @@ -1,22 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const indexInformation = require('./common_functions').indexInformation; - -class IndexesOperation extends OperationBase { - constructor(collection, options) { - super(options); - - this.collection = collection; - } - - execute(callback) { - const coll = this.collection; - let options = this.options; - - options = Object.assign({}, { full: true }, options); - indexInformation(coll.s.db, coll.collectionName, options, callback); - } -} - -module.exports = IndexesOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/insert_many.js b/scripts/node_modules/mongodb/lib/operations/insert_many.js deleted file mode 100644 index 460a535d..00000000 --- a/scripts/node_modules/mongodb/lib/operations/insert_many.js +++ /dev/null @@ -1,63 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const BulkWriteOperation = require('./bulk_write'); -const MongoError = require('../core').MongoError; -const prepareDocs = require('./common_functions').prepareDocs; - -class InsertManyOperation extends OperationBase { - constructor(collection, docs, options) { - super(options); - - this.collection = collection; - this.docs = docs; - } - - execute(callback) { - const coll = this.collection; - let docs = this.docs; - const options = this.options; - - if (!Array.isArray(docs)) { - return callback( - MongoError.create({ message: 'docs parameter must be an array of documents', driver: true }) - ); - } - - // If keep going set unordered - options['serializeFunctions'] = options['serializeFunctions'] || coll.s.serializeFunctions; - - docs = prepareDocs(coll, docs, options); - - // Generate the bulk write operations - const operations = [ - { - insertMany: docs - } - ]; - - const bulkWriteOperation = new BulkWriteOperation(coll, operations, options); - - bulkWriteOperation.execute((err, result) => { - if (err) return callback(err, null); - callback(null, mapInsertManyResults(docs, result)); - }); - } -} - -function mapInsertManyResults(docs, r) { - const finalResult = { - result: { ok: 1, n: r.insertedCount }, - ops: docs, - insertedCount: r.insertedCount, - insertedIds: r.insertedIds - }; - - if (r.getLastOp()) { - finalResult.result.opTime = r.getLastOp(); - } - - return finalResult; -} - -module.exports = InsertManyOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/insert_one.js b/scripts/node_modules/mongodb/lib/operations/insert_one.js deleted file mode 100644 index 5e708801..00000000 --- a/scripts/node_modules/mongodb/lib/operations/insert_one.js +++ /dev/null @@ -1,39 +0,0 @@ -'use strict'; - -const MongoError = require('../core').MongoError; -const OperationBase = require('./operation').OperationBase; -const insertDocuments = require('./common_functions').insertDocuments; - -class InsertOneOperation extends OperationBase { - constructor(collection, doc, options) { - super(options); - - this.collection = collection; - this.doc = doc; - } - - execute(callback) { - const coll = this.collection; - const doc = this.doc; - const options = this.options; - - if (Array.isArray(doc)) { - return callback( - MongoError.create({ message: 'doc parameter must be an object', driver: true }) - ); - } - - insertDocuments(coll, [doc], options, (err, r) => { - if (callback == null) return; - if (err && callback) return callback(err); - // Workaround for pre 2.6 servers - if (r == null) return callback(null, { result: { ok: 1 } }); - // Add values to top level to ensure crud spec compatibility - r.insertedCount = r.result.n; - r.insertedId = doc._id; - if (callback) callback(null, r); - }); - } -} - -module.exports = InsertOneOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/is_capped.js b/scripts/node_modules/mongodb/lib/operations/is_capped.js deleted file mode 100644 index 3bfd9ffa..00000000 --- a/scripts/node_modules/mongodb/lib/operations/is_capped.js +++ /dev/null @@ -1,19 +0,0 @@ -'use strict'; - -const OptionsOperation = require('./options_operation'); -const handleCallback = require('../utils').handleCallback; - -class IsCappedOperation extends OptionsOperation { - constructor(collection, options) { - super(collection, options); - } - - execute(callback) { - super.execute((err, document) => { - if (err) return handleCallback(callback, err); - handleCallback(callback, null, !!(document && document.capped)); - }); - } -} - -module.exports = IsCappedOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/list_collections.js b/scripts/node_modules/mongodb/lib/operations/list_collections.js deleted file mode 100644 index ee01d31e..00000000 --- a/scripts/node_modules/mongodb/lib/operations/list_collections.js +++ /dev/null @@ -1,106 +0,0 @@ -'use strict'; - -const CommandOperationV2 = require('./command_v2'); -const Aspect = require('./operation').Aspect; -const defineAspects = require('./operation').defineAspects; -const maxWireVersion = require('../core/utils').maxWireVersion; -const CONSTANTS = require('../constants'); - -const LIST_COLLECTIONS_WIRE_VERSION = 3; - -function listCollectionsTransforms(databaseName) { - const matching = `${databaseName}.`; - - return { - doc: doc => { - const index = doc.name.indexOf(matching); - // Remove database name if available - if (doc.name && index === 0) { - doc.name = doc.name.substr(index + matching.length); - } - - return doc; - } - }; -} - -class ListCollectionsOperation extends CommandOperationV2 { - constructor(db, filter, options) { - super(db, options, { fullResponse: true }); - - this.db = db; - this.filter = filter; - this.nameOnly = !!this.options.nameOnly; - - if (typeof this.options.batchSize === 'number') { - this.batchSize = this.options.batchSize; - } - } - - execute(server, callback) { - if (maxWireVersion(server) < LIST_COLLECTIONS_WIRE_VERSION) { - let filter = this.filter; - const databaseName = this.db.s.namespace.db; - - // If we have legacy mode and have not provided a full db name filter it - if ( - typeof filter.name === 'string' && - !new RegExp('^' + databaseName + '\\.').test(filter.name) - ) { - filter = Object.assign({}, filter); - filter.name = this.db.s.namespace.withCollection(filter.name).toString(); - } - - // No filter, filter by current database - if (filter == null) { - filter.name = `/${databaseName}/`; - } - - // Rewrite the filter to use $and to filter out indexes - if (filter.name) { - filter = { $and: [{ name: filter.name }, { name: /^((?!\$).)*$/ }] }; - } else { - filter = { name: /^((?!\$).)*$/ }; - } - - const transforms = listCollectionsTransforms(databaseName); - server.query( - `${databaseName}.${CONSTANTS.SYSTEM_NAMESPACE_COLLECTION}`, - { query: filter }, - { batchSize: this.batchSize || 1000 }, - {}, - (err, result) => { - if ( - result && - result.message && - result.message.documents && - Array.isArray(result.message.documents) - ) { - result.message.documents = result.message.documents.map(transforms.doc); - } - - callback(err, result); - } - ); - - return; - } - - const command = { - listCollections: 1, - filter: this.filter, - cursor: this.batchSize ? { batchSize: this.batchSize } : {}, - nameOnly: this.nameOnly - }; - - return super.executeCommand(server, command, callback); - } -} - -defineAspects(ListCollectionsOperation, [ - Aspect.READ_OPERATION, - Aspect.RETRYABLE, - Aspect.EXECUTE_WITH_SELECTION -]); - -module.exports = ListCollectionsOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/list_databases.js b/scripts/node_modules/mongodb/lib/operations/list_databases.js deleted file mode 100644 index 62b2606f..00000000 --- a/scripts/node_modules/mongodb/lib/operations/list_databases.js +++ /dev/null @@ -1,38 +0,0 @@ -'use strict'; - -const CommandOperationV2 = require('./command_v2'); -const Aspect = require('./operation').Aspect; -const defineAspects = require('./operation').defineAspects; -const MongoDBNamespace = require('../utils').MongoDBNamespace; - -class ListDatabasesOperation extends CommandOperationV2 { - constructor(db, options) { - super(db, options); - this.ns = new MongoDBNamespace('admin', '$cmd'); - } - - execute(server, callback) { - const cmd = { listDatabases: 1 }; - if (this.options.nameOnly) { - cmd.nameOnly = Number(cmd.nameOnly); - } - - if (this.options.filter) { - cmd.filter = this.options.filter; - } - - if (typeof this.options.authorizedDatabases === 'boolean') { - cmd.authorizedDatabases = this.options.authorizedDatabases; - } - - super.executeCommand(server, cmd, callback); - } -} - -defineAspects(ListDatabasesOperation, [ - Aspect.READ_OPERATION, - Aspect.RETRYABLE, - Aspect.EXECUTE_WITH_SELECTION -]); - -module.exports = ListDatabasesOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/list_indexes.js b/scripts/node_modules/mongodb/lib/operations/list_indexes.js deleted file mode 100644 index 302a31b7..00000000 --- a/scripts/node_modules/mongodb/lib/operations/list_indexes.js +++ /dev/null @@ -1,42 +0,0 @@ -'use strict'; - -const CommandOperationV2 = require('./command_v2'); -const Aspect = require('./operation').Aspect; -const defineAspects = require('./operation').defineAspects; -const maxWireVersion = require('../core/utils').maxWireVersion; - -const LIST_INDEXES_WIRE_VERSION = 3; - -class ListIndexesOperation extends CommandOperationV2 { - constructor(collection, options) { - super(collection, options, { fullResponse: true }); - - this.collectionNamespace = collection.s.namespace; - } - - execute(server, callback) { - const serverWireVersion = maxWireVersion(server); - if (serverWireVersion < LIST_INDEXES_WIRE_VERSION) { - const systemIndexesNS = this.collectionNamespace.withCollection('system.indexes').toString(); - const collectionNS = this.collectionNamespace.toString(); - - server.query(systemIndexesNS, { query: { ns: collectionNS } }, {}, this.options, callback); - return; - } - - const cursor = this.options.batchSize ? { batchSize: this.options.batchSize } : {}; - super.executeCommand( - server, - { listIndexes: this.collectionNamespace.collection, cursor }, - callback - ); - } -} - -defineAspects(ListIndexesOperation, [ - Aspect.READ_OPERATION, - Aspect.RETRYABLE, - Aspect.EXECUTE_WITH_SELECTION -]); - -module.exports = ListIndexesOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/map_reduce.js b/scripts/node_modules/mongodb/lib/operations/map_reduce.js deleted file mode 100644 index 613f3f73..00000000 --- a/scripts/node_modules/mongodb/lib/operations/map_reduce.js +++ /dev/null @@ -1,189 +0,0 @@ -'use strict'; - -const applyWriteConcern = require('../utils').applyWriteConcern; -const Code = require('../core').BSON.Code; -const decorateWithCollation = require('../utils').decorateWithCollation; -const decorateWithReadConcern = require('../utils').decorateWithReadConcern; -const executeCommand = require('./db_ops').executeCommand; -const handleCallback = require('../utils').handleCallback; -const isObject = require('../utils').isObject; -const loadDb = require('../dynamic_loaders').loadDb; -const OperationBase = require('./operation').OperationBase; -const resolveReadPreference = require('../utils').resolveReadPreference; -const toError = require('../utils').toError; - -const exclusionList = [ - 'readPreference', - 'session', - 'bypassDocumentValidation', - 'w', - 'wtimeout', - 'j', - 'writeConcern' -]; - -/** - * Run Map Reduce across a collection. Be aware that the inline option for out will return an array of results not a collection. - * - * @class - * @property {Collection} a Collection instance. - * @property {(function|string)} map The mapping function. - * @property {(function|string)} reduce The reduce function. - * @property {object} [options] Optional settings. See Collection.prototype.mapReduce for a list of options. - */ -class MapReduceOperation extends OperationBase { - /** - * Constructs a MapReduce operation. - * - * @param {Collection} a Collection instance. - * @param {(function|string)} map The mapping function. - * @param {(function|string)} reduce The reduce function. - * @param {object} [options] Optional settings. See Collection.prototype.mapReduce for a list of options. - */ - constructor(collection, map, reduce, options) { - super(options); - - this.collection = collection; - this.map = map; - this.reduce = reduce; - } - - /** - * Execute the operation. - * - * @param {Collection~resultCallback} [callback] The command result callback - */ - execute(callback) { - const coll = this.collection; - const map = this.map; - const reduce = this.reduce; - let options = this.options; - - const mapCommandHash = { - mapreduce: coll.collectionName, - map: map, - reduce: reduce - }; - - // Add any other options passed in - for (let n in options) { - if ('scope' === n) { - mapCommandHash[n] = processScope(options[n]); - } else { - // Only include if not in exclusion list - if (exclusionList.indexOf(n) === -1) { - mapCommandHash[n] = options[n]; - } - } - } - - options = Object.assign({}, options); - - // Ensure we have the right read preference inheritance - options.readPreference = resolveReadPreference(coll, options); - - // If we have a read preference and inline is not set as output fail hard - if ( - options.readPreference !== false && - options.readPreference !== 'primary' && - options['out'] && - (options['out'].inline !== 1 && options['out'] !== 'inline') - ) { - // Force readPreference to primary - options.readPreference = 'primary'; - // Decorate command with writeConcern if supported - applyWriteConcern(mapCommandHash, { db: coll.s.db, collection: coll }, options); - } else { - decorateWithReadConcern(mapCommandHash, coll, options); - } - - // Is bypassDocumentValidation specified - if (options.bypassDocumentValidation === true) { - mapCommandHash.bypassDocumentValidation = options.bypassDocumentValidation; - } - - // Have we specified collation - try { - decorateWithCollation(mapCommandHash, coll, options); - } catch (err) { - return callback(err, null); - } - - // Execute command - executeCommand(coll.s.db, mapCommandHash, options, (err, result) => { - if (err) return handleCallback(callback, err); - // Check if we have an error - if (1 !== result.ok || result.err || result.errmsg) { - return handleCallback(callback, toError(result)); - } - - // Create statistics value - const stats = {}; - if (result.timeMillis) stats['processtime'] = result.timeMillis; - if (result.counts) stats['counts'] = result.counts; - if (result.timing) stats['timing'] = result.timing; - - // invoked with inline? - if (result.results) { - // If we wish for no verbosity - if (options['verbose'] == null || !options['verbose']) { - return handleCallback(callback, null, result.results); - } - - return handleCallback(callback, null, { results: result.results, stats: stats }); - } - - // The returned collection - let collection = null; - - // If we have an object it's a different db - if (result.result != null && typeof result.result === 'object') { - const doc = result.result; - // Return a collection from another db - let Db = loadDb(); - collection = new Db(doc.db, coll.s.db.s.topology, coll.s.db.s.options).collection( - doc.collection - ); - } else { - // Create a collection object that wraps the result collection - collection = coll.s.db.collection(result.result); - } - - // If we wish for no verbosity - if (options['verbose'] == null || !options['verbose']) { - return handleCallback(callback, err, collection); - } - - // Return stats as third set of values - handleCallback(callback, err, { collection: collection, stats: stats }); - }); - } -} - -/** - * Functions that are passed as scope args must - * be converted to Code instances. - * @ignore - */ -function processScope(scope) { - if (!isObject(scope) || scope._bsontype === 'ObjectID') { - return scope; - } - - const keys = Object.keys(scope); - let key; - const new_scope = {}; - - for (let i = keys.length - 1; i >= 0; i--) { - key = keys[i]; - if ('function' === typeof scope[key]) { - new_scope[key] = new Code(String(scope[key])); - } else { - new_scope[key] = processScope(scope[key]); - } - } - - return new_scope; -} - -module.exports = MapReduceOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/next.js b/scripts/node_modules/mongodb/lib/operations/next.js deleted file mode 100644 index 72bc4eb9..00000000 --- a/scripts/node_modules/mongodb/lib/operations/next.js +++ /dev/null @@ -1,32 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const defineAspects = require('./operation').defineAspects; -const OperationBase = require('./operation').OperationBase; -const nextObject = require('./common_functions').nextObject; - -class NextOperation extends OperationBase { - constructor(cursor) { - super(); - - this.cursor = cursor; - } - - execute(callback) { - const cursor = this.cursor; - - // Return the currentDoc if someone called hasNext first - if (cursor.s.currentDoc) { - const doc = cursor.s.currentDoc; - cursor.s.currentDoc = null; - return callback(null, doc); - } - - // Return the next object - nextObject(cursor, callback); - } -} - -defineAspects(NextOperation, Aspect.SKIP_SESSION); - -module.exports = NextOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/operation.js b/scripts/node_modules/mongodb/lib/operations/operation.js deleted file mode 100644 index 471627ad..00000000 --- a/scripts/node_modules/mongodb/lib/operations/operation.js +++ /dev/null @@ -1,67 +0,0 @@ -'use strict'; - -const Aspect = { - READ_OPERATION: Symbol('READ_OPERATION'), - SKIP_SESSION: Symbol('SKIP_SESSION'), - WRITE_OPERATION: Symbol('WRITE_OPERATION'), - RETRYABLE: Symbol('RETRYABLE'), - EXECUTE_WITH_SELECTION: Symbol('EXECUTE_WITH_SELECTION') -}; - -/** - * This class acts as a parent class for any operation and is responsible for setting this.options, - * as well as setting and getting a session. - * Additionally, this class implements `hasAspect`, which determines whether an operation has - * a specific aspect, including `SKIP_SESSION` and other aspects to encode retryability - * and other functionality. - */ -class OperationBase { - constructor(options) { - this.options = Object.assign({}, options); - } - - hasAspect(aspect) { - if (this.constructor.aspects == null) { - return false; - } - return this.constructor.aspects.has(aspect); - } - - set session(session) { - Object.assign(this.options, { session }); - } - - get session() { - return this.options.session; - } - - clearSession() { - delete this.options.session; - } - - get canRetryRead() { - return true; - } - - execute() { - throw new TypeError('`execute` must be implemented for OperationBase subclasses'); - } -} - -function defineAspects(operation, aspects) { - if (!Array.isArray(aspects) && !(aspects instanceof Set)) { - aspects = [aspects]; - } - aspects = new Set(aspects); - Object.defineProperty(operation, 'aspects', { - value: aspects, - writable: false - }); - return aspects; -} - -module.exports = { - Aspect, - defineAspects, - OperationBase -}; diff --git a/scripts/node_modules/mongodb/lib/operations/options_operation.js b/scripts/node_modules/mongodb/lib/operations/options_operation.js deleted file mode 100644 index 9a739a51..00000000 --- a/scripts/node_modules/mongodb/lib/operations/options_operation.js +++ /dev/null @@ -1,32 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const handleCallback = require('../utils').handleCallback; -const MongoError = require('../core').MongoError; - -class OptionsOperation extends OperationBase { - constructor(collection, options) { - super(options); - - this.collection = collection; - } - - execute(callback) { - const coll = this.collection; - const opts = this.options; - - coll.s.db.listCollections({ name: coll.collectionName }, opts).toArray((err, collections) => { - if (err) return handleCallback(callback, err); - if (collections.length === 0) { - return handleCallback( - callback, - MongoError.create({ message: `collection ${coll.namespace} not found`, driver: true }) - ); - } - - handleCallback(callback, err, collections[0].options || null); - }); - } -} - -module.exports = OptionsOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/profiling_level.js b/scripts/node_modules/mongodb/lib/operations/profiling_level.js deleted file mode 100644 index 3f7639b4..00000000 --- a/scripts/node_modules/mongodb/lib/operations/profiling_level.js +++ /dev/null @@ -1,31 +0,0 @@ -'use strict'; - -const CommandOperation = require('./command'); - -class ProfilingLevelOperation extends CommandOperation { - constructor(db, command, options) { - super(db, options); - } - - _buildCommand() { - const command = { profile: -1 }; - - return command; - } - - execute(callback) { - super.execute((err, doc) => { - if (err == null && doc.ok === 1) { - const was = doc.was; - if (was === 0) return callback(null, 'off'); - if (was === 1) return callback(null, 'slow_only'); - if (was === 2) return callback(null, 'all'); - return callback(new Error('Error: illegal profiling level value ' + was), null); - } else { - err != null ? callback(err, null) : callback(new Error('Error with profile command'), null); - } - }); - } -} - -module.exports = ProfilingLevelOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/re_index.js b/scripts/node_modules/mongodb/lib/operations/re_index.js deleted file mode 100644 index 89437fe3..00000000 --- a/scripts/node_modules/mongodb/lib/operations/re_index.js +++ /dev/null @@ -1,28 +0,0 @@ -'use strict'; - -const CommandOperation = require('./command'); -const handleCallback = require('../utils').handleCallback; - -class ReIndexOperation extends CommandOperation { - constructor(collection, options) { - super(collection.s.db, options, collection); - } - - _buildCommand() { - const collection = this.collection; - - const cmd = { reIndex: collection.collectionName }; - - return cmd; - } - - execute(callback) { - super.execute((err, result) => { - if (callback == null) return; - if (err) return handleCallback(callback, err, null); - handleCallback(callback, null, result.ok ? true : false); - }); - } -} - -module.exports = ReIndexOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/remove_user.js b/scripts/node_modules/mongodb/lib/operations/remove_user.js deleted file mode 100644 index 9a59744d..00000000 --- a/scripts/node_modules/mongodb/lib/operations/remove_user.js +++ /dev/null @@ -1,52 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const CommandOperation = require('./command'); -const defineAspects = require('./operation').defineAspects; -const handleCallback = require('../utils').handleCallback; -const WriteConcern = require('../write_concern'); - -class RemoveUserOperation extends CommandOperation { - constructor(db, username, options) { - const commandOptions = {}; - - const writeConcern = WriteConcern.fromOptions(options); - if (writeConcern != null) { - commandOptions.writeConcern = writeConcern; - } - - if (options.dbName) { - commandOptions.dbName = options.dbName; - } - - // Add maxTimeMS to options if set - if (typeof options.maxTimeMS === 'number') { - commandOptions.maxTimeMS = options.maxTimeMS; - } - - super(db, commandOptions); - - this.username = username; - } - - _buildCommand() { - const username = this.username; - - // Build the command to execute - const command = { dropUser: username }; - - return command; - } - - execute(callback) { - // Attempt to execute command - super.execute((err, result) => { - if (err) return handleCallback(callback, err, null); - handleCallback(callback, err, result.ok ? true : false); - }); - } -} - -defineAspects(RemoveUserOperation, [Aspect.WRITE_OPERATION, Aspect.SKIP_SESSIONS]); - -module.exports = RemoveUserOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/rename.js b/scripts/node_modules/mongodb/lib/operations/rename.js deleted file mode 100644 index 8098fe6b..00000000 --- a/scripts/node_modules/mongodb/lib/operations/rename.js +++ /dev/null @@ -1,61 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const applyWriteConcern = require('../utils').applyWriteConcern; -const checkCollectionName = require('../utils').checkCollectionName; -const executeDbAdminCommand = require('./db_ops').executeDbAdminCommand; -const handleCallback = require('../utils').handleCallback; -const loadCollection = require('../dynamic_loaders').loadCollection; -const toError = require('../utils').toError; - -class RenameOperation extends OperationBase { - constructor(collection, newName, options) { - super(options); - - this.collection = collection; - this.newName = newName; - } - - execute(callback) { - const coll = this.collection; - const newName = this.newName; - const options = this.options; - - let Collection = loadCollection(); - // Check the collection name - checkCollectionName(newName); - // Build the command - const renameCollection = coll.namespace; - const toCollection = coll.s.namespace.withCollection(newName).toString(); - const dropTarget = typeof options.dropTarget === 'boolean' ? options.dropTarget : false; - const cmd = { renameCollection: renameCollection, to: toCollection, dropTarget: dropTarget }; - - // Decorate command with writeConcern if supported - applyWriteConcern(cmd, { db: coll.s.db, collection: coll }, options); - - // Execute against admin - executeDbAdminCommand(coll.s.db.admin().s.db, cmd, options, (err, doc) => { - if (err) return handleCallback(callback, err, null); - // We have an error - if (doc.errmsg) return handleCallback(callback, toError(doc), null); - try { - return handleCallback( - callback, - null, - new Collection( - coll.s.db, - coll.s.topology, - coll.s.namespace.db, - newName, - coll.s.pkFactory, - coll.s.options - ) - ); - } catch (err) { - return handleCallback(callback, toError(err), null); - } - }); - } -} - -module.exports = RenameOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/replace_one.js b/scripts/node_modules/mongodb/lib/operations/replace_one.js deleted file mode 100644 index a5aa7608..00000000 --- a/scripts/node_modules/mongodb/lib/operations/replace_one.js +++ /dev/null @@ -1,47 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const updateDocuments = require('./common_functions').updateDocuments; - -class ReplaceOneOperation extends OperationBase { - constructor(collection, filter, doc, options) { - super(options); - - this.collection = collection; - this.filter = filter; - this.doc = doc; - } - - execute(callback) { - const coll = this.collection; - const filter = this.filter; - const doc = this.doc; - const options = this.options; - - // Set single document update - options.multi = false; - - // Execute update - updateDocuments(coll, filter, doc, options, (err, r) => replaceCallback(err, r, doc, callback)); - } -} - -function replaceCallback(err, r, doc, callback) { - if (callback == null) return; - if (err && callback) return callback(err); - if (r == null) return callback(null, { result: { ok: 1 } }); - - r.modifiedCount = r.result.nModified != null ? r.result.nModified : r.result.n; - r.upsertedId = - Array.isArray(r.result.upserted) && r.result.upserted.length > 0 - ? r.result.upserted[0] // FIXME(major): should be `r.result.upserted[0]._id` - : null; - r.upsertedCount = - Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0; - r.matchedCount = - Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? 0 : r.result.n; - r.ops = [doc]; // TODO: Should we still have this? - if (callback) callback(null, r); -} - -module.exports = ReplaceOneOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/set_profiling_level.js b/scripts/node_modules/mongodb/lib/operations/set_profiling_level.js deleted file mode 100644 index b31cc130..00000000 --- a/scripts/node_modules/mongodb/lib/operations/set_profiling_level.js +++ /dev/null @@ -1,48 +0,0 @@ -'use strict'; - -const CommandOperation = require('./command'); -const levelValues = new Set(['off', 'slow_only', 'all']); - -class SetProfilingLevelOperation extends CommandOperation { - constructor(db, level, options) { - let profile = 0; - - if (level === 'off') { - profile = 0; - } else if (level === 'slow_only') { - profile = 1; - } else if (level === 'all') { - profile = 2; - } - - super(db, options); - this.level = level; - this.profile = profile; - } - - _buildCommand() { - const profile = this.profile; - - // Set up the profile number - const command = { profile }; - - return command; - } - - execute(callback) { - const level = this.level; - - if (!levelValues.has(level)) { - return callback(new Error('Error: illegal profiling level value ' + level)); - } - - super.execute((err, doc) => { - if (err == null && doc.ok === 1) return callback(null, level); - return err != null - ? callback(err, null) - : callback(new Error('Error with profile command'), null); - }); - } -} - -module.exports = SetProfilingLevelOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/stats.js b/scripts/node_modules/mongodb/lib/operations/stats.js deleted file mode 100644 index ff79126e..00000000 --- a/scripts/node_modules/mongodb/lib/operations/stats.js +++ /dev/null @@ -1,45 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const CommandOperation = require('./command'); -const defineAspects = require('./operation').defineAspects; - -/** - * Get all the collection statistics. - * - * @class - * @property {Collection} a Collection instance. - * @property {object} [options] Optional settings. See Collection.prototype.stats for a list of options. - */ -class StatsOperation extends CommandOperation { - /** - * Construct a Stats operation. - * - * @param {Collection} a Collection instance. - * @param {object} [options] Optional settings. See Collection.prototype.stats for a list of options. - */ - constructor(collection, options) { - super(collection.s.db, options, collection); - } - - _buildCommand() { - const collection = this.collection; - const options = this.options; - - // Build command object - const command = { - collStats: collection.collectionName - }; - - // Check if we have the scale value - if (options['scale'] != null) { - command['scale'] = options['scale']; - } - - return command; - } -} - -defineAspects(StatsOperation, Aspect.READ_OPERATION); - -module.exports = StatsOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/to_array.js b/scripts/node_modules/mongodb/lib/operations/to_array.js deleted file mode 100644 index db6d1a07..00000000 --- a/scripts/node_modules/mongodb/lib/operations/to_array.js +++ /dev/null @@ -1,66 +0,0 @@ -'use strict'; - -const Aspect = require('./operation').Aspect; -const defineAspects = require('./operation').defineAspects; -const handleCallback = require('../utils').handleCallback; -const CursorState = require('../core/cursor').CursorState; -const OperationBase = require('./operation').OperationBase; -const push = Array.prototype.push; - -class ToArrayOperation extends OperationBase { - constructor(cursor) { - super(); - - this.cursor = cursor; - } - - execute(callback) { - const cursor = this.cursor; - const items = []; - - // Reset cursor - cursor.rewind(); - cursor.s.state = CursorState.INIT; - - // Fetch all the documents - const fetchDocs = () => { - cursor._next((err, doc) => { - if (err) { - return cursor._endSession - ? cursor._endSession(() => handleCallback(callback, err)) - : handleCallback(callback, err); - } - - if (doc == null) { - return cursor.close({ skipKillCursors: true }, () => - handleCallback(callback, null, items) - ); - } - - // Add doc to items - items.push(doc); - - // Get all buffered objects - if (cursor.bufferedCount() > 0) { - let docs = cursor.readBufferedDocuments(cursor.bufferedCount()); - - // Transform the doc if transform method added - if (cursor.s.transforms && typeof cursor.s.transforms.doc === 'function') { - docs = docs.map(cursor.s.transforms.doc); - } - - push.apply(items, docs); - } - - // Attempt a fetch - fetchDocs(); - }); - }; - - fetchDocs(); - } -} - -defineAspects(ToArrayOperation, Aspect.SKIP_SESSION); - -module.exports = ToArrayOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/update_many.js b/scripts/node_modules/mongodb/lib/operations/update_many.js deleted file mode 100644 index 9a18d253..00000000 --- a/scripts/node_modules/mongodb/lib/operations/update_many.js +++ /dev/null @@ -1,29 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const updateCallback = require('./common_functions').updateCallback; -const updateDocuments = require('./common_functions').updateDocuments; - -class UpdateManyOperation extends OperationBase { - constructor(collection, filter, update, options) { - super(options); - - this.collection = collection; - this.filter = filter; - this.update = update; - } - - execute(callback) { - const coll = this.collection; - const filter = this.filter; - const update = this.update; - const options = this.options; - - // Set single document update - options.multi = true; - // Execute update - updateDocuments(coll, filter, update, options, (err, r) => updateCallback(err, r, callback)); - } -} - -module.exports = UpdateManyOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/update_one.js b/scripts/node_modules/mongodb/lib/operations/update_one.js deleted file mode 100644 index b1c1bc16..00000000 --- a/scripts/node_modules/mongodb/lib/operations/update_one.js +++ /dev/null @@ -1,44 +0,0 @@ -'use strict'; - -const OperationBase = require('./operation').OperationBase; -const updateDocuments = require('./common_functions').updateDocuments; - -class UpdateOneOperation extends OperationBase { - constructor(collection, filter, update, options) { - super(options); - - this.collection = collection; - this.filter = filter; - this.update = update; - } - - execute(callback) { - const coll = this.collection; - const filter = this.filter; - const update = this.update; - const options = this.options; - - // Set single document update - options.multi = false; - // Execute update - updateDocuments(coll, filter, update, options, (err, r) => updateCallback(err, r, callback)); - } -} - -function updateCallback(err, r, callback) { - if (callback == null) return; - if (err) return callback(err); - if (r == null) return callback(null, { result: { ok: 1 } }); - r.modifiedCount = r.result.nModified != null ? r.result.nModified : r.result.n; - r.upsertedId = - Array.isArray(r.result.upserted) && r.result.upserted.length > 0 - ? r.result.upserted[0] // FIXME(major): should be `r.result.upserted[0]._id` - : null; - r.upsertedCount = - Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0; - r.matchedCount = - Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? 0 : r.result.n; - callback(null, r); -} - -module.exports = UpdateOneOperation; diff --git a/scripts/node_modules/mongodb/lib/operations/validate_collection.js b/scripts/node_modules/mongodb/lib/operations/validate_collection.js deleted file mode 100644 index 133c6c4b..00000000 --- a/scripts/node_modules/mongodb/lib/operations/validate_collection.js +++ /dev/null @@ -1,40 +0,0 @@ -'use strict'; - -const CommandOperation = require('./command'); - -class ValidateCollectionOperation extends CommandOperation { - constructor(admin, collectionName, options) { - // Decorate command with extra options - let command = { validate: collectionName }; - const keys = Object.keys(options); - for (let i = 0; i < keys.length; i++) { - if (options.hasOwnProperty(keys[i]) && keys[i] !== 'session') { - command[keys[i]] = options[keys[i]]; - } - } - - super(admin.s.db, options, null, command); - - this.collectionName; - } - - execute(callback) { - const collectionName = this.collectionName; - - super.execute((err, doc) => { - if (err != null) return callback(err, null); - - if (doc.ok === 0) return callback(new Error('Error with validate command'), null); - if (doc.result != null && doc.result.constructor !== String) - return callback(new Error('Error with validation data'), null); - if (doc.result != null && doc.result.match(/exception|corrupt/) != null) - return callback(new Error('Error: invalid collection ' + collectionName), null); - if (doc.valid != null && !doc.valid) - return callback(new Error('Error: invalid collection ' + collectionName), null); - - return callback(null, doc); - }); - } -} - -module.exports = ValidateCollectionOperation; diff --git a/scripts/node_modules/mongodb/lib/read_concern.js b/scripts/node_modules/mongodb/lib/read_concern.js deleted file mode 100644 index b48b8e0e..00000000 --- a/scripts/node_modules/mongodb/lib/read_concern.js +++ /dev/null @@ -1,61 +0,0 @@ -'use strict'; - -/** - * The **ReadConcern** class is a class that represents a MongoDB ReadConcern. - * @class - * @property {string} level The read concern level - * @see https://docs.mongodb.com/manual/reference/read-concern/index.html - */ -class ReadConcern { - /** - * Constructs a ReadConcern from the read concern properties. - * @param {string} [level] The read concern level ({'local'|'available'|'majority'|'linearizable'|'snapshot'}) - */ - constructor(level) { - if (level != null) { - this.level = level; - } - } - - /** - * Construct a ReadConcern given an options object. - * - * @param {object} options The options object from which to extract the write concern. - * @return {ReadConcern} - */ - static fromOptions(options) { - if (options == null) { - return; - } - - if (options.readConcern) { - if (options.readConcern instanceof ReadConcern) { - return options.readConcern; - } - - return new ReadConcern(options.readConcern.level); - } - - if (options.level) { - return new ReadConcern(options.level); - } - } - - static get MAJORITY() { - return 'majority'; - } - - static get AVAILABLE() { - return 'available'; - } - - static get LINEARIZABLE() { - return 'linearizable'; - } - - static get SNAPSHOT() { - return 'snapshot'; - } -} - -module.exports = ReadConcern; diff --git a/scripts/node_modules/mongodb/lib/topologies/mongos.js b/scripts/node_modules/mongodb/lib/topologies/mongos.js deleted file mode 100644 index ec14f485..00000000 --- a/scripts/node_modules/mongodb/lib/topologies/mongos.js +++ /dev/null @@ -1,452 +0,0 @@ -'use strict'; - -const TopologyBase = require('./topology_base').TopologyBase; -const MongoError = require('../core').MongoError; -const CMongos = require('../core').Mongos; -const Cursor = require('../cursor'); -const Server = require('./server'); -const Store = require('./topology_base').Store; -const MAX_JS_INT = require('../utils').MAX_JS_INT; -const translateOptions = require('../utils').translateOptions; -const filterOptions = require('../utils').filterOptions; -const mergeOptions = require('../utils').mergeOptions; - -/** - * @fileOverview The **Mongos** class is a class that represents a Mongos Proxy topology and is - * used to construct connections. - * - * **Mongos Should not be used, use MongoClient.connect** - */ - -// Allowed parameters -var legalOptionNames = [ - 'ha', - 'haInterval', - 'acceptableLatencyMS', - 'poolSize', - 'ssl', - 'checkServerIdentity', - 'sslValidate', - 'sslCA', - 'sslCRL', - 'sslCert', - 'ciphers', - 'ecdhCurve', - 'sslKey', - 'sslPass', - 'socketOptions', - 'bufferMaxEntries', - 'store', - 'auto_reconnect', - 'autoReconnect', - 'emitError', - 'keepAlive', - 'keepAliveInitialDelay', - 'noDelay', - 'connectTimeoutMS', - 'socketTimeoutMS', - 'loggerLevel', - 'logger', - 'reconnectTries', - 'appname', - 'domainsEnabled', - 'servername', - 'promoteLongs', - 'promoteValues', - 'promoteBuffers', - 'promiseLibrary', - 'monitorCommands' -]; - -/** - * Creates a new Mongos instance - * @class - * @deprecated - * @param {Server[]} servers A seedlist of servers participating in the replicaset. - * @param {object} [options] Optional settings. - * @param {booelan} [options.ha=true] Turn on high availability monitoring. - * @param {number} [options.haInterval=5000] Time between each replicaset status check. - * @param {number} [options.poolSize=5] Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons. - * @param {number} [options.acceptableLatencyMS=15] Cutoff latency point in MS for MongoS proxy selection - * @param {boolean} [options.ssl=false] Use ssl connection (needs to have a mongod server with ssl support) - * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. - * @param {boolean} [options.sslValidate=false] Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {array} [options.sslCA] Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {array} [options.sslCRL] Array of revocation certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {string} [options.ciphers] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. - * @param {string} [options.ecdhCurve] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. - * @param {(Buffer|string)} [options.sslCert] String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {(Buffer|string)} [options.sslKey] String or buffer containing the certificate private key we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {(Buffer|string)} [options.sslPass] String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {string} [options.servername] String containing the server name requested via TLS SNI. - * @param {object} [options.socketOptions] Socket options - * @param {boolean} [options.socketOptions.noDelay=true] TCP Socket NoDelay option. - * @param {boolean} [options.socketOptions.keepAlive=true] TCP Connection keep alive enabled - * @param {number} [options.socketOptions.keepAliveInitialDelay=30000] The number of milliseconds to wait before initiating keepAlive on the TCP socket - * @param {number} [options.socketOptions.connectTimeoutMS=0] TCP Connection timeout setting - * @param {number} [options.socketOptions.socketTimeoutMS=0] TCP Socket timeout setting - * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. - * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology - * @fires Mongos#connect - * @fires Mongos#ha - * @fires Mongos#joined - * @fires Mongos#left - * @fires Mongos#fullsetup - * @fires Mongos#open - * @fires Mongos#close - * @fires Mongos#error - * @fires Mongos#timeout - * @fires Mongos#parseError - * @fires Mongos#commandStarted - * @fires Mongos#commandSucceeded - * @fires Mongos#commandFailed - * @property {string} parserType the parser type used (c++ or js). - * @return {Mongos} a Mongos instance. - */ -class Mongos extends TopologyBase { - constructor(servers, options) { - super(); - - options = options || {}; - var self = this; - - // Filter the options - options = filterOptions(options, legalOptionNames); - - // Ensure all the instances are Server - for (var i = 0; i < servers.length; i++) { - if (!(servers[i] instanceof Server)) { - throw MongoError.create({ - message: 'all seed list instances must be of the Server type', - driver: true - }); - } - } - - // Stored options - var storeOptions = { - force: false, - bufferMaxEntries: - typeof options.bufferMaxEntries === 'number' ? options.bufferMaxEntries : MAX_JS_INT - }; - - // Shared global store - var store = options.store || new Store(self, storeOptions); - - // Build seed list - var seedlist = servers.map(function(x) { - return { host: x.host, port: x.port }; - }); - - // Get the reconnect option - var reconnect = typeof options.auto_reconnect === 'boolean' ? options.auto_reconnect : true; - reconnect = typeof options.autoReconnect === 'boolean' ? options.autoReconnect : reconnect; - - // Clone options - var clonedOptions = mergeOptions( - {}, - { - disconnectHandler: store, - cursorFactory: Cursor, - reconnect: reconnect, - emitError: typeof options.emitError === 'boolean' ? options.emitError : true, - size: typeof options.poolSize === 'number' ? options.poolSize : 5, - monitorCommands: - typeof options.monitorCommands === 'boolean' ? options.monitorCommands : false - } - ); - - // Translate any SSL options and other connectivity options - clonedOptions = translateOptions(clonedOptions, options); - - // Socket options - var socketOptions = - options.socketOptions && Object.keys(options.socketOptions).length > 0 - ? options.socketOptions - : options; - - // Translate all the options to the core types - clonedOptions = translateOptions(clonedOptions, socketOptions); - - // Build default client information - clonedOptions.clientInfo = this.clientInfo; - // Do we have an application specific string - if (options.appname) { - clonedOptions.clientInfo.application = { name: options.appname }; - } - - // Internal state - this.s = { - // Create the Mongos - coreTopology: new CMongos(seedlist, clonedOptions), - // Server capabilities - sCapabilities: null, - // Debug turned on - debug: clonedOptions.debug, - // Store option defaults - storeOptions: storeOptions, - // Cloned options - clonedOptions: clonedOptions, - // Actual store of callbacks - store: store, - // Options - options: options, - // Server Session Pool - sessionPool: null, - // Active client sessions - sessions: new Set(), - // Promise library - promiseLibrary: options.promiseLibrary || Promise - }; - } - - // Connect - connect(_options, callback) { - var self = this; - if ('function' === typeof _options) (callback = _options), (_options = {}); - if (_options == null) _options = {}; - if (!('function' === typeof callback)) callback = null; - _options = Object.assign({}, this.s.clonedOptions, _options); - self.s.options = _options; - - // Update bufferMaxEntries - self.s.storeOptions.bufferMaxEntries = - typeof _options.bufferMaxEntries === 'number' ? _options.bufferMaxEntries : -1; - - // Error handler - var connectErrorHandler = function() { - return function(err) { - // Remove all event handlers - var events = ['timeout', 'error', 'close']; - events.forEach(function(e) { - self.removeListener(e, connectErrorHandler); - }); - - self.s.coreTopology.removeListener('connect', connectErrorHandler); - // Force close the topology - self.close(true); - - // Try to callback - try { - callback(err); - } catch (err) { - process.nextTick(function() { - throw err; - }); - } - }; - }; - - // Actual handler - var errorHandler = function(event) { - return function(err) { - if (event !== 'error') { - self.emit(event, err); - } - }; - }; - - // Error handler - var reconnectHandler = function() { - self.emit('reconnect'); - self.s.store.execute(); - }; - - // relay the event - var relay = function(event) { - return function(t, server) { - self.emit(event, t, server); - }; - }; - - // Connect handler - var connectHandler = function() { - // Clear out all the current handlers left over - var events = ['timeout', 'error', 'close', 'fullsetup']; - events.forEach(function(e) { - self.s.coreTopology.removeAllListeners(e); - }); - - // Set up listeners - self.s.coreTopology.on('timeout', errorHandler('timeout')); - self.s.coreTopology.on('error', errorHandler('error')); - self.s.coreTopology.on('close', errorHandler('close')); - - // Set up serverConfig listeners - self.s.coreTopology.on('fullsetup', function() { - self.emit('fullsetup', self); - }); - - // Emit open event - self.emit('open', null, self); - - // Return correctly - try { - callback(null, self); - } catch (err) { - process.nextTick(function() { - throw err; - }); - } - }; - - // Clear out all the current handlers left over - var events = [ - 'timeout', - 'error', - 'close', - 'serverOpening', - 'serverDescriptionChanged', - 'serverHeartbeatStarted', - 'serverHeartbeatSucceeded', - 'serverHeartbeatFailed', - 'serverClosed', - 'topologyOpening', - 'topologyClosed', - 'topologyDescriptionChanged', - 'commandStarted', - 'commandSucceeded', - 'commandFailed' - ]; - events.forEach(function(e) { - self.s.coreTopology.removeAllListeners(e); - }); - - // Set up SDAM listeners - self.s.coreTopology.on('serverDescriptionChanged', relay('serverDescriptionChanged')); - self.s.coreTopology.on('serverHeartbeatStarted', relay('serverHeartbeatStarted')); - self.s.coreTopology.on('serverHeartbeatSucceeded', relay('serverHeartbeatSucceeded')); - self.s.coreTopology.on('serverHeartbeatFailed', relay('serverHeartbeatFailed')); - self.s.coreTopology.on('serverOpening', relay('serverOpening')); - self.s.coreTopology.on('serverClosed', relay('serverClosed')); - self.s.coreTopology.on('topologyOpening', relay('topologyOpening')); - self.s.coreTopology.on('topologyClosed', relay('topologyClosed')); - self.s.coreTopology.on('topologyDescriptionChanged', relay('topologyDescriptionChanged')); - self.s.coreTopology.on('commandStarted', relay('commandStarted')); - self.s.coreTopology.on('commandSucceeded', relay('commandSucceeded')); - self.s.coreTopology.on('commandFailed', relay('commandFailed')); - - // Set up listeners - self.s.coreTopology.once('timeout', connectErrorHandler('timeout')); - self.s.coreTopology.once('error', connectErrorHandler('error')); - self.s.coreTopology.once('close', connectErrorHandler('close')); - self.s.coreTopology.once('connect', connectHandler); - // Join and leave events - self.s.coreTopology.on('joined', relay('joined')); - self.s.coreTopology.on('left', relay('left')); - - // Reconnect server - self.s.coreTopology.on('reconnect', reconnectHandler); - - // Start connection - self.s.coreTopology.connect(_options); - } -} - -Object.defineProperty(Mongos.prototype, 'haInterval', { - enumerable: true, - get: function() { - return this.s.coreTopology.s.haInterval; - } -}); - -/** - * A mongos connect event, used to verify that the connection is up and running - * - * @event Mongos#connect - * @type {Mongos} - */ - -/** - * The mongos high availability event - * - * @event Mongos#ha - * @type {function} - * @param {string} type The stage in the high availability event (start|end) - * @param {boolean} data.norepeat This is a repeating high availability process or a single execution only - * @param {number} data.id The id for this high availability request - * @param {object} data.state An object containing the information about the current replicaset - */ - -/** - * A server member left the mongos set - * - * @event Mongos#left - * @type {function} - * @param {string} type The type of member that left (primary|secondary|arbiter) - * @param {Server} server The server object that left - */ - -/** - * A server member joined the mongos set - * - * @event Mongos#joined - * @type {function} - * @param {string} type The type of member that joined (primary|secondary|arbiter) - * @param {Server} server The server object that joined - */ - -/** - * Mongos fullsetup event, emitted when all proxies in the topology have been connected to. - * - * @event Mongos#fullsetup - * @type {Mongos} - */ - -/** - * Mongos open event, emitted when mongos can start processing commands. - * - * @event Mongos#open - * @type {Mongos} - */ - -/** - * Mongos close event - * - * @event Mongos#close - * @type {object} - */ - -/** - * Mongos error event, emitted if there is an error listener. - * - * @event Mongos#error - * @type {MongoError} - */ - -/** - * Mongos timeout event - * - * @event Mongos#timeout - * @type {object} - */ - -/** - * Mongos parseError event - * - * @event Mongos#parseError - * @type {object} - */ - -/** - * An event emitted indicating a command was started, if command monitoring is enabled - * - * @event Mongos#commandStarted - * @type {object} - */ - -/** - * An event emitted indicating a command succeeded, if command monitoring is enabled - * - * @event Mongos#commandSucceeded - * @type {object} - */ - -/** - * An event emitted indicating a command failed, if command monitoring is enabled - * - * @event Mongos#commandFailed - * @type {object} - */ - -module.exports = Mongos; diff --git a/scripts/node_modules/mongodb/lib/topologies/native_topology.js b/scripts/node_modules/mongodb/lib/topologies/native_topology.js deleted file mode 100644 index 51574878..00000000 --- a/scripts/node_modules/mongodb/lib/topologies/native_topology.js +++ /dev/null @@ -1,72 +0,0 @@ -'use strict'; - -const Topology = require('../core').Topology; -const ServerCapabilities = require('./topology_base').ServerCapabilities; -const Cursor = require('../cursor'); -const translateOptions = require('../utils').translateOptions; - -class NativeTopology extends Topology { - constructor(servers, options) { - options = options || {}; - - let clonedOptions = Object.assign( - {}, - { - cursorFactory: Cursor, - reconnect: false, - emitError: typeof options.emitError === 'boolean' ? options.emitError : true, - size: typeof options.poolSize === 'number' ? options.poolSize : 5, - monitorCommands: - typeof options.monitorCommands === 'boolean' ? options.monitorCommands : false - } - ); - - // Translate any SSL options and other connectivity options - clonedOptions = translateOptions(clonedOptions, options); - - // Socket options - var socketOptions = - options.socketOptions && Object.keys(options.socketOptions).length > 0 - ? options.socketOptions - : options; - - // Translate all the options to the core types - clonedOptions = translateOptions(clonedOptions, socketOptions); - - super(servers, clonedOptions); - - // Do we have an application specific string - if (options.appname) { - this.s.clientInfo.application = { name: options.appname }; - } - } - - capabilities() { - if (this.s.sCapabilities) return this.s.sCapabilities; - if (this.lastIsMaster() == null) return null; - this.s.sCapabilities = new ServerCapabilities(this.lastIsMaster()); - return this.s.sCapabilities; - } - - // Command - command(ns, cmd, options, callback) { - super.command(ns.toString(), cmd, options, callback); - } - - // Insert - insert(ns, ops, options, callback) { - super.insert(ns.toString(), ops, options, callback); - } - - // Update - update(ns, ops, options, callback) { - super.update(ns.toString(), ops, options, callback); - } - - // Remove - remove(ns, ops, options, callback) { - super.remove(ns.toString(), ops, options, callback); - } -} - -module.exports = NativeTopology; diff --git a/scripts/node_modules/mongodb/lib/topologies/replset.js b/scripts/node_modules/mongodb/lib/topologies/replset.js deleted file mode 100644 index 44e83d11..00000000 --- a/scripts/node_modules/mongodb/lib/topologies/replset.js +++ /dev/null @@ -1,496 +0,0 @@ -'use strict'; - -const Server = require('./server'); -const Cursor = require('../cursor'); -const MongoError = require('../core').MongoError; -const TopologyBase = require('./topology_base').TopologyBase; -const Store = require('./topology_base').Store; -const CReplSet = require('../core').ReplSet; -const MAX_JS_INT = require('../utils').MAX_JS_INT; -const translateOptions = require('../utils').translateOptions; -const filterOptions = require('../utils').filterOptions; -const mergeOptions = require('../utils').mergeOptions; - -/** - * @fileOverview The **ReplSet** class is a class that represents a Replicaset topology and is - * used to construct connections. - * - * **ReplSet Should not be used, use MongoClient.connect** - */ - -// Allowed parameters -var legalOptionNames = [ - 'ha', - 'haInterval', - 'replicaSet', - 'rs_name', - 'secondaryAcceptableLatencyMS', - 'connectWithNoPrimary', - 'poolSize', - 'ssl', - 'checkServerIdentity', - 'sslValidate', - 'sslCA', - 'sslCert', - 'ciphers', - 'ecdhCurve', - 'sslCRL', - 'sslKey', - 'sslPass', - 'socketOptions', - 'bufferMaxEntries', - 'store', - 'auto_reconnect', - 'autoReconnect', - 'emitError', - 'keepAlive', - 'keepAliveInitialDelay', - 'noDelay', - 'connectTimeoutMS', - 'socketTimeoutMS', - 'strategy', - 'debug', - 'family', - 'loggerLevel', - 'logger', - 'reconnectTries', - 'appname', - 'domainsEnabled', - 'servername', - 'promoteLongs', - 'promoteValues', - 'promoteBuffers', - 'maxStalenessSeconds', - 'promiseLibrary', - 'minSize', - 'monitorCommands' -]; - -/** - * Creates a new ReplSet instance - * @class - * @deprecated - * @param {Server[]} servers A seedlist of servers participating in the replicaset. - * @param {object} [options] Optional settings. - * @param {boolean} [options.ha=true] Turn on high availability monitoring. - * @param {number} [options.haInterval=10000] Time between each replicaset status check. - * @param {string} [options.replicaSet] The name of the replicaset to connect to. - * @param {number} [options.secondaryAcceptableLatencyMS=15] Sets the range of servers to pick when using NEAREST (lowest ping ms + the latency fence, ex: range of 1 to (1 + 15) ms) - * @param {boolean} [options.connectWithNoPrimary=false] Sets if the driver should connect even if no primary is available - * @param {number} [options.poolSize=5] Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons. - * @param {boolean} [options.ssl=false] Use ssl connection (needs to have a mongod server with ssl support) - * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. - * @param {boolean} [options.sslValidate=false] Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {array} [options.sslCA] Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {array} [options.sslCRL] Array of revocation certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {(Buffer|string)} [options.sslCert] String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher. - * @param {string} [options.ciphers] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. - * @param {string} [options.ecdhCurve] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. - * @param {(Buffer|string)} [options.sslKey] String or buffer containing the certificate private key we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {(Buffer|string)} [options.sslPass] String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {string} [options.servername] String containing the server name requested via TLS SNI. - * @param {object} [options.socketOptions] Socket options - * @param {boolean} [options.socketOptions.noDelay=true] TCP Socket NoDelay option. - * @param {boolean} [options.socketOptions.keepAlive=true] TCP Connection keep alive enabled - * @param {number} [options.socketOptions.keepAliveInitialDelay=30000] The number of milliseconds to wait before initiating keepAlive on the TCP socket - * @param {number} [options.socketOptions.connectTimeoutMS=10000] TCP Connection timeout setting - * @param {number} [options.socketOptions.socketTimeoutMS=0] TCP Socket timeout setting - * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. - * @param {number} [options.maxStalenessSeconds=undefined] The max staleness to secondary reads (values under 10 seconds cannot be guaranteed); - * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology - * @fires ReplSet#connect - * @fires ReplSet#ha - * @fires ReplSet#joined - * @fires ReplSet#left - * @fires ReplSet#fullsetup - * @fires ReplSet#open - * @fires ReplSet#close - * @fires ReplSet#error - * @fires ReplSet#timeout - * @fires ReplSet#parseError - * @fires ReplSet#commandStarted - * @fires ReplSet#commandSucceeded - * @fires ReplSet#commandFailed - * @property {string} parserType the parser type used (c++ or js). - * @return {ReplSet} a ReplSet instance. - */ -class ReplSet extends TopologyBase { - constructor(servers, options) { - super(); - - options = options || {}; - var self = this; - - // Filter the options - options = filterOptions(options, legalOptionNames); - - // Ensure all the instances are Server - for (var i = 0; i < servers.length; i++) { - if (!(servers[i] instanceof Server)) { - throw MongoError.create({ - message: 'all seed list instances must be of the Server type', - driver: true - }); - } - } - - // Stored options - var storeOptions = { - force: false, - bufferMaxEntries: - typeof options.bufferMaxEntries === 'number' ? options.bufferMaxEntries : MAX_JS_INT - }; - - // Shared global store - var store = options.store || new Store(self, storeOptions); - - // Build seed list - var seedlist = servers.map(function(x) { - return { host: x.host, port: x.port }; - }); - - // Clone options - var clonedOptions = mergeOptions( - {}, - { - disconnectHandler: store, - cursorFactory: Cursor, - reconnect: false, - emitError: typeof options.emitError === 'boolean' ? options.emitError : true, - size: typeof options.poolSize === 'number' ? options.poolSize : 5, - monitorCommands: - typeof options.monitorCommands === 'boolean' ? options.monitorCommands : false - } - ); - - // Translate any SSL options and other connectivity options - clonedOptions = translateOptions(clonedOptions, options); - - // Socket options - var socketOptions = - options.socketOptions && Object.keys(options.socketOptions).length > 0 - ? options.socketOptions - : options; - - // Translate all the options to the core types - clonedOptions = translateOptions(clonedOptions, socketOptions); - - // Build default client information - clonedOptions.clientInfo = this.clientInfo; - // Do we have an application specific string - if (options.appname) { - clonedOptions.clientInfo.application = { name: options.appname }; - } - - // Create the ReplSet - var coreTopology = new CReplSet(seedlist, clonedOptions); - - // Listen to reconnect event - coreTopology.on('reconnect', function() { - self.emit('reconnect'); - store.execute(); - }); - - // Internal state - this.s = { - // Replicaset - coreTopology: coreTopology, - // Server capabilities - sCapabilities: null, - // Debug tag - tag: options.tag, - // Store options - storeOptions: storeOptions, - // Cloned options - clonedOptions: clonedOptions, - // Store - store: store, - // Options - options: options, - // Server Session Pool - sessionPool: null, - // Active client sessions - sessions: new Set(), - // Promise library - promiseLibrary: options.promiseLibrary || Promise - }; - - // Debug - if (clonedOptions.debug) { - // Last ismaster - Object.defineProperty(this, 'replset', { - enumerable: true, - get: function() { - return coreTopology; - } - }); - } - } - - // Connect method - connect(_options, callback) { - var self = this; - if ('function' === typeof _options) (callback = _options), (_options = {}); - if (_options == null) _options = {}; - if (!('function' === typeof callback)) callback = null; - _options = Object.assign({}, this.s.clonedOptions, _options); - self.s.options = _options; - - // Update bufferMaxEntries - self.s.storeOptions.bufferMaxEntries = - typeof _options.bufferMaxEntries === 'number' ? _options.bufferMaxEntries : -1; - - // Actual handler - var errorHandler = function(event) { - return function(err) { - if (event !== 'error') { - self.emit(event, err); - } - }; - }; - - // Clear out all the current handlers left over - var events = [ - 'timeout', - 'error', - 'close', - 'serverOpening', - 'serverDescriptionChanged', - 'serverHeartbeatStarted', - 'serverHeartbeatSucceeded', - 'serverHeartbeatFailed', - 'serverClosed', - 'topologyOpening', - 'topologyClosed', - 'topologyDescriptionChanged', - 'commandStarted', - 'commandSucceeded', - 'commandFailed', - 'joined', - 'left', - 'ping', - 'ha' - ]; - events.forEach(function(e) { - self.s.coreTopology.removeAllListeners(e); - }); - - // relay the event - var relay = function(event) { - return function(t, server) { - self.emit(event, t, server); - }; - }; - - // Replset events relay - var replsetRelay = function(event) { - return function(t, server) { - self.emit(event, t, server.lastIsMaster(), server); - }; - }; - - // Relay ha - var relayHa = function(t, state) { - self.emit('ha', t, state); - - if (t === 'start') { - self.emit('ha_connect', t, state); - } else if (t === 'end') { - self.emit('ha_ismaster', t, state); - } - }; - - // Set up serverConfig listeners - self.s.coreTopology.on('joined', replsetRelay('joined')); - self.s.coreTopology.on('left', relay('left')); - self.s.coreTopology.on('ping', relay('ping')); - self.s.coreTopology.on('ha', relayHa); - - // Set up SDAM listeners - self.s.coreTopology.on('serverDescriptionChanged', relay('serverDescriptionChanged')); - self.s.coreTopology.on('serverHeartbeatStarted', relay('serverHeartbeatStarted')); - self.s.coreTopology.on('serverHeartbeatSucceeded', relay('serverHeartbeatSucceeded')); - self.s.coreTopology.on('serverHeartbeatFailed', relay('serverHeartbeatFailed')); - self.s.coreTopology.on('serverOpening', relay('serverOpening')); - self.s.coreTopology.on('serverClosed', relay('serverClosed')); - self.s.coreTopology.on('topologyOpening', relay('topologyOpening')); - self.s.coreTopology.on('topologyClosed', relay('topologyClosed')); - self.s.coreTopology.on('topologyDescriptionChanged', relay('topologyDescriptionChanged')); - self.s.coreTopology.on('commandStarted', relay('commandStarted')); - self.s.coreTopology.on('commandSucceeded', relay('commandSucceeded')); - self.s.coreTopology.on('commandFailed', relay('commandFailed')); - - self.s.coreTopology.on('fullsetup', function() { - self.emit('fullsetup', self, self); - }); - - self.s.coreTopology.on('all', function() { - self.emit('all', null, self); - }); - - // Connect handler - var connectHandler = function() { - // Set up listeners - self.s.coreTopology.once('timeout', errorHandler('timeout')); - self.s.coreTopology.once('error', errorHandler('error')); - self.s.coreTopology.once('close', errorHandler('close')); - - // Emit open event - self.emit('open', null, self); - - // Return correctly - try { - callback(null, self); - } catch (err) { - process.nextTick(function() { - throw err; - }); - } - }; - - // Error handler - var connectErrorHandler = function() { - return function(err) { - ['timeout', 'error', 'close'].forEach(function(e) { - self.s.coreTopology.removeListener(e, connectErrorHandler); - }); - - self.s.coreTopology.removeListener('connect', connectErrorHandler); - // Destroy the replset - self.s.coreTopology.destroy(); - - // Try to callback - try { - callback(err); - } catch (err) { - if (!self.s.coreTopology.isConnected()) - process.nextTick(function() { - throw err; - }); - } - }; - }; - - // Set up listeners - self.s.coreTopology.once('timeout', connectErrorHandler('timeout')); - self.s.coreTopology.once('error', connectErrorHandler('error')); - self.s.coreTopology.once('close', connectErrorHandler('close')); - self.s.coreTopology.once('connect', connectHandler); - - // Start connection - self.s.coreTopology.connect(_options); - } - - close(forceClosed, callback) { - ['timeout', 'error', 'close', 'joined', 'left'].forEach(e => this.removeAllListeners(e)); - super.close(forceClosed, callback); - } -} - -Object.defineProperty(ReplSet.prototype, 'haInterval', { - enumerable: true, - get: function() { - return this.s.coreTopology.s.haInterval; - } -}); - -/** - * A replset connect event, used to verify that the connection is up and running - * - * @event ReplSet#connect - * @type {ReplSet} - */ - -/** - * The replset high availability event - * - * @event ReplSet#ha - * @type {function} - * @param {string} type The stage in the high availability event (start|end) - * @param {boolean} data.norepeat This is a repeating high availability process or a single execution only - * @param {number} data.id The id for this high availability request - * @param {object} data.state An object containing the information about the current replicaset - */ - -/** - * A server member left the replicaset - * - * @event ReplSet#left - * @type {function} - * @param {string} type The type of member that left (primary|secondary|arbiter) - * @param {Server} server The server object that left - */ - -/** - * A server member joined the replicaset - * - * @event ReplSet#joined - * @type {function} - * @param {string} type The type of member that joined (primary|secondary|arbiter) - * @param {Server} server The server object that joined - */ - -/** - * ReplSet open event, emitted when replicaset can start processing commands. - * - * @event ReplSet#open - * @type {Replset} - */ - -/** - * ReplSet fullsetup event, emitted when all servers in the topology have been connected to. - * - * @event ReplSet#fullsetup - * @type {Replset} - */ - -/** - * ReplSet close event - * - * @event ReplSet#close - * @type {object} - */ - -/** - * ReplSet error event, emitted if there is an error listener. - * - * @event ReplSet#error - * @type {MongoError} - */ - -/** - * ReplSet timeout event - * - * @event ReplSet#timeout - * @type {object} - */ - -/** - * ReplSet parseError event - * - * @event ReplSet#parseError - * @type {object} - */ - -/** - * An event emitted indicating a command was started, if command monitoring is enabled - * - * @event ReplSet#commandStarted - * @type {object} - */ - -/** - * An event emitted indicating a command succeeded, if command monitoring is enabled - * - * @event ReplSet#commandSucceeded - * @type {object} - */ - -/** - * An event emitted indicating a command failed, if command monitoring is enabled - * - * @event ReplSet#commandFailed - * @type {object} - */ - -module.exports = ReplSet; diff --git a/scripts/node_modules/mongodb/lib/topologies/server.js b/scripts/node_modules/mongodb/lib/topologies/server.js deleted file mode 100644 index 9bbe4350..00000000 --- a/scripts/node_modules/mongodb/lib/topologies/server.js +++ /dev/null @@ -1,455 +0,0 @@ -'use strict'; - -const CServer = require('../core').Server; -const Cursor = require('../cursor'); -const TopologyBase = require('./topology_base').TopologyBase; -const Store = require('./topology_base').Store; -const MongoError = require('../core').MongoError; -const MAX_JS_INT = require('../utils').MAX_JS_INT; -const translateOptions = require('../utils').translateOptions; -const filterOptions = require('../utils').filterOptions; -const mergeOptions = require('../utils').mergeOptions; - -/** - * @fileOverview The **Server** class is a class that represents a single server topology and is - * used to construct connections. - * - * **Server Should not be used, use MongoClient.connect** - */ - -// Allowed parameters -var legalOptionNames = [ - 'ha', - 'haInterval', - 'acceptableLatencyMS', - 'poolSize', - 'ssl', - 'checkServerIdentity', - 'sslValidate', - 'sslCA', - 'sslCRL', - 'sslCert', - 'ciphers', - 'ecdhCurve', - 'sslKey', - 'sslPass', - 'socketOptions', - 'bufferMaxEntries', - 'store', - 'auto_reconnect', - 'autoReconnect', - 'emitError', - 'keepAlive', - 'keepAliveInitialDelay', - 'noDelay', - 'connectTimeoutMS', - 'socketTimeoutMS', - 'family', - 'loggerLevel', - 'logger', - 'reconnectTries', - 'reconnectInterval', - 'monitoring', - 'appname', - 'domainsEnabled', - 'servername', - 'promoteLongs', - 'promoteValues', - 'promoteBuffers', - 'compression', - 'promiseLibrary', - 'monitorCommands' -]; - -/** - * Creates a new Server instance - * @class - * @deprecated - * @param {string} host The host for the server, can be either an IP4, IP6 or domain socket style host. - * @param {number} [port] The server port if IP4. - * @param {object} [options] Optional settings. - * @param {number} [options.poolSize=5] Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons. - * @param {boolean} [options.ssl=false] Use ssl connection (needs to have a mongod server with ssl support) - * @param {boolean} [options.sslValidate=false] Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {boolean|function} [options.checkServerIdentity=true] Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. - * @param {array} [options.sslCA] Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {array} [options.sslCRL] Array of revocation certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {(Buffer|string)} [options.sslCert] String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {string} [options.ciphers] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. - * @param {string} [options.ecdhCurve] Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. - * @param {(Buffer|string)} [options.sslKey] String or buffer containing the certificate private key we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {(Buffer|string)} [options.sslPass] String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {string} [options.servername] String containing the server name requested via TLS SNI. - * @param {object} [options.socketOptions] Socket options - * @param {boolean} [options.socketOptions.autoReconnect=true] Reconnect on error. - * @param {boolean} [options.socketOptions.noDelay=true] TCP Socket NoDelay option. - * @param {boolean} [options.socketOptions.keepAlive=true] TCP Connection keep alive enabled - * @param {number} [options.socketOptions.keepAliveInitialDelay=30000] The number of milliseconds to wait before initiating keepAlive on the TCP socket - * @param {number} [options.socketOptions.connectTimeoutMS=0] TCP Connection timeout setting - * @param {number} [options.socketOptions.socketTimeoutMS=0] TCP Socket timeout setting - * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times - * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries - * @param {boolean} [options.monitoring=true] Triggers the server instance to call ismaster - * @param {number} [options.haInterval=10000] The interval of calling ismaster when monitoring is enabled. - * @param {boolean} [options.domainsEnabled=false] Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit. - * @param {boolean} [options.monitorCommands=false] Enable command monitoring for this topology - * @fires Server#connect - * @fires Server#close - * @fires Server#error - * @fires Server#timeout - * @fires Server#parseError - * @fires Server#reconnect - * @fires Server#commandStarted - * @fires Server#commandSucceeded - * @fires Server#commandFailed - * @property {string} parserType the parser type used (c++ or js). - * @return {Server} a Server instance. - */ -class Server extends TopologyBase { - constructor(host, port, options) { - super(); - var self = this; - - // Filter the options - options = filterOptions(options, legalOptionNames); - - // Promise library - const promiseLibrary = options.promiseLibrary; - - // Stored options - var storeOptions = { - force: false, - bufferMaxEntries: - typeof options.bufferMaxEntries === 'number' ? options.bufferMaxEntries : MAX_JS_INT - }; - - // Shared global store - var store = options.store || new Store(self, storeOptions); - - // Detect if we have a socket connection - if (host.indexOf('/') !== -1) { - if (port != null && typeof port === 'object') { - options = port; - port = null; - } - } else if (port == null) { - throw MongoError.create({ message: 'port must be specified', driver: true }); - } - - // Get the reconnect option - var reconnect = typeof options.auto_reconnect === 'boolean' ? options.auto_reconnect : true; - reconnect = typeof options.autoReconnect === 'boolean' ? options.autoReconnect : reconnect; - - // Clone options - var clonedOptions = mergeOptions( - {}, - { - host: host, - port: port, - disconnectHandler: store, - cursorFactory: Cursor, - reconnect: reconnect, - emitError: typeof options.emitError === 'boolean' ? options.emitError : true, - size: typeof options.poolSize === 'number' ? options.poolSize : 5, - monitorCommands: - typeof options.monitorCommands === 'boolean' ? options.monitorCommands : false - } - ); - - // Translate any SSL options and other connectivity options - clonedOptions = translateOptions(clonedOptions, options); - - // Socket options - var socketOptions = - options.socketOptions && Object.keys(options.socketOptions).length > 0 - ? options.socketOptions - : options; - - // Translate all the options to the core types - clonedOptions = translateOptions(clonedOptions, socketOptions); - - // Build default client information - clonedOptions.clientInfo = this.clientInfo; - // Do we have an application specific string - if (options.appname) { - clonedOptions.clientInfo.application = { name: options.appname }; - } - - // Define the internal properties - this.s = { - // Create an instance of a server instance from core module - coreTopology: new CServer(clonedOptions), - // Server capabilities - sCapabilities: null, - // Cloned options - clonedOptions: clonedOptions, - // Reconnect - reconnect: clonedOptions.reconnect, - // Emit error - emitError: clonedOptions.emitError, - // Pool size - poolSize: clonedOptions.size, - // Store Options - storeOptions: storeOptions, - // Store - store: store, - // Host - host: host, - // Port - port: port, - // Options - options: options, - // Server Session Pool - sessionPool: null, - // Active client sessions - sessions: new Set(), - // Promise library - promiseLibrary: promiseLibrary || Promise - }; - } - - // Connect - connect(_options, callback) { - var self = this; - if ('function' === typeof _options) (callback = _options), (_options = {}); - if (_options == null) _options = this.s.clonedOptions; - if (!('function' === typeof callback)) callback = null; - _options = Object.assign({}, this.s.clonedOptions, _options); - self.s.options = _options; - - // Update bufferMaxEntries - self.s.storeOptions.bufferMaxEntries = - typeof _options.bufferMaxEntries === 'number' ? _options.bufferMaxEntries : -1; - - // Error handler - var connectErrorHandler = function() { - return function(err) { - // Remove all event handlers - var events = ['timeout', 'error', 'close']; - events.forEach(function(e) { - self.s.coreTopology.removeListener(e, connectHandlers[e]); - }); - - self.s.coreTopology.removeListener('connect', connectErrorHandler); - - // Try to callback - try { - callback(err); - } catch (err) { - process.nextTick(function() { - throw err; - }); - } - }; - }; - - // Actual handler - var errorHandler = function(event) { - return function(err) { - if (event !== 'error') { - self.emit(event, err); - } - }; - }; - - // Error handler - var reconnectHandler = function() { - self.emit('reconnect', self); - self.s.store.execute(); - }; - - // Reconnect failed - var reconnectFailedHandler = function(err) { - self.emit('reconnectFailed', err); - self.s.store.flush(err); - }; - - // Destroy called on topology, perform cleanup - var destroyHandler = function() { - self.s.store.flush(); - }; - - // relay the event - var relay = function(event) { - return function(t, server) { - self.emit(event, t, server); - }; - }; - - // Connect handler - var connectHandler = function() { - // Clear out all the current handlers left over - ['timeout', 'error', 'close', 'destroy'].forEach(function(e) { - self.s.coreTopology.removeAllListeners(e); - }); - - // Set up listeners - self.s.coreTopology.on('timeout', errorHandler('timeout')); - self.s.coreTopology.once('error', errorHandler('error')); - self.s.coreTopology.on('close', errorHandler('close')); - // Only called on destroy - self.s.coreTopology.on('destroy', destroyHandler); - - // Emit open event - self.emit('open', null, self); - - // Return correctly - try { - callback(null, self); - } catch (err) { - process.nextTick(function() { - throw err; - }); - } - }; - - // Set up listeners - var connectHandlers = { - timeout: connectErrorHandler('timeout'), - error: connectErrorHandler('error'), - close: connectErrorHandler('close') - }; - - // Clear out all the current handlers left over - [ - 'timeout', - 'error', - 'close', - 'serverOpening', - 'serverDescriptionChanged', - 'serverHeartbeatStarted', - 'serverHeartbeatSucceeded', - 'serverHeartbeatFailed', - 'serverClosed', - 'topologyOpening', - 'topologyClosed', - 'topologyDescriptionChanged', - 'commandStarted', - 'commandSucceeded', - 'commandFailed' - ].forEach(function(e) { - self.s.coreTopology.removeAllListeners(e); - }); - - // Add the event handlers - self.s.coreTopology.once('timeout', connectHandlers.timeout); - self.s.coreTopology.once('error', connectHandlers.error); - self.s.coreTopology.once('close', connectHandlers.close); - self.s.coreTopology.once('connect', connectHandler); - // Reconnect server - self.s.coreTopology.on('reconnect', reconnectHandler); - self.s.coreTopology.on('reconnectFailed', reconnectFailedHandler); - - // Set up SDAM listeners - self.s.coreTopology.on('serverDescriptionChanged', relay('serverDescriptionChanged')); - self.s.coreTopology.on('serverHeartbeatStarted', relay('serverHeartbeatStarted')); - self.s.coreTopology.on('serverHeartbeatSucceeded', relay('serverHeartbeatSucceeded')); - self.s.coreTopology.on('serverHeartbeatFailed', relay('serverHeartbeatFailed')); - self.s.coreTopology.on('serverOpening', relay('serverOpening')); - self.s.coreTopology.on('serverClosed', relay('serverClosed')); - self.s.coreTopology.on('topologyOpening', relay('topologyOpening')); - self.s.coreTopology.on('topologyClosed', relay('topologyClosed')); - self.s.coreTopology.on('topologyDescriptionChanged', relay('topologyDescriptionChanged')); - self.s.coreTopology.on('commandStarted', relay('commandStarted')); - self.s.coreTopology.on('commandSucceeded', relay('commandSucceeded')); - self.s.coreTopology.on('commandFailed', relay('commandFailed')); - self.s.coreTopology.on('attemptReconnect', relay('attemptReconnect')); - self.s.coreTopology.on('monitoring', relay('monitoring')); - - // Start connection - self.s.coreTopology.connect(_options); - } -} - -Object.defineProperty(Server.prototype, 'poolSize', { - enumerable: true, - get: function() { - return this.s.coreTopology.connections().length; - } -}); - -Object.defineProperty(Server.prototype, 'autoReconnect', { - enumerable: true, - get: function() { - return this.s.reconnect; - } -}); - -Object.defineProperty(Server.prototype, 'host', { - enumerable: true, - get: function() { - return this.s.host; - } -}); - -Object.defineProperty(Server.prototype, 'port', { - enumerable: true, - get: function() { - return this.s.port; - } -}); - -/** - * Server connect event - * - * @event Server#connect - * @type {object} - */ - -/** - * Server close event - * - * @event Server#close - * @type {object} - */ - -/** - * Server reconnect event - * - * @event Server#reconnect - * @type {object} - */ - -/** - * Server error event - * - * @event Server#error - * @type {MongoError} - */ - -/** - * Server timeout event - * - * @event Server#timeout - * @type {object} - */ - -/** - * Server parseError event - * - * @event Server#parseError - * @type {object} - */ - -/** - * An event emitted indicating a command was started, if command monitoring is enabled - * - * @event Server#commandStarted - * @type {object} - */ - -/** - * An event emitted indicating a command succeeded, if command monitoring is enabled - * - * @event Server#commandSucceeded - * @type {object} - */ - -/** - * An event emitted indicating a command failed, if command monitoring is enabled - * - * @event Server#commandFailed - * @type {object} - */ - -module.exports = Server; diff --git a/scripts/node_modules/mongodb/lib/topologies/topology_base.js b/scripts/node_modules/mongodb/lib/topologies/topology_base.js deleted file mode 100644 index e74cb9ff..00000000 --- a/scripts/node_modules/mongodb/lib/topologies/topology_base.js +++ /dev/null @@ -1,438 +0,0 @@ -'use strict'; - -const EventEmitter = require('events'), - MongoError = require('../core').MongoError, - f = require('util').format, - os = require('os'), - translateReadPreference = require('../utils').translateReadPreference, - ClientSession = require('../core').Sessions.ClientSession; - -// The store of ops -var Store = function(topology, storeOptions) { - var self = this; - var storedOps = []; - storeOptions = storeOptions || { force: false, bufferMaxEntries: -1 }; - - // Internal state - this.s = { - storedOps: storedOps, - storeOptions: storeOptions, - topology: topology - }; - - Object.defineProperty(this, 'length', { - enumerable: true, - get: function() { - return self.s.storedOps.length; - } - }); -}; - -Store.prototype.add = function(opType, ns, ops, options, callback) { - if (this.s.storeOptions.force) { - return callback(MongoError.create({ message: 'db closed by application', driver: true })); - } - - if (this.s.storeOptions.bufferMaxEntries === 0) { - return callback( - MongoError.create({ - message: f( - 'no connection available for operation and number of stored operation > %s', - this.s.storeOptions.bufferMaxEntries - ), - driver: true - }) - ); - } - - if ( - this.s.storeOptions.bufferMaxEntries > 0 && - this.s.storedOps.length > this.s.storeOptions.bufferMaxEntries - ) { - while (this.s.storedOps.length > 0) { - var op = this.s.storedOps.shift(); - op.c( - MongoError.create({ - message: f( - 'no connection available for operation and number of stored operation > %s', - this.s.storeOptions.bufferMaxEntries - ), - driver: true - }) - ); - } - - return; - } - - this.s.storedOps.push({ t: opType, n: ns, o: ops, op: options, c: callback }); -}; - -Store.prototype.addObjectAndMethod = function(opType, object, method, params, callback) { - if (this.s.storeOptions.force) { - return callback(MongoError.create({ message: 'db closed by application', driver: true })); - } - - if (this.s.storeOptions.bufferMaxEntries === 0) { - return callback( - MongoError.create({ - message: f( - 'no connection available for operation and number of stored operation > %s', - this.s.storeOptions.bufferMaxEntries - ), - driver: true - }) - ); - } - - if ( - this.s.storeOptions.bufferMaxEntries > 0 && - this.s.storedOps.length > this.s.storeOptions.bufferMaxEntries - ) { - while (this.s.storedOps.length > 0) { - var op = this.s.storedOps.shift(); - op.c( - MongoError.create({ - message: f( - 'no connection available for operation and number of stored operation > %s', - this.s.storeOptions.bufferMaxEntries - ), - driver: true - }) - ); - } - - return; - } - - this.s.storedOps.push({ t: opType, m: method, o: object, p: params, c: callback }); -}; - -Store.prototype.flush = function(err) { - while (this.s.storedOps.length > 0) { - this.s.storedOps - .shift() - .c( - err || - MongoError.create({ message: f('no connection available for operation'), driver: true }) - ); - } -}; - -var primaryOptions = ['primary', 'primaryPreferred', 'nearest', 'secondaryPreferred']; -var secondaryOptions = ['secondary', 'secondaryPreferred']; - -Store.prototype.execute = function(options) { - options = options || {}; - // Get current ops - var ops = this.s.storedOps; - // Reset the ops - this.s.storedOps = []; - - // Unpack options - var executePrimary = typeof options.executePrimary === 'boolean' ? options.executePrimary : true; - var executeSecondary = - typeof options.executeSecondary === 'boolean' ? options.executeSecondary : true; - - // Execute all the stored ops - while (ops.length > 0) { - var op = ops.shift(); - - if (op.t === 'cursor') { - if (executePrimary && executeSecondary) { - op.o[op.m].apply(op.o, op.p); - } else if ( - executePrimary && - op.o.options && - op.o.options.readPreference && - primaryOptions.indexOf(op.o.options.readPreference.mode) !== -1 - ) { - op.o[op.m].apply(op.o, op.p); - } else if ( - !executePrimary && - executeSecondary && - op.o.options && - op.o.options.readPreference && - secondaryOptions.indexOf(op.o.options.readPreference.mode) !== -1 - ) { - op.o[op.m].apply(op.o, op.p); - } - } else if (op.t === 'auth') { - this.s.topology[op.t].apply(this.s.topology, op.o); - } else { - if (executePrimary && executeSecondary) { - this.s.topology[op.t](op.n, op.o, op.op, op.c); - } else if ( - executePrimary && - op.op && - op.op.readPreference && - primaryOptions.indexOf(op.op.readPreference.mode) !== -1 - ) { - this.s.topology[op.t](op.n, op.o, op.op, op.c); - } else if ( - !executePrimary && - executeSecondary && - op.op && - op.op.readPreference && - secondaryOptions.indexOf(op.op.readPreference.mode) !== -1 - ) { - this.s.topology[op.t](op.n, op.o, op.op, op.c); - } - } - } -}; - -Store.prototype.all = function() { - return this.s.storedOps; -}; - -// Server capabilities -var ServerCapabilities = function(ismaster) { - var setup_get_property = function(object, name, value) { - Object.defineProperty(object, name, { - enumerable: true, - get: function() { - return value; - } - }); - }; - - // Capabilities - var aggregationCursor = false; - var writeCommands = false; - var textSearch = false; - var authCommands = false; - var listCollections = false; - var listIndexes = false; - var maxNumberOfDocsInBatch = ismaster.maxWriteBatchSize || 1000; - var commandsTakeWriteConcern = false; - var commandsTakeCollation = false; - - if (ismaster.minWireVersion >= 0) { - textSearch = true; - } - - if (ismaster.maxWireVersion >= 1) { - aggregationCursor = true; - authCommands = true; - } - - if (ismaster.maxWireVersion >= 2) { - writeCommands = true; - } - - if (ismaster.maxWireVersion >= 3) { - listCollections = true; - listIndexes = true; - } - - if (ismaster.maxWireVersion >= 5) { - commandsTakeWriteConcern = true; - commandsTakeCollation = true; - } - - // If no min or max wire version set to 0 - if (ismaster.minWireVersion == null) { - ismaster.minWireVersion = 0; - } - - if (ismaster.maxWireVersion == null) { - ismaster.maxWireVersion = 0; - } - - // Map up read only parameters - setup_get_property(this, 'hasAggregationCursor', aggregationCursor); - setup_get_property(this, 'hasWriteCommands', writeCommands); - setup_get_property(this, 'hasTextSearch', textSearch); - setup_get_property(this, 'hasAuthCommands', authCommands); - setup_get_property(this, 'hasListCollectionsCommand', listCollections); - setup_get_property(this, 'hasListIndexesCommand', listIndexes); - setup_get_property(this, 'minWireVersion', ismaster.minWireVersion); - setup_get_property(this, 'maxWireVersion', ismaster.maxWireVersion); - setup_get_property(this, 'maxNumberOfDocsInBatch', maxNumberOfDocsInBatch); - setup_get_property(this, 'commandsTakeWriteConcern', commandsTakeWriteConcern); - setup_get_property(this, 'commandsTakeCollation', commandsTakeCollation); -}; - -// Get package.json variable -const driverVersion = require('../../package.json').version, - nodejsversion = f('Node.js %s, %s', process.version, os.endianness()), - type = os.type(), - name = process.platform, - architecture = process.arch, - release = os.release(); - -class TopologyBase extends EventEmitter { - constructor() { - super(); - - // Build default client information - this.clientInfo = { - driver: { - name: 'nodejs', - version: driverVersion - }, - os: { - type: type, - name: name, - architecture: architecture, - version: release - }, - platform: nodejsversion - }; - - this.setMaxListeners(Infinity); - } - - // Sessions related methods - hasSessionSupport() { - return this.logicalSessionTimeoutMinutes != null; - } - - startSession(options, clientOptions) { - const session = new ClientSession(this, this.s.sessionPool, options, clientOptions); - - session.once('ended', () => { - this.s.sessions.delete(session); - }); - - this.s.sessions.add(session); - return session; - } - - endSessions(sessions, callback) { - return this.s.coreTopology.endSessions(sessions, callback); - } - - // Server capabilities - capabilities() { - if (this.s.sCapabilities) return this.s.sCapabilities; - if (this.s.coreTopology.lastIsMaster() == null) return null; - this.s.sCapabilities = new ServerCapabilities(this.s.coreTopology.lastIsMaster()); - return this.s.sCapabilities; - } - - // Command - command(ns, cmd, options, callback) { - this.s.coreTopology.command(ns.toString(), cmd, translateReadPreference(options), callback); - } - - // Insert - insert(ns, ops, options, callback) { - this.s.coreTopology.insert(ns.toString(), ops, options, callback); - } - - // Update - update(ns, ops, options, callback) { - this.s.coreTopology.update(ns.toString(), ops, options, callback); - } - - // Remove - remove(ns, ops, options, callback) { - this.s.coreTopology.remove(ns.toString(), ops, options, callback); - } - - // IsConnected - isConnected(options) { - options = options || {}; - options = translateReadPreference(options); - - return this.s.coreTopology.isConnected(options); - } - - // IsDestroyed - isDestroyed() { - return this.s.coreTopology.isDestroyed(); - } - - // Cursor - cursor(ns, cmd, options) { - options = options || {}; - options = translateReadPreference(options); - options.disconnectHandler = this.s.store; - options.topology = this; - - return this.s.coreTopology.cursor(ns, cmd, options); - } - - lastIsMaster() { - return this.s.coreTopology.lastIsMaster(); - } - - selectServer(selector, options, callback) { - return this.s.coreTopology.selectServer(selector, options, callback); - } - - /** - * Unref all sockets - * @method - */ - unref() { - return this.s.coreTopology.unref(); - } - - /** - * All raw connections - * @method - * @return {array} - */ - connections() { - return this.s.coreTopology.connections(); - } - - close(forceClosed, callback) { - // If we have sessions, we want to individually move them to the session pool, - // and then send a single endSessions call. - this.s.sessions.forEach(session => session.endSession()); - - if (this.s.sessionPool) { - this.s.sessionPool.endAllPooledSessions(); - } - - // We need to wash out all stored processes - if (forceClosed === true) { - this.s.storeOptions.force = forceClosed; - this.s.store.flush(); - } - - this.s.coreTopology.destroy( - { - force: typeof forceClosed === 'boolean' ? forceClosed : false - }, - callback - ); - } -} - -// Properties -Object.defineProperty(TopologyBase.prototype, 'bson', { - enumerable: true, - get: function() { - return this.s.coreTopology.s.bson; - } -}); - -Object.defineProperty(TopologyBase.prototype, 'parserType', { - enumerable: true, - get: function() { - return this.s.coreTopology.parserType; - } -}); - -Object.defineProperty(TopologyBase.prototype, 'logicalSessionTimeoutMinutes', { - enumerable: true, - get: function() { - return this.s.coreTopology.logicalSessionTimeoutMinutes; - } -}); - -Object.defineProperty(TopologyBase.prototype, 'type', { - enumerable: true, - get: function() { - return this.s.coreTopology.type; - } -}); - -exports.Store = Store; -exports.ServerCapabilities = ServerCapabilities; -exports.TopologyBase = TopologyBase; diff --git a/scripts/node_modules/mongodb/lib/url_parser.js b/scripts/node_modules/mongodb/lib/url_parser.js deleted file mode 100644 index c0f10b46..00000000 --- a/scripts/node_modules/mongodb/lib/url_parser.js +++ /dev/null @@ -1,623 +0,0 @@ -'use strict'; - -const ReadPreference = require('./core').ReadPreference, - parser = require('url'), - f = require('util').format, - Logger = require('./core').Logger, - dns = require('dns'); -const ReadConcern = require('./read_concern'); - -module.exports = function(url, options, callback) { - if (typeof options === 'function') (callback = options), (options = {}); - options = options || {}; - - let result; - try { - result = parser.parse(url, true); - } catch (e) { - return callback(new Error('URL malformed, cannot be parsed')); - } - - if (result.protocol !== 'mongodb:' && result.protocol !== 'mongodb+srv:') { - return callback(new Error('Invalid schema, expected `mongodb` or `mongodb+srv`')); - } - - if (result.protocol === 'mongodb:') { - return parseHandler(url, options, callback); - } - - // Otherwise parse this as an SRV record - if (result.hostname.split('.').length < 3) { - return callback(new Error('URI does not have hostname, domain name and tld')); - } - - result.domainLength = result.hostname.split('.').length; - - if (result.pathname && result.pathname.match(',')) { - return callback(new Error('Invalid URI, cannot contain multiple hostnames')); - } - - if (result.port) { - return callback(new Error('Ports not accepted with `mongodb+srv` URIs')); - } - - let srvAddress = `_mongodb._tcp.${result.host}`; - dns.resolveSrv(srvAddress, function(err, addresses) { - if (err) return callback(err); - - if (addresses.length === 0) { - return callback(new Error('No addresses found at host')); - } - - for (let i = 0; i < addresses.length; i++) { - if (!matchesParentDomain(addresses[i].name, result.hostname, result.domainLength)) { - return callback(new Error('Server record does not share hostname with parent URI')); - } - } - - let base = result.auth ? `mongodb://${result.auth}@` : `mongodb://`; - let connectionStrings = addresses.map(function(address, i) { - if (i === 0) return `${base}${address.name}:${address.port}`; - else return `${address.name}:${address.port}`; - }); - - let connectionString = connectionStrings.join(',') + '/'; - let connectionStringOptions = []; - - // Add the default database if needed - if (result.path) { - let defaultDb = result.path.slice(1); - if (defaultDb.indexOf('?') !== -1) { - defaultDb = defaultDb.slice(0, defaultDb.indexOf('?')); - } - - connectionString += defaultDb; - } - - // Default to SSL true - if (!options.ssl && !result.search) { - connectionStringOptions.push('ssl=true'); - } else if (!options.ssl && result.search && !result.search.match('ssl')) { - connectionStringOptions.push('ssl=true'); - } - - // Keep original uri options - if (result.search) { - connectionStringOptions.push(result.search.replace('?', '')); - } - - dns.resolveTxt(result.host, function(err, record) { - if (err && err.code !== 'ENODATA') return callback(err); - if (err && err.code === 'ENODATA') record = null; - - if (record) { - if (record.length > 1) { - return callback(new Error('Multiple text records not allowed')); - } - - record = record[0]; - if (record.length > 1) record = record.join(''); - else record = record[0]; - - if (!record.includes('authSource') && !record.includes('replicaSet')) { - return callback(new Error('Text record must only set `authSource` or `replicaSet`')); - } - - connectionStringOptions.push(record); - } - - // Add any options to the connection string - if (connectionStringOptions.length) { - connectionString += `?${connectionStringOptions.join('&')}`; - } - - parseHandler(connectionString, options, callback); - }); - }); -}; - -function matchesParentDomain(srvAddress, parentDomain) { - let regex = /^.*?\./; - let srv = `.${srvAddress.replace(regex, '')}`; - let parent = `.${parentDomain.replace(regex, '')}`; - if (srv.endsWith(parent)) return true; - else return false; -} - -function parseHandler(address, options, callback) { - let result, err; - try { - result = parseConnectionString(address, options); - } catch (e) { - err = e; - } - - return err ? callback(err, null) : callback(null, result); -} - -function parseConnectionString(url, options) { - // Variables - let connection_part = ''; - let auth_part = ''; - let query_string_part = ''; - let dbName = 'admin'; - - // Url parser result - let result = parser.parse(url, true); - if ((result.hostname == null || result.hostname === '') && url.indexOf('.sock') === -1) { - throw new Error('No hostname or hostnames provided in connection string'); - } - - if (result.port === '0') { - throw new Error('Invalid port (zero) with hostname'); - } - - if (!isNaN(parseInt(result.port, 10)) && parseInt(result.port, 10) > 65535) { - throw new Error('Invalid port (larger than 65535) with hostname'); - } - - if ( - result.path && - result.path.length > 0 && - result.path[0] !== '/' && - url.indexOf('.sock') === -1 - ) { - throw new Error('Missing delimiting slash between hosts and options'); - } - - if (result.query) { - for (let name in result.query) { - if (name.indexOf('::') !== -1) { - throw new Error('Double colon in host identifier'); - } - - if (result.query[name] === '') { - throw new Error('Query parameter ' + name + ' is an incomplete value pair'); - } - } - } - - if (result.auth) { - let parts = result.auth.split(':'); - if (url.indexOf(result.auth) !== -1 && parts.length > 2) { - throw new Error('Username with password containing an unescaped colon'); - } - - if (url.indexOf(result.auth) !== -1 && result.auth.indexOf('@') !== -1) { - throw new Error('Username containing an unescaped at-sign'); - } - } - - // Remove query - let clean = url.split('?').shift(); - - // Extract the list of hosts - let strings = clean.split(','); - let hosts = []; - - for (let i = 0; i < strings.length; i++) { - let hostString = strings[i]; - - if (hostString.indexOf('mongodb') !== -1) { - if (hostString.indexOf('@') !== -1) { - hosts.push(hostString.split('@').pop()); - } else { - hosts.push(hostString.substr('mongodb://'.length)); - } - } else if (hostString.indexOf('/') !== -1) { - hosts.push(hostString.split('/').shift()); - } else if (hostString.indexOf('/') === -1) { - hosts.push(hostString.trim()); - } - } - - for (let i = 0; i < hosts.length; i++) { - let r = parser.parse(f('mongodb://%s', hosts[i].trim())); - if (r.path && r.path.indexOf('.sock') !== -1) continue; - if (r.path && r.path.indexOf(':') !== -1) { - // Not connecting to a socket so check for an extra slash in the hostname. - // Using String#split as perf is better than match. - if (r.path.split('/').length > 1 && r.path.indexOf('::') === -1) { - throw new Error('Slash in host identifier'); - } else { - throw new Error('Double colon in host identifier'); - } - } - } - - // If we have a ? mark cut the query elements off - if (url.indexOf('?') !== -1) { - query_string_part = url.substr(url.indexOf('?') + 1); - connection_part = url.substring('mongodb://'.length, url.indexOf('?')); - } else { - connection_part = url.substring('mongodb://'.length); - } - - // Check if we have auth params - if (connection_part.indexOf('@') !== -1) { - auth_part = connection_part.split('@')[0]; - connection_part = connection_part.split('@')[1]; - } - - // Check there is not more than one unescaped slash - if (connection_part.split('/').length > 2) { - throw new Error( - "Unsupported host '" + - connection_part.split('?')[0] + - "', hosts must be URL encoded and contain at most one unencoded slash" - ); - } - - // Check if the connection string has a db - if (connection_part.indexOf('.sock') !== -1) { - if (connection_part.indexOf('.sock/') !== -1) { - dbName = connection_part.split('.sock/')[1]; - // Check if multiple database names provided, or just an illegal trailing backslash - if (dbName.indexOf('/') !== -1) { - if (dbName.split('/').length === 2 && dbName.split('/')[1].length === 0) { - throw new Error('Illegal trailing backslash after database name'); - } - throw new Error('More than 1 database name in URL'); - } - connection_part = connection_part.split( - '/', - connection_part.indexOf('.sock') + '.sock'.length - ); - } - } else if (connection_part.indexOf('/') !== -1) { - // Check if multiple database names provided, or just an illegal trailing backslash - if (connection_part.split('/').length > 2) { - if (connection_part.split('/')[2].length === 0) { - throw new Error('Illegal trailing backslash after database name'); - } - throw new Error('More than 1 database name in URL'); - } - dbName = connection_part.split('/')[1]; - connection_part = connection_part.split('/')[0]; - } - - // URI decode the host information - connection_part = decodeURIComponent(connection_part); - - // Result object - let object = {}; - - // Pick apart the authentication part of the string - let authPart = auth_part || ''; - let auth = authPart.split(':', 2); - - // Decode the authentication URI components and verify integrity - let user = decodeURIComponent(auth[0]); - if (auth[0] !== encodeURIComponent(user)) { - throw new Error('Username contains an illegal unescaped character'); - } - auth[0] = user; - - if (auth[1]) { - let pass = decodeURIComponent(auth[1]); - if (auth[1] !== encodeURIComponent(pass)) { - throw new Error('Password contains an illegal unescaped character'); - } - auth[1] = pass; - } - - // Add auth to final object if we have 2 elements - if (auth.length === 2) object.auth = { user: auth[0], password: auth[1] }; - // if user provided auth options, use that - if (options && options.auth != null) object.auth = options.auth; - - // Variables used for temporary storage - let hostPart; - let urlOptions; - let servers; - let compression; - let serverOptions = { socketOptions: {} }; - let dbOptions = { read_preference_tags: [] }; - let replSetServersOptions = { socketOptions: {} }; - let mongosOptions = { socketOptions: {} }; - // Add server options to final object - object.server_options = serverOptions; - object.db_options = dbOptions; - object.rs_options = replSetServersOptions; - object.mongos_options = mongosOptions; - - // Let's check if we are using a domain socket - if (url.match(/\.sock/)) { - // Split out the socket part - let domainSocket = url.substring( - url.indexOf('mongodb://') + 'mongodb://'.length, - url.lastIndexOf('.sock') + '.sock'.length - ); - // Clean out any auth stuff if any - if (domainSocket.indexOf('@') !== -1) domainSocket = domainSocket.split('@')[1]; - domainSocket = decodeURIComponent(domainSocket); - servers = [{ domain_socket: domainSocket }]; - } else { - // Split up the db - hostPart = connection_part; - // Deduplicate servers - let deduplicatedServers = {}; - - // Parse all server results - servers = hostPart - .split(',') - .map(function(h) { - let _host, _port, ipv6match; - //check if it matches [IPv6]:port, where the port number is optional - if ((ipv6match = /\[([^\]]+)\](?::(.+))?/.exec(h))) { - _host = ipv6match[1]; - _port = parseInt(ipv6match[2], 10) || 27017; - } else { - //otherwise assume it's IPv4, or plain hostname - let hostPort = h.split(':', 2); - _host = hostPort[0] || 'localhost'; - _port = hostPort[1] != null ? parseInt(hostPort[1], 10) : 27017; - // Check for localhost?safe=true style case - if (_host.indexOf('?') !== -1) _host = _host.split(/\?/)[0]; - } - - // No entry returned for duplicate server - if (deduplicatedServers[_host + '_' + _port]) return null; - deduplicatedServers[_host + '_' + _port] = 1; - - // Return the mapped object - return { host: _host, port: _port }; - }) - .filter(function(x) { - return x != null; - }); - } - - // Get the db name - object.dbName = dbName || 'admin'; - // Split up all the options - urlOptions = (query_string_part || '').split(/[&;]/); - // Ugh, we have to figure out which options go to which constructor manually. - urlOptions.forEach(function(opt) { - if (!opt) return; - var splitOpt = opt.split('='), - name = splitOpt[0], - value = splitOpt[1]; - - // Options implementations - switch (name) { - case 'slaveOk': - case 'slave_ok': - serverOptions.slave_ok = value === 'true'; - dbOptions.slaveOk = value === 'true'; - break; - case 'maxPoolSize': - case 'poolSize': - serverOptions.poolSize = parseInt(value, 10); - replSetServersOptions.poolSize = parseInt(value, 10); - break; - case 'appname': - object.appname = decodeURIComponent(value); - break; - case 'autoReconnect': - case 'auto_reconnect': - serverOptions.auto_reconnect = value === 'true'; - break; - case 'ssl': - if (value === 'prefer') { - serverOptions.ssl = value; - replSetServersOptions.ssl = value; - mongosOptions.ssl = value; - break; - } - serverOptions.ssl = value === 'true'; - replSetServersOptions.ssl = value === 'true'; - mongosOptions.ssl = value === 'true'; - break; - case 'sslValidate': - serverOptions.sslValidate = value === 'true'; - replSetServersOptions.sslValidate = value === 'true'; - mongosOptions.sslValidate = value === 'true'; - break; - case 'replicaSet': - case 'rs_name': - replSetServersOptions.rs_name = value; - break; - case 'reconnectWait': - replSetServersOptions.reconnectWait = parseInt(value, 10); - break; - case 'retries': - replSetServersOptions.retries = parseInt(value, 10); - break; - case 'readSecondary': - case 'read_secondary': - replSetServersOptions.read_secondary = value === 'true'; - break; - case 'fsync': - dbOptions.fsync = value === 'true'; - break; - case 'journal': - dbOptions.j = value === 'true'; - break; - case 'safe': - dbOptions.safe = value === 'true'; - break; - case 'nativeParser': - case 'native_parser': - dbOptions.native_parser = value === 'true'; - break; - case 'readConcernLevel': - dbOptions.readConcern = new ReadConcern(value); - break; - case 'connectTimeoutMS': - serverOptions.socketOptions.connectTimeoutMS = parseInt(value, 10); - replSetServersOptions.socketOptions.connectTimeoutMS = parseInt(value, 10); - mongosOptions.socketOptions.connectTimeoutMS = parseInt(value, 10); - break; - case 'socketTimeoutMS': - serverOptions.socketOptions.socketTimeoutMS = parseInt(value, 10); - replSetServersOptions.socketOptions.socketTimeoutMS = parseInt(value, 10); - mongosOptions.socketOptions.socketTimeoutMS = parseInt(value, 10); - break; - case 'w': - dbOptions.w = parseInt(value, 10); - if (isNaN(dbOptions.w)) dbOptions.w = value; - break; - case 'authSource': - dbOptions.authSource = value; - break; - case 'gssapiServiceName': - dbOptions.gssapiServiceName = value; - break; - case 'authMechanism': - if (value === 'GSSAPI') { - // If no password provided decode only the principal - if (object.auth == null) { - let urlDecodeAuthPart = decodeURIComponent(authPart); - if (urlDecodeAuthPart.indexOf('@') === -1) - throw new Error('GSSAPI requires a provided principal'); - object.auth = { user: urlDecodeAuthPart, password: null }; - } else { - object.auth.user = decodeURIComponent(object.auth.user); - } - } else if (value === 'MONGODB-X509') { - object.auth = { user: decodeURIComponent(authPart) }; - } - - // Only support GSSAPI or MONGODB-CR for now - if ( - value !== 'GSSAPI' && - value !== 'MONGODB-X509' && - value !== 'MONGODB-CR' && - value !== 'DEFAULT' && - value !== 'SCRAM-SHA-1' && - value !== 'SCRAM-SHA-256' && - value !== 'PLAIN' - ) - throw new Error( - 'Only DEFAULT, GSSAPI, PLAIN, MONGODB-X509, or SCRAM-SHA-1 is supported by authMechanism' - ); - - // Authentication mechanism - dbOptions.authMechanism = value; - break; - case 'authMechanismProperties': - { - // Split up into key, value pairs - let values = value.split(','); - let o = {}; - // For each value split into key, value - values.forEach(function(x) { - let v = x.split(':'); - o[v[0]] = v[1]; - }); - - // Set all authMechanismProperties - dbOptions.authMechanismProperties = o; - // Set the service name value - if (typeof o.SERVICE_NAME === 'string') dbOptions.gssapiServiceName = o.SERVICE_NAME; - if (typeof o.SERVICE_REALM === 'string') dbOptions.gssapiServiceRealm = o.SERVICE_REALM; - if (typeof o.CANONICALIZE_HOST_NAME === 'string') - dbOptions.gssapiCanonicalizeHostName = - o.CANONICALIZE_HOST_NAME === 'true' ? true : false; - } - break; - case 'wtimeoutMS': - dbOptions.wtimeout = parseInt(value, 10); - break; - case 'readPreference': - if (!ReadPreference.isValid(value)) - throw new Error( - 'readPreference must be either primary/primaryPreferred/secondary/secondaryPreferred/nearest' - ); - dbOptions.readPreference = value; - break; - case 'maxStalenessSeconds': - dbOptions.maxStalenessSeconds = parseInt(value, 10); - break; - case 'readPreferenceTags': - { - // Decode the value - value = decodeURIComponent(value); - // Contains the tag object - let tagObject = {}; - if (value == null || value === '') { - dbOptions.read_preference_tags.push(tagObject); - break; - } - - // Split up the tags - let tags = value.split(/,/); - for (let i = 0; i < tags.length; i++) { - let parts = tags[i].trim().split(/:/); - tagObject[parts[0]] = parts[1]; - } - - // Set the preferences tags - dbOptions.read_preference_tags.push(tagObject); - } - break; - case 'compressors': - { - compression = serverOptions.compression || {}; - let compressors = value.split(','); - if ( - !compressors.every(function(compressor) { - return compressor === 'snappy' || compressor === 'zlib'; - }) - ) { - throw new Error('Compressors must be at least one of snappy or zlib'); - } - - compression.compressors = compressors; - serverOptions.compression = compression; - } - break; - case 'zlibCompressionLevel': - { - compression = serverOptions.compression || {}; - let zlibCompressionLevel = parseInt(value, 10); - if (zlibCompressionLevel < -1 || zlibCompressionLevel > 9) { - throw new Error('zlibCompressionLevel must be an integer between -1 and 9'); - } - - compression.zlibCompressionLevel = zlibCompressionLevel; - serverOptions.compression = compression; - } - break; - case 'retryWrites': - dbOptions.retryWrites = value === 'true'; - break; - case 'minSize': - dbOptions.minSize = parseInt(value, 10); - break; - default: - { - let logger = Logger('URL Parser'); - logger.warn(`${name} is not supported as a connection string option`); - } - break; - } - }); - - // No tags: should be null (not []) - if (dbOptions.read_preference_tags.length === 0) { - dbOptions.read_preference_tags = null; - } - - // Validate if there are an invalid write concern combinations - if ( - (dbOptions.w === -1 || dbOptions.w === 0) && - (dbOptions.journal === true || dbOptions.fsync === true || dbOptions.safe === true) - ) - throw new Error('w set to -1 or 0 cannot be combined with safe/w/journal/fsync'); - - // If no read preference set it to primary - if (!dbOptions.readPreference) { - dbOptions.readPreference = 'primary'; - } - - // make sure that user-provided options are applied with priority - dbOptions = Object.assign(dbOptions, options); - - // Add servers to result - object.servers = servers; - - // Returned parsed object - return object; -} diff --git a/scripts/node_modules/mongodb/lib/utils.js b/scripts/node_modules/mongodb/lib/utils.js deleted file mode 100644 index 98dee668..00000000 --- a/scripts/node_modules/mongodb/lib/utils.js +++ /dev/null @@ -1,716 +0,0 @@ -'use strict'; - -const MongoError = require('./core/error').MongoError; -const ReadPreference = require('./core/topologies/read_preference'); -const WriteConcern = require('./write_concern'); - -var shallowClone = function(obj) { - var copy = {}; - for (var name in obj) copy[name] = obj[name]; - return copy; -}; - -// Figure out the read preference -var translateReadPreference = function(options) { - var r = null; - if (options.readPreference) { - r = options.readPreference; - } else { - return options; - } - - if (typeof r === 'string') { - options.readPreference = new ReadPreference(r); - } else if (r && !(r instanceof ReadPreference) && typeof r === 'object') { - const mode = r.mode || r.preference; - if (mode && typeof mode === 'string') { - options.readPreference = new ReadPreference(mode, r.tags, { - maxStalenessSeconds: r.maxStalenessSeconds - }); - } - } else if (!(r instanceof ReadPreference)) { - throw new TypeError('Invalid read preference: ' + r); - } - - return options; -}; - -// Set simple property -var getSingleProperty = function(obj, name, value) { - Object.defineProperty(obj, name, { - enumerable: true, - get: function() { - return value; - } - }); -}; - -var formatSortValue = (exports.formatSortValue = function(sortDirection) { - var value = ('' + sortDirection).toLowerCase(); - - switch (value) { - case 'ascending': - case 'asc': - case '1': - return 1; - case 'descending': - case 'desc': - case '-1': - return -1; - default: - throw new Error( - 'Illegal sort clause, must be of the form ' + - "[['field1', '(ascending|descending)'], " + - "['field2', '(ascending|descending)']]" - ); - } -}); - -var formattedOrderClause = (exports.formattedOrderClause = function(sortValue) { - var orderBy = {}; - if (sortValue == null) return null; - if (Array.isArray(sortValue)) { - if (sortValue.length === 0) { - return null; - } - - for (var i = 0; i < sortValue.length; i++) { - if (sortValue[i].constructor === String) { - orderBy[sortValue[i]] = 1; - } else { - orderBy[sortValue[i][0]] = formatSortValue(sortValue[i][1]); - } - } - } else if (sortValue != null && typeof sortValue === 'object') { - orderBy = sortValue; - } else if (typeof sortValue === 'string') { - orderBy[sortValue] = 1; - } else { - throw new Error( - 'Illegal sort clause, must be of the form ' + - "[['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]" - ); - } - - return orderBy; -}); - -var checkCollectionName = function checkCollectionName(collectionName) { - if ('string' !== typeof collectionName) { - throw new MongoError('collection name must be a String'); - } - - if (!collectionName || collectionName.indexOf('..') !== -1) { - throw new MongoError('collection names cannot be empty'); - } - - if ( - collectionName.indexOf('$') !== -1 && - collectionName.match(/((^\$cmd)|(oplog\.\$main))/) == null - ) { - throw new MongoError("collection names must not contain '$'"); - } - - if (collectionName.match(/^\.|\.$/) != null) { - throw new MongoError("collection names must not start or end with '.'"); - } - - // Validate that we are not passing 0x00 in the collection name - if (collectionName.indexOf('\x00') !== -1) { - throw new MongoError('collection names cannot contain a null character'); - } -}; - -var handleCallback = function(callback, err, value1, value2) { - try { - if (callback == null) return; - - if (callback) { - return value2 ? callback(err, value1, value2) : callback(err, value1); - } - } catch (err) { - process.nextTick(function() { - throw err; - }); - return false; - } - - return true; -}; - -/** - * Wrap a Mongo error document in an Error instance - * @ignore - * @api private - */ -var toError = function(error) { - if (error instanceof Error) return error; - - var msg = error.err || error.errmsg || error.errMessage || error; - var e = MongoError.create({ message: msg, driver: true }); - - // Get all object keys - var keys = typeof error === 'object' ? Object.keys(error) : []; - - for (var i = 0; i < keys.length; i++) { - try { - e[keys[i]] = error[keys[i]]; - } catch (err) { - // continue - } - } - - return e; -}; - -/** - * @ignore - */ -var normalizeHintField = function normalizeHintField(hint) { - var finalHint = null; - - if (typeof hint === 'string') { - finalHint = hint; - } else if (Array.isArray(hint)) { - finalHint = {}; - - hint.forEach(function(param) { - finalHint[param] = 1; - }); - } else if (hint != null && typeof hint === 'object') { - finalHint = {}; - for (var name in hint) { - finalHint[name] = hint[name]; - } - } - - return finalHint; -}; - -/** - * Create index name based on field spec - * - * @ignore - * @api private - */ -var parseIndexOptions = function(fieldOrSpec) { - var fieldHash = {}; - var indexes = []; - var keys; - - // Get all the fields accordingly - if ('string' === typeof fieldOrSpec) { - // 'type' - indexes.push(fieldOrSpec + '_' + 1); - fieldHash[fieldOrSpec] = 1; - } else if (Array.isArray(fieldOrSpec)) { - fieldOrSpec.forEach(function(f) { - if ('string' === typeof f) { - // [{location:'2d'}, 'type'] - indexes.push(f + '_' + 1); - fieldHash[f] = 1; - } else if (Array.isArray(f)) { - // [['location', '2d'],['type', 1]] - indexes.push(f[0] + '_' + (f[1] || 1)); - fieldHash[f[0]] = f[1] || 1; - } else if (isObject(f)) { - // [{location:'2d'}, {type:1}] - keys = Object.keys(f); - keys.forEach(function(k) { - indexes.push(k + '_' + f[k]); - fieldHash[k] = f[k]; - }); - } else { - // undefined (ignore) - } - }); - } else if (isObject(fieldOrSpec)) { - // {location:'2d', type:1} - keys = Object.keys(fieldOrSpec); - keys.forEach(function(key) { - indexes.push(key + '_' + fieldOrSpec[key]); - fieldHash[key] = fieldOrSpec[key]; - }); - } - - return { - name: indexes.join('_'), - keys: keys, - fieldHash: fieldHash - }; -}; - -var isObject = (exports.isObject = function(arg) { - return '[object Object]' === Object.prototype.toString.call(arg); -}); - -var debugOptions = function(debugFields, options) { - var finaloptions = {}; - debugFields.forEach(function(n) { - finaloptions[n] = options[n]; - }); - - return finaloptions; -}; - -var decorateCommand = function(command, options, exclude) { - for (var name in options) { - if (exclude.indexOf(name) === -1) command[name] = options[name]; - } - - return command; -}; - -var mergeOptions = function(target, source) { - for (var name in source) { - target[name] = source[name]; - } - - return target; -}; - -// Merge options with translation -var translateOptions = function(target, source) { - var translations = { - // SSL translation options - sslCA: 'ca', - sslCRL: 'crl', - sslValidate: 'rejectUnauthorized', - sslKey: 'key', - sslCert: 'cert', - sslPass: 'passphrase', - // SocketTimeout translation options - socketTimeoutMS: 'socketTimeout', - connectTimeoutMS: 'connectionTimeout', - // Replicaset options - replicaSet: 'setName', - rs_name: 'setName', - secondaryAcceptableLatencyMS: 'acceptableLatency', - connectWithNoPrimary: 'secondaryOnlyConnectionAllowed', - // Mongos options - acceptableLatencyMS: 'localThresholdMS' - }; - - for (var name in source) { - if (translations[name]) { - target[translations[name]] = source[name]; - } else { - target[name] = source[name]; - } - } - - return target; -}; - -var filterOptions = function(options, names) { - var filterOptions = {}; - - for (var name in options) { - if (names.indexOf(name) !== -1) filterOptions[name] = options[name]; - } - - // Filtered options - return filterOptions; -}; - -// Write concern keys -var writeConcernKeys = ['w', 'j', 'wtimeout', 'fsync']; - -// Merge the write concern options -var mergeOptionsAndWriteConcern = function(targetOptions, sourceOptions, keys, mergeWriteConcern) { - // Mix in any allowed options - for (var i = 0; i < keys.length; i++) { - if (!targetOptions[keys[i]] && sourceOptions[keys[i]] !== undefined) { - targetOptions[keys[i]] = sourceOptions[keys[i]]; - } - } - - // No merging of write concern - if (!mergeWriteConcern) return targetOptions; - - // Found no write Concern options - var found = false; - for (i = 0; i < writeConcernKeys.length; i++) { - if (targetOptions[writeConcernKeys[i]]) { - found = true; - break; - } - } - - if (!found) { - for (i = 0; i < writeConcernKeys.length; i++) { - if (sourceOptions[writeConcernKeys[i]]) { - targetOptions[writeConcernKeys[i]] = sourceOptions[writeConcernKeys[i]]; - } - } - } - - return targetOptions; -}; - -/** - * Executes the given operation with provided arguments. - * - * This method reduces large amounts of duplication in the entire codebase by providing - * a single point for determining whether callbacks or promises should be used. Additionally - * it allows for a single point of entry to provide features such as implicit sessions, which - * are required by the Driver Sessions specification in the event that a ClientSession is - * not provided - * - * @param {object} topology The topology to execute this operation on - * @param {function} operation The operation to execute - * @param {array} args Arguments to apply the provided operation - * @param {object} [options] Options that modify the behavior of the method - */ -const executeLegacyOperation = (topology, operation, args, options) => { - if (topology == null) { - throw new TypeError('This method requires a valid topology instance'); - } - - if (!Array.isArray(args)) { - throw new TypeError('This method requires an array of arguments to apply'); - } - - options = options || {}; - const Promise = topology.s.promiseLibrary; - let callback = args[args.length - 1]; - - // The driver sessions spec mandates that we implicitly create sessions for operations - // that are not explicitly provided with a session. - let session, opOptions, owner; - if (!options.skipSessions && topology.hasSessionSupport()) { - opOptions = args[args.length - 2]; - if (opOptions == null || opOptions.session == null) { - owner = Symbol(); - session = topology.startSession({ owner }); - const optionsIndex = args.length - 2; - args[optionsIndex] = Object.assign({}, args[optionsIndex], { session: session }); - } else if (opOptions.session && opOptions.session.hasEnded) { - throw new MongoError('Use of expired sessions is not permitted'); - } - } - - const makeExecuteCallback = (resolve, reject) => - function executeCallback(err, result) { - if (session && session.owner === owner && !options.returnsCursor) { - session.endSession(() => { - delete opOptions.session; - if (err) return reject(err); - resolve(result); - }); - } else { - if (err) return reject(err); - resolve(result); - } - }; - - // Execute using callback - if (typeof callback === 'function') { - callback = args.pop(); - const handler = makeExecuteCallback( - result => callback(null, result), - err => callback(err, null) - ); - args.push(handler); - - try { - return operation.apply(null, args); - } catch (e) { - handler(e); - throw e; - } - } - - // Return a Promise - if (args[args.length - 1] != null) { - throw new TypeError('final argument to `executeLegacyOperation` must be a callback'); - } - - return new Promise(function(resolve, reject) { - const handler = makeExecuteCallback(resolve, reject); - args[args.length - 1] = handler; - - try { - return operation.apply(null, args); - } catch (e) { - handler(e); - } - }); -}; - -/** - * Applies retryWrites: true to a command if retryWrites is set on the command's database. - * - * @param {object} target The target command to which we will apply retryWrites. - * @param {object} db The database from which we can inherit a retryWrites value. - */ -function applyRetryableWrites(target, db) { - if (db && db.s.options.retryWrites) { - target.retryWrites = true; - } - - return target; -} - -/** - * Applies a write concern to a command based on well defined inheritance rules, optionally - * detecting support for the write concern in the first place. - * - * @param {Object} target the target command we will be applying the write concern to - * @param {Object} sources sources where we can inherit default write concerns from - * @param {Object} [options] optional settings passed into a command for write concern overrides - * @returns {Object} the (now) decorated target - */ -function applyWriteConcern(target, sources, options) { - options = options || {}; - const db = sources.db; - const coll = sources.collection; - - if (options.session && options.session.inTransaction()) { - // writeConcern is not allowed within a multi-statement transaction - if (target.writeConcern) { - delete target.writeConcern; - } - - return target; - } - - const writeConcern = WriteConcern.fromOptions(options); - if (writeConcern) { - return Object.assign(target, { writeConcern }); - } - - if (coll && coll.writeConcern) { - return Object.assign(target, { writeConcern: Object.assign({}, coll.writeConcern) }); - } - - if (db && db.writeConcern) { - return Object.assign(target, { writeConcern: Object.assign({}, db.writeConcern) }); - } - - return target; -} - -/** - * Resolves a read preference based on well-defined inheritance rules. This method will not only - * determine the read preference (if there is one), but will also ensure the returned value is a - * properly constructed instance of `ReadPreference`. - * - * @param {Collection|Db|MongoClient} parent The parent of the operation on which to determine the read - * preference, used for determining the inherited read preference. - * @param {Object} options The options passed into the method, potentially containing a read preference - * @returns {(ReadPreference|null)} The resolved read preference - */ -function resolveReadPreference(parent, options) { - options = options || {}; - const session = options.session; - - const inheritedReadPreference = parent.readPreference; - - let readPreference; - if (options.readPreference) { - readPreference = ReadPreference.fromOptions(options); - } else if (session && session.inTransaction() && session.transaction.options.readPreference) { - // The transaction’s read preference MUST override all other user configurable read preferences. - readPreference = session.transaction.options.readPreference; - } else if (inheritedReadPreference != null) { - readPreference = inheritedReadPreference; - } else { - throw new Error('No readPreference was provided or inherited.'); - } - - return typeof readPreference === 'string' ? new ReadPreference(readPreference) : readPreference; -} - -/** - * Checks if a given value is a Promise - * - * @param {*} maybePromise - * @return true if the provided value is a Promise - */ -function isPromiseLike(maybePromise) { - return maybePromise && typeof maybePromise.then === 'function'; -} - -/** - * Applies collation to a given command. - * - * @param {object} [command] the command on which to apply collation - * @param {(Cursor|Collection)} [target] target of command - * @param {object} [options] options containing collation settings - */ -function decorateWithCollation(command, target, options) { - const topology = (target.s && target.s.topology) || target.topology; - - if (!topology) { - throw new TypeError('parameter "target" is missing a topology'); - } - - const capabilities = topology.capabilities(); - if (options.collation && typeof options.collation === 'object') { - if (capabilities && capabilities.commandsTakeCollation) { - command.collation = options.collation; - } else { - throw new MongoError(`Current topology does not support collation`); - } - } -} - -/** - * Applies a read concern to a given command. - * - * @param {object} command the command on which to apply the read concern - * @param {Collection} coll the parent collection of the operation calling this method - */ -function decorateWithReadConcern(command, coll, options) { - if (options && options.session && options.session.inTransaction()) { - return; - } - let readConcern = Object.assign({}, command.readConcern || {}); - if (coll.s.readConcern) { - Object.assign(readConcern, coll.s.readConcern); - } - - if (Object.keys(readConcern).length > 0) { - Object.assign(command, { readConcern: readConcern }); - } -} - -const emitProcessWarning = msg => process.emitWarning(msg, 'DeprecationWarning'); -const emitConsoleWarning = msg => console.error(msg); -const emitDeprecationWarning = process.emitWarning ? emitProcessWarning : emitConsoleWarning; - -/** - * Default message handler for generating deprecation warnings. - * - * @param {string} name function name - * @param {string} option option name - * @return {string} warning message - * @ignore - * @api private - */ -function defaultMsgHandler(name, option) { - return `${name} option [${option}] is deprecated and will be removed in a later version.`; -} - -/** - * Deprecates a given function's options. - * - * @param {object} config configuration for deprecation - * @param {string} config.name function name - * @param {Array} config.deprecatedOptions options to deprecate - * @param {number} config.optionsIndex index of options object in function arguments array - * @param {function} [config.msgHandler] optional custom message handler to generate warnings - * @param {function} fn the target function of deprecation - * @return {function} modified function that warns once per deprecated option, and executes original function - * @ignore - * @api private - */ -function deprecateOptions(config, fn) { - if (process.noDeprecation === true) { - return fn; - } - - const msgHandler = config.msgHandler ? config.msgHandler : defaultMsgHandler; - - const optionsWarned = new Set(); - function deprecated() { - const options = arguments[config.optionsIndex]; - - // ensure options is a valid, non-empty object, otherwise short-circuit - if (!isObject(options) || Object.keys(options).length === 0) { - return fn.apply(this, arguments); - } - - config.deprecatedOptions.forEach(deprecatedOption => { - if (options.hasOwnProperty(deprecatedOption) && !optionsWarned.has(deprecatedOption)) { - optionsWarned.add(deprecatedOption); - const msg = msgHandler(config.name, deprecatedOption); - emitDeprecationWarning(msg); - if (this && this.getLogger) { - const logger = this.getLogger(); - if (logger) { - logger.warn(msg); - } - } - } - }); - - return fn.apply(this, arguments); - } - - // These lines copied from https://github.com/nodejs/node/blob/25e5ae41688676a5fd29b2e2e7602168eee4ceb5/lib/internal/util.js#L73-L80 - // The wrapper will keep the same prototype as fn to maintain prototype chain - Object.setPrototypeOf(deprecated, fn); - if (fn.prototype) { - // Setting this (rather than using Object.setPrototype, as above) ensures - // that calling the unwrapped constructor gives an instanceof the wrapped - // constructor. - deprecated.prototype = fn.prototype; - } - - return deprecated; -} - -const SUPPORTS = {}; -// Test asyncIterator support -try { - require('./async/async_iterator'); - SUPPORTS.ASYNC_ITERATOR = true; -} catch (e) { - SUPPORTS.ASYNC_ITERATOR = false; -} - -class MongoDBNamespace { - constructor(db, collection) { - this.db = db; - this.collection = collection; - } - - toString() { - return this.collection ? `${this.db}.${this.collection}` : this.db; - } - - withCollection(collection) { - return new MongoDBNamespace(this.db, collection); - } - - static fromString(namespace) { - if (!namespace) { - throw new Error(`Cannot parse namespace from "${namespace}"`); - } - - const index = namespace.indexOf('.'); - return new MongoDBNamespace(namespace.substring(0, index), namespace.substring(index + 1)); - } -} - -module.exports = { - filterOptions, - mergeOptions, - translateOptions, - shallowClone, - getSingleProperty, - checkCollectionName, - toError, - formattedOrderClause, - parseIndexOptions, - normalizeHintField, - handleCallback, - decorateCommand, - isObject, - debugOptions, - MAX_JS_INT: Number.MAX_SAFE_INTEGER + 1, - mergeOptionsAndWriteConcern, - translateReadPreference, - executeLegacyOperation, - applyRetryableWrites, - applyWriteConcern, - isPromiseLike, - decorateWithCollation, - decorateWithReadConcern, - deprecateOptions, - SUPPORTS, - MongoDBNamespace, - resolveReadPreference -}; diff --git a/scripts/node_modules/mongodb/lib/write_concern.js b/scripts/node_modules/mongodb/lib/write_concern.js deleted file mode 100644 index 79b0f092..00000000 --- a/scripts/node_modules/mongodb/lib/write_concern.js +++ /dev/null @@ -1,66 +0,0 @@ -'use strict'; - -/** - * The **WriteConcern** class is a class that represents a MongoDB WriteConcern. - * @class - * @property {(number|string)} w The write concern - * @property {number} wtimeout The write concern timeout - * @property {boolean} j The journal write concern - * @property {boolean} fsync The file sync write concern - * @see https://docs.mongodb.com/manual/reference/write-concern/index.html - */ -class WriteConcern { - /** - * Constructs a WriteConcern from the write concern properties. - * @param {(number|string)} [w] The write concern - * @param {number} [wtimeout] The write concern timeout - * @param {boolean} [j] The journal write concern - * @param {boolean} [fsync] The file sync write concern - */ - constructor(w, wtimeout, j, fsync) { - if (w != null) { - this.w = w; - } - if (wtimeout != null) { - this.wtimeout = wtimeout; - } - if (j != null) { - this.j = j; - } - if (fsync != null) { - this.fsync = fsync; - } - } - - /** - * Construct a WriteConcern given an options object. - * - * @param {object} options The options object from which to extract the write concern. - * @return {WriteConcern} - */ - static fromOptions(options) { - if ( - options == null || - (options.writeConcern == null && - options.w == null && - options.wtimeout == null && - options.j == null && - options.fsync == null) - ) { - return; - } - - if (options.writeConcern) { - return new WriteConcern( - options.writeConcern.w, - options.writeConcern.wtimeout, - options.writeConcern.j, - options.writeConcern.fsync - ); - } - - return new WriteConcern(options.w, options.wtimeout, options.j, options.fsync); - } -} - -module.exports = WriteConcern; diff --git a/scripts/node_modules/mongodb/package.json b/scripts/node_modules/mongodb/package.json deleted file mode 100644 index ad87330b..00000000 --- a/scripts/node_modules/mongodb/package.json +++ /dev/null @@ -1,104 +0,0 @@ -{ - "_from": "mongodb", - "_id": "mongodb@3.3.3", - "_inBundle": false, - "_integrity": "sha512-MdRnoOjstmnrKJsK8PY0PjP6fyF/SBS4R8coxmhsfEU7tQ46/J6j+aSHF2n4c2/H8B+Hc/Klbfp8vggZfI0mmA==", - "_location": "/mongodb", - "_phantomChildren": {}, - "_requested": { - "type": "tag", - "registry": true, - "raw": "mongodb", - "name": "mongodb", - "escapedName": "mongodb", - "rawSpec": "", - "saveSpec": null, - "fetchSpec": "latest" - }, - "_requiredBy": [ - "#USER", - "/" - ], - "_resolved": "https://registry.npmjs.org/mongodb/-/mongodb-3.3.3.tgz", - "_shasum": "509cad2225a1c56c65a331ed73a0d5d4ed5cbe67", - "_spec": "mongodb", - "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/2.5", - "bugs": { - "url": "https://github.com/mongodb/node-mongodb-native/issues" - }, - "bundleDependencies": false, - "dependencies": { - "bson": "^1.1.1", - "require_optional": "^1.0.1", - "safe-buffer": "^5.1.2", - "saslprep": "^1.0.0" - }, - "deprecated": false, - "description": "The official MongoDB driver for Node.js", - "devDependencies": { - "bluebird": "3.5.0", - "chai": "^4.1.1", - "chai-subset": "^1.6.0", - "chalk": "^2.4.2", - "co": "4.6.0", - "coveralls": "^2.11.6", - "eslint": "^4.5.0", - "eslint-plugin-prettier": "^2.2.0", - "istanbul": "^0.4.5", - "jsdoc": "3.5.5", - "lodash.camelcase": "^4.3.0", - "mocha": "5.2.0", - "mocha-sinon": "^2.1.0", - "mongodb-extjson": "^2.1.1", - "mongodb-mock-server": "^1.0.1", - "prettier": "~1.12.0", - "semver": "^5.5.0", - "sinon": "^4.3.0", - "sinon-chai": "^3.2.0", - "snappy": "^6.1.2", - "standard-version": "^4.4.0", - "worker-farm": "^1.5.0", - "wtfnode": "^0.8.0" - }, - "engines": { - "node": ">=4" - }, - "files": [ - "index.js", - "lib" - ], - "homepage": "https://github.com/mongodb/node-mongodb-native", - "keywords": [ - "mongodb", - "driver", - "official" - ], - "license": "Apache-2.0", - "main": "index.js", - "name": "mongodb", - "optionalDependencies": { - "saslprep": "^1.0.0" - }, - "peerOptionalDependencies": { - "kerberos": "^1.1.0", - "mongodb-client-encryption": "^1.0.0", - "mongodb-extjson": "^2.1.2", - "snappy": "^6.1.1", - "bson-ext": "^2.0.0" - }, - "repository": { - "type": "git", - "url": "git+ssh://git@github.com/mongodb/node-mongodb-native.git" - }, - "scripts": { - "atlas": "node ./test/atlas_connectivity_tests.js", - "bench": "node test/driverBench/", - "coverage": "istanbul cover mongodb-test-runner -- -t 60000 test/core test/unit test/functional", - "format": "prettier --print-width 100 --tab-width 2 --single-quote --write 'test/**/*.js' 'lib/**/*.js'", - "generate-evergreen": "node .evergreen/generate_evergreen_tasks.js", - "lint": "eslint lib test", - "release": "standard-version -i HISTORY.md", - "test": "npm run lint && mocha --recursive test/functional test/unit test/core" - }, - "version": "3.3.3" -} diff --git a/scripts/node_modules/require_optional/.npmignore b/scripts/node_modules/require_optional/.npmignore deleted file mode 100644 index e920c167..00000000 --- a/scripts/node_modules/require_optional/.npmignore +++ /dev/null @@ -1,33 +0,0 @@ -# Logs -logs -*.log -npm-debug.log* - -# Runtime data -pids -*.pid -*.seed - -# Directory for instrumented libs generated by jscoverage/JSCover -lib-cov - -# Coverage directory used by tools like istanbul -coverage - -# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) -.grunt - -# node-waf configuration -.lock-wscript - -# Compiled binary addons (http://nodejs.org/api/addons.html) -build/Release - -# Dependency directory -node_modules - -# Optional npm cache directory -.npm - -# Optional REPL history -.node_repl_history diff --git a/scripts/node_modules/require_optional/.travis.yml b/scripts/node_modules/require_optional/.travis.yml deleted file mode 100644 index 72903c34..00000000 --- a/scripts/node_modules/require_optional/.travis.yml +++ /dev/null @@ -1,9 +0,0 @@ -language: node_js -node_js: - - "0.10" - - "0.12" - - "4" - - "6" - - "7" - - "8" -sudo: false diff --git a/scripts/node_modules/require_optional/HISTORY.md b/scripts/node_modules/require_optional/HISTORY.md deleted file mode 100644 index 7bee02fc..00000000 --- a/scripts/node_modules/require_optional/HISTORY.md +++ /dev/null @@ -1,7 +0,0 @@ -1.0.1 03-02-2016 -================ -* Fix dependency resolution issue when a component in peerOptionalDependencies is installed at the level of the module declaring in peerOptionalDependencies. - -1.0.0 03-02-2016 -================ -* Initial release allowing us to optionally resolve dependencies in the package.json file under the peerOptionalDependencies tag. \ No newline at end of file diff --git a/scripts/node_modules/require_optional/LICENSE b/scripts/node_modules/require_optional/LICENSE deleted file mode 100644 index 8dada3ed..00000000 --- a/scripts/node_modules/require_optional/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "{}" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright {yyyy} {name of copyright owner} - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/scripts/node_modules/require_optional/README.md b/scripts/node_modules/require_optional/README.md deleted file mode 100644 index c0323f06..00000000 --- a/scripts/node_modules/require_optional/README.md +++ /dev/null @@ -1,2 +0,0 @@ -# require_optional -Work around the problem that we do not have a optionalPeerDependencies concept in node.js making it a hassle to optionally include native modules diff --git a/scripts/node_modules/require_optional/index.js b/scripts/node_modules/require_optional/index.js deleted file mode 100644 index 3710319f..00000000 --- a/scripts/node_modules/require_optional/index.js +++ /dev/null @@ -1,128 +0,0 @@ -var path = require('path'), - fs = require('fs'), - f = require('util').format, - resolveFrom = require('resolve-from'), - semver = require('semver'); - -var exists = fs.existsSync || path.existsSync; - -// Find the location of a package.json file near or above the given location -var find_package_json = function(location) { - var found = false; - - while(!found) { - if (exists(location + '/package.json')) { - found = location; - } else if (location !== '/') { - location = path.dirname(location); - } else { - return false; - } - } - - return location; -} - -// Find the package.json object of the module closest up the module call tree that contains name in that module's peerOptionalDependencies -var find_package_json_with_name = function(name) { - // Walk up the module call tree until we find a module containing name in its peerOptionalDependencies - var currentModule = module; - var found = false; - while (currentModule) { - // Check currentModule has a package.json - location = currentModule.filename; - var location = find_package_json(location) - if (!location) { - currentModule = currentModule.parent; - continue; - } - - // Read the package.json file - var object = JSON.parse(fs.readFileSync(f('%s/package.json', location))); - // Is the name defined by interal file references - var parts = name.split(/\//); - - // Check whether this package.json contains peerOptionalDependencies containing the name we're searching for - if (!object.peerOptionalDependencies || (object.peerOptionalDependencies && !object.peerOptionalDependencies[parts[0]])) { - currentModule = currentModule.parent; - continue; - } - found = true; - break; - } - - // Check whether name has been found in currentModule's peerOptionalDependencies - if (!found) { - throw new Error(f('no optional dependency [%s] defined in peerOptionalDependencies in any package.json', parts[0])); - } - - return { - object: object, - parts: parts - } -} - -var require_optional = function(name, options) { - options = options || {}; - options.strict = typeof options.strict == 'boolean' ? options.strict : true; - - var res = find_package_json_with_name(name) - var object = res.object; - var parts = res.parts; - - // Unpack the expected version - var expectedVersions = object.peerOptionalDependencies[parts[0]]; - // The resolved package - var moduleEntry = undefined; - // Module file - var moduleEntryFile = name; - - try { - // Validate if it's possible to read the module - moduleEntry = require(moduleEntryFile); - } catch(err) { - // Attempt to resolve in top level package - try { - // Get the module entry file - moduleEntryFile = resolveFrom(process.cwd(), name); - if(moduleEntryFile == null) return undefined; - // Attempt to resolve the module - moduleEntry = require(moduleEntryFile); - } catch(err) { - if(err.code === 'MODULE_NOT_FOUND') return undefined; - } - } - - // Resolve the location of the module's package.json file - var location = find_package_json(require.resolve(moduleEntryFile)); - if(!location) { - throw new Error('package.json can not be located'); - } - - // Read the module file - var dependentOnModule = JSON.parse(fs.readFileSync(f('%s/package.json', location))); - // Get the version - var version = dependentOnModule.version; - // Validate if the found module satisfies the version id - if(semver.satisfies(version, expectedVersions) == false - && options.strict) { - var error = new Error(f('optional dependency [%s] found but version [%s] did not satisfy constraint [%s]', parts[0], version, expectedVersions)); - error.code = 'OPTIONAL_MODULE_NOT_FOUND'; - throw error; - } - - // Satifies the module requirement - return moduleEntry; -} - -require_optional.exists = function(name) { - try { - var m = require_optional(name); - if(m === undefined) return false; - return true; - } catch(err) { - return false; - } -} - -module.exports = require_optional; diff --git a/scripts/node_modules/require_optional/package.json b/scripts/node_modules/require_optional/package.json deleted file mode 100644 index 138364fe..00000000 --- a/scripts/node_modules/require_optional/package.json +++ /dev/null @@ -1,67 +0,0 @@ -{ - "_from": "require_optional@^1.0.1", - "_id": "require_optional@1.0.1", - "_inBundle": false, - "_integrity": "sha512-qhM/y57enGWHAe3v/NcwML6a3/vfESLe/sGM2dII+gEO0BpKRUkWZow/tyloNqJyN6kXSl3RyyM8Ll5D/sJP8g==", - "_location": "/require_optional", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "require_optional@^1.0.1", - "name": "require_optional", - "escapedName": "require_optional", - "rawSpec": "^1.0.1", - "saveSpec": null, - "fetchSpec": "^1.0.1" - }, - "_requiredBy": [ - "/mongodb" - ], - "_resolved": "https://registry.npmjs.org/require_optional/-/require_optional-1.0.1.tgz", - "_shasum": "4cf35a4247f64ca3df8c2ef208cc494b1ca8fc2e", - "_spec": "require_optional@^1.0.1", - "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/node_modules/mongodb", - "author": { - "name": "Christian Kvalheim Amor" - }, - "bugs": { - "url": "https://github.com/christkv/require_optional/issues" - }, - "bundleDependencies": false, - "dependencies": { - "resolve-from": "^2.0.0", - "semver": "^5.1.0" - }, - "deprecated": false, - "description": "Allows you declare optionalPeerDependencies that can be satisfied by the top level module but ignored if they are not.", - "devDependencies": { - "bson": "0.4.21", - "co": "4.6.0", - "es6-promise": "^3.0.2", - "mocha": "^2.4.5" - }, - "homepage": "https://github.com/christkv/require_optional", - "keywords": [ - "optional", - "require", - "optionalPeerDependencies" - ], - "license": "Apache-2.0", - "main": "index.js", - "name": "require_optional", - "peerOptionalDependencies": { - "co": ">=5.6.0", - "es6-promise": "^3.0.2", - "es6-promise2": "^4.0.2", - "bson": "0.4.21" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/christkv/require_optional.git" - }, - "scripts": { - "test": "mocha" - }, - "version": "1.0.1" -} diff --git a/scripts/node_modules/require_optional/test/nestedTest/index.js b/scripts/node_modules/require_optional/test/nestedTest/index.js deleted file mode 100644 index 76de2ab4..00000000 --- a/scripts/node_modules/require_optional/test/nestedTest/index.js +++ /dev/null @@ -1,8 +0,0 @@ -var require_optional = require('../../') - -function findPackage(packageName) { - var pkg = require_optional(packageName); - return pkg; -} - -module.exports.findPackage = findPackage diff --git a/scripts/node_modules/require_optional/test/nestedTest/package.json b/scripts/node_modules/require_optional/test/nestedTest/package.json deleted file mode 100644 index 4c456a6b..00000000 --- a/scripts/node_modules/require_optional/test/nestedTest/package.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "name": "nestedtest", - "version": "1.0.0", - "description": "A dummy package that facilitates testing that require_optional correctly walks up the module call stack", - "main": "index.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "author": "Sebastian Hallum Clarke", - "license": "ISC" -} diff --git a/scripts/node_modules/require_optional/test/require_optional_tests.js b/scripts/node_modules/require_optional/test/require_optional_tests.js deleted file mode 100644 index c9cc2a36..00000000 --- a/scripts/node_modules/require_optional/test/require_optional_tests.js +++ /dev/null @@ -1,59 +0,0 @@ -var assert = require('assert'), - require_optional = require('../'), - nestedTest = require('./nestedTest'); - -describe('Require Optional', function() { - describe('top level require', function() { - it('should correctly require co library', function() { - var promise = require_optional('es6-promise'); - assert.ok(promise); - }); - - it('should fail to require es6-promise library', function() { - try { - require_optional('co'); - } catch(e) { - assert.equal('OPTIONAL_MODULE_NOT_FOUND', e.code); - return; - } - - assert.ok(false); - }); - - it('should ignore optional library not defined', function() { - assert.equal(undefined, require_optional('es6-promise2')); - }); - }); - - describe('internal module file require', function() { - it('should correctly require co library', function() { - var Long = require_optional('bson/lib/bson/long.js'); - assert.ok(Long); - }); - }); - - describe('top level resolve', function() { - it('should correctly use exists method', function() { - assert.equal(false, require_optional.exists('co')); - assert.equal(true, require_optional.exists('es6-promise')); - assert.equal(true, require_optional.exists('bson/lib/bson/long.js')); - assert.equal(false, require_optional.exists('es6-promise2')); - }); - }); - - describe('require_optional inside dependencies', function() { - it('should correctly walk up module call stack searching for peerOptionalDependencies', function() { - assert.ok(nestedTest.findPackage('bson')) - }); - it('should return null when a package is defined in top-level package.json but not installed', function() { - assert.equal(null, nestedTest.findPackage('es6-promise2')) - }); - it('should error when searching for an optional dependency that is not defined in any ancestor package.json', function() { - try { - nestedTest.findPackage('bison') - } catch (err) { - assert.equal(err.message, 'no optional dependency [bison] defined in peerOptionalDependencies in any package.json') - } - }) - }); -}); diff --git a/scripts/node_modules/resolve-from/index.js b/scripts/node_modules/resolve-from/index.js deleted file mode 100644 index 434159f1..00000000 --- a/scripts/node_modules/resolve-from/index.js +++ /dev/null @@ -1,23 +0,0 @@ -'use strict'; -var path = require('path'); -var Module = require('module'); - -module.exports = function (fromDir, moduleId) { - if (typeof fromDir !== 'string' || typeof moduleId !== 'string') { - throw new TypeError('Expected `fromDir` and `moduleId` to be a string'); - } - - fromDir = path.resolve(fromDir); - - var fromFile = path.join(fromDir, 'noop.js'); - - try { - return Module._resolveFilename(moduleId, { - id: fromFile, - filename: fromFile, - paths: Module._nodeModulePaths(fromDir) - }); - } catch (err) { - return null; - } -}; diff --git a/scripts/node_modules/resolve-from/license b/scripts/node_modules/resolve-from/license deleted file mode 100644 index 654d0bfe..00000000 --- a/scripts/node_modules/resolve-from/license +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) Sindre Sorhus (sindresorhus.com) - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/scripts/node_modules/resolve-from/package.json b/scripts/node_modules/resolve-from/package.json deleted file mode 100644 index 4484dd56..00000000 --- a/scripts/node_modules/resolve-from/package.json +++ /dev/null @@ -1,66 +0,0 @@ -{ - "_from": "resolve-from@^2.0.0", - "_id": "resolve-from@2.0.0", - "_inBundle": false, - "_integrity": "sha1-lICrIOlP+h2egKgEx+oUdhGWa1c=", - "_location": "/resolve-from", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "resolve-from@^2.0.0", - "name": "resolve-from", - "escapedName": "resolve-from", - "rawSpec": "^2.0.0", - "saveSpec": null, - "fetchSpec": "^2.0.0" - }, - "_requiredBy": [ - "/require_optional" - ], - "_resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-2.0.0.tgz", - "_shasum": "9480ab20e94ffa1d9e80a804c7ea147611966b57", - "_spec": "resolve-from@^2.0.0", - "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/node_modules/require_optional", - "author": { - "name": "Sindre Sorhus", - "email": "sindresorhus@gmail.com", - "url": "sindresorhus.com" - }, - "bugs": { - "url": "https://github.com/sindresorhus/resolve-from/issues" - }, - "bundleDependencies": false, - "deprecated": false, - "description": "Resolve the path of a module like require.resolve() but from a given path", - "devDependencies": { - "ava": "*", - "xo": "*" - }, - "engines": { - "node": ">=0.10.0" - }, - "files": [ - "index.js" - ], - "homepage": "https://github.com/sindresorhus/resolve-from#readme", - "keywords": [ - "require", - "resolve", - "path", - "module", - "from", - "like", - "path" - ], - "license": "MIT", - "name": "resolve-from", - "repository": { - "type": "git", - "url": "git+https://github.com/sindresorhus/resolve-from.git" - }, - "scripts": { - "test": "xo && ava" - }, - "version": "2.0.0" -} diff --git a/scripts/node_modules/resolve-from/readme.md b/scripts/node_modules/resolve-from/readme.md deleted file mode 100644 index bb4ca91e..00000000 --- a/scripts/node_modules/resolve-from/readme.md +++ /dev/null @@ -1,58 +0,0 @@ -# resolve-from [![Build Status](https://travis-ci.org/sindresorhus/resolve-from.svg?branch=master)](https://travis-ci.org/sindresorhus/resolve-from) - -> Resolve the path of a module like [`require.resolve()`](http://nodejs.org/api/globals.html#globals_require_resolve) but from a given path - -Unlike `require.resolve()` it returns `null` instead of throwing when the module can't be found. - - -## Install - -``` -$ npm install --save resolve-from -``` - - -## Usage - -```js -const resolveFrom = require('resolve-from'); - -// there's a file at `./foo/bar.js` - -resolveFrom('foo', './bar'); -//=> '/Users/sindresorhus/dev/test/foo/bar.js' -``` - - -## API - -### resolveFrom(fromDir, moduleId) - -#### fromDir - -Type: `string` - -Directory to resolve from. - -#### moduleId - -Type: `string` - -What you would use in `require()`. - - -## Tip - -Create a partial using a bound function if you want to require from the same `fromDir` multiple times: - -```js -const resolveFromFoo = resolveFrom.bind(null, 'foo'); - -resolveFromFoo('./bar'); -resolveFromFoo('./baz'); -``` - - -## License - -MIT © [Sindre Sorhus](http://sindresorhus.com) diff --git a/scripts/node_modules/safe-buffer/LICENSE b/scripts/node_modules/safe-buffer/LICENSE deleted file mode 100644 index 0c068cee..00000000 --- a/scripts/node_modules/safe-buffer/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) Feross Aboukhadijeh - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/scripts/node_modules/safe-buffer/README.md b/scripts/node_modules/safe-buffer/README.md deleted file mode 100644 index 356e3519..00000000 --- a/scripts/node_modules/safe-buffer/README.md +++ /dev/null @@ -1,586 +0,0 @@ -# safe-buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] - -[travis-image]: https://img.shields.io/travis/feross/safe-buffer/master.svg -[travis-url]: https://travis-ci.org/feross/safe-buffer -[npm-image]: https://img.shields.io/npm/v/safe-buffer.svg -[npm-url]: https://npmjs.org/package/safe-buffer -[downloads-image]: https://img.shields.io/npm/dm/safe-buffer.svg -[downloads-url]: https://npmjs.org/package/safe-buffer -[standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg -[standard-url]: https://standardjs.com - -#### Safer Node.js Buffer API - -**Use the new Node.js Buffer APIs (`Buffer.from`, `Buffer.alloc`, -`Buffer.allocUnsafe`, `Buffer.allocUnsafeSlow`) in all versions of Node.js.** - -**Uses the built-in implementation when available.** - -## install - -``` -npm install safe-buffer -``` - -[Get supported safe-buffer with the Tidelift Subscription](https://tidelift.com/subscription/pkg/npm-safe-buffer?utm_source=npm-safe-buffer&utm_medium=referral&utm_campaign=readme) - -## usage - -The goal of this package is to provide a safe replacement for the node.js `Buffer`. - -It's a drop-in replacement for `Buffer`. You can use it by adding one `require` line to -the top of your node.js modules: - -```js -var Buffer = require('safe-buffer').Buffer - -// Existing buffer code will continue to work without issues: - -new Buffer('hey', 'utf8') -new Buffer([1, 2, 3], 'utf8') -new Buffer(obj) -new Buffer(16) // create an uninitialized buffer (potentially unsafe) - -// But you can use these new explicit APIs to make clear what you want: - -Buffer.from('hey', 'utf8') // convert from many types to a Buffer -Buffer.alloc(16) // create a zero-filled buffer (safe) -Buffer.allocUnsafe(16) // create an uninitialized buffer (potentially unsafe) -``` - -## api - -### Class Method: Buffer.from(array) - - -* `array` {Array} - -Allocates a new `Buffer` using an `array` of octets. - -```js -const buf = Buffer.from([0x62,0x75,0x66,0x66,0x65,0x72]); - // creates a new Buffer containing ASCII bytes - // ['b','u','f','f','e','r'] -``` - -A `TypeError` will be thrown if `array` is not an `Array`. - -### Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]]) - - -* `arrayBuffer` {ArrayBuffer} The `.buffer` property of a `TypedArray` or - a `new ArrayBuffer()` -* `byteOffset` {Number} Default: `0` -* `length` {Number} Default: `arrayBuffer.length - byteOffset` - -When passed a reference to the `.buffer` property of a `TypedArray` instance, -the newly created `Buffer` will share the same allocated memory as the -TypedArray. - -```js -const arr = new Uint16Array(2); -arr[0] = 5000; -arr[1] = 4000; - -const buf = Buffer.from(arr.buffer); // shares the memory with arr; - -console.log(buf); - // Prints: - -// changing the TypedArray changes the Buffer also -arr[1] = 6000; - -console.log(buf); - // Prints: -``` - -The optional `byteOffset` and `length` arguments specify a memory range within -the `arrayBuffer` that will be shared by the `Buffer`. - -```js -const ab = new ArrayBuffer(10); -const buf = Buffer.from(ab, 0, 2); -console.log(buf.length); - // Prints: 2 -``` - -A `TypeError` will be thrown if `arrayBuffer` is not an `ArrayBuffer`. - -### Class Method: Buffer.from(buffer) - - -* `buffer` {Buffer} - -Copies the passed `buffer` data onto a new `Buffer` instance. - -```js -const buf1 = Buffer.from('buffer'); -const buf2 = Buffer.from(buf1); - -buf1[0] = 0x61; -console.log(buf1.toString()); - // 'auffer' -console.log(buf2.toString()); - // 'buffer' (copy is not changed) -``` - -A `TypeError` will be thrown if `buffer` is not a `Buffer`. - -### Class Method: Buffer.from(str[, encoding]) - - -* `str` {String} String to encode. -* `encoding` {String} Encoding to use, Default: `'utf8'` - -Creates a new `Buffer` containing the given JavaScript string `str`. If -provided, the `encoding` parameter identifies the character encoding. -If not provided, `encoding` defaults to `'utf8'`. - -```js -const buf1 = Buffer.from('this is a tést'); -console.log(buf1.toString()); - // prints: this is a tést -console.log(buf1.toString('ascii')); - // prints: this is a tC)st - -const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex'); -console.log(buf2.toString()); - // prints: this is a tést -``` - -A `TypeError` will be thrown if `str` is not a string. - -### Class Method: Buffer.alloc(size[, fill[, encoding]]) - - -* `size` {Number} -* `fill` {Value} Default: `undefined` -* `encoding` {String} Default: `utf8` - -Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the -`Buffer` will be *zero-filled*. - -```js -const buf = Buffer.alloc(5); -console.log(buf); - // -``` - -The `size` must be less than or equal to the value of -`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is -`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will -be created if a `size` less than or equal to 0 is specified. - -If `fill` is specified, the allocated `Buffer` will be initialized by calling -`buf.fill(fill)`. See [`buf.fill()`][] for more information. - -```js -const buf = Buffer.alloc(5, 'a'); -console.log(buf); - // -``` - -If both `fill` and `encoding` are specified, the allocated `Buffer` will be -initialized by calling `buf.fill(fill, encoding)`. For example: - -```js -const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); -console.log(buf); - // -``` - -Calling `Buffer.alloc(size)` can be significantly slower than the alternative -`Buffer.allocUnsafe(size)` but ensures that the newly created `Buffer` instance -contents will *never contain sensitive data*. - -A `TypeError` will be thrown if `size` is not a number. - -### Class Method: Buffer.allocUnsafe(size) - - -* `size` {Number} - -Allocates a new *non-zero-filled* `Buffer` of `size` bytes. The `size` must -be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit -architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is -thrown. A zero-length Buffer will be created if a `size` less than or equal to -0 is specified. - -The underlying memory for `Buffer` instances created in this way is *not -initialized*. The contents of the newly created `Buffer` are unknown and -*may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such -`Buffer` instances to zeroes. - -```js -const buf = Buffer.allocUnsafe(5); -console.log(buf); - // - // (octets will be different, every time) -buf.fill(0); -console.log(buf); - // -``` - -A `TypeError` will be thrown if `size` is not a number. - -Note that the `Buffer` module pre-allocates an internal `Buffer` instance of -size `Buffer.poolSize` that is used as a pool for the fast allocation of new -`Buffer` instances created using `Buffer.allocUnsafe(size)` (and the deprecated -`new Buffer(size)` constructor) only when `size` is less than or equal to -`Buffer.poolSize >> 1` (floor of `Buffer.poolSize` divided by two). The default -value of `Buffer.poolSize` is `8192` but can be modified. - -Use of this pre-allocated internal memory pool is a key difference between -calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`. -Specifically, `Buffer.alloc(size, fill)` will *never* use the internal Buffer -pool, while `Buffer.allocUnsafe(size).fill(fill)` *will* use the internal -Buffer pool if `size` is less than or equal to half `Buffer.poolSize`. The -difference is subtle but can be important when an application requires the -additional performance that `Buffer.allocUnsafe(size)` provides. - -### Class Method: Buffer.allocUnsafeSlow(size) - - -* `size` {Number} - -Allocates a new *non-zero-filled* and non-pooled `Buffer` of `size` bytes. The -`size` must be less than or equal to the value of -`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is -`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will -be created if a `size` less than or equal to 0 is specified. - -The underlying memory for `Buffer` instances created in this way is *not -initialized*. The contents of the newly created `Buffer` are unknown and -*may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such -`Buffer` instances to zeroes. - -When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances, -allocations under 4KB are, by default, sliced from a single pre-allocated -`Buffer`. This allows applications to avoid the garbage collection overhead of -creating many individually allocated Buffers. This approach improves both -performance and memory usage by eliminating the need to track and cleanup as -many `Persistent` objects. - -However, in the case where a developer may need to retain a small chunk of -memory from a pool for an indeterminate amount of time, it may be appropriate -to create an un-pooled Buffer instance using `Buffer.allocUnsafeSlow()` then -copy out the relevant bits. - -```js -// need to keep around a few small chunks of memory -const store = []; - -socket.on('readable', () => { - const data = socket.read(); - // allocate for retained data - const sb = Buffer.allocUnsafeSlow(10); - // copy the data into the new allocation - data.copy(sb, 0, 0, 10); - store.push(sb); -}); -``` - -Use of `Buffer.allocUnsafeSlow()` should be used only as a last resort *after* -a developer has observed undue memory retention in their applications. - -A `TypeError` will be thrown if `size` is not a number. - -### All the Rest - -The rest of the `Buffer` API is exactly the same as in node.js. -[See the docs](https://nodejs.org/api/buffer.html). - - -## Related links - -- [Node.js issue: Buffer(number) is unsafe](https://github.com/nodejs/node/issues/4660) -- [Node.js Enhancement Proposal: Buffer.from/Buffer.alloc/Buffer.zalloc/Buffer() soft-deprecate](https://github.com/nodejs/node-eps/pull/4) - -## Why is `Buffer` unsafe? - -Today, the node.js `Buffer` constructor is overloaded to handle many different argument -types like `String`, `Array`, `Object`, `TypedArrayView` (`Uint8Array`, etc.), -`ArrayBuffer`, and also `Number`. - -The API is optimized for convenience: you can throw any type at it, and it will try to do -what you want. - -Because the Buffer constructor is so powerful, you often see code like this: - -```js -// Convert UTF-8 strings to hex -function toHex (str) { - return new Buffer(str).toString('hex') -} -``` - -***But what happens if `toHex` is called with a `Number` argument?*** - -### Remote Memory Disclosure - -If an attacker can make your program call the `Buffer` constructor with a `Number` -argument, then they can make it allocate uninitialized memory from the node.js process. -This could potentially disclose TLS private keys, user data, or database passwords. - -When the `Buffer` constructor is passed a `Number` argument, it returns an -**UNINITIALIZED** block of memory of the specified `size`. When you create a `Buffer` like -this, you **MUST** overwrite the contents before returning it to the user. - -From the [node.js docs](https://nodejs.org/api/buffer.html#buffer_new_buffer_size): - -> `new Buffer(size)` -> -> - `size` Number -> -> The underlying memory for `Buffer` instances created in this way is not initialized. -> **The contents of a newly created `Buffer` are unknown and could contain sensitive -> data.** Use `buf.fill(0)` to initialize a Buffer to zeroes. - -(Emphasis our own.) - -Whenever the programmer intended to create an uninitialized `Buffer` you often see code -like this: - -```js -var buf = new Buffer(16) - -// Immediately overwrite the uninitialized buffer with data from another buffer -for (var i = 0; i < buf.length; i++) { - buf[i] = otherBuf[i] -} -``` - - -### Would this ever be a problem in real code? - -Yes. It's surprisingly common to forget to check the type of your variables in a -dynamically-typed language like JavaScript. - -Usually the consequences of assuming the wrong type is that your program crashes with an -uncaught exception. But the failure mode for forgetting to check the type of arguments to -the `Buffer` constructor is more catastrophic. - -Here's an example of a vulnerable service that takes a JSON payload and converts it to -hex: - -```js -// Take a JSON payload {str: "some string"} and convert it to hex -var server = http.createServer(function (req, res) { - var data = '' - req.setEncoding('utf8') - req.on('data', function (chunk) { - data += chunk - }) - req.on('end', function () { - var body = JSON.parse(data) - res.end(new Buffer(body.str).toString('hex')) - }) -}) - -server.listen(8080) -``` - -In this example, an http client just has to send: - -```json -{ - "str": 1000 -} -``` - -and it will get back 1,000 bytes of uninitialized memory from the server. - -This is a very serious bug. It's similar in severity to the -[the Heartbleed bug](http://heartbleed.com/) that allowed disclosure of OpenSSL process -memory by remote attackers. - - -### Which real-world packages were vulnerable? - -#### [`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht) - -[Mathias Buus](https://github.com/mafintosh) and I -([Feross Aboukhadijeh](http://feross.org/)) found this issue in one of our own packages, -[`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht). The bug would allow -anyone on the internet to send a series of messages to a user of `bittorrent-dht` and get -them to reveal 20 bytes at a time of uninitialized memory from the node.js process. - -Here's -[the commit](https://github.com/feross/bittorrent-dht/commit/6c7da04025d5633699800a99ec3fbadf70ad35b8) -that fixed it. We released a new fixed version, created a -[Node Security Project disclosure](https://nodesecurity.io/advisories/68), and deprecated all -vulnerable versions on npm so users will get a warning to upgrade to a newer version. - -#### [`ws`](https://www.npmjs.com/package/ws) - -That got us wondering if there were other vulnerable packages. Sure enough, within a short -period of time, we found the same issue in [`ws`](https://www.npmjs.com/package/ws), the -most popular WebSocket implementation in node.js. - -If certain APIs were called with `Number` parameters instead of `String` or `Buffer` as -expected, then uninitialized server memory would be disclosed to the remote peer. - -These were the vulnerable methods: - -```js -socket.send(number) -socket.ping(number) -socket.pong(number) -``` - -Here's a vulnerable socket server with some echo functionality: - -```js -server.on('connection', function (socket) { - socket.on('message', function (message) { - message = JSON.parse(message) - if (message.type === 'echo') { - socket.send(message.data) // send back the user's message - } - }) -}) -``` - -`socket.send(number)` called on the server, will disclose server memory. - -Here's [the release](https://github.com/websockets/ws/releases/tag/1.0.1) where the issue -was fixed, with a more detailed explanation. Props to -[Arnout Kazemier](https://github.com/3rd-Eden) for the quick fix. Here's the -[Node Security Project disclosure](https://nodesecurity.io/advisories/67). - - -### What's the solution? - -It's important that node.js offers a fast way to get memory otherwise performance-critical -applications would needlessly get a lot slower. - -But we need a better way to *signal our intent* as programmers. **When we want -uninitialized memory, we should request it explicitly.** - -Sensitive functionality should not be packed into a developer-friendly API that loosely -accepts many different types. This type of API encourages the lazy practice of passing -variables in without checking the type very carefully. - -#### A new API: `Buffer.allocUnsafe(number)` - -The functionality of creating buffers with uninitialized memory should be part of another -API. We propose `Buffer.allocUnsafe(number)`. This way, it's not part of an API that -frequently gets user input of all sorts of different types passed into it. - -```js -var buf = Buffer.allocUnsafe(16) // careful, uninitialized memory! - -// Immediately overwrite the uninitialized buffer with data from another buffer -for (var i = 0; i < buf.length; i++) { - buf[i] = otherBuf[i] -} -``` - - -### How do we fix node.js core? - -We sent [a PR to node.js core](https://github.com/nodejs/node/pull/4514) (merged as -`semver-major`) which defends against one case: - -```js -var str = 16 -new Buffer(str, 'utf8') -``` - -In this situation, it's implied that the programmer intended the first argument to be a -string, since they passed an encoding as a second argument. Today, node.js will allocate -uninitialized memory in the case of `new Buffer(number, encoding)`, which is probably not -what the programmer intended. - -But this is only a partial solution, since if the programmer does `new Buffer(variable)` -(without an `encoding` parameter) there's no way to know what they intended. If `variable` -is sometimes a number, then uninitialized memory will sometimes be returned. - -### What's the real long-term fix? - -We could deprecate and remove `new Buffer(number)` and use `Buffer.allocUnsafe(number)` when -we need uninitialized memory. But that would break 1000s of packages. - -~~We believe the best solution is to:~~ - -~~1. Change `new Buffer(number)` to return safe, zeroed-out memory~~ - -~~2. Create a new API for creating uninitialized Buffers. We propose: `Buffer.allocUnsafe(number)`~~ - -#### Update - -We now support adding three new APIs: - -- `Buffer.from(value)` - convert from any type to a buffer -- `Buffer.alloc(size)` - create a zero-filled buffer -- `Buffer.allocUnsafe(size)` - create an uninitialized buffer with given size - -This solves the core problem that affected `ws` and `bittorrent-dht` which is -`Buffer(variable)` getting tricked into taking a number argument. - -This way, existing code continues working and the impact on the npm ecosystem will be -minimal. Over time, npm maintainers can migrate performance-critical code to use -`Buffer.allocUnsafe(number)` instead of `new Buffer(number)`. - - -### Conclusion - -We think there's a serious design issue with the `Buffer` API as it exists today. It -promotes insecure software by putting high-risk functionality into a convenient API -with friendly "developer ergonomics". - -This wasn't merely a theoretical exercise because we found the issue in some of the -most popular npm packages. - -Fortunately, there's an easy fix that can be applied today. Use `safe-buffer` in place of -`buffer`. - -```js -var Buffer = require('safe-buffer').Buffer -``` - -Eventually, we hope that node.js core can switch to this new, safer behavior. We believe -the impact on the ecosystem would be minimal since it's not a breaking change. -Well-maintained, popular packages would be updated to use `Buffer.alloc` quickly, while -older, insecure packages would magically become safe from this attack vector. - - -## links - -- [Node.js PR: buffer: throw if both length and enc are passed](https://github.com/nodejs/node/pull/4514) -- [Node Security Project disclosure for `ws`](https://nodesecurity.io/advisories/67) -- [Node Security Project disclosure for`bittorrent-dht`](https://nodesecurity.io/advisories/68) - - -## credit - -The original issues in `bittorrent-dht` -([disclosure](https://nodesecurity.io/advisories/68)) and -`ws` ([disclosure](https://nodesecurity.io/advisories/67)) were discovered by -[Mathias Buus](https://github.com/mafintosh) and -[Feross Aboukhadijeh](http://feross.org/). - -Thanks to [Adam Baldwin](https://github.com/evilpacket) for helping disclose these issues -and for his work running the [Node Security Project](https://nodesecurity.io/). - -Thanks to [John Hiesey](https://github.com/jhiesey) for proofreading this README and -auditing the code. - - -## license - -MIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org) diff --git a/scripts/node_modules/safe-buffer/index.d.ts b/scripts/node_modules/safe-buffer/index.d.ts deleted file mode 100644 index e9fed809..00000000 --- a/scripts/node_modules/safe-buffer/index.d.ts +++ /dev/null @@ -1,187 +0,0 @@ -declare module "safe-buffer" { - export class Buffer { - length: number - write(string: string, offset?: number, length?: number, encoding?: string): number; - toString(encoding?: string, start?: number, end?: number): string; - toJSON(): { type: 'Buffer', data: any[] }; - equals(otherBuffer: Buffer): boolean; - compare(otherBuffer: Buffer, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number; - copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; - slice(start?: number, end?: number): Buffer; - writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number; - readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number; - readIntLE(offset: number, byteLength: number, noAssert?: boolean): number; - readIntBE(offset: number, byteLength: number, noAssert?: boolean): number; - readUInt8(offset: number, noAssert?: boolean): number; - readUInt16LE(offset: number, noAssert?: boolean): number; - readUInt16BE(offset: number, noAssert?: boolean): number; - readUInt32LE(offset: number, noAssert?: boolean): number; - readUInt32BE(offset: number, noAssert?: boolean): number; - readInt8(offset: number, noAssert?: boolean): number; - readInt16LE(offset: number, noAssert?: boolean): number; - readInt16BE(offset: number, noAssert?: boolean): number; - readInt32LE(offset: number, noAssert?: boolean): number; - readInt32BE(offset: number, noAssert?: boolean): number; - readFloatLE(offset: number, noAssert?: boolean): number; - readFloatBE(offset: number, noAssert?: boolean): number; - readDoubleLE(offset: number, noAssert?: boolean): number; - readDoubleBE(offset: number, noAssert?: boolean): number; - swap16(): Buffer; - swap32(): Buffer; - swap64(): Buffer; - writeUInt8(value: number, offset: number, noAssert?: boolean): number; - writeUInt16LE(value: number, offset: number, noAssert?: boolean): number; - writeUInt16BE(value: number, offset: number, noAssert?: boolean): number; - writeUInt32LE(value: number, offset: number, noAssert?: boolean): number; - writeUInt32BE(value: number, offset: number, noAssert?: boolean): number; - writeInt8(value: number, offset: number, noAssert?: boolean): number; - writeInt16LE(value: number, offset: number, noAssert?: boolean): number; - writeInt16BE(value: number, offset: number, noAssert?: boolean): number; - writeInt32LE(value: number, offset: number, noAssert?: boolean): number; - writeInt32BE(value: number, offset: number, noAssert?: boolean): number; - writeFloatLE(value: number, offset: number, noAssert?: boolean): number; - writeFloatBE(value: number, offset: number, noAssert?: boolean): number; - writeDoubleLE(value: number, offset: number, noAssert?: boolean): number; - writeDoubleBE(value: number, offset: number, noAssert?: boolean): number; - fill(value: any, offset?: number, end?: number): this; - indexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; - lastIndexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; - includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean; - - /** - * Allocates a new buffer containing the given {str}. - * - * @param str String to store in buffer. - * @param encoding encoding to use, optional. Default is 'utf8' - */ - constructor (str: string, encoding?: string); - /** - * Allocates a new buffer of {size} octets. - * - * @param size count of octets to allocate. - */ - constructor (size: number); - /** - * Allocates a new buffer containing the given {array} of octets. - * - * @param array The octets to store. - */ - constructor (array: Uint8Array); - /** - * Produces a Buffer backed by the same allocated memory as - * the given {ArrayBuffer}. - * - * - * @param arrayBuffer The ArrayBuffer with which to share memory. - */ - constructor (arrayBuffer: ArrayBuffer); - /** - * Allocates a new buffer containing the given {array} of octets. - * - * @param array The octets to store. - */ - constructor (array: any[]); - /** - * Copies the passed {buffer} data onto a new {Buffer} instance. - * - * @param buffer The buffer to copy. - */ - constructor (buffer: Buffer); - prototype: Buffer; - /** - * Allocates a new Buffer using an {array} of octets. - * - * @param array - */ - static from(array: any[]): Buffer; - /** - * When passed a reference to the .buffer property of a TypedArray instance, - * the newly created Buffer will share the same allocated memory as the TypedArray. - * The optional {byteOffset} and {length} arguments specify a memory range - * within the {arrayBuffer} that will be shared by the Buffer. - * - * @param arrayBuffer The .buffer property of a TypedArray or a new ArrayBuffer() - * @param byteOffset - * @param length - */ - static from(arrayBuffer: ArrayBuffer, byteOffset?: number, length?: number): Buffer; - /** - * Copies the passed {buffer} data onto a new Buffer instance. - * - * @param buffer - */ - static from(buffer: Buffer): Buffer; - /** - * Creates a new Buffer containing the given JavaScript string {str}. - * If provided, the {encoding} parameter identifies the character encoding. - * If not provided, {encoding} defaults to 'utf8'. - * - * @param str - */ - static from(str: string, encoding?: string): Buffer; - /** - * Returns true if {obj} is a Buffer - * - * @param obj object to test. - */ - static isBuffer(obj: any): obj is Buffer; - /** - * Returns true if {encoding} is a valid encoding argument. - * Valid string encodings in Node 0.12: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' - * - * @param encoding string to test. - */ - static isEncoding(encoding: string): boolean; - /** - * Gives the actual byte length of a string. encoding defaults to 'utf8'. - * This is not the same as String.prototype.length since that returns the number of characters in a string. - * - * @param string string to test. - * @param encoding encoding used to evaluate (defaults to 'utf8') - */ - static byteLength(string: string, encoding?: string): number; - /** - * Returns a buffer which is the result of concatenating all the buffers in the list together. - * - * If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer. - * If the list has exactly one item, then the first item of the list is returned. - * If the list has more than one item, then a new Buffer is created. - * - * @param list An array of Buffer objects to concatenate - * @param totalLength Total length of the buffers when concatenated. - * If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly. - */ - static concat(list: Buffer[], totalLength?: number): Buffer; - /** - * The same as buf1.compare(buf2). - */ - static compare(buf1: Buffer, buf2: Buffer): number; - /** - * Allocates a new buffer of {size} octets. - * - * @param size count of octets to allocate. - * @param fill if specified, buffer will be initialized by calling buf.fill(fill). - * If parameter is omitted, buffer will be filled with zeros. - * @param encoding encoding used for call to buf.fill while initalizing - */ - static alloc(size: number, fill?: string | Buffer | number, encoding?: string): Buffer; - /** - * Allocates a new buffer of {size} octets, leaving memory not initialized, so the contents - * of the newly created Buffer are unknown and may contain sensitive data. - * - * @param size count of octets to allocate - */ - static allocUnsafe(size: number): Buffer; - /** - * Allocates a new non-pooled buffer of {size} octets, leaving memory not initialized, so the contents - * of the newly created Buffer are unknown and may contain sensitive data. - * - * @param size count of octets to allocate - */ - static allocUnsafeSlow(size: number): Buffer; - } -} \ No newline at end of file diff --git a/scripts/node_modules/safe-buffer/index.js b/scripts/node_modules/safe-buffer/index.js deleted file mode 100644 index 054c8d30..00000000 --- a/scripts/node_modules/safe-buffer/index.js +++ /dev/null @@ -1,64 +0,0 @@ -/* eslint-disable node/no-deprecated-api */ -var buffer = require('buffer') -var Buffer = buffer.Buffer - -// alternative to using Object.keys for old browsers -function copyProps (src, dst) { - for (var key in src) { - dst[key] = src[key] - } -} -if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { - module.exports = buffer -} else { - // Copy properties from require('buffer') - copyProps(buffer, exports) - exports.Buffer = SafeBuffer -} - -function SafeBuffer (arg, encodingOrOffset, length) { - return Buffer(arg, encodingOrOffset, length) -} - -SafeBuffer.prototype = Object.create(Buffer.prototype) - -// Copy static methods from Buffer -copyProps(Buffer, SafeBuffer) - -SafeBuffer.from = function (arg, encodingOrOffset, length) { - if (typeof arg === 'number') { - throw new TypeError('Argument must not be a number') - } - return Buffer(arg, encodingOrOffset, length) -} - -SafeBuffer.alloc = function (size, fill, encoding) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - var buf = Buffer(size) - if (fill !== undefined) { - if (typeof encoding === 'string') { - buf.fill(fill, encoding) - } else { - buf.fill(fill) - } - } else { - buf.fill(0) - } - return buf -} - -SafeBuffer.allocUnsafe = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - return Buffer(size) -} - -SafeBuffer.allocUnsafeSlow = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - return buffer.SlowBuffer(size) -} diff --git a/scripts/node_modules/safe-buffer/package.json b/scripts/node_modules/safe-buffer/package.json deleted file mode 100644 index ee699fac..00000000 --- a/scripts/node_modules/safe-buffer/package.json +++ /dev/null @@ -1,62 +0,0 @@ -{ - "_from": "safe-buffer@^5.1.2", - "_id": "safe-buffer@5.2.0", - "_inBundle": false, - "_integrity": "sha512-fZEwUGbVl7kouZs1jCdMLdt95hdIv0ZeHg6L7qPeciMZhZ+/gdesW4wgTARkrFWEpspjEATAzUGPG8N2jJiwbg==", - "_location": "/safe-buffer", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "safe-buffer@^5.1.2", - "name": "safe-buffer", - "escapedName": "safe-buffer", - "rawSpec": "^5.1.2", - "saveSpec": null, - "fetchSpec": "^5.1.2" - }, - "_requiredBy": [ - "/mongodb" - ], - "_resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.0.tgz", - "_shasum": "b74daec49b1148f88c64b68d49b1e815c1f2f519", - "_spec": "safe-buffer@^5.1.2", - "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/node_modules/mongodb", - "author": { - "name": "Feross Aboukhadijeh", - "email": "feross@feross.org", - "url": "http://feross.org" - }, - "bugs": { - "url": "https://github.com/feross/safe-buffer/issues" - }, - "bundleDependencies": false, - "deprecated": false, - "description": "Safer Node.js Buffer API", - "devDependencies": { - "standard": "*", - "tape": "^4.0.0" - }, - "homepage": "https://github.com/feross/safe-buffer", - "keywords": [ - "buffer", - "buffer allocate", - "node security", - "safe", - "safe-buffer", - "security", - "uninitialized" - ], - "license": "MIT", - "main": "index.js", - "name": "safe-buffer", - "repository": { - "type": "git", - "url": "git://github.com/feross/safe-buffer.git" - }, - "scripts": { - "test": "standard && tape test/*.js" - }, - "types": "index.d.ts", - "version": "5.2.0" -} diff --git a/scripts/node_modules/saslprep/.editorconfig b/scripts/node_modules/saslprep/.editorconfig deleted file mode 100644 index d1d8a417..00000000 --- a/scripts/node_modules/saslprep/.editorconfig +++ /dev/null @@ -1,10 +0,0 @@ -# http://editorconfig.org -root = true - -[*] -indent_style = space -indent_size = 2 -end_of_line = lf -charset = utf-8 -trim_trailing_whitespace = true -insert_final_newline = true diff --git a/scripts/node_modules/saslprep/.gitattributes b/scripts/node_modules/saslprep/.gitattributes deleted file mode 100644 index 3ba45360..00000000 --- a/scripts/node_modules/saslprep/.gitattributes +++ /dev/null @@ -1 +0,0 @@ -*.mem binary diff --git a/scripts/node_modules/saslprep/.travis.yml b/scripts/node_modules/saslprep/.travis.yml deleted file mode 100644 index 0bca8265..00000000 --- a/scripts/node_modules/saslprep/.travis.yml +++ /dev/null @@ -1,10 +0,0 @@ -sudo: false -language: node_js -node_js: - - "6" - - "8" - - "10" - - "12" - -before_install: -- npm install -g npm@6 diff --git a/scripts/node_modules/saslprep/CHANGELOG.md b/scripts/node_modules/saslprep/CHANGELOG.md deleted file mode 100644 index 77980787..00000000 --- a/scripts/node_modules/saslprep/CHANGELOG.md +++ /dev/null @@ -1,19 +0,0 @@ -# Change Log -All notable changes to the "saslprep" package will be documented in this file. - -## [1.0.3] - 2019-05-01 - -- Correctly get code points >U+FFFF ([#5](https://github.com/reklatsmasters/saslprep/pull/5)) -- Fix perfomance downgrades from [#5](https://github.com/reklatsmasters/saslprep/pull/5). - -## [1.0.2] - 2018-09-13 - -- Reduced initialization time ([#3](https://github.com/reklatsmasters/saslprep/issues/3)) - -## [1.0.1] - 2018-06-20 - -- Reduced stack overhead of range creation ([#2](https://github.com/reklatsmasters/saslprep/pull/2)) - -## [1.0.0] - 2017-06-21 - -- First release diff --git a/scripts/node_modules/saslprep/LICENSE b/scripts/node_modules/saslprep/LICENSE deleted file mode 100644 index 481c7a50..00000000 --- a/scripts/node_modules/saslprep/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -Copyright (c) 2014 Dmitry Tsvettsikh - -Permission is hereby granted, free of charge, to any person -obtaining a copy of this software and associated documentation -files (the "Software"), to deal in the Software without -restriction, including without limitation the rights to use, -copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the -Software is furnished to do so, subject to the following -conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/scripts/node_modules/saslprep/code-points.mem b/scripts/node_modules/saslprep/code-points.mem deleted file mode 100644 index 4781b066802688bdf954d2e89bcfac967db29c09..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 419864 zcmeI*O^9Si9RTop)4e+(t{DX(dsufSM8xBQfdsOo2lf&{@FWO&5cZ;Y@FWHe%nKV~ z@sxvzw;c53DIgdRk!c;t<{;##B4%51h#=^gL^8Y6+hx^z-92x{*9;3Umv`GA&vUy%enler!HTQKkA3&c=OSJMn7j|JGjl-d;Iey^#7>ZH0(RWYm^YJNA>kJ59aOu`p6X{MHRe9bu8cD2oYvN=9*ybv z%TyjdGTZ46aN&^<{xI6U)O2~U(!G+Yl0gPYRjbu8Wx~a<(#z+pIGvPkC#O7E&NgnV zIeue)&FW_ULfI&__U^^i@bTrer0O33=x2+%W4?Qo^)pjbsxinkv-K<<-Z9O6ZEyaQ zcB_@u#{%W}q9N0;ypzw%<*<}a^^Ob|R8?1xx0U*l{Mfi-J@SG5+xHJnzAqkVA73p) zfWWZ=`LSE4W4mY|K!5-N0t5&UATSizd-XW}{r>FO4Bx#OzCAE{nLD@VvjcA?1PBnA ze}O7c;{B8P-)Ji&@Gu01QMDYyI+%*sOCglv+~@Yqqm#Pz_SKwJ*n6ekt-IE7xb$i{ z#vJ7-%1?!2rG0Ri^X0*sx?FU--CIQw%Y*Zsb~)W#QAMFvj~+Qsr{Zh=QgU=xwFC$d zAV7cs0RjXF5FkK+009C72oNAZfB*pkrx2*aLB}2IZvhtFBipAEvDq7W9J^}&<>l~& z=Z6hT7u&hviF4icy{;$Z#$Rfh)bDEDcnTt22oNAJj{^NkPm$UP5FkK+009C72oNAZ zfB*pk1PBlya5e=N=WpRu-1tFH?r+Uep=aLS_2t}!1M%`E=_N&nH;IH{&FT4 zVA2E#5FkK+009C72oNAZfB*pk1PBlyK!5-N0tDtqVE;Gx53TDIQTIm zIQs(S*`MN>nqk~d)2W{+PVszkrlxK(QxGVpFoq#!SYT-_Rh1zb5B|v}x z0RjXF5FkK+009C72oNAZfB*pk1PBlyK!5;&ITaB9pVN)CECK`w5FkK+009C72oNAZ zfB*pk1PBlyK!5-N0t5&USSSJU|ApFaizPsS009C72oNAZfB*pk1PBlyK!5-N0t5&U zAV7csfjJcr|DV&1wJZVz2oNAZfB*pk1PBlyK!5-N0t5&UAV7cs0RjXF5LhUI)_PiQ zY@~%+y~PqBK!5-N0t5&UAV7cs0RjXF5FkK+009C72oNAZfB=E{5NI_*|FQ%K5FkK+ z009C72oNAZfB*pk1PBlyK!5-N0t5&UAV7e?Yzp*ebJ}K2fB*pk1PBlyK!5-N0t5&U zAV7cs0RjXF5FkK+009C72s8ykSewfEzdsXvos!llv!K)XN+!bACMEW{kJW7s~i{EW^`xUX5|{=UXrRtoY&_gwz< zRvE$%TJf3i_%h&Xxb|Z>^W9wXR6Vl#j!mc_rtE>35?{Z6IbwcGK;>nSRoF zHt&;$O2P80zs-^hqp)?4qhw2`7#YP=_?Tw>wDeltgbe?$_^GM=@ z?HoDm9erzgM=HMNFC|BJRZD;X0RjXF5FkK+009C72oNAZfB*pk1PBlya0-DOe>pzY z-vZ3vILv9#>4l5=+gV#xaVim;YNYBg{{HIj=YJUg^!l*j-g~>b;hnpk&0)>Sr{)*n zj_ut&1&%HR2oRWKfn%Q^H4q>`fB*pk1PBlyK!5-N0t5&UAVA>E3Jm7>U0X{dK!5-N z0t5&U__zX7c= character.codePointAt(0); -const first = x => x[0]; -const last = x => x[x.length - 1]; - -/** - * Convert provided string into an array of Unicode Code Points. - * Based on https://stackoverflow.com/a/21409165/1556249 - * and https://www.npmjs.com/package/code-point-at. - * @param {string} input - * @returns {number[]} - */ -function toCodePoints(input) { - const codepoints = []; - const size = input.length; - - for (let i = 0; i < size; i += 1) { - const before = input.charCodeAt(i); - - if (before >= 0xd800 && before <= 0xdbff && size > i + 1) { - const next = input.charCodeAt(i + 1); - - if (next >= 0xdc00 && next <= 0xdfff) { - codepoints.push((before - 0xd800) * 0x400 + next - 0xdc00 + 0x10000); - i += 1; - continue; - } - } - - codepoints.push(before); - } - - return codepoints; -} - -/** - * SASLprep. - * @param {string} input - * @param {Object} opts - * @param {boolean} opts.allowUnassigned - * @returns {string} - */ -function saslprep(input, opts = {}) { - if (typeof input !== 'string') { - throw new TypeError('Expected string.'); - } - - if (input.length === 0) { - return ''; - } - - // 1. Map - const mapped_input = toCodePoints(input) - // 1.1 mapping to space - .map(character => (mapping2space.get(character) ? 0x20 : character)) - // 1.2 mapping to nothing - .filter(character => !mapping2nothing.get(character)); - - // 2. Normalize - const normalized_input = String.fromCodePoint - .apply(null, mapped_input) - .normalize('NFKC'); - - const normalized_map = toCodePoints(normalized_input); - - // 3. Prohibit - const hasProhibited = normalized_map.some(character => - prohibited_characters.get(character) - ); - - if (hasProhibited) { - throw new Error( - 'Prohibited character, see https://tools.ietf.org/html/rfc4013#section-2.3' - ); - } - - // Unassigned Code Points - if (opts.allowUnassigned !== true) { - const hasUnassigned = normalized_map.some(character => - unassigned_code_points.get(character) - ); - - if (hasUnassigned) { - throw new Error( - 'Unassigned code point, see https://tools.ietf.org/html/rfc4013#section-2.5' - ); - } - } - - // 4. check bidi - - const hasBidiRAL = normalized_map.some(character => - bidirectional_r_al.get(character) - ); - - const hasBidiL = normalized_map.some(character => - bidirectional_l.get(character) - ); - - // 4.1 If a string contains any RandALCat character, the string MUST NOT - // contain any LCat character. - if (hasBidiRAL && hasBidiL) { - throw new Error( - 'String must not contain RandALCat and LCat at the same time,' + - ' see https://tools.ietf.org/html/rfc3454#section-6' - ); - } - - /** - * 4.2 If a string contains any RandALCat character, a RandALCat - * character MUST be the first character of the string, and a - * RandALCat character MUST be the last character of the string. - */ - - const isFirstBidiRAL = bidirectional_r_al.get( - getCodePoint(first(normalized_input)) - ); - const isLastBidiRAL = bidirectional_r_al.get( - getCodePoint(last(normalized_input)) - ); - - if (hasBidiRAL && !(isFirstBidiRAL && isLastBidiRAL)) { - throw new Error( - 'Bidirectional RandALCat character must be the first and the last' + - ' character of the string, see https://tools.ietf.org/html/rfc3454#section-6' - ); - } - - return normalized_input; -} diff --git a/scripts/node_modules/saslprep/lib/code-points.js b/scripts/node_modules/saslprep/lib/code-points.js deleted file mode 100644 index 222182c8..00000000 --- a/scripts/node_modules/saslprep/lib/code-points.js +++ /dev/null @@ -1,996 +0,0 @@ -'use strict'; - -const { range } = require('./util'); - -/** - * A.1 Unassigned code points in Unicode 3.2 - * @link https://tools.ietf.org/html/rfc3454#appendix-A.1 - */ -const unassigned_code_points = new Set([ - 0x0221, - ...range(0x0234, 0x024f), - ...range(0x02ae, 0x02af), - ...range(0x02ef, 0x02ff), - ...range(0x0350, 0x035f), - ...range(0x0370, 0x0373), - ...range(0x0376, 0x0379), - ...range(0x037b, 0x037d), - ...range(0x037f, 0x0383), - 0x038b, - 0x038d, - 0x03a2, - 0x03cf, - ...range(0x03f7, 0x03ff), - 0x0487, - 0x04cf, - ...range(0x04f6, 0x04f7), - ...range(0x04fa, 0x04ff), - ...range(0x0510, 0x0530), - ...range(0x0557, 0x0558), - 0x0560, - 0x0588, - ...range(0x058b, 0x0590), - 0x05a2, - 0x05ba, - ...range(0x05c5, 0x05cf), - ...range(0x05eb, 0x05ef), - ...range(0x05f5, 0x060b), - ...range(0x060d, 0x061a), - ...range(0x061c, 0x061e), - 0x0620, - ...range(0x063b, 0x063f), - ...range(0x0656, 0x065f), - ...range(0x06ee, 0x06ef), - 0x06ff, - 0x070e, - ...range(0x072d, 0x072f), - ...range(0x074b, 0x077f), - ...range(0x07b2, 0x0900), - 0x0904, - ...range(0x093a, 0x093b), - ...range(0x094e, 0x094f), - ...range(0x0955, 0x0957), - ...range(0x0971, 0x0980), - 0x0984, - ...range(0x098d, 0x098e), - ...range(0x0991, 0x0992), - 0x09a9, - 0x09b1, - ...range(0x09b3, 0x09b5), - ...range(0x09ba, 0x09bb), - 0x09bd, - ...range(0x09c5, 0x09c6), - ...range(0x09c9, 0x09ca), - ...range(0x09ce, 0x09d6), - ...range(0x09d8, 0x09db), - 0x09de, - ...range(0x09e4, 0x09e5), - ...range(0x09fb, 0x0a01), - ...range(0x0a03, 0x0a04), - ...range(0x0a0b, 0x0a0e), - ...range(0x0a11, 0x0a12), - 0x0a29, - 0x0a31, - 0x0a34, - 0x0a37, - ...range(0x0a3a, 0x0a3b), - 0x0a3d, - ...range(0x0a43, 0x0a46), - ...range(0x0a49, 0x0a4a), - ...range(0x0a4e, 0x0a58), - 0x0a5d, - ...range(0x0a5f, 0x0a65), - ...range(0x0a75, 0x0a80), - 0x0a84, - 0x0a8c, - 0x0a8e, - 0x0a92, - 0x0aa9, - 0x0ab1, - 0x0ab4, - ...range(0x0aba, 0x0abb), - 0x0ac6, - 0x0aca, - ...range(0x0ace, 0x0acf), - ...range(0x0ad1, 0x0adf), - ...range(0x0ae1, 0x0ae5), - ...range(0x0af0, 0x0b00), - 0x0b04, - ...range(0x0b0d, 0x0b0e), - ...range(0x0b11, 0x0b12), - 0x0b29, - 0x0b31, - ...range(0x0b34, 0x0b35), - ...range(0x0b3a, 0x0b3b), - ...range(0x0b44, 0x0b46), - ...range(0x0b49, 0x0b4a), - ...range(0x0b4e, 0x0b55), - ...range(0x0b58, 0x0b5b), - 0x0b5e, - ...range(0x0b62, 0x0b65), - ...range(0x0b71, 0x0b81), - 0x0b84, - ...range(0x0b8b, 0x0b8d), - 0x0b91, - ...range(0x0b96, 0x0b98), - 0x0b9b, - 0x0b9d, - ...range(0x0ba0, 0x0ba2), - ...range(0x0ba5, 0x0ba7), - ...range(0x0bab, 0x0bad), - 0x0bb6, - ...range(0x0bba, 0x0bbd), - ...range(0x0bc3, 0x0bc5), - 0x0bc9, - ...range(0x0bce, 0x0bd6), - ...range(0x0bd8, 0x0be6), - ...range(0x0bf3, 0x0c00), - 0x0c04, - 0x0c0d, - 0x0c11, - 0x0c29, - 0x0c34, - ...range(0x0c3a, 0x0c3d), - 0x0c45, - 0x0c49, - ...range(0x0c4e, 0x0c54), - ...range(0x0c57, 0x0c5f), - ...range(0x0c62, 0x0c65), - ...range(0x0c70, 0x0c81), - 0x0c84, - 0x0c8d, - 0x0c91, - 0x0ca9, - 0x0cb4, - ...range(0x0cba, 0x0cbd), - 0x0cc5, - 0x0cc9, - ...range(0x0cce, 0x0cd4), - ...range(0x0cd7, 0x0cdd), - 0x0cdf, - ...range(0x0ce2, 0x0ce5), - ...range(0x0cf0, 0x0d01), - 0x0d04, - 0x0d0d, - 0x0d11, - 0x0d29, - ...range(0x0d3a, 0x0d3d), - ...range(0x0d44, 0x0d45), - 0x0d49, - ...range(0x0d4e, 0x0d56), - ...range(0x0d58, 0x0d5f), - ...range(0x0d62, 0x0d65), - ...range(0x0d70, 0x0d81), - 0x0d84, - ...range(0x0d97, 0x0d99), - 0x0db2, - 0x0dbc, - ...range(0x0dbe, 0x0dbf), - ...range(0x0dc7, 0x0dc9), - ...range(0x0dcb, 0x0dce), - 0x0dd5, - 0x0dd7, - ...range(0x0de0, 0x0df1), - ...range(0x0df5, 0x0e00), - ...range(0x0e3b, 0x0e3e), - ...range(0x0e5c, 0x0e80), - 0x0e83, - ...range(0x0e85, 0x0e86), - 0x0e89, - ...range(0x0e8b, 0x0e8c), - ...range(0x0e8e, 0x0e93), - 0x0e98, - 0x0ea0, - 0x0ea4, - 0x0ea6, - ...range(0x0ea8, 0x0ea9), - 0x0eac, - 0x0eba, - ...range(0x0ebe, 0x0ebf), - 0x0ec5, - 0x0ec7, - ...range(0x0ece, 0x0ecf), - ...range(0x0eda, 0x0edb), - ...range(0x0ede, 0x0eff), - 0x0f48, - ...range(0x0f6b, 0x0f70), - ...range(0x0f8c, 0x0f8f), - 0x0f98, - 0x0fbd, - ...range(0x0fcd, 0x0fce), - ...range(0x0fd0, 0x0fff), - 0x1022, - 0x1028, - 0x102b, - ...range(0x1033, 0x1035), - ...range(0x103a, 0x103f), - ...range(0x105a, 0x109f), - ...range(0x10c6, 0x10cf), - ...range(0x10f9, 0x10fa), - ...range(0x10fc, 0x10ff), - ...range(0x115a, 0x115e), - ...range(0x11a3, 0x11a7), - ...range(0x11fa, 0x11ff), - 0x1207, - 0x1247, - 0x1249, - ...range(0x124e, 0x124f), - 0x1257, - 0x1259, - ...range(0x125e, 0x125f), - 0x1287, - 0x1289, - ...range(0x128e, 0x128f), - 0x12af, - 0x12b1, - ...range(0x12b6, 0x12b7), - 0x12bf, - 0x12c1, - ...range(0x12c6, 0x12c7), - 0x12cf, - 0x12d7, - 0x12ef, - 0x130f, - 0x1311, - ...range(0x1316, 0x1317), - 0x131f, - 0x1347, - ...range(0x135b, 0x1360), - ...range(0x137d, 0x139f), - ...range(0x13f5, 0x1400), - ...range(0x1677, 0x167f), - ...range(0x169d, 0x169f), - ...range(0x16f1, 0x16ff), - 0x170d, - ...range(0x1715, 0x171f), - ...range(0x1737, 0x173f), - ...range(0x1754, 0x175f), - 0x176d, - 0x1771, - ...range(0x1774, 0x177f), - ...range(0x17dd, 0x17df), - ...range(0x17ea, 0x17ff), - 0x180f, - ...range(0x181a, 0x181f), - ...range(0x1878, 0x187f), - ...range(0x18aa, 0x1dff), - ...range(0x1e9c, 0x1e9f), - ...range(0x1efa, 0x1eff), - ...range(0x1f16, 0x1f17), - ...range(0x1f1e, 0x1f1f), - ...range(0x1f46, 0x1f47), - ...range(0x1f4e, 0x1f4f), - 0x1f58, - 0x1f5a, - 0x1f5c, - 0x1f5e, - ...range(0x1f7e, 0x1f7f), - 0x1fb5, - 0x1fc5, - ...range(0x1fd4, 0x1fd5), - 0x1fdc, - ...range(0x1ff0, 0x1ff1), - 0x1ff5, - 0x1fff, - ...range(0x2053, 0x2056), - ...range(0x2058, 0x205e), - ...range(0x2064, 0x2069), - ...range(0x2072, 0x2073), - ...range(0x208f, 0x209f), - ...range(0x20b2, 0x20cf), - ...range(0x20eb, 0x20ff), - ...range(0x213b, 0x213c), - ...range(0x214c, 0x2152), - ...range(0x2184, 0x218f), - ...range(0x23cf, 0x23ff), - ...range(0x2427, 0x243f), - ...range(0x244b, 0x245f), - 0x24ff, - ...range(0x2614, 0x2615), - 0x2618, - ...range(0x267e, 0x267f), - ...range(0x268a, 0x2700), - 0x2705, - ...range(0x270a, 0x270b), - 0x2728, - 0x274c, - 0x274e, - ...range(0x2753, 0x2755), - 0x2757, - ...range(0x275f, 0x2760), - ...range(0x2795, 0x2797), - 0x27b0, - ...range(0x27bf, 0x27cf), - ...range(0x27ec, 0x27ef), - ...range(0x2b00, 0x2e7f), - 0x2e9a, - ...range(0x2ef4, 0x2eff), - ...range(0x2fd6, 0x2fef), - ...range(0x2ffc, 0x2fff), - 0x3040, - ...range(0x3097, 0x3098), - ...range(0x3100, 0x3104), - ...range(0x312d, 0x3130), - 0x318f, - ...range(0x31b8, 0x31ef), - ...range(0x321d, 0x321f), - ...range(0x3244, 0x3250), - ...range(0x327c, 0x327e), - ...range(0x32cc, 0x32cf), - 0x32ff, - ...range(0x3377, 0x337a), - ...range(0x33de, 0x33df), - 0x33ff, - ...range(0x4db6, 0x4dff), - ...range(0x9fa6, 0x9fff), - ...range(0xa48d, 0xa48f), - ...range(0xa4c7, 0xabff), - ...range(0xd7a4, 0xd7ff), - ...range(0xfa2e, 0xfa2f), - ...range(0xfa6b, 0xfaff), - ...range(0xfb07, 0xfb12), - ...range(0xfb18, 0xfb1c), - 0xfb37, - 0xfb3d, - 0xfb3f, - 0xfb42, - 0xfb45, - ...range(0xfbb2, 0xfbd2), - ...range(0xfd40, 0xfd4f), - ...range(0xfd90, 0xfd91), - ...range(0xfdc8, 0xfdcf), - ...range(0xfdfd, 0xfdff), - ...range(0xfe10, 0xfe1f), - ...range(0xfe24, 0xfe2f), - ...range(0xfe47, 0xfe48), - 0xfe53, - 0xfe67, - ...range(0xfe6c, 0xfe6f), - 0xfe75, - ...range(0xfefd, 0xfefe), - 0xff00, - ...range(0xffbf, 0xffc1), - ...range(0xffc8, 0xffc9), - ...range(0xffd0, 0xffd1), - ...range(0xffd8, 0xffd9), - ...range(0xffdd, 0xffdf), - 0xffe7, - ...range(0xffef, 0xfff8), - ...range(0x10000, 0x102ff), - 0x1031f, - ...range(0x10324, 0x1032f), - ...range(0x1034b, 0x103ff), - ...range(0x10426, 0x10427), - ...range(0x1044e, 0x1cfff), - ...range(0x1d0f6, 0x1d0ff), - ...range(0x1d127, 0x1d129), - ...range(0x1d1de, 0x1d3ff), - 0x1d455, - 0x1d49d, - ...range(0x1d4a0, 0x1d4a1), - ...range(0x1d4a3, 0x1d4a4), - ...range(0x1d4a7, 0x1d4a8), - 0x1d4ad, - 0x1d4ba, - 0x1d4bc, - 0x1d4c1, - 0x1d4c4, - 0x1d506, - ...range(0x1d50b, 0x1d50c), - 0x1d515, - 0x1d51d, - 0x1d53a, - 0x1d53f, - 0x1d545, - ...range(0x1d547, 0x1d549), - 0x1d551, - ...range(0x1d6a4, 0x1d6a7), - ...range(0x1d7ca, 0x1d7cd), - ...range(0x1d800, 0x1fffd), - ...range(0x2a6d7, 0x2f7ff), - ...range(0x2fa1e, 0x2fffd), - ...range(0x30000, 0x3fffd), - ...range(0x40000, 0x4fffd), - ...range(0x50000, 0x5fffd), - ...range(0x60000, 0x6fffd), - ...range(0x70000, 0x7fffd), - ...range(0x80000, 0x8fffd), - ...range(0x90000, 0x9fffd), - ...range(0xa0000, 0xafffd), - ...range(0xb0000, 0xbfffd), - ...range(0xc0000, 0xcfffd), - ...range(0xd0000, 0xdfffd), - 0xe0000, - ...range(0xe0002, 0xe001f), - ...range(0xe0080, 0xefffd), -]); - -/** - * B.1 Commonly mapped to nothing - * @link https://tools.ietf.org/html/rfc3454#appendix-B.1 - */ -const commonly_mapped_to_nothing = new Set([ - 0x00ad, - 0x034f, - 0x1806, - 0x180b, - 0x180c, - 0x180d, - 0x200b, - 0x200c, - 0x200d, - 0x2060, - 0xfe00, - 0xfe01, - 0xfe02, - 0xfe03, - 0xfe04, - 0xfe05, - 0xfe06, - 0xfe07, - 0xfe08, - 0xfe09, - 0xfe0a, - 0xfe0b, - 0xfe0c, - 0xfe0d, - 0xfe0e, - 0xfe0f, - 0xfeff, -]); - -/** - * C.1.2 Non-ASCII space characters - * @link https://tools.ietf.org/html/rfc3454#appendix-C.1.2 - */ -const non_ASCII_space_characters = new Set([ - 0x00a0 /* NO-BREAK SPACE */, - 0x1680 /* OGHAM SPACE MARK */, - 0x2000 /* EN QUAD */, - 0x2001 /* EM QUAD */, - 0x2002 /* EN SPACE */, - 0x2003 /* EM SPACE */, - 0x2004 /* THREE-PER-EM SPACE */, - 0x2005 /* FOUR-PER-EM SPACE */, - 0x2006 /* SIX-PER-EM SPACE */, - 0x2007 /* FIGURE SPACE */, - 0x2008 /* PUNCTUATION SPACE */, - 0x2009 /* THIN SPACE */, - 0x200a /* HAIR SPACE */, - 0x200b /* ZERO WIDTH SPACE */, - 0x202f /* NARROW NO-BREAK SPACE */, - 0x205f /* MEDIUM MATHEMATICAL SPACE */, - 0x3000 /* IDEOGRAPHIC SPACE */, -]); - -/** - * 2.3. Prohibited Output - * @type {Set} - */ -const prohibited_characters = new Set([ - ...non_ASCII_space_characters, - - /** - * C.2.1 ASCII control characters - * @link https://tools.ietf.org/html/rfc3454#appendix-C.2.1 - */ - ...range(0, 0x001f) /* [CONTROL CHARACTERS] */, - 0x007f /* DELETE */, - - /** - * C.2.2 Non-ASCII control characters - * @link https://tools.ietf.org/html/rfc3454#appendix-C.2.2 - */ - ...range(0x0080, 0x009f) /* [CONTROL CHARACTERS] */, - 0x06dd /* ARABIC END OF AYAH */, - 0x070f /* SYRIAC ABBREVIATION MARK */, - 0x180e /* MONGOLIAN VOWEL SEPARATOR */, - 0x200c /* ZERO WIDTH NON-JOINER */, - 0x200d /* ZERO WIDTH JOINER */, - 0x2028 /* LINE SEPARATOR */, - 0x2029 /* PARAGRAPH SEPARATOR */, - 0x2060 /* WORD JOINER */, - 0x2061 /* FUNCTION APPLICATION */, - 0x2062 /* INVISIBLE TIMES */, - 0x2063 /* INVISIBLE SEPARATOR */, - ...range(0x206a, 0x206f) /* [CONTROL CHARACTERS] */, - 0xfeff /* ZERO WIDTH NO-BREAK SPACE */, - ...range(0xfff9, 0xfffc) /* [CONTROL CHARACTERS] */, - ...range(0x1d173, 0x1d17a) /* [MUSICAL CONTROL CHARACTERS] */, - - /** - * C.3 Private use - * @link https://tools.ietf.org/html/rfc3454#appendix-C.3 - */ - ...range(0xe000, 0xf8ff) /* [PRIVATE USE, PLANE 0] */, - ...range(0xf0000, 0xffffd) /* [PRIVATE USE, PLANE 15] */, - ...range(0x100000, 0x10fffd) /* [PRIVATE USE, PLANE 16] */, - - /** - * C.4 Non-character code points - * @link https://tools.ietf.org/html/rfc3454#appendix-C.4 - */ - ...range(0xfdd0, 0xfdef) /* [NONCHARACTER CODE POINTS] */, - ...range(0xfffe, 0xffff) /* [NONCHARACTER CODE POINTS] */, - ...range(0x1fffe, 0x1ffff) /* [NONCHARACTER CODE POINTS] */, - ...range(0x2fffe, 0x2ffff) /* [NONCHARACTER CODE POINTS] */, - ...range(0x3fffe, 0x3ffff) /* [NONCHARACTER CODE POINTS] */, - ...range(0x4fffe, 0x4ffff) /* [NONCHARACTER CODE POINTS] */, - ...range(0x5fffe, 0x5ffff) /* [NONCHARACTER CODE POINTS] */, - ...range(0x6fffe, 0x6ffff) /* [NONCHARACTER CODE POINTS] */, - ...range(0x7fffe, 0x7ffff) /* [NONCHARACTER CODE POINTS] */, - ...range(0x8fffe, 0x8ffff) /* [NONCHARACTER CODE POINTS] */, - ...range(0x9fffe, 0x9ffff) /* [NONCHARACTER CODE POINTS] */, - ...range(0xafffe, 0xaffff) /* [NONCHARACTER CODE POINTS] */, - ...range(0xbfffe, 0xbffff) /* [NONCHARACTER CODE POINTS] */, - ...range(0xcfffe, 0xcffff) /* [NONCHARACTER CODE POINTS] */, - ...range(0xdfffe, 0xdffff) /* [NONCHARACTER CODE POINTS] */, - ...range(0xefffe, 0xeffff) /* [NONCHARACTER CODE POINTS] */, - ...range(0x10fffe, 0x10ffff) /* [NONCHARACTER CODE POINTS] */, - - /** - * C.5 Surrogate codes - * @link https://tools.ietf.org/html/rfc3454#appendix-C.5 - */ - ...range(0xd800, 0xdfff), - - /** - * C.6 Inappropriate for plain text - * @link https://tools.ietf.org/html/rfc3454#appendix-C.6 - */ - 0xfff9 /* INTERLINEAR ANNOTATION ANCHOR */, - 0xfffa /* INTERLINEAR ANNOTATION SEPARATOR */, - 0xfffb /* INTERLINEAR ANNOTATION TERMINATOR */, - 0xfffc /* OBJECT REPLACEMENT CHARACTER */, - 0xfffd /* REPLACEMENT CHARACTER */, - - /** - * C.7 Inappropriate for canonical representation - * @link https://tools.ietf.org/html/rfc3454#appendix-C.7 - */ - ...range(0x2ff0, 0x2ffb) /* [IDEOGRAPHIC DESCRIPTION CHARACTERS] */, - - /** - * C.8 Change display properties or are deprecated - * @link https://tools.ietf.org/html/rfc3454#appendix-C.8 - */ - 0x0340 /* COMBINING GRAVE TONE MARK */, - 0x0341 /* COMBINING ACUTE TONE MARK */, - 0x200e /* LEFT-TO-RIGHT MARK */, - 0x200f /* RIGHT-TO-LEFT MARK */, - 0x202a /* LEFT-TO-RIGHT EMBEDDING */, - 0x202b /* RIGHT-TO-LEFT EMBEDDING */, - 0x202c /* POP DIRECTIONAL FORMATTING */, - 0x202d /* LEFT-TO-RIGHT OVERRIDE */, - 0x202e /* RIGHT-TO-LEFT OVERRIDE */, - 0x206a /* INHIBIT SYMMETRIC SWAPPING */, - 0x206b /* ACTIVATE SYMMETRIC SWAPPING */, - 0x206c /* INHIBIT ARABIC FORM SHAPING */, - 0x206d /* ACTIVATE ARABIC FORM SHAPING */, - 0x206e /* NATIONAL DIGIT SHAPES */, - 0x206f /* NOMINAL DIGIT SHAPES */, - - /** - * C.9 Tagging characters - * @link https://tools.ietf.org/html/rfc3454#appendix-C.9 - */ - 0xe0001 /* LANGUAGE TAG */, - ...range(0xe0020, 0xe007f) /* [TAGGING CHARACTERS] */, -]); - -/** - * D.1 Characters with bidirectional property "R" or "AL" - * @link https://tools.ietf.org/html/rfc3454#appendix-D.1 - */ -const bidirectional_r_al = new Set([ - 0x05be, - 0x05c0, - 0x05c3, - ...range(0x05d0, 0x05ea), - ...range(0x05f0, 0x05f4), - 0x061b, - 0x061f, - ...range(0x0621, 0x063a), - ...range(0x0640, 0x064a), - ...range(0x066d, 0x066f), - ...range(0x0671, 0x06d5), - 0x06dd, - ...range(0x06e5, 0x06e6), - ...range(0x06fa, 0x06fe), - ...range(0x0700, 0x070d), - 0x0710, - ...range(0x0712, 0x072c), - ...range(0x0780, 0x07a5), - 0x07b1, - 0x200f, - 0xfb1d, - ...range(0xfb1f, 0xfb28), - ...range(0xfb2a, 0xfb36), - ...range(0xfb38, 0xfb3c), - 0xfb3e, - ...range(0xfb40, 0xfb41), - ...range(0xfb43, 0xfb44), - ...range(0xfb46, 0xfbb1), - ...range(0xfbd3, 0xfd3d), - ...range(0xfd50, 0xfd8f), - ...range(0xfd92, 0xfdc7), - ...range(0xfdf0, 0xfdfc), - ...range(0xfe70, 0xfe74), - ...range(0xfe76, 0xfefc), -]); - -/** - * D.2 Characters with bidirectional property "L" - * @link https://tools.ietf.org/html/rfc3454#appendix-D.2 - */ -const bidirectional_l = new Set([ - ...range(0x0041, 0x005a), - ...range(0x0061, 0x007a), - 0x00aa, - 0x00b5, - 0x00ba, - ...range(0x00c0, 0x00d6), - ...range(0x00d8, 0x00f6), - ...range(0x00f8, 0x0220), - ...range(0x0222, 0x0233), - ...range(0x0250, 0x02ad), - ...range(0x02b0, 0x02b8), - ...range(0x02bb, 0x02c1), - ...range(0x02d0, 0x02d1), - ...range(0x02e0, 0x02e4), - 0x02ee, - 0x037a, - 0x0386, - ...range(0x0388, 0x038a), - 0x038c, - ...range(0x038e, 0x03a1), - ...range(0x03a3, 0x03ce), - ...range(0x03d0, 0x03f5), - ...range(0x0400, 0x0482), - ...range(0x048a, 0x04ce), - ...range(0x04d0, 0x04f5), - ...range(0x04f8, 0x04f9), - ...range(0x0500, 0x050f), - ...range(0x0531, 0x0556), - ...range(0x0559, 0x055f), - ...range(0x0561, 0x0587), - 0x0589, - 0x0903, - ...range(0x0905, 0x0939), - ...range(0x093d, 0x0940), - ...range(0x0949, 0x094c), - 0x0950, - ...range(0x0958, 0x0961), - ...range(0x0964, 0x0970), - ...range(0x0982, 0x0983), - ...range(0x0985, 0x098c), - ...range(0x098f, 0x0990), - ...range(0x0993, 0x09a8), - ...range(0x09aa, 0x09b0), - 0x09b2, - ...range(0x09b6, 0x09b9), - ...range(0x09be, 0x09c0), - ...range(0x09c7, 0x09c8), - ...range(0x09cb, 0x09cc), - 0x09d7, - ...range(0x09dc, 0x09dd), - ...range(0x09df, 0x09e1), - ...range(0x09e6, 0x09f1), - ...range(0x09f4, 0x09fa), - ...range(0x0a05, 0x0a0a), - ...range(0x0a0f, 0x0a10), - ...range(0x0a13, 0x0a28), - ...range(0x0a2a, 0x0a30), - ...range(0x0a32, 0x0a33), - ...range(0x0a35, 0x0a36), - ...range(0x0a38, 0x0a39), - ...range(0x0a3e, 0x0a40), - ...range(0x0a59, 0x0a5c), - 0x0a5e, - ...range(0x0a66, 0x0a6f), - ...range(0x0a72, 0x0a74), - 0x0a83, - ...range(0x0a85, 0x0a8b), - 0x0a8d, - ...range(0x0a8f, 0x0a91), - ...range(0x0a93, 0x0aa8), - ...range(0x0aaa, 0x0ab0), - ...range(0x0ab2, 0x0ab3), - ...range(0x0ab5, 0x0ab9), - ...range(0x0abd, 0x0ac0), - 0x0ac9, - ...range(0x0acb, 0x0acc), - 0x0ad0, - 0x0ae0, - ...range(0x0ae6, 0x0aef), - ...range(0x0b02, 0x0b03), - ...range(0x0b05, 0x0b0c), - ...range(0x0b0f, 0x0b10), - ...range(0x0b13, 0x0b28), - ...range(0x0b2a, 0x0b30), - ...range(0x0b32, 0x0b33), - ...range(0x0b36, 0x0b39), - ...range(0x0b3d, 0x0b3e), - 0x0b40, - ...range(0x0b47, 0x0b48), - ...range(0x0b4b, 0x0b4c), - 0x0b57, - ...range(0x0b5c, 0x0b5d), - ...range(0x0b5f, 0x0b61), - ...range(0x0b66, 0x0b70), - 0x0b83, - ...range(0x0b85, 0x0b8a), - ...range(0x0b8e, 0x0b90), - ...range(0x0b92, 0x0b95), - ...range(0x0b99, 0x0b9a), - 0x0b9c, - ...range(0x0b9e, 0x0b9f), - ...range(0x0ba3, 0x0ba4), - ...range(0x0ba8, 0x0baa), - ...range(0x0bae, 0x0bb5), - ...range(0x0bb7, 0x0bb9), - ...range(0x0bbe, 0x0bbf), - ...range(0x0bc1, 0x0bc2), - ...range(0x0bc6, 0x0bc8), - ...range(0x0bca, 0x0bcc), - 0x0bd7, - ...range(0x0be7, 0x0bf2), - ...range(0x0c01, 0x0c03), - ...range(0x0c05, 0x0c0c), - ...range(0x0c0e, 0x0c10), - ...range(0x0c12, 0x0c28), - ...range(0x0c2a, 0x0c33), - ...range(0x0c35, 0x0c39), - ...range(0x0c41, 0x0c44), - ...range(0x0c60, 0x0c61), - ...range(0x0c66, 0x0c6f), - ...range(0x0c82, 0x0c83), - ...range(0x0c85, 0x0c8c), - ...range(0x0c8e, 0x0c90), - ...range(0x0c92, 0x0ca8), - ...range(0x0caa, 0x0cb3), - ...range(0x0cb5, 0x0cb9), - 0x0cbe, - ...range(0x0cc0, 0x0cc4), - ...range(0x0cc7, 0x0cc8), - ...range(0x0cca, 0x0ccb), - ...range(0x0cd5, 0x0cd6), - 0x0cde, - ...range(0x0ce0, 0x0ce1), - ...range(0x0ce6, 0x0cef), - ...range(0x0d02, 0x0d03), - ...range(0x0d05, 0x0d0c), - ...range(0x0d0e, 0x0d10), - ...range(0x0d12, 0x0d28), - ...range(0x0d2a, 0x0d39), - ...range(0x0d3e, 0x0d40), - ...range(0x0d46, 0x0d48), - ...range(0x0d4a, 0x0d4c), - 0x0d57, - ...range(0x0d60, 0x0d61), - ...range(0x0d66, 0x0d6f), - ...range(0x0d82, 0x0d83), - ...range(0x0d85, 0x0d96), - ...range(0x0d9a, 0x0db1), - ...range(0x0db3, 0x0dbb), - 0x0dbd, - ...range(0x0dc0, 0x0dc6), - ...range(0x0dcf, 0x0dd1), - ...range(0x0dd8, 0x0ddf), - ...range(0x0df2, 0x0df4), - ...range(0x0e01, 0x0e30), - ...range(0x0e32, 0x0e33), - ...range(0x0e40, 0x0e46), - ...range(0x0e4f, 0x0e5b), - ...range(0x0e81, 0x0e82), - 0x0e84, - ...range(0x0e87, 0x0e88), - 0x0e8a, - 0x0e8d, - ...range(0x0e94, 0x0e97), - ...range(0x0e99, 0x0e9f), - ...range(0x0ea1, 0x0ea3), - 0x0ea5, - 0x0ea7, - ...range(0x0eaa, 0x0eab), - ...range(0x0ead, 0x0eb0), - ...range(0x0eb2, 0x0eb3), - 0x0ebd, - ...range(0x0ec0, 0x0ec4), - 0x0ec6, - ...range(0x0ed0, 0x0ed9), - ...range(0x0edc, 0x0edd), - ...range(0x0f00, 0x0f17), - ...range(0x0f1a, 0x0f34), - 0x0f36, - 0x0f38, - ...range(0x0f3e, 0x0f47), - ...range(0x0f49, 0x0f6a), - 0x0f7f, - 0x0f85, - ...range(0x0f88, 0x0f8b), - ...range(0x0fbe, 0x0fc5), - ...range(0x0fc7, 0x0fcc), - 0x0fcf, - ...range(0x1000, 0x1021), - ...range(0x1023, 0x1027), - ...range(0x1029, 0x102a), - 0x102c, - 0x1031, - 0x1038, - ...range(0x1040, 0x1057), - ...range(0x10a0, 0x10c5), - ...range(0x10d0, 0x10f8), - 0x10fb, - ...range(0x1100, 0x1159), - ...range(0x115f, 0x11a2), - ...range(0x11a8, 0x11f9), - ...range(0x1200, 0x1206), - ...range(0x1208, 0x1246), - 0x1248, - ...range(0x124a, 0x124d), - ...range(0x1250, 0x1256), - 0x1258, - ...range(0x125a, 0x125d), - ...range(0x1260, 0x1286), - 0x1288, - ...range(0x128a, 0x128d), - ...range(0x1290, 0x12ae), - 0x12b0, - ...range(0x12b2, 0x12b5), - ...range(0x12b8, 0x12be), - 0x12c0, - ...range(0x12c2, 0x12c5), - ...range(0x12c8, 0x12ce), - ...range(0x12d0, 0x12d6), - ...range(0x12d8, 0x12ee), - ...range(0x12f0, 0x130e), - 0x1310, - ...range(0x1312, 0x1315), - ...range(0x1318, 0x131e), - ...range(0x1320, 0x1346), - ...range(0x1348, 0x135a), - ...range(0x1361, 0x137c), - ...range(0x13a0, 0x13f4), - ...range(0x1401, 0x1676), - ...range(0x1681, 0x169a), - ...range(0x16a0, 0x16f0), - ...range(0x1700, 0x170c), - ...range(0x170e, 0x1711), - ...range(0x1720, 0x1731), - ...range(0x1735, 0x1736), - ...range(0x1740, 0x1751), - ...range(0x1760, 0x176c), - ...range(0x176e, 0x1770), - ...range(0x1780, 0x17b6), - ...range(0x17be, 0x17c5), - ...range(0x17c7, 0x17c8), - ...range(0x17d4, 0x17da), - 0x17dc, - ...range(0x17e0, 0x17e9), - ...range(0x1810, 0x1819), - ...range(0x1820, 0x1877), - ...range(0x1880, 0x18a8), - ...range(0x1e00, 0x1e9b), - ...range(0x1ea0, 0x1ef9), - ...range(0x1f00, 0x1f15), - ...range(0x1f18, 0x1f1d), - ...range(0x1f20, 0x1f45), - ...range(0x1f48, 0x1f4d), - ...range(0x1f50, 0x1f57), - 0x1f59, - 0x1f5b, - 0x1f5d, - ...range(0x1f5f, 0x1f7d), - ...range(0x1f80, 0x1fb4), - ...range(0x1fb6, 0x1fbc), - 0x1fbe, - ...range(0x1fc2, 0x1fc4), - ...range(0x1fc6, 0x1fcc), - ...range(0x1fd0, 0x1fd3), - ...range(0x1fd6, 0x1fdb), - ...range(0x1fe0, 0x1fec), - ...range(0x1ff2, 0x1ff4), - ...range(0x1ff6, 0x1ffc), - 0x200e, - 0x2071, - 0x207f, - 0x2102, - 0x2107, - ...range(0x210a, 0x2113), - 0x2115, - ...range(0x2119, 0x211d), - 0x2124, - 0x2126, - 0x2128, - ...range(0x212a, 0x212d), - ...range(0x212f, 0x2131), - ...range(0x2133, 0x2139), - ...range(0x213d, 0x213f), - ...range(0x2145, 0x2149), - ...range(0x2160, 0x2183), - ...range(0x2336, 0x237a), - 0x2395, - ...range(0x249c, 0x24e9), - ...range(0x3005, 0x3007), - ...range(0x3021, 0x3029), - ...range(0x3031, 0x3035), - ...range(0x3038, 0x303c), - ...range(0x3041, 0x3096), - ...range(0x309d, 0x309f), - ...range(0x30a1, 0x30fa), - ...range(0x30fc, 0x30ff), - ...range(0x3105, 0x312c), - ...range(0x3131, 0x318e), - ...range(0x3190, 0x31b7), - ...range(0x31f0, 0x321c), - ...range(0x3220, 0x3243), - ...range(0x3260, 0x327b), - ...range(0x327f, 0x32b0), - ...range(0x32c0, 0x32cb), - ...range(0x32d0, 0x32fe), - ...range(0x3300, 0x3376), - ...range(0x337b, 0x33dd), - ...range(0x33e0, 0x33fe), - ...range(0x3400, 0x4db5), - ...range(0x4e00, 0x9fa5), - ...range(0xa000, 0xa48c), - ...range(0xac00, 0xd7a3), - ...range(0xd800, 0xfa2d), - ...range(0xfa30, 0xfa6a), - ...range(0xfb00, 0xfb06), - ...range(0xfb13, 0xfb17), - ...range(0xff21, 0xff3a), - ...range(0xff41, 0xff5a), - ...range(0xff66, 0xffbe), - ...range(0xffc2, 0xffc7), - ...range(0xffca, 0xffcf), - ...range(0xffd2, 0xffd7), - ...range(0xffda, 0xffdc), - ...range(0x10300, 0x1031e), - ...range(0x10320, 0x10323), - ...range(0x10330, 0x1034a), - ...range(0x10400, 0x10425), - ...range(0x10428, 0x1044d), - ...range(0x1d000, 0x1d0f5), - ...range(0x1d100, 0x1d126), - ...range(0x1d12a, 0x1d166), - ...range(0x1d16a, 0x1d172), - ...range(0x1d183, 0x1d184), - ...range(0x1d18c, 0x1d1a9), - ...range(0x1d1ae, 0x1d1dd), - ...range(0x1d400, 0x1d454), - ...range(0x1d456, 0x1d49c), - ...range(0x1d49e, 0x1d49f), - 0x1d4a2, - ...range(0x1d4a5, 0x1d4a6), - ...range(0x1d4a9, 0x1d4ac), - ...range(0x1d4ae, 0x1d4b9), - 0x1d4bb, - ...range(0x1d4bd, 0x1d4c0), - ...range(0x1d4c2, 0x1d4c3), - ...range(0x1d4c5, 0x1d505), - ...range(0x1d507, 0x1d50a), - ...range(0x1d50d, 0x1d514), - ...range(0x1d516, 0x1d51c), - ...range(0x1d51e, 0x1d539), - ...range(0x1d53b, 0x1d53e), - ...range(0x1d540, 0x1d544), - 0x1d546, - ...range(0x1d54a, 0x1d550), - ...range(0x1d552, 0x1d6a3), - ...range(0x1d6a8, 0x1d7c9), - ...range(0x20000, 0x2a6d6), - ...range(0x2f800, 0x2fa1d), - ...range(0xf0000, 0xffffd), - ...range(0x100000, 0x10fffd), -]); - -module.exports = { - unassigned_code_points, - commonly_mapped_to_nothing, - non_ASCII_space_characters, - prohibited_characters, - bidirectional_r_al, - bidirectional_l, -}; diff --git a/scripts/node_modules/saslprep/lib/memory-code-points.js b/scripts/node_modules/saslprep/lib/memory-code-points.js deleted file mode 100644 index cb0289c8..00000000 --- a/scripts/node_modules/saslprep/lib/memory-code-points.js +++ /dev/null @@ -1,39 +0,0 @@ -'use strict'; - -const fs = require('fs'); -const path = require('path'); -const bitfield = require('sparse-bitfield'); - -/* eslint-disable-next-line security/detect-non-literal-fs-filename */ -const memory = fs.readFileSync(path.resolve(__dirname, '../code-points.mem')); -let offset = 0; - -/** - * Loads each code points sequence from buffer. - * @returns {bitfield} - */ -function read() { - const size = memory.readUInt32BE(offset); - offset += 4; - - const codepoints = memory.slice(offset, offset + size); - offset += size; - - return bitfield({ buffer: codepoints }); -} - -const unassigned_code_points = read(); -const commonly_mapped_to_nothing = read(); -const non_ASCII_space_characters = read(); -const prohibited_characters = read(); -const bidirectional_r_al = read(); -const bidirectional_l = read(); - -module.exports = { - unassigned_code_points, - commonly_mapped_to_nothing, - non_ASCII_space_characters, - prohibited_characters, - bidirectional_r_al, - bidirectional_l, -}; diff --git a/scripts/node_modules/saslprep/lib/util.js b/scripts/node_modules/saslprep/lib/util.js deleted file mode 100644 index 506bdc99..00000000 --- a/scripts/node_modules/saslprep/lib/util.js +++ /dev/null @@ -1,21 +0,0 @@ -'use strict'; - -/** - * Create an array of numbers. - * @param {number} from - * @param {number} to - * @returns {number[]} - */ -function range(from, to) { - // TODO: make this inlined. - const list = new Array(to - from + 1); - - for (let i = 0; i < list.length; i += 1) { - list[i] = from + i; - } - return list; -} - -module.exports = { - range, -}; diff --git a/scripts/node_modules/saslprep/package.json b/scripts/node_modules/saslprep/package.json deleted file mode 100644 index 8d894e04..00000000 --- a/scripts/node_modules/saslprep/package.json +++ /dev/null @@ -1,100 +0,0 @@ -{ - "_from": "saslprep@^1.0.0", - "_id": "saslprep@1.0.3", - "_inBundle": false, - "_integrity": "sha512-/MY/PEMbk2SuY5sScONwhUDsV2p77Znkb/q3nSVstq/yQzYJOH/Azh29p9oJLsl3LnQwSvZDKagDGBsBwSooag==", - "_location": "/saslprep", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "saslprep@^1.0.0", - "name": "saslprep", - "escapedName": "saslprep", - "rawSpec": "^1.0.0", - "saveSpec": null, - "fetchSpec": "^1.0.0" - }, - "_requiredBy": [ - "/mongodb" - ], - "_resolved": "https://registry.npmjs.org/saslprep/-/saslprep-1.0.3.tgz", - "_shasum": "4c02f946b56cf54297e347ba1093e7acac4cf226", - "_spec": "saslprep@^1.0.0", - "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/node_modules/mongodb", - "author": { - "name": "Dmitry Tsvettsikh", - "email": "me@reklatsmasters.com" - }, - "bugs": { - "url": "https://github.com/reklatsmasters/saslprep/issues" - }, - "bundleDependencies": false, - "dependencies": { - "sparse-bitfield": "^3.0.3" - }, - "deprecated": false, - "description": "SASLprep: Stringprep Profile for User Names and Passwords, rfc4013.", - "devDependencies": { - "@nodertc/eslint-config": "^0.2.1", - "eslint": "^5.16.0", - "jest": "^23.6.0", - "prettier": "^1.14.3" - }, - "engines": { - "node": ">=6" - }, - "eslintConfig": { - "extends": "@nodertc", - "rules": { - "camelcase": "off", - "no-continue": "off" - }, - "overrides": [ - { - "files": [ - "test/*.js" - ], - "env": { - "jest": true - }, - "rules": { - "require-jsdoc": "off" - } - } - ] - }, - "homepage": "https://github.com/reklatsmasters/saslprep#readme", - "jest": { - "modulePaths": [ - "" - ], - "testMatch": [ - "**/test/*.js" - ], - "testPathIgnorePatterns": [ - "/node_modules/" - ] - }, - "keywords": [ - "sasl", - "saslprep", - "stringprep", - "rfc4013", - "4013" - ], - "license": "MIT", - "main": "index.js", - "name": "saslprep", - "repository": { - "type": "git", - "url": "git+https://github.com/reklatsmasters/saslprep.git" - }, - "scripts": { - "gen-code-points": "node generate-code-points.js > code-points.mem", - "lint": "npx eslint --quiet .", - "test": "npm run lint && npm run unit-test", - "unit-test": "npx jest" - }, - "version": "1.0.3" -} diff --git a/scripts/node_modules/saslprep/readme.md b/scripts/node_modules/saslprep/readme.md deleted file mode 100644 index 8ff3d70d..00000000 --- a/scripts/node_modules/saslprep/readme.md +++ /dev/null @@ -1,31 +0,0 @@ -# saslprep -[![Build Status](https://travis-ci.org/reklatsmasters/saslprep.svg?branch=master)](https://travis-ci.org/reklatsmasters/saslprep) -[![npm](https://img.shields.io/npm/v/saslprep.svg)](https://npmjs.org/package/saslprep) -[![node](https://img.shields.io/node/v/saslprep.svg)](https://npmjs.org/package/saslprep) -[![license](https://img.shields.io/npm/l/saslprep.svg)](https://npmjs.org/package/saslprep) -[![downloads](https://img.shields.io/npm/dm/saslprep.svg)](https://npmjs.org/package/saslprep) - -Stringprep Profile for User Names and Passwords, [rfc4013](https://tools.ietf.org/html/rfc4013) - -### Usage - -```js -const saslprep = require('saslprep') - -saslprep('password\u00AD') // password -saslprep('password\u0007') // Error: prohibited character -``` - -### API - -##### `saslprep(input: String, opts: Options): String` - -Normalize user name or password. - -##### `Options.allowUnassigned: bool` - -A special behavior for unassigned code points, see https://tools.ietf.org/html/rfc4013#section-2.5. Disabled by default. - -## License - -MIT, 2017-2019 (c) Dmitriy Tsvettsikh diff --git a/scripts/node_modules/saslprep/test/index.js b/scripts/node_modules/saslprep/test/index.js deleted file mode 100644 index 80c71af5..00000000 --- a/scripts/node_modules/saslprep/test/index.js +++ /dev/null @@ -1,76 +0,0 @@ -'use strict'; - -const saslprep = require('..'); - -const chr = String.fromCodePoint; - -test('should work with liatin letters', () => { - const str = 'user'; - expect(saslprep(str)).toEqual(str); -}); - -test('should work be case preserved', () => { - const str = 'USER'; - expect(saslprep(str)).toEqual(str); -}); - -test('should work with high code points (> U+FFFF)', () => { - const str = '\uD83D\uDE00'; - expect(saslprep(str, { allowUnassigned: true })).toEqual(str); -}); - -test('should remove `mapped to nothing` characters', () => { - expect(saslprep('I\u00ADX')).toEqual('IX'); -}); - -test('should replace `Non-ASCII space characters` with space', () => { - expect(saslprep('a\u00A0b')).toEqual('a\u0020b'); -}); - -test('should normalize as NFKC', () => { - expect(saslprep('\u00AA')).toEqual('a'); - expect(saslprep('\u2168')).toEqual('IX'); -}); - -test('should throws when prohibited characters', () => { - // C.2.1 ASCII control characters - expect(() => saslprep('a\u007Fb')).toThrow(); - - // C.2.2 Non-ASCII control characters - expect(() => saslprep('a\u06DDb')).toThrow(); - - // C.3 Private use - expect(() => saslprep('a\uE000b')).toThrow(); - - // C.4 Non-character code points - expect(() => saslprep(`a${chr(0x1fffe)}b`)).toThrow(); - - // C.5 Surrogate codes - expect(() => saslprep('a\uD800b')).toThrow(); - - // C.6 Inappropriate for plain text - expect(() => saslprep('a\uFFF9b')).toThrow(); - - // C.7 Inappropriate for canonical representation - expect(() => saslprep('a\u2FF0b')).toThrow(); - - // C.8 Change display properties or are deprecated - expect(() => saslprep('a\u200Eb')).toThrow(); - - // C.9 Tagging characters - expect(() => saslprep(`a${chr(0xe0001)}b`)).toThrow(); -}); - -test('should not containt RandALCat and LCat bidi', () => { - expect(() => saslprep('a\u06DD\u00AAb')).toThrow(); -}); - -test('RandALCat should be first and last', () => { - expect(() => saslprep('\u0627\u0031\u0628')).not.toThrow(); - expect(() => saslprep('\u0627\u0031')).toThrow(); -}); - -test('should handle unassigned code points', () => { - expect(() => saslprep('a\u0487')).toThrow(); - expect(() => saslprep('a\u0487', { allowUnassigned: true })).not.toThrow(); -}); diff --git a/scripts/node_modules/saslprep/test/util.js b/scripts/node_modules/saslprep/test/util.js deleted file mode 100644 index 355db3f8..00000000 --- a/scripts/node_modules/saslprep/test/util.js +++ /dev/null @@ -1,16 +0,0 @@ -'use strict'; - -const { setFlagsFromString } = require('v8'); -const { range } = require('../lib/util'); - -// 984 by default. -setFlagsFromString('--stack_size=500'); - -test('should work', () => { - const list = range(1, 3); - expect(list).toEqual([1, 2, 3]); -}); - -test('should work for large ranges', () => { - expect(() => range(1, 1e6)).not.toThrow(); -}); diff --git a/scripts/node_modules/semver/CHANGELOG.md b/scripts/node_modules/semver/CHANGELOG.md deleted file mode 100644 index 66304fdd..00000000 --- a/scripts/node_modules/semver/CHANGELOG.md +++ /dev/null @@ -1,39 +0,0 @@ -# changes log - -## 5.7 - -* Add `minVersion` method - -## 5.6 - -* Move boolean `loose` param to an options object, with - backwards-compatibility protection. -* Add ability to opt out of special prerelease version handling with - the `includePrerelease` option flag. - -## 5.5 - -* Add version coercion capabilities - -## 5.4 - -* Add intersection checking - -## 5.3 - -* Add `minSatisfying` method - -## 5.2 - -* Add `prerelease(v)` that returns prerelease components - -## 5.1 - -* Add Backus-Naur for ranges -* Remove excessively cute inspection methods - -## 5.0 - -* Remove AMD/Browserified build artifacts -* Fix ltr and gtr when using the `*` range -* Fix for range `*` with a prerelease identifier diff --git a/scripts/node_modules/semver/LICENSE b/scripts/node_modules/semver/LICENSE deleted file mode 100644 index 19129e31..00000000 --- a/scripts/node_modules/semver/LICENSE +++ /dev/null @@ -1,15 +0,0 @@ -The ISC License - -Copyright (c) Isaac Z. Schlueter and Contributors - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted, provided that the above -copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR -IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/scripts/node_modules/semver/README.md b/scripts/node_modules/semver/README.md deleted file mode 100644 index f8dfa5a0..00000000 --- a/scripts/node_modules/semver/README.md +++ /dev/null @@ -1,412 +0,0 @@ -semver(1) -- The semantic versioner for npm -=========================================== - -## Install - -```bash -npm install --save semver -```` - -## Usage - -As a node module: - -```js -const semver = require('semver') - -semver.valid('1.2.3') // '1.2.3' -semver.valid('a.b.c') // null -semver.clean(' =v1.2.3 ') // '1.2.3' -semver.satisfies('1.2.3', '1.x || >=2.5.0 || 5.0.0 - 7.2.3') // true -semver.gt('1.2.3', '9.8.7') // false -semver.lt('1.2.3', '9.8.7') // true -semver.minVersion('>=1.0.0') // '1.0.0' -semver.valid(semver.coerce('v2')) // '2.0.0' -semver.valid(semver.coerce('42.6.7.9.3-alpha')) // '42.6.7' -``` - -As a command-line utility: - -``` -$ semver -h - -A JavaScript implementation of the https://semver.org/ specification -Copyright Isaac Z. Schlueter - -Usage: semver [options] [ [...]] -Prints valid versions sorted by SemVer precedence - -Options: --r --range - Print versions that match the specified range. - --i --increment [] - Increment a version by the specified level. Level can - be one of: major, minor, patch, premajor, preminor, - prepatch, or prerelease. Default level is 'patch'. - Only one version may be specified. - ---preid - Identifier to be used to prefix premajor, preminor, - prepatch or prerelease version increments. - --l --loose - Interpret versions and ranges loosely - --p --include-prerelease - Always include prerelease versions in range matching - --c --coerce - Coerce a string into SemVer if possible - (does not imply --loose) - -Program exits successfully if any valid version satisfies -all supplied ranges, and prints all satisfying versions. - -If no satisfying versions are found, then exits failure. - -Versions are printed in ascending order, so supplying -multiple versions to the utility will just sort them. -``` - -## Versions - -A "version" is described by the `v2.0.0` specification found at -. - -A leading `"="` or `"v"` character is stripped off and ignored. - -## Ranges - -A `version range` is a set of `comparators` which specify versions -that satisfy the range. - -A `comparator` is composed of an `operator` and a `version`. The set -of primitive `operators` is: - -* `<` Less than -* `<=` Less than or equal to -* `>` Greater than -* `>=` Greater than or equal to -* `=` Equal. If no operator is specified, then equality is assumed, - so this operator is optional, but MAY be included. - -For example, the comparator `>=1.2.7` would match the versions -`1.2.7`, `1.2.8`, `2.5.3`, and `1.3.9`, but not the versions `1.2.6` -or `1.1.0`. - -Comparators can be joined by whitespace to form a `comparator set`, -which is satisfied by the **intersection** of all of the comparators -it includes. - -A range is composed of one or more comparator sets, joined by `||`. A -version matches a range if and only if every comparator in at least -one of the `||`-separated comparator sets is satisfied by the version. - -For example, the range `>=1.2.7 <1.3.0` would match the versions -`1.2.7`, `1.2.8`, and `1.2.99`, but not the versions `1.2.6`, `1.3.0`, -or `1.1.0`. - -The range `1.2.7 || >=1.2.9 <2.0.0` would match the versions `1.2.7`, -`1.2.9`, and `1.4.6`, but not the versions `1.2.8` or `2.0.0`. - -### Prerelease Tags - -If a version has a prerelease tag (for example, `1.2.3-alpha.3`) then -it will only be allowed to satisfy comparator sets if at least one -comparator with the same `[major, minor, patch]` tuple also has a -prerelease tag. - -For example, the range `>1.2.3-alpha.3` would be allowed to match the -version `1.2.3-alpha.7`, but it would *not* be satisfied by -`3.4.5-alpha.9`, even though `3.4.5-alpha.9` is technically "greater -than" `1.2.3-alpha.3` according to the SemVer sort rules. The version -range only accepts prerelease tags on the `1.2.3` version. The -version `3.4.5` *would* satisfy the range, because it does not have a -prerelease flag, and `3.4.5` is greater than `1.2.3-alpha.7`. - -The purpose for this behavior is twofold. First, prerelease versions -frequently are updated very quickly, and contain many breaking changes -that are (by the author's design) not yet fit for public consumption. -Therefore, by default, they are excluded from range matching -semantics. - -Second, a user who has opted into using a prerelease version has -clearly indicated the intent to use *that specific* set of -alpha/beta/rc versions. By including a prerelease tag in the range, -the user is indicating that they are aware of the risk. However, it -is still not appropriate to assume that they have opted into taking a -similar risk on the *next* set of prerelease versions. - -Note that this behavior can be suppressed (treating all prerelease -versions as if they were normal versions, for the purpose of range -matching) by setting the `includePrerelease` flag on the options -object to any -[functions](https://github.com/npm/node-semver#functions) that do -range matching. - -#### Prerelease Identifiers - -The method `.inc` takes an additional `identifier` string argument that -will append the value of the string as a prerelease identifier: - -```javascript -semver.inc('1.2.3', 'prerelease', 'beta') -// '1.2.4-beta.0' -``` - -command-line example: - -```bash -$ semver 1.2.3 -i prerelease --preid beta -1.2.4-beta.0 -``` - -Which then can be used to increment further: - -```bash -$ semver 1.2.4-beta.0 -i prerelease -1.2.4-beta.1 -``` - -### Advanced Range Syntax - -Advanced range syntax desugars to primitive comparators in -deterministic ways. - -Advanced ranges may be combined in the same way as primitive -comparators using white space or `||`. - -#### Hyphen Ranges `X.Y.Z - A.B.C` - -Specifies an inclusive set. - -* `1.2.3 - 2.3.4` := `>=1.2.3 <=2.3.4` - -If a partial version is provided as the first version in the inclusive -range, then the missing pieces are replaced with zeroes. - -* `1.2 - 2.3.4` := `>=1.2.0 <=2.3.4` - -If a partial version is provided as the second version in the -inclusive range, then all versions that start with the supplied parts -of the tuple are accepted, but nothing that would be greater than the -provided tuple parts. - -* `1.2.3 - 2.3` := `>=1.2.3 <2.4.0` -* `1.2.3 - 2` := `>=1.2.3 <3.0.0` - -#### X-Ranges `1.2.x` `1.X` `1.2.*` `*` - -Any of `X`, `x`, or `*` may be used to "stand in" for one of the -numeric values in the `[major, minor, patch]` tuple. - -* `*` := `>=0.0.0` (Any version satisfies) -* `1.x` := `>=1.0.0 <2.0.0` (Matching major version) -* `1.2.x` := `>=1.2.0 <1.3.0` (Matching major and minor versions) - -A partial version range is treated as an X-Range, so the special -character is in fact optional. - -* `""` (empty string) := `*` := `>=0.0.0` -* `1` := `1.x.x` := `>=1.0.0 <2.0.0` -* `1.2` := `1.2.x` := `>=1.2.0 <1.3.0` - -#### Tilde Ranges `~1.2.3` `~1.2` `~1` - -Allows patch-level changes if a minor version is specified on the -comparator. Allows minor-level changes if not. - -* `~1.2.3` := `>=1.2.3 <1.(2+1).0` := `>=1.2.3 <1.3.0` -* `~1.2` := `>=1.2.0 <1.(2+1).0` := `>=1.2.0 <1.3.0` (Same as `1.2.x`) -* `~1` := `>=1.0.0 <(1+1).0.0` := `>=1.0.0 <2.0.0` (Same as `1.x`) -* `~0.2.3` := `>=0.2.3 <0.(2+1).0` := `>=0.2.3 <0.3.0` -* `~0.2` := `>=0.2.0 <0.(2+1).0` := `>=0.2.0 <0.3.0` (Same as `0.2.x`) -* `~0` := `>=0.0.0 <(0+1).0.0` := `>=0.0.0 <1.0.0` (Same as `0.x`) -* `~1.2.3-beta.2` := `>=1.2.3-beta.2 <1.3.0` Note that prereleases in - the `1.2.3` version will be allowed, if they are greater than or - equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but - `1.2.4-beta.2` would not, because it is a prerelease of a - different `[major, minor, patch]` tuple. - -#### Caret Ranges `^1.2.3` `^0.2.5` `^0.0.4` - -Allows changes that do not modify the left-most non-zero digit in the -`[major, minor, patch]` tuple. In other words, this allows patch and -minor updates for versions `1.0.0` and above, patch updates for -versions `0.X >=0.1.0`, and *no* updates for versions `0.0.X`. - -Many authors treat a `0.x` version as if the `x` were the major -"breaking-change" indicator. - -Caret ranges are ideal when an author may make breaking changes -between `0.2.4` and `0.3.0` releases, which is a common practice. -However, it presumes that there will *not* be breaking changes between -`0.2.4` and `0.2.5`. It allows for changes that are presumed to be -additive (but non-breaking), according to commonly observed practices. - -* `^1.2.3` := `>=1.2.3 <2.0.0` -* `^0.2.3` := `>=0.2.3 <0.3.0` -* `^0.0.3` := `>=0.0.3 <0.0.4` -* `^1.2.3-beta.2` := `>=1.2.3-beta.2 <2.0.0` Note that prereleases in - the `1.2.3` version will be allowed, if they are greater than or - equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but - `1.2.4-beta.2` would not, because it is a prerelease of a - different `[major, minor, patch]` tuple. -* `^0.0.3-beta` := `>=0.0.3-beta <0.0.4` Note that prereleases in the - `0.0.3` version *only* will be allowed, if they are greater than or - equal to `beta`. So, `0.0.3-pr.2` would be allowed. - -When parsing caret ranges, a missing `patch` value desugars to the -number `0`, but will allow flexibility within that value, even if the -major and minor versions are both `0`. - -* `^1.2.x` := `>=1.2.0 <2.0.0` -* `^0.0.x` := `>=0.0.0 <0.1.0` -* `^0.0` := `>=0.0.0 <0.1.0` - -A missing `minor` and `patch` values will desugar to zero, but also -allow flexibility within those values, even if the major version is -zero. - -* `^1.x` := `>=1.0.0 <2.0.0` -* `^0.x` := `>=0.0.0 <1.0.0` - -### Range Grammar - -Putting all this together, here is a Backus-Naur grammar for ranges, -for the benefit of parser authors: - -```bnf -range-set ::= range ( logical-or range ) * -logical-or ::= ( ' ' ) * '||' ( ' ' ) * -range ::= hyphen | simple ( ' ' simple ) * | '' -hyphen ::= partial ' - ' partial -simple ::= primitive | partial | tilde | caret -primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial -partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? -xr ::= 'x' | 'X' | '*' | nr -nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * -tilde ::= '~' partial -caret ::= '^' partial -qualifier ::= ( '-' pre )? ( '+' build )? -pre ::= parts -build ::= parts -parts ::= part ( '.' part ) * -part ::= nr | [-0-9A-Za-z]+ -``` - -## Functions - -All methods and classes take a final `options` object argument. All -options in this object are `false` by default. The options supported -are: - -- `loose` Be more forgiving about not-quite-valid semver strings. - (Any resulting output will always be 100% strict compliant, of - course.) For backwards compatibility reasons, if the `options` - argument is a boolean value instead of an object, it is interpreted - to be the `loose` param. -- `includePrerelease` Set to suppress the [default - behavior](https://github.com/npm/node-semver#prerelease-tags) of - excluding prerelease tagged versions from ranges unless they are - explicitly opted into. - -Strict-mode Comparators and Ranges will be strict about the SemVer -strings that they parse. - -* `valid(v)`: Return the parsed version, or null if it's not valid. -* `inc(v, release)`: Return the version incremented by the release - type (`major`, `premajor`, `minor`, `preminor`, `patch`, - `prepatch`, or `prerelease`), or null if it's not valid - * `premajor` in one call will bump the version up to the next major - version and down to a prerelease of that major version. - `preminor`, and `prepatch` work the same way. - * If called from a non-prerelease version, the `prerelease` will work the - same as `prepatch`. It increments the patch version, then makes a - prerelease. If the input version is already a prerelease it simply - increments it. -* `prerelease(v)`: Returns an array of prerelease components, or null - if none exist. Example: `prerelease('1.2.3-alpha.1') -> ['alpha', 1]` -* `major(v)`: Return the major version number. -* `minor(v)`: Return the minor version number. -* `patch(v)`: Return the patch version number. -* `intersects(r1, r2, loose)`: Return true if the two supplied ranges - or comparators intersect. -* `parse(v)`: Attempt to parse a string as a semantic version, returning either - a `SemVer` object or `null`. - -### Comparison - -* `gt(v1, v2)`: `v1 > v2` -* `gte(v1, v2)`: `v1 >= v2` -* `lt(v1, v2)`: `v1 < v2` -* `lte(v1, v2)`: `v1 <= v2` -* `eq(v1, v2)`: `v1 == v2` This is true if they're logically equivalent, - even if they're not the exact same string. You already know how to - compare strings. -* `neq(v1, v2)`: `v1 != v2` The opposite of `eq`. -* `cmp(v1, comparator, v2)`: Pass in a comparison string, and it'll call - the corresponding function above. `"==="` and `"!=="` do simple - string comparison, but are included for completeness. Throws if an - invalid comparison string is provided. -* `compare(v1, v2)`: Return `0` if `v1 == v2`, or `1` if `v1` is greater, or `-1` if - `v2` is greater. Sorts in ascending order if passed to `Array.sort()`. -* `rcompare(v1, v2)`: The reverse of compare. Sorts an array of versions - in descending order when passed to `Array.sort()`. -* `diff(v1, v2)`: Returns difference between two versions by the release type - (`major`, `premajor`, `minor`, `preminor`, `patch`, `prepatch`, or `prerelease`), - or null if the versions are the same. - -### Comparators - -* `intersects(comparator)`: Return true if the comparators intersect - -### Ranges - -* `validRange(range)`: Return the valid range or null if it's not valid -* `satisfies(version, range)`: Return true if the version satisfies the - range. -* `maxSatisfying(versions, range)`: Return the highest version in the list - that satisfies the range, or `null` if none of them do. -* `minSatisfying(versions, range)`: Return the lowest version in the list - that satisfies the range, or `null` if none of them do. -* `minVersion(range)`: Return the lowest version that can possibly match - the given range. -* `gtr(version, range)`: Return `true` if version is greater than all the - versions possible in the range. -* `ltr(version, range)`: Return `true` if version is less than all the - versions possible in the range. -* `outside(version, range, hilo)`: Return true if the version is outside - the bounds of the range in either the high or low direction. The - `hilo` argument must be either the string `'>'` or `'<'`. (This is - the function called by `gtr` and `ltr`.) -* `intersects(range)`: Return true if any of the ranges comparators intersect - -Note that, since ranges may be non-contiguous, a version might not be -greater than a range, less than a range, *or* satisfy a range! For -example, the range `1.2 <1.2.9 || >2.0.0` would have a hole from `1.2.9` -until `2.0.0`, so the version `1.2.10` would not be greater than the -range (because `2.0.1` satisfies, which is higher), nor less than the -range (since `1.2.8` satisfies, which is lower), and it also does not -satisfy the range. - -If you want to know if a version satisfies or does not satisfy a -range, use the `satisfies(version, range)` function. - -### Coercion - -* `coerce(version)`: Coerces a string to semver if possible - -This aims to provide a very forgiving translation of a non-semver string to -semver. It looks for the first digit in a string, and consumes all -remaining characters which satisfy at least a partial semver (e.g., `1`, -`1.2`, `1.2.3`) up to the max permitted length (256 characters). Longer -versions are simply truncated (`4.6.3.9.2-alpha2` becomes `4.6.3`). All -surrounding text is simply ignored (`v3.4 replaces v3.3.1` becomes -`3.4.0`). Only text which lacks digits will fail coercion (`version one` -is not valid). The maximum length for any semver component considered for -coercion is 16 characters; longer components will be ignored -(`10000000000000000.4.7.4` becomes `4.7.4`). The maximum value for any -semver component is `Number.MAX_SAFE_INTEGER || (2**53 - 1)`; higher value -components are invalid (`9999999999999999.4.7.4` is likely invalid). diff --git a/scripts/node_modules/semver/bin/semver b/scripts/node_modules/semver/bin/semver deleted file mode 100755 index 801e77f1..00000000 --- a/scripts/node_modules/semver/bin/semver +++ /dev/null @@ -1,160 +0,0 @@ -#!/usr/bin/env node -// Standalone semver comparison program. -// Exits successfully and prints matching version(s) if -// any supplied version is valid and passes all tests. - -var argv = process.argv.slice(2) - -var versions = [] - -var range = [] - -var inc = null - -var version = require('../package.json').version - -var loose = false - -var includePrerelease = false - -var coerce = false - -var identifier - -var semver = require('../semver') - -var reverse = false - -var options = {} - -main() - -function main () { - if (!argv.length) return help() - while (argv.length) { - var a = argv.shift() - var indexOfEqualSign = a.indexOf('=') - if (indexOfEqualSign !== -1) { - a = a.slice(0, indexOfEqualSign) - argv.unshift(a.slice(indexOfEqualSign + 1)) - } - switch (a) { - case '-rv': case '-rev': case '--rev': case '--reverse': - reverse = true - break - case '-l': case '--loose': - loose = true - break - case '-p': case '--include-prerelease': - includePrerelease = true - break - case '-v': case '--version': - versions.push(argv.shift()) - break - case '-i': case '--inc': case '--increment': - switch (argv[0]) { - case 'major': case 'minor': case 'patch': case 'prerelease': - case 'premajor': case 'preminor': case 'prepatch': - inc = argv.shift() - break - default: - inc = 'patch' - break - } - break - case '--preid': - identifier = argv.shift() - break - case '-r': case '--range': - range.push(argv.shift()) - break - case '-c': case '--coerce': - coerce = true - break - case '-h': case '--help': case '-?': - return help() - default: - versions.push(a) - break - } - } - - var options = { loose: loose, includePrerelease: includePrerelease } - - versions = versions.map(function (v) { - return coerce ? (semver.coerce(v) || { version: v }).version : v - }).filter(function (v) { - return semver.valid(v) - }) - if (!versions.length) return fail() - if (inc && (versions.length !== 1 || range.length)) { return failInc() } - - for (var i = 0, l = range.length; i < l; i++) { - versions = versions.filter(function (v) { - return semver.satisfies(v, range[i], options) - }) - if (!versions.length) return fail() - } - return success(versions) -} - -function failInc () { - console.error('--inc can only be used on a single version with no range') - fail() -} - -function fail () { process.exit(1) } - -function success () { - var compare = reverse ? 'rcompare' : 'compare' - versions.sort(function (a, b) { - return semver[compare](a, b, options) - }).map(function (v) { - return semver.clean(v, options) - }).map(function (v) { - return inc ? semver.inc(v, inc, options, identifier) : v - }).forEach(function (v, i, _) { console.log(v) }) -} - -function help () { - console.log(['SemVer ' + version, - '', - 'A JavaScript implementation of the https://semver.org/ specification', - 'Copyright Isaac Z. Schlueter', - '', - 'Usage: semver [options] [ [...]]', - 'Prints valid versions sorted by SemVer precedence', - '', - 'Options:', - '-r --range ', - ' Print versions that match the specified range.', - '', - '-i --increment []', - ' Increment a version by the specified level. Level can', - ' be one of: major, minor, patch, premajor, preminor,', - " prepatch, or prerelease. Default level is 'patch'.", - ' Only one version may be specified.', - '', - '--preid ', - ' Identifier to be used to prefix premajor, preminor,', - ' prepatch or prerelease version increments.', - '', - '-l --loose', - ' Interpret versions and ranges loosely', - '', - '-p --include-prerelease', - ' Always include prerelease versions in range matching', - '', - '-c --coerce', - ' Coerce a string into SemVer if possible', - ' (does not imply --loose)', - '', - 'Program exits successfully if any valid version satisfies', - 'all supplied ranges, and prints all satisfying versions.', - '', - 'If no satisfying versions are found, then exits failure.', - '', - 'Versions are printed in ascending order, so supplying', - 'multiple versions to the utility will just sort them.' - ].join('\n')) -} diff --git a/scripts/node_modules/semver/package.json b/scripts/node_modules/semver/package.json deleted file mode 100644 index dc3f686a..00000000 --- a/scripts/node_modules/semver/package.json +++ /dev/null @@ -1,60 +0,0 @@ -{ - "_from": "semver@^5.1.0", - "_id": "semver@5.7.1", - "_inBundle": false, - "_integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==", - "_location": "/semver", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "semver@^5.1.0", - "name": "semver", - "escapedName": "semver", - "rawSpec": "^5.1.0", - "saveSpec": null, - "fetchSpec": "^5.1.0" - }, - "_requiredBy": [ - "/require_optional" - ], - "_resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz", - "_shasum": "a954f931aeba508d307bbf069eff0c01c96116f7", - "_spec": "semver@^5.1.0", - "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/node_modules/require_optional", - "bin": { - "semver": "./bin/semver" - }, - "bugs": { - "url": "https://github.com/npm/node-semver/issues" - }, - "bundleDependencies": false, - "deprecated": false, - "description": "The semantic version parser used by npm.", - "devDependencies": { - "tap": "^13.0.0-rc.18" - }, - "files": [ - "bin", - "range.bnf", - "semver.js" - ], - "homepage": "https://github.com/npm/node-semver#readme", - "license": "ISC", - "main": "semver.js", - "name": "semver", - "repository": { - "type": "git", - "url": "git+https://github.com/npm/node-semver.git" - }, - "scripts": { - "postpublish": "git push origin --all; git push origin --tags", - "postversion": "npm publish", - "preversion": "npm test", - "test": "tap" - }, - "tap": { - "check-coverage": true - }, - "version": "5.7.1" -} diff --git a/scripts/node_modules/semver/range.bnf b/scripts/node_modules/semver/range.bnf deleted file mode 100644 index d4c6ae0d..00000000 --- a/scripts/node_modules/semver/range.bnf +++ /dev/null @@ -1,16 +0,0 @@ -range-set ::= range ( logical-or range ) * -logical-or ::= ( ' ' ) * '||' ( ' ' ) * -range ::= hyphen | simple ( ' ' simple ) * | '' -hyphen ::= partial ' - ' partial -simple ::= primitive | partial | tilde | caret -primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial -partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? -xr ::= 'x' | 'X' | '*' | nr -nr ::= '0' | [1-9] ( [0-9] ) * -tilde ::= '~' partial -caret ::= '^' partial -qualifier ::= ( '-' pre )? ( '+' build )? -pre ::= parts -build ::= parts -parts ::= part ( '.' part ) * -part ::= nr | [-0-9A-Za-z]+ diff --git a/scripts/node_modules/semver/semver.js b/scripts/node_modules/semver/semver.js deleted file mode 100644 index d315d5d6..00000000 --- a/scripts/node_modules/semver/semver.js +++ /dev/null @@ -1,1483 +0,0 @@ -exports = module.exports = SemVer - -var debug -/* istanbul ignore next */ -if (typeof process === 'object' && - process.env && - process.env.NODE_DEBUG && - /\bsemver\b/i.test(process.env.NODE_DEBUG)) { - debug = function () { - var args = Array.prototype.slice.call(arguments, 0) - args.unshift('SEMVER') - console.log.apply(console, args) - } -} else { - debug = function () {} -} - -// Note: this is the semver.org version of the spec that it implements -// Not necessarily the package version of this code. -exports.SEMVER_SPEC_VERSION = '2.0.0' - -var MAX_LENGTH = 256 -var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || - /* istanbul ignore next */ 9007199254740991 - -// Max safe segment length for coercion. -var MAX_SAFE_COMPONENT_LENGTH = 16 - -// The actual regexps go on exports.re -var re = exports.re = [] -var src = exports.src = [] -var R = 0 - -// The following Regular Expressions can be used for tokenizing, -// validating, and parsing SemVer version strings. - -// ## Numeric Identifier -// A single `0`, or a non-zero digit followed by zero or more digits. - -var NUMERICIDENTIFIER = R++ -src[NUMERICIDENTIFIER] = '0|[1-9]\\d*' -var NUMERICIDENTIFIERLOOSE = R++ -src[NUMERICIDENTIFIERLOOSE] = '[0-9]+' - -// ## Non-numeric Identifier -// Zero or more digits, followed by a letter or hyphen, and then zero or -// more letters, digits, or hyphens. - -var NONNUMERICIDENTIFIER = R++ -src[NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*' - -// ## Main Version -// Three dot-separated numeric identifiers. - -var MAINVERSION = R++ -src[MAINVERSION] = '(' + src[NUMERICIDENTIFIER] + ')\\.' + - '(' + src[NUMERICIDENTIFIER] + ')\\.' + - '(' + src[NUMERICIDENTIFIER] + ')' - -var MAINVERSIONLOOSE = R++ -src[MAINVERSIONLOOSE] = '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + - '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + - '(' + src[NUMERICIDENTIFIERLOOSE] + ')' - -// ## Pre-release Version Identifier -// A numeric identifier, or a non-numeric identifier. - -var PRERELEASEIDENTIFIER = R++ -src[PRERELEASEIDENTIFIER] = '(?:' + src[NUMERICIDENTIFIER] + - '|' + src[NONNUMERICIDENTIFIER] + ')' - -var PRERELEASEIDENTIFIERLOOSE = R++ -src[PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[NUMERICIDENTIFIERLOOSE] + - '|' + src[NONNUMERICIDENTIFIER] + ')' - -// ## Pre-release Version -// Hyphen, followed by one or more dot-separated pre-release version -// identifiers. - -var PRERELEASE = R++ -src[PRERELEASE] = '(?:-(' + src[PRERELEASEIDENTIFIER] + - '(?:\\.' + src[PRERELEASEIDENTIFIER] + ')*))' - -var PRERELEASELOOSE = R++ -src[PRERELEASELOOSE] = '(?:-?(' + src[PRERELEASEIDENTIFIERLOOSE] + - '(?:\\.' + src[PRERELEASEIDENTIFIERLOOSE] + ')*))' - -// ## Build Metadata Identifier -// Any combination of digits, letters, or hyphens. - -var BUILDIDENTIFIER = R++ -src[BUILDIDENTIFIER] = '[0-9A-Za-z-]+' - -// ## Build Metadata -// Plus sign, followed by one or more period-separated build metadata -// identifiers. - -var BUILD = R++ -src[BUILD] = '(?:\\+(' + src[BUILDIDENTIFIER] + - '(?:\\.' + src[BUILDIDENTIFIER] + ')*))' - -// ## Full Version String -// A main version, followed optionally by a pre-release version and -// build metadata. - -// Note that the only major, minor, patch, and pre-release sections of -// the version string are capturing groups. The build metadata is not a -// capturing group, because it should not ever be used in version -// comparison. - -var FULL = R++ -var FULLPLAIN = 'v?' + src[MAINVERSION] + - src[PRERELEASE] + '?' + - src[BUILD] + '?' - -src[FULL] = '^' + FULLPLAIN + '$' - -// like full, but allows v1.2.3 and =1.2.3, which people do sometimes. -// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty -// common in the npm registry. -var LOOSEPLAIN = '[v=\\s]*' + src[MAINVERSIONLOOSE] + - src[PRERELEASELOOSE] + '?' + - src[BUILD] + '?' - -var LOOSE = R++ -src[LOOSE] = '^' + LOOSEPLAIN + '$' - -var GTLT = R++ -src[GTLT] = '((?:<|>)?=?)' - -// Something like "2.*" or "1.2.x". -// Note that "x.x" is a valid xRange identifer, meaning "any version" -// Only the first item is strictly required. -var XRANGEIDENTIFIERLOOSE = R++ -src[XRANGEIDENTIFIERLOOSE] = src[NUMERICIDENTIFIERLOOSE] + '|x|X|\\*' -var XRANGEIDENTIFIER = R++ -src[XRANGEIDENTIFIER] = src[NUMERICIDENTIFIER] + '|x|X|\\*' - -var XRANGEPLAIN = R++ -src[XRANGEPLAIN] = '[v=\\s]*(' + src[XRANGEIDENTIFIER] + ')' + - '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + - '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + - '(?:' + src[PRERELEASE] + ')?' + - src[BUILD] + '?' + - ')?)?' - -var XRANGEPLAINLOOSE = R++ -src[XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[XRANGEIDENTIFIERLOOSE] + ')' + - '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + - '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + - '(?:' + src[PRERELEASELOOSE] + ')?' + - src[BUILD] + '?' + - ')?)?' - -var XRANGE = R++ -src[XRANGE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAIN] + '$' -var XRANGELOOSE = R++ -src[XRANGELOOSE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAINLOOSE] + '$' - -// Coercion. -// Extract anything that could conceivably be a part of a valid semver -var COERCE = R++ -src[COERCE] = '(?:^|[^\\d])' + - '(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' + - '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + - '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + - '(?:$|[^\\d])' - -// Tilde ranges. -// Meaning is "reasonably at or greater than" -var LONETILDE = R++ -src[LONETILDE] = '(?:~>?)' - -var TILDETRIM = R++ -src[TILDETRIM] = '(\\s*)' + src[LONETILDE] + '\\s+' -re[TILDETRIM] = new RegExp(src[TILDETRIM], 'g') -var tildeTrimReplace = '$1~' - -var TILDE = R++ -src[TILDE] = '^' + src[LONETILDE] + src[XRANGEPLAIN] + '$' -var TILDELOOSE = R++ -src[TILDELOOSE] = '^' + src[LONETILDE] + src[XRANGEPLAINLOOSE] + '$' - -// Caret ranges. -// Meaning is "at least and backwards compatible with" -var LONECARET = R++ -src[LONECARET] = '(?:\\^)' - -var CARETTRIM = R++ -src[CARETTRIM] = '(\\s*)' + src[LONECARET] + '\\s+' -re[CARETTRIM] = new RegExp(src[CARETTRIM], 'g') -var caretTrimReplace = '$1^' - -var CARET = R++ -src[CARET] = '^' + src[LONECARET] + src[XRANGEPLAIN] + '$' -var CARETLOOSE = R++ -src[CARETLOOSE] = '^' + src[LONECARET] + src[XRANGEPLAINLOOSE] + '$' - -// A simple gt/lt/eq thing, or just "" to indicate "any version" -var COMPARATORLOOSE = R++ -src[COMPARATORLOOSE] = '^' + src[GTLT] + '\\s*(' + LOOSEPLAIN + ')$|^$' -var COMPARATOR = R++ -src[COMPARATOR] = '^' + src[GTLT] + '\\s*(' + FULLPLAIN + ')$|^$' - -// An expression to strip any whitespace between the gtlt and the thing -// it modifies, so that `> 1.2.3` ==> `>1.2.3` -var COMPARATORTRIM = R++ -src[COMPARATORTRIM] = '(\\s*)' + src[GTLT] + - '\\s*(' + LOOSEPLAIN + '|' + src[XRANGEPLAIN] + ')' - -// this one has to use the /g flag -re[COMPARATORTRIM] = new RegExp(src[COMPARATORTRIM], 'g') -var comparatorTrimReplace = '$1$2$3' - -// Something like `1.2.3 - 1.2.4` -// Note that these all use the loose form, because they'll be -// checked against either the strict or loose comparator form -// later. -var HYPHENRANGE = R++ -src[HYPHENRANGE] = '^\\s*(' + src[XRANGEPLAIN] + ')' + - '\\s+-\\s+' + - '(' + src[XRANGEPLAIN] + ')' + - '\\s*$' - -var HYPHENRANGELOOSE = R++ -src[HYPHENRANGELOOSE] = '^\\s*(' + src[XRANGEPLAINLOOSE] + ')' + - '\\s+-\\s+' + - '(' + src[XRANGEPLAINLOOSE] + ')' + - '\\s*$' - -// Star ranges basically just allow anything at all. -var STAR = R++ -src[STAR] = '(<|>)?=?\\s*\\*' - -// Compile to actual regexp objects. -// All are flag-free, unless they were created above with a flag. -for (var i = 0; i < R; i++) { - debug(i, src[i]) - if (!re[i]) { - re[i] = new RegExp(src[i]) - } -} - -exports.parse = parse -function parse (version, options) { - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - } - } - - if (version instanceof SemVer) { - return version - } - - if (typeof version !== 'string') { - return null - } - - if (version.length > MAX_LENGTH) { - return null - } - - var r = options.loose ? re[LOOSE] : re[FULL] - if (!r.test(version)) { - return null - } - - try { - return new SemVer(version, options) - } catch (er) { - return null - } -} - -exports.valid = valid -function valid (version, options) { - var v = parse(version, options) - return v ? v.version : null -} - -exports.clean = clean -function clean (version, options) { - var s = parse(version.trim().replace(/^[=v]+/, ''), options) - return s ? s.version : null -} - -exports.SemVer = SemVer - -function SemVer (version, options) { - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - } - } - if (version instanceof SemVer) { - if (version.loose === options.loose) { - return version - } else { - version = version.version - } - } else if (typeof version !== 'string') { - throw new TypeError('Invalid Version: ' + version) - } - - if (version.length > MAX_LENGTH) { - throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters') - } - - if (!(this instanceof SemVer)) { - return new SemVer(version, options) - } - - debug('SemVer', version, options) - this.options = options - this.loose = !!options.loose - - var m = version.trim().match(options.loose ? re[LOOSE] : re[FULL]) - - if (!m) { - throw new TypeError('Invalid Version: ' + version) - } - - this.raw = version - - // these are actually numbers - this.major = +m[1] - this.minor = +m[2] - this.patch = +m[3] - - if (this.major > MAX_SAFE_INTEGER || this.major < 0) { - throw new TypeError('Invalid major version') - } - - if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { - throw new TypeError('Invalid minor version') - } - - if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { - throw new TypeError('Invalid patch version') - } - - // numberify any prerelease numeric ids - if (!m[4]) { - this.prerelease = [] - } else { - this.prerelease = m[4].split('.').map(function (id) { - if (/^[0-9]+$/.test(id)) { - var num = +id - if (num >= 0 && num < MAX_SAFE_INTEGER) { - return num - } - } - return id - }) - } - - this.build = m[5] ? m[5].split('.') : [] - this.format() -} - -SemVer.prototype.format = function () { - this.version = this.major + '.' + this.minor + '.' + this.patch - if (this.prerelease.length) { - this.version += '-' + this.prerelease.join('.') - } - return this.version -} - -SemVer.prototype.toString = function () { - return this.version -} - -SemVer.prototype.compare = function (other) { - debug('SemVer.compare', this.version, this.options, other) - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options) - } - - return this.compareMain(other) || this.comparePre(other) -} - -SemVer.prototype.compareMain = function (other) { - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options) - } - - return compareIdentifiers(this.major, other.major) || - compareIdentifiers(this.minor, other.minor) || - compareIdentifiers(this.patch, other.patch) -} - -SemVer.prototype.comparePre = function (other) { - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options) - } - - // NOT having a prerelease is > having one - if (this.prerelease.length && !other.prerelease.length) { - return -1 - } else if (!this.prerelease.length && other.prerelease.length) { - return 1 - } else if (!this.prerelease.length && !other.prerelease.length) { - return 0 - } - - var i = 0 - do { - var a = this.prerelease[i] - var b = other.prerelease[i] - debug('prerelease compare', i, a, b) - if (a === undefined && b === undefined) { - return 0 - } else if (b === undefined) { - return 1 - } else if (a === undefined) { - return -1 - } else if (a === b) { - continue - } else { - return compareIdentifiers(a, b) - } - } while (++i) -} - -// preminor will bump the version up to the next minor release, and immediately -// down to pre-release. premajor and prepatch work the same way. -SemVer.prototype.inc = function (release, identifier) { - switch (release) { - case 'premajor': - this.prerelease.length = 0 - this.patch = 0 - this.minor = 0 - this.major++ - this.inc('pre', identifier) - break - case 'preminor': - this.prerelease.length = 0 - this.patch = 0 - this.minor++ - this.inc('pre', identifier) - break - case 'prepatch': - // If this is already a prerelease, it will bump to the next version - // drop any prereleases that might already exist, since they are not - // relevant at this point. - this.prerelease.length = 0 - this.inc('patch', identifier) - this.inc('pre', identifier) - break - // If the input is a non-prerelease version, this acts the same as - // prepatch. - case 'prerelease': - if (this.prerelease.length === 0) { - this.inc('patch', identifier) - } - this.inc('pre', identifier) - break - - case 'major': - // If this is a pre-major version, bump up to the same major version. - // Otherwise increment major. - // 1.0.0-5 bumps to 1.0.0 - // 1.1.0 bumps to 2.0.0 - if (this.minor !== 0 || - this.patch !== 0 || - this.prerelease.length === 0) { - this.major++ - } - this.minor = 0 - this.patch = 0 - this.prerelease = [] - break - case 'minor': - // If this is a pre-minor version, bump up to the same minor version. - // Otherwise increment minor. - // 1.2.0-5 bumps to 1.2.0 - // 1.2.1 bumps to 1.3.0 - if (this.patch !== 0 || this.prerelease.length === 0) { - this.minor++ - } - this.patch = 0 - this.prerelease = [] - break - case 'patch': - // If this is not a pre-release version, it will increment the patch. - // If it is a pre-release it will bump up to the same patch version. - // 1.2.0-5 patches to 1.2.0 - // 1.2.0 patches to 1.2.1 - if (this.prerelease.length === 0) { - this.patch++ - } - this.prerelease = [] - break - // This probably shouldn't be used publicly. - // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction. - case 'pre': - if (this.prerelease.length === 0) { - this.prerelease = [0] - } else { - var i = this.prerelease.length - while (--i >= 0) { - if (typeof this.prerelease[i] === 'number') { - this.prerelease[i]++ - i = -2 - } - } - if (i === -1) { - // didn't increment anything - this.prerelease.push(0) - } - } - if (identifier) { - // 1.2.0-beta.1 bumps to 1.2.0-beta.2, - // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 - if (this.prerelease[0] === identifier) { - if (isNaN(this.prerelease[1])) { - this.prerelease = [identifier, 0] - } - } else { - this.prerelease = [identifier, 0] - } - } - break - - default: - throw new Error('invalid increment argument: ' + release) - } - this.format() - this.raw = this.version - return this -} - -exports.inc = inc -function inc (version, release, loose, identifier) { - if (typeof (loose) === 'string') { - identifier = loose - loose = undefined - } - - try { - return new SemVer(version, loose).inc(release, identifier).version - } catch (er) { - return null - } -} - -exports.diff = diff -function diff (version1, version2) { - if (eq(version1, version2)) { - return null - } else { - var v1 = parse(version1) - var v2 = parse(version2) - var prefix = '' - if (v1.prerelease.length || v2.prerelease.length) { - prefix = 'pre' - var defaultResult = 'prerelease' - } - for (var key in v1) { - if (key === 'major' || key === 'minor' || key === 'patch') { - if (v1[key] !== v2[key]) { - return prefix + key - } - } - } - return defaultResult // may be undefined - } -} - -exports.compareIdentifiers = compareIdentifiers - -var numeric = /^[0-9]+$/ -function compareIdentifiers (a, b) { - var anum = numeric.test(a) - var bnum = numeric.test(b) - - if (anum && bnum) { - a = +a - b = +b - } - - return a === b ? 0 - : (anum && !bnum) ? -1 - : (bnum && !anum) ? 1 - : a < b ? -1 - : 1 -} - -exports.rcompareIdentifiers = rcompareIdentifiers -function rcompareIdentifiers (a, b) { - return compareIdentifiers(b, a) -} - -exports.major = major -function major (a, loose) { - return new SemVer(a, loose).major -} - -exports.minor = minor -function minor (a, loose) { - return new SemVer(a, loose).minor -} - -exports.patch = patch -function patch (a, loose) { - return new SemVer(a, loose).patch -} - -exports.compare = compare -function compare (a, b, loose) { - return new SemVer(a, loose).compare(new SemVer(b, loose)) -} - -exports.compareLoose = compareLoose -function compareLoose (a, b) { - return compare(a, b, true) -} - -exports.rcompare = rcompare -function rcompare (a, b, loose) { - return compare(b, a, loose) -} - -exports.sort = sort -function sort (list, loose) { - return list.sort(function (a, b) { - return exports.compare(a, b, loose) - }) -} - -exports.rsort = rsort -function rsort (list, loose) { - return list.sort(function (a, b) { - return exports.rcompare(a, b, loose) - }) -} - -exports.gt = gt -function gt (a, b, loose) { - return compare(a, b, loose) > 0 -} - -exports.lt = lt -function lt (a, b, loose) { - return compare(a, b, loose) < 0 -} - -exports.eq = eq -function eq (a, b, loose) { - return compare(a, b, loose) === 0 -} - -exports.neq = neq -function neq (a, b, loose) { - return compare(a, b, loose) !== 0 -} - -exports.gte = gte -function gte (a, b, loose) { - return compare(a, b, loose) >= 0 -} - -exports.lte = lte -function lte (a, b, loose) { - return compare(a, b, loose) <= 0 -} - -exports.cmp = cmp -function cmp (a, op, b, loose) { - switch (op) { - case '===': - if (typeof a === 'object') - a = a.version - if (typeof b === 'object') - b = b.version - return a === b - - case '!==': - if (typeof a === 'object') - a = a.version - if (typeof b === 'object') - b = b.version - return a !== b - - case '': - case '=': - case '==': - return eq(a, b, loose) - - case '!=': - return neq(a, b, loose) - - case '>': - return gt(a, b, loose) - - case '>=': - return gte(a, b, loose) - - case '<': - return lt(a, b, loose) - - case '<=': - return lte(a, b, loose) - - default: - throw new TypeError('Invalid operator: ' + op) - } -} - -exports.Comparator = Comparator -function Comparator (comp, options) { - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - } - } - - if (comp instanceof Comparator) { - if (comp.loose === !!options.loose) { - return comp - } else { - comp = comp.value - } - } - - if (!(this instanceof Comparator)) { - return new Comparator(comp, options) - } - - debug('comparator', comp, options) - this.options = options - this.loose = !!options.loose - this.parse(comp) - - if (this.semver === ANY) { - this.value = '' - } else { - this.value = this.operator + this.semver.version - } - - debug('comp', this) -} - -var ANY = {} -Comparator.prototype.parse = function (comp) { - var r = this.options.loose ? re[COMPARATORLOOSE] : re[COMPARATOR] - var m = comp.match(r) - - if (!m) { - throw new TypeError('Invalid comparator: ' + comp) - } - - this.operator = m[1] - if (this.operator === '=') { - this.operator = '' - } - - // if it literally is just '>' or '' then allow anything. - if (!m[2]) { - this.semver = ANY - } else { - this.semver = new SemVer(m[2], this.options.loose) - } -} - -Comparator.prototype.toString = function () { - return this.value -} - -Comparator.prototype.test = function (version) { - debug('Comparator.test', version, this.options.loose) - - if (this.semver === ANY) { - return true - } - - if (typeof version === 'string') { - version = new SemVer(version, this.options) - } - - return cmp(version, this.operator, this.semver, this.options) -} - -Comparator.prototype.intersects = function (comp, options) { - if (!(comp instanceof Comparator)) { - throw new TypeError('a Comparator is required') - } - - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - } - } - - var rangeTmp - - if (this.operator === '') { - rangeTmp = new Range(comp.value, options) - return satisfies(this.value, rangeTmp, options) - } else if (comp.operator === '') { - rangeTmp = new Range(this.value, options) - return satisfies(comp.semver, rangeTmp, options) - } - - var sameDirectionIncreasing = - (this.operator === '>=' || this.operator === '>') && - (comp.operator === '>=' || comp.operator === '>') - var sameDirectionDecreasing = - (this.operator === '<=' || this.operator === '<') && - (comp.operator === '<=' || comp.operator === '<') - var sameSemVer = this.semver.version === comp.semver.version - var differentDirectionsInclusive = - (this.operator === '>=' || this.operator === '<=') && - (comp.operator === '>=' || comp.operator === '<=') - var oppositeDirectionsLessThan = - cmp(this.semver, '<', comp.semver, options) && - ((this.operator === '>=' || this.operator === '>') && - (comp.operator === '<=' || comp.operator === '<')) - var oppositeDirectionsGreaterThan = - cmp(this.semver, '>', comp.semver, options) && - ((this.operator === '<=' || this.operator === '<') && - (comp.operator === '>=' || comp.operator === '>')) - - return sameDirectionIncreasing || sameDirectionDecreasing || - (sameSemVer && differentDirectionsInclusive) || - oppositeDirectionsLessThan || oppositeDirectionsGreaterThan -} - -exports.Range = Range -function Range (range, options) { - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - } - } - - if (range instanceof Range) { - if (range.loose === !!options.loose && - range.includePrerelease === !!options.includePrerelease) { - return range - } else { - return new Range(range.raw, options) - } - } - - if (range instanceof Comparator) { - return new Range(range.value, options) - } - - if (!(this instanceof Range)) { - return new Range(range, options) - } - - this.options = options - this.loose = !!options.loose - this.includePrerelease = !!options.includePrerelease - - // First, split based on boolean or || - this.raw = range - this.set = range.split(/\s*\|\|\s*/).map(function (range) { - return this.parseRange(range.trim()) - }, this).filter(function (c) { - // throw out any that are not relevant for whatever reason - return c.length - }) - - if (!this.set.length) { - throw new TypeError('Invalid SemVer Range: ' + range) - } - - this.format() -} - -Range.prototype.format = function () { - this.range = this.set.map(function (comps) { - return comps.join(' ').trim() - }).join('||').trim() - return this.range -} - -Range.prototype.toString = function () { - return this.range -} - -Range.prototype.parseRange = function (range) { - var loose = this.options.loose - range = range.trim() - // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` - var hr = loose ? re[HYPHENRANGELOOSE] : re[HYPHENRANGE] - range = range.replace(hr, hyphenReplace) - debug('hyphen replace', range) - // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` - range = range.replace(re[COMPARATORTRIM], comparatorTrimReplace) - debug('comparator trim', range, re[COMPARATORTRIM]) - - // `~ 1.2.3` => `~1.2.3` - range = range.replace(re[TILDETRIM], tildeTrimReplace) - - // `^ 1.2.3` => `^1.2.3` - range = range.replace(re[CARETTRIM], caretTrimReplace) - - // normalize spaces - range = range.split(/\s+/).join(' ') - - // At this point, the range is completely trimmed and - // ready to be split into comparators. - - var compRe = loose ? re[COMPARATORLOOSE] : re[COMPARATOR] - var set = range.split(' ').map(function (comp) { - return parseComparator(comp, this.options) - }, this).join(' ').split(/\s+/) - if (this.options.loose) { - // in loose mode, throw out any that are not valid comparators - set = set.filter(function (comp) { - return !!comp.match(compRe) - }) - } - set = set.map(function (comp) { - return new Comparator(comp, this.options) - }, this) - - return set -} - -Range.prototype.intersects = function (range, options) { - if (!(range instanceof Range)) { - throw new TypeError('a Range is required') - } - - return this.set.some(function (thisComparators) { - return thisComparators.every(function (thisComparator) { - return range.set.some(function (rangeComparators) { - return rangeComparators.every(function (rangeComparator) { - return thisComparator.intersects(rangeComparator, options) - }) - }) - }) - }) -} - -// Mostly just for testing and legacy API reasons -exports.toComparators = toComparators -function toComparators (range, options) { - return new Range(range, options).set.map(function (comp) { - return comp.map(function (c) { - return c.value - }).join(' ').trim().split(' ') - }) -} - -// comprised of xranges, tildes, stars, and gtlt's at this point. -// already replaced the hyphen ranges -// turn into a set of JUST comparators. -function parseComparator (comp, options) { - debug('comp', comp, options) - comp = replaceCarets(comp, options) - debug('caret', comp) - comp = replaceTildes(comp, options) - debug('tildes', comp) - comp = replaceXRanges(comp, options) - debug('xrange', comp) - comp = replaceStars(comp, options) - debug('stars', comp) - return comp -} - -function isX (id) { - return !id || id.toLowerCase() === 'x' || id === '*' -} - -// ~, ~> --> * (any, kinda silly) -// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0 -// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0 -// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0 -// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0 -// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0 -function replaceTildes (comp, options) { - return comp.trim().split(/\s+/).map(function (comp) { - return replaceTilde(comp, options) - }).join(' ') -} - -function replaceTilde (comp, options) { - var r = options.loose ? re[TILDELOOSE] : re[TILDE] - return comp.replace(r, function (_, M, m, p, pr) { - debug('tilde', comp, _, M, m, p, pr) - var ret - - if (isX(M)) { - ret = '' - } else if (isX(m)) { - ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' - } else if (isX(p)) { - // ~1.2 == >=1.2.0 <1.3.0 - ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' - } else if (pr) { - debug('replaceTilde pr', pr) - ret = '>=' + M + '.' + m + '.' + p + '-' + pr + - ' <' + M + '.' + (+m + 1) + '.0' - } else { - // ~1.2.3 == >=1.2.3 <1.3.0 - ret = '>=' + M + '.' + m + '.' + p + - ' <' + M + '.' + (+m + 1) + '.0' - } - - debug('tilde return', ret) - return ret - }) -} - -// ^ --> * (any, kinda silly) -// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0 -// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0 -// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0 -// ^1.2.3 --> >=1.2.3 <2.0.0 -// ^1.2.0 --> >=1.2.0 <2.0.0 -function replaceCarets (comp, options) { - return comp.trim().split(/\s+/).map(function (comp) { - return replaceCaret(comp, options) - }).join(' ') -} - -function replaceCaret (comp, options) { - debug('caret', comp, options) - var r = options.loose ? re[CARETLOOSE] : re[CARET] - return comp.replace(r, function (_, M, m, p, pr) { - debug('caret', comp, _, M, m, p, pr) - var ret - - if (isX(M)) { - ret = '' - } else if (isX(m)) { - ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' - } else if (isX(p)) { - if (M === '0') { - ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' - } else { - ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0' - } - } else if (pr) { - debug('replaceCaret pr', pr) - if (M === '0') { - if (m === '0') { - ret = '>=' + M + '.' + m + '.' + p + '-' + pr + - ' <' + M + '.' + m + '.' + (+p + 1) - } else { - ret = '>=' + M + '.' + m + '.' + p + '-' + pr + - ' <' + M + '.' + (+m + 1) + '.0' - } - } else { - ret = '>=' + M + '.' + m + '.' + p + '-' + pr + - ' <' + (+M + 1) + '.0.0' - } - } else { - debug('no pr') - if (M === '0') { - if (m === '0') { - ret = '>=' + M + '.' + m + '.' + p + - ' <' + M + '.' + m + '.' + (+p + 1) - } else { - ret = '>=' + M + '.' + m + '.' + p + - ' <' + M + '.' + (+m + 1) + '.0' - } - } else { - ret = '>=' + M + '.' + m + '.' + p + - ' <' + (+M + 1) + '.0.0' - } - } - - debug('caret return', ret) - return ret - }) -} - -function replaceXRanges (comp, options) { - debug('replaceXRanges', comp, options) - return comp.split(/\s+/).map(function (comp) { - return replaceXRange(comp, options) - }).join(' ') -} - -function replaceXRange (comp, options) { - comp = comp.trim() - var r = options.loose ? re[XRANGELOOSE] : re[XRANGE] - return comp.replace(r, function (ret, gtlt, M, m, p, pr) { - debug('xRange', comp, ret, gtlt, M, m, p, pr) - var xM = isX(M) - var xm = xM || isX(m) - var xp = xm || isX(p) - var anyX = xp - - if (gtlt === '=' && anyX) { - gtlt = '' - } - - if (xM) { - if (gtlt === '>' || gtlt === '<') { - // nothing is allowed - ret = '<0.0.0' - } else { - // nothing is forbidden - ret = '*' - } - } else if (gtlt && anyX) { - // we know patch is an x, because we have any x at all. - // replace X with 0 - if (xm) { - m = 0 - } - p = 0 - - if (gtlt === '>') { - // >1 => >=2.0.0 - // >1.2 => >=1.3.0 - // >1.2.3 => >= 1.2.4 - gtlt = '>=' - if (xm) { - M = +M + 1 - m = 0 - p = 0 - } else { - m = +m + 1 - p = 0 - } - } else if (gtlt === '<=') { - // <=0.7.x is actually <0.8.0, since any 0.7.x should - // pass. Similarly, <=7.x is actually <8.0.0, etc. - gtlt = '<' - if (xm) { - M = +M + 1 - } else { - m = +m + 1 - } - } - - ret = gtlt + M + '.' + m + '.' + p - } else if (xm) { - ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' - } else if (xp) { - ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' - } - - debug('xRange return', ret) - - return ret - }) -} - -// Because * is AND-ed with everything else in the comparator, -// and '' means "any version", just remove the *s entirely. -function replaceStars (comp, options) { - debug('replaceStars', comp, options) - // Looseness is ignored here. star is always as loose as it gets! - return comp.trim().replace(re[STAR], '') -} - -// This function is passed to string.replace(re[HYPHENRANGE]) -// M, m, patch, prerelease, build -// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 -// 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do -// 1.2 - 3.4 => >=1.2.0 <3.5.0 -function hyphenReplace ($0, - from, fM, fm, fp, fpr, fb, - to, tM, tm, tp, tpr, tb) { - if (isX(fM)) { - from = '' - } else if (isX(fm)) { - from = '>=' + fM + '.0.0' - } else if (isX(fp)) { - from = '>=' + fM + '.' + fm + '.0' - } else { - from = '>=' + from - } - - if (isX(tM)) { - to = '' - } else if (isX(tm)) { - to = '<' + (+tM + 1) + '.0.0' - } else if (isX(tp)) { - to = '<' + tM + '.' + (+tm + 1) + '.0' - } else if (tpr) { - to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr - } else { - to = '<=' + to - } - - return (from + ' ' + to).trim() -} - -// if ANY of the sets match ALL of its comparators, then pass -Range.prototype.test = function (version) { - if (!version) { - return false - } - - if (typeof version === 'string') { - version = new SemVer(version, this.options) - } - - for (var i = 0; i < this.set.length; i++) { - if (testSet(this.set[i], version, this.options)) { - return true - } - } - return false -} - -function testSet (set, version, options) { - for (var i = 0; i < set.length; i++) { - if (!set[i].test(version)) { - return false - } - } - - if (version.prerelease.length && !options.includePrerelease) { - // Find the set of versions that are allowed to have prereleases - // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 - // That should allow `1.2.3-pr.2` to pass. - // However, `1.2.4-alpha.notready` should NOT be allowed, - // even though it's within the range set by the comparators. - for (i = 0; i < set.length; i++) { - debug(set[i].semver) - if (set[i].semver === ANY) { - continue - } - - if (set[i].semver.prerelease.length > 0) { - var allowed = set[i].semver - if (allowed.major === version.major && - allowed.minor === version.minor && - allowed.patch === version.patch) { - return true - } - } - } - - // Version has a -pre, but it's not one of the ones we like. - return false - } - - return true -} - -exports.satisfies = satisfies -function satisfies (version, range, options) { - try { - range = new Range(range, options) - } catch (er) { - return false - } - return range.test(version) -} - -exports.maxSatisfying = maxSatisfying -function maxSatisfying (versions, range, options) { - var max = null - var maxSV = null - try { - var rangeObj = new Range(range, options) - } catch (er) { - return null - } - versions.forEach(function (v) { - if (rangeObj.test(v)) { - // satisfies(v, range, options) - if (!max || maxSV.compare(v) === -1) { - // compare(max, v, true) - max = v - maxSV = new SemVer(max, options) - } - } - }) - return max -} - -exports.minSatisfying = minSatisfying -function minSatisfying (versions, range, options) { - var min = null - var minSV = null - try { - var rangeObj = new Range(range, options) - } catch (er) { - return null - } - versions.forEach(function (v) { - if (rangeObj.test(v)) { - // satisfies(v, range, options) - if (!min || minSV.compare(v) === 1) { - // compare(min, v, true) - min = v - minSV = new SemVer(min, options) - } - } - }) - return min -} - -exports.minVersion = minVersion -function minVersion (range, loose) { - range = new Range(range, loose) - - var minver = new SemVer('0.0.0') - if (range.test(minver)) { - return minver - } - - minver = new SemVer('0.0.0-0') - if (range.test(minver)) { - return minver - } - - minver = null - for (var i = 0; i < range.set.length; ++i) { - var comparators = range.set[i] - - comparators.forEach(function (comparator) { - // Clone to avoid manipulating the comparator's semver object. - var compver = new SemVer(comparator.semver.version) - switch (comparator.operator) { - case '>': - if (compver.prerelease.length === 0) { - compver.patch++ - } else { - compver.prerelease.push(0) - } - compver.raw = compver.format() - /* fallthrough */ - case '': - case '>=': - if (!minver || gt(minver, compver)) { - minver = compver - } - break - case '<': - case '<=': - /* Ignore maximum versions */ - break - /* istanbul ignore next */ - default: - throw new Error('Unexpected operation: ' + comparator.operator) - } - }) - } - - if (minver && range.test(minver)) { - return minver - } - - return null -} - -exports.validRange = validRange -function validRange (range, options) { - try { - // Return '*' instead of '' so that truthiness works. - // This will throw if it's invalid anyway - return new Range(range, options).range || '*' - } catch (er) { - return null - } -} - -// Determine if version is less than all the versions possible in the range -exports.ltr = ltr -function ltr (version, range, options) { - return outside(version, range, '<', options) -} - -// Determine if version is greater than all the versions possible in the range. -exports.gtr = gtr -function gtr (version, range, options) { - return outside(version, range, '>', options) -} - -exports.outside = outside -function outside (version, range, hilo, options) { - version = new SemVer(version, options) - range = new Range(range, options) - - var gtfn, ltefn, ltfn, comp, ecomp - switch (hilo) { - case '>': - gtfn = gt - ltefn = lte - ltfn = lt - comp = '>' - ecomp = '>=' - break - case '<': - gtfn = lt - ltefn = gte - ltfn = gt - comp = '<' - ecomp = '<=' - break - default: - throw new TypeError('Must provide a hilo val of "<" or ">"') - } - - // If it satisifes the range it is not outside - if (satisfies(version, range, options)) { - return false - } - - // From now on, variable terms are as if we're in "gtr" mode. - // but note that everything is flipped for the "ltr" function. - - for (var i = 0; i < range.set.length; ++i) { - var comparators = range.set[i] - - var high = null - var low = null - - comparators.forEach(function (comparator) { - if (comparator.semver === ANY) { - comparator = new Comparator('>=0.0.0') - } - high = high || comparator - low = low || comparator - if (gtfn(comparator.semver, high.semver, options)) { - high = comparator - } else if (ltfn(comparator.semver, low.semver, options)) { - low = comparator - } - }) - - // If the edge version comparator has a operator then our version - // isn't outside it - if (high.operator === comp || high.operator === ecomp) { - return false - } - - // If the lowest version comparator has an operator and our version - // is less than it then it isn't higher than the range - if ((!low.operator || low.operator === comp) && - ltefn(version, low.semver)) { - return false - } else if (low.operator === ecomp && ltfn(version, low.semver)) { - return false - } - } - return true -} - -exports.prerelease = prerelease -function prerelease (version, options) { - var parsed = parse(version, options) - return (parsed && parsed.prerelease.length) ? parsed.prerelease : null -} - -exports.intersects = intersects -function intersects (r1, r2, options) { - r1 = new Range(r1, options) - r2 = new Range(r2, options) - return r1.intersects(r2) -} - -exports.coerce = coerce -function coerce (version) { - if (version instanceof SemVer) { - return version - } - - if (typeof version !== 'string') { - return null - } - - var match = version.match(re[COERCE]) - - if (match == null) { - return null - } - - return parse(match[1] + - '.' + (match[2] || '0') + - '.' + (match[3] || '0')) -} diff --git a/scripts/node_modules/sparse-bitfield/.npmignore b/scripts/node_modules/sparse-bitfield/.npmignore deleted file mode 100644 index 3c3629e6..00000000 --- a/scripts/node_modules/sparse-bitfield/.npmignore +++ /dev/null @@ -1 +0,0 @@ -node_modules diff --git a/scripts/node_modules/sparse-bitfield/.travis.yml b/scripts/node_modules/sparse-bitfield/.travis.yml deleted file mode 100644 index c0428217..00000000 --- a/scripts/node_modules/sparse-bitfield/.travis.yml +++ /dev/null @@ -1,6 +0,0 @@ -language: node_js -node_js: - - '0.10' - - '0.12' - - '4.0' - - '5.0' diff --git a/scripts/node_modules/sparse-bitfield/LICENSE b/scripts/node_modules/sparse-bitfield/LICENSE deleted file mode 100644 index bae9da7b..00000000 --- a/scripts/node_modules/sparse-bitfield/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2016 Mathias Buus - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/scripts/node_modules/sparse-bitfield/README.md b/scripts/node_modules/sparse-bitfield/README.md deleted file mode 100644 index 7b6b8f9e..00000000 --- a/scripts/node_modules/sparse-bitfield/README.md +++ /dev/null @@ -1,62 +0,0 @@ -# sparse-bitfield - -Bitfield implementation that allocates a series of 1kb buffers to support sparse bitfields -without allocating a massive buffer. If you want to simple implementation of a flat bitfield -see the [bitfield](https://github.com/fb55/bitfield) module. - -This module is mostly useful if you need a big bitfield where you won't nessecarily set every bit. - -``` -npm install sparse-bitfield -``` - -[![build status](http://img.shields.io/travis/mafintosh/sparse-bitfield.svg?style=flat)](http://travis-ci.org/mafintosh/sparse-bitfield) - -## Usage - -``` js -var bitfield = require('sparse-bitfield') -var bits = bitfield() - -bits.set(0, true) // set first bit -bits.set(1, true) // set second bit -bits.set(1000000000000, true) // set the 1.000.000.000.000th bit -``` - -Running the above example will allocate two 1kb buffers internally. -Each 1kb buffer can hold information about 8192 bits so the first one will be used to store information about the first two bits and the second will be used to store the 1.000.000.000.000th bit. - -## API - -#### `var bits = bitfield([options])` - -Create a new bitfield. Options include - -``` js -{ - pageSize: 1024, // how big should the partial buffers be - buffer: anExistingBitfield, - trackUpdates: false // track when pages are being updated in the pager -} -``` - -#### `bits.set(index, value)` - -Set a bit to true or false. - -#### `bits.get(index)` - -Get the value of a bit. - -#### `bits.pages` - -A [memory-pager](https://github.com/mafintosh/memory-pager) instance that is managing the underlying memory. -If you set `trackUpdates` to true in the constructor you can use `.lastUpdate()` on this instance to get the last updated memory page. - -#### `var buffer = bits.toBuffer()` - -Get a single buffer representing the entire bitfield. - -## License - -MIT diff --git a/scripts/node_modules/sparse-bitfield/index.js b/scripts/node_modules/sparse-bitfield/index.js deleted file mode 100644 index ff458c97..00000000 --- a/scripts/node_modules/sparse-bitfield/index.js +++ /dev/null @@ -1,95 +0,0 @@ -var pager = require('memory-pager') - -module.exports = Bitfield - -function Bitfield (opts) { - if (!(this instanceof Bitfield)) return new Bitfield(opts) - if (!opts) opts = {} - if (Buffer.isBuffer(opts)) opts = {buffer: opts} - - this.pageOffset = opts.pageOffset || 0 - this.pageSize = opts.pageSize || 1024 - this.pages = opts.pages || pager(this.pageSize) - - this.byteLength = this.pages.length * this.pageSize - this.length = 8 * this.byteLength - - if (!powerOfTwo(this.pageSize)) throw new Error('The page size should be a power of two') - - this._trackUpdates = !!opts.trackUpdates - this._pageMask = this.pageSize - 1 - - if (opts.buffer) { - for (var i = 0; i < opts.buffer.length; i += this.pageSize) { - this.pages.set(i / this.pageSize, opts.buffer.slice(i, i + this.pageSize)) - } - this.byteLength = opts.buffer.length - this.length = 8 * this.byteLength - } -} - -Bitfield.prototype.get = function (i) { - var o = i & 7 - var j = (i - o) / 8 - - return !!(this.getByte(j) & (128 >> o)) -} - -Bitfield.prototype.getByte = function (i) { - var o = i & this._pageMask - var j = (i - o) / this.pageSize - var page = this.pages.get(j, true) - - return page ? page.buffer[o + this.pageOffset] : 0 -} - -Bitfield.prototype.set = function (i, v) { - var o = i & 7 - var j = (i - o) / 8 - var b = this.getByte(j) - - return this.setByte(j, v ? b | (128 >> o) : b & (255 ^ (128 >> o))) -} - -Bitfield.prototype.toBuffer = function () { - var all = alloc(this.pages.length * this.pageSize) - - for (var i = 0; i < this.pages.length; i++) { - var next = this.pages.get(i, true) - var allOffset = i * this.pageSize - if (next) next.buffer.copy(all, allOffset, this.pageOffset, this.pageOffset + this.pageSize) - } - - return all -} - -Bitfield.prototype.setByte = function (i, b) { - var o = i & this._pageMask - var j = (i - o) / this.pageSize - var page = this.pages.get(j, false) - - o += this.pageOffset - - if (page.buffer[o] === b) return false - page.buffer[o] = b - - if (i >= this.byteLength) { - this.byteLength = i + 1 - this.length = this.byteLength * 8 - } - - if (this._trackUpdates) this.pages.updated(page) - - return true -} - -function alloc (n) { - if (Buffer.alloc) return Buffer.alloc(n) - var b = new Buffer(n) - b.fill(0) - return b -} - -function powerOfTwo (x) { - return !(x & (x - 1)) -} diff --git a/scripts/node_modules/sparse-bitfield/package.json b/scripts/node_modules/sparse-bitfield/package.json deleted file mode 100644 index b1cf7878..00000000 --- a/scripts/node_modules/sparse-bitfield/package.json +++ /dev/null @@ -1,55 +0,0 @@ -{ - "_from": "sparse-bitfield@^3.0.3", - "_id": "sparse-bitfield@3.0.3", - "_inBundle": false, - "_integrity": "sha1-/0rm5oZWBWuks+eSqzM004JzyhE=", - "_location": "/sparse-bitfield", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "sparse-bitfield@^3.0.3", - "name": "sparse-bitfield", - "escapedName": "sparse-bitfield", - "rawSpec": "^3.0.3", - "saveSpec": null, - "fetchSpec": "^3.0.3" - }, - "_requiredBy": [ - "/saslprep" - ], - "_resolved": "https://registry.npmjs.org/sparse-bitfield/-/sparse-bitfield-3.0.3.tgz", - "_shasum": "ff4ae6e68656056ba4b3e792ab3334d38273ca11", - "_spec": "sparse-bitfield@^3.0.3", - "_where": "/Users/rlreamy/git/kpmp/orion-data/scripts/node_modules/saslprep", - "author": { - "name": "Mathias Buus", - "url": "@mafintosh" - }, - "bugs": { - "url": "https://github.com/mafintosh/sparse-bitfield/issues" - }, - "bundleDependencies": false, - "dependencies": { - "memory-pager": "^1.0.2" - }, - "deprecated": false, - "description": "Bitfield that allocates a series of small buffers to support sparse bits without allocating a massive buffer", - "devDependencies": { - "buffer-alloc": "^1.1.0", - "standard": "^9.0.0", - "tape": "^4.6.3" - }, - "homepage": "https://github.com/mafintosh/sparse-bitfield", - "license": "MIT", - "main": "index.js", - "name": "sparse-bitfield", - "repository": { - "type": "git", - "url": "git+https://github.com/mafintosh/sparse-bitfield.git" - }, - "scripts": { - "test": "standard && tape test.js" - }, - "version": "3.0.3" -} diff --git a/scripts/node_modules/sparse-bitfield/test.js b/scripts/node_modules/sparse-bitfield/test.js deleted file mode 100644 index ae42ef46..00000000 --- a/scripts/node_modules/sparse-bitfield/test.js +++ /dev/null @@ -1,79 +0,0 @@ -var alloc = require('buffer-alloc') -var tape = require('tape') -var bitfield = require('./') - -tape('set and get', function (t) { - var bits = bitfield() - - t.same(bits.get(0), false, 'first bit is false') - bits.set(0, true) - t.same(bits.get(0), true, 'first bit is true') - t.same(bits.get(1), false, 'second bit is false') - bits.set(0, false) - t.same(bits.get(0), false, 'first bit is reset') - t.end() -}) - -tape('set large and get', function (t) { - var bits = bitfield() - - t.same(bits.get(9999999999999), false, 'large bit is false') - bits.set(9999999999999, true) - t.same(bits.get(9999999999999), true, 'large bit is true') - t.same(bits.get(9999999999999 + 1), false, 'large bit + 1 is false') - bits.set(9999999999999, false) - t.same(bits.get(9999999999999), false, 'large bit is reset') - t.end() -}) - -tape('get and set buffer', function (t) { - var bits = bitfield({trackUpdates: true}) - - t.same(bits.pages.get(0, true), undefined) - t.same(bits.pages.get(Math.floor(9999999999999 / 8 / 1024), true), undefined) - bits.set(9999999999999, true) - - var bits2 = bitfield() - var upd = bits.pages.lastUpdate() - bits2.pages.set(Math.floor(upd.offset / 1024), upd.buffer) - t.same(bits2.get(9999999999999), true, 'bit is set') - t.end() -}) - -tape('toBuffer', function (t) { - var bits = bitfield() - - t.same(bits.toBuffer(), alloc(0)) - - bits.set(0, true) - - t.same(bits.toBuffer(), bits.pages.get(0).buffer) - - bits.set(9000, true) - - t.same(bits.toBuffer(), Buffer.concat([bits.pages.get(0).buffer, bits.pages.get(1).buffer])) - t.end() -}) - -tape('pass in buffer', function (t) { - var bits = bitfield() - - bits.set(0, true) - bits.set(9000, true) - - var clone = bitfield(bits.toBuffer()) - - t.same(clone.get(0), true) - t.same(clone.get(9000), true) - t.end() -}) - -tape('set small buffer', function (t) { - var buf = alloc(1) - buf[0] = 255 - var bits = bitfield(buf) - - t.same(bits.get(0), true) - t.same(bits.pages.get(0).buffer.length, bits.pageSize) - t.end() -}) From 143a51c178f484e6a0dd414c790d6f9730db1cd6 Mon Sep 17 00:00:00 2001 From: Becky Reamy Date: Tue, 29 Oct 2019 16:10:23 -0400 Subject: [PATCH 26/26] KPMP-1135: Remove the isDownloadable piece --- src/main/java/org/kpmp/packages/PackageService.java | 6 ------ src/main/java/org/kpmp/packages/PackageView.java | 9 --------- src/test/java/org/kpmp/packages/PackageServiceTest.java | 1 - src/test/java/org/kpmp/packages/PackageViewTest.java | 6 ------ 4 files changed, 22 deletions(-) diff --git a/src/main/java/org/kpmp/packages/PackageService.java b/src/main/java/org/kpmp/packages/PackageService.java index ac68cad4..f6a241b6 100755 --- a/src/main/java/org/kpmp/packages/PackageService.java +++ b/src/main/java/org/kpmp/packages/PackageService.java @@ -70,12 +70,6 @@ public List findAllPackages() throws JSONException, IOException { PackageView packageView = new PackageView(packageToCheck); String packageId = packageToCheck.getString("_id"); packageView.setState(stateMap.get(packageId)); - String zipFileName = filePathHelper.getZipFileName(packageId); - if (new File(zipFileName).exists()) { - packageView.setIsDownloadable(true); - } else { - packageView.setIsDownloadable(false); - } packageViews.add(packageView); } return packageViews; diff --git a/src/main/java/org/kpmp/packages/PackageView.java b/src/main/java/org/kpmp/packages/PackageView.java index 31c9344e..626dc7cb 100644 --- a/src/main/java/org/kpmp/packages/PackageView.java +++ b/src/main/java/org/kpmp/packages/PackageView.java @@ -9,7 +9,6 @@ class PackageView { - private boolean isDownloadable; private JsonNode packageInfo; private ObjectMapper mapper; private State state; @@ -19,14 +18,6 @@ public PackageView(JSONObject packageJSON) throws IOException { this.packageInfo = mapper.readTree(packageJSON.toString()); } - public void setIsDownloadable(boolean isDownloadable) { - this.isDownloadable = isDownloadable; - } - - public boolean isDownloadable() { - return isDownloadable; - } - public JsonNode getPackageInfo() { return packageInfo; } diff --git a/src/test/java/org/kpmp/packages/PackageServiceTest.java b/src/test/java/org/kpmp/packages/PackageServiceTest.java index 9481e953..05031c3a 100755 --- a/src/test/java/org/kpmp/packages/PackageServiceTest.java +++ b/src/test/java/org/kpmp/packages/PackageServiceTest.java @@ -92,7 +92,6 @@ public void testFindAllPackages() throws JSONException, IOException { List packages = service.findAllPackages(); - assertEquals(false, packages.get(0).isDownloadable()); assertEquals(newState, packages.get(0).getState()); verify(packageRepository).findAll(); verify(stateHandlerService).getState(); diff --git a/src/test/java/org/kpmp/packages/PackageViewTest.java b/src/test/java/org/kpmp/packages/PackageViewTest.java index de4f7d46..e84db934 100644 --- a/src/test/java/org/kpmp/packages/PackageViewTest.java +++ b/src/test/java/org/kpmp/packages/PackageViewTest.java @@ -26,12 +26,6 @@ public void tearDown() throws Exception { packageView = null; } - @Test - public void testSetIsDownloadable() { - packageView.setIsDownloadable(true); - assertEquals(true, packageView.isDownloadable()); - } - @Test public void testSetPackageJSON() throws IOException { JSONObject packageInfo = new JSONObject();